From 980c3bc32d60eff4fe938dda180ca4997b2df438 Mon Sep 17 00:00:00 2001 From: yaanlaan Date: Thu, 24 Sep 2026 22:28:34 +0800 Subject: [PATCH 001/142] docs(readme): add panel4cliproxyapi to community projects --- README.md | 4 ++++ README_CN.md | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/README.md b/README.md index d5e6ffaca8d..91f66cce08e 100644 --- a/README.md +++ b/README.md @@ -291,6 +291,10 @@ Claude Code status line for CLIProxyAPI: per-account Codex / Grok / Antigravity Cross-platform Electron tray dashboard for CLIProxyAPI. Shows the real OAuth quota windows per account across ChatGPT/Codex, Claude, Gemini/Antigravity, Grok, Kimi and Cursor, estimates usage-queue cost, and tracks OpenAI/Claude service status. Dark terminal-style UI; runs on Windows and Linux. +### [panel4cliproxyapi](https://github.com/yaanlaan/panel4cliproxyapi) + +A modern, responsive web dashboard and management console for CLIProxyAPI built with React and Tailwind CSS. Features multi-provider OAuth login with LAN redirect assistance, visual zero-YAML configuration, real-time traffic analytics charts, client API key management, core version checking & hot-reloading, and a live SSE streaming playground. + > [!NOTE] > If you developed a project based on CLIProxyAPI, please open a PR to add it to this list. diff --git a/README_CN.md b/README_CN.md index 7463cc344c8..947fc03e2e8 100644 --- a/README_CN.md +++ b/README_CN.md @@ -284,6 +284,10 @@ Claude Code 状态栏,按当前 CPA 实例展示 Codex / Grok / Antigravity / 适用于 CLIProxyAPI 的跨平台 Electron 托盘仪表盘。展示 ChatGPT/Codex、Claude、Gemini/Antigravity、Grok、Kimi 和 Cursor 各账户的真实 OAuth 配额窗口,预估用量队列成本,并跟踪 OpenAI/Claude 服务状态。深色终端风格 UI;支持在 Windows 和 Linux 上运行。 +### [panel4cliproxyapi](https://github.com/yaanlaan/panel4cliproxyapi) + +面向 CLIProxyAPI 的现代化 Web 控制台与管理大盘,基于 React 19 与 Tailwind CSS 构建。支持多平台一键 OAuth 网页授权与特色局域网/跨设备换码辅助、图形化免手写 YAML 系统配置、账号池调用量与成功率走势图表、客户端 API Key 统一管理、核心版本检测与热重载,以及原生打字机流式 API 测试台。 + > [!NOTE] > 如果你开发了基于 CLIProxyAPI 的项目,请提交一个 PR(拉取请求)将其添加到此列表中。 From 673b8ee9f631e5fc0f6a7ca35994c4b606805cb0 Mon Sep 17 00:00:00 2001 From: Supra4E8C Date: Fri, 2 Oct 2026 00:09:08 +0800 Subject: [PATCH 002/142] feat: add getPluginLogo utility and corresponding tests for plugin logo resolution --- src/features/plugins/PluginsPage.tsx | 38 ++++++++++++++++++-- src/features/plugins/pluginLogo.ts | 21 +++++++++++ tests/pluginLogo.test.ts | 54 ++++++++++++++++++++++++++++ 3 files changed, 110 insertions(+), 3 deletions(-) create mode 100644 src/features/plugins/pluginLogo.ts create mode 100644 tests/pluginLogo.test.ts diff --git a/src/features/plugins/PluginsPage.tsx b/src/features/plugins/PluginsPage.tsx index 767a30ba4b2..fa07de117b8 100644 --- a/src/features/plugins/PluginsPage.tsx +++ b/src/features/plugins/PluginsPage.tsx @@ -17,13 +17,14 @@ import { IconTrash2, } from '@/components/ui/icons'; import { useHeaderRefresh } from '@/hooks/useHeaderRefresh'; -import { pluginsApi } from '@/services/api'; +import { pluginsApi, pluginStoreApi } from '@/services/api'; import { useAuthStore, useConfigStore, useNotificationStore } from '@/stores'; import { getErrorMessage, isRecord } from '@/utils/helpers'; import type { PluginConfigField, PluginListEntry, PluginListResponse, + PluginStoreEntry, } from '@/types'; import { buildPluginConfigDraft, @@ -37,6 +38,7 @@ import { resolvePluginAssetURL, } from './pluginResources'; import { waitForPluginState } from './pluginPolling'; +import { getPluginLogo } from './pluginLogo'; import styles from './PluginsPage.module.scss'; type PluginRuntimeWaitStatus = 'ready' | 'globalDisabled' | 'timeout'; @@ -64,11 +66,17 @@ export function PluginsPage() { const navigate = useNavigate(); const connectionStatus = useAuthStore((state) => state.connectionStatus); const apiBase = useAuthStore((state) => state.apiBase); + const managementKey = useAuthStore((state) => state.managementKey); const clearConfigCache = useConfigStore((state) => state.clearCache); const showNotification = useNotificationStore((state) => state.showNotification); const showConfirmation = useNotificationStore((state) => state.showConfirmation); const [data, setData] = useState(null); + const [storeLogos, setStoreLogos] = useState<{ + apiBase: string; + managementKey: string; + entries: PluginStoreEntry[]; + } | null>(null); const [filter, setFilter] = useState(''); const [loading, setLoading] = useState(true); const [error, setError] = useState(''); @@ -126,6 +134,30 @@ export function PluginsPage() { void loadPlugins(); }, [loadPlugins]); + useEffect(() => { + setStoreLogos(null); + if (!connected || !data) return; + let cancelled = false; + void pluginStoreApi.list().then( + (response) => { + if (!cancelled) { + setStoreLogos({ apiBase, managementKey, entries: response.plugins }); + } + }, + () => { + // Store metadata is optional; its failure must not block plugin management. + } + ); + return () => { + cancelled = true; + }; + }, [connected, apiBase, managementKey, data]); + + const logoEntries = + connected && storeLogos?.apiBase === apiBase && storeLogos.managementKey === managementKey + ? storeLogos.entries + : []; + const pluginStats = useMemo(() => { const plugins = data?.plugins ?? []; return { @@ -567,7 +599,7 @@ export function PluginsPage() { ) : (
{visiblePlugins.map((plugin) => { - const logo = resolvePluginAsset(plugin.logo || plugin.metadata?.logo || ''); + const logo = resolvePluginAsset(getPluginLogo(plugin, logoEntries)); const github = plugin.metadata?.githubRepository.trim(); const openingConfig = openingConfigID === plugin.id; const deletingPlugin = deletingID === plugin.id; @@ -579,7 +611,7 @@ export function PluginsPage() {
{/* Logo */} {/* Info */} diff --git a/src/features/plugins/pluginLogo.ts b/src/features/plugins/pluginLogo.ts new file mode 100644 index 00000000000..3ec9ac6a994 --- /dev/null +++ b/src/features/plugins/pluginLogo.ts @@ -0,0 +1,21 @@ +import type { PluginListEntry, PluginStoreEntry } from '@/types'; +import { buildRepositoryURL } from './pluginResources'; + +// Do not pick an arbitrary registry when multiple sources advertise the same ID. +export const getPluginLogo = (plugin: PluginListEntry, entries: PluginStoreEntry[]): string => { + const logo = plugin.logo.trim() || plugin.metadata?.logo.trim(); + if (logo) return logo; + + const repository = plugin.metadata?.githubRepository.trim(); + const normalizeRepository = (value: string) => + buildRepositoryURL(value) + .replace(/\/+$/, '') + .replace(/\.git$/i, '') + .toLowerCase(); + const matches = entries.filter( + (entry) => + entry.id === plugin.id && + (!repository || normalizeRepository(entry.repository) === normalizeRepository(repository)) + ); + return matches.length === 1 ? matches[0].logo.trim() : ''; +}; diff --git a/tests/pluginLogo.test.ts b/tests/pluginLogo.test.ts new file mode 100644 index 00000000000..b396319beb9 --- /dev/null +++ b/tests/pluginLogo.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, test } from 'bun:test'; +import { getPluginLogo } from '../src/features/plugins/pluginLogo'; +import type { PluginListEntry, PluginStoreEntry } from '../src/types'; + +const plugin = (overrides: Partial = {}) => + ({ id: 'example', logo: '', metadata: null, ...overrides }) as PluginListEntry; +const entry = (overrides: Partial = {}) => + ({ + id: 'example', + logo: 'https://example.com/store.png', + repository: 'owner/repo', + ...overrides, + }) as PluginStoreEntry; + +describe('management plugin logos', () => { + test('uses the store logo for unregistered plugins or missing runtime logos', () => { + expect(getPluginLogo(plugin({ registered: false }), [entry()])).toBe(entry().logo); + expect(getPluginLogo(plugin({ registered: true }), [entry()])).toBe(entry().logo); + }); + + test('prefers runtime logo, then metadata logo over store metadata', () => { + const metadata = { + name: '', + version: '', + author: '', + githubRepository: '', + logo: 'metadata.png', + configFields: [], + }; + expect(getPluginLogo(plugin({ logo: 'runtime.png', metadata }), [entry()])).toBe('runtime.png'); + expect(getPluginLogo(plugin({ logo: ' ', metadata }), [entry()])).toBe('metadata.png'); + }); + + test('does not use unrelated or ambiguous registry entries', () => { + expect(getPluginLogo(plugin(), [entry({ id: 'other' })])).toBe(''); + expect(getPluginLogo(plugin(), [entry(), entry({ repository: 'other/repo' })])).toBe(''); + expect(getPluginLogo(plugin(), [])).toBe(''); + }); + + test('matches repository metadata when multiple sources declare the same ID', () => { + const metadata = { + name: '', + version: '', + author: '', + githubRepository: 'https://github.com/owner/repo.git', + logo: '', + configFields: [], + }; + expect( + getPluginLogo(plugin({ metadata }), [entry(), entry({ repository: 'other/repo' })]) + ).toBe(entry().logo); + expect(getPluginLogo(plugin({ metadata }), [entry({ repository: 'other/repo' })])).toBe(''); + }); +}); From 8348923a1782ccf2aee40e3076e36d6e92316694 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Fri, 2 Oct 2026 23:32:32 +0800 Subject: [PATCH 003/142] feat(pluginhost): add host routing reset cooldown callback - Add `MethodHostRoutingResetCooldown` RPC callback to plugin ABI and host dispatcher - Introduce `HostRoutingResetCooldownRequest` and `HostRoutingResetCooldownResponse` in plugin API - Reset credential quota and cooldown routing state in memory without persisting to token files Closes: #6274 --- internal/pluginhost/host_callbacks.go | 2 + internal/pluginhost/routing_callbacks.go | 48 ++++ internal/pluginhost/routing_callbacks_test.go | 245 ++++++++++++++++++ sdk/pluginabi/types.go | 2 + sdk/pluginabi/types_test.go | 3 + sdk/pluginapi/types.go | 14 + 6 files changed, 314 insertions(+) create mode 100644 internal/pluginhost/routing_callbacks.go create mode 100644 internal/pluginhost/routing_callbacks_test.go diff --git a/internal/pluginhost/host_callbacks.go b/internal/pluginhost/host_callbacks.go index 88b8c92b7d5..4af872a9f83 100644 --- a/internal/pluginhost/host_callbacks.go +++ b/internal/pluginhost/host_callbacks.go @@ -181,6 +181,8 @@ func (h *Host) callFromPlugin(ctx context.Context, method string, request []byte return h.callHostAuthSave(ctx, request) case pluginabi.MethodHostAffinityLookup: return h.callHostAffinityLookup(ctx, request) + case pluginabi.MethodHostRoutingResetCooldown: + return h.callHostRoutingResetCooldown(ctx, request) default: return nil, fmt.Errorf("unsupported host callback %s", method) } diff --git a/internal/pluginhost/routing_callbacks.go b/internal/pluginhost/routing_callbacks.go new file mode 100644 index 00000000000..da20fd2c219 --- /dev/null +++ b/internal/pluginhost/routing_callbacks.go @@ -0,0 +1,48 @@ +package pluginhost + +import ( + "context" + "encoding/json" + "fmt" + "strings" + + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginapi" + log "github.com/sirupsen/logrus" +) + +// callHostRoutingResetCooldown clears quota and cooldown routing state for one credential, the +// same reset POST /v8/management/routing/cooldown/reset performs, while ensuring token files are left alone. +func (h *Host) callHostRoutingResetCooldown(ctx context.Context, request []byte) ([]byte, error) { + var req pluginapi.HostRoutingResetCooldownRequest + if errUnmarshal := json.Unmarshal(request, &req); errUnmarshal != nil { + return nil, fmt.Errorf("decode host routing reset cooldown request: %w", errUnmarshal) + } + authIndex := strings.TrimSpace(req.AuthIndex) + auth, errGet := h.authByIndex(authIndex) + if errGet != nil { + return nil, errGet + } + manager := h.currentAuthManager() + if manager == nil { + return nil, fmt.Errorf("core auth manager unavailable") + } + resetCtx := coreauth.WithSkipPersist(ctx) + updated, models, errReset := manager.ResetQuota(resetCtx, auth.ID) + if errReset != nil { + return nil, fmt.Errorf("reset cooldown: %w", errReset) + } + if updated == nil { + return nil, fmt.Errorf("auth not found for auth_index %s", authIndex) + } + updated.EnsureIndex() + log.WithFields(log.Fields{ + "plugin_id": hostCallbackPluginIDFromContext(ctx), + "auth_index": updated.Index, + "models": len(models), + }).Info("pluginhost: plugin reset credential cooldown") + return marshalRPCResult(pluginapi.HostRoutingResetCooldownResponse{ + AuthIndex: updated.Index, + Models: models, + }) +} diff --git a/internal/pluginhost/routing_callbacks_test.go b/internal/pluginhost/routing_callbacks_test.go new file mode 100644 index 00000000000..b1c6d5ea09d --- /dev/null +++ b/internal/pluginhost/routing_callbacks_test.go @@ -0,0 +1,245 @@ +package pluginhost + +import ( + "context" + "encoding/json" + "strings" + "testing" + "time" + + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginabi" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginapi" + log "github.com/sirupsen/logrus" + logtest "github.com/sirupsen/logrus/hooks/test" +) + +type recordingTokenStore struct { + saveCalls int +} + +func (s *recordingTokenStore) List(ctx context.Context) ([]*coreauth.Auth, error) { return nil, nil } +func (s *recordingTokenStore) Save(ctx context.Context, auth *coreauth.Auth) (string, error) { + s.saveCalls++ + return auth.ID, nil +} +func (s *recordingTokenStore) Delete(ctx context.Context, id string) error { return nil } + +func TestHostRoutingResetCooldownClearsCredentialCooldown(t *testing.T) { + const model = "claude-sonnet-5-5" + next := time.Now().Add(65 * time.Hour) + auth := &coreauth.Auth{ + ID: "claude-a.json", + Provider: "claude", + FileName: "claude-a.json", + Status: coreauth.StatusError, + StatusMessage: "quota exhausted", + Unavailable: true, + NextRetryAfter: next, + Quota: coreauth.QuotaState{Exceeded: true, Reason: "credential_quota", NextRecoverAt: next, BackoffLevel: 1}, + ModelStates: map[string]*coreauth.ModelState{ + model: { + Status: coreauth.StatusError, + Unavailable: true, + NextRetryAfter: next, + Quota: coreauth.QuotaState{Exceeded: true, Reason: "credential_quota", NextRecoverAt: next, BackoffLevel: 1}, + UpdatedAt: time.Now(), + }, + }, + } + auth.EnsureIndex() + + host := New() + manager := coreauth.NewManager(nil, nil, nil) + host.SetAuthManager(manager) + if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil { + t.Fatalf("register auth: %v", errRegister) + } + if held, _ := manager.GetByID(auth.ID); held == nil || !held.Quota.Exceeded || !held.Unavailable { + t.Fatalf("registered auth = %+v, want a held credential_quota cooldown", held) + } + + request, errMarshal := json.Marshal(pluginapi.HostRoutingResetCooldownRequest{AuthIndex: auth.Index}) + if errMarshal != nil { + t.Fatalf("marshal request: %v", errMarshal) + } + rawResp, errCall := host.callFromPlugin(context.Background(), pluginabi.MethodHostRoutingResetCooldown, request) + if errCall != nil { + t.Fatalf("callFromPlugin() error = %v", errCall) + } + resp, errDecode := decodeRPCEnvelope[pluginapi.HostRoutingResetCooldownResponse](rawResp) + if errDecode != nil { + t.Fatalf("decode response: %v", errDecode) + } + if resp.AuthIndex != auth.Index { + t.Fatalf("auth_index = %q, want %q", resp.AuthIndex, auth.Index) + } + if len(resp.Models) != 1 || resp.Models[0] != model { + t.Fatalf("models = %v, want [%s]", resp.Models, model) + } + + updated, ok := manager.GetByID(auth.ID) + if !ok || updated == nil { + t.Fatalf("auth %s missing after reset", auth.ID) + } + if updated.Status != coreauth.StatusActive || updated.Unavailable || !updated.NextRetryAfter.IsZero() { + t.Fatalf("auth state = status %q unavailable %v next %v, want active and available", updated.Status, updated.Unavailable, updated.NextRetryAfter) + } + if updated.Quota.Exceeded || updated.Quota.Reason != "" || !updated.Quota.NextRecoverAt.IsZero() { + t.Fatalf("auth quota = %+v, want cleared", updated.Quota) + } + state := updated.ModelStates[model] + if state == nil || state.Unavailable || !state.NextRetryAfter.IsZero() || state.Quota.Exceeded { + t.Fatalf("model state = %+v, want cleared", state) + } +} + +func TestHostRoutingResetCooldownLeavesTokenFilesAlone(t *testing.T) { + const model = "claude-sonnet-5-5" + next := time.Now().Add(48 * time.Hour) + auth := &coreauth.Auth{ + ID: "claude-token-test.json", + Provider: "claude", + FileName: "claude-token-test.json", + Status: coreauth.StatusError, + StatusMessage: "quota exhausted", + Unavailable: true, + NextRetryAfter: next, + Quota: coreauth.QuotaState{Exceeded: true, Reason: "credential_quota", NextRecoverAt: next, BackoffLevel: 1}, + Metadata: map[string]any{ + "account_id": "claude-seat-123", + }, + ModelStates: map[string]*coreauth.ModelState{ + model: { + Status: coreauth.StatusError, + Unavailable: true, + NextRetryAfter: next, + Quota: coreauth.QuotaState{Exceeded: true, Reason: "credential_quota", NextRecoverAt: next, BackoffLevel: 1}, + UpdatedAt: time.Now(), + }, + }, + } + auth.EnsureIndex() + + store := &recordingTokenStore{} + manager := coreauth.NewManager(store, nil, nil) + host := New() + host.SetAuthManager(manager) + + if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil { + t.Fatalf("register auth: %v", errRegister) + } + // Reset recorded save calls from registration + store.saveCalls = 0 + + request, errMarshal := json.Marshal(pluginapi.HostRoutingResetCooldownRequest{AuthIndex: auth.Index}) + if errMarshal != nil { + t.Fatalf("marshal request: %v", errMarshal) + } + rawResp, errCall := host.callFromPlugin(context.Background(), pluginabi.MethodHostRoutingResetCooldown, request) + if errCall != nil { + t.Fatalf("callFromPlugin() error = %v", errCall) + } + resp, errDecode := decodeRPCEnvelope[pluginapi.HostRoutingResetCooldownResponse](rawResp) + if errDecode != nil { + t.Fatalf("decode response: %v", errDecode) + } + if resp.AuthIndex != auth.Index { + t.Fatalf("auth_index = %q, want %q", resp.AuthIndex, auth.Index) + } + + // Verify token store Save was NOT called (token files left alone) + if store.saveCalls != 0 { + t.Fatalf("token store Save was called %d times during cooldown reset, want 0", store.saveCalls) + } + + // Verify cooldown was still reset in memory + updated, ok := manager.GetByID(auth.ID) + if !ok || updated == nil { + t.Fatalf("auth %s missing after reset", auth.ID) + } + if updated.Unavailable || updated.Quota.Exceeded { + t.Fatalf("auth quota state = %+v, unavailable=%v; want cooldown cleared", updated.Quota, updated.Unavailable) + } +} + +func TestHostRoutingResetCooldownRejectsUnknownAuthIndex(t *testing.T) { + host := New() + host.SetAuthManager(coreauth.NewManager(nil, nil, nil)) + + for _, authIndex := range []string{"", "missing"} { + request, errMarshal := json.Marshal(pluginapi.HostRoutingResetCooldownRequest{AuthIndex: authIndex}) + if errMarshal != nil { + t.Fatalf("marshal request: %v", errMarshal) + } + if _, errCall := host.callFromPlugin(context.Background(), pluginabi.MethodHostRoutingResetCooldown, request); errCall == nil { + t.Fatalf("callFromPlugin(%q) error = nil, want error", authIndex) + } + } +} + +func TestHostRoutingResetCooldownRejectsInvalidJSON(t *testing.T) { + host := New() + host.SetAuthManager(coreauth.NewManager(nil, nil, nil)) + + if _, errCall := host.callFromPlugin(context.Background(), pluginabi.MethodHostRoutingResetCooldown, []byte("{invalid-json")); errCall == nil { + t.Fatal("expected error on invalid JSON request, got nil") + } +} + +func TestHostRoutingResetCooldownRequiresAuthManager(t *testing.T) { + host := New() + host.SetAuthManager(nil) + + request, errMarshal := json.Marshal(pluginapi.HostRoutingResetCooldownRequest{AuthIndex: "any"}) + if errMarshal != nil { + t.Fatalf("marshal request: %v", errMarshal) + } + if _, errCall := host.callFromPlugin(context.Background(), pluginabi.MethodHostRoutingResetCooldown, request); errCall == nil { + t.Fatal("expected error when auth manager is unavailable, got nil") + } +} + +func TestHostRoutingResetCooldownLogsPluginID(t *testing.T) { + hook := logtest.NewGlobal() + defer hook.Reset() + + auth := &coreauth.Auth{ + ID: "claude-log-test.json", + Provider: "claude", + FileName: "claude-log-test.json", + Status: coreauth.StatusActive, + ModelStates: map[string]*coreauth.ModelState{}, + } + auth.EnsureIndex() + + host := New() + manager := coreauth.NewManager(nil, nil, nil) + host.SetAuthManager(manager) + if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil { + t.Fatalf("register auth: %v", errRegister) + } + + request, errMarshal := json.Marshal(pluginapi.HostRoutingResetCooldownRequest{AuthIndex: auth.Index}) + if errMarshal != nil { + t.Fatalf("marshal request: %v", errMarshal) + } + + pluginCtx := withHostCallbackPluginID(context.Background(), "claude-seat-pacer") + if _, errCall := host.callFromPlugin(pluginCtx, pluginabi.MethodHostRoutingResetCooldown, request); errCall != nil { + t.Fatalf("callFromPlugin() error = %v", errCall) + } + + found := false + for _, entry := range hook.AllEntries() { + if entry.Level == log.InfoLevel && strings.Contains(entry.Message, "plugin reset credential cooldown") { + if entry.Data["plugin_id"] == "claude-seat-pacer" && entry.Data["auth_index"] == auth.Index { + found = true + break + } + } + } + if !found { + t.Fatalf("expected info log entry with plugin_id=claude-seat-pacer and auth_index=%s, got entries: %+v", auth.Index, hook.AllEntries()) + } +} diff --git a/sdk/pluginabi/types.go b/sdk/pluginabi/types.go index 31800ccce8a..e79fd8c16fe 100644 --- a/sdk/pluginabi/types.go +++ b/sdk/pluginabi/types.go @@ -110,6 +110,8 @@ const ( MethodHostAuthGetRuntime = "host.auth.get_runtime" MethodHostAuthSave = "host.auth.save" MethodHostAffinityLookup = "host.affinity.lookup" + + MethodHostRoutingResetCooldown = "host.routing.reset_cooldown" ) type Envelope struct { diff --git a/sdk/pluginabi/types_test.go b/sdk/pluginabi/types_test.go index 80700f99ae5..e4b1156570e 100644 --- a/sdk/pluginabi/types_test.go +++ b/sdk/pluginabi/types_test.go @@ -109,6 +109,9 @@ func TestMethodNamesAreStable(t *testing.T) { if MethodHostAffinityLookup != "host.affinity.lookup" { t.Fatalf("MethodHostAffinityLookup = %q", MethodHostAffinityLookup) } + if MethodHostRoutingResetCooldown != "host.routing.reset_cooldown" { + t.Fatalf("MethodHostRoutingResetCooldown = %q", MethodHostRoutingResetCooldown) + } if MethodExecutorExecuteStream != "executor.execute_stream" { t.Fatalf("MethodExecutorExecuteStream = %q", MethodExecutorExecuteStream) } diff --git a/sdk/pluginapi/types.go b/sdk/pluginapi/types.go index 3d2e619767c..b1bd3686841 100644 --- a/sdk/pluginapi/types.go +++ b/sdk/pluginapi/types.go @@ -884,6 +884,20 @@ type HostAffinityLookupResponse struct { Unavailable bool `json:"unavailable,omitempty"` } +// HostRoutingResetCooldownRequest asks the host to clear quota and cooldown routing state for one credential. +type HostRoutingResetCooldownRequest struct { + // AuthIndex identifies the credential index. + AuthIndex string `json:"auth_index"` +} + +// HostRoutingResetCooldownResponse reports the credential whose quota and cooldown state was cleared. +type HostRoutingResetCooldownResponse struct { + // AuthIndex identifies the credential index. + AuthIndex string `json:"auth_index"` + // Models lists the model keys whose routing state was reset. + Models []string `json:"models,omitempty"` +} + // HTTPWireProfile configures transport-level wire representation for plugin HTTP requests. type HTTPWireProfile struct { // HTTP1Only forces the transport to use HTTP/1.1 and disables HTTP/2 negotiation. From d306f2c56dd70003aed937cab579b61126fd7930 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Sat, 3 Oct 2026 00:01:42 +0800 Subject: [PATCH 004/142] fix(codex): retain template freeform apply_patch capability by default - Retain `freeform` apply_patch tool type for native template models when `enable-apply-patch` is false - Update client configuration documentation for `client.codex.enable-apply-patch` Closes: #6286 --- config.example.yaml | 4 +- .../api/server_apply_patch_config_test.go | 4 +- internal/client/codex/models/apply_patch.go | 10 ++- .../client/codex/models/apply_patch_test.go | 62 ++++++++++++++++++- .../openai/codex_client_models_test.go | 9 ++- 5 files changed, 80 insertions(+), 9 deletions(-) diff --git a/config.example.yaml b/config.example.yaml index b52adf58bd6..dd93a0125de 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -275,8 +275,8 @@ requests: # Client-facing compatibility settings apply to both OAuth and API-key routes. client: codex: - # Default false clears apply_patch_tool_type in /v1/models?client_version= catalogs. - # When true, only models supported by every routing executor advertise "freeform". + # When false (default), only models that natively declare freeform apply_patch advertise it. + # When true, non-template and bridged models supported by every routing executor also advertise "freeform". enable-apply-patch: false # When true, optimize Codex Desktop, codex-tui, and codex_cli_rs requests for multi-agent v2. # This refreshes Codex spawn_agent model details, removes message parameter encryption, diff --git a/internal/api/server_apply_patch_config_test.go b/internal/api/server_apply_patch_config_test.go index 422d678ee5a..9283c75f51d 100644 --- a/internal/api/server_apply_patch_config_test.go +++ b/internal/api/server_apply_patch_config_test.go @@ -74,7 +74,9 @@ func TestModelsApplyPatchClientConfigAndReload(t *testing.T) { for _, entry := range response.Models { var want any switch entry["slug"] { - case "gpt-5.5", "config-patch-synthetic": + case "gpt-5.5": + want = "freeform" + case "config-patch-synthetic": if tc.want { want = "freeform" } diff --git a/internal/client/codex/models/apply_patch.go b/internal/client/codex/models/apply_patch.go index 601db662917..0883b7fd059 100644 --- a/internal/client/codex/models/apply_patch.go +++ b/internal/client/codex/models/apply_patch.go @@ -7,10 +7,8 @@ import "strings" type ApplyPatchCapabilityForModelFunc func(string) bool func applyCodexClientApplyPatchCapability(entry map[string]any, id string, capability ApplyPatchCapabilityForModelFunc) { + templateSupported := entry["apply_patch_tool_type"] == "freeform" entry["apply_patch_tool_type"] = nil - if capability == nil { - return - } // Built-in image/video IDs can inherit a generic text template in Home. // This classification is a model restriction, not routing capability evidence. baseID := strings.ToLower(strings.TrimSpace(id)) @@ -44,6 +42,12 @@ func applyCodexClientApplyPatchCapability(entry map[string]any, id string, capab if !supportsText && (hasModalities || entry["visibility"] == "hide") { return } + if capability == nil { + if templateSupported { + entry["apply_patch_tool_type"] = "freeform" + } + return + } if capability(strings.TrimSpace(id)) { entry["apply_patch_tool_type"] = "freeform" } diff --git a/internal/client/codex/models/apply_patch_test.go b/internal/client/codex/models/apply_patch_test.go index 55b09f09a3f..717f0ae8688 100644 --- a/internal/client/codex/models/apply_patch_test.go +++ b/internal/client/codex/models/apply_patch_test.go @@ -71,6 +71,11 @@ func TestCodexCatalogApplyPatchCapability(t *testing.T) { var want any if capability.want { want = "freeform" + } else if capability.get == nil && providerLookup.name == "nil" { + switch model.id { + case "gpt-5.5", "catalog-patch-alias", "team/gpt-5.5", "gpt-reserve": + want = "freeform" + } } if !present || value != want { t.Fatalf("apply_patch_tool_type = %#v (present %v), want %#v", value, present, want) @@ -97,7 +102,15 @@ func TestCodexCatalogApplyPatchLegacyEntryPointsUnknown(t *testing.T) { } for _, response := range responses { for _, entry := range response["models"].([]map[string]any) { - assertCodexNullableFieldCleared(t, entry, "apply_patch_tool_type") + slug := stringModelValue(entry, "slug") + switch slug { + case "gpt-5.5", "gpt-reserve": + if got, _ := entry["apply_patch_tool_type"].(string); got != "freeform" { + t.Fatalf("model %s: apply_patch_tool_type = %#v, want freeform", slug, entry["apply_patch_tool_type"]) + } + default: + assertCodexNullableFieldCleared(t, entry, "apply_patch_tool_type") + } } } } @@ -138,3 +151,50 @@ func TestApplyPatchFieldModalities(t *testing.T) { }) } } + +func TestCodexCatalogApplyPatch_TemplateModelsRetainFreeformByDefault_Issue6286(t *testing.T) { + // Models defined in codex_client_models.json with "apply_patch_tool_type": "freeform" + // must retain "freeform" under pure Codex providers even when enable-apply-patch is false (capability == nil). + canonicalTemplateModels := []string{ + "gpt-6.1-sol", + "gpt-6-astra", + "gpt-6-sol", + "gpt-6-luna", + "gpt-reserve", + "gpt-5.6-sol", + "gpt-5.6-terra", + "gpt-5.6-luna", + "gpt-5.5", + } + + for _, modelID := range canonicalTemplateModels { + t.Run(modelID, func(t *testing.T) { + available := []map[string]any{{"id": modelID}} + // capability is nil (simulates client.codex.enable-apply-patch: false) + // providersForModel is nil (pure Codex default) + resp := BuildResponseForClientWithToolCapabilities(available, nil, nil, nil, false, "0.153.4") + entries, ok := resp["models"].([]map[string]any) + if !ok || len(entries) != 1 { + t.Fatalf("expected 1 model entry, got %v", resp["models"]) + } + entry := entries[0] + if got, present := entry["apply_patch_tool_type"]; !present || got != "freeform" { + t.Fatalf("model %s: apply_patch_tool_type = %#v (present: %t), want %q", modelID, got, present, "freeform") + } + }) + } + + // Non-template models without freeform in template must still default to null when capability is nil. + t.Run("non-template model defaults to null", func(t *testing.T) { + available := []map[string]any{{"id": "non-template-custom-model"}} + resp := BuildResponseForClientWithToolCapabilities(available, nil, nil, nil, false, "0.153.4") + entries, ok := resp["models"].([]map[string]any) + if !ok || len(entries) != 1 { + t.Fatalf("expected 1 model entry, got %v", resp["models"]) + } + entry := entries[0] + if got, present := entry["apply_patch_tool_type"]; !present || got != nil { + t.Fatalf("non-template model: apply_patch_tool_type = %#v (present: %t), want nil", got, present) + } + }) +} diff --git a/sdk/api/handlers/openai/codex_client_models_test.go b/sdk/api/handlers/openai/codex_client_models_test.go index a60aedafd61..84e6258df53 100644 --- a/sdk/api/handlers/openai/codex_client_models_test.go +++ b/sdk/api/handlers/openai/codex_client_models_test.go @@ -338,8 +338,8 @@ func TestCodexClientModelsApplyPatchRouting(t *testing.T) { } t.Fatalf("missing model %q", id) } - // A provider label alone is not an executor capability claim. - assertPatch(t, handler.codexClientModelsResponse("0.153.4"), "gpt-5.5", nil) + // Models that natively declare freeform apply_patch advertise it by default under pure Codex routes. + assertPatch(t, handler.codexClientModelsResponse("0.153.4"), "gpt-5.5", "freeform") manager.RegisterExecutor(executor.NewCodexAutoExecutor(&config.Config{})) manager.RegisterExecutor(executor.NewOpenAICompatExecutor("catalog-custom", &config.Config{})) manager.RegisterExecutor(catalogUnknownExecutor{executor.NewOpenAICompatExecutor("catalog-remote", &config.Config{})}) @@ -356,6 +356,11 @@ func TestCodexClientModelsApplyPatchRouting(t *testing.T) { case "gpt-5.5", "gpt-reserve", "catalog-patch-synthetic", "catalog-patch-alias", "catalog-patch-mixed": want = "freeform" } + } else { + switch entry["slug"] { + case "gpt-5.5", "gpt-reserve": + want = "freeform" + } } assertPatch(t, response, entry["slug"].(string), want) } From 6d57ac9087623268e35086728d893487657127e8 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Sat, 3 Oct 2026 00:28:35 +0800 Subject: [PATCH 005/142] fix(claude): pin session date in cloaked reminder to prevent prompt cache invalidation - Pin local date to continuity context on the first request of a session - Reuse pinned session date during cloaked date injection across execute and stream flows - Prevent midnight calendar date flips from invalidating conversation prompt cache prefixes Closes: #6282 --- .../executor/claude_cloaked_date_pin_test.go | 345 ++++++++++++++++++ .../executor/claude_executor_cloaking.go | 47 ++- .../executor/claude_executor_execute.go | 5 +- .../executor/claude_executor_stream.go | 5 +- .../runtime/executor/claude_executor_test.go | 22 +- .../executor/helps/claude_diagnostics.go | 35 +- .../executor/helps/claude_diagnostics_test.go | 32 ++ 7 files changed, 465 insertions(+), 26 deletions(-) create mode 100644 internal/runtime/executor/claude_cloaked_date_pin_test.go diff --git a/internal/runtime/executor/claude_cloaked_date_pin_test.go b/internal/runtime/executor/claude_cloaked_date_pin_test.go new file mode 100644 index 00000000000..309dae53d6c --- /dev/null +++ b/internal/runtime/executor/claude_cloaked_date_pin_test.go @@ -0,0 +1,345 @@ +package executor + +import ( + "context" + "fmt" + "io" + "net/http" + "regexp" + "strings" + "testing" + "time" + + claudeauth "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/claude" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +var claudeDateReminderPattern = regexp.MustCompile(`Today's date is (\d{4}-\d{2}-\d{2})`) + +// extractClaudeCloakDate pulls the calendar date out of the currentDate +// reminder injected into the first user message of a cloaked payload. +func extractClaudeCloakDate(t *testing.T, payload []byte) string { + t.Helper() + content := gjson.GetBytes(payload, "messages.0.content") + if content.IsArray() { + for _, block := range content.Array() { + if match := claudeDateReminderPattern.FindStringSubmatch(block.Get("text").String()); match != nil { + return match[1] + } + } + } else if match := claudeDateReminderPattern.FindStringSubmatch(content.String()); match != nil { + return match[1] + } + t.Fatalf("no currentDate reminder found in first user message: %s", payload) + return "" +} + +// TestClaudeCloakedDateReminderPinnedToSessionAcrossMidnight verifies that the +// cloaked currentDate reminder stays identical for one session even when the +// local calendar date flips between two requests. Rewriting the date on every +// request would invalidate the prompt-cache prefix in front of the entire +// conversation, including in-flight turns. +func TestClaudeCloakedDateReminderPinnedToSessionAcrossMidnight(t *testing.T) { + helps.ResetClaudeDiagnosticsForTest() + t.Cleanup(helps.ResetClaudeDiagnosticsForTest) + + auth := &cliproxyauth.Auth{ + ID: "test-date-pin-cred", + Attributes: map[string]string{"timezone": "Asia/Shanghai"}, + } + headers := http.Header{} + ctx := helps.WithClaudeSessionID(context.Background(), "sess-midnight") + + payload1 := []byte(`{"model":"claude-opus-5","messages":[{"role":"user","content":"turn one"}]}`) + prevReq1, promptID1, cCtx1, ok1 := resolveClaudeContinuityTags(ctx, nil, auth, headers, payload1, true, "", "") + if !ok1 { + t.Fatal("continuity context not resolved for session request 1") + } + if cCtx1.PinnedDate == "" { + t.Fatal("first request must establish a pinned session date") + } + out1 := checkSystemInstructionsWithSigningModeAt(payload1, false, false, "2.1.280", "cli", "", cCtx1.PinnedDate, false, prevReq1, promptID1) + date1 := extractClaudeCloakDate(t, out1) + if date1 != cCtx1.PinnedDate { + t.Fatalf("first request date = %q, want pinned anchor %q", date1, cCtx1.PinnedDate) + } + + // Second request after local midnight: the per-request candidate would be + // the flipped date, but the session pin must win. Compute the next calendar day + // dynamically from the pinned anchor date rather than hardcoding. + parsedAnchor, errParse := time.Parse("2006-01-02", cCtx1.PinnedDate) + if errParse != nil { + t.Fatalf("parse anchor date: %v", errParse) + } + nextDay := parsedAnchor.AddDate(0, 0, 1).Format("2006-01-02") + if nextDay == cCtx1.PinnedDate { + t.Fatalf("test setup: anchor %q must differ from the simulated next day", cCtx1.PinnedDate) + } + resolved := helps.PinClaudeSessionDate(cCtx1.Key, nextDay) + if resolved != cCtx1.PinnedDate { + t.Fatalf("second request resolved date = %q, want session-pinned %q (local midnight flip busts the cached prefix)", resolved, cCtx1.PinnedDate) + } + + payload2 := []byte(`{"model":"claude-opus-5","messages":[` + + `{"role":"user","content":"turn one"},` + + `{"role":"assistant","content":"ok"},` + + `{"role":"user","content":"turn two"}]}`) + prevReq2, promptID2, cCtx2, ok2 := resolveClaudeContinuityTags(ctx, nil, auth, headers, payload2, true, "", "") + if !ok2 { + t.Fatal("continuity context not resolved for session request 2") + } + if cCtx2.PinnedDate != cCtx1.PinnedDate { + t.Fatalf("second request continuity pin = %q, want anchor %q", cCtx2.PinnedDate, cCtx1.PinnedDate) + } + out2 := checkSystemInstructionsWithSigningModeAt(payload2, false, false, "2.1.280", "cli", "", cCtx2.PinnedDate, false, prevReq2, promptID2) + date2 := extractClaudeCloakDate(t, out2) + if date2 != date1 { + t.Fatalf("date reminder changed within one session: %q -> %q (busts prompt cache prefix)", date1, date2) + } +} + +// roundTripperFunc mirrors the helper used by the cache repro tests. +type datePinRoundTripperFunc func(req *http.Request) (*http.Response, error) + +func (f datePinRoundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) { + return f(req) +} + +// TestClaudeCloakedDateReminderSessionByteStability locks the executor-level +// behaviour: two requests of the same pinned session produce an identical +// messages[0] (which carries the currentDate reminder) even across simulated +// local midnight, and a fresh session re-anchors to the new date. +func TestClaudeCloakedDateReminderSessionByteStability(t *testing.T) { + helps.ResetClaudeDiagnosticsForTest() + t.Cleanup(helps.ResetClaudeDiagnosticsForTest) + + var mockTime time.Time + claudeCodeCurrentTimeFunc = func(cfg *config.Config, auth *cliproxyauth.Auth) time.Time { + return mockTime + } + t.Cleanup(func() { + claudeCodeCurrentTimeFunc = nil + }) + + var capturedBodies [][]byte + call := 0 + transport := datePinRoundTripperFunc(func(req *http.Request) (*http.Response, error) { + body := make([]byte, 0) + if req.Body != nil { + buf, errRead := io.ReadAll(req.Body) + if errRead != nil { + t.Fatal(errRead) + } + body = buf + } + capturedBodies = append(capturedBodies, body) + call++ + response := fmt.Sprintf(`{"id":"msg_%d","type":"message","model":"claude-opus-5","role":"assistant","content":[{"type":"text","text":"OK"}],"usage":{"input_tokens":10,"output_tokens":2}}`, call) + header := make(http.Header) + header.Set("Content-Type", "application/json") + header.Set("request-id", fmt.Sprintf("req_upstream_%d", call)) + return &http.Response{ + StatusCode: http.StatusOK, + Header: header, + Body: io.NopCloser(strings.NewReader(response)), + Request: req, + }, nil + }) + + cfg := &config.Config{} + auth := &cliproxyauth.Auth{ + ID: "test-date-pin-exec-oauth", + Attributes: map[string]string{"api_key": "sk-ant-oat-test-oauth-key-date-pin", "cloak_mode": "always", "timezone": "Asia/Shanghai"}, + Metadata: map[string]any{ + "account_uuid": "11111111-2222-4333-8444-555555555555", + claudeauth.ClaudeDeviceIDsMetadataKey: []string{ + "00000000000000000000000000000000000000000000000000000000000000d1", + }, + }, + } + exec := NewClaudeExecutor(cfg) + + payload := `{ + "model": "claude-opus-5", + "system": [{"type": "text", "text": "You are an expert software engineer.", "cache_control": {"type": "ephemeral"}}], + "messages": [{"role": "user", "content": "Say OK."}], + "max_tokens": 100 + }` + options := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatClaude, + Headers: http.Header{"X-Session-ID": []string{"date-pin-session-1"}}, + } + + // Request 1: before midnight + mockTime = time.Date(2026, 8, 1, 23, 59, 0, 0, time.UTC) + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + req := cliproxyexecutor.Request{Model: "claude-opus-5", Payload: []byte(payload)} + if _, err := exec.Execute(ctx, auth, req, options); err != nil { + t.Fatalf("request 1 failed: %v", err) + } + + // Request 2: after midnight in the same session + mockTime = time.Date(2026, 8, 2, 0, 1, 0, 0, time.UTC) + if _, err := exec.Execute(ctx, auth, req, options); err != nil { + t.Fatalf("request 2 failed: %v", err) + } + + // Request 2b: after midnight in the same session via ExecuteStream + if _, err := exec.ExecuteStream(ctx, auth, req, options); err != nil { + t.Fatalf("request 2b (stream) failed: %v", err) + } + + if len(capturedBodies) != 3 { + t.Fatalf("expected 3 captured bodies, got %d", len(capturedBodies)) + } + + msg0First := gjson.GetBytes(capturedBodies[0], "messages.0").Raw + msg0Second := gjson.GetBytes(capturedBodies[1], "messages.0").Raw + msg0SecondStream := gjson.GetBytes(capturedBodies[2], "messages.0").Raw + if msg0First != msg0Second { + t.Fatalf("messages[0] changed between requests of one session:\nfirst: %s\nsecond: %s", msg0First, msg0Second) + } + if msg0First != msg0SecondStream { + t.Fatalf("messages[0] changed between requests of one session in stream:\nfirst: %s\nstream: %s", msg0First, msg0SecondStream) + } + + if got := extractClaudeCloakDate(t, capturedBodies[0]); got != "2026-08-01" { + t.Fatalf("first session date = %q, want anchored 2026-08-01", got) + } + if got := extractClaudeCloakDate(t, capturedBodies[1]); got != "2026-08-01" { + t.Fatalf("second session date across midnight = %q, want pinned 2026-08-01", got) + } + if got := extractClaudeCloakDate(t, capturedBodies[2]); got != "2026-08-01" { + t.Fatalf("stream session date across midnight = %q, want pinned 2026-08-01", got) + } + + // Request 3: a fresh session re-anchors to the new date + options.Headers = http.Header{"X-Session-ID": []string{"date-pin-session-2"}} + if _, err := exec.Execute(ctx, auth, req, options); err != nil { + t.Fatalf("fresh session request failed: %v", err) + } + if len(capturedBodies) != 4 { + t.Fatalf("expected 4 captured bodies, got %d", len(capturedBodies)) + } + if got := extractClaudeCloakDate(t, capturedBodies[3]); got != "2026-08-02" { + t.Fatalf("fresh session date = %q, want current date 2026-08-02", got) + } +} + +// TestClaudeCloakedDateReminderDeclassifiedProbePinsSessionDate verifies that when +// a probe request is declassified into a normal request across midnight in an ongoing +// session, the declassification branch re-applies the pinned session date. +func TestClaudeCloakedDateReminderDeclassifiedProbePinsSessionDate(t *testing.T) { + helps.ResetClaudeDiagnosticsForTest() + t.Cleanup(helps.ResetClaudeDiagnosticsForTest) + + var mockTime time.Time + claudeCodeCurrentTimeFunc = func(cfg *config.Config, auth *cliproxyauth.Auth) time.Time { + return mockTime + } + t.Cleanup(func() { + claudeCodeCurrentTimeFunc = nil + }) + + var capturedBodies [][]byte + call := 0 + transport := datePinRoundTripperFunc(func(req *http.Request) (*http.Response, error) { + body := make([]byte, 0) + if req.Body != nil { + buf, errRead := io.ReadAll(req.Body) + if errRead != nil { + t.Fatal(errRead) + } + body = buf + } + capturedBodies = append(capturedBodies, body) + call++ + response := fmt.Sprintf(`{"id":"msg_%d","type":"message","model":"claude-opus-5","role":"assistant","content":[{"type":"text","text":"OK"}],"usage":{"input_tokens":10,"output_tokens":2}}`, call) + header := make(http.Header) + header.Set("Content-Type", "application/json") + header.Set("request-id", fmt.Sprintf("req_upstream_%d", call)) + return &http.Response{ + StatusCode: http.StatusOK, + Header: header, + Body: io.NopCloser(strings.NewReader(response)), + Request: req, + }, nil + }) + + // Use PayloadConfig to override max_tokens: 1 (which would classify as probe) to 100, + // triggering declassification via wasProbeOrHelper. + cfg := &config.Config{ + Payload: config.PayloadConfig{ + Override: []config.PayloadRule{ + { + Models: []config.PayloadModelRule{{Name: "claude-opus-5", Protocol: "claude"}}, + Params: map[string]any{"max_tokens": 100}, + }, + }, + }, + } + auth := &cliproxyauth.Auth{ + ID: "test-date-pin-exec-oauth-declass", + Attributes: map[string]string{"api_key": "sk-ant-oat-test-oauth-key-date-pin", "cloak_mode": "always", "timezone": "Asia/Shanghai"}, + Metadata: map[string]any{ + "account_uuid": "11111111-2222-4333-8444-555555555555", + claudeauth.ClaudeDeviceIDsMetadataKey: []string{ + "00000000000000000000000000000000000000000000000000000000000000d1", + }, + }, + } + exec := NewClaudeExecutor(cfg) + + // Normal request establishing the session on day 1 + mockTime = time.Date(2026, 8, 1, 23, 59, 0, 0, time.UTC) + normalPayload := `{ + "model": "claude-opus-5", + "messages": [{"role": "user", "content": "normal request"}], + "max_tokens": 100 + }` + options := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatClaude, + Headers: http.Header{"X-Session-ID": []string{"declass-session-1"}}, + } + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + req1 := cliproxyexecutor.Request{Model: "claude-opus-5", Payload: []byte(normalPayload)} + if _, err := exec.Execute(ctx, auth, req1, options); err != nil { + t.Fatalf("request 1 failed: %v", err) + } + + // Request 2: Across midnight, request initially has max_tokens: 1 and content: "probe", + // but PayloadOverride declassifies it into a normal request. + mockTime = time.Date(2026, 8, 2, 0, 1, 0, 0, time.UTC) + probePayload := `{ + "model": "claude-opus-5", + "messages": [{"role": "user", "content": "probe"}], + "max_tokens": 1 + }` + req2 := cliproxyexecutor.Request{Model: "claude-opus-5", Payload: []byte(probePayload)} + if _, err := exec.Execute(ctx, auth, req2, options); err != nil { + t.Fatalf("request 2 (Execute) failed: %v", err) + } + + // Request 3: Same thing for ExecuteStream + req3 := cliproxyexecutor.Request{Model: "claude-opus-5", Payload: []byte(probePayload)} + if _, err := exec.ExecuteStream(ctx, auth, req3, options); err != nil { + t.Fatalf("request 3 (ExecuteStream) failed: %v", err) + } + + if len(capturedBodies) != 3 { + t.Fatalf("expected 3 captured bodies, got %d", len(capturedBodies)) + } + + // Both declassified requests must carry the session's pinned date ("2026-08-01") + if got := extractClaudeCloakDate(t, capturedBodies[1]); got != "2026-08-01" { + t.Fatalf("declassified Execute request date = %q, want session pinned 2026-08-01", got) + } + if got := extractClaudeCloakDate(t, capturedBodies[2]); got != "2026-08-01" { + t.Fatalf("declassified ExecuteStream request date = %q, want session pinned 2026-08-01", got) + } +} diff --git a/internal/runtime/executor/claude_executor_cloaking.go b/internal/runtime/executor/claude_executor_cloaking.go index 40f72da07ea..c2e34aa9fb5 100644 --- a/internal/runtime/executor/claude_executor_cloaking.go +++ b/internal/runtime/executor/claude_executor_cloaking.go @@ -194,6 +194,7 @@ func generateBillingHeader(cchSigning bool, version, messageText, entrypoint, wo func resolveClaudeContinuityTags( ctx context.Context, + cfg *config.Config, auth *cliproxyauth.Auth, incomingHeaders http.Header, payload []byte, @@ -213,6 +214,11 @@ func resolveClaudeContinuityTags( isNewTurn := helps.IsClaudeNewPromptTurn(payload) continuityKey, seq, prevMsgID, storedPrevReq, storedPromptID := helps.BeginClaudeContinuity(credIdentity, sessionID, isNewTurn, existingPromptID) + // The currentDate reminder is pinned to the session on its first request so + // a local-midnight flip between requests cannot rewrite it and invalidate + // the prompt-cache prefix in front of the whole conversation. + pinnedDate := helps.PinClaudeSessionDate(continuityKey, claudeCodeLocalDate(claudeCodeCurrentTime(cfg, auth))) + if existingPromptID != "" { promptID = existingPromptID } else if prevMsgID != "" && storedPromptID != "" && (hasExecutionMetadata || !isNewTurn) { @@ -233,6 +239,7 @@ func resolveClaudeContinuityTags( Key: continuityKey, Sequence: seq, PromptID: promptID, + PinnedDate: pinnedDate, Initialized: true, } if hasExecutionMetadata || existingPrevReq != "" { @@ -313,7 +320,7 @@ func checkSystemInstructionsWithMode(payload []byte, strictMode bool) []byte { // Claude models give it operator-level authority without changing the cached // top-level prefix. func checkSystemInstructionsWithSigningMode(payload []byte, strictMode bool, cchSigning bool, version, entrypoint, workload string) []byte { - return checkSystemInstructionsWithSigningModeAt(payload, strictMode, cchSigning, version, entrypoint, workload, time.Now(), false, "", "") + return checkSystemInstructionsWithSigningModeAt(payload, strictMode, cchSigning, version, entrypoint, workload, claudeCodeLocalDate(time.Now()), false, "", "") } // isClaudeFable51Model reports whether the model is specifically Fable 5.1 / Mythos 5.1, @@ -337,7 +344,7 @@ func checkSystemInstructionsWithSigningModeAt( strictMode bool, cchSigning bool, version, entrypoint, workload string, - now time.Time, + currentDate string, isSubagent bool, prevReq, promptID string, turnOrigin ...string, @@ -356,19 +363,19 @@ func checkSystemInstructionsWithSigningModeAt( } payload, _ = sjson.SetRawBytes(payload, "system", []byte("["+strings.Join(systemBlocks, ",")+"]")) if strictMode { - return injectClaudeCodeCurrentDate(payload, now) + return injectClaudeCodeCurrentDate(payload, currentDate) } forwardedSystemBlocks := collectForwardedClaudeSystemPromptBlocks(system) if len(forwardedSystemBlocks) == 0 { - return injectClaudeCodeCurrentDate(payload, now) + return injectClaudeCodeCurrentDate(payload, currentDate) } if claudeHistoryHasAdvisorCallOrResult(payload) { for _, block := range forwardedSystemBlocks { systemBlocks = append(systemBlocks, buildTextBlock(block, nil)) } payload, _ = sjson.SetRawBytes(payload, "system", []byte("["+strings.Join(systemBlocks, ",")+"]")) - return injectClaudeCodeCurrentDate(payload, now) + return injectClaudeCodeCurrentDate(payload, currentDate) } if claudeUsesLegacySystemReminder(payload) { payload = prependClaudeSystemRemindersToFirstUserMessage(payload, forwardedSystemBlocks) @@ -378,7 +385,7 @@ func checkSystemInstructionsWithSigningModeAt( // stay on the user-reminder compatibility path. payload = insertClaudeMidConversationSystemMessages(payload, forwardedSystemBlocks) } - return injectClaudeCodeCurrentDate(payload, now) + return injectClaudeCodeCurrentDate(payload, currentDate) } // relocateClaudeSystemPromptForCountTokens keeps a cloaked count_tokens request @@ -1081,7 +1088,12 @@ func claudeCodeLocalDate(now time.Time) string { return fmt.Sprintf("%04d-%02d-%02d", year, int(month), day) } +var claudeCodeCurrentTimeFunc func(cfg *config.Config, auth *cliproxyauth.Auth) time.Time + func claudeCodeCurrentTime(cfg *config.Config, auth *cliproxyauth.Auth) time.Time { + if claudeCodeCurrentTimeFunc != nil { + return claudeCodeCurrentTimeFunc(cfg, auth) + } return time.Now().In(claudeCodeTimezone(cfg, auth)) } @@ -1117,7 +1129,7 @@ func claudeCredentialTimezone(auth *cliproxyauth.Auth) string { return strings.TrimSpace(claudeauth.ReadMetadataString(&auth.Metadata, "timezone")) } -func claudeCodeCurrentDateReminder(now time.Time) string { +func claudeCodeCurrentDateReminder(date string) string { return fmt.Sprintf(` As you answer the user's questions, you can use the following context: # currentDate @@ -1126,7 +1138,7 @@ Today's date is %s. IMPORTANT: this context may or may not be relevant to your tasks. You should not respond to this context unless it is highly relevant to your task. -`, claudeCodeLocalDate(now)) +`, date) } func firstClaudeUserMessageIndex(payload []byte) int { @@ -1154,7 +1166,11 @@ func isClaudeCodeCurrentDateReminder(text string) bool { return strings.HasPrefix(text, "\nAs you answer the user's questions, you can use the following context:\n# currentDate\nToday's date is ") } -func injectClaudeCodeCurrentDate(payload []byte, now time.Time) []byte { +// injectClaudeCodeCurrentDate stamps the currentDate reminder into the first +// user message. date is the already-resolved calendar date (the session-pinned +// one whenever continuity is available) so the reminder text cannot change +// between requests of one session. +func injectClaudeCodeCurrentDate(payload []byte, date string) []byte { firstUserIdx := firstClaudeUserMessageIndex(payload) if firstUserIdx < 0 { return payload @@ -1162,7 +1178,7 @@ func injectClaudeCodeCurrentDate(payload []byte, now time.Time) []byte { contentPath := fmt.Sprintf("messages.%d.content", firstUserIdx) content := gjson.GetBytes(payload, contentPath) - dateText := claudeCodeCurrentDateReminder(now) + dateText := claudeCodeCurrentDateReminder(date) dateBlock := buildTextBlock(dateText, nil) if content.Type == gjson.String { @@ -1420,6 +1436,7 @@ func applyCloakingInternal( isSubagent := false prevReq := "" promptID := "" + pinnedDate := "" var incomingHeaders http.Header if !isProbeOrHelper { incomingHeaders = resolveIncomingClaudeHeaders(ctx, helps.IncomingHeadersFromContext(ctx)) @@ -1428,13 +1445,19 @@ func applyCloakingInternal( var cCtx helps.ClaudeContinuityContext var ok bool - prevReq, promptID, cCtx, ok = resolveClaudeContinuityTags(ctx, auth, incomingHeaders, payload, confirmedClaudeCode, existingPrevReq, existingPromptID) + prevReq, promptID, cCtx, ok = resolveClaudeContinuityTags(ctx, cfg, auth, incomingHeaders, payload, confirmedClaudeCode, existingPrevReq, existingPromptID) if ok { + pinnedDate = cCtx.PinnedDate if continuityCtx := helps.ClaudeContinuityContextFromContext(ctx); continuityCtx != nil { *continuityCtx = cCtx } } } + // Without continuity state (probe/helper traffic, or no session identity) + // fall back to the per-request date, which is the pre-pinning behaviour. + if pinnedDate == "" { + pinnedDate = claudeCodeLocalDate(claudeCodeCurrentTime(cfg, auth)) + } turnOrigin := "" if !isProbeOrHelper && !isSubagent { @@ -1447,7 +1470,7 @@ func applyCloakingInternal( billingVersion, "cli", workload, - claudeCodeCurrentTime(cfg, auth), + pinnedDate, isSubagent, prevReq, promptID, diff --git a/internal/runtime/executor/claude_executor_execute.go b/internal/runtime/executor/claude_executor_execute.go index 5a26dabba99..cfda1b35263 100644 --- a/internal/runtime/executor/claude_executor_execute.go +++ b/internal/runtime/executor/claude_executor_execute.go @@ -178,11 +178,14 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r // Initialize continuity and diagnostics if cloaked and eligible. if cloaked { existingPrevReq, existingPromptID := helps.ExtractClaudeBillingTags(body) - prevReq, promptID, cCtx, ok := resolveClaudeContinuityTags(ctx, auth, incomingHeaders, body, confirmedClaudeCode, existingPrevReq, existingPromptID) + prevReq, promptID, cCtx, ok := resolveClaudeContinuityTags(ctx, e.cfg, auth, incomingHeaders, body, confirmedClaudeCode, existingPrevReq, existingPromptID) if ok { if continuityCtx != nil { *continuityCtx = cCtx } + if cCtx.PinnedDate != "" { + body = injectClaudeCodeCurrentDate(body, cCtx.PinnedDate) + } body = helps.InjectClaudeBillingTags(body, prevReq, promptID) if fp.InjectDiagnostics && isAnthropicUpstreamBase(baseURL) { body, diagnosticsState = injectClaudeDiagnosticsWithState(body, cCtx.Key, cCtx.Sequence, cCtx.PreviousMessageID, promptID) diff --git a/internal/runtime/executor/claude_executor_stream.go b/internal/runtime/executor/claude_executor_stream.go index d51f0e32f0e..1356d45a90b 100644 --- a/internal/runtime/executor/claude_executor_stream.go +++ b/internal/runtime/executor/claude_executor_stream.go @@ -181,11 +181,14 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A // Initialize continuity and diagnostics if cloaked and eligible. if cloaked { existingPrevReq, existingPromptID := helps.ExtractClaudeBillingTags(body) - prevReq, promptID, cCtx, ok := resolveClaudeContinuityTags(ctx, auth, incomingHeaders, body, confirmedClaudeCode, existingPrevReq, existingPromptID) + prevReq, promptID, cCtx, ok := resolveClaudeContinuityTags(ctx, e.cfg, auth, incomingHeaders, body, confirmedClaudeCode, existingPrevReq, existingPromptID) if ok { if continuityCtx != nil { *continuityCtx = cCtx } + if cCtx.PinnedDate != "" { + body = injectClaudeCodeCurrentDate(body, cCtx.PinnedDate) + } body = helps.InjectClaudeBillingTags(body, prevReq, promptID) if fp.InjectDiagnostics && isAnthropicUpstreamBase(baseURL) { body, diagnosticsState = injectClaudeDiagnosticsWithState(body, cCtx.Key, cCtx.Sequence, cCtx.PreviousMessageID, promptID) diff --git a/internal/runtime/executor/claude_executor_test.go b/internal/runtime/executor/claude_executor_test.go index 082914b30a1..5bfbe8df696 100644 --- a/internal/runtime/executor/claude_executor_test.go +++ b/internal/runtime/executor/claude_executor_test.go @@ -3922,7 +3922,7 @@ func assertClaudeCodeCurrentDateBlockAt(t *testing.T, block gjson.Result, now ti if got := block.Get("type").String(); got != "text" { t.Fatalf("currentDate block type = %q, want text", got) } - if got, want := block.Get("text").String(), claudeCodeCurrentDateReminder(now); got != want { + if got, want := block.Get("text").String(), claudeCodeCurrentDateReminder(claudeCodeLocalDate(now)); got != want { t.Fatalf("currentDate reminder = %q, want %q", got, want) } if block.Get("cache_control").Exists() { @@ -3972,7 +3972,7 @@ func TestClaudeCodeLocalDateMatchesNativeLocalCalendarAlgorithm(t *testing.T) { t.Fatalf("GMT-12 local date = %q, want 2026-07-31", got) } wantReminder := "\nAs you answer the user's questions, you can use the following context:\n# currentDate\nToday's date is 2026-08-01.\n\n IMPORTANT: this context may or may not be relevant to your tasks. You should not respond to this context unless it is highly relevant to your task.\n\n\n" - if got := claudeCodeCurrentDateReminder(instant.In(kiritimati)); got != wantReminder { + if got := claudeCodeCurrentDateReminder(claudeCodeLocalDate(instant.In(kiritimati))); got != wantReminder { t.Fatalf("currentDate reminder = %q, want exact native text %q", got, wantReminder) } } @@ -4001,11 +4001,11 @@ func TestInjectClaudeCodeCurrentDateIsIdempotentAndAlignsFirstUserCache(t *testi fixed := time.Date(2026, time.August, 1, 9, 0, 0, 0, time.FixedZone("UTC+8", 8*60*60)) payload := []byte(`{"messages":[{"role":"user","content":[{"type":"text","text":"hello","cache_control":{"type":"ephemeral","ttl":"1h"}}]}]}`) - first := injectClaudeCodeCurrentDate(payload, fixed) + first := injectClaudeCodeCurrentDate(payload, claudeCodeLocalDate(fixed)) if !bytes.Contains(first, []byte(``)) || bytes.Contains(first, []byte(`\u003csystem-reminder`)) { t.Fatalf("currentDate angle brackets must match JSON.stringify bytes: %s", first) } - second := injectClaudeCodeCurrentDate(first, fixed) + second := injectClaudeCodeCurrentDate(first, claudeCodeLocalDate(fixed)) if !bytes.Equal(first, second) { t.Fatalf("currentDate injection is not idempotent:\nfirst: %s\nsecond: %s", first, second) } @@ -4013,7 +4013,7 @@ func TestInjectClaudeCodeCurrentDateIsIdempotentAndAlignsFirstUserCache(t *testi if len(content) != 2 { t.Fatalf("first user content has %d blocks, want 2: %s", len(content), first) } - if got := content[0].Get("text").String(); got != claudeCodeCurrentDateReminder(fixed) { + if got := content[0].Get("text").String(); got != claudeCodeCurrentDateReminder(claudeCodeLocalDate(fixed)) { t.Fatalf("currentDate text = %q, want exact native reminder", got) } if content[0].Get("cache_control").Exists() { @@ -4024,11 +4024,11 @@ func TestInjectClaudeCodeCurrentDateIsIdempotentAndAlignsFirstUserCache(t *testi func TestInjectClaudeCodeCurrentDateMovesExistingCopyToFirstBlock(t *testing.T) { fixed := time.Date(2026, time.August, 1, 9, 0, 0, 0, time.FixedZone("UTC+8", 8*60*60)) - dateBlock := buildTextBlock(claudeCodeCurrentDateReminder(fixed), nil) + dateBlock := buildTextBlock(claudeCodeCurrentDateReminder(claudeCodeLocalDate(fixed)), nil) payload := []byte(`{"messages":[{"role":"user","content":[` + `{"type":"text","text":"hello"},` + dateBlock + `]}]}`) - out := injectClaudeCodeCurrentDate(payload, fixed) + out := injectClaudeCodeCurrentDate(payload, claudeCodeLocalDate(fixed)) content := gjson.GetBytes(out, "messages.0.content").Array() if len(content) != 2 { t.Fatalf("content has %d blocks, want one currentDate and user text: %s", len(content), out) @@ -4044,7 +4044,7 @@ func TestInjectClaudeCodeCurrentDatePrecedesExistingReminder(t *testing.T) { buildTextBlock(reminder, nil) + `,` + `{"type":"text","text":"continue","cache_control":{"type":"ephemeral","ttl":"1h"}}]}]}`) - out := injectClaudeCodeCurrentDate(payload, fixed) + out := injectClaudeCodeCurrentDate(payload, claudeCodeLocalDate(fixed)) content := gjson.GetBytes(out, "messages.0.content").Array() if len(content) != 3 { t.Fatalf("content has %d blocks, want currentDate, reminder, and user text: %s", len(content), out) @@ -4064,8 +4064,8 @@ func TestInjectClaudeCodeCurrentDateFollowsLeadingToolResults(t *testing.T) { `{"type":"tool_result","tool_use_id":"toolu_1","content":"ok"},` + `{"type":"text","text":"continue"}]}]}`) - first := injectClaudeCodeCurrentDate(payload, fixed) - second := injectClaudeCodeCurrentDate(first, fixed) + first := injectClaudeCodeCurrentDate(payload, claudeCodeLocalDate(fixed)) + second := injectClaudeCodeCurrentDate(first, claudeCodeLocalDate(fixed)) if !bytes.Equal(first, second) { t.Fatalf("currentDate injection is not idempotent:\nfirst: %s\nsecond: %s", first, second) } @@ -4094,7 +4094,7 @@ func TestInjectClaudeCodeCurrentDateFollowsAllLeadingToolResults(t *testing.T) { `{"type":"tool_result","tool_use_id":"toolu_1","content":"ok"},` + `{"type":"tool_result","tool_use_id":"toolu_2","content":"ok"}]}]}`) - out := injectClaudeCodeCurrentDate(payload, fixed) + out := injectClaudeCodeCurrentDate(payload, claudeCodeLocalDate(fixed)) content := gjson.GetBytes(out, "messages.1.content").Array() if len(content) != 3 { t.Fatalf("content has %d blocks, want two tool_results and currentDate: %s", len(content), out) diff --git a/internal/runtime/executor/helps/claude_diagnostics.go b/internal/runtime/executor/helps/claude_diagnostics.go index 8a2c62b23d3..3c83b9733fb 100644 --- a/internal/runtime/executor/helps/claude_diagnostics.go +++ b/internal/runtime/executor/helps/claude_diagnostics.go @@ -63,7 +63,11 @@ type ClaudeContinuityContext struct { PreviousMessageID string PreviousRequestID string PromptID string - Initialized bool + // PinnedDate is the calendar date this session was first seen on. The + // cloaked currentDate reminder reuses it so the reminder text stays + // byte-stable within a session even when the local date flips mid-session. + PinnedDate string + Initialized bool } // WithClaudeSessionID attaches a known Claude session ID to ctx. @@ -108,6 +112,7 @@ type claudeDiagnosticsEntry struct { previousMessageID string previousRequestID string promptID string + pinnedDate string minimumSequence uint64 committedSequence uint64 lastAccess uint64 @@ -192,6 +197,34 @@ func BeginClaudeContinuity(credentialIdentity, sessionID string, isNewPromptTurn return key, sequence, entry.previousMessageID, entry.previousRequestID, activePromptID } +// PinClaudeSessionDate returns the calendar date pinned for this continuity +// session, recording date on the first call of a session and returning the +// pinned value on later calls. This keeps the cloaked currentDate reminder +// byte-stable within a session so a local-midnight flip cannot invalidate the +// prompt-cache prefix. TTL expiry resets the entry, which re-anchors the next +// request of the same session to the then-current date. An unknown key (for +// example after a process restart) returns date unchanged, matching the +// per-request behaviour. +func PinClaudeSessionDate(key, date string) string { + key = strings.TrimSpace(key) + date = strings.TrimSpace(date) + if key == "" || date == "" { + return date + } + claudeDiagnosticsState.Lock() + defer claudeDiagnosticsState.Unlock() + entry, ok := claudeDiagnosticsState.entries[key] + if !ok { + return date + } + if entry.pinnedDate == "" { + entry.pinnedDate = date + claudeDiagnosticsState.entries[key] = entry + return date + } + return entry.pinnedDate +} + // BeginClaudeDiagnostics starts one request generation for a stable credential // identity and Claude conversation. It returns the last successfully completed // upstream message ID, if any. Only a SHA-256 digest of the credential identity diff --git a/internal/runtime/executor/helps/claude_diagnostics_test.go b/internal/runtime/executor/helps/claude_diagnostics_test.go index 3be9be6351a..5b425f1e326 100644 --- a/internal/runtime/executor/helps/claude_diagnostics_test.go +++ b/internal/runtime/executor/helps/claude_diagnostics_test.go @@ -441,3 +441,35 @@ func TestClaudeSubagentRequests1h(t *testing.T) { t.Fatal("ClaudeSubagentRequests1h() = false, want true when header has extended-cache-ttl beta") } } + +func TestPinClaudeSessionDateAnchorsFirstRequestAndReanchorsAfterTTL(t *testing.T) { + resetClaudeDiagnosticsForTest() + defer resetClaudeDiagnosticsForTest() + + key, _, _ := BeginClaudeDiagnostics("credential", "session") + if got := PinClaudeSessionDate(key, "2026-08-01"); got != "2026-08-01" { + t.Fatalf("first pin = %q, want 2026-08-01", got) + } + // Later requests of the same session keep the anchor even when the + // candidate date has flipped past local midnight. + if got := PinClaudeSessionDate(key, "2026-08-02"); got != "2026-08-01" { + t.Fatalf("second pin = %q, want anchored 2026-08-01", got) + } + + // TTL expiry resets the entry, so the session re-anchors to the current date. + claudeDiagnosticsState.Lock() + entry := claudeDiagnosticsState.entries[key] + entry.expiresAt = time.Now().Add(-time.Second) + claudeDiagnosticsState.entries[key] = entry + claudeDiagnosticsState.Unlock() + BeginClaudeDiagnostics("credential", "session") + if got := PinClaudeSessionDate(key, "2026-08-02"); got != "2026-08-02" { + t.Fatalf("post-TTL pin = %q, want re-anchored 2026-08-02", got) + } + + // Unknown keys (no continuity entry) fall back to the candidate date, + // preserving the pre-pinning per-request behaviour. + if got := PinClaudeSessionDate("unknown-key", "2026-08-03"); got != "2026-08-03" { + t.Fatalf("unknown key pin = %q, want candidate 2026-08-03", got) + } +} From 0fb50a18c3eb918420ea2fa41dc7d49b27bfef9c Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Sat, 3 Oct 2026 02:32:15 +0800 Subject: [PATCH 006/142] feat(management): inject auth indexes into v8 api-keys config - Synthesize and populate live `auth_index` attributes into V8 `api-keys` responses - Strip transient `auth_index` and `auth-index` fields from incoming update payloads and root nodes before persistence - Ensure `auth_index` keys are omitted during V8 config transformations Closes: #6287 --- .../handlers/management/config_auth_index.go | 496 ++++++- internal/api/handlers/management/config_v8.go | 3 + .../management/config_v8_auth_index_test.go | 1280 +++++++++++++++++ internal/config/config_v8.go | 12 +- 4 files changed, 1783 insertions(+), 8 deletions(-) create mode 100644 internal/api/handlers/management/config_v8_auth_index_test.go diff --git a/internal/api/handlers/management/config_auth_index.go b/internal/api/handlers/management/config_auth_index.go index d243d83cd50..9d38363e25b 100644 --- a/internal/api/handlers/management/config_auth_index.go +++ b/internal/api/handlers/management/config_auth_index.go @@ -2,10 +2,14 @@ package management import ( "fmt" + "strconv" "strings" + "time" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" "github.com/router-for-me/CLIProxyAPI/v8/internal/watcher/synthesizer" + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + "gopkg.in/yaml.v3" ) type geminiKeyWithAuthIndex struct { @@ -59,14 +63,8 @@ type openAICompatibilityWithAuthIndex struct { AuthIndex string `json:"auth-index,omitempty"` } -func (h *Handler) liveAuthIndexByID() map[string]string { +func liveAuthIndexFromManager(manager *coreauth.Manager) map[string]string { out := map[string]string{} - if h == nil { - return out - } - h.mu.Lock() - manager := h.authManager - h.mu.Unlock() if manager == nil { return out } @@ -91,6 +89,490 @@ func (h *Handler) liveAuthIndexByID() map[string]string { return out } +func (h *Handler) liveAuthIndexByID() map[string]string { + if h == nil { + return map[string]string{} + } + h.mu.Lock() + manager := h.authManager + h.mu.Unlock() + return liveAuthIndexFromManager(manager) +} + +func yamlMapScalar(node *yaml.Node, key string) string { + if node == nil || node.Kind != yaml.MappingNode { + return "" + } + for i := 0; i+1 < len(node.Content); i += 2 { + if node.Content[i].Value == key { + return strings.TrimSpace(node.Content[i+1].Value) + } + } + return "" +} + +func setMapScalar(mapping *yaml.Node, key, value string) { + if mapping == nil || mapping.Kind != yaml.MappingNode { + return + } + for i := 0; i+1 < len(mapping.Content); i += 2 { + if mapping.Content[i].Value == key { + mapping.Content[i+1].Value = value + mapping.Content[i+1].Tag = "!!str" + mapping.Content[i+1].Kind = yaml.ScalarNode + return + } + } + mapping.Content = append(mapping.Content, + &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: key}, + &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: value}, + ) +} + +func deleteMapKey(mapping *yaml.Node, key string) bool { + if mapping == nil || mapping.Kind != yaml.MappingNode { + return false + } + for i := 0; i+1 < len(mapping.Content); i += 2 { + if mapping.Content[i].Value == key { + mapping.Content = append(mapping.Content[:i], mapping.Content[i+2:]...) + return true + } + } + return false +} + +func stripAPIKeysAuthIndexesFromGroup(group *yaml.Node) { + if group == nil || group.Kind != yaml.MappingNode { + return + } + deleteMapKey(group, "auth_index") + deleteMapKey(group, "auth-index") + keysNode := configV8Node(group, []string{"keys"}) + if keysNode != nil && keysNode.Kind == yaml.SequenceNode { + for _, keyNode := range keysNode.Content { + if keyNode != nil && keyNode.Kind == yaml.MappingNode { + deleteMapKey(keyNode, "auth_index") + deleteMapKey(keyNode, "auth-index") + } + } + } +} + +func stripAPIKeysAuthIndexesFromGroups(groupsNode *yaml.Node) { + if groupsNode == nil { + return + } + if groupsNode.Kind == yaml.SequenceNode { + for _, group := range groupsNode.Content { + stripAPIKeysAuthIndexesFromGroup(group) + } + } else if groupsNode.Kind == yaml.MappingNode { + stripAPIKeysAuthIndexesFromGroup(groupsNode) + } +} + +func stripAPIKeysAuthIndexesFromProvidersMap(apiKeysNode *yaml.Node) { + if apiKeysNode == nil || apiKeysNode.Kind != yaml.MappingNode { + return + } + for i := 0; i+1 < len(apiKeysNode.Content); i += 2 { + stripAPIKeysAuthIndexesFromGroups(apiKeysNode.Content[i+1]) + } +} + +func stripAPIKeysAuthIndexesFromRoot(root *yaml.Node) { + if root == nil || root.Kind != yaml.MappingNode { + return + } + apiKeysNode := configV8Node(root, []string{"api-keys"}) + if apiKeysNode != nil { + stripAPIKeysAuthIndexesFromProvidersMap(apiKeysNode) + } +} + +func stripAPIKeysAuthIndexesFromUpdate(parts []string, update *yaml.Node) { + if update == nil || len(update.Content) == 0 { + return + } + node := update.Content[0] + if len(parts) == 0 { + stripAPIKeysAuthIndexesFromRoot(node) + return + } + if parts[0] != "api-keys" { + return + } + if len(parts) == 1 { + stripAPIKeysAuthIndexesFromProvidersMap(node) + return + } + stripAPIKeysAuthIndexesFromGroups(node) +} + +func yamlMapScalarPresent(node *yaml.Node, key string) (string, bool) { + if node == nil || node.Kind != yaml.MappingNode { + return "", false + } + for i := 0; i+1 < len(node.Content); i += 2 { + if node.Content[i].Value == key { + if node.Content[i+1].Tag == "!!null" { + return "", false + } + return strings.TrimSpace(node.Content[i+1].Value), true + } + } + return "", false +} + +func yamlMapHeadersPresent(node *yaml.Node, key string) (map[string]string, bool) { + if node == nil || node.Kind != yaml.MappingNode { + return nil, false + } + for i := 0; i+1 < len(node.Content); i += 2 { + if node.Content[i].Value == key { + if node.Content[i+1].Tag == "!!null" { + return nil, false + } + var h map[string]string + if errDecode := node.Content[i+1].Decode(&h); errDecode == nil { + return h, true + } + return nil, false + } + } + return nil, false +} + +func resolveInheritedScalar(keyNode, groupNode *yaml.Node, field string) string { + if val, ok := yamlMapScalarPresent(keyNode, field); ok { + return val + } + if val, ok := yamlMapScalarPresent(groupNode, field); ok { + return val + } + return "" +} + +func resolveInheritedHeaders(keyNode, groupNode *yaml.Node, field string) map[string]string { + if h, ok := yamlMapHeadersPresent(keyNode, field); ok { + return h + } + if h, ok := yamlMapHeadersPresent(groupNode, field); ok { + return h + } + return nil +} + +func normalizeModelPrefixHelper(prefix string) string { + trimmed := strings.TrimSpace(prefix) + trimmed = strings.Trim(trimmed, "/") + if trimmed == "" || strings.Contains(trimmed, "/") { + return "" + } + return trimmed +} + +func formatCredentialDedupKey(key, base, proxyURL, prefix string, headers map[string]string) string { + var b strings.Builder + b.WriteString(strings.TrimSpace(key)) + b.WriteByte(0) + b.WriteString(strings.TrimSpace(base)) + b.WriteByte(0) + b.WriteString(strings.TrimSpace(proxyURL)) + b.WriteByte(0) + b.WriteString(normalizeModelPrefixHelper(prefix)) + b.WriteByte(0) + b.WriteString(config.FormatSortedHeaders(config.NormalizeHeaders(headers))) + return b.String() +} + +func (h *Handler) injectV8APIKeyAuthIndexesLocked(root *yaml.Node, data []byte) { + if h == nil || root == nil || root.Kind != yaml.MappingNode { + return + } + apiKeysNode := configV8Node(root, []string{"api-keys"}) + if apiKeysNode == nil || apiKeysNode.Kind != yaml.MappingNode { + return + } + + cfg, errParse := config.ParseConfigBytes(data) + if errParse != nil { + cfg = h.cfg + } + if cfg == nil { + return + } + + synth := synthesizer.NewConfigSynthesizer() + synthCtx := &synthesizer.SynthesisContext{ + Config: cfg, + Now: time.Now(), + IDGenerator: synthesizer.NewStableIDGenerator(), + } + auths, errSynth := synth.Synthesize(synthCtx) + if errSynth != nil { + return + } + + liveIndexByID := liveAuthIndexFromManager(h.authManager) + resolveAuthIndex := func(a *coreauth.Auth) string { + if a == nil { + return "" + } + if idx := strings.TrimSpace(liveIndexByID[a.ID]); idx != "" { + return idx + } + return a.EnsureIndex() + } + + authsByProvider := make(map[string][]*coreauth.Auth) + for _, a := range auths { + if a != nil { + authsByProvider[a.Provider] = append(authsByProvider[a.Provider], a) + } + } + + providerAuthMap := make(map[string]map[string]string) + for _, p := range []string{"gemini", "interactions", "vertex"} { + providerAuthMap[p] = make(map[string]string) + } + + for _, a := range authsByProvider["gemini"] { + if a == nil || a.Attributes == nil { + continue + } + idx, errConv := strconv.Atoi(a.Attributes["config_index"]) + if errConv != nil || idx < 0 || idx >= len(cfg.GeminiKey) { + continue + } + e := cfg.GeminiKey[idx] + key := formatCredentialDedupKey(e.APIKey, e.BaseURL, e.ProxyURL, e.Prefix, e.Headers) + providerAuthMap["gemini"][key] = resolveAuthIndex(a) + } + for _, a := range authsByProvider["gemini-interactions"] { + if a == nil || a.Attributes == nil { + continue + } + idx, errConv := strconv.Atoi(a.Attributes["config_index"]) + if errConv != nil || idx < 0 || idx >= len(cfg.InteractionsKey) { + continue + } + e := cfg.InteractionsKey[idx] + key := formatCredentialDedupKey(e.APIKey, e.BaseURL, e.ProxyURL, e.Prefix, e.Headers) + providerAuthMap["interactions"][key] = resolveAuthIndex(a) + } + for _, a := range authsByProvider["vertex"] { + if a == nil || a.Attributes == nil { + continue + } + idx, errConv := strconv.Atoi(a.Attributes["config_index"]) + if errConv != nil || idx < 0 || idx >= len(cfg.VertexCompatAPIKey) { + continue + } + e := cfg.VertexCompatAPIKey[idx] + key := strings.TrimSpace(e.APIKey) + "|" + strings.TrimSpace(e.BaseURL) + providerAuthMap["vertex"][key] = resolveAuthIndex(a) + } + + authByConfigIndex := make(map[string]map[string]*coreauth.Auth) + for _, p := range []string{"codex", "claude", "xai", "meta"} { + authByConfigIndex[p] = make(map[string]*coreauth.Auth) + for _, a := range authsByProvider[p] { + if a != nil && a.Attributes != nil { + authByConfigIndex[p][a.Attributes["config_index"]] = a + } + } + } + + for i := 0; i+1 < len(apiKeysNode.Content); i += 2 { + providerName := strings.TrimSpace(apiKeysNode.Content[i].Value) + groupsNode := apiKeysNode.Content[i+1] + if groupsNode == nil || groupsNode.Kind != yaml.SequenceNode { + continue + } + + if providerName == "openai-compatibility" { + validGroupIdx := 0 + for _, group := range groupsNode.Content { + if group == nil || group.Kind != yaml.MappingNode { + continue + } + groupBase := strings.TrimSpace(yamlMapScalar(group, "base-url")) + if groupBase == "" { + continue + } + targetGroupIdxStr := strconv.Itoa(validGroupIdx) + validGroupIdx++ + + isOpenAICompatAuth := func(a *coreauth.Auth) bool { + if a == nil || a.Attributes == nil { + return false + } + if a.Attributes["config_index"] != targetGroupIdxStr { + return false + } + return a.Provider == "openai-compatibility" || strings.HasPrefix(a.Provider, "openai-compatible-") + } + + keysNode := configV8Node(group, []string{"keys"}) + if keysNode == nil || keysNode.Kind != yaml.SequenceNode || len(keysNode.Content) == 0 { + for _, a := range auths { + if isOpenAICompatAuth(a) && a.Attributes["api_key"] == "" { + if idx := resolveAuthIndex(a); idx != "" { + setMapScalar(group, "auth_index", idx) + } + break + } + } + continue + } + + var groupAuths []*coreauth.Auth + for _, a := range auths { + if isOpenAICompatAuth(a) { + groupAuths = append(groupAuths, a) + } + } + + for kIdx, keyNode := range keysNode.Content { + if keyNode == nil || keyNode.Kind != yaml.MappingNode { + continue + } + if kIdx < len(groupAuths) { + if idx := resolveAuthIndex(groupAuths[kIdx]); idx != "" { + setMapScalar(keyNode, "auth_index", idx) + } + } + } + } + continue + } + + if providerName == "claude" { + rawIdx := 0 + for _, group := range groupsNode.Content { + if group == nil || group.Kind != yaml.MappingNode { + continue + } + groupBase := strings.TrimSpace(yamlMapScalar(group, "base-url")) + keysNode := configV8Node(group, []string{"keys"}) + if keysNode == nil || keysNode.Kind != yaml.SequenceNode { + continue + } + for _, keyNode := range keysNode.Content { + if keyNode == nil || keyNode.Kind != yaml.MappingNode { + continue + } + apiKey := strings.TrimSpace(yamlMapScalar(keyNode, "api-key")) + targetIdx := strconv.Itoa(rawIdx) + rawIdx++ + if apiKey == "" && groupBase == "" { + continue + } + if a := authByConfigIndex["claude"][targetIdx]; a != nil { + if idx := resolveAuthIndex(a); idx != "" { + setMapScalar(keyNode, "auth_index", idx) + } + } + } + } + continue + } + + if providerName == "codex" || providerName == "xai" { + validIdx := 0 + for _, group := range groupsNode.Content { + if group == nil || group.Kind != yaml.MappingNode { + continue + } + groupBase := strings.TrimSpace(yamlMapScalar(group, "base-url")) + if groupBase == "" { + continue + } + keysNode := configV8Node(group, []string{"keys"}) + if keysNode == nil || keysNode.Kind != yaml.SequenceNode { + continue + } + for _, keyNode := range keysNode.Content { + if keyNode == nil || keyNode.Kind != yaml.MappingNode { + continue + } + targetIdx := strconv.Itoa(validIdx) + validIdx++ + if a := authByConfigIndex[providerName][targetIdx]; a != nil { + if idx := resolveAuthIndex(a); idx != "" { + setMapScalar(keyNode, "auth_index", idx) + } + } + } + } + continue + } + + if providerName == "meta" { + validIdx := 0 + for _, group := range groupsNode.Content { + if group == nil || group.Kind != yaml.MappingNode { + continue + } + keysNode := configV8Node(group, []string{"keys"}) + if keysNode == nil || keysNode.Kind != yaml.SequenceNode { + continue + } + for _, keyNode := range keysNode.Content { + if keyNode == nil || keyNode.Kind != yaml.MappingNode { + continue + } + apiKey := strings.TrimSpace(yamlMapScalar(keyNode, "api-key")) + if apiKey == "" || strings.HasPrefix(apiKey, "dca:") { + continue + } + targetIdx := strconv.Itoa(validIdx) + validIdx++ + if a := authByConfigIndex["meta"][targetIdx]; a != nil { + if idx := resolveAuthIndex(a); idx != "" { + setMapScalar(keyNode, "auth_index", idx) + } + } + } + } + continue + } + + for _, group := range groupsNode.Content { + if group == nil || group.Kind != yaml.MappingNode { + continue + } + groupBase := strings.TrimSpace(yamlMapScalar(group, "base-url")) + keysNode := configV8Node(group, []string{"keys"}) + if keysNode == nil || keysNode.Kind != yaml.SequenceNode { + continue + } + for _, keyNode := range keysNode.Content { + if keyNode == nil || keyNode.Kind != yaml.MappingNode { + continue + } + apiKey := strings.TrimSpace(yamlMapScalar(keyNode, "api-key")) + if providerName == "vertex" { + if idx, ok := providerAuthMap["vertex"][apiKey+"|"+groupBase]; ok { + setMapScalar(keyNode, "auth_index", idx) + } + continue + } + + proxyURL := resolveInheritedScalar(keyNode, group, "proxy-url") + prefix := resolveInheritedScalar(keyNode, group, "prefix") + headers := resolveInheritedHeaders(keyNode, group, "headers") + dedupKey := formatCredentialDedupKey(apiKey, groupBase, proxyURL, prefix, headers) + if idx, ok := providerAuthMap[providerName][dedupKey]; ok { + setMapScalar(keyNode, "auth_index", idx) + } + } + } + } +} + func (h *Handler) geminiKeysWithAuthIndex() []geminiKeyWithAuthIndex { if h == nil { return nil diff --git a/internal/api/handlers/management/config_v8.go b/internal/api/handlers/management/config_v8.go index 57eb913cbce..7bf13575966 100644 --- a/internal/api/handlers/management/config_v8.go +++ b/internal/api/handlers/management/config_v8.go @@ -52,6 +52,7 @@ func (h *Handler) ConfigV8(c *gin.Context) { deleteConfigV8Path(server, []string{"credential"}) } } + h.injectV8APIKeyAuthIndexesLocked(root, data) } value := configV8Node(root, parts) if value == nil { @@ -97,6 +98,7 @@ func (h *Handler) ConfigV8(c *gin.Context) { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid_body"}) return } + stripAPIKeysAuthIndexesFromUpdate(parts, &update) if len(parts) == 0 && update.Content[0].Kind != yaml.MappingNode { c.JSON(http.StatusBadRequest, gin.H{"error": "config_must_be_object"}) return @@ -155,6 +157,7 @@ func (h *Handler) ConfigV8(c *gin.Context) { return } } + stripAPIKeysAuthIndexesFromRoot(root) data, err = yaml.Marshal(&doc) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid_config", "message": err.Error()}) diff --git a/internal/api/handlers/management/config_v8_auth_index_test.go b/internal/api/handlers/management/config_v8_auth_index_test.go new file mode 100644 index 00000000000..9b42ceb7f31 --- /dev/null +++ b/internal/api/handlers/management/config_v8_auth_index_test.go @@ -0,0 +1,1280 @@ +package management + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/watcher/synthesizer" + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" +) + +func TestConfigV8APIKeysExposeAuthIndex_Issue6287(t *testing.T) { + gin.SetMode(gin.TestMode) + dir := t.TempDir() + path := filepath.Join(dir, "config.yaml") + + rawYAML := `config-version: 8 +port: 8317 +api-keys: + codex: + - name: codex-group + base-url: https://api.openai.invalid + keys: + - api-key: sk-codex-1 + - api-key: sk-codex-2 + claude: + - name: claude-group + base-url: https://api.anthropic.invalid + keys: + - api-key: sk-claude-1 + openai-compatibility: + - name: compat-provider + base-url: https://api.compat.invalid + keys: + - api-key: sk-compat-1 + - name: keyless-provider + base-url: https://api.keyless.invalid + keys: [] +` + if err := os.WriteFile(path, []byte(rawYAML), 0600); err != nil { + t.Fatal(err) + } + + cfg, err := config.LoadConfig(path) + if err != nil { + t.Fatal(err) + } + + synth := synthesizer.NewConfigSynthesizer() + synthCtx := &synthesizer.SynthesisContext{ + Config: cfg, + Now: time.Now(), + IDGenerator: synthesizer.NewStableIDGenerator(), + } + auths, err := synth.Synthesize(synthCtx) + if err != nil { + t.Fatalf("synthesize auths: %v", err) + } + + manager := coreauth.NewManager(nil, nil, nil) + expectedIndexes := make(map[string]string) + for _, a := range auths { + if _, errReg := manager.Register(context.Background(), a); errReg != nil { + t.Fatalf("register auth: %v", errReg) + } + apiKey := a.Attributes["api_key"] + idx := a.EnsureIndex() + if idx == "" { + t.Fatalf("auth %s has empty EnsureIndex", a.ID) + } + name := a.Attributes["compat_name"] + if name == "" { + name = a.Provider + } + if apiKey != "" { + expectedIndexes[name+":"+apiKey] = idx + } else { + expectedIndexes[name+":keyless"] = idx + } + } + + h := &Handler{cfg: cfg, configFilePath: path, authManager: manager} + + router := gin.New() + router.GET("/v8/management/config", h.ConfigV8) + router.GET("/v8/management/config.yaml", h.ConfigV8) + router.GET("/v8/management/config/*path", h.ConfigV8) + router.PUT("/v8/management/config/*path", h.ConfigV8) + router.PATCH("/v8/management/config", h.ConfigV8) + + // 1. GET /v8/management/config/api-keys/codex + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/v8/management/config/api-keys/codex", nil) + router.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("GET /v8/management/config/api-keys/codex: status=%d body=%s", rec.Code, rec.Body.String()) + } + + var codexGroups []map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &codexGroups); err != nil { + t.Fatalf("decode codex groups: %v", err) + } + if len(codexGroups) != 1 { + t.Fatalf("expected 1 codex group, got %d", len(codexGroups)) + } + keys, ok := codexGroups[0]["keys"].([]any) + if !ok || len(keys) != 2 { + t.Fatalf("expected 2 keys in codex group, got %#v", codexGroups[0]["keys"]) + } + for i, k := range keys { + keyMap, ok := k.(map[string]any) + if !ok { + t.Fatalf("key %d is not map: %#v", i, k) + } + apiKey, _ := keyMap["api-key"].(string) + authIndex, _ := keyMap["auth_index"].(string) + wantIndex := expectedIndexes["codex:"+apiKey] + if wantIndex == "" { + t.Fatalf("missing expected index for codex key %s", apiKey) + } + if authIndex != wantIndex { + t.Fatalf("codex key %s: auth_index = %q, want %q", apiKey, authIndex, wantIndex) + } + } + + // 2. GET /v8/management/config/api-keys + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/v8/management/config/api-keys", nil) + router.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("GET /v8/management/config/api-keys: status=%d body=%s", rec.Code, rec.Body.String()) + } + var allAPIKeys map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &allAPIKeys); err != nil { + t.Fatalf("decode all api-keys: %v", err) + } + claudeVal, ok := allAPIKeys["claude"].([]any) + if !ok || len(claudeVal) != 1 { + t.Fatalf("expected claude in api-keys, got %#v", allAPIKeys["claude"]) + } + claudeGroup := claudeVal[0].(map[string]any) + claudeKeys := claudeGroup["keys"].([]any) + claudeKeyMap := claudeKeys[0].(map[string]any) + if got := claudeKeyMap["auth_index"]; got != expectedIndexes["claude:sk-claude-1"] { + t.Fatalf("claude key auth_index = %q, want %q", got, expectedIndexes["claude:sk-claude-1"]) + } + + // Verify keyless openai-compatibility group has group-level auth_index + compatVal, ok := allAPIKeys["openai-compatibility"].([]any) + if !ok || len(compatVal) != 2 { + t.Fatalf("expected 2 openai-compatibility groups, got %#v", allAPIKeys["openai-compatibility"]) + } + keylessGroup := compatVal[1].(map[string]any) + if got := keylessGroup["auth_index"]; got != expectedIndexes["keyless-provider:keyless"] { + t.Fatalf("keyless group auth_index = %q, want %q", got, expectedIndexes["keyless-provider:keyless"]) + } + + // 3. GET /v8/management/config (root) + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/v8/management/config", nil) + router.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("GET /v8/management/config: status=%d body=%s", rec.Code, rec.Body.String()) + } + var fullConfig map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &fullConfig); err != nil { + t.Fatalf("decode full config: %v", err) + } + configAPIKeys, ok := fullConfig["api-keys"].(map[string]any) + if !ok { + t.Fatalf("full config missing api-keys object: %#v", fullConfig["api-keys"]) + } + codexFromRoot := configAPIKeys["codex"].([]any)[0].(map[string]any)["keys"].([]any)[0].(map[string]any) + if got := codexFromRoot["auth_index"]; got != expectedIndexes["codex:sk-codex-1"] { + t.Fatalf("root config codex auth_index = %q, want %q", got, expectedIndexes["codex:sk-codex-1"]) + } + + // 4. GET /v8/management/config.yaml should not contain auth_index + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/v8/management/config.yaml", nil) + router.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("GET /v8/management/config.yaml: status=%d body=%s", rec.Code, rec.Body.String()) + } + if strings.Contains(rec.Body.String(), "auth_index") { + t.Fatal("config.yaml output must not contain auth_index") + } + + // 5. PUT round-trip with payload containing auth_index + codexJSON, _ := json.Marshal(codexGroups) + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodPut, "/v8/management/config/api-keys/codex", strings.NewReader(string(codexJSON))) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("PUT /v8/management/config/api-keys/codex with auth_index: status=%d body=%s", rec.Code, rec.Body.String()) + } + + // Verify disk config does not have auth_index + saved, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(saved), "auth_index") { + t.Fatal("saved config.yaml must not contain auth_index") + } + + // 6. PATCH on root containing auth_index in api-keys + patchBody := `{"api-keys":{"claude":[{"name":"claude-group","base-url":"https://api.anthropic.invalid","keys":[{"api-key":"sk-claude-1","auth_index":"arbitrary-ignore"}]}]}}` + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodPatch, "/v8/management/config", strings.NewReader(patchBody)) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("PATCH /v8/management/config with auth_index: status=%d body=%s", rec.Code, rec.Body.String()) + } + + saved, err = os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(saved), "auth_index") { + t.Fatal("saved config.yaml after PATCH must not contain auth_index") + } + + // 7. Fallback when authManager is nil + hNoManager := &Handler{cfg: cfg, configFilePath: path, authManager: nil} + routerNoManager := gin.New() + routerNoManager.GET("/v8/management/config/*path", hNoManager.ConfigV8) + + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/v8/management/config/api-keys/codex", nil) + routerNoManager.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("GET with nil authManager: status=%d body=%s", rec.Code, rec.Body.String()) + } + var noManagerGroups []map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &noManagerGroups); err != nil { + t.Fatalf("decode codex groups: %v", err) + } + key0 := noManagerGroups[0]["keys"].([]any)[0].(map[string]any) + if got := key0["auth_index"]; got != expectedIndexes["codex:sk-codex-1"] { + t.Fatalf("fallback auth_index = %q, want %q", got, expectedIndexes["codex:sk-codex-1"]) + } + + // 8. Meta provider with omitted base-url defaults to https://api.meta.ai/v1 matching runtime + metaYAML := `config-version: 8 +port: 8317 +api-keys: + meta: + - name: meta-group + keys: + - api-key: sk-meta-default-base +` + metaPath := filepath.Join(dir, "meta-config.yaml") + if errWrite := os.WriteFile(metaPath, []byte(metaYAML), 0600); errWrite != nil { + t.Fatal(errWrite) + } + metaCfg, errLoad := config.LoadConfig(metaPath) + if errLoad != nil { + t.Fatal(errLoad) + } + metaAuths, errMetaSynth := synth.Synthesize(&synthesizer.SynthesisContext{ + Config: metaCfg, + Now: time.Now(), + IDGenerator: synthesizer.NewStableIDGenerator(), + }) + if errMetaSynth != nil || len(metaAuths) != 1 { + t.Fatalf("synthesize meta auth: %v, len=%d", errMetaSynth, len(metaAuths)) + } + metaManager := coreauth.NewManager(nil, nil, nil) + if _, errReg := metaManager.Register(context.Background(), metaAuths[0]); errReg != nil { + t.Fatal(errReg) + } + expectedMetaIndex := metaAuths[0].EnsureIndex() + + hMeta := &Handler{cfg: metaCfg, configFilePath: metaPath, authManager: metaManager} + routerMeta := gin.New() + routerMeta.GET("/v8/management/config/*path", hMeta.ConfigV8) + + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/v8/management/config/api-keys/meta", nil) + routerMeta.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("GET /v8/management/config/api-keys/meta: status=%d body=%s", rec.Code, rec.Body.String()) + } + var metaGroups []map[string]any + if errDecode := json.Unmarshal(rec.Body.Bytes(), &metaGroups); errDecode != nil { + t.Fatalf("decode meta groups: %v", errDecode) + } + metaKey0 := metaGroups[0]["keys"].([]any)[0].(map[string]any) + if got := metaKey0["auth_index"]; got != expectedMetaIndex { + t.Fatalf("meta key auth_index = %q, want %q", got, expectedMetaIndex) + } + + // 9. Explicit empty proxy-url on key overrides group proxy-url + proxyYAML := `config-version: 8 +port: 8317 +api-keys: + vertex: + - name: vertex-group + base-url: https://api.vertex.invalid + proxy-url: http://proxy.group.invalid:8080 + keys: + - api-key: sk-vertex-inherited + - api-key: sk-vertex-explicit-empty + proxy-url: "" +` + proxyPath := filepath.Join(dir, "proxy-config.yaml") + if errWrite := os.WriteFile(proxyPath, []byte(proxyYAML), 0600); errWrite != nil { + t.Fatal(errWrite) + } + proxyCfg, errLoadProxy := config.LoadConfig(proxyPath) + if errLoadProxy != nil { + t.Fatal(errLoadProxy) + } + proxyAuths, errProxySynth := synth.Synthesize(&synthesizer.SynthesisContext{ + Config: proxyCfg, + Now: time.Now(), + IDGenerator: synthesizer.NewStableIDGenerator(), + }) + if errProxySynth != nil || len(proxyAuths) != 2 { + t.Fatalf("synthesize vertex auths: %v, len=%d", errProxySynth, len(proxyAuths)) + } + proxyManager := coreauth.NewManager(nil, nil, nil) + for _, a := range proxyAuths { + if _, errReg := proxyManager.Register(context.Background(), a); errReg != nil { + t.Fatal(errReg) + } + } + wantInheritedIndex := proxyAuths[0].EnsureIndex() + wantExplicitEmptyIndex := proxyAuths[1].EnsureIndex() + + hProxy := &Handler{cfg: proxyCfg, configFilePath: proxyPath, authManager: proxyManager} + routerProxy := gin.New() + routerProxy.GET("/v8/management/config/*path", hProxy.ConfigV8) + + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/v8/management/config/api-keys/vertex", nil) + routerProxy.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("GET /v8/management/config/api-keys/vertex: status=%d body=%s", rec.Code, rec.Body.String()) + } + var vertexGroups []map[string]any + if errDecode := json.Unmarshal(rec.Body.Bytes(), &vertexGroups); errDecode != nil { + t.Fatalf("decode vertex groups: %v", errDecode) + } + vertexKeys := vertexGroups[0]["keys"].([]any) + if got := vertexKeys[0].(map[string]any)["auth_index"]; got != wantInheritedIndex { + t.Fatalf("vertex key 0 auth_index = %q, want %q", got, wantInheritedIndex) + } + if got := vertexKeys[1].(map[string]any)["auth_index"]; got != wantExplicitEmptyIndex { + t.Fatalf("vertex key 1 auth_index = %q, want %q", got, wantExplicitEmptyIndex) + } + + // 10. Plugin options and headers retaining auth_index outside of credential level + pluginYAML := `config-version: 8 +port: 8317 +plugins: + configs: + custom-plugin: + enabled: true + options: + auth_index: keep-this-plugin-field +api-keys: + codex: + - name: codex-group + base-url: https://api.openai.invalid + headers: + auth_index: keep-group-header + keys: + - api-key: sk-codex-headers + headers: + auth_index: keep-key-header +` + pluginPath := filepath.Join(dir, "plugin-config.yaml") + if errWrite := os.WriteFile(pluginPath, []byte(pluginYAML), 0600); errWrite != nil { + t.Fatal(errWrite) + } + pluginCfg, errLoadPlugin := config.LoadConfig(pluginPath) + if errLoadPlugin != nil { + t.Fatal(errLoadPlugin) + } + hPlugin := &Handler{cfg: pluginCfg, configFilePath: pluginPath} + routerPlugin := gin.New() + routerPlugin.GET("/v8/management/config/*path", hPlugin.ConfigV8) + routerPlugin.PUT("/v8/management/config/*path", hPlugin.ConfigV8) + + // Fetch codex keys with auth_index injected + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/v8/management/config/api-keys/codex", nil) + routerPlugin.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("GET codex with plugin: status=%d body=%s", rec.Code, rec.Body.String()) + } + var pluginCodexGroups []map[string]any + if errDecode := json.Unmarshal(rec.Body.Bytes(), &pluginCodexGroups); errDecode != nil { + t.Fatal(errDecode) + } + + // PUT codex keys back (round-trip with auth_index) + codexBytes, _ := json.Marshal(pluginCodexGroups) + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodPut, "/v8/management/config/api-keys/codex", strings.NewReader(string(codexBytes))) + req.Header.Set("Content-Type", "application/json") + routerPlugin.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("PUT codex: status=%d body=%s", rec.Code, rec.Body.String()) + } + + // Read saved config on disk: plugin option auth_index and headers auth_index MUST be intact! + savedPluginData, errRead := os.ReadFile(pluginPath) + if errRead != nil { + t.Fatal(errRead) + } + savedPluginStr := string(savedPluginData) + if !strings.Contains(savedPluginStr, "keep-this-plugin-field") { + t.Fatalf("plugin option auth_index was stripped! saved config:\n%s", savedPluginStr) + } + if !strings.Contains(savedPluginStr, "keep-group-header") { + t.Fatalf("group header auth_index was stripped! saved config:\n%s", savedPluginStr) + } + if !strings.Contains(savedPluginStr, "keep-key-header") { + t.Fatalf("key header auth_index was stripped! saved config:\n%s", savedPluginStr) + } + + // 11. Duplicate Vertex keys in YAML map to the same deduplicated runtime auth_index + dupVertexYAML := `config-version: 8 +port: 8317 +api-keys: + vertex: + - name: vertex-group + base-url: https://api.vertex.invalid + keys: + - api-key: sk-vertex-shared + - api-key: sk-vertex-shared +` + dupVertexPath := filepath.Join(dir, "dup-vertex-config.yaml") + if errWrite := os.WriteFile(dupVertexPath, []byte(dupVertexYAML), 0600); errWrite != nil { + t.Fatal(errWrite) + } + dupVertexCfg, errLoadDup := config.LoadConfig(dupVertexPath) + if errLoadDup != nil { + t.Fatal(errLoadDup) + } + dupAuths, errDupSynth := synth.Synthesize(&synthesizer.SynthesisContext{ + Config: dupVertexCfg, + Now: time.Now(), + IDGenerator: synthesizer.NewStableIDGenerator(), + }) + // Runtime deduplicates identical vertex keys to 1 credential! + if errDupSynth != nil || len(dupAuths) != 1 { + t.Fatalf("synthesize dup vertex auth: %v, len=%d", errDupSynth, len(dupAuths)) + } + dupManager := coreauth.NewManager(nil, nil, nil) + if _, errReg := dupManager.Register(context.Background(), dupAuths[0]); errReg != nil { + t.Fatal(errReg) + } + expectedDupVertexIndex := dupAuths[0].EnsureIndex() + + hDup := &Handler{cfg: dupVertexCfg, configFilePath: dupVertexPath, authManager: dupManager} + routerDup := gin.New() + routerDup.GET("/v8/management/config/*path", hDup.ConfigV8) + + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/v8/management/config/api-keys/vertex", nil) + routerDup.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("GET /v8/management/config/api-keys/vertex: status=%d body=%s", rec.Code, rec.Body.String()) + } + var dupVertexGroups []map[string]any + if errDecode := json.Unmarshal(rec.Body.Bytes(), &dupVertexGroups); errDecode != nil { + t.Fatal(errDecode) + } + dupKeys := dupVertexGroups[0]["keys"].([]any) + if len(dupKeys) != 2 { + t.Fatalf("expected 2 keys in YAML response, got %d", len(dupKeys)) + } + if got0 := dupKeys[0].(map[string]any)["auth_index"]; got0 != expectedDupVertexIndex { + t.Fatalf("dup key 0 auth_index = %q, want %q", got0, expectedDupVertexIndex) + } + if got1 := dupKeys[1].(map[string]any)["auth_index"]; got1 != expectedDupVertexIndex { + t.Fatalf("dup key 1 auth_index = %q, want %q", got1, expectedDupVertexIndex) + } + + // 12. Unnormalized prefix (prefix: /team/) matches live credential with normalized prefix + unnormalizedPrefixYAML := `config-version: 8 +port: 8317 +api-keys: + codex: + - name: codex-team + prefix: /team/ + base-url: https://api.openai.invalid + keys: + - api-key: sk-codex-team +` + prefixPath := filepath.Join(dir, "prefix-config.yaml") + if errWrite := os.WriteFile(prefixPath, []byte(unnormalizedPrefixYAML), 0600); errWrite != nil { + t.Fatal(errWrite) + } + prefixCfg, errLoadPrefix := config.LoadConfig(prefixPath) + if errLoadPrefix != nil { + t.Fatal(errLoadPrefix) + } + prefixAuths, errPrefixSynth := synth.Synthesize(&synthesizer.SynthesisContext{ + Config: prefixCfg, + Now: time.Now(), + IDGenerator: synthesizer.NewStableIDGenerator(), + }) + if errPrefixSynth != nil || len(prefixAuths) != 1 { + t.Fatalf("synthesize prefix auth: %v, len=%d", errPrefixSynth, len(prefixAuths)) + } + prefixManager := coreauth.NewManager(nil, nil, nil) + if _, errReg := prefixManager.Register(context.Background(), prefixAuths[0]); errReg != nil { + t.Fatal(errReg) + } + expectedPrefixIndex := prefixAuths[0].EnsureIndex() + + hPrefix := &Handler{cfg: prefixCfg, configFilePath: prefixPath, authManager: prefixManager} + routerPrefix := gin.New() + routerPrefix.GET("/v8/management/config/*path", hPrefix.ConfigV8) + + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/v8/management/config/api-keys/codex", nil) + routerPrefix.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("GET /v8/management/config/api-keys/codex: status=%d body=%s", rec.Code, rec.Body.String()) + } + var prefixGroups []map[string]any + if errDecode := json.Unmarshal(rec.Body.Bytes(), &prefixGroups); errDecode != nil { + t.Fatal(errDecode) + } + prefixKey0 := prefixGroups[0]["keys"].([]any)[0].(map[string]any) + if got := prefixKey0["auth_index"]; got != expectedPrefixIndex { + t.Fatalf("prefix key auth_index = %q, want %q", got, expectedPrefixIndex) + } + + // 13. Gemini with duplicate keys [A, A, B]: both A get A's index, B gets B's index + geminiDupYAML := `config-version: 8 +port: 8317 +api-keys: + gemini: + - name: gemini-group + base-url: https://api.gemini.invalid + keys: + - api-key: sk-gemini-a + - api-key: sk-gemini-a + - api-key: sk-gemini-b +` + geminiPath := filepath.Join(dir, "gemini-dup-config.yaml") + if errWrite := os.WriteFile(geminiPath, []byte(geminiDupYAML), 0600); errWrite != nil { + t.Fatal(errWrite) + } + geminiCfg, errLoadGemini := config.LoadConfig(geminiPath) + if errLoadGemini != nil { + t.Fatal(errLoadGemini) + } + geminiAuths, errGeminiSynth := synth.Synthesize(&synthesizer.SynthesisContext{ + Config: geminiCfg, + Now: time.Now(), + IDGenerator: synthesizer.NewStableIDGenerator(), + }) + // Runtime deduplicates identical gemini keys to 2 credentials: A and B + if errGeminiSynth != nil || len(geminiAuths) != 2 { + t.Fatalf("synthesize gemini dup auth: %v, len=%d", errGeminiSynth, len(geminiAuths)) + } + geminiManager := coreauth.NewManager(nil, nil, nil) + wantGeminiA := "" + wantGeminiB := "" + for _, a := range geminiAuths { + if _, errReg := geminiManager.Register(context.Background(), a); errReg != nil { + t.Fatal(errReg) + } + if a.Attributes["api_key"] == "sk-gemini-a" { + wantGeminiA = a.EnsureIndex() + } else if a.Attributes["api_key"] == "sk-gemini-b" { + wantGeminiB = a.EnsureIndex() + } + } + if wantGeminiA == "" || wantGeminiB == "" || wantGeminiA == wantGeminiB { + t.Fatalf("unexpected gemini auth indexes: A=%q, B=%q", wantGeminiA, wantGeminiB) + } + + hGemini := &Handler{cfg: geminiCfg, configFilePath: geminiPath, authManager: geminiManager} + routerGemini := gin.New() + routerGemini.GET("/v8/management/config/*path", hGemini.ConfigV8) + + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/v8/management/config/api-keys/gemini", nil) + routerGemini.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("GET /v8/management/config/api-keys/gemini: status=%d body=%s", rec.Code, rec.Body.String()) + } + var geminiGroups []map[string]any + if errDecode := json.Unmarshal(rec.Body.Bytes(), &geminiGroups); errDecode != nil { + t.Fatal(errDecode) + } + geminiKeys := geminiGroups[0]["keys"].([]any) + if len(geminiKeys) != 3 { + t.Fatalf("expected 3 keys in gemini response, got %d", len(geminiKeys)) + } + if got0 := geminiKeys[0].(map[string]any)["auth_index"]; got0 != wantGeminiA { + t.Fatalf("gemini key 0 auth_index = %q, want %q", got0, wantGeminiA) + } + if got1 := geminiKeys[1].(map[string]any)["auth_index"]; got1 != wantGeminiA { + t.Fatalf("gemini key 1 auth_index = %q, want %q", got1, wantGeminiA) + } + if got2 := geminiKeys[2].(map[string]any)["auth_index"]; got2 != wantGeminiB { + t.Fatalf("gemini key 2 auth_index = %q, want %q", got2, wantGeminiB) + } + + // 14. OpenAI-compatible with [empty_key, B] and invalid group without base-url + compatMixedYAML := `config-version: 8 +port: 8317 +api-keys: + openai-compatibility: + - name: invalid-group-no-base + keys: + - api-key: sk-invalid + - name: mixed-group + base-url: https://api.mixed.invalid + keys: + - api-key: "" + - api-key: sk-compat-b +` + compatMixedPath := filepath.Join(dir, "compat-mixed-config.yaml") + if errWrite := os.WriteFile(compatMixedPath, []byte(compatMixedYAML), 0600); errWrite != nil { + t.Fatal(errWrite) + } + compatMixedCfg, errLoadMixed := config.LoadConfig(compatMixedPath) + if errLoadMixed != nil { + t.Fatal(errLoadMixed) + } + compatMixedAuths, errMixedSynth := synth.Synthesize(&synthesizer.SynthesisContext{ + Config: compatMixedCfg, + Now: time.Now(), + IDGenerator: synthesizer.NewStableIDGenerator(), + }) + if errMixedSynth != nil || len(compatMixedAuths) != 2 { + t.Fatalf("synthesize compat mixed auths: %v, len=%d", errMixedSynth, len(compatMixedAuths)) + } + mixedManager := coreauth.NewManager(nil, nil, nil) + wantEmptyKeyIndex := "" + wantKeyBIndex := "" + for _, a := range compatMixedAuths { + if _, errReg := mixedManager.Register(context.Background(), a); errReg != nil { + t.Fatal(errReg) + } + if a.Attributes["api_key"] == "" { + wantEmptyKeyIndex = a.EnsureIndex() + } else if a.Attributes["api_key"] == "sk-compat-b" { + wantKeyBIndex = a.EnsureIndex() + } + } + if wantEmptyKeyIndex == "" || wantKeyBIndex == "" || wantEmptyKeyIndex == wantKeyBIndex { + t.Fatalf("unexpected mixed auth indexes: empty=%q, B=%q", wantEmptyKeyIndex, wantKeyBIndex) + } + + hMixed := &Handler{cfg: compatMixedCfg, configFilePath: compatMixedPath, authManager: mixedManager} + routerMixed := gin.New() + routerMixed.GET("/v8/management/config/*path", hMixed.ConfigV8) + + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/v8/management/config/api-keys/openai-compatibility", nil) + routerMixed.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("GET /v8/management/config/api-keys/openai-compatibility: status=%d body=%s", rec.Code, rec.Body.String()) + } + var mixedGroups []map[string]any + if errDecode := json.Unmarshal(rec.Body.Bytes(), &mixedGroups); errDecode != nil { + t.Fatal(errDecode) + } + // Group 0 had no base-url, so its key has no auth_index + invalidKeys := mixedGroups[0]["keys"].([]any) + if gotInvalid := invalidKeys[0].(map[string]any)["auth_index"]; gotInvalid != nil { + t.Fatalf("invalid group key auth_index = %v, want nil", gotInvalid) + } + // Group 1 has [empty_key, B] + validKeys := mixedGroups[1]["keys"].([]any) + if gotEmpty := validKeys[0].(map[string]any)["auth_index"]; gotEmpty != wantEmptyKeyIndex { + t.Fatalf("empty key auth_index = %q, want %q", gotEmpty, wantEmptyKeyIndex) + } + if gotB := validKeys[1].(map[string]any)["auth_index"]; gotB != wantKeyBIndex { + t.Fatalf("key B auth_index = %q, want %q", gotB, wantKeyBIndex) + } + + // 15. Empty API key with valid base-url (Gemini base-url only) produces non-empty auth_index + emptyKeyGeminiYAML := `config-version: 8 +port: 8317 +api-keys: + gemini: + - name: gemini-emulator + base-url: http://emulator.invalid:8080 + keys: + - api-key: "" +` + emptyKeyPath := filepath.Join(dir, "gemini-empty-key.yaml") + if errWrite := os.WriteFile(emptyKeyPath, []byte(emptyKeyGeminiYAML), 0600); errWrite != nil { + t.Fatal(errWrite) + } + emptyKeyCfg, errLoadEmpty := config.LoadConfig(emptyKeyPath) + if errLoadEmpty != nil { + t.Fatal(errLoadEmpty) + } + emptyKeyAuths, errEmptySynth := synth.Synthesize(&synthesizer.SynthesisContext{ + Config: emptyKeyCfg, + Now: time.Now(), + IDGenerator: synthesizer.NewStableIDGenerator(), + }) + if errEmptySynth != nil || len(emptyKeyAuths) != 1 { + t.Fatalf("synthesize empty key auths: %v, len=%d", errEmptySynth, len(emptyKeyAuths)) + } + wantEmulatorIndex := emptyKeyAuths[0].EnsureIndex() + if wantEmulatorIndex == "" { + t.Fatal("empty key auth EnsureIndex must not be empty") + } + + hEmpty := &Handler{cfg: emptyKeyCfg, configFilePath: emptyKeyPath} + routerEmpty := gin.New() + routerEmpty.GET("/v8/management/config/*path", hEmpty.ConfigV8) + + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/v8/management/config/api-keys/gemini", nil) + routerEmpty.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("GET /v8/management/config/api-keys/gemini: status=%d body=%s", rec.Code, rec.Body.String()) + } + var emptyKeyGroups []map[string]any + if errDecode := json.Unmarshal(rec.Body.Bytes(), &emptyKeyGroups); errDecode != nil { + t.Fatal(errDecode) + } + if got := emptyKeyGroups[0]["keys"].([]any)[0].(map[string]any)["auth_index"]; got != wantEmulatorIndex { + t.Fatalf("emulator auth_index = %q, want %q", got, wantEmulatorIndex) + } + + // 16. Multiple OpenAI-compatible empty-key entries with different proxy-url + compatMultiEmptyYAML := `config-version: 8 +port: 8317 +api-keys: + openai-compatibility: + - name: multi-empty-group + base-url: https://api.multi.invalid + keys: + - api-key: "" + proxy-url: http://proxy1.invalid:8080 + - api-key: "" + proxy-url: http://proxy2.invalid:8080 +` + multiEmptyPath := filepath.Join(dir, "compat-multi-empty.yaml") + if errWrite := os.WriteFile(multiEmptyPath, []byte(compatMultiEmptyYAML), 0600); errWrite != nil { + t.Fatal(errWrite) + } + multiEmptyCfg, errLoadMulti := config.LoadConfig(multiEmptyPath) + if errLoadMulti != nil { + t.Fatal(errLoadMulti) + } + multiEmptyAuths, errMultiSynth := synth.Synthesize(&synthesizer.SynthesisContext{ + Config: multiEmptyCfg, + Now: time.Now(), + IDGenerator: synthesizer.NewStableIDGenerator(), + }) + if errMultiSynth != nil || len(multiEmptyAuths) != 2 { + t.Fatalf("synthesize multi empty auths: %v, len=%d", errMultiSynth, len(multiEmptyAuths)) + } + wantMultiIdx1 := multiEmptyAuths[0].EnsureIndex() + wantMultiIdx2 := multiEmptyAuths[1].EnsureIndex() + if wantMultiIdx1 == "" || wantMultiIdx2 == "" || wantMultiIdx1 == wantMultiIdx2 { + t.Fatalf("expected distinct non-empty auth indexes for different proxies: %q vs %q", wantMultiIdx1, wantMultiIdx2) + } + + hMulti := &Handler{cfg: multiEmptyCfg, configFilePath: multiEmptyPath} + routerMulti := gin.New() + routerMulti.GET("/v8/management/config/*path", hMulti.ConfigV8) + + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/v8/management/config/api-keys/openai-compatibility", nil) + routerMulti.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("GET multi empty: status=%d body=%s", rec.Code, rec.Body.String()) + } + var multiGroups []map[string]any + if errDecode := json.Unmarshal(rec.Body.Bytes(), &multiGroups); errDecode != nil { + t.Fatal(errDecode) + } + multiKeys := multiGroups[0]["keys"].([]any) + if len(multiKeys) != 2 { + t.Fatalf("expected 2 keys, got %d", len(multiKeys)) + } + if got1 := multiKeys[0].(map[string]any)["auth_index"]; got1 != wantMultiIdx1 { + t.Fatalf("multi key 1 auth_index = %q, want %q", got1, wantMultiIdx1) + } + if got2 := multiKeys[1].(map[string]any)["auth_index"]; got2 != wantMultiIdx2 { + t.Fatalf("multi key 2 auth_index = %q, want %q", got2, wantMultiIdx2) + } + + // 17. Gemini with empty API keys and proxies [P1, P1, P2]: key 0 and 1 get P1, key 2 gets P2 + geminiProxyYAML := `config-version: 8 +port: 8317 +api-keys: + gemini: + - name: gemini-proxy-group + base-url: http://emulator.invalid:8080 + keys: + - api-key: "" + proxy-url: http://proxy1.invalid:8080 + - api-key: "" + proxy-url: http://proxy1.invalid:8080 + - api-key: "" + proxy-url: http://proxy2.invalid:8080 +` + geminiProxyPath := filepath.Join(dir, "gemini-proxy-dup.yaml") + if errWrite := os.WriteFile(geminiProxyPath, []byte(geminiProxyYAML), 0600); errWrite != nil { + t.Fatal(errWrite) + } + geminiProxyCfg, errLoadGProxy := config.LoadConfig(geminiProxyPath) + if errLoadGProxy != nil { + t.Fatal(errLoadGProxy) + } + gProxyAuths, errGProxySynth := synth.Synthesize(&synthesizer.SynthesisContext{ + Config: geminiProxyCfg, + Now: time.Now(), + IDGenerator: synthesizer.NewStableIDGenerator(), + }) + // Runtime deduplicates identical empty key + proxy entries to 2 credentials: P1 and P2 + if errGProxySynth != nil || len(gProxyAuths) != 2 { + t.Fatalf("synthesize gemini proxy auths: %v, len=%d", errGProxySynth, len(gProxyAuths)) + } + gProxyManager := coreauth.NewManager(nil, nil, nil) + for _, a := range gProxyAuths { + if _, errReg := gProxyManager.Register(context.Background(), a); errReg != nil { + t.Fatal(errReg) + } + } + wantGProxy1 := gProxyAuths[0].EnsureIndex() + wantGProxy2 := gProxyAuths[1].EnsureIndex() + if wantGProxy1 == "" || wantGProxy2 == "" || wantGProxy1 == wantGProxy2 { + t.Fatalf("expected distinct indexes for P1 and P2: %q vs %q", wantGProxy1, wantGProxy2) + } + + hGProxy := &Handler{cfg: geminiProxyCfg, configFilePath: geminiProxyPath, authManager: gProxyManager} + routerGProxy := gin.New() + routerGProxy.GET("/v8/management/config/*path", hGProxy.ConfigV8) + + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/v8/management/config/api-keys/gemini", nil) + routerGProxy.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("GET gemini proxy: status=%d body=%s", rec.Code, rec.Body.String()) + } + var gProxyGroups []map[string]any + if errDecode := json.Unmarshal(rec.Body.Bytes(), &gProxyGroups); errDecode != nil { + t.Fatal(errDecode) + } + gProxyKeys := gProxyGroups[0]["keys"].([]any) + if len(gProxyKeys) != 3 { + t.Fatalf("expected 3 keys, got %d", len(gProxyKeys)) + } + if got0 := gProxyKeys[0].(map[string]any)["auth_index"]; got0 != wantGProxy1 { + t.Fatalf("key 0 auth_index = %q, want %q", got0, wantGProxy1) + } + if got1 := gProxyKeys[1].(map[string]any)["auth_index"]; got1 != wantGProxy1 { + t.Fatalf("key 1 auth_index = %q, want %q (should reuse P1, not jump to P2)", got1, wantGProxy1) + } + if got2 := gProxyKeys[2].(map[string]any)["auth_index"]; got2 != wantGProxy2 { + t.Fatalf("key 2 auth_index = %q, want %q", got2, wantGProxy2) + } + + // 18. Two OpenAI-compatible groups with identical name and base-url: no cross-group collision + compatDupGroupYAML := `config-version: 8 +port: 8317 +api-keys: + openai-compatibility: + - name: shared-name + base-url: https://api.shared.invalid + keys: + - api-key: "" + proxy-url: http://proxyA.invalid:8080 + - name: shared-name + base-url: https://api.shared.invalid + keys: + - api-key: "" + proxy-url: http://proxyB.invalid:8080 +` + compatDupGroupPath := filepath.Join(dir, "compat-dup-group.yaml") + if errWrite := os.WriteFile(compatDupGroupPath, []byte(compatDupGroupYAML), 0600); errWrite != nil { + t.Fatal(errWrite) + } + compatDupGroupCfg, errLoadDupGroup := config.LoadConfig(compatDupGroupPath) + if errLoadDupGroup != nil { + t.Fatal(errLoadDupGroup) + } + dupGroupAuths, errDupGroupSynth := synth.Synthesize(&synthesizer.SynthesisContext{ + Config: compatDupGroupCfg, + Now: time.Now(), + IDGenerator: synthesizer.NewStableIDGenerator(), + }) + if errDupGroupSynth != nil || len(dupGroupAuths) != 2 { + t.Fatalf("synthesize dup group auths: %v, len=%d", errDupGroupSynth, len(dupGroupAuths)) + } + dupGroupManager := coreauth.NewManager(nil, nil, nil) + for _, a := range dupGroupAuths { + if _, errReg := dupGroupManager.Register(context.Background(), a); errReg != nil { + t.Fatal(errReg) + } + } + wantGroup0Index := dupGroupAuths[0].EnsureIndex() + wantGroup1Index := dupGroupAuths[1].EnsureIndex() + if wantGroup0Index == "" || wantGroup1Index == "" || wantGroup0Index == wantGroup1Index { + t.Fatalf("expected distinct indexes across groups: %q vs %q", wantGroup0Index, wantGroup1Index) + } + + hDupGroup := &Handler{cfg: compatDupGroupCfg, configFilePath: compatDupGroupPath, authManager: dupGroupManager} + routerDupGroup := gin.New() + routerDupGroup.GET("/v8/management/config/*path", hDupGroup.ConfigV8) + + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/v8/management/config/api-keys/openai-compatibility", nil) + routerDupGroup.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("GET dup group: status=%d body=%s", rec.Code, rec.Body.String()) + } + var dupGroups []map[string]any + if errDecode := json.Unmarshal(rec.Body.Bytes(), &dupGroups); errDecode != nil { + t.Fatal(errDecode) + } + if len(dupGroups) != 2 { + t.Fatalf("expected 2 groups, got %d", len(dupGroups)) + } + gotGroup0KeyIndex := dupGroups[0]["keys"].([]any)[0].(map[string]any)["auth_index"] + gotGroup1KeyIndex := dupGroups[1]["keys"].([]any)[0].(map[string]any)["auth_index"] + if gotGroup0KeyIndex != wantGroup0Index { + t.Fatalf("group 0 key auth_index = %q, want %q", gotGroup0KeyIndex, wantGroup0Index) + } + if gotGroup1KeyIndex != wantGroup1Index { + t.Fatalf("group 1 key auth_index = %q, want %q", gotGroup1KeyIndex, wantGroup1Index) + } + + // 19. Gemini with empty API keys and different prefixes [A, A, B]: key 0 and 1 get A, key 2 gets B + geminiPrefixYAML := `config-version: 8 +port: 8317 +api-keys: + gemini: + - name: gemini-prefix-group + base-url: http://emulator.invalid:8080 + keys: + - api-key: "" + prefix: /team-a/ + - api-key: "" + prefix: /team-a/ + - api-key: "" + prefix: /team-b/ +` + geminiPrefixPath := filepath.Join(dir, "gemini-prefix-dup.yaml") + if errWrite := os.WriteFile(geminiPrefixPath, []byte(geminiPrefixYAML), 0600); errWrite != nil { + t.Fatal(errWrite) + } + geminiPrefixCfg, errLoadGPrefix := config.LoadConfig(geminiPrefixPath) + if errLoadGPrefix != nil { + t.Fatal(errLoadGPrefix) + } + gPrefixAuths, errGPrefixSynth := synth.Synthesize(&synthesizer.SynthesisContext{ + Config: geminiPrefixCfg, + Now: time.Now(), + IDGenerator: synthesizer.NewStableIDGenerator(), + }) + if errGPrefixSynth != nil || len(gPrefixAuths) != 2 { + t.Fatalf("synthesize gemini prefix auths: %v, len=%d", errGPrefixSynth, len(gPrefixAuths)) + } + gPrefixManager := coreauth.NewManager(nil, nil, nil) + for _, a := range gPrefixAuths { + if _, errReg := gPrefixManager.Register(context.Background(), a); errReg != nil { + t.Fatal(errReg) + } + } + wantGPrefixA := gPrefixAuths[0].EnsureIndex() + wantGPrefixB := gPrefixAuths[1].EnsureIndex() + if wantGPrefixA == "" || wantGPrefixB == "" || wantGPrefixA == wantGPrefixB { + t.Fatalf("expected distinct indexes for A and B: %q vs %q", wantGPrefixA, wantGPrefixB) + } + + hGPrefix := &Handler{cfg: geminiPrefixCfg, configFilePath: geminiPrefixPath, authManager: gPrefixManager} + routerGPrefix := gin.New() + routerGPrefix.GET("/v8/management/config/*path", hGPrefix.ConfigV8) + + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/v8/management/config/api-keys/gemini", nil) + routerGPrefix.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("GET gemini prefix: status=%d body=%s", rec.Code, rec.Body.String()) + } + var gPrefixGroups []map[string]any + if errDecode := json.Unmarshal(rec.Body.Bytes(), &gPrefixGroups); errDecode != nil { + t.Fatal(errDecode) + } + gPrefixKeys := gPrefixGroups[0]["keys"].([]any) + if len(gPrefixKeys) != 3 { + t.Fatalf("expected 3 keys, got %d", len(gPrefixKeys)) + } + if got0 := gPrefixKeys[0].(map[string]any)["auth_index"]; got0 != wantGPrefixA { + t.Fatalf("key 0 auth_index = %q, want %q", got0, wantGPrefixA) + } + if got1 := gPrefixKeys[1].(map[string]any)["auth_index"]; got1 != wantGPrefixA { + t.Fatalf("key 1 auth_index = %q, want %q (should reuse A, not jump to B)", got1, wantGPrefixA) + } + if got2 := gPrefixKeys[2].(map[string]any)["auth_index"]; got2 != wantGPrefixB { + t.Fatalf("key 2 auth_index = %q, want %q", got2, wantGPrefixB) + } + + // 20. Unnamed OpenAI-compatible groups (name omitted) expose correct auth_index + unnamedCompatYAML := `config-version: 8 +port: 8317 +api-keys: + openai-compatibility: + - base-url: https://api.unnamed-keyless.invalid + keys: [] + - base-url: https://api.unnamed-keyed.invalid + keys: + - api-key: sk-unnamed-key +` + unnamedPath := filepath.Join(dir, "unnamed-compat.yaml") + if errWrite := os.WriteFile(unnamedPath, []byte(unnamedCompatYAML), 0600); errWrite != nil { + t.Fatal(errWrite) + } + unnamedCfg, errLoadUnnamed := config.LoadConfig(unnamedPath) + if errLoadUnnamed != nil { + t.Fatal(errLoadUnnamed) + } + unnamedAuths, errUnnamedSynth := synth.Synthesize(&synthesizer.SynthesisContext{ + Config: unnamedCfg, + Now: time.Now(), + IDGenerator: synthesizer.NewStableIDGenerator(), + }) + if errUnnamedSynth != nil || len(unnamedAuths) != 2 { + t.Fatalf("synthesize unnamed auths: %v, len=%d", errUnnamedSynth, len(unnamedAuths)) + } + unnamedManager := coreauth.NewManager(nil, nil, nil) + for _, a := range unnamedAuths { + if _, errReg := unnamedManager.Register(context.Background(), a); errReg != nil { + t.Fatal(errReg) + } + } + wantUnnamedKeyless := unnamedAuths[0].EnsureIndex() + wantUnnamedKeyed := unnamedAuths[1].EnsureIndex() + if wantUnnamedKeyless == "" || wantUnnamedKeyed == "" || wantUnnamedKeyless == wantUnnamedKeyed { + t.Fatalf("expected distinct indexes for unnamed compat: %q vs %q", wantUnnamedKeyless, wantUnnamedKeyed) + } + + hUnnamed := &Handler{cfg: unnamedCfg, configFilePath: unnamedPath, authManager: unnamedManager} + routerUnnamed := gin.New() + routerUnnamed.GET("/v8/management/config/*path", hUnnamed.ConfigV8) + + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/v8/management/config/api-keys/openai-compatibility", nil) + routerUnnamed.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("GET unnamed compat: status=%d body=%s", rec.Code, rec.Body.String()) + } + var unnamedGroups []map[string]any + if errDecode := json.Unmarshal(rec.Body.Bytes(), &unnamedGroups); errDecode != nil { + t.Fatal(errDecode) + } + if len(unnamedGroups) != 2 { + t.Fatalf("expected 2 unnamed groups, got %d", len(unnamedGroups)) + } + if gotKeyless := unnamedGroups[0]["auth_index"]; gotKeyless != wantUnnamedKeyless { + t.Fatalf("unnamed keyless group auth_index = %q, want %q", gotKeyless, wantUnnamedKeyless) + } + unnamedKeyMap := unnamedGroups[1]["keys"].([]any)[0].(map[string]any) + if gotKeyed := unnamedKeyMap["auth_index"]; gotKeyed != wantUnnamedKeyed { + t.Fatalf("unnamed keyed auth_index = %q, want %q", gotKeyed, wantUnnamedKeyed) + } + + // 21. Claude group with empty key entry [{}, {key-a}, {key-b}]: empty key has no index, A gets A, B gets B + claudeEmptyKeyYAML := `config-version: 8 +port: 8317 +api-keys: + claude: + - name: claude-group + keys: + - {} + - api-key: sk-claude-real-a + - api-key: sk-claude-real-b +` + claudeEmptyPath := filepath.Join(dir, "claude-empty-key.yaml") + if errWrite := os.WriteFile(claudeEmptyPath, []byte(claudeEmptyKeyYAML), 0600); errWrite != nil { + t.Fatal(errWrite) + } + claudeEmptyCfg, errLoadClaudeEmpty := config.LoadConfig(claudeEmptyPath) + if errLoadClaudeEmpty != nil { + t.Fatal(errLoadClaudeEmpty) + } + claudeEmptyAuths, errClaudeSynth := synth.Synthesize(&synthesizer.SynthesisContext{ + Config: claudeEmptyCfg, + Now: time.Now(), + IDGenerator: synthesizer.NewStableIDGenerator(), + }) + // Empty Claude key with no base-url is skipped by synthesizeClaudeKeys, producing 2 auths: A and B + if errClaudeSynth != nil || len(claudeEmptyAuths) != 2 { + t.Fatalf("synthesize claude empty auths: %v, len=%d", errClaudeSynth, len(claudeEmptyAuths)) + } + claudeEmptyManager := coreauth.NewManager(nil, nil, nil) + for _, a := range claudeEmptyAuths { + if _, errReg := claudeEmptyManager.Register(context.Background(), a); errReg != nil { + t.Fatal(errReg) + } + } + wantClaudeA := claudeEmptyAuths[0].EnsureIndex() + wantClaudeB := claudeEmptyAuths[1].EnsureIndex() + if wantClaudeA == "" || wantClaudeB == "" || wantClaudeA == wantClaudeB { + t.Fatalf("expected distinct indexes for A and B: %q vs %q", wantClaudeA, wantClaudeB) + } + + hClaudeEmpty := &Handler{cfg: claudeEmptyCfg, configFilePath: claudeEmptyPath, authManager: claudeEmptyManager} + routerClaudeEmpty := gin.New() + routerClaudeEmpty.GET("/v8/management/config/*path", hClaudeEmpty.ConfigV8) + + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/v8/management/config/api-keys/claude", nil) + routerClaudeEmpty.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("GET claude empty: status=%d body=%s", rec.Code, rec.Body.String()) + } + var claudeEmptyGroups []map[string]any + if errDecode := json.Unmarshal(rec.Body.Bytes(), &claudeEmptyGroups); errDecode != nil { + t.Fatal(errDecode) + } + emptyGroupKeys := claudeEmptyGroups[0]["keys"].([]any) + if len(emptyGroupKeys) != 3 { + t.Fatalf("expected 3 keys in claude response, got %d", len(emptyGroupKeys)) + } + // Key 0 was empty, should have no auth_index + if gotEmpty := emptyGroupKeys[0].(map[string]any)["auth_index"]; gotEmpty != nil { + t.Fatalf("claude empty key auth_index = %v, want nil", gotEmpty) + } + // Key 1 is A + if gotA := emptyGroupKeys[1].(map[string]any)["auth_index"]; gotA != wantClaudeA { + t.Fatalf("claude key 1 auth_index = %q, want %q", gotA, wantClaudeA) + } + // Key 2 is B + if gotB := emptyGroupKeys[2].(map[string]any)["auth_index"]; gotB != wantClaudeB { + t.Fatalf("claude key 2 auth_index = %q, want %q", gotB, wantClaudeB) + } + + // 22. Codex with multiple empty API keys in the same group with different models (non-deduplicated) + codexEmptyKeysYAML := `config-version: 8 +port: 8317 +api-keys: + codex: + - name: codex-models-group + base-url: https://api.openai.invalid + keys: + - api-key: "" + models: + - name: gpt-5 + alias: gpt-5 + - api-key: "" + models: + - name: gpt-6 + alias: gpt-6 +` + codexEmptyPath := filepath.Join(dir, "codex-empty-keys.yaml") + if errWrite := os.WriteFile(codexEmptyPath, []byte(codexEmptyKeysYAML), 0600); errWrite != nil { + t.Fatal(errWrite) + } + codexEmptyCfg, errLoadCodexEmpty := config.LoadConfig(codexEmptyPath) + if errLoadCodexEmpty != nil { + t.Fatal(errLoadCodexEmpty) + } + codexEmptyAuths, errCodexSynth := synth.Synthesize(&synthesizer.SynthesisContext{ + Config: codexEmptyCfg, + Now: time.Now(), + IDGenerator: synthesizer.NewStableIDGenerator(), + }) + if errCodexSynth != nil || len(codexEmptyAuths) != 2 { + t.Fatalf("synthesize codex empty auths: %v, len=%d", errCodexSynth, len(codexEmptyAuths)) + } + wantCodexModel0 := codexEmptyAuths[0].EnsureIndex() + wantCodexModel1 := codexEmptyAuths[1].EnsureIndex() + if wantCodexModel0 == "" || wantCodexModel1 == "" || wantCodexModel0 == wantCodexModel1 { + t.Fatalf("expected distinct indexes for codex empty keys: %q vs %q", wantCodexModel0, wantCodexModel1) + } + + hCodexEmpty := &Handler{cfg: codexEmptyCfg, configFilePath: codexEmptyPath} + routerCodexEmpty := gin.New() + routerCodexEmpty.GET("/v8/management/config/*path", hCodexEmpty.ConfigV8) + + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/v8/management/config/api-keys/codex", nil) + routerCodexEmpty.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("GET codex empty keys: status=%d body=%s", rec.Code, rec.Body.String()) + } + var codexEmptyGroups []map[string]any + if errDecode := json.Unmarshal(rec.Body.Bytes(), &codexEmptyGroups); errDecode != nil { + t.Fatal(errDecode) + } + codexKeys := codexEmptyGroups[0]["keys"].([]any) + if len(codexKeys) != 2 { + t.Fatalf("expected 2 keys, got %d", len(codexKeys)) + } + if got0 := codexKeys[0].(map[string]any)["auth_index"]; got0 != wantCodexModel0 { + t.Fatalf("codex key 0 auth_index = %q, want %q", got0, wantCodexModel0) + } + if got1 := codexKeys[1].(map[string]any)["auth_index"]; got1 != wantCodexModel1 { + t.Fatalf("codex key 1 auth_index = %q, want %q", got1, wantCodexModel1) + } + + // 23. Meta with [empty key, dca key, valid A, valid B]: empty and dca skipped, A gets A, B gets B + metaFilteredYAML := `config-version: 8 +port: 8317 +api-keys: + meta: + - name: meta-filtered-group + keys: + - api-key: "" + - api-key: dca:some-oauth-token + - api-key: sk-meta-real-a + - api-key: sk-meta-real-b +` + metaFilteredPath := filepath.Join(dir, "meta-filtered.yaml") + if errWrite := os.WriteFile(metaFilteredPath, []byte(metaFilteredYAML), 0600); errWrite != nil { + t.Fatal(errWrite) + } + metaFilteredCfg, errLoadMetaFiltered := config.LoadConfig(metaFilteredPath) + if errLoadMetaFiltered != nil { + t.Fatal(errLoadMetaFiltered) + } + metaFilteredAuths, errMetaFilteredSynth := synth.Synthesize(&synthesizer.SynthesisContext{ + Config: metaFilteredCfg, + Now: time.Now(), + IDGenerator: synthesizer.NewStableIDGenerator(), + }) + if errMetaFilteredSynth != nil || len(metaFilteredAuths) != 2 { + t.Fatalf("synthesize meta filtered auths: %v, len=%d", errMetaFilteredSynth, len(metaFilteredAuths)) + } + wantMetaRealA := metaFilteredAuths[0].EnsureIndex() + wantMetaRealB := metaFilteredAuths[1].EnsureIndex() + if wantMetaRealA == "" || wantMetaRealB == "" || wantMetaRealA == wantMetaRealB { + t.Fatalf("expected distinct indexes for meta real keys: %q vs %q", wantMetaRealA, wantMetaRealB) + } + + hMetaFiltered := &Handler{cfg: metaFilteredCfg, configFilePath: metaFilteredPath} + routerMetaFiltered := gin.New() + routerMetaFiltered.GET("/v8/management/config/*path", hMetaFiltered.ConfigV8) + + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/v8/management/config/api-keys/meta", nil) + routerMetaFiltered.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("GET meta filtered: status=%d body=%s", rec.Code, rec.Body.String()) + } + var metaFilteredGroups []map[string]any + if errDecode := json.Unmarshal(rec.Body.Bytes(), &metaFilteredGroups); errDecode != nil { + t.Fatal(errDecode) + } + metaFilteredKeys := metaFilteredGroups[0]["keys"].([]any) + if len(metaFilteredKeys) != 4 { + t.Fatalf("expected 4 keys in response, got %d", len(metaFilteredKeys)) + } + if gotEmpty := metaFilteredKeys[0].(map[string]any)["auth_index"]; gotEmpty != nil { + t.Fatalf("empty key auth_index = %v, want nil", gotEmpty) + } + if gotDCA := metaFilteredKeys[1].(map[string]any)["auth_index"]; gotDCA != nil { + t.Fatalf("dca key auth_index = %v, want nil", gotDCA) + } + if gotA := metaFilteredKeys[2].(map[string]any)["auth_index"]; gotA != wantMetaRealA { + t.Fatalf("key A auth_index = %q, want %q", gotA, wantMetaRealA) + } + if gotB := metaFilteredKeys[3].(map[string]any)["auth_index"]; gotB != wantMetaRealB { + t.Fatalf("key B auth_index = %q, want %q", gotB, wantMetaRealB) + } +} diff --git a/internal/config/config_v8.go b/internal/config/config_v8.go index 704a4d26641..92cec524605 100644 --- a/internal/config/config_v8.go +++ b/internal/config/config_v8.go @@ -371,7 +371,14 @@ func expandV8Groups(groups *yaml.Node, provider string) (*yaml.Node, error) { if provider == "openai-compatibility" { item := deepCopyNode(group) deleteYAMLPath(item, "keys") - setYAMLPath(item, "api-key-entries", keys) + deleteYAMLPath(item, "auth_index") + deleteYAMLPath(item, "auth-index") + cleanKeys := deepCopyNode(keys) + for _, k := range cleanKeys.Content { + deleteYAMLPath(k, "auth_index") + deleteYAMLPath(k, "auth-index") + } + setYAMLPath(item, "api-key-entries", cleanKeys) out.Content = append(out.Content, item) continue } @@ -396,6 +403,9 @@ func expandV8Groups(groups *yaml.Node, provider string) (*yaml.Node, error) { } } for i := 0; i < len(key.Content); i += 2 { + if key.Content[i].Value == "auth_index" || key.Content[i].Value == "auth-index" { + continue + } if key.Content[i+1].Tag != "!!null" { setYAMLPath(item, key.Content[i].Value, key.Content[i+1]) } From c163bae4bcc12df5aa76a1a58ba3f26860be9393 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Sat, 3 Oct 2026 03:19:06 +0800 Subject: [PATCH 007/142] fix(auth): preserve terminal unauthorized state and prevent unsafe refresh retry - Avoid retrying Claude token refresh on ambiguous transport or decoding errors to protect single-use tokens - Block selection and unschedule refresh for credentials when both access token is rejected and refresh encounters `invalid_grant` - Prevent in-flight request completions or cooldown clears from reviving terminal unauthorized credentials - Allow manual force refresh to bypass terminal unauthorized checks Closes: #6288 --- internal/auth/claude/anthropic_auth.go | 6 +- internal/auth/claude/anthropic_auth_test.go | 90 ++++ sdk/cliproxy/auth/conductor_cooldown.go | 75 +++- sdk/cliproxy/auth/conductor_refresh.go | 77 +++- .../conductor_unauthorized_refresh_test.go | 386 +++++++++++++++++- 5 files changed, 605 insertions(+), 29 deletions(-) diff --git a/internal/auth/claude/anthropic_auth.go b/internal/auth/claude/anthropic_auth.go index 284db7175a8..b3b2618fd38 100644 --- a/internal/auth/claude/anthropic_auth.go +++ b/internal/auth/claude/anthropic_auth.go @@ -120,7 +120,11 @@ func isClaudeRefreshRetryable(err error) bool { if errors.As(err, &httpErr) { return httpErr.Retryable() } - return true + // A transport or response-decoding error is ambiguous: Anthropic may have + // consumed the single-use refresh token even though the response was lost. + // Retrying the same token can turn a transient network fault into + // invalid_grant. Only explicit retryable HTTP responses are safe to replay. + return false } // tokenResponse represents the response structure from Anthropic's OAuth token endpoint. diff --git a/internal/auth/claude/anthropic_auth_test.go b/internal/auth/claude/anthropic_auth_test.go index 21764ccc354..aaa8e2ddd77 100644 --- a/internal/auth/claude/anthropic_auth_test.go +++ b/internal/auth/claude/anthropic_auth_test.go @@ -2,6 +2,7 @@ package claude import ( "context" + "errors" "io" "net/http" "strings" @@ -260,6 +261,95 @@ func TestExchangeCodeForTokensSurvivesCompanionLookupFailure(t *testing.T) { } } +type errorReader struct { + err error +} + +func (r *errorReader) Read([]byte) (int, error) { + return 0, r.err +} + +func (r *errorReader) Close() error { + return nil +} + +func TestRefreshTokensWithRetry_DoesNotReplayAfterResponseReadError(t *testing.T) { + resetClaudeRefreshState() + defer resetClaudeRefreshState() + + var calls int32 + auth := &ClaudeAuth{ + httpClient: &http.Client{ + Transport: roundTripFunc(func(*http.Request) (*http.Response, error) { + atomic.AddInt32(&calls, 1) + return &http.Response{ + StatusCode: http.StatusOK, + Body: &errorReader{err: io.ErrUnexpectedEOF}, + Header: make(http.Header), + }, nil + }), + }, + } + + _, err := auth.RefreshTokensWithRetry(context.Background(), "single-use-refresh-token", 3) + if err == nil { + t.Fatal("expected refresh error") + } + if got := atomic.LoadInt32(&calls); got != 1 { + t.Fatalf("expected one refresh attempt after a response decode/read error, got %d", got) + } +} + +func TestRefreshTokensWithRetry_DoesNotReplayAfterJSONDecodeError(t *testing.T) { + resetClaudeRefreshState() + defer resetClaudeRefreshState() + + var calls int32 + auth := &ClaudeAuth{ + httpClient: &http.Client{ + Transport: roundTripFunc(func(*http.Request) (*http.Response, error) { + atomic.AddInt32(&calls, 1) + return &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader(`invalid json payload`)), + Header: make(http.Header), + }, nil + }), + }, + } + + _, err := auth.RefreshTokensWithRetry(context.Background(), "single-use-refresh-token", 3) + if err == nil { + t.Fatal("expected refresh error") + } + if got := atomic.LoadInt32(&calls); got != 1 { + t.Fatalf("expected one refresh attempt after a JSON decode error, got %d", got) + } +} + +func TestRefreshTokensWithRetry_DoesNotReplayAfterTransportError(t *testing.T) { + resetClaudeRefreshState() + defer resetClaudeRefreshState() + + var calls int32 + auth := &ClaudeAuth{ + httpClient: &http.Client{ + Transport: roundTripFunc(func(*http.Request) (*http.Response, error) { + atomic.AddInt32(&calls, 1) + return nil, errors.New("connection reset by peer") + }), + }, + } + + _, err := auth.RefreshTokensWithRetry(context.Background(), "single-use-refresh-token", 3) + if err == nil { + t.Fatal("expected refresh error") + } + if got := atomic.LoadInt32(&calls); got != 1 { + t.Fatalf("expected one refresh attempt after an ambiguous transport error, got %d", got) + } +} + func TestRefreshTokensWithRetry_429BlocksImmediateReplay(t *testing.T) { resetClaudeRefreshState() defer resetClaudeRefreshState() diff --git a/sdk/cliproxy/auth/conductor_cooldown.go b/sdk/cliproxy/auth/conductor_cooldown.go index 277029596c2..33f8b5d8d7f 100644 --- a/sdk/cliproxy/auth/conductor_cooldown.go +++ b/sdk/cliproxy/auth/conductor_cooldown.go @@ -357,7 +357,7 @@ func (m *Manager) restoreCooldownRecordLocked(record CooldownStateRecord, now ti return false } auth := m.auths[authID] - if auth == nil || auth.Disabled || auth.Status == StatusDisabled || m.cooldownDisabledForAuth(auth) { + if auth == nil || auth.Disabled || auth.Status == StatusDisabled || m.cooldownDisabledForAuth(auth) || hasUnauthorizedAuthFailure(auth) { return false } updatedAt := record.UpdatedAt @@ -406,6 +406,9 @@ func clearCooldownStateForAuth(auth *Auth, now time.Time) bool { if auth == nil { return false } + if hasUnauthorizedAuthFailure(auth) { + return false + } changed := false if auth.Unavailable || !auth.NextRetryAfter.IsZero() || auth.Quota.Exceeded || !auth.Quota.NextRecoverAt.IsZero() { auth.Unavailable = false @@ -508,9 +511,11 @@ func (m *Manager) ResetQuota(ctx context.Context, authID string) (*Auth, []strin models = dedupeStrings(models) if !auth.Disabled && auth.Status != StatusDisabled && !hasModelError(auth, now) { - auth.LastError = nil - auth.StatusMessage = "" - auth.Status = StatusActive + if !hasUnauthorizedAuthFailure(auth) { + auth.LastError = nil + auth.StatusMessage = "" + auth.Status = StatusActive + } } auth.Generation++ auth.UpdatedAt = now @@ -785,9 +790,16 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) { } else { auth.Failed++ } + wasTerminalUnauthorized := hasUnauthorizedAuthFailure(auth) if result.Success { - if auth.Quota.Reason == "credential_quota" && auth.Quota.NextRecoverAt.After(now) { + if wasTerminalUnauthorized { + if modelKey != "" { + state := ensureModelState(auth, modelKey) + modelState = state + resetModelState(state, now) + } + } else if auth.Quota.Reason == "credential_quota" && auth.Quota.NextRecoverAt.After(now) { // Retain active credential-scoped cooldown } else if modelKey != "" { state := ensureModelState(auth, modelKey) @@ -818,8 +830,10 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) { if result.Error != nil { state.LastError = cloneError(result.Error) state.StatusMessage = result.Error.Message - auth.LastError = cloneError(result.Error) - auth.StatusMessage = result.Error.Message + if !wasTerminalUnauthorized { + auth.LastError = cloneError(result.Error) + auth.StatusMessage = result.Error.Message + } } statusCode := statusCodeFromResult(result.Error) @@ -836,7 +850,7 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) { next, backoffLevel := nextCloudflareCooldown(state.Quota.BackoffLevel, disableCooling, now) state.NextRetryAfter = next state.StatusMessage = "cloudflare challenge" - if auth.LastError != nil { + if auth.LastError != nil && !wasTerminalUnauthorized { auth.StatusMessage = "cloudflare challenge" } applyCooldownFields(&state.Quota, QuotaState{ @@ -934,17 +948,19 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) { }) } } - auth.Unavailable = true - authNext := credentialNext - if auth.Quota.Exceeded && auth.Quota.Reason == "credential_quota" && - auth.Quota.NextRecoverAt.After(authNext) { - authNext = auth.Quota.NextRecoverAt + if !wasTerminalUnauthorized { + auth.Unavailable = true + authNext := credentialNext + if auth.Quota.Exceeded && auth.Quota.Reason == "credential_quota" && + auth.Quota.NextRecoverAt.After(authNext) { + authNext = auth.Quota.NextRecoverAt + } + auth.Quota.Exceeded = true + auth.Quota.Reason = "credential_quota" + auth.Quota.NextRecoverAt = authNext + auth.Quota.BackoffLevel = backoffLevel + auth.NextRetryAfter = authNext } - auth.Quota.Exceeded = true - auth.Quota.Reason = "credential_quota" - auth.Quota.NextRecoverAt = authNext - auth.Quota.BackoffLevel = backoffLevel - auth.NextRetryAfter = authNext } case 408, 500, 502, 503, 504, 520, 521, 522, 523, 524, 525, 526: state.NextRetryAfter = recoverableFailureRetryAfterWithHint(now, result.RetryAfter, disableCooling) @@ -977,10 +993,19 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) { if result.Error != nil && result.Error.Code == ErrorCodeForceCooldown { disableCooling = false } - applyAuthFailureState(auth, result.Error, result.RetryAfter, now, disableCooling) + if !wasTerminalUnauthorized { + applyAuthFailureState(auth, result.Error, result.RetryAfter, now, disableCooling) + } } } + if wasTerminalUnauthorized { + auth.Unavailable = true + auth.Status = StatusError + auth.NextRefreshAfter = time.Time{} + auth.NextRetryAfter = time.Time{} + } + auth.Generation++ auth.UpdatedAt = now @@ -1305,6 +1330,12 @@ func updateAggregatedAvailability(auth *Auth, now time.Time) { if auth == nil { return } + // A terminal unauthorized credential stays blocked until its tokens change. + // Model-level results must not make it selectable again. + if hasUnauthorizedAuthFailure(auth) { + auth.Unavailable = true + return + } if auth.Quota.Exceeded && auth.Quota.Reason == "credential_quota" && auth.Quota.NextRecoverAt.After(now) { auth.Unavailable = true return @@ -1414,6 +1445,10 @@ func clearAuthStateOnSuccess(auth *Auth, now time.Time) { if auth == nil { return } + if hasUnauthorizedAuthFailure(auth) { + auth.Unavailable = true + return + } auth.Unavailable = false auth.Status = StatusActive auth.StatusMessage = "" @@ -1680,7 +1715,7 @@ func hasUnauthorizedAuthFailure(auth *Auth) bool { if auth == nil || auth.LastError == nil { return false } - if auth.Unavailable && auth.Status == StatusError && auth.NextRefreshAfter.IsZero() && + if auth.Unavailable && auth.Status == StatusError && auth.NextRefreshAfter.IsZero() && auth.NextRetryAfter.IsZero() && (auth.LastError.StatusCode() == http.StatusUnauthorized || strings.EqualFold(auth.LastError.Code, "unauthorized")) { return true } diff --git a/sdk/cliproxy/auth/conductor_refresh.go b/sdk/cliproxy/auth/conductor_refresh.go index 6112a5fb5b0..a92e6b5c2a5 100644 --- a/sdk/cliproxy/auth/conductor_refresh.go +++ b/sdk/cliproxy/auth/conductor_refresh.go @@ -523,6 +523,9 @@ func (m *Manager) tryRefreshAfterUnauthorized(ctx context.Context, auth *Auth, e if !isUnauthorizedError(execErr) || !authHasRefreshCredential(auth) { return auth, false } + if hasUnauthorizedAuthFailure(auth) { + return auth, false + } log.Debugf("unauthorized response for %s (%s), refreshing credentials before fallback", auth.Provider, auth.ID) refreshed, errRefresh := m.refreshAuthForRequest(ctx, auth.ID, authAccessToken(auth)) if errRefresh != nil || refreshed == nil { @@ -558,14 +561,35 @@ func (m *Manager) refreshAuthForRequest(ctx context.Context, id, failedAccessTok return m.refreshAuthForRequestAtEpoch(ctx, id, failedAccessToken, 0) } +type forceRefreshContextKey struct{} + +func withForceRefresh(ctx context.Context) context.Context { + if ctx == nil { + ctx = context.Background() + } + return context.WithValue(ctx, forceRefreshContextKey{}, true) +} + +func isForceRefreshContext(ctx context.Context) bool { + if ctx == nil { + return false + } + v, ok := ctx.Value(forceRefreshContextKey{}).(bool) + return ok && v +} + func (m *Manager) refreshAuthForRequestAtEpoch(ctx context.Context, id, failedAccessToken string, registrationEpoch uint64) (*Auth, error) { if m == nil { return nil, errors.New("auth manager is nil") } + forceRefresh := isForceRefreshContext(ctx) ctx = cliproxyexecutor.WithoutRequestProxyURL(ctx) if ctx == nil { ctx = context.Background() } + if forceRefresh { + ctx = withForceRefresh(ctx) + } id = strings.TrimSpace(id) if id == "" { return nil, errors.New("auth id is empty") @@ -595,9 +619,12 @@ func (m *Manager) refreshAuthForRequestAtEpoch(ctx context.Context, id, failedAc if registrationEpoch != 0 && auth.RegistrationEpoch != registrationEpoch { return nil, errors.New("auth registration changed before refresh") } - if hasDisabledInvalidGrantFailure(auth) { + if hasDisabledInvalidGrantFailure(auth) && !forceRefresh { return nil, errors.New("auth is disabled with invalid grant") } + if hasUnauthorizedAuthFailure(auth) && !forceRefresh { + return nil, errors.New("auth is unauthorized") + } // Another request may already have refreshed this credential. if failedAccessToken != "" { @@ -619,26 +646,53 @@ func (m *Manager) refreshAuthForRequestAtEpoch(ctx context.Context, id, failedAc invalidGrant := isInvalidGrantError(err) shouldReschedule := false isDisabled := false - isPermanentlyDisabled := false + shouldUnschedule := false m.mu.Lock() if current := m.auths[id]; current != nil { if base != nil && current.RegistrationEpoch != base.RegistrationEpoch { m.mu.Unlock() return nil, err } + if hasUnauthorizedAuthFailure(current) && !forceRefresh { + m.mu.Unlock() + return nil, err + } + wasTerminalUnauthorized := hasUnauthorizedAuthFailure(current) + if wasTerminalUnauthorized { + current.Generation++ + current.UpdatedAt = now + current.Unavailable = true + current.Status = StatusError + current.NextRefreshAfter = time.Time{} + current.NextRetryAfter = time.Time{} + if isUnauthorizedError(err) || isInvalidGrantError(err) { + current.LastError = &Error{Code: "unauthorized", Message: err.Error(), HTTPStatus: http.StatusUnauthorized} + current.StatusMessage = "unauthorized (refresh token invalid)" + } + m.auths[id] = current + if m.scheduler != nil { + m.scheduler.upsertAuth(current.Clone()) + } + m.mu.Unlock() + m.queueRefreshUnschedule(id) + return nil, err + } current.Generation++ current.UpdatedAt = now current.LastError = refreshErrorFromError(err) isDisabled = current.Disabled || current.Status == StatusDisabled hasValidAccessToken := current.HasValidAccessToken(now) + // failedAccessToken is set only when upstream rejected this exact access + // token. Its expiry time no longer proves it is usable. + accessTokenRejected := failedAccessToken != "" && authAccessToken(current) == failedAccessToken if isDisabled && invalidGrant { current.Unavailable = true current.Status = StatusDisabled current.NextRefreshAfter = time.Time{} current.RefreshFailures = 0 current.StatusMessage = "disabled (invalid grant)" - isPermanentlyDisabled = true + shouldUnschedule = true } else if isDisabled { current.Unavailable = true current.Status = StatusDisabled @@ -647,11 +701,24 @@ func (m *Manager) refreshAuthForRequestAtEpoch(ctx context.Context, id, failedAc current.StatusMessage = "disabled" } shouldReschedule = true + } else if accessTokenRejected && invalidGrant { + // Neither token can recover without a new login. Stop selecting the + // credential until its tokens change instead of retrying it after + // every cooldown and returning the same 401 to clients. + current.Unavailable = true + current.Status = StatusError + current.NextRefreshAfter = time.Time{} + current.NextRetryAfter = time.Time{} + current.RefreshFailures = 0 + current.LastError = &Error{Code: "unauthorized", Message: err.Error(), HTTPStatus: http.StatusUnauthorized} + current.StatusMessage = "unauthorized (refresh token invalid)" + shouldUnschedule = true } else if !hasValidAccessToken { current.Unavailable = true current.Status = StatusError if unauthorized { current.NextRefreshAfter = time.Time{} + current.NextRetryAfter = time.Time{} current.RefreshFailures = 0 current.StatusMessage = "unauthorized" } else if invalidGrant { @@ -692,7 +759,7 @@ func (m *Manager) refreshAuthForRequestAtEpoch(ctx context.Context, id, failedAc m.mu.Unlock() if shouldReschedule { m.queueRefreshReschedule(id) - } else if isPermanentlyDisabled { + } else if shouldUnschedule { m.queueRefreshUnschedule(id) } return nil, err @@ -752,7 +819,7 @@ func (m *Manager) ForceRefreshAuth(ctx context.Context, id string) (*Auth, error if id == "" { return nil, errors.New("auth id is empty") } - return m.refreshAuthForRequest(ctx, id, "") + return m.refreshAuthForRequest(withForceRefresh(ctx), id, "") } func (m *Manager) refreshWorkers() int { diff --git a/sdk/cliproxy/auth/conductor_unauthorized_refresh_test.go b/sdk/cliproxy/auth/conductor_unauthorized_refresh_test.go index 6d46cd643e6..3ff1c129fa0 100644 --- a/sdk/cliproxy/auth/conductor_unauthorized_refresh_test.go +++ b/sdk/cliproxy/auth/conductor_unauthorized_refresh_test.go @@ -2,9 +2,11 @@ package auth import ( "context" + "errors" "net/http" "sync" "testing" + "time" "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" @@ -19,7 +21,10 @@ type unauthorizedRefreshExecutor struct { refreshCalls int tokenInvalid map[string]struct{} refreshFail bool + refreshErr error refreshTokens map[string]string + onExecute func(authID string) + onRefresh func() } func (e *unauthorizedRefreshExecutor) Identifier() string { return e.id } @@ -29,7 +34,11 @@ func (e *unauthorizedRefreshExecutor) Execute(_ context.Context, auth *Auth, _ c e.executeCalls = append(e.executeCalls, auth.ID) token := authAccessToken(auth) _, invalid := e.tokenInvalid[token] + onExec := e.onExecute e.mu.Unlock() + if onExec != nil { + onExec(auth.ID) + } if invalid { return cliproxyexecutor.Response{}, &Error{ HTTPStatus: http.StatusUnauthorized, @@ -44,7 +53,11 @@ func (e *unauthorizedRefreshExecutor) ExecuteStream(_ context.Context, auth *Aut e.streamCalls = append(e.streamCalls, auth.ID) token := authAccessToken(auth) _, invalid := e.tokenInvalid[token] + onExec := e.onExecute e.mu.Unlock() + if onExec != nil { + onExec(auth.ID) + } if invalid { return nil, &Error{ HTTPStatus: http.StatusUnauthorized, @@ -59,15 +72,24 @@ func (e *unauthorizedRefreshExecutor) ExecuteStream(_ context.Context, auth *Aut func (e *unauthorizedRefreshExecutor) Refresh(_ context.Context, auth *Auth) (*Auth, error) { e.mu.Lock() - defer e.mu.Unlock() e.refreshCalls++ - if e.refreshFail { + onRef := e.onRefresh + err := e.refreshErr + fail := e.refreshFail + next := e.refreshTokens[auth.ID] + e.mu.Unlock() + if onRef != nil { + onRef() + } + if err != nil { + return nil, err + } + if fail { return nil, &Error{HTTPStatus: http.StatusUnauthorized, Message: "refresh token invalid"} } if auth.Metadata == nil { auth.Metadata = make(map[string]any) } - next := e.refreshTokens[auth.ID] if next == "" { next = "refreshed-access-token" } @@ -227,6 +249,364 @@ func TestManager_ExecuteStream_UnauthorizedRefreshesCurrentAuthBeforeFallback(t } } +func TestManager_Execute_RejectedTokenWithInvalidGrantStopsSelectingAuth(t *testing.T) { + m, executor, primary, backup, model := newUnauthorizedRefreshFixture(t, false) + executor.mu.Lock() + executor.refreshErr = errors.New(`token refresh failed with status 400: {"error": "invalid_grant", "error_description": "Refresh token not found or invalid"}`) + executor.mu.Unlock() + // The revoked access token still has a future expiry, as in production. + updated, ok := m.GetByID(primary.ID) + if !ok || updated == nil { + t.Fatal("primary auth missing") + } + updated.Metadata["expired"] = time.Now().Add(6 * time.Hour).Format(time.RFC3339) + if _, errUpdate := m.Update(context.Background(), updated); errUpdate != nil { + t.Fatalf("update primary: %v", errUpdate) + } + + for i := 0; i < 2; i++ { + resp, errExecute := m.Execute(context.Background(), []string{"codex"}, cliproxyexecutor.Request{Model: model}, cliproxyexecutor.Options{}) + if errExecute != nil { + t.Fatalf("Execute %d error = %v, want success via backup", i, errExecute) + } + if got := string(resp.Payload); got != backup.ID+":backup-access-token" { + t.Fatalf("Execute %d payload = %q, want backup response", i, got) + } + } + + primaryCalls := 0 + for _, id := range executor.ExecuteCalls() { + if id == primary.ID { + primaryCalls++ + } + } + if primaryCalls != 1 { + t.Fatalf("primary executions = %d, want 1; calls = %v", primaryCalls, executor.ExecuteCalls()) + } + if got := executor.RefreshCalls(); got != 1 { + t.Fatalf("Refresh calls = %d, want 1", got) + } + final, ok := m.GetByID(primary.ID) + if !ok || final == nil { + t.Fatal("primary auth missing after refresh failure") + } + if !hasUnauthorizedAuthFailure(final) { + t.Fatalf("expected terminal unauthorized state, got unavailable=%v status=%s next_refresh=%v last_error=%+v", final.Unavailable, final.Status, final.NextRefreshAfter, final.LastError) + } +} + +func TestManager_MarkResult_InFlightResultDoesNotReviveTerminalUnauthorizedAuth(t *testing.T) { + m, executor, primary, backup, model := newUnauthorizedRefreshFixture(t, false) + executor.mu.Lock() + executor.refreshErr = errors.New(`token refresh failed with status 400: {"error": "invalid_grant", "error_description": "Refresh token not found or invalid"}`) + executor.mu.Unlock() + + // Initial request triggers 401 + invalid_grant -> terminal unauthorized. + _, errExecute := m.Execute(context.Background(), []string{"codex"}, cliproxyexecutor.Request{Model: model}, cliproxyexecutor.Options{}) + if errExecute != nil { + t.Fatalf("Execute error = %v, want success via backup", errExecute) + } + + authAfterRefresh, ok := m.GetByID(primary.ID) + if !ok || authAfterRefresh == nil { + t.Fatal("primary auth missing") + } + if !hasUnauthorizedAuthFailure(authAfterRefresh) { + t.Fatalf("expected terminal unauthorized state initially") + } + + // Simulate an in-flight request on primary finishing with 500 Internal Server Error. + m.MarkResult(context.Background(), Result{ + AuthID: primary.ID, + Provider: "codex", + Model: model, + Success: false, + Error: &Error{ + HTTPStatus: http.StatusInternalServerError, + Code: "internal_error", + Message: "internal server error", + }, + }) + + authAfter500, ok := m.GetByID(primary.ID) + if !ok || authAfter500 == nil { + t.Fatal("primary auth missing") + } + if !hasUnauthorizedAuthFailure(authAfter500) { + t.Fatalf("expected terminal unauthorized state preserved after in-flight 500, got status=%s unavailable=%v last_error=%+v", authAfter500.Status, authAfter500.Unavailable, authAfter500.LastError) + } + + // Simulate another in-flight request finishing with Success. + m.MarkResult(context.Background(), Result{ + AuthID: primary.ID, + Provider: "codex", + Model: model, + Success: true, + }) + + authAfterSuccess, ok := m.GetByID(primary.ID) + if !ok || authAfterSuccess == nil { + t.Fatal("primary auth missing") + } + if !hasUnauthorizedAuthFailure(authAfterSuccess) { + t.Fatalf("expected terminal unauthorized state preserved after in-flight success, got status=%s unavailable=%v last_error=%+v", authAfterSuccess.Status, authAfterSuccess.Unavailable, authAfterSuccess.LastError) + } + + // Reset any model cooldowns / advance time. + _, _, _ = m.ResetQuota(context.Background(), primary.ID) + + // Execute again: primary MUST NOT be selected. + callsBefore := len(executor.ExecuteCalls()) + resp, errSecond := m.Execute(context.Background(), []string{"codex"}, cliproxyexecutor.Request{Model: model}, cliproxyexecutor.Options{}) + if errSecond != nil { + t.Fatalf("second execute error: %v", errSecond) + } + if got := string(resp.Payload); got != backup.ID+":backup-access-token" { + t.Fatalf("got payload %q, want backup", got) + } + for _, id := range executor.ExecuteCalls()[callsBefore:] { + if id == primary.ID { + t.Fatalf("primary was selected again after in-flight result!") + } + } +} + +func TestManager_ConcurrentUnauthorized_BarrierExecutionPreservesTerminalState(t *testing.T) { + model := "gpt-5.5" + primary := &Auth{ + ID: "aa-primary", + Provider: "codex", + Metadata: map[string]any{ + "access_token": "stale-access-token", + "refresh_token": "primary-refresh-token", + "expired": time.Now().Add(6 * time.Hour).Format(time.RFC3339), + }, + } + backup := &Auth{ + ID: "bb-backup", + Provider: "codex", + Metadata: map[string]any{ + "access_token": "backup-access-token", + "refresh_token": "backup-refresh-token", + }, + } + + executor := &unauthorizedRefreshExecutor{ + id: "codex", + tokenInvalid: map[string]struct{}{ + "stale-access-token": {}, + }, + refreshErr: errors.New(`token refresh failed with status 400: {"error": "invalid_grant", "error_description": "Refresh token not found or invalid"}`), + } + + m := NewManager(nil, &FillFirstSelector{}, nil) + m.RegisterExecutor(executor) + + reg := registry.GetGlobalRegistry() + reg.RegisterClient(primary.ID, "codex", []*registry.ModelInfo{{ID: model}}) + reg.RegisterClient(backup.ID, "codex", []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { + reg.UnregisterClient(primary.ID) + reg.UnregisterClient(backup.ID) + }) + + if _, err := m.Register(context.Background(), primary); err != nil { + t.Fatalf("register primary: %v", err) + } + if _, err := m.Register(context.Background(), backup); err != nil { + t.Fatalf("register backup: %v", err) + } + + // Channel-based synchronization barrier: + // Hold both requests when executing primary until both have entered. + primaryEntered := make(chan struct{}, 2) + releasePrimary := make(chan struct{}) + executor.mu.Lock() + executor.onExecute = func(authID string) { + if authID == primary.ID { + primaryEntered <- struct{}{} + <-releasePrimary + } + } + executor.mu.Unlock() + + var wg sync.WaitGroup + wg.Add(2) + results := make([]string, 2) + errs := make([]error, 2) + + for i := 0; i < 2; i++ { + idx := i + go func() { + defer wg.Done() + resp, err := m.Execute(context.Background(), []string{"codex"}, cliproxyexecutor.Request{Model: model}, cliproxyexecutor.Options{}) + errs[idx] = err + if err == nil { + results[idx] = string(resp.Payload) + } + }() + } + + // Wait until both concurrent goroutines have arrived at executing primary with timeout protection. + timeout := time.After(5 * time.Second) + for i := 0; i < 2; i++ { + select { + case <-primaryEntered: + case <-timeout: + t.Fatal("timed out waiting for concurrent executions to enter primary") + } + } + // Release both goroutines to receive 401 concurrently. + close(releasePrimary) + + waitDone := make(chan struct{}) + go func() { + wg.Wait() + close(waitDone) + }() + select { + case <-waitDone: + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for concurrent executions to complete") + } + + for i := 0; i < 2; i++ { + if errs[i] != nil { + t.Fatalf("goroutine %d error = %v, want success via backup", i, errs[i]) + } + if results[i] != backup.ID+":backup-access-token" { + t.Fatalf("goroutine %d payload = %q, want backup response", i, results[i]) + } + } + + // Only 1 refresh attempt should have occurred for the invalidated primary token. + if got := executor.RefreshCalls(); got != 1 { + t.Fatalf("expected 1 refresh call during concurrent execution, got %d", got) + } + + final, ok := m.GetByID(primary.ID) + if !ok || final == nil { + t.Fatal("primary auth missing") + } + if !hasUnauthorizedAuthFailure(final) { + t.Fatalf("expected terminal unauthorized state after concurrent execution, got unavailable=%v status=%s next_refresh=%v last_error=%+v", + final.Unavailable, final.Status, final.NextRefreshAfter, final.LastError) + } + + // Explicitly verify background and request-triggered refresh do NOT call executor.Refresh on terminal unauthorized auth. + callsBefore := executor.RefreshCalls() + m.refreshAuth(context.Background(), primary.ID) + if got := executor.RefreshCalls(); got != callsBefore { + t.Fatalf("background refreshAuth called executor.Refresh on terminal unauthorized auth (%d -> %d)", callsBefore, got) + } + + _, refreshed := m.tryRefreshAfterUnauthorized(context.Background(), final, &Error{HTTPStatus: http.StatusUnauthorized, Message: "401"}, false) + if refreshed { + t.Fatal("tryRefreshAfterUnauthorized should not report refreshed for terminal unauthorized auth") + } + if got := executor.RefreshCalls(); got != callsBefore { + t.Fatalf("tryRefreshAfterUnauthorized called executor.Refresh on terminal unauthorized auth (%d -> %d)", callsBefore, got) + } + + // Verify that manual ForceRefreshAuth DOES call executor.Refresh. + _, _ = m.ForceRefreshAuth(context.Background(), primary.ID) + if got := executor.RefreshCalls(); got != callsBefore+1 { + t.Fatalf("ForceRefreshAuth should call executor.Refresh, got %d calls, want %d", got, callsBefore+1) + } + + // Verify that a subsequent request still does not touch primary. + execCallsBefore := len(executor.ExecuteCalls()) + resp3, err3 := m.Execute(context.Background(), []string{"codex"}, cliproxyexecutor.Request{Model: model}, cliproxyexecutor.Options{}) + if err3 != nil { + t.Fatalf("Execute 3 error: %v", err3) + } + if string(resp3.Payload) != backup.ID+":backup-access-token" { + t.Fatalf("Execute 3 want backup, got %s", resp3.Payload) + } + for _, id := range executor.ExecuteCalls()[execCallsBefore:] { + if id == primary.ID { + t.Fatalf("primary was selected again after concurrent execution!") + } + } +} + +func TestManager_ForceRefreshAuth_FailurePreservesTerminalUnauthorizedState(t *testing.T) { + m, executor, primary, backup, model := newUnauthorizedRefreshFixture(t, false) + + // Primary has future nominal expiry. + updated, ok := m.GetByID(primary.ID) + if !ok || updated == nil { + t.Fatal("primary auth missing") + } + updated.Metadata["expired"] = time.Now().Add(6 * time.Hour).Format(time.RFC3339) + if _, errUpdate := m.Update(context.Background(), updated); errUpdate != nil { + t.Fatalf("update primary: %v", errUpdate) + } + + executor.mu.Lock() + executor.refreshErr = errors.New(`token refresh failed with status 400: {"error": "invalid_grant", "error_description": "Refresh token not found or invalid"}`) + executor.mu.Unlock() + + // Initial request triggers 401 + invalid_grant -> terminal unauthorized. + _, errExecute := m.Execute(context.Background(), []string{"codex"}, cliproxyexecutor.Request{Model: model}, cliproxyexecutor.Options{}) + if errExecute != nil { + t.Fatalf("Execute error: %v", errExecute) + } + + authAfterInit, _ := m.GetByID(primary.ID) + if !hasUnauthorizedAuthFailure(authAfterInit) { + t.Fatalf("expected terminal unauthorized state initially") + } + + // 1. Manually force refresh, but the refresh fails with 503 Service Unavailable. + executor.mu.Lock() + executor.refreshErr = errors.New("upstream 503 service unavailable") + executor.mu.Unlock() + + _, errForce := m.ForceRefreshAuth(context.Background(), primary.ID) + if errForce == nil { + t.Fatal("expected ForceRefreshAuth to fail") + } + + authAfterFailedForce, _ := m.GetByID(primary.ID) + if !hasUnauthorizedAuthFailure(authAfterFailedForce) { + t.Fatalf("expected terminal unauthorized state to be preserved after failed force refresh, got unavailable=%v status=%s next_refresh=%v last_error=%+v", + authAfterFailedForce.Unavailable, authAfterFailedForce.Status, authAfterFailedForce.NextRefreshAfter, authAfterFailedForce.LastError) + } + if !authAfterFailedForce.NextRefreshAfter.IsZero() { + t.Fatalf("expected NextRefreshAfter to remain zero after failed force refresh, got %v", authAfterFailedForce.NextRefreshAfter) + } + + // Selection still skips primary. + resp, errAfterFailedForce := m.Execute(context.Background(), []string{"codex"}, cliproxyexecutor.Request{Model: model}, cliproxyexecutor.Options{}) + if errAfterFailedForce != nil { + t.Fatalf("Execute error: %v", errAfterFailedForce) + } + if string(resp.Payload) != backup.ID+":backup-access-token" { + t.Fatalf("expected backup selection, got %s", resp.Payload) + } + + // 2. Now force refresh succeeds with a valid token. + executor.mu.Lock() + executor.refreshErr = nil + executor.refreshTokens[primary.ID] = "newly-minted-token" + executor.mu.Unlock() + + refreshed, errSuccess := m.ForceRefreshAuth(context.Background(), primary.ID) + if errSuccess != nil { + t.Fatalf("ForceRefreshAuth should succeed, got: %v", errSuccess) + } + if refreshed.Status != StatusActive { + t.Fatalf("expected StatusActive after successful force refresh, got %s", refreshed.Status) + } + if refreshed.Unavailable { + t.Fatal("expected Unavailable=false after successful force refresh") + } + if hasUnauthorizedAuthFailure(refreshed) { + t.Fatal("hasUnauthorizedAuthFailure should be false after successful force refresh") + } +} + func TestManager_Execute_UnauthorizedRefreshFailureFallsBackToNextAuth(t *testing.T) { m, executor, primary, backup, model := newUnauthorizedRefreshFixture(t, true) From e6f6f26ad5563e7dd597a3aa889d67261cb6a509 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Sat, 3 Oct 2026 03:30:53 +0800 Subject: [PATCH 008/142] fix(claude): handle pause_turn stop reason in responses translation - Map Claude `pause_turn` stop reason to incomplete status with null incomplete details - Switch stop reason evaluation to normalized lowercase matching Closes: #6250 --- .../claude_openai-responses_pause_test.go | 72 +++++++++++++++++++ .../claude_openai-responses_response.go | 8 ++- 2 files changed, 79 insertions(+), 1 deletion(-) create mode 100644 internal/translator/claude/openai/responses/claude_openai-responses_pause_test.go diff --git a/internal/translator/claude/openai/responses/claude_openai-responses_pause_test.go b/internal/translator/claude/openai/responses/claude_openai-responses_pause_test.go new file mode 100644 index 00000000000..3e0f6445f4b --- /dev/null +++ b/internal/translator/claude/openai/responses/claude_openai-responses_pause_test.go @@ -0,0 +1,72 @@ +package responses + +import ( + "bytes" + "context" + "fmt" + "testing" + + "github.com/tidwall/gjson" +) + +func TestClaudeResponsesServerToolStopReason(t *testing.T) { + for _, tc := range []struct { + reason string + status string + detail string + }{ + {"pause_turn", "incomplete", "null"}, + {" PAUSE_TURN ", "incomplete", "null"}, + {"max_tokens", "incomplete", `{"reason":"max_output_tokens"}`}, + {"end_turn", "completed", ""}, + {"tool_use", "completed", ""}, + {"stop_sequence", "completed", ""}, + } { + t.Run(tc.reason, func(t *testing.T) { + chunks := claudeWebSearchStreamChunks() + stop := chunks[len(chunks)-1] + chunks = append(chunks[:len(chunks)-1], []byte(fmt.Sprintf( + `data: {"type":"message_delta","delta":{"stop_reason":%q},"usage":{"output_tokens":12}}`, tc.reason)), stop) + check := func(t *testing.T, response gjson.Result) { + t.Helper() + if got := response.Get("status").String(); got != tc.status { + t.Fatalf("status = %q, want %q", got, tc.status) + } + if got := response.Get("incomplete_details").Raw; got != tc.detail && !(tc.status == "completed" && got == "null") { + t.Fatalf("incomplete_details = %q, want %q", got, tc.detail) + } + if got := response.Get("output.0.action.query").String(); got != "lindorm vector" { + t.Fatalf("search query = %q", got) + } + if got := response.Get("output.0.results.0.encrypted_content").String(); got != "ENC_A" { + t.Fatalf("search replay content = %q", got) + } + if got := response.Get("usage.output_tokens").Int(); got != 12 { + t.Fatalf("output_tokens = %d, want 12", got) + } + } + t.Run("stream", func(t *testing.T) { + terminals := 0 + for _, output := range translateClaudeResponsesStreamThroughRegistry(chunks) { + event, data := parseClaudeResponsesSSEEvent(t, output) + if event != "response.completed" && event != "response.incomplete" { + continue + } + terminals++ + if want := "response." + tc.status; event != want { + t.Fatalf("terminal = %q, want %q", event, want) + } + check(t, data.Get("response")) + } + if terminals != 1 { + t.Fatalf("terminal count = %d, want 1", terminals) + } + }) + t.Run("buffered", func(t *testing.T) { + output := ConvertClaudeResponseToOpenAIResponsesNonStream( + context.Background(), "claude-test", nil, nil, bytes.Join(chunks, []byte("\n")), nil) + check(t, gjson.ParseBytes(output)) + }) + }) + } +} diff --git a/internal/translator/claude/openai/responses/claude_openai-responses_response.go b/internal/translator/claude/openai/responses/claude_openai-responses_response.go index 8fe68caf5d3..1a8a6e6990d 100644 --- a/internal/translator/claude/openai/responses/claude_openai-responses_response.go +++ b/internal/translator/claude/openai/responses/claude_openai-responses_response.go @@ -164,8 +164,14 @@ func (u claudeResponsesUsageTokens) OpenAIResponsesUsage() (inputTokens, outputT } func claudeResponsesIncompleteDetails(stopReason string) ([]byte, bool) { - if strings.EqualFold(strings.TrimSpace(stopReason), "max_tokens") { + switch strings.ToLower(strings.TrimSpace(stopReason)) { + case "max_tokens": return []byte(`{"reason":"max_output_tokens"}`), true + case "pause_turn": + // Anthropic's server-tool iteration pause is unfinished, not a token limit: + // https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons#pause_turn + // Responses has no matching incomplete reason, so keep its nullable details null. + return []byte(`null`), true } return nil, false } From 2044a01f422998de79a5da8015141b878886534d Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Sat, 3 Oct 2026 04:03:55 +0800 Subject: [PATCH 009/142] fix(codex): preserve web search sources in responses request include - Retain `web_search_call.action.sources` alongside `reasoning.encrypted_content` in Codex request include field - Avoid payload re-encoding when include array is already normalized Closes: #6251 --- .../codex_openai-responses_request.go | 26 ++++- .../codex_openai-responses_request_test.go | 83 ++++++++++++++++ .../codex_openai-responses_response_test.go | 99 +++++++++++++++++++ 3 files changed, 204 insertions(+), 4 deletions(-) diff --git a/internal/translator/codex/openai/responses/codex_openai-responses_request.go b/internal/translator/codex/openai/responses/codex_openai-responses_request.go index c2ac3abf4f8..447e5e72a69 100644 --- a/internal/translator/codex/openai/responses/codex_openai-responses_request.go +++ b/internal/translator/codex/openai/responses/codex_openai-responses_request.go @@ -117,12 +117,30 @@ func setCodexRequiredBool(rawJSON []byte, path string, value bool) []byte { func setCodexRequiredInclude(rawJSON []byte) []byte { current := gjson.GetBytes(rawJSON, "include") - values := current.Array() - if current.IsArray() && len(values) == 1 && values[0].Type == gjson.String && values[0].String() == "reasoning.encrypted_content" { - return rawJSON + includeSources := false + if current.IsArray() { + values := current.Array() + for _, value := range values { + if value.Type == gjson.String && value.String() == "web_search_call.action.sources" { + includeSources = true + break + } + } + if !includeSources && len(values) == 1 && values[0].Type == gjson.String && values[0].String() == "reasoning.encrypted_content" { + return rawJSON + } + if includeSources && len(values) == 2 && + values[0].Type == gjson.String && values[0].String() == "reasoning.encrypted_content" && + values[1].Type == gjson.String && values[1].String() == "web_search_call.action.sources" { + return rawJSON + } } - updated, errSet := sjson.SetRawBytes(rawJSON, "include", []byte(`["reasoning.encrypted_content"]`)) + encoded := []byte(`["reasoning.encrypted_content"]`) + if includeSources { + encoded = []byte(`["reasoning.encrypted_content","web_search_call.action.sources"]`) + } + updated, errSet := sjson.SetRawBytes(rawJSON, "include", encoded) if errSet != nil { return rawJSON } diff --git a/internal/translator/codex/openai/responses/codex_openai-responses_request_test.go b/internal/translator/codex/openai/responses/codex_openai-responses_request_test.go index b55913830d6..907a1f6159c 100644 --- a/internal/translator/codex/openai/responses/codex_openai-responses_request_test.go +++ b/internal/translator/codex/openai/responses/codex_openai-responses_request_test.go @@ -293,6 +293,89 @@ func TestConvertOpenAIResponsesRequestToCodexNormalizesRequiredFields(t *testing } } +func TestConvertOpenAIResponsesRequestToCodex_PreservesWebSearchSourcesInclude(t *testing.T) { + reasoningOnly := []string{"reasoning.encrypted_content"} + reasoningAndSources := []string{"reasoning.encrypted_content", "web_search_call.action.sources"} + tests := []struct { + name string + includeJSON string + want []string + }{ + {name: "missing include", includeJSON: "", want: reasoningOnly}, + {name: "null include", includeJSON: "null", want: reasoningOnly}, + {name: "string include", includeJSON: `"web_search_call.action.sources"`, want: reasoningOnly}, + {name: "object include", includeJSON: `{"web_search_call.action.sources":true}`, want: reasoningOnly}, + {name: "non-string entries", includeJSON: `[42,true]`, want: reasoningOnly}, + {name: "empty array", includeJSON: `[]`, want: reasoningOnly}, + {name: "sources alone", includeJSON: `["web_search_call.action.sources"]`, want: reasoningAndSources}, + {name: "reasoning then sources", includeJSON: `["reasoning.encrypted_content","web_search_call.action.sources"]`, want: reasoningAndSources}, + {name: "sources before reasoning", includeJSON: `["web_search_call.action.sources","reasoning.encrypted_content"]`, want: reasoningAndSources}, + {name: "duplicate sources", includeJSON: `["web_search_call.action.sources","web_search_call.action.sources"]`, want: reasoningAndSources}, + {name: "unsupported entries filtered", includeJSON: `["file_search_call.results","web_search_call.action.sources","code_interpreter_call.outputs"]`, want: reasoningAndSources}, + {name: "non-string entries alongside sources", includeJSON: `[42,"web_search_call.action.sources",null]`, want: reasoningAndSources}, + } + + for _, stream := range []bool{false, true} { + for _, tt := range tests { + t.Run(fmt.Sprintf("stream_%v/%s", stream, tt.name), func(t *testing.T) { + inputJSON := []byte(`{"model":"gpt-5.6","input":[{"type":"message","role":"user","content":"hi"}]}`) + if tt.includeJSON != "" { + var errSet error + inputJSON, errSet = sjson.SetRawBytes(inputJSON, "include", []byte(tt.includeJSON)) + if errSet != nil { + t.Fatalf("setting include: %v", errSet) + } + } + + before := string(inputJSON) + output := ConvertOpenAIResponsesRequestToCodex("gpt-5.6", inputJSON, stream) + if string(inputJSON) != before { + t.Fatalf("caller input changed:\n got: %s\nwant: %s", inputJSON, before) + } + got := gjson.GetBytes(output, "include").Array() + if len(got) != len(tt.want) { + t.Fatalf("include = %s, want %v", gjson.GetBytes(output, "include").Raw, tt.want) + } + for i, want := range tt.want { + if got[i].Type != gjson.String || got[i].String() != want { + t.Fatalf("include[%d] = %s, want %q; include = %s", i, got[i].Raw, want, gjson.GetBytes(output, "include").Raw) + } + } + }) + } + } +} + +func TestConvertOpenAIResponsesRequestToCodex_WebSearchToolDoesNotOptIntoSources(t *testing.T) { + inputJSON := []byte(`{"model":"gpt-5.6","input":"find python asyncio docs","tools":[{"type":"web_search"}],"tool_choice":"required"}`) + + output := ConvertOpenAIResponsesRequestToCodex("gpt-5.6", inputJSON, true) + + include := gjson.GetBytes(output, "include").Array() + if len(include) != 1 || include[0].Type != gjson.String || include[0].String() != "reasoning.encrypted_content" { + t.Fatalf("include = %s, want reasoning.encrypted_content only", gjson.GetBytes(output, "include").Raw) + } +} + +func TestConvertOpenAIResponsesRequestToCodexReusesNormalizedPayloadWithSources(t *testing.T) { + for _, includeJSON := range []string{ + `["reasoning.encrypted_content","web_search_call.action.sources"]`, + `[ "reasoning.encrypted_content" , "web_search_call.action.sources" ]`, + `[ "reasoning.encrypted_content" ]`, + } { + inputJSON := []byte(`{"model":"gpt-5.6","stream":true,"store":false,"parallel_tool_calls":true,"include":` + includeJSON + `,"service_tier":"priority","input":[{"type":"message","role":"user","content":"hello"}]}`) + + output := ConvertOpenAIResponsesRequestToCodex("gpt-5.6", inputJSON, true) + + if &output[0] != &inputJSON[0] { + t.Fatalf("normalized request payload with include %s was copied", includeJSON) + } + if string(output) != string(inputJSON) { + t.Fatalf("normalized request changed:\n got: %s\nwant: %s", output, inputJSON) + } + } +} + func TestConvertOpenAIResponsesRequestToCodex_FiltersPromptCacheRetention(t *testing.T) { inputJSON := []byte(`{ "model": "gpt-5.6-terra", diff --git a/internal/translator/codex/openai/responses/codex_openai-responses_response_test.go b/internal/translator/codex/openai/responses/codex_openai-responses_response_test.go index 8295ba142de..e0b525acbb9 100644 --- a/internal/translator/codex/openai/responses/codex_openai-responses_response_test.go +++ b/internal/translator/codex/openai/responses/codex_openai-responses_response_test.go @@ -38,6 +38,105 @@ func TestConvertCodexResponseToOpenAIResponsesNonStreamIncomplete(t *testing.T) } } +func TestConvertCodexResponseToOpenAIResponses_PreservesWebSearchSources(t *testing.T) { + const searchItem = `{"id":"ws_fixture_0123456789abcdef0123456789abcdef","type":"web_search_call","status":"completed","action":{"type":"search","queries":["python asyncio documentation"],"query":"python asyncio documentation","sources":[{"type":"url","url":"https://docs.python.org/3.13/library/asyncio.html"},{"type":"url","url":"https://docs.python.org/3/library/asyncio-task.html?highlight=n"}]}}` + const messageItem = `{"id":"msg_fixture_0123456789abcdef0123456789abcdef","type":"message","role":"assistant","status":"completed","content":[{"type":"output_text","text":"Python docs","annotations":[{"type":"url_citation","start_index":0,"end_index":11,"title":"asyncio","url":"https://docs.python.org/3/library/asyncio.html?trk=article-ssr-frontend-pulse_little-text-block&utm_source=openai"}]}]}` + + done := []byte(`data: {"type":"response.output_item.done","output_index":0,"item":` + searchItem + "}") + outputs := ConvertCodexResponseToOpenAIResponses(context.Background(), "gpt-6-luna", nil, nil, done, nil) + if len(outputs) != 1 { + t.Fatalf("output_item.done outputs = %d, want 1", len(outputs)) + } + if got := gjson.GetBytes(outputs[0], "item.id").String(); got != "ws_fixture_0123456789abcdef0123456789abcdef" { + t.Fatalf("item.id = %q, want ws_fixture_0123456789abcdef0123456789abcdef", got) + } + sources := gjson.GetBytes(outputs[0], "item.action.sources").Array() + if len(sources) != 2 { + t.Fatalf("item.action.sources = %s, want 2 entries", gjson.GetBytes(outputs[0], "item.action.sources").Raw) + } + if got := sources[0].Get("url").String(); got != "https://docs.python.org/3.13/library/asyncio.html" { + t.Fatalf("sources[0].url = %q", got) + } + if got := sources[1].Get("url").String(); got != "https://docs.python.org/3/library/asyncio-task.html?highlight=n" { + t.Fatalf("sources[1].url = %q", got) + } + + completed := []byte(`data: {"type":"response.completed","response":{"id":"resp_04f9","status":"completed","output":[` + searchItem + "," + messageItem + "]}}") + outputs = ConvertCodexResponseToOpenAIResponses(context.Background(), "gpt-6-luna", nil, nil, completed, nil) + if len(outputs) != 1 { + t.Fatalf("response.completed outputs = %d, want 1", len(outputs)) + } + if got := gjson.GetBytes(outputs[0], "response.output.0.action.sources.1.url").String(); got != "https://docs.python.org/3/library/asyncio-task.html?highlight=n" { + t.Fatalf("response.output.0.action.sources.1.url = %q", got) + } + if got := gjson.GetBytes(outputs[0], "response.output.1.id").String(); got != "msg_fixture_0123456789abcdef0123456789abcdef" { + t.Fatalf("response.output.1.id = %q, want msg_fixture_0123456789abcdef0123456789abcdef", got) + } + if got := gjson.GetBytes(outputs[0], "response.output.1.content.0.annotations.0.url").String(); got != "https://docs.python.org/3/library/asyncio.html?trk=article-ssr-frontend-pulse_little-text-block&utm_source=openai" { + t.Fatalf("citation url = %q", got) + } +} + +func TestConvertCodexResponseToOpenAIResponsesNonStream_PreservesWebSearchSources(t *testing.T) { + raw := []byte(`{"type":"response.completed","response":{"id":"resp_04f9","status":"completed","output":[{"id":"ws_fixture_0123456789abcdef0123456789abcdef","type":"web_search_call","status":"completed","action":{"type":"search","query":"python asyncio documentation","sources":[{"type":"url","url":"https://docs.python.org/3.13/library/asyncio.html"},{"type":"url","url":"https://docs.python.org/3/library/asyncio-task.html?highlight=n"}]}},{"id":"msg_fixture_0123456789abcdef0123456789abcdef","type":"message","role":"assistant","status":"completed","content":[{"type":"output_text","text":"Python docs","annotations":[{"type":"url_citation","start_index":0,"end_index":11,"title":"asyncio","url":"https://docs.python.org/3/library/asyncio.html?trk=article-ssr-frontend-pulse_little-text-block&utm_source=openai"}]}]}]}}`) + + out := ConvertCodexResponseToOpenAIResponsesNonStream(context.Background(), "gpt-6-luna", nil, nil, raw, nil) + + if got := gjson.GetBytes(out, "output.0.id").String(); got != "ws_fixture_0123456789abcdef0123456789abcdef" { + t.Fatalf("output.0.id = %q, want ws_fixture_0123456789abcdef0123456789abcdef", got) + } + sources := gjson.GetBytes(out, "output.0.action.sources").Array() + if len(sources) != 2 { + t.Fatalf("output.0.action.sources = %s, want 2 entries", gjson.GetBytes(out, "output.0.action.sources").Raw) + } + if got := sources[0].Get("url").String(); got != "https://docs.python.org/3.13/library/asyncio.html" { + t.Fatalf("sources[0].url = %q", got) + } + if got := sources[1].Get("url").String(); got != "https://docs.python.org/3/library/asyncio-task.html?highlight=n" { + t.Fatalf("sources[1].url = %q", got) + } + if got := gjson.GetBytes(out, "output.1.content.0.annotations.0.type").String(); got != "url_citation" { + t.Fatalf("annotation type = %q, want url_citation", got) + } + if got := gjson.GetBytes(out, "output.1.content.0.annotations.0.url").String(); got != "https://docs.python.org/3/library/asyncio.html?trk=article-ssr-frontend-pulse_little-text-block&utm_source=openai" { + t.Fatalf("citation url = %q", got) + } +} + +func TestConvertCodexResponseToOpenAIResponses_MissingSourcesStayAbsentWithCitation(t *testing.T) { + const searchItem = `{"id":"ws_missing","type":"web_search_call","status":"completed","action":{"type":"search","query":"python asyncio documentation"}}` + const messageItem = `{"id":"msg_cited","type":"message","role":"assistant","status":"completed","content":[{"type":"output_text","text":"Python docs","annotations":[{"type":"url_citation","start_index":0,"end_index":11,"title":"asyncio","url":"https://docs.python.org/3/library/asyncio.html?trk=article-ssr-frontend-pulse_little-text-block&utm_source=openai"}]}]}` + + done := []byte(`data: {"type":"response.output_item.done","output_index":0,"item":` + searchItem + "}") + outputs := ConvertCodexResponseToOpenAIResponses(context.Background(), "gpt-6-luna", nil, nil, done, nil) + if len(outputs) != 1 { + t.Fatalf("output_item.done outputs = %d, want 1", len(outputs)) + } + if gjson.GetBytes(outputs[0], "item.action.sources").Exists() { + t.Fatalf("sources should not be fabricated on output_item.done: %s", outputs[0]) + } + + completed := []byte(`data: {"type":"response.completed","response":{"id":"resp_missing","status":"completed","output":[` + searchItem + "," + messageItem + "]}}") + outputs = ConvertCodexResponseToOpenAIResponses(context.Background(), "gpt-6-luna", nil, nil, completed, nil) + if len(outputs) != 1 { + t.Fatalf("response.completed outputs = %d, want 1", len(outputs)) + } + if gjson.GetBytes(outputs[0], "response.output.0.action.sources").Exists() { + t.Fatalf("sources should not be fabricated on response.completed: %s", outputs[0]) + } + if got := gjson.GetBytes(outputs[0], "response.output.1.content.0.annotations.0.type").String(); got != "url_citation" { + t.Fatalf("annotation type = %q, want url_citation; payload=%s", got, outputs[0]) + } + + out := ConvertCodexResponseToOpenAIResponsesNonStream(context.Background(), "gpt-6-luna", nil, nil, []byte(`{"type":"response.completed","response":{"id":"resp_missing","status":"completed","output":[`+searchItem+","+messageItem+"]}}"), nil) + if gjson.GetBytes(out, "output.0.action.sources").Exists() { + t.Fatalf("sources should not be fabricated on non-stream response: %s", out) + } + if got := gjson.GetBytes(out, "output.1.content.0.annotations.0.url").String(); got != "https://docs.python.org/3/library/asyncio.html?trk=article-ssr-frontend-pulse_little-text-block&utm_source=openai" { + t.Fatalf("citation url = %q", got) + } +} + func TestApplyPatchResponsesActualRequestGatesNativeCodex(t *testing.T) { original := []byte(`{"tools":[{"type":"custom","name":"apply_patch"}]}`) bridged, errNormalize := translatorcommon.NormalizeApplyPatchResponsesRequest(original) From 5dbce4f3fbfd5ed1d83b59dc7b972ed17ce27e7e Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Sat, 3 Oct 2026 10:48:07 +0800 Subject: [PATCH 010/142] perf(claude): prefilter JSON payloads before diagnostic walks - Add ASCII pre-filter to skip expensive gjson traversals for title helper and 1h TTL checks - Check raw bytes for target keywords before initiating full JSON walks - Fall back to full inspection when printable ASCII Unicode escapes are detected Closes: #6291 --- .../executor/helps/claude_diagnostics.go | 10 +- .../executor/helps/claude_json_prefilter.go | 50 ++++++ .../helps/claude_json_prefilter_fuzz_test.go | 147 ++++++++++++++++++ .../helps/claude_json_prefilter_test.go | 137 ++++++++++++++++ 4 files changed, 343 insertions(+), 1 deletion(-) create mode 100644 internal/runtime/executor/helps/claude_json_prefilter.go create mode 100644 internal/runtime/executor/helps/claude_json_prefilter_fuzz_test.go create mode 100644 internal/runtime/executor/helps/claude_json_prefilter_test.go diff --git a/internal/runtime/executor/helps/claude_diagnostics.go b/internal/runtime/executor/helps/claude_diagnostics.go index 3c83b9733fb..c43fe6cfed8 100644 --- a/internal/runtime/executor/helps/claude_diagnostics.go +++ b/internal/runtime/executor/helps/claude_diagnostics.go @@ -441,6 +441,12 @@ func isClaudeTitleHelperInstruction(body []byte) bool { } func isClaudeTitleHelperRequest(body []byte) bool { + // Without an output_config key the request is a helper only if one of the + // system title instructions below appears, so skip the walks when none can. + if !jsonMayContainASCII(body, "output_config", "naming a coding session", "Return a short title", + "Write the title in the predominant language") { + return false + } props := gjson.GetBytes(body, "output_config.format.schema.properties") if props.Exists() { if props.Get("title").Exists() && len(props.Map()) == 1 { @@ -527,7 +533,9 @@ func IsClaudeSubagentRequest(headers http.Header, body []byte) bool { // ClaudePayloadHas1hTTL reports whether the request payload contains any cache_control // block with ttl set to "1h". func ClaudePayloadHas1hTTL(payload []byte) bool { - if len(payload) == 0 || !gjson.ValidBytes(payload) { + // A ttl of "1h" is the JSON string "1h"; its quotes are structural and never + // escaped, so a payload without that token cannot match. + if len(payload) == 0 || !jsonMayContainASCII(payload, `"1h"`) || !gjson.ValidBytes(payload) { return false } has1h := false diff --git a/internal/runtime/executor/helps/claude_json_prefilter.go b/internal/runtime/executor/helps/claude_json_prefilter.go new file mode 100644 index 00000000000..32509c7d9ed --- /dev/null +++ b/internal/runtime/executor/helps/claude_json_prefilter.go @@ -0,0 +1,50 @@ +package helps + +import "bytes" + +// jsonMayContainASCII reports whether decoding the JSON document body could +// yield a key or string value containing any of needles. +// +// It lets the request classifiers below skip their gjson walks: a Claude Code +// request body carries the whole conversation (often several MB), and each +// walk re-scans it. bytes.Contains is far cheaper than a gjson walk. +// +// Every needle must be printable ASCII without '\\' or '/' (JSON may spell +// '/' as `\/`). A '"' may only stand at +// either end of a needle, where it matches a structural string delimiter +// (`"1h"` matches the whole string value 1h). JSON can only +// spell such a character as itself or as a \u00XX escape, so when body holds +// no \u escape of a printable ASCII character, a needle that is absent from +// the raw bytes is absent from every decoded string too. If such an escape is +// present the function answers true and the caller falls back to its full +// walk, so the result never changes, only the cost. +func jsonMayContainASCII(body []byte, needles ...string) bool { + if hasPrintableASCIIUnicodeEscape(body) { + return true + } + for _, needle := range needles { + if bytes.Contains(body, []byte(needle)) { + return true + } + } + return false +} + +// hasPrintableASCIIUnicodeEscape reports whether body contains a \u00XX +// escape whose first hex digit is 2-7, i.e. a printable ASCII character. It +// errs only toward "yes": it also matches DEL (7F), malformed escapes such as +// a 2-7 digit followed by a non-hex character, an escape truncated after that +// digit, and an escaped backslash followed by literal text such as `\\u0041`. +// Each of those only makes the caller fall back to a full walk. +func hasPrintableASCIIUnicodeEscape(body []byte) bool { + for rest := body; ; { + i := bytes.Index(rest, []byte(`\u00`)) + if i < 0 || i+4 >= len(rest) { + return false + } + if c := rest[i+4]; c >= '2' && c <= '7' { + return true + } + rest = rest[i+4:] + } +} diff --git a/internal/runtime/executor/helps/claude_json_prefilter_fuzz_test.go b/internal/runtime/executor/helps/claude_json_prefilter_fuzz_test.go new file mode 100644 index 00000000000..295e1e07da2 --- /dev/null +++ b/internal/runtime/executor/helps/claude_json_prefilter_fuzz_test.go @@ -0,0 +1,147 @@ +package helps + +import ( + "strings" + "testing" + + "github.com/tidwall/gjson" +) + +// referenceIsClaudeTitleHelperRequest is isClaudeTitleHelperRequest without +// the jsonMayContainASCII pre-filter (the v8.0.11 implementation). +func referenceIsClaudeTitleHelperRequest(body []byte) bool { + props := gjson.GetBytes(body, "output_config.format.schema.properties") + if props.Exists() { + if props.Get("title").Exists() && len(props.Map()) == 1 { + return isClaudeTitleHelperInstruction(body) + } + return false + } + matchesSystemTitleInstruction := func(t string) bool { + return strings.Contains(t, "naming a coding session") || + strings.Contains(t, "Return a short title") || + strings.Contains(t, "Write the title in the predominant language") + } + system := gjson.GetBytes(body, "system") + if system.IsArray() { + for _, part := range system.Array() { + if matchesSystemTitleInstruction(part.Get("text").String()) { + return true + } + } + } else if matchesSystemTitleInstruction(system.String()) { + return true + } + messages := gjson.GetBytes(body, "messages") + if messages.IsArray() { + for _, msg := range messages.Array() { + if msg.Get("role").String() == "system" { + content := msg.Get("content") + if content.IsArray() { + for _, part := range content.Array() { + if matchesSystemTitleInstruction(part.Get("text").String()) { + return true + } + } + } else if matchesSystemTitleInstruction(content.String()) { + return true + } + } + } + } + return false +} + +// referenceClaudePayloadHas1hTTL is ClaudePayloadHas1hTTL without the +// jsonMayContainASCII pre-filter (the v8.0.11 implementation). +func referenceClaudePayloadHas1hTTL(payload []byte) bool { + if len(payload) == 0 || !gjson.ValidBytes(payload) { + return false + } + has1h := false + checkBlock := func(item gjson.Result) bool { + cc := item.Get("cache_control") + if cc.IsObject() && cc.Get("ttl").String() == "1h" { + has1h = true + return false + } + return true + } + for _, key := range []string{"tools", "system"} { + if arr := gjson.GetBytes(payload, key); arr.IsArray() { + arr.ForEach(func(_, item gjson.Result) bool { + return checkBlock(item) + }) + if has1h { + return true + } + } + } + if messages := gjson.GetBytes(payload, "messages"); messages.IsArray() { + messages.ForEach(func(_, msg gjson.Result) bool { + content := msg.Get("content") + if content.IsArray() { + content.ForEach(func(_, item gjson.Result) bool { + return checkBlock(item) + }) + } + return !has1h + }) + } + return has1h +} + +// bs is one backslash; the seeds below build JSON escapes from it. +const bs = `\` + +var prefilterSeeds = []string{ + ``, + `{}`, + `not json`, + `{"system":"naming a coding session"}`, + `{"system":"naming a` + bs + `u0020coding session"}`, + `{"system":[{"text":"Return a short ` + bs + `u0074itle"}]}`, + `{"system":"Return a short title`, + `{"messages":[{"role":"system","content":[{"text":"Write the title in the predominant language"}]}]}`, + `{"messages":[{"role":"system","content":"naming a coding session"}`, + `{"output_config":{"format":{"schema":{"properties":{"title":{}}}}},"messages":[{"content":""}]}`, + `{"output_` + bs + `u0063onfig":{"format":{"schema":{"properties":{"title":{}}}}},"system":"Return a short title"}`, + `{"output_config":{"format":{"schema":{"properties":{"title":{},"x":{}}}}}}`, + `{"system":"` + bs + `ud83d` + bs + `ude00 naming a coding session"}`, + `{"system":"` + bs + `/naming a coding session` + bs + `"}`, + `{"system":"` + bs + bs + `u0041 naming"}`, + `{"system":"` + bs + `u00`, + `{"messages":[{"content":[{"cache_control":{"ttl":"1h"}}]}]}`, + `{"messages":[{"content":[{"cache_control":{"ttl":"` + bs + `u0031h"}}]}]}`, + `{"tools":[{"cache_control":{"ttl":"1` + bs + `u0068"}}]}`, + `{"system":[{"cache_control":{"ttl":"5m"}}],"note":"1h"}`, + `{"tools":[{"cache_control":{"ttl":"1h"}}]}`, + `{"messages":[{"content":[{"cache_control":{"ttl":1}}]}]}`, +} + +func checkPrefilterEquivalence(t *testing.T, body []byte) { + t.Helper() + if got, want := isClaudeTitleHelperRequest(body), referenceIsClaudeTitleHelperRequest(body); got != want { + t.Fatalf("isClaudeTitleHelperRequest(%q) = %v, reference %v", body, got, want) + } + if got, want := ClaudePayloadHas1hTTL(body), referenceClaudePayloadHas1hTTL(body); got != want { + t.Fatalf("ClaudePayloadHas1hTTL(%q) = %v, reference %v", body, got, want) + } +} + +func TestPrefilterMatchesReferenceOnSeeds(t *testing.T) { + for _, seed := range prefilterSeeds { + checkPrefilterEquivalence(t, []byte(seed)) + } +} + +// FuzzPrefilterMatchesReference checks the pre-filtered classifiers against +// the full walks on arbitrary bytes: go test -fuzz FuzzPrefilterMatchesReference +func FuzzPrefilterMatchesReference(f *testing.F) { + for _, seed := range prefilterSeeds { + f.Add([]byte(seed)) + } + f.Fuzz(func(t *testing.T, body []byte) { + checkPrefilterEquivalence(t, body) + }) +} diff --git a/internal/runtime/executor/helps/claude_json_prefilter_test.go b/internal/runtime/executor/helps/claude_json_prefilter_test.go new file mode 100644 index 00000000000..d85e887247f --- /dev/null +++ b/internal/runtime/executor/helps/claude_json_prefilter_test.go @@ -0,0 +1,137 @@ +package helps + +import ( + "fmt" + "strings" + "testing" +) + +func TestJSONMayContainASCII(t *testing.T) { + tests := []struct { + name string + body string + needles []string + want bool + }{ + {"absent", `{"system":"hello"}`, []string{"naming a coding session"}, false}, + {"present", `{"system":"naming a coding session"}`, []string{"naming a coding session"}, true}, + {"any needle", `{"output_config":{}}`, []string{"naming", "output_config"}, true}, + {"escaped space falls back", `{"system":"naming a\u0020coding session"}`, []string{"naming a coding session"}, true}, + {"escaped letter falls back", `{"s":"n\u0061ming"}`, []string{"naming"}, true}, + {"upper hex falls back", `{"s":"\u004E"}`, []string{"N"}, true}, + {"escaped backslash is conservative", `{"s":"\\u0041"}`, []string{"zzz"}, true}, + {"control escape keeps shortcut", `{"s":"a\u001bbé"}`, []string{"naming"}, false}, + {"truncated escape", `{"s":"\u00`, []string{"naming"}, false}, + {"quoted value", `{"ttl":"1h"}`, []string{`"1h"`}, true}, + {"quoted value absent", `{"ttl":"5m","note":"11h"}`, []string{`"1h"`}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := jsonMayContainASCII([]byte(tt.body), tt.needles...); got != tt.want { + t.Fatalf("jsonMayContainASCII(%s, %q) = %v, want %v", tt.body, tt.needles, got, tt.want) + } + }) + } +} + +// The pre-filters must never change an answer, including when the matched +// text is spelled with \u escapes. +func TestPrefilteredClassifiersKeepEscapedMatches(t *testing.T) { + escapedTitle := `{"model":"m","system":[{"type":"text","text":"You are naming a\u0020coding session."}],` + + `"messages":[{"role":"user","content":"hi"}]}` + if !isClaudeTitleHelperRequest([]byte(escapedTitle)) { + t.Fatal("escaped system title instruction must still be detected") + } + plainTitle := `{"model":"m","system":"Return a short title for this.","messages":[{"role":"user","content":"hi"}]}` + if !isClaudeTitleHelperRequest([]byte(plainTitle)) { + t.Fatal("plain system title instruction must be detected") + } + schemaTitle := `{"model":"m","output_config":{"format":{"schema":{"properties":{"title":{"type":"string"}}}}},` + + `"messages":[{"role":"user","content":"x"}]}` + if !isClaudeTitleHelperRequest([]byte(schemaTitle)) { + t.Fatal("title schema request must be detected") + } + ordinary := `{"model":"m","system":"You are Claude Code.","messages":[{"role":"user","content":"Return a short answer"}]}` + if isClaudeTitleHelperRequest([]byte(ordinary)) { + t.Fatal("ordinary request must not be a title helper") + } + escaped1h := `{"messages":[{"role":"user","content":[{"type":"text","text":"x","cache_control":{"type":"ephemeral","ttl":"\u0031h"}}]}]}` + if !ClaudePayloadHas1hTTL([]byte(escaped1h)) { + t.Fatal("escaped 1h ttl must still be detected") + } + fiveMinutes := `{"messages":[{"role":"user","content":[{"type":"text","text":"took 11h","cache_control":{"type":"ephemeral","ttl":"5m"}}]}]}` + if ClaudePayloadHas1hTTL([]byte(fiveMinutes)) { + t.Fatal("5m ttl must not count as 1h") + } +} + +// largeClaudeCodeBody builds a Claude Code style request with n tool round +// trips, about 2.2 KB each, ending with the top-level keys Claude Code sends +// after messages. +func largeClaudeCodeBody(n int) []byte { + var b strings.Builder + b.WriteString(`{"model":"claude-opus-5-5","messages":[`) + output := strings.Repeat(`line of tool output with \"quotes\", tabs\t and a \u001b[0m reset `, 30) + for i := 0; i < n; i++ { + if i > 0 { + b.WriteByte(',') + } + fmt.Fprintf(&b, `{"role":"assistant","content":[{"type":"tool_use","id":"toolu_%d","name":"Bash","input":{"command":"ls %d"}}]},`, i, i) + fmt.Fprintf(&b, `{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_%d","content":"%s"}]}`, i, output) + } + b.WriteString(`],"system":[{"type":"text","text":"x-anthropic-billing-header: cc_version=2.1.286;"},`) + b.WriteString(`{"type":"text","text":"You are Claude Code.","cache_control":{"type":"ephemeral","ttl":"5m"}}],`) + b.WriteString(`"tools":[{"name":"Bash","input_schema":{"type":"object"}}],"metadata":{"user_id":"u"},`) + b.WriteString(`"max_tokens":64000,"thinking":{"type":"adaptive"},"stream":true}`) + return []byte(b.String()) +} + +func BenchmarkIsClaudeProbeOrHelperRequestLarge(b *testing.B) { + body := largeClaudeCodeBody(1500) + b.SetBytes(int64(len(body))) + b.ResetTimer() + for i := 0; i < b.N; i++ { + if IsClaudeProbeOrHelperRequest(body) { + b.Fatal("ordinary request classified as probe or helper") + } + } +} + +func BenchmarkClaudePayloadHas1hTTLLarge(b *testing.B) { + body := largeClaudeCodeBody(1500) + b.SetBytes(int64(len(body))) + b.ResetTimer() + for i := 0; i < b.N; i++ { + if ClaudePayloadHas1hTTL(body) { + b.Fatal("5m payload reported as 1h") + } + } +} + +// The worst cases: a printable-ASCII escape forces the full walk, so the +// pre-filter's scan is pure overhead. +func BenchmarkClaudePayloadHas1hTTLLargeEscapeFallback(b *testing.B) { + body := largeClaudeCodeBody(1500) + body = append([]byte(`{"note":"\u0041",`), body[1:]...) + b.SetBytes(int64(len(body))) + b.ResetTimer() + for i := 0; i < b.N; i++ { + if ClaudePayloadHas1hTTL(body) { + b.Fatal("5m payload reported as 1h") + } + } +} + +func BenchmarkClaudePayloadHas1hTTLLargeEscapeFallbackLate(b *testing.B) { + body := largeClaudeCodeBody(1500) + if len(body) > 1 && body[len(body)-1] == '}' { + body = append(body[:len(body)-1], []byte(`,"late_escape":"\u0041"}`)...) + } + b.SetBytes(int64(len(body))) + b.ResetTimer() + for i := 0; i < b.N; i++ { + if ClaudePayloadHas1hTTL(body) { + b.Fatal("5m payload reported as 1h") + } + } +} From e3abd9ae8e3d0e844cd8a6ef5b4fe2b421f482c3 Mon Sep 17 00:00:00 2001 From: sususu Date: Sat, 3 Oct 2026 14:21:20 +0800 Subject: [PATCH 011/142] fix(antigravity): replace retired Claude 4.6 models with 5.5 --- internal/registry/models/models.json | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/internal/registry/models/models.json b/internal/registry/models/models.json index 4ca36db6e07..b7b406a008f 100644 --- a/internal/registry/models/models.json +++ b/internal/registry/models/models.json @@ -3979,13 +3979,13 @@ ], "antigravity": [ { - "id": "claude-opus-4-6-thinking", + "id": "claude-opus-5-5-thinking", "object": "model", "owned_by": "antigravity", "type": "antigravity", - "display_name": "Claude Opus 4.6 (Thinking)", - "name": "claude-opus-4-6-thinking", - "description": "Claude Opus 4.6 (Thinking)", + "display_name": "Claude Opus 5.5 (Thinking)", + "name": "claude-opus-5-5-thinking", + "description": "Claude Opus 5.5 (Thinking)", "context_length": 200000, "max_completion_tokens": 64000, "thinking": { @@ -4003,13 +4003,13 @@ ] }, { - "id": "claude-sonnet-4-6", + "id": "claude-sonnet-5-5", "object": "model", "owned_by": "antigravity", "type": "antigravity", - "display_name": "Claude Sonnet 4.6 (Thinking)", - "name": "claude-sonnet-4-6", - "description": "Claude Sonnet 4.6 (Thinking)", + "display_name": "Claude Sonnet 5.5 (Thinking)", + "name": "claude-sonnet-5-5", + "description": "Claude Sonnet 5.5 (Thinking)", "context_length": 200000, "max_completion_tokens": 64000, "thinking": { From c575291ad31bc62dccfd3fc18fc49aae0b6008de Mon Sep 17 00:00:00 2001 From: sususu Date: Sat, 3 Oct 2026 14:22:45 +0800 Subject: [PATCH 012/142] fix(antigravity): align Claude 5.5 token limits with upstream catalog --- internal/registry/models/models.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/internal/registry/models/models.json b/internal/registry/models/models.json index b7b406a008f..f87a6ead4d8 100644 --- a/internal/registry/models/models.json +++ b/internal/registry/models/models.json @@ -3986,8 +3986,8 @@ "display_name": "Claude Opus 5.5 (Thinking)", "name": "claude-opus-5-5-thinking", "description": "Claude Opus 5.5 (Thinking)", - "context_length": 200000, - "max_completion_tokens": 64000, + "context_length": 1000000, + "max_completion_tokens": 128000, "thinking": { "min": 1024, "max": 64000, @@ -4010,8 +4010,8 @@ "display_name": "Claude Sonnet 5.5 (Thinking)", "name": "claude-sonnet-5-5", "description": "Claude Sonnet 5.5 (Thinking)", - "context_length": 200000, - "max_completion_tokens": 64000, + "context_length": 1000000, + "max_completion_tokens": 128000, "thinking": { "min": 1024, "max": 64000, From 6b037f614cc312d6845ddbfabb46c487cc313542 Mon Sep 17 00:00:00 2001 From: sususu Date: Sat, 3 Oct 2026 14:41:09 +0800 Subject: [PATCH 013/142] fix(antigravity): use actual Claude 5.5 high model IDs --- internal/registry/models/models.json | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/internal/registry/models/models.json b/internal/registry/models/models.json index f87a6ead4d8..462b77eee16 100644 --- a/internal/registry/models/models.json +++ b/internal/registry/models/models.json @@ -3979,13 +3979,13 @@ ], "antigravity": [ { - "id": "claude-opus-5-5-thinking", + "id": "claude-opus-5-5-high", "object": "model", "owned_by": "antigravity", "type": "antigravity", - "display_name": "Claude Opus 5.5 (Thinking)", - "name": "claude-opus-5-5-thinking", - "description": "Claude Opus 5.5 (Thinking)", + "display_name": "Claude Opus 5.5 (High)", + "name": "claude-opus-5-5-high", + "description": "Claude Opus 5.5 (High)", "context_length": 1000000, "max_completion_tokens": 128000, "thinking": { @@ -4003,13 +4003,13 @@ ] }, { - "id": "claude-sonnet-5-5", + "id": "claude-sonnet-5-5-high", "object": "model", "owned_by": "antigravity", "type": "antigravity", - "display_name": "Claude Sonnet 5.5 (Thinking)", - "name": "claude-sonnet-5-5", - "description": "Claude Sonnet 5.5 (Thinking)", + "display_name": "Claude Sonnet 5.5 (High)", + "name": "claude-sonnet-5-5-high", + "description": "Claude Sonnet 5.5 (High)", "context_length": 1000000, "max_completion_tokens": 128000, "thinking": { From 42d484f9a2ffdd295b705dc7ae9b8ad7dd7e1afc Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Sat, 3 Oct 2026 15:03:30 +0800 Subject: [PATCH 014/142] fix(claude): map request timeout status to timeout_error - Map `http.StatusRequestTimeout` (408) to Claude `timeout_error` response type Closes: #6298 --- sdk/api/handlers/claude/code_handlers.go | 2 +- .../claude/code_handlers_error_test.go | 79 +++++++++++++++++++ 2 files changed, 80 insertions(+), 1 deletion(-) diff --git a/sdk/api/handlers/claude/code_handlers.go b/sdk/api/handlers/claude/code_handlers.go index ab380078d5b..9a576e88647 100644 --- a/sdk/api/handlers/claude/code_handlers.go +++ b/sdk/api/handlers/claude/code_handlers.go @@ -459,7 +459,7 @@ func claudeErrorTypeFromStatus(status int) string { return "request_too_large" case http.StatusTooManyRequests: return "rate_limit_error" - case http.StatusGatewayTimeout: + case http.StatusRequestTimeout, http.StatusGatewayTimeout: return "timeout_error" case 529: return "overloaded_error" diff --git a/sdk/api/handlers/claude/code_handlers_error_test.go b/sdk/api/handlers/claude/code_handlers_error_test.go index 6fca0c0c201..fbed86859c8 100644 --- a/sdk/api/handlers/claude/code_handlers_error_test.go +++ b/sdk/api/handlers/claude/code_handlers_error_test.go @@ -4,6 +4,7 @@ import ( "errors" "net/http" "net/http/httptest" + "strings" "testing" "time" @@ -14,6 +15,84 @@ import ( "github.com/tidwall/gjson" ) +func TestClaudeErrorTypeFromStatus(t *testing.T) { + for _, tt := range []struct { + status int + want string + }{ + {http.StatusBadRequest, "invalid_request_error"}, + {http.StatusRequestTimeout, "timeout_error"}, + {http.StatusTooManyRequests, "rate_limit_error"}, + {http.StatusInternalServerError, "api_error"}, + {http.StatusGatewayTimeout, "timeout_error"}, + } { + t.Run(http.StatusText(tt.status), func(t *testing.T) { + if got := claudeErrorTypeFromStatus(tt.status); got != tt.want { + t.Fatalf("error.type = %q, want %q", got, tt.want) + } + }) + } +} + +func TestClaudeIncompleteStreamError(t *testing.T) { + const message = "stream error: stream disconnected before completion: stream closed before response.completed" + for _, streaming := range []bool{false, true} { + name := "JSON" + if streaming { + name = "committed SSE" + } + t.Run(name, func(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + handler := NewClaudeCodeAPIHandler(&handlers.BaseAPIHandler{}) + msg := &interfaces.ErrorMessage{ + StatusCode: http.StatusRequestTimeout, + Error: errors.New(message), + } + wantStatus := http.StatusRequestTimeout + if streaming { + c.Header("Content-Type", "text/event-stream") + _, _ = c.Writer.Write([]byte("event: message_start\ndata: {}\n\n")) + c.Writer.Flush() + errs := make(chan *interfaces.ErrorMessage, 1) + errs <- msg + close(errs) + handler.forwardClaudeStream(c, c.Writer, func(err error) { + if err != msg.Error { + t.Errorf("cancel error = %v, want %v", err, msg.Error) + } + }, nil, errs) + wantStatus = http.StatusOK + } else { + handler.WriteErrorResponse(c, msg) + } + if recorder.Code != wantStatus { + t.Fatalf("status = %d, want %d", recorder.Code, wantStatus) + } + body := recorder.Body.String() + if streaming { + const prefix = "event: error\ndata: " + if strings.Count(body, prefix) != 1 { + t.Fatalf("expected one terminal error event; body=%s", body) + } + _, body, _ = strings.Cut(body, prefix) + body = strings.TrimSpace(body) + } + if got := gjson.Get(body, "type").String(); got != "error" { + t.Errorf("type = %q, want error", got) + } + if got := gjson.Get(body, "error.type").String(); got != "timeout_error" { + t.Errorf("error.type = %q, want timeout_error", got) + } + if got := gjson.Get(body, "error.message").String(); got != message { + t.Errorf("error.message = %q, want %q", got, message) + } + }) + } +} + func TestClaudeErrorExtractsOpenAIStyleUpstreamJSON(t *testing.T) { handler := &ClaudeCodeAPIHandler{} msg := &interfaces.ErrorMessage{ From d4692663be0bbc370e53110f95fd319ce64f0f82 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Sat, 3 Oct 2026 15:16:34 +0800 Subject: [PATCH 015/142] fix(auth): snapshot auth before unlocking during registration and update - Snapshot scheduler auth copy while holding mutex lock to prevent concurrent mutation race with `MarkResult` Closes: #6300 --- sdk/cliproxy/auth/conductor_lifecycle.go | 14 +++- .../auth/conductor_lifecycle_race_test.go | 75 +++++++++++++++++++ 2 files changed, 87 insertions(+), 2 deletions(-) create mode 100644 sdk/cliproxy/auth/conductor_lifecycle_race_test.go diff --git a/sdk/cliproxy/auth/conductor_lifecycle.go b/sdk/cliproxy/auth/conductor_lifecycle.go index df2f5767883..6ce03dc3d67 100644 --- a/sdk/cliproxy/auth/conductor_lifecycle.go +++ b/sdk/cliproxy/auth/conductor_lifecycle.go @@ -116,12 +116,17 @@ func (m *Manager) Register(ctx context.Context, auth *Auth) (*Auth, error) { auth.Generation = 1 authClone := auth.Clone() m.auths[auth.ID] = authClone + // Snapshot before unlocking: MarkResult mutates the published auth in place. + var schedulerSnapshot *Auth + if m.scheduler != nil { + schedulerSnapshot = authClone.Clone() + } m.mu.Unlock() if !shouldDeferAPIKeyModelAliasRebuild(ctx) { m.rebuildAPIKeyModelAliasFromRuntimeConfig() } if m.scheduler != nil { - m.scheduler.upsertAuth(authClone.Clone()) + m.scheduler.upsertAuth(schedulerSnapshot) } m.structuralEpoch.Add(1) m.queueRefreshReschedule(auth.ID) @@ -266,12 +271,17 @@ func (m *Manager) updateInternal(ctx context.Context, base, auth *Auth, mode upd } authClone := auth.Clone() m.auths[auth.ID] = authClone + // Snapshot before unlocking: MarkResult mutates the published auth in place. + var schedulerSnapshot *Auth + if m.scheduler != nil { + schedulerSnapshot = authClone.Clone() + } m.mu.Unlock() if !shouldDeferAPIKeyModelAliasRebuild(ctx) { m.rebuildAPIKeyModelAliasFromRuntimeConfig() } if m.scheduler != nil { - m.scheduler.upsertAuth(authClone.Clone()) + m.scheduler.upsertAuth(schedulerSnapshot) } m.structuralEpoch.Add(1) m.queueRefreshReschedule(auth.ID) diff --git a/sdk/cliproxy/auth/conductor_lifecycle_race_test.go b/sdk/cliproxy/auth/conductor_lifecycle_race_test.go new file mode 100644 index 00000000000..113ce75aa04 --- /dev/null +++ b/sdk/cliproxy/auth/conductor_lifecycle_race_test.go @@ -0,0 +1,75 @@ +package auth + +import ( + "context" + "fmt" + "sync" + "testing" +) + +// Run with -race to check that scheduler snapshots never read published auths unlocked. +func TestPublishedAuthSnapshotRace(t *testing.T) { + for _, operation := range []string{"Register", "Update", "UpdatePreparedAuth", "UpdateRefreshedAuth"} { + t.Run(operation, func(t *testing.T) { + ctx := WithSkipPersist(context.Background()) + m := NewManager(nil, nil, nil) + a := &Auth{ + ID: "snapshot-race", Provider: "audit", Status: StatusActive, + Metadata: map[string]any{"type": "audit"}, + } + for i := 0; i < 200; i++ { + a.Metadata[fmt.Sprintf("field-%d", i)] = i + } + if _, errRegister := m.Register(ctx, a); errRegister != nil { + t.Fatal(errRegister) + } + + start := make(chan struct{}) + var wg sync.WaitGroup + for worker := 0; worker < 32; worker++ { + wg.Add(1) + go func() { + defer wg.Done() + <-start + for i := 0; i < 100; i++ { + m.MarkResult(ctx, Result{ + AuthID: a.ID, Provider: a.Provider, + Model: fmt.Sprintf("model-%d", i%8), Success: true, + }) + } + }() + } + wg.Add(1) + go func() { + defer wg.Done() + <-start + for i := 0; i < 100; i++ { + base, ok := m.GetByID(a.ID) + if !ok { + t.Error("missing auth") + return + } + updated := base.Clone() + updated.Metadata["note"] = fmt.Sprint(i) + var errPublish error + switch operation { + case "Register": + _, errPublish = m.Register(ctx, updated) + case "Update": + _, errPublish = m.Update(ctx, updated) + case "UpdatePreparedAuth": + _, errPublish = m.UpdatePreparedAuth(ctx, base, updated) + case "UpdateRefreshedAuth": + _, errPublish = m.UpdateRefreshedAuth(ctx, base, updated) + } + if errPublish != nil { + t.Error(errPublish) + return + } + } + }() + close(start) + wg.Wait() + }) + } +} From ea8ffd5f92c2d5b18c55d5d91738484cf7ec043f Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Sat, 3 Oct 2026 15:53:39 +0800 Subject: [PATCH 016/142] fix(devin): stream content early and defer thought stop for late signatures - Allow early content streaming for OpenAI formats while preserving ordering behind queued tools - Defer thought step termination and accumulate signature fragments for OpenAI Responses format - Flush deferred reasoning step stops when closing open stream steps Closes: #6306 --- internal/runtime/executor/devin_executor.go | 34 +- .../runtime/executor/devin_executor_test.go | 3 +- .../executor/devin_stream_content_test.go | 326 ++++++++++++++++++ 3 files changed, 355 insertions(+), 8 deletions(-) create mode 100644 internal/runtime/executor/devin_stream_content_test.go diff --git a/internal/runtime/executor/devin_executor.go b/internal/runtime/executor/devin_executor.go index 7f39d3643e2..8a1fe47851b 100644 --- a/internal/runtime/executor/devin_executor.go +++ b/internal/runtime/executor/devin_executor.go @@ -594,9 +594,12 @@ func (e *DevinExecutor) streamDevinFrames( var lastStopReason uint64 sawEOS := false - // Buffer subsequent content/tools while thinking is active so late-arriving or split - // thought signatures can be emitted before closing the thinking content block. + // Keep tools and block-oriented content queued for late or split thought signatures. + // OpenAI text can stream independently, but must not overtake queued tools. + streamContentEarly := responseFormat == sdktranslator.FormatOpenAI || responseFormat == sdktranslator.FormatOpenAIResponse var pendingActions []func() bool + var deferredThoughtStops []int + responseThoughtSignatures := make(map[int]string) flushPendingActions := func() bool { if thoughtStarted { @@ -629,9 +632,15 @@ func (e *DevinExecutor) streamDevinFrames( if stopIdx < 0 { stopIdx = stepIndex } - stopEvent, _ := sjson.SetBytes([]byte(`{"event_type":"step.stop","index":0}`), "index", stopIdx) - if !emitInteractionsEvent(stopEvent) { - return false + if responseFormat == sdktranslator.FormatOpenAIResponse { + // Responses items may overlap. Keep reasoning open for late signatures + // so output_item.done and response.completed contain the same item. + deferredThoughtStops = append(deferredThoughtStops, stopIdx) + } else { + stopEvent, _ := sjson.SetBytes([]byte(`{"event_type":"step.stop","index":0}`), "index", stopIdx) + if !emitInteractionsEvent(stopEvent) { + return false + } } thoughtStarted = false stepIndex++ @@ -744,6 +753,11 @@ func (e *DevinExecutor) streamDevinFrames( } closeOpenSteps := func() { + for _, index := range deferredThoughtStops { + stopEvent, _ := sjson.SetBytes([]byte(`{"event_type":"step.stop","index":0}`), "index", index) + _ = emitInteractionsEvent(stopEvent) + } + deferredThoughtStops = nil if len(pendingActions) > 0 || thoughtStarted { _ = flushPendingActions() } @@ -940,7 +954,13 @@ func (e *DevinExecutor) streamDevinFrames( } sigEvent := []byte(`{"event_type":"step.delta","index":0,"delta":{"type":"thought_signature","signature":""}}`) sigEvent, _ = sjson.SetBytes(sigEvent, "index", targetIdx) - sigEvent, _ = sjson.SetBytes(sigEvent, "delta.signature", string(frameRes.DeltaSignature)) + sig := string(frameRes.DeltaSignature) + if responseFormat == sdktranslator.FormatOpenAIResponse { + // The Responses translator accepts complete signatures, not fragments. + responseThoughtSignatures[targetIdx] += sig + sig = responseThoughtSignatures[targetIdx] + } + sigEvent, _ = sjson.SetBytes(sigEvent, "delta.signature", sig) if frameRes.DeltaSignatureType != "" { sigEvent, _ = sjson.SetBytes(sigEvent, "delta.signature_type", frameRes.DeltaSignatureType) } @@ -968,7 +988,7 @@ func (e *DevinExecutor) streamDevinFrames( accumulatedContent.WriteString(frameRes.ContentText) chunk := contentBuf.Feed([]byte(frameRes.ContentText)) if chunk != "" { - if thoughtStarted { + if thoughtStarted && (!streamContentEarly || len(pendingActions) > 0) { capturedChunk := chunk pendingActions = append(pendingActions, func() bool { return emitContentChunk(capturedChunk) diff --git a/internal/runtime/executor/devin_executor_test.go b/internal/runtime/executor/devin_executor_test.go index ec849d1ac04..f3b78153848 100644 --- a/internal/runtime/executor/devin_executor_test.go +++ b/internal/runtime/executor/devin_executor_test.go @@ -3800,7 +3800,8 @@ func TestDevinExecutor_WarnsWhenUpstreamServesUnexpectedModel(t *testing.T) { exec := NewDevinExecutor(&config.Config{}) auth := &cliproxyauth.Auth{ - ID: "devin-auth-unexpected", + // Isolate this run from the process-wide model warning throttle. + ID: "devin-auth-unexpected-" + uuid.NewString(), Provider: "devin", Attributes: map[string]string{"api_key": "test-key"}, } diff --git a/internal/runtime/executor/devin_stream_content_test.go b/internal/runtime/executor/devin_stream_content_test.go new file mode 100644 index 00000000000..0e8c674bd6e --- /dev/null +++ b/internal/runtime/executor/devin_stream_content_test.go @@ -0,0 +1,326 @@ +package executor + +import ( + "bytes" + "context" + "encoding/base64" + "io" + "slices" + "strings" + "testing" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" + "google.golang.org/protobuf/encoding/protowire" +) + +type devinContentCheckpointReader func([]byte) (int, error) + +func (r devinContentCheckpointReader) Read(p []byte) (int, error) { + return r(p) +} + +func TestDevinStreamEmitsContentBeforeThinkingCloses(t *testing.T) { + for _, format := range []sdktranslator.Format{sdktranslator.FormatOpenAI, sdktranslator.FormatOpenAIResponse} { + t.Run(string(format), func(t *testing.T) { + // Each checkpoint runs synchronously when the executor requests the next + // frame, after all output for the previous frame has been enqueued. + // EOS is unavailable until every pre-EOS assertion has run. + out := make(chan cliproxyexecutor.StreamChunk, 64) + var content []string + var thinking strings.Builder + drain := func() { + for len(out) > 0 { + chunk := <-out + if chunk.Err != nil { + t.Fatalf("unexpected stream error: %v", chunk.Err) + } + for _, line := range strings.Split(string(chunk.Payload), "\n") { + data := strings.TrimSpace(strings.TrimPrefix(line, "data: ")) + if !gjson.Valid(data) { + continue + } + event := gjson.Parse(data) + var text string + switch format { + case sdktranslator.FormatOpenAI: + thinking.WriteString(event.Get("choices.0.delta.reasoning_content").String()) + text = event.Get("choices.0.delta.content").String() + case sdktranslator.FormatOpenAIResponse: + switch event.Get("type").String() { + case "response.reasoning_summary_text.delta": + thinking.WriteString(event.Get("delta").String()) + case "response.output_text.delta": + text = event.Get("delta").String() + } + } + if text != "" { + content = append(content, text) + } + } + } + } + + stages := []struct { + name string + field protowire.Number + text string + want []string + }{ + {name: "thinking", field: 9, text: "planning"}, + {name: "incomplete UTF-8", field: 3, text: "甲"[:1]}, + {name: "first complete UTF-8 chunk", field: 3, text: "甲"[1:], want: []string{"甲"}}, + {name: "second complete UTF-8 chunk", field: 3, text: "乙", want: []string{"甲", "乙"}}, + } + var readers []io.Reader + checkpoints := 0 + for _, stage := range stages { + frame := protowire.AppendTag(nil, stage.field, protowire.BytesType) + frame = protowire.AppendString(frame, stage.text) + readers = append(readers, bytes.NewReader(helps.WrapConnectEnvelope(frame))) + readers = append(readers, devinContentCheckpointReader(func(_ []byte) (int, error) { + drain() + checkpoints++ + if thinking.String() != "planning" { + t.Fatalf("%s: thinking = %q, want planning before EOS", stage.name, thinking.String()) + } + if !slices.Equal(content, stage.want) { + t.Errorf("%s: content deltas before upstream EOS = %q, want %q", stage.name, content, stage.want) + } + return 0, io.EOF + })) + } + readers = append(readers, bytes.NewReader(helps.WrapConnectEnvelopeWithFlag(helps.ConnectFlagEndStream, []byte(`{}`)))) + + original := []byte(`{"model":"devin/swe-2","stream":true,"messages":[{"role":"user","content":"hi"}]}`) + if format == sdktranslator.FormatOpenAIResponse { + original = []byte(`{"model":"devin/swe-2","stream":true,"input":"hi"}`) + } + opts := cliproxyexecutor.Options{SourceFormat: format, OriginalRequest: original} + req := cliproxyexecutor.Request{ + Model: "devin/swe-2", + Payload: sdktranslator.TranslateRequest(format, sdktranslator.FormatInteractions, "devin/swe-2", original, true), + } + e := &DevinExecutor{} + e.streamDevinFrames(context.Background(), io.MultiReader(readers...), req, opts, "swe-2-high", format, nil, out) + drain() + if checkpoints != len(stages) { + t.Fatalf("reached %d checkpoints, want %d", checkpoints, len(stages)) + } + if !slices.Equal(content, []string{"甲", "乙"}) { + t.Errorf("content deltas after EOS = %q, want [甲 乙] without loss or duplication", content) + } + }) + } +} + +func devinContentTestFrame(field protowire.Number, text string) []byte { + frame := protowire.AppendTag(nil, field, protowire.BytesType) + return helps.WrapConnectEnvelope(protowire.AppendString(frame, text)) +} + +func devinContentTestEvents(out <-chan cliproxyexecutor.StreamChunk) ([]gjson.Result, []error) { + var events []gjson.Result + var errs []error + for len(out) > 0 { + chunk := <-out + if chunk.Err != nil { + errs = append(errs, chunk.Err) + } + for _, line := range strings.Split(string(chunk.Payload), "\n") { + data := strings.TrimSpace(strings.TrimPrefix(line, "data: ")) + if gjson.Valid(data) { + events = append(events, gjson.Parse(data)) + } + } + } + return events, errs +} + +func TestDevinStreamContentLateSignatures(t *testing.T) { + payload := make([]byte, 1+8+16+16+32) + payload[0] = 0x80 + for i := 9; i < len(payload); i++ { + payload[i] = byte(i) + } + signature := base64.URLEncoding.EncodeToString(payload) + for _, format := range []sdktranslator.Format{sdktranslator.FormatOpenAI, sdktranslator.FormatOpenAIResponse} { + for _, split := range []bool{false, true} { + for _, ending := range []string{"eos", "trailer_error", "truncated", "read_error"} { + name := string(format) + "/late/" + ending + if split { + name = string(format) + "/split/" + ending + } + t.Run(name, func(t *testing.T) { + out := make(chan cliproxyexecutor.StreamChunk, 64) + var prefix bytes.Buffer + prefix.Write(devinContentTestFrame(9, "planning")) + tailSignature := signature + if split { + prefix.Write(devinContentTestFrame(10, signature[:20])) + tailSignature = signature[20:] + } + prefix.Write(devinContentTestFrame(3, "甲")) + var events []gjson.Result + checkpointReached := false + checkpoint := devinContentCheckpointReader(func(_ []byte) (int, error) { + checkpointReached = true + var errs []error + events, errs = devinContentTestEvents(out) + if len(errs) > 0 { + t.Fatalf("unexpected pre-signature errors: %v", errs) + } + var text strings.Builder + for _, event := range events { + if format == sdktranslator.FormatOpenAI { + text.WriteString(event.Get("choices.0.delta.content").String()) + } else { + if event.Get("type").String() == "response.output_text.delta" { + text.WriteString(event.Get("delta").String()) + } + if event.Get("type").String() == "response.output_item.done" && event.Get("item.type").String() == "reasoning" { + t.Error("reasoning item finalized before its late signature") + } + } + } + if text.String() != "甲" { + t.Errorf("content before late signature and termination = %q, want 甲", text.String()) + } + return 0, io.EOF + }) + var suffix bytes.Buffer + suffix.Write(devinContentTestFrame(10, tailSignature)) + switch ending { + case "eos": + suffix.Write(helps.WrapConnectEnvelopeWithFlag(helps.ConnectFlagEndStream, []byte(`{}`))) + case "trailer_error": + suffix.Write(helps.WrapConnectEnvelopeWithFlag(helps.ConnectFlagEndStream, []byte(`{"error":{"code":"internal","message":"upstream failed"}}`))) + case "read_error": + suffix.Write([]byte{0, 0}) // Incomplete frame header causes io.ErrUnexpectedEOF. + } + e := &DevinExecutor{} + e.streamDevinFrames(context.Background(), io.MultiReader(&prefix, checkpoint, &suffix), cliproxyexecutor.Request{Model: "devin/swe-2"}, cliproxyexecutor.Options{SourceFormat: format}, "swe-2-high", format, nil, out) + remaining, errs := devinContentTestEvents(out) + events = append(events, remaining...) + if !checkpointReached { + t.Fatal("pre-signature checkpoint not reached") + } + wantError := ending != "eos" + if (len(errs) == 1) != wantError || len(errs) > 1 { + t.Errorf("stream errors = %v, want exactly one error: %v", errs, wantError) + } + var reasoningDone, completedReasoning gjson.Result + doneCount, messageDoneCount, completedCount, failedCount := 0, 0, 0, 0 + var text strings.Builder + for _, event := range events { + if format == sdktranslator.FormatOpenAI { + text.WriteString(event.Get("choices.0.delta.content").String()) + if event.Get("error").Exists() { + failedCount++ + } + continue + } + switch event.Get("type").String() { + case "response.output_text.delta": + text.WriteString(event.Get("delta").String()) + case "response.output_item.done": + if event.Get("item.type").String() == "message" { + messageDoneCount++ + } + if event.Get("item.type").String() == "reasoning" { + reasoningDone = event.Get("item") + doneCount++ + } + case "response.completed": + completedCount++ + completedReasoning = event.Get("response.output.0") + case "response.failed": + failedCount++ + } + } + if text.String() != "甲" { + t.Errorf("final content = %q, want 甲 without duplication", text.String()) + } + if (failedCount == 1) != wantError || failedCount > 1 { + t.Errorf("failure event count = %d, want failure: %v", failedCount, wantError) + } + if format == sdktranslator.FormatOpenAIResponse { + if doneCount != 1 || reasoningDone.Get("encrypted_content").String() != signature { + t.Errorf("reasoning done count = %d, item = %s; want full signature %q", doneCount, reasoningDone.Raw, signature) + } + if messageDoneCount != 1 { + t.Errorf("message done count = %d, want 1", messageDoneCount) + } + if wantError { + if events[len(events)-1].Get("type").String() != "response.failed" { + t.Error("failure must terminate the stream after closing open items") + } + if completedCount != 0 { + t.Error("response.completed emitted after upstream failure") + } + } else if completedCount != 1 || completedReasoning.Raw != reasoningDone.Raw { + t.Errorf("completed reasoning = %s, want same item as done = %s", completedReasoning.Raw, reasoningDone.Raw) + } + } + }) + } + } + } +} + +func TestDevinStreamContentDoesNotOvertakeQueuedTool(t *testing.T) { + for _, format := range []sdktranslator.Format{sdktranslator.FormatOpenAI, sdktranslator.FormatOpenAIResponse} { + t.Run(string(format), func(t *testing.T) { + var frames bytes.Buffer + frames.Write(devinContentTestFrame(9, "planning")) + var tool []byte + for i, value := range []string{"call_1", "bash", `{"cmd":"ls"}`} { + tool = protowire.AppendTag(tool, protowire.Number(i+1), protowire.BytesType) + tool = protowire.AppendString(tool, value) + } + frames.Write(devinContentTestFrame(6, string(tool))) + frames.Write(devinContentTestFrame(3, "甲")) + out := make(chan cliproxyexecutor.StreamChunk, 64) + checkpointReached := false + checkpoint := devinContentCheckpointReader(func(_ []byte) (int, error) { + checkpointReached = true + events, errs := devinContentTestEvents(out) + if len(errs) > 0 { + t.Fatalf("unexpected errors: %v", errs) + } + for _, event := range events { + if event.Get("choices.0.delta.content").String() != "" || event.Get("choices.0.delta.tool_calls").Exists() || event.Get("type").String() == "response.output_text.delta" || event.Get("item.type").String() == "function_call" { + t.Errorf("queued tool or following text emitted before thinking signature: %s", event.Raw) + } + } + return 0, io.EOF + }) + var tail bytes.Buffer + tail.Write(devinContentTestFrame(10, "CAQS-late-tool-signature")) + tail.Write(helps.WrapConnectEnvelopeWithFlag(helps.ConnectFlagEndStream, []byte(`{}`))) + e := &DevinExecutor{} + e.streamDevinFrames(context.Background(), io.MultiReader(&frames, checkpoint, &tail), cliproxyexecutor.Request{Model: "devin/swe-2"}, cliproxyexecutor.Options{SourceFormat: format}, "swe-2-high", format, nil, out) + events, errs := devinContentTestEvents(out) + if !checkpointReached || len(errs) > 0 { + t.Fatalf("checkpoint = %v, errors = %v", checkpointReached, errs) + } + toolSeen, textSeen := false, false + for _, event := range events { + if event.Get("choices.0.delta.tool_calls.0.id").String() == "call_1" || (event.Get("type").String() == "response.output_item.done" && event.Get("item.call_id").String() == "call_1") { + toolSeen = true + } + if event.Get("choices.0.delta.content").String() == "甲" || (event.Get("type").String() == "response.output_text.delta" && event.Get("delta").String() == "甲") { + textSeen = true + if !toolSeen { + t.Error("content overtook queued tool") + } + } + } + if !toolSeen || !textSeen { + t.Errorf("tool seen = %v, text seen = %v; want both", toolSeen, textSeen) + } + }) + } +} From ee79a794526a30c03748a8864a9ac6589a31833b Mon Sep 17 00:00:00 2001 From: Supra4E8C Date: Sat, 3 Oct 2026 15:57:46 +0800 Subject: [PATCH 017/142] feat: update plan names to Pro 200 and Pro 100 across locales and tests --- src/i18n/locales/en.json | 4 ++-- src/i18n/locales/ru.json | 4 ++-- src/i18n/locales/zh-CN.json | 4 ++-- src/i18n/locales/zh-TW.json | 4 ++-- src/utils/quota/planTier.ts | 8 ++++---- tests/quotaBodyRendering.test.ts | 4 ++-- tests/quotaPlanTier.test.ts | 15 ++++++++++++++- 7 files changed, 28 insertions(+), 15 deletions(-) diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json index f356196ec36..820a0690610 100644 --- a/src/i18n/locales/en.json +++ b/src/i18n/locales/en.json @@ -540,8 +540,8 @@ "plan_plus": "Plus", "plan_team": "Team", "plan_free": "Free", - "plan_pro": "Pro 20x", - "plan_prolite": "Pro 5x", + "plan_pro": "Pro 200", + "plan_prolite": "Pro 100", "plan_business_premium": "Business Premium" }, "devin_quota": { diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index b420bf3e913..e0b6d8ba3d0 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -543,8 +543,8 @@ "plan_plus": "Plus", "plan_team": "Team", "plan_free": "Free", - "plan_pro": "Pro 20x", - "plan_prolite": "Pro 5x", + "plan_pro": "Pro 200", + "plan_prolite": "Pro 100", "plan_business_premium": "Business Premium" }, "devin_quota": { diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index fce60cbbda0..d7029c6955d 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -538,8 +538,8 @@ "plan_plus": "Plus", "plan_team": "Team", "plan_free": "Free", - "plan_pro": "Pro 20x", - "plan_prolite": "Pro 5x", + "plan_pro": "Pro 200", + "plan_prolite": "Pro 100", "plan_business_premium": "Business Premium" }, "devin_quota": { diff --git a/src/i18n/locales/zh-TW.json b/src/i18n/locales/zh-TW.json index cee344d6d17..ee4918d4f55 100644 --- a/src/i18n/locales/zh-TW.json +++ b/src/i18n/locales/zh-TW.json @@ -538,8 +538,8 @@ "plan_plus": "Plus", "plan_team": "Team", "plan_free": "Free", - "plan_pro": "Pro 20x", - "plan_prolite": "Pro 5x", + "plan_pro": "Pro 200", + "plan_prolite": "Pro 100", "plan_business_premium": "Business Premium" }, "devin_quota": { diff --git a/src/utils/quota/planTier.ts b/src/utils/quota/planTier.ts index bcd82d8d23f..af94f3e0233 100644 --- a/src/utils/quota/planTier.ts +++ b/src/utils/quota/planTier.ts @@ -3,8 +3,8 @@ import { normalizePlanType } from './parsers'; /** * Codex 套餐档位 → 徽章样式的纯映射。 * - * - elite → 液态铂金徽章(Pro 20x,plan=pro) - * - premium → 金卡徽章(Pro Lite;Antigravity ultra / xAI paid 亦复用金卡类名) + * - elite → 液态铂金徽章(Pro 200,plan=pro) + * - premium → 金卡徽章(Pro 100;Antigravity ultra / xAI paid 亦复用金卡类名) * - plain → 普通文字徽章(plus/team/free/未知) */ export type CodexPlanTier = 'elite' | 'premium' | 'plain'; @@ -17,13 +17,13 @@ export const PREMIUM_CODEX_PLAN_TYPES = new Set([ 'self_serve_business_prolite', ]); -// Pro 20x(plan=pro)在金色 premium 之上再进一档:液态铂金徽章, +// Pro 200(plan=pro)在金色 premium 之上再进一档:液态铂金徽章, // 见 QuotaPage.module.scss 的 .elitePlanValue。 export const ELITE_CODEX_PLAN_TYPE = 'pro'; /** * 顺序敏感:'pro' 同时命中 PREMIUM_CODEX_PLAN_TYPES,elite 判断必须在最前, - * 否则 Pro 20x 会静默退回金卡。契约由 tests/quotaPlanTier.test.ts 守护。 + * 否则 Pro 200 会静默退回金卡。契约由 tests/quotaPlanTier.test.ts 守护。 */ export function resolvePlanTier(planType: string | null | undefined): CodexPlanTier { const normalized = normalizePlanType(planType); diff --git a/tests/quotaBodyRendering.test.ts b/tests/quotaBodyRendering.test.ts index e30bce35c77..08542ac8e32 100644 --- a/tests/quotaBodyRendering.test.ts +++ b/tests/quotaBodyRendering.test.ts @@ -79,8 +79,8 @@ describe('CodexQuotaBody', () => { ); test.each([ - ['pro', 'Pro 20x', 'elitePlanValue'], - ['prolite', 'Pro 5x', 'premiumPlanValue'], + ['pro', 'Pro 200', 'elitePlanValue'], + ['prolite', 'Pro 100', 'premiumPlanValue'], ['team', 'Team', 'codexPlanValue'], ['self_serve_business_usage_based', 'self_serve_business_usage_based', 'codexPlanValue'], ])('preserves the label and badge for %s', (planType, label, className) => { diff --git a/tests/quotaPlanTier.test.ts b/tests/quotaPlanTier.test.ts index 5561bd98ec0..0e24cf4be15 100644 --- a/tests/quotaPlanTier.test.ts +++ b/tests/quotaPlanTier.test.ts @@ -1,14 +1,27 @@ import { describe, expect, test } from 'bun:test'; +import en from '@/i18n/locales/en.json'; +import zhCN from '@/i18n/locales/zh-CN.json'; +import zhTW from '@/i18n/locales/zh-TW.json'; +import ru from '@/i18n/locales/ru.json'; import { ELITE_CODEX_PLAN_TYPE, PREMIUM_CODEX_PLAN_TYPES, resolvePlanTier, } from '@/utils/quota'; +describe('Codex Pro display names', () => { + for (const [locale, messages] of Object.entries({ en, 'zh-CN': zhCN, 'zh-TW': zhTW, ru })) { + test(`${locale} labels Pro plans as Pro 100 and Pro 200`, () => { + expect(messages.codex_quota.plan_prolite).toBe('Pro 100'); + expect(messages.codex_quota.plan_pro).toBe('Pro 200'); + }); + } +}); + describe('resolvePlanTier', () => { test("elite wins for 'pro' even though it is also in the premium set (order contract)", () => { // 顺序契约回归:'pro' 同时命中 PREMIUM_CODEX_PLAN_TYPES, - // 一旦 premium 判断先行,Pro 20x 会静默退回金卡。 + // 一旦 premium 判断先行,Pro 200 会静默退回金卡。 expect(PREMIUM_CODEX_PLAN_TYPES.has(ELITE_CODEX_PLAN_TYPE)).toBe(true); expect(resolvePlanTier('pro')).toBe('elite'); }); From ed4d972ef0bff51973c6eee577dd593de60a351f Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Sat, 3 Oct 2026 16:05:49 +0800 Subject: [PATCH 018/142] fix(responses): complete reasoning summary stream lifecycle events - Emit `response.reasoning_summary_part.added` event on reasoning item initialization - Include `item_id` and `summary_index` in reasoning summary text delta events - Emit summary text done and part done events upon thought step completion - Consolidate reasoning summaries into a single completed summary block Closes #6309 --- .../interactions_openai_responses_response.go | 45 +++++--- ...ractions_openai_responses_response_test.go | 106 ++++++++++++++++++ 2 files changed, 138 insertions(+), 13 deletions(-) diff --git a/internal/translator/openai/interactions/responses/interactions_openai_responses_response.go b/internal/translator/openai/interactions/responses/interactions_openai_responses_response.go index ed9e35288fb..491a7f20123 100644 --- a/internal/translator/openai/interactions/responses/interactions_openai_responses_response.go +++ b/internal/translator/openai/interactions/responses/interactions_openai_responses_response.go @@ -425,7 +425,11 @@ func interactionsStepStartToResponses(modelName string, root gjson.Result, st *i if signature := interactionsReasoningEncryptedContent(st.ReasoningEncrypted[index]); signature != "" { added, _ = sjson.SetBytes(added, "item.encrypted_content", signature) } - return [][]byte{emitResponsesEvent("response.output_item.added", added)} + part := []byte(`{"type":"response.reasoning_summary_part.added","item_id":"","output_index":0,"summary_index":0,"part":{"type":"summary_text","text":""}}`) + part, _ = sjson.SetBytes(part, "sequence_number", nextResponsesSeq(st)) + part, _ = sjson.SetBytes(part, "item_id", itemID) + part, _ = sjson.SetBytes(part, "output_index", index) + return [][]byte{emitResponsesEvent("response.output_item.added", added), emitResponsesEvent("response.reasoning_summary_part.added", part)} } return nil @@ -463,8 +467,9 @@ func interactionsStepDeltaToResponses(root gjson.Result, st *interactionsToRespo case "thought_summary": text := firstNonEmpty(delta.Get("content.text").String(), delta.Get("text").String()) recordResponsesReasoningSummary(st, index, text) - payload := []byte(`{"type":"response.reasoning_summary_text.delta","output_index":0,"delta":""}`) + payload := []byte(`{"type":"response.reasoning_summary_text.delta","item_id":"","output_index":0,"summary_index":0,"delta":""}`) payload, _ = sjson.SetBytes(payload, "sequence_number", nextResponsesSeq(st)) + payload, _ = sjson.SetBytes(payload, "item_id", st.ItemIDs[index]) payload, _ = sjson.SetBytes(payload, "output_index", index) payload, _ = sjson.SetBytes(payload, "delta", text) return [][]byte{emitResponsesEvent("response.reasoning_summary_text.delta", payload)} @@ -680,6 +685,27 @@ func interactionsStepStopToResponses(root gjson.Result, st *interactionsToRespon done, _ = translatorcommon.SetStringWithoutHTMLEscape(done, "item.arguments", arguments) call.ItemDoneEmitted = true return append(events, emitResponsesEvent("response.output_item.done", done)) + case "thought": + text := strings.Join(st.ReasoningSummaries[index], "") + textDone := []byte(`{"type":"response.reasoning_summary_text.done","item_id":"","output_index":0,"summary_index":0,"text":""}`) + textDone, _ = sjson.SetBytes(textDone, "sequence_number", nextResponsesSeq(st)) + textDone, _ = sjson.SetBytes(textDone, "item_id", itemID) + textDone, _ = sjson.SetBytes(textDone, "output_index", index) + textDone, _ = sjson.SetBytes(textDone, "text", text) + partDone := []byte(`{"type":"response.reasoning_summary_part.done","item_id":"","output_index":0,"summary_index":0,"part":{"type":"summary_text","text":""}}`) + partDone, _ = sjson.SetBytes(partDone, "sequence_number", nextResponsesSeq(st)) + partDone, _ = sjson.SetBytes(partDone, "item_id", itemID) + partDone, _ = sjson.SetBytes(partDone, "output_index", index) + partDone, _ = sjson.SetBytes(partDone, "part.text", text) + done := []byte(`{"type":"response.output_item.done","output_index":0,"item":{}}`) + done, _ = sjson.SetBytes(done, "sequence_number", nextResponsesSeq(st)) + done, _ = sjson.SetBytes(done, "output_index", index) + done, _ = sjson.SetRawBytes(done, "item", responsesReasoningItem(index, st)) + return [][]byte{ + emitResponsesEvent("response.reasoning_summary_text.done", textDone), + emitResponsesEvent("response.reasoning_summary_part.done", partDone), + emitResponsesEvent("response.output_item.done", done), + } default: done := []byte(`{"type":"response.output_item.done","output_index":0,"item":{}}`) done, _ = sjson.SetBytes(done, "sequence_number", nextResponsesSeq(st)) @@ -900,21 +926,14 @@ func responsesCompletedOutputItem(index int, itemType string, st *interactionsTo } func responsesReasoningItem(index int, st *interactionsToResponsesStreamState) []byte { - item := []byte(`{"id":"","type":"reasoning","encrypted_content":"","summary":[]}`) + item := []byte(`{"id":"","type":"reasoning","status":"completed","encrypted_content":"","summary":[]}`) item, _ = sjson.SetBytes(item, "id", st.ItemIDs[index]) if signature := interactionsReasoningEncryptedContent(st.ReasoningEncrypted[index]); signature != "" { item, _ = sjson.SetBytes(item, "encrypted_content", signature) } - summaries := st.ReasoningSummaries[index] - if len(summaries) > 0 { - summaryBlocks := make([][]byte, 0, len(summaries)) - for _, text := range summaries { - part := []byte(`{"type":"summary_text","text":""}`) - part, _ = sjson.SetBytes(part, "text", text) - summaryBlocks = append(summaryBlocks, part) - } - item = translatorcommon.SetRawArrayItems(item, "summary", summaryBlocks) - } + part := []byte(`{"type":"summary_text","text":""}`) + part, _ = sjson.SetBytes(part, "text", strings.Join(st.ReasoningSummaries[index], "")) + item = translatorcommon.SetRawArrayItems(item, "summary", [][]byte{part}) return item } diff --git a/internal/translator/openai/interactions/responses/interactions_openai_responses_response_test.go b/internal/translator/openai/interactions/responses/interactions_openai_responses_response_test.go index 4791a4249c2..c07750ab443 100644 --- a/internal/translator/openai/interactions/responses/interactions_openai_responses_response_test.go +++ b/internal/translator/openai/interactions/responses/interactions_openai_responses_response_test.go @@ -235,6 +235,112 @@ func testGPTResponsesReasoningSignature() string { return base64.URLEncoding.EncodeToString(payload) } +func TestConvertInteractionsResponseToOpenAIResponsesStreamReasoningSummaryLifecycle(t *testing.T) { + for _, tc := range []struct { + name string + chunks []string + signed bool + }{ + {name: "single_frame", chunks: []string{"thinking"}}, + {name: "multiple_frames_late_signature", chunks: []string{"think", " carefully"}, signed: true}, + {name: "signature_only", signed: true}, + {name: "empty_summary", chunks: []string{""}}, + } { + t.Run(tc.name, func(t *testing.T) { + var param any + var out [][]byte + send := func(raw string) [][]byte { + frames := ConvertInteractionsResponseToOpenAIResponses(context.Background(), "devin/swe-2", nil, nil, []byte("data: "+raw+"\n\n"), ¶m) + out = append(out, frames...) + return frames + } + send(`{"index":3,"step":{"id":"reasoning_3","type":"thought"},"event_type":"step.start"}`) + for i, chunk := range tc.chunks { + field := fmt.Sprintf(`"text":%q`, chunk) + if i%2 == 0 { + field = fmt.Sprintf(`"content":{"type":"text","text":%q}`, chunk) + } + frames := send(`{"index":3,"delta":{"type":"thought_summary",` + field + `},"event_type":"step.delta"}`) + if got := strings.Join(responsesEventNames(frames), ","); got != "response.reasoning_summary_text.delta" || len(frames) != 1 { + t.Fatalf("frame %d events = %s, want exactly one immediate summary delta", i, got) + } + payload := findResponsesEventPayload(frames, "response.reasoning_summary_text.delta") + if got := gjson.GetBytes(payload, "delta"); !got.Exists() || got.String() != chunk { + t.Fatalf("frame %d delta = %s, want %q", i, payload, chunk) + } + } + signature := "" + if tc.signed { + signature = testGPTResponsesReasoningSignature() + for _, value := range []string{signature, ""} { + if frames := send(`{"index":3,"delta":{"type":"thought_signature","signature":"` + value + `"},"event_type":"step.delta"}`); len(frames) != 0 { + t.Fatalf("signature emitted events: %s", responsesEventNames(frames)) + } + } + } + send(`{"index":3,"event_type":"step.stop"}`) + send(`{"interaction":{"id":"interaction_1","status":"completed"},"event_type":"interaction.completed"}`) + wantNames := []string{"response.output_item.added", "response.reasoning_summary_part.added"} + for range tc.chunks { + wantNames = append(wantNames, "response.reasoning_summary_text.delta") + } + wantNames = append(wantNames, "response.reasoning_summary_text.done", "response.reasoning_summary_part.done", "response.output_item.done", "response.completed") + if got := strings.Join(responsesEventNames(out), ","); got != strings.Join(wantNames, ",") || len(out) != len(wantNames) { + t.Fatalf("events = %s, want %s", got, strings.Join(wantNames, ",")) + } + var previousSequence int64 + for i, frame := range out { + payload := findResponsesEventPayload([][]byte{frame}, wantNames[i]) + sequence := gjson.GetBytes(payload, "sequence_number") + if !sequence.Exists() || (i > 0 && sequence.Int() != previousSequence+1) { + t.Fatalf("invalid sequence: %s", payload) + } + previousSequence = sequence.Int() + if wantNames[i] == "response.completed" { + continue + } + if index := gjson.GetBytes(payload, "output_index"); !index.Exists() || index.Int() != 3 { + t.Fatalf("invalid output_index: %s", payload) + } + idPath := "item.id" + if strings.HasPrefix(wantNames[i], "response.reasoning_summary_") { + idPath = "item_id" + if index := gjson.GetBytes(payload, "summary_index"); !index.Exists() || index.Int() != 0 { + t.Fatalf("invalid summary_index: %s", payload) + } + } + if id := gjson.GetBytes(payload, idPath); !id.Exists() || id.String() != "reasoning_3" { + t.Fatalf("invalid item identity: %s", payload) + } + } + text := strings.Join(tc.chunks, "") + for _, check := range []struct{ event, path, want string }{ + {"response.output_item.added", "item.status", "in_progress"}, + {"response.reasoning_summary_part.added", "part.type", "summary_text"}, + {"response.reasoning_summary_part.added", "part.text", ""}, + {"response.reasoning_summary_text.done", "text", text}, + {"response.reasoning_summary_part.done", "part.type", "summary_text"}, + {"response.reasoning_summary_part.done", "part.text", text}, + {"response.output_item.done", "item.type", "reasoning"}, + {"response.output_item.done", "item.status", "completed"}, + {"response.output_item.done", "item.summary.0.type", "summary_text"}, + {"response.output_item.done", "item.summary.0.text", text}, + {"response.output_item.done", "item.encrypted_content", signature}, + } { + payload := findResponsesEventPayload(out, check.event) + if got := gjson.GetBytes(payload, check.path); !got.Exists() || got.String() != check.want { + t.Errorf("%s %s = %s, want %q", check.event, check.path, payload, check.want) + } + } + done := gjson.GetBytes(findResponsesEventPayload(out, "response.output_item.done"), "item") + completed := gjson.GetBytes(findResponsesEventPayload(out, "response.completed"), "response.output") + if len(done.Get("summary").Array()) != 1 || len(completed.Array()) != 1 || done.Raw != completed.Get("0").Raw { + t.Fatalf("terminal reasoning items differ or summary count is wrong: done=%s completed=%s", done.Raw, completed.Raw) + } + }) + } +} + func TestConvertInteractionsResponseToOpenAIResponsesStreamPreservesThoughtSignature(t *testing.T) { var param any signature := testGPTResponsesReasoningSignature() From a3b77566adf439446cee84c5744f0562a458c68d Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Sat, 3 Oct 2026 16:14:51 +0800 Subject: [PATCH 019/142] fix(codex): publish main usage before image tool usage in execute - Publish primary model usage prior to image tool usage during response execution Closes: #6311 --- .../executor/codex_executor_execute.go | 2 +- .../codex_executor_execute_usage_test.go | 92 +++++++++++++++++++ 2 files changed, 93 insertions(+), 1 deletion(-) create mode 100644 internal/runtime/executor/codex_executor_execute_usage_test.go diff --git a/internal/runtime/executor/codex_executor_execute.go b/internal/runtime/executor/codex_executor_execute.go index 7fdda8b61d1..9bc1b6a4f7b 100644 --- a/internal/runtime/executor/codex_executor_execute.go +++ b/internal/runtime/executor/codex_executor_execute.go @@ -186,10 +186,10 @@ func (e *CodexExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, re if helps.ApplyPatchTranslationError(param) != nil || len(out) == 0 { return cliproxyexecutor.Response{}, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage} } - publishCodexImageToolUsage(ctx, reporter, body, eventData) if detail, ok := helps.ParseCodexUsage(eventData); ok { reporter.Publish(ctx, detail) } + publishCodexImageToolUsage(ctx, reporter, body, eventData) if responseFormat == sdktranslator.FormatOpenAIResponse { out = helps.EnsureResponsesUsageDetails(out) } diff --git a/internal/runtime/executor/codex_executor_execute_usage_test.go b/internal/runtime/executor/codex_executor_execute_usage_test.go new file mode 100644 index 00000000000..604f0ad8eb2 --- /dev/null +++ b/internal/runtime/executor/codex_executor_execute_usage_test.go @@ -0,0 +1,92 @@ +package executor + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "testing" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + _ "github.com/router-for-me/CLIProxyAPI/v8/internal/translator" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + coreusage "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +func TestCodexExecutorExecutePublishesMainUsageBeforeImageUsage(t *testing.T) { + for _, mainUsage := range []bool{true, false} { + for _, imageUsage := range []struct { + name string + fields string + want coreusage.Detail + }{ + {name: "zero", fields: `,"tool_usage":{"image_gen":{"input_tokens":0,"output_tokens":0,"total_tokens":0}}`}, + { + name: "nonzero", + fields: `,"tool_usage":{"image_gen":{"input_tokens":10,"output_tokens":20,"total_tokens":30,"input_tokens_details":{"cached_tokens":3}}}`, + want: coreusage.Detail{InputTokens: 10, OutputTokens: 20, TotalTokens: 30, CachedTokens: 3, CacheReadTokens: 3}, + }, + {name: "missing"}, + } { + if !mainUsage && imageUsage.fields == "" { + continue + } + t.Run(fmt.Sprintf("main_%t/image_%s", mainUsage, imageUsage.name), func(t *testing.T) { + var mainFields string + var wantMain coreusage.Detail + if mainUsage { + mainFields = `,"usage":{"input_tokens":100,"output_tokens":40,"total_tokens":140,"input_tokens_details":{"cached_tokens":25}}` + wantMain = coreusage.Detail{InputTokens: 100, OutputTokens: 40, TotalTokens: 140, CachedTokens: 25, CacheReadTokens: 25} + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost || r.URL.Path != "/responses" { + t.Errorf("upstream request = %s %s, want POST /responses", r.Method, r.URL.Path) + } + w.Header().Set("Content-Type", "text/event-stream") + _, errWrite := fmt.Fprintf(w, "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_usage\",\"object\":\"response\",\"status\":\"completed\",\"model\":\"gpt-5.5\",\"output\":[{\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"ok\"}]}]%s%s}}\n\n", mainFields, imageUsage.fields) + if errWrite != nil { + t.Errorf("write upstream response: %v", errWrite) + } + })) + t.Cleanup(server.Close) + + alias := t.Name() + capture := &codexResponseModelUsageCapture{alias: alias, records: make(chan coreusage.Record, 4)} + coreusage.RegisterNamedPlugin(t.Name(), capture) + t.Cleanup(func() { + coreusage.RegisterNamedPlugin(t.Name(), codexResponseModelNoopUsagePlugin{}) + }) + ctx := coreusage.WithRequestedModelAlias(context.Background(), alias) + executor := NewCodexExecutor(&config.Config{}) + resp, errExecute := executor.Execute(ctx, codexOAuthTestAuth(server.URL), cliproxyexecutor.Request{ + Model: "gpt-5.5", + Payload: []byte(`{"model":"gpt-5.5","input":"hi"}`), + }, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatOpenAIResponse}) + if errExecute != nil { + t.Fatalf("Execute: %v", errExecute) + } + if len(resp.Payload) == 0 { + t.Fatal("Execute returned an empty response") + } + + mainRecord := capture.await(t) + if mainRecord.Model != "gpt-5.5" || mainRecord.Failed { + t.Errorf("main record model = %q, failed = %t", mainRecord.Model, mainRecord.Failed) + } + if got := mainRecord.Detail; got.InputTokens != wantMain.InputTokens || got.OutputTokens != wantMain.OutputTokens || got.TotalTokens != wantMain.TotalTokens || got.CachedTokens != wantMain.CachedTokens || got.CacheReadTokens != wantMain.CacheReadTokens { + t.Errorf("main usage = %+v, want %+v", mainRecord.Detail, wantMain) + } + if imageUsage.name == "nonzero" { + imageRecord := capture.await(t) + if imageRecord.Model != codexDefaultImageToolModel || imageRecord.Failed { + t.Errorf("image record model = %q, failed = %t", imageRecord.Model, imageRecord.Failed) + } + if got, want := imageRecord.Detail, imageUsage.want; got.InputTokens != want.InputTokens || got.OutputTokens != want.OutputTokens || got.TotalTokens != want.TotalTokens || got.CachedTokens != want.CachedTokens || got.CacheReadTokens != want.CacheReadTokens { + t.Errorf("image usage = %+v, want %+v", imageRecord.Detail, imageUsage.want) + } + } + }) + } + } +} From 2c1dcc7c8b88f5c03f176d7fbf3e37910b1507f3 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Sat, 3 Oct 2026 16:25:14 +0800 Subject: [PATCH 020/142] fix(claude): include web search sources in codex request when search tool is present - Include `web_search_call.action.sources` in Codex request `include` field when Claude web search tools are detected Closes: #6312 --- .../codex/claude/codex_claude_request.go | 8 +++- .../codex/claude/codex_claude_request_test.go | 38 +++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/internal/translator/codex/claude/codex_claude_request.go b/internal/translator/codex/claude/codex_claude_request.go index 85f9cee1487..ae94c90909e 100644 --- a/internal/translator/codex/claude/codex_claude_request.go +++ b/internal/translator/codex/claude/codex_claude_request.go @@ -339,6 +339,7 @@ func convertClaudeRequestToCodex(modelName string, inputRawJSON []byte, _ bool, // Convert tools declarations to the expected format for the Codex API. toolsResult := rootResult.Get("tools") + hasWebSearchTool := false var toolItems [][]byte if toolsResult.IsArray() { webSearchToolNames := buildClaudeWebSearchToolNameSet(toolsResult) @@ -349,6 +350,7 @@ func convertClaudeRequestToCodex(modelName string, inputRawJSON []byte, _ bool, toolResult := toolResults[i] // Special handling: map Claude web search tool to Codex web_search if isClaudeWebSearchToolType(toolResult.Get("type").String()) { + hasWebSearchTool = true toolItems = append(toolItems, convertClaudeWebSearchToolToCodex(toolResult)) continue } @@ -433,7 +435,11 @@ func convertClaudeRequestToCodex(modelName string, inputRawJSON []byte, _ bool, } template, _ = sjson.SetBytes(template, "stream", true) template, _ = sjson.SetBytes(template, "store", false) - template, _ = sjson.SetBytes(template, "include", []string{"reasoning.encrypted_content"}) + includeFields := []string{"reasoning.encrypted_content"} + if hasWebSearchTool { + includeFields = append(includeFields, "web_search_call.action.sources") + } + template, _ = sjson.SetBytes(template, "include", includeFields) // Map Claude output_config.format to Codex Responses text.format. if format := rootResult.Get("output_config.format"); format.IsObject() && format.Get("type").String() == "json_schema" && format.Get("schema").IsObject() { diff --git a/internal/translator/codex/claude/codex_claude_request_test.go b/internal/translator/codex/claude/codex_claude_request_test.go index c26d9553df7..bbc4fe67561 100644 --- a/internal/translator/codex/claude/codex_claude_request_test.go +++ b/internal/translator/codex/claude/codex_claude_request_test.go @@ -442,6 +442,44 @@ func TestConvertClaudeRequestToCodex_ToolChoiceSpecificFunctionUsesConvertedName } } +func TestConvertClaudeRequestToCodex_WebSearchSourcesInclude(t *testing.T) { + tests := []struct { + name string + tools string + wantSources bool + }{ + {name: "no tools"}, + {name: "empty tools", tools: `[]`}, + {name: "ordinary function", tools: `[{"name":"lookup","input_schema":{"type":"object"}}]`}, + {name: "same name function", tools: `[{"name":"web_search","input_schema":{"type":"object"}}]`}, + {name: "unsupported type", tools: `[{"type":"web_search_20990101","name":"web_search"}]`}, + {name: "20250305", tools: `[{"type":"web_search_20250305","name":"web_search"}]`, wantSources: true}, + {name: "20260209", tools: `[{"type":"web_search_20260209","name":"web_search"}]`, wantSources: true}, + {name: "custom name", tools: `[{"type":"web_search_20250305","name":"browser_search"}]`, wantSources: true}, + {name: "nameless search", tools: `[{"type":"web_search_20250305"}]`, wantSources: true}, + {name: "multiple searches and function", tools: `[{"type":"web_search_20250305","name":"search_one"},{"type":"web_search_20260209","name":"search_two"},{"name":"lookup","input_schema":{"type":"object"}}]`, wantSources: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + for _, stream := range []bool{false, true} { + inputJSON := `{"model":"claude-opus-4-7","messages":[{"role":"user","content":"hello"}]` + if tt.tools != "" { + inputJSON += `,"tools":` + tt.tools + } + inputJSON += `}` + result := ConvertClaudeRequestToCodex("test-model", []byte(inputJSON), stream) + wantInclude := `["reasoning.encrypted_content"]` + if tt.wantSources { + wantInclude = `["reasoning.encrypted_content","web_search_call.action.sources"]` + } + if got := gjson.GetBytes(result, "include").Raw; got != wantInclude { + t.Errorf("stream=%v: include = %s, want %s", stream, got, wantInclude) + } + } + }) + } +} + func TestConvertClaudeRequestToCodex_WebSearchToolMapping(t *testing.T) { inputJSON := `{ "model": "claude-3-opus", From d7914afdedca7af95ee974a42453dc49fc1388ce Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Sat, 3 Oct 2026 17:01:12 +0800 Subject: [PATCH 021/142] fix(codex): expand integer field normalization mappings for tools - Add integer field paths for memories, history, notes, web, and collaboration tool schemas - Support nested property paths and union types in parameter schema normalization Closes: #6255 --- .../testdata/history_notes_tools.json | 412 ++++++++++++++++++ .../client/codex/tool-schema/tool_schema.go | 128 +++++- .../tool_schema_integer_fields_test.go | 219 ++++++++++ 3 files changed, 738 insertions(+), 21 deletions(-) create mode 100644 internal/client/codex/tool-schema/testdata/history_notes_tools.json create mode 100644 internal/client/codex/tool-schema/tool_schema_integer_fields_test.go diff --git a/internal/client/codex/tool-schema/testdata/history_notes_tools.json b/internal/client/codex/tool-schema/testdata/history_notes_tools.json new file mode 100644 index 00000000000..5f47de67832 --- /dev/null +++ b/internal/client/codex/tool-schema/testdata/history_notes_tools.json @@ -0,0 +1,412 @@ +{ + "tools": [ + { + "type": "namespace", + "name": "history", + "tools": [ + { + "type": "function", + "name": "list_windows", + "parameters": { + "type": "object", + "properties": { + "limit": { + "type": "integer", + "minimum": 1, + "description": "Maximum number of windows to return." + }, + "agent_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Agent whose history to inspect. Omit to use the current agent; otherwise pass an absolute agent name or a name relative to the current agent." + }, + "recent_first": { + "type": "boolean", + "description": "Whether to return the most recently created windows first." + } + } + } + } + ] + }, + { + "type": "namespace", + "name": "history", + "tools": [ + { + "type": "function", + "name": "list_items", + "parameters": { + "type": "object", + "properties": { + "limit": { + "type": "integer", + "minimum": 1, + "description": "Maximum number of items to return." + }, + "recent_first": { + "type": "boolean", + "description": "Whether to return the most recently created items first." + }, + "tool_namespace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Callable namespace to include. When set, non-tool messages are excluded." + }, + "role": { + "anyOf": [ + { + "type": "string", + "enum": [ + "user", + "assistant", + "tool", + "system", + "developer" + ] + }, + { + "type": "null" + } + ], + "description": "Message role to include. Null or omission includes all roles." + }, + "agent_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Agent whose history to inspect. Omit to use the current agent; otherwise pass an absolute agent name or a name relative to the current agent." + }, + "tool_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Callable tool name to include. When set, non-tool messages are excluded." + }, + "window_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Full window ID. Null or omission includes all windows." + }, + "max_chars_per_item": { + "type": "integer", + "minimum": 1, + "description": "Maximum characters returned in each item's truncated_content." + } + } + } + } + ] + }, + { + "type": "namespace", + "name": "history", + "tools": [ + { + "type": "function", + "name": "read_item", + "parameters": { + "type": "object", + "properties": { + "agent_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Agent whose history to inspect. Omit to use the current agent; otherwise pass an absolute agent name or a name relative to the current agent." + }, + "item_id": { + "type": "string", + "description": "The short item ID is the suffix shown in the target item's trailing `[id: ...]` marker, printed after that item's content." + }, + "offset_chars": { + "type": "integer", + "minimum": 0, + "description": "Zero-based character offset at which reading starts." + }, + "limit_chars": { + "type": "integer", + "minimum": 1, + "description": "Maximum number of characters to return." + }, + "window_id": { + "type": "string", + "description": "Full window ID containing the item." + } + }, + "required": [ + "item_id", + "window_id" + ] + } + } + ] + }, + { + "type": "namespace", + "name": "history", + "tools": [ + { + "type": "function", + "name": "search_contents", + "parameters": { + "type": "object", + "properties": { + "limit": { + "type": "integer", + "minimum": 1, + "description": "Maximum number of matching items to return." + }, + "query": { + "type": "string", + "encrypted": true, + "description": "Case-sensitive literal substring to find in item content." + }, + "recent_first": { + "type": "boolean", + "description": "Whether to return the most recently created matches first." + }, + "tool_namespace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Callable namespace to include. When set, non-tool messages are excluded." + }, + "role": { + "anyOf": [ + { + "type": "string", + "enum": [ + "user", + "assistant", + "tool", + "system", + "developer" + ] + }, + { + "type": "null" + } + ], + "description": "Message role to include. Null or omission includes all roles." + }, + "agent_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Agent whose history to inspect. Omit to use the current agent; otherwise pass an absolute agent name or a name relative to the current agent." + }, + "tool_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Callable tool name to include. When set, non-tool messages are excluded." + }, + "window_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Full window ID. Null or omission includes all windows." + } + }, + "required": [ + "query" + ] + } + } + ] + }, + { + "type": "namespace", + "name": "notes", + "tools": [ + { + "type": "function", + "name": "list_files_by_prefix", + "parameters": { + "type": "object", + "properties": { + "prefix": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Note path prefix to list." + }, + "max_results": { + "type": "integer", + "minimum": 1, + "description": "Maximum number of files to return." + }, + "file_order_by": { + "type": "string", + "enum": [ + "name", + "created_at", + "updated_at" + ], + "description": "Field used to order files." + }, + "file_order": { + "type": "string", + "enum": [ + "ascending", + "descending" + ], + "description": "Direction used to order files." + } + } + } + } + ] + }, + { + "type": "namespace", + "name": "notes", + "tools": [ + { + "type": "function", + "name": "read_file", + "parameters": { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "Note file path to read." + }, + "start_line": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "description": "First line to return, inclusive and 1-based. Negative values count backward from the final line." + }, + "stop_line": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "description": "Last line to return, inclusive and 1-based. Negative values count backward from the final line." + } + }, + "required": [ + "path" + ] + } + } + ] + }, + { + "type": "namespace", + "name": "notes", + "tools": [ + { + "type": "function", + "name": "search_contents", + "parameters": { + "type": "object", + "properties": { + "max_matches_per_file": { + "type": "integer", + "minimum": 1, + "description": "Maximum number of matching lines returned per file." + }, + "query": { + "type": "string", + "encrypted": true, + "description": "Case-sensitive literal substring to find in note lines." + }, + "recent_file_first": { + "type": "boolean", + "description": "Whether to order matching files by creation time, newest first." + }, + "max_files": { + "type": "integer", + "minimum": 1, + "description": "Maximum number of matching files returned." + }, + "path_prefix": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Note path prefix to search." + } + }, + "required": [ + "query" + ] + } + } + ] + } + ] +} diff --git a/internal/client/codex/tool-schema/tool_schema.go b/internal/client/codex/tool-schema/tool_schema.go index 3c240a10d39..21e0a477b96 100644 --- a/internal/client/codex/tool-schema/tool_schema.go +++ b/internal/client/codex/tool-schema/tool_schema.go @@ -35,6 +35,7 @@ func headerValueCaseInsensitive(headers http.Header, name string) string { return "" } +// Keys are explicit schema paths relative to parameters.properties, not recursive field names. var codexClientToolIntegerFields = map[string]map[string]struct{}{ "exec_command": { "yield_time_ms": struct{}{}, @@ -60,10 +61,85 @@ var codexClientToolIntegerFields = map[string]map[string]struct{}{ "limit": struct{}{}, }, "test_sync_tool": { - "sleep_before_ms": struct{}{}, - "sleep_after_ms": struct{}{}, - "participants": struct{}{}, - "timeout_ms": struct{}{}, + "sleep_before_ms": struct{}{}, + "sleep_after_ms": struct{}{}, + "participants": struct{}{}, + "timeout_ms": struct{}{}, + "barrier.properties.participants": struct{}{}, + "barrier.properties.timeout_ms": struct{}{}, + }, + "create_goal": { + "token_budget": struct{}{}, + }, + "get_channels": { + "limit": struct{}{}, + }, + "list_threads": { + "limit": struct{}{}, + "max_chars_per_post": struct{}{}, + }, + "search_posts": { + "limit": struct{}{}, + "max_chars_per_post": struct{}{}, + }, + "read_thread": { + "limit": struct{}{}, + "max_chars_per_post": struct{}{}, + }, + "read_post": { + "offset_chars": struct{}{}, + "limit_chars": struct{}{}, + }, + "memories__list": { + "max_results": struct{}{}, + }, + "memories__read": { + "line_offset": struct{}{}, + "max_lines": struct{}{}, + }, + "memories__search": { + "context_lines": struct{}{}, + "max_results": struct{}{}, + }, + "history__list_windows": { + "limit": struct{}{}, + }, + "history__list_items": { + "limit": struct{}{}, + "max_chars_per_item": struct{}{}, + }, + "history__read_item": { + "offset_chars": struct{}{}, + "limit_chars": struct{}{}, + }, + "history__search_contents": { + "limit": struct{}{}, + }, + "notes__list_files_by_prefix": { + "max_results": struct{}{}, + }, + "notes__read_file": { + "start_line": struct{}{}, + "stop_line": struct{}{}, + // Codex declares signed line numbers in the first nullable union branch. + "start_line.anyOf.0": struct{}{}, + "stop_line.anyOf.0": struct{}{}, + }, + "notes__search_contents": { + "max_matches_per_file": struct{}{}, + "max_files": struct{}{}, + }, + "image_gen__imagegen": { + "num_last_images_to_include": struct{}{}, + }, + "web__run": { + "search_query.items.properties.recency": struct{}{}, + "image_query.items.properties.recency": struct{}{}, + "open.items.properties.lineno": struct{}{}, + "click.items.properties.id": struct{}{}, + "screenshot.items.properties.pageno": struct{}{}, + "weather.items.properties.duration": struct{}{}, + "sports.items.properties.num_games": struct{}{}, }, } @@ -74,6 +150,13 @@ func matchCodexTargetTool(toolName string) map[string]struct{} { } else if strings.HasPrefix(baseName, "collab__") { baseName = strings.TrimPrefix(baseName, "collab__") } + switch baseName { + case "multi_agent_v1__wait_agent", "collaboration__wait_agent": + baseName = "wait_agent" + case "collaboration__get_channels", "collaboration__list_threads", "collaboration__search_posts", + "collaboration__read_thread", "collaboration__read_post": + baseName = strings.TrimPrefix(baseName, "collaboration__") + } return codexClientToolIntegerFields[baseName] } @@ -96,9 +179,9 @@ func normalizeCodexToolFieldTypes(rawParams []byte, targetFields map[string]stru if !typeVal.Exists() { continue } - escapedKey := escapeCodexSjsonKey(fieldName) + typePath := "properties." + fieldName + ".type" if typeVal.Type == gjson.String && typeVal.String() == "number" { - if updated, errSet := sjson.SetBytes(rawParams, "properties."+escapedKey+".type", "integer"); errSet == nil { + if updated, errSet := sjson.SetBytes(rawParams, typePath, "integer"); errSet == nil { rawParams = updated changed = true } @@ -119,7 +202,7 @@ func normalizeCodexToolFieldTypes(rawParams []byte, targetFields map[string]stru } } if hasNumber { - if updated, errSet := sjson.SetBytes(rawParams, "properties."+escapedKey+".type", newTypes); errSet == nil { + if updated, errSet := sjson.SetBytes(rawParams, typePath, newTypes); errSet == nil { rawParams = updated changed = true } @@ -142,7 +225,7 @@ func NormalizeCodexToolIntegerTypes(body []byte, headers http.Header) []byte { // 1. Process top-level tools toolsResult := gjson.GetBytes(body, "tools") if toolsResult.IsArray() { - if updated, ok := normalizeToolIntegerTypesInArray(toolsResult); ok { + if updated, ok := normalizeToolIntegerTypesInArray(toolsResult, ""); ok { if out, errSet := sjson.SetRawBytes(body, "tools", updated); errSet == nil { body = out changed = true @@ -157,7 +240,7 @@ func NormalizeCodexToolIntegerTypes(body []byte, headers http.Header) []byte { if item.Get("type").String() == "additional_tools" { addTools := item.Get("tools") if addTools.IsArray() { - if updated, ok := normalizeToolIntegerTypesInArray(addTools); ok { + if updated, ok := normalizeToolIntegerTypesInArray(addTools, ""); ok { path := fmt.Sprintf("input.%d.tools", idx) if out, errSet := sjson.SetRawBytes(body, path, updated); errSet == nil { body = out @@ -175,14 +258,14 @@ func NormalizeCodexToolIntegerTypes(body []byte, headers http.Header) []byte { return body } -func normalizeToolIntegerTypesInArray(tools gjson.Result) ([]byte, bool) { +func normalizeToolIntegerTypesInArray(tools gjson.Result, namespace string) ([]byte, bool) { if !tools.IsArray() { return nil, false } var out []byte offset := 0 tools.ForEach(func(_, tool gjson.Result) bool { - updated, changed := normalizeToolIntegerTypesInElement(tool) + updated, changed := normalizeToolIntegerTypesInElement(tool, namespace) if !changed { return true } @@ -201,15 +284,22 @@ func normalizeToolIntegerTypesInArray(tools gjson.Result) ([]byte, bool) { return append(out, tools.Raw[offset:]...), true } -func normalizeToolIntegerTypesInElement(tool gjson.Result) ([]byte, bool) { +func normalizeToolIntegerTypesInElement(tool gjson.Result, namespace string) ([]byte, bool) { toolRaw := []byte(tool.Raw) changed := false // Handle namespace tools if tool.Get("type").String() == "namespace" { + if namespace != "" { + return nil, false + } + namespace = tool.Get("name").String() + if namespace == "" { + return nil, false + } nested := tool.Get("tools") if nested.IsArray() { - if updated, ok := normalizeToolIntegerTypesInArray(nested); ok { + if updated, ok := normalizeToolIntegerTypesInArray(nested, namespace); ok { if out, errSet := sjson.SetRawBytes(toolRaw, "tools", updated); errSet == nil { toolRaw = out changed = true @@ -223,7 +313,7 @@ func normalizeToolIntegerTypesInElement(tool gjson.Result) ([]byte, bool) { for _, declKey := range []string{"function_declarations", "functionDeclarations"} { decls := tool.Get(declKey) if decls.IsArray() { - if updated, ok := normalizeToolIntegerTypesInArray(decls); ok { + if updated, ok := normalizeToolIntegerTypesInArray(decls, namespace); ok { if out, errSet := sjson.SetRawBytes(toolRaw, declKey, updated); errSet == nil { toolRaw = out changed = true @@ -256,6 +346,9 @@ func normalizeToolIntegerTypesInElement(tool gjson.Result) ([]byte, bool) { } } + if namespace != "" { + toolName = namespace + "__" + toolName + } targetFields := matchCodexTargetTool(toolName) if len(targetFields) == 0 { return nil, false @@ -272,10 +365,3 @@ func normalizeToolIntegerTypesInElement(tool gjson.Result) ([]byte, bool) { } return updatedTool, true } - -func escapeCodexSjsonKey(key string) string { - key = strings.ReplaceAll(key, `\`, `\\`) - key = strings.ReplaceAll(key, `.`, `\.`) - key = strings.ReplaceAll(key, `:`, `\:`) - return key -} diff --git a/internal/client/codex/tool-schema/tool_schema_integer_fields_test.go b/internal/client/codex/tool-schema/tool_schema_integer_fields_test.go new file mode 100644 index 00000000000..580e4813b48 --- /dev/null +++ b/internal/client/codex/tool-schema/tool_schema_integer_fields_test.go @@ -0,0 +1,219 @@ +package toolschema + +import ( + "bytes" + "fmt" + "net/http" + "os" + "strings" + "testing" + + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +func TestNormalizeCodexToolIntegerTypesSourceFields(t *testing.T) { + // Paths follow the input schemas and Deserialize types in codex-rs core and ext. + tests := []struct { + name string + fields []string + }{ + {"test_sync_tool", []string{"barrier.properties.participants", "barrier.properties.timeout_ms"}}, + {"create_goal", []string{"token_budget"}}, + {"get_channels", []string{"limit"}}, + {"list_threads", []string{"limit", "max_chars_per_post"}}, + {"search_posts", []string{"limit", "max_chars_per_post"}}, + {"read_thread", []string{"limit", "max_chars_per_post"}}, + {"read_post", []string{"offset_chars", "limit_chars"}}, + {"memories__list", []string{"max_results"}}, + {"memories__read", []string{"line_offset", "max_lines"}}, + {"memories__search", []string{"context_lines", "max_results"}}, + {"history__list_windows", []string{"limit"}}, + {"history__list_items", []string{"limit", "max_chars_per_item"}}, + {"history__read_item", []string{"offset_chars", "limit_chars"}}, + {"history__search_contents", []string{"limit"}}, + {"notes__list_files_by_prefix", []string{"max_results"}}, + {"notes__read_file", []string{"start_line", "stop_line", "start_line.anyOf.0", "stop_line.anyOf.0"}}, + {"notes__search_contents", []string{"max_matches_per_file", "max_files"}}, + {"image_gen__imagegen", []string{"num_last_images_to_include"}}, + {"web__run", []string{ + "search_query.items.properties.recency", "image_query.items.properties.recency", + "open.items.properties.lineno", "click.items.properties.id", + "screenshot.items.properties.pageno", "weather.items.properties.duration", + "sports.items.properties.num_games", + }}, + {"collaboration__wait_agent", []string{"timeout_ms"}}, + {"multi_agent_v1__wait_agent", []string{"timeout_ms"}}, + {"functions__create_goal", []string{"token_budget"}}, + {"collab__read_post", []string{"offset_chars", "limit_chars"}}, + {"collaboration__get_channels", []string{"limit"}}, + {"collaboration__list_threads", []string{"limit", "max_chars_per_post"}}, + {"collaboration__search_posts", []string{"limit", "max_chars_per_post"}}, + {"collaboration__read_thread", []string{"limit", "max_chars_per_post"}}, + {"collaboration__read_post", []string{"offset_chars", "limit_chars"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + for _, typeJSON := range []string{`"number"`, `["number","integer","null"]`, `"integer"`, `"string"`} { + input := []byte(fmt.Sprintf(`{"tools":[{"type":"function","name":%q,"parameters":{"type":"object","properties":{"unrelated":{"type":"number","default":1.5}}},"output_schema":{"properties":{"wall_time_seconds":{"type":"number"}}}}],"input":[{"type":"function_call","arguments":"{\"limit\":1.5}"}]}`, tt.name)) + for _, field := range tt.fields { + input = setIntegerTestRaw(t, input, "tools.0.parameters.properties."+field, `{"type":`+typeJSON+`,"description":"Keep metadata","minimum":0,"default":1}`) + } + for _, ua := range []string{"codex-tui/0.154.0", "curl/8.7.1", ""} { + var headers http.Header + if ua != "" { + headers = http.Header{"user-agent": []string{ua}} + } + want := bytes.Clone(input) + if ua == "codex-tui/0.154.0" { + wantType := typeJSON + if typeJSON == `"number"` { + wantType = `"integer"` + } else if typeJSON == `["number","integer","null"]` { + wantType = `["integer","null"]` + } + for _, field := range tt.fields { + want = setIntegerTestRaw(t, want, "tools.0.parameters.properties."+field+".type", wantType) + } + } + out := NormalizeCodexToolIntegerTypes(input, headers) + if !bytes.Equal(out, want) { + t.Fatalf("UA %q type %s: got %s, want %s", ua, typeJSON, out, want) + } + if again := NormalizeCodexToolIntegerTypes(out, headers); !bytes.Equal(again, out) { + t.Fatal("normalization is not idempotent") + } + } + } + }) + } +} + +func TestNormalizeCodexToolIntegerTypesNamespaceFormats(t *testing.T) { + schema := `{"type":"object","properties":{"line_offset":{"type":"number"},"max_lines":{"type":["number","null"]},"max_tokens":{"type":"number"}}}` + tests := []struct { + name string + body string + path string + }{ + {"responses", `{"tools":[{"type":"function","name":"memories__read","parameters":%s}]}`, "tools.0.parameters"}, + {"chat", `{"tools":[{"type":"function","function":{"name":"memories__read","parameters":%s}}]}`, "tools.0.function.parameters"}, + {"claude", `{"tools":[{"name":"memories__read","input_schema":%s}]}`, "tools.0.input_schema"}, + {"gemini", `{"tools":[{"function_declarations":[{"name":"memories__read","parameters":%s}]}]}`, "tools.0.function_declarations.0.parameters"}, + {"gemini JSON schema", `{"tools":[{"functionDeclarations":[{"name":"memories__read","parametersJsonSchema":%s}]}]}`, "tools.0.functionDeclarations.0.parametersJsonSchema"}, + {"namespace", `{"tools":[{"type":"namespace","name":"memories","tools":[{"type":"function","name":"read","parameters":%s}]}]}`, "tools.0.tools.0.parameters"}, + {"additional namespace", `{"input":[{"type":"additional_tools","tools":[{"type":"namespace","name":"memories","tools":[{"type":"function","name":"read","parameters":%s}]}]}]}`, "input.0.tools.0.tools.0.parameters"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + input := []byte(fmt.Sprintf(tt.body, schema)) + want := setIntegerTestRaw(t, input, tt.path+".properties.line_offset.type", `"integer"`) + want = setIntegerTestRaw(t, want, tt.path+".properties.max_lines.type", `["integer","null"]`) + out := NormalizeCodexToolIntegerTypes(input, http.Header{"User-Agent": []string{"Codex/1.0"}}) + if !bytes.Equal(out, want) { + t.Fatalf("got %s, want %s", out, want) + } + }) + } +} + +func TestNormalizeCodexToolIntegerTypesPreservesUnprovenFields(t *testing.T) { + tests := []struct { + name string + namespace string + }{ + {"unknown_tool", ""}, {"mcp__server__read_post", ""}, + {"read", ""}, {"run", ""}, {"imagegen", ""}, + {"read_post", "user_tools"}, {"wait_agent", "mcp__server"}, + {"read", "skills"}, {"read", "user_tools"}, + {"read_post", "multi_agent_v1"}, {"read_post", "arbitrary_collaboration"}, + } + for _, tt := range tests { + t.Run(tt.namespace+"/"+tt.name, func(t *testing.T) { + tool := fmt.Sprintf(`{"type":"function","name":%q,"parameters":{"properties":{"limit":{"type":"number"},"offset_chars":{"type":"number"},"line_offset":{"type":"number"},"timeout_ms":{"type":"number"}}}}`, tt.name) + if tt.namespace != "" { + tool = fmt.Sprintf(`{"type":"namespace","name":%q,"tools":[%s]}`, tt.namespace, tool) + } + input := []byte(`{"tools":[` + tool + `]}`) + out := NormalizeCodexToolIntegerTypes(input, http.Header{"User-Agent": []string{"codex"}}) + if !bytes.Equal(out, input) { + t.Fatalf("unknown tool changed: %s", out) + } + }) + } + input := []byte(`{"tools":[{"name":"test_sync_tool","parameters":{"properties":{"barrier.participants":{"type":"number"},"other":{"properties":{"participants":{"type":"number"}}},"barrier":{"properties":{"participants":{"type":"number"},"ratio":{"type":"number"}}}}}}]}`) + out := NormalizeCodexToolIntegerTypes(input, http.Header{"User-Agent": []string{"codex"}}) + want := setIntegerTestRaw(t, input, "tools.0.parameters.properties.barrier.properties.participants.type", `"integer"`) + if !bytes.Equal(out, want) || !gjson.ValidBytes(out) { + t.Fatalf("nested path changed unrelated fields: %s", out) + } +} + +func TestNormalizeCodexToolIntegerTypesHistoryNotesSchemas(t *testing.T) { + // Parameter schemas copied from codex-rs/ext/history-notes/src/tools.rs:143-218. + fixture, errRead := os.ReadFile("testdata/history_notes_tools.json") + if errRead != nil { + t.Fatal(errRead) + } + if !gjson.ValidBytes(fixture) { + t.Fatal("invalid source schema fixture") + } + for _, namespace := range gjson.GetBytes(fixture, "tools").Array() { + tool := namespace.Get("tools.0") + name := namespace.Get("name").String() + "__" + tool.Get("name").String() + t.Run(name, func(t *testing.T) { + formats := []struct { + name string + body string + }{ + {"namespace", `{"tools":[` + namespace.Raw + `]}`}, + {"flat", fmt.Sprintf(`{"tools":[{"name":%q,"parameters":%s}]}`, name, tool.Get("parameters").Raw)}, + {"additional", `{"input":[{"type":"additional_tools","tools":[` + namespace.Raw + `]}]}`}, + } + for _, format := range formats { + t.Run(format.name, func(t *testing.T) { + // Simulate integer declarations degraded to number, retaining the real schema shape. + input := []byte(strings.ReplaceAll(format.body, `"type": "integer"`, `"type": "number"`)) + for _, ua := range []string{"codex", "curl", ""} { + want := input + if ua == "codex" { + want = []byte(format.body) + } + out := NormalizeCodexToolIntegerTypes(input, http.Header{"User-Agent": []string{ua}}) + if !bytes.Equal(out, want) { + t.Fatalf("UA %q: got %s, want %s", ua, out, want) + } + if again := NormalizeCodexToolIntegerTypes(out, http.Header{"User-Agent": []string{ua}}); !bytes.Equal(again, out) { + t.Fatal("source schema is not stable") + } + } + }) + } + for _, unknownName := range []string{tool.Get("name").String(), "mcp__server__" + name, "user__" + name} { + input := []byte(fmt.Sprintf(`{"tools":[{"name":%q,"parameters":%s}]}`, unknownName, strings.ReplaceAll(tool.Get("parameters").Raw, `"type": "integer"`, `"type": "number"`))) + if out := NormalizeCodexToolIntegerTypes(input, http.Header{"User-Agent": []string{"codex"}}); !bytes.Equal(out, input) { + t.Fatalf("unknown tool %q changed: %s", unknownName, out) + } + } + }) + } +} + +func TestNormalizeCodexToolIntegerTypesNotesExplicitUnionPaths(t *testing.T) { + input := []byte(`{"tools":[{"name":"notes__read_file","parameters":{"type":"object","properties":{"start_line":{"anyOf":[{"type":"number"},{"type":"null"}],"default":-3},"stop_line":{"anyOf":[{"type":"number"},{"type":"number"}],"default":-1},"ratio":{"anyOf":[{"type":"number"},{"type":"null"}]},"other":{"properties":{"start_line":{"anyOf":[{"type":"number"}]}}}},"required":["path"]}}],"input":[{"type":"function_call","arguments":"{\"start_line\":-3,\"stop_line\":-1}"}]}`) + want := setIntegerTestRaw(t, input, "tools.0.parameters.properties.start_line.anyOf.0.type", `"integer"`) + want = setIntegerTestRaw(t, want, "tools.0.parameters.properties.stop_line.anyOf.0.type", `"integer"`) + out := NormalizeCodexToolIntegerTypes(input, http.Header{"User-Agent": []string{"codex"}}) + if !bytes.Equal(out, want) { + t.Fatalf("explicit union paths changed unrelated branches or signed values: %s", out) + } +} + +func setIntegerTestRaw(t *testing.T, body []byte, path, value string) []byte { + t.Helper() + out, errSet := sjson.SetRawBytes(body, path, []byte(value)) + if errSet != nil { + t.Fatal(errSet) + } + return out +} From 8a945b3fb8d18927d469476c13b10f28aa6ddec1 Mon Sep 17 00:00:00 2001 From: sususu Date: Sat, 3 Oct 2026 17:24:32 +0800 Subject: [PATCH 022/142] fix(antigravity): restore Claude 4.6 model definitions --- internal/registry/models/models.json | 48 ++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/internal/registry/models/models.json b/internal/registry/models/models.json index 462b77eee16..228ef1c7319 100644 --- a/internal/registry/models/models.json +++ b/internal/registry/models/models.json @@ -3978,6 +3978,54 @@ } ], "antigravity": [ + { + "id": "claude-opus-4-6-thinking", + "object": "model", + "owned_by": "antigravity", + "type": "antigravity", + "display_name": "Claude Opus 4.6 (Thinking)", + "name": "claude-opus-4-6-thinking", + "description": "Claude Opus 4.6 (Thinking)", + "context_length": 200000, + "max_completion_tokens": 64000, + "thinking": { + "min": 1024, + "max": 64000, + "zero_allowed": true, + "dynamic_allowed": true + }, + "supportedInputModalities": [ + "text", + "image" + ], + "supportedOutputModalities": [ + "text" + ] + }, + { + "id": "claude-sonnet-4-6", + "object": "model", + "owned_by": "antigravity", + "type": "antigravity", + "display_name": "Claude Sonnet 4.6 (Thinking)", + "name": "claude-sonnet-4-6", + "description": "Claude Sonnet 4.6 (Thinking)", + "context_length": 200000, + "max_completion_tokens": 64000, + "thinking": { + "min": 1024, + "max": 64000, + "zero_allowed": true, + "dynamic_allowed": true + }, + "supportedInputModalities": [ + "text", + "image" + ], + "supportedOutputModalities": [ + "text" + ] + }, { "id": "claude-opus-5-5-high", "object": "model", From 9b9c2bdf54b01944248047133c7f79aea8250021 Mon Sep 17 00:00:00 2001 From: sususu Date: Sat, 3 Oct 2026 17:31:27 +0800 Subject: [PATCH 023/142] feat(antigravity): support Claude 5.5 CAQS thinking signature replay --- .../executor/antigravity_caqs_replay_test.go | 145 ++++++++++++++++++ .../claude_antigravity_validation.go | 44 ++++++ .../claude_antigravity_validation_test.go | 145 ++++++++++++++++++ internal/signature/claude_validation.go | 61 +++++--- internal/signature/provider_compatibility.go | 18 ++- .../signature/provider_compatibility_test.go | 7 +- internal/signature/signaturetest/claude.go | 35 +++++ 7 files changed, 430 insertions(+), 25 deletions(-) create mode 100644 internal/runtime/executor/antigravity_caqs_replay_test.go create mode 100644 internal/signature/claude_antigravity_validation.go create mode 100644 internal/signature/claude_antigravity_validation_test.go create mode 100644 internal/signature/signaturetest/claude.go diff --git a/internal/runtime/executor/antigravity_caqs_replay_test.go b/internal/runtime/executor/antigravity_caqs_replay_test.go new file mode 100644 index 00000000000..7190604945e --- /dev/null +++ b/internal/runtime/executor/antigravity_caqs_replay_test.go @@ -0,0 +1,145 @@ +package executor + +import ( + "bytes" + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/cache" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/signature/signaturetest" + antigravityclaude "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/antigravity/claude" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +func TestAntigravityExecutorCAQSTwoTurnReplay(t *testing.T) { + sig := signaturetest.AntigravityCAQS() + previousCache, previousStrict := cache.SignatureCacheEnabled(), cache.SignatureBypassStrictMode() + t.Cleanup(func() { + cache.SetSignatureCacheEnabled(previousCache) + cache.SetSignatureBypassStrictMode(previousStrict) + }) + for _, mode := range []struct { + name string + cached, strict bool + }{{"cache", true, false}, {"bypass", false, false}, {"strict", false, true}} { + t.Run(mode.name, func(t *testing.T) { + cache.SetSignatureCacheEnabled(mode.cached) + cache.SetSignatureBypassStrictMode(mode.strict) + for _, streaming := range []bool{false, true} { + t.Run(fmt.Sprintf("stream=%t", streaming), func(t *testing.T) { + model := "claude-opus-5-5-high" + response := []byte(`{"response":{"candidates":[{"content":{"role":"model","parts":[{"thought":true,"text":"checked calculation","thoughtSignature":"` + sig + `"},{"text":"34113"}]},"finishReason":"STOP"}],"modelVersion":"claude-opus-5-5-high","usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":2,"thoughtsTokenCount":3,"totalTokenCount":15}}}`) + requests := make(chan []byte, 2) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, errBody := io.ReadAll(r.Body) + if errBody != nil { + t.Error(errBody) + w.WriteHeader(500) + return + } + requests <- b + if strings.Contains(r.URL.Path, "streamGenerateContent") { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = fmt.Fprintf(w, "data: %s\n\n", response) + } else { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write(response) + } + })) + defer server.Close() + executor := NewAntigravityExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{ID: "caqs-replay-" + t.Name(), Metadata: map[string]any{"access_token": "test-token", "expired": time.Now().Add(time.Hour).Format(time.RFC3339), "project_id": "test-project"}, Attributes: map[string]string{"base_url": server.URL}} + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude, ResponseFormat: sdktranslator.FormatClaude, Stream: streaming} + call := func(payload []byte) []byte { + t.Helper() + req := cliproxyexecutor.Request{Model: model, Payload: payload} + if !streaming { + res, errExecute := executor.Execute(context.Background(), auth, req, opts) + if errExecute != nil { + t.Fatal(errExecute) + } + return res.Payload + } + res, errExecute := executor.ExecuteStream(context.Background(), auth, req, opts) + if errExecute != nil { + t.Fatal(errExecute) + } + var out []byte + for chunk := range res.Chunks { + if chunk.Err != nil { + t.Fatal(chunk.Err) + } + out = append(out, chunk.Payload...) + } + return out + } + first := []byte(`{"model":"claude-opus-5-5-high","max_tokens":4096,"thinking":{"type":"enabled","budget_tokens":1024},"messages":[{"role":"user","content":"calculate"}]}`) + downstream := call(first) + <-requests + var content []byte + if streaming { + var signatureOut, thinkingOut, textOut string + for _, line := range bytes.Split(downstream, []byte("\n")) { + if !bytes.HasPrefix(line, []byte("data:")) { + continue + } + event := gjson.ParseBytes(bytes.TrimSpace(line[5:])) + switch event.Get("delta.type").String() { + case "signature_delta": + signatureOut += event.Get("delta.signature").String() + case "thinking_delta": + thinkingOut += event.Get("delta.thinking").String() + case "text_delta": + textOut += event.Get("delta.text").String() + } + } + if signatureOut != sig { + t.Fatal("stream changed the original signature") + } + content = []byte(`[{"type":"thinking"},{"type":"text"}]`) + content, _ = sjson.SetBytes(content, "0.thinking", thinkingOut) + content, _ = sjson.SetBytes(content, "0.signature", signatureOut) + content, _ = sjson.SetBytes(content, "1.text", textOut) + } else { + content = []byte(gjson.GetBytes(downstream, "content").Raw) + if gjson.GetBytes(content, "0.signature").String() != sig { + t.Fatal("nonstream changed original signature") + } + } + second := []byte(`{"model":"claude-opus-5-5-high","max_tokens":4096,"thinking":{"type":"enabled","budget_tokens":1024},"messages":[{"role":"user","content":"calculate"},{"role":"assistant","content":[]},{"role":"user","content":"plus 17"}]}`) + second, _ = sjson.SetRawBytes(second, "messages.1.content", content) + call(second) + upstream := <-requests + if gjson.GetBytes(upstream, "model").String() != model { + t.Fatal("upstream model changed") + } + parts := gjson.GetBytes(upstream, "request.contents.1.parts").Array() + if len(parts) < 2 || !parts[0].Get("thought").Bool() || parts[0].Get("text").String() != "checked calculation" || parts[0].Get("thoughtSignature").String() != sig { + t.Fatal("second turn lost thinking or changed the original signature") + } + if mode.cached { + const text = "caqs-cache-recovery-test" + cache.CacheSignature(model, text, sig) + t.Cleanup(func() { _ = cache.DeleteCachedSignatureRequired(context.Background(), model, text) }) + recovery := []byte(`{"model":"claude-opus-5-5-high","messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"caqs-cache-recovery-test"}]},{"role":"user","content":"continue"}]}`) + recovered := antigravityclaude.ConvertClaudeRequestToAntigravity(model, recovery, false) + if gjson.GetBytes(recovered, "request.contents.0.parts.0.thoughtSignature").String() != sig { + t.Fatal("cache recovery changed original signature") + } + } + }) + } + }) + } +} diff --git a/internal/signature/claude_antigravity_validation.go b/internal/signature/claude_antigravity_validation.go new file mode 100644 index 00000000000..5a714412261 --- /dev/null +++ b/internal/signature/claude_antigravity_validation.go @@ -0,0 +1,44 @@ +package signature + +import ( + "encoding/base64" + "fmt" + "strings" +) + +// InspectAntigravityClaudeCAQSSignature validates the double-base64 CAQS +// envelope observed on Antigravity Claude 5.5. This is structural validation, +// not proof of cryptographic validity or cross-account replay compatibility. +// Only two encoding layers are supported; arbitrary recursive wrapping is not. +func InspectAntigravityClaudeCAQSSignature(rawSignature string) (*ClaudeCAISSignatureInfo, error) { + sig := stripClaudeSignaturePrefix(rawSignature) + if len(sig) == 0 || len(sig) > MaxClaudeThinkingSignatureLen { + return nil, fmt.Errorf("invalid Antigravity CAQS signature length") + } + if sig[0] != 'Q' || strings.ContainsAny(sig, "\r\n") { + return nil, fmt.Errorf("invalid Antigravity CAQS wrapper") + } + inner, errDecode := base64.StdEncoding.Strict().DecodeString(sig) + if errDecode != nil { + return nil, fmt.Errorf("invalid Antigravity CAQS encoding: %w", errDecode) + } + innerText := string(inner) + if len(innerText) == 0 || innerText[0] != 'C' || strings.ContainsAny(innerText, " \t\r\n#") { + return nil, fmt.Errorf("invalid Antigravity CAQS inner encoding") + } + if _, errInner := base64.StdEncoding.Strict().DecodeString(innerText); errInner != nil { + return nil, fmt.Errorf("invalid Antigravity CAQS inner encoding: %w", errInner) + } + info, errInspect := InspectClaudeCAISSignature(innerText) + if errInspect != nil { + return nil, fmt.Errorf("invalid Antigravity CAQS payload: %w", errInspect) + } + // Scope this new replay shape to the observed Google thinking channel. + // Other versions/channels require their own capture and replay verification. + if info.EnvelopeVersion != 4 || info.ChannelID != 18 || + info.Infrastructure == nil || *info.Infrastructure != 2 || + info.BlockKind != "thinking" || !info.SignatureInContainer { + return nil, fmt.Errorf("unsupported Antigravity CAQS envelope or channel schema") + } + return info, nil +} diff --git a/internal/signature/claude_antigravity_validation_test.go b/internal/signature/claude_antigravity_validation_test.go new file mode 100644 index 00000000000..4441eec8736 --- /dev/null +++ b/internal/signature/claude_antigravity_validation_test.go @@ -0,0 +1,145 @@ +package signature + +import ( + "encoding/base64" + "strings" + "testing" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/signature/signaturetest" + "google.golang.org/protobuf/encoding/protowire" +) + +// Generate the envelope at test time; no captured signature files are needed. +func antigravityCAQSFixture(t *testing.T) string { + t.Helper() + return signaturetest.AntigravityCAQS() +} + +func TestAntigravityCAQSRecognitionAndReplay(t *testing.T) { + sig := antigravityCAQSFixture(t) + info, errInspect := InspectAntigravityClaudeCAQSSignature(sig) + if errInspect != nil { + t.Fatal(errInspect) + } + if info.EnvelopeVersion != 4 || info.ChannelID != 18 || info.Infrastructure == nil || *info.Infrastructure != 2 || info.BlockKind != "thinking" || info.ModelText != "" || info.SignatureLen != 1020 || !info.SignatureInContainer { + t.Fatalf("unexpected envelope: %+v", info) + } + if !maybeSelfDescribingSignatureEnvelope(sig) || DetectSignatureProvider(sig) != SignatureProviderClaude { + t.Fatal("double CAQS must be detected as Claude") + } + for _, opts := range []ClaudeSignatureValidationOptions{{}, {Strict: true}, {PrefixOnly: true}, {Base64Only: true}} { + if !IsValidClaudeThinkingSignature(sig, opts) { + t.Fatalf("signature rejected in mode %+v", opts) + } + normalized, errNormalize := NormalizeClaudeThinkingSignature(sig, opts) + if errNormalize != nil || normalized != sig { + t.Fatalf("normalization changed the wrapper: %v", errNormalize) + } + } + if normalized, ok := CompatibleAntigravityClaudeThinkingSignature(sig); !ok || normalized != sig { + t.Fatal("Antigravity replay must preserve the original bytes") + } + for _, target := range []SignatureProvider{SignatureProviderClaude, SignatureProviderGemini, SignatureProviderGPT, SignatureProviderKimi, SignatureProviderGrok} { + if d := DecideSignatureCompatibility(target, sig, SignatureBlockKindClaudeThinking); d.Compatible { + t.Errorf("Google wrapper must not be replayed directly to %s", target) + } + } + inner, _ := base64.StdEncoding.DecodeString(sig) + if !IsValidClaudeCAISSignature(string(inner)) { + t.Fatal("inner CAQS is invalid") + } + if _, ok := CompatibleAntigravityClaudeThinkingSignature(string(inner)); ok { + t.Fatal("bare CAQS must not be promoted to Antigravity wire format") + } +} + +func TestAntigravityCAQSRejectsMalformedWrappers(t *testing.T) { + sig := antigravityCAQSFixture(t) + inner, _ := base64.StdEncoding.DecodeString(sig) + raw, _ := base64.StdEncoding.DecodeString(string(inner)) + wrap := func(b []byte) string { + return base64.StdEncoding.EncodeToString([]byte(base64.StdEncoding.EncodeToString(b))) + } + wrongVersion := append([]byte(nil), raw...) + wrongVersion[1] = 2 + wrongInfra := append([]byte(nil), raw...) + // Locate the channel infrastructure field without touching the ciphertext. + index := strings.Index(string(wrongInfra), string([]byte{8, 18, 16, 2, 24, 2})) + if index < 0 { + t.Fatal("fixture channel missing") + } + wrongInfra[index+3] = 1 + badField := append([]byte(nil), raw...) + badField[index+2] = 18 + futureVersion := append([]byte(nil), raw...) + futureVersion[1] = 5 + wrongChannel := append([]byte(nil), raw...) + wrongChannel[index+1] = 16 + // Build an otherwise valid CAQS with its signature in the old channel slot. + misplaced := defaultClaudeCAISParts("claude-opus-5-5") + misplaced.topEnvelope = 4 + misplaced.channelID = 18 + misplacedRaw, _ := base64.StdEncoding.DecodeString(misplaced.encode()) + container, _ := extractClaudeBytesField(misplacedRaw, 2, "container") + channel, _ := extractClaudeBytesField(container, 1, "channel") + channel = protowire.AppendTag(channel, 2, protowire.VarintType) + channel = protowire.AppendVarint(channel, 2) + newContainer := protowire.AppendTag(nil, 1, protowire.BytesType) + newContainer = protowire.AppendBytes(newContainer, channel) + misplacedPayload := []byte{8, 4} + misplacedPayload = protowire.AppendTag(misplacedPayload, 2, protowire.BytesType) + misplacedPayload = protowire.AppendBytes(misplacedPayload, newContainer) + // Add a harmless unknown varint to make the inner encoding padded. + paddedPayload := append(append([]byte(nil), raw...), 32, 0) + badPadding := []byte(base64.StdEncoding.EncodeToString(paddedPayload)) + alphabet := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" + padIndex := len(badPadding) - 1 + for padIndex >= 0 && badPadding[padIndex] == '=' { + padIndex-- + } + if padIndex == len(badPadding)-1 { + t.Fatal("fixture must have padding") + } + badPadding[padIndex] = alphabet[strings.IndexByte(alphabet, badPadding[padIndex])|1] + originalContainer, _ := extractClaudeBytesField(raw, 2, "container") + originalChannel, _ := extractClaudeBytesField(originalContainer, 1, "channel") + narrationChannel := []byte(strings.Replace(string(originalChannel), "\x42\x08thinking", "\x42\x09narration", 1)) + narrationContainer := protowire.AppendTag(nil, 1, protowire.BytesType) + narrationContainer = protowire.AppendBytes(narrationContainer, narrationChannel) + narrationContainer = append(narrationContainer, originalContainer[2+len(originalChannel):]...) + narrationPayload := protowire.AppendTag([]byte{8, 4}, 2, protowire.BytesType) + narrationPayload = protowire.AppendBytes(narrationPayload, narrationContainer) + cases := map[string]string{ + "empty": "", "prefix only": "Q0FRUw==", "truncated": sig[:len(sig)-8], + "triple encoding": base64.StdEncoding.EncodeToString([]byte(sig)), + "wrapped native CAQS": base64.StdEncoding.EncodeToString([]byte(observedFable51CAQSSample)), + "wrapped native CAIS": base64.StdEncoding.EncodeToString([]byte(testClaudeCAISSignature("claude-opus-5"))), + "version": wrap(wrongVersion), "infra": wrap(wrongInfra), "infra wire type": wrap(badField), + "future version": wrap(futureVersion), "channel": wrap(wrongChannel), + "narration": wrap(narrationPayload), + "signature location": wrap(misplacedPayload), + "inner trailing space": base64.StdEncoding.EncodeToString(append(append([]byte(nil), inner...), ' ')), + "inner trailing tab": base64.StdEncoding.EncodeToString(append(append([]byte(nil), inner...), '\t')), + "inner padding bits": base64.StdEncoding.EncodeToString(badPadding), + "outer newline": sig[:8] + "\n" + sig[8:], + "inner newline": base64.StdEncoding.EncodeToString(append([]byte("CAQS\n"), inner[4:]...)), + "inner label": base64.StdEncoding.EncodeToString(append([]byte("Claude#"), inner...)), + "inner whitespace": base64.StdEncoding.EncodeToString(append([]byte(" "), inner...)), + "oversize": "Q" + strings.Repeat("A", MaxClaudeThinkingSignatureLen), + } + for name, value := range cases { + t.Run(name, func(t *testing.T) { + if _, errInspect := InspectAntigravityClaudeCAQSSignature(value); errInspect == nil { + t.Fatal("malformed envelope accepted") + } + for _, opts := range []ClaudeSignatureValidationOptions{{}, {Strict: true}, {PrefixOnly: true}, {Base64Only: true}} { + if IsValidClaudeThinkingSignature(value, opts) { + t.Fatalf("invalid wrapper accepted in mode %+v", opts) + } + } + if got, ok := CompatibleAntigravityClaudeThinkingSignature(value); ok || got != "" { + t.Fatal("invalid wrapper replayable") + } + }) + } +} diff --git a/internal/signature/claude_validation.go b/internal/signature/claude_validation.go index 9a3b174fcb1..e4e1043545c 100644 --- a/internal/signature/claude_validation.go +++ b/internal/signature/claude_validation.go @@ -12,9 +12,11 @@ // base64 index 4 = E. // - R prefix: double-layer, inner[0] == E (0x45), first 6 bits = 010001, // base64 index 17 = R. +// - Q prefix: double-layer CAQS, inner[0] == C (0x43); inspected separately +// with the observed Google version-4 thinking channel schema. // -// Valid signatures can be normalized to R-form (double-layer base64) before -// sending to the Antigravity backend. +// Classic signatures normalize to R-form before Antigravity replay. Valid +// Q-form signatures keep their original wrapper unchanged. // // # Protobuf structure (Spec sections 4.1 and 4.2) in strict mode only // @@ -100,11 +102,11 @@ // channel_id 16 channel schema, so only the envelope differs. // - Claude Messages API: the full Claude model range, same envelopes as the // Claude Code OAuth subscription. -// - Antigravity: only opus-4-6-think and sonnet-4-6, and always the -// double-layer R form on Google infrastructure (infra_google). Antigravity -// never issues a CAIS envelope or a single-layer E signature, and its replay -// path requires R form, so CompatibleAntigravityClaudeThinkingSignature -// rejects CAIS signatures. +// - Antigravity: legacy Claude models use double-layer R form on Google +// infrastructure. Claude 5.5 also emits double-layer CAQS (Q-form): one +// base64 decode yields CAQS, and the second yields an envelope version 4 +// protobuf with Google infrastructure in the channel block. Preserve that +// wrapper on replay; bare native CAIS/CAQS is not an Antigravity wrapper. // // A single conversation therefore mixes envelopes whenever a user switches model // generations or providers, and every form must stay replayable toward the @@ -126,14 +128,16 @@ const MaxClaudeThinkingSignatureLen = 32 * 1024 * 1024 // ClaudeSignatureValidationOptions controls how far Claude thinking signatures // are inspected. The base validation always checks the cache prefix, base64 // layers, and decoded 0x12 Claude payload marker. Strict mode additionally -// verifies the known protobuf tree used by Claude thinking signatures. +// verifies the classic protobuf tree. Q-form always receives full structural +// validation, regardless of these legacy validation options. type ClaudeSignatureValidationOptions struct { - // PrefixOnly only checks for an optional cache prefix followed by an E/R - // Claude signature prefix. Use it to preserve legacy shallow cleanup. + // PrefixOnly checks the legacy E/R prefix or a fully validated Q envelope. + // Use it to preserve legacy shallow cleanup without blindly allowing Q. PrefixOnly bool // Base64Only checks the optional cache prefix, E/R Claude signature prefix, // and base64 layers without validating the decoded Claude marker or protobuf - // tree. Use it for conservative request cleanup. + // tree for legacy E/R; Q envelopes always receive structural validation. + // Use it for conservative request cleanup. Base64Only bool // AllowEmptySignatureWithEmptyText preserves empty thinking placeholders with // no signature and no thinking/text payload during strip operations. @@ -176,8 +180,8 @@ func IsValidClaudeThinkingSignature(rawSignature string, opts ...ClaudeSignature return err == nil } -// HasDecodableClaudeThinkingSignature reports whether rawSignature has the -// Claude E/R shape and its expected base64 layer(s) can be decoded. +// HasDecodableClaudeThinkingSignature checks legacy E/R encoding or a strictly +// validated Antigravity double-layer CAQS envelope. func HasDecodableClaudeThinkingSignature(rawSignature string) bool { sig := stripClaudeSignaturePrefix(rawSignature) if sig == "" || len(sig) > MaxClaudeThinkingSignatureLen { @@ -185,6 +189,9 @@ func HasDecodableClaudeThinkingSignature(rawSignature string) bool { } switch sig[0] { + case 'Q': + _, err := InspectAntigravityClaudeCAQSSignature(sig) + return err == nil case 'E': decoded, err := base64.StdEncoding.DecodeString(sig) return err == nil && len(decoded) > 0 @@ -201,12 +208,16 @@ func HasDecodableClaudeThinkingSignature(rawSignature string) bool { } // HasClaudeThinkingSignaturePrefix reports whether rawSignature has the Claude -// E/R signature prefix after stripping an optional cache prefix. +// E/R prefix or a structurally validated Q envelope after cache-prefix removal. func HasClaudeThinkingSignaturePrefix(rawSignature string) bool { sig := stripClaudeSignaturePrefix(rawSignature) if sig == "" { return false } + if sig[0] == 'Q' { + _, err := InspectAntigravityClaudeCAQSSignature(sig) + return err == nil + } return sig[0] == 'E' || sig[0] == 'R' } @@ -258,8 +269,8 @@ func ValidateClaudeThinkingSignatures(inputRawJSON []byte, opts ...ClaudeSignatu } // NormalizeClaudeThinkingSignature strips any cache prefix, validates the -// signature, and returns the double-layer R-form expected by Antigravity bypass -// mode. +// signature, and returns the double-layer R or Q form expected by Antigravity. +// Q envelopes always require structural validation, even in shallow modes. func NormalizeClaudeThinkingSignature(rawSignature string, opts ...ClaudeSignatureValidationOptions) (string, error) { opt := claudeSignatureValidationOptions(opts) sig := stripClaudeSignaturePrefix(rawSignature) @@ -272,6 +283,11 @@ func NormalizeClaudeThinkingSignature(rawSignature string, opts ...ClaudeSignatu } switch sig[0] { + case 'Q': + if _, err := InspectAntigravityClaudeCAQSSignature(sig); err != nil { + return "", err + } + return sig, nil case 'R': if err := validateClaudeDoubleLayerSignature(sig, opt); err != nil { return "", err @@ -283,7 +299,7 @@ func NormalizeClaudeThinkingSignature(rawSignature string, opts ...ClaudeSignatu } return base64.StdEncoding.EncodeToString([]byte(sig)), nil default: - return "", fmt.Errorf("invalid signature: expected 'E' or 'R' prefix, got %q", string(sig[0])) + return "", fmt.Errorf("invalid signature: expected 'E', 'R' or 'Q' prefix, got %q", string(sig[0])) } } @@ -591,12 +607,14 @@ const claudeCAISModelTextPrefix = "claude-" type ClaudeCAISSignatureInfo struct { FirstByte byte EnvelopeVersion uint64 + Infrastructure *uint64 ChannelID uint64 ModelText string BlockKind string ContextID string - SignatureLen int + SignatureLen int + SignatureInContainer bool } // IsValidClaudeCAISSignature returns whether rawSignature is a valid Claude CAIS @@ -703,6 +721,12 @@ func InspectClaudeCAISSignature(rawSignature string) (*ClaudeCAISSignatureInfo, } info.ChannelID = value haveChannelID = true + case 2: + value, errField := decodeClaudeCAISVarint(raw, typ, "CAIS channel field 2 infrastructure") + if errField != nil { + return errField + } + info.Infrastructure = &value case 3: if _, errField := decodeClaudeCAISVarint(raw, typ, "CAIS channel field 3 version"); errField != nil { return errField @@ -754,6 +778,7 @@ func InspectClaudeCAISSignature(rawSignature string) (*ClaudeCAISSignatureInfo, } if !haveSignatureBytes && info.EnvelopeVersion >= 4 && len(containerSignatureBytes) > 0 { info.SignatureLen = len(containerSignatureBytes) + info.SignatureInContainer = true haveSignatureBytes = true } switch { diff --git a/internal/signature/provider_compatibility.go b/internal/signature/provider_compatibility.go index 6df2c3975ae..be24d650526 100644 --- a/internal/signature/provider_compatibility.go +++ b/internal/signature/provider_compatibility.go @@ -92,6 +92,7 @@ func SignatureProviderFromModelName(modelName string) SignatureProvider { // // 'C' -> 0x08..0x0b : Claude CAIS (0x08) // 'E' -> 0x10..0x13 : Claude single-layer (0x12), Gemini protobuf_field_2 (0x12) +// 'Q' -> 0x40..0x43 : Antigravity double-layer CAQS (0x43, inner 'C') // 'R' -> 0x44..0x47 : Claude double-layer R (0x45, inner 'E') // 'g' -> 0x80..0x83 : GPT Fernet reasoning (0x80) // @@ -106,7 +107,7 @@ func SignatureProviderFromModelName(modelName string) SignatureProvider { // DetectSignatureProviderForBlock, otherwise its signatures would fall through // to the residual class. TestSelfDescribingSignatureFirstChars_CoversEveryKnownEnvelope // fails when a replay-safe envelope is missing from this set. -const selfDescribingSignatureFirstChars = "CERg" +const selfDescribingSignatureFirstChars = "CEQRg" // base64AlphabetSet builds a byte lookup table for the alphanumeric base64 core // plus the alphabet-specific characters in extra. Signature charset validation @@ -136,7 +137,7 @@ func base64AlphabetSet(extra string) [256]bool { // classifier: a false result is conclusive, a true result only narrows the // candidate set. Opaque ciphertext that carries no envelope (xAI/Grok // encrypted_content) is uniformly distributed over the byte space, so this -// rejects roughly 92% of it with one comparison and no allocation. +// rejects most of it with one comparison and no allocation. func maybeSelfDescribingSignatureEnvelope(rawSignature string) bool { if rawSignature == "" { return false @@ -216,7 +217,7 @@ func DetectSignatureProviderForBlock(rawSignature string, blockKind SignatureBlo // The envelope pre-filter gates only the envelope probes. A blob that cannot // be an envelope skips straight to the size probe below rather than returning // early, because Kimi's uniformly distributed base64 starts with one of - // "CERg" about 6% of the time and would otherwise be dropped by whichever + // "CEQRg" about 8% of the time and would otherwise be dropped by whichever // side of the gate it happened to land on. if maybeSelfDescribingSignatureEnvelope(sig) { if IsValidGPTReasoningSignature(sig) { @@ -269,6 +270,15 @@ func DecideSignatureCompatibilityForModel(targetProvider SignatureProvider, targ BlockKind: blockKind, } + // Recognizing a Claude envelope does not authorize a Google transport + // wrapper on native Claude endpoints. Antigravity has its own replay gate. + if targetProvider == SignatureProviderClaude && detected == SignatureProviderClaude && + strings.HasPrefix(SignaturePayloadWithoutProviderPrefix(rawSignature), "Q") { + decision.Action = SignatureActionDropBlock + decision.Reason = "Antigravity CAQS wrapper requires Antigravity replay" + return decision + } + if signatureProviderMatchesTarget(targetProvider, detected) { decision.Compatible = true decision.Action = SignatureActionPreserve @@ -377,7 +387,7 @@ func CompatibleSignatureForProviderBlock(targetProvider SignatureProvider, rawSi return decision.NormalizedSignature, true } -// CompatibleAntigravityClaudeThinkingSignature returns the double-layer R-form +// CompatibleAntigravityClaudeThinkingSignature returns the double-layer R or Q form // required by Antigravity Claude replay. It only accepts signatures that are // strictly identifiable as Claude, so Gemini E-prefixed envelopes cannot slip // through the looser Antigravity bypass normalization path. diff --git a/internal/signature/provider_compatibility_test.go b/internal/signature/provider_compatibility_test.go index d75a453cb7d..1e5d4c52e53 100644 --- a/internal/signature/provider_compatibility_test.go +++ b/internal/signature/provider_compatibility_test.go @@ -59,7 +59,7 @@ func TestBase64AlphabetSet_MatchesEncoderAlphabets(t *testing.T) { // replaySafeEnvelopeFixtures returns one fixture per self-describing provider // envelope that carries replayable state. Every entry must survive the structural // pre-filter, because losing one would silently reclassify that provider. -func replaySafeEnvelopeFixtures() map[string]struct { +func replaySafeEnvelopeFixtures(t *testing.T) map[string]struct { sig string want SignatureProvider } { @@ -70,6 +70,7 @@ func replaySafeEnvelopeFixtures() map[string]struct { "claude single-layer E": {testClaudeThinkingSignature(), SignatureProviderClaude}, "claude double-layer R": {testUnpaddedAntigravityClaudeThinkingSignature(), SignatureProviderClaude}, "claude CAIS": {testClaudeCAISSignature("claude-fable-5"), SignatureProviderClaude}, + "antigravity CAQS": {antigravityCAQSFixture(t), SignatureProviderClaude}, "gemini protobuf field2": {testGeminiThoughtSignatureEnvelope(), SignatureProviderGemini}, "gpt fernet": {testGPTReasoningSignature(), SignatureProviderGPT}, } @@ -82,7 +83,7 @@ func replaySafeEnvelopeFixtures() map[string]struct { // through to the residual class. Adding a provider envelope without registering // its base64 first character fails here. func TestSelfDescribingSignatureFirstChars_CoversEveryKnownEnvelope(t *testing.T) { - for name, fixture := range replaySafeEnvelopeFixtures() { + for name, fixture := range replaySafeEnvelopeFixtures(t) { if !maybeSelfDescribingSignatureEnvelope(fixture.sig) { t.Errorf("%s: first char %q is not in selfDescribingSignatureFirstChars %q; register it or detection will skip this envelope", name, string(fixture.sig[0]), selfDescribingSignatureFirstChars) @@ -133,7 +134,7 @@ func TestGeminiASCIIUUIDIsGateIndependent(t *testing.T) { // classification of each envelope so a reordering of the validator chain cannot // silently reassign one provider's signatures to another. func TestDetectSignatureProviderForBlock_ClassifiesEveryKnownEnvelope(t *testing.T) { - for name, fixture := range replaySafeEnvelopeFixtures() { + for name, fixture := range replaySafeEnvelopeFixtures(t) { if got := DetectSignatureProvider(fixture.sig); got != fixture.want { t.Errorf("%s: DetectSignatureProvider = %q, want %q", name, got, fixture.want) } diff --git a/internal/signature/signaturetest/claude.go b/internal/signature/signaturetest/claude.go new file mode 100644 index 00000000000..197fcea14b9 --- /dev/null +++ b/internal/signature/signaturetest/claude.go @@ -0,0 +1,35 @@ +// Package signaturetest provides synthetic envelopes for signature regression tests. +package signaturetest + +import ( + "encoding/base64" + + "google.golang.org/protobuf/encoding/protowire" +) + +// AntigravityCAQS builds a double-base64 Google Claude thinking envelope. +// All opaque fields are generated zeros, not captured or replayable state. +func AntigravityCAQS() string { + appendVarint := func(dst []byte, field protowire.Number, value uint64) []byte { + return protowire.AppendVarint(protowire.AppendTag(dst, field, protowire.VarintType), value) + } + appendBytes := func(dst []byte, field protowire.Number, value []byte) []byte { + return protowire.AppendBytes(protowire.AppendTag(dst, field, protowire.BytesType), value) + } + var channel []byte + channel = appendVarint(channel, 1, 18) + channel = appendVarint(channel, 2, 2) + channel = appendVarint(channel, 3, 2) + channel = appendVarint(channel, 7, 1) + channel = appendBytes(channel, 8, []byte("thinking")) + container := appendBytes(nil, 1, channel) + container = appendBytes(container, 2, make([]byte, 12)) + container = appendBytes(container, 3, make([]byte, 12)) + container = appendBytes(container, 4, make([]byte, 48)) + container = appendBytes(container, 5, make([]byte, 1020)) + payload := appendVarint(nil, 1, 4) + payload = appendBytes(payload, 2, container) + payload = appendVarint(payload, 3, 1) + inner := base64.StdEncoding.EncodeToString(payload) + return base64.StdEncoding.EncodeToString([]byte(inner)) +} From 174248ca71629153715d6b22f54d465225319f12 Mon Sep 17 00:00:00 2001 From: sususu Date: Sat, 3 Oct 2026 17:40:47 +0800 Subject: [PATCH 024/142] fix(antigravity): reject ambiguous CAQS signature wrappers --- .../claude_antigravity_boundaries_test.go | 143 ++++++++++++++++++ .../claude_antigravity_validation.go | 5 +- internal/signature/claude_validation.go | 18 ++- internal/signature/provider_compatibility.go | 19 ++- 4 files changed, 177 insertions(+), 8 deletions(-) create mode 100644 internal/signature/claude_antigravity_boundaries_test.go diff --git a/internal/signature/claude_antigravity_boundaries_test.go b/internal/signature/claude_antigravity_boundaries_test.go new file mode 100644 index 00000000000..80648113658 --- /dev/null +++ b/internal/signature/claude_antigravity_boundaries_test.go @@ -0,0 +1,143 @@ +package signature + +import ( + "encoding/base64" + "encoding/json" + "testing" + + "github.com/tidwall/gjson" + "google.golang.org/protobuf/encoding/protowire" +) + +func TestAntigravityCAQSNativeSanitizerRejectsPrefixedWrappers(t *testing.T) { + sig := antigravityCAQSFixture(t) + for _, test := range []struct { + name, prefix string + wantDetected SignatureProvider + wantAntigravity bool + }{ + {"bare", "", SignatureProviderClaude, true}, + {"single prefix", "claude#", SignatureProviderClaude, true}, + {"alias prefix", "anthropic#", SignatureProviderClaude, true}, + {"duplicate prefix", "claude#claude#", SignatureProviderUnknown, false}, + {"nested unknown prefix", "claude#junk#", SignatureProviderUnknown, false}, + {"nested alias prefix", "anthropic#cais#", SignatureProviderUnknown, false}, + {"unknown prefix", "junk#", SignatureProviderUnknown, false}, + } { + t.Run(test.name, func(t *testing.T) { + raw := test.prefix + sig + if got := DetectSignatureProvider(raw); got != test.wantDetected { + t.Errorf("detected = %q, want %q", got, test.wantDetected) + } + decision := DecideSignatureCompatibility(SignatureProviderClaude, raw, SignatureBlockKindClaudeThinking) + if decision.Compatible || decision.Action != SignatureActionDropBlock || decision.NormalizedSignature != "" { + t.Errorf("native Claude must reject Q wrapper: %+v", decision) + } + normalized, ok := CompatibleAntigravityClaudeThinkingSignature(raw) + if ok != test.wantAntigravity || (ok && normalized != sig) || (!ok && normalized != "") { + t.Errorf("Antigravity compatibility = %t, normalized length = %d", ok, len(normalized)) + } + encoded, errMarshal := json.Marshal(raw) + if errMarshal != nil { + t.Fatal(errMarshal) + } + payload := []byte(`{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"reasoning","signature":` + string(encoded) + `},{"type":"text","text":"answer"}]}]}`) + output, report := SanitizeClaudeMessagesForClaudeUpstream(payload, "claude-opus-5-5") + parts := gjson.GetBytes(output, "messages.0.content").Array() + if len(parts) != 1 || parts[0].Get("type").String() != "text" || parts[0].Get("text").String() != "answer" || report.DroppedBlocks != 1 || report.Preserved != 0 { + t.Errorf("native sanitizer retained Google thinking wrapper: report=%+v", report) + } + }) + } +} + +func TestAntigravityCAQSRejectsDuplicateSubmessages(t *testing.T) { + inner, errDecode := base64.StdEncoding.DecodeString(antigravityCAQSFixture(t)) + if errDecode != nil { + t.Fatal(errDecode) + } + raw, errDecode := base64.StdEncoding.DecodeString(string(inner)) + if errDecode != nil { + t.Fatal(errDecode) + } + container, errExtract := extractClaudeBytesField(raw, 2, "container") + if errExtract != nil { + t.Fatal(errExtract) + } + channel, errExtract := extractClaudeBytesField(container, 1, "channel") + if errExtract != nil { + t.Fatal(errExtract) + } + bytesField := func(field protowire.Number, value []byte) []byte { + return protowire.AppendBytes(protowire.AppendTag(nil, field, protowire.BytesType), value) + } + payload := func(containers ...[]byte) []byte { + out := []byte{8, 4} + for _, value := range containers { + out = append(out, bytesField(2, value)...) + } + return append(out, 24, 1) + } + for _, test := range []struct { + name string + firstChannel []byte + }{ + {"malformed tag", []byte{0x80}}, + {"infrastructure wire type", []byte{0x12, 0x01, 0x02}}, + {"old signature slot", []byte{0x2a, 0x01, 0x01}}, + {"empty", nil}, + {"valid duplicate", channel}, + } { + for _, scope := range []string{"channel", "container"} { + t.Run(scope+"/"+test.name, func(t *testing.T) { + first := bytesField(1, test.firstChannel) + var duplicated []byte + if scope == "channel" { + duplicated = payload(append(first, container...)) + } else { + duplicated = payload(first, container) + } + assertAntigravityCAQSDuplicateRejected(t, duplicated) + }) + } + } + for _, first := range []struct { + name string + value []byte + }{ + {"malformed container", []byte{0x80}}, + {"empty container", nil}, + {"valid container duplicate", container}, + } { + t.Run(first.name, func(t *testing.T) { + assertAntigravityCAQSDuplicateRejected(t, payload(first.value, container)) + }) + } +} + +func assertAntigravityCAQSDuplicateRejected(t *testing.T, raw []byte) { + t.Helper() + inner := base64.StdEncoding.EncodeToString(raw) + // Keep legacy native CAIS/CAQS parsing behavior outside the new Q gate. + if _, errInspect := InspectClaudeCAISSignature(inner); errInspect != nil { + t.Fatalf("native parser behavior changed: %v", errInspect) + } + sig := base64.StdEncoding.EncodeToString([]byte(inner)) + if _, errInspect := InspectAntigravityClaudeCAQSSignature(sig); errInspect == nil { + t.Error("duplicate submessage passed Q structural validation") + } + for _, opts := range []ClaudeSignatureValidationOptions{{}, {Strict: true}, {PrefixOnly: true}, {Base64Only: true}} { + if IsValidClaudeThinkingSignature(sig, opts) { + t.Errorf("duplicate submessage accepted in mode %+v", opts) + } + if normalized, errNormalize := NormalizeClaudeThinkingSignature(sig, opts); errNormalize == nil || normalized != "" { + t.Errorf("duplicate submessage normalized in mode %+v", opts) + } + } + if DetectSignatureProvider(sig) != SignatureProviderUnknown { + t.Error("duplicate submessage classified as a valid signature") + } + if normalized, ok := CompatibleAntigravityClaudeThinkingSignature(sig); ok || normalized != "" { + t.Error("duplicate submessage allowed for Antigravity replay") + } +} diff --git a/internal/signature/claude_antigravity_validation.go b/internal/signature/claude_antigravity_validation.go index 5a714412261..18c57e997a2 100644 --- a/internal/signature/claude_antigravity_validation.go +++ b/internal/signature/claude_antigravity_validation.go @@ -26,10 +26,11 @@ func InspectAntigravityClaudeCAQSSignature(rawSignature string) (*ClaudeCAISSign if len(innerText) == 0 || innerText[0] != 'C' || strings.ContainsAny(innerText, " \t\r\n#") { return nil, fmt.Errorf("invalid Antigravity CAQS inner encoding") } - if _, errInner := base64.StdEncoding.Strict().DecodeString(innerText); errInner != nil { + decoded, errInner := base64.StdEncoding.Strict().DecodeString(innerText) + if errInner != nil { return nil, fmt.Errorf("invalid Antigravity CAQS inner encoding: %w", errInner) } - info, errInspect := InspectClaudeCAISSignature(innerText) + info, errInspect := inspectClaudeCAISPayload(decoded, true) if errInspect != nil { return nil, fmt.Errorf("invalid Antigravity CAQS payload: %w", errInspect) } diff --git a/internal/signature/claude_validation.go b/internal/signature/claude_validation.go index e4e1043545c..29191559d56 100644 --- a/internal/signature/claude_validation.go +++ b/internal/signature/claude_validation.go @@ -647,6 +647,12 @@ func InspectClaudeCAISSignature(rawSignature string) (*ClaudeCAISSignatureInfo, if err != nil { return nil, fmt.Errorf("invalid Claude CAIS signature: base64 decode failed: %w", err) } + return inspectClaudeCAISPayload(decoded, false) +} + +// inspectClaudeCAISPayload shares native envelope parsing with the Q replay gate. +// Only Q rejects duplicate submessages; native CAIS/CAQS behavior is unchanged. +func inspectClaudeCAISPayload(decoded []byte, rejectDuplicateMessages bool) (*ClaudeCAISSignatureInfo, error) { if len(decoded) == 0 { return nil, fmt.Errorf("invalid Claude CAIS signature: empty after decode") } @@ -658,7 +664,8 @@ func InspectClaudeCAISSignature(rawSignature string) (*ClaudeCAISSignatureInfo, var container []byte var containerSignatureBytes []byte - err = walkClaudeProtobufFields(decoded, func(num protowire.Number, typ protowire.Type, raw []byte) error { + var haveContainer bool + err := walkClaudeProtobufFields(decoded, func(num protowire.Number, typ protowire.Type, raw []byte) error { switch num { case 1: value, errField := decodeClaudeCAISVarint(raw, typ, "CAIS top-level field 1 envelope version") @@ -667,6 +674,10 @@ func InspectClaudeCAISSignature(rawSignature string) (*ClaudeCAISSignatureInfo, } info.EnvelopeVersion = value case 2: + if rejectDuplicateMessages && haveContainer { + return fmt.Errorf("invalid Antigravity CAQS signature: duplicate container") + } + haveContainer = true value, errField := decodeClaudeCAISBytes(raw, typ, "CAIS top-level field 2 container") if errField != nil { return errField @@ -687,9 +698,14 @@ func InspectClaudeCAISSignature(rawSignature string) (*ClaudeCAISSignatureInfo, } var channelBlock []byte + var haveChannelBlock bool err = walkClaudeProtobufFields(container, func(num protowire.Number, typ protowire.Type, raw []byte) error { switch num { case 1: + if rejectDuplicateMessages && haveChannelBlock { + return fmt.Errorf("invalid Antigravity CAQS signature: duplicate channel block") + } + haveChannelBlock = true value, errField := decodeClaudeCAISBytes(raw, typ, "CAIS container field 1 channel block") if errField != nil { return errField diff --git a/internal/signature/provider_compatibility.go b/internal/signature/provider_compatibility.go index be24d650526..f28d86ae272 100644 --- a/internal/signature/provider_compatibility.go +++ b/internal/signature/provider_compatibility.go @@ -164,6 +164,11 @@ func DetectSignatureProviderForBlock(rawSignature string, blockKind SignatureBlo } if prefixedProvider, unprefixed, ok := SplitSignatureProviderPrefix(sig); ok { + // Validators may strip cache prefixes themselves; never let a second + // prefix make detection disagree with the payload used for replay. + if strings.Contains(unprefixed, "#") { + return SignatureProviderUnknown + } switch prefixedProvider { case SignatureProviderGemini: if IsGeminiThoughtSignatureBypass(unprefixed) { @@ -280,11 +285,15 @@ func DecideSignatureCompatibilityForModel(targetProvider SignatureProvider, targ } if signatureProviderMatchesTarget(targetProvider, detected) { - decision.Compatible = true - decision.Action = SignatureActionPreserve - decision.NormalizedSignature = normalizeCompatibleSignatureForProvider(targetProvider, rawSignature, blockKind) - decision.Reason = claudeCompatibleSignatureReason(targetProvider, rawSignature, targetModel) - return decision + // A matching family is not sufficient: replay also requires successful + // normalization. Otherwise sanitizers could preserve the original input. + if normalized := normalizeCompatibleSignatureForProvider(targetProvider, rawSignature, blockKind); normalized != "" { + decision.Compatible = true + decision.Action = SignatureActionPreserve + decision.NormalizedSignature = normalized + decision.Reason = claudeCompatibleSignatureReason(targetProvider, rawSignature, targetModel) + return decision + } } decision.Compatible = false From 91c934f68baf4ddf4a30bf1da82a0fda331f70b4 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Sat, 3 Oct 2026 20:21:15 +0800 Subject: [PATCH 025/142] feat(responses): support local shell tool translation - Map local shell tool declarations and tool choice to synthetic function calls - Normalize shell call and output history items into chat completion tool messages - Convert upstream tool calls back to `shell_call` output items in stream and non-stream responses - Validate shell action arguments and handle invalid input errors Closes: #4812 --- .../openai_openai-responses_request.go | 8 +- .../openai_openai-responses_response.go | 46 ++++- .../openai_openai-responses_tools.go | 31 ++- .../openai/responses/responses_tool_index.go | 2 + .../openai/openai/responses/shell_tool.go | 132 +++++++++++++ .../openai/responses/shell_tool_test.go | 187 ++++++++++++++++++ 6 files changed, 400 insertions(+), 6 deletions(-) create mode 100644 internal/translator/openai/openai/responses/shell_tool.go create mode 100644 internal/translator/openai/openai/responses/shell_tool_test.go diff --git a/internal/translator/openai/openai/responses/openai_openai-responses_request.go b/internal/translator/openai/openai/responses/openai_openai-responses_request.go index a45fa2a0bc5..9c633c64f9e 100644 --- a/internal/translator/openai/openai/responses/openai_openai-responses_request.go +++ b/internal/translator/openai/openai/responses/openai_openai-responses_request.go @@ -73,7 +73,7 @@ func ConvertOpenAIResponsesRequestToOpenAIChatCompletions(modelName string, inpu // Convert input array to messages if input := root.Get("input"); input.Exists() && input.IsArray() { - rawInputArray := input.Array() + rawInputArray := toolIndex.shellHistory(input.Array()) explicitOutputCounts := make(map[string]int) missingIDOutputsCount := 0 for _, item := range rawInputArray { @@ -482,6 +482,12 @@ func convertResponsesToolChoiceWithIndex(toolChoice gjson.Result, toolIndex *res } choiceType := toolChoice.Get("type").String() + if choiceType == "shell" { + if name := toolIndex.shellName(); name != "" { + converted, _ := sjson.SetBytes([]byte(`{"type":"function","function":{}}`), "function.name", name) + return converted + } + } if choiceType != "function" && choiceType != "custom" { return []byte(toolChoice.Raw) } diff --git a/internal/translator/openai/openai/responses/openai_openai-responses_response.go b/internal/translator/openai/openai/responses/openai_openai-responses_response.go index 1a1ac352f9c..6d87b1f5ffc 100644 --- a/internal/translator/openai/openai/responses/openai_openai-responses_response.go +++ b/internal/translator/openai/openai/responses/openai_openai-responses_response.go @@ -213,6 +213,13 @@ func buildResponsesCompletedEvent(st *oaiToResponsesState, requestRawJSON []byte if _, isInc := incompleteByFinishReason(st.FinishReason); isInc { toolStatus = "incomplete" } + if st.ToolIndex.isShell(name) { + item, errShellCallItem := shellCallItem(callID, args, toolStatus) + if errShellCallItem == nil { + outputItems = append(outputItems, completedOutputItem{index: st.FuncOutputIx[key], raw: item}) + } + continue + } if st.FuncItemCustom[key] { item := []byte(`{"id":"","type":"custom_tool_call","status":"completed","input":"","call_id":"","name":""}`) item, _ = sjson.SetBytes(item, "id", fmt.Sprintf("ctc_%s", callID)) @@ -359,7 +366,7 @@ func ConvertOpenAIChatCompletionsResponseToOpenAIResponses(ctx context.Context, failToolInput := func(err error) { if st.ToolInputError() == nil { st.SetToolInputError(err) - out = append(out, emitRespEvent("response.failed", translatorcommon.ApplyPatchFailure(st.ResponseID, nextSeq()))) + out = append(out, emitRespEvent("response.failed", responsesToolInputFailure(st.ResponseID, nextSeq(), err))) } } emitToolItem := func(key string, force bool) { @@ -390,7 +397,13 @@ func ConvertOpenAIChatCompletionsResponseToOpenAIResponses(ctx context.Context, outputIndex := st.FuncOutputIx[key] _, isCustomTool := st.CustomToolNames[name] st.FuncItemCustom[key] = isCustomTool - if isCustomTool { + if st.ToolIndex.isShell(name) { + o := []byte(`{"type":"response.output_item.added"}`) + o, _ = sjson.SetBytes(o, "sequence_number", nextSeq()) + o, _ = sjson.SetBytes(o, "output_index", outputIndex) + o, _ = sjson.SetRawBytes(o, "item", shellCallPlaceholder(callID)) + out = append(out, emitRespEvent("response.output_item.added", o)) + } else if isCustomTool { if st.ToolIndex.isApplyPatch(name) { d := st.ToolIndex.byChat[name] st.ApplyPatchCalls[key] = &translatorcommon.ApplyPatchCallState{ @@ -417,7 +430,7 @@ func ConvertOpenAIChatCompletionsResponseToOpenAIResponses(ctx context.Context, st.FuncItemAdded[key] = true } emitPendingFunctionArgs := func(key string) { - if !st.FuncItemAdded[key] || st.ToolInputError() != nil { + if !st.FuncItemAdded[key] || st.ToolInputError() != nil || st.ToolIndex.isShell(st.FuncNames[key]) { return } argsBuf := st.FuncArgsBuf[key] @@ -644,6 +657,22 @@ func ConvertOpenAIChatCompletionsResponseToOpenAIResponses(ctx context.Context, toolStatus = "incomplete" } + if st.ToolIndex.isShell(name) { + item, errShellCallItem := shellCallItem(callID, args, toolStatus) + if errShellCallItem != nil { + failToolInput(errShellCallItem) + return + } + event := []byte(`{"type":"response.output_item.done"}`) + event, _ = sjson.SetBytes(event, "sequence_number", nextSeq()) + event, _ = sjson.SetBytes(event, "output_index", outputIndex) + event, _ = sjson.SetRawBytes(event, "item", item) + out = append(out, emitRespEvent("response.output_item.done", event)) + st.FuncItemDone[key] = true + st.FuncArgsDone[key] = true + continue + } + if st.FuncItemCustom[key] { input := "" if patchCall := st.ApplyPatchCalls[key]; patchCall != nil { @@ -1044,6 +1073,15 @@ func ConvertOpenAIChatCompletionsResponseToOpenAIResponsesNonStream(_ context.Co if isIncomplete { toolStatus = "incomplete" } + if toolIndex.isShell(name) { + item, errShellCallItem := shellCallItem(callID, args, toolStatus) + if errShellCallItem != nil { + st.SetToolInputError(errShellCallItem) + return false + } + outputItems = append(outputItems, item) + return true + } if _, isCustomTool := customToolNames[name]; isCustomTool { item := []byte(`{"id":"","type":"custom_tool_call","status":"completed","input":"","call_id":"","name":""}`) item, _ = sjson.SetBytes(item, "id", fmt.Sprintf("ctc_%s", callID)) @@ -1081,7 +1119,7 @@ func ConvertOpenAIChatCompletionsResponseToOpenAIResponsesNonStream(_ context.Co }) } if st.ToolInputError() != nil { - return []byte(gjson.GetBytes(translatorcommon.ApplyPatchFailure(id, 0), "response").Raw) + return []byte(gjson.GetBytes(responsesToolInputFailure(id, 0, st.ToolInputError()), "response").Raw) } if len(outputItems) > 0 { resp, _ = sjson.SetRawBytes(resp, "output", translatorcommon.JoinRawArray(outputItems)) diff --git a/internal/translator/openai/openai/responses/openai_openai-responses_tools.go b/internal/translator/openai/openai/responses/openai_openai-responses_tools.go index 6b6cb29026a..dd0a1405b20 100644 --- a/internal/translator/openai/openai/responses/openai_openai-responses_tools.go +++ b/internal/translator/openai/openai/responses/openai_openai-responses_tools.go @@ -20,6 +20,7 @@ type responsesToolDeclaration struct { localName string namespace string custom bool + shell bool } // walkResponsesToolDeclarations visits the tool declarations of a Responses @@ -36,15 +37,23 @@ type responsesToolDeclaration struct { func walkResponsesToolDeclarations(root gjson.Result, visit func(responsesToolDeclaration) bool) { var declarations []responsesToolDeclaration emit := func(tool gjson.Result, namespaceName string) { - var custom bool + var custom, shell bool switch strings.TrimSpace(tool.Get("type").String()) { case "", "function": case "custom": custom = true + case "shell": + if namespaceName != "" || tool.Get("environment.type").String() != "local" { + return + } + shell = true default: return } localName := responsesToolName(tool) + if shell { + localName = "__cpa_local_shell" + } if localName == "" { return } @@ -54,6 +63,7 @@ func walkResponsesToolDeclarations(root gjson.Result, visit func(responsesToolDe localName: localName, namespace: namespaceName, custom: custom, + shell: shell, }) } scan := func(tools gjson.Result) { @@ -86,6 +96,25 @@ func walkResponsesToolDeclarations(root gjson.Result, visit func(responsesToolDe }) } + // Reserve user identities before assigning the synthetic shell name. + reserved := make(map[string]bool) + for _, d := range declarations { + if !d.shell { + reserved[d.localName] = true + reserved[d.chatName] = true + reserved[rawResponsesNamespaceQualifiedName(d.namespace, d.localName)] = true + } + } + shellName := "__cpa_local_shell" + for suffix := 1; reserved[shellName]; suffix++ { + shellName = "__cpa_local_shell_" + strconv.Itoa(suffix) + } + for i := range declarations { + if declarations[i].shell { + declarations[i].localName = shellName + declarations[i].chatName = shellName + } + } disambiguateResponsesChatToolNames(declarations) proceed := true diff --git a/internal/translator/openai/openai/responses/responses_tool_index.go b/internal/translator/openai/openai/responses/responses_tool_index.go index f2e35a1ff30..353e897178e 100644 --- a/internal/translator/openai/openai/responses/responses_tool_index.go +++ b/internal/translator/openai/openai/responses/responses_tool_index.go @@ -118,6 +118,8 @@ func (idx *responsesToolIndex) chatTools() [][]byte { convert := convertResponsesFunctionToolToOpenAIChat if d.custom { convert = convertResponsesCustomToolToOpenAIChat + } else if d.shell { + convert = convertResponsesShellToolToOpenAIChat } if tool, ok := convert(d.tool, d.chatName); ok { merged = append(merged, tool) diff --git a/internal/translator/openai/openai/responses/shell_tool.go b/internal/translator/openai/openai/responses/shell_tool.go new file mode 100644 index 00000000000..9b8f9cd8ffc --- /dev/null +++ b/internal/translator/openai/openai/responses/shell_tool.go @@ -0,0 +1,132 @@ +package responses + +import ( + "errors" + "math" + "strconv" + "strings" + + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +var errInvalidShellAction = errors.New("invalid shell action: expected nonempty commands strings and optional positive integer limits") + +func convertResponsesShellToolToOpenAIChat(_ gjson.Result, name string) ([]byte, bool) { + tool := []byte(`{"type":"function","function":{"name":"","description":"Request commands to execute in the client-provided local shell environment. Each commands entry is a complete shell command, not an argv element.","parameters":{"type":"object","properties":{"commands":{"type":"array","items":{"type":"string"},"minItems":1},"timeout_ms":{"type":"integer","minimum":1},"max_output_length":{"type":"integer","minimum":1}},"required":["commands"],"additionalProperties":false}}}`) + tool, _ = sjson.SetBytes(tool, "function.name", name) + return tool, true +} + +func (idx *responsesToolIndex) isShell(name string) bool { + return idx.byChat[name].shell +} + +func (idx *responsesToolIndex) shellName() string { + for _, d := range idx.declarations { + if d.shell { + return d.chatName + } + } + return "" +} + +// Normalize shell history before the existing call grouping and output pairing. +// Keep the entire output envelope as JSON text, including truncation metadata. +func (idx *responsesToolIndex) shellHistory(items []gjson.Result) []gjson.Result { + name := idx.shellName() + if name == "" { + // Historical calls remain meaningful after the client withdraws the tool. + // Reserve a replay-only name without adding an available declaration. + reserved := make(map[string]bool) + for key := range idx.byChat { + reserved[key] = true + } + for key := range idx.byRaw { + reserved[key] = true + } + for key := range idx.byLocal { + reserved[key] = true + } + for _, item := range items { + if kind := item.Get("type").String(); kind == "function_call" || kind == "custom_tool_call" { + reserved[idx.canonicalName(item.Get("name").String())] = true + } + } + name = "__cpa_local_shell" + for suffix := 1; reserved[name]; suffix++ { + name = "__cpa_local_shell_" + strconv.Itoa(suffix) + } + } + for i, item := range items { + raw := []byte(item.Raw) + switch item.Get("type").String() { + case "shell_call": + if environment := item.Get("environment.type"); environment.Exists() && environment.String() != "local" { + continue + } + raw, _ = sjson.SetBytes(raw, "type", "function_call") + raw, _ = sjson.SetBytes(raw, "name", name) + raw, _ = sjson.SetBytes(raw, "arguments", item.Get("action").Raw) + case "shell_call_output": + raw, _ = sjson.SetBytes(raw, "type", "function_call_output") + raw, _ = sjson.SetBytes(raw, "output", item.Raw) + default: + continue + } + items[i] = gjson.ParseBytes(raw) + } + return items +} + +func shellCallItem(callID, arguments, status string) ([]byte, error) { + action := gjson.Parse(arguments) + if !gjson.Valid(arguments) || !action.IsObject() { + return nil, errInvalidShellAction + } + commands := action.Get("commands") + if !commands.IsArray() || len(commands.Array()) == 0 { + return nil, errInvalidShellAction + } + for _, command := range commands.Array() { + if command.Type != gjson.String || strings.TrimSpace(command.String()) == "" { + return nil, errInvalidShellAction + } + } + valid := true + action.ForEach(func(key, value gjson.Result) bool { + switch key.String() { + case "commands": + case "timeout_ms", "max_output_length": + if value.Type != gjson.Null && (value.Type != gjson.Number || value.Float() <= 0 || math.Trunc(value.Float()) != value.Float()) { + valid = false + } + default: + valid = false + } + return valid + }) + if !valid { + return nil, errInvalidShellAction + } + item := shellCallPlaceholder(callID) + item, _ = sjson.SetBytes(item, "status", status) + item, _ = sjson.SetRawBytes(item, "action", []byte(arguments)) + return item, nil +} + +func shellCallPlaceholder(callID string) []byte { + item := []byte(`{"id":"","type":"shell_call","status":"in_progress","call_id":"","action":{"commands":[]}}`) + item, _ = sjson.SetBytes(item, "id", "sh_"+callID) + item, _ = sjson.SetBytes(item, "call_id", callID) + return item +} + +func responsesToolInputFailure(responseID string, sequence int, err error) []byte { + failure := translatorcommon.ApplyPatchFailure(responseID, sequence) + if errors.Is(err, errInvalidShellAction) { + failure, _ = sjson.SetBytes(failure, "response.error.message", errInvalidShellAction.Error()) + } + return failure +} diff --git a/internal/translator/openai/openai/responses/shell_tool_test.go b/internal/translator/openai/openai/responses/shell_tool_test.go new file mode 100644 index 00000000000..3cf36f01e0a --- /dev/null +++ b/internal/translator/openai/openai/responses/shell_tool_test.go @@ -0,0 +1,187 @@ +package responses + +import ( + "context" + "encoding/json" + "reflect" + "strings" + "testing" + + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +func TestLocalShellDeclarationSurvivesChatTranslation(t *testing.T) { + request := []byte(`{"tools":[{"type":"shell","environment":{"type":"local"}}],"tool_choice":"auto","input":"Run echo SHELL_OK"}`) + got := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("test", request, false) + if gjson.GetBytes(got, "tools.#").Int() != 1 { + t.Fatalf("local shell declaration was dropped from chat request: %s", got) + } + if gjson.GetBytes(got, "tools.0.function.parameters.properties.commands.items.type").String() != "string" { + t.Fatalf("shell action must expose commands as strings: %s", got) + } +} + +const shellRequest = `{"tools":[{"type":"shell","environment":{"type":"local"}},{"type":"function","name":"__cpa_local_shell","parameters":{}},{"type":"custom","name":"__cpa_local_shell_1"},{"type":"namespace","name":"ns","tools":[{"type":"function","name":"lookup","parameters":{}}]}],"tool_choice":{"type":"shell"}}` + +func shellUpstreamCall(name, args string) []byte { + call := []byte(`{"index":0,"id":"call_shell","type":"function","function":{}}`) + call, _ = sjson.SetBytes(call, "function.name", name) + call, _ = sjson.SetBytes(call, "function.arguments", args) + return call +} + +func shellNonStream(request []byte, name, args string) []byte { + upstream := []byte(`{"id":"resp_test","choices":[{"index":0,"finish_reason":"tool_calls","message":{"role":"assistant","tool_calls":[]}}]}`) + upstream, _ = sjson.SetRawBytes(upstream, "choices.0.message.tool_calls.0", shellUpstreamCall(name, args)) + return ConvertOpenAIChatCompletionsResponseToOpenAIResponsesNonStream(context.Background(), "test", request, nil, upstream, nil) +} + +func shellStream(request []byte, name, args string) []gjson.Result { + var state any + var events []gjson.Result + push := func(chunk []byte) { + for _, output := range ConvertOpenAIChatCompletionsResponseToOpenAIResponses(context.Background(), "test", request, nil, chunk, &state) { + for _, line := range strings.Split(string(output), "\n") { + if strings.HasPrefix(line, "data: ") { + events = append(events, gjson.Parse(strings.TrimPrefix(line, "data: "))) + } + } + } + } + for i, fragment := range []string{args[:len(args)/2], args[len(args)/2:]} { + chunk := []byte(`{"id":"resp_test","choices":[{"index":0,"delta":{"tool_calls":[]}}]}`) + call := shellUpstreamCall(name, fragment) + if i == 1 { + call, _ = sjson.DeleteBytes(call, "id") + call, _ = sjson.DeleteBytes(call, "function.name") + } + chunk, _ = sjson.SetRawBytes(chunk, "choices.0.delta.tool_calls.0", call) + push(append([]byte("data: "), chunk...)) + } + push([]byte(`data: {"id":"resp_test","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}`)) + push([]byte("data: [DONE]")) + return events +} + +func TestLocalShellRoundTrip(t *testing.T) { + request := []byte(shellRequest) + chat := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("test", request, false) + name := gjson.GetBytes(chat, "tools.0.function.name").String() + if name == "" || name == "__cpa_local_shell" || name == "__cpa_local_shell_1" || gjson.GetBytes(chat, "tools.#").Int() != 4 { + t.Fatalf("synthetic tool collided with user tools: %s", chat) + } + if gjson.GetBytes(chat, "tool_choice.function.name").String() != name { + t.Fatalf("shell tool_choice not mapped: %s", chat) + } + args := `{"commands":["echo SHELL_OK","pwd"],"timeout_ms":120000,"max_output_length":4096}` + nonstream := shellNonStream(request, name, args) + item := gjson.GetBytes(nonstream, "output.0") + if item.Get("type").String() != "shell_call" || item.Get("action.commands.0").String() != "echo SHELL_OK" || item.Get("status").String() != "completed" || item.Get("name").Exists() || item.Get("arguments").Exists() { + t.Fatalf("invalid shell item: %s", nonstream) + } + var done, completed gjson.Result + for _, event := range shellStream(request, name, args) { + switch event.Get("type").String() { + case "response.output_item.added": + if event.Get("item.type").String() != "shell_call" { + t.Fatalf("wrong added item: %s", event.Raw) + } + case "response.output_item.done": + done = event.Get("item") + case "response.completed": + completed = event.Get("response.output.0") + case "response.function_call_arguments.delta", "response.function_call_arguments.done": + t.Fatalf("shell leaked function event: %s", event.Raw) + } + } + if !done.Exists() || !reflect.DeepEqual(done.Value(), item.Value()) || !reflect.DeepEqual(done.Value(), completed.Value()) { + t.Fatalf("inconsistent final items: nonstream=%s done=%s completed=%s", item.Raw, done.Raw, completed.Raw) + } + output := `{"type":"shell_call_output","call_id":"call_shell","max_output_length":4096,"output":[{"stdout":"SHELL_OK\n","stderr":"warning","outcome":{"type":"exit","exit_code":0}},{"stdout":"partial","stderr":"","outcome":{"type":"timeout"}}]}` + replay, _ := sjson.SetRawBytes(request, "input", []byte("["+item.Raw+`,`+`{"type":"function_call","call_id":"call_user","name":"__cpa_local_shell","arguments":"{}"},`+output+`,`+`{"type":"function_call_output","call_id":"call_user","output":"ok"}]`)) + replayed := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("test", replay, false) + if gjson.GetBytes(replayed, "messages.0.tool_calls.#").Int() != 2 || gjson.GetBytes(replayed, "messages.0.tool_calls.0.function.name").String() != name || gjson.GetBytes(replayed, "messages.0.tool_calls.0.function.arguments").String() != args { + t.Fatalf("shell history not grouped/replayed: %s", replayed) + } + content := gjson.GetBytes(replayed, "messages.1.content").String() + if gjson.GetBytes(replayed, "messages.1.role").String() != "tool" || !reflect.DeepEqual(gjson.Parse(content).Value(), gjson.Parse(output).Value()) { + t.Fatalf("shell output envelope lost: %s", replayed) + } + for _, tc := range []struct{ name, kind string }{{"__cpa_local_shell", "function_call"}, {"__cpa_local_shell_1", "custom_tool_call"}, {"ns__lookup", "function_call"}} { + got := shellNonStream(request, tc.name, `{"input":"hello"}`) + if gjson.GetBytes(got, "output.0.type").String() != tc.kind { + t.Fatalf("user tool misclassified: %s", got) + } + } + unknown := shellNonStream([]byte(`{}`), name, args) + if gjson.GetBytes(unknown, "output.0.type").String() != "function_call" { + t.Fatalf("synthetic name recognized without provenance: %s", unknown) + } +} + +func TestLocalShellInvalidActions(t *testing.T) { + request := []byte(`{"tools":[{"type":"shell","environment":{"type":"local"}}]}`) + for _, args := range []string{`{`, `{}`, `{"commands":[]}`, `{"commands":[42]}`, `{"commands":[" "]}`, `{"command":["echo","ok"]}`, `{"commands":["pwd"],"timeout_ms":-1}`, `{"commands":["pwd"],"timeout_ms":1.5}`, `{"commands":["pwd"],"env":{}}`} { + t.Run(args, func(t *testing.T) { + got := shellNonStream(request, "__cpa_local_shell", args) + if gjson.GetBytes(got, "status").String() != "failed" || !strings.Contains(gjson.GetBytes(got, "error.message").String(), "shell") { + t.Fatalf("invalid action accepted: %s", got) + } + failed := false + for _, event := range shellStream(request, "__cpa_local_shell", args) { + if event.Get("type").String() == "response.failed" { + failed = true + } + if event.Get("type").String() == "response.completed" || event.Get("type").String() == "response.output_item.done" { + t.Fatalf("invalid action completed: %s", event.Raw) + } + } + if !failed { + t.Fatal("invalid action did not fail streaming") + } + }) + } +} + +func TestLocalShellOnlyExplicitLocalEnvironment(t *testing.T) { + for _, environment := range []string{`{"type":"container_auto"}`, `{"type":"container_reference","container_id":"cntr_x"}`, `{}`} { + request := []byte(`{"tools":[{"type":"shell","environment":` + environment + `}]}`) + got := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("test", request, false) + if gjson.GetBytes(got, "tools.#").Int() != 0 { + t.Fatalf("hosted shell represented as local: %s", got) + } + } + for _, choice := range []string{`"auto"`, `"required"`, `"none"`} { + request := []byte(`{"tools":[{"type":"shell","environment":{"type":"local"}}],"tool_choice":` + choice + `}`) + got := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("test", request, false) + var expected string + if errUnmarshal := json.Unmarshal([]byte(choice), &expected); errUnmarshal != nil { + t.Fatal(errUnmarshal) + } + if gjson.GetBytes(got, "tool_choice").String() != expected { + t.Fatalf("choice changed: %s", got) + } + } +} + +func TestLocalShellHistoryWithoutDeclaration(t *testing.T) { + for _, tools := range []string{``, `,"tools":[]`, `,"tools":[{"type":"function","name":"__cpa_local_shell_1","parameters":{}}]`} { + request := []byte(`{"input":[{"type":"shell_call","call_id":"shell_1","action":{"commands":["pwd"]}},{"type":"shell_call_output","call_id":"shell_1","output":[{"stdout":"/workspace","stderr":"","outcome":{"type":"exit","exit_code":0}}]},{"type":"function_call","call_id":"user_1","name":"__cpa_local_shell","arguments":"{}"},{"type":"function_call_output","call_id":"user_1","output":"ok"}]` + tools + `}`) + got := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("test", request, false) + calls := gjson.GetBytes(got, "messages.0.tool_calls").Array() + if len(calls) != 1 || calls[0].Get("id").String() != "shell_1" || gjson.GetBytes(got, "messages.2.tool_calls.0.id").String() != "user_1" { + t.Fatalf("shell history dropped without declaration: %s", got) + } + name := calls[0].Get("function.name").String() + if name == "__cpa_local_shell" || name == "__cpa_local_shell_1" && tools != "" && tools != `,"tools":[]` { + t.Fatalf("history name collided: %s", got) + } + if gjson.Parse(gjson.GetBytes(got, "messages.1.content").String()).Get("output.0.stdout").String() != "/workspace" { + t.Fatalf("shell result lost: %s", got) + } + if gjson.GetBytes(got, "tools.#").Int() != gjson.GetBytes(request, "tools.#").Int() { + t.Fatalf("history re-enabled a tool: %s", got) + } + } +} From 61a70dc687013f32601c79545cab7f6ca6d40b18 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Sat, 3 Oct 2026 20:40:16 +0800 Subject: [PATCH 026/142] feat(claude): adapt native messages JSON to SSE for non-stream translation - Add `ClaudeMessagesJSONToSSE` adapter to convert native Claude message JSON payloads into synthetic SSE events - Support non-stream Claude JSON responses in OpenAI chat completions and responses translators - Preserve authoritative model from native responses in OpenAI responses format Closes: #4815 --- .../claude_openai_native_response_test.go | 83 +++++++++++ .../claude_openai_response.go | 2 + .../claude_openai-responses_response.go | 7 + .../claude_openai_native_response_test.go | 99 +++++++++++++ .../common/claude_native_response.go | 81 +++++++++++ .../common/claude_native_response_test.go | 72 +++++++++ .../common/claude_native_sse_test.go | 137 ++++++++++++++++++ 7 files changed, 481 insertions(+) create mode 100644 internal/translator/claude/openai/chat-completions/claude_openai_native_response_test.go create mode 100644 internal/translator/claude/openai/responses/claude_openai_native_response_test.go create mode 100644 internal/translator/common/claude_native_response.go create mode 100644 internal/translator/common/claude_native_response_test.go create mode 100644 internal/translator/common/claude_native_sse_test.go diff --git a/internal/translator/claude/openai/chat-completions/claude_openai_native_response_test.go b/internal/translator/claude/openai/chat-completions/claude_openai_native_response_test.go new file mode 100644 index 00000000000..a9269d76678 --- /dev/null +++ b/internal/translator/claude/openai/chat-completions/claude_openai_native_response_test.go @@ -0,0 +1,83 @@ +package chat_completions + +import ( + "context" + "fmt" + "testing" + + "github.com/tidwall/gjson" +) + +func TestConvertClaudeResponseToOpenAINonStream_NativeMessagesJSON(t *testing.T) { + for _, tt := range []struct { + name string + content string + stopReason string + finishReason string + tools bool + }{ + {"text", `[{"type":"text","text":"Hello "},{"type":"text","text":"world!"}]`, "end_turn", "stop", false}, + {"tools", `[{"type":"text","text":"Hello world!"},{"type":"tool_use","id":"toolu_weather","name":"get_weather","input":{"city":"Paris","days":2}},{"type":"tool_use","id":"toolu_clock","name":"get_time","input":{}}]`, "tool_use", "tool_calls", true}, + {"max_tokens", `[{"type":"text","text":"Hello world!"}]`, "max_tokens", "length", false}, + } { + t.Run(tt.name, func(t *testing.T) { + raw := []byte(fmt.Sprintf(`{"id":"msg_native","type":"message","role":"assistant","model":"claude-sonnet-4-6","content":%s,"stop_reason":%q,"stop_sequence":null,"usage":{"input_tokens":13,"cache_read_input_tokens":7,"cache_creation_input_tokens":3,"output_tokens":5}}`, tt.content, tt.stopReason)) + request := []byte(`{"model":"claude-sonnet-4-6"}`) + out := ConvertClaudeResponseToOpenAINonStream(context.Background(), "claude-sonnet-4-6", request, request, raw, nil) + if !gjson.ValidBytes(out) { + t.Fatalf("invalid response JSON: %s", out) + } + root := gjson.ParseBytes(out) + for path, want := range map[string]string{ + "id": "msg_native", + "object": "chat.completion", + "model": "claude-sonnet-4-6", + "choices.0.message.role": "assistant", + "choices.0.message.content": "Hello world!", + "choices.0.finish_reason": tt.finishReason, + } { + if got := root.Get(path).String(); got != want { + t.Errorf("%s = %q, want %q", path, got, want) + } + } + for path, want := range map[string]int64{ + "choices.#": 1, + "usage.prompt_tokens": 23, + "usage.completion_tokens": 5, + "usage.total_tokens": 28, + "usage.prompt_tokens_details.cached_tokens": 7, + "usage.prompt_tokens_details.cached_creation_tokens": 3, + } { + if got := root.Get(path).Int(); got != want { + t.Errorf("%s = %d, want %d", path, got, want) + } + } + calls := root.Get("choices.0.message.tool_calls") + if !tt.tools { + if len(calls.Array()) != 0 { + t.Errorf("unexpected tool calls: %s", calls.Raw) + } + return + } + if got := len(calls.Array()); got != 2 { + t.Errorf("tool call count = %d, want 2", got) + } + for path, want := range map[string]string{ + "0.id": "toolu_weather", "0.type": "function", "0.function.name": "get_weather", + "1.id": "toolu_clock", "1.type": "function", "1.function.name": "get_time", + } { + if got := calls.Get(path).String(); got != want { + t.Errorf("tool_calls.%s = %q, want %q", path, got, want) + } + } + args := gjson.Parse(calls.Get("0.function.arguments").String()) + if !args.IsObject() || len(args.Map()) != 2 || args.Get("city").String() != "Paris" || args.Get("days").Int() != 2 { + t.Errorf("weather arguments not preserved: %s", calls.Get("0.function.arguments").Raw) + } + emptyArgs := gjson.Parse(calls.Get("1.function.arguments").String()) + if !emptyArgs.IsObject() || len(emptyArgs.Map()) != 0 { + t.Errorf("empty arguments not preserved: %s", calls.Get("1.function.arguments").Raw) + } + }) + } +} diff --git a/internal/translator/claude/openai/chat-completions/claude_openai_response.go b/internal/translator/claude/openai/chat-completions/claude_openai_response.go index 88876fe1a7c..af43b16d3bd 100644 --- a/internal/translator/claude/openai/chat-completions/claude_openai_response.go +++ b/internal/translator/claude/openai/chat-completions/claude_openai_response.go @@ -12,6 +12,7 @@ import ( "strings" "time" + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" "github.com/tidwall/gjson" "github.com/tidwall/sjson" ) @@ -338,6 +339,7 @@ func mapAnthropicStopReasonToOpenAI(anthropicReason string) string { // Returns: // - []byte: An OpenAI-compatible JSON response containing all message content and metadata func ConvertClaudeResponseToOpenAINonStream(_ context.Context, _ string, originalRequestRawJSON, requestRawJSON, rawJSON []byte, _ *any) []byte { + rawJSON, _ = translatorcommon.ClaudeMessagesJSONToSSE(rawJSON) chunks := make([][]byte, 0) lines := bytes.Split(rawJSON, []byte("\n")) diff --git a/internal/translator/claude/openai/responses/claude_openai-responses_response.go b/internal/translator/claude/openai/responses/claude_openai-responses_response.go index 1a8a6e6990d..c10b8713d0f 100644 --- a/internal/translator/claude/openai/responses/claude_openai-responses_response.go +++ b/internal/translator/claude/openai/responses/claude_openai-responses_response.go @@ -1177,6 +1177,7 @@ func ConvertClaudeResponseToOpenAIResponses(ctx context.Context, modelName strin // ConvertClaudeResponseToOpenAIResponsesNonStream aggregates Claude SSE into a single OpenAI Responses JSON. func ConvertClaudeResponseToOpenAIResponsesNonStream(_ context.Context, _ string, originalRequestRawJSON, requestRawJSON, rawJSON []byte, param *any) []byte { + rawJSON, nativeModel := translatorcommon.ClaudeMessagesJSONToSSE(rawJSON) // Aggregate Claude SSE lines into a single OpenAI Responses JSON (non-stream) // We follow the same aggregation logic as the streaming variant but produce // one final object matching docs/out.json structure. @@ -1498,6 +1499,12 @@ func ConvertClaudeResponseToOpenAIResponsesNonStream(_ context.Context, _ string } } + // A native response's model is authoritative; otherwise retain request echo + // behavior, including the existing SSE path. + if nativeModel != "" { + out, _ = sjson.SetBytes(out, "model", nativeModel) + } + // Build output array in the order of the original content blocks. outputs := make([][]byte, 0, len(outputItems)) for i, outputItem := range outputItems { diff --git a/internal/translator/claude/openai/responses/claude_openai_native_response_test.go b/internal/translator/claude/openai/responses/claude_openai_native_response_test.go new file mode 100644 index 00000000000..bf9b93facf8 --- /dev/null +++ b/internal/translator/claude/openai/responses/claude_openai_native_response_test.go @@ -0,0 +1,99 @@ +package responses + +import ( + "context" + "fmt" + "testing" + + "github.com/tidwall/gjson" +) + +func TestConvertClaudeResponseToOpenAIResponsesNonStream_NativeMessagesJSON(t *testing.T) { + for _, tt := range []struct { + name string + content string + stopReason string + status string + tools bool + }{ + {"text", `[{"type":"text","text":"Hello "},{"type":"text","text":"world!"}]`, "end_turn", "completed", false}, + {"tools", `[{"type":"text","text":"Hello world!"},{"type":"tool_use","id":"toolu_weather","name":"get_weather","input":{"city":"Paris","days":2}},{"type":"tool_use","id":"toolu_clock","name":"get_time","input":{}}]`, "tool_use", "completed", true}, + {"max_tokens", `[{"type":"text","text":"Hello world!"}]`, "max_tokens", "incomplete", false}, + } { + t.Run(tt.name, func(t *testing.T) { + raw := []byte(fmt.Sprintf(`{"id":"msg_native","type":"message","role":"assistant","model":"claude-sonnet-4-6","content":%s,"stop_reason":%q,"stop_sequence":null,"usage":{"input_tokens":13,"cache_read_input_tokens":7,"cache_creation_input_tokens":3,"output_tokens":5}}`, tt.content, tt.stopReason)) + request := []byte(`{"model":"claude-sonnet-4-6"}`) + out := ConvertClaudeResponseToOpenAIResponsesNonStream(context.Background(), "claude-sonnet-4-6", request, request, raw, nil) + if !gjson.ValidBytes(out) { + t.Fatalf("invalid response JSON: %s", out) + } + root := gjson.ParseBytes(out) + for path, want := range map[string]string{ + "id": "msg_native", + "object": "response", + "model": "claude-sonnet-4-6", + "status": tt.status, + "output.0.type": "message", + "output.0.role": "assistant", + "output.0.status": tt.status, + "output.0.content.0.type": "output_text", + "output.0.content.0.text": "Hello world!", + } { + if got := root.Get(path).String(); got != want { + t.Errorf("%s = %q, want %q", path, got, want) + } + } + for path, want := range map[string]int64{ + "usage.input_tokens": 23, + "usage.output_tokens": 5, + "usage.total_tokens": 28, + "usage.input_tokens_details.cached_tokens": 7, + } { + if got := root.Get(path).Int(); got != want { + t.Errorf("%s = %d, want %d", path, got, want) + } + } + if tt.status == "incomplete" { + if got := root.Get("incomplete_details.reason").String(); got != "max_output_tokens" { + t.Errorf("incomplete reason = %q, want max_output_tokens", got) + } + } else if got := root.Get("incomplete_details"); !got.Exists() || got.Type != gjson.Null { + t.Errorf("incomplete_details = %s, want null", got.Raw) + } + if !tt.tools { + if got := len(root.Get("output").Array()); got != 1 { + t.Errorf("output count = %d, want 1", got) + } + return + } + if got := len(root.Get("output").Array()); got != 3 { + t.Errorf("output count = %d, want 3", got) + } + for path, want := range map[string]string{ + "output.1.call_id": "toolu_weather", "output.1.type": "function_call", "output.1.name": "get_weather", "output.1.status": "completed", + "output.2.call_id": "toolu_clock", "output.2.type": "function_call", "output.2.name": "get_time", "output.2.status": "completed", + } { + if got := root.Get(path).String(); got != want { + t.Errorf("%s = %q, want %q", path, got, want) + } + } + args := gjson.Parse(root.Get("output.1.arguments").String()) + if !args.IsObject() || len(args.Map()) != 2 || args.Get("city").String() != "Paris" || args.Get("days").Int() != 2 { + t.Errorf("weather arguments not preserved: %s", root.Get("output.1.arguments").Raw) + } + emptyArgs := gjson.Parse(root.Get("output.2.arguments").String()) + if !emptyArgs.IsObject() || len(emptyArgs.Map()) != 0 { + t.Errorf("empty arguments not preserved: %s", root.Get("output.2.arguments").Raw) + } + }) + } +} + +func TestNativeMessagesJSONCitations(t *testing.T) { + raw := []byte(`{"id":"msg_citations","type":"message","model":"claude-native","content":[{"type":"text","text":"Answer.","citations":[{"type":"web_search_result_location","url":"https://example.com","title":"Source","cited_text":"Answer.","encrypted_index":"IDX"}]}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":2}}`) + out := ConvertClaudeResponseToOpenAIResponsesNonStream(context.Background(), "", nil, nil, raw, nil) + annotations := gjson.GetBytes(out, "output.0.content.0.annotations") + if len(annotations.Array()) != 1 || annotations.Get("0.url").String() != "https://example.com" || annotations.Get("0.encrypted_index").String() != "IDX" { + t.Fatalf("citations not preserved: %s", out) + } +} diff --git a/internal/translator/common/claude_native_response.go b/internal/translator/common/claude_native_response.go new file mode 100644 index 00000000000..16c9f4f5357 --- /dev/null +++ b/internal/translator/common/claude_native_response.go @@ -0,0 +1,81 @@ +package common + +import ( + "bytes" + "encoding/json" + + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// ClaudeMessagesJSONToSSE adapts a native Messages response for the existing SSE +// aggregators and returns its model. SSE and other payloads pass through unchanged. +func ClaudeMessagesJSONToSSE(rawJSON []byte) ([]byte, string) { + if !gjson.ValidBytes(rawJSON) { + return rawJSON, "" + } + root := gjson.ParseBytes(rawJSON) + if root.Get("type").String() != "message" || !root.Get("content").IsArray() { + return rawJSON, "" + } + + var out bytes.Buffer + emit := func(event map[string]any) { + // All values are JSON primitives or validated raw JSON from the response. + payload, _ := json.Marshal(event) + out.WriteString("data: ") + out.Write(payload) + out.WriteString("\n\n") + } + message, _ := sjson.SetRawBytes(rawJSON, "content", []byte(`[]`)) + message, _ = sjson.SetBytes(message, "stop_reason", nil) + message, _ = sjson.SetBytes(message, "stop_sequence", nil) + emit(map[string]any{"type": "message_start", "message": json.RawMessage(message)}) + + for index, block := range root.Get("content").Array() { + start := []byte(block.Raw) + var delta map[string]any + switch block.Get("type").String() { + case "text": + start, _ = sjson.SetBytes(start, "text", "") + delta = map[string]any{"type": "text_delta", "text": block.Get("text").String()} + case "tool_use": + start, _ = sjson.SetRawBytes(start, "input", []byte(`{}`)) + input := block.Get("input").Raw + if input == "" { + input = "{}" + } + delta = map[string]any{"type": "input_json_delta", "partial_json": input} + case "thinking": + start, _ = sjson.SetBytes(start, "thinking", "") + start, _ = sjson.SetBytes(start, "signature", "") + delta = map[string]any{"type": "thinking_delta", "thinking": block.Get("thinking").String()} + } + emit(map[string]any{"type": "content_block_start", "index": index, "content_block": json.RawMessage(start)}) + if delta != nil { + emit(map[string]any{"type": "content_block_delta", "index": index, "delta": delta}) + } + if block.Get("type").String() == "text" { + for _, citation := range block.Get("citations").Array() { + emit(map[string]any{"type": "content_block_delta", "index": index, "delta": map[string]any{ + "type": "citations_delta", "citation": json.RawMessage(citation.Raw), + }}) + } + } + if block.Get("type").String() == "thinking" && block.Get("signature").Exists() { + emit(map[string]any{"type": "content_block_delta", "index": index, "delta": map[string]any{ + "type": "signature_delta", "signature": block.Get("signature").String(), + }}) + } + emit(map[string]any{"type": "content_block_stop", "index": index}) + } + usage := json.RawMessage(root.Get("usage").Raw) + if len(usage) == 0 { + usage = json.RawMessage(`{}`) + } + emit(map[string]any{"type": "message_delta", "delta": map[string]any{ + "stop_reason": root.Get("stop_reason").Value(), "stop_sequence": root.Get("stop_sequence").Value(), + }, "usage": usage}) + emit(map[string]any{"type": "message_stop"}) + return out.Bytes(), root.Get("model").String() +} diff --git a/internal/translator/common/claude_native_response_test.go b/internal/translator/common/claude_native_response_test.go new file mode 100644 index 00000000000..615040a00bd --- /dev/null +++ b/internal/translator/common/claude_native_response_test.go @@ -0,0 +1,72 @@ +package common_test + +import ( + "context" + "encoding/json" + "reflect" + "testing" + + chat "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/claude/openai/chat-completions" + responses "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/claude/openai/responses" + "github.com/tidwall/gjson" +) + +func TestClaudeNativeResponseNonStreamModelAndContent(t *testing.T) { + text := "line 1\n\"quoted\" \\ 雪 " + input := map[string]any{"nested": map[string]any{"text": text, "items": []any{true, nil, float64(2)}}, "empty": map[string]any{}} + raw, errMarshal := json.Marshal(map[string]any{ + "id": "msg_native", "type": "message", "role": "assistant", "model": "claude-native", + "content": []any{ + map[string]any{"type": "thinking", "thinking": text, "signature": "sig\n\"native"}, + map[string]any{"type": "redacted_thinking", "data": "opaque-data"}, + map[string]any{"type": "text", "text": text}, + map[string]any{"type": "tool_use", "id": "tool_native", "name": "lookup", "input": input}, + }, + "stop_reason": "tool_use", "stop_sequence": nil, + "usage": map[string]any{"input_tokens": 11, "output_tokens": 9}, + }) + if errMarshal != nil { + t.Fatal(errMarshal) + } + for _, provider := range []struct { + name string + convert func(context.Context, string, []byte, []byte, []byte, *any) []byte + textPath string + thinkPath string + argsPath string + }{ + {"chat", chat.ConvertClaudeResponseToOpenAINonStream, "choices.0.message.content", "choices.0.message.reasoning_content", "choices.0.message.tool_calls.0.function.arguments"}, + {"responses", responses.ConvertClaudeResponseToOpenAIResponsesNonStream, "output.2.content.0.text", "output.0.summary.0.text", "output.3.arguments"}, + } { + t.Run(provider.name, func(t *testing.T) { + for _, request := range []string{`{}`, `{"model":"request-alias"}`} { + t.Run(request, func(t *testing.T) { + out := provider.convert(context.Background(), "executor-alias", []byte(request), []byte(request), raw, nil) + root := gjson.ParseBytes(out) + for path, want := range map[string]string{"model": "claude-native", "id": "msg_native", provider.textPath: text, provider.thinkPath: text} { + if got := root.Get(path).String(); got != want { + t.Errorf("%s = %q, want %q", path, got, want) + } + } + var gotInput map[string]any + if errUnmarshal := json.Unmarshal([]byte(root.Get(provider.argsPath).String()), &gotInput); errUnmarshal != nil { + t.Errorf("invalid tool arguments: %v", errUnmarshal) + } else if !reflect.DeepEqual(gotInput, input) { + t.Errorf("tool arguments = %#v, want %#v", gotInput, input) + } + if provider.name == "responses" { + for path, want := range map[string]string{ + "output.0.type": "reasoning", "output.0.encrypted_content": "sig\n\"native", + "output.1.type": "reasoning", "output.1.encrypted_content": responses.ClaudeResponsesRedactedThinkingPrefix + "opaque-data", + "output.3.call_id": "tool_native", "output.3.name": "lookup", + } { + if got := root.Get(path).String(); got != want { + t.Errorf("%s = %q, want %q", path, got, want) + } + } + } + }) + } + }) + } +} diff --git a/internal/translator/common/claude_native_sse_test.go b/internal/translator/common/claude_native_sse_test.go new file mode 100644 index 00000000000..fd7279a5abb --- /dev/null +++ b/internal/translator/common/claude_native_sse_test.go @@ -0,0 +1,137 @@ +package common + +import ( + "bytes" + "encoding/json" + "reflect" + "testing" + + "github.com/tidwall/gjson" +) + +func TestClaudeMessagesJSONToSSEPassthrough(t *testing.T) { + for _, raw := range []string{ + "event: message_start\r\ndata: {\"type\":\"message_start\",\"message\":{\"model\":\"sse-model\"}}\r\n\r\n: keepalive\r\n", + "data: {\"type\":\"message_stop\"}\n\n", + `{"type":"error","error":{"message":"bad request"}}`, + `{"type":"message","content":`, + `{"type":"message","content":"not an array"}`, + "", + } { + out, model := ClaudeMessagesJSONToSSE([]byte(raw)) + if !bytes.Equal(out, []byte(raw)) || model != "" { + t.Errorf("passthrough changed payload: %q -> %q, model=%q", raw, out, model) + } + } +} + +func TestClaudeMessagesJSONToSSEEvents(t *testing.T) { + raw := []byte(`{ + "id":"msg_native","type":"message","role":"assistant","model":"claude-native", + "content":[ + {"type":"text","text":"line 1\n\"quoted\" \\ 雪 "}, + {"type":"tool_use","id":"tool_nested","name":"lookup","input":{"nested":{"text":"line\n\"quoted\"","items":[true,null,2]},"empty":{}}}, + {"type":"tool_use","id":"tool_empty","name":"clock","input":{}}, + {"type":"thinking","thinking":"plan\nnext","signature":"sig\"native"}, + {"type":"redacted_thinking","data":"opaque"} + ], + "stop_reason":"stop_sequence","stop_sequence":"END\n", + "usage":{"input_tokens":13,"output_tokens":5,"cache_read_input_tokens":7,"cache_creation_input_tokens":3} + }`) + out, model := ClaudeMessagesJSONToSSE(raw) + if model != "claude-native" { + t.Errorf("model = %q, want claude-native", model) + } + var events []gjson.Result + for _, line := range bytes.Split(out, []byte("\n")) { + if !bytes.HasPrefix(line, []byte("data: ")) { + continue + } + payload := bytes.TrimPrefix(line, []byte("data: ")) + if !gjson.ValidBytes(payload) { + t.Fatalf("invalid SSE JSON: %s", payload) + } + events = append(events, gjson.ParseBytes(payload)) + } + wantTypes := []string{ + "message_start", + "content_block_start", "content_block_delta", "content_block_stop", + "content_block_start", "content_block_delta", "content_block_stop", + "content_block_start", "content_block_delta", "content_block_stop", + "content_block_start", "content_block_delta", "content_block_delta", "content_block_stop", + "content_block_start", "content_block_stop", + "message_delta", "message_stop", + } + if len(events) != len(wantTypes) { + t.Fatalf("event count = %d, want %d; payload=%s", len(events), len(wantTypes), out) + } + for i, want := range wantTypes { + if got := events[i].Get("type").String(); got != want { + t.Errorf("event %d type = %q, want %q", i, got, want) + } + } + root := gjson.ParseBytes(raw) + for _, path := range []string{"id", "model", "role", "usage"} { + if got, want := events[0].Get("message."+path).Value(), root.Get(path).Value(); !reflect.DeepEqual(got, want) { + t.Errorf("message_start %s = %#v, want %#v", path, got, want) + } + } + if got := events[0].Get("message.content"); !got.IsArray() || len(got.Array()) != 0 { + t.Errorf("message_start content must be empty, got %s", got.Raw) + } + for _, block := range []struct{ start, stop, index int }{{1, 3, 0}, {4, 6, 1}, {7, 9, 2}, {10, 13, 3}, {14, 15, 4}} { + for i := block.start; i <= block.stop; i++ { + if got := events[i].Get("index"); !got.Exists() || got.Int() != int64(block.index) { + t.Errorf("event %d index = %s, want %d", i, got.Raw, block.index) + } + } + } + for _, check := range []struct { + event int + path string + want string + }{ + {2, "delta.type", "text_delta"}, {2, "delta.text", root.Get("content.0.text").String()}, + {4, "content_block.id", "tool_nested"}, {4, "content_block.name", "lookup"}, + {5, "delta.type", "input_json_delta"}, {8, "delta.type", "input_json_delta"}, + {11, "delta.type", "thinking_delta"}, {11, "delta.thinking", "plan\nnext"}, + {12, "delta.type", "signature_delta"}, {12, "delta.signature", "sig\"native"}, + {14, "content_block.type", "redacted_thinking"}, {14, "content_block.data", "opaque"}, + {16, "delta.stop_reason", "stop_sequence"}, {16, "delta.stop_sequence", "END\n"}, + } { + if got := events[check.event].Get(check.path).String(); got != check.want { + t.Errorf("event %d %s = %q, want %q", check.event, check.path, got, check.want) + } + } + for _, check := range []struct{ event, block int }{{5, 1}, {8, 2}} { + var got any + if errUnmarshal := json.Unmarshal([]byte(events[check.event].Get("delta.partial_json").String()), &got); errUnmarshal != nil { + t.Fatal(errUnmarshal) + } + want := root.Get("content").Array()[check.block].Get("input").Value() + if !reflect.DeepEqual(got, want) { + t.Errorf("tool input = %#v, want %#v", got, want) + } + } + if got, want := events[16].Get("usage").Value(), root.Get("usage").Value(); !reflect.DeepEqual(got, want) { + t.Errorf("final usage = %#v, want %#v", got, want) + } +} + +func TestClaudeMessagesJSONToSSECitations(t *testing.T) { + raw := []byte(`{"type":"message","content":[{"type":"text","text":"Answer.","citations":[{"type":"web_search_result_location","url":"https://example.com","title":"Source","cited_text":"Answer.","encrypted_index":"IDX"}]}]}`) + out, _ := ClaudeMessagesJSONToSSE(raw) + count := 0 + for _, line := range bytes.Split(out, []byte("\n")) { + event := gjson.ParseBytes(bytes.TrimPrefix(line, []byte("data: "))) + if event.Get("delta.type").String() == "citations_delta" { + count++ + if event.Get("index").Int() != 0 || event.Get("delta.citation.encrypted_index").String() != "IDX" { + t.Errorf("citation not preserved: %s", line) + } + } + } + if count != 1 { + t.Fatalf("citation events = %d, want 1", count) + } +} From 7e857c375a1a74b4d5c241114d1d875b0a68145f Mon Sep 17 00:00:00 2001 From: sususu Date: Sat, 3 Oct 2026 21:21:51 +0800 Subject: [PATCH 027/142] feat(antigravity): refresh per-account model entitlements safely Isolate account entitlement caches and add retry backoff, auth-change cancellation, and publication fencing. Decouple refresh scheduling from startup and config updates, bound native and plugin probe concurrency, and cancel background probes on shutdown. Preserve cooldown state and projection generation watermarks during conditional model replacement, with regression coverage. --- internal/registry/model_registry.go | 56 +- .../registry/model_registry_replace_test.go | 84 +++ internal/registry/model_updater.go | 5 +- sdk/cliproxy/antigravity_model_probes.go | 161 +++++ sdk/cliproxy/antigravity_model_probes_test.go | 93 +++ sdk/cliproxy/antigravity_models.go | 661 ++++++++++++------ .../antigravity_models_backoff_test.go | 150 ++++ sdk/cliproxy/antigravity_models_dedup_test.go | 660 +++++------------ .../antigravity_models_fencing_test.go | 159 +++++ .../antigravity_models_publication_test.go | 90 +++ .../antigravity_models_refresh_test.go | 200 ++++++ .../antigravity_models_registration_test.go | 208 ++++++ .../antigravity_models_review_test.go | 139 ++++ .../antigravity_models_timeout_test.go | 150 ++-- sdk/cliproxy/auth/auth_change_watch.go | 46 ++ sdk/cliproxy/auth/auth_change_watch_test.go | 79 +++ sdk/cliproxy/auth/conductor.go | 1 + sdk/cliproxy/auth/conductor_lifecycle.go | 6 + sdk/cliproxy/service.go | 10 + sdk/cliproxy/service_auth.go | 4 +- sdk/cliproxy/service_config.go | 1 + sdk/cliproxy/service_excluded_models_test.go | 13 +- .../service_executionregistry_test.go | 90 +-- sdk/cliproxy/service_executors.go | 3 + sdk/cliproxy/service_lifecycle.go | 13 + sdk/cliproxy/service_models.go | 13 +- sdk/cliproxy/service_plugins.go | 3 +- 27 files changed, 2167 insertions(+), 931 deletions(-) create mode 100644 internal/registry/model_registry_replace_test.go create mode 100644 sdk/cliproxy/antigravity_model_probes.go create mode 100644 sdk/cliproxy/antigravity_model_probes_test.go create mode 100644 sdk/cliproxy/antigravity_models_backoff_test.go create mode 100644 sdk/cliproxy/antigravity_models_fencing_test.go create mode 100644 sdk/cliproxy/antigravity_models_publication_test.go create mode 100644 sdk/cliproxy/antigravity_models_refresh_test.go create mode 100644 sdk/cliproxy/antigravity_models_registration_test.go create mode 100644 sdk/cliproxy/antigravity_models_review_test.go create mode 100644 sdk/cliproxy/auth/auth_change_watch.go create mode 100644 sdk/cliproxy/auth/auth_change_watch_test.go diff --git a/internal/registry/model_registry.go b/internal/registry/model_registry.go index 8a4bf7c1581..5f548aa1016 100644 --- a/internal/registry/model_registry.go +++ b/internal/registry/model_registry.go @@ -434,6 +434,27 @@ func (r *ModelRegistry) triggerModelsUnregistered(provider, clientID string) { func (r *ModelRegistry) RegisterClient(clientID, clientProvider string, models []*ModelInfo) { r.mutex.Lock() defer r.mutex.Unlock() + r.registerClientLocked(clientID, clientProvider, models, false) +} + +// ReplaceClientModels replaces a client's models only if its registration epoch matches. +// Epoch zero and epochs for empty catalogs are valid. A successful replacement advances +// the epoch and preserves quota, suspension state and the projection generation +// watermark for an existing registration with the same provider. +// Empty models unregister the client; a mismatched epoch leaves the registry unchanged. +// The successful epoch is returned under the same lock as the replacement. +func (r *ModelRegistry) ReplaceClientModels(clientID, clientProvider string, expectedEpoch uint64, models []*ModelInfo) (uint64, bool) { + r.mutex.Lock() + defer r.mutex.Unlock() + if r.clientEpochs[clientID] != expectedEpoch { + return 0, false + } + r.registerClientLocked(clientID, clientProvider, models, true) + return r.clientEpochs[clientID], true +} + +// registerClientLocked reconciles a client's models while the registry mutex is held. +func (r *ModelRegistry) registerClientLocked(clientID, clientProvider string, models []*ModelInfo, preserveState bool) { r.ensureAvailableModelsCacheLocked() if r.clientGenerations == nil { @@ -472,16 +493,19 @@ func (r *ModelRegistry) RegisterClient(clientID, clientProvider string, models [ return } - // Monotonically increment client registration epoch and reset generation to 0. + oldModels, hadExisting := r.clientModels[clientID] + oldProvider := r.clientProviders[clientID] + providerChanged := oldProvider != provider + + // Retaining scheduling state also retains its projection watermark. An older + // request result may read the new epoch after capturing its auth snapshot. r.clientEpochs[clientID]++ - r.clientGenerations[clientID] = uint64(0) + if !preserveState || !hadExisting || providerChanged { + r.clientGenerations[clientID] = uint64(0) + } r.registrationEpoch.Add(1) now := time.Now() - - oldModels, hadExisting := r.clientModels[clientID] - oldProvider := r.clientProviders[clientID] - providerChanged := oldProvider != provider if !hadExisting { // Pure addition path. for _, modelID := range rawModelIDs { @@ -562,7 +586,7 @@ func (r *ModelRegistry) RegisterClient(clientID, clientProvider string, models [ for _, id := range removed { oldCount := oldCounts[id] for i := 0; i < oldCount; i++ { - r.removeModelRegistration(clientID, id, oldProvider, now) + r.removeModelRegistration(clientID, id, oldProvider, now, false) } } @@ -573,7 +597,7 @@ func (r *ModelRegistry) RegisterClient(clientID, clientProvider string, models [ } overage := oldCount - newCount for i := 0; i < overage; i++ { - r.removeModelRegistration(clientID, id, oldProvider, now) + r.removeModelRegistration(clientID, id, oldProvider, now, preserveState && !providerChanged) } } @@ -613,13 +637,10 @@ func (r *ModelRegistry) RegisterClient(clientID, clientProvider string, models [ reg.InfoByProvider[oldProvider].SupportsWebSearch = r.hasClientSupportingWebSearchLocked(id, oldProvider, clientID) } reg.LastUpdated = now - // Re-registering an existing client/model binding starts a fresh registry - // snapshot for that binding. Cooldown and suspension are transient - // scheduling state and must not survive this reconciliation step. - if reg.QuotaExceededClients != nil { + // Only conditional replacements preserve scheduling state for retained + // bindings with the same provider. Ordinary registration starts fresh. + if !preserveState || providerChanged || oldCounts[id] == 0 { delete(reg.QuotaExceededClients, clientID) - } - if reg.SuspendedClients != nil { delete(reg.SuspendedClients, clientID) } if providerChanged && provider != "" { @@ -713,17 +734,16 @@ func (r *ModelRegistry) addModelRegistration(modelID, provider string, model *Mo log.Debugf("Registered new model %s from provider %s", modelID, provider) } -func (r *ModelRegistry) removeModelRegistration(clientID, modelID, provider string, now time.Time) { +// removeModelRegistration may preserve state when only a duplicate binding is removed. +func (r *ModelRegistry) removeModelRegistration(clientID, modelID, provider string, now time.Time, preserveState bool) { registration, exists := r.models[modelID] if !exists { return } registration.Count-- registration.LastUpdated = now - if registration.QuotaExceededClients != nil { + if !preserveState { delete(registration.QuotaExceededClients, clientID) - } - if registration.SuspendedClients != nil { delete(registration.SuspendedClients, clientID) } if registration.Count < 0 { diff --git a/internal/registry/model_registry_replace_test.go b/internal/registry/model_registry_replace_test.go new file mode 100644 index 00000000000..366b5f9fbbd --- /dev/null +++ b/internal/registry/model_registry_replace_test.go @@ -0,0 +1,84 @@ +package registry + +import "testing" + +func TestReplaceClientModelsProjectionGeneration(t *testing.T) { + for _, mode := range []string{"same-provider", "new-provider", "register"} { + t.Run(mode, func(t *testing.T) { + r := newTestModelRegistry() + models := []*ModelInfo{{ID: "keep"}} + r.RegisterClient("account", "antigravity", models) + epoch := r.ClientRegistrationEpoch("account") + if !r.ApplyClientModelProjections("account", epoch, 11, []ClientModelProjection{{ModelID: "keep", QuotaExceeded: true, Suspended: true, SuspendReason: "rate_limit"}}) { + t.Fatal("initial projection rejected") + } + switch mode { + case "register": + r.RegisterClient("account", "antigravity", models) + default: + provider := "antigravity" + if mode == "new-provider" { + provider = "gemini" + } + if _, ok := r.ReplaceClientModels("account", provider, epoch, models); !ok { + t.Fatal("replacement rejected") + } + } + epoch = r.ClientRegistrationEpoch("account") + accepted := r.ApplyClientModelProjections("account", epoch, 10, []ClientModelProjection{{ModelID: "keep"}}) + if mode == "same-provider" { + if accepted || !r.IsModelQuotaExceededForClient("account", "keep") || r.models["keep"].SuspendedClients["account"] != "rate_limit" { + t.Fatal("older generation overwrote retained scheduling state") + } + if !r.ApplyClientModelProjections("account", epoch, 12, []ClientModelProjection{{ModelID: "keep"}}) { + t.Fatal("newer projection rejected") + } + } else if !accepted { + t.Fatal("fresh registration did not reset generation") + } + }) + } +} + +func TestReplaceClientModelsEpochAndAvailability(t *testing.T) { + r := newTestModelRegistry() + models := []*ModelInfo{{ID: "keep"}, {ID: "remove"}, {ID: "keep"}} + if _, ok := r.ReplaceClientModels("account", "antigravity", 0, models); !ok { + t.Fatal("initial epoch rejected") + } + epoch := r.ClientRegistrationEpoch("account") + r.SuspendClientModel("account", "keep", "rate_limit") + r.SetModelQuotaExceeded("account", "keep") + if _, ok := r.ReplaceClientModels("account", "antigravity", epoch, []*ModelInfo{{ID: "keep"}, {ID: "add"}}); !ok { + t.Fatal("replacement failed") + } + if r.models["keep"].SuspendedClients["account"] != "rate_limit" || !r.IsModelQuotaExceededForClient("account", "keep") { + t.Fatal("retained model lost cooldown") + } + if r.ClientSupportsModel("account", "remove") || !r.ClientSupportsModel("account", "add") { + t.Fatal("wrong model set") + } + if _, ok := r.ReplaceClientModels("account", "antigravity", epoch, models); ok { + t.Fatal("stale epoch accepted") + } + r.RegisterClient("account", "antigravity", []*ModelInfo{{ID: "keep"}}) + if r.models["keep"].SuspendedClients["account"] != "" || r.IsModelQuotaExceededForClient("account", "keep") { + t.Fatal("ordinary registration no longer clears state") + } + epoch = r.ClientRegistrationEpoch("account") + if _, ok := r.ReplaceClientModels("account", "antigravity", epoch, nil); !ok { + t.Fatal("empty catalog rejected") + } + if len(r.GetModelsForClient("account")) != 0 { + t.Fatal("empty catalog did not revoke models") + } + emptyEpoch := r.ClientRegistrationEpoch("account") + if applied, ok := r.ReplaceClientModels("account", "antigravity", emptyEpoch, models); !ok || emptyEpoch == epoch || applied != emptyEpoch+1 { + t.Fatal("empty catalog cannot recover") + } + epoch = r.ClientRegistrationEpoch("account") + r.UnregisterClient("account") + if _, ok := r.ReplaceClientModels("account", "antigravity", epoch, models); ok { + t.Fatal("removed client resurrected") + } +} diff --git a/internal/registry/model_updater.go b/internal/registry/model_updater.go index 5a21f48822a..f440070fc86 100644 --- a/internal/registry/model_updater.go +++ b/internal/registry/model_updater.go @@ -17,9 +17,12 @@ import ( const ( modelsFetchTimeout = 30 * time.Second - modelsRefreshInterval = 3 * time.Hour + modelsRefreshInterval = ModelsRefreshInterval ) +// ModelsRefreshInterval is the shared cadence for model catalogs and account entitlements. +const ModelsRefreshInterval = 3 * time.Hour + var modelsURLs = []string{ "https://raw.githubusercontent.com/router-for-me/models/refs/heads/main/models.json", "https://models.router-for.me/models.json", diff --git a/sdk/cliproxy/antigravity_model_probes.go b/sdk/cliproxy/antigravity_model_probes.go new file mode 100644 index 00000000000..530124d91b7 --- /dev/null +++ b/sdk/cliproxy/antigravity_model_probes.go @@ -0,0 +1,161 @@ +package cliproxy + +import ( + "context" + "strings" + + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" +) + +// antigravityAccountProbe owns both queued and connected work for one auth snapshot. +// Cancellation releases network slots without imposing an upstream timeout. +type antigravityAccountProbe struct { + auth *coreauth.Auth + routeKey string + flightKey string + token string + cancel context.CancelFunc +} + +func (s *Service) beginAntigravityAccountProbe(parent context.Context, auth *coreauth.Auth, routeKey, flightKey, token string) (context.Context, func(), bool) { + ctx, cancel := context.WithCancel(parent) + s.cfgMu.RLock() + lifetime := s.antigravityContext + s.cfgMu.RUnlock() + var stop func() bool + if lifetime != nil { + stop = context.AfterFunc(lifetime, cancel) + if lifetime.Err() != nil { + cancel() + } + } + var changes <-chan struct{} + var unsubscribe func() + if s.coreManager != nil { + // Subscribe before validation, so a native refresh/removal cannot fall + // between checking the auth and installing the invalidation observer. + changes, unsubscribe = s.coreManager.WatchAuthChanges(auth.ID) + } + var watcherDone chan struct{} + probe := &antigravityAccountProbe{auth: auth.Clone(), routeKey: routeKey, flightKey: flightKey, token: token, cancel: cancel} + s.antigravityProbeMu.Lock() + valid := ctx.Err() == nil && s.antigravityAccountProbeCurrent(probe) + if valid { + if s.antigravityAccountProbes == nil { + s.antigravityAccountProbes = make(map[string]map[*antigravityAccountProbe]struct{}) + } + if s.antigravityAccountProbes[auth.ID] == nil { + s.antigravityAccountProbes[auth.ID] = make(map[*antigravityAccountProbe]struct{}) + } + s.antigravityAccountProbes[auth.ID][probe] = struct{}{} + } + s.antigravityProbeMu.Unlock() + if valid && changes != nil { + watcherDone = make(chan struct{}) + go func() { + defer close(watcherDone) + for { + select { + case <-ctx.Done(): + return + case _, open := <-changes: + if !open { + return + } + s.cancelStaleAntigravityProbes(auth.ID) + } + } + }() + } + cleanup := func() { + cancel() + if unsubscribe != nil { + unsubscribe() + } + if watcherDone != nil { + <-watcherDone + } + if stop != nil { + stop() + } + s.antigravityProbeMu.Lock() + delete(s.antigravityAccountProbes[auth.ID], probe) + if len(s.antigravityAccountProbes[auth.ID]) == 0 { + delete(s.antigravityAccountProbes, auth.ID) + } + s.antigravityProbeMu.Unlock() + s.signalAntigravityModelRefresh() + } + if !valid { + cleanup() + return ctx, func() {}, false + } + return ctx, cleanup, true +} + +// Caller holds antigravityProbeMu, making tracking and invalidation indivisible. +func (s *Service) antigravityAccountProbeCurrent(probe *antigravityAccountProbe) bool { + if s.antigravityHomeEnabled() { + return false + } + current := probe.auth + if s.coreManager != nil { + var exists bool + current, exists = s.coreManager.GetByID(probe.auth.ID) + if !exists || current == nil { + return false + } + } + token, _ := current.Metadata["access_token"].(string) + return !current.Disabled && current.Status != coreauth.StatusDisabled && + antigravityAuthModelSettingsEqual(current, probe.auth) && + s.antigravityCapabilityKey(current) == probe.routeKey && strings.TrimSpace(token) == probe.token +} + +// Run after the manager/config mutation. New probes check current state while +// joining this same map, so deletion cannot slip between validation and tracking. +// Empty authID invalidates stale probes across all accounts after config changes. +func (s *Service) cancelStaleAntigravityProbes(authID string) { + if s == nil { + return + } + s.antigravityProbeMu.Lock() + for id, probes := range s.antigravityAccountProbes { + if authID != "" && id != authID { + continue + } + for probe := range probes { + if !s.antigravityAccountProbeCurrent(probe) { + probe.cancel() + // An updated snapshot with the same token may start immediately instead + // of joining an obsolete leader that is still unwinding its HTTP request. + antigravityCapabilityGroup.Forget(probe.flightKey) + delete(probes, probe) + } + } + if len(probes) == 0 { + delete(s.antigravityAccountProbes, id) + } + } + s.antigravityProbeMu.Unlock() + s.signalAntigravityModelRefresh() +} + +func (s *Service) antigravityModelRefreshWake() chan struct{} { + s.antigravityProbeMu.Lock() + defer s.antigravityProbeMu.Unlock() + if s.antigravityRefreshWake == nil { + s.antigravityRefreshWake = make(chan struct{}, 1) + } + return s.antigravityRefreshWake +} + +func (s *Service) signalAntigravityModelRefresh() { + if s == nil { + return + } + select { + case s.antigravityModelRefreshWake() <- struct{}{}: + default: + } +} diff --git a/sdk/cliproxy/antigravity_model_probes_test.go b/sdk/cliproxy/antigravity_model_probes_test.go new file mode 100644 index 00000000000..e09a45a7cc0 --- /dev/null +++ b/sdk/cliproxy/antigravity_model_probes_test.go @@ -0,0 +1,93 @@ +package cliproxy + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + "time" + + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" +) + +func TestAntigravityAccountChangesCancelConnectedProbe(t *testing.T) { + for _, change := range []string{"disabled", "route", "token", "config-proxy", "native-refresh", "native-prepare", "native-update", "native-remove"} { + t.Run(change, func(t *testing.T) { + resetAntigravityCapabilityCache() + t.Cleanup(resetAntigravityCapabilityCache) + started, cancelled := make(chan struct{}), make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(200) + w.(http.Flusher).Flush() + close(started) + <-r.Context().Done() + close(cancelled) + })) + ctx, cancel := context.WithCancel(t.Context()) + svc := &Service{cfg: &config.Config{}, coreManager: coreauth.NewManager(nil, nil, nil)} + t.Cleanup(func() { cancel(); svc.WaitAntigravityProbes(); server.Close() }) + auth, _ := svc.coreManager.Register(ctx, antigravityTestAuth("cancel-"+change, server.URL)) + t.Cleanup(func() { GlobalModelRegistry().UnregisterClient(auth.ID) }) + svc.registerModelsForAuth(ctx, auth) + <-started + updated := auth.Clone() + switch change { + case "disabled": + updated.Disabled = true + case "route": + updated.Attributes["base_url"] = "https://new-route.invalid" + case "token", "native-refresh", "native-prepare", "native-update": + updated.Metadata["access_token"] = "new-token" + } + if change == "config-proxy" { + next := &config.Config{} + next.ProxyURL = "direct" + svc.commitConfigUpdate(next) + } else { + switch change { + case "native-refresh": + _, _ = svc.coreManager.UpdateRefreshedAuth(ctx, auth, updated) + case "native-prepare": + _, _ = svc.coreManager.UpdatePreparedAuth(ctx, auth, updated) + case "native-update": + _, _ = svc.coreManager.Update(ctx, updated) + case "native-remove": + svc.coreManager.Remove(ctx, auth.ID) + default: + svc.prepareCoreAuthForModelRegistration(ctx, updated) + } + } + select { + case <-cancelled: + case <-time.After(time.Second): + t.Fatal("obsolete connected probe was not canceled") + } + svc.WaitAntigravityProbes() + antigravityCapabilityMu.RLock() + failures := len(antigravityAuthFailureCache) + antigravityCapabilityMu.RUnlock() + if failures != 0 { + t.Fatal("account invalidation counted as upstream failure") + } + svc.antigravityProbeMu.Lock() + active := len(svc.antigravityAccountProbes) + svc.antigravityProbeMu.Unlock() + if active != 0 { + t.Fatal("completed account probes retained") + } + }) + } +} + +func TestAntigravityDeletedAccountCannotStartQueuedProbe(t *testing.T) { + svc := &Service{cfg: &config.Config{}, coreManager: coreauth.NewManager(nil, nil, nil)} + auth, _ := svc.coreManager.Register(t.Context(), antigravityTestAuth("queued-removed", "http://127.0.0.1:1")) + key := svc.antigravityCapabilityKey(auth) + svc.applyCoreAuthRemoval(t.Context(), auth.ID) + ctx, finish, active := svc.beginAntigravityAccountProbe(t.Context(), auth, key, "flight", "token-queued-removed") + defer finish() + if active || ctx.Err() == nil { + t.Fatal("removed account started a late queued probe") + } +} diff --git a/sdk/cliproxy/antigravity_models.go b/sdk/cliproxy/antigravity_models.go index cdb40066420..d36be67b716 100644 --- a/sdk/cliproxy/antigravity_models.go +++ b/sdk/cliproxy/antigravity_models.go @@ -1,11 +1,14 @@ package cliproxy import ( + "bytes" "context" "crypto/sha256" "encoding/json" "fmt" "io" + "maps" + "math/rand/v2" "net/http" "strings" "sync" @@ -13,6 +16,7 @@ import ( "time" "github.com/router-for-me/CLIProxyAPI/v8/internal/misc" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" "github.com/router-for-me/CLIProxyAPI/v8/sdk/proxyutil" @@ -21,12 +25,12 @@ import ( ) const ( - antigravityModelBaseURLDaily = "https://daily-cloudcode-pa.googleapis.com" - antigravityModelBaseURLProd = "https://cloudcode-pa.googleapis.com" - antigravityModelsPath = "/v1internal:fetchAvailableModels" - antigravityCapabilityProbeTimeout = 5 * time.Second - antigravityCapabilityCacheTTL = 5 * time.Minute - antigravityCapabilityFailureTTL = 1 * time.Minute + antigravityModelBaseURLDaily = "https://daily-cloudcode-pa.googleapis.com" + antigravityModelsPath = "/v1internal:fetchAvailableModels" + antigravityCapabilityCacheTTL = registry.ModelsRefreshInterval + antigravityCapabilityRetryBase = time.Minute + antigravityCapabilityRetryMax = 30 * time.Minute + antigravityRefreshScanInterval = time.Minute ) type antigravityProbeStatus int @@ -38,232 +42,245 @@ const ( ) type antigravityCapabilityCacheEntry struct { - hints antigravityModelCapabilityHints - expiresAt time.Time + hints antigravityModelCapabilityHints + expiresAt time.Time + lastUsed time.Time + probeRevision uint64 + appliedRevision uint64 + appliedEpoch uint64 + pending bool } -type antigravityProbeResult struct { - hints antigravityModelCapabilityHints - status antigravityProbeStatus - token string +// Keep attempt history beyond nextRetry; deleting it at retry time would turn +// exponential backoff back into a fixed interval. Inactive histories expire with +// the same retention horizon as inactive successful catalogs. +type antigravityFailureState struct { + failures uint8 + lastFailure time.Time + nextRetry time.Time +} + +func nextAntigravityFailure(previous antigravityFailureState, now time.Time, randomInt64N func(int64) int64) antigravityFailureState { + if now.Sub(previous.lastFailure) > 2*antigravityCapabilityCacheTTL { + previous.failures = 0 + } + // Five failures reach the capped window: 2, 4, 8, 16, 30 minutes. + failures := min(previous.failures, 4) + 1 + window := min(2*antigravityCapabilityRetryBase<<(failures-1), antigravityCapabilityRetryMax) + // Equal jitter retains a minimum delay, including at the cap (15-30 minutes). + half := window / 2 + delay := half + time.Duration(randomInt64N(int64(half)+1)) + return antigravityFailureState{failures: failures, lastFailure: now, nextRetry: now.Add(delay)} } var ( antigravityNowFunc = time.Now antigravityCapabilityMu sync.RWMutex antigravityCapabilityCache = make(map[string]antigravityCapabilityCacheEntry) - antigravityAuthFailureCache = make(map[string]time.Time) + antigravityAuthFailureCache = make(map[string]antigravityFailureState) antigravityCapabilityGroup singleflight.Group - antigravityProbeInFlight atomic.Int32 + antigravityProbeSequence atomic.Uint64 + antigravityProbeSlots = make(chan struct{}, modelRegistrationMaxWorkersPerCategory) ) -func purgeExpiredAntigravityCacheLocked(now time.Time) { - for k, v := range antigravityCapabilityCache { - if !now.Before(v.expiresAt) { - delete(antigravityCapabilityCache, k) - } - } - for k, exp := range antigravityAuthFailureCache { - if !now.Before(exp) { - delete(antigravityAuthFailureCache, k) - } - } -} - type antigravityFetchAvailableModelsResponse struct { - WebSearchModelIDs []string `json:"webSearchModelIds"` + WebSearchModelIDs []string `json:"webSearchModelIds"` + Models map[string]json.RawMessage `json:"models"` } type antigravityModelCapabilityHints struct { WebSearchModelIDs map[string]struct{} + // Nil means unknown; an empty non-nil set is an authoritative empty catalog. + ModelIDs map[string]struct{} + revision uint64 } func (h antigravityModelCapabilityHints) clone() antigravityModelCapabilityHints { - if h.WebSearchModelIDs == nil { - return antigravityModelCapabilityHints{} + return antigravityModelCapabilityHints{WebSearchModelIDs: maps.Clone(h.WebSearchModelIDs), ModelIDs: maps.Clone(h.ModelIDs), revision: h.revision} +} + +// antigravityCapabilityKey isolates catalogs by account, project and route, not token lifetime. +func (s *Service) antigravityCapabilityKey(auth *coreauth.Auth) string { + if auth == nil { + return "" } - cloned := make(map[string]struct{}, len(h.WebSearchModelIDs)) - for k := range h.WebSearchModelIDs { - cloned[k] = struct{}{} + return antigravityCapabilityKeyForRoute(auth, antigravityModelBaseURLs(auth)[0], s.antigravityModelFetchProxyURL(auth)) +} + +func antigravityCapabilityKeyForRoute(auth *coreauth.Auth, endpoint, proxy string) string { + project, _ := auth.Metadata["project_id"].(string) + identity := auth.ID + if identity == "" { + token, _ := auth.Metadata["access_token"].(string) + identity = fmt.Sprintf("%x", sha256.Sum256([]byte(token))) } - return antigravityModelCapabilityHints{WebSearchModelIDs: cloned} + return fmt.Sprintf("%q/%d/%q/%q/%q", identity, auth.RegistrationEpoch, project, endpoint, proxy) +} + +func (s *Service) cachedAntigravityHints(auth *coreauth.Auth) antigravityModelCapabilityHints { + key := s.antigravityCapabilityKey(auth) + antigravityCapabilityMu.RLock() + defer antigravityCapabilityMu.RUnlock() + return antigravityCapabilityCache[key].hints.clone() } func (s *Service) fetchAntigravityModelCapabilityHintsForAuth(ctx context.Context, auth *coreauth.Auth) antigravityModelCapabilityHints { - if auth == nil || auth.Metadata == nil { + if auth == nil || auth.Metadata == nil || s.antigravityHomeEnabled() { return antigravityModelCapabilityHints{} } + if ctx == nil { + ctx = context.Background() + } accessToken, _ := auth.Metadata["access_token"].(string) accessToken = strings.TrimSpace(accessToken) - if accessToken == "" { - return antigravityModelCapabilityHints{} + if accessToken == "" || ctx.Err() != nil { + return s.cachedAntigravityHints(auth) } - - baseURLs := antigravityModelBaseURLs(auth) - if len(baseURLs) == 0 { - return antigravityModelCapabilityHints{} - } - - proxyURL := s.antigravityModelFetchProxyURL(auth) - cacheKey := strings.Join(baseURLs, "|") + "#" + proxyURL - tokenHash := fmt.Sprintf("%x", sha256.Sum256([]byte(accessToken))) - authFailKey := auth.ID + "#" + tokenHash - - now := antigravityNowFunc() - antigravityCapabilityMu.RLock() - if failExpiry, failed := antigravityAuthFailureCache[authFailKey]; failed && now.Before(failExpiry) { - antigravityCapabilityMu.RUnlock() - return antigravityModelCapabilityHints{} + baseURLs, proxyURL := antigravityModelBaseURLs(auth), s.antigravityModelFetchProxyURL(auth) + cacheKey := antigravityCapabilityKeyForRoute(auth, baseURLs[0], proxyURL) + failureKey := cacheKey + fmt.Sprintf("/%x", sha256.Sum256([]byte(accessToken))) + lookup := func() (antigravityModelCapabilityHints, bool) { + antigravityCapabilityMu.Lock() + defer antigravityCapabilityMu.Unlock() + entry, exists := antigravityCapabilityCache[cacheKey] + now := antigravityNowFunc() + if exists { + entry.lastUsed = now + antigravityCapabilityCache[cacheKey] = entry + } + return entry.hints.clone(), now.Before(entry.expiresAt) || now.Before(antigravityAuthFailureCache[failureKey].nextRetry) } - if entry, ok := antigravityCapabilityCache[cacheKey]; ok && now.Before(entry.expiresAt) { - hints := entry.hints.clone() - antigravityCapabilityMu.RUnlock() + if hints, cached := lookup(); cached { return hints } - antigravityCapabilityMu.RUnlock() - - antigravityProbeInFlight.Add(1) - defer antigravityProbeInFlight.Add(-1) - - res, errDo, _ := antigravityCapabilityGroup.Do(cacheKey, func() (any, error) { - nowInside := antigravityNowFunc() - antigravityCapabilityMu.RLock() - if entry, ok := antigravityCapabilityCache[cacheKey]; ok && nowInside.Before(entry.expiresAt) { - hints := entry.hints.clone() - antigravityCapabilityMu.RUnlock() - return antigravityProbeResult{hints: hints, status: antigravityProbeStatusSuccess, token: accessToken}, nil + // The initiating caller owns the shared HTTP operation. Followers may cancel + // their own wait without canceling that operation or blocking a refresh worker. + resultCh := antigravityCapabilityGroup.DoChan(failureKey, func() (any, error) { + if hints, cached := lookup(); cached { + return hints, nil } - antigravityCapabilityMu.RUnlock() - + ctx, finish, active := s.beginAntigravityAccountProbe(ctx, auth, cacheKey, failureKey, accessToken) + if !active { + return s.cachedAntigravityHints(auth), nil + } + defer finish() + revision := antigravityProbeSequence.Add(1) + antigravityCapabilityMu.Lock() + entry := antigravityCapabilityCache[cacheKey] + entry.probeRevision, entry.lastUsed, entry.pending = revision, antigravityNowFunc(), true + antigravityCapabilityCache[cacheKey] = entry + antigravityCapabilityMu.Unlock() + defer func() { + antigravityCapabilityMu.Lock() + current := antigravityCapabilityCache[cacheKey] + if current.probeRevision == revision { + current.pending = false + antigravityCapabilityCache[cacheKey] = current + } + antigravityCapabilityMu.Unlock() + }() + select { + case antigravityProbeSlots <- struct{}{}: + case <-ctx.Done(): + hints, _ := lookup() + return hints, nil + } + defer func() { <-antigravityProbeSlots }() hints, status := s.probeAntigravityModelCapabilityHints(ctx, auth, baseURLs, proxyURL, accessToken) - if status == antigravityProbeStatusSuccess || status == antigravityProbeStatusTransientError { - if status != antigravityProbeStatusTransientError || ctx == nil || ctx.Err() == nil { - ttl := antigravityCapabilityCacheTTL - if status != antigravityProbeStatusSuccess { - ttl = antigravityCapabilityFailureTTL - } - antigravityCapabilityMu.Lock() - purgeExpiredAntigravityCacheLocked(nowInside) - antigravityCapabilityCache[cacheKey] = antigravityCapabilityCacheEntry{ - hints: hints.clone(), - expiresAt: antigravityNowFunc().Add(ttl), - } - antigravityCapabilityMu.Unlock() + antigravityCapabilityMu.Lock() + defer antigravityCapabilityMu.Unlock() + current := antigravityCapabilityCache[cacheKey] + if ctx.Err() != nil || current.probeRevision != revision { + return current.hints.clone(), nil + } + now := antigravityNowFunc() + for key, other := range antigravityCapabilityCache { + if key != cacheKey && !other.pending && now.Sub(other.lastUsed) > 2*antigravityCapabilityCacheTTL { + delete(antigravityCapabilityCache, key) } } - return antigravityProbeResult{hints: hints, status: status, token: accessToken}, nil + for key, failure := range antigravityAuthFailureCache { + if now.Sub(failure.lastFailure) > 2*antigravityCapabilityCacheTTL { + delete(antigravityAuthFailureCache, key) + } + } + if status == antigravityProbeStatusSuccess && hints.ModelIDs != nil { + hints.revision = revision + current.hints, current.expiresAt, current.lastUsed = hints.clone(), now.Add(antigravityCapabilityCacheTTL), now + antigravityCapabilityCache[cacheKey] = current + delete(antigravityAuthFailureCache, failureKey) + return hints, nil + } + // Missing models (including legacy capability-only responses) are not a + // successful catalog. Preserve last success and increase the jittered backoff. + antigravityAuthFailureCache[failureKey] = nextAntigravityFailure(antigravityAuthFailureCache[failureKey], now, rand.Int64N) + retained := current.hints.clone() + if status == antigravityProbeStatusSuccess && len(hints.WebSearchModelIDs) > 0 { + retained.WebSearchModelIDs = hints.WebSearchModelIDs + } + return retained, nil }) - if errDo != nil || res == nil { - return antigravityModelCapabilityHints{} - } - result, ok := res.(antigravityProbeResult) - if !ok { - return antigravityModelCapabilityHints{} - } - - if result.status == antigravityProbeStatusAuthError { - if result.token != accessToken { - // The shared probe failed with an auth error from another account's token. - // Re-try with our own account's token. - return s.fetchAntigravityModelCapabilityHintsForAuth(ctx, auth) + select { + case <-ctx.Done(): + hints, _ := lookup() + return hints + case result := <-resultCh: + if result.Err != nil || result.Val == nil { + hints, _ := lookup() + return hints } - // Our own token failed with 401/403. Record backoff for this account/token. - antigravityCapabilityMu.Lock() - purgeExpiredAntigravityCacheLocked(now) - antigravityAuthFailureCache[authFailKey] = antigravityNowFunc().Add(antigravityCapabilityFailureTTL) - antigravityCapabilityMu.Unlock() - return antigravityModelCapabilityHints{} + return result.Val.(antigravityModelCapabilityHints).clone() } - - return result.hints.clone() } func (s *Service) probeAntigravityModelCapabilityHints(ctx context.Context, auth *coreauth.Auth, baseURLs []string, proxyURL string, accessToken string) (antigravityModelCapabilityHints, antigravityProbeStatus) { - probeCtx := context.Background() - var cancel context.CancelFunc - probeCtx, cancel = context.WithTimeout(probeCtx, antigravityCapabilityProbeTimeout) - defer cancel() - - client := &http.Client{ - Timeout: antigravityCapabilityProbeTimeout, - } - if transport, _, errProxy := proxyutil.BuildHTTPTransport(proxyURL); errProxy == nil && transport != nil { - client.Transport = transport - } - - if len(baseURLs) == 1 { - return s.fetchAntigravityModelHintsFromURL(probeCtx, client, baseURLs[0], accessToken) - } - - type probeResult struct { - hints antigravityModelCapabilityHints - status antigravityProbeStatus + if len(baseURLs) == 0 { + return antigravityModelCapabilityHints{}, antigravityProbeStatusTransientError } - ch := make(chan probeResult, len(baseURLs)) - for _, baseURL := range baseURLs { - go func(url string) { - h, status := s.fetchAntigravityModelHintsFromURL(probeCtx, client, url, accessToken) - ch <- probeResult{hints: h, status: status} - }(baseURL) + client := &http.Client{} + transport, _, errProxy := proxyutil.BuildHTTPTransport(proxyURL) + if errProxy != nil { + return antigravityModelCapabilityHints{}, antigravityProbeStatusTransientError } - - var firstSuccess antigravityModelCapabilityHints - var hadSuccess bool - overallStatus := antigravityProbeStatusTransientError - for i := 0; i < len(baseURLs); i++ { - select { - case <-probeCtx.Done(): - return antigravityModelCapabilityHints{}, antigravityProbeStatusTransientError - case res := <-ch: - if res.status == antigravityProbeStatusSuccess { - if len(res.hints.WebSearchModelIDs) > 0 { - return res.hints, antigravityProbeStatusSuccess - } - if !hadSuccess { - firstSuccess = res.hints - hadSuccess = true - } - } else if res.status == antigravityProbeStatusAuthError { - overallStatus = antigravityProbeStatusAuthError - } - } + if transport != nil { + client.Transport = transport + defer transport.CloseIdleConnections() } - if hadSuccess { - return firstSuccess, antigravityProbeStatusSuccess + project, _ := auth.Metadata["project_id"].(string) + body, errMarshal := json.Marshal(map[string]string{"project": project}) + if errMarshal != nil { + return antigravityModelCapabilityHints{}, antigravityProbeStatusTransientError } - return antigravityModelCapabilityHints{}, overallStatus -} - -func (s *Service) fetchAntigravityModelHintsFromURL(ctx context.Context, client *http.Client, baseURL string, accessToken string) (antigravityModelCapabilityHints, antigravityProbeStatus) { - req, errReq := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(baseURL, "/")+antigravityModelsPath, strings.NewReader(`{}`)) + // Default to daily and use only the first explicitly configured endpoint. + // Racing catalogs from different endpoints can grant incompatible entitlements. + req, errReq := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(baseURLs[0], "/")+antigravityModelsPath, bytes.NewReader(body)) if errReq != nil { return antigravityModelCapabilityHints{}, antigravityProbeStatusTransientError } - req.Close = true req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+accessToken) req.Header.Set("User-Agent", misc.AntigravityUserAgent()) - resp, errDo := client.Do(req) if errDo != nil { return antigravityModelCapabilityHints{}, antigravityProbeStatusTransientError } defer func() { if errClose := resp.Body.Close(); errClose != nil { - log.Debugf("antigravity model fetch: close response body: %v", errClose) + log.Debug("antigravity model fetch: response close failed") } }() if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden { return antigravityModelCapabilityHints{}, antigravityProbeStatusAuthError } - body, errRead := io.ReadAll(resp.Body) - if errRead != nil { + if resp.StatusCode < 200 || resp.StatusCode >= 300 { return antigravityModelCapabilityHints{}, antigravityProbeStatusTransientError } - if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices { + const maxCatalogBytes = 8 << 20 + data, errRead := io.ReadAll(io.LimitReader(resp.Body, maxCatalogBytes+1)) + if errRead != nil || len(data) > maxCatalogBytes { return antigravityModelCapabilityHints{}, antigravityProbeStatusTransientError } - hints, ok := parseAntigravityModelCapabilityHints(body) + hints, ok := parseAntigravityModelCapabilityHints(data) if !ok { return antigravityModelCapabilityHints{}, antigravityProbeStatusTransientError } @@ -339,7 +356,16 @@ func parseAntigravityModelCapabilityHints(body []byte) (antigravityModelCapabili webSearchModels[modelID] = struct{}{} } } - return antigravityModelCapabilityHints{WebSearchModelIDs: webSearchModels}, true + var modelIDs map[string]struct{} + if parsed.Models != nil { + modelIDs = make(map[string]struct{}, len(parsed.Models)) + for id := range parsed.Models { + if normalized := normalizeAntigravityFetchedModelID(id); normalized != "" { + modelIDs[normalized] = struct{}{} + } + } + } + return antigravityModelCapabilityHints{WebSearchModelIDs: webSearchModels, ModelIDs: modelIDs}, true } func applyAntigravityFetchedModelCapabilities(models []*ModelInfo, hints antigravityModelCapabilityHints) []*ModelInfo { @@ -371,80 +397,293 @@ func (s *Service) WaitAntigravityProbes() { s.antigravityProbeWg.Wait() } -func (s *Service) waitAntigravityProbesContext(ctx context.Context) { - if s == nil || ctx == nil { +// Native Antigravity reconciliation belongs to the fenced asynchronous registry +// publication, not cache availability. A known cache can precede its registration. +func (s *Service) reconcileRegisteredModelStates(ctx context.Context, auth *coreauth.Auth) { + if auth == nil || s.coreManager == nil { return } - done := make(chan struct{}) - go func() { - s.antigravityProbeWg.Wait() - close(done) - }() - select { - case <-ctx.Done(): - case <-done: + if strings.EqualFold(auth.Provider, "antigravity") && !s.antigravityHomeEnabled() { + return + } + s.coreManager.ReconcileRegistryModelStates(ctx, auth.ID) +} + +func (s *Service) antigravityHomeEnabled() bool { + if s == nil { + return false } + s.cfgMu.RLock() + defer s.cfgMu.RUnlock() + return s.cfg != nil && s.cfg.Home.Enabled +} + +func filterAntigravityModels(models []*ModelInfo, hints antigravityModelCapabilityHints) []*ModelInfo { + filtered := make([]*ModelInfo, 0, len(models)) + for _, model := range models { + if model != nil { + if _, ok := hints.ModelIDs[normalizeAntigravityFetchedModelID(model.ID)]; ok { + filtered = append(filtered, model) + } + } + } + return filtered +} + +func (s *Service) antigravityModelsForHints(auth *coreauth.Auth, hints antigravityModelCapabilityHints) []*ModelInfo { + s.cfgMu.RLock() + cfg := s.cfg + s.cfgMu.RUnlock() + return s.antigravityModelsForHintsWithConfig(auth, hints, cfg) +} + +func (s *Service) antigravityModelsForHintsWithConfig(auth *coreauth.Auth, hints antigravityModelCapabilityHints, cfg *config.Config) []*ModelInfo { + if cfg == nil { + cfg = &config.Config{} + } + models := filterAntigravityModels(registry.GetAntigravityModels(), hints) + models = applyAntigravityFetchedModelCapabilities(models, hints) + excluded := cfg.OAuthExcludedModels[coreauth.OAuthModelAliasChannel(auth.Provider, auth.AuthKind())] + if value := strings.TrimSpace(auth.Attributes["excluded_models"]); value != "" { + excluded = strings.Split(value, ",") + } + models = applyExcludedModels(models, excluded) + models = applyOAuthModelAliasForAuth(cfg, "antigravity", auth.AuthKind(), auth.Attributes, models) + models = s.appendPluginModels("antigravity", models) + models = applyOAuthSettingsForAuth(cfg, "antigravity", auth.AuthKind(), models) + return applyModelPrefixes(models, auth.Prefix, cfg.ForceModelPrefix) } func (s *Service) asyncProbeAntigravityCapabilities(ctx context.Context, auth *coreauth.Auth, providerKey string) { - if auth == nil || auth.ID == "" || auth.Disabled { + if s == nil || auth == nil || auth.ID == "" || auth.Disabled || s.antigravityHomeEnabled() { return } + if ctx == nil { + ctx = context.Background() + } authClone := auth.Clone() expectedEpoch := auth.RegistrationEpoch - expectedPrefix := auth.Prefix expectedRegEpoch := GlobalModelRegistry().ClientRegistrationEpoch(auth.ID) + s.antigravityProbeWg.Add(1) + go func() { + defer s.antigravityProbeWg.Done() + probeCtx, cancel := context.WithCancel(ctx) + defer cancel() + s.cfgMu.RLock() + lifetime := s.antigravityContext + s.cfgMu.RUnlock() + if lifetime != nil { + stop := context.AfterFunc(lifetime, cancel) + defer stop() + if lifetime.Err() != nil { + return + } + } + s.probeAndRegisterAntigravityModels(probeCtx, authClone, providerKey, expectedEpoch, expectedRegEpoch) + }() +} - probeCtx := ctx - if probeCtx == nil { - probeCtx = context.Background() - } +func (s *Service) probeAndRegisterAntigravityModels(ctx context.Context, auth *coreauth.Auth, providerKey string, expectedEpoch, expectedRegEpoch uint64) { + expectedKey := s.antigravityCapabilityKey(auth) + hints := s.fetchAntigravityModelCapabilityHintsForAuth(ctx, auth) + s.applyAntigravityModelHints(ctx, auth, providerKey, hints, expectedKey, expectedEpoch, expectedRegEpoch) +} - if s != nil { - s.antigravityProbeWg.Add(1) - } +// Request results change Generation, not these registration inputs. Compare the +// actual model settings so exclusions and account aliases cannot be replayed stale. +func antigravityAuthModelSettingsEqual(a, b *coreauth.Auth) bool { + return a != nil && b != nil && a.Provider == b.Provider && a.Prefix == b.Prefix && + a.RegistrationEpoch == b.RegistrationEpoch && a.Disabled == b.Disabled && + (a.Status == coreauth.StatusDisabled) == (b.Status == coreauth.StatusDisabled) && + a.AuthKind() == b.AuthKind() && maps.Equal(a.Attributes, b.Attributes) +} - go func() { - if s != nil { - defer s.antigravityProbeWg.Done() +func (s *Service) applyAntigravityModelHints(ctx context.Context, auth *coreauth.Auth, providerKey string, hints antigravityModelCapabilityHints, expectedKey string, expectedEpoch, expectedRegEpoch uint64) { + if ctx.Err() != nil || s.antigravityHomeEnabled() { + return + } + if hints.ModelIDs == nil && len(hints.WebSearchModelIDs) == 0 { + return + } + if s.coreManager != nil { + current, exists := s.coreManager.GetByID(auth.ID) + if !exists || current == nil || current.Disabled || current.Provider != auth.Provider || current.RegistrationEpoch != expectedEpoch || !antigravityAuthModelSettingsEqual(current, auth) || s.antigravityCapabilityKey(current) != expectedKey { + return } - hints := s.fetchAntigravityModelCapabilityHintsForAuth(probeCtx, authClone) - if len(hints.WebSearchModelIDs) == 0 { + } + var updated bool + if hints.ModelIDs != nil { + // Keep the config snapshot stable through publication. Registry CAS must + // remain strict: an epoch from another publisher may use newer auth settings. + s.cfgMu.RLock() + models := s.antigravityModelsForHintsWithConfig(auth, hints, s.cfg) + // Fence the cache-to-registry publication as well as the network result. + // A newer successful catalog must never be replaced by an older caller. + antigravityCapabilityMu.Lock() + entry := antigravityCapabilityCache[expectedKey] + if entry.hints.revision != hints.revision { + antigravityCapabilityMu.Unlock() + s.cfgMu.RUnlock() return } - if s == nil { + reg := registry.GetGlobalRegistry() + var appliedEpoch uint64 + appliedEpoch, updated = reg.ReplaceClientModels(auth.ID, providerKey, expectedRegEpoch, models) + if updated { + entry.appliedRevision = hints.revision + entry.appliedEpoch = appliedEpoch + antigravityCapabilityCache[expectedKey] = entry + } + antigravityCapabilityMu.Unlock() + s.cfgMu.RUnlock() + } else { + // Older capability-only responses cannot revoke model entitlements. + aliasMap := s.buildAntigravityReverseAliasMap(auth) + updated = GlobalModelRegistry().ApplyClientModelCapabilities(auth.ID, expectedRegEpoch, func(id string, info *ModelInfo) { + if _, ok := hints.WebSearchModelIDs[resolveAntigravityUpstreamModelID(id, auth.Prefix, aliasMap)]; ok { + info.SupportsWebSearch = true + } + }) + } + if updated && s.coreManager != nil { + s.coreManager.ReconcileRegistryModelStates(ctx, auth.ID) + s.coreManager.RefreshSchedulerEntry(auth.ID) + } +} + +// refreshAntigravityModels schedules account refreshes without waiting for the batch. +// One unfinished request must not block other accounts' retry or expiry deadlines. +// Network concurrency remains bounded by antigravityProbeSlots. +func (s *Service) refreshAntigravityModels(ctx context.Context) { + if s == nil || s.coreManager == nil || s.antigravityHomeEnabled() { + return + } + if ctx == nil { + ctx = context.Background() + } + for _, auth := range s.coreManager.List() { + if ctx.Err() != nil { + return + } + if auth == nil || auth.Disabled || !strings.EqualFold(auth.Provider, "antigravity") { + continue + } + snapshot := auth.Clone() + key := s.antigravityCapabilityKey(snapshot) + token, _ := snapshot.Metadata["access_token"].(string) + failureKey := key + fmt.Sprintf("/%x", sha256.Sum256([]byte(strings.TrimSpace(token)))) + epoch := GlobalModelRegistry().ClientRegistrationEpoch(snapshot.ID) + antigravityCapabilityMu.RLock() + entry := antigravityCapabilityCache[key] + registered := entry.appliedRevision == entry.hints.revision && entry.appliedEpoch == epoch + fresh := (antigravityNowFunc().Before(entry.expiresAt) && registered) || antigravityNowFunc().Before(antigravityAuthFailureCache[failureKey].nextRetry) + antigravityCapabilityMu.RUnlock() + if fresh { + continue + } + s.scheduleAntigravityModelRefresh(ctx, snapshot) + } +} + +func (s *Service) scheduleAntigravityModelRefresh(ctx context.Context, auth *coreauth.Auth) { + s.antigravityProbeMu.Lock() + if _, pending := s.antigravityRefreshPending[auth.ID]; pending { + s.antigravityProbeMu.Unlock() + return + } + if s.antigravityRefreshPending == nil { + s.antigravityRefreshPending = make(map[string]struct{}) + } + s.antigravityRefreshPending[auth.ID] = struct{}{} + if s.antigravityRefreshPluginSlots == nil { + s.antigravityRefreshPluginSlots = make(chan struct{}, modelRegistrationMaxWorkersPerCategory) + } + pluginSlots := s.antigravityRefreshPluginSlots + s.antigravityProbeWg.Add(1) + s.antigravityProbeMu.Unlock() + go func() { + defer s.antigravityProbeWg.Done() + defer func() { + s.antigravityProbeMu.Lock() + delete(s.antigravityRefreshPending, auth.ID) + s.antigravityProbeMu.Unlock() + s.signalAntigravityModelRefresh() + }() + if ctx.Err() != nil { return } - if s.coreManager != nil { - current, exists := s.coreManager.GetByID(authClone.ID) - if !exists || current == nil || current.Disabled { + if s.pluginHost != nil { + select { + case pluginSlots <- struct{}{}: + case <-ctx.Done(): return } - // Version protection: verify auth registration epoch and prefix did not change. - // Auth.Generation is intentionally NOT checked here because regular request completions - // increment Generation on every request (via MarkResult), which must not invalidate valid probe results. - if current.RegistrationEpoch != expectedEpoch || current.Prefix != expectedPrefix { + result := s.pluginHost.ModelsForAuth(ctx, auth) + <-pluginSlots + if result.Handled || ctx.Err() != nil { return } } - aliasMap := s.buildAntigravityReverseAliasMap(authClone) + epoch := GlobalModelRegistry().ClientRegistrationEpoch(auth.ID) + s.probeAndRegisterAntigravityModels(ctx, auth, "antigravity", auth.RegistrationEpoch, epoch) + }() +} - // Atomically update capabilities on existing registered models if epoch matches - updated := GlobalModelRegistry().ApplyClientModelCapabilities(authClone.ID, expectedRegEpoch, func(modelID string, info *ModelInfo) { - upstreamID := resolveAntigravityUpstreamModelID(modelID, authClone.Prefix, aliasMap) - if _, ok := hints.WebSearchModelIDs[upstreamID]; ok { - info.SupportsWebSearch = true +// nextAntigravityModelRefreshDelay preserves retry jitter in actual scheduling, +// rather than rounding every account's deadline up to the same minute tick. +// The upper bound still discovers accounts/config changes that bypass a wakeup. +func (s *Service) nextAntigravityModelRefreshDelay() time.Duration { + now := antigravityNowFunc() + next := now.Add(antigravityRefreshScanInterval) + if s == nil || s.coreManager == nil || s.antigravityHomeEnabled() { + return antigravityRefreshScanInterval + } + for _, auth := range s.coreManager.List() { + if auth == nil || auth.Disabled || !strings.EqualFold(auth.Provider, "antigravity") { + continue + } + key := s.antigravityCapabilityKey(auth) + token, _ := auth.Metadata["access_token"].(string) + failureKey := key + fmt.Sprintf("/%x", sha256.Sum256([]byte(strings.TrimSpace(token)))) + antigravityCapabilityMu.RLock() + retry := antigravityAuthFailureCache[failureKey].nextRetry + expiry := antigravityCapabilityCache[key].expiresAt + antigravityCapabilityMu.RUnlock() + for _, deadline := range []time.Time{retry, expiry} { + if deadline.After(now) && deadline.Before(next) { + next = deadline } - }) - if !updated { - return } + } + return next.Sub(now) +} - if s.coreManager != nil { - s.coreManager.ReconcileRegistryModelStates(context.Background(), authClone.ID) - s.coreManager.RefreshSchedulerEntry(authClone.ID) +func (s *Service) runAntigravityModelRefresh(ctx context.Context) { + wake := s.antigravityModelRefreshWake() + delay := s.nextAntigravityModelRefreshDelay() + deadline := antigravityNowFunc().Add(delay) + timer := time.NewTimer(delay) + defer timer.Stop() + for { + select { + case <-ctx.Done(): + return + case <-wake: + // Wakeups may advance a timer, never postpone an already due retry. + delay = s.nextAntigravityModelRefreshDelay() + earlier := antigravityNowFunc().Add(delay) + if earlier.Before(deadline) { + deadline = earlier + timer.Reset(delay) + } + continue + case <-timer.C: + s.refreshAntigravityModels(ctx) } - }() + delay = s.nextAntigravityModelRefreshDelay() + deadline = antigravityNowFunc().Add(delay) + timer.Reset(delay) + } } func (s *Service) buildAntigravityReverseAliasMap(auth *coreauth.Auth) map[string]string { diff --git a/sdk/cliproxy/antigravity_models_backoff_test.go b/sdk/cliproxy/antigravity_models_backoff_test.go new file mode 100644 index 00000000000..392fabdc1eb --- /dev/null +++ b/sdk/cliproxy/antigravity_models_backoff_test.go @@ -0,0 +1,150 @@ +package cliproxy + +import ( + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" + + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" +) + +func TestAntigravityFailureBackoffWindowsAndCap(t *testing.T) { + for _, sample := range []struct { + name string + random func(int64) int64 + }{ + {"lower", func(int64) int64 { return 0 }}, + {"middle", func(n int64) int64 { return n / 2 }}, + {"upper", func(n int64) int64 { return n - 1 }}, + } { + t.Run(sample.name, func(t *testing.T) { + now := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + var state antigravityFailureState + for i := range 300 { + expectedWindow := []time.Duration{2, 4, 8, 16, 30}[min(i, 4)] * time.Minute + state = nextAntigravityFailure(state, now, sample.random) + delay := state.nextRetry.Sub(now) + expected := expectedWindow/2 + time.Duration(sample.random(int64(expectedWindow/2)+1)) + if delay != expected || state.failures != uint8(min(i+1, 5)) || !state.lastFailure.Equal(now) { + t.Fatalf("attempt %d: state=%+v delay=%s want=%s", i+1, state, delay, expected) + } + now = state.nextRetry + } + // An expired retry deadline alone must not reset consecutive failures. + state = nextAntigravityFailure(state, state.nextRetry.Add(time.Minute), sample.random) + if state.failures != 5 { + t.Fatal("expired retry deadline discarded failure history") + } + // Truly inactive account/token histories can start over after retention. + state = nextAntigravityFailure(state, state.lastFailure.Add(2*antigravityCapabilityCacheTTL+time.Nanosecond), sample.random) + if state.failures != 1 { + t.Fatal("inactive failure history did not reset") + } + }) + } +} + +func TestAntigravityFailureBackoffIntegration(t *testing.T) { + resetAntigravityCapabilityCache() + t.Cleanup(resetAntigravityCapabilityCache) + now := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + antigravityNowFunc = func() time.Time { return now } + t.Cleanup(func() { antigravityNowFunc = time.Now }) + var calls atomic.Int32 + var status atomic.Int32 + status.Store(503) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + w.WriteHeader(int(status.Load())) + _, _ = w.Write([]byte(`{"models":{"gemini-3.1-flash-lite":{}}}`)) + })) + defer server.Close() + manager := coreauth.NewManager(nil, nil, nil) + svc := &Service{cfg: &config.Config{}, coreManager: manager} + auth := antigravityTestAuth("backoff", server.URL) + auth, _ = manager.Register(t.Context(), auth) + t.Cleanup(func() { GlobalModelRegistry().UnregisterClient(auth.ID) }) + readFailure := func() antigravityFailureState { + t.Helper() + antigravityCapabilityMu.RLock() + defer antigravityCapabilityMu.RUnlock() + if len(antigravityAuthFailureCache) != 1 { + t.Fatalf("failure entries=%d", len(antigravityAuthFailureCache)) + } + for _, entry := range antigravityAuthFailureCache { + return entry + } + return antigravityFailureState{} + } + antigravityCapabilityMu.Lock() + antigravityAuthFailureCache["inactive-token"] = antigravityFailureState{ + failures: 5, lastFailure: now.Add(-2*antigravityCapabilityCacheTTL - time.Nanosecond), + } + antigravityCapabilityMu.Unlock() + for i := range 8 { + svc.refreshAntigravityModels(t.Context()) + svc.WaitAntigravityProbes() + if calls.Load() != int32(i+1) { + t.Fatalf("attempt %d calls=%d", i+1, calls.Load()) + } + state := readFailure() + window := []time.Duration{2, 4, 8, 16, 30}[min(i, 4)] * time.Minute + delay := state.nextRetry.Sub(now) + if state.failures != uint8(min(i+1, 5)) || delay < window/2 || delay > window { + t.Fatalf("attempt %d: %+v delay=%s", i+1, state, delay) + } + now = state.nextRetry.Add(-time.Nanosecond) + // Both periodic and direct registration fetches respect the same deadline. + svc.refreshAntigravityModels(t.Context()) + svc.WaitAntigravityProbes() + svc.fetchAntigravityModelCapabilityHintsForAuth(t.Context(), auth) + if calls.Load() != int32(i+1) { + t.Fatal("retried before jittered deadline") + } + now = state.nextRetry + } + status.Store(200) + svc.refreshAntigravityModels(t.Context()) + svc.WaitAntigravityProbes() + antigravityCapabilityMu.RLock() + failures := len(antigravityAuthFailureCache) + antigravityCapabilityMu.RUnlock() + if failures != 0 { + t.Fatal("success did not reset consecutive failures") + } + if len(GlobalModelRegistry().GetModelsForClient(auth.ID)) != 1 { + t.Fatal("successful retry did not restore models") + } + status.Store(503) + now = now.Add(antigravityCapabilityCacheTTL) + svc.refreshAntigravityModels(t.Context()) + svc.WaitAntigravityProbes() + if state := readFailure(); state.failures != 1 { + t.Fatal("failure following success did not restart at first window") + } + if len(GlobalModelRegistry().GetModelsForClient(auth.ID)) != 1 { + t.Fatal("failed refresh discarded last successful catalog") + } + // A new token must not inherit the old token's authorization/backoff state. + rotated := auth.Clone() + rotated.Metadata["access_token"] = "rotated" + rotated, _ = manager.Update(t.Context(), rotated) + before := calls.Load() + svc.fetchAntigravityModelCapabilityHintsForAuth(t.Context(), rotated) + if calls.Load() != before+1 { + t.Fatal("new token blocked by old token backoff") + } + antigravityCapabilityMu.RLock() + defer antigravityCapabilityMu.RUnlock() + if len(antigravityAuthFailureCache) != 2 { + t.Fatal("token histories not isolated") + } + for _, failure := range antigravityAuthFailureCache { + if failure.failures != 1 { + t.Fatal("new token inherited consecutive failures") + } + } +} diff --git a/sdk/cliproxy/antigravity_models_dedup_test.go b/sdk/cliproxy/antigravity_models_dedup_test.go index e7010cb30dc..f8c20785ca4 100644 --- a/sdk/cliproxy/antigravity_models_dedup_test.go +++ b/sdk/cliproxy/antigravity_models_dedup_test.go @@ -2,6 +2,8 @@ package cliproxy import ( "context" + "encoding/json" + "fmt" "net/http" "net/http/httptest" "sync" @@ -9,566 +11,218 @@ import ( "testing" "time" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" - "golang.org/x/sync/singleflight" ) func resetAntigravityCapabilityCache() { antigravityCapabilityMu.Lock() antigravityCapabilityCache = make(map[string]antigravityCapabilityCacheEntry) - antigravityAuthFailureCache = make(map[string]time.Time) + antigravityAuthFailureCache = make(map[string]antigravityFailureState) antigravityCapabilityMu.Unlock() - antigravityCapabilityGroup = singleflight.Group{} } -// TestAntigravityModelBaseURLs_DefaultDaily verifies that when no custom base_url -// or base_urls attribute is configured, the default base URL is daily-cloudcode-pa.googleapis.com only. +func antigravityTestAuth(id, endpoint string) *coreauth.Auth { + return &coreauth.Auth{ID: id, Provider: "antigravity", Attributes: map[string]string{"base_url": endpoint}, Metadata: map[string]any{"access_token": "token-" + id, "project_id": "project-" + id}} +} + func TestAntigravityModelBaseURLs_DefaultDaily(t *testing.T) { - auth := &coreauth.Auth{ - ID: "test-ag", - Provider: "antigravity", - } - urls := antigravityModelBaseURLs(auth) - if len(urls) != 1 { - t.Fatalf("antigravityModelBaseURLs returned %d URLs (%v), want exactly 1 default URL", len(urls), urls) + urls := antigravityModelBaseURLs(&coreauth.Auth{}) + if len(urls) != 1 || urls[0] != antigravityModelBaseURLDaily { + t.Fatalf("unexpected default: %v", urls) } - if urls[0] != antigravityModelBaseURLDaily { - t.Fatalf("antigravityModelBaseURLs[0] = %q, want %q", urls[0], antigravityModelBaseURLDaily) + if antigravityCapabilityCacheTTL != registry.ModelsRefreshInterval { + t.Fatal("catalog and entitlement cache must share cadence") } } -// TestAntigravityCapabilityProbe_DeduplicatesConcurrentRequests verifies that concurrent capability -// probe requests across multiple accounts share a single upstream request via singleflight deduplication -// even before any cache entry has been committed. func TestAntigravityCapabilityProbe_DeduplicatesConcurrentRequests(t *testing.T) { resetAntigravityCapabilityCache() t.Cleanup(resetAntigravityCapabilityCache) - - var requestCount atomic.Int32 - requestStarted := make(chan struct{}) - releaseRequest := make(chan struct{}) - var releaseOnce sync.Once - release := func() { releaseOnce.Do(func() { close(releaseRequest) }) } - defer release() - + var calls atomic.Int32 + started, release := make(chan struct{}), make(chan struct{}) + var once sync.Once + unblock := func() { once.Do(func() { close(release) }) } + defer unblock() server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - requestCount.Add(1) - close(requestStarted) - <-releaseRequest - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(`{"webSearchModelIds":["gemini-3.1-flash-lite"]}`)) + if calls.Add(1) == 1 { + close(started) + } + <-release + _, _ = w.Write([]byte(`{"models":{"allowed":{}},"webSearchModelIds":["allowed"]}`)) })) - t.Cleanup(func() { - release() - server.CloseClientConnections() - server.Close() - }) - - svc := &Service{ - cfg: &config.Config{}, - } - - const numCallers = 5 + t.Cleanup(func() { unblock(); server.Close() }) + svc := &Service{cfg: &config.Config{}} + auth := antigravityTestAuth("shared", server.URL) var wg sync.WaitGroup - wg.Add(numCallers) - - // Caller 1: initiates request and blocks inside the server handler - go func() { - defer wg.Done() - auth := &coreauth.Auth{ - ID: "test-ag-dedup-1", - Provider: "antigravity", - Attributes: map[string]string{ - "base_url": server.URL, - }, - Metadata: map[string]any{ - "access_token": "ya29.test-token-1", - }, - } - hints := svc.fetchAntigravityModelCapabilityHintsForAuth(context.Background(), auth) - if _, ok := hints.WebSearchModelIDs["gemini-3.1-flash-lite"]; !ok { - t.Errorf("caller 1: expected gemini-3.1-flash-lite in hints") - } - }() - - // Wait until caller 1's request is actively inside the server handler (before cache is written) - <-requestStarted - - // Callers 2..5: launched while caller 1 is in flight. They must be merged by singleflight. - for i := 2; i <= numCallers; i++ { - go func(idx int) { + for range 12 { + wg.Add(1) + go func() { defer wg.Done() - auth := &coreauth.Auth{ - ID: "test-ag-dedup-subsequent", - Provider: "antigravity", - Attributes: map[string]string{ - "base_url": server.URL, - }, - Metadata: map[string]any{ - "access_token": "ya29.test-token", - }, - } - hints := svc.fetchAntigravityModelCapabilityHintsForAuth(context.Background(), auth) - if _, ok := hints.WebSearchModelIDs["gemini-3.1-flash-lite"]; !ok { - t.Errorf("caller %d: expected gemini-3.1-flash-lite in hints", idx) + hints := svc.fetchAntigravityModelCapabilityHintsForAuth(t.Context(), auth) + if _, ok := hints.ModelIDs["allowed"]; !ok { + t.Error("missing model") } - }(i) - } - - // Deterministically verify that all callers are in-flight in singleflight before server responds - deadline := time.Now().Add(2 * time.Second) - for antigravityProbeInFlight.Load() < numCallers && time.Now().Before(deadline) { - time.Sleep(time.Millisecond) + }() } - if got := antigravityProbeInFlight.Load(); got != numCallers { - t.Fatalf("expected all %d callers in flight, got %d", numCallers, got) - } - - // Release the in-flight server response - release() + <-started + unblock() wg.Wait() - - if got := requestCount.Load(); got != 1 { - t.Fatalf("concurrent probes resulted in %d upstream requests, want exactly 1 deduplicated request", got) + if calls.Load() != 1 { + t.Fatalf("calls=%d", calls.Load()) } } -// TestAntigravityCapabilityProbe_CachedWithinTTL verifies that capability probe results -// are cached and repeated probes within the 5-minute TTL do not hit upstream network. -func TestAntigravityCapabilityProbe_CachedWithinTTL(t *testing.T) { - var requestCount atomic.Int32 - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - requestCount.Add(1) - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(`{"webSearchModelIds":["gemini-3.1-flash-lite"]}`)) - })) - t.Cleanup(func() { - server.CloseClientConnections() - server.Close() - }) - - svc := &Service{ - cfg: &config.Config{}, - } - - auth1 := &coreauth.Auth{ - ID: "test-ag-cache-1", - Provider: "antigravity", - Attributes: map[string]string{ - "base_url": server.URL, - }, - Metadata: map[string]any{ - "access_token": "ya29.test-token-1", - }, - } - - // First probe hits upstream - hints1 := svc.fetchAntigravityModelCapabilityHintsForAuth(context.Background(), auth1) - if _, ok := hints1.WebSearchModelIDs["gemini-3.1-flash-lite"]; !ok { - t.Fatalf("first probe: expected gemini-3.1-flash-lite in hints") - } - if got := requestCount.Load(); got != 1 { - t.Fatalf("first probe resulted in %d upstream requests, want 1", got) - } - - // Second probe for another account with same base URL within TTL must be served from cache - auth2 := &coreauth.Auth{ - ID: "test-ag-cache-2", - Provider: "antigravity", - Attributes: map[string]string{ - "base_url": server.URL, - }, - Metadata: map[string]any{ - "access_token": "ya29.test-token-2", - }, - } - - hints2 := svc.fetchAntigravityModelCapabilityHintsForAuth(context.Background(), auth2) - if _, ok := hints2.WebSearchModelIDs["gemini-3.1-flash-lite"]; !ok { - t.Fatalf("second probe: expected gemini-3.1-flash-lite in hints") - } - if got := requestCount.Load(); got != 1 { - t.Fatalf("second probe hit upstream; total requests = %d, want 1 (served from cache)", got) - } -} - -// TestAntigravityCapabilityProbe_CacheExpiresAfterTTL verifies that cached capability probe -// results expire after the 5-minute TTL, triggering a new upstream fetch. -func TestAntigravityCapabilityProbe_CacheExpiresAfterTTL(t *testing.T) { +func TestAntigravityCapabilityProbe_AccountAndProjectIsolation(t *testing.T) { resetAntigravityCapabilityCache() t.Cleanup(resetAntigravityCapabilityCache) - - simulatedTime := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC) - antigravityNowFunc = func() time.Time { return simulatedTime } - t.Cleanup(func() { antigravityNowFunc = time.Now }) - - var requestCount atomic.Int32 + var calls atomic.Int32 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - requestCount.Add(1) - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(`{"webSearchModelIds":["gemini-3.1-flash-lite"]}`)) + calls.Add(1) + if r.URL.Path != antigravityModelsPath { + t.Errorf("path=%s", r.URL.Path) + } + var body map[string]string + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Error(err) + } + id := body["project"] + _ = json.NewEncoder(w).Encode(map[string]any{"models": map[string]any{id: map[string]any{}}}) })) - t.Cleanup(func() { - server.CloseClientConnections() - server.Close() - }) - + defer server.Close() svc := &Service{cfg: &config.Config{}} - auth := &coreauth.Auth{ - ID: "test-ag-ttl", - Provider: "antigravity", - Attributes: map[string]string{ - "base_url": server.URL, - }, - Metadata: map[string]any{ - "access_token": "ya29.test", - }, + a, b := antigravityTestAuth("a", server.URL), antigravityTestAuth("b", server.URL) + for _, auth := range []*coreauth.Auth{a, b, a, b} { + hints := svc.fetchAntigravityModelCapabilityHintsForAuth(t.Context(), auth) + if len(hints.ModelIDs) != 1 { + t.Fatalf("hints=%v", hints) + } + if _, ok := hints.ModelIDs[auth.Metadata["project_id"].(string)]; !ok { + t.Fatal("cross-account catalog") + } + delete(hints.ModelIDs, auth.Metadata["project_id"].(string)) } - - // 1. Initial probe hits upstream - svc.fetchAntigravityModelCapabilityHintsForAuth(context.Background(), auth) - if requestCount.Load() != 1 { - t.Fatalf("first probe requests = %d, want 1", requestCount.Load()) + if calls.Load() != 2 { + t.Fatalf("calls=%d", calls.Load()) } - - // 2. Advance clock by 4 minutes (still within 5m TTL) -> served from cache - simulatedTime = simulatedTime.Add(4 * time.Minute) - svc.fetchAntigravityModelCapabilityHintsForAuth(context.Background(), auth) - if requestCount.Load() != 1 { - t.Fatalf("probe at 4m requests = %d, want 1 (cached)", requestCount.Load()) + a.Metadata["access_token"] = "rotated" + svc.fetchAntigravityModelCapabilityHintsForAuth(t.Context(), a) + if calls.Load() != 2 { + t.Fatal("token rotation invalidated successful catalog") } - - // 3. Advance clock past 5-minute TTL -> fetches from upstream again - simulatedTime = simulatedTime.Add(1*time.Minute + time.Second) - svc.fetchAntigravityModelCapabilityHintsForAuth(context.Background(), auth) - if requestCount.Load() != 2 { - t.Fatalf("probe after TTL expiry requests = %d, want 2", requestCount.Load()) + a.Metadata["project_id"] = "changed" + svc.fetchAntigravityModelCapabilityHintsForAuth(t.Context(), a) + if calls.Load() != 3 { + t.Fatal("project change reused catalog") } } -// TestAntigravityCapabilityProbe_CachesEmptyWebSearchModelIDs verifies that valid upstream -// responses with empty WebSearchModelIDs are cached for the full 5-minute TTL. -func TestAntigravityCapabilityProbe_CachesEmptyWebSearchModelIDs(t *testing.T) { +func TestAntigravityCapabilityProbe_TTLAndStaleOnError(t *testing.T) { resetAntigravityCapabilityCache() t.Cleanup(resetAntigravityCapabilityCache) - - simulatedTime := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC) - antigravityNowFunc = func() time.Time { return simulatedTime } + now := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + antigravityNowFunc = func() time.Time { return now } t.Cleanup(func() { antigravityNowFunc = time.Now }) - - var requestCount atomic.Int32 + var calls atomic.Int32 + var status atomic.Int32 + status.Store(200) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - requestCount.Add(1) - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(`{"webSearchModelIds":[]}`)) + calls.Add(1) + w.WriteHeader(int(status.Load())) + _, _ = w.Write([]byte(`{"models":{"allowed":{}}}`)) })) - t.Cleanup(func() { - server.CloseClientConnections() - server.Close() - }) - + defer server.Close() svc := &Service{cfg: &config.Config{}} - auth1 := &coreauth.Auth{ - ID: "test-ag-empty-1", - Provider: "antigravity", - Attributes: map[string]string{"base_url": server.URL}, - Metadata: map[string]any{"access_token": "ya29.test-1"}, - } - - // First probe: hits upstream, returns empty hints - hints1 := svc.fetchAntigravityModelCapabilityHintsForAuth(context.Background(), auth1) - if len(hints1.WebSearchModelIDs) != 0 { - t.Fatalf("expected empty hints, got %v", hints1) - } - if got := requestCount.Load(); got != 1 { - t.Fatalf("first probe requests = %d, want 1", got) - } - - // Second probe for another account 3 minutes later: must be served from cache - simulatedTime = simulatedTime.Add(3 * time.Minute) - auth2 := &coreauth.Auth{ - ID: "test-ag-empty-2", - Provider: "antigravity", - Attributes: map[string]string{"base_url": server.URL}, - Metadata: map[string]any{"access_token": "ya29.test-2"}, - } - hints2 := svc.fetchAntigravityModelCapabilityHintsForAuth(context.Background(), auth2) - if len(hints2.WebSearchModelIDs) != 0 { - t.Fatalf("expected empty hints, got %v", hints2) - } - if got := requestCount.Load(); got != 1 { - t.Fatalf("second probe hit upstream; total requests = %d, want 1 (served from cache)", got) + auth := antigravityTestAuth("ttl", server.URL) + svc.fetchAntigravityModelCapabilityHintsForAuth(t.Context(), auth) + now = now.Add(antigravityCapabilityCacheTTL - time.Second) + svc.fetchAntigravityModelCapabilityHintsForAuth(t.Context(), auth) + if calls.Load() != 1 { + t.Fatal("expired too early") + } + now = now.Add(time.Second) + status.Store(500) + hints := svc.fetchAntigravityModelCapabilityHintsForAuth(t.Context(), auth) + if _, ok := hints.ModelIDs["allowed"]; !ok { + t.Fatal("lost last successful catalog") + } + svc.fetchAntigravityModelCapabilityHintsForAuth(t.Context(), auth) + if calls.Load() != 2 { + t.Fatal("failure not throttled") + } + now = now.Add(2 * antigravityCapabilityRetryBase) + status.Store(200) + svc.fetchAntigravityModelCapabilityHintsForAuth(t.Context(), auth) + if calls.Load() != 3 { + t.Fatal("did not retry") } } -// TestAntigravityCapabilityProbe_CachesFailureWithBackoff verifies that failed upstream probes -// (e.g. 500 error) are cached with failure backoff TTL (1 minute) to avoid spamming upstream. -func TestAntigravityCapabilityProbe_CachesFailureWithBackoff(t *testing.T) { - resetAntigravityCapabilityCache() - t.Cleanup(resetAntigravityCapabilityCache) - - simulatedTime := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC) - antigravityNowFunc = func() time.Time { return simulatedTime } - t.Cleanup(func() { antigravityNowFunc = time.Now }) - - var requestCount atomic.Int32 - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - requestCount.Add(1) - w.WriteHeader(http.StatusInternalServerError) - })) - t.Cleanup(func() { - server.CloseClientConnections() - server.Close() - }) - - svc := &Service{cfg: &config.Config{}} - auth1 := &coreauth.Auth{ - ID: "test-ag-fail-1", - Provider: "antigravity", - Attributes: map[string]string{"base_url": server.URL}, - Metadata: map[string]any{"access_token": "ya29.test-1"}, - } - - // First probe: fails with 500 - hints1 := svc.fetchAntigravityModelCapabilityHintsForAuth(context.Background(), auth1) - if len(hints1.WebSearchModelIDs) != 0 { - t.Fatalf("expected empty hints on error, got %v", hints1) - } - if got := requestCount.Load(); got != 1 { - t.Fatalf("first probe requests = %d, want 1", got) - } - - // Second probe for another account 30 seconds later (within 1m failure TTL): served from failure cache - simulatedTime = simulatedTime.Add(30 * time.Second) - auth2 := &coreauth.Auth{ - ID: "test-ag-fail-2", - Provider: "antigravity", - Attributes: map[string]string{"base_url": server.URL}, - Metadata: map[string]any{"access_token": "ya29.test-2"}, - } - hints2 := svc.fetchAntigravityModelCapabilityHintsForAuth(context.Background(), auth2) - if len(hints2.WebSearchModelIDs) != 0 { - t.Fatalf("expected empty hints on error, got %v", hints2) - } - if got := requestCount.Load(); got != 1 { - t.Fatalf("second probe during failure backoff hit upstream; total requests = %d, want 1", got) - } - - // Third probe after failure TTL (61 seconds): retries upstream - simulatedTime = simulatedTime.Add(31 * time.Second) - hints3 := svc.fetchAntigravityModelCapabilityHintsForAuth(context.Background(), auth2) - if len(hints3.WebSearchModelIDs) != 0 { - t.Fatalf("expected empty hints on error, got %v", hints3) - } - if got := requestCount.Load(); got != 2 { - t.Fatalf("probe after failure TTL expired requests = %d, want 2", got) - } -} - -// TestAntigravityCapabilityProbe_InvalidJSONHandledAsFailure verifies that malformed JSON -// responses are treated as failures (with failure TTL) rather than successful 5-minute caches. -func TestAntigravityCapabilityProbe_InvalidJSONHandledAsFailure(t *testing.T) { - resetAntigravityCapabilityCache() - t.Cleanup(resetAntigravityCapabilityCache) - - simulatedTime := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC) - antigravityNowFunc = func() time.Time { return simulatedTime } - t.Cleanup(func() { antigravityNowFunc = time.Now }) - - var requestCount atomic.Int32 - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - requestCount.Add(1) - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(`{not-valid-json`)) - })) - t.Cleanup(func() { - server.CloseClientConnections() - server.Close() - }) - - svc := &Service{cfg: &config.Config{}} - auth := &coreauth.Auth{ - ID: "test-ag-badjson", - Provider: "antigravity", - Attributes: map[string]string{"base_url": server.URL}, - Metadata: map[string]any{"access_token": "ya29.test"}, - } - - // First probe: malformed JSON - hints := svc.fetchAntigravityModelCapabilityHintsForAuth(context.Background(), auth) - if len(hints.WebSearchModelIDs) != 0 { - t.Fatalf("expected empty hints on bad JSON, got %v", hints) - } - if requestCount.Load() != 1 { - t.Fatalf("requestCount = %d, want 1", requestCount.Load()) - } - - // Advance past 1 minute failure TTL (e.g. 70s) -> should retry upstream - simulatedTime = simulatedTime.Add(70 * time.Second) - svc.fetchAntigravityModelCapabilityHintsForAuth(context.Background(), auth) - if requestCount.Load() != 2 { - t.Fatalf("requestCount after failure TTL = %d, want 2 (retried)", requestCount.Load()) +func TestAntigravityCapabilityProbe_FailuresAreAccountScoped(t *testing.T) { + for _, status := range []int{401, 403, 429, 500} { + t.Run(fmt.Sprint(status), func(t *testing.T) { + resetAntigravityCapabilityCache() + t.Cleanup(resetAntigravityCapabilityCache) + var calls atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + if r.Header.Get("Authorization") == "Bearer token-bad" { + w.WriteHeader(status) + return + } + _, _ = w.Write([]byte(`{"models":{"allowed":{}}}`)) + })) + defer server.Close() + svc := &Service{cfg: &config.Config{}} + bad := antigravityTestAuth("bad", server.URL) + good := antigravityTestAuth("good", server.URL) + if hints := svc.fetchAntigravityModelCapabilityHintsForAuth(t.Context(), bad); hints.ModelIDs != nil { + t.Fatal("error treated as empty catalog") + } + svc.fetchAntigravityModelCapabilityHintsForAuth(t.Context(), bad) + if hints := svc.fetchAntigravityModelCapabilityHintsForAuth(t.Context(), good); len(hints.ModelIDs) != 1 { + t.Fatal("good account blocked") + } + if calls.Load() != 2 { + t.Fatalf("calls=%d", calls.Load()) + } + bad.Metadata["access_token"] = "refreshed" + if hints := svc.fetchAntigravityModelCapabilityHintsForAuth(t.Context(), bad); len(hints.ModelIDs) != 1 { + t.Fatal("new token blocked") + } + }) } } -// TestAntigravityCapabilityProbe_AuthErrorDoesNotPoisonCache verifies that 401 Unauthorized -// from an expired account token does not poison the shared endpoint cache, allowing another -// account with valid credentials to probe successfully. -func TestAntigravityCapabilityProbe_AuthErrorDoesNotPoisonCache(t *testing.T) { - resetAntigravityCapabilityCache() - t.Cleanup(resetAntigravityCapabilityCache) - - var requestCount atomic.Int32 - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - requestCount.Add(1) - authHeader := r.Header.Get("Authorization") - if authHeader == "Bearer ya29.bad-token" { - w.WriteHeader(http.StatusUnauthorized) - _, _ = w.Write([]byte(`{"error":"unauthorized"}`)) - return +func TestAntigravityCapabilityParsing(t *testing.T) { + for _, tc := range []struct { + body string + valid, known bool + count int + }{ + {`{"models":{"known":{"quotaInfo":{"remainingFraction":0}}}}`, true, true, 1}, + {`{"models":{}}`, true, true, 0}, + {`{"webSearchModelIds":[]}`, true, false, 0}, + {`{"models":null}`, true, false, 0}, + {`{"models":[]}`, false, false, 0}, + {`{"models":`, false, false, 0}, + } { + hints, ok := parseAntigravityModelCapabilityHints([]byte(tc.body)) + if ok != tc.valid || (hints.ModelIDs != nil) != tc.known || len(hints.ModelIDs) != tc.count { + t.Fatalf("body=%s hints=%v valid=%v", tc.body, hints, ok) } - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(`{"webSearchModelIds":["gemini-3.1-flash-lite"]}`)) - })) - t.Cleanup(func() { - server.CloseClientConnections() - server.Close() - }) - - svc := &Service{cfg: &config.Config{}} - - badAuth := &coreauth.Auth{ - ID: "test-ag-bad", - Provider: "antigravity", - Attributes: map[string]string{"base_url": server.URL}, - Metadata: map[string]any{"access_token": "ya29.bad-token"}, - } - - // 1. Account with bad token fails with 401 - hintsBad := svc.fetchAntigravityModelCapabilityHintsForAuth(context.Background(), badAuth) - if len(hintsBad.WebSearchModelIDs) != 0 { - t.Fatalf("expected empty hints on 401, got %v", hintsBad) - } - if requestCount.Load() != 1 { - t.Fatalf("requestCount after 401 = %d, want 1", requestCount.Load()) - } - - // 2. Another account with good token immediately probes the same endpoint - // It must NOT be blocked by any failure cache and should probe successfully. - goodAuth := &coreauth.Auth{ - ID: "test-ag-good", - Provider: "antigravity", - Attributes: map[string]string{"base_url": server.URL}, - Metadata: map[string]any{"access_token": "ya29.good-token"}, - } - - hintsGood := svc.fetchAntigravityModelCapabilityHintsForAuth(context.Background(), goodAuth) - if _, ok := hintsGood.WebSearchModelIDs["gemini-3.1-flash-lite"]; !ok { - t.Fatalf("good account failed to get hints: %v", hintsGood) - } - if requestCount.Load() != 2 { - t.Fatalf("good account requestCount = %d, want 2", requestCount.Load()) - } - - // 3. Bad account tries again within failure TTL -> throttled by auth failure cache - hintsBadAgain := svc.fetchAntigravityModelCapabilityHintsForAuth(context.Background(), badAuth) - if len(hintsBadAgain.WebSearchModelIDs) != 0 { - t.Fatalf("expected empty hints for repeated bad auth, got %v", hintsBadAgain) - } - if requestCount.Load() != 2 { - t.Fatalf("repeated bad auth probe hit upstream; total requests = %d, want 2 (throttled)", requestCount.Load()) } } -// TestAntigravityCapabilityProbe_ConcurrentAuthErrorDoesNotBlockHealthyAccount verifies that -// if caller 1 has an invalid token (401) and caller 2 has a valid token, caller 2 detects that -// the shared probe failed due to caller 1's token and retries with its own token, succeeding. -func TestAntigravityCapabilityProbe_ConcurrentAuthErrorDoesNotBlockHealthyAccount(t *testing.T) { +func TestAntigravityCapabilityProbe_CancelledDoesNotCacheFailure(t *testing.T) { resetAntigravityCapabilityCache() t.Cleanup(resetAntigravityCapabilityCache) - - var requestCount atomic.Int32 - request1Started := make(chan struct{}) - releaseRequest1 := make(chan struct{}) - var release1Once sync.Once - release1 := func() { release1Once.Do(func() { close(releaseRequest1) }) } - defer release1() - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - idx := requestCount.Add(1) - authHeader := r.Header.Get("Authorization") - if idx == 1 { - close(request1Started) - <-releaseRequest1 - if authHeader != "Bearer ya29.bad-token" { - t.Errorf("request 1 auth = %q, want ya29.bad-token", authHeader) - } - w.WriteHeader(http.StatusUnauthorized) - _, _ = w.Write([]byte(`{"error":"unauthorized"}`)) - return - } - if authHeader != "Bearer ya29.good-token" { - t.Errorf("request 2 auth = %q, want ya29.good-token", authHeader) - } - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(`{"webSearchModelIds":["gemini-3.1-flash-lite"]}`)) - })) - t.Cleanup(func() { - release1() - server.CloseClientConnections() - server.Close() - }) - svc := &Service{cfg: &config.Config{}} - - badAuth := &coreauth.Auth{ - ID: "test-ag-bad-concurrent", - Provider: "antigravity", - Attributes: map[string]string{"base_url": server.URL}, - Metadata: map[string]any{"access_token": "ya29.bad-token"}, - } - goodAuth := &coreauth.Auth{ - ID: "test-ag-good-concurrent", - Provider: "antigravity", - Attributes: map[string]string{"base_url": server.URL}, - Metadata: map[string]any{"access_token": "ya29.good-token"}, - } - - var hintsBad, hintsGood antigravityModelCapabilityHints - var wg sync.WaitGroup - wg.Add(2) - - go func() { - defer wg.Done() - hintsBad = svc.fetchAntigravityModelCapabilityHintsForAuth(context.Background(), badAuth) - }() - - <-request1Started - - go func() { - defer wg.Done() - hintsGood = svc.fetchAntigravityModelCapabilityHintsForAuth(context.Background(), goodAuth) - }() - - deadline := time.Now().Add(2 * time.Second) - for antigravityProbeInFlight.Load() < 2 && time.Now().Before(deadline) { - time.Sleep(time.Millisecond) - } - if got := antigravityProbeInFlight.Load(); got != 2 { - t.Fatalf("expected both callers in flight, got %d", got) - } - - release1() - wg.Wait() - - if len(hintsBad.WebSearchModelIDs) != 0 { - t.Fatalf("expected bad account to have empty hints, got %v", hintsBad) - } - if _, ok := hintsGood.WebSearchModelIDs["gemini-3.1-flash-lite"]; !ok { - t.Fatalf("expected good account to recover and obtain capabilities, got %v", hintsGood) - } - if got := requestCount.Load(); got != 2 { - t.Fatalf("requestCount = %d, want 2", got) + ctx, cancel := context.WithCancel(t.Context()) + cancel() + svc.fetchAntigravityModelCapabilityHintsForAuth(ctx, antigravityTestAuth("cancelled", "http://127.0.0.1:1")) + if len(antigravityCapabilityCache) != 0 || len(antigravityAuthFailureCache) != 0 { + t.Fatal("cancellation cached") } } diff --git a/sdk/cliproxy/antigravity_models_fencing_test.go b/sdk/cliproxy/antigravity_models_fencing_test.go new file mode 100644 index 00000000000..f09daa12cb0 --- /dev/null +++ b/sdk/cliproxy/antigravity_models_fencing_test.go @@ -0,0 +1,159 @@ +package cliproxy + +import ( + "context" + "net/http" + "net/http/httptest" + "sync" + "sync/atomic" + "testing" + "time" + + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" +) + +func TestAntigravityProbeFencesOlderTokenResult(t *testing.T) { + resetAntigravityCapabilityCache() + t.Cleanup(resetAntigravityCapabilityCache) + started, release := make(chan struct{}), make(chan struct{}) + var once sync.Once + unblock := func() { once.Do(func() { close(release) }) } + defer unblock() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") == "Bearer old" { + close(started) + <-release + _, _ = w.Write([]byte(`{"models":{"old":{}}}`)) + return + } + _, _ = w.Write([]byte(`{"models":{"new":{}}}`)) + })) + t.Cleanup(func() { unblock(); server.Close() }) + svc := &Service{cfg: &config.Config{}} + auth := antigravityTestAuth("fenced", server.URL) + auth.Metadata["access_token"] = "old" + done := make(chan struct{}) + go func() { defer close(done); svc.fetchAntigravityModelCapabilityHintsForAuth(t.Context(), auth) }() + <-started + updated := auth.Clone() + updated.Metadata["access_token"] = "new" + hints := svc.fetchAntigravityModelCapabilityHintsForAuth(t.Context(), updated) + if _, ok := hints.ModelIDs["new"]; !ok { + t.Fatal("new token missing catalog") + } + unblock() + <-done + if _, ok := svc.cachedAntigravityHints(updated).ModelIDs["new"]; !ok { + t.Fatal("old completion overwrote newer cache") + } + recreated := updated.Clone() + recreated.RegistrationEpoch++ + if svc.cachedAntigravityHints(recreated).ModelIDs != nil { + t.Fatal("recreated account inherited old lifecycle cache") + } +} + +func TestAntigravityNonAuthoritativeResponsePreservesSuccess(t *testing.T) { + for _, response := range []string{`{}`, `null`, `{"models":null}`, `{"webSearchModelIds":["search"]}`} { + t.Run(response, func(t *testing.T) { + resetAntigravityCapabilityCache() + t.Cleanup(resetAntigravityCapabilityCache) + var calls atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if calls.Add(1) == 1 { + _, _ = w.Write([]byte(`{"models":{"allowed":{}}}`)) + return + } + _, _ = w.Write([]byte(response)) + })) + defer server.Close() + svc := &Service{cfg: &config.Config{}} + auth := antigravityTestAuth("non-authoritative", server.URL) + svc.fetchAntigravityModelCapabilityHintsForAuth(t.Context(), auth) + key := svc.antigravityCapabilityKey(auth) + antigravityCapabilityMu.Lock() + entry := antigravityCapabilityCache[key] + entry.expiresAt = time.Time{} + antigravityCapabilityCache[key] = entry + antigravityCapabilityMu.Unlock() + hints := svc.fetchAntigravityModelCapabilityHintsForAuth(t.Context(), auth) + if _, ok := hints.ModelIDs["allowed"]; !ok { + t.Fatal("lost successful entitlement") + } + if _, ok := svc.cachedAntigravityHints(auth).ModelIDs["allowed"]; !ok { + t.Fatal("cache erased") + } + antigravityCapabilityMu.RLock() + expiry := antigravityCapabilityCache[key].expiresAt + antigravityCapabilityMu.RUnlock() + if !expiry.IsZero() { + t.Fatal("non-authoritative response renewed success TTL") + } + }) + } +} + +type antigravityObservedContext struct { + context.Context + waiting chan struct{} + once sync.Once +} + +func (c *antigravityObservedContext) Done() <-chan struct{} { + c.once.Do(func() { close(c.waiting) }) + return c.Context.Done() +} + +func TestAntigravitySingleflightFollowerCancellation(t *testing.T) { + started, release := make(chan struct{}), make(chan struct{}) + var once sync.Once + unblock := func() { once.Do(func() { close(release) }) } + defer unblock() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + close(started) + <-release + _, _ = w.Write([]byte(`{"models":{}}`)) + })) + t.Cleanup(func() { unblock(); server.Close() }) + svc := &Service{cfg: &config.Config{}} + auth := antigravityTestAuth("follower", server.URL) + leaderDone := make(chan struct{}) + go func() { defer close(leaderDone); svc.fetchAntigravityModelCapabilityHintsForAuth(t.Context(), auth) }() + <-started + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + followerCtx := &antigravityObservedContext{Context: ctx, waiting: make(chan struct{})} + done := make(chan struct{}) + go func() { defer close(done); svc.fetchAntigravityModelCapabilityHintsForAuth(followerCtx, auth) }() + <-followerCtx.waiting + cancel() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("follower ignored cancellation") + } + select { + case <-leaderDone: + t.Fatal("follower canceled leader") + default: + } + unblock() + <-leaderDone +} + +func TestAntigravityUnknownCatalogPreservesRestoredCooldown(t *testing.T) { + manager := coreauth.NewManager(nil, nil, nil) + svc := &Service{cfg: &config.Config{}, coreManager: manager} + const model = "gemini-3.1-flash-lite" + retry := time.Now().Add(time.Hour) + auth := &coreauth.Auth{ID: "unknown-cooldown", Provider: "antigravity", ModelStates: map[string]*coreauth.ModelState{model: {Unavailable: true, NextRetryAfter: retry, Status: coreauth.StatusError}}} + auth, _ = manager.Register(t.Context(), auth) + t.Cleanup(func() { GlobalModelRegistry().UnregisterClient(auth.ID) }) + svc.completeModelRegistrationForAuth(t.Context(), auth) + svc.WaitAntigravityProbes() + current, _ := manager.GetByID(auth.ID) + if state := current.ModelStates[model]; state == nil || !state.NextRetryAfter.Equal(retry) { + t.Fatal("unknown catalog erased restored cooldown") + } +} diff --git a/sdk/cliproxy/antigravity_models_publication_test.go b/sdk/cliproxy/antigravity_models_publication_test.go new file mode 100644 index 00000000000..4fff4f82d2c --- /dev/null +++ b/sdk/cliproxy/antigravity_models_publication_test.go @@ -0,0 +1,90 @@ +package cliproxy + +import ( + "testing" + "time" + + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" +) + +func TestAntigravityPublishedCacheDoesNotReconcileEmptyRegistry(t *testing.T) { + resetAntigravityCapabilityCache() + t.Cleanup(resetAntigravityCapabilityCache) + manager := coreauth.NewManager(nil, nil, nil) + svc := &Service{cfg: &config.Config{}, coreManager: manager} + const model = "gemini-3.1-flash-lite" + auth := antigravityTestAuth("publication-cooldown", "http://127.0.0.1:1") + retry := time.Now().Add(time.Hour) + auth.ModelStates = map[string]*coreauth.ModelState{model: {Unavailable: true, NextRetryAfter: retry, Status: coreauth.StatusError}} + auth, _ = manager.Register(t.Context(), auth) + t.Cleanup(func() { GlobalModelRegistry().UnregisterClient(auth.ID) }) + key := svc.antigravityCapabilityKey(auth) + hints := antigravityModelCapabilityHints{ModelIDs: map[string]struct{}{model: {}}, revision: 1} + antigravityCapabilityMu.Lock() + antigravityCapabilityCache[key] = antigravityCapabilityCacheEntry{hints: hints, probeRevision: 1, expiresAt: time.Now().Add(antigravityCapabilityCacheTTL)} + antigravityCapabilityMu.Unlock() + // Cache published, but the async publisher has not registered any model yet. + svc.reconcileRegisteredModelStates(t.Context(), auth) + current, _ := manager.GetByID(auth.ID) + if current.ModelStates[model] == nil || !current.ModelStates[model].NextRetryAfter.Equal(retry) { + t.Fatal("cache publication erased cooldown before registry publication") + } + epoch := GlobalModelRegistry().ClientRegistrationEpoch(auth.ID) + svc.applyAntigravityModelHints(t.Context(), auth, "antigravity", hints, key, auth.RegistrationEpoch, epoch) + current, _ = manager.GetByID(auth.ID) + if current.ModelStates[model] == nil || !current.ModelStates[model].NextRetryAfter.Equal(retry) { + t.Fatal("registry publication lost retained cooldown") + } +} + +func TestAntigravityRegistryPublicationFencesCacheRevision(t *testing.T) { + resetAntigravityCapabilityCache() + t.Cleanup(resetAntigravityCapabilityCache) + manager := coreauth.NewManager(nil, nil, nil) + svc := &Service{cfg: &config.Config{}, coreManager: manager} + auth := antigravityTestAuth("publication-version", "http://127.0.0.1:1") + auth, _ = manager.Register(t.Context(), auth) + t.Cleanup(func() { GlobalModelRegistry().UnregisterClient(auth.ID) }) + key := svc.antigravityCapabilityKey(auth) + epoch := GlobalModelRegistry().ClientRegistrationEpoch(auth.ID) + old := antigravityModelCapabilityHints{ModelIDs: map[string]struct{}{"gemini-3.1-flash-lite": {}}, revision: 1} + newer := antigravityModelCapabilityHints{ModelIDs: map[string]struct{}{}, revision: 2} + antigravityCapabilityMu.Lock() + antigravityCapabilityCache[key] = antigravityCapabilityCacheEntry{hints: newer, probeRevision: 2, expiresAt: time.Now().Add(antigravityCapabilityCacheTTL)} + antigravityCapabilityMu.Unlock() + // The old caller resumes after the newer cache publication, with the same registry epoch. + svc.applyAntigravityModelHints(t.Context(), auth, "antigravity", old, key, auth.RegistrationEpoch, epoch) + if GlobalModelRegistry().ClientRegistrationEpoch(auth.ID) != epoch { + t.Fatal("old hints advanced registry epoch") + } + svc.applyAntigravityModelHints(t.Context(), auth, "antigravity", newer, key, auth.RegistrationEpoch, epoch) + if len(GlobalModelRegistry().GetModelsForClient(auth.ID)) != 0 { + t.Fatal("new empty catalog not applied") + } + // A second successful catalog may lose CAS to another publisher. It must + // retry with a current auth/registry snapshot, never promote its old epoch. + newest := antigravityModelCapabilityHints{ModelIDs: map[string]struct{}{"gemini-3.1-flash-lite": {}}, revision: 3} + antigravityCapabilityMu.Lock() + entry := antigravityCapabilityCache[key] + entry.hints = newest + entry.probeRevision = 3 + antigravityCapabilityCache[key] = entry + antigravityCapabilityMu.Unlock() + svc.applyAntigravityModelHints(t.Context(), auth, "antigravity", newest, key, auth.RegistrationEpoch, epoch) + if len(GlobalModelRegistry().GetModelsForClient(auth.ID)) != 0 { + t.Fatal("stale registry epoch was promoted") + } + svc.refreshAntigravityModels(t.Context()) + svc.WaitAntigravityProbes() + if len(GlobalModelRegistry().GetModelsForClient(auth.ID)) != 1 { + t.Fatal("periodic retry failed to publish the newer cached catalog") + } + // External removal must still win over a cached publication. + publishedEpoch := GlobalModelRegistry().ClientRegistrationEpoch(auth.ID) + GlobalModelRegistry().UnregisterClient(auth.ID) + svc.applyAntigravityModelHints(t.Context(), auth, "antigravity", newest, key, auth.RegistrationEpoch, publishedEpoch) + if len(GlobalModelRegistry().GetModelsForClient(auth.ID)) != 0 { + t.Fatal("external unregister overwritten") + } +} diff --git a/sdk/cliproxy/antigravity_models_refresh_test.go b/sdk/cliproxy/antigravity_models_refresh_test.go new file mode 100644 index 00000000000..d8803441e50 --- /dev/null +++ b/sdk/cliproxy/antigravity_models_refresh_test.go @@ -0,0 +1,200 @@ +package cliproxy + +import ( + "context" + "fmt" + "io" + "net/http" + "strings" + "sync/atomic" + "testing" + "testing/synctest" + "time" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/pluginhost" + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" +) + +func TestAntigravityStalledAccountDoesNotBlockOtherRetries(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + resetAntigravityCapabilityCache() + defer resetAntigravityCapabilityCache() + svc := &Service{cfg: &config.Config{}, coreManager: coreauth.NewManager(nil, nil, nil)} + for _, id := range []string{"refresh-stall", "refresh-retry"} { + auth, errRegister := svc.coreManager.Register(t.Context(), antigravityTestAuth(id, "https://refresh.invalid")) + if errRegister != nil { + t.Fatal(errRegister) + } + defer GlobalModelRegistry().UnregisterClient(auth.ID) + } + var calls, stalledCalls atomic.Int32 + transport := http.DefaultTransport + http.DefaultTransport = antigravityReviewTransport(func(r *http.Request) (*http.Response, error) { + if strings.Contains(r.Header.Get("Authorization"), "refresh-stall") { + stalledCalls.Add(1) + <-r.Context().Done() + return nil, r.Context().Err() + } + calls.Add(1) + return &http.Response{StatusCode: http.StatusServiceUnavailable, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("")), Request: r}, nil + }) + defer func() { http.DefaultTransport = transport }() + ctx, cancel := context.WithCancel(t.Context()) + done := make(chan struct{}) + go func() { defer close(done); svc.runAntigravityModelRefresh(ctx) }() + // Synthetic time: every possible first retry deadline is within this window. + time.Sleep(10 * time.Minute) + synctest.Wait() + attempts, stalledAttempts := calls.Load(), stalledCalls.Load() + svc.antigravityProbeMu.Lock() + pending := len(svc.antigravityRefreshPending) + svc.antigravityProbeMu.Unlock() + cancel() + <-done + svc.WaitAntigravityProbes() + synctest.Wait() + if attempts < 2 { + t.Fatalf("other account never retried: calls=%d", attempts) + } + if stalledAttempts != 1 || pending != 1 { + t.Fatalf("stalled account calls=%d pending=%d, want one task", stalledAttempts, pending) + } + }) +} + +func TestAntigravityPluginRefreshDoesNotWaitForProbe(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + resetAntigravityCapabilityCache() + defer resetAntigravityCapabilityCache() + svc := &Service{cfg: &config.Config{}, coreManager: coreauth.NewManager(nil, nil, nil), pluginHost: pluginhost.New()} + auth, errRegister := svc.coreManager.Register(t.Context(), antigravityTestAuth("plugin-refresh-stall", "https://refresh.invalid")) + if errRegister != nil { + t.Fatal(errRegister) + } + defer GlobalModelRegistry().UnregisterClient(auth.ID) + started := make(chan struct{}) + transport := http.DefaultTransport + http.DefaultTransport = antigravityReviewTransport(func(r *http.Request) (*http.Response, error) { + close(started) + <-r.Context().Done() + return nil, r.Context().Err() + }) + defer func() { http.DefaultTransport = transport }() + ctx, cancel := context.WithCancel(t.Context()) + done := make(chan struct{}) + go func() { defer close(done); svc.refreshPluginModelRegistrations(ctx) }() + <-started + synctest.Wait() + completed := false + select { + case <-done: + completed = true + default: + } + cancel() + <-done + svc.WaitAntigravityProbes() + synctest.Wait() + if !completed { + t.Fatal("plugin refresh waits for an unfinished background probe") + } + }) +} + +func TestAntigravityRefreshBoundsQueuedWorkAndCancels(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + resetAntigravityCapabilityCache() + defer resetAntigravityCapabilityCache() + // Blocked semaphore operations must belong to this synthetic-time bubble. + slots := antigravityProbeSlots + antigravityProbeSlots = make(chan struct{}, cap(slots)) + defer func() { antigravityProbeSlots = slots }() + svc := &Service{cfg: &config.Config{}, coreManager: coreauth.NewManager(nil, nil, nil), pluginHost: pluginhost.New()} + svc.antigravityRefreshPluginSlots = make(chan struct{}, modelRegistrationMaxWorkersPerCategory) + for range cap(svc.antigravityRefreshPluginSlots) { + svc.antigravityRefreshPluginSlots <- struct{}{} + } + const accounts = modelRegistrationMaxWorkersPerCategory + 3 + for i := range accounts { + auth, errRegister := svc.coreManager.Register(t.Context(), antigravityTestAuth(fmt.Sprintf("queued-refresh-%d", i), "https://refresh.invalid")) + if errRegister != nil { + t.Fatal(errRegister) + } + defer GlobalModelRegistry().UnregisterClient(auth.ID) + } + var calls atomic.Int32 + transport := http.DefaultTransport + http.DefaultTransport = antigravityReviewTransport(func(r *http.Request) (*http.Response, error) { + calls.Add(1) + <-r.Context().Done() + return nil, r.Context().Err() + }) + defer func() { http.DefaultTransport = transport }() + ctx, cancel := context.WithCancel(t.Context()) + done := make(chan struct{}) + go func() { defer close(done); svc.runAntigravityModelRefresh(ctx) }() + time.Sleep(2 * time.Minute) // Synthetic time: plugin calls are waiting for admission. + synctest.Wait() + beforeAdmission := calls.Load() + <-svc.antigravityRefreshPluginSlots + time.Sleep(8 * time.Minute) // Repeated scans must not accumulate followers. + synctest.Wait() + connected := calls.Load() + svc.antigravityProbeMu.Lock() + pending := len(svc.antigravityRefreshPending) + svc.antigravityProbeMu.Unlock() + cancel() + <-done + svc.WaitAntigravityProbes() + synctest.Wait() + svc.antigravityProbeMu.Lock() + remaining := len(svc.antigravityRefreshPending) + len(svc.antigravityAccountProbes) + svc.antigravityProbeMu.Unlock() + if connected != modelRegistrationMaxWorkersPerCategory || pending != accounts { + t.Fatalf("connected=%d pending=%d, want %d and %d", connected, pending, modelRegistrationMaxWorkersPerCategory, accounts) + } + if beforeAdmission != 0 || len(svc.antigravityRefreshPluginSlots) != cap(svc.antigravityRefreshPluginSlots)-1 { + t.Fatal("plugin admission was bypassed or its slot was held during native probes") + } + if remaining != 0 || len(antigravityProbeSlots) != 0 { + t.Fatal("canceled refresh retained tasks or network slots") + } + }) +} + +func TestAntigravityShutdownCancelsServiceProbes(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + resetAntigravityCapabilityCache() + defer resetAntigravityCapabilityCache() + lifetime, cancel := context.WithCancel(t.Context()) + defer cancel() + svc := &Service{cfg: &config.Config{}, coreManager: coreauth.NewManager(nil, nil, nil), antigravityContext: lifetime, runCancel: cancel} + auth, errRegister := svc.coreManager.Register(t.Context(), antigravityTestAuth("shutdown-probe", "https://refresh.invalid")) + if errRegister != nil { + t.Fatal(errRegister) + } + defer GlobalModelRegistry().UnregisterClient(auth.ID) + started := make(chan struct{}) + transport := http.DefaultTransport + http.DefaultTransport = antigravityReviewTransport(func(r *http.Request) (*http.Response, error) { + close(started) + <-r.Context().Done() + return nil, r.Context().Err() + }) + defer func() { http.DefaultTransport = transport }() + svc.registerModelsForAuth(t.Context(), auth) + <-started + errShutdown := svc.Shutdown(t.Context()) + cancelled := lifetime.Err() != nil + cancel() + svc.WaitAntigravityProbes() + synctest.Wait() + if errShutdown != nil { + t.Fatal(errShutdown) + } + if !cancelled { + t.Fatal("shutdown did not cancel the service probe lifetime") + } + }) +} diff --git a/sdk/cliproxy/antigravity_models_registration_test.go b/sdk/cliproxy/antigravity_models_registration_test.go new file mode 100644 index 00000000000..6bf995250e4 --- /dev/null +++ b/sdk/cliproxy/antigravity_models_registration_test.go @@ -0,0 +1,208 @@ +package cliproxy + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" +) + +func TestAntigravityDynamicRegistrationLifecycle(t *testing.T) { + resetAntigravityCapabilityCache() + t.Cleanup(resetAntigravityCapabilityCache) + const allowed = "gemini-3.1-flash-lite" + var response atomic.Value + response.Store(map[string]any{"models": map[string]any{allowed: map[string]any{"maxTokens": 1}, "not-in-static": map[string]any{}}, "webSearchModelIds": []string{allowed}}) + var status atomic.Int32 + status.Store(200) + var calls atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + w.WriteHeader(int(status.Load())) + _ = json.NewEncoder(w).Encode(response.Load()) + })) + defer server.Close() + cfg := &config.Config{OAuthModelAlias: map[string][]config.OAuthModelAlias{"antigravity": {{Name: allowed, Alias: "my-model"}}}} + manager := coreauth.NewManager(nil, nil, nil) + svc := &Service{cfg: cfg, coreManager: manager} + auth := antigravityTestAuth("dynamic-account", server.URL) + auth.Prefix = "tenant" + var err error + auth, err = manager.Register(t.Context(), auth) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { GlobalModelRegistry().UnregisterClient(auth.ID) }) + svc.registerModelsForAuth(t.Context(), auth) + svc.WaitAntigravityProbes() + assertModels := func(want bool) { + t.Helper() + models := GlobalModelRegistry().GetModelsForClient(auth.ID) + if !want { + if len(models) != 0 { + t.Fatalf("expected empty catalog: %v", models) + } + return + } + if len(models) != 2 { + t.Fatalf("expected alias and prefixed alias, got %v", models) + } + for _, m := range models { + if m.ID != "my-model" && m.ID != "tenant/my-model" { + t.Fatalf("unentitled model %s", m.ID) + } + if m.ContextLength <= 1 || !m.SupportsWebSearch { + t.Fatalf("lost static info or fetched capability: %+v", m) + } + } + } + assertModels(true) + svc.refreshAntigravityModels(t.Context()) + svc.WaitAntigravityProbes() + if calls.Load() != 1 { + t.Fatal("fresh cache probed") + } + expire := func() { + key := svc.antigravityCapabilityKey(auth) + antigravityCapabilityMu.Lock() + entry := antigravityCapabilityCache[key] + entry.expiresAt = time.Time{} + antigravityCapabilityCache[key] = entry + antigravityAuthFailureCache = make(map[string]antigravityFailureState) + antigravityCapabilityMu.Unlock() + } + // Errors preserve the last successful account catalog. + expire() + status.Store(403) + svc.refreshAntigravityModels(t.Context()) + svc.WaitAntigravityProbes() + assertModels(true) + // A successful empty catalog revokes all registrations, without disabling the auth. + expire() + status.Store(200) + response.Store(map[string]any{"models": map[string]any{}}) + svc.refreshAntigravityModels(t.Context()) + svc.WaitAntigravityProbes() + assertModels(false) + current, _ := manager.GetByID(auth.ID) + if current.Disabled { + t.Fatal("empty catalog disabled credential") + } + // Registration from cache must not temporarily restore static-only models. + svc.registerModelsForAuth(t.Context(), current) + svc.WaitAntigravityProbes() + assertModels(false) + expire() + response.Store(map[string]any{"models": map[string]any{allowed: map[string]any{}}, "webSearchModelIds": []string{allowed}}) + svc.refreshAntigravityModels(t.Context()) + svc.WaitAntigravityProbes() + assertModels(true) + if len(registry.GetAntigravityModels()) < 3 { + t.Fatal("static catalog mutated") + } +} + +func TestAntigravityDynamicRegistrationExclusions(t *testing.T) { + svc := &Service{cfg: &config.Config{OAuthExcludedModels: map[string][]string{"antigravity": {"gemini-3.1-flash-lite"}}}} + auth := antigravityTestAuth("excluded", "http://127.0.0.1:1") + hints := antigravityModelCapabilityHints{ModelIDs: map[string]struct{}{"gemini-3.1-flash-lite": {}}} + if models := svc.antigravityModelsForHints(auth, hints); len(models) != 0 { + t.Fatalf("excluded models restored: %v", models) + } +} + +func TestAntigravityDynamicRegistrationBatches(t *testing.T) { + resetAntigravityCapabilityCache() + t.Cleanup(resetAntigravityCapabilityCache) + const workers = modelRegistrationMaxWorkersPerCategory + var active, peak, calls atomic.Int32 + started := make(chan struct{}, workers*2+3) + release := make(chan struct{}) + var once sync.Once + unblock := func() { once.Do(func() { close(release) }) } + defer unblock() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + current := active.Add(1) + defer active.Add(-1) + calls.Add(1) + for previous := peak.Load(); current > previous; previous = peak.Load() { + if peak.CompareAndSwap(previous, current) { + break + } + } + started <- struct{}{} + select { + case <-release: + case <-r.Context().Done(): + return + } + _, _ = w.Write([]byte(`{"models":{"gemini-3.1-flash-lite":{}}}`)) + })) + defer server.Close() + manager := coreauth.NewManager(nil, nil, nil) + svc := &Service{cfg: &config.Config{}, coreManager: manager} + for i := range workers*2 + 3 { + auth := antigravityTestAuth(fmt.Sprint("batch-", i), server.URL) + if _, err := manager.Register(t.Context(), auth); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { GlobalModelRegistry().UnregisterClient(auth.ID) }) + } + done := make(chan struct{}) + go func() { defer close(done); svc.refreshAntigravityModels(t.Context()) }() + for range workers { + <-started + } + if peak.Load() > workers { + t.Fatal("unbounded probes") + } + unblock() + <-done + svc.WaitAntigravityProbes() + if calls.Load() != workers*2+3 || peak.Load() > workers { + t.Fatalf("calls=%d peak=%d", calls.Load(), peak.Load()) + } + for _, auth := range manager.List() { + if len(GlobalModelRegistry().GetModelsForClient(auth.ID)) != 1 { + t.Fatal("batch registration incomplete") + } + } +} + +func TestAntigravityDynamicRegistrationDropsStaleFullCatalog(t *testing.T) { + resetAntigravityCapabilityCache() + t.Cleanup(resetAntigravityCapabilityCache) + started, release := make(chan struct{}), make(chan struct{}) + var once sync.Once + unblock := func() { once.Do(func() { close(release) }) } + defer unblock() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + close(started) + <-release + _, _ = w.Write([]byte(`{"models":{"gemini-3.1-flash-lite":{}}}`)) + })) + defer server.Close() + manager := coreauth.NewManager(nil, nil, nil) + svc := &Service{cfg: &config.Config{}, coreManager: manager} + auth := antigravityTestAuth("stale-full", server.URL) + auth, _ = manager.Register(t.Context(), auth) + t.Cleanup(func() { GlobalModelRegistry().UnregisterClient(auth.ID) }) + svc.registerModelsForAuth(t.Context(), auth) + <-started + GlobalModelRegistry().UnregisterClient(auth.ID) + manager.Remove(context.Background(), auth.ID) + unblock() + svc.WaitAntigravityProbes() + if len(GlobalModelRegistry().GetModelsForClient(auth.ID)) != 0 { + t.Fatal("removed credential resurrected") + } +} diff --git a/sdk/cliproxy/antigravity_models_review_test.go b/sdk/cliproxy/antigravity_models_review_test.go new file mode 100644 index 00000000000..531e6eab08c --- /dev/null +++ b/sdk/cliproxy/antigravity_models_review_test.go @@ -0,0 +1,139 @@ +package cliproxy + +import ( + "context" + "crypto/sha256" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "testing/synctest" + "time" + + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" +) + +func TestAntigravityStaleAuthCannotRestoreExcludedModel(t *testing.T) { + resetAntigravityCapabilityCache() + t.Cleanup(resetAntigravityCapabilityCache) + svc := &Service{cfg: &config.Config{}, coreManager: coreauth.NewManager(nil, nil, nil)} + auth, _ := svc.coreManager.Register(t.Context(), antigravityTestAuth("stale-auth-models", "http://127.0.0.1:1")) + t.Cleanup(func() { GlobalModelRegistry().UnregisterClient(auth.ID) }) + const model = "gemini-3.1-flash-lite" + hints := antigravityModelCapabilityHints{ModelIDs: map[string]struct{}{model: {}}, revision: 1} + key := svc.antigravityCapabilityKey(auth) + antigravityCapabilityMu.Lock() + antigravityCapabilityCache[key] = antigravityCapabilityCacheEntry{hints: hints, expiresAt: time.Now().Add(antigravityCapabilityCacheTTL)} + antigravityCapabilityMu.Unlock() + oldEpoch := GlobalModelRegistry().ClientRegistrationEpoch(auth.ID) + updated := auth.Clone() + updated.Attributes["excluded_models"] = model + updated, _ = svc.coreManager.Update(t.Context(), updated) + svc.registerModelsForAuth(t.Context(), updated) + svc.WaitAntigravityProbes() + svc.applyAntigravityModelHints(t.Context(), auth, "antigravity", hints, key, auth.RegistrationEpoch, oldEpoch) + svc.refreshAntigravityModels(t.Context()) + svc.WaitAntigravityProbes() + if len(GlobalModelRegistry().GetModelsForClient(auth.ID)) != 0 { + t.Fatal("stale publisher reinstated excluded model") + } + // Even when a stale queued task captures the new registry epoch it must not + // publish the old account-level model settings. + currentEpoch := GlobalModelRegistry().ClientRegistrationEpoch(auth.ID) + svc.applyAntigravityModelHints(t.Context(), auth, "antigravity", hints, key, auth.RegistrationEpoch, currentEpoch) + if len(GlobalModelRegistry().GetModelsForClient(auth.ID)) != 0 { + t.Fatal("stale auth accepted with current registry epoch") + } +} + +func TestAntigravityRemovedAccountsReleaseProbeSlots(t *testing.T) { + resetAntigravityCapabilityCache() + t.Cleanup(resetAntigravityCapabilityCache) + started := make(chan struct{}, modelRegistrationMaxWorkersPerCategory) + healthy := make(chan struct{}, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") == "Bearer token-healthy" { + healthy <- struct{}{} + _, _ = w.Write([]byte(`{"models":{}}`)) + return + } + w.WriteHeader(200) + w.(http.Flusher).Flush() + started <- struct{}{} + <-r.Context().Done() + })) + ctx, cancel := context.WithCancel(t.Context()) + svc := &Service{cfg: &config.Config{}, coreManager: coreauth.NewManager(nil, nil, nil)} + t.Cleanup(func() { cancel(); svc.WaitAntigravityProbes(); server.Close() }) + for i := range modelRegistrationMaxWorkersPerCategory { + auth, _ := svc.coreManager.Register(ctx, antigravityTestAuth(fmt.Sprint("removed-", i), server.URL)) + svc.registerModelsForAuth(ctx, auth) + } + for range modelRegistrationMaxWorkersPerCategory { + <-started + } + for i := range modelRegistrationMaxWorkersPerCategory { + svc.applyCoreAuthRemoval(ctx, fmt.Sprint("removed-", i)) + } + auth, _ := svc.coreManager.Register(ctx, antigravityTestAuth("healthy", server.URL)) + t.Cleanup(func() { GlobalModelRegistry().UnregisterClient(auth.ID) }) + svc.registerModelsForAuth(ctx, auth) + select { + case <-healthy: + case <-time.After(time.Second): + t.Fatal("removed accounts still occupy all probe slots") + } +} + +type antigravityReviewTransport func(*http.Request) (*http.Response, error) + +func (f antigravityReviewTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +func TestAntigravityRetrySchedulerPreservesJitterDeadlines(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + resetAntigravityCapabilityCache() + defer resetAntigravityCapabilityCache() + svc := &Service{cfg: &config.Config{}, coreManager: coreauth.NewManager(nil, nil, nil)} + start := time.Now() + type observation struct { + id string + elapsed time.Duration + } + observed := make(chan observation, 2) + transport := http.DefaultTransport + http.DefaultTransport = antigravityReviewTransport(func(r *http.Request) (*http.Response, error) { + observed <- observation{strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer token-"), time.Since(start)} + return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"models":{}}`)), Request: r}, nil + }) + defer func() { http.DefaultTransport = transport }() + deadlines := map[string]time.Duration{"early": 70 * time.Second, "late": 110 * time.Second} + for id, deadline := range deadlines { + auth, _ := svc.coreManager.Register(t.Context(), antigravityTestAuth(id, "https://daily.invalid")) + defer GlobalModelRegistry().UnregisterClient(auth.ID) + key := svc.antigravityCapabilityKey(auth) + fmt.Sprintf("/%x", sha256.Sum256([]byte("token-"+id))) + antigravityCapabilityMu.Lock() + antigravityAuthFailureCache[key] = antigravityFailureState{failures: 1, lastFailure: start, nextRetry: start.Add(deadline)} + antigravityCapabilityMu.Unlock() + } + ctx, cancel := context.WithCancel(t.Context()) + done := make(chan struct{}) + go func() { defer close(done); svc.runAntigravityModelRefresh(ctx) }() + synctest.Wait() + time.Sleep(130 * time.Second) // Synthetic time: exercise actual scheduler, not just delay arithmetic. + synctest.Wait() + cancel() + <-done + if len(observed) != 2 { + t.Fatalf("observed %d retries", len(observed)) + } + for range 2 { + got := <-observed + if got.elapsed != deadlines[got.id] { + t.Errorf("%s retried at %s, want %s", got.id, got.elapsed, deadlines[got.id]) + } + } + }) +} diff --git a/sdk/cliproxy/antigravity_models_timeout_test.go b/sdk/cliproxy/antigravity_models_timeout_test.go index cba8e137f8b..fe25493e4cf 100644 --- a/sdk/cliproxy/antigravity_models_timeout_test.go +++ b/sdk/cliproxy/antigravity_models_timeout_test.go @@ -6,7 +6,6 @@ import ( "net/http/httptest" "os" "path/filepath" - "sync" "sync/atomic" "testing" "time" @@ -16,120 +15,51 @@ import ( "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" ) -// TestAntigravityCapabilityProbe_HardTimeout verifies that fetchAntigravityModelCapabilityHintsForAuth -// enforces a hard timeout (not exceeding 5s) even when passed an unbounded background context -// and connecting to a hanging server. -func TestAntigravityCapabilityProbe_HardTimeout(t *testing.T) { - // Mock server that hangs unless client cancels +func TestAntigravityCapabilityProbe_CallerCancellation(t *testing.T) { + started := make(chan struct{}) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - if f, ok := w.(http.Flusher); ok { - f.Flush() - } - select { - case <-r.Context().Done(): - return - case <-time.After(10 * time.Second): - } - _, _ = w.Write([]byte(`{"webSearchModelIds":["gemini-2.5-flash"]}`)) + w.WriteHeader(200) + w.(http.Flusher).Flush() + close(started) + <-r.Context().Done() })) - t.Cleanup(func() { - server.CloseClientConnections() - server.Close() - }) - - svc := &Service{ - cfg: &config.Config{}, - } - - auth := &coreauth.Auth{ - ID: "test-antigravity-auth", - Provider: "antigravity", - Attributes: map[string]string{ - "base_url": server.URL, - }, - Metadata: map[string]any{ - "access_token": "ya29.test-token", - }, - } - - start := time.Now() - hints := svc.fetchAntigravityModelCapabilityHintsForAuth(context.Background(), auth) - elapsed := time.Since(start) - - // It must enforce a hard timeout <= 6 seconds instead of waiting the full 10s - if elapsed >= 8*time.Second { - t.Fatalf("fetchAntigravityModelCapabilityHintsForAuth took %v, want hard timeout <= 6s", elapsed) - } - if len(hints.WebSearchModelIDs) != 0 { - t.Fatalf("expected empty hints due to timeout, got %v", hints) - } + defer server.Close() + svc := &Service{cfg: &config.Config{}} + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + done := make(chan struct{}) + go func() { + defer close(done) + svc.fetchAntigravityModelCapabilityHintsForAuth(ctx, antigravityTestAuth("cancel", server.URL)) + }() + <-started + cancel() + <-done } -// TestAntigravityCapabilityProbe_ConcurrentBaseURLs verifies that when multiple baseURLs -// are configured and one hangs while the other responds promptly, both endpoints receive requests -// concurrently and the probe returns the fast result quickly (< 2s) without waiting for the slow one. -func TestAntigravityCapabilityProbe_ConcurrentBaseURLs(t *testing.T) { - slowStarted := make(chan struct{}) - var slowOnce sync.Once - slowServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - slowOnce.Do(func() { close(slowStarted) }) - w.WriteHeader(http.StatusOK) - if f, ok := w.(http.Flusher); ok { - f.Flush() - } - select { - case <-r.Context().Done(): - return - case <-time.After(10 * time.Second): - } +func TestAntigravityCapabilityProbe_UsesFirstConfiguredEndpoint(t *testing.T) { + var firstCalls, secondCalls atomic.Int32 + first := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + firstCalls.Add(1) + _, _ = w.Write([]byte(`{"models":{"first":{}}}`)) })) - t.Cleanup(func() { - slowServer.CloseClientConnections() - slowServer.Close() - }) - - fastServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // Wait for slowServer to have received its concurrent request or client context cancellation - select { - case <-slowStarted: - case <-r.Context().Done(): - return - } - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(`{"webSearchModelIds":["gemini-3.1-flash-lite"]}`)) + defer first.Close() + second := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + secondCalls.Add(1) + _, _ = w.Write([]byte(`{"models":{"second":{}}}`)) })) - t.Cleanup(fastServer.Close) - - svc := &Service{ - cfg: &config.Config{}, - } - - auth := &coreauth.Auth{ - ID: "test-ag-concurrent-auth", - Provider: "antigravity", - Attributes: map[string]string{ - "base_urls": slowServer.URL + "," + fastServer.URL, - }, - Metadata: map[string]any{ - "access_token": "ya29.test-token", - }, - } - - start := time.Now() - hints := svc.fetchAntigravityModelCapabilityHintsForAuth(context.Background(), auth) - elapsed := time.Since(start) - - if elapsed >= 2*time.Second { - t.Fatalf("concurrent fetch took %v, want < 2s", elapsed) - } - if _, ok := hints.WebSearchModelIDs["gemini-3.1-flash-lite"]; !ok { - t.Fatalf("expected gemini-3.1-flash-lite in hints, got %v", hints) + defer second.Close() + svc := &Service{cfg: &config.Config{}} + auth := antigravityTestAuth("route", first.URL) + auth.Attributes["base_urls"] = first.URL + "," + second.URL + hints := svc.fetchAntigravityModelCapabilityHintsForAuth(t.Context(), auth) + if _, ok := hints.ModelIDs["first"]; !ok || firstCalls.Load() != 1 || secondCalls.Load() != 0 { + t.Fatalf("hints=%v first=%d second=%d", hints, firstCalls.Load(), secondCalls.Load()) } } // TestAntigravityModelRegistration_AsyncNonBlocking verifies that registerModelsForAuth -// returns immediately (< 500ms) with baseline models and does not block on a hanging capability probe. +// returns immediately without exposing unverified models and does not block on the probe. func TestAntigravityModelRegistration_AsyncNonBlocking(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { select { @@ -161,8 +91,10 @@ func TestAntigravityModelRegistration_AsyncNonBlocking(t *testing.T) { GlobalModelRegistry().UnregisterClient(auth.ID) }) + ctx, cancel := context.WithCancel(t.Context()) + defer func() { cancel(); svc.WaitAntigravityProbes() }() start := time.Now() - svc.registerModelsForAuth(context.Background(), auth) + svc.registerModelsForAuth(ctx, auth) elapsed := time.Since(start) if elapsed >= 500*time.Millisecond { @@ -170,8 +102,8 @@ func TestAntigravityModelRegistration_AsyncNonBlocking(t *testing.T) { } models := GlobalModelRegistry().GetModelsForClient(auth.ID) - if len(models) == 0 { - t.Fatal("expected baseline models to be registered immediately") + if len(models) != 0 { + t.Fatal("unverified models registered before probe completed") } } @@ -461,7 +393,7 @@ func TestAntigravityAsyncProbe_NormalRequestsDoNotDiscardProbe(t *testing.T) { close(probeStarted) <-releaseProbe w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(`{"webSearchModelIds":["gemini-3.1-flash-lite"]}`)) + _, _ = w.Write([]byte(`{"models":{"gemini-3.1-flash-lite":{}},"webSearchModelIds":["gemini-3.1-flash-lite"]}`)) })) t.Cleanup(func() { server.CloseClientConnections() diff --git a/sdk/cliproxy/auth/auth_change_watch.go b/sdk/cliproxy/auth/auth_change_watch.go new file mode 100644 index 00000000000..5659fa0c9bf --- /dev/null +++ b/sdk/cliproxy/auth/auth_change_watch.go @@ -0,0 +1,46 @@ +package auth + +// WatchAuthChanges observes structural changes to one runtime credential, +// including token preparation/refresh, replacement, removal and store reload. +// Notifications are coalesced: consumers must inspect the latest manager state. +// The caller must unsubscribe when its work ends. Request result accounting does +// not notify watchers, so ordinary Generation increments do not invalidate work. +func (m *Manager) WatchAuthChanges(authID string) (<-chan struct{}, func()) { + changes := make(chan struct{}, 1) + if m == nil || authID == "" { + close(changes) + return changes, func() {} + } + m.mu.Lock() + if m.authChangeWatchers == nil { + m.authChangeWatchers = make(map[string]map[chan struct{}]struct{}) + } + if m.authChangeWatchers[authID] == nil { + m.authChangeWatchers[authID] = make(map[chan struct{}]struct{}) + } + m.authChangeWatchers[authID][changes] = struct{}{} + m.mu.Unlock() + return changes, func() { + m.mu.Lock() + defer m.mu.Unlock() + watchers := m.authChangeWatchers[authID] + if _, exists := watchers[changes]; !exists { + return + } + delete(watchers, changes) + if len(watchers) == 0 { + delete(m.authChangeWatchers, authID) + } + close(changes) + } +} + +// Caller holds m.mu. No user callback or blocking work runs under the manager lock. +func (m *Manager) notifyAuthChangeLocked(authID string) { + for changes := range m.authChangeWatchers[authID] { + select { + case changes <- struct{}{}: + default: + } + } +} diff --git a/sdk/cliproxy/auth/auth_change_watch_test.go b/sdk/cliproxy/auth/auth_change_watch_test.go new file mode 100644 index 00000000000..9597dddee79 --- /dev/null +++ b/sdk/cliproxy/auth/auth_change_watch_test.go @@ -0,0 +1,79 @@ +package auth + +import "testing" + +func TestAuthChangeWatchCoversNativeMutationsAndReload(t *testing.T) { + store := newMemoryAuthTestStore() + manager := NewManager(store, nil, nil) + changes, stop := manager.WatchAuthChanges("watched") + defer stop() + other, stopOther := manager.WatchAuthChanges("other") + defer stopOther() + assertChanged := func() { + t.Helper() + select { + case <-changes: + default: + t.Fatal("native mutation did not notify watcher") + } + select { + case <-other: + t.Fatal("unrelated watcher notified") + default: + } + } + auth, err := manager.Register(t.Context(), &Auth{ID: "watched", Provider: "antigravity", Metadata: map[string]any{"access_token": "initial"}}) + if err != nil { + t.Fatal(err) + } + assertChanged() + for _, mode := range []string{"refresh", "prepare", "replace"} { + next := auth.Clone() + next.Metadata["access_token"] = mode + switch mode { + case "refresh": + auth, err = manager.UpdateRefreshedAuth(t.Context(), auth, next) + case "prepare": + auth, err = manager.UpdatePreparedAuth(t.Context(), auth, next) + default: + auth, err = manager.Update(t.Context(), next) + } + if err != nil { + t.Fatal(err) + } + assertChanged() + } + // Slow subscribers never block manager mutations and receive a coalesced hint. + for range 100 { + auth, err = manager.Update(t.Context(), auth) + if err != nil { + t.Fatal(err) + } + } + if len(changes) != 1 { + t.Fatalf("queued %d events, want coalesced notification", len(changes)) + } + assertChanged() + manager.Remove(t.Context(), auth.ID) + assertChanged() + // Reload invalidates all subscribed snapshots, including currently absent IDs. + if err = manager.Load(t.Context()); err != nil { + t.Fatal(err) + } + select { + case <-changes: + default: + t.Fatal("reload did not invalidate watcher") + } + stop() + stop() + if _, open := <-changes; open { + t.Fatal("unsubscribe did not close watcher") + } + manager.mu.RLock() + _, retained := manager.authChangeWatchers["watched"] + manager.mu.RUnlock() + if retained { + t.Fatal("watcher retained after unsubscribe") + } +} diff --git a/sdk/cliproxy/auth/conductor.go b/sdk/cliproxy/auth/conductor.go index 9c12c710192..050da3295e6 100644 --- a/sdk/cliproxy/auth/conductor.go +++ b/sdk/cliproxy/auth/conductor.go @@ -158,6 +158,7 @@ type Manager struct { syncedVersion atomic.Uint64 auths map[string]*Auth authEpochs map[string]uint64 + authChangeWatchers map[string]map[chan struct{}]struct{} scheduler *authScheduler // pluginScheduler runs outside m.mu before falling back to native selection. pluginScheduler PluginScheduler diff --git a/sdk/cliproxy/auth/conductor_lifecycle.go b/sdk/cliproxy/auth/conductor_lifecycle.go index 6ce03dc3d67..3fa801b2665 100644 --- a/sdk/cliproxy/auth/conductor_lifecycle.go +++ b/sdk/cliproxy/auth/conductor_lifecycle.go @@ -116,6 +116,7 @@ func (m *Manager) Register(ctx context.Context, auth *Auth) (*Auth, error) { auth.Generation = 1 authClone := auth.Clone() m.auths[auth.ID] = authClone + m.notifyAuthChangeLocked(auth.ID) // Snapshot before unlocking: MarkResult mutates the published auth in place. var schedulerSnapshot *Auth if m.scheduler != nil { @@ -271,6 +272,7 @@ func (m *Manager) updateInternal(ctx context.Context, base, auth *Auth, mode upd } authClone := auth.Clone() m.auths[auth.ID] = authClone + m.notifyAuthChangeLocked(auth.ID) // Snapshot before unlocking: MarkResult mutates the published auth in place. var schedulerSnapshot *Auth if m.scheduler != nil { @@ -319,6 +321,7 @@ func (m *Manager) Remove(ctx context.Context, id string) { } provider := strings.TrimSpace(existing.Provider) delete(m.auths, id) + m.notifyAuthChangeLocked(id) if m.modelPoolOffsets != nil { delete(m.modelPoolOffsets, id) } @@ -423,6 +426,9 @@ func (m *Manager) Load(ctx context.Context) error { cfg = &internalconfig.Config{} } m.rebuildAPIKeyModelAliasLocked(cfg) + for id := range m.authChangeWatchers { + m.notifyAuthChangeLocked(id) + } m.mu.Unlock() if m.scheduler != nil { diff --git a/sdk/cliproxy/service.go b/sdk/cliproxy/service.go index a8d9603ab99..44428b24dca 100644 --- a/sdk/cliproxy/service.go +++ b/sdk/cliproxy/service.go @@ -132,6 +132,16 @@ type Service struct { homePluginSyncFetch func(context.Context, sdkpluginstore.PluginSyncRequest) (sdkpluginstore.PluginSyncResponse, error) homePluginDeleteTask func(context.Context, *config.Config, home.PluginTask) homeplugins.SyncReport antigravityProbeWg sync.WaitGroup + // antigravityContext is protected by cfgMu and owns background model probes. + antigravityContext context.Context + antigravityProbeMu sync.Mutex + antigravityAccountProbes map[string]map[*antigravityAccountProbe]struct{} + antigravityRefreshWake chan struct{} + // antigravityRefreshPending is protected by antigravityProbeMu and bounds + // periodic refresh work to one queued or running task per account. + antigravityRefreshPending map[string]struct{} + // Plugin queries have their own bound; native HTTP must not hold these slots. + antigravityRefreshPluginSlots chan struct{} } // SetResultPolicy sets an execution result policy on the underlying core auth manager. diff --git a/sdk/cliproxy/service_auth.go b/sdk/cliproxy/service_auth.go index c2b4f73550c..a4b6be1ff8c 100644 --- a/sdk/cliproxy/service_auth.go +++ b/sdk/cliproxy/service_auth.go @@ -387,6 +387,7 @@ func (s *Service) prepareCoreAuthForModelRegistration(ctx context.Context, auth } auth = current } + s.cancelStaleAntigravityProbes(auth.ID) return auth } @@ -506,7 +507,7 @@ func (s *Service) completeModelRegistrationForAuthWithCache(ctx context.Context, if ctx != nil && ctx.Err() != nil { return } - s.coreManager.ReconcileRegistryModelStates(ctx, auth.ID) + s.reconcileRegisteredModelStates(ctx, auth) // Refresh the scheduler entry so that the auth's supportedModelSet is rebuilt // from the now-populated global model registry. Without this, newly added auths @@ -529,6 +530,7 @@ func (s *Service) applyCoreAuthRemoval(ctx context.Context, id string) { } GlobalModelRegistry().UnregisterClient(id) s.coreManager.Remove(ctx, id) + s.cancelStaleAntigravityProbes(id) if strings.EqualFold(provider, "codex") { executor.CloseCodexWebsocketSessionsForAuthID(id, "auth_removed") } diff --git a/sdk/cliproxy/service_config.go b/sdk/cliproxy/service_config.go index 9cac9e47acc..8e3f9780033 100644 --- a/sdk/cliproxy/service_config.go +++ b/sdk/cliproxy/service_config.go @@ -117,6 +117,7 @@ func (s *Service) commitConfigUpdate(newCfg *config.Config) configCommit { s.cfgMu.Lock() s.cfg = newCfg s.cfgMu.Unlock() + s.cancelStaleAntigravityProbes("") s.configSequence++ return configCommit{cfg: newCfg, sequence: s.configSequence} } diff --git a/sdk/cliproxy/service_excluded_models_test.go b/sdk/cliproxy/service_excluded_models_test.go index 4b557881ada..86cd24f27b6 100644 --- a/sdk/cliproxy/service_excluded_models_test.go +++ b/sdk/cliproxy/service_excluded_models_test.go @@ -356,17 +356,8 @@ func TestRegisterModelsForAuth_AntigravityFetchesWebSearchCapability(t *testing. if webSearchModel.ContextLength != staticWebSearchModel.ContextLength || webSearchModel.MaxCompletionTokens != staticWebSearchModel.MaxCompletionTokens { t.Fatalf("static token limits should be preserved, got=%#v static=%#v", webSearchModel, staticWebSearchModel) } - if agentModel == nil { - t.Fatal("expected gemini-pro-agent to be registered") - } - if !agentModel.SupportsWebSearch { - t.Fatal("gemini-pro-agent should support web search") - } - if staticOnlyModel == nil { - t.Fatal("expected static-only Antigravity model to remain registered") - } - if staticOnlyModel.SupportsWebSearch { - t.Fatal("gpt-oss-120b-medium should not support web search") + if agentModel != nil || staticOnlyModel != nil { + t.Fatal("models absent from the account catalog must not be registered") } if fetchedOnlyModel != nil { t.Fatalf("fetched-only model should not be registered: %#v", fetchedOnlyModel) diff --git a/sdk/cliproxy/service_executionregistry_test.go b/sdk/cliproxy/service_executionregistry_test.go index 4f16a2d143e..baed016679f 100644 --- a/sdk/cliproxy/service_executionregistry_test.go +++ b/sdk/cliproxy/service_executionregistry_test.go @@ -20,7 +20,6 @@ import ( internalconfig "github.com/router-for-me/CLIProxyAPI/v8/internal/config" "github.com/router-for-me/CLIProxyAPI/v8/internal/home" "github.com/router-for-me/CLIProxyAPI/v8/internal/homeplugins" - "github.com/router-for-me/CLIProxyAPI/v8/internal/pluginhost" coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executionregistry" cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" @@ -648,82 +647,25 @@ func TestHomeConfigWorkerShutdownCancelsBlockedRuntimeUpdatesBeforePublish(t *te } } -func TestHomeConfigWorkerCancelsBlockedAntigravityModelRefreshBeforePublish(t *testing.T) { - modelRefreshStarted := make(chan struct{}) - releaseModelRefresh := make(chan struct{}) - var releaseModelRefreshOnce sync.Once - modelServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - close(modelRefreshStarted) - select { - case <-r.Context().Done(): - case <-releaseModelRefresh: - } - })) - t.Cleanup(modelServer.Close) - t.Cleanup(func() { releaseModelRefreshOnce.Do(func() { close(releaseModelRefresh) }) }) - - client, _ := newHomePluginTaskTestClient(t, nil, 0) - baseCfg := &config.Config{} - baseCfg.Home.Enabled = true +func TestHomeModelRegistrationSkipsAntigravityProbes(t *testing.T) { + var requests atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { requests.Add(1); w.WriteHeader(500) })) + defer server.Close() + cfg := &config.Config{} + cfg.Home.Enabled = true manager := coreauth.NewManager(nil, nil, nil) - auth := &coreauth.Auth{ - ID: "blocked-antigravity-refresh", - Provider: "antigravity", - Metadata: map[string]any{"access_token": "test-token"}, - Attributes: map[string]string{ - "base_url": modelServer.URL, - }, - } - if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil { - t.Fatal(errRegister) + auth := antigravityTestAuth("home-no-probe", server.URL) + if _, err := manager.Register(t.Context(), auth); err != nil { + t.Fatal(err) } t.Cleanup(func() { GlobalModelRegistry().UnregisterClient(auth.ID) }) - - parentCtx, cancelParent := context.WithCancel(context.Background()) - t.Cleanup(cancelParent) - homeCtx, cancelHome := context.WithCancel(parentCtx) - t.Cleanup(cancelHome) - lifetimeCtx, cancelLifetime := context.WithCancel(homeCtx) - t.Cleanup(cancelLifetime) - service := &Service{ - cfg: baseCfg, - coreManager: manager, - pluginHost: pluginhost.New(), - homeGeneration: 1, - } - queue := newHomeConfigWorkQueue() - queue.enqueue([]byte("routing:\n strategy: fill-first\n")) - ready := make(chan struct{}) - close(ready) - published := atomic.Bool{} - cancelBound := atomic.Int64{} - cancelBound.Store(int64(time.Second)) - workerDone := make(chan struct{}) - go func() { - defer close(workerDone) - service.runHomeConfigWorker(lifetimeCtx, homeCtx, 1, client, executionregistry.New(), queue, ready, &published, &cancelBound) - }() - - select { - case <-modelRefreshStarted: - case <-time.After(time.Second): - t.Fatal("Home config worker did not start Antigravity model refresh") - } - cancelLifetime() - select { - case <-workerDone: - case <-time.After(time.Second): - t.Fatal("Home config worker did not stop after model refresh cancellation") - } - if published.Load() { - t.Fatal("canceled model refresh published Home runtime") - } - service.homeMu.Lock() - publishedClient := service.homeClient - publishedRegistry := service.homeRegistry - service.homeMu.Unlock() - if publishedClient != nil || publishedRegistry != nil { - t.Fatal("canceled model refresh exposed Home runtime state") + service := &Service{cfg: cfg, coreManager: manager} + service.registerModelsForAuth(t.Context(), auth) + service.WaitAntigravityProbes() + service.refreshAntigravityModels(t.Context()) + service.WaitAntigravityProbes() + if requests.Load() != 0 { + t.Fatal("Home mode launched standalone entitlement probe") } } diff --git a/sdk/cliproxy/service_executors.go b/sdk/cliproxy/service_executors.go index c0578881c55..a1a64250e1a 100644 --- a/sdk/cliproxy/service_executors.go +++ b/sdk/cliproxy/service_executors.go @@ -512,6 +512,9 @@ func (s *Service) tryRegisterPluginModelsForAuth(ctx context.Context, a *coreaut if result.Err != nil { return true } + if s.coreManager != nil && strings.EqualFold(a.Provider, "antigravity") && !s.antigravityHomeEnabled() { + defer s.coreManager.ReconcileRegistryModelStates(ctx, a.ID) + } activeAuth := a providerKey := strings.ToLower(strings.TrimSpace(result.Provider)) if providerKey == "" { diff --git a/sdk/cliproxy/service_lifecycle.go b/sdk/cliproxy/service_lifecycle.go index 7f313edb6bf..6bf6976647d 100644 --- a/sdk/cliproxy/service_lifecycle.go +++ b/sdk/cliproxy/service_lifecycle.go @@ -37,6 +37,9 @@ func (s *Service) Run(ctx context.Context) error { ctx = context.Background() } ctx, runCancel := context.WithCancel(ctx) + s.cfgMu.Lock() + s.antigravityContext = ctx + s.cfgMu.Unlock() s.homeMu.Lock() s.runCancel = runCancel s.homeMu.Unlock() @@ -206,6 +209,9 @@ func (s *Service) Run(ctx context.Context) error { } s.registerModelRefreshCallback() + if !homeEnabled { + go s.runAntigravityModelRefresh(ctx) + } select { case <-ctx.Done(): @@ -235,6 +241,13 @@ func (s *Service) Shutdown(ctx context.Context) error { ctx = context.Background() } + s.homeMu.Lock() + runCancel := s.runCancel + s.homeMu.Unlock() + if runCancel != nil { + runCancel() + } + s.homeLifecycleMu.Lock() if supervisor := s.homeSupervisor; supervisor != nil { s.homeConfigCommitMu.Lock() diff --git a/sdk/cliproxy/service_models.go b/sdk/cliproxy/service_models.go index 1bb4b621f5f..17c1ff9db07 100644 --- a/sdk/cliproxy/service_models.go +++ b/sdk/cliproxy/service_models.go @@ -28,6 +28,7 @@ func (s *Service) registerModelsForAuthWithCache(ctx context.Context, a *coreaut if ctx.Err() != nil { return } + s.cancelStaleAntigravityProbes(a.ID) if a.Disabled { if s != nil && s.coreManager != nil { if current, ok := s.coreManager.GetByID(a.ID); ok && current != nil && !current.Disabled { @@ -111,6 +112,11 @@ func (s *Service) registerModelsForAuthWithCache(ctx context.Context, a *coreaut models = applyExcludedModels(models, excluded) case "antigravity": models = registry.GetAntigravityModels() + if !s.antigravityHomeEnabled() { + hints := s.cachedAntigravityHints(a) + models = filterAntigravityModels(models, hints) + models = applyAntigravityFetchedModelCapabilities(models, hints) + } models = applyExcludedModels(models, excluded) case "claude": models = registry.GetClaudeModels() @@ -304,6 +310,9 @@ func (s *Service) registerModelsForAuthWithCache(ctx context.Context, a *coreaut } GlobalModelRegistry().UnregisterClient(a.ID) + if provider == "antigravity" { + s.asyncProbeAntigravityCapabilities(ctx, a, key) + } } // refreshModelRegistrationForAuth re-applies the latest model registration for @@ -335,7 +344,7 @@ func (s *Service) refreshModelRegistrationForAuthWithContext(ctx context.Context s.ensureExecutorsForAuthWithContext(ctx, current, false) } s.registerModelsForAuthWithCache(ctx, current, compatCache) - s.coreManager.ReconcileRegistryModelStates(ctx, current.ID) + s.reconcileRegisteredModelStates(ctx, current) if ctx.Err() != nil { return false } @@ -355,7 +364,7 @@ func (s *Service) refreshModelRegistrationForAuthWithContext(ctx context.Context if ctx.Err() != nil { return false } - s.coreManager.ReconcileRegistryModelStates(ctx, latest.ID) + s.reconcileRegisteredModelStates(ctx, latest) s.coreManager.RefreshSchedulerEntry(current.ID) return true } diff --git a/sdk/cliproxy/service_plugins.go b/sdk/cliproxy/service_plugins.go index 383cf146cc4..df9a65a401a 100644 --- a/sdk/cliproxy/service_plugins.go +++ b/sdk/cliproxy/service_plugins.go @@ -163,8 +163,9 @@ func (s *Service) refreshPluginModelRegistrations(ctx context.Context) { if s == nil || s.pluginHost == nil || s.coreManager == nil { return } + // Native capability probes publish and refresh their scheduler entries + // asynchronously; startup and config updates must not wait for network I/O. s.registerModelsForAuthBatch(ctx, s.coreManager.List()) - s.waitAntigravityProbesContext(ctx) } func (s *Service) registerModelsForAuthBatch(ctx context.Context, auths []*coreauth.Auth) { From 9521fe29b2818d4070a3d4185e8bc19c118da31d Mon Sep 17 00:00:00 2001 From: sususu Date: Sat, 3 Oct 2026 21:40:13 +0800 Subject: [PATCH 028/142] fix(antigravity): preserve model lifecycle and cooldown state Invalidate runtime auths before unregistering models to fence concurrent refreshes. Publish cached catalogs through state-preserving conditional replacement and add lifecycle regression tests. --- sdk/cliproxy/antigravity_models.go | 4 +- .../antigravity_models_lifecycle_test.go | 153 ++++++++++++++++++ sdk/cliproxy/service_auth.go | 5 +- sdk/cliproxy/service_models.go | 21 ++- 4 files changed, 174 insertions(+), 9 deletions(-) create mode 100644 sdk/cliproxy/antigravity_models_lifecycle_test.go diff --git a/sdk/cliproxy/antigravity_models.go b/sdk/cliproxy/antigravity_models.go index d36be67b716..cc928c1cb60 100644 --- a/sdk/cliproxy/antigravity_models.go +++ b/sdk/cliproxy/antigravity_models.go @@ -397,8 +397,8 @@ func (s *Service) WaitAntigravityProbes() { s.antigravityProbeWg.Wait() } -// Native Antigravity reconciliation belongs to the fenced asynchronous registry -// publication, not cache availability. A known cache can precede its registration. +// Native Antigravity reconciliation belongs to fenced registry publication, +// whether from cache or a network refresh. Cache availability alone is not enough. func (s *Service) reconcileRegisteredModelStates(ctx context.Context, auth *coreauth.Auth) { if auth == nil || s.coreManager == nil { return diff --git a/sdk/cliproxy/antigravity_models_lifecycle_test.go b/sdk/cliproxy/antigravity_models_lifecycle_test.go new file mode 100644 index 00000000000..4bb41dd7440 --- /dev/null +++ b/sdk/cliproxy/antigravity_models_lifecycle_test.go @@ -0,0 +1,153 @@ +package cliproxy + +import ( + "context" + "net/http" + "net/http/httptest" + "sync" + "testing" + "time" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" +) + +// Manager.Remove closes executor sessions after removing the runtime auth. Use +// that boundary to verify the registry cannot expose a tombstone epoch first. +type antigravityRemovalExecutor struct { + coreauth.ProviderExecutor + onClose func() +} + +func (e *antigravityRemovalExecutor) CloseExecutionSession(string) { e.onClose() } + +func TestAntigravityRemovalInvalidatesAuthBeforeRegistry(t *testing.T) { + resetAntigravityCapabilityCache() + t.Cleanup(resetAntigravityCapabilityCache) + svc := &Service{cfg: &config.Config{}, coreManager: coreauth.NewManager(nil, nil, nil)} + auth, errRegister := svc.coreManager.Register(t.Context(), antigravityTestAuth("removal-publication", "http://127.0.0.1:1")) + if errRegister != nil { + t.Fatal(errRegister) + } + reg := registry.GetGlobalRegistry() + t.Cleanup(func() { reg.UnregisterClient(auth.ID) }) + key := svc.antigravityCapabilityKey(auth) + hints := antigravityModelCapabilityHints{ModelIDs: map[string]struct{}{"gemini-3.1-flash-lite": {}}, revision: 1} + antigravityCapabilityMu.Lock() + antigravityCapabilityCache[key] = antigravityCapabilityCacheEntry{hints: hints, expiresAt: time.Now().Add(antigravityCapabilityCacheTTL)} + antigravityCapabilityMu.Unlock() + svc.applyAntigravityModelHints(t.Context(), auth, "antigravity", hints, key, auth.RegistrationEpoch, reg.ClientRegistrationEpoch(auth.ID)) + initialEpoch := reg.ClientRegistrationEpoch(auth.ID) + if !reg.ClientSupportsModel(auth.ID, "gemini-3.1-flash-lite") { + t.Fatal("initial catalog not registered") + } + closed := false + svc.coreManager.RegisterExecutor(&antigravityRemovalExecutor{ + ProviderExecutor: &mockAntigravityRefreshExecutor{}, + onClose: func() { + closed = true + if _, exists := svc.coreManager.GetByID(auth.ID); exists { + t.Error("runtime auth still exists during removal cleanup") + } + if reg.ClientRegistrationEpoch(auth.ID) != initialEpoch { + t.Error("registry epoch advanced before runtime auth invalidation") + } + // Neither a new scan nor work queued with an old auth snapshot may + // publish from cache while the deletion is between its two stores. + svc.refreshAntigravityModels(t.Context()) + svc.scheduleAntigravityModelRefresh(t.Context(), auth) + svc.WaitAntigravityProbes() + }, + }) + svc.applyCoreAuthRemoval(t.Context(), auth.ID) + if !closed { + t.Fatal("removal cleanup boundary was not exercised") + } + if _, exists := svc.coreManager.GetByID(auth.ID); exists { + t.Fatal("removed auth retained in manager") + } + if len(reg.GetModelsForClient(auth.ID)) != 0 || reg.ClientRegistrationEpoch(auth.ID) != initialEpoch+1 { + t.Fatal("removal did not leave a single final registry tombstone") + } + // A publisher that already validated its auth must still lose registry CAS. + if _, applied := reg.ReplaceClientModels(auth.ID, "antigravity", initialEpoch, []*ModelInfo{{ID: "gemini-3.1-flash-lite"}}); applied { + t.Fatal("pre-removal publisher overwrote the tombstone") + } +} + +func TestAntigravityCachedRegistrationPreservesCooldownWhileProbePending(t *testing.T) { + for _, registered := range []bool{false, true} { + name := "first-publication" + if registered { + name = "reregistration" + } + t.Run(name, func(t *testing.T) { + resetAntigravityCapabilityCache() + t.Cleanup(resetAntigravityCapabilityCache) + started, release := make(chan struct{}), make(chan struct{}) + var once sync.Once + unblock := func() { once.Do(func() { close(release) }) } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + close(started) + select { + case <-release: + _, _ = w.Write([]byte(`{"models":{}}`)) + case <-r.Context().Done(): + } + })) + ctx, cancel := context.WithCancel(t.Context()) + svc := &Service{cfg: &config.Config{}, coreManager: coreauth.NewManager(nil, nil, nil)} + t.Cleanup(func() { + unblock() + svc.WaitAntigravityProbes() + cancel() + server.Close() + }) + const model = "gemini-3.1-flash-lite" + auth := antigravityTestAuth("cached-cooldown-"+name, server.URL) + retry := time.Now().Add(time.Hour) + auth.ModelStates = map[string]*coreauth.ModelState{ + model: {Unavailable: true, NextRetryAfter: retry, Status: coreauth.StatusError, Quota: coreauth.QuotaState{Exceeded: true, NextRecoverAt: retry}}, + } + auth, errRegister := svc.coreManager.Register(ctx, auth) + if errRegister != nil { + t.Fatal(errRegister) + } + reg := registry.GetGlobalRegistry() + t.Cleanup(func() { reg.UnregisterClient(auth.ID) }) + key := svc.antigravityCapabilityKey(auth) + hints := antigravityModelCapabilityHints{ModelIDs: map[string]struct{}{model: {}}, revision: 1} + antigravityCapabilityMu.Lock() + antigravityCapabilityCache[key] = antigravityCapabilityCacheEntry{hints: hints, expiresAt: time.Now().Add(-time.Hour)} + antigravityCapabilityMu.Unlock() + if registered { + svc.applyAntigravityModelHints(ctx, auth, "antigravity", hints, key, auth.RegistrationEpoch, reg.ClientRegistrationEpoch(auth.ID)) + if !reg.IsModelQuotaExceededForClient(auth.ID, model) || !reg.IsModelSuspendedForClient(auth.ID, model) { + t.Fatal("initial cooldown was not projected") + } + } + current, _ := svc.coreManager.GetByID(auth.ID) + svc.completeModelRegistrationForAuth(ctx, current) + <-started + if !reg.IsModelQuotaExceededForClient(auth.ID, model) || !reg.IsModelSuspendedForClient(auth.ID, model) { + t.Error("cached publication lost active cooldown while the network probe was pending") + } + current, _ = svc.coreManager.GetByID(auth.ID) + if state := current.ModelStates[model]; state == nil || !state.NextRetryAfter.Equal(retry) { + t.Error("cached publication lost runtime cooldown") + } + if reg.ApplyClientModelProjections(auth.ID, reg.ClientRegistrationEpoch(auth.ID), current.Generation-1, []registry.ClientModelProjection{{ModelID: model}}) { + t.Error("cached publication accepted a stale scheduling projection") + } + // A later authoritative empty response must still revoke the binding + // and prune its cooldown; preserving cached state cannot prevent updates. + unblock() + svc.WaitAntigravityProbes() + current, _ = svc.coreManager.GetByID(auth.ID) + if len(reg.GetModelsForClient(auth.ID)) != 0 || current.ModelStates[model] != nil { + t.Fatal("authoritative empty catalog did not revoke cached registration") + } + }) + } +} diff --git a/sdk/cliproxy/service_auth.go b/sdk/cliproxy/service_auth.go index a4b6be1ff8c..5acfeeddf16 100644 --- a/sdk/cliproxy/service_auth.go +++ b/sdk/cliproxy/service_auth.go @@ -528,8 +528,11 @@ func (s *Service) applyCoreAuthRemoval(ctx context.Context, id string) { if existing, ok := s.coreManager.GetByID(id); ok && existing != nil { provider = strings.TrimSpace(existing.Provider) } - GlobalModelRegistry().UnregisterClient(id) + // Invalidate the auth before advancing the registry epoch. Otherwise a + // refresh can adopt the tombstone epoch while the auth still exists and + // republish its cached models after the registry has been cleared. s.coreManager.Remove(ctx, id) + GlobalModelRegistry().UnregisterClient(id) s.cancelStaleAntigravityProbes(id) if strings.EqualFold(provider, "codex") { executor.CloseCodexWebsocketSessionsForAuthID(id, "auth_removed") diff --git a/sdk/cliproxy/service_models.go b/sdk/cliproxy/service_models.go index 17c1ff9db07..a444b64c60f 100644 --- a/sdk/cliproxy/service_models.go +++ b/sdk/cliproxy/service_models.go @@ -111,11 +111,20 @@ func (s *Service) registerModelsForAuthWithCache(ctx context.Context, a *coreaut models = registry.GetAIStudioModels() models = applyExcludedModels(models, excluded) case "antigravity": - models = registry.GetAntigravityModels() if !s.antigravityHomeEnabled() { + expectedRegEpoch := GlobalModelRegistry().ClientRegistrationEpoch(a.ID) + expectedKey := s.antigravityCapabilityKey(a) hints := s.cachedAntigravityHints(a) - models = filterAntigravityModels(models, hints) - models = applyAntigravityFetchedModelCapabilities(models, hints) + if hints.ModelIDs != nil { + // Publish known catalogs through the same fenced, state-preserving + // path as refreshes. An expired catalog remains usable while HTTP + // is pending, including its quota and suspension projections. + s.applyAntigravityModelHints(ctx, a, provider, hints, expectedKey, a.RegistrationEpoch, expectedRegEpoch) + s.asyncProbeAntigravityCapabilities(ctx, a, provider) + return + } + } else { + models = registry.GetAntigravityModels() } models = applyExcludedModels(models, excluded) case "claude": @@ -319,9 +328,9 @@ func (s *Service) registerModelsForAuthWithCache(ctx context.Context, a *coreaut // one auth and reconciles any concurrent auth changes that race with the // refresh. Callers are expected to pre-filter provider membership. // -// Re-registration is deliberate: registry cooldown/suspension state is treated -// as part of the previous registration snapshot and is cleared when the auth is -// rebound to the refreshed model catalog. +// Re-registration is deliberate: most providers start a fresh registry snapshot. +// Native Antigravity catalogs instead use fenced replacement to preserve quota +// and suspension state while account entitlement refreshes are pending. func (s *Service) refreshModelRegistrationForAuth(current *coreauth.Auth) bool { return s.refreshModelRegistrationForAuthWithContext(context.Background(), current, nil) } From ad381435a15d72271bc0dc70ddcc15eb387a2786 Mon Sep 17 00:00:00 2001 From: sususu Date: Sat, 3 Oct 2026 21:57:23 +0800 Subject: [PATCH 029/142] fix(antigravity): coalesce probes and respect plugin model ownership Check plugin model declarations without executing discovery. Share one per-account refresh worker across registration and periodic triggers, retaining one latest queued snapshot with its publication epoch. Add ownership, coalescing, and stale-publication regression tests. --- internal/pluginhost/adapters.go | 63 +++--- .../pluginhost/auth_model_provider_test.go | 74 +++++++ sdk/cliproxy/antigravity_model_probes.go | 97 +++++++++ sdk/cliproxy/antigravity_models.go | 69 +------ sdk/cliproxy/antigravity_models_queue_test.go | 189 ++++++++++++++++++ .../antigravity_models_refresh_test.go | 15 +- sdk/cliproxy/service.go | 9 +- sdk/cliproxy/service_executors.go | 5 + 8 files changed, 415 insertions(+), 106 deletions(-) create mode 100644 internal/pluginhost/auth_model_provider_test.go create mode 100644 sdk/cliproxy/antigravity_models_queue_test.go diff --git a/internal/pluginhost/adapters.go b/internal/pluginhost/adapters.go index 88846201314..1406998713e 100644 --- a/internal/pluginhost/adapters.go +++ b/internal/pluginhost/adapters.go @@ -301,6 +301,40 @@ func (h *Host) RegisterModels(ctx context.Context, modelRegistry modelRegistry) h.commitModelClients(snap, modelRegistry, registrations, nextClients, nextProviders, nextModelRegistrations) } +// HasAuthModelProvider reports whether an active plugin declares per-auth model +// discovery for provider. It does not fetch models or refresh credentials. +func (h *Host) HasAuthModelProvider(provider string) bool { + if h == nil { + return false + } + provider = normalizeProviderID(provider) + if provider == "" { + return false + } + for _, record := range h.activeRecords() { + if h.authModelProviderMatches(record, provider) { + return true + } + } + return false +} + +func (h *Host) authModelProviderMatches(record capabilityRecord, provider string) bool { + caps := record.plugin.Capabilities + if caps.ModelProvider == nil || h.isPluginFused(record.id) || !executorScopeAllowsOAuthModels(caps) { + return false + } + if caps.AuthProvider != nil { + identifier, ok := h.callAuthProviderIdentifier(record.id, caps.AuthProvider) + return ok && normalizeProviderID(identifier) == provider + } + candidate := normalizeProviderID(h.modelProvider(record.id)) + if candidate == "" && caps.Executor != nil { + candidate, _ = h.executorProvider(record, caps.Executor) + } + return candidate == provider +} + func (h *Host) ModelsForAuth(ctx context.Context, auth *coreauth.Auth) AuthModelResult { if h == nil || auth == nil { return AuthModelResult{} @@ -310,35 +344,10 @@ func (h *Host) ModelsForAuth(ctx context.Context, auth *coreauth.Auth) AuthModel return AuthModelResult{} } for _, record := range h.activeRecords() { - modelProvider := record.plugin.Capabilities.ModelProvider - if modelProvider == nil || h.isPluginFused(record.id) { + if !h.authModelProviderMatches(record, providerKey) { continue } - if !executorScopeAllowsOAuthModels(record.plugin.Capabilities) { - continue - } - authProvider := record.plugin.Capabilities.AuthProvider - if authProvider != nil { - identifier, okIdentifier := h.callAuthProviderIdentifier(record.id, authProvider) - if !okIdentifier || normalizeProviderID(identifier) != providerKey { - continue - } - } else { - recordProvider := normalizeProviderID(h.modelProvider(record.id)) - if recordProvider == "" { - executor := record.plugin.Capabilities.Executor - if executor != nil { - candidate, okCandidate := h.executorProvider(record, executor) - if okCandidate { - recordProvider = candidate - } - } - } - if recordProvider != providerKey { - continue - } - } - resp, errModels := h.callModelsForAuth(ctx, record, modelProvider, auth) + resp, errModels := h.callModelsForAuth(ctx, record, record.plugin.Capabilities.ModelProvider, auth) if errModels != nil { log.Warnf("pluginhost: models for auth %s failed: %v", auth.ID, errModels) return AuthModelResult{Handled: true, Err: errModels} diff --git a/internal/pluginhost/auth_model_provider_test.go b/internal/pluginhost/auth_model_provider_test.go new file mode 100644 index 00000000000..970118ca4c6 --- /dev/null +++ b/internal/pluginhost/auth_model_provider_test.go @@ -0,0 +1,74 @@ +package pluginhost + +import ( + "context" + "testing" + + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginapi" +) + +func TestHasAuthModelProviderDoesNotRunDiscovery(t *testing.T) { + for _, mode := range []string{"auth", "executor", "registered", "static-only", "fused", "unloaded", "no-model-provider"} { + t.Run(mode, func(t *testing.T) { + calls := 0 + caps := pluginapi.Capabilities{ + ModelProvider: modelProviderFunc{ + staticModels: func(context.Context, pluginapi.StaticModelRequest) (pluginapi.ModelResponse, error) { + t.Error("ownership lookup called StaticModels") + return pluginapi.ModelResponse{}, nil + }, + modelsForAuth: func(context.Context, pluginapi.AuthModelRequest) (pluginapi.ModelResponse, error) { + calls++ + return pluginapi.ModelResponse{Provider: "antigravity", Models: []pluginapi.ModelInfo{{ID: "plugin-model"}}, AuthUpdate: pluginapi.AuthData{Metadata: map[string]any{"access_token": "rotated"}}}, nil + }, + }, + } + switch mode { + case "executor", "static-only": + caps.Executor = &fakeExecutor{identifier: "antigravity"} + caps.ExecutorModelScope = pluginapi.ExecutorModelScopeOAuth + if mode == "static-only" { + caps.ExecutorModelScope = pluginapi.ExecutorModelScopeStatic + } + case "registered": + default: + caps.AuthProvider = fakeAuthProvider{identifier: "antigravity"} + } + if mode == "no-model-provider" { + caps.ModelProvider = nil + } + host := newHostWithRecords(capabilityRecord{id: "ownership", plugin: pluginapi.Plugin{Capabilities: caps}}) + if mode == "registered" { + host.modelProviders["ownership"] = "antigravity" + } + if mode == "fused" { + host.fused["ownership"] = "test" + } + if mode == "unloaded" { + setHostSnapshotForTest(host, true) + } + want := mode == "auth" || mode == "executor" || mode == "registered" + for range 100 { + if got := host.HasAuthModelProvider(" ANTIGRAVITY "); got != want { + t.Fatalf("ownership=%v, want %v", got, want) + } + } + if calls != 0 || host.HasAuthModelProvider("claude") || host.HasAuthModelProvider("") { + t.Fatal("ownership lookup executed discovery or matched an unrelated provider") + } + // The normal registration path must still consume discovery and auth updates. + result := host.ModelsForAuth(t.Context(), &coreauth.Auth{ID: "account", Provider: "antigravity"}) + if result.Handled != want { + t.Fatal("ownership lookup disagrees with per-auth dispatch") + } + if want && (calls != 1 || result.Auth == nil || result.Auth.Metadata["access_token"] != "rotated" || len(result.Models) != 1) { + t.Fatal("normal discovery lost model or credential updates") + } + }) + } + var host *Host + if host.HasAuthModelProvider("antigravity") { + t.Fatal("nil host claims model ownership") + } +} diff --git a/sdk/cliproxy/antigravity_model_probes.go b/sdk/cliproxy/antigravity_model_probes.go index 530124d91b7..21a8ecdaa23 100644 --- a/sdk/cliproxy/antigravity_model_probes.go +++ b/sdk/cliproxy/antigravity_model_probes.go @@ -7,6 +7,103 @@ import ( coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" ) +// antigravityModelRefreshRequest captures publication ownership at admission. +// A queued successor must not adopt a later epoch from an external publisher. +type antigravityModelRefreshRequest struct { + ctx context.Context + auth *coreauth.Auth + provider string + registryEpoch uint64 +} + +// queueAntigravityModelRefresh coalesces registration and periodic probes into +// one worker per account. Repeated updates replace a single queued successor, +// rather than accumulating singleflight followers while an upstream is stalled. +func (s *Service) queueAntigravityModelRefresh(ctx context.Context, auth *coreauth.Auth, provider string) { + if s == nil || auth == nil || auth.ID == "" || auth.Disabled || s.antigravityHomeEnabled() { + return + } + if ctx == nil { + ctx = context.Background() + } + if ctx.Err() != nil || pluginHostHasAuthModelProvider(s.pluginHost, auth.Provider) { + return + } + s.cfgMu.RLock() + lifetime := s.antigravityContext + s.cfgMu.RUnlock() + if lifetime != nil && lifetime.Err() != nil { + return + } + request := &antigravityModelRefreshRequest{ + ctx: ctx, auth: auth.Clone(), provider: provider, + registryEpoch: GlobalModelRegistry().ClientRegistrationEpoch(auth.ID), + } + token, _ := request.auth.Metadata["access_token"].(string) + probe := &antigravityAccountProbe{ + auth: request.auth, routeKey: s.antigravityCapabilityKey(request.auth), token: strings.TrimSpace(token), + } + s.antigravityProbeMu.Lock() + // Late stale callers must not replace the latest queued auth snapshot. + if ctx.Err() != nil || !s.antigravityAccountProbeCurrent(probe) { + s.antigravityProbeMu.Unlock() + return + } + if s.antigravityRefreshPending == nil { + s.antigravityRefreshPending = make(map[string]*antigravityModelRefreshRequest) + } + queued, running := s.antigravityRefreshPending[auth.ID] + if queued != nil && queued.registryEpoch > request.registryEpoch { + // Concurrent registration callers can reach admission out of order. + s.antigravityProbeMu.Unlock() + return + } + s.antigravityRefreshPending[auth.ID] = request + if !running { + s.antigravityProbeWg.Add(1) + } + s.antigravityProbeMu.Unlock() + if !running { + go s.runAntigravityAccountRefresh(auth.ID) + } +} + +func (s *Service) runAntigravityAccountRefresh(authID string) { + defer s.antigravityProbeWg.Done() + defer s.signalAntigravityModelRefresh() + for { + s.antigravityProbeMu.Lock() + request := s.antigravityRefreshPending[authID] + if request == nil { + delete(s.antigravityRefreshPending, authID) + s.antigravityProbeMu.Unlock() + return + } + s.antigravityRefreshPending[authID] = nil + s.antigravityProbeMu.Unlock() + s.executeAntigravityModelRefresh(request) + } +} + +func (s *Service) executeAntigravityModelRefresh(request *antigravityModelRefreshRequest) { + if request.ctx.Err() != nil || pluginHostHasAuthModelProvider(s.pluginHost, request.auth.Provider) { + return + } + probeCtx, cancel := context.WithCancel(request.ctx) + defer cancel() + s.cfgMu.RLock() + lifetime := s.antigravityContext + s.cfgMu.RUnlock() + if lifetime != nil { + stop := context.AfterFunc(lifetime, cancel) + defer stop() + if lifetime.Err() != nil { + return + } + } + s.probeAndRegisterAntigravityModels(probeCtx, request.auth, request.provider, request.auth.RegistrationEpoch, request.registryEpoch) +} + // antigravityAccountProbe owns both queued and connected work for one auth snapshot. // Cancellation releases network slots without imposing an upstream timeout. type antigravityAccountProbe struct { diff --git a/sdk/cliproxy/antigravity_models.go b/sdk/cliproxy/antigravity_models.go index cc928c1cb60..20051299a52 100644 --- a/sdk/cliproxy/antigravity_models.go +++ b/sdk/cliproxy/antigravity_models.go @@ -455,32 +455,7 @@ func (s *Service) antigravityModelsForHintsWithConfig(auth *coreauth.Auth, hints } func (s *Service) asyncProbeAntigravityCapabilities(ctx context.Context, auth *coreauth.Auth, providerKey string) { - if s == nil || auth == nil || auth.ID == "" || auth.Disabled || s.antigravityHomeEnabled() { - return - } - if ctx == nil { - ctx = context.Background() - } - authClone := auth.Clone() - expectedEpoch := auth.RegistrationEpoch - expectedRegEpoch := GlobalModelRegistry().ClientRegistrationEpoch(auth.ID) - s.antigravityProbeWg.Add(1) - go func() { - defer s.antigravityProbeWg.Done() - probeCtx, cancel := context.WithCancel(ctx) - defer cancel() - s.cfgMu.RLock() - lifetime := s.antigravityContext - s.cfgMu.RUnlock() - if lifetime != nil { - stop := context.AfterFunc(lifetime, cancel) - defer stop() - if lifetime.Err() != nil { - return - } - } - s.probeAndRegisterAntigravityModels(probeCtx, authClone, providerKey, expectedEpoch, expectedRegEpoch) - }() + s.queueAntigravityModelRefresh(ctx, auth, providerKey) } func (s *Service) probeAndRegisterAntigravityModels(ctx context.Context, auth *coreauth.Auth, providerKey string, expectedEpoch, expectedRegEpoch uint64) { @@ -586,47 +561,7 @@ func (s *Service) refreshAntigravityModels(ctx context.Context) { } func (s *Service) scheduleAntigravityModelRefresh(ctx context.Context, auth *coreauth.Auth) { - s.antigravityProbeMu.Lock() - if _, pending := s.antigravityRefreshPending[auth.ID]; pending { - s.antigravityProbeMu.Unlock() - return - } - if s.antigravityRefreshPending == nil { - s.antigravityRefreshPending = make(map[string]struct{}) - } - s.antigravityRefreshPending[auth.ID] = struct{}{} - if s.antigravityRefreshPluginSlots == nil { - s.antigravityRefreshPluginSlots = make(chan struct{}, modelRegistrationMaxWorkersPerCategory) - } - pluginSlots := s.antigravityRefreshPluginSlots - s.antigravityProbeWg.Add(1) - s.antigravityProbeMu.Unlock() - go func() { - defer s.antigravityProbeWg.Done() - defer func() { - s.antigravityProbeMu.Lock() - delete(s.antigravityRefreshPending, auth.ID) - s.antigravityProbeMu.Unlock() - s.signalAntigravityModelRefresh() - }() - if ctx.Err() != nil { - return - } - if s.pluginHost != nil { - select { - case pluginSlots <- struct{}{}: - case <-ctx.Done(): - return - } - result := s.pluginHost.ModelsForAuth(ctx, auth) - <-pluginSlots - if result.Handled || ctx.Err() != nil { - return - } - } - epoch := GlobalModelRegistry().ClientRegistrationEpoch(auth.ID) - s.probeAndRegisterAntigravityModels(ctx, auth, "antigravity", auth.RegistrationEpoch, epoch) - }() + s.queueAntigravityModelRefresh(ctx, auth, "antigravity") } // nextAntigravityModelRefreshDelay preserves retry jitter in actual scheduling, diff --git a/sdk/cliproxy/antigravity_models_queue_test.go b/sdk/cliproxy/antigravity_models_queue_test.go new file mode 100644 index 00000000000..f306762a48e --- /dev/null +++ b/sdk/cliproxy/antigravity_models_queue_test.go @@ -0,0 +1,189 @@ +package cliproxy + +import ( + "context" + "io" + "net/http" + "runtime" + "strings" + "sync" + "sync/atomic" + "testing" + "testing/synctest" + "time" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/pluginhost" + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" +) + +func TestAntigravityRefreshSkipsPluginOwnedModels(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + resetAntigravityCapabilityCache() + defer resetAntigravityCapabilityCache() + svc := &Service{cfg: &config.Config{}, coreManager: coreauth.NewManager(nil, nil, nil), pluginHost: pluginhost.New()} + auth, errRegister := svc.coreManager.Register(t.Context(), antigravityTestAuth("plugin-owned-refresh", "https://unused.invalid")) + if errRegister != nil { + t.Fatal(errRegister) + } + reg := GlobalModelRegistry() + defer reg.UnregisterClient(auth.ID) + reg.RegisterClient(auth.ID, "antigravity", []*ModelInfo{{ID: "plugin-model"}}) + var owned atomic.Bool + owned.Store(true) + var lookups atomic.Int32 + oldOwnership := pluginHostHasAuthModelProvider + pluginHostHasAuthModelProvider = func(host *pluginhost.Host, provider string) bool { + lookups.Add(1) + return host == svc.pluginHost && provider == "antigravity" && owned.Load() + } + defer func() { pluginHostHasAuthModelProvider = oldOwnership }() + var calls atomic.Int32 + transport := http.DefaultTransport + http.DefaultTransport = antigravityReviewTransport(func(req *http.Request) (*http.Response, error) { + calls.Add(1) + return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"models":{"gemini-3.1-flash-lite":{}}}`)), Request: req}, nil + }) + defer func() { http.DefaultTransport = transport }() + ctx, cancel := context.WithCancel(t.Context()) + done := make(chan struct{}) + go func() { defer close(done); svc.runAntigravityModelRefresh(ctx) }() + svc.asyncProbeAntigravityCapabilities(ctx, auth, "antigravity") + time.Sleep(10 * time.Minute) // Synthetic time: exercise multiple native scans. + synctest.Wait() + cancel() + <-done + svc.WaitAntigravityProbes() + synctest.Wait() + if lookups.Load() == 0 || calls.Load() != 0 || !reg.ClientSupportsModel(auth.ID, "plugin-model") { + t.Fatal("native refresh ignored plugin model ownership") + } + // Plugin removal must immediately make native discovery eligible again. + owned.Store(false) + svc.completeModelRegistrationForAuth(t.Context(), auth) + svc.WaitAntigravityProbes() + if calls.Load() != 1 || !reg.ClientSupportsModel(auth.ID, "gemini-3.1-flash-lite") { + t.Fatal("removed plugin continued to suppress native discovery") + } + }) +} + +func TestAntigravityRegistrationCoalescesLatestPublication(t *testing.T) { + for _, name := range []string{"publish-latest", "concurrent-registration", "external-unregister"} { + t.Run(name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + resetAntigravityCapabilityCache() + defer resetAntigravityCapabilityCache() + svc := &Service{cfg: &config.Config{}, coreManager: coreauth.NewManager(nil, nil, nil)} + auth, errRegister := svc.coreManager.Register(t.Context(), antigravityTestAuth("coalesced-"+name, "https://stalled.invalid")) + if errRegister != nil { + t.Fatal(errRegister) + } + reg := GlobalModelRegistry() + defer reg.UnregisterClient(auth.ID) + var calls atomic.Int32 + release := make(chan struct{}) + transport := http.DefaultTransport + http.DefaultTransport = antigravityReviewTransport(func(req *http.Request) (*http.Response, error) { + calls.Add(1) + select { + case <-release: + return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"models":{"gemini-3.1-flash-lite":{}}}`)), Request: req}, nil + case <-req.Context().Done(): + return nil, req.Context().Err() + } + }) + defer func() { http.DefaultTransport = transport }() + ctx, cancel := context.WithCancel(t.Context()) + defer func() { cancel(); svc.WaitAntigravityProbes(); synctest.Wait() }() + svc.completeModelRegistrationForAuth(ctx, auth) + synctest.Wait() + before := runtime.NumGoroutine() + register := func() { + svc.completeModelRegistrationForAuth(ctx, auth) + svc.refreshAntigravityModels(ctx) + } + var registrations sync.WaitGroup + for range 100 { + if name == "concurrent-registration" { + registrations.Go(register) + } else { + register() + } + } + registrations.Wait() + synctest.Wait() + growth := runtime.NumGoroutine() - before + svc.antigravityProbeMu.Lock() + pending := len(svc.antigravityRefreshPending) + latest := svc.antigravityRefreshPending[auth.ID] + svc.antigravityProbeMu.Unlock() + if growth > 4 || calls.Load() != 1 || pending != 1 { + t.Fatalf("unbounded work: goroutine growth=%d HTTP=%d workers=%d", growth, calls.Load(), pending) + } + if latest == nil || latest.registryEpoch != reg.ClientRegistrationEpoch(auth.ID) { + t.Fatal("latest queued publication snapshot was not retained") + } + if name == "external-unregister" { + reg.UnregisterClient(auth.ID) + } + close(release) + svc.WaitAntigravityProbes() + synctest.Wait() + wantRegistered := name != "external-unregister" + if reg.ClientSupportsModel(auth.ID, "gemini-3.1-flash-lite") != wantRegistered || calls.Load() != 1 { + t.Fatal("queued publication lost the latest snapshot or adopted an external registry epoch") + } + svc.antigravityProbeMu.Lock() + remaining := len(svc.antigravityRefreshPending) + len(svc.antigravityAccountProbes) + svc.antigravityProbeMu.Unlock() + if remaining != 0 { + t.Fatal("completed coalesced refresh retained pending work") + } + }) + }) + } +} + +func TestAntigravityQueuedAuthUpdateRejectsLateStaleCaller(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + resetAntigravityCapabilityCache() + defer resetAntigravityCapabilityCache() + svc := &Service{cfg: &config.Config{SDKConfig: config.SDKConfig{ForceModelPrefix: true}}, coreManager: coreauth.NewManager(nil, nil, nil)} + auth, errRegister := svc.coreManager.Register(t.Context(), antigravityTestAuth("coalesced-auth-update", "https://stalled.invalid")) + if errRegister != nil { + t.Fatal(errRegister) + } + defer GlobalModelRegistry().UnregisterClient(auth.ID) + var oldCalls, newCalls atomic.Int32 + transport := http.DefaultTransport + http.DefaultTransport = antigravityReviewTransport(func(req *http.Request) (*http.Response, error) { + if req.Header.Get("Authorization") != "Bearer updated-token" { + oldCalls.Add(1) + <-req.Context().Done() + return nil, req.Context().Err() + } + newCalls.Add(1) + return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"models":{"gemini-3.1-flash-lite":{}}}`)), Request: req}, nil + }) + defer func() { http.DefaultTransport = transport }() + ctx, cancel := context.WithCancel(t.Context()) + defer func() { cancel(); svc.WaitAntigravityProbes(); synctest.Wait() }() + svc.completeModelRegistrationForAuth(ctx, auth) + synctest.Wait() + updated := auth.Clone() + updated.Prefix = "latest" + updated.Metadata["access_token"] = "updated-token" + updated, errUpdate := svc.coreManager.Update(ctx, updated) + if errUpdate != nil { + t.Fatal(errUpdate) + } + svc.completeModelRegistrationForAuth(ctx, updated) + svc.asyncProbeAntigravityCapabilities(ctx, auth, "antigravity") + svc.WaitAntigravityProbes() + synctest.Wait() + if oldCalls.Load() != 1 || newCalls.Load() != 1 || !GlobalModelRegistry().ClientSupportsModel(auth.ID, "latest/gemini-3.1-flash-lite") { + t.Fatal("stale caller replaced the updated queued auth snapshot") + } + }) +} diff --git a/sdk/cliproxy/antigravity_models_refresh_test.go b/sdk/cliproxy/antigravity_models_refresh_test.go index d8803441e50..ae23ed43a1d 100644 --- a/sdk/cliproxy/antigravity_models_refresh_test.go +++ b/sdk/cliproxy/antigravity_models_refresh_test.go @@ -111,9 +111,8 @@ func TestAntigravityRefreshBoundsQueuedWorkAndCancels(t *testing.T) { antigravityProbeSlots = make(chan struct{}, cap(slots)) defer func() { antigravityProbeSlots = slots }() svc := &Service{cfg: &config.Config{}, coreManager: coreauth.NewManager(nil, nil, nil), pluginHost: pluginhost.New()} - svc.antigravityRefreshPluginSlots = make(chan struct{}, modelRegistrationMaxWorkersPerCategory) - for range cap(svc.antigravityRefreshPluginSlots) { - svc.antigravityRefreshPluginSlots <- struct{}{} + for range cap(antigravityProbeSlots) { + antigravityProbeSlots <- struct{}{} } const accounts = modelRegistrationMaxWorkersPerCategory + 3 for i := range accounts { @@ -134,10 +133,12 @@ func TestAntigravityRefreshBoundsQueuedWorkAndCancels(t *testing.T) { ctx, cancel := context.WithCancel(t.Context()) done := make(chan struct{}) go func() { defer close(done); svc.runAntigravityModelRefresh(ctx) }() - time.Sleep(2 * time.Minute) // Synthetic time: plugin calls are waiting for admission. + time.Sleep(2 * time.Minute) // Synthetic time: native probes are waiting for admission. synctest.Wait() beforeAdmission := calls.Load() - <-svc.antigravityRefreshPluginSlots + for range cap(antigravityProbeSlots) { + <-antigravityProbeSlots + } time.Sleep(8 * time.Minute) // Repeated scans must not accumulate followers. synctest.Wait() connected := calls.Load() @@ -154,8 +155,8 @@ func TestAntigravityRefreshBoundsQueuedWorkAndCancels(t *testing.T) { if connected != modelRegistrationMaxWorkersPerCategory || pending != accounts { t.Fatalf("connected=%d pending=%d, want %d and %d", connected, pending, modelRegistrationMaxWorkersPerCategory, accounts) } - if beforeAdmission != 0 || len(svc.antigravityRefreshPluginSlots) != cap(svc.antigravityRefreshPluginSlots)-1 { - t.Fatal("plugin admission was bypassed or its slot was held during native probes") + if beforeAdmission != 0 { + t.Fatal("native network admission was bypassed") } if remaining != 0 || len(antigravityProbeSlots) != 0 { t.Fatal("canceled refresh retained tasks or network slots") diff --git a/sdk/cliproxy/service.go b/sdk/cliproxy/service.go index 44428b24dca..63f113a2e1b 100644 --- a/sdk/cliproxy/service.go +++ b/sdk/cliproxy/service.go @@ -137,11 +137,10 @@ type Service struct { antigravityProbeMu sync.Mutex antigravityAccountProbes map[string]map[*antigravityAccountProbe]struct{} antigravityRefreshWake chan struct{} - // antigravityRefreshPending is protected by antigravityProbeMu and bounds - // periodic refresh work to one queued or running task per account. - antigravityRefreshPending map[string]struct{} - // Plugin queries have their own bound; native HTTP must not hold these slots. - antigravityRefreshPluginSlots chan struct{} + // antigravityRefreshPending is protected by antigravityProbeMu. Each entry + // owns one worker and at most one queued snapshot shared by all probe entry + // points. A nil value means the worker is running without a queued successor. + antigravityRefreshPending map[string]*antigravityModelRefreshRequest } // SetResultPolicy sets an execution result policy on the underlying core auth manager. diff --git a/sdk/cliproxy/service_executors.go b/sdk/cliproxy/service_executors.go index a1a64250e1a..edc1098af0d 100644 --- a/sdk/cliproxy/service_executors.go +++ b/sdk/cliproxy/service_executors.go @@ -23,6 +23,11 @@ var pluginHostHasAuthProvider = func(host *pluginhost.Host, provider string) boo return host != nil && host.HasAuthProvider(provider) } +// pluginHostHasAuthModelProvider only checks declarations, never model discovery. +var pluginHostHasAuthModelProvider = func(host *pluginhost.Host, provider string) bool { + return host != nil && host.HasAuthModelProvider(provider) +} + type openAICompatibilityRegistrationEntry struct { providerKey string models []*ModelInfo From 868e137f6c1dd10bc78a4e6fcdee99889f8af77d Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Sun, 4 Oct 2026 03:01:18 +0800 Subject: [PATCH 030/142] feat(payload): introduce payload finalizer for protobuf and multipart requests - Add `PayloadFinalizer` to apply configuration rules at the final serialization barrier - Support decoding, modifying, and re-encoding Devin protobuf business fields - Add multipart form-data payload normalization to JSON for media payload rules Closes: #5067 --- AGENTS.md | 1 + .../runtime/executor/aistudio_executor.go | 11 +- .../executor/aistudio_executor_test.go | 6 +- .../executor/antigravity_executor_execute.go | 8 +- .../executor/antigravity_executor_request.go | 2 + .../executor/antigravity_executor_stream.go | 4 +- .../executor/antigravity_executor_tokens.go | 2 + .../executor/claude_cloaked_date_pin_test.go | 21 +- .../executor/claude_executor_cloaking.go | 9 +- .../executor/claude_executor_execute.go | 97 ++---- .../executor/claude_executor_stream.go | 94 ++---- .../runtime/executor/claude_executor_test.go | 291 +++++------------- .../executor/claude_executor_tokens.go | 10 + .../executor/claude_mid_system_model_test.go | 89 ++++-- .../executor/codex_executor_execute.go | 8 +- .../executor/codex_executor_request.go | 1 + .../runtime/executor/codex_executor_stream.go | 4 +- .../runtime/executor/codex_executor_tokens.go | 5 + .../runtime/executor/codex_openai_images.go | 27 +- .../executor/codex_websockets_connection.go | 10 +- .../executor/codex_websockets_duplex.go | 10 +- .../executor/codex_websockets_execute.go | 9 +- .../executor/codex_websockets_stream.go | 9 +- internal/runtime/executor/devin_executor.go | 9 + internal/runtime/executor/gemini_executor.go | 13 +- .../runtime/executor/gemini_executor_test.go | 10 +- .../executor/gemini_vertex_executor.go | 30 +- .../runtime/executor/helps/devin_payload.go | 227 ++++++++++++++ .../executor/helps/payload_finalizer.go | 38 +++ .../executor/helps/payload_finalizer_test.go | 122 ++++++++ .../runtime/executor/helps/payload_media.go | 120 ++++++++ internal/runtime/executor/kimi_executor.go | 8 +- .../runtime/executor/meta_executor_execute.go | 2 +- .../executor/openai_compat_executor.go | 17 +- .../runtime/executor/payload_barrier_test.go | 184 +++++++++++ .../runtime/executor/payload_review_test.go | 203 ++++++++++++ .../runtime/executor/xai_executor_execute.go | 2 + .../runtime/executor/xai_executor_media.go | 2 + .../runtime/executor/xai_executor_request.go | 6 +- .../runtime/executor/xai_executor_stream.go | 1 + .../runtime/executor/xai_executor_test.go | 6 +- .../runtime/executor/xai_executor_tokens.go | 1 + .../executor/xai_websockets_executor.go | 10 +- 43 files changed, 1257 insertions(+), 482 deletions(-) create mode 100644 internal/runtime/executor/helps/devin_payload.go create mode 100644 internal/runtime/executor/helps/payload_finalizer.go create mode 100644 internal/runtime/executor/helps/payload_finalizer_test.go create mode 100644 internal/runtime/executor/helps/payload_media.go create mode 100644 internal/runtime/executor/payload_barrier_test.go create mode 100644 internal/runtime/executor/payload_review_test.go diff --git a/AGENTS.md b/AGENTS.md index 8a40ce91d60..55ab25d8b00 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -50,6 +50,7 @@ go build -o test-output ./cmd/server && rm test-output # Verify compile (REQUIRE - As a rule, do not make standalone changes to `internal/translator/`. You may modify it only as part of broader changes elsewhere. - If a task requires changing only `internal/translator/`, run `gh repo view --json viewerPermission -q .viewerPermission` to confirm you have `WRITE`, `MAINTAIN`, or `ADMIN`. If you do, you may proceed; otherwise, file a GitHub issue including the goal, rationale, and the intended implementation code, then stop further work. - `internal/runtime/executor/` should contain executors and their unit tests only. Place any helper/supporting files under `internal/runtime/executor/helps/`. +- Payload configuration MUST be the final semantic barrier before sending requests in every executor, including streaming, WebSocket, continuation, retry/fallback, image, and token-count paths where applicable. Complete all built-in payload translation, normalization, injection, and cleanup first, then evaluate and apply user payload rules exactly once to the final business payload. No subsequent logic may overwrite configured values or restore filtered fields. Only necessary transport framing, serialization, signature calculation, and read-only validation may follow without changing business payload semantics. Add regression tests when introducing or changing request-building paths to enforce this ordering. - Follow `gofmt`; keep imports goimports-style; wrap errors with context where helpful - Do not use `log.Fatal`/`log.Fatalf` (terminates the process); prefer returning errors and logging via logrus - Shadowed variables: use method suffix (`errStart := server.Start()`) diff --git a/internal/runtime/executor/aistudio_executor.go b/internal/runtime/executor/aistudio_executor.go index 1e8e249efc4..8efc1920c16 100644 --- a/internal/runtime/executor/aistudio_executor.go +++ b/internal/runtime/executor/aistudio_executor.go @@ -460,10 +460,6 @@ func (e *AIStudioExecutor) CountTokens(ctx context.Context, auth *cliproxyauth.A return cliproxyexecutor.Response{}, err } - body.payload, _ = sjson.DeleteBytes(body.payload, "generationConfig") - body.payload, _ = sjson.DeleteBytes(body.payload, "tools") - body.payload, _ = sjson.DeleteBytes(body.payload, "safetySettings") - endpoint := e.buildEndpoint(baseModel, "countTokens", "") wsReq := &wsrelay.HTTPRequest{ Method: http.MethodPost, @@ -542,7 +538,6 @@ func (e *AIStudioExecutor) translateRequest(ctx context.Context, req cliproxyexe payload = fixGeminiImageAspectRatio(baseModel, payload) requestedModel := helps.PayloadRequestedModel(opts, req.Model) requestPath := helps.PayloadRequestPath(opts) - payload = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, to.String(), from.String(), "", payload, originalTranslated, requestedModel, requestPath, opts.Headers) payload, _ = sjson.DeleteBytes(payload, "generationConfig.maxOutputTokens") payload, _ = sjson.DeleteBytes(payload, "generationConfig.responseMimeType") payload, _ = sjson.DeleteBytes(payload, "generationConfig.responseJsonSchema") @@ -562,6 +557,12 @@ func (e *AIStudioExecutor) translateRequest(ctx context.Context, req cliproxyexe payload = helps.EnsureGeminiTrailingUserContent(payload, "contents") } payload = normalizeAIStudioThinkingLevel(payload) + if action == "countTokens" { + payload, _ = sjson.DeleteBytes(payload, "generationConfig") + payload, _ = sjson.DeleteBytes(payload, "tools") + payload, _ = sjson.DeleteBytes(payload, "safetySettings") + } + payload = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, to.String(), from.String(), "", payload, originalTranslated, requestedModel, requestPath, opts.Headers) return payload, translatedPayload{payload: payload, action: action, toFormat: to}, nil } diff --git a/internal/runtime/executor/aistudio_executor_test.go b/internal/runtime/executor/aistudio_executor_test.go index 7e8e226c599..8606d7e1eb9 100644 --- a/internal/runtime/executor/aistudio_executor_test.go +++ b/internal/runtime/executor/aistudio_executor_test.go @@ -63,7 +63,7 @@ func TestAIStudioTranslateRequestNormalizesThinkingLevel(t *testing.T) { } } -func TestAIStudioTranslateRequestNormalizesThinkingLevelAfterPayloadOverride(t *testing.T) { +func TestAIStudioTranslateRequestPayloadOverrideWinsThinkingNormalization(t *testing.T) { executor := NewAIStudioExecutor(&config.Config{Payload: config.PayloadConfig{Override: []config.PayloadRule{{ Models: []config.PayloadModelRule{{Name: "gemini-3.7-flash", Protocol: "gemini"}}, Params: map[string]any{"generationConfig.thinkingConfig.thinkingLevel": "medium"}, @@ -78,8 +78,8 @@ func TestAIStudioTranslateRequestNormalizesThinkingLevelAfterPayloadOverride(t * if err != nil { t.Fatalf("translateRequest() error = %v", err) } - if got := gjson.GetBytes(payload, "generationConfig.thinkingConfig.thinkingLevel").String(); got != "MEDIUM" { - t.Fatalf("thinkingLevel = %q, want MEDIUM; payload=%s", got, payload) + if got := gjson.GetBytes(payload, "generationConfig.thinkingConfig.thinkingLevel").String(); got != "medium" { + t.Fatalf("thinkingLevel = %q, want medium; payload=%s", got, payload) } } diff --git a/internal/runtime/executor/antigravity_executor_execute.go b/internal/runtime/executor/antigravity_executor_execute.go index 3c7d552a13f..e42a12a0d03 100644 --- a/internal/runtime/executor/antigravity_executor_execute.go +++ b/internal/runtime/executor/antigravity_executor_execute.go @@ -92,9 +92,7 @@ func (e *AntigravityExecutor) Execute(ctx context.Context, auth *cliproxyauth.Au return resp, err } - requestedModel := helps.PayloadRequestedModel(opts, req.Model) - requestPath := helps.PayloadRequestPath(opts) - translated = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, "antigravity", from.String(), "request", translated, originalTranslated, requestedModel, requestPath, opts.Headers) + ctx = helps.WithPayloadFinalizer(ctx, helps.NewPayloadFinalizer(e.cfg, e.Identifier(), baseModel, "antigravity", "request", originalTranslated, req, opts)) translated = e.obfuscateSensitiveWords(translated) translated = sanitizeAntigravityGeminiRequestSignatures(baseModel, translated) reporter.SetTranslatedReasoningEffort(translated, to.String()) @@ -302,9 +300,7 @@ func (e *AntigravityExecutor) executeClaudeNonStream(ctx context.Context, auth * return resp, err } - requestedModel := helps.PayloadRequestedModel(opts, req.Model) - requestPath := helps.PayloadRequestPath(opts) - translated = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, "antigravity", from.String(), "request", translated, originalTranslated, requestedModel, requestPath, opts.Headers) + ctx = helps.WithPayloadFinalizer(ctx, helps.NewPayloadFinalizer(e.cfg, e.Identifier(), baseModel, "antigravity", "request", originalTranslated, req, opts)) translated = e.obfuscateSensitiveWords(translated) translated = sanitizeAntigravityGeminiRequestSignatures(baseModel, translated) reporter.SetTranslatedReasoningEffort(translated, to.String()) diff --git a/internal/runtime/executor/antigravity_executor_request.go b/internal/runtime/executor/antigravity_executor_request.go index 574b16d5b74..9c51a68acd2 100644 --- a/internal/runtime/executor/antigravity_executor_request.go +++ b/internal/runtime/executor/antigravity_executor_request.go @@ -83,6 +83,7 @@ func (e *AntigravityExecutor) buildRequest(ctx context.Context, auth *cliproxyau } payloadStrBytes := applyAntigravityNativeSignatureReplayIfNeeded(modelName, []byte(payloadStr)) + payloadStrBytes = helps.FinalizePayload(ctx, payloadStrBytes) bodyReader = bytes.NewReader(payloadStrBytes) if e.cfg != nil && e.cfg.RequestLog { payloadLog = append([]byte(nil), payloadStrBytes...) @@ -95,6 +96,7 @@ func (e *AntigravityExecutor) buildRequest(ctx context.Context, auth *cliproxyau } payload = applyAntigravityNativeSignatureReplayIfNeeded(modelName, payload) + payload = helps.FinalizePayload(ctx, payload) bodyReader = bytes.NewReader(payload) if e.cfg != nil && e.cfg.RequestLog { payloadLog = append([]byte(nil), payload...) diff --git a/internal/runtime/executor/antigravity_executor_stream.go b/internal/runtime/executor/antigravity_executor_stream.go index 0d2d6243da2..bd02f0f4d58 100644 --- a/internal/runtime/executor/antigravity_executor_stream.go +++ b/internal/runtime/executor/antigravity_executor_stream.go @@ -91,9 +91,7 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya return nil, err } - requestedModel := helps.PayloadRequestedModel(opts, req.Model) - requestPath := helps.PayloadRequestPath(opts) - translated = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, "antigravity", from.String(), "request", translated, originalTranslated, requestedModel, requestPath, opts.Headers) + ctx = helps.WithPayloadFinalizer(ctx, helps.NewPayloadFinalizer(e.cfg, e.Identifier(), baseModel, "antigravity", "request", originalTranslated, req, opts)) translated = e.obfuscateSensitiveWords(translated) translated = sanitizeAntigravityGeminiRequestSignatures(baseModel, translated) translated, _ = sjson.DeleteBytes(translated, "request.stream") diff --git a/internal/runtime/executor/antigravity_executor_tokens.go b/internal/runtime/executor/antigravity_executor_tokens.go index 9085fea5a0a..a493030271a 100644 --- a/internal/runtime/executor/antigravity_executor_tokens.go +++ b/internal/runtime/executor/antigravity_executor_tokens.go @@ -51,6 +51,7 @@ func (e *AntigravityExecutor) CountTokens(ctx context.Context, auth *cliproxyaut modelInfo, _ := cliproxyauth.ResolvedModelInfo(req) translationReq := sdktranslator.RequestEnvelope{Format: from, Model: baseModel, Body: req.Payload, ModelInfo: modelInfo} payload := helps.TranslateRequestEnvelopeWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, translationReq).Body + originalTranslatedForPayload := append([]byte(nil), payload...) payload, err := helps.ApplyRequestThinking(payload, req, opts, from.String(), to.String(), e.Identifier()) if err != nil { @@ -89,6 +90,7 @@ func (e *AntigravityExecutor) CountTokens(ctx context.Context, auth *cliproxyaut requestURL.WriteString(url.QueryEscape(opts.Alt)) } + payload = helps.NewPayloadFinalizer(e.cfg, e.Identifier(), baseModel, to.String(), "request", originalTranslatedForPayload, req, opts)(payload) httpReq, errReq := http.NewRequestWithContext(ctx, http.MethodPost, requestURL.String(), bytes.NewReader(payload)) if errReq != nil { return cliproxyexecutor.Response{}, errReq diff --git a/internal/runtime/executor/claude_cloaked_date_pin_test.go b/internal/runtime/executor/claude_cloaked_date_pin_test.go index 309dae53d6c..d320501cb82 100644 --- a/internal/runtime/executor/claude_cloaked_date_pin_test.go +++ b/internal/runtime/executor/claude_cloaked_date_pin_test.go @@ -231,10 +231,8 @@ func TestClaudeCloakedDateReminderSessionByteStability(t *testing.T) { } } -// TestClaudeCloakedDateReminderDeclassifiedProbePinsSessionDate verifies that when -// a probe request is declassified into a normal request across midnight in an ongoing -// session, the declassification branch re-applies the pinned session date. -func TestClaudeCloakedDateReminderDeclassifiedProbePinsSessionDate(t *testing.T) { +// Explicit max_tokens overrides must not rerun the built-in probe date policy. +func TestClaudeCloakedDateReminderProbeOverrideDoesNotReinitializeSessionDate(t *testing.T) { helps.ResetClaudeDiagnosticsForTest() t.Cleanup(helps.ResetClaudeDiagnosticsForTest) @@ -271,8 +269,7 @@ func TestClaudeCloakedDateReminderDeclassifiedProbePinsSessionDate(t *testing.T) }, nil }) - // Use PayloadConfig to override max_tokens: 1 (which would classify as probe) to 100, - // triggering declassification via wasProbeOrHelper. + // Override max_tokens without reclassifying the original probe. cfg := &config.Config{ Payload: config.PayloadConfig{ Override: []config.PayloadRule{ @@ -313,7 +310,7 @@ func TestClaudeCloakedDateReminderDeclassifiedProbePinsSessionDate(t *testing.T) } // Request 2: Across midnight, request initially has max_tokens: 1 and content: "probe", - // but PayloadOverride declassifies it into a normal request. + // and PayloadOverride changes only the final max_tokens field. mockTime = time.Date(2026, 8, 2, 0, 1, 0, 0, time.UTC) probePayload := `{ "model": "claude-opus-5", @@ -335,11 +332,11 @@ func TestClaudeCloakedDateReminderDeclassifiedProbePinsSessionDate(t *testing.T) t.Fatalf("expected 3 captured bodies, got %d", len(capturedBodies)) } - // Both declassified requests must carry the session's pinned date ("2026-08-01") - if got := extractClaudeCloakDate(t, capturedBodies[1]); got != "2026-08-01" { - t.Fatalf("declassified Execute request date = %q, want session pinned 2026-08-01", got) + // Payload does not reclassify probes or replay the prior session date. + if got := extractClaudeCloakDate(t, capturedBodies[1]); got != "2026-08-02" { + t.Fatalf("configured Execute request date = %q, want original probe date 2026-08-02", got) } - if got := extractClaudeCloakDate(t, capturedBodies[2]); got != "2026-08-01" { - t.Fatalf("declassified ExecuteStream request date = %q, want session pinned 2026-08-01", got) + if got := extractClaudeCloakDate(t, capturedBodies[2]); got != "2026-08-02" { + t.Fatalf("configured ExecuteStream request date = %q, want original probe date 2026-08-02", got) } } diff --git a/internal/runtime/executor/claude_executor_cloaking.go b/internal/runtime/executor/claude_executor_cloaking.go index c2e34aa9fb5..ef04fc5d721 100644 --- a/internal/runtime/executor/claude_executor_cloaking.go +++ b/internal/runtime/executor/claude_executor_cloaking.go @@ -1270,11 +1270,10 @@ type claudeCodeContextManagementState struct { eligible bool callerOwned bool automaticallyInjected bool - payloadRuleTouched bool } -// reconcileClaudeCodeContextManagement resolves automatic ownership after all -// payload rules and forced tool-choice processing have completed. +// reconcileClaudeCodeContextManagement resolves built-in ownership after forced +// tool-choice processing. User payload rules run later and never need reconciliation. func reconcileClaudeCodeContextManagement(payload []byte, state claudeCodeContextManagementState) []byte { contextManagement := gjson.GetBytes(payload, "context_management") @@ -1283,7 +1282,7 @@ func reconcileClaudeCodeContextManagement(payload []byte, state claudeCodeContex // thinking field after injection, so this also covers a request that was // still eligible when injectClaudeCodeContextManagement ran. if !claudeThinkingAcceptsClearThinking(payload) { - if state.callerOwned || !state.automaticallyInjected || state.payloadRuleTouched { + if state.callerOwned || !state.automaticallyInjected { return payload } if contextManagement.Raw != claudeCodeContextManagement { @@ -1296,7 +1295,7 @@ func reconcileClaudeCodeContextManagement(payload []byte, state claudeCodeContex return updated } - if !state.eligible || state.callerOwned || state.payloadRuleTouched || contextManagement.Exists() { + if !state.eligible || state.callerOwned || contextManagement.Exists() { return payload } updated, err := sjson.SetRawBytes(payload, "context_management", []byte(claudeCodeContextManagement)) diff --git a/internal/runtime/executor/claude_executor_execute.go b/internal/runtime/executor/claude_executor_execute.go index cfda1b35263..934f2db1bfc 100644 --- a/internal/runtime/executor/claude_executor_execute.go +++ b/internal/runtime/executor/claude_executor_execute.go @@ -14,7 +14,6 @@ import ( sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" log "github.com/sirupsen/logrus" "github.com/tidwall/gjson" - "github.com/tidwall/sjson" ) func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (resp cliproxyexecutor.Response, err error) { @@ -91,8 +90,7 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r // Apply cloaking (system prompt injection, fake user ID, sensitive word obfuscation) // based on client type and configuration. _, wireSettings := resolveClaudeWirePolicy(e.cfg, auth, apiKey, confirmedClaudeCode) - bodyBeforeCloaking := body - isProbeOrHelper := helps.IsClaudeProbeOrHelperRequest(bodyBeforeCloaking) + isProbeOrHelper := helps.IsClaudeProbeOrHelperRequest(body) var cloaked bool body, cloaked, err = applyCloakingInternal( ctx, @@ -107,8 +105,6 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r if err != nil { return resp, err } - systemPlacementState := captureClaudeCodeSystemPlacement(bodyBeforeCloaking, body, cloaked) - fableState := captureClaudeCodeFableState(bodyBeforeCloaking, body, cloaked) // Only the Messages endpoint on Anthropic itself was captured; count_tokens // keeps its own shape and other gateways never see this field. diagnosticsState := claudeDiagnosticsRequestState{} @@ -126,11 +122,9 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r eligible: cloaked && isAnthropicUpstreamBase(baseURL), callerOwned: gjson.GetBytes(body, "context_management").Exists(), } - diagnosticsInjectedByCPA := false if contextManagementState.eligible { body, contextManagementState.automaticallyInjected = injectClaudeCodeContextManagement(body) if fp.InjectDiagnostics && !isProbeOrHelper { - diagnosticsInjectedByCPA = true if continuityCtx.Initialized { body, diagnosticsState = injectClaudeDiagnosticsWithState(body, continuityCtx.Key, continuityCtx.Sequence, continuityCtx.PreviousMessageID, continuityCtx.PromptID) } else { @@ -139,68 +133,6 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r } } - requestedModel := helps.PayloadRequestedModel(opts, req.Model) - requestPath := helps.PayloadRequestPath(opts) - var touchedPayloadPaths map[string]bool - body, touchedPayloadPaths = helps.ApplyPayloadConfigWithTrackedPaths( - e.cfg, - baseModel, - to.String(), - from.String(), - "", - body, - originalTranslated, - requestedModel, - requestPath, - opts.Headers, - "context_management", - "fallbacks", - "thinking.display", - "diagnostics", - ) - contextManagementState.payloadRuleTouched = touchedPayloadPaths["context_management"] - body = reconcileClaudeCodeSystemPlacementAfterPayload(body, systemPlacementState) - wasProbeOrHelper := isProbeOrHelper - isProbeOrHelper = helps.IsClaudeProbeOrHelperRequest(body) - if isProbeOrHelper { - diagnosticsState = claudeDiagnosticsRequestState{} - if diagnosticsInjectedByCPA && !touchedPayloadPaths["diagnostics"] { - body, _ = sjson.DeleteBytes(body, "diagnostics") - } - if cloaked { - body = helps.StripClaudeBillingTags(body) - } - if continuityCtx != nil { - *continuityCtx = helps.ClaudeContinuityContext{} - } - } else if wasProbeOrHelper { - // Declassified as probe (e.g. payload override changed max_tokens: 1 to normal request): - // Initialize continuity and diagnostics if cloaked and eligible. - if cloaked { - existingPrevReq, existingPromptID := helps.ExtractClaudeBillingTags(body) - prevReq, promptID, cCtx, ok := resolveClaudeContinuityTags(ctx, e.cfg, auth, incomingHeaders, body, confirmedClaudeCode, existingPrevReq, existingPromptID) - if ok { - if continuityCtx != nil { - *continuityCtx = cCtx - } - if cCtx.PinnedDate != "" { - body = injectClaudeCodeCurrentDate(body, cCtx.PinnedDate) - } - body = helps.InjectClaudeBillingTags(body, prevReq, promptID) - if fp.InjectDiagnostics && isAnthropicUpstreamBase(baseURL) { - body, diagnosticsState = injectClaudeDiagnosticsWithState(body, cCtx.Key, cCtx.Sequence, cCtx.PreviousMessageID, promptID) - } - } - } - } - body = reconcileClaudeCodeFableModelAfterPayload( - body, - fableState, - touchedPayloadPaths["fallbacks"], - touchedPayloadPaths["thinking.display"], - cloaked, - isProbeOrHelper, - ) body = ensureModelMaxTokens(body, baseModel) // Disable thinking if tool_choice forces tool use (Anthropic API constraint) @@ -248,8 +180,7 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r // Normalize TTL values to prevent ordering violations under prompt-caching-scope-2026-01-05. // A 1h-TTL block must not appear after a 5m-TTL block in evaluation order (tools→system→messages). body = normalizeCacheControlTTL(body) - // Payload rules and other request processing may rewrite stream. Keep the - // upstream body, transport headers, and response parser on one authority. + // Set the built-in transport default before the explicit payload barrier. // Native non-stream Haiku helper requests omit stream rather than sending // false, so preserve that measured wire shape when the transport agrees. streamField := gjson.GetBytes(body, "stream") @@ -259,7 +190,6 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r // Extract betas from body and convert to header var extraBetas []string - extraBetas, body = extractAndRemoveBetas(body) bodyForTranslation := body bodyForUpstream := body var oauthToolNamesReverseMap map[string]string @@ -283,15 +213,30 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r if !claudeCodeDetection.HelperProfile || claudeBodyNeedsBillingFallback(bodyForUpstream) { cchBilling = claudeCCHFallbackBillingHeader(ctx, e.cfg, bodyForUpstream, claudeCodeDetection.Entrypoint) } - bodyForUpstream, err = finalizeAnthropicMessagesBodyCCH(bodyForUpstream, cchBilling) + bodyForUpstream, err = ensureClaudeBillingHeaderCCHPlaceholder(bodyForUpstream, cchBilling) if err != nil { return resp, fmt.Errorf("finalize Claude CCH: %w", err) } } bodyForUpstream = stripDefaultKimiClaudeCodeAttribution(auth, url, fp.ProfileClaudeCodeCLI, bodyForUpstream) - // Runs on the finished body: payload rules can rewrite model and messages - // long after translation, so an earlier check would not describe the request - // that is about to be sent. + // User rules match the fully prepared business body and are applied only once. + var touchedPayloadPaths map[string]bool + bodyForUpstream, touchedPayloadPaths = helps.ApplyPayloadConfigWithTrackedPaths( + e.cfg, baseModel, to.String(), from.String(), "", bodyForUpstream, originalTranslated, + helps.PayloadRequestedModel(opts, req.Model), helps.PayloadRequestPath(opts), opts.Headers, + "diagnostics", + ) + if touchedPayloadPaths["diagnostics"] { + diagnosticsState = claudeDiagnosticsRequestState{} + } + extraBetas, bodyForUpstream = extractAndRemoveBetas(bodyForUpstream) + if cchSigning { + bodyForUpstream, err = signAnthropicMessagesBody(bodyForUpstream) + if err != nil { + return resp, fmt.Errorf("sign Claude CCH: %w", err) + } + } + // Read-only validation must observe the final configured model and messages. if errMidSystem := validateClaudeMidSystemMessageModel(bodyForUpstream, confirmedClaudeCode, isAnthropicUpstreamBase(baseURL)); errMidSystem != nil { return resp, errMidSystem } diff --git a/internal/runtime/executor/claude_executor_stream.go b/internal/runtime/executor/claude_executor_stream.go index 1356d45a90b..0ef0c91fe2e 100644 --- a/internal/runtime/executor/claude_executor_stream.go +++ b/internal/runtime/executor/claude_executor_stream.go @@ -16,7 +16,6 @@ import ( sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" log "github.com/sirupsen/logrus" "github.com/tidwall/gjson" - "github.com/tidwall/sjson" ) func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (_ *cliproxyexecutor.StreamResult, err error) { @@ -94,8 +93,7 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A // Apply cloaking (system prompt injection, fake user ID, sensitive word obfuscation) // based on client type and configuration. _, wireSettings := resolveClaudeWirePolicy(e.cfg, auth, apiKey, confirmedClaudeCode) - bodyBeforeCloaking := body - isProbeOrHelper := helps.IsClaudeProbeOrHelperRequest(bodyBeforeCloaking) + isProbeOrHelper := helps.IsClaudeProbeOrHelperRequest(body) var cloaked bool body, cloaked, err = applyCloakingInternal( ctx, @@ -110,8 +108,6 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A if err != nil { return nil, err } - systemPlacementState := captureClaudeCodeSystemPlacement(bodyBeforeCloaking, body, cloaked) - fableState := captureClaudeCodeFableState(bodyBeforeCloaking, body, cloaked) // Only the Messages endpoint on Anthropic itself was captured; count_tokens // keeps its own shape and other gateways never see this field. diagnosticsState := claudeDiagnosticsRequestState{} @@ -129,11 +125,9 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A eligible: cloaked && isAnthropicUpstreamBase(baseURL), callerOwned: gjson.GetBytes(body, "context_management").Exists(), } - diagnosticsInjectedByCPA := false if contextManagementState.eligible { body, contextManagementState.automaticallyInjected = injectClaudeCodeContextManagement(body) if fp.InjectDiagnostics && !isProbeOrHelper { - diagnosticsInjectedByCPA = true if continuityCtx.Initialized { body, diagnosticsState = injectClaudeDiagnosticsWithState(body, continuityCtx.Key, continuityCtx.Sequence, continuityCtx.PreviousMessageID, continuityCtx.PromptID) } else { @@ -142,68 +136,6 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A } } - requestedModel := helps.PayloadRequestedModel(opts, req.Model) - requestPath := helps.PayloadRequestPath(opts) - var touchedPayloadPaths map[string]bool - body, touchedPayloadPaths = helps.ApplyPayloadConfigWithTrackedPaths( - e.cfg, - baseModel, - to.String(), - from.String(), - "", - body, - originalTranslated, - requestedModel, - requestPath, - opts.Headers, - "context_management", - "fallbacks", - "thinking.display", - "diagnostics", - ) - contextManagementState.payloadRuleTouched = touchedPayloadPaths["context_management"] - body = reconcileClaudeCodeSystemPlacementAfterPayload(body, systemPlacementState) - wasProbeOrHelper := isProbeOrHelper - isProbeOrHelper = helps.IsClaudeProbeOrHelperRequest(body) - if isProbeOrHelper { - diagnosticsState = claudeDiagnosticsRequestState{} - if diagnosticsInjectedByCPA && !touchedPayloadPaths["diagnostics"] { - body, _ = sjson.DeleteBytes(body, "diagnostics") - } - if cloaked { - body = helps.StripClaudeBillingTags(body) - } - if continuityCtx != nil { - *continuityCtx = helps.ClaudeContinuityContext{} - } - } else if wasProbeOrHelper { - // Declassified as probe (e.g. payload override changed max_tokens: 1 to normal request): - // Initialize continuity and diagnostics if cloaked and eligible. - if cloaked { - existingPrevReq, existingPromptID := helps.ExtractClaudeBillingTags(body) - prevReq, promptID, cCtx, ok := resolveClaudeContinuityTags(ctx, e.cfg, auth, incomingHeaders, body, confirmedClaudeCode, existingPrevReq, existingPromptID) - if ok { - if continuityCtx != nil { - *continuityCtx = cCtx - } - if cCtx.PinnedDate != "" { - body = injectClaudeCodeCurrentDate(body, cCtx.PinnedDate) - } - body = helps.InjectClaudeBillingTags(body, prevReq, promptID) - if fp.InjectDiagnostics && isAnthropicUpstreamBase(baseURL) { - body, diagnosticsState = injectClaudeDiagnosticsWithState(body, cCtx.Key, cCtx.Sequence, cCtx.PreviousMessageID, promptID) - } - } - } - } - body = reconcileClaudeCodeFableModelAfterPayload( - body, - fableState, - touchedPayloadPaths["fallbacks"], - touchedPayloadPaths["thinking.display"], - cloaked, - isProbeOrHelper, - ) body = ensureModelMaxTokens(body, baseModel) // Disable thinking if tool_choice forces tool use (Anthropic API constraint) @@ -253,7 +185,6 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A // Extract betas from body and convert to header var extraBetas []string - extraBetas, body = extractAndRemoveBetas(body) bodyForTranslation := body bodyForUpstream := body var oauthToolNamesReverseMap map[string]string @@ -277,15 +208,30 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A if !claudeCodeDetection.HelperProfile || claudeBodyNeedsBillingFallback(bodyForUpstream) { cchBilling = claudeCCHFallbackBillingHeader(ctx, e.cfg, bodyForUpstream, claudeCodeDetection.Entrypoint) } - bodyForUpstream, err = finalizeAnthropicMessagesBodyCCH(bodyForUpstream, cchBilling) + bodyForUpstream, err = ensureClaudeBillingHeaderCCHPlaceholder(bodyForUpstream, cchBilling) if err != nil { return nil, fmt.Errorf("finalize Claude CCH: %w", err) } } bodyForUpstream = stripDefaultKimiClaudeCodeAttribution(auth, url, fp.ProfileClaudeCodeCLI, bodyForUpstream) - // Runs on the finished body: payload rules can rewrite model and messages - // long after translation, so an earlier check would not describe the request - // that is about to be sent. + // User rules match the fully prepared business body and are applied only once. + var touchedPayloadPaths map[string]bool + bodyForUpstream, touchedPayloadPaths = helps.ApplyPayloadConfigWithTrackedPaths( + e.cfg, baseModel, to.String(), from.String(), "", bodyForUpstream, originalTranslated, + helps.PayloadRequestedModel(opts, req.Model), helps.PayloadRequestPath(opts), opts.Headers, + "diagnostics", + ) + if touchedPayloadPaths["diagnostics"] { + diagnosticsState = claudeDiagnosticsRequestState{} + } + extraBetas, bodyForUpstream = extractAndRemoveBetas(bodyForUpstream) + if cchSigning { + bodyForUpstream, err = signAnthropicMessagesBody(bodyForUpstream) + if err != nil { + return nil, fmt.Errorf("sign Claude CCH: %w", err) + } + } + // Read-only validation must observe the final configured model and messages. if errMidSystem := validateClaudeMidSystemMessageModel(bodyForUpstream, confirmedClaudeCode, isAnthropicUpstreamBase(baseURL)); errMidSystem != nil { return nil, errMidSystem } diff --git a/internal/runtime/executor/claude_executor_test.go b/internal/runtime/executor/claude_executor_test.go index 5bfbe8df696..f8cfdbea19e 100644 --- a/internal/runtime/executor/claude_executor_test.go +++ b/internal/runtime/executor/claude_executor_test.go @@ -2971,7 +2971,7 @@ func TestClaudeExecutor_ExecuteOpenAINonStreamConvertsValidClaudeStream(t *testi } } -func TestClaudeExecutor_ExecuteTransportMatchesResponseFormat(t *testing.T) { +func TestClaudeExecutor_ExecutePayloadStreamOverrideDoesNotChangeResponseParser(t *testing.T) { const model = "claude-3-5-sonnet-20241022" streamResponse := strings.Join([]string{ `event: message_start`, @@ -3048,8 +3048,8 @@ func TestClaudeExecutor_ExecuteTransportMatchesResponseFormat(t *testing.T) { t.Fatalf("Execute error: %v", err) } stream := gjson.GetBytes(seenBody, "stream") - if !stream.Exists() || stream.Bool() != tt.wantStream { - t.Fatalf("upstream stream = %s, want %t; body=%s", stream.Raw, tt.wantStream, string(seenBody)) + if !stream.Exists() || stream.Bool() != !tt.wantStream { + t.Fatalf("upstream stream = %s, want %t; body=%s", stream.Raw, !tt.wantStream, string(seenBody)) } wantAccept := "application/json" wantEncoding := "gzip, deflate, br, zstd" @@ -5649,12 +5649,10 @@ func TestClaudeExecutor_SubagentAndProbeOmit1hCacheTTLAndBeta(t *testing.T) { } } -func TestClaudeExecutor_PayloadOverrideFableModelReconciled(t *testing.T) { +func TestClaudeExecutor_PayloadOverrideFableModelLeavesBuiltinsUnchanged(t *testing.T) { var seenBody []byte - var seenHeaders http.Header server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { seenBody, _ = io.ReadAll(r.Body) - seenHeaders = r.Header.Clone() w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{"id":"msg_1","type":"message","model":"claude-sonnet-5","role":"assistant","content":[{"type":"text","text":"ok"}]}`)) })) @@ -5698,26 +5696,19 @@ func TestClaudeExecutor_PayloadOverrideFableModelReconciled(t *testing.T) { t.Fatalf("model = %q, want claude-sonnet-5", got) } - // Because model is now claude-sonnet-5, Fable additions must NOT be present: - if gjson.GetBytes(seenBody, "fallbacks").Exists() { - t.Fatalf("fallbacks must be omitted when rewritten to non-Fable, got: %s", gjson.GetBytes(seenBody, "fallbacks").Raw) - } - if strings.Contains(seenHeaders.Get("Anthropic-Beta"), "server-side-fallback") { - t.Fatalf("server-side-fallback beta must be omitted when rewritten to non-Fable, got: %s", seenHeaders.Get("Anthropic-Beta")) + if gjson.GetBytes(seenBody, "fallbacks.0.model").String() != "claude-opus-5" { + t.Fatalf("payload override must not rerun built-ins: %s", seenBody) } - for _, blk := range gjson.GetBytes(seenBody, "system").Array() { - if strings.Contains(blk.Get("text").String(), "Reporting outcomes") { - t.Fatalf("system must not contain Reporting outcomes when rewritten to non-Fable, got: %s", blk.Raw) - } + if !strings.Contains(strings.ReplaceAll(gjson.GetBytes(seenBody, "system").Raw, "\u200b", ""), "eporting outcomes") { + t.Fatalf("payload override must not rerun built-ins: %s", seenBody) } + } -func TestClaudeExecutor_PayloadOverrideNonFableToFableReconciled(t *testing.T) { +func TestClaudeExecutor_PayloadOverrideNonFableModelDoesNotInjectFableBuiltins(t *testing.T) { var seenBody []byte - var seenHeaders http.Header server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { seenBody, _ = io.ReadAll(r.Body) - seenHeaders = r.Header.Clone() w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{"id":"msg_1","type":"message","model":"claude-fable-5-1","role":"assistant","content":[{"type":"text","text":"ok"}]}`)) })) @@ -5761,24 +5752,13 @@ func TestClaudeExecutor_PayloadOverrideNonFableToFableReconciled(t *testing.T) { t.Fatalf("model = %q, want claude-fable-5-1", got) } - // Fable additions must now be attached: - fallbacks := gjson.GetBytes(seenBody, "fallbacks").Array() - if len(fallbacks) != 1 || fallbacks[0].Get("model").String() != "claude-opus-5" { - t.Fatalf("fallbacks must be injected for Fable 5.1, got: %s", gjson.GetBytes(seenBody, "fallbacks").Raw) - } - if !strings.Contains(seenHeaders.Get("Anthropic-Beta"), "server-side-fallback") { - t.Fatalf("server-side-fallback beta must be present, got: %s", seenHeaders.Get("Anthropic-Beta")) - } - hasReporting := false - for _, blk := range gjson.GetBytes(seenBody, "system").Array() { - if strings.Contains(blk.Get("text").String(), "Reporting outcomes") { - hasReporting = true - break - } + if gjson.GetBytes(seenBody, "fallbacks").Exists() { + t.Fatalf("payload override must not rerun built-ins: %s", seenBody) } - if !hasReporting { - t.Fatalf("system must contain Reporting outcomes for Fable 5.1, got: %s", gjson.GetBytes(seenBody, "system").Raw) + if strings.Contains(gjson.GetBytes(seenBody, "system").Raw, "eporting outcomes") { + t.Fatalf("payload override must not rerun built-ins: %s", seenBody) } + } func TestClaudeExecutor_PayloadOverridePreservesExplicitFallbacks(t *testing.T) { @@ -5836,12 +5816,10 @@ func TestClaudeExecutor_PayloadOverridePreservesExplicitFallbacks(t *testing.T) } } -func TestClaudeExecutor_PayloadOverrideUnrelatedModelRuleDoesNotPreserveFableFallbacks(t *testing.T) { +func TestClaudeExecutor_PayloadUnrelatedRuleLeavesBuiltinFallbacksUnchanged(t *testing.T) { var seenBody []byte - var seenHeaders http.Header server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { seenBody, _ = io.ReadAll(r.Body) - seenHeaders = r.Header.Clone() w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{"id":"msg_1","type":"message","model":"claude-sonnet-5","role":"assistant","content":[{"type":"text","text":"ok"}]}`)) })) @@ -5890,21 +5868,19 @@ func TestClaudeExecutor_PayloadOverrideUnrelatedModelRuleDoesNotPreserveFableFal t.Fatalf("Execute error = %v", err) } - // Unrelated rule must NOT preserve fallback on Sonnet 5 - if gjson.GetBytes(seenBody, "fallbacks").Exists() { - t.Fatalf("unrelated rule for gpt-4 must not cause fallbacks to be preserved on sonnet-5, got: %s", gjson.GetBytes(seenBody, "fallbacks").Raw) + if gjson.GetBytes(seenBody, "fallbacks.0.model").String() != "claude-opus-5" { + t.Fatalf("payload override must not rerun built-ins: %s", seenBody) } - if strings.Contains(seenHeaders.Get("Anthropic-Beta"), "server-side-fallback") { - t.Fatalf("server-side-fallback beta must be omitted, got: %s", seenHeaders.Get("Anthropic-Beta")) + if gjson.GetBytes(seenBody, "model").String() != "claude-sonnet-5" { + t.Fatalf("payload override must not rerun built-ins: %s", seenBody) } + } -func TestClaudeExecutor_PayloadOverrideMaxTokensTo1ReclassifiesAsProbe(t *testing.T) { +func TestClaudeExecutor_PayloadMaxTokensOverrideDoesNotReclassifyBuiltins(t *testing.T) { var seenBody []byte - var seenHeaders http.Header server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { seenBody, _ = io.ReadAll(r.Body) - seenHeaders = r.Header.Clone() w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{"id":"msg_probe1","type":"message","model":"claude-sonnet-5","role":"assistant","content":[{"type":"text","text":"."}]}`)) })) @@ -5948,37 +5924,16 @@ func TestClaudeExecutor_PayloadOverrideMaxTokensTo1ReclassifiesAsProbe(t *testin t.Fatalf("max_tokens = %d, want 1", got) } - // Probe must NOT carry 1h cache control and must NOT carry extended-cache-ttl beta - if strings.Contains(seenHeaders.Get("Anthropic-Beta"), "extended-cache-ttl-2025-04-11") { - t.Fatalf("reclassified probe must not carry extended-cache-ttl beta, got: %s", seenHeaders.Get("Anthropic-Beta")) - } - for _, blk := range gjson.GetBytes(seenBody, "system").Array() { - if blk.Get("cache_control.ttl").String() == "1h" { - t.Fatalf("reclassified probe system block must not carry ttl: 1h, got: %s", blk.Raw) - } + if !strings.Contains(gjson.GetBytes(seenBody, "system").Raw, `"ttl":"1h"`) { + t.Fatalf("payload override must not rerun built-ins: %s", seenBody) } - // Probe must NOT carry diagnostics - if gjson.GetBytes(seenBody, "diagnostics").Exists() { - t.Fatalf("reclassified probe must omit diagnostics, got: %s", gjson.GetBytes(seenBody, "diagnostics").Raw) - } - - // Probe must NOT carry cc_prev_req or cc_prompt_id in billing header - billingText := gjson.GetBytes(seenBody, "system.0.text").String() - if strings.Contains(billingText, "cc_prev_req=") { - t.Fatalf("reclassified probe must omit cc_prev_req, got: %s", billingText) - } - if strings.Contains(billingText, "cc_prompt_id=") { - t.Fatalf("reclassified probe must omit cc_prompt_id, got: %s", billingText) - } } -func TestClaudeExecutor_PayloadOverrideFableToProbeStripsFableAdditions(t *testing.T) { +func TestClaudeExecutor_PayloadFableProbeOverrideKeepsBuiltinAdditions(t *testing.T) { var seenBody []byte - var seenHeaders http.Header server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { seenBody, _ = io.ReadAll(r.Body) - seenHeaders = r.Header.Clone() w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{"id":"msg_1","type":"message","model":"claude-fable-5-1","role":"assistant","content":[{"type":"text","text":"ok"}]}`)) })) @@ -6018,40 +5973,22 @@ func TestClaudeExecutor_PayloadOverrideFableToProbeStripsFableAdditions(t *testi t.Fatalf("Execute error = %v", err) } - // Because payload rule reclassified request as probe (max_tokens: 1): - // 1. fallbacks must be stripped - if gjson.GetBytes(seenBody, "fallbacks").Exists() { - t.Fatalf("probe must not carry fallbacks, got: %s", gjson.GetBytes(seenBody, "fallbacks").Raw) - } - // 2. thinking.display must be stripped - if gjson.GetBytes(seenBody, "thinking.display").Exists() { - t.Fatalf("probe must not carry thinking.display, got: %s", gjson.GetBytes(seenBody, "thinking.display").Raw) + if gjson.GetBytes(seenBody, "fallbacks.0.model").String() != "claude-opus-5" { + t.Fatalf("payload override must not rerun built-ins: %s", seenBody) } - // 3. Reporting outcomes block must be stripped - for _, blk := range gjson.GetBytes(seenBody, "system").Array() { - if strings.Contains(blk.Get("text").String(), "Reporting outcomes") { - t.Fatalf("probe must not carry Reporting outcomes block, got: %s", blk.Raw) - } + if !strings.Contains(strings.ReplaceAll(gjson.GetBytes(seenBody, "system").Raw, "\u200b", ""), "eporting outcomes") { + t.Fatalf("payload override must not rerun built-ins: %s", seenBody) } - // 4. Beta headers must omit server-side-fallback, thinking-display-updates, and extended-cache-ttl - betas := seenHeaders.Get("Anthropic-Beta") - if strings.Contains(betas, "server-side-fallback") { - t.Fatalf("probe must omit server-side-fallback beta, got: %s", betas) - } - if strings.Contains(betas, "thinking-display-updates") { - t.Fatalf("probe must omit thinking-display-updates beta, got: %s", betas) - } - if strings.Contains(betas, "extended-cache-ttl") { - t.Fatalf("probe must omit extended-cache-ttl beta, got: %s", betas) + if gjson.GetBytes(seenBody, "max_tokens").Int() != 1 || gjson.GetBytes(seenBody, "thinking.display").String() != "updates" { + t.Fatalf("payload override must not rerun built-ins: %s", seenBody) } + } -func TestClaudeExecutor_PayloadOverrideProbeToNormalReinitializes(t *testing.T) { +func TestClaudeExecutor_PayloadProbeToNormalDoesNotReinitializeBuiltins(t *testing.T) { var seenBody []byte - var seenHeaders http.Header server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { seenBody, _ = io.ReadAll(r.Body) - seenHeaders = r.Header.Clone() w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{"id":"msg_1","type":"message","model":"claude-fable-5-1","role":"assistant","content":[{"type":"text","text":"ok"}]}`)) })) @@ -6091,32 +6028,10 @@ func TestClaudeExecutor_PayloadOverrideProbeToNormalReinitializes(t *testing.T) t.Fatalf("Execute error = %v", err) } - // Declassified probe is now a normal request: - // 1. Must carry 1h cache TTL and extended-cache-ttl beta - has1h := false - for _, blk := range gjson.GetBytes(seenBody, "system").Array() { - if blk.Get("cache_control.ttl").String() == "1h" { - has1h = true - break - } - } - if !has1h { - t.Fatalf("declassified normal request must carry 1h cache, got: %s", gjson.GetBytes(seenBody, "system").Raw) - } - betas := seenHeaders.Get("Anthropic-Beta") - if !strings.Contains(betas, "extended-cache-ttl-2025-04-11") { - t.Fatalf("declassified normal request must carry extended-cache-ttl beta, got: %s", betas) - } - // 2. Must carry Fable additions (fallbacks, display, reporting block) - if !gjson.GetBytes(seenBody, "fallbacks").Exists() { - t.Fatalf("declassified Fable request must carry fallbacks") + if gjson.GetBytes(seenBody, "max_tokens").Int() != 1000 || gjson.GetBytes(seenBody, "fallbacks").Exists() || strings.Contains(gjson.GetBytes(seenBody, "system").Raw, `"ttl":"1h"`) { + t.Fatalf("payload override must not rerun built-ins: %s", seenBody) } - // 3. Must carry cc_prompt_id in billing header - billingText := gjson.GetBytes(seenBody, "system.0.text").String() - if !strings.Contains(billingText, "cc_prompt_id=") { - t.Fatalf("declassified normal request must carry cc_prompt_id, got: %s", billingText) - } } func TestClaudeExecutor_CallerOwnedDiagnosticsPreservedOnProbe(t *testing.T) { @@ -6209,7 +6124,7 @@ func TestClaudeExecutor_PayloadOverrideParentThinkingPreventsDisplayUpdates(t *t } } -func TestClaudeExecutor_PayloadSystemTTLOverrideStillRemovesInjectedFableReportingBlock(t *testing.T) { +func TestClaudeExecutor_PayloadSystemTTLOverrideKeepsBuiltinFableReporting(t *testing.T) { var seenBody []byte server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { seenBody, _ = io.ReadAll(r.Body) @@ -6252,16 +6167,16 @@ func TestClaudeExecutor_PayloadSystemTTLOverrideStillRemovesInjectedFableReporti t.Fatalf("Execute error = %v", err) } - // Model was rewritten from Fable 5.1 to Sonnet 5, so injected Reporting outcomes block - // MUST be removed even though payload rule touched system.0.cache_control.ttl! - for _, blk := range gjson.GetBytes(seenBody, "system").Array() { - if strings.Contains(blk.Get("text").String(), "Reporting outcomes") { - t.Fatalf("Reporting outcomes block must be removed on rewritten Sonnet model, got: %s", blk.Raw) - } + if !strings.Contains(strings.ReplaceAll(gjson.GetBytes(seenBody, "system").Raw, "\u200b", ""), "eporting outcomes") { + t.Fatalf("payload override must not rerun built-ins: %s", seenBody) + } + if gjson.GetBytes(seenBody, "system.0.cache_control.ttl").String() != cfg.Payload.Override[0].Params["system.0.cache_control.ttl"] { + t.Fatalf("payload override must not rerun built-ins: %s", seenBody) } + } -func TestClaudeExecutor_PayloadSonnetToFableWithSystemTTLEditsAddsReportingBlock(t *testing.T) { +func TestClaudeExecutor_PayloadSonnetToFableDoesNotAddReporting(t *testing.T) { var seenBody []byte server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { seenBody, _ = io.ReadAll(r.Body) @@ -6304,18 +6219,13 @@ func TestClaudeExecutor_PayloadSonnetToFableWithSystemTTLEditsAddsReportingBlock t.Fatalf("Execute error = %v", err) } - // Model was rewritten from Sonnet 5 to Fable 5.1, so Reporting outcomes block - // MUST be added even though payload rule touched system.1.cache_control.ttl! - hasReporting := false - for _, blk := range gjson.GetBytes(seenBody, "system").Array() { - if strings.Contains(blk.Get("text").String(), "Reporting outcomes") { - hasReporting = true - break - } + if strings.Contains(gjson.GetBytes(seenBody, "system").Raw, "eporting outcomes") { + t.Fatalf("payload override must not rerun built-ins: %s", seenBody) } - if !hasReporting { - t.Fatalf("Reporting outcomes block must be attached on rewritten Fable model, got: %s", gjson.GetBytes(seenBody, "system").Raw) + if gjson.GetBytes(seenBody, "system.1.cache_control.ttl").String() != "1h" { + t.Fatalf("payload override must not rerun built-ins: %s", seenBody) } + } func TestClaudeExecutor_PayloadOverrideProbeWithExplicitDiagnosticsPreserved(t *testing.T) { @@ -6370,7 +6280,7 @@ func TestClaudeExecutor_PayloadOverrideProbeWithExplicitDiagnosticsPreserved(t * } } -func TestClaudeExecutor_PayloadStringSystemFableAddsReportingBlock(t *testing.T) { +func TestClaudeExecutor_PayloadStringSystemFableWinsReportingBlock(t *testing.T) { var seenBody []byte server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { seenBody, _ = io.ReadAll(r.Body) @@ -6413,21 +6323,12 @@ func TestClaudeExecutor_PayloadStringSystemFableAddsReportingBlock(t *testing.T) t.Fatalf("Execute error = %v", err) } - // Payload rule set string system and rewrote to Fable 5.1: - // System must become an array containing the reporting outcomes block! - hasReporting := false - for _, blk := range gjson.GetBytes(seenBody, "system").Array() { - if strings.Contains(blk.Get("text").String(), "Reporting outcomes") { - hasReporting = true - break - } - } - if !hasReporting { - t.Fatalf("Reporting outcomes block must be attached for string system Fable request, got: %s", gjson.GetBytes(seenBody, "system").Raw) + if got := gjson.GetBytes(seenBody, "system"); got.Type != gjson.String || got.String() != cfg.Payload.Override[0].Params["system"] { + t.Fatalf("payload system override was rewritten: %s", seenBody) } } -func TestClaudeExecutor_PayloadStringSystemMentioningReportingOutcomesStillInjectsFableReportingBlock(t *testing.T) { +func TestClaudeExecutor_PayloadStringSystemMentioningReportingOutcomesStaysExact(t *testing.T) { var seenBody []byte server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { seenBody, _ = io.ReadAll(r.Body) @@ -6470,17 +6371,8 @@ func TestClaudeExecutor_PayloadStringSystemMentioningReportingOutcomesStillInjec t.Fatalf("Execute error = %v", err) } - // Payload rule had a system string that merely mentioned "reporting outcomes". - // The exact `# Reporting outcomes` block MUST be injected! - hasExactReporting := false - for _, blk := range gjson.GetBytes(seenBody, "system").Array() { - if blk.Get("text").String() == claudeCodeFableReportingOutcomes { - hasExactReporting = true - break - } - } - if !hasExactReporting { - t.Fatalf("exact `# Reporting outcomes` block must be injected even when string mentions reporting outcomes, got: %s", gjson.GetBytes(seenBody, "system").Raw) + if got := gjson.GetBytes(seenBody, "system"); got.Type != gjson.String || got.String() != cfg.Payload.Override[0].Params["system"] { + t.Fatalf("payload system override was rewritten: %s", seenBody) } } @@ -6527,18 +6419,12 @@ func TestClaudeExecutor_PayloadStringSystemWithExactReportingPromptDoesNotDuplic t.Fatalf("Execute error = %v", err) } - reportingCount := 0 - for _, blk := range gjson.GetBytes(seenBody, "system").Array() { - if blk.Get("text").String() == claudeCodeFableReportingOutcomes { - reportingCount++ - } - } - if reportingCount != 1 { - t.Fatalf("expected exactly 1 reporting block, got %d in: %s", reportingCount, gjson.GetBytes(seenBody, "system").Raw) + if got := gjson.GetBytes(seenBody, "system"); got.Type != gjson.String || got.String() != cfg.Payload.Override[0].Params["system"] { + t.Fatalf("payload system override was rewritten: %s", seenBody) } } -func TestClaudeExecutor_PayloadFableThinkingAdaptiveToDisabledDropsInjectedDisplay(t *testing.T) { +func TestClaudeExecutor_PayloadFableThinkingAdaptiveToDisabledKeepsBuiltinDisplay(t *testing.T) { var seenHeaders http.Header var seenBody []byte server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -6584,9 +6470,9 @@ func TestClaudeExecutor_PayloadFableThinkingAdaptiveToDisabledDropsInjectedDispl t.Fatalf("Execute error = %v", err) } - // Injected thinking.display must be dropped - if gjson.GetBytes(seenBody, "thinking.display").Exists() { - t.Fatalf("thinking.display must be dropped when thinking.type is disabled, got: %s", gjson.GetBytes(seenBody, "thinking").Raw) + // The scalar override does not rerun thinking normalization. + if gjson.GetBytes(seenBody, "thinking.display").String() != "updates" { + t.Fatalf("thinking.display must remain untouched by the thinking.type override, got: %s", gjson.GetBytes(seenBody, "thinking").Raw) } // thinking-display-updates beta header must NOT be present betas := seenHeaders.Get("anthropic-beta") @@ -6693,7 +6579,7 @@ func TestClaudeExecutor_FableWithSensitiveWordsHasSingleObfuscatedReportingBlock } } -func TestClaudeExecutor_PayloadSonnetToFableWithSensitiveWordsObfuscatesInjectedReportingBlock(t *testing.T) { +func TestClaudeExecutor_PayloadSonnetToFableWithSensitiveWordsDoesNotInjectReporting(t *testing.T) { var seenBody []byte server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { seenBody, _ = io.ReadAll(r.Body) @@ -6751,12 +6637,12 @@ func TestClaudeExecutor_PayloadSonnetToFableWithSensitiveWordsObfuscatesInjected } } } - if reportingCount != 1 { - t.Fatalf("expected exactly 1 reporting block, got %d; system = %s", reportingCount, gjson.GetBytes(seenBody, "system").Raw) + if reportingCount != 0 { + t.Fatalf("expected no newly injected reporting block, got %d; system = %s", reportingCount, gjson.GetBytes(seenBody, "system").Raw) } } -func TestClaudeExecutor_PayloadFableToSonnetWithSensitiveWordsRemovesReportingBlock(t *testing.T) { +func TestClaudeExecutor_PayloadFableToSonnetPreservesObfuscatedBuiltins(t *testing.T) { var seenBody []byte server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { seenBody, _ = io.ReadAll(r.Body) @@ -6800,13 +6686,13 @@ func TestClaudeExecutor_PayloadFableToSonnetWithSensitiveWordsRemovesReportingBl t.Fatalf("Execute error = %v", err) } - for _, blk := range gjson.GetBytes(seenBody, "system").Array() { - raw := blk.Get("text").String() - cleaned := strings.ReplaceAll(raw, "\u200B", "") - if cleaned == claudeCodeFableReportingOutcomes { - t.Fatalf("reporting block should be removed when rewritten to Sonnet 5, got: %s", raw) - } + if !strings.Contains(strings.ReplaceAll(gjson.GetBytes(seenBody, "system").Raw, "\u200b", ""), "eporting outcomes") { + t.Fatalf("payload override must not rerun built-ins: %s", seenBody) + } + if !strings.Contains(gjson.GetBytes(seenBody, "system").Raw, "\u200b") { + t.Fatalf("payload override must not rerun built-ins: %s", seenBody) } + } func TestClaudeExecutor_SensitiveWordsDoNotCorruptBillingHeaderTags(t *testing.T) { @@ -6953,7 +6839,7 @@ func TestClaudeExecutor_DisabledCloakingStreamSkipsSensitiveWordObfuscation(t *t } } -func TestClaudeExecutor_PayloadReplacesSystemOnOriginalFableReaddsReportingBlock(t *testing.T) { +func TestClaudeExecutor_PayloadReplacesSystemOnOriginalFableWithoutReinjection(t *testing.T) { var seenBody []byte server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { seenBody, _ = io.ReadAll(r.Body) @@ -6994,22 +6880,8 @@ func TestClaudeExecutor_PayloadReplacesSystemOnOriginalFableReaddsReportingBlock t.Fatalf("Execute error = %v", err) } - hasReplacedSystem := false - hasReporting := false - for _, blk := range gjson.GetBytes(seenBody, "system").Array() { - text := blk.Get("text").String() - if text == "Custom replaced system prompt" { - hasReplacedSystem = true - } - if text == claudeCodeFableReportingOutcomes { - hasReporting = true - } - } - if !hasReplacedSystem { - t.Fatalf("expected custom replaced system prompt in system, got: %s", gjson.GetBytes(seenBody, "system").Raw) - } - if !hasReporting { - t.Fatalf("expected Fable reporting outcomes block re-added in system, got: %s", gjson.GetBytes(seenBody, "system").Raw) + if got := gjson.GetBytes(seenBody, "system"); got.Type != gjson.String || got.String() != cfg.Payload.Override[0].Params["system"] { + t.Fatalf("payload system override was rewritten: %s", seenBody) } } @@ -8665,12 +8537,7 @@ func TestReconcileClaudeCodeContextManagement(t *testing.T) { payload: withAutomatic("disabled"), state: claudeCodeContextManagementState{eligible: true, automaticallyInjected: true}, }, - { - name: "preserves rule owned automatic object when disabled", - payload: withAutomatic("disabled"), - state: claudeCodeContextManagementState{eligible: true, automaticallyInjected: true, payloadRuleTouched: true}, - wantRaw: claudeCodeContextManagement, - }, + { name: "preserves changed automatic object when disabled", payload: `{"thinking":{"type":"disabled"},"context_management":{"edits":[{"type":"custom"}]}}`, @@ -8694,11 +8561,7 @@ func TestReconcileClaudeCodeContextManagement(t *testing.T) { payload: `{"thinking":{"type":"enabled"}}`, state: claudeCodeContextManagementState{eligible: true, callerOwned: true}, }, - { - name: "payload rule ownership prevents addition", - payload: `{"thinking":{"type":"enabled"}}`, - state: claudeCodeContextManagementState{eligible: true, payloadRuleTouched: true}, - }, + { name: "ineligible request prevents addition", payload: `{"thinking":{"type":"enabled"}}`, @@ -8926,8 +8789,8 @@ func TestClaudeExecutorPayloadOverrideReenablesThinking(t *testing.T) { if got := gjson.GetBytes(upstreamBody, "thinking.type").String(); got != test.thinkingType { t.Fatalf("final upstream thinking.type = %q, want %q; body=%s", got, test.thinkingType, upstreamBody) } - if got := gjson.GetBytes(upstreamBody, "context_management").Raw; got != claudeCodeContextManagement { - t.Fatalf("final upstream context_management = %s, want %s after payload override to %s; body=%s", got, claudeCodeContextManagement, test.thinkingType, upstreamBody) + if got := gjson.GetBytes(upstreamBody, "context_management").Raw; got != "" { + t.Fatalf("payload must not reinject context_management after enabling thinking: %s", upstreamBody) } }) } diff --git a/internal/runtime/executor/claude_executor_tokens.go b/internal/runtime/executor/claude_executor_tokens.go index 8e95d91c570..9d231566067 100644 --- a/internal/runtime/executor/claude_executor_tokens.go +++ b/internal/runtime/executor/claude_executor_tokens.go @@ -39,6 +39,10 @@ func (e *ClaudeExecutor) CountTokens(ctx context.Context, auth *cliproxyauth.Aut // Use streaming translation to preserve function calling, except for claude. stream := from != to body := helps.TranslateRequestWithAPIKeyModelCompatibility(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, stream, helps.APIKeyModelIsCompat(req)) + originalTranslatedForPayload := append([]byte(nil), body...) + if len(opts.OriginalRequest) > 0 { + originalTranslatedForPayload = helps.TranslateRequestWithAPIKeyModelCompatibility(ctx, opts.Headers, e.cfg, from, to, baseModel, opts.OriginalRequest, stream, helps.APIKeyModelIsCompat(req)) + } var errThinking error body, errThinking = helps.ApplyRequestThinking(body, req, opts, from.String(), to.String(), e.Identifier()) if errThinking != nil { @@ -48,6 +52,7 @@ func (e *ClaudeExecutor) CountTokens(ctx context.Context, auth *cliproxyauth.Aut body = rebuildMidSystemMessagesToTopLevel(body) } body = sanitizeClaudeMessagesForClaudeUpstreamWithDebug(ctx, body, baseModel, helps.APIKeyModelIsCompat(req)) + body = helps.NewPayloadFinalizer(e.cfg, e.Identifier(), baseModel, to.String(), "", originalTranslatedForPayload, req, opts)(body) if errValidate := validateClaudeTokenCountRequest(body); errValidate != nil { return cliproxyexecutor.Response{}, errValidate } @@ -144,6 +149,10 @@ func (e *ClaudeExecutor) countTokensUpstream(ctx context.Context, auth *cliproxy // Use streaming translation to preserve function calling, except for claude. stream := from != to body := helps.TranslateRequestWithAPIKeyModelCompatibility(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, stream, helps.APIKeyModelIsCompat(req)) + originalTranslatedForPayload := append([]byte(nil), body...) + if len(opts.OriginalRequest) > 0 { + originalTranslatedForPayload = helps.TranslateRequestWithAPIKeyModelCompatibility(ctx, opts.Headers, e.cfg, from, to, baseModel, opts.OriginalRequest, stream, helps.APIKeyModelIsCompat(req)) + } body = helps.SetStringIfDifferent(body, "model", upstreamModel) var errThinking error body, errThinking = helps.ApplyRequestThinking(body, req, opts, from.String(), to.String(), e.Identifier()) @@ -217,6 +226,7 @@ func (e *ClaudeExecutor) countTokensUpstream(ctx context.Context, auth *cliproxy if errMidSystem := validateClaudeMidSystemMessageModel(body, confirmedClaudeCode, directAnthropic); errMidSystem != nil { return cliproxyexecutor.Response{}, errMidSystem } + body = helps.NewPayloadFinalizer(e.cfg, e.Identifier(), baseModel, to.String(), "", originalTranslatedForPayload, req, opts)(body) httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) if err != nil { return cliproxyexecutor.Response{}, err diff --git a/internal/runtime/executor/claude_mid_system_model_test.go b/internal/runtime/executor/claude_mid_system_model_test.go index 5fcb79e7e7b..767e0aac850 100644 --- a/internal/runtime/executor/claude_mid_system_model_test.go +++ b/internal/runtime/executor/claude_mid_system_model_test.go @@ -171,8 +171,7 @@ func sendMidSystemCountTokens(t *testing.T, ex *ClaudeExecutor, ctx context.Cont return err } -// Payload rules run long after translation and can rewrite model and messages, -// so the guard has to read the finished body rather than an intermediate one. +// Read-only validation rejects an incompatible final model/messages pairing. func TestClaudeExecutor_PayloadOverrideCannotSmuggleLegacyMidSystemMessage(t *testing.T) { upstream := &midSystemUpstream{} cfg := midSystemConfig() @@ -183,7 +182,7 @@ func TestClaudeExecutor_PayloadOverrideCannotSmuggleLegacyMidSystemMessage(t *te ex := NewClaudeExecutor(cfg) // The caller addresses a model that accepts the turn; only the payload rule - // turns it into the rejected pairing. + // selects the otherwise incompatible pairing. _, err := ex.Execute(upstream.context(t, nil), midSystemAuth(), cliproxyexecutor.Request{ Model: "claude-sonnet-5", Payload: midSystemLegacyPayload("claude-sonnet-5"), }, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude}) @@ -192,7 +191,7 @@ func TestClaudeExecutor_PayloadOverrideCannotSmuggleLegacyMidSystemMessage(t *te // A caller may already have the exact role=system turn that cloaking would // otherwise insert. The message-count proof must keep that turn caller-owned, -// so a later legacy model rewrite is rejected instead of silently consuming it. +// and a later explicit model override must not silently consume it. func TestClaudeExecutor_PayloadOverrideDoesNotClaimMatchingCallerTurn(t *testing.T) { upstream := &midSystemUpstream{} cfg := midSystemConfig() @@ -214,9 +213,9 @@ func TestClaudeExecutor_PayloadOverrideDoesNotClaimMatchingCallerTurn(t *testing // Cloaking relocates a caller's system prompt into a role=system turn for models // that accept one. A payload rule can then rewrite the model to one that does -// not. Because the caller never wrote that turn, CPA must reconcile its own -// placement through the legacy reminder path instead of returning 400. -func TestClaudeExecutor_PayloadOverrideReconcilesRelocatedSystemPrompt(t *testing.T) { +// not. CPA must not rerun placement; read-only validation rejects the final +// incompatible pairing instead of silently rewriting the configured body. +func TestClaudeExecutor_PayloadOverrideDoesNotRerunSystemPlacement(t *testing.T) { for _, test := range []struct { name string send func(t *testing.T, ex *ClaudeExecutor, ctx context.Context, payload []byte) error @@ -257,28 +256,12 @@ func TestClaudeExecutor_PayloadOverrideReconcilesRelocatedSystemPrompt(t *testin `"system":[{"type":"text","text":"Caller top"}],` + `"messages":[{"role":"user","content":[{"type":"text","text":"hi"}]}]}`) - if err := test.send(t, ex, upstream.context(t, nil), payload); err != nil { - t.Fatalf("request error = %v, want CPA's inserted turn reconciled", err) - } - if !upstream.called { - t.Fatal("expected reconciled request to reach upstream") - } - if got := gjson.GetBytes(upstream.body, "model").String(); got != "claude-haiku-4-5-20251001" { - t.Fatalf("upstream model = %q, want payload override preserved", got) - } - if gjson.GetBytes(upstream.body, `messages.#(role=="system")`).Exists() { - t.Fatalf("reconciled body still carries role=system; body=%s", upstream.body) - } - if !strings.Contains(gjson.GetBytes(upstream.body, "messages.0.content").Raw, "") || - !strings.Contains(gjson.GetBytes(upstream.body, "messages.0.content").Raw, "Caller top") { - t.Fatalf("caller system prompt was not replayed as a legacy reminder; body=%s", upstream.body) - } + errSend := test.send(t, ex, upstream.context(t, nil), payload) + assertMidSystemRejected(t, errSend, upstream) }) } } -// A confirmed native caller owns its wire. It gates the turn on the model -// itself, so CPA forwards the body untouched and lets the upstream answer. func TestClaudeExecutor_ConfirmedNativeLegacyMidSystemMessageForwarded(t *testing.T) { upstream := &midSystemUpstream{} ex := NewClaudeExecutor(midSystemConfig()) @@ -484,3 +467,59 @@ func TestValidateClaudeMidSystemMessageModel(t *testing.T) { }) } } + +// Payload rules can repair an otherwise invalid caller pairing. Validation must +// inspect the configured body without translating or normalizing it again. +func TestClaudeExecutorPayloadRepairsLegacyMidSystemMessage(t *testing.T) { + const legacyModel = "claude-haiku-4-5-20251001" + const supportedModel = "claude-sonnet-5" + models := []config.PayloadModelRule{{Name: legacyModel, Protocol: "claude"}} + for _, path := range []struct { + name string + send func(*testing.T, *ClaudeExecutor, context.Context, string) error + }{ + {name: "execute", send: sendMidSystemExecute}, + {name: "stream", send: sendMidSystemStream}, + } { + for _, repair := range []struct { + name string + payload config.PayloadConfig + wantModel string + wantSystem bool + }{ + { + name: "filter system turns", + payload: config.PayloadConfig{Filter: []config.PayloadFilterRule{{Models: models, Params: []string{`messages.#(role=="system")#`}}}}, + wantModel: legacyModel, + }, + { + name: "override supported model", + payload: config.PayloadConfig{Override: []config.PayloadRule{{Models: models, Params: map[string]any{"model": supportedModel}}}}, + wantModel: supportedModel, + wantSystem: true, + }, + } { + t.Run(path.name+"/"+repair.name, func(t *testing.T) { + upstream := &midSystemUpstream{} + cfg := midSystemConfig() + cfg.Payload = repair.payload + executor := NewClaudeExecutor(cfg) + if errSend := path.send(t, executor, upstream.context(t, nil), legacyModel); errSend != nil { + t.Fatalf("configured repair rejected: %v", errSend) + } + if !upstream.called { + t.Fatal("repaired body did not reach upstream") + } + if got := gjson.GetBytes(upstream.body, "model").String(); got != repair.wantModel { + t.Fatalf("final model = %q, want %q", got, repair.wantModel) + } + if got := gjson.GetBytes(upstream.body, `messages.#(role=="system")`).Exists(); got != repair.wantSystem { + t.Fatalf("final system-turn presence = %v, want %v; body=%s", got, repair.wantSystem, upstream.body) + } + if !gjson.GetBytes(upstream.body, `messages.#(role=="user")`).Exists() { + t.Fatalf("repair removed caller user turn: %s", upstream.body) + } + }) + } + } +} diff --git a/internal/runtime/executor/codex_executor_execute.go b/internal/runtime/executor/codex_executor_execute.go index 9bc1b6a4f7b..9c768102f2e 100644 --- a/internal/runtime/executor/codex_executor_execute.go +++ b/internal/runtime/executor/codex_executor_execute.go @@ -52,9 +52,7 @@ func (e *CodexExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, re return resp, err } - requestedModel := helps.PayloadRequestedModel(opts, req.Model) - requestPath := helps.PayloadRequestPath(opts) - body = helps.ApplyPayloadConfigWithRequestForExecutor(e.cfg, e.Identifier(), baseModel, to.String(), from.String(), "", body, originalTranslated, requestedModel, requestPath, opts.Headers) + ctx = helps.WithPayloadFinalizer(ctx, helps.NewPayloadFinalizer(e.cfg, e.Identifier(), baseModel, to.String(), "", originalTranslated, req, opts)) body = helps.SetStringIfDifferent(body, "model", baseModel) body = helps.SetBoolIfDifferent(body, "stream", true) body, _ = sjson.DeleteBytes(body, "previous_response_id") @@ -235,9 +233,7 @@ func (e *CodexExecutor) executeCompact(ctx context.Context, auth *cliproxyauth.A return resp, err } - requestedModel := helps.PayloadRequestedModel(opts, req.Model) - requestPath := helps.PayloadRequestPath(opts) - body = helps.ApplyPayloadConfigWithRequestForExecutor(e.cfg, e.Identifier(), baseModel, to.String(), from.String(), "", body, originalTranslated, requestedModel, requestPath, opts.Headers) + ctx = helps.WithPayloadFinalizer(ctx, helps.NewPayloadFinalizer(e.cfg, e.Identifier(), baseModel, to.String(), "", originalTranslated, req, opts)) body = helps.SetStringIfDifferent(body, "model", baseModel) body, _ = sjson.DeleteBytes(body, "stream") body = normalizeCodexInstructions(body, helps.IsNativeCodexRequest(req.Payload, opts)) diff --git a/internal/runtime/executor/codex_executor_request.go b/internal/runtime/executor/codex_executor_request.go index 6e948f9bd3a..af8790c2f54 100644 --- a/internal/runtime/executor/codex_executor_request.go +++ b/internal/runtime/executor/codex_executor_request.go @@ -135,6 +135,7 @@ func (e *CodexExecutor) cacheHelper(ctx context.Context, from sdktranslator.Form rawJSON = helps.SetStringIfDifferent(rawJSON, "prompt_cache_key", cache.ID) } rawJSON = helps.SanitizeCodexInputItemIDs(rawJSON) + rawJSON = helps.FinalizePayload(ctx, rawJSON) httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(rawJSON)) if err != nil { return nil, nil, err diff --git a/internal/runtime/executor/codex_executor_stream.go b/internal/runtime/executor/codex_executor_stream.go index bae496f658f..a0e6a32ee41 100644 --- a/internal/runtime/executor/codex_executor_stream.go +++ b/internal/runtime/executor/codex_executor_stream.go @@ -57,9 +57,7 @@ func (e *CodexExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Au return nil, err } - requestedModel := helps.PayloadRequestedModel(opts, req.Model) - requestPath := helps.PayloadRequestPath(opts) - body = helps.ApplyPayloadConfigWithRequestForExecutor(e.cfg, e.Identifier(), baseModel, to.String(), from.String(), "", body, originalTranslated, requestedModel, requestPath, opts.Headers) + ctx = helps.WithPayloadFinalizer(ctx, helps.NewPayloadFinalizer(e.cfg, e.Identifier(), baseModel, to.String(), "", originalTranslated, req, opts)) body, _ = sjson.DeleteBytes(body, "previous_response_id") body, _ = sjson.DeleteBytes(body, "generate") body, _ = sjson.DeleteBytes(body, "prompt_cache_retention") diff --git a/internal/runtime/executor/codex_executor_tokens.go b/internal/runtime/executor/codex_executor_tokens.go index 96db686a103..50e7f1583b9 100644 --- a/internal/runtime/executor/codex_executor_tokens.go +++ b/internal/runtime/executor/codex_executor_tokens.go @@ -22,6 +22,10 @@ func (e *CodexExecutor) CountTokens(ctx context.Context, auth *cliproxyauth.Auth responseFormat := cliproxyexecutor.ResponseFormatOrSource(opts) to := sdktranslator.FromString("codex") body, updatesChanged := helps.TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntentForExecutor(ctx, opts.Headers, e.cfg, e.Identifier(), from, to, baseModel, req.Payload, false, helps.APIKeyModelIsCompat(req)) + originalTranslatedForPayload := append([]byte(nil), body...) + if len(opts.OriginalRequest) > 0 { + originalTranslatedForPayload, _ = helps.TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntentForExecutor(ctx, opts.Headers, e.cfg, e.Identifier(), from, to, baseModel, opts.OriginalRequest, false, helps.APIKeyModelIsCompat(req)) + } body, err := helps.ApplyRequestThinking(body, req, opts, from.String(), to.String(), e.Identifier(), updatesChanged) if err != nil { @@ -37,6 +41,7 @@ func (e *CodexExecutor) CountTokens(ctx context.Context, auth *cliproxyauth.Auth body = helps.SetBoolIfDifferent(body, "stream", false) body = normalizeCodexInstructions(body, helps.IsNativeCodexRequest(req.Payload, opts)) + body = helps.NewPayloadFinalizer(e.cfg, e.Identifier(), baseModel, to.String(), "", originalTranslatedForPayload, req, opts)(body) enc, err := tokenizerForCodexModel(baseModel) if err != nil { return cliproxyexecutor.Response{}, fmt.Errorf("codex executor: tokenizer init failed: %w", err) diff --git a/internal/runtime/executor/codex_openai_images.go b/internal/runtime/executor/codex_openai_images.go index 65797a3ad4e..e8e0fc0e7d5 100644 --- a/internal/runtime/executor/codex_openai_images.go +++ b/internal/runtime/executor/codex_openai_images.go @@ -110,6 +110,9 @@ func (e *CodexExecutor) executeOpenAIImage(ctx context.Context, auth *cliproxyau reporter.SetTranslatedReasoningEffort(body, "codex") url := strings.TrimSuffix(baseURL, "/") + "/responses" + payloadOpts := opts + payloadOpts.SourceFormat = sdktranslator.FromString(codexOpenAIImageSourceFormat) + ctx = helps.WithPayloadFinalizer(ctx, helps.NewPayloadFinalizer(e.cfg, e.Identifier(), mainModel, "codex", "", prepared.Body, req, payloadOpts)) httpReq, body, errCache := e.cacheHelper(ctx, sdktranslator.FromString(codexOpenAIImageSourceFormat), url, req, body) if errCache != nil { return resp, errCache @@ -205,6 +208,9 @@ func (e *CodexExecutor) executeOpenAIImageStream(ctx context.Context, auth *clip reporter.SetTranslatedReasoningEffort(body, "codex") url := strings.TrimSuffix(baseURL, "/") + "/responses" + payloadOpts := opts + payloadOpts.SourceFormat = sdktranslator.FromString(codexOpenAIImageSourceFormat) + ctx = helps.WithPayloadFinalizer(ctx, helps.NewPayloadFinalizer(e.cfg, e.Identifier(), mainModel, "codex", "", prepared.Body, req, payloadOpts)) httpReq, body, errCache := e.cacheHelper(ctx, sdktranslator.FromString(codexOpenAIImageSourceFormat), url, req, body) if errCache != nil { return nil, errCache @@ -334,6 +340,15 @@ func (e *CodexExecutor) executeDirectOpenAIImage(ctx context.Context, auth *clip if errCache != nil { return resp, errCache } + payloadOpts := opts + payloadOpts.SourceFormat = sdktranslator.FromString(codexOpenAIImageSourceFormat) + body, contentType, errPrepare = helps.ApplyMediaPayloadConfig(e.cfg, e.Identifier(), model, "openai", body, contentType, req, payloadOpts) + if errPrepare != nil { + return resp, errPrepare + } + httpReq.Body = io.NopCloser(bytes.NewReader(body)) + httpReq.ContentLength = int64(len(body)) + httpReq.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(body)), nil } applyCodexDirectImageHeaders(httpReq, auth, apiKey, false, e.cfg) applyModelHeaderOverrides(httpReq.Header, model) if contentType != "" { @@ -392,6 +407,15 @@ func (e *CodexExecutor) executeDirectOpenAIImageStream(ctx context.Context, auth if errCache != nil { return nil, errCache } + payloadOpts := opts + payloadOpts.SourceFormat = sdktranslator.FromString(codexOpenAIImageSourceFormat) + body, contentType, errPrepare = helps.ApplyMediaPayloadConfig(e.cfg, e.Identifier(), model, "openai", body, contentType, req, payloadOpts) + if errPrepare != nil { + return nil, errPrepare + } + httpReq.Body = io.NopCloser(bytes.NewReader(body)) + httpReq.ContentLength = int64(len(body)) + httpReq.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(body)), nil } applyCodexDirectImageHeaders(httpReq, auth, apiKey, true, e.cfg) applyModelHeaderOverrides(httpReq.Header, model) if contentType != "" { @@ -671,9 +695,6 @@ func (e *CodexExecutor) prepareCodexOpenAIImageBody(body []byte, req cliproxyexe return nil, errThinking } - requestedModel := helps.PayloadRequestedModel(opts, req.Model) - requestPath := helps.PayloadRequestPath(opts) - out = helps.ApplyPayloadConfigWithRequest(e.cfg, mainModel, "codex", codexOpenAIImageSourceFormat, "", out, body, requestedModel, requestPath, opts.Headers) out = helps.SetStringIfDifferent(out, "model", mainModel) out = helps.SetBoolIfDifferent(out, "stream", true) out, _ = sjson.DeleteBytes(out, "previous_response_id") diff --git a/internal/runtime/executor/codex_websockets_connection.go b/internal/runtime/executor/codex_websockets_connection.go index b9d06112274..e5171651350 100644 --- a/internal/runtime/executor/codex_websockets_connection.go +++ b/internal/runtime/executor/codex_websockets_connection.go @@ -132,14 +132,14 @@ func normalizeCodexWebsocketParallelToolCalls(body []byte, headers http.Header) } func buildCodexWebsocketRequestBody(body []byte) []byte { + return frameCodexWebsocketRequestBody(helps.SanitizeCodexInputItemIDs(body)) +} + +// Framing must not normalize the configured business payload. +func frameCodexWebsocketRequestBody(body []byte) []byte { if len(body) == 0 { return nil } - - // Match codex-rs websocket v2 semantics: every request is `response.create`. - // Incremental follow-up turns continue on the same websocket using - // `previous_response_id` + incremental `input`, not `response.append`. - body = helps.SanitizeCodexInputItemIDs(body) wsReqBody, errSet := sjson.SetBytes(body, "type", "response.create") if errSet == nil && len(wsReqBody) > 0 { return wsReqBody diff --git a/internal/runtime/executor/codex_websockets_duplex.go b/internal/runtime/executor/codex_websockets_duplex.go index 132e416936d..32bcd071758 100644 --- a/internal/runtime/executor/codex_websockets_duplex.go +++ b/internal/runtime/executor/codex_websockets_duplex.go @@ -12,6 +12,7 @@ import ( "github.com/gorilla/websocket" "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps" + "github.com/router-for-me/CLIProxyAPI/v8/internal/thinking" cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" log "github.com/sirupsen/logrus" @@ -200,7 +201,7 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( fail(cliproxyexecutor.NewUpstreamWebsocketReplayRequiredError()) return false } - payload = buildCodexWebsocketRequestBody(prepared.clientBody) + payload = frameCodexWebsocketRequestBody(prepared.clientBody) metadataMu.Lock() if len(pending) >= 16 { metadataMu.Unlock() @@ -277,6 +278,11 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( } switch gjson.GetBytes(payload, "type").String() { case "response.steer": + // Steering carries business input but must not inherit response.create defaults. + steerReq := req + steerReq.Payload = payload + payload = helps.NewPayloadFinalizer(e.cfg, "codex-websockets", thinking.ParseSuffix(req.Model).ModelName, "codex", "", payload, steerReq, opts)(payload) + payload, _ = sjson.SetBytes(payload, "type", "response.steer") parent := gjson.GetBytes(payload, "previous_response_id").String() metadataMu.Lock() settings := responseSettings[parent] @@ -295,7 +301,7 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( steeringSettings[parent] = settings } metadataMu.Unlock() - // Control frames bypass ALL response.create translations and defaults. + // Control frames bypass response.create translations and built-in defaults. // Unknown fields and unsupported input are left to upstream validation. if !cliproxyexecutor.WebsocketAuthEnabled(streamCtx, auth.ID) { fail(fmt.Errorf("websocket credential is no longer enabled")) diff --git a/internal/runtime/executor/codex_websockets_execute.go b/internal/runtime/executor/codex_websockets_execute.go index 7c6eca05d28..9b47dab12f7 100644 --- a/internal/runtime/executor/codex_websockets_execute.go +++ b/internal/runtime/executor/codex_websockets_execute.go @@ -52,9 +52,7 @@ func (e *CodexWebsocketsExecutor) Execute(ctx context.Context, auth *cliproxyaut return resp, err } - requestedModel := helps.PayloadRequestedModel(opts, req.Model) - requestPath := helps.PayloadRequestPath(opts) - body = helps.ApplyPayloadConfigWithRequestForExecutor(e.cfg, "codex-websockets", baseModel, to.String(), from.String(), "", body, originalTranslated, requestedModel, requestPath, opts.Headers) + finalizePayload := helps.NewPayloadFinalizer(e.cfg, "codex-websockets", baseModel, to.String(), "", originalTranslated, req, opts) body = helps.SetStringIfDifferent(body, "model", baseModel) body = helps.SetBoolIfDifferent(body, "stream", true) body, _ = sjson.DeleteBytes(body, "prompt_cache_retention") @@ -83,6 +81,7 @@ func (e *CodexWebsocketsExecutor) Execute(ctx context.Context, auth *cliproxyaut if errPromptCache != nil { return resp, errPromptCache } + body = finalizePayload(helps.SanitizeCodexInputItemIDs(body)) reporter.SetTranslatedReasoningEffort(body, to.String()) wsHeaders = applyCodexWebsocketHeaders(ctx, wsHeaders, auth, apiKey, e.cfg, nativeRequest, opts.Headers) applyCodexRoutingHint(ctx, wsHeaders, auth, baseModel, body, opts.Headers) @@ -115,7 +114,7 @@ func (e *CodexWebsocketsExecutor) Execute(ctx context.Context, auth *cliproxyaut sess = newEphemeralCodexWebsocketSession() } - wsReqBody := buildCodexWebsocketRequestBody(body) + wsReqBody := frameCodexWebsocketRequestBody(body) wsReqLog := helps.UpstreamRequestLog{ URL: wsURL, Method: "WEBSOCKET", @@ -226,7 +225,7 @@ func (e *CodexWebsocketsExecutor) Execute(ctx context.Context, auth *cliproxyaut } readCh = sess.activate(conn) restoreMultiAgentV2 = !multiAgentV2Conflict && (optimizeMultiAgentV2 || sess.isMultiAgentV2Optimized(conn)) - wsReqBodyRetry := buildCodexWebsocketRequestBody(body) + wsReqBodyRetry := frameCodexWebsocketRequestBody(body) helps.RecordAPIWebsocketRequest(ctx, e.cfg, helps.UpstreamRequestLog{ URL: wsURL, Method: "WEBSOCKET", diff --git a/internal/runtime/executor/codex_websockets_stream.go b/internal/runtime/executor/codex_websockets_stream.go index b6bcb49e8eb..406bfacde14 100644 --- a/internal/runtime/executor/codex_websockets_stream.go +++ b/internal/runtime/executor/codex_websockets_stream.go @@ -75,7 +75,7 @@ func (e *CodexWebsocketsExecutor) ExecuteStream(ctx context.Context, auth *clipr } } - wsReqBody := buildCodexWebsocketRequestBody(clientBody) + wsReqBody := frameCodexWebsocketRequestBody(clientBody) wsReqLog := helps.UpstreamRequestLog{ URL: wsURL, Method: "WEBSOCKET", @@ -193,7 +193,7 @@ func (e *CodexWebsocketsExecutor) ExecuteStream(ctx context.Context, auth *clipr } readCh = sess.activate(conn) restoreMultiAgentV2 = !multiAgentV2Conflict && (optimizeMultiAgentV2 || sess.isMultiAgentV2Optimized(conn)) - wsReqBodyRetry := buildCodexWebsocketRequestBody(clientBody) + wsReqBodyRetry := frameCodexWebsocketRequestBody(clientBody) helps.RecordAPIWebsocketRequest(ctx, e.cfg, helps.UpstreamRequestLog{ URL: wsURL, Method: "WEBSOCKET", @@ -774,9 +774,7 @@ func (e *CodexWebsocketsExecutor) prepareCodexWebsocketStream(ctx context.Contex return nil, err } - requestedModel := helps.PayloadRequestedModel(opts, req.Model) - requestPath := helps.PayloadRequestPath(opts) - body = helps.ApplyPayloadConfigWithRequestForExecutor(e.cfg, "codex-websockets", baseModel, to.String(), from.String(), "", body, originalTranslated, requestedModel, requestPath, opts.Headers) + finalizePayload := helps.NewPayloadFinalizer(e.cfg, "codex-websockets", baseModel, to.String(), "", originalTranslated, req, opts) body = helps.SetStringIfDifferent(body, "model", baseModel) body = normalizeCodexInstructions(body, preserveNativeOutput) if e.cfg == nil || e.cfg.DisableImageGeneration == config.DisableImageGenerationOff { @@ -802,6 +800,7 @@ func (e *CodexWebsocketsExecutor) prepareCodexWebsocketStream(ctx context.Contex if errPromptCache != nil { return nil, errPromptCache } + body = finalizePayload(helps.SanitizeCodexInputItemIDs(body)) wsHeaders = applyCodexWebsocketHeaders(ctx, wsHeaders, auth, apiKey, e.cfg, preserveNativeOutput, opts.Headers) applyCodexRoutingHint(ctx, wsHeaders, auth, baseModel, body, opts.Headers) applyModelHeaderOverrides(wsHeaders, baseModel) diff --git a/internal/runtime/executor/devin_executor.go b/internal/runtime/executor/devin_executor.go index 8a1fe47851b..17092f352f7 100644 --- a/internal/runtime/executor/devin_executor.go +++ b/internal/runtime/executor/devin_executor.go @@ -444,6 +444,15 @@ func (e *DevinExecutor) prepareDevinHTTPRequest(ctx context.Context, auth *clipr cascadeID, ) + var errPayload error + protoBytes, logBody, errPayload = helps.FinalizeDevinPayload(protoBytes, func(body []byte) []byte { + original := helps.DevinPayloadDefaultsSource(body, payload) + return helps.NewPayloadFinalizer(e.cfg, e.Identifier(), baseModel, "devin", "", original, req, opts)(body) + }) + if errPayload != nil { + return nil, "", nil, errPayload + } + framed := helps.WrapConnectEnvelope(protoBytes) url := strings.TrimRight(baseURL, "/") + helps.DevinChatPath diff --git a/internal/runtime/executor/gemini_executor.go b/internal/runtime/executor/gemini_executor.go index 4c99b073509..eac599212f0 100644 --- a/internal/runtime/executor/gemini_executor.go +++ b/internal/runtime/executor/gemini_executor.go @@ -161,7 +161,6 @@ func (e *GeminiExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r body = fixGeminiImageAspectRatio(baseModel, body) requestedModel := helps.PayloadRequestedModel(opts, req.Model) requestPath := helps.PayloadRequestPath(opts) - body = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, to.String(), from.String(), "", body, originalTranslated, requestedModel, requestPath, opts.Headers) body = helps.SetStringIfDifferent(body, "model", baseModel) body = capGeminiMaxOutputTokens(body, baseModel) body = internalsignature.SanitizeGeminiRequestThoughtSignatures(body, "contents") @@ -185,6 +184,7 @@ func (e *GeminiExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r body, _ = sjson.DeleteBytes(body, "session_id") reporter.SetTranslatedReasoningEffort(body, to.String()) + body = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, to.String(), from.String(), "", body, originalTranslated, requestedModel, requestPath, opts.Headers) httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) if err != nil { return resp, err @@ -287,7 +287,6 @@ func (e *GeminiExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A body = fixGeminiImageAspectRatio(baseModel, body) requestedModel := helps.PayloadRequestedModel(opts, req.Model) requestPath := helps.PayloadRequestPath(opts) - body = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, to.String(), from.String(), "", body, originalTranslated, requestedModel, requestPath, opts.Headers) body = helps.SetStringIfDifferent(body, "model", baseModel) body = capGeminiMaxOutputTokens(body, baseModel) body = internalsignature.SanitizeGeminiRequestThoughtSignatures(body, "contents") @@ -304,6 +303,7 @@ func (e *GeminiExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A body, _ = sjson.DeleteBytes(body, "session_id") reporter.SetTranslatedReasoningEffort(body, to.String()) + body = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, to.String(), from.String(), "", body, originalTranslated, requestedModel, requestPath, opts.Headers) httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) if err != nil { return nil, err @@ -439,11 +439,11 @@ func (e *GeminiExecutor) executeInteractions(ctx context.Context, auth *cliproxy requestedModel := helps.PayloadRequestedModel(opts, req.Model) requestPath := helps.PayloadRequestPath(opts) fromProtocol := opts.SourceFormat.String() - body = helps.ApplyPayloadConfigWithRequest(e.cfg, targetName, "interactions", fromProtocol, "", body, originalTranslated, requestedModel, requestPath, opts.Headers) body = sanitizeGeminiInteractionsUnsupportedInputIDs(body) baseURL := resolveGeminiBaseURL(auth) url := fmt.Sprintf("%s/%s/interactions", baseURL, glAPIVersion) + body = helps.ApplyPayloadConfigWithRequest(e.cfg, targetName, "interactions", fromProtocol, "", body, originalTranslated, requestedModel, requestPath, opts.Headers) httpReq, errRequest := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) if errRequest != nil { return resp, errRequest @@ -524,11 +524,11 @@ func (e *GeminiExecutor) executeInteractionsStream(ctx context.Context, auth *cl requestedModel := helps.PayloadRequestedModel(opts, req.Model) requestPath := helps.PayloadRequestPath(opts) fromProtocol := opts.SourceFormat.String() - body = helps.ApplyPayloadConfigWithRequest(e.cfg, targetName, "interactions", fromProtocol, "", body, originalTranslated, requestedModel, requestPath, opts.Headers) body = sanitizeGeminiInteractionsUnsupportedInputIDs(body) body = helps.SetBoolIfDifferent(body, "stream", true) baseURL := resolveGeminiBaseURL(auth) url := fmt.Sprintf("%s/%s/interactions", baseURL, glAPIVersion) + body = helps.ApplyPayloadConfigWithRequest(e.cfg, targetName, "interactions", fromProtocol, "", body, originalTranslated, requestedModel, requestPath, opts.Headers) httpReq, errRequest := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) if errRequest != nil { return nil, errRequest @@ -682,6 +682,10 @@ func (e *GeminiExecutor) CountTokens(ctx context.Context, auth *cliproxyauth.Aut responseFormat := cliproxyexecutor.ResponseFormatOrSource(opts) to := sdktranslator.FromString("gemini") translatedReq := helps.TranslateRequestWithAPIKeyModelCompatibility(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, false, helps.APIKeyModelIsCompat(req)) + originalTranslatedForPayload := append([]byte(nil), translatedReq...) + if len(opts.OriginalRequest) > 0 { + originalTranslatedForPayload = helps.TranslateRequestWithAPIKeyModelCompatibility(ctx, opts.Headers, e.cfg, from, to, baseModel, opts.OriginalRequest, false, helps.APIKeyModelIsCompat(req)) + } translatedReq, err := helps.ApplyRequestThinking(translatedReq, req, opts, from.String(), to.String(), e.Identifier()) if err != nil { @@ -700,6 +704,7 @@ func (e *GeminiExecutor) CountTokens(ctx context.Context, auth *cliproxyauth.Aut baseURL := resolveGeminiBaseURL(auth) url := fmt.Sprintf("%s/%s/models/%s:%s", baseURL, glAPIVersion, baseModel, "countTokens") + translatedReq = helps.NewPayloadFinalizer(e.cfg, e.Identifier(), baseModel, to.String(), "", originalTranslatedForPayload, req, opts)(translatedReq) requestBody := bytes.NewReader(translatedReq) httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, requestBody) diff --git a/internal/runtime/executor/gemini_executor_test.go b/internal/runtime/executor/gemini_executor_test.go index 6230fc19eb8..868b2ff7a50 100644 --- a/internal/runtime/executor/gemini_executor_test.go +++ b/internal/runtime/executor/gemini_executor_test.go @@ -245,7 +245,7 @@ func TestGeminiExecutorCountTokensPrependsLeadingUser(t *testing.T) { } } -func TestGeminiExecutorAppliesPayloadRulesBeforeLeadingUserNormalization(t *testing.T) { +func TestGeminiExecutorAppliesPayloadRulesAfterLeadingUserNormalization(t *testing.T) { var upstreamBody []byte server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { body, errRead := io.ReadAll(r.Body) @@ -281,11 +281,11 @@ func TestGeminiExecutorAppliesPayloadRulesBeforeLeadingUserNormalization(t *test if len(contents) != 3 || contents[0].Get("role").String() != "user" || contents[1].Get("role").String() != "model" { t.Fatalf("upstream roles malformed: %s", upstreamBody) } - if text := contents[0].Get("parts.0.text"); !text.Exists() || text.String() != "" { - t.Fatalf("synthetic leading user changed: %s", upstreamBody) + if text := contents[0].Get("parts.0.text"); !text.Exists() || text.String() != "payload override" { + t.Fatalf("payload override did not target final leading user: %s", upstreamBody) } - if got := contents[1].Get("parts.0.text").String(); got != "payload override" { - t.Fatalf("payload rule applied to %q, want original first model turn; body=%s", got, upstreamBody) + if got := contents[1].Get("parts.0.text").String(); got != "prior output" { + t.Fatalf("payload rule applied to %q, want unmodified original first model turn; body=%s", got, upstreamBody) } } diff --git a/internal/runtime/executor/gemini_vertex_executor.go b/internal/runtime/executor/gemini_vertex_executor.go index 3054d707db0..035d260402f 100644 --- a/internal/runtime/executor/gemini_vertex_executor.go +++ b/internal/runtime/executor/gemini_vertex_executor.go @@ -313,6 +313,7 @@ func (e *GeminiVertexExecutor) executeWithServiceAccount(ctx context.Context, au defer reporter.TrackFailure(ctx, &err) var body []byte + var originalTranslated []byte // Handle Imagen models with special request format if isImagenModel(baseModel) { @@ -321,6 +322,13 @@ func (e *GeminiVertexExecutor) executeWithServiceAccount(ctx context.Context, au return resp, errImagen } body = imagenBody + originalTranslated = append([]byte(nil), imagenBody...) + if len(opts.OriginalRequest) > 0 { + originalTranslated, errImagen = convertToImagenRequest(opts.OriginalRequest) + if errImagen != nil { + return resp, errImagen + } + } } else { // Standard Gemini translation flow from := opts.SourceFormat @@ -331,7 +339,7 @@ func (e *GeminiVertexExecutor) executeWithServiceAccount(ctx context.Context, au originalPayloadSource = opts.OriginalRequest } originalPayload := originalPayloadSource - originalTranslated := helps.TranslateRequestWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, baseModel, originalPayload, false) + originalTranslated = helps.TranslateRequestWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, baseModel, originalPayload, false) body = helps.TranslateRequestWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, false) body, err = helps.ApplyRequestThinking(body, req, opts, from.String(), to.String(), e.Identifier()) @@ -340,9 +348,6 @@ func (e *GeminiVertexExecutor) executeWithServiceAccount(ctx context.Context, au } body = fixGeminiImageAspectRatio(baseModel, body) - requestedModel := helps.PayloadRequestedModel(opts, req.Model) - requestPath := helps.PayloadRequestPath(opts) - body = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, to.String(), from.String(), "", body, originalTranslated, requestedModel, requestPath, opts.Headers) body = helps.SetStringIfDifferent(body, "model", baseModel) body = helps.StripVertexOpenAIResponsesToolCallIDs(body, from.String()) body = internalsignature.SanitizeGeminiRequestThoughtSignatures(body, "contents") @@ -366,6 +371,7 @@ func (e *GeminiVertexExecutor) executeWithServiceAccount(ctx context.Context, au body, _ = sjson.DeleteBytes(body, "session_id") reporter.SetTranslatedReasoningEffort(body, "gemini") + body = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, "gemini", opts.SourceFormat.String(), "", body, originalTranslated, helps.PayloadRequestedModel(opts, req.Model), helps.PayloadRequestPath(opts), opts.Headers) httpReq, errNewReq := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) if errNewReq != nil { return resp, errNewReq @@ -479,7 +485,6 @@ func (e *GeminiVertexExecutor) executeWithAPIKey(ctx context.Context, auth *clip body = fixGeminiImageAspectRatio(baseModel, body) requestedModel := helps.PayloadRequestedModel(opts, req.Model) requestPath := helps.PayloadRequestPath(opts) - body = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, to.String(), from.String(), "", body, originalTranslated, requestedModel, requestPath, opts.Headers) body = helps.SetStringIfDifferent(body, "model", baseModel) body = helps.StripVertexOpenAIResponsesToolCallIDs(body, from.String()) body = internalsignature.SanitizeGeminiRequestThoughtSignatures(body, "contents") @@ -506,6 +511,7 @@ func (e *GeminiVertexExecutor) executeWithAPIKey(ctx context.Context, auth *clip body, _ = sjson.DeleteBytes(body, "session_id") reporter.SetTranslatedReasoningEffort(body, to.String()) + body = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, to.String(), from.String(), "", body, originalTranslated, requestedModel, requestPath, opts.Headers) httpReq, errNewReq := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) if errNewReq != nil { return resp, errNewReq @@ -606,7 +612,6 @@ func (e *GeminiVertexExecutor) executeStreamWithServiceAccount(ctx context.Conte body = fixGeminiImageAspectRatio(baseModel, body) requestedModel := helps.PayloadRequestedModel(opts, req.Model) requestPath := helps.PayloadRequestPath(opts) - body = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, to.String(), from.String(), "", body, originalTranslated, requestedModel, requestPath, opts.Headers) body = helps.SetStringIfDifferent(body, "model", baseModel) body = helps.StripVertexOpenAIResponsesToolCallIDs(body, from.String()) body = internalsignature.SanitizeGeminiRequestThoughtSignatures(body, "contents") @@ -626,6 +631,7 @@ func (e *GeminiVertexExecutor) executeStreamWithServiceAccount(ctx context.Conte body, _ = sjson.DeleteBytes(body, "session_id") reporter.SetTranslatedReasoningEffort(body, to.String()) + body = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, to.String(), from.String(), "", body, originalTranslated, requestedModel, requestPath, opts.Headers) httpReq, errNewReq := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) if errNewReq != nil { return nil, errNewReq @@ -774,7 +780,6 @@ func (e *GeminiVertexExecutor) executeStreamWithAPIKey(ctx context.Context, auth body = fixGeminiImageAspectRatio(baseModel, body) requestedModel := helps.PayloadRequestedModel(opts, req.Model) requestPath := helps.PayloadRequestPath(opts) - body = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, to.String(), from.String(), "", body, originalTranslated, requestedModel, requestPath, opts.Headers) body = helps.SetStringIfDifferent(body, "model", baseModel) body = helps.StripVertexOpenAIResponsesToolCallIDs(body, from.String()) body = internalsignature.SanitizeGeminiRequestThoughtSignatures(body, "contents") @@ -797,6 +802,7 @@ func (e *GeminiVertexExecutor) executeStreamWithAPIKey(ctx context.Context, auth body, _ = sjson.DeleteBytes(body, "session_id") reporter.SetTranslatedReasoningEffort(body, to.String()) + body = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, to.String(), from.String(), "", body, originalTranslated, requestedModel, requestPath, opts.Headers) httpReq, errNewReq := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) if errNewReq != nil { return nil, errNewReq @@ -924,6 +930,10 @@ func (e *GeminiVertexExecutor) countTokensWithServiceAccount(ctx context.Context to := sdktranslator.FromString("gemini") translatedReq := helps.TranslateRequestWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, false) + originalTranslatedForPayload := append([]byte(nil), translatedReq...) + if len(opts.OriginalRequest) > 0 { + originalTranslatedForPayload = helps.TranslateRequestWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, baseModel, opts.OriginalRequest, false) + } translatedReq, err := helps.ApplyRequestThinking(translatedReq, req, opts, from.String(), to.String(), e.Identifier()) if err != nil { @@ -943,6 +953,7 @@ func (e *GeminiVertexExecutor) countTokensWithServiceAccount(ctx context.Context baseURL := vertexBaseURL(location) url := fmt.Sprintf("%s/%s/projects/%s/locations/%s/publishers/google/models/%s:%s", baseURL, vertexAPIVersion, projectID, location, baseModel, "countTokens") + translatedReq = helps.NewPayloadFinalizer(e.cfg, e.Identifier(), baseModel, to.String(), "", originalTranslatedForPayload, req, opts)(translatedReq) httpReq, errNewReq := http.NewRequestWithContext(respCtx, http.MethodPost, url, bytes.NewReader(translatedReq)) if errNewReq != nil { return cliproxyexecutor.Response{}, errNewReq @@ -1018,6 +1029,10 @@ func (e *GeminiVertexExecutor) countTokensWithAPIKey(ctx context.Context, auth * to := sdktranslator.FromString("gemini") translatedReq := helps.TranslateRequestWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, false) + originalTranslatedForPayload := append([]byte(nil), translatedReq...) + if len(opts.OriginalRequest) > 0 { + originalTranslatedForPayload = helps.TranslateRequestWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, baseModel, opts.OriginalRequest, false) + } translatedReq, err := helps.ApplyRequestThinking(translatedReq, req, opts, from.String(), to.String(), e.Identifier()) if err != nil { @@ -1040,6 +1055,7 @@ func (e *GeminiVertexExecutor) countTokensWithAPIKey(ctx context.Context, auth * } url := fmt.Sprintf("%s/%s/publishers/google/models/%s:%s", baseURL, vertexAPIVersion, baseModel, "countTokens") + translatedReq = helps.NewPayloadFinalizer(e.cfg, e.Identifier(), baseModel, to.String(), "", originalTranslatedForPayload, req, opts)(translatedReq) httpReq, errNewReq := http.NewRequestWithContext(respCtx, http.MethodPost, url, bytes.NewReader(translatedReq)) if errNewReq != nil { return cliproxyexecutor.Response{}, errNewReq diff --git a/internal/runtime/executor/helps/devin_payload.go b/internal/runtime/executor/helps/devin_payload.go new file mode 100644 index 00000000000..19d2b75f016 --- /dev/null +++ b/internal/runtime/executor/helps/devin_payload.go @@ -0,0 +1,227 @@ +package helps + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "fmt" + "math" + + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" + "google.golang.org/protobuf/encoding/protowire" +) + +// Devin payload rules address the native business fields, never credentials or +// Connect framing. Encoding after the barrier does not inject defaults or sanitize. +type devinPayloadField struct { + name string + kind protowire.Type + repeated bool + binary bool + jsonValue bool + children map[protowire.Number]devinPayloadField +} + +var devinPayloadFields = map[protowire.Number]devinPayloadField{ + 2: {name: "system_prompt", kind: protowire.BytesType}, + 3: {name: "prompts", kind: protowire.BytesType, repeated: true, children: map[protowire.Number]devinPayloadField{ + 1: {name: "id", kind: protowire.BytesType}, + 2: {name: "source", kind: protowire.VarintType}, + 3: {name: "content", kind: protowire.BytesType}, + 6: {name: "tool_calls", kind: protowire.BytesType, repeated: true, children: map[protowire.Number]devinPayloadField{ + 1: {name: "id", kind: protowire.BytesType}, + 2: {name: "name", kind: protowire.BytesType}, + 3: {name: "arguments", kind: protowire.BytesType}, + }}, + 7: {name: "tool_call_id", kind: protowire.BytesType}, + 10: {name: "images", kind: protowire.BytesType, repeated: true, children: map[protowire.Number]devinPayloadField{ + 1: {name: "data", kind: protowire.BytesType}, + 2: {name: "mime_type", kind: protowire.BytesType}, + }}, + 11: {name: "thinking", kind: protowire.BytesType}, + 12: {name: "signature", kind: protowire.BytesType, binary: true}, + 18: {name: "signature_type", kind: protowire.BytesType}, + }}, + 8: {name: "completion_config", kind: protowire.BytesType, children: map[protowire.Number]devinPayloadField{ + 1: {name: "enabled", kind: protowire.VarintType}, + 2: {name: "max_tokens", kind: protowire.VarintType}, + 3: {name: "parameter_3", kind: protowire.VarintType}, + 5: {name: "temperature", kind: protowire.Fixed64Type}, + 7: {name: "top_k", kind: protowire.VarintType}, + 8: {name: "top_p", kind: protowire.Fixed64Type}, + }}, + 10: {name: "tools", kind: protowire.BytesType, repeated: true, children: map[protowire.Number]devinPayloadField{ + 1: {name: "name", kind: protowire.BytesType}, + 2: {name: "description", kind: protowire.BytesType}, + 3: {name: "parameters", kind: protowire.BytesType, jsonValue: true}, + }}, + 16: {name: "cascade_id", kind: protowire.BytesType}, + 21: {name: "model", kind: protowire.BytesType}, +} + +// DevinPayloadDefaultsSource maps caller field presence to the native business +// view so defaults can replace built-in values without replacing caller values. +func DevinPayloadDefaultsSource(native, interactions []byte) []byte { + out := []byte(`{}`) + for target, sources := range map[string][]string{ + "model": {"model"}, + "system_prompt": {"system_instruction", "systemInstruction"}, + "prompts": {"input"}, + "tools": {"tools"}, + "cascade_id": {"session_id", "sessionId", "conversation_id", "previous_interaction_id"}, + "completion_config.max_tokens": {"generation_config.max_output_tokens", "generationConfig.max_output_tokens"}, + "completion_config.temperature": {"generation_config.temperature", "generationConfig.temperature", "temperature"}, + "completion_config.top_k": {"generation_config.top_k", "generationConfig.top_k"}, + "completion_config.top_p": {"generation_config.top_p", "generationConfig.top_p"}, + } { + var value gjson.Result + for _, source := range sources { + value = gjson.GetBytes(interactions, source) + if value.Exists() { + break + } + } + if !value.Exists() { + continue + } + if target == "prompts" || target == "tools" { + value = gjson.GetBytes(native, target) + } + if value.Exists() { + out, _ = sjson.SetRawBytes(out, target, []byte(value.Raw)) + } + } + return out +} + +// FinalizeDevinPayload projects the already-normalized protobuf business fields +// to JSON for user rules, then replaces only those fields in the wire message. +func FinalizeDevinPayload(wire []byte, finalize PayloadFinalizer) ([]byte, []byte, error) { + view, errDecode := decodeDevinPayload(wire, devinPayloadFields) + if errDecode != nil { + return nil, nil, errDecode + } + body, errMarshal := json.Marshal(view) + if errMarshal != nil { + return nil, nil, errMarshal + } + configured := finalize(body) + if bytes.Equal(configured, body) { + return wire, configured, nil + } + body = configured + out, errEncode := encodeDevinPayload(wire, gjson.ParseBytes(body), devinPayloadFields) + return out, body, errEncode +} + +func decodeDevinPayload(wire []byte, fields map[protowire.Number]devinPayloadField) (map[string]any, error) { + out := make(map[string]any) + for len(wire) > 0 { + num, kind, tagLen := protowire.ConsumeTag(wire) + if tagLen < 0 { + return nil, protowire.ParseError(tagLen) + } + wire = wire[tagLen:] + n := protowire.ConsumeFieldValue(num, kind, wire) + if n < 0 { + return nil, protowire.ParseError(n) + } + field, ok := fields[num] + if ok { + var value any + switch kind { + case protowire.BytesType: + data, _ := protowire.ConsumeBytes(wire) + switch { + case field.children != nil: + decoded, errDecode := decodeDevinPayload(data, field.children) + if errDecode != nil { + return nil, errDecode + } + value = decoded + case field.binary: + value = base64.StdEncoding.EncodeToString(data) + case field.jsonValue && json.Valid(data): + value = json.RawMessage(data) + default: + value = string(data) + } + case protowire.VarintType: + value, _ = protowire.ConsumeVarint(wire) + case protowire.Fixed64Type: + bits, _ := protowire.ConsumeFixed64(wire) + value = math.Float64frombits(bits) + } + if field.repeated { + values, _ := out[field.name].([]any) + out[field.name] = append(values, value) + } else { + out[field.name] = value + } + } + wire = wire[n:] + } + return out, nil +} + +func encodeDevinPayload(original []byte, body gjson.Result, fields map[protowire.Number]devinPayloadField) ([]byte, error) { + var out []byte + // Credentials, device metadata, thread ordinals, and protocol flags stay opaque. + for len(original) > 0 { + num, kind, tagLen := protowire.ConsumeTag(original) + if tagLen < 0 { + return nil, protowire.ParseError(tagLen) + } + n := protowire.ConsumeFieldValue(num, kind, original[tagLen:]) + if n < 0 { + return nil, protowire.ParseError(n) + } + if _, ok := fields[num]; !ok { + out = append(out, original[:tagLen+n]...) + } + original = original[tagLen+n:] + } + for num := protowire.Number(1); num <= 21; num++ { + field, ok := fields[num] + if !ok { + continue + } + value := body.Get(field.name) + if !value.Exists() || value.Type == gjson.Null { + continue + } + values := []gjson.Result{value} + if field.repeated { + values = value.Array() + } + for _, item := range values { + out = protowire.AppendTag(out, num, field.kind) + switch field.kind { + case protowire.BytesType: + data := []byte(item.String()) + if field.children != nil { + var errEncode error + data, errEncode = encodeDevinPayload(nil, item, field.children) + if errEncode != nil { + return nil, errEncode + } + } else if field.binary { + var errDecode error + data, errDecode = base64.StdEncoding.DecodeString(item.String()) + if errDecode != nil { + return nil, fmt.Errorf("Devin payload %s: %w", field.name, errDecode) + } + } else if field.jsonValue { + data = []byte(item.Raw) + } + out = protowire.AppendBytes(out, data) + case protowire.VarintType: + out = protowire.AppendVarint(out, item.Uint()) + case protowire.Fixed64Type: + out = protowire.AppendFixed64(out, math.Float64bits(item.Float())) + } + } + } + return out, nil +} diff --git a/internal/runtime/executor/helps/payload_finalizer.go b/internal/runtime/executor/helps/payload_finalizer.go new file mode 100644 index 00000000000..68bb79c0592 --- /dev/null +++ b/internal/runtime/executor/helps/payload_finalizer.go @@ -0,0 +1,38 @@ +package helps + +import ( + "context" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" +) + +// PayloadFinalizer applies user rules to a fully prepared business payload. +// Each rebuilt attempt must start from the unconfigured body, not a previous result. +type PayloadFinalizer func([]byte) []byte + +// NewPayloadFinalizer snapshots matching context before built-in request mutations. +func NewPayloadFinalizer(cfg *config.Config, executor, model, protocol, root string, original []byte, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) PayloadFinalizer { + requestedModel := PayloadRequestedModel(opts, req.Model) + requestPath := PayloadRequestPath(opts) + headers := opts.Headers.Clone() + source := append([]byte(nil), original...) + return func(body []byte) []byte { + return ApplyPayloadConfigWithRequestForExecutor(cfg, executor, model, protocol, opts.SourceFormat.String(), root, body, source, requestedModel, requestPath, headers) + } +} + +type payloadFinalizerKey struct{} + +// WithPayloadFinalizer carries the final barrier through shared request builders. +func WithPayloadFinalizer(ctx context.Context, finalize PayloadFinalizer) context.Context { + return context.WithValue(ctx, payloadFinalizerKey{}, finalize) +} + +// FinalizePayload runs immediately before serialization or transport framing. +func FinalizePayload(ctx context.Context, body []byte) []byte { + if finalize, ok := ctx.Value(payloadFinalizerKey{}).(PayloadFinalizer); ok && finalize != nil { + return finalize(body) + } + return body +} diff --git a/internal/runtime/executor/helps/payload_finalizer_test.go b/internal/runtime/executor/helps/payload_finalizer_test.go new file mode 100644 index 00000000000..dcbe961f012 --- /dev/null +++ b/internal/runtime/executor/helps/payload_finalizer_test.go @@ -0,0 +1,122 @@ +package helps + +import ( + "bytes" + "context" + "mime/multipart" + "net/http" + "testing" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" + "google.golang.org/protobuf/encoding/protowire" +) + +func TestPayloadFinalizerDefaultsUseOriginalAndNormalizeBeforeRules(t *testing.T) { + cfg := &config.Config{Payload: config.PayloadConfig{ + Default: []config.PayloadRule{{Models: []config.PayloadModelRule{{Name: "alias", Protocol: "openai", FromProtocol: "claude", Headers: map[string]string{"X-Test": "yes"}}}, Params: map[string]any{"missing": "user default", "present": "not applied"}}}, + Override: []config.PayloadRule{{Models: []config.PayloadModelRule{{Name: "alias"}}, Params: map[string]any{"tools.0.function.parameters.properties.count.type": "number"}}}, + Filter: []config.PayloadFilterRule{{Models: []config.PayloadModelRule{{Name: "alias"}}, Params: []string{"late"}}}, + }} + req := cliproxyexecutor.Request{Model: "alias"} + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude, Headers: http.Header{"X-Test": {"yes"}, "User-Agent": {"codex-cli/0.1"}}} + finalize := NewPayloadFinalizer(cfg, "openai", "upstream", "openai", "", []byte(`{"present":"caller"}`), req, opts) + body := []byte(`{"missing":"built-in","present":"caller","late":"injected","tools":[{"type":"function","function":{"name":"f","parameters":{"type":"object","properties":{"count":{"type":"integer"}}}}}]}`) + out := FinalizePayload(WithPayloadFinalizer(context.Background(), finalize), body) + if gjson.GetBytes(out, "missing").String() != "user default" || gjson.GetBytes(out, "present").String() != "caller" || gjson.GetBytes(out, "late").Exists() || gjson.GetBytes(out, "tools.0.function.parameters.properties.count.type").String() != "number" { + t.Fatalf("unexpected final payload: %s", out) + } +} + +func TestPayloadFinalizerDevinBusinessFieldsAndCredentials(t *testing.T) { + wire := BuildDevinGetChatMessageRequest("secret-token", "device", "model", "system", []DevinPrompt{{MessageID: "id", Source: 1, Content: "hello"}}, []DevinTool{{Name: "f", Parameters: []byte(`{"type":"object"}`)}}, nil, 1024, "session", "cascade", nil) + unchanged, _, errUnchanged := FinalizeDevinPayload(wire, func(body []byte) []byte { return body }) + if errUnchanged != nil || !bytes.Equal(unchanged, wire) { + t.Fatalf("no-op changed protobuf: %v", errUnchanged) + } + final, view, errFinalize := FinalizeDevinPayload(wire, func(body []byte) []byte { + body, _ = sjson.DeleteBytes(body, "system_prompt") + body, _ = sjson.DeleteBytes(body, "tools") + body, _ = sjson.SetBytes(body, "completion_config.max_tokens", 0) + body, _ = sjson.SetBytes(body, "prompts.0.content", "configured") + return body + }) + if errFinalize != nil { + t.Fatal(errFinalize) + } + if gjson.GetBytes(view, "system_prompt").Exists() || gjson.GetBytes(view, "tools").Exists() { + t.Fatalf("filter undone: %s", view) + } + decoded, errDecode := decodeDevinPayload(final, devinPayloadFields) + if errDecode != nil { + t.Fatal(errDecode) + } + if decoded["completion_config"].(map[string]any)["max_tokens"] != uint64(0) { + t.Fatalf("default was re-injected: %v", decoded) + } + fieldOne := func(wire []byte) []byte { + for len(wire) > 0 { + num, kind, tagLen := protowire.ConsumeTag(wire) + n := protowire.ConsumeFieldValue(num, kind, wire[tagLen:]) + if num == 1 { + return wire[:tagLen+n] + } + wire = wire[tagLen+n:] + } + return nil + } + if !bytes.Equal(fieldOne(wire), fieldOne(final)) { + t.Fatal("payload rules changed credentials") + } +} + +func TestPayloadFinalizerMultipartPreservesFiles(t *testing.T) { + var buffer bytes.Buffer + writer := multipart.NewWriter(&buffer) + if errWrite := writer.WriteField("model", "original"); errWrite != nil { + t.Fatal(errWrite) + } + file, errFile := writer.CreateFormFile("image", "input.png") + if errFile != nil { + t.Fatal(errFile) + } + if _, errWrite := file.Write([]byte{0, 255, 13, 10}); errWrite != nil { + t.Fatal(errWrite) + } + if errClose := writer.Close(); errClose != nil { + t.Fatal(errClose) + } + cfg := &config.Config{Payload: config.PayloadConfig{Override: []config.PayloadRule{{Models: []config.PayloadModelRule{{Name: "original"}}, Params: map[string]any{"model": "configured"}}}}} + req := cliproxyexecutor.Request{Model: "original", Payload: buffer.Bytes()} + opts := cliproxyexecutor.Options{Headers: http.Header{"Content-Type": {writer.FormDataContentType()}}} + body, contentType, errFinalize := ApplyMediaPayloadConfig(cfg, "openai", "original", "openai", req.Payload, writer.FormDataContentType(), req, opts) + if errFinalize != nil { + t.Fatal(errFinalize) + } + view, _, errView := mediaPayloadJSON(body, contentType) + if errView != nil { + t.Fatal(errView) + } + if gjson.GetBytes(view, "model").String() != "configured" || gjson.GetBytes(view, "image.data").String() != "AP8NCg==" { + t.Fatalf("unexpected multipart business payload: %s", view) + } +} + +func TestPayloadRulesMatchFinalBodyAndTrackPaths(t *testing.T) { + cfg := &config.Config{Payload: config.PayloadConfig{ + Override: []config.PayloadRule{{Models: []config.PayloadModelRule{{Name: "*", Match: []map[string]any{{"max_tokens": 100}}}}, Params: map[string]any{"unexpected": true}}, + {Models: []config.PayloadModelRule{{Name: "*", Match: []map[string]any{{"max_tokens": 300}}}}, Params: map[string]any{"diagnostics.user": true}}}, + Filter: []config.PayloadFilterRule{{Models: []config.PayloadModelRule{{Name: "*", Match: []map[string]any{{"max_tokens": 300}}}}, Params: []string{"context_management", "messages.0"}}}, + }} + original := []byte(`{"max_tokens":100,"messages":[{},{}]}`) + body, touched := ApplyPayloadConfigWithTrackedPaths(cfg, "model", "claude", "claude", "", []byte(`{"max_tokens":300,"context_management":{"builtin":true},"messages":[{},{},{}]}`), original, "model", "", nil, "diagnostics", "context_management") + if gjson.GetBytes(body, "unexpected").Exists() || !gjson.GetBytes(body, "diagnostics.user").Bool() || gjson.GetBytes(body, "context_management").Exists() || gjson.GetBytes(body, "messages.#").Int() != 2 { + t.Fatalf("rules did not match final body: %s", body) + } + if !touched["diagnostics"] || !touched["context_management"] { + t.Fatalf("final tracking lost: %v", touched) + } +} diff --git a/internal/runtime/executor/helps/payload_media.go b/internal/runtime/executor/helps/payload_media.go new file mode 100644 index 00000000000..47bbd95cff4 --- /dev/null +++ b/internal/runtime/executor/helps/payload_media.go @@ -0,0 +1,120 @@ +package helps + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "fmt" + "io" + "mime" + "mime/multipart" + "net/textproto" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + "github.com/tidwall/gjson" +) + +// ApplyMediaPayloadConfig exposes multipart fields as JSON business values. File +// parts use {filename, content_type, data} with base64 data; framing stays opaque. +func ApplyMediaPayloadConfig(cfg *config.Config, executor, model, protocol string, body []byte, contentType string, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) ([]byte, string, error) { + view, multipartBody, errDecode := mediaPayloadJSON(body, contentType) + if errDecode != nil { + return nil, "", errDecode + } + original := req.Payload + if len(opts.OriginalRequest) > 0 { + original = opts.OriginalRequest + } + originalView, _, errOriginal := mediaPayloadJSON(original, opts.Headers.Get("Content-Type")) + if errOriginal != nil { + return nil, "", errOriginal + } + out := NewPayloadFinalizer(cfg, executor, model, protocol, "", originalView, req, opts)(view) + if !multipartBody || bytes.Equal(out, view) { + return outOrBody(out, body, multipartBody), contentType, nil + } + var buffer bytes.Buffer + writer := multipart.NewWriter(&buffer) + for key, value := range gjson.ParseBytes(out).Map() { + values := []gjson.Result{value} + if value.IsArray() { + values = value.Array() + } + for _, item := range values { + if item.IsObject() && item.Get("filename").Exists() { + data, errData := base64.StdEncoding.DecodeString(item.Get("data").String()) + if errData != nil { + return nil, "", fmt.Errorf("multipart payload %s: %w", key, errData) + } + header := make(textproto.MIMEHeader) + header.Set("Content-Disposition", mime.FormatMediaType("form-data", map[string]string{"name": key, "filename": item.Get("filename").String()})) + header.Set("Content-Type", item.Get("content_type").String()) + part, errPart := writer.CreatePart(header) + if errPart != nil { + return nil, "", errPart + } + if _, errWrite := part.Write(data); errWrite != nil { + return nil, "", errWrite + } + } else if errWrite := writer.WriteField(key, item.String()); errWrite != nil { + return nil, "", errWrite + } + } + } + if errClose := writer.Close(); errClose != nil { + return nil, "", errClose + } + return buffer.Bytes(), writer.FormDataContentType(), nil +} + +func outOrBody(out, body []byte, multipartBody bool) []byte { + if multipartBody { + return body + } + return out +} + +func mediaPayloadJSON(body []byte, contentType string) ([]byte, bool, error) { + if json.Valid(body) { + return body, false, nil + } + mediaType, params, errParse := mime.ParseMediaType(contentType) + if errParse != nil || mediaType != "multipart/form-data" { + return body, false, nil + } + reader := multipart.NewReader(bytes.NewReader(body), params["boundary"]) + fields := make(map[string]any) + for { + part, errNext := reader.NextPart() + if errNext == io.EOF { + break + } + if errNext != nil { + return nil, false, errNext + } + data, errRead := io.ReadAll(part) + if errClose := part.Close(); errClose != nil { + return nil, false, errClose + } + if errRead != nil { + return nil, false, errRead + } + var value any = string(data) + if part.FileName() != "" { + value = map[string]string{"filename": part.FileName(), "content_type": part.Header.Get("Content-Type"), "data": base64.StdEncoding.EncodeToString(data)} + } + key := part.FormName() + if previous, ok := fields[key]; ok { + values, isArray := previous.([]any) + if !isArray { + values = []any{previous} + } + fields[key] = append(values, value) + } else { + fields[key] = value + } + } + view, errMarshal := json.Marshal(fields) + return view, true, errMarshal +} diff --git a/internal/runtime/executor/kimi_executor.go b/internal/runtime/executor/kimi_executor.go index 877e07ebf8c..126e1e81249 100644 --- a/internal/runtime/executor/kimi_executor.go +++ b/internal/runtime/executor/kimi_executor.go @@ -151,7 +151,6 @@ func (e *KimiExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, req requestedModel := helps.PayloadRequestedModel(opts, req.Model) requestPath := helps.PayloadRequestPath(opts) - body = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, to.String(), from.String(), "", body, originalTranslated, requestedModel, requestPath, opts.Headers) body, err = normalizeKimiToolMessageLinks(body) if err != nil { return resp, err @@ -161,6 +160,7 @@ func (e *KimiExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, req reporter.SetTranslatedReasoningEffort(body, e.Identifier()) url := helps.ResolveKimiChatURL(auth) + body = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, to.String(), from.String(), "", body, originalTranslated, requestedModel, requestPath, opts.Headers) httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) if err != nil { return resp, err @@ -290,7 +290,6 @@ func (e *KimiExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Aut } requestedModel := helps.PayloadRequestedModel(opts, req.Model) requestPath := helps.PayloadRequestPath(opts) - body = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, to.String(), from.String(), "", body, originalTranslated, requestedModel, requestPath, opts.Headers) body, err = normalizeKimiToolMessageLinks(body) if err != nil { return nil, err @@ -300,6 +299,7 @@ func (e *KimiExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Aut reporter.SetTranslatedReasoningEffort(body, e.Identifier()) url := helps.ResolveKimiChatURL(auth) + body = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, to.String(), from.String(), "", body, originalTranslated, requestedModel, requestPath, opts.Headers) httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) if err != nil { return nil, err @@ -434,7 +434,6 @@ func (e *KimiExecutor) executeResponses(ctx context.Context, auth *cliproxyauth. requestedModel := helps.PayloadRequestedModel(opts, req.Model) requestPath := helps.PayloadRequestPath(opts) - body = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, "openai-response", opts.SourceFormat.String(), "", body, req.Payload, requestedModel, requestPath, opts.Headers) var errNormalizePatch error body, errNormalizePatch = helps.NormalizeApplyPatchResponsesRequest(body) if errNormalizePatch != nil { @@ -450,6 +449,7 @@ func (e *KimiExecutor) executeResponses(ctx context.Context, auth *cliproxyauth. reporter.SetTranslatedReasoningEffort(body, e.Identifier()) url := helps.ResolveKimiResponsesURL(auth) + body = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, "openai-response", opts.SourceFormat.String(), "", body, req.Payload, requestedModel, requestPath, opts.Headers) httpReq, errNewRequest := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) if errNewRequest != nil { return resp, errNewRequest @@ -566,7 +566,6 @@ func (e *KimiExecutor) executeResponsesStream(ctx context.Context, auth *cliprox requestedModel := helps.PayloadRequestedModel(opts, req.Model) requestPath := helps.PayloadRequestPath(opts) - body = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, "openai-response", opts.SourceFormat.String(), "", body, req.Payload, requestedModel, requestPath, opts.Headers) var errNormalizePatch error body, errNormalizePatch = helps.NormalizeApplyPatchResponsesRequest(body) if errNormalizePatch != nil { @@ -582,6 +581,7 @@ func (e *KimiExecutor) executeResponsesStream(ctx context.Context, auth *cliprox reporter.SetTranslatedReasoningEffort(body, e.Identifier()) url := helps.ResolveKimiResponsesURL(auth) + body = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, "openai-response", opts.SourceFormat.String(), "", body, req.Payload, requestedModel, requestPath, opts.Headers) httpReq, errNewRequest := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) if errNewRequest != nil { return nil, errNewRequest diff --git a/internal/runtime/executor/meta_executor_execute.go b/internal/runtime/executor/meta_executor_execute.go index 516ce7e4cc8..6de21936ac0 100644 --- a/internal/runtime/executor/meta_executor_execute.go +++ b/internal/runtime/executor/meta_executor_execute.go @@ -54,7 +54,6 @@ func (e *MetaExecutor) prepareResponsesRequest(ctx context.Context, req cliproxy requestedModel := helps.PayloadRequestedModel(opts, req.Model) requestPath := helps.PayloadRequestPath(opts) - body = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, e.Identifier(), from.String(), "", body, originalTranslated, requestedModel, requestPath, opts.Headers) body = helps.SetStringIfDifferent(body, "model", baseModel) body = helps.SetBoolIfDifferent(body, "stream", stream) body, _ = sjson.DeleteBytes(body, "generate") @@ -73,6 +72,7 @@ func (e *MetaExecutor) prepareResponsesRequest(ctx context.Context, req cliproxy body = helps.SanitizeMetaWebSearchTools(body) body = helps.NormalizeCodexToolIntegerTypes(body, opts.Headers) + body = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, e.Identifier(), from.String(), "", body, originalTranslated, requestedModel, requestPath, opts.Headers) return &metaPreparedRequest{ applyPatch: applyPatch, baseModel: baseModel, diff --git a/internal/runtime/executor/openai_compat_executor.go b/internal/runtime/executor/openai_compat_executor.go index c213d41f0ea..49ba0eb3963 100644 --- a/internal/runtime/executor/openai_compat_executor.go +++ b/internal/runtime/executor/openai_compat_executor.go @@ -125,7 +125,6 @@ func (e *OpenAICompatExecutor) Execute(ctx context.Context, auth *cliproxyauth.A requestedModel := helps.PayloadRequestedModel(opts, req.Model) requestPath := helps.PayloadRequestPath(opts) - translated = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, to.String(), from.String(), "", translated, originalTranslated, requestedModel, requestPath, opts.Headers) if helps.ShouldNormalizeOpenAIToolResultsForModel(e.resolveCompatConfig(auth, req), baseModel, requestedModel) { translated = helps.NormalizeOpenAIToolResultsTextOnly(translated) } @@ -146,6 +145,7 @@ func (e *OpenAICompatExecutor) Execute(ctx context.Context, auth *cliproxyauth.A reporter.SetTranslatedReasoningEffort(translated, to.String()) url := strings.TrimSuffix(baseURL, "/") + endpoint + translated = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, to.String(), from.String(), "", translated, originalTranslated, requestedModel, requestPath, opts.Headers) httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(translated)) if err != nil { return resp, err @@ -240,6 +240,10 @@ func (e *OpenAICompatExecutor) executeImages(ctx context.Context, auth *cliproxy if contentType == "" { contentType = "application/json" } + payload, contentType, errPrepare = helps.ApplyMediaPayloadConfig(e.cfg, e.Identifier(), baseModel, "openai", payload, contentType, req, opts) + if errPrepare != nil { + return resp, errPrepare + } reporter.SetTranslatedReasoningEffort(payload, "openai") url := strings.TrimSuffix(baseURL, "/") + endpointPath @@ -345,7 +349,6 @@ func (e *OpenAICompatExecutor) ExecuteStream(ctx context.Context, auth *cliproxy requestedModel := helps.PayloadRequestedModel(opts, req.Model) requestPath := helps.PayloadRequestPath(opts) - translated = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, to.String(), from.String(), "", translated, originalTranslated, requestedModel, requestPath, opts.Headers) if helps.ShouldNormalizeOpenAIToolResultsForModel(e.resolveCompatConfig(auth, req), baseModel, requestedModel) { translated = helps.NormalizeOpenAIToolResultsTextOnly(translated) } @@ -364,6 +367,7 @@ func (e *OpenAICompatExecutor) ExecuteStream(ctx context.Context, auth *cliproxy reporter.SetTranslatedReasoningEffort(translated, to.String()) url := strings.TrimSuffix(baseURL, "/") + "/chat/completions" + translated = helps.ApplyPayloadConfigWithRequest(e.cfg, baseModel, to.String(), from.String(), "", translated, originalTranslated, requestedModel, requestPath, opts.Headers) httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(translated)) if err != nil { return nil, err @@ -609,6 +613,10 @@ func (e *OpenAICompatExecutor) executeImagesStream(ctx context.Context, auth *cl if contentType == "" { contentType = "application/json" } + payload, contentType, errPrepare = helps.ApplyMediaPayloadConfig(e.cfg, e.Identifier(), baseModel, "openai", payload, contentType, req, opts) + if errPrepare != nil { + return nil, errPrepare + } reporter.SetTranslatedReasoningEffort(payload, "openai") url := strings.TrimSuffix(baseURL, "/") + endpointPath @@ -717,6 +725,10 @@ func (e *OpenAICompatExecutor) CountTokens(ctx context.Context, auth *cliproxyau to := sdktranslator.FromString("openai") isCompat := helps.APIKeyModelIsCompat(req) translated, updatesChanged := helps.TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntent(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, false, isCompat) + originalTranslatedForPayload := append([]byte(nil), translated...) + if len(opts.OriginalRequest) > 0 { + originalTranslatedForPayload, _ = helps.TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntent(ctx, opts.Headers, e.cfg, from, to, baseModel, opts.OriginalRequest, false, isCompat) + } modelForCounting := baseModel @@ -725,6 +737,7 @@ func (e *OpenAICompatExecutor) CountTokens(ctx context.Context, auth *cliproxyau return cliproxyexecutor.Response{}, err } + translated = helps.NewPayloadFinalizer(e.cfg, e.Identifier(), baseModel, to.String(), "", originalTranslatedForPayload, req, opts)(translated) enc, err := helps.TokenizerForModel(modelForCounting) if err != nil { return cliproxyexecutor.Response{}, fmt.Errorf("openai compat executor: tokenizer init failed: %w", err) diff --git a/internal/runtime/executor/payload_barrier_test.go b/internal/runtime/executor/payload_barrier_test.go new file mode 100644 index 00000000000..ef3f767644d --- /dev/null +++ b/internal/runtime/executor/payload_barrier_test.go @@ -0,0 +1,184 @@ +package executor + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "testing" + + "github.com/gorilla/websocket" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +func TestPayloadBarrierCodexImageFilter(t *testing.T) { + for _, transport := range []string{"http", "websocket"} { + for _, stream := range []bool{false, true} { + for _, model := range []string{"gpt-5.6-sol", "gpt-5.6-luna"} { + t.Run(transport+"/"+model+map[bool]string{false: "/execute", true: "/stream"}[stream], func(t *testing.T) { + captured := make(chan []byte, 1) + completed := []byte(`{"type":"response.completed","response":{"id":"resp_barrier","status":"completed","output":[],"usage":{"input_tokens":0,"output_tokens":0,"total_tokens":0}}}`) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if transport == "websocket" { + upgrader := websocket.Upgrader{} + conn, errUpgrade := upgrader.Upgrade(w, r, nil) + if errUpgrade != nil { + t.Error(errUpgrade) + return + } + defer func() { + if errClose := conn.Close(); errClose != nil { + t.Error(errClose) + } + }() + _, body, errRead := conn.ReadMessage() + if errRead != nil { + t.Error(errRead) + return + } + captured <- body + if errWrite := conn.WriteMessage(websocket.TextMessage, completed); errWrite != nil { + t.Error(errWrite) + } + return + } + body, errRead := io.ReadAll(r.Body) + if errRead != nil { + t.Error(errRead) + return + } + captured <- body + w.Header().Set("Content-Type", "text/event-stream") + _, _ = w.Write(append(append([]byte("data: "), completed...), '\n', '\n')) + })) + defer server.Close() + cfg := &config.Config{Payload: config.PayloadConfig{Filter: []config.PayloadFilterRule{{Models: []config.PayloadModelRule{{Name: "gpt-5.6-sol"}}, Params: []string{`tools.#(type=="image_generation")#`, "instructions", "prompt_cache_key"}}}}} + var executor cliproxyauth.ProviderExecutor = NewCodexExecutor(cfg) + if transport == "websocket" { + executor = NewCodexWebsocketsExecutor(cfg) + } + auth := &cliproxyauth.Auth{ID: t.Name(), Provider: "codex", Attributes: map[string]string{"api_key": "test", "base_url": server.URL, "plan_type": "pro"}} + req := cliproxyexecutor.Request{Model: model, Payload: []byte(`{"input":"hello","prompt_cache_key":"injected-cache"}`)} + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatOpenAIResponse} + if stream { + result, errStream := executor.ExecuteStream(context.Background(), auth, req, opts) + if errStream != nil { + t.Fatal(errStream) + } + for chunk := range result.Chunks { + if chunk.Err != nil { + t.Fatal(chunk.Err) + } + } + } else if _, errExecute := executor.Execute(context.Background(), auth, req, opts); errExecute != nil { + t.Fatal(errExecute) + } + body := <-captured + image := gjson.GetBytes(body, `tools.#(type=="image_generation")`).Exists() + if image != (model == "gpt-5.6-luna") { + t.Fatalf("image tool presence = %v: %s", image, body) + } + if model == "gpt-5.6-sol" && (gjson.GetBytes(body, "instructions").Exists() || gjson.GetBytes(body, "prompt_cache_key").Exists()) { + t.Fatalf("late injection undid filter: %s", body) + } + }) + } + } + } +} + +func TestPayloadBarrierAntigravityRebuiltAttempts(t *testing.T) { + cfg := &config.Config{Payload: config.PayloadConfig{ + Override: []config.PayloadRule{{Models: []config.PayloadModelRule{{Name: "gemini-*"}}, Params: map[string]any{"generationConfig.maxOutputTokens": 123, "toolConfig.functionCallingConfig.mode": "CUSTOM"}}}, + Filter: []config.PayloadFilterRule{{Models: []config.PayloadModelRule{{Name: "gemini-*"}}, Params: []string{"sessionId", "contents.0"}}}, + }} + req := cliproxyexecutor.Request{Model: "gemini-3.1-pro-preview"} + body := []byte(`{"request":{"contents":[{"role":"user","parts":[{"text":"first"}]},{"role":"user","parts":[{"text":"second"}]}]}}`) + ctx := helps.WithPayloadFinalizer(context.Background(), helps.NewPayloadFinalizer(cfg, "antigravity", req.Model, "antigravity", "request", body, req, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatGemini})) + executor := NewAntigravityExecutor(cfg) + auth := &cliproxyauth.Auth{Metadata: map[string]any{"project_id": "project-test"}} + for attempt := 0; attempt < 2; attempt++ { + request, errBuild := executor.buildRequest(ctx, auth, "token", req.Model, body, attempt == 1, "", "https://example.invalid", "injected-session") + if errBuild != nil { + t.Fatal(errBuild) + } + wire, errRead := io.ReadAll(request.Body) + if errRead != nil { + t.Fatal(errRead) + } + if errClose := request.Body.Close(); errClose != nil { + t.Fatal(errClose) + } + if gjson.GetBytes(wire, "request.generationConfig.maxOutputTokens").Int() != 123 { + t.Fatalf("built-in cleanup undid override: %s", wire) + } + if gjson.GetBytes(wire, "request.sessionId").Exists() { + t.Fatalf("session reinjected: %s", wire) + } + if got := gjson.GetBytes(wire, "request.contents.#").Int(); got != 1 { + t.Fatalf("filter applied more than once: %s", wire) + } + } +} + +func TestPayloadBarrierAIStudio(t *testing.T) { + cfg := &config.Config{Payload: config.PayloadConfig{ + Override: []config.PayloadRule{{Models: []config.PayloadModelRule{{Name: "*"}}, Params: map[string]any{"generationConfig.maxOutputTokens": 900000, "generationConfig.thinkingConfig.thinkingLevel": "low"}}}, + Filter: []config.PayloadFilterRule{{Models: []config.PayloadModelRule{{Name: "*"}}, Params: []string{"contents"}}}, + }} + executor := NewAIStudioExecutor(cfg, "aistudio", nil) + for _, stream := range []bool{false, true} { + body, _, errTranslate := executor.translateRequest(context.Background(), cliproxyexecutor.Request{Model: "gemini-3.1-pro-preview", Payload: []byte(`{"contents":[{"role":"model","parts":[{"text":"hi"}]}]}`)}, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatGemini}, stream) + if errTranslate != nil { + t.Fatal(errTranslate) + } + if gjson.GetBytes(body, "contents").Exists() || gjson.GetBytes(body, "generationConfig.maxOutputTokens").Int() != 900000 || gjson.GetBytes(body, "generationConfig.thinkingConfig.thinkingLevel").String() != "low" { + t.Fatalf("late normalization undid rules: %s", body) + } + } +} + +func TestPayloadBarrierXAIWebsocketRetry(t *testing.T) { + cfg := &config.Config{Payload: config.PayloadConfig{ + Override: []config.PayloadRule{{Models: []config.PayloadModelRule{{Name: "*"}}, Params: map[string]any{"store": false, "instructions": "configured"}}}, + Filter: []config.PayloadFilterRule{{Models: []config.PayloadModelRule{{Name: "*"}}, Params: []string{"input.0", "previous_response_id"}}}, + }} + req := cliproxyexecutor.Request{Model: "grok-4.3"} + body := []byte(`{"previous_response_id":"previous","input":[{"content":"first"},{"content":"second"}]}`) + finalize := helps.NewPayloadFinalizer(cfg, "xai", req.Model, "codex", "", body, req, cliproxyexecutor.Options{}) + first := buildXAIWebsocketRequestBody(body, finalize) + retry := buildXAIWebsocketRequestBody(body, finalize) + if !bytes.Equal(first, retry) { + t.Fatalf("retry changed configured body: %s != %s", first, retry) + } + if gjson.GetBytes(first, "store").Bool() || gjson.GetBytes(first, "instructions").String() != "configured" || gjson.GetBytes(first, "previous_response_id").Exists() || gjson.GetBytes(first, "input.#").Int() != 1 { + t.Fatalf("invalid final payload: %s", first) + } + if gjson.GetBytes(first, "type").String() != "response.create" { + t.Fatalf("missing frame type: %s", first) + } +} + +func TestPayloadBarrierClaudeDoesNotReplayFiltersOrReinjectIdentity(t *testing.T) { + cfg := &config.Config{Payload: config.PayloadConfig{ + Filter: []config.PayloadFilterRule{{Models: []config.PayloadModelRule{{Name: "*"}}, Params: []string{"system", "metadata", "diagnostics", "context_management", "messages.0"}}}, + Override: []config.PayloadRule{{Models: []config.PayloadModelRule{{Name: "*"}}, Params: map[string]any{"max_tokens": 1}}}, + }} + for _, stream := range []bool{false, true} { + body := executeClaudeContextManagementRequest(t, cfg, []byte(`{"model":"claude-opus-5","thinking":{"type":"adaptive"},"messages":[{"role":"user","content":"first"},{"role":"assistant","content":"second"},{"role":"user","content":"third"}]}`), stream) + for _, path := range []string{"system", "metadata", "diagnostics", "context_management"} { + if gjson.GetBytes(body, path).Exists() { + t.Fatalf("%s was reinjected: %s", path, body) + } + } + if gjson.GetBytes(body, "messages.#").Int() != 2 || gjson.GetBytes(body, "max_tokens").Int() != 1 { + t.Fatalf("built-in processing changed final rule semantics: %s", body) + } + } +} diff --git a/internal/runtime/executor/payload_review_test.go b/internal/runtime/executor/payload_review_test.go new file mode 100644 index 00000000000..e95f304f7af --- /dev/null +++ b/internal/runtime/executor/payload_review_test.go @@ -0,0 +1,203 @@ +package executor + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/gorilla/websocket" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/wsrelay" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + core "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +func TestClaudePayloadConditionsEvaluateOnceAtFinalBarrier(t *testing.T) { + cfg := &config.Config{Payload: config.PayloadConfig{ + Override: []config.PayloadRule{{ + Models: []config.PayloadModelRule{{Name: "*", Match: []map[string]any{{"max_tokens": 100}}}}, + Params: map[string]any{"max_tokens": 200, "temperature": 0.2, "diagnostics": map[string]any{"user": true}}, + }, { + Models: []config.PayloadModelRule{{Name: "*", Match: []map[string]any{{"max_tokens": 200}}}}, + Params: map[string]any{"top_p": 0.4}, + }}, + Filter: []config.PayloadFilterRule{{Models: []config.PayloadModelRule{{Name: "*", Match: []map[string]any{{"max_tokens": 200}}}}, Params: []string{"messages.0"}}}, + }} + for _, stream := range []bool{false, true} { + body := executeClaudeContextManagementRequest(t, cfg, []byte(`{"model":"claude-opus-5","max_tokens":100,"messages":[{"role":"user","content":"first"},{"role":"assistant","content":"second"},{"role":"user","content":"third"}]}`), stream) + if gjson.GetBytes(body, "max_tokens").Int() != 200 || gjson.GetBytes(body, "temperature").Float() != 0.2 || gjson.GetBytes(body, "top_p").Float() != 0.4 || !gjson.GetBytes(body, "diagnostics.user").Bool() { + t.Fatalf("conditional rule lost fields (stream=%v): %s", stream, body) + } + if gjson.GetBytes(body, "messages.#").Int() != 2 { + t.Fatalf("conditional filter applied more than once (stream=%v): %s", stream, body) + } + } +} + +func TestAIStudioCountPayloadAfterCleanup(t *testing.T) { + cfg := &config.Config{Payload: config.PayloadConfig{Override: []config.PayloadRule{{ + Models: []config.PayloadModelRule{{Name: "*"}}, + Params: map[string]any{"generationConfig.temperature": 0.2, "tools": []any{map[string]any{"googleSearch": map[string]any{}}}, "safetySettings": []any{map[string]any{"category": "configured"}}}, + }}}} + req := core.Request{Model: "gemini-3.7-flash", Payload: []byte(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`), Metadata: map[string]any{"action": "countTokens"}} + connected := make(chan struct{}) + relay := wsrelay.NewManager(wsrelay.Options{ + ProviderFactory: func(*http.Request) (string, error) { return "count-test", nil }, + OnConnected: func(string) { close(connected) }, + }) + server := httptest.NewServer(relay.Handler()) + defer server.Close() + defer func() { + if errStop := relay.Stop(context.Background()); errStop != nil { + t.Error(errStop) + } + }() + conn, _, errDial := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(server.URL, "http")+relay.Path(), nil) + if errDial != nil { + t.Fatal(errDial) + } + defer func() { + if errClose := conn.Close(); errClose != nil { + t.Error(errClose) + } + }() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + select { + case <-connected: + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } + for _, configured := range []bool{false, true} { + selected := &config.Config{} + if configured { + selected = cfg + } + captured := make(chan []byte, 1) + clientErrors := make(chan error, 1) + go func() { + var message wsrelay.Message + if errRead := conn.ReadJSON(&message); errRead != nil { + clientErrors <- errRead + return + } + captured <- []byte(message.Payload["body"].(string)) + clientErrors <- conn.WriteJSON(wsrelay.Message{ID: message.ID, Type: wsrelay.MessageTypeHTTPResp, Payload: map[string]any{"status": float64(http.StatusOK), "headers": map[string]any{"Content-Type": "application/json"}, "body": `{"totalTokens":1}`}}) + }() + executor := NewAIStudioExecutor(selected, "aistudio", relay) + if _, errCount := executor.CountTokens(ctx, &cliproxyauth.Auth{ID: "count-test", Provider: "aistudio"}, req, core.Options{SourceFormat: sdktranslator.FormatGemini}); errCount != nil { + t.Fatal(errCount) + } + if errClient := <-clientErrors; errClient != nil { + t.Fatal(errClient) + } + body := <-captured + for _, field := range []string{"generationConfig", "tools", "safetySettings"} { + if gjson.GetBytes(body, field).Exists() != configured { + t.Fatalf("count cleanup precedence for %s: %s", field, body) + } + } + } +} + +func TestCodexDuplexSteerPayloadBarrier(t *testing.T) { + for _, filter := range []bool{false, true} { + t.Run(map[bool]string{false: "override", true: "filter"}[filter], func(t *testing.T) { + captured := make(chan []byte, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, errUpgrade := (&websocket.Upgrader{}).Upgrade(w, r, nil) + if errUpgrade != nil { + t.Error(errUpgrade) + return + } + defer func() { _ = conn.Close() }() + if _, _, errRead := conn.ReadMessage(); errRead != nil { + t.Error(errRead) + return + } + if errWrite := conn.WriteMessage(websocket.TextMessage, []byte(`{"type":"response.created","response":{"id":"parent","output":[]}}`)); errWrite != nil { + t.Error(errWrite) + return + } + _, body, errRead := conn.ReadMessage() + if errRead != nil { + t.Error(errRead) + return + } + captured <- body + _, _, _ = conn.ReadMessage() + })) + defer server.Close() + models := []config.PayloadModelRule{{Name: "*", Match: []map[string]any{{"type": "response.steer"}}}} + cfg := &config.Config{Codex: config.CodexConfig{ResponseSteering: true}, Payload: config.PayloadConfig{Override: []config.PayloadRule{{Models: models, Params: map[string]any{"input": "configured", "type": "response.create"}}}}} + if filter { + cfg.Payload = config.PayloadConfig{Filter: []config.PayloadFilterRule{{Models: models, Params: []string{"input", "type"}}}} + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + input := make(chan core.WebsocketInput, 1) + ctx = core.WithWebsocketInput(core.WithDownstreamWebsocket(ctx), input) + executor := NewCodexWebsocketsExecutor(cfg) + executor.store = &codexWebsocketSessionStore{sessions: make(map[string]*codexWebsocketSession)} + auth := &cliproxyauth.Auth{ID: t.Name(), Provider: "codex", Attributes: map[string]string{"api_key": "test", "base_url": server.URL, "websockets": "true"}} + result, errStream := executor.ExecuteStream(ctx, auth, core.Request{Model: "gpt-6-astra", Payload: []byte(`{"input":[]}`)}, core.Options{SourceFormat: sdktranslator.FormatCodex}) + if errStream != nil { + t.Fatal(errStream) + } + input <- core.WebsocketInput{Payload: []byte(`{"type":"response.steer","previous_response_id":"parent","input":"original"}`)} + for { + select { + case body := <-captured: + if gjson.GetBytes(body, "type").String() != "response.steer" || gjson.GetBytes(body, "previous_response_id").String() != "parent" { + t.Fatalf("steer framing changed: %s", body) + } + if filter && gjson.GetBytes(body, "input").Exists() || !filter && gjson.GetBytes(body, "input").String() != "configured" { + t.Fatalf("steer payload bypassed config: %s", body) + } + cancel() + for range result.Chunks { + } + return + case chunk, ok := <-result.Chunks: + if !ok || chunk.Err != nil { + t.Fatalf("stream ended before steer: %v", chunk.Err) + } + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } + } + }) + } +} + +func TestClaudePayloadConditionsObserveBuiltinThinkingRemoval(t *testing.T) { + for _, stream := range []bool{false, true} { + present := []config.PayloadModelRule{{Name: "*", Exist: []string{"thinking"}}} + absent := []config.PayloadModelRule{{Name: "*", NotExist: []string{"thinking"}}} + cfg := &config.Config{Payload: config.PayloadConfig{ + Default: []config.PayloadRule{{Models: absent, Params: map[string]any{"default_matched": true}}, {Models: present, Params: map[string]any{"default_unmatched": true}}}, + DefaultRaw: []config.PayloadRule{{Models: absent, Params: map[string]any{"default_raw_matched": `true`}}, {Models: present, Params: map[string]any{"default_raw_unmatched": `true`}}}, + Override: []config.PayloadRule{{Models: absent, Params: map[string]any{"override_matched": true}}, {Models: present, Params: map[string]any{"override_unmatched": true}}}, + OverrideRaw: []config.PayloadRule{{Models: absent, Params: map[string]any{"override_raw_matched": `true`}}, {Models: present, Params: map[string]any{"override_raw_unmatched": `true`}}}, + Filter: []config.PayloadFilterRule{{Models: absent, Params: []string{"metadata"}}, {Models: present, Params: []string{"system"}}}, + }} + payload := []byte(`{"model":"claude-opus-5","max_tokens":100,"thinking":{"type":"adaptive"},"tool_choice":{"type":"any"},"tools":[{"name":"lookup","input_schema":{"type":"object"}}],"messages":[{"role":"user","content":"hi"}]}`) + body := executeClaudeContextManagementRequest(t, cfg, payload, stream) + if gjson.GetBytes(body, "thinking").Exists() { + t.Fatalf("builtin did not remove forced-tool thinking: %s", body) + } + for _, prefix := range []string{"default", "default_raw", "override", "override_raw"} { + if !gjson.GetBytes(body, prefix+"_matched").Bool() || gjson.GetBytes(body, prefix+"_unmatched").Exists() { + t.Fatalf("%s matched pre-builtin conditions (stream=%v): %s", prefix, stream, body) + } + } + if gjson.GetBytes(body, "metadata").Exists() || !gjson.GetBytes(body, "system").Exists() { + t.Fatalf("filters matched pre-builtin conditions (stream=%v): %s", stream, body) + } + } +} diff --git a/internal/runtime/executor/xai_executor_execute.go b/internal/runtime/executor/xai_executor_execute.go index bd08febc5d5..de001c96155 100644 --- a/internal/runtime/executor/xai_executor_execute.go +++ b/internal/runtime/executor/xai_executor_execute.go @@ -44,6 +44,7 @@ func (e *XAIExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, req reporter.SetTranslatedReasoningEffort(prepared.body, e.Identifier()) url := strings.TrimSuffix(baseURL, "/") + "/responses" + prepared.body = prepared.finalizePayload(prepared.body) httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(prepared.body)) if err != nil { return resp, err @@ -195,6 +196,7 @@ func (e *XAIExecutor) executeCompactRequest(ctx context.Context, auth *cliproxya reporter.SetTranslatedReasoningEffort(prepared.body, e.Identifier()) requestURL := strings.TrimSuffix(baseURL, "/") + "/responses/compact" + prepared.body = prepared.finalizePayload(prepared.body) httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, requestURL, bytes.NewReader(prepared.body)) if err != nil { return nil, nil, nil, nil, err diff --git a/internal/runtime/executor/xai_executor_media.go b/internal/runtime/executor/xai_executor_media.go index f617c1c9764..9804232850c 100644 --- a/internal/runtime/executor/xai_executor_media.go +++ b/internal/runtime/executor/xai_executor_media.go @@ -31,6 +31,7 @@ func (e *XAIExecutor) executeImages(ctx context.Context, auth *cliproxyauth.Auth } payload := normalizeXAIImageRefs(req.Payload) + payload = helps.NewPayloadFinalizer(e.cfg, e.Identifier(), model, "openai", "", req.Payload, req, opts)(payload) url := strings.TrimSuffix(baseURL, "/") + endpointPath httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(payload)) if err != nil { @@ -84,6 +85,7 @@ func (e *XAIExecutor) executeVideos(ctx context.Context, auth *cliproxyauth.Auth logXAIResolvedBaseURL(ctx, baseURL) payload := normalizeXAIImageRefs(req.Payload) + payload = helps.NewPayloadFinalizer(e.cfg, e.Identifier(), model, "openai", "", req.Payload, req, opts)(payload) method := http.MethodPost endpointPath := xaiVideosGenerationsPath var body io.Reader = bytes.NewReader(payload) diff --git a/internal/runtime/executor/xai_executor_request.go b/internal/runtime/executor/xai_executor_request.go index 131338c317e..34606c74f03 100644 --- a/internal/runtime/executor/xai_executor_request.go +++ b/internal/runtime/executor/xai_executor_request.go @@ -23,6 +23,7 @@ import ( ) type xaiPreparedRequest struct { + finalizePayload helps.PayloadFinalizer applyPatch *helps.ApplyPatchResponsesState baseModel string from sdktranslator.Format @@ -81,9 +82,7 @@ func (e *XAIExecutor) prepareResponsesRequestTo(ctx context.Context, req cliprox return nil, err } - requestedModel := helps.PayloadRequestedModel(opts, req.Model) - requestPath := helps.PayloadRequestPath(opts) - body = helps.ApplyPayloadConfigWithRequestForExecutor(e.cfg, e.Identifier(), baseModel, to.String(), from.String(), "", body, originalTranslated, requestedModel, requestPath, opts.Headers) + finalizePayload := helps.NewPayloadFinalizer(e.cfg, e.Identifier(), baseModel, to.String(), "", originalTranslated, req, opts) body = helps.SetStringIfDifferent(body, "model", baseModel) body = helps.SetBoolIfDifferent(body, "stream", stream) body, _ = sjson.DeleteBytes(body, "previous_response_id") @@ -158,6 +157,7 @@ func (e *XAIExecutor) prepareResponsesRequestTo(ctx context.Context, req cliprox } return &xaiPreparedRequest{ + finalizePayload: finalizePayload, applyPatch: applyPatch, baseModel: baseModel, from: from, diff --git a/internal/runtime/executor/xai_executor_stream.go b/internal/runtime/executor/xai_executor_stream.go index 8ec809d1479..d7918e1eebc 100644 --- a/internal/runtime/executor/xai_executor_stream.go +++ b/internal/runtime/executor/xai_executor_stream.go @@ -38,6 +38,7 @@ func (e *XAIExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Auth reporter.SetTranslatedReasoningEffort(prepared.body, e.Identifier()) url := strings.TrimSuffix(baseURL, "/") + "/responses" + prepared.body = prepared.finalizePayload(prepared.body) httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(prepared.body)) if err != nil { return nil, err diff --git a/internal/runtime/executor/xai_executor_test.go b/internal/runtime/executor/xai_executor_test.go index 4b503f71ff3..daaa358d501 100644 --- a/internal/runtime/executor/xai_executor_test.go +++ b/internal/runtime/executor/xai_executor_test.go @@ -2675,11 +2675,14 @@ func TestXAIExecutorCompactUsesCompactEndpoint(t *testing.T) { if gotAccept != "application/json" { t.Fatalf("Accept = %q, want application/json", gotAccept) } - for _, field := range []string{"stream", "max_output_tokens", "temperature", "top_p", "top_k", "stop"} { + for _, field := range []string{"stream", "max_output_tokens", "temperature", "top_p", "stop"} { if gjson.GetBytes(gotBody, field).Exists() { t.Fatalf("%s exists in compact body: %s", field, string(gotBody)) } } + if got := gjson.GetBytes(gotBody, "top_k").Int(); got != 10 { + t.Fatalf("payload override top_k = %d, want 10", got) + } if got := gjson.GetBytes(gotBody, "input.0.encrypted_content").String(); got != validEncryptedContent { t.Fatalf("input.0.encrypted_content = %q, want valid sample; body=%s", got, string(gotBody)) } @@ -3092,6 +3095,7 @@ func TestXAIExecutorThinkingPayloadOverride(t *testing.T) { if errPrepare != nil { t.Fatalf("prepareResponsesRequest() error = %v", errPrepare) } + prepared.body = prepared.finalizePayload(prepared.body) if got := gjson.GetBytes(prepared.body, "reasoning.effort").String(); got != wantEffort { t.Fatalf("reasoning.effort = %q, want %q; body=%s", got, wantEffort, prepared.body) } diff --git a/internal/runtime/executor/xai_executor_tokens.go b/internal/runtime/executor/xai_executor_tokens.go index 0e4c9e2f5cc..2a3b5c9d431 100644 --- a/internal/runtime/executor/xai_executor_tokens.go +++ b/internal/runtime/executor/xai_executor_tokens.go @@ -22,6 +22,7 @@ func (e *XAIExecutor) CountTokens(ctx context.Context, auth *cliproxyauth.Auth, if err != nil { return cliproxyexecutor.Response{}, fmt.Errorf("xai executor: tokenizer init failed: %w", err) } + prepared.body = prepared.finalizePayload(prepared.body) count, err := countXAIInputTokens(enc, prepared.body) if err != nil { return cliproxyexecutor.Response{}, fmt.Errorf("xai executor: token counting failed: %w", err) diff --git a/internal/runtime/executor/xai_websockets_executor.go b/internal/runtime/executor/xai_websockets_executor.go index 28402efff2d..93cebfef38e 100644 --- a/internal/runtime/executor/xai_websockets_executor.go +++ b/internal/runtime/executor/xai_websockets_executor.go @@ -519,7 +519,7 @@ func (e *XAIWebsocketsExecutor) ExecuteStream(ctx context.Context, auth *cliprox reporter.SetTranslatedReasoningEffort(prepared.body, e.Identifier()) wsHeaders := applyXAIWebsocketHeaders(ctx, http.Header{}, auth, token, prepared.sessionID, opts.Headers) - wsReqBody := buildXAIWebsocketRequestBody(prepared.body) + wsReqBody := buildXAIWebsocketRequestBody(prepared.body, prepared.finalizePayload) requestType := strings.TrimSpace(gjson.GetBytes(req.Payload, "type").String()) transcriptReset := strings.TrimSpace(gjson.GetBytes(wsReqBody, "previous_response_id").String()) == "" && (requestType != "response.append" || (idMapper != nil && idMapper.replayedCompactedTranscript)) @@ -628,7 +628,7 @@ func (e *XAIWebsocketsExecutor) ExecuteStream(ctx context.Context, auth *cliprox return nil, errBind } readCh = sess.activate(conn) - wsReqBodyRetry := buildXAIWebsocketRequestBody(prepared.body) + wsReqBodyRetry := buildXAIWebsocketRequestBody(prepared.body, prepared.finalizePayload) helps.RecordAPIWebsocketRequest(ctx, e.cfg, helps.UpstreamRequestLog{ URL: wsURL, Method: "WEBSOCKET", @@ -1551,7 +1551,7 @@ func closeXAIWebsocketSession(sess *codexWebsocketSession, reason string) { } } -func buildXAIWebsocketRequestBody(body []byte) []byte { +func buildXAIWebsocketRequestBody(body []byte, finalizers ...helps.PayloadFinalizer) []byte { if len(body) == 0 { return nil } @@ -1564,6 +1564,10 @@ func buildXAIWebsocketRequestBody(body []byte) []byte { if strings.TrimSpace(gjson.GetBytes(wsReqBody, "previous_response_id").String()) != "" { wsReqBody, _ = sjson.DeleteBytes(wsReqBody, "instructions") } + if len(finalizers) > 0 && finalizers[0] != nil { + wsReqBody = finalizers[0](wsReqBody) + } + wsReqBody, _ = sjson.SetBytes(wsReqBody, "type", "response.create") return wsReqBody } From cbc4cd55329fbe4aa78ab7012a81a6680499f433 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Sun, 4 Oct 2026 04:23:31 +0800 Subject: [PATCH 031/142] feat(interactions): support antigravity session continuation and model detail lookup - Add `InteractionsSessionCache` to preserve Antigravity interaction continuations across tool call rounds - Automatically restore and inject `previous_interaction_id` and `environment_id` in Gemini interactions executor - Normalize Antigravity tool identity mappings in OpenAI responses translator - Add `/v1/models/*model` endpoint to support retrieving individual model details Closes: #5190 --- internal/api/server_model_detail_test.go | 132 +++++++++++++++ internal/api/server_routes.go | 4 + .../cache/antigravity_interactions_session.go | 76 +++++++++ .../antigravity_interactions_session_test.go | 56 ++++++ internal/runtime/executor/gemini_executor.go | 4 + .../gemini_interactions_continuation_test.go | 119 +++++++++++++ .../gemini_interactions_tool_names_test.go | 68 ++++++++ .../helps/antigravity_interactions_state.go | 159 ++++++++++++++++++ .../antigravity_interactions_state_test.go | 74 ++++++++ .../translator/common/antigravity_tools.go | 16 +- .../antigravity_tools_collision_test.go | 17 ++ .../interactions_openai_responses_response.go | 11 +- sdk/api/handlers/handlers_interceptors.go | 43 ++++- 13 files changed, 765 insertions(+), 14 deletions(-) create mode 100644 internal/api/server_model_detail_test.go create mode 100644 internal/cache/antigravity_interactions_session.go create mode 100644 internal/cache/antigravity_interactions_session_test.go create mode 100644 internal/runtime/executor/gemini_interactions_continuation_test.go create mode 100644 internal/runtime/executor/gemini_interactions_tool_names_test.go create mode 100644 internal/runtime/executor/helps/antigravity_interactions_state.go create mode 100644 internal/runtime/executor/helps/antigravity_interactions_state_test.go create mode 100644 internal/translator/common/antigravity_tools_collision_test.go diff --git a/internal/api/server_model_detail_test.go b/internal/api/server_model_detail_test.go new file mode 100644 index 00000000000..9c0b52b04cd --- /dev/null +++ b/internal/api/server_model_detail_test.go @@ -0,0 +1,132 @@ +package api + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/router-for-me/CLIProxyAPI/v8/internal/home" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginapi" + "github.com/tidwall/gjson" +) + +type issue5190LifecycleHost struct { + mockModelListInterceptorHost + completions []pluginapi.RequestCompletion +} + +func (h *issue5190LifecycleHost) CompleteRequest(_ context.Context, completion pluginapi.RequestCompletion) { + h.completions = append(h.completions, completion) +} + +func TestIssue5190ModelDetailLifecycle(t *testing.T) { + for _, tc := range []struct { + name string + body string + status int + }{ + {"visible", `{"data":[{"id":"visible"}]}`, http.StatusOK}, + {"missing", `{"data":[]}`, http.StatusNotFound}, + {"invalid", `invalid`, http.StatusBadGateway}, + } { + t.Run(tc.name, func(t *testing.T) { + server := newTestServer(t) + host := &issue5190LifecycleHost{} + host.interceptResponse = func(_ context.Context, _ pluginapi.ResponseInterceptRequest) pluginapi.ResponseInterceptResponse { + return pluginapi.ResponseInterceptResponse{Body: []byte(tc.body)} + } + server.handlers.SetPluginHost(host) + req := httptest.NewRequest(http.MethodGet, "/v1/models/visible", nil) + req.Header.Set("Authorization", "Bearer test-key") + rr := httptest.NewRecorder() + server.engine.ServeHTTP(rr, req) + if rr.Code != tc.status || len(host.completions) != 1 { + t.Fatalf("status=%d completions=%+v", rr.Code, host.completions) + } + completion := host.completions[0] + wantOutcome := pluginapi.RequestCompletionSucceeded + if tc.status != http.StatusOK { + wantOutcome = pluginapi.RequestCompletionFailed + } + if completion.StatusCode != tc.status || completion.Outcome != wantOutcome { + t.Fatalf("completion=%+v want status=%d outcome=%s", completion, tc.status, wantOutcome) + } + }) + } +} + +func TestIssue5190ModelDetailUsesVisibleCatalog(t *testing.T) { + server := newTestServer(t) + calls := 0 + server.handlers.SetPluginHost(&mockModelListInterceptorHost{ + interceptResponse: func(_ context.Context, req pluginapi.ResponseInterceptRequest) pluginapi.ResponseInterceptResponse { + calls++ + return pluginapi.ResponseInterceptResponse{Headers: http.Header{"Content-Length": []string{"98"}}, Body: []byte(`{"object":"list","data":[{"id":"vendor/visible","object":"model","owned_by":"plugin"}]}`)} + }, + }) + for _, tc := range []struct { + id string + status int + }{{"vendor/visible", 200}, {"hidden", 404}} { + req := httptest.NewRequest(http.MethodGet, "/v1/models/"+tc.id, nil) + req.Header.Set("Authorization", "Bearer test-key") + rr := httptest.NewRecorder() + server.engine.ServeHTTP(rr, req) + if length := rr.Header().Get("Content-Length"); length != "" { + t.Errorf("stale catalog content length: %s", length) + } + if rr.Code != tc.status { + t.Errorf("%s: status=%d want=%d body=%s", tc.id, rr.Code, tc.status, rr.Body.String()) + } + if tc.status == 200 && gjson.Get(rr.Body.String(), "id").String() != tc.id { + t.Errorf("wrong model: %s", rr.Body.String()) + } + } + if calls != 2 { + t.Errorf("catalog interceptor calls=%d want=2", calls) + } +} + +func TestIssue5190ModelDetailHomeVisibility(t *testing.T) { + server := newTestServer(t) + modelRegistry := registry.GetGlobalRegistry() + modelRegistry.RegisterClient(t.Name(), "openai", []*registry.ModelInfo{{ID: "local/only", Object: "model"}}) + t.Cleanup(func() { modelRegistry.UnregisterClient(t.Name()) }) + engine := server.engine + get := func(id string, authorized bool) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodGet, "/v1/models/"+id, nil) + if authorized { + req.Header.Set("Authorization", "Bearer test-key") + } + rr := httptest.NewRecorder() + engine.ServeHTTP(rr, req) + return rr + } + if rr := get("local/only", true); rr.Code != 200 { + t.Fatalf("local detail: %d %s", rr.Code, rr.Body.String()) + } + if rr := get("local/only", false); rr.Code != 401 { + t.Fatalf("unauthorized detail: %d", rr.Code) + } + server.cfg.Home.Enabled = true + // The catalog fixture does not implement Home's readiness handshake. + // Reuse the registered route without the unrelated readiness middleware. + engine = gin.New() + for _, route := range server.engine.Routes() { + if route.Method == http.MethodGet && route.Path == "/v1/models/*model" { + engine.GET(route.Path, route.HandlerFunc) + } + } + previousHome := home.Current() + home.SetCurrent(newHomeCatalogClient(t, `{"openai":[{"id":"home/visible"}]}`)) + t.Cleanup(func() { home.SetCurrent(previousHome) }) + if rr := get("home/visible", true); rr.Code != 200 || gjson.Get(rr.Body.String(), "id").String() != "home/visible" { + t.Fatalf("Home detail: %d %s", rr.Code, rr.Body.String()) + } + if rr := get("local/only", true); rr.Code != 404 { + t.Fatalf("local registry leaked into Home: %d %s", rr.Code, rr.Body.String()) + } +} diff --git a/internal/api/server_routes.go b/internal/api/server_routes.go index deb5c7c37c0..fa78ec5b190 100644 --- a/internal/api/server_routes.go +++ b/internal/api/server_routes.go @@ -64,6 +64,10 @@ func (s *Server) setupRoutes() { v1.Use(AuthMiddleware(s.accessManager)) { v1.GET("/models", s.unifiedModelsHandler(openaiHandlers, claudeCodeHandlers)) + v1.GET("/models/*model", func(c *gin.Context) { + c.Set(handlers.ModelDetailIDContextKey, strings.TrimPrefix(c.Param("model"), "/")) + s.unifiedModelsHandler(openaiHandlers, claudeCodeHandlers)(c) + }) v1.POST("/chat/completions", openaiHandlers.ChatCompletions) v1.POST("/completions", openaiHandlers.Completions) v1.POST("/images/generations", openaiHandlers.ImagesGenerations) diff --git a/internal/cache/antigravity_interactions_session.go b/internal/cache/antigravity_interactions_session.go new file mode 100644 index 00000000000..97ad5f8e12b --- /dev/null +++ b/internal/cache/antigravity_interactions_session.go @@ -0,0 +1,76 @@ +package cache + +import ( + "sort" + "strings" + "sync" + "time" +) + +// InteractionsContinuation contains only upstream continuation identifiers. +type InteractionsContinuation struct { + ID string + Environment string +} + +type interactionsContinuationEntry struct { + state InteractionsContinuation + expires time.Time +} + +// InteractionsSessionCache is a bounded, process-local cache. Keys must already +// isolate the caller, credential, model, conversation, and pending call IDs. +type InteractionsSessionCache struct { + mu sync.Mutex + entries map[string]interactionsContinuationEntry + now func() time.Time +} + +func NewInteractionsSessionCache() *InteractionsSessionCache { + return &InteractionsSessionCache{entries: make(map[string]interactionsContinuationEntry), now: time.Now} +} + +// InteractionsCallKey rejects ambiguous or incomplete call sets. +func InteractionsCallKey(ids []string) string { + ids = append([]string(nil), ids...) + sort.Strings(ids) + for i, id := range ids { + if id == "" || strings.ContainsRune(id, '\x00') || (i > 0 && ids[i-1] == id) { + return "" + } + } + return strings.Join(ids, "\x00") +} + +func (c *InteractionsSessionCache) Get(key string) (InteractionsContinuation, bool) { + c.mu.Lock() + defer c.mu.Unlock() + entry, ok := c.entries[key] + if !ok || !c.now().Before(entry.expires) { + delete(c.entries, key) + return InteractionsContinuation{}, false + } + return entry.state, true +} + +func (c *InteractionsSessionCache) Put(key string, state InteractionsContinuation) { + c.mu.Lock() + defer c.mu.Unlock() + now := c.now() + for k, entry := range c.entries { + if !now.Before(entry.expires) { + delete(c.entries, k) + } + } + if _, exists := c.entries[key]; !exists && len(c.entries) >= 1024 { + var oldestKey string + var oldest time.Time + for k, entry := range c.entries { + if oldest.IsZero() || entry.expires.Before(oldest) { + oldestKey, oldest = k, entry.expires + } + } + delete(c.entries, oldestKey) + } + c.entries[key] = interactionsContinuationEntry{state: state, expires: now.Add(30 * time.Minute)} +} diff --git a/internal/cache/antigravity_interactions_session_test.go b/internal/cache/antigravity_interactions_session_test.go new file mode 100644 index 00000000000..74dd2ee38b2 --- /dev/null +++ b/internal/cache/antigravity_interactions_session_test.go @@ -0,0 +1,56 @@ +package cache + +import ( + "fmt" + "testing" + "time" +) + +func TestIssue5190InteractionsCacheUpdateAtCapacity(t *testing.T) { + c := NewInteractionsSessionCache() + now := time.Unix(100, 0) + c.now = func() time.Time { return now } + for i := 0; i < 1024; i++ { + c.Put(fmt.Sprint(i), InteractionsContinuation{ID: "original"}) + now = now.Add(time.Second) + } + c.Put("1023", InteractionsContinuation{ID: "updated"}) + if len(c.entries) != 1024 { + t.Fatalf("update evicted an unrelated entry: size=%d", len(c.entries)) + } + if _, ok := c.Get("0"); !ok { + t.Fatal("update evicted oldest entry") + } + if state, ok := c.Get("1023"); !ok || state.ID != "updated" { + t.Fatalf("update not retained: %+v, %v", state, ok) + } +} + +func TestIssue5190InteractionsCacheExpiryAndBound(t *testing.T) { + c := NewInteractionsSessionCache() + now := time.Unix(100, 0) + c.now = func() time.Time { return now } + c.Put("first", InteractionsContinuation{ID: "one"}) + now = now.Add(30 * time.Minute) + if _, ok := c.Get("first"); ok { + t.Fatal("expired continuation retained") + } + for i := 0; i < 1030; i++ { + c.Put(fmt.Sprint(i), InteractionsContinuation{ID: "one"}) + now = now.Add(time.Second) + } + if len(c.entries) != 1024 { + t.Fatalf("size=%d", len(c.entries)) + } + if _, ok := c.Get("0"); ok { + t.Fatal("oldest continuation retained") + } + if InteractionsCallKey([]string{"b", "a"}) != InteractionsCallKey([]string{"a", "b"}) { + t.Fatal("call order matters") + } + for _, calls := range [][]string{nil, {""}, {"a", "a"}, {"a\x00b"}} { + if InteractionsCallKey(calls) != "" { + t.Fatalf("accepted invalid calls %q", calls) + } + } +} diff --git a/internal/runtime/executor/gemini_executor.go b/internal/runtime/executor/gemini_executor.go index eac599212f0..96c9b473a7f 100644 --- a/internal/runtime/executor/gemini_executor.go +++ b/internal/runtime/executor/gemini_executor.go @@ -440,6 +440,7 @@ func (e *GeminiExecutor) executeInteractions(ctx context.Context, auth *cliproxy requestPath := helps.PayloadRequestPath(opts) fromProtocol := opts.SourceFormat.String() body = sanitizeGeminiInteractionsUnsupportedInputIDs(body) + continuation, body := helps.PrepareAntigravityInteractions(auth, req, opts, targetName, body) baseURL := resolveGeminiBaseURL(auth) url := fmt.Sprintf("%s/%s/interactions", baseURL, glAPIVersion) @@ -492,6 +493,7 @@ func (e *GeminiExecutor) executeInteractions(ctx context.Context, auth *cliproxy err = statusErr{code: httpResp.StatusCode, msg: string(data)} return resp, err } + continuation.Observe(data) reporter.ObserveResponseModel(data) targetFormat := cliproxyexecutor.ResponseFormatOrSource(opts) var param any @@ -525,6 +527,7 @@ func (e *GeminiExecutor) executeInteractionsStream(ctx context.Context, auth *cl requestPath := helps.PayloadRequestPath(opts) fromProtocol := opts.SourceFormat.String() body = sanitizeGeminiInteractionsUnsupportedInputIDs(body) + continuation, body := helps.PrepareAntigravityInteractions(auth, req, opts, targetName, body) body = helps.SetBoolIfDifferent(body, "stream", true) baseURL := resolveGeminiBaseURL(auth) url := fmt.Sprintf("%s/%s/interactions", baseURL, glAPIVersion) @@ -607,6 +610,7 @@ func (e *GeminiExecutor) executeInteractionsStream(ctx context.Context, auth *cl payload = trimmed } if len(payload) > 0 { + continuation.Observe(payload) reporter.ObserveResponseModel(payload) if detail, ok := helps.ParseInteractionsStreamUsage(payload); ok { streamUsage.Observe(detail, true) diff --git a/internal/runtime/executor/gemini_interactions_continuation_test.go b/internal/runtime/executor/gemini_interactions_continuation_test.go new file mode 100644 index 00000000000..ac75b0a2a8e --- /dev/null +++ b/internal/runtime/executor/gemini_interactions_continuation_test.go @@ -0,0 +1,119 @@ +package executor + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "testing" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +func TestIssue5190StatelessTwoToolRounds(t *testing.T) { + for _, rule := range []string{"baseline", "override", "filter", "explicit"} { + t.Run(rule, func(t *testing.T) { testIssue5190ToolRounds(t, rule) }) + } +} + +func testIssue5190ToolRounds(t *testing.T, rule string) { + for _, tc := range []struct { + stream bool + format sdktranslator.Format + }{{false, sdktranslator.FormatOpenAI}, {true, sdktranslator.FormatOpenAI}, {false, sdktranslator.FormatOpenAIResponse}, {true, sdktranslator.FormatOpenAIResponse}} { + stream := tc.stream + t.Run(fmt.Sprint(tc.format, stream), func(t *testing.T) { + requests := make(chan []byte, 3) + round := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, errRead := io.ReadAll(r.Body) + if errRead != nil { + t.Error(errRead) + return + } + requests <- body + round++ + step := fmt.Sprintf(`{"type":"function_call","id":"call_%d","name":"external_read_file","arguments":{"path":"x"}}`, round) + interaction := fmt.Sprintf(`{"id":"interaction_%d","environment_id":"env_1","status":"requires_action","steps":[%s]}`, round, step) + if stream { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = fmt.Fprintf(w, "data: {\"event_type\":\"interaction.created\",\"interaction\":{\"id\":\"interaction_%d\",\"environment_id\":\"env_1\"}}\n\ndata: {\"event_type\":\"step.start\",\"index\":0,\"step\":%s}\n\ndata: {\"event_type\":\"interaction.completed\",\"interaction\":%s}\n\n", round, step, interaction) + } else { + _, _ = w.Write([]byte(interaction)) + } + })) + defer server.Close() + cfg := &config.Config{} + models := []config.PayloadModelRule{{Name: "antigravity*", Protocol: "interactions", Exist: []string{"previous_interaction_id"}}} + if rule == "override" { + cfg.Payload.Override = []config.PayloadRule{{Models: models, Params: map[string]any{"previous_interaction_id": "configured", "environment_id": "configured-env", "input": []any{map[string]any{"type": "user_input", "content": "configured-input"}}}}} + } + if rule == "filter" { + cfg.Payload.Filter = []config.PayloadFilterRule{{Models: models, Params: []string{"previous_interaction_id", "environment_id", "input"}}} + } + exec := NewGeminiInteractionsExecutor(cfg) + auth := &cliproxyauth.Auth{ID: t.Name(), Provider: "gemini-interactions", Attributes: map[string]string{"api_key": "key", "base_url": server.URL}} + messages := `{"role":"user","content":"read two files"}` + input := messages + opts := cliproxyexecutor.Options{SourceFormat: tc.format, ResponseFormat: tc.format, Metadata: map[string]any{cliproxyexecutor.CallerScopeMetadataKey: t.Name()}} + for i := 0; i < 3; i++ { + req := cliproxyexecutor.Request{Model: "antigravity-preview-05-2026", Payload: []byte(`{"messages":[` + messages + `],"tools":[{"type":"function","function":{"name":"read_file","parameters":{"type":"object"}}}]}`)} + if tc.format == sdktranslator.FormatOpenAIResponse { + req.Payload = []byte(`{"input":[` + input + `],"tools":[{"type":"function","name":"read_file","parameters":{"type":"object"}}]}`) + } + if i > 0 && rule == "explicit" { + req.Payload = append([]byte(`{"previous_response_id":"explicit",`), req.Payload[1:]...) + } + if stream { + result, errExecute := exec.ExecuteStream(context.Background(), auth, req, opts) + if errExecute != nil { + t.Fatal(errExecute) + } + for chunk := range result.Chunks { + if chunk.Err != nil { + t.Fatal(chunk.Err) + } + } + } else { + if _, errExecute := exec.Execute(context.Background(), auth, req, opts); errExecute != nil { + t.Fatal(errExecute) + } + } + body := <-requests + if i > 0 && rule == "explicit" && gjson.GetBytes(body, "previous_interaction_id").String() != "explicit" { + t.Errorf("explicit continuation lost: %s", body) + } + if i > 0 && rule == "override" { + if gjson.GetBytes(body, "previous_interaction_id").String() != "configured" || gjson.GetBytes(body, "environment_id").String() != "configured-env" || gjson.GetBytes(body, "input.0.content").String() != "configured-input" { + t.Errorf("payload override lost: %s", body) + } + } + if i > 0 && rule == "filter" { + for _, path := range []string{"previous_interaction_id", "environment_id", "input"} { + if gjson.GetBytes(body, path).Exists() { + t.Errorf("filtered %s restored: %s", path, body) + } + } + } + if i > 0 && rule == "baseline" { + if got := gjson.GetBytes(body, "previous_interaction_id").String(); got != fmt.Sprintf("interaction_%d", i) { + t.Errorf("round %d continuation=%q body=%s", i, got, body) + } + if got := gjson.GetBytes(body, "environment_id").String(); got != "env_1" { + t.Errorf("round %d environment=%q", i, got) + } + if got := gjson.GetBytes(body, "input.#").Int(); got != 1 { + t.Errorf("round %d replayed history: %s", i, body) + } + } + input += fmt.Sprintf(`,{"type":"function_call","call_id":"call_%d","name":"read_file","arguments":"{\"path\":\"x\"}"},{"type":"function_call_output","call_id":"call_%d","output":"file content"}`, i+1, i+1) + messages += fmt.Sprintf(`,{"role":"assistant","tool_calls":[{"id":"call_%d","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"x\"}"}}]},{"role":"tool","tool_call_id":"call_%d","content":"file content"}`, i+1, i+1) + } + }) + } +} diff --git a/internal/runtime/executor/gemini_interactions_tool_names_test.go b/internal/runtime/executor/gemini_interactions_tool_names_test.go new file mode 100644 index 00000000000..687c71ef58e --- /dev/null +++ b/internal/runtime/executor/gemini_interactions_tool_names_test.go @@ -0,0 +1,68 @@ +package executor + +import ( + "context" + "fmt" + "strings" + "testing" + + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +func TestIssue5190ToolNamesAcrossChatAndResponses(t *testing.T) { + const model = "antigravity-preview-05-2026" + for _, format := range []sdktranslator.Format{sdktranslator.FormatOpenAI, sdktranslator.FormatOpenAIResponse} { + t.Run(format.String(), func(t *testing.T) { + original := []byte(`{"messages":[{"role":"user","content":"hi"}],"tools":[{"type":"function","function":{"name":"read_file","parameters":{"type":"object"}}},{"type":"function","function":{"name":"external_read_file","parameters":{"type":"object"}}}]}`) + if format == sdktranslator.FormatOpenAIResponse { + original = []byte(`{"input":"hi","tools":[{"type":"function","name":"read_file","parameters":{"type":"object"}},{"type":"function","name":"external_read_file","parameters":{"type":"object"}}]}`) + } + request := sdktranslator.TranslateRequest(format, sdktranslator.FormatInteractions, model, original, false) + for i, upstream := range []string{"external_read_file", "external_external_read_file"} { + if got := gjson.GetBytes(request, fmt.Sprintf("tools.%d.name", i)).String(); got != upstream { + t.Fatalf("upstream tool=%q want=%q: %s", got, upstream, request) + } + name := []string{"read_file", "external_read_file"}[i] + raw := []byte(fmt.Sprintf(`{"id":"interaction_1","model":%q,"status":"requires_action","steps":[{"type":"function_call","id":"call_1","name":%q,"arguments":{}}]}`, model, upstream)) + var param any + out := sdktranslator.TranslateNonStream(context.Background(), sdktranslator.FormatInteractions, format, model, original, request, raw, ¶m) + path := "choices.0.message.tool_calls.0.function.name" + if format == sdktranslator.FormatOpenAIResponse { + path = "output.0.name" + } + if got := gjson.GetBytes(out, path).String(); got != name { + t.Errorf("nonstream tool=%q want=%q: %s", got, name, out) + } + param = nil + events := []string{ + fmt.Sprintf(`{"event_type":"interaction.created","interaction":{"id":"interaction_1","model":%q}}`, model), + fmt.Sprintf(`{"event_type":"step.start","index":0,"step":{"type":"function_call","id":"call_1","name":%q,"arguments":{}}}`, upstream), + `{"event_type":"step.stop","index":0}`, + `{"event_type":"interaction.completed","interaction":{"id":"interaction_1","status":"requires_action"}}`, + } + found := false + for _, event := range events { + for _, chunk := range sdktranslator.TranslateStream(context.Background(), sdktranslator.FormatInteractions, format, model, original, request, []byte("data: "+event), ¶m) { + for _, line := range strings.Split(string(chunk), "\n") { + line = strings.TrimSpace(strings.TrimPrefix(line, "data:")) + path := "choices.0.delta.tool_calls.0.function.name" + if format == sdktranslator.FormatOpenAIResponse { + path = "item.name" + } + if got := gjson.Get(line, path); got.Exists() { + found = true + if got.String() != name { + t.Errorf("stream tool=%q want=%q: %s", got.String(), name, line) + } + } + } + } + } + if !found { + t.Error("missing streamed tool name") + } + } + }) + } +} diff --git a/internal/runtime/executor/helps/antigravity_interactions_state.go b/internal/runtime/executor/helps/antigravity_interactions_state.go new file mode 100644 index 00000000000..1c370200740 --- /dev/null +++ b/internal/runtime/executor/helps/antigravity_interactions_state.go @@ -0,0 +1,159 @@ +package helps + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "strings" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/cache" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/session" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +var antigravityInteractionsSessions = cache.NewInteractionsSessionCache() + +// AntigravityInteractionsState tracks a single request, including streamed steps. +// The cache namespace is computed before continuation rewriting and payload rules. +type AntigravityInteractionsState struct { + key string + id string + environment string + calls []string +} + +func interactionsDigest(value any) string { + encoded, errMarshal := json.Marshal(value) + if errMarshal != nil { + return "" + } + sum := sha256.Sum256(encoded) + return hex.EncodeToString(sum[:]) +} + +// PrepareAntigravityInteractions restores only a matching tool-result suffix. +// Explicit continuation always wins, including an explicitly empty field. +func PrepareAntigravityInteractions(auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, model string, body []byte) (*AntigravityInteractionsState, []byte) { + state := &AntigravityInteractionsState{} + if !strings.HasPrefix(strings.ToLower(model), "antigravity") || auth == nil { + return state, body + } + caller, _ := opts.Metadata[cliproxyexecutor.CallerScopeMetadataKey].(string) + if caller == "" { + caller, _ = req.Metadata[cliproxyexecutor.CallerScopeMetadataKey].(string) + } + if caller == "" { + caller = opts.Headers.Get("Authorization") + } + original := opts.OriginalRequest + if len(original) == 0 { + original = req.Payload + } + identity := "" + if info, ok := session.ExtractSessionInfo(opts.Headers, original, opts.Metadata); ok { + identity = info.SessionID + } + input := gjson.GetBytes(body, "input").Array() + if identity == "" { + lastUser := -1 + for i, step := range input { + if step.Get("type").String() == "user_input" { + lastUser = i + } + } + if lastUser < 0 { + return state, body + } + // Decode JSON objects before hashing, so whitespace and key order do not + // split a conversation. Tool rounds after the last user are excluded. + prefix := make([]json.RawMessage, 0, lastUser+1) + for _, step := range input[:lastUser+1] { + prefix = append(prefix, json.RawMessage(step.Raw)) + } + raw, errMarshal := json.Marshal(map[string]any{"input": prefix, "system_instruction": gjson.GetBytes(body, "system_instruction").Value()}) + if errMarshal != nil { + return state, body + } + decoder := json.NewDecoder(bytes.NewReader(raw)) + decoder.UseNumber() + var canonical any + if errDecode := decoder.Decode(&canonical); errDecode != nil { + return state, body + } + identity = interactionsDigest(canonical) + } + state.key = interactionsDigest([]string{caller, auth.ID, auth.Provider, auth.Attributes["api_key"], auth.Attributes["base_url"], model, identity}) + if gjson.GetBytes(body, "previous_interaction_id").Exists() { + return state, body + } + start := len(input) + var calls []string + for start > 0 && input[start-1].Get("type").String() == "function_result" { + start-- + calls = append(calls, input[start].Get("call_id").String()) + } + callKey := cache.InteractionsCallKey(calls) + if callKey == "" { + return state, body + } + cached, ok := antigravityInteractionsSessions.Get(state.key + ":" + callKey) + if !ok { + return state, body + } + body, _ = sjson.SetBytes(body, "previous_interaction_id", cached.ID) + if !gjson.GetBytes(body, "environment_id").Exists() && cached.Environment != "" { + body, _ = sjson.SetBytes(body, "environment_id", cached.Environment) + } + results := make([]json.RawMessage, 0, len(input)-start) + for _, step := range input[start:] { + results = append(results, json.RawMessage(step.Raw)) + } + body, _ = sjson.SetBytes(body, "input", results) + return state, body +} + +// Observe records only completed requires_action interactions, never failed or +// truncated streams. Stream events may carry steps outside the final snapshot. +func (s *AntigravityInteractionsState) Observe(payload []byte) { + if s == nil || s.key == "" { + return + } + root := gjson.ParseBytes(payload) + event := root.Get("event_type").String() + interaction := root + if event != "" { + interaction = root.Get("interaction") + } + if id := interaction.Get("id").String(); id != "" { + s.id = id + } + if environment := interaction.Get("environment_id").String(); environment != "" { + s.environment = environment + } + if event == "step.start" && root.Get("step.type").String() == "function_call" { + s.calls = append(s.calls, root.Get("step.id").String()) + } + if event != "" && event != "interaction.completed" { + return + } + if interaction.Get("status").String() != "requires_action" || s.id == "" { + return + } + if steps := interaction.Get("steps"); steps.IsArray() { + s.calls = nil + for _, step := range steps.Array() { + if step.Get("type").String() == "function_call" { + s.calls = append(s.calls, step.Get("id").String()) + } + } + } + callKey := cache.InteractionsCallKey(s.calls) + if callKey == "" { + return + } + antigravityInteractionsSessions.Put(s.key+":"+callKey, cache.InteractionsContinuation{ID: s.id, Environment: s.environment}) +} diff --git a/internal/runtime/executor/helps/antigravity_interactions_state_test.go b/internal/runtime/executor/helps/antigravity_interactions_state_test.go new file mode 100644 index 00000000000..213ca42b605 --- /dev/null +++ b/internal/runtime/executor/helps/antigravity_interactions_state_test.go @@ -0,0 +1,74 @@ +package helps + +import ( + "testing" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/cache" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + "github.com/tidwall/gjson" +) + +func TestIssue5190ContinuationIsolation(t *testing.T) { + previous := antigravityInteractionsSessions + t.Cleanup(func() { antigravityInteractionsSessions = previous }) + const initial = `{"input":[{"type":"user_input","content":[{"type":"text","text":"hi"}]}]}` + const continued = `{"input":[{"content":[{"text":"hi","type":"text"}],"type":"user_input"},{"type":"function_call","id":"call_1"},{"type":"function_result","call_id":"call_1","result":"ok"}]}` + const model = "antigravity-preview-05-2026" + for _, name := range []string{"match", "caller", "credential", "key", "model", "call", "prefix", "explicit", "environment", "missing", "partial", "failed"} { + t.Run(name, func(t *testing.T) { + antigravityInteractionsSessions = cache.NewInteractionsSessionCache() + auth := &cliproxyauth.Auth{ID: "credential", Provider: "gemini-interactions", Attributes: map[string]string{"api_key": "secret"}} + opts := cliproxyexecutor.Options{Metadata: map[string]any{cliproxyexecutor.CallerScopeMetadataKey: "caller"}} + req := cliproxyexecutor.Request{} + state, _ := PrepareAntigravityInteractions(auth, req, opts, model, []byte(initial)) + response := `{"id":"interaction_1","environment_id":"env_1","status":"requires_action","steps":[{"type":"function_call","id":"call_1"}]}` + if name == "partial" { + response = `{"id":"interaction_1","status":"requires_action","steps":[{"type":"function_call","id":"call_1"},{"type":"function_call","id":"call_2"}]}` + } + if name == "failed" { + response = `{"id":"interaction_1","status":"failed","steps":[{"type":"function_call","id":"call_1"}]}` + } + state.Observe([]byte(response)) + body := []byte(continued) + targetModel := model + want := "" + switch name { + case "match": + want = "interaction_1" + case "caller": + opts.Metadata[cliproxyexecutor.CallerScopeMetadataKey] = "other" + case "credential": + auth.ID = "other" + case "key": + auth.Attributes["api_key"] = "rotated" + case "model": + targetModel = "antigravity-other" + case "call": + body = []byte(`{"input":[{"type":"user_input","content":[{"type":"text","text":"hi"}]},{"type":"function_result","call_id":"other","result":"ok"}]}`) + case "prefix": + body = []byte(`{"input":[{"type":"user_input","content":[{"type":"text","text":"different"}]},{"type":"function_result","call_id":"call_1","result":"ok"}]}`) + case "missing": + body = []byte(initial) + case "explicit": + body = append([]byte(`{"previous_interaction_id":"explicit",`), body[1:]...) + want = "explicit" + case "environment": + body = append([]byte(`{"environment_id":"explicit-env",`), body[1:]...) + want = "interaction_1" + } + _, rewritten := PrepareAntigravityInteractions(auth, req, opts, targetModel, body) + if got := gjson.GetBytes(rewritten, "previous_interaction_id").String(); got != want { + t.Fatalf("continuation=%q want=%q body=%s", got, want, rewritten) + } + if want == "" || name == "explicit" { + if string(body) != string(rewritten) { + t.Fatalf("unexpected rewrite: %s", rewritten) + } + } + if name == "environment" && gjson.GetBytes(rewritten, "environment_id").String() != "explicit-env" { + t.Fatalf("explicit environment overwritten: %s", rewritten) + } + }) + } +} diff --git a/internal/translator/common/antigravity_tools.go b/internal/translator/common/antigravity_tools.go index a4219947632..edab65dca5f 100644 --- a/internal/translator/common/antigravity_tools.go +++ b/internal/translator/common/antigravity_tools.go @@ -19,15 +19,23 @@ var antigravityCollidingToolNames = map[string]struct{}{ } // AntigravityToolNameToUpstream maps a client-facing tool name to the name -// sent to the antigravity Interactions API. Names that do not collide are -// returned unchanged. +// sent to the antigravity Interactions API. Escape the entire prefix chain +// ending in an intrinsic name so real external_ names remain distinguishable. func AntigravityToolNameToUpstream(name string) string { - if _, collides := antigravityCollidingToolNames[name]; collides { + if antigravityIntrinsicBase(name) { return ExternalToolPrefix + name } return name } +func antigravityIntrinsicBase(name string) bool { + for strings.HasPrefix(name, ExternalToolPrefix) { + name = strings.TrimPrefix(name, ExternalToolPrefix) + } + _, collides := antigravityCollidingToolNames[name] + return collides +} + // AntigravityUpstreamToolNameToClient strips the external prefix from an // upstream tool name before it reaches the client, provided that the base // name is an intrinsic tool that was prefixed to avoid collisions. Non-colliding @@ -35,7 +43,7 @@ func AntigravityToolNameToUpstream(name string) string { func AntigravityUpstreamToolNameToClient(name string) string { if strings.HasPrefix(name, ExternalToolPrefix) { base := strings.TrimPrefix(name, ExternalToolPrefix) - if _, collides := antigravityCollidingToolNames[base]; collides { + if antigravityIntrinsicBase(base) { return base } } diff --git a/internal/translator/common/antigravity_tools_collision_test.go b/internal/translator/common/antigravity_tools_collision_test.go new file mode 100644 index 00000000000..6041b32309c --- /dev/null +++ b/internal/translator/common/antigravity_tools_collision_test.go @@ -0,0 +1,17 @@ +package common + +import "testing" + +func TestIssue5190AntigravityToolNamesAreInjective(t *testing.T) { + seen := map[string]string{} + for _, name := range []string{"read_file", "external_read_file", "external_external_read_file", "write_file", "external_write_file", "execute_code", "external_execute_code", "external_lookup"} { + upstream := AntigravityToolNameToUpstream(name) + if previous, exists := seen[upstream]; exists { + t.Errorf("%q and %q collide as %q", previous, name, upstream) + } + seen[upstream] = name + if restored := AntigravityUpstreamToolNameToClient(upstream); restored != name { + t.Errorf("round trip %q became %q", name, restored) + } + } +} diff --git a/internal/translator/openai/interactions/responses/interactions_openai_responses_response.go b/internal/translator/openai/interactions/responses/interactions_openai_responses_response.go index 491a7f20123..63a5a7357d1 100644 --- a/internal/translator/openai/interactions/responses/interactions_openai_responses_response.go +++ b/internal/translator/openai/interactions/responses/interactions_openai_responses_response.go @@ -1532,15 +1532,10 @@ func interactionsToolIdentityMap(rawJSON []byte, forAntigravity bool) map[string identities := make(map[string]util.ResponsesToolIdentity) for name, descriptor := range util.CollectResponsesToolWinners(root) { identity := util.ResponsesToolIdentity{Name: descriptor.LocalName, Namespace: descriptor.Namespace, Custom: descriptor.ToolType == "custom", ApplyPatch: applypatch.IsCustomTool(descriptor.Tool)} - identities[name] = identity - } - if forAntigravity { - for name, descriptor := range util.CollectResponsesToolWinners(root) { - upstreamName := translatorcommon.AntigravityToolNameToUpstream(name) - if _, exists := identities[upstreamName]; !exists { - identities[upstreamName] = util.ResponsesToolIdentity{Name: descriptor.LocalName, Namespace: descriptor.Namespace, Custom: descriptor.ToolType == "custom", ApplyPatch: applypatch.IsCustomTool(descriptor.Tool)} - } + if forAntigravity { + name = translatorcommon.AntigravityToolNameToUpstream(name) } + identities[name] = identity } return identities } diff --git a/sdk/api/handlers/handlers_interceptors.go b/sdk/api/handlers/handlers_interceptors.go index a8acb2a9570..734232bc92a 100644 --- a/sdk/api/handlers/handlers_interceptors.go +++ b/sdk/api/handlers/handlers_interceptors.go @@ -623,6 +623,9 @@ func (h *BaseAPIHandler) applyResponseInterceptors(ctx context.Context, requestI return body, responseHeaders } +// ModelDetailIDContextKey requests selection from the final, plugin-filtered catalog. +const ModelDetailIDContextKey = "cliproxy.model_detail_id" + // WriteModelListResponse serializes the model-list payload, applies plugin response interceptors // if a plugin host is configured, and writes the resulting headers and body to the Gin context. func (h *BaseAPIHandler) WriteModelListResponse(c *gin.Context, sourceFormat string, payload any) { @@ -646,6 +649,7 @@ func (h *BaseAPIHandler) WriteModelListResponse(c *gin.Context, sourceFormat str "Content-Type": []string{"application/json; charset=utf-8"}, } + var lifecycle *requestLifecycleTracker host := h.interceptorHost() if host != nil { ctx := context.Background() @@ -656,7 +660,7 @@ func (h *BaseAPIHandler) WriteModelListResponse(c *gin.Context, sourceFormat str ctx = reqCtx } } - lifecycle := h.newRequestLifecycleTracker(ctx, sourceFormat, "", "", false, nil, "") + lifecycle = h.newRequestLifecycleTracker(ctx, sourceFormat, "", "", false, nil, "") resp := interceptResponse(ctx, host, pluginapi.ResponseInterceptRequest{ RequestID: lifecycle.requestID(), SourceFormat: sourceFormat, @@ -679,9 +683,44 @@ func (h *BaseAPIHandler) WriteModelListResponse(c *gin.Context, sourceFormat str c.Writer.Header()[key] = append([]string(nil), values...) } } - lifecycle.complete(pluginapi.RequestCompletionSucceeded, http.StatusOK, nil) } + if modelID, detail := c.Get(ModelDetailIDContextKey); detail { + c.Writer.Header().Del("Content-Length") + var catalog struct { + Data []json.RawMessage `json:"data"` + Models []json.RawMessage `json:"models"` + } + if errUnmarshal := json.Unmarshal(body, &catalog); errUnmarshal != nil { + lifecycle.complete(pluginapi.RequestCompletionFailed, http.StatusBadGateway, errUnmarshal) + c.JSON(http.StatusBadGateway, gin.H{"error": gin.H{"message": "Invalid model catalog", "type": "api_error"}}) + return + } + var selected json.RawMessage + for _, model := range append(catalog.Data, catalog.Models...) { + var entry struct { + ID string `json:"id"` + Slug string `json:"slug"` + } + if errUnmarshal := json.Unmarshal(model, &entry); errUnmarshal != nil { + continue + } + if entry.ID == "" { + entry.ID = entry.Slug + } + if entry.ID != "" && entry.ID == modelID { + selected = model + break + } + } + if selected == nil { + lifecycle.complete(pluginapi.RequestCompletionFailed, http.StatusNotFound, nil) + c.JSON(http.StatusNotFound, gin.H{"error": gin.H{"message": "Model not found", "type": "invalid_request_error", "code": "model_not_found"}}) + return + } + body = selected + } + lifecycle.complete(pluginapi.RequestCompletionSucceeded, http.StatusOK, nil) if c.Writer.Header().Get("Content-Type") == "" { c.Header("Content-Type", "application/json; charset=utf-8") } From 33ec5502c38ac6841a0754577ebff2483fa10cef Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Sun, 4 Oct 2026 05:50:40 +0800 Subject: [PATCH 032/142] fix(claude): refine model version parsing for assistant prefill rejection - Strip provider namespaces and prefix before evaluating model family - Parse major and minor version numbers dynamically while ignoring snapshot dates - Correctly identify unsupported assistant prefill models for Fable, Opus 5+, and Sonnet 4.6+ Closes: #5483 --- .../claude_openai-responses_request.go | 35 ++++++++++++++++--- .../claude_openai-responses_request_test.go | 26 ++++++++++++++ 2 files changed, 57 insertions(+), 4 deletions(-) diff --git a/internal/translator/claude/openai/responses/claude_openai-responses_request.go b/internal/translator/claude/openai/responses/claude_openai-responses_request.go index 9c880b7ca23..d4251a62726 100644 --- a/internal/translator/claude/openai/responses/claude_openai-responses_request.go +++ b/internal/translator/claude/openai/responses/claude_openai-responses_request.go @@ -727,12 +727,39 @@ func stripTrailingClaudeThinkingBlocks(messages [][]byte) [][]byte { // disallows trailing assistant prefill in its conversation history. func claudeModelRejectsAssistantPrefill(modelName string) bool { normalized := strings.ToLower(strings.TrimSpace(modelName)) - for _, family := range []string{"fable", "opus-5", "sonnet-4-6"} { - if strings.Contains(normalized, family) { - return true + // Provider namespaces are not part of the model family. + if index := strings.LastIndexByte(normalized, '/'); index >= 0 { + normalized = normalized[index+1:] + } + normalized = strings.TrimPrefix(normalized, "claude-") + tokens := strings.Split(strings.ReplaceAll(normalized, ".", "-"), "-") + if tokens[0] == "fable" { + return true + } + if len(tokens) < 2 || (tokens[0] != "opus" && tokens[0] != "sonnet") { + return false + } + parseVersion := func(token string) int { + // Eight-digit snapshot dates must never be treated as versions. + if token == "" || len(token) >= 8 { + return -1 } + for _, digit := range token { + if digit < '0' || digit > '9' { + return -1 + } + } + version, errAtoi := strconv.Atoi(token) + if errAtoi != nil { + return -1 + } + return version + } + major := parseVersion(tokens[1]) + if major >= 5 { + return true } - return false + return tokens[0] == "sonnet" && major == 4 && len(tokens) > 2 && parseVersion(tokens[2]) >= 6 } // responsesSystemUnsupportedBlock represents a system-level content part that diff --git a/internal/translator/claude/openai/responses/claude_openai-responses_request_test.go b/internal/translator/claude/openai/responses/claude_openai-responses_request_test.go index 655adac6742..d95d837271e 100644 --- a/internal/translator/claude/openai/responses/claude_openai-responses_request_test.go +++ b/internal/translator/claude/openai/responses/claude_openai-responses_request_test.go @@ -2036,6 +2036,18 @@ func TestConvertOpenAIResponsesRequestToClaude_UnsupportedPrefillModelsStripTrai "claude-fable-5", "claude-opus-5", "claude-sonnet-4-6", + "fable", + "opus-5", + "sonnet-4.6", + "anthropic/claude-opus-5-thinking", + "claude-sonnet-4.6", + "claude-sonnet-4-7", + "claude-sonnet-4-10", + "claude-sonnet-5", + "claude-opus-6", + "claude-opus-5.1", + "claude-sonnet-4-6-20260217", + " ANTHROPIC/CLAUDE-OPUS-5-THINKING ", } for _, model := range unsupportedModels { t.Run(model, func(t *testing.T) { @@ -2065,6 +2077,20 @@ func TestConvertOpenAIResponsesRequestToClaude_SupportedPrefillModelsPreserveAss supportedModels := []string{ "claude-sonnet-4-5", "claude-haiku-4-5", + "claude-3-opus-20240229", + "claude-opus-20240229", + "claude-sonnet-4-20260217", + "claude-sonnet-4.5", + "not-a-fable-model", + "my-custom-opus-5-wrapper", + "my-sonnet-4-6-wrapper", + "claude-fabled-5", + "claude-opus-5foo", + "claude-sonnet-4-6foo", + "fable/gpt-4o", + "opus", + "sonnet", + "", } for _, model := range supportedModels { t.Run(model, func(t *testing.T) { From 6d06098dbebeb550da7ab51446916f40ebc5e54d Mon Sep 17 00:00:00 2001 From: Vayun Godara Date: Sun, 4 Oct 2026 00:18:09 +0200 Subject: [PATCH 033/142] docs(readme): add cliproxy-rs to More choices --- README.md | 4 ++++ README_CN.md | 4 ++++ README_JA.md | 4 ++++ 3 files changed, 12 insertions(+) diff --git a/README.md b/README.md index 041ad841417..7dd3a4008be 100644 --- a/README.md +++ b/README.md @@ -320,6 +320,10 @@ OmniRoute is an AI gateway for multi-provider LLMs: an OpenAI-compatible endpoin This is a tool built with Tauri 2 + Vue 3 for managing multiple OpenAI Codex desktop accounts. Switch between saved ChatGPT/Codex certification profiles, check 5-hour and weekly quota usage in real time, verify token health, view active account details, and import or save auth.json files without manual copying. +### [cliproxy-rs](https://github.com/vayungodara/cliproxy-rs) + +A Rust port of CLIProxyAPI that reads the same `config.yaml` and auth files and serves the same routes and v8 Management API, so you can switch between the two in either direction. Ships as a single binary with the management dashboard built in (per-account 5-hour and weekly quota view, account sign-in, client setup guides), and adds an opt-in `soonest-reset` routing strategy that spends the account whose weekly window resets first. + > [!NOTE] > If you have developed a port of CLIProxyAPI or a project inspired by it, please open a PR to add it to this list. diff --git a/README_CN.md b/README_CN.md index e5bd19bc0c1..33f710ca2a9 100644 --- a/README_CN.md +++ b/README_CN.md @@ -313,6 +313,10 @@ OmniRoute 是一个面向多供应商大语言模型的 AI 网关:它提供兼 这是一个使用 Tauri 2 + Vue 3 构建的工具,用于管理多个 OpenAI Codex 桌面账户。它可以在已保存的 ChatGPT/Codex 认证配置之间切换,实时查看 5 小时和每周配额使用情况,验证 token 健康状态,查看当前账户详情,并在无需手动复制的情况下导入或保存 auth.json 文件。 +### [cliproxy-rs](https://github.com/vayungodara/cliproxy-rs) + +CLIProxyAPI 的 Rust 移植版,读取相同的 `config.yaml` 和认证文件,提供相同的路由和 v8 管理 API,可以在两者之间双向切换。单个二进制文件内置管理面板(按账户显示 5 小时和每周配额、账户登录、客户端配置指南),并新增可选的 `soonest-reset` 路由策略,优先使用每周额度最先重置的账户。 + > [!NOTE] > 如果你开发了 CLIProxyAPI 的移植或衍生项目,请提交 PR 将其添加到此列表中。 diff --git a/README_JA.md b/README_JA.md index dfa6dc8da33..41167ec50db 100644 --- a/README_JA.md +++ b/README_JA.md @@ -312,6 +312,10 @@ OmniRouteはマルチプロバイダーLLM向けのAIゲートウェイです: Tauri 2 + Vue 3で構築された、複数のOpenAI Codexデスクトップアカウントを管理するためのツールです。保存済みのChatGPT/Codex認証プロファイルを切り替え、5時間および週次クォータ使用量をリアルタイムで確認し、tokenの状態を検証し、現在のアカウント詳細を表示し、手動コピーなしでauth.jsonファイルをインポートまたは保存できます。 +### [cliproxy-rs](https://github.com/vayungodara/cliproxy-rs) + +CLIProxyAPIのRust移植版です。同じ`config.yaml`と認証ファイルを読み込み、同じルートとv8 Management APIを提供するため、両者の間をどちらの方向にも切り替えられます。管理ダッシュボード(アカウントごとの5時間・週次クォータ表示、アカウントのサインイン、クライアント設定ガイド)を内蔵した単一バイナリで、週次ウィンドウが最も早くリセットされるアカウントから使うオプトインの`soonest-reset`ルーティング戦略も追加しています。 + > [!NOTE] > CLIProxyAPIの移植版またはそれに触発されたプロジェクトを開発した場合は、PRを送ってこのリストに追加してください。 From 8ef43e4df3b216a42493105d31c2873b69191473 Mon Sep 17 00:00:00 2001 From: Supra4E8C Date: Sun, 4 Oct 2026 13:30:43 +0800 Subject: [PATCH 034/142] fix(readme): remove AxisNow sponsorship details from README files --- README.md | 4 ---- README_CN.md | 4 ---- README_JA.md | 4 ---- 3 files changed, 12 deletions(-) diff --git a/README.md b/README.md index 041ad841417..53fbeb421cb 100644 --- a/README.md +++ b/README.md @@ -89,10 +89,6 @@ PackyCode provides special discounts for our software users: register using Thanks to APIMart for sponsoring this project! APIMart is a low-cost API platform for AI image & video generation — GPT-Image-2 from $0.006/image, 160+ images per dollar. One async API covers both image and video: submit a task, get an ID, fetch results via polling or callback. Batch tens of thousands of images without timeouts, switch models without changing code. Pay-as-you-go with no monthly fee — sign up here to get started. -AxisNow -Protect and accelerate websites and APIs while optimizing access from both mainland China and the rest of the world. Extend acceleration and security to native and mobile apps through client SDKs — self-hosted private CDN | subscription-based DDoS-protected CDN | independently controlled, flexibly composable CDN networks. - - Swiftproxy Swiftproxy provides 90M+ clean residential IPs across 220+ locations, supporting HTTP(S)/SOCKS5, IP rotation, Sticky Sessions, and precise location targeting. It helps AI API tools and automation workflows access online services reliably from different locations, making it ideal for API requests, web access, data collection, and location-based testing. Residential proxies from $0.7/GB. Free testing is available, with 10% off using code PROXY90. Try Swiftproxy Now diff --git a/README_CN.md b/README_CN.md index e5bd19bc0c1..781932413f3 100644 --- a/README_CN.md +++ b/README_CN.md @@ -84,10 +84,6 @@ PackyCode 为本软件用户提供了特别优惠:使用此注册链接注册即可开用。 -AxisNow -保护并加速网站与 API,兼顾中国大陆及全球的访问体验,并通过客户端 SDK,将加速与安全能力延伸至原生/移动 App — 自建私有部署 CDN|订阅式高防 CDN|自主可控、灵活组合的 CDN 网络。 - - Swiftproxy Swiftproxy 提供 9000万+ 纯净住宅 IP,覆盖全球 220+ 个国家和地区,支持 HTTP(S)/SOCKS5、IP 轮换、Sticky Session 及精准地域定位。帮助 AI API 工具和自动化工作流从不同地区稳定访问在线服务,适用于 API 请求、网页访问、数据采集及地域测试等场景。住宅代理低至 $0.7/GB,支持免费测试,使用优惠码 PROXY90 可享 9 折优惠。立即体验 Swiftproxy。 diff --git a/README_JA.md b/README_JA.md index dfa6dc8da33..a81582e8c65 100644 --- a/README_JA.md +++ b/README_JA.md @@ -84,10 +84,6 @@ PackyCodeは当ソフトウェアのユーザーに特別割引を提供して APIMartによる本プロジェクトへのご支援に感謝します!APIMartは、AI画像・動画生成に特化した低価格APIプラットフォームです。GPT-Image-2は1枚あたりわずか$0.006で、1ドルで160枚以上の画像を生成できます。画像と動画の両方を1つの非同期APIで扱えます。タスクを送信してIDを取得し、ポーリングまたはコールバックで結果を受け取れます。数万枚規模の画像をタイムアウトなしでバッチ生成でき、コードを変更せずにモデルを切り替えられます。従量課金制で月額料金は不要です。こちらの登録リンクからすぐに始められます。 -AxisNow -中国本土と世界各地の双方からのアクセス体験に配慮しながら、WebサイトとAPIを保護・高速化します。さらにクライアントSDKを通じて、高速化とセキュリティの機能をネイティブ/モバイルアプリにも拡張します — セルフホスト型プライベートCDN|サブスクリプション型DDoS防御CDN|自律的に制御でき、柔軟に組み合わせられるCDNネットワーク。 - - Swiftproxy Swiftproxyは、世界220以上の国と地域をカバーする9,000万以上のクリーンな住宅IPを提供し、HTTP(S)/SOCKS5、IPローテーション、Sticky Session、詳細な地域指定に対応しています。AI APIツールや自動化ワークフローが異なる地域からオンラインサービスへ安定してアクセスできるよう支援し、APIリクエスト、Webアクセス、データ収集、地域別テストなどに最適です。住宅プロキシは$0.7/GBから利用でき、無料テストにも対応しています。割引コードPROXY90の使用で10%割引になります。今すぐSwiftproxyを試す From 1672be5d25bdd84f360a49de3515a76ff2973e38 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Sun, 4 Oct 2026 13:34:54 +0800 Subject: [PATCH 035/142] feat(registry): support custom model catalog sources and dynamic reload - Add `CatalogSources` configuration to allow overriding general, Codex, and Devin catalog sources via URLs or absolute local file paths - Centralize model catalog fetch, validation, and scheduled background updates in `catalogUpdater` - Support dynamic catalog source updates and hot reloading during service runtime - Update `--local-model` flag to use embedded models as defaults while respecting explicit overrides Closes: #6319 Closes: #5024 --- cmd/server/main.go | 33 +-- cmd/server/main_test.go | 53 ---- config.example.yaml | 11 + internal/config/config.go | 3 + internal/config/config_v8.go | 10 +- internal/config/model_catalogs.go | 6 + internal/config/model_catalogs_test.go | 85 ++++++ internal/registry/catalog_config.go | 29 ++ .../catalog_devin_notification_test.go | 41 +++ internal/registry/catalog_policy_test.go | 45 +++ internal/registry/catalog_reload_test.go | 86 ++++++ internal/registry/catalog_sources.go | 263 ++++++++++++++++++ internal/registry/catalog_sources_test.go | 127 +++++++++ .../registry/codex_client_models_updater.go | 75 +---- internal/registry/devin_models_updater.go | 69 +---- internal/registry/model_updater.go | 126 +-------- sdk/cliproxy/service_catalogs_test.go | 99 +++++++ sdk/cliproxy/service_config.go | 9 +- sdk/cliproxy/service_lifecycle.go | 12 + sdk/config/config.go | 2 + 20 files changed, 844 insertions(+), 340 deletions(-) create mode 100644 internal/config/model_catalogs.go create mode 100644 internal/config/model_catalogs_test.go create mode 100644 internal/registry/catalog_config.go create mode 100644 internal/registry/catalog_devin_notification_test.go create mode 100644 internal/registry/catalog_policy_test.go create mode 100644 internal/registry/catalog_reload_test.go create mode 100644 internal/registry/catalog_sources.go create mode 100644 internal/registry/catalog_sources_test.go create mode 100644 sdk/cliproxy/service_catalogs_test.go diff --git a/cmd/server/main.go b/cmd/server/main.go index 2b990778238..98139c7b437 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -159,7 +159,7 @@ func main() { flag.BoolVar(&tuiMode, "tui", false, "Start with terminal management UI") flag.BoolVar(&standalone, "standalone", false, "In TUI mode, start an embedded local server") flag.StringVar(&managementBaseURL, "management-base-url", "", "Base URL of remote management API for TUI client mode (e.g. https://proxy.example.com)") - flag.BoolVar(&localModel, "local-model", false, "Use embedded models.json and codex_client_models.json only, skip remote model catalog fetching") + flag.BoolVar(&localModel, "local-model", false, "Use embedded model catalogs unless models.catalog, models.codex-catalog, or models.devin-catalog explicitly overrides the source") flag.CommandLine.Usage = func() { out := flag.CommandLine.Output() @@ -742,14 +742,14 @@ func main() { return } if localModel && (!tuiMode || standalone) { - log.Info("Local model mode: using embedded model catalogs, remote model updates disabled") + log.Info("Local model mode: using embedded catalogs unless an explicit catalog source is configured") } if tuiMode { if standalone { // Standalone mode: start an embedded local server and connect TUI client to it. managementasset.StartAutoUpdater(context.Background(), configFilePath) misc.StartAntigravityVersionUpdater(context.Background()) - startModelCatalogUpdaters(localModel, cfg.Home.Enabled) + registry.SetLocalModelCatalogs(localModel) hook := tui.NewLogHook(2000) hook.SetFormatter(&logging.LogFormatter{}) log.AddHook(hook) @@ -824,7 +824,7 @@ func main() { // Start the main proxy service managementasset.StartAutoUpdater(context.Background(), configFilePath) misc.StartAntigravityVersionUpdater(context.Background()) - startModelCatalogUpdaters(localModel, cfg.Home.Enabled) + registry.SetLocalModelCatalogs(localModel) cmd.StartServiceWithPluginHost(cfg, configFilePath, password, pluginHost, serverOptions...) } } @@ -850,31 +850,6 @@ func resolveManagementBaseURL(flagURL string, cfg *config.Config) string { return fmt.Sprintf("http://127.0.0.1:%d", port) } -// modelCatalogUpdaterPlan decides which remote model catalogs should refresh. -// Codex client and Devin catalogs still refresh under Home mode because -// template metadata and Devin models stay edge-local. -func modelCatalogUpdaterPlan(localModel, homeEnabled bool) (startModels, startCodexClient, startDevin bool) { - if localModel { - return false, false, false - } - return !homeEnabled, true, true -} - -func startModelCatalogUpdaters(localModel, homeEnabled bool) { - startModels, startCodexClient, startDevin := modelCatalogUpdaterPlan(localModel, homeEnabled) - if startCodexClient { - registry.StartCodexClientModelsUpdater(context.Background()) - } - if startDevin { - registry.StartDevinModelsUpdater(context.Background()) - } - if startModels { - registry.StartModelsUpdater(context.Background()) - } else if homeEnabled { - log.Info("Home mode: remote models.json updates disabled; Codex client model list follows Home model IDs") - } -} - func pluginBootstrapConfigPath(args []string, defaultPath string) string { for i := 0; i < len(args); i++ { arg := args[i] diff --git a/cmd/server/main_test.go b/cmd/server/main_test.go index 08d88544603..39dcf38b5c6 100644 --- a/cmd/server/main_test.go +++ b/cmd/server/main_test.go @@ -113,59 +113,6 @@ func TestShouldEnableExampleAPIKeySafeMode(t *testing.T) { } } -func TestModelCatalogUpdaterPlan(t *testing.T) { - tests := []struct { - name string - localModel bool - homeEnabled bool - wantModels bool - wantCodexClient bool - wantDevin bool - }{ - { - name: "normal CPA refreshes all catalogs", - localModel: false, - homeEnabled: false, - wantModels: true, - wantCodexClient: true, - wantDevin: true, - }, - { - name: "home mode keeps models.json local and refreshes codex templates and devin", - localModel: false, - homeEnabled: true, - wantModels: false, - wantCodexClient: true, - wantDevin: true, - }, - { - name: "local-model disables all remote catalogs", - localModel: true, - homeEnabled: false, - wantModels: false, - wantCodexClient: false, - wantDevin: false, - }, - { - name: "local-model disables all remote catalogs even under home", - localModel: true, - homeEnabled: true, - wantModels: false, - wantCodexClient: false, - wantDevin: false, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - gotModels, gotCodex, gotDevin := modelCatalogUpdaterPlan(tt.localModel, tt.homeEnabled) - if gotModels != tt.wantModels || gotCodex != tt.wantCodexClient || gotDevin != tt.wantDevin { - t.Fatalf("modelCatalogUpdaterPlan(%v, %v) = (%v, %v, %v), want (%v, %v, %v)", - tt.localModel, tt.homeEnabled, gotModels, gotCodex, gotDevin, tt.wantModels, tt.wantCodexClient, tt.wantDevin) - } - }) - } -} - func TestHomeConfigPayloadPortApplication(t *testing.T) { tests := []struct { name string diff --git a/config.example.yaml b/config.example.yaml index dd93a0125de..cb4d4e9d5c8 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -9,6 +9,17 @@ # The compatibility notes at the end show old spellings for existing deployments. config-version: 8 +# Optional model catalog sources: http(s) URLs or absolute local file paths. +# Each explicit source overrides --local-model; otherwise --local-model uses +# embedded catalogs, and normal mode uses the official remote sources. +# Failed refreshes retain the last valid catalog; custom sources never fall back +# to official URLs. Files and URLs are refreshed every 3 hours and on source changes. +# Home mode never loads the general catalog, even when explicitly configured. +models: + catalog: "" + codex-catalog: "" + devin-catalog: "" + # Listener, TLS, network discovery, and server operation. server: # Server host/interface to bind to. Default is empty ("") to bind all interfaces (IPv4 + IPv6). diff --git a/internal/config/config.go b/internal/config/config.go index ca3767a5d95..214ec58e946 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -6,6 +6,9 @@ package config // Config represents the application's configuration, loaded from a YAML file. type Config struct { + // Models selects optional catalog sources independently for each catalog. + Models ModelCatalogs `yaml:"models" json:"models"` + SDKConfig `yaml:",inline"` // Host is the network host/interface on which the API server will bind. // Default is empty ("") to bind all interfaces (IPv4 + IPv6). Use "127.0.0.1" or "localhost" for local-only access. diff --git a/internal/config/config_v8.go b/internal/config/config_v8.go index 92cec524605..cc24a40fb83 100644 --- a/internal/config/config_v8.go +++ b/internal/config/config_v8.go @@ -249,6 +249,9 @@ func (cfg *Config) UnmarshalYAML(node *yaml.Node) error { if err = root.Decode(&decoded); err != nil { return err } + if errValidate := decoded.Models.Validate(); errValidate != nil { + return errValidate + } *cfg = Config(decoded) cfg.OAuthOnlyFields = nil source := expandConfigAliases(node) @@ -570,7 +573,7 @@ func IsV8ConfigLayout(root *yaml.Node) bool { } func v8AllowedRoots() map[string]bool { - allowed := map[string]bool{"config-version": true, "api-keys": true, "plugins": true, "quota-exceeded": true, "client": true} + allowed := map[string]bool{"models": true, "config-version": true, "api-keys": true, "plugins": true, "quota-exceeded": true, "client": true} for _, path := range v8Paths { section, _, _ := strings.Cut(path.current, ".") allowed[section] = true @@ -907,5 +910,8 @@ func ValidateV8Config(data []byte) error { decoder := yaml.NewDecoder(bytes.NewReader(encoded)) decoder.KnownFields(true) var cfg legacyConfig - return decoder.Decode(&cfg) + if errDecode := decoder.Decode(&cfg); errDecode != nil { + return errDecode + } + return cfg.Models.Validate() } diff --git a/internal/config/model_catalogs.go b/internal/config/model_catalogs.go new file mode 100644 index 00000000000..2b64af2b45a --- /dev/null +++ b/internal/config/model_catalogs.go @@ -0,0 +1,6 @@ +package config + +import "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + +// ModelCatalogs selects optional sources for the process-wide model catalogs. +type ModelCatalogs = registry.CatalogSources diff --git a/internal/config/model_catalogs_test.go b/internal/config/model_catalogs_test.go new file mode 100644 index 00000000000..905efaa7dbe --- /dev/null +++ b/internal/config/model_catalogs_test.go @@ -0,0 +1,85 @@ +package config + +import ( + "fmt" + "os" + "path/filepath" + "testing" + + "gopkg.in/yaml.v3" +) + +func TestModelCatalogConfigRoundTrip(t *testing.T) { + for _, migrate := range []bool{false, true} { + t.Run(fmt.Sprint(migrate), func(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + sources := ModelCatalogs{Catalog: filepath.Join(t.TempDir(), "models.json"), CodexCatalog: "https://example.com/codex.json", DevinCatalog: "http://localhost/devin.json"} + data, errMarshal := yaml.Marshal(map[string]any{"config-version": 8, "models": sources}) + if errMarshal != nil { + t.Fatal(errMarshal) + } + if errValidate := ValidateV8Config(data); errValidate != nil { + t.Fatal(errValidate) + } + if errWrite := os.WriteFile(path, data, 0600); errWrite != nil { + t.Fatal(errWrite) + } + cfg, errLoad := LoadConfig(path) + if errLoad != nil { + t.Fatal(errLoad) + } + if cfg.Models != sources { + t.Fatalf("loaded sources: %+v", cfg.Models) + } + if errSave := SaveConfigPreserveComments(path, cfg, migrate); errSave != nil { + t.Fatal(errSave) + } + saved, errRead := os.ReadFile(path) + if errRead != nil { + t.Fatal(errRead) + } + if errValidate := ValidateV8Config(saved); errValidate != nil { + t.Fatal(errValidate) + } + reloaded, errReload := LoadConfig(path) + if errReload != nil { + t.Fatal(errReload) + } + if reloaded.Models != sources { + t.Fatalf("saved sources: %+v", reloaded.Models) + } + cfg.Models = ModelCatalogs{} + if errSave := SaveConfigPreserveComments(path, cfg, migrate); errSave != nil { + t.Fatal(errSave) + } + cleared, errClear := LoadConfig(path) + if errClear != nil { + t.Fatal(errClear) + } + if cleared.Models != (ModelCatalogs{}) { + t.Fatalf("cleared sources retained: %+v", cleared.Models) + } + + }) + } +} + +func TestModelCatalogConfigValidation(t *testing.T) { + for _, field := range []string{"catalog", "codex-catalog", "devin-catalog"} { + for _, source := range []string{"relative.json", "./models.json", "~/models.json", "ftp://example.com/models", "file:///tmp/models.json", "https:///models"} { + data := []byte(fmt.Sprintf("models:\n %s: %q\n", field, source)) + var cfg Config + if errUnmarshal := yaml.Unmarshal(data, &cfg); errUnmarshal == nil { + t.Fatalf("accepted %s: %s", field, source) + } + if errValidate := ValidateV8Config(data); errValidate == nil { + t.Fatalf("v8 accepted %s: %s", field, source) + } + } + } + for _, raw := range []string{"models: {}", "models: {catalog: ''}", "models: {codex-catalog: 'https://example.com/models.json'}"} { + if errValidate := ValidateV8Config([]byte(raw)); errValidate != nil { + t.Fatal(errValidate) + } + } +} diff --git a/internal/registry/catalog_config.go b/internal/registry/catalog_config.go new file mode 100644 index 00000000000..65d8c9e1ea8 --- /dev/null +++ b/internal/registry/catalog_config.go @@ -0,0 +1,29 @@ +package registry + +import ( + "fmt" + "net/url" + "path/filepath" +) + +// CatalogSources overrides the source of each model catalog independently. +// Empty values retain the process default (embedded or official remote catalogs). +type CatalogSources struct { + Catalog string `yaml:"catalog" json:"catalog,omitempty"` + CodexCatalog string `yaml:"codex-catalog" json:"codex-catalog,omitempty"` + DevinCatalog string `yaml:"devin-catalog" json:"devin-catalog,omitempty"` +} + +// Validate rejects relative paths and unsupported URL schemes. +func (m CatalogSources) Validate() error { + for name, source := range map[string]string{"catalog": m.Catalog, "codex-catalog": m.CodexCatalog, "devin-catalog": m.DevinCatalog} { + if source == "" || filepath.IsAbs(source) { + continue + } + parsed, errParse := url.Parse(source) + if errParse != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Hostname() == "" { + return fmt.Errorf("models.%s must be an http(s) URL or an absolute local path", name) + } + } + return nil +} diff --git a/internal/registry/catalog_devin_notification_test.go b/internal/registry/catalog_devin_notification_test.go new file mode 100644 index 00000000000..42ff94614fc --- /dev/null +++ b/internal/registry/catalog_devin_notification_test.go @@ -0,0 +1,41 @@ +package registry + +import ( + "context" + "reflect" + "testing" +) + +func TestDevinCatalogRefreshNotifiesOnlyOnChange(t *testing.T) { + original := GetDevinModelsJSON() + refreshCallbackMu.Lock() + previousCallback, previousPending := refreshCallback, pendingRefreshChanges + pendingRefreshChanges = nil + var notifications [][]string + refreshCallback = func(providers []string) { notifications = append(notifications, providers) } + refreshCallbackMu.Unlock() + defer func() { + refreshCallbackMu.Lock() + refreshCallback, pendingRefreshChanges = previousCallback, previousPending + refreshCallbackMu.Unlock() + if _, errLoad := loadDevinModelsFromBytes(original, "restore"); errLoad != nil { + t.Error(errLoad) + } + }() + + data := []byte(`{"devin":[{"id":"devin/catalog-notification-regression","display_name":"Catalog notification regression"}]}`) + u := &catalogUpdater{ + fetch: func(context.Context, string) ([]byte, error) { return data, nil }, + publish: devinCatalogUpdater.publish, + } + u.refresh(context.Background(), "test", 0) + if !reflect.DeepEqual(notifications, [][]string{{"devin"}}) { + t.Fatalf("notifications = %v", notifications) + } + u.refresh(context.Background(), "test", 0) + data = []byte(`invalid`) + u.refresh(context.Background(), "test", 0) + if len(notifications) != 1 { + t.Fatalf("unchanged/invalid catalog triggered notifications: %v", notifications) + } +} diff --git a/internal/registry/catalog_policy_test.go b/internal/registry/catalog_policy_test.go new file mode 100644 index 00000000000..2692878d75e --- /dev/null +++ b/internal/registry/catalog_policy_test.go @@ -0,0 +1,45 @@ +package registry + +import ( + "context" + "testing" +) + +func TestEffectiveCatalogSources(t *testing.T) { + for _, local := range []bool{false, true} { + for _, home := range []bool{false, true} { + for mask := 0; mask < 8; mask++ { + sources := CatalogSources{} + fields := []*string{&sources.Catalog, &sources.CodexCatalog, &sources.DevinCatalog} + for index, field := range fields { + if mask&(1< maxCodexClientModelsSize { + return nil, fmt.Errorf("catalog exceeds size limit") + } + return data, nil +} + +func catalogFetcher(embedded []byte, urls []string, validate func([]byte) error) func(context.Context, string) ([]byte, error) { + return func(ctx context.Context, source string) ([]byte, error) { + if source == embeddedCatalogSource { + return embedded, nil + } + sources := urls + if source != "" { + sources = []string{source} + } + for _, candidate := range sources { + data, errRead := readCatalogSource(ctx, candidate) + if errRead == nil && validate(data) == nil { + return data, nil + } + if ctx.Err() != nil { + break + } + } + return nil, fmt.Errorf("no valid model catalog source") + } +} + +func validateCatalogBytes(data []byte) error { + var parsed staticModelsJSON + if errUnmarshal := json.Unmarshal(data, &parsed); errUnmarshal != nil { + return errUnmarshal + } + return validateModelsCatalog(&parsed) +} + +func publishCatalogBytes(data []byte) ([]string, error) { + var parsed staticModelsJSON + if errUnmarshal := json.Unmarshal(data, &parsed); errUnmarshal != nil { + return nil, errUnmarshal + } + if errValidate := validateModelsCatalog(&parsed); errValidate != nil { + return nil, errValidate + } + old := getModels() + if len(parsed.Meta) == 0 && old != nil { + parsed.Meta = old.Meta + } + changed := detectChangedProviders(old, &parsed) + modelsCatalogStore.mu.Lock() + modelsCatalogStore.data = &parsed + modelsCatalogStore.mu.Unlock() + return changed, nil +} + +var generalCatalogUpdater = &catalogUpdater{ + fetch: catalogFetcher(embeddedModelsJSON, modelsURLs, validateCatalogBytes), + publish: publishCatalogBytes, +} +var codexCatalogUpdater = &catalogUpdater{ + fetch: catalogFetcher(embeddedCodexClientModelsJSON, codexClientModelsURLs, ValidateCodexClientModelsJSON), + publish: func(data []byte) ([]string, error) { + _, errLoad := loadCodexClientModelsFromBytes(data, "catalog") + return nil, errLoad + }, +} +var devinCatalogUpdater = &catalogUpdater{ + fetch: catalogFetcher(embeddedDevinModelsJSON, devinModelsURLs, validateDevinCatalogBytes), + publish: func(data []byte) ([]string, error) { + changed, errLoad := loadDevinModelsFromBytes(data, "catalog") + if errLoad == nil && changed { + return []string{"devin"}, nil + } + return nil, errLoad + }, +} + +var catalogRuntime struct { + sync.Mutex + ctx context.Context + local bool +} + +// SetLocalModelCatalogs sets the process default before the service starts. +// Explicit catalog sources still take precedence over this default. +func SetLocalModelCatalogs(local bool) { + catalogRuntime.Lock() + defer catalogRuntime.Unlock() + catalogRuntime.local = local +} + +// StartModelCatalogUpdaters binds process-wide readers to the service lifetime. +func StartModelCatalogUpdaters(ctx context.Context, sources CatalogSources, home bool) { + catalogRuntime.Lock() + defer catalogRuntime.Unlock() + catalogRuntime.ctx = ctx + configureCatalogs(ctx, sources, catalogRuntime.local, home) +} + +// UpdateModelCatalogSources updates an already-started process policy on reload. +// Updates before service startup or after shutdown do not start readers. +func UpdateModelCatalogSources(sources CatalogSources, home bool) { + catalogRuntime.Lock() + defer catalogRuntime.Unlock() + if catalogRuntime.ctx != nil && catalogRuntime.ctx.Err() == nil { + configureCatalogs(catalogRuntime.ctx, sources, catalogRuntime.local, home) + } +} + +func configureCatalogs(ctx context.Context, sources CatalogSources, local, home bool) { + if errValidate := sources.Validate(); errValidate != nil { + log.WithError(errValidate).Warn("invalid catalog sources") + return + } + sources = effectiveCatalogSources(sources, local, home) + generalCatalogUpdater.configure(ctx, sources.Catalog) + codexCatalogUpdater.configure(ctx, sources.CodexCatalog) + devinCatalogUpdater.configure(ctx, sources.DevinCatalog) +} + +func effectiveCatalogSources(sources CatalogSources, local, home bool) CatalogSources { + selectSource := func(source string) string { + if source == "" && local { + return embeddedCatalogSource + } + return source + } + general := selectSource(sources.Catalog) + if home { + general = "disabled" + } + return CatalogSources{Catalog: general, CodexCatalog: selectSource(sources.CodexCatalog), DevinCatalog: selectSource(sources.DevinCatalog)} +} + +func validateDevinCatalogBytes(data []byte) error { + _, errValidate := ValidateDevinModelsJSON(data) + return errValidate +} diff --git a/internal/registry/catalog_sources_test.go b/internal/registry/catalog_sources_test.go new file mode 100644 index 00000000000..336c72e2231 --- /dev/null +++ b/internal/registry/catalog_sources_test.go @@ -0,0 +1,127 @@ +package registry + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "sync/atomic" + "testing" + "time" +) + +func TestCatalogFetcherSources(t *testing.T) { + for _, tc := range []struct { + name string + data []byte + validate func([]byte) error + }{ + {"general", embeddedModelsJSON, validateCatalogBytes}, + {"codex", embeddedCodexClientModelsJSON, ValidateCodexClientModelsJSON}, + {"devin", embeddedDevinModelsJSON, validateDevinCatalogBytes}, + } { + t.Run(tc.name, func(t *testing.T) { + var officialHits atomic.Int32 + official := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { officialHits.Add(1); _, _ = w.Write(tc.data) })) + defer official.Close() + custom := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write(tc.data) })) + defer custom.Close() + broken := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("invalid")) })) + defer broken.Close() + path := filepath.Join(t.TempDir(), "catalog.json") + if errWrite := os.WriteFile(path, tc.data, 0600); errWrite != nil { + t.Fatal(errWrite) + } + fetch := catalogFetcher(tc.data, []string{official.URL}, tc.validate) + for _, source := range []string{embeddedCatalogSource, custom.URL, path} { + data, errFetch := fetch(context.Background(), source) + if errFetch != nil || string(data) != string(tc.data) { + t.Fatalf("source %s: %v", source, errFetch) + } + } + for _, source := range []string{broken.URL, path + ".missing"} { + if _, errFetch := fetch(context.Background(), source); errFetch == nil { + t.Fatal("accepted invalid custom source") + } + } + if officialHits.Load() != 0 { + t.Fatal("custom sources fell back to official URL") + } + if _, errFetch := fetch(context.Background(), ""); errFetch != nil { + t.Fatal(errFetch) + } + if officialHits.Load() != 1 { + t.Fatal("default source was not fetched") + } + if errWrite := os.WriteFile(path, []byte("invalid"), 0600); errWrite != nil { + t.Fatal(errWrite) + } + if _, errFetch := fetch(context.Background(), path); errFetch == nil { + t.Fatal("file was not reread") + } + }) + } +} + +func TestCatalogSourceSwitchRejectsStalePublication(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + started, release, done := make(chan struct{}), make(chan struct{}), make(chan struct{}) + published := make(chan string, 3) + u := &catalogUpdater{ + generation: 1, + fetch: func(ctx context.Context, source string) ([]byte, error) { + if source == "old" { + close(started) + <-release + } + return []byte(source), nil + }, + publish: func(data []byte) ([]string, error) { published <- string(data); return nil, nil }, + } + go func() { u.refresh(ctx, "old", 1); close(done) }() + <-started + u.configure(ctx, "new") + select { + case value := <-published: + if value != "new" { + t.Fatalf("published %s", value) + } + case <-time.After(5 * time.Second): + t.Fatal("new source blocked behind old fetch") + } + close(release) + <-done + select { + case value := <-published: + t.Fatalf("stale publication: %s", value) + default: + } + u.configure(ctx, "new") + u.mu.Lock() + generation := u.generation + u.mu.Unlock() + if generation != 2 { + t.Fatal("unchanged source restarted") + } +} + +func TestCatalogRefreshKeepsLastValidData(t *testing.T) { + last := "last valid" + u := &catalogUpdater{ + fetch: func(context.Context, string) ([]byte, error) { return nil, errors.New("unavailable") }, + publish: func(data []byte) ([]string, error) { last = string(data); return nil, nil }, + } + u.refresh(context.Background(), "", 0) + if last != "last valid" { + t.Fatal("failed fetch changed catalog") + } + u.fetch = func(context.Context, string) ([]byte, error) { return []byte("invalid"), nil } + u.publish = func([]byte) ([]string, error) { return nil, errors.New("invalid") } + u.refresh(context.Background(), "", 0) + if last != "last valid" { + t.Fatal("invalid catalog changed data") + } +} diff --git a/internal/registry/codex_client_models_updater.go b/internal/registry/codex_client_models_updater.go index c556daad0e2..f7b7b0ff73a 100644 --- a/internal/registry/codex_client_models_updater.go +++ b/internal/registry/codex_client_models_updater.go @@ -2,10 +2,6 @@ package registry import ( "context" - "io" - "net/http" - "sync" - "time" log "github.com/sirupsen/logrus" ) @@ -17,31 +13,11 @@ var codexClientModelsURLs = []string{ "https://models.router-for.me/codex_client_models.json", } -var codexClientModelsUpdaterOnce sync.Once - // StartCodexClientModelsUpdater starts a background updater that fetches the // Codex client model catalog immediately and then refreshes it every 3 hours. // Safe to call multiple times; only one updater will run. func StartCodexClientModelsUpdater(ctx context.Context) { - codexClientModelsUpdaterOnce.Do(func() { - go runCodexClientModelsUpdater(ctx) - }) -} - -func runCodexClientModelsUpdater(ctx context.Context) { - tryRefreshCodexClientModels(ctx, "startup Codex client model refresh") - - ticker := time.NewTicker(modelsRefreshInterval) - defer ticker.Stop() - log.Infof("periodic Codex client model refresh started (interval=%s)", modelsRefreshInterval) - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - tryRefreshCodexClientModels(ctx, "periodic Codex client model refresh") - } - } + codexCatalogUpdater.configure(ctx, "") } func tryRefreshCodexClientModels(ctx context.Context, label string) { @@ -64,51 +40,14 @@ func tryRefreshCodexClientModels(ctx context.Context, label string) { } func fetchCodexClientModelsFromRemote(ctx context.Context) ([]byte, string) { - client := &http.Client{Timeout: modelsFetchTimeout} - for _, sourceURL := range codexClientModelsURLs { - reqCtx, cancel := context.WithTimeout(ctx, modelsFetchTimeout) - req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, sourceURL, nil) - if err != nil { - cancel() - log.Debugf("Codex client models fetch request creation failed for %s: %v", sourceURL, err) - continue - } - - resp, err := client.Do(req) - if err != nil { - cancel() - log.Debugf("Codex client models fetch failed from %s: %v", sourceURL, err) - continue - } - if resp.StatusCode != http.StatusOK { - if errClose := resp.Body.Close(); errClose != nil { - log.Debugf("Codex client models response close failed for %s: %v", sourceURL, errClose) - } - cancel() - log.Debugf("Codex client models fetch returned %d from %s", resp.StatusCode, sourceURL) - continue - } - - data, errRead := io.ReadAll(io.LimitReader(resp.Body, maxCodexClientModelsSize+1)) - errClose := resp.Body.Close() - cancel() - if errRead != nil { - log.Debugf("Codex client models fetch read error from %s: %v", sourceURL, errRead) - continue - } - if errClose != nil { - log.Debugf("Codex client models response close failed for %s: %v", sourceURL, errClose) - continue - } - if len(data) > maxCodexClientModelsSize { - log.Warnf("Codex client models fetch from %s exceeded %d bytes", sourceURL, maxCodexClientModelsSize) - continue + for _, source := range codexClientModelsURLs { + data, errRead := readCatalogSource(ctx, source) + if errRead == nil && ValidateCodexClientModelsJSON(data) == nil { + return data, source } - if err := ValidateCodexClientModelsJSON(data); err != nil { - log.Warnf("Codex client models validate failed from %s: %v", sourceURL, err) - continue + if ctx.Err() != nil { + break } - return data, sourceURL } return nil, "" } diff --git a/internal/registry/devin_models_updater.go b/internal/registry/devin_models_updater.go index fd4d1cd78b9..5ed460d6870 100644 --- a/internal/registry/devin_models_updater.go +++ b/internal/registry/devin_models_updater.go @@ -2,10 +2,6 @@ package registry import ( "context" - "io" - "net/http" - "sync" - "time" log "github.com/sirupsen/logrus" ) @@ -17,31 +13,11 @@ var devinModelsURLs = []string{ "https://models.router-for.me/devin_models.json", } -var devinModelsUpdaterOnce sync.Once - // StartDevinModelsUpdater starts a background updater that fetches the // Devin model catalog immediately and refreshes it every 3 hours. // Safe to call multiple times; only one updater runs. func StartDevinModelsUpdater(ctx context.Context) { - devinModelsUpdaterOnce.Do(func() { - go runDevinModelsUpdater(ctx) - }) -} - -func runDevinModelsUpdater(ctx context.Context) { - tryRefreshDevinModels(ctx, "startup Devin model refresh") - - ticker := time.NewTicker(modelsRefreshInterval) - defer ticker.Stop() - log.Infof("periodic Devin model refresh started (interval=%s)", modelsRefreshInterval) - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - tryRefreshDevinModels(ctx, "periodic Devin model refresh") - } - } + devinCatalogUpdater.configure(ctx, "") } func tryRefreshDevinModels(ctx context.Context, label string) { @@ -64,45 +40,14 @@ func tryRefreshDevinModels(ctx context.Context, label string) { } func fetchDevinModelsFromRemote(ctx context.Context) ([]byte, string) { - client := &http.Client{Timeout: modelsFetchTimeout} - for _, sourceURL := range devinModelsURLs { - reqCtx, cancel := context.WithTimeout(ctx, modelsFetchTimeout) - req, errReq := http.NewRequestWithContext(reqCtx, http.MethodGet, sourceURL, nil) - if errReq != nil { - cancel() - log.Warnf("devin models updater: invalid request for %s: %v", sourceURL, errReq) - continue + for _, source := range devinModelsURLs { + data, errRead := readCatalogSource(ctx, source) + if errRead == nil && validateDevinCatalogBytes(data) == nil { + return data, source } - - resp, errDo := client.Do(req) - if errDo != nil { - cancel() - log.Warnf("devin models updater: fetch failed from %s: %v", sourceURL, errDo) - continue + if ctx.Err() != nil { + break } - - if resp.StatusCode != http.StatusOK { - if errClose := resp.Body.Close(); errClose != nil { - log.Warnf("devin models updater: response close failed for %s: %v", sourceURL, errClose) - } - cancel() - log.Warnf("devin models updater: unexpected status %d from %s", resp.StatusCode, sourceURL) - continue - } - - body, errRead := io.ReadAll(io.LimitReader(resp.Body, maxDevinModelsSize)) - errClose := resp.Body.Close() - cancel() - if errRead != nil { - log.Warnf("devin models updater: read failed from %s: %v", sourceURL, errRead) - continue - } - if errClose != nil { - log.Warnf("devin models updater: response close failed for %s: %v", sourceURL, errClose) - continue - } - - return body, sourceURL } return nil, "" } diff --git a/internal/registry/model_updater.go b/internal/registry/model_updater.go index f440070fc86..59a0329b5a6 100644 --- a/internal/registry/model_updater.go +++ b/internal/registry/model_updater.go @@ -5,8 +5,6 @@ import ( _ "embed" "encoding/json" "fmt" - "io" - "net/http" "reflect" "strings" "sync" @@ -15,11 +13,6 @@ import ( log "github.com/sirupsen/logrus" ) -const ( - modelsFetchTimeout = 30 * time.Second - modelsRefreshInterval = ModelsRefreshInterval -) - // ModelsRefreshInterval is the shared cadence for model catalogs and account entitlements. const ModelsRefreshInterval = 3 * time.Hour @@ -38,8 +31,6 @@ type modelStore struct { var modelsCatalogStore = &modelStore{} -var updaterOnce sync.Once - // ModelRefreshCallback is invoked when startup or periodic model refresh detects changes. // changedProviders contains the provider names whose model definitions changed. type ModelRefreshCallback func(changedProviders []string) @@ -79,122 +70,7 @@ func init() { // immediately on startup and then refreshes the model catalog every 3 hours. // Safe to call multiple times; only one updater will run. func StartModelsUpdater(ctx context.Context) { - updaterOnce.Do(func() { - go runModelsUpdater(ctx) - }) -} - -func runModelsUpdater(ctx context.Context) { - tryStartupRefresh(ctx) - periodicRefresh(ctx) -} - -func periodicRefresh(ctx context.Context) { - ticker := time.NewTicker(modelsRefreshInterval) - defer ticker.Stop() - log.Infof("periodic model refresh started (interval=%s)", modelsRefreshInterval) - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - tryPeriodicRefresh(ctx) - } - } -} - -// tryPeriodicRefresh fetches models from remote, compares with the current -// catalog, and notifies the registered callback if any provider changed. -func tryPeriodicRefresh(ctx context.Context) { - tryRefreshModels(ctx, "periodic model refresh") -} - -// tryStartupRefresh fetches models from remote in the background during -// process startup. It uses the same change detection as periodic refresh so -// existing auth registrations can be updated after the callback is registered. -func tryStartupRefresh(ctx context.Context) { - tryRefreshModels(ctx, "startup model refresh") -} - -func tryRefreshModels(ctx context.Context, label string) { - oldData := getModels() - - parsed, url := fetchModelsFromRemote(ctx) - if parsed == nil { - log.Warnf("%s: fetch failed from all URLs, keeping current data", label) - return - } - - if len(parsed.Meta) == 0 && oldData != nil && len(oldData.Meta) > 0 { - parsed.Meta = oldData.Meta - } - - // Detect changes before updating store. - changed := detectChangedProviders(oldData, parsed) - - // Update store with new data regardless. - modelsCatalogStore.mu.Lock() - modelsCatalogStore.data = parsed - modelsCatalogStore.mu.Unlock() - - if len(changed) == 0 { - log.Infof("%s completed from %s, no changes detected", label, url) - return - } - - log.Infof("%s completed from %s, changes detected for providers: %v", label, url, changed) - notifyModelRefresh(changed) -} - -// fetchModelsFromRemote tries all remote URLs and returns the parsed model catalog -// along with the URL it was fetched from. Returns (nil, "") if all fetches fail. -func fetchModelsFromRemote(ctx context.Context) (*staticModelsJSON, string) { - client := &http.Client{Timeout: modelsFetchTimeout} - for _, url := range modelsURLs { - reqCtx, cancel := context.WithTimeout(ctx, modelsFetchTimeout) - req, err := http.NewRequestWithContext(reqCtx, "GET", url, nil) - if err != nil { - cancel() - log.Debugf("models fetch request creation failed for %s: %v", url, err) - continue - } - - resp, err := client.Do(req) - if err != nil { - cancel() - log.Debugf("models fetch failed from %s: %v", url, err) - continue - } - - if resp.StatusCode != 200 { - resp.Body.Close() - cancel() - log.Debugf("models fetch returned %d from %s", resp.StatusCode, url) - continue - } - - data, err := io.ReadAll(resp.Body) - resp.Body.Close() - cancel() - - if err != nil { - log.Debugf("models fetch read error from %s: %v", url, err) - continue - } - - var parsed staticModelsJSON - if err := json.Unmarshal(data, &parsed); err != nil { - log.Warnf("models parse failed from %s: %v", url, err) - continue - } - if err := validateModelsCatalog(&parsed); err != nil { - log.Warnf("models validate failed from %s: %v", url, err) - continue - } - - return &parsed, url - } - return nil, "" + generalCatalogUpdater.configure(ctx, "") } // detectChangedProviders compares two model catalogs and returns provider names diff --git a/sdk/cliproxy/service_catalogs_test.go b/sdk/cliproxy/service_catalogs_test.go new file mode 100644 index 00000000000..2936de75fea --- /dev/null +++ b/sdk/cliproxy/service_catalogs_test.go @@ -0,0 +1,99 @@ +package cliproxy + +import ( + "context" + "os" + "path/filepath" + "testing" + "time" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" +) + +func TestServiceCatalogStartupAndConfigReload(t *testing.T) { + fixture := func(name string) string { + t.Helper() + path, errAbs := filepath.Abs(filepath.Join("..", "..", "internal", "registry", "models", name)) + if errAbs != nil { + t.Fatal(errAbs) + } + return path + } + writeCatalog := func(name string, data []byte) string { + t.Helper() + path := filepath.Join(t.TempDir(), name) + if errWrite := os.WriteFile(path, data, 0600); errWrite != nil { + t.Fatal(errWrite) + } + return path + } + original := registry.GetDevinModelsJSON() + originalPath := writeCatalog("original.json", original) + first := []byte(`{"devin":[{"id":"devin/sdk-startup-regression","display_name":"SDK startup"}]}`) + second := []byte(`{"devin":[{"id":"devin/sdk-reload-regression","display_name":"SDK reload"}]}`) + cfg := &config.Config{Models: config.ModelCatalogs{ + Catalog: fixture("models.json"), + CodexCatalog: fixture("codex_client_models.json"), + DevinCatalog: writeCatalog("first.json", first), + }} + s := &Service{cfg: cfg} + ctx, cancel := context.WithCancel(context.Background()) + notifications := make(chan struct{}, 8) + registry.SetModelRefreshCallback(func(providers []string) { + for _, provider := range providers { + if provider == "devin" { + notifications <- struct{}{} + } + } + }) + awaitCatalog := func(want []byte) { + t.Helper() + deadline := time.NewTimer(5 * time.Second) + defer deadline.Stop() + for { + select { + case <-notifications: + if string(registry.GetDevinModelsJSON()) == string(want) { + return + } + case <-deadline.C: + t.Fatal("service did not publish configured Devin catalog") + } + } + } + defer func() { + cancel() + defer registry.SetModelRefreshCallback(nil) + restoreCtx, restoreCancel := context.WithCancel(context.Background()) + defer restoreCancel() + restoreCfg := *cfg + restoreCfg.Home.Enabled = true + restoreCfg.Models.DevinCatalog = originalPath + restore := &Service{cfg: &restoreCfg} + if string(registry.GetDevinModelsJSON()) != string(original) { + restore.startModelCatalogUpdaters(restoreCtx) + awaitCatalog(original) + } + }() + + // Exercise the startup hook used by Run without starting a listening server. + s.startModelCatalogUpdaters(ctx) + awaitCatalog(first) + updated := *cfg + updated.Models.DevinCatalog = writeCatalog("second.json", second) + if commit := s.commitConfigUpdate(&updated); commit.cfg == nil { + t.Fatal("config update rejected") + } + awaitCatalog(second) + + // The same source must restart under a new service lifetime after cancellation. + cancel() + if errWrite := os.WriteFile(updated.Models.DevinCatalog, first, 0600); errWrite != nil { + t.Fatal(errWrite) + } + restartCtx, restartCancel := context.WithCancel(context.Background()) + defer restartCancel() + s.startModelCatalogUpdaters(restartCtx) + awaitCatalog(first) +} diff --git a/sdk/cliproxy/service_config.go b/sdk/cliproxy/service_config.go index 8e3f9780033..5abac0976a0 100644 --- a/sdk/cliproxy/service_config.go +++ b/sdk/cliproxy/service_config.go @@ -5,6 +5,7 @@ import ( "strings" "time" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" "github.com/router-for-me/CLIProxyAPI/v8/internal/watcher/synthesizer" coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" @@ -92,7 +93,8 @@ func (s *Service) applyConfigUpdateWithAuthSynthesis(ctx context.Context, newCfg } // commitConfigUpdate applies only in-memory configuration state. Runtime work that -// may block on plugins, models, storage, or networking is deliberately deferred. +// may block on plugins, storage, or networking is deliberately deferred. Catalog +// source generations change here so an older commit cannot restart stale readers. func (s *Service) commitConfigUpdate(newCfg *config.Config) configCommit { if s == nil { return configCommit{} @@ -114,11 +116,16 @@ func (s *Service) commitConfigUpdate(newCfg *config.Config) configCommit { return configCommit{} } + if errValidate := newCfg.Models.Validate(); errValidate != nil { + log.WithError(errValidate).Warn("rejected invalid model catalog sources") + return configCommit{} + } s.cfgMu.Lock() s.cfg = newCfg s.cfgMu.Unlock() s.cancelStaleAntigravityProbes("") s.configSequence++ + registry.UpdateModelCatalogSources(newCfg.Models, newCfg.Home.Enabled) return configCommit{cfg: newCfg, sequence: s.configSequence} } diff --git a/sdk/cliproxy/service_lifecycle.go b/sdk/cliproxy/service_lifecycle.go index 6bf6976647d..d2aa6af9462 100644 --- a/sdk/cliproxy/service_lifecycle.go +++ b/sdk/cliproxy/service_lifecycle.go @@ -52,6 +52,8 @@ func (s *Service) Run(ctx context.Context) error { s.homeMu.Unlock() }() + s.startModelCatalogUpdaters(ctx) + usage.StartDefault(ctx) homeEnabled := s.cfg != nil && s.cfg.Home.Enabled if homeEnabled { @@ -386,3 +388,13 @@ func (s *Service) ensureAuthDir() error { } return nil } + +// startModelCatalogUpdaters applies the same catalog policy for SDK and CLI users. +func (s *Service) startModelCatalogUpdaters(ctx context.Context) { + s.cfgMu.RLock() + cfg := s.cfg + s.cfgMu.RUnlock() + if cfg != nil { + registry.StartModelCatalogUpdaters(ctx, cfg.Models, cfg.Home.Enabled) + } +} diff --git a/sdk/config/config.go b/sdk/config/config.go index c321a25c025..47f477d6bec 100644 --- a/sdk/config/config.go +++ b/sdk/config/config.go @@ -10,6 +10,8 @@ type SDKConfig = internalconfig.SDKConfig type Config = internalconfig.Config +type ModelCatalogs = internalconfig.ModelCatalogs + type ClientConfig = internalconfig.ClientConfig type CodexClientConfig = internalconfig.CodexClientConfig type StreamingConfig = internalconfig.StreamingConfig From 8a01bc022bf50a31bb8026f26eaa2fa786c60dd7 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Sun, 4 Oct 2026 15:14:16 +0800 Subject: [PATCH 036/142] feat(auth): introduce mutation locking and persistence delta merging - Add `lockAuthMutation` and `lockAuthMutationContext` with context cancellation support for mutation gates and reload barriers - Introduce `persistLocked` to unlock manager state during storage I/O and prevent blocking runtime operations - Implement `mergeAuthSaveDelta` to merge store save changes while preserving concurrent edits Closes: #6329 --- sdk/cliproxy/auth/conductor.go | 8 + .../auth/conductor_cancellation_test.go | 180 ++++++ sdk/cliproxy/auth/conductor_cooldown.go | 15 +- sdk/cliproxy/auth/conductor_lifecycle.go | 89 ++- .../auth/conductor_load_persistence_test.go | 196 +++++++ sdk/cliproxy/auth/conductor_persistence.go | 113 ++++ sdk/cliproxy/auth/conductor_refresh.go | 4 +- .../auth/conductor_saved_fields_test.go | 521 ++++++++++++++++++ sdk/cliproxy/auth/conductor_selection.go | 5 +- sdk/cliproxy/auth/force_refresh_test.go | 55 +- sdk/cliproxy/auth/store.go | 6 + 11 files changed, 1155 insertions(+), 37 deletions(-) create mode 100644 sdk/cliproxy/auth/conductor_cancellation_test.go create mode 100644 sdk/cliproxy/auth/conductor_load_persistence_test.go create mode 100644 sdk/cliproxy/auth/conductor_persistence.go create mode 100644 sdk/cliproxy/auth/conductor_saved_fields_test.go diff --git a/sdk/cliproxy/auth/conductor.go b/sdk/cliproxy/auth/conductor.go index 050da3295e6..785efcd7064 100644 --- a/sdk/cliproxy/auth/conductor.go +++ b/sdk/cliproxy/auth/conductor.go @@ -2,6 +2,7 @@ package auth import ( "context" + "math" "net/http" "sync" "sync/atomic" @@ -10,6 +11,7 @@ import ( internalconfig "github.com/router-for-me/CLIProxyAPI/v8/internal/config" cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" "github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginapi" + "golang.org/x/sync/semaphore" ) // ProviderExecutor defines the contract required by Manager to execute provider calls. @@ -208,6 +210,11 @@ type Manager struct { refreshLocks sync.Map // persistLocks serializes disk persistence per auth ID and guards against out-of-order writes. persistLocks sync.Map + // authMutationLocks coordinate credential mutations without blocking unrelated readers. + authMutationLocks sync.Map + // authLoadGate allows concurrent credential transactions, but excludes whole-store reloads. + // Mutations acquire one permit; Load acquires all permits before reading the store. + authLoadGate *semaphore.Weighted } // NewManager constructs a manager with optional custom selector and hook. @@ -220,6 +227,7 @@ func NewManager(store Store, selector Selector, hook Hook) *Manager { } manager := &Manager{ store: store, + authLoadGate: semaphore.NewWeighted(math.MaxInt64), executors: make(map[string]ProviderExecutor), selector: selector, hook: hook, diff --git a/sdk/cliproxy/auth/conductor_cancellation_test.go b/sdk/cliproxy/auth/conductor_cancellation_test.go new file mode 100644 index 00000000000..c783f6e3ce0 --- /dev/null +++ b/sdk/cliproxy/auth/conductor_cancellation_test.go @@ -0,0 +1,180 @@ +package auth + +import ( + "context" + "errors" + "math" + "sync/atomic" + "testing" + "testing/synctest" +) + +type cancellationStore struct { + saves atomic.Int32 + lists atomic.Int32 + entered chan struct{} + release chan struct{} +} + +func (s *cancellationStore) Save(_ context.Context, auth *Auth) (string, error) { + s.saves.Add(1) + if auth.Label == "blocked" { + close(s.entered) + <-s.release + } + return "", nil +} +func (s *cancellationStore) List(context.Context) ([]*Auth, error) { + s.lists.Add(1) + return nil, nil +} +func (*cancellationStore) Delete(context.Context, string) error { return nil } + +type cancellationHook struct{ calls atomic.Int32 } + +func (h *cancellationHook) OnAuthRegistered(context.Context, *Auth) { h.calls.Add(1) } +func (h *cancellationHook) OnAuthUpdated(context.Context, *Auth) { h.calls.Add(1) } +func (*cancellationHook) OnResult(context.Context, Result) {} + +func assertCanceledMutation(t *testing.T, done <-chan error) { + t.Helper() + select { + case err := <-done: + if !errors.Is(err, context.Canceled) { + t.Errorf("expected context cancellation, got %v", err) + } + default: + t.Error("canceled operation still waiting for lock") + } +} + +func TestManagerCanceledLoadUnblocksUnrelatedMutation(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + store := &cancellationStore{entered: make(chan struct{}), release: make(chan struct{})} + manager := NewManager(store, nil, nil) + saveDone := make(chan error, 1) + go func() { + _, err := manager.Register(context.Background(), &Auth{ID: "A", Provider: "audit", Label: "blocked", Metadata: map[string]any{"type": "audit"}}) + saveDone <- err + }() + <-store.entered + ctx, cancel := context.WithCancel(context.Background()) + loadDone := make(chan error, 1) + go func() { loadDone <- manager.Load(ctx) }() + synctest.Wait() + bDone := make(chan error, 1) + go func() { + _, err := manager.Register(context.Background(), &Auth{ID: "B", Provider: "audit"}) + bDone <- err + }() + synctest.Wait() + select { + case <-bDone: + t.Error("B overtook queued reload") + default: + } + cancel() + synctest.Wait() + assertCanceledMutation(t, loadDone) + select { + case err := <-bDone: + if err != nil { + t.Error(err) + } + default: + t.Error("canceled reload still blocks unrelated B") + } + if store.lists.Load() != 0 { + t.Error("canceled reload called List") + } + close(store.release) + synctest.Wait() + if err := <-saveDone; err != nil { + t.Error(err) + } + if !manager.authLoadGate.TryAcquire(math.MaxInt64) { + t.Error("reload barrier permit leaked") + } else { + manager.authLoadGate.Release(math.MaxInt64) + } + }) +} + +func TestManagerCanceledMutationWait(t *testing.T) { + for _, operation := range []string{"Register", "Update", "Prepare", "Refresh"} { + for _, waitOn := range []string{"barrier", "gate"} { + t.Run(operation+"/"+waitOn, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + store := &cancellationStore{} + hook := &cancellationHook{} + manager := NewManager(store, nil, hook) + base, err := manager.Register(WithSkipPersist(context.Background()), &Auth{ID: "A", Provider: "audit", Metadata: map[string]any{"type": "audit"}}) + if err != nil { + t.Fatal(err) + } + hook.calls.Store(0) + var release func() + if waitOn == "barrier" { + if errAcquire := manager.authLoadGate.Acquire(context.Background(), math.MaxInt64); errAcquire != nil { + t.Fatal(errAcquire) + } + release = func() { manager.authLoadGate.Release(math.MaxInt64) } + } else { + release = manager.lockAuthMutation(base.ID) + } + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { + var errMutation error + switch operation { + case "Register": + _, errMutation = manager.Register(ctx, base.Clone()) + case "Update": + _, errMutation = manager.Update(ctx, base.Clone()) + case "Prepare": + _, errMutation = manager.UpdatePreparedAuth(ctx, base, base.Clone()) + case "Refresh": + _, errMutation = manager.UpdateRefreshedAuth(ctx, base, base.Clone()) + } + done <- errMutation + }() + synctest.Wait() + cancel() + synctest.Wait() + assertCanceledMutation(t, done) + release() + synctest.Wait() + if store.saves.Load() != 0 || hook.calls.Load() != 0 { + t.Error("canceled mutation invoked Save or hook") + } + if got, _ := manager.GetByID(base.ID); got.Generation != base.Generation || got.RegistrationEpoch != base.RegistrationEpoch { + t.Error("canceled mutation published auth") + } + if !manager.authLoadGate.TryAcquire(math.MaxInt64) { + t.Error("mutation leaked reload barrier permit") + } else { + manager.authLoadGate.Release(math.MaxInt64) + } + value, _ := manager.authMutationLocks.Load(base.ID) + if len(value.(chan struct{})) != 0 { + t.Error("mutation leaked credential gate") + } + }) + }) + } + } +} + +func TestManagerMutationNilContext(t *testing.T) { + manager := NewManager(&cancellationStore{}, nil, nil) + auth, err := manager.Register(nil, &Auth{ID: "A", Provider: "audit", Metadata: map[string]any{"type": "audit"}}) + if err != nil { + t.Fatal(err) + } + if _, errUpdate := manager.Update(nil, auth); errUpdate != nil { + t.Fatal(errUpdate) + } + if errLoad := manager.Load(nil); errLoad != nil { + t.Fatal(errLoad) + } +} diff --git a/sdk/cliproxy/auth/conductor_cooldown.go b/sdk/cliproxy/auth/conductor_cooldown.go index 33f8b5d8d7f..8e6f08461e3 100644 --- a/sdk/cliproxy/auth/conductor_cooldown.go +++ b/sdk/cliproxy/auth/conductor_cooldown.go @@ -475,6 +475,8 @@ func (m *Manager) ResetQuota(ctx context.Context, authID string) (*Auth, []strin registeredModels := modelsForRegisteredAuth(authID) cooldownStateChanged := false + releaseMutation := m.lockAuthMutation(authID) + defer releaseMutation() m.mu.Lock() auth, ok := m.auths[authID] if !ok || auth == nil { @@ -524,8 +526,9 @@ func (m *Manager) ResetQuota(ctx context.Context, authID string) (*Auth, []strin cooldownRecordsAfter := m.cooldownStateRecordsForAuthLocked(auth, now) cooldownStateChanged = !cooldownStateRecordsEqual(cooldownRecordsBefore, cooldownRecordsAfter) } - errPersist := m.persist(ctx, auth) + errPersist := m.persistLocked(ctx, auth) m.mu.Unlock() + releaseMutation() defer func() { if cooldownStateChanged { @@ -766,6 +769,8 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) { cooldownStateChanged := false now := time.Now() + releaseMutation := m.lockAuthMutation(result.AuthID) + defer releaseMutation() m.mu.Lock() if auth, ok := m.auths[result.AuthID]; ok && auth != nil { if modelKey == "" && strings.TrimSpace(result.RouteModel) != "" { @@ -1016,7 +1021,7 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) { } } - _ = m.persist(ctx, auth) + _ = m.persistLocked(ctx, auth) authSnapshot = auth.Clone() if trackCooldownState { cooldownRecordsAfter := m.cooldownStateRecordsForAuthLocked(auth, now) @@ -1024,6 +1029,7 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) { } } m.mu.Unlock() + releaseMutation() if m.scheduler != nil && authSnapshot != nil { var targetModels []string if !result.CredentialScope && modelKey != "" { @@ -1096,6 +1102,8 @@ func (m *Manager) recordAvailabilityNeutralResult(ctx context.Context, result Re } var authSnapshot *Auth + releaseMutation := m.lockAuthMutation(result.AuthID) + defer releaseMutation() m.mu.Lock() if auth, ok := m.auths[result.AuthID]; ok && auth != nil { now := time.Now() @@ -1107,10 +1115,11 @@ func (m *Manager) recordAvailabilityNeutralResult(ctx context.Context, result Re } auth.Generation++ auth.UpdatedAt = now - _ = m.persist(ctx, auth) + _ = m.persistLocked(ctx, auth) authSnapshot = auth.Clone() } m.mu.Unlock() + releaseMutation() m.hook.OnResult(ctx, result) m.publishErrorEvent(result, authSnapshot) diff --git a/sdk/cliproxy/auth/conductor_lifecycle.go b/sdk/cliproxy/auth/conductor_lifecycle.go index 3fa801b2665..597a7d7c3a2 100644 --- a/sdk/cliproxy/auth/conductor_lifecycle.go +++ b/sdk/cliproxy/auth/conductor_lifecycle.go @@ -3,6 +3,7 @@ package auth import ( "context" "fmt" + "math" "strings" "sync" "time" @@ -88,6 +89,11 @@ func (m *Manager) Register(ctx context.Context, auth *Auth) (*Auth, error) { if auth.ID == "" { auth.ID = uuid.NewString() } + releaseMutation, errMutation := m.lockAuthMutationContext(ctx, auth.ID) + if errMutation != nil { + return nil, errMutation + } + defer releaseMutation() now := time.Now() if auth.Generation == 0 { auth.Generation = 1 @@ -114,6 +120,16 @@ func (m *Manager) Register(ctx context.Context, auth *Auth) (*Auth, error) { m.authEpochs[auth.ID]++ auth.RegistrationEpoch = m.authEpochs[auth.ID] auth.Generation = 1 + // Serialize this credential, but release the manager lock during store I/O. + // Persist failures stay non-fatal, but must not be silent: a restart would + // lose the credential that only exists in memory. + if errPersist := m.persistLocked(ctx, auth); errPersist != nil { + log.WithFields(log.Fields{"auth_id": auth.ID, "credential": auth.ID, "provider": auth.Provider}).Warnf("failed to persist registered auth %s (%s): %v", auth.Provider, auth.ID, errPersist) + } + if m.authEpochs[auth.ID] != auth.RegistrationEpoch { + m.mu.Unlock() + return nil, fmt.Errorf("auth %s changed registration during persistence", auth.ID) + } authClone := auth.Clone() m.auths[auth.ID] = authClone m.notifyAuthChangeLocked(auth.ID) @@ -123,6 +139,7 @@ func (m *Manager) Register(ctx context.Context, auth *Auth) (*Auth, error) { schedulerSnapshot = authClone.Clone() } m.mu.Unlock() + releaseMutation() if !shouldDeferAPIKeyModelAliasRebuild(ctx) { m.rebuildAPIKeyModelAliasFromRuntimeConfig() } @@ -131,11 +148,6 @@ func (m *Manager) Register(ctx context.Context, auth *Auth) (*Auth, error) { } m.structuralEpoch.Add(1) m.queueRefreshReschedule(auth.ID) - // Persist failures stay non-fatal, but must not be silent: a restart would - // lose the credential that only exists in memory. - if errPersist := m.persist(ctx, auth); errPersist != nil { - log.WithFields(log.Fields{"auth_id": auth.ID, "credential": auth.ID, "provider": auth.Provider}).Warnf("failed to persist registered auth %s (%s): %v", auth.Provider, auth.ID, errPersist) - } m.hook.OnAuthRegistered(ctx, auth.Clone()) if cooldownStateChanged { m.persistCooldownStates(context.Background()) @@ -176,6 +188,11 @@ func (m *Manager) updateInternal(ctx context.Context, base, auth *Auth, mode upd if errWeight := ValidateAuthWeight(auth); errWeight != nil { return nil, fmt.Errorf("update auth: %w", errWeight) } + releaseMutation, errMutation := m.lockAuthMutationContext(ctx, auth.ID) + if errMutation != nil { + return nil, errMutation + } + defer releaseMutation() m.mu.Lock() existing, ok := m.auths[auth.ID] if !ok || existing == nil { @@ -260,15 +277,26 @@ func (m *Manager) updateInternal(ctx context.Context, base, auth *Auth, mode upd cooldownStateChanged = clearCooldownStateForAuth(auth, now) || cooldownStateChanged } auth.EnsureIndex() - // A minted Meta key must reach the configured store before requests can use it. - // Keep the epoch check, save and installation together so a concurrent reload - // or removal cannot let an obsolete mint overwrite the credential on disk. + // Save before publication, including the transactional Meta mint path. + // Runtime-only changes made during I/O are merged below, never overwritten. + existingBeforeSave := existing.Clone() persistMetaMint := (mode == updateModePrepare || mode == updateModeRefresh) && strings.EqualFold(strings.TrimSpace(auth.Provider), "meta") - if persistMetaMint { - if errPersist := m.persist(ctx, auth); errPersist != nil { + if errPersist := m.persistLocked(ctx, auth); errPersist != nil { + // A minted Meta key must reach the store before requests can use it. + if persistMetaMint { m.mu.Unlock() return nil, fmt.Errorf("persist meta auth: %w", errPersist) } + // Ordinary persistence failures remain non-fatal, but never silent. + log.WithFields(log.Fields{"auth_id": auth.ID, "credential": auth.ID, "provider": auth.Provider}).Warnf("failed to persist updated auth %s (%s): %v", auth.Provider, auth.ID, errPersist) + } + if m.authEpochs[auth.ID] != auth.RegistrationEpoch { + m.mu.Unlock() + return nil, fmt.Errorf("auth %s changed registration during persistence", auth.ID) + } + mergeAuthSaveDelta(auth, existingBeforeSave, existing, false) + if existing.Generation >= auth.Generation { + auth.Generation = existing.Generation + 1 } authClone := auth.Clone() m.auths[auth.ID] = authClone @@ -279,6 +307,7 @@ func (m *Manager) updateInternal(ctx context.Context, base, auth *Auth, mode upd schedulerSnapshot = authClone.Clone() } m.mu.Unlock() + releaseMutation() if !shouldDeferAPIKeyModelAliasRebuild(ctx) { m.rebuildAPIKeyModelAliasFromRuntimeConfig() } @@ -287,13 +316,6 @@ func (m *Manager) updateInternal(ctx context.Context, base, auth *Auth, mode upd } m.structuralEpoch.Add(1) m.queueRefreshReschedule(auth.ID) - if !persistMetaMint { - // Persist failures stay non-fatal, but must not be silent: after a token - // refresh the rotated credentials only exist in memory until persisted. - if errPersist := m.persist(ctx, auth); errPersist != nil { - log.WithFields(log.Fields{"auth_id": auth.ID, "credential": auth.ID, "provider": auth.Provider}).Warnf("failed to persist updated auth %s (%s): %v", auth.Provider, auth.ID, errPersist) - } - } m.hook.OnAuthUpdated(ctx, auth.Clone()) if cooldownStateChanged { m.persistCooldownStates(context.Background()) @@ -312,6 +334,8 @@ func (m *Manager) Remove(ctx context.Context, id string) { return } _ = ctx + releaseMutation := m.lockAuthMutation(id) + defer releaseMutation() m.mu.Lock() existing := m.auths[id] @@ -343,6 +367,7 @@ func (m *Manager) Remove(ctx context.Context, id string) { m.authEpochs[id]++ tombstoneEpoch := m.authEpochs[id] m.mu.Unlock() + releaseMutation() if !shouldDeferAPIKeyModelAliasRebuild(ctx) { m.rebuildAPIKeyModelAliasFromRuntimeConfig() @@ -376,16 +401,27 @@ func (m *Manager) invalidateSessionAffinity(authID string) { // Load resets manager state from the backing store. func (m *Manager) Load(ctx context.Context) error { - m.mu.Lock() - if m.store == nil { - m.mu.Unlock() + // Exclude complete Save/publication transactions, including new registrations + // not yet present in auths. Never wait for this barrier while holding m.mu. + lockCtx := ctx + if lockCtx == nil { + lockCtx = context.Background() + } + if errAcquire := m.authLoadGate.Acquire(lockCtx, math.MaxInt64); errAcquire != nil { + return errAcquire + } + defer m.authLoadGate.Release(math.MaxInt64) + m.mu.RLock() + store := m.store + m.mu.RUnlock() + if store == nil { return nil } - items, err := m.store.List(ctx) + items, err := store.List(ctx) if err != nil { - m.mu.Unlock() return err } + m.mu.Lock() previousAuths := m.auths m.auths = make(map[string]*Auth, len(items)) if m.authEpochs == nil { @@ -448,7 +484,10 @@ type authPersistLock struct { } func (m *Manager) persist(ctx context.Context, auth *Auth) error { - if m.store == nil || auth == nil { + m.mu.RLock() + store := m.store + m.mu.RUnlock() + if store == nil || auth == nil { return nil } if errWeight := ValidateAuthWeight(auth); errWeight != nil { @@ -483,13 +522,13 @@ func (m *Manager) persist(ctx context.Context, auth *Auth) error { if shouldSkipPersist(ctx) { return nil } - _, err := m.store.Save(ctx, auth) + _, err := store.Save(ctx, auth) return err } if shouldSkipPersist(ctx) { return nil } - _, err := m.store.Save(ctx, auth) + _, err := store.Save(ctx, auth) return err } diff --git a/sdk/cliproxy/auth/conductor_load_persistence_test.go b/sdk/cliproxy/auth/conductor_load_persistence_test.go new file mode 100644 index 00000000000..6507b550b07 --- /dev/null +++ b/sdk/cliproxy/auth/conductor_load_persistence_test.go @@ -0,0 +1,196 @@ +package auth + +import ( + "context" + "errors" + "reflect" + "sync" + "testing" + "testing/synctest" + + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" +) + +// reloadAuthStore snapshots records independently of blocked storage I/O. +type reloadAuthStore struct { + mu sync.Mutex + records map[string]*Auth + saveEntered chan struct{} + saveRelease chan struct{} + listEntered chan struct{} + listRelease chan struct{} +} + +func (*reloadAuthStore) Delete(context.Context, string) error { return nil } +func (s *reloadAuthStore) Save(_ context.Context, auth *Auth) (string, error) { + if s.saveEntered != nil { + close(s.saveEntered) + <-s.saveRelease + } + auth.FileName = auth.ID + ".json" + s.mu.Lock() + s.records[auth.ID] = auth.Clone() + s.mu.Unlock() + return auth.FileName, nil +} +func (s *reloadAuthStore) List(context.Context) ([]*Auth, error) { + s.mu.Lock() + items := make([]*Auth, 0, len(s.records)) + for _, auth := range s.records { + items = append(items, auth.Clone()) + } + s.mu.Unlock() + close(s.listEntered) + if s.listRelease != nil { + <-s.listRelease + } + return items, nil +} + +func assertUnrelatedAuthReadable(t *testing.T, manager *Manager) { + t.Helper() + done := make(chan error, 1) + go func() { + if _, ok := manager.GetByID("B"); !ok { + done <- errors.New("B disappeared") + return + } + selected, err := manager.SelectAuth(context.Background(), "audit-b", "", cliproxyexecutor.Options{}) + if err == nil && (selected == nil || selected.ID != "B") { + err = errors.New("did not select B") + } + done <- err + }() + synctest.Wait() + select { + case err := <-done: + if err != nil { + t.Error(err) + } + default: + t.Error("storage I/O blocked reading/selecting unrelated B") + } +} + +func TestManagerBlockedSaveSerializesLoad(t *testing.T) { + for _, operation := range []string{"Register", "ReRegister", "Update", "Prepare", "Refresh", "MarkResult"} { + t.Run(operation, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx := context.Background() + store := &reloadAuthStore{records: make(map[string]*Auth), saveEntered: make(chan struct{}), saveRelease: make(chan struct{}), listEntered: make(chan struct{})} + manager := NewManager(store, nil, nil) + manager.RegisterExecutor(&aliasRoutingExecutor{id: "audit-b"}) + b, err := manager.Register(WithSkipPersist(ctx), &Auth{ID: "B", Provider: "audit-b", Status: StatusActive}) + if err != nil { + t.Fatal(err) + } + store.records[b.ID] = b.Clone() + base := &Auth{ID: "A", Provider: "meta", Status: StatusActive, Metadata: map[string]any{"access_token": "old"}} + if operation != "Register" { + base, err = manager.Register(WithSkipPersist(ctx), base) + if err != nil { + t.Fatal(err) + } + store.records[base.ID] = base.Clone() + } + updated := base.Clone() + updated.Metadata["access_token"] = "minted" + saveDone := make(chan error, 1) + go func() { + var errSave error + switch operation { + case "Register", "ReRegister": + _, errSave = manager.Register(ctx, updated) + case "Update": + _, errSave = manager.Update(ctx, updated) + case "Prepare": + _, errSave = manager.UpdatePreparedAuth(ctx, base, updated) + case "Refresh": + _, errSave = manager.UpdateRefreshedAuth(ctx, base, updated) + case "MarkResult": + manager.MarkResult(ctx, Result{AuthID: base.ID, Provider: base.Provider, Success: true}) + } + saveDone <- errSave + }() + <-store.saveEntered + loadDone := make(chan error, 1) + go func() { loadDone <- manager.Load(ctx) }() + synctest.Wait() + select { + case <-store.listEntered: + t.Error("Load read stale records before Save/publication completed") + default: + } + assertUnrelatedAuthReadable(t, manager) + close(store.saveRelease) + if errSave := <-saveDone; errSave != nil { + t.Errorf("save/publication failed: %v", errSave) + } + if errLoad := <-loadDone; errLoad != nil { + t.Fatal(errLoad) + } + got, ok := manager.GetByID(base.ID) + if !ok { + t.Fatal("Load lost the saved credential") + } + store.mu.Lock() + saved := store.records[base.ID].Clone() + store.mu.Unlock() + if got.RegistrationEpoch <= saved.RegistrationEpoch { + t.Error("Load did not run after save/publication") + } + saved.RegistrationEpoch, saved.Generation = got.RegistrationEpoch, got.Generation + if !reflect.DeepEqual(saved, got) { + t.Errorf("store and manager diverged: saved=%+v got=%+v", saved, got) + } + manager.scheduler.mu.Lock() + scheduled := manager.scheduler.providers["meta"].auths[base.ID].auth.Clone() + manager.scheduler.mu.Unlock() + if !reflect.DeepEqual(got, scheduled) { + t.Error("scheduler differs from reloaded credential") + } + }) + }) + } +} + +func TestManagerBlockedLoadSerializesNewRegistration(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx := context.Background() + store := &reloadAuthStore{records: make(map[string]*Auth), saveEntered: make(chan struct{}), saveRelease: make(chan struct{}), listEntered: make(chan struct{}), listRelease: make(chan struct{})} + manager := NewManager(store, nil, nil) + manager.RegisterExecutor(&aliasRoutingExecutor{id: "audit-b"}) + b, err := manager.Register(WithSkipPersist(ctx), &Auth{ID: "B", Provider: "audit-b", Status: StatusActive}) + if err != nil { + t.Fatal(err) + } + store.records[b.ID] = b.Clone() + loadDone := make(chan error, 1) + go func() { loadDone <- manager.Load(ctx) }() + <-store.listEntered + saveDone := make(chan error, 1) + go func() { + _, errRegister := manager.Register(ctx, &Auth{ID: "new", Provider: "audit", Metadata: map[string]any{"type": "audit"}}) + saveDone <- errRegister + }() + synctest.Wait() + select { + case <-store.saveEntered: + t.Error("new registration overtook Load's whole-map replacement") + default: + } + assertUnrelatedAuthReadable(t, manager) + close(store.listRelease) + if errLoad := <-loadDone; errLoad != nil { + t.Fatal(errLoad) + } + <-store.saveEntered + close(store.saveRelease) + if errSave := <-saveDone; errSave != nil { + t.Fatal(errSave) + } + if got, ok := manager.GetByID("new"); !ok || got.FileName != "new.json" { + t.Fatal("Load discarded a new registration") + } + }) +} diff --git a/sdk/cliproxy/auth/conductor_persistence.go b/sdk/cliproxy/auth/conductor_persistence.go new file mode 100644 index 00000000000..72739c0540a --- /dev/null +++ b/sdk/cliproxy/auth/conductor_persistence.go @@ -0,0 +1,113 @@ +package auth + +import ( + "context" + "reflect" + "sync" +) + +// lockAuthMutation acquires the reload barrier, then the credential gate, before +// m.mu. Keep both until publication completes. Load never takes credential or +// refresh locks. Store callbacks may read the manager, but must not mutate it. +func (m *Manager) lockAuthMutation(id string) func() { + release, _ := m.lockAuthMutationContext(context.Background(), id) + return release +} + +// lockAuthMutationContext lets fallible mutations cancel either lock wait. +func (m *Manager) lockAuthMutationContext(ctx context.Context, id string) (func(), error) { + if ctx == nil { + ctx = context.Background() + } + if errAcquire := m.authLoadGate.Acquire(ctx, 1); errAcquire != nil { + return nil, errAcquire + } + value, _ := m.authMutationLocks.LoadOrStore(id, make(chan struct{}, 1)) + gate := value.(chan struct{}) + select { + case gate <- struct{}{}: + // Cancellation may race with the gate becoming available. + if errContext := ctx.Err(); errContext != nil { + <-gate + m.authLoadGate.Release(1) + return nil, errContext + } + case <-ctx.Done(): + m.authLoadGate.Release(1) + return nil, ctx.Err() + } + var once sync.Once + return func() { + once.Do(func() { + <-gate + m.authLoadGate.Release(1) + }) + }, nil +} + +// persistLocked requires m.mu and the credential mutation gate. Never pass a +// published object to Store.Save: readers and runtime-only writers remain live +// during I/O. Only the store's delta is merged back, preserving intervening edits. +func (m *Manager) persistLocked(ctx context.Context, auth *Auth) error { + before := auth.Clone() + saved := auth.Clone() + m.mu.Unlock() + err := m.persist(ctx, saved) + m.mu.Lock() + mergeAuthSaveDelta(auth, before, saved, true) + return err +} + +// mergeAuthSaveDelta handles all exported value fields, not a store-specific +// allowlist. Map entries are independent fields; nested values are atomic. +// Identity/version fields belong exclusively to the manager. Store-owned shared +// objects must be replaced rather than mutated in place (see Store.Save). +func mergeAuthSaveDelta(target, before, after *Auth, preserveConcurrent bool) { + dst := reflect.ValueOf(target).Elem() + base := reflect.ValueOf(before).Elem() + next := reflect.ValueOf(after).Elem() + for i := 0; i < dst.NumField(); i++ { + field := dst.Type().Field(i) + if field.PkgPath != "" || field.Name == "ID" || field.Name == "RegistrationEpoch" || field.Name == "Generation" { + continue + } + d, b, n := dst.Field(i), base.Field(i), next.Field(i) + if reflect.DeepEqual(b.Interface(), n.Interface()) { + continue + } + if reflect.DeepEqual(d.Interface(), b.Interface()) { + d.Set(n) + continue + } + if d.Kind() == reflect.Map { + keys := make(map[any]reflect.Value) + for _, key := range b.MapKeys() { + keys[key.Interface()] = key + } + for _, key := range n.MapKeys() { + keys[key.Interface()] = key + } + for _, key := range keys { + oldValue, newValue := b.MapIndex(key), n.MapIndex(key) + if equalSaveValue(oldValue, newValue) || (preserveConcurrent && !equalSaveValue(d.MapIndex(key), oldValue)) { + continue + } + if d.IsNil() { + d.Set(reflect.MakeMap(d.Type())) + } + d.SetMapIndex(key, newValue) + } + continue + } + if !preserveConcurrent { + d.Set(n) + } + } +} + +func equalSaveValue(a, b reflect.Value) bool { + if !a.IsValid() || !b.IsValid() { + return a.IsValid() == b.IsValid() + } + return reflect.DeepEqual(a.Interface(), b.Interface()) +} diff --git a/sdk/cliproxy/auth/conductor_refresh.go b/sdk/cliproxy/auth/conductor_refresh.go index a92e6b5c2a5..285f83e431c 100644 --- a/sdk/cliproxy/auth/conductor_refresh.go +++ b/sdk/cliproxy/auth/conductor_refresh.go @@ -786,7 +786,9 @@ func (m *Manager) refreshAuthForRequestAtEpoch(ctx context.Context, id, failedAc if m.shouldRefresh(updated, now) { updated.NextRefreshAfter = now.Add(refreshIneffectiveBackoff) } - saved, errUpdate := m.UpdateRefreshedAuth(ctx, base, updated) + // A successful refresh may have rotated upstream tokens after cancellation. + // Commit its result with context values intact; keep epoch checks and save ordering. + saved, errUpdate := m.UpdateRefreshedAuth(context.WithoutCancel(ctx), base, updated) if errUpdate != nil { // Warn, not debug: a restart after a lost persist fails with invalid_grant. log.WithFields(log.Fields{"auth_id": auth.ID, "credential": auth.ID, "provider": auth.Provider}).Warnf("persist refreshed auth %s (%s) failed: %v", auth.Provider, auth.ID, errUpdate) diff --git a/sdk/cliproxy/auth/conductor_saved_fields_test.go b/sdk/cliproxy/auth/conductor_saved_fields_test.go new file mode 100644 index 00000000000..ec88b3325a5 --- /dev/null +++ b/sdk/cliproxy/auth/conductor_saved_fields_test.go @@ -0,0 +1,521 @@ +package auth + +import ( + "context" + "errors" + "reflect" + "sync" + "testing" + "testing/synctest" + "time" + + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" +) + +type enrichingAuthStore struct{ err error } + +func (*enrichingAuthStore) List(context.Context) ([]*Auth, error) { return nil, nil } +func (*enrichingAuthStore) Delete(context.Context, string) error { return nil } +func (s *enrichingAuthStore) Save(_ context.Context, auth *Auth) (string, error) { + if auth.Attributes == nil { + auth.Attributes = make(map[string]string) + } + auth.Attributes[AttributePath] = "/fixture/" + auth.ID + ".json" + auth.Attributes[AttributeSource] = auth.Attributes[AttributePath] + auth.Attributes[AttributeSourceBackend] = AuthSourceFile + auth.FileName = auth.ID + ".json" + auth.Metadata["disabled"] = auth.Disabled + return auth.Attributes[AttributePath], s.err +} + +type savedFieldsHook struct{ auth *Auth } + +func (h *savedFieldsHook) OnAuthRegistered(_ context.Context, auth *Auth) { h.auth = auth.Clone() } +func (h *savedFieldsHook) OnAuthUpdated(_ context.Context, auth *Auth) { h.auth = auth.Clone() } +func (*savedFieldsHook) OnResult(context.Context, Result) {} + +func TestManagerSavedFieldsPublished(t *testing.T) { + for _, saveErr := range []error{nil, errors.New("save failed after enrichment")} { + name := "success" + if saveErr != nil { + name = "failure" + } + t.Run(name, func(t *testing.T) { + testManagerSavedFieldsPublished(t, saveErr) + }) + } +} + +func testManagerSavedFieldsPublished(t *testing.T, saveErr error) { + for _, operation := range []string{"Register", "Update", "Prepare", "Refresh"} { + t.Run(operation, func(t *testing.T) { + ctx := context.Background() + hook := &savedFieldsHook{} + manager := NewManager(&enrichingAuthStore{err: saveErr}, nil, hook) + input := &Auth{ID: "saved-fields", Provider: "audit", Status: StatusActive, Metadata: map[string]any{"type": "audit"}} + var returned *Auth + var err error + if operation == "Register" { + returned, err = manager.Register(ctx, input) + } else { + base, errRegister := manager.Register(ctx, input) + if errRegister != nil { + t.Fatal(errRegister) + } + input = base.Clone() + input.FileName = "" + input.Attributes = nil + delete(input.Metadata, "disabled") + switch operation { + case "Update": + returned, err = manager.Update(ctx, input) + case "Prepare": + returned, err = manager.UpdatePreparedAuth(ctx, base, input) + case "Refresh": + returned, err = manager.UpdateRefreshedAuth(ctx, base, input) + } + } + if err != nil { + t.Fatal(err) + } + published, ok := manager.GetByID(input.ID) + if !ok { + t.Fatal("missing published auth") + } + for name, snapshot := range map[string]*Auth{"manager": published, "return": returned, "hook": hook.auth} { + if snapshot == nil || snapshot.FileName != "saved-fields.json" || snapshot.Attributes[AttributePath] != "/fixture/saved-fields.json" || snapshot.Attributes[AttributeSource] != "/fixture/saved-fields.json" || snapshot.Attributes[AttributeSourceBackend] != AuthSourceFile || snapshot.Metadata["disabled"] != false { + t.Errorf("%s snapshot missing Store.Save enrichment: %+v", name, snapshot) + } + if !reflect.DeepEqual(snapshot, published) { + t.Errorf("%s snapshot differs from manager", name) + } + } + manager.scheduler.mu.Lock() + scheduled := manager.scheduler.providers["audit"].auths[input.ID].auth.Clone() + manager.scheduler.mu.Unlock() + if !reflect.DeepEqual(scheduled, published) { + t.Error("scheduler snapshot differs from manager") + } + }) + } +} + +// blockingEnrichingAuthStore pauses one save before enriching the auth. +type blockingEnrichingAuthStore struct { + enrichingAuthStore + entered chan struct{} + release chan struct{} + once sync.Once + mu sync.Mutex + saved []*Auth +} + +func (s *blockingEnrichingAuthStore) Save(ctx context.Context, auth *Auth) (string, error) { + s.once.Do(func() { + close(s.entered) + <-s.release + }) + path, err := s.enrichingAuthStore.Save(ctx, auth) + s.mu.Lock() + s.saved = append(s.saved, auth.Clone()) + s.mu.Unlock() + return path, err +} + +func TestManagerSavedFieldsConcurrentLifecycle(t *testing.T) { + for _, saveErr := range []error{nil, errors.New("save failed after enrichment")} { + name := "success" + if saveErr != nil { + name = "failure" + } + t.Run(name, func(t *testing.T) { testManagerSavedFieldsConcurrentLifecycle(t, saveErr) }) + } +} + +func testManagerSavedFieldsConcurrentLifecycle(t *testing.T, saveErr error) { + for _, operation := range []string{"Register", "Update"} { + for _, concurrent := range []string{"MarkResult", "Update", "Remove", "ReRegister"} { + t.Run(operation+"/"+concurrent, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx := context.Background() + store := &blockingEnrichingAuthStore{enrichingAuthStore: enrichingAuthStore{err: saveErr}, entered: make(chan struct{}), release: make(chan struct{})} + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(store.release) }) } + defer release() + manager := NewManager(store, nil, nil) + input := &Auth{ID: "saved-fields", Provider: "audit", Status: StatusActive, Label: "old", Metadata: map[string]any{"type": "audit"}} + if operation == "Update" { + var errRegister error + input, errRegister = manager.Register(WithSkipPersist(ctx), input) + if errRegister != nil { + t.Fatal(errRegister) + } + } + next := input.Clone() + next.Label = "new" + done := make(chan error, 1) + go func() { + var err error + if operation == "Register" { + _, err = manager.Register(ctx, input) + } else { + _, err = manager.Update(ctx, input) + } + done <- err + }() + <-store.entered + started := make(chan struct{}) + concurrentDone := make(chan error, 1) + go func() { + close(started) + var err error + switch concurrent { + case "MarkResult": + manager.MarkResult(ctx, Result{AuthID: next.ID, Provider: next.Provider, Model: "model", Error: &Error{HTTPStatus: 429, Message: "quota exceeded"}}) + case "Update": + _, err = manager.Update(ctx, next) + case "Remove": + manager.Remove(ctx, next.ID) + case "ReRegister": + manager.Remove(ctx, next.ID) + _, err = manager.Register(ctx, next) + } + concurrentDone <- err + }() + <-started + synctest.Wait() + select { + case <-concurrentDone: + t.Fatal("same-credential mutation completed before the active save") + default: + } + release() + if errDone := <-done; errDone != nil { + t.Fatal(errDone) + } + if errConcurrent := <-concurrentDone; errConcurrent != nil { + t.Fatal(errConcurrent) + } + published, ok := manager.GetByID(input.ID) + manager.scheduler.mu.Lock() + var scheduled *Auth + if provider := manager.scheduler.providers["audit"]; provider != nil { + if meta := provider.auths[input.ID]; meta != nil { + scheduled = meta.auth.Clone() + } + } + manager.scheduler.mu.Unlock() + if concurrent == "Remove" { + if ok || scheduled != nil { + t.Fatal("completed save resurrected removed auth") + } + return + } + if !ok || published.FileName != "saved-fields.json" || published.Attributes[AttributePath] != "/fixture/saved-fields.json" { + t.Fatalf("missing saved fields: %+v", published) + } + if concurrent == "MarkResult" { + state := published.ModelStates["model"] + if published.Failed != 1 || published.LastError == nil || state == nil || !state.Quota.Exceeded || !state.Unavailable { + t.Fatalf("save overwrote concurrent result: %+v", published) + } + } else if published.Label != "new" { + t.Fatalf("save overwrote newer lifecycle state: %+v", published) + } + if !reflect.DeepEqual(scheduled, published) { + t.Fatal("scheduler retained an obsolete save snapshot") + } + store.mu.Lock() + saved := store.saved[len(store.saved)-1].Clone() + store.mu.Unlock() + if !reflect.DeepEqual(saved, published) { + t.Fatal("store retained an obsolete auth version") + } + if concurrent == "ReRegister" { + if published.RegistrationEpoch <= input.RegistrationEpoch { + t.Fatal("re-registration did not advance epoch") + } + if _, errUpdate := manager.UpdateRefreshedAuth(ctx, input, input.Clone()); errUpdate == nil { + t.Fatal("accepted stale registration after re-register") + } + } + }) + }) + } + } +} + +func TestManagerBlockedSaveAllowsUnrelatedCredential(t *testing.T) { + for _, operation := range []string{"Register", "Update"} { + t.Run(operation, func(t *testing.T) { + ctx := context.Background() + store := &blockingEnrichingAuthStore{entered: make(chan struct{}), release: make(chan struct{})} + manager := NewManager(store, nil, nil) + manager.RegisterExecutor(&aliasRoutingExecutor{id: "audit"}) + if _, err := manager.Register(WithSkipPersist(ctx), &Auth{ID: "B", Provider: "audit", Status: StatusActive}); err != nil { + t.Fatal(err) + } + input := &Auth{ID: "A", Provider: "audit-a", Status: StatusActive, Metadata: map[string]any{"type": "audit-a"}} + if operation == "Update" { + if _, err := manager.Register(WithSkipPersist(ctx), input); err != nil { + t.Fatal(err) + } + } + done := make(chan struct{}) + go func() { + defer close(done) + if operation == "Register" { + _, _ = manager.Register(ctx, input) + } else { + _, _ = manager.Update(ctx, input) + } + }() + <-store.entered + readDone := make(chan error, 1) + go func() { + if _, ok := manager.GetByID("B"); !ok { + readDone <- errors.New("missing B") + return + } + selected, err := manager.SelectAuth(ctx, "audit", "", cliproxyexecutor.Options{}) + if err == nil && (selected == nil || selected.ID != "B") { + err = errors.New("did not select B") + } + readDone <- err + }() + select { + case err := <-readDone: + if err != nil { + t.Error(err) + } + case <-time.After(2 * time.Second): + t.Error("blocked Save(A) prevented reading/selecting unrelated B") + } + close(store.release) + <-done + }) + } +} + +type callbackAuthStore struct{ save func(*Auth) error } + +func (*callbackAuthStore) List(context.Context) ([]*Auth, error) { return nil, nil } +func (*callbackAuthStore) Delete(context.Context, string) error { return nil } +func (s *callbackAuthStore) Save(_ context.Context, auth *Auth) (string, error) { + return "", s.save(auth) +} + +func TestManagerSaveReadCallbackAndCustomFields(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx := context.Background() + store := &callbackAuthStore{} + manager := NewManager(store, nil, nil) + store.save = func(auth *Auth) error { + manager.GetByID(auth.ID) + manager.List() + auth.Prefix = "custom-prefix" + auth.ProxyURL = "http://custom.invalid" + auth.Metadata["custom"] = map[string]any{"value": "saved"} + delete(auth.Metadata, "remove") + return nil + } + for _, operation := range []string{"Register", "Update"} { + input := &Auth{ID: "callback", Provider: "audit", Status: StatusActive, Metadata: map[string]any{"remove": true}} + var result *Auth + var err error + if operation == "Register" { + result, err = manager.Register(ctx, input) + } else { + result, err = manager.Update(ctx, input) + } + if err != nil { + t.Fatal(err) + } + got, _ := manager.GetByID(input.ID) + if got.Prefix != "custom-prefix" || got.ProxyURL != "http://custom.invalid" || got.Metadata["custom"] == nil { + t.Fatalf("custom store fields missing: %+v", got) + } + if _, ok := got.Metadata["remove"]; ok { + t.Fatal("store deletion lost") + } + if !reflect.DeepEqual(result, got) { + t.Fatal("return differs from manager") + } + } + }) +} + +func TestManagerSavePreservesConcurrentRefreshState(t *testing.T) { + for _, operation := range []string{"Update", "MarkResult"} { + t.Run(operation, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx := context.Background() + store := &blockingEnrichingAuthStore{entered: make(chan struct{}), release: make(chan struct{})} + manager := NewManager(store, nil, nil) + base, err := manager.Register(WithSkipPersist(ctx), &Auth{ID: "runtime", Provider: "audit", Status: StatusActive, Metadata: map[string]any{"type": "audit"}}) + if err != nil { + t.Fatal(err) + } + done := make(chan struct{}) + go func() { + defer close(done) + if operation == "Update" { + _, _ = manager.Update(ctx, base.Clone()) + } else { + manager.MarkResult(ctx, Result{AuthID: base.ID, Provider: base.Provider, Success: true}) + } + }() + <-store.entered + job := manager.markRefreshPending(nil, base.ID, base.RegistrationEpoch, time.Now()) + if job == nil { + t.Fatal("failed to schedule concurrent refresh") + } + close(store.release) + <-done + got, _ := manager.GetByID(base.ID) + if !got.NextRefreshAfter.Equal(job.pendingUntil) { + t.Fatal("save lost concurrent refresh scheduling") + } + if got.Attributes[AttributePath] == "" { + t.Fatal("save enrichment lost") + } + if operation == "MarkResult" && got.Success != 1 { + t.Fatal("save lost result counter") + } + }) + }) + } +} + +func TestManagerSavedFieldsSkipPersistence(t *testing.T) { + ctx := context.Background() + store := &callbackAuthStore{save: func(*Auth) error { t.Fatal("unexpected Save"); return nil }} + for _, mode := range []string{"context", "nil-metadata", "runtime-only", "config-api-key", "plugin-virtual"} { + t.Run(mode, func(t *testing.T) { + manager := NewManager(store, nil, nil) + input := &Auth{ID: mode, Provider: "audit", Status: StatusActive, Metadata: map[string]any{"type": "audit"}} + saveCtx := ctx + switch mode { + case "context": + saveCtx = WithSkipPersist(ctx) + case "nil-metadata": + input.Metadata = nil + case "runtime-only": + input.Attributes = map[string]string{"runtime_only": "true"} + case "config-api-key": + input.Attributes = map[string]string{"source": "config", "api_key": "test"} + case "plugin-virtual": + MarkPluginVirtualAuth(input, "fixture", 0) + } + for _, operation := range []string{"Register", "Update"} { + var result *Auth + var err error + if operation == "Register" { + result, err = manager.Register(saveCtx, input) + } else { + result, err = manager.Update(saveCtx, input) + } + if err != nil { + t.Fatal(err) + } + got, _ := manager.GetByID(input.ID) + if !reflect.DeepEqual(got, result) { + t.Fatal("skip return differs from manager") + } + } + }) + } +} + +func TestMergeAuthSaveDeltaMapChanges(t *testing.T) { + t.Run("empty-map", func(t *testing.T) { + before := &Auth{} + after := &Auth{Attributes: map[string]string{}, Metadata: map[string]any{}} + target := before.Clone() + mergeAuthSaveDelta(target, before, after, true) + if !reflect.DeepEqual(target, after) { + t.Fatal("lost explicit empty map enrichment") + } + }) + t.Run("delete-map-preserves-concurrent-key", func(t *testing.T) { + before := &Auth{Metadata: map[string]any{"old": true}} + after := before.Clone() + after.Metadata = nil + target := before.Clone() + target.Metadata["concurrent"] = true + mergeAuthSaveDelta(target, before, after, true) + if len(target.Metadata) != 1 || target.Metadata["concurrent"] != true { + t.Fatalf("map deletion lost: %v", target.Metadata) + } + }) + t.Run("conflicts", func(t *testing.T) { + before := &Auth{Label: "old", Metadata: map[string]any{"same": "old", "other": "old"}} + after := before.Clone() + after.Label = "store" + after.Metadata["same"] = "store" + after.Metadata["other"] = "store" + target := before.Clone() + target.Label = "runtime" + target.Metadata["same"] = "runtime" + mergeAuthSaveDelta(target, before, after, true) + if target.Label != "runtime" || target.Metadata["same"] != "runtime" || target.Metadata["other"] != "store" { + t.Fatalf("incorrect merge: %+v", target) + } + }) +} + +func TestManagerSavedFieldsMetaMintPublication(t *testing.T) { + for _, operation := range []string{"Prepare", "Refresh"} { + for _, fail := range []bool{false, true} { + name := operation + "/success" + if fail { + name = operation + "/failure" + } + t.Run(name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx := context.Background() + store := &blockingEnrichingAuthStore{entered: make(chan struct{}), release: make(chan struct{})} + if fail { + store.err = errors.New("mint save failed") + } + hook := &savedFieldsHook{} + manager := NewManager(store, nil, hook) + base, err := manager.Register(WithSkipPersist(ctx), &Auth{ID: "meta-mint", Provider: "meta", Status: StatusActive, Metadata: map[string]any{"access_token": "old"}}) + if err != nil { + t.Fatal(err) + } + updated := base.Clone() + updated.Metadata["access_token"] = "minted" + done := make(chan struct{}) + var returned *Auth + var errUpdate error + go func() { + defer close(done) + if operation == "Prepare" { + returned, errUpdate = manager.UpdatePreparedAuth(ctx, base, updated) + } else { + returned, errUpdate = manager.UpdateRefreshedAuth(ctx, base, updated) + } + }() + <-store.entered + pending, _ := manager.GetByID(base.ID) + if !reflect.DeepEqual(base, pending) { + t.Fatal("mint published before persistence completed") + } + close(store.release) + <-done + got, _ := manager.GetByID(base.ID) + if fail { + if errUpdate == nil || returned != nil || !reflect.DeepEqual(base, got) || !reflect.DeepEqual(base, hook.auth) { + t.Fatal("failed Meta mint changed published state") + } + } else { + if errUpdate != nil || got.Metadata["access_token"] != "minted" || got.FileName == "" || !reflect.DeepEqual(got, returned) || !reflect.DeepEqual(got, hook.auth) { + t.Fatalf("successful mint snapshots differ: %v", errUpdate) + } + } + }) + }) + } + } +} diff --git a/sdk/cliproxy/auth/conductor_selection.go b/sdk/cliproxy/auth/conductor_selection.go index 4464cac366c..755e81c004f 100644 --- a/sdk/cliproxy/auth/conductor_selection.go +++ b/sdk/cliproxy/auth/conductor_selection.go @@ -213,6 +213,8 @@ func (m *Manager) ReconcileRegistryModelStates(ctx context.Context, authID strin cooldownStateChanged bool ) + releaseMutation := m.lockAuthMutation(authID) + defer releaseMutation() m.mu.Lock() auth, ok := m.auths[authID] if ok && auth != nil { @@ -347,7 +349,7 @@ func (m *Manager) ReconcileRegistryModelStates(ctx context.Context, authID strin } auth.Generation++ auth.UpdatedAt = now - if errPersist := m.persist(context.Background(), auth); errPersist != nil { + if errPersist := m.persistLocked(context.Background(), auth); errPersist != nil { logEntryWithRequestID(ctx).WithField("auth_id", auth.ID).Warnf("failed to persist auth changes during model state reconciliation: %v", errPersist) } } @@ -361,6 +363,7 @@ func (m *Manager) ReconcileRegistryModelStates(ctx context.Context, authID strin } } m.mu.Unlock() + releaseMutation() if snapshot == nil { return diff --git a/sdk/cliproxy/auth/force_refresh_test.go b/sdk/cliproxy/auth/force_refresh_test.go index e970787a646..6b170717f22 100644 --- a/sdk/cliproxy/auth/force_refresh_test.go +++ b/sdk/cliproxy/auth/force_refresh_test.go @@ -175,7 +175,8 @@ func (e *concurrencyTrackingRefreshExecutor) Refresh(_ context.Context, auth *Au if auth.Metadata == nil { auth.Metadata = make(map[string]any) } - auth.Metadata["access_token"] = "refreshed-token" + auth.Metadata["access_token"] = "rotated-access-" + auth.ID + auth.Metadata["refresh_token"] = "rotated-refresh-" + auth.ID return auth, nil } @@ -269,10 +270,34 @@ func TestManager_ForceRefreshAll_CanceledContextSkipsExecutors(t *testing.T) { } } -func TestManager_ForceRefreshAll_DynamicCancellationSkipsRemaining(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) +// refreshCommitStore observes the commit context without writing credential files. +type refreshCommitStore struct { + *memoryAuthTestStore + checkContext func(context.Context) +} - manager := NewManager(nil, &RoundRobinSelector{}, nil) +func (s *refreshCommitStore) Save(ctx context.Context, auth *Auth) (string, error) { + s.checkContext(ctx) + return s.memoryAuthTestStore.Save(ctx, auth) +} + +func TestManager_ForceRefreshAll_DynamicCancellationSkipsRemaining(t *testing.T) { + type contextKey struct{} + ctx, cancel := context.WithCancel(context.WithValue(context.Background(), contextKey{}, "refresh-value")) + defer cancel() + + store := &refreshCommitStore{ + memoryAuthTestStore: newMemoryAuthTestStore(), + checkContext: func(ctx context.Context) { + if ctx.Err() != nil || ctx.Done() != nil { + t.Error("successful refresh commit must not inherit cancellation") + } + if ctx.Value(contextKey{}) != "refresh-value" { + t.Error("refresh commit lost context value") + } + }, + } + manager := NewManager(store, &RoundRobinSelector{}, nil) manager.runtimeConfig.Store(&internalconfig.Config{AuthAutoRefreshWorkers: 2}) executor := &concurrencyTrackingRefreshExecutor{ @@ -286,9 +311,9 @@ func TestManager_ForceRefreshAll_DynamicCancellationSkipsRemaining(t *testing.T) auth := &Auth{ ID: fmt.Sprintf("ag-%d", i), Provider: "antigravity", - Metadata: map[string]any{"refresh_token": fmt.Sprintf("ref-%d", i)}, + Metadata: map[string]any{"access_token": "old-access", "refresh_token": "old-refresh"}, } - if _, err := manager.Register(context.Background(), auth); err != nil { + if _, err := manager.Register(WithSkipPersist(context.Background()), auth); err != nil { t.Fatalf("register auth: %v", err) } } @@ -315,7 +340,8 @@ func TestManager_ForceRefreshAll_DynamicCancellationSkipsRemaining(t *testing.T) t.Fatalf("expected 6 results, got %d", len(results)) } - // Exactly 2 workers entered Refresh; remaining 4 were canceled in queue + // Exactly 2 workers entered Refresh; remaining 4 were canceled in queue. + // Successful rotations must be saved and published despite cancellation. if entered := executor.totalEntered.Load(); entered != 2 { t.Fatalf("expected exactly 2 entered calls, got %d", entered) } @@ -323,10 +349,25 @@ func TestManager_ForceRefreshAll_DynamicCancellationSkipsRemaining(t *testing.T) successCount := 0 cancelCount := 0 for _, res := range results { + current, exists := manager.GetByID(res.ID) + if !exists { + t.Fatalf("auth %s disappeared", res.ID) + } + store.mu.Lock() + persisted := store.auths[res.ID].Clone() + store.mu.Unlock() if res.Success { successCount++ + for name, auth := range map[string]*Auth{"manager": current, "store": persisted} { + if auth == nil || auth.Metadata["access_token"] != "rotated-access-"+res.ID || auth.Metadata["refresh_token"] != "rotated-refresh-"+res.ID { + t.Errorf("%s missing rotated tokens for %s", name, res.ID) + } + } } else if res.Error == context.Canceled.Error() { cancelCount++ + if persisted != nil || current.Metadata["access_token"] != "old-access" || current.Metadata["refresh_token"] != "old-refresh" { + t.Errorf("unstarted auth %s was modified or persisted", res.ID) + } } } if successCount != 2 { diff --git a/sdk/cliproxy/auth/store.go b/sdk/cliproxy/auth/store.go index 0594a77dd37..83e401dfa0f 100644 --- a/sdk/cliproxy/auth/store.go +++ b/sdk/cliproxy/auth/store.go @@ -7,6 +7,12 @@ type Store interface { // List returns all auth records stored in the backend. List(ctx context.Context) ([]*Auth, error) // Save persists the provided auth record, replacing any existing one with same ID. + // It may enrich exported fields, but must not change ID, RegistrationEpoch or + // Generation. The manager merges these changes even on non-fatal save errors. + // Do not retain auth or mutate shared nested values in place: replace metadata + // values, pointers, Storage and Runtime instead. Auth.Clone shares these objects. + // Save may call manager read APIs, but must not synchronously mutate the + // manager or call Load (the reload barrier remains held until publication). Save(ctx context.Context, auth *Auth) (string, error) // Delete removes the auth record identified by id. Delete(ctx context.Context, id string) error From c997cbb58afe0035fcb0cbd94aa766acb951c674 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Sun, 4 Oct 2026 17:33:19 +0800 Subject: [PATCH 037/142] feat(httpwire): introduce error-aware response flushing helper - Add `FlushResponse` to prefer error-aware flushing and unwrap wrapped response writers - Bypass Gin's void `Flush` while maintaining header accounting via `WriteHeaderNow` to keep transport errors observable Closes: #6332 --- internal/api/middleware/response_writer.go | 6 + internal/cache/issue6332_delivery_test.go | 147 +++++ internal/cache/issue6332_export_test.go | 24 + internal/httpwire/flush.go | 38 ++ internal/httpwire/flush_test.go | 151 +++++ internal/logging/cpa_trace.go | 8 +- .../pluginhost/issue6332_delivery_test.go | 194 +++++++ .../executor/antigravity_executor_stream.go | 75 ++- sdk/api/handlers/handlers_stream.go | 55 +- .../handlers/handlers_stream_delivery_test.go | 162 ++++++ sdk/api/handlers/model_execution.go | 3 + .../handlers/model_execution_delivery_test.go | 67 +++ .../handlers/openai/issue6332_review7_test.go | 268 +++++++++ sdk/api/handlers/openai/issue6332_test.go | 548 ++++++++++++++++++ .../openai/openai_responses_handlers.go | 94 ++- .../openai_responses_plugin_route_test.go | 8 +- sdk/api/handlers/stream_forwarder.go | 42 +- sdk/cliproxy/usage/stream_delivery.go | 73 +++ sdk/cliproxy/usage/stream_delivery_test.go | 95 +++ 19 files changed, 1989 insertions(+), 69 deletions(-) create mode 100644 internal/cache/issue6332_delivery_test.go create mode 100644 internal/cache/issue6332_export_test.go create mode 100644 internal/httpwire/flush.go create mode 100644 internal/httpwire/flush_test.go create mode 100644 internal/pluginhost/issue6332_delivery_test.go create mode 100644 sdk/api/handlers/handlers_stream_delivery_test.go create mode 100644 sdk/api/handlers/model_execution_delivery_test.go create mode 100644 sdk/api/handlers/openai/issue6332_review7_test.go create mode 100644 sdk/api/handlers/openai/issue6332_test.go create mode 100644 sdk/cliproxy/usage/stream_delivery.go create mode 100644 sdk/cliproxy/usage/stream_delivery_test.go diff --git a/internal/api/middleware/response_writer.go b/internal/api/middleware/response_writer.go index 44e1f0b66b6..0fe5b72bec1 100644 --- a/internal/api/middleware/response_writer.go +++ b/internal/api/middleware/response_writer.go @@ -13,6 +13,7 @@ import ( "github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v8/internal/clienterror" + "github.com/router-for-me/CLIProxyAPI/v8/internal/httpwire" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/logging" log "github.com/sirupsen/logrus" @@ -104,6 +105,11 @@ func (w *ResponseWriterWrapper) Write(data []byte) (int, error) { return n, err } +// FlushError forwards transport errors without bypassing inner middleware. +func (w *ResponseWriterWrapper) FlushError() error { + return httpwire.FlushResponse(w.ResponseWriter) +} + func (w *ResponseWriterWrapper) shouldBufferResponseBody() bool { if w.logger != nil && w.logger.IsEnabled() { return true diff --git a/internal/cache/issue6332_delivery_test.go b/internal/cache/issue6332_delivery_test.go new file mode 100644 index 00000000000..73573229b8e --- /dev/null +++ b/internal/cache/issue6332_delivery_test.go @@ -0,0 +1,147 @@ +package cache_test + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/router-for-me/CLIProxyAPI/v8/internal/api/middleware" + "github.com/router-for-me/CLIProxyAPI/v8/internal/cache" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/logging" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + runtimeexecutor "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor" + _ "github.com/router-for-me/CLIProxyAPI/v8/internal/translator" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers/openai" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + sdkconfig "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +func TestIssue6332ReplayCommitPrecedesCompletion(t *testing.T) { + for _, mode := range []string{"held_open", "clean_eof", "internal_eof"} { + t.Run(mode, func(t *testing.T) { + const model = "gemini-3.7-flash" + signature := strings.Repeat("s", 128) + session := t.Name() + cache.ClearAntigravityReasoningReplayCache() + t.Cleanup(cache.ClearAntigravityReasoningReplayCache) + entered, release, calls := cache.Issue6332BlockCommit(t) + var releaseOnce sync.Once + unblock := func() { releaseOnce.Do(func() { close(release) }) } + defer unblock() + requests := make(chan []byte, 2) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, errRead := io.ReadAll(r.Body) + if errRead != nil { + t.Error(errRead) + return + } + requests <- body + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"functionCall":{"id":"native-call","name":"lookup","args":{"key":"value"}},"thoughtSignature":"`+signature+`"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":11,"candidatesTokenCount":22,"totalTokenCount":33},"responseId":"resp-replay"}}`+"\n\n") + w.(http.Flusher).Flush() + if mode == "held_open" { + <-r.Context().Done() + } + })) + defer server.Close() + manager := cliproxyauth.NewManager(nil, nil, nil) + manager.RegisterExecutor(runtimeexecutor.NewAntigravityExecutor(&config.Config{})) + auth := &cliproxyauth.Auth{ID: t.Name(), Provider: "antigravity", Status: cliproxyauth.StatusActive, ProxyURL: "direct", Metadata: map[string]any{"access_token": "token", "expired": time.Now().Add(time.Hour).Format(time.RFC3339), "project_id": "project"}, Attributes: map[string]string{"base_url": server.URL}} + if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil { + t.Fatal(errRegister) + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, auth.Provider, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(auth.ID) }) + base := handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, manager) + h := openai.NewOpenAIResponsesAPIHandler(base) + router := gin.New() + router.Use(logging.CPATraceIDMiddleware(), middleware.RequestLoggingMiddleware(logging.NewFileRequestLogger(true, t.TempDir(), "", 0))) + router.POST("/v1/responses", h.Responses) + call := func(payload string) string { + t.Helper() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + if mode == "internal_eof" { + stream, errExecute := base.ExecuteModelStream(ctx, handlers.ModelExecutionRequest{EntryProtocol: "openai-response", ExitProtocol: "openai-response", Model: model, Stream: true, Body: []byte(payload)}) + if errExecute != nil { + t.Error(errExecute) + return "" + } + var output strings.Builder + for chunk := range stream.Chunks { + if chunk.Err != nil { + t.Error(chunk.Err) + } + output.Write(chunk.Payload) + } + return output.String() + } + writer := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(payload)).WithContext(ctx) + request.Header.Set("Session-Id", session) + router.ServeHTTP(writer, request) + return writer.Body.String() + } + first := `{"model":"gemini-3.7-flash","input":[{"role":"user","content":"hello"}],"stream":true,"tools":[{"type":"function","name":"lookup","parameters":{"type":"object","properties":{"key":{"type":"string"}}}}]}` + first, _ = sjson.Set(first, "metadata.session_id", session) + firstDone := make(chan string, 1) + go func() { firstDone <- call(first) }() + <-requests + <-entered + select { + case <-firstDone: + t.Fatal("completion escaped before replay commit") + default: + } + unblock() + downstream := <-firstDone + var functionCall gjson.Result + for _, line := range strings.Split(downstream, "\n") { + if !strings.HasPrefix(line, "data:") { + continue + } + event := gjson.Parse(strings.TrimSpace(strings.TrimPrefix(line, "data:"))) + if event.Get("type").String() == "response.completed" { + for _, item := range event.Get("response.output").Array() { + if item.Get("type").String() == "function_call" { + functionCall = item + } + } + } + } + if !functionCall.Exists() { + t.Fatalf("no completed tool call: %s", downstream) + } + // Deliberately omit encrypted reasoning: restoration must come from the session ledger. + second, _ := sjson.Set(first, "input.-1", map[string]any{"type": "function_call", "call_id": functionCall.Get("call_id").String(), "name": "lookup", "arguments": `{"key":"value"}`}) + second, _ = sjson.Set(second, "input.-1", map[string]any{"type": "function_call_output", "call_id": functionCall.Get("call_id").String(), "output": "found"}) + call(second) + upstream := <-requests + restored := false + for _, content := range gjson.GetBytes(upstream, "request.contents").Array() { + for _, part := range content.Get("parts").Array() { + if part.Get("functionCall.name").String() == "lookup" && part.Get("thoughtSignature").String() == signature { + restored = true + } + } + } + + if got := calls(); got != 4 { + t.Errorf("replay storage calls = %d, want one read and one commit per turn", got) + } + if !restored { + t.Errorf("second turn lost tool-call signature: %s", upstream) + } + }) + } +} diff --git a/internal/cache/issue6332_export_test.go b/internal/cache/issue6332_export_test.go new file mode 100644 index 00000000000..b140bb1768b --- /dev/null +++ b/internal/cache/issue6332_export_test.go @@ -0,0 +1,24 @@ +package cache + +import ( + "sync/atomic" + "testing" +) + +// Issue6332BlockCommit pauses the first commit before it can update the ledger. +// This hook exists only in the test binary. +func Issue6332BlockCommit(t *testing.T) (<-chan struct{}, chan<- struct{}, func() int32) { + t.Helper() + original := currentAntigravityReasoningReplayKVClient + entered, release := make(chan struct{}), make(chan struct{}) + var calls atomic.Int32 + currentAntigravityReasoningReplayKVClient = func() (antigravityReasoningReplayKVClient, bool, error) { + if calls.Add(1) == 2 { + close(entered) + <-release + } + return original() + } + t.Cleanup(func() { currentAntigravityReasoningReplayKVClient = original }) + return entered, release, calls.Load +} diff --git a/internal/httpwire/flush.go b/internal/httpwire/flush.go new file mode 100644 index 00000000000..36735953ff1 --- /dev/null +++ b/internal/httpwire/flush.go @@ -0,0 +1,38 @@ +package httpwire + +import ( + "net/http" + "reflect" +) + +// FlushResponse prefers error-aware flushing and preserves legacy middleware. +// Only Gin's raw void Flush is bypassed so transport errors remain observable. +func FlushResponse(w http.ResponseWriter) error { + for { + if flusher, ok := w.(interface{ FlushError() error }); ok { + return flusher.FlushError() + } + if flusher, ok := w.(http.Flusher); ok { + if !isGinResponseWriter(w) { + flusher.Flush() + return nil + } + // Match Gin's Flush header accounting before reaching its transport. + w.(interface{ WriteHeaderNow() }).WriteHeaderNow() + } + unwrapper, ok := w.(interface{ Unwrap() http.ResponseWriter }) + if !ok { + return http.NewResponseController(w).Flush() + } + w = unwrapper.Unwrap() + } +} + +func isGinResponseWriter(w http.ResponseWriter) bool { + // Gin's concrete writer is unexported. Interface checks also match wrappers + // embedding gin.ResponseWriter, whose Flush may drain buffers or compressors. + // Restrict this exception to the exact package/type; never inspect its fields. + t := reflect.TypeOf(w) + return t != nil && t.Kind() == reflect.Pointer && + t.Elem().PkgPath() == "github.com/gin-gonic/gin" && t.Elem().Name() == "responseWriter" +} diff --git a/internal/httpwire/flush_test.go b/internal/httpwire/flush_test.go new file mode 100644 index 00000000000..887bc017e90 --- /dev/null +++ b/internal/httpwire/flush_test.go @@ -0,0 +1,151 @@ +package httpwire + +import ( + "bufio" + "errors" + "io" + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" +) + +type flushErrorWriter struct { + *httptest.ResponseRecorder + flushes int + legacyFlushes int +} + +func (w *flushErrorWriter) Flush() { + w.legacyFlushes++ + w.ResponseRecorder.Flush() +} + +func (w *flushErrorWriter) FlushError() error { + w.flushes++ + return io.ErrClosedPipe +} + +type flushMiddlewareWriter struct { + http.ResponseWriter + flushes int +} + +func (w *flushMiddlewareWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } +func (w *flushMiddlewareWriter) FlushError() error { + w.flushes++ + w.Header().Set("X-Middleware-Flush", "preserved") + return FlushResponse(w.ResponseWriter) +} + +func TestFlushResponsePreservesMiddlewareBeforeUnwrap(t *testing.T) { + transport := &flushErrorWriter{ResponseRecorder: httptest.NewRecorder()} + c, _ := gin.CreateTestContext(transport) + c.Writer.WriteHeader(http.StatusAccepted) + wrapper := &flushMiddlewareWriter{ResponseWriter: c.Writer} + if errFlush := FlushResponse(wrapper); !errors.Is(errFlush, io.ErrClosedPipe) { + t.Fatalf("flush error = %v", errFlush) + } + if wrapper.flushes != 1 || transport.flushes != 1 || transport.legacyFlushes != 0 { + t.Fatalf("flush counts = %d/%d/%d, want 1/1/0", wrapper.flushes, transport.flushes, transport.legacyFlushes) + } + if c.Writer.Status() != http.StatusAccepted || transport.Code != http.StatusAccepted || c.Writer.Size() != 0 { + t.Fatalf("Gin accounting: status=%d, transport=%d, size=%d", c.Writer.Status(), transport.Code, c.Writer.Size()) + } + if !c.Writer.Written() || transport.Result().Header.Get("X-Middleware-Flush") != "preserved" { + t.Fatal("flush bypassed middleware or Gin header accounting") + } +} + +type bufferedFlushWriter struct { + http.ResponseWriter + buffer *bufio.Writer + flushes int + unwraps int + flushErr error +} + +func (w *bufferedFlushWriter) Write(p []byte) (int, error) { return w.buffer.Write(p) } +func (w *bufferedFlushWriter) Unwrap() http.ResponseWriter { + w.unwraps++ + return w.ResponseWriter +} +func (w *bufferedFlushWriter) Flush() { + w.flushes++ + w.flushErr = w.buffer.Flush() + w.ResponseWriter.(http.Flusher).Flush() +} + +// Embedding Gin's interface must not make middleware look like its raw writer. +type bufferedGinFlushWriter struct { + gin.ResponseWriter + buffered *bufferedFlushWriter +} + +func (w *bufferedGinFlushWriter) Write(p []byte) (int, error) { return w.buffered.Write(p) } +func (w *bufferedGinFlushWriter) Flush() { w.buffered.Flush() } +func (w *bufferedGinFlushWriter) Unwrap() http.ResponseWriter { + return w.buffered.Unwrap() +} + +type countedFlushWriter struct { + *httptest.ResponseRecorder + flushes int +} + +func (w *countedFlushWriter) Flush() { + w.flushes++ + w.ResponseRecorder.Flush() +} + +func TestFlushResponsePreservesBufferedLegacyWrapper(t *testing.T) { + for _, shape := range []string{"http", "gin", "under_gin"} { + t.Run(shape, func(t *testing.T) { + transport := &countedFlushWriter{ResponseRecorder: httptest.NewRecorder()} + c, _ := gin.CreateTestContext(transport) + inner := http.ResponseWriter(transport) + if shape == "gin" { + inner = c.Writer + } + buffered := &bufferedFlushWriter{ResponseWriter: inner, buffer: bufio.NewWriter(inner)} + var writer http.ResponseWriter = buffered + if shape == "gin" { + writer = &bufferedGinFlushWriter{ResponseWriter: c.Writer, buffered: buffered} + } else if shape == "under_gin" { + c, _ = gin.CreateTestContext(buffered) + writer = c.Writer + } + wrapper := &flushMiddlewareWriter{ResponseWriter: writer} + const body = "data: buffered response\n\n" + if _, errWrite := wrapper.Write([]byte(body)); errWrite != nil { + t.Fatal(errWrite) + } + if transport.Body.Len() != 0 || buffered.buffer.Buffered() != len(body) { + t.Fatal("test write did not stay buffered") + } + if errFlush := FlushResponse(wrapper); errFlush != nil { + t.Fatal(errFlush) + } + if buffered.flushErr != nil || buffered.buffer.Buffered() != 0 || transport.Body.String() != body { + t.Errorf("buffer not drained: buffered=%d, body=%q, error=%v", buffered.buffer.Buffered(), transport.Body.String(), buffered.flushErr) + } + if wrapper.flushes != 1 || buffered.flushes != 1 || buffered.unwraps != 0 || transport.flushes != 1 { + t.Errorf("calls: middleware=%d, buffer flush=%d, buffer unwrap=%d, transport=%d; want 1/1/0/1", wrapper.flushes, buffered.flushes, buffered.unwraps, transport.flushes) + } + if !transport.Flushed { + t.Error("transport was not flushed") + } + }) + } +} + +func TestFlushResponseSupportsLegacyFlusher(t *testing.T) { + writer := httptest.NewRecorder() + if errFlush := FlushResponse(writer); errFlush != nil { + t.Fatal(errFlush) + } + if !writer.Flushed { + t.Fatal("legacy flusher was not called") + } +} diff --git a/internal/logging/cpa_trace.go b/internal/logging/cpa_trace.go index bc1d243a88a..fd2df4c555d 100644 --- a/internal/logging/cpa_trace.go +++ b/internal/logging/cpa_trace.go @@ -6,6 +6,7 @@ import ( "time" "github.com/gin-gonic/gin" + "github.com/router-for-me/CLIProxyAPI/v8/internal/httpwire" ) // CPATraceIDHeader is the downstream response header used to correlate requests with selected credentials. @@ -137,8 +138,13 @@ func (w *cpaTraceResponseWriter) WriteString(data string) (int, error) { } func (w *cpaTraceResponseWriter) Flush() { + _ = w.FlushError() +} + +// FlushError preserves trace headers while forwarding transport errors. +func (w *cpaTraceResponseWriter) FlushError() error { w.applyTraceHeader() - w.ResponseWriter.Flush() + return httpwire.FlushResponse(w.ResponseWriter) } func (w *cpaTraceResponseWriter) applyTraceHeader() { diff --git a/internal/pluginhost/issue6332_delivery_test.go b/internal/pluginhost/issue6332_delivery_test.go new file mode 100644 index 00000000000..c81b0ad4bce --- /dev/null +++ b/internal/pluginhost/issue6332_delivery_test.go @@ -0,0 +1,194 @@ +package pluginhost + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/cache" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + runtimeexecutor "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor" + _ "github.com/router-for-me/CLIProxyAPI/v8/internal/translator" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" + sdkconfig "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginabi" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginapi" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +type issue6332NestedLifecycle struct { + handlers.PluginInterceptorHost + completed chan pluginapi.RequestCompletion +} + +func (*issue6332NestedLifecycle) HasRequestInterceptors() bool { return false } +func (*issue6332NestedLifecycle) HasStreamInterceptors() bool { return false } +func (h *issue6332NestedLifecycle) CompleteRequest(_ context.Context, c pluginapi.RequestCompletion) { + h.completed <- c +} + +// Exercise the actual plugin RPC callbacks and stream bridge, not a fake model executor. +func TestIssue6332PluginNestedDelivery(t *testing.T) { + for _, mode := range []string{"complete", "cancel_partial", "cancel_complete"} { + t.Run(mode, func(t *testing.T) { + cancelStream := mode != "complete" + const model = "gemini-3.7-flash" + signature := strings.Repeat("s", 128) + requests := make(chan []byte, 2) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, errRead := io.ReadAll(r.Body) + if errRead != nil { + t.Error(errRead) + return + } + requests <- body + w.Header().Set("Content-Type", "text/event-stream") + // Cancellation of partial upstream output must not commit replay. + finish := `,"finishReason":"STOP"` + if mode == "cancel_partial" { + finish = "" + } + _, _ = io.WriteString(w, `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"functionCall":{"id":"native-call","name":"lookup","args":{"key":"value"}},"thoughtSignature":"`+signature+`"}]}`+finish+`}],"usageMetadata":{"promptTokenCount":11,"candidatesTokenCount":22,"totalTokenCount":33},"responseId":"nested"}}`+"\n\n") + w.(http.Flusher).Flush() + if cancelStream { + <-r.Context().Done() + } + })) + defer server.Close() + manager := cliproxyauth.NewManager(nil, nil, nil) + manager.RegisterExecutor(runtimeexecutor.NewAntigravityExecutor(&config.Config{})) + auth := &cliproxyauth.Auth{ID: t.Name(), Provider: "antigravity", Status: cliproxyauth.StatusActive, ProxyURL: "direct", Metadata: map[string]any{"access_token": "token", "expired": time.Now().Add(time.Hour).Format(time.RFC3339), "project_id": "project"}, Attributes: map[string]string{"base_url": server.URL}} + if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil { + t.Fatal(errRegister) + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, auth.Provider, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(auth.ID) }) + base := handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, manager) + lifecycle := &issue6332NestedLifecycle{completed: make(chan pluginapi.RequestCompletion, 4)} + base.SetPluginHost(lifecycle) + host := New() + host.SetModelExecutor(base) + outer, finishOuter := usage.WithStreamDelivery(context.Background()) + // No outer completion is acknowledged until the nested tool loop finishes. + defer finishOuter(context.Canceled) + callbackID, closeCallback := host.openCallbackContextForPlugin(outer, "tool-loop-plugin") + defer closeCallback() + call := func(body string) (string, error) { + raw, _ := json.Marshal(rpcHostModelExecutionRequest{HostCallbackID: callbackID, HostModelExecutionRequest: pluginapi.HostModelExecutionRequest{EntryProtocol: "openai-response", ExitProtocol: "openai-response", Model: model, Stream: true, Body: []byte(body)}}) + response, errCall := host.callFromPlugin(context.Background(), pluginabi.MethodHostModelExecuteStream, raw) + if errCall != nil { + return "", errCall + } + stream, errDecode := decodeRPCEnvelope[pluginapi.HostModelStreamResponse](response) + if errDecode != nil { + return "", errDecode + } + read, _ := json.Marshal(pluginapi.HostModelStreamReadRequest{StreamID: stream.StreamID}) + var output strings.Builder + for { + response, errRead := host.callFromPlugin(context.Background(), pluginabi.MethodHostModelStreamRead, read) + if errRead != nil { + return "", errRead + } + chunk, errDecodeChunk := decodeRPCEnvelope[pluginapi.HostModelStreamReadResponse](response) + if errDecodeChunk != nil { + return "", errDecodeChunk + } + if chunk.Error != "" { + return "", fmt.Errorf("stream error: %s", chunk.Error) + } + output.Write(chunk.Payload) + if cancelStream { + closeCallback() + return output.String(), nil + } + if chunk.Done { + return output.String(), nil + } + } + } + result := make(chan error, 1) + go func() { + first := `{"model":"` + model + `","stream":true,"metadata":{"session_id":"` + t.Name() + `"},"input":[{"role":"user","content":"lookup"}]}` + output, errCall := call(first) + if errCall != nil || cancelStream { + result <- errCall + return + } + var callID string + for _, line := range strings.Split(output, "\n") { + event := gjson.Parse(strings.TrimSpace(strings.TrimPrefix(line, "data:"))) + for _, item := range event.Get("response.output").Array() { + if item.Get("type").String() == "function_call" { + callID = item.Get("call_id").String() + } + } + } + if callID == "" { + result <- fmt.Errorf("missing function call: %s", output) + return + } + second, _ := sjson.Set(first, "input.-1", map[string]any{"type": "function_call", "call_id": callID, "name": "lookup", "arguments": `{"key":"value"}`}) + second, _ = sjson.Set(second, "input.-1", map[string]any{"type": "function_call_output", "call_id": callID, "output": "found"}) + _, errCall = call(second) + result <- errCall + }() + select { + case errResult := <-result: + if errResult != nil { + t.Fatal(errResult) + } + case <-time.After(3 * time.Second): + finishOuter(context.Canceled) + closeCallback() + <-result + t.Fatal("nested tool loop blocked waiting for outer HTTP delivery") + } + if usage.StreamDeliverySupported(outer) { + t.Error("nested producer leaked outer delivery support") + } + turns := 2 + if cancelStream { + turns = 1 + } + for range turns { + select { + case c := <-lifecycle.completed: + want := pluginapi.RequestCompletionSucceeded + if cancelStream { + want = pluginapi.RequestCompletionCanceled + } + if c.Outcome != want { + t.Errorf("nested lifecycle = %+v, want %s", c, want) + } + case <-time.After(3 * time.Second): + t.Fatal("nested lifecycle waits for outer delivery") + } + } + <-requests + if !cancelStream { + second := <-requests + if !strings.Contains(string(second), signature) { + t.Errorf("second turn lost replay signature: %s", second) + } + } else { + readCtx, cancelRead := context.WithTimeout(context.Background(), 3*time.Second) + defer cancelRead() + items, _, _, errGet := cache.GetAntigravityReasoningReplayItemsWithSnapshotRequired(readCtx, model, "responses:"+t.Name()) + if errGet != nil || (len(items) > 0) != (mode == "cancel_complete") { + t.Errorf("replay must follow upstream completeness, not delivery: %v, %v", items, errGet) + } + } + }) + } +} diff --git a/internal/runtime/executor/antigravity_executor_stream.go b/internal/runtime/executor/antigravity_executor_stream.go index bd02f0f4d58..904b333cdce 100644 --- a/internal/runtime/executor/antigravity_executor_stream.go +++ b/internal/runtime/executor/antigravity_executor_stream.go @@ -14,6 +14,7 @@ import ( "github.com/router-for-me/CLIProxyAPI/v8/internal/thinking" cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" log "github.com/sirupsen/logrus" "github.com/tidwall/gjson" @@ -192,8 +193,8 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya } replayAccumulator := newAntigravityReasoningReplayAccumulator(replayScope, requestPayload) out := make(chan cliproxyexecutor.StreamChunk) + stopDeliverySupport := usage.SupportStreamDelivery(ctx) go func(resp *http.Response) { - defer close(out) defer func() { if errClose := resp.Body.Close(); errClose != nil { log.Errorf("antigravity executor: close response line error: %v", errClose) @@ -203,8 +204,42 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya scanner.Buffer(nil, streamScannerBuffer) claudeInputTokens := helps.NewClaudeInputTokenState(from, to, responseFormat, originalPayload) var streamUsage helps.StreamUsageBuffer - defer streamUsage.Publish(ctx, reporter) + var streamErr error + var replayCommitted bool var param any + commitReplay := func() { + if !replayCommitted && replayAccumulator != nil && replayAccumulator.terminal && helps.ApplyPatchTranslationError(param) == nil { + replayAccumulator.Commit(ctx) + replayCommitted = true + } + } + defer func() { + defer stopDeliverySupport() + if helps.ApplyPatchTranslationError(param) != nil { + streamErr = statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage} + stopDeliverySupport() + } + // Replay is settled before forwarding completion; accounting still waits + // for the HTTP consumer, which may need EOF to acknowledge delivery. + close(out) + if streamErr == nil { + streamErr = ctx.Err() + } + if deliveryErr, tracked := usage.WaitStreamDelivery(ctx); tracked { + if streamErr == nil || errors.Is(streamErr, context.Canceled) { + streamErr = deliveryErr + } + } + if streamErr != nil { + if !streamUsage.PublishFailure(ctx, reporter, streamErr) { + reporter.PublishFailure(ctx, streamErr) + } + return + } + + streamUsage.Publish(ctx, reporter) + reporter.EnsurePublished(ctx) + }() helps.InitializeApplyPatchStream(ctx, to, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), translated, ¶m) for scanner.Scan() { line := scanner.Bytes() @@ -213,6 +248,9 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya replayAccumulator.ObserveSSELine(line) } + // Capture accounting before the client-facing filter renames usage. + streamUsage.Observe(helps.ParseAntigravityStreamUsage(line)) + // Filter usage metadata for all models // Only retain usage statistics in the terminal chunk line = helps.FilterSSEUsageMetadata(line) @@ -223,13 +261,20 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya } reporter.ObserveResponseModel(payload) - if detail, ok := helps.ParseAntigravityStreamUsage(payload); ok { - streamUsage.Observe(detail, true) - } - payload = e.resolveWebSearchGroundingURLs(ctx, auth, from, originalPayload, translated, payload) chunks := helps.TranslateStreamWithClaudeInputTokens(ctx, to, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), translated, bytes.Clone(payload), ¶m, claudeInputTokens) helps.RecordApplyPatchStreamFailure(ctx, param, reporter, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) + if replayAccumulator != nil && replayAccumulator.terminal && !replayCommitted && responseFormat == sdktranslator.FormatOpenAIResponse { + // Wait for the translated completion, not the first finishReason: + // split usage/signature frames may still extend the replay ledger. + for _, chunk := range chunks { + for _, line := range bytes.Split(chunk, []byte("\n")) { + if gjson.GetBytes(helps.JSONPayload(line), "type").String() == "response.completed" { + commitReplay() + } + } + } + } for i := range chunks { select { case out <- cliproxyexecutor.StreamChunk{Payload: chunks[i]}: @@ -245,8 +290,14 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya return } if errScan := scanner.Err(); errScan != nil { + streamErr = errScan + if errors.Is(errScan, context.Canceled) && ctx.Err() != nil { + if deliveryErr, tracked := usage.WaitStreamDelivery(ctx); tracked && deliveryErr == nil { + return + } + } + stopDeliverySupport() helps.RecordAPIResponseError(ctx, e.cfg, errScan) - reporter.PublishFailure(ctx, errScan) select { case out <- cliproxyexecutor.StreamChunk{Err: errScan}: case <-ctx.Done(): @@ -257,6 +308,9 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya // stream as a successful completion. tail := helps.TranslateStreamWithClaudeInputTokens(ctx, to, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), translated, []byte("[DONE]"), ¶m, claudeInputTokens) helps.RecordApplyPatchStreamFailure(ctx, param, reporter, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) + // Commit upstream output before EOF-generated completion reaches interceptors. + // Commit itself rejects partial streams without an upstream terminal. + commitReplay() for i := range tail { select { case out <- cliproxyexecutor.StreamChunk{Payload: tail[i]}: @@ -264,13 +318,6 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya return } } - if replayAccumulator != nil { - replayAccumulator.Commit(ctx) - } - // The reporter keeps only the first outcome. Publish the buffered - // usage before EnsurePublished, which otherwise records an empty detail. - streamUsage.Publish(ctx, reporter) - reporter.EnsurePublished(ctx) } }(httpResp) return &cliproxyexecutor.StreamResult{Headers: httpResp.Header.Clone(), Chunks: out}, nil diff --git a/sdk/api/handlers/handlers_stream.go b/sdk/api/handlers/handlers_stream.go index 5ac61ec936f..a207c5fc3d5 100644 --- a/sdk/api/handlers/handlers_stream.go +++ b/sdk/api/handlers/handlers_stream.go @@ -3,6 +3,7 @@ package handlers import ( "bytes" "encoding/json" + "errors" "fmt" "net/http" @@ -150,6 +151,7 @@ func (h *BaseAPIHandler) streamWithPluginExecutor(ctx context.Context, entryProt var completionErr error var streamUsage helps.StreamUsageBuffer defer func() { + completionOutcome, completionStatus, completionErr = streamDeliveryCompletion(ctx, completionOutcome, completionStatus, completionErr) lifecycle.complete(completionOutcome, completionStatus, completionErr) if reporter != nil && !nestedTracker.hasNestedExecution() { if completionOutcome != pluginapi.RequestCompletionSucceeded && completionErr != nil { @@ -185,11 +187,6 @@ func (h *BaseAPIHandler) streamWithPluginExecutor(ctx context.Context, entryProt select { case errChan <- &interfaces.ErrorMessage{StatusCode: http.StatusBadGateway, Error: errValidate}: case <-done: - completionOutcome = pluginapi.RequestCompletionCanceled - completionStatus = 0 - if ctx != nil { - completionErr = ctx.Err() - } } } } @@ -203,11 +200,6 @@ func (h *BaseAPIHandler) streamWithPluginExecutor(ctx context.Context, entryProt select { case errChan <- errMsg: case <-done: - completionOutcome = pluginapi.RequestCompletionCanceled - completionStatus = 0 - if ctx != nil { - completionErr = ctx.Err() - } } return } @@ -259,11 +251,6 @@ func (h *BaseAPIHandler) streamWithPluginExecutor(ctx context.Context, entryProt select { case errChan <- &interfaces.ErrorMessage{StatusCode: http.StatusBadGateway, Error: errValidate}: case <-done: - completionOutcome = pluginapi.RequestCompletionCanceled - completionStatus = 0 - if ctx != nil { - completionErr = ctx.Err() - } } return } @@ -609,6 +596,7 @@ func (h *BaseAPIHandler) executeStreamWithAuthManagerFormats(ctx context.Context completionStatus := http.StatusOK var completionErr error defer func() { + completionOutcome, completionStatus, completionErr = streamDeliveryCompletion(ctx, completionOutcome, completionStatus, completionErr) lifecycle.complete(completionOutcome, completionStatus, completionErr) }() defer close(dataChan) @@ -655,11 +643,7 @@ func (h *BaseAPIHandler) executeStreamWithAuthManagerFormats(ctx context.Context } completionStatus = bootstrapErr.StatusCode completionErr = bootstrapErr.Error - if !sendErr(bootstrapErr) && ctx != nil && ctx.Err() != nil { - completionOutcome = pluginapi.RequestCompletionCanceled - completionStatus = 0 - completionErr = ctx.Err() - } + _ = sendErr(bootstrapErr) return } @@ -705,11 +689,7 @@ func (h *BaseAPIHandler) executeStreamWithAuthManagerFormats(ctx context.Context completionOutcome = pluginapi.RequestCompletionFailed completionStatus = errMsg.StatusCode completionErr = chunk.Err - if !sendErr(errMsg) && ctx != nil && ctx.Err() != nil { - completionOutcome = pluginapi.RequestCompletionCanceled - completionStatus = 0 - completionErr = ctx.Err() - } + _ = sendErr(errMsg) return } if len(chunk.Payload) == 0 { @@ -720,11 +700,7 @@ func (h *BaseAPIHandler) executeStreamWithAuthManagerFormats(ctx context.Context completionOutcome = pluginapi.RequestCompletionFailed completionStatus = errMsg.StatusCode completionErr = errMsg.Error - if !sendErr(errMsg) && ctx != nil && ctx.Err() != nil { - completionOutcome = pluginapi.RequestCompletionCanceled - completionStatus = 0 - completionErr = ctx.Err() - } + _ = sendErr(errMsg) return } if !deliverable { @@ -871,3 +847,22 @@ func validateSSEDataJSON(chunk []byte) error { } return state.Finish() } + +// streamDeliveryCompletion reconciles execution cleanup with the HTTP outcome. +// Call only after closing output channels: the consumer may need EOF to finish. +func streamDeliveryCompletion(ctx context.Context, outcome pluginapi.RequestCompletionOutcome, status int, err error) (pluginapi.RequestCompletionOutcome, int, error) { + if ctx == nil { + return outcome, status, err + } + deliveryErr, tracked := coreusage.WaitStreamDelivery(ctx) + if !tracked || (err != nil && !errors.Is(err, context.Canceled)) || outcome == pluginapi.RequestCompletionRejected { + return outcome, status, err + } + if deliveryErr == nil { + return pluginapi.RequestCompletionSucceeded, http.StatusOK, nil + } + if errors.Is(deliveryErr, context.Canceled) || errors.Is(deliveryErr, context.DeadlineExceeded) { + return pluginapi.RequestCompletionCanceled, 0, deliveryErr + } + return pluginapi.RequestCompletionFailed, executionErrorMessage(deliveryErr).StatusCode, deliveryErr +} diff --git a/sdk/api/handlers/handlers_stream_delivery_test.go b/sdk/api/handlers/handlers_stream_delivery_test.go new file mode 100644 index 00000000000..a3c63b65d84 --- /dev/null +++ b/sdk/api/handlers/handlers_stream_delivery_test.go @@ -0,0 +1,162 @@ +package handlers + +import ( + "context" + "io" + "net/http" + "strings" + "testing" + "time" + + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + coreexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + coreusage "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" + sdkconfig "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginapi" +) + +func TestIssue6332LifecycleDeliveryReadyBoundary(t *testing.T) { + for _, tc := range []struct { + name string + deliveryErr error + upstreamErr error + want pluginapi.RequestCompletionOutcome + status int + }{ + {name: "delivered", want: pluginapi.RequestCompletionSucceeded, status: http.StatusOK}, + {name: "early_cancel", deliveryErr: context.Canceled, want: pluginapi.RequestCompletionCanceled}, + {name: "write_failure", deliveryErr: io.ErrClosedPipe, want: pluginapi.RequestCompletionFailed, status: http.StatusInternalServerError}, + {name: "read_failure", upstreamErr: io.ErrUnexpectedEOF, want: pluginapi.RequestCompletionFailed, status: http.StatusBadGateway}, + } { + t.Run(tc.name, func(t *testing.T) { + for range 100 { + ctx, finish := coreusage.WithStreamDelivery(context.Background()) + ctx, cancel := context.WithCancel(ctx) + finish(tc.deliveryErr) + cancel() + chunks := make(chan coreexecutor.StreamChunk) + close(chunks) + // Both EOF and cancellation are ready before the shared select. + _, _, canceled := nextStreamChunk(ctx, nil, nil, chunks) + outcome, status, err := pluginapi.RequestCompletionSucceeded, http.StatusOK, error(nil) + if canceled { + outcome, status, err = pluginapi.RequestCompletionCanceled, 0, ctx.Err() + } + if tc.upstreamErr != nil { + outcome, status, err = pluginapi.RequestCompletionFailed, http.StatusBadGateway, tc.upstreamErr + } + outcome, status, err = streamDeliveryCompletion(ctx, outcome, status, err) + completions := make(chan pluginapi.RequestCompletion, 1) + h := NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, nil) + h.SetPluginHost(&handlerInterceptorTestHost{completeRequest: func(_ context.Context, completion pluginapi.RequestCompletion) { completions <- completion }}) + h.newRequestLifecycleTracker(ctx, "openai-response", "model", "model", true, nil, "").complete(outcome, status, err) + completion := <-completions + wantErr := tc.deliveryErr + if tc.upstreamErr != nil { + wantErr = tc.upstreamErr + } + wantMessage := "" + if wantErr != nil { + wantMessage = wantErr.Error() + } + if completion.Outcome != tc.want || completion.StatusCode != tc.status || completion.Error != wantMessage { + t.Fatalf("completion = %+v, want %s/%d/%q", completion, tc.want, tc.status, wantMessage) + } + } + }) + } +} + +func TestIssue6332LifecycleClosesChannelsBeforeDeliveryWait(t *testing.T) { + model := "issue6332-lifecycle-eof" + executor := &interceptorCaptureExecutor{stream: func(context.Context, *coreauth.Auth, coreexecutor.Request, coreexecutor.Options) (*coreexecutor.StreamResult, error) { + chunks := make(chan coreexecutor.StreamChunk, 1) + chunks <- coreexecutor.StreamChunk{Payload: []byte(`{"chunk":true}`)} + close(chunks) + return &coreexecutor.StreamResult{Chunks: chunks}, nil + }} + h := newInterceptorHandler(t, model, executor, &sdkconfig.SDKConfig{}) + completions := make(chan pluginapi.RequestCompletion, 2) + h.SetPluginHost(&handlerInterceptorTestHost{completeRequest: func(_ context.Context, completion pluginapi.RequestCompletion) { completions <- completion }}) + ctx, finish := coreusage.WithStreamDelivery(context.Background()) + defer finish(context.Canceled) + data, _, errs := h.ExecuteStreamWithAuthManager(ctx, "openai", model, []byte(`{"stream":true}`), "") + timer := time.NewTimer(5 * time.Second) + defer timer.Stop() + for data != nil || errs != nil { + select { + case _, ok := <-data: + if !ok { + data = nil + } + case errMsg, ok := <-errs: + if ok && errMsg != nil { + t.Fatalf("stream error: %+v", errMsg) + } + if !ok { + errs = nil + } + case <-timer.C: + t.Fatal("output channels blocked on delivery acknowledgement") + } + } + select { + case completion := <-completions: + t.Fatalf("lifecycle completed before delivery: %+v", completion) + default: + } + finish(nil) + select { + case completion := <-completions: + if completion.Outcome != pluginapi.RequestCompletionSucceeded || completion.StatusCode != http.StatusOK || completion.Error != "" { + t.Fatalf("completion = %+v", completion) + } + case <-timer.C: + t.Fatal("missing lifecycle completion") + } + select { + case duplicate := <-completions: + t.Fatalf("duplicate completion: %+v", duplicate) + default: + } +} + +func TestIssue6332LifecycleValidationFailureSurvivesDeliveryCancellation(t *testing.T) { + model := "issue6332-lifecycle-validation" + executor := &interceptorCaptureExecutor{stream: func(context.Context, *coreauth.Auth, coreexecutor.Request, coreexecutor.Options) (*coreexecutor.StreamResult, error) { + chunks := make(chan coreexecutor.StreamChunk, 1) + chunks <- coreexecutor.StreamChunk{Payload: []byte("data: invalid JSON\n\n")} + close(chunks) + return &coreexecutor.StreamResult{Chunks: chunks}, nil + }} + h := newInterceptorHandler(t, model, executor, &sdkconfig.SDKConfig{}) + ctx, finish := coreusage.WithStreamDelivery(context.Background()) + ctx, cancel := context.WithCancel(ctx) + defer cancel() + defer finish(context.Canceled) + completions := make(chan pluginapi.RequestCompletion, 1) + h.SetPluginHost(&handlerInterceptorTestHost{ + interceptStreamChunk: func(_ context.Context, req pluginapi.StreamChunkInterceptRequest) pluginapi.StreamChunkInterceptResponse { + if len(req.Body) > 0 { + // Make cancellation and the buffered error send ready together. + finish(nil) + cancel() + } + return pluginapi.StreamChunkInterceptResponse{Body: req.Body} + }, + completeRequest: func(_ context.Context, completion pluginapi.RequestCompletion) { completions <- completion }, + }) + data, _, errs := h.ExecuteStreamWithAuthManager(ctx, "openai-response", model, []byte(`{"stream":true}`), "") + for range data { + } + for range errs { + } + select { + case completion := <-completions: + if completion.Outcome != pluginapi.RequestCompletionFailed || completion.StatusCode != http.StatusBadGateway || !strings.Contains(completion.Error, "invalid SSE data JSON") { + t.Fatalf("concrete failure replaced by delivery cleanup: %+v", completion) + } + case <-time.After(5 * time.Second): + t.Fatal("missing lifecycle completion") + } +} diff --git a/sdk/api/handlers/model_execution.go b/sdk/api/handlers/model_execution.go index daf1f53e60c..3c690550724 100644 --- a/sdk/api/handlers/model_execution.go +++ b/sdk/api/handlers/model_execution.go @@ -7,6 +7,7 @@ import ( "strings" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" "github.com/router-for-me/CLIProxyAPI/v8/sdk/proxyutil" "golang.org/x/net/context" ) @@ -105,6 +106,7 @@ func (e *ModelExecutionStreamError) Error() string { // for the nested model execution while other plugins may still run. func (h *BaseAPIHandler) ExecuteModel(ctx context.Context, req ModelExecutionRequest) (ModelExecutionResponse, *interfaces.ErrorMessage) { markNestedExecution(ctx) + ctx = usage.WithoutStreamDelivery(ctx) if req.Stream { return ModelExecutionResponse{}, modelExecutionModeError("ExecuteModel requires Stream=false") } @@ -141,6 +143,7 @@ func (h *BaseAPIHandler) ExecuteModel(ctx context.Context, req ModelExecutionReq // for the nested model execution while other plugins may still run. func (h *BaseAPIHandler) ExecuteModelStream(ctx context.Context, req ModelExecutionRequest) (ModelExecutionStream, *interfaces.ErrorMessage) { markNestedExecution(ctx) + ctx = usage.WithoutStreamDelivery(ctx) if !req.Stream { return ModelExecutionStream{}, modelExecutionModeError("ExecuteModelStream requires Stream=true") } diff --git a/sdk/api/handlers/model_execution_delivery_test.go b/sdk/api/handlers/model_execution_delivery_test.go new file mode 100644 index 00000000000..4724a06f572 --- /dev/null +++ b/sdk/api/handlers/model_execution_delivery_test.go @@ -0,0 +1,67 @@ +package handlers + +import ( + "context" + "testing" + + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + coreexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" + sdkconfig "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" +) + +func TestInternalModelExecutionIsolatesDelivery(t *testing.T) { + for _, stream := range []bool{false, true} { + name := "nonstream" + if stream { + name = "stream" + } + t.Run(name, func(t *testing.T) { + parent, cancel := context.WithCancel(context.Background()) + defer cancel() + outer, finish := usage.WithStreamDelivery(parent) + defer finish(context.Canceled) + seen := make(chan context.Context, 1) + executor := &modelExecutionCaptureExecutor{ + execute: func(ctx context.Context, _ *coreauth.Auth, _ coreexecutor.Request, _ coreexecutor.Options) (coreexecutor.Response, error) { + seen <- ctx + return coreexecutor.Response{Payload: []byte(`{"ok":true}`)}, nil + }, + stream: func(ctx context.Context, _ *coreauth.Auth, _ coreexecutor.Request, _ coreexecutor.Options) (*coreexecutor.StreamResult, error) { + seen <- ctx + chunks := make(chan coreexecutor.StreamChunk, 1) + chunks <- coreexecutor.StreamChunk{Payload: []byte("data: {\"ok\":true}\n\n")} + close(chunks) + return &coreexecutor.StreamResult{Chunks: chunks}, nil + }, + } + h := newModelExecutionHandler(t, "nested-delivery-model", executor, &sdkconfig.SDKConfig{}) + req := ModelExecutionRequest{Model: "nested-delivery-model", EntryProtocol: "openai", Stream: stream, Body: []byte(`{"model":"nested-delivery-model"}`)} + if stream { + result, errMsg := h.ExecuteModelStream(outer, req) + if errMsg != nil { + t.Fatal(errMsg) + } + for range result.Chunks { + } + } else { + if _, errMsg := h.ExecuteModel(outer, req); errMsg != nil { + t.Fatal(errMsg) + } + } + ctx := <-seen + if usage.StreamDeliveryTracked(ctx) { + t.Fatal("internal execution inherited HTTP acknowledgment") + } + stop := usage.SupportStreamDelivery(ctx) + defer stop() + if usage.StreamDeliverySupported(outer) { + t.Error("nested support escaped to HTTP consumer") + } + cancel() + if ctx.Err() != context.Canceled { + t.Error("internal execution lost caller cancellation") + } + }) + } +} diff --git a/sdk/api/handlers/openai/issue6332_review7_test.go b/sdk/api/handlers/openai/issue6332_review7_test.go new file mode 100644 index 00000000000..5aefd6711de --- /dev/null +++ b/sdk/api/handlers/openai/issue6332_review7_test.go @@ -0,0 +1,268 @@ +package openai + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/router-for-me/CLIProxyAPI/v8/internal/cache" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + runtimeexecutor "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" + sdkconfig "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginapi" + "github.com/tidwall/sjson" +) + +const issue6332ReviewModel = "gemini-3.7-flash" + +func issue6332ToolFrame() string { + return `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"functionCall":{"id":"native-call","name":"lookup","args":{"key":"value"}},"thoughtSignature":"` + strings.Repeat("s", 128) + `"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":11,"candidatesTokenCount":22,"totalTokenCount":33}}}` + "\n\n" +} + +func issue6332ReviewBase(t *testing.T, url string) (*handlers.BaseAPIHandler, *cliproxyauth.Manager) { + t.Helper() + manager := cliproxyauth.NewManager(nil, nil, nil) + manager.RegisterExecutor(runtimeexecutor.NewAntigravityExecutor(&config.Config{})) + auth := &cliproxyauth.Auth{ID: t.Name(), Provider: "antigravity", Status: cliproxyauth.StatusActive, Metadata: map[string]any{"access_token": "token", "expired": time.Now().Add(time.Hour).Format(time.RFC3339), "project_id": "project"}, Attributes: map[string]string{"base_url": url}} + if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil { + t.Fatal(errRegister) + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, auth.Provider, []*registry.ModelInfo{{ID: issue6332ReviewModel}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(auth.ID) }) + return handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, manager), manager +} + +func issue6332ReviewBody(t *testing.T) []byte { + return []byte(`{"model":"` + issue6332ReviewModel + `","stream":true,"metadata":{"session_id":"` + t.Name() + `"},"input":[{"role":"user","content":"hello"}]}`) +} + +func issue6332ReviewNested(ctx context.Context, base *handlers.BaseAPIHandler, body []byte) error { + stream, errExecute := base.ExecuteModelStream(ctx, handlers.ModelExecutionRequest{EntryProtocol: "openai-response", ExitProtocol: "openai-response", Model: issue6332ReviewModel, Stream: true, Body: body}) + if errExecute != nil { + return errExecute.Error + } + for chunk := range stream.Chunks { + if chunk.Err != nil { + return chunk.Err + } + } + return ctx.Err() +} + +type issue6332PeerHost struct { + handlers.PluginInterceptorHost + base *handlers.BaseAPIHandler + arrived sync.WaitGroup + finished sync.WaitGroup + results chan error +} + +func (*issue6332PeerHost) HasRequestInterceptors() bool { return false } +func (*issue6332PeerHost) HasStreamInterceptors() bool { return true } +func (*issue6332PeerHost) CompleteRequest(context.Context, pluginapi.RequestCompletion) {} +func (h *issue6332PeerHost) InterceptStreamChunk(ctx context.Context, req pluginapi.StreamChunkInterceptRequest) pluginapi.StreamChunkInterceptResponse { + if !strings.Contains(string(req.Body), "response.completed") || req.Metadata["source"] == "plugin_host_model_callback" { + return pluginapi.StreamChunkInterceptResponse{} + } + h.arrived.Done() + h.arrived.Wait() + // Both independent terminal interceptors are now active, before either delivery. + nested, cancel := context.WithTimeout(ctx, time.Second) + defer cancel() + h.results <- issue6332ReviewNested(nested, h.base, req.RequestBody) + h.finished.Done() + h.finished.Wait() + return pluginapi.StreamChunkInterceptResponse{} +} + +func TestIssue6332Review7ConcurrentTerminalInterceptors(t *testing.T) { + var requests atomic.Int32 + var initial sync.WaitGroup + initial.Add(2) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if requests.Add(1) <= 2 { + // Both outer requests must pass their initial replay read before responding. + initial.Done() + initial.Wait() + } + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, issue6332ToolFrame()) + })) + defer server.Close() + base, _ := issue6332ReviewBase(t, server.URL) + host := &issue6332PeerHost{base: base, results: make(chan error, 2)} + host.arrived.Add(2) + host.finished.Add(2) + base.SetPluginHost(host) + router := gin.New() + router.POST("/v1/responses", NewOpenAIResponsesAPIHandler(base).Responses) + var done sync.WaitGroup + for range 2 { + done.Add(1) + go func() { + defer done.Done() + writer := httptest.NewRecorder() + router.ServeHTTP(writer, httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(string(issue6332ReviewBody(t))))) + if !strings.Contains(writer.Body.String(), "response.completed") { + t.Errorf("outer completion missing: %s", writer.Body.String()) + } + }() + } + done.Wait() + for range 2 { + if errNested := <-host.results; errNested != nil { + t.Errorf("same-session peer terminal interceptor deadlocked: %v", errNested) + } + } +} + +type issue6332GatedBody struct { + io.Reader + release <-chan struct{} + closed chan struct{} +} + +func (b *issue6332GatedBody) Read(p []byte) (int, error) { + n, errRead := b.Reader.Read(p) + if errRead == io.EOF { + <-b.release + } + return n, errRead +} +func (b *issue6332GatedBody) Close() error { close(b.closed); return nil } + +type issue6332LifecycleTransport struct { + calls atomic.Int32 + release <-chan struct{} + closed chan struct{} + requests chan []byte + firstFrame string +} + +func (rt *issue6332LifecycleTransport) RoundTripperFor(*cliproxyauth.Auth) http.RoundTripper { + return rt +} +func (rt *issue6332LifecycleTransport) RoundTrip(r *http.Request) (*http.Response, error) { + body, errRead := io.ReadAll(r.Body) + if errRead != nil { + return nil, errRead + } + rt.requests <- body + var response io.ReadCloser = io.NopCloser(strings.NewReader(issue6332ToolFrame())) + if rt.calls.Add(1) == 1 { + response = &issue6332GatedBody{Reader: strings.NewReader(rt.firstFrame), release: rt.release, closed: rt.closed} + } + return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": {"text/event-stream"}}, Body: response, Request: r}, nil +} + +type issue6332CallbackHost struct { + handlers.PluginInterceptorHost + base *handlers.BaseAPIHandler + body []byte + result chan error +} + +func (*issue6332CallbackHost) HasRequestInterceptors() bool { return false } +func (*issue6332CallbackHost) HasStreamInterceptors() bool { return false } +func (h *issue6332CallbackHost) CompleteRequest(ctx context.Context, c pluginapi.RequestCompletion) { + if c.Metadata["source"] == "plugin_host_model_callback" { + return + } + if c.Outcome != pluginapi.RequestCompletionSucceeded { + h.result <- fmt.Errorf("outer lifecycle failed: %+v", c) + return + } + // A lifecycle callback starts a new turn without waiting for usage or upstream cleanup. + nested, cancel := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second) + defer cancel() + h.result <- issue6332ReviewNested(nested, h.base, h.body) +} + +func TestIssue6332Review7LifecycleNextTurn(t *testing.T) { + for _, split := range []bool{false, true} { + t.Run(fmt.Sprintf("split_signature_%v", split), func(t *testing.T) { + testIssue6332LifecycleNextTurn(t, split) + }) + } +} + +func testIssue6332LifecycleNextTurn(t *testing.T, split bool) { + base, manager := issue6332ReviewBase(t, "http://upstream.invalid") + release := make(chan struct{}) + var once sync.Once + unblock := func() { once.Do(func() { close(release) }) } + defer unblock() + rt := &issue6332LifecycleTransport{release: release, closed: make(chan struct{}), requests: make(chan []byte, 2)} + rt.firstFrame = issue6332ToolFrame() + if split { + // A finishReason alone is not the replay boundary: signature and usage follow. + rt.firstFrame = `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"functionCall":{"id":"native-call","name":"lookup","args":{"key":"value"}}}]},"finishReason":"STOP"}]}}` + "\n\n" + + `data: {"response":{"candidates":[{"content":{"parts":[{"text":"","thoughtSignature":"` + strings.Repeat("s", 128) + `"}]}}]}}` + "\n\n" + + `data: {"response":{"usageMetadata":{"promptTokenCount":11,"candidatesTokenCount":22,"totalTokenCount":33}}}` + "\n\n" + } + manager.SetRoundTripperProvider(rt) + body := issue6332ReviewBody(t) + second, _ := sjson.SetBytes(body, "input.-1", map[string]any{"type": "function_call", "call_id": "native-call", "name": "lookup", "arguments": `{"key":"value"}`}) + second, _ = sjson.SetBytes(second, "input.-1", map[string]any{"type": "function_call_output", "call_id": "native-call", "output": "found"}) + host := &issue6332CallbackHost{base: base, body: second, result: make(chan error, 1)} + base.SetPluginHost(host) + capture := &issue6332Capture{records: make(chan usage.Record, 4), authID: t.Name()} + usage.RegisterNamedPlugin(t.Name(), capture) + t.Cleanup(func() { usage.RegisterNamedPlugin(t.Name(), responsesUsageNop{}) }) + router := gin.New() + router.POST("/v1/responses", NewOpenAIResponsesAPIHandler(base).Responses) + writer := httptest.NewRecorder() + router.ServeHTTP(writer, httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(string(body)))) + select { + case errNested := <-host.result: + if errNested != nil { + t.Fatal(errNested) + } + case <-time.After(5 * time.Second): + t.Fatal("lifecycle next turn blocked") + } + <-rt.requests + secondRequest := <-rt.requests + if !strings.Contains(string(secondRequest), strings.Repeat("s", 128)) { + t.Errorf("lifecycle next turn read stale replay ledger: %s", secondRequest) + } + unblock() + <-rt.closed + // Join both producers only after the next-turn assertion. + for range 2 { + <-capture.records + } + cache.ClearAntigravityReasoningReplayCache() +} + +func TestIssue6332Review7PartialEOFDoesNotCommitReplay(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, strings.Replace(issue6332ToolFrame(), `,"finishReason":"STOP"`, "", 1)) + })) + defer server.Close() + base, _ := issue6332ReviewBase(t, server.URL) + router := gin.New() + router.POST("/v1/responses", NewOpenAIResponsesAPIHandler(base).Responses) + writer := httptest.NewRecorder() + router.ServeHTTP(writer, httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(string(issue6332ReviewBody(t))))) + if !strings.Contains(writer.Body.String(), "response.completed") { + t.Fatalf("expected synthetic EOF completion: %s", writer.Body.String()) + } + items, ok := cache.GetAntigravityReasoningReplayItems(issue6332ReviewModel, "responses:"+t.Name()) + if ok || len(items) != 0 { + t.Fatal("synthetic completion committed partial upstream output without finishReason") + } +} diff --git a/sdk/api/handlers/openai/issue6332_test.go b/sdk/api/handlers/openai/issue6332_test.go new file mode 100644 index 00000000000..da0bc43c3a8 --- /dev/null +++ b/sdk/api/handlers/openai/issue6332_test.go @@ -0,0 +1,548 @@ +package openai + +import ( + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/router-for-me/CLIProxyAPI/v8/internal/api/middleware" + "github.com/router-for-me/CLIProxyAPI/v8/internal/cache" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/logging" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + runtimeexecutor "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor" + _ "github.com/router-for-me/CLIProxyAPI/v8/internal/translator" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" + sdkconfig "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginapi" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +type issue6332Capture struct { + records chan usage.Record + authID string +} + +func (p *issue6332Capture) HandleUsage(_ context.Context, r usage.Record) { + if r.AuthID == p.authID { + p.records <- r + } +} + +type issue6332LifecycleHost struct { + handlers.PluginInterceptorHost + completions chan pluginapi.RequestCompletion +} + +func (*issue6332LifecycleHost) HasRequestInterceptors() bool { return false } +func (*issue6332LifecycleHost) HasStreamInterceptors() bool { return false } +func (h *issue6332LifecycleHost) CompleteRequest(_ context.Context, completion pluginapi.RequestCompletion) { + h.completions <- completion +} + +type issue6332Writer struct { + *httptest.ResponseRecorder + cancel context.CancelFunc + event string + failWrite bool + shortWrite bool + failFlush bool +} + +func (w *issue6332Writer) Write(p []byte) (int, error) { + if w.failWrite && strings.Contains(string(p), w.event) { + if w.shortWrite { + return len(p) - 1, nil + } + return 0, io.ErrClosedPipe + } + return w.ResponseRecorder.Write(p) +} +func (w *issue6332Writer) Flush() { + w.ResponseRecorder.Flush() + if strings.Contains(w.Body.String(), w.event) { + w.cancel() + } +} + +func (w *issue6332Writer) FlushError() error { + w.Flush() + if w.failFlush && strings.Contains(w.Body.String(), w.event) { + return io.ErrClosedPipe + } + return nil +} + +func TestIssue6332AntigravityResponsesDelivery(t *testing.T) { + for _, tc := range []struct { + name string + early, failWrite, split, readFailure bool + cleanEOF, noCancel, initialFailure, shortWrite, failFlush bool + }{ + {name: "completed"}, {name: "split_usage", split: true}, + {name: "cancel_before_completion", early: true}, {name: "completion_write_failure", failWrite: true}, + {name: "clean_eof", cleanEOF: true}, {name: "completed_without_client_cancel", noCancel: true}, + {name: "initial_write_failure", failWrite: true, initialFailure: true}, + {name: "completion_short_write", failWrite: true, shortWrite: true}, + {name: "completion_flush_failure", failFlush: true}, + {name: "upstream_read_failure", readFailure: true, noCancel: true}, + } { + t.Run(tc.name, func(t *testing.T) { + capture := &issue6332Capture{records: make(chan usage.Record, 8), authID: t.Name()} + usage.RegisterNamedPlugin(t.Name(), capture) + t.Cleanup(func() { usage.RegisterNamedPlugin(t.Name(), responsesUsageNop{}) }) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + finish := `,"finishReason":"STOP"` + if tc.readFailure { + w.Header().Set("Content-Length", "100000") + } + if tc.early || tc.split || tc.readFailure { + finish = "" + } + _, _ = io.WriteString(w, `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"hello"}]}`+finish+`}],"usageMetadata":{"promptTokenCount":11,"candidatesTokenCount":22,"totalTokenCount":33},"responseId":"resp-test"}}`+"\n\n") + if tc.split { + _, _ = io.WriteString(w, "data: {\"response\":{\"candidates\":[{\"finishReason\":\"STOP\"}]},\"traceId\":\"issue6332\"}\n\n") + _, _ = io.WriteString(w, "data: {\"response\":{\"usageMetadata\":{\"promptTokenCount\":11,\"candidatesTokenCount\":22,\"totalTokenCount\":33}},\"traceId\":\"issue6332\"}\n\n") + } + w.(http.Flusher).Flush() + if !tc.cleanEOF && !tc.readFailure { + <-r.Context().Done() + } + })) + defer server.Close() + manager := cliproxyauth.NewManager(nil, nil, nil) + manager.RegisterExecutor(runtimeexecutor.NewAntigravityExecutor(&config.Config{})) + auth := &cliproxyauth.Auth{ + ID: t.Name(), Provider: "antigravity", Status: cliproxyauth.StatusActive, ProxyURL: "direct", + Metadata: map[string]any{"access_token": "token", "expired": time.Now().Add(time.Hour).Format(time.RFC3339), "project_id": "project"}, Attributes: map[string]string{"base_url": server.URL}, + } + if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil { + t.Fatal(errRegister) + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, auth.Provider, []*registry.ModelInfo{{ID: "gemini-3.7-flash"}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(auth.ID) }) + base := handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, manager) + completions := make(chan pluginapi.RequestCompletion, 2) + base.SetPluginHost(&issue6332LifecycleHost{completions: completions}) + h := NewOpenAIResponsesAPIHandler(base) + requestCtx, cancel := context.WithCancel(context.Background()) + defer cancel() + event := "response.completed" + if tc.early { + event = "response.output_text.delta" + } + if tc.initialFailure { + event = "response.created" + } + clientCancel := cancel + if tc.noCancel { + clientCancel = func() {} + } + writer := &issue6332Writer{ResponseRecorder: httptest.NewRecorder(), cancel: clientCancel, event: event, failWrite: tc.failWrite, shortWrite: tc.shortWrite, failFlush: tc.failFlush} + router := gin.New() + router.Use(logging.CPATraceIDMiddleware(), middleware.RequestLoggingMiddleware(logging.NewFileRequestLogger(true, t.TempDir(), "", 0))) + router.POST("/backend-api/codex/responses", h.Responses) + request := httptest.NewRequest(http.MethodPost, "/backend-api/codex/responses", strings.NewReader(`{"model":"gemini-3.7-flash","input":"hello","stream":true}`)).WithContext(requestCtx) + router.ServeHTTP(writer, request) + select { + case completion := <-completions: + wantOutcome := pluginapi.RequestCompletionSucceeded + wantError := "" + if tc.early { + wantOutcome = pluginapi.RequestCompletionCanceled + wantError = context.Canceled.Error() + } else if tc.failWrite || tc.failFlush || tc.readFailure { + wantOutcome = pluginapi.RequestCompletionFailed + wantError = io.ErrClosedPipe.Error() + if tc.shortWrite { + wantError = io.ErrShortWrite.Error() + } + if tc.readFailure { + wantError = io.ErrUnexpectedEOF.Error() + } + } + if completion.Outcome != wantOutcome || !strings.Contains(completion.Error, wantError) || (wantError == "" && completion.Error != "") { + t.Errorf("lifecycle = %+v, want outcome=%s error=%q", completion, wantOutcome, wantError) + } + if wantOutcome == pluginapi.RequestCompletionSucceeded && completion.StatusCode != http.StatusOK { + t.Errorf("successful lifecycle status = %d, want 200", completion.StatusCode) + } + if tc.early && completion.StatusCode != 0 { + t.Errorf("canceled lifecycle status = %d", completion.StatusCode) + } + case <-time.After(5 * time.Second): + t.Fatal("lifecycle completion not published") + } + if tc.noCancel && requestCtx.Err() != nil { + t.Error("client context unexpectedly canceled") + } + select { + case record := <-capture.records: + wantFailed := tc.early || tc.failWrite || tc.failFlush || tc.readFailure + if record.Failed != wantFailed { + t.Errorf("failed = %v, want %v; failure=%+v", record.Failed, wantFailed, record.Fail) + } + if record.Detail.InputTokens != 11 || record.Detail.OutputTokens != 22 || record.Detail.TotalTokens != 33 { + t.Errorf("usage = %+v, want 11/22/33", record.Detail) + } + if !wantFailed && !strings.Contains(writer.Body.String(), "response.completed") { + t.Error("completion not delivered") + } + if !wantFailed && record.Fail.StatusCode != 0 { + t.Errorf("success has failure status: %+v", record.Fail) + } + if tc.failWrite && record.Fail.Body == "context canceled" { + t.Error("write error replaced by cancellation") + } + case <-time.After(5 * time.Second): + t.Fatal("usage record not published") + } + }) + } +} + +func TestIssue6332PendingCompletionWriteFailure(t *testing.T) { + h := NewOpenAIResponsesAPIHandler(handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, nil)) + writer := &issue6332Writer{ResponseRecorder: httptest.NewRecorder(), cancel: func() {}, event: "response.completed", failWrite: true} + c, _ := gin.CreateTestContext(writer) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + data := make(chan []byte, 1) + data <- []byte(`data: {"type":"response.completed"}`) + close(data) + var outcome error + h.forwardResponsesStream(c, c.Writer, func(err error) { outcome = err }, data, nil, nil) + if outcome == nil { + t.Fatal("buffered completion write failure was reported as success") + } +} + +func TestIssue6332MiddlewareFlushError(t *testing.T) { + for _, requestLogging := range []bool{false, true} { + name := "trace" + if requestLogging { + name = "trace_and_request_log" + } + t.Run(name, func(t *testing.T) { + router := gin.New() + router.Use(func(c *gin.Context) { logging.SetGinRequestID(c, "6332"); c.Next() }) + router.Use(logging.CPATraceIDMiddleware()) + logsDir := t.TempDir() + if requestLogging { + router.Use(middleware.RequestLoggingMiddleware(logging.NewFileRequestLogger(true, logsDir, "", 0))) + } + router.POST("/v1/responses", func(c *gin.Context) { + logging.SetGinCPATraceID(c, "test-auth") + c.Header("Content-Type", "text/event-stream") + // Flush before the first write must still commit Gin status and trace headers. + if errFlush := flushResponsesSSE(c.Writer); !errors.Is(errFlush, io.ErrClosedPipe) { + t.Errorf("middleware flush error = %v, want closed pipe", errFlush) + } + if !c.Writer.Written() { + t.Error("flush did not commit Gin headers") + } + _, _ = c.Writer.Write([]byte("data: logged-response\n\n")) + }) + writer := &issue6332Writer{ResponseRecorder: httptest.NewRecorder(), cancel: func() {}, failFlush: true} + router.ServeHTTP(writer, httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(`{"stream":true}`))) + if writer.Result().Header.Get(logging.CPATraceIDHeader) == "" { + t.Error("flush skipped trace header behavior") + } + if requestLogging { + files, errReadDir := os.ReadDir(logsDir) + if errReadDir != nil { + t.Fatal(errReadDir) + } + found := false + for _, file := range files { + data, errReadFile := os.ReadFile(filepath.Join(logsDir, file.Name())) + if errReadFile != nil { + t.Fatal(errReadFile) + } + found = found || strings.Contains(string(data), "logged-response") + } + if !found { + t.Error("middleware did not capture response body") + } + } + }) + } +} + +func TestIssue6332ReasoningReplayTwoTurns(t *testing.T) { + for _, mode := range []string{"held_open", "client_cancel", "clean_eof", "flush_failure"} { + t.Run(mode, func(t *testing.T) { + const model = "gemini-3.7-flash" + signature := strings.Repeat("s", 128) + session := t.Name() + cache.ClearAntigravityReasoningReplayCache() + t.Cleanup(cache.ClearAntigravityReasoningReplayCache) + capture := &issue6332Capture{records: make(chan usage.Record, 8), authID: t.Name()} + usage.RegisterNamedPlugin(t.Name(), capture) + t.Cleanup(func() { usage.RegisterNamedPlugin(t.Name(), responsesUsageNop{}) }) + requests := make(chan []byte, 2) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, errRead := io.ReadAll(r.Body) + if errRead != nil { + t.Error(errRead) + return + } + requests <- body + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"functionCall":{"id":"native-call","name":"lookup","args":{"key":"value"}},"thoughtSignature":"`+signature+`"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":11,"candidatesTokenCount":22,"totalTokenCount":33},"responseId":"resp-replay"}}`+"\n\n") + w.(http.Flusher).Flush() + if mode != "clean_eof" { + <-r.Context().Done() + } + })) + defer server.Close() + manager := cliproxyauth.NewManager(nil, nil, nil) + manager.RegisterExecutor(runtimeexecutor.NewAntigravityExecutor(&config.Config{})) + auth := &cliproxyauth.Auth{ID: t.Name(), Provider: "antigravity", Status: cliproxyauth.StatusActive, ProxyURL: "direct", Metadata: map[string]any{"access_token": "token", "expired": time.Now().Add(time.Hour).Format(time.RFC3339), "project_id": "project"}, Attributes: map[string]string{"base_url": server.URL}} + if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil { + t.Fatal(errRegister) + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, auth.Provider, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(auth.ID) }) + h := NewOpenAIResponsesAPIHandler(handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, manager)) + router := gin.New() + router.Use(logging.CPATraceIDMiddleware(), middleware.RequestLoggingMiddleware(logging.NewFileRequestLogger(true, t.TempDir(), "", 0))) + router.POST("/v1/responses", h.Responses) + call := func(payload string) string { + t.Helper() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + clientCancel := func() {} + if mode == "client_cancel" { + clientCancel = cancel + } + writer := &issue6332Writer{ResponseRecorder: httptest.NewRecorder(), cancel: clientCancel, event: "response.completed", failFlush: mode == "flush_failure"} + request := httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(payload)).WithContext(ctx) + request.Header.Set("Session-Id", session) + router.ServeHTTP(writer, request) + select { + case record := <-capture.records: + if record.Failed != (mode == "flush_failure") { + t.Errorf("unexpected delivery outcome: %+v", record) + } + if mode == "flush_failure" && !strings.Contains(record.Fail.Body, io.ErrClosedPipe.Error()) { + t.Errorf("flush error not preserved: %+v", record.Fail) + } + case <-time.After(5 * time.Second): + t.Fatal("usage not published") + } + return writer.Body.String() + } + first := `{"model":"gemini-3.7-flash","input":[{"role":"user","content":"hello"}],"stream":true,"tools":[{"type":"function","name":"lookup","parameters":{"type":"object","properties":{"key":{"type":"string"}}}}]}` + downstream := call(first) + <-requests + items, ok := cache.GetAntigravityReasoningReplayItems(model, "responses:"+session) + + if !ok || len(items) == 0 { + t.Error("complete upstream output did not commit reasoning replay") + } + var functionCall gjson.Result + for _, line := range strings.Split(downstream, "\n") { + if !strings.HasPrefix(line, "data:") { + continue + } + event := gjson.Parse(strings.TrimSpace(strings.TrimPrefix(line, "data:"))) + if event.Get("type").String() == "response.completed" { + for _, item := range event.Get("response.output").Array() { + if item.Get("type").String() == "function_call" { + functionCall = item + } + } + } + } + if !functionCall.Exists() { + t.Fatalf("no completed tool call: %s", downstream) + } + // Deliberately omit encrypted reasoning: restoration must come from the session ledger. + second, _ := sjson.Set(first, "input.-1", map[string]any{"type": "function_call", "call_id": functionCall.Get("call_id").String(), "name": "lookup", "arguments": `{"key":"value"}`}) + second, _ = sjson.Set(second, "input.-1", map[string]any{"type": "function_call_output", "call_id": functionCall.Get("call_id").String(), "output": "found"}) + call(second) + upstream := <-requests + restored := false + for _, content := range gjson.GetBytes(upstream, "request.contents").Array() { + for _, part := range content.Get("parts").Array() { + if part.Get("functionCall.name").String() == "lookup" && part.Get("thoughtSignature").String() == signature { + restored = true + } + } + } + if !restored { + t.Errorf("second turn lost tool-call signature: %s", upstream) + } + }) + } +} + +func TestIssue6332NativeGeminiCompletedWithoutEOF(t *testing.T) { + capture := &issue6332Capture{records: make(chan usage.Record, 8), authID: t.Name()} + usage.RegisterNamedPlugin(t.Name(), capture) + t.Cleanup(func() { usage.RegisterNamedPlugin(t.Name(), responsesUsageNop{}) }) + release := make(chan struct{}, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, `data: {"candidates":[{"content":{"role":"model","parts":[{"text":"hello"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":11,"candidatesTokenCount":22,"totalTokenCount":33},"responseId":"native"}`+"\n\n") + w.(http.Flusher).Flush() + select { + case <-release: + case <-r.Context().Done(): + } + })) + defer server.Close() + defer close(release) + manager := cliproxyauth.NewManager(nil, nil, nil) + manager.RegisterExecutor(runtimeexecutor.NewGeminiExecutor(&config.Config{})) + auth := &cliproxyauth.Auth{ID: t.Name(), Provider: "gemini", Status: cliproxyauth.StatusActive, ProxyURL: "direct", Attributes: map[string]string{"api_key": "token", "base_url": server.URL}} + if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil { + t.Fatal(errRegister) + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, auth.Provider, []*registry.ModelInfo{{ID: "gemini-3.7-flash"}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(auth.ID) }) + router := gin.New() + router.POST("/v1/responses", NewOpenAIResponsesAPIHandler(handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, manager)).Responses) + completed := make(chan struct{}, 1) + writer := &issue6332Writer{ResponseRecorder: httptest.NewRecorder(), event: "response.completed", cancel: func() { + select { + case completed <- struct{}{}: + default: + } + }} + done := make(chan struct{}) + go func() { + router.ServeHTTP(writer, httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(`{"model":"gemini-3.7-flash","input":"hello","stream":true}`))) + close(done) + }() + select { + case <-completed: + case <-time.After(5 * time.Second): + t.Fatal("completion not delivered") + } + // The unsupported executor must retain its EOF lifecycle, not be cancelled by completion. + select { + case <-done: + t.Error("native Gemini cancelled before EOF without client cancellation") + case <-time.After(100 * time.Millisecond): + } + release <- struct{}{} + <-done + select { + case record := <-capture.records: + if record.Failed || record.Detail.InputTokens != 11 || record.Detail.OutputTokens != 22 || record.Detail.TotalTokens != 33 { + t.Errorf("native Gemini outcome = %+v", record) + } + case <-time.After(5 * time.Second): + t.Fatal("usage not published") + } +} + +type issue6332ReentrantHost struct { + handlers.PluginInterceptorHost + base *handlers.BaseAPIHandler + stream bool + result chan error +} + +func (*issue6332ReentrantHost) HasRequestInterceptors() bool { return false } +func (*issue6332ReentrantHost) HasStreamInterceptors() bool { return true } +func (*issue6332ReentrantHost) InterceptResponse(context.Context, pluginapi.ResponseInterceptRequest) pluginapi.ResponseInterceptResponse { + return pluginapi.ResponseInterceptResponse{} +} +func (*issue6332ReentrantHost) CompleteRequest(context.Context, pluginapi.RequestCompletion) {} +func (h *issue6332ReentrantHost) InterceptStreamChunk(ctx context.Context, req pluginapi.StreamChunkInterceptRequest) pluginapi.StreamChunkInterceptResponse { + if !strings.Contains(string(req.Body), "response.completed") || req.Metadata["source"] == "plugin_host_model_callback" { + return pluginapi.StreamChunkInterceptResponse{} + } + // Bound the regression failure while keeping the outer acknowledgment pending. + nested, cancel := context.WithTimeout(ctx, time.Second) + defer cancel() + request := handlers.ModelExecutionRequest{EntryProtocol: "openai-response", ExitProtocol: "openai-response", Model: req.Model, Stream: h.stream, Body: req.RequestBody} + var result error + if h.stream { + stream, errExecute := h.base.ExecuteModelStream(nested, request) + if errExecute != nil { + result = errExecute.Error + } else { + for chunk := range stream.Chunks { + if chunk.Err != nil { + result = chunk.Err + } + } + } + } else { + _, errExecute := h.base.ExecuteModel(nested, request) + if errExecute != nil { + result = errExecute.Error + } + } + if nested.Err() != nil { + result = nested.Err() + } + h.result <- result + return pluginapi.StreamChunkInterceptResponse{} +} + +func TestIssue6332HTTPReentrantReplayDelivery(t *testing.T) { + for _, mode := range []string{"sync", "stream"} { + t.Run(mode, func(t *testing.T) { + const model = "gemini-3.7-flash" + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"hello"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":11,"candidatesTokenCount":22,"totalTokenCount":33}}}`+"\n\n") + })) + defer server.Close() + manager := cliproxyauth.NewManager(nil, nil, nil) + manager.RegisterExecutor(runtimeexecutor.NewAntigravityExecutor(&config.Config{})) + auth := &cliproxyauth.Auth{ID: t.Name(), Provider: "antigravity", Status: cliproxyauth.StatusActive, ProxyURL: "direct", Metadata: map[string]any{"access_token": "token", "expired": time.Now().Add(time.Hour).Format(time.RFC3339), "project_id": "project"}, Attributes: map[string]string{"base_url": server.URL}} + if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil { + t.Fatal(errRegister) + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, auth.Provider, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(auth.ID) }) + base := handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, manager) + host := &issue6332ReentrantHost{base: base, stream: mode == "stream", result: make(chan error, 4)} + base.SetPluginHost(host) + router := gin.New() + router.POST("/v1/responses", NewOpenAIResponsesAPIHandler(base).Responses) + httpServer := httptest.NewServer(router) + defer httpServer.Close() + body := `{"model":"` + model + `","stream":true,"metadata":{"session_id":"` + t.Name() + `"},"input":[{"role":"user","content":"hello"}]}` + response, errPost := http.Post(httpServer.URL+"/v1/responses", "application/json", strings.NewReader(body)) + if errPost != nil { + t.Fatal(errPost) + } + output, errRead := io.ReadAll(response.Body) + if errClose := response.Body.Close(); errClose != nil { + t.Error(errClose) + } + if errRead != nil { + t.Fatal(errRead) + } + select { + case errResult := <-host.result: + if errResult != nil { + t.Fatalf("nested execution blocked on ancestor replay delivery: %v", errResult) + } + default: + t.Fatal("terminal interceptor did not execute") + } + if !strings.Contains(string(output), "response.completed") { + t.Fatalf("outer terminal missing: %s", output) + } + }) + } +} diff --git a/sdk/api/handlers/openai/openai_responses_handlers.go b/sdk/api/handlers/openai/openai_responses_handlers.go index 977aa6cf8c0..a07fffc70c4 100644 --- a/sdk/api/handlers/openai/openai_responses_handlers.go +++ b/sdk/api/handlers/openai/openai_responses_handlers.go @@ -20,22 +20,26 @@ import ( "github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v8/internal/client/codex/optimize-multi-agent-v2" . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" + "github.com/router-for-me/CLIProxyAPI/v8/internal/httpwire" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" "github.com/tidwall/gjson" "github.com/tidwall/sjson" ) -func writeResponsesSSEChunk(w io.Writer, chunk []byte) { +func writeResponsesSSEChunk(w io.Writer, chunk []byte) error { if w == nil || len(chunk) == 0 { - return + return nil } - if _, err := w.Write(chunk); err != nil { - return + if n, errWrite := w.Write(chunk); errWrite != nil { + return errWrite + } else if n != len(chunk) { + return io.ErrShortWrite } if bytes.HasSuffix(chunk, []byte("\n\n")) || bytes.HasSuffix(chunk, []byte("\r\n\r\n")) { - return + return nil } suffix := []byte("\n\n") if bytes.HasSuffix(chunk, []byte("\r\n")) { @@ -43,9 +47,17 @@ func writeResponsesSSEChunk(w io.Writer, chunk []byte) { } else if bytes.HasSuffix(chunk, []byte("\n")) { suffix = []byte("\n") } - if _, err := w.Write(suffix); err != nil { - return + if n, errWrite := w.Write(suffix); errWrite != nil { + return errWrite + } else if n != len(suffix) { + return io.ErrShortWrite } + return nil +} + +// flushResponsesSSE preserves middleware behavior and transport flush errors. +func flushResponsesSSE(w http.ResponseWriter) error { + return httpwire.FlushResponse(w) } type responsesSSEFramer struct { @@ -59,6 +71,8 @@ type responsesSSEFramer struct { failureEvent string isCodexClient bool dataFrames int + writeErr error + canComplete func() bool } func (f *responsesSSEFramer) WriteChunk(w io.Writer, chunk []byte) { @@ -117,7 +131,9 @@ func (f *responsesSSEFramer) Flush(w io.Writer) { } func (f *responsesSSEFramer) writeFrame(w io.Writer, frame []byte) { - writeResponsesSSEChunk(w, f.repairFrame(frame)) + if f.writeErr == nil { + f.writeErr = writeResponsesSSEChunk(w, f.repairFrame(frame)) + } } func (f *responsesSSEFramer) shouldFilterPrivateEvent(streamEvent, payloadType string) bool { @@ -702,7 +718,13 @@ func (h *OpenAIResponsesAPIHandler) handleStreamingResponse(c *gin.Context, rawJ // New core execution path modelName := gjson.GetBytes(rawJSON, "model").String() - cliCtx, cliCancel := h.GetContextWithCancel(h, c, context.Background()) + deliveryCtx, finishDelivery := usage.WithStreamDelivery(context.Background()) + defer finishDelivery(context.Canceled) + cliCtx, cancelExecution := h.GetContextWithCancel(h, c, deliveryCtx) + cliCancel := func(err error) { + finishDelivery(err) + cancelExecution(err) + } dataChan, upstreamHeaders, errChan := h.ExecuteStreamWithAuthManager(cliCtx, h.HandlerType(), modelName, rawJSON, "") setSSEHeaders := func() { @@ -716,7 +738,7 @@ func (h *OpenAIResponsesAPIHandler) handleStreamingResponse(c *gin.Context, rawJ if isCodexClient { failureEvent = "response.failed" } - framer := &responsesSSEFramer{failureEvent: failureEvent, isCodexClient: isCodexClient} + framer := &responsesSSEFramer{failureEvent: failureEvent, isCodexClient: isCodexClient, canComplete: func() bool { return usage.StreamDeliverySupported(cliCtx) }} var initialOutput bytes.Buffer // Peek at the first complete SSE data frame. @@ -739,8 +761,14 @@ func (h *OpenAIResponsesAPIHandler) handleStreamingResponse(c *gin.Context, rawJ if safeErrMsg != nil && framer.dataFrames > 0 { setSSEHeaders() handlers.WriteUpstreamHeaders(c.Writer.Header(), upstreamHeaders) - _, _ = c.Writer.Write(initialOutput.Bytes()) - flusher.Flush() + if errWrite := writeResponsesSSEChunk(c.Writer, initialOutput.Bytes()); errWrite != nil { + cliCancel(errWrite) + return + } + if errFlush := flushResponsesSSE(c.Writer); errFlush != nil { + cliCancel(errFlush) + return + } pendingErrors := make(chan *interfaces.ErrorMessage, 1) pendingErrors <- safeErrMsg close(pendingErrors) @@ -776,8 +804,14 @@ func (h *OpenAIResponsesAPIHandler) handleStreamingResponse(c *gin.Context, rawJ if framer.dataFrames > 0 { setSSEHeaders() handlers.WriteUpstreamHeaders(c.Writer.Header(), upstreamHeaders) - _, _ = c.Writer.Write(initialOutput.Bytes()) - flusher.Flush() + if errWrite := writeResponsesSSEChunk(c.Writer, initialOutput.Bytes()); errWrite != nil { + cliCancel(errWrite) + return + } + if errFlush := flushResponsesSSE(c.Writer); errFlush != nil { + cliCancel(errFlush) + return + } if framer.terminalError != nil { h.logResponsesStreamError(c, framer, framer.terminalError) cliCancel(framer.terminalError.Error) @@ -811,8 +845,14 @@ func (h *OpenAIResponsesAPIHandler) handleStreamingResponse(c *gin.Context, rawJ setSSEHeaders() handlers.WriteUpstreamHeaders(c.Writer.Header(), upstreamHeaders) - _, _ = c.Writer.Write(initialOutput.Bytes()) - flusher.Flush() + if errWrite := writeResponsesSSEChunk(c.Writer, initialOutput.Bytes()); errWrite != nil { + cliCancel(errWrite) + return + } + if errFlush := flushResponsesSSE(c.Writer); errFlush != nil { + cliCancel(errFlush) + return + } if framer.terminalError != nil { h.logResponsesStreamError(c, framer, framer.terminalError) cliCancel(framer.terminalError.Error) @@ -1017,6 +1057,18 @@ func (h *OpenAIResponsesAPIHandler) forwardResponsesStream(c *gin.Context, flush framer.failureEvent = "error" framer.isCodexClient = false } + // Initial frames have already been written and flushed by the caller. + if framer.writeErr != nil { + cancel(framer.writeErr) + return + } + if framer.canComplete != nil && framer.canComplete() && framer.terminalEvent == "response.completed" && framer.terminalError == nil { + if errMsg, pending := handlers.PendingStreamError(errs); pending { + h.logResponsesStreamError(c, framer, sanitizeResponsesStreamErrorMessage(errMsg)) + } + cancel(nil) + return + } writeTerminalError := func(errMsg *interfaces.ErrorMessage) { framer.Flush(c.Writer) if errMsg == nil { @@ -1049,10 +1101,17 @@ func (h *OpenAIResponsesAPIHandler) forwardResponsesStream(c *gin.Context, flush h.ForwardStream(c, flusher, cancel, data, errs, handlers.StreamForwardOptions{ NormalizeTerminalError: sanitizeResponsesStreamErrorMessage, + Flush: func() error { return flushResponsesSSE(c.Writer) }, WriteChunk: func(chunk []byte) { framer.WriteChunk(c.Writer, chunk) }, + ChunkDone: func() bool { + return framer.canComplete != nil && framer.canComplete() && framer.terminalEvent == "response.completed" && framer.writeErr == nil + }, ChunkError: func() *interfaces.ErrorMessage { + if framer.writeErr != nil { + return &interfaces.ErrorMessage{Error: framer.writeErr} + } if framer.terminalError != nil { h.logResponsesStreamError(c, framer, framer.terminalError) } @@ -1061,6 +1120,9 @@ func (h *OpenAIResponsesAPIHandler) forwardResponsesStream(c *gin.Context, flush WriteTerminalError: writeTerminalError, CloseError: func() *interfaces.ErrorMessage { framer.Flush(c.Writer) + if framer.writeErr != nil { + return &interfaces.ErrorMessage{Error: framer.writeErr} + } if framer.terminalError != nil { return framer.terminalError } diff --git a/sdk/api/handlers/openai/openai_responses_plugin_route_test.go b/sdk/api/handlers/openai/openai_responses_plugin_route_test.go index 2694343a6f6..3ea567126d8 100644 --- a/sdk/api/handlers/openai/openai_responses_plugin_route_test.go +++ b/sdk/api/handlers/openai/openai_responses_plugin_route_test.go @@ -85,13 +85,13 @@ func TestResponsesStreamTrueReachesPluginExecutorStream(t *testing.T) { } func TestResponsesWithoutStreamParsesPluginUsage(t *testing.T) { - plugin := &responsesUsageCapture{records: make(chan usage.Record, 4)} + plugin := &responsesUsageCapture{records: make(chan usage.Record, 4), model: "commandcode/deepseek/usage-test"} usage.RegisterNamedPlugin("test-responses-plugin-route-usage", plugin) t.Cleanup(func() { usage.RegisterNamedPlugin("test-responses-plugin-route-usage", responsesUsageNop{}) }) - handler, host, ctx := newResponsesPluginRouteContext(t, `{"model":"commandcode/deepseek/deepseek-v4.1-flash","input":[{"role":"user","type":"message","content":"Write me a poem"}]}`) + handler, host, ctx := newResponsesPluginRouteContext(t, `{"model":"commandcode/deepseek/usage-test","input":[{"role":"user","type":"message","content":"Write me a poem"}]}`) host.execPayload = []byte(`{"id":"resp_1","object":"response","service_tier":"default","usage":{"input_tokens":34,"output_tokens":499,"total_tokens":533}}`) handler.Responses(ctx) if host.executeCalls != 1 || host.streamCalls != 0 { @@ -119,10 +119,12 @@ func TestResponsesWithoutStreamParsesPluginUsage(t *testing.T) { type responsesUsageCapture struct { records chan usage.Record + model string } func (p *responsesUsageCapture) HandleUsage(_ context.Context, record usage.Record) { - if record.Provider != "commandcode" { + // A previous streaming request may publish after this test has started. + if record.Provider != "commandcode" || record.Model != p.model { return } select { diff --git a/sdk/api/handlers/stream_forwarder.go b/sdk/api/handlers/stream_forwarder.go index 7a8d2aaac8b..2b37b28b2fc 100644 --- a/sdk/api/handlers/stream_forwarder.go +++ b/sdk/api/handlers/stream_forwarder.go @@ -35,6 +35,12 @@ type StreamForwardOptions struct { // The failure is passed to cancel without writing another terminal payload. ChunkError func() *interfaces.ErrorMessage + // ChunkDone reports successful terminal delivery after WriteChunk and Flush. + ChunkDone func() bool + + // Flush optionally exposes transport flush errors hidden by http.Flusher. + Flush func() error + // NormalizeTerminalError optionally replaces an upstream error before it is // written or passed to cancel. NormalizeTerminalError func(errMsg *interfaces.ErrorMessage) *interfaces.ErrorMessage @@ -64,6 +70,18 @@ func (h *BaseAPIHandler) ForwardStream(c *gin.Context, flusher http.Flusher, can return } + flush := func() bool { + if opts.Flush != nil { + if errFlush := opts.Flush(); errFlush != nil { + cancel(errFlush) + return false + } + } else { + flusher.Flush() + } + return true + } + writeChunk := opts.WriteChunk if writeChunk == nil { writeChunk = func([]byte) {} @@ -112,19 +130,25 @@ func (h *BaseAPIHandler) ForwardStream(c *gin.Context, flusher http.Flusher, can if opts.WriteTerminalError != nil { opts.WriteTerminalError(terminalErr) } - flusher.Flush() + if !flush() { + return + } cancel(terminalErr.Error) return } if opts.WriteDone != nil { opts.WriteDone() } - flusher.Flush() + if !flush() { + return + } cancel(nil) return } writeChunk(chunk) - flusher.Flush() + if !flush() { + return + } if opts.ChunkError != nil { chunkErr := opts.ChunkError() if chunkErr != nil { @@ -139,6 +163,10 @@ func (h *BaseAPIHandler) ForwardStream(c *gin.Context, flusher http.Flusher, can return } } + if opts.ChunkDone != nil && opts.ChunkDone() { + cancel(nil) + return + } case errMsg, ok := <-errs: if !ok { errs = nil @@ -151,7 +179,9 @@ func (h *BaseAPIHandler) ForwardStream(c *gin.Context, flusher http.Flusher, can } if opts.WriteTerminalError != nil { opts.WriteTerminalError(terminalErr) - flusher.Flush() + if !flush() { + return + } } } var execErr error @@ -162,7 +192,9 @@ func (h *BaseAPIHandler) ForwardStream(c *gin.Context, flusher http.Flusher, can return case <-keepAliveC: writeKeepAlive() - flusher.Flush() + if !flush() { + return + } } } } diff --git a/sdk/cliproxy/usage/stream_delivery.go b/sdk/cliproxy/usage/stream_delivery.go new file mode 100644 index 00000000000..0606dae9007 --- /dev/null +++ b/sdk/cliproxy/usage/stream_delivery.go @@ -0,0 +1,73 @@ +package usage + +import ( + "context" + "sync" + "sync/atomic" +) + +type streamDeliveryKey struct{} + +type streamDelivery struct { + supported atomic.Int32 + once sync.Once + done chan struct{} + err error +} + +// WithStreamDelivery lets the HTTP consumer acknowledge delivery independently +// of request cancellation. The consumer must resolve the outcome on every exit. +func WithStreamDelivery(ctx context.Context) (context.Context, func(error)) { + delivery := &streamDelivery{done: make(chan struct{})} + return context.WithValue(ctx, streamDeliveryKey{}, delivery), func(err error) { + delivery.once.Do(func() { + delivery.err = err + close(delivery.done) + }) + } +} + +// WithoutStreamDelivery isolates an internal execution from its caller's HTTP +// acknowledgment. Internal consumers retain EOF-based accounting completion; +// cancellation and all unrelated context values remain inherited. +func WithoutStreamDelivery(ctx context.Context) context.Context { + if ctx == nil { + return nil + } + return context.WithValue(ctx, streamDeliveryKey{}, struct{}{}) +} + +// StreamDeliveryTracked reports whether a consumer will acknowledge delivery. +func StreamDeliveryTracked(ctx context.Context) bool { + _, ok := ctx.Value(streamDeliveryKey{}).(*streamDelivery) + return ok +} + +// WaitStreamDelivery waits for the consumer, not the upstream reader, to finish. +// Producers must close their output channel before waiting to avoid deadlocks. +func WaitStreamDelivery(ctx context.Context) (error, bool) { + delivery, ok := ctx.Value(streamDeliveryKey{}).(*streamDelivery) + if !ok { + return nil, false + } + <-delivery.done + return delivery.err, true +} + +// SupportStreamDelivery opts an active producer into early terminal cancellation. +// The producer must reconcile cancellation with WaitStreamDelivery. +func SupportStreamDelivery(ctx context.Context) func() { + delivery, ok := ctx.Value(streamDeliveryKey{}).(*streamDelivery) + if !ok { + return func() {} + } + delivery.supported.Add(1) + var once sync.Once + return func() { once.Do(func() { delivery.supported.Add(-1) }) } +} + +// StreamDeliverySupported reports whether an active producer understands delivery. +func StreamDeliverySupported(ctx context.Context) bool { + delivery, ok := ctx.Value(streamDeliveryKey{}).(*streamDelivery) + return ok && delivery.supported.Load() > 0 +} diff --git a/sdk/cliproxy/usage/stream_delivery_test.go b/sdk/cliproxy/usage/stream_delivery_test.go new file mode 100644 index 00000000000..d18d5c39b14 --- /dev/null +++ b/sdk/cliproxy/usage/stream_delivery_test.go @@ -0,0 +1,95 @@ +package usage + +import ( + "context" + "errors" + "io" + "testing" +) + +func TestStreamDeliverySurvivesCancellation(t *testing.T) { + for _, deliveryErr := range []error{nil, io.ErrClosedPipe} { + parent, cancel := context.WithCancel(context.Background()) + ctx, finish := WithStreamDelivery(parent) + if !StreamDeliveryTracked(ctx) { + t.Fatal("missing delivery tracking") + } + cancel() + result := make(chan error) + go func() { + err, tracked := WaitStreamDelivery(ctx) + if !tracked { + result <- errors.New("missing delivery tracking") + return + } + result <- err + }() + finish(deliveryErr) + finish(context.Canceled) + if err := <-result; !errors.Is(err, deliveryErr) { + t.Fatalf("delivery error = %v, want %v", err, deliveryErr) + } + } +} + +func TestStreamDeliveryUntracked(t *testing.T) { + if StreamDeliveryTracked(context.Background()) { + t.Fatal("unexpected delivery tracking") + } + if err, tracked := WaitStreamDelivery(context.Background()); err != nil || tracked { + t.Fatalf("untracked outcome = %v, %v", err, tracked) + } +} + +func TestStreamDeliveryRequiresProducerSupport(t *testing.T) { + ctx, finish := WithStreamDelivery(context.Background()) + defer finish(nil) + if StreamDeliverySupported(ctx) { + t.Fatal("consumer registration opted in an unsupported producer") + } + stop := SupportStreamDelivery(ctx) + if !StreamDeliverySupported(ctx) { + t.Fatal("producer support not visible") + } + stop() + stop() + if StreamDeliverySupported(ctx) { + t.Fatal("failed attempt leaked support to fallback producer") + } + SupportStreamDelivery(context.Background())() +} + +func TestWithoutStreamDeliveryPreservesContext(t *testing.T) { + type valueKey struct{} + parent, cancel := context.WithCancel(context.WithValue(context.Background(), valueKey{}, "metadata")) + defer cancel() + outer, finishOuter := WithStreamDelivery(parent) + defer finishOuter(context.Canceled) + stopOuter := SupportStreamDelivery(outer) + defer stopOuter() + inner := WithoutStreamDelivery(outer) + if StreamDeliveryTracked(inner) || StreamDeliverySupported(inner) { + t.Fatal("internal execution inherited delivery ownership") + } + if err, tracked := WaitStreamDelivery(inner); err != nil || tracked { + t.Fatalf("internal delivery = %v, %v", err, tracked) + } + if inner.Value(valueKey{}) != "metadata" { + t.Error("unrelated context value lost") + } + nested, finishNested := WithStreamDelivery(inner) + finishNested(io.ErrClosedPipe) + if err, tracked := WaitStreamDelivery(nested); !errors.Is(err, io.ErrClosedPipe) || !tracked { + t.Fatalf("independent consumer outcome = %v, %v", err, tracked) + } + if !StreamDeliverySupported(outer) { + t.Error("outer producer support lost") + } + cancel() + if inner.Err() != context.Canceled { + t.Error("caller cancellation lost") + } + if WithoutStreamDelivery(nil) != nil { + t.Error("nil context changed") + } +} From 5d890405b59c4b84a2f00ca39c4ee1494ce51a72 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Sun, 4 Oct 2026 20:32:07 +0800 Subject: [PATCH 038/142] fix(claude): keep system messages top level for terminal user turns - Add `claudeMidConversationSystemMessagesAtEnd` to detect consecutive user messages ending the message array - Append forwarded system blocks to top-level `system` payload instead of inserting mid-conversation message turns when trailing user turns are present Closes: #6336 --- .../executor/claude_executor_cloaking.go | 31 +++++++++++++ .../runtime/executor/claude_executor_test.go | 46 +++++++++++++++++++ 2 files changed, 77 insertions(+) diff --git a/internal/runtime/executor/claude_executor_cloaking.go b/internal/runtime/executor/claude_executor_cloaking.go index ef04fc5d721..e482119ce41 100644 --- a/internal/runtime/executor/claude_executor_cloaking.go +++ b/internal/runtime/executor/claude_executor_cloaking.go @@ -379,6 +379,11 @@ func checkSystemInstructionsWithSigningModeAt( } if claudeUsesLegacySystemReminder(payload) { payload = prependClaudeSystemRemindersToFirstUserMessage(payload, forwardedSystemBlocks) + } else if claudeMidConversationSystemMessagesAtEnd(payload) { + for _, block := range forwardedSystemBlocks { + systemBlocks = append(systemBlocks, buildTextBlock(block, &claudeCodeCacheControl)) + } + payload, _ = sjson.SetRawBytes(payload, "system", []byte("["+strings.Join(systemBlocks, ",")+"]")) } else { // Unknown and future model IDs optimistically use the authoritative // mid-conversation system role. Only empirically unsupported legacy IDs @@ -430,6 +435,14 @@ func relocateClaudeSystemPromptForCountTokens(payload []byte, strictMode bool) [ if claudeUsesLegacySystemReminder(payload) { return prependClaudeSystemRemindersToFirstUserMessage(payload, forwardedSystemBlocks) } + if claudeMidConversationSystemMessagesAtEnd(payload) { + blocks := make([]string, 0, len(forwardedSystemBlocks)) + for _, block := range forwardedSystemBlocks { + blocks = append(blocks, buildTextBlock(block, &claudeCodeCacheControl)) + } + updated, _ := sjson.SetRawBytes(payload, "system", []byte("["+strings.Join(blocks, ",")+"]")) + return updated + } return insertClaudeMidConversationSystemMessages(payload, forwardedSystemBlocks) } @@ -753,6 +766,24 @@ func claudeHistoryHasAdvisorCallOrResult(payload []byte) bool { return false } +func claudeMidConversationSystemMessagesAtEnd(payload []byte) bool { + firstUserIdx := firstClaudeUserMessageIndex(payload) + if firstUserIdx < 0 { + return false + } + + messages := gjson.GetBytes(payload, "messages") + if !messages.IsArray() { + return false + } + messageBlocks := messages.Array() + insertAt := firstUserIdx + 1 + for insertAt < len(messageBlocks) && messageBlocks[insertAt].Get("role").String() == "user" { + insertAt++ + } + return insertAt > firstUserIdx+1 && insertAt == len(messageBlocks) +} + func insertClaudeMidConversationSystemMessages(payload []byte, texts []string) []byte { firstUserIdx := firstClaudeUserMessageIndex(payload) if firstUserIdx < 0 || len(texts) == 0 { diff --git a/internal/runtime/executor/claude_executor_test.go b/internal/runtime/executor/claude_executor_test.go index f8cfdbea19e..666a63ab36c 100644 --- a/internal/runtime/executor/claude_executor_test.go +++ b/internal/runtime/executor/claude_executor_test.go @@ -4308,6 +4308,52 @@ func TestCheckSystemInstructionsWithMode_ArraySystemKeepsBlocksAsSeparateMessage assertClaudeMidConversationSystemMessage(t, out, 2, "second guidance", "") } +func TestCheckSystemInstructionsWithMode_TerminalUserRunKeepsSystemTopLevel(t *testing.T) { + payload := []byte(`{"model":"claude-opus-5","system":[` + + `{"type":"text","text":"first guidance"},` + + `{"type":"text","text":"second guidance"}],` + + `"messages":[{"role":"user","content":"first"},{"role":"user","content":"second"}]}`) + + out := checkSystemInstructionsWithMode(payload, false) + if got := gjson.GetBytes(out, "system.#").Int(); got != 4 { + t.Fatalf("top-level system block count = %d, want 4 (2 identity + 2 caller blocks): %s", got, out) + } + if got := gjson.GetBytes(out, "messages.#").Int(); got != 2 { + t.Fatalf("message count = %d, want 2 without trailing system turns: %s", got, out) + } + for idx, want := range []string{"first guidance", "second guidance"} { + if got := gjson.GetBytes(out, fmt.Sprintf("system.%d.text", idx+2)).String(); got != want { + t.Fatalf("system.%d.text = %q, want %q", idx+2, got, want) + } + if got := gjson.GetBytes(out, fmt.Sprintf("system.%d.cache_control.type", idx+2)).String(); got != "ephemeral" { + t.Fatalf("system.%d.cache_control.type = %q, want ephemeral", idx+2, got) + } + } +} + +func TestRelocateClaudeSystemPromptForCountTokens_TerminalUserRunKeepsSystemTopLevel(t *testing.T) { + payload := []byte(`{"model":"claude-opus-5","system":[` + + `{"type":"text","text":"first guidance"},` + + `{"type":"text","text":"second guidance"}],` + + `"messages":[{"role":"user","content":"first"},{"role":"user","content":"second"}]}`) + + out := relocateClaudeSystemPromptForCountTokens(payload, false) + if got := gjson.GetBytes(out, "system.#").Int(); got != 2 { + t.Fatalf("top-level system block count = %d, want 2 caller blocks: %s", got, out) + } + if got := gjson.GetBytes(out, "messages.#").Int(); got != 2 { + t.Fatalf("message count = %d, want 2 without trailing system turns: %s", got, out) + } + for idx, want := range []string{"first guidance", "second guidance"} { + if got := gjson.GetBytes(out, fmt.Sprintf("system.%d.text", idx)).String(); got != want { + t.Fatalf("system.%d.text = %q, want %q", idx, got, want) + } + if got := gjson.GetBytes(out, fmt.Sprintf("system.%d.cache_control.type", idx)).String(); got != "ephemeral" { + t.Fatalf("system.%d.cache_control.type = %q, want ephemeral", idx, got) + } + } +} + func TestRelocateClaudeSystemPromptForCountTokensKeepsBlocksSeparate(t *testing.T) { tests := []struct { name string From 26e5efbbdf6739eafa782cb98225e3fc2fbea99c Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Sun, 4 Oct 2026 21:00:20 +0800 Subject: [PATCH 039/142] fix(claude): reserve cache breakpoint for thread continuation - Decrement `maxBlocks` when a `thread` field is present in payload to reserve a cache breakpoint for Anthropic thread continuation Closes: #6338 --- .../executor/claude_executor_cloaking.go | 6 ++++++ .../runtime/executor/claude_executor_test.go | 21 +++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/internal/runtime/executor/claude_executor_cloaking.go b/internal/runtime/executor/claude_executor_cloaking.go index e482119ce41..14bcd5b3d0f 100644 --- a/internal/runtime/executor/claude_executor_cloaking.go +++ b/internal/runtime/executor/claude_executor_cloaking.go @@ -1876,6 +1876,12 @@ func enforceCacheControlLimit(payload []byte, maxBlocks int) []byte { return payload } + thread := gjson.GetBytes(payload, "thread") + if thread.Exists() && thread.Type != gjson.Null && maxBlocks > 0 { + // Anthropic reserves one cache breakpoint for thread continuation. + maxBlocks-- + } + total := countCacheControls(payload) if total <= maxBlocks { return payload diff --git a/internal/runtime/executor/claude_executor_test.go b/internal/runtime/executor/claude_executor_test.go index 666a63ab36c..da361df6bd3 100644 --- a/internal/runtime/executor/claude_executor_test.go +++ b/internal/runtime/executor/claude_executor_test.go @@ -3240,6 +3240,27 @@ func TestEnforceCacheControlLimit_PreservesKeyOrderWhenModified(t *testing.T) { } } +func TestEnforceCacheControlLimit_ReservesThreadMarker(t *testing.T) { + payload := []byte(`{ + "thread": {"type":"create"}, + "tools": [{"name":"t1","cache_control":{"type":"ephemeral"}}], + "system": [ + {"type":"text","text":"s1","cache_control":{"type":"ephemeral"}}, + {"type":"text","text":"s2","cache_control":{"type":"ephemeral"}} + ], + "messages": [{"role":"user","content":[ + {"type":"text","text":"u1","cache_control":{"type":"ephemeral"}}, + {"type":"text","text":"u2","cache_control":{"type":"ephemeral"}} + ]}] + }`) + + out := enforceCacheControlLimit(payload, 4) + + if got := countCacheControls(out); got != 3 { + t.Fatalf("cache_control count = %d, want 3 when thread is present", got) + } +} + func TestEnforceCacheControlLimit_ToolOnlyPayloadStillRespectsLimit(t *testing.T) { payload := []byte(`{ "tools": [ From 5c959cb032efb6f2067341915c9fb137532b8d5b Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Sun, 4 Oct 2026 21:40:10 +0800 Subject: [PATCH 040/142] fix(claude): mark missing thread state error for client replay - Treat Claude missing thread state 404 errors as client errors to bypass credential rotation and cooldown - Inject `thread_not_found` error code into Claude error response details to signal client-side replay - Support extracting upstream response bodies across error formatting and classification helpers Closes: #6344 --- internal/clienterror/client_error.go | 27 +++++++++ internal/clienterror/client_error_test.go | 25 ++++++++ sdk/api/handlers/claude/code_handlers.go | 41 +++++++++++-- .../claude/code_handlers_error_test.go | 58 +++++++++++++++++++ 4 files changed, 147 insertions(+), 4 deletions(-) diff --git a/internal/clienterror/client_error.go b/internal/clienterror/client_error.go index f5d520ccb66..8687d6df0d2 100644 --- a/internal/clienterror/client_error.go +++ b/internal/clienterror/client_error.go @@ -92,6 +92,11 @@ func IsRequestFault(status int, err error) bool { if status == http.StatusUnauthorized && hasAuthenticationErrorBody(err) { return false } + // Claude's missing thread state is tied to the stale continuation ID rather + // than the selected credential. Let the client replay the full conversation. + if IsClaudeThreadNotFound(status, err) { + return true + } // Model not found indicates a credential-model capability mismatch rather than // a caller request error. Preserve rotation and cooldown for the model. if hasModelNotFoundErrorBody(err) { @@ -129,6 +134,28 @@ func IsItemNotPersisted(message string) bool { strings.Contains(lower, "items are not persisted when `store` is set to false") } +// IsClaudeThreadNotFound reports the bare Claude 404 response for a stale +// previous_message_id continuation. +func IsClaudeThreadNotFound(status int, err error) bool { + if status != http.StatusNotFound || err == nil { + return false + } + body := strings.TrimSpace(err.Error()) + type responseBodyProvider interface { + ResponseBody() []byte + } + var responseBody responseBodyProvider + if errors.As(err, &responseBody) && responseBody != nil && len(responseBody.ResponseBody()) > 0 { + body = strings.TrimSpace(string(responseBody.ResponseBody())) + } + if body == "" || !json.Valid([]byte(body)) { + return false + } + return strings.EqualFold(strings.TrimSpace(gjson.Get(body, "error.type").String()), "not_found_error") && + strings.Contains(strings.ToLower(gjson.Get(body, "error.message").String()), "thread state") && + strings.Contains(strings.ToLower(gjson.Get(body, "error.message").String()), "previous_message_id") +} + func hasModelNotFoundErrorBody(err error) bool { if err == nil { return false diff --git a/internal/clienterror/client_error_test.go b/internal/clienterror/client_error_test.go index 12ee78c1121..00a533758ff 100644 --- a/internal/clienterror/client_error_test.go +++ b/internal/clienterror/client_error_test.go @@ -17,6 +17,15 @@ type statusError struct { func (e statusError) Error() string { return e.body } func (e statusError) StatusCode() int { return e.status } +type responseBodyError struct { + status int + body string +} + +func (e responseBodyError) Error() string { return "upstream request failed" } +func (e responseBodyError) StatusCode() int { return e.status } +func (e responseBodyError) ResponseBody() []byte { return []byte(e.body) } + func TestHTTPStatusFromError(t *testing.T) { tests := []struct { name string @@ -182,6 +191,20 @@ func TestIsRequestFault(t *testing.T) { err: errors.New("Item with id 'rs_0b5f3eb6f51f175c0169ca74e4a85881998539920821603a74' not found. Items are not persisted when `store` is set to false. Try again with `store` set to true, or remove this item from your input."), want: true, }, + { + name: "Claude missing thread state", + status: http.StatusNotFound, + err: errors.New(`{"type":"error","error":{"type":"not_found_error","message":"No thread state was found for the requested previous_message_id. Replay the full conversation with thread create to start a new Thread."}}`), + want: true, + }, + { + name: "Claude missing thread state in response body", + err: responseBodyError{ + status: http.StatusNotFound, + body: `{"type":"error","error":{"type":"not_found_error","message":"No thread state was found for the requested previous_message_id."}}`, + }, + want: true, + }, { // An upstream internal error is not a request fault: it must stay eligible // for credential rotation and (credential, model) cooldown. @@ -190,6 +213,8 @@ func TestIsRequestFault(t *testing.T) { err: errors.New(`{"error":{"code":500,"message":"Internal error encountered.","status":"UNKNOWN"}}`), }, {name: "plain not found", status: http.StatusNotFound, err: errors.New("model not found")}, + {name: "generic Claude not found", status: http.StatusNotFound, err: errors.New(`{"error":{"type":"not_found_error","message":"Not Found"}}`)}, + {name: "Claude missing thread on server error", status: http.StatusInternalServerError, err: errors.New(`{"error":{"type":"not_found_error","message":"No thread state was found for the requested previous_message_id."}}`)}, {name: "unauthorized", status: http.StatusUnauthorized, err: errors.New("invalid token")}, { name: "deepseek authentication failure is credential failure", diff --git a/sdk/api/handlers/claude/code_handlers.go b/sdk/api/handlers/claude/code_handlers.go index 9a576e88647..08d37bfe800 100644 --- a/sdk/api/handlers/claude/code_handlers.go +++ b/sdk/api/handlers/claude/code_handlers.go @@ -11,6 +11,7 @@ import ( "compress/gzip" "context" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -19,6 +20,7 @@ import ( "github.com/gin-gonic/gin" claudemodels "github.com/router-for-me/CLIProxyAPI/v8/internal/client/claude/models" + "github.com/router-for-me/CLIProxyAPI/v8/internal/clienterror" . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" @@ -326,8 +328,13 @@ func (h *ClaudeCodeAPIHandler) forwardClaudeStream(c *gin.Context, flusher http. } type claudeErrorDetail struct { - Type string `json:"type"` - Message string `json:"message"` + Type string `json:"type"` + Message string `json:"message"` + Details *claudeErrorDetails `json:"details,omitempty"` +} + +type claudeErrorDetails struct { + ErrorCode string `json:"error_code"` } type claudeErrorResponse struct { @@ -344,19 +351,23 @@ func (h *ClaudeCodeAPIHandler) toClaudeError(msg *interfaces.ErrorMessage) claud errText = http.StatusText(status) } if msg.Error != nil { - if v := strings.TrimSpace(msg.Error.Error()); v != "" { + if v := strings.TrimSpace(claudeErrorText(msg.Error)); v != "" { errText = v } } } errType, message := claudeErrorDetailFromText(status, errText) - return claudeErrorResponse{ + response := claudeErrorResponse{ Type: "error", Error: claudeErrorDetail{ Type: errType, Message: message, }, } + if clienterror.IsClaudeThreadNotFound(status, errors.New(errText)) { + response.Error.Details = &claudeErrorDetails{ErrorCode: "thread_not_found"} + } + return response } func (h *ClaudeCodeAPIHandler) WriteErrorResponse(c *gin.Context, msg *interfaces.ErrorMessage) { @@ -375,6 +386,14 @@ func (h *ClaudeCodeAPIHandler) WriteErrorResponse(c *gin.Context, msg *interface } } body := bytes.Clone(msg.Body) + if clienterror.IsClaudeThreadNotFound(status, errors.New(string(body))) { + if markedBody, errMarshal := json.Marshal(h.toClaudeError(&interfaces.ErrorMessage{ + StatusCode: status, + Error: errors.New(string(body)), + })); errMarshal == nil { + body = markedBody + } + } appendClaudeAPIResponse(c, body) if !c.Writer.Written() && c.Writer.Header().Get("Content-Type") == "" { c.Writer.Header().Set("Content-Type", "application/json") @@ -412,6 +431,20 @@ func (h *ClaudeCodeAPIHandler) WriteErrorResponse(c *gin.Context, msg *interface _, _ = c.Writer.Write(body) } +func claudeErrorText(err error) string { + if err == nil { + return "" + } + type responseBodyProvider interface { + ResponseBody() []byte + } + var responseBody responseBodyProvider + if errors.As(err, &responseBody) && responseBody != nil && len(responseBody.ResponseBody()) > 0 { + return string(responseBody.ResponseBody()) + } + return err.Error() +} + func claudeErrorDetailFromText(status int, errText string) (string, string) { message := strings.TrimSpace(errText) if message == "" { diff --git a/sdk/api/handlers/claude/code_handlers_error_test.go b/sdk/api/handlers/claude/code_handlers_error_test.go index fbed86859c8..f6949534199 100644 --- a/sdk/api/handlers/claude/code_handlers_error_test.go +++ b/sdk/api/handlers/claude/code_handlers_error_test.go @@ -1,6 +1,7 @@ package claude import ( + "encoding/json" "errors" "net/http" "net/http/httptest" @@ -130,6 +131,63 @@ func TestClaudeErrorExtractsClaudeStyleUpstreamJSON(t *testing.T) { } } +type responseBodyOnlyClaudeError struct { + body []byte +} + +func (e responseBodyOnlyClaudeError) Error() string { return "wrapped upstream error" } +func (e responseBodyOnlyClaudeError) ResponseBody() []byte { return e.body } + +func TestClaudeErrorMarksWrappedMissingThreadForClientReplay(t *testing.T) { + handler := &ClaudeCodeAPIHandler{} + msg := &interfaces.ErrorMessage{ + StatusCode: http.StatusNotFound, + Error: responseBodyOnlyClaudeError{body: []byte(`{"type":"error","error":{"type":"not_found_error","message":"No thread state was found for the requested previous_message_id."}}`)}, + } + + body, errMarshal := json.Marshal(handler.toClaudeError(msg)) + if errMarshal != nil { + t.Fatalf("marshal Claude error: %v", errMarshal) + } + if got := gjson.GetBytes(body, "error.details.error_code").String(); got != "thread_not_found" { + t.Fatalf("error.details.error_code = %q, want thread_not_found; body=%s", got, body) + } +} + +func TestClaudeErrorMarksMissingThreadForClientReplay(t *testing.T) { + handler := &ClaudeCodeAPIHandler{} + msg := &interfaces.ErrorMessage{ + StatusCode: http.StatusNotFound, + Error: errors.New(`{"type":"error","error":{"type":"not_found_error","message":"No thread state was found for the requested previous_message_id. Replay the full conversation with thread create to start a new Thread."}}`), + } + + body, errMarshal := json.Marshal(handler.toClaudeError(msg)) + if errMarshal != nil { + t.Fatalf("marshal Claude error: %v", errMarshal) + } + if got := gjson.GetBytes(body, "error.details.error_code").String(); got != "thread_not_found" { + t.Fatalf("error.details.error_code = %q, want thread_not_found; body=%s", got, body) + } +} + +func TestWriteClaudeDirectErrorMarksMissingThreadForClientReplay(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + handler := &ClaudeCodeAPIHandler{} + msg := &interfaces.ErrorMessage{ + StatusCode: http.StatusNotFound, + DirectResponse: true, + Body: []byte(`{"type":"error","error":{"type":"not_found_error","message":"No thread state was found for the requested previous_message_id. Replay the full conversation with thread create to start a new Thread."}}`), + } + + handler.WriteErrorResponse(c, msg) + + if got := gjson.GetBytes(recorder.Body.Bytes(), "error.details.error_code").String(); got != "thread_not_found" { + t.Fatalf("error.details.error_code = %q, want thread_not_found; body=%s", got, recorder.Body.Bytes()) + } +} + func TestWriteClaudeErrorResponseUsesClaudeEnvelope(t *testing.T) { gin.SetMode(gin.TestMode) recorder := httptest.NewRecorder() From dfd7c638d68dc854fb77ac2a360c3ed7d741f1fe Mon Sep 17 00:00:00 2001 From: JUNZE <127123086+WizisCool@users.noreply.github.com> Date: Sun, 4 Oct 2026 22:46:44 +0800 Subject: [PATCH 041/142] docs(readme): add Oh-My-CPA to usage statistics --- README.md | 4 ++++ README_CN.md | 4 ++++ README_JA.md | 4 ++++ 3 files changed, 12 insertions(+) diff --git a/README.md b/README.md index 53fbeb421cb..5ac7f568cca 100644 --- a/README.md +++ b/README.md @@ -154,6 +154,10 @@ Standalone persistence and visualization service for CLIProxyAPI, with periodic Full CLIProxyAPI management center with request-level monitoring and cost estimates. CPA-Manager tracks collected requests by account, model, channel, latency, status, and token usage; estimates cost with editable model prices and one-click LiteLLM price sync; persists events in SQLite; and provides Codex account-pool operations with batch inspection, quota detection, unhealthy account discovery, cleanup suggestions, and one-click execution for day-to-day multi-account maintenance. +### [Oh-My-CPA](https://github.com/WizisCool/oh-my-cpa) + +Modern Ant Design-based management console for CLIProxyAPI v8+, combining CPAMC-style administration with SQLite-backed request records and usage analytics. Covers OAuth accounts, API providers, client keys, quotas, pricing and CPA operations in one interface. Tracks request-level latency, TTFT, tokens and cost, with multi-dimensional filtering, live dashboards and token heatmaps. OpenRouter price sync, custom rates and per-request price snapshots keep historical costs stable; a built-in Agent and MCP tools support assisted investigation and management. + ## SDK Docs - Usage: [docs/sdk-usage.md](docs/sdk-usage.md) diff --git a/README_CN.md b/README_CN.md index 781932413f3..569d56ead24 100644 --- a/README_CN.md +++ b/README_CN.md @@ -150,6 +150,10 @@ CLIProxyAPI 用户手册: [https://help.router-for.me/](https://help.router-fo 面向 CLIProxyAPI 的完整管理中心,提供请求级监控和费用预估。CPA-Manager 可按账号、模型、渠道、延迟、状态和 token 用量追踪采集到的请求;支持可编辑模型价格与一键同步 LiteLLM 价格来估算费用;用 SQLite 持久化事件;并提供面向 Codex 账号池的批量巡检、配额识别、异常账号定位、清理建议与一键执行能力,适合多账号池的日常运维管理。 +### [Oh-My-CPA](https://github.com/WizisCool/oh-my-cpa) + +基于 Ant Design 的现代 CLIProxyAPI v8+ 管理面板,将 CPAMC 核心管理能力与 SQLite 持久化请求记录、用量分析整合在一起。覆盖 OAuth 账号、API 提供商、客户端密钥、配额、定价与 CPA 运维;逐请求追踪延迟、首 Token 延迟(TTFT)、Token 用量和成本,支持多维筛选、实时仪表盘与 Token 热力图。支持 OpenRouter 价格同步、自定义定价和逐请求价格快照,保持历史成本稳定;内置 Agent 与 MCP 工具,辅助用量分析和日常管理。 + ## SDK 文档 - 使用文档:[docs/sdk-usage_CN.md](docs/sdk-usage_CN.md) diff --git a/README_JA.md b/README_JA.md index a81582e8c65..dec03364aa2 100644 --- a/README_JA.md +++ b/README_JA.md @@ -149,6 +149,10 @@ CLIProxyAPI向けの独立した使用量永続化・可視化サービス。CLI リクエスト単位の監視とコスト推定を備えたCLIProxyAPI向けのフル管理センターです。CPA-Managerは、収集したリクエストをアカウント、モデル、チャネル、レイテンシ、ステータス、Token使用量ごとに追跡し、編集可能なモデル価格とLiteLLM価格のワンクリック同期でコストを推定します。SQLiteでイベントを永続化し、Codexアカウントプール向けに一括検査、クォータ判定、異常アカウント検出、クリーンアップ提案、ワンクリック実行を提供し、日常的なマルチアカウント運用に適しています。 +### [Oh-My-CPA](https://github.com/WizisCool/oh-my-cpa) + +Ant Design を採用した CLIProxyAPI v8+ 向けのモダンな管理コンソール。CPAMC に相当する主要な管理機能と、SQLite に永続化するリクエスト記録・使用量分析を統合し、OAuth アカウント、API プロバイダー、クライアントキー、クォータ、料金設定、CPA 運用を一つの画面で管理できます。リクエストごとのレイテンシ、最初のトークンまでの時間(TTFT)、トークン数、コストを追跡し、多条件フィルター、リアルタイムダッシュボード、トークンヒートマップを提供します。OpenRouter の価格同期、カスタム料金、リクエストごとの価格スナップショットで過去のコストを保持し、組み込み Agent と MCP ツールで分析と日常管理を支援します。 + ## SDKドキュメント - 使い方:[docs/sdk-usage.md](docs/sdk-usage.md) From 678a92578ca346ff9e77d4811cbd41f899a8cc96 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Sun, 4 Oct 2026 23:18:38 +0800 Subject: [PATCH 042/142] feat(claude): preserve OAuth tool aliases across thread continuations - Add bounded in-memory store to retain Claude OAuth tool alias mappings keyed by message ID - Restore alias mappings for thread continuation requests omitting tool declarations, returning a request-scoped not found error when state is missing - Record tool aliases on execution and streaming response completion Closes: #6346 --- internal/runtime/executor/claude_executor.go | 6 +- .../executor/claude_executor_execute.go | 10 +- .../claude_executor_request_remap_test.go | 68 +++++++++ .../executor/claude_executor_stream.go | 7 +- .../executor/claude_executor_tool_state.go | 139 ++++++++++++++++++ 5 files changed, 226 insertions(+), 4 deletions(-) create mode 100644 internal/runtime/executor/claude_executor_tool_state.go diff --git a/internal/runtime/executor/claude_executor.go b/internal/runtime/executor/claude_executor.go index 0fc1f0acf90..5c6562e7716 100644 --- a/internal/runtime/executor/claude_executor.go +++ b/internal/runtime/executor/claude_executor.go @@ -7,6 +7,7 @@ import ( "fmt" "net/http" "strings" + "sync" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps" @@ -18,13 +19,16 @@ import ( "github.com/tidwall/sjson" ) -// ClaudeExecutor is a stateless executor for Anthropic Claude over the messages API. +// ClaudeExecutor handles Anthropic Claude over the messages API and keeps bounded +// in-memory thread alias state for OAuth continuations. // If api_key is unavailable on auth, it falls back to legacy via ClientAdapter. type ClaudeExecutor struct { cfg *config.Config requestLogProvider string upstreamModelNormalizer func(string) string oauthProfileFetcher claudeOAuthProfileFetcher + oauthToolAliasStoreMu sync.Mutex + oauthToolAliases *claudeOAuthToolAliasStore } type claudeOAuthCancellationError struct { diff --git a/internal/runtime/executor/claude_executor_execute.go b/internal/runtime/executor/claude_executor_execute.go index 934f2db1bfc..3ee64fa6177 100644 --- a/internal/runtime/executor/claude_executor_execute.go +++ b/internal/runtime/executor/claude_executor_execute.go @@ -195,7 +195,10 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r var oauthToolNamesReverseMap map[string]string if fp.MCPAlias && cloaked { mcpAliases := resolveClaudeMCPAliasOptions(ctx) - bodyForUpstream, oauthToolNamesReverseMap = prepareClaudeOAuthToolNamesForUpstream(bodyForUpstream, mcpAliases) + bodyForUpstream, oauthToolNamesReverseMap, err = e.prepareClaudeOAuthToolNamesForRequest(bodyForUpstream, mcpAliases) + if err != nil { + return resp, err + } } bodyForUpstream = sanitizeClaudeMessagesForClaudeUpstreamWithDebug(ctx, bodyForUpstream, baseModel, helps.APIKeyModelIsCompat(req)) if fp.ApplyCLIIdentity { @@ -341,6 +344,7 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r } if msgID := claudeMessageIDFromSSE(data); msgID != "" { commitClaudeContinuity(diagnosticsState, msgID, helps.HeaderValueCaseInsensitive(httpResp.Header, "request-id")) + e.rememberClaudeOAuthToolAliases(body, oauthToolNamesReverseMap, msgID) } lines := bytes.Split(data, []byte("\n")) for i, line := range lines { @@ -357,7 +361,9 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r } data = bytes.Join(lines, []byte("\n")) } else { - commitClaudeContinuity(diagnosticsState, claudeMessageIDFromResponse(data), helps.HeaderValueCaseInsensitive(httpResp.Header, "request-id")) + messageID := claudeMessageIDFromResponse(data) + commitClaudeContinuity(diagnosticsState, messageID, helps.HeaderValueCaseInsensitive(httpResp.Header, "request-id")) + e.rememberClaudeOAuthToolAliases(body, oauthToolNamesReverseMap, messageID) reporter.ObserveResponseModel(data) var errRestore error data, errRestore = restoreClaudeOAuthToolNamesFromResponse(data, oauthToolNamesReverseMap) diff --git a/internal/runtime/executor/claude_executor_request_remap_test.go b/internal/runtime/executor/claude_executor_request_remap_test.go index 13e071b588f..f615544afa6 100644 --- a/internal/runtime/executor/claude_executor_request_remap_test.go +++ b/internal/runtime/executor/claude_executor_request_remap_test.go @@ -13,6 +13,74 @@ import ( "github.com/tidwall/gjson" ) +func TestClaudeOAuthToolAliasRestoresContinuationWithoutDeclarations(t *testing.T) { + secret := "continuation-alias-caller" + createBody := []byte(`{"thread":{"type":"create"},"tools":[{"name":"Read","input_schema":{"type":"object"}}]}`) + executor := &ClaudeExecutor{} + _, reverseMap, errPrepare := executor.prepareClaudeOAuthToolNamesForRequest(createBody, claudeMCPAliasOptions{secret: secret}) + if errPrepare != nil { + t.Fatalf("prepare create request: %v", errPrepare) + } + alias := "" + for upstreamName := range reverseMap { + alias = upstreamName + break + } + if alias == "" { + t.Fatal("create request did not allocate an OAuth MCP alias") + } + + continuationBody := []byte(`{"thread":{"type":"continue","previous_message_id":"msg-one"},"messages":[{"role":"user","content":[{"type":"tool_result","tool_use_id":"tool-one","content":"ok"}]}]}`) + executor.rememberClaudeOAuthToolAliases(createBody, reverseMap, "msg-one") + _, continuationReverseMap, errPrepareContinuation := executor.prepareClaudeOAuthToolNamesForRequest(continuationBody, claudeMCPAliasOptions{secret: secret}) + if errPrepareContinuation != nil { + t.Fatalf("prepare continuation request: %v", errPrepareContinuation) + } + response := []byte(fmt.Sprintf(`{"content":[{"type":"tool_use","id":"tool-two","name":%q,"input":{}}]}`, alias)) + restored, errRestore := restoreClaudeOAuthToolNamesFromResponse(response, continuationReverseMap) + if errRestore != nil { + t.Fatalf("restore continuation tool name: %v", errRestore) + } + if got := gjson.GetBytes(restored, "content.0.name").String(); got != "Read" { + t.Fatalf("continuation tool name = %q, want Read; response=%s", got, restored) + } +} + +func TestClaudeOAuthToolAliasMissingContinuationStateIsRequestScopedNotFound(t *testing.T) { + continuationBody := []byte(`{"thread":{"type":"continue","previous_message_id":"missing-message"}}`) + _, _, errPrepare := (&ClaudeExecutor{}).prepareClaudeOAuthToolNamesForRequest(continuationBody, claudeMCPAliasOptions{secret: "missing-state-caller"}) + if errPrepare == nil { + t.Fatal("prepare continuation request returned nil error") + } + statusErr, okStatus := errPrepare.(interface{ StatusCode() int }) + if !okStatus || statusErr.StatusCode() != 404 { + t.Fatalf("continuation error status = %v, want 404", errPrepare) + } + requestErr, okRequest := errPrepare.(cliproxyexecutor.RequestScopedError) + if !okRequest || !requestErr.IsRequestScoped() { + t.Fatalf("continuation error is not request-scoped: %T", errPrepare) + } +} + +func TestClaudeOAuthToolAliasEvictionReturnsThreadNotFound(t *testing.T) { + executor := &ClaudeExecutor{} + createBody := []byte(`{"thread":{"type":"create"}}`) + executor.rememberClaudeOAuthToolAliases(createBody, map[string]string{"alias": "Read"}, "first-message") + for i := 0; i < claudeOAuthToolAliasStateLimit; i++ { + executor.rememberClaudeOAuthToolAliases(createBody, nil, fmt.Sprintf("message-%d", i)) + } + + continuationBody := []byte(`{"thread":{"type":"continue","previous_message_id":"first-message"}}`) + _, _, errPrepare := executor.prepareClaudeOAuthToolNamesForRequest(continuationBody, claudeMCPAliasOptions{secret: "evicted-state-caller"}) + if errPrepare == nil { + t.Fatal("evicted continuation returned nil error") + } + statusErr, okStatus := errPrepare.(interface{ StatusCode() int }) + if !okStatus || statusErr.StatusCode() != 404 { + t.Fatalf("evicted continuation error status = %v, want 404", errPrepare) + } +} + func TestRemapOAuthToolNamesWithBatchedEditsMatchesLegacyBytes(t *testing.T) { secret := "differential-caller" collision := helps.ClaudeMCPToolAlias(secret, "fetch_url", 0) diff --git a/internal/runtime/executor/claude_executor_stream.go b/internal/runtime/executor/claude_executor_stream.go index 0ef0c91fe2e..f8b220390e7 100644 --- a/internal/runtime/executor/claude_executor_stream.go +++ b/internal/runtime/executor/claude_executor_stream.go @@ -190,7 +190,10 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A var oauthToolNamesReverseMap map[string]string if fp.MCPAlias && cloaked { mcpAliases := resolveClaudeMCPAliasOptions(ctx) - bodyForUpstream, oauthToolNamesReverseMap = prepareClaudeOAuthToolNamesForUpstream(bodyForUpstream, mcpAliases) + bodyForUpstream, oauthToolNamesReverseMap, err = e.prepareClaudeOAuthToolNamesForRequest(bodyForUpstream, mcpAliases) + if err != nil { + return nil, err + } } bodyForUpstream = sanitizeClaudeMessagesForClaudeUpstreamWithDebug(ctx, bodyForUpstream, baseModel, helps.APIKeyModelIsCompat(req)) if fp.ApplyCLIIdentity { @@ -415,6 +418,7 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A } if upstreamCompleted { commitClaudeContinuity(diagnosticsState, upstreamMessageID, helps.HeaderValueCaseInsensitive(httpResp.Header, "request-id")) + e.rememberClaudeOAuthToolAliases(body, oauthToolNamesReverseMap, upstreamMessageID) } return } @@ -489,6 +493,7 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A } if upstreamCompleted { commitClaudeContinuity(diagnosticsState, upstreamMessageID, helps.HeaderValueCaseInsensitive(httpResp.Header, "request-id")) + e.rememberClaudeOAuthToolAliases(body, oauthToolNamesReverseMap, upstreamMessageID) } }() result := &cliproxyexecutor.StreamResult{Headers: httpResp.Header.Clone(), Chunks: out} diff --git a/internal/runtime/executor/claude_executor_tool_state.go b/internal/runtime/executor/claude_executor_tool_state.go new file mode 100644 index 00000000000..c36f615a50b --- /dev/null +++ b/internal/runtime/executor/claude_executor_tool_state.go @@ -0,0 +1,139 @@ +package executor + +import ( + "net/http" + "sync" + + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + "github.com/tidwall/gjson" +) + +const claudeOAuthToolAliasStateLimit = 1024 + +type claudeOAuthToolAliasStore struct { + mu sync.Mutex + entries map[string]map[string]string + order []string +} + +func (s *claudeOAuthToolAliasStore) load(keys []string) (map[string]string, bool) { + if s == nil { + return nil, false + } + s.mu.Lock() + defer s.mu.Unlock() + for _, key := range keys { + aliases, ok := s.entries[key] + if !ok { + continue + } + return cloneClaudeOAuthToolAliasMap(aliases), true + } + return nil, false +} + +func (s *claudeOAuthToolAliasStore) save(keys []string, aliases map[string]string) { + if s == nil { + return + } + s.mu.Lock() + defer s.mu.Unlock() + if s.entries == nil { + s.entries = make(map[string]map[string]string) + } + for _, key := range keys { + if key == "" { + continue + } + if _, exists := s.entries[key]; !exists { + s.order = append(s.order, key) + } + s.entries[key] = cloneClaudeOAuthToolAliasMap(aliases) + } + for len(s.order) > claudeOAuthToolAliasStateLimit { + oldest := s.order[0] + s.order = s.order[1:] + delete(s.entries, oldest) + } +} + +func cloneClaudeOAuthToolAliasMap(source map[string]string) map[string]string { + if len(source) == 0 { + return map[string]string{} + } + clone := make(map[string]string, len(source)) + for key, value := range source { + clone[key] = value + } + return clone +} + +func (e *ClaudeExecutor) claudeOAuthToolAliasStore() *claudeOAuthToolAliasStore { + e.oauthToolAliasStoreMu.Lock() + defer e.oauthToolAliasStoreMu.Unlock() + if e.oauthToolAliases == nil { + e.oauthToolAliases = &claudeOAuthToolAliasStore{} + } + return e.oauthToolAliases +} + +func claudeOAuthToolAliasKeys(payload []byte, messageID string) []string { + keys := make([]string, 0, 2) + if previousMessageID := gjson.GetBytes(payload, "thread.previous_message_id").String(); previousMessageID != "" { + keys = append(keys, "message:"+previousMessageID) + } + if messageID != "" { + keys = append(keys, "message:"+messageID) + } + return keys +} + +func claudeThreadContinuationNeedsAliasState(payload []byte) bool { + if gjson.GetBytes(payload, "thread.type").String() != "continue" { + return false + } + previousMessageID := gjson.GetBytes(payload, "thread.previous_message_id") + if !previousMessageID.Exists() || previousMessageID.String() == "" { + return false + } + tools := gjson.GetBytes(payload, "tools") + return !tools.Exists() || !tools.IsArray() || len(tools.Array()) == 0 +} + +func (e *ClaudeExecutor) prepareClaudeOAuthToolNamesForRequest(payload []byte, options claudeMCPAliasOptions) ([]byte, map[string]string, error) { + if claudeThreadContinuationNeedsAliasState(payload) { + aliases, ok := e.claudeOAuthToolAliasStore().load(claudeOAuthToolAliasKeys(payload, "")) + if !ok { + return nil, nil, newClaudeThreadNotFoundError() + } + return payload, aliases, nil + } + remapped, aliases := prepareClaudeOAuthToolNamesForUpstream(payload, options) + return remapped, aliases, nil +} + +func (e *ClaudeExecutor) rememberClaudeOAuthToolAliases(payload []byte, aliases map[string]string, messageID string) { + if gjson.GetBytes(payload, "thread.type").String() == "" { + return + } + keys := claudeOAuthToolAliasKeys(payload, messageID) + if len(keys) == 0 { + return + } + e.claudeOAuthToolAliasStore().save(keys, aliases) +} + +type claudeThreadNotFoundError struct { + statusErr +} + +func newClaudeThreadNotFoundError() claudeThreadNotFoundError { + return claudeThreadNotFoundError{statusErr: statusErr{ + code: http.StatusNotFound, + msg: "No thread state was found for the requested previous_message_id. Replay the full conversation with thread create to start a new Thread.", + }} +} + +func (claudeThreadNotFoundError) IsRequestScoped() bool { return true } + +var _ cliproxyexecutor.RequestScopedError = claudeThreadNotFoundError{} From dfc1b1cfaa45069da51e301510869e70eceea306 Mon Sep 17 00:00:00 2001 From: whale Date: Mon, 5 Oct 2026 02:39:34 +0800 Subject: [PATCH 043/142] fix(i18n): keep Claude and Antigravity plan names untranslated in Chinese locales (#464) * fix(i18n): show the Claude Pro plan as Pro in Chinese locales * fix(i18n): keep Free and Team plan names untranslated in Chinese locales --- src/i18n/locales/zh-CN.json | 8 ++++---- src/i18n/locales/zh-TW.json | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index d7029c6955d..854fc70c0e1 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -435,7 +435,7 @@ }, "antigravity_subscription": { "plan_unknown": "未知", - "plan_free": "免费版", + "plan_free": "Free", "plan_pro": "Pro", "plan_ultra": "Ultra", "plan_ultra_lite": "Ultra Lite" @@ -491,12 +491,12 @@ "extra_usage_label": "额外用量", "plan_label": "套餐", "plan_unknown": "未知", - "plan_free": "免费版", - "plan_pro": "专业版", + "plan_free": "Free", + "plan_pro": "Pro", "plan_max": "Max", "plan_max5": "Max 5x", "plan_max20": "Max 20x", - "plan_team": "团队版" + "plan_team": "Team" }, "codex_quota": { "title": "Codex 额度", diff --git a/src/i18n/locales/zh-TW.json b/src/i18n/locales/zh-TW.json index ee4918d4f55..09c8713d3cc 100644 --- a/src/i18n/locales/zh-TW.json +++ b/src/i18n/locales/zh-TW.json @@ -435,7 +435,7 @@ }, "antigravity_subscription": { "plan_unknown": "未知", - "plan_free": "免費版", + "plan_free": "Free", "plan_pro": "Pro", "plan_ultra": "Ultra", "plan_ultra_lite": "Ultra Lite" @@ -491,12 +491,12 @@ "extra_usage_label": "額外用量", "plan_label": "方案", "plan_unknown": "未知", - "plan_free": "免費版", - "plan_pro": "專業版", + "plan_free": "Free", + "plan_pro": "Pro", "plan_max": "Max", "plan_max5": "Max 5x", "plan_max20": "Max 20x", - "plan_team": "團隊版" + "plan_team": "Team" }, "codex_quota": { "title": "Codex 配額", From fc9b8e2d4042bb0fc2134bde544f2da0f9bb40ae Mon Sep 17 00:00:00 2001 From: nguyenha935 Date: Mon, 5 Oct 2026 02:01:41 +0700 Subject: [PATCH 044/142] feat(i18n): add Vietnamese (vi) locale (#382) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add a complete Vietnamese translation for the Management Center UI: - src/i18n/locales/vi.json: full translation of all 1540 keys from en.json, with all interpolation placeholders preserved - src/i18n/index.ts: register the vi resource bundle - src/types/common.ts: extend the Language type with 'vi' - src/utils/constants.ts: add 'vi' to LANGUAGE_ORDER and LANGUAGE_LABEL_KEYS - src/utils/language.ts: auto-detect vi-* browser languages - locales/{en,zh-CN,zh-TW,ru}.json: add the Tiếng Việt label so the new language appears in every language switcher Tested by building with vite and deploying the bundle against a live CLIProxyAPI v7.2.133 server; vi-* browsers resolve to the Vietnamese UI and all strings render with correct placeholders. Co-authored-by: nguyenha935 Co-authored-by: Claude Opus 5 (1M context) --- src/i18n/index.ts | 2 + src/i18n/locales/en.json | 3 +- src/i18n/locales/ru.json | 3 +- src/i18n/locales/vi.json | 1725 +++++++++++++++++++++++++++++++++++ src/i18n/locales/zh-CN.json | 3 +- src/i18n/locales/zh-TW.json | 3 +- src/types/common.ts | 2 +- src/utils/constants.ts | 3 +- src/utils/language.ts | 1 + 9 files changed, 1739 insertions(+), 6 deletions(-) create mode 100644 src/i18n/locales/vi.json diff --git a/src/i18n/index.ts b/src/i18n/index.ts index 9da45107954..8be00f84abd 100644 --- a/src/i18n/index.ts +++ b/src/i18n/index.ts @@ -8,6 +8,7 @@ import zhCN from './locales/zh-CN.json'; import zhTW from './locales/zh-TW.json'; import en from './locales/en.json'; import ru from './locales/ru.json'; +import vi from './locales/vi.json'; import { getInitialLanguage } from '@/utils/language'; i18n.use(initReactI18next).init({ @@ -16,6 +17,7 @@ i18n.use(initReactI18next).init({ 'zh-TW': { translation: zhTW }, en: { translation: en }, ru: { translation: ru }, + vi: { translation: vi }, }, lng: getInitialLanguage(), fallbackLng: 'zh-CN', diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json index 820a0690610..5aecec3824a 100644 --- a/src/i18n/locales/en.json +++ b/src/i18n/locales/en.json @@ -1805,7 +1805,8 @@ "chinese": "中文", "chinese_tw": "Traditional Chinese (Taiwan)", "english": "English", - "russian": "Русский" + "russian": "Русский", + "vietnamese": "Tiếng Việt" }, "theme": { "switch": "Theme", diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index e0b6d8ba3d0..ff34aa8d789 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -1799,7 +1799,8 @@ "chinese": "中文", "chinese_tw": "繁體中文(台灣)", "english": "English", - "russian": "Русский" + "russian": "Русский", + "vietnamese": "Tiếng Việt" }, "theme": { "switch": "Тема", diff --git a/src/i18n/locales/vi.json b/src/i18n/locales/vi.json new file mode 100644 index 00000000000..dc9a3cf99fc --- /dev/null +++ b/src/i18n/locales/vi.json @@ -0,0 +1,1725 @@ +{ + "common": { + "login": "Đăng nhập", + "logout": "Đăng xuất", + "back": "Quay lại", + "cancel": "Hủy", + "confirm": "Xác nhận", + "leave": "Rời đi", + "stay": "Ở lại", + "save": "Lưu", + "delete": "Xóa", + "edit": "Chỉnh sửa", + "add": "Thêm", + "update": "Cập nhật", + "refresh": "Làm mới", + "close": "Đóng", + "success": "Thành công", + "error": "Lỗi", + "info": "Thông tin", + "warning": "Cảnh báo", + "loading": "Đang tải...", + "connecting": "Đang kết nối...", + "connected": "Đã kết nối", + "disconnected": "Mất kết nối", + "connecting_status": "Đang kết nối", + "connected_status": "Đã kết nối", + "disconnected_status": "Mất kết nối", + "yes": "Có", + "no": "Không", + "not_set": "Chưa đặt", + "optional": "Tùy chọn", + "required": "Bắt buộc", + "api_key": "Key", + "base_url": "Địa chỉ", + "prefix": "Tiền tố", + "proxy_url": "Proxy", + "priority": "Ưu tiên", + "alias": "Bí danh", + "failure": "Thất bại", + "unknown_error": "Lỗi không xác định", + "quota_update_required": "Vui lòng cập nhật phiên bản CPA hoặc kiểm tra bản cập nhật", + "quota_check_credential": "Vui lòng kiểm tra trạng thái credential", + "copy": "Sao chép", + "expand": "Mở rộng", + "collapse": "Thu gọn", + "status": "Trạng thái", + "action": "Hành động", + "custom_headers_label": "Header tùy chỉnh", + "custom_headers_hint": "Header HTTP tùy chọn gửi kèm yêu cầu. Để trống để xóa.", + "custom_headers_add": "Thêm Header", + "custom_headers_key_placeholder": "Tên header, ví dụ X-Custom-Header", + "custom_headers_value_placeholder": "Giá trị header", + "model_name_placeholder": "Tên model, ví dụ claude-3-5-sonnet-20241022", + "model_alias_placeholder": "Bí danh model (tùy chọn)", + "invalid_provider_index": "Chỉ mục provider không hợp lệ.", + "unsaved_changes_title": "Thay đổi chưa lưu", + "unsaved_changes_message": "Bạn có thay đổi chưa lưu. Rời đi bây giờ sẽ mất các thay đổi đó. Bạn có muốn rời đi không?" + }, + "title": { + "login": "Trung tâm Quản lý CLI Proxy API", + "abbr": "CPAMC" + }, + "splash": { + "title": "CLI Proxy API", + "subtitle": "Trung tâm Quản lý" + }, + "login": { + "subtitle": "Vui lòng nhập thông tin kết nối để truy cập giao diện quản lý", + "connection_current": "URL hiện tại", + "connection_auto_hint": "Hệ thống sẽ tự động dùng URL hiện tại để kết nối", + "custom_connection_label": "URL kết nối tùy chỉnh:", + "custom_connection_placeholder": "Ví dụ: https://example.com:8317", + "custom_connection_hint": "Mặc định dùng URL hiện tại. Ghi đè tại đây nếu cần.", + "remember_password_label": "Ghi nhớ mật khẩu", + "management_key_label": "Key quản lý:", + "management_key_placeholder": "Nhập key quản lý", + "submit_button": "Đăng nhập", + "submitting": "Đang kết nối...", + "error_backend_detail": "Phản hồi từ backend", + "error_required": "Vui lòng điền đầy đủ thông tin kết nối", + "error_invalid": "Kết nối thất bại, vui lòng kiểm tra địa chỉ máy chủ, Management API và key quản lý", + "error_network": "Kết nối mạng thất bại, vui lòng kiểm tra mạng hoặc địa chỉ máy chủ", + "error_timeout": "Kết nối hết thời gian chờ, máy chủ không phản hồi", + "error_unauthorized": "Xác thực thất bại, key quản lý bị thiếu hoặc không hợp lệ", + "error_forbidden": "Truy cập bị từ chối, quản lý từ xa bị tắt, key quản lý chưa được cấu hình, hoặc IP này bị cấm tạm thời", + "error_not_found": "Không tìm thấy Management API, hãy xác nhận địa chỉ máy chủ trỏ đến backend CLIProxyAPI", + "error_server": "Backend gặp lỗi khi xử lý yêu cầu quản lý, hãy kiểm tra log máy chủ", + "error_cors": "Yêu cầu cross-origin bị chặn, vui lòng kiểm tra cấu hình máy chủ", + "error_ssl": "Xác minh chứng chỉ SSL/TLS thất bại" + }, + "header": { + "refresh_all": "Làm mới tất cả", + "logout": "Đăng xuất" + }, + "connection": { + "status": "Trạng thái kết nối:" + }, + "nav": { + "dashboard": "Bảng điều khiển", + "quick_start": "Bắt đầu nhanh", + "ai_providers": "AI Provider", + "auth_files": "File xác thực", + "oauth": "Đăng nhập OAuth", + "quota_management": "Quản lý Quota", + "plugins": "Plugin", + "plugin_store": "Cửa hàng Plugin", + "config_management": "Bảng cấu hình", + "logs": "Trình xem Log", + "system_info": "Thông tin Trung tâm Quản lý" + }, + "nav_groups": { + "operate": "Vận hành", + "gateway": "Gateway", + "observe": "Giám sát", + "plugin_pages": "Plugin", + "control": "Điều khiển" + }, + "nav_meta": { + "dashboard": "Tổng quan vận hành", + "quick_start": "Thiết lập APIKEY.FUN", + "ai_providers": "Định tuyến model upstream", + "auth_files": "File xác thực & credential", + "oauth": "Ủy quyền OAuth", + "quota_management": "API key & giới hạn", + "plugins": "Bật/tắt & cấu hình plugin", + "plugin_store": "Khám phá & cài đặt plugin", + "logs": "Truy vết yêu cầu", + "config_management": "Cấu hình gateway", + "system_info": "Runtime & chẩn đoán" + }, + "dashboard": { + "hero_verdict_good": "Mọi hệ thống ổn định", + "hero_verdict_warning": "Có chút trục trặc nhỏ", + "hero_verdict_critical": "Cần chú ý", + "hero_verdict_idle": "Tạm thời yên tĩnh", + "hero_verdict_offline": "Đang chờ kết nối", + "hero_verdict_connecting": "Đang kết nối", + "hero_period": ".", + "hero_requests_label": "Yêu cầu đã xử lý", + "hero_live": "Trực tiếp", + "hero_window_meta": "Cửa sổ trượt {{window}} · bucket 10 phút", + "hero_spark_label": "Lưu lượng yêu cầu trong {{window}} vừa qua", + "cta_manage_providers": "Quản lý provider", + "cta_inspect_logs": "Kiểm tra log", + "stats_aria": "Chỉ số chính", + "success_rate": "Tỷ lệ thành công", + "stat_success_hint": "Trên {{total}} yêu cầu trong cửa sổ", + "stat_credentials": "Credential", + "stat_credentials_hint": "{{active}} đang hoạt động · {{disabled}} không phục vụ", + "stat_credentials_empty": "Chưa tìm thấy file credential nào", + "stat_provider_keys": "Key provider", + "stat_provider_keys_hint": "API key được cấu hình trên tất cả các thương hiệu", + "stat_models": "Model", + "stat_models_hint": "Được phục vụ qua proxy endpoint", + "traffic_eyebrow": "Lưu lượng trực tiếp", + "traffic_title": "Thông lượng, từng khoảng mười phút", + "traffic_description": "Số lần thành công và thất bại mỗi bucket 10 phút trong {{window}} vừa qua. Di chuột vào cột để xem phân tách chính xác.", + "traffic_table": "Bảng dữ liệu", + "traffic_table_window": "Cửa sổ", + "traffic_chart_summary": "{{total}} yêu cầu trong {{minutes}} phút vừa qua: {{success}} thành công, {{failed}} thất bại.", + "traffic_unavailable": "Chưa có lưu lượng nào được ghi nhận", + "traffic_unavailable_hint": "Bộ đếm sẽ xuất hiện khi proxy phục vụ yêu cầu đầu tiên.", + "fleet_eyebrow": "Toàn cảnh", + "fleet_title": "Mọi provider, đặt cạnh nhau", + "fleet_description": "Lưu lượng và tỷ lệ thành công của từng provider trong cùng cửa sổ.", + "fleet_empty": "Chưa có lưu lượng provider nào được ghi nhận.", + "fleet_credentials": "Credential: {{value}}", + "fleet_spark_label": "Lưu lượng yêu cầu của {{provider}}", + "fleet_requests": "yêu cầu", + "provider_unknown": "Chưa xác định", + "health_eyebrow": "Sức khỏe", + "health_title": "Trạng thái credential", + "health_active": "Đang hoạt động", + "health_unavailable": "Không khả dụng", + "health_disabled": "Đã tắt", + "health_by_type": "Theo provider", + "health_empty": "Chưa tìm thấy file credential nào.", + "health_link": "Mở file xác thực", + "runtime_eyebrow": "Runtime", + "runtime_title": "Tổng quan cấu hình", + "runtime_routing": "Chiến lược định tuyến", + "runtime_retry": "Thử lại yêu cầu", + "runtime_management_keys": "Key quản lý", + "runtime_version": "Phiên bản máy chủ", + "runtime_build": "Ngày build", + "runtime_proxy": "Proxy upstream", + "runtime_debug": "Debug", + "runtime_file_logging": "Ghi log ra file", + "runtime_request_log": "Log yêu cầu", + "runtime_ws_auth": "Xác thực WebSocket", + "runtime_model_prefix": "Tiền tố model", + "runtime_link": "Chỉnh sửa cấu hình", + "cta_eyebrow": "Tiếp theo", + "cta_title": "Nên đi đâu từ đây", + "cta_providers_desc": "Thêm API key, đặt ưu tiên và kiểm thử các thương hiệu.", + "cta_auth_files_desc": "Tải lên, làm mới và vô hiệu hóa credential OAuth.", + "cta_config_desc": "Tinh chỉnh định tuyến, thử lại, ghi log và truy cập.", + "cta_quota_desc": "Kiểm tra quota còn lại của từng credential.", + "cta_logs_desc": "Theo dõi yêu cầu và tải báo cáo lỗi.", + "cta_system_desc": "Chi tiết phiên bản và thông tin trung tâm quản lý.", + "window_m": "{{minutes}}p", + "window_h": "{{hours}}g", + "window_hm": "{{hours}}g {{minutes}}p" + }, + "basic_settings": { + "debug_enable": "Bật chế độ Debug", + "proxy_url_label": "URL Proxy:", + "retry_count_label": "Số lần thử lại:", + "logging_to_file_enable": "Bật ghi log ra file", + "request_log_title": "Ghi log yêu cầu", + "request_log_enable": "Bật ghi log yêu cầu", + "request_log_warning": "Hãy tắt tính năng này trừ khi bạn cần gỡ lỗi chi tiết.", + "ws_auth_enable": "Yêu cầu xác thực cho /ws/*", + "routing_strategy_round_robin": "round-robin (luân phiên)", + "routing_strategy_weighted_round_robin": "weighted-round-robin (luân phiên có trọng số)", + "routing_strategy_fill_first": "fill-first (ưu tiên lấp đầy)" + }, + "auth_files": { + "title": "Quản lý File xác thực", + "meta_total": "{{count}} credential", + "meta_active": "{{count}} đang hoạt động", + "meta_problem": "{{count}} có vấn đề", + "empty_title": "Chưa có credential nào", + "empty_desc": "Tải lên file xác thực hoặc kết nối provider qua OAuth để bắt đầu.", + "empty_oauth_link": "Kết nối qua OAuth", + "no_results_clear": "Xóa bộ lọc", + "title_section": "File xác thực", + "upload_button": "Tải file lên", + "delete_all_button": "Xóa tất cả", + "search_empty_title": "Không có file phù hợp", + "search_empty_desc": "Hãy thử đổi bộ lọc hoặc xóa ô tìm kiếm.", + "file_size": "Kích thước", + "file_modified": "Đã sửa", + "health_status_label": "Sức khỏe", + "health_status_healthy": "Khỏe mạnh", + "health_status_warning": "Cảnh báo", + "health_status_disabled": "Đã tắt", + "download_button": "Tải xuống", + "manual_refresh_button": "Làm mới credential OAuth", + "manual_refresh_requested": "Đã yêu cầu làm mới credential cho \"{{name}}\"", + "manual_refresh_failed": "Không thể yêu cầu làm mới credential cho \"{{name}}\": {{message}}", + "delete_button": "Xóa", + "delete_confirm": "Bạn có chắc muốn xóa file", + "delete_all_confirm": "Bạn có chắc muốn xóa tất cả file xác thực? Thao tác này không thể hoàn tác!", + "delete_filtered_confirm": "Bạn có chắc muốn xóa tất cả file xác thực {{type}}? Thao tác này không thể hoàn tác!", + "delete_problem_button": "Xóa file có vấn đề", + "delete_problem_button_with_type": "Xóa file {{type}} có vấn đề", + "delete_problem_confirm": "Bạn có chắc muốn xóa tất cả file xác thực có vấn đề? Thao tác này không thể hoàn tác!", + "delete_problem_filtered_confirm": "Bạn có chắc muốn xóa tất cả file xác thực {{type}} có vấn đề? Thao tác này không thể hoàn tác!", + "delete_filtered_result_button": "Xóa kết quả đã lọc", + "delete_filtered_result_confirm": "Bạn có chắc muốn xóa các file xác thực trong kết quả lọc hiện tại? Thao tác này không thể hoàn tác!", + "upload_error_json": "Chỉ chấp nhận file JSON", + "upload_error_size": "Kích thước file không được vượt quá {{maxSize}}", + "upload_success": "Tải file lên thành công", + "download_success": "Tải file xuống thành công", + "delete_success": "Xóa file thành công", + "delete_all_success": "Đã xóa thành công", + "delete_filtered_success": "Đã xóa thành công {{count}} file xác thực {{type}}", + "delete_filtered_partial": "Hoàn tất xóa file xác thực {{type}}: {{success}} thành công, {{failed}} thất bại", + "delete_filtered_none": "Không có file xác thực nào xóa được trong bộ lọc hiện tại ({{type}})", + "delete_problem_success": "Đã xóa thành công {{count}} file xác thực có vấn đề", + "delete_problem_filtered_success": "Đã xóa thành công {{count}} file xác thực {{type}} có vấn đề", + "delete_problem_partial": "Hoàn tất xóa file xác thực có vấn đề: {{success}} thành công, {{failed}} thất bại", + "delete_problem_filtered_partial": "Hoàn tất xóa file xác thực {{type}} có vấn đề: {{success}} thành công, {{failed}} thất bại", + "delete_problem_none": "Không có file xác thực có vấn đề nào xóa được trong bộ lọc hiện tại", + "delete_problem_filtered_none": "Không có file xác thực {{type}} có vấn đề nào xóa được trong bộ lọc hiện tại", + "delete_filtered_result_success": "Đã xóa thành công {{count}} file xác thực từ kết quả lọc", + "delete_filtered_result_partial": "Hoàn tất xóa kết quả lọc: {{success}} thành công, {{failed}} thất bại", + "delete_filtered_result_none": "Không có file xác thực nào xóa được trong kết quả lọc hiện tại", + "pagination_prev": "Trước", + "pagination_next": "Sau", + "pagination_info": "Trang {{current}} / {{total}} · {{count}} file", + "search_label": "Tìm kiếm cấu hình", + "search_placeholder": "Lọc theo tên, tài khoản, loại hoặc provider. Dùng * làm ký tự đại diện", + "problem_filter_label": "Lọc trạng thái", + "problem_filter_all": "Tất cả", + "problem_filter_enabled": "Đang bật", + "problem_filter_problem": "Có vấn đề", + "problem_filter_disabled": "Đã tắt", + "display_options_label": "Tùy chọn hiển thị", + "compact_mode_label": "Chế độ thu gọn", + "sort_label": "Sắp xếp", + "sort_default": "Mặc định", + "sort_az": "Tên A-Z", + "sort_priority": "Ưu tiên", + "priority_display": "Ưu tiên", + "weight_display": "Trọng số WRR", + "page_size_label": "Mỗi trang", + "filter_all": "Tất cả", + "filter_qwen": "Qwen", + "filter_gemini": "Gemini", + "filter_kimi": "Kimi", + "filter_aistudio": "AIStudio", + "filter_claude": "Claude", + "filter_codex": "Codex", + "filter_antigravity": "Antigravity", + "filter_xai": "xAI", + "filter_iflow": "iFlow", + "filter_vertex": "Vertex", + "filter_empty": "Trống", + "filter_unknown": "Khác", + "type_virtual": "File xác thực ảo", + "models_button": "Model", + "models_title": "Model được hỗ trợ", + "models_loading": "Đang tải danh sách model...", + "models_empty": "Không có model khả dụng cho credential này", + "models_empty_desc": "Credential này có thể chưa được máy chủ nạp, hoặc chưa có model nào gắn với nó.", + "models_unsupported": "Phiên bản hiện tại không hỗ trợ tính năng này", + "models_unsupported_desc": "Vui lòng cập nhật CLI Proxy API lên phiên bản mới nhất và thử lại", + "models_excluded_badge": "Đã tắt", + "models_excluded_hint": "Model OAuth này đã bị tắt", + "status_toggle_label": "Đang bật", + "status_enabled_success": "\"{{name}}\" đã được bật", + "status_disabled_success": "\"{{name}}\" đã được tắt", + "batch_status_success": "Đã cập nhật thành công {{count}} file", + "batch_status_partial": "{{success}} đã cập nhật, {{failed}} thất bại", + "batch_delete_title": "Xóa các file đã chọn", + "batch_delete_confirm": "Bạn có chắc muốn xóa {{count}} file?", + "batch_selected": "Đã chọn {{count}}", + "batch_toolbar_label": "Hành động hàng loạt", + "batch_select_all": "Chọn tất cả", + "batch_select_page": "Chọn trang này", + "batch_select_filtered": "Chọn đã lọc", + "batch_invert_page": "Đảo lựa chọn trang", + "batch_deselect": "Bỏ chọn", + "batch_download": "Tải xuống đã chọn", + "batch_download_success": "Đã bắt đầu tải xuống {{count}} file", + "batch_download_partial": "Hoàn tất tải xuống: {{success}} thành công, {{failed}} thất bại", + "batch_enable": "Bật", + "batch_disable": "Tắt", + "prefix_proxy_button": "Chi tiết / Chỉnh sửa File xác thực", + "prefix_proxy_loading": "Đang tải file xác thực...", + "prefix_proxy_info_label": "Thông tin file xác thực (info)", + "prefix_proxy_source_label": "JSON file xác thực (xem trước)", + "prefix_proxy_invalid_content_label": "Nội dung đã tải (bị cắt)", + "prefix_label": "Tiền tố (prefix)", + "proxy_url_label": "URL Proxy (proxy_url)", + "proxy_url_placeholder": "socks5://username:password@proxy_ip:port/", + "priority_label": "Ưu tiên (priority)", + "priority_placeholder": "ví dụ 10 hoặc -1", + "priority_hint": "Chỉ nhận số nguyên. Giá trị không hợp lệ sẽ bị bỏ qua. Giá trị lớn hơn nghĩa là ưu tiên cao hơn.", + "weight_label": "Trọng số điều phối (weight)", + "weight_hint": "Mặc định là 1. Giá trị ≤ 0 sẽ loại credential này khỏi điều phối có trọng số; tối đa 1.000.000.", + "weight_invalid_integer": "Trọng số phải là số nguyên.", + "weight_invalid_max": "Trọng số không được vượt quá 1.000.000.", + "disable_cooling_label": "Tắt cooldown lũy thừa (disable_cooling)", + "disable_cooling_hint": "Bỏ qua cooldown thất bại và backoff lũy thừa chỉ cho credential này; các credential khác không bị ảnh hưởng.", + "websockets_label": "WebSocket (websockets)", + "websockets_hint": "Bật truyền tải websocket của Responses API cho credential này.", + "using_api_label": "Dùng API chính thức (using_api)", + "using_api_hint": "Dùng API xAI chính thức khi bật; dùng chat-proxy Grok CLI khi tắt.", + "note_label": "Ghi chú", + "note_placeholder": "Nhập ghi chú, ví dụ: Tài khoản của John", + "note_hint": "Tùy chọn. Dùng để mô tả mục đích hoặc chủ sở hữu của credential này; để trống nếu không cần.", + "excluded_models_label": "Model bị loại trừ (excluded_models)", + "headers_label": "Header tùy chỉnh (headers)", + "headers_placeholder": "{\n \"Header-Name\": \"value\"\n}", + "headers_hint": "Nhập header HTTP tùy chỉnh dưới dạng đối tượng JSON, ví dụ {\"X-My-Header\": \"value\"}", + "headers_invalid_json": "Header tùy chỉnh phải là JSON hợp lệ.", + "headers_invalid_object": "Header tùy chỉnh phải là một đối tượng JSON.", + "headers_invalid_value": "Mỗi giá trị header tùy chỉnh phải là chuỗi.", + "prefix_proxy_invalid_json": "File xác thực này không phải đối tượng JSON nên không thể chỉnh sửa các trường.", + "prefix_proxy_html_challenge": "Nội dung tải xuống là trang HTML challenge, không phải đối tượng JSON xác thực. Hãy xác thực lại hoặc thay file xác thực này trước khi chỉnh sửa.", + "prefix_proxy_saved_success": "Đã cập nhật file xác thực \"{{name}}\" thành công", + "quota_refresh_single": "Làm mới quota", + "quota_refresh_hint": "Chỉ làm mới quota cho credential này", + "quota_refresh_success": "Đã làm mới quota cho \"{{name}}\"", + "quota_refresh_failed": "Không thể làm mới quota cho \"{{name}}\": {{message}}" + }, + "antigravity_subscription": { + "plan_unknown": "Không rõ", + "plan_free": "Miễn phí", + "plan_pro": "Pro", + "plan_ultra": "Ultra", + "plan_ultra_lite": "Ultra Lite" + }, + "antigravity_quota": { + "title": "Quota Antigravity", + "empty_title": "Không có File xác thực Antigravity", + "empty_desc": "Tải lên credential Antigravity để xem quota còn lại.", + "idle": "Nhấn vào đây để làm mới quota", + "loading": "Đang tải quota...", + "load_failed": "Không thể tải quota: {{message}}", + "missing_auth_index": "File xác thực thiếu auth_index", + "missing_project_id": "Credential Antigravity thiếu project_id. Đăng nhập lại hoặc làm mới credential để xác định project.", + "empty_models": "Chưa có dữ liệu quota", + "plan_label": "Gói", + "group_gemini_models": "Model Gemini", + "group_claude_gpt_models": "Model Claude và GPT", + "group_models_description": "Các model trong nhóm này: {{models}}", + "weekly_limit": "Giới hạn tuần", + "daily_limit": "Giới hạn ngày", + "five_hour_limit": "Giới hạn 5 giờ", + "monthly_limit": "Giới hạn tháng", + "quota_available": "Quota khả dụng", + "remaining_percent": "Còn lại {{percent}}%", + "refreshes_in": "Làm mới sau {{duration}}", + "refresh_available": "Có thể làm mới", + "duration_day_hour": "{{days}}n {{hours}}g", + "duration_hour_minute": "{{hours}}g {{minutes}}p", + "duration_minute": "{{minutes}}p", + "duration_less_than_minute": "<1p", + "refresh_button": "Làm mới Quota", + "fetch_all": "Lấy tất cả" + }, + "claude_quota": { + "title": "Quota Claude", + "empty_title": "Không có File OAuth Claude", + "empty_desc": "Đăng nhập bằng Claude OAuth để xem quota.", + "idle": "Nhấn vào đây để làm mới quota", + "loading": "Đang tải quota...", + "load_failed": "Không thể tải quota: {{message}}", + "missing_auth_index": "File xác thực thiếu auth_index", + "empty_windows": "Chưa có dữ liệu quota", + "refresh_button": "Làm mới Quota", + "fetch_all": "Lấy tất cả", + "five_hour": "Giới hạn 5 giờ", + "seven_day": "Giới hạn 7 ngày", + "seven_day_oauth_apps": "OAuth apps 7 ngày", + "seven_day_opus": "Opus 7 ngày", + "seven_day_sonnet": "Sonnet 7 ngày", + "seven_day_cowork": "Cowork 7 ngày", + "iguana_necktie": "Iguana Necktie", + "seven_day_fable": "Fable 5 · 7 ngày", + "extra_usage_label": "Sử dụng thêm", + "plan_label": "Gói", + "plan_unknown": "Không rõ", + "plan_free": "Miễn phí", + "plan_pro": "Pro", + "plan_max": "Max", + "plan_max5": "Max 5x", + "plan_max20": "Max 20x", + "plan_team": "Team" + }, + "codex_quota": { + "title": "Quota Codex", + "empty_title": "Không có File xác thực Codex", + "empty_desc": "Tải lên credential Codex để xem quota.", + "idle": "Nhấn vào đây để làm mới quota", + "loading": "Đang tải quota...", + "load_failed": "Không thể tải quota: {{message}}", + "missing_auth_index": "File xác thực thiếu auth_index", + "missing_account_id": "Credential Codex thiếu ID tài khoản ChatGPT", + "empty_windows": "Chưa có dữ liệu quota", + "no_access": "Credential này không có quyền truy cập Codex (gói: free).", + "refresh_button": "Làm mới Quota", + "fetch_all": "Lấy tất cả", + "primary_window": "Giới hạn 5 giờ", + "secondary_window": "Giới hạn tuần", + "team_secondary_window": "Giới hạn tháng", + "code_review_primary_window": "Giới hạn 5 giờ cho code review", + "code_review_secondary_window": "Giới hạn tuần cho code review", + "code_review_team_secondary_window": "Giới hạn tháng cho code review", + "additional_primary_window": "Giới hạn 5 giờ của {{name}}", + "additional_secondary_window": "Giới hạn tuần của {{name}}", + "additional_team_secondary_window": "Giới hạn tháng của {{name}}", + "plan_label": "Gói", + "expires_label": "Thời gian gia hạn", + "reset_credits_label": "Lượt đặt lại thủ công", + "reset_credits_expiry_label": "Hết hạn đặt lại thủ công ({{timezone}})", + "reset_credit_number": "Lượt đặt lại {{index}}", + "reset_credits_expiry_failed": "Không thể tải thời hạn đặt lại thủ công: {{message}}", + "reset_credits_invalid_payload": "Phản hồi thời hạn đặt lại thủ công không hợp lệ", + "reset_button": "Đặt lại quota", + "reset_confirm_title": "Đặt lại quota Codex", + "reset_confirm_message": "Thao tác này sẽ dùng 1 lượt đặt lại thủ công để đặt lại quota Codex cho \"{{name}}\". Tiếp tục?", + "reset_confirm_button": "Đặt lại quota", + "reset_success": "Đã đặt lại quota Codex cho \"{{name}}\"", + "reset_failed": "Không thể đặt lại quota Codex cho \"{{name}}\": {{message}}", + "plan_plus": "Plus", + "plan_team": "Team", + "plan_free": "Miễn phí", + "plan_pro": "Pro 20x", + "plan_prolite": "Pro 5x" + }, + "kimi_quota": { + "title": "Quota Kimi", + "empty_title": "Không có File xác thực Kimi", + "empty_desc": "Tải lên credential Kimi để xem quota còn lại.", + "idle": "Nhấn vào đây để làm mới quota", + "loading": "Đang tải quota...", + "load_failed": "Không thể tải quota: {{message}}", + "missing_auth_index": "File xác thực thiếu auth_index", + "empty_data": "Chưa có dữ liệu quota", + "refresh_button": "Làm mới Quota", + "fetch_all": "Lấy tất cả", + "weekly_limit": "Giới hạn tuần", + "limit_window": "Giới hạn {{duration}}", + "limit_index": "Giới hạn #{{index}}", + "reset_hint": "đặt lại sau {{hint}}" + }, + "xai_quota": { + "title": "Quota Grok", + "empty_title": "Không có File xác thực xAI/Grok", + "empty_desc": "Đăng nhập bằng xAI OAuth để xem quota Grok.", + "idle": "Nhấn vào đây để làm mới quota", + "loading": "Đang tải quota...", + "load_failed": "Không thể tải quota: {{message}}", + "missing_auth_index": "File xác thực thiếu auth_index", + "empty_data": "Chưa có dữ liệu quota", + "refresh_button": "Làm mới Quota", + "fetch_all": "Lấy tất cả", + "weekly_limit": "Giới hạn tuần", + "monthly_credits": "Credit tháng", + "used_percent": "Đã dùng {{percent}}", + "reset_at": "Đặt lại lúc {{time}}", + "product_usage": "Mức sử dụng {{product}}", + "plan_label": "Gói", + "plan_supergrok": "SuperGrok", + "plan_supergrok_heavy": "SuperGrok Heavy", + "plan_paid": "Trả phí", + "paid_health": "API chat trả phí khả dụng. xAI không công bố tổng quota cho credential OAuth này.", + "pay_as_you_go_label": "Trả theo mức sử dụng", + "pay_as_you_go_enabled": "Đang bật, giới hạn {{cap}}", + "pay_as_you_go_disabled": "Đã tắt" + }, + "vertex_import": { + "title": "Đăng nhập Vertex bằng JSON", + "description": "Tải lên file JSON service account của Google để lưu thành auth-dir/vertex-.json theo cùng quy tắc với công cụ vertex-import của CLI.", + "location_label": "Khu vực (tùy chọn)", + "location_placeholder": "us-central1", + "location_hint": "Để trống để dùng khu vực mặc định us-central1.", + "file_label": "JSON key của service account", + "file_hint": "Chỉ chấp nhận file JSON key của service account Google Cloud.", + "file_placeholder": "Chưa chọn file", + "choose_file": "Chọn File", + "import_button": "Nhập Credential Vertex", + "file_required": "Hãy chọn file credential .json trước", + "success": "Đã nhập credential Vertex thành công", + "result_title": "Đã lưu credential", + "result_project": "Project ID", + "result_email": "Service account", + "result_location": "Khu vực", + "result_file": "File đã lưu" + }, + "oauth_excluded": { + "title": "Vô hiệu hóa Model OAuth", + "description": "Việc vô hiệu hóa model theo từng provider được hiển thị dưới dạng thẻ; nhấn vào thẻ để chỉnh sửa hoặc xóa. Hỗ trợ ký tự đại diện * và phạm vi áp dụng theo bộ lọc file xác thực.", + "add": "Thêm vô hiệu hóa", + "add_title": "Thêm vô hiệu hóa model của provider", + "edit_title": "Chỉnh sửa vô hiệu hóa model cho {{provider}}", + "provider_label": "Provider", + "provider_placeholder": "ví dụ codex / openai", + "provider_hint": "Mặc định theo bộ lọc hiện tại; chọn provider có sẵn hoặc nhập tên mới.", + "models_label": "Model cần vô hiệu hóa", + "save": "Lưu/Cập nhật", + "save_success": "Đã cập nhật vô hiệu hóa model", + "save_failed": "Không thể cập nhật vô hiệu hóa model", + "delete": "Xóa Provider", + "delete_confirm": "Xóa vô hiệu hóa model của {{provider}}?", + "delete_success": "Đã xóa vô hiệu hóa model của provider", + "delete_failed": "Không thể xóa vô hiệu hóa model", + "no_models": "Chưa cấu hình model bị vô hiệu hóa nào", + "model_count": "{{count}} model bị vô hiệu hóa", + "list_empty_all": "Chưa có vô hiệu hóa model provider nào; nhấn “Thêm vô hiệu hóa” để tạo.", + "provider_required": "Vui lòng nhập provider trước", + "upgrade_required": "Phiên bản CPA hiện tại không hỗ trợ vô hiệu hóa model OAuth. Vui lòng nâng cấp.", + "upgrade_required_title": "Vui lòng nâng cấp CLI Proxy API", + "upgrade_required_desc": "Phiên bản máy chủ hiện tại không hỗ trợ lấy danh sách vô hiệu hóa model OAuth. Vui lòng nâng cấp lên phiên bản CPA (CLI Proxy API) mới nhất và thử lại." + }, + "excluded_models": { + "trigger_summary": "{{excluded}} bị loại trừ · {{available}} khả dụng", + "trigger_summary_rules": "{{n}} quy tắc", + "trigger_empty": "Không có model nào bị loại trừ", + "meter_aria": "{{excluded}} trong {{total}} model bị loại trừ", + "search_placeholder": "Tìm model…", + "search_aria": "Tìm model để loại trừ", + "list_aria": "Model", + "no_results": "Không có model nào khớp “{{query}}”", + "catalog_loading": "Đang tải model…", + "catalog_unavailable": "Không lấy được danh sách model — các quy tắc vẫn được áp dụng.", + "catalog_error": "Không thể tải danh sách model.", + "catalog_retry": "Thử lại", + "catalog_empty": "Không có model nào để liệt kê.", + "footer_count": "{{excluded}} / {{total}} bị loại trừ", + "select_all": "Loại trừ tất cả", + "clear": "Xóa", + "clear_aria": "Bỏ chọn các model (giữ lại quy tắc ký tự đại diện)", + "badge_wildcard": "Theo quy tắc", + "badge_unknown": "Không có trong danh sách", + "wildcard_reason": "Khớp quy tắc {{rule}}", + "wildcard_locked": "Bị loại trừ bởi quy tắc {{rule}} — hãy sửa quy tắc bên dưới", + "also_wildcard": "Cũng khớp {{rule}}", + "chips_more": "+{{n}} khác", + "chip_remove": "Ngừng loại trừ {{rule}}", + "rules_label": "Quy tắc ký tự đại diện", + "rules_placeholder": "Mỗi dòng một quy tắc, ví dụ gpt-5-*", + "rules_hint": "* khớp mọi ký tự. Không phân biệt hoa thường.", + "rules_match_count": "khớp {{n}} model", + "rules_match_none": "không khớp model nào trong danh sách", + "rules_reserved": "“*” vô hiệu hóa toàn bộ provider — hãy dùng công tắc Đã tắt thay thế" + }, + "oauth_model_alias": { + "title": "Bí danh Model OAuth", + "add": "Thêm bí danh", + "add_title": "Thêm bí danh model của provider", + "provider_label": "Provider", + "provider_placeholder": "ví dụ codex / vertex", + "provider_hint": "Mặc định theo bộ lọc hiện tại; chọn provider có sẵn hoặc nhập tên mới.", + "model_source_loading": "Đang tải model...", + "model_source_unsupported": "Phiên bản CPA hiện tại không hỗ trợ lấy danh sách model (vẫn có thể nhập thủ công).", + "model_source_loaded": "Đã tải {{count}} model. Dùng menu thả trong 'Tên model gốc', hoặc nhập giá trị tùy chỉnh. Lưu danh sách trống sẽ xóa provider đó. Bật 'Giữ tên gốc' để giữ tên gốc trong khi thêm bí danh.", + "alias_label": "Bí danh model", + "alias_name_placeholder": "Tên model gốc", + "alias_placeholder": "Bí danh (bắt buộc)", + "duplicate_alias": "Mỗi bí danh phải là duy nhất cho provider này.", + "alias_fork_label": "Giữ tên gốc", + "add_alias": "Thêm bí danh", + "save": "Lưu/Cập nhật", + "save_success": "Đã cập nhật bí danh model", + "save_failed": "Không thể cập nhật bí danh model", + "delete": "Xóa Provider", + "delete_confirm": "Xóa bí danh model của {{provider}}?", + "delete_link_title": "Bỏ liên kết ánh xạ", + "delete_link_confirm": "Bỏ liên kết ánh xạ từ {{sourceModel}} ({{provider}}) sang bí danh {{alias}}?", + "delete_alias_title": "Xóa bí danh", + "delete_alias_confirm": "Xóa bí danh {{alias}} và bỏ ánh xạ tất cả model liên quan?", + "delete_success": "Đã xóa bí danh model", + "delete_failed": "Không thể xóa bí danh model", + "no_models": "Không có bí danh model", + "model_count": "{{count}} bí danh", + "list_empty_all": "Chưa có bí danh model nào—dùng “Thêm bí danh” để tạo.", + "chart_title": "Tổng quan mọi ánh xạ", + "diagram_providers": "Provider", + "diagram_source_models": "Model gốc", + "diagram_aliases": "Bí danh", + "diagram_expand": "Mở rộng", + "diagram_collapse": "Thu gọn", + "diagram_add_alias": "Thêm bí danh", + "diagram_rename": "Đổi tên", + "diagram_rename_alias_title": "Đổi tên bí danh", + "diagram_rename_alias_label": "Tên bí danh mới", + "diagram_rename_placeholder": "Nhập tên bí danh...", + "diagram_delete_link": "Bỏ liên kết khỏi {{provider}} / {{name}}", + "diagram_delete_alias": "Xóa bí danh", + "diagram_please_enter_alias": "Vui lòng nhập tên bí danh.", + "diagram_alias_exists": "Bí danh này đã tồn tại.", + "diagram_add_alias_title": "Thêm bí danh", + "diagram_add_alias_label": "Tên bí danh", + "diagram_add_placeholder": "Nhập tên bí danh mới...", + "diagram_rename_btn": "Đổi tên", + "diagram_add_btn": "Thêm", + "diagram_settings": "Cài đặt", + "diagram_settings_title": "Cài đặt bí danh — {{alias}}", + "diagram_settings_source_title": "Cài đặt model gốc", + "diagram_settings_empty": "Chưa có ánh xạ nào cho bí danh này.", + "diagram_tap_hint": "Trên thiết bị cảm ứng: chạm vào model gốc, sau đó chạm vào bí danh để liên kết.", + "view_mode_diagram": "Sơ đồ", + "view_mode_list": "Danh sách", + "provider_required": "Vui lòng nhập provider trước", + "upgrade_required": "Tính năng này yêu cầu phiên bản CLI Proxy API (CPA) mới hơn. Vui lòng nâng cấp.", + "upgrade_required_title": "Vui lòng nâng cấp CLI Proxy API", + "upgrade_required_desc": "Máy chủ hiện tại không hỗ trợ API bí danh model OAuth. Vui lòng nâng cấp lên phiên bản CLI Proxy API (CPA) mới nhất." + }, + "auth_login": { + "recommended_provider_section": "Provider đề xuất", + "recommended_provider_badge": "Provider đề xuất", + "other_oauth_providers": "Provider OAuth khác", + "other_login_methods": "Phương thức đăng nhập khác", + "codex_oauth_title": "Codex OAuth", + "codex_oauth_button": "Bắt đầu đăng nhập Codex", + "codex_oauth_hint": "Đăng nhập dịch vụ Codex qua luồng OAuth, tự động lấy và lưu file xác thực.", + "codex_oauth_url_label": "URL ủy quyền:", + "codex_open_link": "Mở liên kết", + "codex_copy_link": "Sao chép liên kết", + "codex_oauth_status_waiting": "Đang chờ xác thực...", + "codex_oauth_status_success": "Xác thực thành công!", + "codex_oauth_status_error": "Xác thực thất bại:", + "codex_oauth_start_error": "Không thể bắt đầu Codex OAuth:", + "codex_oauth_polling_error": "Không thể kiểm tra trạng thái xác thực:", + "anthropic_oauth_title": "Anthropic OAuth", + "anthropic_oauth_button": "Bắt đầu đăng nhập Anthropic", + "anthropic_oauth_hint": "Đăng nhập dịch vụ Anthropic (Claude) qua luồng OAuth, tự động lấy và lưu file xác thực.", + "anthropic_oauth_url_label": "URL ủy quyền:", + "anthropic_open_link": "Mở liên kết", + "anthropic_copy_link": "Sao chép liên kết", + "anthropic_oauth_status_waiting": "Đang chờ xác thực...", + "anthropic_oauth_status_success": "Xác thực thành công!", + "anthropic_oauth_status_error": "Xác thực thất bại:", + "anthropic_oauth_start_error": "Không thể bắt đầu Anthropic OAuth:", + "anthropic_oauth_polling_error": "Không thể kiểm tra trạng thái xác thực:", + "antigravity_oauth_title": "Antigravity OAuth", + "antigravity_oauth_button": "Bắt đầu đăng nhập Antigravity", + "antigravity_oauth_hint": "Đăng nhập dịch vụ Antigravity (tài khoản Google) qua luồng OAuth, tự động lấy và lưu file xác thực.", + "antigravity_oauth_url_label": "URL ủy quyền:", + "antigravity_open_link": "Mở liên kết", + "antigravity_copy_link": "Sao chép liên kết", + "antigravity_oauth_status_waiting": "Đang chờ xác thực...", + "antigravity_oauth_status_success": "Xác thực thành công!", + "antigravity_oauth_status_error": "Xác thực thất bại:", + "antigravity_oauth_start_error": "Không thể bắt đầu Antigravity OAuth:", + "antigravity_oauth_polling_error": "Không thể kiểm tra trạng thái xác thực:", + "kimi_oauth_title": "Kimi OAuth", + "kimi_oauth_button": "Đăng nhập bằng Kimi", + "kimi_sign_up_button": "Đăng ký ngay", + "kimi_oauth_hint": "Đăng nhập nhanh vào Kimi qua ủy quyền thiết bị. File xác thực được lấy và lưu tự động.", + "kimi_oauth_url_label": "URL ủy quyền:", + "kimi_open_link": "Mở liên kết", + "kimi_copy_link": "Sao chép liên kết", + "kimi_oauth_status_waiting": "Đang chờ xác thực...", + "kimi_oauth_status_success": "Xác thực thành công!", + "kimi_oauth_status_error": "Xác thực thất bại:", + "kimi_oauth_start_error": "Không thể bắt đầu Kimi OAuth:", + "kimi_oauth_polling_error": "Không thể kiểm tra trạng thái xác thực:", + "xai_oauth_title": "xAI OAuth", + "xai_oauth_button": "Bắt đầu đăng nhập xAI", + "xai_oauth_hint": "Đăng nhập xAI Grok qua luồng OAuth, tự động lấy và lưu file xác thực.", + "xai_oauth_url_label": "URL ủy quyền:", + "xai_open_link": "Mở liên kết", + "xai_copy_link": "Sao chép liên kết", + "xai_oauth_status_waiting": "Đang chờ xác thực...", + "xai_oauth_status_success": "Xác thực thành công!", + "xai_oauth_status_error": "Xác thực thất bại:", + "xai_oauth_start_error": "Không thể bắt đầu xAI OAuth:", + "xai_oauth_polling_error": "Không thể kiểm tra trạng thái xác thực:", + "plugin_oauth_title": "{{name}} OAuth", + "plugin_oauth_button": "Bắt đầu đăng nhập {{name}}", + "plugin_oauth_hint": "Đăng nhập {{name}} qua luồng OAuth của plugin, tự động lấy và lưu file xác thực.", + "plugin_oauth_url_label": "URL ủy quyền:", + "plugin_open_link": "Mở liên kết", + "plugin_copy_link": "Sao chép liên kết", + "plugin_oauth_status_waiting": "Đang chờ xác thực...", + "plugin_oauth_status_success": "Xác thực thành công!", + "plugin_oauth_status_error": "Xác thực thất bại:", + "plugin_oauth_start_error": "Không thể bắt đầu plugin OAuth:", + "xai_callback_label": "URL callback hoặc mã", + "xai_callback_placeholder": "Dán mã mà Grok hiển thị, hoặc URL callback đầy đủ", + "xai_callback_hint": "Grok có thể chỉ hiển thị mã trên trang. Dán trực tiếp mã đó và ứng dụng sẽ tự động gửi dưới dạng http://127.0.0.1:56121/callback?...", + "xai_callback_required": "Vui lòng dán mã Grok hiển thị hoặc URL callback đầy đủ trước.", + "xai_callback_state_missing": "Thiếu state cho lần đăng nhập xAI này. Hãy bắt đầu đăng nhập xAI lại, sau đó gửi mã.", + "oauth_callback_label": "URL callback", + "oauth_callback_placeholder": "http://localhost:1455/auth/callback?code=...&state=...", + "oauth_callback_hint": "Chế độ trình duyệt từ xa: sau khi provider chuyển hướng đến http://localhost:..., hãy sao chép URL đầy đủ và gửi tại đây.", + "oauth_callback_button": "Gửi URL callback", + "oauth_callback_required": "Vui lòng dán URL chuyển hướng đầy đủ trước.", + "oauth_callback_success": "Đã gửi URL callback. Tiếp tục chờ xác thực.", + "oauth_callback_error": "Không thể gửi URL callback:", + "oauth_callback_upgrade_hint": "Vui lòng cập nhật CLI Proxy API hoặc kiểm tra kết nối.", + "oauth_callback_status_success": "Đã gửi URL callback, đang chờ xác thực...", + "oauth_callback_status_error": "Gửi URL callback thất bại:", + "missing_state": "Không thể lấy tham số trạng thái xác thực", + "login_another_account": "Đăng nhập tài khoản khác", + "view_auth_files": "Xem file xác thực", + "iflow_oauth_title": "iFlow OAuth", + "iflow_oauth_button": "Bắt đầu đăng nhập iFlow", + "iflow_oauth_hint": "Đăng nhập dịch vụ iFlow qua luồng OAuth, tự động lấy và lưu file xác thực.", + "iflow_oauth_url_label": "URL ủy quyền:", + "iflow_open_link": "Mở liên kết", + "iflow_copy_link": "Sao chép liên kết", + "iflow_oauth_status_waiting": "Đang chờ xác thực...", + "iflow_oauth_status_success": "Xác thực thành công!", + "iflow_oauth_status_error": "Xác thực thất bại:", + "iflow_oauth_start_error": "Không thể bắt đầu iFlow OAuth:", + "iflow_oauth_polling_error": "Không thể kiểm tra trạng thái xác thực:", + "remote_access_disabled": "Phương thức đăng nhập này không khả dụng cho truy cập từ xa. Vui lòng truy cập từ localhost." + }, + "stats": { + "success": "Thành công", + "failure": "Thất bại" + }, + "status_bar": { + "success_short": "✓", + "failure_short": "✗", + "no_requests": "Không có yêu cầu" + }, + "logs": { + "title": "Trình xem Log", + "refresh_button": "Làm mới Log", + "clear_button": "Xóa Log", + "fullscreen_button": "Toàn màn hình", + "exit_fullscreen_button": "Thoát toàn màn hình", + "download_button": "Tải Log xuống", + "error_logs_modal_title": "Log yêu cầu lỗi", + "error_logs_description": "Chọn file log yêu cầu lỗi để mở hoặc tải xuống (chỉ được tạo khi tính năng ghi log yêu cầu đang tắt).", + "error_logs_request_log_enabled": "Ghi log yêu cầu đang bật nên danh sách này sẽ luôn trống. Hãy tắt ghi log yêu cầu và làm mới để xem log lỗi.", + "error_logs_empty": "Không tìm thấy file log yêu cầu lỗi nào", + "error_logs_load_error": "Không thể tải danh sách log lỗi", + "error_logs_size": "Kích thước", + "error_logs_modified": "Sửa lần cuối", + "error_logs_open": "Mở", + "error_logs_download": "Tải xuống", + "error_log_view_title": "Chi tiết Log yêu cầu lỗi", + "error_log_open_failed": "Không thể mở log lỗi", + "error_log_empty_content": "Log lỗi này trống", + "error_log_copy_success": "Đã sao chép nội dung log lỗi", + "error_log_download_success": "Đã tải log lỗi xuống thành công", + "request_log_download_title": "Tải xuống Log yêu cầu", + "request_log_download_confirm": "Tải xuống log yêu cầu của ID {{id}}?", + "request_log_download_success": "Đã tải log yêu cầu xuống thành công", + "empty_title": "Chưa có Log", + "empty_desc": "Khi bật \"Ghi log ra file\", log sẽ hiển thị tại đây", + "cpa_file_logging_required": "Runtime đang kết nối là CPA. Xem log yêu cầu bật ghi log ra file trước.", + "cpa_file_logging_required_title": "Cần bật ghi log ra file", + "cpa_file_logging_required_desc": "CPA đọc khung xem log này từ file log cục bộ. Hãy bật logging-to-file trong cấu hình rồi làm mới.", + "file_logging_required": "Endpoint log này cần bật ghi log ra file trước khi đọc được file log.", + "file_logging_required_title": "Cần bật ghi log ra file", + "file_logging_required_desc": "Endpoint log này đọc file log cục bộ. Hãy bật logging-to-file trong cấu hình rồi làm mới.", + "log_content": "Nội dung Log", + "loading": "Đang tải log...", + "load_error": "Không thể tải log", + "clear_confirm": "Bạn có chắc muốn xóa toàn bộ log? Thao tác này không thể hoàn tác!", + "clear_success": "Đã xóa log thành công", + "download_success": "Đã tải log xuống thành công", + "auto_refresh": "Tự động làm mới", + "load_more_hint": "Cuộn lên để tải thêm", + "hidden_lines": "Bị ẩn: {{count}} dòng", + "loaded_lines": "Đã tải: {{count}} dòng", + "filtered_lines": "Đã lọc: {{count}} dòng", + "hide_management_logs": "Ẩn log {{prefix}}", + "show_raw_logs": "Hiện Log thô", + "show_raw_logs_hint": "Hiện văn bản log gốc để dễ sao chép nhiều dòng", + "search_placeholder": "Tìm log theo nội dung hoặc từ khóa", + "filter_panel_title": "Bộ lọc cấu trúc", + "filter_panel_expand": "Mở bộ lọc cấu trúc", + "filter_panel_collapse": "Thu gọn bộ lọc cấu trúc", + "filter_panel_active_count": "{{count}} đang hoạt động", + "filter_method": "Phương thức", + "filter_status": "Trạng thái", + "filter_path": "Đường dẫn", + "filter_path_empty": "Không có ứng viên đường dẫn", + "filter_status_2xx": "2xx", + "filter_status_3xx": "3xx", + "filter_status_4xx": "4xx", + "filter_status_5xx": "5xx", + "clear_filters": "Xóa bộ lọc", + "search_empty_title": "Không tìm thấy log phù hợp", + "search_empty_desc": "Hãy thử từ khóa khác hoặc xóa bộ lọc.", + "double_click_copy_hint": "Nhấp đúp để sao chép dòng log thô", + "copy_success": "Đã sao chép log vào clipboard", + "copy_failed": "Sao chép thất bại" + }, + "config_management": { + "title": "Bảng cấu hình", + "meta_fields": "{{count}} cài đặt", + "meta_dirty": "{{count}} chưa lưu", + "meta_dirty_source": "Chỉnh sửa nguồn chưa lưu", + "meta_errors": "{{count}} lỗi xác thực", + "meta_synced": "Đã đồng bộ", + "actions": { + "discard": "Hủy thay đổi", + "save": "Lưu thay đổi" + }, + "discard_confirm_message": "Hủy mọi thay đổi chưa lưu và khôi phục phiên bản máy chủ gần nhất?", + "mode": { + "label": "Chế độ trình chỉnh sửa", + "visual": "Trực quan", + "source": "Mã nguồn" + }, + "reload": "Tải lại", + "reload_confirm_message": "Tải lại sẽ hủy các thay đổi chưa lưu của bạn. Bạn có muốn tiếp tục không?", + "save": "Lưu", + "status_loading": "Đang tải cấu hình...", + "status_loading_short": "Đang tải", + "status_loaded": "Đã tải cấu hình", + "status_loaded_short": "Đã tải", + "status_dirty": "Thay đổi chưa lưu", + "status_dirty_short": "Chưa lưu", + "status_disconnected": "Kết nối máy chủ để tải cấu hình", + "status_disconnected_short": "Mất kết nối", + "status_load_failed": "Tải thất bại", + "status_load_failed_short": "Thất bại", + "status_saving": "Đang lưu cấu hình...", + "status_saving_short": "Đang lưu", + "save_success": "Đã lưu cấu hình thành công", + "visual_mode_unavailable": "Trình chỉnh sửa trực quan không khả dụng cho đến khi sửa cú pháp YAML", + "visual_mode_unavailable_short": "Lỗi YAML", + "validation_blocked_short": "Sửa lỗi", + "visual_mode_unavailable_detail": "Trình chỉnh sửa trực quan không khả dụng vì cấu hình chứa YAML không hợp lệ: {{message}}", + "visual_mode_save_blocked": "Không thể lưu từ chế độ trực quan cho đến khi sửa cú pháp YAML", + "visual_mode_latest_yaml_invalid": "Cấu hình máy chủ mới nhất chứa YAML không hợp lệ. Hãy xem lại ở chế độ mã nguồn trước khi lưu thay đổi trực quan: {{message}}", + "editor_placeholder": "key: value", + "search_placeholder": "Tìm cấu hình...", + "search_button": "Tìm", + "search_no_results": "Không có kết quả", + "search_prev": "Trước", + "search_next": "Sau", + "diff": { + "title": "Xem lại thay đổi", + "confirm": "Xác nhận lưu", + "no_changes": "Không phát hiện thay đổi" + }, + "visual": { + "search": { + "placeholder": "Tìm cài đặt (nhãn hoặc key YAML)", + "no_results": "Không có cài đặt phù hợp" + }, + "sections": { + "common": { + "title": "Chung", + "description": "Các cài đặt dùng nhiều nhất, dùng chung dữ liệu với các mục đầy đủ" + }, + "connectivity": { + "title": "Truy cập & Xác thực", + "description": "Địa chỉ máy chủ, cổng, thư mục xác thực và API key" + }, + "logging": { + "title": "Ghi log & Chẩn đoán", + "description": "Debug, xuất log và thống kê sử dụng" + }, + "advanced": { + "title": "Nâng cao & Thử nghiệm", + "description": "Giả mạo header, cache chữ ký, nguồn plugin và các cài đặt ít thay đổi khác", + "plugins_title": "Plugin", + "signature_title": "Chữ ký Antigravity" + }, + "server": { + "host": "Địa chỉ Host", + "port": "Cổng" + }, + "tls": { + "title": "Cấu hình TLS/SSL", + "description": "Cài đặt kết nối HTTPS bảo mật", + "enable": "Bật TLS", + "enable_desc": "Bật kết nối HTTPS bảo mật", + "cert": "Đường dẫn file chứng chỉ", + "key": "Đường dẫn file khóa riêng" + }, + "remote": { + "title": "Quản lý từ xa", + "description": "Truy cập từ xa và cài đặt bảng điều khiển", + "allow_remote": "Cho phép truy cập từ xa", + "allow_remote_desc": "Cho phép truy cập quản lý từ máy chủ khác", + "disable_panel": "Tắt bảng điều khiển", + "disable_panel_desc": "Tắt bảng điều khiển web tích hợp", + "disable_auto_update_panel": "Tắt tự động cập nhật bảng điều khiển", + "disable_auto_update_panel_desc": "Tải bảng điều khiển khi thiếu lần đầu, nhưng không bao giờ tự cập nhật từ GitHub", + "secret_key": "Key quản lý", + "secret_key_placeholder": "Đặt key quản lý", + "panel_repo": "Repository bảng điều khiển" + }, + "auth": { + "auth_dir": "Thư mục xác thực (auth-dir)", + "auth_dir_hint": "Đường dẫn thư mục chứa file xác thực (hỗ trợ ~)" + }, + "system": { + "debug": "Chế độ Debug", + "debug_desc": "Bật ghi log debug chi tiết", + "commercial_mode": "Chế độ thương mại", + "commercial_mode_desc": "Tắt middleware tốn tài nguyên để hỗ trợ đồng thời cao", + "logging_to_file": "Ghi log ra file", + "logging_to_file_desc": "Lưu log vào file", + "plugins_enabled": "Bật hệ thống Plugin", + "plugins_enabled_desc": "Bật nạp plugin thư viện động chuẩn; từng phiên bản plugin vẫn được quản lý ở trang Plugin", + "plugin_store_sources": "Nguồn Plugin bên thứ ba", + "plugin_store_sources_desc": "Thêm nguồn registry plugin store; nguồn chính thức tích hợp luôn được giữ", + "plugin_store_sources_label": "URL registry nguồn plugin (plugins.store-sources)", + "plugin_store_sources_placeholder": "https://example.com/cliproxy-plugins/registry.json", + "plugin_store_sources_hint": "Mỗi dòng một URL registry.json. Dòng trống sẽ bị lọc khi lưu", + "plugin_store_auth": "Quy tắc xác thực Plugin Store", + "plugin_store_auth_desc": "Cấu hình header xác thực cho registry riêng tư, metadata GitHub Release hoặc tải artifact", + "plugin_store_auth_hint": "Chỉ nhập tên biến môi trường, không nhập token thật. Backend đọc giá trị từ môi trường runtime của nó.", + "store_auth_empty": "Chưa cấu hình quy tắc xác thực nào. Nguồn plugin công khai không cần.", + "store_auth_rule": "Quy tắc xác thực", + "store_auth_add": "Thêm quy tắc xác thực", + "store_auth_match": "Tiền tố URL khớp", + "store_auth_type": "Loại xác thực", + "store_auth_apply_to": "Áp dụng cho", + "store_auth_apply_to_hint": "Khi không chọn gì, quy tắc áp dụng cho mọi loại yêu cầu.", + "store_auth_apply_registry": "Registry", + "store_auth_apply_metadata": "Metadata", + "store_auth_apply_artifact": "Artifact", + "store_auth_type_none": "Không", + "store_auth_type_bearer": "Bearer", + "store_auth_type_basic": "Basic", + "store_auth_type_header": "Header tùy chỉnh", + "store_auth_type_github_token": "GitHub token", + "store_auth_token_env": "Biến môi trường token", + "store_auth_username_env": "Biến môi trường tên đăng nhập", + "store_auth_password_env": "Biến môi trường mật khẩu", + "store_auth_header_name": "Tên header", + "store_auth_header_value_env": "Biến môi trường giá trị header", + "store_auth_allow_insecure": "Cho phép URL HTTP không bảo mật", + "logs_max_size": "Giới hạn kích thước file log (MB)", + "error_logs_max_files": "Số file log lỗi giữ lại", + "usage_statistics_enabled": "Bật thống kê sử dụng trong bộ nhớ", + "usage_statistics_enabled_desc": "Tổng hợp thống kê sử dụng yêu cầu trong bộ nhớ", + "redis_usage_retention": "Thời gian giữ hàng đợi sử dụng Redis (giây)", + "redis_usage_retention_hint": "Thời gian giữ trong bộ nhớ cho đầu ra sử dụng RESP LPOP/RPOP, tối đa 3600 giây", + "antigravity_signature_cache": "Bật cache chữ ký Antigravity", + "antigravity_signature_cache_desc": "Ưu tiên và xác thực chữ ký thinking-block đã cache", + "antigravity_signature_strict": "Bỏ qua xác thực chữ ký nghiêm ngặt", + "antigravity_signature_strict_desc": "Chỉ áp dụng khi cache chữ ký bị tắt; xác thực toàn bộ cây protobuf Claude" + }, + "headers": { + "title": "Header mặc định", + "description": "Header mặc định cho yêu cầu OAuth Claude và Codex khi client không gửi", + "claude_title": "Header mặc định Claude", + "codex_title": "Header mặc định Codex", + "user_agent": "User-Agent", + "package_version": "Phiên bản gói", + "runtime_version": "Phiên bản runtime", + "os": "Hệ điều hành", + "arch": "Kiến trúc", + "timeout": "Timeout", + "stabilize_device": "Ổn định hồ sơ thiết bị", + "stabilize_device_desc": "Cố định OS/Kiến trúc và ổn định vân tay phần mềm theo từng credential/API key", + "beta_features": "Tính năng Beta" + }, + "network": { + "title": "Cấu hình mạng", + "description": "Cài đặt proxy, thử lại và định tuyến", + "proxy_url": "URL Proxy", + "request_retry": "Số lần thử lại yêu cầu", + "max_retry_credentials": "Số credential thử lại tối đa", + "max_retry_credentials_hint": "Để trống nếu không muốn đặt. Đặt 0 để giữ hành vi cũ và thử mọi credential khả dụng.", + "max_retry_interval": "Khoảng thử lại tối đa (giây)", + "auth_auto_refresh_workers": "Số worker tự làm mới xác thực", + "auth_auto_refresh_workers_hint": "Khi lớn hơn 0, ghi đè số worker mặc định (16)", + "disable_image_generation": "Tắt tạo ảnh", + "disable_image_generation_hint": "false để bật; true tắt toàn bộ tạo ảnh; chat tắt inject endpoint phi ảnh; passthrough giữ danh sách tool của client mà không inject", + "disable_image_generation_false": "false (đang bật)", + "disable_image_generation_true": "true (tắt ở mọi nơi)", + "disable_image_generation_chat": "chat (chỉ tắt inject trong chat)", + "disable_image_generation_passthrough": "passthrough (giữ danh sách tool của client)", + "gpt_image_2_base_model": "Model gốc GPT Image 2", + "gpt_image_2_base_model_hint": "Model chính dùng khi proxy yêu cầu ảnh gpt-image-2; backend dùng mặc định nếu trống hoặc không hợp lệ", + "routing_strategy": "Chiến lược định tuyến", + "routing_strategy_hint": "Chọn chiến lược lựa chọn credential", + "strategy_round_robin": "Round Robin", + "strategy_weighted_round_robin": "Weighted Round Robin", + "strategy_fill_first": "Fill First", + "session_affinity_ttl": "TTL Session Affinity", + "force_model_prefix": "Bắt buộc tiền tố model", + "force_model_prefix_desc": "Yêu cầu model không có tiền tố chỉ dùng credential không có tiền tố", + "passthrough_headers": "Chuyển tiếp Header upstream", + "passthrough_headers_desc": "Chuyển tiếp header phản hồi upstream đã lọc đến client downstream", + "disable_cooling": "Tắt Cooling", + "disable_cooling_desc": "Tắt toàn cục cửa sổ cooldown auth/model sau thất bại", + "session_affinity": "Định tuyến Session Affinity", + "ws_auth": "Xác thực WebSocket", + "ws_auth_desc": "Bật xác thực WebSocket (/v1/ws)" + }, + "quota": { + "title": "Quota dự phòng", + "description": "Chiến lược dự phòng khi vượt quota", + "switch_project": "Chuyển Project", + "switch_project_desc": "Tự động chuyển sang project khác khi vượt quota", + "switch_preview_model": "Chuyển sang model Preview", + "switch_preview_model_desc": "Chuyển sang phiên bản model preview khi vượt quota", + "antigravity_credits": "Dùng credit Antigravity" + }, + "streaming": { + "title": "Cấu hình Streaming", + "description": "Cài đặt keepalive và thử lại bootstrap", + "keepalive_seconds": "Số giây Keepalive", + "keepalive_hint": "Đặt 0 hoặc để trống để tắt keepalive", + "bootstrap_retries": "Số lần thử Bootstrap", + "bootstrap_hint": "Số lần thử lại khi khởi động stream (trước byte đầu tiên)", + "nonstream_keepalive": "Khoảng keepalive phi stream (giây)", + "nonstream_keepalive_hint": "Gửi dòng trống mỗi N giây cho phản hồi phi stream để tránh timeout nhàn rỗi, đặt 0 hoặc để trống để tắt", + "disabled": "Đã tắt" + }, + "payload": { + "title": "Cấu hình Payload", + "description": "Giá trị mặc định, quy tắc JSON thô, quy tắc ghi đè và quy tắc lọc", + "default_rules": "Quy tắc mặc định", + "default_rules_desc": "Dùng các giá trị mặc định này khi tham số không được chỉ định trong yêu cầu", + "default_raw_rules": "Quy tắc thô mặc định", + "default_raw_rules_desc": "Khi thiếu tham số, ghi các giá trị này dưới dạng đoạn JSON thô như true, 123, \"high\" hoặc {\"type\":\"object\"}", + "override_rules": "Quy tắc ghi đè", + "override_rules_desc": "Bắt buộc ghi đè giá trị tham số trong yêu cầu", + "override_raw_rules": "Quy tắc thô ghi đè", + "override_raw_rules_desc": "Luôn ghi đè giá trị tham số dưới dạng đoạn JSON thô, hữu ích cho response_format, schema và các trường phức tạp khác", + "filter_rules": "Quy tắc lọc", + "filter_rules_desc": "Lọc trước body yêu cầu upstream qua JSON Path, tự động loại bỏ tham số không tuân thủ/dư thừa (Làm sạch yêu cầu)" + } + }, + "api_keys": { + "label": "Danh sách API Key (api-keys)", + "add": "Thêm API Key", + "generate": "Tạo", + "empty": "Chưa có API key", + "hint": "Mỗi mục là một API key (nhất quán với phong cách trang 'Quản lý API Key')", + "edit_title": "Chỉnh sửa API Key", + "add_title": "Thêm API Key", + "input_label": "API Key", + "input_placeholder": "Dán API key của bạn", + "input_hint": "Chỉ sửa nội dung file cấu hình cục bộ, không đồng bộ sang giao diện Quản lý API Key", + "error_empty": "Vui lòng nhập API key", + "error_invalid": "API key chứa ký tự không hợp lệ", + "strength": { + "label": "Độ mạnh API key", + "empty": "Chưa nhập", + "weak": "Yếu", + "fair": "Khá", + "good": "Tốt", + "strong": "Mạnh" + } + }, + "payload_rules": { + "rule": "Quy tắc", + "models": "Model áp dụng", + "model_name": "Tên model", + "provider_type": "Loại Provider", + "add_model": "Thêm model", + "params": "Cài đặt tham số", + "remove_params": "Xóa tham số", + "json_path": "JSON Path (ví dụ temperature)", + "json_path_filter": "JSON Path (gjson/sjson), ví dụ generationConfig.thinkingConfig.thinkingBudget", + "param_type": "Loại tham số", + "param_value": "Giá trị tham số", + "add_param": "Thêm tham số", + "no_rules": "Chưa có quy tắc", + "add_rule": "Thêm quy tắc", + "provider_default": "Mặc định", + "provider_openai": "OpenAI", + "provider_openai_response": "OpenAI Response", + "provider_responses": "Responses", + "provider_gemini": "Gemini", + "provider_claude": "Claude", + "provider_codex": "Codex", + "provider_antigravity": "Antigravity", + "advanced": "Nâng cao", + "hide_advanced": "Ẩn nâng cao", + "from_protocol": "Giao thức nguồn (from-protocol)", + "headers": "Khớp Header yêu cầu", + "header_name": "Tên Header", + "header_value": "Giá trị Header", + "add_header": "Thêm Header", + "match": "Khớp bắt buộc (match)", + "notMatch": "Khớp cấm (not-match)", + "exist": "Đường dẫn bắt buộc (exist)", + "notExist": "Đường dẫn cấm (not-exist)", + "condition_path": "Đường dẫn khớp", + "condition_value": "Giá trị khớp", + "add_condition": "Thêm điều kiện", + "value_type_string": "Chuỗi", + "value_type_number": "Số", + "value_type_boolean": "Boolean", + "value_type_json": "JSON", + "value_string": "Giá trị chuỗi", + "value_number": "Giá trị số (ví dụ 0.7)", + "value_boolean": "true hoặc false", + "value_json": "Giá trị JSON", + "value_raw_json": "Đoạn JSON thô, ví dụ true, 123, \"high\" hoặc {\"type\":\"object\"}", + "value_default": "Giá trị", + "boolean_true": "true", + "boolean_false": "false" + }, + "validation": { + "validation_blocked": "Hãy sửa lỗi xác thực trước khi lưu", + "port_range": "Nhập cổng hợp lệ từ 1 đến 65535", + "non_negative_integer": "Nhập số nguyên không âm", + "integer_range_1_3600": "Nhập số nguyên từ 1 đến 3600", + "payload_invalid_number": "Nhập số hợp lệ", + "payload_invalid_boolean": "Chọn true hoặc false", + "payload_invalid_json": "Nhập JSON hợp lệ" + }, + "common": { + "edit": "Chỉnh sửa", + "delete": "Xóa", + "cancel": "Hủy", + "update": "Cập nhật", + "add": "Thêm" + } + } + }, + "quota_management": { + "title": "Quản lý Quota", + "description": "Theo dõi trạng thái quota OAuth của credential Antigravity, Codex, Claude, Kimi và xAI.", + "refresh_all_credentials": "Làm mới mọi credential", + "sort_label": "Sắp xếp", + "sort_default": "Mặc định", + "sort_soonest": "Sớm khôi phục nhất", + "meta_credentials": "{{count}} credential", + "meta_loaded": "{{count}} đã tải", + "meta_attention": "{{count}} cần chú ý", + "empty_title": "Không có credential hỗ trợ quota", + "empty_desc": "Kết nối credential Antigravity, Claude, Codex, xAI hoặc Kimi để theo dõi quota tại đây.", + "windows_title": "Cửa sổ quota", + "windows_span_weekly": "hai tuần", + "windows_span_session": "ba ngày", + "windows_current": "hiện tại", + "windows_today": "Hôm nay", + "windows_prev": "Trước", + "windows_next": "Sau", + "windows_mode_weekly": "Tuần", + "windows_mode_session": "5 giờ", + "windows_credential": "Credential", + "windows_idle": "không có cửa sổ nào đang đếm ngược", + "windows_empty_session": "Không có credential nào trên trang này báo cáo cửa sổ quota 5 giờ.", + "windows_legend_current": "cửa sổ hiện tại", + "windows_legend_upcoming": "sắp tới", + "windows_legend_elapsed": "đã trôi qua", + "windows_legend_reset_credit": "hết hạn đặt lại thủ công", + "soonest_row_hint": "Khôi phục sớm nhất trên credential này", + "windows_reset_credit": "Đặt lại thủ công", + "windows_credit_granted": "Được cấp", + "windows_credit_expires": "Hết hạn", + "windows_note_weekly": "Mỗi thanh là một cửa sổ quota đầy đủ, vẽ từ lúc mở đến lúc đặt lại. Các làn kết thúc cùng lúc sẽ cạnh tranh cùng ngày.", + "windows_note_session": "Mỗi thanh là một cửa sổ 5 giờ. Chỉ credential có cửa sổ đang đếm ngược mới được dự báo; các credential khác để trống thay vì bịa đặt.", + "weekday_sun": "CN", + "weekday_mon": "T2", + "weekday_tue": "T3", + "weekday_wed": "T4", + "weekday_thu": "T5", + "weekday_fri": "T6", + "weekday_sat": "T7" + }, + "plugin_management": { + "title": "Quản lý Plugin", + "description": "Xem plugin đã phát hiện và đăng ký, sau đó quản lý bật/tắt phiên bản, trường cấu hình và liên kết tài nguyên.", + "refresh": "Làm mới", + "load_failed": "Không thể tải plugin", + "config_load_failed": "Không thể đọc cấu hình plugin", + "config_not_found": "Không thể đọc cấu hình plugin vì backend không tìm thấy plugin này.", + "unsupported_backend": "Backend hiện tại không cung cấp API quản lý plugin. Hãy dùng bản backend mới hơn có endpoint quản lý plugin, sau đó khởi động lại dịch vụ.", + "global_status": "Trạng thái toàn cục", + "global_enabled": "Đang bật", + "global_disabled": "Đã tắt", + "global_disabled_hint": "plugins.enabled đang là false nên phiên bản plugin đã bật sẽ không có hiệu lực.", + "plugins_dir": "Thư mục plugin", + "discovered": "Đã phát hiện", + "effective": "Có hiệu lực", + "search_placeholder": "Tìm ID, tên, tác giả hoặc tài nguyên plugin...", + "search_label": "Tìm plugin", + "no_plugins": "Không có plugin", + "no_plugins_desc": "Không tìm thấy plugin nào trong thư mục plugin hoặc registry runtime.", + "configured": "Đã cấu hình", + "not_configured": "Chưa cấu hình", + "registered": "Đã đăng ký", + "not_registered": "Chưa đăng ký", + "oauth": "OAuth", + "status_effective": "Có hiệu lực", + "status_inactive": "Không hoạt động", + "edit_config": "Chỉnh sửa cấu hình", + "open_repository": "Mở repository", + "config_title": "Cấu hình {{name}}", + "base_settings": "Cài đặt cơ bản", + "enabled": "Đang bật", + "enabled_hint": "Điều khiển trường enabled của phiên bản plugin này trong plugins.configs.", + "priority": "Ưu tiên", + "config_fields": "Trường cấu hình", + "no_config_fields": "Plugin này không khai báo trường cấu hình trực quan.", + "select_placeholder": "Chọn", + "array_item_placeholder": "Nhập phần tử mảng", + "add_array_item": "Thêm phần tử mảng", + "remove_array_item": "Xóa phần tử mảng", + "delete_plugin": "Xóa", + "delete_confirm_title": "Xóa plugin", + "delete_confirm_message": "Xóa {{name}} ({{id}})? Thao tác này sẽ xóa file plugin cục bộ và cấu hình đã lưu.", + "delete_success": "Đã xóa plugin", + "delete_failed": "Không thể xóa plugin", + "delete_restart_required": "Plugin đã nạp không thể bị xóa cho đến khi backend khởi động lại.", + "toggle_success": "Đã cập nhật trạng thái plugin", + "toggle_failed": "Không thể cập nhật trạng thái plugin", + "runtime_pending": "Thay đổi plugin đã lưu nhưng trạng thái runtime vẫn đang chờ. Hãy làm mới sau hoặc kiểm tra log backend.", + "save_success": "Đã lưu cấu hình plugin", + "save_failed": "Không thể lưu cấu hình plugin", + "validation_failed": "Hãy sửa lỗi form cấu hình plugin trước", + "invalid_priority": "Nhập mức ưu tiên là số nguyên", + "invalid_number": "Nhập số hợp lệ", + "invalid_integer": "Nhập số nguyên hợp lệ", + "invalid_json": "Nhập JSON hợp lệ", + "expected_array": "Nhập mảng JSON", + "expected_object": "Nhập đối tượng JSON", + "invalid_enum": "Chọn một trong các giá trị enum đã khai báo" + }, + "plugin_store": { + "title": "Cửa hàng Plugin", + "description": "Duyệt registry plugin, sau đó cài đặt hoặc cập nhật plugin cho backend hiện tại.", + "description_show_more": "Hiện thêm", + "description_show_less": "Ẩn bớt", + "source_name": "Nguồn: {{source}}", + "cli_proxy_api_source": "Nguồn CLIProxyAPI", + "refresh": "Làm mới", + "retry": "Thử lại", + "load_failed": "Không thể tải cửa hàng plugin", + "unsupported_backend": "Backend hiện tại không cung cấp API plugin store. Hãy dùng bản backend mới hơn có endpoint plugin store, sau đó khởi động lại dịch vụ.", + "registry_failed": "Không thể kết nối registry plugin", + "global_status": "Trạng thái toàn cục", + "global_enabled": "Đang bật", + "global_disabled": "Đã tắt", + "global_disabled_hint": "plugins.enabled đang là false nên plugin đã cài sẽ không có hiệu lực.", + "plugins_dir": "Thư mục plugin", + "stat_available": "Khả dụng", + "search_placeholder": "Tìm ID, tên, tác giả hoặc tag plugin...", + "search_label": "Tìm cửa hàng plugin", + "filter_label": "Lọc theo trạng thái cài đặt", + "filter_all": "Tất cả", + "filter_installed": "Đã cài", + "filter_not_installed": "Chưa cài", + "filter_updates": "Có bản cập nhật", + "badge_installed": "Đã cài", + "badge_update": "Có bản cập nhật", + "badge_effective": "Có hiệu lực", + "version_arrow": "v{{from}} → v{{to}}", + "install_type": "Cài đặt: {{type}}", + "platforms": "Nền tảng: {{platforms}}", + "auth_required": "Cần xác thực", + "auth_configured": "Đã cấu hình xác thực", + "auth_required_hint": "Hãy cấu hình plugins.store-auth trước khi cài từ nguồn hoặc URL artifact này", + "source_errors_title": "Một số nguồn plugin không tải được", + "install": "Cài đặt", + "update": "Cập nhật", + "manage": "Quản lý", + "install_confirm_title": "Cài đặt plugin", + "install_confirm_message": "Tải {{target}} từ registry plugin và cài vào thư mục plugin cục bộ?", + "update_confirm_title": "Cập nhật plugin", + "update_confirm_message": "Tải và cài đặt {{target}}?", + "install_version_label": "Phiên bản", + "install_version_latest": "mới nhất", + "install_version_latest_mode": "Bản ổn định mới nhất", + "install_version_latest_hint": "Backend sẽ phân giải khi cài đặt. Phiên bản đang niêm yết: {{version}}.", + "install_version_release_mode": "Chọn bản phát hành", + "install_version_release_hint": "Đọc các tag cài được từ GitHub Releases.", + "install_version_manual_mode": "Tag phát hành thủ công", + "install_version_manual_hint": "Chỉ dùng khi không thể tự động tải danh sách bản phát hành.", + "install_versions_loading": "Đang tải GitHub Releases...", + "install_versions_load_failed": "Không thể tải danh sách phiên bản phát hành", + "install_version_non_github": "Repository plugin này không phải repository GitHub", + "install_versions_empty": "Không tìm thấy bản phát hành nào chọn được.", + "install_versions_only_prerelease": "Chỉ có phiên bản prerelease. Hãy hiện prerelease để chọn.", + "install_version_release_select": "Chọn phiên bản phát hành", + "install_version_release_placeholder": "Chọn phiên bản phát hành", + "install_version_prerelease_badge": "prerelease", + "install_version_assets_count": "{{count}} asset", + "install_version_show_prerelease": "Hiện phiên bản prerelease", + "install_version_manual_placeholder": "Ví dụ v0.1.4", + "install_version_manual_error": "Tag phát hành chỉ được chứa chữ cái, chữ số, dấu chấm, gạch dưới, dấu cộng và dấu gạch nối; không cho phép khoảng trắng và dấu gạch chéo.", + "install_version_current_selected": "{{version}} đã được cài. Hãy chọn phiên bản khác.", + "install_version_releases_link": "Xem GitHub Releases", + "install_success": "Đã cài đặt plugin", + "update_success": "Đã cập nhật plugin", + "install_failed": "Không thể cài đặt plugin", + "update_failed": "Không thể cập nhật plugin", + "status_pending": "File plugin đã cập nhật nhưng trạng thái cục bộ chưa làm mới. Hãy làm mới sau hoặc kiểm tra log backend.", + "registration_pending": "File plugin đã cập nhật nhưng việc đăng ký vẫn đang chờ. Hãy làm mới sau hoặc kiểm tra log backend.", + "restart_required_notice": "Khởi động lại dịch vụ để nạp phiên bản plugin mới", + "restart_required_banner": "Khởi động lại dịch vụ để áp dụng phiên bản mới của: {{plugins}}", + "open_repository": "Mở repository", + "open_homepage": "Mở trang chủ", + "no_plugins": "Registry trống", + "no_plugins_desc": "Registry plugin không trả về plugin nào.", + "no_matches": "Không có plugin phù hợp", + "no_matches_desc": "Không có plugin nào khớp tìm kiếm hoặc bộ lọc hiện tại.", + "clear_filters": "Xóa bộ lọc", + "security_banner_title": "Plugin bên thứ ba chạy với toàn quyền truy cập backend", + "security_banner_text": "Plugin thực thi mã bên trong dịch vụ proxy và có thể đọc credential cũng như lưu lượng của bạn. Chỉ cài plugin bạn tin tưởng — đặc biệt cẩn thận với plugin không do tổ chức chính thức router-for-me phát hành.", + "badge_untrusted": "Bên thứ ba", + "gate_title": "Cài đặt {{name}}", + "gate_title_update": "Cập nhật {{name}}", + "gate_warning": "Những điều bất ngờ và gây hại có thể xảy ra nếu bạn không đọc phần này.", + "gate_effect_runs_code": "Plugin này sẽ chạy mã bên thứ ba chưa được kiểm định trong backend proxy của bạn. Hệ thống không thể cô lập hay kiểm toán hành vi của nó, và nó có thể truy cập credential nhạy cảm, yêu cầu mạng và dữ liệu phản hồi của bạn.", + "gate_effect_no_review": "Plugin này không được tổ chức chính thức router-for-me phát hành hay đánh giá. Tổ chức chính thức không bảo hành rõ ràng hay ngụ ý về tính ổn định, bảo mật, tuân thủ hay bất kỳ thay đổi hành vi nào trong các phiên bản tương lai của plugin này.", + "gate_effect_restart": "Cài đặt sẽ thay đổi thư mục plugin cục bộ và có thể cần khởi động lại dịch vụ để có hiệu lực.", + "gate_untrusted_alert": "Plugin này không thuộc tổ chức chính thức router-for-me. Chỉ tiếp tục nếu bạn hoàn toàn tin tưởng tác giả và nguồn của nó.", + "gate_repository_label": "Repository", + "gate_source_label": "Nguồn", + "gate_step1_action": "Tôi muốn cài plugin này", + "gate_step2_action": "Tôi đã đọc và hiểu các rủi ro này", + "gate_step3_prompt": "Để xác nhận, nhập \"{{token}}\" vào ô bên dưới", + "gate_step3_action": "Cài đặt plugin này", + "gate_step3_hint": "Nhập chính xác mã định danh hiển thị ở trên để cho phép cài đặt." + }, + "plugin_resource": { + "page_count": "{{count}} trang", + "load_failed": "Không thể tải trang plugin", + "unavailable": "Trang plugin không khả dụng", + "not_found": "Không tìm thấy trang plugin", + "not_found_desc": "Trang plugin này không được khai báo trong danh sách plugin backend hiện tại.", + "empty_src": "URL trang plugin trống", + "empty_src_desc": "Menu plugin này không cung cấp URL trang nhúng được." + }, + "system_info": { + "title": "Thông tin Trung tâm Quản lý", + "about_title": "Trung tâm Quản lý CLI Proxy API", + "models_title": "Model khả dụng", + "models_desc": "Hiển thị phản hồi /models và tự động dùng API key đã lưu để xác thực.", + "models_loading": "Đang tải model khả dụng...", + "models_empty": "/models không trả về model nào", + "models_error": "Không thể tải danh sách model", + "models_count": "{{count}} model khả dụng", + "version_check_button": "Kiểm tra cập nhật", + "version_update_available": "Có bản cập nhật: {{version}}", + "version_is_latest": "Bạn đang dùng phiên bản mới nhất", + "version_check_error": "Kiểm tra cập nhật thất bại", + "version_current_missing": "Không có phiên bản máy chủ; không thể so sánh", + "version_unknown": "Không rõ", + "quick_links_title": "Liên kết nhanh", + "quick_links_desc": "Truy cập repository dự án và tài liệu để được trợ giúp và cập nhật.", + "link_main_repo": "Repository chính", + "link_main_repo_desc": "Mã nguồn chương trình lõi CLI Proxy API", + "link_webui_repo": "Repository WebUI", + "link_webui_repo_desc": "Mã nguồn frontend Trung tâm Quản lý", + "link_docs": "Tài liệu", + "link_docs_desc": "Hướng dẫn và tutorial cấu hình", + "clear_login_title": "Dữ liệu đăng nhập cục bộ", + "clear_login_desc": "Xóa dữ liệu đăng nhập đã lưu cục bộ và đăng xuất.", + "clear_login_button": "Xóa dữ liệu đăng nhập", + "clear_login_confirm": "Xóa dữ liệu đăng nhập cục bộ và đăng xuất ngay?" + }, + "notification": { + "request_log_updated": "Đã cập nhật cài đặt ghi log yêu cầu", + "login_storage_cleared": "Đã xóa dữ liệu đăng nhập cục bộ", + "data_refreshed": "Đã làm mới dữ liệu thành công", + "connection_required": "Vui lòng thiết lập kết nối trước", + "refresh_failed": "Làm mới thất bại", + "update_failed": "Cập nhật thất bại", + "add_failed": "Thêm thất bại", + "delete_failed": "Xóa thất bại", + "upload_failed": "Tải lên thất bại", + "download_failed": "Tải xuống thất bại", + "login_failed": "Đăng nhập thất bại", + "commercial_mode_restart_required": "Đã đổi cài đặt chế độ thương mại. Vui lòng khởi động lại dịch vụ để có hiệu lực", + "copy_failed": "Sao chép thất bại", + "link_copied": "Đã sao chép liên kết vào clipboard" + }, + "language": { + "switch": "Ngôn ngữ", + "chinese": "中文", + "chinese_tw": "繁體中文(台灣)", + "english": "English", + "russian": "Русский", + "vietnamese": "Tiếng Việt" + }, + "theme": { + "switch": "Giao diện", + "light": "Giấy len", + "white": "Trắng tinh", + "dark": "Tối", + "auto": "Theo hệ thống" + }, + "sidebar": { + "toggle_expand": "Mở rộng thanh bên", + "toggle_collapse": "Thu gọn thanh bên", + "expand": "Mở rộng", + "collapse": "Thu gọn", + "subtitle": "Bảng điều khiển CLI Proxy API", + "auth_files_count": "File xác thực: {{count}}" + }, + "footer": { + "api_version": "Phiên bản CLI Proxy API", + "build_date": "Thời gian build", + "version": "Phiên bản giao diện quản lý" + }, + "providersPage": { + "header": { + "title": "AI Provider", + "activeResources": "{{active}}/{{total}} tài nguyên đang hoạt động", + "providerFamilies": "{{count}} nhóm provider", + "updatedAt": "Cập nhật {{time}}" + }, + "actions": { + "refresh": "Làm mới", + "syncing": "Đang đồng bộ", + "new": "Mới", + "edit": "Chỉnh sửa", + "view": "Xem", + "delete": "Xóa", + "cancel": "Hủy", + "save": "Lưu", + "create": "Tạo", + "enable": "Bật", + "disable": "Tắt" + }, + "categories": { + "title": "Provider", + "quickFill": "Điền nhanh", + "activeCount": "{{active}}/{{total}} đang hoạt động" + }, + "providerNames": { + "gemini": "Gemini", + "interactions": "Interactions API", + "codex": "Codex", + "xai": "xAI", + "claude": "Claude", + "claudeApi": "ClaudeAPI", + "vertex": "Vertex", + "openaiCompatibility": "Tương thích OpenAI", + "apikeyFun": "APIKEY.FUN", + "code0": "Code0", + "fennoAI": "FennoAI", + "qiniuCloud": "Qiniu Cloud", + "lmuAI": "LMU AI (Linhmou AI)", + "infistar": "Infistar", + "kimi": "Kimi" + }, + "table": { + "key": "Key", + "baseUrl": "Base URL", + "prefix": "Tiền tố", + "models": "Model/Header", + "status": "Trạng thái", + "actions": "Hành động", + "metrics": { + "models": "Model", + "keys": "Key", + "headers": "Header" + }, + "websocketsTag": "WebSocket", + "cloakTag": "Cloak", + "empty": "Chưa có tài nguyên nào, nhấn \"Mới\" để thêm.", + "filterPlaceholder": "Tìm key, URL, tiền tố…", + "description": "Quản lý tài nguyên trong {{route}}" + }, + "sponsor": { + "protocolSummary": "Anthropic / OpenAI / Gemini / Codex API (Responses)", + "detailHint": "{{provider}} được lưu vào cấu hình API key tương ứng theo giao thức; khung xem này quản lý chúng cùng nhau.", + "registerLink": "Đăng ký tại đây", + "registerNow": "Đăng ký ngay", + "dashboardLink": "Bảng điều khiển", + "emptyRegisterHint": "Chưa có cấu hình nào.", + "apiKeyHint": "Key này chỉ được ghi vào cấu hình nhóm/giao thức đã chọn.", + "usageCheck": "Kiểm tra mức sử dụng", + "usageChecking": "Đang kiểm tra", + "usageRemaining": "Còn lại: {{amount}} {{unit}}", + "usageBreakdown": "Đã dùng {{used}} / Giới hạn {{limit}}", + "usageStatus": "Trạng thái: {{status}}", + "usageInvalid": "Key không hợp lệ", + "usageEmpty": "Endpoint không trả về dữ liệu sử dụng nào.", + "usageApiKeyRequired": "Cần có API key", + "aggregationConflict": "Provider được nhóm này chứa nhiều cấu hình backend hoặc key OpenAI. Hãy chỉnh trong cấu hình nguồn để tránh mất dữ liệu.", + "partialMutationWarning": "Thao tác thất bại sau khi một hoặc nhiều giao thức có thể đã được cập nhật. Cấu hình mới nhất đã được tải lại; hãy xem lại trước khi thử lại.", + "groupedKeysTitle": "Key được nhóm", + "groupedKeysHint": "Key nền tảng có thể được gắn vào nhóm khi tạo. Mỗi key được nhóm tại đây quản lý một giao thức, và khám phá model chỉ dùng giao thức đó.", + "groupedKey": "Key được nhóm #{{index}}", + "addGroupedKey": "Thêm key được nhóm", + "removeGroupedKey": "Xóa key được nhóm", + "protocol": "Nhóm/giao thức", + "protocolHint": "Chọn nhóm/giao thức cho key này.", + "protocolEndpoint": "Endpoint giao thức hiện tại", + "urlMode": "URL {{provider}}", + "urlHint": "Mọi URL dùng cùng quy ước API. Lưu chỉ ghi endpoint của giao thức được nhóm hiện tại.", + "urlOptions": { + "standard": "URL chuẩn", + "direct": "URL trực tiếp", + "domestic": "Tuyến Trung Quốc đại lục", + "overseas": "Tuyến nước ngoài", + "mainlandChina": "Trung Quốc đại lục (khuyến nghị)", + "global": "Toàn cầu" + }, + "urlOptionDescriptions": { + "domestic": "Dành cho người dùng và khối lượng công việc tại Trung Quốc đại lục; thường có độ trễ thấp hơn trên mạng đại lục.", + "overseas": "Dành cho triển khai nước ngoài, truy cập xuyên biên giới hoặc khối lượng công việc cần model nước ngoài.", + "mainlandChinaRecommended": "Khuyến nghị cho người dùng và khối lượng công việc trên mạng Trung Quốc đại lục.", + "global": "Dành cho người dùng và khối lượng công việc ở mọi khu vực khác." + }, + "modelsTitle": "Cài đặt model giao thức", + "modelsHint": "Cấu hình danh sách cho phép hoặc bí danh model riêng cho các tuyến Codex API, Anthropic, Gemini và tương thích OpenAI.", + "protocolModels": { + "codex": "Model Codex API", + "anthropic": "Model Anthropic", + "gemini": "Model Gemini", + "openai": "Model tương thích OpenAI" + }, + "protocolModelHints": { + "codex": "Ghi vào cấu hình model Codex API. Lấy từ /v1/models và đặt bí danh nếu cần.", + "anthropic": "Ghi vào cấu hình model Anthropic. Lấy từ /v1/models và đặt bí danh nếu cần.", + "gemini": "Ghi vào cấu hình model Gemini. Lấy từ /v1beta/models và đặt bí danh nếu cần.", + "openai": "Ghi vào cấu hình model tương thích OpenAI. Lấy từ /models và đặt bí danh nếu cần." + }, + "validation": { + "keyRequired": "Nhập API key cho mọi key được nhóm.", + "protocolDuplicate": "Mỗi giao thức chỉ có một key được nhóm." + }, + "openaiEntries": "Key tương thích OpenAI", + "codexEntries": "Key Codex API", + "anthropicEntries": "Key Anthropic", + "geminiEntries": "Key Gemini", + "protocols": { + "anthropic": "Anthropic", + "openai": "Tương thích OpenAI", + "gemini": "Gemini", + "codexResponses": "Codex API (Responses)" + } + }, + "status": { + "active": "Đang hoạt động", + "disabled": "Đã tắt", + "notSet": "Chưa đặt", + "none": "Không", + "notConfigured": "Chưa cấu hình", + "defaultSuffix": "(mặc định)" + }, + "detail": { + "title": "Chi tiết", + "metadataTitle": "Metadata", + "fields": { + "identifier": "Định danh", + "baseUrl": "Base URL", + "proxyUrl": "URL Proxy", + "prefix": "Tiền tố", + "models": "Model", + "headers": "Header", + "authIndex": "Chỉ mục xác thực", + "excludedModels": "Model bị loại trừ", + "apiKeyEntries": "Mục API key" + } + }, + "form": { + "createEyebrow": "Mới", + "editEyebrow": "Chỉnh sửa", + "name": "Tên", + "apiKey": "API key", + "apiKeyCreatePlaceholder": "Nhập API key", + "apiKeyEditPlaceholder": "Để trống nếu không đổi", + "baseUrl": "Base URL", + "baseUrlRequiredHint": "Bắt buộc với provider này", + "proxyUrl": "URL Proxy", + "prefix": "Tiền tố", + "priority": "Ưu tiên", + "weight": "Trọng số điều phối", + "weightHint": "Mặc định 1 · ≤ 0 bị loại trừ · tối đa 1.000.000", + "disabled": "Tắt mục này", + "disabledHint": "Gateway sẽ không dùng mục đã tắt", + "websockets": "Bật WebSocket", + "testModel": "Model kiểm thử", + "testModelClaudeHint": "Chỉ dùng để kiểm thử kết nối; không được lưu", + "testModelAutoWith": "Tự động · {{name}}", + "testModelAutoEmpty": "Tự động (chưa thêm model nào)", + "testModelCustom": "{{name}} (tùy chỉnh)", + "modelsSection": "Model tùy chỉnh", + "addModel": "Thêm model", + "headersSection": "Header yêu cầu", + "addHeader": "Thêm header", + "excludedSection": "Model bị loại trừ", + "excludedDisabledNote": "“*” nghĩa là toàn bộ provider bị tắt — hãy dùng công tắc Đã tắt ở trên thay thế.", + "cloakSection": "Cài đặt Cloak", + "cloakMode": "Chế độ", + "cloakStrict": "Chế độ nghiêm ngặt", + "cloakSensitiveWords": "Từ nhạy cảm (mỗi dòng một từ)", + "apiKeyEntriesSection": "Mục API key", + "apiKeyEntry": "Key #{{index}}", + "addApiKeyEntry": "Thêm mục key", + "showApiKey": "Hiện API key", + "hideApiKey": "Ẩn API key", + "disableCooling": "Tắt cooling", + "disableCoolingHint": "Chỉ tắt cửa sổ cooldown thất bại cho credential hoặc provider này", + "modelImage": "Cho phép endpoint ảnh", + "modelImageHint": "Cho phép model này trên /v1/images/generations và /v1/images/edits", + "showAllEntries": "Hiện tất cả ({{count}})", + "showFewerEntries": "Ẩn bớt", + "proxyBadge": "Proxy", + "modelBadgeImage": "Ảnh", + "modelBadgeThinking": "Suy luận", + "thinkingConfig": "Mức suy luận được phép", + "thinkingExistingHint": "Cấu hình backend hiện tại không đổi cho đến khi bạn đổi lựa chọn; sau đó sẽ được thay bằng các mức chuẩn đã chọn.", + "thinkingLevels": { + "none": "Tắt suy luận", + "minimal": "Tối thiểu", + "low": "Thấp", + "medium": "Trung bình", + "high": "Cao", + "xhigh": "Rất cao", + "max": "Tối đa", + "auto": "Tự động" + }, + "cloakCacheUserId": "Cache user_id", + "cloakCacheUserIdHint": "Dùng lại user_id Claude cloak theo từng API key", + "experimentalCchSigning": "Ký CCH thử nghiệm", + "experimentalCchSigningHint": "Ký body /v1/messages Claude đã cloak cuối cùng bằng CCH", + "validation": { + "nameRequired": "Tên là bắt buộc", + "apiKeyRequired": "Cần ít nhất một API key", + "baseUrlRequired": "Base URL là bắt buộc", + "weightInteger": "Trọng số điều phối phải là số nguyên", + "weightMax": "Trọng số điều phối không được vượt quá {{max}}" + } + }, + "delete": { + "title": "Xóa tài nguyên", + "confirm": "Xóa {{name}}? Thao tác này không thể hoàn tác." + }, + "toast": { + "created": "Đã tạo", + "updated": "Đã cập nhật", + "deleted": "Đã xóa", + "enabled": "Đã bật", + "disabled": "Đã tắt", + "toggleFailed": "Không thể cập nhật trạng thái" + }, + "unsavedChanges": { + "title": "Hủy thay đổi chưa lưu?", + "message": "Bạn có chỉnh sửa chưa lưu trong form này. Đóng sẽ hủy chúng.", + "discard": "Hủy thay đổi", + "keepEditing": "Tiếp tục chỉnh sửa" + }, + "connectivity": { + "test": "Kiểm thử", + "testAll": "Kiểm thử tất cả", + "success": "Kết nối được", + "baseUrlRequired": "Cần có Base URL", + "endpointInvalid": "URL endpoint không hợp lệ", + "apiKeyRequired": "Cần có API key", + "modelRequired": "Cần có model kiểm thử", + "timeout": "Hết thời gian sau {{seconds}} giây", + "requestFailed": "Yêu cầu thất bại" + }, + "discovery": { + "openButton": "Lấy từ endpoint", + "searchPlaceholder": "Tìm model", + "reload": "Tải lại", + "loading": "Đang tải model…", + "empty": "Endpoint không trả về model nào", + "notLoaded": "Nhấn Tải lại để lấy model", + "selectAll": "Chọn tất cả", + "clearAll": "Bỏ chọn", + "selectedCount": "{{selected}} / {{total}}", + "alreadyAdded": "Đã thêm", + "close": "Đóng", + "apply": "Áp dụng ({{count}})" + }, + "toolbar": { + "sortBy": "Sắp xếp theo", + "sort": { + "name": "Tên", + "priority": "Ưu tiên", + "recentSuccess": "Thành công gần đây", + "directionAsc": "Tăng dần", + "directionDesc": "Giảm dần" + }, + "filter": { + "allModels": "Mọi model", + "selectedModels": "{{selected}}/{{total}} model", + "selectAll": "Chọn tất cả", + "clear": "Xóa", + "empty": "Chưa cấu hình model nào" + } + }, + "modelCatalog": { + "notLoaded": "Chưa tải" + } + } +} diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index 854fc70c0e1..9da5051d20d 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -1803,7 +1803,8 @@ "chinese": "中文", "chinese_tw": "繁體中文(台灣)", "english": "English", - "russian": "Русский" + "russian": "Русский", + "vietnamese": "Tiếng Việt" }, "theme": { "switch": "主题", diff --git a/src/i18n/locales/zh-TW.json b/src/i18n/locales/zh-TW.json index 09c8713d3cc..1f95bda181d 100644 --- a/src/i18n/locales/zh-TW.json +++ b/src/i18n/locales/zh-TW.json @@ -1829,7 +1829,8 @@ "chinese": "簡體中文", "chinese_tw": "繁體中文(台灣)", "english": "英文", - "russian": "俄文" + "russian": "俄文", + "vietnamese": "Tiếng Việt" }, "theme": { "switch": "主題", diff --git a/src/types/common.ts b/src/types/common.ts index 83efd66bc2f..38213a2cc85 100644 --- a/src/types/common.ts +++ b/src/types/common.ts @@ -4,7 +4,7 @@ export type Theme = 'light' | 'white' | 'dark' | 'auto'; -export type Language = 'zh-CN' | 'zh-TW' | 'en' | 'ru'; +export type Language = 'zh-CN' | 'zh-TW' | 'en' | 'ru' | 'vi'; export type NotificationType = 'info' | 'success' | 'warning' | 'error'; diff --git a/src/utils/constants.ts b/src/utils/constants.ts index afec117e47c..3636ff9f49a 100644 --- a/src/utils/constants.ts +++ b/src/utils/constants.ts @@ -34,12 +34,13 @@ export const STORAGE_KEY_THEME = 'cli-proxy-theme'; export const STORAGE_KEY_LANGUAGE = 'cli-proxy-language'; // 语言配置 -export const LANGUAGE_ORDER = defineLanguageOrder(['zh-CN', 'zh-TW', 'en', 'ru'] as const); +export const LANGUAGE_ORDER = defineLanguageOrder(['zh-CN', 'zh-TW', 'en', 'ru', 'vi'] as const); export const LANGUAGE_LABEL_KEYS: Record = { 'zh-CN': 'language.chinese', 'zh-TW': 'language.chinese_tw', en: 'language.english', ru: 'language.russian', + vi: 'language.vietnamese', }; export const SUPPORTED_LANGUAGES = LANGUAGE_ORDER; diff --git a/src/utils/language.ts b/src/utils/language.ts index 67395ab2437..7de8b52ed59 100644 --- a/src/utils/language.ts +++ b/src/utils/language.ts @@ -45,6 +45,7 @@ const getBrowserLanguage = (): Language => { if (TRADITIONAL_CHINESE_PREFIXES.some((prefix) => lower.startsWith(prefix))) return 'zh-TW'; if (lower.startsWith('zh')) return 'zh-CN'; if (lower.startsWith('ru')) return 'ru'; + if (lower.startsWith('vi')) return 'vi'; return 'en'; }; From d31b61cb87c2664416368686c13f8bcd48e110a3 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Mon, 5 Oct 2026 04:05:41 +0800 Subject: [PATCH 045/142] fix(websockets): propagate upstream disconnect errors during session activation - Track terminal connection errors on websocket session when upstream read loops fail or receive unexpected binary payloads - Return recorded terminal errors immediately during session activation to prevent callers from blocking indefinitely after upstream disconnects - Reset terminal error state when configuring new connections Closes: #6354 --- .../executor/codex_websockets_session.go | 47 +++++++++- .../websocket_upstream_disconnect_test.go | 89 +++++++++++++++++++ .../executor/xai_websockets_executor.go | 2 + 3 files changed, 136 insertions(+), 2 deletions(-) create mode 100644 internal/runtime/executor/websocket_upstream_disconnect_test.go diff --git a/internal/runtime/executor/codex_websockets_session.go b/internal/runtime/executor/codex_websockets_session.go index f42deba7108..697cd007f59 100644 --- a/internal/runtime/executor/codex_websockets_session.go +++ b/internal/runtime/executor/codex_websockets_session.go @@ -71,6 +71,8 @@ type codexWebsocketSession struct { activeCh chan codexWebsocketRead activeDone <-chan struct{} activeCancel context.CancelFunc + terminalConn *websocket.Conn + terminalErr error readerConn *websocket.Conn @@ -97,6 +99,11 @@ func (s *codexWebsocketSession) setActive(conn *websocket.Conn, ch chan codexWeb return } s.activeMu.Lock() + s.setActiveLocked(conn, ch) + s.activeMu.Unlock() +} + +func (s *codexWebsocketSession) setActiveLocked(conn *websocket.Conn, ch chan codexWebsocketRead) { if s.activeCancel != nil { s.activeCancel() s.activeCancel = nil @@ -109,7 +116,6 @@ func (s *codexWebsocketSession) setActive(conn *websocket.Conn, ch chan codexWeb s.activeDone = activeCtx.Done() s.activeCancel = activeCancel } - s.activeMu.Unlock() } func (s *codexWebsocketSession) activate(conn *websocket.Conn) chan codexWebsocketRead { @@ -117,10 +123,44 @@ func (s *codexWebsocketSession) activate(conn *websocket.Conn) chan codexWebsock return nil } ch := make(chan codexWebsocketRead, 4096) - s.setActive(conn, ch) + s.activeMu.Lock() + defer s.activeMu.Unlock() + if s.terminalConn == conn && s.terminalErr != nil { + ch <- codexWebsocketRead{conn: conn, err: s.terminalErr} + close(ch) + return ch + } + s.setActiveLocked(conn, ch) return ch } +func (s *codexWebsocketSession) resetTerminalError(conn *websocket.Conn) { + if s == nil || conn == nil { + return + } + s.activeMu.Lock() + s.terminalConn = conn + s.terminalErr = nil + s.activeMu.Unlock() +} + +func (s *codexWebsocketSession) markTerminalError(conn *websocket.Conn, err error) bool { + if s == nil || conn == nil || err == nil { + return false + } + s.connMu.Lock() + if s.conn != conn { + s.connMu.Unlock() + return false + } + s.activeMu.Lock() + s.terminalConn = conn + s.terminalErr = err + s.activeMu.Unlock() + s.connMu.Unlock() + return true +} + func (s *codexWebsocketSession) activeForConn(conn *websocket.Conn) (chan codexWebsocketRead, <-chan struct{}) { if s == nil || conn == nil { return nil, nil @@ -252,6 +292,7 @@ func (s *codexWebsocketSession) configureConn(conn *websocket.Conn) { if s == nil || conn == nil { return } + s.resetTerminalError(conn) s.resetUpstreamDisconnectError(conn) conn.SetPingHandler(func(appData string) error { sessionID := "" @@ -670,6 +711,7 @@ func (e *CodexWebsocketsExecutor) readUpstreamLoop(sess *codexWebsocketSession, _ = conn.SetReadDeadline(time.Now().Add(codexResponsesWebsocketIdleTimeout)) msgType, payload, errRead := conn.ReadMessage() if errRead != nil { + sess.markTerminalError(conn, errRead) invalidate := func() { e.invalidateUpstreamConn(sess, conn, "upstream_disconnected", errRead) } @@ -690,6 +732,7 @@ func (e *CodexWebsocketsExecutor) readUpstreamLoop(sess *codexWebsocketSession, if msgType != websocket.TextMessage { if msgType == websocket.BinaryMessage { errBinary := fmt.Errorf("codex websockets executor: unexpected binary message") + sess.markTerminalError(conn, errBinary) invalidate := func() { e.invalidateUpstreamConn(sess, conn, "unexpected_binary", errBinary) } diff --git a/internal/runtime/executor/websocket_upstream_disconnect_test.go b/internal/runtime/executor/websocket_upstream_disconnect_test.go new file mode 100644 index 00000000000..7e8e283b448 --- /dev/null +++ b/internal/runtime/executor/websocket_upstream_disconnect_test.go @@ -0,0 +1,89 @@ +package executor + +import ( + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/gorilla/websocket" +) + +func TestWebsocketActivationAfterUpstreamDisconnect(t *testing.T) { + tests := []struct { + name string + readLoop func(*codexWebsocketSession, *websocket.Conn) + }{ + { + name: "codex", + readLoop: func(sess *codexWebsocketSession, conn *websocket.Conn) { + NewCodexWebsocketsExecutor(nil).readUpstreamLoop(sess, conn) + }, + }, + { + name: "xai", + readLoop: func(sess *codexWebsocketSession, conn *websocket.Conn) { + NewXAIWebsocketsExecutor(nil).readUpstreamLoop(sess, conn) + }, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + serverClosed := make(chan struct{}) + upgrader := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }} + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, errUpgrade := upgrader.Upgrade(w, r, nil) + if errUpgrade != nil { + return + } + _ = conn.Close() + close(serverClosed) + })) + defer server.Close() + + conn, _, errDial := websocket.DefaultDialer.Dial("ws"+server.URL[len("http"):], nil) + if errDial != nil { + t.Fatalf("dial websocket: %v", errDial) + } + defer func() { _ = conn.Close() }() + + sess := &codexWebsocketSession{ + conn: conn, + connCloser: newWebsocketConnectionCloser(conn), + readerConn: conn, + } + sess.configureConn(conn) + go test.readLoop(sess, conn) + + <-serverClosed + deadline := time.NewTimer(time.Second) + ticker := time.NewTicker(time.Millisecond) + defer deadline.Stop() + defer ticker.Stop() + for { + sess.connMu.Lock() + invalidated := sess.conn == nil + sess.connMu.Unlock() + if invalidated { + break + } + select { + case <-ticker.C: + case <-deadline.C: + t.Fatal("upstream disconnect was not processed") + } + } + + readCh := sess.activate(conn) + select { + case event := <-readCh: + if event.err == nil { + t.Fatalf("expected terminal upstream error, got event %#v", event) + } + case <-time.After(time.Second): + t.Fatal("activation after upstream disconnect blocked forever") + } + }) + } +} diff --git a/internal/runtime/executor/xai_websockets_executor.go b/internal/runtime/executor/xai_websockets_executor.go index 93cebfef38e..56b4096d031 100644 --- a/internal/runtime/executor/xai_websockets_executor.go +++ b/internal/runtime/executor/xai_websockets_executor.go @@ -1357,6 +1357,7 @@ func (e *XAIWebsocketsExecutor) readUpstreamLoop(sess *codexWebsocketSession, co for { msgType, payload, errRead := conn.ReadMessage() if errRead != nil { + sess.markTerminalError(conn, errRead) invalidate := func() { e.invalidateUpstreamConn(sess, conn, "upstream_disconnected", errRead) } @@ -1377,6 +1378,7 @@ func (e *XAIWebsocketsExecutor) readUpstreamLoop(sess *codexWebsocketSession, co if msgType != websocket.TextMessage { if msgType == websocket.BinaryMessage { errBinary := fmt.Errorf("xai websockets executor: unexpected binary message") + sess.markTerminalError(conn, errBinary) invalidate := func() { e.invalidateUpstreamConn(sess, conn, "unexpected_binary", errBinary) } From 4e4dede4811ab99c6ce20bdea3e45041e6304b29 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Mon, 5 Oct 2026 04:32:35 +0800 Subject: [PATCH 046/142] fix(antigravity): surface backend errors and support multi-line stream payloads - Buffer and assemble multi-line or split JSON chunks until a valid JSON payload is formed - Intercept upstream backend error objects during streaming and surface them as terminal errors with appropriate status codes Closes: #6357 --- ...antigravity_executor_finish_reason_test.go | 62 +++++++++++++++++++ .../executor/antigravity_executor_stream.go | 33 ++++++++++ 2 files changed, 95 insertions(+) diff --git a/internal/runtime/executor/antigravity_executor_finish_reason_test.go b/internal/runtime/executor/antigravity_executor_finish_reason_test.go index 64377c178ff..c54065f65bf 100644 --- a/internal/runtime/executor/antigravity_executor_finish_reason_test.go +++ b/internal/runtime/executor/antigravity_executor_finish_reason_test.go @@ -70,6 +70,68 @@ func collectAntigravityStream(t *testing.T, baseURL string, sourceFormat, respon return chunks } +func TestAntigravityStreamSurfacesTrailingBackendError(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, `data: {"response":{"candidates":[{"content":{"parts":[{"text":"partial"}]}}],"modelVersion":"gemini-3.7-flash"}} + +{ + "error": { + "code": 503, + "message": "backend capacity exhausted", + "status": "UNAVAILABLE" + } +} +`) + })) + defer server.Close() + + for _, format := range []sdktranslator.Format{sdktranslator.FormatClaude, sdktranslator.FormatOpenAI} { + t.Run(format.String(), func(t *testing.T) { + executor := NewAntigravityExecutor(&config.Config{ + Antigravity: config.AntigravityConfig{}, + RequestRetry: 1, + }) + result, errExecute := executor.ExecuteStream(context.Background(), &cliproxyauth.Auth{ + Metadata: map[string]any{ + "access_token": "token-123", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-1", + }, + Attributes: map[string]string{"base_url": server.URL}, + }, cliproxyexecutor.Request{ + Model: "gemini-3.7-flash", + Payload: []byte(`{"model":"gemini-3.7-flash","stream":true,"messages":[{"role":"user","content":"hello"}]}`), + }, cliproxyexecutor.Options{ + SourceFormat: format, + ResponseFormat: format, + Stream: true, + }) + if errExecute != nil { + t.Fatalf("ExecuteStream() error = %v", errExecute) + } + + var streamErr error + for chunk := range result.Chunks { + if chunk.Err != nil { + streamErr = chunk.Err + continue + } + if bytes.Contains(chunk.Payload, []byte("message_stop")) || bytes.Contains(chunk.Payload, []byte(`"finish_reason":"stop"`)) { + t.Fatalf("trailing backend error became successful completion: %s", chunk.Payload) + } + } + if streamErr == nil || !bytes.Contains([]byte(streamErr.Error()), []byte("backend capacity exhausted")) { + t.Fatalf("trailing backend error = %v, want surfaced backend message", streamErr) + } + statusError, ok := streamErr.(interface{ StatusCode() int }) + if !ok || statusError.StatusCode() != http.StatusServiceUnavailable { + t.Fatalf("trailing backend status code = %v, want %d", streamErr, http.StatusServiceUnavailable) + } + }) + } +} + // TestAntigravityStreamDoesNotEmitClaudeMessageStopOnReadError locks in the // executor ordering fix on the response format where it is observable: the // Claude translator has always synthesized a terminal event on [DONE], so diff --git a/internal/runtime/executor/antigravity_executor_stream.go b/internal/runtime/executor/antigravity_executor_stream.go index 904b333cdce..de64ce73369 100644 --- a/internal/runtime/executor/antigravity_executor_stream.go +++ b/internal/runtime/executor/antigravity_executor_stream.go @@ -205,6 +205,7 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya claudeInputTokens := helps.NewClaudeInputTokenState(from, to, responseFormat, originalPayload) var streamUsage helps.StreamUsageBuffer var streamErr error + var pendingJSON []byte var replayCommitted bool var param any commitReplay := func() { @@ -256,9 +257,41 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya line = helps.FilterSSEUsageMetadata(line) payload := helps.JSONPayload(line) + if len(pendingJSON) > 0 { + trimmedLine := bytes.TrimSpace(line) + if bytes.HasPrefix(trimmedLine, []byte("data:")) { + trimmedLine = bytes.TrimSpace(trimmedLine[len("data:"):]) + } + if len(trimmedLine) > 0 { + pendingJSON = append(pendingJSON, '\n') + pendingJSON = append(pendingJSON, trimmedLine...) + } + if !gjson.ValidBytes(pendingJSON) { + continue + } + payload = pendingJSON + pendingJSON = nil + } else if payload != nil && !gjson.ValidBytes(payload) { + pendingJSON = append([]byte(nil), payload...) + continue + } if payload == nil { continue } + if errorResult := gjson.GetBytes(payload, "error"); errorResult.Exists() { + statusCode := int(errorResult.Get("code").Int()) + if statusCode < http.StatusBadRequest || statusCode > 599 { + statusCode = http.StatusBadGateway + } + streamErr = newAntigravityStatusErr(statusCode, payload) + stopDeliverySupport() + helps.RecordAPIResponseError(ctx, e.cfg, streamErr) + select { + case out <- cliproxyexecutor.StreamChunk{Err: streamErr}: + case <-ctx.Done(): + } + return + } reporter.ObserveResponseModel(payload) payload = e.resolveWebSearchGroundingURLs(ctx, auth, from, originalPayload, translated, payload) From 16d98881d4bb37adaa827599e4be8f5154e81646 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Mon, 5 Oct 2026 05:35:53 +0800 Subject: [PATCH 047/142] feat(codex): preserve URL citations in OpenAI response translation - Parse and map `url_citation` annotations to OpenAI message and delta annotations for both stream and non-stream responses - Track emitted text rune offsets to calculate citation start and end indices accurately - Deduplicate citations across streaming annotation events and message completion updates Closes: #6361 --- .../chat-completions/codex_openai_response.go | 134 ++++++++++++++++-- .../codex_openai_response_test.go | 103 ++++++++++++++ 2 files changed, 228 insertions(+), 9 deletions(-) diff --git a/internal/translator/codex/openai/chat-completions/codex_openai_response.go b/internal/translator/codex/openai/chat-completions/codex_openai_response.go index 435abad567e..d69d3b56ae4 100644 --- a/internal/translator/codex/openai/chat-completions/codex_openai_response.go +++ b/internal/translator/codex/openai/chat-completions/codex_openai_response.go @@ -9,8 +9,10 @@ import ( "bytes" "context" "crypto/sha256" + "strconv" "strings" "time" + "unicode/utf8" applypatch "github.com/router-for-me/CLIProxyAPI/v8/internal/client/codex/apply-patch" translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" @@ -42,6 +44,8 @@ type ConvertCliToOpenAIParams struct { FunctionCallIndex int toolCallStates map[string]*toolCallStreamState currentToolCall *toolCallStreamState + citationKeys map[string]struct{} + emittedTextRunes int64 LastImageHashByItemID map[string][32]byte } @@ -67,6 +71,7 @@ func ConvertCodexResponseToOpenAI(_ context.Context, modelName string, originalR ResponseID: "", FunctionCallIndex: -1, toolCallStates: make(map[string]*toolCallStreamState), + citationKeys: make(map[string]struct{}), LastImageHashByItemID: make(map[string][32]byte), } } @@ -148,9 +153,18 @@ func ConvertCodexResponseToOpenAI(_ context.Context, modelName string, originalR template, _ = sjson.SetBytes(template, "choices.0.delta.reasoning_content", "\n\n") } else if dataType == "response.output_text.delta" { if deltaResult := rootResult.Get("delta"); deltaResult.Exists() { + delta := deltaResult.String() template, _ = sjson.SetBytes(template, "choices.0.delta.role", "assistant") - template, _ = sjson.SetBytes(template, "choices.0.delta.content", deltaResult.String()) + template, _ = sjson.SetBytes(template, "choices.0.delta.content", delta) + p.emittedTextRunes += int64(utf8.RuneCountInString(delta)) } + } else if dataType == "response.output_text.annotation.added" || dataType == "response.output_text.done" || dataType == "response.content_part.done" { + citations := buildCodexURLCitations(codexAnnotationsFromEvent(rootResult), p.emittedTextRunes, p.citationKeys) + if len(citations) == 0 { + return [][]byte{} + } + template, _ = sjson.SetBytes(template, "choices.0.delta.role", "assistant") + template, _ = sjson.SetRawBytes(template, "choices.0.delta.annotations", translatorcommon.JoinRawArray(citations)) } else if dataType == "response.image_generation_call.partial_image" { itemID := rootResult.Get("item_id").String() b64 := rootResult.Get("partial_image_b64").String() @@ -285,6 +299,15 @@ func ConvertCodexResponseToOpenAI(_ context.Context, modelName string, originalR if !itemResult.Exists() { return [][]byte{} } + if itemResult.Get("type").String() == "message" { + citations := buildCodexURLCitations(codexAnnotationsFromEvent(rootResult), p.emittedTextRunes, p.citationKeys) + if len(citations) == 0 { + return [][]byte{} + } + template, _ = sjson.SetBytes(template, "choices.0.delta.role", "assistant") + template, _ = sjson.SetRawBytes(template, "choices.0.delta.annotations", translatorcommon.JoinRawArray(citations)) + return [][]byte{template} + } itemType := itemResult.Get("type").String() if itemType == "image_generation_call" { itemID := itemResult.Get("id").String() @@ -466,6 +489,9 @@ func ConvertCodexResponseToOpenAINonStream(_ context.Context, _ string, original outputArray := outputResult.Array() var contentText string var reasoningText string + var messageAnnotations [][]byte + annotationKeys := make(map[string]struct{}) + var contentRuneOffset int64 for _, outputItem := range outputArray { outputType := outputItem.Get("type").String() @@ -496,16 +522,20 @@ func ConvertCodexResponseToOpenAINonStream(_ context.Context, _ string, original } } case "message": - // Extract message content + // Extract message content and URL citations. if contentResult := outputItem.Get("content"); contentResult.IsArray() { - contentArray := contentResult.Array() - for _, contentItem := range contentArray { - if contentItem.Get("type").String() == "output_text" { - if text := contentItem.Get("text").String(); text != "" { - contentText += text - } - break + for _, contentItem := range contentResult.Array() { + if contentItem.Get("type").String() != "output_text" { + continue } + text := contentItem.Get("text").String() + contentText += text + messageAnnotations = append(messageAnnotations, buildCodexURLCitations( + codexAnnotationResults(contentItem.Get("annotations")), + contentRuneOffset, + annotationKeys, + )...) + contentRuneOffset += int64(utf8.RuneCountInString(text)) } } case "function_call", "custom_tool_call": @@ -557,6 +587,10 @@ func ConvertCodexResponseToOpenAINonStream(_ context.Context, _ string, original template, _ = sjson.SetBytes(template, "choices.0.message.reasoning_content", reasoningText) } + if len(messageAnnotations) > 0 { + template, _ = sjson.SetRawBytes(template, "choices.0.message.annotations", translatorcommon.JoinRawArray(messageAnnotations)) + } + // Add tool calls if any if len(toolCalls) > 0 { template, _ = sjson.SetRawBytes(template, "choices.0.message.tool_calls", translatorcommon.JoinRawArray(toolCalls)) @@ -601,6 +635,88 @@ func ConvertCodexResponseToOpenAINonStream(_ context.Context, _ string, original return template } +func codexAnnotationResults(value gjson.Result) []gjson.Result { + if !value.Exists() { + return nil + } + if value.IsArray() { + results := make([]gjson.Result, 0, len(value.Array())) + value.ForEach(func(_, item gjson.Result) bool { + results = append(results, item) + return true + }) + return results + } + return []gjson.Result{value} +} + +func codexAnnotationsFromEvent(event gjson.Result) []gjson.Result { + annotations := make([]gjson.Result, 0) + for _, path := range []string{"annotation", "annotations", "part.annotations"} { + annotations = append(annotations, codexAnnotationResults(event.Get(path))...) + } + item := event.Get("item") + if item.Exists() { + annotations = append(annotations, codexAnnotationResults(item.Get("annotations"))...) + if content := item.Get("content"); content.IsArray() { + for _, contentItem := range content.Array() { + annotations = append(annotations, codexAnnotationResults(contentItem.Get("annotations"))...) + } + } + } + return annotations +} + +func buildCodexURLCitations(annotations []gjson.Result, runeOffset int64, seen map[string]struct{}) [][]byte { + citations := make([][]byte, 0, len(annotations)) + for _, annotation := range annotations { + if annotation.Get("type").String() != "url_citation" { + continue + } + + rawStartIndex := annotation.Get("start_index").Int() + rawEndIndex := annotation.Get("end_index").Int() + startIndex := rawStartIndex + runeOffset + endIndex := rawEndIndex + runeOffset + if startIndex < 0 || endIndex < startIndex { + continue + } + + url := annotation.Get("url").String() + key := url + "\x00" + strconv.FormatInt(rawStartIndex, 10) + if url == "" { + key = annotation.Get("id").String() + "\x00" + strconv.FormatInt(rawStartIndex, 10) + } + keys := []string{key} + if id := annotation.Get("id").String(); id != "" { + keys = append(keys, "id\x00"+id) + } + if seen != nil { + duplicate := false + for _, key := range keys { + if _, exists := seen[key]; exists { + duplicate = true + break + } + } + if duplicate { + continue + } + for _, key := range keys { + seen[key] = struct{}{} + } + } + + citation := []byte(`{"type":"url_citation","url":"","title":"","start_index":0,"end_index":0}`) + citation, _ = sjson.SetBytes(citation, "url", url) + citation, _ = sjson.SetBytes(citation, "title", annotation.Get("title").String()) + citation, _ = sjson.SetBytes(citation, "start_index", startIndex) + citation, _ = sjson.SetBytes(citation, "end_index", endIndex) + citations = append(citations, citation) + } + return citations +} + func registerToolCallState(p *ConvertCliToOpenAIParams, eventResult, itemResult gjson.Result, state *toolCallStreamState) { if p.toolCallStates == nil { p.toolCallStates = make(map[string]*toolCallStreamState) diff --git a/internal/translator/codex/openai/chat-completions/codex_openai_response_test.go b/internal/translator/codex/openai/chat-completions/codex_openai_response_test.go index fcc96d9bcfe..61c71b74c03 100644 --- a/internal/translator/codex/openai/chat-completions/codex_openai_response_test.go +++ b/internal/translator/codex/openai/chat-completions/codex_openai_response_test.go @@ -77,6 +77,109 @@ func TestConvertCodexResponseToOpenAI_FirstChunkUsesRequestModelName(t *testing. } } +func TestConvertCodexResponseToOpenAI_PreservesURLCitations(t *testing.T) { + t.Run("non-stream", func(t *testing.T) { + raw := []byte(`{"type":"response.completed","response":{"id":"resp_citation","model":"gpt-5.5","status":"completed","output":[{"type":"message","content":[{"type":"output_text","text":"前🙂"},{"type":"output_text","text":"引用","annotations":[{"type":"url_citation","url":"https://example.com","title":"Example","start_index":0,"end_index":2},{"type":"file_citation","file_id":"file_1","index":0}]}]}]}}`) + out := ConvertCodexResponseToOpenAINonStream(t.Context(), "gpt-5.5", nil, nil, raw, nil) + + if got := gjson.GetBytes(out, "choices.0.message.content").String(); got != "前🙂引用" { + t.Fatalf("content = %q, want %q; response=%s", got, "前🙂引用", out) + } + annotation := gjson.GetBytes(out, "choices.0.message.annotations.0") + if !annotation.Exists() { + t.Fatalf("expected message annotation, response=%s", out) + } + if got := gjson.GetBytes(out, "choices.0.message.annotations.#").Int(); got != 1 { + t.Fatalf("annotation count = %d, want 1 after filtering unsupported types; response=%s", got, out) + } + if got := annotation.Get("type").String(); got != "url_citation" { + t.Fatalf("annotation type = %q, want url_citation; response=%s", got, out) + } + if got := annotation.Get("url").String(); got != "https://example.com" { + t.Fatalf("annotation url = %q, want https://example.com; response=%s", got, out) + } + if got := annotation.Get("title").String(); got != "Example" { + t.Fatalf("annotation title = %q, want Example; response=%s", got, out) + } + if got := annotation.Get("start_index").Int(); got != 2 { + t.Fatalf("annotation start_index = %d, want 2; response=%s", got, out) + } + if got := annotation.Get("end_index").Int(); got != 4 { + t.Fatalf("annotation end_index = %d, want 4; response=%s", got, out) + } + }) + + t.Run("stream", func(t *testing.T) { + var param any + if out := ConvertCodexResponseToOpenAI(t.Context(), "gpt-5.5", nil, nil, []byte(`data: {"type":"response.output_text.delta","delta":"前🙂"}`), ¶m); len(out) != 1 { + t.Fatalf("expected text delta chunk, got %d", len(out)) + } + + annotationEvent := []byte(`data: {"type":"response.output_text.annotation.added","annotation_index":0,"annotation":{"type":"url_citation","url":"https://example.com","title":"Example","start_index":0,"end_index":1}}`) + out := ConvertCodexResponseToOpenAI(t.Context(), "gpt-5.5", nil, nil, annotationEvent, ¶m) + if len(out) != 1 { + t.Fatalf("expected citation chunk, got %d", len(out)) + } + annotation := gjson.GetBytes(out[0], "choices.0.delta.annotations.0") + if !annotation.Exists() { + t.Fatalf("expected delta annotation, chunk=%s", out[0]) + } + if got := annotation.Get("type").String(); got != "url_citation" { + t.Fatalf("annotation type = %q, want url_citation; chunk=%s", got, out[0]) + } + if got := annotation.Get("start_index").Int(); got != 2 { + t.Fatalf("annotation start_index = %d, want 2; chunk=%s", got, out[0]) + } + if got := annotation.Get("end_index").Int(); got != 3 { + t.Fatalf("annotation end_index = %d, want 3; chunk=%s", got, out[0]) + } + + if out = ConvertCodexResponseToOpenAI(t.Context(), "gpt-5.5", nil, nil, []byte(`data: {"type":"response.output_text.delta","delta":"引用"}`), ¶m); len(out) != 1 { + t.Fatalf("expected second text delta chunk, got %d", len(out)) + } + updatedAnnotationEvent := []byte(`data: {"type":"response.output_text.annotation.added","annotation_index":0,"annotation":{"type":"url_citation","url":"https://example.com","title":"Example","start_index":0,"end_index":2}}`) + if out = ConvertCodexResponseToOpenAI(t.Context(), "gpt-5.5", nil, nil, updatedAnnotationEvent, ¶m); len(out) != 0 { + t.Fatalf("expected duplicate citation to be suppressed after more text, got %d chunks", len(out)) + } + }) + + t.Run("stream completion annotation", func(t *testing.T) { + var param any + for _, delta := range []string{"前🙂", "引用"} { + if out := ConvertCodexResponseToOpenAI(t.Context(), "gpt-5.5", nil, nil, []byte(`data: {"type":"response.output_text.delta","delta":`+string(mustJSONMarshal(t, delta))+`}`), ¶m); len(out) != 1 { + t.Fatalf("expected text delta chunk, got %d", len(out)) + } + } + + doneEvent := []byte(`data: {"type":"response.output_text.done","text":"前🙂引用","annotations":[{"type":"url_citation","url":"https://example.com","title":"Example","start_index":0,"end_index":2}]}`) + out := ConvertCodexResponseToOpenAI(t.Context(), "gpt-5.5", nil, nil, doneEvent, ¶m) + if len(out) != 1 { + t.Fatalf("expected citation completion chunk, got %d", len(out)) + } + annotation := gjson.GetBytes(out[0], "choices.0.delta.annotations.0") + if got := annotation.Get("start_index").Int(); got != 4 { + t.Fatalf("annotation start_index = %d, want 4; chunk=%s", got, out[0]) + } + if got := annotation.Get("end_index").Int(); got != 6 { + t.Fatalf("annotation end_index = %d, want 6; chunk=%s", got, out[0]) + } + + contentPartDoneEvent := []byte(`data: {"type":"response.content_part.done","part":{"type":"output_text","text":"前🙂引用","annotations":[{"type":"url_citation","url":"https://other.example","title":"Other","start_index":0,"end_index":1}]}}`) + out = ConvertCodexResponseToOpenAI(t.Context(), "gpt-5.5", nil, nil, contentPartDoneEvent, ¶m) + if len(out) != 1 || gjson.GetBytes(out[0], "choices.0.delta.annotations.0.url").String() != "https://other.example" { + t.Fatalf("expected content-part citation chunk, got %d: %s", len(out), out) + } + if got := gjson.GetBytes(out[0], "choices.0.delta.annotations.0.start_index").Int(); got != 4 { + t.Fatalf("content-part annotation start_index = %d, want 4; chunk=%s", got, out[0]) + } + + itemDoneEvent := []byte(`data: {"type":"response.output_item.done","item":{"type":"message","content":[{"type":"output_text","text":"前🙂引用","annotations":[{"type":"url_citation","url":"https://example.com","title":"Example","start_index":0,"end_index":2}]}]}}`) + if out = ConvertCodexResponseToOpenAI(t.Context(), "gpt-5.5", nil, nil, itemDoneEvent, ¶m); len(out) != 0 { + t.Fatalf("expected duplicate completion citation to be suppressed, got %d chunks", len(out)) + } + }) +} + func TestConvertCodexResponseToOpenAI_ToolCallChunkOmitsNullContentFields(t *testing.T) { ctx := context.Background() var param any From 97dd9eec628c6b1e89847f31bb10c1da49b0402a Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Mon, 5 Oct 2026 06:06:14 +0800 Subject: [PATCH 048/142] fix(openai): report error on truncated stream missing finish_reason - Track `finish_reason` presence across initial and streaming response chunks - Return a terminal bad gateway error instead of `[DONE]` when upstream stream closes prematurely without a finish reason Closes: #6371 --- sdk/api/handlers/openai/openai_handlers.go | 36 ++- .../openai_handlers_stream_truncation_test.go | 286 ++++++++++++++++++ 2 files changed, 319 insertions(+), 3 deletions(-) create mode 100644 sdk/api/handlers/openai/openai_handlers_stream_truncation_test.go diff --git a/sdk/api/handlers/openai/openai_handlers.go b/sdk/api/handlers/openai/openai_handlers.go index 088e8fd821f..de21739f750 100644 --- a/sdk/api/handlers/openai/openai_handlers.go +++ b/sdk/api/handlers/openai/openai_handlers.go @@ -7,6 +7,7 @@ package openai import ( + "bytes" "context" "encoding/json" "fmt" @@ -536,11 +537,12 @@ func (h *OpenAIAPIHandler) handleStreamingResponse(c *gin.Context, rawJSON []byt setSSEHeaders() handlers.WriteUpstreamHeaders(c.Writer.Header(), upstreamHeaders) + initialHasFinishReason := chunkHasFinishReason(chunk) _, _ = fmt.Fprintf(c.Writer, "data: %s\n\n", string(chunk)) flusher.Flush() // Continue streaming the rest - h.handleStreamResult(c, flusher, func(err error) { cliCancel(err) }, dataChan, errChan) + h.handleStreamResult(c, flusher, func(err error) { cliCancel(err) }, dataChan, errChan, initialHasFinishReason) return } } @@ -653,7 +655,9 @@ func (h *OpenAIAPIHandler) handleCompletionsStreamingResponse(c *gin.Context, ra // Write the first chunk converted := convertChatCompletionsStreamChunkToCompletions(chunk) + var initialHasFinishReason bool if converted != nil { + initialHasFinishReason = chunkHasFinishReason(converted) _, _ = fmt.Fprintf(c.Writer, "data: %s\n\n", string(converted)) flusher.Flush() } @@ -689,14 +693,31 @@ func (h *OpenAIAPIHandler) handleCompletionsStreamingResponse(c *gin.Context, ra h.handleStreamResult(c, flusher, func(err error) { stop() cliCancel(err) - }, convertedChan, errChan) + }, convertedChan, errChan, initialHasFinishReason) return } } } -func (h *OpenAIAPIHandler) handleStreamResult(c *gin.Context, flusher http.Flusher, cancel func(error), data <-chan []byte, errs <-chan *interfaces.ErrorMessage) { +func chunkHasFinishReason(chunk []byte) bool { + chunk = bytes.TrimSpace(chunk) + if bytes.HasPrefix(chunk, []byte("data:")) { + chunk = bytes.TrimSpace(chunk[5:]) + } + for _, choice := range gjson.GetBytes(chunk, "choices").Array() { + if reason := choice.Get("finish_reason"); reason.Exists() && reason.Type != gjson.Null && reason.String() != "" { + return true + } + } + return false +} + +func (h *OpenAIAPIHandler) handleStreamResult(c *gin.Context, flusher http.Flusher, cancel func(error), data <-chan []byte, errs <-chan *interfaces.ErrorMessage, initialHasFinishReason bool) { + sawFinishReason := initialHasFinishReason h.ForwardStream(c, flusher, cancel, data, errs, handlers.StreamForwardOptions{ WriteChunk: func(chunk []byte) { + if !sawFinishReason && chunkHasFinishReason(chunk) { + sawFinishReason = true + } _, _ = fmt.Fprintf(c.Writer, "data: %s\n\n", string(chunk)) }, WriteTerminalError: func(errMsg *interfaces.ErrorMessage) { @@ -714,6 +735,15 @@ func (h *OpenAIAPIHandler) handleStreamResult(c *gin.Context, flusher http.Flush body := handlers.BuildErrorResponseBody(status, errText) _, _ = fmt.Fprintf(c.Writer, "data: %s\n\n", string(body)) }, + CloseError: func() *interfaces.ErrorMessage { + if sawFinishReason { + return nil + } + return &interfaces.ErrorMessage{ + StatusCode: http.StatusBadGateway, + Error: fmt.Errorf("upstream stream closed before any chunk carried finish_reason"), + } + }, WriteDone: func() { _, _ = fmt.Fprint(c.Writer, "data: [DONE]\n\n") }, diff --git a/sdk/api/handlers/openai/openai_handlers_stream_truncation_test.go b/sdk/api/handlers/openai/openai_handlers_stream_truncation_test.go new file mode 100644 index 00000000000..03ae8c16d03 --- /dev/null +++ b/sdk/api/handlers/openai/openai_handlers_stream_truncation_test.go @@ -0,0 +1,286 @@ +package openai + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers" + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + coreexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdkconfig "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" +) + +const truncatedStreamChatModel = "truncated-stream-chat-model" + +type mockStreamExecutor struct { + chunks []string +} + +func (*mockStreamExecutor) Identifier() string { return "mock-stream-executor" } + +func (*mockStreamExecutor) Execute(context.Context, *coreauth.Auth, coreexecutor.Request, coreexecutor.Options) (coreexecutor.Response, error) { + return coreexecutor.Response{}, errors.New("not implemented") +} + +func (e *mockStreamExecutor) ExecuteStream(_ context.Context, _ *coreauth.Auth, _ coreexecutor.Request, _ coreexecutor.Options) (*coreexecutor.StreamResult, error) { + chunks := make(chan coreexecutor.StreamChunk, len(e.chunks)) + for _, c := range e.chunks { + chunks <- coreexecutor.StreamChunk{Payload: []byte(c)} + } + close(chunks) + return &coreexecutor.StreamResult{Chunks: chunks}, nil +} + +func (*mockStreamExecutor) Refresh(_ context.Context, auth *coreauth.Auth) (*coreauth.Auth, error) { + return auth, nil +} + +func (*mockStreamExecutor) CountTokens(context.Context, *coreauth.Auth, coreexecutor.Request, coreexecutor.Options) (coreexecutor.Response, error) { + return coreexecutor.Response{}, errors.New("not implemented") +} + +func (*mockStreamExecutor) HttpRequest(context.Context, *coreauth.Auth, *http.Request) (*http.Response, error) { + return nil, errors.New("not implemented") +} + +func runMockStreamTest(t *testing.T, chunks []string, authID string) string { + t.Helper() + gin.SetMode(gin.TestMode) + + executor := &mockStreamExecutor{chunks: chunks} + manager := coreauth.NewManager(nil, nil, nil) + manager.RegisterExecutor(executor) + auth := &coreauth.Auth{ID: authID, Provider: executor.Identifier(), Status: coreauth.StatusActive} + if _, err := manager.Register(context.Background(), auth); err != nil { + t.Fatalf("register auth: %v", err) + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, auth.Provider, []*registry.ModelInfo{{ID: truncatedStreamChatModel}}) + defer registry.GetGlobalRegistry().UnregisterClient(auth.ID) + + base := handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, manager) + h := NewOpenAIAPIHandler(base) + router := gin.New() + router.POST("/v1/chat/completions", h.ChatCompletions) + + body := `{"model":"truncated-stream-chat-model","messages":[{"role":"user","content":"hi"}],"stream":true}` + request := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(body)) + request.Header.Set("Content-Type", "application/json") + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, request) + return recorder.Body.String() +} + +// Issue #6371: A stream that emits multiple chunks and then cleanly closes without +// any chunk carrying finish_reason is truncated. It must NOT be answered with [DONE], +// but must surface an error so clients can detect truncation and retry. +func TestChatCompletionsStreamWithoutFinishReasonIsReportedAsError(t *testing.T) { + chunks := []string{ + `{"choices":[{"index":0,"delta":{"role":"assistant"}}]}`, + `{"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"name":"do_thing","arguments":"{\"a\":1"}}]}}]}`, + } + out := runMockStreamTest(t, chunks, "truncated-stream-auth-multi-chunk-missing") + if strings.Contains(out, "data: [DONE]") { + t.Errorf("truncated stream was terminated with [DONE] as if it had succeeded: %q", out) + } + if !strings.Contains(out, "finish_reason") { + t.Errorf("truncated stream did not surface an error naming the missing terminator: %q", out) + } + if !strings.Contains(out, `"error":{"message":"upstream stream closed before any chunk carried finish_reason"`) { + t.Errorf("truncated stream did not format structured error payload: %q", out) + } +} + +// Issue #6371: A stream with explicit null or empty finish_reason must still be detected as truncated. +func TestChatCompletionsStreamExplicitNullOrEmptyFinishReasonIsReportedAsError(t *testing.T) { + chunks := []string{ + `{"choices":[{"index":0,"delta":{"role":"assistant","content":"part1"},"finish_reason":null}]}`, + `{"choices":[{"index":0,"delta":{"content":"part2"},"finish_reason":""}]}`, + } + out := runMockStreamTest(t, chunks, "truncated-stream-auth-null-finish") + if strings.Contains(out, "data: [DONE]") { + t.Errorf("stream with null/empty finish_reason was terminated with [DONE]: %q", out) + } + if !strings.Contains(out, "finish_reason") { + t.Errorf("stream with null/empty finish_reason did not surface error: %q", out) + } +} + +// Issue #6371: A stream that emits only 1 chunk without finish_reason and closes must also +// be flagged as truncated, not [DONE]. +func TestChatCompletionsStreamSingleChunkWithoutFinishReasonIsReportedAsError(t *testing.T) { + chunks := []string{ + `{"choices":[{"index":0,"delta":{"role":"assistant","content":"hello"}}]}`, + } + out := runMockStreamTest(t, chunks, "truncated-stream-auth-single-chunk-missing") + if strings.Contains(out, "data: [DONE]") { + t.Errorf("single-chunk truncated stream was terminated with [DONE] as if it had succeeded: %q", out) + } + if !strings.Contains(out, "finish_reason") { + t.Errorf("single-chunk truncated stream did not surface an error naming the missing terminator: %q", out) + } +} + +// Control: A multi-chunk stream that does carry finish_reason must complete with [DONE]. +func TestChatCompletionsStreamWithFinishReasonStillCompletes(t *testing.T) { + chunks := []string{ + `{"choices":[{"index":0,"delta":{"role":"assistant"}}]}`, + `{"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"name":"do_thing","arguments":"{\"a\":1}"}}]}}]}`, + `{"choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}`, + } + out := runMockStreamTest(t, chunks, "truncated-stream-auth-multi-chunk-present") + if !strings.Contains(out, "data: [DONE]") { + t.Errorf("complete stream was not terminated with [DONE]: %q", out) + } + if strings.Contains(out, "upstream stream closed before") { + t.Errorf("complete stream was wrongly flagged as truncated: %q", out) + } +} + +// Control: A single-chunk stream that carries finish_reason must complete with [DONE]. +func TestChatCompletionsStreamSingleChunkWithFinishReasonStillCompletes(t *testing.T) { + chunks := []string{ + `{"choices":[{"index":0,"delta":{"content":"instant"},"finish_reason":"stop"}]}`, + } + out := runMockStreamTest(t, chunks, "truncated-stream-auth-single-chunk-present") + if !strings.Contains(out, "data: [DONE]") { + t.Errorf("single-chunk complete stream was not terminated with [DONE]: %q", out) + } + if strings.Contains(out, "upstream stream closed before") { + t.Errorf("single-chunk complete stream was wrongly flagged as truncated: %q", out) + } +} + +// Issue #6371: Legacy /v1/completions stream that ends without finish_reason must also be flagged as error. +func TestCompletionsStreamWithoutFinishReasonIsReportedAsError(t *testing.T) { + gin.SetMode(gin.TestMode) + + chunks := []string{ + `{"choices":[{"index":0,"delta":{"role":"assistant"}}]}`, + `{"choices":[{"index":0,"delta":{"content":"trunc"}}]}`, + } + executor := &mockStreamExecutor{chunks: chunks} + manager := coreauth.NewManager(nil, nil, nil) + manager.RegisterExecutor(executor) + auth := &coreauth.Auth{ID: "truncated-legacy-auth-missing", Provider: executor.Identifier(), Status: coreauth.StatusActive} + if _, err := manager.Register(context.Background(), auth); err != nil { + t.Fatalf("register auth: %v", err) + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, auth.Provider, []*registry.ModelInfo{{ID: "legacy-model"}}) + defer registry.GetGlobalRegistry().UnregisterClient(auth.ID) + + base := handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, manager) + h := NewOpenAIAPIHandler(base) + router := gin.New() + router.POST("/v1/completions", h.Completions) + + body := `{"model":"legacy-model","prompt":"hi","stream":true}` + request := httptest.NewRequest(http.MethodPost, "/v1/completions", strings.NewReader(body)) + request.Header.Set("Content-Type", "application/json") + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, request) + out := recorder.Body.String() + + if strings.Contains(out, "data: [DONE]") { + t.Errorf("truncated legacy completions stream was terminated with [DONE]: %q", out) + } + if !strings.Contains(out, "finish_reason") { + t.Errorf("truncated legacy completions stream did not surface error: %q", out) + } +} + +// Control: Legacy /v1/completions stream that carries finish_reason completes with [DONE]. +func TestCompletionsStreamWithFinishReasonStillCompletes(t *testing.T) { + gin.SetMode(gin.TestMode) + + chunks := []string{ + `{"choices":[{"index":0,"delta":{"role":"assistant"}}]}`, + `{"choices":[{"index":0,"delta":{"content":"hello"},"finish_reason":"stop"}]}`, + } + executor := &mockStreamExecutor{chunks: chunks} + manager := coreauth.NewManager(nil, nil, nil) + manager.RegisterExecutor(executor) + auth := &coreauth.Auth{ID: "truncated-legacy-auth-present", Provider: executor.Identifier(), Status: coreauth.StatusActive} + if _, err := manager.Register(context.Background(), auth); err != nil { + t.Fatalf("register auth: %v", err) + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, auth.Provider, []*registry.ModelInfo{{ID: "legacy-model-ok"}}) + defer registry.GetGlobalRegistry().UnregisterClient(auth.ID) + + base := handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, manager) + h := NewOpenAIAPIHandler(base) + router := gin.New() + router.POST("/v1/completions", h.Completions) + + body := `{"model":"legacy-model-ok","prompt":"hi","stream":true}` + request := httptest.NewRequest(http.MethodPost, "/v1/completions", strings.NewReader(body)) + request.Header.Set("Content-Type", "application/json") + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, request) + out := recorder.Body.String() + + if !strings.Contains(out, "data: [DONE]") { + t.Errorf("complete legacy completions stream was not terminated with [DONE]: %q", out) + } + if strings.Contains(out, "upstream stream closed before") { + t.Errorf("complete legacy completions stream was wrongly flagged as truncated: %q", out) + } +} + +// Control: A stream with usage chunk arriving after finish_reason chunk must complete with [DONE]. +func TestChatCompletionsStreamUsageAfterFinishReasonStillCompletes(t *testing.T) { + chunks := []string{ + `{"choices":[{"index":0,"delta":{"content":"hi"}}]}`, + `{"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`, + `{"choices":[],"usage":{"prompt_tokens":5,"completion_tokens":2,"total_tokens":7}}`, + } + out := runMockStreamTest(t, chunks, "truncated-stream-auth-usage-after-finish") + if !strings.Contains(out, "data: [DONE]") { + t.Errorf("stream with usage after finish_reason was not terminated with [DONE]: %q", out) + } + if strings.Contains(out, "upstream stream closed before") { + t.Errorf("stream with usage after finish_reason was wrongly flagged as truncated: %q", out) + } +} + +// Control: Legacy /v1/completions single-chunk stream with finish_reason completes with [DONE]. +func TestCompletionsStreamSingleChunkWithFinishReasonStillCompletes(t *testing.T) { + gin.SetMode(gin.TestMode) + + chunks := []string{ + `{"choices":[{"index":0,"delta":{"content":"single"},"finish_reason":"stop"}]}`, + } + executor := &mockStreamExecutor{chunks: chunks} + manager := coreauth.NewManager(nil, nil, nil) + manager.RegisterExecutor(executor) + auth := &coreauth.Auth{ID: "truncated-legacy-auth-single-present", Provider: executor.Identifier(), Status: coreauth.StatusActive} + if _, err := manager.Register(context.Background(), auth); err != nil { + t.Fatalf("register auth: %v", err) + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, auth.Provider, []*registry.ModelInfo{{ID: "legacy-model-single-ok"}}) + defer registry.GetGlobalRegistry().UnregisterClient(auth.ID) + + base := handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, manager) + h := NewOpenAIAPIHandler(base) + router := gin.New() + router.POST("/v1/completions", h.Completions) + + body := `{"model":"legacy-model-single-ok","prompt":"hi","stream":true}` + request := httptest.NewRequest(http.MethodPost, "/v1/completions", strings.NewReader(body)) + request.Header.Set("Content-Type", "application/json") + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, request) + out := recorder.Body.String() + + if !strings.Contains(out, "data: [DONE]") { + t.Errorf("single chunk legacy completions stream was not terminated with [DONE]: %q", out) + } + if strings.Contains(out, "upstream stream closed before") { + t.Errorf("single chunk legacy completions stream was wrongly flagged as truncated: %q", out) + } +} From a4acc9f752bd46571f737a10c04bf413656ab06b Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Mon, 5 Oct 2026 06:25:53 +0800 Subject: [PATCH 049/142] fix(antigravity): treat client disconnect after terminal stream chunk as success - Track terminal chunks including finish reasons, stop messages, and completion events during streaming - Commit replay settlements and publish observed usage instead of reporting stream failure when the client disconnects after a terminal chunk Closes: #6376 --- .../executor/antigravity_executor_stream.go | 52 ++++ ...avity_executor_terminal_disconnect_test.go | 289 ++++++++++++++++++ 2 files changed, 341 insertions(+) create mode 100644 internal/runtime/executor/antigravity_executor_terminal_disconnect_test.go diff --git a/internal/runtime/executor/antigravity_executor_stream.go b/internal/runtime/executor/antigravity_executor_stream.go index de64ce73369..13d404402ac 100644 --- a/internal/runtime/executor/antigravity_executor_stream.go +++ b/internal/runtime/executor/antigravity_executor_stream.go @@ -8,6 +8,7 @@ import ( "fmt" "io" "net/http" + "strings" "time" "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps" @@ -207,6 +208,7 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya var streamErr error var pendingJSON []byte var replayCommitted bool + var terminalDelivered bool var param any commitReplay := func() { if !replayCommitted && replayAccumulator != nil && replayAccumulator.terminal && helps.ApplyPatchTranslationError(param) == nil { @@ -222,6 +224,9 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya } // Replay is settled before forwarding completion; accounting still waits // for the HTTP consumer, which may need EOF to acknowledge delivery. + if terminalDelivered { + commitReplay() + } close(out) if streamErr == nil { streamErr = ctx.Err() @@ -232,6 +237,11 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya } } if streamErr != nil { + if terminalDelivered && errors.Is(streamErr, context.Canceled) { + streamUsage.Publish(ctx, reporter) + reporter.EnsurePublished(ctx) + return + } if !streamUsage.PublishFailure(ctx, reporter, streamErr) { reporter.PublishFailure(ctx, streamErr) } @@ -297,6 +307,41 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya payload = e.resolveWebSearchGroundingURLs(ctx, auth, from, originalPayload, translated, payload) chunks := helps.TranslateStreamWithClaudeInputTokens(ctx, to, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), translated, bytes.Clone(payload), ¶m, claudeInputTokens) helps.RecordApplyPatchStreamFailure(ctx, param, reporter, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) + var isTerminalChunk bool + if finishReason := gjson.GetBytes(payload, "candidates.0.finishReason"); finishReason.Exists() && strings.TrimSpace(finishReason.String()) != "" { + isTerminalChunk = true + } else if finishReason := gjson.GetBytes(payload, "response.candidates.0.finishReason"); finishReason.Exists() && strings.TrimSpace(finishReason.String()) != "" { + isTerminalChunk = true + } else if replayAccumulator != nil && replayAccumulator.terminal { + isTerminalChunk = true + } + if !isTerminalChunk { + for _, chunk := range chunks { + for _, cLine := range bytes.Split(chunk, []byte("\n")) { + trimmed := bytes.TrimSpace(cLine) + if bytes.Equal(trimmed, []byte("data: [DONE]")) || bytes.Equal(trimmed, []byte("[DONE]")) { + isTerminalChunk = true + break + } + cPayload := helps.JSONPayload(cLine) + if len(cPayload) == 0 { + continue + } + cType := gjson.GetBytes(cPayload, "type").String() + if cType == "response.completed" || cType == "message_stop" { + isTerminalChunk = true + break + } + if finishReason := gjson.GetBytes(cPayload, "choices.0.finish_reason"); finishReason.Exists() && strings.TrimSpace(finishReason.String()) != "" { + isTerminalChunk = true + break + } + } + if isTerminalChunk { + break + } + } + } if replayAccumulator != nil && replayAccumulator.terminal && !replayCommitted && responseFormat == sdktranslator.FormatOpenAIResponse { // Wait for the translated completion, not the first finishReason: // split usage/signature frames may still extend the replay ledger. @@ -315,6 +360,9 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya return } } + if isTerminalChunk { + terminalDelivered = true + } if helps.StopApplyPatchStream(ctx, param, reporter, out, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) { return } @@ -325,6 +373,9 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya if errScan := scanner.Err(); errScan != nil { streamErr = errScan if errors.Is(errScan, context.Canceled) && ctx.Err() != nil { + if terminalDelivered { + return + } if deliveryErr, tracked := usage.WaitStreamDelivery(ctx); tracked && deliveryErr == nil { return } @@ -351,6 +402,7 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya return } } + terminalDelivered = true } }(httpResp) return &cliproxyexecutor.StreamResult{Headers: httpResp.Header.Clone(), Chunks: out}, nil diff --git a/internal/runtime/executor/antigravity_executor_terminal_disconnect_test.go b/internal/runtime/executor/antigravity_executor_terminal_disconnect_test.go new file mode 100644 index 00000000000..d83088c3c83 --- /dev/null +++ b/internal/runtime/executor/antigravity_executor_terminal_disconnect_test.go @@ -0,0 +1,289 @@ +package executor + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +// TestAntigravityStream_ClientDisconnectAfterTerminalChunkDoesNotReportFailure +// reproduces Issue #6376 where downstream client disconnects after terminal event, +// causing upstream scanner context cancellation before upstream EOF. +// The settlement tail must treat this as success and publish observed usage. +func TestAntigravityStream_ClientDisconnectAfterTerminalChunkDoesNotReportFailure(t *testing.T) { + const authID = "antigravity-term-disconnect-test" + capture := &antigravityUsageCapture{authID: authID, records: make(chan usage.Record, 4)} + usage.RegisterNamedPlugin(t.Name(), capture) + t.Cleanup(func() { + usage.RegisterNamedPlugin(t.Name(), antigravityUsageNoop{}) + }) + + const upstreamSSE = `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"Hello, world!"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":5,"totalTokenCount":15},"modelVersion":"gemini-3.8-flash","responseId":"resp-123"}} + +` + + upstreamClosed := make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, upstreamSSE) + if flusher, ok := w.(http.Flusher); ok { + flusher.Flush() + } + // Hold the upstream body open until downstream disconnects or test ends, + // reproducing upstream lag where body close / EOF happens after terminal event. + select { + case <-r.Context().Done(): + case <-upstreamClosed: + } + })) + defer func() { + close(upstreamClosed) + server.Close() + }() + + executor := NewAntigravityExecutor(&config.Config{ + Antigravity: config.AntigravityConfig{}, + RequestRetry: 1, + }) + + deliveryCtx, finishDelivery := usage.WithStreamDelivery(context.Background()) + ctx, cancel := context.WithCancel(deliveryCtx) + defer cancel() + + result, errExecute := executor.ExecuteStream(ctx, &cliproxyauth.Auth{ + ID: authID, + Metadata: map[string]any{ + "access_token": "token-123", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-1", + }, + Attributes: map[string]string{"base_url": server.URL}, + }, cliproxyexecutor.Request{ + Model: "gemini-3.8-flash-high", + Payload: []byte(`{"model":"gemini-3.8-flash-high","input":"hello","stream":true}`), + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + Stream: true, + }) + if errExecute != nil { + t.Fatalf("ExecuteStream() error = %v", errExecute) + } + + // Consume chunks until terminal event response.completed is observed + terminalReceived := false + for chunk := range result.Chunks { + if chunk.Err != nil { + break + } + if gjson.GetBytes(chunk.Payload, "type").String() == "response.completed" { + terminalReceived = true + // Client received completed response and terminates connection + finishDelivery(context.Canceled) + cancel() + break + } + } + + if !terminalReceived { + t.Fatal("expected to receive response.completed chunk before cancellation") + } + + select { + case record := <-capture.records: + if record.Failed { + t.Fatalf("usage record marked failed: status=%d, body=%q", record.Fail.StatusCode, record.Fail.Body) + } + if record.Detail.InputTokens != 10 || record.Detail.OutputTokens != 5 || record.Detail.TotalTokens != 15 { + t.Fatalf("reported usage = %+v, want input 10 output 5 total 15", record.Detail) + } + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for usage record") + } +} + +// TestAntigravityStream_ClientDisconnectPlainContextAfterTerminalChunkDoesNotReportFailure +// covers plain cancellation without streamDelivery tracked. +func TestAntigravityStream_ClientDisconnectPlainContextAfterTerminalChunkDoesNotReportFailure(t *testing.T) { + const authID = "antigravity-plain-cancel-test" + capture := &antigravityUsageCapture{authID: authID, records: make(chan usage.Record, 4)} + usage.RegisterNamedPlugin(t.Name(), capture) + t.Cleanup(func() { + usage.RegisterNamedPlugin(t.Name(), antigravityUsageNoop{}) + }) + + const upstreamSSE = `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"Hello, world!"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":20,"candidatesTokenCount":8,"totalTokenCount":28},"modelVersion":"gemini-3.8-flash","responseId":"resp-456"}} + +` + + upstreamClosed := make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, upstreamSSE) + if flusher, ok := w.(http.Flusher); ok { + flusher.Flush() + } + select { + case <-r.Context().Done(): + case <-upstreamClosed: + } + })) + defer func() { + close(upstreamClosed) + server.Close() + }() + + executor := NewAntigravityExecutor(&config.Config{ + Antigravity: config.AntigravityConfig{}, + RequestRetry: 1, + }) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + result, errExecute := executor.ExecuteStream(ctx, &cliproxyauth.Auth{ + ID: authID, + Metadata: map[string]any{ + "access_token": "token-123", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-1", + }, + Attributes: map[string]string{"base_url": server.URL}, + }, cliproxyexecutor.Request{ + Model: "gemini-3.8-flash-high", + Payload: []byte(`{"model":"gemini-3.8-flash-high","input":"hello","stream":true}`), + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + Stream: true, + }) + if errExecute != nil { + t.Fatalf("ExecuteStream() error = %v", errExecute) + } + + terminalReceived := false + for chunk := range result.Chunks { + if chunk.Err != nil { + break + } + if gjson.GetBytes(chunk.Payload, "type").String() == "response.completed" { + terminalReceived = true + cancel() + break + } + } + + if !terminalReceived { + t.Fatal("expected to receive response.completed chunk before cancellation") + } + + select { + case record := <-capture.records: + if record.Failed { + t.Fatalf("usage record marked failed: status=%d, body=%q", record.Fail.StatusCode, record.Fail.Body) + } + if record.Detail.InputTokens != 20 || record.Detail.OutputTokens != 8 || record.Detail.TotalTokens != 28 { + t.Fatalf("reported usage = %+v, want input 20 output 8 total 28", record.Detail) + } + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for usage record") + } +} + +// TestAntigravityStream_OpenAIChatCompletions_ClientDisconnectAfterStopChunkDoesNotReportFailure +// covers standard chat completions FormatOpenAI streaming where client disconnects after finish_reason. +func TestAntigravityStream_OpenAIChatCompletions_ClientDisconnectAfterStopChunkDoesNotReportFailure(t *testing.T) { + const authID = "antigravity-chat-disconnect-test" + capture := &antigravityUsageCapture{authID: authID, records: make(chan usage.Record, 4)} + usage.RegisterNamedPlugin(t.Name(), capture) + t.Cleanup(func() { + usage.RegisterNamedPlugin(t.Name(), antigravityUsageNoop{}) + }) + + const upstreamSSE = `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"Hello, world!"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":30,"candidatesTokenCount":12,"totalTokenCount":42},"modelVersion":"gemini-3.8-flash","responseId":"resp-789"}} + +` + + upstreamClosed := make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, upstreamSSE) + if flusher, ok := w.(http.Flusher); ok { + flusher.Flush() + } + select { + case <-r.Context().Done(): + case <-upstreamClosed: + } + })) + defer func() { + close(upstreamClosed) + server.Close() + }() + + executor := NewAntigravityExecutor(&config.Config{ + Antigravity: config.AntigravityConfig{}, + RequestRetry: 1, + }) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + result, errExecute := executor.ExecuteStream(ctx, &cliproxyauth.Auth{ + ID: authID, + Metadata: map[string]any{ + "access_token": "token-123", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-1", + }, + Attributes: map[string]string{"base_url": server.URL}, + }, cliproxyexecutor.Request{ + Model: "gemini-3.8-flash-high", + Payload: []byte(`{"model":"gemini-3.8-flash-high","messages":[{"role":"user","content":"hello"}],"stream":true}`), + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAI, + ResponseFormat: sdktranslator.FormatOpenAI, + Stream: true, + }) + if errExecute != nil { + t.Fatalf("ExecuteStream() error = %v", errExecute) + } + + terminalReceived := false + for chunk := range result.Chunks { + if chunk.Err != nil { + break + } + if gjson.GetBytes(chunk.Payload, "choices.0.finish_reason").String() != "" { + terminalReceived = true + cancel() + break + } + } + + if !terminalReceived { + t.Fatal("expected to receive finish_reason chunk before cancellation") + } + + select { + case record := <-capture.records: + if record.Failed { + t.Fatalf("usage record marked failed: status=%d, body=%q", record.Fail.StatusCode, record.Fail.Body) + } + if record.Detail.InputTokens != 30 || record.Detail.OutputTokens != 12 || record.Detail.TotalTokens != 42 { + t.Fatalf("reported usage = %+v, want input 30 output 12 total 42", record.Detail) + } + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for usage record") + } +} From 68afd0d1b47bc274f475c7cb7bae2cb548a35bba Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Mon, 5 Oct 2026 06:40:20 +0800 Subject: [PATCH 050/142] feat(codex): support action sources in Claude web search translation - Extract web search result sources from `action.sources` in item and root payloads in addition to `results` Closes: #5546 --- .../claude/codex_claude_response_test.go | 117 ++++++++++++++++++ .../codex_claude_response_web_search.go | 14 ++- 2 files changed, 128 insertions(+), 3 deletions(-) diff --git a/internal/translator/codex/claude/codex_claude_response_test.go b/internal/translator/codex/claude/codex_claude_response_test.go index 6f74b655c64..e827a165e35 100644 --- a/internal/translator/codex/claude/codex_claude_response_test.go +++ b/internal/translator/codex/claude/codex_claude_response_test.go @@ -990,6 +990,59 @@ func TestConvertCodexResponseToClaude_StreamWebSearchCallReusesFallbackToolUseID } } +func TestConvertCodexResponseToClaude_StreamWebSearchCallActionSources(t *testing.T) { + ctx := context.Background() + originalRequest := []byte(`{ + "tools":[{"type":"web_search_20250305","name":"web_search"}], + "messages":[{"role":"user","content":"search xai docs"}] + }`) + var param any + + chunks := [][]byte{ + []byte(`data: {"type":"response.created","response":{"id":"resp_1","model":"grok-4"}}`), + []byte(`data: {"type":"response.output_item.added","item":{"id":"ws_123","type":"web_search_call","status":"in_progress"}}`), + []byte(`data: {"type":"response.output_item.done","item":{"id":"ws_123","type":"web_search_call","status":"completed","action":{"type":"search","query":"xAI web search docs","sources":[{"type":"url","url":"https://docs.x.ai/developers/tools/web-search","title":"xAI Docs"},{"type":"url","url":"https://example.com/notitle"},{"type":"url","url":""},{"type":"url","url":" "}]}}}`), + []byte(`data: {"type":"response.completed","response":{"stop_reason":"stop","usage":{"input_tokens":5,"output_tokens":10}}}`), + } + var outputs [][]byte + for _, chunk := range chunks { + outputs = append(outputs, ConvertCodexResponseToClaude(ctx, "", originalRequest, nil, chunk, ¶m)...) + } + + var webSearchResultBlock gjson.Result + for _, out := range outputs { + for _, line := range strings.Split(string(out), "\n") { + if !strings.HasPrefix(line, "data: ") { + continue + } + data := gjson.Parse(strings.TrimPrefix(line, "data: ")) + if data.Get("type").String() == "content_block_start" && data.Get("content_block.type").String() == "web_search_tool_result" { + webSearchResultBlock = data.Get("content_block") + } + } + } + + if !webSearchResultBlock.Exists() { + t.Fatalf("expected web_search_tool_result block in stream output") + } + content := webSearchResultBlock.Get("content").Array() + if len(content) != 2 { + t.Fatalf("web_search_tool_result.content length = %d, want 2; raw: %s", len(content), webSearchResultBlock.Get("content").Raw) + } + if got := content[0].Get("url").String(); got != "https://docs.x.ai/developers/tools/web-search" { + t.Errorf("content[0].url = %q, want https://docs.x.ai/developers/tools/web-search", got) + } + if got := content[0].Get("title").String(); got != "xAI Docs" { + t.Errorf("content[0].title = %q, want xAI Docs", got) + } + if got := content[1].Get("url").String(); got != "https://example.com/notitle" { + t.Errorf("content[1].url = %q, want https://example.com/notitle", got) + } + if got := content[1].Get("title").String(); got != "https://example.com/notitle" { + t.Errorf("content[1].title = %q, want https://example.com/notitle (fallback to url)", got) + } +} + func TestConvertCodexResponseToClaude_ShortensLongToolUseIDs(t *testing.T) { longCallID := "call_" + strings.Repeat("a", 62) if len(longCallID) <= 64 { @@ -1188,6 +1241,70 @@ func TestConvertCodexResponseToClaudeNonStream_WebSearchDedupesEmptyOpenPageItem } } +func TestConvertCodexResponseToClaudeNonStream_WebSearchCallActionSources(t *testing.T) { + ctx := context.Background() + originalRequest := []byte(`{"tools":[{"type":"web_search_20250305","name":"web_search"}],"messages":[{"role":"user","content":"search xai docs"}]}`) + response := []byte(`{ + "type":"response.completed", + "response":{ + "id":"resp_1", + "model":"grok-4", + "stop_reason":"stop", + "usage":{"input_tokens":5,"output_tokens":10}, + "output":[ + { + "type":"web_search_call", + "id":"ws_123", + "status":"completed", + "action":{ + "type":"search", + "query":"xAI web search docs", + "sources":[ + {"type":"url","url":"https://docs.x.ai/developers/tools/web-search","title":"xAI Docs"}, + {"type":"url","url":"https://example.com/notitle"}, + {"type":"url","url":""}, + {"type":"url","url":" "} + ] + } + }, + { + "type":"message", + "content":[{"type":"output_text","text":"here are the docs"}] + } + ] + } + }`) + out := ConvertCodexResponseToClaudeNonStream(ctx, "", originalRequest, nil, response, nil) + parsed := gjson.ParseBytes(out) + var resultContent gjson.Result + parsed.Get("content").ForEach(func(_, block gjson.Result) bool { + if block.Get("type").String() == "web_search_tool_result" { + resultContent = block.Get("content") + return false + } + return true + }) + if !resultContent.Exists() { + t.Fatalf("missing web_search_tool_result in non-stream content: %s", string(out)) + } + contentArray := resultContent.Array() + if len(contentArray) != 2 { + t.Fatalf("web_search_tool_result content length = %d, want 2; raw: %s", len(contentArray), resultContent.Raw) + } + if got := contentArray[0].Get("url").String(); got != "https://docs.x.ai/developers/tools/web-search" { + t.Errorf("content[0].url = %q, want https://docs.x.ai/developers/tools/web-search", got) + } + if got := contentArray[0].Get("title").String(); got != "xAI Docs" { + t.Errorf("content[0].title = %q, want xAI Docs", got) + } + if got := contentArray[1].Get("url").String(); got != "https://example.com/notitle" { + t.Errorf("content[1].url = %q, want https://example.com/notitle", got) + } + if got := contentArray[1].Get("title").String(); got != "https://example.com/notitle" { + t.Errorf("content[1].title = %q, want https://example.com/notitle (fallback to url)", got) + } +} + func TestConvertCodexResponseToClaudeNonStream_StopReasonMapping(t *testing.T) { tests := []struct { name string diff --git a/internal/translator/codex/claude/codex_claude_response_web_search.go b/internal/translator/codex/claude/codex_claude_response_web_search.go index 7db54b5ed8a..333e021a84f 100644 --- a/internal/translator/codex/claude/codex_claude_response_web_search.go +++ b/internal/translator/codex/claude/codex_claude_response_web_search.go @@ -127,9 +127,17 @@ func codexWebSearchQuery(root, item gjson.Result) string { } func codexWebSearchResultContent(root, item gjson.Result) []byte { - results := item.Get("results") - if !results.IsArray() { - results = root.Get("results") + var results gjson.Result + for _, candidate := range []gjson.Result{ + item.Get("results"), + root.Get("results"), + item.Get("action.sources"), + root.Get("action.sources"), + } { + if candidate.IsArray() { + results = candidate + break + } } if !results.IsArray() { return nil From 611ebba415902fdc1c07d567168ba7d96bea1607 Mon Sep 17 00:00:00 2001 From: hkfires <10558748+hkfires@users.noreply.github.com> Date: Mon, 5 Oct 2026 11:10:54 +0800 Subject: [PATCH 051/142] refactor(executor): unify model reporting and replay logs Replace Codex-specific response model APIs with shared model observation and remove redundant substitution warning throttling. Consolidate repeated Antigravity context-hash rejection messages into a single request-level log while preserving rejection details across index rebuilds. --- .../executor/antigravity_reasoning_replay.go | 57 ++++++--- ...antigravity_reasoning_replay_index_test.go | 46 +++++++- .../executor/codex_executor_execute.go | 2 +- .../executor/codex_executor_terminal.go | 2 +- .../runtime/executor/codex_openai_images.go | 4 +- .../runtime/executor/helps/response_model.go | 99 +--------------- .../executor/helps/response_model_test.go | 108 +++++------------- .../runtime/executor/helps/usage_helpers.go | 32 +----- 8 files changed, 121 insertions(+), 229 deletions(-) diff --git a/internal/runtime/executor/antigravity_reasoning_replay.go b/internal/runtime/executor/antigravity_reasoning_replay.go index 2bf053e80ba..ebcd29348d2 100644 --- a/internal/runtime/executor/antigravity_reasoning_replay.go +++ b/internal/runtime/executor/antigravity_reasoning_replay.go @@ -350,12 +350,7 @@ func applyAntigravityReasoningReplayItems(payload []byte, items [][]byte, toolSc updated := payload changed := false tracker := newAntigravityReplayContextHashLogTracker() - defer func() { - if tracker != nil && tracker.rejections > 1 { - log.Debugf("antigravity replay: suppressed %d repeated context-hash rejections across %d parts in same request", - tracker.rejections-1, len(tracker.loggedKeys)) - } - }() + defer tracker.log() index := newAntigravityReplayRequestIndexWithTracker(payload, tracker) for len(items) > 0 { batch := newAntigravityReplayBatch(index) @@ -418,7 +413,7 @@ func applyAntigravityReasoningReplayItemsSequential(index *antigravityReplayRequ // mutation so later items observe exactly the same payload as before. // The final item has no successor, so its rebuild would never be read. if itemIndex+1 < len(items) { - index = newAntigravityReplayRequestIndex(updated) + index = newAntigravityReplayRequestIndexWithTracker(updated, index.logTracker) } } return updated, changed @@ -990,13 +985,15 @@ func (i *antigravityReplayRequestIndex) functionCallPartLocationForReplayWithSch // cached signature but not the tool identity. key := antigravityReplayPartKey{contentIndex: location.contentIndex, partIndex: location.partIndex} i.logTracker.rejections++ - if !i.logTracker.loggedKeys[key] { - if len(i.logTracker.loggedKeys) == 0 { - log.Debugf("antigravity replay: exact tool ID match for %q at contents[%d].parts[%d] rejected by context hash (opaque_id=%t)", - name, location.contentIndex, location.partIndex, util.IsGeminiClaudeToolUseID(candidateID)) + if i.logTracker.sample == nil { + i.logTracker.sample = &antigravityReplayContextHashSample{ + name: name, + contentIndex: location.contentIndex, + partIndex: location.partIndex, + opaqueID: util.IsGeminiClaudeToolUseID(candidateID), } - i.logTracker.loggedKeys[key] = true } + i.logTracker.loggedKeys[key] = true return antigravityReplayIndexedPart{}, false } @@ -1322,9 +1319,17 @@ type antigravityReplayIndexedContent struct { // alias the payload bytes and memoizes context fingerprints lazily, so it must // be discarded and rebuilt as soon as the payload changes, and it must never be // shared across goroutines. +type antigravityReplayContextHashSample struct { + name string + contentIndex int + partIndex int + opaqueID bool +} + type antigravityReplayContextHashLogTracker struct { rejections int loggedKeys map[antigravityReplayPartKey]bool + sample *antigravityReplayContextHashSample } func newAntigravityReplayContextHashLogTracker() *antigravityReplayContextHashLogTracker { @@ -1333,6 +1338,28 @@ func newAntigravityReplayContextHashLogTracker() *antigravityReplayContextHashLo } } +func (t *antigravityReplayContextHashLogTracker) log() { + if t == nil || t.sample == nil || t.rejections == 0 { + return + } + if t.rejections == 1 { + log.Debugf("antigravity replay: exact tool ID match for %q at contents[%d].parts[%d] rejected by context hash (opaque_id=%t)", + t.sample.name, t.sample.contentIndex, t.sample.partIndex, t.sample.opaqueID) + return + } + partsNoun := "parts" + if len(t.loggedKeys) == 1 { + partsNoun = "part" + } + rejectionsNoun := "rejections" + if t.rejections-1 == 1 { + rejectionsNoun = "rejection" + } + log.Debugf("antigravity replay: exact tool ID match for %q at contents[%d].parts[%d] rejected by context hash (opaque_id=%t, suppressed %d repeated context-hash %s across %d %s in same request)", + t.sample.name, t.sample.contentIndex, t.sample.partIndex, t.sample.opaqueID, + t.rejections-1, rejectionsNoun, len(t.loggedKeys), partsNoun) +} + type antigravityReplayRequestIndex struct { validContents bool contents []antigravityReplayIndexedContent @@ -1906,14 +1933,14 @@ func insertAntigravityReasoningReplayItemsWithSchemas(index *antigravityReplayRe // antigravityRemoveThoughtSignatureFromOtherParts may already have // rewritten out, so the index has to be refreshed regardless. if hasSuccessor { - index = newAntigravityReplayRequestIndex(out) + index = newAntigravityReplayRequestIndexWithTracker(out, index.logTracker) } continue } out = updated changed = true if hasSuccessor { - index = newAntigravityReplayRequestIndex(out) + index = newAntigravityReplayRequestIndexWithTracker(out, index.logTracker) } case "function_call_part": updated, ok := mergeAntigravityFunctionCallPartReplayWithSchemas(index, out, itemResult, toolSchemas) @@ -1921,7 +1948,7 @@ func insertAntigravityReasoningReplayItemsWithSchemas(index *antigravityReplayRe out = updated changed = true if hasSuccessor { - index = newAntigravityReplayRequestIndex(out) + index = newAntigravityReplayRequestIndexWithTracker(out, index.logTracker) } } } diff --git a/internal/runtime/executor/antigravity_reasoning_replay_index_test.go b/internal/runtime/executor/antigravity_reasoning_replay_index_test.go index 04dacff833d..dc066f4630b 100644 --- a/internal/runtime/executor/antigravity_reasoning_replay_index_test.go +++ b/internal/runtime/executor/antigravity_reasoning_replay_index_test.go @@ -1020,23 +1020,57 @@ func TestApplyAntigravityReasoningReplayItems_PreservesContextHashRejectionLoggi } detailCount := 0 - suppressedCount := 0 for _, entry := range hook.AllEntries() { if entry.Level != log.DebugLevel { continue } + if strings.HasPrefix(entry.Message, "antigravity replay: suppressed repeated context-hash rejections") { + t.Fatalf("standalone suppressed summary log should no longer be emitted: %q", entry.Message) + } if strings.Contains(entry.Message, "rejected by context hash") { detailCount++ + if !strings.Contains(entry.Message, "suppressed 4 repeated context-hash rejections across 1 part in same request") { + t.Fatalf("expected merged suppression summary in single log, got: %q", entry.Message) + } } - if strings.Contains(entry.Message, "suppressed") && strings.Contains(entry.Message, "repeated context-hash rejections") { - suppressedCount++ + } + + if detailCount != 1 { + t.Fatalf("expected exactly 1 merged rejection log, got %d", detailCount) + } +} + +func TestApplyAntigravityReasoningReplayItems_SingleContextHashRejectionLogsWithoutSuppression(t *testing.T) { + hook := newSignatureDebugHook(t) + + tracker := newAntigravityReplayContextHashLogTracker() + func() { + defer tracker.log() + + payload := []byte(`{"request":{"contents":[ + {"role":"user","parts":[{"text":"first prompt"}]}, + {"role":"model","parts":[{"functionCall":{"id":"call-1","name":"exec","args":{"cmd":"ls"}}}]}, + {"role":"user","parts":[{"functionResponse":{"id":"call-1","name":"exec","response":{"result":"ok"}}}]} + ]}}`) + index := newAntigravityReplayRequestIndexWithTracker(payload, tracker) + item := []byte(`{"type":"function_call_part","call_id":"call-1","name":"exec","args":{"cmd":"ls"},"thoughtSignature":"sig-1","contextHash":"wrong-hash-1"}`) + index.functionCallPartLocationForReplayWithSchemas(gjson.ParseBytes(item), map[string]any{"exec": map[string]any{"type": "object"}}) + }() + + detailCount := 0 + for _, entry := range hook.AllEntries() { + if entry.Level != log.DebugLevel { + continue + } + if strings.Contains(entry.Message, "rejected by context hash") { + detailCount++ + if strings.Contains(entry.Message, "suppressed") { + t.Fatalf("single rejection should not mention suppression, got: %q", entry.Message) + } } } if detailCount != 1 { t.Fatalf("expected exactly 1 detailed rejection log, got %d", detailCount) } - if suppressedCount != 1 { - t.Fatalf("expected exactly 1 suppressed summary log across rebuilds, got %d", suppressedCount) - } } diff --git a/internal/runtime/executor/codex_executor_execute.go b/internal/runtime/executor/codex_executor_execute.go index 9c768102f2e..73f6ec228df 100644 --- a/internal/runtime/executor/codex_executor_execute.go +++ b/internal/runtime/executor/codex_executor_execute.go @@ -136,7 +136,7 @@ func (e *CodexExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, re eventData := bytes.TrimSpace(line[5:]) eventData = helps.RestoreCodexMultiAgentV2Response(eventData, optimizeMultiAgentV2) - reporter.ObserveCodexResponseModel(eventData) + reporter.ObserveResponseModel(eventData) eventType := gjson.GetBytes(eventData, "type").String() if helps.HasMeaningfulCodexOutputDelta(eventData) { diff --git a/internal/runtime/executor/codex_executor_terminal.go b/internal/runtime/executor/codex_executor_terminal.go index 01d4b3784da..3e7437d4a59 100644 --- a/internal/runtime/executor/codex_executor_terminal.go +++ b/internal/runtime/executor/codex_executor_terminal.go @@ -595,7 +595,7 @@ func isCodexEmptyPart(payload []byte) bool { // token event, and records the model the upstream reports serving. func observeCodexTokenEvent(reporter *helps.UsageReporter, payload []byte) { helps.ObserveResponsesTokenEvent(reporter, payload) - reporter.ObserveCodexResponseModel(payload) + reporter.ObserveResponseModel(payload) } // newCodexBootstrapOverloadErr reports a buffered overload rejection with its real status. diff --git a/internal/runtime/executor/codex_openai_images.go b/internal/runtime/executor/codex_openai_images.go index e8e0fc0e7d5..ab42d1dc2fb 100644 --- a/internal/runtime/executor/codex_openai_images.go +++ b/internal/runtime/executor/codex_openai_images.go @@ -154,7 +154,7 @@ func (e *CodexExecutor) executeOpenAIImage(ctx context.Context, auth *cliproxyau continue } eventData := bytes.TrimSpace(line[len(dataTag):]) - reporter.ObserveCodexResponseModel(eventData) + reporter.ObserveResponseModel(eventData) switch gjson.GetBytes(eventData, "type").String() { case "response.output_item.done": collectCodexOutputItemDone(eventData, outputItemsByIndex, &outputItemsFallback) @@ -279,7 +279,7 @@ func (e *CodexExecutor) executeOpenAIImageStream(ctx context.Context, auth *clip continue } eventData := bytes.TrimSpace(line[len(dataTag):]) - reporter.ObserveCodexResponseModel(eventData) + reporter.ObserveResponseModel(eventData) switch gjson.GetBytes(eventData, "type").String() { case "response.output_item.done": collectCodexOutputItemDone(eventData, outputItemsByIndex, &outputItemsFallback) diff --git a/internal/runtime/executor/helps/response_model.go b/internal/runtime/executor/helps/response_model.go index c0138e6bc9c..b9c0403a0a5 100644 --- a/internal/runtime/executor/helps/response_model.go +++ b/internal/runtime/executor/helps/response_model.go @@ -2,8 +2,6 @@ package helps import ( "strings" - "sync" - "time" "github.com/router-for-me/CLIProxyAPI/v8/internal/thinking" "github.com/tidwall/gjson" @@ -12,18 +10,7 @@ import ( const ( // maxResponseModelLength is a defensive bound on an upstream-controlled string // reaching logs and usage records; known model ids stay under ~128 bytes. - maxResponseModelLength = 128 - maxCodexResponseModelLength = maxResponseModelLength - - // modelSubstitutionWarnWindow bounds how often one credential and model pair - // warns: on an affected credential every request is substituted. - modelSubstitutionWarnWindow = 10 * time.Minute - codexModelSubstitutionWarnWindow = modelSubstitutionWarnWindow - - // modelSubstitutionWarnMaxEntries caps the throttle state, naturally bounded by - // credentials times models; memory safety wins over perfect throttling. - modelSubstitutionWarnMaxEntries = 1024 - codexModelSubstitutionWarnMaxEntries = modelSubstitutionWarnMaxEntries + maxResponseModelLength = 128 ) // extractResponseModelEvent returns the model an upstream reports serving, read @@ -228,7 +215,7 @@ func extractCodexResponseModelEvent(payload []byte) (model string, terminal bool return "", terminal } model = strings.TrimSpace(modelResult.String()) - if len(model) > maxCodexResponseModelLength { + if len(model) > maxResponseModelLength { return "", terminal } return model, terminal @@ -253,12 +240,6 @@ func normalizeModelName(model string) string { return strings.TrimSpace(thinking.ParseSuffix(strings.ToLower(strings.TrimSpace(model))).ModelName) } -// normalizeCodexModelName lower-cases a model id and drops its thinking suffix, -// which never reaches the upstream request body. -func normalizeCodexModelName(model string) string { - return normalizeModelName(model) -} - func stripModelProviderPrefix(model string) string { if idx := strings.LastIndex(model, "/"); idx >= 0 && idx < len(model)-1 { return model[idx+1:] @@ -266,12 +247,6 @@ func stripModelProviderPrefix(model string) string { return model } -// IsCodexModelSubstituted reports whether the upstream served a model other than the -// requested one; a dated alias pins a snapshot of the same model and is accepted. -func IsCodexModelSubstituted(requested, served string) bool { - return IsModelSubstituted(requested, served) -} - // IsModelSubstituted reports whether the upstream served a model other than the // requested one for any provider; dated aliases and snapshot pins are accepted. func IsModelSubstituted(requested, served string) bool { @@ -321,12 +296,6 @@ func isDatedModelAlias(base, dated string) bool { return isModelDateSuffix(suffix) || isModelNumericVersionSuffix(suffix) } -// isCodexDatedModelAlias reports whether dated is base plus a release date suffix, -// which upstreams use to pin the exact snapshot of the same model. -func isCodexDatedModelAlias(base, dated string) bool { - return isDatedModelAlias(base, dated) -} - func isModelDateSuffix(suffix string) bool { switch len(suffix) { case len("YYYY-MM-DD"): @@ -341,11 +310,6 @@ func isModelDateSuffix(suffix string) bool { } } -// isCodexModelDateSuffix reports whether suffix is a YYYY-MM-DD or YYYYMMDD date. -func isCodexModelDateSuffix(suffix string) bool { - return isModelDateSuffix(suffix) -} - func isModelNumericVersionSuffix(suffix string) bool { if len(suffix) == 3 && isModelDigits(suffix) { return true @@ -364,62 +328,3 @@ func isModelDigits(value string) bool { } return true } - -// isCodexModelDigits reports whether value is a non-empty run of ASCII digits. -func isCodexModelDigits(value string) bool { - return isModelDigits(value) -} - -type codexModelSubstitutionKey struct { - provider string - authID string - requested string - served string -} - -// codexModelSubstitutionThrottle records the last warning per key; nowFunc is -// injectable so tests can advance the window without sleeping. -type codexModelSubstitutionThrottle struct { - mu sync.Mutex - nowFunc func() time.Time - lastWarn map[codexModelSubstitutionKey]time.Time -} - -func newCodexModelSubstitutionThrottle(nowFunc func() time.Time) *codexModelSubstitutionThrottle { - if nowFunc == nil { - nowFunc = time.Now - } - return &codexModelSubstitutionThrottle{ - nowFunc: nowFunc, - lastWarn: make(map[codexModelSubstitutionKey]time.Time), - } -} - -// allow reports whether the key may emit a warning now and records the decision. -// Suppressed repeats stay silent instead of moving to a lower level. -func (t *codexModelSubstitutionThrottle) allow(key codexModelSubstitutionKey) bool { - if t == nil { - return true - } - t.mu.Lock() - defer t.mu.Unlock() - now := t.nowFunc() - if last, ok := t.lastWarn[key]; ok && now.Sub(last) < codexModelSubstitutionWarnWindow { - return false - } - if len(t.lastWarn) >= codexModelSubstitutionWarnMaxEntries { - for storedKey, storedAt := range t.lastWarn { - if now.Sub(storedAt) >= codexModelSubstitutionWarnWindow { - delete(t.lastWarn, storedKey) - } - } - if len(t.lastWarn) >= codexModelSubstitutionWarnMaxEntries { - clear(t.lastWarn) - } - } - t.lastWarn[key] = now - return true -} - -// codexModelSubstitutionWarns throttles substitution warnings process-wide. -var codexModelSubstitutionWarns = newCodexModelSubstitutionThrottle(time.Now) diff --git a/internal/runtime/executor/helps/response_model_test.go b/internal/runtime/executor/helps/response_model_test.go index 32a50c33a28..e32a0c413d8 100644 --- a/internal/runtime/executor/helps/response_model_test.go +++ b/internal/runtime/executor/helps/response_model_test.go @@ -2,11 +2,9 @@ package helps import ( "context" - "strconv" "strings" "sync" "testing" - "time" cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" @@ -107,13 +105,13 @@ func TestExtractCodexResponseModel(t *testing.T) { }, { name: "oversized model value", - payload: `{"type":"response.created","response":{"model":"` + strings.Repeat("m", maxCodexResponseModelLength+1) + `"}}`, + payload: `{"type":"response.created","response":{"model":"` + strings.Repeat("m", maxResponseModelLength+1) + `"}}`, want: "", }, { name: "model value at the length limit", - payload: `{"type":"response.created","response":{"model":"` + strings.Repeat("m", maxCodexResponseModelLength) + `"}}`, - want: strings.Repeat("m", maxCodexResponseModelLength), + payload: `{"type":"response.created","response":{"model":"` + strings.Repeat("m", maxResponseModelLength) + `"}}`, + want: strings.Repeat("m", maxResponseModelLength), }, { name: "done marker", @@ -151,7 +149,7 @@ func TestExtractCodexResponseModel(t *testing.T) { } } -func TestIsCodexModelSubstituted(t *testing.T) { +func TestIsModelSubstituted(t *testing.T) { tests := []struct { name string requested string @@ -185,15 +183,14 @@ func TestIsCodexModelSubstituted(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if got := IsCodexModelSubstituted(tt.requested, tt.served); got != tt.want { - t.Fatalf("IsCodexModelSubstituted(%q, %q) = %v, want %v", tt.requested, tt.served, got, tt.want) + if got := IsModelSubstituted(tt.requested, tt.served); got != tt.want { + t.Fatalf("IsModelSubstituted(%q, %q) = %v, want %v", tt.requested, tt.served, got, tt.want) } }) } } -// setupResponseModelLoggerHook captures warnings from the process-global logrus logger -// and gives the test its own throttle; both are shared, so callers must not use t.Parallel. +// setupResponseModelLoggerHook captures warnings from the process-global logrus logger. func setupResponseModelLoggerHook(t *testing.T) *logtest.Hook { t.Helper() logger := log.StandardLogger() @@ -202,10 +199,7 @@ func setupResponseModelLoggerHook(t *testing.T) *logtest.Hook { savedHooks := logger.ReplaceHooks(make(log.LevelHooks)) hook := new(logtest.Hook) logger.AddHook(hook) - savedThrottle := codexModelSubstitutionWarns - codexModelSubstitutionWarns = newCodexModelSubstitutionThrottle(nil) t.Cleanup(func() { - codexModelSubstitutionWarns = savedThrottle logger.SetLevel(oldLevel) logger.ReplaceHooks(savedHooks) }) @@ -254,7 +248,7 @@ func TestUsageReporterRecordsSubstitutedCodexResponseModelAndWarnsOnce(t *testin var detail usage.Detail for _, line := range strings.Split(codexSubstitutedStream, "\n") { - reporter.ObserveCodexResponseModel([]byte(line)) + reporter.ObserveResponseModel([]byte(line)) if parsed, ok := ParseCodexUsage(JSONPayload([]byte(line))); ok { detail = parsed } @@ -292,13 +286,13 @@ func TestUsageReporterRecordsSubstitutedCodexResponseModelAndWarnsOnce(t *testin } } -// Relies on the global logrus logger and warning throttle; do not add t.Parallel. +// Relies on the global logrus logger; do not add t.Parallel. func TestUsageReporterDoesNotWarnWhenCodexResponseModelMatches(t *testing.T) { hook := setupResponseModelLoggerHook(t) ctx := context.Background() reporter := newCodexTestReporter(ctx, "gpt-6-astra(high)", nil) - reporter.ObserveCodexResponseModel([]byte(`data: {"type":"response.created","response":{"model":"gpt-6-astra-2026-05-13"}}`)) + reporter.ObserveResponseModel([]byte(`data: {"type":"response.created","response":{"model":"gpt-6-astra-2026-05-13"}}`)) reporter.Publish(ctx, usage.Detail{TotalTokens: 3}) if got := reporter.ResponseModel(); got != "gpt-6-astra-2026-05-13" { @@ -309,14 +303,14 @@ func TestUsageReporterDoesNotWarnWhenCodexResponseModelMatches(t *testing.T) { } } -// Relies on the global logrus logger and warning throttle; do not add t.Parallel. +// Relies on the global logrus logger; do not add t.Parallel. func TestUsageReporterIgnoresPayloadsWithoutResponseModel(t *testing.T) { hook := setupResponseModelLoggerHook(t) ctx := context.Background() reporter := newCodexTestReporter(ctx, "gpt-6-astra", nil) - reporter.ObserveCodexResponseModel([]byte(`data: {"type":"response.created","response":{"model":"gpt-5.6-luna"}}`)) - reporter.ObserveCodexResponseModel([]byte(`data: {"type":"response.output_text.delta","delta":"hello"}`)) + reporter.ObserveResponseModel([]byte(`data: {"type":"response.created","response":{"model":"gpt-5.6-luna"}}`)) + reporter.ObserveResponseModel([]byte(`data: {"type":"response.output_text.delta","delta":"hello"}`)) reporter.Publish(ctx, usage.Detail{TotalTokens: 3}) if got := reporter.ResponseModel(); got != "gpt-5.6-luna" { @@ -332,7 +326,7 @@ func TestUsageReporterIgnoresPayloadsWithoutResponseModel(t *testing.T) { } } -// Relies on the global logrus logger and warning throttle; do not add t.Parallel. +// Relies on the global logrus logger; do not add t.Parallel. func TestUsageReporterWarnsOnceUnderConcurrentObservationsAndPublishes(t *testing.T) { hook := setupResponseModelLoggerHook(t) ctx := context.Background() @@ -349,9 +343,9 @@ func TestUsageReporterWarnsOnceUnderConcurrentObservationsAndPublishes(t *testin defer wg.Done() <-start if worker%2 == 0 { - reporter.ObserveCodexResponseModel(created) + reporter.ObserveResponseModel(created) } else { - reporter.ObserveCodexResponseModel(completed) + reporter.ObserveResponseModel(completed) } reporter.EnsurePublished(ctx) }(i) @@ -367,97 +361,53 @@ func TestUsageReporterWarnsOnceUnderConcurrentObservationsAndPublishes(t *testin } } -// Relies on the global logrus logger and warning throttle; do not add t.Parallel. -func TestUsageReporterThrottlesRepeatedSubstitutionWarnings(t *testing.T) { +// Relies on the global logrus logger; do not add t.Parallel. +func TestUsageReporterEmitsWarningOnRepeatedSubstitutionsWithoutThrottle(t *testing.T) { hook := setupResponseModelLoggerHook(t) ctx := context.Background() - now := time.Unix(1_700_000_000, 0) - codexModelSubstitutionWarns = newCodexModelSubstitutionThrottle(func() time.Time { return now }) publishSubstitutedAttempt := func(authID, authIndex string) { auth := &cliproxyauth.Auth{ID: authID, Index: authIndex, Provider: "codex"} reporter := newCodexTestReporter(ctx, "gpt-6-astra", auth) - reporter.ObserveCodexResponseModel([]byte(`{"type":"response.completed","response":{"model":"gpt-5.6-luna"}}`)) + reporter.ObserveResponseModel([]byte(`{"type":"response.completed","response":{"model":"gpt-5.6-luna"}}`)) reporter.Publish(ctx, usage.Detail{TotalTokens: 3}) } publishSubstitutedAttempt("codex-auth-1", "auth-index-7") publishSubstitutedAttempt("codex-auth-1", "auth-index-7") - if warnings := substitutionWarnings(hook); len(warnings) != 1 { - t.Fatalf("substitution warnings = %d, want 1 inside the window: %#v", len(warnings), warnings) - } - - // A different credential is an independent signal. - publishSubstitutedAttempt("codex-auth-2", "auth-index-8") - if warnings := substitutionWarnings(hook); len(warnings) != 2 { - t.Fatalf("substitution warnings = %d, want 2 after a second credential: %#v", len(warnings), warnings) - } - - now = now.Add(codexModelSubstitutionWarnWindow - time.Second) - publishSubstitutedAttempt("codex-auth-1", "auth-index-7") if warnings := substitutionWarnings(hook); len(warnings) != 2 { - t.Fatalf("substitution warnings = %d, want 2 before the window elapsed: %#v", len(warnings), warnings) + t.Fatalf("substitution warnings = %d, want 2 without throttle: %#v", len(warnings), warnings) } - now = now.Add(time.Second) - publishSubstitutedAttempt("codex-auth-1", "auth-index-7") + // A different credential is also recorded without throttle. + publishSubstitutedAttempt("codex-auth-2", "auth-index-8") if warnings := substitutionWarnings(hook); len(warnings) != 3 { - t.Fatalf("substitution warnings = %d, want 3 once the window elapsed: %#v", len(warnings), warnings) + t.Fatalf("substitution warnings = %d, want 3: %#v", len(warnings), warnings) } } -// Relies on the global logrus logger and warning throttle; do not add t.Parallel. -func TestUsageReporterThrottlesSubstitutionWarningsAcrossServedModelCase(t *testing.T) { +// Relies on the global logrus logger; do not add t.Parallel. +func TestUsageReporterEmitsWarningAcrossServedModelCaseWithoutThrottle(t *testing.T) { hook := setupResponseModelLoggerHook(t) ctx := context.Background() - now := time.Unix(1_700_000_000, 0) - codexModelSubstitutionWarns = newCodexModelSubstitutionThrottle(func() time.Time { return now }) auth := &cliproxyauth.Auth{ID: "codex-auth-1", Index: "auth-index-7", Provider: "codex"} for _, served := range []string{"gpt-5.6-luna", "GPT-5.6-LUNA"} { reporter := newCodexTestReporter(ctx, "gpt-6-astra", auth) - reporter.ObserveCodexResponseModel([]byte(`{"type":"response.completed","response":{"model":"` + served + `"}}`)) + reporter.ObserveResponseModel([]byte(`{"type":"response.completed","response":{"model":"` + served + `"}}`)) reporter.Publish(ctx, usage.Detail{TotalTokens: 3}) } - // Both attempts describe one substitution pair, so the casing must not open a - // second throttle window while the WARN keeps the raw upstream name. warnings := substitutionWarnings(hook) - if len(warnings) != 1 { - t.Fatalf("substitution warnings = %d, want 1 for one normalized pair: %#v", len(warnings), warnings) - } - want := `codex executor: upstream served model "gpt-5.6-luna" for requested model "gpt-6-astra" (auth_index=auth-index-7)` - if warnings[0] != want { - t.Fatalf("warning = %q, want %q", warnings[0], want) - } -} - -func TestCodexModelSubstitutionThrottleBoundsStoredEntries(t *testing.T) { - now := time.Unix(1_700_000_000, 0) - throttle := newCodexModelSubstitutionThrottle(func() time.Time { return now }) - - for i := range codexModelSubstitutionWarnMaxEntries + 16 { - key := codexModelSubstitutionKey{ - authID: "codex-auth-" + strconv.Itoa(i), - requested: "gpt-6-astra", - served: "gpt-5.6-luna", - } - if !throttle.allow(key) { - t.Fatalf("first warning for key %d was suppressed", i) - } - } - throttle.mu.Lock() - stored := len(throttle.lastWarn) - throttle.mu.Unlock() - if stored > codexModelSubstitutionWarnMaxEntries { - t.Fatalf("stored throttle entries = %d, want at most %d", stored, codexModelSubstitutionWarnMaxEntries) + if len(warnings) != 2 { + t.Fatalf("substitution warnings = %d, want 2 without throttle: %#v", len(warnings), warnings) } } func TestUsageReporterAdditionalModelRecordOmitsResponseModel(t *testing.T) { ctx := context.Background() reporter := newCodexTestReporter(ctx, "gpt-5.4-mini", nil) - reporter.ObserveCodexResponseModel([]byte(`data: {"type":"response.completed","response":{"model":"gpt-5.4-mini"}}`)) + reporter.ObserveResponseModel([]byte(`data: {"type":"response.completed","response":{"model":"gpt-5.4-mini"}}`)) mainRecord := reporter.buildRecord(usage.Detail{TotalTokens: 12}, false) if mainRecord.ResponseModel != "gpt-5.4-mini" { diff --git a/internal/runtime/executor/helps/usage_helpers.go b/internal/runtime/executor/helps/usage_helpers.go index 266012a431d..5774964f025 100644 --- a/internal/runtime/executor/helps/usage_helpers.go +++ b/internal/runtime/executor/helps/usage_helpers.go @@ -222,12 +222,6 @@ func (r *UsageReporter) ObserveResponseModel(payload []byte) { } } -// ObserveCodexResponseModel stores the model reported by a codex upstream event and -// ignores payloads without one; the substitution warning is emitted at publish time. -func (r *UsageReporter) ObserveCodexResponseModel(payload []byte) { - r.ObserveResponseModel(payload) -} - // SetResponseModel sets the reported model directly if valid and not already marked final. func (r *UsageReporter) SetResponseModel(model string) { if r == nil || r.responseModelFinal.Load() { @@ -270,8 +264,8 @@ func (r *UsageReporter) IsResponseModelFinal() bool { return r != nil && r.responseModelFinal.Load() } -// warnModelSubstitution warns about a silent upstream model swap, throttled per -// credential and model pair, and labels the credential by index only, never by account. +// warnModelSubstitution warns about a silent upstream model swap, and labels the +// credential by index only, never by account. func (r *UsageReporter) warnModelSubstitution(ctx context.Context) { if r == nil { return @@ -287,31 +281,13 @@ func (r *UsageReporter) warnModelSubstitution(ctx context.Context) { if r.model != "" && !IsModelSubstituted(r.model, served) { return } - // The throttle key uses the same normalized names as the substitution check, so - // aliases of one pair share a window instead of each warning on its own. - requested := normalizeModelName(expectedModel) - servedNormalized := normalizeModelName(served) - providerName := r.provider + providerName := strings.TrimSpace(r.provider) if providerName == "" { - providerName = "codex" - } - if !codexModelSubstitutionWarns.allow(codexModelSubstitutionKey{ - provider: providerName, - authID: r.authID, - requested: requested, - served: servedNormalized, - }) { - return + providerName = "unknown" } LogWithRequestID(ctx).Warnf("%s executor: upstream served model %q for requested model %q (auth_index=%s)", providerName, served, r.model, r.authIndexForLog()) } -// warnCodexModelSubstitution warns about a silent upstream model swap, throttled per -// credential and model pair, and labels the credential by index only, never by account. -func (r *UsageReporter) warnCodexModelSubstitution(ctx context.Context) { - r.warnModelSubstitution(ctx) -} - // authIndexForLog labels the credential without exposing its file name or account. func (r *UsageReporter) authIndexForLog() string { if r == nil { From 17dc1b81c248a10a5aa4db4f2268d723607a87a5 Mon Sep 17 00:00:00 2001 From: hkfires <10558748+hkfires@users.noreply.github.com> Date: Mon, 5 Oct 2026 11:41:11 +0800 Subject: [PATCH 052/142] feat(antigravity): enhance context hash rejection logging and introduce replay phases --- .../executor/antigravity_reasoning_replay.go | 73 +++++++++++------ ...antigravity_reasoning_replay_index_test.go | 82 ++++++++++++++----- 2 files changed, 110 insertions(+), 45 deletions(-) diff --git a/internal/runtime/executor/antigravity_reasoning_replay.go b/internal/runtime/executor/antigravity_reasoning_replay.go index ebcd29348d2..15a6067b1a3 100644 --- a/internal/runtime/executor/antigravity_reasoning_replay.go +++ b/internal/runtime/executor/antigravity_reasoning_replay.go @@ -353,6 +353,7 @@ func applyAntigravityReasoningReplayItems(payload []byte, items [][]byte, toolSc defer tracker.log() index := newAntigravityReplayRequestIndexWithTracker(payload, tracker) for len(items) > 0 { + tracker.setPhase(antigravityReplayPhaseBatch) batch := newAntigravityReplayBatch(index) handled := 0 for handled < len(items) && batch.apply(items[handled], toolSchemas) { @@ -364,6 +365,7 @@ func applyAntigravityReasoningReplayItems(payload []byte, items [][]byte, toolSc // A malformed or non-addressable part offset makes splicing unsafe. // Nothing has been committed yet, so retain the exact legacy behavior // for all remaining items. + tracker.setPhase(antigravityReplayPhaseSequential) next, sequentialChanged := applyAntigravityReasoningReplayItemsSequential(index, updated, items, toolSchemas) return next, changed || sequentialChanged } @@ -384,6 +386,7 @@ func applyAntigravityReasoningReplayItems(payload []byte, items [][]byte, toolSc // sequential implementation, then start another safe batch. A rare // fallback therefore cannot make every preceding signature rewrite the // entire request again. + tracker.setPhase(antigravityReplayPhaseSequential) next, itemChanged := applyAntigravityReasoningReplayItemsSequential(index, updated, items[:1], toolSchemas) updated = next changed = itemChanged || changed @@ -984,16 +987,12 @@ func (i *antigravityReplayRequestIndex) functionCallPartLocationForReplayWithSch // identical. Only the surrounding context drifted, which invalidates the // cached signature but not the tool identity. key := antigravityReplayPartKey{contentIndex: location.contentIndex, partIndex: location.partIndex} - i.logTracker.rejections++ - if i.logTracker.sample == nil { - i.logTracker.sample = &antigravityReplayContextHashSample{ - name: name, - contentIndex: location.contentIndex, - partIndex: location.partIndex, - opaqueID: util.IsGeminiClaudeToolUseID(candidateID), - } - } - i.logTracker.loggedKeys[key] = true + i.logTracker.recordRejection(antigravityReplayContextHashSample{ + name: name, + contentIndex: location.contentIndex, + partIndex: location.partIndex, + opaqueID: util.IsGeminiClaudeToolUseID(candidateID), + }, key) return antigravityReplayIndexedPart{}, false } @@ -1319,6 +1318,13 @@ type antigravityReplayIndexedContent struct { // alias the payload bytes and memoizes context fingerprints lazily, so it must // be discarded and rebuilt as soon as the payload changes, and it must never be // shared across goroutines. +type antigravityReplayPhase int + +const ( + antigravityReplayPhaseBatch antigravityReplayPhase = iota + antigravityReplayPhaseSequential +) + type antigravityReplayContextHashSample struct { name string contentIndex int @@ -1327,9 +1333,11 @@ type antigravityReplayContextHashSample struct { } type antigravityReplayContextHashLogTracker struct { - rejections int - loggedKeys map[antigravityReplayPartKey]bool - sample *antigravityReplayContextHashSample + phase antigravityReplayPhase + batchRejections int + sequentialRejections int + loggedKeys map[antigravityReplayPartKey]bool + sample *antigravityReplayContextHashSample } func newAntigravityReplayContextHashLogTracker() *antigravityReplayContextHashLogTracker { @@ -1338,26 +1346,39 @@ func newAntigravityReplayContextHashLogTracker() *antigravityReplayContextHashLo } } -func (t *antigravityReplayContextHashLogTracker) log() { - if t == nil || t.sample == nil || t.rejections == 0 { +func (t *antigravityReplayContextHashLogTracker) setPhase(phase antigravityReplayPhase) { + if t != nil { + t.phase = phase + } +} + +func (t *antigravityReplayContextHashLogTracker) recordRejection(sample antigravityReplayContextHashSample, key antigravityReplayPartKey) { + if t == nil { return } - if t.rejections == 1 { - log.Debugf("antigravity replay: exact tool ID match for %q at contents[%d].parts[%d] rejected by context hash (opaque_id=%t)", - t.sample.name, t.sample.contentIndex, t.sample.partIndex, t.sample.opaqueID) + if t.phase == antigravityReplayPhaseSequential { + t.sequentialRejections++ + } else { + t.batchRejections++ + } + if t.sample == nil { + t.sample = &sample + } + t.loggedKeys[key] = true +} + +func (t *antigravityReplayContextHashLogTracker) log() { + if t == nil || t.sample == nil || (t.batchRejections == 0 && t.sequentialRejections == 0) { return } + partsCount := len(t.loggedKeys) partsNoun := "parts" - if len(t.loggedKeys) == 1 { + if partsCount == 1 { partsNoun = "part" } - rejectionsNoun := "rejections" - if t.rejections-1 == 1 { - rejectionsNoun = "rejection" - } - log.Debugf("antigravity replay: exact tool ID match for %q at contents[%d].parts[%d] rejected by context hash (opaque_id=%t, suppressed %d repeated context-hash %s across %d %s in same request)", - t.sample.name, t.sample.contentIndex, t.sample.partIndex, t.sample.opaqueID, - t.rejections-1, rejectionsNoun, len(t.loggedKeys), partsNoun) + log.Debugf("antigravity replay: context hash rejected %d %s (first=%q at contents[%d].parts[%d], opaque_id=%t, batch=%d, seq=%d)", + partsCount, partsNoun, t.sample.name, t.sample.contentIndex, t.sample.partIndex, t.sample.opaqueID, + t.batchRejections, t.sequentialRejections) } type antigravityReplayRequestIndex struct { diff --git a/internal/runtime/executor/antigravity_reasoning_replay_index_test.go b/internal/runtime/executor/antigravity_reasoning_replay_index_test.go index dc066f4630b..4fc80a81db7 100644 --- a/internal/runtime/executor/antigravity_reasoning_replay_index_test.go +++ b/internal/runtime/executor/antigravity_reasoning_replay_index_test.go @@ -1027,10 +1027,11 @@ func TestApplyAntigravityReasoningReplayItems_PreservesContextHashRejectionLoggi if strings.HasPrefix(entry.Message, "antigravity replay: suppressed repeated context-hash rejections") { t.Fatalf("standalone suppressed summary log should no longer be emitted: %q", entry.Message) } - if strings.Contains(entry.Message, "rejected by context hash") { + if strings.Contains(entry.Message, "context hash rejected") { detailCount++ - if !strings.Contains(entry.Message, "suppressed 4 repeated context-hash rejections across 1 part in same request") { - t.Fatalf("expected merged suppression summary in single log, got: %q", entry.Message) + expected := `antigravity replay: context hash rejected 1 part (first="exec" at contents[1].parts[0], opaque_id=false, batch=3, seq=2)` + if entry.Message != expected { + t.Fatalf("expected log %q, got %q", expected, entry.Message) } } } @@ -1040,32 +1041,75 @@ func TestApplyAntigravityReasoningReplayItems_PreservesContextHashRejectionLoggi } } -func TestApplyAntigravityReasoningReplayItems_SingleContextHashRejectionLogsWithoutSuppression(t *testing.T) { +func TestApplyAntigravityReasoningReplayItems_MultiPartContextHashRejectionLogging(t *testing.T) { hook := newSignatureDebugHook(t) - tracker := newAntigravityReplayContextHashLogTracker() - func() { - defer tracker.log() + payload := []byte(`{"request":{"contents":[ + {"role":"user","parts":[{"text":"first prompt"}]}, + {"role":"model","parts":[{"functionCall":{"id":"call-1","name":"exec","args":{"cmd":"ls"}}}]}, + {"role":"user","parts":[{"functionResponse":{"id":"call-1","name":"exec","response":{"result":"ok"}}}]}, + {"role":"model","parts":[{"functionCall":{"id":"call-2","name":"read","args":{"path":"a.txt"}}}]}, + {"role":"user","parts":[{"functionResponse":{"id":"call-2","name":"read","response":{"result":"content"}}}]} + ]}}`) + + item1 := []byte(`{"type":"function_call_part","call_id":"call-1","name":"exec","args":{"cmd":"ls"},"thoughtSignature":"sig-1","contextHash":"wrong-hash-1"}`) + item2 := []byte(`{"type":"function_call_part","call_id":"call-2","name":"read","args":{"path":"a.txt"},"thoughtSignature":"sig-2","contextHash":"wrong-hash-2"}`) + + toolSchemas := map[string]any{ + "exec": map[string]any{"type": "object"}, + "read": map[string]any{"type": "object"}, + } + _, changed := applyAntigravityReasoningReplayItems(payload, [][]byte{item1, item2}, toolSchemas) + if changed { + t.Fatal("expected payload not to change") + } - payload := []byte(`{"request":{"contents":[ - {"role":"user","parts":[{"text":"first prompt"}]}, - {"role":"model","parts":[{"functionCall":{"id":"call-1","name":"exec","args":{"cmd":"ls"}}}]}, - {"role":"user","parts":[{"functionResponse":{"id":"call-1","name":"exec","response":{"result":"ok"}}}]} - ]}}`) - index := newAntigravityReplayRequestIndexWithTracker(payload, tracker) - item := []byte(`{"type":"function_call_part","call_id":"call-1","name":"exec","args":{"cmd":"ls"},"thoughtSignature":"sig-1","contextHash":"wrong-hash-1"}`) - index.functionCallPartLocationForReplayWithSchemas(gjson.ParseBytes(item), map[string]any{"exec": map[string]any{"type": "object"}}) - }() + detailCount := 0 + for _, entry := range hook.AllEntries() { + if entry.Level != log.DebugLevel { + continue + } + if strings.Contains(entry.Message, "context hash rejected") { + detailCount++ + expected := `antigravity replay: context hash rejected 2 parts (first="exec" at contents[1].parts[0], opaque_id=false, batch=2, seq=2)` + if entry.Message != expected { + t.Fatalf("expected log %q, got %q", expected, entry.Message) + } + } + } + + if detailCount != 1 { + t.Fatalf("expected exactly 1 multi-part rejection log, got %d", detailCount) + } +} + +func TestApplyAntigravityReasoningReplayItems_SingleContextHashRejectionLogs(t *testing.T) { + hook := newSignatureDebugHook(t) + + payload := []byte(`{"request":{"contents":[ + {"role":"user","parts":[{"text":"first prompt"}]}, + {"role":"model","parts":[{"functionCall":{"id":"call-1","name":"exec","args":{"cmd":"ls"}}}]}, + {"role":"user","parts":[{"functionResponse":{"id":"call-1","name":"exec","response":{"result":"ok"}}}]} + ]}}`) + + item := []byte(`{"type":"function_call_part","call_id":"call-1","name":"exec","args":{"cmd":"ls"},"thoughtSignature":"sig-1","contextHash":"wrong-hash-1"}`) + + toolSchemas := map[string]any{"exec": map[string]any{"type": "object"}} + _, changed := applyAntigravityReasoningReplayItems(payload, [][]byte{item}, toolSchemas) + if changed { + t.Fatal("expected payload to remain unchanged on rejection") + } detailCount := 0 for _, entry := range hook.AllEntries() { if entry.Level != log.DebugLevel { continue } - if strings.Contains(entry.Message, "rejected by context hash") { + if strings.Contains(entry.Message, "context hash rejected") { detailCount++ - if strings.Contains(entry.Message, "suppressed") { - t.Fatalf("single rejection should not mention suppression, got: %q", entry.Message) + expected := `antigravity replay: context hash rejected 1 part (first="exec" at contents[1].parts[0], opaque_id=false, batch=1, seq=1)` + if entry.Message != expected { + t.Fatalf("expected log %q, got %q", expected, entry.Message) } } } From 40f4df07b7c81a84fe676f3cb15c8fd7c11b50ec Mon Sep 17 00:00:00 2001 From: hkfires <10558748+hkfires@users.noreply.github.com> Date: Mon, 5 Oct 2026 13:24:20 +0800 Subject: [PATCH 053/142] feat(antigravity): enhance context hash rejection logging and batch retry logic --- .../executor/antigravity_reasoning_replay.go | 94 +++++++++---- ...antigravity_reasoning_replay_index_test.go | 126 +++++++++++++++++- 2 files changed, 196 insertions(+), 24 deletions(-) diff --git a/internal/runtime/executor/antigravity_reasoning_replay.go b/internal/runtime/executor/antigravity_reasoning_replay.go index 15a6067b1a3..964284e79e9 100644 --- a/internal/runtime/executor/antigravity_reasoning_replay.go +++ b/internal/runtime/executor/antigravity_reasoning_replay.go @@ -356,7 +356,13 @@ func applyAntigravityReasoningReplayItems(payload []byte, items [][]byte, toolSc tracker.setPhase(antigravityReplayPhaseBatch) batch := newAntigravityReplayBatch(index) handled := 0 - for handled < len(items) && batch.apply(items[handled], toolSchemas) { + contextHashStopped := false + for handled < len(items) { + rejectionsBefore := tracker.contextHashRejectionCount() + if !batch.apply(items[handled], toolSchemas) { + contextHashStopped = tracker.contextHashRejectionCount() > rejectionsBefore + break + } handled++ } if handled > 0 { @@ -376,10 +382,13 @@ func applyAntigravityReasoningReplayItems(payload []byte, items [][]byte, toolSc break } index = newAntigravityReplayRequestIndexWithTracker(updated, tracker) - // Retry the first unhandled item against the freshly flushed payload. - // It may only have rejected the batch because a prior stable-ID restore - // made the old context index stale. - continue + // Retry only when this batch restored a stable ID. That changes the + // context fingerprint, so the rejection may belong to the stale index. + // A context-hash mismatch on an unchanged identity cannot be repaired + // by rebuilding the same payload. + if !(contextHashStopped && !batch.identityChanged) { + continue + } } // Apply one structural or context-dependent item with the original @@ -1332,17 +1341,30 @@ type antigravityReplayContextHashSample struct { opaqueID bool } -type antigravityReplayContextHashLogTracker struct { - phase antigravityReplayPhase +type antigravityReplayContextHashGroupKey struct { + toolName string + opaqueID bool +} + +type antigravityReplayContextHashGroup struct { + key antigravityReplayContextHashGroupKey batchRejections int sequentialRejections int loggedKeys map[antigravityReplayPartKey]bool - sample *antigravityReplayContextHashSample + sampleContentIndex int + samplePartIndex int +} + +type antigravityReplayContextHashLogTracker struct { + phase antigravityReplayPhase + totalContextHashRejections int + groups map[antigravityReplayContextHashGroupKey]*antigravityReplayContextHashGroup + order []antigravityReplayContextHashGroupKey } func newAntigravityReplayContextHashLogTracker() *antigravityReplayContextHashLogTracker { return &antigravityReplayContextHashLogTracker{ - loggedKeys: make(map[antigravityReplayPartKey]bool), + groups: make(map[antigravityReplayContextHashGroupKey]*antigravityReplayContextHashGroup), } } @@ -1352,33 +1374,59 @@ func (t *antigravityReplayContextHashLogTracker) setPhase(phase antigravityRepla } } +func (t *antigravityReplayContextHashLogTracker) contextHashRejectionCount() int { + if t == nil { + return 0 + } + return t.totalContextHashRejections +} + func (t *antigravityReplayContextHashLogTracker) recordRejection(sample antigravityReplayContextHashSample, key antigravityReplayPartKey) { if t == nil { return } + t.totalContextHashRejections++ + groupKey := antigravityReplayContextHashGroupKey{ + toolName: sample.name, + opaqueID: sample.opaqueID, + } + group, exists := t.groups[groupKey] + if !exists { + group = &antigravityReplayContextHashGroup{ + key: groupKey, + loggedKeys: make(map[antigravityReplayPartKey]bool), + sampleContentIndex: sample.contentIndex, + samplePartIndex: sample.partIndex, + } + t.groups[groupKey] = group + t.order = append(t.order, groupKey) + } if t.phase == antigravityReplayPhaseSequential { - t.sequentialRejections++ + group.sequentialRejections++ } else { - t.batchRejections++ - } - if t.sample == nil { - t.sample = &sample + group.batchRejections++ } - t.loggedKeys[key] = true + group.loggedKeys[key] = true } func (t *antigravityReplayContextHashLogTracker) log() { - if t == nil || t.sample == nil || (t.batchRejections == 0 && t.sequentialRejections == 0) { + if t == nil || len(t.groups) == 0 { return } - partsCount := len(t.loggedKeys) - partsNoun := "parts" - if partsCount == 1 { - partsNoun = "part" + for _, groupKey := range t.order { + group := t.groups[groupKey] + if group == nil || (group.batchRejections == 0 && group.sequentialRejections == 0) { + continue + } + partsCount := len(group.loggedKeys) + partsNoun := "parts" + if partsCount == 1 { + partsNoun = "part" + } + log.Debugf("antigravity replay: context hash rejected %d %s (first=%q at contents[%d].parts[%d], opaque_id=%t, batch=%d, seq=%d)", + partsCount, partsNoun, group.key.toolName, group.sampleContentIndex, group.samplePartIndex, group.key.opaqueID, + group.batchRejections, group.sequentialRejections) } - log.Debugf("antigravity replay: context hash rejected %d %s (first=%q at contents[%d].parts[%d], opaque_id=%t, batch=%d, seq=%d)", - partsCount, partsNoun, t.sample.name, t.sample.contentIndex, t.sample.partIndex, t.sample.opaqueID, - t.batchRejections, t.sequentialRejections) } type antigravityReplayRequestIndex struct { diff --git a/internal/runtime/executor/antigravity_reasoning_replay_index_test.go b/internal/runtime/executor/antigravity_reasoning_replay_index_test.go index 4fc80a81db7..f3d33ddbe36 100644 --- a/internal/runtime/executor/antigravity_reasoning_replay_index_test.go +++ b/internal/runtime/executor/antigravity_reasoning_replay_index_test.go @@ -1064,6 +1064,53 @@ func TestApplyAntigravityReasoningReplayItems_MultiPartContextHashRejectionLoggi t.Fatal("expected payload not to change") } + execCount := 0 + readCount := 0 + for _, entry := range hook.AllEntries() { + if entry.Level != log.DebugLevel { + continue + } + if strings.Contains(entry.Message, `first="exec"`) { + execCount++ + expected := `antigravity replay: context hash rejected 1 part (first="exec" at contents[1].parts[0], opaque_id=false, batch=1, seq=1)` + if entry.Message != expected { + t.Fatalf("expected exec log %q, got %q", expected, entry.Message) + } + } + if strings.Contains(entry.Message, `first="read"`) { + readCount++ + expected := `antigravity replay: context hash rejected 1 part (first="read" at contents[3].parts[0], opaque_id=false, batch=1, seq=1)` + if entry.Message != expected { + t.Fatalf("expected read log %q, got %q", expected, entry.Message) + } + } + } + + if execCount != 1 || readCount != 1 { + t.Fatalf("expected 1 exec log and 1 read log for different tools, got exec=%d read=%d", execCount, readCount) + } +} + +func TestApplyAntigravityReasoningReplayItems_SameToolMultiPartContextHashRejectionAggregates(t *testing.T) { + hook := newSignatureDebugHook(t) + + payload := []byte(`{"request":{"contents":[ + {"role":"user","parts":[{"text":"first prompt"}]}, + {"role":"model","parts":[{"functionCall":{"id":"call-1","name":"exec","args":{"cmd":"ls"}}}]}, + {"role":"user","parts":[{"functionResponse":{"id":"call-1","name":"exec","response":{"result":"ok"}}}]}, + {"role":"model","parts":[{"functionCall":{"id":"call-2","name":"exec","args":{"cmd":"pwd"}}}]}, + {"role":"user","parts":[{"functionResponse":{"id":"call-2","name":"exec","response":{"result":"/app"}}}]} + ]}}`) + + item1 := []byte(`{"type":"function_call_part","call_id":"call-1","name":"exec","args":{"cmd":"ls"},"thoughtSignature":"sig-1","contextHash":"wrong-hash-1"}`) + item2 := []byte(`{"type":"function_call_part","call_id":"call-2","name":"exec","args":{"cmd":"pwd"},"thoughtSignature":"sig-2","contextHash":"wrong-hash-2"}`) + + toolSchemas := map[string]any{"exec": map[string]any{"type": "object"}} + _, changed := applyAntigravityReasoningReplayItems(payload, [][]byte{item1, item2}, toolSchemas) + if changed { + t.Fatal("expected payload not to change") + } + detailCount := 0 for _, entry := range hook.AllEntries() { if entry.Level != log.DebugLevel { @@ -1079,7 +1126,49 @@ func TestApplyAntigravityReasoningReplayItems_MultiPartContextHashRejectionLoggi } if detailCount != 1 { - t.Fatalf("expected exactly 1 multi-part rejection log, got %d", detailCount) + t.Fatalf("expected exactly 1 aggregated log for same tool across multiple parts, got %d", detailCount) + } +} + +func TestApplyAntigravityReasoningReplayItems_SameToolDifferentOpaqueIDTypesRemainSeparate(t *testing.T) { + hook := newSignatureDebugHook(t) + + nativeID := "call-2" + name := "exec" + args := `{"cmd":"pwd"}` + opaqueID := util.GeminiClaudeToolUseID(nativeID, name, args) + payload := []byte(fmt.Sprintf(`{"request":{"contents":[ + {"role":"user","parts":[{"text":"first prompt"}]}, + {"role":"model","parts":[{"functionCall":{"id":"call-1","name":%q,"args":{"cmd":"ls"}}}]}, + {"role":"user","parts":[{"functionResponse":{"id":"call-1","name":%q,"response":{"result":"ok"}}}]}, + {"role":"model","parts":[{"functionCall":{"id":%q,"name":%q,"args":%s}}]}, + {"role":"user","parts":[{"functionResponse":{"id":%q,"name":%q,"response":{"result":"/app"}}}]} + ]}}`, name, name, opaqueID, name, args, opaqueID, name)) + + item1 := []byte(`{"type":"function_call_part","call_id":"call-1","name":"exec","args":{"cmd":"ls"},"thoughtSignature":"sig-1","contextHash":"wrong-hash-1"}`) + item2 := []byte(fmt.Sprintf(`{"type":"function_call_part","call_id":%q,"name":%q,"args":%s,"thoughtSignature":"sig-2","contextHash":"wrong-hash-2"}`, nativeID, name, args)) + + _, _ = applyAntigravityReasoningReplayItems(payload, [][]byte{item1, item2}, map[string]any{ + "exec": map[string]any{"type": "object"}, + }) + + entries := make([]string, 0, 2) + for _, entry := range hook.AllEntries() { + if entry.Level == log.DebugLevel && strings.Contains(entry.Message, "context hash rejected") { + entries = append(entries, entry.Message) + } + } + expected := []string{ + `antigravity replay: context hash rejected 1 part (first="exec" at contents[1].parts[0], opaque_id=false, batch=1, seq=1)`, + `antigravity replay: context hash rejected 1 part (first="exec" at contents[3].parts[0], opaque_id=true, batch=1, seq=0)`, + } + if len(entries) != len(expected) { + t.Fatalf("expected %d separate logs, got %d: %v", len(expected), len(entries), entries) + } + for index, got := range entries { + if got != expected[index] { + t.Fatalf("log[%d] = %q, want %q", index, got, expected[index]) + } } } @@ -1118,3 +1207,38 @@ func TestApplyAntigravityReasoningReplayItems_SingleContextHashRejectionLogs(t * t.Fatalf("expected exactly 1 detailed rejection log, got %d", detailCount) } } + +func TestApplyAntigravityReasoningReplayItems_ContextHashRejectionSkipsBatchRetry(t *testing.T) { + hook := newSignatureDebugHook(t) + + payload := []byte(`{"request":{"contents":[ + {"role":"user","parts":[{"text":"first prompt"}]}, + {"role":"model","parts":[{"functionCall":{"id":"call-ok","name":"exec","args":{"cmd":"pwd"}},"thoughtSignature":"sig-ok"}]}, + {"role":"user","parts":[{"functionResponse":{"id":"call-ok","name":"exec","response":{"result":"/app"}}}]}, + {"role":"model","parts":[{"functionCall":{"id":"call-1","name":"tool_call","args":{"id":"web_search"}}}]}, + {"role":"user","parts":[{"functionResponse":{"id":"call-1","name":"tool_call","response":{"result":"ok"}}}]} + ]}}`) + + applied := []byte(`{"type":"function_call_part","call_id":"call-ok","name":"exec","args":{"cmd":"pwd"},"thoughtSignature":"sig-ok"}`) + rejected := []byte(`{"type":"function_call_part","call_id":"call-1","name":"tool_call","args":{"id":"web_search"},"thoughtSignature":"sig-1","contextHash":"wrong-hash-1"}`) + toolSchemas := map[string]any{ + "exec": map[string]any{"type": "object"}, + "tool_call": map[string]any{"type": "object"}, + } + _, _ = applyAntigravityReasoningReplayItems(payload, [][]byte{applied, rejected}, toolSchemas) + + detailCount := 0 + for _, entry := range hook.AllEntries() { + if entry.Level != log.DebugLevel || !strings.Contains(entry.Message, "context hash rejected") { + continue + } + detailCount++ + expected := `antigravity replay: context hash rejected 1 part (first="tool_call" at contents[3].parts[0], opaque_id=false, batch=1, seq=1)` + if entry.Message != expected { + t.Fatalf("expected log %q, got %q", expected, entry.Message) + } + } + if detailCount != 1 { + t.Fatalf("expected exactly 1 rejection log, got %d", detailCount) + } +} From eb6a768d103da08c039c20dfad28aad2c936fbbc Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Mon, 5 Oct 2026 14:16:37 +0800 Subject: [PATCH 054/142] feat(claude): support explicit prompt cache options - Honor `prompt_cache_options.mode = "explicit"` to suppress automatic `cache_control` insertion while preserving client-defined cache breakpoints - Strip `prompt_cache_options` from request payloads before forwarding upstream and during token counting Closes: #6380 --- .../runtime/executor/caching_verify_test.go | 3 + .../executor/claude_executor_cloaking.go | 259 +++-- .../executor/claude_executor_execute.go | 15 +- .../executor/claude_executor_stream.go | 15 +- .../executor/claude_executor_tokens.go | 10 +- .../claude_prompt_cache_options_test.go | 950 ++++++++++++++++++ 6 files changed, 1188 insertions(+), 64 deletions(-) create mode 100644 internal/runtime/executor/claude_prompt_cache_options_test.go diff --git a/internal/runtime/executor/caching_verify_test.go b/internal/runtime/executor/caching_verify_test.go index 198bcd9b426..dd9c9f35485 100644 --- a/internal/runtime/executor/caching_verify_test.go +++ b/internal/runtime/executor/caching_verify_test.go @@ -441,6 +441,9 @@ func TestShouldEnsureCacheControl(t *testing.T) { {name: "cloaked with marker", payload: withMarker, cloaked: true, want: true}, {name: "unconfirmed markerless", payload: markerless, want: true}, {name: "unconfirmed with marker", payload: withMarker, want: false}, + {name: "explicit mode markerless", payload: []byte(`{"prompt_cache_options":{"mode":"explicit"},"messages":[{"role":"user","content":"x"}]}`), want: false}, + {name: "explicit mode cloaked", payload: []byte(`{"prompt_cache_options":{"mode":"explicit"},"messages":[{"role":"user","content":"x"}]}`), cloaked: true, want: false}, + {name: "explicit mode with marker", payload: []byte(`{"prompt_cache_options":{"mode":"explicit"},"messages":[{"role":"user","content":[{"type":"text","text":"x","cache_control":{"type":"ephemeral"}}]}]}`), cloaked: true, want: false}, } for _, tt := range tests { diff --git a/internal/runtime/executor/claude_executor_cloaking.go b/internal/runtime/executor/claude_executor_cloaking.go index 14bcd5b3d0f..f43102b6e1c 100644 --- a/internal/runtime/executor/claude_executor_cloaking.go +++ b/internal/runtime/executor/claude_executor_cloaking.go @@ -320,7 +320,7 @@ func checkSystemInstructionsWithMode(payload []byte, strictMode bool) []byte { // Claude models give it operator-level authority without changing the cached // top-level prefix. func checkSystemInstructionsWithSigningMode(payload []byte, strictMode bool, cchSigning bool, version, entrypoint, workload string) []byte { - return checkSystemInstructionsWithSigningModeAt(payload, strictMode, cchSigning, version, entrypoint, workload, claudeCodeLocalDate(time.Now()), false, "", "") + return checkSystemInstructionsWithSigningModeAt(payload, strictMode, cchSigning, version, entrypoint, workload, claudeCodeLocalDate(time.Now()), false, "", "", "") } // isClaudeFable51Model reports whether the model is specifically Fable 5.1 / Mythos 5.1, @@ -339,6 +339,65 @@ func isClaudeFable51Model(model string) bool { return false } +type forwardedClaudeSystemPromptBlock struct { + Text string + CacheControl *claudeCacheControl + RawCC string +} + +func buildForwardedSystemBlock(text string, block forwardedClaudeSystemPromptBlock, isExplicit bool) string { + if isExplicit { + if block.RawCC != "" { + return `{"type":"text","text":` + marshalJSONStringWithoutHTMLEscape(text) + `,"cache_control":` + block.RawCC + `}` + } + return buildTextBlock(text, nil) + } + return buildTextBlock(text, &claudeCodeCacheControl) +} + +func isValidClaudeCacheControl(cc gjson.Result) bool { + if !cc.Exists() || cc.Type == gjson.Null || !cc.IsObject() { + return false + } + typ := cc.Get("type") + return typ.Type == gjson.String && typ.String() == "ephemeral" +} + +func collectForwardedClaudeSystemPromptBlocksWithCache(system gjson.Result) []forwardedClaudeSystemPromptBlock { + var blocks []forwardedClaudeSystemPromptBlock + appendBlock := func(text string, cc *claudeCacheControl, rawCC string) { + if strings.TrimSpace(text) == "" || util.IsClaudeCodeAttributionSystemText(text) || text == claudeCodeCLIIdentity { + return + } + blocks = append(blocks, forwardedClaudeSystemPromptBlock{Text: text, CacheControl: cc, RawCC: rawCC}) + } + + if system.Type == gjson.String { + appendBlock(system.String(), nil, "") + return blocks + } + if !system.IsArray() { + return blocks + } + system.ForEach(func(_, item gjson.Result) bool { + if item.Get("type").String() == "text" { + var cc *claudeCacheControl + rawCC := "" + if itemCC := item.Get("cache_control"); isValidClaudeCacheControl(itemCC) { + cc = &claudeCacheControl{ + Type: itemCC.Get("type").String(), + TTL: itemCC.Get("ttl").String(), + Scope: itemCC.Get("scope").String(), + } + rawCC = itemCC.Raw + } + appendBlock(item.Get("text").String(), cc, rawCC) + } + return true + }) + return blocks +} + func checkSystemInstructionsWithSigningModeAt( payload []byte, strictMode bool, @@ -354,7 +413,13 @@ func checkSystemInstructionsWithSigningModeAt( billingText := generateBillingHeader(cchSigning, version, messageText, entrypoint, workload, isSubagent, prevReq, promptID, turnOrigin...) billingBlock := buildTextBlock(billingText, nil) - agentBlock := buildTextBlock(claudeCodeCLIIdentity, &claudeCodeCacheControl) + + isExplicit := (len(turnOrigin) > 1 && turnOrigin[1] == "explicit_cache_mode") || isExplicitPromptCacheMode(payload) + var agentCC *claudeCacheControl = &claudeCodeCacheControl + if isExplicit { + agentCC = nil + } + agentBlock := buildTextBlock(claudeCodeCLIIdentity, agentCC) systemBlocks := []string{billingBlock, agentBlock} model := strings.ToLower(strings.TrimSpace(gjson.GetBytes(payload, "model").String())) @@ -363,34 +428,31 @@ func checkSystemInstructionsWithSigningModeAt( } payload, _ = sjson.SetRawBytes(payload, "system", []byte("["+strings.Join(systemBlocks, ",")+"]")) if strictMode { - return injectClaudeCodeCurrentDate(payload, currentDate) + return injectClaudeCodeCurrentDateInternal(payload, currentDate, isExplicit) } - forwardedSystemBlocks := collectForwardedClaudeSystemPromptBlocks(system) + forwardedSystemBlocks := collectForwardedClaudeSystemPromptBlocksWithCache(system) if len(forwardedSystemBlocks) == 0 { - return injectClaudeCodeCurrentDate(payload, currentDate) + return injectClaudeCodeCurrentDateInternal(payload, currentDate, isExplicit) } if claudeHistoryHasAdvisorCallOrResult(payload) { for _, block := range forwardedSystemBlocks { - systemBlocks = append(systemBlocks, buildTextBlock(block, nil)) + systemBlocks = append(systemBlocks, buildForwardedSystemBlock(block.Text, block, isExplicit)) } payload, _ = sjson.SetRawBytes(payload, "system", []byte("["+strings.Join(systemBlocks, ",")+"]")) - return injectClaudeCodeCurrentDate(payload, currentDate) + return injectClaudeCodeCurrentDateInternal(payload, currentDate, isExplicit) } if claudeUsesLegacySystemReminder(payload) { - payload = prependClaudeSystemRemindersToFirstUserMessage(payload, forwardedSystemBlocks) + payload = prependClaudeSystemReminderBlocksToFirstUserMessage(payload, forwardedSystemBlocks, isExplicit) } else if claudeMidConversationSystemMessagesAtEnd(payload) { for _, block := range forwardedSystemBlocks { - systemBlocks = append(systemBlocks, buildTextBlock(block, &claudeCodeCacheControl)) + systemBlocks = append(systemBlocks, buildForwardedSystemBlock(block.Text, block, isExplicit)) } payload, _ = sjson.SetRawBytes(payload, "system", []byte("["+strings.Join(systemBlocks, ",")+"]")) } else { - // Unknown and future model IDs optimistically use the authoritative - // mid-conversation system role. Only empirically unsupported legacy IDs - // stay on the user-reminder compatibility path. - payload = insertClaudeMidConversationSystemMessages(payload, forwardedSystemBlocks) + payload = insertClaudeMidConversationSystemBlocks(payload, forwardedSystemBlocks, isExplicit) } - return injectClaudeCodeCurrentDate(payload, currentDate) + return injectClaudeCodeCurrentDateInternal(payload, currentDate, isExplicit) } // relocateClaudeSystemPromptForCountTokens keeps a cloaked count_tokens request @@ -400,16 +462,17 @@ func checkSystemInstructionsWithSigningModeAt( // using the same positional mapping as the Messages path. That keeps the counted // tokens aligned with the request the caller is about to send while preventing a // third-party system prompt from reaching Anthropic in the system slot. -func relocateClaudeSystemPromptForCountTokens(payload []byte, strictMode bool) []byte { +func relocateClaudeSystemPromptForCountTokens(payload []byte, strictMode bool, explicitCacheMode ...bool) []byte { system := gjson.GetBytes(payload, "system") if !system.Exists() { return payload } + isExplicit := (len(explicitCacheMode) > 0 && explicitCacheMode[0]) || isExplicitPromptCacheMode(payload) // Strict mode drops caller prompts on the Messages path, so it must not // reintroduce them here either. - var forwardedSystemBlocks []string + var forwardedSystemBlocks []forwardedClaudeSystemPromptBlock if !strictMode { - forwardedSystemBlocks = collectForwardedClaudeSystemPromptBlocks(system) + forwardedSystemBlocks = collectForwardedClaudeSystemPromptBlocksWithCache(system) } if len(forwardedSystemBlocks) == 0 { updated, _ := sjson.DeleteBytes(payload, "system") @@ -422,7 +485,7 @@ func relocateClaudeSystemPromptForCountTokens(payload []byte, strictMode bool) [ // remains aligned with the Messages path without splicing messages[]. blocks := make([]string, 0, len(forwardedSystemBlocks)) for _, block := range forwardedSystemBlocks { - blocks = append(blocks, buildTextBlock(block, nil)) + blocks = append(blocks, buildForwardedSystemBlock(block.Text, block, isExplicit)) } updated, _ := sjson.SetRawBytes(payload, "system", []byte("["+strings.Join(blocks, ",")+"]")) return updated @@ -433,17 +496,17 @@ func relocateClaudeSystemPromptForCountTokens(payload []byte, strictMode bool) [ } payload = updated if claudeUsesLegacySystemReminder(payload) { - return prependClaudeSystemRemindersToFirstUserMessage(payload, forwardedSystemBlocks) + return prependClaudeSystemReminderBlocksToFirstUserMessage(payload, forwardedSystemBlocks, isExplicit) } if claudeMidConversationSystemMessagesAtEnd(payload) { blocks := make([]string, 0, len(forwardedSystemBlocks)) for _, block := range forwardedSystemBlocks { - blocks = append(blocks, buildTextBlock(block, &claudeCodeCacheControl)) + blocks = append(blocks, buildForwardedSystemBlock(block.Text, block, isExplicit)) } updated, _ := sjson.SetRawBytes(payload, "system", []byte("["+strings.Join(blocks, ",")+"]")) return updated } - return insertClaudeMidConversationSystemMessages(payload, forwardedSystemBlocks) + return insertClaudeMidConversationSystemBlocks(payload, forwardedSystemBlocks, isExplicit) } // claudeLegacySystemReminderModels lists the official Anthropic model IDs and @@ -635,6 +698,9 @@ func buildTextBlock(text string, cacheControl *claudeCacheControl) string { if cacheControl.TTL != "" { block += `,"ttl":` + marshalJSONStringWithoutHTMLEscape(cacheControl.TTL) } + if cacheControl.Scope != "" { + block += `,"scope":` + marshalJSONStringWithoutHTMLEscape(cacheControl.Scope) + } block += "}" } return block + "}" @@ -649,58 +715,71 @@ func marshalJSONStringWithoutHTMLEscape(value string) string { } func prependClaudeSystemRemindersToFirstUserMessage(payload []byte, texts []string) []byte { - firstUserIdx := firstClaudeUserMessageIndex(payload) - if firstUserIdx < 0 || len(texts) == 0 { - return payload + blocks := make([]forwardedClaudeSystemPromptBlock, 0, len(texts)) + for _, text := range texts { + blocks = append(blocks, forwardedClaudeSystemPromptBlock{Text: text}) } + return prependClaudeSystemReminderBlocksToFirstUserMessage(payload, blocks, false) +} - reminderTexts := make([]string, 0, len(texts)) - for _, text := range texts { - reminderTexts = append(reminderTexts, claudeCallerSystemReminder(text)) +func prependClaudeSystemReminderBlocksToFirstUserMessage(payload []byte, blocks []forwardedClaudeSystemPromptBlock, isExplicit bool) []byte { + firstUserIdx := firstClaudeUserMessageIndex(payload) + if firstUserIdx < 0 || len(blocks) == 0 { + return payload } contentPath := fmt.Sprintf("messages.%d.content", firstUserIdx) content := gjson.GetBytes(payload, contentPath) if content.IsArray() { - blocks := content.Array() - existing := make(map[string]int, len(blocks)) - for _, block := range blocks { + contentBlocks := content.Array() + existing := make(map[string]int, len(contentBlocks)) + for _, block := range contentBlocks { if block.Get("type").String() == "text" { existing[block.Get("text").String()]++ } } - reminderBlocks := make([]string, 0, len(reminderTexts)) - for _, reminderText := range reminderTexts { + reminderBlocks := make([]string, 0, len(blocks)) + for _, b := range blocks { + reminderText := claudeCallerSystemReminder(b.Text) if existing[reminderText] > 0 { existing[reminderText]-- continue } - reminderBlocks = append(reminderBlocks, buildTextBlock(reminderText, nil)) + if isExplicit && b.RawCC != "" { + reminderBlocks = append(reminderBlocks, `{"type":"text","text":`+marshalJSONStringWithoutHTMLEscape(reminderText)+`,"cache_control":`+b.RawCC+`}`) + } else { + reminderBlocks = append(reminderBlocks, buildTextBlock(reminderText, nil)) + } } if len(reminderBlocks) == 0 { return payload } insertAt := 0 - for insertAt < len(blocks) && blocks[insertAt].Get("type").String() == "tool_result" { + for insertAt < len(contentBlocks) && contentBlocks[insertAt].Get("type").String() == "tool_result" { insertAt++ } - rawBlocks := make([]string, 0, len(blocks)+len(reminderBlocks)) - for idx, block := range blocks { + rawBlocks := make([]string, 0, len(contentBlocks)+len(reminderBlocks)) + for idx, block := range contentBlocks { if idx == insertAt { rawBlocks = append(rawBlocks, reminderBlocks...) } rawBlocks = append(rawBlocks, block.Raw) } - if insertAt == len(blocks) { + if insertAt == len(contentBlocks) { rawBlocks = append(rawBlocks, reminderBlocks...) } payload, _ = sjson.SetRawBytes(payload, contentPath, []byte("["+strings.Join(rawBlocks, ",")+"]")) } else if content.Type == gjson.String { - rawBlocks := make([]string, 0, len(reminderTexts)+1) - for _, reminderText := range reminderTexts { - rawBlocks = append(rawBlocks, buildTextBlock(reminderText, nil)) + rawBlocks := make([]string, 0, len(blocks)+1) + for _, b := range blocks { + reminderText := claudeCallerSystemReminder(b.Text) + if isExplicit && b.RawCC != "" { + rawBlocks = append(rawBlocks, `{"type":"text","text":`+marshalJSONStringWithoutHTMLEscape(reminderText)+`,"cache_control":`+b.RawCC+`}`) + } else { + rawBlocks = append(rawBlocks, buildTextBlock(reminderText, nil)) + } } rawBlocks = append(rawBlocks, buildTextBlock(content.String(), nil)) payload, _ = sjson.SetRawBytes(payload, contentPath, []byte("["+strings.Join(rawBlocks, ",")+"]")) @@ -785,8 +864,16 @@ func claudeMidConversationSystemMessagesAtEnd(payload []byte) bool { } func insertClaudeMidConversationSystemMessages(payload []byte, texts []string) []byte { + blocks := make([]forwardedClaudeSystemPromptBlock, 0, len(texts)) + for _, text := range texts { + blocks = append(blocks, forwardedClaudeSystemPromptBlock{Text: text, CacheControl: &claudeCodeCacheControl}) + } + return insertClaudeMidConversationSystemBlocks(payload, blocks, false) +} + +func insertClaudeMidConversationSystemBlocks(payload []byte, blocks []forwardedClaudeSystemPromptBlock, isExplicit bool) []byte { firstUserIdx := firstClaudeUserMessageIndex(payload) - if firstUserIdx < 0 || len(texts) == 0 { + if firstUserIdx < 0 || len(blocks) == 0 { return payload } @@ -799,11 +886,11 @@ func insertClaudeMidConversationSystemMessages(payload []byte, texts []string) [ for insertAt < len(messageBlocks) && messageBlocks[insertAt].Get("role").String() == "user" { insertAt++ } - if len(messageBlocks)-insertAt >= len(texts) { + if len(messageBlocks)-insertAt >= len(blocks) { matches := true - for idx, text := range texts { + for idx, block := range blocks { message := messageBlocks[insertAt+idx] - if message.Get("role").String() != "system" || claudeMessageContentText(message.Get("content")) != text { + if message.Get("role").String() != "system" || claudeMessageContentText(message.Get("content")) != block.Text { matches = false break } @@ -813,9 +900,9 @@ func insertClaudeMidConversationSystemMessages(payload []byte, texts []string) [ } } - systemMessages := make([]string, 0, len(texts)) - for _, text := range texts { - content := "[" + buildTextBlock(text, &claudeCodeCacheControl) + "]" + systemMessages := make([]string, 0, len(blocks)) + for _, block := range blocks { + content := "[" + buildForwardedSystemBlock(block.Text, block, isExplicit) + "]" systemMessages = append(systemMessages, `{"role":"system","content":`+content+"}") } rawMessages := make([]string, 0, len(messageBlocks)+len(systemMessages)) @@ -1202,6 +1289,10 @@ func isClaudeCodeCurrentDateReminder(text string) bool { // one whenever continuity is available) so the reminder text cannot change // between requests of one session. func injectClaudeCodeCurrentDate(payload []byte, date string) []byte { + return injectClaudeCodeCurrentDateInternal(payload, date, false) +} + +func injectClaudeCodeCurrentDateInternal(payload []byte, date string, isExplicit bool) []byte { firstUserIdx := firstClaudeUserMessageIndex(payload) if firstUserIdx < 0 { return payload @@ -1213,7 +1304,11 @@ func injectClaudeCodeCurrentDate(payload []byte, date string) []byte { dateBlock := buildTextBlock(dateText, nil) if content.Type == gjson.String { - userBlock := buildTextBlock(content.String(), &claudeCodeCacheControl) + var userCC *claudeCacheControl = &claudeCodeCacheControl + if isExplicit { + userCC = nil + } + userBlock := buildTextBlock(content.String(), userCC) newArray := "[" + dateBlock + "," + userBlock + "]" payload, _ = sjson.SetRawBytes(payload, contentPath, []byte(newArray)) return payload @@ -1232,9 +1327,11 @@ func injectClaudeCodeCurrentDate(payload []byte, date string) []byte { continue } if !actualTextCached && !isClaudeCodeContextReminder(text) { - rawBlocks = append(rawBlocks, withEphemeralCacheControl(block.Raw)) - actualTextCached = true - continue + if !isExplicit { + rawBlocks = append(rawBlocks, withEphemeralCacheControl(block.Raw)) + actualTextCached = true + continue + } } } rawBlocks = append(rawBlocks, block.Raw) @@ -1446,11 +1543,13 @@ func applyCloakingInternal( confirmedClaudeCode bool, cchSigning bool, obfuscateSensitiveWords bool, + explicitCacheMode ...bool, ) ([]byte, bool, error) { policy, settings := resolveClaudeWirePolicy(cfg, auth, apiKey, confirmedClaudeCode) if !policy.Cloak { return payload, false, nil } + isExplicit := (len(explicitCacheMode) > 0 && explicitCacheMode[0]) || isExplicitPromptCacheModeContext(ctx) // Strict mode drops caller system prompts entirely, so nothing needs a // destination and an unusable block cannot lose information. if !settings.strictMode { @@ -1493,6 +1592,10 @@ func applyCloakingInternal( if !isProbeOrHelper && !isSubagent { turnOrigin = "human" } + turnOriginArgs := []string{turnOrigin} + if isExplicit { + turnOriginArgs = append(turnOriginArgs, "explicit_cache_mode") + } payload = checkSystemInstructionsWithSigningModeAt( payload, settings.strictMode, @@ -1504,7 +1607,7 @@ func applyCloakingInternal( isSubagent, prevReq, promptID, - turnOrigin, + turnOriginArgs..., ) // In native Claude Code 2.1.258, claude-fable-5-1 requests carry: @@ -1525,7 +1628,7 @@ func applyCloakingInternal( // Probes never use 1h cache in native Claude Code; ensure any caller-supplied // 1h ttl is stripped to match extended-cache-ttl beta suppression. Subagents // preserve caller-requested 1h cache TTL (e.g. subagentPromptCacheTtl: 1h). - if isProbeOrHelper || (isSubagent && !helps.ClaudeSubagentRequests1h(incomingHeaders, payload)) { + if !isExplicit && (isProbeOrHelper || (isSubagent && !helps.ClaudeSubagentRequests1h(incomingHeaders, payload))) { payload = stripClaudeCacheControlTTL(payload) } @@ -1550,8 +1653,9 @@ func applyCloakingInternal( } type claudeCacheControl struct { - Type string `json:"type"` - TTL string `json:"ttl,omitempty"` + Type string `json:"type"` + TTL string `json:"ttl,omitempty"` + Scope string `json:"scope,omitempty"` } // claudeCodeCacheControl is the default Claude Code breakpoint shape. @@ -1723,7 +1827,50 @@ func forEachClaudeCacheControlBlock(payload []byte, visit func(path string, bloc } } -func shouldEnsureCacheControl(payload []byte, cloaked, confirmedClaudeCode bool) bool { +// isExplicitPromptCacheMode reports whether any of the candidate payloads +// specifies prompt_cache_options.mode as "explicit" (case-insensitive). +func isExplicitPromptCacheMode(payloads ...[]byte) bool { + for _, payload := range payloads { + if len(payload) == 0 { + continue + } + mode := gjson.GetBytes(payload, "prompt_cache_options.mode").String() + if strings.EqualFold(strings.TrimSpace(mode), "explicit") { + return true + } + } + return false +} + +type explicitPromptCacheModeContextKey struct{} + +func withExplicitPromptCacheMode(ctx context.Context, explicit bool) context.Context { + return context.WithValue(ctx, explicitPromptCacheModeContextKey{}, explicit) +} + +func isExplicitPromptCacheModeContext(ctx context.Context) bool { + if ctx == nil { + return false + } + v, _ := ctx.Value(explicitPromptCacheModeContextKey{}).(bool) + return v +} + +func stripPromptCacheOptions(payload []byte) []byte { + if !gjson.GetBytes(payload, "prompt_cache_options").Exists() { + return payload + } + updated, err := sjson.DeleteBytes(payload, "prompt_cache_options") + if err != nil { + return payload + } + return updated +} + +func shouldEnsureCacheControl(payload []byte, cloaked, confirmedClaudeCode bool, candidates ...[]byte) bool { + if isExplicitPromptCacheMode(append([][]byte{payload}, candidates...)...) { + return false + } return !confirmedClaudeCode && (cloaked || countCacheControls(payload) == 0) } diff --git a/internal/runtime/executor/claude_executor_execute.go b/internal/runtime/executor/claude_executor_execute.go index 3ee64fa6177..db3fc46ba48 100644 --- a/internal/runtime/executor/claude_executor_execute.go +++ b/internal/runtime/executor/claude_executor_execute.go @@ -91,6 +91,10 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r // based on client type and configuration. _, wireSettings := resolveClaudeWirePolicy(e.cfg, auth, apiKey, confirmedClaudeCode) isProbeOrHelper := helps.IsClaudeProbeOrHelperRequest(body) + explicitCacheMode := isExplicitPromptCacheMode(originalPayload, req.Payload, body) + if explicitCacheMode { + ctx = withExplicitPromptCacheMode(ctx, true) + } var cloaked bool body, cloaked, err = applyCloakingInternal( ctx, @@ -101,6 +105,7 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r confirmedClaudeCode, cchSigning, false, + explicitCacheMode, ) if err != nil { return resp, err @@ -146,7 +151,7 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r // first-user marker cannot suppress system/latest-user breakpoints. // cloaked and confirmedClaudeCode are mutually exclusive: resolveClaudeWirePolicy // forces Cloak off for a confirmed native client. - cpaOwnsCacheControl := shouldEnsureCacheControl(body, cloaked, confirmedClaudeCode) + cpaOwnsCacheControl := shouldEnsureCacheControl(body, cloaked, confirmedClaudeCode, originalPayload, req.Payload) if cpaOwnsCacheControl { body = ensureCacheControl(body) } @@ -155,6 +160,7 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r // Cloaking and ensureCacheControl may push the total over 4 when the client // already sends multiple cache_control blocks. body = enforceCacheControlLimit(body, 4) + body = stripPromptCacheOptions(body) // Native selects the 1h cache pool only for OAuth credentials and pairs it with // extended-cache-ttl-2025-04-11, which claudeCodeCLIBetas emits on exactly the @@ -173,13 +179,15 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r subagent1h := isSubagent && helps.ClaudeSubagentRequests1h(incomingHeaders, body) if cpaOwnsCacheControl && fp.ProfileClaudeCodeCLI && (!isSubagent || subagent1h) && !isProbeOrHelper { body = upgradeClaudeCacheControlTTL(body, claudeCacheControlTTL1h) - } else if isProbeOrHelper || (isSubagent && !subagent1h) { + } else if (isProbeOrHelper || (isSubagent && !subagent1h)) && !explicitCacheMode { body = stripClaudeCacheControlTTL(body) } // Normalize TTL values to prevent ordering violations under prompt-caching-scope-2026-01-05. // A 1h-TTL block must not appear after a 5m-TTL block in evaluation order (tools→system→messages). - body = normalizeCacheControlTTL(body) + if !explicitCacheMode { + body = normalizeCacheControlTTL(body) + } // Set the built-in transport default before the explicit payload barrier. // Native non-stream Haiku helper requests omit stream rather than sending // false, so preserve that measured wire shape when the transport agrees. @@ -233,6 +241,7 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r diagnosticsState = claudeDiagnosticsRequestState{} } extraBetas, bodyForUpstream = extractAndRemoveBetas(bodyForUpstream) + bodyForUpstream = stripPromptCacheOptions(bodyForUpstream) if cchSigning { bodyForUpstream, err = signAnthropicMessagesBody(bodyForUpstream) if err != nil { diff --git a/internal/runtime/executor/claude_executor_stream.go b/internal/runtime/executor/claude_executor_stream.go index f8b220390e7..aa22c4f0862 100644 --- a/internal/runtime/executor/claude_executor_stream.go +++ b/internal/runtime/executor/claude_executor_stream.go @@ -94,6 +94,10 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A // based on client type and configuration. _, wireSettings := resolveClaudeWirePolicy(e.cfg, auth, apiKey, confirmedClaudeCode) isProbeOrHelper := helps.IsClaudeProbeOrHelperRequest(body) + explicitCacheMode := isExplicitPromptCacheMode(originalPayload, req.Payload, body) + if explicitCacheMode { + ctx = withExplicitPromptCacheMode(ctx, true) + } var cloaked bool body, cloaked, err = applyCloakingInternal( ctx, @@ -104,6 +108,7 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A confirmedClaudeCode, cchSigning, false, + explicitCacheMode, ) if err != nil { return nil, err @@ -149,7 +154,7 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A // first-user marker cannot suppress system/latest-user breakpoints. // cloaked and confirmedClaudeCode are mutually exclusive: resolveClaudeWirePolicy // forces Cloak off for a confirmed native client. - cpaOwnsCacheControl := shouldEnsureCacheControl(body, cloaked, confirmedClaudeCode) + cpaOwnsCacheControl := shouldEnsureCacheControl(body, cloaked, confirmedClaudeCode, originalPayload, req.Payload) if cpaOwnsCacheControl { body = ensureCacheControl(body) } @@ -158,6 +163,7 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A // Cloaking and ensureCacheControl may push the total over 4 when the client // already sends multiple cache_control blocks. body = enforceCacheControlLimit(body, 4) + body = stripPromptCacheOptions(body) // Native selects the 1h cache pool only for OAuth credentials and pairs it with // extended-cache-ttl-2025-04-11, which claudeCodeCLIBetas emits on exactly the @@ -176,12 +182,14 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A subagent1h := isSubagent && helps.ClaudeSubagentRequests1h(incomingHeaders, body) if cpaOwnsCacheControl && fp.ProfileClaudeCodeCLI && (!isSubagent || subagent1h) && !isProbeOrHelper { body = upgradeClaudeCacheControlTTL(body, claudeCacheControlTTL1h) - } else if isProbeOrHelper || (isSubagent && !subagent1h) { + } else if (isProbeOrHelper || (isSubagent && !subagent1h)) && !explicitCacheMode { body = stripClaudeCacheControlTTL(body) } // Normalize TTL values to prevent ordering violations under prompt-caching-scope-2026-01-05. - body = normalizeCacheControlTTL(body) + if !explicitCacheMode { + body = normalizeCacheControlTTL(body) + } // Extract betas from body and convert to header var extraBetas []string @@ -228,6 +236,7 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A diagnosticsState = claudeDiagnosticsRequestState{} } extraBetas, bodyForUpstream = extractAndRemoveBetas(bodyForUpstream) + bodyForUpstream = stripPromptCacheOptions(bodyForUpstream) if cchSigning { bodyForUpstream, err = signAnthropicMessagesBody(bodyForUpstream) if err != nil { diff --git a/internal/runtime/executor/claude_executor_tokens.go b/internal/runtime/executor/claude_executor_tokens.go index 9d231566067..6e3ecdae61f 100644 --- a/internal/runtime/executor/claude_executor_tokens.go +++ b/internal/runtime/executor/claude_executor_tokens.go @@ -53,6 +53,7 @@ func (e *ClaudeExecutor) CountTokens(ctx context.Context, auth *cliproxyauth.Aut } body = sanitizeClaudeMessagesForClaudeUpstreamWithDebug(ctx, body, baseModel, helps.APIKeyModelIsCompat(req)) body = helps.NewPayloadFinalizer(e.cfg, e.Identifier(), baseModel, to.String(), "", originalTranslatedForPayload, req, opts)(body) + body = stripPromptCacheOptions(body) if errValidate := validateClaudeTokenCountRequest(body); errValidate != nil { return cliproxyexecutor.Response{}, errValidate } @@ -171,13 +172,14 @@ func (e *ClaudeExecutor) countTokensUpstream(ctx context.Context, auth *cliproxy // Messages path. Kimi opt-in uses the same contract. policy, settings := resolveClaudeWirePolicy(e.cfg, auth, apiKey, confirmedClaudeCode) cloaked := policy.Cloak + explicitCacheMode := isExplicitPromptCacheMode(originalPayload, req.Payload, body) if cloaked { if !settings.strictMode { if errSystem := validateClaudeCallerSystemBlocks(gjson.GetBytes(body, "system")); errSystem != nil { return cliproxyexecutor.Response{}, errSystem } } - body = relocateClaudeSystemPromptForCountTokens(body, settings.strictMode) + body = relocateClaudeSystemPromptForCountTokens(body, settings.strictMode, explicitCacheMode) if len(settings.sensitiveWords) > 0 { body = helps.ObfuscateSensitiveWords(body, helps.BuildSensitiveWordMatcher(settings.sensitiveWords)) } @@ -185,7 +187,9 @@ func (e *ClaudeExecutor) countTokensUpstream(ctx context.Context, auth *cliproxy // Keep count_tokens requests compatible with Anthropic cache-control constraints too. body = enforceCacheControlLimit(body, 4) - body = normalizeCacheControlTTL(body) + if !explicitCacheMode { + body = normalizeCacheControlTTL(body) + } // Extract betas from body and convert to header (for count_tokens too) var extraBetas []string @@ -197,6 +201,7 @@ func (e *ClaudeExecutor) countTokensUpstream(ctx context.Context, auth *cliproxy body, _ = prepareClaudeOAuthToolNamesForUpstream(body, mcpAliases) } body = sanitizeClaudeMessagesForClaudeUpstreamWithDebug(ctx, body, baseModel, helps.APIKeyModelIsCompat(req)) + body = stripPromptCacheOptions(body) // Two different reasons converge on the same deletions, and they must stay // separable. // @@ -227,6 +232,7 @@ func (e *ClaudeExecutor) countTokensUpstream(ctx context.Context, auth *cliproxy return cliproxyexecutor.Response{}, errMidSystem } body = helps.NewPayloadFinalizer(e.cfg, e.Identifier(), baseModel, to.String(), "", originalTranslatedForPayload, req, opts)(body) + body = stripPromptCacheOptions(body) httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) if err != nil { return cliproxyexecutor.Response{}, err diff --git a/internal/runtime/executor/claude_prompt_cache_options_test.go b/internal/runtime/executor/claude_prompt_cache_options_test.go new file mode 100644 index 00000000000..2d92d389f87 --- /dev/null +++ b/internal/runtime/executor/claude_prompt_cache_options_test.go @@ -0,0 +1,950 @@ +package executor + +import ( + "bytes" + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +func writeClaudeSSEMockResponse(w http.ResponseWriter) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = fmt.Fprint(w, "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_1\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[],\"model\":\"claude-3-5-sonnet\",\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n") + _, _ = fmt.Fprint(w, "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"ok\"}}\n\n") + _, _ = fmt.Fprint(w, "event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":1}}\n\n") + _, _ = fmt.Fprint(w, "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n") +} + +func TestClaudeExecutor_PromptCacheOptionsMode_Explicit_SuppressesAutoCacheControl(t *testing.T) { + var seenBody []byte + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + seenBody = bytes.Clone(body) + writeClaudeSSEMockResponse(w) + })) + defer server.Close() + + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{Attributes: map[string]string{ + "api_key": "key-123", + "base_url": server.URL, + }} + + originalReq := []byte(`{ + "model": "claude-3-5-sonnet-20241022", + "prompt_cache_options": { + "mode": "explicit" + }, + "messages": [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Hello"} + ] + }`) + + _, err := executor.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "claude-3-5-sonnet-20241022", + Payload: originalReq, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FromString("openai"), + OriginalRequest: originalReq, + }) + if err != nil { + t.Fatalf("Execute() error = %v", err) + } + + if count := countCacheControls(seenBody); count != 0 { + t.Fatalf("expected 0 cache_control blocks with mode: explicit and no client breakpoints, got %d: %s", count, string(seenBody)) + } + if gjson.GetBytes(seenBody, "prompt_cache_options").Exists() { + t.Fatalf("prompt_cache_options should not be forwarded upstream: %s", string(seenBody)) + } +} + +func TestClaudeExecutor_PromptCacheOptionsMode_Explicit_PreservesClientBreakpoints(t *testing.T) { + var seenBody []byte + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + seenBody = bytes.Clone(body) + writeClaudeSSEMockResponse(w) + })) + defer server.Close() + + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{Attributes: map[string]string{ + "api_key": "key-123", + "base_url": server.URL, + }} + + originalReq := []byte(`{ + "model": "claude-3-5-sonnet-20241022", + "prompt_cache_options": { + "mode": "explicit" + }, + "messages": [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": [ + {"type": "text", "text": "Cached part", "cache_control": {"type": "ephemeral"}} + ]}, + {"role": "user", "content": "Uncached part"} + ] + }`) + + _, err := executor.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "claude-3-5-sonnet-20241022", + Payload: originalReq, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FromString("openai"), + OriginalRequest: originalReq, + }) + if err != nil { + t.Fatalf("Execute() error = %v", err) + } + + if count := countCacheControls(seenBody); count != 1 { + t.Fatalf("expected exactly 1 cache_control block (the client-specified one), got %d: %s", count, string(seenBody)) + } + if !gjson.GetBytes(seenBody, "messages.0.content.0.cache_control").Exists() { + t.Fatalf("client cache_control was not preserved: %s", string(seenBody)) + } + if gjson.GetBytes(seenBody, "system.0.cache_control").Exists() { + t.Fatalf("system prompt unexpectedly received automatic cache_control: %s", string(seenBody)) + } + if gjson.GetBytes(seenBody, "messages.1.content.0.cache_control").Exists() { + t.Fatalf("second message unexpectedly received automatic cache_control: %s", string(seenBody)) + } +} + +func TestClaudeExecutor_PromptCacheOptionsMode_Stream_Explicit_SuppressesAutoCacheControl(t *testing.T) { + var seenBody []byte + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + seenBody = bytes.Clone(body) + writeClaudeSSEMockResponse(w) + })) + defer server.Close() + + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{Attributes: map[string]string{ + "api_key": "key-123", + "base_url": server.URL, + }} + + originalReq := []byte(`{ + "model": "claude-3-5-sonnet-20241022", + "stream": true, + "prompt_cache_options": { + "mode": "explicit" + }, + "messages": [ + {"role": "user", "content": "Stream query"} + ] + }`) + + streamRes, err := executor.ExecuteStream(context.Background(), auth, cliproxyexecutor.Request{ + Model: "claude-3-5-sonnet-20241022", + Payload: originalReq, + }, cliproxyexecutor.Options{ + Stream: true, + SourceFormat: sdktranslator.FromString("openai"), + OriginalRequest: originalReq, + }) + if err != nil { + t.Fatalf("ExecuteStream() error = %v", err) + } + for range streamRes.Chunks { + } + + if count := countCacheControls(seenBody); count != 0 { + t.Fatalf("expected 0 cache_control blocks in stream with mode: explicit, got %d: %s", count, string(seenBody)) + } + if gjson.GetBytes(seenBody, "prompt_cache_options").Exists() { + t.Fatalf("prompt_cache_options should not be forwarded upstream: %s", string(seenBody)) + } +} + +func TestClaudeExecutor_PromptCacheOptionsMode_ImplicitOrMissing_PreservesAutoCacheControl(t *testing.T) { + for _, tc := range []struct { + name string + originalReq []byte + }{ + { + name: "missing prompt_cache_options", + originalReq: []byte(`{ + "model": "claude-3-5-sonnet-20241022", + "messages": [ + {"role": "system", "content": "You are helpful."}, + {"role": "user", "content": "Hello"} + ] + }`), + }, + { + name: "mode implicit", + originalReq: []byte(`{ + "model": "claude-3-5-sonnet-20241022", + "prompt_cache_options": { + "mode": "implicit" + }, + "messages": [ + {"role": "system", "content": "You are helpful."}, + {"role": "user", "content": "Hello"} + ] + }`), + }, + } { + t.Run(tc.name, func(t *testing.T) { + var seenBody []byte + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + seenBody = bytes.Clone(body) + writeClaudeSSEMockResponse(w) + })) + defer server.Close() + + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{Attributes: map[string]string{ + "api_key": "key-123", + "base_url": server.URL, + }} + + _, err := executor.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "claude-3-5-sonnet-20241022", + Payload: tc.originalReq, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FromString("openai"), + OriginalRequest: tc.originalReq, + }) + if err != nil { + t.Fatalf("Execute() error = %v", err) + } + + // In normal mode without client markers, system and message should receive auto-injected cache_control. + if !gjson.GetBytes(seenBody, "system.0.cache_control").Exists() { + t.Fatalf("expected system cache_control in implicit mode: %s", string(seenBody)) + } + if !gjson.GetBytes(seenBody, "messages.0.content.0.cache_control").Exists() { + t.Fatalf("expected message cache_control in implicit mode: %s", string(seenBody)) + } + }) + } +} + +func TestClaudeExecutor_PromptCacheOptionsMode_Explicit_ToolsFallbackSuppressed(t *testing.T) { + var seenBody []byte + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + seenBody = bytes.Clone(body) + writeClaudeSSEMockResponse(w) + })) + defer server.Close() + + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{Attributes: map[string]string{ + "api_key": "key-123", + "base_url": server.URL, + }} + + originalReq := []byte(`{ + "model": "claude-3-5-sonnet-20241022", + "prompt_cache_options": { + "mode": "explicit" + }, + "tools": [ + {"type": "function", "function": {"name": "tool1", "description": "t1", "parameters": {"type": "object"}}}, + {"type": "function", "function": {"name": "tool2", "description": "t2", "parameters": {"type": "object"}}} + ], + "messages": [ + {"role": "user", "content": "Hello without system"} + ] + }`) + + _, err := executor.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "claude-3-5-sonnet-20241022", + Payload: originalReq, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FromString("openai"), + OriginalRequest: originalReq, + }) + if err != nil { + t.Fatalf("Execute() error = %v", err) + } + + if count := countCacheControls(seenBody); count != 0 { + t.Fatalf("expected 0 cache_control blocks with mode: explicit when only tools are present, got %d: %s", count, string(seenBody)) + } +} + +func TestClaudeExecutor_PromptCacheOptionsMode_Explicit_ClientToolBreakpointPreserved(t *testing.T) { + var seenBody []byte + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + seenBody = bytes.Clone(body) + writeClaudeSSEMockResponse(w) + })) + defer server.Close() + + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{Attributes: map[string]string{ + "api_key": "key-123", + "base_url": server.URL, + }} + + originalReq := []byte(`{ + "model": "claude-3-5-sonnet-20241022", + "prompt_cache_options": { + "mode": "explicit" + }, + "tools": [ + {"type": "function", "cache_control": {"type": "ephemeral"}, "function": {"name": "tool1", "description": "t1", "parameters": {"type": "object"}}}, + {"type": "function", "function": {"name": "tool2", "description": "t2", "parameters": {"type": "object"}}} + ], + "messages": [ + {"role": "user", "content": "Hello"} + ] + }`) + + _, err := executor.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "claude-3-5-sonnet-20241022", + Payload: originalReq, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FromString("openai"), + OriginalRequest: originalReq, + }) + if err != nil { + t.Fatalf("Execute() error = %v", err) + } + + if count := countCacheControls(seenBody); count != 1 { + t.Fatalf("expected 1 cache_control block on client-specified tool, got %d: %s", count, string(seenBody)) + } + if !gjson.GetBytes(seenBody, "tools.0.cache_control").Exists() { + t.Fatalf("tools.0 should have client-specified cache_control: %s", string(seenBody)) + } + if gjson.GetBytes(seenBody, "tools.1.cache_control").Exists() { + t.Fatalf("tools.1 should NOT have cache_control: %s", string(seenBody)) + } + if gjson.GetBytes(seenBody, "messages.0.content.0.cache_control").Exists() { + t.Fatalf("message should NOT receive automatic cache_control: %s", string(seenBody)) + } +} + +func TestClaudeExecutor_PromptCacheOptionsMode_Explicit_Cloaked_SuppressesAllAutoCacheControl(t *testing.T) { + var seenBody []byte + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + seenBody = bytes.Clone(body) + writeClaudeSSEMockResponse(w) + })) + defer server.Close() + + cfg := &config.Config{ + ClaudeKey: []config.ClaudeKey{{ + APIKey: "key-123", + Cloak: &config.CloakConfig{Mode: "always"}, + }}, + } + executor := NewClaudeExecutor(cfg) + auth := &cliproxyauth.Auth{Attributes: map[string]string{ + "api_key": "key-123", + "base_url": server.URL, + }} + + originalReq := []byte(`{ + "model": "claude-3-5-sonnet-20241022", + "prompt_cache_options": { + "mode": "explicit" + }, + "messages": [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Hello in cloaked mode"} + ] + }`) + + _, err := executor.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "claude-3-5-sonnet-20241022", + Payload: originalReq, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FromString("openai"), + OriginalRequest: originalReq, + }) + if err != nil { + t.Fatalf("Execute() error = %v", err) + } + + if count := countCacheControls(seenBody); count != 0 { + t.Fatalf("expected 0 cache_control blocks in cloaked mode with explicit mode and no client breakpoints, got %d: %s", count, string(seenBody)) + } + if gjson.GetBytes(seenBody, "prompt_cache_options").Exists() { + t.Fatalf("prompt_cache_options should not be forwarded upstream: %s", string(seenBody)) + } +} + +func TestClaudeExecutor_PromptCacheOptionsMode_Explicit_Cloaked_PreservesClientBreakpoints(t *testing.T) { + var seenBody []byte + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + seenBody = bytes.Clone(body) + writeClaudeSSEMockResponse(w) + })) + defer server.Close() + + cfg := &config.Config{ + ClaudeKey: []config.ClaudeKey{{ + APIKey: "key-123", + Cloak: &config.CloakConfig{Mode: "always"}, + }}, + } + executor := NewClaudeExecutor(cfg) + auth := &cliproxyauth.Auth{Attributes: map[string]string{ + "api_key": "key-123", + "base_url": server.URL, + }} + + originalReq := []byte(`{ + "model": "claude-3-5-sonnet-20241022", + "prompt_cache_options": { + "mode": "explicit" + }, + "messages": [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "First turn"}, + {"role": "assistant", "content": "Understood."}, + {"role": "user", "content": [ + {"type": "text", "text": "Specific cached user query", "cache_control": {"type": "ephemeral"}} + ]} + ] + }`) + + _, err := executor.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "claude-3-5-sonnet-20241022", + Payload: originalReq, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FromString("openai"), + OriginalRequest: originalReq, + }) + if err != nil { + t.Fatalf("Execute() error = %v", err) + } + + if count := countCacheControls(seenBody); count != 1 { + t.Fatalf("expected exactly 1 cache_control block (the client-specified one), got %d: %s", count, string(seenBody)) + } + if gjson.GetBytes(seenBody, "system.0.cache_control").Exists() || gjson.GetBytes(seenBody, "system.1.cache_control").Exists() { + t.Fatalf("system blocks should not have automatic cache_control: %s", string(seenBody)) + } + if !gjson.GetBytes(seenBody, "messages.3.content.0.cache_control").Exists() { + t.Fatalf("client specified cache_control on user turn should be preserved: %s", string(seenBody)) + } +} + +func TestClaudeExecutor_PromptCacheOptionsMode_Explicit_Cloaked_PreservesClientSystemBreakpoint(t *testing.T) { + var seenBody []byte + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + seenBody = bytes.Clone(body) + writeClaudeSSEMockResponse(w) + })) + defer server.Close() + + cfg := &config.Config{ + ClaudeKey: []config.ClaudeKey{{ + APIKey: "key-123", + Cloak: &config.CloakConfig{Mode: "always"}, + }}, + } + executor := NewClaudeExecutor(cfg) + auth := &cliproxyauth.Auth{Attributes: map[string]string{ + "api_key": "key-123", + "base_url": server.URL, + }} + + originalReq := []byte(`{ + "model": "claude-3-5-sonnet-20241022", + "prompt_cache_options": { + "mode": "explicit" + }, + "messages": [ + { + "role": "system", + "content": "Special client system prompt with breakpoint", + "cache_control": {"type": "ephemeral", "scope": "global"} + }, + { + "role": "user", + "content": "Regular user query" + } + ] + }`) + + _, err := executor.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "claude-3-5-sonnet-20241022", + Payload: originalReq, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FromString("openai"), + OriginalRequest: originalReq, + }) + if err != nil { + t.Fatalf("Execute() error = %v", err) + } + + if count := countCacheControls(seenBody); count != 1 { + t.Fatalf("expected exactly 1 cache_control block (the client system one), got %d: %s", count, string(seenBody)) + } + // Verify CPA synthetic agent block does NOT have cache_control + if gjson.GetBytes(seenBody, "system.1.cache_control").Exists() { + t.Fatalf("CPA synthetic agent block must not have cache_control: %s", string(seenBody)) + } + // Verify user message does NOT have cache_control + if gjson.GetBytes(seenBody, "messages.0.content.0.cache_control").Exists() { + t.Fatalf("first user message must not receive auto cache_control: %s", string(seenBody)) + } + // Verify client system prompt has cache_control preserved + foundClientSystemCC := false + messages := gjson.GetBytes(seenBody, "messages") + if messages.IsArray() { + messages.ForEach(func(_, msg gjson.Result) bool { + if msg.Get("role").String() == "system" { + content := msg.Get("content") + if content.IsArray() { + content.ForEach(func(_, part gjson.Result) bool { + if part.Get("text").String() == "Special client system prompt with breakpoint" && part.Get("cache_control.type").String() == "ephemeral" && part.Get("cache_control.scope").String() == "global" { + foundClientSystemCC = true + } + return true + }) + } + } + return true + }) + } + system := gjson.GetBytes(seenBody, "system") + if system.IsArray() { + system.ForEach(func(_, part gjson.Result) bool { + if part.Get("text").String() == "Special client system prompt with breakpoint" && part.Get("cache_control.type").String() == "ephemeral" && part.Get("cache_control.scope").String() == "global" { + foundClientSystemCC = true + } + return true + }) + } + if !foundClientSystemCC { + t.Fatalf("client specified cache_control on system prompt must be preserved: %s", string(seenBody)) + } +} + +func TestClaudeExecutor_CountTokens_StripsPromptCacheOptions(t *testing.T) { + var seenBody []byte + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + seenBody = bytes.Clone(body) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"input_tokens": 15}`)) + })) + defer server.Close() + + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{Attributes: map[string]string{ + "api_key": "key-123", + "base_url": server.URL, + }} + + originalReq := []byte(`{ + "model": "claude-3-5-sonnet-20241022", + "prompt_cache_options": { + "mode": "explicit" + }, + "messages": [ + {"role": "user", "content": "How many tokens?"} + ] + }`) + + resp, err := executor.CountTokens(context.Background(), auth, cliproxyexecutor.Request{ + Model: "claude-3-5-sonnet-20241022", + Payload: originalReq, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FromString("openai"), + OriginalRequest: originalReq, + }) + if err != nil { + t.Fatalf("CountTokens() error = %v", err) + } + if len(resp.Payload) == 0 { + t.Fatal("expected non-empty CountTokens payload") + } + + // For custom base_url, CountTokens uses the local estimator after stripping fields. + // Now test countTokensUpstream specifically to verify upstream payload body: + upstreamResp, errUpstream := executor.countTokensUpstream(context.Background(), auth, cliproxyexecutor.Request{ + Model: "claude-3-5-sonnet-20241022", + Payload: originalReq, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FromString("openai"), + OriginalRequest: originalReq, + }) + if errUpstream != nil { + t.Fatalf("countTokensUpstream() error = %v", errUpstream) + } + if len(upstreamResp.Payload) == 0 { + t.Fatal("expected non-empty countTokensUpstream payload") + } + if gjson.GetBytes(seenBody, "prompt_cache_options").Exists() { + t.Fatalf("prompt_cache_options should not be forwarded in count_tokens upstream: %s", string(seenBody)) + } +} + +func TestClaudeExecutor_CountTokensUpstream_StripsPromptCacheOptions_EvenWithPayloadRule(t *testing.T) { + var seenBody []byte + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + seenBody = bytes.Clone(body) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"input_tokens": 15}`)) + })) + defer server.Close() + + cfg := &config.Config{ + Payload: config.PayloadConfig{ + Override: []config.PayloadRule{ + { + Models: []config.PayloadModelRule{{Name: "claude-3-5-sonnet-20241022"}}, + Params: map[string]any{ + "prompt_cache_options.mode": "explicit", + }, + }, + }, + }, + } + executor := NewClaudeExecutor(cfg) + auth := &cliproxyauth.Auth{Attributes: map[string]string{ + "api_key": "key-123", + "base_url": server.URL, + }} + + originalReq := []byte(`{ + "model": "claude-3-5-sonnet-20241022", + "messages": [ + {"role": "user", "content": "How many tokens?"} + ] + }`) + + upstreamResp, errUpstream := executor.countTokensUpstream(context.Background(), auth, cliproxyexecutor.Request{ + Model: "claude-3-5-sonnet-20241022", + Payload: originalReq, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FromString("openai"), + OriginalRequest: originalReq, + }) + if errUpstream != nil { + t.Fatalf("countTokensUpstream() error = %v", errUpstream) + } + if len(upstreamResp.Payload) == 0 { + t.Fatal("expected non-empty countTokensUpstream payload") + } + if gjson.GetBytes(seenBody, "prompt_cache_options").Exists() { + t.Fatalf("prompt_cache_options should not be forwarded in count_tokens upstream even if injected by payload rule: %s", string(seenBody)) + } +} + +func TestClaudeExecutor_PromptCacheOptionsMode_Explicit_ProbePreservesClient1hTTL(t *testing.T) { + var seenBody []byte + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + seenBody = bytes.Clone(body) + writeClaudeSSEMockResponse(w) + })) + defer server.Close() + + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{Attributes: map[string]string{ + "api_key": "key-123", + "base_url": server.URL, + }} + + // "Hi" is a classic probe text that would trigger isProbeOrHelper in native cloaking. + originalReq := []byte(`{ + "model": "claude-3-5-sonnet-20241022", + "prompt_cache_options": { + "mode": "explicit" + }, + "messages": [ + { + "role": "user", + "content": [ + {"type": "text", "text": "Hi", "cache_control": {"type": "ephemeral", "ttl": "1h"}} + ] + } + ] + }`) + + _, err := executor.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "claude-3-5-sonnet-20241022", + Payload: originalReq, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FromString("openai"), + OriginalRequest: originalReq, + }) + if err != nil { + t.Fatalf("Execute() error = %v", err) + } + + if gotTTL := gjson.GetBytes(seenBody, "messages.0.content.0.cache_control.ttl").String(); gotTTL != "1h" { + t.Fatalf("client specified 1h TTL must be preserved in explicit mode even on probe request, got %q: %s", gotTTL, string(seenBody)) + } +} + +func TestClaudeExecutor_CountTokensUpstream_Cloaked_ExplicitPreservesClientSystemBreakpoint(t *testing.T) { + var seenBody []byte + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + seenBody = bytes.Clone(body) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"input_tokens": 20}`)) + })) + defer server.Close() + + cfg := &config.Config{ + ClaudeKey: []config.ClaudeKey{{ + APIKey: "key-123", + Cloak: &config.CloakConfig{Mode: "always"}, + }}, + } + executor := NewClaudeExecutor(cfg) + auth := &cliproxyauth.Auth{Attributes: map[string]string{ + "api_key": "key-123", + "base_url": server.URL, + }} + + originalReq := []byte(`{ + "model": "claude-3-5-sonnet-20241022", + "prompt_cache_options": { + "mode": "explicit" + }, + "messages": [ + { + "role": "system", + "content": "Count tokens system instructions", + "cache_control": {"type": "ephemeral", "scope": "global"} + }, + { + "role": "user", + "content": "Count tokens user message" + } + ] + }`) + + upstreamResp, errUpstream := executor.countTokensUpstream(context.Background(), auth, cliproxyexecutor.Request{ + Model: "claude-3-5-sonnet-20241022", + Payload: originalReq, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FromString("openai"), + OriginalRequest: originalReq, + }) + if errUpstream != nil { + t.Fatalf("countTokensUpstream() error = %v", errUpstream) + } + if len(upstreamResp.Payload) == 0 { + t.Fatal("expected non-empty countTokensUpstream payload") + } + + if count := countCacheControls(seenBody); count != 1 { + t.Fatalf("expected exactly 1 cache_control in count_tokens explicit mode, got %d: %s", count, string(seenBody)) + } + // Verify user message did not get auto-cached + if gjson.GetBytes(seenBody, "messages.0.content.0.cache_control").Exists() { + t.Fatalf("user message must not receive auto cache_control: %s", string(seenBody)) + } + // Verify client system breakpoint was preserved with scope: global + foundClientSystemCC := false + messages := gjson.GetBytes(seenBody, "messages") + if messages.IsArray() { + messages.ForEach(func(_, msg gjson.Result) bool { + if msg.Get("role").String() == "system" { + content := msg.Get("content") + if content.IsArray() { + content.ForEach(func(_, part gjson.Result) bool { + if part.Get("text").String() == "Count tokens system instructions" && + part.Get("cache_control.type").String() == "ephemeral" && + part.Get("cache_control.scope").String() == "global" { + foundClientSystemCC = true + } + return true + }) + } + } + return true + }) + } + if !foundClientSystemCC { + t.Fatalf("client specified cache_control with scope: global must be preserved in count_tokens: %s", string(seenBody)) + } +} + +func TestClaudeExecutor_PromptCacheOptionsMode_Explicit_Cloaked_LegacyModelPreservesClientSystemBreakpoint(t *testing.T) { + var seenBody []byte + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + seenBody = bytes.Clone(body) + writeClaudeSSEMockResponse(w) + })) + defer server.Close() + + cfg := &config.Config{ + ClaudeKey: []config.ClaudeKey{{ + APIKey: "key-123", + Cloak: &config.CloakConfig{Mode: "always"}, + }}, + } + executor := NewClaudeExecutor(cfg) + auth := &cliproxyauth.Auth{Attributes: map[string]string{ + "api_key": "key-123", + "base_url": server.URL, + }} + + // claude-3-5-haiku-20241022 is in claudeLegacySystemReminderModels, so it uses legacy system reminders + originalReq := []byte(`{ + "model": "claude-3-5-haiku-20241022", + "prompt_cache_options": { + "mode": "explicit" + }, + "messages": [ + { + "role": "system", + "content": "Legacy system instructions with scope", + "cache_control": {"type": "ephemeral", "scope": "global"} + }, + { + "role": "user", + "content": "User prompt" + } + ] + }`) + + _, err := executor.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "claude-3-5-haiku-20241022", + Payload: originalReq, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FromString("openai"), + OriginalRequest: originalReq, + }) + if err != nil { + t.Fatalf("Execute() error = %v", err) + } + + if count := countCacheControls(seenBody); count != 1 { + t.Fatalf("expected exactly 1 cache_control block in legacy model explicit mode, got %d: %s", count, string(seenBody)) + } + // Verify system.1 agent block does not have cache_control + if gjson.GetBytes(seenBody, "system.1.cache_control").Exists() { + t.Fatalf("agent block must not have cache_control: %s", string(seenBody)) + } + // Verify the prepended reminder on user message preserves scope: global + foundReminderCC := false + messages := gjson.GetBytes(seenBody, "messages") + if messages.IsArray() { + messages.ForEach(func(_, msg gjson.Result) bool { + content := msg.Get("content") + if content.IsArray() { + content.ForEach(func(_, part gjson.Result) bool { + if strings.Contains(part.Get("text").String(), "Legacy system instructions with scope") && + part.Get("cache_control.type").String() == "ephemeral" && + part.Get("cache_control.scope").String() == "global" { + foundReminderCC = true + } + return true + }) + } + return true + }) + } + if !foundReminderCC { + t.Fatalf("legacy system reminder must preserve client cache_control with scope: global: %s", string(seenBody)) + } +} + +func TestClaudeExecutor_CountTokensUpstream_Cloaked_LegacyModel_ExplicitPreservesClientSystemBreakpoint(t *testing.T) { + var seenBody []byte + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + seenBody = bytes.Clone(body) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"input_tokens": 20}`)) + })) + defer server.Close() + + cfg := &config.Config{ + ClaudeKey: []config.ClaudeKey{{ + APIKey: "key-123", + Cloak: &config.CloakConfig{Mode: "always"}, + }}, + } + executor := NewClaudeExecutor(cfg) + auth := &cliproxyauth.Auth{Attributes: map[string]string{ + "api_key": "key-123", + "base_url": server.URL, + }} + + originalReq := []byte(`{ + "model": "claude-3-5-haiku-20241022", + "prompt_cache_options": { + "mode": "explicit" + }, + "messages": [ + { + "role": "system", + "content": "Count tokens legacy system instructions", + "cache_control": {"type": "ephemeral", "scope": "global"} + }, + { + "role": "user", + "content": "User prompt" + } + ] + }`) + + upstreamResp, errUpstream := executor.countTokensUpstream(context.Background(), auth, cliproxyexecutor.Request{ + Model: "claude-3-5-haiku-20241022", + Payload: originalReq, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FromString("openai"), + OriginalRequest: originalReq, + }) + if errUpstream != nil { + t.Fatalf("countTokensUpstream() error = %v", errUpstream) + } + if len(upstreamResp.Payload) == 0 { + t.Fatal("expected non-empty countTokensUpstream payload") + } + + if count := countCacheControls(seenBody); count != 1 { + t.Fatalf("expected exactly 1 cache_control in legacy count_tokens explicit mode, got %d: %s", count, string(seenBody)) + } + foundReminderCC := false + messages := gjson.GetBytes(seenBody, "messages") + if messages.IsArray() { + messages.ForEach(func(_, msg gjson.Result) bool { + content := msg.Get("content") + if content.IsArray() { + content.ForEach(func(_, part gjson.Result) bool { + if strings.Contains(part.Get("text").String(), "Count tokens legacy system instructions") && + part.Get("cache_control.type").String() == "ephemeral" && + part.Get("cache_control.scope").String() == "global" { + foundReminderCC = true + } + return true + }) + } + return true + }) + } + if !foundReminderCC { + t.Fatalf("legacy count_tokens system reminder must preserve client cache_control with scope: global: %s", string(seenBody)) + } +} From 0ea4e1dcb4f0820c15789aded986e7b217c1086e Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Mon, 5 Oct 2026 15:55:23 +0800 Subject: [PATCH 055/142] fix(openai): complete responses stream on clean EOF after finish reason - Track pending completion state in OpenAI-to-Responses translator when item output is complete and a finish reason is received - Synthesize terminal `[DONE]` event on clean EOF when response completion is pending instead of failing the stream Closes: #6381 --- .../runtime/executor/helps/apply_patch.go | 6 + .../executor/issue6381_responses_eof_test.go | 196 ++++++++++++++++++ .../executor/openai_compat_executor.go | 22 +- .../openai_openai-responses_response.go | 34 ++- 4 files changed, 252 insertions(+), 6 deletions(-) create mode 100644 internal/runtime/executor/issue6381_responses_eof_test.go diff --git a/internal/runtime/executor/helps/apply_patch.go b/internal/runtime/executor/helps/apply_patch.go index bd0c8e9e5f9..bfbb78901fb 100644 --- a/internal/runtime/executor/helps/apply_patch.go +++ b/internal/runtime/executor/helps/apply_patch.go @@ -30,6 +30,12 @@ func FinalizeApplyPatchStream(param any) [][]byte { return state.FinalizeToolInput() } +// CanFinalizeResponseStream reports whether EOF can safely synthesize the source terminator. +func CanFinalizeResponseStream(param any) bool { + state, okState := param.(interface{ CanFinalizeResponseStream() bool }) + return okState && state.CanFinalizeResponseStream() +} + // RecordApplyPatchStreamFailure records validation before delivery can be canceled. func RecordApplyPatchStreamFailure(ctx context.Context, param any, reporter *UsageReporter, gatewayErr error) bool { if ApplyPatchTranslationError(param) == nil { diff --git a/internal/runtime/executor/issue6381_responses_eof_test.go b/internal/runtime/executor/issue6381_responses_eof_test.go new file mode 100644 index 00000000000..efe1899bec6 --- /dev/null +++ b/internal/runtime/executor/issue6381_responses_eof_test.go @@ -0,0 +1,196 @@ +package executor + +import ( + "bytes" + "context" + "errors" + "io" + "net/http" + "strings" + "testing" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +type issue6381RoundTripperFunc func(*http.Request) (*http.Response, error) + +func (fn issue6381RoundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) { + return fn(req) +} + +type issue6381ReadError struct { + chunks [][]byte + index int +} + +func (r *issue6381ReadError) Read(p []byte) (int, error) { + if r.index >= len(r.chunks) { + return 0, errors.New("synthetic upstream read error") + } + chunk := r.chunks[r.index] + if len(chunk) > len(p) { + copy(p, chunk[:len(p)]) + r.chunks[r.index] = chunk[len(p):] + return len(p), nil + } + r.index++ + return copy(p, chunk), nil +} + +func TestOpenAICompatExecutorResponsesEOFAfterFinishReasonCompletesStream(t *testing.T) { + reply := strings.Join([]string{ + `data: {"id":"chatcmpl-eof","object":"chat.completion.chunk","created":1773896263,"model":"test","choices":[{"index":0,"delta":{"role":"assistant","content":"done"},"finish_reason":null}]}`, + "", + `data: {"id":"chatcmpl-eof","object":"chat.completion.chunk","created":1773896263,"model":"test","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`, + "", + `data: {"id":"chatcmpl-eof","object":"chat.completion.chunk","created":1773896263,"model":"test","choices":[],"usage":{"prompt_tokens":3,"completion_tokens":1,"total_tokens":4}}`, + "", + }, "\n") + exec, auth, _ := newApplyPatchCompatTestExecutor(t, reply) + request := []byte(`{"model":"test","input":[{"role":"user","content":[{"type":"input_text","text":"hello"}]}],"stream":true}`) + + result, errExecuteStream := exec.ExecuteStream(t.Context(), auth, cliproxyexecutor.Request{Model: "test", Payload: request}, cliproxyexecutor.Options{ + SourceFormat: translator.FormatOpenAIResponse, + ResponseFormat: translator.FormatOpenAIResponse, + OriginalRequest: request, + Stream: true, + }) + if errExecuteStream != nil { + t.Fatal(errExecuteStream) + } + + var output bytes.Buffer + for chunk := range result.Chunks { + if chunk.Err != nil { + t.Fatalf("unexpected stream error after a completed finish_reason: %v", chunk.Err) + } + output.Write(chunk.Payload) + } + if got := strings.Count(output.String(), `"type":"response.completed"`); got != 1 { + t.Fatalf("response.completed count = %d, want 1; output = %q", got, output.String()) + } + if !strings.Contains(output.String(), `"input_tokens":3`) || !strings.Contains(output.String(), `"output_tokens":1`) { + t.Fatalf("late usage was not preserved in response.completed: %q", output.String()) + } +} + +func TestOpenAICompatExecutorResponsesEOFAfterApplyPatchFinishReasonCompletesStream(t *testing.T) { + first, last := applyPatchTestFrames("chat", "apply_patch") + last = strings.Replace(last, "\ndata: [DONE]\n\n", "\n\n", 1) + exec, auth, _ := newApplyPatchCompatTestExecutor(t, first+last) + request := applyPatchTestRequest() + + result, errExecuteStream := exec.ExecuteStream(t.Context(), auth, cliproxyexecutor.Request{Model: "test", Payload: request}, cliproxyexecutor.Options{ + SourceFormat: translator.FormatOpenAIResponse, + ResponseFormat: translator.FormatOpenAIResponse, + OriginalRequest: request, + Stream: true, + }) + if errExecuteStream != nil { + t.Fatal(errExecuteStream) + } + + var output bytes.Buffer + for chunk := range result.Chunks { + if chunk.Err != nil { + t.Fatalf("unexpected apply_patch stream error after a completed finish_reason: %v", chunk.Err) + } + output.Write(chunk.Payload) + } + if got := strings.Count(output.String(), `"type":"response.completed"`); got != 1 { + t.Fatalf("response.completed count = %d, want 1; output = %q", got, output.String()) + } + if strings.Contains(output.String(), `"type":"response.failed"`) { + t.Fatalf("completed apply_patch stream emitted response.failed: %q", output.String()) + } +} + +func TestOpenAICompatExecutorResponsesScannerErrorDoesNotSynthesizeCompletion(t *testing.T) { + reply := strings.Join([]string{ + `data: {"id":"chatcmpl-reset","object":"chat.completion.chunk","created":1773896263,"model":"test","choices":[{"index":0,"delta":{"role":"assistant","content":"done"},"finish_reason":null}]}`, + "", + `data: {"id":"chatcmpl-reset","object":"chat.completion.chunk","created":1773896263,"model":"test","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`, + "", + }, "\n") + exec := NewOpenAICompatExecutor("custom-compat", &config.Config{}) + auth := &cliproxyauth.Auth{Provider: "custom-compat", Attributes: map[string]string{"base_url": "http://responses.test/v1", "api_key": "test"}} + ctx := context.WithValue(t.Context(), "cliproxy.roundtripper", issue6381RoundTripperFunc(func(req *http.Request) (*http.Response, error) { + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(&issue6381ReadError{chunks: [][]byte{ + []byte(strings.Split(reply, "\n\n")[0] + "\n\n"), + []byte(strings.Split(reply, "\n\n")[1] + "\n\n"), + }}), + Request: req, + }, nil + })) + request := []byte(`{"model":"test","input":[{"role":"user","content":[{"type":"input_text","text":"hello"}]}],"stream":true}`) + + result, errExecuteStream := exec.ExecuteStream(ctx, auth, cliproxyexecutor.Request{Model: "test", Payload: request}, cliproxyexecutor.Options{ + SourceFormat: translator.FormatOpenAIResponse, + ResponseFormat: translator.FormatOpenAIResponse, + OriginalRequest: request, + Stream: true, + }) + if errExecuteStream != nil { + t.Fatal(errExecuteStream) + } + + var output bytes.Buffer + var streamFailed bool + for chunk := range result.Chunks { + if chunk.Err != nil { + streamFailed = true + continue + } + output.Write(chunk.Payload) + } + if !strings.Contains(output.String(), `"type":"response.output_text.delta"`) { + t.Fatalf("scanner-error stream did not deliver its valid content frame: %q", output.String()) + } + if !streamFailed { + t.Fatalf("scanner error was treated as a successful stream: %q", output.String()) + } + if strings.Contains(output.String(), `"type":"response.completed"`) { + t.Fatalf("scanner-error stream emitted response.completed: %q", output.String()) + } +} + +func TestOpenAICompatExecutorResponsesEOFBeforeFinishReasonFailsStream(t *testing.T) { + reply := "data: {\"id\":\"chatcmpl-truncated\",\"object\":\"chat.completion.chunk\",\"created\":1773896263,\"model\":\"test\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"partial\"},\"finish_reason\":null}]}\n\n" + exec, auth, _ := newApplyPatchCompatTestExecutor(t, reply) + request := []byte(`{"model":"test","input":[{"role":"user","content":[{"type":"input_text","text":"hello"}]}],"stream":true}`) + + result, errExecuteStream := exec.ExecuteStream(t.Context(), auth, cliproxyexecutor.Request{Model: "test", Payload: request}, cliproxyexecutor.Options{ + SourceFormat: translator.FormatOpenAIResponse, + ResponseFormat: translator.FormatOpenAIResponse, + OriginalRequest: request, + Stream: true, + }) + if errExecuteStream != nil { + t.Fatal(errExecuteStream) + } + + var output bytes.Buffer + var streamFailed bool + for chunk := range result.Chunks { + if chunk.Err != nil { + streamFailed = true + continue + } + output.Write(chunk.Payload) + } + if !strings.Contains(output.String(), `"type":"response.output_text.delta"`) { + t.Fatalf("truncated Responses stream did not deliver its valid content frame: %q", output.String()) + } + if !streamFailed { + t.Fatalf("truncated Responses stream completed successfully: %q", output.String()) + } + if strings.Contains(output.String(), `"type":"response.completed"`) { + t.Fatalf("truncated Responses stream emitted response.completed: %q", output.String()) + } +} diff --git a/internal/runtime/executor/openai_compat_executor.go b/internal/runtime/executor/openai_compat_executor.go index 49ba0eb3963..562a0c959f8 100644 --- a/internal/runtime/executor/openai_compat_executor.go +++ b/internal/runtime/executor/openai_compat_executor.go @@ -551,10 +551,26 @@ func (e *OpenAICompatExecutor) ExecuteStream(ctx context.Context, auth *cliproxy if !streamFailed && !streamAborted && helps.EndApplyPatchStream(ctx, param, reporter, out, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) { return } + if !streamFailed && !streamAborted && !seenDone && errScan == nil && responseFormat == sdktranslator.FormatOpenAIResponse && ctx.Err() == nil && helps.CanFinalizeResponseStream(param) { + finalChunks := helps.TranslateStreamWithClaudeInputTokens(ctx, to, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), translated, []byte("data: [DONE]"), ¶m, claudeInputTokens) + for _, finalChunk := range finalChunks { + select { + case out <- cliproxyexecutor.StreamChunk{Payload: finalChunk}: + case <-ctx.Done(): + streamAborted = true + } + if streamAborted { + break + } + } + if len(finalChunks) > 0 && !streamAborted { + seenDone = true + } + } if streamFailed || streamAborted { return } - if errScan != nil { + if errScan != nil && !seenDone { helps.RecordAPIResponseError(ctx, e.cfg, errScan) reporter.PublishFailure(ctx, errScan) select { @@ -562,8 +578,8 @@ func (e *OpenAICompatExecutor) ExecuteStream(ctx context.Context, auth *cliproxy case <-ctx.Done(): } } else if !seenDone { - // Responses clients require an explicit terminal event. Treat a clean - // upstream EOF without [DONE] as a failed stream instead of completing it. + // Without a translator-confirmed terminal state, a clean Responses EOF + // without [DONE] remains a failed stream instead of completing it. if responseFormat == sdktranslator.FormatOpenAIResponse { streamErr := statusErr{code: http.StatusBadGateway, msg: "upstream stream closed before [DONE]"} helps.RecordAPIResponseError(ctx, e.cfg, streamErr) diff --git a/internal/translator/openai/openai/responses/openai_openai-responses_response.go b/internal/translator/openai/openai/responses/openai_openai-responses_response.go index 6d87b1f5ffc..63f7eb4ebaf 100644 --- a/internal/translator/openai/openai/responses/openai_openai-responses_response.go +++ b/internal/translator/openai/openai/responses/openai_openai-responses_response.go @@ -30,6 +30,7 @@ type oaiToResponsesState struct { Created int64 Started bool CompletedEmitted bool + CompletionPending bool ReasoningID string ReasoningIndex int // aggregation buffers for response.output @@ -494,6 +495,7 @@ func ConvertOpenAIChatCompletionsResponseToOpenAIResponses(ctx context.Context, st.FinishReason = "" st.UsageSeen = false st.CompletedEmitted = false + st.CompletionPending = false // response.created created := []byte(`{"type":"response.created","sequence_number":0,"response":{"id":"","object":"response","created_at":0,"status":"in_progress","background":false,"error":null,"output":[]}}`) created, _ = sjson.SetBytes(created, "sequence_number", nextSeq()) @@ -883,12 +885,13 @@ func ConvertOpenAIChatCompletionsResponseToOpenAIResponses(ctx context.Context, return false } - // finish_reason triggers item-level finalization. response.completed is - // deferred until the terminal [DONE] marker so late usage-only chunks can - // still populate response.usage. + // finish_reason triggers item-level finalization. The terminal event is + // deferred until [DONE] or transport finalization so late usage-only chunks + // can still populate response.usage. if fr := choice.Get("finish_reason"); fr.Exists() && fr.String() != "" { st.FinishReason = fr.String() finalizeOpenItems() + st.CompletionPending = st.canFinalizeResponse() } return st.ToolInputError() == nil @@ -1148,11 +1151,36 @@ func ConvertOpenAIChatCompletionsResponseToOpenAIResponsesNonStream(_ context.Co return resp } +func (st *oaiToResponsesState) canFinalizeResponse() bool { + if st.ToolInputError() != nil || st.FinishReason == "" || (len(st.MsgItemAdded) == 0 && len(st.FuncItemAdded) == 0) { + return false + } + for idx := range st.MsgItemAdded { + if !st.MsgItemDone[idx] { + return false + } + } + for key := range st.FuncItemAdded { + if !st.FuncItemDone[key] { + return false + } + } + return st.ReasoningID == "" +} + +// CanFinalizeResponseStream reports whether EOF can safely synthesize the source terminator. +func (st *oaiToResponsesState) CanFinalizeResponseStream() bool { + return st.ToolInputError() == nil && !st.CompletedEmitted && st.CompletionPending +} + // FinalizeToolInput rejects a patch-enabled stream lacking its source terminator. func (st *oaiToResponsesState) FinalizeToolInput() [][]byte { if st.ToolInputError() != nil || st.CompletedEmitted { return nil } + if st.CanFinalizeResponseStream() { + return nil + } enabled := false if st.ToolIndex != nil { for name := range st.ToolIndex.byChat { From 01e2856704d86ac6e63b477c445802b13616740e Mon Sep 17 00:00:00 2001 From: hkfires <10558748+hkfires@users.noreply.github.com> Date: Mon, 5 Oct 2026 16:47:04 +0800 Subject: [PATCH 056/142] fix(registry): disable Devin catalog for home builds --- internal/registry/catalog_policy_test.go | 3 +++ internal/registry/catalog_reload_test.go | 7 ++++++- internal/registry/catalog_sources.go | 4 +++- 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/internal/registry/catalog_policy_test.go b/internal/registry/catalog_policy_test.go index 2692878d75e..b1b7f562fc0 100644 --- a/internal/registry/catalog_policy_test.go +++ b/internal/registry/catalog_policy_test.go @@ -26,6 +26,9 @@ func TestEffectiveCatalogSources(t *testing.T) { if index == 0 && home { want = "disabled" } + if index == 2 && home { + want = "disabled" + } if values[index] != want { t.Fatalf("local=%v home=%v mask=%d catalog=%d: got %q want %q", local, home, mask, index, values[index], want) } diff --git a/internal/registry/catalog_reload_test.go b/internal/registry/catalog_reload_test.go index 65db38bc2e4..5da07776e4d 100644 --- a/internal/registry/catalog_reload_test.go +++ b/internal/registry/catalog_reload_test.go @@ -57,6 +57,12 @@ func TestCatalogPolicyHotReload(t *testing.T) { if source != "disabled" { t.Fatal("Home allowed general catalog") } + devinCatalogUpdater.mu.Lock() + source = devinCatalogUpdater.source + devinCatalogUpdater.mu.Unlock() + if source != "disabled" { + t.Fatal("Home allowed Devin catalog") + } UpdateModelCatalogSources(CatalogSources{}, false) awaitSource(general, embeddedCatalogSource) @@ -76,7 +82,6 @@ func TestCatalogPolicyHotReload(t *testing.T) { defer restartCancel() StartModelCatalogUpdaters(restartCtx, CatalogSources{Catalog: "https://example.com/ignored"}, true) awaitSource(codex, embeddedCatalogSource) - awaitSource(devin, embeddedCatalogSource) generalCatalogUpdater.mu.Lock() source = generalCatalogUpdater.source generalCatalogUpdater.mu.Unlock() diff --git a/internal/registry/catalog_sources.go b/internal/registry/catalog_sources.go index 114a5f6c29a..f89a153f2f3 100644 --- a/internal/registry/catalog_sources.go +++ b/internal/registry/catalog_sources.go @@ -251,10 +251,12 @@ func effectiveCatalogSources(sources CatalogSources, local, home bool) CatalogSo return source } general := selectSource(sources.Catalog) + devin := selectSource(sources.DevinCatalog) if home { general = "disabled" + devin = "disabled" } - return CatalogSources{Catalog: general, CodexCatalog: selectSource(sources.CodexCatalog), DevinCatalog: selectSource(sources.DevinCatalog)} + return CatalogSources{Catalog: general, CodexCatalog: selectSource(sources.CodexCatalog), DevinCatalog: devin} } func validateDevinCatalogBytes(data []byte) error { From c7b4d573f9f810979c88631a777581639b3d3956 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Mon, 5 Oct 2026 17:07:50 +0800 Subject: [PATCH 057/142] fix(codex): record reasoning effort after applying payload overrides - Record reasoning effort from finalized upstream payload after cache helper processing across execution, streaming, compaction, and image requests Closes: #6388 --- .../executor/codex_executor_execute.go | 4 +- .../codex_executor_execute_usage_test.go | 175 ++++++++++++++++++ .../runtime/executor/codex_executor_stream.go | 2 +- .../runtime/executor/codex_openai_images.go | 4 +- 4 files changed, 180 insertions(+), 5 deletions(-) diff --git a/internal/runtime/executor/codex_executor_execute.go b/internal/runtime/executor/codex_executor_execute.go index 73f6ec228df..60bc8bb638b 100644 --- a/internal/runtime/executor/codex_executor_execute.go +++ b/internal/runtime/executor/codex_executor_execute.go @@ -72,13 +72,13 @@ func (e *CodexExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, re if errReplay != nil { return resp, errReplay } - reporter.SetTranslatedReasoningEffort(body, to.String()) url := strings.TrimSuffix(baseURL, "/") + "/responses" httpReq, upstreamBody, err := e.cacheHelper(ctx, from, url, req, body, opts.Headers) if err != nil { return resp, err } + reporter.SetTranslatedReasoningEffort(upstreamBody, to.String()) applyCodexHeaders(httpReq, auth, apiKey, true, e.cfg, opts.Headers) applyCodexRoutingHint(ctx, httpReq.Header, auth, baseModel, upstreamBody, opts.Headers) applyModelHeaderOverrides(httpReq.Header, baseModel) @@ -241,13 +241,13 @@ func (e *CodexExecutor) executeCompact(ctx context.Context, auth *cliproxyauth.A body = normalizeCodexParallelToolCalls(body, opts.Headers) body = helps.NormalizeCodexToolSchemas(body) body, optimizeMultiAgentV2 := helps.OptimizeCodexMultiAgentV2RequestForAuth(ctx, opts.Headers, body, e.cfg, auth, isCompat) - reporter.SetTranslatedReasoningEffort(body, to.String()) url := strings.TrimSuffix(baseURL, "/") + "/responses/compact" httpReq, upstreamBody, err := e.cacheHelper(ctx, from, url, req, body, opts.Headers) if err != nil { return resp, err } + reporter.SetTranslatedReasoningEffort(upstreamBody, to.String()) applyCodexHeaders(httpReq, auth, apiKey, false, e.cfg, opts.Headers) applyCodexRoutingHint(ctx, httpReq.Header, auth, baseModel, upstreamBody, opts.Headers) applyModelHeaderOverrides(httpReq.Header, baseModel) diff --git a/internal/runtime/executor/codex_executor_execute_usage_test.go b/internal/runtime/executor/codex_executor_execute_usage_test.go index 604f0ad8eb2..e289a4444dd 100644 --- a/internal/runtime/executor/codex_executor_execute_usage_test.go +++ b/internal/runtime/executor/codex_executor_execute_usage_test.go @@ -3,6 +3,7 @@ package executor import ( "context" "fmt" + "io" "net/http" "net/http/httptest" "testing" @@ -12,6 +13,7 @@ import ( cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" coreusage "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" ) func TestCodexExecutorExecutePublishesMainUsageBeforeImageUsage(t *testing.T) { @@ -90,3 +92,176 @@ func TestCodexExecutorExecutePublishesMainUsageBeforeImageUsage(t *testing.T) { } } } + +func TestCodexExecutorExecuteRecordsFinalizedPayloadOverrideReasoningEffort(t *testing.T) { + cfg := &config.Config{ + Payload: config.PayloadConfig{ + Override: []config.PayloadRule{ + { + Models: []config.PayloadModelRule{ + {Name: "gpt-5.6-luna", Protocol: "codex"}, + }, + Params: map[string]any{ + "reasoning.effort": "high", + }, + }, + }, + }, + } + + var upstreamBody []byte + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var errRead error + upstreamBody, errRead = io.ReadAll(r.Body) + if errRead != nil { + t.Errorf("read body: %v", errRead) + } + w.Header().Set("Content-Type", "text/event-stream") + _, _ = fmt.Fprintf(w, "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_1\",\"object\":\"response\",\"status\":\"completed\",\"model\":\"gpt-5.6-luna\",\"output\":[{\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"ok\"}]}],\"usage\":{\"input_tokens\":10,\"output_tokens\":20,\"total_tokens\":30}}}\n\n") + })) + t.Cleanup(server.Close) + + alias := t.Name() + capture := &codexResponseModelUsageCapture{alias: alias, records: make(chan coreusage.Record, 4)} + coreusage.RegisterNamedPlugin(t.Name(), capture) + t.Cleanup(func() { + coreusage.RegisterNamedPlugin(t.Name(), codexResponseModelNoopUsagePlugin{}) + }) + + ctx := coreusage.WithRequestedModelAlias(context.Background(), alias) + executor := NewCodexExecutor(cfg) + resp, errExecute := executor.Execute(ctx, codexOAuthTestAuth(server.URL), cliproxyexecutor.Request{ + Model: "gpt-5.6-luna", + Payload: []byte(`{"model":"gpt-5.6-luna","messages":[{"role":"user","content":"hello"}]}`), + }, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatOpenAI}) + if errExecute != nil { + t.Fatalf("Execute: %v", errExecute) + } + if len(resp.Payload) == 0 { + t.Fatal("Execute returned an empty response") + } + + if effort := gjson.GetBytes(upstreamBody, "reasoning.effort").String(); effort != "high" { + t.Fatalf("upstream payload reasoning.effort = %q, want %q", effort, "high") + } + + record := capture.await(t) + if record.ReasoningEffort != "high" { + t.Fatalf("usage record ReasoningEffort = %q, want %q", record.ReasoningEffort, "high") + } +} + +func TestCodexExecutorExecuteStreamRecordsFinalizedPayloadOverrideReasoningEffort(t *testing.T) { + cfg := &config.Config{ + Payload: config.PayloadConfig{ + Override: []config.PayloadRule{ + { + Models: []config.PayloadModelRule{ + {Name: "gpt-5.6-luna", Protocol: "codex"}, + }, + Params: map[string]any{ + "reasoning.effort": "high", + }, + }, + }, + }, + } + + var upstreamBody []byte + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var errRead error + upstreamBody, errRead = io.ReadAll(r.Body) + if errRead != nil { + t.Errorf("read body: %v", errRead) + } + w.Header().Set("Content-Type", "text/event-stream") + _, _ = fmt.Fprintf(w, "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_1\",\"object\":\"response\",\"status\":\"completed\",\"model\":\"gpt-5.6-luna\",\"output\":[{\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"ok\"}]}],\"usage\":{\"input_tokens\":10,\"output_tokens\":20,\"total_tokens\":30}}}\n\n") + })) + t.Cleanup(server.Close) + + alias := t.Name() + capture := &codexResponseModelUsageCapture{alias: alias, records: make(chan coreusage.Record, 4)} + coreusage.RegisterNamedPlugin(t.Name(), capture) + t.Cleanup(func() { + coreusage.RegisterNamedPlugin(t.Name(), codexResponseModelNoopUsagePlugin{}) + }) + + ctx := coreusage.WithRequestedModelAlias(context.Background(), alias) + executor := NewCodexExecutor(cfg) + streamRes, errStream := executor.ExecuteStream(ctx, codexOAuthTestAuth(server.URL), cliproxyexecutor.Request{ + Model: "gpt-5.6-luna", + Payload: []byte(`{"model":"gpt-5.6-luna","messages":[{"role":"user","content":"hello"}]}`), + }, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatOpenAI, Stream: true}) + if errStream != nil { + t.Fatalf("ExecuteStream: %v", errStream) + } + for range streamRes.Chunks { + } + + if effort := gjson.GetBytes(upstreamBody, "reasoning.effort").String(); effort != "high" { + t.Fatalf("upstream payload reasoning.effort = %q, want %q", effort, "high") + } + + record := capture.await(t) + if record.ReasoningEffort != "high" { + t.Fatalf("usage record ReasoningEffort = %q, want %q", record.ReasoningEffort, "high") + } +} + +func TestCodexExecutorExecuteCompactRecordsFinalizedPayloadOverrideReasoningEffort(t *testing.T) { + cfg := &config.Config{ + Payload: config.PayloadConfig{ + Override: []config.PayloadRule{ + { + Models: []config.PayloadModelRule{ + {Name: "gpt-5.6-luna", Protocol: "openai-response"}, + }, + Params: map[string]any{ + "reasoning.effort": "high", + }, + }, + }, + }, + } + + var upstreamBody []byte + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var errRead error + upstreamBody, errRead = io.ReadAll(r.Body) + if errRead != nil { + t.Errorf("read body: %v", errRead) + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"id":"resp_1","object":"response.compaction","usage":{"input_tokens":1,"output_tokens":2,"total_tokens":3}}`)) + })) + t.Cleanup(server.Close) + + alias := t.Name() + capture := &codexResponseModelUsageCapture{alias: alias, records: make(chan coreusage.Record, 4)} + coreusage.RegisterNamedPlugin(t.Name(), capture) + t.Cleanup(func() { + coreusage.RegisterNamedPlugin(t.Name(), codexResponseModelNoopUsagePlugin{}) + }) + + ctx := coreusage.WithRequestedModelAlias(context.Background(), alias) + executor := NewCodexExecutor(cfg) + resp, errExecute := executor.Execute(ctx, codexOAuthTestAuth(server.URL), cliproxyexecutor.Request{ + Model: "gpt-5.6-luna", + Payload: []byte(`{"model":"gpt-5.6-luna","input":[{"type":"message","role":"user","content":"history"},{"type":"compaction_trigger"}]}`), + }, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatOpenAIResponse, Alt: "responses/compact"}) + if errExecute != nil { + t.Fatalf("Execute: %v", errExecute) + } + if len(resp.Payload) == 0 { + t.Fatal("Execute returned an empty response") + } + + if effort := gjson.GetBytes(upstreamBody, "reasoning.effort").String(); effort != "high" { + t.Fatalf("upstream payload reasoning.effort = %q, want %q", effort, "high") + } + + record := capture.await(t) + if record.ReasoningEffort != "high" { + t.Fatalf("usage record ReasoningEffort = %q, want %q", record.ReasoningEffort, "high") + } +} diff --git a/internal/runtime/executor/codex_executor_stream.go b/internal/runtime/executor/codex_executor_stream.go index a0e6a32ee41..fa0f07303e8 100644 --- a/internal/runtime/executor/codex_executor_stream.go +++ b/internal/runtime/executor/codex_executor_stream.go @@ -80,13 +80,13 @@ func (e *CodexExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Au if errReplay != nil { return nil, errReplay } - reporter.SetTranslatedReasoningEffort(body, to.String()) url := strings.TrimSuffix(baseURL, "/") + "/responses" httpReq, upstreamBody, err := e.cacheHelper(ctx, from, url, req, body, opts.Headers) if err != nil { return nil, err } + reporter.SetTranslatedReasoningEffort(upstreamBody, to.String()) applyCodexHeaders(httpReq, auth, apiKey, true, e.cfg, opts.Headers) applyCodexRoutingHint(ctx, httpReq.Header, auth, baseModel, upstreamBody, opts.Headers) applyModelHeaderOverrides(httpReq.Header, baseModel) diff --git a/internal/runtime/executor/codex_openai_images.go b/internal/runtime/executor/codex_openai_images.go index ab42d1dc2fb..98e7c48e8ef 100644 --- a/internal/runtime/executor/codex_openai_images.go +++ b/internal/runtime/executor/codex_openai_images.go @@ -107,7 +107,6 @@ func (e *CodexExecutor) executeOpenAIImage(ctx context.Context, auth *cliproxyau if errBuild != nil { return resp, errBuild } - reporter.SetTranslatedReasoningEffort(body, "codex") url := strings.TrimSuffix(baseURL, "/") + "/responses" payloadOpts := opts @@ -117,6 +116,7 @@ func (e *CodexExecutor) executeOpenAIImage(ctx context.Context, auth *cliproxyau if errCache != nil { return resp, errCache } + reporter.SetTranslatedReasoningEffort(body, "codex") applyCodexHeaders(httpReq, auth, apiKey, true, e.cfg, opts.Headers) applyModelHeaderOverrides(httpReq.Header, mainModel) recordCodexOpenAIImageRequest(ctx, e.cfg, e.Identifier(), auth, url, httpReq.Header.Clone(), body) @@ -205,7 +205,6 @@ func (e *CodexExecutor) executeOpenAIImageStream(ctx context.Context, auth *clip if errBuild != nil { return nil, errBuild } - reporter.SetTranslatedReasoningEffort(body, "codex") url := strings.TrimSuffix(baseURL, "/") + "/responses" payloadOpts := opts @@ -215,6 +214,7 @@ func (e *CodexExecutor) executeOpenAIImageStream(ctx context.Context, auth *clip if errCache != nil { return nil, errCache } + reporter.SetTranslatedReasoningEffort(body, "codex") applyCodexHeaders(httpReq, auth, apiKey, true, e.cfg, opts.Headers) applyModelHeaderOverrides(httpReq.Header, mainModel) recordCodexOpenAIImageRequest(ctx, e.cfg, e.Identifier(), auth, url, httpReq.Header.Clone(), body) From ba1bbd75d881501ced1e9cd4e250873b52d44a37 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Mon, 5 Oct 2026 18:00:44 +0800 Subject: [PATCH 058/142] fix(gemini): support document blocks in Claude request translation - Support base64 `document` content blocks alongside `image` blocks when converting Claude requests to Gemini inline data - Avoid creating empty contents turns when all message parts are filtered or unsupported Closes: #5960 --- .../gemini/claude/gemini_claude_request.go | 6 +- .../claude/gemini_claude_request_test.go | 120 ++++++++++++++++++ 2 files changed, 124 insertions(+), 2 deletions(-) diff --git a/internal/translator/gemini/claude/gemini_claude_request.go b/internal/translator/gemini/claude/gemini_claude_request.go index 2beb9a07c3e..ed1a2c40de7 100644 --- a/internal/translator/gemini/claude/gemini_claude_request.go +++ b/internal/translator/gemini/claude/gemini_claude_request.go @@ -188,7 +188,7 @@ func convertClaudeRequestToGemini(modelName string, inputRawJSON []byte, _ bool, partItems = append(partItems, imagePart) } - case "image": + case "image", "document": source := contentResult.Get("source") if source.Get("type").String() != "base64" { return true @@ -208,7 +208,9 @@ func convertClaudeRequestToGemini(modelName string, inputRawJSON []byte, _ bool, if role == "user" { partItems = translatorcommon.ReorderGeminiUserParts(partItems) } - contentItems = append(contentItems, geminiContentWithParts(role, partItems)) + if len(partItems) > 0 { + contentItems = append(contentItems, geminiContentWithParts(role, partItems)) + } } else if contentsResult.Type == gjson.String { part := []byte(`{"text":""}`) part, _ = sjson.SetBytes(part, "text", contentsResult.String()) diff --git a/internal/translator/gemini/claude/gemini_claude_request_test.go b/internal/translator/gemini/claude/gemini_claude_request_test.go index db9eac03f35..269617ff635 100644 --- a/internal/translator/gemini/claude/gemini_claude_request_test.go +++ b/internal/translator/gemini/claude/gemini_claude_request_test.go @@ -706,3 +706,123 @@ func TestConvertClaudeRequestToGemini_FunctionResponseJSONRef(t *testing.T) { t.Fatalf("expected result to contain ref target, got %q", result.String()) } } + +func TestConvertClaudeRequestToGemini_Issue5960_DocumentPreservation(t *testing.T) { + // Case 1: basic user document with base64 PDF + pdfInput := []byte(`{ + "model": "gemini-2.5-pro", + "messages": [ + { + "role": "user", + "content": [ + { + "type": "document", + "source": { + "type": "base64", + "media_type": "application/pdf", + "data": "JVBERi0xLjQK" + } + } + ] + } + ] + }`) + pdfOut := ConvertClaudeRequestToGemini("gemini-2.5-pro", pdfInput, false) + pdfParts := gjson.GetBytes(pdfOut, "contents.0.parts").Array() + if len(pdfParts) == 0 { + t.Fatalf("expected non-empty parts for base64 document, got: %s", string(pdfOut)) + } + if gotMime := gjson.GetBytes(pdfOut, "contents.0.parts.0.inline_data.mime_type").String(); gotMime != "application/pdf" { + t.Fatalf("expected inline_data.mime_type application/pdf, got %q (output: %s)", gotMime, string(pdfOut)) + } + if gotData := gjson.GetBytes(pdfOut, "contents.0.parts.0.inline_data.data").String(); gotData != "JVBERi0xLjQK" { + t.Fatalf("expected inline_data.data JVBERi0xLjQK, got %q (output: %s)", gotData, string(pdfOut)) + } + + // Mixed text and PDF document preserves both in order + mixedInput := []byte(`{ + "model": "gemini-2.5-pro", + "messages": [ + { + "role": "user", + "content": [ + {"type": "text", "text": "Please summarize this document:"}, + { + "type": "document", + "source": { + "type": "base64", + "media_type": "application/pdf", + "data": "JVBERi0xLjQK" + } + } + ] + } + ] + }`) + mixedOut := ConvertClaudeRequestToGemini("gemini-2.5-pro", mixedInput, false) + mixedParts := gjson.GetBytes(mixedOut, "contents.0.parts").Array() + if len(mixedParts) != 2 { + t.Fatalf("expected 2 parts for mixed text + document, got %d (output: %s)", len(mixedParts), string(mixedOut)) + } + if mixedParts[0].Get("text").String() != "Please summarize this document:" { + t.Fatalf("expected first part to be text, got %s", mixedParts[0].Raw) + } + if mixedParts[1].Get("inline_data.mime_type").String() != "application/pdf" { + t.Fatalf("expected second part to be inline_data PDF, got %s", mixedParts[1].Raw) + } + + // Multiple PDFs interleaved with text + interleavedInput := []byte(`{ + "model": "gemini-2.5-pro", + "messages": [ + { + "role": "user", + "content": [ + { + "type": "document", + "source": { + "type": "base64", + "media_type": "application/pdf", + "data": "PDF_ONE" + } + }, + {"type": "text", "text": "compare with"}, + { + "type": "document", + "source": { + "type": "base64", + "media_type": "application/pdf", + "data": "PDF_TWO" + } + } + ] + } + ] + }`) + interleavedOut := ConvertClaudeRequestToGemini("gemini-2.5-pro", interleavedInput, false) + interleavedParts := gjson.GetBytes(interleavedOut, "contents.0.parts").Array() + if len(interleavedParts) != 3 { + t.Fatalf("expected 3 parts for interleaved documents, got %d (output: %s)", len(interleavedParts), string(interleavedOut)) + } + if interleavedParts[0].Get("inline_data.data").String() != "PDF_ONE" || interleavedParts[2].Get("inline_data.data").String() != "PDF_TWO" { + t.Fatalf("expected PDF data to be preserved in order, got: %s", string(interleavedOut)) + } + + // Prevent empty turn when all content parts are skipped/unsupported + unsupportedInput := []byte(`{ + "model": "gemini-2.5-pro", + "messages": [ + { + "role": "user", + "content": [ + {"type": "unsupported_unknown_block", "foo": "bar"} + ] + } + ] + }`) + unsupportedOut := ConvertClaudeRequestToGemini("gemini-2.5-pro", unsupportedInput, false) + contents := gjson.GetBytes(unsupportedOut, "contents").Array() + if len(contents) != 0 { + t.Fatalf("expected 0 contents turns instead of empty parts turn, got: %s", string(unsupportedOut)) + } +} From e1e3a811b84eff1cec8aff0190015139e63e7449 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Mon, 5 Oct 2026 23:10:26 +0800 Subject: [PATCH 059/142] fix(gemini): enforce object type on schema nodes with properties - Ensure schema nodes defining `properties` explicitly set `type` to `object` - Prefer `object` type when resolving multi-type unions on nodes declaring `properties` Closes: #6394 --- internal/util/gemini_schema.go | 36 ++++++++++++++++ internal/util/gemini_schema_test.go | 67 +++++++++++++++++++++++++++++ 2 files changed, 103 insertions(+) diff --git a/internal/util/gemini_schema.go b/internal/util/gemini_schema.go index c21fb596ae8..bd4dae893a1 100644 --- a/internal/util/gemini_schema.go +++ b/internal/util/gemini_schema.go @@ -153,6 +153,7 @@ func cleanJSONSchema(jsonStr string, options jsonSchemaCleanOptions) string { } jsonStr = cleanupRequiredFields(jsonStr) jsonStr = sanitizeArrayItems(jsonStr) + jsonStr = sanitizeObjectProperties(jsonStr) // Phase 4: Add placeholder for empty object schemas (Claude VALIDATED mode requirement) if options.addPlaceholder { jsonStr = addEmptySchemaPlaceholder(jsonStr) @@ -161,6 +162,31 @@ func cleanJSONSchema(jsonStr string, options jsonSchemaCleanOptions) string { return jsonStr } +// sanitizeObjectProperties ensures that any schema node declaring "properties" has "type": "object". +// Gemini's protobuf validator enforces a strict field predicate on properties and required ($type == Type.OBJECT); +// if type is missing or not object, it is normalized to object so nested properties and required fields remain valid. +func sanitizeObjectProperties(jsonStr string) string { + paths := findPaths(jsonStr, "properties") + sortByDepth(paths) + for _, p := range paths { + parentPath := trimSuffix(p, ".properties") + if isPropertyDefinition(parentPath) { + continue + } + props := gjson.Get(jsonStr, p) + if !props.IsObject() { + continue + } + typePath := joinPath(parentPath, "type") + t := gjson.Get(jsonStr, typePath).String() + if !strings.EqualFold(t, "object") { + updated, _ := sjson.SetBytes([]byte(jsonStr), typePath, "object") + jsonStr = string(updated) + } + } + return jsonStr +} + // sanitizeArrayItems ensures that any schema node declaring "items" has "type": "array". // Gemini's protobuf validator enforces a strict field predicate on items ($type == Type.ARRAY); // if type is missing, it is inferred as array; if type is explicitly a non-array, items is removed. @@ -470,6 +496,10 @@ func repairSchemaNode(node map[string]any, addMissingArrayItems bool) (map[strin // 2. If node has a "properties" map, recursively repair all properties inside it if propsVal, ok := clone["properties"].(map[string]any); ok { + if _, hasType := clone["type"]; !hasType { + clone["type"] = "object" + modified = true + } repairedProps, promotedReqs, propsMod := repairPropertyMap(propsVal, addMissingArrayItems) if propsMod { clone["properties"] = repairedProps @@ -1131,6 +1161,10 @@ func flattenAnyOfOneOf(jsonStr string) string { updated, _ := sjson.SetBytes([]byte(jsonStr), joinPath(parentPath, "nullable"), true) jsonStr = string(updated) } + if parent.Get("type").String() == "" { + updated, _ := sjson.SetBytes([]byte(jsonStr), joinPath(parentPath, "type"), "object") + jsonStr = string(updated) + } jsonStr, _ = sjson.Delete(jsonStr, p) continue } @@ -1223,6 +1257,8 @@ func flattenTypeArrays(jsonStr string, preserveNativeNullable bool) string { if len(nonNullTypes) > 0 { if gjson.Get(jsonStr, joinPath(parentPath, "items")).Exists() && contains(nonNullTypes, "array") { firstType = "array" + } else if gjson.Get(jsonStr, joinPath(parentPath, "properties")).Exists() && contains(nonNullTypes, "object") { + firstType = "object" } else { firstType = nonNullTypes[0] } diff --git a/internal/util/gemini_schema_test.go b/internal/util/gemini_schema_test.go index 2bb00d6f3fd..f31410813c9 100644 --- a/internal/util/gemini_schema_test.go +++ b/internal/util/gemini_schema_test.go @@ -2972,3 +2972,70 @@ func TestSanitizeArrayItems_PreservesItemsForUppercaseArrayType(t *testing.T) { }) } } + +// TestCleanJSONSchema_EnforcesObjectTypeForProperties_Issue6394 tests issue 6394: +// When a property defines nested properties/required (e.g. through a union type like ["string", "object"], +// merged anyOf branches, or missing type), Gemini requires type to be OBJECT. +// Properties or required must never be emitted on a non-OBJECT type node. +func TestCleanJSONSchema_EnforcesObjectTypeForProperties_Issue6394(t *testing.T) { + cleaners := map[string]func(string) string{ + "Gemini": CleanJSONSchemaForGemini, + "GeminiJSONSchema": CleanJSONSchemaForGeminiJSONSchema, + "AntigravityTool": func(s string) string { return CleanJSONSchemaForAntigravityTool(s, false) }, + "AntigravityResponse": CleanJSONSchemaForAntigravityResponse, + } + + t.Run("TypeArrayWithPropertiesPrefersObject", func(t *testing.T) { + input := `{"type":"object","properties":{"requestBody":{"type":"object","properties":{"delivery":{"type":"object","properties":{"endpoint":{"type":["string","object"],"properties":{"traces":{"type":"string"}},"required":["traces"]}},"required":["endpoint"]}},"required":["delivery"]}},"required":["requestBody"]}` + + for name, clean := range cleaners { + t.Run(name, func(t *testing.T) { + got := clean(input) + parsed := gjson.Parse(got) + + endpointType := parsed.Get("properties.requestBody.properties.delivery.properties.endpoint.type").String() + if !strings.EqualFold(endpointType, "object") { + t.Fatalf("[%s] endpoint type = %q, want object; cleaned: %s", name, endpointType, got) + } + if !parsed.Get("properties.requestBody.properties.delivery.properties.endpoint.properties.traces").Exists() { + t.Fatalf("[%s] endpoint.properties.traces missing; cleaned: %s", name, got) + } + }) + } + }) + + t.Run("AnyOfUnionMergedIntoNodeWithoutTypeEnsuresObject", func(t *testing.T) { + input := `{"type":"object","properties":{"endpoint":{"properties":{"traces":{"type":"string"}},"required":["traces"],"anyOf":[{"type":"string"},{"type":"object","properties":{"other":{"type":"string"}}}]}}}` + + for name, clean := range cleaners { + t.Run(name, func(t *testing.T) { + got := clean(input) + parsed := gjson.Parse(got) + + endpointType := parsed.Get("properties.endpoint.type").String() + if !strings.EqualFold(endpointType, "object") { + t.Fatalf("[%s] endpoint type = %q, want object; cleaned: %s", name, endpointType, got) + } + if !parsed.Get("properties.endpoint.properties.traces").Exists() { + t.Fatalf("[%s] endpoint.properties.traces missing; cleaned: %s", name, got) + } + }) + } + }) + + t.Run("PrimitiveTypeWithPropertiesPromotedToObject", func(t *testing.T) { + input := `{"type":"object","properties":{"endpoint":{"type":"string","properties":{"traces":{"type":"string"}},"required":["traces"]}}}` + + for name, clean := range cleaners { + t.Run(name, func(t *testing.T) { + got := clean(input) + parsed := gjson.Parse(got) + + endpointType := parsed.Get("properties.endpoint.type").String() + if !strings.EqualFold(endpointType, "object") { + t.Fatalf("[%s] endpoint type = %q, want object; cleaned: %s", name, endpointType, got) + } + }) + } + }) +} From d2597a24e4b16957b619fb26ed51701409656711 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Tue, 6 Oct 2026 05:07:50 +0800 Subject: [PATCH 060/142] fix(openai): preserve unknown encrypted content in responses compat mode - Retain unknown-format `encrypted_content` during reasoning signature sanitization when compatibility mode is enabled - Continue stripping empty signatures and known foreign provider signatures in compat mode Closes: #6399 --- .../executor/openai_responses_signature.go | 6 +++++- .../openai_responses_signature_test.go | 21 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/internal/runtime/executor/openai_responses_signature.go b/internal/runtime/executor/openai_responses_signature.go index fa7d6a24c21..80b8dec295e 100644 --- a/internal/runtime/executor/openai_responses_signature.go +++ b/internal/runtime/executor/openai_responses_signature.go @@ -168,7 +168,11 @@ func sanitizeOpenAIResponsesReasoningEncryptedContentWithCompat(ctx context.Cont if rawSignature != strings.TrimSpace(rawSignature) { reason = "encrypted_content has leading or trailing whitespace" } else if _, err := signature.InspectGPTReasoningSignature(rawSignature); err != nil { - reason = err.Error() + // When isCompat is true, third-party Responses models (such as Muse) + // expect their own unknown-format encrypted_content to be replayed. + if !isCompat || rawSignature == "" || signature.DetectSignatureProvider(rawSignature) != signature.SignatureProviderUnknown { + reason = err.Error() + } } case gjson.Null: reason = "encrypted_content is null" diff --git a/internal/runtime/executor/openai_responses_signature_test.go b/internal/runtime/executor/openai_responses_signature_test.go index c63154d0877..ae9914634cc 100644 --- a/internal/runtime/executor/openai_responses_signature_test.go +++ b/internal/runtime/executor/openai_responses_signature_test.go @@ -194,6 +194,27 @@ func TestSanitizeOpenAIResponsesReasoningEncryptedContentWithCompat_PreservesRea } } +func TestSanitizeOpenAIResponsesReasoningEncryptedContentWithCompat_PreservesUnknownFormatEncryptedContent(t *testing.T) { + const unknownSig = "opaque-encrypted-reasoning-token-xyz" + body := []byte(`{"store":false,"input":[{"type":"reasoning","summary":[],"content":null,"encrypted_content":"` + unknownSig + `"},{"type":"reasoning","summary":[],"content":null,"encrypted_content":""},{"type":"reasoning","summary":[],"content":null,"encrypted_content":"` + testClaudeCAISSample + `"}]}`) + + got := sanitizeOpenAIResponsesReasoningEncryptedContentWithCompat(context.Background(), "test", body, true) + if gotSig := gjson.GetBytes(got, "input.0.encrypted_content").String(); gotSig != unknownSig { + t.Fatalf("compat encrypted_content = %q, want %q; body=%s", gotSig, unknownSig, got) + } + if gjson.GetBytes(got, "input.1.encrypted_content").Exists() { + t.Fatalf("empty encrypted_content should still be stripped: %s", got) + } + if gjson.GetBytes(got, "input.2.encrypted_content").Exists() { + t.Fatalf("Claude signature should still be stripped: %s", got) + } + + got = sanitizeOpenAIResponsesReasoningEncryptedContent(context.Background(), "test", body) + if gjson.GetBytes(got, "input.0.encrypted_content").Exists() { + t.Fatalf("non-compat sanitization unexpectedly preserved unknown-format encrypted_content: %s", got) + } +} + func BenchmarkSanitizeOpenAIResponsesReasoningEncryptedContentLargeNoopPayload(b *testing.B) { body := []byte(`{"store":false,"input":[{"type":"message","role":"user","content":"` + strings.Repeat("x", 8<<20) + `"}]}`) b.ReportAllocs() From d2e3a77ef16d2bab8b213d1a6d851eea8ef276cc Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Tue, 6 Oct 2026 05:28:12 +0800 Subject: [PATCH 061/142] docs(readme): add japanese translation for panel4cliproxyapi --- README_JA.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README_JA.md b/README_JA.md index 16b44c21cd7..dcfb015ab4e 100644 --- a/README_JA.md +++ b/README_JA.md @@ -291,6 +291,10 @@ Claude Code のステータスライン。現在の CPA インスタンスに対 CLIProxyAPI 向けのクロスプラットフォームな Electron トレイダッシュボード。ChatGPT/Codex、Claude、Gemini/Antigravity、Grok、Kimi、Cursor の各アカウントにおける実際の OAuth クォータウィンドウを表示し、利用キューコストを試算し、OpenAI/Claude のサービスステータスを追跡します。ダークなターミナル風 UI。Windows および Linux で動作します。 +### [panel4cliproxyapi](https://github.com/yaanlaan/panel4cliproxyapi) + +React と Tailwind CSS で構築された、CLIProxyAPI 向けのモダンでレスポンシブな Web ダッシュボードおよび管理コンソール。LAN リダイレクト支援付きの複数プロバイダー対応 OAuth ログイン、YAML 不要の直感的なビジュアル設定、リアルタイムのトラフィック分析チャート、クライアント API キー管理、コアのバージョン確認とホットリロード、およびライブ SSE ストリーミングのプレイグラウンドを備えています。 + > [!NOTE] > CLIProxyAPIをベースにプロジェクトを開発した場合は、PRを送ってこのリストに追加してください。 From a2976eb8a303f11b4ea5177bce9f9ff752634dfc Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Tue, 6 Oct 2026 05:45:17 +0800 Subject: [PATCH 062/142] fix(claude): share OAuth tool alias store across scoped executor copies - Pre-allocate `oauthToolAliases` in Claude and Kimi executor constructors so request copies created via `ForAPIKey` reuse the same store - Replace struct-level mutex with package-level mutex for lazy store allocation to prevent copying mutexes by value Closes: #6401 --- internal/runtime/executor/claude_executor.go | 10 ++-- .../claude_executor_tool_alias_scope_test.go | 51 +++++++++++++++++++ .../executor/claude_executor_tool_state.go | 9 +++- internal/runtime/executor/kimi_executor.go | 1 + 4 files changed, 65 insertions(+), 6 deletions(-) create mode 100644 internal/runtime/executor/claude_executor_tool_alias_scope_test.go diff --git a/internal/runtime/executor/claude_executor.go b/internal/runtime/executor/claude_executor.go index 5c6562e7716..7cb1f5b9f87 100644 --- a/internal/runtime/executor/claude_executor.go +++ b/internal/runtime/executor/claude_executor.go @@ -7,7 +7,6 @@ import ( "fmt" "net/http" "strings" - "sync" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps" @@ -27,8 +26,9 @@ type ClaudeExecutor struct { requestLogProvider string upstreamModelNormalizer func(string) string oauthProfileFetcher claudeOAuthProfileFetcher - oauthToolAliasStoreMu sync.Mutex - oauthToolAliases *claudeOAuthToolAliasStore + // oauthToolAliases is shared by every ForAPIKey copy of this executor; + // constructors allocate it so copies made per request reuse one store. + oauthToolAliases *claudeOAuthToolAliasStore } type claudeOAuthCancellationError struct { @@ -140,7 +140,9 @@ func logClaudeSignatureSanitizeReport(ctx context.Context, baseModel string, rep // omit max_tokens. Prefer registered model metadata before using a fallback. const defaultModelMaxTokens = 1024 -func NewClaudeExecutor(cfg *config.Config) *ClaudeExecutor { return &ClaudeExecutor{cfg: cfg} } +func NewClaudeExecutor(cfg *config.Config) *ClaudeExecutor { + return &ClaudeExecutor{cfg: cfg, oauthToolAliases: &claudeOAuthToolAliasStore{}} +} func (e *ClaudeExecutor) Identifier() string { return "claude" } diff --git a/internal/runtime/executor/claude_executor_tool_alias_scope_test.go b/internal/runtime/executor/claude_executor_tool_alias_scope_test.go new file mode 100644 index 00000000000..e157ba7517f --- /dev/null +++ b/internal/runtime/executor/claude_executor_tool_alias_scope_test.go @@ -0,0 +1,51 @@ +package executor + +import ( + "testing" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" +) + +// API key credentials are scoped per request with ForAPIKey, which copies the +// executor by value (see executorForAuth in sdk/cliproxy/auth). Thread +// continuation aliases saved by one request must be visible to the next one, +// so every scoped copy has to share one alias store. +func TestClaudeOAuthToolAliasStoreIsSharedAcrossForAPIKeyCopies(t *testing.T) { + createBody := []byte(`{"thread":{"type":"create"}}`) + continuationBody := []byte(`{"thread":{"type":"continue","previous_message_id":"msg-shared"}}`) + cases := map[string]cliproxyauth.APIKeyConfigExecutor{ + "claude": NewClaudeExecutor(&config.Config{}), + "kimi": NewKimiExecutor(&config.Config{}), + } + for name, registered := range cases { + t.Run(name, func(t *testing.T) { + first := claudeExecutorForAliasTest(t, registered.ForAPIKey()) + second := claudeExecutorForAliasTest(t, registered.ForAPIKey()) + if first == second { + t.Fatal("ForAPIKey returned the same executor; test needs two scoped copies") + } + first.rememberClaudeOAuthToolAliases(createBody, map[string]string{"alias": "Read"}, "msg-shared") + _, aliases, err := second.prepareClaudeOAuthToolNamesForRequest(continuationBody, claudeMCPAliasOptions{secret: "shared-store"}) + if err != nil { + t.Fatalf("continuation on another scoped copy: %v", err) + } + if aliases["alias"] != "Read" { + t.Fatalf("aliases = %#v, want alias -> Read", aliases) + } + }) + } +} + +func claudeExecutorForAliasTest(t *testing.T, scoped cliproxyauth.ProviderExecutor) *ClaudeExecutor { + t.Helper() + switch executor := scoped.(type) { + case *ClaudeExecutor: + return executor + case *KimiExecutor: + return &executor.ClaudeExecutor + default: + t.Fatalf("unexpected scoped executor %T", scoped) + return nil + } +} diff --git a/internal/runtime/executor/claude_executor_tool_state.go b/internal/runtime/executor/claude_executor_tool_state.go index c36f615a50b..9785d7bc308 100644 --- a/internal/runtime/executor/claude_executor_tool_state.go +++ b/internal/runtime/executor/claude_executor_tool_state.go @@ -10,6 +10,11 @@ import ( const claudeOAuthToolAliasStateLimit = 1024 +// claudeOAuthToolAliasStoreInitMu guards lazy allocation for executors built +// without a constructor. It lives outside ClaudeExecutor because ForAPIKey +// copies the executor by value, and a mutex field would be copied with it. +var claudeOAuthToolAliasStoreInitMu sync.Mutex + type claudeOAuthToolAliasStore struct { mu sync.Mutex entries map[string]map[string]string @@ -69,8 +74,8 @@ func cloneClaudeOAuthToolAliasMap(source map[string]string) map[string]string { } func (e *ClaudeExecutor) claudeOAuthToolAliasStore() *claudeOAuthToolAliasStore { - e.oauthToolAliasStoreMu.Lock() - defer e.oauthToolAliasStoreMu.Unlock() + claudeOAuthToolAliasStoreInitMu.Lock() + defer claudeOAuthToolAliasStoreInitMu.Unlock() if e.oauthToolAliases == nil { e.oauthToolAliases = &claudeOAuthToolAliasStore{} } diff --git a/internal/runtime/executor/kimi_executor.go b/internal/runtime/executor/kimi_executor.go index 126e1e81249..05e2408c27c 100644 --- a/internal/runtime/executor/kimi_executor.go +++ b/internal/runtime/executor/kimi_executor.go @@ -42,6 +42,7 @@ func NewKimiExecutor(cfg *config.Config) *KimiExecutor { cfg: cfg, requestLogProvider: "kimi", upstreamModelNormalizer: normalizeKimiUpstreamModel, + oauthToolAliases: &claudeOAuthToolAliasStore{}, }, cfg: cfg, } From d510dccf1b0be049ace849a8eda40ed67982fbba Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Tue, 6 Oct 2026 11:44:23 +0800 Subject: [PATCH 063/142] fix(gemini): support camelCase systemInstruction in request translation - Support `systemInstruction` field alongside `system_instruction` when converting Gemini requests to Claude format Closes: #6407 --- .../claude/gemini/claude_gemini_request.go | 6 +++++- .../gemini/claude_gemini_request_test.go | 18 ++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/internal/translator/claude/gemini/claude_gemini_request.go b/internal/translator/claude/gemini/claude_gemini_request.go index 69701c60620..9c04b4dd7ed 100644 --- a/internal/translator/claude/gemini/claude_gemini_request.go +++ b/internal/translator/claude/gemini/claude_gemini_request.go @@ -189,7 +189,11 @@ func ConvertGeminiRequestToClaude(modelName string, inputRawJSON []byte, stream } // System instruction conversion to Claude Code format - if sysInstr := root.Get("system_instruction"); sysInstr.Exists() { + sysInstr := root.Get("systemInstruction") + if !sysInstr.Exists() { + sysInstr = root.Get("system_instruction") + } + if sysInstr.Exists() { if parts := sysInstr.Get("parts"); parts.Exists() && parts.IsArray() { var systemText strings.Builder parts.ForEach(func(_, part gjson.Result) bool { diff --git a/internal/translator/claude/gemini/claude_gemini_request_test.go b/internal/translator/claude/gemini/claude_gemini_request_test.go index e5ccc70a784..191ded3ce6e 100644 --- a/internal/translator/claude/gemini/claude_gemini_request_test.go +++ b/internal/translator/claude/gemini/claude_gemini_request_test.go @@ -139,6 +139,24 @@ func TestConvertGeminiRequestToClaude_KeepsSystemInstructionUserSeparate(t *test } } +func TestConvertGeminiRequestToClaude_SupportsCamelCaseSystemInstruction(t *testing.T) { + raw := []byte(`{ + "systemInstruction":{"parts":[{"text":"system rule in camelCase"}]}, + "contents":[{"role":"user","parts":[{"text":"question"}]}] + }`) + out := ConvertGeminiRequestToClaude("claude-test", raw, false) + messages := gjson.GetBytes(out, "messages").Array() + if len(messages) != 2 { + t.Fatalf("message count = %d, want 2. Output: %s", len(messages), string(out)) + } + if got := messages[0].Get("content.0.text").String(); got != "system rule in camelCase" { + t.Fatalf("system user text = %q, want system rule in camelCase", got) + } + if got := messages[1].Get("content.0.text").String(); got != "question" { + t.Fatalf("ordinary user text = %q, want question", got) + } +} + func TestConvertGeminiRequestToClaude_DropsTemperature(t *testing.T) { raw := []byte(`{ "generationConfig": { From a0d31924e05c718ed0aadbb12aec9a4dba997591 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Tue, 6 Oct 2026 15:14:04 +0800 Subject: [PATCH 064/142] fix(gemini): map refusal finish reasons and handle partless stream completion in Claude response translation - Map Gemini safety, recitation, and malformed function call finish reasons to Claude `refusal` stop reason across streaming and non-streaming responses - Ensure `content_block` and `message_delta` events are properly emitted on partless stream completions and `[DONE]` signals Closes: #6408 --- .../gemini/claude/gemini_claude_response.go | 128 ++++++++---- .../claude/gemini_claude_response_test.go | 189 ++++++++++++++++++ 2 files changed, 276 insertions(+), 41 deletions(-) diff --git a/internal/translator/gemini/claude/gemini_claude_response.go b/internal/translator/gemini/claude/gemini_claude_response.go index 2d0c870f92a..8e812fd0a23 100644 --- a/internal/translator/gemini/claude/gemini_claude_response.go +++ b/internal/translator/gemini/claude/gemini_claude_response.go @@ -30,6 +30,26 @@ type Params struct { SanitizedNameMap map[string]string SawToolCall bool HasFinalEvents bool + FinishReason string + InputTokens int64 + OutputTokens int64 + CachedTokens int64 +} + +func resolveGeminiClaudeStopReason(finishReason string, sawToolCall bool) string { + if sawToolCall { + return "tool_use" + } + switch finishReason { + case "MAX_TOKENS": + return "max_tokens" + case "SAFETY", "RECITATION", "PROHIBITED_CONTENT", "SPII", "BLOCKLIST", "MALFORMED_FUNCTION_CALL", "IMAGE_SAFETY": + return "refusal" + case "STOP", "FINISH_REASON_UNSPECIFIED", "UNKNOWN", "": + return "end_turn" + default: + return "end_turn" + } } // toolUseIDCounter provides a process-wide unique counter for tool use identifiers. @@ -64,18 +84,40 @@ func ConvertGeminiResponseToClaude(_ context.Context, _ string, originalRequestR } } + output := make([]byte, 0, 1024) + appendEvent := func(event, payload string) { + output = translatorcommon.AppendSSEEventString(output, event, payload, 3) + } + p := (*param).(*Params) + if bytes.Equal(rawJSON, []byte("[DONE]")) { - // Only send message_stop if we have actually output content - if (*param).(*Params).HasContent { - return [][]byte{translatorcommon.AppendSSEEventString(nil, "message_stop", `{"type":"message_stop"}`, 3)} + if p.HasFirstResponse && !p.HasContent { + appendEvent("content_block_start", fmt.Sprintf(`{"type":"content_block_start","index":%d,"content_block":{"type":"text","text":""}}`, p.ResponseIndex)) + p.ResponseType = 1 + p.HasContent = true + } + if p.HasContent { + if p.ResponseType != 0 { + appendEvent("content_block_stop", fmt.Sprintf(`{"type":"content_block_stop","index":%d}`, p.ResponseIndex)) + p.ResponseType = 0 + } + if !p.HasFinalEvents { + stopReason := resolveGeminiClaudeStopReason(p.FinishReason, p.SawToolCall) + template := []byte(fmt.Sprintf(`{"type":"message_delta","delta":{"stop_reason":"%s","stop_sequence":null},"usage":{"input_tokens":0,"output_tokens":0}}`, stopReason)) + template, _ = sjson.SetBytes(template, "usage.output_tokens", p.OutputTokens) + template, _ = sjson.SetBytes(template, "usage.input_tokens", p.InputTokens) + if p.CachedTokens > 0 { + template, _ = sjson.SetBytes(template, "usage.cache_read_input_tokens", p.CachedTokens) + } + appendEvent("message_delta", string(template)) + p.HasFinalEvents = true + } + appendEvent("message_stop", `{"type":"message_stop"}`) + return [][]byte{output} } return [][]byte{} } - output := make([]byte, 0, 1024) - appendEvent := func(event, payload string) { - output = translatorcommon.AppendSSEEventString(output, event, payload, 3) - } appendSignatureDelta := func(signature string) { if signature == "" || (*param).(*Params).ResponseType != 2 { return @@ -246,33 +288,48 @@ func ConvertGeminiResponseToClaude(_ context.Context, _ string, originalRequestR } } + if finish := gjson.GetBytes(rawJSON, "candidates.0.finishReason"); finish.Exists() && finish.String() != "" { + (*param).(*Params).FinishReason = finish.String() + } + usageResult := gjson.GetBytes(rawJSON, "usageMetadata") + if usageResult.Exists() { + cachedTokens := usageResult.Get("cachedContentTokenCount").Int() + promptTokens := usageResult.Get("promptTokenCount").Int() - cachedTokens + if promptTokens < 0 { + promptTokens = 0 + } + outputTokens := usageResult.Get("candidatesTokenCount").Int() + usageResult.Get("thoughtsTokenCount").Int() + if outputTokens == 0 && usageResult.Get("totalTokenCount").Int() > 0 { + outputTokens = usageResult.Get("totalTokenCount").Int() - usageResult.Get("promptTokenCount").Int() + if outputTokens < 0 { + outputTokens = 0 + } + } + (*param).(*Params).InputTokens = promptTokens + (*param).(*Params).OutputTokens = outputTokens + (*param).(*Params).CachedTokens = cachedTokens + } + if usageResult.Exists() && bytes.Contains(rawJSON, []byte(`"finishReason"`)) && !(*param).(*Params).HasFinalEvents { - // Only send final events if we have actually output content + if !(*param).(*Params).HasContent && (*param).(*Params).HasFirstResponse { + appendEvent("content_block_start", fmt.Sprintf(`{"type":"content_block_start","index":%d,"content_block":{"type":"text","text":""}}`, (*param).(*Params).ResponseIndex)) + (*param).(*Params).ResponseType = 1 + (*param).(*Params).HasContent = true + } + if (*param).(*Params).HasContent { if (*param).(*Params).ResponseType != 0 { appendEvent("content_block_stop", fmt.Sprintf(`{"type":"content_block_stop","index":%d}`, (*param).(*Params).ResponseIndex)) (*param).(*Params).ResponseType = 0 } - template := []byte(`{"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"input_tokens":0,"output_tokens":0}}`) - if (*param).(*Params).SawToolCall { - template = []byte(`{"type":"message_delta","delta":{"stop_reason":"tool_use","stop_sequence":null},"usage":{"input_tokens":0,"output_tokens":0}}`) - } else if finish := gjson.GetBytes(rawJSON, "candidates.0.finishReason"); finish.Exists() && finish.String() == "MAX_TOKENS" { - template = []byte(`{"type":"message_delta","delta":{"stop_reason":"max_tokens","stop_sequence":null},"usage":{"input_tokens":0,"output_tokens":0}}`) - } - - thoughtsTokenCount := usageResult.Get("thoughtsTokenCount").Int() - candidatesTokenCount := usageResult.Get("candidatesTokenCount").Int() - cachedTokenCount := usageResult.Get("cachedContentTokenCount").Int() - promptTokenCount := usageResult.Get("promptTokenCount").Int() - cachedTokenCount - if promptTokenCount < 0 { - promptTokenCount = 0 - } - template, _ = sjson.SetBytes(template, "usage.output_tokens", candidatesTokenCount+thoughtsTokenCount) - template, _ = sjson.SetBytes(template, "usage.input_tokens", promptTokenCount) - if cachedTokenCount > 0 { - template, _ = sjson.SetBytes(template, "usage.cache_read_input_tokens", cachedTokenCount) + stopReason := resolveGeminiClaudeStopReason((*param).(*Params).FinishReason, (*param).(*Params).SawToolCall) + template := []byte(fmt.Sprintf(`{"type":"message_delta","delta":{"stop_reason":"%s","stop_sequence":null},"usage":{"input_tokens":0,"output_tokens":0}}`, stopReason)) + template, _ = sjson.SetBytes(template, "usage.output_tokens", (*param).(*Params).OutputTokens) + template, _ = sjson.SetBytes(template, "usage.input_tokens", (*param).(*Params).InputTokens) + if (*param).(*Params).CachedTokens > 0 { + template, _ = sjson.SetBytes(template, "usage.cache_read_input_tokens", (*param).(*Params).CachedTokens) } appendEvent("message_delta", string(template)) @@ -407,22 +464,11 @@ func ConvertGeminiResponseToClaudeNonStream(_ context.Context, _ string, origina out, _ = sjson.SetRawBytes(out, "content", translatorcommon.JoinRawArray(blocks)) } - stopReason := "end_turn" - if hasToolCall { - stopReason = "tool_use" - } else { - if finish := root.Get("candidates.0.finishReason"); finish.Exists() { - switch finish.String() { - case "MAX_TOKENS": - stopReason = "max_tokens" - case "STOP", "FINISH_REASON_UNSPECIFIED", "UNKNOWN": - stopReason = "end_turn" - default: - stopReason = "end_turn" - } - } + var finishReason string + if finish := root.Get("candidates.0.finishReason"); finish.Exists() { + finishReason = finish.String() } - out, _ = sjson.SetBytes(out, "stop_reason", stopReason) + out, _ = sjson.SetBytes(out, "stop_reason", resolveGeminiClaudeStopReason(finishReason, hasToolCall)) if inputTokens == int64(0) && outputTokens == int64(0) && !root.Get("usageMetadata").Exists() { out, _ = sjson.DeleteBytes(out, "usage") diff --git a/internal/translator/gemini/claude/gemini_claude_response_test.go b/internal/translator/gemini/claude/gemini_claude_response_test.go index 3d4d65a3d1f..6241d674621 100644 --- a/internal/translator/gemini/claude/gemini_claude_response_test.go +++ b/internal/translator/gemini/claude/gemini_claude_response_test.go @@ -290,3 +290,192 @@ func TestConvertGeminiResponseToClaudeNonStream_UsageWithCachedContentTokenCount t.Fatalf("expected usage.output_tokens = 7, got %d. Output: %s", outputTokens, string(output)) } } + +func TestConvertGeminiResponseToClaudeStream_PartlessSafetyClosesMessageWithRefusal(t *testing.T) { + requestJSON := []byte(`{"model":"claude-opus-5-5","messages":[{"role":"user","content":"hi"}]}`) + chunk := []byte(`{ + "candidates": [{ + "content": {"role": "model", "parts": []}, + "index": 0, + "finishReason": "SAFETY" + }], + "modelVersion": "m", + "usageMetadata": { + "promptTokenCount": 120, + "candidatesTokenCount": 37, + "totalTokenCount": 157 + } + }`) + + var param any + ctx := context.Background() + output := bytes.Join(ConvertGeminiResponseToClaude(ctx, "claude-opus-5-5", requestJSON, requestJSON, chunk, ¶m), nil) + output = append(output, bytes.Join(ConvertGeminiResponseToClaude(ctx, "claude-opus-5-5", requestJSON, requestJSON, []byte("[DONE]"), ¶m), nil)...) + outputText := string(output) + + lastIndex := -1 + for _, eventName := range []string{"message_start", "content_block_start", "content_block_stop", "message_delta", "message_stop"} { + index := strings.Index(outputText, "event: "+eventName+"\n") + if index < 0 { + t.Fatalf("event %q not found in output:\n%s", eventName, outputText) + } + if index <= lastIndex { + t.Fatalf("event %q is out of order in output:\n%s", eventName, outputText) + } + lastIndex = index + } + + var foundDelta bool + for _, line := range strings.Split(outputText, "\n") { + if strings.HasPrefix(line, "data: ") && strings.Contains(line, `"type":"message_delta"`) { + foundDelta = true + deltaJSON := gjson.Parse(strings.TrimPrefix(line, "data: ")) + if got := deltaJSON.Get("delta.stop_reason").String(); got != "refusal" { + t.Fatalf("stop_reason = %q, want refusal. Payload: %s", got, line) + } + if got := deltaJSON.Get("usage.input_tokens").Int(); got != 120 { + t.Fatalf("input_tokens = %d, want 120. Payload: %s", got, line) + } + if got := deltaJSON.Get("usage.output_tokens").Int(); got != 37 { + t.Fatalf("output_tokens = %d, want 37. Payload: %s", got, line) + } + } + } + if !foundDelta { + t.Fatalf("failed to find message_delta event in output:\n%s", outputText) + } +} + +func TestConvertGeminiResponseToClaudeStream_PartlessMalformedFunctionCallClosesMessage(t *testing.T) { + requestJSON := []byte(`{"model":"claude-opus-5-5","messages":[{"role":"user","content":"hi"}]}`) + chunk := []byte(`{ + "candidates": [{ + "content": {"role": "model", "parts": []}, + "index": 0, + "finishReason": "MALFORMED_FUNCTION_CALL" + }], + "modelVersion": "m", + "usageMetadata": { + "promptTokenCount": 50, + "candidatesTokenCount": 10, + "totalTokenCount": 60 + } + }`) + + var param any + ctx := context.Background() + output := bytes.Join(ConvertGeminiResponseToClaude(ctx, "claude-opus-5-5", requestJSON, requestJSON, chunk, ¶m), nil) + output = append(output, bytes.Join(ConvertGeminiResponseToClaude(ctx, "claude-opus-5-5", requestJSON, requestJSON, []byte("[DONE]"), ¶m), nil)...) + outputText := string(output) + + if !strings.Contains(outputText, `"type":"message_delta"`) { + t.Fatalf("expected message_delta in output:\n%s", outputText) + } + if !strings.Contains(outputText, `"type":"message_stop"`) { + t.Fatalf("expected message_stop in output:\n%s", outputText) + } + + var foundDelta bool + for _, line := range strings.Split(outputText, "\n") { + if strings.HasPrefix(line, "data: ") && strings.Contains(line, `"type":"message_delta"`) { + foundDelta = true + deltaJSON := gjson.Parse(strings.TrimPrefix(line, "data: ")) + if got := deltaJSON.Get("delta.stop_reason").String(); got != "refusal" { + t.Fatalf("stop_reason = %q, want refusal. Payload: %s", got, line) + } + } + } + if !foundDelta { + t.Fatalf("failed to find message_delta in output:\n%s", outputText) + } +} + +func TestConvertGeminiResponseToClaudeStream_PartlessStopClosesMessageWithEndTurn(t *testing.T) { + requestJSON := []byte(`{"model":"claude-opus-5-5","messages":[{"role":"user","content":"hi"}]}`) + chunk := []byte(`{ + "candidates": [{ + "content": {"role": "model", "parts": [{"text": ""}]}, + "index": 0, + "finishReason": "STOP" + }], + "modelVersion": "m", + "usageMetadata": { + "promptTokenCount": 80, + "candidatesTokenCount": 0, + "totalTokenCount": 80 + } + }`) + + var param any + ctx := context.Background() + output := bytes.Join(ConvertGeminiResponseToClaude(ctx, "claude-opus-5-5", requestJSON, requestJSON, chunk, ¶m), nil) + output = append(output, bytes.Join(ConvertGeminiResponseToClaude(ctx, "claude-opus-5-5", requestJSON, requestJSON, []byte("[DONE]"), ¶m), nil)...) + outputText := string(output) + + lastIndex := -1 + for _, eventName := range []string{"message_start", "content_block_start", "content_block_stop", "message_delta", "message_stop"} { + index := strings.Index(outputText, "event: "+eventName+"\n") + if index < 0 { + t.Fatalf("event %q not found in output:\n%s", eventName, outputText) + } + if index <= lastIndex { + t.Fatalf("event %q is out of order in output:\n%s", eventName, outputText) + } + lastIndex = index + } + + var foundDelta bool + for _, line := range strings.Split(outputText, "\n") { + if strings.HasPrefix(line, "data: ") && strings.Contains(line, `"type":"message_delta"`) { + foundDelta = true + deltaJSON := gjson.Parse(strings.TrimPrefix(line, "data: ")) + if got := deltaJSON.Get("delta.stop_reason").String(); got != "end_turn" { + t.Fatalf("stop_reason = %q, want end_turn. Payload: %s", got, line) + } + } + } + if !foundDelta { + t.Fatalf("failed to find message_delta in output:\n%s", outputText) + } +} + +func TestConvertGeminiResponseToClaudeNonStream_SafetyAndMalformedFunctionCallRefusal(t *testing.T) { + requestJSON := []byte(`{"model":"claude-opus-5-5","messages":[{"role":"user","content":"hi"}]}`) + testCases := []struct { + finishReason string + wantReason string + }{ + {finishReason: "SAFETY", wantReason: "refusal"}, + {finishReason: "MALFORMED_FUNCTION_CALL", wantReason: "refusal"}, + {finishReason: "RECITATION", wantReason: "refusal"}, + {finishReason: "PROHIBITED_CONTENT", wantReason: "refusal"}, + {finishReason: "SPII", wantReason: "refusal"}, + {finishReason: "BLOCKLIST", wantReason: "refusal"}, + {finishReason: "MAX_TOKENS", wantReason: "max_tokens"}, + {finishReason: "STOP", wantReason: "end_turn"}, + } + + ctx := context.Background() + for _, tc := range testCases { + t.Run(tc.finishReason, func(t *testing.T) { + rawJSON := []byte(`{ + "candidates": [{ + "content": {"role": "model", "parts": []}, + "finishReason": "` + tc.finishReason + `" + }], + "usageMetadata": { + "promptTokenCount": 120, + "candidatesTokenCount": 37, + "totalTokenCount": 157 + }, + "modelVersion": "m", + "responseId": "resp-test" + }`) + output := ConvertGeminiResponseToClaudeNonStream(ctx, "claude-opus-5-5", requestJSON, requestJSON, rawJSON, nil) + outputJSON := gjson.ParseBytes(output) + if got := outputJSON.Get("stop_reason").String(); got != tc.wantReason { + t.Fatalf("stop_reason = %q, want %q. Output: %s", got, tc.wantReason, string(output)) + } + }) + } +} From 68ea171da27654de4e0dc789652bad13d96d810d Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Tue, 6 Oct 2026 15:43:01 +0800 Subject: [PATCH 065/142] fix(gemini): handle carrier thinking blocks for signed visible text and tool calls in Claude response translation - Emit carrier thinking blocks for thought signatures accompanying visible text or tool calls in both streaming and non-streaming responses - Ensure thinking content and visible text are properly segregated without misclassifying regular output as reasoning Closes: #6409 --- .../gemini/claude/gemini_claude_response.go | 245 +++++++---- .../claude/gemini_claude_response_test.go | 388 +++++++++++++++++- 2 files changed, 541 insertions(+), 92 deletions(-) diff --git a/internal/translator/gemini/claude/gemini_claude_response.go b/internal/translator/gemini/claude/gemini_claude_response.go index 8e812fd0a23..8d52f9226f9 100644 --- a/internal/translator/gemini/claude/gemini_claude_response.go +++ b/internal/translator/gemini/claude/gemini_claude_response.go @@ -127,6 +127,25 @@ func ConvertGeminiResponseToClaude(_ context.Context, _ string, originalRequestR (*param).(*Params).HasContent = true } + appendCarrierThinkingBlock := func(signature string) { + if signature == "" { + return + } + p := (*param).(*Params) + if p.ResponseType != 0 { + appendEvent("content_block_stop", fmt.Sprintf(`{"type":"content_block_stop","index":%d}`, p.ResponseIndex)) + p.ResponseIndex++ + p.ResponseType = 0 + } + appendEvent("content_block_start", fmt.Sprintf(`{"type":"content_block_start","index":%d,"content_block":{"type":"thinking","thinking":""}}`, p.ResponseIndex)) + data, _ := sjson.SetBytes([]byte(fmt.Sprintf(`{"type":"content_block_delta","index":%d,"delta":{"type":"signature_delta","signature":""}}`, p.ResponseIndex)), "delta.signature", signature) + appendEvent("content_block_delta", string(data)) + appendEvent("content_block_stop", fmt.Sprintf(`{"type":"content_block_stop","index":%d}`, p.ResponseIndex)) + p.ResponseIndex++ + p.ResponseType = 0 + p.HasContent = true + } + // Initialize the streaming session with a message_start event // This is only sent for the very first response chunk if !(*param).(*Params).HasFirstResponse { @@ -161,118 +180,87 @@ func ConvertGeminiResponseToClaude(_ context.Context, _ string, originalRequestR if !thoughtSignatureResult.Exists() { thoughtSignatureResult = partResult.Get("thought_signature") } - hasThoughtSignature := thoughtSignatureResult.Exists() && thoughtSignatureResult.String() != "" + partSig := "" + if thoughtSignatureResult.Exists() && thoughtSignatureResult.String() != "" { + partSig = thoughtSignatureResult.String() + } + hasThoughtSignature := partSig != "" + isThought := partResult.Get("thought").Bool() - if hasThoughtSignature && !partTextResult.Exists() && !functionCallResult.Exists() { - appendSignatureDelta(thoughtSignatureResult.String()) + if hasThoughtSignature && (!partTextResult.Exists() || partTextResult.String() == "") && !functionCallResult.Exists() { + if (*param).(*Params).ResponseType == 2 { + appendSignatureDelta(partSig) + continue + } + appendCarrierThinkingBlock(partSig) continue } - // Handle text content (both regular content and thinking) - if partTextResult.Exists() { - // Process thinking content (internal reasoning) - if partResult.Get("thought").Bool() || hasThoughtSignature { - if hasThoughtSignature && partTextResult.String() == "" { - appendSignatureDelta(thoughtSignatureResult.String()) - continue - } - // Continue existing thinking block + if isThought { + if hasThoughtSignature && (!partTextResult.Exists() || partTextResult.String() == "") { if (*param).(*Params).ResponseType == 2 { - data, _ := sjson.SetBytes([]byte(fmt.Sprintf(`{"type":"content_block_delta","index":%d,"delta":{"type":"thinking_delta","thinking":""}}`, (*param).(*Params).ResponseIndex)), "delta.thinking", partTextResult.String()) - appendEvent("content_block_delta", string(data)) - (*param).(*Params).HasContent = true + appendSignatureDelta(partSig) } else { - // Transition from another state to thinking - // First, close any existing content block - if (*param).(*Params).ResponseType != 0 { - if (*param).(*Params).ResponseType == 2 { - // output = output + "event: content_block_delta\n" - // output = output + fmt.Sprintf(`data: {"type":"content_block_delta","index":%d,"delta":{"type":"signature_delta","signature":null}}`, (*param).(*Params).ResponseIndex) - // output = output + "\n\n\n" - } - appendEvent("content_block_stop", fmt.Sprintf(`{"type":"content_block_stop","index":%d}`, (*param).(*Params).ResponseIndex)) - (*param).(*Params).ResponseIndex++ - } - - // Start a new thinking content block - appendEvent("content_block_start", fmt.Sprintf(`{"type":"content_block_start","index":%d,"content_block":{"type":"thinking","thinking":""}}`, (*param).(*Params).ResponseIndex)) - data, _ := sjson.SetBytes([]byte(fmt.Sprintf(`{"type":"content_block_delta","index":%d,"delta":{"type":"thinking_delta","thinking":""}}`, (*param).(*Params).ResponseIndex)), "delta.thinking", partTextResult.String()) - appendEvent("content_block_delta", string(data)) - (*param).(*Params).ResponseType = 2 // Set state to thinking - (*param).(*Params).HasContent = true + appendCarrierThinkingBlock(partSig) } - appendSignatureDelta(thoughtSignatureResult.String()) + continue + } + + partText := partTextResult.String() + if (*param).(*Params).ResponseType == 2 { + data, _ := sjson.SetBytes([]byte(fmt.Sprintf(`{"type":"content_block_delta","index":%d,"delta":{"type":"thinking_delta","thinking":""}}`, (*param).(*Params).ResponseIndex)), "delta.thinking", partText) + appendEvent("content_block_delta", string(data)) + (*param).(*Params).HasContent = true } else { - // Process regular text content (user-visible output) - // Continue existing text block - if (*param).(*Params).ResponseType == 1 { - data, _ := sjson.SetBytes([]byte(fmt.Sprintf(`{"type":"content_block_delta","index":%d,"delta":{"type":"text_delta","text":""}}`, (*param).(*Params).ResponseIndex)), "delta.text", partTextResult.String()) - appendEvent("content_block_delta", string(data)) - (*param).(*Params).HasContent = true - } else { - // Transition from another state to text content - // First, close any existing content block - if (*param).(*Params).ResponseType != 0 { - if (*param).(*Params).ResponseType == 2 { - // output = output + "event: content_block_delta\n" - // output = output + fmt.Sprintf(`data: {"type":"content_block_delta","index":%d,"delta":{"type":"signature_delta","signature":null}}`, (*param).(*Params).ResponseIndex) - // output = output + "\n\n\n" - } - appendEvent("content_block_stop", fmt.Sprintf(`{"type":"content_block_stop","index":%d}`, (*param).(*Params).ResponseIndex)) - (*param).(*Params).ResponseIndex++ - } - - // Start a new text content block - appendEvent("content_block_start", fmt.Sprintf(`{"type":"content_block_start","index":%d,"content_block":{"type":"text","text":""}}`, (*param).(*Params).ResponseIndex)) - data, _ := sjson.SetBytes([]byte(fmt.Sprintf(`{"type":"content_block_delta","index":%d,"delta":{"type":"text_delta","text":""}}`, (*param).(*Params).ResponseIndex)), "delta.text", partTextResult.String()) - appendEvent("content_block_delta", string(data)) - (*param).(*Params).ResponseType = 1 // Set state to content - (*param).(*Params).HasContent = true + if (*param).(*Params).ResponseType != 0 { + appendEvent("content_block_stop", fmt.Sprintf(`{"type":"content_block_stop","index":%d}`, (*param).(*Params).ResponseIndex)) + (*param).(*Params).ResponseIndex++ } + + appendEvent("content_block_start", fmt.Sprintf(`{"type":"content_block_start","index":%d,"content_block":{"type":"thinking","thinking":""}}`, (*param).(*Params).ResponseIndex)) + data, _ := sjson.SetBytes([]byte(fmt.Sprintf(`{"type":"content_block_delta","index":%d,"delta":{"type":"thinking_delta","thinking":""}}`, (*param).(*Params).ResponseIndex)), "delta.thinking", partText) + appendEvent("content_block_delta", string(data)) + (*param).(*Params).ResponseType = 2 + (*param).(*Params).HasContent = true + } + if hasThoughtSignature { + appendSignatureDelta(partSig) } - } else if functionCallResult.Exists() { - // Handle function/tool calls from the AI model - // This processes tool usage requests and formats them for Claude API compatibility + continue + } + + // From here on, !isThought (visible text, functionCall, or standalone signature) + if functionCallResult.Exists() { (*param).(*Params).SawToolCall = true upstreamToolName := functionCallResult.Get("name").String() upstreamToolName = util.RestoreSanitizedToolName((*param).(*Params).SanitizedNameMap, upstreamToolName) clientToolName := util.MapToolName((*param).(*Params).ToolNameMap, upstreamToolName) - // FIX: Handle streaming split/delta where name might be empty in subsequent chunks. - // If we are already in tool use mode and name is empty, treat as continuation (delta). if (*param).(*Params).ResponseType == 3 && upstreamToolName == "" { if fcArgsResult := functionCallResult.Get("args"); fcArgsResult.Exists() { data, _ := sjson.SetBytes([]byte(fmt.Sprintf(`{"type":"content_block_delta","index":%d,"delta":{"type":"input_json_delta","partial_json":""}}`, (*param).(*Params).ResponseIndex)), "delta.partial_json", fcArgsResult.Raw) appendEvent("content_block_delta", string(data)) } - // Continue to next part without closing/opening logic + if hasThoughtSignature { + appendCarrierThinkingBlock(partSig) + } continue } - // Handle state transitions when switching to function calls - // Close any existing function call block first + if hasThoughtSignature { + appendCarrierThinkingBlock(partSig) + } + if (*param).(*Params).ResponseType == 3 { appendEvent("content_block_stop", fmt.Sprintf(`{"type":"content_block_stop","index":%d}`, (*param).(*Params).ResponseIndex)) (*param).(*Params).ResponseIndex++ (*param).(*Params).ResponseType = 0 } - - // Special handling for thinking state transition - if (*param).(*Params).ResponseType == 2 { - // output = output + "event: content_block_delta\n" - // output = output + fmt.Sprintf(`data: {"type":"content_block_delta","index":%d,"delta":{"type":"signature_delta","signature":null}}`, (*param).(*Params).ResponseIndex) - // output = output + "\n\n\n" - } - - // Close any other existing content block if (*param).(*Params).ResponseType != 0 { appendEvent("content_block_stop", fmt.Sprintf(`{"type":"content_block_stop","index":%d}`, (*param).(*Params).ResponseIndex)) (*param).(*Params).ResponseIndex++ } - // Start a new tool use content block - // This creates the structure for a function call in Claude format - // Create the tool use block with unique ID and function details data := []byte(fmt.Sprintf(`{"type":"content_block_start","index":%d,"content_block":{"type":"tool_use","id":"","name":"","input":{}}}`, (*param).(*Params).ResponseIndex)) data, _ = sjson.SetBytes(data, "content_block.id", util.SanitizeClaudeToolID(fmt.Sprintf("%s-%d", upstreamToolName, atomic.AddUint64(&toolUseIDCounter, 1)))) data, _ = sjson.SetBytes(data, "content_block.name", clientToolName) @@ -284,6 +272,43 @@ func ConvertGeminiResponseToClaude(_ context.Context, _ string, originalRequestR } (*param).(*Params).ResponseType = 3 (*param).(*Params).HasContent = true + continue + } + + if partTextResult.Exists() { + partText := partTextResult.String() + if hasThoughtSignature && partText == "" { + if (*param).(*Params).ResponseType == 2 { + appendSignatureDelta(partSig) + continue + } + appendCarrierThinkingBlock(partSig) + continue + } + if hasThoughtSignature { + appendCarrierThinkingBlock(partSig) + } + if (*param).(*Params).ResponseType == 1 { + data, _ := sjson.SetBytes([]byte(fmt.Sprintf(`{"type":"content_block_delta","index":%d,"delta":{"type":"text_delta","text":""}}`, (*param).(*Params).ResponseIndex)), "delta.text", partText) + appendEvent("content_block_delta", string(data)) + (*param).(*Params).HasContent = true + } else { + if (*param).(*Params).ResponseType != 0 { + appendEvent("content_block_stop", fmt.Sprintf(`{"type":"content_block_stop","index":%d}`, (*param).(*Params).ResponseIndex)) + (*param).(*Params).ResponseIndex++ + } + appendEvent("content_block_start", fmt.Sprintf(`{"type":"content_block_start","index":%d,"content_block":{"type":"text","text":""}}`, (*param).(*Params).ResponseIndex)) + data, _ := sjson.SetBytes([]byte(fmt.Sprintf(`{"type":"content_block_delta","index":%d,"delta":{"type":"text_delta","text":""}}`, (*param).(*Params).ResponseIndex)), "delta.text", partText) + appendEvent("content_block_delta", string(data)) + (*param).(*Params).ResponseType = 1 + (*param).(*Params).HasContent = true + } + continue + } + + if hasThoughtSignature { + appendCarrierThinkingBlock(partSig) + continue } } } @@ -405,38 +430,65 @@ func ConvertGeminiResponseToClaudeNonStream(_ context.Context, _ string, origina thinkingSignature = "" } + appendCarrierThinkingBlock := func(signature string) { + if signature == "" { + return + } + carrier := []byte(`{"type":"thinking","thinking":"","signature":""}`) + carrier, _ = sjson.SetBytes(carrier, "signature", signature) + blocks = append(blocks, carrier) + } + if parts.IsArray() { for _, part := range parts.Array() { thoughtSignatureResult := part.Get("thoughtSignature") if !thoughtSignatureResult.Exists() { thoughtSignatureResult = part.Get("thought_signature") } - hasThoughtSignature := thoughtSignatureResult.Exists() && thoughtSignatureResult.String() != "" - if hasThoughtSignature { - thinkingSignature = thoughtSignatureResult.String() + partSig := "" + if thoughtSignatureResult.Exists() && thoughtSignatureResult.String() != "" { + partSig = thoughtSignatureResult.String() } text := part.Get("text") functionCall := part.Get("functionCall") + isThought := part.Get("thought").Bool() - if hasThoughtSignature && (!text.Exists() || text.String() == "") && !functionCall.Exists() { + if isThought { + flushText() + if partSig != "" { + thinkingSignature = partSig + } + if text.Exists() && text.String() != "" { + thinkingBuilder.WriteString(text.String()) + } continue } - if text.Exists() && text.String() != "" { - if part.Get("thought").Bool() || hasThoughtSignature { + // If this is a part without visible text or function call, and thinking is in progress: + // this signature belongs to the thinking block! + if (!text.Exists() || text.String() == "") && !functionCall.Exists() { + if thinkingBuilder.Len() > 0 && partSig != "" { + thinkingSignature = partSig + continue + } + if partSig != "" { + flushThinking() flushText() - thinkingBuilder.WriteString(text.String()) + appendCarrierThinkingBlock(partSig) continue } - flushThinking() - textBuilder.WriteString(text.String()) continue } + // From here on, !isThought (visible text or functionCall) + flushThinking() + if functionCall.Exists() { - flushThinking() flushText() + if partSig != "" { + appendCarrierThinkingBlock(partSig) + } hasToolCall = true upstreamToolName := functionCall.Get("name").String() @@ -454,6 +506,21 @@ func ConvertGeminiResponseToClaudeNonStream(_ context.Context, _ string, origina blocks = append(blocks, toolBlock) continue } + + if text.Exists() && text.String() != "" { + if partSig != "" { + flushText() + appendCarrierThinkingBlock(partSig) + } + textBuilder.WriteString(text.String()) + continue + } + + if partSig != "" { + flushText() + appendCarrierThinkingBlock(partSig) + continue + } } } diff --git a/internal/translator/gemini/claude/gemini_claude_response_test.go b/internal/translator/gemini/claude/gemini_claude_response_test.go index 6241d674621..b729fe20081 100644 --- a/internal/translator/gemini/claude/gemini_claude_response_test.go +++ b/internal/translator/gemini/claude/gemini_claude_response_test.go @@ -143,15 +143,15 @@ func TestConvertGeminiResponseToClaudeNonStream_PartWithThoughtSignatureWithoutT if thinkingBlock.Get("type").String() != "thinking" { t.Fatalf("expected first block to be thinking, got %s", thinkingBlock.Get("type").String()) } - if thinkingBlock.Get("thinking").String() != "inferred reasoning" { - t.Fatalf("unexpected thinking content: %s", thinkingBlock.Get("thinking").String()) + if thinkingBlock.Get("thinking").String() != "" { + t.Fatalf("carrier thinking block must have empty thinking, got %q", thinkingBlock.Get("thinking").String()) } if thinkingBlock.Get("signature").String() != "sig-snake-case" { t.Fatalf("expected signature 'sig-snake-case', got %q. Output: %s", thinkingBlock.Get("signature").String(), string(output)) } textBlock := blocks[1] - if textBlock.Get("type").String() != "text" || textBlock.Get("text").String() != "final answer" { + if textBlock.Get("type").String() != "text" || textBlock.Get("text").String() != "inferred reasoningfinal answer" { t.Fatalf("unexpected text block: %s", textBlock.Raw) } } @@ -479,3 +479,385 @@ func TestConvertGeminiResponseToClaudeNonStream_SafetyAndMalformedFunctionCallRe }) } } + +func TestConvertGeminiResponseToClaudeNonStream_Issue6409_SignedVisibleText(t *testing.T) { + requestJSON := []byte(`{"model":"gemini-3.5-flash-lite","messages":[{"role":"user","content":"hi"}]}`) + geminiResponse := []byte(`{ + "candidates": [{ + "content": { + "parts": [ + {"text": "ok", "thoughtSignature": "EmAKXgFpFH0Tb/MkBw="} + ], + "role": "model" + }, + "finishReason": "STOP", + "index": 0 + }], + "usageMetadata": { + "promptTokenCount": 5, + "candidatesTokenCount": 1 + }, + "modelVersion": "gemini-3.5-flash-lite", + "responseId": "5Qm-as2qBuLI-sAP76KVkAk" + }`) + + ctx := context.Background() + output := ConvertGeminiResponseToClaudeNonStream(ctx, "gemini-3.5-flash-lite", requestJSON, requestJSON, geminiResponse, nil) + outputJSON := gjson.ParseBytes(output) + + blocks := outputJSON.Get("content").Array() + if len(blocks) != 2 { + t.Fatalf("expected 2 content blocks (carrier thinking + text), got %d: %s", len(blocks), string(output)) + } + + thinkingBlock := blocks[0] + if thinkingBlock.Get("type").String() != "thinking" { + t.Fatalf("expected block 0 to be thinking carrier, got %s", thinkingBlock.Get("type").String()) + } + if got := thinkingBlock.Get("thinking").String(); got != "" { + t.Fatalf("carrier thinking block must have empty thinking, got %q", got) + } + if got := thinkingBlock.Get("signature").String(); got != "EmAKXgFpFH0Tb/MkBw=" { + t.Fatalf("expected signature 'EmAKXgFpFH0Tb/MkBw=', got %q", got) + } + + textBlock := blocks[1] + if textBlock.Get("type").String() != "text" || textBlock.Get("text").String() != "ok" { + t.Fatalf("expected visible text block with 'ok', got: %s", textBlock.Raw) + } +} + +func TestConvertGeminiResponseToClaudeNonStream_Issue6409_ThinkingFollowedBySignedVisibleText(t *testing.T) { + requestJSON := []byte(`{"model":"gemini-3.5-flash-lite","messages":[{"role":"user","content":"hi"}]}`) + geminiResponse := []byte(`{ + "candidates": [{ + "content": { + "parts": [ + {"text": "reasoning step", "thought": true, "thoughtSignature": "sig-think"}, + {"text": "final answer", "thoughtSignature": "sig-visible"} + ], + "role": "model" + }, + "finishReason": "STOP" + }], + "modelVersion": "gemini-3.5-flash-lite", + "responseId": "resp-mixed" + }`) + + ctx := context.Background() + output := ConvertGeminiResponseToClaudeNonStream(ctx, "gemini-3.5-flash-lite", requestJSON, requestJSON, geminiResponse, nil) + outputJSON := gjson.ParseBytes(output) + + blocks := outputJSON.Get("content").Array() + if len(blocks) != 3 { + t.Fatalf("expected 3 blocks (thinking, carrier thinking, text), got %d: %s", len(blocks), string(output)) + } + + if blocks[0].Get("type").String() != "thinking" || blocks[0].Get("thinking").String() != "reasoning step" || blocks[0].Get("signature").String() != "sig-think" { + t.Fatalf("block 0 must be thinking with its own signature, got: %s", blocks[0].Raw) + } + if blocks[1].Get("type").String() != "thinking" || blocks[1].Get("thinking").String() != "" || blocks[1].Get("signature").String() != "sig-visible" { + t.Fatalf("block 1 must be detached carrier thinking for visible text signature, got: %s", blocks[1].Raw) + } + if blocks[2].Get("type").String() != "text" || blocks[2].Get("text").String() != "final answer" { + t.Fatalf("block 2 must be text block with visible answer, got: %s", blocks[2].Raw) + } +} + +func TestConvertGeminiResponseToClaudeNonStream_Issue6409_ConsecutiveSignedVisibleTexts(t *testing.T) { + requestJSON := []byte(`{"model":"gemini-3.5-flash-lite","messages":[{"role":"user","content":"hi"}]}`) + geminiResponse := []byte(`{ + "candidates": [{ + "content": { + "parts": [ + {"text": "part A", "thoughtSignature": "sig-A"}, + {"text": "part B", "thoughtSignature": "sig-B"} + ], + "role": "model" + }, + "finishReason": "STOP" + }], + "modelVersion": "gemini-3.5-flash-lite", + "responseId": "resp-consecutive" + }`) + + ctx := context.Background() + output := ConvertGeminiResponseToClaudeNonStream(ctx, "gemini-3.5-flash-lite", requestJSON, requestJSON, geminiResponse, nil) + outputJSON := gjson.ParseBytes(output) + + blocks := outputJSON.Get("content").Array() + if len(blocks) != 4 { + t.Fatalf("expected 4 blocks (carrier A, text A, carrier B, text B), got %d: %s", len(blocks), string(output)) + } + + if blocks[0].Get("type").String() != "thinking" || blocks[0].Get("signature").String() != "sig-A" { + t.Fatalf("block 0 must be carrier for sig-A, got: %s", blocks[0].Raw) + } + if blocks[1].Get("type").String() != "text" || blocks[1].Get("text").String() != "part A" { + t.Fatalf("block 1 must be text part A, got: %s", blocks[1].Raw) + } + if blocks[2].Get("type").String() != "thinking" || blocks[2].Get("signature").String() != "sig-B" { + t.Fatalf("block 2 must be carrier for sig-B, got: %s", blocks[2].Raw) + } + if blocks[3].Get("type").String() != "text" || blocks[3].Get("text").String() != "part B" { + t.Fatalf("block 3 must be text part B, got: %s", blocks[3].Raw) + } +} + +func TestConvertGeminiResponseToClaudeStream_Issue6409_SignedVisibleText(t *testing.T) { + requestJSON := []byte(`{"model":"gemini-3.5-flash-lite","messages":[{"role":"user","content":"hi"}]}`) + chunk := []byte(`{ + "candidates": [{ + "content": { + "parts": [ + {"text": "ok", "thoughtSignature": "sig-stream-1"} + ], + "role": "model" + }, + "finishReason": "STOP", + "index": 0 + }], + "usageMetadata": { + "promptTokenCount": 5, + "candidatesTokenCount": 1 + }, + "modelVersion": "gemini-3.5-flash-lite", + "responseId": "resp-s1" + }`) + + var param any + ctx := context.Background() + output := bytes.Join(ConvertGeminiResponseToClaude(ctx, "gemini-3.5-flash-lite", requestJSON, requestJSON, chunk, ¶m), nil) + output = append(output, bytes.Join(ConvertGeminiResponseToClaude(ctx, "gemini-3.5-flash-lite", requestJSON, requestJSON, []byte("[DONE]"), ¶m), nil)...) + outputText := string(output) + + if strings.Contains(outputText, `"thinking_delta"`) { + t.Fatalf("signed visible text must not emit thinking_delta, got: %s", outputText) + } + + // Verify block 0 is carrier thinking + if !strings.Contains(outputText, `{"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}`) { + t.Fatalf("expected block 0 to be carrier thinking, got: %s", outputText) + } + if !strings.Contains(outputText, `{"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"sig-stream-1"}}`) { + t.Fatalf("expected block 0 to have signature_delta, got: %s", outputText) + } + if !strings.Contains(outputText, `{"type":"content_block_stop","index":0}`) { + t.Fatalf("expected block 0 stop, got: %s", outputText) + } + + // Verify block 1 is visible text + if !strings.Contains(outputText, `{"type":"content_block_start","index":1,"content_block":{"type":"text","text":""}}`) { + t.Fatalf("expected block 1 to be text block, got: %s", outputText) + } + if !strings.Contains(outputText, `{"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"ok"}}`) { + t.Fatalf("expected block 1 to have text_delta with 'ok', got: %s", outputText) + } + if !strings.Contains(outputText, `{"type":"content_block_stop","index":1}`) { + t.Fatalf("expected block 1 stop, got: %s", outputText) + } +} + +func TestConvertGeminiResponseToClaudeStream_Issue6409_SplitTrailingSignature(t *testing.T) { + requestJSON := []byte(`{"model":"gemini-3.5-flash-lite","messages":[{"role":"user","content":"hi"}]}`) + textChunk := []byte(`{ + "candidates": [{ + "content": { + "parts": [{"text": "ok"}] + } + }], + "modelVersion": "gemini-3.5-flash-lite", + "responseId": "resp-s2" + }`) + sigChunk := []byte(`{ + "candidates": [{ + "content": { + "parts": [{"text": "", "thoughtSignature": "sig-stream-trailing"}] + }, + "finishReason": "STOP" + }], + "usageMetadata": { + "promptTokenCount": 5, + "candidatesTokenCount": 1 + }, + "modelVersion": "gemini-3.5-flash-lite", + "responseId": "resp-s2" + }`) + + var param any + ctx := context.Background() + output := bytes.Join(ConvertGeminiResponseToClaude(ctx, "gemini-3.5-flash-lite", requestJSON, requestJSON, textChunk, ¶m), nil) + output = append(output, bytes.Join(ConvertGeminiResponseToClaude(ctx, "gemini-3.5-flash-lite", requestJSON, requestJSON, sigChunk, ¶m), nil)...) + output = append(output, bytes.Join(ConvertGeminiResponseToClaude(ctx, "gemini-3.5-flash-lite", requestJSON, requestJSON, []byte("[DONE]"), ¶m), nil)...) + outputText := string(output) + + if strings.Contains(outputText, `"thinking_delta"`) { + t.Fatalf("unexpected thinking_delta in stream: %s", outputText) + } + + // Block 0: text block with "ok" + if !strings.Contains(outputText, `{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`) { + t.Fatalf("expected block 0 text start, got: %s", outputText) + } + if !strings.Contains(outputText, `{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"ok"}}`) { + t.Fatalf("expected block 0 text delta, got: %s", outputText) + } + if !strings.Contains(outputText, `{"type":"content_block_stop","index":0}`) { + t.Fatalf("expected block 0 text stop, got: %s", outputText) + } + + // Block 1: trailing carrier thinking block + if !strings.Contains(outputText, `{"type":"content_block_start","index":1,"content_block":{"type":"thinking","thinking":""}}`) { + t.Fatalf("expected block 1 trailing carrier thinking, got: %s", outputText) + } + if !strings.Contains(outputText, `{"type":"content_block_delta","index":1,"delta":{"type":"signature_delta","signature":"sig-stream-trailing"}}`) { + t.Fatalf("expected block 1 signature_delta, got: %s", outputText) + } + if !strings.Contains(outputText, `{"type":"content_block_stop","index":1}`) { + t.Fatalf("expected block 1 stop, got: %s", outputText) + } +} + +func TestConvertGeminiResponseToClaudeStream_Issue6409_SignedFunctionCall(t *testing.T) { + requestJSON := []byte(`{"model":"gemini-3.5-flash-lite","messages":[{"role":"user","content":"hi"}]}`) + chunk := []byte(`{ + "candidates": [{ + "content": { + "parts": [ + {"thoughtSignature": "sig-fc-stream", "functionCall": {"name": "test_tool", "args": {}}} + ] + }, + "finishReason": "STOP" + }], + "usageMetadata": { + "promptTokenCount": 5, + "candidatesTokenCount": 1 + }, + "modelVersion": "gemini-3.5-flash-lite", + "responseId": "resp-fc" + }`) + + var param any + ctx := context.Background() + output := bytes.Join(ConvertGeminiResponseToClaude(ctx, "gemini-3.5-flash-lite", requestJSON, requestJSON, chunk, ¶m), nil) + output = append(output, bytes.Join(ConvertGeminiResponseToClaude(ctx, "gemini-3.5-flash-lite", requestJSON, requestJSON, []byte("[DONE]"), ¶m), nil)...) + outputText := string(output) + + // Block 0: carrier thinking + if !strings.Contains(outputText, `{"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}`) { + t.Fatalf("expected block 0 carrier thinking, got: %s", outputText) + } + if !strings.Contains(outputText, `{"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"sig-fc-stream"}}`) { + t.Fatalf("expected block 0 signature_delta, got: %s", outputText) + } + if !strings.Contains(outputText, `{"type":"content_block_stop","index":0}`) { + t.Fatalf("expected block 0 stop, got: %s", outputText) + } + + // Block 1: tool_use + if !strings.Contains(outputText, `{"type":"content_block_start","index":1,"content_block":{"type":"tool_use"`) { + t.Fatalf("expected block 1 tool_use, got: %s", outputText) + } + if !strings.Contains(outputText, `{"type":"content_block_stop","index":1}`) { + t.Fatalf("expected block 1 tool_use stop, got: %s", outputText) + } +} + +func TestConvertGeminiResponseToClaudeStream_Issue6409_FunctionCallContinuationSignature(t *testing.T) { + requestJSON := []byte(`{"model":"gemini-3.5-flash-lite","messages":[{"role":"user","content":"hi"}]}`) + chunk1 := []byte(`{ + "candidates": [{ + "content": { + "parts": [ + {"functionCall": {"name": "test_tool", "args": {}}} + ] + } + }], + "modelVersion": "gemini-3.5-flash-lite", + "responseId": "resp-fc-cont" + }`) + chunk2 := []byte(`{ + "candidates": [{ + "content": { + "parts": [ + {"thoughtSignature": "sig-fc-cont-done", "functionCall": {"args": {"key":"val"}}} + ] + }, + "finishReason": "STOP" + }], + "modelVersion": "gemini-3.5-flash-lite", + "responseId": "resp-fc-cont" + }`) + + var param any + ctx := context.Background() + output := bytes.Join(ConvertGeminiResponseToClaude(ctx, "gemini-3.5-flash-lite", requestJSON, requestJSON, chunk1, ¶m), nil) + output = append(output, bytes.Join(ConvertGeminiResponseToClaude(ctx, "gemini-3.5-flash-lite", requestJSON, requestJSON, chunk2, ¶m), nil)...) + output = append(output, bytes.Join(ConvertGeminiResponseToClaude(ctx, "gemini-3.5-flash-lite", requestJSON, requestJSON, []byte("[DONE]"), ¶m), nil)...) + outputText := string(output) + + if !strings.Contains(outputText, `"type":"input_json_delta"`) { + t.Fatalf("expected input_json_delta, got: %s", outputText) + } + if !strings.Contains(outputText, `"signature":"sig-fc-cont-done"`) { + t.Fatalf("expected signature_delta with 'sig-fc-cont-done', got: %s", outputText) + } +} + +func TestConvertGeminiResponseToClaudeStream_Issue6409_ThinkingFollowedBySignedVisibleText(t *testing.T) { + requestJSON := []byte(`{"model":"gemini-3.5-flash-lite","messages":[{"role":"user","content":"hi"}]}`) + chunk1 := []byte(`{ + "candidates": [{ + "content": { + "parts": [ + {"text": "thinking step", "thought": true, "thoughtSignature": "sig-stream-think"} + ] + } + }], + "modelVersion": "gemini-3.5-flash-lite", + "responseId": "resp-mixed-stream" + }`) + chunk2 := []byte(`{ + "candidates": [{ + "content": { + "parts": [ + {"text": "visible text", "thoughtSignature": "sig-stream-visible"} + ] + }, + "finishReason": "STOP" + }], + "modelVersion": "gemini-3.5-flash-lite", + "responseId": "resp-mixed-stream" + }`) + + var param any + ctx := context.Background() + output := bytes.Join(ConvertGeminiResponseToClaude(ctx, "gemini-3.5-flash-lite", requestJSON, requestJSON, chunk1, ¶m), nil) + output = append(output, bytes.Join(ConvertGeminiResponseToClaude(ctx, "gemini-3.5-flash-lite", requestJSON, requestJSON, chunk2, ¶m), nil)...) + output = append(output, bytes.Join(ConvertGeminiResponseToClaude(ctx, "gemini-3.5-flash-lite", requestJSON, requestJSON, []byte("[DONE]"), ¶m), nil)...) + outputText := string(output) + + // Block 0: thinking with "sig-stream-think" + if !strings.Contains(outputText, `{"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}`) { + t.Fatalf("expected block 0 thinking start, got: %s", outputText) + } + if !strings.Contains(outputText, `{"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"sig-stream-think"}}`) { + t.Fatalf("expected block 0 thinking signature, got: %s", outputText) + } + + // Block 1: detached carrier thinking for visible text signature "sig-stream-visible" + if !strings.Contains(outputText, `{"type":"content_block_start","index":1,"content_block":{"type":"thinking","thinking":""}}`) { + t.Fatalf("expected block 1 detached carrier thinking start, got: %s", outputText) + } + if !strings.Contains(outputText, `{"type":"content_block_delta","index":1,"delta":{"type":"signature_delta","signature":"sig-stream-visible"}}`) { + t.Fatalf("expected block 1 signature_delta 'sig-stream-visible', got: %s", outputText) + } + + // Block 2: text block with "visible text" + if !strings.Contains(outputText, `{"type":"content_block_start","index":2,"content_block":{"type":"text","text":""}}`) { + t.Fatalf("expected block 2 text start, got: %s", outputText) + } + if !strings.Contains(outputText, `{"type":"content_block_delta","index":2,"delta":{"type":"text_delta","text":"visible text"}}`) { + t.Fatalf("expected block 2 text_delta, got: %s", outputText) + } +} From 6a853dce05f532a35d9222f4403bd0b2d4106a37 Mon Sep 17 00:00:00 2001 From: luohui1 <3053763193@qq.com> Date: Tue, 6 Oct 2026 02:49:21 -0700 Subject: [PATCH 066/142] feat(xai): expose Grok TTS on /v1/audio/speech Route OpenAI speech requests to the official xAI /tts endpoint and register grok-tts and grok-voice-tts-1.0. --- internal/api/server_routes.go | 2 + internal/client/codex/models/apply_patch.go | 2 +- internal/client/codex/models/models.go | 4 +- internal/client/codex/models/models_test.go | 11 + internal/registry/model_definitions.go | 34 ++- internal/registry/model_definitions_test.go | 22 ++ internal/runtime/executor/xai_executor.go | 2 + .../runtime/executor/xai_executor_execute.go | 3 + .../runtime/executor/xai_executor_request.go | 16 +- .../runtime/executor/xai_executor_speech.go | 68 +++++ .../executor/xai_executor_speech_test.go | 122 +++++++++ .../runtime/executor/xai_executor_stream.go | 3 + .../handlers/openai/openai_speech_handlers.go | 249 ++++++++++++++++++ .../openai/openai_speech_handlers_test.go | 150 +++++++++++ sdk/cliproxy/auth/conductor_execution.go | 2 +- .../auth/conductor_speech_format_test.go | 36 +++ 16 files changed, 717 insertions(+), 9 deletions(-) create mode 100644 internal/runtime/executor/xai_executor_speech.go create mode 100644 internal/runtime/executor/xai_executor_speech_test.go create mode 100644 sdk/api/handlers/openai/openai_speech_handlers.go create mode 100644 sdk/api/handlers/openai/openai_speech_handlers_test.go create mode 100644 sdk/cliproxy/auth/conductor_speech_format_test.go diff --git a/internal/api/server_routes.go b/internal/api/server_routes.go index fa78ec5b190..8081670ec4c 100644 --- a/internal/api/server_routes.go +++ b/internal/api/server_routes.go @@ -77,6 +77,8 @@ func (s *Server) setupRoutes() { v1.POST("/videos/edits", openaiHandlers.XAIVideosEdits) v1.POST("/videos/extensions", openaiHandlers.XAIVideosExtensions) v1.GET("/videos/:request_id", openaiHandlers.XAIVideosRetrieve) + v1.POST("/audio/speech", openaiHandlers.AudioSpeech) + v1.POST("/tts", openaiHandlers.XAITTS) v1.POST("/messages", claudeCodeHandlers.ClaudeMessages) v1.POST("/messages/count_tokens", claudeCodeHandlers.ClaudeCountTokens) v1.GET("/responses", openaiResponsesHandlers.ResponsesWebsocket) diff --git a/internal/client/codex/models/apply_patch.go b/internal/client/codex/models/apply_patch.go index 0883b7fd059..c2934ad1147 100644 --- a/internal/client/codex/models/apply_patch.go +++ b/internal/client/codex/models/apply_patch.go @@ -9,7 +9,7 @@ type ApplyPatchCapabilityForModelFunc func(string) bool func applyCodexClientApplyPatchCapability(entry map[string]any, id string, capability ApplyPatchCapabilityForModelFunc) { templateSupported := entry["apply_patch_tool_type"] == "freeform" entry["apply_patch_tool_type"] = nil - // Built-in image/video IDs can inherit a generic text template in Home. + // Built-in image, video, and speech IDs can inherit a generic text template in Home. // This classification is a model restriction, not routing capability evidence. baseID := strings.ToLower(strings.TrimSpace(id)) if index := strings.LastIndex(baseID, "/"); index != -1 { diff --git a/internal/client/codex/models/models.go b/internal/client/codex/models/models.go index 97001de2ee1..90d301ea065 100644 --- a/internal/client/codex/models/models.go +++ b/internal/client/codex/models/models.go @@ -730,13 +730,15 @@ func applyCodexClientVisibilityOverride(entry map[string]any, id string) { } } +// isCodexClientImageOrVideoModel reports catalog IDs that are not chat models. +// Speech IDs are included so the Codex client does not offer them as text models. func isCodexClientImageOrVideoModel(id string) bool { target := strings.TrimSpace(id) if idx := strings.Index(target, "/"); idx != -1 { target = strings.TrimSpace(target[idx+1:]) } switch target { - case "grok-imagine-image-quality", "gpt-image-1.5", "gpt-image-2", "gpt-image-2.5-flare", "gpt-image-2.5-sunburst", "gpt-image-2.5", "grok-imagine-image", "grok-imagine-image-2.0", "grok-imagine-video", "grok-imagine-video-1.5", "grok-imagine-video-1.5-preview": + case "grok-imagine-image-quality", "gpt-image-1.5", "gpt-image-2", "gpt-image-2.5-flare", "gpt-image-2.5-sunburst", "gpt-image-2.5", "grok-imagine-image", "grok-imagine-image-2.0", "grok-imagine-video", "grok-imagine-video-1.5", "grok-imagine-video-1.5-preview", "grok-tts", "grok-voice-tts-1.0": return true default: return false diff --git a/internal/client/codex/models/models_test.go b/internal/client/codex/models/models_test.go index ea981f41944..763ca455baf 100644 --- a/internal/client/codex/models/models_test.go +++ b/internal/client/codex/models/models_test.go @@ -132,6 +132,17 @@ func TestCodexClientModelsResponse_InputModalitiesFromRegistry(t *testing.T) { } } +func TestCodexClientHidesSpeechModels(t *testing.T) { + for _, id := range []string{"grok-tts", "grok-voice-tts-1.0", "xai/grok-tts"} { + if !isCodexClientImageOrVideoModel(id) { + t.Fatalf("%s should be hidden from the Codex chat catalog", id) + } + } + if isCodexClientImageOrVideoModel("grok-4") { + t.Fatal("grok-4 should stay visible") + } +} + func TestCodexClientModelsResponse_AppliesDisplayNameToTemplateModel(t *testing.T) { resp := BuildResponse([]map[string]any{{ "id": "gpt-5.5", diff --git a/internal/registry/model_definitions.go b/internal/registry/model_definitions.go index 8b4e34509e4..1cedc675905 100644 --- a/internal/registry/model_definitions.go +++ b/internal/registry/model_definitions.go @@ -18,6 +18,8 @@ const ( xaiBuiltinVideoModelID = "grok-imagine-video" xaiBuiltinVideo15ModelID = "grok-imagine-video-1.5" xaiBuiltinVideo15PreviewID = "grok-imagine-video-1.5-preview" + xaiBuiltinSpeechModelID = "grok-tts" + xaiBuiltinSpeechVoiceModelID = "grok-voice-tts-1.0" ) // staticModelsJSON mirrors the top-level structure of models.json. @@ -255,10 +257,10 @@ func WithCodexBuiltins(models []*ModelInfo) []*ModelInfo { ) } -// WithXAIBuiltins injects hard-coded xAI image/video model definitions that should -// not depend on remote models.json updates. +// WithXAIBuiltins injects hard-coded xAI image, video, and speech model definitions +// that should not depend on remote models.json updates. func WithXAIBuiltins(models []*ModelInfo) []*ModelInfo { - return upsertModelInfos(models, xaiBuiltinImageModelInfo(), xaiBuiltinImageQualityModelInfo(), xaiBuiltinImage20ModelInfo(), xaiBuiltinVideoModelInfo(), xaiBuiltinVideo15ModelInfo(), xaiBuiltinVideo15PreviewModelInfo()) + return upsertModelInfos(models, xaiBuiltinImageModelInfo(), xaiBuiltinImageQualityModelInfo(), xaiBuiltinImage20ModelInfo(), xaiBuiltinVideoModelInfo(), xaiBuiltinVideo15ModelInfo(), xaiBuiltinVideo15PreviewModelInfo(), xaiBuiltinSpeechModelInfo(), xaiBuiltinSpeechVoiceModelInfo()) } func normalizeAntigravityCapabilityModelID(modelID string) string { @@ -407,6 +409,32 @@ func xaiBuiltinVideo15PreviewModelInfo() *ModelInfo { } } +func xaiBuiltinSpeechModelInfo() *ModelInfo { + return &ModelInfo{ + ID: xaiBuiltinSpeechModelID, + Object: "model", + Created: 1773619200, // 2026-03-16 + OwnedBy: "xai", + Type: "xai", + DisplayName: "Grok TTS", + Name: xaiBuiltinSpeechModelID, + Description: "xAI Grok unary text-to-speech model.", + } +} + +func xaiBuiltinSpeechVoiceModelInfo() *ModelInfo { + return &ModelInfo{ + ID: xaiBuiltinSpeechVoiceModelID, + Object: "model", + Created: 1773619200, // 2026-03-16 + OwnedBy: "xai", + Type: "xai", + DisplayName: "Grok Voice TTS 1.0", + Name: xaiBuiltinSpeechVoiceModelID, + Description: "xAI Grok unary text-to-speech model.", + } +} + func upsertModelInfos(models []*ModelInfo, extras ...*ModelInfo) []*ModelInfo { if len(extras) == 0 { return models diff --git a/internal/registry/model_definitions_test.go b/internal/registry/model_definitions_test.go index 24b2d8925f0..667d61aac5f 100644 --- a/internal/registry/model_definitions_test.go +++ b/internal/registry/model_definitions_test.go @@ -131,6 +131,28 @@ func TestWithXAIBuiltinsIncludesImage20(t *testing.T) { t.Fatalf("expected xAI builtin model %s", xaiBuiltinImage20ModelID) } +func TestWithXAIBuiltinsIncludesSpeechModels(t *testing.T) { + models := WithXAIBuiltins(nil) + found := map[string]*ModelInfo{} + for _, model := range models { + if model == nil { + continue + } + if model.ID == xaiBuiltinSpeechModelID || model.ID == xaiBuiltinSpeechVoiceModelID { + found[model.ID] = model + } + } + for _, id := range []string{xaiBuiltinSpeechModelID, xaiBuiltinSpeechVoiceModelID} { + model := found[id] + if model == nil { + t.Fatalf("expected xAI builtin model %s", id) + } + if model.OwnedBy != "xai" || model.Type != "xai" { + t.Fatalf("%s owned_by/type = %s/%s, want xai/xai", id, model.OwnedBy, model.Type) + } + } +} + func TestWithXAIBuiltinsIncludesVideo15GAAndPreviewAlias(t *testing.T) { models := WithXAIBuiltins(nil) foundGA := false diff --git a/internal/runtime/executor/xai_executor.go b/internal/runtime/executor/xai_executor.go index d39097fb17d..3629697ff0c 100644 --- a/internal/runtime/executor/xai_executor.go +++ b/internal/runtime/executor/xai_executor.go @@ -20,6 +20,7 @@ var ( const ( xaiImageHandlerType = "openai-image" xaiVideoHandlerType = "openai-video" + xaiSpeechHandlerType = "openai-speech" xaiCustomToolType = "custom" xaiFunctionToolType = "function" xaiImageGenerationToolType = "image_generation" @@ -43,6 +44,7 @@ const ( xaiVideosEditsPath = "/videos/edits" xaiVideosExtensionsPath = "/videos/extensions" xaiVideosPath = "/videos" + xaiTTSPath = "/tts" xaiIdempotencyKeyMetaKey = "idempotency_key" xaiComposerModelPrefix = "grok-composer-" xaiTokenAuthHeader = "X-XAI-Token-Auth" diff --git a/internal/runtime/executor/xai_executor_execute.go b/internal/runtime/executor/xai_executor_execute.go index de001c96155..53cb87a7814 100644 --- a/internal/runtime/executor/xai_executor_execute.go +++ b/internal/runtime/executor/xai_executor_execute.go @@ -29,6 +29,9 @@ func (e *XAIExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, req if xaiIsVideoRequest(opts) { return e.executeVideos(ctx, auth, req, opts) } + if xaiIsSpeechRequest(opts) { + return e.executeSpeech(ctx, auth, req, opts) + } token, _ := xaiCreds(auth) baseURL := xaiChatBaseURL(auth) diff --git a/internal/runtime/executor/xai_executor_request.go b/internal/runtime/executor/xai_executor_request.go index 34606c74f03..1d3ab89b2bc 100644 --- a/internal/runtime/executor/xai_executor_request.go +++ b/internal/runtime/executor/xai_executor_request.go @@ -253,9 +253,9 @@ func xaiUsingAPI(auth *cliproxyauth.Auth) bool { // is false (including its OAuth default), empty or official default base_url is // rewritten to the CLI chat-proxy endpoint; an explicit non-default base_url is // still honored. -// Websocket and compact transports intentionally do not use this helper: -// cli-chat-proxy does not implement /responses/compact (404) or websocket -// upgrades (405). +// Websocket, compact, and speech intentionally do not use this helper: +// cli-chat-proxy does not implement /responses/compact (404), websocket +// upgrades (405), or /tts. Speech uses xaiSpeechRequestURL. func xaiChatBaseURL(auth *cliproxyauth.Auth) string { _, baseURL := xaiCreds(auth) if xaiUsingAPI(auth) { @@ -504,6 +504,16 @@ func xaiIsVideoRequest(opts cliproxyexecutor.Options) bool { return opts.SourceFormat.String() == xaiVideoHandlerType } +func xaiIsSpeechRequest(opts cliproxyexecutor.Options) bool { + return opts.SourceFormat.String() == xaiSpeechHandlerType +} + +// xaiSpeechRequestURL stays on the official API. cli-chat-proxy does not implement /tts, +// and a 404 there would cool the OAuth auth down as not_found. +func xaiSpeechRequestURL(auth *cliproxyauth.Auth) string { + return strings.TrimSuffix(xaiCompactBaseURL(auth), "/") + xaiTTSPath +} + func xaiVideoEndpointPath(opts cliproxyexecutor.Options) string { if !xaiIsVideoRequest(opts) { return "" diff --git a/internal/runtime/executor/xai_executor_speech.go b/internal/runtime/executor/xai_executor_speech.go new file mode 100644 index 00000000000..c8946bcb46c --- /dev/null +++ b/internal/runtime/executor/xai_executor_speech.go @@ -0,0 +1,68 @@ +package executor + +import ( + "bytes" + "context" + "io" + "net/http" + "strings" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + log "github.com/sirupsen/logrus" + "github.com/tidwall/gjson" +) + +func (e *XAIExecutor) executeSpeech(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (resp cliproxyexecutor.Response, err error) { + model := strings.TrimSpace(gjson.GetBytes(req.Payload, "model").String()) + if model == "" { + model = strings.TrimSpace(req.Model) + } + reporter := helps.NewExecutorUsageReporter(ctx, e, model, auth) + defer reporter.TrackFailure(ctx, &err) + + token, _ := xaiCreds(auth) + requestURL := xaiSpeechRequestURL(auth) + logXAIResolvedBaseURL(ctx, strings.TrimSuffix(requestURL, xaiTTSPath)) + + payload := helps.NewPayloadFinalizer(e.cfg, e.Identifier(), model, xaiSpeechHandlerType, "", req.Payload, req, opts)(req.Payload) + httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, requestURL, bytes.NewReader(payload)) + if err != nil { + return resp, err + } + applyXAIHeaders(httpReq, auth, token, false, "", opts.Headers) + // Official TTS returns raw audio. The media header helper asks for JSON. + httpReq.Header.Set("Accept", "*/*") + e.recordXAIRequest(ctx, auth, requestURL, httpReq.Header.Clone(), payload) + + httpClient := helps.NewProxyAwareHTTPClient(ctx, e.cfg, auth, 0) + httpClient = reporter.TrackHTTPClient(httpClient) + httpResp, err := httpClient.Do(httpReq) + if err != nil { + helps.RecordAPIResponseError(ctx, e.cfg, err) + return resp, err + } + defer func() { + if errClose := httpResp.Body.Close(); errClose != nil { + log.Errorf("xai executor: close response body error: %v", errClose) + } + }() + helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) + + data, err := io.ReadAll(httpResp.Body) + if err != nil { + helps.RecordAPIResponseError(ctx, e.cfg, err) + return resp, err + } + helps.AppendAPIResponseChunk(ctx, e.cfg, data) + + if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { + helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), data)) + err = xaiStatusErr(httpResp.StatusCode, data) + return resp, err + } + + reporter.EnsurePublished(ctx) + return cliproxyexecutor.Response{Payload: data, Headers: httpResp.Header.Clone()}, nil +} diff --git a/internal/runtime/executor/xai_executor_speech_test.go b/internal/runtime/executor/xai_executor_speech_test.go new file mode 100644 index 00000000000..3248d8920e5 --- /dev/null +++ b/internal/runtime/executor/xai_executor_speech_test.go @@ -0,0 +1,122 @@ +package executor + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + xaiauth "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/xai" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +func TestXAISpeechRequestURLStaysOnOfficialAPI(t *testing.T) { + auth := &cliproxyauth.Auth{ + Attributes: map[string]string{ + "auth_kind": "oauth", + "base_url": xaiauth.CLIChatProxyBaseURL, + }, + } + got := xaiSpeechRequestURL(auth) + want := strings.TrimSuffix(xaiauth.DefaultAPIBaseURL, "/") + xaiTTSPath + if got != want { + t.Fatalf("xaiSpeechRequestURL() = %q, want %q", got, want) + } + if xaiIsCLIChatProxyBaseURL(got) { + t.Fatalf("speech URL pinned to CLI chat proxy: %s", got) + } + + custom := &cliproxyauth.Auth{Attributes: map[string]string{"base_url": "https://gateway.example/v1"}} + if got := xaiSpeechRequestURL(custom); got != "https://gateway.example/v1/tts" { + t.Fatalf("custom speech URL = %q", got) + } +} + +func TestXAIExecutorExecuteSpeechPostsAudioRequest(t *testing.T) { + const body = `{"text":"hello","voice_id":"eve","language":"auto"}` + var gotPath string + var gotAuth string + var gotAccept string + var gotContentType string + var gotClientVersion string + var gotTokenAuth string + var gotBody string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotPath = r.URL.Path + gotAuth = r.Header.Get("Authorization") + gotAccept = r.Header.Get("Accept") + gotContentType = r.Header.Get("Content-Type") + gotClientVersion = r.Header.Get(xaiClientVersionHeader) + gotTokenAuth = r.Header.Get(xaiTokenAuthHeader) + raw, errRead := io.ReadAll(r.Body) + if errRead != nil { + t.Errorf("read body: %v", errRead) + } + gotBody = string(raw) + w.Header().Set("Content-Type", "audio/mpeg") + _, _ = w.Write([]byte("ID3audio")) + })) + defer server.Close() + + exec := NewXAIExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{ + Provider: "xai", + Attributes: map[string]string{ + "base_url": server.URL + "/v1", + "auth_kind": "oauth", + }, + Metadata: map[string]any{"access_token": "xai-token"}, + } + resp, err := exec.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "grok-tts", + Payload: []byte(body), + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FromString("openai-speech"), + }) + if err != nil { + t.Fatalf("Execute() error = %v", err) + } + if gotPath != "/v1/tts" { + t.Fatalf("path = %q, want /v1/tts", gotPath) + } + if gotAuth != "Bearer xai-token" { + t.Fatalf("Authorization = %q", gotAuth) + } + if gotAccept != "*/*" { + t.Fatalf("Accept = %q, want */*", gotAccept) + } + if gotContentType != "application/json" { + t.Fatalf("Content-Type = %q", gotContentType) + } + if gotClientVersion != "" || gotTokenAuth != "" { + t.Fatalf("chat-proxy headers leaked: version=%q token-auth=%q", gotClientVersion, gotTokenAuth) + } + if gotBody != body { + t.Fatalf("body = %s", gotBody) + } + if string(resp.Payload) != "ID3audio" { + t.Fatalf("payload = %q", resp.Payload) + } + if resp.Headers.Get("Content-Type") != "audio/mpeg" { + t.Fatalf("response Content-Type = %q", resp.Headers.Get("Content-Type")) + } +} + +func TestXAIExecutorExecuteStreamRejectsSpeech(t *testing.T) { + exec := NewXAIExecutor(&config.Config{}) + _, err := exec.ExecuteStream(context.Background(), &cliproxyauth.Auth{}, cliproxyexecutor.Request{}, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FromString(xaiSpeechHandlerType), + }) + if err == nil || !strings.Contains(err.Error(), "streaming not supported") { + t.Fatalf("error = %v", err) + } + status, ok := err.(interface{ StatusCode() int }) + if !ok || status.StatusCode() != http.StatusBadRequest { + t.Fatalf("status error = %v", err) + } +} diff --git a/internal/runtime/executor/xai_executor_stream.go b/internal/runtime/executor/xai_executor_stream.go index d7918e1eebc..a41be22bb3d 100644 --- a/internal/runtime/executor/xai_executor_stream.go +++ b/internal/runtime/executor/xai_executor_stream.go @@ -20,6 +20,9 @@ func (e *XAIExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Auth if opts.Alt == "responses/compact" { return nil, statusErr{code: http.StatusBadRequest, msg: "streaming not supported for /responses/compact"} } + if xaiIsSpeechRequest(opts) { + return nil, statusErr{code: http.StatusBadRequest, msg: "streaming not supported for /audio/speech"} + } if xaiInputHasItemType(req.Payload, "compaction_trigger") { return e.executeCompactionTriggerStream(ctx, auth, req, opts) } diff --git a/sdk/api/handlers/openai/openai_speech_handlers.go b/sdk/api/handlers/openai/openai_speech_handlers.go new file mode 100644 index 00000000000..033dca0398d --- /dev/null +++ b/sdk/api/handlers/openai/openai_speech_handlers.go @@ -0,0 +1,249 @@ +package openai + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + "unicode/utf8" + + "github.com/gin-gonic/gin" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers" + "github.com/tidwall/gjson" +) + +const ( + xaiSpeechHandlerType = "openai-speech" + defaultXAISpeechModel = "grok-tts" + xaiSpeechVoiceModel = "grok-voice-tts-1.0" + defaultXAISpeechVoice = "eve" + maxXAISpeechRunes = 60000 + maxXAISpeechBody = 1 << 20 + defaultXAISpeechSampleRate = 24000 +) + +// openAISpeechVoices maps OpenAI TTS voice names onto Grok voices. +// Unknown names pass through so Grok voice ids keep working. +var openAISpeechVoices = map[string]string{ + "alloy": "ara", + "ash": "orion", + "ballad": "luna", + "coral": "celeste", + "echo": "rex", + "fable": "sal", + "onyx": "leo", + "nova": "eve", + "sage": "iris", + "shimmer": "aurora", + "verse": "lumen", +} + +func (h *OpenAIAPIHandler) AudioSpeech(c *gin.Context) { + h.handleXAISpeech(c) +} + +func (h *OpenAIAPIHandler) XAITTS(c *gin.Context) { + h.handleXAISpeech(c) +} + +func (h *OpenAIAPIHandler) handleXAISpeech(c *gin.Context) { + raw, err := handlers.ReadRequestBody(c) + if err != nil { + writeSpeechError(c, http.StatusBadRequest, fmt.Sprintf("Invalid request: %v", err)) + return + } + if len(raw) > maxXAISpeechBody { + writeSpeechError(c, http.StatusBadRequest, "request body is larger than 1MB") + return + } + + requested := strings.TrimSpace(gjson.GetBytes(raw, "model").String()) + model, ok := speechRoutingModel(requested) + if !ok { + writeSpeechError(c, http.StatusBadRequest, fmt.Sprintf("Model %s is not supported on /v1/audio/speech. Use %s.", requested, defaultXAISpeechModel)) + return + } + payload, format, err := buildXAISpeechPayload(raw) + if err != nil { + writeSpeechError(c, http.StatusBadRequest, err.Error()) + return + } + + cliCtx, cliCancel := h.GetContextWithCancel(h, c, context.Background()) + // Keep-alive newlines would be prefixed onto the audio body. + resp, upstreamHeaders, errMsg := h.ExecuteWithAuthManager(cliCtx, xaiSpeechHandlerType, model, payload, "") + if errMsg != nil { + h.WriteErrorResponse(c, errMsg) + if errMsg.Error != nil { + cliCancel(errMsg.Error) + } else { + cliCancel(nil) + } + return + } + + c.Header("Content-Type", speechResponseContentType(format, upstreamHeaders.Get("Content-Type"))) + handlers.WriteUpstreamHeaders(c.Writer.Header(), upstreamHeaders) + c.Writer.Header().Del("Content-Length") + _, _ = c.Writer.Write(resp) + cliCancel(nil) +} + +func writeSpeechError(c *gin.Context, status int, message string) { + c.JSON(status, handlers.ErrorResponse{ + Error: handlers.ErrorDetail{ + Message: message, + Type: "invalid_request_error", + }, + }) +} + +func speechRoutingModel(model string) (string, bool) { + switch speechModelBase(model) { + case "", "tts-1", "tts-1-hd", "gpt-4o-mini-tts", defaultXAISpeechModel: + return defaultXAISpeechModel, true + case xaiSpeechVoiceModel: + return xaiSpeechVoiceModel, true + default: + return "", false + } +} + +func speechModelBase(model string) string { + model = strings.TrimSpace(model) + lower := strings.ToLower(model) + for _, prefix := range []string{"xai/", "x-ai/", "grok/"} { + if strings.HasPrefix(lower, prefix) { + model = strings.TrimSpace(model[len(prefix):]) + break + } + } + if open := strings.LastIndex(model, "("); open > 0 && strings.HasSuffix(model, ")") { + model = strings.TrimSpace(model[:open]) + } + return strings.ToLower(strings.TrimSpace(model)) +} + +func buildXAISpeechPayload(raw []byte) ([]byte, string, error) { + if !gjson.ValidBytes(raw) { + return nil, "", errors.New("body must be valid JSON") + } + text := strings.TrimSpace(gjson.GetBytes(raw, "input").String()) + if text == "" { + text = strings.TrimSpace(gjson.GetBytes(raw, "text").String()) + } + if text == "" { + return nil, "", errors.New("input is required") + } + if utf8.RuneCountInString(text) > maxXAISpeechRunes { + return nil, "", errors.New("input is longer than 60000 characters") + } + + voice := strings.TrimSpace(gjson.GetBytes(raw, "voice").String()) + if voice == "" { + voice = gjson.GetBytes(raw, "voice_id").String() + } + language := strings.TrimSpace(gjson.GetBytes(raw, "language").String()) + if language == "" { + language = "auto" + } + body := map[string]any{ + "text": text, + "voice_id": mapXAISpeechVoice(voice), + "language": language, + } + if speed := gjson.GetBytes(raw, "speed"); speed.Exists() && speed.Type == gjson.Number && speed.Float() > 0 { + body["speed"] = speed.Float() + } + format, output, err := speechOutputFormat(raw) + if err != nil { + return nil, "", err + } + if output != nil { + body["output_format"] = output + } + encoded, err := json.Marshal(body) + if err != nil { + return nil, "", err + } + return encoded, format, nil +} + +func mapXAISpeechVoice(voice string) string { + voice = strings.ToLower(strings.TrimSpace(voice)) + if voice == "" { + return defaultXAISpeechVoice + } + if mapped, ok := openAISpeechVoices[voice]; ok { + return mapped + } + return voice +} + +func speechOutputFormat(raw []byte) (string, map[string]any, error) { + responseFormat := strings.ToLower(strings.TrimSpace(gjson.GetBytes(raw, "response_format").String())) + if responseFormat != "" { + format, output, err := speechCodecFormat(responseFormat, defaultXAISpeechSampleRate) + return format, output, err + } + native := gjson.GetBytes(raw, "output_format") + if !native.Exists() { + return "mp3", nil, nil + } + if !native.IsObject() { + return "", nil, errors.New("output_format must be an object") + } + codec := strings.ToLower(strings.TrimSpace(native.Get("codec").String())) + sampleRate := defaultXAISpeechSampleRate + if rate := native.Get("sample_rate"); rate.Exists() && rate.Type == gjson.Number && rate.Float() > 0 { + sampleRate = int(rate.Float()) + } + return speechCodecFormat(codec, sampleRate) +} + +func speechCodecFormat(codec string, sampleRate int) (string, map[string]any, error) { + switch codec { + case "", "mp3": + return "mp3", nil, nil + case "wav", "pcm": + if sampleRate <= 0 { + sampleRate = defaultXAISpeechSampleRate + } + return codec, map[string]any{"codec": codec, "sample_rate": sampleRate}, nil + default: + return "", nil, errors.New("response_format must be mp3, wav, or pcm") + } +} + +func speechContentType(format string) string { + switch format { + case "wav": + return "audio/wav" + case "pcm": + return "audio/pcm" + default: + return "audio/mpeg" + } +} + +func speechContentTypeNeedsDefault(contentType string) bool { + mediaType := strings.ToLower(strings.TrimSpace(contentType)) + if i := strings.Index(mediaType, ";"); i >= 0 { + mediaType = strings.TrimSpace(mediaType[:i]) + } + switch mediaType { + case "", "application/json", "application/octet-stream", "text/plain": + return true + default: + return false + } +} + +func speechResponseContentType(format, upstream string) string { + if !speechContentTypeNeedsDefault(upstream) { + return upstream + } + return speechContentType(format) +} diff --git a/sdk/api/handlers/openai/openai_speech_handlers_test.go b/sdk/api/handlers/openai/openai_speech_handlers_test.go new file mode 100644 index 00000000000..f5b74b80bf9 --- /dev/null +++ b/sdk/api/handlers/openai/openai_speech_handlers_test.go @@ -0,0 +1,150 @@ +package openai + +import ( + "strings" + "testing" + "unicode/utf8" + + "github.com/tidwall/gjson" +) + +func TestBuildXAISpeechPayloadMapsOpenAIVoice(t *testing.T) { + payload, format, err := buildXAISpeechPayload([]byte(`{"model":"tts-1","input":" Hello ","voice":"Alloy","response_format":"mp3"}`)) + if err != nil { + t.Fatalf("buildXAISpeechPayload() error = %v", err) + } + if format != "mp3" { + t.Fatalf("format = %q, want mp3", format) + } + if gjson.GetBytes(payload, "text").String() != "Hello" { + t.Fatalf("text = %s", payload) + } + if gjson.GetBytes(payload, "voice_id").String() != "ara" { + t.Fatalf("voice_id = %s", payload) + } + if gjson.GetBytes(payload, "language").String() != "auto" { + t.Fatalf("language = %s", payload) + } + if gjson.GetBytes(payload, "output_format").Exists() { + t.Fatalf("mp3 should omit output_format: %s", payload) + } + if gjson.GetBytes(payload, "model").Exists() { + t.Fatalf("upstream payload should omit model: %s", payload) + } +} + +func TestBuildXAISpeechPayloadWavAndSpeed(t *testing.T) { + payload, format, err := buildXAISpeechPayload([]byte(`{"text":"你好","voice_id":"Luna","language":"zh","speed":1.25,"response_format":"wav"}`)) + if err != nil { + t.Fatalf("buildXAISpeechPayload() error = %v", err) + } + if format != "wav" { + t.Fatalf("format = %q, want wav", format) + } + if gjson.GetBytes(payload, "voice_id").String() != "luna" { + t.Fatalf("voice_id = %s", payload) + } + if gjson.GetBytes(payload, "language").String() != "zh" { + t.Fatalf("language = %s", payload) + } + if gjson.GetBytes(payload, "speed").Float() != 1.25 { + t.Fatalf("speed = %s", payload) + } + if gjson.GetBytes(payload, "output_format.codec").String() != "wav" || gjson.GetBytes(payload, "output_format.sample_rate").Int() != 24000 { + t.Fatalf("output_format = %s", payload) + } +} + +func TestBuildXAISpeechPayloadNativePCMKeepsSampleRate(t *testing.T) { + payload, format, err := buildXAISpeechPayload([]byte(`{"input":"pcm","output_format":{"codec":"pcm","sample_rate":16000}}`)) + if err != nil { + t.Fatalf("buildXAISpeechPayload() error = %v", err) + } + if format != "pcm" { + t.Fatalf("format = %q, want pcm", format) + } + if gjson.GetBytes(payload, "voice_id").String() != "eve" { + t.Fatalf("voice_id = %s", payload) + } + if gjson.GetBytes(payload, "output_format.sample_rate").Int() != 16000 { + t.Fatalf("sample_rate = %s", payload) + } +} + +func TestBuildXAISpeechPayloadRejects(t *testing.T) { + cases := []struct { + name string + body string + want string + }{ + {name: "missing input", body: `{"voice":"eve"}`, want: "input is required"}, + {name: "bad format", body: `{"input":"hi","response_format":"flac"}`, want: "response_format"}, + {name: "bad json", body: `{`, want: "valid JSON"}, + {name: "zero speed omitted", body: `{"input":"hi","speed":0}`, want: ""}, + } + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + payload, _, err := buildXAISpeechPayload([]byte(tt.body)) + if tt.want == "" { + if err != nil { + t.Fatalf("buildXAISpeechPayload() error = %v", err) + } + if gjson.GetBytes(payload, "speed").Exists() { + t.Fatalf("speed should be omitted: %s", payload) + } + return + } + if err == nil || !strings.Contains(err.Error(), tt.want) { + t.Fatalf("error = %v, want substring %q", err, tt.want) + } + }) + } +} + +func TestBuildXAISpeechPayloadRejectsLongInput(t *testing.T) { + body := `{"input":"` + strings.Repeat("a", maxXAISpeechRunes+1) + `"}` + _, _, err := buildXAISpeechPayload([]byte(body)) + if err == nil || !strings.Contains(err.Error(), "60000") { + t.Fatalf("error = %v", err) + } + if !utf8.ValidString(strings.Repeat("你", 2)) { + t.Fatal("rune fixture is invalid") + } +} + +func TestSpeechRoutingModel(t *testing.T) { + cases := []struct { + in string + want string + ok bool + }{ + {in: "", want: "grok-tts", ok: true}, + {in: "tts-1-hd", want: "grok-tts", ok: true}, + {in: "gpt-4o-mini-tts", want: "grok-tts", ok: true}, + {in: "xai/grok-tts", want: "grok-tts", ok: true}, + {in: "grok-voice-tts-1.0", want: "grok-voice-tts-1.0", ok: true}, + {in: "x-ai/grok-voice-tts-1.0(high)", want: "grok-voice-tts-1.0", ok: true}, + {in: "grok-4.7", ok: false}, + {in: "openai/tts-1", ok: false}, + } + for _, tt := range cases { + t.Run(tt.in, func(t *testing.T) { + got, ok := speechRoutingModel(tt.in) + if ok != tt.ok || got != tt.want { + t.Fatalf("speechRoutingModel(%q) = %q, %v; want %q, %v", tt.in, got, ok, tt.want, tt.ok) + } + }) + } +} + +func TestSpeechResponseContentType(t *testing.T) { + if got := speechResponseContentType("mp3", ""); got != "audio/mpeg" { + t.Fatalf("empty upstream = %q", got) + } + if got := speechResponseContentType("wav", "application/json"); got != "audio/wav" { + t.Fatalf("json upstream = %q", got) + } + if got := speechResponseContentType("pcm", "audio/L16; rate=24000"); got != "audio/L16; rate=24000" { + t.Fatalf("audio upstream = %q", got) + } +} diff --git a/sdk/cliproxy/auth/conductor_execution.go b/sdk/cliproxy/auth/conductor_execution.go index 9616a82176e..1571c4892c1 100644 --- a/sdk/cliproxy/auth/conductor_execution.go +++ b/sdk/cliproxy/auth/conductor_execution.go @@ -407,7 +407,7 @@ func requestToFormat(provider string, executor ProviderExecutor, req cliproxyexe } } source := opts.SourceFormat.String() - if source == "openai-image" || source == "openai-video" { + if source == "openai-image" || source == "openai-video" || source == "openai-speech" { return opts.SourceFormat } if opts.Alt == "responses/compact" && !opts.Stream { diff --git a/sdk/cliproxy/auth/conductor_speech_format_test.go b/sdk/cliproxy/auth/conductor_speech_format_test.go new file mode 100644 index 00000000000..3f2340cc290 --- /dev/null +++ b/sdk/cliproxy/auth/conductor_speech_format_test.go @@ -0,0 +1,36 @@ +package auth + +import ( + "testing" + + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +func TestRequestToFormatKeepsMediaSources(t *testing.T) { + cases := []struct { + source string + want string + }{ + {source: "openai-image", want: "openai-image"}, + {source: "openai-video", want: "openai-video"}, + {source: "openai-speech", want: "openai-speech"}, + } + for _, tt := range cases { + t.Run(tt.source, func(t *testing.T) { + got := requestToFormat("xai", nil, cliproxyexecutor.Request{}, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FromString(tt.source), + }) + if got.String() != tt.want { + t.Fatalf("requestToFormat() = %q, want %q", got, tt.want) + } + }) + } + + got := requestToFormat("xai", nil, cliproxyexecutor.Request{}, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAI, + }) + if got != sdktranslator.FormatCodex { + t.Fatalf("chat requestToFormat() = %q, want codex", got) + } +} From da5f109f34b6edf6ba8c1b7a95d400386392e8ec Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Tue, 6 Oct 2026 20:27:42 +0800 Subject: [PATCH 067/142] test(cliproxy): fix model catalog restore configuration in tests - Set catalog fixtures and disable home config when restoring service state in catalog updater tests Closes: #6414 --- sdk/cliproxy/service_catalogs_test.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/sdk/cliproxy/service_catalogs_test.go b/sdk/cliproxy/service_catalogs_test.go index 2936de75fea..8cb3a7a1c2c 100644 --- a/sdk/cliproxy/service_catalogs_test.go +++ b/sdk/cliproxy/service_catalogs_test.go @@ -68,8 +68,12 @@ func TestServiceCatalogStartupAndConfigReload(t *testing.T) { restoreCtx, restoreCancel := context.WithCancel(context.Background()) defer restoreCancel() restoreCfg := *cfg - restoreCfg.Home.Enabled = true - restoreCfg.Models.DevinCatalog = originalPath + restoreCfg.Home.Enabled = false + restoreCfg.Models = config.ModelCatalogs{ + Catalog: fixture("models.json"), + CodexCatalog: fixture("codex_client_models.json"), + DevinCatalog: originalPath, + } restore := &Service{cfg: &restoreCfg} if string(registry.GetDevinModelsJSON()) != string(original) { restore.startModelCatalogUpdaters(restoreCtx) From 50d5fe1831fe375d0f37626b49c9c89417503d13 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Wed, 7 Oct 2026 00:14:50 +0800 Subject: [PATCH 068/142] fix(cliproxy): avoid selecting rejected credentials during refresh and preserve active quota cooldowns - Track `RejectedAccessToken` on 401 failures so rejected tokens are treated as expired and bypassed by concurrent requests while refresh is pending - Preserve active model quota cooldown states when clearing unauthorized errors upon successful token refresh - Reschedule token refresh if the refresh operation is canceled Closes: #6415 --- sdk/cliproxy/auth/conductor_issue6415_test.go | 350 ++++++++++++++++++ sdk/cliproxy/auth/conductor_lifecycle.go | 6 +- sdk/cliproxy/auth/conductor_persistence.go | 2 +- sdk/cliproxy/auth/conductor_refresh.go | 53 ++- sdk/cliproxy/auth/metadata_merge.go | 1 + sdk/cliproxy/auth/types.go | 12 +- 6 files changed, 418 insertions(+), 6 deletions(-) create mode 100644 sdk/cliproxy/auth/conductor_issue6415_test.go diff --git a/sdk/cliproxy/auth/conductor_issue6415_test.go b/sdk/cliproxy/auth/conductor_issue6415_test.go new file mode 100644 index 00000000000..10614738066 --- /dev/null +++ b/sdk/cliproxy/auth/conductor_issue6415_test.go @@ -0,0 +1,350 @@ +package auth + +import ( + "context" + "errors" + "net/http" + "testing" + "time" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" +) + +// TestManager_Issue6415_RefreshPending_DoesNotSelectRejectedCredential reproduces +// Issue #6415 symptom 1: +// When a request fails with 401 and token expiry is unknown, concurrent requests +// should not pick the credential while refresh is pending. +func TestManager_Issue6415_RefreshPending_DoesNotSelectRejectedCredential(t *testing.T) { + m, executor, primary, backup, model := newUnauthorizedRefreshFixture(t, false) + + refreshStarted := make(chan struct{}) + releaseRefresh := make(chan struct{}) + + executor.mu.Lock() + executor.onRefresh = func() { + select { + case <-refreshStarted: + default: + close(refreshStarted) + } + <-releaseRefresh + } + executor.mu.Unlock() + + req1Done := make(chan struct{}) + var resp1 cliproxyexecutor.Response + var err1 error + go func() { + defer close(req1Done) + resp1, err1 = m.Execute(context.Background(), []string{"codex"}, cliproxyexecutor.Request{Model: model}, cliproxyexecutor.Options{}) + }() + + // Wait for primary to hit 401 and enter Refresh (which is now blocked). + <-refreshStarted + + // While refresh is pending on primary with a rejected token, primary must be blocked / not selectable. + currentPrimary, ok := m.GetByID(primary.ID) + if !ok || currentPrimary == nil { + t.Fatal("primary auth missing") + } + blocked, _, _ := isAuthBlockedForModel(currentPrimary, model, time.Now()) + if !blocked { + t.Fatalf("primary must be blocked while refresh is pending for rejected token") + } + + // Concurrent request while refresh is pending must pick backup and succeed without touching primary. + execCallsBefore := len(executor.ExecuteCalls()) + resp2, err2 := m.Execute(context.Background(), []string{"codex"}, cliproxyexecutor.Request{Model: model}, cliproxyexecutor.Options{}) + if err2 != nil { + t.Fatalf("concurrent Execute error = %v, want success via backup", err2) + } + if got := string(resp2.Payload); got != backup.ID+":backup-access-token" { + t.Fatalf("concurrent Execute payload = %q, want backup response", got) + } + for _, call := range executor.ExecuteCalls()[execCallsBefore:] { + if call == primary.ID { + t.Fatalf("primary was executed during pending refresh!") + } + } + + // Release refresh and wait for first request to complete. + close(releaseRefresh) + <-req1Done + if err1 != nil { + t.Fatalf("first Execute error = %v, want success after refresh", err1) + } + if got := string(resp1.Payload); got != primary.ID+":fresh-access-token" { + t.Fatalf("first Execute payload = %q, want fresh primary response", got) + } +} + +// TestManager_Issue6415_NonTerminalRefreshFailure_MarksCredentialUnavailable reproduces +// Issue #6415 symptom 2: +// When refresh fails with a non-terminal error (e.g. transient 503) for a token with +// unknown expiry, the rejected token must not be retained as active. +func TestManager_Issue6415_NonTerminalRefreshFailure_MarksCredentialUnavailable(t *testing.T) { + m, executor, primary, _, _ := newUnauthorizedRefreshFixture(t, false) + + executor.mu.Lock() + executor.refreshErr = errors.New("upstream 503 Service Unavailable") + executor.mu.Unlock() + + // Direct call to refreshAuthForRequest with the rejected access token. + _, errRefresh := m.refreshAuthForRequest(context.Background(), primary.ID, authAccessToken(primary)) + if errRefresh == nil { + t.Fatal("expected refresh error") + } + + updatedPrimary, ok := m.GetByID(primary.ID) + if !ok || updatedPrimary == nil { + t.Fatal("primary auth missing") + } + if !updatedPrimary.Unavailable { + t.Fatalf("primary.Unavailable = false, want true after rejected token refresh failed") + } + if updatedPrimary.Status != StatusError { + t.Fatalf("primary.Status = %q, want StatusError", updatedPrimary.Status) + } +} + +// TestManager_Issue6415_RefreshSuccess_PreservesActiveQuotaCooldown reproduces +// Issue #6415 related symptom: +// A successful 401 refresh must not wipe an independent, still-active quota cooldown on that model. +func TestManager_Issue6415_RefreshSuccess_PreservesActiveQuotaCooldown(t *testing.T) { + m, _, primary, _, model := newUnauthorizedRefreshFixture(t, false) + + // Set active quota cooldown on primary for model. + now := time.Now() + quotaRecover := now.Add(30 * time.Minute) + primaryAuth, ok := m.GetByID(primary.ID) + if !ok || primaryAuth == nil { + t.Fatal("primary auth missing") + } + primaryAuth.ModelStates = map[string]*ModelState{ + model: { + Status: StatusError, + StatusMessage: "unauthorized", + Unavailable: true, + NextRetryAfter: quotaRecover, + Quota: QuotaState{ + Exceeded: true, + Reason: "quota", + NextRecoverAt: quotaRecover, + }, + LastError: &Error{HTTPStatus: http.StatusUnauthorized, Message: "unauthorized"}, + }, + } + if _, errUpdate := m.Update(context.Background(), primaryAuth); errUpdate != nil { + t.Fatalf("update primary auth: %v", errUpdate) + } + + // Trigger 401 refresh on primary. + _, errRefresh := m.ForceRefreshAuth(context.Background(), primary.ID) + if errRefresh != nil { + t.Fatalf("ForceRefreshAuth error = %v", errRefresh) + } + + updatedPrimary, ok := m.GetByID(primary.ID) + if !ok || updatedPrimary == nil { + t.Fatal("primary auth missing after refresh") + } + ms := updatedPrimary.ModelStates[model] + if ms == nil { + t.Fatalf("model state for %q missing after refresh", model) + } + if !ms.Quota.Exceeded { + t.Fatalf("model state Quota.Exceeded = false, want true (quota cooldown was discarded)") + } + if !ms.Quota.NextRecoverAt.Equal(quotaRecover) { + t.Fatalf("model state Quota.NextRecoverAt = %v, want %v", ms.Quota.NextRecoverAt, quotaRecover) + } +} + +// TestManager_Issue6415_ExecuteRetrySuccess_PreservesActiveQuotaCooldown tests +// the full Execute path (401 -> refresh -> retry success) and ensures both sibling +// models and the retried model with active quota cooldown keep their quota state. +func TestManager_Issue6415_ExecuteRetrySuccess_PreservesActiveQuotaCooldown(t *testing.T) { + m, executor, primary, _, model := newUnauthorizedRefreshFixture(t, false) + + siblingModel := "gpt-5-mini" + reg := registry.GetGlobalRegistry() + reg.RegisterClient(primary.ID, "codex", []*registry.ModelInfo{{ID: model}, {ID: siblingModel}}) + t.Cleanup(func() { + reg.UnregisterClient(primary.ID) + }) + + now := time.Now() + quotaRecover := now.Add(45 * time.Minute) + primaryAuth, ok := m.GetByID(primary.ID) + if !ok || primaryAuth == nil { + t.Fatal("primary auth missing") + } + primaryAuth.ModelStates = map[string]*ModelState{ + siblingModel: { + Status: StatusError, + StatusMessage: "quota_exceeded", + Unavailable: true, + NextRetryAfter: quotaRecover, + Quota: QuotaState{ + Exceeded: true, + Reason: "quota", + NextRecoverAt: quotaRecover, + }, + LastError: &Error{HTTPStatus: http.StatusTooManyRequests, Message: "429 rate limited"}, + }, + } + if _, errUpdate := m.Update(context.Background(), primaryAuth); errUpdate != nil { + t.Fatalf("update primary auth: %v", errUpdate) + } + + // Execute model: triggers 401 on primary, refreshes token, retries, and succeeds. + resp, errExec := m.Execute(context.Background(), []string{"codex"}, cliproxyexecutor.Request{Model: model}, cliproxyexecutor.Options{}) + if errExec != nil { + t.Fatalf("Execute error = %v, want success after refresh retry", errExec) + } + if got := string(resp.Payload); got != primary.ID+":fresh-access-token" { + t.Fatalf("payload = %q, want fresh primary response", got) + } + + if got := executor.RefreshCalls(); got != 1 { + t.Fatalf("Refresh calls = %d, want 1", got) + } + + updatedPrimary, ok := m.GetByID(primary.ID) + if !ok || updatedPrimary == nil { + t.Fatal("primary auth missing after execution") + } + + // Verify sibling model still preserves its active quota cooldown. + siblingState := updatedPrimary.ModelStates[siblingModel] + if siblingState == nil { + t.Fatalf("sibling model state %q missing", siblingModel) + } + if !siblingState.Quota.Exceeded { + t.Fatalf("sibling model Quota.Exceeded = false, want true after successful refresh of primary") + } + if !siblingState.Quota.NextRecoverAt.Equal(quotaRecover) { + t.Fatalf("sibling model Quota.NextRecoverAt = %v, want %v", siblingState.Quota.NextRecoverAt, quotaRecover) + } +} + +// TestManager_Issue6415_MarkRejectedAccessToken_AdvancesGeneration verifies +// that markRejectedAccessToken increments Generation so stale in-flight results +// cannot overwrite the rejected credential status in the scheduler. +func TestManager_Issue6415_MarkRejectedAccessToken_AdvancesGeneration(t *testing.T) { + m, _, primary, _, _ := newUnauthorizedRefreshFixture(t, false) + + initialPrimary, ok := m.GetByID(primary.ID) + if !ok || initialPrimary == nil { + t.Fatal("primary auth missing") + } + initialGen := initialPrimary.Generation + + m.markRejectedAccessToken(primary.ID, authAccessToken(initialPrimary)) + + afterPrimary, ok := m.GetByID(primary.ID) + if !ok || afterPrimary == nil { + t.Fatal("primary auth missing after rejection") + } + if afterPrimary.Generation <= initialGen { + t.Fatalf("Generation = %d, want > %d after markRejectedAccessToken", afterPrimary.Generation, initialGen) + } + if afterPrimary.RejectedAccessToken != authAccessToken(initialPrimary) { + t.Fatalf("RejectedAccessToken = %q, want %q", afterPrimary.RejectedAccessToken, authAccessToken(initialPrimary)) + } +} + +// TestManager_Issue6415_UpdateWithoutCredentialChange_PreservesRejectedAccessToken +// verifies that hot-reloads or Manager.Update with identical credentials does not +// wipe out the runtime RejectedAccessToken marker. +func TestManager_Issue6415_UpdateWithoutCredentialChange_PreservesRejectedAccessToken(t *testing.T) { + m, _, primary, _, _ := newUnauthorizedRefreshFixture(t, false) + + token := authAccessToken(primary) + m.markRejectedAccessToken(primary.ID, token) + + // Simulate config reload or metadata update (e.g. note or weight change, but same credentials). + reloadAuth := primary.Clone() + reloadAuth.RejectedAccessToken = "" // Serialized auth from file has empty runtime field + reloadAuth.Metadata["note"] = "reloaded from file" + + updated, errUpdate := m.Update(context.Background(), reloadAuth) + if errUpdate != nil { + t.Fatalf("Update error = %v", errUpdate) + } + if updated.RejectedAccessToken != token { + t.Fatalf("RejectedAccessToken after reload = %q, want %q", updated.RejectedAccessToken, token) + } + + fetched, ok := m.GetByID(primary.ID) + if !ok || fetched == nil { + t.Fatal("primary auth missing") + } + if fetched.RejectedAccessToken != token { + t.Fatalf("fetched RejectedAccessToken = %q, want %q", fetched.RejectedAccessToken, token) + } +} + +// TestManager_Issue6415_RefreshSuccessWithUnchangedToken_ClearsRejectedAccessToken +// verifies that when Refresh succeeds but returns the exact same token string, +// the RejectedAccessToken marker is cleared and not erroneously restored. +func TestManager_Issue6415_RefreshSuccessWithUnchangedToken_ClearsRejectedAccessToken(t *testing.T) { + m, executor, primary, _, model := newUnauthorizedRefreshFixture(t, false) + + token := authAccessToken(primary) + m.markRejectedAccessToken(primary.ID, token) + + // Executor Refresh returns the same token string (e.g. session refreshed without rotating key). + executor.mu.Lock() + executor.refreshTokens[primary.ID] = token + executor.mu.Unlock() + + refreshed, errRefresh := m.ForceRefreshAuth(context.Background(), primary.ID) + if errRefresh != nil { + t.Fatalf("ForceRefreshAuth error = %v", errRefresh) + } + if refreshed.RejectedAccessToken != "" { + t.Fatalf("refreshed.RejectedAccessToken = %q, want empty after successful refresh", refreshed.RejectedAccessToken) + } + + fetched, ok := m.GetByID(primary.ID) + if !ok || fetched == nil { + t.Fatal("primary auth missing") + } + if fetched.RejectedAccessToken != "" { + t.Fatalf("fetched.RejectedAccessToken = %q, want empty after successful refresh", fetched.RejectedAccessToken) + } + + blocked, _, _ := isAuthBlockedForModel(fetched, model, time.Now()) + if blocked { + t.Fatalf("primary is blocked after successful refresh with unchanged token") + } +} + +// TestManager_Issue6415_RefreshCanceled_ReschedulesRefresh verifies that if +// a refresh is canceled via context, a retry is scheduled so the rejected credential +// does not remain indefinitely unselectable without a retry attempt. +func TestManager_Issue6415_RefreshCanceled_ReschedulesRefresh(t *testing.T) { + m, executor, primary, _, _ := newUnauthorizedRefreshFixture(t, false) + + executor.mu.Lock() + executor.refreshErr = context.Canceled + executor.mu.Unlock() + + _, err := m.refreshAuthForRequest(context.Background(), primary.ID, authAccessToken(primary)) + if err == nil { + t.Fatal("expected canceled error, got nil") + } + if !errors.Is(err, context.Canceled) { + t.Fatalf("err = %v, want context.Canceled", err) + } + + fetched, ok := m.GetByID(primary.ID) + if !ok || fetched == nil { + t.Fatal("primary auth missing") + } + if fetched.NextRefreshAfter.IsZero() { + t.Fatal("NextRefreshAfter should be scheduled after refresh cancellation, got zero") + } +} diff --git a/sdk/cliproxy/auth/conductor_lifecycle.go b/sdk/cliproxy/auth/conductor_lifecycle.go index 597a7d7c3a2..3106f801ed7 100644 --- a/sdk/cliproxy/auth/conductor_lifecycle.go +++ b/sdk/cliproxy/auth/conductor_lifecycle.go @@ -249,17 +249,21 @@ func (m *Manager) updateInternal(ctx context.Context, base, auth *Auth, mode upd auth.ModelStates = existing.ModelStates } credChanged := CredentialsChanged(existing, auth) - if credChanged { + if credChanged || mode == updateModeRefresh { + auth.RejectedAccessToken = "" if hasUnauthorizedAuthFailure(existing) || (auth.LastError != nil && isUnauthorizedError(auth.LastError)) { auth.Unavailable = false auth.LastError = nil auth.StatusMessage = "" auth.Status = StatusActive + cooldownStateChanged = true } resumed := clearUnauthorizedModelStates(auth, time.Now()) if len(resumed) > 0 { cooldownStateChanged = true } + } else { + auth.RejectedAccessToken = existing.RejectedAccessToken } if existing.Quota.Exceeded && existing.Quota.Reason == "credential_quota" && existing.Quota.NextRecoverAt.After(time.Now()) { auth.Unavailable = existing.Unavailable diff --git a/sdk/cliproxy/auth/conductor_persistence.go b/sdk/cliproxy/auth/conductor_persistence.go index 72739c0540a..e647ec1c620 100644 --- a/sdk/cliproxy/auth/conductor_persistence.go +++ b/sdk/cliproxy/auth/conductor_persistence.go @@ -68,7 +68,7 @@ func mergeAuthSaveDelta(target, before, after *Auth, preserveConcurrent bool) { next := reflect.ValueOf(after).Elem() for i := 0; i < dst.NumField(); i++ { field := dst.Type().Field(i) - if field.PkgPath != "" || field.Name == "ID" || field.Name == "RegistrationEpoch" || field.Name == "Generation" { + if field.PkgPath != "" || field.Name == "ID" || field.Name == "RegistrationEpoch" || field.Name == "Generation" || field.Name == "RejectedAccessToken" { continue } d, b, n := dst.Field(i), base.Field(i), next.Field(i) diff --git a/sdk/cliproxy/auth/conductor_refresh.go b/sdk/cliproxy/auth/conductor_refresh.go index 285f83e431c..69b11c674ed 100644 --- a/sdk/cliproxy/auth/conductor_refresh.go +++ b/sdk/cliproxy/auth/conductor_refresh.go @@ -464,6 +464,7 @@ func clearUnauthorizedModelStates(auth *Auth, now time.Time) []string { return nil } var resumed []string + anyChanged := false for model, state := range auth.ModelStates { if state == nil { continue @@ -480,10 +481,19 @@ func clearUnauthorizedModelStates(auth *Auth, now time.Time) []string { if !isUnauth { continue } + anyChanged = true + if state.Quota.Exceeded && (state.Quota.NextRecoverAt.IsZero() || state.Quota.NextRecoverAt.After(now)) { + state.LastError = nil + if strings.Contains(strings.ToLower(state.StatusMessage), "unauthorized") { + state.StatusMessage = state.Quota.Reason + } + state.UpdatedAt = now + continue + } resetModelState(state, now) resumed = append(resumed, model) } - if len(resumed) > 0 { + if anyChanged { updateAggregatedAvailability(auth, now) } return resumed @@ -578,6 +588,27 @@ func isForceRefreshContext(ctx context.Context) bool { return ok && v } +func (m *Manager) markRejectedAccessToken(id, failedAccessToken string) { + if m == nil || id == "" || failedAccessToken == "" { + return + } + releaseMutation := m.lockAuthMutation(id) + defer releaseMutation() + m.mu.Lock() + if current := m.auths[id]; current != nil && authAccessToken(current) == failedAccessToken { + if _, hasExp := current.AccessTokenExpirationTime(); !hasExp { + current.Generation++ + current.UpdatedAt = time.Now() + current.RejectedAccessToken = failedAccessToken + m.auths[id] = current + if m.scheduler != nil { + m.scheduler.upsertAuth(current.Clone()) + } + } + } + m.mu.Unlock() +} + func (m *Manager) refreshAuthForRequestAtEpoch(ctx context.Context, id, failedAccessToken string, registrationEpoch uint64) (*Auth, error) { if m == nil { return nil, errors.New("auth manager is nil") @@ -594,6 +625,9 @@ func (m *Manager) refreshAuthForRequestAtEpoch(ctx context.Context, id, failedAc if id == "" { return nil, errors.New("auth id is empty") } + if failedAccessToken != "" { + m.markRejectedAccessToken(id, failedAccessToken) + } lockValue, _ := m.refreshLocks.LoadOrStore(id, &authRefreshLock{}) lock, _ := lockValue.(*authRefreshLock) @@ -635,12 +669,24 @@ func (m *Manager) refreshAuthForRequestAtEpoch(ctx context.Context, id, failedAc base := auth.Clone() updated, err := exec.Refresh(ctx, base.Clone()) + now := time.Now() if err != nil && errors.Is(err, context.Canceled) { log.Debugf("refresh canceled for %s, %s", auth.Provider, auth.ID) + m.mu.Lock() + if current := m.auths[id]; current != nil { + if current.NextRefreshAfter.IsZero() || current.NextRefreshAfter.Before(now) { + current.NextRefreshAfter = now.Add(time.Second) + } + m.auths[id] = current + if m.scheduler != nil { + m.scheduler.upsertAuth(current.Clone()) + } + } + m.mu.Unlock() + m.queueRefreshReschedule(id) return nil, err } log.Debugf("refreshed %s, %s, %v", auth.Provider, auth.ID, err) - now := time.Now() if err != nil { unauthorized := isUnauthorizedError(err) invalidGrant := isInvalidGrantError(err) @@ -713,7 +759,7 @@ func (m *Manager) refreshAuthForRequestAtEpoch(ctx context.Context, id, failedAc current.LastError = &Error{Code: "unauthorized", Message: err.Error(), HTTPStatus: http.StatusUnauthorized} current.StatusMessage = "unauthorized (refresh token invalid)" shouldUnschedule = true - } else if !hasValidAccessToken { + } else if !hasValidAccessToken || accessTokenRejected { current.Unavailable = true current.Status = StatusError if unauthorized { @@ -778,6 +824,7 @@ func (m *Manager) refreshAuthForRequestAtEpoch(ctx context.Context, id, failedAc updated.StatusMessage = "" updated.Unavailable = false updated.RefreshFailures = 0 + updated.RejectedAccessToken = "" if updated.Status == StatusError || updated.Status == "" { updated.Status = StatusActive } diff --git a/sdk/cliproxy/auth/metadata_merge.go b/sdk/cliproxy/auth/metadata_merge.go index 590567f42c8..ca99a5208d5 100644 --- a/sdk/cliproxy/auth/metadata_merge.go +++ b/sdk/cliproxy/auth/metadata_merge.go @@ -71,6 +71,7 @@ func MergeRefreshedAuth(base, current, updated *Auth) *Auth { } // 1. Refresh Lifecycle Timestamps + merged.RejectedAccessToken = updated.RejectedAccessToken if !updated.LastRefreshedAt.IsZero() { merged.LastRefreshedAt = updated.LastRefreshedAt } diff --git a/sdk/cliproxy/auth/types.go b/sdk/cliproxy/auth/types.go index 0aeb7b2adee..2db42e28878 100644 --- a/sdk/cliproxy/auth/types.go +++ b/sdk/cliproxy/auth/types.go @@ -100,6 +100,9 @@ type Auth struct { // Runtime carries non-serialisable data used during execution (in-memory only). Runtime any `json:"-"` + // RejectedAccessToken tracks the access token rejected by upstream 401 until a refresh succeeds. + RejectedAccessToken string `json:"-"` + Success int64 `json:"-"` Failed int64 `json:"-"` @@ -617,7 +620,11 @@ func (a *Auth) ExpirationTime() (time.Time, bool) { if a == nil { return time.Time{}, false } - if tokenStr := authAccessToken(a); tokenStr != "" { + tokenStr := authAccessToken(a) + if tokenStr != "" && a.RejectedAccessToken != "" && a.RejectedAccessToken == tokenStr { + return time.Unix(0, 0), true + } + if tokenStr != "" { if jwtExp, ok := parseJWTExp(tokenStr); ok { return jwtExp, true } @@ -638,6 +645,9 @@ func (a *Auth) AccessTokenExpirationTime() (time.Time, bool) { if tokenStr == "" { return time.Time{}, false } + if a.RejectedAccessToken != "" && a.RejectedAccessToken == tokenStr { + return time.Unix(0, 0), true + } if jwtExp, ok := parseJWTExp(tokenStr); ok { return jwtExp, true } From 3a71fcf8d5d071761ce7acddff6884abf103f467 Mon Sep 17 00:00:00 2001 From: Supra4E8C Date: Wed, 7 Oct 2026 01:10:23 +0800 Subject: [PATCH 069/142] fix(config): read/write optimize-multi-agent-v2 at canonical client path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The backend migrated oauth.providers.codex.optimize-multi-agent-v2 to client.codex.optimize-multi-agent-v2 (v8ClientPaths in config_v8.go). The visual editor still read the historical path, so toggling "Optimize multi-agent v2" saved but reverted to off after refresh — and when client.codex already held false, writes to the stale alias could never enable the feature. Point the addition field and its search yamlKeys at the canonical client.codex path; the backend normalizes any remaining legacy keys on save. Fixes router-for-me/Cli-Proxy-API-Management-Center#472 --- src/features/config/searchIndex.ts | 2 +- src/features/config/visualConfigAdditions.ts | 2 +- tests/configFieldParity.test.ts | 1 + tests/configOAuthBehaviorUi.test.ts | 2 +- 4 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/features/config/searchIndex.ts b/src/features/config/searchIndex.ts index d2a69034bd1..b17f01b229e 100644 --- a/src/features/config/searchIndex.ts +++ b/src/features/config/searchIndex.ts @@ -126,7 +126,7 @@ export const CONFIG_FIELD_SEARCH_INDEX: ConfigFieldSearchEntry[] = [ sectionId: 'advanced', labelKey: L('additions.codexOptimizeMultiAgentV2.label'), hintKey: L('additions.codexOptimizeMultiAgentV2.hint'), - yamlKeys: ['oauth', 'providers', 'codex', 'optimize-multi-agent-v2'], + yamlKeys: ['client', 'codex', 'optimize-multi-agent-v2'], }, { fieldId: 'codexOrphanDelegationCompatibility', diff --git a/src/features/config/visualConfigAdditions.ts b/src/features/config/visualConfigAdditions.ts index 8118a10661b..097b2122fcc 100644 --- a/src/features/config/visualConfigAdditions.ts +++ b/src/features/config/visualConfigAdditions.ts @@ -72,7 +72,7 @@ export const ADDITION_FIELDS = [ }, { key: 'codexOptimizeMultiAgentV2', - path: 'oauth.providers.codex.optimize-multi-agent-v2'.split('.'), + path: 'client.codex.optimize-multi-agent-v2'.split('.'), kind: 'boolean', }, { diff --git a/tests/configFieldParity.test.ts b/tests/configFieldParity.test.ts index 375515849b5..1f5047e070d 100644 --- a/tests/configFieldParity.test.ts +++ b/tests/configFieldParity.test.ts @@ -148,6 +148,7 @@ describe('v8 YAML search paths', () => { ['quotaAntigravityCredits', 'oauth.providers.antigravity.antigravity-credits'], ['wsAuth', 'oauth.providers.aistudio.ws-auth'], ['codexHeaderUserAgent', 'oauth.providers.codex.header-defaults.user-agent'], + ['codexOptimizeMultiAgentV2', 'client.codex.optimize-multi-agent-v2'], ['streamingNonstreamKeepalive', 'requests.nonstream-keepalive-interval'], ['payloadDefaultRules', 'requests.payload.default'], ['pluginStoreAuth', 'plugins.store-auth'], diff --git a/tests/configOAuthBehaviorUi.test.ts b/tests/configOAuthBehaviorUi.test.ts index 9ff8430529b..2b84e4b16c3 100644 --- a/tests/configOAuthBehaviorUi.test.ts +++ b/tests/configOAuthBehaviorUi.test.ts @@ -43,7 +43,7 @@ describe('OAuth behavior configuration UI', () => { expect(other).not.toContain(`id="cfg-field-${entry.fieldId}"`); expect(own).toContain(escapeText(translations.t(entry.labelKey))); expect(own).toContain(escapeText(translations.t(entry.hintKey!))); - expect(entry.yamlKeys?.join('.')).toMatch(/^(routing|multimedia|oauth)\./); + expect(entry.yamlKeys?.join('.')).toMatch(/^(routing|multimedia|oauth|upstream|client)\./); } const oauth = render(createElement(SectionOAuthBehavior, props)); expect(oauth).toContain(' Date: Wed, 7 Oct 2026 01:11:22 +0800 Subject: [PATCH 070/142] fix(cliproxy): propagate credential version and registration epoch in execution results - Include `CredentialVersion` and `RegistrationEpoch` when recording execution results to prevent late failures from stale credentials or older registrations from cooling down or invalidating updated credentials - Update `Store` contract to ensure `CredentialVersion` remains immutable during persistence Closes: #6416 --- sdk/cliproxy/auth/conductor.go | 4 + sdk/cliproxy/auth/conductor_cooldown.go | 33 + sdk/cliproxy/auth/conductor_execution.go | 10 +- sdk/cliproxy/auth/conductor_home.go | 2 +- sdk/cliproxy/auth/conductor_issue6416_test.go | 846 ++++++++++++++++++ sdk/cliproxy/auth/conductor_lifecycle.go | 25 +- sdk/cliproxy/auth/conductor_persistence.go | 2 +- sdk/cliproxy/auth/conductor_stream.go | 16 +- sdk/cliproxy/auth/store.go | 4 +- sdk/cliproxy/auth/types.go | 2 + 10 files changed, 926 insertions(+), 18 deletions(-) create mode 100644 sdk/cliproxy/auth/conductor_issue6416_test.go diff --git a/sdk/cliproxy/auth/conductor.go b/sdk/cliproxy/auth/conductor.go index 785efcd7064..f90b0dd5ca4 100644 --- a/sdk/cliproxy/auth/conductor.go +++ b/sdk/cliproxy/auth/conductor.go @@ -74,6 +74,10 @@ type Result struct { // observed watermark. Count-tokens requests reuse the credential but are not // generation traffic; their response headers are not a generation snapshot. SkipQuotaObservation bool + // CredentialVersion captures the credential version under which the request was executed. + CredentialVersion uint64 + // RegistrationEpoch captures the registration epoch under which the request was executed. + RegistrationEpoch uint64 } // Selector chooses an auth candidate for execution. diff --git a/sdk/cliproxy/auth/conductor_cooldown.go b/sdk/cliproxy/auth/conductor_cooldown.go index 8e6f08461e3..4a97aa56f43 100644 --- a/sdk/cliproxy/auth/conductor_cooldown.go +++ b/sdk/cliproxy/auth/conductor_cooldown.go @@ -747,6 +747,17 @@ func cooldownReason(statusMessage string, quota QuotaState, lastErr *Error) stri return "" } +// isStaleExecutionResult reports whether an execution result originated from a superseded +// credential version or an earlier registration epoch than the currently active auth. +func isStaleExecutionResult(result Result, current *Auth) bool { + if current == nil { + return false + } + staleVersion := result.CredentialVersion < current.CredentialVersion && (result.CredentialVersion > 0 || current.CredentialVersion > 1) + staleEpoch := result.RegistrationEpoch > 0 && result.RegistrationEpoch < current.RegistrationEpoch + return staleVersion || staleEpoch +} + // MarkResult records an execution result and notifies hooks. func (m *Manager) MarkResult(ctx context.Context, result Result) { if result.AuthID == "" { @@ -773,6 +784,13 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) { defer releaseMutation() m.mu.Lock() if auth, ok := m.auths[result.AuthID]; ok && auth != nil { + if isStaleExecutionResult(result, auth) { + m.mu.Unlock() + releaseMutation() + m.hook.OnResult(ctx, result) + m.publishErrorEvent(result, nil) + return + } if modelKey == "" && strings.TrimSpace(result.RouteModel) != "" { if m != nil { modelKey = m.selectionModelKeyForAuth(auth, result.RouteModel) @@ -1075,6 +1093,14 @@ func (m *Manager) updateSessionAffinity(result Result) { } func (m *Manager) recordExecutionResult(ctx context.Context, result Result, auth *Auth, ephemeral bool) { + if auth != nil { + if result.CredentialVersion == 0 { + result.CredentialVersion = auth.CredentialVersion + } + if result.RegistrationEpoch == 0 { + result.RegistrationEpoch = auth.RegistrationEpoch + } + } if !ephemeral { m.MarkResult(ctx, result) return @@ -1106,6 +1132,13 @@ func (m *Manager) recordAvailabilityNeutralResult(ctx context.Context, result Re defer releaseMutation() m.mu.Lock() if auth, ok := m.auths[result.AuthID]; ok && auth != nil { + if isStaleExecutionResult(result, auth) { + m.mu.Unlock() + releaseMutation() + m.hook.OnResult(ctx, result) + m.publishErrorEvent(result, nil) + return + } now := time.Now() auth.recordRecentRequest(now, result.Success) if result.Success { diff --git a/sdk/cliproxy/auth/conductor_execution.go b/sdk/cliproxy/auth/conductor_execution.go index 9616a82176e..f90ba109c21 100644 --- a/sdk/cliproxy/auth/conductor_execution.go +++ b/sdk/cliproxy/auth/conductor_execution.go @@ -547,7 +547,7 @@ func (m *Manager) executeMixedOnce(ctx context.Context, providers []string, req if stateModel == "" { stateModel = canonicalModelKey(routeModel) } - result := Result{AuthID: auth.ID, Provider: provider, Model: stateModel, RouteModel: routeModel, Success: false, Error: resultErrorFromError(errPrepare), Options: pickOpts} + result := Result{AuthID: auth.ID, Provider: provider, Model: stateModel, RouteModel: routeModel, Success: false, Error: resultErrorFromError(errPrepare), Options: pickOpts, CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch} m.MarkResult(execCtx, result) lastErr = errPrepare continue @@ -628,7 +628,7 @@ func (m *Manager) executeMixedOnce(ctx context.Context, providers []string, req if errCancel := claudeOAuthRequestCancellation(execCtx, auth, errExec); errCancel != nil { return cliproxyexecutor.Response{}, errCancel } - result := Result{AuthID: auth.ID, Provider: provider, Model: resultModel, RouteModel: routeModel, Success: errExec == nil, Options: execOpts} + result := Result{AuthID: auth.ID, Provider: provider, Model: resultModel, RouteModel: routeModel, Success: errExec == nil, Options: execOpts, CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch} if errExec != nil { result.Error = resultErrorFromError(errExec) if ra := retryAfterFromError(errExec); ra != nil { @@ -759,7 +759,7 @@ func (m *Manager) executeCountMixedOnce(ctx context.Context, providers []string, if stateModel == "" { stateModel = canonicalModelKey(routeModel) } - result := Result{AuthID: auth.ID, Provider: provider, Model: stateModel, RouteModel: routeModel, Success: false, Error: resultErrorFromError(errPrepare), Options: pickOpts, SkipQuotaObservation: true} + result := Result{AuthID: auth.ID, Provider: provider, Model: stateModel, RouteModel: routeModel, Success: false, Error: resultErrorFromError(errPrepare), Options: pickOpts, SkipQuotaObservation: true, CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch} m.MarkResult(execCtx, result) lastErr = errPrepare continue @@ -840,7 +840,7 @@ func (m *Manager) executeCountMixedOnce(ctx context.Context, providers []string, if errCancel := claudeOAuthRequestCancellation(execCtx, auth, errExec); errCancel != nil { return cliproxyexecutor.Response{}, errCancel } - result := Result{AuthID: auth.ID, Provider: provider, Model: resultModel, RouteModel: routeModel, Success: errExec == nil, Options: execOpts, SkipQuotaObservation: true} + result := Result{AuthID: auth.ID, Provider: provider, Model: resultModel, RouteModel: routeModel, Success: errExec == nil, Options: execOpts, SkipQuotaObservation: true, CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch} if errExec != nil { result.Error = resultErrorFromError(errExec) if ra := retryAfterFromError(errExec); ra != nil { @@ -1104,7 +1104,7 @@ func (m *Manager) executeStreamMixedOnce(ctx context.Context, providers []string if stateModel == "" { stateModel = canonicalModelKey(routeModel) } - result := Result{AuthID: auth.ID, Provider: provider, Model: stateModel, RouteModel: routeModel, Success: false, Error: resultErrorFromError(errPrepare), Options: pickOpts} + result := Result{AuthID: auth.ID, Provider: provider, Model: stateModel, RouteModel: routeModel, Success: false, Error: resultErrorFromError(errPrepare), Options: pickOpts, CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch} if selection != nil { m.reportHomeResult(execCtx, result, auth) releaseAttempt() diff --git a/sdk/cliproxy/auth/conductor_home.go b/sdk/cliproxy/auth/conductor_home.go index 5d049e72a43..1ac4181cebd 100644 --- a/sdk/cliproxy/auth/conductor_home.go +++ b/sdk/cliproxy/auth/conductor_home.go @@ -1423,7 +1423,7 @@ func (m *Manager) tryAntigravityCreditsExecute(ctx context.Context, req cliproxy execReq.Model = upstreamModel creditsCtx = syncMetadataSessionToContext(creditsCtx, creditsOpts.Metadata) resp, errExec := c.executor.Execute(creditsCtx, c.auth, execReq, creditsOpts) - result := Result{AuthID: c.auth.ID, Provider: c.provider, Model: resultModel, RouteModel: routeModel, Success: errExec == nil, Options: creditsOpts} + result := Result{AuthID: c.auth.ID, Provider: c.provider, Model: resultModel, RouteModel: routeModel, Success: errExec == nil, Options: creditsOpts, CredentialVersion: c.auth.CredentialVersion, RegistrationEpoch: c.auth.RegistrationEpoch} if errExec != nil { result.Error = resultErrorFromError(errExec) if ra := retryAfterFromError(errExec); ra != nil { diff --git a/sdk/cliproxy/auth/conductor_issue6416_test.go b/sdk/cliproxy/auth/conductor_issue6416_test.go new file mode 100644 index 00000000000..2e065ddc4fc --- /dev/null +++ b/sdk/cliproxy/auth/conductor_issue6416_test.go @@ -0,0 +1,846 @@ +package auth + +import ( + "context" + "net/http" + "sync" + "testing" + "time" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" +) + +type issue6416TestExecutor struct { + id string + + mu sync.Mutex + onExecute func(auth *Auth) + onStream func(auth *Auth) +} + +func (e *issue6416TestExecutor) Identifier() string { return e.id } + +func (e *issue6416TestExecutor) Execute(_ context.Context, auth *Auth, _ cliproxyexecutor.Request, _ cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + e.mu.Lock() + onExec := e.onExecute + e.mu.Unlock() + if onExec != nil { + onExec(auth) + } + token := authAccessToken(auth) + if token == "old-access-token" || token == "old-api-key" { + return cliproxyexecutor.Response{}, &Error{ + HTTPStatus: http.StatusTooManyRequests, + Message: "rate limited on old credential", + } + } + if token == "invalid-old-token" { + return cliproxyexecutor.Response{}, &Error{ + HTTPStatus: http.StatusUnauthorized, + Message: "unauthorized on old token", + } + } + return cliproxyexecutor.Response{Payload: []byte(auth.ID + ":" + token)}, nil +} + +func (e *issue6416TestExecutor) ExecuteStream(ctx context.Context, auth *Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) { + e.mu.Lock() + onStream := e.onStream + e.mu.Unlock() + if onStream != nil { + onStream(auth) + } + token := authAccessToken(auth) + chunks := make(chan cliproxyexecutor.StreamChunk, 2) + chunks <- cliproxyexecutor.StreamChunk{Payload: []byte("chunk-1")} + if token == "old-access-token" { + chunks <- cliproxyexecutor.StreamChunk{ + Err: &Error{ + HTTPStatus: http.StatusTooManyRequests, + Message: "rate limited on old token", + }, + } + } else { + chunks <- cliproxyexecutor.StreamChunk{Payload: []byte("chunk-2")} + } + close(chunks) + return &cliproxyexecutor.StreamResult{Chunks: chunks}, nil +} + +func (e *issue6416TestExecutor) Refresh(ctx context.Context, auth *Auth) (*Auth, error) { + return auth, nil +} + +func (e *issue6416TestExecutor) CountTokens(ctx context.Context, auth *Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + return cliproxyexecutor.Response{}, nil +} + +func (e *issue6416TestExecutor) HttpRequest(ctx context.Context, auth *Auth, req *http.Request) (*http.Response, error) { + return nil, nil +} + +type issue6416MockStore struct { + mu sync.Mutex + records map[string]*Auth +} + +func (s *issue6416MockStore) Delete(context.Context, string) error { return nil } +func (s *issue6416MockStore) Save(_ context.Context, auth *Auth) (string, error) { + s.mu.Lock() + defer s.mu.Unlock() + if s.records == nil { + s.records = make(map[string]*Auth) + } + s.records[auth.ID] = auth.Clone() + return auth.ID + ".json", nil +} +func (s *issue6416MockStore) List(context.Context) ([]*Auth, error) { + s.mu.Lock() + defer s.mu.Unlock() + items := make([]*Auth, 0, len(s.records)) + for _, auth := range s.records { + items = append(items, auth.Clone()) + } + return items, nil +} + +// TestManager_Issue6416_LateResultBeforeCredentialUpdate_DoesNotCooldownNewCredential reproduces +// Issue #6416: +// When a request is started with an old token, and the auth is updated with a new access token +// while the request is in flight, a subsequent 429 from the old request must NOT cool down +// or mark unavailable the new credential. +func TestManager_Issue6416_LateResultBeforeCredentialUpdate_DoesNotCooldownNewCredential(t *testing.T) { + previous := quotaCooldownDisabled.Load() + quotaCooldownDisabled.Store(false) + t.Cleanup(func() { quotaCooldownDisabled.Store(previous) }) + + model := "gpt-5" + executor := &issue6416TestExecutor{id: "codex"} + m := NewManager(nil, nil, nil) + m.RegisterExecutor(executor) + + reg := registry.GetGlobalRegistry() + authID := "auth-issue-6416-exec" + reg.RegisterClient(authID, "codex", []*registry.ModelInfo{{ID: model, Created: time.Now().Unix()}}) + t.Cleanup(func() { reg.UnregisterClient(authID) }) + + initialAuth := &Auth{ + ID: authID, + Provider: "codex", + Metadata: map[string]any{ + "access_token": "old-access-token", + }, + } + if _, errRegister := m.Register(context.Background(), initialAuth); errRegister != nil { + t.Fatalf("register auth: %v", errRegister) + } + + execStarted := make(chan struct{}) + allowExecToFail := make(chan struct{}) + + executor.mu.Lock() + executor.onExecute = func(auth *Auth) { + select { + case <-execStarted: + default: + close(execStarted) + } + <-allowExecToFail + } + executor.mu.Unlock() + + reqDone := make(chan struct{}) + var execErr error + go func() { + defer close(reqDone) + _, execErr = m.Execute(context.Background(), []string{"codex"}, cliproxyexecutor.Request{Model: model}, cliproxyexecutor.Options{}) + }() + + // Wait until the request is in-flight within the executor. + <-execStarted + + // Replace the credential with a new access token while the request is in-flight. + currentAuth, ok := m.GetByID(authID) + if !ok || currentAuth == nil { + t.Fatal("auth not found") + } + updatedAuth := currentAuth.Clone() + updatedAuth.Metadata = map[string]any{ + "access_token": "new-access-token", + } + if _, errUpdate := m.Update(context.Background(), updatedAuth); errUpdate != nil { + t.Fatalf("update auth: %v", errUpdate) + } + + // Release the in-flight request, which will return 429 using the old token. + close(allowExecToFail) + <-reqDone + + if execErr == nil { + t.Fatal("expected in-flight request to fail with 429") + } + + // Verify the updated credential: the new credential must NOT be cooling or unavailable. + freshAuth, ok := m.GetByID(authID) + if !ok || freshAuth == nil { + t.Fatal("fresh auth not found") + } + if freshAuth.Unavailable { + t.Fatalf("fresh credential must not be marked unavailable by late result from old token") + } + if ms := freshAuth.ModelStates[model]; ms != nil { + if ms.Quota.Exceeded { + t.Fatalf("model state Quota.Exceeded = true, want false (new credential cooled down by old token 429)") + } + if ms.Unavailable { + t.Fatalf("model state Unavailable = true, want false (new credential marked unavailable by old token 429)") + } + if !ms.NextRetryAfter.IsZero() && ms.NextRetryAfter.After(time.Now()) { + t.Fatalf("model state NextRetryAfter = %v, want zero (new credential given cooldown deadline by old token 429)", ms.NextRetryAfter) + } + } +} + +// TestManager_Issue6416_LateStreamResultBeforeCredentialUpdate_DoesNotCooldownNewCredential tests +// that streaming responses where the stream fails with 429 after credentials were replaced +// do not cool down the newly installed credential. +func TestManager_Issue6416_LateStreamResultBeforeCredentialUpdate_DoesNotCooldownNewCredential(t *testing.T) { + previous := quotaCooldownDisabled.Load() + quotaCooldownDisabled.Store(false) + t.Cleanup(func() { quotaCooldownDisabled.Store(previous) }) + + model := "gpt-5" + executor := &issue6416TestExecutor{id: "codex"} + m := NewManager(nil, nil, nil) + m.RegisterExecutor(executor) + + reg := registry.GetGlobalRegistry() + authID := "auth-issue-6416-stream" + reg.RegisterClient(authID, "codex", []*registry.ModelInfo{{ID: model, Created: time.Now().Unix()}}) + t.Cleanup(func() { reg.UnregisterClient(authID) }) + + initialAuth := &Auth{ + ID: authID, + Provider: "codex", + Metadata: map[string]any{ + "access_token": "old-access-token", + }, + } + if _, errRegister := m.Register(context.Background(), initialAuth); errRegister != nil { + t.Fatalf("register auth: %v", errRegister) + } + + streamStarted := make(chan struct{}) + allowStreamToDeliver := make(chan struct{}) + + executor.mu.Lock() + executor.onStream = func(auth *Auth) { + select { + case <-streamStarted: + default: + close(streamStarted) + } + <-allowStreamToDeliver + } + executor.mu.Unlock() + + reqDone := make(chan struct{}) + var streamResult *cliproxyexecutor.StreamResult + var streamErr error + go func() { + defer close(reqDone) + streamResult, streamErr = m.ExecuteStream(context.Background(), []string{"codex"}, cliproxyexecutor.Request{Model: model}, cliproxyexecutor.Options{Stream: true}) + }() + + <-streamStarted + + // Replace the credential with a new access token while stream is in-flight. + currentAuth, ok := m.GetByID(authID) + if !ok || currentAuth == nil { + t.Fatal("auth not found") + } + updatedAuth := currentAuth.Clone() + updatedAuth.Metadata = map[string]any{ + "access_token": "new-access-token", + } + if _, errUpdate := m.Update(context.Background(), updatedAuth); errUpdate != nil { + t.Fatalf("update auth: %v", errUpdate) + } + + close(allowStreamToDeliver) + <-reqDone + + if streamErr != nil { + t.Fatalf("stream bootstrap failed: %v", streamErr) + } + if streamResult != nil { + for chunk := range streamResult.Chunks { + _ = chunk + } + } + + // Verify the updated credential: the new credential must NOT be cooling or unavailable. + freshAuth, ok := m.GetByID(authID) + if !ok || freshAuth == nil { + t.Fatal("fresh auth not found") + } + if freshAuth.Unavailable { + t.Fatalf("fresh credential must not be marked unavailable by late stream error from old token") + } + if ms := freshAuth.ModelStates[model]; ms != nil { + if ms.Quota.Exceeded { + t.Fatalf("model state Quota.Exceeded = true, want false (new credential cooled down by stream 429)") + } + if ms.Unavailable { + t.Fatalf("model state Unavailable = true, want false (new credential marked unavailable by stream 429)") + } + } +} + +// TestManager_Issue6416_LoadInitializesCredentialVersion tests that Manager.Load +// initializes CredentialVersion from store even when unpersisted (value 0), so that +// subsequent in-flight requests and updates track version changes correctly. +func TestManager_Issue6416_LoadInitializesCredentialVersion(t *testing.T) { + previous := quotaCooldownDisabled.Load() + quotaCooldownDisabled.Store(false) + t.Cleanup(func() { quotaCooldownDisabled.Store(previous) }) + + model := "gpt-5" + executor := &issue6416TestExecutor{id: "codex"} + authID := "auth-issue-6416-load" + + store := &issue6416MockStore{ + records: map[string]*Auth{ + authID: { + ID: authID, + Provider: "codex", + CredentialVersion: 0, // unpersisted on disk + Metadata: map[string]any{ + "access_token": "old-access-token", + }, + }, + }, + } + + m := NewManager(store, nil, nil) + m.RegisterExecutor(executor) + + reg := registry.GetGlobalRegistry() + reg.RegisterClient(authID, "codex", []*registry.ModelInfo{{ID: model, Created: time.Now().Unix()}}) + t.Cleanup(func() { reg.UnregisterClient(authID) }) + + if errLoad := m.Load(context.Background()); errLoad != nil { + t.Fatalf("Load error = %v", errLoad) + } + + loadedAuth, ok := m.GetByID(authID) + if !ok || loadedAuth == nil { + t.Fatal("auth not found after Load") + } + if loadedAuth.CredentialVersion != 1 { + t.Fatalf("loaded CredentialVersion = %d, want 1", loadedAuth.CredentialVersion) + } + + execStarted := make(chan struct{}) + allowExecToFail := make(chan struct{}) + + executor.mu.Lock() + executor.onExecute = func(auth *Auth) { + select { + case <-execStarted: + default: + close(execStarted) + } + <-allowExecToFail + } + executor.mu.Unlock() + + reqDone := make(chan struct{}) + go func() { + defer close(reqDone) + _, _ = m.Execute(context.Background(), []string{"codex"}, cliproxyexecutor.Request{Model: model}, cliproxyexecutor.Options{}) + }() + + <-execStarted + + // Update with new token + newAuth := loadedAuth.Clone() + newAuth.Metadata = map[string]any{"access_token": "new-access-token"} + updated, errUpdate := m.Update(context.Background(), newAuth) + if errUpdate != nil { + t.Fatalf("update: %v", errUpdate) + } + if updated.CredentialVersion != 2 { + t.Fatalf("updated CredentialVersion = %d, want 2", updated.CredentialVersion) + } + + close(allowExecToFail) + <-reqDone + + freshAuth, _ := m.GetByID(authID) + if freshAuth.Unavailable { + t.Fatalf("fresh credential must not be unavailable after late 429 from old token") + } + if ms := freshAuth.ModelStates[model]; ms != nil && ms.Quota.Exceeded { + t.Fatalf("fresh credential model must not be in cooldown after late 429 from old token") + } +} + +// TestManager_Issue6416_Late401ResultBeforeCredentialUpdate_DoesNotInvalidateNewCredential tests +// that in-flight requests that hit 401 on an invalidated old token do not mark the +// newly installed token as unauthorized or unavailable. +func TestManager_Issue6416_Late401ResultBeforeCredentialUpdate_DoesNotInvalidateNewCredential(t *testing.T) { + previous := quotaCooldownDisabled.Load() + quotaCooldownDisabled.Store(false) + t.Cleanup(func() { quotaCooldownDisabled.Store(previous) }) + + model := "gpt-5" + executor := &issue6416TestExecutor{id: "codex"} + m := NewManager(nil, nil, nil) + m.RegisterExecutor(executor) + + reg := registry.GetGlobalRegistry() + authID := "auth-issue-6416-401" + reg.RegisterClient(authID, "codex", []*registry.ModelInfo{{ID: model, Created: time.Now().Unix()}}) + t.Cleanup(func() { reg.UnregisterClient(authID) }) + + initialAuth := &Auth{ + ID: authID, + Provider: "codex", + Status: StatusActive, + Metadata: map[string]any{"access_token": "invalid-old-token"}, + } + if _, errRegister := m.Register(context.Background(), initialAuth); errRegister != nil { + t.Fatalf("register: %v", errRegister) + } + + execStarted := make(chan struct{}) + allowExecToFail := make(chan struct{}) + + executor.mu.Lock() + executor.onExecute = func(auth *Auth) { + select { + case <-execStarted: + default: + close(execStarted) + } + <-allowExecToFail + } + executor.mu.Unlock() + + reqDone := make(chan struct{}) + go func() { + defer close(reqDone) + _, _ = m.Execute(context.Background(), []string{"codex"}, cliproxyexecutor.Request{Model: model}, cliproxyexecutor.Options{}) + }() + + <-execStarted + + currentAuth, _ := m.GetByID(authID) + newAuth := currentAuth.Clone() + newAuth.Metadata = map[string]any{"access_token": "valid-new-token"} + if _, errUpdate := m.Update(context.Background(), newAuth); errUpdate != nil { + t.Fatalf("update: %v", errUpdate) + } + + close(allowExecToFail) + <-reqDone + + freshAuth, _ := m.GetByID(authID) + if freshAuth.Unavailable { + t.Fatalf("fresh credential must not be unavailable after late 401 from old token") + } + if freshAuth.Status == StatusError { + t.Fatalf("fresh credential status must not be StatusError, got %q", freshAuth.Status) + } + if ms := freshAuth.ModelStates[model]; ms != nil && ms.Unavailable { + t.Fatalf("model state must not be unavailable after late 401 from old token") + } +} + +// TestManager_Issue6416_APIKeyRotation_LateResultDoesNotCooldownNewAPIKey tests +// that rotating an API key (without refresh token) properly increments CredentialVersion +// and isolates the new API key from in-flight failures of the old API key. +func TestManager_Issue6416_APIKeyRotation_LateResultDoesNotCooldownNewAPIKey(t *testing.T) { + previous := quotaCooldownDisabled.Load() + quotaCooldownDisabled.Store(false) + t.Cleanup(func() { quotaCooldownDisabled.Store(previous) }) + + model := "gpt-5" + executor := &issue6416TestExecutor{id: "codex"} + m := NewManager(nil, nil, nil) + m.RegisterExecutor(executor) + + reg := registry.GetGlobalRegistry() + authID := "auth-issue-6416-apikey" + reg.RegisterClient(authID, "codex", []*registry.ModelInfo{{ID: model, Created: time.Now().Unix()}}) + t.Cleanup(func() { reg.UnregisterClient(authID) }) + + initialAuth := &Auth{ + ID: authID, + Provider: "codex", + Attributes: map[string]string{ + AttributeAPIKey: "old-api-key", + }, + } + registered, errRegister := m.Register(context.Background(), initialAuth) + if errRegister != nil { + t.Fatalf("register: %v", errRegister) + } + if registered.CredentialVersion != 1 { + t.Fatalf("registered CredentialVersion = %d, want 1", registered.CredentialVersion) + } + + execStarted := make(chan struct{}) + allowExecToFail := make(chan struct{}) + + executor.mu.Lock() + executor.onExecute = func(auth *Auth) { + select { + case <-execStarted: + default: + close(execStarted) + } + <-allowExecToFail + } + executor.mu.Unlock() + + reqDone := make(chan struct{}) + go func() { + defer close(reqDone) + _, _ = m.Execute(context.Background(), []string{"codex"}, cliproxyexecutor.Request{Model: model}, cliproxyexecutor.Options{}) + }() + + <-execStarted + + currentAuth, _ := m.GetByID(authID) + newAuth := currentAuth.Clone() + newAuth.Attributes = map[string]string{ + AttributeAPIKey: "new-api-key", + } + updated, errUpdate := m.Update(context.Background(), newAuth) + if errUpdate != nil { + t.Fatalf("update: %v", errUpdate) + } + if updated.CredentialVersion != 2 { + t.Fatalf("updated CredentialVersion = %d, want 2", updated.CredentialVersion) + } + + close(allowExecToFail) + <-reqDone + + freshAuth, _ := m.GetByID(authID) + if freshAuth.Unavailable { + t.Fatalf("fresh API key must not be unavailable after late 429 from old key") + } + if ms := freshAuth.ModelStates[model]; ms != nil && ms.Quota.Exceeded { + t.Fatalf("fresh API key model must not be in cooldown after late 429 from old key") + } +} + +// TestManager_Issue6416_DirectMarkResult_StaleCredentialVersionIgnored verifies that +// MarkResult directly ignores availability and cooldown effects when CredentialVersion +// is older than the current registered auth, even if result version is 0 when auth version > 1. +func TestManager_Issue6416_DirectMarkResult_StaleCredentialVersionIgnored(t *testing.T) { + previous := quotaCooldownDisabled.Load() + quotaCooldownDisabled.Store(false) + t.Cleanup(func() { quotaCooldownDisabled.Store(previous) }) + + model := "gpt-5" + m := NewManager(nil, nil, nil) + authID := "auth-direct-stale-version" + + reg := registry.GetGlobalRegistry() + reg.RegisterClient(authID, "codex", []*registry.ModelInfo{{ID: model, Created: time.Now().Unix()}}) + t.Cleanup(func() { reg.UnregisterClient(authID) }) + + initialAuth := &Auth{ + ID: authID, + Provider: "codex", + Metadata: map[string]any{"access_token": "token-v1"}, + } + registered, errRegister := m.Register(context.Background(), initialAuth) + if errRegister != nil { + t.Fatalf("register: %v", errRegister) + } + if registered.CredentialVersion != 1 { + t.Fatalf("registered CredentialVersion = %d, want 1", registered.CredentialVersion) + } + + // Update credentials to version 2. + updatedAuth := registered.Clone() + updatedAuth.Metadata = map[string]any{"access_token": "token-v2"} + updated, errUpdate := m.Update(context.Background(), updatedAuth) + if errUpdate != nil { + t.Fatalf("update: %v", errUpdate) + } + if updated.CredentialVersion != 2 { + t.Fatalf("updated CredentialVersion = %d, want 2", updated.CredentialVersion) + } + + // Stale MarkResult with CredentialVersion = 1 and 429 error. + m.MarkResult(context.Background(), Result{ + AuthID: authID, + Provider: "codex", + Model: model, + Success: false, + CredentialVersion: 1, + Error: &Error{HTTPStatus: http.StatusTooManyRequests, Message: "stale 429"}, + }) + + afterStale, _ := m.GetByID(authID) + if afterStale.Unavailable { + t.Fatalf("afterStale must not be unavailable after stale MarkResult (v1)") + } + if ms := afterStale.ModelStates[model]; ms != nil && ms.Quota.Exceeded { + t.Fatalf("afterStale model state must not be in quota cooldown after stale MarkResult (v1)") + } + + // Stale MarkResult with CredentialVersion = 0 (unversioned in-flight snapshot) and 429 error. + m.MarkResult(context.Background(), Result{ + AuthID: authID, + Provider: "codex", + Model: model, + Success: false, + CredentialVersion: 0, + Error: &Error{HTTPStatus: http.StatusTooManyRequests, Message: "stale 429 v0"}, + }) + + afterStaleZero, _ := m.GetByID(authID) + if afterStaleZero.Unavailable { + t.Fatalf("afterStaleZero must not be unavailable after stale MarkResult (v0)") + } + if ms := afterStaleZero.ModelStates[model]; ms != nil && ms.Quota.Exceeded { + t.Fatalf("afterStaleZero model state must not be in quota cooldown after stale MarkResult (v0)") + } + + // Current MarkResult with CredentialVersion = 2 and 429 error must apply cooldown. + m.MarkResult(context.Background(), Result{ + AuthID: authID, + Provider: "codex", + Model: model, + Success: false, + CredentialVersion: 2, + Error: &Error{HTTPStatus: http.StatusTooManyRequests, Message: "current 429"}, + }) + + afterCurrent, _ := m.GetByID(authID) + ms := afterCurrent.ModelStates[model] + if ms == nil || !ms.Quota.Exceeded { + t.Fatalf("afterCurrent model state must be in quota cooldown after current MarkResult, got %+v", ms) + } +} + +// TestManager_Issue6416_DirectMarkResult_StaleRegistrationEpochIgnored verifies that +// MarkResult directly ignores results from a previous registration epoch. +func TestManager_Issue6416_DirectMarkResult_StaleRegistrationEpochIgnored(t *testing.T) { + previous := quotaCooldownDisabled.Load() + quotaCooldownDisabled.Store(false) + t.Cleanup(func() { quotaCooldownDisabled.Store(previous) }) + + model := "gpt-5" + m := NewManager(nil, nil, nil) + authID := "auth-direct-stale-epoch" + + reg := registry.GetGlobalRegistry() + reg.RegisterClient(authID, "codex", []*registry.ModelInfo{{ID: model, Created: time.Now().Unix()}}) + t.Cleanup(func() { reg.UnregisterClient(authID) }) + + initialAuth := &Auth{ + ID: authID, + Provider: "codex", + Metadata: map[string]any{"access_token": "token-v1"}, + } + registered, errRegister := m.Register(context.Background(), initialAuth) + if errRegister != nil { + t.Fatalf("register: %v", errRegister) + } + epoch1 := registered.RegistrationEpoch + + // Remove and re-register to advance RegistrationEpoch. + m.Remove(context.Background(), authID) + reRegistered, errReReg := m.Register(context.Background(), initialAuth.Clone()) + if errReReg != nil { + t.Fatalf("re-register: %v", errReReg) + } + epoch2 := reRegistered.RegistrationEpoch + if epoch2 <= epoch1 { + t.Fatalf("expected epoch2 (%d) > epoch1 (%d)", epoch2, epoch1) + } + + // Stale MarkResult with epoch1 and 429 error must be ignored. + m.MarkResult(context.Background(), Result{ + AuthID: authID, + Provider: "codex", + Model: model, + Success: false, + RegistrationEpoch: epoch1, + Error: &Error{HTTPStatus: http.StatusTooManyRequests, Message: "stale epoch 429"}, + }) + + afterStale, _ := m.GetByID(authID) + if afterStale.Unavailable { + t.Fatalf("afterStale must not be unavailable after stale epoch MarkResult") + } + if ms := afterStale.ModelStates[model]; ms != nil && ms.Quota.Exceeded { + t.Fatalf("afterStale model state must not be in quota cooldown after stale epoch MarkResult") + } +} + +// TestManager_Issue6416_LateResultBeforeCredentialUpdate_PreservesSessionAffinity verifies +// that late failures from an older credential version do not unseat or tear down +// session affinity bindings on the updated credential. +func TestManager_Issue6416_LateResultBeforeCredentialUpdate_PreservesSessionAffinity(t *testing.T) { + previous := quotaCooldownDisabled.Load() + quotaCooldownDisabled.Store(false) + t.Cleanup(func() { quotaCooldownDisabled.Store(previous) }) + + model := "gpt-5" + fallback := &RoundRobinSelector{} + selector := NewSessionAffinitySelector(fallback) + m := NewManager(nil, selector, nil) + + authID := "auth-session-affinity" + reg := registry.GetGlobalRegistry() + reg.RegisterClient(authID, "codex", []*registry.ModelInfo{{ID: model, Created: time.Now().Unix()}}) + t.Cleanup(func() { reg.UnregisterClient(authID) }) + + initialAuth := &Auth{ + ID: authID, + Provider: "codex", + Status: StatusActive, + Metadata: map[string]any{"access_token": "token-v1"}, + } + registered, errRegister := m.Register(context.Background(), initialAuth) + if errRegister != nil { + t.Fatalf("register: %v", errRegister) + } + + sessionID := "test-session-123" + opts := cliproxyexecutor.Options{ + Headers: http.Header{ + "X-Session-Id": []string{sessionID}, + }, + } + + // First execution succeeds and establishes affinity binding. + m.MarkResult(context.Background(), Result{ + AuthID: authID, + Provider: "codex", + Model: model, + Success: true, + CredentialVersion: registered.CredentialVersion, + Options: opts, + }) + + // Pick with session ID must select authID. + picked, errPick := selector.Pick(context.Background(), "codex", model, opts, []*Auth{registered}) + if errPick != nil || picked == nil || picked.ID != authID { + t.Fatalf("expected selector to pick %s via affinity, got %v (err=%v)", authID, picked, errPick) + } + + // Update credentials to version 2. + updatedAuth := registered.Clone() + updatedAuth.Metadata = map[string]any{"access_token": "token-v2"} + updated, errUpdate := m.Update(context.Background(), updatedAuth) + if errUpdate != nil { + t.Fatalf("update: %v", errUpdate) + } + + // Stale failure from version 1 arrives with 429 error. + m.MarkResult(context.Background(), Result{ + AuthID: authID, + Provider: "codex", + Model: model, + Success: false, + CredentialVersion: 1, + Error: &Error{HTTPStatus: http.StatusTooManyRequests, Message: "stale 429"}, + Options: opts, + }) + + // Session affinity must still be preserved for the new credential version. + pickedAfter, errPickAfter := selector.Pick(context.Background(), "codex", model, opts, []*Auth{updated}) + if errPickAfter != nil || pickedAfter == nil || pickedAfter.ID != authID { + t.Fatalf("expected session affinity to remain preserved after stale MarkResult, got %v (err=%v)", pickedAfter, errPickAfter) + } +} + +// TestManager_Issue6416_NonSecretUpdate_PreservesVersionAndAppliesCooldown verifies +// that updating non-secret fields (like Label or ProxyURL) does not advance CredentialVersion, +// ensuring in-flight failures correctly cool down the credential. +func TestManager_Issue6416_NonSecretUpdate_PreservesVersionAndAppliesCooldown(t *testing.T) { + previous := quotaCooldownDisabled.Load() + quotaCooldownDisabled.Store(false) + t.Cleanup(func() { quotaCooldownDisabled.Store(previous) }) + + model := "gpt-5" + executor := &issue6416TestExecutor{id: "codex"} + m := NewManager(nil, nil, nil) + m.RegisterExecutor(executor) + + reg := registry.GetGlobalRegistry() + authID := "auth-nonsecret-update" + reg.RegisterClient(authID, "codex", []*registry.ModelInfo{{ID: model, Created: time.Now().Unix()}}) + t.Cleanup(func() { reg.UnregisterClient(authID) }) + + initialAuth := &Auth{ + ID: authID, + Provider: "codex", + Metadata: map[string]any{ + "access_token": "old-access-token", + }, + Label: "initial-label", + } + registered, errRegister := m.Register(context.Background(), initialAuth) + if errRegister != nil { + t.Fatalf("register: %v", errRegister) + } + if registered.CredentialVersion != 1 { + t.Fatalf("registered CredentialVersion = %d, want 1", registered.CredentialVersion) + } + + execStarted := make(chan struct{}) + allowExecToFail := make(chan struct{}) + + executor.mu.Lock() + executor.onExecute = func(auth *Auth) { + select { + case <-execStarted: + default: + close(execStarted) + } + <-allowExecToFail + } + executor.mu.Unlock() + + reqDone := make(chan struct{}) + go func() { + defer close(reqDone) + _, _ = m.Execute(context.Background(), []string{"codex"}, cliproxyexecutor.Request{Model: model}, cliproxyexecutor.Options{}) + }() + + <-execStarted + + // Update non-secret metadata (Label only, token unchanged). + currentAuth, _ := m.GetByID(authID) + nonSecretAuth := currentAuth.Clone() + nonSecretAuth.Label = "updated-label" + updated, errUpdate := m.Update(context.Background(), nonSecretAuth) + if errUpdate != nil { + t.Fatalf("update: %v", errUpdate) + } + if updated.CredentialVersion != 1 { + t.Fatalf("expected CredentialVersion to remain 1 after non-secret update, got %d", updated.CredentialVersion) + } + + close(allowExecToFail) + <-reqDone + + // Because secret was not replaced, 429 should cool down the credential. + finalAuth, _ := m.GetByID(authID) + ms := finalAuth.ModelStates[model] + if ms == nil || !ms.Quota.Exceeded { + t.Fatalf("expected model to be in quota cooldown when secrets were unchanged, got %+v", ms) + } +} diff --git a/sdk/cliproxy/auth/conductor_lifecycle.go b/sdk/cliproxy/auth/conductor_lifecycle.go index 3106f801ed7..af5c4600c0a 100644 --- a/sdk/cliproxy/auth/conductor_lifecycle.go +++ b/sdk/cliproxy/auth/conductor_lifecycle.go @@ -119,6 +119,11 @@ func (m *Manager) Register(ctx context.Context, auth *Auth) (*Auth, error) { } m.authEpochs[auth.ID]++ auth.RegistrationEpoch = m.authEpochs[auth.ID] + if existing, exists := m.auths[auth.ID]; exists && existing != nil { + auth.CredentialVersion = max(auth.CredentialVersion, existing.CredentialVersion) + 1 + } else if auth.CredentialVersion == 0 { + auth.CredentialVersion = 1 + } auth.Generation = 1 // Serialize this credential, but release the manager lock during store I/O. // Persist failures stay non-fatal, but must not be silent: a restart would @@ -243,12 +248,21 @@ func (m *Manager) updateInternal(ctx context.Context, base, auth *Auth, mode upd } else { auth.Generation++ } + existingVersion := existing.CredentialVersion + if existingVersion == 0 { + existingVersion = 1 + } + credChanged := CredentialsChanged(existing, auth) + if credChanged { + auth.CredentialVersion = max(auth.CredentialVersion, existingVersion) + 1 + } else { + auth.CredentialVersion = existingVersion + } cooldownStateChanged := false if !existing.Disabled && existing.Status != StatusDisabled && !auth.Disabled && auth.Status != StatusDisabled { if len(auth.ModelStates) == 0 && len(existing.ModelStates) > 0 { auth.ModelStates = existing.ModelStates } - credChanged := CredentialsChanged(existing, auth) if credChanged || mode == updateModeRefresh { auth.RejectedAccessToken = "" if hasUnauthorizedAuthFailure(existing) || (auth.LastError != nil && isUnauthorizedError(auth.LastError)) { @@ -443,6 +457,15 @@ func (m *Manager) Load(ctx context.Context) error { m.authEpochs[auth.ID] = max(m.authEpochs[auth.ID], auth.RegistrationEpoch) + 1 auth.RegistrationEpoch = m.authEpochs[auth.ID] auth.Generation = 1 + if prev, exists := previousAuths[auth.ID]; exists && prev != nil { + auth.CredentialVersion = max(auth.CredentialVersion, prev.CredentialVersion) + if CredentialsChanged(prev, auth) { + auth.CredentialVersion++ + } + } + if auth.CredentialVersion == 0 { + auth.CredentialVersion = 1 + } m.auths[auth.ID] = auth.Clone() } diff --git a/sdk/cliproxy/auth/conductor_persistence.go b/sdk/cliproxy/auth/conductor_persistence.go index e647ec1c620..426ef69c88e 100644 --- a/sdk/cliproxy/auth/conductor_persistence.go +++ b/sdk/cliproxy/auth/conductor_persistence.go @@ -68,7 +68,7 @@ func mergeAuthSaveDelta(target, before, after *Auth, preserveConcurrent bool) { next := reflect.ValueOf(after).Elem() for i := 0; i < dst.NumField(); i++ { field := dst.Type().Field(i) - if field.PkgPath != "" || field.Name == "ID" || field.Name == "RegistrationEpoch" || field.Name == "Generation" || field.Name == "RejectedAccessToken" { + if field.PkgPath != "" || field.Name == "ID" || field.Name == "RegistrationEpoch" || field.Name == "CredentialVersion" || field.Name == "Generation" || field.Name == "RejectedAccessToken" { continue } d, b, n := dst.Field(i), base.Field(i), next.Field(i) diff --git a/sdk/cliproxy/auth/conductor_stream.go b/sdk/cliproxy/auth/conductor_stream.go index 1e0137b9aa4..565c8d2f74e 100644 --- a/sdk/cliproxy/auth/conductor_stream.go +++ b/sdk/cliproxy/auth/conductor_stream.go @@ -138,7 +138,7 @@ func (m *Manager) wrapStreamResult(ctx context.Context, auth *Auth, provider, re warnLogUpstreamFailure(ctx, entry, provider, resultModel, auth, time.Since(streamStart), chunk.Err) rerr := resultErrorFromError(chunk.Err) action, okAction := matchRequestScopedErrorAction(auth, chunk.Err, m.runtimeConfigSnapshot()) - result := Result{AuthID: auth.ID, Provider: provider, Model: resultModel, RouteModel: routeModel, Success: false, Error: rerr, Options: opts} + result := Result{AuthID: auth.ID, Provider: provider, Model: resultModel, RouteModel: routeModel, Success: false, Error: rerr, Options: opts, CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch} result.RetryAfter = retryAfterFromError(chunk.Err) result.CredentialScope = isCredentialScopedError(chunk.Err) applyRequestScopedActionToResult(action, okAction, &result) @@ -199,7 +199,7 @@ func (m *Manager) wrapStreamResult(ctx context.Context, auth *Auth, provider, re } } if !failed && (ephemeralResult || claudeOAuthRequestCancellation(ctx, auth, nil) == nil) { - m.recordExecutionResult(ctx, Result{AuthID: auth.ID, Provider: provider, Model: resultModel, RouteModel: routeModel, Success: true, Options: opts}, auth, ephemeralResult) + m.recordExecutionResult(ctx, Result{AuthID: auth.ID, Provider: provider, Model: resultModel, RouteModel: routeModel, Success: true, Options: opts, CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch}, auth, ephemeralResult) } }() return &cliproxyexecutor.StreamResult{Headers: headers, Chunks: out} @@ -289,7 +289,7 @@ func (m *Manager) executeStreamWithModelPool(ctx context.Context, executor Provi if errStream != nil { rerr := resultErrorFromError(errStream) action, okAction := matchRequestScopedErrorAction(auth, errStream, m.runtimeConfigSnapshot()) - result := Result{AuthID: auth.ID, Provider: provider, Model: resultModel, RouteModel: routeModel, Success: false, Error: rerr, Options: execOpts} + result := Result{AuthID: auth.ID, Provider: provider, Model: resultModel, RouteModel: routeModel, Success: false, Error: rerr, Options: execOpts, CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch} result.RetryAfter = retryAfterFromError(errStream) if isCredentialScopedError(errStream) { result.CredentialScope = true @@ -375,7 +375,7 @@ func (m *Manager) executeStreamWithModelPool(ctx context.Context, executor Provi action, okAction := matchRequestScopedErrorAction(auth, bootstrapErr, m.runtimeConfigSnapshot()) if okAction { rerr := resultErrorFromError(bootstrapErr) - result := Result{AuthID: auth.ID, Provider: provider, Model: resultModel, RouteModel: routeModel, Success: false, Error: rerr, Options: execOpts} + result := Result{AuthID: auth.ID, Provider: provider, Model: resultModel, RouteModel: routeModel, Success: false, Error: rerr, Options: execOpts, CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch} result.RetryAfter = retryAfterFromError(bootstrapErr) if isCredentialScopedError(bootstrapErr) { result.CredentialScope = true @@ -395,7 +395,7 @@ func (m *Manager) executeStreamWithModelPool(ctx context.Context, executor Provi } if isRequestInvalidError(bootstrapErr) { rerr := resultErrorFromError(bootstrapErr) - result := Result{AuthID: auth.ID, Provider: provider, Model: resultModel, RouteModel: routeModel, Success: false, Error: rerr, Options: execOpts} + result := Result{AuthID: auth.ID, Provider: provider, Model: resultModel, RouteModel: routeModel, Success: false, Error: rerr, Options: execOpts, CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch} result.RetryAfter = retryAfterFromError(bootstrapErr) if isCredentialScopedError(bootstrapErr) { result.CredentialScope = true @@ -406,7 +406,7 @@ func (m *Manager) executeStreamWithModelPool(ctx context.Context, executor Provi } if idx < len(execModels)-1 { rerr := resultErrorFromError(bootstrapErr) - result := Result{AuthID: auth.ID, Provider: provider, Model: resultModel, RouteModel: routeModel, Success: false, Error: rerr, Options: execOpts} + result := Result{AuthID: auth.ID, Provider: provider, Model: resultModel, RouteModel: routeModel, Success: false, Error: rerr, Options: execOpts, CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch} result.RetryAfter = retryAfterFromError(bootstrapErr) if isCredentialScopedError(bootstrapErr) { result.CredentialScope = true @@ -421,7 +421,7 @@ func (m *Manager) executeStreamWithModelPool(ctx context.Context, executor Provi continue } rerr := resultErrorFromError(bootstrapErr) - result := Result{AuthID: auth.ID, Provider: provider, Model: resultModel, RouteModel: routeModel, Success: false, Error: rerr, Options: execOpts} + result := Result{AuthID: auth.ID, Provider: provider, Model: resultModel, RouteModel: routeModel, Success: false, Error: rerr, Options: execOpts, CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch} result.RetryAfter = retryAfterFromError(bootstrapErr) if isCredentialScopedError(bootstrapErr) { result.CredentialScope = true @@ -439,7 +439,7 @@ func (m *Manager) executeStreamWithModelPool(ctx context.Context, executor Provi upstreamErr = currentErr } warnLogUpstreamFailure(ctx, entry, provider, execModel, auth, time.Since(startStream), emptyErr) - result := Result{AuthID: auth.ID, Provider: provider, Model: resultModel, RouteModel: routeModel, Success: false, Error: resultErrorFromError(emptyErr), Options: execOpts} + result := Result{AuthID: auth.ID, Provider: provider, Model: resultModel, RouteModel: routeModel, Success: false, Error: resultErrorFromError(emptyErr), Options: execOpts, CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch} m.recordExecutionResult(ctx, result, auth, ephemeralResult) if idx < len(execModels)-1 { lastErr = emptyErr diff --git a/sdk/cliproxy/auth/store.go b/sdk/cliproxy/auth/store.go index 83e401dfa0f..a903a46bf3a 100644 --- a/sdk/cliproxy/auth/store.go +++ b/sdk/cliproxy/auth/store.go @@ -7,8 +7,8 @@ type Store interface { // List returns all auth records stored in the backend. List(ctx context.Context) ([]*Auth, error) // Save persists the provided auth record, replacing any existing one with same ID. - // It may enrich exported fields, but must not change ID, RegistrationEpoch or - // Generation. The manager merges these changes even on non-fatal save errors. + // It may enrich exported fields, but must not change ID, RegistrationEpoch, + // CredentialVersion or Generation. The manager merges these changes even on non-fatal save errors. // Do not retain auth or mutate shared nested values in place: replace metadata // values, pointers, Storage and Runtime instead. Auth.Clone shares these objects. // Save may call manager read APIs, but must not synchronously mutate the diff --git a/sdk/cliproxy/auth/types.go b/sdk/cliproxy/auth/types.go index 2db42e28878..70715622d36 100644 --- a/sdk/cliproxy/auth/types.go +++ b/sdk/cliproxy/auth/types.go @@ -50,6 +50,8 @@ type Auth struct { ID string `json:"id"` // RegistrationEpoch tracks monotonic registration cycles across unregister/re-register. RegistrationEpoch uint64 `json:"registration_epoch,omitempty"` + // CredentialVersion tracks monotonic credential replacements for secret material. + CredentialVersion uint64 `json:"credential_version,omitempty"` // Generation tracks monotonic mutations to resolve scheduler/reconcile snapshot races. Generation uint64 `json:"generation,omitempty"` // Index is a stable runtime identifier derived from auth metadata (not persisted). From bb324614ff0740dafc462f2b96c8f838131c7694 Mon Sep 17 00:00:00 2001 From: Supra4E8C Date: Wed, 7 Oct 2026 01:11:24 +0800 Subject: [PATCH 071/142] fix(config): point migrated OAuth settings at upstream.* paths Backend config_v8.go relocated shared provider behavior out of oauth.providers.* to upstream.* (v8SharedPaths): Codex cloaking, model-level cooling, stream bootstrap, orphan delegation and response steering; Claude model-level cooling, cloak mode, cloaking model list and header-defaults; and xAI inject-x-search. Read and write the canonical paths so the panel reflects the values the runtime actually applies; the backend still accepts and migrates legacy spellings. OAuth-only fields (Codex live-media-relay and header-defaults, Antigravity, aistudio, devin) keep their oauth.providers.* paths. --- src/features/config/searchIndex.ts | 36 ++++++++++---------- src/features/config/visualConfigAdditions.ts | 25 +++++++------- src/hooks/useVisualConfig.ts | 23 +++++++------ tests/configFieldParity.test.ts | 3 ++ tests/visualConfigDurationFallback.test.ts | 2 +- 5 files changed, 47 insertions(+), 42 deletions(-) diff --git a/src/features/config/searchIndex.ts b/src/features/config/searchIndex.ts index b17f01b229e..dd08fa7a514 100644 --- a/src/features/config/searchIndex.ts +++ b/src/features/config/searchIndex.ts @@ -70,56 +70,56 @@ export const CONFIG_FIELD_SEARCH_INDEX: ConfigFieldSearchEntry[] = [ sectionId: 'advanced', labelKey: L('additions.claudeHeaderTimezone.label'), hintKey: L('additions.claudeHeaderTimezone.hint'), - yamlKeys: ['oauth', 'providers', 'claude', 'header-defaults', 'timezone'], + yamlKeys: ['upstream', 'claude', 'header-defaults', 'timezone'], }, { fieldId: 'claudeModelLevelCooling', sectionId: 'advanced', labelKey: L('additions.claudeModelLevelCooling.label'), hintKey: L('additions.claudeModelLevelCooling.hint'), - yamlKeys: ['oauth', 'providers', 'claude', 'model-level-cooling'], + yamlKeys: ['upstream', 'claude', 'model-level-cooling'], }, { fieldId: 'claudeDisableCloakMode', sectionId: 'advanced', labelKey: L('additions.claudeDisableCloakMode.label'), hintKey: L('additions.claudeDisableCloakMode.hint'), - yamlKeys: ['oauth', 'providers', 'claude', 'disable-claude-cloak-mode'], + yamlKeys: ['upstream', 'claude', 'disable-claude-cloak-mode'], }, { fieldId: 'claudeCodeDisableCloakingModelList', sectionId: 'advanced', labelKey: L('additions.claudeCodeDisableCloakingModelList.label'), hintKey: L('additions.claudeCodeDisableCloakingModelList.hint'), - yamlKeys: ['oauth', 'providers', 'claude', 'claude-code', 'disable-cloaking-model-list'], + yamlKeys: ['upstream', 'claude', 'disable-cloaking-model-list'], }, { fieldId: 'codexDisableCloaking', sectionId: 'advanced', labelKey: L('additions.codexDisableCloaking.label'), hintKey: L('additions.codexDisableCloaking.hint'), - yamlKeys: ['oauth', 'providers', 'codex', 'disable-codex-cloaking'], + yamlKeys: ['upstream', 'codex', 'disable-codex-cloaking'], }, { fieldId: 'codexModelLevelCooling', sectionId: 'advanced', labelKey: L('additions.codexModelLevelCooling.label'), hintKey: L('additions.codexModelLevelCooling.hint'), - yamlKeys: ['oauth', 'providers', 'codex', 'model-level-cooling'], + yamlKeys: ['upstream', 'codex', 'model-level-cooling'], }, { fieldId: 'codexStreamBootstrapBuffering', sectionId: 'advanced', labelKey: L('additions.codexStreamBootstrapBuffering.label'), hintKey: L('additions.codexStreamBootstrapBuffering.hint'), - yamlKeys: ['oauth', 'providers', 'codex', 'stream-bootstrap-buffering'], + yamlKeys: ['upstream', 'codex', 'stream-bootstrap-buffering'], }, { fieldId: 'codexStreamBootstrapTimeout', sectionId: 'advanced', labelKey: L('additions.codexStreamBootstrapTimeout.label'), hintKey: L('additions.codexStreamBootstrapTimeout.hint'), - yamlKeys: ['oauth', 'providers', 'codex', 'stream-bootstrap-timeout'], + yamlKeys: ['upstream', 'codex', 'stream-bootstrap-timeout'], }, { fieldId: 'codexOptimizeMultiAgentV2', @@ -133,14 +133,14 @@ export const CONFIG_FIELD_SEARCH_INDEX: ConfigFieldSearchEntry[] = [ sectionId: 'advanced', labelKey: L('additions.codexOrphanDelegationCompatibility.label'), hintKey: L('additions.codexOrphanDelegationCompatibility.hint'), - yamlKeys: ['oauth', 'providers', 'codex', 'orphan-delegation-compatibility'], + yamlKeys: ['upstream', 'codex', 'orphan-delegation-compatibility'], }, { fieldId: 'codexResponseSteering', sectionId: 'advanced', labelKey: L('additions.codexResponseSteering.label'), hintKey: L('additions.codexResponseSteering.hint'), - yamlKeys: ['oauth', 'providers', 'codex', 'response-steering'], + yamlKeys: ['upstream', 'codex', 'response-steering'], }, { fieldId: 'antigravityConnectionPoolEnabled', @@ -168,7 +168,7 @@ export const CONFIG_FIELD_SEARCH_INDEX: ConfigFieldSearchEntry[] = [ sectionId: 'advanced', labelKey: L('additions.xaiInjectXSearch.label'), hintKey: L('additions.xaiInjectXSearch.hint'), - yamlKeys: ['oauth', 'providers', 'xai', 'inject-x-search'], + yamlKeys: ['upstream', 'xai', 'inject-x-search'], }, { fieldId: 'codexLiveMediaRelayEnabled', @@ -611,7 +611,7 @@ export const CONFIG_FIELD_SEARCH_INDEX: ConfigFieldSearchEntry[] = [ sectionId: 'advanced', labelKey: L('sections.headers.user_agent'), qualifierKey: L('sections.headers.claude_title'), - yamlKeys: ['oauth', 'providers', 'claude', 'header-defaults', 'user-agent'], + yamlKeys: ['upstream', 'claude', 'header-defaults', 'user-agent'], keywords: ['claude'], }, { @@ -619,7 +619,7 @@ export const CONFIG_FIELD_SEARCH_INDEX: ConfigFieldSearchEntry[] = [ sectionId: 'advanced', labelKey: L('sections.headers.package_version'), qualifierKey: L('sections.headers.claude_title'), - yamlKeys: ['oauth', 'providers', 'claude', 'header-defaults', 'package-version'], + yamlKeys: ['upstream', 'claude', 'header-defaults', 'package-version'], keywords: ['claude'], }, { @@ -627,7 +627,7 @@ export const CONFIG_FIELD_SEARCH_INDEX: ConfigFieldSearchEntry[] = [ sectionId: 'advanced', labelKey: L('sections.headers.runtime_version'), qualifierKey: L('sections.headers.claude_title'), - yamlKeys: ['oauth', 'providers', 'claude', 'header-defaults', 'runtime-version'], + yamlKeys: ['upstream', 'claude', 'header-defaults', 'runtime-version'], keywords: ['claude'], }, { @@ -635,7 +635,7 @@ export const CONFIG_FIELD_SEARCH_INDEX: ConfigFieldSearchEntry[] = [ sectionId: 'advanced', labelKey: L('sections.headers.os'), qualifierKey: L('sections.headers.claude_title'), - yamlKeys: ['oauth', 'providers', 'claude', 'header-defaults', 'os'], + yamlKeys: ['upstream', 'claude', 'header-defaults', 'os'], keywords: ['claude'], }, { @@ -643,7 +643,7 @@ export const CONFIG_FIELD_SEARCH_INDEX: ConfigFieldSearchEntry[] = [ sectionId: 'advanced', labelKey: L('sections.headers.arch'), qualifierKey: L('sections.headers.claude_title'), - yamlKeys: ['oauth', 'providers', 'claude', 'header-defaults', 'arch'], + yamlKeys: ['upstream', 'claude', 'header-defaults', 'arch'], keywords: ['claude'], }, { @@ -651,7 +651,7 @@ export const CONFIG_FIELD_SEARCH_INDEX: ConfigFieldSearchEntry[] = [ sectionId: 'advanced', labelKey: L('sections.headers.timeout'), qualifierKey: L('sections.headers.claude_title'), - yamlKeys: ['oauth', 'providers', 'claude', 'header-defaults', 'timeout'], + yamlKeys: ['upstream', 'claude', 'header-defaults', 'timeout'], keywords: ['claude'], }, { @@ -660,7 +660,7 @@ export const CONFIG_FIELD_SEARCH_INDEX: ConfigFieldSearchEntry[] = [ labelKey: L('sections.headers.stabilize_device'), qualifierKey: L('sections.headers.claude_title'), hintKey: L('sections.headers.stabilize_device_desc'), - yamlKeys: ['oauth', 'providers', 'claude', 'header-defaults', 'stabilize-device-profile'], + yamlKeys: ['upstream', 'claude', 'header-defaults', 'stabilize-device-profile'], keywords: ['claude'], }, // Codex header defaults. diff --git a/src/features/config/visualConfigAdditions.ts b/src/features/config/visualConfigAdditions.ts index 097b2122fcc..6de0a1ad70d 100644 --- a/src/features/config/visualConfigAdditions.ts +++ b/src/features/config/visualConfigAdditions.ts @@ -8,7 +8,8 @@ import type { import { assertConfigListsUnchanged } from '@/services/api/configPatch'; import { readConfigBoolean } from './visualConfigBoolean'; -// Source: backend config_v8.go/config_types.go; provider paths are OAuth-only. +// Source: backend config_v8.go/config_types.go. Shared upstream behavior lives +// under upstream.*/client.codex; only OAuth-only provider paths keep oauth.providers.*. export const ADDITION_FIELDS = [ { key: 'routingSessionAffinitySubagents', @@ -32,42 +33,42 @@ export const ADDITION_FIELDS = [ }, { key: 'claudeHeaderTimezone', - path: 'oauth.providers.claude.header-defaults.timezone'.split('.'), + path: 'upstream.claude.header-defaults.timezone'.split('.'), kind: 'string', }, { key: 'claudeModelLevelCooling', - path: 'oauth.providers.claude.model-level-cooling'.split('.'), + path: 'upstream.claude.model-level-cooling'.split('.'), kind: 'boolean', }, { key: 'claudeDisableCloakMode', - path: 'oauth.providers.claude.disable-claude-cloak-mode'.split('.'), + path: 'upstream.claude.disable-claude-cloak-mode'.split('.'), kind: 'boolean', }, { key: 'claudeCodeDisableCloakingModelList', - path: 'oauth.providers.claude.claude-code.disable-cloaking-model-list'.split('.'), + path: 'upstream.claude.disable-cloaking-model-list'.split('.'), kind: 'boolean', }, { key: 'codexDisableCloaking', - path: 'oauth.providers.codex.disable-codex-cloaking'.split('.'), + path: 'upstream.codex.disable-codex-cloaking'.split('.'), kind: 'boolean', }, { key: 'codexModelLevelCooling', - path: 'oauth.providers.codex.model-level-cooling'.split('.'), + path: 'upstream.codex.model-level-cooling'.split('.'), kind: 'boolean', }, { key: 'codexStreamBootstrapBuffering', - path: 'oauth.providers.codex.stream-bootstrap-buffering'.split('.'), + path: 'upstream.codex.stream-bootstrap-buffering'.split('.'), kind: 'boolean', }, { key: 'codexStreamBootstrapTimeout', - path: 'oauth.providers.codex.stream-bootstrap-timeout'.split('.'), + path: 'upstream.codex.stream-bootstrap-timeout'.split('.'), kind: 'string', }, { @@ -77,12 +78,12 @@ export const ADDITION_FIELDS = [ }, { key: 'codexOrphanDelegationCompatibility', - path: 'oauth.providers.codex.orphan-delegation-compatibility'.split('.'), + path: 'upstream.codex.orphan-delegation-compatibility'.split('.'), kind: 'boolean', }, { key: 'codexResponseSteering', - path: 'oauth.providers.codex.response-steering'.split('.'), + path: 'upstream.codex.response-steering'.split('.'), kind: 'boolean', }, { @@ -102,7 +103,7 @@ export const ADDITION_FIELDS = [ }, { key: 'xaiInjectXSearch', - path: 'oauth.providers.xai.inject-x-search'.split('.'), + path: 'upstream.xai.inject-x-search'.split('.'), kind: 'boolean', }, { diff --git a/src/hooks/useVisualConfig.ts b/src/hooks/useVisualConfig.ts index 2f859e3b4f6..88c3a73cb43 100644 --- a/src/hooks/useVisualConfig.ts +++ b/src/hooks/useVisualConfig.ts @@ -1417,7 +1417,8 @@ function parseVisualValuesFromYaml(yamlContent: string): VisualConfigValues { const v8OauthProviders = asRecord(v8Oauth?.['providers']); const v8OauthProvidersAistudio = asRecord(v8OauthProviders?.['aistudio']); const v8OauthProvidersCodex = asRecord(v8OauthProviders?.['codex']); - const v8OauthProvidersClaude = asRecord(v8OauthProviders?.['claude']); + const v8Upstream = asRecord(parsed?.['upstream']); + const v8UpstreamClaude = asRecord(v8Upstream?.['claude']); const v8OauthProvidersAntigravity = asRecord(v8OauthProviders?.['antigravity']); const v8Multimedia = asRecord(parsed?.['multimedia']); const v8Observability = asRecord(parsed?.['observability']); @@ -1432,7 +1433,7 @@ function parseVisualValuesFromYaml(yamlContent: string): VisualConfigValues { const plugins = asRecord(parsed.plugins); const antigravity = asRecord(v8OauthProviders?.['antigravity']); const devin = asRecord(v8OauthProviders?.['devin']); - const claudeHeaderDefaults = asRecord(v8OauthProvidersClaude?.['header-defaults']); + const claudeHeaderDefaults = asRecord(v8UpstreamClaude?.['header-defaults']); const codexHeaderDefaults = asRecord(v8OauthProvidersCodex?.['header-defaults']); const newValues: VisualConfigValues = { @@ -1904,57 +1905,57 @@ export function useVisualConfig() { dirtyFields.has('claudeHeaderTimeout') || dirtyFields.has('claudeHeaderStabilizeDeviceProfile'); if (claudeHeadersDirty) { - ensureMapInDoc(doc, ['oauth', 'providers', 'claude', 'header-defaults']); + ensureMapInDoc(doc, ['upstream', 'claude', 'header-defaults']); if (dirtyFields.has('claudeHeaderUserAgent')) { setStringInDoc( doc, - ['oauth', 'providers', 'claude', 'header-defaults', 'user-agent'], + ['upstream', 'claude', 'header-defaults', 'user-agent'], values.claudeHeaderUserAgent ); } if (dirtyFields.has('claudeHeaderPackageVersion')) { setStringInDoc( doc, - ['oauth', 'providers', 'claude', 'header-defaults', 'package-version'], + ['upstream', 'claude', 'header-defaults', 'package-version'], values.claudeHeaderPackageVersion ); } if (dirtyFields.has('claudeHeaderRuntimeVersion')) { setStringInDoc( doc, - ['oauth', 'providers', 'claude', 'header-defaults', 'runtime-version'], + ['upstream', 'claude', 'header-defaults', 'runtime-version'], values.claudeHeaderRuntimeVersion ); } if (dirtyFields.has('claudeHeaderOs')) { setStringInDoc( doc, - ['oauth', 'providers', 'claude', 'header-defaults', 'os'], + ['upstream', 'claude', 'header-defaults', 'os'], values.claudeHeaderOs ); } if (dirtyFields.has('claudeHeaderArch')) { setStringInDoc( doc, - ['oauth', 'providers', 'claude', 'header-defaults', 'arch'], + ['upstream', 'claude', 'header-defaults', 'arch'], values.claudeHeaderArch ); } if (dirtyFields.has('claudeHeaderTimeout')) { setStringInDoc( doc, - ['oauth', 'providers', 'claude', 'header-defaults', 'timeout'], + ['upstream', 'claude', 'header-defaults', 'timeout'], values.claudeHeaderTimeout ); } if (dirtyFields.has('claudeHeaderStabilizeDeviceProfile')) { setBooleanInDoc( doc, - ['oauth', 'providers', 'claude', 'header-defaults', 'stabilize-device-profile'], + ['upstream', 'claude', 'header-defaults', 'stabilize-device-profile'], values.claudeHeaderStabilizeDeviceProfile ); } - deleteIfMapEmpty(doc, ['oauth', 'providers', 'claude', 'header-defaults']); + deleteIfMapEmpty(doc, ['upstream', 'claude', 'header-defaults']); } const codexHeadersDirty = diff --git a/tests/configFieldParity.test.ts b/tests/configFieldParity.test.ts index 1f5047e070d..b9d438ef085 100644 --- a/tests/configFieldParity.test.ts +++ b/tests/configFieldParity.test.ts @@ -149,6 +149,9 @@ describe('v8 YAML search paths', () => { ['wsAuth', 'oauth.providers.aistudio.ws-auth'], ['codexHeaderUserAgent', 'oauth.providers.codex.header-defaults.user-agent'], ['codexOptimizeMultiAgentV2', 'client.codex.optimize-multi-agent-v2'], + ['codexResponseSteering', 'upstream.codex.response-steering'], + ['claudeHeaderUserAgent', 'upstream.claude.header-defaults.user-agent'], + ['xaiInjectXSearch', 'upstream.xai.inject-x-search'], ['streamingNonstreamKeepalive', 'requests.nonstream-keepalive-interval'], ['payloadDefaultRules', 'requests.payload.default'], ['pluginStoreAuth', 'plugins.store-auth'], diff --git a/tests/visualConfigDurationFallback.test.ts b/tests/visualConfigDurationFallback.test.ts index 26c2a7dcb52..e7ca55861bb 100644 --- a/tests/visualConfigDurationFallback.test.ts +++ b/tests/visualConfigDurationFallback.test.ts @@ -16,7 +16,7 @@ const cases = [ }, { key: 'codexStreamBootstrapTimeout', - path: ['oauth', 'providers', 'codex', 'stream-bootstrap-timeout'], + path: ['upstream', 'codex', 'stream-bootstrap-timeout'], existing: '-1s', edited: '-2s', error: 'invalid_duration', From 936b5eba74f8e6090b42289ce30681ad085cadc6 Mon Sep 17 00:00:00 2001 From: Supra4E8C Date: Wed, 7 Oct 2026 01:14:28 +0800 Subject: [PATCH 072/142] Add Vietnamese locale tests and update existing tests for localization - Introduced a new test suite for the Vietnamese locale to ensure all English keys are covered with matching interpolation tokens. - Updated the ApiKeyStrengthMeter and configUiState tests to utilize the LANGUAGE_ORDER constant for locale management. - Enhanced test descriptions for clarity regarding supported locales. --- src/i18n/locales/vi.json | 553 ++++++++++++++++++++++++++++-- tests/apiKeyStrengthMeter.test.ts | 5 +- tests/configUiState.test.ts | 5 +- tests/vietnameseLocale.test.ts | 32 ++ 4 files changed, 570 insertions(+), 25 deletions(-) create mode 100644 tests/vietnameseLocale.test.ts diff --git a/src/i18n/locales/vi.json b/src/i18n/locales/vi.json index dc9a3cf99fc..a2ff682c936 100644 --- a/src/i18n/locales/vi.json +++ b/src/i18n/locales/vi.json @@ -86,7 +86,8 @@ "error_not_found": "Không tìm thấy Management API, hãy xác nhận địa chỉ máy chủ trỏ đến backend CLIProxyAPI", "error_server": "Backend gặp lỗi khi xử lý yêu cầu quản lý, hãy kiểm tra log máy chủ", "error_cors": "Yêu cầu cross-origin bị chặn, vui lòng kiểm tra cấu hình máy chủ", - "error_ssl": "Xác minh chứng chỉ SSL/TLS thất bại" + "error_ssl": "Xác minh chứng chỉ SSL/TLS thất bại", + "error_legacy_backend": "This backend accepts v0 Management API but does not provide v8. Upgrade CLIProxyAPI to v8 or later to use this management page." }, "header": { "refresh_all": "Làm mới tất cả", @@ -365,7 +366,74 @@ "quota_refresh_single": "Làm mới quota", "quota_refresh_hint": "Chỉ làm mới quota cho credential này", "quota_refresh_success": "Đã làm mới quota cho \"{{name}}\"", - "quota_refresh_failed": "Không thể làm mới quota cho \"{{name}}\": {{message}}" + "quota_refresh_failed": "Không thể làm mới quota cho \"{{name}}\": {{message}}", + "card_select": "Select credential {{name}}", + "card_toggle": "Enable credential {{name}}", + "card_requests": "Requests", + "cooldown_unknown": "Cooldown state unknown", + "cooldown_models_one": "{{count}} model cooling down", + "cooldown_models_other": "{{count}} models cooling down", + "cooldown_credential": "Credential-wide cooldown", + "cooldown_credential_and_models_one": "Credential + {{count}} model cooling down", + "cooldown_credential_and_models_other": "Credential + {{count}} models cooling down", + "cooldown_scope_credential": "Entire credential", + "cooldown_earliest": "Earliest end in ~{{time}}", + "cooldown_elapsed": "Cooldown timers elapsed", + "cooldown_timer_elapsed": "Timer elapsed", + "cooldown_refresh_hint": "Refresh list to confirm", + "cooldown_seconds": "{{count}}s", + "cooldown_minutes": "{{count}}m", + "cooldown_hours": "{{count}}h", + "cooldown_http_status": "Upstream HTTP {{status}}", + "cooldown_backoff": "Backoff level {{level}}", + "cooldown_deadline": "Timer deadline", + "cooldown_observed": "Snapshot at", + "cooldown_note": "Local scheduling snapshot; remaining times are estimates. Expiry does not guarantee availability, quota recovery, or an automatic retry. Model names are internal state keys; backoff levels are not failure counts.", + "cooldown_reset_button": "Clear cooldown", + "cooldown_reset_hint": "Clear this credential's local routing cooldown", + "cooldown_reset_title": "Clear credential cooldown?", + "cooldown_reset_confirm": "Clear the local routing cooldown for “{{name}}”? This may make the credential eligible for another request immediately. It does not restore upstream quota.", + "cooldown_reset_success": "Cooldown cleared for {{name}}.", + "cooldown_reset_failed": "Could not clear cooldown for {{name}}: {{message}}", + "cooldown_reason_quota": "Quota restriction", + "cooldown_reason_credential_quota": "Credential quota restriction", + "cooldown_reason_cloudflare_challenge": "Cloudflare challenge", + "cooldown_reason_invalid_grant": "Invalid grant", + "cooldown_reason_unauthorized": "Unauthorized", + "cooldown_reason_payment_required": "Access restricted (402/403; not a billing diagnosis)", + "cooldown_reason_not_found": "Resource not found", + "cooldown_reason_model_not_supported": "Model not supported", + "cooldown_reason_transient_error": "Transient upstream error", + "cooldown_reason_unknown": "Other or unknown reason", + "refresh_all_button": "Refresh all credentials", + "refresh_all_confirm": "Refresh all eligible credentials on the server, not just the current filtered results. The backend skips disabled or ineligible credentials. This does not reload the list or reset quotas and may take several minutes. Continue?", + "refresh_all_results": "Credential refresh results", + "refresh_all_summary": "{{success}} refreshed, {{failed}} failed.", + "refresh_all_empty": "No credentials were eligible for refresh.", + "refresh_all_failed": "Could not obtain complete refresh results: {{message}}. Some credentials may already have refreshed. Check the list before retrying.", + "refresh_result_success": "Refreshed", + "refresh_result_failed": "Refresh failed", + "filter_meta": "Muse (Meta)", + "filter_devin": "Devin", + "weight_tooltip": "Defaults to 1. Values at or below 0 exclude this credential from weighted scheduling; maximum 1,000,000. After entering a value, enable weighted round robin for it to take effect.", + "policy_alias_name": "Alias", + "policy_alias_display_name": "Display name", + "policy_alias_fork": "Keep the original model in listings", + "policy_alias_force_mapping": "Rewrite response model to the alias", + "policy_unsupported": "Existing data cannot be edited with this form and will be preserved. Select Inherit to clear it, or replace it to start a new list.", + "policy_replace": "Replace existing data", + "policy_retry_label": "Credential request retries", + "policy_inherit": "Inherit", + "policy_custom": "Custom", + "policy_retry_count": "Retry count", + "policy_retry_hint": "Inherit uses the global request-retry setting. Custom 0 explicitly disables request retries for this credential.", + "policy_aliases_label": "Account model aliases", + "policy_aliases_hint": "Account aliases are checked first; unmatched aliases fall back to channel aliases. Inherit or an empty list clears only account aliases.", + "policy_rules_label": "Account error rules", + "policy_rules_hint": "Custom rules take precedence in list order. Inherit or an empty list uses inherited rules; it does not disable them. Regex patterns use Go syntax.", + "policy_retry_invalid": "Enter a non-negative safe integer, or select Inherit.", + "policy_aliases_invalid": "Enter a non-empty model name and alias for each new or edited row.", + "policy_rules_invalid": "Complete each edited rule with a positive status, an action and at least one non-empty match condition." }, "antigravity_subscription": { "plan_unknown": "Không rõ", @@ -471,7 +539,10 @@ "plan_team": "Team", "plan_free": "Miễn phí", "plan_pro": "Pro 20x", - "plan_prolite": "Pro 5x" + "plan_prolite": "Pro 5x", + "credit_balance_label": "Credit balance", + "credit_unlimited": "Unlimited", + "plan_business_premium": "Business Premium" }, "kimi_quota": { "title": "Quota Kimi", @@ -487,7 +558,10 @@ "weekly_limit": "Giới hạn tuần", "limit_window": "Giới hạn {{duration}}", "limit_index": "Giới hạn #{{index}}", - "reset_hint": "đặt lại sau {{hint}}" + "reset_hint": "đặt lại sau {{hint}}", + "domain_unavailable": "Could not read the Kimi credential's domain. A downloadable, valid authentication file is required.", + "stale_request": "The connection or credential changed. Please retry.", + "monthly_limit": "Monthly limit" }, "xai_quota": { "title": "Quota Grok", @@ -512,7 +586,10 @@ "paid_health": "API chat trả phí khả dụng. xAI không công bố tổng quota cho credential OAuth này.", "pay_as_you_go_label": "Trả theo mức sử dụng", "pay_as_you_go_enabled": "Đang bật, giới hạn {{cap}}", - "pay_as_you_go_disabled": "Đã tắt" + "pay_as_you_go_disabled": "Đã tắt", + "usage_unavailable": "Usage unavailable from xAI", + "resets_label": "Resets", + "prepaid": "Prepaid" }, "vertex_import": { "title": "Đăng nhập Vertex bằng JSON", @@ -556,7 +633,9 @@ "provider_required": "Vui lòng nhập provider trước", "upgrade_required": "Phiên bản CPA hiện tại không hỗ trợ vô hiệu hóa model OAuth. Vui lòng nâng cấp.", "upgrade_required_title": "Vui lòng nâng cấp CLI Proxy API", - "upgrade_required_desc": "Phiên bản máy chủ hiện tại không hỗ trợ lấy danh sách vô hiệu hóa model OAuth. Vui lòng nâng cấp lên phiên bản CPA (CLI Proxy API) mới nhất và thử lại." + "upgrade_required_desc": "Phiên bản máy chủ hiện tại không hỗ trợ lấy danh sách vô hiệu hóa model OAuth. Vui lòng nâng cấp lên phiên bản CPA (CLI Proxy API) mới nhất và thử lại.", + "editor_description": "Choose which models a provider exposes using individual selections or wildcard rules.", + "models_hint": "Expand the list to select models, or enter wildcard rules below." }, "excluded_models": { "trigger_summary": "{{excluded}} bị loại trừ · {{available}} khả dụng", @@ -650,7 +729,12 @@ "provider_required": "Vui lòng nhập provider trước", "upgrade_required": "Tính năng này yêu cầu phiên bản CLI Proxy API (CPA) mới hơn. Vui lòng nâng cấp.", "upgrade_required_title": "Vui lòng nâng cấp CLI Proxy API", - "upgrade_required_desc": "Máy chủ hiện tại không hỗ trợ API bí danh model OAuth. Vui lòng nâng cấp lên phiên bản CLI Proxy API (CPA) mới nhất." + "upgrade_required_desc": "Máy chủ hiện tại không hỗ trợ API bí danh model OAuth. Vui lòng nâng cấp lên phiên bản CLI Proxy API (CPA) mới nhất.", + "editor_description": "Give provider models consistent names for use in your clients.", + "edit_title": "Edit model aliases for {{provider}}", + "mapping_hint": "Choose a source model, then enter the alias your clients will use.", + "mapping_row": "Alias mapping {{number}}", + "remove_mapping": "Delete alias mapping {{number}}" }, "auth_login": { "recommended_provider_section": "Provider đề xuất", @@ -752,7 +836,49 @@ "iflow_oauth_status_error": "Xác thực thất bại:", "iflow_oauth_start_error": "Không thể bắt đầu iFlow OAuth:", "iflow_oauth_polling_error": "Không thể kiểm tra trạng thái xác thực:", - "remote_access_disabled": "Phương thức đăng nhập này không khả dụng cho truy cập từ xa. Vui lòng truy cập từ localhost." + "remote_access_disabled": "Phương thức đăng nhập này không khả dụng cho truy cập từ xa. Vui lòng truy cập từ localhost.", + "devin_oauth_cancel": "Cancel Devin Login", + "devin_oauth_cancelled": "Devin login cancelled.", + "devin_oauth_cancel_error": "Failed to cancel Devin login:", + "devin_oauth_retry_hint": "The server may still be waiting for authorization. Cancel this login before starting again.", + "devin_oauth_title": "Devin OAuth", + "devin_oauth_button": "Start Devin Login", + "devin_oauth_hint": "Sign in to Devin / Cognition through browser OAuth to save an authentication file. Requires CLI Proxy API v7.3.1 or later; complete authorization within five minutes.", + "devin_oauth_url_label": "Authorization URL:", + "devin_copy_link": "Copy Link", + "devin_open_link": "Open Link", + "devin_oauth_status_waiting": "Waiting for Devin authentication...", + "devin_oauth_status_success": "Devin authentication successful!", + "devin_oauth_status_error": "Devin authentication failed:", + "devin_oauth_start_error": "Failed to start Devin OAuth:", + "devin_callback_hint": "Remote server: copy the complete final URL ending in /devin/callback?… from the browser address bar, even if the loopback page cannot be reached. Keep its port, http/https, code and state unchanged. Submit the URL here, then wait for authentication to finish.", + "devin_callback_placeholder": "http://127.0.0.1:/devin/callback?code=...&state=...", + "devin_callback_invalid": "Paste the complete http/https callback URL containing state and an authorization code or error.", + "devin_callback_state_mismatch": "This callback does not belong to the current Devin login. Use the final URL from this attempt; do not reuse an old callback.", + "meta_oauth_title": "Muse (Meta) OAuth", + "meta_oauth_button": "Log in with Muse", + "meta_oauth_hint": "Open the authorization link and enter the device code if requested. Authentication files are saved automatically after authorization.", + "meta_oauth_url_label": "Authorization URL:", + "meta_open_link": "Open Link", + "meta_copy_link": "Copy Link", + "meta_oauth_status_waiting": "Waiting for authentication...", + "meta_oauth_status_success": "Authentication successful!", + "meta_oauth_status_error": "Authentication failed:", + "meta_oauth_start_error": "Failed to start Muse OAuth:", + "meta_oauth_polling_error": "Failed to check authentication status:", + "device_code_label": "Device code:", + "device_code_copy": "Copy device code", + "kimi_ai_oauth_title": "Kimi International (kimi.ai)", + "kimi_ai_oauth_button": "Log in to Kimi International", + "kimi_ai_oauth_hint": "Authorize your kimi.ai international account via device login. A separate kimi-ai authentication file is saved automatically. China and international accounts are not interchangeable.", + "kimi_ai_oauth_url_label": "Authorization URL:", + "kimi_ai_open_link": "Open link", + "kimi_ai_copy_link": "Copy link", + "kimi_ai_oauth_status_waiting": "Waiting for authentication...", + "kimi_ai_oauth_status_success": "Authentication successful!", + "kimi_ai_oauth_status_error": "Authentication failed:", + "kimi_ai_oauth_start_error": "Failed to start Kimi International login:", + "kimi_ai_oauth_polling_error": "Failed to check authentication status:" }, "stats": { "success": "Thành công", @@ -827,7 +953,28 @@ "search_empty_desc": "Hãy thử từ khóa khác hoặc xóa bộ lọc.", "double_click_copy_hint": "Nhấp đúp để sao chép dòng log thô", "copy_success": "Đã sao chép log vào clipboard", - "copy_failed": "Sao chép thất bại" + "copy_failed": "Sao chép thất bại", + "preview_too_large": "This request log exceeds the 2 MiB preview limit. Download it to view.", + "read_status_live": "Reading continuously", + "read_status_paused": "Reading paused", + "read_status_catching_up": "Catching up on queued logs", + "last_updated": "Last successful update: {{time}}", + "buffer_scope": "Searching loaded logs only: {{count}} lines cached, {{matched}} lines matched", + "buffer_evicted": "Older logs have been removed from the cache and cannot be searched here", + "cursor_reset_notice": "Logs were rotated or reset. The latest content has been reloaded.", + "history_evicted": "Your reading position is no longer cached. Please choose a new position.", + "resume_following": "Back to latest · New lines: {{count}}", + "level_filter": "Log level", + "all_levels": "All levels", + "view_request": "View log for request {{id}}", + "copy_line": "Copy this line", + "request_log_missing": "Request log not found: it may not have been recorded or may have been cleaned up. When request logging is disabled, only error request logs are usually retained.", + "download_cached": "Download cached logs", + "clear_application_confirm": "Clear application logs on the server? Request log files will not be deleted. This action cannot be undone.", + "clear_search": "Clear search", + "reading_enabled": "Continuous reading", + "filter_load_more": "Show more matching logs", + "wrap_lines": "Wrap long lines" }, "config_management": { "title": "Bảng cấu hình", @@ -901,7 +1048,9 @@ "title": "Nâng cao & Thử nghiệm", "description": "Giả mạo header, cache chữ ký, nguồn plugin và các cài đặt ít thay đổi khác", "plugins_title": "Plugin", - "signature_title": "Chữ ký Antigravity" + "signature_title": "Chữ ký Antigravity", + "antigravity_title": "Antigravity", + "devin_title": "Devin" }, "server": { "host": "Địa chỉ Host", @@ -979,7 +1128,17 @@ "antigravity_signature_cache": "Bật cache chữ ký Antigravity", "antigravity_signature_cache_desc": "Ưu tiên và xác thực chữ ký thinking-block đã cache", "antigravity_signature_strict": "Bỏ qua xác thực chữ ký nghiêm ngặt", - "antigravity_signature_strict_desc": "Chỉ áp dụng khi cache chữ ký bị tắt; xác thực toàn bộ cây protobuf Claude" + "antigravity_signature_strict_desc": "Chỉ áp dụng khi cache chữ ký bị tắt; xác thực toàn bộ cây protobuf Claude", + "antigravity_sensitive_words": "Sensitive Word Obfuscation", + "antigravity_sensitive_words_desc": "Insert zero-width characters into matching words in Antigravity system instructions to reduce exact keyword matching upstream", + "antigravity_sensitive_words_label": "OAuth sensitive words (oauth.providers.antigravity.sensitive-words)", + "antigravity_sensitive_words_placeholder": "proxy", + "antigravity_sensitive_words_hint": "One word or phrase per row. Matching is case-insensitive; empty entries are removed and entries shorter than 2 characters are ignored by the backend", + "devin_sensitive_words": "Devin System Prompt Sensitive Words", + "devin_sensitive_words_desc": "In Devin system prompts only, a line containing a configured word is removed in full; the remaining system prompt is then obfuscated. Regular messages and tool arguments are not changed", + "devin_sensitive_words_label": "OAuth sensitive words (oauth.providers.devin.sensitive-words)", + "devin_sensitive_words_placeholder": "sensitive phrase", + "devin_sensitive_words_hint": "One word or phrase per row. Configure carefully: matching content causes the entire system-prompt line to be deleted; empty entries are removed when saved" }, "headers": { "title": "Header mặc định", @@ -1028,7 +1187,9 @@ "disable_cooling_desc": "Tắt toàn cục cửa sổ cooldown auth/model sau thất bại", "session_affinity": "Định tuyến Session Affinity", "ws_auth": "Xác thực WebSocket", - "ws_auth_desc": "Bật xác thực WebSocket (/v1/ws)" + "ws_auth_desc": "Bật xác thực WebSocket (/v1/ws)", + "proxy_url_sponsor_hint": "No suitable proxy?", + "max_retry_interval_hint": "Set to 0 or a negative integer to skip cooldown waits between retry rounds." }, "quota": { "title": "Quota dự phòng", @@ -1085,7 +1246,11 @@ "fair": "Khá", "good": "Tốt", "strong": "Mạnh" - } + }, + "name_label": "Name / description (optional)", + "name_placeholder": "For example: Alice's laptop", + "name_hint": "Saved immediately in this browser only, separately for each server. Not included in server configuration. Clear this field to remove the name.", + "name_save_error": "Could not save the name in browser storage. Check your browser storage settings." }, "payload_rules": { "rule": "Quy tắc", @@ -1144,7 +1309,18 @@ "integer_range_1_3600": "Nhập số nguyên từ 1 đến 3600", "payload_invalid_number": "Nhập số hợp lệ", "payload_invalid_boolean": "Chọn true hoặc false", - "payload_invalid_json": "Nhập JSON hợp lệ" + "payload_invalid_json": "Nhập JSON hợp lệ", + "invalid_trusted_proxies": "Each trusted proxy must be a valid IP address or CIDR.", + "invalid_discovery_service_type": "Use _name._tcp: name must be 1–15 letters, digits or hyphens, with no leading or trailing hyphen.", + "invalid_duration": "Enter a valid duration, such as 30s or 3h", + "positive_duration": "Enter a duration greater than zero", + "invalid_timezone": "Enter a valid IANA timezone, such as Asia/Singapore", + "invalid_ip": "Enter a valid IPv4 or IPv6 address", + "udp_port_pair": "Set both UDP ports to 0, or set both with the minimum not exceeding the maximum", + "udp_port_capacity": "The UDP range must contain at least twice the effective maximum session count in ports (0 sessions uses 32)", + "invalid_ice_servers": "Each ICE server needs at least one valid stun:, stuns:, turn:, or turns: URL", + "integer_range_0_65535": "Enter a whole number between 0 and 65535", + "integer": "Enter a whole number" }, "common": { "edit": "Chỉnh sửa", @@ -1152,8 +1328,172 @@ "cancel": "Hủy", "update": "Cập nhật", "add": "Thêm" + }, + "serverExtras": { + "trustedProxies": { + "label": "Trusted proxies", + "hint": "IP addresses or CIDRs; empty means forwarded headers are not trusted. Trusting all-address ranges risks client IP spoofing. Requires a backend restart." + }, + "discoveryEnabled": { + "label": "Enable discovery", + "hint": "Broadcast via mDNS / DNS-SD on the LAN. Off by default; changes apply without a restart." + }, + "discoveryServiceName": { + "label": "Service name prefix", + "hint": "The backend appends a short ID. Empty uses CPA-." + }, + "discoveryServiceType": { + "label": "Service type", + "hint": "Empty uses _ai-gateway._tcp." + }, + "discoverySubtypes": { + "label": "Protocol subtypes", + "hint": "Empty uses the five default protocols. Missing leading _ is added; invalid entries are ignored." + }, + "discoveryInterfacesInclude": { + "label": "Include interfaces", + "hint": "Empty auto-selects physical LAN interfaces. Use names or prefix patterns ending in *." + }, + "discoveryInterfacesExclude": { + "label": "Exclude interfaces", + "hint": "Use names or prefix patterns ending in *. Exclusions take priority over inclusions." + }, + "discoveryAuthRequired": { + "label": "Advertise authentication requirement", + "hint": "On by default. Broadcast metadata only; does not change actual API authentication." + }, + "discoveryAdvertiseManagement": { + "label": "Advertise management service", + "hint": "Off by default. Only announces the management service exists; does not change remote access permissions." + }, + "discoveryTitle": "LAN discovery", + "discoveryHint": "Requires multicast-capable physical interfaces and a non-loopback listener. Docker usually needs host networking; reachability is not guaranteed." + }, + "additions": { + "oauthTitle": "OAuth provider behavior", + "oauthHint": "These provider settings apply only to OAuth/file-backed credentials, not API-key credentials.", + "claudeTitle": "Claude", + "codexTitle": "Codex", + "antigravityTitle": "Antigravity", + "xaiTitle": "xAI", + "liveRelayTitle": "Codex Live media relay", + "liveRelayHint": "Relay WebRTC audio and DataChannel traffic in the proxy process. Inbound UDP must be reachable. Keep ICE credentials out of screenshots and logs.", + "iceAdd": "Add ICE server", + "iceRemove": "Remove ICE server {{index}}", + "iceURLs": "STUN/TURN URLs", + "iceUsername": "TURN username", + "iceCredential": "TURN password", + "iceServer": "ICE server {{index}}", + "routingSessionAffinitySubagents": { + "label": "Subagent session affinity", + "hint": "Enabled by default; only effective when session affinity is enabled. Subagents inherit their parent's credential to reuse caches. Disable to distribute subagents across the credential pool for greater concurrency." + }, + "saveCooldownStatus": { + "label": "Persist cooldown status", + "hint": "Save per-credential cooldown status in .cds files beside auth files. Disabled by default; otherwise status is kept only in memory." + }, + "transientErrorCooldownSeconds": { + "label": "Transient error cooldown (seconds)", + "hint": "Cooldown for upstream 408/500/502/503/504/520–526 errors. 0 uses the default 60 seconds; a negative value disables this cooldown." + }, + "videoResultAuthCacheTTL": { + "label": "Video result credential cache TTL", + "hint": "How long video IDs remain bound to the credential that created them. Use a duration such as 30m or 3h; default: 3h." + }, + "claudeHeaderTimezone": { + "label": "Fallback timezone", + "hint": "IANA timezone for the cloaked currentDate, e.g. Asia/Singapore, or Local for the backend host's timezone. The credential JSON's timezone takes priority." + }, + "claudeModelLevelCooling": { + "label": "Model-level cooldown", + "hint": "Apply Claude quota cooldowns only to the requested model, rather than all models sharing the credential. Disabled by default." + }, + "claudeDisableCloakMode": { + "label": "Disable request cloaking", + "hint": "Disable the Claude Code CLI disguise and system prompt replacement; pass through the original system prompt. Credential files can override this with cloak_mode. Default: false (automatic cloaking for non-Claude-Code clients)." + }, + "claudeCodeDisableCloakingModelList": { + "label": "Disable model ID cloaking", + "hint": "Return original model IDs in Anthropic model list responses instead of cloaked IDs. Disabled by default." + }, + "codexDisableCloaking": { + "label": "Disable request cloaking", + "hint": "Stop forcing official Codex User-Agent and Originator headers on HTTP/SSE and WebSocket requests. Disabled by default." + }, + "codexModelLevelCooling": { + "label": "Model-level cooldown", + "hint": "Apply usage_limit_reached quota cooldowns only to the requested model, rather than all models sharing the credential. Disabled by default." + }, + "codexStreamBootstrapBuffering": { + "label": "Buffer stream bootstrap", + "hint": "Hold initial empty events and heartbeats to allow credential failover on early overload or rate-limit rejections. Disabled by default. Delays response headers and may trigger client or reverse-proxy timeouts; buffering has frame and byte budgets." + }, + "codexStreamBootstrapTimeout": { + "label": "Stream bootstrap timeout", + "hint": "Optional buffering time limit, e.g. 20s. Default: 0 (unlimited time; frame and byte budgets still apply). Checked as upstream frames arrive; not a hard deadline for every network stall. Headers may still wait for translated output." + }, + "codexOptimizeMultiAgentV2": { + "label": "Optimize multi-agent v2", + "hint": "Optimize official Codex multi-agent requests: refresh spawn_agent model details, remove message parameter encryption, normalize agent_message content, and convert it to user messages for non-Codex protocols. Disabled by default." + }, + "codexOrphanDelegationCompatibility": { + "label": "Orphan delegation compatibility", + "hint": "For X-Openai-Subagent: collab_spawn requests, convert orphan codex_app/create_thread and codex_app/send_message_to_thread outputs without a valid matching call into user messages. Disabled by default." + }, + "codexResponseSteering": { + "label": "Response steering", + "hint": "Experimental full-duplex Codex Responses WebSockets. Each socket stays bound to one upstream account and model; accepted input is never replayed. Disabled by default." + }, + "antigravityConnectionPoolEnabled": { + "label": "Enable connection pooling", + "hint": "Reuse upstream HTTP/1.1 connections. Default: false (short-lived connections)." + }, + "antigravityConnectionPoolIdleTimeout": { + "label": "Idle connection timeout", + "hint": "How long idle connections remain in the pool. Default: 30s; capped at 210s. Zero or a negative duration switches to short-lived connections." + }, + "antigravityConnectionPoolMaxIdleConnsPerHost": { + "label": "Maximum idle connections per host", + "hint": "Maximum idle connections retained per upstream host per credential. Default: 2; capped at 100. Zero uses Go's default of 2; a negative value switches to short-lived connections." + }, + "xaiInjectXSearch": { + "label": "Inject x_search", + "hint": "Add xAI's native x_search tool when absent from the request, including tool_choice.allowed_tools when applicable. Disabled by default." + }, + "codexLiveMediaRelayEnabled": { + "label": "Enable media relay", + "hint": "Terminate and relay Codex Live WebRTC media in this process. Requires inbound UDP reachability. Disabled by default to preserve direct media connections." + }, + "codexLiveMediaRelayMaxSessions": { + "label": "Maximum concurrent media sessions", + "hint": "Blank or 0 uses the default of 32 sessions. A custom UDP range must provide at least two ports per session." + }, + "codexLiveMediaRelayDisablePrivateRemoteIPs": { + "label": "Block private remote IP candidates", + "hint": "Default: false, allowing private candidates for local or trusted-network clients. Enable to reject downstream SDP candidates targeting private, loopback, link-local, or unspecified IPs and reduce internal-network exposure; local connections may fail." + }, + "codexLiveMediaRelayPublicIP": { + "label": "Advertised public IP", + "hint": "Optional public IPv4 or IPv6 address to advertise when the proxy is behind 1:1 NAT. Enter an IP address, not a hostname." + }, + "codexLiveMediaRelayUDPPortMin": { + "label": "Minimum UDP port", + "hint": "Set both UDP bounds to 0 for system allocation, or specify an inclusive continuous range with at least twice the effective session limit in ports." + }, + "codexLiveMediaRelayUDPPortMax": { + "label": "Maximum UDP port", + "hint": "Must be at least the minimum port. Both bounds must be 0 or both nonzero; a custom range needs at least two ports per session (64 with the default 32 sessions)." + }, + "codexLiveMediaRelayICEServers": { + "label": "ICE servers", + "hint": "Optional STUN/TURN servers using stun:, stuns:, turn:, or turns: URLs. TURN credentials are omitted from the JSON config API. Enter the credential as a password and keep secrets out of screenshots and logs." + } } - } + }, + "source_changes_before_visual": "Save or discard your unsaved source edits before switching to visual mode.", + "precise_save_incomplete": "The precise save did not finish; some changes may already be applied. Your draft is retained. Save again to review the remaining server differences.", + "concurrent_list_conflict": "The server list {{path}} changed after your draft baseline. Saving was blocked to avoid overwriting those changes. Your draft is retained; note your edits, then reload the configuration and reconcile them.", + "precise_save_recovery_required": "Could not read back the save result. Editing is paused. Save again to recover the draft baseline, or reload the configuration." }, "quota_management": { "title": "Quản lý Quota", @@ -1195,7 +1535,12 @@ "weekday_wed": "T4", "weekday_thu": "T5", "weekday_fri": "T6", - "weekday_sat": "T7" + "weekday_sat": "T7", + "search_label": "Search accounts", + "search_placeholder": "Search by filename or email", + "search_empty_title": "No matching accounts", + "search_empty_desc": "Try another filename or email, or clear the search.", + "search_clear": "Clear search" }, "plugin_management": { "title": "Quản lý Plugin", @@ -1404,7 +1749,13 @@ "login_failed": "Đăng nhập thất bại", "commercial_mode_restart_required": "Đã đổi cài đặt chế độ thương mại. Vui lòng khởi động lại dịch vụ để có hiệu lực", "copy_failed": "Sao chép thất bại", - "link_copied": "Đã sao chép liên kết vào clipboard" + "link_copied": "Đã sao chép liên kết vào clipboard", + "trusted_proxies_restart_required": "Trusted proxy settings saved. Restart the backend to apply them.", + "region_label": "Notifications", + "type_success": "Success", + "type_info": "Information", + "type_warning": "Warning", + "type_error": "Error" }, "language": { "switch": "Ngôn ngữ", @@ -1474,7 +1825,8 @@ "qiniuCloud": "Qiniu Cloud", "lmuAI": "LMU AI (Linhmou AI)", "infistar": "Infistar", - "kimi": "Kimi" + "kimi": "Kimi", + "meta": "Muse (Meta)" }, "table": { "key": "Key", @@ -1492,7 +1844,8 @@ "cloakTag": "Cloak", "empty": "Chưa có tài nguyên nào, nhấn \"Mới\" để thêm.", "filterPlaceholder": "Tìm key, URL, tiền tố…", - "description": "Quản lý tài nguyên trong {{route}}" + "description": "Quản lý tài nguyên trong {{route}}", + "cliProfileTag": "CLI Profile" }, "sponsor": { "protocolSummary": "Anthropic / OpenAI / Gemini / Codex API (Responses)", @@ -1563,7 +1916,8 @@ "openai": "Tương thích OpenAI", "gemini": "Gemini", "codexResponses": "Codex API (Responses)" - } + }, + "kimiPromo": "New users get API credit worth 10% of their first successful top-up, up to ¥1000. Offer ends September 30." }, "status": { "active": "Đang hoạt động", @@ -1656,7 +2010,11 @@ "baseUrlRequired": "Base URL là bắt buộc", "weightInteger": "Trọng số điều phối phải là số nguyên", "weightMax": "Trọng số điều phối không được vượt quá {{max}}" - } + }, + "fingerprintProfile": "Request fingerprint", + "fingerprintProfileDefault": "Default (caller-owned)", + "fingerprintProfileClaudeCodeCli": "Claude Code CLI", + "fingerprintProfileHint": "Keep the caller's prompt and headers by default, or opt in to the Claude Code CLI request fingerprint." }, "delete": { "title": "Xóa tài nguyên", @@ -1720,6 +2078,159 @@ }, "modelCatalog": { "notLoaded": "Chưa tải" + }, + "behavior": { + "title": "Provider-specific behavior", + "alphaSearch": "Enable Alpha Search", + "alphaSearchHint": "Allow this Codex key to serve Alpha Search. The upstream must support it.", + "codexCloaking": "Codex request cloaking", + "codexCloakingHint": "Override official Codex identity headers for this API key. Default removes the credential override; OAuth-only settings do not apply here.", + "useDefault": "Use backend default", + "cloakingEnabled": "Enable cloaking", + "cloakingDisabled": "Disable cloaking", + "rebuildMidSystemMessage": "Rebuild system messages", + "rebuildMidSystemMessageHint": "Move Claude messages with role system into the top-level system field.", + "supportPromptCacheKey": "Inject prompt cache key", + "supportPromptCacheKeyHint": "Derive and inject prompt_cache_key for compatible requests. Enable only when the upstream supports this field." + }, + "modelOptions": { + "displayName": "Display name", + "maxContextLength": "Context length", + "contextHint": "Non-negative integer; leave empty to use the default.", + "forceMapping": "Rewrite response model to alias", + "isCompat": "Compatibility mode", + "supportConfigurationUpdate": "Allow configuration updates", + "inputModalitiesText": "Input modalities", + "outputModalitiesText": "Output modalities", + "modalitiesHint": "Separate values with commas or whitespace. Custom modality names are preserved.", + "useMaxCompletionTokens": "Use max_completion_tokens", + "thinkingMode": "Thinking override", + "useDefault": "Use default", + "custom": "Custom", + "thinkingHint": "Default inherits backend behavior; an empty custom override is an explicit {}. Budgets and effort levels can coexist. Only when both budgets are 0 or blank is the numeric range unspecified. Set a maximum at least as large as a positive minimum.", + "thinkingMin": "Minimum thinking budget", + "thinkingMax": "Maximum thinking budget", + "thinkingZeroAllowed": "Allow zero budget", + "thinkingDynamicAllowed": "Allow dynamic budget", + "invalidContext": "Context length must be a non-negative safe integer.", + "invalidThinking": "Thinking must be a valid JSON object.", + "invalidBudget": "Thinking budgets must be non-negative safe integers.", + "invalidRange": "Minimum thinking budget must not exceed the maximum. Blank bounds count as 0.", + "removeModel": "Remove model", + "modelName": "Model name", + "modelAlias": "Alias (optional)" + }, + "runtimePolicy": { + "title": "Advanced runtime policy", + "description": "Inherit uses the parent group policy, then backend defaults. Overrides apply only to this entry.", + "cooling": "Cooling", + "inherit": "Inherit", + "coolingEnabled": "Enable cooling", + "coolingDisabled": "Disable cooling", + "retry": "Request retries", + "retryHint": "Blank inherits the group setting. Use an integer: 0 disables retries; a negative value uses the global retry policy instead of the group policy.", + "errorsMode": "Request error rules", + "override": "Override", + "errorsHint": "Inherit follows the parent policy. Override replaces the entire list, which may be empty. Switching modes keeps your rule draft.", + "invalidRetry": "Retries must be a safe integer, or blank to inherit." + }, + "errorRules": { + "hint": "Use the first matching rule in order; for the same status code, any condition may match.", + "empty": "No rules. You can save an empty list.", + "rule": "Rule {{number}}", + "status": "Status code", + "action": "Action", + "selectAction": "Select an action", + "moveUp": "Move rule up", + "moveDown": "Move rule down", + "removeRule": "Delete rule", + "matchType": "Match type", + "text": "Contains text", + "regex": "Regular expression", + "matchValue": "Condition", + "regexHint": "Go regular expression", + "removeMatch": "Delete condition", + "addMatch": "Add condition", + "addRule": "Add rule", + "invalidStatus": "Status code must be a positive safe integer.", + "invalidAction": "Select a valid action.", + "invalidMatch": "Match conditions cannot be empty.", + "missingMatch": "Add at least one match condition.", + "actions": { + "stop": "Stop", + "stop-and-cooldown": "Stop and cool down", + "continue": "Continue", + "continue-and-cooldown": "Continue and cool down" + } } + }, + "devin_quota": { + "daily": "Daily remaining", + "weekly": "Weekly remaining", + "plan_label": "Plan", + "plan_end": "Subscription ends", + "unavailable": "Unavailable", + "reset_unknown": "Reset time unavailable", + "observed_at": "Quota observed: {{time}}", + "observed_unknown": "Quota observation time unavailable", + "missing_identity": "The credential name or auth index is missing. Reload the credential list.", + "stale_request": "The connection or credential changed. Please retry.", + "empty_data": "Devin returned no usable quota data.", + "loading": "Querying Devin quota…", + "idle": "Click to query Devin quota", + "load_failed": "Failed to query quota: {{message}}", + "empty_title": "No Devin credentials", + "empty_desc": "Upload a Devin credential file or sign in using the backend CLI to query quota." + }, + "meta_quota": { + "title": "Muse (Meta) Quota", + "empty_title": "No Muse credentials", + "empty_desc": "Sign in with Muse OAuth or upload a Meta credential file to query quota.", + "idle": "Click to query Muse quota", + "loading": "Querying Muse quota…", + "load_failed": "Failed to query quota: {{message}}", + "missing_auth_index": "Auth file missing auth_index", + "empty_data": "Quota unknown. You may not have made a model request yet.", + "invalid_response": "Muse returned an invalid quota response.", + "request_failed": "Muse quota request failed. Check that the DCA credential is valid.", + "missing_file": "Quota requires a downloadable Meta authentication file.", + "missing_dca_token": "The authentication file has no valid dca_token. Sign in with Muse OAuth again.", + "invalid_auth_file": "The downloaded authentication file is not valid JSON.", + "download_failed": "Could not download the authentication file for quota lookup.", + "stale_request": "The connection or credential changed. Please retry.", + "plan": "Plan", + "active": "Subscription active", + "inactive": "Subscription inactive", + "window": "Usage window", + "window_duration": "{{minutes}}-minute window", + "weekly": "Weekly quota", + "unknown": "Unknown", + "remaining": "{{percent}}% remaining" + }, + "claude_reset": { + "retry_confirm": "Retry the unknown reset for “{{name}}” with its original request ID? A reset may already have been spent. Retry within 10 minutes; do not reload or start another claim in another tab.", + "remaining": "Resets remaining", + "title": "Banked resets", + "scope": "Uses a limited reset grant to clear eligible Claude usage windows. Only confirm when you want to spend a reset. Recovery is limited to this tab/session; do not reload or use another tab while an outcome is unknown.", + "loading": "Loading…", + "read_error": "Reset grants could not be read. Nothing was submitted.", + "blocked": "Reset not submitted: eligibility, account identity, or session could not be verified. Refresh and check again.", + "unknown": "The outcome is unknown. A reset may have been spent. Retry within 10 minutes using the same request ID; do not start another claim elsewhere.", + "expired": "The retry window has expired. Further claims are blocked in this session. Check your Claude account before taking any further action.", + "retry": "Retry the same claim", + "empty": "No banked reset grants.", + "count": "{{left}} / {{total}} resets remaining", + "ends": "Expires: {{date}}", + "use": "Reset limits", + "confirm": "Confirm reset", + "confirm_text": "Spend one reset to clear eligible usage limits for “{{name}}”? This uses a limited reset grant.", + "reset": "Usage limits reset.", + "already_used": "This grant was already used.", + "not_limited": "No reset: the account is not currently limited.", + "cooldown": "No reset: cooldown is active.", + "ineligible": "This account is not eligible.", + "unavailable": "Resets are currently unavailable.", + "rate_limited": "Request rate limited.", + "auth_error": "Authorization was refused." } } diff --git a/tests/apiKeyStrengthMeter.test.ts b/tests/apiKeyStrengthMeter.test.ts index 9f8d3c3005f..d899ef53e0f 100644 --- a/tests/apiKeyStrengthMeter.test.ts +++ b/tests/apiKeyStrengthMeter.test.ts @@ -5,8 +5,9 @@ import i18n from '@/i18n'; import { ApiKeyStrengthMeter } from '@/features/config/components/blocks/ApiKeyStrengthMeter'; import { SEGMENT_STAGGER_MS, segmentFillDelayMs } from '@/features/config/components/blocks/shared'; import { generateSecureApiKey } from '@/utils/apiKey'; +import { LANGUAGE_ORDER } from '@/utils/constants'; -const LOCALES = ['en', 'zh-CN', 'zh-TW', 'ru']; +const LOCALES = LANGUAGE_ORDER; describe('ApiKeyStrengthMeter', () => { test('exposes the tier through the progressbar', () => { @@ -49,7 +50,7 @@ describe('ApiKeyStrengthMeter', () => { expect(delays(2, 4)).toEqual([0, 0, 0, 0]); }); - test('every tier label is translated in all locales', async () => { + test('every tier label is translated in all supported locales', async () => { const original = i18n.language; for (const locale of LOCALES) { diff --git a/tests/configUiState.test.ts b/tests/configUiState.test.ts index 9db5b366bb4..1b3d3a2c406 100644 --- a/tests/configUiState.test.ts +++ b/tests/configUiState.test.ts @@ -10,6 +10,7 @@ import { type ConfigStatusInput, } from '@/features/config/uiState'; import type { VisualConfigValidationErrors } from '@/types/visualConfig'; +import { LANGUAGE_ORDER } from '@/utils/constants'; const statusInput = (overrides: Partial = {}): ConfigStatusInput => ({ disconnected: false, @@ -50,8 +51,8 @@ describe('resolveStatus', () => { expect(status.tone).toBe('error'); }); - test('every status resolves label keys that exist in all four locales', async () => { - const locales = ['en', 'zh-CN', 'zh-TW', 'ru']; + test('every status resolves label keys that exist in all supported locales', async () => { + const locales = LANGUAGE_ORDER; const inputs: Partial[] = [ { disconnected: true }, { loading: true }, diff --git a/tests/vietnameseLocale.test.ts b/tests/vietnameseLocale.test.ts new file mode 100644 index 00000000000..b357af7b509 --- /dev/null +++ b/tests/vietnameseLocale.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, test } from 'bun:test'; + +const flattenLeaves = (value: unknown, prefix = ''): Record => { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return prefix ? { [prefix]: String(value ?? '') } : {}; + } + + return Object.entries(value).reduce>((leaves, [key, child]) => { + const path = prefix ? `${prefix}.${key}` : key; + return { ...leaves, ...flattenLeaves(child, path) }; + }, {}); +}; + +const interpolationTokens = (value: string): string[] => value.match(/\{\{[^}]+\}\}/g) ?? []; + +describe('Vietnamese locale', () => { + test('covers every current English key with matching interpolation tokens', async () => { + const english = flattenLeaves(await Bun.file('src/i18n/locales/en.json').json()); + const vietnamese = flattenLeaves(await Bun.file('src/i18n/locales/vi.json').json()); + const missing = Object.keys(english).filter((key) => !(key in vietnamese)); + const mismatches = Object.keys(english) + .filter((key) => key in vietnamese) + .filter( + (key) => + interpolationTokens(english[key]).sort().join('|') !== + interpolationTokens(vietnamese[key]).sort().join('|') + ); + + expect(missing).toEqual([]); + expect(mismatches).toEqual([]); + }); +}); From 6abace9ffb83a9ac349464ded04bb4e7f7cb309e Mon Sep 17 00:00:00 2001 From: Supra4E8C Date: Wed, 7 Oct 2026 01:34:06 +0800 Subject: [PATCH 073/142] Implement feature X to enhance user experience and fix bug Y in module Z --- src/i18n/locales/vi.json | 812 +++++++++++++++++++-------------------- 1 file changed, 406 insertions(+), 406 deletions(-) diff --git a/src/i18n/locales/vi.json b/src/i18n/locales/vi.json index a2ff682c936..68f54829041 100644 --- a/src/i18n/locales/vi.json +++ b/src/i18n/locales/vi.json @@ -87,7 +87,7 @@ "error_server": "Backend gặp lỗi khi xử lý yêu cầu quản lý, hãy kiểm tra log máy chủ", "error_cors": "Yêu cầu cross-origin bị chặn, vui lòng kiểm tra cấu hình máy chủ", "error_ssl": "Xác minh chứng chỉ SSL/TLS thất bại", - "error_legacy_backend": "This backend accepts v0 Management API but does not provide v8. Upgrade CLIProxyAPI to v8 or later to use this management page." + "error_legacy_backend": "Backend này chấp nhận Management API v0 nhưng không cung cấp v8. Vui lòng nâng cấp CLIProxyAPI lên v8 hoặc mới hơn để sử dụng trang quản lý này." }, "header": { "refresh_all": "Làm mới tất cả", @@ -367,73 +367,73 @@ "quota_refresh_hint": "Chỉ làm mới quota cho credential này", "quota_refresh_success": "Đã làm mới quota cho \"{{name}}\"", "quota_refresh_failed": "Không thể làm mới quota cho \"{{name}}\": {{message}}", - "card_select": "Select credential {{name}}", - "card_toggle": "Enable credential {{name}}", - "card_requests": "Requests", - "cooldown_unknown": "Cooldown state unknown", - "cooldown_models_one": "{{count}} model cooling down", - "cooldown_models_other": "{{count}} models cooling down", - "cooldown_credential": "Credential-wide cooldown", - "cooldown_credential_and_models_one": "Credential + {{count}} model cooling down", - "cooldown_credential_and_models_other": "Credential + {{count}} models cooling down", - "cooldown_scope_credential": "Entire credential", - "cooldown_earliest": "Earliest end in ~{{time}}", - "cooldown_elapsed": "Cooldown timers elapsed", - "cooldown_timer_elapsed": "Timer elapsed", - "cooldown_refresh_hint": "Refresh list to confirm", - "cooldown_seconds": "{{count}}s", - "cooldown_minutes": "{{count}}m", - "cooldown_hours": "{{count}}h", - "cooldown_http_status": "Upstream HTTP {{status}}", - "cooldown_backoff": "Backoff level {{level}}", - "cooldown_deadline": "Timer deadline", - "cooldown_observed": "Snapshot at", - "cooldown_note": "Local scheduling snapshot; remaining times are estimates. Expiry does not guarantee availability, quota recovery, or an automatic retry. Model names are internal state keys; backoff levels are not failure counts.", - "cooldown_reset_button": "Clear cooldown", - "cooldown_reset_hint": "Clear this credential's local routing cooldown", - "cooldown_reset_title": "Clear credential cooldown?", - "cooldown_reset_confirm": "Clear the local routing cooldown for “{{name}}”? This may make the credential eligible for another request immediately. It does not restore upstream quota.", - "cooldown_reset_success": "Cooldown cleared for {{name}}.", - "cooldown_reset_failed": "Could not clear cooldown for {{name}}: {{message}}", - "cooldown_reason_quota": "Quota restriction", - "cooldown_reason_credential_quota": "Credential quota restriction", - "cooldown_reason_cloudflare_challenge": "Cloudflare challenge", - "cooldown_reason_invalid_grant": "Invalid grant", - "cooldown_reason_unauthorized": "Unauthorized", - "cooldown_reason_payment_required": "Access restricted (402/403; not a billing diagnosis)", - "cooldown_reason_not_found": "Resource not found", - "cooldown_reason_model_not_supported": "Model not supported", - "cooldown_reason_transient_error": "Transient upstream error", - "cooldown_reason_unknown": "Other or unknown reason", - "refresh_all_button": "Refresh all credentials", - "refresh_all_confirm": "Refresh all eligible credentials on the server, not just the current filtered results. The backend skips disabled or ineligible credentials. This does not reload the list or reset quotas and may take several minutes. Continue?", - "refresh_all_results": "Credential refresh results", - "refresh_all_summary": "{{success}} refreshed, {{failed}} failed.", - "refresh_all_empty": "No credentials were eligible for refresh.", - "refresh_all_failed": "Could not obtain complete refresh results: {{message}}. Some credentials may already have refreshed. Check the list before retrying.", - "refresh_result_success": "Refreshed", - "refresh_result_failed": "Refresh failed", + "card_select": "Chọn credential {{name}}", + "card_toggle": "Bật credential {{name}}", + "card_requests": "Yêu cầu", + "cooldown_unknown": "Trạng thái cooldown không xác định", + "cooldown_models_one": "{{count}} model đang cooldown", + "cooldown_models_other": "{{count}} model đang cooldown", + "cooldown_credential": "Cooldown toàn bộ credential", + "cooldown_credential_and_models_one": "Credential + {{count}} model đang cooldown", + "cooldown_credential_and_models_other": "Credential + {{count}} model đang cooldown", + "cooldown_scope_credential": "Toàn bộ credential", + "cooldown_earliest": "Sớm nhất kết thúc sau ~{{time}}", + "cooldown_elapsed": "Bộ đếm cooldown đã hết hạn", + "cooldown_timer_elapsed": "Bộ đếm thời gian đã hết hạn", + "cooldown_refresh_hint": "Làm mới danh sách để xác nhận", + "cooldown_seconds": "{{count}} giây", + "cooldown_minutes": "{{count}} phút", + "cooldown_hours": "{{count}} giờ", + "cooldown_http_status": "HTTP upstream {{status}}", + "cooldown_backoff": "Mức độ backoff {{level}}", + "cooldown_deadline": "Hạn chót đếm giờ", + "cooldown_observed": "Ảnh chụp nhanh lúc", + "cooldown_note": "Ảnh chụp nhanh điều phối cục bộ; thời gian còn lại chỉ là ước tính. Việc hết hạn không đảm bảo credential khả dụng, phục hồi quota hay tự động thử lại. Tên model là key trạng thái nội bộ; mức độ backoff không phải số lần thất bại.", + "cooldown_reset_button": "Xóa cooldown", + "cooldown_reset_hint": "Xóa cooldown định tuyến cục bộ của credential này", + "cooldown_reset_title": "Xóa cooldown của credential?", + "cooldown_reset_confirm": "Xóa cooldown định tuyến cục bộ cho “{{name}}”? Điều này có thể khiến credential đủ điều kiện nhận yêu cầu tiếp theo ngay lập tức, nhưng không khôi phục quota ở upstream.", + "cooldown_reset_success": "Đã xóa cooldown cho {{name}}.", + "cooldown_reset_failed": "Không thể xóa cooldown cho {{name}}: {{message}}", + "cooldown_reason_quota": "Hạn chế quota", + "cooldown_reason_credential_quota": "Hạn chế quota của credential", + "cooldown_reason_cloudflare_challenge": "Thử thách Cloudflare", + "cooldown_reason_invalid_grant": "Cấp quyền không hợp lệ", + "cooldown_reason_unauthorized": "Chưa được ủy quyền (Unauthorized)", + "cooldown_reason_payment_required": "Truy cập bị hạn chế (402/403; không phải chẩn đoán thanh toán)", + "cooldown_reason_not_found": "Không tìm thấy tài nguyên", + "cooldown_reason_model_not_supported": "Model không được hỗ trợ", + "cooldown_reason_transient_error": "Lỗi tạm thời từ upstream", + "cooldown_reason_unknown": "Lý do khác hoặc không xác định", + "refresh_all_button": "Làm mới tất cả credential", + "refresh_all_confirm": "Làm mới tất cả credential đủ điều kiện trên máy chủ (không chỉ các kết quả lọc hiện tại). Backend sẽ bỏ qua các credential bị tắt hoặc không đủ điều kiện. Thao tác này không tải lại danh sách hay đặt lại quota và có thể mất vài phút. Tiếp tục?", + "refresh_all_results": "Kết quả làm mới credential", + "refresh_all_summary": "Đã làm mới {{success}} mục, thất bại {{failed}} mục.", + "refresh_all_empty": "Không có credential nào đủ điều kiện để làm mới.", + "refresh_all_failed": "Không thể lấy kết quả làm mới hoàn chỉnh: {{message}}. Một số credential có thể đã được làm mới. Vui lòng kiểm tra danh sách trước khi thử lại.", + "refresh_result_success": "Làm mới thành công", + "refresh_result_failed": "Làm mới thất bại", "filter_meta": "Muse (Meta)", "filter_devin": "Devin", - "weight_tooltip": "Defaults to 1. Values at or below 0 exclude this credential from weighted scheduling; maximum 1,000,000. After entering a value, enable weighted round robin for it to take effect.", - "policy_alias_name": "Alias", - "policy_alias_display_name": "Display name", - "policy_alias_fork": "Keep the original model in listings", - "policy_alias_force_mapping": "Rewrite response model to the alias", - "policy_unsupported": "Existing data cannot be edited with this form and will be preserved. Select Inherit to clear it, or replace it to start a new list.", - "policy_replace": "Replace existing data", - "policy_retry_label": "Credential request retries", - "policy_inherit": "Inherit", - "policy_custom": "Custom", - "policy_retry_count": "Retry count", - "policy_retry_hint": "Inherit uses the global request-retry setting. Custom 0 explicitly disables request retries for this credential.", - "policy_aliases_label": "Account model aliases", - "policy_aliases_hint": "Account aliases are checked first; unmatched aliases fall back to channel aliases. Inherit or an empty list clears only account aliases.", - "policy_rules_label": "Account error rules", - "policy_rules_hint": "Custom rules take precedence in list order. Inherit or an empty list uses inherited rules; it does not disable them. Regex patterns use Go syntax.", - "policy_retry_invalid": "Enter a non-negative safe integer, or select Inherit.", - "policy_aliases_invalid": "Enter a non-empty model name and alias for each new or edited row.", - "policy_rules_invalid": "Complete each edited rule with a positive status, an action and at least one non-empty match condition." + "weight_tooltip": "Mặc định là 1. Giá trị nhỏ hơn hoặc bằng 0 sẽ loại trừ credential này khỏi điều phối theo trọng số; tối đa 1.000.000. Sau khi nhập giá trị, hãy bật round robin có trọng số để có hiệu lực.", + "policy_alias_name": "Bí danh", + "policy_alias_display_name": "Tên hiển thị", + "policy_alias_fork": "Giữ lại model gốc trong danh sách", + "policy_alias_force_mapping": "Viết lại tên model trong phản hồi thành bí danh", + "policy_unsupported": "Dữ liệu hiện tại không thể chỉnh sửa bằng biểu mẫu này và sẽ được giữ nguyên. Chọn Kế thừa để xóa dữ liệu, hoặc Thay thế để bắt đầu danh sách mới.", + "policy_replace": "Thay thế dữ liệu hiện có", + "policy_retry_label": "Số lần thử lại yêu cầu của credential", + "policy_inherit": "Kế thừa", + "policy_custom": "Tùy chỉnh", + "policy_retry_count": "Số lần thử lại", + "policy_retry_hint": "Kế thừa sẽ sử dụng cài đặt thử lại yêu cầu toàn cục. Tùy chỉnh bằng 0 sẽ vô hiệu hóa rõ ràng việc thử lại yêu cầu cho credential này.", + "policy_aliases_label": "Bí danh model của tài khoản", + "policy_aliases_hint": "Bí danh của tài khoản được kiểm tra trước; bí danh không khớp sẽ chuyển về bí danh kênh. Kế thừa hoặc danh sách trống chỉ xóa bí danh của tài khoản.", + "policy_rules_label": "Quy tắc lỗi của tài khoản", + "policy_rules_hint": "Các quy tắc tùy chỉnh được ưu tiên theo thứ tự danh sách. Kế thừa hoặc danh sách trống sẽ sử dụng quy tắc kế thừa; điều này không vô hiệu hóa chúng. Mẫu biểu thức chính quy (Regex) dùng cú pháp của Go.", + "policy_retry_invalid": "Nhập một số nguyên an toàn không âm, hoặc chọn Kế thừa.", + "policy_aliases_invalid": "Nhập tên model và bí danh không để trống cho mỗi hàng mới hoặc đã chỉnh sửa.", + "policy_rules_invalid": "Hoàn thành mỗi quy tắc đã chỉnh sửa với mã trạng thái dương, một hành động và ít nhất một điều kiện khớp không để trống." }, "antigravity_subscription": { "plan_unknown": "Không rõ", @@ -540,8 +540,8 @@ "plan_free": "Miễn phí", "plan_pro": "Pro 20x", "plan_prolite": "Pro 5x", - "credit_balance_label": "Credit balance", - "credit_unlimited": "Unlimited", + "credit_balance_label": "Số dư Credit", + "credit_unlimited": "Không giới hạn", "plan_business_premium": "Business Premium" }, "kimi_quota": { @@ -559,9 +559,9 @@ "limit_window": "Giới hạn {{duration}}", "limit_index": "Giới hạn #{{index}}", "reset_hint": "đặt lại sau {{hint}}", - "domain_unavailable": "Could not read the Kimi credential's domain. A downloadable, valid authentication file is required.", - "stale_request": "The connection or credential changed. Please retry.", - "monthly_limit": "Monthly limit" + "domain_unavailable": "Không thể đọc miền của credential Kimi. Cần có file xác thực hợp lệ và có thể tải xuống.", + "stale_request": "Kết nối hoặc credential đã thay đổi. Vui lòng thử lại.", + "monthly_limit": "Giới hạn tháng" }, "xai_quota": { "title": "Quota Grok", @@ -587,9 +587,9 @@ "pay_as_you_go_label": "Trả theo mức sử dụng", "pay_as_you_go_enabled": "Đang bật, giới hạn {{cap}}", "pay_as_you_go_disabled": "Đã tắt", - "usage_unavailable": "Usage unavailable from xAI", - "resets_label": "Resets", - "prepaid": "Prepaid" + "usage_unavailable": "Dữ liệu mức sử dụng từ xAI hiện không khả dụng", + "resets_label": "Đặt lại", + "prepaid": "Trả trước" }, "vertex_import": { "title": "Đăng nhập Vertex bằng JSON", @@ -634,8 +634,8 @@ "upgrade_required": "Phiên bản CPA hiện tại không hỗ trợ vô hiệu hóa model OAuth. Vui lòng nâng cấp.", "upgrade_required_title": "Vui lòng nâng cấp CLI Proxy API", "upgrade_required_desc": "Phiên bản máy chủ hiện tại không hỗ trợ lấy danh sách vô hiệu hóa model OAuth. Vui lòng nâng cấp lên phiên bản CPA (CLI Proxy API) mới nhất và thử lại.", - "editor_description": "Choose which models a provider exposes using individual selections or wildcard rules.", - "models_hint": "Expand the list to select models, or enter wildcard rules below." + "editor_description": "Chọn các model mà provider hiển thị bằng cách chọn riêng lẻ hoặc dùng quy tắc ký tự đại diện (wildcard).", + "models_hint": "Mở rộng danh sách để chọn model hoặc nhập quy tắc ký tự đại diện bên dưới." }, "excluded_models": { "trigger_summary": "{{excluded}} bị loại trừ · {{available}} khả dụng", @@ -730,11 +730,11 @@ "upgrade_required": "Tính năng này yêu cầu phiên bản CLI Proxy API (CPA) mới hơn. Vui lòng nâng cấp.", "upgrade_required_title": "Vui lòng nâng cấp CLI Proxy API", "upgrade_required_desc": "Máy chủ hiện tại không hỗ trợ API bí danh model OAuth. Vui lòng nâng cấp lên phiên bản CLI Proxy API (CPA) mới nhất.", - "editor_description": "Give provider models consistent names for use in your clients.", - "edit_title": "Edit model aliases for {{provider}}", - "mapping_hint": "Choose a source model, then enter the alias your clients will use.", - "mapping_row": "Alias mapping {{number}}", - "remove_mapping": "Delete alias mapping {{number}}" + "editor_description": "Đặt tên gọi nhất quán cho các model của provider để sử dụng trong client của bạn.", + "edit_title": "Chỉnh sửa bí danh model cho {{provider}}", + "mapping_hint": "Chọn model gốc, sau đó nhập bí danh mà client của bạn sẽ dùng.", + "mapping_row": "Ánh xạ bí danh {{number}}", + "remove_mapping": "Xóa ánh xạ bí danh {{number}}" }, "auth_login": { "recommended_provider_section": "Provider đề xuất", @@ -837,48 +837,48 @@ "iflow_oauth_start_error": "Không thể bắt đầu iFlow OAuth:", "iflow_oauth_polling_error": "Không thể kiểm tra trạng thái xác thực:", "remote_access_disabled": "Phương thức đăng nhập này không khả dụng cho truy cập từ xa. Vui lòng truy cập từ localhost.", - "devin_oauth_cancel": "Cancel Devin Login", - "devin_oauth_cancelled": "Devin login cancelled.", - "devin_oauth_cancel_error": "Failed to cancel Devin login:", - "devin_oauth_retry_hint": "The server may still be waiting for authorization. Cancel this login before starting again.", + "devin_oauth_cancel": "Hủy đăng nhập Devin", + "devin_oauth_cancelled": "Đã hủy đăng nhập Devin.", + "devin_oauth_cancel_error": "Hủy đăng nhập Devin thất bại:", + "devin_oauth_retry_hint": "Máy chủ có thể vẫn đang chờ ủy quyền. Hãy hủy lượt đăng nhập này trước khi bắt đầu lại.", "devin_oauth_title": "Devin OAuth", - "devin_oauth_button": "Start Devin Login", - "devin_oauth_hint": "Sign in to Devin / Cognition through browser OAuth to save an authentication file. Requires CLI Proxy API v7.3.1 or later; complete authorization within five minutes.", - "devin_oauth_url_label": "Authorization URL:", - "devin_copy_link": "Copy Link", - "devin_open_link": "Open Link", - "devin_oauth_status_waiting": "Waiting for Devin authentication...", - "devin_oauth_status_success": "Devin authentication successful!", - "devin_oauth_status_error": "Devin authentication failed:", - "devin_oauth_start_error": "Failed to start Devin OAuth:", - "devin_callback_hint": "Remote server: copy the complete final URL ending in /devin/callback?… from the browser address bar, even if the loopback page cannot be reached. Keep its port, http/https, code and state unchanged. Submit the URL here, then wait for authentication to finish.", - "devin_callback_placeholder": "http://127.0.0.1:/devin/callback?code=...&state=...", - "devin_callback_invalid": "Paste the complete http/https callback URL containing state and an authorization code or error.", - "devin_callback_state_mismatch": "This callback does not belong to the current Devin login. Use the final URL from this attempt; do not reuse an old callback.", + "devin_oauth_button": "Bắt đầu đăng nhập Devin", + "devin_oauth_hint": "Đăng nhập Devin / Cognition qua trình duyệt OAuth để tự động lưu file xác thực. Yêu cầu CLI Proxy API v7.3.1 trở lên; vui lòng hoàn tất ủy quyền trong vòng năm phút.", + "devin_oauth_url_label": "URL ủy quyền:", + "devin_copy_link": "Sao chép liên kết", + "devin_open_link": "Mở liên kết", + "devin_oauth_status_waiting": "Đang chờ xác thực Devin...", + "devin_oauth_status_success": "Xác thực Devin thành công!", + "devin_oauth_status_error": "Xác thực Devin thất bại:", + "devin_oauth_start_error": "Không thể bắt đầu Devin OAuth:", + "devin_callback_hint": "Máy chủ từ xa: sao chép URL cuối cùng kết thúc bằng /devin/callback?… từ thanh địa chỉ trình duyệt, ngay cả khi không thể truy cập trang loopback. Giữ nguyên cổng, http/https, code và state. Gửi URL vào đây, sau đó tiếp tục chờ xác thực hoàn tất.", + "devin_callback_placeholder": "http://127.0.0.1:/devin/callback?code=...&state=...", + "devin_callback_invalid": "Dán URL callback http/https hoàn chỉnh chứa state và mã ủy quyền hoặc thông báo lỗi.", + "devin_callback_state_mismatch": "Callback này không thuộc về lượt đăng nhập Devin hiện tại. Vui lòng dùng URL cuối cùng từ lần thử này; không tái sử dụng callback cũ.", "meta_oauth_title": "Muse (Meta) OAuth", - "meta_oauth_button": "Log in with Muse", - "meta_oauth_hint": "Open the authorization link and enter the device code if requested. Authentication files are saved automatically after authorization.", - "meta_oauth_url_label": "Authorization URL:", - "meta_open_link": "Open Link", - "meta_copy_link": "Copy Link", - "meta_oauth_status_waiting": "Waiting for authentication...", - "meta_oauth_status_success": "Authentication successful!", - "meta_oauth_status_error": "Authentication failed:", - "meta_oauth_start_error": "Failed to start Muse OAuth:", - "meta_oauth_polling_error": "Failed to check authentication status:", - "device_code_label": "Device code:", - "device_code_copy": "Copy device code", - "kimi_ai_oauth_title": "Kimi International (kimi.ai)", - "kimi_ai_oauth_button": "Log in to Kimi International", - "kimi_ai_oauth_hint": "Authorize your kimi.ai international account via device login. A separate kimi-ai authentication file is saved automatically. China and international accounts are not interchangeable.", - "kimi_ai_oauth_url_label": "Authorization URL:", - "kimi_ai_open_link": "Open link", - "kimi_ai_copy_link": "Copy link", - "kimi_ai_oauth_status_waiting": "Waiting for authentication...", - "kimi_ai_oauth_status_success": "Authentication successful!", - "kimi_ai_oauth_status_error": "Authentication failed:", - "kimi_ai_oauth_start_error": "Failed to start Kimi International login:", - "kimi_ai_oauth_polling_error": "Failed to check authentication status:" + "meta_oauth_button": "Đăng nhập bằng Muse", + "meta_oauth_hint": "Mở liên kết ủy quyền và nhập mã thiết bị nếu được yêu cầu. File xác thực sẽ tự động được lưu sau khi ủy quyền.", + "meta_oauth_url_label": "URL ủy quyền:", + "meta_open_link": "Mở liên kết", + "meta_copy_link": "Sao chép liên kết", + "meta_oauth_status_waiting": "Đang chờ xác thực...", + "meta_oauth_status_success": "Xác thực thành công!", + "meta_oauth_status_error": "Xác thực thất bại:", + "meta_oauth_start_error": "Không thể bắt đầu Muse OAuth:", + "meta_oauth_polling_error": "Không thể kiểm tra trạng thái xác thực:", + "device_code_label": "Mã thiết bị:", + "device_code_copy": "Sao chép mã thiết bị", + "kimi_ai_oauth_title": "Kimi quốc tế (kimi.ai)", + "kimi_ai_oauth_button": "Đăng nhập Kimi quốc tế", + "kimi_ai_oauth_hint": "Ủy quyền tài khoản kimi.ai quốc tế qua đăng nhập thiết bị. File xác thực kimi-ai độc lập sẽ được lưu tự động. Tài khoản nội địa Trung Quốc và quốc tế không thể dùng thay thế cho nhau.", + "kimi_ai_oauth_url_label": "URL ủy quyền:", + "kimi_ai_open_link": "Mở liên kết", + "kimi_ai_copy_link": "Sao chép liên kết", + "kimi_ai_oauth_status_waiting": "Đang chờ xác thực...", + "kimi_ai_oauth_status_success": "Xác thực thành công!", + "kimi_ai_oauth_status_error": "Xác thực thất bại:", + "kimi_ai_oauth_start_error": "Không thể bắt đầu đăng nhập Kimi quốc tế:", + "kimi_ai_oauth_polling_error": "Không thể kiểm tra trạng thái xác thực:" }, "stats": { "success": "Thành công", @@ -954,27 +954,27 @@ "double_click_copy_hint": "Nhấp đúp để sao chép dòng log thô", "copy_success": "Đã sao chép log vào clipboard", "copy_failed": "Sao chép thất bại", - "preview_too_large": "This request log exceeds the 2 MiB preview limit. Download it to view.", - "read_status_live": "Reading continuously", - "read_status_paused": "Reading paused", - "read_status_catching_up": "Catching up on queued logs", - "last_updated": "Last successful update: {{time}}", - "buffer_scope": "Searching loaded logs only: {{count}} lines cached, {{matched}} lines matched", - "buffer_evicted": "Older logs have been removed from the cache and cannot be searched here", - "cursor_reset_notice": "Logs were rotated or reset. The latest content has been reloaded.", - "history_evicted": "Your reading position is no longer cached. Please choose a new position.", - "resume_following": "Back to latest · New lines: {{count}}", - "level_filter": "Log level", - "all_levels": "All levels", - "view_request": "View log for request {{id}}", - "copy_line": "Copy this line", - "request_log_missing": "Request log not found: it may not have been recorded or may have been cleaned up. When request logging is disabled, only error request logs are usually retained.", - "download_cached": "Download cached logs", - "clear_application_confirm": "Clear application logs on the server? Request log files will not be deleted. This action cannot be undone.", - "clear_search": "Clear search", - "reading_enabled": "Continuous reading", - "filter_load_more": "Show more matching logs", - "wrap_lines": "Wrap long lines" + "preview_too_large": "Bản ghi yêu cầu này vượt quá giới hạn xem trước 2 MiB. Vui lòng tải xuống để xem.", + "read_status_live": "Đang đọc liên tục", + "read_status_paused": "Đã tạm dừng đọc", + "read_status_catching_up": "Đang đuổi kịp các bản ghi log tồn đọng", + "last_updated": "Cập nhật thành công lần cuối: {{time}}", + "buffer_scope": "Chỉ tìm kiếm trong các bản ghi đã tải: {{count}} dòng trong bộ nhớ cache, khớp {{matched}} dòng", + "buffer_evicted": "Các bản ghi log cũ hơn đã bị xóa khỏi cache và không thể tìm kiếm tại đây", + "cursor_reset_notice": "Bản ghi log đã được xoay vòng hoặc đặt lại. Nội dung mới nhất đã được tải lại.", + "history_evicted": "Vị trí đọc của bạn không còn trong cache. Vui lòng chọn vị trí mới.", + "resume_following": "Về mới nhất · Dòng mới: {{count}}", + "level_filter": "Cấp độ log", + "all_levels": "Tất cả cấp độ", + "view_request": "Xem log cho yêu cầu {{id}}", + "copy_line": "Sao chép dòng này", + "request_log_missing": "Không tìm thấy log yêu cầu: có thể chưa được ghi hoặc đã được dọn dẹp. Khi tính năng ghi log yêu cầu bị tắt, thường chỉ các log yêu cầu lỗi mới được giữ lại.", + "download_cached": "Tải xuống log trong cache", + "clear_application_confirm": "Xóa log ứng dụng trên máy chủ? Các file log yêu cầu sẽ không bị xóa. Hành động này không thể hoàn tác.", + "clear_search": "Xóa tìm kiếm", + "reading_enabled": "Đọc liên tục", + "filter_load_more": "Hiển thị thêm log phù hợp", + "wrap_lines": "Tự động xuống dòng dài" }, "config_management": { "title": "Bảng cấu hình", @@ -1129,16 +1129,16 @@ "antigravity_signature_cache_desc": "Ưu tiên và xác thực chữ ký thinking-block đã cache", "antigravity_signature_strict": "Bỏ qua xác thực chữ ký nghiêm ngặt", "antigravity_signature_strict_desc": "Chỉ áp dụng khi cache chữ ký bị tắt; xác thực toàn bộ cây protobuf Claude", - "antigravity_sensitive_words": "Sensitive Word Obfuscation", - "antigravity_sensitive_words_desc": "Insert zero-width characters into matching words in Antigravity system instructions to reduce exact keyword matching upstream", - "antigravity_sensitive_words_label": "OAuth sensitive words (oauth.providers.antigravity.sensitive-words)", + "antigravity_sensitive_words": "Làm rối từ nhạy cảm", + "antigravity_sensitive_words_desc": "Chèn ký tự có độ rộng bằng 0 (zero-width) vào các từ khớp trong hướng dẫn hệ thống Antigravity để giảm khả năng so khớp từ khóa chính xác ở upstream", + "antigravity_sensitive_words_label": "Từ nhạy cảm OAuth (oauth.providers.antigravity.sensitive-words)", "antigravity_sensitive_words_placeholder": "proxy", - "antigravity_sensitive_words_hint": "One word or phrase per row. Matching is case-insensitive; empty entries are removed and entries shorter than 2 characters are ignored by the backend", - "devin_sensitive_words": "Devin System Prompt Sensitive Words", - "devin_sensitive_words_desc": "In Devin system prompts only, a line containing a configured word is removed in full; the remaining system prompt is then obfuscated. Regular messages and tool arguments are not changed", - "devin_sensitive_words_label": "OAuth sensitive words (oauth.providers.devin.sensitive-words)", - "devin_sensitive_words_placeholder": "sensitive phrase", - "devin_sensitive_words_hint": "One word or phrase per row. Configure carefully: matching content causes the entire system-prompt line to be deleted; empty entries are removed when saved" + "antigravity_sensitive_words_hint": "Mỗi hàng một từ hoặc cụm từ. Không phân biệt chữ hoa chữ thường; các mục trống sẽ bị xóa và các mục ngắn hơn 2 ký tự sẽ bị backend bỏ qua", + "devin_sensitive_words": "Từ nhạy cảm trong System Prompt Devin", + "devin_sensitive_words_desc": "Chỉ áp dụng trong system prompt Devin: dòng chứa từ đã cấu hình sẽ bị xóa hoàn toàn; phần system prompt còn lại sau đó sẽ được làm rối. Tin nhắn thông thường và tham số công cụ không bị thay đổi", + "devin_sensitive_words_label": "Từ nhạy cảm OAuth (oauth.providers.devin.sensitive-words)", + "devin_sensitive_words_placeholder": "cụm từ nhạy cảm", + "devin_sensitive_words_hint": "Mỗi hàng một từ hoặc cụm từ. Cấu hình cẩn thận: nội dung khớp sẽ khiến toàn bộ dòng system prompt bị xóa; các mục trống sẽ bị xóa khi lưu" }, "headers": { "title": "Header mặc định", @@ -1188,8 +1188,8 @@ "session_affinity": "Định tuyến Session Affinity", "ws_auth": "Xác thực WebSocket", "ws_auth_desc": "Bật xác thực WebSocket (/v1/ws)", - "proxy_url_sponsor_hint": "No suitable proxy?", - "max_retry_interval_hint": "Set to 0 or a negative integer to skip cooldown waits between retry rounds." + "proxy_url_sponsor_hint": "Chưa có proxy phù hợp?", + "max_retry_interval_hint": "Đặt thành 0 hoặc số nguyên âm để bỏ qua thời gian chờ cooldown giữa các lượt thử lại." }, "quota": { "title": "Quota dự phòng", @@ -1247,10 +1247,10 @@ "good": "Tốt", "strong": "Mạnh" }, - "name_label": "Name / description (optional)", - "name_placeholder": "For example: Alice's laptop", - "name_hint": "Saved immediately in this browser only, separately for each server. Not included in server configuration. Clear this field to remove the name.", - "name_save_error": "Could not save the name in browser storage. Check your browser storage settings." + "name_label": "Tên / mô tả (tùy chọn)", + "name_placeholder": "Ví dụ: Laptop của Alice", + "name_hint": "Được lưu ngay trong trình duyệt này, riêng cho từng máy chủ. Không bao gồm trong cấu hình máy chủ. Xóa trường này để xóa tên.", + "name_save_error": "Không thể lưu tên vào bộ lưu trữ trình duyệt. Vui lòng kiểm tra cài đặt lưu trữ của trình duyệt." }, "payload_rules": { "rule": "Quy tắc", @@ -1310,17 +1310,17 @@ "payload_invalid_number": "Nhập số hợp lệ", "payload_invalid_boolean": "Chọn true hoặc false", "payload_invalid_json": "Nhập JSON hợp lệ", - "invalid_trusted_proxies": "Each trusted proxy must be a valid IP address or CIDR.", - "invalid_discovery_service_type": "Use _name._tcp: name must be 1–15 letters, digits or hyphens, with no leading or trailing hyphen.", - "invalid_duration": "Enter a valid duration, such as 30s or 3h", - "positive_duration": "Enter a duration greater than zero", - "invalid_timezone": "Enter a valid IANA timezone, such as Asia/Singapore", - "invalid_ip": "Enter a valid IPv4 or IPv6 address", - "udp_port_pair": "Set both UDP ports to 0, or set both with the minimum not exceeding the maximum", - "udp_port_capacity": "The UDP range must contain at least twice the effective maximum session count in ports (0 sessions uses 32)", - "invalid_ice_servers": "Each ICE server needs at least one valid stun:, stuns:, turn:, or turns: URL", - "integer_range_0_65535": "Enter a whole number between 0 and 65535", - "integer": "Enter a whole number" + "invalid_trusted_proxies": "Mỗi proxy đáng tin cậy phải là một địa chỉ IP hoặc CIDR hợp lệ.", + "invalid_discovery_service_type": "Sử dụng định dạng _tên._tcp: tên phải gồm 1–15 chữ cái, chữ số hoặc dấu gạch nối, không bắt đầu hoặc kết thúc bằng dấu gạch nối.", + "invalid_duration": "Nhập khoảng thời gian hợp lệ, chẳng hạn như 30s hoặc 3h", + "positive_duration": "Nhập khoảng thời gian lớn hơn 0", + "invalid_timezone": "Nhập múi giờ IANA hợp lệ, chẳng hạn như Asia/Ho_Chi_Minh hoặc Asia/Singapore", + "invalid_ip": "Nhập địa chỉ IPv4 hoặc IPv6 hợp lệ", + "udp_port_pair": "Đặt cả hai cổng UDP thành 0, hoặc đặt cả hai với giá trị tối thiểu không vượt quá tối đa", + "udp_port_capacity": "Phạm vi UDP phải chứa số cổng tối thiểu bằng hai lần số lượng phiên tối đa hiệu dụng (0 phiên sẽ tính là 32)", + "invalid_ice_servers": "Mỗi máy chủ ICE cần ít nhất một URL stun:, stuns:, turn:, hoặc turns: hợp lệ", + "integer_range_0_65535": "Nhập số nguyên từ 0 đến 65535", + "integer": "Nhập một số nguyên" }, "common": { "edit": "Chỉnh sửa", @@ -1331,169 +1331,169 @@ }, "serverExtras": { "trustedProxies": { - "label": "Trusted proxies", - "hint": "IP addresses or CIDRs; empty means forwarded headers are not trusted. Trusting all-address ranges risks client IP spoofing. Requires a backend restart." + "label": "Proxy đáng tin cậy", + "hint": "Địa chỉ IP hoặc CIDR; để trống nghĩa là các header chuyển tiếp không được tin cậy. Tin cậy dải mạng chứa tất cả địa chỉ có nguy cơ giả mạo IP client. Yêu cầu khởi động lại backend." }, "discoveryEnabled": { - "label": "Enable discovery", - "hint": "Broadcast via mDNS / DNS-SD on the LAN. Off by default; changes apply without a restart." + "label": "Bật khám phá dịch vụ", + "hint": "Phát quảng bá qua mDNS / DNS-SD trong mạng cục bộ (LAN). Mặc định tắt; thay đổi có hiệu lực mà không cần khởi động lại." }, "discoveryServiceName": { - "label": "Service name prefix", - "hint": "The backend appends a short ID. Empty uses CPA-." + "label": "Tiền tố tên dịch vụ", + "hint": "Backend sẽ nối thêm một ID ngắn. Để trống sẽ dùng CPA-." }, "discoveryServiceType": { - "label": "Service type", - "hint": "Empty uses _ai-gateway._tcp." + "label": "Loại dịch vụ", + "hint": "Để trống sẽ dùng _ai-gateway._tcp." }, "discoverySubtypes": { - "label": "Protocol subtypes", - "hint": "Empty uses the five default protocols. Missing leading _ is added; invalid entries are ignored." + "label": "Phân loại giao thức con", + "hint": "Để trống sẽ dùng năm giao thức mặc định. Thiếu tiền tố _ sẽ tự động được thêm; các mục không hợp lệ sẽ bị bỏ qua." }, "discoveryInterfacesInclude": { - "label": "Include interfaces", - "hint": "Empty auto-selects physical LAN interfaces. Use names or prefix patterns ending in *." + "label": "Bao gồm giao diện mạng", + "hint": "Để trống sẽ tự động chọn giao diện mạng LAN vật lý. Dùng tên hoặc mẫu tiền tố kết thúc bằng *." }, "discoveryInterfacesExclude": { - "label": "Exclude interfaces", - "hint": "Use names or prefix patterns ending in *. Exclusions take priority over inclusions." + "label": "Loại trừ giao diện mạng", + "hint": "Dùng tên hoặc mẫu tiền tố kết thúc bằng *. Quy tắc loại trừ được ưu tiên hơn quy tắc bao gồm." }, "discoveryAuthRequired": { - "label": "Advertise authentication requirement", - "hint": "On by default. Broadcast metadata only; does not change actual API authentication." + "label": "Quảng bá yêu cầu xác thực", + "hint": "Mặc định bật. Chỉ quảng bá siêu dữ liệu (metadata); không thay đổi quy trình xác thực API thực tế." }, "discoveryAdvertiseManagement": { - "label": "Advertise management service", - "hint": "Off by default. Only announces the management service exists; does not change remote access permissions." + "label": "Quảng bá dịch vụ quản lý", + "hint": "Mặc định tắt. Chỉ thông báo dịch vụ quản lý tồn tại; không thay đổi quyền truy cập từ xa." }, - "discoveryTitle": "LAN discovery", - "discoveryHint": "Requires multicast-capable physical interfaces and a non-loopback listener. Docker usually needs host networking; reachability is not guaranteed." + "discoveryTitle": "Khám phá mạng cục bộ (LAN)", + "discoveryHint": "Yêu cầu giao diện mạng vật lý hỗ trợ multicast và địa chỉ lắng nghe non-loopback. Docker thường cần host networking; không đảm bảo khả năng tiếp cận." }, "additions": { - "oauthTitle": "OAuth provider behavior", - "oauthHint": "These provider settings apply only to OAuth/file-backed credentials, not API-key credentials.", + "oauthTitle": "Hành vi của provider OAuth", + "oauthHint": "Các cài đặt provider này chỉ áp dụng cho credential OAuth / file xác thực, không áp dụng cho credential API key.", "claudeTitle": "Claude", "codexTitle": "Codex", "antigravityTitle": "Antigravity", "xaiTitle": "xAI", "liveRelayTitle": "Codex Live media relay", - "liveRelayHint": "Relay WebRTC audio and DataChannel traffic in the proxy process. Inbound UDP must be reachable. Keep ICE credentials out of screenshots and logs.", - "iceAdd": "Add ICE server", - "iceRemove": "Remove ICE server {{index}}", - "iceURLs": "STUN/TURN URLs", - "iceUsername": "TURN username", - "iceCredential": "TURN password", - "iceServer": "ICE server {{index}}", + "liveRelayHint": "Chuyển tiếp âm thanh WebRTC và lưu lượng DataChannel trong tiến trình proxy. UDP chiều đến phải truy cập được. Không để lộ thông tin xác thực ICE trong ảnh chụp màn hình hoặc log.", + "iceAdd": "Thêm máy chủ ICE", + "iceRemove": "Xóa máy chủ ICE {{index}}", + "iceURLs": "URL STUN/TURN", + "iceUsername": "Tên người dùng TURN", + "iceCredential": "Mật khẩu TURN", + "iceServer": "Máy chủ ICE {{index}}", "routingSessionAffinitySubagents": { - "label": "Subagent session affinity", - "hint": "Enabled by default; only effective when session affinity is enabled. Subagents inherit their parent's credential to reuse caches. Disable to distribute subagents across the credential pool for greater concurrency." + "label": "Session affinity cho subagent", + "hint": "Mặc định bật; chỉ có hiệu lực khi session affinity được bật. Subagent kế thừa credential của cha để tái sử dụng cache. Tắt để phân bổ subagent trên toàn bộ pool credential nhằm tăng tính đồng thời." }, "saveCooldownStatus": { - "label": "Persist cooldown status", - "hint": "Save per-credential cooldown status in .cds files beside auth files. Disabled by default; otherwise status is kept only in memory." + "label": "Lưu trữ bền vững trạng thái cooldown", + "hint": "Lưu trạng thái cooldown của từng credential vào các file .cds cạnh file xác thực. Mặc định tắt; nếu tắt trạng thái chỉ được giữ trong bộ nhớ." }, "transientErrorCooldownSeconds": { - "label": "Transient error cooldown (seconds)", - "hint": "Cooldown for upstream 408/500/502/503/504/520–526 errors. 0 uses the default 60 seconds; a negative value disables this cooldown." + "label": "Thời gian cooldown lỗi tạm thời (giây)", + "hint": "Thời gian cooldown cho các lỗi 408/500/502/503/504/520–526 từ upstream. 0 sử dụng mặc định 60 giây; giá trị âm sẽ tắt cooldown này." }, "videoResultAuthCacheTTL": { - "label": "Video result credential cache TTL", - "hint": "How long video IDs remain bound to the credential that created them. Use a duration such as 30m or 3h; default: 3h." + "label": "TTL cache credential của kết quả video", + "hint": "Thời gian ID video duy trì liên kết với credential đã tạo ra nó. Nhập khoảng thời gian như 30m hoặc 3h; mặc định: 3h." }, "claudeHeaderTimezone": { - "label": "Fallback timezone", - "hint": "IANA timezone for the cloaked currentDate, e.g. Asia/Singapore, or Local for the backend host's timezone. The credential JSON's timezone takes priority." + "label": "Múi giờ dự phòng", + "hint": "Múi giờ IANA cho currentDate được ngụy trang, ví dụ: Asia/Ho_Chi_Minh, Asia/Singapore, hoặc Local cho múi giờ của máy chủ backend. Múi giờ trong JSON của credential được ưu tiên." }, "claudeModelLevelCooling": { - "label": "Model-level cooldown", - "hint": "Apply Claude quota cooldowns only to the requested model, rather than all models sharing the credential. Disabled by default." + "label": "Cooldown theo cấp độ model", + "hint": "Chỉ áp dụng cooldown quota Claude cho model được yêu cầu, thay vì tất cả các model dùng chung credential. Mặc định tắt." }, "claudeDisableCloakMode": { - "label": "Disable request cloaking", - "hint": "Disable the Claude Code CLI disguise and system prompt replacement; pass through the original system prompt. Credential files can override this with cloak_mode. Default: false (automatic cloaking for non-Claude-Code clients)." + "label": "Tắt ngụy trang yêu cầu", + "hint": "Tắt ngụy trang danh tính Claude Code CLI và thay thế system prompt; truyền qua system prompt gốc. File credential có thể ghi đè bằng cloak_mode. Mặc định: false (tự động ngụy trang cho client không phải Claude Code)." }, "claudeCodeDisableCloakingModelList": { - "label": "Disable model ID cloaking", - "hint": "Return original model IDs in Anthropic model list responses instead of cloaked IDs. Disabled by default." + "label": "Tắt ngụy trang ID model", + "hint": "Trả về ID model gốc trong phản hồi danh sách model Anthropic thay vì ID đã ngụy trang. Mặc định tắt." }, "codexDisableCloaking": { - "label": "Disable request cloaking", - "hint": "Stop forcing official Codex User-Agent and Originator headers on HTTP/SSE and WebSocket requests. Disabled by default." + "label": "Tắt ngụy trang yêu cầu", + "hint": "Dừng ép buộc header User-Agent và Originator chính thức của Codex trên các yêu cầu HTTP/SSE và WebSocket. Mặc định tắt." }, "codexModelLevelCooling": { - "label": "Model-level cooldown", - "hint": "Apply usage_limit_reached quota cooldowns only to the requested model, rather than all models sharing the credential. Disabled by default." + "label": "Cooldown theo cấp độ model", + "hint": "Chỉ áp dụng cooldown quota usage_limit_reached cho model được yêu cầu, thay vì tất cả các model dùng chung credential. Mặc định tắt." }, "codexStreamBootstrapBuffering": { - "label": "Buffer stream bootstrap", - "hint": "Hold initial empty events and heartbeats to allow credential failover on early overload or rate-limit rejections. Disabled by default. Delays response headers and may trigger client or reverse-proxy timeouts; buffering has frame and byte budgets." + "label": "Đệm khởi động stream", + "hint": "Tạm giữ các sự kiện rỗng và heartbeat ban đầu để cho phép chuyển đổi credential (failover) khi gặp quá tải sớm hoặc bị từ chối do giới hạn tốc độ. Mặc định tắt. Làm trễ header phản hồi và có thể kích hoạt timeout ở client hoặc reverse proxy; việc đệm có hạn mức frame và byte." }, "codexStreamBootstrapTimeout": { - "label": "Stream bootstrap timeout", - "hint": "Optional buffering time limit, e.g. 20s. Default: 0 (unlimited time; frame and byte budgets still apply). Checked as upstream frames arrive; not a hard deadline for every network stall. Headers may still wait for translated output." + "label": "Timeout đệm khởi động stream", + "hint": "Giới hạn thời gian đệm tùy chọn, ví dụ: 20s. Mặc định: 0 (không giới hạn thời gian; hạn mức frame và byte vẫn áp dụng). Được kiểm tra khi các frame từ upstream đến; không phải hạn chót cứng cho mọi trường hợp treo mạng. Header vẫn có thể phải chờ đầu ra đã được dịch." }, "codexOptimizeMultiAgentV2": { - "label": "Optimize multi-agent v2", - "hint": "Optimize official Codex multi-agent requests: refresh spawn_agent model details, remove message parameter encryption, normalize agent_message content, and convert it to user messages for non-Codex protocols. Disabled by default." + "label": "Tối ưu hóa multi-agent v2", + "hint": "Tối ưu hóa các yêu cầu multi-agent chính thức của Codex: làm mới chi tiết model spawn_agent, loại bỏ mã hóa tham số thông điệp, chuẩn hóa nội dung agent_message và chuyển đổi thành tin nhắn người dùng cho các giao thức không phải Codex. Mặc định tắt." }, "codexOrphanDelegationCompatibility": { - "label": "Orphan delegation compatibility", - "hint": "For X-Openai-Subagent: collab_spawn requests, convert orphan codex_app/create_thread and codex_app/send_message_to_thread outputs without a valid matching call into user messages. Disabled by default." + "label": "Tương thích ủy quyền mồ côi (orphan delegation)", + "hint": "Đối với yêu cầu X-Openai-Subagent: collab_spawn, chuyển đổi đầu ra mồ côi của codex_app/create_thread và codex_app/send_message_to_thread không có lệnh gọi khớp hợp lệ thành tin nhắn người dùng. Mặc định tắt." }, "codexResponseSteering": { - "label": "Response steering", - "hint": "Experimental full-duplex Codex Responses WebSockets. Each socket stays bound to one upstream account and model; accepted input is never replayed. Disabled by default." + "label": "Điều hướng phản hồi (Response steering)", + "hint": "Tính năng thử nghiệm WebSocket Codex Responses song công toàn phần (full-duplex). Mỗi socket luôn gắn chặt với một tài khoản và model upstream; đầu vào đã được chấp nhận sẽ không bao giờ phát lại. Mặc định tắt." }, "antigravityConnectionPoolEnabled": { - "label": "Enable connection pooling", - "hint": "Reuse upstream HTTP/1.1 connections. Default: false (short-lived connections)." + "label": "Bật connection pool", + "hint": "Tái sử dụng các kết nối HTTP/1.1 upstream. Mặc định: false (kết nối ngắn hạn)." }, "antigravityConnectionPoolIdleTimeout": { - "label": "Idle connection timeout", - "hint": "How long idle connections remain in the pool. Default: 30s; capped at 210s. Zero or a negative duration switches to short-lived connections." + "label": "Timeout kết nối nhàn rỗi", + "hint": "Thời gian kết nối nhàn rỗi tồn tại trong pool. Mặc định: 30s; giới hạn tối đa 210s. Bằng 0 hoặc thời lượng âm sẽ chuyển sang kết nối ngắn hạn." }, "antigravityConnectionPoolMaxIdleConnsPerHost": { - "label": "Maximum idle connections per host", - "hint": "Maximum idle connections retained per upstream host per credential. Default: 2; capped at 100. Zero uses Go's default of 2; a negative value switches to short-lived connections." + "label": "Số kết nối nhàn rỗi tối đa trên mỗi host", + "hint": "Số kết nối nhàn rỗi tối đa được duy trì cho mỗi host upstream trên mỗi credential. Mặc định: 2; giới hạn tối đa 100. Bằng 0 sẽ dùng mặc định của Go là 2; giá trị âm sẽ chuyển sang kết nối ngắn hạn." }, "xaiInjectXSearch": { - "label": "Inject x_search", - "hint": "Add xAI's native x_search tool when absent from the request, including tool_choice.allowed_tools when applicable. Disabled by default." + "label": "Chèn x_search", + "hint": "Tự động thêm công cụ x_search gốc của xAI khi thiếu trong yêu cầu, bao gồm tool_choice.allowed_tools khi áp dụng. Mặc định tắt." }, "codexLiveMediaRelayEnabled": { - "label": "Enable media relay", - "hint": "Terminate and relay Codex Live WebRTC media in this process. Requires inbound UDP reachability. Disabled by default to preserve direct media connections." + "label": "Bật media relay", + "hint": "Chấm dứt và chuyển tiếp phương tiện Codex Live WebRTC trong tiến trình này. Yêu cầu UDP chiều đến phải truy cập được. Mặc định tắt để giữ kết nối phương tiện trực tiếp." }, "codexLiveMediaRelayMaxSessions": { - "label": "Maximum concurrent media sessions", - "hint": "Blank or 0 uses the default of 32 sessions. A custom UDP range must provide at least two ports per session." + "label": "Số phiên phương tiện đồng thời tối đa", + "hint": "Để trống hoặc 0 sẽ dùng mặc định 32 phiên. Dải cổng UDP tùy chỉnh phải cung cấp ít nhất hai cổng cho mỗi phiên." }, "codexLiveMediaRelayDisablePrivateRemoteIPs": { - "label": "Block private remote IP candidates", - "hint": "Default: false, allowing private candidates for local or trusted-network clients. Enable to reject downstream SDP candidates targeting private, loopback, link-local, or unspecified IPs and reduce internal-network exposure; local connections may fail." + "label": "Chặn ứng viên IP từ xa riêng tư", + "hint": "Mặc định: false, cho phép ứng viên địa chỉ riêng tư cho các client mạng cục bộ hoặc đáng tin cậy. Bật để từ chối các ứng viên SDP hạ lưu trỏ tới IP riêng tư, loopback, link-local hoặc chưa chỉ định nhằm giảm nguy cơ lộ mạng nội bộ; các kết nối cục bộ có thể thất bại." }, "codexLiveMediaRelayPublicIP": { - "label": "Advertised public IP", - "hint": "Optional public IPv4 or IPv6 address to advertise when the proxy is behind 1:1 NAT. Enter an IP address, not a hostname." + "label": "IP công khai được thông báo", + "hint": "Địa chỉ IPv4 hoặc IPv6 công khai tùy chọn để thông báo khi proxy nằm sau 1:1 NAT. Nhập địa chỉ IP, không phải hostname." }, "codexLiveMediaRelayUDPPortMin": { - "label": "Minimum UDP port", - "hint": "Set both UDP bounds to 0 for system allocation, or specify an inclusive continuous range with at least twice the effective session limit in ports." + "label": "Cổng UDP tối thiểu", + "hint": "Đặt cả hai giới hạn UDP thành 0 để hệ thống tự phân bổ, hoặc chỉ định một dải liên tục bao gồm cả hai đầu với số cổng ít nhất gấp đôi giới hạn phiên hiệu dụng." }, "codexLiveMediaRelayUDPPortMax": { - "label": "Maximum UDP port", - "hint": "Must be at least the minimum port. Both bounds must be 0 or both nonzero; a custom range needs at least two ports per session (64 with the default 32 sessions)." + "label": "Cổng UDP tối đa", + "hint": "Phải lớn hơn hoặc bằng cổng tối thiểu. Cả hai giới hạn phải cùng bằng 0 hoặc cùng khác 0; dải tùy chỉnh cần ít nhất hai cổng cho mỗi phiên (64 cổng với mặc định 32 phiên)." }, "codexLiveMediaRelayICEServers": { - "label": "ICE servers", - "hint": "Optional STUN/TURN servers using stun:, stuns:, turn:, or turns: URLs. TURN credentials are omitted from the JSON config API. Enter the credential as a password and keep secrets out of screenshots and logs." + "label": "Máy chủ ICE", + "hint": "Các máy chủ STUN/TURN tùy chọn dùng URL stun:, stuns:, turn:, hoặc turns:. Thông tin xác thực TURN được bỏ qua trong API cấu hình JSON. Nhập thông tin xác thực dưới dạng mật khẩu và không để lộ bí mật trong ảnh chụp màn hình hay log." } } }, - "source_changes_before_visual": "Save or discard your unsaved source edits before switching to visual mode.", - "precise_save_incomplete": "The precise save did not finish; some changes may already be applied. Your draft is retained. Save again to review the remaining server differences.", - "concurrent_list_conflict": "The server list {{path}} changed after your draft baseline. Saving was blocked to avoid overwriting those changes. Your draft is retained; note your edits, then reload the configuration and reconcile them.", - "precise_save_recovery_required": "Could not read back the save result. Editing is paused. Save again to recover the draft baseline, or reload the configuration." + "source_changes_before_visual": "Lưu hoặc hủy các chỉnh sửa mã nguồn chưa lưu trước khi chuyển sang chế độ trực quan.", + "precise_save_incomplete": "Quá trình lưu chính xác chưa hoàn tất; một số thay đổi có thể đã được áp dụng. Bản nháp của bạn được giữ lại. Hãy lưu lại để xem xét các khác biệt còn lại trên máy chủ.", + "concurrent_list_conflict": "Danh sách trên máy chủ {{path}} đã thay đổi sau mốc cơ sở bản nháp của bạn. Thao tác lưu bị chặn để tránh ghi đè các thay đổi đó. Bản nháp của bạn được giữ lại; hãy ghi lại các chỉnh sửa, sau đó tải lại cấu hình và hợp nhất.", + "precise_save_recovery_required": "Không thể đọc lại kết quả lưu. Đã tạm dừng chỉnh sửa. Lưu lại để khôi phục mốc cơ sở của bản nháp, hoặc tải lại cấu hình." }, "quota_management": { "title": "Quản lý Quota", @@ -1536,11 +1536,11 @@ "weekday_thu": "T5", "weekday_fri": "T6", "weekday_sat": "T7", - "search_label": "Search accounts", - "search_placeholder": "Search by filename or email", - "search_empty_title": "No matching accounts", - "search_empty_desc": "Try another filename or email, or clear the search.", - "search_clear": "Clear search" + "search_label": "Tìm kiếm tài khoản", + "search_placeholder": "Tìm theo tên file hoặc email", + "search_empty_title": "Không có tài khoản phù hợp", + "search_empty_desc": "Hãy thử tên file hoặc email khác, hoặc xóa tìm kiếm.", + "search_clear": "Xóa tìm kiếm" }, "plugin_management": { "title": "Quản lý Plugin", @@ -1750,12 +1750,12 @@ "commercial_mode_restart_required": "Đã đổi cài đặt chế độ thương mại. Vui lòng khởi động lại dịch vụ để có hiệu lực", "copy_failed": "Sao chép thất bại", "link_copied": "Đã sao chép liên kết vào clipboard", - "trusted_proxies_restart_required": "Trusted proxy settings saved. Restart the backend to apply them.", - "region_label": "Notifications", - "type_success": "Success", - "type_info": "Information", - "type_warning": "Warning", - "type_error": "Error" + "trusted_proxies_restart_required": "Đã lưu cài đặt proxy đáng tin cậy. Hãy khởi động lại backend để áp dụng.", + "region_label": "Thông báo", + "type_success": "Thành công", + "type_info": "Thông tin", + "type_warning": "Cảnh báo", + "type_error": "Lỗi" }, "language": { "switch": "Ngôn ngữ", @@ -1845,7 +1845,7 @@ "empty": "Chưa có tài nguyên nào, nhấn \"Mới\" để thêm.", "filterPlaceholder": "Tìm key, URL, tiền tố…", "description": "Quản lý tài nguyên trong {{route}}", - "cliProfileTag": "CLI Profile" + "cliProfileTag": "Hồ sơ CLI" }, "sponsor": { "protocolSummary": "Anthropic / OpenAI / Gemini / Codex API (Responses)", @@ -1917,7 +1917,7 @@ "gemini": "Gemini", "codexResponses": "Codex API (Responses)" }, - "kimiPromo": "New users get API credit worth 10% of their first successful top-up, up to ¥1000. Offer ends September 30." + "kimiPromo": "Người dùng mới nạp tiền lần đầu thành công sẽ được tặng hạn mức API trị giá 10% số tiền nạp, tối đa ¥1000. Ưu đãi kết thúc vào ngày 30 tháng 9." }, "status": { "active": "Đang hoạt động", @@ -2011,10 +2011,10 @@ "weightInteger": "Trọng số điều phối phải là số nguyên", "weightMax": "Trọng số điều phối không được vượt quá {{max}}" }, - "fingerprintProfile": "Request fingerprint", - "fingerprintProfileDefault": "Default (caller-owned)", + "fingerprintProfile": "Dấu vân tay yêu cầu", + "fingerprintProfileDefault": "Mặc định (do phía gọi kiểm soát)", "fingerprintProfileClaudeCodeCli": "Claude Code CLI", - "fingerprintProfileHint": "Keep the caller's prompt and headers by default, or opt in to the Claude Code CLI request fingerprint." + "fingerprintProfileHint": "Mặc định giữ nguyên prompt và header của phía gọi, hoặc chọn sử dụng dấu vân tay yêu cầu của Claude Code CLI." }, "delete": { "title": "Xóa tài nguyên", @@ -2080,157 +2080,157 @@ "notLoaded": "Chưa tải" }, "behavior": { - "title": "Provider-specific behavior", - "alphaSearch": "Enable Alpha Search", - "alphaSearchHint": "Allow this Codex key to serve Alpha Search. The upstream must support it.", - "codexCloaking": "Codex request cloaking", - "codexCloakingHint": "Override official Codex identity headers for this API key. Default removes the credential override; OAuth-only settings do not apply here.", - "useDefault": "Use backend default", - "cloakingEnabled": "Enable cloaking", - "cloakingDisabled": "Disable cloaking", - "rebuildMidSystemMessage": "Rebuild system messages", - "rebuildMidSystemMessageHint": "Move Claude messages with role system into the top-level system field.", - "supportPromptCacheKey": "Inject prompt cache key", - "supportPromptCacheKeyHint": "Derive and inject prompt_cache_key for compatible requests. Enable only when the upstream supports this field." + "title": "Hành vi dành riêng cho provider", + "alphaSearch": "Bật Alpha Search", + "alphaSearchHint": "Cho phép key Codex này phục vụ Alpha Search. Upstream phải hỗ trợ tính năng này.", + "codexCloaking": "Ngụy trang yêu cầu Codex", + "codexCloakingHint": "Ghi đè các header định danh Codex chính thức cho API key này. Mặc định sẽ xóa ghi đè của credential; các cài đặt chỉ dành cho OAuth không áp dụng ở đây.", + "useDefault": "Dùng mặc định của backend", + "cloakingEnabled": "Bật ngụy trang", + "cloakingDisabled": "Tắt ngụy trang", + "rebuildMidSystemMessage": "Tái cấu trúc thông điệp hệ thống", + "rebuildMidSystemMessageHint": "Chuyển các tin nhắn Claude có role là system vào trường system ở cấp cao nhất.", + "supportPromptCacheKey": "Chèn prompt cache key", + "supportPromptCacheKeyHint": "Tạo và chèn prompt_cache_key cho các yêu cầu tương thích. Chỉ bật khi upstream hỗ trợ trường này." }, "modelOptions": { - "displayName": "Display name", - "maxContextLength": "Context length", - "contextHint": "Non-negative integer; leave empty to use the default.", - "forceMapping": "Rewrite response model to alias", - "isCompat": "Compatibility mode", - "supportConfigurationUpdate": "Allow configuration updates", - "inputModalitiesText": "Input modalities", - "outputModalitiesText": "Output modalities", - "modalitiesHint": "Separate values with commas or whitespace. Custom modality names are preserved.", - "useMaxCompletionTokens": "Use max_completion_tokens", - "thinkingMode": "Thinking override", - "useDefault": "Use default", - "custom": "Custom", - "thinkingHint": "Default inherits backend behavior; an empty custom override is an explicit {}. Budgets and effort levels can coexist. Only when both budgets are 0 or blank is the numeric range unspecified. Set a maximum at least as large as a positive minimum.", - "thinkingMin": "Minimum thinking budget", - "thinkingMax": "Maximum thinking budget", - "thinkingZeroAllowed": "Allow zero budget", - "thinkingDynamicAllowed": "Allow dynamic budget", - "invalidContext": "Context length must be a non-negative safe integer.", - "invalidThinking": "Thinking must be a valid JSON object.", - "invalidBudget": "Thinking budgets must be non-negative safe integers.", - "invalidRange": "Minimum thinking budget must not exceed the maximum. Blank bounds count as 0.", - "removeModel": "Remove model", - "modelName": "Model name", - "modelAlias": "Alias (optional)" + "displayName": "Tên hiển thị", + "maxContextLength": "Độ dài ngữ cảnh", + "contextHint": "Số nguyên không âm; để trống để dùng giá trị mặc định.", + "forceMapping": "Viết lại model trong phản hồi thành bí danh", + "isCompat": "Chế độ tương thích", + "supportConfigurationUpdate": "Cho phép cập nhật cấu hình", + "inputModalitiesText": "Phương thức đầu vào (Modalities)", + "outputModalitiesText": "Phương thức đầu ra (Modalities)", + "modalitiesHint": "Phân tách các giá trị bằng dấu phẩy hoặc khoảng trắng. Tên phương thức tùy chỉnh được giữ nguyên.", + "useMaxCompletionTokens": "Sử dụng max_completion_tokens", + "thinkingMode": "Ghi đè cấu hình suy nghĩ (Thinking)", + "useDefault": "Dùng mặc định", + "custom": "Tùy chỉnh", + "thinkingHint": "Mặc định kế thừa hành vi backend; ghi đè tùy chỉnh trống là một đối tượng {} rõ ràng. Ngân sách và mức độ nỗ lực có thể cùng tồn tại. Chỉ khi cả hai ngân sách đều là 0 hoặc để trống thì dải số mới không được chỉ định. Đặt giá trị tối đa ít nhất bằng giá trị tối thiểu dương.", + "thinkingMin": "Ngân sách suy nghĩ tối thiểu", + "thinkingMax": "Ngân sách suy nghĩ tối đa", + "thinkingZeroAllowed": "Cho phép ngân sách bằng 0", + "thinkingDynamicAllowed": "Cho phép ngân sách động", + "invalidContext": "Độ dài ngữ cảnh phải là một số nguyên an toàn không âm.", + "invalidThinking": "Cấu hình suy nghĩ phải là một đối tượng JSON hợp lệ.", + "invalidBudget": "Ngân sách suy nghĩ phải là số nguyên an toàn không âm.", + "invalidRange": "Ngân sách suy nghĩ tối thiểu không được vượt quá mức tối đa. Giới hạn để trống được tính là 0.", + "removeModel": "Xóa model", + "modelName": "Tên model", + "modelAlias": "Bí danh (tùy chọn)" }, "runtimePolicy": { - "title": "Advanced runtime policy", - "description": "Inherit uses the parent group policy, then backend defaults. Overrides apply only to this entry.", - "cooling": "Cooling", - "inherit": "Inherit", - "coolingEnabled": "Enable cooling", - "coolingDisabled": "Disable cooling", - "retry": "Request retries", - "retryHint": "Blank inherits the group setting. Use an integer: 0 disables retries; a negative value uses the global retry policy instead of the group policy.", - "errorsMode": "Request error rules", - "override": "Override", - "errorsHint": "Inherit follows the parent policy. Override replaces the entire list, which may be empty. Switching modes keeps your rule draft.", - "invalidRetry": "Retries must be a safe integer, or blank to inherit." + "title": "Chính sách thực thi nâng cao", + "description": "Kế thừa sẽ dùng chính sách nhóm cha, sau đó là mặc định của backend. Ghi đè chỉ áp dụng cho mục này.", + "cooling": "Chiến lược Cooling", + "inherit": "Kế thừa", + "coolingEnabled": "Bật cooling", + "coolingDisabled": "Tắt cooling", + "retry": "Số lần thử lại yêu cầu", + "retryHint": "Để trống sẽ kế thừa cài đặt nhóm. Dùng số nguyên: 0 để tắt thử lại; giá trị âm sẽ dùng chính sách thử lại toàn cục thay vì chính sách nhóm.", + "errorsMode": "Quy tắc lỗi yêu cầu", + "override": "Ghi đè", + "errorsHint": "Kế thừa sẽ tuân theo chính sách cấp trên. Ghi đè sẽ thay thế toàn bộ danh sách, có thể để trống. Chuyển đổi chế độ vẫn giữ lại bản nháp quy tắc của bạn.", + "invalidRetry": "Số lần thử lại phải là số nguyên an toàn, hoặc để trống để kế thừa." }, "errorRules": { - "hint": "Use the first matching rule in order; for the same status code, any condition may match.", - "empty": "No rules. You can save an empty list.", - "rule": "Rule {{number}}", - "status": "Status code", - "action": "Action", - "selectAction": "Select an action", - "moveUp": "Move rule up", - "moveDown": "Move rule down", - "removeRule": "Delete rule", - "matchType": "Match type", - "text": "Contains text", - "regex": "Regular expression", - "matchValue": "Condition", - "regexHint": "Go regular expression", - "removeMatch": "Delete condition", - "addMatch": "Add condition", - "addRule": "Add rule", - "invalidStatus": "Status code must be a positive safe integer.", - "invalidAction": "Select a valid action.", - "invalidMatch": "Match conditions cannot be empty.", - "missingMatch": "Add at least one match condition.", + "hint": "Áp dụng quy tắc khớp đầu tiên theo thứ tự; với cùng một mã trạng thái, bất kỳ điều kiện nào cũng có thể khớp.", + "empty": "Chưa có quy tắc nào. Bạn có thể lưu một danh sách trống.", + "rule": "Quy tắc {{number}}", + "status": "Mã trạng thái", + "action": "Hành động", + "selectAction": "Chọn một hành động", + "moveUp": "Di chuyển quy tắc lên", + "moveDown": "Di chuyển quy tắc xuống", + "removeRule": "Xóa quy tắc", + "matchType": "Loại khớp", + "text": "Chứa văn bản", + "regex": "Biểu thức chính quy", + "matchValue": "Điều kiện", + "regexHint": "Biểu thức chính quy Go", + "removeMatch": "Xóa điều kiện", + "addMatch": "Thêm điều kiện", + "addRule": "Thêm quy tắc", + "invalidStatus": "Mã trạng thái phải là một số nguyên an toàn dương.", + "invalidAction": "Chọn một hành động hợp lệ.", + "invalidMatch": "Điều kiện khớp không được để trống.", + "missingMatch": "Thêm ít nhất một điều kiện khớp.", "actions": { - "stop": "Stop", - "stop-and-cooldown": "Stop and cool down", - "continue": "Continue", - "continue-and-cooldown": "Continue and cool down" + "stop": "Dừng", + "stop-and-cooldown": "Dừng và cooldown", + "continue": "Tiếp tục", + "continue-and-cooldown": "Tiếp tục và cooldown" } } }, "devin_quota": { - "daily": "Daily remaining", - "weekly": "Weekly remaining", - "plan_label": "Plan", - "plan_end": "Subscription ends", - "unavailable": "Unavailable", - "reset_unknown": "Reset time unavailable", - "observed_at": "Quota observed: {{time}}", - "observed_unknown": "Quota observation time unavailable", - "missing_identity": "The credential name or auth index is missing. Reload the credential list.", - "stale_request": "The connection or credential changed. Please retry.", - "empty_data": "Devin returned no usable quota data.", - "loading": "Querying Devin quota…", - "idle": "Click to query Devin quota", - "load_failed": "Failed to query quota: {{message}}", - "empty_title": "No Devin credentials", - "empty_desc": "Upload a Devin credential file or sign in using the backend CLI to query quota." + "daily": "Còn lại hàng ngày", + "weekly": "Còn lại hàng tuần", + "plan_label": "Gói cước", + "plan_end": "Hết hạn đăng ký", + "unavailable": "Không có sẵn dữ liệu", + "reset_unknown": "Không có thời gian đặt lại", + "observed_at": "Quan sát quota lúc: {{time}}", + "observed_unknown": "Không có thời gian quan sát quota", + "missing_identity": "Thiếu tên credential hoặc chỉ số xác thực. Vui lòng tải lại danh sách credential.", + "stale_request": "Kết nối hoặc credential đã thay đổi. Vui lòng thử lại.", + "empty_data": "Devin không trả về dữ liệu quota khả dụng nào.", + "loading": "Đang truy vấn quota Devin…", + "idle": "Nhấn để truy vấn quota Devin", + "load_failed": "Truy vấn quota thất bại: {{message}}", + "empty_title": "Không có credential Devin", + "empty_desc": "Tải lên file credential Devin hoặc đăng nhập bằng CLI backend để truy vấn quota." }, "meta_quota": { - "title": "Muse (Meta) Quota", - "empty_title": "No Muse credentials", - "empty_desc": "Sign in with Muse OAuth or upload a Meta credential file to query quota.", - "idle": "Click to query Muse quota", - "loading": "Querying Muse quota…", - "load_failed": "Failed to query quota: {{message}}", - "missing_auth_index": "Auth file missing auth_index", - "empty_data": "Quota unknown. You may not have made a model request yet.", - "invalid_response": "Muse returned an invalid quota response.", - "request_failed": "Muse quota request failed. Check that the DCA credential is valid.", - "missing_file": "Quota requires a downloadable Meta authentication file.", - "missing_dca_token": "The authentication file has no valid dca_token. Sign in with Muse OAuth again.", - "invalid_auth_file": "The downloaded authentication file is not valid JSON.", - "download_failed": "Could not download the authentication file for quota lookup.", - "stale_request": "The connection or credential changed. Please retry.", - "plan": "Plan", - "active": "Subscription active", - "inactive": "Subscription inactive", - "window": "Usage window", - "window_duration": "{{minutes}}-minute window", - "weekly": "Weekly quota", - "unknown": "Unknown", - "remaining": "{{percent}}% remaining" + "title": "Quota Muse (Meta)", + "empty_title": "Không có credential Muse", + "empty_desc": "Đăng nhập bằng Muse OAuth hoặc tải lên file credential Meta để truy vấn quota.", + "idle": "Nhấn để truy vấn quota Muse", + "loading": "Đang truy vấn quota Muse…", + "load_failed": "Truy vấn quota thất bại: {{message}}", + "missing_auth_index": "File xác thực thiếu auth_index", + "empty_data": "Quota không xác định. Có thể bạn chưa thực hiện yêu cầu model nào.", + "invalid_response": "Muse trả về phản hồi quota không hợp lệ.", + "request_failed": "Yêu cầu quota Muse thất bại. Hãy kiểm tra xem credential DCA có hợp lệ không.", + "missing_file": "Tra cứu quota yêu cầu file xác thực Meta có thể tải xuống.", + "missing_dca_token": "File xác thực không có dca_token hợp lệ. Vui lòng đăng nhập lại bằng Muse OAuth.", + "invalid_auth_file": "File xác thực đã tải xuống không phải là JSON hợp lệ.", + "download_failed": "Không thể tải xuống file xác thực để tra cứu quota.", + "stale_request": "Kết nối hoặc credential đã thay đổi. Vui lòng thử lại.", + "plan": "Gói cước", + "active": "Đăng ký đang hoạt động", + "inactive": "Đăng ký không hoạt động", + "window": "Chu kỳ sử dụng", + "window_duration": "Chu kỳ {{minutes}} phút", + "weekly": "Quota hàng tuần", + "unknown": "Không rõ", + "remaining": "Còn lại {{percent}}%" }, "claude_reset": { - "retry_confirm": "Retry the unknown reset for “{{name}}” with its original request ID? A reset may already have been spent. Retry within 10 minutes; do not reload or start another claim in another tab.", - "remaining": "Resets remaining", - "title": "Banked resets", - "scope": "Uses a limited reset grant to clear eligible Claude usage windows. Only confirm when you want to spend a reset. Recovery is limited to this tab/session; do not reload or use another tab while an outcome is unknown.", - "loading": "Loading…", - "read_error": "Reset grants could not be read. Nothing was submitted.", - "blocked": "Reset not submitted: eligibility, account identity, or session could not be verified. Refresh and check again.", - "unknown": "The outcome is unknown. A reset may have been spent. Retry within 10 minutes using the same request ID; do not start another claim elsewhere.", - "expired": "The retry window has expired. Further claims are blocked in this session. Check your Claude account before taking any further action.", - "retry": "Retry the same claim", - "empty": "No banked reset grants.", - "count": "{{left}} / {{total}} resets remaining", - "ends": "Expires: {{date}}", - "use": "Reset limits", - "confirm": "Confirm reset", - "confirm_text": "Spend one reset to clear eligible usage limits for “{{name}}”? This uses a limited reset grant.", - "reset": "Usage limits reset.", - "already_used": "This grant was already used.", - "not_limited": "No reset: the account is not currently limited.", - "cooldown": "No reset: cooldown is active.", - "ineligible": "This account is not eligible.", - "unavailable": "Resets are currently unavailable.", - "rate_limited": "Request rate limited.", - "auth_error": "Authorization was refused." + "retry_confirm": "Thử lại lượt đặt lại chưa rõ kết quả cho “{{name}}” với ID yêu cầu ban đầu? Một lượt đặt lại có thể đã được tiêu tốn. Hãy thử lại trong vòng 10 phút; không tải lại trang hoặc bắt đầu nhận ở tab khác.", + "remaining": "Lượt đặt lại còn lại", + "title": "Lượt đặt lại dự trữ", + "scope": "Sử dụng một quyền đặt lại có hạn để xóa chu kỳ sử dụng Claude đủ điều kiện. Chỉ xác nhận khi bạn muốn tiêu tốn một lượt đặt lại. Việc khôi phục chỉ giới hạn trong tab/phiên này; không tải lại hoặc dùng tab khác trong khi kết quả chưa rõ.", + "loading": "Đang tải…", + "read_error": "Không thể đọc quyền đặt lại. Chưa gửi yêu cầu nào.", + "blocked": "Chưa gửi yêu cầu đặt lại: không thể xác minh tính đủ điều kiện, danh tính tài khoản hoặc phiên. Hãy làm mới và kiểm tra lại.", + "unknown": "Kết quả chưa xác định. Một lượt đặt lại có thể đã được sử dụng. Thử lại trong vòng 10 phút bằng cùng ID yêu cầu; không bắt đầu yêu cầu khác ở nơi khác.", + "expired": "Khoảng thời gian thử lại đã hết hạn. Các yêu cầu tiếp theo bị chặn trong phiên này. Hãy kiểm tra tài khoản Claude của bạn trước khi thực hiện thêm hành động.", + "retry": "Thử lại cùng yêu cầu", + "empty": "Không có quyền đặt lại dự trữ nào.", + "count": "Còn {{left}} / {{total}} lượt đặt lại", + "ends": "Hết hạn: {{date}}", + "use": "Đặt lại giới hạn", + "confirm": "Xác nhận đặt lại", + "confirm_text": "Tiêu tốn một lượt đặt lại để xóa giới hạn sử dụng đủ điều kiện cho “{{name}}”? Thao tác này sẽ dùng một quyền đặt lại có hạn.", + "reset": "Đã đặt lại giới hạn sử dụng.", + "already_used": "Quyền này đã được sử dụng.", + "not_limited": "Không đặt lại: tài khoản hiện không bị giới hạn.", + "cooldown": "Không đặt lại: đang trong thời gian cooldown.", + "ineligible": "Tài khoản này không đủ điều kiện.", + "unavailable": "Tính năng đặt lại hiện không khả dụng.", + "rate_limited": "Yêu cầu bị giới hạn tốc độ.", + "auth_error": "Ủy quyền đã bị từ chối." } } From 935aa6e3eac58f6d422242a44ac0ecb7de211809 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Wed, 7 Oct 2026 07:40:18 +0800 Subject: [PATCH 074/142] fix(cliproxy): prevent in-flight token refresh from overwriting concurrently updated credentials - Ignore in-flight refresh results when the credential version or credentials have been modified concurrently after the initial snapshot Closes: #6417 --- sdk/cliproxy/auth/conductor_issue6417_test.go | 92 +++++++++++++++++++ sdk/cliproxy/auth/conductor_lifecycle.go | 6 ++ 2 files changed, 98 insertions(+) create mode 100644 sdk/cliproxy/auth/conductor_issue6417_test.go diff --git a/sdk/cliproxy/auth/conductor_issue6417_test.go b/sdk/cliproxy/auth/conductor_issue6417_test.go new file mode 100644 index 00000000000..da361792f40 --- /dev/null +++ b/sdk/cliproxy/auth/conductor_issue6417_test.go @@ -0,0 +1,92 @@ +package auth + +import ( + "context" + "testing" + "time" +) + +type issue6417BlockingRefreshExecutor struct { + schedulerProviderTestExecutor + started chan struct{} + release chan struct{} +} + +func (e *issue6417BlockingRefreshExecutor) Refresh(_ context.Context, auth *Auth) (*Auth, error) { + close(e.started) + <-e.release + auth.Metadata["access_token"] = "access-token-a-refreshed" + auth.Metadata["refresh_token"] = "refresh-token-a-refreshed" + auth.Metadata["expired"] = time.Now().Add(time.Hour).Format(time.RFC3339) + return auth, nil +} + +func TestManager_RefreshAuth_DropsStaleConcurrentCredential(t *testing.T) { + ctx := context.Background() + store := newMemoryAuthTestStore() + manager := NewManager(store, &RoundRobinSelector{}, nil) + executor := &issue6417BlockingRefreshExecutor{ + schedulerProviderTestExecutor: schedulerProviderTestExecutor{provider: "antigravity"}, + started: make(chan struct{}), + release: make(chan struct{}), + } + manager.RegisterExecutor(executor) + + auth := &Auth{ + ID: "issue-6417-auth", + Provider: "antigravity", + Status: StatusActive, + Metadata: map[string]any{ + "access_token": "access-token-a", + "refresh_token": "refresh-token-a", + "expired": time.Now().Add(-time.Hour).Format(time.RFC3339), + }, + } + if _, errRegister := manager.Register(ctx, auth); errRegister != nil { + t.Fatalf("register auth: %v", errRegister) + } + + refreshDone := make(chan struct{}) + go func() { + manager.refreshAuth(ctx, auth.ID) + close(refreshDone) + }() + <-executor.started + + current, ok := manager.GetByID(auth.ID) + if !ok { + t.Fatalf("auth %q not found", auth.ID) + } + current.Metadata["access_token"] = "access-token-b" + current.Metadata["refresh_token"] = "refresh-token-b" + if _, errUpdate := manager.Update(ctx, current); errUpdate != nil { + t.Fatalf("update concurrent credential: %v", errUpdate) + } + + close(executor.release) + <-refreshDone + + updated, ok := manager.GetByID(auth.ID) + if !ok { + t.Fatalf("auth %q not found after refresh", auth.ID) + } + if got := updated.Metadata["access_token"]; got != "access-token-b" { + t.Fatalf("access_token = %q, want access-token-b", got) + } + if got := updated.Metadata["refresh_token"]; got != "refresh-token-b" { + t.Fatalf("refresh_token = %q, want refresh-token-b", got) + } + + store.mu.Lock() + persisted := store.auths[auth.ID] + store.mu.Unlock() + if persisted == nil { + t.Fatalf("persisted auth %q not found", auth.ID) + } + if got := persisted.Metadata["access_token"]; got != "access-token-b" { + t.Fatalf("persisted access_token = %q, want access-token-b", got) + } + if got := persisted.Metadata["refresh_token"]; got != "refresh-token-b" { + t.Fatalf("persisted refresh_token = %q, want refresh-token-b", got) + } +} diff --git a/sdk/cliproxy/auth/conductor_lifecycle.go b/sdk/cliproxy/auth/conductor_lifecycle.go index af5c4600c0a..263a3d33ce6 100644 --- a/sdk/cliproxy/auth/conductor_lifecycle.go +++ b/sdk/cliproxy/auth/conductor_lifecycle.go @@ -214,6 +214,12 @@ func (m *Manager) updateInternal(ctx context.Context, base, auth *Auth, mode upd m.mu.Unlock() return nil, fmt.Errorf("update auth %s: stale registration epoch %d != %d", auth.ID, base.RegistrationEpoch, existing.RegistrationEpoch) } + // Do not let an in-flight refresh overwrite credentials committed after its snapshot. + if mode == updateModeRefresh && base != nil && (existing.CredentialVersion != base.CredentialVersion || CredentialsChanged(base, existing)) { + current := existing.Clone() + m.mu.Unlock() + return current, nil + } if mode == updateModeRefresh { merged := MergeRefreshedAuth(base, existing, auth) if merged != nil { From dbc4aad9e9210611b7537404823622a651841a9f Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Wed, 7 Oct 2026 08:16:52 +0800 Subject: [PATCH 075/142] fix(gemini): ignore context cancellation after terminal chunk in Vertex stream - Detect terminal stream chunks and avoid recording client cancellations as execution failures once completion events have been delivered Closes: #6421 --- .../executor/gemini_vertex_executor.go | 43 +++++ ...ertex_executor_terminal_disconnect_test.go | 147 ++++++++++++++++++ 2 files changed, 190 insertions(+) create mode 100644 internal/runtime/executor/gemini_vertex_executor_terminal_disconnect_test.go diff --git a/internal/runtime/executor/gemini_vertex_executor.go b/internal/runtime/executor/gemini_vertex_executor.go index 035d260402f..a3d3996fd68 100644 --- a/internal/runtime/executor/gemini_vertex_executor.go +++ b/internal/runtime/executor/gemini_vertex_executor.go @@ -8,6 +8,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -54,6 +55,34 @@ func getVertexAction(model string, isStream bool) string { return "generateContent" } +func isGeminiVertexTerminalStreamChunk(chunk []byte) bool { + for _, line := range bytes.Split(chunk, []byte("\n")) { + trimmed := bytes.TrimSpace(line) + if bytes.Equal(trimmed, []byte("data: [DONE]")) || bytes.Equal(trimmed, []byte("[DONE]")) { + return true + } + payload := helps.JSONPayload(line) + if len(payload) == 0 { + continue + } + eventType := gjson.GetBytes(payload, "type").String() + if eventType == "response.completed" || eventType == "response.incomplete" || eventType == "response.done" || eventType == "message_stop" { + return true + } + for _, path := range []string{ + "choices.0.finish_reason", + "response.choices.0.finish_reason", + "candidates.0.finishReason", + "response.candidates.0.finishReason", + } { + if finishReason := gjson.GetBytes(payload, path); finishReason.Exists() && strings.TrimSpace(finishReason.String()) != "" { + return true + } + } + } + return false +} + // convertImagenToGeminiResponse converts Imagen API response to Gemini format // so it can be processed by the standard translation pipeline. // This ensures Imagen models return responses in the same format as gemini-3-pro-image-preview. @@ -700,6 +729,7 @@ func (e *GeminiVertexExecutor) executeStreamWithServiceAccount(ctx context.Conte claudeInputTokens := helps.NewClaudeInputTokenState(from, to, responseFormat, originalPayload) var streamUsage helps.StreamUsageBuffer defer streamUsage.Publish(ctx, reporter) + var terminalDelivered bool var param any helps.InitializeApplyPatchStream(ctx, to, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), body, ¶m) for scanner.Scan() { @@ -714,6 +744,9 @@ func (e *GeminiVertexExecutor) executeStreamWithServiceAccount(ctx context.Conte for i := range lines { select { case out <- cliproxyexecutor.StreamChunk{Payload: lines[i]}: + if isGeminiVertexTerminalStreamChunk(lines[i]) { + terminalDelivered = true + } case <-ctx.Done(): return } @@ -726,6 +759,9 @@ func (e *GeminiVertexExecutor) executeStreamWithServiceAccount(ctx context.Conte return } if errScan := scanner.Err(); errScan != nil { + if terminalDelivered && errors.Is(errScan, context.Canceled) { + return + } helps.RecordAPIResponseError(ctx, e.cfg, errScan) reporter.PublishFailure(ctx, errScan) select { @@ -868,6 +904,7 @@ func (e *GeminiVertexExecutor) executeStreamWithAPIKey(ctx context.Context, auth claudeInputTokens := helps.NewClaudeInputTokenState(from, to, responseFormat, originalPayload) var streamUsage helps.StreamUsageBuffer defer streamUsage.Publish(ctx, reporter) + var terminalDelivered bool var param any helps.InitializeApplyPatchStream(ctx, to, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), body, ¶m) for scanner.Scan() { @@ -882,6 +919,9 @@ func (e *GeminiVertexExecutor) executeStreamWithAPIKey(ctx context.Context, auth for i := range lines { select { case out <- cliproxyexecutor.StreamChunk{Payload: lines[i]}: + if isGeminiVertexTerminalStreamChunk(lines[i]) { + terminalDelivered = true + } case <-ctx.Done(): return } @@ -894,6 +934,9 @@ func (e *GeminiVertexExecutor) executeStreamWithAPIKey(ctx context.Context, auth return } if errScan := scanner.Err(); errScan != nil { + if terminalDelivered && errors.Is(errScan, context.Canceled) { + return + } helps.RecordAPIResponseError(ctx, e.cfg, errScan) reporter.PublishFailure(ctx, errScan) select { diff --git a/internal/runtime/executor/gemini_vertex_executor_terminal_disconnect_test.go b/internal/runtime/executor/gemini_vertex_executor_terminal_disconnect_test.go new file mode 100644 index 00000000000..921cec5dc72 --- /dev/null +++ b/internal/runtime/executor/gemini_vertex_executor_terminal_disconnect_test.go @@ -0,0 +1,147 @@ +package executor + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + "time" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +type vertexTerminalDisconnectUsageCapture struct { + authID string + records chan usage.Record +} + +func (c *vertexTerminalDisconnectUsageCapture) HandleUsage(_ context.Context, record usage.Record) { + if c == nil || record.Provider != "vertex" || record.AuthID != c.authID { + return + } + select { + case c.records <- record: + default: + } +} + +type vertexTerminalDisconnectUsageNoop struct{} + +func (vertexTerminalDisconnectUsageNoop) HandleUsage(context.Context, usage.Record) {} + +func TestGeminiVertexStream_ClientDisconnectAfterTerminalEventIsNotFailed(t *testing.T) { + for _, terminal := range []struct { + name string + finishReason string + event string + }{ + {name: "completed", finishReason: "STOP", event: "response.completed"}, + {name: "incomplete", finishReason: "MAX_TOKENS", event: "response.incomplete"}, + } { + t.Run(terminal.name, func(t *testing.T) { + upstreamSSE := "data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"hello\"}]},\"finishReason\":\"" + terminal.finishReason + "\"}],\"usageMetadata\":{\"promptTokenCount\":10,\"candidatesTokenCount\":5,\"totalTokenCount\":15},\"modelVersion\":\"gemini-3.7-flash\",\"responseId\":\"vertex-terminal-disconnect\"}\n\n" + for _, provider := range []string{"api_key", "service_account"} { + t.Run(provider, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) { + if request.URL.Path == "/token" { + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"access_token":"local-token","token_type":"Bearer","expires_in":3600}`) + return + } + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, upstreamSSE) + if flusher, ok := w.(http.Flusher); ok { + flusher.Flush() + } + <-request.Context().Done() + })) + defer server.Close() + + ctx := context.Background() + auth := &cliproxyauth.Auth{ID: t.Name()} + if provider == "api_key" { + auth.Attributes = map[string]string{"api_key": "test-key", "base_url": server.URL} + } else { + var serviceAccount map[string]any + if errUnmarshal := json.Unmarshal(testVertexServiceAccountJSON(t, server.URL+"/token"), &serviceAccount); errUnmarshal != nil { + t.Fatal(errUnmarshal) + } + auth.Metadata = map[string]any{ + "project_id": "proxy-test", + "location": "global", + "service_account": serviceAccount, + } + target, errParse := parseTestURL(t, server.URL) + if errParse != nil { + t.Fatal(errParse) + } + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.Proxy = nil + t.Cleanup(transport.CloseIdleConnections) + ctx = context.WithValue(ctx, "cliproxy.roundtripper", issue6258RedirectTransport{target: target, base: transport}) + } + + capture := &vertexTerminalDisconnectUsageCapture{authID: auth.ID, records: make(chan usage.Record, 1)} + usage.RegisterNamedPlugin(t.Name(), capture) + t.Cleanup(func() { + usage.RegisterNamedPlugin(t.Name(), vertexTerminalDisconnectUsageNoop{}) + }) + + ctx, cancel := context.WithCancel(ctx) + defer cancel() + result, errExecute := NewGeminiVertexExecutor(&config.Config{}).ExecuteStream(ctx, auth, cliproxyexecutor.Request{ + Model: "gemini-3.7-flash", + Payload: []byte(`{"input":"hello","stream":true}`), + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + Stream: true, + }) + if errExecute != nil { + t.Fatalf("ExecuteStream() error = %v", errExecute) + } + + terminalReceived := false + for chunk := range result.Chunks { + if chunk.Err != nil { + t.Fatalf("unexpected stream error: %v", chunk.Err) + } + if strings.Contains(string(chunk.Payload), terminal.event) { + terminalReceived = true + cancel() + break + } + } + if !terminalReceived { + t.Fatalf("expected %s before client cancellation", terminal.event) + } + + select { + case record := <-capture.records: + if record.Failed { + t.Fatalf("usage record marked failed: status=%d, body=%q", record.Fail.StatusCode, record.Fail.Body) + } + if record.Detail.InputTokens != 10 || record.Detail.OutputTokens != 5 || record.Detail.TotalTokens != 15 { + t.Fatalf("reported usage = %+v, want input 10 output 5 total 15", record.Detail) + } + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for usage record") + } + }) + } + }) + } +} + +func parseTestURL(t *testing.T, rawURL string) (*url.URL, error) { + t.Helper() + return url.Parse(rawURL) +} From eca1d113859efe75984773b9cb69dca45476259d Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Wed, 7 Oct 2026 08:40:41 +0800 Subject: [PATCH 076/142] fix(claude): keep system prompt at top level for single terminal user turn - Update terminal user run check in Claude cloaking logic so conversations ending with a single user turn keep caller system instructions at the top level instead of relocating them into mid-conversation messages Closes: #6423 --- .../claude_cloaked_cache_repro_test.go | 10 +- .../executor/claude_executor_cloaking.go | 2 +- .../runtime/executor/claude_executor_test.go | 115 +++++++++++++----- .../executor/claude_mid_system_model_test.go | 4 +- .../claude_prompt_cache_options_test.go | 24 ++-- 5 files changed, 107 insertions(+), 48 deletions(-) diff --git a/internal/runtime/executor/claude_cloaked_cache_repro_test.go b/internal/runtime/executor/claude_cloaked_cache_repro_test.go index 981d2d78bb9..28ca44a3a13 100644 --- a/internal/runtime/executor/claude_cloaked_cache_repro_test.go +++ b/internal/runtime/executor/claude_cloaked_cache_repro_test.go @@ -282,7 +282,11 @@ func TestClaudeCloakedMultiTurnPrefixStability(t *testing.T) { turn1Payload := fmt.Sprintf(`{ "model": "claude-opus-5", "system": [{"type": "text", "text": %q, "cache_control": {"type": "ephemeral"}}], - "messages": [{"role": "user", "content": "turn 1 user prompt"}], + "messages": [ + {"role": "user", "content": "turn 0 user prompt"}, + {"role": "assistant", "content": "Earlier response."}, + {"role": "user", "content": "turn 1 user prompt"} + ], "max_tokens": 100 }`, systemPrompt) @@ -290,6 +294,8 @@ func TestClaudeCloakedMultiTurnPrefixStability(t *testing.T) { "model": "claude-opus-5", "system": [{"type": "text", "text": %q, "cache_control": {"type": "ephemeral"}}], "messages": [ + {"role": "user", "content": "turn 0 user prompt"}, + {"role": "assistant", "content": "Earlier response."}, {"role": "user", "content": "turn 1 user prompt"}, {"role": "assistant", "content": "Understood."}, {"role": "user", "content": "turn 2 user prompt with new question"} @@ -369,6 +375,8 @@ func TestClaudeCloakedMultiTurnPrefixStability(t *testing.T) { "model": "claude-opus-5", "system": [{"type": "text", "text": %q, "cache_control": {"type": "ephemeral"}}], "messages": [ + {"role": "user", "content": "turn 0 user prompt"}, + {"role": "assistant", "content": "Earlier response."}, {"role": "user", "content": "turn 1 user prompt"}, {"role": "assistant", "content": "Understood."}, {"role": "user", "content": "turn 2 user prompt with new question"}, diff --git a/internal/runtime/executor/claude_executor_cloaking.go b/internal/runtime/executor/claude_executor_cloaking.go index f43102b6e1c..c0da3668ba5 100644 --- a/internal/runtime/executor/claude_executor_cloaking.go +++ b/internal/runtime/executor/claude_executor_cloaking.go @@ -860,7 +860,7 @@ func claudeMidConversationSystemMessagesAtEnd(payload []byte) bool { for insertAt < len(messageBlocks) && messageBlocks[insertAt].Get("role").String() == "user" { insertAt++ } - return insertAt > firstUserIdx+1 && insertAt == len(messageBlocks) + return insertAt == len(messageBlocks) } func insertClaudeMidConversationSystemMessages(payload []byte, texts []string) []byte { diff --git a/internal/runtime/executor/claude_executor_test.go b/internal/runtime/executor/claude_executor_test.go index da361df6bd3..c7a7a6ed4bb 100644 --- a/internal/runtime/executor/claude_executor_test.go +++ b/internal/runtime/executor/claude_executor_test.go @@ -1159,8 +1159,11 @@ func TestClaudeExecutor_CopiedVSCodeAgentSDKHeadersWithoutMetadataAreCloaked(t * if got := seenHeaders.Get("User-Agent"); got != "claude-cli/2.1.280 (external, cli)" { t.Fatalf("User-Agent = %q, want CLI cloak", got) } - if got := gjson.GetBytes(seenBody, "system.#").Int(); got != 2 { - t.Fatalf("system block count = %d, want billing and CLI identity only", got) + if got := gjson.GetBytes(seenBody, "system.#").Int(); got != 3 { + t.Fatalf("system block count = %d, want billing, CLI identity, and caller system", got) + } + if got := gjson.GetBytes(seenBody, "system.2.text").String(); got != "spoofed-system" { + t.Fatalf("system.2.text = %q, want spoofed-system", got) } content := gjson.GetBytes(seenBody, "messages.0.content").Array() if len(content) != 2 { @@ -1168,7 +1171,9 @@ func TestClaudeExecutor_CopiedVSCodeAgentSDKHeadersWithoutMetadataAreCloaked(t * } assertClaudeCodeCurrentDateBlock(t, content[0]) assertEphemeralUserTextBlock(t, content[1], "x", "") - assertClaudeMidConversationSystemMessage(t, seenBody, 1, "spoofed-system", "") + if got := gjson.GetBytes(seenBody, "messages.#").Int(); got != 1 { + t.Fatalf("message count = %d, want no trailing system turn", got) + } } func TestClaudeExecutor_AgentSDKEntrypointWithStrongSignalsUsesCLICloak(t *testing.T) { @@ -2543,7 +2548,9 @@ func TestClaudeExecutor_CountTokensCloakRelocatesCallerSystemAndObfuscates(t *te "cloak_sensitive_words": sensitiveWord, }} payload := []byte(`{"model":"` + testCase.model + `","system":[{"type":"text","text":"` + callerSystem + `"}],` + - `"messages":[{"role":"user","content":[{"type":"text","text":"hello"}]}],"tools":[]}`) + `"messages":[{"role":"user","content":[{"type":"text","text":"hello"}]},` + + `{"role":"assistant","content":[{"type":"text","text":"acknowledged"}]},` + + `{"role":"user","content":[{"type":"text","text":"follow-up"}]}],"tools":[]}`) _, errCount := NewClaudeExecutor(&config.Config{}).countTokensUpstream(ctx, auth, cliproxyexecutor.Request{Model: testCase.model, Payload: payload}, @@ -4134,7 +4141,7 @@ func TestInjectClaudeCodeCurrentDateFollowsAllLeadingToolResults(t *testing.T) { // Test case 1: String system prompt becomes an authoritative mid-conversation // system message after the first user turn. func TestCheckSystemInstructionsWithMode_StringSystemPreserved(t *testing.T) { - payload := []byte(`{"model":"claude-opus-5","system":"You are a helpful assistant.","messages":[{"role":"user","content":"hi"}]}`) + payload := []byte(`{"model":"claude-opus-5","system":"You are a helpful assistant.","messages":[{"role":"user","content":"hi"},{"role":"assistant","content":"hello"},{"role":"user","content":"follow-up"}]}`) out := checkSystemInstructionsWithMode(payload, false) @@ -4191,7 +4198,7 @@ func TestClaudeUsesLegacySystemReminder(t *testing.T) { } func TestCheckSystemInstructionsWithMode_FutureModelDefaultsToMidSystem(t *testing.T) { - payload := []byte(`{"model":"claude-opus-6","system":"future instructions","messages":[{"role":"user","content":"hi"}]}`) + payload := []byte(`{"model":"claude-opus-6","system":"future instructions","messages":[{"role":"user","content":"hi"},{"role":"assistant","content":"hello"},{"role":"user","content":"follow-up"}]}`) out := checkSystemInstructionsWithMode(payload, false) if got := gjson.GetBytes(out, "system.#").Int(); got != 2 { @@ -4292,7 +4299,7 @@ func TestCheckSystemInstructionsWithMode_EmptyStringSystemIgnored(t *testing.T) // Test case 4: Array system prompt becomes one mid-conversation system message. func TestCheckSystemInstructionsWithMode_ArraySystemStillWorks(t *testing.T) { - payload := []byte(`{"model":"claude-opus-5","system":[{"type":"text","text":"Be concise."}],"messages":[{"role":"user","content":"hi"}]}`) + payload := []byte(`{"model":"claude-opus-5","system":[{"type":"text","text":"Be concise."}],"messages":[{"role":"user","content":"hi"},{"role":"assistant","content":"hello"},{"role":"user","content":"follow-up"}]}`) out := checkSystemInstructionsWithMode(payload, false) @@ -4313,11 +4320,11 @@ func TestCheckSystemInstructionsWithMode_ArraySystemKeepsBlocksAsSeparateMessage payload := []byte(`{"model":"claude-opus-5","system":[` + `{"type":"text","text":"first guidance","cache_control":{"type":"ephemeral","ttl":"1h"}},` + `{"type":"text","text":"second guidance"}],` + - `"messages":[{"role":"user","content":"hi"}]}`) + `"messages":[{"role":"user","content":"hi"},{"role":"assistant","content":"hello"},{"role":"user","content":"follow-up"}]}`) out := checkSystemInstructionsWithMode(payload, false) - if got := gjson.GetBytes(out, "messages.#").Int(); got != 3 { - t.Fatalf("message count = %d, want user and two separate system messages: %s", got, out) + if got := gjson.GetBytes(out, "messages.#").Int(); got != 5 { + t.Fatalf("message count = %d, want user, two system messages, assistant, and user: %s", got, out) } content := gjson.GetBytes(out, "messages.0.content").Array() if len(content) != 2 { @@ -4352,6 +4359,26 @@ func TestCheckSystemInstructionsWithMode_TerminalUserRunKeepsSystemTopLevel(t *t } } +func TestCheckSystemInstructionsWithMode_SingleTerminalUserKeepsSystemTopLevel(t *testing.T) { + payload := []byte(`{"model":"claude-opus-5","system":[` + + `{"type":"text","text":"caller guidance"}],` + + `"messages":[{"role":"user","content":"request"}]}`) + + out := checkSystemInstructionsWithMode(payload, false) + if got := gjson.GetBytes(out, "system.#").Int(); got != 3 { + t.Fatalf("top-level system block count = %d, want 3 (2 identity + caller block): %s", got, out) + } + if got := gjson.GetBytes(out, "messages.#").Int(); got != 1 { + t.Fatalf("message count = %d, want 1 without trailing system turn: %s", got, out) + } + if got := gjson.GetBytes(out, "system.2.text").String(); got != "caller guidance" { + t.Fatalf("system.2.text = %q, want caller guidance", got) + } + if got := gjson.GetBytes(out, "system.2.cache_control.type").String(); got != "ephemeral" { + t.Fatalf("system.2.cache_control.type = %q, want ephemeral", got) + } +} + func TestRelocateClaudeSystemPromptForCountTokens_TerminalUserRunKeepsSystemTopLevel(t *testing.T) { payload := []byte(`{"model":"claude-opus-5","system":[` + `{"type":"text","text":"first guidance"},` + @@ -4375,6 +4402,23 @@ func TestRelocateClaudeSystemPromptForCountTokens_TerminalUserRunKeepsSystemTopL } } +func TestRelocateClaudeSystemPromptForCountTokens_SingleTerminalUserKeepsSystemTopLevel(t *testing.T) { + payload := []byte(`{"model":"claude-opus-5","system":[` + + `{"type":"text","text":"caller guidance"}],` + + `"messages":[{"role":"user","content":"request"}]}`) + + out := relocateClaudeSystemPromptForCountTokens(payload, false) + if got := gjson.GetBytes(out, "system.#").Int(); got != 1 { + t.Fatalf("top-level system block count = %d, want 1 caller block: %s", got, out) + } + if got := gjson.GetBytes(out, "system.0.text").String(); got != "caller guidance" { + t.Fatalf("system.0.text = %q, want caller guidance", got) + } + if got := gjson.GetBytes(out, "messages.#").Int(); got != 1 { + t.Fatalf("message count = %d, want 1 without trailing system turn: %s", got, out) + } +} + func TestRelocateClaudeSystemPromptForCountTokensKeepsBlocksSeparate(t *testing.T) { tests := []struct { name string @@ -4390,7 +4434,7 @@ func TestRelocateClaudeSystemPromptForCountTokensKeepsBlocksSeparate(t *testing. payload := []byte(`{"model":"` + test.model + `","system":[` + `{"type":"text","text":"first guidance"},` + `{"type":"text","text":"second guidance"}],` + - `"messages":[{"role":"user","content":"hi"}]}`) + `"messages":[{"role":"user","content":"hi"},{"role":"assistant","content":"hello"},{"role":"user","content":"follow-up"}]}`) out := relocateClaudeSystemPromptForCountTokens(payload, false) if gjson.GetBytes(out, "system").Exists() { @@ -4412,8 +4456,8 @@ func TestRelocateClaudeSystemPromptForCountTokensKeepsBlocksSeparate(t *testing. } return } - if got := gjson.GetBytes(out, "messages.#").Int(); got != 3 { - t.Fatalf("message count = %d, want user and two system messages: %s", got, out) + if got := gjson.GetBytes(out, "messages.#").Int(); got != 5 { + t.Fatalf("message count = %d, want user, two system messages, assistant, and user: %s", got, out) } assertClaudeMidConversationSystemMessage(t, out, 1, "first guidance", "") assertClaudeMidConversationSystemMessage(t, out, 2, "second guidance", "") @@ -4668,15 +4712,17 @@ func TestCheckSystemInstructionsWithMode_NormalTextWithAdvisorWordDoesNotBypassM {"type": "text", "text": "second guidance"} ], "messages": [ - {"role": "user", "content": "I need an advisor on financial planning."} + {"role": "user", "content": "I need an advisor on financial planning."}, + {"role": "assistant", "content": "I can help."}, + {"role": "user", "content": "Please continue."} ] }`) out := checkSystemInstructionsWithMode(payload, false) // Since there is no advisor tool invocation/result, normal mid-conversation system insertion occurs. - if got := gjson.GetBytes(out, "messages.#").Int(); got != 3 { - t.Fatalf("messages count = %d, want 3 (user + 2 system messages): %s", got, out) + if got := gjson.GetBytes(out, "messages.#").Int(); got != 5 { + t.Fatalf("messages count = %d, want 5 (user + 2 system messages + assistant + user): %s", got, out) } assertClaudeMidConversationSystemMessage(t, out, 1, "first guidance", "") assertClaudeMidConversationSystemMessage(t, out, 2, "second guidance", "") @@ -4872,7 +4918,7 @@ func TestRelocateClaudeSystemPromptForCountTokens_ClientToolNamedAdvisorRelocate // Test case 5: Special characters survive the mid-conversation system move. func TestCheckSystemInstructionsWithMode_StringWithSpecialChars(t *testing.T) { - payload := []byte(`{"model":"claude-opus-5","system":"Use tags & \"quotes\" in output.","messages":[{"role":"user","content":"hi"}]}`) + payload := []byte(`{"model":"claude-opus-5","system":"Use tags & \"quotes\" in output.","messages":[{"role":"user","content":"hi"},{"role":"assistant","content":"hello"},{"role":"user","content":"follow-up"}]}`) out := checkSystemInstructionsWithMode(payload, false) @@ -4894,10 +4940,11 @@ func TestCheckSystemInstructionsWithSigningMode_LongPromptIsExactAndIdempotent(t payloadMap := map[string]any{ "model": "claude-opus-5", "system": wantSystem, - "messages": []any{map[string]any{ - "role": "user", - "content": "hello", - }}, + "messages": []any{ + map[string]any{"role": "user", "content": "hello"}, + map[string]any{"role": "assistant", "content": "acknowledged"}, + map[string]any{"role": "user", "content": "follow-up"}, + }, } payload, errMarshal := json.Marshal(payloadMap) if errMarshal != nil { @@ -4912,8 +4959,8 @@ func TestCheckSystemInstructionsWithSigningMode_LongPromptIsExactAndIdempotent(t if got := gjson.GetBytes(first, "system.#").Int(); got != 2 { t.Fatalf("top-level system block count = %d, want 2", got) } - if got := gjson.GetBytes(first, "messages.#").Int(); got != 2 { - t.Fatalf("message count = %d, want user then system", got) + if got := gjson.GetBytes(first, "messages.#").Int(); got != 4 { + t.Fatalf("message count = %d, want user, system, assistant, and user", got) } content := gjson.GetBytes(first, "messages.0.content").Array() if len(content) != 2 { @@ -7817,8 +7864,11 @@ func TestClaudeExecutor_ExecuteOAuthCustomToolMCPAliasRoundTrip(t *testing.T) { if got := gjson.GetBytes(upstreamBody, "system.1.text").String(); got != claudeCodeCLIIdentity { t.Fatalf("Messages system.1.text = %q, want official CLI identity", got) } - if got := gjson.GetBytes(upstreamBody, "system.#").Int(); got != 2 { - t.Fatalf("Messages top-level system block count = %d, want 2", got) + if got := gjson.GetBytes(upstreamBody, "system.#").Int(); got != 3 { + t.Fatalf("Messages top-level system block count = %d, want 3", got) + } + if got := gjson.GetBytes(upstreamBody, "system.2.text").String(); got != "messages-system-prompt" { + t.Fatalf("Messages system.2.text = %q, want messages-system-prompt", got) } content := gjson.GetBytes(upstreamBody, "messages.0.content").Array() if len(content) != 2 { @@ -7826,7 +7876,9 @@ func TestClaudeExecutor_ExecuteOAuthCustomToolMCPAliasRoundTrip(t *testing.T) { } assertClaudeCodeCurrentDateBlock(t, content[0]) assertEphemeralUserTextBlock(t, content[1], "search", "1h") - assertClaudeMidConversationSystemMessage(t, upstreamBody, 1, "messages-system-prompt", "1h") + if got := gjson.GetBytes(upstreamBody, "messages.#").Int(); got != 1 { + t.Fatalf("Messages count = %d, want no trailing system turn", got) + } } func TestClaudeExecutor_ExecuteStreamOAuthCustomToolMCPAliasRoundTrip(t *testing.T) { @@ -7894,8 +7946,11 @@ func TestClaudeExecutor_ExecuteStreamOAuthCustomToolMCPAliasRoundTrip(t *testing if got := gjson.GetBytes(upstreamBody, "system.1.text").String(); got != claudeCodeCLIIdentity { t.Fatalf("streaming system.1.text = %q, want official CLI identity", got) } - if got := gjson.GetBytes(upstreamBody, "system.#").Int(); got != 2 { - t.Fatalf("streaming top-level system block count = %d, want 2", got) + if got := gjson.GetBytes(upstreamBody, "system.#").Int(); got != 3 { + t.Fatalf("streaming top-level system block count = %d, want 3", got) + } + if got := gjson.GetBytes(upstreamBody, "system.2.text").String(); got != "stream-system-prompt" { + t.Fatalf("streaming system.2.text = %q, want stream-system-prompt", got) } content := gjson.GetBytes(upstreamBody, "messages.0.content").Array() if len(content) != 2 { @@ -7903,7 +7958,9 @@ func TestClaudeExecutor_ExecuteStreamOAuthCustomToolMCPAliasRoundTrip(t *testing } assertClaudeCodeCurrentDateBlock(t, content[0]) assertEphemeralUserTextBlock(t, content[1], "fetch", "1h") - assertClaudeMidConversationSystemMessage(t, upstreamBody, 1, "stream-system-prompt", "1h") + if got := gjson.GetBytes(upstreamBody, "messages.#").Int(); got != 1 { + t.Fatalf("streaming message count = %d, want no trailing system turn", got) + } assertClaudeCredentialIdentity(t, upstreamBody, upstreamHeaders, deviceIDs, "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa") if !strings.Contains(downstream.String(), `"name":"fetch_url"`) { t.Fatalf("downstream stream did not restore fetch_url: %s", downstream.String()) diff --git a/internal/runtime/executor/claude_mid_system_model_test.go b/internal/runtime/executor/claude_mid_system_model_test.go index 767e0aac850..10ca9c0b358 100644 --- a/internal/runtime/executor/claude_mid_system_model_test.go +++ b/internal/runtime/executor/claude_mid_system_model_test.go @@ -254,7 +254,9 @@ func TestClaudeExecutor_PayloadOverrideDoesNotRerunSystemPlacement(t *testing.T) // role=system turn. payload := []byte(`{"model":"claude-sonnet-5","max_tokens":32,` + `"system":[{"type":"text","text":"Caller top"}],` + - `"messages":[{"role":"user","content":[{"type":"text","text":"hi"}]}]}`) + `"messages":[{"role":"user","content":[{"type":"text","text":"hi"}]},` + + `{"role":"assistant","content":[{"type":"text","text":"hello"}]},` + + `{"role":"user","content":[{"type":"text","text":"follow-up"}]}]}`) errSend := test.send(t, ex, upstream.context(t, nil), payload) assertMidSystemRejected(t, errSend, upstream) diff --git a/internal/runtime/executor/claude_prompt_cache_options_test.go b/internal/runtime/executor/claude_prompt_cache_options_test.go index 2d92d389f87..900e08d3025 100644 --- a/internal/runtime/executor/claude_prompt_cache_options_test.go +++ b/internal/runtime/executor/claude_prompt_cache_options_test.go @@ -761,23 +761,15 @@ func TestClaudeExecutor_CountTokensUpstream_Cloaked_ExplicitPreservesClientSyste if gjson.GetBytes(seenBody, "messages.0.content.0.cache_control").Exists() { t.Fatalf("user message must not receive auto cache_control: %s", string(seenBody)) } - // Verify client system breakpoint was preserved with scope: global + // Verify client system breakpoint was preserved with scope: global. foundClientSystemCC := false - messages := gjson.GetBytes(seenBody, "messages") - if messages.IsArray() { - messages.ForEach(func(_, msg gjson.Result) bool { - if msg.Get("role").String() == "system" { - content := msg.Get("content") - if content.IsArray() { - content.ForEach(func(_, part gjson.Result) bool { - if part.Get("text").String() == "Count tokens system instructions" && - part.Get("cache_control.type").String() == "ephemeral" && - part.Get("cache_control.scope").String() == "global" { - foundClientSystemCC = true - } - return true - }) - } + system := gjson.GetBytes(seenBody, "system") + if system.IsArray() { + system.ForEach(func(_, part gjson.Result) bool { + if part.Get("text").String() == "Count tokens system instructions" && + part.Get("cache_control.type").String() == "ephemeral" && + part.Get("cache_control.scope").String() == "global" { + foundClientSystemCC = true } return true }) From 39632e52a6e07a52b909d45fca3a53aca4f28fc4 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Wed, 7 Oct 2026 08:57:39 +0800 Subject: [PATCH 077/142] fix(claude): keep system prompt at top level for leading user message runs - Update cloaking check to retain caller system instructions at the top level when a conversation begins with multiple consecutive user messages followed by assistant turns Closes: #6426 --- .../executor/claude_executor_cloaking.go | 2 +- .../runtime/executor/claude_executor_test.go | 36 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/internal/runtime/executor/claude_executor_cloaking.go b/internal/runtime/executor/claude_executor_cloaking.go index c0da3668ba5..a12cf906611 100644 --- a/internal/runtime/executor/claude_executor_cloaking.go +++ b/internal/runtime/executor/claude_executor_cloaking.go @@ -860,7 +860,7 @@ func claudeMidConversationSystemMessagesAtEnd(payload []byte) bool { for insertAt < len(messageBlocks) && messageBlocks[insertAt].Get("role").String() == "user" { insertAt++ } - return insertAt == len(messageBlocks) + return insertAt == len(messageBlocks) || insertAt > firstUserIdx+1 } func insertClaudeMidConversationSystemMessages(payload []byte, texts []string) []byte { diff --git a/internal/runtime/executor/claude_executor_test.go b/internal/runtime/executor/claude_executor_test.go index c7a7a6ed4bb..8547e870405 100644 --- a/internal/runtime/executor/claude_executor_test.go +++ b/internal/runtime/executor/claude_executor_test.go @@ -4379,6 +4379,24 @@ func TestCheckSystemInstructionsWithMode_SingleTerminalUserKeepsSystemTopLevel(t } } +func TestCheckSystemInstructionsWithMode_LeadingUserRunKeepsSystemTopLevelAfterAssistantTurn(t *testing.T) { + payload := []byte(`{"model":"claude-opus-5","system":[` + + `{"type":"text","text":"caller guidance"}],` + + `"messages":[{"role":"user","content":"prompt"},{"role":"user","content":"context"},` + + `{"role":"assistant","content":"answer"},{"role":"user","content":"follow-up"}]}`) + + out := checkSystemInstructionsWithMode(payload, false) + if got := gjson.GetBytes(out, "system.#").Int(); got != 3 { + t.Fatalf("top-level system block count = %d, want 3 (2 identity + caller block): %s", got, out) + } + if got := gjson.GetBytes(out, "system.2.text").String(); got != "caller guidance" { + t.Fatalf("system.2.text = %q, want caller guidance", got) + } + if got := gjson.GetBytes(out, "messages.#").Int(); got != 4 { + t.Fatalf("message count = %d, want unchanged conversation shape: %s", got, out) + } +} + func TestRelocateClaudeSystemPromptForCountTokens_TerminalUserRunKeepsSystemTopLevel(t *testing.T) { payload := []byte(`{"model":"claude-opus-5","system":[` + `{"type":"text","text":"first guidance"},` + @@ -4419,6 +4437,24 @@ func TestRelocateClaudeSystemPromptForCountTokens_SingleTerminalUserKeepsSystemT } } +func TestRelocateClaudeSystemPromptForCountTokens_LeadingUserRunKeepsSystemTopLevelAfterAssistantTurn(t *testing.T) { + payload := []byte(`{"model":"claude-opus-5","system":[` + + `{"type":"text","text":"caller guidance"}],` + + `"messages":[{"role":"user","content":"prompt"},{"role":"user","content":"context"},` + + `{"role":"assistant","content":"answer"},{"role":"user","content":"follow-up"}]}`) + + out := relocateClaudeSystemPromptForCountTokens(payload, false) + if got := gjson.GetBytes(out, "system.#").Int(); got != 1 { + t.Fatalf("top-level system block count = %d, want 1 caller block: %s", got, out) + } + if got := gjson.GetBytes(out, "system.0.text").String(); got != "caller guidance" { + t.Fatalf("system.0.text = %q, want caller guidance", got) + } + if got := gjson.GetBytes(out, "messages.#").Int(); got != 4 { + t.Fatalf("message count = %d, want unchanged conversation shape: %s", got, out) + } +} + func TestRelocateClaudeSystemPromptForCountTokensKeepsBlocksSeparate(t *testing.T) { tests := []struct { name string From 57bde35179ecbdca176ca8923d39cc18805774f2 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Wed, 7 Oct 2026 09:31:03 +0800 Subject: [PATCH 078/142] fix(executor): preserve upstream usage on apply patch failures - Buffer and publish observed upstream usage when apply patch transformation or translation encounters an error in Meta and xAI executors - Add stream usage buffer helpers to report failure metrics with captured upstream token usage Closes: #6427 --- .../executor/apply_patch_integration_test.go | 77 ++++++++++++++++++- .../runtime/executor/helps/apply_patch.go | 15 +++- .../runtime/executor/meta_executor_execute.go | 12 ++- .../runtime/executor/meta_executor_stream.go | 12 +-- .../runtime/executor/xai_executor_execute.go | 21 ++++- .../runtime/executor/xai_executor_stream.go | 12 +-- 6 files changed, 129 insertions(+), 20 deletions(-) diff --git a/internal/runtime/executor/apply_patch_integration_test.go b/internal/runtime/executor/apply_patch_integration_test.go index 4140bb3a3df..10a4ee823d1 100644 --- a/internal/runtime/executor/apply_patch_integration_test.go +++ b/internal/runtime/executor/apply_patch_integration_test.go @@ -282,6 +282,10 @@ func (p *task6UsageCapture) HandleUsage(_ context.Context, record usage.Record) } } func task6CaptureFailureUsage(t *testing.T, id string) func() { + return task6CaptureFailureUsageWithCheck(t, id, nil) +} + +func task6CaptureFailureUsageWithCheck(t *testing.T, id string, check func(usage.Record)) func() { t.Helper() capture := &task6UsageCapture{id: id, records: make(chan usage.Record, 32)} usage.RegisterNamedPlugin("task6-patch-failure", capture) @@ -293,7 +297,7 @@ func task6CaptureFailureUsage(t *testing.T, id string) func() { case record := <-capture.records: if record.RequestID == id+"-barrier" { if count != 1 { - t.Errorf("usage records=%d, want one failure", count) + t.Errorf("usage records=%d, want one", count) } return } @@ -301,6 +305,9 @@ func task6CaptureFailureUsage(t *testing.T, id string) func() { if !record.Failed { t.Errorf("invalid patch published success usage: %+v", record) } + if check != nil { + check(record) + } case <-time.After(3 * time.Second): t.Fatal("usage barrier did not arrive") } @@ -360,6 +367,74 @@ func task6Gateway(t *testing.T, exec cliproxyauth.ProviderExecutor, auth *clipro return recorder } +func TestApplyPatchFailurePreservesUpstreamUsage(t *testing.T) { + const sseBody = `data: {"type":"response.created","response":{"id":"r"}} + +data: {"type":"response.completed","response":{"output":[{"type":"function_call","id":"c","name":"apply_patch","arguments":"{}"}],"usage":{"input_tokens":5,"output_tokens":3}}} + +` + for _, tc := range []struct { + name string + provider string + body string + stream bool + compact bool + }{ + {name: "meta-direct", provider: "meta", body: `{"object":"response","output":[{"type":"function_call","id":"c","name":"apply_patch","arguments":"{}"}],"usage":{"input_tokens":5,"output_tokens":3}}`}, + {name: "meta-direct-event", provider: "meta", body: `{"type":"response.completed","response":{"output":[{"type":"function_call","id":"c","name":"apply_patch","arguments":"{}"}],"usage":{"input_tokens":5,"output_tokens":3}}}`}, + {name: "xai-compact", provider: "xai", body: `{"id":"r","output":[{"type":"function_call","id":"c","name":"apply_patch","arguments":"{}"}],"usage":{"input_tokens":5,"output_tokens":3}}`, compact: true}, + {name: "meta-sse", provider: "meta", body: sseBody, stream: true}, + {name: "xai-sse", provider: "xai", body: sseBody, stream: true}, + {name: "meta-buffered-sse", provider: "meta", body: sseBody}, + {name: "xai-buffered-sse", provider: "xai", body: sseBody}, + } { + t.Run(tc.name, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if tc.compact && r.URL.Path != "/responses/compact" { + t.Errorf("request path = %q, want /responses/compact", r.URL.Path) + } + if tc.stream { + w.Header().Set("Content-Type", "text/event-stream") + } + _, _ = io.WriteString(w, tc.body) + })) + defer server.Close() + + var exec cliproxyauth.ProviderExecutor + if tc.provider == "meta" { + exec = NewMetaExecutor(&config.Config{}) + } else { + exec = NewXAIExecutor(&config.Config{}) + } + auth := &cliproxyauth.Auth{ID: "task6-usage-" + tc.name, Provider: tc.provider, Attributes: map[string]string{"api_key": "test", "base_url": server.URL}} + checkUsage := task6CaptureFailureUsageWithCheck(t, auth.ID, func(record usage.Record) { + if record.Detail.InputTokens != 5 || record.Detail.OutputTokens != 3 { + t.Errorf("failure usage = %+v, want input/output 5/3", record.Detail) + } + }) + req := cliproxyexecutor.Request{Model: "grok-4", Payload: []byte(task6PatchRequest)} + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatOpenAIResponse, OriginalRequest: req.Payload} + if tc.compact { + opts.Alt = "responses/compact" + } + if tc.stream { + result, errExecuteStream := exec.ExecuteStream(t.Context(), auth, req, opts) + if errExecuteStream != nil { + t.Fatal(errExecuteStream) + } + assertTask6FailedStream(t, result.Chunks) + } else { + result, errExecute := exec.Execute(t.Context(), auth, req, opts) + if len(result.Payload) != 0 { + t.Errorf("failed response returned payload %s", result.Payload) + } + assertTask6PatchError(t, errExecute) + } + checkUsage() + }) + } +} + func TestApplyPatchHTTPGatewayErrorMatrix(t *testing.T) { for _, provider := range []string{"custom-compat", "claude", "claude-oauth", "gemini", "gemini-interactions", "vertex", "antigravity", "devin", "xai", "meta", "kimi"} { for _, mode := range []string{"nonstream", "stream", "eof"} { diff --git a/internal/runtime/executor/helps/apply_patch.go b/internal/runtime/executor/helps/apply_patch.go index bfbb78901fb..a0223f153d0 100644 --- a/internal/runtime/executor/helps/apply_patch.go +++ b/internal/runtime/executor/helps/apply_patch.go @@ -38,9 +38,17 @@ func CanFinalizeResponseStream(param any) bool { // RecordApplyPatchStreamFailure records validation before delivery can be canceled. func RecordApplyPatchStreamFailure(ctx context.Context, param any, reporter *UsageReporter, gatewayErr error) bool { + return RecordApplyPatchStreamFailureWithUsage(ctx, param, reporter, nil, gatewayErr) +} + +// RecordApplyPatchStreamFailureWithUsage records validation with buffered upstream usage. +func RecordApplyPatchStreamFailureWithUsage(ctx context.Context, param any, reporter *UsageReporter, streamUsage *StreamUsageBuffer, gatewayErr error) bool { if ApplyPatchTranslationError(param) == nil { return false } + if streamUsage != nil && streamUsage.PublishFailure(ctx, reporter, gatewayErr) { + return true + } reporter.PublishFailure(ctx, gatewayErr) return true } @@ -48,7 +56,12 @@ func RecordApplyPatchStreamFailure(ctx context.Context, param any, reporter *Usa // StopApplyPatchStream propagates a retained failure after its one translated frame. // The caller supplies its existing sanitized gateway status error. func StopApplyPatchStream(ctx context.Context, param any, reporter *UsageReporter, out chan<- cliproxyexecutor.StreamChunk, gatewayErr error) bool { - if !RecordApplyPatchStreamFailure(ctx, param, reporter, gatewayErr) { + return StopApplyPatchStreamWithUsage(ctx, param, reporter, nil, out, gatewayErr) +} + +// StopApplyPatchStreamWithUsage propagates a retained failure with buffered upstream usage. +func StopApplyPatchStreamWithUsage(ctx context.Context, param any, reporter *UsageReporter, streamUsage *StreamUsageBuffer, out chan<- cliproxyexecutor.StreamChunk, gatewayErr error) bool { + if !RecordApplyPatchStreamFailureWithUsage(ctx, param, reporter, streamUsage, gatewayErr) { return false } select { diff --git a/internal/runtime/executor/meta_executor_execute.go b/internal/runtime/executor/meta_executor_execute.go index 6de21936ac0..3fa0c19a5fd 100644 --- a/internal/runtime/executor/meta_executor_execute.go +++ b/internal/runtime/executor/meta_executor_execute.go @@ -143,8 +143,10 @@ func (e *MetaExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, req return resp, wrapMetaUpstreamError(httpResp.StatusCode, data) } - out, errCompleted := e.translateMetaCompleted(ctx, req, prepared, data) + var upstreamUsage helps.StreamUsageBuffer + out, errCompleted := e.translateMetaCompleted(ctx, req, prepared, data, &upstreamUsage) if errCompleted != nil { + upstreamUsage.PublishFailure(ctx, reporter, errCompleted) return resp, errCompleted } if len(out.sourceEvent) > 0 { @@ -167,7 +169,7 @@ type metaCompletedTranslation struct { sourceEvent []byte } -func (e *MetaExecutor) translateMetaCompleted(ctx context.Context, req cliproxyexecutor.Request, prepared *metaPreparedRequest, data []byte) (metaCompletedTranslation, error) { +func (e *MetaExecutor) translateMetaCompleted(ctx context.Context, req cliproxyexecutor.Request, prepared *metaPreparedRequest, data []byte, upstreamUsage *helps.StreamUsageBuffer) (metaCompletedTranslation, error) { outputItemsByIndex := make(map[int64][]byte) var outputItemsFallback [][]byte for _, line := range bytes.Split(data, []byte("\n")) { @@ -175,6 +177,9 @@ func (e *MetaExecutor) translateMetaCompleted(ctx context.Context, req cliproxye continue } eventData := bytes.TrimSpace(line[len(dataTag):]) + if detail, ok := helps.ParseCodexUsage(eventData); ok { + upstreamUsage.Observe(detail, true) + } if errEvent := metaStreamEventError(eventData); errEvent != nil { return metaCompletedTranslation{}, errEvent } @@ -201,6 +206,9 @@ func (e *MetaExecutor) translateMetaCompleted(ctx context.Context, req cliproxye } if completedData, ok := metaAsCompletedEvent(data); ok { + if detail, okUsage := helps.ParseCodexUsage(completedData); okUsage { + upstreamUsage.Observe(detail, true) + } completedData = patchCodexCompletedOutput(completedData, outputItemsByIndex, outputItemsFallback) var errBridge error completedData, errBridge = prepared.applyPatch.Bridge.TransformNonStream(completedData) diff --git a/internal/runtime/executor/meta_executor_stream.go b/internal/runtime/executor/meta_executor_stream.go index 8d5f54626da..d6733090808 100644 --- a/internal/runtime/executor/meta_executor_stream.go +++ b/internal/runtime/executor/meta_executor_stream.go @@ -89,13 +89,13 @@ func (e *MetaExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Aut emitTranslatedLine := func(translatedLine []byte) bool { lines, errBridge := prepared.applyPatch.Stream(translatedLine) if errBridge != nil { - reporter.PublishFailure(ctx, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) + streamUsage.PublishFailure(ctx, reporter, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) } var chunks [][]byte for _, line := range lines { chunks = append(chunks, helps.TranslateStreamWithClaudeInputTokens(ctx, prepared.to, prepared.responseFormat, req.Model, prepared.originalPayload, prepared.body, line, ¶m, claudeInputTokens)...) } - helps.RecordApplyPatchStreamFailure(ctx, param, reporter, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) + helps.RecordApplyPatchStreamFailureWithUsage(ctx, param, reporter, &streamUsage, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) for i := range chunks { select { case out <- cliproxyexecutor.StreamChunk{Payload: chunks[i]}: @@ -103,12 +103,12 @@ func (e *MetaExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Aut return false } } - if helps.StopApplyPatchStream(ctx, param, reporter, out, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) { + if helps.StopApplyPatchStreamWithUsage(ctx, param, reporter, &streamUsage, out, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) { return false } if errBridge != nil { errBridge = statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage} - reporter.PublishFailure(ctx, errBridge) + streamUsage.PublishFailure(ctx, reporter, errBridge) select { case out <- cliproxyexecutor.StreamChunk{Err: errBridge}: case <-ctx.Done(): @@ -153,7 +153,7 @@ func (e *MetaExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Aut } finishEvents, errFinish := prepared.applyPatch.FinishStream() if errFinish != nil { - reporter.PublishFailure(ctx, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) + streamUsage.PublishFailure(ctx, reporter, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) } for _, event := range finishEvents { for _, chunk := range helps.TranslateStreamWithClaudeInputTokens(ctx, prepared.to, prepared.responseFormat, req.Model, prepared.originalPayload, prepared.body, event, ¶m, claudeInputTokens) { @@ -166,7 +166,7 @@ func (e *MetaExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Aut } if errFinish != nil { errFinish = statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage} - reporter.PublishFailure(ctx, errFinish) + streamUsage.PublishFailure(ctx, reporter, errFinish) select { case out <- cliproxyexecutor.StreamChunk{Err: errFinish}: case <-ctx.Done(): diff --git a/internal/runtime/executor/xai_executor_execute.go b/internal/runtime/executor/xai_executor_execute.go index de001c96155..ef4e80a19a1 100644 --- a/internal/runtime/executor/xai_executor_execute.go +++ b/internal/runtime/executor/xai_executor_execute.go @@ -87,11 +87,15 @@ func (e *XAIExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, req var outputItemsFallback [][]byte responseFilter := newXAIInternalXSearchResponseFilter(prepared.filterInternalXSearch, prepared.clientDeclaredTools) namespaceRestorer := newXAINamespaceRestorer(prepared.namespaceTools) + var upstreamUsage helps.StreamUsageBuffer for _, line := range bytes.Split(data, []byte("\n")) { if !bytes.HasPrefix(line, xaiDataTag) { continue } eventData := xaiNormalizeReasoningSummaryData(bytes.TrimSpace(line[len(xaiDataTag):])) + if detail, ok := helps.ParseCodexUsage(eventData); ok { + upstreamUsage.Observe(detail, true) + } prepared.applyPatch.RememberDispatcherEvent(eventData) eventData = namespaceRestorer.restore(eventData) if prepared.webSearchAlias != "" { @@ -104,6 +108,7 @@ func (e *XAIExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, req events, errBridge := prepared.applyPatch.Transform(eventData) if errBridge != nil { errBridge = statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage} + upstreamUsage.PublishFailure(ctx, reporter, errBridge) return resp, errBridge } for _, eventData := range events { @@ -123,7 +128,9 @@ func (e *XAIExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, req var param any out := sdktranslator.TranslateNonStream(ctx, prepared.to, prepared.responseFormat, req.Model, prepared.originalPayload, prepared.body, completedData, ¶m) if helps.ApplyPatchTranslationError(param) != nil || len(out) == 0 { - return cliproxyexecutor.Response{}, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage} + errTranslation := statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage} + upstreamUsage.PublishFailure(ctx, reporter, errTranslation) + return cliproxyexecutor.Response{}, errTranslation } if detail, ok := helps.ParseCodexUsage(eventData); ok { reporter.Publish(ctx, detail) @@ -137,7 +144,9 @@ func (e *XAIExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, req } if errFinish := prepared.applyPatch.Finish(); errFinish != nil { - return resp, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage} + errFinish = statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage} + upstreamUsage.PublishFailure(ctx, reporter, errFinish) + return resp, errFinish } return resp, statusErr{code: http.StatusRequestTimeout, msg: "xai stream error: stream disconnected before response.completed or response.incomplete"} } @@ -149,17 +158,21 @@ func (e *XAIExecutor) executeCompact(ctx context.Context, auth *cliproxyauth.Aut } defer reporter.TrackFailure(ctx, &err) + upstreamUsage := helps.ParseOpenAIUsage(data) converted, errBridge := prepared.applyPatch.Bridge.TransformNonStream(data) if errBridge != nil { errBridge = statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage} + reporter.PublishFailureWithDetail(ctx, upstreamUsage, errBridge) return resp, errBridge } var param any out := sdktranslator.TranslateNonStream(ctx, prepared.to, prepared.responseFormat, req.Model, prepared.originalPayload, prepared.body, converted, ¶m) if helps.ApplyPatchTranslationError(param) != nil || len(out) == 0 { - return cliproxyexecutor.Response{}, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage} + errTranslation := statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage} + reporter.PublishFailureWithDetail(ctx, upstreamUsage, errTranslation) + return cliproxyexecutor.Response{}, errTranslation } - reporter.Publish(ctx, helps.ParseOpenAIUsage(data)) + reporter.Publish(ctx, upstreamUsage) if prepared.responseFormat == sdktranslator.FormatOpenAIResponse { out = helps.EnsureResponsesUsageDetails(out) } diff --git a/internal/runtime/executor/xai_executor_stream.go b/internal/runtime/executor/xai_executor_stream.go index d7918e1eebc..1c5588a8bdb 100644 --- a/internal/runtime/executor/xai_executor_stream.go +++ b/internal/runtime/executor/xai_executor_stream.go @@ -90,7 +90,7 @@ func (e *XAIExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Auth emitTranslatedLine := func(translatedLine []byte) bool { lines, errBridge := prepared.applyPatch.Stream(translatedLine) if errBridge != nil { - reporter.PublishFailure(ctx, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) + streamUsage.PublishFailure(ctx, reporter, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) } var chunks [][]byte for _, line := range lines { @@ -113,7 +113,7 @@ func (e *XAIExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Auth } chunks = append(chunks, helps.TranslateStreamWithClaudeInputTokens(ctx, prepared.to, prepared.responseFormat, req.Model, prepared.originalPayload, prepared.body, line, ¶m, claudeInputTokens)...) } - helps.RecordApplyPatchStreamFailure(ctx, param, reporter, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) + helps.RecordApplyPatchStreamFailureWithUsage(ctx, param, reporter, &streamUsage, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) for i := range chunks { select { case out <- cliproxyexecutor.StreamChunk{Payload: chunks[i]}: @@ -121,12 +121,12 @@ func (e *XAIExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Auth return false } } - if helps.StopApplyPatchStream(ctx, param, reporter, out, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) { + if helps.StopApplyPatchStreamWithUsage(ctx, param, reporter, &streamUsage, out, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) { return false } if errBridge != nil { errBridge = statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage} - reporter.PublishFailure(ctx, errBridge) + streamUsage.PublishFailure(ctx, reporter, errBridge) select { case out <- cliproxyexecutor.StreamChunk{Err: errBridge}: case <-ctx.Done(): @@ -203,7 +203,7 @@ func (e *XAIExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Auth } finishEvents, errFinish := prepared.applyPatch.FinishStream() if errFinish != nil { - reporter.PublishFailure(ctx, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) + streamUsage.PublishFailure(ctx, reporter, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) } for _, event := range finishEvents { for _, chunk := range helps.TranslateStreamWithClaudeInputTokens(ctx, prepared.to, prepared.responseFormat, req.Model, prepared.originalPayload, prepared.body, event, ¶m, claudeInputTokens) { @@ -216,7 +216,7 @@ func (e *XAIExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Auth } if errFinish != nil { errFinish = statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage} - reporter.PublishFailure(ctx, errFinish) + streamUsage.PublishFailure(ctx, reporter, errFinish) select { case out <- cliproxyexecutor.StreamChunk{Err: errFinish}: case <-ctx.Done(): From 306c9bd824edb5218b600e0ebe60db5b14e99425 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Wed, 7 Oct 2026 13:46:58 +0800 Subject: [PATCH 079/142] fix(routing): restrict speech-only models to speech endpoints and refine xAI error scoping - Reject speech-only models (such as `grok-tts` and `grok-voice-tts-1.0`) on non-speech entry protocols to prevent invalid chat upstream routing - Mark upstream 404 errors for xAI speech as request-scoped unless indicating model unavailability, preventing unnecessary credential rotation and model cooldowns - Align xAI speech payload finalizer protocol with `openai` for consistent payload override rules --- .../runtime/executor/xai_executor_speech.go | 69 ++++- .../executor/xai_executor_speech_test.go | 226 ++++++++++++++ sdk/api/handlers/handlers_execution.go | 2 + sdk/api/handlers/handlers_routing.go | 40 ++- sdk/api/handlers/handlers_speech_only_test.go | 282 ++++++++++++++++++ sdk/api/handlers/handlers_stream.go | 2 + sdk/api/handlers/model_execution.go | 5 + .../openai/openai_speech_routing_test.go | 167 +++++++++++ 8 files changed, 788 insertions(+), 5 deletions(-) create mode 100644 sdk/api/handlers/handlers_speech_only_test.go create mode 100644 sdk/api/handlers/openai/openai_speech_routing_test.go diff --git a/internal/runtime/executor/xai_executor_speech.go b/internal/runtime/executor/xai_executor_speech.go index c8946bcb46c..243477f3be3 100644 --- a/internal/runtime/executor/xai_executor_speech.go +++ b/internal/runtime/executor/xai_executor_speech.go @@ -14,6 +14,70 @@ import ( "github.com/tidwall/gjson" ) +// xaiSpeechRequestError marks upstream speech failures caused by the request itself, +// such as an unknown voice id answered with 404, so the auth manager neither retries +// them on other credentials nor cools down the credential or model. +type xaiSpeechRequestError struct { + statusErr +} + +func (xaiSpeechRequestError) IsRequestScoped() bool { + return true +} + +// xaiSpeechModelUnavailablePatterns mirror the auth manager's model-support phrases so +// model availability failures keep their credential rotation and model cooldown handling. +var xaiSpeechModelUnavailablePatterns = [...]string{ + "model_not_found", + "model_not_supported", + "model is not supported", + "model is unsupported", + "model not supported", + "unsupported model", + "model is not available", + "model not available", + "model is unavailable", + "model unavailable", + "not available for your plan", + "not available for your account", +} + +// xaiSpeechModelUnavailable reports whether an upstream error body says the speech model +// itself is missing, unsupported or unavailable, as opposed to a bad request value. +func xaiSpeechModelUnavailable(body []byte) bool { + if !gjson.ValidBytes(body) { + return xaiSpeechModelUnavailableText(string(body)) + } + for _, path := range []string{"code", "error.code", "type", "error.type", "error", "error.message", "message", "detail"} { + if xaiSpeechModelUnavailableText(gjson.GetBytes(body, path).String()) { + return true + } + } + return false +} + +func xaiSpeechModelUnavailableText(text string) bool { + lower := strings.ToLower(text) + for _, pattern := range xaiSpeechModelUnavailablePatterns { + if strings.Contains(lower, pattern) { + return true + } + } + return false +} + +// xaiSpeechStatusErr keeps credential, rate-limit, server and model-availability failures on +// the regular xAI error path. Only other 404s, such as an unknown voice id, are flagged as +// request-scoped. 400/422 stay unwrapped because the auth manager already treats them as +// request faults while still honoring model-support errors. +func xaiSpeechStatusErr(code int, body []byte) error { + err := xaiStatusErr(code, body) + if err.code == http.StatusNotFound && !xaiSpeechModelUnavailable(body) { + return xaiSpeechRequestError{statusErr: err} + } + return err +} + func (e *XAIExecutor) executeSpeech(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (resp cliproxyexecutor.Response, err error) { model := strings.TrimSpace(gjson.GetBytes(req.Payload, "model").String()) if model == "" { @@ -26,7 +90,8 @@ func (e *XAIExecutor) executeSpeech(ctx context.Context, auth *cliproxyauth.Auth requestURL := xaiSpeechRequestURL(auth) logXAIResolvedBaseURL(ctx, strings.TrimSuffix(requestURL, xaiTTSPath)) - payload := helps.NewPayloadFinalizer(e.cfg, e.Identifier(), model, xaiSpeechHandlerType, "", req.Payload, req, opts)(req.Payload) + // Payload rules target the "openai" protocol, matching xAI image/video and config.example.yaml. + payload := helps.NewPayloadFinalizer(e.cfg, e.Identifier(), model, "openai", "", req.Payload, req, opts)(req.Payload) httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, requestURL, bytes.NewReader(payload)) if err != nil { return resp, err @@ -59,7 +124,7 @@ func (e *XAIExecutor) executeSpeech(ctx context.Context, auth *cliproxyauth.Auth if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), data)) - err = xaiStatusErr(httpResp.StatusCode, data) + err = xaiSpeechStatusErr(httpResp.StatusCode, data) return resp, err } diff --git a/internal/runtime/executor/xai_executor_speech_test.go b/internal/runtime/executor/xai_executor_speech_test.go index 3248d8920e5..3515ab297bf 100644 --- a/internal/runtime/executor/xai_executor_speech_test.go +++ b/internal/runtime/executor/xai_executor_speech_test.go @@ -2,17 +2,23 @@ package executor import ( "context" + "errors" "io" "net/http" "net/http/httptest" "strings" + "sync/atomic" "testing" + "time" + "github.com/google/uuid" xaiauth "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/xai" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" ) func TestXAISpeechRequestURLStaysOnOfficialAPI(t *testing.T) { @@ -120,3 +126,223 @@ func TestXAIExecutorExecuteStreamRejectsSpeech(t *testing.T) { t.Fatalf("status error = %v", err) } } + +func TestXAIExecutorExecuteSpeechPayloadRulesMatchOpenAIProtocol(t *testing.T) { + const body = `{"text":"hello","voice_id":"eve","language":"auto"}` + var gotBody string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + raw, errRead := io.ReadAll(r.Body) + if errRead != nil { + t.Errorf("read body: %v", errRead) + } + gotBody = string(raw) + w.Header().Set("Content-Type", "audio/mpeg") + _, _ = w.Write([]byte("ID3audio")) + })) + defer server.Close() + + cfg := &config.Config{Payload: config.PayloadConfig{Override: []config.PayloadRule{{ + Models: []config.PayloadModelRule{{Name: "grok-tts", Protocol: "openai"}}, + Params: map[string]any{"voice_id": "ara", "language": "en"}, + }}}} + exec := NewXAIExecutor(cfg) + auth := &cliproxyauth.Auth{ + Provider: "xai", + Attributes: map[string]string{ + "base_url": server.URL + "/v1", + "auth_kind": "oauth", + }, + Metadata: map[string]any{"access_token": "xai-token"}, + } + _, err := exec.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "grok-tts", + Payload: []byte(body), + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FromString(xaiSpeechHandlerType), + }) + if err != nil { + t.Fatalf("Execute() error = %v", err) + } + if got := gjson.Get(gotBody, "voice_id").String(); got != "ara" { + t.Fatalf("voice_id = %q, want payload rule override ara; body=%s", got, gotBody) + } + if got := gjson.Get(gotBody, "language").String(); got != "en" { + t.Fatalf("language = %q, want payload rule override en; body=%s", got, gotBody) + } + if got := gjson.Get(gotBody, "text").String(); got != "hello" { + t.Fatalf("text = %q, want hello; body=%s", got, gotBody) + } +} + +func TestXAIExecutorExecuteSpeechUpstreamErrorScope(t *testing.T) { + tests := []struct { + name string + status int + body string + wantStatus int + wantScoped bool + }{ + {name: "bad request", status: http.StatusBadRequest, body: `{"error":"invalid language"}`, wantStatus: http.StatusBadRequest}, + {name: "bad request model unsupported", status: http.StatusBadRequest, body: `{"error":"requested model is not supported"}`, wantStatus: http.StatusBadRequest}, + {name: "unknown voice not found", status: http.StatusNotFound, body: `{"error":"voice not found"}`, wantStatus: http.StatusNotFound, wantScoped: true}, + {name: "model not found nested code", status: http.StatusNotFound, body: `{"error":{"code":"model_not_found","message":"The model grok-tts does not exist"}}`, wantStatus: http.StatusNotFound}, + {name: "model not found flat code", status: http.StatusNotFound, body: `{"code":"model_not_found","error":"model unavailable"}`, wantStatus: http.StatusNotFound}, + {name: "model not available", status: http.StatusNotFound, body: `{"error":"The model grok-tts is not available for your account"}`, wantStatus: http.StatusNotFound}, + {name: "model not available plain text", status: http.StatusNotFound, body: `model is not available`, wantStatus: http.StatusNotFound}, + {name: "model unsupported", status: http.StatusNotFound, body: `{"error":{"message":"Unsupported model: grok-tts"}}`, wantStatus: http.StatusNotFound}, + {name: "unprocessable", status: http.StatusUnprocessableEntity, body: `{"error":"text too long"}`, wantStatus: http.StatusUnprocessableEntity}, + {name: "unprocessable model unsupported", status: http.StatusUnprocessableEntity, body: `{"code":"model_not_supported","error":"model is not supported"}`, wantStatus: http.StatusUnprocessableEntity}, + {name: "unauthorized", status: http.StatusUnauthorized, body: `{"error":"unauthorized"}`, wantStatus: http.StatusUnauthorized}, + {name: "bad credentials remapped", status: http.StatusForbidden, body: `{"code":"bad-credentials","error":"access token could not be validated"}`, wantStatus: http.StatusUnauthorized}, + {name: "forbidden", status: http.StatusForbidden, body: `{"error":"forbidden"}`, wantStatus: http.StatusForbidden}, + {name: "rate limited", status: http.StatusTooManyRequests, body: `{"error":"rate limited"}`, wantStatus: http.StatusTooManyRequests}, + {name: "upstream failure", status: http.StatusInternalServerError, body: `{"error":"boom"}`, wantStatus: http.StatusInternalServerError}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(tt.status) + _, _ = w.Write([]byte(tt.body)) + })) + defer server.Close() + + exec := NewXAIExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{ + Provider: "xai", + Attributes: map[string]string{ + "base_url": server.URL + "/v1", + "auth_kind": "oauth", + }, + Metadata: map[string]any{"access_token": "xai-token"}, + } + _, err := exec.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "grok-tts", + Payload: []byte(`{"text":"hello","voice_id":"nope","language":"auto"}`), + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FromString(xaiSpeechHandlerType), + }) + if err == nil { + t.Fatal("Execute() error = nil, want upstream error") + } + status, ok := err.(interface{ StatusCode() int }) + if !ok || status.StatusCode() != tt.wantStatus { + t.Fatalf("status error = %v (%T), want status %d", err, err, tt.wantStatus) + } + if err.Error() != tt.body { + t.Fatalf("error message = %q, want upstream body %q", err.Error(), tt.body) + } + if tt.wantScoped { + assertRequestScopedTestError(t, err) + if !isRequestScopedExecutorError(err) { + t.Fatalf("error %T is not recognized as cliproxyexecutor.RequestScopedError", err) + } + return + } + assertNotRequestScopedTestError(t, err) + if isRequestScopedExecutorError(err) { + t.Fatalf("error %T unexpectedly recognized as cliproxyexecutor.RequestScopedError", err) + } + }) + } +} + +func isRequestScopedExecutorError(err error) bool { + var requestErr cliproxyexecutor.RequestScopedError + return errors.As(err, &requestErr) && requestErr.IsRequestScoped() +} + +func newXAISpeechScopeManager(t *testing.T, baseURL string, count int) (*cliproxyauth.Manager, []string) { + t.Helper() + manager := cliproxyauth.NewManager(nil, nil, nil) + manager.SetRetryConfig(0, 0, 0) + manager.RegisterExecutor(NewXAIExecutor(&config.Config{})) + + reg := registry.GetGlobalRegistry() + authIDs := make([]string, 0, count) + for i := 0; i < count; i++ { + auth := &cliproxyauth.Auth{ + ID: uuid.NewString() + "-xai-speech-scope", + Provider: "xai", + Attributes: map[string]string{ + "base_url": baseURL + "/v1", + "auth_kind": "oauth", + }, + Metadata: map[string]any{"access_token": "xai-token-" + uuid.NewString()}, + } + reg.RegisterClient(auth.ID, "xai", []*registry.ModelInfo{{ID: "grok-tts"}}) + authID := auth.ID + t.Cleanup(func() { reg.UnregisterClient(authID) }) + if _, err := manager.Register(context.Background(), auth); err != nil { + t.Fatalf("register auth: %v", err) + } + authIDs = append(authIDs, auth.ID) + } + return manager, authIDs +} + +func TestXAIExecutorSpeechUnknownVoiceDoesNotRotateOrCoolCredentials(t *testing.T) { + var attempts atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + attempts.Add(1) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(`{"error":"voice not found"}`)) + })) + defer server.Close() + + manager, authIDs := newXAISpeechScopeManager(t, server.URL, 2) + reg := registry.GetGlobalRegistry() + + _, err := manager.Execute(context.Background(), []string{"xai"}, cliproxyexecutor.Request{ + Model: "grok-tts", + Payload: []byte(`{"text":"hello","voice_id":"nope","language":"auto"}`), + }, cliproxyexecutor.Options{SourceFormat: sdktranslator.FromString(xaiSpeechHandlerType)}) + if err == nil { + t.Fatal("Execute() error = nil, want upstream 404") + } + if got := attempts.Load(); got != 1 { + t.Fatalf("upstream attempts = %d, want 1 (no cross-credential retry)", got) + } + + now := time.Now() + for _, id := range authIDs { + updated, ok := manager.GetByID(id) + if !ok || updated == nil { + t.Fatalf("auth %s not found", id) + } + if updated.Unavailable || updated.NextRetryAfter.After(now) { + t.Fatalf("auth %s cooled down: unavailable=%v next_retry_after=%v", id, updated.Unavailable, updated.NextRetryAfter) + } + if state := updated.ModelStates["grok-tts"]; state != nil && (state.Unavailable || state.NextRetryAfter.After(now)) { + t.Fatalf("auth %s model grok-tts cooled down: %+v", id, state) + } + if reg.IsModelSuspendedForClient(id, "grok-tts") { + t.Fatalf("auth %s model grok-tts suspended in registry", id) + } + } +} + +func TestXAIExecutorSpeechModelNotFoundRotatesCredentials(t *testing.T) { + var attempts atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + attempts.Add(1) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(`{"error":{"code":"model_not_found","message":"The model grok-tts does not exist"}}`)) + })) + defer server.Close() + + manager, _ := newXAISpeechScopeManager(t, server.URL, 2) + + _, err := manager.Execute(context.Background(), []string{"xai"}, cliproxyexecutor.Request{ + Model: "grok-tts", + Payload: []byte(`{"text":"hello","voice_id":"eve","language":"auto"}`), + }, cliproxyexecutor.Options{SourceFormat: sdktranslator.FromString(xaiSpeechHandlerType)}) + if err == nil { + t.Fatal("Execute() error = nil, want upstream 404") + } + if got := attempts.Load(); got != 2 { + t.Fatalf("upstream attempts = %d, want 2 (model_not_found keeps credential rotation)", got) + } +} diff --git a/sdk/api/handlers/handlers_execution.go b/sdk/api/handlers/handlers_execution.go index 75eab384c21..16c0f4f781c 100644 --- a/sdk/api/handlers/handlers_execution.go +++ b/sdk/api/handlers/handlers_execution.go @@ -46,6 +46,8 @@ func (h *BaseAPIHandler) executeWithAuthManager(ctx context.Context, handlerType func (h *BaseAPIHandler) executeWithAuthManagerFormats(ctx context.Context, entryProtocol, exitProtocol, modelName string, rawJSON []byte, alt string, allowImageModel bool, execOptions modelExecutionOptions) ([]byte, http.Header, *interfaces.ErrorMessage) { originalRequestedModel := modelName + // Speech-only models are reachable solely through the speech entry protocol. + execOptions.AllowSpeechModel = isModelExecutionSpeechProtocol(entryProtocol) routeDecision := h.applyModelRouter(ctx, entryProtocol, modelName, rawJSON, false, execOptions) responseProtocol := modelExecutionResponseProtocol(entryProtocol, exitProtocol) if errMsg := validateNativeInteractionsExecution(entryProtocol, execOptions, routeDecision); errMsg != nil { diff --git a/sdk/api/handlers/handlers_routing.go b/sdk/api/handlers/handlers_routing.go index e7297704cf4..e29a1a89ada 100644 --- a/sdk/api/handlers/handlers_routing.go +++ b/sdk/api/handlers/handlers_routing.go @@ -98,7 +98,7 @@ func excludeExecutionProvider(providers []string, excluded string) []string { } func (h *BaseAPIHandler) getRequestDetails(modelName string) (providers []string, normalizedModel string, err *interfaces.ErrorMessage) { - return h.getRequestDetailsWithOptions(modelName, false) + return h.getRequestDetailsWithOptions(modelName, false, false) } func validateNativeInteractionsExecution(entryProtocol string, execOptions modelExecutionOptions, routeDecision modelRouteDecision) *interfaces.ErrorMessage { @@ -141,6 +141,9 @@ func (h *BaseAPIHandler) providersForExecution(modelName, originalRequestedModel if errMsg := h.validateImageOnlyModel(normalizedModel, allowImageModel); errMsg != nil { return nil, "", errMsg } + if errMsg := h.validateSpeechOnlyModel(normalizedModel, execOptions.AllowSpeechModel); errMsg != nil { + return nil, "", errMsg + } return []string{forcedProvider}, normalizedModel, nil } if routeDecision.Provider != "" { @@ -151,12 +154,15 @@ func (h *BaseAPIHandler) providersForExecution(modelName, originalRequestedModel if errMsg := h.validateImageOnlyModel(normalizedModel, allowImageModel); errMsg != nil { return nil, "", errMsg } + if errMsg := h.validateSpeechOnlyModel(normalizedModel, execOptions.AllowSpeechModel); errMsg != nil { + return nil, "", errMsg + } return []string{routeDecision.Provider}, normalizedModel, nil } - return h.getRequestDetailsWithOptions(modelName, allowImageModel) + return h.getRequestDetailsWithOptions(modelName, allowImageModel, execOptions.AllowSpeechModel) } -func (h *BaseAPIHandler) getRequestDetailsWithOptions(modelName string, allowImageModel bool) (providers []string, normalizedModel string, err *interfaces.ErrorMessage) { +func (h *BaseAPIHandler) getRequestDetailsWithOptions(modelName string, allowImageModel, allowSpeechModel bool) (providers []string, normalizedModel string, err *interfaces.ErrorMessage) { resolvedModelName := modelName initialSuffix := thinking.ParseSuffix(modelName) if initialSuffix.ModelName == "auto" { @@ -184,6 +190,9 @@ func (h *BaseAPIHandler) getRequestDetailsWithOptions(modelName string, allowIma if errMsg := h.validateImageOnlyModel(baseModel, allowImageModel); errMsg != nil { return nil, "", errMsg } + if errMsg := h.validateSpeechOnlyModel(baseModel, allowSpeechModel); errMsg != nil { + return nil, "", errMsg + } if h != nil && h.AuthManager != nil && h.AuthManager.HomeEnabled() { return []string{"home"}, resolvedModelName, nil @@ -246,6 +255,31 @@ func isOpenAIImageOnlyModel(model string) bool { } } +// validateSpeechOnlyModel rejects speech-only models outside the speech endpoints so they are +// never sent to a chat upstream. +func (h *BaseAPIHandler) validateSpeechOnlyModel(modelName string, allowSpeechModel bool) *interfaces.ErrorMessage { + baseModel := strings.TrimSpace(thinking.ParseSuffix(modelName).ModelName) + if baseModel == "" { + baseModel = strings.TrimSpace(modelName) + } + if isXAISpeechOnlyModel(baseModel) && !allowSpeechModel { + return &interfaces.ErrorMessage{ + StatusCode: http.StatusBadRequest, + Error: fmt.Errorf("model %s is only supported on /v1/audio/speech and /v1/tts", routeModelBaseName(baseModel)), + } + } + return nil +} + +func isXAISpeechOnlyModel(model string) bool { + switch strings.ToLower(strings.TrimSpace(routeModelBaseName(model))) { + case "grok-tts", "grok-voice-tts-1.0": + return true + default: + return false + } +} + func routeModelBaseName(model string) string { model = strings.TrimSpace(model) if idx := strings.LastIndex(model, "/"); idx >= 0 && idx < len(model)-1 { diff --git a/sdk/api/handlers/handlers_speech_only_test.go b/sdk/api/handlers/handlers_speech_only_test.go new file mode 100644 index 00000000000..445e61f04fa --- /dev/null +++ b/sdk/api/handlers/handlers_speech_only_test.go @@ -0,0 +1,282 @@ +package handlers + +import ( + "context" + "net/http" + "strings" + "testing" + "time" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + sdkconfig "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" +) + +const speechOnlyRouteHint = "/v1/audio/speech" + +var speechOnlyModels = []string{ + "grok-tts", + "xai/grok-tts", + "XAI/Grok-TTS", + "grok-tts(auto)", + "grok-voice-tts-1.0", + "xai/grok-voice-tts-1.0", +} + +func registerSpeechOnlyTestModels(t *testing.T) { + t.Helper() + modelRegistry := registry.GetGlobalRegistry() + const clientID = "test-speech-only-xai" + modelRegistry.RegisterClient(clientID, "xai", []*registry.ModelInfo{ + {ID: "grok-tts", Created: time.Now().Unix()}, + {ID: "grok-voice-tts-1.0", Created: time.Now().Unix()}, + }) + t.Cleanup(func() { + modelRegistry.UnregisterClient(clientID) + }) +} + +func requireSpeechOnlyError(t *testing.T, errMsg *interfaces.ErrorMessage) { + t.Helper() + if errMsg == nil { + t.Fatal("error = nil, want speech-only rejection") + } + if errMsg.StatusCode != http.StatusBadRequest { + t.Fatalf("status = %d, want %d", errMsg.StatusCode, http.StatusBadRequest) + } + if errMsg.Error == nil || !strings.Contains(errMsg.Error.Error(), speechOnlyRouteHint) { + t.Fatalf("error = %+v, want message mentioning %s", errMsg.Error, speechOnlyRouteHint) + } +} + +func requireNotSpeechOnlyError(t *testing.T, errMsg *interfaces.ErrorMessage) { + t.Helper() + if errMsg != nil && errMsg.Error != nil && strings.Contains(errMsg.Error.Error(), speechOnlyRouteHint) { + t.Fatalf("speech endpoint rejected speech-only model: %+v", errMsg) + } +} + +func TestGetRequestDetails_SpeechOnlyModelReturns400(t *testing.T) { + registerSpeechOnlyTestModels(t) + handler := NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, coreauth.NewManager(nil, nil, nil)) + + for _, model := range speechOnlyModels { + t.Run(model, func(t *testing.T) { + providers, _, errMsg := handler.getRequestDetails(model) + if errMsg == nil { + t.Fatalf("getRequestDetails(%q) providers = %v, want speech-only rejection", model, providers) + } + requireSpeechOnlyError(t, errMsg) + }) + } +} + +func TestExecuteWithAuthManager_RejectsSpeechOnlyModelOnNonSpeechProtocols(t *testing.T) { + registerSpeechOnlyTestModels(t) + handler := NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, coreauth.NewManager(nil, nil, nil)) + + protocols := []string{"openai", "openai-response", "claude", "gemini", "openai-image", "openai-video"} + for _, protocol := range protocols { + for _, model := range speechOnlyModels { + t.Run(protocol+"/"+model, func(t *testing.T) { + body := []byte(`{"model":"` + model + `","messages":[{"role":"user","content":"hi"}]}`) + + _, _, errMsg := handler.ExecuteWithAuthManager(context.Background(), protocol, model, body, "") + requireSpeechOnlyError(t, errMsg) + + dataChan, _, errChan := handler.ExecuteStreamWithAuthManager(context.Background(), protocol, model, body, "") + if dataChan != nil { + t.Fatal("stream returned a data channel for a speech-only model") + } + requireSpeechOnlyError(t, <-errChan) + + _, _, errMsg = handler.ExecuteCountWithAuthManager(context.Background(), protocol, model, body, "") + requireSpeechOnlyError(t, errMsg) + + _, _, errMsg = handler.ExecuteImageWithAuthManager(context.Background(), protocol, model, body, "") + requireSpeechOnlyError(t, errMsg) + }) + } + } +} + +func TestExecuteWithAuthManager_AllowsSpeechOnlyModelOnSpeechProtocol(t *testing.T) { + registerSpeechOnlyTestModels(t) + handler := NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, coreauth.NewManager(nil, nil, nil)) + + for _, model := range speechOnlyModels { + t.Run(model, func(t *testing.T) { + body := []byte(`{"text":"hello","voice_id":"eve"}`) + _, _, errMsg := handler.ExecuteWithAuthManager(context.Background(), "openai-speech", model, body, "") + if errMsg == nil { + t.Fatal("expected auth selection error on empty manager, got nil") + } + requireNotSpeechOnlyError(t, errMsg) + }) + } +} + +func TestModelExecutionRejectsSpeechOnlyModelOutsideSpeechProtocol(t *testing.T) { + registerSpeechOnlyTestModels(t) + handler := NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, coreauth.NewManager(nil, nil, nil)) + body := []byte(`{"model":"grok-tts"}`) + + _, errMsg := handler.ExecuteProtocolWithAuthManager(context.Background(), ProtocolExecutionRequest{ + EntryProtocol: "openai", + ExitProtocol: "openai", + Model: "grok-tts", + Body: body, + }) + requireSpeechOnlyError(t, errMsg) + + _, errMsg = handler.ExecuteModel(context.Background(), ModelExecutionRequest{ + EntryProtocol: "openai", + ExitProtocol: "openai", + Model: "grok-tts", + Body: body, + }) + requireSpeechOnlyError(t, errMsg) + + _, errMsg = handler.ExecuteProtocolWithAuthManager(context.Background(), ProtocolExecutionRequest{ + EntryProtocol: "openai-speech", + ExitProtocol: "openai-speech", + Model: "grok-tts", + Body: body, + }) + requireNotSpeechOnlyError(t, errMsg) + + _, errMsg = handler.ExecuteModel(context.Background(), ModelExecutionRequest{ + EntryProtocol: "openai-speech", + ExitProtocol: "openai-speech", + Model: "grok-tts", + Body: body, + }) + requireNotSpeechOnlyError(t, errMsg) +} + +func TestHandlerProvidersForExecutionRejectsSpeechOnlyModelOnProviderRoute(t *testing.T) { + handler := NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, nil) + cases := []struct { + name string + modelName string + originalModel string + decision modelRouteDecision + execOptions modelExecutionOptions + }{ + { + name: "target-model", + modelName: "ignored", + originalModel: "original-model", + decision: modelRouteDecision{Provider: "xai", Model: "grok-tts"}, + }, + { + name: "original-model-thinking-suffix", + modelName: "ignored", + originalModel: "grok-voice-tts-1.0(auto)", + decision: modelRouteDecision{Provider: "xai"}, + }, + { + name: "forced-provider", + modelName: "xai/grok-tts", + originalModel: "xai/grok-tts", + execOptions: modelExecutionOptions{ForcedProvider: "xai"}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + _, _, errMsg := handler.providersForExecution(tc.modelName, tc.originalModel, false, tc.decision, tc.execOptions) + requireSpeechOnlyError(t, errMsg) + }) + } +} + +func TestSpeechOnlyModelsKeepImageAndVideoBehavior(t *testing.T) { + for _, model := range speechOnlyModels { + if isOpenAIImageOnlyModel(model) { + t.Fatalf("isOpenAIImageOnlyModel(%q) = true, want false", model) + } + } + handler := NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, coreauth.NewManager(nil, nil, nil)) + if errMsg := handler.validateImageOnlyModel("grok-imagine-video", false); errMsg != nil { + t.Fatalf("validateImageOnlyModel(video) = %+v, want nil", errMsg) + } + _, _, errMsg := handler.ExecuteWithAuthManager(context.Background(), "openai-video", "grok-imagine-video", []byte(`{}`), "") + requireNotSpeechOnlyError(t, errMsg) +} + +func speechOnlyChatBody(model string) []byte { + return []byte(`{"model":"` + model + `","messages":[{"role":"user","content":"hi"}]}`) +} + +func TestSpeechOnlyModelRejectedWhenOnlyExitProtocolIsSpeech(t *testing.T) { + registerSpeechOnlyTestModels(t) + handler := NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, coreauth.NewManager(nil, nil, nil)) + + for _, model := range speechOnlyModels { + t.Run(model, func(t *testing.T) { + body := speechOnlyChatBody(model) + + _, _, errMsg := handler.executeWithAuthManagerFormats(context.Background(), "openai", "openai-speech", model, body, "", false, modelExecutionOptions{}) + requireSpeechOnlyError(t, errMsg) + + _, errMsg = handler.ExecuteProtocolWithAuthManager(context.Background(), ProtocolExecutionRequest{ + EntryProtocol: "openai", + ExitProtocol: "openai-speech", + Model: model, + Body: body, + }) + requireSpeechOnlyError(t, errMsg) + }) + } +} + +func TestSpeechOnlyModelStreamRejectedWhenOnlyExitProtocolIsSpeech(t *testing.T) { + registerSpeechOnlyTestModels(t) + handler := NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, coreauth.NewManager(nil, nil, nil)) + + for _, model := range speechOnlyModels { + t.Run(model, func(t *testing.T) { + body := speechOnlyChatBody(model) + + dataChan, _, errChan := handler.executeStreamWithAuthManagerFormats(context.Background(), "openai", "openai-speech", model, body, "", false, modelExecutionOptions{}) + if dataChan != nil { + t.Fatal("stream returned a data channel for a speech-only model on a chat entry") + } + requireSpeechOnlyError(t, <-errChan) + + _, errMsg := handler.ExecuteProtocolStreamWithAuthManager(context.Background(), ProtocolExecutionRequest{ + EntryProtocol: "openai", + ExitProtocol: "openai-speech", + Model: model, + Body: body, + Stream: true, + }) + requireSpeechOnlyError(t, errMsg) + }) + } +} + +func TestSpeechOnlyModelAllowedWhenEntryAndExitAreSpeech(t *testing.T) { + registerSpeechOnlyTestModels(t) + handler := NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, coreauth.NewManager(nil, nil, nil)) + + for _, model := range speechOnlyModels { + t.Run(model, func(t *testing.T) { + body := []byte(`{"text":"hello","voice_id":"eve"}`) + + _, _, errMsg := handler.executeWithAuthManagerFormats(context.Background(), "openai-speech", "openai-speech", model, body, "", false, modelExecutionOptions{}) + if errMsg == nil { + t.Fatal("expected auth selection error on empty manager, got nil") + } + requireNotSpeechOnlyError(t, errMsg) + + _, _, errChan := handler.executeStreamWithAuthManagerFormats(context.Background(), "openai-speech", "openai-speech", model, body, "", false, modelExecutionOptions{}) + errMsg = <-errChan + if errMsg == nil { + t.Fatal("expected auth selection error on empty manager, got nil") + } + requireNotSpeechOnlyError(t, errMsg) + }) + } +} diff --git a/sdk/api/handlers/handlers_stream.go b/sdk/api/handlers/handlers_stream.go index a207c5fc3d5..9e637964b42 100644 --- a/sdk/api/handlers/handlers_stream.go +++ b/sdk/api/handlers/handlers_stream.go @@ -283,6 +283,8 @@ func (h *BaseAPIHandler) executeStreamWithAuthManager(ctx context.Context, handl func (h *BaseAPIHandler) executeStreamWithAuthManagerFormats(ctx context.Context, entryProtocol, exitProtocol, modelName string, rawJSON []byte, alt string, allowImageModel bool, execOptions modelExecutionOptions) (<-chan []byte, http.Header, <-chan *interfaces.ErrorMessage) { originalRequestedModel := modelName + // Speech-only models are reachable solely through the speech entry protocol. + execOptions.AllowSpeechModel = isModelExecutionSpeechProtocol(entryProtocol) routeDecision, preparedRoute := preparedModelRouteFromContext(ctx, execOptions.SkipRouterPluginID) if !preparedRoute { routeDecision = h.applyModelRouter(ctx, entryProtocol, modelName, rawJSON, true, execOptions) diff --git a/sdk/api/handlers/model_execution.go b/sdk/api/handlers/model_execution.go index 3c690550724..3a24476cca4 100644 --- a/sdk/api/handlers/model_execution.go +++ b/sdk/api/handlers/model_execution.go @@ -27,6 +27,7 @@ type modelExecutionOptions struct { AuthSelectionModel string ProxyURL string Path string + AllowSpeechModel bool } // ProtocolExecutionRequest describes a route-level model execution request with explicit protocols. @@ -230,6 +231,10 @@ func isModelExecutionImageProtocol(protocol string) bool { return strings.EqualFold(strings.TrimSpace(protocol), "openai-image") } +func isModelExecutionSpeechProtocol(protocol string) bool { + return strings.EqualFold(strings.TrimSpace(protocol), "openai-speech") +} + func validateModelExecutionProxy(raw string) *interfaces.ErrorMessage { raw = strings.TrimSpace(raw) if raw == "" { diff --git a/sdk/api/handlers/openai/openai_speech_routing_test.go b/sdk/api/handlers/openai/openai_speech_routing_test.go new file mode 100644 index 00000000000..f0d5f3417e4 --- /dev/null +++ b/sdk/api/handlers/openai/openai_speech_routing_test.go @@ -0,0 +1,167 @@ +package openai + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/gin-gonic/gin" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + apihandlers "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers" + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + coreexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdkconfig "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" +) + +type speechCaptureExecutor struct { + mu sync.Mutex + models []string + sources []string +} + +func (e *speechCaptureExecutor) Identifier() string { return "xai" } + +func (e *speechCaptureExecutor) Execute(_ context.Context, _ *coreauth.Auth, req coreexecutor.Request, opts coreexecutor.Options) (coreexecutor.Response, error) { + e.mu.Lock() + e.models = append(e.models, req.Model) + e.sources = append(e.sources, opts.SourceFormat.String()) + e.mu.Unlock() + return coreexecutor.Response{Payload: []byte("ID3audio"), Headers: http.Header{"Content-Type": []string{"audio/mpeg"}}}, nil +} + +func (e *speechCaptureExecutor) ExecuteStream(context.Context, *coreauth.Auth, coreexecutor.Request, coreexecutor.Options) (*coreexecutor.StreamResult, error) { + e.mu.Lock() + e.models = append(e.models, "stream") + e.mu.Unlock() + return nil, &coreauth.Error{Code: "not_implemented", Message: "ExecuteStream not implemented"} +} + +func (e *speechCaptureExecutor) Refresh(_ context.Context, auth *coreauth.Auth) (*coreauth.Auth, error) { + return auth, nil +} + +func (e *speechCaptureExecutor) CountTokens(context.Context, *coreauth.Auth, coreexecutor.Request, coreexecutor.Options) (coreexecutor.Response, error) { + return coreexecutor.Response{}, &coreauth.Error{Code: "not_implemented", Message: "CountTokens not implemented"} +} + +func (e *speechCaptureExecutor) HttpRequest(context.Context, *coreauth.Auth, *http.Request) (*http.Response, error) { + return nil, &coreauth.Error{Code: "not_implemented", Message: "HttpRequest not implemented"} +} + +func (e *speechCaptureExecutor) calls() (models, sources []string) { + e.mu.Lock() + defer e.mu.Unlock() + return append([]string(nil), e.models...), append([]string(nil), e.sources...) +} + +func newSpeechRoutingTestHandlers(t *testing.T, executor *speechCaptureExecutor) (*OpenAIAPIHandler, *OpenAIResponsesAPIHandler) { + t.Helper() + + manager := coreauth.NewManager(nil, &coreauth.RoundRobinSelector{}, nil) + manager.RegisterExecutor(executor) + auth := &coreauth.Auth{ID: "speech-routing-auth", Provider: "xai", Status: coreauth.StatusActive} + if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil { + t.Fatalf("manager.Register: %v", errRegister) + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, auth.Provider, []*registry.ModelInfo{{ID: defaultXAISpeechModel}, {ID: xaiSpeechVoiceModel}}) + manager.RefreshSchedulerEntry(auth.ID) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(auth.ID) + }) + + base := apihandlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, manager) + return NewOpenAIAPIHandler(base), NewOpenAIResponsesAPIHandler(base) +} + +func performSpeechRoutingRequest(t *testing.T, path string, body string, handler gin.HandlerFunc) *httptest.ResponseRecorder { + t.Helper() + + gin.SetMode(gin.TestMode) + router := gin.New() + router.POST(path, handler) + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + resp := httptest.NewRecorder() + router.ServeHTTP(resp, req) + return resp +} + +func TestSpeechEndpointsRouteSpeechOnlyModelsToExecutor(t *testing.T) { + executor := &speechCaptureExecutor{} + handler, _ := newSpeechRoutingTestHandlers(t, executor) + + cases := []struct { + name string + path string + handler gin.HandlerFunc + body string + wantModel string + }{ + {name: "audio speech default model", path: "/v1/audio/speech", handler: handler.AudioSpeech, body: `{"model":"tts-1","input":"hello","voice":"nova"}`, wantModel: defaultXAISpeechModel}, + {name: "audio speech grok-tts", path: "/v1/audio/speech", handler: handler.AudioSpeech, body: `{"model":"xai/grok-tts","input":"hello"}`, wantModel: defaultXAISpeechModel}, + {name: "audio speech voice model", path: "/v1/audio/speech", handler: handler.AudioSpeech, body: `{"model":"grok-voice-tts-1.0","input":"hello"}`, wantModel: xaiSpeechVoiceModel}, + {name: "native tts", path: "/v1/tts", handler: handler.XAITTS, body: `{"text":"hello","voice_id":"eve"}`, wantModel: defaultXAISpeechModel}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + before, _ := executor.calls() + resp := performSpeechRoutingRequest(t, tc.path, tc.body, tc.handler) + if resp.Code != http.StatusOK { + t.Fatalf("status = %d, want %d: %s", resp.Code, http.StatusOK, resp.Body.String()) + } + if resp.Body.String() != "ID3audio" { + t.Fatalf("body = %q", resp.Body.String()) + } + models, sources := executor.calls() + if len(models) != len(before)+1 { + t.Fatalf("executor calls = %v, want one new call", models) + } + if got := models[len(models)-1]; got != tc.wantModel { + t.Fatalf("executor model = %q, want %q", got, tc.wantModel) + } + if got := sources[len(sources)-1]; got != xaiSpeechHandlerType { + t.Fatalf("executor source format = %q, want %q", got, xaiSpeechHandlerType) + } + }) + } +} + +func TestChatAndResponsesRejectSpeechOnlyModels(t *testing.T) { + executor := &speechCaptureExecutor{} + chat, responses := newSpeechRoutingTestHandlers(t, executor) + + for _, model := range []string{"grok-tts", "xai/grok-tts", "grok-voice-tts-1.0"} { + t.Run(model, func(t *testing.T) { + chatBody := `{"model":"` + model + `","messages":[{"role":"user","content":"hi"}]}` + chatStreamBody := `{"model":"` + model + `","stream":true,"messages":[{"role":"user","content":"hi"}]}` + responsesBody := `{"model":"` + model + `","input":"hi"}` + responsesStreamBody := `{"model":"` + model + `","stream":true,"input":"hi"}` + requests := []struct { + name string + path string + body string + handler gin.HandlerFunc + }{ + {name: "chat", path: "/v1/chat/completions", body: chatBody, handler: chat.ChatCompletions}, + {name: "chat stream", path: "/v1/chat/completions", body: chatStreamBody, handler: chat.ChatCompletions}, + {name: "responses", path: "/v1/responses", body: responsesBody, handler: responses.Responses}, + {name: "responses stream", path: "/v1/responses", body: responsesStreamBody, handler: responses.Responses}, + } + for _, request := range requests { + resp := performSpeechRoutingRequest(t, request.path, request.body, request.handler) + if resp.Code < 400 || resp.Code >= 500 { + t.Fatalf("%s status = %d, want 4xx: %s", request.name, resp.Code, resp.Body.String()) + } + if !strings.Contains(resp.Body.String(), "/v1/audio/speech") { + t.Fatalf("%s body = %s, want speech endpoint hint", request.name, resp.Body.String()) + } + } + if models, _ := executor.calls(); len(models) != 0 { + t.Fatalf("executor received speech-only model on chat route: %v", models) + } + }) + } +} From 3b69068e6c8c028c56b7d0d0467a61d8c66e103c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=8B=E1=85=B5=E1=84=83=E1=85=A2=E1=84=92=E1=85=B4?= Date: Wed, 7 Oct 2026 19:21:32 +0900 Subject: [PATCH 080/142] fix(translator): stop dropping attachments and empty turns An attachment a translator could not represent was dropped without a word, and a turn whose only content was that attachment went upstream as an empty messages, parts, or input array. The model then answered as if nothing was attached, or the upstream rejected a request that never named the attachment. A base64 document now reaches OpenAI as a file part. A file the target cannot receive, such as container_upload, an OpenAI file_id, or input_audio sent to Claude, is reported by name so the route answers 400 instead of forwarding an empty turn. Text beside it still travels. One rule, ErrIfNothingLeft, decides when to refuse, and RegisterCheckedRequest carries the refusal on the request envelope. Every executor that translates checks it before calling upstream. The exported converters keep their []byte signature, so no caller or sibling test had to change. --- internal/pluginhost/adapters_executors.go | 11 ++- .../runtime/executor/aistudio_executor.go | 7 +- .../executor/claude_executor_execute.go | 5 +- .../executor/claude_executor_stream.go | 5 +- .../executor/claude_executor_tokens.go | 10 ++- .../executor/codex_executor_execute.go | 10 ++- .../executor/codex_executor_request.go | 21 ++--- .../runtime/executor/codex_executor_stream.go | 5 +- .../runtime/executor/codex_executor_tokens.go | 9 +- .../executor/codex_websockets_execute.go | 5 +- .../executor/codex_websockets_stream.go | 5 +- internal/runtime/executor/devin_executor.go | 11 ++- internal/runtime/executor/gemini_executor.go | 47 +++++++---- .../gemini_interactions_translate_test.go | 26 +++--- .../executor/gemini_vertex_executor.go | 34 ++++++-- .../executor/helps/codex_multi_agent_v2.go | 71 +++++++++++----- .../helps/codex_multi_agent_v2_test.go | 4 +- .../helps/configuration_update_plugin_test.go | 2 +- .../executor/helps/unsupported_part_test.go | 46 +++++++++++ internal/runtime/executor/kimi_executor.go | 10 ++- .../runtime/executor/meta_executor_execute.go | 5 +- .../executor/openai_compat_executor.go | 19 +++-- .../unsupported_part_executor_test.go | 82 +++++++++++++++++++ .../runtime/executor/xai_executor_request.go | 6 +- .../claude_openai_file_test.go | 54 ++++++++++++ .../chat-completions/claude_openai_request.go | 23 ++++-- .../claude/openai/chat-completions/init.go | 6 +- .../codex/claude/codex_claude_request.go | 55 +++++++++---- internal/translator/codex/claude/init.go | 6 +- internal/translator/common/parts.go | 31 +++++++ .../gemini/claude/gemini_claude_request.go | 49 +++++++---- .../claude/gemini_claude_request_test.go | 56 +++++++++++++ internal/translator/gemini/claude/init.go | 6 +- .../gemini_openai_file_id_test.go | 47 +++++++++++ .../chat-completions/gemini_openai_request.go | 13 ++- .../gemini/openai/chat-completions/init.go | 4 +- .../translator/interactions/claude/init.go | 6 +- .../claude/interactions_claude_request.go | 32 +++++--- internal/translator/openai/claude/init.go | 6 +- .../openai/claude/openai_claude_request.go | 50 ++++++++++- .../claude/openai_claude_request_test.go | 56 +++++++++++++ .../handlers/handlers_error_response_test.go | 12 +++ sdk/translator/pipeline.go | 2 + sdk/translator/registry.go | 9 ++ 44 files changed, 822 insertions(+), 157 deletions(-) create mode 100644 internal/runtime/executor/helps/unsupported_part_test.go create mode 100644 internal/runtime/executor/unsupported_part_executor_test.go create mode 100644 internal/translator/claude/openai/chat-completions/claude_openai_file_test.go create mode 100644 internal/translator/common/parts.go create mode 100644 internal/translator/gemini/openai/chat-completions/gemini_openai_file_id_test.go diff --git a/internal/pluginhost/adapters_executors.go b/internal/pluginhost/adapters_executors.go index a83f638e92d..f4d261dfa06 100644 --- a/internal/pluginhost/adapters_executors.go +++ b/internal/pluginhost/adapters_executors.go @@ -411,7 +411,16 @@ func (a *executorAdapter) prepareExecutorCall(req coreexecutor.Request, opts cor nativeReq := req nativeOpts := opts if inputRequested != "" && inputRequested != inputFormat { - nativeReq.Payload = sdktranslator.TranslateRequest(inputRequested, inputFormat, req.Model, req.Payload, opts.Stream) + translated := sdktranslator.TranslateRequestEnvelope(context.Background(), inputRequested, inputFormat, sdktranslator.RequestEnvelope{ + Format: inputRequested, + Model: req.Model, + Stream: opts.Stream, + Body: req.Payload, + }) + if translated.Err != nil { + return preparedExecutorCall{}, translated.Err + } + nativeReq.Payload = translated.Body } nativeReq.Format = outputFormat nativeOpts.SourceFormat = inputFormat diff --git a/internal/runtime/executor/aistudio_executor.go b/internal/runtime/executor/aistudio_executor.go index 8efc1920c16..182bc8f22d3 100644 --- a/internal/runtime/executor/aistudio_executor.go +++ b/internal/runtime/executor/aistudio_executor.go @@ -530,8 +530,11 @@ func (e *AIStudioExecutor) translateRequest(ctx context.Context, req cliproxyexe } originalPayload := originalPayloadSource originalTranslated := helps.TranslateRequestWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, baseModel, originalPayload, stream) - payload := helps.TranslateRequestWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, stream) - payload, err := helps.ApplyThinkingWithSourcePayload(payload, req.Payload, originalPayloadSource, req.Model, from.String(), to.String(), e.Identifier()) + payload, err := helps.TranslateRequestReturningError(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, stream, false) + if err != nil { + return nil, translatedPayload{}, err + } + payload, err = helps.ApplyThinkingWithSourcePayload(payload, req.Payload, originalPayloadSource, req.Model, from.String(), to.String(), e.Identifier()) if err != nil { return nil, translatedPayload{}, err } diff --git a/internal/runtime/executor/claude_executor_execute.go b/internal/runtime/executor/claude_executor_execute.go index db3fc46ba48..0e5b6f31dc7 100644 --- a/internal/runtime/executor/claude_executor_execute.go +++ b/internal/runtime/executor/claude_executor_execute.go @@ -76,7 +76,10 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r } isCompat := helps.APIKeyModelIsCompat(req) - originalTranslated, body := helps.TranslateRequestPairWithAPIKeyModelCompatibility(ctx, opts.Headers, e.cfg, from, to, baseModel, originalPayload, req.Payload, upstreamStream, isCompat) + originalTranslated, body, err := helps.TranslateRequestPairReturningError(ctx, opts.Headers, e.cfg, from, to, baseModel, originalPayload, req.Payload, upstreamStream, isCompat) + if err != nil { + return resp, err + } body = helps.SetStringIfDifferent(body, "model", upstreamModel) body, err = helps.ApplyRequestThinking(body, req, opts, from.String(), to.String(), e.Identifier()) diff --git a/internal/runtime/executor/claude_executor_stream.go b/internal/runtime/executor/claude_executor_stream.go index aa22c4f0862..436536f44cd 100644 --- a/internal/runtime/executor/claude_executor_stream.go +++ b/internal/runtime/executor/claude_executor_stream.go @@ -79,7 +79,10 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A } isCompat := helps.APIKeyModelIsCompat(req) - originalTranslated, body := helps.TranslateRequestPairWithAPIKeyModelCompatibility(ctx, opts.Headers, e.cfg, from, to, baseModel, originalPayload, req.Payload, true, isCompat) + originalTranslated, body, err := helps.TranslateRequestPairReturningError(ctx, opts.Headers, e.cfg, from, to, baseModel, originalPayload, req.Payload, true, isCompat) + if err != nil { + return nil, err + } body = helps.SetStringIfDifferent(body, "model", upstreamModel) body, err = helps.ApplyRequestThinking(body, req, opts, from.String(), to.String(), e.Identifier()) diff --git a/internal/runtime/executor/claude_executor_tokens.go b/internal/runtime/executor/claude_executor_tokens.go index 6e3ecdae61f..41e52ccefdf 100644 --- a/internal/runtime/executor/claude_executor_tokens.go +++ b/internal/runtime/executor/claude_executor_tokens.go @@ -38,7 +38,10 @@ func (e *ClaudeExecutor) CountTokens(ctx context.Context, auth *cliproxyauth.Aut // Use streaming translation to preserve function calling, except for claude. stream := from != to - body := helps.TranslateRequestWithAPIKeyModelCompatibility(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, stream, helps.APIKeyModelIsCompat(req)) + body, err := helps.TranslateRequestReturningError(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, stream, helps.APIKeyModelIsCompat(req)) + if err != nil { + return cliproxyexecutor.Response{}, err + } originalTranslatedForPayload := append([]byte(nil), body...) if len(opts.OriginalRequest) > 0 { originalTranslatedForPayload = helps.TranslateRequestWithAPIKeyModelCompatibility(ctx, opts.Headers, e.cfg, from, to, baseModel, opts.OriginalRequest, stream, helps.APIKeyModelIsCompat(req)) @@ -149,7 +152,10 @@ func (e *ClaudeExecutor) countTokensUpstream(ctx context.Context, auth *cliproxy } // Use streaming translation to preserve function calling, except for claude. stream := from != to - body := helps.TranslateRequestWithAPIKeyModelCompatibility(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, stream, helps.APIKeyModelIsCompat(req)) + body, err := helps.TranslateRequestReturningError(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, stream, helps.APIKeyModelIsCompat(req)) + if err != nil { + return cliproxyexecutor.Response{}, err + } originalTranslatedForPayload := append([]byte(nil), body...) if len(opts.OriginalRequest) > 0 { originalTranslatedForPayload = helps.TranslateRequestWithAPIKeyModelCompatibility(ctx, opts.Headers, e.cfg, from, to, baseModel, opts.OriginalRequest, stream, helps.APIKeyModelIsCompat(req)) diff --git a/internal/runtime/executor/codex_executor_execute.go b/internal/runtime/executor/codex_executor_execute.go index 60bc8bb638b..f5afac2f64f 100644 --- a/internal/runtime/executor/codex_executor_execute.go +++ b/internal/runtime/executor/codex_executor_execute.go @@ -45,7 +45,10 @@ func (e *CodexExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, re } originalPayload := originalPayloadSource isCompat := e.resolveCodexModelIsCompat(auth, req, baseModel) - originalTranslated, body, updatesChanged := translateCodexRequestPairWithUpdateIntent(from, to, baseModel, originalPayload, req.Payload, false, isCompat) + originalTranslated, body, updatesChanged, err := translateCodexRequestPairWithUpdateIntent(from, to, baseModel, originalPayload, req.Payload, false, isCompat) + if err != nil { + return resp, err + } body, err = helps.ApplyRequestThinking(body, req, opts, from.String(), to.String(), e.Identifier(), updatesChanged) if err != nil { @@ -226,7 +229,10 @@ func (e *CodexExecutor) executeCompact(ctx context.Context, auth *cliproxyauth.A } originalPayload := originalPayloadSource isCompat := e.resolveCodexModelIsCompat(auth, req, baseModel) - originalTranslated, body, updatesChanged := translateCodexRequestPairWithUpdateIntent(from, to, baseModel, originalPayload, req.Payload, false, isCompat) + originalTranslated, body, updatesChanged, err := translateCodexRequestPairWithUpdateIntent(from, to, baseModel, originalPayload, req.Payload, false, isCompat) + if err != nil { + return resp, err + } body, err = helps.ApplyRequestThinking(body, req, opts, from.String(), to.String(), e.Identifier(), updatesChanged) if err != nil { diff --git a/internal/runtime/executor/codex_executor_request.go b/internal/runtime/executor/codex_executor_request.go index af8790c2f54..cc6661acf8d 100644 --- a/internal/runtime/executor/codex_executor_request.go +++ b/internal/runtime/executor/codex_executor_request.go @@ -33,27 +33,28 @@ const ( var dataTag = []byte("data:") func translateCodexRequestPair(from, to sdktranslator.Format, model string, originalPayload, payload []byte, stream bool, preserveEmptyThinkingBlocks ...bool) ([]byte, []byte) { - original, body, _ := translateCodexRequestPairWithUpdateIntent(from, to, model, originalPayload, payload, stream, preserveEmptyThinkingBlocks...) + original, body, _, _ := translateCodexRequestPairWithUpdateIntent(from, to, model, originalPayload, payload, stream, preserveEmptyThinkingBlocks...) return original, body } -func translateCodexRequestPairWithUpdateIntent(from, to sdktranslator.Format, model string, originalPayload, payload []byte, stream bool, preserveEmptyThinkingBlocks ...bool) ([]byte, []byte, bool) { +func translateCodexRequestPairWithUpdateIntent(from, to sdktranslator.Format, model string, originalPayload, payload []byte, stream bool, preserveEmptyThinkingBlocks ...bool) ([]byte, []byte, bool, error) { isCompat := len(preserveEmptyThinkingBlocks) > 0 && preserveEmptyThinkingBlocks[0] ctx := context.Background() - translate := func(raw []byte) ([]byte, bool) { + translate := func(raw []byte) ([]byte, bool, error) { if isCompat && from == sdktranslator.FormatClaude && to == sdktranslator.FormatCodex { - return helps.TranslateRequestWithAPIKeyModelCompatibility(ctx, nil, nil, from, to, model, raw, stream, true), false + body, err := helps.TranslateRequestReturningError(ctx, nil, nil, from, to, model, raw, stream, true) + return body, false, err } translated := sdktranslator.TranslateRequestEnvelope(ctx, from, to, sdktranslator.RequestEnvelope{Format: from, Model: model, Stream: stream, Body: raw}) - return translated.Body, translated.ConfigurationUpdatesChanged + return translated.Body, translated.ConfigurationUpdatesChanged, translated.Err } if bytes.Equal(originalPayload, payload) { - body, changed := translate(payload) - return body, body, changed + body, changed, err := translate(payload) + return body, body, changed, err } - originalTranslated, _ := translate(originalPayload) - body, changed := translate(payload) - return originalTranslated, body, changed + originalTranslated, _, _ := translate(originalPayload) + body, changed, err := translate(payload) + return originalTranslated, body, changed, err } // PrepareRequest injects Codex credentials into the outgoing HTTP request. diff --git a/internal/runtime/executor/codex_executor_stream.go b/internal/runtime/executor/codex_executor_stream.go index fa0f07303e8..7c9fef29cdc 100644 --- a/internal/runtime/executor/codex_executor_stream.go +++ b/internal/runtime/executor/codex_executor_stream.go @@ -50,7 +50,10 @@ func (e *CodexExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Au } originalPayload := originalPayloadSource isCompat := e.resolveCodexModelIsCompat(auth, req, baseModel) - originalTranslated, body, updatesChanged := translateCodexRequestPairWithUpdateIntent(from, to, baseModel, originalPayload, req.Payload, true, isCompat) + originalTranslated, body, updatesChanged, err := translateCodexRequestPairWithUpdateIntent(from, to, baseModel, originalPayload, req.Payload, true, isCompat) + if err != nil { + return nil, err + } body, err = helps.ApplyRequestThinking(body, req, opts, from.String(), to.String(), e.Identifier(), updatesChanged) if err != nil { diff --git a/internal/runtime/executor/codex_executor_tokens.go b/internal/runtime/executor/codex_executor_tokens.go index 50e7f1583b9..5d8f70be68b 100644 --- a/internal/runtime/executor/codex_executor_tokens.go +++ b/internal/runtime/executor/codex_executor_tokens.go @@ -21,13 +21,16 @@ func (e *CodexExecutor) CountTokens(ctx context.Context, auth *cliproxyauth.Auth from := opts.SourceFormat responseFormat := cliproxyexecutor.ResponseFormatOrSource(opts) to := sdktranslator.FromString("codex") - body, updatesChanged := helps.TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntentForExecutor(ctx, opts.Headers, e.cfg, e.Identifier(), from, to, baseModel, req.Payload, false, helps.APIKeyModelIsCompat(req)) + body, updatesChanged, err := helps.TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntentForExecutor(ctx, opts.Headers, e.cfg, e.Identifier(), from, to, baseModel, req.Payload, false, helps.APIKeyModelIsCompat(req)) + if err != nil { + return cliproxyexecutor.Response{}, err + } originalTranslatedForPayload := append([]byte(nil), body...) if len(opts.OriginalRequest) > 0 { - originalTranslatedForPayload, _ = helps.TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntentForExecutor(ctx, opts.Headers, e.cfg, e.Identifier(), from, to, baseModel, opts.OriginalRequest, false, helps.APIKeyModelIsCompat(req)) + originalTranslatedForPayload, _, _ = helps.TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntentForExecutor(ctx, opts.Headers, e.cfg, e.Identifier(), from, to, baseModel, opts.OriginalRequest, false, helps.APIKeyModelIsCompat(req)) } - body, err := helps.ApplyRequestThinking(body, req, opts, from.String(), to.String(), e.Identifier(), updatesChanged) + body, err = helps.ApplyRequestThinking(body, req, opts, from.String(), to.String(), e.Identifier(), updatesChanged) if err != nil { return cliproxyexecutor.Response{}, err } diff --git a/internal/runtime/executor/codex_websockets_execute.go b/internal/runtime/executor/codex_websockets_execute.go index 9b47dab12f7..6b6e1934b94 100644 --- a/internal/runtime/executor/codex_websockets_execute.go +++ b/internal/runtime/executor/codex_websockets_execute.go @@ -45,7 +45,10 @@ func (e *CodexWebsocketsExecutor) Execute(ctx context.Context, auth *cliproxyaut } originalPayload := originalPayloadSource isCompat := e.resolveCodexModelIsCompat(auth, req, baseModel) - originalTranslated, body, updatesChanged := translateCodexRequestPairWithUpdateIntent(from, to, baseModel, originalPayload, req.Payload, false, isCompat) + originalTranslated, body, updatesChanged, err := translateCodexRequestPairWithUpdateIntent(from, to, baseModel, originalPayload, req.Payload, false, isCompat) + if err != nil { + return resp, err + } body, err = helps.ApplyRequestThinking(body, req, opts, from.String(), to.String(), e.Identifier(), updatesChanged) if err != nil { diff --git a/internal/runtime/executor/codex_websockets_stream.go b/internal/runtime/executor/codex_websockets_stream.go index 406bfacde14..3c924248ca0 100644 --- a/internal/runtime/executor/codex_websockets_stream.go +++ b/internal/runtime/executor/codex_websockets_stream.go @@ -767,7 +767,10 @@ func (e *CodexWebsocketsExecutor) prepareCodexWebsocketStream(ctx context.Contex } originalPayload := originalPayloadSource isCompat := e.resolveCodexModelIsCompat(auth, req, baseModel) - originalTranslated, body, updatesChanged := translateCodexRequestPairWithUpdateIntent(from, to, baseModel, originalPayload, req.Payload, true, isCompat) + originalTranslated, body, updatesChanged, err := translateCodexRequestPairWithUpdateIntent(from, to, baseModel, originalPayload, req.Payload, true, isCompat) + if err != nil { + return nil, err + } body, err = helps.ApplyRequestThinking(body, req, opts, from.String(), to.String(), e.Identifier(), updatesChanged) if err != nil { diff --git a/internal/runtime/executor/devin_executor.go b/internal/runtime/executor/devin_executor.go index 17092f352f7..55801e66885 100644 --- a/internal/runtime/executor/devin_executor.go +++ b/internal/runtime/executor/devin_executor.go @@ -396,7 +396,16 @@ func (e *DevinExecutor) prepareDevinHTTPRequest(ctx context.Context, auth *clipr payload := req.Payload isInteractionsSource := opts.SourceFormat == "" || opts.SourceFormat == sdktranslator.FormatInteractions if !isInteractionsSource { - payload = sdktranslator.TranslateRequest(opts.SourceFormat, sdktranslator.FormatInteractions, req.Model, payload, opts.Stream) + translated := sdktranslator.TranslateRequestEnvelope(ctx, opts.SourceFormat, sdktranslator.FormatInteractions, sdktranslator.RequestEnvelope{ + Format: opts.SourceFormat, + Model: req.Model, + Stream: opts.Stream, + Body: payload, + }) + if translated.Err != nil { + return nil, "", nil, translated.Err + } + payload = translated.Body } systemPrompt, prompts, tools, temp, maxTokens, sessionID, cascadeID, thinkingLevel, budgetTokens := parseInteractionsPayload(payload, opts.OriginalRequest) sessionID, cascadeID = resolveDevinSessionAndCascadeIDs(ctx, sessionID, cascadeID, opts) diff --git a/internal/runtime/executor/gemini_executor.go b/internal/runtime/executor/gemini_executor.go index 96c9b473a7f..95b74cef1fc 100644 --- a/internal/runtime/executor/gemini_executor.go +++ b/internal/runtime/executor/gemini_executor.go @@ -151,7 +151,10 @@ func (e *GeminiExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r } originalPayload := originalPayloadSource isCompat := helps.APIKeyModelIsCompat(req) - originalTranslated, body := helps.TranslateRequestPairWithAPIKeyModelCompatibility(ctx, opts.Headers, e.cfg, from, to, baseModel, originalPayload, req.Payload, false, isCompat) + originalTranslated, body, err := helps.TranslateRequestPairReturningError(ctx, opts.Headers, e.cfg, from, to, baseModel, originalPayload, req.Payload, false, isCompat) + if err != nil { + return resp, err + } body, err = helps.ApplyRequestThinking(body, req, opts, from.String(), to.String(), e.Identifier()) if err != nil { @@ -277,7 +280,10 @@ func (e *GeminiExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A } originalPayload := originalPayloadSource isCompat := helps.APIKeyModelIsCompat(req) - originalTranslated, body := helps.TranslateRequestPairWithAPIKeyModelCompatibility(ctx, opts.Headers, e.cfg, from, to, baseModel, originalPayload, req.Payload, true, isCompat) + originalTranslated, body, err := helps.TranslateRequestPairReturningError(ctx, opts.Headers, e.cfg, from, to, baseModel, originalPayload, req.Payload, true, isCompat) + if err != nil { + return nil, err + } body, err = helps.ApplyRequestThinking(body, req, opts, from.String(), to.String(), e.Identifier()) if err != nil { @@ -428,7 +434,10 @@ func (e *GeminiExecutor) executeInteractions(ctx context.Context, auth *cliproxy defer reporter.TrackFailure(ctx, &err) isCompat := helps.APIKeyModelIsCompat(req) - originalTranslated, body := translateGeminiInteractionsRequestPair(ctx, e.cfg, targetName, req.Payload, opts, false, isCompat) + originalTranslated, body, err := translateGeminiInteractionsRequestPair(ctx, e.cfg, targetName, req.Payload, opts, false, isCompat) + if err != nil { + return resp, err + } if gjson.GetBytes(body, "model").Exists() && targetName != "" { body = helps.SetStringIfDifferent(body, "model", targetName) } @@ -515,7 +524,10 @@ func (e *GeminiExecutor) executeInteractionsStream(ctx context.Context, auth *cl defer reporter.TrackFailure(ctx, &err) isCompat := helps.APIKeyModelIsCompat(req) - originalTranslated, body := translateGeminiInteractionsRequestPair(ctx, e.cfg, targetName, req.Payload, opts, true, isCompat) + originalTranslated, body, err := translateGeminiInteractionsRequestPair(ctx, e.cfg, targetName, req.Payload, opts, true, isCompat) + if err != nil { + return nil, err + } if gjson.GetBytes(body, "model").Exists() && targetName != "" { body = helps.SetStringIfDifferent(body, "model", targetName) } @@ -685,13 +697,16 @@ func (e *GeminiExecutor) CountTokens(ctx context.Context, auth *cliproxyauth.Aut from := opts.SourceFormat responseFormat := cliproxyexecutor.ResponseFormatOrSource(opts) to := sdktranslator.FromString("gemini") - translatedReq := helps.TranslateRequestWithAPIKeyModelCompatibility(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, false, helps.APIKeyModelIsCompat(req)) + translatedReq, err := helps.TranslateRequestReturningError(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, false, helps.APIKeyModelIsCompat(req)) + if err != nil { + return cliproxyexecutor.Response{}, err + } originalTranslatedForPayload := append([]byte(nil), translatedReq...) if len(opts.OriginalRequest) > 0 { originalTranslatedForPayload = helps.TranslateRequestWithAPIKeyModelCompatibility(ctx, opts.Headers, e.cfg, from, to, baseModel, opts.OriginalRequest, false, helps.APIKeyModelIsCompat(req)) } - translatedReq, err := helps.ApplyRequestThinking(translatedReq, req, opts, from.String(), to.String(), e.Identifier()) + translatedReq, err = helps.ApplyRequestThinking(translatedReq, req, opts, from.String(), to.String(), e.Identifier()) if err != nil { return cliproxyexecutor.Response{}, err } @@ -890,11 +905,11 @@ func sanitizeGeminiInteractionsUnsupportedInputIDs(body []byte) []byte { return body } -func translateGeminiInteractionsRequestBody(ctx context.Context, cfg *config.Config, model string, payload []byte, opts cliproxyexecutor.Options, stream, isCompat bool) []byte { +func translateGeminiInteractionsRequestBody(ctx context.Context, cfg *config.Config, model string, payload []byte, opts cliproxyexecutor.Options, stream, isCompat bool) ([]byte, error) { if opts.SourceFormat == "" || opts.SourceFormat == sdktranslator.FormatInteractions { - return bytes.Clone(payload) + return bytes.Clone(payload), nil } - return helps.TranslateRequestWithAPIKeyModelCompatibility(ctx, opts.Headers, cfg, opts.SourceFormat, sdktranslator.FormatInteractions, model, payload, stream, isCompat) + return helps.TranslateRequestReturningError(ctx, opts.Headers, cfg, opts.SourceFormat, sdktranslator.FormatInteractions, model, payload, stream, isCompat) } // translateGeminiInteractionsRequestPair translates the working payload and the @@ -903,18 +918,18 @@ func translateGeminiInteractionsRequestBody(ctx context.Context, cfg *config.Con // working buffer is a separate copy so those mutations cannot change it. Distinct // inputs keep the existing order: working payload first, then the payload-config // source. -func translateGeminiInteractionsRequestPair(ctx context.Context, cfg *config.Config, model string, payload []byte, opts cliproxyexecutor.Options, stream, isCompat bool) (original, working []byte) { +func translateGeminiInteractionsRequestPair(ctx context.Context, cfg *config.Config, model string, payload []byte, opts cliproxyexecutor.Options, stream, isCompat bool) (original, working []byte, err error) { source := geminiInteractionsPayloadConfigInput(opts, payload) if geminiInteractionsSameByteSlice(payload, source) { - original = translateGeminiInteractionsRequestBody(ctx, cfg, model, payload, opts, stream, isCompat) - return original, bytes.Clone(original) + original, err = translateGeminiInteractionsRequestBody(ctx, cfg, model, payload, opts, stream, isCompat) + return original, bytes.Clone(original), err } - working = translateGeminiInteractionsRequestBody(ctx, cfg, model, payload, opts, stream, isCompat) - original = geminiInteractionsPayloadConfigSource(ctx, cfg, model, payload, opts, stream, isCompat) - return original, working + working, err = translateGeminiInteractionsRequestBody(ctx, cfg, model, payload, opts, stream, isCompat) + original, _ = geminiInteractionsPayloadConfigSource(ctx, cfg, model, payload, opts, stream, isCompat) + return original, working, err } -func geminiInteractionsPayloadConfigSource(ctx context.Context, cfg *config.Config, model string, payload []byte, opts cliproxyexecutor.Options, stream, isCompat bool) []byte { +func geminiInteractionsPayloadConfigSource(ctx context.Context, cfg *config.Config, model string, payload []byte, opts cliproxyexecutor.Options, stream, isCompat bool) ([]byte, error) { return translateGeminiInteractionsRequestBody(ctx, cfg, model, geminiInteractionsPayloadConfigInput(opts, payload), opts, stream, isCompat) } diff --git a/internal/runtime/executor/gemini_interactions_translate_test.go b/internal/runtime/executor/gemini_interactions_translate_test.go index 7e6e45cde6b..2b4b7b091ca 100644 --- a/internal/runtime/executor/gemini_interactions_translate_test.go +++ b/internal/runtime/executor/gemini_interactions_translate_test.go @@ -56,8 +56,8 @@ func TestTranslateGeminiInteractionsRequestPairReusesSameSlice(t *testing.T) { for _, stream := range []bool{false, true} { for _, compat := range []bool{false, true} { opts := cliproxyexecutor.Options{SourceFormat: formats[i]} - base, work := translateGeminiInteractionsRequestPair(ctx, cfg, model, payload, opts, stream, compat) - want := translateGeminiInteractionsRequestBody(ctx, cfg, model, payload, opts, stream, compat) + base, work, _ := translateGeminiInteractionsRequestPair(ctx, cfg, model, payload, opts, stream, compat) + want, _ := translateGeminiInteractionsRequestBody(ctx, cfg, model, payload, opts, stream, compat) if !bytes.Equal(base, want) || !bytes.Equal(work, want) { t.Fatalf("format=%s stream=%v compat=%v: reused translation differs", formats[i], stream, compat) } @@ -100,7 +100,7 @@ func TestTranslateGeminiInteractionsRequestPairTranslatesSameSliceOnce(t *testin wantStream = stream calls = 0 opts := cliproxyexecutor.Options{SourceFormat: from} - base, work := translateGeminiInteractionsRequestPair(ctx, cfg, model, payload, opts, stream, compat) + base, work, _ := translateGeminiInteractionsRequestPair(ctx, cfg, model, payload, opts, stream, compat) if calls != 1 { t.Fatalf("stream=%v compat=%v: same slice translations = %d, want 1", stream, compat, calls) } @@ -111,7 +111,7 @@ func TestTranslateGeminiInteractionsRequestPairTranslatesSameSliceOnce(t *testin calls = 0 opts.OriginalRequest = payload - base, work = translateGeminiInteractionsRequestPair(ctx, cfg, model, payload, opts, stream, compat) + base, work, _ = translateGeminiInteractionsRequestPair(ctx, cfg, model, payload, opts, stream, compat) if calls != 1 { t.Fatalf("stream=%v compat=%v: identical backing translations = %d, want 1", stream, compat, calls) } @@ -120,7 +120,7 @@ func TestTranslateGeminiInteractionsRequestPairTranslatesSameSliceOnce(t *testin calls = 0 detached := bytes.Clone(payload) opts.OriginalRequest = detached - base, work = translateGeminiInteractionsRequestPair(ctx, cfg, model, payload, opts, stream, compat) + base, work, _ = translateGeminiInteractionsRequestPair(ctx, cfg, model, payload, opts, stream, compat) if calls != 2 { t.Fatalf("stream=%v compat=%v: equal content with a different backing array translations = %d, want 2", stream, compat, calls) } @@ -143,9 +143,9 @@ func TestTranslateGeminiInteractionsRequestPairTranslatesDistinctInputs(t *testi for _, original := range [][]byte{originalReq, detached} { opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatOpenAI, OriginalRequest: original} - base, work := translateGeminiInteractionsRequestPair(ctx, cfg, model, payload, opts, true, false) - wantWork := translateGeminiInteractionsRequestBody(ctx, cfg, model, payload, opts, true, false) - wantBase := geminiInteractionsPayloadConfigSource(ctx, cfg, model, payload, opts, true, false) + base, work, _ := translateGeminiInteractionsRequestPair(ctx, cfg, model, payload, opts, true, false) + wantWork, _ := translateGeminiInteractionsRequestBody(ctx, cfg, model, payload, opts, true, false) + wantBase, _ := geminiInteractionsPayloadConfigSource(ctx, cfg, model, payload, opts, true, false) if !bytes.Equal(work, wantWork) || !bytes.Equal(base, wantBase) { t.Fatal("distinct inputs did not keep separate translations") } @@ -166,7 +166,7 @@ func TestTranslateGeminiInteractionsRequestPairInvokesPluginOncePerInput(t *test for _, stream := range []bool{false, true} { for _, compat := range []bool{false, true} { hooks.calls = 0 - base, work := translateGeminiInteractionsRequestPair(ctx, cfg, model, payload, opts, stream, compat) + base, work, _ := translateGeminiInteractionsRequestPair(ctx, cfg, model, payload, opts, stream, compat) if hooks.calls != 1 { t.Fatalf("stream=%v compat=%v: plugin calls = %d, want 1", stream, compat, hooks.calls) } @@ -183,7 +183,7 @@ func TestTranslateGeminiInteractionsRequestPairInvokesPluginOncePerInput(t *test detached := bytes.Clone(payload) opts.OriginalRequest = detached before := hooks.calls - base, work := translateGeminiInteractionsRequestPair(ctx, cfg, model, payload, opts, true, false) + base, work, _ := translateGeminiInteractionsRequestPair(ctx, cfg, model, payload, opts, true, false) if hooks.calls != before+2 { t.Fatalf("distinct plugin hook calls = %d, want %d", hooks.calls-before, 2) } @@ -201,7 +201,7 @@ func TestTranslateGeminiInteractionsRequestPairNativeCopy(t *testing.T) { payload := []byte(`{"model":"gemini-3.1-flash-lite","input":"hi"}`) for _, format := range []sdktranslator.Format{"", sdktranslator.FormatInteractions} { opts := cliproxyexecutor.Options{SourceFormat: format} - base, work := translateGeminiInteractionsRequestPair(ctx, cfg, "gemini-3.1-flash-lite", payload, opts, false, false) + base, work, _ := translateGeminiInteractionsRequestPair(ctx, cfg, "gemini-3.1-flash-lite", payload, opts, false, false) if !bytes.Equal(base, payload) || !bytes.Equal(work, payload) { t.Fatalf("format=%q: native interactions payload was translated", format) } @@ -209,7 +209,7 @@ func TestTranslateGeminiInteractionsRequestPairNativeCopy(t *testing.T) { originalReq := []byte(`{"model":"gemini-3.1-flash-lite","input":"original"}`) opts.OriginalRequest = originalReq - base, work = translateGeminiInteractionsRequestPair(ctx, cfg, "gemini-3.1-flash-lite", payload, opts, true, true) + base, work, _ = translateGeminiInteractionsRequestPair(ctx, cfg, "gemini-3.1-flash-lite", payload, opts, true, true) if !bytes.Equal(work, payload) || !bytes.Equal(base, originalReq) { t.Fatalf("format=%q: distinct native inputs were not copied independently", format) } @@ -224,7 +224,7 @@ func TestTranslateGeminiInteractionsRequestPairNativeCopyIgnoresHooks(t *testing payload := []byte(`{"model":"gemini-3.1-flash-lite","input":"hi"}`) opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatInteractions, OriginalRequest: payload} - base, work := translateGeminiInteractionsRequestPair(context.Background(), &config.Config{}, "gemini-3.1-flash-lite", payload, opts, true, false) + base, work, _ := translateGeminiInteractionsRequestPair(context.Background(), &config.Config{}, "gemini-3.1-flash-lite", payload, opts, true, false) if hooks.calls != 0 { t.Fatalf("native copy invoked plugin hooks %d times", hooks.calls) } diff --git a/internal/runtime/executor/gemini_vertex_executor.go b/internal/runtime/executor/gemini_vertex_executor.go index a3d3996fd68..c8a932d4007 100644 --- a/internal/runtime/executor/gemini_vertex_executor.go +++ b/internal/runtime/executor/gemini_vertex_executor.go @@ -369,7 +369,10 @@ func (e *GeminiVertexExecutor) executeWithServiceAccount(ctx context.Context, au } originalPayload := originalPayloadSource originalTranslated = helps.TranslateRequestWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, baseModel, originalPayload, false) - body = helps.TranslateRequestWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, false) + body, err = helps.TranslateRequestReturningError(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, false, false) + if err != nil { + return resp, err + } body, err = helps.ApplyRequestThinking(body, req, opts, from.String(), to.String(), e.Identifier()) if err != nil { @@ -504,7 +507,10 @@ func (e *GeminiVertexExecutor) executeWithAPIKey(ctx context.Context, auth *clip } originalPayload := originalPayloadSource originalTranslated := helps.TranslateRequestWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, baseModel, originalPayload, false) - body := helps.TranslateRequestWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, false) + body, err := helps.TranslateRequestReturningError(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, false, false) + if err != nil { + return resp, err + } body, err = helps.ApplyRequestThinking(body, req, opts, from.String(), to.String(), e.Identifier()) if err != nil { @@ -631,7 +637,10 @@ func (e *GeminiVertexExecutor) executeStreamWithServiceAccount(ctx context.Conte } originalPayload := originalPayloadSource originalTranslated := helps.TranslateRequestWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, baseModel, originalPayload, true) - body := helps.TranslateRequestWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, true) + body, err := helps.TranslateRequestReturningError(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, true, false) + if err != nil { + return nil, err + } body, err = helps.ApplyRequestThinking(body, req, opts, from.String(), to.String(), e.Identifier()) if err != nil { @@ -806,7 +815,10 @@ func (e *GeminiVertexExecutor) executeStreamWithAPIKey(ctx context.Context, auth } originalPayload := originalPayloadSource originalTranslated := helps.TranslateRequestWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, baseModel, originalPayload, true) - body := helps.TranslateRequestWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, true) + body, err := helps.TranslateRequestReturningError(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, true, false) + if err != nil { + return nil, err + } body, err = helps.ApplyRequestThinking(body, req, opts, from.String(), to.String(), e.Identifier()) if err != nil { @@ -972,13 +984,16 @@ func (e *GeminiVertexExecutor) countTokensWithServiceAccount(ctx context.Context responseFormat := cliproxyexecutor.ResponseFormatOrSource(opts) to := sdktranslator.FromString("gemini") - translatedReq := helps.TranslateRequestWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, false) + translatedReq, err := helps.TranslateRequestReturningError(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, false, false) + if err != nil { + return cliproxyexecutor.Response{}, err + } originalTranslatedForPayload := append([]byte(nil), translatedReq...) if len(opts.OriginalRequest) > 0 { originalTranslatedForPayload = helps.TranslateRequestWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, baseModel, opts.OriginalRequest, false) } - translatedReq, err := helps.ApplyRequestThinking(translatedReq, req, opts, from.String(), to.String(), e.Identifier()) + translatedReq, err = helps.ApplyRequestThinking(translatedReq, req, opts, from.String(), to.String(), e.Identifier()) if err != nil { return cliproxyexecutor.Response{}, err } @@ -1071,13 +1086,16 @@ func (e *GeminiVertexExecutor) countTokensWithAPIKey(ctx context.Context, auth * responseFormat := cliproxyexecutor.ResponseFormatOrSource(opts) to := sdktranslator.FromString("gemini") - translatedReq := helps.TranslateRequestWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, false) + translatedReq, err := helps.TranslateRequestReturningError(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, false, false) + if err != nil { + return cliproxyexecutor.Response{}, err + } originalTranslatedForPayload := append([]byte(nil), translatedReq...) if len(opts.OriginalRequest) > 0 { originalTranslatedForPayload = helps.TranslateRequestWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, baseModel, opts.OriginalRequest, false) } - translatedReq, err := helps.ApplyRequestThinking(translatedReq, req, opts, from.String(), to.String(), e.Identifier()) + translatedReq, err = helps.ApplyRequestThinking(translatedReq, req, opts, from.String(), to.String(), e.Identifier()) if err != nil { return cliproxyexecutor.Response{}, err } diff --git a/internal/runtime/executor/helps/codex_multi_agent_v2.go b/internal/runtime/executor/helps/codex_multi_agent_v2.go index c4d15e11e8c..ea94835783f 100644 --- a/internal/runtime/executor/helps/codex_multi_agent_v2.go +++ b/internal/runtime/executor/helps/codex_multi_agent_v2.go @@ -99,40 +99,55 @@ func sameByteSlice(a, b []byte) bool { // TranslateRequestPairWithAPIKeyModelCompatibility avoids translating identical // inputs twice while retaining separate buffers and invoking plugins once per input. func TranslateRequestPairWithAPIKeyModelCompatibility(ctx context.Context, headers http.Header, cfg *config.Config, from, to sdktranslator.Format, model string, originalPayload, requestPayload []byte, stream, isCompat bool) (original, working []byte) { - original, working, _ = TranslateRequestPairWithAPIKeyModelCompatibilityAndUpdateIntent(ctx, headers, cfg, from, to, model, originalPayload, requestPayload, stream, isCompat) + original, working, _ = translateRequestPairWithAPIKeyModelCompatibility(ctx, headers, cfg, from, to, model, originalPayload, requestPayload, stream, isCompat) return original, working } +// TranslateRequestPairReturningError reports a content part the target cannot represent. +func TranslateRequestPairReturningError(ctx context.Context, headers http.Header, cfg *config.Config, from, to sdktranslator.Format, model string, originalPayload, requestPayload []byte, stream, isCompat bool) ([]byte, []byte, error) { + return translateRequestPairWithAPIKeyModelCompatibility(ctx, headers, cfg, from, to, model, originalPayload, requestPayload, stream, isCompat) +} + +func translateRequestPairWithAPIKeyModelCompatibility(ctx context.Context, headers http.Header, cfg *config.Config, from, to sdktranslator.Format, model string, originalPayload, requestPayload []byte, stream, isCompat bool) (original, working []byte, err error) { + original, working, _, err = TranslateRequestPairWithAPIKeyModelCompatibilityAndUpdateIntent(ctx, headers, cfg, from, to, model, originalPayload, requestPayload, stream, isCompat) + return original, working, err +} + // TranslateRequestPairWithAPIKeyModelCompatibilityAndUpdateIntent returns the -// normalizer decision for the working payload, not for the baseline payload. -func TranslateRequestPairWithAPIKeyModelCompatibilityAndUpdateIntent(ctx context.Context, headers http.Header, cfg *config.Config, from, to sdktranslator.Format, model string, originalPayload, requestPayload []byte, stream, isCompat bool) (original, working []byte, updatesChanged bool) { - original, updatesChanged = TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntent(ctx, headers, cfg, from, to, model, originalPayload, stream, isCompat) +// normalizer decision for the working payload, not for the baseline payload, +// and the error for a content part the target cannot represent. +func TranslateRequestPairWithAPIKeyModelCompatibilityAndUpdateIntent(ctx context.Context, headers http.Header, cfg *config.Config, from, to sdktranslator.Format, model string, originalPayload, requestPayload []byte, stream, isCompat bool) (original, working []byte, updatesChanged bool, err error) { + original, updatesChanged, err = TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntent(ctx, headers, cfg, from, to, model, originalPayload, stream, isCompat) if sameByteSlice(originalPayload, requestPayload) { - return original, append([]byte(nil), original...), updatesChanged + return original, append([]byte(nil), original...), updatesChanged, err + } + working, updatesChanged, errWorking := TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntent(ctx, headers, cfg, from, to, model, requestPayload, stream, isCompat) + if err == nil { + err = errWorking } - working, updatesChanged = TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntent(ctx, headers, cfg, from, to, model, requestPayload, stream, isCompat) - return original, working, updatesChanged + return original, working, updatesChanged, err } // TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntent returns the // plugin normalizer's request-scoped update decision for Responses targets. -func TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntent(ctx context.Context, headers http.Header, cfg *config.Config, from, to sdktranslator.Format, model string, payload []byte, stream, isCompat bool) ([]byte, bool) { +func TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntent(ctx context.Context, headers http.Header, cfg *config.Config, from, to sdktranslator.Format, model string, payload []byte, stream, isCompat bool) ([]byte, bool, error) { return TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntentForExecutor(ctx, headers, cfg, "", from, to, model, payload, stream, isCompat) } // TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntentForExecutor // translates a request while applying client schema compatibility for the // actual target executor. -func TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntentForExecutor(ctx context.Context, headers http.Header, cfg *config.Config, targetExecutor string, from, to sdktranslator.Format, model string, payload []byte, stream, isCompat bool) ([]byte, bool) { +func TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntentForExecutor(ctx context.Context, headers http.Header, cfg *config.Config, targetExecutor string, from, to sdktranslator.Format, model string, payload []byte, stream, isCompat bool) ([]byte, bool, error) { if !isCompat || (to == sdktranslator.FormatCodex && from != sdktranslator.FormatClaude) { translated := sdktranslator.RequestEnvelope{Format: from, Model: model, Stream: stream, Body: payload} if IsCodexUserAgent(headers) && !isCodexTargetExecutor(targetExecutor) { translated.Body = NormalizeCodexToolIntegerTypes(translated.Body, headers) } translated = multiagentv2.TranslateRequestEnvelopeWithCodexMultiAgentV2(ctx, headers, cfg, from, to, translated) - return translated.Body, translated.ConfigurationUpdatesChanged + return translated.Body, translated.ConfigurationUpdatesChanged, translated.Err } - return TranslateRequestWithAPIKeyModelCompatibilityForExecutor(ctx, headers, cfg, targetExecutor, from, to, model, payload, stream, isCompat), false + body, err := translateRequestWithAPIKeyModelCompatibilityForExecutor(ctx, headers, cfg, targetExecutor, from, to, model, payload, stream, isCompat) + return body, false, err } // TranslateRequestWithAPIKeyModelCompatibility applies compatibility-aware @@ -144,11 +159,21 @@ func TranslateRequestWithAPIKeyModelCompatibility(ctx context.Context, headers h // TranslateRequestWithAPIKeyModelCompatibilityForExecutor applies compatibility-aware // request translation while preserving the actual target executor's schema policy. func TranslateRequestWithAPIKeyModelCompatibilityForExecutor(ctx context.Context, headers http.Header, cfg *config.Config, targetExecutor string, from, to sdktranslator.Format, model string, payload []byte, stream, isCompat bool) []byte { + body, _ := translateRequestWithAPIKeyModelCompatibilityForExecutor(ctx, headers, cfg, targetExecutor, from, to, model, payload, stream, isCompat) + return body +} + +// TranslateRequestReturningError reports a content part the target cannot represent. +func TranslateRequestReturningError(ctx context.Context, headers http.Header, cfg *config.Config, from, to sdktranslator.Format, model string, payload []byte, stream, isCompat bool) ([]byte, error) { + return translateRequestWithAPIKeyModelCompatibilityForExecutor(ctx, headers, cfg, "", from, to, model, payload, stream, isCompat) +} + +func translateRequestWithAPIKeyModelCompatibilityForExecutor(ctx context.Context, headers http.Header, cfg *config.Config, targetExecutor string, from, to sdktranslator.Format, model string, payload []byte, stream, isCompat bool) ([]byte, error) { if IsCodexUserAgent(headers) && !isCodexTargetExecutor(targetExecutor) { payload = NormalizeCodexToolIntegerTypes(payload, headers) } if !isCompat { - return TranslateRequestWithCodexMultiAgentV2ForExecutor(ctx, headers, cfg, targetExecutor, from, to, model, payload, stream) + return translateRequestWithCodexMultiAgentV2Checked(ctx, headers, cfg, from, to, model, payload, stream) } if from == sdktranslator.FormatOpenAIResponse { payload = RewriteCodexOrphanDelegationInput(ctx, headers, payload, cfg) @@ -158,26 +183,27 @@ func TranslateRequestWithAPIKeyModelCompatibilityForExecutor(ctx context.Context } var translated []byte + var convertErr error switch { case from == sdktranslator.FormatClaude && to == sdktranslator.FormatCodex: - translated = codexclaude.ConvertClaudeRequestToCodexWithCompat(model, payload, stream) + translated, convertErr = codexclaude.ConvertClaudeRequestToCodexWithCompatReturningError(model, payload, stream) case from == sdktranslator.FormatClaude && to == sdktranslator.FormatGemini: - translated = geminiclaude.ConvertClaudeRequestToGeminiWithCompat(model, payload, stream) + translated, convertErr = geminiclaude.ConvertClaudeRequestToGeminiWithCompatReturningError(model, payload, stream) case from == sdktranslator.FormatClaude && to == sdktranslator.FormatInteractions: - translated = interactionsclaude.ConvertClaudeRequestToInteractionsWithCompat(model, payload, stream) + translated, convertErr = interactionsclaude.ConvertClaudeRequestToInteractionsWithCompatReturningError(model, payload, stream) case from == sdktranslator.FormatClaude && to == sdktranslator.FormatOpenAI: - translated = openaiclaude.ConvertClaudeRequestToOpenAIWithCompat(model, payload, stream) + translated, convertErr = openaiclaude.ConvertClaudeRequestToOpenAIWithCompatReturningError(model, payload, stream) case from == sdktranslator.FormatOpenAI && to == sdktranslator.FormatClaude: - translated = openaichatclaude.ConvertOpenAIRequestToClaudeWithCompat(model, payload, stream) + translated, convertErr = openaichatclaude.ConvertOpenAIRequestToClaudeWithCompatReturningError(model, payload, stream) case from == sdktranslator.FormatOpenAIResponse && to == sdktranslator.FormatClaude: translated = responsesclaude.ConvertOpenAIResponsesRequestToClaudeWithCompat(model, payload, stream) default: - return TranslateRequestWithCodexMultiAgentV2ForExecutor(ctx, headers, cfg, targetExecutor, from, to, model, payload, stream) + return translateRequestWithCodexMultiAgentV2Checked(ctx, headers, cfg, from, to, model, payload, stream) } summaryConfig := thinking.ExtractTranslatedSummaryConfig(payload, from.String(), to.String()) translated = thinking.ApplySummaryConfigForModel(translated, to.String(), model, summaryConfig) - return sdktranslator.NormalizeRequest(ctx, from, to, model, translated, stream) + return sdktranslator.NormalizeRequest(ctx, from, to, model, translated, stream), convertErr } // HasCodexMultiAgentV2NamespaceConflict reports whether the request defines @@ -213,3 +239,10 @@ func OptimizeCodexMultiAgentV2RequestForAuth(ctx context.Context, headers http.H func RestoreCodexMultiAgentV2Response(payload []byte, optimized bool) []byte { return multiagentv2.RestoreCodexMultiAgentV2Response(payload, optimized) } + +// translateRequestWithCodexMultiAgentV2Checked is the multi-agent translation that +// keeps the envelope failure instead of dropping it with the body. +func translateRequestWithCodexMultiAgentV2Checked(ctx context.Context, headers http.Header, cfg *config.Config, from, to sdktranslator.Format, model string, payload []byte, stream bool) ([]byte, error) { + translated := multiagentv2.TranslateRequestEnvelopeWithCodexMultiAgentV2(ctx, headers, cfg, from, to, sdktranslator.RequestEnvelope{Format: from, Model: model, Stream: stream, Body: payload}) + return translated.Body, translated.Err +} diff --git a/internal/runtime/executor/helps/codex_multi_agent_v2_test.go b/internal/runtime/executor/helps/codex_multi_agent_v2_test.go index fb32c1f9928..e5a6df82444 100644 --- a/internal/runtime/executor/helps/codex_multi_agent_v2_test.go +++ b/internal/runtime/executor/helps/codex_multi_agent_v2_test.go @@ -343,14 +343,14 @@ func TestTranslateRequestCompatibilityForExecutorToolIntegerTypes(t *testing.T) headers = http.Header{"User-Agent": []string{ua}, "X-Openai-Subagent": []string{"collab_spawn"}} } payload := []byte(route.payload) - out, changed := TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntentForExecutor(t.Context(), headers, &config.Config{}, target.name, route.from, route.to, "model", payload, false, compat) + out, changed, _ := TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntentForExecutor(t.Context(), headers, &config.Config{}, target.name, route.from, route.to, "model", payload, false, compat) outputs := map[string][]byte{ "update_intent": out, "body": TranslateRequestWithAPIKeyModelCompatibilityForExecutor(t.Context(), headers, &config.Config{}, target.name, route.from, route.to, "model", payload, false, compat), } if target.name == "" { outputs["legacy_body"] = TranslateRequestWithAPIKeyModelCompatibility(t.Context(), headers, &config.Config{}, route.from, route.to, "model", payload, false, compat) - outputs["legacy_update_intent"], _ = TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntent(t.Context(), headers, &config.Config{}, route.from, route.to, "model", payload, false, compat) + outputs["legacy_update_intent"], _, _ = TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntent(t.Context(), headers, &config.Config{}, route.from, route.to, "model", payload, false, compat) } wantType := "number" if ua == "codex_cli_rs/0.1" && !target.preserve { diff --git a/internal/runtime/executor/helps/configuration_update_plugin_test.go b/internal/runtime/executor/helps/configuration_update_plugin_test.go index 701c5b5e258..805425ef34f 100644 --- a/internal/runtime/executor/helps/configuration_update_plugin_test.go +++ b/internal/runtime/executor/helps/configuration_update_plugin_test.go @@ -76,7 +76,7 @@ func TestRequestPairPreservesPluginConfigurationUpdateIntent(t *testing.T) { wantCalls = 2 } inputBefore := bytes.Clone(request) - base, work, updatesChanged := helps.TranslateRequestPairWithAPIKeyModelCompatibilityAndUpdateIntent(t.Context(), nil, &config.Config{}, sdktranslator.FormatOpenAIResponse, sdktranslator.FormatCodex, "opaque-route", original, request, stream, compat) + base, work, updatesChanged, _ := helps.TranslateRequestPairWithAPIKeyModelCompatibilityAndUpdateIntent(t.Context(), nil, &config.Config{}, sdktranslator.FormatOpenAIResponse, sdktranslator.FormatCodex, "opaque-route", original, request, stream, compat) if hooks.calls != wantCalls { t.Fatalf("stream=%v compat=%v distinct=%v: plugin calls = %d, want %d", stream, compat, distinct, hooks.calls, wantCalls) } diff --git a/internal/runtime/executor/helps/unsupported_part_test.go b/internal/runtime/executor/helps/unsupported_part_test.go new file mode 100644 index 00000000000..e592e8c38f4 --- /dev/null +++ b/internal/runtime/executor/helps/unsupported_part_test.go @@ -0,0 +1,46 @@ +package helps + +import ( + "context" + "testing" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/clienterror" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +// A turn that only holds a file the target cannot receive is refused with a named +// 400, through both the single and the pair translation, with and without compat. +func TestClaudeContainerUploadReturns400(t *testing.T) { + payload := []byte(`{"messages":[{"role":"user","content":[{"type":"container_upload","file_id":"file-example"}]}]}`) + for _, to := range []sdktranslator.Format{sdktranslator.FormatGemini, sdktranslator.FormatOpenAI, sdktranslator.FormatCodex, sdktranslator.FormatInteractions} { + for _, compat := range []bool{false, true} { + _, single := TranslateRequestReturningError(context.Background(), nil, nil, sdktranslator.FormatClaude, to, "m", payload, false, compat) + _, _, pair := TranslateRequestPairReturningError(context.Background(), nil, nil, sdktranslator.FormatClaude, to, "m", payload, payload, false, compat) + for name, err := range map[string]error{"single": single, "pair": pair} { + if err == nil || err.Error() != "unsupported content part: container_upload" || clienterror.HTTPStatusFromError(err) != 400 { + t.Errorf("to=%s compat=%v %s: err = %v, want a 400 naming container_upload", to, compat, name, err) + } + } + } + } +} + +// TestByteWrappersKeepAJSONBodyForAnUnsendableFile guards the executors that still +// ignore the error: they must get a request body, never an empty one. +func TestByteWrappersKeepAJSONBodyForAnUnsendableFile(t *testing.T) { + payload := []byte(`{"model":"m","messages":[{"role":"user","content":[{"type":"container_upload","file_id":"file-absent"}]}]}`) + for _, to := range []sdktranslator.Format{sdktranslator.FormatOpenAI, sdktranslator.FormatCodex, sdktranslator.FormatInteractions, sdktranslator.FormatGemini} { + for _, compat := range []bool{false, true} { + original, working := TranslateRequestPairWithAPIKeyModelCompatibility(context.Background(), nil, nil, sdktranslator.FormatClaude, to, "m", payload, payload, false, compat) + for _, body := range [][]byte{original, working} { + if !gjson.ValidBytes(body) || len(body) < 2 { + t.Fatalf("to=%s compat=%v: body = %q", to, compat, body) + } + } + if _, _, err := TranslateRequestPairReturningError(context.Background(), nil, nil, sdktranslator.FormatClaude, to, "m", payload, payload, false, compat); err == nil { + t.Fatalf("to=%s compat=%v: the checked variant lost the error", to, compat) + } + } + } +} diff --git a/internal/runtime/executor/kimi_executor.go b/internal/runtime/executor/kimi_executor.go index 05e2408c27c..5cc510c0b46 100644 --- a/internal/runtime/executor/kimi_executor.go +++ b/internal/runtime/executor/kimi_executor.go @@ -135,7 +135,10 @@ func (e *KimiExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, req } originalPayload := bytes.Clone(originalPayloadSource) originalTranslated := helps.TranslateRequestWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, baseModel, originalPayload, false) - body := helps.TranslateRequestWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, baseModel, bytes.Clone(req.Payload), false) + body, err := helps.TranslateRequestReturningError(ctx, opts.Headers, e.cfg, from, to, baseModel, bytes.Clone(req.Payload), false, false) + if err != nil { + return resp, err + } // Strip kimi- prefix and any [1m] suffix for upstream API upstreamModel := normalizeKimiUpstreamModel(baseModel) @@ -270,7 +273,10 @@ func (e *KimiExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Aut } originalPayload := bytes.Clone(originalPayloadSource) originalTranslated := helps.TranslateRequestWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, baseModel, originalPayload, true) - body := helps.TranslateRequestWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, baseModel, bytes.Clone(req.Payload), true) + body, err := helps.TranslateRequestReturningError(ctx, opts.Headers, e.cfg, from, to, baseModel, bytes.Clone(req.Payload), true, false) + if err != nil { + return nil, err + } // Strip kimi- prefix and any [1m] suffix for upstream API upstreamModel := normalizeKimiUpstreamModel(baseModel) diff --git a/internal/runtime/executor/meta_executor_execute.go b/internal/runtime/executor/meta_executor_execute.go index 3fa0c19a5fd..c78db800a88 100644 --- a/internal/runtime/executor/meta_executor_execute.go +++ b/internal/runtime/executor/meta_executor_execute.go @@ -44,7 +44,10 @@ func (e *MetaExecutor) prepareResponsesRequest(ctx context.Context, req cliproxy originalPayload := bytes.Clone(originalPayloadSource) isCompat := helps.APIKeyModelIsCompat(req) originalTranslated := helps.TranslateRequestWithAPIKeyModelCompatibility(ctx, opts.Headers, e.cfg, from, to, baseModel, originalPayload, stream, isCompat) - body := helps.TranslateRequestWithAPIKeyModelCompatibility(ctx, opts.Headers, e.cfg, from, to, baseModel, bytes.Clone(req.Payload), stream, isCompat) + body, err := helps.TranslateRequestReturningError(ctx, opts.Headers, e.cfg, from, to, baseModel, bytes.Clone(req.Payload), stream, isCompat) + if err != nil { + return nil, err + } var errThinking error body, errThinking = helps.ApplyRequestThinking(body, req, opts, from.String(), to.String(), e.Identifier()) diff --git a/internal/runtime/executor/openai_compat_executor.go b/internal/runtime/executor/openai_compat_executor.go index 562a0c959f8..a2ef933448e 100644 --- a/internal/runtime/executor/openai_compat_executor.go +++ b/internal/runtime/executor/openai_compat_executor.go @@ -116,7 +116,10 @@ func (e *OpenAICompatExecutor) Execute(ctx context.Context, auth *cliproxyauth.A } originalPayload := originalPayloadSource isCompat := helps.APIKeyModelIsCompat(req) - originalTranslated, translated, updatesChanged := helps.TranslateRequestPairWithAPIKeyModelCompatibilityAndUpdateIntent(ctx, opts.Headers, e.cfg, from, to, baseModel, originalPayload, req.Payload, opts.Stream, isCompat) + originalTranslated, translated, updatesChanged, err := helps.TranslateRequestPairWithAPIKeyModelCompatibilityAndUpdateIntent(ctx, opts.Headers, e.cfg, from, to, baseModel, originalPayload, req.Payload, opts.Stream, isCompat) + if err != nil { + return resp, err + } translated, err = helps.ApplyRequestThinking(translated, req, opts, from.String(), to.String(), e.Identifier(), updatesChanged) if err != nil { @@ -340,7 +343,10 @@ func (e *OpenAICompatExecutor) ExecuteStream(ctx context.Context, auth *cliproxy } originalPayload := originalPayloadSource isCompat := helps.APIKeyModelIsCompat(req) - originalTranslated, translated, updatesChanged := helps.TranslateRequestPairWithAPIKeyModelCompatibilityAndUpdateIntent(ctx, opts.Headers, e.cfg, from, to, baseModel, originalPayload, req.Payload, true, isCompat) + originalTranslated, translated, updatesChanged, err := helps.TranslateRequestPairWithAPIKeyModelCompatibilityAndUpdateIntent(ctx, opts.Headers, e.cfg, from, to, baseModel, originalPayload, req.Payload, true, isCompat) + if err != nil { + return nil, err + } translated, err = helps.ApplyRequestThinking(translated, req, opts, from.String(), to.String(), e.Identifier(), updatesChanged) if err != nil { @@ -740,15 +746,18 @@ func (e *OpenAICompatExecutor) CountTokens(ctx context.Context, auth *cliproxyau responseFormat := cliproxyexecutor.ResponseFormatOrSource(opts) to := sdktranslator.FromString("openai") isCompat := helps.APIKeyModelIsCompat(req) - translated, updatesChanged := helps.TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntent(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, false, isCompat) + translated, updatesChanged, err := helps.TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntent(ctx, opts.Headers, e.cfg, from, to, baseModel, req.Payload, false, isCompat) + if err != nil { + return cliproxyexecutor.Response{}, err + } originalTranslatedForPayload := append([]byte(nil), translated...) if len(opts.OriginalRequest) > 0 { - originalTranslatedForPayload, _ = helps.TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntent(ctx, opts.Headers, e.cfg, from, to, baseModel, opts.OriginalRequest, false, isCompat) + originalTranslatedForPayload, _, _ = helps.TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntent(ctx, opts.Headers, e.cfg, from, to, baseModel, opts.OriginalRequest, false, isCompat) } modelForCounting := baseModel - translated, err := helps.ApplyRequestThinking(translated, req, opts, from.String(), to.String(), e.Identifier(), updatesChanged) + translated, err = helps.ApplyRequestThinking(translated, req, opts, from.String(), to.String(), e.Identifier(), updatesChanged) if err != nil { return cliproxyexecutor.Response{}, err } diff --git a/internal/runtime/executor/unsupported_part_executor_test.go b/internal/runtime/executor/unsupported_part_executor_test.go new file mode 100644 index 00000000000..e3dbcd5185a --- /dev/null +++ b/internal/runtime/executor/unsupported_part_executor_test.go @@ -0,0 +1,82 @@ +package executor + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "testing" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +// A turn whose only content is a file the target cannot receive must be refused +// before any upstream call, instead of forwarding an empty turn. +func TestExecutorsRefuseAFileOnlyTurnBeforeCallingUpstream(t *testing.T) { + var upstreamCalls int + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + upstreamCalls++ + w.WriteHeader(http.StatusOK) + })) + defer server.Close() + + const ( + claudeFile = `{"model":"m","max_tokens":8,"messages":[{"role":"user","content":[{"type":"container_upload","file_id":"file_not_stored"}]}]}` + openAIFile = `{"model":"m","messages":[{"role":"user","content":[{"type":"file","file":{"file_id":"file-not-stored"}}]}]}` + ) + keyAuth := func(provider string, extra map[string]string) *cliproxyauth.Auth { + attrs := map[string]string{"api_key": "k", "base_url": server.URL} + for k, v := range extra { + attrs[k] = v + } + return &cliproxyauth.Auth{Provider: provider, Attributes: attrs} + } + targets := []struct { + name string + exec cliproxyauth.ProviderExecutor + auth *cliproxyauth.Auth + source string + payload string + wantPart string + }{ + {"claude to openai-compat", NewOpenAICompatExecutor("openai-compatibility", &config.Config{OpenAICompatibility: []config.OpenAICompatibility{{Name: "compat"}}}), + keyAuth("openai-compatibility", map[string]string{"base_url": server.URL + "/v1", "compat_name": "compat", "provider_key": "compat"}), "claude", claudeFile, "container_upload"}, + {"claude to codex", NewCodexExecutor(&config.Config{}), keyAuth("codex", map[string]string{"plan_type": "pro"}), "claude", claudeFile, "container_upload"}, + {"openai to claude", NewClaudeExecutor(&config.Config{}), keyAuth("claude", nil), "openai", openAIFile, "file"}, + {"openai to gemini", NewGeminiExecutor(&config.Config{}), keyAuth("gemini", nil), "openai", openAIFile, "file"}, + } + for _, target := range targets { + req := cliproxyexecutor.Request{Model: "m", Payload: []byte(target.payload)} + opts := func(stream bool) cliproxyexecutor.Options { + return cliproxyexecutor.Options{SourceFormat: sdktranslator.FromString(target.source), Stream: stream} + } + calls := map[string]func() error{ + "Execute": func() error { + _, err := target.exec.Execute(context.Background(), target.auth, req, opts(false)) + return err + }, + "ExecuteStream": func() error { + _, err := target.exec.ExecuteStream(context.Background(), target.auth, req, opts(true)) + return err + }, + "CountTokens": func() error { + _, err := target.exec.CountTokens(context.Background(), target.auth, req, opts(false)) + return err + }, + } + for method, call := range calls { + err := call() + var part *translatorcommon.UnsupportedPartError + if !errors.As(err, &part) || part.Type != target.wantPart { + t.Errorf("%s %s: err = %v, want unsupported %s", target.name, method, err, target.wantPart) + } + } + } + if upstreamCalls != 0 { + t.Fatalf("upstream was called %d times, want 0", upstreamCalls) + } +} diff --git a/internal/runtime/executor/xai_executor_request.go b/internal/runtime/executor/xai_executor_request.go index 1d3ab89b2bc..01a7d44eef7 100644 --- a/internal/runtime/executor/xai_executor_request.go +++ b/internal/runtime/executor/xai_executor_request.go @@ -73,10 +73,12 @@ func (e *XAIExecutor) prepareResponsesRequestTo(ctx context.Context, req cliprox originalPayload := bytes.Clone(originalPayloadSource) originalTranslated := helps.TranslateRequestWithAPIKeyModelCompatibilityForExecutor(ctx, opts.Headers, e.cfg, e.Identifier(), from, to, baseModel, originalPayload, stream, helps.APIKeyModelIsCompat(req)) originalTranslated = preserveXAIResponsesOutputControls(originalTranslated, originalPayload, from) - body, updatesChanged := helps.TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntentForExecutor(ctx, opts.Headers, e.cfg, e.Identifier(), from, to, baseModel, bytes.Clone(req.Payload), stream, helps.APIKeyModelIsCompat(req)) + body, updatesChanged, err := helps.TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntentForExecutor(ctx, opts.Headers, e.cfg, e.Identifier(), from, to, baseModel, bytes.Clone(req.Payload), stream, helps.APIKeyModelIsCompat(req)) + if err != nil { + return nil, err + } body = preserveXAIResponsesOutputControls(body, req.Payload, from) - var err error body, err = helps.ApplyRequestThinking(body, req, opts, from.String(), e.Identifier(), e.Identifier(), updatesChanged) if err != nil { return nil, err diff --git a/internal/translator/claude/openai/chat-completions/claude_openai_file_test.go b/internal/translator/claude/openai/chat-completions/claude_openai_file_test.go new file mode 100644 index 00000000000..0b27b6288aa --- /dev/null +++ b/internal/translator/claude/openai/chat-completions/claude_openai_file_test.go @@ -0,0 +1,54 @@ +package chat_completions + +import ( + "context" + "errors" + "testing" + + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +func TestConvertOpenAIRequestToClaude_FileParts(t *testing.T) { + const ( + text = `{"type":"text","text":"read it"}` + audio = `{"type":"input_audio","input_audio":{"format":"wav","data":"UklGRg=="}}` + missing = `{"type":"file","file":{"file_id":"file-absent"}}` + inline = `{"type":"file","file":{"filename":"a.pdf","file_data":"data:application/pdf;base64,JVBERi0xLjQK"}}` + system = `{"role":"system","content":"be brief"},` + ) + cases := []struct { + name, prefix, content string + wantErr string + wantTypes string + }{ + {name: "unknown file id alone", content: missing, wantErr: "file"}, + {name: "audio alone", content: audio, wantErr: "input_audio"}, + {name: "a system prompt does not hide the empty turn", prefix: system, content: missing, wantErr: "file"}, + {name: "text beside an unknown file id", content: text + "," + missing, wantTypes: `["text"]`}, + {name: "text beside audio", content: text + "," + audio, wantTypes: `["text"]`}, + {name: "inline file data becomes a document", content: inline, wantTypes: `["document"]`}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + payload := `{"model":"claude-sonnet-4","messages":[` + tc.prefix + `{"role":"user","content":[` + tc.content + `]}]}` + got := sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatOpenAI, sdktranslator.FormatClaude, + sdktranslator.RequestEnvelope{Format: sdktranslator.FormatOpenAI, Model: "claude-sonnet-4", Body: []byte(payload)}) + + var part *translatorcommon.UnsupportedPartError + if tc.wantErr != "" { + if !errors.As(got.Err, &part) || part.Type != tc.wantErr { + t.Fatalf("err = %v, want unsupported %s", got.Err, tc.wantErr) + } + return + } + if got.Err != nil { + t.Fatalf("err = %v", got.Err) + } + if types := gjson.GetBytes(got.Body, "messages.0.content.#.type").Raw; types != tc.wantTypes { + t.Fatalf("content types = %s, want %s. Output: %s", types, tc.wantTypes, got.Body) + } + }) + } +} diff --git a/internal/translator/claude/openai/chat-completions/claude_openai_request.go b/internal/translator/claude/openai/chat-completions/claude_openai_request.go index bb607095484..3bac7b7359e 100644 --- a/internal/translator/claude/openai/chat-completions/claude_openai_request.go +++ b/internal/translator/claude/openai/chat-completions/claude_openai_request.go @@ -34,17 +34,26 @@ import ( // Returns: // - []byte: The transformed request data in Claude Code API format func ConvertOpenAIRequestToClaude(modelName string, inputRawJSON []byte, stream bool) []byte { - return convertOpenAIRequestToClaude(modelName, inputRawJSON, stream, false) + body, _ := convertOpenAIRequestToClaude(modelName, inputRawJSON, stream, false) + return body } // ConvertOpenAIRequestToClaudeWithCompat preserves assistant reasoning content // as an unsigned thinking block for configured compatibility endpoints. func ConvertOpenAIRequestToClaudeWithCompat(modelName string, inputRawJSON []byte, stream bool) []byte { + body, _ := convertOpenAIRequestToClaude(modelName, inputRawJSON, stream, true) + return body +} + +// ConvertOpenAIRequestToClaudeWithCompatReturningError also reports a file part +// Claude cannot receive when nothing else was left to send. +func ConvertOpenAIRequestToClaudeWithCompatReturningError(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { return convertOpenAIRequestToClaude(modelName, inputRawJSON, stream, true) } -func convertOpenAIRequestToClaude(modelName string, inputRawJSON []byte, stream, preserveEmptyThinkingBlocks bool) []byte { +func convertOpenAIRequestToClaude(modelName string, inputRawJSON []byte, stream, preserveEmptyThinkingBlocks bool) ([]byte, error) { rawJSON := inputRawJSON + var droppedAttachment string userID := common.DeriveClaudeUserID(rawJSON) @@ -208,9 +217,10 @@ func convertOpenAIRequestToClaude(modelName string, inputRawJSON []byte, stream, contentBlocks = append(contentBlocks, part) } else if contentResult.Exists() && contentResult.IsArray() { contentResult.ForEach(func(_, part gjson.Result) bool { - claudePart := convertOpenAIContentPartToClaudePart(part) - if claudePart != "" { + if claudePart := convertOpenAIContentPartToClaudePart(part); claudePart != "" { contentBlocks = append(contentBlocks, []byte(claudePart)) + } else if partType := part.Get("type").String(); partType == "file" || partType == "input_audio" { + droppedAttachment = partType } return true }) @@ -305,6 +315,9 @@ func convertOpenAIRequestToClaude(modelName string, inputRawJSON []byte, stream, systemBlocks = append(systemBlocks, systemBlock) } + // Decided before the blank turn below is added, or a system prompt would hide an empty request. + nothingLeftErr := common.ErrIfNothingLeft(droppedAttachment, len(messageBlocks)) + // Preserve a minimal conversational turn for system-only inputs. // Claude payloads with top-level system instructions but no messages are risky for downstream validation. if len(messageBlocks) == 0 && len(systemBlocks) > 0 { @@ -458,7 +471,7 @@ func convertOpenAIRequestToClaude(modelName string, inputRawJSON []byte, stream, } } - return thinking.ApplyTranslatedSummaryToClaude(out, rawJSON, "openai", modelName) + return thinking.ApplyTranslatedSummaryToClaude(out, rawJSON, "openai", modelName), nothingLeftErr } func convertOpenAIContentPartToClaudePartRaw(part gjson.Result) []byte { diff --git a/internal/translator/claude/openai/chat-completions/init.go b/internal/translator/claude/openai/chat-completions/init.go index f1505748429..3073174ca78 100644 --- a/internal/translator/claude/openai/chat-completions/init.go +++ b/internal/translator/claude/openai/chat-completions/init.go @@ -4,16 +4,20 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( OpenAI, Claude, - ConvertOpenAIRequestToClaude, + nil, interfaces.TranslateResponse{ Stream: ConvertClaudeResponseToOpenAI, NonStream: ConvertClaudeResponseToOpenAINonStream, }, ) + sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatOpenAI, sdktranslator.FormatClaude, func(model string, body []byte, stream bool) ([]byte, error) { + return convertOpenAIRequestToClaude(model, body, stream, false) + }) } diff --git a/internal/translator/codex/claude/codex_claude_request.go b/internal/translator/codex/claude/codex_claude_request.go index ae94c90909e..ffc92c9a1c3 100644 --- a/internal/translator/codex/claude/codex_claude_request.go +++ b/internal/translator/codex/claude/codex_claude_request.go @@ -42,17 +42,25 @@ import ( // Returns: // - []byte: The transformed request data in internal client format func ConvertClaudeRequestToCodex(modelName string, inputRawJSON []byte, stream bool) []byte { - return convertClaudeRequestToCodex(modelName, inputRawJSON, stream, false) + body, _ := convertClaudeRequestToCodex(modelName, inputRawJSON, stream, false) + return body } // ConvertClaudeRequestToCodexWithCompat preserves assistant thinking blocks with // empty or unknown-format signatures for configured compatibility endpoints. func ConvertClaudeRequestToCodexWithCompat(modelName string, inputRawJSON []byte, stream bool) []byte { + body, _ := convertClaudeRequestToCodex(modelName, inputRawJSON, stream, true) + return body +} + +// ConvertClaudeRequestToCodexWithCompatReturningError reports a file part the target cannot represent. +func ConvertClaudeRequestToCodexWithCompatReturningError(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { return convertClaudeRequestToCodex(modelName, inputRawJSON, stream, true) } -func convertClaudeRequestToCodex(modelName string, inputRawJSON []byte, _ bool, preserveEmptyThinkingBlocks bool) []byte { +func convertClaudeRequestToCodex(modelName string, inputRawJSON []byte, _ bool, preserveEmptyThinkingBlocks bool) ([]byte, error) { rawJSON := inputRawJSON + var droppedAttachment string template := []byte(`{"model":"","instructions":"","input":[]}`) @@ -228,25 +236,15 @@ func convertClaudeRequestToCodex(modelName string, inputRawJSON []byte, _ bool, appendImageContent(dataURL) } } - case "document": + case "document", "container_upload": if len(pendingSystemReminders) > 0 { inputItems = append(inputItems, pendingSystemReminders...) pendingSystemReminders = nil } - sourceResult := messageContentResult.Get("source") - if sourceResult.Get("type").String() != "base64" { - continue - } - mediaType := strings.TrimSpace(sourceResult.Get("media_type").String()) - if !strings.EqualFold(mediaType, "application/pdf") { - continue - } - data := sourceResult.Get("data").String() - if data == "" { - data = sourceResult.Get("base64").String() - } - if data != "" { - appendDocumentContent(fmt.Sprintf("data:%s;base64,%s", mediaType, data)) + if dataURL, ok := claudeDocumentDataURL(messageContentResult); ok { + appendDocumentContent(dataURL) + } else { + droppedAttachment = messageContentResult.Get("type").String() } case "tool_use": flushMessage() @@ -469,7 +467,7 @@ func convertClaudeRequestToCodex(modelName string, inputRawJSON []byte, _ bool, } template = translatorcommon.SetRawArrayItems(template, "input", inputItems) - return template + return template, translatorcommon.ErrIfNothingLeft(droppedAttachment, len(inputItems)) } func codexClaudeTargetAcceptsGrokSignature(modelName string) bool { @@ -845,3 +843,24 @@ func codexSchemaMissesRequired(schema gjson.Result) bool { } return false } + +// claudeDocumentDataURL turns an inline PDF into a Codex input_file URL. Anything +// else, a file id included, is not representable and is reported by the caller. +func claudeDocumentDataURL(part gjson.Result) (string, bool) { + source := part.Get("source") + if source.Get("type").String() == "base64" { + mediaType := strings.TrimSpace(source.Get("media_type").String()) + if !strings.EqualFold(mediaType, "application/pdf") { + return "", false + } + data := source.Get("data").String() + if data == "" { + data = source.Get("base64").String() + } + if data == "" { + return "", false + } + return fmt.Sprintf("data:%s;base64,%s", mediaType, data), true + } + return "", false +} diff --git a/internal/translator/codex/claude/init.go b/internal/translator/codex/claude/init.go index eb121ece9d9..c47d7eaa941 100644 --- a/internal/translator/codex/claude/init.go +++ b/internal/translator/codex/claude/init.go @@ -4,17 +4,21 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( Claude, Codex, - ConvertClaudeRequestToCodex, + nil, interfaces.TranslateResponse{ Stream: ConvertCodexResponseToClaude, NonStream: ConvertCodexResponseToClaudeNonStream, TokenCount: ClaudeTokenCount, }, ) + sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatClaude, sdktranslator.FormatCodex, func(model string, body []byte, stream bool) ([]byte, error) { + return convertClaudeRequestToCodex(model, body, stream, false) + }) } diff --git a/internal/translator/common/parts.go b/internal/translator/common/parts.go new file mode 100644 index 00000000000..a402fabec7b --- /dev/null +++ b/internal/translator/common/parts.go @@ -0,0 +1,31 @@ +package common + +import "fmt" + +// UnsupportedPartError is a request-scoped rejection. The part type was present +// and this translation has no equivalent, so the request must not be sent with +// that part removed. +type UnsupportedPartError struct { + Type string +} + +func (e *UnsupportedPartError) Error() string { + if e == nil || e.Type == "" { + return "unsupported content part" + } + return fmt.Sprintf("unsupported content part: %s", e.Type) +} + +func (e *UnsupportedPartError) StatusCode() int { return 400 } + +func (e *UnsupportedPartError) IsRequestScoped() bool { return true } + +// ErrIfNothingLeft is the shared policy for a file part a translation cannot +// send: text beside it still goes out, but a request left with no content is +// refused rather than forwarded empty. +func ErrIfNothingLeft(droppedType string, remaining int) error { + if droppedType == "" || remaining > 0 { + return nil + } + return &UnsupportedPartError{Type: droppedType} +} diff --git a/internal/translator/gemini/claude/gemini_claude_request.go b/internal/translator/gemini/claude/gemini_claude_request.go index ed1a2c40de7..fe58d81dea3 100644 --- a/internal/translator/gemini/claude/gemini_claude_request.go +++ b/internal/translator/gemini/claude/gemini_claude_request.go @@ -31,17 +31,25 @@ const geminiClaudeThoughtSignature = "skip_thought_signature_validator" // Returns: // - []byte: The transformed request in Gemini format. func ConvertClaudeRequestToGemini(modelName string, inputRawJSON []byte, stream bool) []byte { - return convertClaudeRequestToGemini(modelName, inputRawJSON, stream, false) + body, _ := convertClaudeRequestToGemini(modelName, inputRawJSON, stream, false) + return body } // ConvertClaudeRequestToGeminiWithCompat preserves assistant thinking blocks // with empty signatures for configured compatibility endpoints. func ConvertClaudeRequestToGeminiWithCompat(modelName string, inputRawJSON []byte, stream bool) []byte { + body, _ := convertClaudeRequestToGemini(modelName, inputRawJSON, stream, true) + return body +} + +// ConvertClaudeRequestToGeminiWithCompatReturningError reports a file part the target cannot represent. +func ConvertClaudeRequestToGeminiWithCompatReturningError(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { return convertClaudeRequestToGemini(modelName, inputRawJSON, stream, true) } -func convertClaudeRequestToGemini(modelName string, inputRawJSON []byte, _ bool, preserveEmptyThinkingBlocks bool) []byte { +func convertClaudeRequestToGemini(modelName string, inputRawJSON []byte, _ bool, preserveEmptyThinkingBlocks bool) ([]byte, error) { rawJSON := inputRawJSON + var droppedAttachment string // Build output Gemini request JSON out := []byte(`{"contents":[]}`) out, _ = sjson.SetBytes(out, "model", modelName) @@ -188,20 +196,14 @@ func convertClaudeRequestToGemini(modelName string, inputRawJSON []byte, _ bool, partItems = append(partItems, imagePart) } - case "image", "document": - source := contentResult.Get("source") - if source.Get("type").String() != "base64" { - return true - } - mimeType := source.Get("media_type").String() - data := source.Get("data").String() - if mimeType == "" || data == "" { - return true + case "image", "document", "container_upload": + if part := claudeBase64InlineData(contentResult.Get("source")); part != nil { + partItems = append(partItems, part) + } else if partType := contentResult.Get("type").String(); partType != "image" { + droppedAttachment = partType } - part := []byte(`{"inline_data":{"mime_type":"","data":""}}`) - part, _ = sjson.SetBytes(part, "inline_data.mime_type", mimeType) - part, _ = sjson.SetBytes(part, "inline_data.data", data) - partItems = append(partItems, part) + default: + return true } return true }) @@ -364,7 +366,22 @@ func convertClaudeRequestToGemini(modelName string, inputRawJSON []byte, _ bool, result := out result = common.AttachDefaultSafetySettings(result, "safetySettings") - return result + return result, translatorcommon.ErrIfNothingLeft(droppedAttachment, int(gjson.GetBytes(result, "contents.#").Int())) +} + +func claudeBase64InlineData(source gjson.Result) []byte { + if source.Get("type").String() != "base64" { + return nil + } + mimeType := source.Get("media_type").String() + data := source.Get("data").String() + if mimeType == "" || data == "" { + return nil + } + part := []byte(`{"inline_data":{"mime_type":"","data":""}}`) + part, _ = sjson.SetBytes(part, "inline_data.mime_type", mimeType) + part, _ = sjson.SetBytes(part, "inline_data.data", data) + return part } func geminiContentWithParts(role string, parts [][]byte) []byte { diff --git a/internal/translator/gemini/claude/gemini_claude_request_test.go b/internal/translator/gemini/claude/gemini_claude_request_test.go index 269617ff635..b68cf8399a3 100644 --- a/internal/translator/gemini/claude/gemini_claude_request_test.go +++ b/internal/translator/gemini/claude/gemini_claude_request_test.go @@ -1,7 +1,9 @@ package claude import ( + "errors" "fmt" + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" "strings" "testing" @@ -826,3 +828,57 @@ func TestConvertClaudeRequestToGemini_Issue5960_DocumentPreservation(t *testing. t.Fatalf("expected 0 contents turns instead of empty parts turn, got: %s", string(unsupportedOut)) } } + +func TestConvertClaudeRequestToGemini_ContainerUploadKeepsOtherText(t *testing.T) { + inputJSON := []byte(`{ + "model": "gemini-3-flash-preview", + "messages": [{"role": "user", "content": [ + {"type": "text", "text": "keep me"}, + {"type": "container_upload", "file_id": "file-example"} + ]}] + }`) + output := ConvertClaudeRequestToGemini("gemini-3-flash-preview", inputJSON, false) + parts := gjson.GetBytes(output, "contents.0.parts").Array() + if len(parts) != 1 || parts[0].Get("text").String() != "keep me" { + t.Fatalf("text was dropped with the file: %s", output) + } +} + +func TestConvertClaudeRequestToGemini_UnsendableFileNamesTheDroppedPart(t *testing.T) { + for partType, block := range map[string]string{ + "container_upload": `{"type": "container_upload", "file_id": "file-example"}`, + "document": `{"type": "document", "source": {"type": "file", "file_id": "file-example"}}`, + } { + inputJSON := []byte(`{ + "model": "gemini-3-flash-preview", + "messages": [{"role": "user", "content": [` + block + `]}] + }`) + output, err := ConvertClaudeRequestToGeminiWithCompatReturningError("gemini-3-flash-preview", inputJSON, false) + if err == nil { + t.Fatalf("%s: expected unsupported part error, output=%s", partType, output) + } + if got, want := err.Error(), "unsupported content part: "+partType; got != want { + t.Fatalf("error = %q, want %q", got, want) + } + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(err, &unsupported) || unsupported.StatusCode() != 400 || !unsupported.IsRequestScoped() { + t.Fatalf("%s: error = %#v", partType, err) + } + } +} + +func TestConvertClaudeRequestToGemini_ImageURLAndRedactedThinkingStaySkipped(t *testing.T) { + inputJSON := []byte(`{ + "model": "gemini-3-flash-preview", + "messages": [{"role": "user", "content": [ + {"type": "text", "text": "keep me"}, + {"type": "image", "source": {"type": "url", "url": "https://example.test/a.png"}}, + {"type": "redacted_thinking", "data": "abc"} + ]}] + }`) + output := ConvertClaudeRequestToGemini("gemini-3-flash-preview", inputJSON, false) + parts := gjson.GetBytes(output, "contents.0.parts").Array() + if len(parts) != 1 || parts[0].Get("text").String() != "keep me" { + t.Fatalf("old skip paths changed the turn: %s", output) + } +} diff --git a/internal/translator/gemini/claude/init.go b/internal/translator/gemini/claude/init.go index a7f510c8edb..357c131d5b9 100644 --- a/internal/translator/gemini/claude/init.go +++ b/internal/translator/gemini/claude/init.go @@ -4,17 +4,21 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( Claude, Gemini, - ConvertClaudeRequestToGemini, + nil, interfaces.TranslateResponse{ Stream: ConvertGeminiResponseToClaude, NonStream: ConvertGeminiResponseToClaudeNonStream, TokenCount: ClaudeTokenCount, }, ) + sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatClaude, sdktranslator.FormatGemini, func(model string, body []byte, stream bool) ([]byte, error) { + return convertClaudeRequestToGemini(model, body, stream, false) + }) } diff --git a/internal/translator/gemini/openai/chat-completions/gemini_openai_file_id_test.go b/internal/translator/gemini/openai/chat-completions/gemini_openai_file_id_test.go new file mode 100644 index 00000000000..449bc61d895 --- /dev/null +++ b/internal/translator/gemini/openai/chat-completions/gemini_openai_file_id_test.go @@ -0,0 +1,47 @@ +package chat_completions + +import ( + "context" + "errors" + "testing" + + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +func TestConvertOpenAIRequestToGemini_FileID(t *testing.T) { + const ( + text = `{"type":"text","text":"read it"}` + missing = `{"type":"file","file":{"file_id":"file-absent"}}` + ) + cases := []struct { + name, content string + wantErr bool + wantParts int + }{ + {name: "unknown file id alone", content: missing, wantErr: true}, + {name: "text beside an unknown file id", content: text + "," + missing, wantParts: 1}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + payload := `{"model":"gemini-2.5-pro","messages":[{"role":"user","content":[` + tc.content + `]}]}` + got := sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatOpenAI, sdktranslator.FormatGemini, + sdktranslator.RequestEnvelope{Format: sdktranslator.FormatOpenAI, Model: "gemini-2.5-pro", Body: []byte(payload)}) + + var part *translatorcommon.UnsupportedPartError + if tc.wantErr { + if !errors.As(got.Err, &part) || part.Type != "file" { + t.Fatalf("err = %v, want unsupported file", got.Err) + } + return + } + if got.Err != nil { + t.Fatalf("err = %v", got.Err) + } + if n := int(gjson.GetBytes(got.Body, "contents.0.parts.#").Int()); n != tc.wantParts { + t.Fatalf("parts = %d, want %d. Output: %s", n, tc.wantParts, got.Body) + } + }) + } +} diff --git a/internal/translator/gemini/openai/chat-completions/gemini_openai_request.go b/internal/translator/gemini/openai/chat-completions/gemini_openai_request.go index b4c0ec53721..58b87d545b9 100644 --- a/internal/translator/gemini/openai/chat-completions/gemini_openai_request.go +++ b/internal/translator/gemini/openai/chat-completions/gemini_openai_request.go @@ -26,8 +26,16 @@ const geminiFunctionThoughtSignature = "skip_thought_signature_validator" // // Returns: // - []byte: The transformed request data in Gemini API format -func ConvertOpenAIRequestToGemini(modelName string, inputRawJSON []byte, _ bool) []byte { +func ConvertOpenAIRequestToGemini(modelName string, inputRawJSON []byte, stream bool) []byte { + body, _ := convertOpenAIRequestToGemini(modelName, inputRawJSON, stream) + return body +} + +// convertOpenAIRequestToGemini also reports a file part Gemini cannot receive +// when nothing else was left to send. +func convertOpenAIRequestToGemini(modelName string, inputRawJSON []byte, _ bool) ([]byte, error) { rawJSON := inputRawJSON + var droppedAttachment string // Base envelope (no default thinkingConfig) out := []byte(`{"contents":[]}`) @@ -174,6 +182,7 @@ func ConvertOpenAIRequestToGemini(modelName string, inputRawJSON []byte, _ bool) partItems = append(partItems, geminiInlineDataPart(mimeType, data, "")) } else { log.Warn("Invalid file data or unknown file name extension in user message, skip") + droppedAttachment = "file" } case "input_audio": audioData := item.Get("input_audio.data").String() @@ -537,7 +546,7 @@ func ConvertOpenAIRequestToGemini(modelName string, inputRawJSON []byte, _ bool) out = common.AttachDefaultSafetySettings(out, "safetySettings") - return out + return out, translatorcommon.ErrIfNothingLeft(droppedAttachment, int(gjson.GetBytes(out, "contents.#").Int())) } func geminiTextPart(text string) []byte { diff --git a/internal/translator/gemini/openai/chat-completions/init.go b/internal/translator/gemini/openai/chat-completions/init.go index 2631f8f93af..a00a836357f 100644 --- a/internal/translator/gemini/openai/chat-completions/init.go +++ b/internal/translator/gemini/openai/chat-completions/init.go @@ -4,16 +4,18 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( OpenAI, Gemini, - ConvertOpenAIRequestToGemini, + nil, interfaces.TranslateResponse{ Stream: ConvertGeminiResponseToOpenAI, NonStream: ConvertGeminiResponseToOpenAINonStream, }, ) + sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatOpenAI, sdktranslator.FormatGemini, convertOpenAIRequestToGemini) } diff --git a/internal/translator/interactions/claude/init.go b/internal/translator/interactions/claude/init.go index 502f1530c40..93ccc6311b3 100644 --- a/internal/translator/interactions/claude/init.go +++ b/internal/translator/interactions/claude/init.go @@ -4,16 +4,20 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( Claude, Interactions, - ConvertClaudeRequestToInteractions, + nil, interfaces.TranslateResponse{ Stream: ConvertInteractionsResponseToClaude, NonStream: ConvertInteractionsResponseToClaudeNonStream, }, ) + sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatClaude, sdktranslator.FormatInteractions, func(model string, body []byte, stream bool) ([]byte, error) { + return convertClaudeRequestToInteractions(model, body, stream, false) + }) } diff --git a/internal/translator/interactions/claude/interactions_claude_request.go b/internal/translator/interactions/claude/interactions_claude_request.go index 07f4ef4b052..e570a257b56 100644 --- a/internal/translator/interactions/claude/interactions_claude_request.go +++ b/internal/translator/interactions/claude/interactions_claude_request.go @@ -9,16 +9,23 @@ import ( ) func ConvertClaudeRequestToInteractions(modelName string, inputRawJSON []byte, stream bool) []byte { - return convertClaudeRequestToInteractions(modelName, inputRawJSON, stream, false) + body, _ := convertClaudeRequestToInteractions(modelName, inputRawJSON, stream, false) + return body } // ConvertClaudeRequestToInteractionsWithCompat preserves empty assistant // thinking blocks for configured compatibility endpoints. func ConvertClaudeRequestToInteractionsWithCompat(modelName string, inputRawJSON []byte, stream bool) []byte { + body, _ := convertClaudeRequestToInteractions(modelName, inputRawJSON, stream, true) + return body +} + +// ConvertClaudeRequestToInteractionsWithCompatReturningError reports a file part the target cannot represent. +func ConvertClaudeRequestToInteractionsWithCompatReturningError(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { return convertClaudeRequestToInteractions(modelName, inputRawJSON, stream, true) } -func convertClaudeRequestToInteractions(modelName string, inputRawJSON []byte, stream, preserveEmptyThinkingBlocks bool) []byte { +func convertClaudeRequestToInteractions(modelName string, inputRawJSON []byte, stream, preserveEmptyThinkingBlocks bool) ([]byte, error) { root := gjson.ParseBytes(inputRawJSON) out := []byte(`{"model":"","input":[]}`) out, _ = sjson.SetBytes(out, "model", firstNonEmpty(modelName, root.Get("model").String())) @@ -27,9 +34,9 @@ func convertClaudeRequestToInteractions(modelName string, inputRawJSON []byte, s } out = copyClaudeSystemToInteractions(out, root) out = copyClaudeGenerationConfigToInteractions(out, root) - out = appendClaudeMessagesToInteractions(out, root.Get("messages"), preserveEmptyThinkingBlocks) + out, droppedAttachment := appendClaudeMessagesToInteractions(out, root.Get("messages"), preserveEmptyThinkingBlocks) out = copyClaudeToolsToInteractions(out, root) - return out + return out, translatorcommon.ErrIfNothingLeft(droppedAttachment, int(gjson.GetBytes(out, "input.#").Int())) } func claudeRequestStreamValue(root gjson.Result, stream bool) (bool, bool) { @@ -122,10 +129,11 @@ func copyClaudeToolChoiceToInteractions(out []byte, toolChoice gjson.Result) []b return out } -func appendClaudeMessagesToInteractions(out []byte, messages gjson.Result, preserveEmptyThinkingBlocks bool) []byte { +func appendClaudeMessagesToInteractions(out []byte, messages gjson.Result, preserveEmptyThinkingBlocks bool) ([]byte, string) { if !messages.Exists() || !messages.IsArray() { - return out + return out, "" } + droppedAttachment := "" inputItems := translatorcommon.NewRawArrayItems(messages.Get("#").Int()) var pendingToolUseIDs []string var pendingSystemReminders [][]byte @@ -152,7 +160,7 @@ func appendClaudeMessagesToInteractions(out []byte, messages gjson.Result, prese } pendingToolUseIDs = nil - appendClaudeMessageToInteractions(&inputItems, &pendingToolUseIDs, &pendingSystemReminders, toolNamesByID, role, content, preserveEmptyThinkingBlocks) + appendClaudeMessageToInteractions(&inputItems, &pendingToolUseIDs, &pendingSystemReminders, toolNamesByID, role, content, preserveEmptyThinkingBlocks, &droppedAttachment) if len(pendingSystemReminders) > 0 { inputItems = append(inputItems, pendingSystemReminders...) pendingSystemReminders = nil @@ -163,10 +171,10 @@ func appendClaudeMessagesToInteractions(out []byte, messages gjson.Result, prese inputItems = append(inputItems, pendingSystemReminders...) } out = translatorcommon.SetRawArrayItems(out, "input", inputItems) - return out + return out, droppedAttachment } -func appendClaudeMessageToInteractions(items *[][]byte, pendingToolUseIDs *[]string, pendingSystemReminders *[][]byte, toolNamesByID map[string]string, role string, content gjson.Result, preserveEmptyThinkingBlocks bool) { +func appendClaudeMessageToInteractions(items *[][]byte, pendingToolUseIDs *[]string, pendingSystemReminders *[][]byte, toolNamesByID map[string]string, role string, content gjson.Result, preserveEmptyThinkingBlocks bool, droppedAttachment *string) { defaultStepType := "user_input" if role == "assistant" { defaultStepType = "model_output" @@ -218,7 +226,7 @@ func appendClaudeMessageToInteractions(items *[][]byte, pendingToolUseIDs *[]str step, _ = sjson.SetBytes(step, "content.0.text", text) *items = append(*items, step) } - case "image", "document": + case "image", "document", "container_upload": if mediaPart, ok := claudeMediaPartToInteractions(part, partType); ok { if pendingSystemReminders != nil && len(*pendingSystemReminders) > 0 { flushContent() @@ -226,6 +234,8 @@ func appendClaudeMessageToInteractions(items *[][]byte, pendingToolUseIDs *[]str *pendingSystemReminders = nil } stepContent = append(stepContent, mediaPart) + } else if droppedAttachment != nil { + *droppedAttachment = partType } case "tool_use": flushContent() @@ -327,7 +337,7 @@ func claudeToolResultToInteractions(part gjson.Result, toolNamesByID map[string] } else if raw := strings.TrimSpace(item.Raw); raw != "" { contentItems = append(contentItems, []byte(raw)) } - case "image", "document": + case "image", "document", "container_upload": if mediaPart, ok := claudeMediaPartToInteractions(item, itemType); ok { contentItems = append(contentItems, mediaPart) } else if raw := strings.TrimSpace(item.Raw); raw != "" { diff --git a/internal/translator/openai/claude/init.go b/internal/translator/openai/claude/init.go index ba35bd9b78c..8b541fc51a0 100644 --- a/internal/translator/openai/claude/init.go +++ b/internal/translator/openai/claude/init.go @@ -4,17 +4,21 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( Claude, OpenAI, - ConvertClaudeRequestToOpenAI, + nil, interfaces.TranslateResponse{ Stream: ConvertOpenAIResponseToClaude, NonStream: ConvertOpenAIResponseToClaudeNonStream, TokenCount: ClaudeTokenCount, }, ) + sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatClaude, sdktranslator.FormatOpenAI, func(model string, body []byte, stream bool) ([]byte, error) { + return convertClaudeRequestToOpenAI(model, body, stream, false) + }) } diff --git a/internal/translator/openai/claude/openai_claude_request.go b/internal/translator/openai/claude/openai_claude_request.go index dd0823a406b..9d3a46fd68f 100644 --- a/internal/translator/openai/claude/openai_claude_request.go +++ b/internal/translator/openai/claude/openai_claude_request.go @@ -6,6 +6,7 @@ package claude import ( + "encoding/base64" "strings" sigcompat "github.com/router-for-me/CLIProxyAPI/v8/internal/signature" @@ -20,17 +21,25 @@ import ( // It extracts the model name, system instruction, message contents, and tool declarations // from the raw JSON request and returns them in the format expected by the OpenAI API. func ConvertClaudeRequestToOpenAI(modelName string, inputRawJSON []byte, stream bool) []byte { - return convertClaudeRequestToOpenAI(modelName, inputRawJSON, stream, false) + body, _ := convertClaudeRequestToOpenAI(modelName, inputRawJSON, stream, false) + return body } // ConvertClaudeRequestToOpenAIWithCompat preserves assistant thinking text // for configured compatibility endpoints. func ConvertClaudeRequestToOpenAIWithCompat(modelName string, inputRawJSON []byte, stream bool) []byte { + body, _ := convertClaudeRequestToOpenAI(modelName, inputRawJSON, stream, true) + return body +} + +// ConvertClaudeRequestToOpenAIWithCompatReturningError reports a file part the target cannot represent. +func ConvertClaudeRequestToOpenAIWithCompatReturningError(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { return convertClaudeRequestToOpenAI(modelName, inputRawJSON, stream, true) } -func convertClaudeRequestToOpenAI(modelName string, inputRawJSON []byte, stream bool, preserveThinkingBlocks bool) []byte { +func convertClaudeRequestToOpenAI(modelName string, inputRawJSON []byte, stream bool, preserveThinkingBlocks bool) ([]byte, error) { rawJSON := inputRawJSON + var droppedAttachment string // Base OpenAI Chat Completions API template out := []byte(`{"model":"","messages":[]}`) @@ -207,9 +216,11 @@ func convertClaudeRequestToOpenAI(modelName string, inputRawJSON []byte, stream case "redacted_thinking": // Explicitly ignore redacted_thinking - never map to reasoning_content (AC2) - case "text", "image": + case "text", "image", "document", "container_upload": if contentItem, ok := convertClaudeContentPart(part); ok { contentItems = append(contentItems, []byte(contentItem)) + } else if partType := part.Get("type").String(); partType == "document" || partType == "container_upload" { + droppedAttachment = partType } case "tool_use": @@ -422,7 +433,7 @@ func convertClaudeRequestToOpenAI(modelName string, inputRawJSON []byte, stream out, _ = sjson.SetBytes(out, "user", user.String()) } - return out + return out, translatorcommon.ErrIfNothingLeft(droppedAttachment, int(gjson.GetBytes(out, "messages.#").Int())) } func normalizeObjectSchemaProperties(schema any) any { @@ -557,11 +568,42 @@ func convertClaudeContentPart(part gjson.Result) (string, bool) { return string(imageContent), true + case "document", "container_upload": + return convertClaudeFilePartToOpenAI(part) + default: return "", false } } +// convertClaudeFilePartToOpenAI emits an OpenAI file part for inline base64 bytes. +// A file id carries none, so it stays unconverted and the caller reports it. +func convertClaudeFilePartToOpenAI(part gjson.Result) (string, bool) { + source := part.Get("source") + mimeType := source.Get("media_type").String() + + var data []byte + if source.Get("type").String() == "base64" { + decoded, errDecode := base64.StdEncoding.DecodeString(strings.TrimSpace(source.Get("data").String())) + if errDecode != nil { + return "", false + } + data = decoded + } + + if len(data) == 0 { + return "", false + } + if mimeType == "" { + mimeType = "application/octet-stream" + } + + fileContent := []byte(`{"type":"file","file":{"filename":"","file_data":""}}`) + fileContent, _ = sjson.SetBytes(fileContent, "file.filename", part.Get("filename").String()) + fileContent, _ = sjson.SetBytes(fileContent, "file.file_data", "data:"+mimeType+";base64,"+base64.StdEncoding.EncodeToString(data)) + return string(fileContent), true +} + // toolResultImagePlaceholder keeps the OpenAI tool message non-empty when a Claude // tool_result carried nothing but images. const toolResultImagePlaceholder = "[Tool returned image content; the images follow in the next user message.]" diff --git a/internal/translator/openai/claude/openai_claude_request_test.go b/internal/translator/openai/claude/openai_claude_request_test.go index d3865781fa8..98a04a9f147 100644 --- a/internal/translator/openai/claude/openai_claude_request_test.go +++ b/internal/translator/openai/claude/openai_claude_request_test.go @@ -1,10 +1,13 @@ package claude import ( + "context" "encoding/base64" "fmt" + "strings" "testing" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" "github.com/tidwall/gjson" ) @@ -1767,3 +1770,56 @@ func TestConvertClaudeRequestToOpenAI_NormalizesBooleanSubschemas(t *testing.T) t.Fatalf("enabled_flag.enum.1 should remain boolean false, got: %s", enum1.Raw) } } + +func TestConvertClaudeRequestToOpenAI_UncachedFileKeepsOldDrop(t *testing.T) { + input := []byte(`{"model":"gpt-5","messages":[{"role":"user","content":[{"type":"text","text":"read"},{"type":"container_upload","file_id":"file-absent"}]}]}`) + output := string(ConvertClaudeRequestToOpenAI("gpt-5", input, false)) + if strings.Contains(output, "file_data") { + t.Fatalf("output = %s", output) + } + if !strings.Contains(output, `"text":"read"`) { + t.Fatalf("text was lost: %s", output) + } +} + +func claudeToOpenAIEnvelope(model string, input []byte) sdktranslator.RequestEnvelope { + return sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatClaude, sdktranslator.FormatOpenAI, sdktranslator.RequestEnvelope{ + Format: sdktranslator.FormatClaude, + Model: model, + Body: input, + }) +} + +func TestClaudeFileOnlyRequestSurfacesUnsupportedPart(t *testing.T) { + input := []byte(`{"model":"gpt-5","messages":[{"role":"user","content":[{"type":"container_upload","file_id":"file-absent"}]}]}`) + envelope := claudeToOpenAIEnvelope("gpt-5", input) + if envelope.Err == nil { + t.Fatalf("expected an unsupported part error, body = %s", envelope.Body) + } + if !strings.Contains(envelope.Err.Error(), "container_upload") { + t.Fatalf("err = %v", envelope.Err) + } +} + +func TestClaudeBase64DocumentBecomesFilePart(t *testing.T) { + input := []byte(`{"model":"gpt-5","messages":[{"role":"user","content":[{"type":"document","source":{"type":"base64","media_type":"application/pdf","data":"JVBERi0xLjQK"}}]}]}`) + envelope := claudeToOpenAIEnvelope("gpt-5", input) + if envelope.Err != nil { + t.Fatalf("err = %v", envelope.Err) + } + part := gjson.GetBytes(envelope.Body, "messages.0.content.0") + if part.Get("type").String() != "file" || part.Get("file.file_data").String() != "data:application/pdf;base64,JVBERi0xLjQK" { + t.Fatalf("part = %s, body = %s", part.Raw, envelope.Body) + } +} + +func TestClaudeTextWithUncachedFileKeepsText(t *testing.T) { + input := []byte(`{"model":"gpt-5","messages":[{"role":"user","content":[{"type":"text","text":"read"},{"type":"container_upload","file_id":"file-absent"}]}]}`) + envelope := claudeToOpenAIEnvelope("gpt-5", input) + if envelope.Err != nil { + t.Fatalf("err = %v", envelope.Err) + } + if !strings.Contains(string(envelope.Body), `"text":"read"`) { + t.Fatalf("body = %s", envelope.Body) + } +} diff --git a/sdk/api/handlers/handlers_error_response_test.go b/sdk/api/handlers/handlers_error_response_test.go index be10180b953..62a0731c0d3 100644 --- a/sdk/api/handlers/handlers_error_response_test.go +++ b/sdk/api/handlers/handlers_error_response_test.go @@ -17,6 +17,7 @@ import ( "github.com/router-for-me/CLIProxyAPI/v8/internal/clienterror" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" coreexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" sdkconfig "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" @@ -909,6 +910,17 @@ func TestStatusFromErrorMapsContextStatuses(t *testing.T) { } } +func TestExecutionErrorMessage_UnsupportedPartKeepsNameAnd400(t *testing.T) { + err := &translatorcommon.UnsupportedPartError{Type: "container_upload"} + msg := ExecutionErrorMessage(err) + if msg == nil || msg.StatusCode != http.StatusBadRequest { + t.Fatalf("status = %v", msg) + } + if msg.Error == nil || !strings.Contains(msg.Error.Error(), "container_upload") { + t.Fatalf("part name lost: %v", msg.Error) + } +} + func TestWriteErrorResponse_ContextCanceledUses499(t *testing.T) { gin.SetMode(gin.TestMode) recorder := httptest.NewRecorder() diff --git a/sdk/translator/pipeline.go b/sdk/translator/pipeline.go index 569b9326010..5cd2e9acc15 100644 --- a/sdk/translator/pipeline.go +++ b/sdk/translator/pipeline.go @@ -15,6 +15,8 @@ type RequestEnvelope struct { ModelInfo *registry.ModelInfo // ConfigurationUpdatesChanged reports that a plugin normalizer modified Responses updates. ConfigurationUpdatesChanged bool + // Err is a request-scoped translation failure. Callers must not send Body upstream when it is set. + Err error } // ResponseEnvelope represents a response in the translation pipeline. diff --git a/sdk/translator/registry.go b/sdk/translator/registry.go index b04411614b2..c05371649ad 100644 --- a/sdk/translator/registry.go +++ b/sdk/translator/registry.go @@ -60,6 +60,15 @@ func (r *Registry) RegisterRequestEnvelope(from, to Format, request RequestEnvel } } +// RegisterCheckedRequest stores a request translator that may refuse a request, +// carrying the refusal on the envelope next to the legacy-shaped body. +func (r *Registry) RegisterCheckedRequest(from, to Format, request func(model string, body []byte, stream bool) ([]byte, error)) { + r.RegisterRequestEnvelope(from, to, func(_ context.Context, req RequestEnvelope) RequestEnvelope { + req.Body, req.Err = request(req.Model, req.Body, req.Stream) + return req + }) +} + // Unregister removes the request and response transforms for one format pair. // Empty parent maps are dropped so a temporary registration can be restored. func (r *Registry) Unregister(from, to Format) { From efe96bff0fa937fef17bee6f36e2b5fdd2d531f7 Mon Sep 17 00:00:00 2001 From: Supra4E8C Date: Wed, 7 Oct 2026 20:05:48 +0800 Subject: [PATCH 081/142] refactor: remove testModel field from models and update related logic --- .../sheets/forms/BaseProviderForm.tsx | 16 +-- .../sheets/forms/SponsorProviderForm.tsx | 1 - src/features/providers/types.ts | 3 +- .../providers/useProviderWorkbench.ts | 2 - src/i18n/locales/en.json | 2 +- src/i18n/locales/ru.json | 2 +- src/i18n/locales/vi.json | 2 +- src/i18n/locales/zh-CN.json | 2 +- src/i18n/locales/zh-TW.json | 2 +- src/services/api/providers.ts | 28 +++- src/services/api/transformers.ts | 6 - src/types/provider.ts | 2 - tests/providerTestModel.test.ts | 135 ++++++++++++++++++ 13 files changed, 166 insertions(+), 37 deletions(-) create mode 100644 tests/providerTestModel.test.ts diff --git a/src/features/providers/sheets/forms/BaseProviderForm.tsx b/src/features/providers/sheets/forms/BaseProviderForm.tsx index af7aed8e935..3f17bd406af 100644 --- a/src/features/providers/sheets/forms/BaseProviderForm.tsx +++ b/src/features/providers/sheets/forms/BaseProviderForm.tsx @@ -135,7 +135,6 @@ function buildInitialForm( name: m.name, alias: m.alias ?? '', priority: m.priority, - testModel: m.testModel, image: m.image === true, thinkingJson: formatJsonObject(m.thinking), ...readModelOptions(m), @@ -145,7 +144,7 @@ function buildInitialForm( ? Object.entries(cfg.headers).map(([k, v]) => ({ key: k, value: String(v) })) : [emptyHeader()], excludedModelsText: '', - testModel: cfg.testModel ?? '', + testModel: '', apiKeyEntries: cfg.apiKeyEntries?.length ? cfg.apiKeyEntries.map((entry) => ({ apiKey: '', @@ -184,7 +183,6 @@ function buildInitialForm( name: m.name, alias: m.alias ?? '', priority: m.priority, - testModel: m.testModel, thinkingJson: formatJsonObject(m.thinking), ...readModelOptions(m), })) @@ -663,17 +661,7 @@ export function BaseProviderForm({
onChange({ githubToken: e.target.value })} + disabled={disabled} + hint={t('config_management.visual.sections.server.github_token_hint')} + /> + + = { codexLiveMediaRelayICEServers: ['codexLiveMediaRelayICEServers'], // ── connectivity ────────────────────────────────────────────────────────── + githubToken: ['githubToken'], trustedProxies: ['trustedProxies'], discoveryEnabled: ['discoveryEnabled'], discoveryServiceName: ['discoveryServiceName'], diff --git a/src/features/config/searchIndex.ts b/src/features/config/searchIndex.ts index dd08fa7a514..32828cefd44 100644 --- a/src/features/config/searchIndex.ts +++ b/src/features/config/searchIndex.ts @@ -222,6 +222,14 @@ export const CONFIG_FIELD_SEARCH_INDEX: ConfigFieldSearchEntry[] = [ }, // ── connectivity ────────────────────────────────────────────────────────── + { + fieldId: 'githubToken', + sectionId: 'connectivity', + labelKey: L('sections.server.github_token'), + hintKey: L('sections.server.github_token_hint'), + yamlKeys: ['server', 'github-token'], + keywords: ['GITHUB_TOKEN', 'GitHub', 'token'], + }, { fieldId: 'trustedProxies', sectionId: 'connectivity', diff --git a/src/features/config/visualConfigServer.ts b/src/features/config/visualConfigServer.ts index c7c6daac960..05d21974741 100644 --- a/src/features/config/visualConfigServer.ts +++ b/src/features/config/visualConfigServer.ts @@ -6,6 +6,7 @@ import { readConfigBoolean } from './visualConfigBoolean'; // Backend: config_v8.go, trusted_proxies.go and discovery/service.go. export const SERVER_FIELDS = [ + { key: 'githubToken', path: ['server', 'github-token'], kind: 'string' }, { key: 'trustedProxies', path: ['server', 'trusted-proxies'], kind: 'list' }, { key: 'discoveryEnabled', path: ['server', 'discovery', 'enabled'], kind: 'boolean' }, { key: 'discoveryServiceName', path: ['server', 'discovery', 'service-name'], kind: 'string' }, diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json index cce6e2476eb..c706c7f5c56 100644 --- a/src/i18n/locales/en.json +++ b/src/i18n/locales/en.json @@ -1263,6 +1263,8 @@ "signature_title": "Signature Validation" }, "server": { + "github_token": "Global GitHub Token", + "github_token_hint": "Used for server-side GitHub requests, such as panel updates and plugin downloads. Takes precedence over GITHUB_TOKEN; leave empty to use environment credentials, or unauthenticated requests if none are set. Matching plugin store authentication rules take precedence.", "host": "Host Address", "port": "Port" }, diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index 55c9287989f..b1e03819d39 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -1266,6 +1266,8 @@ "signature_title": "Проверка подписей" }, "server": { + "github_token": "Глобальный токен GitHub", + "github_token_hint": "Используется для серверных запросов к GitHub, например обновлений панели и загрузки плагинов. Имеет приоритет над GITHUB_TOKEN; пустое значение использует учётные данные из окружения, а при их отсутствии — анонимные запросы. Совпадающие правила авторизации магазина плагинов имеют приоритет.", "host": "Адрес хоста", "port": "Порт" }, diff --git a/src/i18n/locales/vi.json b/src/i18n/locales/vi.json index c9a8320acac..c203830923d 100644 --- a/src/i18n/locales/vi.json +++ b/src/i18n/locales/vi.json @@ -1055,6 +1055,8 @@ "devin_title": "Devin" }, "server": { + "github_token": "Token GitHub toàn cục", + "github_token_hint": "Dùng cho các yêu cầu GitHub từ máy chủ, như cập nhật bảng điều khiển và tải plugin. Ưu tiên hơn GITHUB_TOKEN; để trống để dùng thông tin xác thực từ biến môi trường, hoặc gửi yêu cầu ẩn danh nếu chưa thiết lập. Các quy tắc xác thực phù hợp của kho plugin được ưu tiên.", "host": "Địa chỉ Host", "port": "Cổng" }, diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index a241c6ef599..b2b433332e4 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -1262,6 +1262,8 @@ "signature_title": "签名校验" }, "server": { + "github_token": "全局 GitHub 令牌", + "github_token_hint": "用于面板更新、插件下载等服务端 GitHub 请求。优先于 GITHUB_TOKEN;留空时使用环境变量凭据,未设置凭据则匿名请求。插件商店匹配的认证规则优先。", "host": "主机地址", "port": "端口" }, diff --git a/src/i18n/locales/zh-TW.json b/src/i18n/locales/zh-TW.json index 91e01dc772a..182acee89dc 100644 --- a/src/i18n/locales/zh-TW.json +++ b/src/i18n/locales/zh-TW.json @@ -1288,6 +1288,8 @@ "signature_title": "簽章驗證" }, "server": { + "github_token": "全域 GitHub 權杖", + "github_token_hint": "用於面板更新、外掛下載等伺服器端 GitHub 請求。優先於 GITHUB_TOKEN;留空時使用環境變數憑證,未設定憑證則匿名請求。外掛商店符合的驗證規則優先。", "host": "主機位址", "port": "連接埠" }, diff --git a/src/types/visualConfig.ts b/src/types/visualConfig.ts index 24b3c6281d7..c95d3c64bd8 100644 --- a/src/types/visualConfig.ts +++ b/src/types/visualConfig.ts @@ -117,6 +117,7 @@ export type PluginStoreAuthRule = { /** UI draft keys; YAML persistence uses the v8 tree, not these flattened names. */ export type VisualConfigValues = { + githubToken: string; trustedProxies: string[]; discoveryEnabled: boolean; discoveryServiceName: string; @@ -221,6 +222,7 @@ export const makeClientId = () => { }; export const DEFAULT_VISUAL_VALUES: VisualConfigValues = { + githubToken: '', trustedProxies: [], discoveryEnabled: false, discoveryServiceName: '', diff --git a/tests/visualConfigGitHubToken.test.ts b/tests/visualConfigGitHubToken.test.ts new file mode 100644 index 00000000000..5b21febcab4 --- /dev/null +++ b/tests/visualConfigGitHubToken.test.ts @@ -0,0 +1,99 @@ +import { describe, expect, test } from 'bun:test'; +import { createElement } from 'react'; +import { renderToStaticMarkup } from 'react-dom/server'; +import { I18nextProvider } from 'react-i18next'; +import { parseDocument } from 'yaml'; +import i18n from '@/i18n'; +import { SectionConnectivity } from '@/features/config/components/sections/SectionConnectivity'; +import { findConfigFieldById, searchConfigFields } from '@/features/config/searchIndex'; +import { DEFAULT_VISUAL_VALUES } from '@/types/visualConfig'; +import { runVisualConfig } from './helpers/visualConfig'; + +const source = `# config +server: + github-token: fixture-token # credential + future: preserved +plugins: + store-auth: + - match: https://api.github.com/ + type: none +`; + +describe('global GitHub token configuration', () => { + test('loads, replaces and clears the canonical field without changing store auth', () => { + expect(runVisualConfig(source).visualValues.githubToken).toBe('fixture-token'); + for (const token of [' replacement-fixture ', '']) { + const config = runVisualConfig(source, [{ githubToken: token }]); + expect([...config.visualDirtyFields]).toEqual(['githubToken']); + const output = config.applyVisualChangesToYaml(source); + const expected = parseDocument(source).toJS(); + expected.server['github-token'] = token.trim(); + expect(parseDocument(output).toJS()).toEqual(expected); + expect(output).toContain('# credential'); + expect(runVisualConfig(output).visualValues.githubToken).toBe(token.trim()); + } + }); + + test('preserves untouched tokens and does not materialize an absent token', () => { + const config = runVisualConfig(source, [{ port: '9000' }]); + expect( + parseDocument(config.applyVisualChangesToYaml(source)).getIn(['server', 'github-token']) + ).toBe('fixture-token'); + for (const yaml of ['{}', 'server: null', 'server: {github-token: null}']) { + const loaded = runVisualConfig(yaml); + expect(loaded.visualValues.githubToken).toBe(''); + expect(parseDocument(loaded.applyVisualChangesToYaml(yaml)).toJS()).toEqual( + parseDocument(yaml).toJS() + ); + const edited = runVisualConfig(yaml, [{ githubToken: 'fixture-token' }]); + expect( + parseDocument(edited.applyVisualChangesToYaml(yaml)).getIn(['server', 'github-token']) + ).toBe('fixture-token'); + } + }); + + test('registers the canonical search path', () => { + expect(findConfigFieldById('githubToken')).toMatchObject({ + sectionId: 'connectivity', + yamlKeys: ['server', 'github-token'], + }); + expect( + searchConfigFields('server.github-token', () => '').map((entry) => entry.fieldId) + ).toContain('githubToken'); + }); + + test('renders a masked, labelled input with localized hints and disabled support', () => { + for (const lng of ['en', 'zh-CN', 'zh-TW', 'ru', 'vi']) { + const translations = i18n.cloneInstance({ lng }); + const key = 'config_management.visual.sections.server.github_token'; + for (const path of [key, `${key}_hint`]) { + expect(typeof translations.getResource(lng, 'translation', path)).toBe('string'); + } + for (const disabled of [false, true]) { + const markup = renderToStaticMarkup( + createElement( + I18nextProvider, + { i18n: translations }, + createElement(SectionConnectivity, { + values: DEFAULT_VISUAL_VALUES, + disabled, + onChange: () => {}, + }) + ) + ); + const field = markup + .split('id="cfg-field-githubToken"')[1] + .split('id="cfg-field-trustedProxies"')[0]; + const input = field.match(/]*>/)?.[0] ?? ''; + expect(input).toContain('type="password"'); + expect(input).toContain('autoComplete="new-password"'); + expect(input.includes('disabled=""')).toBe(disabled); + const id = input.match(/\bid="([^"]+)"/)?.[1]; + expect(id).toBeTruthy(); + expect(field).toContain(`for="${id}"`); + expect(field).toContain(`id="${id}-hint"`); + expect(input).toContain(`aria-describedby="${id}-hint"`); + } + } + }); +}); From 90654da573200bc4d910982a35f2d3ca4da2f8a5 Mon Sep 17 00:00:00 2001 From: Jellyfish Date: Thu, 8 Oct 2026 00:56:02 +0800 Subject: [PATCH 091/142] feat(xai): dynamically fetch latest Grok CLI version from npm registry with fallback - Fetch latest @xai-official/grok client version from npm registry on startup - Periodically refresh Grok CLI version every 3 hours without multiple retries - Update hardcoded fallback version to 1.0.50 if npm registry is unreachable - Dynamically inject active version into x-grok-client-version and User-Agent headers --- cmd/server/main.go | 3 + .../runtime/executor/helps/xai_version.go | 178 ++++++++++++++++++ .../executor/helps/xai_version_test.go | 143 ++++++++++++++ .../executor/xai_client_version_test.go | 23 +++ internal/runtime/executor/xai_executor.go | 15 +- .../runtime/executor/xai_executor_request.go | 5 +- sdk/cliproxy/service_lifecycle.go | 2 + 7 files changed, 366 insertions(+), 3 deletions(-) create mode 100644 internal/runtime/executor/helps/xai_version.go create mode 100644 internal/runtime/executor/helps/xai_version_test.go diff --git a/cmd/server/main.go b/cmd/server/main.go index 98139c7b437..c79e99d9762 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -31,6 +31,7 @@ import ( "github.com/router-for-me/CLIProxyAPI/v8/internal/pluginhost" "github.com/router-for-me/CLIProxyAPI/v8/internal/redisqueue" "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor" "github.com/router-for-me/CLIProxyAPI/v8/internal/safemode" "github.com/router-for-me/CLIProxyAPI/v8/internal/store" _ "github.com/router-for-me/CLIProxyAPI/v8/internal/translator" @@ -749,6 +750,7 @@ func main() { // Standalone mode: start an embedded local server and connect TUI client to it. managementasset.StartAutoUpdater(context.Background(), configFilePath) misc.StartAntigravityVersionUpdater(context.Background()) + executor.StartXAIVersionUpdater(context.Background()) registry.SetLocalModelCatalogs(localModel) hook := tui.NewLogHook(2000) hook.SetFormatter(&logging.LogFormatter{}) @@ -824,6 +826,7 @@ func main() { // Start the main proxy service managementasset.StartAutoUpdater(context.Background(), configFilePath) misc.StartAntigravityVersionUpdater(context.Background()) + executor.StartXAIVersionUpdater(context.Background()) registry.SetLocalModelCatalogs(localModel) cmd.StartServiceWithPluginHost(cfg, configFilePath, password, pluginHost, serverOptions...) } diff --git a/internal/runtime/executor/helps/xai_version.go b/internal/runtime/executor/helps/xai_version.go new file mode 100644 index 00000000000..9e70163ac70 --- /dev/null +++ b/internal/runtime/executor/helps/xai_version.go @@ -0,0 +1,178 @@ +package helps + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "strings" + "sync" + "testing" + "time" + + log "github.com/sirupsen/logrus" + "github.com/tidwall/gjson" +) + +const ( + // DefaultXAIFallbackClientVersion is the fallback Grok CLI version when npm registry resolution fails. + DefaultXAIFallbackClientVersion = "1.0.50" + // XAIVersionRefreshInterval is the periodic interval to check for Grok CLI updates from npm. + XAIVersionRefreshInterval = 3 * time.Hour + // XAIVersionFetchTimeout is the maximum duration for a single npm registry lookup. + XAIVersionFetchTimeout = 10 * time.Second +) + +var ( + xaiNPMRegistryURL = "https://registry.npmjs.org/@xai-official/grok/latest" +) + +var ( + cachedXAIClientVersion = DefaultXAIFallbackClientVersion + xaiClientVersionMu sync.RWMutex + xaiVersionUpdaterOnce sync.Once +) + +// GetXAIClientVersion returns the current Grok CLI client version. +// If the background updater has fetched a newer version from npm, it returns that version; +// otherwise it returns DefaultXAIFallbackClientVersion. +func GetXAIClientVersion() string { + xaiClientVersionMu.RLock() + defer xaiClientVersionMu.RUnlock() + return cachedXAIClientVersion +} + +// StartXAIVersionUpdater starts a background goroutine that periodically refreshes the Grok CLI version from npm. +// It executes a single fetch on startup and then polls every 3 hours without multiple retries on failure. +func StartXAIVersionUpdater(ctx context.Context) { + xaiVersionUpdaterOnce.Do(func() { + go runXAIVersionUpdater(ctx) + }) +} + +func runXAIVersionUpdater(ctx context.Context) { + if ctx == nil { + ctx = context.Background() + } + + // Fetch once on startup + refreshXAIClientVersion(ctx) + + ticker := time.NewTicker(XAIVersionRefreshInterval) + defer ticker.Stop() + + log.Infof("periodic Grok CLI version refresh started (interval=%s)", XAIVersionRefreshInterval) + + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + refreshXAIClientVersion(ctx) + } + } +} + +func refreshXAIClientVersion(ctx context.Context) { + version, errFetch := FetchXAINPMLatestVersion(ctx, nil) + if errFetch != nil { + log.WithError(errFetch).Warn("failed to fetch latest Grok CLI version from npm, keeping fallback/cached version") + return + } + + if version == "" { + log.Warn("fetched empty Grok CLI version from npm, keeping fallback/cached version") + return + } + + xaiClientVersionMu.Lock() + cachedXAIClientVersion = version + xaiClientVersionMu.Unlock() + + log.WithField("version", version).Info("updated Grok CLI client version from npm") +} + +// FetchXAINPMLatestVersion performs a single request to the npm registry to query the latest version of @xai-official/grok. +func FetchXAINPMLatestVersion(ctx context.Context, client *http.Client) (string, error) { + if ctx == nil { + ctx = context.Background() + } + + fetchCtx, cancel := context.WithTimeout(ctx, XAIVersionFetchTimeout) + defer cancel() + + xaiClientVersionMu.RLock() + registryURL := xaiNPMRegistryURL + xaiClientVersionMu.RUnlock() + + req, errReq := http.NewRequestWithContext(fetchCtx, http.MethodGet, registryURL, nil) + if errReq != nil { + return "", fmt.Errorf("create npm registry request: %w", errReq) + } + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", "CLIProxyAPI") + + if client == nil { + client = &http.Client{Timeout: XAIVersionFetchTimeout} + } + + resp, errDo := client.Do(req) + if errDo != nil { + return "", fmt.Errorf("npm registry request failed: %w", errDo) + } + defer func() { + if errClose := resp.Body.Close(); errClose != nil { + log.Errorf("failed to close npm response body: %v", errClose) + } + }() + + if resp.StatusCode != http.StatusOK { + return "", fmt.Errorf("npm registry returned HTTP %d", resp.StatusCode) + } + + body, errRead := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + if errRead != nil { + return "", fmt.Errorf("read npm registry response: %w", errRead) + } + + version := strings.TrimSpace(gjson.GetBytes(body, "version").String()) + if version == "" { + return "", errors.New("version not found in npm response") + } + + return version, nil +} + +// OverrideXAINPMRegistryURLForTest overrides the npm registry URL for testing purposes. +func OverrideXAINPMRegistryURLForTest(t *testing.T, url string) func() { + xaiClientVersionMu.Lock() + oldURL := xaiNPMRegistryURL + xaiNPMRegistryURL = url + xaiClientVersionMu.Unlock() + return func() { + xaiClientVersionMu.Lock() + xaiNPMRegistryURL = oldURL + xaiClientVersionMu.Unlock() + } +} + +// SetXAIClientVersionForTest sets the cached Grok CLI version directly for testing purposes. +func SetXAIClientVersionForTest(t *testing.T, version string) func() { + xaiClientVersionMu.Lock() + old := cachedXAIClientVersion + cachedXAIClientVersion = version + xaiClientVersionMu.Unlock() + return func() { + xaiClientVersionMu.Lock() + cachedXAIClientVersion = old + xaiClientVersionMu.Unlock() + } +} + +// ResetXAIVersionUpdaterOnceForTest resets the sync.Once for testing updater initialization. +func ResetXAIVersionUpdaterOnceForTest(t *testing.T) { + xaiClientVersionMu.Lock() + xaiVersionUpdaterOnce = sync.Once{} + xaiClientVersionMu.Unlock() +} diff --git a/internal/runtime/executor/helps/xai_version_test.go b/internal/runtime/executor/helps/xai_version_test.go new file mode 100644 index 00000000000..700202ced16 --- /dev/null +++ b/internal/runtime/executor/helps/xai_version_test.go @@ -0,0 +1,143 @@ +package helps + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + "time" +) + +func TestGetXAIClientVersionDefault(t *testing.T) { + restore := SetXAIClientVersionForTest(t, DefaultXAIFallbackClientVersion) + defer restore() + + if got := GetXAIClientVersion(); got != DefaultXAIFallbackClientVersion { + t.Fatalf("GetXAIClientVersion() = %q, want %q", got, DefaultXAIFallbackClientVersion) + } +} + +func TestFetchXAINPMLatestVersionSuccess(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if got := r.Header.Get("Accept"); got != "application/json" { + t.Errorf("Accept header = %q, want application/json", got) + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"name":"@xai-official/grok","version":"1.0.52"}`)) + })) + defer server.Close() + + restore := OverrideXAINPMRegistryURLForTest(t, server.URL) + defer restore() + + version, err := FetchXAINPMLatestVersion(context.Background(), server.Client()) + if err != nil { + t.Fatalf("FetchXAINPMLatestVersion() error = %v", err) + } + if version != "1.0.52" { + t.Fatalf("FetchXAINPMLatestVersion() = %q, want 1.0.52", version) + } +} + +func TestFetchXAINPMLatestVersionHttpError(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "server error", http.StatusInternalServerError) + })) + defer server.Close() + + restore := OverrideXAINPMRegistryURLForTest(t, server.URL) + defer restore() + + _, err := FetchXAINPMLatestVersion(context.Background(), server.Client()) + if err == nil { + t.Fatal("FetchXAINPMLatestVersion() expected error for HTTP 500, got nil") + } +} + +func TestFetchXAINPMLatestVersionMissingVersion(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"name":"@xai-official/grok"}`)) + })) + defer server.Close() + + restore := OverrideXAINPMRegistryURLForTest(t, server.URL) + defer restore() + + _, err := FetchXAINPMLatestVersion(context.Background(), server.Client()) + if err == nil { + t.Fatal("FetchXAINPMLatestVersion() expected error for missing version, got nil") + } +} + +func TestRefreshXAIClientVersionKeepsFallbackOnError(t *testing.T) { + restoreVersion := SetXAIClientVersionForTest(t, "1.0.50") + defer restoreVersion() + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "offline", http.StatusBadGateway) + })) + defer server.Close() + + restoreURL := OverrideXAINPMRegistryURLForTest(t, server.URL) + defer restoreURL() + + refreshXAIClientVersion(context.Background()) + + if got := GetXAIClientVersion(); got != "1.0.50" { + t.Fatalf("GetXAIClientVersion() = %q, want fallback 1.0.50 preserved on error", got) + } +} + +func TestRefreshXAIClientVersionUpdatesOnSuccess(t *testing.T) { + restoreVersion := SetXAIClientVersionForTest(t, "1.0.50") + defer restoreVersion() + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"name":"@xai-official/grok","version":"1.0.55"}`)) + })) + defer server.Close() + + restoreURL := OverrideXAINPMRegistryURLForTest(t, server.URL) + defer restoreURL() + + refreshXAIClientVersion(context.Background()) + + if got := GetXAIClientVersion(); got != "1.0.55" { + t.Fatalf("GetXAIClientVersion() = %q, want updated version 1.0.55", got) + } +} + +func TestStartXAIVersionUpdaterLifecycle(t *testing.T) { + ResetXAIVersionUpdaterOnceForTest(t) + restoreVersion := SetXAIClientVersionForTest(t, "1.0.50") + defer restoreVersion() + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"name":"@xai-official/grok","version":"1.0.60"}`)) + })) + defer server.Close() + + restoreURL := OverrideXAINPMRegistryURLForTest(t, server.URL) + defer restoreURL() + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + StartXAIVersionUpdater(ctx) + + // Wait briefly for the startup fetch to settle + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + if GetXAIClientVersion() == "1.0.60" { + break + } + time.Sleep(20 * time.Millisecond) + } + + if got := GetXAIClientVersion(); got != "1.0.60" { + t.Fatalf("GetXAIClientVersion() = %q, want 1.0.60 after StartXAIVersionUpdater", got) + } +} diff --git a/internal/runtime/executor/xai_client_version_test.go b/internal/runtime/executor/xai_client_version_test.go index 784780875f0..6b153132a05 100644 --- a/internal/runtime/executor/xai_client_version_test.go +++ b/internal/runtime/executor/xai_client_version_test.go @@ -6,6 +6,7 @@ import ( "strings" "testing" + "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps" cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" ) @@ -74,3 +75,25 @@ func TestXAIChatProxyCustomHeadersOverridePinnedVersion(t *testing.T) { t.Fatalf("%s = %q, want the per-auth custom header to override the pin", xaiClientVersionHeader, got) } } + +func TestXAIChatProxyIdentityHeadersFollowDynamicVersion(t *testing.T) { + restore := helps.SetXAIClientVersionForTest(t, "1.2.34") + defer restore() + + auth := &cliproxyauth.Auth{ + Provider: "xai", + Attributes: map[string]string{"auth_kind": "oauth"}, + } + req, err := http.NewRequest(http.MethodPost, xaiChatBaseURL(auth)+"/chat/completions", nil) + if err != nil { + t.Fatal(err) + } + applyXAIChatHeaders(req, auth, "token", false, "") + + if got := req.Header.Get(xaiClientVersionHeader); got != "1.2.34" { + t.Fatalf("%s = %q, want dynamic version 1.2.34", xaiClientVersionHeader, got) + } + if got, want := req.Header.Get("User-Agent"), "xai-grok-workspace/1.2.34"; got != want { + t.Fatalf("User-Agent = %q, want %q", got, want) + } +} diff --git a/internal/runtime/executor/xai_executor.go b/internal/runtime/executor/xai_executor.go index 3629697ff0c..7f97b2b5441 100644 --- a/internal/runtime/executor/xai_executor.go +++ b/internal/runtime/executor/xai_executor.go @@ -53,7 +53,9 @@ const ( // Keep in sync with the current Grok CLI client version that chat-proxy // expects. The server rejects older versions with HTTP 426; it required // 1.0.13+ as of 2026-10-01 (#6249). - xaiClientVersionValue = "1.0.44" + // This hardcoded value serves as fallback if npm registry resolution fails. + xaiClientVersionFallback = helps.DefaultXAIFallbackClientVersion + xaiClientVersionValue = xaiClientVersionFallback xaiClientIdentifierHeader = "x-grok-client-identifier" xaiClientIdentifierValue = "grok-shell" xaiAuthenticateResponseHeader = "x-authenticateresponse" @@ -76,6 +78,17 @@ func NewXAIExecutor(cfg *config.Config) *XAIExecutor { return &XAIExecutor{cfg: cfg} } +// xaiClientVersion returns the active Grok CLI client version (dynamically fetched +// from npm or falling back to xaiClientVersionFallback). +func xaiClientVersion() string { + return helps.GetXAIClientVersion() +} + +// StartXAIVersionUpdater starts the periodic Grok CLI version updater from npm. +func StartXAIVersionUpdater(ctx context.Context) { + helps.StartXAIVersionUpdater(ctx) +} + // Identifier returns the provider identifier. func (e *XAIExecutor) Identifier() string { return "xai" diff --git a/internal/runtime/executor/xai_executor_request.go b/internal/runtime/executor/xai_executor_request.go index 1d3ab89b2bc..edd6bb02c16 100644 --- a/internal/runtime/executor/xai_executor_request.go +++ b/internal/runtime/executor/xai_executor_request.go @@ -354,9 +354,10 @@ func applyXAIChatHeaders(r *http.Request, auth *cliproxyauth.Auth, token string, } applyXAIDefaultHeaders(r, token, stream, sessionID) if xaiIsCLIChatProxyBaseURL(xaiChatBaseURL(auth)) { + clientVer := xaiClientVersion() r.Header.Set(xaiTokenAuthHeader, xaiTokenAuthValue) - r.Header.Set(xaiClientVersionHeader, xaiClientVersionValue) - r.Header.Set("User-Agent", "xai-grok-workspace/"+xaiClientVersionValue) + r.Header.Set(xaiClientVersionHeader, clientVer) + r.Header.Set("User-Agent", "xai-grok-workspace/"+clientVer) r.Header.Set(xaiClientIdentifierHeader, xaiClientIdentifierValue) r.Header.Set(xaiAuthenticateResponseHeader, xaiAuthenticateResponseValue) } diff --git a/sdk/cliproxy/service_lifecycle.go b/sdk/cliproxy/service_lifecycle.go index d2aa6af9462..631e56f2c67 100644 --- a/sdk/cliproxy/service_lifecycle.go +++ b/sdk/cliproxy/service_lifecycle.go @@ -11,6 +11,7 @@ import ( "github.com/router-for-me/CLIProxyAPI/v8/internal/home" "github.com/router-for-me/CLIProxyAPI/v8/internal/redisqueue" "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor" sdkaccess "github.com/router-for-me/CLIProxyAPI/v8/sdk/access" sdkAuth "github.com/router-for-me/CLIProxyAPI/v8/sdk/auth" coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" @@ -397,4 +398,5 @@ func (s *Service) startModelCatalogUpdaters(ctx context.Context) { if cfg != nil { registry.StartModelCatalogUpdaters(ctx, cfg.Models, cfg.Home.Enabled) } + executor.StartXAIVersionUpdater(ctx) } From f51624aa35c1c5fdf21e4307ddb3140af3e86525 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Thu, 8 Oct 2026 02:02:11 +0800 Subject: [PATCH 092/142] fix(translator): report unsendable user turn attachments in openai responses to interactions - Track dropped attachments and reject emptied user turns during OpenAI Responses to Interactions translation - Register checked request translator for OpenAI Responses to Interactions format conversion --- .../executor/antigravity_executor_execute.go | 20 +- .../antigravity_executor_signature_test.go | 5 +- .../executor/antigravity_executor_stream.go | 11 +- .../executor/antigravity_executor_tokens.go | 18 +- ...igravity_executor_unsupported_part_test.go | 91 +++++++ internal/runtime/executor/devin_executor.go | 55 +++- .../runtime/executor/devin_user_turn_test.go | 138 ++++++++++ .../executor/helps/codex_multi_agent_v2.go | 30 ++- .../helps/codex_multi_agent_v2_test.go | 10 +- .../runtime/executor/helps/devin_user_turn.go | 55 ++++ .../executor/helps/devin_user_turn_test.go | 90 +++++++ internal/runtime/executor/helps/devin_wire.go | 1 + .../executor/helps/request_pair_error_test.go | 135 ++++++++++ .../helps/request_pair_plugin_host_test.go | 6 +- .../request_unsupported_user_turn_test.go | 99 +++++++ .../unsupported_part_executor_test.go | 18 ++ .../claude/antigravity_claude_request.go | 48 +++- .../antigravity_claude_user_turn_test.go | 185 +++++++++++++ .../translator/antigravity/claude/init.go | 4 +- .../antigravity/interactions/init.go | 4 +- ...teractions_antigravity_instruction_test.go | 60 +++++ .../interactions_antigravity_request.go | 116 ++++++-- .../interactions_antigravity_uri_test.go | 151 +++++++++++ .../antigravity_openai_media_url_test.go | 92 +++++++ .../antigravity_openai_request.go | 39 +-- .../antigravity_openai_user_turn_test.go | 98 +++++++ .../openai/chat-completions/init.go | 4 +- .../antigravity_openai-responses_request.go | 10 +- ...gravity_openai-responses_user_turn_test.go | 110 ++++++++ .../antigravity/openai/responses/init.go | 2 +- .../claude/gemini/claude_gemini_request.go | 40 ++- .../gemini/claude_gemini_request_test.go | 14 +- .../gemini/claude_gemini_user_turn_test.go | 129 +++++++++ internal/translator/claude/gemini/init.go | 4 +- .../translator/claude/interactions/init.go | 4 +- .../interactions_claude_instruction_test.go | 60 +++++ .../interactions_claude_request.go | 166 +++++++++--- .../interactions_claude_user_turn_test.go | 249 ++++++++++++++++++ .../chat-completions/claude_openai_request.go | 14 +- .../claude_openai_user_turn_test.go | 81 ++++++ .../claude_openai-responses_request.go | 30 ++- .../claude_openai-responses_user_turn_test.go | 142 ++++++++++ .../claude/openai/responses/init.go | 6 +- .../codex/claude/codex_claude_request.go | 80 ++++-- .../claude/codex_claude_user_turn_test.go | 201 ++++++++++++++ .../translator/codex/interactions/init.go | 4 +- .../interactions_codex_request.go | 152 ++++++++--- .../interactions_codex_uri_test.go | 202 ++++++++++++++ .../chat-completions/codex_openai_request.go | 85 +++--- .../codex_openai_user_turn_test.go | 136 ++++++++++ .../codex/openai/chat-completions/init.go | 4 +- internal/translator/common/parts.go | 163 +++++++++++- internal/translator/common/parts_test.go | 179 +++++++++++++ .../gemini/claude/gemini_claude_request.go | 13 +- .../claude/gemini_claude_user_turn_test.go | 165 ++++++++++++ .../translator/gemini/interactions/init.go | 7 +- .../interactions_gemini_common.go | 189 ++++++++++--- .../interactions_gemini_instruction_test.go | 60 +++++ .../interactions_gemini_uri_test.go | 156 +++++++++++ .../interactions_gemini_user_turn_test.go | 168 ++++++++++++ .../gemini_openai_media_url_test.go | 92 +++++++ .../chat-completions/gemini_openai_request.go | 31 +-- .../gemini_openai_user_turn_test.go | 76 ++++++ .../gemini_openai-responses_request.go | 42 ++- .../gemini_openai-responses_user_turn_test.go | 126 +++++++++ .../gemini/openai/responses/init.go | 4 +- .../claude/interactions_claude_request.go | 38 ++- .../interactions_claude_user_turn_test.go | 133 ++++++++++ .../openai/claude/openai_claude_request.go | 11 +- .../claude/openai_claude_user_turn_test.go | 151 +++++++++++ .../interactions/chat-completions/init.go | 4 +- .../openai_interactions_request.go | 66 ++++- .../openai_interactions_user_turn_test.go | 133 ++++++++++ .../openai/interactions/responses/init.go | 4 +- .../interactions_openai_responses_request.go | 152 +++++++++-- ...actions_openai_responses_user_turn_test.go | 184 +++++++++++++ .../openai/openai/responses/init.go | 4 +- .../openai_openai-responses_request.go | 84 +++++- .../openai_openai-responses_user_turn_test.go | 162 ++++++++++++ 79 files changed, 5739 insertions(+), 366 deletions(-) create mode 100644 internal/runtime/executor/antigravity_executor_unsupported_part_test.go create mode 100644 internal/runtime/executor/devin_user_turn_test.go create mode 100644 internal/runtime/executor/helps/devin_user_turn.go create mode 100644 internal/runtime/executor/helps/devin_user_turn_test.go create mode 100644 internal/runtime/executor/helps/request_pair_error_test.go create mode 100644 internal/runtime/executor/helps/request_unsupported_user_turn_test.go create mode 100644 internal/translator/antigravity/claude/antigravity_claude_user_turn_test.go create mode 100644 internal/translator/antigravity/interactions/interactions_antigravity_instruction_test.go create mode 100644 internal/translator/antigravity/interactions/interactions_antigravity_uri_test.go create mode 100644 internal/translator/antigravity/openai/chat-completions/antigravity_openai_media_url_test.go create mode 100644 internal/translator/antigravity/openai/chat-completions/antigravity_openai_user_turn_test.go create mode 100644 internal/translator/antigravity/openai/responses/antigravity_openai-responses_user_turn_test.go create mode 100644 internal/translator/claude/gemini/claude_gemini_user_turn_test.go create mode 100644 internal/translator/claude/interactions/interactions_claude_instruction_test.go create mode 100644 internal/translator/claude/interactions/interactions_claude_user_turn_test.go create mode 100644 internal/translator/claude/openai/chat-completions/claude_openai_user_turn_test.go create mode 100644 internal/translator/claude/openai/responses/claude_openai-responses_user_turn_test.go create mode 100644 internal/translator/codex/claude/codex_claude_user_turn_test.go create mode 100644 internal/translator/codex/interactions/interactions_codex_uri_test.go create mode 100644 internal/translator/codex/openai/chat-completions/codex_openai_user_turn_test.go create mode 100644 internal/translator/common/parts_test.go create mode 100644 internal/translator/gemini/claude/gemini_claude_user_turn_test.go create mode 100644 internal/translator/gemini/interactions/interactions_gemini_instruction_test.go create mode 100644 internal/translator/gemini/interactions/interactions_gemini_uri_test.go create mode 100644 internal/translator/gemini/interactions/interactions_gemini_user_turn_test.go create mode 100644 internal/translator/gemini/openai/chat-completions/gemini_openai_media_url_test.go create mode 100644 internal/translator/gemini/openai/chat-completions/gemini_openai_user_turn_test.go create mode 100644 internal/translator/gemini/openai/responses/gemini_openai-responses_user_turn_test.go create mode 100644 internal/translator/interactions/claude/interactions_claude_user_turn_test.go create mode 100644 internal/translator/openai/claude/openai_claude_user_turn_test.go create mode 100644 internal/translator/openai/interactions/chat-completions/openai_interactions_user_turn_test.go create mode 100644 internal/translator/openai/interactions/responses/interactions_openai_responses_user_turn_test.go create mode 100644 internal/translator/openai/openai/responses/openai_openai-responses_user_turn_test.go diff --git a/internal/runtime/executor/antigravity_executor_execute.go b/internal/runtime/executor/antigravity_executor_execute.go index e42a12a0d03..7c723f3f485 100644 --- a/internal/runtime/executor/antigravity_executor_execute.go +++ b/internal/runtime/executor/antigravity_executor_execute.go @@ -75,6 +75,13 @@ func (e *AntigravityExecutor) Execute(ctx context.Context, auth *cliproxyauth.Au return resp, errValidate } req.Payload = originalPayload + // Observe a translation refusal before the token refresh or any upstream call. + modelInfo, _ := cliproxyauth.ResolvedModelInfo(req) + translationReq := sdktranslator.RequestEnvelope{Format: from, Model: baseModel, ModelInfo: modelInfo} + originalTranslated, translated, errTranslate := helps.TranslateRequestEnvelopePairWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, translationReq, originalPayload, req.Payload) + if errTranslate != nil { + return resp, errTranslate + } token, updatedAuth, errToken := e.ensureAccessToken(ctx, auth) if errToken != nil { return resp, errToken @@ -83,9 +90,6 @@ func (e *AntigravityExecutor) Execute(ctx context.Context, auth *cliproxyauth.Au auth = updatedAuth reporter.UpdateAccessTokenFingerprint(auth) } - modelInfo, _ := cliproxyauth.ResolvedModelInfo(req) - translationReq := sdktranslator.RequestEnvelope{Format: from, Model: baseModel, ModelInfo: modelInfo} - originalTranslated, translated := helps.TranslateRequestEnvelopePairWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, translationReq, originalPayload, req.Payload) translated, err = helps.ApplyRequestThinking(translated, req, opts, from.String(), to.String(), e.Identifier()) if err != nil { @@ -283,6 +287,13 @@ func (e *AntigravityExecutor) executeClaudeNonStream(ctx context.Context, auth * return resp, errValidate } req.Payload = originalPayload + // Observe a translation refusal before the token refresh or any upstream call. + modelInfo, _ := cliproxyauth.ResolvedModelInfo(req) + translationReq := sdktranslator.RequestEnvelope{Format: from, Model: baseModel, Stream: true, ModelInfo: modelInfo} + originalTranslated, translated, errTranslate := helps.TranslateRequestEnvelopePairWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, translationReq, originalPayload, req.Payload) + if errTranslate != nil { + return resp, errTranslate + } token, updatedAuth, errToken := e.ensureAccessToken(ctx, auth) if errToken != nil { return resp, errToken @@ -291,9 +302,6 @@ func (e *AntigravityExecutor) executeClaudeNonStream(ctx context.Context, auth * auth = updatedAuth reporter.UpdateAccessTokenFingerprint(auth) } - modelInfo, _ := cliproxyauth.ResolvedModelInfo(req) - translationReq := sdktranslator.RequestEnvelope{Format: from, Model: baseModel, Stream: true, ModelInfo: modelInfo} - originalTranslated, translated := helps.TranslateRequestEnvelopePairWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, translationReq, originalPayload, req.Payload) translated, err = helps.ApplyRequestThinking(translated, req, opts, from.String(), to.String(), e.Identifier()) if err != nil { diff --git a/internal/runtime/executor/antigravity_executor_signature_test.go b/internal/runtime/executor/antigravity_executor_signature_test.go index c78a4bca48c..e700d22e406 100644 --- a/internal/runtime/executor/antigravity_executor_signature_test.go +++ b/internal/runtime/executor/antigravity_executor_signature_test.go @@ -198,8 +198,11 @@ func TestAntigravityGeminiSignatureNormalizationDoesNotRepeatLogs(t *testing.T) `{"functionCall":{"name":"second","args":{}},"thoughtSignature":"skip_thought_signature_validator"},` + `{"functionCall":{"name":"third","args":{}},"thoughtSignature":"google#skip_thought_signature_validator"}]}]}`) translationReq := sdktranslator.RequestEnvelope{Model: "gemini-3.8-flash-high", Stream: true} - original, working := helps.TranslateRequestEnvelopePairWithCodexMultiAgentV2(t.Context(), nil, &config.Config{}, + original, working, errTranslate := helps.TranslateRequestEnvelopePairWithCodexMultiAgentV2(t.Context(), nil, &config.Config{}, sdktranslator.FormatGemini, sdktranslator.FormatAntigravity, translationReq, payload, payload) + if errTranslate != nil { + t.Fatalf("translate request pair: %v", errTranslate) + } working = sanitizeAntigravityGeminiRequestSignatures(translationReq.Model, working) if got := gjson.GetBytes(working, "request.contents.0.parts.0.thoughtSignature").String(); got != issue4959GeminiThoughtSignature() { diff --git a/internal/runtime/executor/antigravity_executor_stream.go b/internal/runtime/executor/antigravity_executor_stream.go index 13d404402ac..f925fadead4 100644 --- a/internal/runtime/executor/antigravity_executor_stream.go +++ b/internal/runtime/executor/antigravity_executor_stream.go @@ -75,6 +75,13 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya return nil, errValidate } req.Payload = originalPayload + // Observe a translation refusal before the token refresh or any upstream call. + modelInfo, _ := cliproxyauth.ResolvedModelInfo(req) + translationReq := sdktranslator.RequestEnvelope{Format: from, Model: baseModel, Stream: true, ModelInfo: modelInfo} + originalTranslated, translated, errTranslate := helps.TranslateRequestEnvelopePairWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, translationReq, originalPayload, req.Payload) + if errTranslate != nil { + return nil, errTranslate + } token, updatedAuth, errToken := e.ensureAccessToken(ctx, auth) if errToken != nil { return nil, errToken @@ -84,10 +91,6 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya reporter.UpdateAccessTokenFingerprint(auth) } - modelInfo, _ := cliproxyauth.ResolvedModelInfo(req) - translationReq := sdktranslator.RequestEnvelope{Format: from, Model: baseModel, Stream: true, ModelInfo: modelInfo} - originalTranslated, translated := helps.TranslateRequestEnvelopePairWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, translationReq, originalPayload, req.Payload) - translated, err = helps.ApplyRequestThinking(translated, req, opts, from.String(), to.String(), e.Identifier()) if err != nil { return nil, err diff --git a/internal/runtime/executor/antigravity_executor_tokens.go b/internal/runtime/executor/antigravity_executor_tokens.go index a493030271a..6f21244877b 100644 --- a/internal/runtime/executor/antigravity_executor_tokens.go +++ b/internal/runtime/executor/antigravity_executor_tokens.go @@ -35,6 +35,18 @@ func (e *AntigravityExecutor) CountTokens(ctx context.Context, auth *cliproxyaut return cliproxyexecutor.Response{}, errValidate } req.Payload = originalPayloadSource + + // Prepare payload once (doesn't depend on baseURL). A translation refusal is + // observed before the token refresh or any upstream call. + modelInfo, _ := cliproxyauth.ResolvedModelInfo(req) + translationReq := sdktranslator.RequestEnvelope{Format: from, Model: baseModel, Body: req.Payload, ModelInfo: modelInfo} + translatedReq := helps.TranslateRequestEnvelopeWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, translationReq) + if translatedReq.Err != nil { + return cliproxyexecutor.Response{}, translatedReq.Err + } + payload := translatedReq.Body + originalTranslatedForPayload := append([]byte(nil), payload...) + token, updatedAuth, errToken := e.ensureAccessToken(ctx, auth) if errToken != nil { return cliproxyexecutor.Response{}, errToken @@ -47,12 +59,6 @@ func (e *AntigravityExecutor) CountTokens(ctx context.Context, auth *cliproxyaut return cliproxyexecutor.Response{}, statusErr{code: http.StatusUnauthorized, msg: "missing access token"} } - // Prepare payload once (doesn't depend on baseURL) - modelInfo, _ := cliproxyauth.ResolvedModelInfo(req) - translationReq := sdktranslator.RequestEnvelope{Format: from, Model: baseModel, Body: req.Payload, ModelInfo: modelInfo} - payload := helps.TranslateRequestEnvelopeWithCodexMultiAgentV2(ctx, opts.Headers, e.cfg, from, to, translationReq).Body - originalTranslatedForPayload := append([]byte(nil), payload...) - payload, err := helps.ApplyRequestThinking(payload, req, opts, from.String(), to.String(), e.Identifier()) if err != nil { return cliproxyexecutor.Response{}, err diff --git a/internal/runtime/executor/antigravity_executor_unsupported_part_test.go b/internal/runtime/executor/antigravity_executor_unsupported_part_test.go new file mode 100644 index 00000000000..d4d9c98705c --- /dev/null +++ b/internal/runtime/executor/antigravity_executor_unsupported_part_test.go @@ -0,0 +1,91 @@ +package executor + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +// A user turn that only holds a file Antigravity cannot receive must be refused +// before any HTTP call, for every entry point and for both execution paths +// (Gemini models and Claude-on-Antigravity models), even after earlier turns. +func TestAntigravityExecutorRefusesAFileOnlyTurnBeforeCallingUpstream(t *testing.T) { + var upstreamCalls atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + upstreamCalls.Add(1) + w.WriteHeader(http.StatusOK) + })) + defer server.Close() + + const ( + claudeFile = `{"max_tokens":8,"messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"container_upload","file_id":"file_not_stored"}]}]}` + openAIFile = `{"messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"file","file":{"file_id":"file-not-stored"}}]}]}` + // The attachment-only user turn is followed by a developer step that must not hide it. + interactionsDeveloper = `{"input":[{"type":"user_input","content":[{"type":"text","text":"hello"}]},{"type":"model_output","content":[{"type":"text","text":"hi"}]},{"type":"user_input","content":[{"type":"document","uri":"gs://b/a.pdf"}]},{"type":"user_input","role":"developer","content":[{"type":"text","text":"note"}]}]}` + // The only new user turn is a remote image URL, so the earlier turn must not be answered in its place. + openAIImageURL = `{"messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"image_url","image_url":{"url":"https://x.test/a.png"}}]}]}` + ) + cases := []struct { + name string + model string + source string + payload string + wantPart string + }{ + {"claude source to gemini model", "gemini-3.7-flash", "claude", claudeFile, "container_upload"}, + {"claude source to claude model", "claude-sonnet-4-5", "claude", claudeFile, "container_upload"}, + {"openai source to gemini model", "gemini-3.7-flash", "openai", openAIFile, "file"}, + {"openai image_url source to gemini model", "gemini-3.7-flash", "openai", openAIImageURL, "image_url"}, + {"interactions developer step to gemini model", "gemini-3.7-flash", "interactions", interactionsDeveloper, "document"}, + {"openai source to claude model", "claude-sonnet-4-5", "openai", openAIFile, "file"}, + } + for _, tc := range cases { + auth := &cliproxyauth.Auth{ + Metadata: map[string]any{ + "access_token": "token-123", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-1", + }, + Attributes: map[string]string{"base_url": server.URL}, + } + exec := NewAntigravityExecutor(&config.Config{}) + req := cliproxyexecutor.Request{Model: tc.model, Payload: []byte(tc.payload)} + opts := func(stream bool) cliproxyexecutor.Options { + return cliproxyexecutor.Options{SourceFormat: sdktranslator.FromString(tc.source), Stream: stream} + } + calls := map[string]func() error{ + "Execute": func() error { + _, err := exec.Execute(context.Background(), auth, req, opts(false)) + return err + }, + "ExecuteStream": func() error { + _, err := exec.ExecuteStream(context.Background(), auth, req, opts(true)) + return err + }, + "CountTokens": func() error { + _, err := exec.CountTokens(context.Background(), auth, req, opts(false)) + return err + }, + } + for method, call := range calls { + err := call() + var part *translatorcommon.UnsupportedPartError + if !errors.As(err, &part) || part.Type != tc.wantPart { + t.Errorf("%s %s: err = %v, want unsupported %s", tc.name, method, err, tc.wantPart) + } + } + } + if got := upstreamCalls.Load(); got != 0 { + t.Fatalf("upstream was called %d times, want 0", got) + } +} diff --git a/internal/runtime/executor/devin_executor.go b/internal/runtime/executor/devin_executor.go index 55801e66885..2b4ce45c097 100644 --- a/internal/runtime/executor/devin_executor.go +++ b/internal/runtime/executor/devin_executor.go @@ -408,6 +408,12 @@ func (e *DevinExecutor) prepareDevinHTTPRequest(ctx context.Context, auth *clipr payload = translated.Body } systemPrompt, prompts, tools, temp, maxTokens, sessionID, cascadeID, thinkingLevel, budgetTokens := parseInteractionsPayload(payload, opts.OriginalRequest) + // Devin cannot fetch a remote uri or take audio, video or documents. A user turn left + // with nothing else to send is refused here, before any upstream call. + prompts, errTurns := helps.CheckDevinUserTurns(prompts) + if errTurns != nil { + return nil, "", nil, errTurns + } sessionID, cascadeID = resolveDevinSessionAndCascadeIDs(ctx, sessionID, cascadeID, opts) baseModel := thinking.ParseSuffix(req.Model).ModelName @@ -1600,12 +1606,13 @@ func parseInteractionsPayload(payload, originalRequest []byte) ( stepType := strings.ToLower(strings.TrimSpace(step.Get("type").String())) switch stepType { case "user_input": - text, images := extractInteractionsStepContent(step) + text, images, droppedPart := extractInteractionsStepContent(step) prompts = append(prompts, helps.DevinPrompt{ - MessageID: uuid.New().String(), - Source: 1, - Content: text, - Images: images, + MessageID: uuid.New().String(), + Source: 1, + Content: text, + Images: images, + DroppedPart: droppedPart, }) case "model_output": @@ -1712,12 +1719,13 @@ func parseInteractionsPayload(payload, originalRequest []byte) ( systemPrompt = m.Get("content").String() } case "user": - text, images := extractInteractionsStepContent(m) + text, images, droppedPart := extractInteractionsStepContent(m) prompts = append(prompts, helps.DevinPrompt{ - MessageID: uuid.New().String(), - Source: 1, - Content: text, - Images: images, + MessageID: uuid.New().String(), + Source: 1, + Content: text, + Images: images, + DroppedPart: droppedPart, }) case "assistant": text := extractInteractionsStepText(m) @@ -1888,7 +1896,8 @@ func extractDevinImage(part gjson.Result) (helps.DevinImage, bool) { } if base64Data == "" { - url := firstNonEmpty(part.Get("image_url.url").String(), part.Get("image_url").String(), part.Get("url").String()) + // uri and file_uri are Interactions spellings of url; only a data URL is usable. + url := firstNonEmpty(part.Get("image_url.url").String(), part.Get("image_url").String(), part.Get("url").String(), part.Get("uri").String(), part.Get("file_uri").String(), part.Get("fileUri").String()) if m, d, ok := parseDataURL(url); ok { base64Data = d if mimeType == "" { @@ -2117,10 +2126,27 @@ func extractFunctionResultContent(step gjson.Result) (string, []helps.DevinImage return resText, images } -func extractInteractionsStepContent(step gjson.Result) (string, []helps.DevinImage) { +// devinUnsendableMediaType names the type of a media part that Devin cannot send, or +// returns "" for text and for parts that are not media. Devin only takes inline images, +// so a remote uri or any audio, video or document part is unsendable. +func devinUnsendableMediaType(part gjson.Result) string { + if part.Get("text").String() != "" { + return "" + } + switch partType := strings.ToLower(strings.TrimSpace(part.Get("type").String())); partType { + case "image", "input_image", "image_url", "audio", "input_audio", "video", "document", "file", "input_file": + return partType + } + return "" +} + +// extractInteractionsStepContent returns the text and inline images of a user step. The +// third result is the type of the first media part Devin could not send, or "". +func extractInteractionsStepContent(step gjson.Result) (string, []helps.DevinImage, string) { content := step.Get("content") var textParts []string var images []helps.DevinImage + droppedPart := "" extractFromPart := func(p gjson.Result) { if img, ok := extractDevinImage(p); ok { @@ -2130,6 +2156,9 @@ func extractInteractionsStepContent(step gjson.Result) (string, []helps.DevinIma if t := p.Get("text").String(); t != "" { textParts = append(textParts, t) } + if droppedPart == "" { + droppedPart = devinUnsendableMediaType(p) + } } if content.Type == gjson.String { @@ -2158,7 +2187,7 @@ func extractInteractionsStepContent(step gjson.Result) (string, []helps.DevinIma } } - return text, images + return text, images, droppedPart } func extractInteractionsStepText(step gjson.Result) string { diff --git a/internal/runtime/executor/devin_user_turn_test.go b/internal/runtime/executor/devin_user_turn_test.go new file mode 100644 index 00000000000..ffe6abb18e4 --- /dev/null +++ b/internal/runtime/executor/devin_user_turn_test.go @@ -0,0 +1,138 @@ +package executor + +import ( + "bytes" + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +const devinInteractionsHistory = `{"type":"user_input","content":[{"type":"text","text":"a"}]},{"type":"model_output","content":[{"type":"text","text":"b"}]}` + +func devinInteractionsPayload(steps string) string { + return `{"input":[` + devinInteractionsHistory + `,` + steps + `]}` +} + +func requireDevinUnsupportedPart(t *testing.T, err error, wantType string) { + t.Helper() + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(err, &unsupported) || unsupported.Type != wantType || unsupported.StatusCode() != 400 { + t.Fatalf("err = %v, want unsupported content part: %s", err, wantType) + } + if got, want := err.Error(), "unsupported content part: "+wantType; got != want { + t.Fatalf("error text = %q, want %q", got, want) + } +} + +// Devin cannot fetch a remote uri or take audio, video or documents, so a user +// turn that only holds such media is refused before any HTTP call, for both +// execution paths and for Interactions and non-Interactions sources. +func TestDevinExecutorRefusesAnUnsendableMediaOnlyTurnBeforeCallingUpstream(t *testing.T) { + var upstreamCalls atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + upstreamCalls.Add(1) + w.WriteHeader(http.StatusOK) + })) + defer server.Close() + + const claudeWhitespaceImage = `{"max_tokens":8,"messages":[{"role":"user","content":"a"},{"role":"assistant","content":"b"},{"role":"user","content":[{"type":"text","text":" "},{"type":"image","source":{"type":"file","file_id":"f1"}}]}]}` + const geminiFile = `{"contents":[{"role":"user","parts":[{"text":"a"}]},{"role":"model","parts":[{"text":"b"}]},{"role":"user","parts":[{"fileData":{"mimeType":"image/png","fileUri":"gs://b/a.png"}}]}]}` + cases := []struct { + name string + source sdktranslator.Format + payload string + wantPart string + }{ + {"image by uri", sdktranslator.FormatInteractions, devinInteractionsPayload(`{"type":"user_input","content":[{"type":"image","mime_type":"image/png","uri":"https://example.test/a.png"}]}`), "image"}, + {"image by file_uri", sdktranslator.FormatInteractions, devinInteractionsPayload(`{"type":"user_input","content":[{"type":"image","mime_type":"image/png","file_uri":"gs://b/a.png"}]}`), "image"}, + {"document by fileUri", sdktranslator.FormatInteractions, devinInteractionsPayload(`{"type":"user_input","content":[{"type":"document","mime_type":"application/pdf","fileUri":"gs://b/a.pdf"}]}`), "document"}, + {"inline audio", sdktranslator.FormatInteractions, devinInteractionsPayload(`{"type":"user_input","content":[{"type":"audio","mime_type":"audio/wav","data":"UklGRg=="}]}`), "audio"}, + {"whitespace text does not hide it", sdktranslator.FormatInteractions, devinInteractionsPayload(`{"type":"user_input","content":[{"type":"text","text":" \n"},{"type":"video","mime_type":"video/mp4","uri":"https://example.test/a.mp4"}]}`), "video"}, + {"emptied turn before a later text turn", sdktranslator.FormatInteractions, `{"input":[{"type":"user_input","content":[{"type":"image","mime_type":"image/png","uri":"https://example.test/a.png"}]},{"type":"model_output","content":[{"type":"text","text":"ok"}]},{"type":"user_input","content":[{"type":"text","text":"next"}]}]}`, "image"}, + {"gemini fileData through interactions", sdktranslator.FormatGemini, geminiFile, "image"}, + {"claude whitespace text beside an unrepresentable image", sdktranslator.FormatClaude, claudeWhitespaceImage, "image"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + exec := NewDevinExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{ID: "devin-media-only", Provider: "devin", Attributes: map[string]string{"api_key": "test-key", "base_url": server.URL}} + req := cliproxyexecutor.Request{Model: "devin/swe-2", Payload: []byte(tc.payload)} + opts := cliproxyexecutor.Options{SourceFormat: tc.source} + + _, errExecute := exec.Execute(context.Background(), auth, req, opts) + requireDevinUnsupportedPart(t, errExecute, tc.wantPart) + opts.Stream = true + _, errStream := exec.ExecuteStream(context.Background(), auth, req, opts) + requireDevinUnsupportedPart(t, errStream, tc.wantPart) + _, _, _, errPrepare := exec.prepareDevinHTTPRequest(context.Background(), auth, req, opts) + requireDevinUnsupportedPart(t, errPrepare, tc.wantPart) + }) + } + if got := upstreamCalls.Load(); got != 0 { + t.Fatalf("upstream was called %d times, want 0", got) + } +} + +func TestDevinExecutorSendsTextBesideUnsendableMediaWithoutAPlaceholder(t *testing.T) { + exec := NewDevinExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{ID: "devin-text-beside-media", Provider: "devin", Attributes: map[string]string{"api_key": "test-key"}} + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatInteractions} + cases := map[string]string{ + "same step": `{"type":"user_input","content":[{"type":"text","text":"keep me"},{"type":"image","mime_type":"image/png","uri":"https://example.test/a.png"}]}`, + "neighbouring step": `{"type":"user_input","content":[{"type":"text","text":"keep me"}]},{"type":"user_input","content":[{"type":"image","mime_type":"image/png","uri":"https://example.test/a.png"}]}`, + } + for name, steps := range cases { + t.Run(name, func(t *testing.T) { + req := cliproxyexecutor.Request{Model: "devin/swe-2", Payload: []byte(devinInteractionsPayload(steps))} + httpReq, _, _, err := exec.prepareDevinHTTPRequest(context.Background(), auth, req, opts) + if err != nil { + t.Fatalf("prepareDevinHTTPRequest: %v", err) + } + body, errRead := io.ReadAll(httpReq.Body) + if errRead != nil { + t.Fatalf("read body: %v", errRead) + } + if !bytes.Contains(body, []byte("keep me")) { + t.Fatalf("text was lost from the request") + } + for _, forbidden := range []string{"example.test", "omitted", "[Image"} { + if bytes.Contains(body, []byte(forbidden)) { + t.Fatalf("request mentions %q although the media was not sent", forbidden) + } + } + }) + } +} + +func TestDevinExecutorStillSendsInlineImages(t *testing.T) { + exec := NewDevinExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{ID: "devin-inline-image", Provider: "devin", Attributes: map[string]string{"api_key": "test-key"}} + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatInteractions} + for _, part := range []string{ + `{"type":"image","mime_type":"image/png","data":"aGVsbG8="}`, + `{"type":"image","mime_type":"image/png","uri":"data:image/png;base64,aGVsbG8="}`, + } { + req := cliproxyexecutor.Request{Model: "devin/swe-2", Payload: []byte(devinInteractionsPayload(`{"type":"user_input","content":[` + part + `]}`))} + httpReq, _, _, err := exec.prepareDevinHTTPRequest(context.Background(), auth, req, opts) + if err != nil { + t.Fatalf("prepareDevinHTTPRequest(%s): %v", part, err) + } + body, errRead := io.ReadAll(httpReq.Body) + if errRead != nil { + t.Fatalf("read body: %v", errRead) + } + if !bytes.Contains(body, []byte("pasted_image_1.png")) { + t.Fatalf("inline image was not sent for %s", part) + } + } +} diff --git a/internal/runtime/executor/helps/codex_multi_agent_v2.go b/internal/runtime/executor/helps/codex_multi_agent_v2.go index ea94835783f..b9cc92c138f 100644 --- a/internal/runtime/executor/helps/codex_multi_agent_v2.go +++ b/internal/runtime/executor/helps/codex_multi_agent_v2.go @@ -65,22 +65,28 @@ func TranslateRequestEnvelopeWithCodexMultiAgentV2(ctx context.Context, headers // extra pass over payloads that can reach tens of megabytes. func TranslateRequestPairWithCodexMultiAgentV2(ctx context.Context, headers http.Header, cfg *config.Config, from, to sdktranslator.Format, model string, originalPayload, requestPayload []byte, stream bool) (original, working []byte) { req := sdktranslator.RequestEnvelope{Format: from, Model: model, Stream: stream} - return TranslateRequestEnvelopePairWithCodexMultiAgentV2(ctx, headers, cfg, from, to, req, originalPayload, requestPayload) + original, working, _ = TranslateRequestEnvelopePairWithCodexMultiAgentV2(ctx, headers, cfg, from, to, req, originalPayload, requestPayload) + return original, working } // TranslateRequestEnvelopePairWithCodexMultiAgentV2 translates the baseline and -// working payload while preserving request-scoped metadata in req. -func TranslateRequestEnvelopePairWithCodexMultiAgentV2(ctx context.Context, headers http.Header, cfg *config.Config, from, to sdktranslator.Format, req sdktranslator.RequestEnvelope, originalPayload, requestPayload []byte) (original, working []byte) { +// working payload while preserving request-scoped metadata in req. The returned +// error is the one for the working payload, which is the payload sent upstream; +// a failure of the baseline alone never rejects a working payload that translated. +func TranslateRequestEnvelopePairWithCodexMultiAgentV2(ctx context.Context, headers http.Header, cfg *config.Config, from, to sdktranslator.Format, req sdktranslator.RequestEnvelope, originalPayload, requestPayload []byte) (original, working []byte, err error) { originalReq := req originalReq.Body = originalPayload - original = TranslateRequestEnvelopeWithCodexMultiAgentV2(ctx, headers, cfg, from, to, originalReq).Body + originalTranslated := TranslateRequestEnvelopeWithCodexMultiAgentV2(ctx, headers, cfg, from, to, originalReq) + original = originalTranslated.Body if sameByteSlice(originalPayload, requestPayload) { // The caller mutates the working copy, so it must not share the baseline array. - return original, append([]byte(nil), original...) + // A single translation serves both payloads, so its error is the working error. + return original, append([]byte(nil), original...), originalTranslated.Err } workingReq := req workingReq.Body = requestPayload - return original, TranslateRequestEnvelopeWithCodexMultiAgentV2(ctx, headers, cfg, from, to, workingReq).Body + workingTranslated := TranslateRequestEnvelopeWithCodexMultiAgentV2(ctx, headers, cfg, from, to, workingReq) + return original, workingTranslated.Body, workingTranslated.Err } // sameByteSlice reports whether both slices describe the same bytes of the same @@ -115,16 +121,16 @@ func translateRequestPairWithAPIKeyModelCompatibility(ctx context.Context, heade // TranslateRequestPairWithAPIKeyModelCompatibilityAndUpdateIntent returns the // normalizer decision for the working payload, not for the baseline payload, -// and the error for a content part the target cannot represent. +// and the working payload's error for a content part the target cannot +// represent. A baseline failure alone is ignored. func TranslateRequestPairWithAPIKeyModelCompatibilityAndUpdateIntent(ctx context.Context, headers http.Header, cfg *config.Config, from, to sdktranslator.Format, model string, originalPayload, requestPayload []byte, stream, isCompat bool) (original, working []byte, updatesChanged bool, err error) { original, updatesChanged, err = TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntent(ctx, headers, cfg, from, to, model, originalPayload, stream, isCompat) if sameByteSlice(originalPayload, requestPayload) { + // A single translation serves both payloads, so its error is the working error. return original, append([]byte(nil), original...), updatesChanged, err } - working, updatesChanged, errWorking := TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntent(ctx, headers, cfg, from, to, model, requestPayload, stream, isCompat) - if err == nil { - err = errWorking - } + // Only the working payload is sent upstream, so only its error counts. + working, updatesChanged, err = TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntent(ctx, headers, cfg, from, to, model, requestPayload, stream, isCompat) return original, working, updatesChanged, err } @@ -196,7 +202,7 @@ func translateRequestWithAPIKeyModelCompatibilityForExecutor(ctx context.Context case from == sdktranslator.FormatOpenAI && to == sdktranslator.FormatClaude: translated, convertErr = openaichatclaude.ConvertOpenAIRequestToClaudeWithCompatReturningError(model, payload, stream) case from == sdktranslator.FormatOpenAIResponse && to == sdktranslator.FormatClaude: - translated = responsesclaude.ConvertOpenAIResponsesRequestToClaudeWithCompat(model, payload, stream) + translated, convertErr = responsesclaude.ConvertOpenAIResponsesRequestToClaudeWithCompatReturningError(model, payload, stream) default: return translateRequestWithCodexMultiAgentV2Checked(ctx, headers, cfg, from, to, model, payload, stream) } diff --git a/internal/runtime/executor/helps/codex_multi_agent_v2_test.go b/internal/runtime/executor/helps/codex_multi_agent_v2_test.go index e5a6df82444..6fe83990bce 100644 --- a/internal/runtime/executor/helps/codex_multi_agent_v2_test.go +++ b/internal/runtime/executor/helps/codex_multi_agent_v2_test.go @@ -215,7 +215,10 @@ func TestTranslateRequestEnvelopePairWithCodexMultiAgentV2UsesModelInfo(t *testi NativeCapabilities: ®istry.NativeCapabilities{WebSearch: &trueVal}, } envelope := sdktranslator.RequestEnvelope{Format: sdktranslator.FormatOpenAIResponse, Model: model, ModelInfo: enabled} - base, work := TranslateRequestEnvelopePairWithCodexMultiAgentV2(context.Background(), http.Header{}, &config.Config{}, sdktranslator.FormatOpenAIResponse, sdktranslator.FormatAntigravity, envelope, input, input) + base, work, errPair := TranslateRequestEnvelopePairWithCodexMultiAgentV2(context.Background(), http.Header{}, &config.Config{}, sdktranslator.FormatOpenAIResponse, sdktranslator.FormatAntigravity, envelope, input, input) + if errPair != nil { + t.Fatalf("translate request pair: %v", errPair) + } if gjson.GetBytes(base, "requestType").String() != "web_search" { t.Fatalf("expected baseline requestType web_search, got: %s", base) } @@ -228,7 +231,10 @@ func TestTranslateRequestEnvelopePairWithCodexMultiAgentV2UsesModelInfo(t *testi NativeCapabilities: ®istry.NativeCapabilities{WebSearch: &falseVal}, } envelope.ModelInfo = disabled - _, workDisabled := TranslateRequestEnvelopePairWithCodexMultiAgentV2(context.Background(), http.Header{}, &config.Config{}, sdktranslator.FormatOpenAIResponse, sdktranslator.FormatAntigravity, envelope, input, input) + _, workDisabled, errPair := TranslateRequestEnvelopePairWithCodexMultiAgentV2(context.Background(), http.Header{}, &config.Config{}, sdktranslator.FormatOpenAIResponse, sdktranslator.FormatAntigravity, envelope, input, input) + if errPair != nil { + t.Fatalf("translate request pair: %v", errPair) + } if gjson.GetBytes(workDisabled, "requestType").String() == "web_search" { t.Fatalf("expected non-web_search when capability disabled, got: %s", workDisabled) } diff --git a/internal/runtime/executor/helps/devin_user_turn.go b/internal/runtime/executor/helps/devin_user_turn.go new file mode 100644 index 00000000000..10891755c4f --- /dev/null +++ b/internal/runtime/executor/helps/devin_user_turn.go @@ -0,0 +1,55 @@ +package helps + +import ( + "strings" + + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" +) + +// CheckDevinUserTurns applies the shared user-turn policy to the parsed prompts. +// Devin can only receive inline images, so a user prompt that dropped media it +// cannot fetch or carry (a remote uri, audio, video, a document) is refused with +// an unsupported content part error when its whole user turn has nothing else to +// send. A tool result or real text in the same turn keeps the turn alive; the +// emptied prompt is then removed so that no empty user prompt, and no placeholder +// standing in for the media, reaches upstream. +func CheckDevinUserTurns(prompts []DevinPrompt) ([]DevinPrompt, error) { + var run translatorcommon.UserRun + for _, prompt := range prompts { + switch { + case prompt.Source == 2: + run.End() + case prompt.Source == 1 && !prompt.IsOrphanedTool: + if prompt.DroppedPart != "" { + run.Drop(prompt.DroppedPart) + } + if devinPromptHasContent(prompt) { + run.Add() + } + default: + // A tool result is content the model reads, so it keeps the surrounding user turn. + run.Add() + } + } + run.End() + if errRun := run.Err(); errRun != nil { + return nil, errRun + } + + kept := make([]DevinPrompt, 0, len(prompts)) + for _, prompt := range prompts { + if prompt.Source == 1 && !prompt.IsOrphanedTool && prompt.DroppedPart != "" && !devinPromptHasContent(prompt) { + continue + } + kept = append(kept, prompt) + } + if len(kept) == len(prompts) { + return prompts, nil + } + return kept, nil +} + +// devinPromptHasContent reports whether a user prompt carries non-blank text or an image. +func devinPromptHasContent(prompt DevinPrompt) bool { + return strings.TrimSpace(prompt.Content) != "" || len(prompt.Images) > 0 +} diff --git a/internal/runtime/executor/helps/devin_user_turn_test.go b/internal/runtime/executor/helps/devin_user_turn_test.go new file mode 100644 index 00000000000..5aa620fee30 --- /dev/null +++ b/internal/runtime/executor/helps/devin_user_turn_test.go @@ -0,0 +1,90 @@ +package helps + +import ( + "errors" + "testing" + + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" +) + +func TestCheckDevinUserTurnsRefusesAPromptEmptiedByUnsendableMedia(t *testing.T) { + cases := map[string][]DevinPrompt{ + "only the media prompt": { + {Source: 1, DroppedPart: "image"}, + }, + "after earlier turns": { + {Source: 1, Content: "a"}, + {Source: 2, Content: "b"}, + {Source: 1, DroppedPart: "image"}, + }, + "whitespace text does not count": { + {Source: 1, Content: " \n\t"}, + {Source: 1, DroppedPart: "image"}, + }, + "before a later text turn": { + {Source: 1, DroppedPart: "image"}, + {Source: 2, Content: "ok"}, + {Source: 1, Content: "next"}, + }, + } + for name, prompts := range cases { + t.Run(name, func(t *testing.T) { + kept, err := CheckDevinUserTurns(prompts) + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(err, &unsupported) || unsupported.Type != "image" || unsupported.StatusCode() != 400 { + t.Fatalf("err = %v, want unsupported content part: image", err) + } + if kept != nil { + t.Fatalf("kept = %#v, want nil on refusal", kept) + } + }) + } +} + +func TestCheckDevinUserTurnsKeepsATurnWithOtherContent(t *testing.T) { + cases := map[string]struct { + prompts []DevinPrompt + want int + }{ + "text beside the media in one prompt": { + prompts: []DevinPrompt{{Source: 1, Content: "keep me", DroppedPart: "audio"}}, + want: 1, + }, + "text in a neighbouring prompt": { + prompts: []DevinPrompt{{Source: 1, Content: "keep me"}, {Source: 1, DroppedPart: "audio"}}, + want: 1, + }, + "inline image in a neighbouring prompt": { + prompts: []DevinPrompt{{Source: 1, DroppedPart: "audio"}, {Source: 1, Images: []DevinImage{{Base64Data: "aGk=", MimeType: "image/png"}}}}, + want: 1, + }, + "tool result in the same turn": { + prompts: []DevinPrompt{{Source: 2, ToolCalls: []DevinToolCall{{ID: "c1"}}}, {Source: 4, ToolCallID: "c1", Content: "{}"}, {Source: 1, DroppedPart: "audio"}}, + want: 2, + }, + "orphaned tool result in the same turn": { + prompts: []DevinPrompt{{Source: 1, IsOrphanedTool: true, Content: "{}"}, {Source: 1, DroppedPart: "audio"}}, + want: 1, + }, + "prompt without dropped media is left alone": { + prompts: []DevinPrompt{{Source: 1, Content: ""}}, + want: 1, + }, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + kept, err := CheckDevinUserTurns(tc.prompts) + if err != nil { + t.Fatalf("err = %v, want nil", err) + } + if len(kept) != tc.want { + t.Fatalf("kept %d prompts, want %d: %#v", len(kept), tc.want, kept) + } + for _, prompt := range kept { + if prompt.Source == 1 && !prompt.IsOrphanedTool && prompt.DroppedPart != "" && prompt.Content == "" && len(prompt.Images) == 0 { + t.Fatalf("an empty user prompt was kept: %#v", prompt) + } + } + }) + } +} diff --git a/internal/runtime/executor/helps/devin_wire.go b/internal/runtime/executor/helps/devin_wire.go index 2d708c5f5a3..f8274ceede7 100644 --- a/internal/runtime/executor/helps/devin_wire.go +++ b/internal/runtime/executor/helps/devin_wire.go @@ -92,6 +92,7 @@ type DevinPrompt struct { ToolCallID string // For source=4 (tool result) OriginalToolCallID string // Retained when downgraded from source=4 to source=1 IsOrphanedTool bool // Explicit flag marking downgraded tool results + DroppedPart string // Type of a user media part Devin cannot send; never put on the wire Thinking string Signature []byte SignatureType string diff --git a/internal/runtime/executor/helps/request_pair_error_test.go b/internal/runtime/executor/helps/request_pair_error_test.go new file mode 100644 index 00000000000..143070013b1 --- /dev/null +++ b/internal/runtime/executor/helps/request_pair_error_test.go @@ -0,0 +1,135 @@ +package helps + +import ( + "context" + "errors" + "net/http" + "testing" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/clienterror" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +const ( + pairFileOnlyClaude = `{"model":"m","max_tokens":8,"messages":[{"role":"user","content":[{"type":"container_upload","file_id":"file-1"}]}]}` + pairTextOnlyClaude = `{"model":"m","max_tokens":8,"messages":[{"role":"user","content":[{"type":"text","text":"keep me"}]}]}` +) + +func requireUnsupportedPart(t *testing.T, label string, err error, wantType string) { + t.Helper() + var part *translatorcommon.UnsupportedPartError + if !errors.As(err, &part) || part.Type != wantType || clienterror.HTTPStatusFromError(err) != http.StatusBadRequest { + t.Fatalf("%s: err = %v, want a 400 unsupported content part: %s", label, err, wantType) + } + if got, want := err.Error(), "unsupported content part: "+wantType; got != want { + t.Fatalf("%s: error text = %q, want %q", label, got, want) + } +} + +// Only the working payload reaches the upstream, so only its translation error +// may reject the request. The baseline serves payload rules and is never sent. +func TestPairTranslationReportsOnlyTheWorkingError(t *testing.T) { + file := []byte(pairFileOnlyClaude) + text := []byte(pairTextOnlyClaude) + ctx := context.Background() + + type pairFunc func(original, working []byte) (originalBody, workingBody []byte, err error) + routes := map[string]pairFunc{} + routes["antigravity envelope pair"] = func(original, working []byte) ([]byte, []byte, error) { + req := sdktranslator.RequestEnvelope{Format: sdktranslator.FormatClaude, Model: "m"} + return TranslateRequestEnvelopePairWithCodexMultiAgentV2(ctx, nil, &config.Config{}, sdktranslator.FormatClaude, sdktranslator.FormatAntigravity, req, original, working) + } + for _, to := range []sdktranslator.Format{sdktranslator.FormatOpenAI, sdktranslator.FormatGemini, sdktranslator.FormatCodex, sdktranslator.FormatInteractions} { + for _, compat := range []bool{false, true} { + name := "api-key pair to " + to.String() + if compat { + name += " compat" + } + routes[name] = func(original, working []byte) ([]byte, []byte, error) { + return TranslateRequestPairReturningError(ctx, nil, &config.Config{}, sdktranslator.FormatClaude, to, "m", original, working, false, compat) + } + routes[name+" with update intent"] = func(original, working []byte) ([]byte, []byte, error) { + originalBody, workingBody, _, err := TranslateRequestPairWithAPIKeyModelCompatibilityAndUpdateIntent(ctx, nil, &config.Config{}, sdktranslator.FormatClaude, to, "m", original, working, false, compat) + return originalBody, workingBody, err + } + } + } + + for name, pair := range routes { + t.Run(name, func(t *testing.T) { + if _, working, err := pair(file, text); err != nil || !gjson.ValidBytes(working) { + t.Fatalf("failing baseline rejected a working payload that translated: err = %v, working = %s", err, working) + } + if _, _, err := pair(text, file); err == nil { + t.Fatal("a failing working payload was accepted") + } else { + requireUnsupportedPart(t, "working fails", err, "container_upload") + } + if _, _, err := pair(file, file); err == nil { + t.Fatal("a failing payload shared by both sides was accepted") + } else { + requireUnsupportedPart(t, "same slice fails", err, "container_upload") + } + if _, _, err := pair(text, text); err != nil { + t.Fatalf("same slice that translated returned %v", err) + } + }) + } +} + +// A refused baseline never rejects or replaces the working payload that translated. +func TestEnvelopePairKeepsTheWorkingPayloadWhenTheBaselineIsRefused(t *testing.T) { + file := []byte(pairFileOnlyClaude) + text := []byte(pairTextOnlyClaude) + req := sdktranslator.RequestEnvelope{Format: sdktranslator.FormatClaude, Model: "m"} + _, working, err := TranslateRequestEnvelopePairWithCodexMultiAgentV2(context.Background(), nil, &config.Config{}, sdktranslator.FormatClaude, sdktranslator.FormatAntigravity, req, append([]byte(nil), file...), text) + if err != nil { + t.Fatalf("err = %v", err) + } + if got := gjson.GetBytes(working, "request.contents.0.parts.0.text").String(); got != "keep me" { + t.Fatalf("working = %s", working) + } +} + +// A Responses request whose only user content is an input_file file id must be +// refused with a named 400 on the default envelope path and on the compat path. +func TestResponsesFileIDOnlyReturns400OnEveryPath(t *testing.T) { + payload := []byte(`{"model":"claude-sonnet-4","input":[{"type":"message","role":"user","content":[{"type":"input_file","file_id":"file-1"}]}]}`) + for _, compat := range []bool{false, true} { + _, single := TranslateRequestReturningError(context.Background(), nil, &config.Config{}, sdktranslator.FormatOpenAIResponse, sdktranslator.FormatClaude, "claude-sonnet-4", payload, false, compat) + requireUnsupportedPart(t, "single", single, "input_file") + _, _, pair := TranslateRequestPairReturningError(context.Background(), nil, &config.Config{}, sdktranslator.FormatOpenAIResponse, sdktranslator.FormatClaude, "claude-sonnet-4", payload, payload, false, compat) + requireUnsupportedPart(t, "pair", pair, "input_file") + _, _, _, intent := TranslateRequestPairWithAPIKeyModelCompatibilityAndUpdateIntent(context.Background(), nil, &config.Config{}, sdktranslator.FormatOpenAIResponse, sdktranslator.FormatClaude, "claude-sonnet-4", payload, payload, false, compat) + requireUnsupportedPart(t, "pair with update intent", intent, "input_file") + } +} + +func TestResponsesAudioAndTextBesideFileIDOnCompatPath(t *testing.T) { + audio := []byte(`{"model":"claude-sonnet-4","input":[{"type":"message","role":"user","content":[{"type":"input_audio","input_audio":{"data":"UklGRg==","format":"wav"}}]}]}`) + _, err := TranslateRequestReturningError(context.Background(), nil, &config.Config{}, sdktranslator.FormatOpenAIResponse, sdktranslator.FormatClaude, "claude-sonnet-4", audio, false, true) + requireUnsupportedPart(t, "audio", err, "input_audio") + + mixed := []byte(`{"model":"claude-sonnet-4","input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"keep me"},{"type":"input_file","file_id":"file-1"}]}]}`) + body, err := TranslateRequestReturningError(context.Background(), nil, &config.Config{}, sdktranslator.FormatOpenAIResponse, sdktranslator.FormatClaude, "claude-sonnet-4", mixed, false, true) + if err != nil { + t.Fatalf("text beside a file id was refused: %v", err) + } + if got := gjson.GetBytes(body, "messages.0.content").String(); got != "keep me" { + t.Fatalf("text was lost: %s", body) + } +} + +// Antigravity is reached through the same checked registry as every other target. +func TestAntigravityTargetsReportUnsupportedParts(t *testing.T) { + claudeFile := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"container_upload","file_id":"file-1"}]}]}`) + _, err := TranslateRequestReturningError(context.Background(), nil, &config.Config{}, sdktranslator.FormatClaude, sdktranslator.FormatAntigravity, "m", claudeFile, false, false) + requireUnsupportedPart(t, "claude to antigravity", err, "container_upload") + + openAIFile := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"file","file":{"file_id":"file-1"}}]}]}`) + _, err = TranslateRequestReturningError(context.Background(), nil, &config.Config{}, sdktranslator.FormatOpenAI, sdktranslator.FormatAntigravity, "m", openAIFile, false, false) + requireUnsupportedPart(t, "openai to antigravity", err, "file") +} diff --git a/internal/runtime/executor/helps/request_pair_plugin_host_test.go b/internal/runtime/executor/helps/request_pair_plugin_host_test.go index c7abe81f15a..9e403fe9978 100644 --- a/internal/runtime/executor/helps/request_pair_plugin_host_test.go +++ b/internal/runtime/executor/helps/request_pair_plugin_host_test.go @@ -45,7 +45,11 @@ func TestRequestPairWithEmptyPluginHostSanitizesSignaturesOnce(t *testing.T) { var base, work []byte if route == "envelope" { req := sdktranslator.RequestEnvelope{Format: sdktranslator.FormatOpenAIResponse, Model: "gemini-3.6-flash-high", Stream: stream} - base, work = helps.TranslateRequestEnvelopePairWithCodexMultiAgentV2(t.Context(), nil, &config.Config{}, sdktranslator.FormatOpenAIResponse, sdktranslator.FormatAntigravity, req, payload, payload) + var errTranslate error + base, work, errTranslate = helps.TranslateRequestEnvelopePairWithCodexMultiAgentV2(t.Context(), nil, &config.Config{}, sdktranslator.FormatOpenAIResponse, sdktranslator.FormatAntigravity, req, payload, payload) + if errTranslate != nil { + t.Fatalf("translate request pair: %v", errTranslate) + } } else { base, work = helps.TranslateRequestPairWithAPIKeyModelCompatibility(t.Context(), nil, &config.Config{}, sdktranslator.FormatOpenAIResponse, sdktranslator.FormatAntigravity, "gemini-3.6-flash-high", payload, payload, stream, route == "api-key-compat") } diff --git a/internal/runtime/executor/helps/request_unsupported_user_turn_test.go b/internal/runtime/executor/helps/request_unsupported_user_turn_test.go new file mode 100644 index 00000000000..feb3c8819d3 --- /dev/null +++ b/internal/runtime/executor/helps/request_unsupported_user_turn_test.go @@ -0,0 +1,99 @@ +package helps + +import ( + "context" + "testing" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +const ( + chatHistory = `{"role":"user","content":"hello"},{"role":"assistant","content":"hi"}` + responsesHistory = `{"type":"message","role":"user","content":[{"type":"input_text","text":"hello"}]},{"type":"message","role":"assistant","content":[{"type":"output_text","text":"hi"}]}` +) + +// Every executor reaches the translators through these helpers, so the refusal +// must survive the registry, the multi-agent wrapper and the compat switch. +func TestTranslateRequestReturningErrorRefusesEmptiedAttachmentTurns(t *testing.T) { + ctx := context.Background() + routes := []struct { + name string + from, to sdktranslator.Format + refused string + wantType string + accepted string + }{ + { + name: "openai chat to codex", + from: sdktranslator.FormatOpenAI, + to: sdktranslator.FormatCodex, + refused: `{"model":"m","messages":[` + chatHistory + `,{"role":"user","content":[{"type":"file","file":{"filename":"a.pdf"}}]}]}`, + accepted: `{"model":"m","messages":[` + chatHistory + `,{"role":"user","content":[{"type":"file","file":{"file_id":"file-1"}}]}]}`, + wantType: "file", + }, + { + name: "openai chat to interactions", + from: sdktranslator.FormatOpenAI, + to: sdktranslator.FormatInteractions, + refused: `{"model":"m","messages":[` + chatHistory + `,{"role":"user","content":[{"type":"file","file":{"file_id":"file-1"}}]}]}`, + accepted: `{"model":"m","messages":[` + chatHistory + `,{"role":"user","content":[{"type":"file","file":{"file_data":"data:application/pdf;base64,JVBERi0xLjQK","filename":"a.pdf"}}]}]}`, + wantType: "file", + }, + { + name: "responses to openai chat", + from: sdktranslator.FormatOpenAIResponse, + to: sdktranslator.FormatOpenAI, + refused: `{"model":"m","input":[` + responsesHistory + `,{"type":"message","role":"user","content":[{"type":"input_file","file_url":"https://example.test/a.pdf"}]}]}`, + accepted: `{"model":"m","input":[` + responsesHistory + `,{"type":"message","role":"user","content":[{"type":"input_file","file_id":"file-1"}]}]}`, + wantType: "input_file", + }, + { + name: "responses to gemini", + from: sdktranslator.FormatOpenAIResponse, + to: sdktranslator.FormatGemini, + refused: `{"model":"m","input":[` + responsesHistory + `,{"type":"message","role":"user","content":[{"type":"input_file","file_id":"file-1"}]}]}`, + accepted: `{"model":"m","input":[` + responsesHistory + `,{"type":"message","role":"user","content":[{"type":"input_file","file_data":"data:application/pdf;base64,JVBERi0xLjQK"}]}]}`, + wantType: "input_file", + }, + { + name: "responses to antigravity", + from: sdktranslator.FormatOpenAIResponse, + to: sdktranslator.FormatAntigravity, + refused: `{"model":"m","input":[` + responsesHistory + `,{"type":"message","role":"user","content":[{"type":"input_file","file_id":"file-1"}]}]}`, + accepted: `{"model":"m","input":[` + responsesHistory + `,{"type":"message","role":"user","content":[{"type":"input_file","file_data":"data:application/pdf;base64,JVBERi0xLjQK"}]}]}`, + wantType: "input_file", + }, + { + name: "responses to interactions", + from: sdktranslator.FormatOpenAIResponse, + to: sdktranslator.FormatInteractions, + refused: `{"model":"m","input":[` + responsesHistory + `,{"type":"message","role":"user","content":[{"type":"input_file","file_id":"file-1"}]}]}`, + accepted: `{"model":"m","input":[` + responsesHistory + `,{"type":"message","role":"user","content":[{"type":"input_audio","input_audio":{"data":"UklGRg==","format":"wav"}}]}]}`, + wantType: "input_file", + }, + } + for _, route := range routes { + for _, compat := range []bool{false, true} { + name := route.name + if compat { + name += " compat" + } + t.Run(name, func(t *testing.T) { + body, err := TranslateRequestReturningError(ctx, nil, &config.Config{}, route.from, route.to, "m", []byte(route.refused), false, compat) + requireUnsupportedPart(t, "single", err, route.wantType) + if !gjson.ValidBytes(body) { + t.Fatalf("single: body is not JSON: %q", body) + } + + _, _, err = TranslateRequestPairReturningError(ctx, nil, &config.Config{}, route.from, route.to, "m", []byte(route.refused), []byte(route.refused), false, compat) + requireUnsupportedPart(t, "pair", err, route.wantType) + + if _, err = TranslateRequestReturningError(ctx, nil, &config.Config{}, route.from, route.to, "m", []byte(route.accepted), false, compat); err != nil { + t.Fatalf("representable attachment was refused: %v", err) + } + }) + } + } +} diff --git a/internal/runtime/executor/unsupported_part_executor_test.go b/internal/runtime/executor/unsupported_part_executor_test.go index e3dbcd5185a..2eb9b3232ae 100644 --- a/internal/runtime/executor/unsupported_part_executor_test.go +++ b/internal/runtime/executor/unsupported_part_executor_test.go @@ -27,6 +27,17 @@ func TestExecutorsRefuseAFileOnlyTurnBeforeCallingUpstream(t *testing.T) { const ( claudeFile = `{"model":"m","max_tokens":8,"messages":[{"role":"user","content":[{"type":"container_upload","file_id":"file_not_stored"}]}]}` openAIFile = `{"model":"m","messages":[{"role":"user","content":[{"type":"file","file":{"file_id":"file-not-stored"}}]}]}` + // The attachment-only user turn is followed by a developer step that must not hide it. + interactionsDeveloper = `{"model":"m","input":[{"type":"user_input","content":[{"type":"text","text":"hello"}]},{"type":"model_output","content":[{"type":"text","text":"hi"}]},{"type":"user_input","content":[{"type":"document","uri":"gs://b/a.pdf"}]},{"type":"user_input","role":"developer","content":[{"type":"text","text":"note"}]}]}` + // The same emptied audio turn is followed by an instruction step that names itself by role or by type alone. + interactionsCodexAudioPrefix = `{"model":"m","input":[{"type":"user_input","content":[{"type":"text","text":"hello"}]},{"type":"model_output","content":[{"type":"text","text":"hi"}]},{"type":"user_input","content":[{"type":"audio","uri":"gs://b/a.wav"}]},` + interactionsCodexAudioRoleDeveloper = interactionsCodexAudioPrefix + `{"type":"user_input","role":"developer","content":[{"type":"text","text":"note"}]}]}` + interactionsCodexAudioTypeSystem = interactionsCodexAudioPrefix + `{"type":"system","content":[{"type":"text","text":"note"}]}]}` + interactionsCodexAudioTypeDeveloper = interactionsCodexAudioPrefix + `{"type":"developer","content":[{"type":"text","text":"note"}]}]}` + // The only new user turn is inline audio, which Claude cannot read and must not receive as placeholder text. + geminiAudio = `{"model":"m","contents":[{"role":"user","parts":[{"text":"hello"}]},{"role":"model","parts":[{"text":"hi"}]},{"role":"user","parts":[{"inlineData":{"mimeType":"audio/wav","data":"UklGRg=="}}]}]}` + // The only new user turn is a remote image URL, so the earlier turn must not be answered in its place. + openAIImageURL = `{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"image_url","image_url":{"url":"https://x.test/a.png"}}]}]}` ) keyAuth := func(provider string, extra map[string]string) *cliproxyauth.Auth { attrs := map[string]string{"api_key": "k", "base_url": server.URL} @@ -48,6 +59,13 @@ func TestExecutorsRefuseAFileOnlyTurnBeforeCallingUpstream(t *testing.T) { {"claude to codex", NewCodexExecutor(&config.Config{}), keyAuth("codex", map[string]string{"plan_type": "pro"}), "claude", claudeFile, "container_upload"}, {"openai to claude", NewClaudeExecutor(&config.Config{}), keyAuth("claude", nil), "openai", openAIFile, "file"}, {"openai to gemini", NewGeminiExecutor(&config.Config{}), keyAuth("gemini", nil), "openai", openAIFile, "file"}, + {"openai image_url to gemini", NewGeminiExecutor(&config.Config{}), keyAuth("gemini", nil), "openai", openAIImageURL, "image_url"}, + {"gemini audio to claude", NewClaudeExecutor(&config.Config{}), keyAuth("claude", nil), "gemini", geminiAudio, "inlineData"}, + {"interactions developer step to claude", NewClaudeExecutor(&config.Config{}), keyAuth("claude", nil), "interactions", interactionsDeveloper, "document"}, + {"interactions developer step to gemini", NewGeminiExecutor(&config.Config{}), keyAuth("gemini", nil), "interactions", interactionsDeveloper, "document"}, + {"interactions developer role to codex", NewCodexExecutor(&config.Config{}), keyAuth("codex", map[string]string{"plan_type": "pro"}), "interactions", interactionsCodexAudioRoleDeveloper, "audio"}, + {"interactions system type to codex", NewCodexExecutor(&config.Config{}), keyAuth("codex", map[string]string{"plan_type": "pro"}), "interactions", interactionsCodexAudioTypeSystem, "audio"}, + {"interactions developer type to codex", NewCodexExecutor(&config.Config{}), keyAuth("codex", map[string]string{"plan_type": "pro"}), "interactions", interactionsCodexAudioTypeDeveloper, "audio"}, } for _, target := range targets { req := cliproxyexecutor.Request{Model: "m", Payload: []byte(target.payload)} diff --git a/internal/translator/antigravity/claude/antigravity_claude_request.go b/internal/translator/antigravity/claude/antigravity_claude_request.go index b55713ae0c7..ac4e130f50b 100644 --- a/internal/translator/antigravity/claude/antigravity_claude_request.go +++ b/internal/translator/antigravity/claude/antigravity_claude_request.go @@ -305,12 +305,20 @@ func logDroppedAntigravityToolUseSignature(modelName string, messageIndex, conte // // Returns: // - []byte: The transformed request data in Antigravity API format -func ConvertClaudeRequestToAntigravity(modelName string, inputRawJSON []byte, _ bool) []byte { +func ConvertClaudeRequestToAntigravity(modelName string, inputRawJSON []byte, stream bool) []byte { + body, _ := convertClaudeRequestToAntigravity(modelName, inputRawJSON, stream) + return body +} + +// convertClaudeRequestToAntigravity also reports an attachment Antigravity +// cannot receive when it leaves a user turn with nothing to send. +func convertClaudeRequestToAntigravity(modelName string, inputRawJSON []byte, _ bool) ([]byte, error) { enableThoughtTranslate := true rawJSON := inputRawJSON if shouldBuildAntigravityWebSearchRequest(modelName, rawJSON) { - return buildAntigravityWebSearchRequest(modelName, rawJSON) + return buildAntigravityWebSearchRequest(modelName, rawJSON), nil } + var drops translatorcommon.UserTurnDrops functionNameMap := util.SanitizedFunctionNameMap(rawJSON) // system instruction @@ -732,6 +740,15 @@ func ConvertClaudeRequestToAntigravity(modelName string, inputRawJSON []byte, _ partJSON := []byte(`{}`) partJSON, _ = sjson.SetRawBytes(partJSON, "inlineData", inlineDataJSON) partItems = append(partItems, partJSON) + } else if originalRole == "user" { + // A part that cannot be inlined (url or file source) is dropped; the turn is refused only if nothing else is left. + drops.Drop("image") + } + } else if contentTypeResult.Type == gjson.String && (contentTypeResult.String() == "document" || contentTypeResult.String() == "container_upload") { + if partJSON := claudeBase64InlineData(contentResult.Get("source")); partJSON != nil { + partItems = append(partItems, partJSON) + } else if originalRole == "user" { + drops.Drop(contentTypeResult.String()) } } } @@ -740,6 +757,11 @@ func ConvertClaudeRequestToAntigravity(modelName string, inputRawJSON []byte, _ clearPendingDetachedSignature() } + if originalRole == "user" { + // Whitespace-only text is forwarded but never keeps an emptied turn alive. + drops.EndTurn(translatorcommon.CountSendableGeminiParts(partItems)) + } + // Reorder model parts: thinking first, regular content second, function calls and trailing signature carriers last. if len(partItems) == 0 { continue @@ -942,7 +964,27 @@ func ConvertClaudeRequestToAntigravity(modelName string, inputRawJSON []byte, _ out = sigcompat.SanitizeGeminiRequestThoughtSignatures(out, "request.contents") } - return out + return out, drops.Err() +} + +// claudeBase64InlineData converts a Claude base64 source into an Antigravity +// inlineData part. A file id or url carries no bytes, so it stays unconverted +// and the caller reports it. +func claudeBase64InlineData(source gjson.Result) []byte { + if source.Get("type").String() != "base64" { + return nil + } + mimeType := source.Get("media_type").String() + data := source.Get("data").String() + if mimeType == "" || data == "" { + return nil + } + inlineDataJSON := []byte(`{}`) + inlineDataJSON, _ = sjson.SetBytes(inlineDataJSON, "mimeType", mimeType) + inlineDataJSON, _ = sjson.SetBytes(inlineDataJSON, "data", data) + partJSON := []byte(`{}`) + partJSON, _ = sjson.SetRawBytes(partJSON, "inlineData", inlineDataJSON) + return partJSON } func antigravityClaudeContent(role string, parts [][]byte) []byte { diff --git a/internal/translator/antigravity/claude/antigravity_claude_user_turn_test.go b/internal/translator/antigravity/claude/antigravity_claude_user_turn_test.go new file mode 100644 index 00000000000..6361c4661ef --- /dev/null +++ b/internal/translator/antigravity/claude/antigravity_claude_user_turn_test.go @@ -0,0 +1,185 @@ +package claude + +import ( + "context" + "errors" + "testing" + + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +const userTurnUpload = `{"type":"container_upload","file_id":"file-1"}` + +func TestConvertClaudeRequestToAntigravity_RefusesAnyEmptiedUserTurn(t *testing.T) { + cases := []struct { + name string + input string + wantType string + }{ + { + name: "history then attachment only", + input: `{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":[{"type":"text","text":"hi"}]},{"role":"user","content":[` + userTurnUpload + `]}]}`, + wantType: "container_upload", + }, + { + name: "system prompt and system reminder", + input: `{"model":"m","system":"sys","messages":[{"role":"system","content":"reminder"},{"role":"user","content":[` + userTurnUpload + `]}]}`, + wantType: "container_upload", + }, + { + name: "emptied turn before a later text turn", + input: `{"model":"m","messages":[{"role":"user","content":[` + userTurnUpload + `]},{"role":"assistant","content":[{"type":"text","text":"ok"}]},{"role":"user","content":"next"}]}`, + wantType: "container_upload", + }, + { + name: "document without bytes", + input: `{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"document","source":{"type":"file","file_id":"file-1"}}]}]}`, + wantType: "document", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + body, err := convertClaudeRequestToAntigravity("m", []byte(tc.input), false) + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(err, &unsupported) || unsupported.Type != tc.wantType || unsupported.StatusCode() != 400 { + t.Fatalf("err = %v, want unsupported content part: %s; body = %s", err, tc.wantType, body) + } + if got, want := err.Error(), "unsupported content part: "+tc.wantType; got != want { + t.Fatalf("error text = %q, want %q", got, want) + } + if !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } + }) + } +} + +func TestConvertClaudeRequestToAntigravity_KeepsTurnWithTextBesideAttachment(t *testing.T) { + input := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"text","text":"keep me"},` + userTurnUpload + `]}]}`) + body, err := convertClaudeRequestToAntigravity("m", input, false) + if err != nil { + t.Fatalf("err = %v", err) + } + if got := gjson.GetBytes(body, "request.contents.2.parts.0.text").String(); got != "keep me" { + t.Fatalf("text was lost: %s", body) + } +} + +func TestConvertClaudeRequestToAntigravity_Base64DocumentBecomesInlineData(t *testing.T) { + input := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"document","source":{"type":"base64","media_type":"application/pdf","data":"JVBERi0xLjQK"}}]}]}`) + body, err := convertClaudeRequestToAntigravity("m", input, false) + if err != nil { + t.Fatalf("err = %v", err) + } + inlineData := gjson.GetBytes(body, "request.contents.2.parts.0.inlineData") + if inlineData.Get("mimeType").String() != "application/pdf" || inlineData.Get("data").String() != "JVBERi0xLjQK" { + t.Fatalf("inlineData = %s, body = %s", inlineData.Raw, body) + } +} + +func TestConvertClaudeRequestToAntigravity_ExportedWrapperKeepsAJSONBody(t *testing.T) { + input := []byte(`{"model":"m","messages":[{"role":"user","content":[` + userTurnUpload + `]}]}`) + if body := ConvertClaudeRequestToAntigravity("m", input, false); !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } +} + +func TestClaudeToAntigravityRegistryCarriesTheRefusal(t *testing.T) { + input := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[` + userTurnUpload + `]}]}`) + envelope := sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatClaude, sdktranslator.FormatAntigravity, sdktranslator.RequestEnvelope{ + Format: sdktranslator.FormatClaude, + Model: "m", + Body: input, + }) + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(envelope.Err, &unsupported) || unsupported.Type != "container_upload" { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } +} + +// claudeImageTurnToAntigravity translates a conversation of two history turns followed by a final user +// turn holding the given content parts. +func claudeImageTurnToAntigravity(finalContent string) sdktranslator.RequestEnvelope { + input := `{"model":"m","messages":[{"role":"user","content":"a"},{"role":"assistant","content":"b"},{"role":"user","content":[` + finalContent + `]}]}` + return sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatClaude, sdktranslator.FormatAntigravity, sdktranslator.RequestEnvelope{ + Format: sdktranslator.FormatClaude, + Model: "m", + Body: []byte(input), + }) +} + +func requireImageRefusal(t *testing.T, envelope sdktranslator.RequestEnvelope) { + t.Helper() + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(envelope.Err, &unsupported) || unsupported.Type != "image" || unsupported.StatusCode() != 400 { + t.Fatalf("envelope.Err = %v, want unsupported content part: image; body = %s", envelope.Err, envelope.Body) + } + if got, want := envelope.Err.Error(), "unsupported content part: image"; got != want { + t.Fatalf("error text = %q, want %q", got, want) + } +} + +func TestClaudeToAntigravityUnrepresentableImageOnlyTurnIsRefused(t *testing.T) { + cases := map[string]string{ + "url source": `{"type":"url","url":"https://example.test/a.png"}`, + "file source": `{"type":"file","file_id":"file-1"}`, + } + for name, source := range cases { + t.Run(name, func(t *testing.T) { + requireImageRefusal(t, claudeImageTurnToAntigravity(`{"type":"image","source":`+source+`}`)) + }) + } +} + +func TestClaudeToAntigravityUnrepresentableImageBesideTextStillSucceeds(t *testing.T) { + for _, source := range []string{`{"type":"url","url":"https://example.test/a.png"}`, `{"type":"file","file_id":"file-1"}`} { + envelope := claudeImageTurnToAntigravity(`{"type":"text","text":"keep me"},{"type":"image","source":` + source + `}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + parts := gjson.GetBytes(envelope.Body, "request.contents.2.parts").Array() + if len(parts) != 1 || parts[0].Get("text").String() != "keep me" { + t.Fatalf("text was lost or an image leaked: %s", envelope.Body) + } + } +} + +func TestClaudeToAntigravityEmptyTextDoesNotHideAnUnrepresentableImage(t *testing.T) { + requireImageRefusal(t, claudeImageTurnToAntigravity(`{"type":"text","text":""},{"type":"image","source":{"type":"url","url":"https://example.test/a.png"}}`)) +} + +func TestClaudeToAntigravityBase64ImageOnlyTurnStaysInlineData(t *testing.T) { + envelope := claudeImageTurnToAntigravity(`{"type":"image","source":{"type":"base64","media_type":"image/png","data":"aGVsbG8="}}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + inlineData := gjson.GetBytes(envelope.Body, "request.contents.2.parts.0.inlineData") + if inlineData.Get("mimeType").String() != "image/png" || inlineData.Get("data").String() != "aGVsbG8=" { + t.Fatalf("inlineData = %s, body = %s", inlineData.Raw, envelope.Body) + } +} + +func TestClaudeToAntigravityWhitespaceTextDoesNotHideAnUnrepresentableImage(t *testing.T) { + for _, text := range []string{" ", ` \n\t`, `\u00a0`} { + requireImageRefusal(t, claudeImageTurnToAntigravity(`{"type":"text","text":"`+text+`"},{"type":"image","source":{"type":"file","file_id":"file-1"}}`)) + } + requireImageRefusal(t, claudeImageTurnToAntigravity(`{"type":"image","source":{"type":"url","url":"https://example.test/a.png"}},{"type":"text","text":" "}`)) +} + +func TestClaudeToAntigravityRealTextBesideWhitespaceAndAnImageStillSucceeds(t *testing.T) { + envelope := claudeImageTurnToAntigravity(`{"type":"text","text":" "},{"type":"text","text":"keep me"},{"type":"image","source":{"type":"file","file_id":"file-1"}}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + found := false + for _, part := range gjson.GetBytes(envelope.Body, "request.contents.2.parts").Array() { + if part.Get("text").String() == "keep me" { + found = true + } + } + if !found { + t.Fatalf("text was lost: %s", envelope.Body) + } +} diff --git a/internal/translator/antigravity/claude/init.go b/internal/translator/antigravity/claude/init.go index 8bd96f6388b..9f12ad78711 100644 --- a/internal/translator/antigravity/claude/init.go +++ b/internal/translator/antigravity/claude/init.go @@ -4,17 +4,19 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( Claude, Antigravity, - ConvertClaudeRequestToAntigravity, + nil, interfaces.TranslateResponse{ Stream: ConvertAntigravityResponseToClaude, NonStream: ConvertAntigravityResponseToClaudeNonStream, TokenCount: ClaudeTokenCount, }, ) + sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatClaude, sdktranslator.FormatAntigravity, convertClaudeRequestToAntigravity) } diff --git a/internal/translator/antigravity/interactions/init.go b/internal/translator/antigravity/interactions/init.go index a39e2075c9e..3cbbd58cd29 100644 --- a/internal/translator/antigravity/interactions/init.go +++ b/internal/translator/antigravity/interactions/init.go @@ -4,16 +4,18 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( Interactions, Antigravity, - ConvertInteractionsRequestToAntigravity, + nil, interfaces.TranslateResponse{ Stream: ConvertAntigravityResponseToInteractions, NonStream: ConvertAntigravityResponseToInteractionsNonStream, }, ) + sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatInteractions, sdktranslator.FormatAntigravity, convertInteractionsRequestToAntigravity) } diff --git a/internal/translator/antigravity/interactions/interactions_antigravity_instruction_test.go b/internal/translator/antigravity/interactions/interactions_antigravity_instruction_test.go new file mode 100644 index 00000000000..d90685bd6fe --- /dev/null +++ b/internal/translator/antigravity/interactions/interactions_antigravity_instruction_test.go @@ -0,0 +1,60 @@ +package interactions + +import ( + "strings" + "testing" +) + +// antigravityInstructionSteps are developer and system steps in the shapes an +// Interactions client can send. Each one carries the text "note". +var antigravityInstructionSteps = map[string]string{ + "developer user_input": `{"type":"user_input","role":"developer","content":[{"type":"text","text":"note"}]}`, + "system user_input": `{"type":"user_input","role":"system","content":[{"type":"text","text":"note"}]}`, + "developer string content": `{"type":"user_input","role":"developer","content":"note"}`, + "bare system object": `{"role":"system","content":"note"}`, + "bare system text": `{"type":"system","text":"note"}`, + "developer native parts": `{"role":"developer","parts":[{"text":"note"}]}`, + "developer wrapper": `{"role":"developer","steps":[{"type":"user_input","content":[{"type":"text","text":"note"}]}]}`, +} + +// antigravityEmptiedStep is a user step whose only part Antigravity cannot carry. +const antigravityEmptiedStep = `{"type":"user_input","content":[{"type":"document","uri":"gs://b/a.pdf"}]}` + +func TestInteractionsToAntigravityDeveloperOrSystemStepDoesNotHideAnEmptiedUserTurn(t *testing.T) { + for name, note := range antigravityInstructionSteps { + t.Run("after "+name, func(t *testing.T) { + requireInteractionsToAntigravityRefusal(t, interactionsToAntigravityEnvelope(`{"model":"m","input":[`+interactionsAntigravityHistory+`,`+antigravityEmptiedStep+`,`+note+`]}`), "document") + }) + t.Run("before "+name, func(t *testing.T) { + requireInteractionsToAntigravityRefusal(t, interactionsToAntigravityEnvelope(`{"model":"m","input":[`+interactionsAntigravityHistory+`,`+note+`,`+antigravityEmptiedStep+`]}`), "document") + }) + } +} + +func TestInteractionsToAntigravityDeveloperOrSystemStepStillSendsItsText(t *testing.T) { + for name, note := range antigravityInstructionSteps { + t.Run(name, func(t *testing.T) { + envelope := interactionsToAntigravityEnvelope(`{"model":"m","input":[` + interactionsAntigravityHistory + `,{"type":"user_input","content":[{"type":"text","text":"keep me"}]},` + note + `]}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + if !strings.Contains(string(envelope.Body), "note") || !strings.Contains(string(envelope.Body), "keep me") { + t.Fatalf("text was lost: %s", envelope.Body) + } + }) + } +} + +func TestInteractionsToAntigravityRealUserTextBesideAnUnrepresentableAttachmentSurvivesAnInstructionStep(t *testing.T) { + for name, note := range antigravityInstructionSteps { + t.Run(name, func(t *testing.T) { + envelope := interactionsToAntigravityEnvelope(`{"model":"m","input":[` + interactionsAntigravityHistory + `,` + note + `,{"type":"user_input","content":[{"type":"text","text":"keep me"},` + `{"type":"document","uri":"gs://b/a.pdf"}` + `]}]}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + if !strings.Contains(string(envelope.Body), "keep me") { + t.Fatalf("text was lost: %s", envelope.Body) + } + }) + } +} diff --git a/internal/translator/antigravity/interactions/interactions_antigravity_request.go b/internal/translator/antigravity/interactions/interactions_antigravity_request.go index 88fa61f9c5d..b69d922005d 100644 --- a/internal/translator/antigravity/interactions/interactions_antigravity_request.go +++ b/internal/translator/antigravity/interactions/interactions_antigravity_request.go @@ -12,6 +12,13 @@ import ( ) func ConvertInteractionsRequestToAntigravity(modelName string, inputRawJSON []byte, stream bool) []byte { + out, _ := convertInteractionsRequestToAntigravity(modelName, inputRawJSON, stream) + return out +} + +// convertInteractionsRequestToAntigravity also reports a user turn that was left +// empty because its only attachment has no Antigravity equivalent. +func convertInteractionsRequestToAntigravity(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { root := gjson.ParseBytes(inputRawJSON) functionNameMap := util.SanitizedFunctionNameMap(inputRawJSON) out := []byte(`{"project":"","request":{"contents":[]},"model":""}`) @@ -22,7 +29,7 @@ func ConvertInteractionsRequestToAntigravity(modelName string, inputRawJSON []by out = copyInteractionsSystemToAntigravity(out, root) out = copyInteractionsGenerationConfigToAntigravity(out, root) contentItems := translatorcommon.NewRawArrayItems(root.Get("input.#").Int()) - appendInteractionsInputToAntigravity(&contentItems, root.Get("input")) + errInput := appendInteractionsInputToAntigravity(&contentItems, root.Get("input")) out = translatorcommon.SetRawArrayItems(out, "request.contents", contentItems) out = copyInteractionsToolsToAntigravity(out, root, functionNameMap) if gjson.GetBytes(out, "request.toolConfig.functionCallingConfig.mode").String() == "NONE" { @@ -30,7 +37,7 @@ func ConvertInteractionsRequestToAntigravity(modelName string, inputRawJSON []by } out = rewriteInteractionsFunctionNames(out, functionNameMap) out = attachDefaultAntigravitySafetySettings(out) - return out + return out, errInput } func rewriteInteractionsFunctionNames(out []byte, functionNameMap map[string]string) []byte { @@ -298,11 +305,36 @@ type antigravityInteractionsInputContext struct { inModelTurn bool lastStepType string pendingSignature string + // run follows the consecutive user content so that an attachment Antigravity + // cannot carry is refused only when its whole user turn is left with nothing to send. + run translatorcommon.UserRun + // instruction is set while the step being added is developer or system content. + instruction bool +} + +// userRun returns the tracker for content added with role. Model content and +// developer or system content close the open user turn and have no tracker, so +// they can never keep an emptied user turn alive. +func (ctx *antigravityInteractionsInputContext) userRun(role string) *translatorcommon.UserRun { + if role == "user" && !ctx.instruction { + return &ctx.run + } + ctx.run.End() + return nil +} + +// appendText adds a text content; blank text does not keep a user turn alive. +func (ctx *antigravityInteractionsInputContext) appendText(role, text string) { + appendAntigravityTextContent(&ctx.items, role, text) + run := ctx.userRun(role) + if strings.TrimSpace(text) != "" { + run.Add() + } } -func appendInteractionsInputToAntigravity(items *[][]byte, input gjson.Result) { +func appendInteractionsInputToAntigravity(items *[][]byte, input gjson.Result) error { if !input.Exists() { - return + return nil } ctx := &antigravityInteractionsInputContext{ items: *items, @@ -311,7 +343,7 @@ func appendInteractionsInputToAntigravity(items *[][]byte, input gjson.Result) { appendAntigravityTextContent(&ctx.items, "user", input.String()) ctx.lastStepType = "text" *items = ctx.items - return + return nil } if input.IsArray() { input.ForEach(func(_, item gjson.Result) bool { @@ -323,24 +355,31 @@ func appendInteractionsInputToAntigravity(items *[][]byte, input gjson.Result) { if role := input.Get("role").String(); role == "model" || role == "assistant" { defaultRole = "model" } + ctx.instruction = translatorcommon.IsInteractionsInstructionStep(input, false) steps.ForEach(func(_, step gjson.Result) bool { appendInteractionsStepToAntigravity(ctx, step, defaultRole) return true }) + ctx.instruction = false } else { appendInteractionsStepToAntigravity(ctx, input, "user") } flushPendingAntigravitySignature(ctx) *items = ctx.items + ctx.run.End() + return ctx.run.Err() } func appendInteractionsStepToAntigravity(ctx *antigravityInteractionsInputContext, step gjson.Result, defaultRole string) { + inheritedInstruction := ctx.instruction + ctx.instruction = translatorcommon.IsInteractionsInstructionStep(step, inheritedInstruction) + defer func() { ctx.instruction = inheritedInstruction }() if step.Type == gjson.String { if ctx.inModelTurn { flushPendingAntigravitySignature(ctx) ctx.inModelTurn = false } - appendAntigravityTextContent(&ctx.items, defaultRole, step.String()) + ctx.appendText(defaultRole, step.String()) ctx.lastStepType = "text" return } @@ -359,6 +398,7 @@ func appendInteractionsStepToAntigravity(ctx *antigravityInteractionsInputContex } switch step.Get("type").String() { case "model_output": + ctx.run.End() if ctx.pendingSignature != "" { carrier := antigravityTextPartJSON("", false) carrier, _ = sjson.SetBytes(carrier, "thoughtSignature", ctx.pendingSignature) @@ -380,6 +420,7 @@ func appendInteractionsStepToAntigravity(ctx *antigravityInteractionsInputContex ctx.inModelTurn = true ctx.lastStepType = "model_output" case "thought": + ctx.run.End() if sig := firstNonEmptyString(step.Get("signature").String(), step.Get("thought_signature").String(), step.Get("thoughtSignature").String()); sig != "" { if ctx.pendingSignature != "" && ctx.pendingSignature != sig { carrier := antigravityTextPartJSON("", false) @@ -403,6 +444,7 @@ func appendInteractionsStepToAntigravity(ctx *antigravityInteractionsInputContex ctx.inModelTurn = true ctx.lastStepType = "thought" case "function_call": + ctx.run.End() part := buildAntigravityFunctionCallPart(step) sig := firstNonEmptyString(step.Get("signature").String(), step.Get("thought_signature").String(), step.Get("thoughtSignature").String()) if sig == "" && ctx.pendingSignature != "" { @@ -438,6 +480,8 @@ func appendInteractionsStepToAntigravity(ctx *antigravityInteractionsInputContex ctx.inModelTurn = false } part := buildAntigravityFunctionResultPart(step) + // A tool result is content the model reads, so it keeps the surrounding user turn. + ctx.run.Add() if ctx.lastStepType == "function_result" && len(ctx.items) > 0 && gjson.GetBytes(ctx.items[len(ctx.items)-1], "role").String() == "user" { ctx.items[len(ctx.items)-1] = appendGeminiUserContentPart(ctx.items[len(ctx.items)-1], part) } else { @@ -450,9 +494,9 @@ func appendInteractionsStepToAntigravity(ctx *antigravityInteractionsInputContex ctx.inModelTurn = false } if step.Get("parts").Exists() { - appendInteractionsNativeContentToAntigravity(&ctx.items, step, defaultRole) + appendInteractionsNativeContentToAntigravity(ctx, step, defaultRole) } else { - appendInteractionsContentListToAntigravity(&ctx.items, defaultRole, step.Get("content")) + appendInteractionsContentListToAntigravity(ctx, defaultRole, step.Get("content")) } ctx.lastStepType = "user_input" default: @@ -461,11 +505,11 @@ func appendInteractionsStepToAntigravity(ctx *antigravityInteractionsInputContex ctx.inModelTurn = false } if step.Get("parts").Exists() { - appendInteractionsNativeContentToAntigravity(&ctx.items, step, defaultRole) + appendInteractionsNativeContentToAntigravity(ctx, step, defaultRole) } else if step.Get("content").Exists() { - appendInteractionsContentListToAntigravity(&ctx.items, defaultRole, step.Get("content")) + appendInteractionsContentListToAntigravity(ctx, defaultRole, step.Get("content")) } else if text := step.Get("text"); text.Exists() { - appendAntigravityTextContent(&ctx.items, defaultRole, text.String()) + ctx.appendText(defaultRole, text.String()) } ctx.lastStepType = "default" } @@ -623,21 +667,30 @@ func buildAntigravityFunctionResultPart(step gjson.Result) []byte { return part } -func appendInteractionsNativeContentToAntigravity(items *[][]byte, step gjson.Result, defaultRole string) { +func appendInteractionsNativeContentToAntigravity(ctx *antigravityInteractionsInputContext, step gjson.Result, defaultRole string) { parts := step.Get("parts") if !parts.Exists() || !parts.IsArray() { return } + role := antigravityContentRole(step.Get("role").String(), defaultRole) + run := ctx.userRun(role) partItems := make([][]byte, 0, 4) parts.ForEach(func(_, part gjson.Result) bool { - if partJSON := interactionsNativeAntigravityPart(part); len(partJSON) > 0 { - partItems = append(partItems, partJSON) + partJSON := interactionsNativeAntigravityPart(part) + if len(partJSON) == 0 { + if droppedType := translatorcommon.InteractionsAttachmentType(part); droppedType != "" { + run.Drop(droppedType) + } + return true + } + partItems = append(partItems, partJSON) + if translatorcommon.GeminiPartIsSendable(partJSON) { + run.Add() } return true }) if len(partItems) > 0 { - role := antigravityContentRole(step.Get("role").String(), defaultRole) - *items = append(*items, antigravityContent(role, partItems)) + ctx.items = append(ctx.items, antigravityContent(role, partItems)) } } @@ -666,28 +719,38 @@ func appendInteractionsStepContentToAntigravity(items *[][]byte, role string, st } } -func appendInteractionsContentListToAntigravity(items *[][]byte, role string, content gjson.Result) { +func appendInteractionsContentListToAntigravity(ctx *antigravityInteractionsInputContext, role string, content gjson.Result) { if !content.Exists() { return } + run := ctx.userRun(role) if content.IsArray() { content.ForEach(func(_, part gjson.Result) bool { - appendInteractionsContentPartToAntigravity(items, role, part) + appendInteractionsContentPartToAntigravity(&ctx.items, role, part, run) return true }) return } if content.IsObject() { - appendInteractionsContentPartToAntigravity(items, role, content) + appendInteractionsContentPartToAntigravity(&ctx.items, role, content, run) } else if content.Type == gjson.String { - appendAntigravityTextContent(items, role, content.String()) + ctx.appendText(role, content.String()) } } -func appendInteractionsContentPartToAntigravity(items *[][]byte, role string, part gjson.Result) { +// appendInteractionsContentPartToAntigravity adds one content part. run is nil for +// model content; for user content it records what is sent and what cannot be. +func appendInteractionsContentPartToAntigravity(items *[][]byte, role string, part gjson.Result, run *translatorcommon.UserRun) { partJSON := appendInteractionsContentToAntigravityPart(nil, part, false) - if len(partJSON) > 0 { - *items = append(*items, antigravityContent(role, [][]byte{partJSON})) + if len(partJSON) == 0 { + if droppedType := translatorcommon.InteractionsAttachmentType(part); droppedType != "" { + run.Drop(droppedType) + } + return + } + *items = append(*items, antigravityContent(role, [][]byte{partJSON})) + if translatorcommon.GeminiPartIsSendable(partJSON) { + run.Add() } } @@ -716,11 +779,8 @@ func appendInteractionsContentToAntigravityPart(_ []byte, content gjson.Result, return antigravityInlineDataPartJSON(gjson.Parse(fmt.Sprintf(`{"mime_type":%q,"data":%q}`, mimeType, data))) } } - if uri := content.Get("file_uri"); uri.Exists() || content.Get("fileUri").Exists() { - fileURI := uri.String() - if fileURI == "" { - fileURI = content.Get("fileUri").String() - } + // uri is the Interactions spelling of file_uri. + if fileURI := firstNonEmptyString(content.Get("file_uri").String(), content.Get("fileUri").String(), content.Get("uri").String()); fileURI != "" { mimeType := content.Get("mime_type").String() if mimeType == "" { mimeType = content.Get("mimeType").String() diff --git a/internal/translator/antigravity/interactions/interactions_antigravity_uri_test.go b/internal/translator/antigravity/interactions/interactions_antigravity_uri_test.go new file mode 100644 index 00000000000..23375bf81e2 --- /dev/null +++ b/internal/translator/antigravity/interactions/interactions_antigravity_uri_test.go @@ -0,0 +1,151 @@ +package interactions + +import ( + "context" + "errors" + "testing" + + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +const interactionsAntigravityHistory = `{"type":"user_input","content":[{"type":"text","text":"a"}]},{"type":"model_output","content":[{"type":"text","text":"b"}]}` + +func interactionsToAntigravityEnvelope(input string) sdktranslator.RequestEnvelope { + return sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatInteractions, sdktranslator.FormatAntigravity, sdktranslator.RequestEnvelope{ + Format: sdktranslator.FormatInteractions, + Model: "m", + Body: []byte(input), + }) +} + +// interactionsFinalTurnToAntigravity translates two history turns followed by a +// final user step holding the given content parts. +func interactionsFinalTurnToAntigravity(finalContent string) sdktranslator.RequestEnvelope { + return interactionsToAntigravityEnvelope(`{"model":"m","input":[` + interactionsAntigravityHistory + `,{"type":"user_input","content":[` + finalContent + `]}]}`) +} + +func requireInteractionsToAntigravityRefusal(t *testing.T, envelope sdktranslator.RequestEnvelope, wantType string) { + t.Helper() + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(envelope.Err, &unsupported) || unsupported.Type != wantType || unsupported.StatusCode() != 400 { + t.Fatalf("envelope.Err = %v, want unsupported content part: %s; body = %s", envelope.Err, wantType, envelope.Body) + } + if got, want := envelope.Err.Error(), "unsupported content part: "+wantType; got != want { + t.Fatalf("error text = %q, want %q", got, want) + } + if !gjson.ValidBytes(envelope.Body) { + t.Fatalf("body is not JSON: %q", envelope.Body) + } +} + +// TestInteractionsToAntigravityKeepsTheMediaGeminiToInteractionsWrites feeds the +// part shape that the Gemini to Interactions translation emits for a fileData part. +func TestInteractionsToAntigravityKeepsTheMediaGeminiToInteractionsWrites(t *testing.T) { + envelope := interactionsFinalTurnToAntigravity(`{"type":"image","uri":"gs://b/a.png","mime_type":"image/png"}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + if got := gjson.GetBytes(envelope.Body, "request.contents.#").Int(); got != 3 { + t.Fatalf("contents = %d, want 3: %s", got, envelope.Body) + } + fileData := gjson.GetBytes(envelope.Body, "request.contents.2.parts.0.fileData") + if fileData.Get("fileUri").String() != "gs://b/a.png" || fileData.Get("mimeType").String() != "image/png" { + t.Fatalf("last turn lost the file: %s", envelope.Body) + } +} + +func TestInteractionsToAntigravityReadsURIAsFileURI(t *testing.T) { + for _, field := range []string{"uri", "file_uri", "fileUri"} { + t.Run(field, func(t *testing.T) { + envelope := interactionsFinalTurnToAntigravity(`{"type":"document","mime_type":"application/pdf","` + field + `":"gs://b/a.pdf"}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + fileData := gjson.GetBytes(envelope.Body, "request.contents.2.parts.0.fileData") + if fileData.Get("fileUri").String() != "gs://b/a.pdf" || fileData.Get("mimeType").String() != "application/pdf" { + t.Fatalf("fileData = %s, body = %s", fileData.Raw, envelope.Body) + } + }) + } +} + +func TestInteractionsToAntigravityInlineDataStillConverts(t *testing.T) { + envelope := interactionsFinalTurnToAntigravity(`{"type":"image","mime_type":"image/png","data":"aGVsbG8="}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + inlineData := gjson.GetBytes(envelope.Body, "request.contents.2.parts.0.inlineData") + if inlineData.Get("mimeType").String() != "image/png" || inlineData.Get("data").String() != "aGVsbG8=" { + t.Fatalf("inlineData = %s, body = %s", inlineData.Raw, envelope.Body) + } +} + +func TestInteractionsToAntigravityUnrepresentableAttachmentOnlyTurnIsRefused(t *testing.T) { + cases := []struct { + name string + content string + wantType string + }{ + {name: "audio without bytes or uri", content: `{"type":"audio","mime_type":"audio/wav"}`, wantType: "audio"}, + {name: "image without anything", content: `{"type":"image"}`, wantType: "image"}, + {name: "uri without a mime type", content: `{"type":"document","uri":"gs://b/a.pdf"}`, wantType: "document"}, + {name: "image_url that is not a data url", content: `{"type":"image_url","image_url":{"url":"https://example.test/a.png"}}`, wantType: "image_url"}, + {name: "empty text does not hide it", content: `{"type":"text","text":""},{"type":"video","mime_type":"video/mp4"}`, wantType: "video"}, + {name: "whitespace text does not hide it", content: `{"type":"text","text":" \n"},{"type":"audio","mime_type":"audio/wav"}`, wantType: "audio"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + requireInteractionsToAntigravityRefusal(t, interactionsFinalTurnToAntigravity(tc.content), tc.wantType) + }) + } +} + +func TestInteractionsToAntigravityUnrepresentableNativePartIsRefused(t *testing.T) { + envelope := interactionsToAntigravityEnvelope(`{"model":"m","input":[` + interactionsAntigravityHistory + `,{"role":"user","parts":[{"fileData":{"mimeType":"image/png"}}]}]}`) + requireInteractionsToAntigravityRefusal(t, envelope, "fileData") +} + +func TestInteractionsToAntigravityRefusesAnEmptiedTurnBeforeALaterTextTurn(t *testing.T) { + envelope := interactionsToAntigravityEnvelope(`{"model":"m","input":[{"type":"user_input","content":[{"type":"audio","mime_type":"audio/wav"}]},{"type":"model_output","content":[{"type":"text","text":"ok"}]},{"type":"user_input","content":[{"type":"text","text":"next"}]}]}`) + requireInteractionsToAntigravityRefusal(t, envelope, "audio") +} + +func TestInteractionsToAntigravityUnrepresentableAttachmentBesideTextStillSucceeds(t *testing.T) { + envelope := interactionsFinalTurnToAntigravity(`{"type":"text","text":"keep me"},{"type":"audio","mime_type":"audio/wav"}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + if got := gjson.GetBytes(envelope.Body, "request.contents.2.parts.0.text").String(); got != "keep me" { + t.Fatalf("text was lost: %s", envelope.Body) + } + if got := gjson.GetBytes(envelope.Body, "request.contents.2.parts.#").Int(); got != 1 { + t.Fatalf("last turn has %d parts, want 1: %s", got, envelope.Body) + } +} + +func TestInteractionsToAntigravityNeighbouringStepKeepsTheTurnAlive(t *testing.T) { + cases := map[string]string{ + "text step": `{"type":"user_input","content":[{"type":"text","text":"keep me"}]},{"type":"user_input","content":[{"type":"audio","mime_type":"audio/wav"}]}`, + "tool result": `{"type":"function_call","name":"f","call_id":"c1","arguments":{}},{"type":"function_result","name":"f","call_id":"c1","result":{"ok":true}},{"type":"user_input","content":[{"type":"audio","mime_type":"audio/wav"}]}`, + "string step": `"keep me",{"type":"user_input","content":[{"type":"audio","mime_type":"audio/wav"}]}`, + "native step": `{"role":"user","parts":[{"text":"keep me"}]},{"type":"user_input","content":[{"type":"audio","mime_type":"audio/wav"}]}`, + "turn of steps": `{"role":"user","steps":[{"type":"user_input","content":[{"type":"text","text":"keep me"}]},{"type":"user_input","content":[{"type":"audio","mime_type":"audio/wav"}]}]}`, + } + for name, steps := range cases { + t.Run(name, func(t *testing.T) { + envelope := interactionsToAntigravityEnvelope(`{"model":"m","input":[` + interactionsAntigravityHistory + `,` + steps + `]}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + }) + } +} + +func TestInteractionsToAntigravityExportedWrapperKeepsAJSONBody(t *testing.T) { + input := []byte(`{"model":"m","input":[` + interactionsAntigravityHistory + `,{"type":"user_input","content":[{"type":"audio","mime_type":"audio/wav"}]}]}`) + if body := ConvertInteractionsRequestToAntigravity("m", input, false); !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } +} diff --git a/internal/translator/antigravity/openai/chat-completions/antigravity_openai_media_url_test.go b/internal/translator/antigravity/openai/chat-completions/antigravity_openai_media_url_test.go new file mode 100644 index 00000000000..a499a4a1fc8 --- /dev/null +++ b/internal/translator/antigravity/openai/chat-completions/antigravity_openai_media_url_test.go @@ -0,0 +1,92 @@ +package chat_completions + +import ( + "context" + "errors" + "testing" + + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +const ( + mediaImageURL = `{"type":"image_url","image_url":{"url":"https://x.test/a.png"}}` + mediaImageData = `{"type":"image_url","image_url":{"url":"data:image/png;base64,iVBORw0KGgo="}}` + mediaVideoURL = `{"type":"video_url","video_url":{"url":"https://x.test/a.mp4"}}` + mediaAudioNone = `{"type":"input_audio","input_audio":{"data":"","format":"wav"}}` +) + +func mediaTurn(parts string) []byte { + return []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[` + parts + `]}]}`) +} + +func TestConvertOpenAIRequestToAntigravity_RefusesAnAttachmentOnlyTurnItCannotSend(t *testing.T) { + cases := []struct { + name string + parts string + wantType string + }{ + {name: "http image_url", parts: mediaImageURL, wantType: "image_url"}, + {name: "image_url without a base64 payload", parts: `{"type":"image_url","image_url":{"url":"data:image/png,raw"}}`, wantType: "image_url"}, + {name: "image_url as a bare string", parts: `{"type":"image_url","image_url":"https://x.test/a.png"}`, wantType: "image_url"}, + {name: "http video_url", parts: mediaVideoURL, wantType: "video_url"}, + {name: "input_audio without bytes", parts: mediaAudioNone, wantType: "input_audio"}, + {name: "whitespace text beside http image_url", parts: `{"type":"text","text":" "},` + mediaImageURL, wantType: "image_url"}, + {name: "first dropped type is reported", parts: mediaVideoURL + `,` + mediaImageURL, wantType: "video_url"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + body, err := convertOpenAIRequestToAntigravity("m", mediaTurn(tc.parts), false) + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(err, &unsupported) || unsupported.Type != tc.wantType || unsupported.StatusCode() != 400 { + t.Fatalf("err = %v, want unsupported content part: %s; body = %s", err, tc.wantType, body) + } + }) + } +} + +func TestConvertOpenAIRequestToAntigravity_RealTextBesideAnUnsendableAttachmentStillSucceeds(t *testing.T) { + for _, parts := range []string{ + userTurnText + `,` + mediaImageURL, + mediaImageURL + `,` + userTurnText, + `{"type":"text","text":" "},` + userTurnText + `,` + mediaVideoURL + `,` + mediaAudioNone, + } { + body, err := convertOpenAIRequestToAntigravity("m", mediaTurn(parts), false) + if err != nil { + t.Fatalf("parts %s: err = %v, body = %s", parts, err, body) + } + found := false + for _, part := range gjson.GetBytes(body, "request.contents.2.parts").Array() { + if part.Get("text").String() == "keep me" { + found = true + } + } + if !found { + t.Fatalf("parts %s: text was lost: %s", parts, body) + } + } +} + +func TestConvertOpenAIRequestToAntigravity_DataURLImageStillConverts(t *testing.T) { + body, err := convertOpenAIRequestToAntigravity("m", mediaTurn(mediaImageData), false) + if err != nil { + t.Fatalf("err = %v, body = %s", err, body) + } + part := gjson.GetBytes(body, "request.contents.2.parts.0.inlineData") + if part.Get("mimeType").String() != "image/png" || part.Get("data").String() != "iVBORw0KGgo=" { + t.Fatalf("data URL image was not inlined: %s", body) + } +} + +func TestOpenAIToAntigravityRegistryCarriesTheImageURLRefusal(t *testing.T) { + envelope := sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatOpenAI, sdktranslator.FormatAntigravity, sdktranslator.RequestEnvelope{ + Format: sdktranslator.FormatOpenAI, + Model: "m", + Body: mediaTurn(mediaImageURL), + }) + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(envelope.Err, &unsupported) || unsupported.Type != "image_url" { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } +} diff --git a/internal/translator/antigravity/openai/chat-completions/antigravity_openai_request.go b/internal/translator/antigravity/openai/chat-completions/antigravity_openai_request.go index 310ebab45bb..9639d4730ea 100644 --- a/internal/translator/antigravity/openai/chat-completions/antigravity_openai_request.go +++ b/internal/translator/antigravity/openai/chat-completions/antigravity_openai_request.go @@ -28,8 +28,16 @@ const antigravityFunctionThoughtSignature = "skip_thought_signature_validator" // // Returns: // - []byte: The transformed request data in Antigravity API format -func ConvertOpenAIRequestToAntigravity(modelName string, inputRawJSON []byte, _ bool) []byte { +func ConvertOpenAIRequestToAntigravity(modelName string, inputRawJSON []byte, stream bool) []byte { + body, _ := convertOpenAIRequestToAntigravity(modelName, inputRawJSON, stream) + return body +} + +// convertOpenAIRequestToAntigravity also reports a file part Antigravity cannot +// receive when it leaves a user turn with nothing to send. +func convertOpenAIRequestToAntigravity(modelName string, inputRawJSON []byte, _ bool) ([]byte, error) { rawJSON := inputRawJSON + var drops translatorcommon.UserTurnDrops functionNameMap := util.SanitizedFunctionNameMap(rawJSON) // Base envelope (no default thinkingConfig) out := []byte(`{"project":"","request":{"contents":[]},"model":"gemini-2.5-pro"}`) @@ -167,21 +175,17 @@ func ConvertOpenAIRequestToAntigravity(modelName string, inputRawJSON []byte, _ partItems = append(partItems, antigravityOpenAITextPart(antigravityDemotedSystemText(text, isDemotedSystem))) } case "image_url": - imageURL := item.Get("image_url.url").String() - if len(imageURL) > 5 { - pieces := strings.SplitN(imageURL[5:], ";", 2) - if len(pieces) == 2 && len(pieces[1]) > 7 { - part := antigravityOpenAIInlineDataPart(pieces[0], pieces[1][7:], false) - partItems = append(partItems, part) - } + // Only a base64 data URL can be inlined; a remote URL has no equivalent here. + if mimeType, data, ok := translatorcommon.NormalizeOpenAIFileData("", "", item.Get("image_url.url").String()); ok { + partItems = append(partItems, antigravityOpenAIInlineDataPart(mimeType, data, false)) + } else { + drops.Drop("image_url") } case "video_url": - videoURL := item.Get("video_url.url").String() - if len(videoURL) > 5 { - pieces := strings.SplitN(videoURL[5:], ";", 2) - if len(pieces) == 2 && len(pieces[1]) > 7 { - partItems = append(partItems, antigravityOpenAIInlineDataPart(pieces[0], pieces[1][7:], false)) - } + if mimeType, data, ok := translatorcommon.NormalizeOpenAIFileData("", "", item.Get("video_url.url").String()); ok { + partItems = append(partItems, antigravityOpenAIInlineDataPart(mimeType, data, false)) + } else { + drops.Drop("video_url") } case "file": filename := item.Get("file.filename").String() @@ -190,16 +194,21 @@ func ConvertOpenAIRequestToAntigravity(modelName string, inputRawJSON []byte, _ partItems = append(partItems, antigravityOpenAIInlineDataPart(mimeType, data, false)) } else { log.Warn("Invalid file data or unknown file name extension in user message, skip") + drops.Drop("file") } case "input_audio": audioData := item.Get("input_audio.data").String() if audioData != "" { mimeType := antigravityOpenAIAudioMIMEType(item.Get("input_audio.format").String()) partItems = append(partItems, antigravityOpenAIInlineDataPart(mimeType, audioData, true)) + } else { + drops.Drop("input_audio") } } } } + // Whitespace-only text is forwarded but never keeps an emptied turn alive. + drops.EndTurn(translatorcommon.CountSendableGeminiParts(partItems)) if len(partItems) > 0 { contentItems = append(contentItems, antigravityOpenAIContent("user", partItems)) } @@ -438,7 +447,7 @@ func ConvertOpenAIRequestToAntigravity(modelName string, inputRawJSON []byte, _ if strings.Contains(strings.ToLower(modelName), "claude") { out = gemini.SanitizeAntigravityClaudeGeminiRequestSignatures(modelName, out) } - return common.AttachDefaultSafetySettings(out, "request.safetySettings") + return common.AttachDefaultSafetySettings(out, "request.safetySettings"), drops.Err() } func antigravityOpenAITextPart(text string) []byte { diff --git a/internal/translator/antigravity/openai/chat-completions/antigravity_openai_user_turn_test.go b/internal/translator/antigravity/openai/chat-completions/antigravity_openai_user_turn_test.go new file mode 100644 index 00000000000..5ff8bfceeb5 --- /dev/null +++ b/internal/translator/antigravity/openai/chat-completions/antigravity_openai_user_turn_test.go @@ -0,0 +1,98 @@ +package chat_completions + +import ( + "context" + "errors" + "testing" + + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +const ( + userTurnFileID = `{"type":"file","file":{"file_id":"file-absent"}}` + userTurnText = `{"type":"text","text":"keep me"}` + userTurnInline = `{"type":"file","file":{"filename":"a.pdf","file_data":"data:application/pdf;base64,JVBERi0xLjQK"}}` +) + +func TestConvertOpenAIRequestToAntigravity_RefusesAnyEmptiedUserTurn(t *testing.T) { + cases := []struct { + name string + input string + wantType string + }{ + { + name: "history then file id only", + input: `{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[` + userTurnFileID + `]}]}`, + wantType: "file", + }, + { + name: "system and developer prompts do not hide the empty turn", + input: `{"model":"m","messages":[{"role":"system","content":"sys"},{"role":"developer","content":"dev"},{"role":"user","content":[` + userTurnFileID + `]}]}`, + wantType: "file", + }, + { + name: "emptied turn before a later text turn", + input: `{"model":"m","messages":[{"role":"user","content":[` + userTurnFileID + `]},{"role":"assistant","content":"ok"},{"role":"user","content":"next"}]}`, + wantType: "file", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + body, err := convertOpenAIRequestToAntigravity("m", []byte(tc.input), false) + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(err, &unsupported) || unsupported.Type != tc.wantType || unsupported.StatusCode() != 400 { + t.Fatalf("err = %v, want unsupported content part: %s; body = %s", err, tc.wantType, body) + } + if got, want := err.Error(), "unsupported content part: "+tc.wantType; got != want { + t.Fatalf("error text = %q, want %q", got, want) + } + if !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } + }) + } +} + +func TestConvertOpenAIRequestToAntigravity_KeepsTurnWithTextBesideAttachment(t *testing.T) { + input := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[` + userTurnText + `,` + userTurnFileID + `]}]}`) + body, err := convertOpenAIRequestToAntigravity("m", input, false) + if err != nil { + t.Fatalf("err = %v", err) + } + if got := gjson.GetBytes(body, "request.contents.2.parts.0.text").String(); got != "keep me" { + t.Fatalf("text was lost: %s", body) + } +} + +func TestConvertOpenAIRequestToAntigravity_InlineFileAfterHistoryStaysInlineData(t *testing.T) { + input := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[` + userTurnInline + `]}]}`) + body, err := convertOpenAIRequestToAntigravity("m", input, false) + if err != nil { + t.Fatalf("err = %v", err) + } + if got := gjson.GetBytes(body, "request.contents.2.parts.0.inlineData.mimeType").String(); got != "application/pdf" { + t.Fatalf("inline file was not kept: %s", body) + } +} + +func TestOpenAIToAntigravityRegistryCarriesTheRefusal(t *testing.T) { + input := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[` + userTurnFileID + `]}]}`) + envelope := sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatOpenAI, sdktranslator.FormatAntigravity, sdktranslator.RequestEnvelope{ + Format: sdktranslator.FormatOpenAI, + Model: "m", + Body: input, + }) + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(envelope.Err, &unsupported) || unsupported.Type != "file" { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } +} + +func TestConvertOpenAIRequestToAntigravity_ExportedWrapperKeepsAJSONBody(t *testing.T) { + input := []byte(`{"model":"m","messages":[{"role":"user","content":[` + userTurnFileID + `]}]}`) + if body := ConvertOpenAIRequestToAntigravity("m", input, false); !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } +} diff --git a/internal/translator/antigravity/openai/chat-completions/init.go b/internal/translator/antigravity/openai/chat-completions/init.go index de2378033e5..2fb9fd0a04c 100644 --- a/internal/translator/antigravity/openai/chat-completions/init.go +++ b/internal/translator/antigravity/openai/chat-completions/init.go @@ -4,16 +4,18 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( OpenAI, Antigravity, - ConvertOpenAIRequestToAntigravity, + nil, interfaces.TranslateResponse{ Stream: ConvertAntigravityResponseToOpenAI, NonStream: ConvertAntigravityResponseToOpenAINonStream, }, ) + sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatOpenAI, sdktranslator.FormatAntigravity, convertOpenAIRequestToAntigravity) } diff --git a/internal/translator/antigravity/openai/responses/antigravity_openai-responses_request.go b/internal/translator/antigravity/openai/responses/antigravity_openai-responses_request.go index 895a921a927..9b955429553 100644 --- a/internal/translator/antigravity/openai/responses/antigravity_openai-responses_request.go +++ b/internal/translator/antigravity/openai/responses/antigravity_openai-responses_request.go @@ -51,15 +51,15 @@ func shouldBuildAntigravityResponsesWebSearchRequest(model string, payload []byt AllowsResponsesWebSearchToolChoice(root) } -func buildAntigravityResponsesWebSearchRequest(model string, payload []byte, stream bool) []byte { +func buildAntigravityResponsesWebSearchRequest(model string, payload []byte, stream bool) ([]byte, error) { includedDomains := ExtractResponsesWebSearchAllowedDomains(gjson.ParseBytes(payload)) - rawJSON := ConvertOpenAIResponsesRequestToGemini(model, payload, stream) + rawJSON, errConvert := ConvertOpenAIResponsesRequestToGeminiReturningError(model, payload, stream) rawJSON = rewriteOpenAIResponsesReasoningForAntigravityClaude(model, payload, rawJSON) out := ConvertGeminiRequestToAntigravity(model, rawJSON, stream) out, _ = sjson.SetBytes(out, "requestType", "web_search") out = ensureAntigravityResponsesWebSearchTool(out, includedDomains) out = ensureAntigravityResponsesWebSearchSystemInstruction(out) - return enableAntigravityResponsesThinkingSummary(payload, out) + return enableAntigravityResponsesThinkingSummary(payload, out), errConvert } func ensureAntigravityResponsesWebSearchTool(payload []byte, includedDomains []string) []byte { @@ -139,11 +139,11 @@ func ConvertOpenAIResponsesRequestToAntigravity(modelName string, inputRawJSON [ // request and consumes request-scoped model capabilities from the envelope. func ConvertOpenAIResponsesRequestEnvelopeToAntigravity(_ context.Context, req sdktranslator.RequestEnvelope) sdktranslator.RequestEnvelope { if shouldBuildAntigravityResponsesWebSearchRequest(req.Model, req.Body, req.ModelInfo) { - req.Body = buildAntigravityResponsesWebSearchRequest(req.Model, req.Body, req.Stream) + req.Body, req.Err = buildAntigravityResponsesWebSearchRequest(req.Model, req.Body, req.Stream) return req } inputRawJSON := req.Body - req.Body = ConvertOpenAIResponsesRequestToGemini(req.Model, req.Body, req.Stream) + req.Body, req.Err = ConvertOpenAIResponsesRequestToGeminiReturningError(req.Model, req.Body, req.Stream) req.Body = stripAntigravityResponsesGoogleSearch(req.Body) req.Body = rewriteOpenAIResponsesReasoningForAntigravityClaude(req.Model, inputRawJSON, req.Body) req.Body = ConvertGeminiRequestToAntigravity(req.Model, req.Body, req.Stream) diff --git a/internal/translator/antigravity/openai/responses/antigravity_openai-responses_user_turn_test.go b/internal/translator/antigravity/openai/responses/antigravity_openai-responses_user_turn_test.go new file mode 100644 index 00000000000..be1e99ca25e --- /dev/null +++ b/internal/translator/antigravity/openai/responses/antigravity_openai-responses_user_turn_test.go @@ -0,0 +1,110 @@ +package responses + +import ( + "context" + "errors" + "strings" + "testing" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +const ( + antigravityTurnHello = `{"type":"message","role":"user","content":[{"type":"input_text","text":"hello"}]}` + antigravityTurnAssistant = `{"type":"message","role":"assistant","content":[{"type":"output_text","text":"hi"}]}` + antigravityTurnNext = `{"type":"message","role":"user","content":[{"type":"input_text","text":"next"}]}` + antigravityTurnDeveloper = `{"type":"message","role":"developer","content":[{"type":"input_text","text":"dev"}]}` + antigravityTurnFileID = `{"type":"input_file","file_id":"file-1"}` + antigravityTurnFileData = `{"type":"input_file","filename":"a.pdf","file_data":"data:application/pdf;base64,JVBERi0xLjQK"}` + antigravityTurnText = `{"type":"input_text","text":"keep me"}` +) + +func antigravityUserTurn(parts ...string) string { + return `{"type":"message","role":"user","content":[` + strings.Join(parts, ",") + `]}` +} + +func antigravityTurnPayload(extra string, items ...string) []byte { + return []byte(`{"model":"gemini-3-flash",` + extra + `"input":[` + strings.Join(items, ",") + `]}`) +} + +func TestOpenAIResponsesToAntigravityRegistryCarriesTheRefusal(t *testing.T) { + cases := []struct { + name string + input []byte + info *registry.ModelInfo + }{ + { + name: "history then file id only", + input: antigravityTurnPayload("", antigravityTurnHello, antigravityTurnAssistant, antigravityUserTurn(antigravityTurnFileID)), + }, + { + name: "instructions and developer prompt do not hide the empty turn", + input: antigravityTurnPayload(`"instructions":"sys",`, antigravityTurnDeveloper, antigravityUserTurn(antigravityTurnFileID)), + }, + { + name: "emptied turn before a later text turn", + input: antigravityTurnPayload("", antigravityUserTurn(antigravityTurnFileID), antigravityTurnAssistant, antigravityTurnNext), + }, + { + name: "native web search request", + input: antigravityTurnPayload(`"tools":[{"type":"web_search"}],`, antigravityTurnHello, antigravityTurnAssistant, antigravityUserTurn(antigravityTurnFileID)), + info: func() *registry.ModelInfo { + enabled := true + return ®istry.ModelInfo{ID: "gemini-3-flash", NativeCapabilities: ®istry.NativeCapabilities{WebSearch: &enabled}} + }(), + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + envelope := sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatOpenAIResponse, sdktranslator.FormatAntigravity, + sdktranslator.RequestEnvelope{Format: sdktranslator.FormatOpenAIResponse, Model: "gemini-3-flash", Body: tc.input, ModelInfo: tc.info}) + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(envelope.Err, &unsupported) || unsupported.Type != "input_file" || unsupported.StatusCode() != 400 { + t.Fatalf("envelope.Err = %v, want unsupported content part: input_file; body = %s", envelope.Err, envelope.Body) + } + if !gjson.ValidBytes(envelope.Body) { + t.Fatalf("body is not JSON: %q", envelope.Body) + } + + direct := ConvertOpenAIResponsesRequestEnvelopeToAntigravity(context.Background(), + sdktranslator.RequestEnvelope{Model: "gemini-3-flash", Body: tc.input, ModelInfo: tc.info}) + if !errors.As(direct.Err, &unsupported) || unsupported.Type != "input_file" { + t.Fatalf("direct err = %v, want unsupported content part: input_file", direct.Err) + } + }) + } +} + +func TestOpenAIResponsesToAntigravityKeepsTurnWithTextBesideFileID(t *testing.T) { + input := antigravityTurnPayload("", antigravityTurnHello, antigravityTurnAssistant, antigravityUserTurn(antigravityTurnText, antigravityTurnFileID)) + envelope := sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatOpenAIResponse, sdktranslator.FormatAntigravity, + sdktranslator.RequestEnvelope{Format: sdktranslator.FormatOpenAIResponse, Model: "gemini-3-flash", Body: input}) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v", envelope.Err) + } + if got := gjson.GetBytes(envelope.Body, "request.contents.2.parts.0.text").String(); got != "keep me" { + t.Fatalf("text was lost: %s", envelope.Body) + } +} + +func TestOpenAIResponsesToAntigravityInlineFileStaysInlineData(t *testing.T) { + input := antigravityTurnPayload("", antigravityTurnHello, antigravityTurnAssistant, antigravityUserTurn(antigravityTurnFileData)) + envelope := sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatOpenAIResponse, sdktranslator.FormatAntigravity, + sdktranslator.RequestEnvelope{Format: sdktranslator.FormatOpenAIResponse, Model: "gemini-3-flash", Body: input}) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v", envelope.Err) + } + if got := gjson.GetBytes(envelope.Body, "request.contents.2.parts.0.inline_data.mime_type").String(); got != "application/pdf" { + t.Fatalf("inline file was not kept: %s", envelope.Body) + } +} + +func TestConvertOpenAIResponsesRequestToAntigravity_ExportedWrapperKeepsAJSONBody(t *testing.T) { + input := antigravityTurnPayload("", antigravityUserTurn(antigravityTurnFileID)) + if body := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", input, false); !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } +} diff --git a/internal/translator/antigravity/openai/responses/init.go b/internal/translator/antigravity/openai/responses/init.go index e4b3a555626..0faf8945ffa 100644 --- a/internal/translator/antigravity/openai/responses/init.go +++ b/internal/translator/antigravity/openai/responses/init.go @@ -11,7 +11,7 @@ func init() { translator.Register( OpenaiResponse, Antigravity, - ConvertOpenAIResponsesRequestToAntigravity, + nil, interfaces.TranslateResponse{ Stream: ConvertAntigravityResponseToOpenAIResponses, NonStream: ConvertAntigravityResponseToOpenAIResponsesNonStream, diff --git a/internal/translator/claude/gemini/claude_gemini_request.go b/internal/translator/claude/gemini/claude_gemini_request.go index 9c04b4dd7ed..2f18812839f 100644 --- a/internal/translator/claude/gemini/claude_gemini_request.go +++ b/internal/translator/claude/gemini/claude_gemini_request.go @@ -36,7 +36,15 @@ import ( // Returns: // - []byte: The transformed request data in Claude Code API format func ConvertGeminiRequestToClaude(modelName string, inputRawJSON []byte, stream bool) []byte { + body, _ := convertGeminiRequestToClaude(modelName, inputRawJSON, stream) + return body +} + +// convertGeminiRequestToClaude also reports a user turn that was left empty +// because its only attachment has no Claude equivalent. +func convertGeminiRequestToClaude(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { rawJSON := inputRawJSON + var drops translatorcommon.UserTurnDrops userID := translatorcommon.DeriveClaudeUserID(rawJSON) @@ -236,6 +244,8 @@ func ConvertGeminiRequestToClaude(modelName string, inputRawJSON []byte, stream } contentItems := make([][]byte, 0, 4) + // Counts what this turn sends; whitespace-only text is forwarded but never sendable. + sendable := 0 if parts := content.Get("parts"); parts.Exists() && parts.IsArray() { parts.ForEach(func(_, part gjson.Result) bool { if translatorcommon.IsGeminiThoughtPart(part) { @@ -247,6 +257,9 @@ func ConvertGeminiRequestToClaude(modelName string, inputRawJSON []byte, stream textContent := []byte(`{"type":"text","text":""}`) textContent, _ = sjson.SetBytes(textContent, "text", text.String()) contentItems = append(contentItems, textContent) + if strings.TrimSpace(text.String()) != "" { + sendable++ + } return true } @@ -270,6 +283,7 @@ func ConvertGeminiRequestToClaude(modelName string, inputRawJSON []byte, stream toolUse, _ = sjson.SetRawBytes(toolUse, "input", []byte(args.Raw)) } contentItems = append(contentItems, toolUse) + sendable++ return true } @@ -301,13 +315,19 @@ func ConvertGeminiRequestToClaude(modelName string, inputRawJSON []byte, stream toolResult, _ = sjson.SetBytes(toolResult, "content", response.Raw) } contentItems = append(contentItems, toolResult) + sendable++ return true } - // Inline data conversion to Claude Code content format + // Inline data conversion to Claude Code content format. Only model content + // keeps a placeholder for media Claude cannot read; a user attachment is + // never replaced by text, so it is recorded as dropped instead. if inlineData := geminiClaudeInlineData(part); inlineData.Exists() { - if contentPart, ok := claudeContentPartFromGeminiInlineData(inlineData); ok { + if contentPart, ok := claudeContentPartFromGeminiInlineData(inlineData, role == "assistant"); ok { contentItems = append(contentItems, contentPart) + sendable++ + } else if role != "assistant" { + drops.Drop("inlineData") } return true } @@ -316,6 +336,9 @@ func ConvertGeminiRequestToClaude(modelName string, inputRawJSON []byte, stream if fileData := geminiClaudeFileData(part); fileData.Exists() { if contentPart, ok := claudeContentPartFromGeminiFileData(fileData); ok { contentItems = append(contentItems, contentPart) + sendable++ + } else if role != "assistant" { + drops.Drop("fileData") } return true } @@ -323,6 +346,9 @@ func ConvertGeminiRequestToClaude(modelName string, inputRawJSON []byte, stream return true }) } + if role != "assistant" { + drops.EndTurn(sendable) + } // Only add message if it has content. if len(contentItems) > 0 { @@ -385,7 +411,7 @@ func ConvertGeminiRequestToClaude(modelName string, inputRawJSON []byte, stream // Stream setting configuration out, _ = sjson.SetBytes(out, "stream", stream) - return thinking.ApplyTranslatedSummaryToClaude(out, rawJSON, "gemini", modelName) + return thinking.ApplyTranslatedSummaryToClaude(out, rawJSON, "gemini", modelName), drops.Err() } func normalizeClaudeToolSchema(parameters gjson.Result) []byte { @@ -461,7 +487,10 @@ func geminiClaudeFileData(part gjson.Result) gjson.Result { return part.Get("file_data") } -func claudeContentPartFromGeminiInlineData(inlineData gjson.Result) ([]byte, bool) { +// claudeContentPartFromGeminiInlineData maps inline bytes onto a Claude block. +// Media that Claude cannot read becomes placeholder text only when +// keepPlaceholder is set; otherwise it reports false so the caller can refuse it. +func claudeContentPartFromGeminiInlineData(inlineData gjson.Result, keepPlaceholder bool) ([]byte, bool) { mimeType := inlineData.Get("mimeType").String() if mimeType == "" { mimeType = inlineData.Get("mime_type").String() @@ -483,6 +512,9 @@ func claudeContentPartFromGeminiInlineData(inlineData gjson.Result) ([]byte, boo documentContent, _ = sjson.SetBytes(documentContent, "source.data", data) return documentContent, true default: + if !keepPlaceholder { + return nil, false + } return claudeTextContentPart(fmt.Sprintf("Media content: inline data (Type: %s)", mimeType)), true } } diff --git a/internal/translator/claude/gemini/claude_gemini_request_test.go b/internal/translator/claude/gemini/claude_gemini_request_test.go index 191ded3ce6e..18030c60ada 100644 --- a/internal/translator/claude/gemini/claude_gemini_request_test.go +++ b/internal/translator/claude/gemini/claude_gemini_request_test.go @@ -2,6 +2,7 @@ package gemini import ( "fmt" + "strings" "testing" "github.com/tidwall/gjson" @@ -194,18 +195,19 @@ func TestConvertGeminiRequestToClaude_AcceptsCamelInlineData(t *testing.T) { func TestConvertGeminiRequestToClaude_SplitsNonImageInlineDataByMIME(t *testing.T) { out := ConvertGeminiRequestToClaude("claude-sonnet-4", []byte(`{"contents":[{"role":"user","parts":[{"inlineData":{"mimeType":"audio/wav","data":"UklGRg=="}},{"inlineData":{"mimeType":"video/mp4","data":"AAAAIGZ0eXA="}},{"inlineData":{"mimeType":"application/pdf","data":"JVBERi0="}}]}]}`), false) - if got := gjson.GetBytes(out, "messages.0.content.0.type").String(); got != "text" { - t.Fatalf("audio fallback type = %q, want text. Output: %s", got, string(out)) + // A user attachment Claude cannot read is dropped rather than replaced by placeholder text. + if got := gjson.GetBytes(out, "messages.0.content.#").Int(); got != 1 { + t.Fatalf("user content has %d blocks, want only the document. Output: %s", got, string(out)) } - if got := gjson.GetBytes(out, "messages.0.content.1.type").String(); got != "text" { - t.Fatalf("video fallback type = %q, want text. Output: %s", got, string(out)) - } - if got := gjson.GetBytes(out, "messages.0.content.2.type").String(); got != "document" { + if got := gjson.GetBytes(out, "messages.0.content.0.type").String(); got != "document" { t.Fatalf("document content type = %q, want document. Output: %s", got, string(out)) } if gjson.GetBytes(out, "messages.0.content.#(type==\"image\")").Exists() { t.Fatalf("non-image inlineData must not be converted to image. Output: %s", string(out)) } + if strings.Contains(string(out), "Media content") { + t.Fatalf("user attachment was replaced by placeholder text. Output: %s", string(out)) + } } func TestConvertGeminiRequestToClaude_DropsHiddenThoughtParts(t *testing.T) { diff --git a/internal/translator/claude/gemini/claude_gemini_user_turn_test.go b/internal/translator/claude/gemini/claude_gemini_user_turn_test.go new file mode 100644 index 00000000000..a1300b10547 --- /dev/null +++ b/internal/translator/claude/gemini/claude_gemini_user_turn_test.go @@ -0,0 +1,129 @@ +package gemini + +import ( + "context" + "errors" + "strings" + "testing" + + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +const ( + geminiAudioPart = `{"inlineData":{"mimeType":"audio/wav","data":"UklGRg=="}}` + geminiVideoPart = `{"inline_data":{"mime_type":"video/mp4","data":"AAAAIGZ0eXA="}}` +) + +// geminiTurnToClaude translates a user turn followed by a model turn and a final +// user turn holding the given parts. +func geminiTurnToClaude(finalParts string) sdktranslator.RequestEnvelope { + input := `{"contents":[{"role":"user","parts":[{"text":"a"}]},{"role":"model","parts":[{"text":"b"}]},{"role":"user","parts":[` + finalParts + `]}]}` + return sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatGemini, sdktranslator.FormatClaude, sdktranslator.RequestEnvelope{ + Format: sdktranslator.FormatGemini, + Model: "claude-sonnet-4", + Body: []byte(input), + }) +} + +func requireInlineDataRefusal(t *testing.T, envelope sdktranslator.RequestEnvelope) { + t.Helper() + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(envelope.Err, &unsupported) || unsupported.Type != "inlineData" || unsupported.StatusCode() != 400 { + t.Fatalf("envelope.Err = %v, want unsupported content part: inlineData; body = %s", envelope.Err, envelope.Body) + } + if got, want := envelope.Err.Error(), "unsupported content part: inlineData"; got != want { + t.Fatalf("error text = %q, want %q", got, want) + } + if !gjson.ValidBytes(envelope.Body) { + t.Fatalf("body is not JSON: %q", envelope.Body) + } +} + +func TestGeminiToClaudeAudioOnlyUserTurnIsRefusedInsteadOfBecomingPlaceholderText(t *testing.T) { + cases := map[string]string{ + "audio": geminiAudioPart, + "video": geminiVideoPart, + "audio and video": geminiAudioPart + `,` + geminiVideoPart, + "empty text beside audio": `{"text":""},` + geminiAudioPart, + "whitespace beside audio": `{"text":" \n"},` + geminiAudioPart, + "audio beside whitespace": geminiAudioPart + `,{"text":" "}`, + "inline data without a mime": `{"inlineData":{"data":"UklGRg=="}}`, + } + for name, parts := range cases { + t.Run(name, func(t *testing.T) { + envelope := geminiTurnToClaude(parts) + requireInlineDataRefusal(t, envelope) + if strings.Contains(string(envelope.Body), "Media content") { + t.Fatalf("placeholder text was synthesized: %s", envelope.Body) + } + }) + } +} + +func TestGeminiToClaudeRefusesAnEmptiedUserTurnBeforeALaterTextTurn(t *testing.T) { + input := `{"contents":[{"role":"user","parts":[` + geminiAudioPart + `]},{"role":"model","parts":[{"text":"ok"}]},{"role":"user","parts":[{"text":"next"}]}]}` + envelope := sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatGemini, sdktranslator.FormatClaude, sdktranslator.RequestEnvelope{ + Format: sdktranslator.FormatGemini, + Model: "claude-sonnet-4", + Body: []byte(input), + }) + requireInlineDataRefusal(t, envelope) +} + +func TestGeminiToClaudeRealTextBesideAudioIsSentWithoutAPlaceholder(t *testing.T) { + envelope := geminiTurnToClaude(`{"text":" "},{"text":"keep me"},` + geminiAudioPart) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + if strings.Contains(string(envelope.Body), "Media content") { + t.Fatalf("placeholder text was synthesized: %s", envelope.Body) + } + found := false + for _, block := range gjson.GetBytes(envelope.Body, "messages.2.content").Array() { + if block.Get("text").String() == "keep me" { + found = true + } + } + if !found { + t.Fatalf("text was lost: %s", envelope.Body) + } +} + +func TestGeminiToClaudeAudioBesideADocumentOrToolResultStillSucceeds(t *testing.T) { + cases := map[string]string{ + "document": geminiAudioPart + `,{"inlineData":{"mimeType":"application/pdf","data":"JVBERi0="}}`, + "tool result": geminiAudioPart + `,{"functionResponse":{"name":"f","response":{"result":"ok"}}}`, + } + for name, parts := range cases { + t.Run(name, func(t *testing.T) { + envelope := geminiTurnToClaude(parts) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + }) + } +} + +func TestGeminiToClaudeModelAudioKeepsItsPlaceholder(t *testing.T) { + input := `{"contents":[{"role":"user","parts":[{"text":"a"}]},{"role":"model","parts":[` + geminiAudioPart + `]},{"role":"user","parts":[{"text":"b"}]}]}` + envelope := sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatGemini, sdktranslator.FormatClaude, sdktranslator.RequestEnvelope{ + Format: sdktranslator.FormatGemini, + Model: "claude-sonnet-4", + Body: []byte(input), + }) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + if got := gjson.GetBytes(envelope.Body, "messages.1.content.0.text").String(); got != "Media content: inline data (Type: audio/wav)" { + t.Fatalf("assistant placeholder = %q, body = %s", got, envelope.Body) + } +} + +func TestGeminiToClaudeExportedWrapperKeepsAJSONBody(t *testing.T) { + input := []byte(`{"contents":[{"role":"user","parts":[` + geminiAudioPart + `]}]}`) + if body := ConvertGeminiRequestToClaude("claude-sonnet-4", input, false); !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } +} diff --git a/internal/translator/claude/gemini/init.go b/internal/translator/claude/gemini/init.go index fad5b0e28a2..cc95686364e 100644 --- a/internal/translator/claude/gemini/init.go +++ b/internal/translator/claude/gemini/init.go @@ -4,17 +4,19 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( Gemini, Claude, - ConvertGeminiRequestToClaude, + nil, interfaces.TranslateResponse{ Stream: ConvertClaudeResponseToGemini, NonStream: ConvertClaudeResponseToGeminiNonStream, TokenCount: GeminiTokenCount, }, ) + sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatGemini, sdktranslator.FormatClaude, convertGeminiRequestToClaude) } diff --git a/internal/translator/claude/interactions/init.go b/internal/translator/claude/interactions/init.go index bb5830cc9d4..e29c61b4c32 100644 --- a/internal/translator/claude/interactions/init.go +++ b/internal/translator/claude/interactions/init.go @@ -4,16 +4,18 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( Interactions, Claude, - ConvertInteractionsRequestToClaude, + nil, interfaces.TranslateResponse{ Stream: ConvertClaudeResponseToInteractions, NonStream: ConvertClaudeResponseToInteractionsNonStream, }, ) + sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatInteractions, sdktranslator.FormatClaude, convertInteractionsRequestToClaude) } diff --git a/internal/translator/claude/interactions/interactions_claude_instruction_test.go b/internal/translator/claude/interactions/interactions_claude_instruction_test.go new file mode 100644 index 00000000000..226a1c969b8 --- /dev/null +++ b/internal/translator/claude/interactions/interactions_claude_instruction_test.go @@ -0,0 +1,60 @@ +package interactions + +import ( + "strings" + "testing" +) + +// claudeInstructionSteps are developer and system steps in the shapes an +// Interactions client can send. Each one carries the text "note". +var claudeInstructionSteps = map[string]string{ + "developer user_input": `{"type":"user_input","role":"developer","content":[{"type":"text","text":"note"}]}`, + "system user_input": `{"type":"user_input","role":"system","content":[{"type":"text","text":"note"}]}`, + "developer string content": `{"type":"user_input","role":"developer","content":"note"}`, + "bare system object": `{"role":"system","content":"note"}`, + "bare system text": `{"type":"system","text":"note"}`, + "developer native parts": `{"role":"developer","parts":[{"text":"note"}]}`, + "developer wrapper": `{"role":"developer","steps":[{"type":"user_input","content":[{"type":"text","text":"note"}]}]}`, +} + +// claudeEmptiedStep is a user step whose only part Claude cannot carry. +const claudeEmptiedStep = `{"type":"user_input","content":[{"type":"video","mime_type":"video/mp4","uri":"https://example.test/a.mp4"}]}` + +func TestInteractionsToClaudeDeveloperOrSystemStepDoesNotHideAnEmptiedUserTurn(t *testing.T) { + for name, note := range claudeInstructionSteps { + t.Run("after "+name, func(t *testing.T) { + requireMediaRefusal(t, interactionsToClaudeEnvelope(`{"model":"m","input":[`+interactionsHistory+`,`+claudeEmptiedStep+`,`+note+`]}`), "video") + }) + t.Run("before "+name, func(t *testing.T) { + requireMediaRefusal(t, interactionsToClaudeEnvelope(`{"model":"m","input":[`+interactionsHistory+`,`+note+`,`+claudeEmptiedStep+`]}`), "video") + }) + } +} + +func TestInteractionsToClaudeDeveloperOrSystemStepStillSendsItsText(t *testing.T) { + for name, note := range claudeInstructionSteps { + t.Run(name, func(t *testing.T) { + envelope := interactionsToClaudeEnvelope(`{"model":"m","input":[` + interactionsHistory + `,{"type":"user_input","content":[{"type":"text","text":"keep me"}]},` + note + `]}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + if !strings.Contains(string(envelope.Body), "note") || !strings.Contains(string(envelope.Body), "keep me") { + t.Fatalf("text was lost: %s", envelope.Body) + } + }) + } +} + +func TestInteractionsToClaudeRealUserTextBesideAnUnrepresentableAttachmentSurvivesAnInstructionStep(t *testing.T) { + for name, note := range claudeInstructionSteps { + t.Run(name, func(t *testing.T) { + envelope := interactionsToClaudeEnvelope(`{"model":"m","input":[` + interactionsHistory + `,` + note + `,{"type":"user_input","content":[{"type":"text","text":"keep me"},` + videoByURI + `]}]}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + if !strings.Contains(string(envelope.Body), "keep me") { + t.Fatalf("text was lost: %s", envelope.Body) + } + }) + } +} diff --git a/internal/translator/claude/interactions/interactions_claude_request.go b/internal/translator/claude/interactions/interactions_claude_request.go index 5f815edfe29..a667f78d590 100644 --- a/internal/translator/claude/interactions/interactions_claude_request.go +++ b/internal/translator/claude/interactions/interactions_claude_request.go @@ -12,6 +12,14 @@ import ( ) func ConvertInteractionsRequestToClaude(modelName string, inputRawJSON []byte, stream bool) []byte { + out, _ := convertInteractionsRequestToClaude(modelName, inputRawJSON, stream) + return out +} + +// convertInteractionsRequestToClaude also reports a user turn that was left empty +// because its only media part has no Claude equivalent. +func convertInteractionsRequestToClaude(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { + var run interactionsClaudeUserRun root := gjson.ParseBytes(inputRawJSON) out := []byte(`{"model":"","max_tokens":32000,"messages":[]}`) out, _ = sjson.SetBytes(out, "model", modelName) @@ -21,10 +29,34 @@ func ConvertInteractionsRequestToClaude(modelName string, inputRawJSON []byte, s out = copyInteractionsSystemToClaude(out, root) out = copyInteractionsGenerationConfigToClaude(out, root) messageAccumulator := translatorcommon.NewClaudeMessageAccumulator(int(root.Get("input.#").Int())) - appendInteractionsInputToClaudeMessages(messageAccumulator, root.Get("input")) + appendInteractionsInputToClaudeMessages(messageAccumulator, root.Get("input"), &run) + run.end() out = translatorcommon.SetRawArrayItems(out, "messages", messageAccumulator.Messages()) out = copyInteractionsToolsToClaude(out, root) - return out + return out, run.drops.Err() +} + +// interactionsClaudeUserRun follows the consecutive user content that the message +// accumulator merges into one Claude user message. A media part Claude cannot +// carry is refused only when that whole turn is left with nothing to send, so +// text or a tool result in a neighbouring step still keeps the turn alive. +type interactionsClaudeUserRun struct { + drops translatorcommon.UserTurnDrops + sendable int +} + +func (r *interactionsClaudeUserRun) add() { + r.sendable++ +} + +func (r *interactionsClaudeUserRun) drop(partType string) { + r.drops.Drop(partType) +} + +// end closes the current user turn; call it when a non-user message starts or the input ends. +func (r *interactionsClaudeUserRun) end() { + r.drops.EndTurn(r.sendable) + r.sendable = 0 } func copyInteractionsSystemToClaude(out []byte, root gjson.Result) []byte { @@ -125,34 +157,35 @@ func setClaudeThinkingFromLevel(out []byte, level string) []byte { return out } -func appendInteractionsInputToClaudeMessages(accumulator *translatorcommon.ClaudeMessageAccumulator, input gjson.Result) { +func appendInteractionsInputToClaudeMessages(accumulator *translatorcommon.ClaudeMessageAccumulator, input gjson.Result, run *interactionsClaudeUserRun) { if !input.Exists() { return } if input.Type == gjson.String { step := []byte(`{"type":"user_input","content":[{"type":"text","text":""}]}`) step, _ = sjson.SetBytes(step, "content.0.text", input.String()) - appendInteractionsStepToClaude(accumulator, gjson.ParseBytes(step), "user") + appendInteractionsStepToClaude(accumulator, gjson.ParseBytes(step), "user", false, run) return } if input.IsObject() { - appendInteractionsInputItemToClaude(accumulator, input) + appendInteractionsInputItemToClaude(accumulator, input, run) return } input.ForEach(func(_, step gjson.Result) bool { - appendInteractionsInputItemToClaude(accumulator, step) + appendInteractionsInputItemToClaude(accumulator, step, run) return true }) } -func appendInteractionsInputItemToClaude(accumulator *translatorcommon.ClaudeMessageAccumulator, step gjson.Result) { +func appendInteractionsInputItemToClaude(accumulator *translatorcommon.ClaudeMessageAccumulator, step gjson.Result, run *interactionsClaudeUserRun) { if step.Get("steps").IsArray() { defaultRole := "user" if role := step.Get("role").String(); role == "model" || role == "assistant" { defaultRole = "assistant" } + instruction := translatorcommon.IsInteractionsInstructionStep(step, false) step.Get("steps").ForEach(func(_, nestedStep gjson.Result) bool { - appendInteractionsStepToClaude(accumulator, nestedStep, defaultRole) + appendInteractionsStepToClaude(accumulator, nestedStep, defaultRole, instruction, run) return true }) return @@ -163,48 +196,72 @@ func appendInteractionsInputItemToClaude(accumulator *translatorcommon.ClaudeMes wrapped, _ = sjson.SetBytes(wrapped, "type", "model_output") } wrapped, _ = sjson.SetRawBytes(wrapped, "content", []byte(step.Get("parts").Raw)) - appendInteractionsStepToClaude(accumulator, gjson.ParseBytes(wrapped), "user") + appendInteractionsStepToClaude(accumulator, gjson.ParseBytes(wrapped), "user", translatorcommon.IsInteractionsInstructionStep(step, false), run) return } stepType := step.Get("type").String() switch stepType { case "function_call": - appendInteractionsFunctionCallToClaude(accumulator, step) + appendInteractionsFunctionCallToClaude(accumulator, step, run) case "function_result": - appendInteractionsFunctionResultToClaude(accumulator, step) + appendInteractionsFunctionResultToClaude(accumulator, step, run) case "model_output", "thought": - appendInteractionsStepToClaude(accumulator, step, "assistant") + appendInteractionsStepToClaude(accumulator, step, "assistant", false, run) default: - appendInteractionsStepToClaude(accumulator, step, "user") + appendInteractionsStepToClaude(accumulator, step, "user", false, run) } } -func appendInteractionsStepToClaude(accumulator *translatorcommon.ClaudeMessageAccumulator, step gjson.Result, defaultRole string) { +// appendInteractionsStepToClaude adds one step. instruction says the step sits in +// a developer or system wrapper. Developer and system content is sent as user +// content, but it is not the user's own turn: it closes the open user turn and +// never counts toward keeping an emptied one alive. +func appendInteractionsStepToClaude(accumulator *translatorcommon.ClaudeMessageAccumulator, step gjson.Result, defaultRole string, instruction bool, run *interactionsClaudeUserRun) { role := defaultRole if stepRole := step.Get("role").String(); stepRole == "user" || stepRole == "assistant" { role = stepRole } + userContent := role == "user" && !translatorcommon.IsInteractionsInstructionStep(step, instruction) contentItems := make([][]byte, 0, 4) + appendPart := func(part gjson.Result) { + converted := interactionsContentToClaude(part, role) + if len(converted) == 0 { + if userContent { + if droppedType := interactionsClaudeDroppedPart(part); droppedType != "" { + run.drop(droppedType) + } + } + return + } + contentItems = append(contentItems, converted) + if userContent && interactionsClaudePartIsSendable(converted) { + run.add() + } + } stepContent := step.Get("content") if stepContent.Type == gjson.String { part := []byte(`{"type":"text","text":""}`) part, _ = sjson.SetBytes(part, "text", stepContent.String()) - contentItems = append(contentItems, part) + appendPart(gjson.ParseBytes(part)) } else if stepContent.IsArray() { stepContent.ForEach(func(_, part gjson.Result) bool { - if converted := interactionsContentToClaude(part, role); len(converted) > 0 { - contentItems = append(contentItems, converted) - } + appendPart(part) return true }) } else if text := step.Get("text"); text.Exists() { part := []byte(`{"type":"text","text":""}`) part, _ = sjson.SetBytes(part, "text", text.String()) - contentItems = append(contentItems, part) + appendPart(gjson.ParseBytes(part)) + } else if interactionsClaudeDroppedMedia(step) != "" { + // A bare media content object stands for a step of its own. + appendPart(step) } if len(contentItems) == 0 { return } + if !userContent { + run.end() + } msg := []byte(`{"role":"","content":[]}`) msg, _ = sjson.SetBytes(msg, "role", role) msg, _ = sjson.SetRawBytes(msg, "content", translatorcommon.JoinRawArray(contentItems)) @@ -240,7 +297,10 @@ func interactionsContentToClaude(part gjson.Result, role string) []byte { textPart, _ = sjson.SetBytes(textPart, "text", text) return textPart } - if part.Get("data").String() != "" || part.Get("file_data").String() != "" { + // A user attachment Claude cannot carry is never replaced by placeholder text; + // the caller records it as dropped. Assistant and tool result content only + // echoes earlier output, so it keeps the placeholder. + if role != "user" && (part.Get("data").String() != "" || part.Get("file_data").String() != "") { textPart := []byte(`{"type":"text","text":""}`) textPart, _ = sjson.SetBytes(textPart, "text", fmt.Sprintf("[%s content omitted]", partType)) return textPart @@ -249,7 +309,7 @@ func interactionsContentToClaude(part gjson.Result, role string) []byte { return nil } -func appendInteractionsFunctionCallToClaude(accumulator *translatorcommon.ClaudeMessageAccumulator, step gjson.Result) { +func appendInteractionsFunctionCallToClaude(accumulator *translatorcommon.ClaudeMessageAccumulator, step gjson.Result, run *interactionsClaudeUserRun) { toolUse := []byte(`{"type":"tool_use","id":"","name":"","input":{}}`) toolUse, _ = sjson.SetBytes(toolUse, "id", interactionsClaudeToolID(step)) toolUse, _ = sjson.SetBytes(toolUse, "name", util.SanitizeClaudeFunctionName(step.Get("name").String())) @@ -262,10 +322,11 @@ func appendInteractionsFunctionCallToClaude(accumulator *translatorcommon.Claude } msg := []byte(`{"role":"assistant","content":[]}`) msg, _ = sjson.SetRawBytes(msg, "content", translatorcommon.JoinRawArray([][]byte{toolUse})) + run.end() accumulator.Append(msg) } -func appendInteractionsFunctionResultToClaude(accumulator *translatorcommon.ClaudeMessageAccumulator, step gjson.Result) { +func appendInteractionsFunctionResultToClaude(accumulator *translatorcommon.ClaudeMessageAccumulator, step gjson.Result, run *interactionsClaudeUserRun) { toolResult := []byte(`{"type":"tool_result","tool_use_id":"","content":""}`) toolResult, _ = sjson.SetBytes(toolResult, "tool_use_id", interactionsClaudeToolID(step)) if isError := step.Get("is_error"); isError.Exists() && isError.Bool() { @@ -279,7 +340,7 @@ func appendInteractionsFunctionResultToClaude(accumulator *translatorcommon.Clau case result.IsArray(): contentItems := make([][]byte, 0, 4) result.ForEach(func(_, part gjson.Result) bool { - if converted := interactionsContentToClaude(part, "user"); len(converted) > 0 { + if converted := interactionsContentToClaude(part, "tool_result"); len(converted) > 0 { contentItems = append(contentItems, converted) } return true @@ -292,6 +353,8 @@ func appendInteractionsFunctionResultToClaude(accumulator *translatorcommon.Clau } msg := []byte(`{"role":"user","content":[]}`) msg, _ = sjson.SetRawBytes(msg, "content", translatorcommon.JoinRawArray([][]byte{toolResult})) + // A tool result is content the model reads, so it keeps the surrounding user turn. + run.add() accumulator.Append(msg) } @@ -433,6 +496,9 @@ func interactionsClaudeText(value gjson.Result) string { return "" } +// interactionsClaudeMediaPart maps an Interactions image or document onto a Claude +// block. Inline bytes become a base64 source and an http(s) uri becomes a url +// source. It reports false when the part carries neither. func interactionsClaudeMediaPart(part gjson.Result, claudeType string) ([]byte, bool) { mimeType := firstClaudeInteractionsExisting(part, "mime_type", "mimeType", "media_type", "mediaType").String() data := firstClaudeInteractionsExisting(part, "data", "file_data", "fileData").String() @@ -444,14 +510,54 @@ func interactionsClaudeMediaPart(part gjson.Result, claudeType string) ([]byte, data = source.Get("data").String() } } - if mimeType == "" || data == "" { - return nil, false + if mimeType != "" && data != "" { + out := []byte(`{"type":"","source":{"type":"base64","media_type":"","data":""}}`) + out, _ = sjson.SetBytes(out, "type", claudeType) + out, _ = sjson.SetBytes(out, "source.media_type", mimeType) + out, _ = sjson.SetBytes(out, "source.data", data) + return out, true + } + for _, path := range []string{"uri", "file_uri", "fileUri", "url"} { + if uri := strings.TrimSpace(part.Get(path).String()); translatorcommon.IsHTTPURL(uri) { + out := []byte(`{"type":"","source":{"type":"url","url":""}}`) + out, _ = sjson.SetBytes(out, "type", claudeType) + out, _ = sjson.SetBytes(out, "source.url", uri) + return out, true + } + } + return nil, false +} + +// interactionsClaudeDroppedMedia names the media type of a part that +// interactionsContentToClaude left out, or returns "" when the part is not media. +func interactionsClaudeDroppedMedia(part gjson.Result) string { + switch partType := part.Get("type").String(); partType { + case "image", "audio", "video", "document": + return partType + case "file": + return "document" + } + return "" +} + +// interactionsClaudeDroppedPart names the type of a user part that +// interactionsContentToClaude left out: media, or any other part that carries +// bytes. It returns "" when the part holds nothing to report. +func interactionsClaudeDroppedPart(part gjson.Result) string { + if mediaType := interactionsClaudeDroppedMedia(part); mediaType != "" { + return mediaType + } + if part.Get("data").String() != "" || part.Get("file_data").String() != "" { + return translatorcommon.InteractionsAttachmentType(part) } - out := []byte(`{"type":"","source":{"type":"base64","media_type":"","data":""}}`) - out, _ = sjson.SetBytes(out, "type", claudeType) - out, _ = sjson.SetBytes(out, "source.media_type", mimeType) - out, _ = sjson.SetBytes(out, "source.data", data) - return out, true + return "" +} + +// interactionsClaudePartIsSendable reports whether a converted Claude block gives +// the model something to read. Blank text does not. +func interactionsClaudePartIsSendable(converted []byte) bool { + block := gjson.ParseBytes(converted) + return block.Get("type").String() != "text" || strings.TrimSpace(block.Get("text").String()) != "" } func firstClaudeInteractionsExisting(root gjson.Result, paths ...string) gjson.Result { diff --git a/internal/translator/claude/interactions/interactions_claude_user_turn_test.go b/internal/translator/claude/interactions/interactions_claude_user_turn_test.go new file mode 100644 index 00000000000..9d810a55004 --- /dev/null +++ b/internal/translator/claude/interactions/interactions_claude_user_turn_test.go @@ -0,0 +1,249 @@ +package interactions + +import ( + "context" + "errors" + "strings" + "testing" + + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +const ( + interactionsHistory = `{"type":"user_input","content":[{"type":"text","text":"a"}]},{"type":"model_output","content":[{"type":"text","text":"b"}]}` + pdfByURI = `{"type":"document","mime_type":"application/pdf","uri":"https://example.test/a.pdf"}` + videoByURI = `{"type":"video","mime_type":"video/mp4","uri":"https://example.test/a.mp4"}` +) + +func interactionsToClaudeEnvelope(input string) sdktranslator.RequestEnvelope { + return sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatInteractions, sdktranslator.FormatClaude, sdktranslator.RequestEnvelope{ + Format: sdktranslator.FormatInteractions, + Model: "m", + Body: []byte(input), + }) +} + +// interactionsFinalTurnToClaude translates two history turns followed by a final +// user step holding the given content parts. +func interactionsFinalTurnToClaude(finalContent string) sdktranslator.RequestEnvelope { + return interactionsToClaudeEnvelope(`{"model":"m","input":[` + interactionsHistory + `,{"type":"user_input","content":[` + finalContent + `]}]}`) +} + +func requireMediaRefusal(t *testing.T, envelope sdktranslator.RequestEnvelope, wantType string) { + t.Helper() + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(envelope.Err, &unsupported) || unsupported.Type != wantType || unsupported.StatusCode() != 400 { + t.Fatalf("envelope.Err = %v, want unsupported content part: %s; body = %s", envelope.Err, wantType, envelope.Body) + } + if got, want := envelope.Err.Error(), "unsupported content part: "+wantType; got != want { + t.Fatalf("error text = %q, want %q", got, want) + } + if !gjson.ValidBytes(envelope.Body) { + t.Fatalf("body is not JSON: %q", envelope.Body) + } +} + +func TestInteractionsToClaudeURIOnlyDocumentBecomesAURLSource(t *testing.T) { + for _, field := range []string{"uri", "file_uri", "fileUri", "url"} { + t.Run(field, func(t *testing.T) { + envelope := interactionsFinalTurnToClaude(`{"type":"document","mime_type":"application/pdf","` + field + `":"https://example.test/a.pdf"}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + if got := gjson.GetBytes(envelope.Body, "messages.#").Int(); got != 3 { + t.Fatalf("messages = %d, want 3: %s", got, envelope.Body) + } + part := gjson.GetBytes(envelope.Body, "messages.2.content.0") + if part.Get("type").String() != "document" || part.Get("source.type").String() != "url" || part.Get("source.url").String() != "https://example.test/a.pdf" { + t.Fatalf("part = %s, body = %s", part.Raw, envelope.Body) + } + }) + } +} + +func TestInteractionsToClaudeURIOnlyImageBecomesAURLSource(t *testing.T) { + envelope := interactionsFinalTurnToClaude(`{"type":"image","mime_type":"image/png","uri":"https://example.test/a.png"}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + part := gjson.GetBytes(envelope.Body, "messages.2.content.0") + if part.Get("type").String() != "image" || part.Get("source.type").String() != "url" || part.Get("source.url").String() != "https://example.test/a.png" { + t.Fatalf("part = %s, body = %s", part.Raw, envelope.Body) + } +} + +func TestInteractionsToClaudeInlineDocumentStaysBase64(t *testing.T) { + envelope := interactionsFinalTurnToClaude(`{"type":"document","mime_type":"application/pdf","data":"JVBERi0xLjQK"}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + part := gjson.GetBytes(envelope.Body, "messages.2.content.0") + if part.Get("source.type").String() != "base64" || part.Get("source.media_type").String() != "application/pdf" || part.Get("source.data").String() != "JVBERi0xLjQK" { + t.Fatalf("part = %s, body = %s", part.Raw, envelope.Body) + } +} + +func TestInteractionsToClaudeUnrepresentableMediaOnlyTurnIsRefused(t *testing.T) { + cases := []struct { + name string + part string + wantType string + }{ + {name: "video by uri", part: videoByURI, wantType: "video"}, + {name: "audio by uri", part: `{"type":"audio","mime_type":"audio/wav","uri":"https://example.test/a.wav"}`, wantType: "audio"}, + {name: "document by gs uri", part: `{"type":"document","mime_type":"application/pdf","uri":"gs://bucket/a.pdf"}`, wantType: "document"}, + {name: "document by files api uri", part: `{"type":"document","mime_type":"application/pdf","uri":"files/abc123"}`, wantType: "document"}, + {name: "document with nothing", part: `{"type":"document","mime_type":"application/pdf"}`, wantType: "document"}, + {name: "file with nothing", part: `{"type":"file"}`, wantType: "document"}, + {name: "image by gs uri", part: `{"type":"image","mime_type":"image/png","uri":"gs://bucket/a.png"}`, wantType: "image"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + requireMediaRefusal(t, interactionsFinalTurnToClaude(tc.part), tc.wantType) + }) + } +} + +func TestInteractionsToClaudeRefusalIsNotHiddenBySystemInstructionOrHistory(t *testing.T) { + requireMediaRefusal(t, interactionsToClaudeEnvelope(`{"model":"m","system_instruction":"be brief","input":[`+interactionsHistory+`,{"type":"user_input","content":[`+videoByURI+`]}]}`), "video") +} + +func TestInteractionsToClaudeRefusesAnEmptiedTurnBeforeALaterTextTurn(t *testing.T) { + envelope := interactionsToClaudeEnvelope(`{"model":"m","input":[{"type":"user_input","content":[` + videoByURI + `]},{"type":"model_output","content":[{"type":"text","text":"ok"}]},{"type":"user_input","content":[{"type":"text","text":"next"}]}]}`) + requireMediaRefusal(t, envelope, "video") +} + +func TestInteractionsToClaudeEmptyTextDoesNotHideAnUnrepresentableMedia(t *testing.T) { + requireMediaRefusal(t, interactionsFinalTurnToClaude(`{"type":"text","text":""},`+videoByURI), "video") +} + +func TestInteractionsToClaudeUnrepresentableMediaBesideTextStillSucceeds(t *testing.T) { + envelope := interactionsFinalTurnToClaude(`{"type":"text","text":"keep me"},` + videoByURI) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + content := gjson.GetBytes(envelope.Body, "messages.2.content").Array() + if len(content) != 1 || content[0].Get("text").String() != "keep me" { + t.Fatalf("text was lost or media leaked: %s", envelope.Body) + } +} + +func TestInteractionsToClaudeFlatContentInputKeepsTextBesideMedia(t *testing.T) { + envelope := interactionsToClaudeEnvelope(`{"model":"m","input":[{"type":"text","text":"Describe this"},` + videoByURI + `]}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + if got := gjson.GetBytes(envelope.Body, "messages.0.content.0.text").String(); got != "Describe this" { + t.Fatalf("text was lost: %s", envelope.Body) + } +} + +func TestInteractionsToClaudeFlatContentInputConvertsAndRefusesBareMedia(t *testing.T) { + envelope := interactionsToClaudeEnvelope(`{"model":"m","input":[` + interactionsHistory + `,` + pdfByURI + `]}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + if got := gjson.GetBytes(envelope.Body, "messages.2.content.0.source.url").String(); got != "https://example.test/a.pdf" { + t.Fatalf("bare document was lost: %s", envelope.Body) + } + requireMediaRefusal(t, interactionsToClaudeEnvelope(`{"model":"m","input":[`+interactionsHistory+`,`+videoByURI+`]}`), "video") +} + +func TestInteractionsToClaudeNeighbouringUserStepsShareOneTurn(t *testing.T) { + cases := map[string]string{ + "text step after the media step": `{"model":"m","input":[` + interactionsHistory + `,{"type":"user_input","content":[` + videoByURI + `]},{"type":"user_input","content":[{"type":"text","text":"keep me"}]}]}`, + "text step before the media step": `{"model":"m","input":[` + interactionsHistory + `,{"type":"user_input","content":[{"type":"text","text":"keep me"}]},{"type":"user_input","content":[` + videoByURI + `]}]}`, + "tool result beside the media step": `{"model":"m","input":[{"type":"user_input","content":[{"type":"text","text":"a"}]},{"type":"function_call","name":"lookup","call_id":"toolu_1","arguments":{}},{"type":"function_result","name":"lookup","call_id":"toolu_1","result":{"ok":true}},{"type":"user_input","content":[` + videoByURI + `]}]}`, + } + for name, input := range cases { + t.Run(name, func(t *testing.T) { + envelope := interactionsToClaudeEnvelope(input) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + }) + } +} + +func TestInteractionsToClaudeAssistantStepEndsTheUserTurn(t *testing.T) { + envelope := interactionsToClaudeEnvelope(`{"model":"m","input":[{"type":"user_input","content":[{"type":"text","text":"a"}]},{"type":"user_input","content":[` + videoByURI + `]},{"type":"model_output","content":[{"type":"text","text":"b"}]},{"type":"user_input","content":[{"type":"text","text":"c"}]}]}`) + if envelope.Err != nil { + t.Fatalf("a text step in the same turn keeps it alive, envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + envelope = interactionsToClaudeEnvelope(`{"model":"m","input":[{"type":"user_input","content":[` + videoByURI + `]},{"type":"model_output","content":[{"type":"text","text":"b"}]},{"type":"user_input","content":[{"type":"text","text":"c"}]}]}`) + requireMediaRefusal(t, envelope, "video") +} + +func TestInteractionsToClaudeExportedWrapperKeepsAJSONBody(t *testing.T) { + input := []byte(`{"model":"m","input":[{"type":"user_input","content":[` + videoByURI + `]}]}`) + if body := ConvertInteractionsRequestToClaude("m", input, false); !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } +} + +const ( + inlineAudio = `{"type":"audio","mime_type":"audio/wav","data":"UklGRg=="}` + inlineVideo = `{"type":"video","mime_type":"video/mp4","data":"AAAAIGZ0eXA="}` +) + +func TestInteractionsToClaudeInlineAudioOrVideoOnlyUserTurnIsRefused(t *testing.T) { + cases := []struct { + name string + content string + wantType string + }{ + {name: "audio", content: inlineAudio, wantType: "audio"}, + {name: "video", content: inlineVideo, wantType: "video"}, + {name: "empty text does not hide audio", content: `{"type":"text","text":""},` + inlineAudio, wantType: "audio"}, + {name: "whitespace text does not hide video", content: `{"type":"text","text":" \n"},` + inlineVideo, wantType: "video"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + envelope := interactionsFinalTurnToClaude(tc.content) + requireMediaRefusal(t, envelope, tc.wantType) + if strings.Contains(string(envelope.Body), "omitted") { + t.Fatalf("a placeholder was synthesized for a user attachment: %s", envelope.Body) + } + }) + } +} + +func TestInteractionsToClaudeInlineAudioBesideTextSendsTheTextWithoutAPlaceholder(t *testing.T) { + envelope := interactionsFinalTurnToClaude(`{"type":"text","text":"keep me"},` + inlineAudio + `,` + inlineVideo) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + content := gjson.GetBytes(envelope.Body, "messages.2.content").Array() + if len(content) != 1 || content[0].Get("text").String() != "keep me" { + t.Fatalf("text was lost or a placeholder leaked: %s", envelope.Body) + } +} + +func TestInteractionsToClaudeAssistantMediaKeepsThePlaceholder(t *testing.T) { + envelope := interactionsToClaudeEnvelope(`{"model":"m","input":[{"type":"user_input","content":[{"type":"text","text":"a"}]},{"type":"model_output","content":[` + inlineAudio + `]},{"type":"user_input","content":[{"type":"text","text":"c"}]}]}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + if got := gjson.GetBytes(envelope.Body, "messages.1.content.0.text").String(); got != "[audio content omitted]" { + t.Fatalf("assistant placeholder = %q, body = %s", got, envelope.Body) + } +} + +func TestInteractionsToClaudeInlineAndURLDocumentsStillConvert(t *testing.T) { + inline := interactionsFinalTurnToClaude(`{"type":"document","mime_type":"application/pdf","data":"JVBERi0xLjQK"}`) + if inline.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", inline.Err, inline.Body) + } + if got := gjson.GetBytes(inline.Body, "messages.2.content.0.source.type").String(); got != "base64" { + t.Fatalf("inline document = %s", inline.Body) + } + byURL := interactionsFinalTurnToClaude(pdfByURI) + if byURL.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", byURL.Err, byURL.Body) + } + if got := gjson.GetBytes(byURL.Body, "messages.2.content.0.source.url").String(); got != "https://example.test/a.pdf" { + t.Fatalf("url document = %s", byURL.Body) + } +} diff --git a/internal/translator/claude/openai/chat-completions/claude_openai_request.go b/internal/translator/claude/openai/chat-completions/claude_openai_request.go index 3bac7b7359e..b473bdbcd59 100644 --- a/internal/translator/claude/openai/chat-completions/claude_openai_request.go +++ b/internal/translator/claude/openai/chat-completions/claude_openai_request.go @@ -53,7 +53,7 @@ func ConvertOpenAIRequestToClaudeWithCompatReturningError(modelName string, inpu func convertOpenAIRequestToClaude(modelName string, inputRawJSON []byte, stream, preserveEmptyThinkingBlocks bool) ([]byte, error) { rawJSON := inputRawJSON - var droppedAttachment string + var drops common.UserTurnDrops userID := common.DeriveClaudeUserID(rawJSON) @@ -219,13 +219,17 @@ func convertOpenAIRequestToClaude(modelName string, inputRawJSON []byte, stream, contentResult.ForEach(func(_, part gjson.Result) bool { if claudePart := convertOpenAIContentPartToClaudePart(part); claudePart != "" { contentBlocks = append(contentBlocks, []byte(claudePart)) - } else if partType := part.Get("type").String(); partType == "file" || partType == "input_audio" { - droppedAttachment = partType + } else if partType := part.Get("type").String(); role == "user" && (partType == "file" || partType == "input_audio") { + drops.Drop(partType) } return true }) } + if role == "user" { + drops.EndTurn(len(contentBlocks)) + } + // Handle tool calls (for assistant messages) if toolCalls := message.Get("tool_calls"); toolCalls.Exists() && toolCalls.IsArray() && role == "assistant" { toolCalls.ForEach(func(_, toolCall gjson.Result) bool { @@ -315,8 +319,8 @@ func convertOpenAIRequestToClaude(modelName string, inputRawJSON []byte, stream, systemBlocks = append(systemBlocks, systemBlock) } - // Decided before the blank turn below is added, or a system prompt would hide an empty request. - nothingLeftErr := common.ErrIfNothingLeft(droppedAttachment, len(messageBlocks)) + // Decided per user turn, so neither a system prompt nor the blank turn added below hides an emptied turn. + nothingLeftErr := drops.Err() // Preserve a minimal conversational turn for system-only inputs. // Claude payloads with top-level system instructions but no messages are risky for downstream validation. diff --git a/internal/translator/claude/openai/chat-completions/claude_openai_user_turn_test.go b/internal/translator/claude/openai/chat-completions/claude_openai_user_turn_test.go new file mode 100644 index 00000000000..99fa983297a --- /dev/null +++ b/internal/translator/claude/openai/chat-completions/claude_openai_user_turn_test.go @@ -0,0 +1,81 @@ +package chat_completions + +import ( + "errors" + "testing" + + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + "github.com/tidwall/gjson" +) + +const ( + userTurnFileID = `{"type":"file","file":{"file_id":"file-absent"}}` + userTurnText = `{"type":"text","text":"keep me"}` + userTurnInline = `{"type":"file","file":{"filename":"a.pdf","file_data":"data:application/pdf;base64,JVBERi0xLjQK"}}` +) + +func TestConvertOpenAIRequestToClaude_RefusesAnyEmptiedUserTurn(t *testing.T) { + cases := []struct { + name string + input string + wantType string + }{ + { + name: "history then file id only", + input: `{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[` + userTurnFileID + `]}]}`, + wantType: "file", + }, + { + name: "system and developer prompts do not hide the empty turn", + input: `{"model":"m","messages":[{"role":"system","content":"sys"},{"role":"developer","content":"dev"},{"role":"user","content":[` + userTurnFileID + `]}]}`, + wantType: "file", + }, + { + name: "emptied turn before a later text turn", + input: `{"model":"m","messages":[{"role":"user","content":[` + userTurnFileID + `]},{"role":"assistant","content":"ok"},{"role":"user","content":"next"}]}`, + wantType: "file", + }, + { + name: "audio only after history", + input: `{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"input_audio","input_audio":{"format":"wav","data":"UklGRg=="}}]}]}`, + wantType: "input_audio", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + body, err := ConvertOpenAIRequestToClaudeWithCompatReturningError("m", []byte(tc.input), false) + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(err, &unsupported) || unsupported.Type != tc.wantType || unsupported.StatusCode() != 400 { + t.Fatalf("err = %v, want unsupported content part: %s; body = %s", err, tc.wantType, body) + } + if got, want := err.Error(), "unsupported content part: "+tc.wantType; got != want { + t.Fatalf("error text = %q, want %q", got, want) + } + if !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } + }) + } +} + +func TestConvertOpenAIRequestToClaude_KeepsTurnWithTextBesideAttachment(t *testing.T) { + input := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[` + userTurnText + `,` + userTurnFileID + `]}]}`) + body, err := ConvertOpenAIRequestToClaudeWithCompatReturningError("m", input, false) + if err != nil { + t.Fatalf("err = %v", err) + } + if got := gjson.GetBytes(body, "messages.2.content.0.text").String(); got != "keep me" { + t.Fatalf("text was lost: %s", body) + } +} + +func TestConvertOpenAIRequestToClaude_InlineFileAfterHistoryStaysADocument(t *testing.T) { + input := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[` + userTurnInline + `]}]}`) + body, err := ConvertOpenAIRequestToClaudeWithCompatReturningError("m", input, false) + if err != nil { + t.Fatalf("err = %v", err) + } + if got := gjson.GetBytes(body, "messages.2.content.0.type").String(); got != "document" { + t.Fatalf("inline file was not kept: %s", body) + } +} diff --git a/internal/translator/claude/openai/responses/claude_openai-responses_request.go b/internal/translator/claude/openai/responses/claude_openai-responses_request.go index d4251a62726..c52ff89ec19 100644 --- a/internal/translator/claude/openai/responses/claude_openai-responses_request.go +++ b/internal/translator/claude/openai/responses/claude_openai-responses_request.go @@ -34,17 +34,26 @@ const ( // - max_output_tokens -> max_tokens // - stream passthrough via parameter func ConvertOpenAIResponsesRequestToClaude(modelName string, inputRawJSON []byte, stream bool) []byte { - return convertOpenAIResponsesRequestToClaude(modelName, inputRawJSON, stream, false) + body, _ := convertOpenAIResponsesRequestToClaude(modelName, inputRawJSON, stream, false) + return body } // ConvertOpenAIResponsesRequestToClaudeWithCompat preserves reasoning items // whose encrypted content is empty for configured compatibility endpoints. func ConvertOpenAIResponsesRequestToClaudeWithCompat(modelName string, inputRawJSON []byte, stream bool) []byte { + body, _ := convertOpenAIResponsesRequestToClaude(modelName, inputRawJSON, stream, true) + return body +} + +// ConvertOpenAIResponsesRequestToClaudeWithCompatReturningError also reports a +// file or audio part Claude cannot receive when it leaves a user turn empty. +func ConvertOpenAIResponsesRequestToClaudeWithCompatReturningError(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { return convertOpenAIResponsesRequestToClaude(modelName, inputRawJSON, stream, true) } -func convertOpenAIResponsesRequestToClaude(modelName string, inputRawJSON []byte, stream, preserveEmptyThinkingBlocks bool) []byte { +func convertOpenAIResponsesRequestToClaude(modelName string, inputRawJSON []byte, stream, preserveEmptyThinkingBlocks bool) ([]byte, error) { rawJSON := normalizeCodexAgentMessages(inputRawJSON) + var drops common.UserTurnDrops userID := common.DeriveClaudeUserID(rawJSON) @@ -321,6 +330,7 @@ func convertOpenAIResponsesRequestToClaude(modelName string, inputRawJSON []byte // Determine role and construct Claude-compatible content parts. var role string var partsJSON [][]byte + var droppedPartType string if parts := item.Get("content"); parts.Exists() && parts.IsArray() { parts.ForEach(func(_, part gjson.Result) bool { ptype := part.Get("type").String() @@ -406,6 +416,13 @@ func convertOpenAIResponsesRequestToClaude(modelName string, inputRawJSON []byte if role == "" { role = "user" } + } else if droppedPartType == "" { + droppedPartType = ptype + } + case "input_audio": + // Claude has no audio block, so the part cannot be sent. + if droppedPartType == "" { + droppedPartType = ptype } } return true @@ -427,6 +444,13 @@ func convertOpenAIResponsesRequestToClaude(modelName string, inputRawJSON []byte } } + if role == "user" { + if droppedPartType != "" { + drops.Drop(droppedPartType) + } + drops.EndTurn(len(partsJSON)) + } + if len(partsJSON) > 0 { lastIdx := len(partsJSON) - 1 if !gjson.GetBytes(partsJSON[lastIdx], "cache_control").Exists() { @@ -631,7 +655,7 @@ func convertOpenAIResponsesRequestToClaude(modelName string, inputRawJSON []byte } } - return thinking.ApplyTranslatedSummaryToClaude(out, rawJSON, "openai-response", modelName) + return thinking.ApplyTranslatedSummaryToClaude(out, rawJSON, "openai-response", modelName), drops.Err() } func defaultClaudeResponsesMaxTokensForModel(modelName string) int { diff --git a/internal/translator/claude/openai/responses/claude_openai-responses_user_turn_test.go b/internal/translator/claude/openai/responses/claude_openai-responses_user_turn_test.go new file mode 100644 index 00000000000..94782a7bda2 --- /dev/null +++ b/internal/translator/claude/openai/responses/claude_openai-responses_user_turn_test.go @@ -0,0 +1,142 @@ +package responses + +import ( + "context" + "errors" + "testing" + + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +const ( + responsesUserHello = `{"type":"message","role":"user","content":[{"type":"input_text","text":"hello"}]}` + responsesAssistantHi = `{"type":"message","role":"assistant","content":[{"type":"output_text","text":"hi"}]}` + responsesUserNext = `{"type":"message","role":"user","content":[{"type":"input_text","text":"next"}]}` + responsesFileIDPart = `{"type":"input_file","file_id":"file-1"}` + responsesAudioPart = `{"type":"input_audio","input_audio":{"data":"UklGRg==","format":"wav"}}` + responsesTextPart = `{"type":"input_text","text":"keep me"}` + responsesInlineFile = `{"type":"input_file","filename":"a.pdf","file_data":"data:application/pdf;base64,JVBERi0xLjQK"}` + responsesDeveloperMsg = `{"type":"message","role":"developer","content":[{"type":"input_text","text":"dev"}]}` +) + +func responsesUserTurn(parts ...string) string { + content := "" + for i, part := range parts { + if i > 0 { + content += "," + } + content += part + } + return `{"type":"message","role":"user","content":[` + content + `]}` +} + +func responsesPayload(instructions string, items ...string) []byte { + input := "" + for i, item := range items { + if i > 0 { + input += "," + } + input += item + } + prefix := `{"model":"claude-sonnet-4",` + if instructions != "" { + prefix += `"instructions":"` + instructions + `",` + } + return []byte(prefix + `"input":[` + input + `]}`) +} + +func TestConvertOpenAIResponsesRequestToClaude_RefusesAnyEmptiedUserTurn(t *testing.T) { + cases := []struct { + name string + input []byte + wantType string + }{ + { + name: "history then file id only", + input: responsesPayload("", responsesUserHello, responsesAssistantHi, responsesUserTurn(responsesFileIDPart)), + wantType: "input_file", + }, + { + name: "audio only after history", + input: responsesPayload("", responsesUserHello, responsesAssistantHi, responsesUserTurn(responsesAudioPart)), + wantType: "input_audio", + }, + { + name: "instructions and developer prompt do not hide the empty turn", + input: responsesPayload("sys", responsesDeveloperMsg, responsesUserTurn(responsesFileIDPart)), + wantType: "input_file", + }, + { + name: "emptied turn before a later text turn", + input: responsesPayload("", responsesUserTurn(responsesFileIDPart), responsesAssistantHi, responsesUserNext), + wantType: "input_file", + }, + { + name: "file url carries no bytes", + input: responsesPayload("", responsesUserTurn(`{"type":"input_file","file_url":"https://example.test/a.pdf"}`)), + wantType: "input_file", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + body, err := ConvertOpenAIResponsesRequestToClaudeWithCompatReturningError("claude-sonnet-4", tc.input, false) + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(err, &unsupported) || unsupported.Type != tc.wantType || unsupported.StatusCode() != 400 { + t.Fatalf("err = %v, want unsupported content part: %s; body = %s", err, tc.wantType, body) + } + if got, want := err.Error(), "unsupported content part: "+tc.wantType; got != want { + t.Fatalf("error text = %q, want %q", got, want) + } + if !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } + + envelope := sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatOpenAIResponse, sdktranslator.FormatClaude, + sdktranslator.RequestEnvelope{Format: sdktranslator.FormatOpenAIResponse, Model: "claude-sonnet-4", Body: tc.input}) + if !errors.As(envelope.Err, &unsupported) || unsupported.Type != tc.wantType { + t.Fatalf("registry err = %v, want unsupported content part: %s", envelope.Err, tc.wantType) + } + }) + } +} + +func TestConvertOpenAIResponsesRequestToClaude_KeepsTurnWithTextBesideAttachment(t *testing.T) { + for name, attachment := range map[string]string{"file id": responsesFileIDPart, "audio": responsesAudioPart} { + t.Run(name, func(t *testing.T) { + input := responsesPayload("", responsesUserHello, responsesAssistantHi, responsesUserTurn(responsesTextPart, attachment)) + body, err := ConvertOpenAIResponsesRequestToClaudeWithCompatReturningError("claude-sonnet-4", input, false) + if err != nil { + t.Fatalf("err = %v", err) + } + if got := gjson.GetBytes(body, "messages.2.content").String(); got != "keep me" { + t.Fatalf("text was lost: %s", body) + } + }) + } +} + +func TestConvertOpenAIResponsesRequestToClaude_InlineFileStaysADocument(t *testing.T) { + input := responsesPayload("", responsesUserHello, responsesAssistantHi, responsesUserTurn(responsesInlineFile)) + body, err := ConvertOpenAIResponsesRequestToClaudeWithCompatReturningError("claude-sonnet-4", input, false) + if err != nil { + t.Fatalf("err = %v", err) + } + part := gjson.GetBytes(body, "messages.2.content.0") + if part.Get("type").String() != "document" || part.Get("source.data").String() != "JVBERi0xLjQK" { + t.Fatalf("part = %s, body = %s", part.Raw, body) + } +} + +func TestConvertOpenAIResponsesRequestToClaude_ExportedWrappersKeepAJSONBody(t *testing.T) { + input := responsesPayload("", responsesUserTurn(responsesFileIDPart)) + for name, body := range map[string][]byte{ + "plain": ConvertOpenAIResponsesRequestToClaude("claude-sonnet-4", input, false), + "compat": ConvertOpenAIResponsesRequestToClaudeWithCompat("claude-sonnet-4", input, false), + } { + if !gjson.ValidBytes(body) { + t.Fatalf("%s: body is not JSON: %q", name, body) + } + } +} diff --git a/internal/translator/claude/openai/responses/init.go b/internal/translator/claude/openai/responses/init.go index 0ab246d41b4..c720803116a 100644 --- a/internal/translator/claude/openai/responses/init.go +++ b/internal/translator/claude/openai/responses/init.go @@ -4,16 +4,20 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( OpenaiResponse, Claude, - ConvertOpenAIResponsesRequestToClaude, + nil, interfaces.TranslateResponse{ Stream: ConvertClaudeResponseToOpenAIResponses, NonStream: ConvertClaudeResponseToOpenAIResponsesNonStream, }, ) + sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatOpenAIResponse, sdktranslator.FormatClaude, func(model string, body []byte, stream bool) ([]byte, error) { + return convertOpenAIResponsesRequestToClaude(model, body, stream, false) + }) } diff --git a/internal/translator/codex/claude/codex_claude_request.go b/internal/translator/codex/claude/codex_claude_request.go index ffc92c9a1c3..17b60ca656d 100644 --- a/internal/translator/codex/claude/codex_claude_request.go +++ b/internal/translator/codex/claude/codex_claude_request.go @@ -60,7 +60,7 @@ func ConvertClaudeRequestToCodexWithCompatReturningError(modelName string, input func convertClaudeRequestToCodex(modelName string, inputRawJSON []byte, _ bool, preserveEmptyThinkingBlocks bool) ([]byte, error) { rawJSON := inputRawJSON - var droppedAttachment string + var drops translatorcommon.UserTurnDrops template := []byte(`{"model":"","instructions":"","input":[]}`) @@ -132,9 +132,15 @@ func convertClaudeRequestToCodex(modelName string, inputRawJSON []byte, _ bool, } pendingToolUseIDs = nil contentItems := make([][]byte, 0, 4) + // Counts only what this turn itself sends, not system reminders flushed beside it. + // Empty text is forwarded but does not count: it can hide an emptied attachment. + turnSendable := 0 + bufferedSendable := 0 flushMessage := func() { if len(contentItems) > 0 { + turnSendable += bufferedSendable + bufferedSendable = 0 message := []byte(`{"type":"message","role":""}`) message, _ = sjson.SetBytes(message, "role", messageRole) message, _ = sjson.SetRawBytes(message, "content", translatorcommon.JoinRawArray(contentItems)) @@ -152,18 +158,21 @@ func convertClaudeRequestToCodex(modelName string, inputRawJSON []byte, _ bool, content, _ = sjson.SetBytes(content, "type", partType) content, _ = sjson.SetBytes(content, "text", text) contentItems = append(contentItems, content) + if text != "" { + bufferedSendable++ + } } - appendImageContent := func(dataURL string) { - content := []byte(`{"type":"input_image","image_url":""}`) - content, _ = sjson.SetBytes(content, "image_url", dataURL) + appendImageContent := func(content []byte) { contentItems = append(contentItems, content) + bufferedSendable++ } appendDocumentContent := func(dataURL string) { content := []byte(`{"type":"input_file","file_data":"","filename":"document.pdf"}`) content, _ = sjson.SetBytes(content, "file_data", dataURL) contentItems = append(contentItems, content) + bufferedSendable++ } appendReasoningContent := func(part gjson.Result) { @@ -218,23 +227,10 @@ func convertClaudeRequestToCodex(modelName string, inputRawJSON []byte, _ bool, inputItems = append(inputItems, pendingSystemReminders...) pendingSystemReminders = nil } - sourceResult := messageContentResult.Get("source") - if sourceResult.Exists() { - data := sourceResult.Get("data").String() - if data == "" { - data = sourceResult.Get("base64").String() - } - if data != "" { - mediaType := sourceResult.Get("media_type").String() - if mediaType == "" { - mediaType = sourceResult.Get("mime_type").String() - } - if mediaType == "" { - mediaType = "application/octet-stream" - } - dataURL := fmt.Sprintf("data:%s;base64,%s", mediaType, data) - appendImageContent(dataURL) - } + if imagePart, ok := claudeImageInputPart(messageContentResult.Get("source")); ok { + appendImageContent(imagePart) + } else if messageRole == "user" { + drops.Drop(contentType) } case "document", "container_upload": if len(pendingSystemReminders) > 0 { @@ -243,8 +239,8 @@ func convertClaudeRequestToCodex(modelName string, inputRawJSON []byte, _ bool, } if dataURL, ok := claudeDocumentDataURL(messageContentResult); ok { appendDocumentContent(dataURL) - } else { - droppedAttachment = messageContentResult.Get("type").String() + } else if messageRole == "user" { + drops.Drop(contentType) } case "tool_use": flushMessage() @@ -313,6 +309,7 @@ func convertClaudeRequestToCodex(modelName string, inputRawJSON []byte, _ bool, } inputItems = append(inputItems, functionCallOutputMessage) + turnSendable++ } } flushMessage() @@ -328,6 +325,9 @@ func convertClaudeRequestToCodex(modelName string, inputRawJSON []byte, _ bool, pendingSystemReminders = nil } } + if messageRole == "user" { + drops.EndTurn(turnSendable) + } } if len(pendingSystemReminders) > 0 { @@ -467,7 +467,7 @@ func convertClaudeRequestToCodex(modelName string, inputRawJSON []byte, _ bool, } template = translatorcommon.SetRawArrayItems(template, "input", inputItems) - return template, translatorcommon.ErrIfNothingLeft(droppedAttachment, len(inputItems)) + return template, drops.Err() } func codexClaudeTargetAcceptsGrokSignature(modelName string) bool { @@ -846,6 +846,38 @@ func codexSchemaMissesRequired(schema gjson.Result) bool { // claudeDocumentDataURL turns an inline PDF into a Codex input_file URL. Anything // else, a file id included, is not representable and is reported by the caller. +// claudeImageInputPart maps a Claude image source onto a Responses input_image +// part. Base64 bytes become a data URL, an http(s) url passes through and a file +// id is carried as file_id. It reports false for a source with none of them. +func claudeImageInputPart(source gjson.Result) ([]byte, bool) { + if !source.Exists() { + return nil, false + } + part := []byte(`{"type":"input_image"}`) + data := source.Get("data").String() + if data == "" { + data = source.Get("base64").String() + } + switch { + case data != "": + mediaType := source.Get("media_type").String() + if mediaType == "" { + mediaType = source.Get("mime_type").String() + } + if mediaType == "" { + mediaType = "application/octet-stream" + } + part, _ = sjson.SetBytes(part, "image_url", fmt.Sprintf("data:%s;base64,%s", mediaType, data)) + case source.Get("type").String() == "url" && translatorcommon.IsHTTPURL(source.Get("url").String()): + part, _ = sjson.SetBytes(part, "image_url", strings.TrimSpace(source.Get("url").String())) + case source.Get("type").String() == "file" && source.Get("file_id").String() != "": + part, _ = sjson.SetBytes(part, "file_id", source.Get("file_id").String()) + default: + return nil, false + } + return part, true +} + func claudeDocumentDataURL(part gjson.Result) (string, bool) { source := part.Get("source") if source.Get("type").String() == "base64" { diff --git a/internal/translator/codex/claude/codex_claude_user_turn_test.go b/internal/translator/codex/claude/codex_claude_user_turn_test.go new file mode 100644 index 00000000000..4b39328be33 --- /dev/null +++ b/internal/translator/codex/claude/codex_claude_user_turn_test.go @@ -0,0 +1,201 @@ +package claude + +import ( + "context" + "errors" + "testing" + + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +const userTurnUpload = `{"type":"container_upload","file_id":"file-1"}` + +func TestConvertClaudeRequestToCodex_RefusesAnyEmptiedUserTurn(t *testing.T) { + cases := []struct { + name string + input string + wantType string + }{ + { + name: "history then attachment only", + input: `{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":[{"type":"text","text":"hi"}]},{"role":"user","content":[` + userTurnUpload + `]}]}`, + wantType: "container_upload", + }, + { + name: "system prompt and system reminder", + input: `{"model":"m","system":"sys","messages":[{"role":"system","content":"reminder"},{"role":"user","content":[` + userTurnUpload + `]}]}`, + wantType: "container_upload", + }, + { + name: "emptied turn before a later text turn", + input: `{"model":"m","messages":[{"role":"user","content":[` + userTurnUpload + `]},{"role":"assistant","content":[{"type":"text","text":"ok"}]},{"role":"user","content":"next"}]}`, + wantType: "container_upload", + }, + { + name: "document without bytes", + input: `{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"document","source":{"type":"file","file_id":"file-1"}}]}]}`, + wantType: "document", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + body, err := ConvertClaudeRequestToCodexWithCompatReturningError("m", []byte(tc.input), false) + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(err, &unsupported) || unsupported.Type != tc.wantType || unsupported.StatusCode() != 400 { + t.Fatalf("err = %v, want unsupported content part: %s; body = %s", err, tc.wantType, body) + } + if got, want := err.Error(), "unsupported content part: "+tc.wantType; got != want { + t.Fatalf("error text = %q, want %q", got, want) + } + if !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } + }) + } +} + +func TestConvertClaudeRequestToCodex_KeepsTurnWithTextBesideAttachment(t *testing.T) { + input := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"text","text":"keep me"},` + userTurnUpload + `]}]}`) + body, err := ConvertClaudeRequestToCodexWithCompatReturningError("m", input, false) + if err != nil { + t.Fatalf("err = %v", err) + } + if got := gjson.GetBytes(body, "input.2.content.0.text").String(); got != "keep me" { + t.Fatalf("text was lost: %s", body) + } +} + +func TestConvertClaudeRequestToCodex_Base64DocumentAfterHistoryStaysAFile(t *testing.T) { + input := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"document","source":{"type":"base64","media_type":"application/pdf","data":"JVBERi0xLjQK"}}]}]}`) + body, err := ConvertClaudeRequestToCodexWithCompatReturningError("m", input, false) + if err != nil { + t.Fatalf("err = %v", err) + } + part := gjson.GetBytes(body, "input.2.content.0") + if part.Get("type").String() != "input_file" || part.Get("file_data").String() != "data:application/pdf;base64,JVBERi0xLjQK" { + t.Fatalf("part = %s, body = %s", part.Raw, body) + } +} + +func TestConvertClaudeRequestToCodex_EmptyTextDoesNotHideAnEmptiedUserTurn(t *testing.T) { + cases := map[string]string{ + "array content": `{"model":"m","messages":[{"role":"user","content":[{"type":"text","text":""},` + userTurnUpload + `]}]}`, + "after history": `{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[` + userTurnUpload + `,{"type":"text","text":""}]}]}`, + } + for name, input := range cases { + t.Run(name, func(t *testing.T) { + body, err := ConvertClaudeRequestToCodexWithCompatReturningError("m", []byte(input), false) + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(err, &unsupported) || unsupported.Type != "container_upload" || unsupported.StatusCode() != 400 { + t.Fatalf("err = %v, want unsupported content part: container_upload; body = %s", err, body) + } + if !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } + }) + } +} + +func TestConvertClaudeRequestToCodex_NonEmptyTextBesideAttachmentStillSucceeds(t *testing.T) { + input := []byte(`{"model":"m","messages":[{"role":"user","content":[{"type":"text","text":""},{"type":"text","text":"keep me"},` + userTurnUpload + `]}]}`) + body, err := ConvertClaudeRequestToCodexWithCompatReturningError("m", input, false) + if err != nil { + t.Fatalf("err = %v", err) + } + if got := gjson.GetBytes(body, "input.0.content.1.text").String(); got != "keep me" { + t.Fatalf("text was lost: %s", body) + } +} + +// claudeImageTurnToCodex translates a conversation of two history turns followed by +// a final user turn holding the given content parts. +func claudeImageTurnToCodex(finalContent string) sdktranslator.RequestEnvelope { + input := `{"model":"m","messages":[{"role":"user","content":"a"},{"role":"assistant","content":"b"},{"role":"user","content":[` + finalContent + `]}]}` + return sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatClaude, sdktranslator.FormatCodex, sdktranslator.RequestEnvelope{ + Format: sdktranslator.FormatClaude, + Model: "m", + Body: []byte(input), + }) +} + +func TestClaudeToCodexImageOnlyTurnKeepsTheImage(t *testing.T) { + cases := []struct { + name string + source string + field string + want string + }{ + { + name: "base64", + source: `{"type":"base64","media_type":"image/png","data":"aGVsbG8="}`, + field: "image_url", + want: "data:image/png;base64,aGVsbG8=", + }, + { + name: "http url", + source: `{"type":"url","url":"https://example.test/a.png"}`, + field: "image_url", + want: "https://example.test/a.png", + }, + { + name: "file id", + source: `{"type":"file","file_id":"file-1"}`, + field: "file_id", + want: "file-1", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + envelope := claudeImageTurnToCodex(`{"type":"image","source":` + tc.source + `}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + part := gjson.GetBytes(envelope.Body, "input.2.content.0") + if part.Get("type").String() != "input_image" || part.Get(tc.field).String() != tc.want { + t.Fatalf("part = %s, body = %s", part.Raw, envelope.Body) + } + }) + } +} + +func TestClaudeToCodexUnrepresentableImageOnlyTurnIsRefused(t *testing.T) { + cases := map[string]string{ + "non http url": `{"type":"url","url":"ftp://example.test/a.png"}`, + "empty url": `{"type":"url","url":""}`, + "file no id": `{"type":"file"}`, + "unknown kind": `{"type":"unknown"}`, + "base64 no data": `{"type":"base64","media_type":"image/png","data":""}`, + } + for name, source := range cases { + t.Run(name, func(t *testing.T) { + envelope := claudeImageTurnToCodex(`{"type":"image","source":` + source + `}`) + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(envelope.Err, &unsupported) || unsupported.Type != "image" || unsupported.StatusCode() != 400 { + t.Fatalf("envelope.Err = %v, want unsupported content part: image; body = %s", envelope.Err, envelope.Body) + } + if got, want := envelope.Err.Error(), "unsupported content part: image"; got != want { + t.Fatalf("error text = %q, want %q", got, want) + } + }) + } +} + +func TestClaudeToCodexUnrepresentableImageBesideTextStillSucceeds(t *testing.T) { + envelope := claudeImageTurnToCodex(`{"type":"text","text":"keep me"},{"type":"image","source":{"type":"file"}}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + if got := gjson.GetBytes(envelope.Body, "input.2.content.0.text").String(); got != "keep me" { + t.Fatalf("text was lost: %s", envelope.Body) + } +} + +func TestClaudeToCodexEmptyTextDoesNotHideAnUnrepresentableImage(t *testing.T) { + envelope := claudeImageTurnToCodex(`{"type":"text","text":""},{"type":"image","source":{"type":"file"}}`) + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(envelope.Err, &unsupported) || unsupported.Type != "image" { + t.Fatalf("envelope.Err = %v, want unsupported content part: image; body = %s", envelope.Err, envelope.Body) + } +} diff --git a/internal/translator/codex/interactions/init.go b/internal/translator/codex/interactions/init.go index c119cc14261..e248fb4c7dc 100644 --- a/internal/translator/codex/interactions/init.go +++ b/internal/translator/codex/interactions/init.go @@ -4,16 +4,18 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( Interactions, Codex, - ConvertInteractionsRequestToCodex, + nil, interfaces.TranslateResponse{ Stream: ConvertCodexResponseToInteractions, NonStream: ConvertCodexResponseToInteractionsNonStream, }, ) + sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatInteractions, sdktranslator.FormatCodex, convertInteractionsRequestToCodex) } diff --git a/internal/translator/codex/interactions/interactions_codex_request.go b/internal/translator/codex/interactions/interactions_codex_request.go index 70649af6842..018d769ba4b 100644 --- a/internal/translator/codex/interactions/interactions_codex_request.go +++ b/internal/translator/codex/interactions/interactions_codex_request.go @@ -12,6 +12,13 @@ import ( ) func ConvertInteractionsRequestToCodex(modelName string, inputRawJSON []byte, stream bool) []byte { + out, _ := convertInteractionsRequestToCodex(modelName, inputRawJSON, stream) + return out +} + +// convertInteractionsRequestToCodex also reports a user turn that was left empty +// because its only attachment has no Codex equivalent. +func convertInteractionsRequestToCodex(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { root := gjson.ParseBytes(inputRawJSON) out := []byte(`{"model":"","instructions":"","input":[]}`) out, _ = sjson.SetBytes(out, "model", modelName) @@ -21,11 +28,11 @@ func ConvertInteractionsRequestToCodex(modelName string, inputRawJSON []byte, st out = copyInteractionsSystemToCodex(out, root) out = copyInteractionsGenerationConfigToCodex(out, root) inputItems := translatorcommon.NewRawArrayItems(root.Get("input.#").Int()) - appendInteractionsInputToCodex(&inputItems, root.Get("input")) + errInput := appendInteractionsInputToCodex(&inputItems, root.Get("input")) out = translatorcommon.SetRawArrayItems(out, "input", inputItems) out = copyInteractionsToolsToCodex(out, root) out = copyInteractionsCodexTopLevel(out, root) - return out + return out, errInput } func copyInteractionsSystemToCodex(out []byte, root gjson.Result) []byte { @@ -181,41 +188,54 @@ func interactionsCodexReasoningSummary(cfg gjson.Result) string { return "" } -func appendInteractionsInputToCodex(items *[][]byte, input gjson.Result) { +// appendInteractionsInputToCodex adds the input steps and reports a user turn that +// was left with nothing to send because of an attachment Codex cannot carry. +func appendInteractionsInputToCodex(items *[][]byte, input gjson.Result) error { if !input.Exists() { - return + return nil } if input.Type == gjson.String { appendInteractionsTextToCodex(items, "user", input.String()) - return + return nil } + var run translatorcommon.UserRun if input.IsArray() { input.ForEach(func(_, step gjson.Result) bool { - appendInteractionsStepToCodex(items, step, "user") + appendInteractionsStepToCodex(items, step, "user", &run) return true }) - return - } - if steps := input.Get("steps"); steps.Exists() && steps.IsArray() { - defaultRole := interactionsCodexDefaultRole(input.Get("role").String(), "user") + } else if steps := input.Get("steps"); steps.Exists() && steps.IsArray() { + defaultRole := interactionsCodexStepRole(input, "user") steps.ForEach(func(_, step gjson.Result) bool { - appendInteractionsStepToCodex(items, step, defaultRole) + appendInteractionsStepToCodex(items, step, defaultRole, &run) return true }) - return + } else { + appendInteractionsStepToCodex(items, input, "user", &run) } - appendInteractionsStepToCodex(items, input, "user") + run.End() + return run.Err() +} + +// interactionsCodexUserRun returns run for user content. Content of any other +// role closes the open user turn and has no tracker. +func interactionsCodexUserRun(run *translatorcommon.UserRun, role string) *translatorcommon.UserRun { + if role == "user" { + return run + } + run.End() + return nil } -func appendInteractionsStepToCodex(items *[][]byte, step gjson.Result, defaultRole string) { +func appendInteractionsStepToCodex(items *[][]byte, step gjson.Result, defaultRole string, run *translatorcommon.UserRun) { if step.Type == gjson.String { - appendInteractionsTextToCodex(items, defaultRole, step.String()) + appendInteractionsRoleTextToCodex(items, defaultRole, step.String(), run) return } if steps := step.Get("steps"); steps.Exists() && steps.IsArray() { - role := interactionsCodexDefaultRole(step.Get("role").String(), defaultRole) + role := interactionsCodexStepRole(step, defaultRole) steps.ForEach(func(_, nested gjson.Result) bool { - appendInteractionsStepToCodex(items, nested, role) + appendInteractionsStepToCodex(items, nested, role, run) return true }) return @@ -223,52 +243,88 @@ func appendInteractionsStepToCodex(items *[][]byte, step gjson.Result, defaultRo stepType := strings.ToLower(strings.TrimSpace(step.Get("type").String())) switch stepType { case "function_call": + run.End() appendInteractionsFunctionCallToCodex(items, step) case "function_result", "function_call_output": + // A tool result is content the model reads, so it keeps the surrounding user turn. + run.Add() appendInteractionsFunctionResultToCodex(items, step) case "model_output", "assistant": - appendInteractionsContentToCodexItem(items, step.Get("content"), "assistant") + run.End() + appendInteractionsContentToCodexItem(items, step.Get("content"), "assistant", run) case "thought", "reasoning": + run.End() appendInteractionsThoughtToCodex(items, step) case "user_input", "message", "": - role := interactionsCodexDefaultRole(step.Get("role").String(), defaultRole) + role := interactionsCodexStepRole(step, defaultRole) if content := step.Get("content"); content.Exists() { - appendInteractionsContentToCodexItem(items, content, role) + appendInteractionsContentToCodexItem(items, content, role, run) } else if text := step.Get("text"); text.Exists() { - appendInteractionsTextToCodex(items, role, text.String()) + appendInteractionsRoleTextToCodex(items, role, text.String(), run) } default: - role := interactionsCodexDefaultRole(step.Get("role").String(), defaultRole) + role := interactionsCodexStepRole(step, defaultRole) if content := step.Get("content"); content.Exists() { - appendInteractionsContentToCodexItem(items, content, role) + appendInteractionsContentToCodexItem(items, content, role, run) } else if text := step.Get("text"); text.Exists() { - appendInteractionsTextToCodex(items, role, text.String()) + appendInteractionsRoleTextToCodex(items, role, text.String(), run) } } } -func appendInteractionsContentToCodexItem(items *[][]byte, content gjson.Result, role string) { +// appendInteractionsRoleTextToCodex adds a text message; blank text does not keep a user turn alive. +func appendInteractionsRoleTextToCodex(items *[][]byte, role, text string, run *translatorcommon.UserRun) { + appendInteractionsTextToCodex(items, role, text) + userRun := interactionsCodexUserRun(run, role) + if strings.TrimSpace(text) != "" { + userRun.Add() + } +} + +func appendInteractionsContentToCodexItem(items *[][]byte, content gjson.Result, role string, run *translatorcommon.UserRun) { if !content.Exists() { return } if content.Type == gjson.String { - appendInteractionsTextToCodex(items, role, content.String()) + appendInteractionsRoleTextToCodex(items, role, content.String(), run) return } + userRun := interactionsCodexUserRun(run, role) if content.IsArray() { content.ForEach(func(_, part gjson.Result) bool { - if item := interactionsCodexMessagePart(part, role); len(item) > 0 { - appendInteractionsMessagePartToCodex(items, role, item) - } + appendInteractionsContentPartToCodex(items, part, role, userRun) return true }) return } if content.IsObject() { - if item := interactionsCodexMessagePart(content, role); len(item) > 0 { - appendInteractionsMessagePartToCodex(items, role, item) + appendInteractionsContentPartToCodex(items, content, role, userRun) + } +} + +// appendInteractionsContentPartToCodex adds one content part. run is nil for +// content that is not user content; for user content it records what is sent and +// what cannot be. +func appendInteractionsContentPartToCodex(items *[][]byte, part gjson.Result, role string, run *translatorcommon.UserRun) { + item := interactionsCodexMessagePart(part, role) + if len(item) == 0 { + if droppedType := translatorcommon.InteractionsAttachmentType(part); droppedType != "" { + run.Drop(droppedType) } + return } + appendInteractionsMessagePartToCodex(items, role, item) + if !interactionsCodexIsBlankText(item) { + run.Add() + } +} + +// interactionsCodexIsBlankText reports whether a Codex message part is a text part +// holding only whitespace. +func interactionsCodexIsBlankText(item []byte) bool { + parsed := gjson.ParseBytes(item) + partType := parsed.Get("type").String() + return (partType == "input_text" || partType == "output_text") && strings.TrimSpace(parsed.Get("text").String()) == "" } func appendInteractionsFunctionCallToCodex(items *[][]byte, step gjson.Result) { @@ -452,14 +508,10 @@ func interactionsCodexMessagePart(part gjson.Result, role string) []byte { } func interactionsCodexImagePart(part gjson.Result) []byte { - if url := part.Get("url"); url.Exists() { + // uri is the Interactions spelling of file_uri. + if imageURL := firstNonBlankString(part, "url", "file_uri", "fileUri", "uri"); imageURL != "" { item := []byte(`{"type":"input_image","image_url":""}`) - item, _ = sjson.SetBytes(item, "image_url", url.String()) - return item - } - if fileURI := firstString(part, "file_uri", "fileUri"); fileURI != "" { - item := []byte(`{"type":"input_image","image_url":""}`) - item, _ = sjson.SetBytes(item, "image_url", fileURI) + item, _ = sjson.SetBytes(item, "image_url", imageURL) return item } mimeType := firstString(part, "mime_type", "mimeType") @@ -492,7 +544,8 @@ func interactionsCodexFilePart(part gjson.Result) []byte { return item } mimeType := firstString(part, "mime_type", "mimeType") - if fileURI := firstString(part, "file_uri", "fileUri", "url"); fileURI != "" { + // uri is the Interactions spelling of file_uri. + if fileURI := firstNonBlankString(part, "file_uri", "fileUri", "uri", "url"); fileURI != "" { item := []byte(`{"type":"input_file","file_url":"","filename":""}`) item, _ = sjson.SetBytes(item, "file_url", fileURI) item, _ = sjson.SetBytes(item, "filename", codexFileNameFromMIME(mimeType)) @@ -638,6 +691,17 @@ func interactionsCodexOutputString(value gjson.Result) string { return "" } +// interactionsCodexStepRole resolves the Codex role of a step. A step that +// carries system or developer content, named by its role or by its type, is +// developer content: it closes the open user turn and never keeps an emptied one +// alive. Any other step uses its own role, then the role it inherits. +func interactionsCodexStepRole(step gjson.Result, inherited string) string { + if translatorcommon.IsInteractionsInstructionStep(step, inherited == "developer") { + return "developer" + } + return interactionsCodexDefaultRole(step.Get("role").String(), inherited) +} + func interactionsCodexDefaultRole(role, fallback string) string { switch strings.ToLower(strings.TrimSpace(role)) { case "model", "assistant": @@ -717,6 +781,16 @@ func shortenCodexToolNameIfNeeded(name string) string { return name[:limit] } +// firstNonBlankString returns the first non-blank string found at paths. +func firstNonBlankString(root gjson.Result, paths ...string) string { + for _, path := range paths { + if value := strings.TrimSpace(root.Get(path).String()); value != "" { + return value + } + } + return "" +} + func firstString(root gjson.Result, paths ...string) string { for _, path := range paths { if value := root.Get(path); value.Exists() { diff --git a/internal/translator/codex/interactions/interactions_codex_uri_test.go b/internal/translator/codex/interactions/interactions_codex_uri_test.go new file mode 100644 index 00000000000..8dd35d79d96 --- /dev/null +++ b/internal/translator/codex/interactions/interactions_codex_uri_test.go @@ -0,0 +1,202 @@ +package interactions + +import ( + "context" + "errors" + "testing" + + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +const interactionsCodexHistory = `{"type":"user_input","content":[{"type":"text","text":"a"}]},{"type":"model_output","content":[{"type":"text","text":"b"}]}` + +func interactionsToCodexEnvelope(input string) sdktranslator.RequestEnvelope { + return sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatInteractions, sdktranslator.FormatCodex, sdktranslator.RequestEnvelope{ + Format: sdktranslator.FormatInteractions, + Model: "m", + Body: []byte(input), + }) +} + +// interactionsFinalTurnToCodex translates two history turns followed by a final +// user step holding the given content parts. +func interactionsFinalTurnToCodex(finalContent string) sdktranslator.RequestEnvelope { + return interactionsToCodexEnvelope(`{"model":"m","input":[` + interactionsCodexHistory + `,{"type":"user_input","content":[` + finalContent + `]}]}`) +} + +func requireInteractionsToCodexRefusal(t *testing.T, envelope sdktranslator.RequestEnvelope, wantType string) { + t.Helper() + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(envelope.Err, &unsupported) || unsupported.Type != wantType || unsupported.StatusCode() != 400 { + t.Fatalf("envelope.Err = %v, want unsupported content part: %s; body = %s", envelope.Err, wantType, envelope.Body) + } + if got, want := envelope.Err.Error(), "unsupported content part: "+wantType; got != want { + t.Fatalf("error text = %q, want %q", got, want) + } + if !gjson.ValidBytes(envelope.Body) { + t.Fatalf("body is not JSON: %q", envelope.Body) + } +} + +// TestInteractionsToCodexKeepsTheMediaGeminiToInteractionsWrites feeds the part +// shape that the Gemini to Interactions translation emits for a fileData part. +func TestInteractionsToCodexKeepsTheMediaGeminiToInteractionsWrites(t *testing.T) { + envelope := interactionsFinalTurnToCodex(`{"type":"image","uri":"gs://b/a.png","mime_type":"image/png"}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + if got := gjson.GetBytes(envelope.Body, "input.#").Int(); got != 3 { + t.Fatalf("input has %d items, want 3: %s", got, envelope.Body) + } + part := gjson.GetBytes(envelope.Body, "input.2.content.0") + if part.Get("type").String() != "input_image" || part.Get("image_url").String() != "gs://b/a.png" { + t.Fatalf("last turn lost the file: %s", envelope.Body) + } +} + +func TestInteractionsToCodexReadsURIAsAFileReference(t *testing.T) { + for _, field := range []string{"uri", "file_uri", "fileUri", "url"} { + t.Run("image "+field, func(t *testing.T) { + envelope := interactionsFinalTurnToCodex(`{"type":"image","mime_type":"image/png","` + field + `":"https://example.test/a.png"}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + part := gjson.GetBytes(envelope.Body, "input.2.content.0") + if part.Get("type").String() != "input_image" || part.Get("image_url").String() != "https://example.test/a.png" { + t.Fatalf("part = %s, body = %s", part.Raw, envelope.Body) + } + }) + t.Run("document "+field, func(t *testing.T) { + envelope := interactionsFinalTurnToCodex(`{"type":"document","mime_type":"application/pdf","` + field + `":"https://example.test/a.pdf"}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + part := gjson.GetBytes(envelope.Body, "input.2.content.0") + if part.Get("type").String() != "input_file" || part.Get("file_url").String() != "https://example.test/a.pdf" { + t.Fatalf("part = %s, body = %s", part.Raw, envelope.Body) + } + }) + } +} + +func TestInteractionsToCodexInlineDataStillConverts(t *testing.T) { + image := interactionsFinalTurnToCodex(`{"type":"image","mime_type":"image/png","data":"aGVsbG8="}`) + if image.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", image.Err, image.Body) + } + if got := gjson.GetBytes(image.Body, "input.2.content.0.image_url").String(); got != "data:image/png;base64,aGVsbG8=" { + t.Fatalf("image_url = %q, body = %s", got, image.Body) + } + audio := interactionsFinalTurnToCodex(`{"type":"audio","mime_type":"audio/wav","data":"UklGRg=="}`) + if audio.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", audio.Err, audio.Body) + } + if got := gjson.GetBytes(audio.Body, "input.2.content.0.input_audio.data").String(); got != "UklGRg==" { + t.Fatalf("input_audio = %s, body = %s", gjson.GetBytes(audio.Body, "input.2.content.0").Raw, audio.Body) + } +} + +func TestInteractionsToCodexUnrepresentableAttachmentOnlyTurnIsRefused(t *testing.T) { + cases := []struct { + name string + content string + wantType string + }{ + {name: "audio by uri", content: `{"type":"audio","mime_type":"audio/wav","uri":"gs://b/a.wav"}`, wantType: "audio"}, + {name: "image without anything", content: `{"type":"image"}`, wantType: "image"}, + {name: "document without anything", content: `{"type":"document","mime_type":"application/pdf"}`, wantType: "document"}, + {name: "empty text does not hide it", content: `{"type":"text","text":""},{"type":"audio","mime_type":"audio/wav"}`, wantType: "audio"}, + {name: "whitespace text does not hide it", content: `{"type":"text","text":" \n"},{"type":"audio","mime_type":"audio/wav"}`, wantType: "audio"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + requireInteractionsToCodexRefusal(t, interactionsFinalTurnToCodex(tc.content), tc.wantType) + }) + } +} + +func TestInteractionsToCodexRefusesAnEmptiedTurnBeforeALaterTextTurn(t *testing.T) { + envelope := interactionsToCodexEnvelope(`{"model":"m","input":[{"type":"user_input","content":[{"type":"audio","mime_type":"audio/wav"}]},{"type":"model_output","content":[{"type":"text","text":"ok"}]},{"type":"user_input","content":[{"type":"text","text":"next"}]}]}`) + requireInteractionsToCodexRefusal(t, envelope, "audio") +} + +// An instruction step names itself by role or by type alone. It closes the +// emptied user turn and must not stand in for the content that turn lost. +func TestInteractionsToCodexInstructionStepDoesNotHideAnEmptiedTurn(t *testing.T) { + const emptied = `{"type":"user_input","content":[{"type":"audio","mime_type":"audio/wav","uri":"gs://b/a.wav"}]}` + cases := map[string]string{ + "role developer": `{"type":"user_input","role":"developer","content":[{"type":"text","text":"note"}]}`, + "role system": `{"type":"user_input","role":"system","content":[{"type":"text","text":"note"}]}`, + "type developer": `{"type":"developer","content":[{"type":"text","text":"note"}]}`, + "type system": `{"type":"system","content":[{"type":"text","text":"note"}]}`, + "type system wrapper": `{"type":"system","steps":[{"type":"user_input","content":[{"type":"text","text":"note"}]}]}`, + } + for name, instruction := range cases { + t.Run(name, func(t *testing.T) { + envelope := interactionsToCodexEnvelope(`{"model":"m","input":[` + interactionsCodexHistory + `,` + emptied + `,` + instruction + `]}`) + requireInteractionsToCodexRefusal(t, envelope, "audio") + }) + } +} + +// An instruction step is still sent, as a developer message, when nothing was lost. +func TestInteractionsToCodexTypeOnlyInstructionStepIsSentAsDeveloper(t *testing.T) { + for _, stepType := range []string{"system", "developer"} { + t.Run(stepType, func(t *testing.T) { + envelope := interactionsToCodexEnvelope(`{"model":"m","input":[` + interactionsCodexHistory + `,{"type":"` + stepType + `","content":[{"type":"text","text":"note"}]}]}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + last := gjson.GetBytes(envelope.Body, "input.2") + if last.Get("role").String() != "developer" || last.Get("content.0.text").String() != "note" { + t.Fatalf("last item = %s, body = %s", last.Raw, envelope.Body) + } + }) + } +} + +func TestInteractionsToCodexUnrepresentableAttachmentBesideTextStillSucceeds(t *testing.T) { + envelope := interactionsFinalTurnToCodex(`{"type":"text","text":"keep me"},{"type":"audio","mime_type":"audio/wav"}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + if got := gjson.GetBytes(envelope.Body, "input.2.content.0.text").String(); got != "keep me" { + t.Fatalf("text was lost: %s", envelope.Body) + } + if got := gjson.GetBytes(envelope.Body, "input.#").Int(); got != 3 { + t.Fatalf("input has %d items, want 3: %s", got, envelope.Body) + } +} + +func TestInteractionsToCodexNeighbouringStepKeepsTheTurnAlive(t *testing.T) { + cases := map[string]string{ + "text step": `{"type":"user_input","content":[{"type":"text","text":"keep me"}]},{"type":"user_input","content":[{"type":"audio","mime_type":"audio/wav"}]}`, + "tool result": `{"type":"function_call","name":"f","call_id":"c1","arguments":{}},{"type":"function_result","name":"f","call_id":"c1","result":{"ok":true}},{"type":"user_input","content":[{"type":"audio","mime_type":"audio/wav"}]}`, + "string step": `"keep me",{"type":"user_input","content":[{"type":"audio","mime_type":"audio/wav"}]}`, + "turn of steps": `{"role":"user","steps":[{"type":"user_input","content":[{"type":"text","text":"keep me"}]},{"type":"user_input","content":[{"type":"audio","mime_type":"audio/wav"}]}]}`, + } + for name, steps := range cases { + t.Run(name, func(t *testing.T) { + envelope := interactionsToCodexEnvelope(`{"model":"m","input":[` + interactionsCodexHistory + `,` + steps + `]}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + }) + } +} + +func TestInteractionsToCodexAssistantMediaIsNotAUserTurn(t *testing.T) { + envelope := interactionsToCodexEnvelope(`{"model":"m","input":[{"type":"user_input","content":[{"type":"text","text":"a"}]},{"type":"model_output","content":[{"type":"audio","mime_type":"audio/wav"}]},{"type":"user_input","content":[{"type":"text","text":"c"}]}]}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } +} + +func TestInteractionsToCodexExportedWrapperKeepsAJSONBody(t *testing.T) { + input := []byte(`{"model":"m","input":[` + interactionsCodexHistory + `,{"type":"user_input","content":[{"type":"audio","mime_type":"audio/wav"}]}]}`) + if body := ConvertInteractionsRequestToCodex("m", input, false); !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } +} diff --git a/internal/translator/codex/openai/chat-completions/codex_openai_request.go b/internal/translator/codex/openai/chat-completions/codex_openai_request.go index 3f855f994bc..66b68a87f0c 100644 --- a/internal/translator/codex/openai/chat-completions/codex_openai_request.go +++ b/internal/translator/codex/openai/chat-completions/codex_openai_request.go @@ -29,7 +29,15 @@ import ( // Returns: // - []byte: The transformed request data in OpenAI Responses API format func ConvertOpenAIRequestToCodex(modelName string, inputRawJSON []byte, stream bool) []byte { + body, _ := convertOpenAIRequestToCodex(modelName, inputRawJSON, stream) + return body +} + +// convertOpenAIRequestToCodex also reports a file or audio part Responses cannot +// receive when it leaves a user turn with nothing to send. +func convertOpenAIRequestToCodex(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { rawJSON := inputRawJSON + var drops translatorcommon.UserTurnDrops root := gjson.ParseBytes(rawJSON) tools := root.Get("tools") toolResults := tools.Array() @@ -212,10 +220,13 @@ func ConvertOpenAIRequestToCodex(modelName string, inputRawJSON []byte, stream b } contentItems := make([][]byte, 0, 4) + // Counts the parts this user turn really sends; an empty text part does not. + turnSendable := 0 // Handle regular content c := m.Get("content") if c.Exists() && c.Type == gjson.String && c.String() != "" { + turnSendable++ // Single string content partType := "input_text" if role == "assistant" { @@ -240,6 +251,9 @@ func ConvertOpenAIRequestToCodex(modelName string, inputRawJSON []byte, stream b part, _ = sjson.SetBytes(part, "type", partType) part, _ = sjson.SetBytes(part, "text", it.Get("text").String()) contentItems = append(contentItems, part) + if it.Get("text").String() != "" { + turnSendable++ + } case "image_url": // Map image inputs to input_image for Responses API if role == "user" { @@ -249,19 +263,15 @@ func ConvertOpenAIRequestToCodex(modelName string, inputRawJSON []byte, stream b part, _ = sjson.SetBytes(part, "image_url", u.String()) } contentItems = append(contentItems, part) + turnSendable++ } case "file": if role == "user" { - fileData := it.Get("file.file_data").String() - filename := it.Get("file.filename").String() - if fileData != "" { - part := []byte(`{}`) - part, _ = sjson.SetBytes(part, "type", "input_file") - part, _ = sjson.SetBytes(part, "file_data", fileData) - if filename != "" { - part, _ = sjson.SetBytes(part, "filename", filename) - } + if part, ok := codexInputFilePart(it); ok { contentItems = append(contentItems, part) + turnSendable++ + } else { + drops.Drop(t) } } case "input_audio": @@ -276,11 +286,17 @@ func ConvertOpenAIRequestToCodex(modelName string, inputRawJSON []byte, stream b part, _ = sjson.SetBytes(part, "format", audioFormat) } contentItems = append(contentItems, part) + turnSendable++ + } else { + drops.Drop(t) } } } } } + if role == "user" { + drops.EndTurn(turnSendable) + } // Don't emit empty assistant messages when only tool_calls // are present — Responses API needs function_call items @@ -518,7 +534,7 @@ func ConvertOpenAIRequestToCodex(modelName string, inputRawJSON []byte, stream b } out, _ = sjson.SetBytes(out, "store", false) - return out + return out, drops.Err() } func setToolCallOutputContent(funcOutput []byte, content gjson.Result) []byte { @@ -580,32 +596,41 @@ func toolOutputContentPart(item gjson.Result) []byte { } return part case "file": - fileID := item.Get("file.file_id").String() - fileData := item.Get("file.file_data").String() - fileURL := item.Get("file.file_url").String() - if fileID == "" && fileData == "" && fileURL == "" { - return toolOutputFallbackPart(item) - } - part := []byte(`{}`) - part, _ = sjson.SetBytes(part, "type", "input_file") - if fileID != "" { - part, _ = sjson.SetBytes(part, "file_id", fileID) + if part, ok := codexInputFilePart(item); ok { + return part } - if fileData != "" { - part, _ = sjson.SetBytes(part, "file_data", fileData) - } - if fileURL != "" { - part, _ = sjson.SetBytes(part, "file_url", fileURL) - } - if filename := item.Get("file.filename").String(); filename != "" { - part, _ = sjson.SetBytes(part, "filename", filename) - } - return part + return toolOutputFallbackPart(item) default: return toolOutputFallbackPart(item) } } +// codexInputFilePart maps a Chat Completions file part onto a Responses input_file +// part. It reports false when the part names no file id, bytes or url. +func codexInputFilePart(item gjson.Result) ([]byte, bool) { + fileID := item.Get("file.file_id").String() + fileData := item.Get("file.file_data").String() + fileURL := item.Get("file.file_url").String() + if fileID == "" && fileData == "" && fileURL == "" { + return nil, false + } + part := []byte(`{}`) + part, _ = sjson.SetBytes(part, "type", "input_file") + if fileID != "" { + part, _ = sjson.SetBytes(part, "file_id", fileID) + } + if fileData != "" { + part, _ = sjson.SetBytes(part, "file_data", fileData) + } + if fileURL != "" { + part, _ = sjson.SetBytes(part, "file_url", fileURL) + } + if filename := item.Get("file.filename").String(); filename != "" { + part, _ = sjson.SetBytes(part, "filename", filename) + } + return part, true +} + func hasToolOutputImagePart(content gjson.Result) bool { if !content.IsArray() { return false diff --git a/internal/translator/codex/openai/chat-completions/codex_openai_user_turn_test.go b/internal/translator/codex/openai/chat-completions/codex_openai_user_turn_test.go new file mode 100644 index 00000000000..39867d2694c --- /dev/null +++ b/internal/translator/codex/openai/chat-completions/codex_openai_user_turn_test.go @@ -0,0 +1,136 @@ +package chat_completions + +import ( + "context" + "errors" + "testing" + + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +const ( + userTurnFileID = `{"type":"file","file":{"file_id":"file-1"}}` + userTurnFileURL = `{"type":"file","file":{"file_url":"https://example.test/a.pdf","filename":"a.pdf"}}` + userTurnEmptyFile = `{"type":"file","file":{"filename":"a.pdf"}}` + userTurnEmptyAudio = `{"type":"input_audio","input_audio":{"format":"wav"}}` + userTurnText = `{"type":"text","text":"keep me"}` + userTurnEmptyText = `{"type":"text","text":""}` + userTurnInline = `{"type":"file","file":{"filename":"a.pdf","file_data":"data:application/pdf;base64,JVBERi0xLjQK"}}` + userTurnAudio = `{"type":"input_audio","input_audio":{"data":"UklGRg==","format":"wav"}}` +) + +func TestConvertOpenAIRequestToCodex_RefusesAnyEmptiedUserTurn(t *testing.T) { + cases := []struct { + name string + input string + wantType string + }{ + { + name: "history then file without a source", + input: `{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[` + userTurnEmptyFile + `]}]}`, + wantType: "file", + }, + { + name: "system and developer prompts do not hide the empty turn", + input: `{"model":"m","messages":[{"role":"system","content":"sys"},{"role":"developer","content":"dev"},{"role":"user","content":[` + userTurnEmptyFile + `]}]}`, + wantType: "file", + }, + { + name: "emptied turn before a later text turn", + input: `{"model":"m","messages":[{"role":"user","content":[` + userTurnEmptyFile + `]},{"role":"assistant","content":"ok"},{"role":"user","content":"next"}]}`, + wantType: "file", + }, + { + name: "audio without bytes", + input: `{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[` + userTurnEmptyAudio + `]}]}`, + wantType: "input_audio", + }, + { + name: "empty text beside the empty file does not count as sendable", + input: `{"model":"m","messages":[{"role":"user","content":[` + userTurnEmptyText + `,` + userTurnEmptyFile + `]}]}`, + wantType: "file", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + body, err := convertOpenAIRequestToCodex("m", []byte(tc.input), false) + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(err, &unsupported) || unsupported.Type != tc.wantType || unsupported.StatusCode() != 400 { + t.Fatalf("err = %v, want unsupported content part: %s; body = %s", err, tc.wantType, body) + } + if got, want := err.Error(), "unsupported content part: "+tc.wantType; got != want { + t.Fatalf("error text = %q, want %q", got, want) + } + if !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } + + envelope := sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatOpenAI, sdktranslator.FormatCodex, + sdktranslator.RequestEnvelope{Format: sdktranslator.FormatOpenAI, Model: "m", Body: []byte(tc.input)}) + if !errors.As(envelope.Err, &unsupported) || unsupported.Type != tc.wantType { + t.Fatalf("registry err = %v, want unsupported content part: %s", envelope.Err, tc.wantType) + } + }) + } +} + +func TestConvertOpenAIRequestToCodex_FileIDStaysAnInputFile(t *testing.T) { + cases := map[string]struct { + part string + key string + want string + }{ + "file id": {part: userTurnFileID, key: "file_id", want: "file-1"}, + "file url": {part: userTurnFileURL, key: "file_url", want: "https://example.test/a.pdf"}, + "file data": { + part: userTurnInline, + key: "file_data", + want: "data:application/pdf;base64,JVBERi0xLjQK", + }, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + input := `{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[` + tc.part + `]}]}` + body, err := convertOpenAIRequestToCodex("m", []byte(input), false) + if err != nil { + t.Fatalf("err = %v", err) + } + part := gjson.GetBytes(body, "input.2.content.0") + if part.Get("type").String() != "input_file" || part.Get(tc.key).String() != tc.want { + t.Fatalf("part = %s, body = %s", part.Raw, body) + } + }) + } +} + +func TestConvertOpenAIRequestToCodex_KeepsTurnWithTextBesideAttachment(t *testing.T) { + input := `{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[` + userTurnText + `,` + userTurnEmptyFile + `]}]}` + body, err := convertOpenAIRequestToCodex("m", []byte(input), false) + if err != nil { + t.Fatalf("err = %v", err) + } + if got := gjson.GetBytes(body, "input.2.content.0.text").String(); got != "keep me" { + t.Fatalf("text was lost: %s", body) + } +} + +func TestConvertOpenAIRequestToCodex_AudioAfterHistoryStaysAudio(t *testing.T) { + input := `{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[` + userTurnAudio + `]}]}` + body, err := convertOpenAIRequestToCodex("m", []byte(input), false) + if err != nil { + t.Fatalf("err = %v", err) + } + part := gjson.GetBytes(body, "input.2.content.0") + if part.Get("type").String() != "input_audio" || part.Get("data").String() != "UklGRg==" { + t.Fatalf("part = %s, body = %s", part.Raw, body) + } +} + +func TestConvertOpenAIRequestToCodex_ExportedWrapperKeepsAJSONBody(t *testing.T) { + input := []byte(`{"model":"m","messages":[{"role":"user","content":[` + userTurnEmptyFile + `]}]}`) + if body := ConvertOpenAIRequestToCodex("m", input, false); !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } +} diff --git a/internal/translator/codex/openai/chat-completions/init.go b/internal/translator/codex/openai/chat-completions/init.go index 35a3da8c02d..82cd75bd9ad 100644 --- a/internal/translator/codex/openai/chat-completions/init.go +++ b/internal/translator/codex/openai/chat-completions/init.go @@ -4,16 +4,18 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( OpenAI, Codex, - ConvertOpenAIRequestToCodex, + nil, interfaces.TranslateResponse{ Stream: ConvertCodexResponseToOpenAI, NonStream: ConvertCodexResponseToOpenAINonStream, }, ) + sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatOpenAI, sdktranslator.FormatCodex, convertOpenAIRequestToCodex) } diff --git a/internal/translator/common/parts.go b/internal/translator/common/parts.go index a402fabec7b..adfa2829562 100644 --- a/internal/translator/common/parts.go +++ b/internal/translator/common/parts.go @@ -1,6 +1,12 @@ package common -import "fmt" +import ( + "fmt" + "net/url" + "strings" + + "github.com/tidwall/gjson" +) // UnsupportedPartError is a request-scoped rejection. The part type was present // and this translation has no equivalent, so the request must not be sent with @@ -20,12 +26,155 @@ func (e *UnsupportedPartError) StatusCode() int { return 400 } func (e *UnsupportedPartError) IsRequestScoped() bool { return true } -// ErrIfNothingLeft is the shared policy for a file part a translation cannot -// send: text beside it still goes out, but a request left with no content is -// refused rather than forwarded empty. -func ErrIfNothingLeft(droppedType string, remaining int) error { - if droppedType == "" || remaining > 0 { +// UserTurnDrops is the shared policy for a part a translation cannot send: text +// or any other sendable part beside it still goes out, but a user turn left with +// nothing to send is refused rather than forwarded empty. The decision is made +// per user turn, so earlier or later turns, system prompts and developer +// prompts can never hide an emptied user turn. +type UserTurnDrops struct { + turn string + first string +} + +// Drop records a part of the current user turn that cannot be sent. The first +// type recorded within a turn is the one reported. +func (d *UserTurnDrops) Drop(partType string) { + if d.turn == "" { + d.turn = partType + } +} + +// EndTurn closes the current user turn. sendable is the number of parts the turn +// contributed to the translated request. A turn that dropped a part and +// contributed nothing is remembered; a later turn never clears it. +func (d *UserTurnDrops) EndTurn(sendable int) { + if d.turn != "" && sendable <= 0 && d.first == "" { + d.first = d.turn + } + d.turn = "" +} + +// Err returns the refusal for the first emptied user turn, or nil. +func (d *UserTurnDrops) Err() error { + if d.first == "" { + return nil + } + return &UnsupportedPartError{Type: d.first} +} + +// UserRun follows the consecutive user content that a target merges into one +// user turn. Add records content that keeps the turn alive, Drop records a part +// that could not be sent, and End closes the turn when model content starts or +// the input ends. Every method is a no-op on a nil receiver, so callers can pass +// nil for content that is not user content. +type UserRun struct { + drops UserTurnDrops + sendable int +} + +// Add records one sendable item in the current user turn. +func (r *UserRun) Add() { + if r != nil { + r.sendable++ + } +} + +// Drop records a part of the current user turn that cannot be sent. +func (r *UserRun) Drop(partType string) { + if r != nil { + r.drops.Drop(partType) + } +} + +// End closes the current user turn. +func (r *UserRun) End() { + if r != nil { + r.drops.EndTurn(r.sendable) + r.sendable = 0 + } +} + +// Err returns the refusal for the first emptied user turn, or nil. +func (r *UserRun) Err() error { + if r == nil { return nil } - return &UnsupportedPartError{Type: droppedType} + return r.drops.Err() +} + +// IsInteractionsInstructionStep reports whether an Interactions step carries +// developer or system content rather than user content. The step's own role +// decides, falling back to its type; a step that names neither inherits the +// answer from the wrapper it sits in. Instruction content is still sent, but it +// closes the open user turn and never keeps an emptied one alive. +func IsInteractionsInstructionStep(step gjson.Result, inherited bool) bool { + name := strings.ToLower(strings.TrimSpace(step.Get("role").String())) + if name == "" { + name = strings.ToLower(strings.TrimSpace(step.Get("type").String())) + } + switch name { + case "developer", "system": + return true + case "user", "assistant", "model", "model_output", "thought": + return false + } + return inherited +} + +// InteractionsAttachmentType names the type of an Interactions content part that +// carries an attachment, or returns "" for text and for parts that name nothing. +// It is the type reported when a translation cannot send the part. +func InteractionsAttachmentType(part gjson.Result) string { + if !part.IsObject() { + return "" + } + if partType := strings.ToLower(strings.TrimSpace(part.Get("type").String())); partType != "" { + if partType == "text" { + return "" + } + return partType + } + if part.Get("inlineData").Exists() || part.Get("inline_data").Exists() { + return "inlineData" + } + if part.Get("fileData").Exists() || part.Get("file_data").Exists() { + return "fileData" + } + return "" +} + +// GeminiPartIsSendable reports whether a Gemini part gives the model something to +// read. A text part that is empty or only whitespace does not. +func GeminiPartIsSendable(part []byte) bool { + parsed := gjson.ParseBytes(part) + text := parsed.Get("text") + if !text.Exists() || strings.TrimSpace(text.String()) != "" { + return true + } + for _, key := range []string{"functionCall", "functionResponse", "inlineData", "inline_data", "fileData", "file_data"} { + if parsed.Get(key).Exists() { + return true + } + } + return false +} + +// CountSendableGeminiParts counts the parts for which GeminiPartIsSendable holds. +func CountSendableGeminiParts(parts [][]byte) int { + count := 0 + for _, part := range parts { + if GeminiPartIsSendable(part) { + count++ + } + } + return count +} + +// IsHTTPURL reports whether value is an absolute http or https URL with a host. +func IsHTTPURL(value string) bool { + parsed, errParse := url.Parse(strings.TrimSpace(value)) + if errParse != nil || parsed.Host == "" { + return false + } + return strings.EqualFold(parsed.Scheme, "http") || strings.EqualFold(parsed.Scheme, "https") } diff --git a/internal/translator/common/parts_test.go b/internal/translator/common/parts_test.go new file mode 100644 index 00000000000..92c889e40ae --- /dev/null +++ b/internal/translator/common/parts_test.go @@ -0,0 +1,179 @@ +package common + +import ( + "errors" + "testing" + + "github.com/tidwall/gjson" +) + +func TestUserTurnDropsRefusesAnEmptiedTurnEvenWhenOtherTurnsRemain(t *testing.T) { + var drops UserTurnDrops + drops.EndTurn(1) // an earlier normal turn + drops.Drop("container_upload") + drops.EndTurn(0) // the turn the attachment emptied + drops.EndTurn(3) // a later normal turn must not clear the refusal + + var unsupported *UnsupportedPartError + err := drops.Err() + if !errors.As(err, &unsupported) || unsupported.Type != "container_upload" { + t.Fatalf("err = %v, want unsupported content part: container_upload", err) + } + if unsupported.StatusCode() != 400 || !unsupported.IsRequestScoped() { + t.Fatalf("err = %#v", unsupported) + } +} + +func TestUserTurnDropsKeepsATurnThatStillHasSendableParts(t *testing.T) { + var drops UserTurnDrops + drops.Drop("file") + drops.EndTurn(1) + if err := drops.Err(); err != nil { + t.Fatalf("err = %v, want nil", err) + } +} + +func TestUserTurnDropsIgnoresAnEmptyTurnWithoutADroppedPart(t *testing.T) { + var drops UserTurnDrops + drops.EndTurn(0) + if err := drops.Err(); err != nil { + t.Fatalf("err = %v, want nil", err) + } +} + +func TestUserTurnDropsReportsTheFirstEmptiedTurn(t *testing.T) { + var drops UserTurnDrops + drops.Drop("document") + drops.Drop("container_upload") + drops.EndTurn(0) + drops.Drop("file") + drops.EndTurn(0) + if got, want := drops.Err().Error(), "unsupported content part: document"; got != want { + t.Fatalf("error text = %q, want %q", got, want) + } +} + +func TestUserTurnDropsDoesNotLeakAFlagIntoTheNextTurn(t *testing.T) { + var drops UserTurnDrops + drops.Drop("file") + drops.EndTurn(1) + drops.EndTurn(0) + if err := drops.Err(); err != nil { + t.Fatalf("err = %v, want nil", err) + } +} + +func TestIsHTTPURL(t *testing.T) { + cases := map[string]bool{ + "https://example.test/a.png": true, + "HTTP://example.test/a.png": true, + " https://example.test/a ": true, + "gs://bucket/a.pdf": false, + "files/abc123": false, + "ftp://example.test/a.png": false, + "data:image/png;base64,aGk=": false, + "https://": false, + "": false, + } + for value, want := range cases { + if got := IsHTTPURL(value); got != want { + t.Fatalf("IsHTTPURL(%q) = %v, want %v", value, got, want) + } + } +} + +func TestUserRunRefusesATurnEmptiedByADroppedPart(t *testing.T) { + var run UserRun + run.Add() + run.End() // an earlier normal turn + run.Drop("image") + run.End() // the turn the attachment emptied + run.Add() + run.End() // a later normal turn must not clear the refusal + if got, want := run.Err().Error(), "unsupported content part: image"; got != want { + t.Fatalf("error text = %q, want %q", got, want) + } +} + +func TestUserRunKeepsATurnWithOtherSendableContent(t *testing.T) { + var run UserRun + run.Drop("audio") + run.Add() + run.End() + if err := run.Err(); err != nil { + t.Fatalf("err = %v, want nil", err) + } +} + +func TestUserRunIsANoOpOnANilReceiver(t *testing.T) { + var run *UserRun + run.Add() + run.Drop("image") + run.End() + if err := run.Err(); err != nil { + t.Fatalf("err = %v, want nil", err) + } +} + +func TestInteractionsAttachmentType(t *testing.T) { + cases := map[string]string{ + `{"type":"image","uri":"gs://b/a.png"}`: "image", + `{"type":" Audio "}`: "audio", + `{"type":"text","text":"hi"}`: "", + `{"text":"hi"}`: "", + `{"inlineData":{"mimeType":"image/png"}}`: "inlineData", + `{"inline_data":{"mime_type":"image/png"}}`: "inlineData", + `{"fileData":{"mimeType":"image/png"}}`: "fileData", + `{"file_data":{"mime_type":"image/png"}}`: "fileData", + `{}`: "", + `"plain string"`: "", + `{"type":"image_url","image_url":{"url":""}}`: "image_url", + } + for raw, want := range cases { + if got := InteractionsAttachmentType(gjson.Parse(raw)); got != want { + t.Fatalf("InteractionsAttachmentType(%s) = %q, want %q", raw, got, want) + } + } +} + +func TestCountSendableGeminiPartsIgnoresBlankText(t *testing.T) { + parts := [][]byte{ + []byte(`{"text":""}`), + []byte(`{"text":" \n\t"}`), + []byte(`{"text":"hi"}`), + []byte(`{"inlineData":{"mimeType":"image/png","data":"aGk="}}`), + []byte(`{"fileData":{"mimeType":"image/png","fileUri":"gs://b/a.png"}}`), + []byte(`{"functionResponse":{"name":"f","response":{}}}`), + } + if got, want := CountSendableGeminiParts(parts), 4; got != want { + t.Fatalf("CountSendableGeminiParts = %d, want %d", got, want) + } +} + +func TestIsInteractionsInstructionStep(t *testing.T) { + cases := []struct { + raw string + inherited bool + want bool + }{ + {`{"type":"user_input","role":"developer","content":"note"}`, false, true}, + {`{"type":"user_input","role":"System","content":"note"}`, false, true}, + {`{"role":"system","content":"note"}`, false, true}, + {`{"type":"system","text":"note"}`, false, true}, + {`{"type":"developer","text":"note"}`, false, true}, + {`{"type":"user_input","role":"user","content":"hi"}`, false, false}, + {`{"type":"user_input","content":"hi"}`, false, false}, + {`{"type":"user_input","content":"hi"}`, true, true}, + {`{"type":"user_input","role":"user","content":"hi"}`, true, false}, + {`{"type":"model_output","content":"hi"}`, true, false}, + {`{"role":"assistant","content":"hi"}`, true, false}, + {`{"role":"user","type":"system"}`, false, false}, + {`"plain string"`, true, true}, + {`"plain string"`, false, false}, + } + for _, tc := range cases { + if got := IsInteractionsInstructionStep(gjson.Parse(tc.raw), tc.inherited); got != tc.want { + t.Fatalf("IsInteractionsInstructionStep(%s, %v) = %v, want %v", tc.raw, tc.inherited, got, tc.want) + } + } +} diff --git a/internal/translator/gemini/claude/gemini_claude_request.go b/internal/translator/gemini/claude/gemini_claude_request.go index fe58d81dea3..e054ac87d72 100644 --- a/internal/translator/gemini/claude/gemini_claude_request.go +++ b/internal/translator/gemini/claude/gemini_claude_request.go @@ -49,7 +49,7 @@ func ConvertClaudeRequestToGeminiWithCompatReturningError(modelName string, inpu func convertClaudeRequestToGemini(modelName string, inputRawJSON []byte, _ bool, preserveEmptyThinkingBlocks bool) ([]byte, error) { rawJSON := inputRawJSON - var droppedAttachment string + var drops translatorcommon.UserTurnDrops // Build output Gemini request JSON out := []byte(`{"contents":[]}`) out, _ = sjson.SetBytes(out, "model", modelName) @@ -199,8 +199,9 @@ func convertClaudeRequestToGemini(modelName string, inputRawJSON []byte, _ bool, case "image", "document", "container_upload": if part := claudeBase64InlineData(contentResult.Get("source")); part != nil { partItems = append(partItems, part) - } else if partType := contentResult.Get("type").String(); partType != "image" { - droppedAttachment = partType + } else if originalRole == "user" { + // A part that cannot be inlined (url or file source) is dropped; the turn is refused only if nothing else is left. + drops.Drop(contentResult.Get("type").String()) } default: return true @@ -210,6 +211,10 @@ func convertClaudeRequestToGemini(modelName string, inputRawJSON []byte, _ bool, if role == "user" { partItems = translatorcommon.ReorderGeminiUserParts(partItems) } + if originalRole == "user" { + // Whitespace-only text is forwarded but never keeps an emptied turn alive. + drops.EndTurn(translatorcommon.CountSendableGeminiParts(partItems)) + } if len(partItems) > 0 { contentItems = append(contentItems, geminiContentWithParts(role, partItems)) } @@ -366,7 +371,7 @@ func convertClaudeRequestToGemini(modelName string, inputRawJSON []byte, _ bool, result := out result = common.AttachDefaultSafetySettings(result, "safetySettings") - return result, translatorcommon.ErrIfNothingLeft(droppedAttachment, int(gjson.GetBytes(result, "contents.#").Int())) + return result, drops.Err() } func claudeBase64InlineData(source gjson.Result) []byte { diff --git a/internal/translator/gemini/claude/gemini_claude_user_turn_test.go b/internal/translator/gemini/claude/gemini_claude_user_turn_test.go new file mode 100644 index 00000000000..c6bde9a41f3 --- /dev/null +++ b/internal/translator/gemini/claude/gemini_claude_user_turn_test.go @@ -0,0 +1,165 @@ +package claude + +import ( + "context" + "errors" + "testing" + + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +const userTurnUpload = `{"type":"container_upload","file_id":"file-1"}` + +func TestConvertClaudeRequestToGemini_RefusesAnyEmptiedUserTurn(t *testing.T) { + cases := []struct { + name string + input string + wantType string + }{ + { + name: "history then attachment only", + input: `{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":[{"type":"text","text":"hi"}]},{"role":"user","content":[` + userTurnUpload + `]}]}`, + wantType: "container_upload", + }, + { + name: "system prompt and system reminder", + input: `{"model":"m","system":"sys","messages":[{"role":"system","content":"reminder"},{"role":"user","content":[` + userTurnUpload + `]}]}`, + wantType: "container_upload", + }, + { + name: "emptied turn before a later text turn", + input: `{"model":"m","messages":[{"role":"user","content":[` + userTurnUpload + `]},{"role":"assistant","content":[{"type":"text","text":"ok"}]},{"role":"user","content":"next"}]}`, + wantType: "container_upload", + }, + { + name: "document without bytes", + input: `{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"document","source":{"type":"file","file_id":"file-1"}}]}]}`, + wantType: "document", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + body, err := ConvertClaudeRequestToGeminiWithCompatReturningError("m", []byte(tc.input), false) + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(err, &unsupported) || unsupported.Type != tc.wantType || unsupported.StatusCode() != 400 { + t.Fatalf("err = %v, want unsupported content part: %s; body = %s", err, tc.wantType, body) + } + if got, want := err.Error(), "unsupported content part: "+tc.wantType; got != want { + t.Fatalf("error text = %q, want %q", got, want) + } + if !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } + }) + } +} + +func TestConvertClaudeRequestToGemini_KeepsTurnWithTextBesideAttachment(t *testing.T) { + input := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"text","text":"keep me"},` + userTurnUpload + `]}]}`) + body, err := ConvertClaudeRequestToGeminiWithCompatReturningError("m", input, false) + if err != nil { + t.Fatalf("err = %v", err) + } + if got := gjson.GetBytes(body, "contents.2.parts.0.text").String(); got != "keep me" { + t.Fatalf("text was lost: %s", body) + } +} + +func TestConvertClaudeRequestToGemini_Base64DocumentAfterHistoryStaysInlineData(t *testing.T) { + input := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"document","source":{"type":"base64","media_type":"application/pdf","data":"JVBERi0xLjQK"}}]}]}`) + body, err := ConvertClaudeRequestToGeminiWithCompatReturningError("m", input, false) + if err != nil { + t.Fatalf("err = %v", err) + } + part := gjson.GetBytes(body, "contents.2.parts.0.inline_data") + if part.Get("mime_type").String() != "application/pdf" || part.Get("data").String() != "JVBERi0xLjQK" { + t.Fatalf("part = %s, body = %s", part.Raw, body) + } +} + +// claudeImageTurnToGemini translates a conversation of two history turns followed by a final user +// turn holding the given content parts. +func claudeImageTurnToGemini(finalContent string) sdktranslator.RequestEnvelope { + input := `{"model":"m","messages":[{"role":"user","content":"a"},{"role":"assistant","content":"b"},{"role":"user","content":[` + finalContent + `]}]}` + return sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatClaude, sdktranslator.FormatGemini, sdktranslator.RequestEnvelope{ + Format: sdktranslator.FormatClaude, + Model: "m", + Body: []byte(input), + }) +} + +func requireImageRefusal(t *testing.T, envelope sdktranslator.RequestEnvelope) { + t.Helper() + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(envelope.Err, &unsupported) || unsupported.Type != "image" || unsupported.StatusCode() != 400 { + t.Fatalf("envelope.Err = %v, want unsupported content part: image; body = %s", envelope.Err, envelope.Body) + } + if got, want := envelope.Err.Error(), "unsupported content part: image"; got != want { + t.Fatalf("error text = %q, want %q", got, want) + } +} + +func TestClaudeToGeminiUnrepresentableImageOnlyTurnIsRefused(t *testing.T) { + cases := map[string]string{ + "url source": `{"type":"url","url":"https://example.test/a.png"}`, + "file source": `{"type":"file","file_id":"file-1"}`, + } + for name, source := range cases { + t.Run(name, func(t *testing.T) { + requireImageRefusal(t, claudeImageTurnToGemini(`{"type":"image","source":`+source+`}`)) + }) + } +} + +func TestClaudeToGeminiUnrepresentableImageBesideTextStillSucceeds(t *testing.T) { + for _, source := range []string{`{"type":"url","url":"https://example.test/a.png"}`, `{"type":"file","file_id":"file-1"}`} { + envelope := claudeImageTurnToGemini(`{"type":"text","text":"keep me"},{"type":"image","source":` + source + `}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + parts := gjson.GetBytes(envelope.Body, "contents.2.parts").Array() + if len(parts) != 1 || parts[0].Get("text").String() != "keep me" { + t.Fatalf("text was lost or an image leaked: %s", envelope.Body) + } + } +} + +func TestClaudeToGeminiEmptyTextDoesNotHideAnUnrepresentableImage(t *testing.T) { + requireImageRefusal(t, claudeImageTurnToGemini(`{"type":"text","text":""},{"type":"image","source":{"type":"url","url":"https://example.test/a.png"}}`)) +} + +func TestClaudeToGeminiBase64ImageOnlyTurnStaysInlineData(t *testing.T) { + envelope := claudeImageTurnToGemini(`{"type":"image","source":{"type":"base64","media_type":"image/png","data":"aGVsbG8="}}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + inlineData := gjson.GetBytes(envelope.Body, "contents.2.parts.0.inline_data") + if inlineData.Get("mime_type").String() != "image/png" || inlineData.Get("data").String() != "aGVsbG8=" { + t.Fatalf("inlineData = %s, body = %s", inlineData.Raw, envelope.Body) + } +} + +func TestClaudeToGeminiWhitespaceTextDoesNotHideAnUnrepresentableImage(t *testing.T) { + for _, text := range []string{" ", ` \n\t`, `\u00a0`} { + requireImageRefusal(t, claudeImageTurnToGemini(`{"type":"text","text":"`+text+`"},{"type":"image","source":{"type":"file","file_id":"file-1"}}`)) + } + requireImageRefusal(t, claudeImageTurnToGemini(`{"type":"image","source":{"type":"url","url":"https://example.test/a.png"}},{"type":"text","text":" "}`)) +} + +func TestClaudeToGeminiRealTextBesideWhitespaceAndAnImageStillSucceeds(t *testing.T) { + envelope := claudeImageTurnToGemini(`{"type":"text","text":" "},{"type":"text","text":"keep me"},{"type":"image","source":{"type":"file","file_id":"file-1"}}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + found := false + for _, part := range gjson.GetBytes(envelope.Body, "contents.2.parts").Array() { + if part.Get("text").String() == "keep me" { + found = true + } + } + if !found { + t.Fatalf("text was lost: %s", envelope.Body) + } +} diff --git a/internal/translator/gemini/interactions/init.go b/internal/translator/gemini/interactions/init.go index 2a338c207a5..ec1785e867b 100644 --- a/internal/translator/gemini/interactions/init.go +++ b/internal/translator/gemini/interactions/init.go @@ -4,6 +4,7 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { @@ -19,7 +20,7 @@ func init() { translator.Register( Interactions, Gemini, - ConvertInteractionsRequestToGemini, + nil, interfaces.TranslateResponse{ Stream: ConvertGeminiResponseToInteractions, NonStream: ConvertGeminiResponseToInteractionsNonStream, @@ -28,10 +29,12 @@ func init() { translator.Register( Gemini, Interactions, - ConvertGeminiRequestToInteractions, + nil, interfaces.TranslateResponse{ Stream: ConvertInteractionsResponseToGemini, NonStream: ConvertInteractionsResponseToGeminiNonStream, }, ) + sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatInteractions, sdktranslator.FormatGemini, convertInteractionsRequestToGemini) + sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatGemini, sdktranslator.FormatInteractions, convertGeminiRequestToInteractions) } diff --git a/internal/translator/gemini/interactions/interactions_gemini_common.go b/internal/translator/gemini/interactions/interactions_gemini_common.go index 56097c8a840..e0ec74a4b5d 100644 --- a/internal/translator/gemini/interactions/interactions_gemini_common.go +++ b/internal/translator/gemini/interactions/interactions_gemini_common.go @@ -27,6 +27,13 @@ type StreamState struct { } func ConvertInteractionsRequestToGemini(modelName string, inputRawJSON []byte, stream bool) []byte { + out, _ := convertInteractionsRequestToGemini(modelName, inputRawJSON, stream) + return out +} + +// convertInteractionsRequestToGemini also reports a user turn that was left empty +// because its only attachment has no Gemini equivalent. +func convertInteractionsRequestToGemini(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { root := gjson.ParseBytes(inputRawJSON) out := []byte(`{"model":"","contents":[]}`) if modelName != "" && root.Get("model").Exists() { @@ -39,12 +46,20 @@ func ConvertInteractionsRequestToGemini(modelName string, inputRawJSON []byte, s out = copyInteractionsToolChoice(out, root) out = copyInteractionsServiceTier(out, root) contentItems := translatorcommon.NewRawArrayItems(root.Get("input.#").Int()) - appendInteractionsInput(&contentItems, root.Get("input")) + errInput := appendInteractionsInput(&contentItems, root.Get("input")) out = translatorcommon.SetRawArrayItems(out, "contents", contentItems) - return out + return out, errInput } func ConvertGeminiRequestToInteractions(modelName string, inputRawJSON []byte, stream bool) []byte { + out, _ := convertGeminiRequestToInteractions(modelName, inputRawJSON, stream) + return out +} + +// convertGeminiRequestToInteractions also reports a user turn that was left empty +// because its only part could not be carried over to Interactions. +func convertGeminiRequestToInteractions(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { + var drops translatorcommon.UserTurnDrops root := gjson.ParseBytes(inputRawJSON) out := []byte(`{"model":"","input":[]}`) out, _ = sjson.SetBytes(out, "model", modelName) @@ -62,11 +77,14 @@ func ConvertGeminiRequestToInteractions(modelName string, inputRawJSON []byte, s if role == "model" { stepType = "model_output" } + // Counts what this turn sends; empty text is not sendable. + sendable := 0 content.Get("parts").ForEach(func(_, part gjson.Result) bool { if fc := part.Get("functionCall"); fc.Exists() { for _, step := range geminiPartToInteractionsSteps(part) { if len(step) > 0 { inputItems = append(inputItems, step) + sendable++ } } return true @@ -75,6 +93,7 @@ func ConvertGeminiRequestToInteractions(modelName string, inputRawJSON []byte, s for _, step := range geminiPartToInteractionsSteps(part) { if len(step) > 0 { inputItems = append(inputItems, step) + sendable++ } } return true @@ -89,6 +108,9 @@ func ConvertGeminiRequestToInteractions(modelName string, inputRawJSON []byte, s } item := geminiPartToInteractionsContent(part) if len(item) == 0 { + if role != "model" && geminiPartFileData(part).Exists() { + drops.Drop("fileData") + } return true } currentStepType := stepType @@ -99,13 +121,17 @@ func ConvertGeminiRequestToInteractions(modelName string, inputRawJSON []byte, s step, _ = sjson.SetBytes(step, "type", currentStepType) step = translatorcommon.SetRawArrayItems(step, "content", [][]byte{item}) inputItems = append(inputItems, step) + sendable++ return true }) + if role != "model" { + drops.EndTurn(sendable) + } return true }) out = translatorcommon.SetRawArrayItems(out, "input", inputItems) out, _ = sjson.SetBytes(out, "stream", stream) - return out + return out, drops.Err() } func copyGeminiSystemInstructionToInteractions(out []byte, root gjson.Result) []byte { @@ -310,9 +336,20 @@ func geminiPartToInteractionsContent(part gjson.Result) []byte { if inline := part.Get("inline_data"); inline.Exists() { return geminiInlineDataToInteractionsContent(inline.Get("mime_type").String(), inline.Get("data").String()) } + if fileData := geminiPartFileData(part); fileData.Exists() { + return geminiFileDataToInteractionsContent(fileData) + } return nil } +// geminiPartFileData returns the fileData object of a Gemini part in either spelling. +func geminiPartFileData(part gjson.Result) gjson.Result { + if fileData := part.Get("fileData"); fileData.Exists() { + return fileData + } + return part.Get("file_data") +} + func ConvertGeminiResponseToInteractionsStream(ctx context.Context, modelName string, originalRequestRawJSON, requestRawJSON, rawJSON []byte, param *any) [][]byte { _ = ctx if *param == nil { @@ -808,11 +845,36 @@ type geminiInteractionsInputContext struct { inModelTurn bool lastStepType string pendingSignature string + // run follows the consecutive user content so that an attachment Gemini cannot + // carry is refused only when its whole user turn is left with nothing to send. + run translatorcommon.UserRun + // instruction is set while the step being added is developer or system content. + instruction bool } -func appendInteractionsInput(items *[][]byte, input gjson.Result) { +// userRun returns the tracker for content added with role. Model content and +// developer or system content close the open user turn and have no tracker, so +// they can never keep an emptied user turn alive. +func (ctx *geminiInteractionsInputContext) userRun(role string) *translatorcommon.UserRun { + if role == "user" && !ctx.instruction { + return &ctx.run + } + ctx.run.End() + return nil +} + +// appendText adds a text content; blank text does not keep a user turn alive. +func (ctx *geminiInteractionsInputContext) appendText(role, text string) { + appendGeminiTextContent(&ctx.items, role, text) + run := ctx.userRun(role) + if strings.TrimSpace(text) != "" { + run.Add() + } +} + +func appendInteractionsInput(items *[][]byte, input gjson.Result) error { if !input.Exists() { - return + return nil } ctx := &geminiInteractionsInputContext{ items: *items, @@ -821,7 +883,7 @@ func appendInteractionsInput(items *[][]byte, input gjson.Result) { appendGeminiTextContent(&ctx.items, "user", input.String()) ctx.lastStepType = "text" *items = ctx.items - return + return nil } if input.IsArray() { input.ForEach(func(_, item gjson.Result) bool { @@ -833,24 +895,31 @@ func appendInteractionsInput(items *[][]byte, input gjson.Result) { if role := input.Get("role").String(); role == "model" || role == "assistant" { defaultRole = "model" } + ctx.instruction = translatorcommon.IsInteractionsInstructionStep(input, false) steps.ForEach(func(_, step gjson.Result) bool { appendInteractionsStepToGemini(ctx, step, defaultRole) return true }) + ctx.instruction = false } else { appendInteractionsStepToGemini(ctx, input, "user") } flushPendingGeminiSignature(ctx) *items = ctx.items + ctx.run.End() + return ctx.run.Err() } func appendInteractionsStepToGemini(ctx *geminiInteractionsInputContext, item gjson.Result, defaultRole string) { + inheritedInstruction := ctx.instruction + ctx.instruction = translatorcommon.IsInteractionsInstructionStep(item, inheritedInstruction) + defer func() { ctx.instruction = inheritedInstruction }() if item.Type == gjson.String { if ctx.inModelTurn { flushPendingGeminiSignature(ctx) ctx.inModelTurn = false } - appendGeminiTextContent(&ctx.items, defaultRole, item.String()) + ctx.appendText(defaultRole, item.String()) ctx.lastStepType = "text" return } @@ -870,6 +939,7 @@ func appendInteractionsStepToGemini(ctx *geminiInteractionsInputContext, item gj stepType := item.Get("type").String() switch stepType { case "model_output": + ctx.run.End() if ctx.pendingSignature != "" { carrier := geminiTextPartJSON("", false) carrier, _ = sjson.SetBytes(carrier, "thoughtSignature", ctx.pendingSignature) @@ -891,6 +961,7 @@ func appendInteractionsStepToGemini(ctx *geminiInteractionsInputContext, item gj ctx.inModelTurn = true ctx.lastStepType = "model_output" case "thought": + ctx.run.End() if sig := firstNonEmptyString(item.Get("signature").String(), item.Get("thought_signature").String(), item.Get("thoughtSignature").String()); sig != "" { if ctx.pendingSignature != "" && ctx.pendingSignature != sig { carrier := geminiTextPartJSON("", false) @@ -914,6 +985,7 @@ func appendInteractionsStepToGemini(ctx *geminiInteractionsInputContext, item gj ctx.inModelTurn = true ctx.lastStepType = "thought" case "function_call": + ctx.run.End() part := buildGeminiFunctionCallPart(item) sig := firstNonEmptyString(item.Get("signature").String(), item.Get("thought_signature").String(), item.Get("thoughtSignature").String()) if sig == "" && ctx.pendingSignature != "" { @@ -949,6 +1021,8 @@ func appendInteractionsStepToGemini(ctx *geminiInteractionsInputContext, item gj ctx.inModelTurn = false } part := buildGeminiFunctionResultPart(item) + // A tool result is content the model reads, so it keeps the surrounding user turn. + ctx.run.Add() if ctx.lastStepType == "function_result" && len(ctx.items) > 0 && gjson.GetBytes(ctx.items[len(ctx.items)-1], "role").String() == "user" { ctx.items[len(ctx.items)-1] = appendGeminiUserContentPart(ctx.items[len(ctx.items)-1], part) } else { @@ -961,9 +1035,9 @@ func appendInteractionsStepToGemini(ctx *geminiInteractionsInputContext, item gj ctx.inModelTurn = false } if item.Get("parts").Exists() { - appendInteractionsNativeContent(&ctx.items, item, defaultRole) + appendInteractionsNativeContent(ctx, item, defaultRole) } else { - appendInteractionsContentList(&ctx.items, defaultRole, item.Get("content")) + appendInteractionsContentList(ctx, defaultRole, item.Get("content")) } ctx.lastStepType = "user_input" default: @@ -972,11 +1046,11 @@ func appendInteractionsStepToGemini(ctx *geminiInteractionsInputContext, item gj ctx.inModelTurn = false } if item.Get("parts").Exists() { - appendInteractionsNativeContent(&ctx.items, item, defaultRole) + appendInteractionsNativeContent(ctx, item, defaultRole) } else if item.Get("content").Exists() { - appendInteractionsContentList(&ctx.items, defaultRole, item.Get("content")) + appendInteractionsContentList(ctx, defaultRole, item.Get("content")) } else if text := item.Get("text"); text.Exists() { - appendGeminiTextContent(&ctx.items, defaultRole, text.String()) + ctx.appendText(defaultRole, text.String()) } ctx.lastStepType = "default" } @@ -1134,23 +1208,32 @@ func buildGeminiFunctionResultPart(item gjson.Result) []byte { return part } -func appendInteractionsNativeContent(items *[][]byte, item gjson.Result, defaultRole string) { +func appendInteractionsNativeContent(ctx *geminiInteractionsInputContext, item gjson.Result, defaultRole string) { parts := item.Get("parts") if !parts.Exists() || !parts.IsArray() { return } + role := interactionsGeminiContentRole(item.Get("role").String(), defaultRole) + run := ctx.userRun(role) partItems := make([][]byte, 0, 4) parts.ForEach(func(_, part gjson.Result) bool { - if partJSON := interactionsNativeGeminiPart(part); len(partJSON) > 0 { - partItems = append(partItems, partJSON) + partJSON := interactionsNativeGeminiPart(part) + if len(partJSON) == 0 { + if droppedType := translatorcommon.InteractionsAttachmentType(part); droppedType != "" { + run.Drop(droppedType) + } + return true + } + partItems = append(partItems, partJSON) + if translatorcommon.GeminiPartIsSendable(partJSON) { + run.Add() } return true }) if len(partItems) == 0 { return } - role := interactionsGeminiContentRole(item.Get("role").String(), defaultRole) - *items = append(*items, interactionsGeminiContent(role, partItems)) + ctx.items = append(ctx.items, interactionsGeminiContent(role, partItems)) } func interactionsGeminiContentRole(role, defaultRole string) string { @@ -1182,12 +1265,20 @@ func interactionsNativeGeminiPart(part gjson.Result) []byte { return nil } -func appendInteractionsContentPart(items *[][]byte, role string, part gjson.Result) { +// appendInteractionsContentPart adds one content part. run is nil for model +// content; for user content it records what is sent and what cannot be. +func appendInteractionsContentPart(items *[][]byte, role string, part gjson.Result, run *translatorcommon.UserRun) { partJSON := interactionsContentPartToGeminiPart(part, false) if len(partJSON) == 0 { + if droppedType := translatorcommon.InteractionsAttachmentType(part); droppedType != "" { + run.Drop(droppedType) + } return } *items = append(*items, interactionsGeminiContent(role, [][]byte{partJSON})) + if translatorcommon.GeminiPartIsSendable(partJSON) { + run.Add() + } } func interactionsContentPartToGeminiPart(part gjson.Result, thought bool) []byte { @@ -1217,11 +1308,8 @@ func interactionsContentPartToGeminiPart(part gjson.Result, thought bool) []byte return geminiInlineDataPartJSON(gjson.Parse(fmt.Sprintf(`{"mime_type":%q,"data":%q}`, mimeType, data))) } } - if uri := part.Get("file_uri"); uri.Exists() || part.Get("fileUri").Exists() { - fileURI := uri.String() - if fileURI == "" { - fileURI = part.Get("fileUri").String() - } + // uri is the Interactions spelling of file_uri. + if fileURI := firstNonEmptyString(part.Get("file_uri").String(), part.Get("fileUri").String(), part.Get("uri").String()); fileURI != "" { mimeType := part.Get("mime_type").String() if mimeType == "" { mimeType = part.Get("mimeType").String() @@ -1320,38 +1408,67 @@ func interactionsInputAudioMimeType(format string) string { } func geminiInlineDataToInteractionsContent(mimeType, data string) []byte { - contentType := "document" + item := []byte(`{"type":"","mime_type":"","data":""}`) + item, _ = sjson.SetBytes(item, "type", geminiInteractionsMediaType(mimeType)) + item, _ = sjson.SetBytes(item, "mime_type", mimeType) + item, _ = sjson.SetBytes(item, "data", data) + return item +} + +// geminiFileDataToInteractionsContent maps a Gemini fileData part onto an +// Interactions media part that references the file by uri. It returns nil when +// the part names no uri, which leaves nothing to send. +func geminiFileDataToInteractionsContent(fileData gjson.Result) []byte { + fileURI := strings.TrimSpace(fileData.Get("fileUri").String()) + if fileURI == "" { + fileURI = strings.TrimSpace(fileData.Get("file_uri").String()) + } + if fileURI == "" { + return nil + } + mimeType := fileData.Get("mimeType").String() + if mimeType == "" { + mimeType = fileData.Get("mime_type").String() + } + item := []byte(`{"type":"","uri":""}`) + item, _ = sjson.SetBytes(item, "type", geminiInteractionsMediaType(mimeType)) + item, _ = sjson.SetBytes(item, "uri", fileURI) + if mimeType != "" { + item, _ = sjson.SetBytes(item, "mime_type", mimeType) + } + return item +} + +// geminiInteractionsMediaType picks the Interactions content type for a MIME type. +func geminiInteractionsMediaType(mimeType string) string { lower := strings.ToLower(mimeType) switch { case strings.HasPrefix(lower, "image/"): - contentType = "image" + return "image" case strings.HasPrefix(lower, "audio/"): - contentType = "audio" + return "audio" case strings.HasPrefix(lower, "video/"): - contentType = "video" + return "video" } - item := []byte(`{"type":"","mime_type":"","data":""}`) - item, _ = sjson.SetBytes(item, "type", contentType) - item, _ = sjson.SetBytes(item, "mime_type", mimeType) - item, _ = sjson.SetBytes(item, "data", data) - return item + return "document" } -func appendInteractionsContentList(items *[][]byte, role string, content gjson.Result) { +func appendInteractionsContentList(ctx *geminiInteractionsInputContext, role string, content gjson.Result) { if !content.Exists() { return } + run := ctx.userRun(role) if content.IsArray() { content.ForEach(func(_, part gjson.Result) bool { - appendInteractionsContentPart(items, role, part) + appendInteractionsContentPart(&ctx.items, role, part, run) return true }) return } if content.IsObject() { - appendInteractionsContentPart(items, role, content) + appendInteractionsContentPart(&ctx.items, role, content, run) } else if content.Type == gjson.String { - appendGeminiTextContent(items, role, content.String()) + ctx.appendText(role, content.String()) } } diff --git a/internal/translator/gemini/interactions/interactions_gemini_instruction_test.go b/internal/translator/gemini/interactions/interactions_gemini_instruction_test.go new file mode 100644 index 00000000000..da9e01b4ac0 --- /dev/null +++ b/internal/translator/gemini/interactions/interactions_gemini_instruction_test.go @@ -0,0 +1,60 @@ +package interactions + +import ( + "strings" + "testing" +) + +// geminiInstructionSteps are developer and system steps in the shapes an +// Interactions client can send. Each one carries the text "note". +var geminiInstructionSteps = map[string]string{ + "developer user_input": `{"type":"user_input","role":"developer","content":[{"type":"text","text":"note"}]}`, + "system user_input": `{"type":"user_input","role":"system","content":[{"type":"text","text":"note"}]}`, + "developer string content": `{"type":"user_input","role":"developer","content":"note"}`, + "bare system object": `{"role":"system","content":"note"}`, + "bare system text": `{"type":"system","text":"note"}`, + "developer native parts": `{"role":"developer","parts":[{"text":"note"}]}`, + "developer wrapper": `{"role":"developer","steps":[{"type":"user_input","content":[{"type":"text","text":"note"}]}]}`, +} + +// geminiEmptiedStep is a user step whose only part Gemini cannot carry. +const geminiEmptiedStep = `{"type":"user_input","content":[{"type":"document","uri":"gs://b/a.pdf"}]}` + +func TestInteractionsToGeminiDeveloperOrSystemStepDoesNotHideAnEmptiedUserTurn(t *testing.T) { + for name, note := range geminiInstructionSteps { + t.Run("after "+name, func(t *testing.T) { + requireInteractionsToGeminiRefusal(t, interactionsToGeminiEnvelope(`{"model":"m","input":[`+interactionsGeminiHistory+`,`+geminiEmptiedStep+`,`+note+`]}`), "document") + }) + t.Run("before "+name, func(t *testing.T) { + requireInteractionsToGeminiRefusal(t, interactionsToGeminiEnvelope(`{"model":"m","input":[`+interactionsGeminiHistory+`,`+note+`,`+geminiEmptiedStep+`]}`), "document") + }) + } +} + +func TestInteractionsToGeminiDeveloperOrSystemStepStillSendsItsText(t *testing.T) { + for name, note := range geminiInstructionSteps { + t.Run(name, func(t *testing.T) { + envelope := interactionsToGeminiEnvelope(`{"model":"m","input":[` + interactionsGeminiHistory + `,{"type":"user_input","content":[{"type":"text","text":"keep me"}]},` + note + `]}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + if !strings.Contains(string(envelope.Body), "note") || !strings.Contains(string(envelope.Body), "keep me") { + t.Fatalf("text was lost: %s", envelope.Body) + } + }) + } +} + +func TestInteractionsToGeminiRealUserTextBesideAnUnrepresentableAttachmentSurvivesAnInstructionStep(t *testing.T) { + for name, note := range geminiInstructionSteps { + t.Run(name, func(t *testing.T) { + envelope := interactionsToGeminiEnvelope(`{"model":"m","input":[` + interactionsGeminiHistory + `,` + note + `,{"type":"user_input","content":[{"type":"text","text":"keep me"},` + `{"type":"document","uri":"gs://b/a.pdf"}` + `]}]}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + if !strings.Contains(string(envelope.Body), "keep me") { + t.Fatalf("text was lost: %s", envelope.Body) + } + }) + } +} diff --git a/internal/translator/gemini/interactions/interactions_gemini_uri_test.go b/internal/translator/gemini/interactions/interactions_gemini_uri_test.go new file mode 100644 index 00000000000..37de80b36b6 --- /dev/null +++ b/internal/translator/gemini/interactions/interactions_gemini_uri_test.go @@ -0,0 +1,156 @@ +package interactions + +import ( + "context" + "errors" + "testing" + + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +const interactionsGeminiHistory = `{"type":"user_input","content":[{"type":"text","text":"a"}]},{"type":"model_output","content":[{"type":"text","text":"b"}]}` + +func interactionsToGeminiEnvelope(input string) sdktranslator.RequestEnvelope { + return sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatInteractions, sdktranslator.FormatGemini, sdktranslator.RequestEnvelope{ + Format: sdktranslator.FormatInteractions, + Model: "m", + Body: []byte(input), + }) +} + +// interactionsFinalTurnToGemini translates two history turns followed by a final +// user step holding the given content parts. +func interactionsFinalTurnToGemini(finalContent string) sdktranslator.RequestEnvelope { + return interactionsToGeminiEnvelope(`{"model":"m","input":[` + interactionsGeminiHistory + `,{"type":"user_input","content":[` + finalContent + `]}]}`) +} + +func requireInteractionsToGeminiRefusal(t *testing.T, envelope sdktranslator.RequestEnvelope, wantType string) { + t.Helper() + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(envelope.Err, &unsupported) || unsupported.Type != wantType || unsupported.StatusCode() != 400 { + t.Fatalf("envelope.Err = %v, want unsupported content part: %s; body = %s", envelope.Err, wantType, envelope.Body) + } + if got, want := envelope.Err.Error(), "unsupported content part: "+wantType; got != want { + t.Fatalf("error text = %q, want %q", got, want) + } + if !gjson.ValidBytes(envelope.Body) { + t.Fatalf("body is not JSON: %q", envelope.Body) + } +} + +func TestGeminiFileDataSurvivesTheRoundTripThroughInteractions(t *testing.T) { + interactions := geminiTurnToInteractions("", `{"fileData":{"mimeType":"image/png","fileUri":"gs://b/a.png"}}`) + if interactions.Err != nil { + t.Fatalf("Gemini to Interactions: %v, body = %s", interactions.Err, interactions.Body) + } + if got := gjson.GetBytes(interactions.Body, "input.2.content.0.uri").String(); got != "gs://b/a.png" { + t.Fatalf("Interactions part = %s", gjson.GetBytes(interactions.Body, "input.2.content.0").Raw) + } + envelope := interactionsToGeminiEnvelope(string(interactions.Body)) + if envelope.Err != nil { + t.Fatalf("Interactions to Gemini: %v, body = %s", envelope.Err, envelope.Body) + } + if got := gjson.GetBytes(envelope.Body, "contents.#").Int(); got != 3 { + t.Fatalf("contents = %d, want 3: %s", got, envelope.Body) + } + fileData := gjson.GetBytes(envelope.Body, "contents.2.parts.0.fileData") + if fileData.Get("fileUri").String() != "gs://b/a.png" || fileData.Get("mimeType").String() != "image/png" { + t.Fatalf("last turn lost the file: %s", envelope.Body) + } +} + +func TestInteractionsToGeminiReadsURIAsFileURI(t *testing.T) { + for _, field := range []string{"uri", "file_uri", "fileUri"} { + t.Run(field, func(t *testing.T) { + envelope := interactionsFinalTurnToGemini(`{"type":"document","mime_type":"application/pdf","` + field + `":"gs://b/a.pdf"}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + fileData := gjson.GetBytes(envelope.Body, "contents.2.parts.0.fileData") + if fileData.Get("fileUri").String() != "gs://b/a.pdf" || fileData.Get("mimeType").String() != "application/pdf" { + t.Fatalf("fileData = %s, body = %s", fileData.Raw, envelope.Body) + } + }) + } +} + +func TestInteractionsToGeminiInlineDataStillConverts(t *testing.T) { + envelope := interactionsFinalTurnToGemini(`{"type":"image","mime_type":"image/png","data":"aGVsbG8="}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + inlineData := gjson.GetBytes(envelope.Body, "contents.2.parts.0.inlineData") + if inlineData.Get("mimeType").String() != "image/png" || inlineData.Get("data").String() != "aGVsbG8=" { + t.Fatalf("inlineData = %s, body = %s", inlineData.Raw, envelope.Body) + } +} + +func TestInteractionsToGeminiUnrepresentableAttachmentOnlyTurnIsRefused(t *testing.T) { + cases := []struct { + name string + content string + wantType string + }{ + {name: "audio without bytes or uri", content: `{"type":"audio","mime_type":"audio/wav"}`, wantType: "audio"}, + {name: "image without anything", content: `{"type":"image"}`, wantType: "image"}, + {name: "uri without a mime type", content: `{"type":"document","uri":"gs://b/a.pdf"}`, wantType: "document"}, + {name: "image_url that is not a data url", content: `{"type":"image_url","image_url":{"url":"https://example.test/a.png"}}`, wantType: "image_url"}, + {name: "empty text does not hide it", content: `{"type":"text","text":""},{"type":"video","mime_type":"video/mp4"}`, wantType: "video"}, + {name: "whitespace text does not hide it", content: `{"type":"text","text":" \n"},{"type":"audio","mime_type":"audio/wav"}`, wantType: "audio"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + requireInteractionsToGeminiRefusal(t, interactionsFinalTurnToGemini(tc.content), tc.wantType) + }) + } +} + +func TestInteractionsToGeminiUnrepresentableNativePartIsRefused(t *testing.T) { + envelope := interactionsToGeminiEnvelope(`{"model":"m","input":[` + interactionsGeminiHistory + `,{"role":"user","parts":[{"fileData":{"mimeType":"image/png"}}]}]}`) + requireInteractionsToGeminiRefusal(t, envelope, "fileData") +} + +func TestInteractionsToGeminiRefusesAnEmptiedTurnBeforeALaterTextTurn(t *testing.T) { + envelope := interactionsToGeminiEnvelope(`{"model":"m","input":[{"type":"user_input","content":[{"type":"audio","mime_type":"audio/wav"}]},{"type":"model_output","content":[{"type":"text","text":"ok"}]},{"type":"user_input","content":[{"type":"text","text":"next"}]}]}`) + requireInteractionsToGeminiRefusal(t, envelope, "audio") +} + +func TestInteractionsToGeminiUnrepresentableAttachmentBesideTextStillSucceeds(t *testing.T) { + envelope := interactionsFinalTurnToGemini(`{"type":"text","text":"keep me"},{"type":"audio","mime_type":"audio/wav"}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + if got := gjson.GetBytes(envelope.Body, "contents.2.parts.0.text").String(); got != "keep me" { + t.Fatalf("text was lost: %s", envelope.Body) + } + if got := gjson.GetBytes(envelope.Body, "contents.2.parts.#").Int(); got != 1 { + t.Fatalf("last turn has %d parts, want 1: %s", got, envelope.Body) + } +} + +func TestInteractionsToGeminiNeighbouringStepKeepsTheTurnAlive(t *testing.T) { + cases := map[string]string{ + "text step": `{"type":"user_input","content":[{"type":"text","text":"keep me"}]},{"type":"user_input","content":[{"type":"audio","mime_type":"audio/wav"}]}`, + "tool result": `{"type":"function_call","name":"f","call_id":"c1","arguments":{}},{"type":"function_result","name":"f","call_id":"c1","result":{"ok":true}},{"type":"user_input","content":[{"type":"audio","mime_type":"audio/wav"}]}`, + "string step": `"keep me",{"type":"user_input","content":[{"type":"audio","mime_type":"audio/wav"}]}`, + "native step": `{"role":"user","parts":[{"text":"keep me"}]},{"type":"user_input","content":[{"type":"audio","mime_type":"audio/wav"}]}`, + "turn of steps": `{"role":"user","steps":[{"type":"user_input","content":[{"type":"text","text":"keep me"}]},{"type":"user_input","content":[{"type":"audio","mime_type":"audio/wav"}]}]}`, + } + for name, steps := range cases { + t.Run(name, func(t *testing.T) { + envelope := interactionsToGeminiEnvelope(`{"model":"m","input":[` + interactionsGeminiHistory + `,` + steps + `]}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + }) + } +} + +func TestInteractionsToGeminiExportedWrapperKeepsAJSONBody(t *testing.T) { + input := []byte(`{"model":"m","input":[` + interactionsGeminiHistory + `,{"type":"user_input","content":[{"type":"audio","mime_type":"audio/wav"}]}]}`) + if body := ConvertInteractionsRequestToGemini("m", input, false); !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } +} diff --git a/internal/translator/gemini/interactions/interactions_gemini_user_turn_test.go b/internal/translator/gemini/interactions/interactions_gemini_user_turn_test.go new file mode 100644 index 00000000000..92831e329b8 --- /dev/null +++ b/internal/translator/gemini/interactions/interactions_gemini_user_turn_test.go @@ -0,0 +1,168 @@ +package interactions + +import ( + "context" + "errors" + "testing" + + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +// geminiTurnToInteractions translates two history turns followed by a final user +// turn holding the given parts. extra is spliced into the request root. +func geminiTurnToInteractions(extra, finalParts string) sdktranslator.RequestEnvelope { + input := `{"model":"m",` + extra + `"contents":[{"role":"user","parts":[{"text":"a"}]},{"role":"model","parts":[{"text":"b"}]},{"role":"user","parts":[` + finalParts + `]}]}` + return sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatGemini, sdktranslator.FormatInteractions, sdktranslator.RequestEnvelope{ + Format: sdktranslator.FormatGemini, + Model: "m", + Body: []byte(input), + }) +} + +func requireFileDataRefusal(t *testing.T, envelope sdktranslator.RequestEnvelope) { + t.Helper() + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(envelope.Err, &unsupported) || unsupported.Type != "fileData" || unsupported.StatusCode() != 400 { + t.Fatalf("envelope.Err = %v, want unsupported content part: fileData; body = %s", envelope.Err, envelope.Body) + } + if got, want := envelope.Err.Error(), "unsupported content part: fileData"; got != want { + t.Fatalf("error text = %q, want %q", got, want) + } + if !gjson.ValidBytes(envelope.Body) { + t.Fatalf("body is not JSON: %q", envelope.Body) + } +} + +func TestGeminiToInteractionsFileDataOnlyTurnKeepsTheFile(t *testing.T) { + cases := []struct { + name string + part string + wantType string + wantURI string + wantMIME string + }{ + { + name: "camel case pdf", + part: `{"fileData":{"mimeType":"application/pdf","fileUri":"gs://bucket/doc.pdf"}}`, + wantType: "document", + wantURI: "gs://bucket/doc.pdf", + wantMIME: "application/pdf", + }, + { + name: "snake case video", + part: `{"file_data":{"mime_type":"video/mp4","file_uri":"https://example.test/a.mp4"}}`, + wantType: "video", + wantURI: "https://example.test/a.mp4", + wantMIME: "video/mp4", + }, + { + name: "image", + part: `{"fileData":{"mimeType":"image/png","fileUri":"https://example.test/a.png"}}`, + wantType: "image", + wantURI: "https://example.test/a.png", + wantMIME: "image/png", + }, + { + name: "without a mime type", + part: `{"fileData":{"fileUri":"https://example.test/a"}}`, + wantType: "document", + wantURI: "https://example.test/a", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + envelope := geminiTurnToInteractions("", tc.part) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + if got := gjson.GetBytes(envelope.Body, "input.#").Int(); got != 3 { + t.Fatalf("input has %d steps, want 3: %s", got, envelope.Body) + } + part := gjson.GetBytes(envelope.Body, "input.2.content.0") + if part.Get("type").String() != tc.wantType || part.Get("uri").String() != tc.wantURI || part.Get("mime_type").String() != tc.wantMIME { + t.Fatalf("part = %s, body = %s", part.Raw, envelope.Body) + } + }) + } +} + +func TestGeminiToInteractionsFileDataWithoutURIIsRefused(t *testing.T) { + cases := map[string]struct { + extra string + parts string + }{ + "history then file only": { + parts: `{"fileData":{"mimeType":"application/pdf"}}`, + }, + "snake case spelling": { + parts: `{"file_data":{"mime_type":"application/pdf","file_uri":""}}`, + }, + "system instruction does not hide it": { + extra: `"systemInstruction":{"parts":[{"text":"be brief"}]},`, + parts: `{"fileData":{"mimeType":"application/pdf"}}`, + }, + "empty text does not hide it": { + parts: `{"text":""},{"fileData":{"mimeType":"application/pdf"}}`, + }, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + requireFileDataRefusal(t, geminiTurnToInteractions(tc.extra, tc.parts)) + }) + } +} + +func TestGeminiToInteractionsRefusesAnEmptiedTurnBeforeALaterTextTurn(t *testing.T) { + input := `{"model":"m","contents":[{"role":"user","parts":[{"fileData":{"mimeType":"application/pdf"}}]},{"role":"model","parts":[{"text":"ok"}]},{"role":"user","parts":[{"text":"next"}]}]}` + envelope := sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatGemini, sdktranslator.FormatInteractions, sdktranslator.RequestEnvelope{ + Format: sdktranslator.FormatGemini, + Model: "m", + Body: []byte(input), + }) + requireFileDataRefusal(t, envelope) +} + +func TestGeminiToInteractionsFileDataWithoutURIBesideTextStillSucceeds(t *testing.T) { + envelope := geminiTurnToInteractions("", `{"text":"keep me"},{"fileData":{"mimeType":"application/pdf"}}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + if got := gjson.GetBytes(envelope.Body, "input.2.content.0.text").String(); got != "keep me" { + t.Fatalf("text was lost: %s", envelope.Body) + } + if got := gjson.GetBytes(envelope.Body, "input.#").Int(); got != 3 { + t.Fatalf("input has %d steps, want 3: %s", got, envelope.Body) + } +} + +func TestGeminiToInteractionsInlineDataOnlyTurnStillConverts(t *testing.T) { + envelope := geminiTurnToInteractions("", `{"inlineData":{"mimeType":"application/pdf","data":"JVBERi0xLjQK"}}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + part := gjson.GetBytes(envelope.Body, "input.2.content.0") + if part.Get("type").String() != "document" || part.Get("mime_type").String() != "application/pdf" || part.Get("data").String() != "JVBERi0xLjQK" { + t.Fatalf("part = %s, body = %s", part.Raw, envelope.Body) + } +} + +func TestGeminiToInteractionsModelFileDataWithoutURIIsNotARefusal(t *testing.T) { + input := `{"model":"m","contents":[{"role":"user","parts":[{"text":"a"}]},{"role":"model","parts":[{"fileData":{"mimeType":"application/pdf"}}]},{"role":"user","parts":[{"text":"b"}]}]}` + envelope := sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatGemini, sdktranslator.FormatInteractions, sdktranslator.RequestEnvelope{ + Format: sdktranslator.FormatGemini, + Model: "m", + Body: []byte(input), + }) + if envelope.Err != nil { + t.Fatalf("only user turns are refused, envelope.Err = %v", envelope.Err) + } +} + +func TestGeminiToInteractionsExportedWrapperKeepsAJSONBody(t *testing.T) { + input := []byte(`{"model":"m","contents":[{"role":"user","parts":[{"fileData":{"mimeType":"application/pdf"}}]}]}`) + if body := ConvertGeminiRequestToInteractions("m", input, false); !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } +} diff --git a/internal/translator/gemini/openai/chat-completions/gemini_openai_media_url_test.go b/internal/translator/gemini/openai/chat-completions/gemini_openai_media_url_test.go new file mode 100644 index 00000000000..1773f167d9a --- /dev/null +++ b/internal/translator/gemini/openai/chat-completions/gemini_openai_media_url_test.go @@ -0,0 +1,92 @@ +package chat_completions + +import ( + "context" + "errors" + "testing" + + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +const ( + mediaImageURL = `{"type":"image_url","image_url":{"url":"https://x.test/a.png"}}` + mediaImageData = `{"type":"image_url","image_url":{"url":"data:image/png;base64,iVBORw0KGgo="}}` + mediaVideoURL = `{"type":"video_url","video_url":{"url":"https://x.test/a.mp4"}}` + mediaAudioNone = `{"type":"input_audio","input_audio":{"data":"","format":"wav"}}` +) + +func mediaTurn(parts string) []byte { + return []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[` + parts + `]}]}`) +} + +func TestConvertOpenAIRequestToGemini_RefusesAnAttachmentOnlyTurnItCannotSend(t *testing.T) { + cases := []struct { + name string + parts string + wantType string + }{ + {name: "http image_url", parts: mediaImageURL, wantType: "image_url"}, + {name: "image_url without a base64 payload", parts: `{"type":"image_url","image_url":{"url":"data:image/png,raw"}}`, wantType: "image_url"}, + {name: "image_url as a bare string", parts: `{"type":"image_url","image_url":"https://x.test/a.png"}`, wantType: "image_url"}, + {name: "http video_url", parts: mediaVideoURL, wantType: "video_url"}, + {name: "input_audio without bytes", parts: mediaAudioNone, wantType: "input_audio"}, + {name: "whitespace text beside http image_url", parts: `{"type":"text","text":" "},` + mediaImageURL, wantType: "image_url"}, + {name: "first dropped type is reported", parts: mediaVideoURL + `,` + mediaImageURL, wantType: "video_url"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + body, err := convertOpenAIRequestToGemini("m", mediaTurn(tc.parts), false) + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(err, &unsupported) || unsupported.Type != tc.wantType || unsupported.StatusCode() != 400 { + t.Fatalf("err = %v, want unsupported content part: %s; body = %s", err, tc.wantType, body) + } + }) + } +} + +func TestConvertOpenAIRequestToGemini_RealTextBesideAnUnsendableAttachmentStillSucceeds(t *testing.T) { + for _, parts := range []string{ + userTurnText + `,` + mediaImageURL, + mediaImageURL + `,` + userTurnText, + `{"type":"text","text":" "},` + userTurnText + `,` + mediaVideoURL + `,` + mediaAudioNone, + } { + body, err := convertOpenAIRequestToGemini("m", mediaTurn(parts), false) + if err != nil { + t.Fatalf("parts %s: err = %v, body = %s", parts, err, body) + } + found := false + for _, part := range gjson.GetBytes(body, "contents.2.parts").Array() { + if part.Get("text").String() == "keep me" { + found = true + } + } + if !found { + t.Fatalf("parts %s: text was lost: %s", parts, body) + } + } +} + +func TestConvertOpenAIRequestToGemini_DataURLImageStillConverts(t *testing.T) { + body, err := convertOpenAIRequestToGemini("m", mediaTurn(mediaImageData), false) + if err != nil { + t.Fatalf("err = %v, body = %s", err, body) + } + part := gjson.GetBytes(body, "contents.2.parts.0.inlineData") + if part.Get("mime_type").String() != "image/png" || part.Get("data").String() != "iVBORw0KGgo=" { + t.Fatalf("data URL image was not inlined: %s", body) + } +} + +func TestOpenAIToGeminiRegistryCarriesTheImageURLRefusal(t *testing.T) { + envelope := sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatOpenAI, sdktranslator.FormatGemini, sdktranslator.RequestEnvelope{ + Format: sdktranslator.FormatOpenAI, + Model: "m", + Body: mediaTurn(mediaImageURL), + }) + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(envelope.Err, &unsupported) || unsupported.Type != "image_url" { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } +} diff --git a/internal/translator/gemini/openai/chat-completions/gemini_openai_request.go b/internal/translator/gemini/openai/chat-completions/gemini_openai_request.go index 58b87d545b9..211df47a18e 100644 --- a/internal/translator/gemini/openai/chat-completions/gemini_openai_request.go +++ b/internal/translator/gemini/openai/chat-completions/gemini_openai_request.go @@ -35,7 +35,7 @@ func ConvertOpenAIRequestToGemini(modelName string, inputRawJSON []byte, stream // when nothing else was left to send. func convertOpenAIRequestToGemini(modelName string, inputRawJSON []byte, _ bool) ([]byte, error) { rawJSON := inputRawJSON - var droppedAttachment string + var drops translatorcommon.UserTurnDrops // Base envelope (no default thinkingConfig) out := []byte(`{"contents":[]}`) @@ -160,20 +160,17 @@ func convertOpenAIRequestToGemini(modelName string, inputRawJSON []byte, _ bool) partItems = append(partItems, geminiTextPart(geminiDemotedSystemText(text, isDemotedSystem))) } case "image_url": - imageURL := item.Get("image_url.url").String() - if len(imageURL) > 5 { - pieces := strings.SplitN(imageURL[5:], ";", 2) - if len(pieces) == 2 && len(pieces[1]) > 7 { - partItems = append(partItems, geminiInlineDataPart(pieces[0], pieces[1][7:], "")) - } + // Only a base64 data URL can be inlined; a remote URL has no equivalent here. + if mimeType, data, ok := translatorcommon.NormalizeOpenAIFileData("", "", item.Get("image_url.url").String()); ok { + partItems = append(partItems, geminiInlineDataPart(mimeType, data, "")) + } else { + drops.Drop("image_url") } case "video_url": - videoURL := item.Get("video_url.url").String() - if len(videoURL) > 5 { - pieces := strings.SplitN(videoURL[5:], ";", 2) - if len(pieces) == 2 && len(pieces[1]) > 7 { - partItems = append(partItems, geminiInlineDataPart(pieces[0], pieces[1][7:], "")) - } + if mimeType, data, ok := translatorcommon.NormalizeOpenAIFileData("", "", item.Get("video_url.url").String()); ok { + partItems = append(partItems, geminiInlineDataPart(mimeType, data, "")) + } else { + drops.Drop("video_url") } case "file": filename := item.Get("file.filename").String() @@ -182,17 +179,21 @@ func convertOpenAIRequestToGemini(modelName string, inputRawJSON []byte, _ bool) partItems = append(partItems, geminiInlineDataPart(mimeType, data, "")) } else { log.Warn("Invalid file data or unknown file name extension in user message, skip") - droppedAttachment = "file" + drops.Drop("file") } case "input_audio": audioData := item.Get("input_audio.data").String() if audioData != "" { mimeType := openAIInputAudioMimeType(item.Get("input_audio.format").String()) partItems = append(partItems, geminiInlineDataPart(mimeType, audioData, "")) + } else { + drops.Drop("input_audio") } } } } + // Whitespace-only text is forwarded but never keeps an emptied turn alive. + drops.EndTurn(translatorcommon.CountSendableGeminiParts(partItems)) if len(partItems) > 0 { contentItems = append(contentItems, geminiContentNode("user", partItems)) } @@ -546,7 +547,7 @@ func convertOpenAIRequestToGemini(modelName string, inputRawJSON []byte, _ bool) out = common.AttachDefaultSafetySettings(out, "safetySettings") - return out, translatorcommon.ErrIfNothingLeft(droppedAttachment, int(gjson.GetBytes(out, "contents.#").Int())) + return out, drops.Err() } func geminiTextPart(text string) []byte { diff --git a/internal/translator/gemini/openai/chat-completions/gemini_openai_user_turn_test.go b/internal/translator/gemini/openai/chat-completions/gemini_openai_user_turn_test.go new file mode 100644 index 00000000000..f92dd1953ee --- /dev/null +++ b/internal/translator/gemini/openai/chat-completions/gemini_openai_user_turn_test.go @@ -0,0 +1,76 @@ +package chat_completions + +import ( + "errors" + "testing" + + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + "github.com/tidwall/gjson" +) + +const ( + userTurnFileID = `{"type":"file","file":{"file_id":"file-absent"}}` + userTurnText = `{"type":"text","text":"keep me"}` + userTurnInline = `{"type":"file","file":{"filename":"a.pdf","file_data":"data:application/pdf;base64,JVBERi0xLjQK"}}` +) + +func TestConvertOpenAIRequestToGemini_RefusesAnyEmptiedUserTurn(t *testing.T) { + cases := []struct { + name string + input string + wantType string + }{ + { + name: "history then file id only", + input: `{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[` + userTurnFileID + `]}]}`, + wantType: "file", + }, + { + name: "system and developer prompts do not hide the empty turn", + input: `{"model":"m","messages":[{"role":"system","content":"sys"},{"role":"developer","content":"dev"},{"role":"user","content":[` + userTurnFileID + `]}]}`, + wantType: "file", + }, + { + name: "emptied turn before a later text turn", + input: `{"model":"m","messages":[{"role":"user","content":[` + userTurnFileID + `]},{"role":"assistant","content":"ok"},{"role":"user","content":"next"}]}`, + wantType: "file", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + body, err := convertOpenAIRequestToGemini("m", []byte(tc.input), false) + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(err, &unsupported) || unsupported.Type != tc.wantType || unsupported.StatusCode() != 400 { + t.Fatalf("err = %v, want unsupported content part: %s; body = %s", err, tc.wantType, body) + } + if got, want := err.Error(), "unsupported content part: "+tc.wantType; got != want { + t.Fatalf("error text = %q, want %q", got, want) + } + if !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } + }) + } +} + +func TestConvertOpenAIRequestToGemini_KeepsTurnWithTextBesideAttachment(t *testing.T) { + input := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[` + userTurnText + `,` + userTurnFileID + `]}]}`) + body, err := convertOpenAIRequestToGemini("m", input, false) + if err != nil { + t.Fatalf("err = %v", err) + } + if got := gjson.GetBytes(body, "contents.2.parts.0.text").String(); got != "keep me" { + t.Fatalf("text was lost: %s", body) + } +} + +func TestConvertOpenAIRequestToGemini_InlineFileAfterHistoryStaysInlineData(t *testing.T) { + input := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[` + userTurnInline + `]}]}`) + body, err := convertOpenAIRequestToGemini("m", input, false) + if err != nil { + t.Fatalf("err = %v", err) + } + if got := gjson.GetBytes(body, "contents.2.parts.0.inlineData.mime_type").String(); got != "application/pdf" { + t.Fatalf("inline file was not kept: %s", body) + } +} diff --git a/internal/translator/gemini/openai/responses/gemini_openai-responses_request.go b/internal/translator/gemini/openai/responses/gemini_openai-responses_request.go index b52561bd4a7..8940252b9e4 100644 --- a/internal/translator/gemini/openai/responses/gemini_openai-responses_request.go +++ b/internal/translator/gemini/openai/responses/gemini_openai-responses_request.go @@ -19,7 +19,20 @@ import ( const geminiResponsesThoughtSignature = "skip_thought_signature_validator" func ConvertOpenAIResponsesRequestToGemini(modelName string, inputRawJSON []byte, stream bool) []byte { + body, _ := convertOpenAIResponsesRequestToGemini(modelName, inputRawJSON, stream) + return body +} + +// ConvertOpenAIResponsesRequestToGeminiReturningError also reports an attachment +// Gemini cannot receive, such as a bare file id, when it leaves a user turn with +// nothing to send. +func ConvertOpenAIResponsesRequestToGeminiReturningError(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { + return convertOpenAIResponsesRequestToGemini(modelName, inputRawJSON, stream) +} + +func convertOpenAIResponsesRequestToGemini(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { rawJSON := inputRawJSON + var drops translatorcommon.UserTurnDrops // Note: stream parameter is part of the fixed method signature useGeminiNativeReasoningLayout := sigcompat.SignatureProviderFromModelName(modelName) == sigcompat.SignatureProviderGemini @@ -230,6 +243,8 @@ func ConvertOpenAIResponsesRequestToGemini(modelName string, inputRawJSON []byte if len(partsToProcess) > 0 { currentRole := "" currentParts := make([][]byte, 0) + // Counts the user parts this item really sends; an empty text part does not. + userSendable := 0 flush := func() { if currentRole == "" || len(currentParts) == 0 { @@ -271,24 +286,35 @@ func ConvertOpenAIResponsesRequestToGemini(modelName string, inputRawJSON []byte } var partJSON []byte + sendsContent := false switch contentType { case "input_text", "output_text", "text": if text := contentItem.Get("text"); text.Exists() { partJSON = []byte(`{"text":""}`) partJSON, _ = sjson.SetBytes(partJSON, "text", text.String()) + sendsContent = text.String() != "" } default: if part, ok := openAIResponsesPartFromBlock(contentItem); ok { partJSON = part + sendsContent = true + } else if effRole == "user" && isResponsesAttachmentPartType(contentType) { + // Gemini has no field for a bare file id and no way to fetch + // the bytes, so the attachment cannot be sent. + drops.Drop(contentType) } } if len(partJSON) > 0 { currentParts = append(currentParts, partJSON) } + if sendsContent && effRole == "user" { + userSendable++ + } } flush() + drops.EndTurn(userSendable) } else if contentArray.Type == gjson.String { effRole := "user" if itemRole != "" { @@ -504,7 +530,7 @@ func ConvertOpenAIResponsesRequestToGemini(modelName string, inputRawJSON []byte if useGeminiNativeReasoningLayout { result = sigcompat.SanitizeGeminiRequestThoughtSignatures(result, "contents") } - return stripTrailingOpenAIResponsesModelPrefill(result) + return stripTrailingOpenAIResponsesModelPrefill(result), drops.Err() } func geminiContent(role string, parts [][]byte) []byte { @@ -959,6 +985,20 @@ func isResponsesContentPartType(itemType string) bool { } } +// isResponsesAttachmentPartType reports the content part types that carry a +// file, image, audio or video rather than text. +func isResponsesAttachmentPartType(itemType string) bool { + switch strings.ToLower(strings.TrimSpace(itemType)) { + case "input_image", "image_url", "image", + "input_audio", "audio", + "input_video", "video_url", "video", + "input_file", "file": + return true + default: + return false + } +} + func openAIResponsesAudioMimeType(audioFormat string) string { audioFormat = strings.TrimSpace(audioFormat) if isGenericMIME(audioFormat) { diff --git a/internal/translator/gemini/openai/responses/gemini_openai-responses_user_turn_test.go b/internal/translator/gemini/openai/responses/gemini_openai-responses_user_turn_test.go new file mode 100644 index 00000000000..e702146363b --- /dev/null +++ b/internal/translator/gemini/openai/responses/gemini_openai-responses_user_turn_test.go @@ -0,0 +1,126 @@ +package responses + +import ( + "context" + "errors" + "strings" + "testing" + + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +const ( + geminiTurnHello = `{"type":"message","role":"user","content":[{"type":"input_text","text":"hello"}]}` + geminiTurnAssistant = `{"type":"message","role":"assistant","content":[{"type":"output_text","text":"hi"}]}` + geminiTurnNext = `{"type":"message","role":"user","content":[{"type":"input_text","text":"next"}]}` + geminiTurnDeveloper = `{"type":"message","role":"developer","content":[{"type":"input_text","text":"dev"}]}` + geminiTurnFileID = `{"type":"input_file","file_id":"file-1"}` + geminiTurnFileData = `{"type":"input_file","filename":"a.pdf","file_data":"data:application/pdf;base64,JVBERi0xLjQK"}` + geminiTurnFileURL = `{"type":"input_file","file_url":"https://example.test/a.pdf","filename":"a.pdf"}` + geminiTurnText = `{"type":"input_text","text":"keep me"}` + geminiTurnEmptyText = `{"type":"input_text","text":""}` +) + +func geminiUserTurn(parts ...string) string { + return `{"type":"message","role":"user","content":[` + strings.Join(parts, ",") + `]}` +} + +func geminiTurnPayload(instructions string, items ...string) []byte { + prefix := `{"model":"gemini-3-pro",` + if instructions != "" { + prefix += `"instructions":"` + instructions + `",` + } + return []byte(prefix + `"input":[` + strings.Join(items, ",") + `]}`) +} + +func TestConvertOpenAIResponsesRequestToGemini_RefusesAnyEmptiedUserTurn(t *testing.T) { + cases := []struct { + name string + input []byte + }{ + { + name: "file id only", + input: geminiTurnPayload("", geminiUserTurn(geminiTurnFileID)), + }, + { + name: "history then file id only", + input: geminiTurnPayload("", geminiTurnHello, geminiTurnAssistant, geminiUserTurn(geminiTurnFileID)), + }, + { + name: "instructions and developer prompt do not hide the empty turn", + input: geminiTurnPayload("sys", geminiTurnDeveloper, geminiUserTurn(geminiTurnFileID)), + }, + { + name: "emptied turn before a later text turn", + input: geminiTurnPayload("", geminiUserTurn(geminiTurnFileID), geminiTurnAssistant, geminiTurnNext), + }, + { + name: "empty text beside the file id does not count as sendable", + input: geminiTurnPayload("", geminiTurnHello, geminiTurnAssistant, geminiUserTurn(geminiTurnEmptyText, geminiTurnFileID)), + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + body, err := ConvertOpenAIResponsesRequestToGeminiReturningError("gemini-3-pro", tc.input, false) + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(err, &unsupported) || unsupported.Type != "input_file" || unsupported.StatusCode() != 400 { + t.Fatalf("err = %v, want unsupported content part: input_file; body = %s", err, body) + } + if got, want := err.Error(), "unsupported content part: input_file"; got != want { + t.Fatalf("error text = %q, want %q", got, want) + } + if !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } + + envelope := sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatOpenAIResponse, sdktranslator.FormatGemini, + sdktranslator.RequestEnvelope{Format: sdktranslator.FormatOpenAIResponse, Model: "gemini-3-pro", Body: tc.input}) + if !errors.As(envelope.Err, &unsupported) || unsupported.Type != "input_file" { + t.Fatalf("registry err = %v, want unsupported content part: input_file", envelope.Err) + } + }) + } +} + +func TestConvertOpenAIResponsesRequestToGemini_KeepsTurnWithTextBesideFileID(t *testing.T) { + input := geminiTurnPayload("", geminiTurnHello, geminiTurnAssistant, geminiUserTurn(geminiTurnText, geminiTurnFileID)) + body, err := ConvertOpenAIResponsesRequestToGeminiReturningError("gemini-3-pro", input, false) + if err != nil { + t.Fatalf("err = %v", err) + } + if got := gjson.GetBytes(body, "contents.2.parts.0.text").String(); got != "keep me" { + t.Fatalf("text was lost: %s", body) + } +} + +func TestConvertOpenAIResponsesRequestToGemini_InlineAndRemoteFilesStayParts(t *testing.T) { + cases := map[string]struct { + part string + path string + want string + }{ + "inline bytes": {part: geminiTurnFileData, path: "contents.2.parts.0.inline_data.mime_type", want: "application/pdf"}, + "remote url": {part: geminiTurnFileURL, path: "contents.2.parts.0.file_data.file_uri", want: "https://example.test/a.pdf"}, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + input := geminiTurnPayload("", geminiTurnHello, geminiTurnAssistant, geminiUserTurn(tc.part)) + body, err := ConvertOpenAIResponsesRequestToGeminiReturningError("gemini-3-pro", input, false) + if err != nil { + t.Fatalf("err = %v", err) + } + if got := gjson.GetBytes(body, tc.path).String(); got != tc.want { + t.Fatalf("%s = %q, want %q; body = %s", tc.path, got, tc.want, body) + } + }) + } +} + +func TestConvertOpenAIResponsesRequestToGemini_ExportedWrapperKeepsAJSONBody(t *testing.T) { + input := geminiTurnPayload("", geminiUserTurn(geminiTurnFileID)) + if body := ConvertOpenAIResponsesRequestToGemini("gemini-3-pro", input, false); !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } +} diff --git a/internal/translator/gemini/openai/responses/init.go b/internal/translator/gemini/openai/responses/init.go index 5917810fb01..062494550c0 100644 --- a/internal/translator/gemini/openai/responses/init.go +++ b/internal/translator/gemini/openai/responses/init.go @@ -4,16 +4,18 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( OpenaiResponse, Gemini, - ConvertOpenAIResponsesRequestToGemini, + nil, interfaces.TranslateResponse{ Stream: ConvertGeminiResponseToOpenAIResponses, NonStream: ConvertGeminiResponseToOpenAIResponsesNonStream, }, ) + sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatOpenAIResponse, sdktranslator.FormatGemini, convertOpenAIResponsesRequestToGemini) } diff --git a/internal/translator/interactions/claude/interactions_claude_request.go b/internal/translator/interactions/claude/interactions_claude_request.go index e570a257b56..9fa81344dc8 100644 --- a/internal/translator/interactions/claude/interactions_claude_request.go +++ b/internal/translator/interactions/claude/interactions_claude_request.go @@ -34,9 +34,9 @@ func convertClaudeRequestToInteractions(modelName string, inputRawJSON []byte, s } out = copyClaudeSystemToInteractions(out, root) out = copyClaudeGenerationConfigToInteractions(out, root) - out, droppedAttachment := appendClaudeMessagesToInteractions(out, root.Get("messages"), preserveEmptyThinkingBlocks) + out, errDrops := appendClaudeMessagesToInteractions(out, root.Get("messages"), preserveEmptyThinkingBlocks) out = copyClaudeToolsToInteractions(out, root) - return out, translatorcommon.ErrIfNothingLeft(droppedAttachment, int(gjson.GetBytes(out, "input.#").Int())) + return out, errDrops } func claudeRequestStreamValue(root gjson.Result, stream bool) (bool, bool) { @@ -129,11 +129,11 @@ func copyClaudeToolChoiceToInteractions(out []byte, toolChoice gjson.Result) []b return out } -func appendClaudeMessagesToInteractions(out []byte, messages gjson.Result, preserveEmptyThinkingBlocks bool) ([]byte, string) { +func appendClaudeMessagesToInteractions(out []byte, messages gjson.Result, preserveEmptyThinkingBlocks bool) ([]byte, error) { if !messages.Exists() || !messages.IsArray() { - return out, "" + return out, nil } - droppedAttachment := "" + var drops translatorcommon.UserTurnDrops inputItems := translatorcommon.NewRawArrayItems(messages.Get("#").Int()) var pendingToolUseIDs []string var pendingSystemReminders [][]byte @@ -160,7 +160,10 @@ func appendClaudeMessagesToInteractions(out []byte, messages gjson.Result, prese } pendingToolUseIDs = nil - appendClaudeMessageToInteractions(&inputItems, &pendingToolUseIDs, &pendingSystemReminders, toolNamesByID, role, content, preserveEmptyThinkingBlocks, &droppedAttachment) + sendable := appendClaudeMessageToInteractions(&inputItems, &pendingToolUseIDs, &pendingSystemReminders, toolNamesByID, role, content, preserveEmptyThinkingBlocks, &drops) + if role == "user" { + drops.EndTurn(sendable) + } if len(pendingSystemReminders) > 0 { inputItems = append(inputItems, pendingSystemReminders...) pendingSystemReminders = nil @@ -171,10 +174,10 @@ func appendClaudeMessagesToInteractions(out []byte, messages gjson.Result, prese inputItems = append(inputItems, pendingSystemReminders...) } out = translatorcommon.SetRawArrayItems(out, "input", inputItems) - return out, droppedAttachment + return out, drops.Err() } -func appendClaudeMessageToInteractions(items *[][]byte, pendingToolUseIDs *[]string, pendingSystemReminders *[][]byte, toolNamesByID map[string]string, role string, content gjson.Result, preserveEmptyThinkingBlocks bool, droppedAttachment *string) { +func appendClaudeMessageToInteractions(items *[][]byte, pendingToolUseIDs *[]string, pendingSystemReminders *[][]byte, toolNamesByID map[string]string, role string, content gjson.Result, preserveEmptyThinkingBlocks bool, drops *translatorcommon.UserTurnDrops) int { defaultStepType := "user_input" if role == "assistant" { defaultStepType = "model_output" @@ -188,11 +191,14 @@ func appendClaudeMessageToInteractions(items *[][]byte, pendingToolUseIDs *[]str step, _ = sjson.SetBytes(step, "type", defaultStepType) step, _ = sjson.SetBytes(step, "content.0.text", content.String()) *items = append(*items, step) - return + return 1 } if !content.IsArray() { - return + return 0 } + // Counts only what this turn itself sends, not system reminders flushed beside it. + // Whitespace-only text is forwarded but never keeps an emptied turn alive. + sendable := 0 stepContent := make([][]byte, 0, 4) flushContent := func() { if len(stepContent) == 0 { @@ -217,6 +223,9 @@ func appendClaudeMessageToInteractions(items *[][]byte, pendingToolUseIDs *[]str contentPart := []byte(`{"type":"text","text":""}`) contentPart, _ = sjson.SetBytes(contentPart, "text", text) stepContent = append(stepContent, contentPart) + if strings.TrimSpace(text) != "" { + sendable++ + } } case "thinking": flushContent() @@ -225,6 +234,7 @@ func appendClaudeMessageToInteractions(items *[][]byte, pendingToolUseIDs *[]str step := []byte(`{"type":"thought","content":[{"type":"text","text":""}]}`) step, _ = sjson.SetBytes(step, "content.0.text", text) *items = append(*items, step) + sendable++ } case "image", "document", "container_upload": if mediaPart, ok := claudeMediaPartToInteractions(part, partType); ok { @@ -234,8 +244,9 @@ func appendClaudeMessageToInteractions(items *[][]byte, pendingToolUseIDs *[]str *pendingSystemReminders = nil } stepContent = append(stepContent, mediaPart) - } else if droppedAttachment != nil { - *droppedAttachment = partType + sendable++ + } else if drops != nil && role == "user" { + drops.Drop(partType) } case "tool_use": flushContent() @@ -250,13 +261,16 @@ func appendClaudeMessageToInteractions(items *[][]byte, pendingToolUseIDs *[]str } } *items = append(*items, claudeToolUseToInteractions(part)) + sendable++ case "tool_result": flushContent() *items = append(*items, claudeToolResultToInteractions(part, toolNamesByID)) + sendable++ } return true }) flushContent() + return sendable } func claudeMediaPartToInteractions(part gjson.Result, partType string) ([]byte, bool) { diff --git a/internal/translator/interactions/claude/interactions_claude_user_turn_test.go b/internal/translator/interactions/claude/interactions_claude_user_turn_test.go new file mode 100644 index 00000000000..c42ec878342 --- /dev/null +++ b/internal/translator/interactions/claude/interactions_claude_user_turn_test.go @@ -0,0 +1,133 @@ +package claude + +import ( + "context" + "errors" + "testing" + + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +const userTurnUpload = `{"type":"container_upload","file_id":"file-1"}` + +func TestConvertClaudeRequestToInteractions_RefusesAnyEmptiedUserTurn(t *testing.T) { + cases := []struct { + name string + input string + wantType string + }{ + { + name: "history then attachment only", + input: `{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":[{"type":"text","text":"hi"}]},{"role":"user","content":[` + userTurnUpload + `]}]}`, + wantType: "container_upload", + }, + { + name: "system prompt and system reminder", + input: `{"model":"m","system":"sys","messages":[{"role":"system","content":"reminder"},{"role":"user","content":[` + userTurnUpload + `]}]}`, + wantType: "container_upload", + }, + { + name: "emptied turn before a later text turn", + input: `{"model":"m","messages":[{"role":"user","content":[` + userTurnUpload + `]},{"role":"assistant","content":[{"type":"text","text":"ok"}]},{"role":"user","content":"next"}]}`, + wantType: "container_upload", + }, + { + name: "document without bytes", + input: `{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"document","source":{"type":"file","file_id":"file-1"}}]}]}`, + wantType: "document", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + body, err := ConvertClaudeRequestToInteractionsWithCompatReturningError("m", []byte(tc.input), false) + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(err, &unsupported) || unsupported.Type != tc.wantType || unsupported.StatusCode() != 400 { + t.Fatalf("err = %v, want unsupported content part: %s; body = %s", err, tc.wantType, body) + } + if got, want := err.Error(), "unsupported content part: "+tc.wantType; got != want { + t.Fatalf("error text = %q, want %q", got, want) + } + if !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } + }) + } +} + +func TestConvertClaudeRequestToInteractions_KeepsTurnWithTextBesideAttachment(t *testing.T) { + input := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"text","text":"keep me"},` + userTurnUpload + `]}]}`) + body, err := ConvertClaudeRequestToInteractionsWithCompatReturningError("m", input, false) + if err != nil { + t.Fatalf("err = %v", err) + } + if got := gjson.GetBytes(body, "input.2.content.0.text").String(); got != "keep me" { + t.Fatalf("text was lost: %s", body) + } +} + +func TestConvertClaudeRequestToInteractions_Base64DocumentAfterHistoryStaysMedia(t *testing.T) { + input := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"document","source":{"type":"base64","media_type":"application/pdf","data":"JVBERi0xLjQK"}}]}]}`) + body, err := ConvertClaudeRequestToInteractionsWithCompatReturningError("m", input, false) + if err != nil { + t.Fatalf("err = %v", err) + } + part := gjson.GetBytes(body, "input.2.content.0") + if part.Get("type").String() != "document" || part.Get("mime_type").String() != "application/pdf" || part.Get("data").String() != "JVBERi0xLjQK" { + t.Fatalf("part = %s, body = %s", part.Raw, body) + } +} + +func TestConvertClaudeRequestToInteractions_WhitespaceTextDoesNotHideAnUnrepresentableImage(t *testing.T) { + fileImage := `{"type":"image","source":{"type":"file","file_id":"f1"}}` + cases := []struct { + name string + parts string + }{ + {name: "spaces before image", parts: `{"type":"text","text":" "},` + fileImage}, + {name: "mixed whitespace before image", parts: `{"type":"text","text":" \n\t"},` + fileImage}, + {name: "spaces after image", parts: fileImage + `,{"type":"text","text":" "}`}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + input := []byte(`{"model":"m","messages":[{"role":"user","content":[` + tc.parts + `]}]}`) + body, err := ConvertClaudeRequestToInteractionsWithCompatReturningError("m", input, false) + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(err, &unsupported) || unsupported.Type != "image" || unsupported.StatusCode() != 400 { + t.Fatalf("err = %v, want unsupported content part: image; body = %s", err, body) + } + }) + } +} + +func TestConvertClaudeRequestToInteractions_RealTextBesideWhitespaceAndAnImageStillSucceeds(t *testing.T) { + input := []byte(`{"model":"m","messages":[{"role":"user","content":[{"type":"text","text":" "},{"type":"text","text":"keep me"},{"type":"image","source":{"type":"file","file_id":"f1"}}]}]}`) + body, err := ConvertClaudeRequestToInteractionsWithCompatReturningError("m", input, false) + if err != nil { + t.Fatalf("err = %v, body = %s", err, body) + } + found := false + gjson.GetBytes(body, "input.0.content").ForEach(func(_, part gjson.Result) bool { + if part.Get("text").String() == "keep me" { + found = true + } + return true + }) + if !found { + t.Fatalf("text was lost: %s", body) + } +} + +func TestClaudeToInteractionsRegistrationCarriesWhitespaceImageRefusal(t *testing.T) { + input := []byte(`{"model":"m","messages":[{"role":"user","content":[{"type":"text","text":" "},{"type":"image","source":{"type":"file","file_id":"f1"}}]}]}`) + envelope := sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatClaude, sdktranslator.FormatInteractions, sdktranslator.RequestEnvelope{ + Format: sdktranslator.FormatClaude, + Model: "m", + Body: input, + }) + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(envelope.Err, &unsupported) || unsupported.Type != "image" { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } +} diff --git a/internal/translator/openai/claude/openai_claude_request.go b/internal/translator/openai/claude/openai_claude_request.go index 9d3a46fd68f..b390d6c67fe 100644 --- a/internal/translator/openai/claude/openai_claude_request.go +++ b/internal/translator/openai/claude/openai_claude_request.go @@ -39,7 +39,7 @@ func ConvertClaudeRequestToOpenAIWithCompatReturningError(modelName string, inpu func convertClaudeRequestToOpenAI(modelName string, inputRawJSON []byte, stream bool, preserveThinkingBlocks bool) ([]byte, error) { rawJSON := inputRawJSON - var droppedAttachment string + var drops translatorcommon.UserTurnDrops // Base OpenAI Chat Completions API template out := []byte(`{"model":"","messages":[]}`) @@ -219,8 +219,8 @@ func convertClaudeRequestToOpenAI(modelName string, inputRawJSON []byte, stream case "text", "image", "document", "container_upload": if contentItem, ok := convertClaudeContentPart(part); ok { contentItems = append(contentItems, []byte(contentItem)) - } else if partType := part.Get("type").String(); partType == "document" || partType == "container_upload" { - droppedAttachment = partType + } else if role == "user" && partType != "text" { + drops.Drop(partType) } case "tool_use": @@ -274,6 +274,9 @@ func convertClaudeRequestToOpenAI(modelName string, inputRawJSON []byte, stream hasReasoning := reasoningContent != "" hasToolCalls := len(toolCalls) > 0 hasToolResults := len(toolResults) > 0 + if role == "user" { + drops.EndTurn(len(contentItems) + len(toolResults)) + } // Flush pending system reminders before new content if no tool_results responded to preceding calls if precedingToolCallsPending && !hasToolResults && len(pendingSystemReminders) > 0 { @@ -433,7 +436,7 @@ func convertClaudeRequestToOpenAI(modelName string, inputRawJSON []byte, stream out, _ = sjson.SetBytes(out, "user", user.String()) } - return out, translatorcommon.ErrIfNothingLeft(droppedAttachment, int(gjson.GetBytes(out, "messages.#").Int())) + return out, drops.Err() } func normalizeObjectSchemaProperties(schema any) any { diff --git a/internal/translator/openai/claude/openai_claude_user_turn_test.go b/internal/translator/openai/claude/openai_claude_user_turn_test.go new file mode 100644 index 00000000000..d2e42c3113a --- /dev/null +++ b/internal/translator/openai/claude/openai_claude_user_turn_test.go @@ -0,0 +1,151 @@ +package claude + +import ( + "context" + "errors" + "testing" + + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +const userTurnUpload = `{"type":"container_upload","file_id":"file-1"}` + +func TestConvertClaudeRequestToOpenAI_RefusesAnyEmptiedUserTurn(t *testing.T) { + cases := []struct { + name string + input string + wantType string + }{ + { + name: "history then attachment only", + input: `{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":[{"type":"text","text":"hi"}]},{"role":"user","content":[` + userTurnUpload + `]}]}`, + wantType: "container_upload", + }, + { + name: "system prompt and system reminder", + input: `{"model":"m","system":"sys","messages":[{"role":"system","content":"reminder"},{"role":"user","content":[` + userTurnUpload + `]}]}`, + wantType: "container_upload", + }, + { + name: "emptied turn before a later text turn", + input: `{"model":"m","messages":[{"role":"user","content":[` + userTurnUpload + `]},{"role":"assistant","content":[{"type":"text","text":"ok"}]},{"role":"user","content":"next"}]}`, + wantType: "container_upload", + }, + { + name: "document without bytes", + input: `{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"document","source":{"type":"file","file_id":"file-1"}}]}]}`, + wantType: "document", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + body, err := ConvertClaudeRequestToOpenAIWithCompatReturningError("m", []byte(tc.input), false) + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(err, &unsupported) || unsupported.Type != tc.wantType || unsupported.StatusCode() != 400 { + t.Fatalf("err = %v, want unsupported content part: %s; body = %s", err, tc.wantType, body) + } + if got, want := err.Error(), "unsupported content part: "+tc.wantType; got != want { + t.Fatalf("error text = %q, want %q", got, want) + } + if !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } + }) + } +} + +func TestConvertClaudeRequestToOpenAI_KeepsTurnWithTextBesideAttachment(t *testing.T) { + input := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"text","text":"keep me"},` + userTurnUpload + `]}]}`) + body, err := ConvertClaudeRequestToOpenAIWithCompatReturningError("m", input, false) + if err != nil { + t.Fatalf("err = %v", err) + } + if got := gjson.GetBytes(body, "messages.2.content.0.text").String(); got != "keep me" { + t.Fatalf("text was lost: %s", body) + } +} + +func TestConvertClaudeRequestToOpenAI_Base64DocumentAfterHistoryStaysAFilePart(t *testing.T) { + input := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"document","source":{"type":"base64","media_type":"application/pdf","data":"JVBERi0xLjQK"}}]}]}`) + body, err := ConvertClaudeRequestToOpenAIWithCompatReturningError("m", input, false) + if err != nil { + t.Fatalf("err = %v", err) + } + part := gjson.GetBytes(body, "messages.2.content.0") + if part.Get("type").String() != "file" || part.Get("file.file_data").String() != "data:application/pdf;base64,JVBERi0xLjQK" { + t.Fatalf("part = %s, body = %s", part.Raw, body) + } +} + +func TestConvertClaudeRequestToOpenAI_ToolResultKeepsTurnBesideUnsendableFile(t *testing.T) { + input := []byte(`{"model":"m","messages":[{"role":"user","content":"run"},{"role":"assistant","content":[{"type":"tool_use","id":"toolu_1","name":"t","input":{}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"done"},` + userTurnUpload + `]}]}`) + body, err := ConvertClaudeRequestToOpenAIWithCompatReturningError("m", input, false) + if err != nil { + t.Fatalf("a tool result is a sendable part, err = %v; body = %s", err, body) + } +} + +// claudeImageTurnToOpenAI translates a conversation of two history turns followed by a final user +// turn holding the given content parts. +func claudeImageTurnToOpenAI(finalContent string) sdktranslator.RequestEnvelope { + input := `{"model":"m","messages":[{"role":"user","content":"a"},{"role":"assistant","content":"b"},{"role":"user","content":[` + finalContent + `]}]}` + return sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatClaude, sdktranslator.FormatOpenAI, sdktranslator.RequestEnvelope{ + Format: sdktranslator.FormatClaude, + Model: "m", + Body: []byte(input), + }) +} + +func requireImageRefusal(t *testing.T, envelope sdktranslator.RequestEnvelope) { + t.Helper() + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(envelope.Err, &unsupported) || unsupported.Type != "image" || unsupported.StatusCode() != 400 { + t.Fatalf("envelope.Err = %v, want unsupported content part: image; body = %s", envelope.Err, envelope.Body) + } + if got, want := envelope.Err.Error(), "unsupported content part: image"; got != want { + t.Fatalf("error text = %q, want %q", got, want) + } +} + +func TestClaudeToOpenAIImageOnlyTurnKeepsTheImage(t *testing.T) { + cases := map[string]struct { + source string + want string + }{ + "base64": {source: `{"type":"base64","media_type":"image/png","data":"aGVsbG8="}`, want: "data:image/png;base64,aGVsbG8="}, + "http url": {source: `{"type":"url","url":"https://example.test/a.png"}`, want: "https://example.test/a.png"}, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + envelope := claudeImageTurnToOpenAI(`{"type":"image","source":` + tc.source + `}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + part := gjson.GetBytes(envelope.Body, "messages.2.content.0") + if part.Get("type").String() != "image_url" || part.Get("image_url.url").String() != tc.want { + t.Fatalf("part = %s, body = %s", part.Raw, envelope.Body) + } + }) + } +} + +func TestClaudeToOpenAIFileImageOnlyTurnIsRefused(t *testing.T) { + requireImageRefusal(t, claudeImageTurnToOpenAI(`{"type":"image","source":{"type":"file","file_id":"file-1"}}`)) +} + +func TestClaudeToOpenAIFileImageBesideTextStillSucceeds(t *testing.T) { + envelope := claudeImageTurnToOpenAI(`{"type":"text","text":"keep me"},{"type":"image","source":{"type":"file","file_id":"file-1"}}`) + if envelope.Err != nil { + t.Fatalf("envelope.Err = %v, body = %s", envelope.Err, envelope.Body) + } + parts := gjson.GetBytes(envelope.Body, "messages.2.content").Array() + if len(parts) != 1 || parts[0].Get("text").String() != "keep me" { + t.Fatalf("text was lost or an image leaked: %s", envelope.Body) + } +} + +func TestClaudeToOpenAIEmptyTextDoesNotHideAFileImage(t *testing.T) { + requireImageRefusal(t, claudeImageTurnToOpenAI(`{"type":"text","text":""},{"type":"image","source":{"type":"file","file_id":"file-1"}}`)) +} diff --git a/internal/translator/openai/interactions/chat-completions/init.go b/internal/translator/openai/interactions/chat-completions/init.go index c6a895b87e6..fd2e6ae6144 100644 --- a/internal/translator/openai/interactions/chat-completions/init.go +++ b/internal/translator/openai/interactions/chat-completions/init.go @@ -4,18 +4,20 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( OpenAI, Interactions, - ConvertOpenAIRequestToInteractions, + nil, interfaces.TranslateResponse{ Stream: ConvertInteractionsResponseToOpenAI, NonStream: ConvertInteractionsResponseToOpenAINonStream, }, ) + sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatOpenAI, sdktranslator.FormatInteractions, convertOpenAIRequestToInteractions) translator.Register( Interactions, OpenAI, diff --git a/internal/translator/openai/interactions/chat-completions/openai_interactions_request.go b/internal/translator/openai/interactions/chat-completions/openai_interactions_request.go index 6bea8ca3442..b9436e3b697 100644 --- a/internal/translator/openai/interactions/chat-completions/openai_interactions_request.go +++ b/internal/translator/openai/interactions/chat-completions/openai_interactions_request.go @@ -9,6 +9,13 @@ import ( ) func ConvertOpenAIRequestToInteractions(modelName string, inputRawJSON []byte, stream bool) []byte { + body, _ := convertOpenAIRequestToInteractions(modelName, inputRawJSON, stream) + return body +} + +// convertOpenAIRequestToInteractions also reports a file or audio part that +// Interactions cannot receive when it leaves a user turn with nothing to send. +func convertOpenAIRequestToInteractions(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { root := gjson.ParseBytes(inputRawJSON) out := []byte(`{"model":"","input":[]}`) model := firstNonEmpty(modelName, root.Get("model").String()) @@ -26,10 +33,10 @@ func ConvertOpenAIRequestToInteractions(modelName string, inputRawJSON []byte, s out, _ = sjson.SetRawBytes(out, "agent_config", []byte(agentConfig.Raw)) } forAntigravity := isAntigravityModel(model) - out = appendOpenAIMessagesToInteractions(out, root.Get("messages"), forAntigravity) + out, errMessages := appendOpenAIMessagesToInteractions(out, root.Get("messages"), forAntigravity) out = copyOpenAIChatGenerationConfigToInteractions(out, root, model) out = appendOpenAIChatToolsToInteractions(out, root.Get("tools"), forAntigravity) - return out + return out, errMessages } func openAIRequestStreamValue(root gjson.Result, stream bool) (bool, bool) { @@ -42,10 +49,11 @@ func openAIRequestStreamValue(root gjson.Result, stream bool) (bool, bool) { return false, false } -func appendOpenAIMessagesToInteractions(out []byte, messages gjson.Result, forAntigravity bool) []byte { +func appendOpenAIMessagesToInteractions(out []byte, messages gjson.Result, forAntigravity bool) ([]byte, error) { if !messages.Exists() || !messages.IsArray() { - return out + return out, nil } + var drops translatorcommon.UserTurnDrops inputItems := translatorcommon.NewRawArrayItems(messages.Get("#").Int()) var systemBuilder strings.Builder toolNamesByID := make(map[string]string) @@ -60,7 +68,7 @@ func appendOpenAIMessagesToInteractions(out []byte, messages gjson.Result, forAn systemBuilder.WriteString(text) } default: - appendOpenAIMessageToInteractions(&inputItems, message, forAntigravity, toolNamesByID) + appendOpenAIMessageToInteractions(&inputItems, message, forAntigravity, toolNamesByID, &drops) } return true }) @@ -68,10 +76,10 @@ func appendOpenAIMessagesToInteractions(out []byte, messages gjson.Result, forAn out, _ = sjson.SetBytes(out, "system_instruction", systemBuilder.String()) } out = translatorcommon.SetRawArrayItems(out, "input", inputItems) - return out + return out, drops.Err() } -func appendOpenAIMessageToInteractions(items *[][]byte, message gjson.Result, forAntigravity bool, toolNamesByID map[string]string) { +func appendOpenAIMessageToInteractions(items *[][]byte, message gjson.Result, forAntigravity bool, toolNamesByID map[string]string, drops *translatorcommon.UserTurnDrops) { role := strings.ToLower(strings.TrimSpace(message.Get("role").String())) switch role { case "assistant": @@ -80,7 +88,7 @@ func appendOpenAIMessageToInteractions(items *[][]byte, message gjson.Result, fo *items = append(*items, interactionsTextStep("thought", text)) } } - if step, ok := openAIChatContentStep("model_output", message.Get("content")); ok { + if step, ok := openAIChatContentStep("model_output", message.Get("content"), nil); ok { *items = append(*items, step) } if toolCalls := message.Get("tool_calls"); toolCalls.Exists() && toolCalls.IsArray() { @@ -99,14 +107,22 @@ func appendOpenAIMessageToInteractions(items *[][]byte, message gjson.Result, fo case "tool", "function": *items = append(*items, openAIToolResultToInteractions(message, forAntigravity, toolNamesByID)) default: - if step, ok := openAIChatContentStep("user_input", message.Get("content")); ok { + if step, ok := openAIChatContentStep("user_input", message.Get("content"), drops); ok { *items = append(*items, step) } } } -func openAIChatContentStep(stepType string, content gjson.Result) ([]byte, bool) { +// openAIChatContentStep converts one message content into an Interactions step. +// A non-nil drops closes the user turn: an attachment that cannot be sent is +// recorded, and text or any other sendable part beside it keeps the turn alive. +// An empty text part is forwarded but does not count as sendable. +func openAIChatContentStep(stepType string, content gjson.Result, drops *translatorcommon.UserTurnDrops) ([]byte, bool) { contentItems := make([][]byte, 0, 4) + sendable := 0 + if drops != nil { + defer func() { drops.EndTurn(sendable) }() + } if content.Type == gjson.String { if content.String() == "" { return nil, false @@ -114,10 +130,19 @@ func openAIChatContentStep(stepType string, content gjson.Result) ([]byte, bool) part := []byte(`{"type":"text","text":""}`) part, _ = sjson.SetBytes(part, "text", content.String()) contentItems = append(contentItems, part) + sendable++ } else { appendPart := func(part gjson.Result) { - if converted, ok := openAIChatContentPartToInteractions(part); ok { - contentItems = append(contentItems, converted) + converted, ok := openAIChatContentPartToInteractions(part) + if !ok { + if partType := openAIChatPartType(part); drops != nil && isOpenAIChatAttachmentType(partType) { + drops.Drop(partType) + } + return + } + contentItems = append(contentItems, converted) + if convertedType := gjson.GetBytes(converted, "type").String(); convertedType != "text" || gjson.GetBytes(converted, "text").String() != "" { + sendable++ } } if content.IsArray() { @@ -138,11 +163,26 @@ func openAIChatContentStep(stepType string, content gjson.Result) ([]byte, bool) return step, true } -func openAIChatContentPartToInteractions(part gjson.Result) ([]byte, bool) { +func openAIChatPartType(part gjson.Result) string { partType := strings.ToLower(strings.TrimSpace(part.Get("type").String())) if partType == "" && part.Get("text").Exists() { partType = "text" } + return partType +} + +// isOpenAIChatAttachmentType reports the part types whose loss must be refused +// when they leave a user turn empty, instead of being skipped silently. +func isOpenAIChatAttachmentType(partType string) bool { + switch partType { + case "file", "input_file", "document", "input_audio", "audio": + return true + } + return false +} + +func openAIChatContentPartToInteractions(part gjson.Result) ([]byte, bool) { + partType := openAIChatPartType(part) switch partType { case "text", "input_text", "output_text": out := []byte(`{"type":"text","text":""}`) diff --git a/internal/translator/openai/interactions/chat-completions/openai_interactions_user_turn_test.go b/internal/translator/openai/interactions/chat-completions/openai_interactions_user_turn_test.go new file mode 100644 index 00000000000..bf98700722f --- /dev/null +++ b/internal/translator/openai/interactions/chat-completions/openai_interactions_user_turn_test.go @@ -0,0 +1,133 @@ +package chat_completions + +import ( + "context" + "errors" + "testing" + + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +const ( + userTurnFileID = `{"type":"file","file":{"file_id":"file-absent"}}` + userTurnEmptyAudio = `{"type":"input_audio","input_audio":{"format":"wav"}}` + userTurnText = `{"type":"text","text":"keep me"}` + userTurnEmptyText = `{"type":"text","text":""}` + userTurnInline = `{"type":"file","file":{"filename":"a.pdf","file_data":"data:application/pdf;base64,JVBERi0xLjQK"}}` + userTurnAudio = `{"type":"input_audio","input_audio":{"data":"UklGRg==","format":"wav"}}` +) + +func TestConvertOpenAIRequestToInteractions_RefusesAnyEmptiedUserTurn(t *testing.T) { + cases := []struct { + name string + input string + wantType string + }{ + { + name: "file id only", + input: `{"model":"gemini-3.5-flash","messages":[{"role":"user","content":[` + userTurnFileID + `]}]}`, + wantType: "file", + }, + { + name: "history then file id only", + input: `{"model":"gemini-3.5-flash","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[` + userTurnFileID + `]}]}`, + wantType: "file", + }, + { + name: "system and developer prompts do not hide the empty turn", + input: `{"model":"gemini-3.5-flash","messages":[{"role":"system","content":"sys"},{"role":"developer","content":"dev"},{"role":"user","content":[` + userTurnFileID + `]}]}`, + wantType: "file", + }, + { + name: "emptied turn before a later text turn", + input: `{"model":"gemini-3.5-flash","messages":[{"role":"user","content":[` + userTurnFileID + `]},{"role":"assistant","content":"ok"},{"role":"user","content":"next"}]}`, + wantType: "file", + }, + { + name: "audio without bytes", + input: `{"model":"gemini-3.5-flash","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[` + userTurnEmptyAudio + `]}]}`, + wantType: "input_audio", + }, + { + name: "empty text beside the file id does not count as sendable", + input: `{"model":"gemini-3.5-flash","messages":[{"role":"user","content":[` + userTurnEmptyText + `,` + userTurnFileID + `]}]}`, + wantType: "file", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + body, err := convertOpenAIRequestToInteractions("gemini-3.5-flash", []byte(tc.input), false) + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(err, &unsupported) || unsupported.Type != tc.wantType || unsupported.StatusCode() != 400 { + t.Fatalf("err = %v, want unsupported content part: %s; body = %s", err, tc.wantType, body) + } + if got, want := err.Error(), "unsupported content part: "+tc.wantType; got != want { + t.Fatalf("error text = %q, want %q", got, want) + } + if !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } + + envelope := sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatOpenAI, sdktranslator.FormatInteractions, + sdktranslator.RequestEnvelope{Format: sdktranslator.FormatOpenAI, Model: "gemini-3.5-flash", Body: []byte(tc.input)}) + if !errors.As(envelope.Err, &unsupported) || unsupported.Type != tc.wantType { + t.Fatalf("registry err = %v, want unsupported content part: %s", envelope.Err, tc.wantType) + } + }) + } +} + +func TestConvertOpenAIRequestToInteractions_KeepsTurnWithTextBesideAttachment(t *testing.T) { + input := `{"model":"gemini-3.5-flash","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[` + userTurnText + `,` + userTurnFileID + `]}]}` + body, err := convertOpenAIRequestToInteractions("gemini-3.5-flash", []byte(input), false) + if err != nil { + t.Fatalf("err = %v", err) + } + if got := gjson.GetBytes(body, "input.2.content.0.text").String(); got != "keep me" { + t.Fatalf("text was lost: %s", body) + } +} + +func TestConvertOpenAIRequestToInteractions_InlineFileAndAudioAfterHistoryStayBytes(t *testing.T) { + cases := map[string]struct { + part string + wantType string + wantData string + }{ + "file": {part: userTurnInline, wantType: "document", wantData: "JVBERi0xLjQK"}, + "audio": {part: userTurnAudio, wantType: "audio", wantData: "UklGRg=="}, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + input := `{"model":"gemini-3.5-flash","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[` + tc.part + `]}]}` + body, err := convertOpenAIRequestToInteractions("gemini-3.5-flash", []byte(input), false) + if err != nil { + t.Fatalf("err = %v", err) + } + part := gjson.GetBytes(body, "input.2.content.0") + if part.Get("type").String() != tc.wantType || part.Get("data").String() != tc.wantData { + t.Fatalf("part = %s, body = %s", part.Raw, body) + } + }) + } +} + +func TestConvertOpenAIRequestToInteractions_FileURLStaysAFile(t *testing.T) { + input := `{"model":"gemini-3.5-flash","messages":[{"role":"user","content":[{"type":"file","file":{"file_url":"https://example.test/a.pdf"}}]}]}` + body, err := convertOpenAIRequestToInteractions("gemini-3.5-flash", []byte(input), false) + if err != nil { + t.Fatalf("err = %v", err) + } + if got := gjson.GetBytes(body, "input.0.content.0.file_url").String(); got != "https://example.test/a.pdf" { + t.Fatalf("file url was lost: %s", body) + } +} + +func TestConvertOpenAIRequestToInteractions_ExportedWrapperKeepsAJSONBody(t *testing.T) { + input := []byte(`{"model":"gemini-3.5-flash","messages":[{"role":"user","content":[` + userTurnFileID + `]}]}`) + if body := ConvertOpenAIRequestToInteractions("gemini-3.5-flash", input, false); !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } +} diff --git a/internal/translator/openai/interactions/responses/init.go b/internal/translator/openai/interactions/responses/init.go index 92d70942103..8ac3a5de184 100644 --- a/internal/translator/openai/interactions/responses/init.go +++ b/internal/translator/openai/interactions/responses/init.go @@ -4,18 +4,20 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( OpenaiResponse, Interactions, - ConvertOpenAIResponsesRequestToInteractions, + nil, interfaces.TranslateResponse{ Stream: ConvertInteractionsResponseToOpenAIResponses, NonStream: ConvertInteractionsResponseToOpenAIResponsesNonStream, }, ) + sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatOpenAIResponse, sdktranslator.FormatInteractions, convertOpenAIResponsesRequestToInteractions) translator.Register( Interactions, OpenaiResponse, diff --git a/internal/translator/openai/interactions/responses/interactions_openai_responses_request.go b/internal/translator/openai/interactions/responses/interactions_openai_responses_request.go index 2ab284e112a..c0975cb8eee 100644 --- a/internal/translator/openai/interactions/responses/interactions_openai_responses_request.go +++ b/internal/translator/openai/interactions/responses/interactions_openai_responses_request.go @@ -11,6 +11,14 @@ import ( ) func ConvertOpenAIResponsesRequestToInteractions(modelName string, inputRawJSON []byte, stream bool) []byte { + body, _ := convertOpenAIResponsesRequestToInteractions(modelName, inputRawJSON, stream) + return body +} + +// convertOpenAIResponsesRequestToInteractions also reports a file, audio or video +// part Interactions cannot receive when it leaves a user turn with nothing to send. +func convertOpenAIResponsesRequestToInteractions(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { + var drops translatorcommon.UserTurnDrops root := gjson.ParseBytes(inputRawJSON) out := []byte(`{"model":"","input":[]}`) model := requestModel(modelName, root) @@ -33,7 +41,7 @@ func ConvertOpenAIResponsesRequestToInteractions(modelName string, inputRawJSON forAntigravity := isAntigravityModel(model) forDevin := isDevinModel(model) || !forAntigravity if input := root.Get("input"); input.Exists() { - out = setResponsesInputOnInteractions(out, input, forAntigravity) + out = setResponsesInputOnInteractions(out, input, forAntigravity, &drops) } out = appendResponsesToolsToInteractions(out, root, forAntigravity, forDevin) if toolChoice := root.Get("tool_choice"); toolChoice.Exists() { @@ -104,7 +112,7 @@ func ConvertOpenAIResponsesRequestToInteractions(modelName string, inputRawJSON out, _ = sjson.SetRawBytes(out, "generation_config.stop_sequences", []byte(stop.Raw)) } } - return out + return out, drops.Err() } func ConvertInteractionsRequestToOpenAIResponses(modelName string, inputRawJSON []byte, stream bool) []byte { @@ -230,20 +238,20 @@ func interactionsThinkingEffort(root gjson.Result) string { return "" } -func setResponsesInputOnInteractions(out []byte, input gjson.Result, forAntigravity bool) []byte { +func setResponsesInputOnInteractions(out []byte, input gjson.Result, forAntigravity bool, drops *translatorcommon.UserTurnDrops) []byte { functionNamesByCallID := make(map[string]string) items := make([][]byte, 0) if input.Type == gjson.String { items = append(items, interactionsTextStep("user_input", input.String())) } else if input.IsArray() { input.ForEach(func(_, item gjson.Result) bool { - if converted := responsesInputItemToInteractions(item, functionNamesByCallID, forAntigravity); converted != nil { + if converted := responsesInputItemToInteractions(item, functionNamesByCallID, forAntigravity, drops); converted != nil { items = append(items, converted) } return true }) } else if input.IsObject() { - if converted := responsesInputItemToInteractions(input, functionNamesByCallID, forAntigravity); converted != nil { + if converted := responsesInputItemToInteractions(input, functionNamesByCallID, forAntigravity, drops); converted != nil { items = append(items, converted) } } @@ -253,16 +261,29 @@ func setResponsesInputOnInteractions(out []byte, input gjson.Result, forAntigrav return out } -func responsesInputItemToInteractions(item gjson.Result, functionNamesByCallID map[string]string, forAntigravity bool) []byte { +// responsesUserTurnDrops returns drops when the item is a real user turn. A +// system or developer message is also sent as a user_input step, but it is not +// the user's own turn and must never be refused or hide an emptied one. +func responsesUserTurnDrops(role string, drops *translatorcommon.UserTurnDrops) *translatorcommon.UserTurnDrops { + if role == "" || role == "user" { + return drops + } + return nil +} + +func responsesInputItemToInteractions(item gjson.Result, functionNamesByCallID map[string]string, forAntigravity bool, drops *translatorcommon.UserTurnDrops) []byte { switch item.Get("type").String() { case "message": stepType := "user_input" - if role := item.Get("role").String(); role == "assistant" || role == "model" { + role := item.Get("role").String() + turnDrops := responsesUserTurnDrops(role, drops) + if role == "assistant" || role == "model" { stepType = "model_output" + turnDrops = nil } step := []byte(`{"type":"","content":[]}`) step, _ = sjson.SetBytes(step, "type", stepType) - return appendResponsesContentToInteractions(step, item.Get("content")) + return appendResponsesContentToInteractions(step, item.Get("content"), turnDrops) case "function_call": callID := firstNonEmpty(item.Get("call_id").String(), item.Get("id").String()) name := item.Get("name").String() @@ -291,43 +312,63 @@ func responsesInputItemToInteractions(item gjson.Result, functionNamesByCallID m stepType = "model_output" } return interactionsTextStep(stepType, item.Get("text").String()) - case "input_image", "output_image": + case "input_image", "output_image", "input_file", "input_audio", "input_video": stepType := "user_input" + var turnDrops *translatorcommon.UserTurnDrops if item.Get("type").String() == "output_image" { stepType = "model_output" + } else { + turnDrops = drops } step := []byte(`{"type":"","content":[]}`) step, _ = sjson.SetBytes(step, "type", stepType) - if part, ok := responsesContentPartToInteractions(item); ok { - step = translatorcommon.SetRawArrayItems(step, "content", [][]byte{part}) - } - return step + return appendResponsesContentToInteractions(step, item, turnDrops) default: if content := item.Get("content"); content.Exists() { step := []byte(`{"type":"user_input","content":[]}`) - return appendResponsesContentToInteractions(step, content) + return appendResponsesContentToInteractions(step, content, responsesUserTurnDrops(item.Get("role").String(), drops)) } } return nil } -func appendResponsesContentToInteractions(step []byte, content gjson.Result) []byte { +// appendResponsesContentToInteractions converts one message content into step +// content. A non-nil drops closes the user turn: an attachment that cannot be +// sent is recorded, and text or any other sendable part beside it keeps the turn +// alive. An empty text part is forwarded but does not count as sendable. +func appendResponsesContentToInteractions(step []byte, content gjson.Result, drops *translatorcommon.UserTurnDrops) []byte { var contentItems [][]byte + sendable := 0 + appendPart := func(item gjson.Result) { + part, ok := responsesContentPartToInteractions(item) + if !ok { + if partType := item.Get("type").String(); drops != nil && isResponsesUnsendableAttachmentType(partType) { + drops.Drop(partType) + } + return + } + contentItems = append(contentItems, part) + if gjson.GetBytes(part, "type").String() != "text" || gjson.GetBytes(part, "text").String() != "" { + sendable++ + } + } if content.Type == gjson.String { part := []byte(`{"type":"text","text":""}`) part, _ = sjson.SetBytes(part, "text", content.String()) contentItems = append(contentItems, part) + if content.String() != "" { + sendable++ + } } else if content.IsArray() { content.ForEach(func(_, item gjson.Result) bool { - if part, ok := responsesContentPartToInteractions(item); ok { - contentItems = append(contentItems, part) - } + appendPart(item) return true }) } else if content.IsObject() { - if part, ok := responsesContentPartToInteractions(content); ok { - contentItems = append(contentItems, part) - } + appendPart(content) + } + if drops != nil { + drops.EndTurn(sendable) } if len(contentItems) > 0 { step = translatorcommon.SetRawArrayItems(step, "content", contentItems) @@ -335,6 +376,17 @@ func appendResponsesContentToInteractions(step []byte, content gjson.Result) []b return step } +// isResponsesUnsendableAttachmentType reports the Responses attachment types +// whose loss must be refused when they leave a user turn empty. A file id, +// a part without bytes and a video have no Interactions counterpart. +func isResponsesUnsendableAttachmentType(partType string) bool { + switch partType { + case "input_file", "input_audio", "input_video": + return true + } + return false +} + func responsesContentPartToInteractions(part gjson.Result) ([]byte, bool) { switch part.Get("type").String() { case "input_text", "output_text", "text": @@ -343,6 +395,10 @@ func responsesContentPartToInteractions(part gjson.Result) ([]byte, bool) { return out, true case "input_image", "output_image": return responsesImagePartToInteractions(part), true + case "input_file": + return responsesFilePartToInteractions(part) + case "input_audio": + return responsesAudioPartToInteractions(part) } if text := part.Get("text"); text.Exists() { out := []byte(`{"type":"text","text":""}`) @@ -352,6 +408,60 @@ func responsesContentPartToInteractions(part gjson.Result) ([]byte, bool) { return nil, false } +// responsesFilePartToInteractions maps an input_file onto an Interactions +// document. Interactions takes inline bytes or a url; a bare file_id names a file +// only the OpenAI side can resolve, so it reports false. +func responsesFilePartToInteractions(part gjson.Result) ([]byte, bool) { + filename := part.Get("filename").String() + fallbackMIMEType := firstNonEmpty(part.Get("mime_type").String(), part.Get("mimeType").String()) + out := []byte(`{"type":"document"}`) + if filename != "" { + out, _ = sjson.SetBytes(out, "filename", filename) + } + hasContent := false + if mimeType, data, ok := translatorcommon.NormalizeOpenAIFileData(filename, fallbackMIMEType, part.Get("file_data").String()); ok { + out, _ = sjson.SetBytes(out, "mime_type", mimeType) + out, _ = sjson.SetBytes(out, "data", data) + hasContent = true + } + if fileURL := part.Get("file_url").String(); fileURL != "" { + out, _ = sjson.SetBytes(out, "file_url", fileURL) + hasContent = true + } + return out, hasContent +} + +// responsesAudioPartToInteractions maps an input_audio with inline bytes onto an +// Interactions audio part. +func responsesAudioPartToInteractions(part gjson.Result) ([]byte, bool) { + audio := part.Get("input_audio") + data := firstNonEmpty(audio.Get("data").String(), part.Get("data").String()) + if data == "" { + return nil, false + } + out := []byte(`{"type":"audio","data":""}`) + out, _ = sjson.SetBytes(out, "data", data) + if format := firstNonEmpty(audio.Get("format").String(), part.Get("format").String()); format != "" { + out, _ = sjson.SetBytes(out, "mime_type", responsesInputAudioMIMEType(format)) + } + return out, true +} + +func responsesInputAudioMIMEType(format string) string { + switch strings.ToLower(strings.TrimSpace(format)) { + case "wav": + return "audio/wav" + case "flac": + return "audio/flac" + case "opus": + return "audio/opus" + case "pcm16": + return "audio/pcm" + default: + return "audio/mpeg" + } +} + func responsesImagePartToInteractions(part gjson.Result) []byte { out := []byte(`{"type":"image"}`) imageURL := firstNonEmpty(part.Get("image_url").String(), part.Get("url").String()) diff --git a/internal/translator/openai/interactions/responses/interactions_openai_responses_user_turn_test.go b/internal/translator/openai/interactions/responses/interactions_openai_responses_user_turn_test.go new file mode 100644 index 00000000000..7b7ad74204b --- /dev/null +++ b/internal/translator/openai/interactions/responses/interactions_openai_responses_user_turn_test.go @@ -0,0 +1,184 @@ +package responses + +import ( + "context" + "errors" + "strings" + "testing" + + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +const ( + interactionsTurnHello = `{"type":"message","role":"user","content":[{"type":"input_text","text":"hello"}]}` + interactionsTurnAssistant = `{"type":"message","role":"assistant","content":[{"type":"output_text","text":"hi"}]}` + interactionsTurnNext = `{"type":"message","role":"user","content":[{"type":"input_text","text":"next"}]}` + interactionsTurnFileID = `{"type":"input_file","file_id":"file-1"}` + interactionsTurnFileData = `{"type":"input_file","filename":"a.pdf","file_data":"data:application/pdf;base64,JVBERi0xLjQK"}` + interactionsTurnFileURL = `{"type":"input_file","file_url":"https://example.test/a.pdf"}` + interactionsTurnAudio = `{"type":"input_audio","input_audio":{"data":"UklGRg==","format":"wav"}}` + interactionsTurnNoAudio = `{"type":"input_audio","input_audio":{"format":"wav"}}` + interactionsTurnVideo = `{"type":"input_video","video_url":"https://example.test/a.mp4"}` + interactionsTurnText = `{"type":"input_text","text":"keep me"}` + interactionsTurnEmptyText = `{"type":"input_text","text":""}` +) + +func interactionsUserTurn(role string, parts ...string) string { + return `{"type":"message","role":"` + role + `","content":[` + strings.Join(parts, ",") + `]}` +} + +func interactionsTurnPayload(instructions string, items ...string) []byte { + prefix := `{"model":"gemini-3.5-flash",` + if instructions != "" { + prefix += `"instructions":"` + instructions + `",` + } + return []byte(prefix + `"input":[` + strings.Join(items, ",") + `]}`) +} + +func TestConvertOpenAIResponsesRequestToInteractions_RefusesAnyEmptiedUserTurn(t *testing.T) { + cases := []struct { + name string + input []byte + wantType string + }{ + { + name: "file id only", + input: interactionsTurnPayload("", interactionsUserTurn("user", interactionsTurnFileID)), + wantType: "input_file", + }, + { + name: "history then file id only", + input: interactionsTurnPayload("", interactionsTurnHello, interactionsTurnAssistant, interactionsUserTurn("user", interactionsTurnFileID)), + wantType: "input_file", + }, + { + name: "audio without bytes", + input: interactionsTurnPayload("", interactionsTurnHello, interactionsTurnAssistant, interactionsUserTurn("user", interactionsTurnNoAudio)), + wantType: "input_audio", + }, + { + name: "video has no counterpart", + input: interactionsTurnPayload("", interactionsTurnHello, interactionsTurnAssistant, interactionsUserTurn("user", interactionsTurnVideo)), + wantType: "input_video", + }, + { + name: "instructions and developer prompt do not hide the empty turn", + input: interactionsTurnPayload("sys", interactionsUserTurn("developer", interactionsTurnText), interactionsUserTurn("user", interactionsTurnFileID)), + wantType: "input_file", + }, + { + name: "emptied turn before a later text turn", + input: interactionsTurnPayload("", interactionsUserTurn("user", interactionsTurnFileID), interactionsTurnAssistant, interactionsTurnNext), + wantType: "input_file", + }, + { + name: "empty text beside the file id does not count as sendable", + input: interactionsTurnPayload("", interactionsUserTurn("user", interactionsTurnEmptyText, interactionsTurnFileID)), + wantType: "input_file", + }, + { + name: "bare input file item", + input: interactionsTurnPayload("", interactionsTurnHello, interactionsTurnAssistant, interactionsTurnFileID), + wantType: "input_file", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + body, err := convertOpenAIResponsesRequestToInteractions("gemini-3.5-flash", tc.input, false) + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(err, &unsupported) || unsupported.Type != tc.wantType || unsupported.StatusCode() != 400 { + t.Fatalf("err = %v, want unsupported content part: %s; body = %s", err, tc.wantType, body) + } + if got, want := err.Error(), "unsupported content part: "+tc.wantType; got != want { + t.Fatalf("error text = %q, want %q", got, want) + } + if !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } + + envelope := sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatOpenAIResponse, sdktranslator.FormatInteractions, + sdktranslator.RequestEnvelope{Format: sdktranslator.FormatOpenAIResponse, Model: "gemini-3.5-flash", Body: tc.input}) + if !errors.As(envelope.Err, &unsupported) || unsupported.Type != tc.wantType { + t.Fatalf("registry err = %v, want unsupported content part: %s", envelope.Err, tc.wantType) + } + }) + } +} + +func TestConvertOpenAIResponsesRequestToInteractions_KeepsTurnWithTextBesideAttachment(t *testing.T) { + for name, attachment := range map[string]string{"file id": interactionsTurnFileID, "audio without bytes": interactionsTurnNoAudio} { + t.Run(name, func(t *testing.T) { + input := interactionsTurnPayload("", interactionsTurnHello, interactionsTurnAssistant, interactionsUserTurn("user", interactionsTurnText, attachment)) + body, err := convertOpenAIResponsesRequestToInteractions("gemini-3.5-flash", input, false) + if err != nil { + t.Fatalf("err = %v", err) + } + if got := gjson.GetBytes(body, "input.2.content.0.text").String(); got != "keep me" { + t.Fatalf("text was lost: %s", body) + } + }) + } +} + +func TestConvertOpenAIResponsesRequestToInteractions_MapsBytesAndUrls(t *testing.T) { + cases := map[string]struct { + part string + want map[string]string + }{ + "file data": { + part: interactionsTurnFileData, + want: map[string]string{"type": "document", "mime_type": "application/pdf", "data": "JVBERi0xLjQK", "filename": "a.pdf"}, + }, + "file url": { + part: interactionsTurnFileURL, + want: map[string]string{"type": "document", "file_url": "https://example.test/a.pdf"}, + }, + "audio": { + part: interactionsTurnAudio, + want: map[string]string{"type": "audio", "data": "UklGRg==", "mime_type": "audio/wav"}, + }, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + input := interactionsTurnPayload("", interactionsTurnHello, interactionsTurnAssistant, interactionsUserTurn("user", tc.part)) + body, err := convertOpenAIResponsesRequestToInteractions("gemini-3.5-flash", input, false) + if err != nil { + t.Fatalf("err = %v", err) + } + part := gjson.GetBytes(body, "input.2.content.0") + for path, want := range tc.want { + if got := part.Get(path).String(); got != want { + t.Fatalf("%s = %q, want %q; part = %s, body = %s", path, got, want, part.Raw, body) + } + } + }) + } +} + +func TestConvertOpenAIResponsesRequestToInteractions_BareFileItemStaysADocument(t *testing.T) { + input := interactionsTurnPayload("", interactionsTurnHello, interactionsTurnAssistant, interactionsTurnFileData) + body, err := convertOpenAIResponsesRequestToInteractions("gemini-3.5-flash", input, false) + if err != nil { + t.Fatalf("err = %v", err) + } + step := gjson.GetBytes(body, "input.2") + if step.Get("type").String() != "user_input" || step.Get("content.0.type").String() != "document" || step.Get("content.0.data").String() != "JVBERi0xLjQK" { + t.Fatalf("step = %s, body = %s", step.Raw, body) + } +} + +func TestConvertOpenAIResponsesRequestToInteractions_DeveloperAttachmentIsNotAUserTurn(t *testing.T) { + input := interactionsTurnPayload("", interactionsUserTurn("developer", interactionsTurnFileID), interactionsTurnNext) + if _, err := convertOpenAIResponsesRequestToInteractions("gemini-3.5-flash", input, false); err != nil { + t.Fatalf("err = %v, want no refusal for a developer message", err) + } +} + +func TestConvertOpenAIResponsesRequestToInteractions_ExportedWrapperKeepsAJSONBody(t *testing.T) { + input := interactionsTurnPayload("", interactionsUserTurn("user", interactionsTurnFileID)) + if body := ConvertOpenAIResponsesRequestToInteractions("gemini-3.5-flash", input, false); !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } +} diff --git a/internal/translator/openai/openai/responses/init.go b/internal/translator/openai/openai/responses/init.go index 96a5d1ed965..06e0de7c7cc 100644 --- a/internal/translator/openai/openai/responses/init.go +++ b/internal/translator/openai/openai/responses/init.go @@ -4,16 +4,18 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( OpenaiResponse, OpenAI, - ConvertOpenAIResponsesRequestToOpenAIChatCompletions, + nil, interfaces.TranslateResponse{ Stream: ConvertOpenAIChatCompletionsResponseToOpenAIResponses, NonStream: ConvertOpenAIChatCompletionsResponseToOpenAIResponsesNonStream, }, ) + sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatOpenAIResponse, sdktranslator.FormatOpenAI, convertOpenAIResponsesRequestToOpenAIChatCompletions) } diff --git a/internal/translator/openai/openai/responses/openai_openai-responses_request.go b/internal/translator/openai/openai/responses/openai_openai-responses_request.go index 9c633c64f9e..87ed9697daa 100644 --- a/internal/translator/openai/openai/responses/openai_openai-responses_request.go +++ b/internal/translator/openai/openai/responses/openai_openai-responses_request.go @@ -28,7 +28,16 @@ import ( // Returns: // - []byte: The transformed request data in OpenAI chat completions format func ConvertOpenAIResponsesRequestToOpenAIChatCompletions(modelName string, inputRawJSON []byte, stream bool) []byte { + body, _ := convertOpenAIResponsesRequestToOpenAIChatCompletions(modelName, inputRawJSON, stream) + return body +} + +// convertOpenAIResponsesRequestToOpenAIChatCompletions also reports a file or +// audio part Chat Completions cannot receive when it leaves a user turn with +// nothing to send. +func convertOpenAIResponsesRequestToOpenAIChatCompletions(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { rawJSON := inputRawJSON + var drops translatorcommon.UserTurnDrops // Base OpenAI chat completions template with default values out := []byte(`{"model":"","messages":[],"stream":false}`) @@ -243,6 +252,9 @@ func ConvertOpenAIResponsesRequestToOpenAIChatCompletions(modelName string, inpu case "message", "": // Handle regular message conversion role := item.Get("role").String() + // Only a real user turn can be refused; developer text is sent as user text + // but never counts as the user's own turn. + isUserTurn := role == "user" if role == "developer" { role = "user" } @@ -256,6 +268,8 @@ func ConvertOpenAIResponsesRequestToOpenAIChatCompletions(modelName string, inpu if content := item.Get("content"); content.Exists() && content.IsArray() { var contentItems [][]byte + // Counts the parts this turn really sends; an empty text part does not. + turnSendable := 0 content.ForEach(func(_, contentItem gjson.Result) bool { contentType := contentItem.Get("type").String() if contentType == "" { @@ -268,6 +282,9 @@ func ConvertOpenAIResponsesRequestToOpenAIChatCompletions(modelName string, inpu contentPart := []byte(`{"type":"text","text":""}`) contentPart, _ = sjson.SetBytes(contentPart, "text", text) contentItems = append(contentItems, contentPart) + if text != "" { + turnSendable++ + } case "input_video", "video_url": contentPart := []byte(`{"type":"video_url","video_url":{}}`) videoURL := contentItem.Get("video_url") @@ -282,6 +299,7 @@ func ConvertOpenAIResponsesRequestToOpenAIChatCompletions(modelName string, inpu // Preserve malformed video parts for upstream validation instead of // silently turning a video request into a text-only request. contentItems = append(contentItems, contentPart) + turnSendable++ case "input_image": imageURL := contentItem.Get("image_url").String() contentPart := []byte(`{"type":"image_url","image_url":{"url":""}}`) @@ -290,9 +308,28 @@ func ConvertOpenAIResponsesRequestToOpenAIChatCompletions(modelName string, inpu contentPart, _ = sjson.SetBytes(contentPart, "image_url.detail", detail) } contentItems = append(contentItems, contentPart) + turnSendable++ + case "input_file": + if contentPart, ok := responsesInputFileToChatPart(contentItem); ok { + contentItems = append(contentItems, contentPart) + turnSendable++ + } else if isUserTurn { + // Chat Completions takes a file id or inline bytes only. + drops.Drop(contentType) + } + case "input_audio": + if contentPart, ok := responsesInputAudioToChatPart(contentItem); ok { + contentItems = append(contentItems, contentPart) + turnSendable++ + } else if isUserTurn { + drops.Drop(contentType) + } } return true }) + if isUserTurn { + drops.EndTurn(turnSendable) + } message = translatorcommon.SetRawArrayItems(message, "content", contentItems) } else if content.Type == gjson.String { message, _ = sjson.SetBytes(message, "content", content.String()) @@ -469,7 +506,52 @@ func ConvertOpenAIResponsesRequestToOpenAIChatCompletions(modelName string, inpu } } - return out + return out, drops.Err() +} + +// responsesInputFileToChatPart maps a Responses input_file part onto a Chat +// Completions file part. It reports false when the part carries neither a file +// id nor inline bytes, because Chat Completions has no field for a bare url. +func responsesInputFileToChatPart(contentItem gjson.Result) ([]byte, bool) { + fileID := contentItem.Get("file_id").String() + fileData := contentItem.Get("file_data").String() + if fileID == "" && fileData == "" { + return nil, false + } + part := []byte(`{"type":"file","file":{}}`) + if fileID != "" { + part, _ = sjson.SetBytes(part, "file.file_id", fileID) + } + if fileData != "" { + part, _ = sjson.SetBytes(part, "file.file_data", fileData) + } + if filename := contentItem.Get("filename").String(); filename != "" { + part, _ = sjson.SetBytes(part, "file.filename", filename) + } + return part, true +} + +// responsesInputAudioToChatPart maps a Responses input_audio part onto a Chat +// Completions input_audio part. It reports false when the part has no bytes. +func responsesInputAudioToChatPart(contentItem gjson.Result) ([]byte, bool) { + audio := contentItem.Get("input_audio") + data := audio.Get("data").String() + if data == "" { + data = contentItem.Get("data").String() + } + if data == "" { + return nil, false + } + format := audio.Get("format").String() + if format == "" { + format = contentItem.Get("format").String() + } + part := []byte(`{"type":"input_audio","input_audio":{"data":""}}`) + part, _ = sjson.SetBytes(part, "input_audio.data", data) + if format != "" { + part, _ = sjson.SetBytes(part, "input_audio.format", format) + } + return part, true } func convertResponsesToolChoiceToChatCompletions(toolChoice gjson.Result, inputRawJSON []byte) []byte { diff --git a/internal/translator/openai/openai/responses/openai_openai-responses_user_turn_test.go b/internal/translator/openai/openai/responses/openai_openai-responses_user_turn_test.go new file mode 100644 index 00000000000..cd409745e48 --- /dev/null +++ b/internal/translator/openai/openai/responses/openai_openai-responses_user_turn_test.go @@ -0,0 +1,162 @@ +package responses + +import ( + "context" + "errors" + "strings" + "testing" + + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +const ( + chatTurnHello = `{"type":"message","role":"user","content":[{"type":"input_text","text":"hello"}]}` + chatTurnAssistant = `{"type":"message","role":"assistant","content":[{"type":"output_text","text":"hi"}]}` + chatTurnNext = `{"type":"message","role":"user","content":[{"type":"input_text","text":"next"}]}` + chatTurnDeveloper = `{"type":"message","role":"developer","content":[{"type":"input_text","text":"dev"}]}` + chatTurnFileID = `{"type":"input_file","file_id":"file-1"}` + chatTurnFileData = `{"type":"input_file","filename":"a.pdf","file_data":"data:application/pdf;base64,JVBERi0xLjQK"}` + chatTurnFileURL = `{"type":"input_file","file_url":"https://example.test/a.pdf"}` + chatTurnAudio = `{"type":"input_audio","input_audio":{"data":"UklGRg==","format":"wav"}}` + chatTurnNoAudio = `{"type":"input_audio","input_audio":{"format":"wav"}}` + chatTurnText = `{"type":"input_text","text":"keep me"}` + chatTurnEmptyText = `{"type":"input_text","text":""}` +) + +func chatUserTurn(parts ...string) string { + return `{"type":"message","role":"user","content":[` + strings.Join(parts, ",") + `]}` +} + +func chatPayload(instructions string, items ...string) []byte { + prefix := `{"model":"gpt-5",` + if instructions != "" { + prefix += `"instructions":"` + instructions + `",` + } + return []byte(prefix + `"input":[` + strings.Join(items, ",") + `]}`) +} + +func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_RefusesAnyEmptiedUserTurn(t *testing.T) { + cases := []struct { + name string + input []byte + wantType string + }{ + { + name: "history then file url only", + input: chatPayload("", chatTurnHello, chatTurnAssistant, chatUserTurn(chatTurnFileURL)), + wantType: "input_file", + }, + { + name: "audio without bytes", + input: chatPayload("", chatTurnHello, chatTurnAssistant, chatUserTurn(chatTurnNoAudio)), + wantType: "input_audio", + }, + { + name: "instructions and developer prompt do not hide the empty turn", + input: chatPayload("sys", chatTurnDeveloper, chatUserTurn(chatTurnFileURL)), + wantType: "input_file", + }, + { + name: "emptied turn before a later text turn", + input: chatPayload("", chatUserTurn(chatTurnFileURL), chatTurnAssistant, chatTurnNext), + wantType: "input_file", + }, + { + name: "empty text beside the unsendable file does not count as sendable", + input: chatPayload("", chatUserTurn(chatTurnEmptyText, chatTurnFileURL)), + wantType: "input_file", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + body, err := convertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5", tc.input, false) + var unsupported *translatorcommon.UnsupportedPartError + if !errors.As(err, &unsupported) || unsupported.Type != tc.wantType || unsupported.StatusCode() != 400 { + t.Fatalf("err = %v, want unsupported content part: %s; body = %s", err, tc.wantType, body) + } + if got, want := err.Error(), "unsupported content part: "+tc.wantType; got != want { + t.Fatalf("error text = %q, want %q", got, want) + } + if !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } + + envelope := sdktranslator.TranslateRequestEnvelope(context.Background(), sdktranslator.FormatOpenAIResponse, sdktranslator.FormatOpenAI, + sdktranslator.RequestEnvelope{Format: sdktranslator.FormatOpenAIResponse, Model: "gpt-5", Body: tc.input}) + if !errors.As(envelope.Err, &unsupported) || unsupported.Type != tc.wantType { + t.Fatalf("registry err = %v, want unsupported content part: %s", envelope.Err, tc.wantType) + } + }) + } +} + +func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_MapsFilesAndAudio(t *testing.T) { + cases := map[string]struct { + part string + want map[string]string + }{ + "file id": { + part: chatTurnFileID, + want: map[string]string{"type": "file", "file.file_id": "file-1"}, + }, + "file data": { + part: chatTurnFileData, + want: map[string]string{"type": "file", "file.file_data": "data:application/pdf;base64,JVBERi0xLjQK", "file.filename": "a.pdf"}, + }, + "audio": { + part: chatTurnAudio, + want: map[string]string{"type": "input_audio", "input_audio.data": "UklGRg==", "input_audio.format": "wav"}, + }, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + input := chatPayload("", chatTurnHello, chatTurnAssistant, chatUserTurn(tc.part)) + body, err := convertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5", input, false) + if err != nil { + t.Fatalf("err = %v", err) + } + part := gjson.GetBytes(body, "messages.2.content.0") + for path, want := range tc.want { + if got := part.Get(path).String(); got != want { + t.Fatalf("%s = %q, want %q; part = %s, body = %s", path, got, want, part.Raw, body) + } + } + }) + } +} + +func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_KeepsTurnWithTextBesideAttachment(t *testing.T) { + for name, attachment := range map[string]string{"file url": chatTurnFileURL, "audio without bytes": chatTurnNoAudio} { + t.Run(name, func(t *testing.T) { + input := chatPayload("", chatTurnHello, chatTurnAssistant, chatUserTurn(chatTurnText, attachment)) + body, err := convertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5", input, false) + if err != nil { + t.Fatalf("err = %v", err) + } + if got := gjson.GetBytes(body, "messages.2.content.0.text").String(); got != "keep me" { + t.Fatalf("text was lost: %s", body) + } + }) + } +} + +func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_MappedAttachmentBesideTextKeepsBoth(t *testing.T) { + input := chatPayload("", chatUserTurn(chatTurnText, chatTurnFileID, chatTurnAudio)) + body, err := convertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5", input, false) + if err != nil { + t.Fatalf("err = %v", err) + } + content := gjson.GetBytes(body, "messages.0.content") + if got := content.Get("#").Int(); got != 3 { + t.Fatalf("content = %s, want text, file and audio", content.Raw) + } +} + +func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_ExportedWrapperKeepsAJSONBody(t *testing.T) { + input := chatPayload("", chatUserTurn(chatTurnFileURL)) + if body := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5", input, false); !gjson.ValidBytes(body) { + t.Fatalf("body is not JSON: %q", body) + } +} From 34e73c75a3a4f9d6b5d7c2c98c44fdffcc060ec9 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Thu, 8 Oct 2026 02:39:32 +0800 Subject: [PATCH 093/142] fix(xai): add proxy support and semver validation to Grok CLI updater - Pass configured proxy URL to the npm registry updater client - Validate fetched versions against strict semver and minimum server version floor (`1.0.13`) - Update default fallback client version to `1.0.46` - Manage background updater lifecycle and context via service lifecycle initialization --- cmd/server/main.go | 3 - .../runtime/executor/helps/xai_version.go | 151 +++++++++--- .../executor/helps/xai_version_test.go | 214 ++++++++++++++++-- .../executor/xai_client_version_test.go | 2 +- internal/runtime/executor/xai_executor.go | 5 +- sdk/cliproxy/service_lifecycle.go | 4 +- 6 files changed, 324 insertions(+), 55 deletions(-) diff --git a/cmd/server/main.go b/cmd/server/main.go index 507f7b66d38..3bcd5e0d7a7 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -32,7 +32,6 @@ import ( "github.com/router-for-me/CLIProxyAPI/v8/internal/pluginhost" "github.com/router-for-me/CLIProxyAPI/v8/internal/redisqueue" "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" - "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor" "github.com/router-for-me/CLIProxyAPI/v8/internal/safemode" "github.com/router-for-me/CLIProxyAPI/v8/internal/store" _ "github.com/router-for-me/CLIProxyAPI/v8/internal/translator" @@ -752,7 +751,6 @@ func main() { // Standalone mode: start an embedded local server and connect TUI client to it. managementasset.StartAutoUpdater(context.Background(), configFilePath) misc.StartAntigravityVersionUpdater(context.Background()) - executor.StartXAIVersionUpdater(context.Background()) registry.SetLocalModelCatalogs(localModel) hook := tui.NewLogHook(2000) hook.SetFormatter(&logging.LogFormatter{}) @@ -828,7 +826,6 @@ func main() { // Start the main proxy service managementasset.StartAutoUpdater(context.Background(), configFilePath) misc.StartAntigravityVersionUpdater(context.Background()) - executor.StartXAIVersionUpdater(context.Background()) registry.SetLocalModelCatalogs(localModel) cmd.StartServiceWithPluginHost(cfg, configFilePath, password, pluginHost, serverOptions...) } diff --git a/internal/runtime/executor/helps/xai_version.go b/internal/runtime/executor/helps/xai_version.go index 9e70163ac70..f6d1e83fb03 100644 --- a/internal/runtime/executor/helps/xai_version.go +++ b/internal/runtime/executor/helps/xai_version.go @@ -6,18 +6,23 @@ import ( "fmt" "io" "net/http" + "strconv" "strings" "sync" - "testing" "time" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" log "github.com/sirupsen/logrus" "github.com/tidwall/gjson" ) const ( - // DefaultXAIFallbackClientVersion is the fallback Grok CLI version when npm registry resolution fails. - DefaultXAIFallbackClientVersion = "1.0.50" + // DefaultXAIFallbackClientVersion is the stable Grok CLI version used when npm + // registry resolution fails. dist-tag latest is 1.0.46; 1.0.50 is the alpha tag. + DefaultXAIFallbackClientVersion = "1.0.46" + // XAIClientVersionServerFloor is the minimum Grok CLI version cli-chat-proxy accepts. + // Older clients are rejected with HTTP 426 (#6249). + XAIClientVersionServerFloor = "1.0.13" // XAIVersionRefreshInterval is the periodic interval to check for Grok CLI updates from npm. XAIVersionRefreshInterval = 3 * time.Hour // XAIVersionFetchTimeout is the maximum duration for a single npm registry lookup. @@ -30,12 +35,14 @@ var ( var ( cachedXAIClientVersion = DefaultXAIFallbackClientVersion + xaiVersionProxyURL string xaiClientVersionMu sync.RWMutex - xaiVersionUpdaterOnce sync.Once + xaiUpdaterCancel context.CancelFunc + xaiVersionRefreshed chan struct{} ) // GetXAIClientVersion returns the current Grok CLI client version. -// If the background updater has fetched a newer version from npm, it returns that version; +// If the background updater has fetched a newer acceptable version from npm, it returns that version; // otherwise it returns DefaultXAIFallbackClientVersion. func GetXAIClientVersion() string { xaiClientVersionMu.RLock() @@ -44,19 +51,26 @@ func GetXAIClientVersion() string { } // StartXAIVersionUpdater starts a background goroutine that periodically refreshes the Grok CLI version from npm. +// A later call cancels the previous goroutine and binds the new service context and proxy URL. // It executes a single fetch on startup and then polls every 3 hours without multiple retries on failure. -func StartXAIVersionUpdater(ctx context.Context) { - xaiVersionUpdaterOnce.Do(func() { - go runXAIVersionUpdater(ctx) - }) -} - -func runXAIVersionUpdater(ctx context.Context) { +func StartXAIVersionUpdater(ctx context.Context, proxyURL string) { if ctx == nil { ctx = context.Background() } + runCtx, cancel := context.WithCancel(ctx) + + xaiClientVersionMu.Lock() + if xaiUpdaterCancel != nil { + xaiUpdaterCancel() + } + xaiUpdaterCancel = cancel + xaiVersionProxyURL = strings.TrimSpace(proxyURL) + xaiClientVersionMu.Unlock() - // Fetch once on startup + go runXAIVersionUpdater(runCtx) +} + +func runXAIVersionUpdater(ctx context.Context) { refreshXAIClientVersion(ctx) ticker := time.NewTicker(XAIVersionRefreshInterval) @@ -75,25 +89,28 @@ func runXAIVersionUpdater(ctx context.Context) { } func refreshXAIClientVersion(ctx context.Context) { + defer notifyXAIVersionRefreshed() + version, errFetch := FetchXAINPMLatestVersion(ctx, nil) if errFetch != nil { log.WithError(errFetch).Warn("failed to fetch latest Grok CLI version from npm, keeping fallback/cached version") return } - if version == "" { - log.Warn("fetched empty Grok CLI version from npm, keeping fallback/cached version") - return - } - xaiClientVersionMu.Lock() - cachedXAIClientVersion = version + changed := cachedXAIClientVersion != version + if changed { + cachedXAIClientVersion = version + } xaiClientVersionMu.Unlock() - log.WithField("version", version).Info("updated Grok CLI client version from npm") + if changed { + log.WithField("version", version).Info("updated Grok CLI client version from npm") + } } // FetchXAINPMLatestVersion performs a single request to the npm registry to query the latest version of @xai-official/grok. +// The returned version is a strict numeric semver at or above XAIClientVersionServerFloor. func FetchXAINPMLatestVersion(ctx context.Context, client *http.Client) (string, error) { if ctx == nil { ctx = context.Background() @@ -114,7 +131,7 @@ func FetchXAINPMLatestVersion(ctx context.Context, client *http.Client) (string, req.Header.Set("User-Agent", "CLIProxyAPI") if client == nil { - client = &http.Client{Timeout: XAIVersionFetchTimeout} + client = xaiVersionHTTPClient() } resp, errDo := client.Do(req) @@ -140,12 +157,88 @@ func FetchXAINPMLatestVersion(ctx context.Context, client *http.Client) (string, if version == "" { return "", errors.New("version not found in npm response") } + if !acceptableXAIClientVersion(version) { + return "", fmt.Errorf("npm registry returned unacceptable Grok CLI version %s", strconv.Quote(version)) + } return version, nil } +func xaiVersionHTTPClient() *http.Client { + xaiClientVersionMu.RLock() + proxyURL := xaiVersionProxyURL + xaiClientVersionMu.RUnlock() + if strings.TrimSpace(proxyURL) == "" { + return &http.Client{Timeout: XAIVersionFetchTimeout} + } + return NewProxyAwareHTTPClient(context.Background(), &config.Config{SDKConfig: config.SDKConfig{ProxyURL: proxyURL}}, nil, XAIVersionFetchTimeout) +} + +func acceptableXAIClientVersion(version string) bool { + if !isStrictXAISemver(version) { + return false + } + return xaiVersionAtLeast(version, XAIClientVersionServerFloor) +} + +func isStrictXAISemver(version string) bool { + parts := strings.Split(version, ".") + if len(parts) != 3 { + return false + } + for _, part := range parts { + if part == "" { + return false + } + for _, ch := range part { + if ch < '0' || ch > '9' { + return false + } + } + } + return true +} + +func xaiVersionAtLeast(got, floor string) bool { + gotParts := strings.Split(got, ".") + floorParts := strings.Split(floor, ".") + for i := 0; i < len(gotParts) || i < len(floorParts); i++ { + var g, f int + var errG, errF error + if i < len(gotParts) { + g, errG = strconv.Atoi(gotParts[i]) + if errG != nil { + return false + } + } + if i < len(floorParts) { + f, errF = strconv.Atoi(floorParts[i]) + if errF != nil { + return false + } + } + if g != f { + return g > f + } + } + return true +} + +func notifyXAIVersionRefreshed() { + xaiClientVersionMu.RLock() + ch := xaiVersionRefreshed + xaiClientVersionMu.RUnlock() + if ch == nil { + return + } + select { + case ch <- struct{}{}: + default: + } +} + // OverrideXAINPMRegistryURLForTest overrides the npm registry URL for testing purposes. -func OverrideXAINPMRegistryURLForTest(t *testing.T, url string) func() { +func OverrideXAINPMRegistryURLForTest(url string) func() { xaiClientVersionMu.Lock() oldURL := xaiNPMRegistryURL xaiNPMRegistryURL = url @@ -158,7 +251,7 @@ func OverrideXAINPMRegistryURLForTest(t *testing.T, url string) func() { } // SetXAIClientVersionForTest sets the cached Grok CLI version directly for testing purposes. -func SetXAIClientVersionForTest(t *testing.T, version string) func() { +func SetXAIClientVersionForTest(version string) func() { xaiClientVersionMu.Lock() old := cachedXAIClientVersion cachedXAIClientVersion = version @@ -170,9 +263,15 @@ func SetXAIClientVersionForTest(t *testing.T, version string) func() { } } -// ResetXAIVersionUpdaterOnceForTest resets the sync.Once for testing updater initialization. -func ResetXAIVersionUpdaterOnceForTest(t *testing.T) { +// SetXAIVersionRefreshedHookForTest receives one signal after each refresh attempt. +func SetXAIVersionRefreshedHookForTest(ch chan struct{}) func() { xaiClientVersionMu.Lock() - xaiVersionUpdaterOnce = sync.Once{} + old := xaiVersionRefreshed + xaiVersionRefreshed = ch xaiClientVersionMu.Unlock() + return func() { + xaiClientVersionMu.Lock() + xaiVersionRefreshed = old + xaiClientVersionMu.Unlock() + } } diff --git a/internal/runtime/executor/helps/xai_version_test.go b/internal/runtime/executor/helps/xai_version_test.go index 700202ced16..cbcc5f44bd3 100644 --- a/internal/runtime/executor/helps/xai_version_test.go +++ b/internal/runtime/executor/helps/xai_version_test.go @@ -2,14 +2,16 @@ package helps import ( "context" + "io" "net/http" "net/http/httptest" + "strconv" + "sync/atomic" "testing" - "time" ) func TestGetXAIClientVersionDefault(t *testing.T) { - restore := SetXAIClientVersionForTest(t, DefaultXAIFallbackClientVersion) + restore := SetXAIClientVersionForTest(DefaultXAIFallbackClientVersion) defer restore() if got := GetXAIClientVersion(); got != DefaultXAIFallbackClientVersion { @@ -27,7 +29,7 @@ func TestFetchXAINPMLatestVersionSuccess(t *testing.T) { })) defer server.Close() - restore := OverrideXAINPMRegistryURLForTest(t, server.URL) + restore := OverrideXAINPMRegistryURLForTest(server.URL) defer restore() version, err := FetchXAINPMLatestVersion(context.Background(), server.Client()) @@ -45,7 +47,7 @@ func TestFetchXAINPMLatestVersionHttpError(t *testing.T) { })) defer server.Close() - restore := OverrideXAINPMRegistryURLForTest(t, server.URL) + restore := OverrideXAINPMRegistryURLForTest(server.URL) defer restore() _, err := FetchXAINPMLatestVersion(context.Background(), server.Client()) @@ -61,7 +63,7 @@ func TestFetchXAINPMLatestVersionMissingVersion(t *testing.T) { })) defer server.Close() - restore := OverrideXAINPMRegistryURLForTest(t, server.URL) + restore := OverrideXAINPMRegistryURLForTest(server.URL) defer restore() _, err := FetchXAINPMLatestVersion(context.Background(), server.Client()) @@ -71,7 +73,7 @@ func TestFetchXAINPMLatestVersionMissingVersion(t *testing.T) { } func TestRefreshXAIClientVersionKeepsFallbackOnError(t *testing.T) { - restoreVersion := SetXAIClientVersionForTest(t, "1.0.50") + restoreVersion := SetXAIClientVersionForTest("1.0.50") defer restoreVersion() server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -79,7 +81,7 @@ func TestRefreshXAIClientVersionKeepsFallbackOnError(t *testing.T) { })) defer server.Close() - restoreURL := OverrideXAINPMRegistryURLForTest(t, server.URL) + restoreURL := OverrideXAINPMRegistryURLForTest(server.URL) defer restoreURL() refreshXAIClientVersion(context.Background()) @@ -90,7 +92,7 @@ func TestRefreshXAIClientVersionKeepsFallbackOnError(t *testing.T) { } func TestRefreshXAIClientVersionUpdatesOnSuccess(t *testing.T) { - restoreVersion := SetXAIClientVersionForTest(t, "1.0.50") + restoreVersion := SetXAIClientVersionForTest("1.0.50") defer restoreVersion() server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -99,7 +101,7 @@ func TestRefreshXAIClientVersionUpdatesOnSuccess(t *testing.T) { })) defer server.Close() - restoreURL := OverrideXAINPMRegistryURLForTest(t, server.URL) + restoreURL := OverrideXAINPMRegistryURLForTest(server.URL) defer restoreURL() refreshXAIClientVersion(context.Background()) @@ -109,9 +111,123 @@ func TestRefreshXAIClientVersionUpdatesOnSuccess(t *testing.T) { } } +func TestRefreshXAIClientVersionAcceptsStableLatest(t *testing.T) { + restoreVersion := SetXAIClientVersionForTest("1.0.44") + defer restoreVersion() + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"version":"1.0.46"}`)) + })) + defer server.Close() + + restoreURL := OverrideXAINPMRegistryURLForTest(server.URL) + defer restoreURL() + + version, errFetch := FetchXAINPMLatestVersion(context.Background(), server.Client()) + if errFetch != nil { + t.Fatalf("FetchXAINPMLatestVersion() error = %v", errFetch) + } + if version != "1.0.46" { + t.Fatalf("FetchXAINPMLatestVersion() = %q, want 1.0.46", version) + } + refreshXAIClientVersion(context.Background()) + if got := GetXAIClientVersion(); got != "1.0.46" { + t.Fatalf("GetXAIClientVersion() = %q, want stable latest 1.0.46", got) + } +} + +func TestRefreshXAIClientVersionRejectsUnsafeVersions(t *testing.T) { + restoreVersion := SetXAIClientVersionForTest(DefaultXAIFallbackClientVersion) + defer restoreVersion() + + unsafeVersions := []string{ + "0.2.93", + "1.0.12", + "1.0.55-beta.1", + "1.0.55\r\nX-Injected: yes", + } + for _, unsafeVersion := range unsafeVersions { + t.Run(unsafeVersion, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"version":` + strconv.Quote(unsafeVersion) + `}`)) + })) + defer server.Close() + + restoreURL := OverrideXAINPMRegistryURLForTest(server.URL) + defer restoreURL() + + if _, errFetch := FetchXAINPMLatestVersion(context.Background(), server.Client()); errFetch == nil { + t.Fatal("FetchXAINPMLatestVersion() expected error for unsafe version, got nil") + } + refreshXAIClientVersion(context.Background()) + if got := GetXAIClientVersion(); got != DefaultXAIFallbackClientVersion { + t.Fatalf("GetXAIClientVersion() = %q, want fallback %s preserved", got, DefaultXAIFallbackClientVersion) + } + }) + } +} + +func TestRefreshXAIClientVersionUsesConfiguredProxy(t *testing.T) { + restoreVersion := SetXAIClientVersionForTest(DefaultXAIFallbackClientVersion) + defer restoreVersion() + + registry := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"version":"1.0.61"}`)) + })) + defer registry.Close() + + var proxied atomic.Bool + proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + proxied.Store(true) + if r.URL.Scheme == "" || r.URL.Host == "" { + http.Error(w, "expected absolute proxy URI", http.StatusBadRequest) + return + } + outbound, errReq := http.NewRequestWithContext(r.Context(), r.Method, r.URL.String(), nil) + if errReq != nil { + http.Error(w, errReq.Error(), http.StatusBadGateway) + return + } + outbound.Header = r.Header.Clone() + direct := &http.Client{Transport: &http.Transport{Proxy: nil}} + resp, errDo := direct.Do(outbound) + if errDo != nil { + http.Error(w, errDo.Error(), http.StatusBadGateway) + return + } + defer func() { + _ = resp.Body.Close() + }() + for key, values := range resp.Header { + for _, value := range values { + w.Header().Add(key, value) + } + } + w.WriteHeader(resp.StatusCode) + _, _ = io.Copy(w, resp.Body) + })) + defer proxyServer.Close() + + restoreURL := OverrideXAINPMRegistryURLForTest(registry.URL) + defer restoreURL() + restoreProxy := setXAIVersionProxyURLForTest(proxyServer.URL) + defer restoreProxy() + + refreshXAIClientVersion(context.Background()) + + if !proxied.Load() { + t.Fatal("expected npm lookup to use the configured proxy") + } + if got := GetXAIClientVersion(); got != "1.0.61" { + t.Fatalf("GetXAIClientVersion() = %q, want 1.0.61 via proxy", got) + } +} + func TestStartXAIVersionUpdaterLifecycle(t *testing.T) { - ResetXAIVersionUpdaterOnceForTest(t) - restoreVersion := SetXAIClientVersionForTest(t, "1.0.50") + restoreVersion := SetXAIClientVersionForTest(DefaultXAIFallbackClientVersion) defer restoreVersion() server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -120,24 +236,78 @@ func TestStartXAIVersionUpdaterLifecycle(t *testing.T) { })) defer server.Close() - restoreURL := OverrideXAINPMRegistryURLForTest(t, server.URL) + restoreURL := OverrideXAINPMRegistryURLForTest(server.URL) defer restoreURL() + notified := make(chan struct{}, 1) + restoreHook := SetXAIVersionRefreshedHookForTest(notified) + defer restoreHook() ctx, cancel := context.WithCancel(context.Background()) defer cancel() - StartXAIVersionUpdater(ctx) - - // Wait briefly for the startup fetch to settle - deadline := time.Now().Add(2 * time.Second) - for time.Now().Before(deadline) { - if GetXAIClientVersion() == "1.0.60" { - break - } - time.Sleep(20 * time.Millisecond) - } + StartXAIVersionUpdater(ctx, "") + waitXAIVersionRefresh(t, notified) if got := GetXAIClientVersion(); got != "1.0.60" { t.Fatalf("GetXAIClientVersion() = %q, want 1.0.60 after StartXAIVersionUpdater", got) } } + +func TestStartXAIVersionUpdaterRestartsWithNewContext(t *testing.T) { + restoreVersion := SetXAIClientVersionForTest(DefaultXAIFallbackClientVersion) + defer restoreVersion() + + var published atomic.Value + published.Store("1.0.70") + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + version, _ := published.Load().(string) + _, _ = w.Write([]byte(`{"version":` + strconv.Quote(version) + `}`)) + })) + defer server.Close() + + restoreURL := OverrideXAINPMRegistryURLForTest(server.URL) + defer restoreURL() + notified := make(chan struct{}, 2) + restoreHook := SetXAIVersionRefreshedHookForTest(notified) + defer restoreHook() + + ctx, cancel := context.WithCancel(context.Background()) + StartXAIVersionUpdater(ctx, "") + waitXAIVersionRefresh(t, notified) + if got := GetXAIClientVersion(); got != "1.0.70" { + cancel() + t.Fatalf("GetXAIClientVersion() = %q, want 1.0.70", got) + } + cancel() + + published.Store("1.0.71") + restartCtx, restartCancel := context.WithCancel(context.Background()) + defer restartCancel() + StartXAIVersionUpdater(restartCtx, "") + waitXAIVersionRefresh(t, notified) + if got := GetXAIClientVersion(); got != "1.0.71" { + t.Fatalf("GetXAIClientVersion() = %q, want 1.0.71 after restart", got) + } +} + +func waitXAIVersionRefresh(t *testing.T, notified <-chan struct{}) { + t.Helper() + select { + case <-notified: + case <-t.Context().Done(): + t.Fatal("timed out waiting for Grok CLI version refresh") + } +} + +func setXAIVersionProxyURLForTest(proxyURL string) func() { + xaiClientVersionMu.Lock() + old := xaiVersionProxyURL + xaiVersionProxyURL = proxyURL + xaiClientVersionMu.Unlock() + return func() { + xaiClientVersionMu.Lock() + xaiVersionProxyURL = old + xaiClientVersionMu.Unlock() + } +} diff --git a/internal/runtime/executor/xai_client_version_test.go b/internal/runtime/executor/xai_client_version_test.go index 6b153132a05..bc7f3eed088 100644 --- a/internal/runtime/executor/xai_client_version_test.go +++ b/internal/runtime/executor/xai_client_version_test.go @@ -77,7 +77,7 @@ func TestXAIChatProxyCustomHeadersOverridePinnedVersion(t *testing.T) { } func TestXAIChatProxyIdentityHeadersFollowDynamicVersion(t *testing.T) { - restore := helps.SetXAIClientVersionForTest(t, "1.2.34") + restore := helps.SetXAIClientVersionForTest("1.2.34") defer restore() auth := &cliproxyauth.Auth{ diff --git a/internal/runtime/executor/xai_executor.go b/internal/runtime/executor/xai_executor.go index 7f97b2b5441..d0ad9b744bc 100644 --- a/internal/runtime/executor/xai_executor.go +++ b/internal/runtime/executor/xai_executor.go @@ -85,8 +85,9 @@ func xaiClientVersion() string { } // StartXAIVersionUpdater starts the periodic Grok CLI version updater from npm. -func StartXAIVersionUpdater(ctx context.Context) { - helps.StartXAIVersionUpdater(ctx) +// proxyURL is the global outbound proxy; an empty value inherits the process environment. +func StartXAIVersionUpdater(ctx context.Context, proxyURL string) { + helps.StartXAIVersionUpdater(ctx, proxyURL) } // Identifier returns the provider identifier. diff --git a/sdk/cliproxy/service_lifecycle.go b/sdk/cliproxy/service_lifecycle.go index 631e56f2c67..250c75c155b 100644 --- a/sdk/cliproxy/service_lifecycle.go +++ b/sdk/cliproxy/service_lifecycle.go @@ -395,8 +395,10 @@ func (s *Service) startModelCatalogUpdaters(ctx context.Context) { s.cfgMu.RLock() cfg := s.cfg s.cfgMu.RUnlock() + proxyURL := "" if cfg != nil { registry.StartModelCatalogUpdaters(ctx, cfg.Models, cfg.Home.Enabled) + proxyURL = cfg.ProxyURL } - executor.StartXAIVersionUpdater(ctx) + executor.StartXAIVersionUpdater(ctx, proxyURL) } From 0f96f568e4dbf6f84ad7399a74b78344c5eac7e6 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Thu, 8 Oct 2026 03:00:04 +0800 Subject: [PATCH 094/142] refactor(translator): update openai and interactions request converters to return errors - Update OpenAI and OpenAI Responses to Interactions request converters to return `([]byte, error)` - Register request converters directly in internal translator registry instead of sdktranslator checked requests --- examples/custom-provider/main.go | 2 +- .../executor/antigravity_caqs_replay_test.go | 2 +- .../antigravity_schema_sanitize_test.go | 4 +- .../executor/codex_executor_translate_test.go | 8 +- .../runtime/executor/devin_executor_test.go | 4 +- .../gemini_interactions_translate_test.go | 4 +- .../executor/helps/codex_multi_agent_v2.go | 12 +- .../helps/request_pair_compat_test.go | 4 +- .../thinking/claude_enabled_effort_test.go | 2 +- .../claude/antigravity_claude_request.go | 6 +- .../claude/antigravity_claude_request_test.go | 188 +++++++-------- .../antigravity_claude_response_test.go | 16 +- .../antigravity_claude_user_turn_test.go | 2 +- .../translator/antigravity/claude/init.go | 4 +- .../gemini/antigravity_gemini_request.go | 6 +- .../gemini/antigravity_gemini_request_test.go | 34 +-- .../gemini/noop_optimization_test.go | 2 +- .../antigravity/interactions/init.go | 4 +- ...interactions_antigravity_file_data_test.go | 2 +- .../interactions_antigravity_request.go | 6 +- .../interactions_antigravity_test.go | 42 ++-- .../interactions_antigravity_uri_test.go | 2 +- .../antigravity_openai_file_data_test.go | 2 +- .../antigravity_openai_request.go | 6 +- .../antigravity_openai_request_test.go | 50 ++-- .../antigravity_openai_user_turn_test.go | 2 +- .../openai/chat-completions/init.go | 4 +- .../antigravity_openai-responses_request.go | 12 +- ...tigravity_openai-responses_request_test.go | 82 +++---- ...igravity_openai-responses_response_test.go | 2 +- ...gravity_openai-responses_user_turn_test.go | 2 +- .../claude/gemini/claude_gemini_request.go | 6 +- .../gemini/claude_gemini_request_test.go | 36 +-- .../gemini/claude_gemini_user_turn_test.go | 2 +- internal/translator/claude/gemini/init.go | 4 +- .../translator/claude/interactions/init.go | 4 +- .../interactions_claude_request.go | 6 +- .../interactions/interactions_claude_test.go | 16 +- .../interactions_claude_user_turn_test.go | 2 +- .../claude_openai_compat_test.go | 4 +- .../chat-completions/claude_openai_request.go | 15 +- .../claude_openai_request_test.go | 96 ++++---- .../claude_openai_user_turn_test.go | 6 +- .../claude/openai/chat-completions/init.go | 6 +- ...penai-responses_interleaved_search_test.go | 2 +- ...e_openai-responses_reasoning_order_test.go | 14 +- .../claude_openai-responses_request.go | 15 +- .../claude_openai-responses_request_test.go | 217 +++++++++++------- ...laude_openai-responses_server_tool_test.go | 22 +- .../claude_openai-responses_user_turn_test.go | 16 +- .../claude_openai_responses_compat_test.go | 6 +- .../claude/openai/responses/init.go | 6 +- .../codex/claude/codex_claude_compat_test.go | 30 +-- .../codex/claude/codex_claude_request.go | 14 +- .../codex_claude_request_benchmark_test.go | 2 +- .../codex/claude/codex_claude_request_test.go | 52 ++--- .../claude/codex_claude_user_turn_test.go | 10 +- internal/translator/codex/claude/init.go | 6 +- .../codex/claude/noop_optimization_test.go | 2 +- .../codex/gemini/codex_gemini_request.go | 4 +- .../codex/gemini/codex_gemini_request_test.go | 14 +- .../translator/codex/interactions/init.go | 4 +- .../interactions_codex_request.go | 6 +- .../interactions/interactions_codex_test.go | 10 +- .../interactions_codex_uri_test.go | 2 +- .../chat-completions/codex_openai_request.go | 6 +- .../codex_openai_request_test.go | 66 +++--- .../codex_openai_response_test.go | 2 +- .../codex_openai_user_turn_test.go | 2 +- .../codex/openai/chat-completions/init.go | 4 +- .../codex_openai-responses_request.go | 4 +- .../codex_openai-responses_request_test.go | 52 ++--- .../claude/gemini_claude_compat_test.go | 6 +- .../gemini/claude/gemini_claude_request.go | 14 +- .../claude/gemini_claude_request_test.go | 48 ++-- .../claude/gemini_claude_user_turn_test.go | 6 +- internal/translator/gemini/claude/init.go | 6 +- .../gemini/gemini/gemini_gemini_request.go | 6 +- .../gemini/gemini_gemini_request_test.go | 10 +- .../translator/gemini/interactions/init.go | 7 +- .../interactions_gemini_common.go | 12 +- .../interactions_gemini_common_test.go | 86 +++---- .../interactions_gemini_file_data_test.go | 2 +- .../interactions_gemini_response.go | 4 +- .../interactions_gemini_uri_test.go | 2 +- .../interactions_gemini_user_turn_test.go | 2 +- .../gemini_openai_file_data_test.go | 2 +- .../chat-completions/gemini_openai_request.go | 6 +- .../gemini_openai_request_test.go | 82 +++---- .../gemini_openai_signature_test.go | 2 +- .../gemini/openai/chat-completions/init.go | 4 +- .../noop_optimization_test.go | 2 +- .../openai/responses/apply_patch_test.go | 2 +- .../gemini_openai-responses_request.go | 10 +- .../gemini_openai-responses_request_test.go | 168 +++++++------- .../gemini_openai-responses_response_test.go | 34 +-- .../gemini_openai-responses_user_turn_test.go | 8 +- ...gemini_openai-responses_web_search_test.go | 14 +- .../gemini/openai/responses/init.go | 4 +- .../responses/noop_optimization_test.go | 2 +- .../responses/signature_carrier_test.go | 14 +- .../responses/trailing_signature_test.go | 14 +- .../translator/interactions/claude/init.go | 6 +- .../claude/interactions_claude_compat_test.go | 4 +- .../claude/interactions_claude_request.go | 14 +- .../claude/interactions_claude_test.go | 14 +- .../interactions_claude_user_turn_test.go | 10 +- internal/translator/openai/claude/init.go | 6 +- .../claude/openai_claude_compat_test.go | 12 +- .../openai/claude/openai_claude_request.go | 14 +- .../claude/openai_claude_request_test.go | 70 +++--- .../claude/openai_claude_user_turn_test.go | 8 +- .../openai/gemini/openai_gemini_request.go | 4 +- .../gemini/openai_gemini_request_test.go | 32 +-- .../interactions/chat-completions/init.go | 4 +- .../interactions_openai_request.go | 4 +- .../interactions_openai_request_test.go | 28 +-- .../openai_interactions_file_data_test.go | 4 +- .../openai_interactions_request.go | 6 +- .../openai_interactions_user_turn_test.go | 2 +- .../responses/apply_patch_test.go | 12 +- .../openai/interactions/responses/init.go | 4 +- .../interactions_openai_responses_request.go | 10 +- ...eractions_openai_responses_request_test.go | 66 +++--- ...actions_openai_responses_user_turn_test.go | 2 +- .../chat-completions/openai_openai_request.go | 8 +- .../openai_openai_request_test.go | 4 +- .../custom_tool_namespace_recovery_test.go | 2 +- .../openai/openai/responses/init.go | 4 +- .../openai_openai-responses_request.go | 6 +- .../openai_openai-responses_request_test.go | 158 ++++++------- .../openai_openai-responses_user_turn_test.go | 2 +- .../openai_openai-responses_video_test.go | 4 +- .../responses_compatibility_digest_test.go | 6 +- .../openai/responses/shell_tool_test.go | 12 +- sdk/api/handlers/openai/openai_handlers.go | 2 +- sdk/translator/registry.go | 11 +- sdk/translator/registry_summary_test.go | 16 +- sdk/translator/registry_test.go | 28 +-- sdk/translator/types.go | 9 +- 140 files changed, 1237 insertions(+), 1261 deletions(-) diff --git a/examples/custom-provider/main.go b/examples/custom-provider/main.go index 984175f607b..98184e28173 100644 --- a/examples/custom-provider/main.go +++ b/examples/custom-provider/main.go @@ -50,7 +50,7 @@ const ( // transformation logic between OpenAI format and your provider's format. func init() { sdktr.Register(fOpenAI, fMyProv, - func(model string, raw []byte, stream bool) []byte { return raw }, + func(model string, raw []byte, stream bool) ([]byte, error) { return raw, nil }, sdktr.ResponseTransform{ Stream: func(ctx context.Context, model string, originalReq, translatedReq, raw []byte, param *any) [][]byte { return [][]byte{raw} diff --git a/internal/runtime/executor/antigravity_caqs_replay_test.go b/internal/runtime/executor/antigravity_caqs_replay_test.go index 7190604945e..57c7fd53848 100644 --- a/internal/runtime/executor/antigravity_caqs_replay_test.go +++ b/internal/runtime/executor/antigravity_caqs_replay_test.go @@ -133,7 +133,7 @@ func TestAntigravityExecutorCAQSTwoTurnReplay(t *testing.T) { cache.CacheSignature(model, text, sig) t.Cleanup(func() { _ = cache.DeleteCachedSignatureRequired(context.Background(), model, text) }) recovery := []byte(`{"model":"claude-opus-5-5-high","messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"caqs-cache-recovery-test"}]},{"role":"user","content":"continue"}]}`) - recovered := antigravityclaude.ConvertClaudeRequestToAntigravity(model, recovery, false) + recovered, _ := antigravityclaude.ConvertClaudeRequestToAntigravity(model, recovery, false) if gjson.GetBytes(recovered, "request.contents.0.parts.0.thoughtSignature").String() != sig { t.Fatal("cache recovery changed original signature") } diff --git a/internal/runtime/executor/antigravity_schema_sanitize_test.go b/internal/runtime/executor/antigravity_schema_sanitize_test.go index ae000ef46f7..aa8b43f96e9 100644 --- a/internal/runtime/executor/antigravity_schema_sanitize_test.go +++ b/internal/runtime/executor/antigravity_schema_sanitize_test.go @@ -340,7 +340,7 @@ func TestSanitizeAntigravityToolSchemasKeepNativeTypeAndNullableOnBothPaths(t *t func TestAntigravityBuildRequestKeepsJSONObjectMimeOnly(t *testing.T) { input := []byte(`{"model":"gemini-3.1-pro-low","messages":[{"role":"user","content":"hi"}],"response_format":{"type":"json_object"}}`) - translated := antigravitychat.ConvertOpenAIRequestToAntigravity("gemini-3.1-pro-low", input, false) + translated, _ := antigravitychat.ConvertOpenAIRequestToAntigravity("gemini-3.1-pro-low", input, false) body := buildRequestBodyFromRawPayload(t, "gemini-3.1-pro-low", translated) encoded, errMarshal := json.Marshal(body) if errMarshal != nil { @@ -396,7 +396,7 @@ func TestAntigravityBuildRequestSanitizesSnakeCaseGenerationResponseSchemas(t *t } { t.Run(testCase.alias, func(t *testing.T) { input := []byte(`{"model":"gemini-3.6-flash-high","messages":[{"role":"user","content":"hi"}],"generation_config":{"` + testCase.alias + `":{"type":"object","$id":"drop-me","properties":{"title":{"type":"string"}}}}}`) - translated := antigravitychat.ConvertOpenAIRequestToAntigravity("gemini-3.6-flash-high", input, false) + translated, _ := antigravitychat.ConvertOpenAIRequestToAntigravity("gemini-3.6-flash-high", input, false) body := buildRequestBodyFromRawPayload(t, "gemini-3.6-flash-high", translated) encoded, errMarshal := json.Marshal(body) if errMarshal != nil { diff --git a/internal/runtime/executor/codex_executor_translate_test.go b/internal/runtime/executor/codex_executor_translate_test.go index 7b9180514cd..c229a035c8c 100644 --- a/internal/runtime/executor/codex_executor_translate_test.go +++ b/internal/runtime/executor/codex_executor_translate_test.go @@ -12,7 +12,7 @@ func TestTranslateCodexRequestPairReusesEqualPayload(t *testing.T) { from := sdktranslator.Format("codex-test-from-equal") to := sdktranslator.Format("codex-test-to-equal") var calls int32 - sdktranslator.Register(from, to, func(model string, rawJSON []byte, stream bool) []byte { + sdktranslator.Register(from, to, func(model string, rawJSON []byte, stream bool) ([]byte, error) { atomic.AddInt32(&calls, 1) if model != "test-model" { t.Errorf("model = %q, want test-model", model) @@ -20,7 +20,7 @@ func TestTranslateCodexRequestPairReusesEqualPayload(t *testing.T) { if !stream { t.Error("stream = false, want true") } - return append([]byte(nil), rawJSON...) + return append([]byte(nil), rawJSON...), nil }, sdktranslator.ResponseTransform{}) payload := []byte(`{"model":"test-model","input":[{"role":"user"}]}`) @@ -38,9 +38,9 @@ func TestTranslateCodexRequestPairTranslatesDifferentPayloads(t *testing.T) { from := sdktranslator.Format("codex-test-from-different") to := sdktranslator.Format("codex-test-to-different") var calls int32 - sdktranslator.Register(from, to, func(_ string, rawJSON []byte, _ bool) []byte { + sdktranslator.Register(from, to, func(_ string, rawJSON []byte, _ bool) ([]byte, error) { atomic.AddInt32(&calls, 1) - return append([]byte(nil), rawJSON...) + return append([]byte(nil), rawJSON...), nil }, sdktranslator.ResponseTransform{}) originalPayload := []byte(`{"model":"test-model","input":[{"role":"system"}]}`) diff --git a/internal/runtime/executor/devin_executor_test.go b/internal/runtime/executor/devin_executor_test.go index f3b78153848..37a09e85342 100644 --- a/internal/runtime/executor/devin_executor_test.go +++ b/internal/runtime/executor/devin_executor_test.go @@ -2381,7 +2381,7 @@ func TestDevinExecutor_ClaudeToolResultEndToEnd(t *testing.T) { }`) // Real conversion from Claude request to Interactions format - interactionsJSON := interactionsclaude.ConvertClaudeRequestToInteractions("devin/swe-2", claudeReq, true) + interactionsJSON, _ := interactionsclaude.ConvertClaudeRequestToInteractions("devin/swe-2", claudeReq, true) systemPrompt, prompts, tools, temp, maxTokens, sessionID, cascadeID, _, _ := parseInteractionsPayload(interactionsJSON, claudeReq) @@ -2715,7 +2715,7 @@ func TestDevinExecutor_ClaudeToolResultMixedBusinessJSONEndToEnd(t *testing.T) { ] }`) - interactionsJSON := interactionsclaude.ConvertClaudeRequestToInteractions("devin/swe-2", claudeReq, false) + interactionsJSON, _ := interactionsclaude.ConvertClaudeRequestToInteractions("devin/swe-2", claudeReq, false) _, prompts, _, _, _, _, _, _, _ := parseInteractionsPayload(interactionsJSON, claudeReq) if len(prompts) != 2 { diff --git a/internal/runtime/executor/gemini_interactions_translate_test.go b/internal/runtime/executor/gemini_interactions_translate_test.go index 2b4b7b091ca..6d9af4ba2e3 100644 --- a/internal/runtime/executor/gemini_interactions_translate_test.go +++ b/internal/runtime/executor/gemini_interactions_translate_test.go @@ -80,7 +80,7 @@ func TestTranslateGeminiInteractionsRequestPairTranslatesSameSliceOnce(t *testin const model = "gemini-interactions-count" var calls int var wantStream bool - sdktranslator.Register(from, to, func(gotModel string, rawJSON []byte, stream bool) []byte { + sdktranslator.Register(from, to, func(gotModel string, rawJSON []byte, stream bool) ([]byte, error) { if gotModel != model { t.Errorf("model = %q, want %q", gotModel, model) } @@ -88,7 +88,7 @@ func TestTranslateGeminiInteractionsRequestPairTranslatesSameSliceOnce(t *testin t.Errorf("stream = %v, want %v", stream, wantStream) } calls++ - return append([]byte(nil), rawJSON...) + return append([]byte(nil), rawJSON...), nil }, sdktranslator.ResponseTransform{}) t.Cleanup(func() { sdktranslator.Unregister(from, to) }) diff --git a/internal/runtime/executor/helps/codex_multi_agent_v2.go b/internal/runtime/executor/helps/codex_multi_agent_v2.go index b9cc92c138f..58ab21ddff7 100644 --- a/internal/runtime/executor/helps/codex_multi_agent_v2.go +++ b/internal/runtime/executor/helps/codex_multi_agent_v2.go @@ -192,17 +192,17 @@ func translateRequestWithAPIKeyModelCompatibilityForExecutor(ctx context.Context var convertErr error switch { case from == sdktranslator.FormatClaude && to == sdktranslator.FormatCodex: - translated, convertErr = codexclaude.ConvertClaudeRequestToCodexWithCompatReturningError(model, payload, stream) + translated, convertErr = codexclaude.ConvertClaudeRequestToCodexWithCompat(model, payload, stream) case from == sdktranslator.FormatClaude && to == sdktranslator.FormatGemini: - translated, convertErr = geminiclaude.ConvertClaudeRequestToGeminiWithCompatReturningError(model, payload, stream) + translated, convertErr = geminiclaude.ConvertClaudeRequestToGeminiWithCompat(model, payload, stream) case from == sdktranslator.FormatClaude && to == sdktranslator.FormatInteractions: - translated, convertErr = interactionsclaude.ConvertClaudeRequestToInteractionsWithCompatReturningError(model, payload, stream) + translated, convertErr = interactionsclaude.ConvertClaudeRequestToInteractionsWithCompat(model, payload, stream) case from == sdktranslator.FormatClaude && to == sdktranslator.FormatOpenAI: - translated, convertErr = openaiclaude.ConvertClaudeRequestToOpenAIWithCompatReturningError(model, payload, stream) + translated, convertErr = openaiclaude.ConvertClaudeRequestToOpenAIWithCompat(model, payload, stream) case from == sdktranslator.FormatOpenAI && to == sdktranslator.FormatClaude: - translated, convertErr = openaichatclaude.ConvertOpenAIRequestToClaudeWithCompatReturningError(model, payload, stream) + translated, convertErr = openaichatclaude.ConvertOpenAIRequestToClaudeWithCompat(model, payload, stream) case from == sdktranslator.FormatOpenAIResponse && to == sdktranslator.FormatClaude: - translated, convertErr = responsesclaude.ConvertOpenAIResponsesRequestToClaudeWithCompatReturningError(model, payload, stream) + translated, convertErr = responsesclaude.ConvertOpenAIResponsesRequestToClaudeWithCompat(model, payload, stream) default: return translateRequestWithCodexMultiAgentV2Checked(ctx, headers, cfg, from, to, model, payload, stream) } diff --git a/internal/runtime/executor/helps/request_pair_compat_test.go b/internal/runtime/executor/helps/request_pair_compat_test.go index 84a3e8cf58e..2e3db0422df 100644 --- a/internal/runtime/executor/helps/request_pair_compat_test.go +++ b/internal/runtime/executor/helps/request_pair_compat_test.go @@ -49,7 +49,7 @@ func TestTranslateRequestPairWithAPIKeyModelCompatibilityCountsTranslations(t *t const model = "compat-count-model" var calls int var wantStream bool - sdktranslator.Register(from, to, func(gotModel string, rawJSON []byte, stream bool) []byte { + sdktranslator.Register(from, to, func(gotModel string, rawJSON []byte, stream bool) ([]byte, error) { if gotModel != model { t.Errorf("model = %q, want %q", gotModel, model) } @@ -57,7 +57,7 @@ func TestTranslateRequestPairWithAPIKeyModelCompatibilityCountsTranslations(t *t t.Errorf("stream = %v, want %v", stream, wantStream) } calls++ - return append([]byte(nil), rawJSON...) + return append([]byte(nil), rawJSON...), nil }, sdktranslator.ResponseTransform{}) t.Cleanup(func() { sdktranslator.Unregister(from, to) }) diff --git a/internal/thinking/claude_enabled_effort_test.go b/internal/thinking/claude_enabled_effort_test.go index 10044747e55..ac50cdfc5e0 100644 --- a/internal/thinking/claude_enabled_effort_test.go +++ b/internal/thinking/claude_enabled_effort_test.go @@ -63,7 +63,7 @@ func TestApplyThinking_ClaudeEnabledWithOutputConfigEffort(t *testing.T) { func TestClaudeToOpenAITranslationAndThinkingChained(t *testing.T) { rawClaude := []byte(`{"model":"custom-openai","messages":[{"role":"user","content":"hi"}],"thinking":{"type":"enabled"},"output_config":{"effort":"high"}}`) - translated := openaiclaude.ConvertClaudeRequestToOpenAI("custom-openai", rawClaude, false) + translated, _ := openaiclaude.ConvertClaudeRequestToOpenAI("custom-openai", rawClaude, false) if got := gjson.GetBytes(translated, "reasoning_effort").String(); got != "high" { t.Fatalf("translated reasoning_effort = %q, want high; body=%s", got, translated) } diff --git a/internal/translator/antigravity/claude/antigravity_claude_request.go b/internal/translator/antigravity/claude/antigravity_claude_request.go index ac4e130f50b..d2595f89cf3 100644 --- a/internal/translator/antigravity/claude/antigravity_claude_request.go +++ b/internal/translator/antigravity/claude/antigravity_claude_request.go @@ -305,9 +305,9 @@ func logDroppedAntigravityToolUseSignature(modelName string, messageIndex, conte // // Returns: // - []byte: The transformed request data in Antigravity API format -func ConvertClaudeRequestToAntigravity(modelName string, inputRawJSON []byte, stream bool) []byte { - body, _ := convertClaudeRequestToAntigravity(modelName, inputRawJSON, stream) - return body +func ConvertClaudeRequestToAntigravity(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { + return convertClaudeRequestToAntigravity(modelName, inputRawJSON, stream) + } // convertClaudeRequestToAntigravity also reports an attachment Antigravity diff --git a/internal/translator/antigravity/claude/antigravity_claude_request_test.go b/internal/translator/antigravity/claude/antigravity_claude_request_test.go index 3d81f9ae849..4a60074f4aa 100644 --- a/internal/translator/antigravity/claude/antigravity_claude_request_test.go +++ b/internal/translator/antigravity/claude/antigravity_claude_request_test.go @@ -123,7 +123,7 @@ func TestConvertClaudeRequestToAntigravity_StripsClaudeCodeAttribution(t *testin ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) outputStr := string(output) parts := gjson.Get(outputStr, "request.systemInstruction.parts").Array() @@ -146,7 +146,7 @@ func TestConvertClaudeRequestToAntigravity_ConvertsMessageSystemRoleToUserConten ] }`) - output := ConvertClaudeRequestToAntigravity("gemini-3-flash-agent", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3-flash-agent", inputJSON, false) outputStr := string(output) if systemContent := gjson.Get(outputStr, `request.contents.#(role=="system")`); systemContent.Exists() { @@ -194,7 +194,7 @@ func TestConvertClaudeRequestToAntigravity_MessageLevelDeveloperInstructionsBeco ] }`) - output := ConvertClaudeRequestToAntigravity("gemini-3.5-flash", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3.5-flash", inputJSON, false) outputStr := string(output) if devContent := gjson.Get(outputStr, `request.contents.#(role=="developer")`); devContent.Exists() { @@ -260,7 +260,7 @@ func TestConvertClaudeRequestToAntigravity_PreservesToolPairingWithInterveningSy ] }`) - output := ConvertClaudeRequestToAntigravity("gemini-3.5-flash", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3.5-flash", inputJSON, false) if errPairing := internalsignature.ValidateGeminiFunctionCallPairing(output); errPairing != nil { t.Fatalf("ValidateGeminiFunctionCallPairing failed: %v\noutput: %s", errPairing, output) @@ -309,7 +309,7 @@ func TestConvertClaudeRequestToAntigravity_MapsTypedWebSearchToIndependentSearch "tools": [{"type": "web_search_20250305", "name": "web_search", "max_uses": 8, "allowed_domains": ["www.baidu.com", "weather.com.cn"]}] }`) - output := ConvertClaudeRequestToAntigravity("gemini-3.1-flash-lite", inputJSON, true) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3.1-flash-lite", inputJSON, true) if got := gjson.GetBytes(output, "requestType").String(); got != "web_search" { t.Fatalf("requestType = %q, want web_search: %s", got, output) } @@ -345,7 +345,7 @@ func TestConvertClaudeRequestToAntigravity_UsesDefaultWebSearchMaxResultCountWit "tools": [{"type": "web_search_20250305", "name": "web_search"}] }`) - output := ConvertClaudeRequestToAntigravity("gemini-3.1-flash-lite", inputJSON, true) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3.1-flash-lite", inputJSON, true) if got := gjson.GetBytes(output, "request.tools.0.googleSearch.enhancedContent.imageSearch.maxResultCount").Int(); got != 5 { t.Fatalf("image search maxResultCount = %d, want default 5: %s", got, output) } @@ -366,7 +366,7 @@ func TestConvertClaudeRequestToAntigravity_DoesNotMapTypedWebSearchWhenMixedWith ] }`) - output := ConvertClaudeRequestToAntigravity("gemini-3.1-flash-lite", inputJSON, true) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3.1-flash-lite", inputJSON, true) if got := gjson.GetBytes(output, "requestType").String(); got == "web_search" { t.Fatalf("mixed tools should not become independent web_search request: %s", output) } @@ -391,7 +391,7 @@ func TestConvertClaudeRequestToAntigravity_DoesNotMapTypedWebSearchForUnsupporte "tools": [{"type": "web_search_20250305", "name": "web_search", "max_uses": 8}] }`) - output := ConvertClaudeRequestToAntigravity("gemini-3.5-flash", inputJSON, true) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3.5-flash", inputJSON, true) if got := gjson.GetBytes(output, "model").String(); got != "gemini-3.5-flash" { t.Fatalf("web search request model = %q, want original route model: %s", got, output) } @@ -413,7 +413,7 @@ func TestConvertClaudeRequestToAntigravity_DoesNotMapTypedWebSearchForFlashAgent "tools": [{"type": "web_search_20250305", "name": "web_search", "max_uses": 8}] }`) - output := ConvertClaudeRequestToAntigravity("gemini-3-flash-agent", inputJSON, true) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3-flash-agent", inputJSON, true) if got := gjson.GetBytes(output, "model").String(); got != "gemini-3-flash-agent" { t.Fatalf("web search request model = %q, want original route model: %s", got, output) } @@ -429,7 +429,7 @@ func TestConvertClaudeRequestToAntigravity_DoesNotMapTypedWebSearchForOtherModel "tools": [{"type": "web_search_20250305", "name": "web_search", "max_uses": 8}] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-6", inputJSON, true) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-6", inputJSON, true) if got := gjson.GetBytes(output, "request.tools.#(googleSearch)").Raw; got != "" { t.Fatalf("model without Antigravity web search capability should not get native googleSearch: %s", output) } @@ -483,7 +483,7 @@ func TestConvertClaudeRequestToAntigravity_ReattachesDetachedGeminiSignature(t * {"type":"thinking","thinking":"","signature":"` + geminiSig + `"} ]}] }`) - output := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) parts := gjson.GetBytes(output, "request.contents.0.parts").Array() if len(parts) != 1 { t.Fatalf("parts = %d, want one native text part; output=%s", len(parts), output) @@ -505,7 +505,7 @@ func TestConvertClaudeRequestToAntigravity_ReattachesLeadingDetachedGeminiSignat {"type":"text","text":"visible answer"} ]}] }`) - output := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) if got := gjson.GetBytes(output, "request.contents.0.parts.0.thoughtSignature").String(); got != geminiSig { t.Fatalf("leading detached signature = %q, want %q; output=%s", got, geminiSig, output) } @@ -515,13 +515,13 @@ func TestConvertClaudeRequestToAntigravity_DropsLegacyRawCarrierFromUserMessage( geminiSig := testGeminiEPrefixSignature(t) inputJSON := []byte(`{"model":"gemini-3.6-flash-high","messages":[{"role":"user","content":[{"type":"thinking","thinking":"","signature":"` + geminiSig + `"},{"type":"text","text":"user text"}]}]}`) filtered := StripInvalidGeminiSignatureThinkingBlocks(inputJSON) - output := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", filtered, true) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", filtered, true) parts := gjson.GetBytes(output, "request.contents.0.parts").Array() if len(parts) != 1 || parts[0].Get("text").String() != "user text" || parts[0].Get("thoughtSignature").Exists() { t.Fatalf("user legacy carrier reached Gemini after filtering: %s", output) } - directOutput := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) + directOutput, _ := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) directParts := gjson.GetBytes(directOutput, "request.contents.0.parts").Array() if len(directParts) != 1 || directParts[0].Get("text").String() != "user text" || directParts[0].Get("thoughtSignature").Exists() { t.Fatalf("user legacy carrier reached Gemini without prefilter: %s", directOutput) @@ -540,7 +540,7 @@ func TestConvertClaudeRequestToAntigravity_DistributesConsecutiveTrailingGeminiC {"type":"thinking","thinking":"","signature":"` + sig2 + `"} ]}] }`) - output := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) parts := gjson.GetBytes(output, "request.contents.0.parts").Array() if len(parts) != 3 { t.Fatalf("parts = %d, want two text parts + detached carrier; output=%s", len(parts), output) @@ -567,7 +567,7 @@ func TestConvertClaudeRequestToAntigravity_PreservesConsecutiveLeadingGeminiCarr {"type":"tool_use","id":"tool-1","name":"run_command","input":{"command":"true"}} ]}] }`) - output := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) parts := gjson.GetBytes(output, "request.contents.0.parts").Array() if len(parts) != 2 { t.Fatalf("parts = %d, want carrier + signed tool; output=%s", len(parts), output) @@ -590,7 +590,7 @@ func TestConvertClaudeRequestToAntigravity_DirectToolSignatureWinsOverLeadingCar {"type":"tool_use","id":"tool-1","name":"run_command","input":{"command":"true"},"signature":"` + directSig + `"} ]}] }`) - output := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) parts := gjson.GetBytes(output, "request.contents.0.parts").Array() if len(parts) != 2 { t.Fatalf("parts = %d, want carrier + directly signed tool; output=%s", len(parts), output) @@ -620,7 +620,7 @@ func TestConvertClaudeRequestToAntigravity_PreservesCarrierBetweenDirectlySigned {"type":"tool_use","id":"tool-2","name":"run_command","input":{"command":"two"},"signature":"` + sig3 + `"} ]}] }`) - output := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) parts := gjson.GetBytes(output, "request.contents.0.parts").Array() if len(parts) != 3 { t.Fatalf("parts = %d, want tool + carrier + tool; output=%s", len(parts), output) @@ -649,7 +649,7 @@ func TestConvertClaudeRequestToAntigravity_PreservesCarrierOnlyAssistantMessage( } { t.Run(tc.name, func(t *testing.T) { inputJSON := []byte(`{"model":"gemini-3.6-flash-high","messages":[{"role":"assistant","content":` + tc.content + `}]}`) - output := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) parts := gjson.GetBytes(output, "request.contents.0.parts").Array() if len(parts) != len(tc.signatures) { t.Fatalf("parts = %d, want %d carriers; output=%s", len(parts), len(tc.signatures), output) @@ -674,7 +674,7 @@ func TestConvertClaudeRequestToAntigravity_PreservesConsecutiveLeadingGeminiCarr {"type":"text","text":"visible"} ]}] }`) - output := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) parts := gjson.GetBytes(output, "request.contents.0.parts").Array() if len(parts) != 2 { t.Fatalf("parts = %d, want carrier + signed text; output=%s", len(parts), output) @@ -698,7 +698,7 @@ func TestConvertClaudeRequestToAntigravity_PreservesTrailingCarrierAfterSignedTo {"type":"thinking","thinking":"","signature":"` + sig2 + `"} ]}] }`) - output := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) parts := gjson.GetBytes(output, "request.contents.0.parts").Array() if len(parts) != 2 { t.Fatalf("parts = %d, want signed tool + trailing carrier; output=%s", len(parts), output) @@ -721,7 +721,7 @@ func TestConvertClaudeRequestToAntigravity_DetachedToolCarrierTargetsFollowingTo {"type":"tool_use","id":"claude-id","name":"run_command","input":{"command":"true"}} ]}] }`) - output := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) if got := gjson.GetBytes(output, "request.contents.0.parts.0.thoughtSignature").String(); got != "" { t.Fatalf("detached tool signature attached backward to text: %q; output=%s", got, output) } @@ -739,7 +739,7 @@ func TestConvertClaudeRequestToAntigravity_GeminiThinkingSignatureTargetsFollowi {"type":"text","text":"visible answer"} ]}] }`) - output := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) if got := gjson.GetBytes(output, "request.contents.0.parts.0.thoughtSignature").String(); got != "" { t.Fatalf("Gemini signature remained on thought part: %q; output=%s", got, output) } @@ -755,7 +755,7 @@ func TestConvertClaudeRequestToAntigravity_LeadingCarrierDoesNotCrossSignedThink signedThought := encodeGeminiClaudeCarrierSignature(signature2, geminiClaudeCarrierStandalone, geminiClaudeCarrierText) inputJSON := []byte(`{"model":"gemini-3.6-flash-high","messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"","signature":"` + leading + `"},{"type":"thinking","thinking":"reason","signature":"` + signedThought + `"},{"type":"text","text":"answer"}]}]}`) inputJSON = StripInvalidGeminiSignatureThinkingBlocks(inputJSON) - output := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) parts := gjson.GetBytes(output, "request.contents.0.parts").Array() if len(parts) != 3 || parts[0].Get("text").String() != "reason" || !parts[0].Get("thought").Bool() || parts[0].Get("thoughtSignature").String() != signature2 || !parts[1].Get("text").Exists() || parts[1].Get("text").String() != "" || parts[1].Get("thoughtSignature").String() != signature1 || parts[2].Get("text").String() != "answer" || parts[2].Get("thoughtSignature").String() != "" { t.Fatalf("leading carrier crossed signed thinking: %s", output) @@ -769,7 +769,7 @@ func TestConvertClaudeRequestToAntigravity_DropsMismatchedMarkedNonEmptyCarrier( `[{"type":"thinking","thinking":"hidden","signature":"` + encodeGeminiClaudeCarrierSignature(geminiSig, geminiClaudeCarrierStandalone, geminiClaudeCarrierFunction) + `"}]`, } { inputJSON := []byte(`{"model":"gemini-3.6-flash-high","messages":[{"role":"assistant","content":` + content + `}]}`) - output := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) if strings.Contains(string(output), geminiSig) || strings.Contains(string(output), geminiClaudeCarrierPrefix) { t.Fatalf("mismatched marked carrier reached Gemini wire: %s", output) } @@ -782,7 +782,7 @@ func TestConvertClaudeRequestToAntigravity_GeminiThoughtTextWithFollowingPreviou inputJSON := []byte(`{"model":"gemini-3.1-pro-preview","messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"let me think","signature":""},{"type":"text","text":"answer text"},{"type":"thinking","thinking":"","signature":"` + validCarrier + `"}]},{"role":"user","content":[{"type":"text","text":"continue"}]}]}`) inputJSON = StripInvalidGeminiSignatureThinkingBlocks(inputJSON) - output := ConvertClaudeRequestToAntigravity("gemini-3.1-pro-preview", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3.1-pro-preview", inputJSON, false) parts := gjson.GetBytes(output, "request.contents.0.parts").Array() if len(parts) != 2 { @@ -805,7 +805,7 @@ func TestConvertClaudeRequestToAntigravity_GeminiThinkingSignatureTargetsFollowi {"type":"tool_use","id":"claude-id","name":"run_command","input":{"command":"true"}} ]}] }`) - output := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) parts := gjson.GetBytes(output, "request.contents.0.parts").Array() if len(parts) != 2 || !parts[0].Get("thought").Bool() { t.Fatalf("thought/tool parts malformed: %s", output) @@ -827,7 +827,7 @@ func TestConvertClaudeRequestToAntigravity_PreservesGeminiToolSignature(t *testi {"type":"tool_use","id":"claude-id","name":"run_command","input":{"command":"true"} ]}] }`) - output := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) if got := gjson.GetBytes(output, "request.contents.0.parts.0.thoughtSignature").String(); got != geminiSig { t.Fatalf("tool signature = %q, want %q; output=%s", got, geminiSig, output) } @@ -844,7 +844,7 @@ func TestConvertClaudeRequestToAntigravity_NativeParallelToolLeavesUnsignedSibli ]}] }`) - output := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) parts := gjson.GetBytes(output, "request.contents.0.parts").Array() if len(parts) != 2 { t.Fatalf("parts = %d, want 2 function calls; output=%s", len(parts), output) @@ -866,7 +866,7 @@ func TestConvertClaudeRequestToAntigravity_SyntheticParallelToolOnlyFirstGetsSen ]}] }`) - output := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", inputJSON, true) parts := gjson.GetBytes(output, "request.contents.0.parts").Array() if len(parts) != 2 { t.Fatalf("parts = %d, want 2 function calls; output=%s", len(parts), output) @@ -895,7 +895,7 @@ func TestConvertClaudeRequestToAntigravity_BasicStructure(t *testing.T) { ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) outputStr := string(output) // Check model @@ -934,7 +934,7 @@ func TestConvertClaudeRequestToAntigravity_RoleMapping(t *testing.T) { ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) outputStr := string(output) // assistant should be mapped to model @@ -970,7 +970,7 @@ func TestConvertClaudeRequestToAntigravity_ThinkingBlocks(t *testing.T) { cache.CacheSignature("claude-sonnet-4-5-thinking", thinkingText, nativeSignature) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) outputStr := string(output) // Check thinking block conversion (now in contents.1 due to user message) @@ -1346,7 +1346,7 @@ func TestConvertClaudeRequestToAntigravity_BypassModeNormalizesESignature(t *tes ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) outputStr := string(output) part := gjson.Get(outputStr, "request.contents.0.parts.0") @@ -1382,7 +1382,7 @@ func TestConvertClaudeRequestToAntigravity_BypassModePreservesShortValidSignatur ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) parts := gjson.GetBytes(output, "request.contents.0.parts").Array() if len(parts) != 2 { t.Fatalf("expected thinking part to be preserved in bypass mode, got %d parts", len(parts)) @@ -1467,7 +1467,7 @@ func TestConvertClaudeRequestToAntigravity_CacheModeAcceptsNativeSignature(t *te ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) parts := gjson.GetBytes(output, "request.contents.0.parts").Array() if len(parts) != 2 { t.Fatalf("Expected native signature thinking block to be preserved in cache mode, got %d parts; output=%s", len(parts), output) @@ -1508,7 +1508,7 @@ func TestConvertClaudeRequestToAntigravity_CacheModeDropsInvalidSignature(t *tes ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) parts := gjson.GetBytes(output, "request.contents.0.parts").Array() if len(parts) != 1 { t.Fatalf("Expected invalid signature thinking block to be dropped in cache mode even if cache exists, got %d parts", len(parts)) @@ -1545,7 +1545,7 @@ func TestConvertClaudeRequestToAntigravity_CacheModeRecoversSignatureWhenClientO ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) parts := gjson.GetBytes(output, "request.contents.0.parts").Array() if len(parts) != 2 { t.Fatalf("Expected omitted signature thinking block to be recovered from cache, got %d parts; output=%s", len(parts), output) @@ -1581,7 +1581,7 @@ func TestConvertClaudeRequestToAntigravity_BypassModeDropsInvalidSignature(t *te ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) outputStr := string(output) parts := gjson.Get(outputStr, "request.contents.0.parts").Array() @@ -1620,7 +1620,7 @@ func TestConvertClaudeRequestToAntigravity_LogsDroppedInvalidThinkingSignature(t ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) parts := gjson.GetBytes(output, "request.contents.0.parts").Array() if len(parts) != 1 || parts[0].Get("text").String() != "Answer" { t.Fatalf("expected invalid thinking block to be dropped, output: %s", output) @@ -1671,7 +1671,7 @@ func TestConvertClaudeRequestToAntigravity_BypassModeDropsGeminiSignature(t *tes ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) parts := gjson.GetBytes(output, "request.contents.0.parts").Array() if len(parts) != 1 { t.Fatalf("expected Gemini-signed thinking block to be dropped, got %d parts", len(parts)) @@ -1704,7 +1704,7 @@ func TestConvertClaudeRequestToAntigravity_BypassModeDropsGeminiEPrefixSignature ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) parts := gjson.GetBytes(output, "request.contents.0.parts").Array() if len(parts) != 1 { t.Fatalf("expected Gemini E-prefix signed thinking block to be dropped, got %d parts: %s", len(parts), output) @@ -1734,7 +1734,7 @@ func TestConvertClaudeRequestToAntigravity_ThinkingBlockWithoutSignature(t *test ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) outputStr := string(output) // Without signature, thinking block should be removed (not converted to text) @@ -1771,7 +1771,7 @@ func TestConvertClaudeRequestToAntigravity_ToolDeclarations(t *testing.T) { ] }`) - output := ConvertClaudeRequestToAntigravity("gemini-1.5-pro", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("gemini-1.5-pro", inputJSON, false) outputStr := string(output) // Check tools structure @@ -1811,7 +1811,7 @@ func TestConvertClaudeRequestToAntigravity_DeduplicatesAndDisambiguatesTools(t * "tool_choice":{"type":"tool","name":"` + second + `"} }`) - out := ConvertClaudeRequestToAntigravity("gemini-3-flash", inputJSON, false) + out, _ := ConvertClaudeRequestToAntigravity("gemini-3-flash", inputJSON, false) declarations := gjson.GetBytes(out, "request.tools.0.functionDeclarations").Array() if len(declarations) != 3 { t.Fatalf("declaration count = %d, want 3. Output: %s", len(declarations), out) @@ -1844,7 +1844,7 @@ func TestConvertClaudeRequestToAntigravity_MapsToolResultNameOnce(t *testing.T) ] }`) - out := ConvertClaudeRequestToAntigravity("gemini-3-flash", inputJSON, false) + out, _ := ConvertClaudeRequestToAntigravity("gemini-3-flash", inputJSON, false) callName := gjson.GetBytes(out, "request.contents.0.parts.0.functionCall.name").String() responseName := gjson.GetBytes(out, "request.contents.1.parts.0.functionResponse.name").String() if callName == "" || responseName != callName { @@ -1876,7 +1876,7 @@ func TestConvertClaudeRequestToAntigravity_ToolChoice_SpecificTool(t *testing.T) "tool_choice": {"type": "tool", "name": "json"} }`) - output := ConvertClaudeRequestToAntigravity("gemini-3-flash-preview", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3-flash-preview", inputJSON, false) outputStr := string(output) if got := gjson.Get(outputStr, "request.toolConfig.functionCallingConfig.mode").String(); got != "ANY" { @@ -1906,7 +1906,7 @@ func TestConvertClaudeRequestToAntigravity_ToolUse(t *testing.T) { ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) outputStr := string(output) // Now we expect only 1 part (tool_use), no dummy thinking block injected @@ -1964,7 +1964,7 @@ func TestConvertClaudeRequestToAntigravity_ToolUsePreservesPresentNonObjectInput }] }`, inputField)) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) part := gjson.GetBytes(output, "request.contents.0.parts.0") functionCall := part.Get("functionCall") if tc.wantFunctionCall { @@ -2004,7 +2004,7 @@ func TestConvertClaudeRequestToAntigravity_ToolUse_DropsInvalidThoughtSignatureO ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) part := gjson.GetBytes(output, "request.contents.0.parts.0") if !part.Get("functionCall").Exists() { @@ -2065,7 +2065,7 @@ func TestConvertClaudeRequestToAntigravity_ToolUse_DoesNotReuseThinkingSignature cache.CacheSignature("claude-sonnet-4-5-thinking", thinkingText, nativeSignature) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) outputStr := string(output) part := gjson.Get(outputStr, "request.contents.1.parts.1") @@ -2103,7 +2103,7 @@ func TestConvertClaudeRequestToAntigravity_ReorderThinking(t *testing.T) { cache.CacheSignature("claude-sonnet-4-5-thinking", thinkingText, nativeSignature) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) outputStr := string(output) // Verify order: Thinking block MUST be first (now in contents.1 due to user message) @@ -2154,7 +2154,7 @@ func TestConvertClaudeRequestToAntigravity_ReorderTextAfterFunctionCall(t *testi ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) outputStr := string(output) parts := gjson.Get(outputStr, "request.contents.0.parts").Array() @@ -2203,7 +2203,7 @@ func TestConvertClaudeRequestToAntigravity_ReorderParallelFunctionCalls(t *testi ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) outputStr := string(output) parts := gjson.Get(outputStr, "request.contents.0.parts").Array() @@ -2250,7 +2250,7 @@ func TestConvertClaudeRequestToAntigravity_AlignsPermutedParallelToolResultsWith ] }`) - output := ConvertClaudeRequestToAntigravity("gemini-3.7-flash-high", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("gemini-3.7-flash-high", inputJSON, false) parts := gjson.GetBytes(output, "request.contents.1.parts").Array() if len(parts) != 8 { t.Fatalf("parts = %d, want eight parts; output=%s", len(parts), output) @@ -2310,7 +2310,7 @@ func TestConvertClaudeRequestToAntigravity_ReorderThinkingAndTextBeforeFunctionC cache.CacheSignature("claude-sonnet-4-5-thinking", thinkingText, nativeSignature) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) outputStr := string(output) // contents.1 = assistant message (contents.0 = user) @@ -2362,7 +2362,7 @@ func TestConvertClaudeRequestToAntigravity_ToolResult(t *testing.T) { ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) outputStr := string(output) // Check function response conversion @@ -2390,7 +2390,7 @@ func TestConvertClaudeRequestToAntigravity_NonThinkingClaudePreservesToolResultA ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) contents := gjson.GetBytes(output, "request.contents").Array() if len(contents) != 3 { t.Fatalf("expected model turn, function response turn, and text turn; got %d: %s", len(contents), output) @@ -2413,7 +2413,7 @@ func TestConvertClaudeRequestToAntigravity_InterveningSystemReminderPreservesToo ] }`) - output := ConvertClaudeRequestToAntigravity("claude-opus-4-6-thinking", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-opus-4-6-thinking", inputJSON, false) contents := gjson.GetBytes(output, "request.contents").Array() if len(contents) != 3 { t.Fatalf("expected model turn, function response turn, and reminder turn; got %d: %s", len(contents), output) @@ -2436,7 +2436,7 @@ func TestConvertClaudeRequestToAntigravity_InterveningDeveloperReminderPreserves ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) contents := gjson.GetBytes(output, "request.contents").Array() if len(contents) != 3 { t.Fatalf("expected model turn, function response turn, and reminder turn; got %d: %s", len(contents), output) @@ -2462,7 +2462,7 @@ func TestConvertClaudeRequestToAntigravity_ParallelToolResultsAcrossMessagesPres ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) contents := gjson.GetBytes(output, "request.contents").Array() if len(contents) != 2 { t.Fatalf("expected model turn and merged function response turn; got %d: %s", len(contents), output) @@ -2496,7 +2496,7 @@ func TestConvertClaudeRequestToAntigravity_ClaudeThinkingPreservesToolResultAdja ] }`) - output := ConvertClaudeRequestToAntigravity("claude-opus-4-6-thinking", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-opus-4-6-thinking", inputJSON, false) contents := gjson.GetBytes(output, "request.contents").Array() if len(contents) != 3 { t.Fatalf("expected model turn, function response turn, and text turn; got %d: %s", len(contents), output) @@ -2555,7 +2555,7 @@ func TestConvertClaudeRequestToAntigravity_ToolResultName_TouluFormat(t *testing ] }`) - output := ConvertClaudeRequestToAntigravity("claude-haiku-4-5-20251001", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-haiku-4-5-20251001", inputJSON, false) outputStr := string(output) funcResp0 := gjson.Get(outputStr, "request.contents.1.parts.0.functionResponse") @@ -2603,7 +2603,7 @@ func TestConvertClaudeRequestToAntigravity_ToolResultName_CustomFormat(t *testin ] }`) - output := ConvertClaudeRequestToAntigravity("claude-haiku-4-5-20251001", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-haiku-4-5-20251001", inputJSON, false) outputStr := string(output) funcResp := gjson.Get(outputStr, "request.contents.1.parts.0.functionResponse") @@ -2632,7 +2632,7 @@ func TestConvertClaudeRequestToAntigravity_ToolResultName_NoMatchingToolUse_Heur ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) outputStr := string(output) funcResp := gjson.Get(outputStr, "request.contents.0.parts.0.functionResponse") @@ -2661,7 +2661,7 @@ func TestConvertClaudeRequestToAntigravity_ToolResultName_NoMatchingToolUse_RawI ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) outputStr := string(output) funcResp := gjson.Get(outputStr, "request.contents.0.parts.0.functionResponse") @@ -2690,7 +2690,7 @@ func TestConvertClaudeRequestToAntigravity_ThinkingConfig(t *testing.T) { } }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) outputStr := string(output) // Check thinking config conversion (only if model supports thinking in registry) @@ -2727,7 +2727,7 @@ func TestConvertClaudeRequestToAntigravity_ImageContent(t *testing.T) { ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) outputStr := string(output) // Check inline data conversion @@ -2753,7 +2753,7 @@ func TestConvertClaudeRequestToAntigravity_GenerationConfig(t *testing.T) { "max_tokens": 2000 }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) outputStr := string(output) genConfig := gjson.Get(outputStr, "request.generationConfig") @@ -2794,7 +2794,7 @@ func TestConvertClaudeRequestToAntigravity_TrailingUnsignedThinking_Removed(t *t ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) outputStr := string(output) // The last part of the last assistant message should NOT be a thinking block @@ -2840,7 +2840,7 @@ func TestConvertClaudeRequestToAntigravity_TrailingSignedThinking_Kept(t *testin cache.CacheSignature("claude-sonnet-4-5-thinking", thinkingText, nativeSignature) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) outputStr := string(output) // The signed thinking block should be preserved @@ -2870,7 +2870,7 @@ func TestConvertClaudeRequestToAntigravity_MiddleUnsignedThinking_Removed(t *tes ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) outputStr := string(output) // Unsigned thinking should be removed entirely @@ -2908,7 +2908,7 @@ func TestConvertClaudeRequestToAntigravity_ToolAndThinking_HintInjected(t *testi "thinking": {"type": "enabled", "budget_tokens": 8000} }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) outputStr := string(output) // System instruction should contain the interleaved thinking hint @@ -2946,7 +2946,7 @@ func TestConvertClaudeRequestToAntigravity_ToolsOnly_NoHint(t *testing.T) { ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) outputStr := string(output) // System instruction should NOT contain the hint @@ -2969,7 +2969,7 @@ func TestConvertClaudeRequestToAntigravity_ThinkingOnly_NoHint(t *testing.T) { "thinking": {"type": "enabled", "budget_tokens": 8000} }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) outputStr := string(output) // System instruction should NOT contain the hint (no tools) @@ -3011,7 +3011,7 @@ func TestConvertClaudeRequestToAntigravity_ToolResultNoContent(t *testing.T) { ] }`) - output := ConvertClaudeRequestToAntigravity("claude-opus-4-6-thinking", inputJSON, true) + output, _ := ConvertClaudeRequestToAntigravity("claude-opus-4-6-thinking", inputJSON, true) outputStr := string(output) if !gjson.Valid(outputStr) { @@ -3054,7 +3054,7 @@ func TestConvertClaudeRequestToAntigravity_ToolResultNullContent(t *testing.T) { ] }`) - output := ConvertClaudeRequestToAntigravity("claude-opus-4-6-thinking", inputJSON, true) + output, _ := ConvertClaudeRequestToAntigravity("claude-opus-4-6-thinking", inputJSON, true) outputStr := string(output) if !gjson.Valid(outputStr) { @@ -3095,7 +3095,7 @@ func TestConvertClaudeRequestToAntigravity_ToolResultWithImage(t *testing.T) { ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) outputStr := string(output) if !gjson.Valid(outputStr) { @@ -3159,7 +3159,7 @@ func TestConvertClaudeRequestToAntigravity_ToolResultWithSingleImage(t *testing. ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) outputStr := string(output) if !gjson.Valid(outputStr) { @@ -3222,7 +3222,7 @@ func TestConvertClaudeRequestToAntigravity_ToolResultWithMultipleImagesAndTexts( ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) outputStr := string(output) if !gjson.Valid(outputStr) { @@ -3296,7 +3296,7 @@ func TestConvertClaudeRequestToAntigravity_ToolResultWithOnlyMultipleImages(t *t ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) outputStr := string(output) if !gjson.Valid(outputStr) { @@ -3356,7 +3356,7 @@ func TestConvertClaudeRequestToAntigravity_ToolResultImageNotBase64(t *testing.T ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) outputStr := string(output) if !gjson.Valid(outputStr) { @@ -3409,7 +3409,7 @@ func TestConvertClaudeRequestToAntigravity_ToolResultImageMissingData(t *testing ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) outputStr := string(output) if !gjson.Valid(outputStr) { @@ -3459,7 +3459,7 @@ func TestConvertClaudeRequestToAntigravity_ToolResultImageMissingMediaType(t *te ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) outputStr := string(output) if !gjson.Valid(outputStr) { @@ -3518,7 +3518,7 @@ func TestConvertClaudeRequestToAntigravity_BypassMode_DropsRedactedThinkingBlock "thinking": {"type": "enabled", "budget_tokens": 10000} }`) - output := ConvertClaudeRequestToAntigravity("claude-opus-4-6", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-opus-4-6", inputJSON, false) assistantParts := gjson.GetBytes(output, "request.contents.1.parts").Array() if len(assistantParts) != 1 { @@ -3566,7 +3566,7 @@ func TestConvertClaudeRequestToAntigravity_BypassMode_DropsWrappedRedactedThinki "thinking": {"type": "enabled", "budget_tokens": 8000} }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-6", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-6", inputJSON, false) assistantParts := gjson.GetBytes(output, "request.contents.1.parts").Array() if len(assistantParts) != 1 { @@ -3602,7 +3602,7 @@ func TestConvertClaudeRequestToAntigravity_BypassMode_DropsWrappedRedactedThinki }] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-6", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-6", inputJSON, false) toolPart := gjson.GetBytes(output, "request.contents.0.parts.0") if !toolPart.Get("functionCall").Exists() { t.Fatalf("Expected tool part preserved: %s", output) @@ -3641,7 +3641,7 @@ func TestConvertClaudeRequestToAntigravity_BypassMode_KeepsNonEmptyThinking(t *t "thinking": {"type": "enabled", "budget_tokens": 10000} }`) - output := ConvertClaudeRequestToAntigravity("claude-opus-4-6", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-opus-4-6", inputJSON, false) assistantParts := gjson.GetBytes(output, "request.contents.1.parts").Array() if len(assistantParts) != 2 { @@ -3699,7 +3699,7 @@ func TestConvertClaudeRequestToAntigravity_BypassMode_MultiTurnRedactedThinking( "thinking": {"type": "enabled", "budget_tokens": 10000} }`) - output := ConvertClaudeRequestToAntigravity("claude-opus-4-6", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-opus-4-6", inputJSON, false) if !gjson.ValidBytes(output) { t.Fatalf("Output is not valid JSON: %s", string(output)) @@ -3753,7 +3753,7 @@ func TestConvertClaudeRequestToAntigravity_ToolAndThinking_NoExistingSystem(t *t "thinking": {"type": "enabled", "budget_tokens": 8000} }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) outputStr := string(output) // System instruction should be created with hint @@ -3813,7 +3813,7 @@ func TestConvertClaudeRequestToAntigravityStripsPropertyNames(t *testing.T) { ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) decls := gjson.GetBytes(output, "request.tools.0.functionDeclarations") if !decls.IsArray() || len(decls.Array()) != 2 { @@ -3846,7 +3846,7 @@ func TestConvertClaudeRequestToAntigravityToolChoiceNoneOmitsTools(t *testing.T) "tools":[{"name":"get_weather","description":"Get weather","input_schema":{"type":"object"}}], "tool_choice":` + tc.toolChoice + ` }`) - out := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) + out, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) if got := gjson.GetBytes(out, "request.toolConfig.functionCallingConfig.mode").String(); got != "NONE" { t.Fatalf("expected mode NONE, got %q", got) } @@ -3873,7 +3873,7 @@ func TestConvertClaudeRequestToAntigravityToolChoiceNoneOmitsInterleavedThinking "tool_choice":` + tc.toolChoice + `, "thinking":{"type":"enabled","budget_tokens":1024} }`) - out := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) + out, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5-thinking", inputJSON, false) if got := gjson.GetBytes(out, "request.toolConfig.functionCallingConfig.mode").String(); got != "NONE" { t.Fatalf("expected mode NONE, got %q", got) } @@ -3915,7 +3915,7 @@ func TestConvertClaudeRequestToAntigravity_FunctionResponseJSONRef(t *testing.T) ] }`) - output := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) + output, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-5", inputJSON, false) result := gjson.GetBytes(output, "request.contents.1.parts.0.functionResponse.response.result") if result.Type != gjson.String { t.Fatalf("expected functionResponse.response.result to be string, got %s (raw: %s)", result.Type, result.Raw) diff --git a/internal/translator/antigravity/claude/antigravity_claude_response_test.go b/internal/translator/antigravity/claude/antigravity_claude_response_test.go index 367d7e4f7b0..d37ad542ff5 100644 --- a/internal/translator/antigravity/claude/antigravity_claude_response_test.go +++ b/internal/translator/antigravity/claude/antigravity_claude_response_test.go @@ -904,7 +904,7 @@ func TestConvertAntigravityResponseToClaude_PreservesClaudeThoughtAndToolSignatu replayRequest := []byte(`{"model":"claude-sonnet-4-6","messages":[{"role":"assistant","content":[]},{"role":"user","content":[{"type":"text","text":"continue"}]}]}`) replayRequest, _ = sjson.SetRawBytes(replayRequest, "messages.0.content", []byte(gjson.GetBytes(nonStream, "content").Raw)) replayRequest = StripEmptySignatureThinkingBlocks(replayRequest) - translated := ConvertClaudeRequestToAntigravity("claude-sonnet-4-6", replayRequest, false) + translated, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-6", replayRequest, false) parts := gjson.GetBytes(translated, "request.contents.0.parts").Array() if len(parts) != 2 || parts[0].Get("thoughtSignature").String() != upstreamSig1 || parts[1].Get("thoughtSignature").String() != upstreamSig2 { t.Fatalf("Claude thought/tool signatures did not round-trip: %s", translated) @@ -930,7 +930,7 @@ func TestConvertAntigravityResponseToClaudeNonStream_SignedThoughtBeforeUnsigned replayRequest := []byte(`{"model":"gemini-3.6-flash-high","messages":[{"role":"assistant","content":[]}]}`) replayRequest, _ = sjson.SetRawBytes(replayRequest, "messages.0.content", []byte(gjson.GetBytes(output, "content").Raw)) replayRequest = StripInvalidGeminiSignatureThinkingBlocks(replayRequest) - translated := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", replayRequest, false) + translated, _ := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", replayRequest, false) parts := gjson.GetBytes(translated, "request.contents.0.parts").Array() if len(parts) != 2 || parts[0].Get("text").String() != "hidden" || !parts[0].Get("thought").Bool() || parts[0].Get("thoughtSignature").String() != signature || parts[1].Get("text").String() != "visible" || parts[1].Get("thoughtSignature").String() != "" { t.Fatalf("signed thought target changed: output=%s translated=%s", output, translated) @@ -984,7 +984,7 @@ func TestConvertAntigravityResponseToClaudeNonStream_PreservesDistinctThoughtAnd replayRequest := []byte(`{"model":"gemini-3.6-flash-high","messages":[{"role":"assistant","content":[]},{"role":"user","content":[{"type":"text","text":"continue"}]}]}`) replayRequest, _ = sjson.SetRawBytes(replayRequest, "messages.0.content", []byte(gjson.GetBytes(output, "content").Raw)) replayRequest = StripInvalidGeminiSignatureThinkingBlocks(replayRequest) - translated := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", replayRequest, false) + translated, _ := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", replayRequest, false) parts := gjson.GetBytes(translated, "request.contents.0.parts").Array() if len(parts) != 2 { t.Fatalf("replayed parts = %d, want thought + text; translated=%s", len(parts), translated) @@ -1061,7 +1061,7 @@ func TestConvertAntigravityResponseToClaudeNonStream_ThoughtBeforeSignedToolRoun replayRequest := []byte(`{"model":"gemini-3.6-flash-high","messages":[{"role":"assistant","content":[]},{"role":"user","content":[{"type":"text","text":"continue"}]}]}`) replayRequest, _ = sjson.SetRawBytes(replayRequest, "messages.0.content", []byte(gjson.GetBytes(output, "content").Raw)) replayRequest = StripInvalidGeminiSignatureThinkingBlocks(replayRequest) - translated := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", replayRequest, false) + translated, _ := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", replayRequest, false) if got := gjson.GetBytes(translated, "request.contents.0.parts.0.text").String(); got != "hidden analysis" { t.Fatalf("replayed thought text = %q; translated=%s", got, translated) } @@ -1104,7 +1104,7 @@ func TestConvertAntigravityResponseToClaude_TrailingFunctionCarrierRoundTrip(t * replayRequest := []byte(`{"model":"gemini-3.6-flash-high","messages":[{"role":"assistant","content":[]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"","content":"ok"}]}],"tools":[{"name":"run_command","input_schema":{"type":"object","properties":{"command":{"type":"string"}}}}]}`) replayRequest, _ = sjson.SetRawBytes(replayRequest, "messages.0.content", []byte(gjson.GetBytes(claudeResponse, "content").Raw)) replayRequest, _ = sjson.SetBytes(replayRequest, "messages.1.content.0.tool_use_id", content[0].Get("id").String()) - translated := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", replayRequest, true) + translated, _ := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", replayRequest, true) parts := gjson.GetBytes(translated, "request.contents.0.parts").Array() if len(parts) != 1 || !parts[0].Get("functionCall").Exists() { t.Fatalf("trailing carrier was not rebound to the function call: %s", translated) @@ -1167,7 +1167,7 @@ func TestConvertAntigravityResponseToClaude_DirectionalTextCarriersRoundTrip(t * replayRequest := []byte(`{"model":"gemini-3.6-flash-high","messages":[{"role":"assistant","content":[]},{"role":"user","content":[{"type":"text","text":"continue"}]}]}`) replayRequest, _ = sjson.SetRawBytes(replayRequest, "messages.0.content", []byte(gjson.GetBytes(nonStream, "content").Raw)) replayRequest = StripInvalidGeminiSignatureThinkingBlocks(replayRequest) - translated := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", replayRequest, false) + translated, _ := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", replayRequest, false) parts := gjson.GetBytes(translated, "request.contents.0.parts").Array() if len(parts) != 2 || parts[0].Get("text").String() != "A" || parts[1].Get("text").String() != "B" { t.Fatalf("text boundaries changed: %s", translated) @@ -1209,7 +1209,7 @@ func TestConvertAntigravityResponseToClaude_LeadingCarrierTargetsFollowingThough if got := gjson.GetBytes(replayRequest, "messages.0.content.#").Int(); got != 2 { t.Fatalf("prevalidation dropped unsigned target thought: %s", replayRequest) } - translated := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", replayRequest, false) + translated, _ := ConvertClaudeRequestToAntigravity("gemini-3.6-flash-high", replayRequest, false) part := gjson.GetBytes(translated, "request.contents.0.parts.0") if part.Get("text").String() != "reason" || !part.Get("thought").Bool() || part.Get("thoughtSignature").String() != signature { t.Fatalf("leading thought carrier did not round-trip: %s", translated) @@ -1435,7 +1435,7 @@ func TestConvertAntigravityResponseToClaude_EmitsNativeSignaturesWithoutProvider replayRequest := []byte(`{"model":"claude-sonnet-4-6","messages":[{"role":"assistant","content":[]},{"role":"user","content":[{"type":"text","text":"continue"}]}]}`) replayRequest, _ = sjson.SetRawBytes(replayRequest, "messages.0.content", []byte(gjson.GetBytes(nonStream, "content").Raw)) replayRequest = StripEmptySignatureThinkingBlocks(replayRequest) - translated := ConvertClaudeRequestToAntigravity("claude-sonnet-4-6", replayRequest, false) + translated, _ := ConvertClaudeRequestToAntigravity("claude-sonnet-4-6", replayRequest, false) parts := gjson.GetBytes(translated, "request.contents.0.parts").Array() if len(parts) != 2 || parts[0].Get("thoughtSignature").String() != upstreamSig1 || parts[1].Get("thoughtSignature").String() != upstreamSig2 { t.Fatalf("Claude native thought/tool signatures did not round-trip in cache mode: %s", translated) diff --git a/internal/translator/antigravity/claude/antigravity_claude_user_turn_test.go b/internal/translator/antigravity/claude/antigravity_claude_user_turn_test.go index 6361c4661ef..187f61f108b 100644 --- a/internal/translator/antigravity/claude/antigravity_claude_user_turn_test.go +++ b/internal/translator/antigravity/claude/antigravity_claude_user_turn_test.go @@ -81,7 +81,7 @@ func TestConvertClaudeRequestToAntigravity_Base64DocumentBecomesInlineData(t *te func TestConvertClaudeRequestToAntigravity_ExportedWrapperKeepsAJSONBody(t *testing.T) { input := []byte(`{"model":"m","messages":[{"role":"user","content":[` + userTurnUpload + `]}]}`) - if body := ConvertClaudeRequestToAntigravity("m", input, false); !gjson.ValidBytes(body) { + if body, _ := ConvertClaudeRequestToAntigravity("m", input, false); !gjson.ValidBytes(body) { t.Fatalf("body is not JSON: %q", body) } } diff --git a/internal/translator/antigravity/claude/init.go b/internal/translator/antigravity/claude/init.go index 9f12ad78711..8bd96f6388b 100644 --- a/internal/translator/antigravity/claude/init.go +++ b/internal/translator/antigravity/claude/init.go @@ -4,19 +4,17 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" - sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( Claude, Antigravity, - nil, + ConvertClaudeRequestToAntigravity, interfaces.TranslateResponse{ Stream: ConvertAntigravityResponseToClaude, NonStream: ConvertAntigravityResponseToClaudeNonStream, TokenCount: ClaudeTokenCount, }, ) - sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatClaude, sdktranslator.FormatAntigravity, convertClaudeRequestToAntigravity) } diff --git a/internal/translator/antigravity/gemini/antigravity_gemini_request.go b/internal/translator/antigravity/gemini/antigravity_gemini_request.go index e247f25f115..9f902a6be3b 100644 --- a/internal/translator/antigravity/gemini/antigravity_gemini_request.go +++ b/internal/translator/antigravity/gemini/antigravity_gemini_request.go @@ -35,7 +35,7 @@ import ( // // Returns: // - []byte: The transformed request data in Gemini API format -func ConvertGeminiRequestToAntigravity(modelName string, inputRawJSON []byte, _ bool) []byte { +func ConvertGeminiRequestToAntigravity(modelName string, inputRawJSON []byte, _ bool) ([]byte, error) { rawJSON := inputRawJSON functionNameMap := util.SanitizedFunctionNameMap(inputRawJSON) // Keep the envelope in []byte form. Round-tripping through string copies the @@ -49,7 +49,7 @@ func ConvertGeminiRequestToAntigravity(modelName string, inputRawJSON []byte, _ fixedJSON, errFixCLIToolResponse := fixCLIToolResponse(rawJSON) if errFixCLIToolResponse != nil { - return []byte{} + return []byte{}, nil } rawJSON = fixedJSON @@ -155,7 +155,7 @@ func ConvertGeminiRequestToAntigravity(modelName string, inputRawJSON []byte, _ rawJSON = signature.SanitizeGeminiRequestThoughtSignatures(rawJSON, "request.contents") } - return common.AttachDefaultSafetySettings(rawJSON, "request.safetySettings") + return common.AttachDefaultSafetySettings(rawJSON, "request.safetySettings"), nil } // normalizeGeminiGenerationConfigResponseSchema converts generationConfig.responseJsonSchema diff --git a/internal/translator/antigravity/gemini/antigravity_gemini_request_test.go b/internal/translator/antigravity/gemini/antigravity_gemini_request_test.go index 4b490ad81fc..2dfa995f765 100644 --- a/internal/translator/antigravity/gemini/antigravity_gemini_request_test.go +++ b/internal/translator/antigravity/gemini/antigravity_gemini_request_test.go @@ -25,7 +25,7 @@ func TestConvertGeminiRequestToAntigravity_ReplacesClientSignatureOnFunctionCall ] }`, validSignature)) - output := ConvertGeminiRequestToAntigravity("gemini-3-pro-preview", inputJSON, false) + output, _ := ConvertGeminiRequestToAntigravity("gemini-3-pro-preview", inputJSON, false) outputStr := string(output) parts := gjson.Get(outputStr, "request.contents.0.parts").Array() @@ -54,7 +54,7 @@ func TestConvertGeminiRequestToAntigravity_DropsIncompatibleClientSignatureOnTex ] }`, validSignature)) - output := ConvertGeminiRequestToAntigravity("gemini-3-pro-preview", inputJSON, false) + output, _ := ConvertGeminiRequestToAntigravity("gemini-3-pro-preview", inputJSON, false) if signature := gjson.GetBytes(output, "request.contents.0.parts.0.thoughtSignature"); signature.Exists() { t.Fatalf("incompatible text signature should be dropped, got %s", signature.Raw) } @@ -73,7 +73,7 @@ func TestConvertGeminiRequestToAntigravity_LeavesUnsignedThoughtPartUnsigned(t * ] }`) - output := ConvertGeminiRequestToAntigravity("gemini-3-pro-preview", inputJSON, false) + output, _ := ConvertGeminiRequestToAntigravity("gemini-3-pro-preview", inputJSON, false) if signature := gjson.GetBytes(output, "request.contents.0.parts.0.thoughtSignature"); signature.Exists() { t.Fatalf("unsigned thought should remain unsigned, got %s", signature.Raw) } @@ -92,7 +92,7 @@ func TestConvertGeminiRequestToAntigravity_SkipsUppercaseClaudeModel(t *testing. ] }`) - output := ConvertGeminiRequestToAntigravity("Claude-Test", inputJSON, false) + output, _ := ConvertGeminiRequestToAntigravity("Claude-Test", inputJSON, false) outputStr := string(output) if sig := gjson.Get(outputStr, "request.contents.0.parts.0.thoughtSignature"); sig.Exists() { @@ -124,7 +124,7 @@ func TestConvertGeminiRequestToAntigravity_ClaudeModelNormalizesStrictClaudeThou ] }`) - output := ConvertGeminiRequestToAntigravity("claude-opus-4-6-thinking", inputJSON, false) + output, _ := ConvertGeminiRequestToAntigravity("claude-opus-4-6-thinking", inputJSON, false) part := gjson.GetBytes(output, "request.contents.0.parts.0") if !part.Get("thought").Bool() { @@ -158,7 +158,7 @@ func TestConvertGeminiRequestToAntigravity_ClaudeModelDropsNonStrictEPrefixThoug ] }`) - output := ConvertGeminiRequestToAntigravity("claude-opus-4-6-thinking", inputJSON, false) + output, _ := ConvertGeminiRequestToAntigravity("claude-opus-4-6-thinking", inputJSON, false) if gjson.GetBytes(output, `request.contents.#.parts.#(thought=true)#`).Int() != 0 { t.Fatalf("non-strict E-prefix thought block should be dropped. Output: %s", output) @@ -187,7 +187,7 @@ func TestConvertGeminiRequestToAntigravity_ClaudeModelDropsEmptyThoughtText(t *t ] }`) - output := ConvertGeminiRequestToAntigravity("claude-opus-4-6-thinking", inputJSON, false) + output, _ := ConvertGeminiRequestToAntigravity("claude-opus-4-6-thinking", inputJSON, false) if gjson.GetBytes(output, `request.contents.#.parts.#(thought=true)#`).Int() != 0 { t.Fatalf("empty-text thought block should be dropped for Antigravity Claude. Output: %s", output) @@ -211,7 +211,7 @@ func TestConvertGeminiRequestToAntigravity_ClaudeModelStripsUnneededFunctionCall ] }`) - output := ConvertGeminiRequestToAntigravity("claude-opus-4-6-thinking", inputJSON, false) + output, _ := ConvertGeminiRequestToAntigravity("claude-opus-4-6-thinking", inputJSON, false) part := gjson.GetBytes(output, "request.contents.0.parts.0") if !part.Get("functionCall").Exists() { @@ -236,7 +236,7 @@ func TestConvertGeminiRequestToAntigravity_AddSkipSentinelToFunctionCall(t *test ] }`) - output := ConvertGeminiRequestToAntigravity("gemini-3-pro-preview", inputJSON, false) + output, _ := ConvertGeminiRequestToAntigravity("gemini-3-pro-preview", inputJSON, false) outputStr := string(output) // Check that skip_thought_signature_validator is added to functionCall @@ -283,7 +283,7 @@ func TestConvertGeminiRequestToAntigravity_ParallelFunctionCallsOnlyFirstGetsSen ] }`) - output := ConvertGeminiRequestToAntigravity("gemini-3-pro-preview", inputJSON, false) + output, _ := ConvertGeminiRequestToAntigravity("gemini-3-pro-preview", inputJSON, false) parts := gjson.GetBytes(output, "request.contents.0.parts").Array() if len(parts) != 2 { t.Fatalf("Expected 2 parts, got %d", len(parts)) @@ -649,7 +649,7 @@ func TestConvertGeminiRequestToAntigravityDeduplicatesRequestWideAndDisambiguate "toolConfig":{"functionCallingConfig":{"mode":"ANY","allowedFunctionNames":["` + second + `"]}} }`) - out := ConvertGeminiRequestToAntigravity("gemini-3-flash", inputJSON, false) + out, _ := ConvertGeminiRequestToAntigravity("gemini-3-flash", inputJSON, false) if got := len(gjson.GetBytes(out, "request.tools").Array()); got != 2 { t.Fatalf("tool count = %d, want 2 after removing the empty duplicate node. Output: %s", got, out) } @@ -690,7 +690,7 @@ func TestConvertGeminiRequestToAntigravityMapsSnakeCaseFunctionReferences(t *tes "tool_config":{"function_calling_config":{"allowed_function_names":["read_file"]}} }`) - out := ConvertGeminiRequestToAntigravity("gemini-3-flash", inputJSON, false) + out, _ := ConvertGeminiRequestToAntigravity("gemini-3-flash", inputJSON, false) mapped := gjson.GetBytes(out, "request.tools.0.function_declarations.1.name").String() if mapped == "" { t.Fatalf("mapped declaration name is empty. Output: %s", out) @@ -1108,7 +1108,7 @@ func TestConvertGeminiRequestToAntigravity_PreservesSiblingToolImageOnUserRole(t ]} ] }`) - out := ConvertGeminiRequestToAntigravity("gemini-3-flash", input, false) + out, _ := ConvertGeminiRequestToAntigravity("gemini-3-flash", input, false) contents := gjson.GetBytes(out, "request.contents").Array() if len(contents) != 3 { t.Fatalf("contents = %d, want 3. Output: %s", len(contents), out) @@ -1149,7 +1149,7 @@ func TestNormalizeRoles_InvalidRoleWithoutFunctionResponseAlternates(t *testing. {"role": "invalid", "parts": [{"text": "second"}]} ] }`) - out := ConvertGeminiRequestToAntigravity("gemini-3-flash", inputJSON, false) + out, _ := ConvertGeminiRequestToAntigravity("gemini-3-flash", inputJSON, false) contents := gjson.GetBytes(out, "request.contents").Array() if len(contents) != 2 { t.Fatalf("expected 2 contents, got %d", len(contents)) @@ -1167,7 +1167,7 @@ func TestNormalizeRoles_InvalidRoleWithFunctionResponseNormalizesToUser(t *testi {"role": "invalid", "parts": [{"functionResponse": {"name": "test", "response": {}}}]} ] }`) - out := ConvertGeminiRequestToAntigravity("gemini-3-flash", inputJSON, false) + out, _ := ConvertGeminiRequestToAntigravity("gemini-3-flash", inputJSON, false) // Role functionResponse should NEVER be normalized to model for _, content := range gjson.GetBytes(out, "request.contents").Array() { if content.Get("parts.0.functionResponse").Exists() { @@ -1215,7 +1215,7 @@ func TestConvertGeminiRequestToAntigravity_TranslatesResponseJsonSchemaToRespons for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - out := ConvertGeminiRequestToAntigravity("gemini-3-flash", []byte(tt.inputJSON), false) + out, _ := ConvertGeminiRequestToAntigravity("gemini-3-flash", []byte(tt.inputJSON), false) schema := gjson.GetBytes(out, "request.generationConfig.responseSchema") if !schema.Exists() { @@ -1250,7 +1250,7 @@ func TestConvertGeminiRequestToAntigravity_PreservesExistingResponseSchema(t *te } } }`) - out := ConvertGeminiRequestToAntigravity("gemini-3-flash", inputJSON, false) + out, _ := ConvertGeminiRequestToAntigravity("gemini-3-flash", inputJSON, false) schema := gjson.GetBytes(out, "request.generationConfig.responseSchema") if !schema.Exists() { diff --git a/internal/translator/antigravity/gemini/noop_optimization_test.go b/internal/translator/antigravity/gemini/noop_optimization_test.go index a5e33f64843..c2d9ea9f894 100644 --- a/internal/translator/antigravity/gemini/noop_optimization_test.go +++ b/internal/translator/antigravity/gemini/noop_optimization_test.go @@ -90,7 +90,7 @@ func TestConvertGeminiRequestToAntigravityBoundsLargePayloadCopies(t *testing.T) var before, after runtime.MemStats runtime.GC() runtime.ReadMemStats(&before) - output := ConvertGeminiRequestToAntigravity("gemini-3-flash", input, false) + output, _ := ConvertGeminiRequestToAntigravity("gemini-3-flash", input, false) runtime.ReadMemStats(&after) if got := gjson.GetBytes(output, "request.contents.0.parts.0.inlineData.data").String(); len(got) != inlineDataSize { diff --git a/internal/translator/antigravity/interactions/init.go b/internal/translator/antigravity/interactions/init.go index 3cbbd58cd29..a39e2075c9e 100644 --- a/internal/translator/antigravity/interactions/init.go +++ b/internal/translator/antigravity/interactions/init.go @@ -4,18 +4,16 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" - sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( Interactions, Antigravity, - nil, + ConvertInteractionsRequestToAntigravity, interfaces.TranslateResponse{ Stream: ConvertAntigravityResponseToInteractions, NonStream: ConvertAntigravityResponseToInteractionsNonStream, }, ) - sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatInteractions, sdktranslator.FormatAntigravity, convertInteractionsRequestToAntigravity) } diff --git a/internal/translator/antigravity/interactions/interactions_antigravity_file_data_test.go b/internal/translator/antigravity/interactions/interactions_antigravity_file_data_test.go index 4aa670a82a6..beeb0b63327 100644 --- a/internal/translator/antigravity/interactions/interactions_antigravity_file_data_test.go +++ b/internal/translator/antigravity/interactions/interactions_antigravity_file_data_test.go @@ -9,7 +9,7 @@ import ( func TestConvertInteractionsRequestToAntigravityNormalizesOpenAIFileDataURL(t *testing.T) { input := []byte(`{"model":"gemini-3.5-flash","input":[{"type":"user_input","content":[{"type":"file","file":{"filename":"test.pdf","file_data":"data:application/pdf;base64,JVBERi0xLjQK"}}]}]}`) - out := ConvertInteractionsRequestToAntigravity("gemini-3.5-flash", input, false) + out, _ := ConvertInteractionsRequestToAntigravity("gemini-3.5-flash", input, false) inlineData := gjson.GetBytes(out, "request.contents.0.parts.0.inlineData") if got := inlineData.Get("mimeType").String(); got != "application/pdf" { t.Fatalf("inlineData.mimeType = %q, want application/pdf. Output: %s", got, out) diff --git a/internal/translator/antigravity/interactions/interactions_antigravity_request.go b/internal/translator/antigravity/interactions/interactions_antigravity_request.go index b69d922005d..015aab39a03 100644 --- a/internal/translator/antigravity/interactions/interactions_antigravity_request.go +++ b/internal/translator/antigravity/interactions/interactions_antigravity_request.go @@ -11,9 +11,9 @@ import ( "github.com/tidwall/sjson" ) -func ConvertInteractionsRequestToAntigravity(modelName string, inputRawJSON []byte, stream bool) []byte { - out, _ := convertInteractionsRequestToAntigravity(modelName, inputRawJSON, stream) - return out +func ConvertInteractionsRequestToAntigravity(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { + return convertInteractionsRequestToAntigravity(modelName, inputRawJSON, stream) + } // convertInteractionsRequestToAntigravity also reports a user turn that was left diff --git a/internal/translator/antigravity/interactions/interactions_antigravity_test.go b/internal/translator/antigravity/interactions/interactions_antigravity_test.go index d79b35dd4f3..4b70d2f0be1 100644 --- a/internal/translator/antigravity/interactions/interactions_antigravity_test.go +++ b/internal/translator/antigravity/interactions/interactions_antigravity_test.go @@ -12,7 +12,7 @@ import ( ) func TestConvertInteractionsRequestToAntigravityWithToolMessagesDirect(t *testing.T) { - out := ConvertInteractionsRequestToAntigravity("antigravity-test", []byte(`{"model":"antigravity-test","system_instruction":"be brief","input":[{"type":"user_input","content":[{"type":"text","text":"hi"}]},{"type":"function_call","name":"lookup","call_id":"call_1","arguments":{"q":"x"}},{"type":"function_result","name":"lookup","call_id":"call_1","result":{"ok":true}}],"tools":[{"type":"function","name":"lookup","parameters":{"type":"object","properties":{"q":{"type":"string"}}}}]}`), false) + out, _ := ConvertInteractionsRequestToAntigravity("antigravity-test", []byte(`{"model":"antigravity-test","system_instruction":"be brief","input":[{"type":"user_input","content":[{"type":"text","text":"hi"}]},{"type":"function_call","name":"lookup","call_id":"call_1","arguments":{"q":"x"}},{"type":"function_result","name":"lookup","call_id":"call_1","result":{"ok":true}}],"tools":[{"type":"function","name":"lookup","parameters":{"type":"object","properties":{"q":{"type":"string"}}}}]}`), false) if got := gjson.GetBytes(out, "request.systemInstruction.parts.0.text").String(); got != "be brief" { t.Fatalf("request.systemInstruction.parts.0.text = %q, want be brief. Output: %s", got, string(out)) } @@ -34,7 +34,7 @@ func TestConvertInteractionsRequestToAntigravityWithToolMessagesDirect(t *testin } func TestConvertInteractionsRequestToAntigravityPreservesGenerationConfig(t *testing.T) { - out := ConvertInteractionsRequestToAntigravity("antigravity-test", []byte(`{"model":"antigravity-test","input":"hi","generation_config":{"max_output_tokens":16,"top_p":0.8,"tool_choice":"auto","thinking_level":"high","thinking_summaries":"auto"},"reasoning":{"summary":"auto"},"stream":true}`), true) + out, _ := ConvertInteractionsRequestToAntigravity("antigravity-test", []byte(`{"model":"antigravity-test","input":"hi","generation_config":{"max_output_tokens":16,"top_p":0.8,"tool_choice":"auto","thinking_level":"high","thinking_summaries":"auto"},"reasoning":{"summary":"auto"},"stream":true}`), true) if gjson.GetBytes(out, "input").Exists() { t.Fatalf("raw interactions input exists in translated request. Output: %s", string(out)) } @@ -84,7 +84,7 @@ func TestConvertInteractionsReasoningToAntigravityKeepsSummaryIndependent(t *tes for _, test := range tests { t.Run(test.name, func(t *testing.T) { body := []byte(`{"model":"antigravity-test","input":"hi","reasoning":` + test.reasoning + `}`) - out := ConvertInteractionsRequestToAntigravity("antigravity-test", body, false) + out, _ := ConvertInteractionsRequestToAntigravity("antigravity-test", body, false) if got := gjson.GetBytes(out, "request.generationConfig.thinkingConfig.thinkingLevel").String(); got != "high" { t.Fatalf("thinkingLevel = %q, want high. Output: %s", got, out) } @@ -150,7 +150,7 @@ func TestConvertInteractionsRequestToAntigravityDeduplicatesAndDisambiguatesTool "tool_choice":{"type":"function","function":{"name":"` + second + `"}} }`) - out := ConvertInteractionsRequestToAntigravity("antigravity-test", inputJSON, false) + out, _ := ConvertInteractionsRequestToAntigravity("antigravity-test", inputJSON, false) declarations := gjson.GetBytes(out, "request.tools.0.functionDeclarations").Array() if len(declarations) != 3 { t.Fatalf("declaration count = %d, want 3. Output: %s", len(declarations), out) @@ -178,7 +178,7 @@ func TestConvertInteractionsRequestToAntigravityPreservesNameMappingWhitespace(t "tool_choice":{"type":"function","function":{"name":" read/file "}} }`) - out := ConvertInteractionsRequestToAntigravity("antigravity-test", inputJSON, false) + out, _ := ConvertInteractionsRequestToAntigravity("antigravity-test", inputJSON, false) declarationName := gjson.GetBytes(out, "request.tools.0.functionDeclarations.0.name").String() callName := gjson.GetBytes(out, "request.contents.0.parts.0.functionCall.name").String() allowedName := gjson.GetBytes(out, "request.toolConfig.functionCallingConfig.allowedFunctionNames.0").String() @@ -232,7 +232,7 @@ func TestConvertInteractionsRequestToAntigravityToolChoiceNoneOmitsTools(t *test "tools":[{"type":"function","name":"get_weather","parameters":{"type":"object"}}], "tool_choice":` + tc.toolChoice + ` }`) - out := ConvertInteractionsRequestToAntigravity("antigravity-test", inputJSON, false) + out, _ := ConvertInteractionsRequestToAntigravity("antigravity-test", inputJSON, false) if got := gjson.GetBytes(out, "request.toolConfig.functionCallingConfig.mode").String(); got != "NONE" { t.Fatalf("expected mode NONE, got %q", got) } @@ -250,7 +250,7 @@ func TestConvertInteractionsRequestToAntigravityBuiltinTools(t *testing.T) { "input":"read url", "tools":[{"type":"url_context"}] }`) - out := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", inputJSON, false) + out, _ := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", inputJSON, false) tools := gjson.GetBytes(out, "request.tools").Array() if len(tools) != 1 { t.Fatalf("expected 1 tool, got %d. Output: %s", len(tools), string(out)) @@ -269,7 +269,7 @@ func TestConvertInteractionsRequestToAntigravityBuiltinTools(t *testing.T) { "input":"execute code", "tools":[{"type":"code_execution"}] }`) - out := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", inputJSON, false) + out, _ := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", inputJSON, false) tools := gjson.GetBytes(out, "request.tools").Array() if len(tools) != 1 { t.Fatalf("expected 1 tool, got %d. Output: %s", len(tools), string(out)) @@ -288,7 +288,7 @@ func TestConvertInteractionsRequestToAntigravityBuiltinTools(t *testing.T) { "input":"search web", "tools":[{"type":"google_search"}] }`) - out := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", inputJSON, false) + out, _ := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", inputJSON, false) tools := gjson.GetBytes(out, "request.tools").Array() if len(tools) != 1 { t.Fatalf("expected 1 tool, got %d. Output: %s", len(tools), string(out)) @@ -311,7 +311,7 @@ func TestConvertInteractionsRequestToAntigravityBuiltinTools(t *testing.T) { {"type":"code_execution"} ] }`) - out := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", inputJSON, false) + out, _ := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", inputJSON, false) tools := gjson.GetBytes(out, "request.tools").Array() if len(tools) != 3 { t.Fatalf("expected 3 tools, got %d. Output: %s", len(tools), string(out)) @@ -348,7 +348,7 @@ func TestConvertInteractionsRequestToAntigravityBuiltinTools(t *testing.T) { {"type":"web_search","google_search":{"mode":"search"}} ] }`) - out := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", inputJSON, false) + out, _ := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", inputJSON, false) tools := gjson.GetBytes(out, "request.tools").Array() if len(tools) != 3 { t.Fatalf("expected 3 tools, got %d. Output: %s", len(tools), string(out)) @@ -370,7 +370,7 @@ func TestConvertInteractionsRequestToAntigravityBuiltinTools(t *testing.T) { "input":"native composite tools", "tools":[{"googleSearch":{},"urlContext":{}}] }`) - out := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", inputJSON, false) + out, _ := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", inputJSON, false) tools := gjson.GetBytes(out, "request.tools").Array() if len(tools) != 1 { t.Fatalf("expected 1 tool node, got %d. Output: %s", len(tools), string(out)) @@ -389,7 +389,7 @@ func TestConvertInteractionsRequestToAntigravityBuiltinTools(t *testing.T) { "input":"unrecognized tool", "tools":[{"type":"file_search","file_search":{"max_results":5}}] }`) - out := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", inputJSON, false) + out, _ := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", inputJSON, false) tools := gjson.GetBytes(out, "request.tools").Array() if len(tools) != 1 { t.Fatalf("expected 1 tool retained, got %d. Output: %s", len(tools), string(out)) @@ -416,7 +416,7 @@ func TestConvertInteractionsRequestToAntigravity_FunctionResponseJSONRef(t *test } ] }`) - out := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", inputJSON, false) + out, _ := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", inputJSON, false) val := gjson.GetBytes(out, "request.contents.0.parts.0.functionResponse.response.result") if val.Type != gjson.String { t.Fatalf("expected functionResponse.response.result to be string, got %s (raw: %s)", val.Type, val.Raw) @@ -440,7 +440,7 @@ func TestConvertInteractionsRequestToAntigravity_ParallelToolCallsHistory(t *tes {"type": "function_result", "name": "f3", "call_id": "c3", "result": {"r": 3}} ] }`) - out := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", inputJSON, false) + out, _ := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", inputJSON, false) contents := gjson.GetBytes(out, "request.contents").Array() if len(contents) != 3 { t.Fatalf("expected 3 contents (user, model, user), got %d: %s", len(contents), string(out)) @@ -469,7 +469,7 @@ func TestConvertInteractionsRequestToAntigravity_ThoughtSummaryAndSignature(t *t {"type": "model_output", "content": [{"type": "text", "text": "my answer"}]} ] }`) - out := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", inputJSON, false) + out, _ := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", inputJSON, false) contents := gjson.GetBytes(out, "request.contents").Array() if len(contents) != 1 { t.Fatalf("expected 1 model content, got %d: %s", len(contents), string(out)) @@ -550,7 +550,7 @@ func TestConvertInteractionsRequestToAntigravity_InterleavedModelTurnSteps(t *te {"type": "function_result", "name": "f2", "call_id": "c2", "result": {"r": 2}} ] }`) - out := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", inputJSON, false) + out, _ := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", inputJSON, false) contents := gjson.GetBytes(out, "request.contents").Array() if len(contents) != 2 { t.Fatalf("expected 2 contents (model, user), got %d: %s", len(contents), string(out)) @@ -595,7 +595,7 @@ func TestConvertInteractionsRequestToAntigravity_ResponseToRequestRoundTrip(t *t } turn2Input += `,{"type":"function_result","name":"lookup","call_id":"call_1","result":{"ok":true}},{"type":"function_result","name":"search","call_id":"call_2","result":{"found":true}}]}` - reqOut := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", []byte(turn2Input), false) + reqOut, _ := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", []byte(turn2Input), false) contents := gjson.GetBytes(reqOut, "request.contents").Array() if len(contents) != 3 { t.Fatalf("expected 3 contents (user, model, user), got %d: %s", len(contents), string(reqOut)) @@ -621,7 +621,7 @@ func TestConvertInteractionsRequestToAntigravity_MultipleSignaturesPreserved(t * {"type": "function_call", "name": "f1", "call_id": "c1", "arguments": {}} ] }`) - out := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", inputJSON, false) + out, _ := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", inputJSON, false) contents := gjson.GetBytes(out, "request.contents").Array() if len(contents) != 1 { t.Fatalf("expected 1 model content, got %d: %s", len(contents), string(out)) @@ -659,7 +659,7 @@ func TestConvertInteractionsRequestToAntigravity_TrailingSignatureRoundTrip(t *t steps := gjson.GetBytes(respOut, "steps").Raw turn2Input := `{"model":"gemini-3.8-flash-high","input":` + steps + `}` - reqOut := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", []byte(turn2Input), false) + reqOut, _ := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", []byte(turn2Input), false) contents := gjson.GetBytes(reqOut, "request.contents").Array() if len(contents) != 1 { t.Fatalf("expected 1 model content, got %d: %s", len(contents), string(reqOut)) @@ -688,7 +688,7 @@ func TestConvertInteractionsRequestToAntigravity_ExplicitSignatureClearsPending( {"type": "function_call", "name": "f2", "call_id": "c2", "arguments": {}} ] }`) - out := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", inputJSON, false) + out, _ := ConvertInteractionsRequestToAntigravity("gemini-3.8-flash-high", inputJSON, false) contents := gjson.GetBytes(out, "request.contents").Array() if len(contents) != 1 { t.Fatalf("expected 1 model content, got %d: %s", len(contents), string(out)) diff --git a/internal/translator/antigravity/interactions/interactions_antigravity_uri_test.go b/internal/translator/antigravity/interactions/interactions_antigravity_uri_test.go index 23375bf81e2..9270be587b5 100644 --- a/internal/translator/antigravity/interactions/interactions_antigravity_uri_test.go +++ b/internal/translator/antigravity/interactions/interactions_antigravity_uri_test.go @@ -145,7 +145,7 @@ func TestInteractionsToAntigravityNeighbouringStepKeepsTheTurnAlive(t *testing.T func TestInteractionsToAntigravityExportedWrapperKeepsAJSONBody(t *testing.T) { input := []byte(`{"model":"m","input":[` + interactionsAntigravityHistory + `,{"type":"user_input","content":[{"type":"audio","mime_type":"audio/wav"}]}]}`) - if body := ConvertInteractionsRequestToAntigravity("m", input, false); !gjson.ValidBytes(body) { + if body, _ := ConvertInteractionsRequestToAntigravity("m", input, false); !gjson.ValidBytes(body) { t.Fatalf("body is not JSON: %q", body) } } diff --git a/internal/translator/antigravity/openai/chat-completions/antigravity_openai_file_data_test.go b/internal/translator/antigravity/openai/chat-completions/antigravity_openai_file_data_test.go index 6270183679b..02222725b05 100644 --- a/internal/translator/antigravity/openai/chat-completions/antigravity_openai_file_data_test.go +++ b/internal/translator/antigravity/openai/chat-completions/antigravity_openai_file_data_test.go @@ -9,7 +9,7 @@ import ( func TestConvertOpenAIRequestToAntigravityNormalizesFileDataURL(t *testing.T) { input := []byte(`{"model":"gemini-2.5-pro","messages":[{"role":"user","content":[{"type":"file","file":{"filename":"test.pdf","file_data":"data:application/pdf;base64,JVBERi0xLjQK"}}]}]}`) - out := ConvertOpenAIRequestToAntigravity("gemini-2.5-pro", input, false) + out, _ := ConvertOpenAIRequestToAntigravity("gemini-2.5-pro", input, false) inlineData := gjson.GetBytes(out, "request.contents.0.parts.0.inlineData") if got := inlineData.Get("mimeType").String(); got != "application/pdf" { t.Fatalf("inlineData.mimeType = %q, want application/pdf. Output: %s", got, out) diff --git a/internal/translator/antigravity/openai/chat-completions/antigravity_openai_request.go b/internal/translator/antigravity/openai/chat-completions/antigravity_openai_request.go index 9639d4730ea..d2c43b5cd58 100644 --- a/internal/translator/antigravity/openai/chat-completions/antigravity_openai_request.go +++ b/internal/translator/antigravity/openai/chat-completions/antigravity_openai_request.go @@ -28,9 +28,9 @@ const antigravityFunctionThoughtSignature = "skip_thought_signature_validator" // // Returns: // - []byte: The transformed request data in Antigravity API format -func ConvertOpenAIRequestToAntigravity(modelName string, inputRawJSON []byte, stream bool) []byte { - body, _ := convertOpenAIRequestToAntigravity(modelName, inputRawJSON, stream) - return body +func ConvertOpenAIRequestToAntigravity(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { + return convertOpenAIRequestToAntigravity(modelName, inputRawJSON, stream) + } // convertOpenAIRequestToAntigravity also reports a file part Antigravity cannot diff --git a/internal/translator/antigravity/openai/chat-completions/antigravity_openai_request_test.go b/internal/translator/antigravity/openai/chat-completions/antigravity_openai_request_test.go index 1994a7082cf..a56b240c2c3 100644 --- a/internal/translator/antigravity/openai/chat-completions/antigravity_openai_request_test.go +++ b/internal/translator/antigravity/openai/chat-completions/antigravity_openai_request_test.go @@ -33,7 +33,7 @@ func TestConvertOpenAIRequestToAntigravitySkipsEmptyTextPartsWithoutNulls(t *tes ] }` - result := ConvertOpenAIRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) userParts := gjson.GetBytes(result, "request.contents.0.parts").Array() if len(userParts) != 1 { t.Fatalf("user parts length = %d, want 1. Output: %s", len(userParts), result) @@ -67,7 +67,7 @@ func TestConvertOpenAIRequestToAntigravity_ClaudeModelSanitizesUnsignedReasoning ] }` - result := ConvertOpenAIRequestToAntigravity("claude-sonnet-4-6", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToAntigravity("claude-sonnet-4-6", []byte(inputJSON), false) contents := gjson.GetBytes(result, "request.contents").Array() if len(contents) != 3 { t.Fatalf("contents length = %d, want 3. Output: %s", len(contents), result) @@ -94,7 +94,7 @@ func TestConvertOpenAIRequestToAntigravity_ClaudeModelDropsEmptyAssistantTurnAft ] }` - result := ConvertOpenAIRequestToAntigravity("claude-sonnet-4-6", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToAntigravity("claude-sonnet-4-6", []byte(inputJSON), false) contents := gjson.GetBytes(result, "request.contents").Array() if len(contents) != 2 { t.Fatalf("contents length = %d, want 2 (empty model turn dropped). Output: %s", len(contents), result) @@ -117,7 +117,7 @@ func TestConvertOpenAIRequestToAntigravityPreservesReasoningContent(t *testing.T ] }` - result := ConvertOpenAIRequestToAntigravity("gemini-3-flash", []byte(inputJSON), true) + result, _ := ConvertOpenAIRequestToAntigravity("gemini-3-flash", []byte(inputJSON), true) contents := gjson.GetBytes(result, "request.contents").Array() if len(contents) != 3 { t.Fatalf("contents length = %d, want 3. Output: %s", len(contents), result) @@ -148,7 +148,7 @@ func TestConvertOpenAIRequestToAntigravityPreservesReasoningBeforeVisibleContent ] }` - result := ConvertOpenAIRequestToAntigravity("gemini-3-flash", []byte(inputJSON), true) + result, _ := ConvertOpenAIRequestToAntigravity("gemini-3-flash", []byte(inputJSON), true) contents := gjson.GetBytes(result, "request.contents").Array() if len(contents) != 4 { t.Fatalf("contents length = %d, want 4. Output: %s", len(contents), result) @@ -187,7 +187,7 @@ func TestConvertOpenAIRequestToAntigravitySkipsEmptyAssistantMessages(t *testing ] }` - result := ConvertOpenAIRequestToAntigravity("gemini-3-flash", []byte(inputJSON), true) + result, _ := ConvertOpenAIRequestToAntigravity("gemini-3-flash", []byte(inputJSON), true) contents := gjson.GetBytes(result, "request.contents").Array() if len(contents) != 2 { t.Fatalf("contents length = %d, want 2. Output: %s", len(contents), result) @@ -206,7 +206,7 @@ func TestConvertOpenAIRequestToAntigravity_MidSessionDeveloperMessageDoesNotMuta ] }` - result := ConvertOpenAIRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) output := gjson.ParseBytes(result) // request.systemInstruction must contain only original system prompt @@ -250,7 +250,7 @@ func TestConvertOpenAIRequestToAntigravity_MidSessionSystemReminderEnvelope(t *t ] }` - result := ConvertOpenAIRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) output := gjson.ParseBytes(result) contents := output.Get("request.contents").Array() @@ -286,8 +286,8 @@ func TestConvertOpenAIRequestToAntigravity_MidSessionTransientSystemInstructionP ] }` - outWith := ConvertOpenAIRequestToAntigravity("gemini-3-flash", []byte(turnWithTransient), false) - outWithout := ConvertOpenAIRequestToAntigravity("gemini-3-flash", []byte(turnWithoutTransient), false) + outWith, _ := ConvertOpenAIRequestToAntigravity("gemini-3-flash", []byte(turnWithTransient), false) + outWithout, _ := ConvertOpenAIRequestToAntigravity("gemini-3-flash", []byte(turnWithoutTransient), false) contentsWith := gjson.GetBytes(outWith, "request.contents").Array() contentsWithout := gjson.GetBytes(outWithout, "request.contents").Array() @@ -328,7 +328,7 @@ func TestConvertOpenAIRequestToAntigravity_MidSessionSystemReminderObjectAndArra ] }` - result := ConvertOpenAIRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) output := gjson.ParseBytes(result) contents := output.Get("request.contents").Array() @@ -432,7 +432,7 @@ func TestConvertOpenAIRequestToAntigravityThinkingAliases(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - result := ConvertOpenAIRequestToAntigravity("gemini-3.1-pro-low", []byte(tt.body), false) + result, _ := ConvertOpenAIRequestToAntigravity("gemini-3.1-pro-low", []byte(tt.body), false) includeThoughts := gjson.GetBytes(result, "request.generationConfig.thinkingConfig.includeThoughts") if includeThoughts.Exists() != tt.wantExists { t.Fatalf("includeThoughts exists = %v, want %v. Output: %s", includeThoughts.Exists(), tt.wantExists, result) @@ -466,7 +466,7 @@ func TestConvertOpenAIRequestToAntigravityDeduplicatesAndDisambiguatesTools(t *t "tool_choice":{"type":"function","function":{"name":"` + second + `"}} }` - out := ConvertOpenAIRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) + out, _ := ConvertOpenAIRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) declarations := gjson.GetBytes(out, "request.tools.0.functionDeclarations").Array() if len(declarations) != 3 { t.Fatalf("declaration count = %d, want 3. Output: %s", len(declarations), out) @@ -498,7 +498,7 @@ func TestConvertOpenAIRequestToAntigravityMapsToolChoiceModes(t *testing.T) { } { t.Run(tt.mode+tt.choice, func(t *testing.T) { inputJSON := []byte(`{"messages":[{"role":"user","content":"hi"}],"tool_choice":` + tt.choice + `}`) - out := ConvertOpenAIRequestToAntigravity("gemini-3-flash", inputJSON, false) + out, _ := ConvertOpenAIRequestToAntigravity("gemini-3-flash", inputJSON, false) if got := gjson.GetBytes(out, "request.toolConfig.functionCallingConfig.mode").String(); got != tt.mode { t.Fatalf("tool choice mode = %q, want %q. Output: %s", got, tt.mode, out) } @@ -519,7 +519,7 @@ func TestConvertOpenAIRequestToAntigravityMapsResponseFormatJSONObject(t *testin "response_format":{"type":"json_object"} }`) - out := ConvertOpenAIRequestToAntigravity("gemini-3.6-flash-high", inputJSON, false) + out, _ := ConvertOpenAIRequestToAntigravity("gemini-3.6-flash-high", inputJSON, false) if got := gjson.GetBytes(out, "request.generationConfig.responseMimeType").String(); got != "application/json" { t.Fatalf("responseMimeType = %q, want application/json. Output: %s", got, out) } @@ -552,7 +552,7 @@ func TestConvertOpenAIRequestToAntigravityMapsResponseFormatJSONSchema(t *testin } }`) - out := ConvertOpenAIRequestToAntigravity("gemini-3.6-flash-high", inputJSON, false) + out, _ := ConvertOpenAIRequestToAntigravity("gemini-3.6-flash-high", inputJSON, false) if got := gjson.GetBytes(out, "request.generationConfig.responseMimeType").String(); got != "application/json" { t.Fatalf("responseMimeType = %q, want application/json. Output: %s", got, out) } @@ -590,7 +590,7 @@ func TestConvertOpenAIRequestToAntigravityTranslatesVideoURL(t *testing.T) { }] }`) - out := ConvertOpenAIRequestToAntigravity("gemini-3.7-flash-high", inputJSON, false) + out, _ := ConvertOpenAIRequestToAntigravity("gemini-3.7-flash-high", inputJSON, false) parts := gjson.GetBytes(out, "request.contents.0.parts").Array() if len(parts) != 2 { t.Fatalf("parts length = %d, want 2. Output: %s", len(parts), out) @@ -637,7 +637,7 @@ func TestConvertOpenAIRequestToAntigravity_MaxCompletionTokens(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - out := ConvertOpenAIRequestToAntigravity("gemini-2.5-flash", []byte(tt.body), false) + out, _ := ConvertOpenAIRequestToAntigravity("gemini-2.5-flash", []byte(tt.body), false) got := gjson.GetBytes(out, "request.generationConfig.maxOutputTokens") if !got.Exists() { t.Fatalf("request.generationConfig.maxOutputTokens missing. Output: %s", out) @@ -673,7 +673,7 @@ func TestConvertOpenAIRequestToAntigravityPreservesToolResponseAsString(t *testi ] }` - result := ConvertOpenAIRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) contents := gjson.GetBytes(result, "request.contents").Array() if len(contents) < 3 { t.Fatalf("expected at least 3 contents, got %d. Output: %s", len(contents), result) @@ -703,7 +703,7 @@ func TestConvertOpenAIRequestToAntigravityToolChoiceNoneOmitsTools(t *testing.T) "tools":[{"type":"function","function":{"name":"get_weather","parameters":{"type":"object"}}}], "tool_choice":` + tc.toolChoice + ` }`) - out := ConvertOpenAIRequestToAntigravity("gemini-3-flash", inputJSON, false) + out, _ := ConvertOpenAIRequestToAntigravity("gemini-3-flash", inputJSON, false) if got := gjson.GetBytes(out, "request.toolConfig.functionCallingConfig.mode").String(); got != "NONE" { t.Fatalf("expected mode NONE, got %q", got) } @@ -741,7 +741,7 @@ func TestConvertOpenAIRequestToAntigravity_MultiTurnRepeatedToolCallID_Issue5933 ] }` - out := ConvertOpenAIRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) + out, _ := ConvertOpenAIRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) // In Turn 1 (contents[1] = model functionCall, contents[2] = user functionResponse): // functionCall.name must be "glob", and functionResponse.name must be "glob". @@ -798,7 +798,7 @@ func TestConvertOpenAIRequestToAntigravity_ParallelAndOutOfOrderToolResponses(t ] }` - out := ConvertOpenAIRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) + out, _ := ConvertOpenAIRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) resp0Name := gjson.GetBytes(out, "request.contents.2.parts.0.functionResponse.name").String() resp0Result := gjson.GetBytes(out, "request.contents.2.parts.0.functionResponse.response.result").String() @@ -842,7 +842,7 @@ func TestConvertOpenAIRequestToAntigravity_SanitizesClaudeToolIDs(t *testing.T) ] }` - out := ConvertOpenAIRequestToAntigravity("claude-sonnet-4-6", []byte(inputJSON), false) + out, _ := ConvertOpenAIRequestToAntigravity("claude-sonnet-4-6", []byte(inputJSON), false) claudePattern := regexp.MustCompile(`^[a-zA-Z0-9_-]+$`) @@ -907,7 +907,7 @@ func TestConvertOpenAIRequestToAntigravity_SanitizesClaudeToolIDs_DisambiguatesC ] }` - out := ConvertOpenAIRequestToAntigravity("claude-sonnet-4-6", []byte(inputJSON), false) + out, _ := ConvertOpenAIRequestToAntigravity("claude-sonnet-4-6", []byte(inputJSON), false) claudePattern := regexp.MustCompile(`^[a-zA-Z0-9_-]+$`) @@ -973,7 +973,7 @@ func TestConvertOpenAIRequestToAntigravity_SanitizesClaudeToolIDs_MissingRespons ] }` - out := ConvertOpenAIRequestToAntigravity("claude-sonnet-4-6", []byte(inputJSON), false) + out, _ := ConvertOpenAIRequestToAntigravity("claude-sonnet-4-6", []byte(inputJSON), false) claudePattern := regexp.MustCompile(`^[a-zA-Z0-9_-]+$`) diff --git a/internal/translator/antigravity/openai/chat-completions/antigravity_openai_user_turn_test.go b/internal/translator/antigravity/openai/chat-completions/antigravity_openai_user_turn_test.go index 5ff8bfceeb5..5ad91377bb2 100644 --- a/internal/translator/antigravity/openai/chat-completions/antigravity_openai_user_turn_test.go +++ b/internal/translator/antigravity/openai/chat-completions/antigravity_openai_user_turn_test.go @@ -92,7 +92,7 @@ func TestOpenAIToAntigravityRegistryCarriesTheRefusal(t *testing.T) { func TestConvertOpenAIRequestToAntigravity_ExportedWrapperKeepsAJSONBody(t *testing.T) { input := []byte(`{"model":"m","messages":[{"role":"user","content":[` + userTurnFileID + `]}]}`) - if body := ConvertOpenAIRequestToAntigravity("m", input, false); !gjson.ValidBytes(body) { + if body, _ := ConvertOpenAIRequestToAntigravity("m", input, false); !gjson.ValidBytes(body) { t.Fatalf("body is not JSON: %q", body) } } diff --git a/internal/translator/antigravity/openai/chat-completions/init.go b/internal/translator/antigravity/openai/chat-completions/init.go index 2fb9fd0a04c..de2378033e5 100644 --- a/internal/translator/antigravity/openai/chat-completions/init.go +++ b/internal/translator/antigravity/openai/chat-completions/init.go @@ -4,18 +4,16 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" - sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( OpenAI, Antigravity, - nil, + ConvertOpenAIRequestToAntigravity, interfaces.TranslateResponse{ Stream: ConvertAntigravityResponseToOpenAI, NonStream: ConvertAntigravityResponseToOpenAINonStream, }, ) - sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatOpenAI, sdktranslator.FormatAntigravity, convertOpenAIRequestToAntigravity) } diff --git a/internal/translator/antigravity/openai/responses/antigravity_openai-responses_request.go b/internal/translator/antigravity/openai/responses/antigravity_openai-responses_request.go index 9b955429553..29ed518d965 100644 --- a/internal/translator/antigravity/openai/responses/antigravity_openai-responses_request.go +++ b/internal/translator/antigravity/openai/responses/antigravity_openai-responses_request.go @@ -53,9 +53,9 @@ func shouldBuildAntigravityResponsesWebSearchRequest(model string, payload []byt func buildAntigravityResponsesWebSearchRequest(model string, payload []byte, stream bool) ([]byte, error) { includedDomains := ExtractResponsesWebSearchAllowedDomains(gjson.ParseBytes(payload)) - rawJSON, errConvert := ConvertOpenAIResponsesRequestToGeminiReturningError(model, payload, stream) + rawJSON, errConvert := ConvertOpenAIResponsesRequestToGemini(model, payload, stream) rawJSON = rewriteOpenAIResponsesReasoningForAntigravityClaude(model, payload, rawJSON) - out := ConvertGeminiRequestToAntigravity(model, rawJSON, stream) + out, _ := ConvertGeminiRequestToAntigravity(model, rawJSON, stream) out, _ = sjson.SetBytes(out, "requestType", "web_search") out = ensureAntigravityResponsesWebSearchTool(out, includedDomains) out = ensureAntigravityResponsesWebSearchSystemInstruction(out) @@ -126,13 +126,13 @@ func ensureAntigravityResponsesWebSearchSystemInstruction(payload []byte) []byte // ConvertOpenAIResponsesRequestToAntigravity translates an OpenAI Responses request // to the Antigravity schema using locally registered Antigravity capabilities. -func ConvertOpenAIResponsesRequestToAntigravity(modelName string, inputRawJSON []byte, stream bool) []byte { +func ConvertOpenAIResponsesRequestToAntigravity(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { req := ConvertOpenAIResponsesRequestEnvelopeToAntigravity(context.Background(), sdktranslator.RequestEnvelope{ Model: modelName, Body: inputRawJSON, Stream: stream, }) - return req.Body + return req.Body, nil } // ConvertOpenAIResponsesRequestEnvelopeToAntigravity translates an OpenAI Responses @@ -143,10 +143,10 @@ func ConvertOpenAIResponsesRequestEnvelopeToAntigravity(_ context.Context, req s return req } inputRawJSON := req.Body - req.Body, req.Err = ConvertOpenAIResponsesRequestToGeminiReturningError(req.Model, req.Body, req.Stream) + req.Body, req.Err = ConvertOpenAIResponsesRequestToGemini(req.Model, req.Body, req.Stream) req.Body = stripAntigravityResponsesGoogleSearch(req.Body) req.Body = rewriteOpenAIResponsesReasoningForAntigravityClaude(req.Model, inputRawJSON, req.Body) - req.Body = ConvertGeminiRequestToAntigravity(req.Model, req.Body, req.Stream) + req.Body, _ = ConvertGeminiRequestToAntigravity(req.Model, req.Body, req.Stream) req.Body = stripAntigravityResponsesGoogleSearch(req.Body) req.Body = enableAntigravityResponsesThinkingSummary(inputRawJSON, req.Body) return req diff --git a/internal/translator/antigravity/openai/responses/antigravity_openai-responses_request_test.go b/internal/translator/antigravity/openai/responses/antigravity_openai-responses_request_test.go index 1d9060cef49..d62af675084 100644 --- a/internal/translator/antigravity/openai/responses/antigravity_openai-responses_request_test.go +++ b/internal/translator/antigravity/openai/responses/antigravity_openai-responses_request_test.go @@ -56,7 +56,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_ClaudeReasoningKeepsClaudeSi ] }`) - out := ConvertOpenAIResponsesRequestToAntigravity("claude-opus-4-6-thinking", raw, false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("claude-opus-4-6-thinking", raw, false) part := gjson.GetBytes(out, "request.contents.0.parts.0") if !part.Get("thought").Bool() { t.Fatalf("first part should remain a thought block. Output: %s", out) @@ -93,7 +93,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_ClaudeReasoningDropsIncompat ] }`) - out := ConvertOpenAIResponsesRequestToAntigravity("claude-opus-4-6-thinking", raw, false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("claude-opus-4-6-thinking", raw, false) if strings.Contains(string(out), sigcompat.GeminiSkipThoughtSignatureValidator) { t.Fatalf("Claude target must not receive Gemini bypass signature. Output: %s", out) } @@ -130,7 +130,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_ClaudeReasoningDropsEmptyThi ] }`) - out := ConvertOpenAIResponsesRequestToAntigravity("claude-opus-4-6-thinking", raw, false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("claude-opus-4-6-thinking", raw, false) if gjson.GetBytes(out, `request.contents.#.parts.#(thought=true)#`).Int() != 0 { t.Fatalf("empty-text reasoning block should be dropped for Antigravity Claude. Output: %s", out) } @@ -199,7 +199,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_EmptyClaudeReasoningDoesNotS {"role":"user","content":[{"type":"input_text","text":"continue"}]} ] }`) - out := ConvertOpenAIResponsesRequestToAntigravity("claude-opus-4-6-thinking", raw, false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("claude-opus-4-6-thinking", raw, false) var thoughts []gjson.Result for _, content := range gjson.GetBytes(out, "request.contents").Array() { for _, part := range content.Get("parts").Array() { @@ -236,7 +236,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_EmptyClaudeReasoningBeforeFu {"role":"user","content":[{"type":"input_text","text":"continue"}]} ] }`) - out := ConvertOpenAIResponsesRequestToAntigravity("claude-opus-4-6-thinking", raw, false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("claude-opus-4-6-thinking", raw, false) var thoughts []gjson.Result for _, content := range gjson.GetBytes(out, "request.contents").Array() { for _, part := range content.Get("parts").Array() { @@ -256,7 +256,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_EmptyClaudeReasoningBeforeFu func TestConvertOpenAIResponsesRequestToAntigravity_GeminiReasoningUsesNativeThoughtSignaturePlacement(t *testing.T) { sig := "EjQKMgEMOdbHO0Gd+c9Mxk4ELwPGbpCEcp2mFfYYLix2UVtBH3fL8GECc4+JITVnHF4qZDsA" raw := []byte(`{"model":"gemini-3.5-flash","input":[{"type":"reasoning","encrypted_content":"gemini#` + sig + `","summary":[{"type":"summary_text","text":"reasoning summary"}]}]}`) - out := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash-agent", raw, false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash-agent", raw, false) parts := gjson.GetBytes(out, "request.contents.0.parts").Array() if len(parts) != 1 { t.Fatalf("parts length = %d, want 1. Output: %s", len(parts), out) @@ -285,7 +285,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_PreservesToolResultImage(t * } ] }` - out := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) contents := gjson.GetBytes(out, "request.contents").Array() if len(contents) != 3 { t.Fatalf("expected 3 contents, got %d. Output: %s", len(contents), out) @@ -341,7 +341,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_AttachesParallelToolImagesTo } ] }` - out := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) parts := gjson.GetBytes(out, "request.contents.2.parts").Array() if len(parts) != 2 { t.Fatalf("function parts = %d, want 2. Output: %s", len(parts), out) @@ -385,7 +385,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_PreservesAdditionalToolsAndT } }` - out := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) if !gjson.ValidBytes(out) { t.Fatalf("invalid JSON output: %s", out) } @@ -439,7 +439,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_MidSessionDeveloperMessageDo ] }` - out := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) if !gjson.ValidBytes(out) { t.Fatalf("invalid JSON output: %s", out) } @@ -500,7 +500,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_MidSessionSystemReminderEnve ] }` - out := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) result := gjson.ParseBytes(out) contents := result.Get("request.contents").Array() @@ -544,7 +544,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_InterveningDeveloperMessageP ] }` - out := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) if !gjson.ValidBytes(out) { t.Fatalf("invalid JSON output: %s", out) } @@ -616,7 +616,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_ReasoningSummaries(t *testin for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - out := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(tc.inputJSON), false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(tc.inputJSON), false) res := gjson.GetBytes(out, "request.generationConfig.thinkingConfig.includeThoughts") if res.Exists() != tc.wantExists { t.Fatalf("includeThoughts exists = %v, want %v; out=%s", res.Exists(), tc.wantExists, out) @@ -638,7 +638,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_FunctionCallOutputAlternateI ] }` - out := ConvertOpenAIResponsesRequestToAntigravity("gemini-3.7-flash-high", []byte(inputJSON), false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("gemini-3.7-flash-high", []byte(inputJSON), false) rawRequest := gjson.GetBytes(out, "request").Raw if errPair := sigcompat.ValidateGeminiFunctionCallPairing([]byte(rawRequest)); errPair != nil { t.Fatalf("ValidateGeminiFunctionCallPairing failed on Antigravity request: %v; output=%s", errPair, out) @@ -669,7 +669,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_InterruptedFunctionCallPrese "stream": false }` - out := ConvertOpenAIResponsesRequestToAntigravity("gemini-3.8-flash-high", []byte(inputJSON), false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("gemini-3.8-flash-high", []byte(inputJSON), false) rawRequest := gjson.GetBytes(out, "request").Raw if errPair := sigcompat.ValidateGeminiFunctionCallPairing([]byte(rawRequest)); errPair != nil { t.Fatalf("ValidateGeminiFunctionCallPairing failed on Antigravity request: %v; output=%s", errPair, out) @@ -706,7 +706,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_ParallelInterruptedFunctionC "stream": false }` - out := ConvertOpenAIResponsesRequestToAntigravity("gemini-3.8-flash-high", []byte(inputJSON), false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("gemini-3.8-flash-high", []byte(inputJSON), false) rawRequest := gjson.GetBytes(out, "request").Raw if errPair := sigcompat.ValidateGeminiFunctionCallPairing([]byte(rawRequest)); errPair != nil { t.Fatalf("ValidateGeminiFunctionCallPairing failed on Antigravity request: %v; output=%s", errPair, out) @@ -740,7 +740,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_TrailingPartialParallelCalls "stream": false }` - out := ConvertOpenAIResponsesRequestToAntigravity("gemini-3.8-flash-high", []byte(inputJSON), false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("gemini-3.8-flash-high", []byte(inputJSON), false) rawRequest := gjson.GetBytes(out, "request").Raw if errPair := sigcompat.ValidateGeminiFunctionCallPairing([]byte(rawRequest)); errPair != nil { t.Fatalf("ValidateGeminiFunctionCallPairing failed on Antigravity trailing partial parallel request: %v; output=%s", errPair, out) @@ -775,7 +775,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_InterruptedMessageBeforeReal "stream": false }` - out := ConvertOpenAIResponsesRequestToAntigravity("gemini-3.8-flash-high", []byte(inputJSON), false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("gemini-3.8-flash-high", []byte(inputJSON), false) rawRequest := gjson.GetBytes(out, "request").Raw if errPair := sigcompat.ValidateGeminiFunctionCallPairing([]byte(rawRequest)); errPair != nil { t.Fatalf("ValidateGeminiFunctionCallPairing failed on Antigravity interrupted message before real output request: %v; output=%s", errPair, out) @@ -813,7 +813,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_FunctionCallOutputWithFCOIte "stream": false }` - out := ConvertOpenAIResponsesRequestToAntigravity("gemini-3.7-flash-high", []byte(inputJSON), false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("gemini-3.7-flash-high", []byte(inputJSON), false) rawRequest := gjson.GetBytes(out, "request").Raw if errPair := sigcompat.ValidateGeminiFunctionCallPairing([]byte(rawRequest)); errPair != nil { t.Fatalf("ValidateGeminiFunctionCallPairing failed on Antigravity fco item ID request: %v; output=%s", errPair, out) @@ -855,7 +855,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_OrphanFunctionCallOutputBeco "stream": false }` - out := ConvertOpenAIResponsesRequestToAntigravity("gemini-3.7-flash-high", []byte(inputJSON), false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("gemini-3.7-flash-high", []byte(inputJSON), false) rawRequest := gjson.GetBytes(out, "request").Raw if errPair := sigcompat.ValidateGeminiFunctionCallPairing([]byte(rawRequest)); errPair != nil { t.Fatalf("ValidateGeminiFunctionCallPairing failed on Antigravity orphan output request: %v; output=%s", errPair, out) @@ -917,7 +917,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_WebSearch(t *testing.T) { }] }`) - out := ConvertOpenAIResponsesRequestToAntigravity(capableModel, input, false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity(capableModel, input, false) parsed := gjson.ParseBytes(out) if parsed.Get("requestType").String() != "web_search" { @@ -940,7 +940,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_WebSearch(t *testing.T) { "input": "What is the newest Go release?", "tools": [{"type": "web_search"}] }`) - incapableOut := ConvertOpenAIResponsesRequestToAntigravity(incapableModel, incapableInput, false) + incapableOut, _ := ConvertOpenAIResponsesRequestToAntigravity(incapableModel, incapableInput, false) if gjson.GetBytes(incapableOut, "requestType").String() == "web_search" { t.Fatalf("incapable model should not build web_search requestType envelope, got: %s", incapableOut) } @@ -966,7 +966,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_MixedToolsSuppressesGoogleSe ] }`) - out := ConvertOpenAIResponsesRequestToAntigravity(modelID, input, false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity(modelID, input, false) parsed := gjson.ParseBytes(out) // 1. Must not build independent web_search requestType envelope @@ -1025,7 +1025,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_CrossProviderCapabilityIsola t.Fatalf("shouldBuildAntigravityResponsesWebSearchRequest should be false for Antigravity route when Antigravity model lacks search capability") } - out := ConvertOpenAIResponsesRequestToAntigravity(modelID, input, false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity(modelID, input, false) if gjson.GetBytes(out, "requestType").String() == "web_search" { t.Fatalf("ConvertOpenAIResponsesRequestToAntigravity should not build web_search requestType envelope when Antigravity route lacks capability: %s", out) } @@ -1046,7 +1046,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_DoesNotBorrowNativeCapabilit "input": "Search web", "tools": [{"type": "web_search"}] }`) - out := ConvertOpenAIResponsesRequestToAntigravity(modelID, input, false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity(modelID, input, false) if gjson.GetBytes(out, "requestType").String() == "web_search" { t.Fatalf("borrowed Gemini capability for Antigravity route: %s", out) } @@ -1083,9 +1083,13 @@ func TestConvertOpenAIResponsesRequestToAntigravity_LocalWebSearchCapability(t * } input := []byte(`{"model":"` + modelID + `","input":"Search weather","tools":[{"type":"web_search"}]}`) + legacy, errLegacy := ConvertOpenAIResponsesRequestToAntigravity(modelID, input, false) + if errLegacy != nil { + t.Fatal(errLegacy) + } unknownInfo := ®istry.ModelInfo{ID: modelID, NativeCapabilities: ®istry.NativeCapabilities{}} for name, out := range map[string][]byte{ - "legacy": ConvertOpenAIResponsesRequestToAntigravity(modelID, input, false), + "legacy": legacy, "unknown envelope with suffix": ConvertOpenAIResponsesRequestEnvelopeToAntigravity(context.Background(), sdktranslator.RequestEnvelope{ Model: modelID + "(high)", Body: input, Stream: true, ModelInfo: unknownInfo, }).Body, @@ -1117,7 +1121,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_IgnoresOtherProviderSearchVe }) input := []byte(`{"model":"` + modelID + `","input":"Search weather","tools":[{"type":"web_search"}]}`) - out := ConvertOpenAIResponsesRequestToAntigravity(modelID, input, false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity(modelID, input, false) if gjson.GetBytes(out, "requestType").String() != "web_search" { t.Fatalf("another provider disabled Antigravity search: %s", out) } @@ -1161,7 +1165,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_WebSearchPreservesMultiTurnC "tools": [{"type": "web_search"}] }`) - out := ConvertOpenAIResponsesRequestToAntigravity(modelID, input, false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity(modelID, input, false) parsed := gjson.ParseBytes(out) if parsed.Get("requestType").String() != "web_search" { t.Fatalf("expected requestType web_search, got %q. Output: %s", parsed.Get("requestType").String(), out) @@ -1204,7 +1208,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_WebSearchPreservesInstructio "tools": [{"type": "web_search"}] }`) - out := ConvertOpenAIResponsesRequestToAntigravity(modelID, input, false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity(modelID, input, false) parsed := gjson.ParseBytes(out) if parsed.Get("requestType").String() != "web_search" { t.Fatalf("expected requestType web_search, got %q. Output: %s", parsed.Get("requestType").String(), out) @@ -1250,7 +1254,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_WebSearchToolChoiceAutoPrese "tools": [{"type": "web_search"}] }`) - out := ConvertOpenAIResponsesRequestToAntigravity(modelID, input, false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity(modelID, input, false) parsed := gjson.ParseBytes(out) if parsed.Get("requestType").String() != "web_search" { t.Fatalf("expected requestType web_search with tool_choice auto, got %q. Output: %s", parsed.Get("requestType").String(), out) @@ -1341,7 +1345,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_AudioAndVideoInput(t *testin ] }` - out := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) contents := gjson.GetBytes(out, "request.contents").Array() if len(contents) == 0 { t.Fatalf("expected at least 1 content, got 0. Output: %s", out) @@ -1418,7 +1422,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_InvalidDataURLsRejected(t *t ] }` - out := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) contents := gjson.GetBytes(out, "request.contents").Array() for _, content := range contents { for _, part := range content.Get("parts").Array() { @@ -1447,7 +1451,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_FallbackMIME(t *testing.T) { ] }` - out := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) parts := gjson.GetBytes(out, "request.contents.0.parts").Array() if len(parts) < 6 { t.Fatalf("expected at least 6 parts, got %d. Output: %s", len(parts), out) @@ -1506,7 +1510,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_RemoteAudioAndVideo(t *testi ] }` - out := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) contents := gjson.GetBytes(out, "request.contents").Array() if len(contents) == 0 { t.Fatalf("expected at least 1 content, got 0. Output: %s", out) @@ -1582,7 +1586,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_InlineExplicitFormatNotOverr ] }` - out := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) parts := gjson.GetBytes(out, "request.contents.0.parts").Array() if len(parts) < 2 { t.Fatalf("expected at least 2 parts, got %d. Output: %s", len(parts), out) @@ -1629,7 +1633,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_RemoteNestedFormatNotOverrid ] }` - out := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) parts := gjson.GetBytes(out, "request.contents.0.parts").Array() if len(parts) < 5 { t.Fatalf("expected at least 5 parts, got %d. Output: %s", len(parts), out) @@ -1683,7 +1687,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_GenericMIMEWithNestedFormatN ] }` - out := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) parts := gjson.GetBytes(out, "request.contents.0.parts").Array() if len(parts) < 3 { t.Fatalf("expected at least 3 parts, got %d. Output: %s", len(parts), out) @@ -1730,7 +1734,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_UnknownExtensionFallsBackToD ] }` - out := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) parts := gjson.GetBytes(out, "request.contents.0.parts").Array() if len(parts) < 2 { t.Fatalf("expected at least 2 parts, got %d. Output: %s", len(parts), out) @@ -1770,7 +1774,7 @@ func TestConvertOpenAIResponsesRequestToAntigravity_TopLevelMedia(t *testing.T) ] }` - out := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) + out, _ := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", []byte(inputJSON), false) contents := gjson.GetBytes(out, "request.contents").Array() if len(contents) == 0 { t.Fatalf("expected at least 1 content, got 0. Output: %s", out) diff --git a/internal/translator/antigravity/openai/responses/antigravity_openai-responses_response_test.go b/internal/translator/antigravity/openai/responses/antigravity_openai-responses_response_test.go index 872bd44a1bb..8cb4ef87ffe 100644 --- a/internal/translator/antigravity/openai/responses/antigravity_openai-responses_response_test.go +++ b/internal/translator/antigravity/openai/responses/antigravity_openai-responses_response_test.go @@ -226,7 +226,7 @@ func TestConvertAntigravityResponseToOpenAIResponsesNonStream_WebSearch(t *testi func TestAntigravityApplyPatchReuse(t *testing.T) { request := []byte(`{"tools":[{"type":"namespace","name":"functions","tools":[{"type":"custom","name":"apply_patch","format":{"type":"grammar","definition":"start: patch"}}]}],"input":"patch"}`) - translated := ConvertOpenAIResponsesRequestToAntigravity("gemini-3.1-pro-preview", request, false) + translated, _ := ConvertOpenAIResponsesRequestToAntigravity("gemini-3.1-pro-preview", request, false) declaration := gjson.GetBytes(translated, "request.tools.0.functionDeclarations.0") if declaration.Get("name").String() != "functions__apply_patch" || !strings.Contains(declaration.Get("description").String(), "*** Begin Patch") || declaration.Get("parametersJsonSchema.properties.input.type").String() != "string" || !declaration.Get("parametersJsonSchema.additionalProperties").Exists() || declaration.Get("parametersJsonSchema.additionalProperties").Bool() { t.Fatalf("missing declaration: %s", translated) diff --git a/internal/translator/antigravity/openai/responses/antigravity_openai-responses_user_turn_test.go b/internal/translator/antigravity/openai/responses/antigravity_openai-responses_user_turn_test.go index be1e99ca25e..dcc3495fdef 100644 --- a/internal/translator/antigravity/openai/responses/antigravity_openai-responses_user_turn_test.go +++ b/internal/translator/antigravity/openai/responses/antigravity_openai-responses_user_turn_test.go @@ -104,7 +104,7 @@ func TestOpenAIResponsesToAntigravityInlineFileStaysInlineData(t *testing.T) { func TestConvertOpenAIResponsesRequestToAntigravity_ExportedWrapperKeepsAJSONBody(t *testing.T) { input := antigravityTurnPayload("", antigravityUserTurn(antigravityTurnFileID)) - if body := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", input, false); !gjson.ValidBytes(body) { + if body, _ := ConvertOpenAIResponsesRequestToAntigravity("gemini-3-flash", input, false); !gjson.ValidBytes(body) { t.Fatalf("body is not JSON: %q", body) } } diff --git a/internal/translator/claude/gemini/claude_gemini_request.go b/internal/translator/claude/gemini/claude_gemini_request.go index 2f18812839f..08747fbe628 100644 --- a/internal/translator/claude/gemini/claude_gemini_request.go +++ b/internal/translator/claude/gemini/claude_gemini_request.go @@ -35,9 +35,9 @@ import ( // // Returns: // - []byte: The transformed request data in Claude Code API format -func ConvertGeminiRequestToClaude(modelName string, inputRawJSON []byte, stream bool) []byte { - body, _ := convertGeminiRequestToClaude(modelName, inputRawJSON, stream) - return body +func ConvertGeminiRequestToClaude(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { + return convertGeminiRequestToClaude(modelName, inputRawJSON, stream) + } // convertGeminiRequestToClaude also reports a user turn that was left empty diff --git a/internal/translator/claude/gemini/claude_gemini_request_test.go b/internal/translator/claude/gemini/claude_gemini_request_test.go index 18030c60ada..e67fdaf3286 100644 --- a/internal/translator/claude/gemini/claude_gemini_request_test.go +++ b/internal/translator/claude/gemini/claude_gemini_request_test.go @@ -19,7 +19,7 @@ func TestConvertGeminiRequestToClaude_ThinkingSummaryVisibility(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - out := ConvertGeminiRequestToClaude("claude-opus-5-5", []byte(test.input), false) + out, _ := ConvertGeminiRequestToClaude("claude-opus-5-5", []byte(test.input), false) if got := gjson.GetBytes(out, "thinking.display").String(); got != test.wanted { t.Fatalf("thinking.display = %q, want %q; body=%s", got, test.wanted, out) } @@ -67,7 +67,7 @@ func TestConvertGeminiRequestToClaude_PreservesCustomToolIDs(t *testing.T) { ] }`, tt.callField, tt.responseField)) - out := ConvertGeminiRequestToClaude("claude-sonnet-4", raw, false) + out, _ := ConvertGeminiRequestToClaude("claude-sonnet-4", raw, false) gotCallID := gjson.GetBytes(out, "messages.0.content.0.id").String() if gotCallID != tt.want { @@ -93,7 +93,7 @@ func TestConvertGeminiRequestToClaude_GroupsConsecutiveRoleTurns(t *testing.T) { ] }`) - out := ConvertGeminiRequestToClaude("claude-test", raw, false) + out, _ := ConvertGeminiRequestToClaude("claude-test", raw, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 2 { t.Fatalf("message count = %d, want 2. Output: %s", len(messages), string(out)) @@ -127,7 +127,7 @@ func TestConvertGeminiRequestToClaude_KeepsSystemInstructionUserSeparate(t *test "system_instruction":{"parts":[{"text":"system rule"}]}, "contents":[{"role":"user","parts":[{"text":"question"}]}] }`) - out := ConvertGeminiRequestToClaude("claude-test", raw, false) + out, _ := ConvertGeminiRequestToClaude("claude-test", raw, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 2 { t.Fatalf("message count = %d, want 2. Output: %s", len(messages), string(out)) @@ -145,7 +145,7 @@ func TestConvertGeminiRequestToClaude_SupportsCamelCaseSystemInstruction(t *test "systemInstruction":{"parts":[{"text":"system rule in camelCase"}]}, "contents":[{"role":"user","parts":[{"text":"question"}]}] }`) - out := ConvertGeminiRequestToClaude("claude-test", raw, false) + out, _ := ConvertGeminiRequestToClaude("claude-test", raw, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 2 { t.Fatalf("message count = %d, want 2. Output: %s", len(messages), string(out)) @@ -172,7 +172,7 @@ func TestConvertGeminiRequestToClaude_DropsTemperature(t *testing.T) { ] }`) - out := ConvertGeminiRequestToClaude("claude-sonnet-5", raw, false) + out, _ := ConvertGeminiRequestToClaude("claude-sonnet-5", raw, false) if gjson.GetBytes(out, "temperature").Exists() { t.Fatalf("temperature should be removed") @@ -183,7 +183,7 @@ func TestConvertGeminiRequestToClaude_DropsTemperature(t *testing.T) { } func TestConvertGeminiRequestToClaude_AcceptsCamelInlineData(t *testing.T) { - out := ConvertGeminiRequestToClaude("claude-sonnet-4", []byte(`{"contents":[{"role":"user","parts":[{"inlineData":{"mimeType":"image/png","data":"aGVsbG8="}}]}]}`), false) + out, _ := ConvertGeminiRequestToClaude("claude-sonnet-4", []byte(`{"contents":[{"role":"user","parts":[{"inlineData":{"mimeType":"image/png","data":"aGVsbG8="}}]}]}`), false) if got := gjson.GetBytes(out, "messages.0.content.0.type").String(); got != "image" { t.Fatalf("content type = %q, want image. Output: %s", got, string(out)) } @@ -193,7 +193,7 @@ func TestConvertGeminiRequestToClaude_AcceptsCamelInlineData(t *testing.T) { } func TestConvertGeminiRequestToClaude_SplitsNonImageInlineDataByMIME(t *testing.T) { - out := ConvertGeminiRequestToClaude("claude-sonnet-4", []byte(`{"contents":[{"role":"user","parts":[{"inlineData":{"mimeType":"audio/wav","data":"UklGRg=="}},{"inlineData":{"mimeType":"video/mp4","data":"AAAAIGZ0eXA="}},{"inlineData":{"mimeType":"application/pdf","data":"JVBERi0="}}]}]}`), false) + out, _ := ConvertGeminiRequestToClaude("claude-sonnet-4", []byte(`{"contents":[{"role":"user","parts":[{"inlineData":{"mimeType":"audio/wav","data":"UklGRg=="}},{"inlineData":{"mimeType":"video/mp4","data":"AAAAIGZ0eXA="}},{"inlineData":{"mimeType":"application/pdf","data":"JVBERi0="}}]}]}`), false) // A user attachment Claude cannot read is dropped rather than replaced by placeholder text. if got := gjson.GetBytes(out, "messages.0.content.#").Int(); got != 1 { @@ -212,7 +212,7 @@ func TestConvertGeminiRequestToClaude_SplitsNonImageInlineDataByMIME(t *testing. func TestConvertGeminiRequestToClaude_DropsHiddenThoughtParts(t *testing.T) { t.Run("thought-only turn", func(t *testing.T) { - out := ConvertGeminiRequestToClaude("claude-test", []byte(`{ + out, _ := ConvertGeminiRequestToClaude("claude-test", []byte(`{ "contents":[ {"role":"model","parts":[{"thought":true,"text":"internal reasoning","thoughtSignature":"opaque-provider-state"}]}, {"role":"user","parts":[{"text":"continue"}]} @@ -226,7 +226,7 @@ func TestConvertGeminiRequestToClaude_DropsHiddenThoughtParts(t *testing.T) { }) t.Run("mixed turn", func(t *testing.T) { - out := ConvertGeminiRequestToClaude("claude-test", []byte(`{ + out, _ := ConvertGeminiRequestToClaude("claude-test", []byte(`{ "contents":[{"role":"model","parts":[ {"thought":true,"text":"internal reasoning","thoughtSignature":"opaque-provider-state"}, {"text":"visible answer"} @@ -270,8 +270,8 @@ func TestConvertGeminiRequestToClaude_DeterministicToolIDs(t *testing.T) { ] }`) - out1 := ConvertGeminiRequestToClaude("claude-sonnet-4", raw, false) - out2 := ConvertGeminiRequestToClaude("claude-sonnet-4", raw, false) + out1, _ := ConvertGeminiRequestToClaude("claude-sonnet-4", raw, false) + out2, _ := ConvertGeminiRequestToClaude("claude-sonnet-4", raw, false) if string(out1) != string(out2) { t.Fatalf("expected deterministic output across multiple conversions, got different outputs:\nout1=%s\nout2=%s", string(out1), string(out2)) @@ -318,7 +318,7 @@ func TestConvertGeminiRequestToClaude_PreservesCallerSuppliedMetadataUserID(t *t for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - out := ConvertGeminiRequestToClaude("claude-test", []byte(tc.rawJSON), false) + out, _ := ConvertGeminiRequestToClaude("claude-test", []byte(tc.rawJSON), false) if !gjson.ValidBytes(out) { t.Fatalf("output is invalid json: %s", string(out)) } @@ -333,8 +333,8 @@ func TestConvertGeminiRequestToClaude_PreservesCallerSuppliedMetadataUserID(t *t func TestConvertGeminiRequestToClaude_DifferentSessionsProduceDifferentUserIDs(t *testing.T) { a := []byte(`{"model":"claude-test","prompt_cache_key":"gemini-session-a","contents":[{"role":"user","parts":[{"text":"hello"}]}]}`) b := []byte(`{"model":"claude-test","prompt_cache_key":"gemini-session-b","contents":[{"role":"user","parts":[{"text":"hello"}]}]}`) - outA := ConvertGeminiRequestToClaude("claude-test", a, false) - outB := ConvertGeminiRequestToClaude("claude-test", b, false) + outA, _ := ConvertGeminiRequestToClaude("claude-test", a, false) + outB, _ := ConvertGeminiRequestToClaude("claude-test", b, false) idA := gjson.GetBytes(outA, "metadata.user_id").String() idB := gjson.GetBytes(outB, "metadata.user_id").String() if idA == idB { @@ -345,8 +345,8 @@ func TestConvertGeminiRequestToClaude_DifferentSessionsProduceDifferentUserIDs(t func TestConvertGeminiRequestToClaude_DefaultRoleDifferentContentProducesDifferentUserIDs(t *testing.T) { a := []byte(`{"contents":[{"parts":[{"text":"first prompt"}]}]}`) b := []byte(`{"contents":[{"parts":[{"text":"second prompt"}]}]}`) - outA := ConvertGeminiRequestToClaude("claude-test", a, false) - outB := ConvertGeminiRequestToClaude("claude-test", b, false) + outA, _ := ConvertGeminiRequestToClaude("claude-test", a, false) + outB, _ := ConvertGeminiRequestToClaude("claude-test", b, false) idA := gjson.GetBytes(outA, "metadata.user_id").String() idB := gjson.GetBytes(outB, "metadata.user_id").String() if idA == "" || idB == "" || idA == "unknown" || idB == "unknown" { @@ -401,7 +401,7 @@ func TestConvertGeminiRequestToClaude_SanitizesToolNamesAndProvidesFallbackSchem } }` - result := ConvertGeminiRequestToClaude("claude-test", []byte(inputJSON), false) + result, _ := ConvertGeminiRequestToClaude("claude-test", []byte(inputJSON), false) // 1. Tool declaration name sanitized toolName := gjson.GetBytes(result, "tools.0.name").String() diff --git a/internal/translator/claude/gemini/claude_gemini_user_turn_test.go b/internal/translator/claude/gemini/claude_gemini_user_turn_test.go index a1300b10547..e260033e4b8 100644 --- a/internal/translator/claude/gemini/claude_gemini_user_turn_test.go +++ b/internal/translator/claude/gemini/claude_gemini_user_turn_test.go @@ -123,7 +123,7 @@ func TestGeminiToClaudeModelAudioKeepsItsPlaceholder(t *testing.T) { func TestGeminiToClaudeExportedWrapperKeepsAJSONBody(t *testing.T) { input := []byte(`{"contents":[{"role":"user","parts":[` + geminiAudioPart + `]}]}`) - if body := ConvertGeminiRequestToClaude("claude-sonnet-4", input, false); !gjson.ValidBytes(body) { + if body, _ := ConvertGeminiRequestToClaude("claude-sonnet-4", input, false); !gjson.ValidBytes(body) { t.Fatalf("body is not JSON: %q", body) } } diff --git a/internal/translator/claude/gemini/init.go b/internal/translator/claude/gemini/init.go index cc95686364e..fad5b0e28a2 100644 --- a/internal/translator/claude/gemini/init.go +++ b/internal/translator/claude/gemini/init.go @@ -4,19 +4,17 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" - sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( Gemini, Claude, - nil, + ConvertGeminiRequestToClaude, interfaces.TranslateResponse{ Stream: ConvertClaudeResponseToGemini, NonStream: ConvertClaudeResponseToGeminiNonStream, TokenCount: GeminiTokenCount, }, ) - sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatGemini, sdktranslator.FormatClaude, convertGeminiRequestToClaude) } diff --git a/internal/translator/claude/interactions/init.go b/internal/translator/claude/interactions/init.go index e29c61b4c32..bb5830cc9d4 100644 --- a/internal/translator/claude/interactions/init.go +++ b/internal/translator/claude/interactions/init.go @@ -4,18 +4,16 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" - sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( Interactions, Claude, - nil, + ConvertInteractionsRequestToClaude, interfaces.TranslateResponse{ Stream: ConvertClaudeResponseToInteractions, NonStream: ConvertClaudeResponseToInteractionsNonStream, }, ) - sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatInteractions, sdktranslator.FormatClaude, convertInteractionsRequestToClaude) } diff --git a/internal/translator/claude/interactions/interactions_claude_request.go b/internal/translator/claude/interactions/interactions_claude_request.go index a667f78d590..556b9a7690d 100644 --- a/internal/translator/claude/interactions/interactions_claude_request.go +++ b/internal/translator/claude/interactions/interactions_claude_request.go @@ -11,9 +11,9 @@ import ( "github.com/tidwall/sjson" ) -func ConvertInteractionsRequestToClaude(modelName string, inputRawJSON []byte, stream bool) []byte { - out, _ := convertInteractionsRequestToClaude(modelName, inputRawJSON, stream) - return out +func ConvertInteractionsRequestToClaude(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { + return convertInteractionsRequestToClaude(modelName, inputRawJSON, stream) + } // convertInteractionsRequestToClaude also reports a user turn that was left empty diff --git a/internal/translator/claude/interactions/interactions_claude_test.go b/internal/translator/claude/interactions/interactions_claude_test.go index f29929e3b93..07684dd6734 100644 --- a/internal/translator/claude/interactions/interactions_claude_test.go +++ b/internal/translator/claude/interactions/interactions_claude_test.go @@ -9,7 +9,7 @@ import ( ) func TestConvertInteractionsRequestToClaudeWithToolMessagesDirect(t *testing.T) { - out := ConvertInteractionsRequestToClaude("claude-test", []byte(`{"model":"claude-test","system_instruction":"be brief","input":[{"type":"user_input","content":[{"type":"text","text":"hi"}]},{"type":"function_call","name":"lookup","call_id":"toolu_1","arguments":{"q":"x"}},{"type":"function_result","name":"lookup","call_id":"toolu_1","result":{"ok":true}}]}`), false) + out, _ := ConvertInteractionsRequestToClaude("claude-test", []byte(`{"model":"claude-test","system_instruction":"be brief","input":[{"type":"user_input","content":[{"type":"text","text":"hi"}]},{"type":"function_call","name":"lookup","call_id":"toolu_1","arguments":{"q":"x"}},{"type":"function_result","name":"lookup","call_id":"toolu_1","result":{"ok":true}}]}`), false) if got := gjson.GetBytes(out, "system").String(); got != "be brief" { t.Fatalf("system = %q, want be brief. Output: %s", got, string(out)) } @@ -28,7 +28,7 @@ func TestConvertInteractionsRequestToClaudeWithToolMessagesDirect(t *testing.T) } func TestConvertInteractionsRequestToClaudePropagatesIsError(t *testing.T) { - out := ConvertInteractionsRequestToClaude("claude-test", []byte(`{"model":"claude-test","input":[{"type":"function_result","name":"lookup","call_id":"toolu_err","result":"command failed","is_error":true}]}`), false) + out, _ := ConvertInteractionsRequestToClaude("claude-test", []byte(`{"model":"claude-test","input":[{"type":"function_result","name":"lookup","call_id":"toolu_err","result":"command failed","is_error":true}]}`), false) if got := gjson.GetBytes(out, "messages.0.content.0.type").String(); got != "tool_result" { t.Fatalf("content type = %q, want tool_result. Output: %s", got, string(out)) } @@ -48,7 +48,7 @@ func TestConvertInteractionsRequestToClaudeGroupsConsecutiveRoleTurns(t *testing {"type":"function_result","call_id":"call_2","result":{"value":"two"}} ] }`) - out := ConvertInteractionsRequestToClaude("claude-test", raw, false) + out, _ := ConvertInteractionsRequestToClaude("claude-test", raw, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 2 { t.Fatalf("message count = %d, want 2. Output: %s", len(messages), string(out)) @@ -82,7 +82,7 @@ func TestConvertInteractionsRequestToClaudeDoesNotMergeAcrossRoleChanges(t *test {"type":"model_output","content":"second assistant"} ] }`) - out := ConvertInteractionsRequestToClaude("claude-test", raw, false) + out, _ := ConvertInteractionsRequestToClaude("claude-test", raw, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 3 { t.Fatalf("message count = %d, want 3. Output: %s", len(messages), string(out)) @@ -95,7 +95,7 @@ func TestConvertInteractionsRequestToClaudeDoesNotMergeAcrossRoleChanges(t *test } func TestConvertInteractionsRequestToClaudeStringInputDirect(t *testing.T) { - out := ConvertInteractionsRequestToClaude("claude-test", []byte(`{"model":"claude-test","input":"hello"}`), false) + out, _ := ConvertInteractionsRequestToClaude("claude-test", []byte(`{"model":"claude-test","input":"hello"}`), false) if got := gjson.GetBytes(out, "messages.0.role").String(); got != "user" { t.Fatalf("messages.0.role = %q, want user. Output: %s", got, string(out)) } @@ -105,7 +105,7 @@ func TestConvertInteractionsRequestToClaudeStringInputDirect(t *testing.T) { } func TestConvertInteractionsRequestToClaudeMapsGenerationConfigToolsAndStreamDirect(t *testing.T) { - out := ConvertInteractionsRequestToClaude("claude-test", []byte(`{"model":"claude-test","stream":true,"input":[{"type":"user_input","content":[{"type":"text","text":"hi"}]}],"tools":[{"type":"function","name":"lookup","description":"Lookup data","parameters":{"type":"object","properties":{"q":{"type":"string"}}}}],"generation_config":{"max_output_tokens":99,"top_p":0.7,"stop_sequences":["END"],"tool_choice":{"type":"function","name":"lookup"},"thinking_level":"high"}}`), false) + out, _ := ConvertInteractionsRequestToClaude("claude-test", []byte(`{"model":"claude-test","stream":true,"input":[{"type":"user_input","content":[{"type":"text","text":"hi"}]}],"tools":[{"type":"function","name":"lookup","description":"Lookup data","parameters":{"type":"object","properties":{"q":{"type":"string"}}}}],"generation_config":{"max_output_tokens":99,"top_p":0.7,"stop_sequences":["END"],"tool_choice":{"type":"function","name":"lookup"},"thinking_level":"high"}}`), false) if !gjson.GetBytes(out, "stream").Bool() { t.Fatalf("stream should be true when request body asks for stream. Output: %s", string(out)) } @@ -124,7 +124,7 @@ func TestConvertInteractionsRequestToClaudeMapsGenerationConfigToolsAndStreamDir } func TestConvertInteractionsRequestToClaudeAcceptsImageContent(t *testing.T) { - out := ConvertInteractionsRequestToClaude("claude-test", []byte(`{"model":"claude-test","input":[{"type":"user_input","content":[{"type":"image","mime_type":"image/png","data":"aGVsbG8="}]}]}`), false) + out, _ := ConvertInteractionsRequestToClaude("claude-test", []byte(`{"model":"claude-test","input":[{"type":"user_input","content":[{"type":"image","mime_type":"image/png","data":"aGVsbG8="}]}]}`), false) if got := gjson.GetBytes(out, "messages.0.content.0.type").String(); got != "image" { t.Fatalf("content type = %q, want image. Output: %s", got, string(out)) } @@ -137,7 +137,7 @@ func TestConvertInteractionsRequestToClaudeAcceptsImageContent(t *testing.T) { } func TestConvertInteractionsRequestToClaudePreservesNonImageMediaContent(t *testing.T) { - out := ConvertInteractionsRequestToClaude("claude-test", []byte(`{"model":"claude-test","input":[{"type":"thought","content":[{"type":"audio","mime_type":"audio/wav","data":"UklGRg=="},{"type":"video","mime_type":"video/mp4","data":"AAAAIGZ0eXA="},{"type":"document","mime_type":"application/pdf","data":"JVBERi0="}]}]}`), false) + out, _ := ConvertInteractionsRequestToClaude("claude-test", []byte(`{"model":"claude-test","input":[{"type":"thought","content":[{"type":"audio","mime_type":"audio/wav","data":"UklGRg=="},{"type":"video","mime_type":"video/mp4","data":"AAAAIGZ0eXA="},{"type":"document","mime_type":"application/pdf","data":"JVBERi0="}]}]}`), false) if got := gjson.GetBytes(out, "messages.0.role").String(); got != "assistant" { t.Fatalf("messages.0.role = %q, want assistant. Output: %s", got, string(out)) diff --git a/internal/translator/claude/interactions/interactions_claude_user_turn_test.go b/internal/translator/claude/interactions/interactions_claude_user_turn_test.go index 9d810a55004..7408f033a1a 100644 --- a/internal/translator/claude/interactions/interactions_claude_user_turn_test.go +++ b/internal/translator/claude/interactions/interactions_claude_user_turn_test.go @@ -178,7 +178,7 @@ func TestInteractionsToClaudeAssistantStepEndsTheUserTurn(t *testing.T) { func TestInteractionsToClaudeExportedWrapperKeepsAJSONBody(t *testing.T) { input := []byte(`{"model":"m","input":[{"type":"user_input","content":[` + videoByURI + `]}]}`) - if body := ConvertInteractionsRequestToClaude("m", input, false); !gjson.ValidBytes(body) { + if body, _ := ConvertInteractionsRequestToClaude("m", input, false); !gjson.ValidBytes(body) { t.Fatalf("body is not JSON: %q", body) } } diff --git a/internal/translator/claude/openai/chat-completions/claude_openai_compat_test.go b/internal/translator/claude/openai/chat-completions/claude_openai_compat_test.go index cf1b84c1c59..b40bbc9f3c8 100644 --- a/internal/translator/claude/openai/chat-completions/claude_openai_compat_test.go +++ b/internal/translator/claude/openai/chat-completions/claude_openai_compat_test.go @@ -9,12 +9,12 @@ import ( func TestConvertOpenAIRequestToClaudeWithCompatPreservesReasoningContent(t *testing.T) { payload := []byte(`{"messages":[{"role":"assistant","content":"answer","reasoning_content":"reason"}]}`) - withoutCompat := ConvertOpenAIRequestToClaude("deepseek-v4", payload, false) + withoutCompat, _ := ConvertOpenAIRequestToClaude("deepseek-v4", payload, false) if gjson.GetBytes(withoutCompat, "messages.0.content.#(type=thinking)").Exists() { t.Fatalf("default translation preserved reasoning_content: %s", withoutCompat) } - withCompat := ConvertOpenAIRequestToClaudeWithCompat("deepseek-v4", payload, false) + withCompat, _ := ConvertOpenAIRequestToClaudeWithCompat("deepseek-v4", payload, false) part := gjson.GetBytes(withCompat, "messages.0.content.#(type=thinking)") if part.Get("thinking").String() != "reason" || part.Get("signature").String() != "" { t.Fatalf("compat translation missing unsigned thinking block: %s", withCompat) diff --git a/internal/translator/claude/openai/chat-completions/claude_openai_request.go b/internal/translator/claude/openai/chat-completions/claude_openai_request.go index b473bdbcd59..6c6cd1b682d 100644 --- a/internal/translator/claude/openai/chat-completions/claude_openai_request.go +++ b/internal/translator/claude/openai/chat-completions/claude_openai_request.go @@ -33,21 +33,14 @@ import ( // // Returns: // - []byte: The transformed request data in Claude Code API format -func ConvertOpenAIRequestToClaude(modelName string, inputRawJSON []byte, stream bool) []byte { - body, _ := convertOpenAIRequestToClaude(modelName, inputRawJSON, stream, false) - return body +func ConvertOpenAIRequestToClaude(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { + return convertOpenAIRequestToClaude(modelName, inputRawJSON, stream, false) + } // ConvertOpenAIRequestToClaudeWithCompat preserves assistant reasoning content // as an unsigned thinking block for configured compatibility endpoints. -func ConvertOpenAIRequestToClaudeWithCompat(modelName string, inputRawJSON []byte, stream bool) []byte { - body, _ := convertOpenAIRequestToClaude(modelName, inputRawJSON, stream, true) - return body -} - -// ConvertOpenAIRequestToClaudeWithCompatReturningError also reports a file part -// Claude cannot receive when nothing else was left to send. -func ConvertOpenAIRequestToClaudeWithCompatReturningError(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { +func ConvertOpenAIRequestToClaudeWithCompat(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { return convertOpenAIRequestToClaude(modelName, inputRawJSON, stream, true) } diff --git a/internal/translator/claude/openai/chat-completions/claude_openai_request_test.go b/internal/translator/claude/openai/chat-completions/claude_openai_request_test.go index b4c1e72cb0d..ebc4a3962a5 100644 --- a/internal/translator/claude/openai/chat-completions/claude_openai_request_test.go +++ b/internal/translator/claude/openai/chat-completions/claude_openai_request_test.go @@ -19,7 +19,7 @@ func TestConvertOpenAIRequestToClaude_ThinkingSummaryVisibility(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - out := ConvertOpenAIRequestToClaude("claude-opus-5-5", []byte(test.input), false) + out, _ := ConvertOpenAIRequestToClaude("claude-opus-5-5", []byte(test.input), false) if got := gjson.GetBytes(out, "thinking.display").String(); got != test.wanted { t.Fatalf("thinking.display = %q, want %q; body=%s", got, test.wanted, out) } @@ -41,7 +41,7 @@ func TestConvertOpenAIRequestToClaudeWithCompat_GroupsAssistantThinkingTextAndTo } ] }`) - out := ConvertOpenAIRequestToClaudeWithCompat("claude-test", inputJSON, false) + out, _ := ConvertOpenAIRequestToClaudeWithCompat("claude-test", inputJSON, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 1 { t.Fatalf("message count = %d, want 1. Output: %s", len(messages), string(out)) @@ -66,7 +66,7 @@ func TestConvertOpenAIRequestToClaude_MergesToolResultWithAdjacentUserContent(t {"role":"user","content":"continue"} ] }`) - out := ConvertOpenAIRequestToClaude("claude-test", inputJSON, false) + out, _ := ConvertOpenAIRequestToClaude("claude-test", inputJSON, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 2 { t.Fatalf("message count = %d, want 2. Output: %s", len(messages), string(out)) @@ -91,7 +91,7 @@ func TestConvertOpenAIRequestToClaude_SystemDoesNotBreakUserTurnAndCacheBoundary {"role":"user","content":"second"} ] }`) - out := ConvertOpenAIRequestToClaude("claude-test", inputJSON, false) + out, _ := ConvertOpenAIRequestToClaude("claude-test", inputJSON, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 1 { t.Fatalf("message count = %d, want 1. Output: %s", len(messages), string(out)) @@ -139,7 +139,7 @@ func TestConvertOpenAIRequestToClaude_SanitizesToolCallIDsForClaude(t *testing.T ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) toolUseID := resultJSON.Get("messages.0.content.0.id").String() toolResultID := resultJSON.Get("messages.1.content.0.tool_use_id").String() @@ -176,7 +176,7 @@ func TestConvertOpenAIRequestToClaude_GroupsConsecutiveParallelToolResults(t *te ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) messages := resultJSON.Get("messages").Array() @@ -226,7 +226,7 @@ func TestConvertOpenAIRequestToClaude_DropsTemperature(t *testing.T) { ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-5", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-5", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) if resultJSON.Get("temperature").Exists() { @@ -271,7 +271,7 @@ func TestConvertOpenAIRequestToClaude_ToolResultTextAndBase64Image(t *testing.T) ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) messages := resultJSON.Get("messages").Array() @@ -344,7 +344,7 @@ func TestConvertOpenAIRequestToClaude_ToolResultURLImageOnly(t *testing.T) { ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) messages := resultJSON.Get("messages").Array() @@ -376,7 +376,7 @@ func TestConvertOpenAIRequestToClaude_SystemRoleBecomesTopLevelSystem(t *testing ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) system := resultJSON.Get("system") @@ -415,7 +415,7 @@ func TestConvertOpenAIRequestToClaude_MultipleSystemMessagesMergedIntoTopLevelSy ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) system := resultJSON.Get("system").Array() @@ -449,7 +449,7 @@ func TestConvertOpenAIRequestToClaude_SystemOnlyInputKeepsFallbackUserMessage(t ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) system := resultJSON.Get("system").Array() @@ -489,7 +489,7 @@ func TestConvertOpenAIRequestToClaude_PreservesContentPartCacheControl(t *testin ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) if got := resultJSON.Get("messages.0.content.0.cache_control.type").String(); got != "ephemeral" { @@ -515,7 +515,7 @@ func TestConvertOpenAIRequestToClaude_PreservesMessageLevelCacheControl(t *testi ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) if got := resultJSON.Get("messages.0.content.0.cache_control.type").String(); got != "ephemeral" { @@ -543,7 +543,7 @@ func TestConvertOpenAIRequestToClaude_PreservesToolCacheControl(t *testing.T) { ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) if got := resultJSON.Get("tools.0.cache_control.type").String(); got != "ephemeral" { @@ -585,7 +585,7 @@ func TestConvertOpenAIRequestToClaude_NormalizesRootToolSchemaUnions(t *testing. ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) root := gjson.ParseBytes(result) for _, toolName := range []string{"without_type", "constraint_union"} { @@ -619,7 +619,7 @@ func TestConvertOpenAIRequestToClaude_PartCacheControlWinsOverMessageLevel(t *te ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) if got := resultJSON.Get("messages.0.content.0.cache_control.type").String(); got != "ephemeral" { @@ -640,7 +640,7 @@ func TestConvertOpenAIRequestToClaude_DeveloperRoleBecomesTopLevelSystem(t *test ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) system := resultJSON.Get("system").Array() @@ -674,7 +674,7 @@ func TestConvertOpenAIRequestToClaude_DeveloperMessageCacheControlAppliesToLastB ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) system := gjson.ParseBytes(result).Get("system").Array() if len(system) != 2 { t.Fatalf("system blocks = %d, want 2", len(system)) @@ -703,7 +703,7 @@ func TestConvertOpenAIRequestToClaude_DeduplicatesToolResults(t *testing.T) { {"role":"tool","tool_call_id":"","content":"empty id output"} ] }`) - out := ConvertOpenAIRequestToClaude("claude-test", inputJSON, false) + out, _ := ConvertOpenAIRequestToClaude("claude-test", inputJSON, false) root := gjson.ParseBytes(out) messages := root.Get("messages").Array() @@ -781,7 +781,7 @@ func TestConvertOpenAIRequestToClaude_MaxTokensAndMaxCompletionTokens(t *testing for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - out := ConvertOpenAIRequestToClaude("claude-3-7-sonnet-20250219", []byte(tc.rawJSON), false) + out, _ := ConvertOpenAIRequestToClaude("claude-3-7-sonnet-20250219", []byte(tc.rawJSON), false) got := gjson.GetBytes(out, "max_tokens").Int() if got != tc.wantLimit { t.Fatalf("max_tokens = %d, want %d. Output: %s", got, tc.wantLimit, string(out)) @@ -815,7 +815,7 @@ func TestConvertOpenAIRequestToClaude_PreservesCallerSuppliedMetadataUserID(t *t for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - out := ConvertOpenAIRequestToClaude("claude-test", []byte(tc.rawJSON), false) + out, _ := ConvertOpenAIRequestToClaude("claude-test", []byte(tc.rawJSON), false) if !gjson.ValidBytes(out) { t.Fatalf("output is invalid json: %s", string(out)) } @@ -829,7 +829,7 @@ func TestConvertOpenAIRequestToClaude_PreservesCallerSuppliedMetadataUserID(t *t func TestConvertOpenAIRequestToClaude_PreservesOpenAIUserField(t *testing.T) { raw := []byte(`{"model":"claude-test","user":"openai-user-456","messages":[{"role":"user","content":"hello"}]}`) - out := ConvertOpenAIRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIRequestToClaude("claude-test", raw, false) if !gjson.ValidBytes(out) { t.Fatalf("output is invalid json: %s", string(out)) } @@ -842,8 +842,8 @@ func TestConvertOpenAIRequestToClaude_PreservesOpenAIUserField(t *testing.T) { func TestConvertOpenAIRequestToClaude_DifferentSessionsProduceDifferentUserIDs(t *testing.T) { a := []byte(`{"model":"claude-test","prompt_cache_key":"session-a","messages":[{"role":"user","content":"hello"}]}`) b := []byte(`{"model":"claude-test","prompt_cache_key":"session-b","messages":[{"role":"user","content":"hello"}]}`) - outA := ConvertOpenAIRequestToClaude("claude-test", a, false) - outB := ConvertOpenAIRequestToClaude("claude-test", b, false) + outA, _ := ConvertOpenAIRequestToClaude("claude-test", a, false) + outB, _ := ConvertOpenAIRequestToClaude("claude-test", b, false) idA := gjson.GetBytes(outA, "metadata.user_id").String() idB := gjson.GetBytes(outB, "metadata.user_id").String() if idA == idB { @@ -854,8 +854,8 @@ func TestConvertOpenAIRequestToClaude_DifferentSessionsProduceDifferentUserIDs(t func TestConvertOpenAIRequestToClaude_DeterministicWithoutSessionKey(t *testing.T) { first := []byte(`{"model":"claude-test","messages":[{"role":"user","content":"stable first message"}]}`) second := []byte(`{"model":"claude-test","messages":[{"role":"user","content":"stable first message"},{"role":"assistant","content":"hi"},{"role":"user","content":"second message"}]}`) - outFirst := ConvertOpenAIRequestToClaude("claude-test", first, false) - outSecond := ConvertOpenAIRequestToClaude("claude-test", second, false) + outFirst, _ := ConvertOpenAIRequestToClaude("claude-test", first, false) + outSecond, _ := ConvertOpenAIRequestToClaude("claude-test", second, false) idFirst := gjson.GetBytes(outFirst, "metadata.user_id").String() idSecond := gjson.GetBytes(outSecond, "metadata.user_id").String() if idFirst == "" || idFirst == "unknown" { @@ -889,7 +889,7 @@ func TestConvertOpenAIRequestToClaude_ResponseFormatJSONSchema(t *testing.T) { } }`) - out := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", inputJSON, false) + out, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", inputJSON, false) system := gjson.GetBytes(out, "system") if !system.Exists() || !system.IsArray() || len(system.Array()) == 0 { t.Fatalf("system blocks missing or empty. Output: %s", string(out)) @@ -917,7 +917,7 @@ func TestConvertOpenAIRequestToClaude_ResponseFormatJSONObject(t *testing.T) { } }`) - out := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", inputJSON, false) + out, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", inputJSON, false) system := gjson.GetBytes(out, "system") if !system.Exists() || !system.IsArray() || len(system.Array()) == 0 { t.Fatalf("system blocks missing or empty. Output: %s", string(out)) @@ -948,7 +948,7 @@ func TestConvertOpenAIRequestToClaude_ResponseFormatPreservesExistingSystem(t *t } }`) - out := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", inputJSON, false) + out, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", inputJSON, false) system := gjson.GetBytes(out, "system") if !system.Exists() || !system.IsArray() || len(system.Array()) < 2 { t.Fatalf("expected at least 2 system blocks (original + response_format). Output: %s", string(out)) @@ -987,7 +987,7 @@ func TestConvertOpenAIRequestToClaude_ResponseFormatAbsentOrTextNoOp(t *testing. for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - out := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(tt.body), false) + out, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(tt.body), false) if gjson.GetBytes(out, "system").Exists() { t.Fatalf("system blocks should not be created when response_format is absent or text. Output: %s", string(out)) } @@ -1007,7 +1007,7 @@ func TestConvertOpenAIRequestToClaude_ToolResultPartCacheControlHoisted(t *testi ], "tools":[{"type":"function","function":{"name":"calc","description":"calc","parameters":{"type":"object","properties":{"expr":{"type":"string"}},"required":["expr"]}}}] }`) - out := ConvertOpenAIRequestToClaude("claude-test", inputJSON, false) + out, _ := ConvertOpenAIRequestToClaude("claude-test", inputJSON, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 3 { @@ -1049,7 +1049,7 @@ func TestConvertOpenAIRequestToClaude_ToolChoice(t *testing.T) { {"type": "function", "function": {"name": "tool_b", "parameters": {"type": "object", "properties": {}}}} ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) gotType := gjson.GetBytes(result, "tool_choice.type").String() if gotType != "none" { t.Fatalf("expected tool_choice.type to be 'none', got %q. Output: %s", gotType, result) @@ -1065,7 +1065,7 @@ func TestConvertOpenAIRequestToClaude_ToolChoice(t *testing.T) { {"type": "function", "function": {"name": "tool_a", "parameters": {"type": "object", "properties": {}}}} ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) gotType := gjson.GetBytes(result, "tool_choice.type").String() if gotType != "none" { t.Fatalf("expected tool_choice.type to be 'none', got %q. Output: %s", gotType, result) @@ -1088,7 +1088,7 @@ func TestConvertOpenAIRequestToClaude_ToolChoice(t *testing.T) { {"type": "function", "function": {"name": "tool_b", "parameters": {"type": "object", "properties": {}}}} ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) gotType := gjson.GetBytes(result, "tool_choice.type").String() tools := gjson.GetBytes(result, "tools").Array() if gotType != "auto" { @@ -1119,7 +1119,7 @@ func TestConvertOpenAIRequestToClaude_ToolChoice(t *testing.T) { {"type": "function", "function": {"name": "tool_c", "parameters": {"type": "object", "properties": {}}}} ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) gotType := gjson.GetBytes(result, "tool_choice.type").String() tools := gjson.GetBytes(result, "tools").Array() if gotType != "any" { @@ -1140,7 +1140,7 @@ func TestConvertOpenAIRequestToClaude_ToolChoice(t *testing.T) { {"type": "function", "function": {"name": "tool_a", "parameters": {"type": "object", "properties": {}}}} ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) gotType := gjson.GetBytes(result, "tool_choice.type").String() gotDisable := gjson.GetBytes(result, "tool_choice.disable_parallel_tool_use").Bool() if gotType != "any" || !gotDisable { @@ -1158,7 +1158,7 @@ func TestConvertOpenAIRequestToClaude_ToolChoice(t *testing.T) { {"type": "function", "function": {"name": "tool_a", "parameters": {"type": "object", "properties": {}}}} ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) gotDisable := gjson.GetBytes(result, "tool_choice.disable_parallel_tool_use") if gotDisable.Exists() && gotDisable.Bool() { t.Fatalf("expected disable_parallel_tool_use to not be true for parallel_tool_calls=null. Output: %s", result) @@ -1175,7 +1175,7 @@ func TestConvertOpenAIRequestToClaude_ToolChoice(t *testing.T) { {"type": "function", "function": {"name": "tool_a", "parameters": {"type": "object", "properties": {}}}} ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) gotDisable := gjson.GetBytes(result, "tool_choice.disable_parallel_tool_use") if gotDisable.Exists() && gotDisable.Bool() { t.Fatalf("expected disable_parallel_tool_use to not be true for parallel_tool_calls=true. Output: %s", result) @@ -1191,7 +1191,7 @@ func TestConvertOpenAIRequestToClaude_ToolChoice(t *testing.T) { {"type": "function", "function": {"name": "tool_a", "parameters": {"type": "object", "properties": {}}}} ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) gotType := gjson.GetBytes(result, "tool_choice.type").String() gotDisable := gjson.GetBytes(result, "tool_choice.disable_parallel_tool_use").Bool() if gotType != "auto" || !gotDisable { @@ -1213,7 +1213,7 @@ func TestConvertOpenAIRequestToClaude_ToolChoice(t *testing.T) { {"type": "function", "function": {"name": "tool_a", "parameters": {"type": "object", "properties": {}}}} ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) gotType := gjson.GetBytes(result, "tool_choice.type").String() if gotType != "none" { t.Fatalf("expected tool_choice type='none', got %q. Output: %s", gotType, result) @@ -1229,7 +1229,7 @@ func TestConvertOpenAIRequestToClaude_ToolChoice(t *testing.T) { {"type": "function", "function": {"name": "tool_a", "parameters": {"type": "object", "properties": {}}}} ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) gotType := gjson.GetBytes(result, "tool_choice.type").String() if gotType != "none" { t.Fatalf("expected tool_choice type='none', got %q. Output: %s", gotType, result) @@ -1245,7 +1245,7 @@ func TestConvertOpenAIRequestToClaude_ToolChoice(t *testing.T) { {"type": "function", "function": {"name": "tool_a", "parameters": {"type": "object", "properties": {}}}} ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) if gjson.GetBytes(result, "tool_choice").Exists() { t.Fatalf("expected tool_choice not to be set when tool_choice is null, got: %s", result) } @@ -1269,7 +1269,7 @@ func TestConvertOpenAIRequestToClaude_ToolStrict(t *testing.T) { } ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) toolStrict := gjson.GetBytes(result, "tools.0.strict") if !toolStrict.Exists() { t.Fatalf("expected tools.0.strict to exist in Claude output: %s", result) @@ -1295,7 +1295,7 @@ func TestConvertOpenAIRequestToClaude_ToolStrict(t *testing.T) { } ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) toolStrict := gjson.GetBytes(result, "tools.0.strict") if !toolStrict.Exists() || !toolStrict.Bool() { t.Fatalf("expected tools.0.strict to be true, got %s", result) @@ -1318,7 +1318,7 @@ func TestConvertOpenAIRequestToClaude_ToolStrict(t *testing.T) { } ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) toolStrict := gjson.GetBytes(result, "tools.0.strict") if !toolStrict.Exists() { t.Fatalf("expected tools.0.strict to exist in Claude output: %s", result) @@ -1343,7 +1343,7 @@ func TestConvertOpenAIRequestToClaude_ToolStrict(t *testing.T) { } ] }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) if gjson.GetBytes(result, "tools.0.strict").Exists() { t.Fatalf("expected tools.0.strict to be omitted when not provided, got %s", result) } @@ -1402,7 +1402,7 @@ func TestConvertOpenAIRequestToClaude_SanitizesToolNamesAndProvidesFallbackSchem } }` - result := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToClaude("claude-sonnet-4-6", []byte(inputJSON), false) // 1. Tool name in declarations must be sanitized tool0Name := gjson.GetBytes(result, "tools.0.name").String() diff --git a/internal/translator/claude/openai/chat-completions/claude_openai_user_turn_test.go b/internal/translator/claude/openai/chat-completions/claude_openai_user_turn_test.go index 99fa983297a..76cd9dcbc22 100644 --- a/internal/translator/claude/openai/chat-completions/claude_openai_user_turn_test.go +++ b/internal/translator/claude/openai/chat-completions/claude_openai_user_turn_test.go @@ -43,7 +43,7 @@ func TestConvertOpenAIRequestToClaude_RefusesAnyEmptiedUserTurn(t *testing.T) { } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - body, err := ConvertOpenAIRequestToClaudeWithCompatReturningError("m", []byte(tc.input), false) + body, err := ConvertOpenAIRequestToClaudeWithCompat("m", []byte(tc.input), false) var unsupported *translatorcommon.UnsupportedPartError if !errors.As(err, &unsupported) || unsupported.Type != tc.wantType || unsupported.StatusCode() != 400 { t.Fatalf("err = %v, want unsupported content part: %s; body = %s", err, tc.wantType, body) @@ -60,7 +60,7 @@ func TestConvertOpenAIRequestToClaude_RefusesAnyEmptiedUserTurn(t *testing.T) { func TestConvertOpenAIRequestToClaude_KeepsTurnWithTextBesideAttachment(t *testing.T) { input := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[` + userTurnText + `,` + userTurnFileID + `]}]}`) - body, err := ConvertOpenAIRequestToClaudeWithCompatReturningError("m", input, false) + body, err := ConvertOpenAIRequestToClaudeWithCompat("m", input, false) if err != nil { t.Fatalf("err = %v", err) } @@ -71,7 +71,7 @@ func TestConvertOpenAIRequestToClaude_KeepsTurnWithTextBesideAttachment(t *testi func TestConvertOpenAIRequestToClaude_InlineFileAfterHistoryStaysADocument(t *testing.T) { input := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[` + userTurnInline + `]}]}`) - body, err := ConvertOpenAIRequestToClaudeWithCompatReturningError("m", input, false) + body, err := ConvertOpenAIRequestToClaudeWithCompat("m", input, false) if err != nil { t.Fatalf("err = %v", err) } diff --git a/internal/translator/claude/openai/chat-completions/init.go b/internal/translator/claude/openai/chat-completions/init.go index 3073174ca78..f1505748429 100644 --- a/internal/translator/claude/openai/chat-completions/init.go +++ b/internal/translator/claude/openai/chat-completions/init.go @@ -4,20 +4,16 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" - sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( OpenAI, Claude, - nil, + ConvertOpenAIRequestToClaude, interfaces.TranslateResponse{ Stream: ConvertClaudeResponseToOpenAI, NonStream: ConvertClaudeResponseToOpenAINonStream, }, ) - sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatOpenAI, sdktranslator.FormatClaude, func(model string, body []byte, stream bool) ([]byte, error) { - return convertOpenAIRequestToClaude(model, body, stream, false) - }) } diff --git a/internal/translator/claude/openai/responses/claude_openai-responses_interleaved_search_test.go b/internal/translator/claude/openai/responses/claude_openai-responses_interleaved_search_test.go index 338962acd78..807b03c911a 100644 --- a/internal/translator/claude/openai/responses/claude_openai-responses_interleaved_search_test.go +++ b/internal/translator/claude/openai/responses/claude_openai-responses_interleaved_search_test.go @@ -65,7 +65,7 @@ func TestInterleavedThinkingAndSearchSurvivesRoundTrip(t *testing.T) { return true }) req, _ := json.Marshal(map[string]any{"model": "claude-test", "input": items}) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", req, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", req, false) got := claudeAssistantBlockTypes(t, out) want := []string{ diff --git a/internal/translator/claude/openai/responses/claude_openai-responses_reasoning_order_test.go b/internal/translator/claude/openai/responses/claude_openai-responses_reasoning_order_test.go index 95ef9417f98..5b7a1d1b49d 100644 --- a/internal/translator/claude/openai/responses/claude_openai-responses_reasoning_order_test.go +++ b/internal/translator/claude/openai/responses/claude_openai-responses_reasoning_order_test.go @@ -21,7 +21,7 @@ func TestConvertOpenAIResponsesRequestToClaude_KeepsLatestConsecutiveReasoning(t responsesFunctionCallOutputItem("call_latest", "done"), ) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) content := gjson.GetBytes(out, "messages.0.content").Array() wantTypes := []string{"text", "thinking", "tool_use"} if len(content) != len(wantTypes) { @@ -56,7 +56,7 @@ func TestConvertOpenAIResponsesRequestToClaude_ToolCallsSeparateReasoningBlocks( responsesFunctionCallOutputItem("call_second", "second result"), ) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) content := gjson.GetBytes(out, "messages.0.content").Array() wantTypes := []string{"thinking", "tool_use", "thinking", "tool_use"} if len(content) != len(wantTypes) { @@ -96,7 +96,7 @@ func TestConvertOpenAIResponsesRequestToClaude_NonThinkingBlocksSeparateReasonin responsesFunctionCallOutputItem("call_separator", "done"), ) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) content := gjson.GetBytes(out, "messages.0.content").Array() wantTypes := []string{"thinking", "text", "thinking", "redacted_thinking", "thinking", "tool_use"} if len(content) != len(wantTypes) { @@ -153,7 +153,7 @@ func TestConvertOpenAIResponsesRequestToClaude_WebSearchSeparatesToolUseWithThin responsesFunctionCallOutputItem("call_00_abc", "hi"), ) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) content := gjson.GetBytes(out, "messages.1.content").Array() wantTypes := []string{"thinking", "text", "server_tool_use", "web_search_tool_result", "thinking", "tool_use"} if len(content) != len(wantTypes) { @@ -188,7 +188,7 @@ func TestConvertOpenAIResponsesRequestToClaude_WebSearchSeparatesToolUseWithThin responsesFunctionCallOutputItem("call_00_abc", "hi"), ) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) content := gjson.GetBytes(out, "messages.1.content").Array() wantTypes := []string{"thinking", "text", "server_tool_use", "web_search_tool_result", "thinking", "tool_use"} if len(content) != len(wantTypes) { @@ -216,7 +216,7 @@ func TestConvertOpenAIResponsesRequestToClaude_WebSearchSeparatesToolUseWithThin responsesFunctionCallOutputItem("call_00_abc", "hi"), ) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) content := gjson.GetBytes(out, "messages.1.content").Array() wantTypes := []string{"text", "server_tool_use", "web_search_tool_result", "tool_use"} if len(content) != len(wantTypes) { @@ -243,7 +243,7 @@ func TestConvertOpenAIResponsesRequestToClaude_WebSearchSeparatesToolUseWithThin responsesFunctionCallOutputItem("call_00_abc", "hi"), ) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) content := gjson.GetBytes(out, "messages.1.content").Array() wantTypes := []string{"thinking", "text", "thinking", "server_tool_use", "web_search_tool_result", "thinking", "tool_use"} if len(content) != len(wantTypes) { diff --git a/internal/translator/claude/openai/responses/claude_openai-responses_request.go b/internal/translator/claude/openai/responses/claude_openai-responses_request.go index c52ff89ec19..e8bb19b962e 100644 --- a/internal/translator/claude/openai/responses/claude_openai-responses_request.go +++ b/internal/translator/claude/openai/responses/claude_openai-responses_request.go @@ -33,21 +33,14 @@ const ( // - top-level tools and input[].additional_tools -> Claude tools[].input_schema // - max_output_tokens -> max_tokens // - stream passthrough via parameter -func ConvertOpenAIResponsesRequestToClaude(modelName string, inputRawJSON []byte, stream bool) []byte { - body, _ := convertOpenAIResponsesRequestToClaude(modelName, inputRawJSON, stream, false) - return body +func ConvertOpenAIResponsesRequestToClaude(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { + return convertOpenAIResponsesRequestToClaude(modelName, inputRawJSON, stream, false) + } // ConvertOpenAIResponsesRequestToClaudeWithCompat preserves reasoning items // whose encrypted content is empty for configured compatibility endpoints. -func ConvertOpenAIResponsesRequestToClaudeWithCompat(modelName string, inputRawJSON []byte, stream bool) []byte { - body, _ := convertOpenAIResponsesRequestToClaude(modelName, inputRawJSON, stream, true) - return body -} - -// ConvertOpenAIResponsesRequestToClaudeWithCompatReturningError also reports a -// file or audio part Claude cannot receive when it leaves a user turn empty. -func ConvertOpenAIResponsesRequestToClaudeWithCompatReturningError(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { +func ConvertOpenAIResponsesRequestToClaudeWithCompat(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { return convertOpenAIResponsesRequestToClaude(modelName, inputRawJSON, stream, true) } diff --git a/internal/translator/claude/openai/responses/claude_openai-responses_request_test.go b/internal/translator/claude/openai/responses/claude_openai-responses_request_test.go index d95d837271e..fef478b2f06 100644 --- a/internal/translator/claude/openai/responses/claude_openai-responses_request_test.go +++ b/internal/translator/claude/openai/responses/claude_openai-responses_request_test.go @@ -30,7 +30,7 @@ func TestConvertOpenAIResponsesRequestToClaude_SanitizesToolCallIDsForClaude(t * ] }` - result := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) + result, _ := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) toolUseID := resultJSON.Get("messages.0.content.0.id").String() toolResultID := resultJSON.Get("messages.1.content.0.tool_use_id").String() @@ -45,7 +45,7 @@ func TestConvertOpenAIResponsesRequestToClaude_SanitizesToolCallIDsForClaude(t * func TestConvertOpenAIResponsesRequestToClaude_FableMaxTokens(t *testing.T) { t.Run("defaults to 64k", func(t *testing.T) { - out := ConvertOpenAIResponsesRequestToClaude( + out, _ := ConvertOpenAIResponsesRequestToClaude( "claude-fable-5-1", []byte(`{"model":"claude-fable-5-1","input":"hello"}`), true, @@ -56,7 +56,7 @@ func TestConvertOpenAIResponsesRequestToClaude_FableMaxTokens(t *testing.T) { }) t.Run("preserves explicit 128k limit", func(t *testing.T) { - out := ConvertOpenAIResponsesRequestToClaude( + out, _ := ConvertOpenAIResponsesRequestToClaude( "claude-fable-5-1", []byte(`{"model":"claude-fable-5-1","max_output_tokens":128000,"input":"hello"}`), true, @@ -67,7 +67,7 @@ func TestConvertOpenAIResponsesRequestToClaude_FableMaxTokens(t *testing.T) { }) t.Run("does not exceed registered model maximum", func(t *testing.T) { - out := ConvertOpenAIResponsesRequestToClaude( + out, _ := ConvertOpenAIResponsesRequestToClaude( "claude-3-5-haiku-20241022", []byte(`{"model":"claude-3-5-haiku-20241022","input":"hello"}`), true, @@ -78,7 +78,7 @@ func TestConvertOpenAIResponsesRequestToClaude_FableMaxTokens(t *testing.T) { }) t.Run("clamps explicit limit exceeding registered model maximum", func(t *testing.T) { - out := ConvertOpenAIResponsesRequestToClaude( + out, _ := ConvertOpenAIResponsesRequestToClaude( "claude-3-5-haiku-20241022", []byte(`{"model":"claude-3-5-haiku-20241022","max_output_tokens":128000,"input":"hello"}`), true, @@ -89,7 +89,7 @@ func TestConvertOpenAIResponsesRequestToClaude_FableMaxTokens(t *testing.T) { }) t.Run("null max_output_tokens retains default 64k", func(t *testing.T) { - out := ConvertOpenAIResponsesRequestToClaude( + out, _ := ConvertOpenAIResponsesRequestToClaude( "claude-fable-5-1", []byte(`{"model":"claude-fable-5-1","max_output_tokens":null,"input":"hello"}`), true, @@ -123,7 +123,7 @@ func TestConvertOpenAIResponsesRequestToClaude_ReasoningItemToThinkingBlock(t *t ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) root := gjson.ParseBytes(out) assistant := root.Get("messages.0") @@ -168,7 +168,7 @@ func TestConvertOpenAIResponsesRequestToClaude_SignatureOnlyReasoningFlushesBefo ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) root := gjson.ParseBytes(out) thinking := root.Get("messages.0.content.0") @@ -209,7 +209,7 @@ func TestConvertOpenAIResponsesRequestToClaude_RedactedReasoningItemRestoresReda ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) root := gjson.ParseBytes(out) block := root.Get("messages.0.content.0") @@ -244,7 +244,7 @@ func TestConvertOpenAIResponsesRequestToClaude_EmptyRedactedReasoningItemIsDropp ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) root := gjson.ParseBytes(out) if got := root.Get("messages.#").Int(); got != 1 { @@ -274,7 +274,7 @@ func TestConvertOpenAIResponsesRequestToClaude_ReasoningContentTextRebuildsThink ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) root := gjson.ParseBytes(out) thinking := root.Get("messages.0.content.0") @@ -304,7 +304,7 @@ func TestConvertOpenAIResponsesRequestToClaude_SummarySetsThinkingDisplay(t *tes reasoning += "," + test.summary } raw := []byte(`{"model":"claude-opus-5-5","reasoning":{` + reasoning + `},"input":"hi"}`) - out := ConvertOpenAIResponsesRequestToClaude("claude-opus-5-5", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-opus-5-5", raw, false) if got := gjson.GetBytes(out, "thinking.display").String(); got != test.want { t.Fatalf("thinking.display = %q, want %q", got, test.want) } @@ -331,7 +331,7 @@ func TestConvertOpenAIResponsesRequestToClaude_SummaryWinsOverDuplicatedReasonin ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) if got := gjson.ParseBytes(out).Get("messages.0.content.0.thinking").String(); got != "chain of thought" { t.Fatalf("thinking text = %q, want the summary text exactly once. Output: %s", got, string(out)) } @@ -354,7 +354,7 @@ func TestConvertOpenAIResponsesRequestToClaude_DropsIncompatibleReasoningSignatu ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) if gjson.GetBytes(out, "messages.0.content.0.type").String() == "thinking" { t.Fatalf("GPT encrypted_content should not become Claude thinking. Output: %s", string(out)) @@ -407,7 +407,7 @@ func TestConvertOpenAIResponsesRequestToClaude_GroupsAssistantAndToolResultTurns ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) root := gjson.ParseBytes(out) if got := root.Get("messages.#").Int(); got != 2 { t.Fatalf("message count = %d, want 2. Output: %s", got, string(out)) @@ -473,7 +473,7 @@ func TestConvertOpenAIResponsesRequestToClaude_MergesConsecutiveUserMessagesAndP ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) root := gjson.ParseBytes(out) if got := root.Get("messages.#").Int(); got != 1 { t.Fatalf("message count = %d, want 1. Output: %s", got, string(out)) @@ -506,7 +506,7 @@ func TestConvertOpenAIResponsesRequestToClaude_DoesNotMergeAcrossRoleChanges(t * ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) root := gjson.ParseBytes(out) messages := root.Get("messages").Array() if len(messages) != 3 { @@ -529,7 +529,7 @@ func TestConvertOpenAIResponsesRequestToClaude_EmptyStringContentDoesNotBreakAss ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) root := gjson.ParseBytes(out) messages := root.Get("messages").Array() if len(messages) != 1 { @@ -578,7 +578,7 @@ func TestConvertOpenAIResponsesRequestToClaude_FunctionCallOutputPreservesInputI ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) root := gjson.ParseBytes(out) toolResult := root.Get("messages.1.content.0") @@ -620,7 +620,7 @@ func TestConvertOpenAIResponsesRequestToClaude_StandaloneToolOutputBecomesUserTe ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) root := gjson.ParseBytes(out) root.Get("messages").ForEach(func(_, msg gjson.Result) bool { @@ -656,7 +656,7 @@ func TestConvertOpenAIResponsesRequestToClaude_SynthesizesResultForDanglingToolU ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) root := gjson.ParseBytes(out) if got := root.Get("messages.#").Int(); got != 3 { @@ -688,7 +688,7 @@ func TestConvertOpenAIResponsesRequestToClaude_SynthesizesResultForTrailingToolU ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) root := gjson.ParseBytes(out) if got := root.Get("messages.#").Int(); got != 3 { @@ -719,7 +719,7 @@ func TestConvertOpenAIResponsesRequestToClaude_MovesToolResultsAheadOfInjectedTe ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) root := gjson.ParseBytes(out) if got := root.Get("messages.#").Int(); got != 3 { @@ -755,7 +755,7 @@ func TestConvertOpenAIResponsesRequestToClaude_SynthesizesResultForTrailingToolU ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-fable-5-1", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-fable-5-1", raw, false) root := gjson.ParseBytes(out) if got := root.Get("messages.#").Int(); got != 3 { @@ -791,7 +791,7 @@ func TestConvertOpenAIResponsesRequestToClaude_LateOrphanToolResultFoldsToText(t ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) root := gjson.ParseBytes(out) // messages: user | assistant(tool_use call_a) | user | assistant(text) | user @@ -839,7 +839,7 @@ func TestConvertOpenAIResponsesRequestToClaude_EmptyStandaloneToolOutputKeepsMar ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) root := gjson.ParseBytes(out) if got := root.Get("messages.#").Int(); got != 1 { @@ -878,7 +878,7 @@ func TestConvertOpenAIResponsesRequestToClaude_SanitizedIDCollisionKeepsOrphanAs ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) root := gjson.ParseBytes(out) blocks := root.Get("messages.2.content").Array() @@ -914,7 +914,7 @@ func TestConvertOpenAIResponsesRequestToClaude_EmptyLateOrphanToolResultKeepsNon ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-fable-5-1", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-fable-5-1", raw, false) root := gjson.ParseBytes(out) root.Get("messages").ForEach(func(_, msg gjson.Result) bool { @@ -953,7 +953,7 @@ func TestConvertOpenAIResponsesRequestToClaude_LateOrphanToolResultArrayOfEmptyT ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-fable-5-1", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-fable-5-1", raw, false) root := gjson.ParseBytes(out) root.Get("messages").ForEach(func(_, msg gjson.Result) bool { @@ -984,7 +984,7 @@ func TestConvertOpenAIResponsesRequestToClaude_StandaloneToolOutputDropsEmptyTex ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) root := gjson.ParseBytes(out) root.Get("messages").ForEach(func(_, msg gjson.Result) bool { @@ -1064,7 +1064,7 @@ func TestConvertOpenAIResponsesRequestToClaude_KeepsToolUseAdjacentToToolResult( ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) root := gjson.ParseBytes(out) if got := root.Get("messages.#").Int(); got != 2 { @@ -1110,7 +1110,7 @@ func TestConvertOpenAIResponsesRequestToClaude_KeepsApplyPatchCustomTool(t *test ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) root := gjson.ParseBytes(out) if got := root.Get("tools.#").Int(); got != 2 { @@ -1142,7 +1142,7 @@ func TestConvertOpenAIResponsesRequestToClaude_NormalizesRootToolSchemaUnion(t * }] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) schema := gjson.GetBytes(out, "tools.0.input_schema") if got := schema.Get("type").String(); got != "object" { @@ -1192,7 +1192,11 @@ func TestConvertOpenAIResponsesRequestToClaude_MergesAdditionalToolsAndPrefersTo ] }`) - root := gjson.ParseBytes(ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false)) + body1, errConvert1 := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + if errConvert1 != nil { + t.Fatal(errConvert1) + } + root := gjson.ParseBytes(body1) if got := root.Get("tools.#").Int(); got != 4 { t.Fatalf("tools count = %d, want 4; output=%s", got, root.Raw) } @@ -1224,7 +1228,11 @@ func TestConvertOpenAIResponsesRequestToClaude_DeduplicatesExpandedToolNames(t * ]}]}] }`) - root := gjson.ParseBytes(ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false)) + body2, errConvert2 := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + if errConvert2 != nil { + t.Fatal(errConvert2) + } + root := gjson.ParseBytes(body2) if got := root.Get("tools.#").Int(); got != 2 { t.Fatalf("tools count = %d, want 2; output=%s", got, root.Raw) } @@ -1254,7 +1262,11 @@ func TestConvertOpenAIResponsesRequestToClaude_DirectToolWinsOverEarlierNamespac "tool_choice":{"type":"custom","name":"n__x"} }`) - root := gjson.ParseBytes(ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false)) + body3, errConvert3 := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + if errConvert3 != nil { + t.Fatal(errConvert3) + } + root := gjson.ParseBytes(body3) if got := root.Get("tools.#").Int(); got != 1 { t.Fatalf("tools count = %d, want 1; output=%s", got, root.Raw) } @@ -1281,7 +1293,11 @@ func TestConvertOpenAIResponsesRequestToClaude_PrefersDirectToolAcrossAdditional ] }`) - root := gjson.ParseBytes(ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false)) + body4, errConvert4 := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + if errConvert4 != nil { + t.Fatal(errConvert4) + } + root := gjson.ParseBytes(body4) if got := root.Get("tools.#").Int(); got != 1 { t.Fatalf("tools count = %d, want 1; output=%s", got, root.Raw) } @@ -1310,7 +1326,11 @@ func TestConvertOpenAIResponsesRequestToClaude_PreservesToolDeclarationOrder(t * ] }`) - root := gjson.ParseBytes(ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false)) + body5, errConvert5 := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + if errConvert5 != nil { + t.Fatal(errConvert5) + } + root := gjson.ParseBytes(body5) want := []string{"first", "n__middle", "last"} got := root.Get("tools.#.name").Array() if len(got) != len(want) { @@ -1332,7 +1352,11 @@ func TestConvertOpenAIResponsesRequestToClaude_ReplaysCustomToolCallHistory(t *t ] }`) - root := gjson.ParseBytes(ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false)) + body6, errConvert6 := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + if errConvert6 != nil { + t.Fatal(errConvert6) + } + root := gjson.ParseBytes(body6) toolUse := root.Get("messages.0.content.0") if got := toolUse.Get("type").String(); got != "tool_use" { t.Fatalf("tool use type = %q, want tool_use; output=%s", got, root.Raw) @@ -1365,7 +1389,11 @@ func TestConvertOpenAIResponsesRequestToClaude_ReplaysNamespacedFunctionCallHist ] }`) - root := gjson.ParseBytes(ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false)) + body7, errConvert7 := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + if errConvert7 != nil { + t.Fatal(errConvert7) + } + root := gjson.ParseBytes(body7) if !root.Get(`tools.#(name=="mcp__node_repl__js")`).Exists() { t.Fatal("missing qualified namespace tool declaration") } @@ -1416,7 +1444,11 @@ func TestConvertOpenAIResponsesRequestToClaude_MapsCustomAndNamespacedToolChoice for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - root := gjson.ParseBytes(ConvertOpenAIResponsesRequestToClaude("claude-test", []byte(tt.raw), false)) + body8, errConvert8 := ConvertOpenAIResponsesRequestToClaude("claude-test", []byte(tt.raw), false) + if errConvert8 != nil { + t.Fatal(errConvert8) + } + root := gjson.ParseBytes(body8) if got := root.Get("tool_choice.type").String(); got != "tool" { t.Fatalf("tool_choice.type = %q, want tool; output=%s", got, root.Raw) } @@ -1449,7 +1481,11 @@ func TestQualifyResponsesNamespaceToolNameAvoidsPrefixCollision(t *testing.T) { raw := []byte(`{ "tools":[{"type":"namespace","name":"collab","tools":[{"type":"function","name":"collaboration"}]}] }`) - root := gjson.ParseBytes(ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false)) + body9, errConvert9 := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + if errConvert9 != nil { + t.Fatal(errConvert9) + } + root := gjson.ParseBytes(body9) if got := root.Get("tools.0.name").String(); got != "collab__collaboration" { t.Fatalf("qualified tool declaration = %q, want collab__collaboration", got) } @@ -1527,7 +1563,7 @@ func TestConvertOpenAIResponsesRequestToClaude_PreservesContentPartCacheControl( ] }` - result := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) + result, _ := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) content := resultJSON.Get("messages.0.content") @@ -1555,7 +1591,7 @@ func TestConvertOpenAIResponsesRequestToClaude_SystemLevelInputsBecomeSeparateSy ] }` - result := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) + result, _ := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-4-5", []byte(inputJSON), false) root := gjson.ParseBytes(result) system := root.Get("system").Array() @@ -1594,7 +1630,11 @@ func TestConvertOpenAIResponsesRequestToClaude_SystemLevelInputsBecomeSeparateSy func TestConvertOpenAIResponsesRequestToClaude_SystemOnlyInputKeepsFallbackUserMessage(t *testing.T) { inputJSON := `{"model": "gpt-4.1", "instructions": "I1"}` - root := gjson.ParseBytes(ConvertOpenAIResponsesRequestToClaude("claude-opus-5", []byte(inputJSON), false)) + body10, errConvert10 := ConvertOpenAIResponsesRequestToClaude("claude-opus-5", []byte(inputJSON), false) + if errConvert10 != nil { + t.Fatal(errConvert10) + } + root := gjson.ParseBytes(body10) if got := len(root.Get("system").Array()); got != 1 { t.Fatalf("system blocks = %d, want 1", got) } @@ -1619,7 +1659,11 @@ func TestConvertOpenAIResponsesRequestToClaude_SystemNonTextPartKeptAsTypedMarke ] }` - root := gjson.ParseBytes(ConvertOpenAIResponsesRequestToClaude("claude-opus-5", []byte(inputJSON), false)) + body11, errConvert11 := ConvertOpenAIResponsesRequestToClaude("claude-opus-5", []byte(inputJSON), false) + if errConvert11 != nil { + t.Fatal(errConvert11) + } + root := gjson.ParseBytes(body11) system := root.Get("system").Array() if len(system) != 2 { t.Fatalf("system blocks = %d, want 2. system: %s", len(system), root.Get("system").Raw) @@ -1647,7 +1691,11 @@ func TestConvertOpenAIResponsesRequestToClaude_SystemItemCacheControlAppliesToLa ] }` - system := gjson.ParseBytes(ConvertOpenAIResponsesRequestToClaude("claude-opus-5", []byte(inputJSON), false)).Get("system").Array() + body12, errConvert12 := ConvertOpenAIResponsesRequestToClaude("claude-opus-5", []byte(inputJSON), false) + if errConvert12 != nil { + t.Fatal(errConvert12) + } + system := gjson.ParseBytes(body12).Get("system").Array() if len(system) != 2 { t.Fatalf("system blocks = %d, want 2", len(system)) } @@ -1721,7 +1769,7 @@ func TestConvertOpenAIResponsesRequestToClaude_DeduplicatesToolOutputs(t *testin ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) root := gjson.ParseBytes(out) messages := root.Get("messages").Array() @@ -1889,7 +1937,7 @@ func TestConvertOpenAIResponsesRequestToClaude_ServiceTierToSpeed(t *testing.T) } raw += `}` - out := ConvertOpenAIResponsesRequestToClaude("claude-3-7-sonnet-20250219", []byte(raw), false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-3-7-sonnet-20250219", []byte(raw), false) root := gjson.ParseBytes(out) speedResult := root.Get("speed") @@ -1928,7 +1976,7 @@ func TestConvertOpenAIResponsesRequestToClaude_PreservesCallerSuppliedMetadataUs for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - out := ConvertOpenAIResponsesRequestToClaude("claude-test", []byte(tc.rawJSON), false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", []byte(tc.rawJSON), false) if !gjson.ValidBytes(out) { t.Fatalf("output is invalid json: %s", string(out)) } @@ -1942,7 +1990,7 @@ func TestConvertOpenAIResponsesRequestToClaude_PreservesCallerSuppliedMetadataUs func TestConvertOpenAIResponsesRequestToClaude_PreservesUserField(t *testing.T) { raw := []byte(`{"model":"claude-test","user":"openai-resp-user-456","input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"hello"}]}]}`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) if !gjson.ValidBytes(out) { t.Fatalf("output is invalid json: %s", string(out)) } @@ -1955,8 +2003,8 @@ func TestConvertOpenAIResponsesRequestToClaude_PreservesUserField(t *testing.T) func TestConvertOpenAIResponsesRequestToClaude_DifferentSessionsProduceDifferentUserIDs(t *testing.T) { a := []byte(`{"model":"claude-test","prompt_cache_key":"resp-session-a","input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"hello"}]}]}`) b := []byte(`{"model":"claude-test","prompt_cache_key":"resp-session-b","input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"hello"}]}]}`) - outA := ConvertOpenAIResponsesRequestToClaude("claude-test", a, false) - outB := ConvertOpenAIResponsesRequestToClaude("claude-test", b, false) + outA, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", a, false) + outB, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", b, false) idA := gjson.GetBytes(outA, "metadata.user_id").String() idB := gjson.GetBytes(outB, "metadata.user_id").String() if idA == idB { @@ -1981,8 +2029,8 @@ func TestConvertOpenAIResponsesRequestToClaude_DifferentUserContentWithSameSyste {"type": "message", "role": "user", "content": "user question B"} ] }`) - outA := ConvertOpenAIResponsesRequestToClaude("claude-test", rawA, false) - outB := ConvertOpenAIResponsesRequestToClaude("claude-test", rawB, false) + outA, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", rawA, false) + outB, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", rawB, false) idA := gjson.GetBytes(outA, "metadata.user_id").String() idB := gjson.GetBytes(outB, "metadata.user_id").String() if idA == "" || idB == "" || idA == "unknown" || idB == "unknown" { @@ -2001,7 +2049,7 @@ func TestConvertOpenAIResponsesRequestToClaude_FableStripsTrailingAssistantPrefi {"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "progress update"}]} ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-fable-5", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-fable-5", raw, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 1 { t.Fatalf("expected 1 message after stripping trailing assistant prefill, got %d: %s", len(messages), string(out)) @@ -2021,7 +2069,7 @@ func TestConvertOpenAIResponsesRequestToClaude_FableOnlyAssistantMessageYieldsFa {"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "orphan progress"}]} ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-fable-5", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-fable-5", raw, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 1 { t.Fatalf("expected 1 fallback user message, got %d: %s", len(messages), string(out)) @@ -2058,7 +2106,7 @@ func TestConvertOpenAIResponsesRequestToClaude_UnsupportedPrefillModelsStripTrai {"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "progress update"}]} ] }`, model)) - out := ConvertOpenAIResponsesRequestToClaude(model, raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude(model, raw, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 1 { t.Fatalf("expected 1 message after stripping trailing assistant prefill for model %s, got %d: %s", model, len(messages), string(out)) @@ -2101,7 +2149,7 @@ func TestConvertOpenAIResponsesRequestToClaude_SupportedPrefillModelsPreserveAss {"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "prefill text"}]} ] }`, model)) - out := ConvertOpenAIResponsesRequestToClaude(model, raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude(model, raw, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 2 { t.Fatalf("expected 2 messages preserving assistant prefill for model %s, got %d: %s", model, len(messages), string(out)) @@ -2124,7 +2172,7 @@ func TestConvertOpenAIResponsesRequestToClaudeWithCompat_FablePreservesAssistant {"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "prefill text"}]} ] }`) - out := ConvertOpenAIResponsesRequestToClaudeWithCompat("claude-fable-5", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaudeWithCompat("claude-fable-5", raw, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 2 { t.Fatalf("expected 2 messages in compat mode, got %d: %s", len(messages), string(out)) @@ -2145,7 +2193,7 @@ func TestConvertOpenAIResponsesRequestToClaude_StripsTrailingThinkingBlocksFromA {"type": "reasoning", "encrypted_content": %q, "summary": [{"type": "summary_text", "text": "thought"}]} ] }`, rawSignature)) - out := ConvertOpenAIResponsesRequestToClaude("claude-haiku-4-5-20251001", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-haiku-4-5-20251001", raw, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 1 { t.Fatalf("expected 1 message (user only) after stripping trailing thinking, got %d: %s", len(messages), string(out)) @@ -2167,7 +2215,7 @@ func TestConvertOpenAIResponsesRequestToClaude_StripsTrailingThinkingBlocksFromA {"type": "reasoning", "encrypted_content": %q, "summary": [{"type": "summary_text", "text": "thought"}]} ] }`, rawSignature)) - out := ConvertOpenAIResponsesRequestToClaude("claude-haiku-4-5-20251001", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-haiku-4-5-20251001", raw, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 2 { t.Fatalf("expected 2 messages (user + assistant text), got %d: %s", len(messages), string(out)) @@ -2190,7 +2238,7 @@ func TestConvertOpenAIResponsesRequestToClaude_StripsTrailingThinkingBlocksFromA {"type": "reasoning", "encrypted_content": %q, "summary": []} ] }`, rawSignature, ClaudeResponsesRedactedThinkingPrefix+"redacted-data")) - out := ConvertOpenAIResponsesRequestToClaude("claude-haiku-4-5-20251001", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-haiku-4-5-20251001", raw, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 2 { t.Fatalf("expected 2 messages (user + assistant text), got %d: %s", len(messages), string(out)) @@ -2207,7 +2255,7 @@ func TestConvertOpenAIResponsesRequestToClaude_StripsTrailingThinkingBlocksFromA {"type": "reasoning", "encrypted_content": %q, "summary": [{"type": "summary_text", "text": "thought"}]} ] }`, rawSignature)) - out := ConvertOpenAIResponsesRequestToClaude("claude-haiku-4-5-20251001", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-haiku-4-5-20251001", raw, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 1 { t.Fatalf("expected 1 message (fallback user), got %d: %s", len(messages), string(out)) @@ -2225,7 +2273,7 @@ func TestConvertOpenAIResponsesRequestToClaude_StripsTrailingThinkingBlocksFromA {"type": "reasoning", "encrypted_content": %q, "summary": [{"type": "summary_text", "text": "thought"}]} ] }`, rawSignature)) - out := ConvertOpenAIResponsesRequestToClaudeWithCompat("claude-haiku-4-5-20251001", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaudeWithCompat("claude-haiku-4-5-20251001", raw, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 2 { t.Fatalf("expected 2 messages in compat mode, got %d: %s", len(messages), string(out)) @@ -2241,13 +2289,16 @@ func TestConvertOpenAIResponsesRequestToClaudeKeepsAgentMessageText(t *testing.T for _, tc := range []struct { name string - fn func(string, []byte, bool) []byte + fn func(string, []byte, bool) ([]byte, error) }{ {"standard", ConvertOpenAIResponsesRequestToClaude}, {"compat", ConvertOpenAIResponsesRequestToClaudeWithCompat}, } { t.Run(tc.name, func(t *testing.T) { - out := tc.fn("claude-fable-5-1", in, false) + out, errConvert := tc.fn("claude-fable-5-1", in, false) + if errConvert != nil { + t.Fatal(errConvert) + } root := gjson.ParseBytes(out) messages := root.Get("messages").Array() if len(messages) != 1 { @@ -2276,7 +2327,7 @@ func TestConvertOpenAIResponsesRequestToClaudeKeepsAgentMessageText(t *testing.T {"type":"encrypted_content","encrypted_content":"step 2"} ]} ]}`) - out := ConvertOpenAIResponsesRequestToClaude("claude-fable-5-1", mixedIn, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-fable-5-1", mixedIn, false) root := gjson.ParseBytes(out) parts := root.Get("messages.0.content").Array() if len(parts) != 2 { @@ -2313,7 +2364,7 @@ func TestConvertOpenAIResponsesRequestToClaude_TextFormatStructuredOutput(t *tes } } }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-4-6", input, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-4-6", input, false) system := gjson.GetBytes(out, "system") if !system.Exists() || len(system.Array()) == 0 { t.Fatalf("system blocks missing. Output: %s", string(out)) @@ -2340,7 +2391,7 @@ func TestConvertOpenAIResponsesRequestToClaude_TextFormatStructuredOutput(t *tes } } }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-4-6", input, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-4-6", input, false) system := gjson.GetBytes(out, "system") if !system.Exists() || len(system.Array()) == 0 { t.Fatalf("system blocks missing. Output: %s", string(out)) @@ -2374,7 +2425,7 @@ func TestConvertOpenAIResponsesRequestToClaude_TextFormatStructuredOutput(t *tes "type": "json_object" } }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-4-6", input, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-4-6", input, false) system := gjson.GetBytes(out, "system") if !system.Exists() || len(system.Array()) < 2 { t.Fatalf("expected at least 2 system blocks. Output: %s", string(out)) @@ -2450,7 +2501,7 @@ func TestConvertOpenAIResponsesRequestToClaude_FunctionCallOutputAlternateIDsAnd ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-4-6", inputJSON, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-4-6", inputJSON, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 3 { t.Fatalf("expected 3 messages (user, assistant, user), got %d; output=%s", len(messages), string(out)) @@ -2496,7 +2547,7 @@ func TestConvertOpenAIResponsesRequestToClaude_MixedMissingAndExplicitParallelOu ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-4-6", inputJSON, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-4-6", inputJSON, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 3 { t.Fatalf("expected 3 messages, got %d; output=%s", len(messages), string(out)) @@ -2537,7 +2588,7 @@ func TestConvertOpenAIResponsesRequestToClaude_MixedMissingAndExplicitParallelOu ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-4-6", inputJSON, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-4-6", inputJSON, false) messages := gjson.GetBytes(out, "messages").Array() resultMap := make(map[string]string) for _, m := range messages { @@ -2566,7 +2617,7 @@ func TestConvertOpenAIResponsesRequestToClaude_StringInput(t *testing.T) { "stream": false }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-4-6", inputJSON, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-4-6", inputJSON, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 1 { t.Fatalf("expected 1 message in translated Claude request, got %d. Output: %s", len(messages), string(out)) @@ -2604,7 +2655,7 @@ func TestConvertOpenAIResponsesRequestToClaude_StringInput(t *testing.T) { "max_output_tokens": 32, "stream": false }`) - outWithInstr := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-4-6", withInstructions, false) + outWithInstr, _ := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-4-6", withInstructions, false) system := gjson.GetBytes(outWithInstr, "system").Array() if len(system) != 1 || system[0].Get("text").String() != "Be concise." { t.Fatalf("expected system block with instructions, got %s", string(outWithInstr)) @@ -2624,7 +2675,7 @@ func TestConvertOpenAIResponsesRequestToClaude_StringInput(t *testing.T) { "max_output_tokens": 16, "stream": false }`) - outComplex := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-4-6", complexInput, false) + outComplex, _ := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-4-6", complexInput, false) complexMsgs := gjson.GetBytes(outComplex, "messages").Array() if len(complexMsgs) != 1 { t.Fatalf("expected 1 message in translated Claude request with complex input, got %d. Output: %s", len(complexMsgs), string(outComplex)) @@ -2649,7 +2700,7 @@ func TestConvertOpenAIResponsesRequestToClaude_LongToolNamesUniqueAndReversible( }] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-5-5", reqJSON, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-5-5", reqJSON, false) tools := gjson.GetBytes(out, "tools").Array() if len(tools) != 2 { t.Fatalf("expected 2 tools, got %d", len(tools)) @@ -2746,7 +2797,7 @@ func TestConvertOpenAIResponsesRequestToClaude_SanitizationCollisions(t *testing ] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-5-5", reqJSON, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-5-5", reqJSON, false) tools := gjson.GetBytes(out, "tools").Array() if len(tools) != 2 { t.Fatalf("expected 2 tools, got %d", len(tools)) @@ -2800,7 +2851,7 @@ func TestConvertOpenAIResponsesRequestToClaude_LongToolChoiceAndHistory(t *testi }] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-5-5", reqJSON, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-5-5", reqJSON, false) // Tool definition name for prices declaredPricesName := gjson.GetBytes(out, "tools.0.name").String() @@ -2830,7 +2881,11 @@ func TestConvertOpenAIResponsesRequestToClaude_LongToolChoiceAndHistory(t *testi func TestApplyPatchClaudeRequestContractAndHistory(t *testing.T) { request := []byte(`{"tools":[{"type":"namespace","name":"editor","tools":[{"type":"custom","name":"apply_patch","description":"Edit files. This is a FREEFORM tool, so do not wrap the patch in JSON.","format":{"type":"grammar","syntax":"lark","definition":"start: patch"},"cache_control":{"type":"ephemeral"}}]}],"input":[{"type":"custom_tool_call","namespace":"editor","name":"apply_patch","call_id":"c1","input":"*** Begin Patch\n*** Add File: a.txt\n+hello\n*** End Patch"},{"type":"custom_tool_call_output","call_id":"c1","output":"done"}]}`) - result := gjson.ParseBytes(ConvertOpenAIResponsesRequestToClaude("test", request, false)) + body13, errConvert13 := ConvertOpenAIResponsesRequestToClaude("test", request, false) + if errConvert13 != nil { + t.Fatal(errConvert13) + } + result := gjson.ParseBytes(body13) tool := result.Get("tools.0") description := tool.Get("description").String() schema := tool.Get("input_schema") diff --git a/internal/translator/claude/openai/responses/claude_openai-responses_server_tool_test.go b/internal/translator/claude/openai/responses/claude_openai-responses_server_tool_test.go index 1e5c7b61260..7239c1c2a67 100644 --- a/internal/translator/claude/openai/responses/claude_openai-responses_server_tool_test.go +++ b/internal/translator/claude/openai/responses/claude_openai-responses_server_tool_test.go @@ -86,7 +86,7 @@ func TestWebSearchCallItemReplaysAsClaudeServerToolBlocks(t *testing.T) { "action":{"type":"search","query":"lindorm vector"}, "results":[{"title":"Lindorm Vector","url":"https://example.com/a","encrypted_content":"ENC_A"}] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) if got := claudeAssistantBlockTypes(t, out); len(got) != 2 || got[0] != "server_tool_use" || got[1] != "web_search_tool_result" { @@ -123,7 +123,7 @@ func TestWebSearchCallWithoutEncryptedContentReplaysEmptyResults(t *testing.T) { "action":{"type":"search","query":"q"}, "results":[{"title":"T","url":"https://example.com/a"}] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) if got := claudeAssistantBlockTypes(t, out); len(got) != 2 { t.Fatalf("assistant blocks = %v, want the server_tool_use/result pair", got) } @@ -139,7 +139,7 @@ func TestOutputTextAnnotationsReplayAsClaudeCitations(t *testing.T) { {"type":"web_search_result_location","url":"https://example.com/a","title":"A","cited_text":"Answer","encrypted_index":"IDX_A"} ]}] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) block := gjson.GetBytes(out, "messages.0.content.0") if got := block.Get("type").String(); got != "text" { t.Fatalf("block type = %q", got) @@ -163,7 +163,7 @@ func TestAnnotationsWithoutEncryptedIndexAreNotReplayedAsCitations(t *testing.T) {"type":"url_citation","url":"https://example.com/a","title":"A"} ]}] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) if gjson.GetBytes(out, "messages.0.content.0.citations").Exists() { t.Fatal("citations without encrypted_index must be dropped, not sent") } @@ -174,7 +174,7 @@ func TestRefusalPartReplaysAsClaudeText(t *testing.T) { "type":"message","role":"assistant", "content":[{"type":"refusal","refusal":"I cannot help with that."}] }`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) block := gjson.GetBytes(out, "messages.0.content") text := block.Get("0.text").String() if block.Type == gjson.String { @@ -225,7 +225,7 @@ func TestRoundTripPreservesReachableClaudeBlocks(t *testing.T) { return true }) req, _ := json.Marshal(map[string]any{"model": "claude-test", "input": items}) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", req, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", req, false) got := claudeAssistantBlockTypes(t, out) want := []string{"thinking", "text", "server_tool_use", "web_search_tool_result", "thinking", "tool_use"} @@ -256,7 +256,7 @@ func TestWebSearchCallIDNormalisedToClaudeServerToolPattern(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { raw := responsesRequestFromItems(`{"type":"web_search_call","id":"` + tc.responsesID + `","status":"completed","action":{"type":"search","query":"q"}}`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) blocks := gjson.GetBytes(out, "messages.0.content") if got := blocks.Get("0.id").String(); got != tc.want { t.Fatalf("server_tool_use id = %q, want %q", got, tc.want) @@ -271,7 +271,7 @@ func TestWebSearchCallIDNormalisedToClaudeServerToolPattern(t *testing.T) { func TestWebSearchCallWithoutIDProducesNoBlocks(t *testing.T) { for _, id := range []string{``, `ws_`} { raw := responsesRequestFromItems(`{"type":"web_search_call","id":"` + id + `","status":"completed","action":{"type":"search","query":"q"}}`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) if got := claudeAssistantBlockTypes(t, out); len(got) != 0 { t.Fatalf("id=%q produced %v; an unpairable server_tool_use is rejected by Anthropic", id, got) } @@ -360,7 +360,7 @@ func TestWebSearchCallQueryAcceptsNativeOpenAIActionShapes(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { raw := responsesRequestFromItems(`{"type":"web_search_call","id":"ws_srvtoolu_1","status":"completed","action":` + tc.action + `}`) - out := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) + out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false) if got := gjson.GetBytes(out, "messages.0.content.0.input.query").String(); got != tc.want { t.Fatalf("input.query = %q, want %q", got, tc.want) } @@ -422,7 +422,7 @@ func TestClaudeWebSearchErrorResultSurvivesRoundTrip(t *testing.T) { // Replay back to Claude req, _ := json.Marshal(map[string]any{"model": "claude-test", "input": []json.RawMessage{json.RawMessage(outputItems[0].Raw)}}) - replayed := ConvertOpenAIResponsesRequestToClaude("claude-test", req, false) + replayed, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", req, false) replayedBlocks := gjson.GetBytes(replayed, "messages.0.content") if got := replayedBlocks.Get("1.content.0.type").String(); got != "web_search_tool_result_error" { t.Fatalf("replayed error type = %q, want web_search_tool_result_error", got) @@ -503,7 +503,7 @@ func TestTextSearchTextOrderPreservedInStreamingAndReplay(t *testing.T) { rawItems = append(rawItems, json.RawMessage(it.Raw)) } req, _ := json.Marshal(map[string]any{"model": "claude-test", "input": rawItems}) - replayed := ConvertOpenAIResponsesRequestToClaude("claude-test", req, false) + replayed, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", req, false) replayedBlocks := claudeAssistantBlockTypes(t, replayed) wantBlocks := []string{"text", "server_tool_use", "web_search_tool_result", "text"} if strings.Join(replayedBlocks, ",") != strings.Join(wantBlocks, ",") { diff --git a/internal/translator/claude/openai/responses/claude_openai-responses_user_turn_test.go b/internal/translator/claude/openai/responses/claude_openai-responses_user_turn_test.go index 94782a7bda2..a2d40e851be 100644 --- a/internal/translator/claude/openai/responses/claude_openai-responses_user_turn_test.go +++ b/internal/translator/claude/openai/responses/claude_openai-responses_user_turn_test.go @@ -81,7 +81,7 @@ func TestConvertOpenAIResponsesRequestToClaude_RefusesAnyEmptiedUserTurn(t *test } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - body, err := ConvertOpenAIResponsesRequestToClaudeWithCompatReturningError("claude-sonnet-4", tc.input, false) + body, err := ConvertOpenAIResponsesRequestToClaudeWithCompat("claude-sonnet-4", tc.input, false) var unsupported *translatorcommon.UnsupportedPartError if !errors.As(err, &unsupported) || unsupported.Type != tc.wantType || unsupported.StatusCode() != 400 { t.Fatalf("err = %v, want unsupported content part: %s; body = %s", err, tc.wantType, body) @@ -106,7 +106,7 @@ func TestConvertOpenAIResponsesRequestToClaude_KeepsTurnWithTextBesideAttachment for name, attachment := range map[string]string{"file id": responsesFileIDPart, "audio": responsesAudioPart} { t.Run(name, func(t *testing.T) { input := responsesPayload("", responsesUserHello, responsesAssistantHi, responsesUserTurn(responsesTextPart, attachment)) - body, err := ConvertOpenAIResponsesRequestToClaudeWithCompatReturningError("claude-sonnet-4", input, false) + body, err := ConvertOpenAIResponsesRequestToClaudeWithCompat("claude-sonnet-4", input, false) if err != nil { t.Fatalf("err = %v", err) } @@ -119,7 +119,7 @@ func TestConvertOpenAIResponsesRequestToClaude_KeepsTurnWithTextBesideAttachment func TestConvertOpenAIResponsesRequestToClaude_InlineFileStaysADocument(t *testing.T) { input := responsesPayload("", responsesUserHello, responsesAssistantHi, responsesUserTurn(responsesInlineFile)) - body, err := ConvertOpenAIResponsesRequestToClaudeWithCompatReturningError("claude-sonnet-4", input, false) + body, err := ConvertOpenAIResponsesRequestToClaudeWithCompat("claude-sonnet-4", input, false) if err != nil { t.Fatalf("err = %v", err) } @@ -131,12 +131,14 @@ func TestConvertOpenAIResponsesRequestToClaude_InlineFileStaysADocument(t *testi func TestConvertOpenAIResponsesRequestToClaude_ExportedWrappersKeepAJSONBody(t *testing.T) { input := responsesPayload("", responsesUserTurn(responsesFileIDPart)) - for name, body := range map[string][]byte{ - "plain": ConvertOpenAIResponsesRequestToClaude("claude-sonnet-4", input, false), - "compat": ConvertOpenAIResponsesRequestToClaudeWithCompat("claude-sonnet-4", input, false), - } { + plain, errPlain := ConvertOpenAIResponsesRequestToClaude("claude-sonnet-4", input, false) + compat, errCompat := ConvertOpenAIResponsesRequestToClaudeWithCompat("claude-sonnet-4", input, false) + for name, body := range map[string][]byte{"plain": plain, "compat": compat} { if !gjson.ValidBytes(body) { t.Fatalf("%s: body is not JSON: %q", name, body) } } + if errPlain == nil || errCompat == nil { + t.Fatalf("plain err = %v, compat err = %v", errPlain, errCompat) + } } diff --git a/internal/translator/claude/openai/responses/claude_openai_responses_compat_test.go b/internal/translator/claude/openai/responses/claude_openai_responses_compat_test.go index adef6718805..cc5c993e288 100644 --- a/internal/translator/claude/openai/responses/claude_openai_responses_compat_test.go +++ b/internal/translator/claude/openai/responses/claude_openai_responses_compat_test.go @@ -9,19 +9,19 @@ import ( func TestConvertOpenAIResponsesRequestToClaudeWithCompatPreservesEmptyReasoning(t *testing.T) { payload := []byte(`{"input":[{"type":"reasoning","summary":[{"type":"summary_text","text":"reason"}],"encrypted_content":""}]}`) - withoutCompat := ConvertOpenAIResponsesRequestToClaude("deepseek-v4", payload, false) + withoutCompat, _ := ConvertOpenAIResponsesRequestToClaude("deepseek-v4", payload, false) if gjson.GetBytes(withoutCompat, "messages.#").Int() != 0 { t.Fatalf("default translation preserved empty reasoning: %s", withoutCompat) } - withCompat := ConvertOpenAIResponsesRequestToClaudeWithCompat("deepseek-v4", payload, false) + withCompat, _ := ConvertOpenAIResponsesRequestToClaudeWithCompat("deepseek-v4", payload, false) part := gjson.GetBytes(withCompat, "messages.0.content.0") if part.Get("type").String() != "thinking" || part.Get("signature").String() != "" { t.Fatalf("compat translation missing unsigned thinking block: %s", withCompat) } opaquePayload := []byte(`{"input":[{"type":"reasoning","summary":[{"type":"summary_text","text":"reason"}],"encrypted_content":"opaque-deepseek-id"}]}`) - opaqueCompat := ConvertOpenAIResponsesRequestToClaudeWithCompat("deepseek-v4", opaquePayload, false) + opaqueCompat, _ := ConvertOpenAIResponsesRequestToClaudeWithCompat("deepseek-v4", opaquePayload, false) opaquePart := gjson.GetBytes(opaqueCompat, "messages.0.content.0") if opaquePart.Get("type").String() != "thinking" || opaquePart.Get("thinking").String() != "reason" || opaquePart.Get("signature").String() != "opaque-deepseek-id" { t.Fatalf("compat translation dropped invalid-signature thinking block: %s", opaqueCompat) diff --git a/internal/translator/claude/openai/responses/init.go b/internal/translator/claude/openai/responses/init.go index c720803116a..0ab246d41b4 100644 --- a/internal/translator/claude/openai/responses/init.go +++ b/internal/translator/claude/openai/responses/init.go @@ -4,20 +4,16 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" - sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( OpenaiResponse, Claude, - nil, + ConvertOpenAIResponsesRequestToClaude, interfaces.TranslateResponse{ Stream: ConvertClaudeResponseToOpenAIResponses, NonStream: ConvertClaudeResponseToOpenAIResponsesNonStream, }, ) - sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatOpenAIResponse, sdktranslator.FormatClaude, func(model string, body []byte, stream bool) ([]byte, error) { - return convertOpenAIResponsesRequestToClaude(model, body, stream, false) - }) } diff --git a/internal/translator/codex/claude/codex_claude_compat_test.go b/internal/translator/codex/claude/codex_claude_compat_test.go index 62394483180..51fb1365cca 100644 --- a/internal/translator/codex/claude/codex_claude_compat_test.go +++ b/internal/translator/codex/claude/codex_claude_compat_test.go @@ -9,12 +9,12 @@ import ( func TestConvertClaudeRequestToCodexWithCompatPreservesEmptyThinking(t *testing.T) { payload := []byte(`{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"reason","signature":""}]}]}`) - withoutCompat := ConvertClaudeRequestToCodex("deepseek-v4", payload, false) + withoutCompat, _ := ConvertClaudeRequestToCodex("deepseek-v4", payload, false) if gjson.GetBytes(withoutCompat, "input.#").Int() != 0 { t.Fatalf("default translation preserved empty-signature thinking: %s", withoutCompat) } - withCompat := ConvertClaudeRequestToCodexWithCompat("deepseek-v4", payload, false) + withCompat, _ := ConvertClaudeRequestToCodexWithCompat("deepseek-v4", payload, false) if !gjson.GetBytes(withCompat, "input.0.type").Exists() || gjson.GetBytes(withCompat, "input.0.type").String() != "reasoning" { t.Fatalf("compat translation missing reasoning item: %s", withCompat) } @@ -27,60 +27,60 @@ func TestConvertClaudeRequestToCodexWithCompat_UnknownThinkingSignatures(t *test const unknownSig = "opaque-encrypted-reasoning-token-xyz" unknownPayload := []byte(`{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"reason","signature":"` + unknownSig + `"}]}]}`) - withCompatNonStream := ConvertClaudeRequestToCodexWithCompat("deepseek-v4", unknownPayload, false) + withCompatNonStream, _ := ConvertClaudeRequestToCodexWithCompat("deepseek-v4", unknownPayload, false) if gjson.GetBytes(withCompatNonStream, "input.0.type").String() != "reasoning" || gjson.GetBytes(withCompatNonStream, "input.0.encrypted_content").String() != unknownSig { t.Fatalf("compat non-stream translation failed to preserve unknown signature: %s", withCompatNonStream) } - withCompatStream := ConvertClaudeRequestToCodexWithCompat("deepseek-v4", unknownPayload, true) + withCompatStream, _ := ConvertClaudeRequestToCodexWithCompat("deepseek-v4", unknownPayload, true) if gjson.GetBytes(withCompatStream, "input.0.type").String() != "reasoning" || gjson.GetBytes(withCompatStream, "input.0.encrypted_content").String() != unknownSig { t.Fatalf("compat stream translation failed to preserve unknown signature: %s", withCompatStream) } - withoutCompatNonStream := ConvertClaudeRequestToCodex("deepseek-v4", unknownPayload, false) + withoutCompatNonStream, _ := ConvertClaudeRequestToCodex("deepseek-v4", unknownPayload, false) if gjson.GetBytes(withoutCompatNonStream, "input.#").Int() != 0 { t.Fatalf("non-compat translation unexpectedly preserved unknown signature: %s", withoutCompatNonStream) } - withoutCompatStream := ConvertClaudeRequestToCodex("deepseek-v4", unknownPayload, true) + withoutCompatStream, _ := ConvertClaudeRequestToCodex("deepseek-v4", unknownPayload, true) if gjson.GetBytes(withoutCompatStream, "input.#").Int() != 0 { t.Fatalf("non-compat stream translation unexpectedly preserved unknown signature: %s", withoutCompatStream) } const claudeSig = "CAISqwIKiAEIEBgCKkBHRlRBsNiptQUWfPoOhuQKwi5LnncZVO9bB5jqOs76D7uBtgktML0zqJtNmLHXHHcgD6lk4MQu4QBXzFd1lbC3Mg5jbGF1ZGUtZmFibGUtNTgBQgh0aGlua2luZ1okZDk3NDM5NzUtNGJiMC00OTM2LTllMjgtZDViMGQyMWJkYzQ4EgxCGh+XVFFFeySAjtAaDL/A1LltGu6MMJ+eXSIwsN0oBpDrqLv22UBfkMnTotnIbkvkOyb9xZHgigG6OZVHaI3gThm+maLKmgO5PrFLKlDFYp+YZksy/wKwszJlnLTPzAK+NUlfzagOE1ymtZTXhAYK260XyFYmg/te/C231+Fr/hoX+EJoUBnrn0gD7hqMISOT+TaFEuOXYsN517GfaxgB" claudePayload := []byte(`{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"reason","signature":"` + claudeSig + `"}]}]}`) - claudeCompat := ConvertClaudeRequestToCodexWithCompat("deepseek-v4", claudePayload, false) + claudeCompat, _ := ConvertClaudeRequestToCodexWithCompat("deepseek-v4", claudePayload, false) if gjson.GetBytes(claudeCompat, "input.#").Int() != 0 { t.Fatalf("compat translation unexpectedly preserved valid Claude signature: %s", claudeCompat) } gptRawSig := validCodexReasoningSignature() gptPayload := []byte(`{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"reason","signature":"gpt#` + gptRawSig + `"}]}]}`) - gptCompat := ConvertClaudeRequestToCodexWithCompat("deepseek-v4", gptPayload, false) + gptCompat, _ := ConvertClaudeRequestToCodexWithCompat("deepseek-v4", gptPayload, false) if gjson.GetBytes(gptCompat, "input.0.type").String() != "reasoning" || gjson.GetBytes(gptCompat, "input.0.encrypted_content").String() != gptRawSig { t.Fatalf("compat translation failed to normalize gpt# signature: %s", gptCompat) } nonStringPayloadInt := []byte(`{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"reason","signature":12345}]}]}`) - nonStringCompatInt := ConvertClaudeRequestToCodexWithCompat("deepseek-v4", nonStringPayloadInt, false) + nonStringCompatInt, _ := ConvertClaudeRequestToCodexWithCompat("deepseek-v4", nonStringPayloadInt, false) if gjson.GetBytes(nonStringCompatInt, "input.#").Int() != 0 { t.Fatalf("compat translation unexpectedly preserved non-string int signature: %s", nonStringCompatInt) } nonStringPayloadObj := []byte(`{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"reason","signature":{"opaque":"data"}}]}]}`) - nonStringCompatObj := ConvertClaudeRequestToCodexWithCompat("deepseek-v4", nonStringPayloadObj, false) + nonStringCompatObj, _ := ConvertClaudeRequestToCodexWithCompat("deepseek-v4", nonStringPayloadObj, false) if gjson.GetBytes(nonStringCompatObj, "input.#").Int() != 0 { t.Fatalf("compat translation unexpectedly preserved non-string object signature: %s", nonStringCompatObj) } nonStringPayloadBool := []byte(`{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"reason","signature":true}]}]}`) - nonStringCompatBool := ConvertClaudeRequestToCodexWithCompat("deepseek-v4", nonStringPayloadBool, false) + nonStringCompatBool, _ := ConvertClaudeRequestToCodexWithCompat("deepseek-v4", nonStringPayloadBool, false) if gjson.GetBytes(nonStringCompatBool, "input.#").Int() != 0 { t.Fatalf("compat translation unexpectedly preserved non-string bool signature: %s", nonStringCompatBool) } nonStringPayloadArr := []byte(`{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"reason","signature":["arr"]}]}]}`) - nonStringCompatArr := ConvertClaudeRequestToCodexWithCompat("deepseek-v4", nonStringPayloadArr, false) + nonStringCompatArr, _ := ConvertClaudeRequestToCodexWithCompat("deepseek-v4", nonStringPayloadArr, false) if gjson.GetBytes(nonStringCompatArr, "input.#").Int() != 0 { t.Fatalf("compat translation unexpectedly preserved non-string array signature: %s", nonStringCompatArr) } @@ -90,7 +90,7 @@ func TestConvertClaudeRequestToCodexWithCompat_PreservesMessageFlushingAndEscape const escapedSig = "enc:\"token\"\\with\\unicode-\u4e00" escapedPayload := []byte(`{"messages":[{"role":"assistant","content":[{"type":"text","text":"before"},{"type":"thinking","thinking":"reason","signature":"enc:\"token\"\\with\\unicode-\u4e00"},{"type":"text","text":"after"}]}]}`) - withCompat := ConvertClaudeRequestToCodexWithCompat("deepseek-v4", escapedPayload, false) + withCompat, _ := ConvertClaudeRequestToCodexWithCompat("deepseek-v4", escapedPayload, false) if gjson.GetBytes(withCompat, "input.#").Int() != 3 { t.Fatalf("compat translation expected 3 items after message flush, got: %s", withCompat) } @@ -107,13 +107,13 @@ func TestConvertClaudeRequestToCodexWithCompat_PreservesMessageFlushingAndEscape func TestConvertClaudeRequestToCodexWithCompat_WhitespaceAndNullSignatures(t *testing.T) { whitespacePayload := []byte(`{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"reason","signature":" "}]}]}`) - whitespaceCompat := ConvertClaudeRequestToCodexWithCompat("deepseek-v4", whitespacePayload, false) + whitespaceCompat, _ := ConvertClaudeRequestToCodexWithCompat("deepseek-v4", whitespacePayload, false) if gjson.GetBytes(whitespaceCompat, "input.0.type").String() != "reasoning" || gjson.GetBytes(whitespaceCompat, "input.0.encrypted_content").String() != " " { t.Fatalf("compat translation failed to preserve whitespace signature via empty fallback: %s", whitespaceCompat) } nullPayload := []byte(`{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"reason","signature":null}]}]}`) - nullCompat := ConvertClaudeRequestToCodexWithCompat("deepseek-v4", nullPayload, false) + nullCompat, _ := ConvertClaudeRequestToCodexWithCompat("deepseek-v4", nullPayload, false) if gjson.GetBytes(nullCompat, "input.0.type").String() != "reasoning" || gjson.GetBytes(nullCompat, "input.0.encrypted_content").String() != "" { t.Fatalf("compat translation failed to preserve null signature via empty fallback: %s", nullCompat) } diff --git a/internal/translator/codex/claude/codex_claude_request.go b/internal/translator/codex/claude/codex_claude_request.go index 17b60ca656d..6585a6cd4b6 100644 --- a/internal/translator/codex/claude/codex_claude_request.go +++ b/internal/translator/codex/claude/codex_claude_request.go @@ -41,20 +41,14 @@ import ( // // Returns: // - []byte: The transformed request data in internal client format -func ConvertClaudeRequestToCodex(modelName string, inputRawJSON []byte, stream bool) []byte { - body, _ := convertClaudeRequestToCodex(modelName, inputRawJSON, stream, false) - return body +func ConvertClaudeRequestToCodex(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { + return convertClaudeRequestToCodex(modelName, inputRawJSON, stream, false) + } // ConvertClaudeRequestToCodexWithCompat preserves assistant thinking blocks with // empty or unknown-format signatures for configured compatibility endpoints. -func ConvertClaudeRequestToCodexWithCompat(modelName string, inputRawJSON []byte, stream bool) []byte { - body, _ := convertClaudeRequestToCodex(modelName, inputRawJSON, stream, true) - return body -} - -// ConvertClaudeRequestToCodexWithCompatReturningError reports a file part the target cannot represent. -func ConvertClaudeRequestToCodexWithCompatReturningError(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { +func ConvertClaudeRequestToCodexWithCompat(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { return convertClaudeRequestToCodex(modelName, inputRawJSON, stream, true) } diff --git a/internal/translator/codex/claude/codex_claude_request_benchmark_test.go b/internal/translator/codex/claude/codex_claude_request_benchmark_test.go index 5ac16a8c481..feac3834801 100644 --- a/internal/translator/codex/claude/codex_claude_request_benchmark_test.go +++ b/internal/translator/codex/claude/codex_claude_request_benchmark_test.go @@ -15,7 +15,7 @@ func BenchmarkConvertClaudeRequestToCodexLargeHistory(b *testing.B) { if !gjson.ValidBytes(request) { b.Fatal("benchmark generated an invalid Claude request") } - if result := ConvertClaudeRequestToCodex("gpt-5.4", request, false); !gjson.ValidBytes(result) { + if result, _ := ConvertClaudeRequestToCodex("gpt-5.4", request, false); !gjson.ValidBytes(result) { b.Fatal("translator generated invalid Codex JSON") } b.ReportAllocs() diff --git a/internal/translator/codex/claude/codex_claude_request_test.go b/internal/translator/codex/claude/codex_claude_request_test.go index bbc4fe67561..694542cf57f 100644 --- a/internal/translator/codex/claude/codex_claude_request_test.go +++ b/internal/translator/codex/claude/codex_claude_request_test.go @@ -73,7 +73,7 @@ func TestConvertClaudeRequestToCodex_SystemMessageScenarios(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - result := ConvertClaudeRequestToCodex("test-model", []byte(tt.inputJSON), false) + result, _ := ConvertClaudeRequestToCodex("test-model", []byte(tt.inputJSON), false) resultJSON := gjson.ParseBytes(result) inputs := resultJSON.Get("input").Array() @@ -115,7 +115,7 @@ func TestConvertClaudeRequestToCodex_MessageSystemRoleWrapsAsUserReminder(t *tes ] }` - result := ConvertClaudeRequestToCodex("test-model", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToCodex("test-model", []byte(inputJSON), false) inputs := gjson.GetBytes(result, "input").Array() if len(inputs) != 5 { t.Fatalf("got %d input items, want 5: %s", len(inputs), gjson.GetBytes(result, "input").Raw) @@ -162,7 +162,7 @@ func TestConvertClaudeRequestToCodex_PreservesToolAdjacencyWithInterveningSystem ] }` - result := ConvertClaudeRequestToCodex("gpt-5.4", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToCodex("gpt-5.4", []byte(inputJSON), false) inputs := gjson.GetBytes(result, "input").Array() // Expected item types: @@ -232,7 +232,7 @@ func TestConvertClaudeRequestToCodex_ParallelToolCalls(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - result := ConvertClaudeRequestToCodex("test-model", []byte(tt.inputJSON), false) + result, _ := ConvertClaudeRequestToCodex("test-model", []byte(tt.inputJSON), false) resultJSON := gjson.ParseBytes(result) if got := resultJSON.Get("parallel_tool_calls").Bool(); got != tt.wantParallelToolCalls { @@ -306,7 +306,7 @@ func TestConvertClaudeRequestToCodex_ServiceTier(t *testing.T) { inputJSON, _ = sjson.SetRawBytes(inputJSON, "speed", []byte(tt.speedJSON)) } - result := ConvertClaudeRequestToCodex("gpt-5.4", inputJSON, false) + result, _ := ConvertClaudeRequestToCodex("gpt-5.4", inputJSON, false) serviceTierResult := gjson.GetBytes(result, "service_tier") if serviceTierResult.Exists() != tt.wantExists { t.Fatalf("service_tier exists = %v, want %v. Output: %s", serviceTierResult.Exists(), tt.wantExists, string(result)) @@ -340,7 +340,7 @@ func TestConvertClaudeRequestToCodex_ShortenLongToolUseIDs(t *testing.T) { ] }` - result := ConvertClaudeRequestToCodex("test-model", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToCodex("test-model", []byte(inputJSON), false) inputs := gjson.GetBytes(result, "input").Array() var callID string @@ -405,7 +405,7 @@ func TestConvertClaudeRequestToCodex_ToolChoiceModeMapping(t *testing.T) { "messages": [{"role": "user", "content": "hello"}] }` - result := ConvertClaudeRequestToCodex("test-model", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToCodex("test-model", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) if got := resultJSON.Get("tool_choice").String(); got != tt.wantCodexToolChoice { @@ -426,7 +426,7 @@ func TestConvertClaudeRequestToCodex_ToolChoiceSpecificFunctionUsesConvertedName "messages": [{"role": "user", "content": "hello"}] }` - result := ConvertClaudeRequestToCodex("test-model", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToCodex("test-model", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) if got := resultJSON.Get("tool_choice.type").String(); got != "function" { @@ -467,7 +467,7 @@ func TestConvertClaudeRequestToCodex_WebSearchSourcesInclude(t *testing.T) { inputJSON += `,"tools":` + tt.tools } inputJSON += `}` - result := ConvertClaudeRequestToCodex("test-model", []byte(inputJSON), stream) + result, _ := ConvertClaudeRequestToCodex("test-model", []byte(inputJSON), stream) wantInclude := `["reasoning.encrypted_content"]` if tt.wantSources { wantInclude = `["reasoning.encrypted_content","web_search_call.action.sources"]` @@ -501,7 +501,7 @@ func TestConvertClaudeRequestToCodex_WebSearchToolMapping(t *testing.T) { "messages": [{"role": "user", "content": "hello"}] }` - result := ConvertClaudeRequestToCodex("test-model", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToCodex("test-model", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) if got := resultJSON.Get("tools.0.type").String(); got != "web_search" { @@ -532,7 +532,7 @@ func TestConvertClaudeRequestToCodex_WebSearchToolChoiceUsesDeclaredTypedToolNam "messages": [{"role": "user", "content": "hello"}] }` - result := ConvertClaudeRequestToCodex("test-model", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToCodex("test-model", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) if got := resultJSON.Get("tool_choice.type").String(); got != "function" { @@ -569,7 +569,7 @@ func TestConvertClaudeRequestToCodex_AssistantThinkingSignatureToReasoningItem(t ] }` - result := ConvertClaudeRequestToCodex("test-model", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToCodex("test-model", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) inputs := resultJSON.Get("input").Array() if len(inputs) != 3 { @@ -617,7 +617,7 @@ func TestConvertClaudeRequestToCodex_PreservesBase64PDFDocumentContent(t *testin }] }` - result := ConvertClaudeRequestToCodex("gpt-5.6-sol", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToCodex("gpt-5.6-sol", []byte(inputJSON), false) content := gjson.GetBytes(result, "input.0.content").Array() if len(content) != 3 { t.Fatalf("got %d content items, want 3. Output: %s", len(content), result) @@ -666,7 +666,7 @@ func TestConvertClaudeRequestToCodex_PreservesContentOrderAcrossToolAndReasoning "tools": [{"name":"lookup","input_schema":{"type":"object"}}] }` - result := ConvertClaudeRequestToCodex("gpt-5.4", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToCodex("gpt-5.4", []byte(inputJSON), false) inputs := gjson.GetBytes(result, "input").Array() if len(inputs) != 8 { t.Fatalf("got %d input items, want 8. Output: %s", len(inputs), result) @@ -704,7 +704,7 @@ func TestConvertClaudeRequestToCodex_AssistantGrokSignatureToReasoningItem(t *te payload := []byte(`{"model":"grok-4.5","messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"summary","signature":""},{"type":"text","text":"answer"}]},{"role":"user","content":"next"}]}`) payload, _ = sjson.SetBytes(payload, "messages.0.content.0.signature", signature) - out := ConvertClaudeRequestToCodex("grok-4.5", payload, false) + out, _ := ConvertClaudeRequestToCodex("grok-4.5", payload, false) reasoning := gjson.GetBytes(out, "input.0") if reasoning.Get("type").String() != "reasoning" { t.Fatalf("input.0 type = %q, want reasoning; output=%s", reasoning.Get("type").String(), out) @@ -721,7 +721,7 @@ func TestConvertClaudeRequestToCodex_IgnoresGrokSignatureForNonGrokTargets(t *te for _, modelName := range []string{"gpt-5.4", "claude-sonnet-4-6"} { t.Run(modelName, func(t *testing.T) { - out := ConvertClaudeRequestToCodex(modelName, payload, false) + out, _ := ConvertClaudeRequestToCodex(modelName, payload, false) if got := countRequestInputItemsByType(out, "reasoning"); got != 0 { t.Fatalf("got %d reasoning items for non-Grok target, want 0; output=%s", got, out) } @@ -782,7 +782,7 @@ func TestConvertClaudeRequestToCodex_IgnoresNonCodexThinkingSignatures(t *testin for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - result := ConvertClaudeRequestToCodex("test-model", []byte(tt.inputJSON), false) + result, _ := ConvertClaudeRequestToCodex("test-model", []byte(tt.inputJSON), false) if got := countRequestInputItemsByType(result, "reasoning"); got != 0 { t.Fatalf("got %d reasoning items, want 0. Output: %s", got, string(result)) } @@ -831,7 +831,7 @@ func TestConvertClaudeRequestToCodex_OutputConfigFormat(t *testing.T) { } }`) - translated := ConvertClaudeRequestToCodex("gpt-5.4", payload, false) + translated, _ := ConvertClaudeRequestToCodex("gpt-5.4", payload, false) root := gjson.ParseBytes(translated) if !root.Get("text.format").Exists() { @@ -869,7 +869,7 @@ func TestConvertClaudeRequestToCodex_OutputConfigFormat(t *testing.T) { } }`) - translated := ConvertClaudeRequestToCodex("gpt-5.4", payload, false) + translated, _ := ConvertClaudeRequestToCodex("gpt-5.4", payload, false) root := gjson.ParseBytes(translated) if got := root.Get("text.format.name").String(); got != "custom_schema" { @@ -888,7 +888,7 @@ func TestConvertClaudeRequestToCodex_OutputConfigFormat(t *testing.T) { ] }`) - translated := ConvertClaudeRequestToCodex("gpt-5.4", payload, false) + translated, _ := ConvertClaudeRequestToCodex("gpt-5.4", payload, false) root := gjson.ParseBytes(translated) if root.Get("text.format").Exists() { t.Fatalf("expected no text.format in translated payload, got: %s", translated) @@ -905,7 +905,7 @@ func TestConvertClaudeRequestToCodex_OutputConfigFormat(t *testing.T) { ] }`) - translated := ConvertClaudeRequestToCodex("gpt-5.4", payload, false) + translated, _ := ConvertClaudeRequestToCodex("gpt-5.4", payload, false) root := gjson.ParseBytes(translated) if root.Get("text.format").Exists() { t.Fatalf("expected no text.format in translated payload, got: %s", translated) @@ -939,7 +939,7 @@ func TestConvertClaudeRequestToCodex_OutputConfigFormat(t *testing.T) { } }`) - translated := ConvertClaudeRequestToCodex("gpt-5.4", payload, false) + translated, _ := ConvertClaudeRequestToCodex("gpt-5.4", payload, false) root := gjson.ParseBytes(translated) if got := root.Get("text.format.strict").Bool(); got != false { t.Errorf("expected text.format.strict to be false for non-strict-compatible schema, got %v (%s)", got, translated) @@ -970,7 +970,7 @@ func TestConvertClaudeRequestToCodex_OutputConfigFormat(t *testing.T) { } }`) - translated := ConvertClaudeRequestToCodex("gpt-5.4", payload, false) + translated, _ := ConvertClaudeRequestToCodex("gpt-5.4", payload, false) root := gjson.ParseBytes(translated) if got := root.Get("text.format.strict").Bool(); !got { t.Errorf("expected text.format.strict to stay true for strict-compatible schema, got %v (%s)", got, translated) @@ -1137,7 +1137,7 @@ func TestConvertClaudeRequestToCodex_StripsNestedToolSchemaMeta(t *testing.T) { }] }` - translated := ConvertClaudeRequestToCodex("gpt-5", []byte(inputJSON), false) + translated, _ := ConvertClaudeRequestToCodex("gpt-5", []byte(inputJSON), false) tools := gjson.GetBytes(translated, "tools").Array() if len(tools) == 0 { t.Fatalf("expected tools in translated payload, got: %s", translated) @@ -1216,7 +1216,7 @@ func TestConvertClaudeRequestToCodex_StripsUnsupportedUnicodePropertyEscapePatte }] }` - translated := ConvertClaudeRequestToCodex("gpt-5.6", []byte(inputJSON), false) + translated, _ := ConvertClaudeRequestToCodex("gpt-5.6", []byte(inputJSON), false) tools := gjson.GetBytes(translated, "tools").Array() if len(tools) == 0 { t.Fatalf("expected tools in translated payload, got: %s", translated) @@ -1285,7 +1285,7 @@ func TestConvertClaudeRequestToCodex_StripsPatternPropertiesIncompatibleKeys(t * }] }` - translated := ConvertClaudeRequestToCodex("gpt-5.6", []byte(inputJSON), false) + translated, _ := ConvertClaudeRequestToCodex("gpt-5.6", []byte(inputJSON), false) tools := gjson.GetBytes(translated, "tools").Array() if len(tools) == 0 { t.Fatalf("expected tools in translated payload, got: %s", translated) diff --git a/internal/translator/codex/claude/codex_claude_user_turn_test.go b/internal/translator/codex/claude/codex_claude_user_turn_test.go index 4b39328be33..ae4637f63bb 100644 --- a/internal/translator/codex/claude/codex_claude_user_turn_test.go +++ b/internal/translator/codex/claude/codex_claude_user_turn_test.go @@ -41,7 +41,7 @@ func TestConvertClaudeRequestToCodex_RefusesAnyEmptiedUserTurn(t *testing.T) { } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - body, err := ConvertClaudeRequestToCodexWithCompatReturningError("m", []byte(tc.input), false) + body, err := ConvertClaudeRequestToCodexWithCompat("m", []byte(tc.input), false) var unsupported *translatorcommon.UnsupportedPartError if !errors.As(err, &unsupported) || unsupported.Type != tc.wantType || unsupported.StatusCode() != 400 { t.Fatalf("err = %v, want unsupported content part: %s; body = %s", err, tc.wantType, body) @@ -58,7 +58,7 @@ func TestConvertClaudeRequestToCodex_RefusesAnyEmptiedUserTurn(t *testing.T) { func TestConvertClaudeRequestToCodex_KeepsTurnWithTextBesideAttachment(t *testing.T) { input := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"text","text":"keep me"},` + userTurnUpload + `]}]}`) - body, err := ConvertClaudeRequestToCodexWithCompatReturningError("m", input, false) + body, err := ConvertClaudeRequestToCodexWithCompat("m", input, false) if err != nil { t.Fatalf("err = %v", err) } @@ -69,7 +69,7 @@ func TestConvertClaudeRequestToCodex_KeepsTurnWithTextBesideAttachment(t *testin func TestConvertClaudeRequestToCodex_Base64DocumentAfterHistoryStaysAFile(t *testing.T) { input := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"document","source":{"type":"base64","media_type":"application/pdf","data":"JVBERi0xLjQK"}}]}]}`) - body, err := ConvertClaudeRequestToCodexWithCompatReturningError("m", input, false) + body, err := ConvertClaudeRequestToCodexWithCompat("m", input, false) if err != nil { t.Fatalf("err = %v", err) } @@ -86,7 +86,7 @@ func TestConvertClaudeRequestToCodex_EmptyTextDoesNotHideAnEmptiedUserTurn(t *te } for name, input := range cases { t.Run(name, func(t *testing.T) { - body, err := ConvertClaudeRequestToCodexWithCompatReturningError("m", []byte(input), false) + body, err := ConvertClaudeRequestToCodexWithCompat("m", []byte(input), false) var unsupported *translatorcommon.UnsupportedPartError if !errors.As(err, &unsupported) || unsupported.Type != "container_upload" || unsupported.StatusCode() != 400 { t.Fatalf("err = %v, want unsupported content part: container_upload; body = %s", err, body) @@ -100,7 +100,7 @@ func TestConvertClaudeRequestToCodex_EmptyTextDoesNotHideAnEmptiedUserTurn(t *te func TestConvertClaudeRequestToCodex_NonEmptyTextBesideAttachmentStillSucceeds(t *testing.T) { input := []byte(`{"model":"m","messages":[{"role":"user","content":[{"type":"text","text":""},{"type":"text","text":"keep me"},` + userTurnUpload + `]}]}`) - body, err := ConvertClaudeRequestToCodexWithCompatReturningError("m", input, false) + body, err := ConvertClaudeRequestToCodexWithCompat("m", input, false) if err != nil { t.Fatalf("err = %v", err) } diff --git a/internal/translator/codex/claude/init.go b/internal/translator/codex/claude/init.go index c47d7eaa941..eb121ece9d9 100644 --- a/internal/translator/codex/claude/init.go +++ b/internal/translator/codex/claude/init.go @@ -4,21 +4,17 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" - sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( Claude, Codex, - nil, + ConvertClaudeRequestToCodex, interfaces.TranslateResponse{ Stream: ConvertCodexResponseToClaude, NonStream: ConvertCodexResponseToClaudeNonStream, TokenCount: ClaudeTokenCount, }, ) - sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatClaude, sdktranslator.FormatCodex, func(model string, body []byte, stream bool) ([]byte, error) { - return convertClaudeRequestToCodex(model, body, stream, false) - }) } diff --git a/internal/translator/codex/claude/noop_optimization_test.go b/internal/translator/codex/claude/noop_optimization_test.go index 49754946246..55a59ba546d 100644 --- a/internal/translator/codex/claude/noop_optimization_test.go +++ b/internal/translator/codex/claude/noop_optimization_test.go @@ -9,7 +9,7 @@ import ( func TestConvertClaudeRequestToCodexNormalizesNonStringToolName(t *testing.T) { input := []byte(`{"messages":[],"tools":[{"name":123,"input_schema":{"type":"object"}}]}`) - output := ConvertClaudeRequestToCodex("gpt-test", input, false) + output, _ := ConvertClaudeRequestToCodex("gpt-test", input, false) name := gjson.GetBytes(output, "tools.0.name") if name.Type != gjson.String || name.String() != "123" { diff --git a/internal/translator/codex/gemini/codex_gemini_request.go b/internal/translator/codex/gemini/codex_gemini_request.go index 7a3c8408095..71bdebaceaa 100644 --- a/internal/translator/codex/gemini/codex_gemini_request.go +++ b/internal/translator/codex/gemini/codex_gemini_request.go @@ -34,7 +34,7 @@ import ( // // Returns: // - []byte: The transformed request data in Codex API format -func ConvertGeminiRequestToCodex(modelName string, inputRawJSON []byte, _ bool) []byte { +func ConvertGeminiRequestToCodex(modelName string, inputRawJSON []byte, _ bool) ([]byte, error) { rawJSON := inputRawJSON // Base template out := []byte(`{"model":"","instructions":"","input":[]}`) @@ -341,7 +341,7 @@ func ConvertGeminiRequestToCodex(modelName string, inputRawJSON []byte, _ bool) out, _ = sjson.SetBytes(out, fullPath, normalizedType) } - return out + return out, nil } func setCodexToolChoiceFromGeminiToolConfig(out []byte, functionCallingConfig gjson.Result) []byte { diff --git a/internal/translator/codex/gemini/codex_gemini_request_test.go b/internal/translator/codex/gemini/codex_gemini_request_test.go index 86671e74cbb..4ac4976a42b 100644 --- a/internal/translator/codex/gemini/codex_gemini_request_test.go +++ b/internal/translator/codex/gemini/codex_gemini_request_test.go @@ -47,7 +47,7 @@ func TestConvertGeminiRequestToCodex_PreservesCustomCallIDs(t *testing.T) { ] }`, tt.callField, tt.responseField)) - out := ConvertGeminiRequestToCodex("gpt-5.1-codex", raw, false) + out, _ := ConvertGeminiRequestToCodex("gpt-5.1-codex", raw, false) gotCallID := gjson.GetBytes(out, "input.0.call_id").String() if gotCallID != tt.want { @@ -63,7 +63,7 @@ func TestConvertGeminiRequestToCodex_PreservesCustomCallIDs(t *testing.T) { } func TestConvertGeminiRequestToCodex_AcceptsInlineData(t *testing.T) { - out := ConvertGeminiRequestToCodex("gpt-5.1-codex", []byte(`{"contents":[{"role":"user","parts":[{"inlineData":{"mimeType":"image/png","data":"aGVsbG8="}}]}]}`), false) + out, _ := ConvertGeminiRequestToCodex("gpt-5.1-codex", []byte(`{"contents":[{"role":"user","parts":[{"inlineData":{"mimeType":"image/png","data":"aGVsbG8="}}]}]}`), false) if got := gjson.GetBytes(out, "input.0.content.0.type").String(); got != "input_image" { t.Fatalf("content type = %q, want input_image. Output: %s", got, string(out)) } @@ -73,7 +73,7 @@ func TestConvertGeminiRequestToCodex_AcceptsInlineData(t *testing.T) { } func TestConvertGeminiRequestToCodex_SplitsNonImageInlineDataByMIME(t *testing.T) { - out := ConvertGeminiRequestToCodex("gpt-5.1-codex", []byte(`{"contents":[{"role":"user","parts":[{"inlineData":{"mimeType":"audio/wav","data":"UklGRg=="}},{"inlineData":{"mimeType":"video/mp4","data":"AAAAIGZ0eXA="}},{"inlineData":{"mimeType":"application/pdf","data":"JVBERi0="}}]}]}`), false) + out, _ := ConvertGeminiRequestToCodex("gpt-5.1-codex", []byte(`{"contents":[{"role":"user","parts":[{"inlineData":{"mimeType":"audio/wav","data":"UklGRg=="}},{"inlineData":{"mimeType":"video/mp4","data":"AAAAIGZ0eXA="}},{"inlineData":{"mimeType":"application/pdf","data":"JVBERi0="}}]}]}`), false) if got := gjson.GetBytes(out, "input.0.content.0.type").String(); got != "input_audio" { t.Fatalf("audio content type = %q, want input_audio. Output: %s", got, string(out)) @@ -88,7 +88,7 @@ func TestConvertGeminiRequestToCodex_SplitsNonImageInlineDataByMIME(t *testing.T func TestConvertGeminiRequestToCodex_DropsHiddenThoughtParts(t *testing.T) { t.Run("thought-only turn", func(t *testing.T) { - out := ConvertGeminiRequestToCodex("codex-test", []byte(`{ + out, _ := ConvertGeminiRequestToCodex("codex-test", []byte(`{ "contents":[ {"role":"model","parts":[{"thought":true,"text":"internal reasoning","thoughtSignature":"opaque-provider-state"}]}, {"role":"user","parts":[{"text":"continue"}]} @@ -102,7 +102,7 @@ func TestConvertGeminiRequestToCodex_DropsHiddenThoughtParts(t *testing.T) { }) t.Run("mixed turn", func(t *testing.T) { - out := ConvertGeminiRequestToCodex("codex-test", []byte(`{ + out, _ := ConvertGeminiRequestToCodex("codex-test", []byte(`{ "contents":[{"role":"model","parts":[ {"thought":true,"text":"internal reasoning","thoughtSignature":"opaque-provider-state"}, {"text":"visible answer"} @@ -146,8 +146,8 @@ func TestConvertGeminiRequestToCodex_DeterministicCallIDs(t *testing.T) { ] }`) - out1 := ConvertGeminiRequestToCodex("gpt-5.1-codex", raw, false) - out2 := ConvertGeminiRequestToCodex("gpt-5.1-codex", raw, false) + out1, _ := ConvertGeminiRequestToCodex("gpt-5.1-codex", raw, false) + out2, _ := ConvertGeminiRequestToCodex("gpt-5.1-codex", raw, false) if string(out1) != string(out2) { t.Fatalf("expected deterministic output across multiple conversions, got different outputs:\nout1=%s\nout2=%s", string(out1), string(out2)) diff --git a/internal/translator/codex/interactions/init.go b/internal/translator/codex/interactions/init.go index e248fb4c7dc..c119cc14261 100644 --- a/internal/translator/codex/interactions/init.go +++ b/internal/translator/codex/interactions/init.go @@ -4,18 +4,16 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" - sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( Interactions, Codex, - nil, + ConvertInteractionsRequestToCodex, interfaces.TranslateResponse{ Stream: ConvertCodexResponseToInteractions, NonStream: ConvertCodexResponseToInteractionsNonStream, }, ) - sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatInteractions, sdktranslator.FormatCodex, convertInteractionsRequestToCodex) } diff --git a/internal/translator/codex/interactions/interactions_codex_request.go b/internal/translator/codex/interactions/interactions_codex_request.go index 018d769ba4b..c6f5a0b2cc7 100644 --- a/internal/translator/codex/interactions/interactions_codex_request.go +++ b/internal/translator/codex/interactions/interactions_codex_request.go @@ -11,9 +11,9 @@ import ( "github.com/tidwall/sjson" ) -func ConvertInteractionsRequestToCodex(modelName string, inputRawJSON []byte, stream bool) []byte { - out, _ := convertInteractionsRequestToCodex(modelName, inputRawJSON, stream) - return out +func ConvertInteractionsRequestToCodex(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { + return convertInteractionsRequestToCodex(modelName, inputRawJSON, stream) + } // convertInteractionsRequestToCodex also reports a user turn that was left empty diff --git a/internal/translator/codex/interactions/interactions_codex_test.go b/internal/translator/codex/interactions/interactions_codex_test.go index 5c6b38eb57e..67581a1046c 100644 --- a/internal/translator/codex/interactions/interactions_codex_test.go +++ b/internal/translator/codex/interactions/interactions_codex_test.go @@ -10,7 +10,7 @@ import ( ) func TestConvertInteractionsRequestToCodexWithToolMessagesDirect(t *testing.T) { - out := ConvertInteractionsRequestToCodex("codex-test", []byte(`{"model":"codex-test","system_instruction":"be brief","input":[{"type":"user_input","content":[{"type":"text","text":"hi"}]},{"type":"thought","content":[{"type":"text","text":"thinking"}]},{"type":"function_call","name":"lookup","call_id":"call_1","arguments":{"q":"x"}},{"type":"function_result","name":"lookup","call_id":"call_1","result":{"ok":true}}],"tools":[{"type":"function","name":"lookup","parameters":{"type":"object","properties":{"q":{"type":"string"}}}}]}`), false) + out, _ := ConvertInteractionsRequestToCodex("codex-test", []byte(`{"model":"codex-test","system_instruction":"be brief","input":[{"type":"user_input","content":[{"type":"text","text":"hi"}]},{"type":"thought","content":[{"type":"text","text":"thinking"}]},{"type":"function_call","name":"lookup","call_id":"call_1","arguments":{"q":"x"}},{"type":"function_result","name":"lookup","call_id":"call_1","result":{"ok":true}}],"tools":[{"type":"function","name":"lookup","parameters":{"type":"object","properties":{"q":{"type":"string"}}}}]}`), false) if got := gjson.GetBytes(out, "instructions").String(); got != "be brief" { t.Fatalf("instructions = %q, want be brief. Output: %s", got, string(out)) } @@ -38,7 +38,7 @@ func TestConvertInteractionsRequestToCodexWithToolMessagesDirect(t *testing.T) { } func TestConvertInteractionsRequestToCodexPreservesNonImageMediaContent(t *testing.T) { - out := ConvertInteractionsRequestToCodex("codex-test", []byte(`{"model":"codex-test","input":[{"type":"model_output","content":[{"type":"audio","mime_type":"audio/wav","data":"UklGRg=="},{"type":"video","mime_type":"video/mp4","data":"AAAAIGZ0eXA="},{"type":"document","mime_type":"application/pdf","data":"JVBERi0="}]}]}`), false) + out, _ := ConvertInteractionsRequestToCodex("codex-test", []byte(`{"model":"codex-test","input":[{"type":"model_output","content":[{"type":"audio","mime_type":"audio/wav","data":"UklGRg=="},{"type":"video","mime_type":"video/mp4","data":"AAAAIGZ0eXA="},{"type":"document","mime_type":"application/pdf","data":"JVBERi0="}]}]}`), false) if got := gjson.GetBytes(out, "input.0.role").String(); got != "assistant" { t.Fatalf("input.0.role = %q, want assistant. Output: %s", got, string(out)) @@ -55,7 +55,7 @@ func TestConvertInteractionsRequestToCodexPreservesNonImageMediaContent(t *testi } func TestConvertInteractionsRequestToCodexPreservesTopLevelThinkingLevel(t *testing.T) { - out := ConvertInteractionsRequestToCodex("codex-test", []byte(`{"model":"codex-test","generation_config":{"thinking_level":"high"},"input":"hi"}`), true) + out, _ := ConvertInteractionsRequestToCodex("codex-test", []byte(`{"model":"codex-test","generation_config":{"thinking_level":"high"},"input":"hi"}`), true) if got := gjson.GetBytes(out, "reasoning.effort").String(); got != "high" { t.Fatalf("reasoning.effort = %q, want high. Output: %s", got, string(out)) } @@ -65,14 +65,14 @@ func TestConvertInteractionsRequestToCodexPreservesTopLevelThinkingLevel(t *test } func TestConvertInteractionsRequestToCodexUsesBodyStream(t *testing.T) { - out := ConvertInteractionsRequestToCodex("codex-test", []byte(`{"model":"codex-test","stream":true,"input":"hi"}`), false) + out, _ := ConvertInteractionsRequestToCodex("codex-test", []byte(`{"model":"codex-test","stream":true,"input":"hi"}`), false) if got := gjson.GetBytes(out, "stream").Bool(); !got { t.Fatalf("stream = %v, want true. Output: %s", got, string(out)) } } func TestConvertInteractionsRequestToCodexFunctionDeclarations(t *testing.T) { - out := ConvertInteractionsRequestToCodex("codex-test", []byte(`{"model":"codex-test","input":"hi","tools":[{"function_declarations":[{"name":"lookup","description":"Lookup data","parameters":{"type":"object","$schema":"http://json-schema.org/draft-07/schema#","properties":{"q":{"type":"string"}}}}]}]}`), false) + out, _ := ConvertInteractionsRequestToCodex("codex-test", []byte(`{"model":"codex-test","input":"hi","tools":[{"function_declarations":[{"name":"lookup","description":"Lookup data","parameters":{"type":"object","$schema":"http://json-schema.org/draft-07/schema#","properties":{"q":{"type":"string"}}}}]}]}`), false) if got := gjson.GetBytes(out, "tools.0.type").String(); got != "function" { t.Fatalf("tools.0.type = %q, want function. Output: %s", got, string(out)) } diff --git a/internal/translator/codex/interactions/interactions_codex_uri_test.go b/internal/translator/codex/interactions/interactions_codex_uri_test.go index 8dd35d79d96..36e20513592 100644 --- a/internal/translator/codex/interactions/interactions_codex_uri_test.go +++ b/internal/translator/codex/interactions/interactions_codex_uri_test.go @@ -196,7 +196,7 @@ func TestInteractionsToCodexAssistantMediaIsNotAUserTurn(t *testing.T) { func TestInteractionsToCodexExportedWrapperKeepsAJSONBody(t *testing.T) { input := []byte(`{"model":"m","input":[` + interactionsCodexHistory + `,{"type":"user_input","content":[{"type":"audio","mime_type":"audio/wav"}]}]}`) - if body := ConvertInteractionsRequestToCodex("m", input, false); !gjson.ValidBytes(body) { + if body, _ := ConvertInteractionsRequestToCodex("m", input, false); !gjson.ValidBytes(body) { t.Fatalf("body is not JSON: %q", body) } } diff --git a/internal/translator/codex/openai/chat-completions/codex_openai_request.go b/internal/translator/codex/openai/chat-completions/codex_openai_request.go index 66b68a87f0c..d4a12f27ea3 100644 --- a/internal/translator/codex/openai/chat-completions/codex_openai_request.go +++ b/internal/translator/codex/openai/chat-completions/codex_openai_request.go @@ -28,9 +28,9 @@ import ( // // Returns: // - []byte: The transformed request data in OpenAI Responses API format -func ConvertOpenAIRequestToCodex(modelName string, inputRawJSON []byte, stream bool) []byte { - body, _ := convertOpenAIRequestToCodex(modelName, inputRawJSON, stream) - return body +func ConvertOpenAIRequestToCodex(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { + return convertOpenAIRequestToCodex(modelName, inputRawJSON, stream) + } // convertOpenAIRequestToCodex also reports a file or audio part Responses cannot diff --git a/internal/translator/codex/openai/chat-completions/codex_openai_request_test.go b/internal/translator/codex/openai/chat-completions/codex_openai_request_test.go index f1bab25ff0a..6336d8bfeb3 100644 --- a/internal/translator/codex/openai/chat-completions/codex_openai_request_test.go +++ b/internal/translator/codex/openai/chat-completions/codex_openai_request_test.go @@ -48,7 +48,7 @@ func TestToolCallSimple(t *testing.T) { ] }`) - out := ConvertOpenAIRequestToCodex("gpt-4o", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-4o", input, true) result := string(out) items := gjson.Get(result, "input").Array() @@ -137,7 +137,7 @@ func TestToolCallWithContent(t *testing.T) { ] }`) - out := ConvertOpenAIRequestToCodex("gpt-4o", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-4o", input, true) result := string(out) items := gjson.Get(result, "input").Array() @@ -214,7 +214,7 @@ func TestToolCallOutputWithMultimodalContent(t *testing.T) { ] }`) - out := ConvertOpenAIRequestToCodex("gpt-4o", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-4o", input, true) result := string(out) output := gjson.Get(result, "input.2.output") @@ -305,7 +305,7 @@ func TestToolCallOutputWithStringifiedImageContent(t *testing.T) { ] }`) - out := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) output := gjson.GetBytes(out, "input.2.output") if !output.IsArray() { t.Fatalf("expected stringified image output to be an array, got: %s", output.Raw) @@ -363,7 +363,7 @@ func TestToolCallOutputKeepsNonImageStrings(t *testing.T) { ] }`) - out := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) output := gjson.GetBytes(out, "input.2.output") if output.Type != gjson.String { t.Fatalf("expected output to remain a string, got: %s", output.Raw) @@ -402,7 +402,7 @@ func TestToolCallOutputFallsBackForInvalidStructuredParts(t *testing.T) { ] }`) - out := ConvertOpenAIRequestToCodex("gpt-4o", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-4o", input, true) result := string(out) parts := gjson.Get(result, "input.2.output").Array() @@ -459,7 +459,7 @@ func TestToolCallOutputWithNonStringJSONContent(t *testing.T) { ] }`) - out := ConvertOpenAIRequestToCodex("gpt-4o", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-4o", input, true) result := string(out) output := gjson.Get(result, "input.2.output") @@ -487,7 +487,7 @@ func TestConvertOpenAIRequestToCodexPreservesInputAudio(t *testing.T) { ] }`) - out := ConvertOpenAIRequestToCodex("gpt-5.5", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-5.5", input, true) parts := gjson.GetBytes(out, "input.0.content").Array() if len(parts) != 2 { t.Fatalf("expected 2 content parts, got %d: %s", len(parts), gjson.GetBytes(out, "input.0.content").Raw) @@ -559,7 +559,7 @@ func TestMultipleToolCalls(t *testing.T) { ] }`) - out := ConvertOpenAIRequestToCodex("gpt-4o", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-4o", input, true) result := string(out) items := gjson.Get(result, "input").Array() @@ -630,7 +630,7 @@ func TestNoSpuriousEmptyAssistantMessage(t *testing.T) { ] }`) - out := ConvertOpenAIRequestToCodex("gpt-4o", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-4o", input, true) result := string(out) items := gjson.Get(result, "input").Array() @@ -694,7 +694,7 @@ func TestMultiTurnToolCalling(t *testing.T) { ] }`) - out := ConvertOpenAIRequestToCodex("gpt-4o", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-4o", input, true) result := string(out) items := gjson.Get(result, "input").Array() @@ -778,7 +778,7 @@ func TestToolNameShortening(t *testing.T) { ] }`) - out := ConvertOpenAIRequestToCodex("gpt-4o", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-4o", input, true) result := string(out) items := gjson.Get(result, "input").Array() @@ -831,7 +831,7 @@ func TestCustomToolNameShortening(t *testing.T) { "tool_choice":{"type":"custom","name":"` + longName + `"} }`) - out := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) items := gjson.GetBytes(out, "input").Array() if len(items) != 3 { t.Fatalf("expected user, custom call, and custom output, got %d: %s", len(items), gjson.GetBytes(out, "input").Raw) @@ -877,7 +877,7 @@ func TestCustomToolShortNameCollisionPreservesFunctionFamily(t *testing.T) { "tool_choice":{"type":"function","function":{"name":"` + functionName + `"}} }`) - out := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) items := gjson.GetBytes(out, "input").Array() if len(items) != 2 { t.Fatalf("expected function call and output, got %d: %s", len(items), gjson.GetBytes(out, "input").Raw) @@ -911,7 +911,7 @@ func TestSameNameCustomAndFunctionDefaultsToFunctionFamily(t *testing.T) { "tool_choice":{"type":"function","function":{"name":"shared_tool"}} }`) - out := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) items := gjson.GetBytes(out, "input").Array() if len(items) != 2 { t.Fatalf("expected function call and output, got %d: %s", len(items), gjson.GetBytes(out, "input").Raw) @@ -961,7 +961,7 @@ func TestEmptyStringContent(t *testing.T) { ] }`) - out := ConvertOpenAIRequestToCodex("gpt-4o", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-4o", input, true) result := string(out) items := gjson.Get(result, "input").Array() @@ -1003,7 +1003,7 @@ func TestCallIDsMatchBetweenCallAndOutput(t *testing.T) { ] }`) - out := ConvertOpenAIRequestToCodex("gpt-4o", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-4o", input, true) result := string(out) items := gjson.Get(result, "input").Array() @@ -1080,7 +1080,7 @@ func TestCustomToolCallHistory(t *testing.T) { "tool_choice": {"type":"function","function":{"name":"apply_patch"}} }`) - out := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) items := gjson.GetBytes(out, "input").Array() if len(items) != 5 { t.Fatalf("expected 5 input items, got %d: %s", len(items), gjson.GetBytes(out, "input").Raw) @@ -1153,7 +1153,7 @@ func TestCustomToolCallResponseFollowUpRoundTrip(t *testing.T) { ], "tools":[{"type":"custom","name":"apply_patch","description":"Apply a patch."}] }`) - out := ConvertOpenAIRequestToCodex("gpt-5.6-sol", followUpRequest, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-5.6-sol", followUpRequest, true) items := gjson.GetBytes(out, "input").Array() if len(items) != 3 { t.Fatalf("expected user, custom call, and custom output, got %d: %s", len(items), gjson.GetBytes(out, "input").Raw) @@ -1186,7 +1186,7 @@ func TestMixedToolCallHistoryPreservesCallFamilies(t *testing.T) { ] }`) - out := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) items := gjson.GetBytes(out, "input").Array() if len(items) != 5 { t.Fatalf("expected 5 input items, got %d: %s", len(items), gjson.GetBytes(out, "input").Raw) @@ -1221,7 +1221,7 @@ func TestToolCallHistoryAllowsReusedCallIDAcrossRounds(t *testing.T) { ] }`) - out := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) items := gjson.GetBytes(out, "input").Array() if len(items) != 5 { t.Fatalf("expected 5 input items, got %d: %s", len(items), gjson.GetBytes(out, "input").Raw) @@ -1245,7 +1245,7 @@ func TestCustomToolCallHistorySynthesizesMissingCallID(t *testing.T) { ] }`) - out := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) items := gjson.GetBytes(out, "input").Array() if len(items) != 2 { t.Fatalf("expected orphan output to be dropped and missing ID pair preserved, got %d items: %s", len(items), gjson.GetBytes(out, "input").Raw) @@ -1278,7 +1278,7 @@ func TestToolCallHistoryClearsUnmatchedCallAtNewBatch(t *testing.T) { ] }`) - out := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) items := gjson.GetBytes(out, "input").Array() if len(items) != 3 { t.Fatalf("expected two calls and one output, got %d items: %s", len(items), gjson.GetBytes(out, "input").Raw) @@ -1300,7 +1300,7 @@ func TestToolCallOutputWithoutIDUsesPendingCall(t *testing.T) { ] }`) - out := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) items := gjson.GetBytes(out, "input").Array() if len(items) != 4 { t.Fatalf("expected two calls and two outputs, got %d items: %s", len(items), gjson.GetBytes(out, "input").Raw) @@ -1332,7 +1332,7 @@ func TestAmbiguousDuplicateToolCallIDsAreDropped(t *testing.T) { ] }`) - out := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) items := gjson.GetBytes(out, "input").Array() if len(items) != 1 || items[0].Get("role").String() != "user" { t.Fatalf("expected ambiguous calls and outputs to be dropped, got %s", gjson.GetBytes(out, "input").Raw) @@ -1354,7 +1354,7 @@ func TestOrphanAndDuplicateToolCallOutputsAreDropped(t *testing.T) { ] }`) - out := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) items := gjson.GetBytes(out, "input").Array() if len(items) != 2 { t.Fatalf("expected only the matched call and first output, got %d items: %s", len(items), gjson.GetBytes(out, "input").Raw) @@ -1389,7 +1389,7 @@ func TestToolsDefinitionTranslated(t *testing.T) { ] }`) - out := ConvertOpenAIRequestToCodex("gpt-4o", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-4o", input, true) result := string(out) tools := gjson.Get(result, "tools").Array() @@ -1442,7 +1442,7 @@ func TestFunctionToolStrictDefaultsToFalse(t *testing.T) { ] }`) - out := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) tools := gjson.GetBytes(out, "tools").Array() if len(tools) != 3 { t.Fatalf("expected 3 tools, got %d: %s", len(tools), gjson.GetBytes(out, "tools").Raw) @@ -1500,7 +1500,7 @@ func TestNormalizeInvalidToolNames(t *testing.T) { } }`) - out := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) toolNameInTools := gjson.GetBytes(out, "tools.0.name").String() nameRegex := regexp.MustCompile(`^[a-zA-Z0-9_-]+$`) if !nameRegex.MatchString(toolNameInTools) { @@ -1552,7 +1552,7 @@ func TestNormalizeInvalidToolNamesCollisionAndNonASCII(t *testing.T) { ] }`) - out := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) tools := gjson.GetBytes(out, "tools").Array() if len(tools) != 3 { t.Fatalf("expected 3 tools, got %d", len(tools)) @@ -1606,7 +1606,7 @@ func TestHistoricalToolCallCollisionWithDeclaredTool(t *testing.T) { ] }`) - out := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) + out, _ := ConvertOpenAIRequestToCodex("gpt-5.6-sol", input, true) toolDeclared := gjson.GetBytes(out, "tools.0.name").String() var histCallName string @@ -1705,7 +1705,7 @@ func TestConvertOpenAIRequestToCodexServiceTier(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - out := ConvertOpenAIRequestToCodex("gpt-6-sol", []byte(tt.body), true) + out, _ := ConvertOpenAIRequestToCodex("gpt-6-sol", []byte(tt.body), true) tierRes := gjson.GetBytes(out, "service_tier") if tierRes.Exists() != tt.wantExists { t.Fatalf("service_tier exists = %v, want %v; payload=%s", tierRes.Exists(), tt.wantExists, out) @@ -1730,7 +1730,7 @@ func TestApplyPatchChatHistoryBoundary(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { raw := []byte(`{"tools":` + tc.tools + `,"messages":[{"role":"assistant","tool_calls":[` + tc.call + `]}]}`) - out := ConvertOpenAIRequestToCodex("m", raw, true) + out, _ := ConvertOpenAIRequestToCodex("m", raw, true) items := gjson.GetBytes(out, "input").Array() item := items[len(items)-1] field := "arguments" diff --git a/internal/translator/codex/openai/chat-completions/codex_openai_response_test.go b/internal/translator/codex/openai/chat-completions/codex_openai_response_test.go index 61c71b74c03..18e35fe5777 100644 --- a/internal/translator/codex/openai/chat-completions/codex_openai_response_test.go +++ b/internal/translator/codex/openai/chat-completions/codex_openai_response_test.go @@ -1045,7 +1045,7 @@ func TestApplyPatchChatCompletionNativeHistoryRoundTrip(t *testing.T) { out := ConvertCodexResponseToOpenAINonStream(t.Context(), "m", original, original, response, nil) message := gjson.GetBytes(out, "choices.0.message") followup := []byte(`{"messages":[` + message.Raw + `,{"role":"tool","tool_call_id":"c","content":"ok"}],"tools":[{"type":"custom","name":"apply_patch"}]}`) - request := ConvertOpenAIRequestToCodex("m", followup, true) + request, _ := ConvertOpenAIRequestToCodex("m", followup, true) if got := gjson.GetBytes(request, "input.0.input").String(); got != "p" { t.Fatalf("normalized function history must restore raw patch before native Codex: got %q, request=%s", got, request) } diff --git a/internal/translator/codex/openai/chat-completions/codex_openai_user_turn_test.go b/internal/translator/codex/openai/chat-completions/codex_openai_user_turn_test.go index 39867d2694c..4d91d23036a 100644 --- a/internal/translator/codex/openai/chat-completions/codex_openai_user_turn_test.go +++ b/internal/translator/codex/openai/chat-completions/codex_openai_user_turn_test.go @@ -130,7 +130,7 @@ func TestConvertOpenAIRequestToCodex_AudioAfterHistoryStaysAudio(t *testing.T) { func TestConvertOpenAIRequestToCodex_ExportedWrapperKeepsAJSONBody(t *testing.T) { input := []byte(`{"model":"m","messages":[{"role":"user","content":[` + userTurnEmptyFile + `]}]}`) - if body := ConvertOpenAIRequestToCodex("m", input, false); !gjson.ValidBytes(body) { + if body, _ := ConvertOpenAIRequestToCodex("m", input, false); !gjson.ValidBytes(body) { t.Fatalf("body is not JSON: %q", body) } } diff --git a/internal/translator/codex/openai/chat-completions/init.go b/internal/translator/codex/openai/chat-completions/init.go index 82cd75bd9ad..35a3da8c02d 100644 --- a/internal/translator/codex/openai/chat-completions/init.go +++ b/internal/translator/codex/openai/chat-completions/init.go @@ -4,18 +4,16 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" - sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( OpenAI, Codex, - nil, + ConvertOpenAIRequestToCodex, interfaces.TranslateResponse{ Stream: ConvertCodexResponseToOpenAI, NonStream: ConvertCodexResponseToOpenAINonStream, }, ) - sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatOpenAI, sdktranslator.FormatCodex, convertOpenAIRequestToCodex) } diff --git a/internal/translator/codex/openai/responses/codex_openai-responses_request.go b/internal/translator/codex/openai/responses/codex_openai-responses_request.go index 447e5e72a69..475e5a31036 100644 --- a/internal/translator/codex/openai/responses/codex_openai-responses_request.go +++ b/internal/translator/codex/openai/responses/codex_openai-responses_request.go @@ -12,7 +12,7 @@ import ( "github.com/tidwall/sjson" ) -func ConvertOpenAIResponsesRequestToCodex(modelName string, inputRawJSON []byte, _ bool) []byte { +func ConvertOpenAIResponsesRequestToCodex(modelName string, inputRawJSON []byte, _ bool) ([]byte, error) { rawJSON := inputRawJSON inputResult := util.GetGJSONBytesNoCopy(rawJSON, "input") @@ -59,7 +59,7 @@ func ConvertOpenAIResponsesRequestToCodex(modelName string, inputRawJSON []byte, rawJSON = normalizeCodexBuiltinTools(rawJSON) rawJSON = normalizeEmptyFunctionCallArguments(rawJSON) - return rawJSON + return rawJSON, nil } // normalizeEmptyFunctionCallArguments rewrites blank string arguments on diff --git a/internal/translator/codex/openai/responses/codex_openai-responses_request_test.go b/internal/translator/codex/openai/responses/codex_openai-responses_request_test.go index 907a1f6159c..3e5c04408d1 100644 --- a/internal/translator/codex/openai/responses/codex_openai-responses_request_test.go +++ b/internal/translator/codex/openai/responses/codex_openai-responses_request_test.go @@ -31,7 +31,7 @@ func TestConvertSystemRoleToDeveloper_BasicConversion(t *testing.T) { ] }`) - output := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) + output, _ := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) outputStr := string(output) // Check that system role was converted to developer @@ -76,7 +76,7 @@ func TestConvertSystemRoleToDeveloper_MultipleSystemMessages(t *testing.T) { ] }`) - output := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) + output, _ := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) outputStr := string(output) // Check that both system roles were converted @@ -115,7 +115,7 @@ func TestConvertSystemRoleToDeveloper_NoSystemMessages(t *testing.T) { ] }`) - output := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) + output, _ := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) outputStr := string(output) // Check that user and assistant roles are unchanged @@ -137,7 +137,7 @@ func TestConvertSystemRoleToDeveloper_EmptyInput(t *testing.T) { "input": [] }`) - output := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) + output, _ := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) outputStr := string(output) // Check that input is still an empty array @@ -157,7 +157,7 @@ func TestConvertSystemRoleToDeveloper_NoInputField(t *testing.T) { "stream": false }`) - output := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) + output, _ := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) outputStr := string(output) // Check that other fields are still set correctly @@ -192,7 +192,7 @@ func TestConvertOpenAIResponsesRequestToCodex_OriginalIssue(t *testing.T) { "stream": false }`) - output := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) + output, _ := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) outputStr := string(output) // Verify system role was converted to developer @@ -229,7 +229,7 @@ func TestConvertOpenAIResponsesRequestToCodex_OriginalIssue(t *testing.T) { func TestConvertOpenAIResponsesRequestToCodexReusesNormalizedPayload(t *testing.T) { inputJSON := []byte(`{"model":"gpt-5.6","stream":true,"store":false,"parallel_tool_calls":true,"include":["reasoning.encrypted_content"],"service_tier":"priority","input":[{"type":"message","role":"user","content":"hello"}]}`) - output := ConvertOpenAIResponsesRequestToCodex("gpt-5.6", inputJSON, true) + output, _ := ConvertOpenAIResponsesRequestToCodex("gpt-5.6", inputJSON, true) if &output[0] != &inputJSON[0] { t.Fatal("normalized request payload was copied") @@ -258,7 +258,7 @@ func TestConvertOpenAIResponsesRequestToCodexNormalizesRequiredFields(t *testing "input":[{"type":"message","role":"system","content":"hello"}] }`) - output := ConvertOpenAIResponsesRequestToCodex("gpt-5.6", inputJSON, true) + output, _ := ConvertOpenAIResponsesRequestToCodex("gpt-5.6", inputJSON, true) if stream := gjson.GetBytes(output, "stream"); stream.Type != gjson.True { t.Fatalf("stream = %s, want true", stream.Raw) @@ -328,7 +328,7 @@ func TestConvertOpenAIResponsesRequestToCodex_PreservesWebSearchSourcesInclude(t } before := string(inputJSON) - output := ConvertOpenAIResponsesRequestToCodex("gpt-5.6", inputJSON, stream) + output, _ := ConvertOpenAIResponsesRequestToCodex("gpt-5.6", inputJSON, stream) if string(inputJSON) != before { t.Fatalf("caller input changed:\n got: %s\nwant: %s", inputJSON, before) } @@ -349,7 +349,7 @@ func TestConvertOpenAIResponsesRequestToCodex_PreservesWebSearchSourcesInclude(t func TestConvertOpenAIResponsesRequestToCodex_WebSearchToolDoesNotOptIntoSources(t *testing.T) { inputJSON := []byte(`{"model":"gpt-5.6","input":"find python asyncio docs","tools":[{"type":"web_search"}],"tool_choice":"required"}`) - output := ConvertOpenAIResponsesRequestToCodex("gpt-5.6", inputJSON, true) + output, _ := ConvertOpenAIResponsesRequestToCodex("gpt-5.6", inputJSON, true) include := gjson.GetBytes(output, "include").Array() if len(include) != 1 || include[0].Type != gjson.String || include[0].String() != "reasoning.encrypted_content" { @@ -365,7 +365,7 @@ func TestConvertOpenAIResponsesRequestToCodexReusesNormalizedPayloadWithSources( } { inputJSON := []byte(`{"model":"gpt-5.6","stream":true,"store":false,"parallel_tool_calls":true,"include":` + includeJSON + `,"service_tier":"priority","input":[{"type":"message","role":"user","content":"hello"}]}`) - output := ConvertOpenAIResponsesRequestToCodex("gpt-5.6", inputJSON, true) + output, _ := ConvertOpenAIResponsesRequestToCodex("gpt-5.6", inputJSON, true) if &output[0] != &inputJSON[0] { t.Fatalf("normalized request payload with include %s was copied", includeJSON) @@ -394,7 +394,7 @@ func TestConvertOpenAIResponsesRequestToCodex_FiltersPromptCacheRetention(t *tes ] }`) - output := ConvertOpenAIResponsesRequestToCodex("gpt-5.6-terra", inputJSON, true) + output, _ := ConvertOpenAIResponsesRequestToCodex("gpt-5.6-terra", inputJSON, true) if gjson.GetBytes(output, "prompt_cache_retention").Exists() { t.Fatalf("prompt_cache_retention should be removed: %s", string(output)) } @@ -423,7 +423,7 @@ func TestConvertSystemRoleToDeveloper_AssistantRole(t *testing.T) { ] }`) - output := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) + output, _ := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) outputStr := string(output) // Check system -> developer @@ -461,7 +461,7 @@ func TestConvertOpenAIResponsesRequestToCodex_NormalizesWebSearchPreview(t *test } }`) - output := ConvertOpenAIResponsesRequestToCodex("gpt-5.4-mini", inputJSON, false) + output, _ := ConvertOpenAIResponsesRequestToCodex("gpt-5.4-mini", inputJSON, false) if got := gjson.GetBytes(output, "tools.0.type").String(); got != "web_search" { t.Fatalf("tools.0.type = %q, want %q: %s", got, "web_search", string(output)) @@ -484,7 +484,7 @@ func TestConvertOpenAIResponsesRequestToCodex_NormalizesTopLevelToolChoicePrevie "tool_choice": {"type": "web_search_preview_2025_03_11"} }`) - output := ConvertOpenAIResponsesRequestToCodex("gpt-5.4-mini", inputJSON, false) + output, _ := ConvertOpenAIResponsesRequestToCodex("gpt-5.4-mini", inputJSON, false) if got := gjson.GetBytes(output, "tool_choice.type").String(); got != "web_search" { t.Fatalf("tool_choice.type = %q, want %q: %s", got, "web_search", string(output)) @@ -498,7 +498,7 @@ func TestUserFieldDeletion(t *testing.T) { "input": [{"role": "user", "content": "Hello"}] }`) - output := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) + output, _ := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) outputStr := string(output) // Verify user field is deleted @@ -520,7 +520,7 @@ func TestContextManagementCompactionCompatibility(t *testing.T) { "input": [{"role":"user","content":"hello"}] }`) - output := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) + output, _ := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) outputStr := string(output) if gjson.Get(outputStr, "context_management").Exists() { @@ -538,7 +538,7 @@ func TestTruncationRemovedForCodexCompatibility(t *testing.T) { "input": [{"role":"user","content":"hello"}] }`) - output := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) + output, _ := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) outputStr := string(output) if gjson.Get(outputStr, "truncation").Exists() { @@ -568,7 +568,7 @@ func TestStripCodexResponsesCacheBreakpoints(t *testing.T) { ] }`) - output := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) + output, _ := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) outputStr := string(output) if strings.Contains(outputStr, "prompt_cache_breakpoint") { @@ -606,7 +606,7 @@ func TestStripCodexResponsesCacheBreakpoints_FunctionCallOutputParts(t *testing. ] }`) - output := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) + output, _ := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) outputStr := string(output) if strings.Contains(outputStr, "prompt_cache_breakpoint") { @@ -636,7 +636,7 @@ func TestStripCodexResponsesCacheBreakpoints_ItemLevel(t *testing.T) { ] }`) - output := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) + output, _ := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) outputStr := string(output) if strings.Contains(outputStr, "prompt_cache_breakpoint") { @@ -673,7 +673,7 @@ func TestStripCodexResponsesCacheBreakpoints_CombinedItemAndPartLevel(t *testing ] }`) - output := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) + output, _ := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) outputStr := string(output) if strings.Contains(outputStr, "prompt_cache_breakpoint") { @@ -722,7 +722,7 @@ func TestStripCodexResponsesCacheBreakpoints_WithSystemRole(t *testing.T) { ] }`) - output := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) + output, _ := ConvertOpenAIResponsesRequestToCodex("gpt-5.2", inputJSON, false) outputStr := string(output) // Check system role is converted to developer @@ -816,7 +816,7 @@ func BenchmarkConvertOpenAIResponsesRequestToCodexNormalizedPayload(b *testing.B var output []byte for b.Loop() { - output = ConvertOpenAIResponsesRequestToCodex("gpt-5.6", testCase.inputJSON, true) + output, _ = ConvertOpenAIResponsesRequestToCodex("gpt-5.6", testCase.inputJSON, true) } benchmarkConvertNormalizedOutput = output }) @@ -955,7 +955,7 @@ func TestConvertOpenAIResponsesRequestToCodex_ServiceTier(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { inputJSON := []byte(fmt.Sprintf(`{"model":"gpt-5.6","service_tier":%s,"input":[{"type":"message","role":"user","content":"hello"}]}`, tt.tierJSON)) - output := ConvertOpenAIResponsesRequestToCodex("gpt-5.6", inputJSON, true) + output, _ := ConvertOpenAIResponsesRequestToCodex("gpt-5.6", inputJSON, true) res := gjson.GetBytes(output, "service_tier") if res.Exists() != tt.wantExists { t.Fatalf("service_tier exists = %v, want %v; output: %s", res.Exists(), tt.wantExists, string(output)) @@ -985,7 +985,7 @@ func TestConvertOpenAIResponsesRequestToCodex_NormalizesEmptyFunctionCallArgumen {"type":"custom_tool_call","id":"ctc_1","call_id":"call_custom","name":"apply_patch","input":"exact patch"}, {"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]} ]}`) - output := ConvertOpenAIResponsesRequestToCodex("gpt-5.6", inputJSON, true) + output, _ := ConvertOpenAIResponsesRequestToCodex("gpt-5.6", inputJSON, true) for index, want := range []string{"{}", "{}", `{"cmd":"pwd"}`, "not-json"} { if got := gjson.GetBytes(output, "input."+strconv.Itoa(index)+".arguments").String(); got != want { t.Fatalf("input.%d.arguments = %q, want %q; output: %s", index, got, want, string(output)) diff --git a/internal/translator/gemini/claude/gemini_claude_compat_test.go b/internal/translator/gemini/claude/gemini_claude_compat_test.go index 0569c12d890..b2436860b06 100644 --- a/internal/translator/gemini/claude/gemini_claude_compat_test.go +++ b/internal/translator/gemini/claude/gemini_claude_compat_test.go @@ -35,7 +35,7 @@ func TestConvertClaudeRequestToGeminiWithCompat_SignatureCompatibility(t *testin for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { payload := []byte(`{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"reason","signature":"` + tt.signature + `"}]}]}`) - withCompat := ConvertClaudeRequestToGeminiWithCompat("deepseek-v4", payload, false) + withCompat, _ := ConvertClaudeRequestToGeminiWithCompat("deepseek-v4", payload, false) part := gjson.GetBytes(withCompat, "contents.0.parts.0") if !part.Get("thought").Bool() || part.Get("text").String() != "reason" { t.Fatalf("compat translation missing thought part: %s", withCompat) @@ -50,12 +50,12 @@ func TestConvertClaudeRequestToGeminiWithCompat_SignatureCompatibility(t *testin func TestConvertClaudeRequestToGeminiWithCompatPreservesEmptyThinking(t *testing.T) { payload := []byte(`{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"reason","signature":""}]}]}`) - withoutCompat := ConvertClaudeRequestToGemini("deepseek-v4", payload, false) + withoutCompat, _ := ConvertClaudeRequestToGemini("deepseek-v4", payload, false) if gjson.GetBytes(withoutCompat, "contents.0.parts.#").Int() != 0 { t.Fatalf("default translation preserved thinking: %s", withoutCompat) } - withCompat := ConvertClaudeRequestToGeminiWithCompat("deepseek-v4", payload, false) + withCompat, _ := ConvertClaudeRequestToGeminiWithCompat("deepseek-v4", payload, false) part := gjson.GetBytes(withCompat, "contents.0.parts.0") if !part.Get("thought").Bool() || part.Get("text").String() != "reason" { t.Fatalf("compat translation missing thought part: %s", withCompat) diff --git a/internal/translator/gemini/claude/gemini_claude_request.go b/internal/translator/gemini/claude/gemini_claude_request.go index e054ac87d72..85b20c42bc5 100644 --- a/internal/translator/gemini/claude/gemini_claude_request.go +++ b/internal/translator/gemini/claude/gemini_claude_request.go @@ -30,20 +30,14 @@ const geminiClaudeThoughtSignature = "skip_thought_signature_validator" // // Returns: // - []byte: The transformed request in Gemini format. -func ConvertClaudeRequestToGemini(modelName string, inputRawJSON []byte, stream bool) []byte { - body, _ := convertClaudeRequestToGemini(modelName, inputRawJSON, stream, false) - return body +func ConvertClaudeRequestToGemini(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { + return convertClaudeRequestToGemini(modelName, inputRawJSON, stream, false) + } // ConvertClaudeRequestToGeminiWithCompat preserves assistant thinking blocks // with empty signatures for configured compatibility endpoints. -func ConvertClaudeRequestToGeminiWithCompat(modelName string, inputRawJSON []byte, stream bool) []byte { - body, _ := convertClaudeRequestToGemini(modelName, inputRawJSON, stream, true) - return body -} - -// ConvertClaudeRequestToGeminiWithCompatReturningError reports a file part the target cannot represent. -func ConvertClaudeRequestToGeminiWithCompatReturningError(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { +func ConvertClaudeRequestToGeminiWithCompat(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { return convertClaudeRequestToGemini(modelName, inputRawJSON, stream, true) } diff --git a/internal/translator/gemini/claude/gemini_claude_request_test.go b/internal/translator/gemini/claude/gemini_claude_request_test.go index b68cf8399a3..29471e5fe1d 100644 --- a/internal/translator/gemini/claude/gemini_claude_request_test.go +++ b/internal/translator/gemini/claude/gemini_claude_request_test.go @@ -35,7 +35,7 @@ func TestConvertClaudeRequestToGemini_ToolChoice_SpecificTool(t *testing.T) { "tool_choice": {"type": "tool", "name": "json"} }`) - output := ConvertClaudeRequestToGemini("gemini-3-flash-preview", inputJSON, false) + output, _ := ConvertClaudeRequestToGemini("gemini-3-flash-preview", inputJSON, false) if got := gjson.GetBytes(output, "toolConfig.functionCallingConfig.mode").String(); got != "ANY" { t.Fatalf("Expected toolConfig.functionCallingConfig.mode 'ANY', got '%s'", got) @@ -53,7 +53,7 @@ func TestConvertClaudeRequestToGemini_StringSystemInstruction(t *testing.T) { "messages": [{"role": "user", "content": "Hello"}] }`) - output := ConvertClaudeRequestToGemini("gemini-3-flash-preview", inputJSON, false) + output, _ := ConvertClaudeRequestToGemini("gemini-3-flash-preview", inputJSON, false) if got := gjson.GetBytes(output, "systemInstruction.parts.0.text").String(); got != "Be concise" { t.Fatalf("Expected systemInstruction text %q, got %q", "Be concise", got) @@ -87,7 +87,7 @@ func TestConvertClaudeRequestToGemini_ImageContent(t *testing.T) { ] }`) - output := ConvertClaudeRequestToGemini("gemini-3-flash-preview", inputJSON, false) + output, _ := ConvertClaudeRequestToGemini("gemini-3-flash-preview", inputJSON, false) parts := gjson.GetBytes(output, "contents.0.parts").Array() if len(parts) != 2 { @@ -115,7 +115,7 @@ func TestConvertClaudeRequestToGemini_StripsClaudeCodeAttribution(t *testing.T) "messages": [{"role": "user", "content": [{"type": "text", "text": "hi"}]}] }`) - output := ConvertClaudeRequestToGemini("gemini-3-flash-preview", inputJSON, false) + output, _ := ConvertClaudeRequestToGemini("gemini-3-flash-preview", inputJSON, false) parts := gjson.GetBytes(output, "systemInstruction.parts").Array() if len(parts) != 2 { @@ -143,7 +143,7 @@ func TestConvertClaudeRequestToGemini_ConvertsMessageSystemRoleToUserContent(t * ] }`) - output := ConvertClaudeRequestToGemini("gemini-3-flash-preview", inputJSON, false) + output, _ := ConvertClaudeRequestToGemini("gemini-3-flash-preview", inputJSON, false) if systemContent := gjson.GetBytes(output, `contents.#(role=="system")`); systemContent.Exists() { t.Fatalf("system role should not be emitted in contents: %s", systemContent.Raw) @@ -190,7 +190,7 @@ func TestConvertClaudeRequestToGemini_MessageLevelDeveloperInstructionsBecomeMer ] }`) - output := ConvertClaudeRequestToGemini("gemini-3-flash-preview", inputJSON, false) + output, _ := ConvertClaudeRequestToGemini("gemini-3-flash-preview", inputJSON, false) if devContent := gjson.GetBytes(output, `contents.#(role=="developer")`); devContent.Exists() { t.Fatalf("developer role should not be emitted in contents: %s", devContent.Raw) @@ -255,7 +255,7 @@ func TestConvertClaudeRequestToGemini_PreservesToolPairingWithInterveningSystemM ] }`) - output := ConvertClaudeRequestToGemini("gemini-3-flash-preview", inputJSON, false) + output, _ := ConvertClaudeRequestToGemini("gemini-3-flash-preview", inputJSON, false) if errPairing := internalsignature.ValidateGeminiFunctionCallPairing(output); errPairing != nil { t.Fatalf("ValidateGeminiFunctionCallPairing failed: %v\noutput: %s", errPairing, output) @@ -307,7 +307,7 @@ func TestConvertClaudeRequestToGemini_SkipsEmptyTextParts(t *testing.T) { ] }`) - output := ConvertClaudeRequestToGemini("gemini-3-flash-preview", inputJSON, false) + output, _ := ConvertClaudeRequestToGemini("gemini-3-flash-preview", inputJSON, false) parts := gjson.GetBytes(output, "contents.0.parts").Array() if len(parts) != 1 { @@ -344,7 +344,7 @@ func TestConvertClaudeRequestToGemini_StructuredToolResult(t *testing.T) { ] }`) - output := ConvertClaudeRequestToGemini("gemini-3-flash-preview", inputJSON, false) + output, _ := ConvertClaudeRequestToGemini("gemini-3-flash-preview", inputJSON, false) fr := gjson.GetBytes(output, "contents.1.parts.0.functionResponse") if !fr.Exists() { @@ -383,7 +383,7 @@ func TestConvertClaudeRequestToGemini_AlignsPermutedParallelToolResultsWithMixed ] }`) - output := ConvertClaudeRequestToGemini("gemini-3.7-flash-high", inputJSON, false) + output, _ := ConvertClaudeRequestToGemini("gemini-3.7-flash-high", inputJSON, false) callParts := gjson.GetBytes(output, "contents.0.parts").Array() responseParts := gjson.GetBytes(output, "contents.1.parts").Array() if len(callParts) != 3 || len(responseParts) != 5 { @@ -433,7 +433,7 @@ func TestConvertClaudeRequestToGemini_StringToolResult(t *testing.T) { ] }`) - output := ConvertClaudeRequestToGemini("gemini-3-flash-preview", inputJSON, false) + output, _ := ConvertClaudeRequestToGemini("gemini-3-flash-preview", inputJSON, false) fr := gjson.GetBytes(output, "contents.1.parts.0.functionResponse") if !fr.Exists() { @@ -469,7 +469,7 @@ func TestConvertClaudeRequestToGemini_ToolResultWithTrailingSystemReminderReorde ] }`) - output := ConvertClaudeRequestToGemini("gemini-3.8-flash", inputJSON, false) + output, _ := ConvertClaudeRequestToGemini("gemini-3.8-flash", inputJSON, false) contents := gjson.GetBytes(output, "contents").Array() if len(contents) != 3 { @@ -553,7 +553,7 @@ func TestConvertClaudeRequestToGemini_ToolStrictMapsToValidatedMode(t *testing.T ] }`, tt.toolChoice) - result := ConvertClaudeRequestToGemini("gemini-3.8-flash", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToGemini("gemini-3.8-flash", []byte(inputJSON), false) if gjson.GetBytes(result, "tools.0.functionDeclarations.0.strict").Exists() { t.Fatalf("strict must be removed from functionDeclarations: %s", result) } @@ -594,7 +594,7 @@ func TestConvertClaudeRequestToGemini_ToolStrictMapsToValidatedMode(t *testing.T } ] }`) - result := ConvertClaudeRequestToGemini("gemini-3.8-flash", inputJSON, false) + result, _ := ConvertClaudeRequestToGemini("gemini-3.8-flash", inputJSON, false) mode := gjson.GetBytes(result, "toolConfig.functionCallingConfig.mode").String() if mode != "VALIDATED" { t.Fatalf("expected mode = 'VALIDATED' for mixed tools, got %q", mode) @@ -619,7 +619,7 @@ func TestConvertClaudeRequestToGemini_ToolStrictMapsToValidatedMode(t *testing.T } ] }`) - result := ConvertClaudeRequestToGemini("gemini-3.8-flash", inputJSON, false) + result, _ := ConvertClaudeRequestToGemini("gemini-3.8-flash", inputJSON, false) if gjson.GetBytes(result, "toolConfig").Exists() { t.Fatalf("expected toolConfig not to be set when no strict tools and no tool_choice, got: %s", result) } @@ -653,7 +653,7 @@ func TestConvertClaudeRequestToGemini_ParametersJsonSchema_PreservesAdditionalPr ] }`) - output := ConvertClaudeRequestToGemini("gemini-2.5-flash", inputJSON, false) + output, _ := ConvertClaudeRequestToGemini("gemini-2.5-flash", inputJSON, false) schema := gjson.GetBytes(output, "tools.0.functionDeclarations.0.parametersJsonSchema") if !schema.Exists() { t.Fatalf("parametersJsonSchema missing. Output: %s", output) @@ -699,7 +699,7 @@ func TestConvertClaudeRequestToGemini_FunctionResponseJSONRef(t *testing.T) { ] }`) - output := ConvertClaudeRequestToGemini("gemini-3.8-flash", inputJSON, false) + output, _ := ConvertClaudeRequestToGemini("gemini-3.8-flash", inputJSON, false) result := gjson.GetBytes(output, "contents.1.parts.0.functionResponse.response.result") if result.Type != gjson.String { t.Fatalf("expected functionResponse.response.result to be string, got %s (raw: %s)", result.Type, result.Raw) @@ -729,7 +729,7 @@ func TestConvertClaudeRequestToGemini_Issue5960_DocumentPreservation(t *testing. } ] }`) - pdfOut := ConvertClaudeRequestToGemini("gemini-2.5-pro", pdfInput, false) + pdfOut, _ := ConvertClaudeRequestToGemini("gemini-2.5-pro", pdfInput, false) pdfParts := gjson.GetBytes(pdfOut, "contents.0.parts").Array() if len(pdfParts) == 0 { t.Fatalf("expected non-empty parts for base64 document, got: %s", string(pdfOut)) @@ -761,7 +761,7 @@ func TestConvertClaudeRequestToGemini_Issue5960_DocumentPreservation(t *testing. } ] }`) - mixedOut := ConvertClaudeRequestToGemini("gemini-2.5-pro", mixedInput, false) + mixedOut, _ := ConvertClaudeRequestToGemini("gemini-2.5-pro", mixedInput, false) mixedParts := gjson.GetBytes(mixedOut, "contents.0.parts").Array() if len(mixedParts) != 2 { t.Fatalf("expected 2 parts for mixed text + document, got %d (output: %s)", len(mixedParts), string(mixedOut)) @@ -801,7 +801,7 @@ func TestConvertClaudeRequestToGemini_Issue5960_DocumentPreservation(t *testing. } ] }`) - interleavedOut := ConvertClaudeRequestToGemini("gemini-2.5-pro", interleavedInput, false) + interleavedOut, _ := ConvertClaudeRequestToGemini("gemini-2.5-pro", interleavedInput, false) interleavedParts := gjson.GetBytes(interleavedOut, "contents.0.parts").Array() if len(interleavedParts) != 3 { t.Fatalf("expected 3 parts for interleaved documents, got %d (output: %s)", len(interleavedParts), string(interleavedOut)) @@ -822,7 +822,7 @@ func TestConvertClaudeRequestToGemini_Issue5960_DocumentPreservation(t *testing. } ] }`) - unsupportedOut := ConvertClaudeRequestToGemini("gemini-2.5-pro", unsupportedInput, false) + unsupportedOut, _ := ConvertClaudeRequestToGemini("gemini-2.5-pro", unsupportedInput, false) contents := gjson.GetBytes(unsupportedOut, "contents").Array() if len(contents) != 0 { t.Fatalf("expected 0 contents turns instead of empty parts turn, got: %s", string(unsupportedOut)) @@ -837,7 +837,7 @@ func TestConvertClaudeRequestToGemini_ContainerUploadKeepsOtherText(t *testing.T {"type": "container_upload", "file_id": "file-example"} ]}] }`) - output := ConvertClaudeRequestToGemini("gemini-3-flash-preview", inputJSON, false) + output, _ := ConvertClaudeRequestToGemini("gemini-3-flash-preview", inputJSON, false) parts := gjson.GetBytes(output, "contents.0.parts").Array() if len(parts) != 1 || parts[0].Get("text").String() != "keep me" { t.Fatalf("text was dropped with the file: %s", output) @@ -853,7 +853,7 @@ func TestConvertClaudeRequestToGemini_UnsendableFileNamesTheDroppedPart(t *testi "model": "gemini-3-flash-preview", "messages": [{"role": "user", "content": [` + block + `]}] }`) - output, err := ConvertClaudeRequestToGeminiWithCompatReturningError("gemini-3-flash-preview", inputJSON, false) + output, err := ConvertClaudeRequestToGeminiWithCompat("gemini-3-flash-preview", inputJSON, false) if err == nil { t.Fatalf("%s: expected unsupported part error, output=%s", partType, output) } @@ -876,7 +876,7 @@ func TestConvertClaudeRequestToGemini_ImageURLAndRedactedThinkingStaySkipped(t * {"type": "redacted_thinking", "data": "abc"} ]}] }`) - output := ConvertClaudeRequestToGemini("gemini-3-flash-preview", inputJSON, false) + output, _ := ConvertClaudeRequestToGemini("gemini-3-flash-preview", inputJSON, false) parts := gjson.GetBytes(output, "contents.0.parts").Array() if len(parts) != 1 || parts[0].Get("text").String() != "keep me" { t.Fatalf("old skip paths changed the turn: %s", output) diff --git a/internal/translator/gemini/claude/gemini_claude_user_turn_test.go b/internal/translator/gemini/claude/gemini_claude_user_turn_test.go index c6bde9a41f3..b6240375023 100644 --- a/internal/translator/gemini/claude/gemini_claude_user_turn_test.go +++ b/internal/translator/gemini/claude/gemini_claude_user_turn_test.go @@ -41,7 +41,7 @@ func TestConvertClaudeRequestToGemini_RefusesAnyEmptiedUserTurn(t *testing.T) { } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - body, err := ConvertClaudeRequestToGeminiWithCompatReturningError("m", []byte(tc.input), false) + body, err := ConvertClaudeRequestToGeminiWithCompat("m", []byte(tc.input), false) var unsupported *translatorcommon.UnsupportedPartError if !errors.As(err, &unsupported) || unsupported.Type != tc.wantType || unsupported.StatusCode() != 400 { t.Fatalf("err = %v, want unsupported content part: %s; body = %s", err, tc.wantType, body) @@ -58,7 +58,7 @@ func TestConvertClaudeRequestToGemini_RefusesAnyEmptiedUserTurn(t *testing.T) { func TestConvertClaudeRequestToGemini_KeepsTurnWithTextBesideAttachment(t *testing.T) { input := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"text","text":"keep me"},` + userTurnUpload + `]}]}`) - body, err := ConvertClaudeRequestToGeminiWithCompatReturningError("m", input, false) + body, err := ConvertClaudeRequestToGeminiWithCompat("m", input, false) if err != nil { t.Fatalf("err = %v", err) } @@ -69,7 +69,7 @@ func TestConvertClaudeRequestToGemini_KeepsTurnWithTextBesideAttachment(t *testi func TestConvertClaudeRequestToGemini_Base64DocumentAfterHistoryStaysInlineData(t *testing.T) { input := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"document","source":{"type":"base64","media_type":"application/pdf","data":"JVBERi0xLjQK"}}]}]}`) - body, err := ConvertClaudeRequestToGeminiWithCompatReturningError("m", input, false) + body, err := ConvertClaudeRequestToGeminiWithCompat("m", input, false) if err != nil { t.Fatalf("err = %v", err) } diff --git a/internal/translator/gemini/claude/init.go b/internal/translator/gemini/claude/init.go index 357c131d5b9..a7f510c8edb 100644 --- a/internal/translator/gemini/claude/init.go +++ b/internal/translator/gemini/claude/init.go @@ -4,21 +4,17 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" - sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( Claude, Gemini, - nil, + ConvertClaudeRequestToGemini, interfaces.TranslateResponse{ Stream: ConvertGeminiResponseToClaude, NonStream: ConvertGeminiResponseToClaudeNonStream, TokenCount: ClaudeTokenCount, }, ) - sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatClaude, sdktranslator.FormatGemini, func(model string, body []byte, stream bool) ([]byte, error) { - return convertClaudeRequestToGemini(model, body, stream, false) - }) } diff --git a/internal/translator/gemini/gemini/gemini_gemini_request.go b/internal/translator/gemini/gemini/gemini_gemini_request.go index ba7add2cc87..330ac46ec8a 100644 --- a/internal/translator/gemini/gemini/gemini_gemini_request.go +++ b/internal/translator/gemini/gemini/gemini_gemini_request.go @@ -21,12 +21,12 @@ import ( // The first message defaults to "user", then alternates user/model when needed. // // It keeps the payload otherwise unchanged. -func ConvertGeminiRequestToGemini(_ string, inputRawJSON []byte, _ bool) []byte { +func ConvertGeminiRequestToGemini(_ string, inputRawJSON []byte, _ bool) ([]byte, error) { rawJSON := inputRawJSON // Fast path: if no contents field, only attach safety settings contents := util.GetGJSONBytesNoCopy(rawJSON, "contents") if !contents.Exists() { - return common.AttachDefaultSafetySettings(rawJSON, "safetySettings") + return common.AttachDefaultSafetySettings(rawJSON, "safetySettings"), nil } toolsResult := gjson.GetBytes(rawJSON, "tools") @@ -138,7 +138,7 @@ func ConvertGeminiRequestToGemini(_ string, inputRawJSON []byte, _ bool) []byte out = backfillEmptyFunctionResponseNames(out) out = common.AttachDefaultSafetySettings(out, "safetySettings") - return out + return out, nil } // backfillEmptyFunctionResponseNames walks the contents array and for each diff --git a/internal/translator/gemini/gemini/gemini_gemini_request_test.go b/internal/translator/gemini/gemini/gemini_gemini_request_test.go index ba70a905cda..d70128a3ee0 100644 --- a/internal/translator/gemini/gemini/gemini_gemini_request_test.go +++ b/internal/translator/gemini/gemini/gemini_gemini_request_test.go @@ -18,7 +18,7 @@ func TestConvertGeminiRequestToGeminiReusesLargeNormalizedPayload(t *testing.T) // a failing benchmark aborts before any iteration completes and yields a zero // BenchmarkResult, so AllocedBytesPerOp would report 0 and silently satisfy the // allocation check below exactly when the payload is being copied. - output := ConvertGeminiRequestToGemini("gemini-test", input, false) + output, _ := ConvertGeminiRequestToGemini("gemini-test", input, false) if &output[0] != &input[0] { t.Fatal("normalized request should reuse the input payload") } @@ -27,7 +27,7 @@ func TestConvertGeminiRequestToGeminiReusesLargeNormalizedPayload(t *testing.T) result := testing.Benchmark(func(b *testing.B) { b.ReportAllocs() for b.Loop() { - largeInlineDataBenchmarkOutput = ConvertGeminiRequestToGemini("gemini-test", input, false) + largeInlineDataBenchmarkOutput, _ = ConvertGeminiRequestToGemini("gemini-test", input, false) } }) @@ -53,7 +53,7 @@ func BenchmarkConvertGeminiRequestToGeminiLargeInlineData(b *testing.B) { b.SetBytes(int64(len(input))) b.ResetTimer() for b.Loop() { - largeInlineDataBenchmarkOutput = ConvertGeminiRequestToGemini("gemini-test", input, false) + largeInlineDataBenchmarkOutput, _ = ConvertGeminiRequestToGemini("gemini-test", input, false) } }) } @@ -170,7 +170,7 @@ func TestConvertGeminiRequestToGemini_BackfillsEmptyName(t *testing.T) { ] }`) - out := ConvertGeminiRequestToGemini("", input, false) + out, _ := ConvertGeminiRequestToGemini("", input, false) name := gjson.GetBytes(out, "contents.1.parts.0.functionResponse.name").String() if name != "Bash" { @@ -261,7 +261,7 @@ func TestConvertGeminiRequestToGemini_FunctionResponseWithInvalidRoleNormalizesT {"role": "invalid", "parts": [{"functionResponse": {"name": "lookup", "response": {}}}]} ] }`) - out := ConvertGeminiRequestToGemini("gemini-3-flash", inputJSON, false) + out, _ := ConvertGeminiRequestToGemini("gemini-3-flash", inputJSON, false) contents := gjson.GetBytes(out, "contents").Array() if len(contents) != 2 { t.Fatalf("expected 2 contents, got %d", len(contents)) diff --git a/internal/translator/gemini/interactions/init.go b/internal/translator/gemini/interactions/init.go index ec1785e867b..2a338c207a5 100644 --- a/internal/translator/gemini/interactions/init.go +++ b/internal/translator/gemini/interactions/init.go @@ -4,7 +4,6 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" - sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { @@ -20,7 +19,7 @@ func init() { translator.Register( Interactions, Gemini, - nil, + ConvertInteractionsRequestToGemini, interfaces.TranslateResponse{ Stream: ConvertGeminiResponseToInteractions, NonStream: ConvertGeminiResponseToInteractionsNonStream, @@ -29,12 +28,10 @@ func init() { translator.Register( Gemini, Interactions, - nil, + ConvertGeminiRequestToInteractions, interfaces.TranslateResponse{ Stream: ConvertInteractionsResponseToGemini, NonStream: ConvertInteractionsResponseToGeminiNonStream, }, ) - sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatInteractions, sdktranslator.FormatGemini, convertInteractionsRequestToGemini) - sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatGemini, sdktranslator.FormatInteractions, convertGeminiRequestToInteractions) } diff --git a/internal/translator/gemini/interactions/interactions_gemini_common.go b/internal/translator/gemini/interactions/interactions_gemini_common.go index e0ec74a4b5d..49d29586d8d 100644 --- a/internal/translator/gemini/interactions/interactions_gemini_common.go +++ b/internal/translator/gemini/interactions/interactions_gemini_common.go @@ -26,9 +26,9 @@ type StreamState struct { StepIndex int } -func ConvertInteractionsRequestToGemini(modelName string, inputRawJSON []byte, stream bool) []byte { - out, _ := convertInteractionsRequestToGemini(modelName, inputRawJSON, stream) - return out +func ConvertInteractionsRequestToGemini(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { + return convertInteractionsRequestToGemini(modelName, inputRawJSON, stream) + } // convertInteractionsRequestToGemini also reports a user turn that was left empty @@ -51,9 +51,9 @@ func convertInteractionsRequestToGemini(modelName string, inputRawJSON []byte, s return out, errInput } -func ConvertGeminiRequestToInteractions(modelName string, inputRawJSON []byte, stream bool) []byte { - out, _ := convertGeminiRequestToInteractions(modelName, inputRawJSON, stream) - return out +func ConvertGeminiRequestToInteractions(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { + return convertGeminiRequestToInteractions(modelName, inputRawJSON, stream) + } // convertGeminiRequestToInteractions also reports a user turn that was left empty diff --git a/internal/translator/gemini/interactions/interactions_gemini_common_test.go b/internal/translator/gemini/interactions/interactions_gemini_common_test.go index c5cf9f27ec2..76e9a699cc2 100644 --- a/internal/translator/gemini/interactions/interactions_gemini_common_test.go +++ b/internal/translator/gemini/interactions/interactions_gemini_common_test.go @@ -11,7 +11,7 @@ import ( ) func TestConvertInteractionsRequestToGeminiStringInput(t *testing.T) { - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","input":"hello"}`), false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","input":"hello"}`), false) if got := gjson.GetBytes(out, "contents.0.role").String(); got != "user" { t.Fatalf("role = %q, want user", got) } @@ -21,7 +21,7 @@ func TestConvertInteractionsRequestToGeminiStringInput(t *testing.T) { } func TestConvertInteractionsRequestToGeminiSystemAndGenerationConfig(t *testing.T) { - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","system_instruction":{"text":"be brief"},"generation_config":{"max_output_tokens":32,"top_p":0.8},"input":"hi"}`), false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","system_instruction":{"text":"be brief"},"generation_config":{"max_output_tokens":32,"top_p":0.8},"input":"hi"}`), false) if got := gjson.GetBytes(out, "systemInstruction.parts.0.text").String(); got != "be brief" { t.Fatalf("systemInstruction = %q, want be brief", got) } @@ -34,14 +34,14 @@ func TestConvertInteractionsRequestToGeminiSystemAndGenerationConfig(t *testing. } func TestConvertInteractionsRequestToGeminiStringSystemInstruction(t *testing.T) { - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","system_instruction":"be brief","input":"hi"}`), false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","system_instruction":"be brief","input":"hi"}`), false) if got := gjson.GetBytes(out, "systemInstruction.parts.0.text").String(); got != "be brief" { t.Fatalf("systemInstruction.parts.0.text = %q, want be brief. Output: %s", got, string(out)) } } func TestConvertGeminiRequestToInteractionsStringSystemInstruction(t *testing.T) { - out := ConvertGeminiRequestToInteractions("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","systemInstruction":{"parts":[{"text":"be brief"},{"text":"answer directly"}]},"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`), false) + out, _ := ConvertGeminiRequestToInteractions("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","systemInstruction":{"parts":[{"text":"be brief"},{"text":"answer directly"}]},"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`), false) sys := gjson.GetBytes(out, "system_instruction") if sys.Type != gjson.String { t.Fatalf("system_instruction type = %v, want string. Output: %s", sys.Type, string(out)) @@ -181,14 +181,14 @@ func TestConvertInteractionsResponseToGeminiNonStreamFunctionCall(t *testing.T) } func TestConvertInteractionsRequestToGeminiTurnInput(t *testing.T) { - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","input":{"role":"user","steps":[{"type":"user_input","content":[{"text":"hi"}]}]}}`), false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","input":{"role":"user","steps":[{"type":"user_input","content":[{"text":"hi"}]}]}}`), false) if got := gjson.GetBytes(out, "contents.0.parts.0.text").String(); got != "hi" { t.Fatalf("text = %q, want hi", got) } } func TestConvertInteractionsRequestToGeminiTurnArrayInput(t *testing.T) { - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","input":[{"role":"user","steps":[{"type":"user_input","content":[{"text":"hi"}]}]},{"role":"assistant","steps":[{"type":"model_output","content":[{"text":"ok"}]}]}]}`), false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","input":[{"role":"user","steps":[{"type":"user_input","content":[{"text":"hi"}]}]},{"role":"assistant","steps":[{"type":"model_output","content":[{"text":"ok"}]}]}]}`), false) if got := gjson.GetBytes(out, "contents.0.role").String(); got != "user" { t.Fatalf("contents.0.role = %q, want user. Output: %s", got, string(out)) } @@ -204,7 +204,7 @@ func TestConvertInteractionsRequestToGeminiTurnArrayInput(t *testing.T) { } func TestConvertInteractionsRequestToGeminiPreservesExpressibleTopLevelFields(t *testing.T) { - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","tool_choice":{"type":"function","function":{"name":"lookup"}},"response_modalities":["text","image"],"service_tier":"priority","input":"hi"}`), false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","tool_choice":{"type":"function","function":{"name":"lookup"}},"response_modalities":["text","image"],"service_tier":"priority","input":"hi"}`), false) if got := gjson.GetBytes(out, "toolConfig.functionCallingConfig.mode").String(); got != "ANY" { t.Fatalf("toolConfig.functionCallingConfig.mode = %q, want ANY. Output: %s", got, string(out)) } @@ -223,7 +223,7 @@ func TestConvertInteractionsRequestToGeminiPreservesExpressibleTopLevelFields(t } func TestConvertInteractionsRequestToGeminiContentInput(t *testing.T) { - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","input":{"role":"user","parts":[{"text":"hi"}]}}`), false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","input":{"role":"user","parts":[{"text":"hi"}]}}`), false) if got := gjson.GetBytes(out, "contents.0.role").String(); got != "user" { t.Fatalf("contents.0.role = %q, want user", got) } @@ -233,7 +233,7 @@ func TestConvertInteractionsRequestToGeminiContentInput(t *testing.T) { } func TestConvertInteractionsRequestToGeminiContentArrayInput(t *testing.T) { - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","input":[{"role":"user","parts":[{"text":"hi"}]},{"role":"assistant","parts":[{"text":"ok"}]}]}`), false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","input":[{"role":"user","parts":[{"text":"hi"}]},{"role":"assistant","parts":[{"text":"ok"}]}]}`), false) if got := gjson.GetBytes(out, "contents.0.role").String(); got != "user" { t.Fatalf("contents.0.role = %q, want user", got) } @@ -462,7 +462,7 @@ func TestConvertGeminiResponseToInteractionsStreamCompletesOnDoneWithoutUsage(t } func TestConvertInteractionsRequestToGeminiImageContent(t *testing.T) { - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","input":[{"type":"user_input","content":[{"type":"image","mime_type":"image/png","data":"aGVsbG8="}]}]}`), false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","input":[{"type":"user_input","content":[{"type":"image","mime_type":"image/png","data":"aGVsbG8="}]}]}`), false) if got := gjson.GetBytes(out, "contents.0.parts.0.inlineData.mimeType").String(); got != "image/png" { t.Fatalf("mimeType = %q, want image/png", got) } @@ -472,7 +472,7 @@ func TestConvertInteractionsRequestToGeminiImageContent(t *testing.T) { } func TestConvertInteractionsRequestToGeminiModelOutputTypedContent(t *testing.T) { - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","input":[{"type":"model_output","content":[{"type":"image","mime_type":"image/png","data":"aGVsbG8="},{"type":"document","mime_type":"application/pdf","file_uri":"gs://bucket/doc.pdf"}]}]}`), false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","input":[{"type":"model_output","content":[{"type":"image","mime_type":"image/png","data":"aGVsbG8="},{"type":"document","mime_type":"application/pdf","file_uri":"gs://bucket/doc.pdf"}]}]}`), false) if got := gjson.GetBytes(out, "contents.0.role").String(); got != "model" { t.Fatalf("contents.0.role = %q, want model. Output: %s", got, string(out)) } @@ -491,7 +491,7 @@ func TestConvertInteractionsRequestToGeminiModelOutputTypedContent(t *testing.T) } func TestConvertInteractionsRequestToGeminiThoughtTypedContent(t *testing.T) { - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","input":[{"type":"thought","content":[{"type":"text","text":"thinking"},{"type":"audio","mime_type":"audio/wav","data":"UklGRg=="}]}]}`), false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","input":[{"type":"thought","content":[{"type":"text","text":"thinking"},{"type":"audio","mime_type":"audio/wav","data":"UklGRg=="}]}]}`), false) if got := gjson.GetBytes(out, "contents.0.parts.0.text").String(); got != "thinking" { t.Fatalf("thought text = %q, want thinking. Output: %s", got, string(out)) } @@ -511,7 +511,7 @@ func TestConvertGeminiResponseToInteractionsNonStreamImage(t *testing.T) { } func TestConvertInteractionsRequestToGeminiGenerationConfigAllFields(t *testing.T) { - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","generation_config":{"max_output_tokens":32,"response_schema":{"type":"object"},"seed":42,"thinking_config":{"thinking_budget":1024,"include_thoughts":true},"context_window_compression":{"trigger_tokens":1000}},"input":"hi"}`), false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","generation_config":{"max_output_tokens":32,"response_schema":{"type":"object"},"seed":42,"thinking_config":{"thinking_budget":1024,"include_thoughts":true},"context_window_compression":{"trigger_tokens":1000}},"input":"hi"}`), false) if got := gjson.GetBytes(out, "generationConfig.maxOutputTokens").Int(); got != 32 { t.Fatalf("maxOutputTokens = %d, want 32", got) } @@ -533,7 +533,7 @@ func TestConvertInteractionsRequestToGeminiGenerationConfigAllFields(t *testing. } func TestConvertInteractionsRequestToGeminiGenerationConfigProtocolFields(t *testing.T) { - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","generation_config":{"tool_choice":"auto","thinking_level":"high","thinking_summaries":"auto"},"stream":true,"input":"hi"}`), true) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","generation_config":{"tool_choice":"auto","thinking_level":"high","thinking_summaries":"auto"},"stream":true,"input":"hi"}`), true) for _, path := range []string{ "stream", "generationConfig.toolChoice", @@ -556,7 +556,7 @@ func TestConvertInteractionsRequestToGeminiGenerationConfigProtocolFields(t *tes } func TestConvertGeminiRequestToInteractionsFunctionCall(t *testing.T) { - out := ConvertGeminiRequestToInteractions("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","contents":[{"role":"model","parts":[{"functionCall":{"name":"lookup","args":{"q":"x"}}}]},{"role":"user","parts":[{"functionResponse":{"name":"lookup","response":{"ok":true}}}]}]}`), false) + out, _ := ConvertGeminiRequestToInteractions("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","contents":[{"role":"model","parts":[{"functionCall":{"name":"lookup","args":{"q":"x"}}}]},{"role":"user","parts":[{"functionResponse":{"name":"lookup","response":{"ok":true}}}]}]}`), false) if got := gjson.GetBytes(out, "input.0.type").String(); got != "function_call" { t.Fatalf("input.0.type = %q, want function_call", got) } @@ -569,7 +569,7 @@ func TestConvertGeminiRequestToInteractionsFunctionCall(t *testing.T) { } func TestConvertGeminiRequestToInteractionsTextContentType(t *testing.T) { - out := ConvertGeminiRequestToInteractions("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","contents":[{"role":"user","parts":[{"text":"hi"}]}]}`), false) + out, _ := ConvertGeminiRequestToInteractions("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","contents":[{"role":"user","parts":[{"text":"hi"}]}]}`), false) if got := gjson.GetBytes(out, "input.0.content.0.type").String(); got != "text" { t.Fatalf("content.0.type = %q, want text. Output: %s", got, string(out)) } @@ -579,7 +579,7 @@ func TestConvertGeminiRequestToInteractionsTextContentType(t *testing.T) { } func TestConvertGeminiRequestToInteractionsMultimodal(t *testing.T) { - out := ConvertGeminiRequestToInteractions("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","contents":[{"role":"user","parts":[{"inlineData":{"mimeType":"audio/wav","data":"aGVsbG8="}}]}]}`), false) + out, _ := ConvertGeminiRequestToInteractions("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","contents":[{"role":"user","parts":[{"inlineData":{"mimeType":"audio/wav","data":"aGVsbG8="}}]}]}`), false) if got := gjson.GetBytes(out, "input.0.type").String(); got != "user_input" { t.Fatalf("input.0.type = %q, want user_input", got) } @@ -592,14 +592,14 @@ func TestConvertGeminiRequestToInteractionsMultimodal(t *testing.T) { } func TestConvertGeminiRequestToInteractionsThought(t *testing.T) { - out := ConvertGeminiRequestToInteractions("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","contents":[{"role":"model","parts":[{"text":"thinking","thought":true}]}]}`), false) + out, _ := ConvertGeminiRequestToInteractions("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","contents":[{"role":"model","parts":[{"text":"thinking","thought":true}]}]}`), false) if got := gjson.GetBytes(out, "input.0.type").String(); got != "thought" { t.Fatalf("input.0.type = %q, want thought", got) } } func TestConvertInteractionsRequestToGeminiTurnWithModelRole(t *testing.T) { - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","input":{"role":"model","steps":[{"type":"user_input","content":[{"text":"hi"}]},{"type":"model_output","content":[{"text":"ok"}]}]}}`), false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","input":{"role":"model","steps":[{"type":"user_input","content":[{"text":"hi"}]},{"type":"model_output","content":[{"text":"ok"}]}]}}`), false) if got := gjson.GetBytes(out, "contents.0.role").String(); got != "model" { t.Fatalf("contents.0.role = %q, want model", got) } @@ -609,7 +609,7 @@ func TestConvertInteractionsRequestToGeminiTurnWithModelRole(t *testing.T) { } func TestConvertInteractionsRequestToGeminiGenerationConfigPreservesLargeIntegers(t *testing.T) { - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","generation_config":{"max_output_tokens":32,"large_identity":9223372036854775807},"input":"hi"}`), false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","generation_config":{"max_output_tokens":32,"large_identity":9223372036854775807},"input":"hi"}`), false) if got := gjson.GetBytes(out, "generationConfig.maxOutputTokens").Int(); got != 32 { t.Fatalf("maxOutputTokens = %d, want 32", got) } @@ -619,7 +619,7 @@ func TestConvertInteractionsRequestToGeminiGenerationConfigPreservesLargeInteger } func TestConvertInteractionsRequestToGeminiFunctionCallPreservesCallID(t *testing.T) { - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","input":[{"type":"function_call","name":"lookup","call_id":"call_1","arguments":{"q":"x"}}]}`), false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","input":[{"type":"function_call","name":"lookup","call_id":"call_1","arguments":{"q":"x"}}]}`), false) if got := gjson.GetBytes(out, "contents.0.parts.0.functionCall.id").String(); got != "call_1" { t.Fatalf("functionCall.id = %q, want call_1", got) } @@ -632,7 +632,7 @@ func TestConvertInteractionsRequestToGeminiFunctionCallPreservesCallID(t *testin } func TestConvertInteractionsRequestToGeminiFunctionResultPreservesCallID(t *testing.T) { - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","input":[{"type":"function_result","name":"lookup","call_id":"call_1","result":{"ok":true}}]}`), false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","input":[{"type":"function_result","name":"lookup","call_id":"call_1","result":{"ok":true}}]}`), false) if got := gjson.GetBytes(out, "contents.0.parts.0.functionResponse.id").String(); got != "call_1" { t.Fatalf("functionResponse.id = %q, want call_1", got) } @@ -642,7 +642,7 @@ func TestConvertInteractionsRequestToGeminiFunctionResultPreservesCallID(t *test } func TestConvertGeminiRequestToInteractionsFunctionCallPreservesID(t *testing.T) { - out := ConvertGeminiRequestToInteractions("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","contents":[{"role":"model","parts":[{"functionCall":{"name":"lookup","id":"call_1","args":{"q":"x"}}}]},{"role":"user","parts":[{"functionResponse":{"name":"lookup","id":"call_1","response":{"ok":true}}}]}]}`), false) + out, _ := ConvertGeminiRequestToInteractions("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","contents":[{"role":"model","parts":[{"functionCall":{"name":"lookup","id":"call_1","args":{"q":"x"}}}]},{"role":"user","parts":[{"functionResponse":{"name":"lookup","id":"call_1","response":{"ok":true}}}]}]}`), false) if got := gjson.GetBytes(out, "input.0.call_id").String(); got != "call_1" { t.Fatalf("input.0.call_id = %q, want call_1", got) } @@ -652,7 +652,7 @@ func TestConvertGeminiRequestToInteractionsFunctionCallPreservesID(t *testing.T) } func TestConvertGeminiRequestToInteractionsFunctionCallPreservesCallID(t *testing.T) { - out := ConvertGeminiRequestToInteractions("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","contents":[{"role":"model","parts":[{"functionCall":{"name":"lookup","call_id":"call_request_1","args":{"q":"x"}}}]},{"role":"user","parts":[{"functionResponse":{"name":"lookup","call_id":"call_request_1","response":{"ok":true}}}]}]}`), false) + out, _ := ConvertGeminiRequestToInteractions("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","contents":[{"role":"model","parts":[{"functionCall":{"name":"lookup","call_id":"call_request_1","args":{"q":"x"}}}]},{"role":"user","parts":[{"functionResponse":{"name":"lookup","call_id":"call_request_1","response":{"ok":true}}}]}]}`), false) if got := gjson.GetBytes(out, "input.0.call_id").String(); got != "call_request_1" { t.Fatalf("input.0.call_id = %q, want call_request_1", got) } @@ -662,7 +662,7 @@ func TestConvertGeminiRequestToInteractionsFunctionCallPreservesCallID(t *testin } func TestConvertGeminiRequestToInteractionsGenerationConfig(t *testing.T) { - out := ConvertGeminiRequestToInteractions("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","generationConfig":{"maxOutputTokens":32,"topP":0.8,"thinkingConfig":{"thinkingBudget":1024}},"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`), false) + out, _ := ConvertGeminiRequestToInteractions("gemini-3.5-flash", []byte(`{"model":"gemini-3.5-flash","generationConfig":{"maxOutputTokens":32,"topP":0.8,"thinkingConfig":{"thinkingBudget":1024}},"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`), false) if got := gjson.GetBytes(out, "generation_config.max_output_tokens").Int(); got != 32 { t.Fatalf("max_output_tokens = %d, want 32", got) } @@ -764,7 +764,7 @@ func TestConvertInteractionsRequestToGeminiBuiltinTools(t *testing.T) { "input":"read url", "tools":[{"type":"url_context"}] }`) - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", inputJSON, false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", inputJSON, false) tools := gjson.GetBytes(out, "tools").Array() if len(tools) != 1 { t.Fatalf("expected 1 tool, got %d. Output: %s", len(tools), string(out)) @@ -783,7 +783,7 @@ func TestConvertInteractionsRequestToGeminiBuiltinTools(t *testing.T) { "input":"execute code", "tools":[{"type":"code_execution"}] }`) - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", inputJSON, false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", inputJSON, false) tools := gjson.GetBytes(out, "tools").Array() if len(tools) != 1 { t.Fatalf("expected 1 tool, got %d. Output: %s", len(tools), string(out)) @@ -802,7 +802,7 @@ func TestConvertInteractionsRequestToGeminiBuiltinTools(t *testing.T) { "input":"search web", "tools":[{"type":"google_search"}] }`) - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", inputJSON, false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", inputJSON, false) tools := gjson.GetBytes(out, "tools").Array() if len(tools) != 1 { t.Fatalf("expected 1 tool, got %d. Output: %s", len(tools), string(out)) @@ -821,7 +821,7 @@ func TestConvertInteractionsRequestToGeminiBuiltinTools(t *testing.T) { "contents":[{"role":"user","parts":[{"text":"hello"}]}], "tools":[{"urlContext":{}},{"codeExecution":{}},{"googleSearch":{}}] }`) - out := ConvertGeminiRequestToInteractions("gemini-3.5-flash", inputJSON, false) + out, _ := ConvertGeminiRequestToInteractions("gemini-3.5-flash", inputJSON, false) tools := gjson.GetBytes(out, "tools").Array() if len(tools) != 3 { t.Fatalf("expected 3 tools, got %d. Output: %s", len(tools), string(out)) @@ -843,7 +843,7 @@ func TestConvertInteractionsRequestToGeminiBuiltinTools(t *testing.T) { "contents":[{"role":"user","parts":[{"text":"hello"}]}], "tools":[{"googleSearch":{"mode":"search"}},{"codeExecution":{"sandbox":true}}] }`) - out := ConvertGeminiRequestToInteractions("gemini-3.5-flash", inputJSON, false) + out, _ := ConvertGeminiRequestToInteractions("gemini-3.5-flash", inputJSON, false) tools := gjson.GetBytes(out, "tools").Array() if len(tools) != 2 { t.Fatalf("expected 2 tools, got %d. Output: %s", len(tools), string(out)) @@ -866,7 +866,7 @@ func TestConvertInteractionsRequestToGeminiBuiltinTools(t *testing.T) { {"type":"web_search","google_search":{"mode":"search"}} ] }`) - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", inputJSON, false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", inputJSON, false) tools := gjson.GetBytes(out, "tools").Array() if len(tools) != 3 { t.Fatalf("expected 3 tools, got %d. Output: %s", len(tools), string(out)) @@ -888,7 +888,7 @@ func TestConvertInteractionsRequestToGeminiBuiltinTools(t *testing.T) { "input":"native composite tools", "tools":[{"googleSearch":{},"urlContext":{}}] }`) - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", inputJSON, false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", inputJSON, false) tools := gjson.GetBytes(out, "tools").Array() if len(tools) != 1 { t.Fatalf("expected 1 tool node, got %d. Output: %s", len(tools), string(out)) @@ -906,7 +906,7 @@ func TestConvertInteractionsRequestToGeminiBuiltinTools(t *testing.T) { "contents":[{"role":"user","parts":[{"text":"hello"}]}], "tools":[{"googleSearch":{},"urlContext":{}}] }`) - interactionsOut := ConvertGeminiRequestToInteractions("gemini-3.5-flash", geminiReq, false) + interactionsOut, _ := ConvertGeminiRequestToInteractions("gemini-3.5-flash", geminiReq, false) interTools := gjson.GetBytes(interactionsOut, "tools").Array() if len(interTools) != 2 { t.Fatalf("expected 2 converted tools from composite, got %d. Output: %s", len(interTools), string(interactionsOut)) @@ -932,7 +932,7 @@ func TestConvertInteractionsRequestToGeminiBuiltinTools(t *testing.T) { "input":"unrecognized tool", "tools":[{"type":"file_search","file_search":{"max_results":5}}] }`) - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", inputJSON, false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", inputJSON, false) tools := gjson.GetBytes(out, "tools").Array() if len(tools) != 1 { t.Fatalf("expected 1 tool retained, got %d. Output: %s", len(tools), string(out)) @@ -959,7 +959,7 @@ func TestConvertInteractionsRequestToGemini_FunctionResponseJSONRef(t *testing.T } ] }`) - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", inputJSON, false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", inputJSON, false) val := gjson.GetBytes(out, "contents.0.parts.0.functionResponse.response.result") if val.Type != gjson.String { t.Fatalf("expected functionResponse.response.result to be string, got %s (raw: %s)", val.Type, val.Raw) @@ -1037,7 +1037,7 @@ func TestConvertInteractionsRequestToGemini_ParallelToolCallsHistory(t *testing. {"type": "function_result", "name": "f3", "call_id": "c3", "result": {"r": 3}} ] }`) - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", inputJSON, false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", inputJSON, false) contents := gjson.GetBytes(out, "contents").Array() if len(contents) != 3 { t.Fatalf("expected 3 contents (user, model, user), got %d: %s", len(contents), string(out)) @@ -1066,7 +1066,7 @@ func TestConvertInteractionsRequestToGemini_ThoughtSummaryAndSignature(t *testin {"type": "model_output", "content": [{"type": "text", "text": "my answer"}]} ] }`) - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", inputJSON, false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", inputJSON, false) contents := gjson.GetBytes(out, "contents").Array() if len(contents) != 1 { t.Fatalf("expected 1 model content, got %d: %s", len(contents), string(out)) @@ -1146,7 +1146,7 @@ func TestConvertGeminiRequestToInteractions_SignedFunctionCallPreserved(t *testi } ] }`) - out := ConvertGeminiRequestToInteractions("gemini-3.5-flash", geminiReq, false) + out, _ := ConvertGeminiRequestToInteractions("gemini-3.5-flash", geminiReq, false) steps := gjson.GetBytes(out, "input").Array() if len(steps) != 2 { t.Fatalf("expected 2 steps (thought, function_call), got %d: %s", len(steps), string(out)) @@ -1170,7 +1170,7 @@ func TestConvertInteractionsRequestToGemini_InterleavedModelTurnSteps(t *testing {"type": "function_result", "name": "f2", "call_id": "c2", "result": {"r": 2}} ] }`) - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", inputJSON, false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", inputJSON, false) contents := gjson.GetBytes(out, "contents").Array() if len(contents) != 2 { t.Fatalf("expected 2 contents (model, user), got %d: %s", len(contents), string(out)) @@ -1213,7 +1213,7 @@ func TestConvertInteractionsRequestToGemini_ResponseToRequestRoundTrip(t *testin } turn2Input += `,{"type":"function_result","name":"lookup","call_id":"call_1","result":{"ok":true}},{"type":"function_result","name":"search","call_id":"call_2","result":{"found":true}}]}` - reqOut := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(turn2Input), false) + reqOut, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(turn2Input), false) contents := gjson.GetBytes(reqOut, "contents").Array() if len(contents) != 3 { t.Fatalf("expected 3 contents (user, model, user), got %d: %s", len(contents), string(reqOut)) @@ -1239,7 +1239,7 @@ func TestConvertInteractionsRequestToGemini_MultipleSignaturesPreserved(t *testi {"type": "function_call", "name": "f1", "call_id": "c1", "arguments": {}} ] }`) - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", inputJSON, false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", inputJSON, false) contents := gjson.GetBytes(out, "contents").Array() if len(contents) != 1 { t.Fatalf("expected 1 model content, got %d: %s", len(contents), string(out)) @@ -1275,7 +1275,7 @@ func TestConvertInteractionsRequestToGemini_TrailingSignatureRoundTrip(t *testin steps := gjson.GetBytes(respOut, "steps").Raw turn2Input := `{"model":"gemini-3.5-flash","input":` + steps + `}` - reqOut := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(turn2Input), false) + reqOut, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", []byte(turn2Input), false) contents := gjson.GetBytes(reqOut, "contents").Array() if len(contents) != 1 { t.Fatalf("expected 1 model content, got %d: %s", len(contents), string(reqOut)) @@ -1304,7 +1304,7 @@ func TestConvertInteractionsRequestToGemini_ExplicitSignatureClearsPending(t *te {"type": "function_call", "name": "f2", "call_id": "c2", "arguments": {}} ] }`) - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", inputJSON, false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", inputJSON, false) contents := gjson.GetBytes(out, "contents").Array() if len(contents) != 1 { t.Fatalf("expected 1 model content, got %d: %s", len(contents), string(out)) diff --git a/internal/translator/gemini/interactions/interactions_gemini_file_data_test.go b/internal/translator/gemini/interactions/interactions_gemini_file_data_test.go index 64ed1c0afaa..29629b02eb0 100644 --- a/internal/translator/gemini/interactions/interactions_gemini_file_data_test.go +++ b/internal/translator/gemini/interactions/interactions_gemini_file_data_test.go @@ -9,7 +9,7 @@ import ( func TestConvertInteractionsRequestToGeminiNormalizesOpenAIFileDataURL(t *testing.T) { input := []byte(`{"model":"gemini-3.5-flash","input":[{"type":"user_input","content":[{"type":"file","file":{"filename":"test.pdf","file_data":"data:application/pdf;base64,JVBERi0xLjQK"}}]}]}`) - out := ConvertInteractionsRequestToGemini("gemini-3.5-flash", input, false) + out, _ := ConvertInteractionsRequestToGemini("gemini-3.5-flash", input, false) inlineData := gjson.GetBytes(out, "contents.0.parts.0.inlineData") if got := inlineData.Get("mimeType").String(); got != "application/pdf" { t.Fatalf("inlineData.mimeType = %q, want application/pdf. Output: %s", got, out) diff --git a/internal/translator/gemini/interactions/interactions_gemini_response.go b/internal/translator/gemini/interactions/interactions_gemini_response.go index d934f3d69d5..202ea0e1e54 100644 --- a/internal/translator/gemini/interactions/interactions_gemini_response.go +++ b/internal/translator/gemini/interactions/interactions_gemini_response.go @@ -67,10 +67,10 @@ func ConvertInteractionsResponseToGeminiNonStream(_ context.Context, modelName s return out } -func ConvertInteractionsRequestToInteractions(modelName string, inputRawJSON []byte, stream bool) []byte { +func ConvertInteractionsRequestToInteractions(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { _ = modelName _ = stream - return inputRawJSON + return inputRawJSON, nil } func ConvertInteractionsResponsePassthrough(_ context.Context, _ string, _, _, rawJSON []byte, _ *any) [][]byte { diff --git a/internal/translator/gemini/interactions/interactions_gemini_uri_test.go b/internal/translator/gemini/interactions/interactions_gemini_uri_test.go index 37de80b36b6..8c13564b7ec 100644 --- a/internal/translator/gemini/interactions/interactions_gemini_uri_test.go +++ b/internal/translator/gemini/interactions/interactions_gemini_uri_test.go @@ -150,7 +150,7 @@ func TestInteractionsToGeminiNeighbouringStepKeepsTheTurnAlive(t *testing.T) { func TestInteractionsToGeminiExportedWrapperKeepsAJSONBody(t *testing.T) { input := []byte(`{"model":"m","input":[` + interactionsGeminiHistory + `,{"type":"user_input","content":[{"type":"audio","mime_type":"audio/wav"}]}]}`) - if body := ConvertInteractionsRequestToGemini("m", input, false); !gjson.ValidBytes(body) { + if body, _ := ConvertInteractionsRequestToGemini("m", input, false); !gjson.ValidBytes(body) { t.Fatalf("body is not JSON: %q", body) } } diff --git a/internal/translator/gemini/interactions/interactions_gemini_user_turn_test.go b/internal/translator/gemini/interactions/interactions_gemini_user_turn_test.go index 92831e329b8..38006abb61a 100644 --- a/internal/translator/gemini/interactions/interactions_gemini_user_turn_test.go +++ b/internal/translator/gemini/interactions/interactions_gemini_user_turn_test.go @@ -162,7 +162,7 @@ func TestGeminiToInteractionsModelFileDataWithoutURIIsNotARefusal(t *testing.T) func TestGeminiToInteractionsExportedWrapperKeepsAJSONBody(t *testing.T) { input := []byte(`{"model":"m","contents":[{"role":"user","parts":[{"fileData":{"mimeType":"application/pdf"}}]}]}`) - if body := ConvertGeminiRequestToInteractions("m", input, false); !gjson.ValidBytes(body) { + if body, _ := ConvertGeminiRequestToInteractions("m", input, false); !gjson.ValidBytes(body) { t.Fatalf("body is not JSON: %q", body) } } diff --git a/internal/translator/gemini/openai/chat-completions/gemini_openai_file_data_test.go b/internal/translator/gemini/openai/chat-completions/gemini_openai_file_data_test.go index 8c5296850b8..4259553d272 100644 --- a/internal/translator/gemini/openai/chat-completions/gemini_openai_file_data_test.go +++ b/internal/translator/gemini/openai/chat-completions/gemini_openai_file_data_test.go @@ -9,7 +9,7 @@ import ( func TestConvertOpenAIRequestToGeminiNormalizesFileDataURL(t *testing.T) { input := []byte(`{"model":"gemini-2.5-pro","messages":[{"role":"user","content":[{"type":"file","file":{"filename":"test.pdf","file_data":"data:application/pdf;base64,JVBERi0xLjQK"}}]}]}`) - out := ConvertOpenAIRequestToGemini("gemini-2.5-pro", input, false) + out, _ := ConvertOpenAIRequestToGemini("gemini-2.5-pro", input, false) inlineData := gjson.GetBytes(out, "contents.0.parts.0.inlineData") if got := inlineData.Get("mime_type").String(); got != "application/pdf" { t.Fatalf("inlineData.mime_type = %q, want application/pdf. Output: %s", got, out) diff --git a/internal/translator/gemini/openai/chat-completions/gemini_openai_request.go b/internal/translator/gemini/openai/chat-completions/gemini_openai_request.go index 211df47a18e..c81c5224316 100644 --- a/internal/translator/gemini/openai/chat-completions/gemini_openai_request.go +++ b/internal/translator/gemini/openai/chat-completions/gemini_openai_request.go @@ -26,9 +26,9 @@ const geminiFunctionThoughtSignature = "skip_thought_signature_validator" // // Returns: // - []byte: The transformed request data in Gemini API format -func ConvertOpenAIRequestToGemini(modelName string, inputRawJSON []byte, stream bool) []byte { - body, _ := convertOpenAIRequestToGemini(modelName, inputRawJSON, stream) - return body +func ConvertOpenAIRequestToGemini(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { + return convertOpenAIRequestToGemini(modelName, inputRawJSON, stream) + } // convertOpenAIRequestToGemini also reports a file part Gemini cannot receive diff --git a/internal/translator/gemini/openai/chat-completions/gemini_openai_request_test.go b/internal/translator/gemini/openai/chat-completions/gemini_openai_request_test.go index f87df4c403e..7026fa72488 100644 --- a/internal/translator/gemini/openai/chat-completions/gemini_openai_request_test.go +++ b/internal/translator/gemini/openai/chat-completions/gemini_openai_request_test.go @@ -18,7 +18,7 @@ func TestConvertOpenAIRequestToGemini_StripsTrailingAssistantPrefill(t *testing. ] }` - result := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) contents := resultJSON.Get("contents").Array() @@ -44,7 +44,7 @@ func TestConvertOpenAIRequestToGeminiPreservesInputAudio(t *testing.T) { ] }` - result := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) parts := resultJSON.Get("contents.0.parts").Array() @@ -76,7 +76,7 @@ func TestConvertOpenAIRequestToGeminiPreservesVideoURL(t *testing.T) { ] }` - result := ConvertOpenAIRequestToGemini("gemini-3-flash", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToGemini("gemini-3-flash", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) parts := resultJSON.Get("contents.0.parts").Array() @@ -119,7 +119,7 @@ func TestConvertOpenAIRequestToGeminiSkipsEmptyTextPartsWithoutNulls(t *testing. ] }` - result := ConvertOpenAIRequestToGemini("gemini-3-flash", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToGemini("gemini-3-flash", []byte(inputJSON), false) userParts := gjson.GetBytes(result, "contents.0.parts").Array() if len(userParts) != 1 { t.Fatalf("user parts length = %d, want 1. Output: %s", len(userParts), result) @@ -153,7 +153,7 @@ func TestConvertOpenAIRequestToGeminiPreservesReasoningContent(t *testing.T) { ] }` - result := ConvertOpenAIRequestToGemini("gemini-3-flash", []byte(inputJSON), true) + result, _ := ConvertOpenAIRequestToGemini("gemini-3-flash", []byte(inputJSON), true) contents := gjson.GetBytes(result, "contents").Array() if len(contents) != 3 { t.Fatalf("contents length = %d, want 3. Output: %s", len(contents), result) @@ -184,7 +184,7 @@ func TestConvertOpenAIRequestToGeminiPreservesReasoningBeforeVisibleContentAndTo ] }` - result := ConvertOpenAIRequestToGemini("gemini-3-flash", []byte(inputJSON), true) + result, _ := ConvertOpenAIRequestToGemini("gemini-3-flash", []byte(inputJSON), true) contents := gjson.GetBytes(result, "contents").Array() if len(contents) != 4 { t.Fatalf("contents length = %d, want 4. Output: %s", len(contents), result) @@ -223,7 +223,7 @@ func TestConvertOpenAIRequestToGeminiSkipsEmptyAssistantMessages(t *testing.T) { ] }` - result := ConvertOpenAIRequestToGemini("gemini-3-flash", []byte(inputJSON), true) + result, _ := ConvertOpenAIRequestToGemini("gemini-3-flash", []byte(inputJSON), true) contents := gjson.GetBytes(result, "contents").Array() if len(contents) != 2 { t.Fatalf("contents length = %d, want 2. Output: %s", len(contents), result) @@ -242,7 +242,7 @@ func TestConvertOpenAIRequestToGemini_MidSessionDeveloperMessageDoesNotMutateSys ] }` - result := ConvertOpenAIRequestToGemini("gemini-3-flash", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToGemini("gemini-3-flash", []byte(inputJSON), false) output := gjson.ParseBytes(result) // systemInstruction must contain only original system prompt @@ -286,7 +286,7 @@ func TestConvertOpenAIRequestToGemini_MidSessionSystemReminderEnvelope(t *testin ] }` - result := ConvertOpenAIRequestToGemini("gemini-3-flash", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToGemini("gemini-3-flash", []byte(inputJSON), false) output := gjson.ParseBytes(result) contents := output.Get("contents").Array() @@ -322,8 +322,8 @@ func TestConvertOpenAIRequestToGemini_MidSessionTransientSystemInstructionPreser ] }` - outWith := ConvertOpenAIRequestToGemini("gemini-3-flash", []byte(turnWithTransient), false) - outWithout := ConvertOpenAIRequestToGemini("gemini-3-flash", []byte(turnWithoutTransient), false) + outWith, _ := ConvertOpenAIRequestToGemini("gemini-3-flash", []byte(turnWithTransient), false) + outWithout, _ := ConvertOpenAIRequestToGemini("gemini-3-flash", []byte(turnWithoutTransient), false) contentsWith := gjson.GetBytes(outWith, "contents").Array() contentsWithout := gjson.GetBytes(outWithout, "contents").Array() @@ -364,7 +364,7 @@ func TestConvertOpenAIRequestToGemini_MidSessionSystemReminderObjectAndArrayCont ] }` - result := ConvertOpenAIRequestToGemini("gemini-3-flash", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToGemini("gemini-3-flash", []byte(inputJSON), false) output := gjson.ParseBytes(result) contents := output.Get("contents").Array() @@ -406,7 +406,7 @@ func TestConvertOpenAIRequestToGeminiMapsMaxTokens(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - out := ConvertOpenAIRequestToGemini("gemini-2.0-flash", []byte(tt.body), false) + out, _ := ConvertOpenAIRequestToGemini("gemini-2.0-flash", []byte(tt.body), false) if got := gjson.GetBytes(out, "generationConfig.maxOutputTokens").Int(); got != tt.want { t.Fatalf("generationConfig.maxOutputTokens = %d, want %d. Output: %s", got, tt.want, out) } @@ -436,7 +436,7 @@ func TestConvertOpenAIRequestToGeminiCleansToolSchemaRequiredFields(t *testing.T }] }` - output := ConvertOpenAIRequestToGemini("gemini-2.0-flash", []byte(inputJSON), false) + output, _ := ConvertOpenAIRequestToGemini("gemini-2.0-flash", []byte(inputJSON), false) schema := gjson.GetBytes(output, "tools.0.functionDeclarations.0.parametersJsonSchema") if !schema.Exists() { @@ -480,7 +480,7 @@ func TestConvertOpenAIRequestToGeminiResponseFormatJSONSchema(t *testing.T) { } }` - output := ConvertOpenAIRequestToGemini("gemini-3.1-flash-lite", []byte(inputJSON), false) + output, _ := ConvertOpenAIRequestToGemini("gemini-3.1-flash-lite", []byte(inputJSON), false) generationConfig := gjson.GetBytes(output, "generationConfig") if got := generationConfig.Get("responseMimeType").String(); got != "application/json" { @@ -509,7 +509,7 @@ func TestConvertOpenAIRequestToGeminiResponseFormatJSONObject(t *testing.T) { "response_format": {"type": "json_object"} }` - output := ConvertOpenAIRequestToGemini("gemini-3.1-flash-lite", []byte(inputJSON), false) + output, _ := ConvertOpenAIRequestToGemini("gemini-3.1-flash-lite", []byte(inputJSON), false) generationConfig := gjson.GetBytes(output, "generationConfig") if got := generationConfig.Get("responseMimeType").String(); got != "application/json" { @@ -530,7 +530,7 @@ func TestConvertOpenAIRequestToGeminiResponseFormatJSONSchemaWithoutSchema(t *te "response_format": {"type": "json_schema", "json_schema": {"name": "response"}} }` - output := ConvertOpenAIRequestToGemini("gemini-3.1-flash-lite", []byte(inputJSON), false) + output, _ := ConvertOpenAIRequestToGemini("gemini-3.1-flash-lite", []byte(inputJSON), false) generationConfig := gjson.GetBytes(output, "generationConfig") if got := generationConfig.Get("responseMimeType").String(); got != "application/json" { @@ -558,7 +558,7 @@ func TestConvertOpenAIRequestToGeminiResponseFormatNoOp(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - output := ConvertOpenAIRequestToGemini("gemini-3.1-flash-lite", []byte(tt.body), false) + output, _ := ConvertOpenAIRequestToGemini("gemini-3.1-flash-lite", []byte(tt.body), false) generationConfig := gjson.GetBytes(output, "generationConfig") if generationConfig.Get("responseMimeType").Exists() { t.Fatalf("responseMimeType should not be set. Output: %s", output) @@ -600,7 +600,7 @@ func TestConvertOpenAIRequestToGemini_MultiTurnRepeatedToolCallID_Issue5933(t *t ] }` - out := ConvertOpenAIRequestToGemini("gemini-3-flash", []byte(inputJSON), false) + out, _ := ConvertOpenAIRequestToGemini("gemini-3-flash", []byte(inputJSON), false) // In Turn 1 (contents[1] = model functionCall, contents[2] = user functionResponse): // functionCall.name must be "glob", and functionResponse.name must be "glob". @@ -657,7 +657,7 @@ func TestConvertOpenAIRequestToGemini_ParallelAndOutOfOrderToolResponses(t *test ] }` - out := ConvertOpenAIRequestToGemini("gemini-3-flash", []byte(inputJSON), false) + out, _ := ConvertOpenAIRequestToGemini("gemini-3-flash", []byte(inputJSON), false) resp0Name := gjson.GetBytes(out, "contents.2.parts.0.functionResponse.name").String() resp0Result := gjson.GetBytes(out, "contents.2.parts.0.functionResponse.response.result").String() @@ -686,7 +686,7 @@ func TestConvertOpenAIRequestToGemini_ToolChoice(t *testing.T) { {"type": "function", "function": {"name": "tool_a", "parameters": {"type": "object", "properties": {}}}} ] }` - result := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) mode := gjson.GetBytes(result, "toolConfig.functionCallingConfig.mode").String() allowed := gjson.GetBytes(result, "toolConfig.functionCallingConfig.allowedFunctionNames").Array() if mode != "ANY" { @@ -706,7 +706,7 @@ func TestConvertOpenAIRequestToGemini_ToolChoice(t *testing.T) { {"type": "function", "function": {"name": "tool_a", "parameters": {"type": "object", "properties": {}}}} ] }` - result := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) mode := gjson.GetBytes(result, "toolConfig.functionCallingConfig.mode").String() if mode != "NONE" { t.Fatalf("expected toolConfig.functionCallingConfig.mode = 'NONE', got %q. Output: %s", mode, result) @@ -722,7 +722,7 @@ func TestConvertOpenAIRequestToGemini_ToolChoice(t *testing.T) { {"type": "function", "function": {"name": "tool_a", "parameters": {"type": "object", "properties": {}}}} ] }` - result := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) mode := gjson.GetBytes(result, "toolConfig.functionCallingConfig.mode").String() if mode != "AUTO" { t.Fatalf("expected toolConfig.functionCallingConfig.mode = 'AUTO', got %q. Output: %s", mode, result) @@ -738,7 +738,7 @@ func TestConvertOpenAIRequestToGemini_ToolChoice(t *testing.T) { {"type": "function", "function": {"name": "tool_a", "parameters": {"type": "object", "properties": {}}}} ] }` - result := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) mode := gjson.GetBytes(result, "toolConfig.functionCallingConfig.mode").String() if mode != "ANY" { t.Fatalf("expected toolConfig.functionCallingConfig.mode = 'ANY', got %q. Output: %s", mode, result) @@ -755,7 +755,7 @@ func TestConvertOpenAIRequestToGemini_ToolChoice(t *testing.T) { {"type": "function", "function": {"name": "tool_a", "parameters": {"type": "object", "properties": {}}}} ] }` - result := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) mode := gjson.GetBytes(result, "toolConfig.functionCallingConfig.mode").String() if mode != "NONE" { t.Fatalf("expected toolConfig.functionCallingConfig.mode = 'NONE', got %q. Output: %s", mode, result) @@ -772,7 +772,7 @@ func TestConvertOpenAIRequestToGemini_ToolChoice(t *testing.T) { {"type": "function", "function": {"name": "tool_a", "parameters": {"type": "object", "properties": {}}}} ] }` - result := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) mode := gjson.GetBytes(result, "toolConfig.functionCallingConfig.mode").String() if mode != "NONE" { t.Fatalf("expected toolConfig.functionCallingConfig.mode = 'NONE', got %q. Output: %s", mode, result) @@ -789,7 +789,7 @@ func TestConvertOpenAIRequestToGemini_ToolChoice(t *testing.T) { {"type": "function", "function": {"name": "tool_a", "parameters": {"type": "object", "properties": {}}}} ] }` - result := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) mode := gjson.GetBytes(result, "toolConfig.functionCallingConfig.mode").String() if mode != "AUTO" { t.Fatalf("expected toolConfig.functionCallingConfig.mode = 'AUTO', got %q. Output: %s", mode, result) @@ -806,7 +806,7 @@ func TestConvertOpenAIRequestToGemini_ToolChoice(t *testing.T) { {"type": "function", "function": {"name": "tool_a", "parameters": {"type": "object", "properties": {}}}} ] }` - result := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) mode := gjson.GetBytes(result, "toolConfig.functionCallingConfig.mode").String() if mode != "AUTO" { t.Fatalf("expected toolConfig.functionCallingConfig.mode = 'AUTO', got %q. Output: %s", mode, result) @@ -829,7 +829,7 @@ func TestConvertOpenAIRequestToGemini_ToolChoice(t *testing.T) { {"type": "function", "function": {"name": "tool_b", "parameters": {"type": "object", "properties": {}}}} ] }` - result := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) mode := gjson.GetBytes(result, "toolConfig.functionCallingConfig.mode").String() allowed := gjson.GetBytes(result, "toolConfig.functionCallingConfig.allowedFunctionNames") if mode != "AUTO" { @@ -860,7 +860,7 @@ func TestConvertOpenAIRequestToGemini_ToolChoice(t *testing.T) { {"type": "function", "function": {"name": "tool_b", "parameters": {"type": "object", "properties": {}}}} ] }` - result := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) mode := gjson.GetBytes(result, "toolConfig.functionCallingConfig.mode").String() allowed := gjson.GetBytes(result, "toolConfig.functionCallingConfig.allowedFunctionNames").Array() if mode != "ANY" { @@ -885,7 +885,7 @@ func TestConvertOpenAIRequestToGemini_ToolChoice(t *testing.T) { {"type": "function", "function": {"name": "tool_a", "parameters": {"type": "object", "properties": {}}}} ] }` - result := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) mode := gjson.GetBytes(result, "toolConfig.functionCallingConfig.mode").String() if mode != "NONE" { t.Fatalf("expected mode = 'NONE', got %q. Output: %s", mode, result) @@ -901,7 +901,7 @@ func TestConvertOpenAIRequestToGemini_ToolChoice(t *testing.T) { {"type": "function", "function": {"name": "tool_a", "parameters": {"type": "object", "properties": {}}}} ] }` - result := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) mode := gjson.GetBytes(result, "toolConfig.functionCallingConfig.mode").String() if mode != "NONE" { t.Fatalf("expected mode = 'NONE', got %q. Output: %s", mode, result) @@ -922,7 +922,7 @@ func TestConvertOpenAIRequestToGemini_ToolChoice(t *testing.T) { {"type": "function", "function": {"name": "_1tool", "parameters": {"type": "object", "properties": {}}}} ] }` - result := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) mode := gjson.GetBytes(result, "toolConfig.functionCallingConfig.mode").String() if mode != "NONE" { t.Fatalf("expected mode = 'NONE' when exact original name not found, got %q. Output: %s", mode, result) @@ -939,7 +939,7 @@ func TestConvertOpenAIRequestToGemini_ToolChoice(t *testing.T) { {"type": "function", "function": {"name": "_1tool", "parameters": {"type": "object", "properties": {}}}} ] }` - result := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) mode := gjson.GetBytes(result, "toolConfig.functionCallingConfig.mode").String() if mode != "NONE" { t.Fatalf("expected mode = 'NONE' on name collision, got %q. Output: %s", mode, result) @@ -955,7 +955,7 @@ func TestConvertOpenAIRequestToGemini_ToolChoice(t *testing.T) { {"type": "function", "function": {"name": "tool_a", "parameters": {"type": "object", "properties": {}}}} ] }` - result := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) mode := gjson.GetBytes(result, "toolConfig.functionCallingConfig.mode").String() if mode != "NONE" { t.Fatalf("expected mode = 'NONE' for undeclared function, got %q. Output: %s", mode, result) @@ -978,7 +978,7 @@ func TestConvertOpenAIRequestToGemini_ToolChoice(t *testing.T) { {"type": "function", "function": {"name": "_1tool", "parameters": {"type": "object", "properties": {}}}} ] }` - result := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) mode := gjson.GetBytes(result, "toolConfig.functionCallingConfig.mode").String() if mode != "AUTO" { t.Fatalf("expected mode = 'AUTO', got %q. Output: %s", mode, result) @@ -998,7 +998,7 @@ func TestConvertOpenAIRequestToGemini_ToolChoice(t *testing.T) { {"type": "function", "function": {"name": "tool_a", "parameters": {"type": "object", "properties": {}}}} ] }` - result := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) if gjson.GetBytes(result, "toolConfig").Exists() { t.Fatalf("expected toolConfig not to be set when tool_choice is null, got: %s", result) } @@ -1074,7 +1074,7 @@ func TestConvertOpenAIRequestToGemini_ToolStrictMapsToValidatedMode(t *testing.T } ] }`, tt.toolChoice) - result := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) if gjson.GetBytes(result, "tools.0.functionDeclarations.0.strict").Exists() { t.Fatalf("tools.0.functionDeclarations.0.strict should be removed from function declaration: %s", result) } @@ -1121,7 +1121,7 @@ func TestConvertOpenAIRequestToGemini_ToolStrictMapsToValidatedMode(t *testing.T } ] }` - result := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) mode := gjson.GetBytes(result, "toolConfig.functionCallingConfig.mode").String() if mode != "VALIDATED" { t.Fatalf("expected mode = 'VALIDATED' for mixed tools, got %q", mode) @@ -1152,7 +1152,7 @@ func TestConvertOpenAIRequestToGemini_ToolStrictMapsToValidatedMode(t *testing.T } ] }` - result := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) if gjson.GetBytes(result, "toolConfig").Exists() { t.Fatalf("expected toolConfig not to be set when no strict tools and no tool_choice, got: %s", result) } @@ -1189,7 +1189,7 @@ func TestConvertOpenAIRequestToGemini_ParametersJsonSchema_PreservesAdditionalPr ] }`) - output := ConvertOpenAIRequestToGemini("gemini-2.5-flash", inputJSON, false) + output, _ := ConvertOpenAIRequestToGemini("gemini-2.5-flash", inputJSON, false) schema := gjson.GetBytes(output, "tools.0.functionDeclarations.0.parametersJsonSchema") if !schema.Exists() { t.Fatalf("parametersJsonSchema missing. Output: %s", output) diff --git a/internal/translator/gemini/openai/chat-completions/gemini_openai_signature_test.go b/internal/translator/gemini/openai/chat-completions/gemini_openai_signature_test.go index 6c316908cab..5b2de083d4b 100644 --- a/internal/translator/gemini/openai/chat-completions/gemini_openai_signature_test.go +++ b/internal/translator/gemini/openai/chat-completions/gemini_openai_signature_test.go @@ -42,7 +42,7 @@ func TestConvertOpenAIRequestToGemini_ToolCallSignatureCompatibility(t *testing. }] }`) - output := ConvertOpenAIRequestToGemini("gemini-3.5-flash", input, false) + output, _ := ConvertOpenAIRequestToGemini("gemini-3.5-flash", input, false) if got := gjson.GetBytes(output, "contents.0.parts.0.thoughtSignature").String(); got != tt.wantSignature { t.Fatalf("thoughtSignature = %q, want %q. Output: %s", got, tt.wantSignature, output) } diff --git a/internal/translator/gemini/openai/chat-completions/init.go b/internal/translator/gemini/openai/chat-completions/init.go index a00a836357f..2631f8f93af 100644 --- a/internal/translator/gemini/openai/chat-completions/init.go +++ b/internal/translator/gemini/openai/chat-completions/init.go @@ -4,18 +4,16 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" - sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( OpenAI, Gemini, - nil, + ConvertOpenAIRequestToGemini, interfaces.TranslateResponse{ Stream: ConvertGeminiResponseToOpenAI, NonStream: ConvertGeminiResponseToOpenAINonStream, }, ) - sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatOpenAI, sdktranslator.FormatGemini, convertOpenAIRequestToGemini) } diff --git a/internal/translator/gemini/openai/chat-completions/noop_optimization_test.go b/internal/translator/gemini/openai/chat-completions/noop_optimization_test.go index b69d0f3d8b4..817424b8f1a 100644 --- a/internal/translator/gemini/openai/chat-completions/noop_optimization_test.go +++ b/internal/translator/gemini/openai/chat-completions/noop_optimization_test.go @@ -10,7 +10,7 @@ import ( func TestConvertOpenAIRequestToGeminiNormalizesToolNameAndStrict(t *testing.T) { input := []byte(`{"messages":[],"tools":[{"type":"function","function":{"name":true,"strict":true,"parameters":{"type":"object"}}}]}`) - output := ConvertOpenAIRequestToGemini("gemini-test", input, false) + output, _ := ConvertOpenAIRequestToGemini("gemini-test", input, false) name := gjson.GetBytes(output, "tools.0.functionDeclarations.0.name") if name.Type != gjson.String || name.String() != "true" { diff --git a/internal/translator/gemini/openai/responses/apply_patch_test.go b/internal/translator/gemini/openai/responses/apply_patch_test.go index 289522b4b6b..cce958ec5d4 100644 --- a/internal/translator/gemini/openai/responses/apply_patch_test.go +++ b/internal/translator/gemini/openai/responses/apply_patch_test.go @@ -197,7 +197,7 @@ func TestGeminiApplyPatchNonStreamConflictingCompleteCalls(t *testing.T) { func TestGeminiApplyPatchHistoryPreservesWhitespaceAndToolPair(t *testing.T) { request := []byte(`{"tools":[{"type":"namespace","name":"functions","tools":[{"type":"custom","name":"apply_patch"}]}],"input":[{"type":"custom_tool_call","call_id":"c1","namespace":"functions","name":"apply_patch","input":" *** Begin Patch\n*** Add File: 中.txt\n+😀\n*** End Patch\n "},{"type":"custom_tool_call_output","call_id":"c1","output":"ok"},{"role":"user","type":"message","content":"continue"}]}`) - out := ConvertOpenAIResponsesRequestToGemini("gemini-3.1-pro-preview", request, false) + out, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.1-pro-preview", request, false) want := " *** Begin Patch\n*** Add File: 中.txt\n+😀\n*** End Patch\n " var call, result gjson.Result gjson.GetBytes(out, "contents").ForEach(func(_, content gjson.Result) bool { diff --git a/internal/translator/gemini/openai/responses/gemini_openai-responses_request.go b/internal/translator/gemini/openai/responses/gemini_openai-responses_request.go index 8940252b9e4..2d7ac679277 100644 --- a/internal/translator/gemini/openai/responses/gemini_openai-responses_request.go +++ b/internal/translator/gemini/openai/responses/gemini_openai-responses_request.go @@ -18,15 +18,7 @@ import ( const geminiResponsesThoughtSignature = "skip_thought_signature_validator" -func ConvertOpenAIResponsesRequestToGemini(modelName string, inputRawJSON []byte, stream bool) []byte { - body, _ := convertOpenAIResponsesRequestToGemini(modelName, inputRawJSON, stream) - return body -} - -// ConvertOpenAIResponsesRequestToGeminiReturningError also reports an attachment -// Gemini cannot receive, such as a bare file id, when it leaves a user turn with -// nothing to send. -func ConvertOpenAIResponsesRequestToGeminiReturningError(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { +func ConvertOpenAIResponsesRequestToGemini(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { return convertOpenAIResponsesRequestToGemini(modelName, inputRawJSON, stream) } diff --git a/internal/translator/gemini/openai/responses/gemini_openai-responses_request_test.go b/internal/translator/gemini/openai/responses/gemini_openai-responses_request_test.go index 91e5667b389..a56a8ac3598 100644 --- a/internal/translator/gemini/openai/responses/gemini_openai-responses_request_test.go +++ b/internal/translator/gemini/openai/responses/gemini_openai-responses_request_test.go @@ -36,7 +36,7 @@ func TestConvertOpenAIResponsesRequestToGemini_ReattachesReasoningAndSignatureTo {"type":"function_call_output","call_id":"call-1","output":"ok"} ] }` - result := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) parts := gjson.GetBytes(result, "contents.1.parts").Array() if len(parts) != 2 || !parts[0].Get("thought").Bool() { t.Fatalf("reasoning/function parts malformed: %s", result) @@ -58,7 +58,7 @@ func TestConvertOpenAIResponsesRequestToGemini_SyntheticParallelCallsOnlyFirstGe ] }` - result := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) parts := gjson.GetBytes(result, "contents.0.parts").Array() if len(parts) != 2 { t.Fatalf("parts = %d, want 2 parallel calls; result=%s", len(parts), result) @@ -82,7 +82,7 @@ func TestConvertOpenAIResponsesRequestToGemini_NativeParallelCallsPreserveUnsign ] }` - result := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) var calls []gjson.Result for _, content := range gjson.GetBytes(result, "contents").Array() { for _, part := range content.Get("parts").Array() { @@ -121,7 +121,7 @@ func TestConvertOpenAIResponsesRequestToGemini_PreservesMultipleLeadingToolSigna {"type":"function_call_output","call_id":"call-2","output":"two"} ] }` - result := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) var signatures, sequence []string for _, content := range gjson.GetBytes(result, "contents").Array() { for _, part := range content.Get("parts").Array() { @@ -155,7 +155,7 @@ func TestConvertOpenAIResponsesRequestToGemini_GroupsReversedParallelToolOutputs {"type":"function_call_output","call_id":"call-1","output":"one"} ] }` - result := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) if errValidate := internalsignature.ValidateGeminiFunctionCallPairing(result); errValidate != nil { t.Fatalf("parallel tool history is invalid: %v; result=%s", errValidate, result) } @@ -192,7 +192,7 @@ func TestConvertOpenAIResponsesRequestToGemini_GroupsNonContiguousParallelToolOu {"type":"function_call_output","call_id":"call-2","output":"two"} ] }` - result := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) contents := gjson.GetBytes(result, "contents").Array() if len(contents) != 4 || contents[0].Get("role").String() != "model" || contents[1].Get("role").String() != "user" || contents[2].Get("role").String() != "user" || contents[3].Get("role").String() != "user" { t.Fatalf("non-contiguous tool output roles malformed; result=%s", result) @@ -219,7 +219,7 @@ func TestConvertOpenAIResponsesRequestToGemini_PreservesReasoningBeforePairedFun {"type":"function_call_output","call_id":"call-1","output":"ok"} ] }` - result := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) var signatures []string for _, content := range gjson.GetBytes(result, "contents").Array() { for _, part := range content.Get("parts").Array() { @@ -244,7 +244,7 @@ func TestConvertOpenAIResponsesRequestToGemini_PreservesFunctionOutputOrderAcros {"type":"function_call_output","call_id":"call-2","output":"two"} ] }` - result := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) var sequence []string for _, content := range gjson.GetBytes(result, "contents").Array() { for _, part := range content.Get("parts").Array() { @@ -271,7 +271,7 @@ func TestConvertOpenAIResponsesRequestToGemini_ReattachesTrailingDetachedSignatu {"type":"message","role":"user","content":[{"type":"input_text","text":"turn two"}]} ] }` - result := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) parts := gjson.GetBytes(result, "contents.1.parts").Array() if len(parts) != 1 { t.Fatalf("model parts = %d, want one signed visible part; result=%s", len(parts), result) @@ -297,7 +297,7 @@ func TestConvertOpenAIResponsesRequestToGemini_ReattachesUnmarkedTrailingSignatu {"type":"message","role":"user","content":[{"type":"input_text","text":"turn two"}]} ] }` - result := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", []byte(inputJSON), false) + result, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", []byte(inputJSON), false) parts := gjson.GetBytes(result, "contents.1.parts").Array() if len(parts) != 1 { t.Fatalf("model parts = %d, want one signed visible part after client rewrites carrier ID; result=%s", len(parts), result) @@ -321,7 +321,7 @@ func TestConvertOpenAIResponsesRequestToGemini_UnmarkedReasoningBeforeFunctionCa {"type":"function_call_output","call_id":"call-1","output":"ok"} ] }` - result := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", []byte(inputJSON), false) + result, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", []byte(inputJSON), false) modelParts := gjson.GetBytes(result, "contents.1.parts").Array() if len(modelParts) != 2 { t.Fatalf("model parts = %d, want unsigned preamble plus signed call; result=%s", len(modelParts), result) @@ -344,7 +344,7 @@ func TestConvertOpenAIResponsesRequestToGemini_ReattachesDetachedSignatureToFunc {"type":"function_call_output","call_id":"call-1","output":"ok"} ] }` - result := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) functionParts := gjson.GetBytes(result, "contents.#(role==\"model\")#.parts").Array() found := false for _, partArray := range functionParts { @@ -372,7 +372,7 @@ func TestConvertOpenAIResponsesRequestToGemini_ReattachesUnmarkedPostCallSignatu {"type":"function_call_output","call_id":"call-1","output":"ok"} ] }` - result := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) if got := gjson.GetBytes(result, "contents.0.parts.0.thoughtSignature").String(); got != testResponsesGeminiThoughtSignature { t.Fatalf("unmarked post-call signature = %q, want native signature; result=%s", got, result) } @@ -402,7 +402,7 @@ func TestConvertOpenAIResponsesRequestToGemini_ReattachesDirectionalFunctionCarr t.Run(testCase.name, func(t *testing.T) { carrier := encodeGeminiResponsesCarrier(testResponsesGeminiThoughtSignature, testCase.direction, geminiResponsesCarrierFunction) inputJSON := []byte(`{"model":"gemini-3.6-flash-high","input":` + testCase.input(carrier) + `}`) - result := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", inputJSON, false) + result, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", inputJSON, false) if got := gjson.GetBytes(result, "contents.0.parts.0.thoughtSignature").String(); got != testResponsesGeminiThoughtSignature { t.Fatalf("directional function signature = %q, want native signature; result=%s", got, result) } @@ -450,7 +450,7 @@ func TestConvertOpenAIResponsesRequestToGemini_DoesNotRetargetExtraPreviousCarri first := encodeGeminiResponsesCarrier(testResponsesGeminiThoughtSignature, geminiResponsesCarrierNext, testCase.targetKind) extra := encodeGeminiResponsesCarrier(signature2, geminiResponsesCarrierPrevious, testCase.targetKind) request := []byte(`{"model":"gemini-3.6-flash-high","input":` + testCase.input(first, extra) + `}`) - translated := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) + translated, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) testCase.assert(t, gjson.GetBytes(translated, "contents.0.parts").Array()) }) } @@ -459,7 +459,7 @@ func TestConvertOpenAIResponsesRequestToGemini_DoesNotRetargetExtraPreviousCarri func TestConvertOpenAIResponsesRequestToGemini_DoesNotBindStandaloneFunctionCarrier(t *testing.T) { carrier := encodeGeminiResponsesCarrier(testResponsesGeminiThoughtSignature, geminiResponsesCarrierStandalone, geminiResponsesCarrierFunction) inputJSON := []byte(`{"model":"gemini-3.6-flash-high","input":[{"type":"reasoning","encrypted_content":"` + carrier + `","summary":[]},{"type":"function_call","call_id":"call-1","name":"run_command","arguments":"{}"}]}`) - result := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", inputJSON, false) + result, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", inputJSON, false) parts := gjson.GetBytes(result, "contents.0.parts").Array() if len(parts) != 2 || parts[0].Get("thoughtSignature").String() != testResponsesGeminiThoughtSignature || parts[1].Get("thoughtSignature").String() != geminiResponsesThoughtSignature { t.Fatalf("standalone carrier was bound to function call: %s", result) @@ -477,7 +477,7 @@ func TestConvertOpenAIResponsesRequestToGemini_ReattachesUnmarkedParallelPostCal {"type":"function_call_output","call_id":"call-2","output":"two"} ] }` - result := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) parts := gjson.GetBytes(result, "contents.0.parts").Array() if len(parts) != 2 || parts[0].Get("thoughtSignature").String() != geminiResponsesThoughtSignature || parts[1].Get("thoughtSignature").String() != testResponsesGeminiThoughtSignature { t.Fatalf("parallel post-call signature was not attached to call-2: %s", result) @@ -497,7 +497,7 @@ func TestConvertOpenAIResponsesRequestToGemini_ReattachesAlternatingParallelPost {"type":"function_call_output","call_id":"call-2","output":"two"} ] }` - result := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) parts := gjson.GetBytes(result, "contents.0.parts").Array() if len(parts) != 2 || parts[0].Get("functionCall.id").String() != "call-1" || parts[0].Get("thoughtSignature").String() != testResponsesGeminiThoughtSignature || parts[1].Get("functionCall.id").String() != "call-2" || parts[1].Get("thoughtSignature").String() != signature2 { t.Fatalf("alternating parallel post-call signatures shifted: %s", result) @@ -515,7 +515,7 @@ func TestConvertOpenAIResponsesRequestToGemini_PreservesExtraConsecutivePostCall {"type":"function_call_output","call_id":"call-1","output":"ok"} ] }` - result := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) parts := gjson.GetBytes(result, "contents.0.parts").Array() if len(parts) != 2 || parts[0].Get("functionCall.id").String() != "call-1" || parts[0].Get("thoughtSignature").String() != testResponsesGeminiThoughtSignature || parts[1].Get("thoughtSignature").String() != signature2 { t.Fatalf("consecutive post-call carriers malformed: %s", result) @@ -531,7 +531,7 @@ func TestConvertOpenAIResponsesRequestToGemini_DoesNotPairUnmarkedPostCallSignat {"type":"function_call_output","call_id":"other-call","output":"ok"} ] }` - result := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) if got := gjson.GetBytes(result, "contents.0.parts.0.thoughtSignature").String(); got != geminiResponsesThoughtSignature { t.Fatalf("mismatched output paired signature %q; result=%s", got, result) } @@ -547,7 +547,7 @@ func TestConvertOpenAIResponsesRequestToGemini_DoesNotPairUnmarkedPostCallSignat {"type":"function_call_output","call_id":"call-1","output":"ok"} ] }` - result := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) if got := gjson.GetBytes(result, "contents.0.parts.0.thoughtSignature").String(); got != geminiResponsesThoughtSignature { t.Fatalf("user-boundary carrier paired signature %q; result=%s", got, result) } @@ -570,7 +570,7 @@ func TestConvertOpenAIResponsesRequestToGemini_StripsTrailingAssistantPrefill(t ] }` - result := ConvertOpenAIResponsesRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.1-pro-high", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) contents := resultJSON.Get("contents").Array() @@ -618,7 +618,7 @@ func TestConvertOpenAIResponsesRequestToGemini_TextFormatJSONSchema(t *testing.T } }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.1-flash-lite", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.1-flash-lite", []byte(inputJSON), false) result := gjson.ParseBytes(output) genConfig := result.Get("generationConfig") @@ -657,7 +657,7 @@ func TestConvertOpenAIResponsesRequestToGemini_TextFormatJSONObject(t *testing.T } }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.1-flash-lite", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.1-flash-lite", []byte(inputJSON), false) result := gjson.ParseBytes(output) genConfig := result.Get("generationConfig") @@ -679,7 +679,7 @@ func TestConvertOpenAIResponsesRequestToGemini_PreservesReasoningOnlyHistory(t * }] }`) - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", input, false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", input, false) parts := gjson.GetBytes(output, "contents.0.parts").Array() if got := gjson.GetBytes(output, "contents").Array(); len(got) != 1 { t.Fatalf("contents length = %d, want 1. Output: %s", len(got), output) @@ -704,7 +704,7 @@ func TestConvertOpenAIResponsesRequestToGemini_DropsEmptyUnsignedReasoningCarrie "input":[{"type":"reasoning","encrypted_content":"","summary":[]}] }`) - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", input, false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", input, false) if got := gjson.GetBytes(output, "contents.#").Int(); got != 0 { t.Fatalf("contents = %d, want no empty unsigned model content; output=%s", got, output) } @@ -721,7 +721,7 @@ func TestConvertOpenAIResponsesRequestToGemini_PreservesUnboundDetachedCarrierWi }] }`) - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", input, false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", input, false) parts := gjson.GetBytes(output, "contents.0.parts").Array() if len(parts) != 1 { t.Fatalf("unbound carrier parts = %d, want one signed carrier; output=%s", len(parts), output) @@ -756,7 +756,7 @@ func TestConvertOpenAIResponsesRequestToGemini_PreservesReasoningBeforeTrailingA ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", []byte(inputJSON), false) contents := gjson.GetBytes(output, "contents").Array() if len(contents) != 2 { t.Fatalf("contents length = %d, want 2. Output: %s", len(contents), output) @@ -803,7 +803,7 @@ func TestConvertOpenAIResponsesRequestToGemini_ReasoningSignatureCompatibility(t }] }`) - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", input, false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", input, false) parts := gjson.GetBytes(output, "contents.0.parts").Array() if len(parts) != 1 { t.Fatalf("parts length = %d, want 1. Output: %s", len(parts), output) @@ -840,7 +840,7 @@ func TestConvertOpenAIResponsesRequestToGemini_MergesReasoningWithAssistantVisib ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", []byte(inputJSON), false) contents := gjson.GetBytes(output, "contents").Array() if len(contents) != 2 { t.Fatalf("contents length = %d, want 2. Output: %s", len(contents), output) @@ -879,7 +879,7 @@ func TestConvertOpenAIResponsesRequestToGemini_MergesReasoningWithUserRoleOutput } ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", []byte(inputJSON), false) contents := gjson.GetBytes(output, "contents").Array() if len(contents) != 1 { t.Fatalf("contents length = %d, want 1. Output: %s", len(contents), output) @@ -905,7 +905,7 @@ func TestConvertOpenAIResponsesRequestToGemini_MergesReasoningWithAssistantStrin } ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", []byte(inputJSON), false) if got := gjson.GetBytes(output, "contents.0.parts.1.text").String(); got != "string visible answer" { t.Fatalf("visible text = %q", got) } @@ -932,7 +932,7 @@ func TestConvertOpenAIResponsesRequestToGemini_PreservesWhitespaceWhenMergingRea } ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", []byte(inputJSON), false) if got := gjson.GetBytes(output, "contents.0.parts.1.text").String(); got != " lead trail " { t.Fatalf("visible text = %q, want preserved whitespace", got) } @@ -983,7 +983,7 @@ func TestConvertOpenAIResponsesRequestToGemini_SystemAndDeveloperRoles(t *testin ] }`) - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", input, false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", input, false) result := gjson.ParseBytes(output) systemInstruction := result.Get("systemInstruction") @@ -1045,7 +1045,7 @@ func TestConvertOpenAIResponsesRequestToGemini_MidSessionDeveloperMessageDoesNot ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", []byte(inputJSON), false) result := gjson.ParseBytes(output) // systemInstruction must remain strictly unchanged (only original instructions, not developer notice) @@ -1115,7 +1115,7 @@ func TestConvertOpenAIResponsesRequestToGemini_MidSessionSystemReminderEnvelope( ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", []byte(inputJSON), false) result := gjson.ParseBytes(output) contents := result.Get("contents").Array() @@ -1154,7 +1154,7 @@ func TestConvertOpenAIResponsesRequestToGemini_MidSessionDeveloperMultiPartConte ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", []byte(inputJSON), false) result := gjson.ParseBytes(output) contents := result.Get("contents").Array() @@ -1210,7 +1210,7 @@ func TestConvertOpenAIResponsesRequestToGemini_MultipleMidSessionDeveloperMessag ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", []byte(inputJSON), false) result := gjson.ParseBytes(output) // systemInstruction only contains original instructions @@ -1270,7 +1270,7 @@ func TestConvertOpenAIResponsesRequestToGemini_InterveningDeveloperMessagePreser ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", []byte(inputJSON), false) result := gjson.ParseBytes(output) // Validate function call pairing passes strictly (no content turn before pending functionResponse) @@ -1329,7 +1329,7 @@ func TestConvertOpenAIResponsesRequestToGemini_InterveningDeveloperAndUserMessag ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.5-flash", []byte(inputJSON), false) result := gjson.ParseBytes(output) // Pairing should be valid @@ -1379,7 +1379,7 @@ func TestConvertOpenAIResponsesRequestToGeminiCleansToolSchemaRequiredFields(t * }] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-2.0-flash", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-2.0-flash", []byte(inputJSON), false) schema := gjson.GetBytes(output, "tools.0.functionDeclarations.0.parametersJsonSchema") if !schema.Exists() { @@ -1448,7 +1448,7 @@ func TestConvertOpenAIResponsesRequestToGemini_FunctionCallOutputWithImages(t *t ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) userContent := gjson.GetBytes(output, "contents.2") if userContent.Get("role").String() != "user" { t.Fatalf("expected role user in third content, got %s", userContent.Raw) @@ -1503,7 +1503,7 @@ func TestConvertOpenAIResponsesRequestToGemini_FunctionCallOutputVariations(t *t } ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) userContent := gjson.GetBytes(output, "contents.1") parts := userContent.Get("parts").Array() if len(parts) != 1 { @@ -1532,7 +1532,7 @@ func TestConvertOpenAIResponsesRequestToGemini_FunctionCallOutputVariations(t *t } ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) userContent := gjson.GetBytes(output, "contents.1") parts := userContent.Get("parts").Array() if len(parts) != 1 { @@ -1564,7 +1564,7 @@ func TestConvertOpenAIResponsesRequestToGemini_FunctionCallOutputVariations(t *t } ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) userContent := gjson.GetBytes(output, "contents.1") parts := userContent.Get("parts").Array() if len(parts) != 1 { @@ -1596,7 +1596,7 @@ func TestConvertOpenAIResponsesRequestToGemini_FunctionCallOutputVariations(t *t } ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) userContent := gjson.GetBytes(output, "contents.1") parts := userContent.Get("parts").Array() if len(parts) != 1 { @@ -1627,7 +1627,7 @@ func TestConvertOpenAIResponsesRequestToGemini_FunctionCallOutputVariations(t *t } ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) userContent := gjson.GetBytes(output, "contents.1") parts := userContent.Get("parts").Array() if len(parts) != 1 { @@ -1659,7 +1659,7 @@ func TestConvertOpenAIResponsesRequestToGemini_FunctionCallOutputVariations(t *t } ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) userContent := gjson.GetBytes(output, "contents.1") parts := userContent.Get("parts").Array() if len(parts) != 1 { @@ -1689,7 +1689,7 @@ func TestConvertOpenAIResponsesRequestToGemini_FunctionCallOutputVariations(t *t } ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) userContent := gjson.GetBytes(output, "contents.1") parts := userContent.Get("parts").Array() if len(parts) != 1 { @@ -1753,7 +1753,7 @@ func TestConvertOpenAIResponsesRequestToGemini_ParallelFunctionCallOutputsWithIm ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) userContent := gjson.GetBytes(output, "contents.2") if userContent.Get("role").String() != "user" { t.Fatalf("expected role user in tool response content, got %s", userContent.Raw) @@ -1823,7 +1823,7 @@ func TestConvertOpenAIResponsesRequestToGemini_FunctionCallOutputWithMultipleIma ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) userContent := gjson.GetBytes(output, "contents.2") parts := userContent.Get("parts").Array() if len(parts) != 1 { @@ -1909,7 +1909,7 @@ func TestConvertOpenAIResponsesRequestToGemini_AdditionalToolsNamespaceAndCustom } }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-flash", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-flash", []byte(inputJSON), false) decls := gjson.GetBytes(output, "tools.0.functionDeclarations").Array() if len(decls) != 2 { t.Fatalf("expected 2 functionDeclarations, got %d; raw: %s", len(decls), output) @@ -1969,7 +1969,7 @@ func TestConvertOpenAIResponsesRequestToGemini_ReplaysCustomToolCallAndOutput(t ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-flash", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-flash", []byte(inputJSON), false) contents := gjson.GetBytes(output, "contents").Array() if len(contents) < 2 { t.Fatalf("expected at least 2 contents, got %d; raw: %s", len(contents), output) @@ -2029,7 +2029,7 @@ func TestConvertOpenAIResponsesRequestToGemini_TwoTurnCustomToolRoundtripWithRea ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(inputJSON), false) contents := gjson.GetBytes(output, "contents").Array() if len(contents) != 3 { t.Fatalf("expected 3 contents (user, model, user), got %d; raw: %s", len(contents), output) @@ -2123,7 +2123,7 @@ func TestConvertOpenAIResponsesRequestToGemini_FunctionCallOutputAlternateIDsAnd ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) contents := gjson.GetBytes(output, "contents").Array() if len(contents) != 3 { t.Fatalf("expected 3 contents, got %d; output=%s", len(contents), string(output)) @@ -2167,7 +2167,7 @@ func TestConvertOpenAIResponsesRequestToGemini_ParallelFunctionCallOutputsAltern ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) if errValidate := internalsignature.ValidateGeminiFunctionCallPairing(output); errValidate != nil { t.Fatalf("parallel tool pairing validation failed: %v; output=%s", errValidate, string(output)) } @@ -2211,7 +2211,7 @@ func TestConvertOpenAIResponsesRequestToGemini_DedicatedCallIDTakesPrecedenceOve ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) if errValidate := internalsignature.ValidateGeminiFunctionCallPairing(output); errValidate != nil { t.Fatalf("pairing validation failed: %v; output=%s", errValidate, string(output)) } @@ -2255,7 +2255,7 @@ func TestConvertOpenAIResponsesRequestToGemini_ExplicitUnmatchedCallIDNotRebound ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) if errValidate := internalsignature.ValidateGeminiFunctionCallPairing(output); errValidate != nil { t.Fatalf("pairing validation failed: %v; output=%s", errValidate, string(output)) } @@ -2296,7 +2296,7 @@ func TestConvertOpenAIResponsesRequestToGemini_MixedMissingAndExplicitParallelOu ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) contents := gjson.GetBytes(output, "contents").Array() resultMap := make(map[string]string) @@ -2335,7 +2335,7 @@ func TestConvertOpenAIResponsesRequestToGemini_AllPendingCallsReservedByFutureEx ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) contents := gjson.GetBytes(output, "contents").Array() var responseIDs []string @@ -2382,7 +2382,7 @@ func TestConvertOpenAIResponsesRequestToGemini_InterruptedFunctionCallPreservesP ] }` - result := ConvertOpenAIResponsesRequestToGemini("gemini-3.8-flash-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.8-flash-high", []byte(inputJSON), false) if err := internalsignature.ValidateGeminiFunctionCallPairing(result); err != nil { t.Fatalf("ValidateGeminiFunctionCallPairing failed on Gemini request: %v; output=%s", err, result) } @@ -2413,7 +2413,7 @@ func TestConvertOpenAIResponsesRequestToGemini_ParallelInterruptedFunctionCallPr ] }` - result := ConvertOpenAIResponsesRequestToGemini("gemini-3.8-flash-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.8-flash-high", []byte(inputJSON), false) if err := internalsignature.ValidateGeminiFunctionCallPairing(result); err != nil { t.Fatalf("ValidateGeminiFunctionCallPairing failed on parallel interrupted request: %v; output=%s", err, result) } @@ -2440,7 +2440,7 @@ func TestConvertOpenAIResponsesRequestToGemini_TrailingPartialParallelCallsPrese ] }` - result := ConvertOpenAIResponsesRequestToGemini("gemini-3.8-flash-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.8-flash-high", []byte(inputJSON), false) if err := internalsignature.ValidateGeminiFunctionCallPairing(result); err != nil { t.Fatalf("ValidateGeminiFunctionCallPairing failed on trailing partial parallel request: %v; output=%s", err, result) } @@ -2468,7 +2468,7 @@ func TestConvertOpenAIResponsesRequestToGemini_InterruptedMessageBeforeRealOutpu ] }` - result := ConvertOpenAIResponsesRequestToGemini("gemini-3.8-flash-high", []byte(inputJSON), false) + result, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.8-flash-high", []byte(inputJSON), false) if err := internalsignature.ValidateGeminiFunctionCallPairing(result); err != nil { t.Fatalf("ValidateGeminiFunctionCallPairing failed on interrupted message before real output request: %v; output=%s", err, result) } @@ -2499,7 +2499,7 @@ func TestConvertOpenAIResponsesRequestToGemini_FunctionCallOutputWithFCOItemID(t ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) if errValidate := internalsignature.ValidateGeminiFunctionCallPairing(output); errValidate != nil { t.Fatalf("pairing validation failed: %v; output=%s", errValidate, string(output)) } @@ -2535,7 +2535,7 @@ func TestConvertOpenAIResponsesRequestToGemini_OrphanFunctionCallOutputBecomesUs ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) if errValidate := internalsignature.ValidateGeminiFunctionCallPairing(output); errValidate != nil { t.Fatalf("pairing validation failed: %v; output=%s", errValidate, string(output)) } @@ -2583,7 +2583,7 @@ func TestConvertOpenAIResponsesRequestToGemini_UnpairedExplicitCallIDBecomesUser ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.7-flash-high", []byte(inputJSON), false) if errValidate := internalsignature.ValidateGeminiFunctionCallPairing(output); errValidate != nil { t.Fatalf("pairing validation failed: %v; output=%s", errValidate, string(output)) } @@ -2649,7 +2649,7 @@ func TestConvertOpenAIResponsesRequestToGemini_ParametersJsonSchema_PreservesAdd }] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-flash", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-flash", []byte(inputJSON), false) schema := gjson.GetBytes(output, "tools.0.functionDeclarations.0.parametersJsonSchema") if !schema.Exists() { @@ -2783,7 +2783,7 @@ func TestConvertOpenAIResponsesRequestToGemini_AudioInput(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - output := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-flash", []byte(tc.inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-flash", []byte(tc.inputJSON), false) contents := gjson.GetBytes(output, "contents").Array() if len(contents) == 0 { t.Fatalf("expected at least 1 content, got 0. Output: %s", output) @@ -2905,7 +2905,7 @@ func TestConvertOpenAIResponsesRequestToGemini_VideoInput(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - output := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-flash", []byte(tc.inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-flash", []byte(tc.inputJSON), false) contents := gjson.GetBytes(output, "contents").Array() if len(contents) == 0 { t.Fatalf("expected at least 1 content, got 0. Output: %s", output) @@ -2939,7 +2939,7 @@ func TestConvertOpenAIResponsesRequestToGemini_TopLevelVideoAndTextCombined(t *t ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-flash", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-flash", []byte(inputJSON), false) contents := gjson.GetBytes(output, "contents").Array() if len(contents) != 1 { t.Fatalf("expected exactly 1 content, got %d. Output: %s", len(contents), output) @@ -2986,7 +2986,7 @@ func TestConvertOpenAIResponsesRequestToGemini_FallbackMIMEOnGenericDataURL(t *t ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-flash", []byte(imgInput), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-flash", []byte(imgInput), false) parts := gjson.GetBytes(output, "contents.0.parts").Array() if len(parts) < 9 { t.Fatalf("expected 9 parts, got %d. Output: %s", len(parts), output) @@ -3036,7 +3036,7 @@ func TestConvertOpenAIResponsesRequestToGemini_RemoteURLDoesNotOverrideExplicitF ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-flash", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-flash", []byte(inputJSON), false) parts := gjson.GetBytes(output, "contents.0.parts").Array() if len(parts) < 2 { t.Fatalf("expected 2 parts, got %d. Output: %s", len(parts), output) @@ -3065,7 +3065,7 @@ func TestConvertOpenAIResponsesRequestToGemini_UnknownExtensionFallsBackToDefaul ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-flash", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-flash", []byte(inputJSON), false) parts := gjson.GetBytes(output, "contents.0.parts").Array() if len(parts) < 2 { t.Fatalf("expected 2 parts, got %d. Output: %s", len(parts), output) @@ -3094,7 +3094,7 @@ func TestConvertOpenAIResponsesRequestToGemini_InlineExplicitFormatNotOverridden ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-flash", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-flash", []byte(inputJSON), false) parts := gjson.GetBytes(output, "contents.0.parts").Array() if len(parts) < 2 { t.Fatalf("expected 2 parts, got %d. Output: %s", len(parts), output) @@ -3126,7 +3126,7 @@ func TestConvertOpenAIResponsesRequestToGemini_RemoteNestedFormatNotOverriddenBy ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-flash", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-flash", []byte(inputJSON), false) parts := gjson.GetBytes(output, "contents.0.parts").Array() if len(parts) < 5 { t.Fatalf("expected 5 parts, got %d. Output: %s", len(parts), output) @@ -3165,7 +3165,7 @@ func TestConvertOpenAIResponsesRequestToGemini_GenericMIMEWithNestedFormatNotOve ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-flash", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-flash", []byte(inputJSON), false) parts := gjson.GetBytes(output, "contents.0.parts").Array() if len(parts) < 3 { t.Fatalf("expected 3 parts, got %d. Output: %s", len(parts), output) @@ -3201,7 +3201,7 @@ func TestConvertOpenAIResponsesRequestToGemini_RemoteMedia(t *testing.T) { ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-flash", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-flash", []byte(inputJSON), false) contents := gjson.GetBytes(output, "contents").Array() if len(contents) == 0 { t.Fatalf("expected at least 1 content, got 0. Output: %s", output) @@ -3359,7 +3359,7 @@ func TestConvertOpenAIResponsesRequestToGemini_InvalidDataURLsRejected(t *testin for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - output := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-flash", []byte(tc.inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-flash", []byte(tc.inputJSON), false) // No inline_data should be created for invalid data URLs contents := gjson.GetBytes(output, "contents").Array() for _, content := range contents { @@ -3403,7 +3403,7 @@ func TestConvertOpenAIResponsesRequestToGemini_FunctionResponseJSONRef(t *testin } ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.8-flash", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.8-flash", []byte(inputJSON), false) result := gjson.GetBytes(output, "contents.1.parts.0.functionResponse.response.result") if result.Type != gjson.String { t.Fatalf("expected functionResponse.response.result to be string, got type %s (raw: %s)", result.Type, result.Raw) @@ -3436,7 +3436,7 @@ func TestConvertOpenAIResponsesRequestToGemini_FunctionResponseJSONRef(t *testin } ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.8-flash", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.8-flash", []byte(inputJSON), false) result := gjson.GetBytes(output, "contents.1.parts.0.functionResponse.response.result") if result.Type != gjson.String { t.Fatalf("expected functionResponse.response.result to be string, got type %s (raw: %s)", result.Type, result.Raw) @@ -3466,7 +3466,7 @@ func TestConvertOpenAIResponsesRequestToGemini_FunctionResponseJSONRef(t *testin } ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.8-flash", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.8-flash", []byte(inputJSON), false) result := gjson.GetBytes(output, "contents.1.parts.0.functionResponse.response.result") if !result.IsObject() { t.Fatalf("expected functionResponse.response.result to remain JSON object, got type %s (raw: %s)", result.Type, result.Raw) @@ -3503,7 +3503,7 @@ func TestConvertOpenAIResponsesRequestToGemini_FunctionResponseJSONRef(t *testin } ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.8-flash", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.8-flash", []byte(inputJSON), false) fr := gjson.GetBytes(output, "contents.1.parts.0.functionResponse") if !fr.Exists() { t.Fatalf("expected functionResponse part, got %s", output) @@ -3544,7 +3544,7 @@ func TestConvertOpenAIResponsesRequestToGemini_UnsignedModelTextDoesNotSynthesiz ] }` - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.8-flash", []byte(inputJSON), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.8-flash", []byte(inputJSON), false) contents := gjson.GetBytes(output, "contents") if len(contents.Array()) != 1 { t.Fatalf("expected 1 content, got %d (raw: %s)", len(contents.Array()), output) diff --git a/internal/translator/gemini/openai/responses/gemini_openai-responses_response_test.go b/internal/translator/gemini/openai/responses/gemini_openai-responses_response_test.go index b611567dca4..8ccbbf53cef 100644 --- a/internal/translator/gemini/openai/responses/gemini_openai-responses_response_test.go +++ b/internal/translator/gemini/openai/responses/gemini_openai-responses_response_test.go @@ -251,7 +251,7 @@ func TestConvertGeminiResponseToOpenAIResponses_ConsecutiveSignedVisibleTextPres request := []byte(`{"model":"gemini-3.6-flash-high","input":[]}`) request, _ = sjson.SetRawBytes(request, "input", []byte(completed.Raw)) - translated := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) + translated, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) var visibleParts []gjson.Result for _, part := range gjson.GetBytes(translated, "contents.0.parts").Array() { if !part.Get("thought").Bool() && part.Get("text").String() != "" { @@ -277,7 +277,7 @@ func TestConvertGeminiResponseToOpenAIResponsesNonStream_ConsecutiveSignedVisibl outputWithoutIDs, _ = sjson.DeleteBytes(outputWithoutIDs, "2.id") request := []byte(`{"model":"gemini-3.6-flash-high","input":[]}`) request, _ = sjson.SetRawBytes(request, "input", outputWithoutIDs) - translated := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) + translated, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) var visibleParts []gjson.Result for _, part := range gjson.GetBytes(translated, "contents.0.parts").Array() { if !part.Get("thought").Bool() && part.Get("text").String() != "" { @@ -307,7 +307,7 @@ func TestConvertGeminiResponseToOpenAIResponses_SignedVisibleThenUnsignedPreserv } request := []byte(`{"model":"gemini-3.6-flash-high","input":[]}`) request, _ = sjson.SetRawBytes(request, "input", []byte(completed.Raw)) - translated := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) + translated, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) parts := gjson.GetBytes(translated, "contents.0.parts").Array() if len(parts) != 2 || parts[0].Get("text").String() != "signed" || parts[0].Get("thoughtSignature").String() != testResponsesGeminiThoughtSignature || parts[1].Get("text").String() != "unsigned" || parts[1].Get("thoughtSignature").String() != "" { t.Fatalf("signed/unsigned visible boundary changed: output=%s translated=%s", completed.Raw, translated) @@ -341,7 +341,7 @@ func TestConvertGeminiResponseToOpenAIResponses_LeadingCarrierDoesNotCrossSigned for name, output := range map[string]gjson.Result{"stream": streamOutput, "non-stream": gjson.GetBytes(nonStream, "output")} { request := []byte(`{"model":"gemini-3.6-flash-high","input":[]}`) request, _ = sjson.SetRawBytes(request, "input", []byte(output.Raw)) - translated := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) + translated, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) parts := gjson.GetBytes(translated, "contents.0.parts").Array() if len(parts) != 3 || !parts[0].Get("text").Exists() || parts[0].Get("text").String() != "" || parts[0].Get("thoughtSignature").String() != testResponsesGeminiThoughtSignature || parts[1].Get("text").String() != "reason" || !parts[1].Get("thought").Bool() || parts[1].Get("thoughtSignature").String() != signature2 || parts[2].Get("text").String() != "answer" || parts[2].Get("thoughtSignature").String() != "" { t.Fatalf("%s leading carrier crossed signed thought: output=%s translated=%s", name, output.Raw, translated) @@ -354,7 +354,7 @@ func TestConvertGeminiResponseToOpenAIResponsesNonStream_SignedVisibleThenUnsign out := ConvertGeminiResponseToOpenAIResponsesNonStream(context.Background(), "gemini-3.6-flash-high", nil, nil, raw, nil) request := []byte(`{"model":"gemini-3.6-flash-high","input":[]}`) request, _ = sjson.SetRawBytes(request, "input", []byte(gjson.GetBytes(out, "output").Raw)) - translated := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) + translated, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) parts := gjson.GetBytes(translated, "contents.0.parts").Array() if len(parts) != 2 || parts[0].Get("text").String() != "signed" || parts[0].Get("thoughtSignature").String() != testResponsesGeminiThoughtSignature || parts[1].Get("text").String() != "unsigned" || parts[1].Get("thoughtSignature").String() != "" { t.Fatalf("non-stream signed/unsigned visible boundary changed: output=%s translated=%s", gjson.GetBytes(out, "output").Raw, translated) @@ -367,7 +367,7 @@ func TestConvertGeminiResponseToOpenAIResponsesNonStream_TrailingCarrierDirectio out := ConvertGeminiResponseToOpenAIResponsesNonStream(context.Background(), "gemini-3.6-flash-high", nil, nil, raw, nil) request := []byte(`{"model":"gemini-3.6-flash-high","input":[]}`) request, _ = sjson.SetRawBytes(request, "input", []byte(gjson.GetBytes(out, "output").Raw)) - translated := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) + translated, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) parts := gjson.GetBytes(translated, "contents.0.parts").Array() if len(parts) != 2 || parts[0].Get("text").String() != "answer" || parts[0].Get("thoughtSignature").String() != testResponsesGeminiThoughtSignature || !parts[1].Get("text").Exists() || parts[1].Get("text").String() != "" || parts[1].Get("thoughtSignature").String() != signature2 { t.Fatalf("non-stream trailing carrier changed direction: output=%s translated=%s", gjson.GetBytes(out, "output").Raw, translated) @@ -393,7 +393,7 @@ func TestConvertGeminiResponseToOpenAIResponses_CachedTrailingCarrierPreservesDi } request := []byte(`{"model":"gemini-3.6-flash-high","input":[]}`) request, _ = sjson.SetRawBytes(request, "input", []byte(completed.Raw)) - translated := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) + translated, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) parts := gjson.GetBytes(translated, "contents.0.parts").Array() if len(parts) != 2 || parts[0].Get("text").String() != "answer" || parts[0].Get("thoughtSignature").String() != testResponsesGeminiThoughtSignature || !parts[1].Get("text").Exists() || parts[1].Get("text").String() != "" || parts[1].Get("thoughtSignature").String() != signature2 { t.Fatalf("Cached trailing carrier changed direction: output=%s translated=%s", completed.Raw, translated) @@ -440,7 +440,7 @@ func TestConvertGeminiResponseToOpenAIResponses_VisibleSignatureDoesNotOverwrite } request := []byte(`{"model":"gemini-3.6-flash-high","input":[]}`) request, _ = sjson.SetRawBytes(request, "input", []byte(completed.Raw)) - translated := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) + translated, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) var signatures []string visibleSignature := "" for _, part := range gjson.GetBytes(translated, "contents.0.parts").Array() { @@ -478,7 +478,7 @@ func TestConvertGeminiResponseToOpenAIResponses_FlushesVisibleSignatureBeforeLat if len(completed.Array()) != 3 || decodedResponsesCarrierSignature(t, completed.Get("0.encrypted_content").String()) != testResponsesGeminiThoughtSignature || completed.Get("1.type").String() != "message" || decodedResponsesCarrierSignature(t, completed.Get("2.encrypted_content").String()) != signature3 { t.Fatalf("visible signature crossed later thought: %s", completed.Raw) } - translated := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(`{"input":`+completed.Raw+`}`), false) + translated, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(`{"input":`+completed.Raw+`}`), false) if gjson.GetBytes(translated, "contents.0.parts.1.text").String() != "answer" || gjson.GetBytes(translated, "contents.0.parts.1.thoughtSignature").String() != signature2 || gjson.GetBytes(translated, "contents.0.parts.2.text").String() != "thought-c" { t.Fatalf("cached visible signature crossed later thought on replay: %s", translated) } @@ -503,7 +503,7 @@ func TestConvertGeminiResponseToOpenAIResponses_FunctionAndTrailingSignaturesRou } request := []byte(`{"model":"gemini-3.6-flash-high","input":[]}`) request, _ = sjson.SetRawBytes(request, "input", []byte(completed.Raw)) - translated := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) + translated, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) var signatures []string for _, content := range gjson.GetBytes(translated, "contents").Array() { for _, part := range content.Get("parts").Array() { @@ -552,7 +552,7 @@ func TestConvertGeminiResponseToOpenAIResponses_FunctionThenTrailingSignatureHas } request := []byte(`{"model":"gemini-3.6-flash-high","input":[]}`) request, _ = sjson.SetRawBytes(request, "input", []byte(output.Raw)) - translated := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) + translated, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) parts := gjson.GetBytes(translated, "contents.0.parts").Array() if len(parts) != 2 || parts[0].Get("text").String() != "preamble" || parts[1].Get("functionCall.name").String() != "run_command" || parts[1].Get("thoughtSignature").String() != testResponsesGeminiThoughtSignature { t.Fatalf("%s trailing function signature did not replay: %s", name, translated) @@ -633,7 +633,7 @@ func TestConvertGeminiResponseToOpenAIResponses_LeadingEmptyAndSignedTextRoundTr } request := []byte(`{"model":"gemini-3.6-flash-high","input":[]}`) request, _ = sjson.SetRawBytes(request, "input", []byte(completed.Raw)) - translated := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) + translated, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) var signatures []string visibleSignature := "" for _, part := range gjson.GetBytes(translated, "contents.0.parts").Array() { @@ -671,7 +671,7 @@ func TestConvertGeminiResponseToOpenAIResponses_SignedTextAndTrailingSignatureRo } request := []byte(`{"model":"gemini-3.6-flash-high","input":[]}`) request, _ = sjson.SetRawBytes(request, "input", []byte(completed.Raw)) - translated := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) + translated, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) var signatures []string for _, part := range gjson.GetBytes(translated, "contents.0.parts").Array() { if signature := part.Get("thoughtSignature").String(); signature != "" { @@ -949,7 +949,7 @@ func TestConvertGeminiResponseToOpenAIResponses_PreservesTextAroundFunction(t *t functionOutput := []byte(`{"type":"function_call_output","call_id":"","output":"ok"}`) functionOutput, _ = sjson.SetBytes(functionOutput, "call_id", completed.Get("1.call_id").String()) request, _ = sjson.SetRawBytes(request, "input.-1", functionOutput) - translated := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) + translated, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) contents := gjson.GetBytes(translated, "contents").Array() if len(contents) != 2 || contents[0].Get("role").String() != "model" || contents[1].Get("role").String() != "user" { t.Fatalf("mixed turn round-trip roles malformed: %s", translated) @@ -998,7 +998,7 @@ func TestConvertGeminiResponseToOpenAIResponses_PendingSignatureBeforeFunctionRo functionOutput := []byte(`{"type":"function_call_output","call_id":"","output":"ok"}`) functionOutput, _ = sjson.SetBytes(functionOutput, "call_id", callID) request, _ = sjson.SetRawBytes(request, "input.-1", functionOutput) - translated := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) + translated, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) functionSignature := "" detachedSignatures := 0 @@ -1045,7 +1045,7 @@ func TestConvertGeminiResponseToOpenAIResponses_SignedTextBeforeSignedFunctionRo functionOutput := []byte(`{"type":"function_call_output","call_id":"","output":"ok"}`) functionOutput, _ = sjson.SetBytes(functionOutput, "call_id", callID) request, _ = sjson.SetRawBytes(request, "input.-1", functionOutput) - translated := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) + translated, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", request, false) var textSignature, functionSignature string for _, content := range gjson.GetBytes(translated, "contents").Array() { @@ -1107,7 +1107,7 @@ func TestConvertGeminiResponseToOpenAIResponses_CachesSignatureAfterVisibleText( if got := strings.Join(doneTypes, ","); got != "message" || len(completedOutput.Array()) != 1 { t.Fatalf("unexpected client timeline: done=%s output=%s", got, completedOutput.Raw) } - translated := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(`{"input":`+completedOutput.Raw+`}`), false) + translated, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.6-flash-high", []byte(`{"input":`+completedOutput.Raw+`}`), false) if gjson.GetBytes(translated, "contents.0.parts.0.thoughtSignature").String() != testResponsesGeminiThoughtSignature { t.Fatalf("cached signature was not replayed: %s", translated) } diff --git a/internal/translator/gemini/openai/responses/gemini_openai-responses_user_turn_test.go b/internal/translator/gemini/openai/responses/gemini_openai-responses_user_turn_test.go index e702146363b..e743f86daa0 100644 --- a/internal/translator/gemini/openai/responses/gemini_openai-responses_user_turn_test.go +++ b/internal/translator/gemini/openai/responses/gemini_openai-responses_user_turn_test.go @@ -63,7 +63,7 @@ func TestConvertOpenAIResponsesRequestToGemini_RefusesAnyEmptiedUserTurn(t *test } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - body, err := ConvertOpenAIResponsesRequestToGeminiReturningError("gemini-3-pro", tc.input, false) + body, err := ConvertOpenAIResponsesRequestToGemini("gemini-3-pro", tc.input, false) var unsupported *translatorcommon.UnsupportedPartError if !errors.As(err, &unsupported) || unsupported.Type != "input_file" || unsupported.StatusCode() != 400 { t.Fatalf("err = %v, want unsupported content part: input_file; body = %s", err, body) @@ -86,7 +86,7 @@ func TestConvertOpenAIResponsesRequestToGemini_RefusesAnyEmptiedUserTurn(t *test func TestConvertOpenAIResponsesRequestToGemini_KeepsTurnWithTextBesideFileID(t *testing.T) { input := geminiTurnPayload("", geminiTurnHello, geminiTurnAssistant, geminiUserTurn(geminiTurnText, geminiTurnFileID)) - body, err := ConvertOpenAIResponsesRequestToGeminiReturningError("gemini-3-pro", input, false) + body, err := ConvertOpenAIResponsesRequestToGemini("gemini-3-pro", input, false) if err != nil { t.Fatalf("err = %v", err) } @@ -107,7 +107,7 @@ func TestConvertOpenAIResponsesRequestToGemini_InlineAndRemoteFilesStayParts(t * for name, tc := range cases { t.Run(name, func(t *testing.T) { input := geminiTurnPayload("", geminiTurnHello, geminiTurnAssistant, geminiUserTurn(tc.part)) - body, err := ConvertOpenAIResponsesRequestToGeminiReturningError("gemini-3-pro", input, false) + body, err := ConvertOpenAIResponsesRequestToGemini("gemini-3-pro", input, false) if err != nil { t.Fatalf("err = %v", err) } @@ -120,7 +120,7 @@ func TestConvertOpenAIResponsesRequestToGemini_InlineAndRemoteFilesStayParts(t * func TestConvertOpenAIResponsesRequestToGemini_ExportedWrapperKeepsAJSONBody(t *testing.T) { input := geminiTurnPayload("", geminiUserTurn(geminiTurnFileID)) - if body := ConvertOpenAIResponsesRequestToGemini("gemini-3-pro", input, false); !gjson.ValidBytes(body) { + if body, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3-pro", input, false); !gjson.ValidBytes(body) { t.Fatalf("body is not JSON: %q", body) } } diff --git a/internal/translator/gemini/openai/responses/gemini_openai-responses_web_search_test.go b/internal/translator/gemini/openai/responses/gemini_openai-responses_web_search_test.go index 03f732701fa..d06faac0b63 100644 --- a/internal/translator/gemini/openai/responses/gemini_openai-responses_web_search_test.go +++ b/internal/translator/gemini/openai/responses/gemini_openai-responses_web_search_test.go @@ -74,7 +74,7 @@ func TestConvertOpenAIResponsesRequestToGemini_WebSearchCapabilityGate(t *testin }`) // Capable model should receive googleSearch tool - capableOut := ConvertOpenAIResponsesRequestToGemini(capableModel, req, false) + capableOut, _ := ConvertOpenAIResponsesRequestToGemini(capableModel, req, false) toolsCapable := gjson.GetBytes(capableOut, "tools").Array() foundGoogleSearch := false for _, tool := range toolsCapable { @@ -88,7 +88,7 @@ func TestConvertOpenAIResponsesRequestToGemini_WebSearchCapabilityGate(t *testin } // Incapable model must NOT receive googleSearch tool - incapableOut := ConvertOpenAIResponsesRequestToGemini(incapableModel, req, false) + incapableOut, _ := ConvertOpenAIResponsesRequestToGemini(incapableModel, req, false) toolsIncapable := gjson.GetBytes(incapableOut, "tools") if toolsIncapable.Exists() { for _, tool := range toolsIncapable.Array() { @@ -114,7 +114,7 @@ func TestConvertOpenAIResponsesRequestToGemini_WebSearchAllowedDomains(t *testin }] }`) - out := ConvertOpenAIResponsesRequestToGemini(modelID, req, false) + out, _ := ConvertOpenAIResponsesRequestToGemini(modelID, req, false) domains := gjson.GetBytes(out, "tools.0.googleSearch.includedDomains").Array() if len(domains) != 2 { t.Fatalf("expected 2 includedDomains, got %d: %s", len(domains), out) @@ -135,7 +135,7 @@ func TestConvertOpenAIResponsesRequestToGemini_WebSearchToolChoiceNoneSuppresses "tool_choice": "none" }`) - out := ConvertOpenAIResponsesRequestToGemini(modelID, req, false) + out, _ := ConvertOpenAIResponsesRequestToGemini(modelID, req, false) if tools := gjson.GetBytes(out, "tools"); tools.Exists() { for _, tool := range tools.Array() { if tool.Get("googleSearch").Exists() { @@ -400,7 +400,7 @@ func TestConvertOpenAIResponsesRequestToGemini_WebSearchOnlyToolChoiceRequiredNo "tool_choice": "required" }`) - out := ConvertOpenAIResponsesRequestToGemini(modelID, req, false) + out, _ := ConvertOpenAIResponsesRequestToGemini(modelID, req, false) parsed := gjson.ParseBytes(out) // googleSearch should be present @@ -712,7 +712,7 @@ func TestConvertOpenAIResponsesRequestToGemini_WebSearchPreview20250311(t *testi "tool_choice": {"type": "web_search_preview_2025_03_11"} }`) - out := ConvertOpenAIResponsesRequestToGemini(modelID, req, false) + out, _ := ConvertOpenAIResponsesRequestToGemini(modelID, req, false) if !gjson.GetBytes(out, "tools.0.googleSearch").Exists() { t.Fatalf("expected googleSearch tool for web_search_preview_2025_03_11 declaration and tool_choice, got: %s", out) } @@ -5000,7 +5000,7 @@ func TestConvertGeminiResponseToOpenAIResponsesStream_WebSearchBufferingSignatur // Translate the completed response outputs back to Gemini request to verify signature binding. replayReq := []byte(`{"model":"gemini-search-sig-boundary-buffering","input":[]}`) replayReq, _ = sjson.SetRawBytes(replayReq, "input", []byte(completedJSON.Get("response.output").Raw)) - translated := ConvertOpenAIResponsesRequestToGemini("gemini-search-sig-boundary-buffering", replayReq, false) + translated, _ := ConvertOpenAIResponsesRequestToGemini("gemini-search-sig-boundary-buffering", replayReq, false) var visibleParts []gjson.Result for _, part := range gjson.GetBytes(translated, "contents.0.parts").Array() { diff --git a/internal/translator/gemini/openai/responses/init.go b/internal/translator/gemini/openai/responses/init.go index 062494550c0..5917810fb01 100644 --- a/internal/translator/gemini/openai/responses/init.go +++ b/internal/translator/gemini/openai/responses/init.go @@ -4,18 +4,16 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" - sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( OpenaiResponse, Gemini, - nil, + ConvertOpenAIResponsesRequestToGemini, interfaces.TranslateResponse{ Stream: ConvertGeminiResponseToOpenAIResponses, NonStream: ConvertGeminiResponseToOpenAIResponsesNonStream, }, ) - sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatOpenAIResponse, sdktranslator.FormatGemini, convertOpenAIResponsesRequestToGemini) } diff --git a/internal/translator/gemini/openai/responses/noop_optimization_test.go b/internal/translator/gemini/openai/responses/noop_optimization_test.go index 255ab295e2d..e78bd85c66b 100644 --- a/internal/translator/gemini/openai/responses/noop_optimization_test.go +++ b/internal/translator/gemini/openai/responses/noop_optimization_test.go @@ -9,7 +9,7 @@ import ( func TestConvertOpenAIResponsesRequestToGeminiBuildsGenerationConfigWithoutIntermediateObject(t *testing.T) { input := []byte(`{"input":"hello","temperature":0.5,"top_p":0.9,"stop_sequences":["done"],"text":{"format":{"type":"json_schema","schema":{"type":"object"}}}}`) - output := ConvertOpenAIResponsesRequestToGemini("gemini-test", input, false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-test", input, false) if got := gjson.GetBytes(output, "generationConfig.temperature").Float(); got != 0.5 { t.Fatalf("temperature = %v, want 0.5", got) diff --git a/internal/translator/gemini/openai/responses/signature_carrier_test.go b/internal/translator/gemini/openai/responses/signature_carrier_test.go index 86391f2940f..515047cbd2d 100644 --- a/internal/translator/gemini/openai/responses/signature_carrier_test.go +++ b/internal/translator/gemini/openai/responses/signature_carrier_test.go @@ -39,7 +39,7 @@ func TestNormalizeGeminiResponsesCarriersDropsMalformedEnvelope(t *testing.T) { func TestConvertOpenAIResponsesRequestToGemini_DecodesCarrierForAliasModel(t *testing.T) { carrier := encodeGeminiResponsesCarrier(testResponsesGeminiThoughtSignature, geminiResponsesCarrierNext, geminiResponsesCarrierText) request := []byte(`{"model":"alias-without-provider-name","input":[{"type":"reasoning","encrypted_content":"` + carrier + `","summary":[]},{"type":"message","role":"assistant","content":[{"type":"output_text","text":"answer"}]}]}`) - translated := ConvertOpenAIResponsesRequestToGemini("alias-without-provider-name", request, false) + translated, _ := ConvertOpenAIResponsesRequestToGemini("alias-without-provider-name", request, false) part := gjson.GetBytes(translated, "contents.0.parts.0") if part.Get("text").String() != "answer" || part.Get("thoughtSignature").String() != testResponsesGeminiThoughtSignature || strings.Contains(string(translated), geminiResponsesCarrierPrefix) { t.Fatalf("alias model did not decode carrier: %s", translated) @@ -83,7 +83,7 @@ func TestGeminiResponsesWrappedUUIDFunctionSignatureRoundTrip(t *testing.T) { clientItems = append(clientItems, `{"type":"function_call_output","call_id":`+strconv.Quote(callID)+`,"output":"ok"}`) request := []byte(`{"model":"alias-without-provider-name","input":[` + strings.Join(clientItems, ",") + `]}`) - translated := ConvertOpenAIResponsesRequestToGemini("alias-without-provider-name", request, false) + translated, _ := ConvertOpenAIResponsesRequestToGemini("alias-without-provider-name", request, false) var functionPart gjson.Result gjson.GetBytes(translated, "contents").ForEach(func(_, content gjson.Result) bool { content.Get("parts").ForEach(func(_, part gjson.Result) bool { @@ -108,7 +108,7 @@ func TestGeminiResponsesWrappedUUIDFunctionSignatureRoundTrip(t *testing.T) { func TestConvertOpenAIResponsesRequestToGemini_DecodesLegacyRawCarrierForAliasModel(t *testing.T) { request := []byte(`{"model":"alias-without-provider-name","input":[{"type":"reasoning","encrypted_content":"` + testResponsesGeminiThoughtSignature + `","summary":[]},{"type":"function_call","call_id":"call-1","name":"run","arguments":"{}"}]}`) - translated := ConvertOpenAIResponsesRequestToGemini("alias-without-provider-name", request, false) + translated, _ := ConvertOpenAIResponsesRequestToGemini("alias-without-provider-name", request, false) part := gjson.GetBytes(translated, "contents.0.parts.0") if part.Get("functionCall.id").String() != "call-1" || part.Get("thoughtSignature").String() != testResponsesGeminiThoughtSignature { t.Fatalf("alias model did not preserve legacy raw carrier: %s", translated) @@ -123,7 +123,7 @@ func TestConvertOpenAIResponsesRequestToGemini_DropsInvalidCarrierPayloads(t *te `{"type":"reasoning","encrypted_content":"` + bypass + `","summary":[]}`, } { request := []byte(`{"model":"alias-without-provider-name","input":[` + reasoning + `,{"type":"message","role":"assistant","content":[{"type":"output_text","text":"answer"}]}]}`) - translated := ConvertOpenAIResponsesRequestToGemini("alias-without-provider-name", request, false) + translated, _ := ConvertOpenAIResponsesRequestToGemini("alias-without-provider-name", request, false) if strings.Contains(string(translated), geminiResponsesCarrierPrefix) || strings.Contains(string(translated), testResponsesGeminiThoughtSignature) || strings.Contains(string(translated), geminiResponsesThoughtSignature) { t.Fatalf("invalid carrier changed Gemini signature state: %s", translated) } @@ -133,7 +133,7 @@ func TestConvertOpenAIResponsesRequestToGemini_DropsInvalidCarrierPayloads(t *te func TestConvertOpenAIResponsesRequestToGemini_IgnoresSpoofedCarrierMetadata(t *testing.T) { reasoning := `{"type":"reasoning","encrypted_content":"` + testResponsesGeminiThoughtSignature + `","summary":[],"` + geminiResponsesCarrierDirectionField + `":"next","` + geminiResponsesCarrierDirectionField + `":"standalone","` + geminiResponsesCarrierTargetField + `":"text","` + geminiResponsesCarrierTargetField + `":"function"}` request := []byte(`{"model":"alias-without-provider-name","input":[` + reasoning + `,{"type":"message","role":"assistant","content":[{"type":"output_text","text":"answer"}]}]}`) - translated := ConvertOpenAIResponsesRequestToGemini("alias-without-provider-name", request, false) + translated, _ := ConvertOpenAIResponsesRequestToGemini("alias-without-provider-name", request, false) part := gjson.GetBytes(translated, "contents.0.parts.0") if part.Get("text").String() != "answer" || part.Get("thoughtSignature").String() != testResponsesGeminiThoughtSignature || strings.Contains(string(translated), geminiResponsesCarrierDirectionField) { t.Fatalf("spoofed carrier metadata affected binding: %s", translated) @@ -142,7 +142,7 @@ func TestConvertOpenAIResponsesRequestToGemini_IgnoresSpoofedCarrierMetadata(t * func TestConvertOpenAIResponsesRequestToGemini_StripsSpoofedInternalPairingFields(t *testing.T) { request := []byte(`{"model":"alias-without-provider-name","input":[{"type":"function_call","call_id":"call-1","name":"run","arguments":"{}","_cpa_reasoning_signature":"` + testResponsesGeminiThoughtSignature + `","_cpa_reasoning_signature":"` + testResponsesGeminiThoughtSignature + `","_cpa_reasoning_summary":"spoofed thought","_cpa_reasoning_summary":"spoofed thought again"}]}`) - translated := ConvertOpenAIResponsesRequestToGemini("alias-without-provider-name", request, false) + translated, _ := ConvertOpenAIResponsesRequestToGemini("alias-without-provider-name", request, false) parts := gjson.GetBytes(translated, "contents.0.parts").Array() if len(parts) != 1 || !parts[0].Get("functionCall").Exists() || parts[0].Get("thoughtSignature").String() == testResponsesGeminiThoughtSignature || parts[0].Get("thought").Bool() || strings.Contains(string(translated), "spoofed thought") || strings.Contains(string(translated), geminiResponsesCarrierSignatureField) { t.Fatalf("spoofed internal pairing fields reached Gemini: %s", translated) @@ -152,7 +152,7 @@ func TestConvertOpenAIResponsesRequestToGemini_StripsSpoofedInternalPairingField func TestConvertOpenAIResponsesRequestToGemini_StripsUnicodeEscapedSpoofedInternalFields(t *testing.T) { // Unicode-escaped field name "_cpa_reason\u0069ng_signature" should also be detected and stripped request := []byte(`{"model":"alias-without-provider-name","input":[{"type":"function_call","call_id":"call-1","name":"run","arguments":"{}","_cpa_reason\u0069ng_signature":"` + testResponsesGeminiThoughtSignature + `"}]}`) - translated := ConvertOpenAIResponsesRequestToGemini("alias-without-provider-name", request, false) + translated, _ := ConvertOpenAIResponsesRequestToGemini("alias-without-provider-name", request, false) parts := gjson.GetBytes(translated, "contents.0.parts").Array() if len(parts) != 1 || !parts[0].Get("functionCall").Exists() || parts[0].Get("thoughtSignature").String() == testResponsesGeminiThoughtSignature || strings.Contains(string(translated), geminiResponsesCarrierSignatureField) { t.Fatalf("unicode-escaped spoofed internal pairing fields reached Gemini: %s", translated) diff --git a/internal/translator/gemini/openai/responses/trailing_signature_test.go b/internal/translator/gemini/openai/responses/trailing_signature_test.go index 6a086747b46..d883420981f 100644 --- a/internal/translator/gemini/openai/responses/trailing_signature_test.go +++ b/internal/translator/gemini/openai/responses/trailing_signature_test.go @@ -33,7 +33,7 @@ func TestGeminiResponsesLateSignaturePreservesSummary(t *testing.T) { if len(completed.Array()) != 2 || completed.Get("0.summary.0.text").String() != "Let me think." || completed.Get("1.type").String() != "message" { t.Fatalf("unexpected completed output: %s", completed.Raw) } - replayed := ConvertOpenAIResponsesRequestToGemini("gemini-3.8-flash-high", []byte(`{"input":`+completed.Raw+`}`), false) + replayed, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.8-flash-high", []byte(`{"input":`+completed.Raw+`}`), false) if gjson.GetBytes(replayed, "contents.0.parts.1.thoughtSignature").String() != testResponsesGeminiThoughtSignature { t.Fatalf("late text signature was not restored: %s", replayed) } @@ -61,7 +61,7 @@ func TestGeminiResponsesCachedTextSignatureReplayBoundaries(t *testing.T) { } { t.Run(testCase.name, func(t *testing.T) { request := []byte(`{"input":[` + testCase.message + `]}`) - output := ConvertOpenAIResponsesRequestToGemini(testCase.model, request, false) + output, _ := ConvertOpenAIResponsesRequestToGemini(testCase.model, request, false) got := strings.Contains(string(output), testResponsesGeminiThoughtSignature) if got != testCase.wantSignature { t.Fatalf("signature restored=%v, want %v: %s", got, testCase.wantSignature, output) @@ -71,7 +71,7 @@ func TestGeminiResponsesCachedTextSignatureReplayBoundaries(t *testing.T) { carrier := []byte(`{"type":"reasoning","summary":[]}`) carrier, _ = sjson.SetBytes(carrier, "encrypted_content", encodeGeminiResponsesCarrier(testResponsesGeminiThoughtSignature, geminiResponsesCarrierPrevious, geminiResponsesCarrierText)) request := []byte(`{"input":[` + message + `,` + string(carrier) + `]}`) - output := ConvertOpenAIResponsesRequestToGemini(model, request, false) + output, _ := ConvertOpenAIResponsesRequestToGemini(model, request, false) if strings.Count(string(output), testResponsesGeminiThoughtSignature) != 1 { t.Fatalf("explicit carrier duplicated cached signature: %s", output) } @@ -109,7 +109,7 @@ func TestGeminiResponsesLateSignatureReplayWithThinkingSuffix(t *testing.T) { completed = data.Get("response.output") } } - output := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-pro", []byte(`{"input":`+completed.Raw+`}`), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-2.5-pro", []byte(`{"input":`+completed.Raw+`}`), false) if gjson.GetBytes(output, "contents.0.parts.0.thoughtSignature").String() != testResponsesGeminiThoughtSignature { t.Fatalf("executor base model could not restore suffixed response signature: %s", output) } @@ -126,7 +126,7 @@ func TestGeminiResponsesCachedSignaturesMergeExplicitPrefixInOrder(t *testing.T) carrier := []byte(`{"type":"reasoning","summary":[]}`) carrier, _ = sjson.SetBytes(carrier, "encrypted_content", encodeGeminiResponsesCarrier(explicitSignature, geminiResponsesCarrierPrevious, geminiResponsesCarrierText)) request := []byte(`{"input":[{"id":"` + messageID + `","type":"message","role":"assistant","content":[{"type":"output_text","text":"answer"}]},` + string(carrier) + `]}`) - output := ConvertOpenAIResponsesRequestToGemini(model, request, false) + output, _ := ConvertOpenAIResponsesRequestToGemini(model, request, false) parts := gjson.GetBytes(output, "contents.0.parts").Array() if len(parts) != 2 || parts[0].Get("text").String() != "answer" || parts[0].Get("thoughtSignature").String() != testResponsesGeminiThoughtSignature || parts[1].Get("thoughtSignature").String() != signature2 { t.Fatalf("partial explicit carrier changed cached signature order: %s", output) @@ -152,7 +152,7 @@ func TestGeminiResponsesLateThoughtSignatureDoesNotBindEarlierMessage(t *testing } } } - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.8-flash-high", []byte(`{"input":`+completed.Raw+`}`), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.8-flash-high", []byte(`{"input":`+completed.Raw+`}`), false) parts := gjson.GetBytes(output, "contents.0.parts").Array() if len(parts) < 2 || parts[0].Get("thoughtSignature").String() != "" || parts[1].Get("thoughtSignature").String() != testResponsesGeminiThoughtSignature || !strings.Contains(string(output), signature2) { t.Fatalf("late thought signature rebound to the earlier message: %s", output) @@ -189,7 +189,7 @@ func TestGeminiResponsesCacheRecoveryPreservesFallbackSignatureOrder(t *testing. if len(completed.Array()) != 2 || decodedResponsesCarrierSignature(t, completed.Get("1.encrypted_content").String()) != testResponsesGeminiThoughtSignature { t.Fatalf("expected only the first write's fallback carrier: %s", completed.Raw) } - output := ConvertOpenAIResponsesRequestToGemini("gemini-3.8-flash-high", []byte(`{"input":`+completed.Raw+`}`), false) + output, _ := ConvertOpenAIResponsesRequestToGemini("gemini-3.8-flash-high", []byte(`{"input":`+completed.Raw+`}`), false) parts := gjson.GetBytes(output, "contents.0.parts").Array() if len(parts) != 2 || parts[0].Get("thoughtSignature").String() != testResponsesGeminiThoughtSignature || parts[1].Get("thoughtSignature").String() != signature2 { t.Fatalf("cache recovery changed fallback signature order: %s", output) diff --git a/internal/translator/interactions/claude/init.go b/internal/translator/interactions/claude/init.go index 93ccc6311b3..502f1530c40 100644 --- a/internal/translator/interactions/claude/init.go +++ b/internal/translator/interactions/claude/init.go @@ -4,20 +4,16 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" - sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( Claude, Interactions, - nil, + ConvertClaudeRequestToInteractions, interfaces.TranslateResponse{ Stream: ConvertInteractionsResponseToClaude, NonStream: ConvertInteractionsResponseToClaudeNonStream, }, ) - sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatClaude, sdktranslator.FormatInteractions, func(model string, body []byte, stream bool) ([]byte, error) { - return convertClaudeRequestToInteractions(model, body, stream, false) - }) } diff --git a/internal/translator/interactions/claude/interactions_claude_compat_test.go b/internal/translator/interactions/claude/interactions_claude_compat_test.go index b12bd707450..5d70ebda141 100644 --- a/internal/translator/interactions/claude/interactions_claude_compat_test.go +++ b/internal/translator/interactions/claude/interactions_claude_compat_test.go @@ -9,12 +9,12 @@ import ( func TestConvertClaudeRequestToInteractionsWithCompatPreservesEmptyThinking(t *testing.T) { payload := []byte(`{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"","signature":""}]}]}`) - withoutCompat := ConvertClaudeRequestToInteractions("deepseek-v4", payload, false) + withoutCompat, _ := ConvertClaudeRequestToInteractions("deepseek-v4", payload, false) if gjson.GetBytes(withoutCompat, "input.#").Int() != 0 { t.Fatalf("default translation preserved empty thinking: %s", withoutCompat) } - withCompat := ConvertClaudeRequestToInteractionsWithCompat("deepseek-v4", payload, false) + withCompat, _ := ConvertClaudeRequestToInteractionsWithCompat("deepseek-v4", payload, false) if gjson.GetBytes(withCompat, "input.0.type").String() != "thought" { t.Fatalf("compat translation missing thought step: %s", withCompat) } diff --git a/internal/translator/interactions/claude/interactions_claude_request.go b/internal/translator/interactions/claude/interactions_claude_request.go index 9fa81344dc8..4c8f9857658 100644 --- a/internal/translator/interactions/claude/interactions_claude_request.go +++ b/internal/translator/interactions/claude/interactions_claude_request.go @@ -8,20 +8,14 @@ import ( "github.com/tidwall/sjson" ) -func ConvertClaudeRequestToInteractions(modelName string, inputRawJSON []byte, stream bool) []byte { - body, _ := convertClaudeRequestToInteractions(modelName, inputRawJSON, stream, false) - return body +func ConvertClaudeRequestToInteractions(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { + return convertClaudeRequestToInteractions(modelName, inputRawJSON, stream, false) + } // ConvertClaudeRequestToInteractionsWithCompat preserves empty assistant // thinking blocks for configured compatibility endpoints. -func ConvertClaudeRequestToInteractionsWithCompat(modelName string, inputRawJSON []byte, stream bool) []byte { - body, _ := convertClaudeRequestToInteractions(modelName, inputRawJSON, stream, true) - return body -} - -// ConvertClaudeRequestToInteractionsWithCompatReturningError reports a file part the target cannot represent. -func ConvertClaudeRequestToInteractionsWithCompatReturningError(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { +func ConvertClaudeRequestToInteractionsWithCompat(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { return convertClaudeRequestToInteractions(modelName, inputRawJSON, stream, true) } diff --git a/internal/translator/interactions/claude/interactions_claude_test.go b/internal/translator/interactions/claude/interactions_claude_test.go index 36fec9f3d48..2c1494ab901 100644 --- a/internal/translator/interactions/claude/interactions_claude_test.go +++ b/internal/translator/interactions/claude/interactions_claude_test.go @@ -11,7 +11,7 @@ import ( func TestConvertClaudeRequestToInteractionsMapsMessagesToolsAndStream(t *testing.T) { raw := []byte(`{"model":"gemini-3.1-flash-lite","stream":true,"max_tokens":1024,"tools":[{"name":"get_weather","description":"Weather","input_schema":{"type":"object","properties":{"location":{"type":"string"}},"required":["location"]}}],"messages":[{"role":"user","content":[{"type":"text","text":"今天北京的天气怎么样?"}]}]}`) - out := ConvertClaudeRequestToInteractions("gemini-3.1-flash-lite", raw, true) + out, _ := ConvertClaudeRequestToInteractions("gemini-3.1-flash-lite", raw, true) if got := gjson.GetBytes(out, "model").String(); got != "gemini-3.1-flash-lite" { t.Fatalf("model = %q, want gemini-3.1-flash-lite. Output: %s", got, string(out)) } @@ -37,7 +37,7 @@ func TestConvertClaudeRequestToInteractionsMapsMessagesToolsAndStream(t *testing func TestConvertClaudeRequestToInteractionsMapsToolUseAndResult(t *testing.T) { raw := []byte(`{"model":"gemini-3.1-flash-lite","messages":[{"role":"assistant","content":[{"type":"tool_use","id":"toolu_1","name":"get_weather","input":{"location":"北京"}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"晴"}]}]}`) - out := ConvertClaudeRequestToInteractions("gemini-3.1-flash-lite", raw, false) + out, _ := ConvertClaudeRequestToInteractions("gemini-3.1-flash-lite", raw, false) if got := gjson.GetBytes(out, "input.0.type").String(); got != "function_call" { t.Fatalf("input.0.type = %q, want function_call. Output: %s", got, string(out)) } @@ -84,7 +84,7 @@ func TestConvertClaudeRequestToInteractionsInfersToolNamesForOutOfOrderResults(t } ] }`) - out := ConvertClaudeRequestToInteractions("gemini-3.1-flash-lite", raw, false) + out, _ := ConvertClaudeRequestToInteractions("gemini-3.1-flash-lite", raw, false) // Since AlignClaudeToolResults aligns tool results with tool_use order (toolu_1 then toolu_2): // input.0: function_call toolu_1 (lookup) // input.1: function_call toolu_2 (weather) @@ -106,7 +106,7 @@ func TestConvertClaudeRequestToInteractionsInfersToolNamesForOutOfOrderResults(t func TestConvertClaudeRequestToInteractionsPropagatesIsError(t *testing.T) { raw := []byte(`{"model":"gemini-3.1-flash-lite","messages":[{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_err","content":"command failed","is_error":true}]}]}`) - out := ConvertClaudeRequestToInteractions("gemini-3.1-flash-lite", raw, false) + out, _ := ConvertClaudeRequestToInteractions("gemini-3.1-flash-lite", raw, false) if !gjson.GetBytes(out, "input.0.is_error").Bool() { t.Fatalf("expected input.0.is_error = true. Output: %s", string(out)) } @@ -141,7 +141,7 @@ func TestConvertClaudeRequestToInteractions_PreservesToolAdjacencyWithIntervenin } ] }`) - out := ConvertClaudeRequestToInteractions("gemini-3.1-flash-lite", raw, false) + out, _ := ConvertClaudeRequestToInteractions("gemini-3.1-flash-lite", raw, false) inputs := gjson.GetBytes(out, "input").Array() // Expected types: @@ -581,7 +581,7 @@ func TestConvertClaudeRequestToInteractionsPreservesImagesInToolResult(t *testin ] }`) - out := ConvertClaudeRequestToInteractions("devin/swe-2", raw, false) + out, _ := ConvertClaudeRequestToInteractions("devin/swe-2", raw, false) res := gjson.GetBytes(out, "input.1.result") if !res.IsArray() { t.Fatalf("expected input.1.result to be array, got: %s", res.Raw) @@ -630,7 +630,7 @@ func TestConvertClaudeRequestToInteractionsPreservesBusinessObjectsInToolResultA ] }`) - out := ConvertClaudeRequestToInteractions("devin/swe-2", raw, false) + out, _ := ConvertClaudeRequestToInteractions("devin/swe-2", raw, false) res := gjson.GetBytes(out, "input.0.result") if !res.IsArray() { t.Fatalf("expected input.0.result to be array, got: %s", res.Raw) diff --git a/internal/translator/interactions/claude/interactions_claude_user_turn_test.go b/internal/translator/interactions/claude/interactions_claude_user_turn_test.go index c42ec878342..dd0af55807c 100644 --- a/internal/translator/interactions/claude/interactions_claude_user_turn_test.go +++ b/internal/translator/interactions/claude/interactions_claude_user_turn_test.go @@ -41,7 +41,7 @@ func TestConvertClaudeRequestToInteractions_RefusesAnyEmptiedUserTurn(t *testing } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - body, err := ConvertClaudeRequestToInteractionsWithCompatReturningError("m", []byte(tc.input), false) + body, err := ConvertClaudeRequestToInteractionsWithCompat("m", []byte(tc.input), false) var unsupported *translatorcommon.UnsupportedPartError if !errors.As(err, &unsupported) || unsupported.Type != tc.wantType || unsupported.StatusCode() != 400 { t.Fatalf("err = %v, want unsupported content part: %s; body = %s", err, tc.wantType, body) @@ -58,7 +58,7 @@ func TestConvertClaudeRequestToInteractions_RefusesAnyEmptiedUserTurn(t *testing func TestConvertClaudeRequestToInteractions_KeepsTurnWithTextBesideAttachment(t *testing.T) { input := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"text","text":"keep me"},` + userTurnUpload + `]}]}`) - body, err := ConvertClaudeRequestToInteractionsWithCompatReturningError("m", input, false) + body, err := ConvertClaudeRequestToInteractionsWithCompat("m", input, false) if err != nil { t.Fatalf("err = %v", err) } @@ -69,7 +69,7 @@ func TestConvertClaudeRequestToInteractions_KeepsTurnWithTextBesideAttachment(t func TestConvertClaudeRequestToInteractions_Base64DocumentAfterHistoryStaysMedia(t *testing.T) { input := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"document","source":{"type":"base64","media_type":"application/pdf","data":"JVBERi0xLjQK"}}]}]}`) - body, err := ConvertClaudeRequestToInteractionsWithCompatReturningError("m", input, false) + body, err := ConvertClaudeRequestToInteractionsWithCompat("m", input, false) if err != nil { t.Fatalf("err = %v", err) } @@ -92,7 +92,7 @@ func TestConvertClaudeRequestToInteractions_WhitespaceTextDoesNotHideAnUnreprese for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { input := []byte(`{"model":"m","messages":[{"role":"user","content":[` + tc.parts + `]}]}`) - body, err := ConvertClaudeRequestToInteractionsWithCompatReturningError("m", input, false) + body, err := ConvertClaudeRequestToInteractionsWithCompat("m", input, false) var unsupported *translatorcommon.UnsupportedPartError if !errors.As(err, &unsupported) || unsupported.Type != "image" || unsupported.StatusCode() != 400 { t.Fatalf("err = %v, want unsupported content part: image; body = %s", err, body) @@ -103,7 +103,7 @@ func TestConvertClaudeRequestToInteractions_WhitespaceTextDoesNotHideAnUnreprese func TestConvertClaudeRequestToInteractions_RealTextBesideWhitespaceAndAnImageStillSucceeds(t *testing.T) { input := []byte(`{"model":"m","messages":[{"role":"user","content":[{"type":"text","text":" "},{"type":"text","text":"keep me"},{"type":"image","source":{"type":"file","file_id":"f1"}}]}]}`) - body, err := ConvertClaudeRequestToInteractionsWithCompatReturningError("m", input, false) + body, err := ConvertClaudeRequestToInteractionsWithCompat("m", input, false) if err != nil { t.Fatalf("err = %v, body = %s", err, body) } diff --git a/internal/translator/openai/claude/init.go b/internal/translator/openai/claude/init.go index 8b541fc51a0..ba35bd9b78c 100644 --- a/internal/translator/openai/claude/init.go +++ b/internal/translator/openai/claude/init.go @@ -4,21 +4,17 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" - sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( Claude, OpenAI, - nil, + ConvertClaudeRequestToOpenAI, interfaces.TranslateResponse{ Stream: ConvertOpenAIResponseToClaude, NonStream: ConvertOpenAIResponseToClaudeNonStream, TokenCount: ClaudeTokenCount, }, ) - sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatClaude, sdktranslator.FormatOpenAI, func(model string, body []byte, stream bool) ([]byte, error) { - return convertClaudeRequestToOpenAI(model, body, stream, false) - }) } diff --git a/internal/translator/openai/claude/openai_claude_compat_test.go b/internal/translator/openai/claude/openai_claude_compat_test.go index 984b2bcb9c8..b79580ed98d 100644 --- a/internal/translator/openai/claude/openai_claude_compat_test.go +++ b/internal/translator/openai/claude/openai_claude_compat_test.go @@ -9,12 +9,12 @@ import ( func TestConvertClaudeRequestToOpenAIWithCompatPreservesEmptySignatureThinking(t *testing.T) { payload := []byte(`{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"reason","signature":""}]}]}`) - withoutCompat := ConvertClaudeRequestToOpenAI("deepseek-v4", payload, false) + withoutCompat, _ := ConvertClaudeRequestToOpenAI("deepseek-v4", payload, false) if gjson.GetBytes(withoutCompat, "messages.0.reasoning_content").Exists() { t.Fatalf("default translation preserved empty-signature reasoning: %s", withoutCompat) } - withCompat := ConvertClaudeRequestToOpenAIWithCompat("deepseek-v4", payload, false) + withCompat, _ := ConvertClaudeRequestToOpenAIWithCompat("deepseek-v4", payload, false) if gjson.GetBytes(withCompat, "messages.0.reasoning_content").String() != "reason" { t.Fatalf("compat translation missing reasoning_content: %s", withCompat) } @@ -23,7 +23,7 @@ func TestConvertClaudeRequestToOpenAIWithCompatPreservesEmptySignatureThinking(t func TestConvertClaudeRequestToOpenAIWithCompatPreservesThinkingWithToolCalls(t *testing.T) { payload := []byte(`{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"reason","signature":""},{"type":"text","text":"Reading files."},{"type":"tool_use","id":"call_1","name":"Read","input":{"path":"main.go"}}]}]}`) - result := ConvertClaudeRequestToOpenAIWithCompat("deepseek-v4", payload, false) + result, _ := ConvertClaudeRequestToOpenAIWithCompat("deepseek-v4", payload, false) assistant := gjson.GetBytes(result, "messages.0") if got := assistant.Get("reasoning_content").String(); got != "reason" { t.Fatalf("reasoning_content = %q, want %q; output: %s", got, "reason", result) @@ -36,7 +36,7 @@ func TestConvertClaudeRequestToOpenAIWithCompatPreservesThinkingWithToolCalls(t func TestConvertClaudeRequestToOpenAIWithCompatDoesNotAddReasoningWithoutThinking(t *testing.T) { payload := []byte(`{"messages":[{"role":"assistant","content":[{"type":"tool_use","id":"call_1","name":"Read","input":{}}]}]}`) - result := ConvertClaudeRequestToOpenAIWithCompat("deepseek-v4", payload, false) + result, _ := ConvertClaudeRequestToOpenAIWithCompat("deepseek-v4", payload, false) assistant := gjson.GetBytes(result, "messages.0") if assistant.Get("reasoning_content").Exists() { t.Fatalf("compatible translation added reasoning_content without thinking: %s", result) @@ -49,7 +49,7 @@ func TestConvertClaudeRequestToOpenAIWithCompatDoesNotAddReasoningWithoutThinkin func TestConvertClaudeRequestToOpenAIWithCompatPreservesIncompatibleThinking(t *testing.T) { payload := []byte(`{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"reason","signature":"claude#opaque"},{"type":"tool_use","id":"call_1","name":"Read","input":{}}]}]}`) - result := ConvertClaudeRequestToOpenAIWithCompat("deepseek-v4", payload, false) + result, _ := ConvertClaudeRequestToOpenAIWithCompat("deepseek-v4", payload, false) assistant := gjson.GetBytes(result, "messages.0") if got := assistant.Get("reasoning_content").String(); got != "reason" { t.Fatalf("reasoning_content = %q, want %q; output: %s", got, "reason", result) @@ -62,7 +62,7 @@ func TestConvertClaudeRequestToOpenAIWithCompatPreservesIncompatibleThinking(t * func TestConvertClaudeRequestToOpenAIWithoutCompatDoesNotAddReasoningForToolCalls(t *testing.T) { payload := []byte(`{"messages":[{"role":"assistant","content":[{"type":"tool_use","id":"call_1","name":"Read","input":{}}]}]}`) - result := ConvertClaudeRequestToOpenAI("deepseek-v4", payload, false) + result, _ := ConvertClaudeRequestToOpenAI("deepseek-v4", payload, false) if gjson.GetBytes(result, "messages.0.reasoning_content").Exists() { t.Fatalf("default translation added reasoning_content: %s", result) } diff --git a/internal/translator/openai/claude/openai_claude_request.go b/internal/translator/openai/claude/openai_claude_request.go index b390d6c67fe..813be7ec3b0 100644 --- a/internal/translator/openai/claude/openai_claude_request.go +++ b/internal/translator/openai/claude/openai_claude_request.go @@ -20,20 +20,14 @@ import ( // ConvertClaudeRequestToOpenAI parses and transforms an Anthropic API request into OpenAI Chat Completions API format. // It extracts the model name, system instruction, message contents, and tool declarations // from the raw JSON request and returns them in the format expected by the OpenAI API. -func ConvertClaudeRequestToOpenAI(modelName string, inputRawJSON []byte, stream bool) []byte { - body, _ := convertClaudeRequestToOpenAI(modelName, inputRawJSON, stream, false) - return body +func ConvertClaudeRequestToOpenAI(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { + return convertClaudeRequestToOpenAI(modelName, inputRawJSON, stream, false) + } // ConvertClaudeRequestToOpenAIWithCompat preserves assistant thinking text // for configured compatibility endpoints. -func ConvertClaudeRequestToOpenAIWithCompat(modelName string, inputRawJSON []byte, stream bool) []byte { - body, _ := convertClaudeRequestToOpenAI(modelName, inputRawJSON, stream, true) - return body -} - -// ConvertClaudeRequestToOpenAIWithCompatReturningError reports a file part the target cannot represent. -func ConvertClaudeRequestToOpenAIWithCompatReturningError(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { +func ConvertClaudeRequestToOpenAIWithCompat(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { return convertClaudeRequestToOpenAI(modelName, inputRawJSON, stream, true) } diff --git a/internal/translator/openai/claude/openai_claude_request_test.go b/internal/translator/openai/claude/openai_claude_request_test.go index 98a04a9f147..ccdb853422c 100644 --- a/internal/translator/openai/claude/openai_claude_request_test.go +++ b/internal/translator/openai/claude/openai_claude_request_test.go @@ -182,7 +182,7 @@ func TestConvertClaudeRequestToOpenAI_ThinkingToReasoningContent(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - result := ConvertClaudeRequestToOpenAI("test-model", []byte(tt.inputJSON), false) + result, _ := ConvertClaudeRequestToOpenAI("test-model", []byte(tt.inputJSON), false) resultJSON := gjson.ParseBytes(result) // Find the relevant message @@ -296,7 +296,7 @@ func TestConvertClaudeRequestToOpenAI_SignedThinkingCompatibility(t *testing.T) }] }` - result := ConvertClaudeRequestToOpenAI("gpt-5", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToOpenAI("gpt-5", []byte(inputJSON), false) assistantMsg := gjson.GetBytes(result, "messages.0") gotReasoningContent := assistantMsg.Get("reasoning_content").String() gotHasReasoningContent := assistantMsg.Get("reasoning_content").Exists() @@ -335,7 +335,7 @@ func TestConvertClaudeRequestToOpenAI_UnsignedThinkingOnlyMessageDropped(t *test ] }` - result := ConvertClaudeRequestToOpenAI("test-model", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToOpenAI("test-model", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) messages := resultJSON.Get("messages").Array() @@ -373,7 +373,7 @@ func TestConvertClaudeRequestToOpenAI_MessageSystemRoleWrapsAsUserReminder(t *te ] }` - result := ConvertClaudeRequestToOpenAI("gpt-5", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToOpenAI("gpt-5", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) messages := resultJSON.Get("messages").Array() @@ -428,7 +428,7 @@ func TestConvertClaudeRequestToOpenAI_PreservesToolAdjacencyWithInterveningSyste ] }` - result := ConvertClaudeRequestToOpenAI("gpt-5", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToOpenAI("gpt-5", []byte(inputJSON), false) messages := gjson.GetBytes(result, "messages").Array() // Expected roles order: @@ -523,7 +523,7 @@ func TestConvertClaudeRequestToOpenAI_SystemMessageScenarios(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - result := ConvertClaudeRequestToOpenAI("test-model", []byte(tt.inputJSON), false) + result, _ := ConvertClaudeRequestToOpenAI("test-model", []byte(tt.inputJSON), false) resultJSON := gjson.ParseBytes(result) messages := resultJSON.Get("messages").Array() @@ -587,7 +587,7 @@ func TestConvertClaudeRequestToOpenAI_ToolSchemaAddsMissingObjectProperties(t *t "messages": [{"role": "user", "content": "hello"}] }`) - output := ConvertClaudeRequestToOpenAI("test-model", inputJSON, false) + output, _ := ConvertClaudeRequestToOpenAI("test-model", inputJSON, false) outputJSON := gjson.ParseBytes(output) if got := outputJSON.Get("tools.0.function.parameters.properties"); !got.Exists() || !got.IsObject() { @@ -622,7 +622,7 @@ func TestConvertClaudeRequestToOpenAI_ToolResultOrderAndContent(t *testing.T) { ] }` - result := ConvertClaudeRequestToOpenAI("test-model", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToOpenAI("test-model", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) messages := resultJSON.Get("messages").Array() @@ -679,7 +679,7 @@ func TestConvertClaudeRequestToOpenAI_ToolResultObjectContent(t *testing.T) { ] }` - result := ConvertClaudeRequestToOpenAI("test-model", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToOpenAI("test-model", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) messages := resultJSON.Get("messages").Array() @@ -732,7 +732,7 @@ func TestConvertClaudeRequestToOpenAI_ToolResultTextAndImageContent(t *testing.T ] }` - result := ConvertClaudeRequestToOpenAI("test-model", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToOpenAI("test-model", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) messages := resultJSON.Get("messages").Array() @@ -800,7 +800,7 @@ func TestConvertClaudeRequestToOpenAI_ToolResultURLImageOnly(t *testing.T) { ] }` - result := ConvertClaudeRequestToOpenAI("test-model", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToOpenAI("test-model", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) messages := resultJSON.Get("messages").Array() @@ -858,7 +858,7 @@ func TestConvertClaudeRequestToOpenAI_ToolResultImageMergesIntoUserText(t *testi ] }` - result := ConvertClaudeRequestToOpenAI("test-model", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToOpenAI("test-model", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) messages := resultJSON.Get("messages").Array() @@ -930,7 +930,7 @@ func TestConvertClaudeRequestToOpenAI_MultipleToolResultsWithImages(t *testing.T ] }` - result := ConvertClaudeRequestToOpenAI("test-model", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToOpenAI("test-model", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) messages := resultJSON.Get("messages").Array() @@ -983,7 +983,7 @@ func TestConvertClaudeRequestToOpenAI_AssistantTextToolUseTextOrder(t *testing.T ] }` - result := ConvertClaudeRequestToOpenAI("test-model", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToOpenAI("test-model", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) messages := resultJSON.Get("messages").Array() @@ -1035,7 +1035,7 @@ func TestConvertClaudeRequestToOpenAI_AssistantThinkingToolUseThinkingSplit(t *t ] }` - result := ConvertClaudeRequestToOpenAI("test-model", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToOpenAI("test-model", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) messages := resultJSON.Get("messages").Array() @@ -1077,7 +1077,7 @@ func TestConvertClaudeRequestToOpenAI_StripsClaudeCodeAttribution(t *testing.T) "messages": [{"role": "user", "content": [{"type": "text", "text": "hi"}]}] }`) - output := ConvertClaudeRequestToOpenAI("gpt-5", inputJSON, false) + output, _ := ConvertClaudeRequestToOpenAI("gpt-5", inputJSON, false) messages := gjson.GetBytes(output, "messages").Array() if len(messages) == 0 || messages[0].Get("role").String() != "system" { t.Fatalf("Expected first message to be system, got: %s", gjson.GetBytes(output, "messages").Raw) @@ -1120,7 +1120,7 @@ func TestConvertClaudeRequestToOpenAI_StopSequences(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - output := ConvertClaudeRequestToOpenAI("gpt-4o", []byte(tt.inputJSON), false) + output, _ := ConvertClaudeRequestToOpenAI("gpt-4o", []byte(tt.inputJSON), false) stopRes := gjson.GetBytes(output, "stop") if !stopRes.Exists() { t.Fatalf("expected 'stop' field in output, got: %s", string(output)) @@ -1161,7 +1161,7 @@ func TestConvertClaudeRequestToOpenAI_ToolWithoutInputSchemaDefaultsParameters(t "messages": [{"role": "user", "content": "hello"}] }`) - output := ConvertClaudeRequestToOpenAI("test-model", inputJSON, false) + output, _ := ConvertClaudeRequestToOpenAI("test-model", inputJSON, false) outputJSON := gjson.ParseBytes(output) for i, toolName := range []string{"web_search", "no_schema_custom", "null_schema_custom"} { @@ -1210,7 +1210,7 @@ func TestConvertClaudeRequestToOpenAI_StripsUnsupportedUnicodePropertyEscapePatt }] }`) - output := ConvertClaudeRequestToOpenAI("gpt-5.6", inputJSON, false) + output, _ := ConvertClaudeRequestToOpenAI("gpt-5.6", inputJSON, false) outputJSON := gjson.ParseBytes(output) params := outputJSON.Get("tools.0.function.parameters") @@ -1262,7 +1262,7 @@ func TestConvertClaudeRequestToOpenAI_PreservesNonSchemaPatternKeys(t *testing.T }] }`) - output := ConvertClaudeRequestToOpenAI("gpt-5.6", inputJSON, false) + output, _ := ConvertClaudeRequestToOpenAI("gpt-5.6", inputJSON, false) outputJSON := gjson.ParseBytes(output) params := outputJSON.Get("tools.0.function.parameters") @@ -1304,7 +1304,7 @@ func TestConvertClaudeRequestToOpenAI_StripsPatternPropertiesIncompatibleKeys(t }] }`) - output := ConvertClaudeRequestToOpenAI("gpt-5.6", inputJSON, false) + output, _ := ConvertClaudeRequestToOpenAI("gpt-5.6", inputJSON, false) outputJSON := gjson.ParseBytes(output) params := outputJSON.Get("tools.0.function.parameters") @@ -1364,7 +1364,7 @@ func TestConvertClaudeRequestToOpenAI_ToolResultPreservesFunctionName(t *testing ] }` - result := ConvertClaudeRequestToOpenAI("gemini-3.8-flash", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToOpenAI("gemini-3.8-flash", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) messages := resultJSON.Get("messages").Array() @@ -1413,7 +1413,7 @@ func TestConvertClaudeRequestToOpenAI_ToolResultUnknownIDNoName(t *testing.T) { ] }` - result := ConvertClaudeRequestToOpenAI("gemini-3.8-flash", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToOpenAI("gemini-3.8-flash", []byte(inputJSON), false) resultJSON := gjson.ParseBytes(result) toolMsg := resultJSON.Get("messages.0") @@ -1463,7 +1463,7 @@ func TestConvertClaudeRequestToOpenAI_ToolCallPairingByID(t *testing.T) { ] }` - result := ConvertClaudeRequestToOpenAI("deepseek-v4.1-flash", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToOpenAI("deepseek-v4.1-flash", []byte(inputJSON), false) messages := gjson.GetBytes(result, "messages").Array() roles := make([]string, 0, len(messages)) @@ -1522,7 +1522,7 @@ func TestConvertClaudeRequestToOpenAI_ToolCallPairing_OrphanAndIncompletePreserv ] }` - result := ConvertClaudeRequestToOpenAI("deepseek-v4.1-flash", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToOpenAI("deepseek-v4.1-flash", []byte(inputJSON), false) messages := gjson.GetBytes(result, "messages").Array() // Incomplete history (call_alpha and call_beta are unanswered) and orphan result @@ -1555,7 +1555,7 @@ func TestConvertClaudeRequestToOpenAI_ToolChoice(t *testing.T) { {"name": "tool_b", "description": "test", "input_schema": {"type": "object", "properties": {}}} ] }` - result := ConvertClaudeRequestToOpenAI("gpt-5.4", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToOpenAI("gpt-5.4", []byte(inputJSON), false) gotToolChoice := gjson.GetBytes(result, "tool_choice").String() if gotToolChoice != "none" { t.Fatalf("expected tool_choice to be 'none', got %q. Output: %s", gotToolChoice, result) @@ -1572,7 +1572,7 @@ func TestConvertClaudeRequestToOpenAI_ToolChoice(t *testing.T) { {"name": "tool_a", "description": "test", "input_schema": {"type": "object", "properties": {}}} ] }` - result := ConvertClaudeRequestToOpenAI("gpt-5.4", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToOpenAI("gpt-5.4", []byte(inputJSON), false) parallel := gjson.GetBytes(result, "parallel_tool_calls") if !parallel.Exists() || parallel.Bool() { t.Fatalf("expected parallel_tool_calls to be false, got %v. Output: %s", parallel.Value(), result) @@ -1589,7 +1589,7 @@ func TestConvertClaudeRequestToOpenAI_ToolChoice(t *testing.T) { {"name": "tool_a", "description": "test", "input_schema": {"type": "object", "properties": {}}} ] }` - result := ConvertClaudeRequestToOpenAI("gpt-5.4", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToOpenAI("gpt-5.4", []byte(inputJSON), false) gotToolChoice := gjson.GetBytes(result, "tool_choice").String() if gotToolChoice != "none" { t.Fatalf("expected tool_choice to fail closed to 'none', got %q. Output: %s", gotToolChoice, result) @@ -1606,7 +1606,7 @@ func TestConvertClaudeRequestToOpenAI_ToolChoice(t *testing.T) { {"name": "tool_a", "description": "test", "input_schema": {"type": "object", "properties": {}}} ] }` - result := ConvertClaudeRequestToOpenAI("gpt-5.4", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToOpenAI("gpt-5.4", []byte(inputJSON), false) gotToolChoice := gjson.GetBytes(result, "tool_choice").String() if gotToolChoice != "none" { t.Fatalf("expected tool_choice to fail closed to 'none', got %q. Output: %s", gotToolChoice, result) @@ -1623,7 +1623,7 @@ func TestConvertClaudeRequestToOpenAI_ToolChoice(t *testing.T) { {"name": "tool_a", "description": "test", "input_schema": {"type": "object", "properties": {}}} ] }` - result := ConvertClaudeRequestToOpenAI("gpt-5.4", []byte(inputJSON), false) + result, _ := ConvertClaudeRequestToOpenAI("gpt-5.4", []byte(inputJSON), false) if gjson.GetBytes(result, "tool_choice").Exists() { t.Fatalf("expected tool_choice not to be set when tool_choice is null, got: %s", result) } @@ -1670,7 +1670,7 @@ func TestConvertClaudeRequestToOpenAI_EnabledThinkingEffort(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - out := ConvertClaudeRequestToOpenAI("test-model", []byte(tt.inputJSON), false) + out, _ := ConvertClaudeRequestToOpenAI("test-model", []byte(tt.inputJSON), false) if got := gjson.GetBytes(out, "reasoning_effort").String(); got != tt.wantEffort { t.Fatalf("reasoning_effort = %q, want %q; body=%s", got, tt.wantEffort, out) } @@ -1709,7 +1709,7 @@ func TestConvertClaudeRequestToOpenAI_NormalizesBooleanSubschemas(t *testing.T) "messages": [{"role": "user", "content": "hello"}] }`) - output := ConvertClaudeRequestToOpenAI("test-model", inputJSON, false) + output, _ := ConvertClaudeRequestToOpenAI("test-model", inputJSON, false) outputJSON := gjson.ParseBytes(output) params := outputJSON.Get("tools.0.function.parameters") @@ -1773,7 +1773,11 @@ func TestConvertClaudeRequestToOpenAI_NormalizesBooleanSubschemas(t *testing.T) func TestConvertClaudeRequestToOpenAI_UncachedFileKeepsOldDrop(t *testing.T) { input := []byte(`{"model":"gpt-5","messages":[{"role":"user","content":[{"type":"text","text":"read"},{"type":"container_upload","file_id":"file-absent"}]}]}`) - output := string(ConvertClaudeRequestToOpenAI("gpt-5", input, false)) + body1, errConvert1 := ConvertClaudeRequestToOpenAI("gpt-5", input, false) + if errConvert1 != nil { + t.Fatal(errConvert1) + } + output := string(body1) if strings.Contains(output, "file_data") { t.Fatalf("output = %s", output) } diff --git a/internal/translator/openai/claude/openai_claude_user_turn_test.go b/internal/translator/openai/claude/openai_claude_user_turn_test.go index d2e42c3113a..2efddad349a 100644 --- a/internal/translator/openai/claude/openai_claude_user_turn_test.go +++ b/internal/translator/openai/claude/openai_claude_user_turn_test.go @@ -41,7 +41,7 @@ func TestConvertClaudeRequestToOpenAI_RefusesAnyEmptiedUserTurn(t *testing.T) { } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - body, err := ConvertClaudeRequestToOpenAIWithCompatReturningError("m", []byte(tc.input), false) + body, err := ConvertClaudeRequestToOpenAIWithCompat("m", []byte(tc.input), false) var unsupported *translatorcommon.UnsupportedPartError if !errors.As(err, &unsupported) || unsupported.Type != tc.wantType || unsupported.StatusCode() != 400 { t.Fatalf("err = %v, want unsupported content part: %s; body = %s", err, tc.wantType, body) @@ -58,7 +58,7 @@ func TestConvertClaudeRequestToOpenAI_RefusesAnyEmptiedUserTurn(t *testing.T) { func TestConvertClaudeRequestToOpenAI_KeepsTurnWithTextBesideAttachment(t *testing.T) { input := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"text","text":"keep me"},` + userTurnUpload + `]}]}`) - body, err := ConvertClaudeRequestToOpenAIWithCompatReturningError("m", input, false) + body, err := ConvertClaudeRequestToOpenAIWithCompat("m", input, false) if err != nil { t.Fatalf("err = %v", err) } @@ -69,7 +69,7 @@ func TestConvertClaudeRequestToOpenAI_KeepsTurnWithTextBesideAttachment(t *testi func TestConvertClaudeRequestToOpenAI_Base64DocumentAfterHistoryStaysAFilePart(t *testing.T) { input := []byte(`{"model":"m","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"document","source":{"type":"base64","media_type":"application/pdf","data":"JVBERi0xLjQK"}}]}]}`) - body, err := ConvertClaudeRequestToOpenAIWithCompatReturningError("m", input, false) + body, err := ConvertClaudeRequestToOpenAIWithCompat("m", input, false) if err != nil { t.Fatalf("err = %v", err) } @@ -81,7 +81,7 @@ func TestConvertClaudeRequestToOpenAI_Base64DocumentAfterHistoryStaysAFilePart(t func TestConvertClaudeRequestToOpenAI_ToolResultKeepsTurnBesideUnsendableFile(t *testing.T) { input := []byte(`{"model":"m","messages":[{"role":"user","content":"run"},{"role":"assistant","content":[{"type":"tool_use","id":"toolu_1","name":"t","input":{}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"done"},` + userTurnUpload + `]}]}`) - body, err := ConvertClaudeRequestToOpenAIWithCompatReturningError("m", input, false) + body, err := ConvertClaudeRequestToOpenAIWithCompat("m", input, false) if err != nil { t.Fatalf("a tool result is a sendable part, err = %v; body = %s", err, body) } diff --git a/internal/translator/openai/gemini/openai_gemini_request.go b/internal/translator/openai/gemini/openai_gemini_request.go index 33f002a9435..cf054a45ae6 100644 --- a/internal/translator/openai/gemini/openai_gemini_request.go +++ b/internal/translator/openai/gemini/openai_gemini_request.go @@ -20,7 +20,7 @@ import ( // ConvertGeminiRequestToOpenAI parses and transforms a Gemini API request into OpenAI Chat Completions API format. // It extracts the model name, generation config, message contents, and tool declarations // from the raw JSON request and returns them in the format expected by the OpenAI API. -func ConvertGeminiRequestToOpenAI(modelName string, inputRawJSON []byte, stream bool) []byte { +func ConvertGeminiRequestToOpenAI(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { rawJSON := inputRawJSON // Base OpenAI Chat Completions API template out := []byte(`{"model":"","messages":[]}`) @@ -369,7 +369,7 @@ func ConvertGeminiRequestToOpenAI(modelName string, inputRawJSON []byte, stream } } - return out + return out, nil } func deterministicToolCallID(kind string, msgIdx, partIdx int, name, payload string) string { diff --git a/internal/translator/openai/gemini/openai_gemini_request_test.go b/internal/translator/openai/gemini/openai_gemini_request_test.go index ab867a83795..c305e9b3992 100644 --- a/internal/translator/openai/gemini/openai_gemini_request_test.go +++ b/internal/translator/openai/gemini/openai_gemini_request_test.go @@ -29,7 +29,7 @@ func TestConvertGeminiRequestToOpenAI_FunctionResponsesConsumeToolCallIDsFIFO(t ] }`) - out := ConvertGeminiRequestToOpenAI("test-model", inputJSON, false) + out, _ := ConvertGeminiRequestToOpenAI("test-model", inputJSON, false) firstID := gjson.GetBytes(out, "messages.0.tool_calls.0.id").String() secondID := gjson.GetBytes(out, "messages.0.tool_calls.1.id").String() thirdID := gjson.GetBytes(out, "messages.0.tool_calls.2.id").String() @@ -63,7 +63,7 @@ func TestConvertGeminiRequestToOpenAI_FunctionResponseWithoutPriorCallGetsFallba ] }`) - out := ConvertGeminiRequestToOpenAI("test-model", inputJSON, false) + out, _ := ConvertGeminiRequestToOpenAI("test-model", inputJSON, false) toolCallID := gjson.GetBytes(out, "messages.0.tool_call_id").String() if !strings.HasPrefix(toolCallID, "call_") { t.Fatalf("fallback tool_call_id = %q, want call_ prefix. Output: %s", toolCallID, string(out)) @@ -89,7 +89,7 @@ func TestConvertGeminiRequestToOpenAI_ExtraFunctionResponsesUseFallbackID(t *tes ] }`) - out := ConvertGeminiRequestToOpenAI("test-model", inputJSON, false) + out, _ := ConvertGeminiRequestToOpenAI("test-model", inputJSON, false) callID := gjson.GetBytes(out, "messages.0.tool_calls.0.id").String() firstResponseID := gjson.GetBytes(out, "messages.1.tool_call_id").String() extraResponseID := gjson.GetBytes(out, "messages.2.tool_call_id").String() @@ -141,7 +141,7 @@ func TestConvertGeminiRequestToOpenAI_PreservesExplicitFunctionCallIDs(t *testin ] }`) - out := ConvertGeminiRequestToOpenAI("test-model", inputJSON, false) + out, _ := ConvertGeminiRequestToOpenAI("test-model", inputJSON, false) if got := gjson.GetBytes(out, "messages.0.tool_calls.0.id").String(); got != tt.want { t.Fatalf("tool call id = %q, want %q. Output: %s", got, tt.want, string(out)) } @@ -153,14 +153,14 @@ func TestConvertGeminiRequestToOpenAI_PreservesExplicitFunctionCallIDs(t *testin } func TestConvertGeminiRequestToOpenAI_AcceptsSnakeInlineData(t *testing.T) { - out := ConvertGeminiRequestToOpenAI("gpt-test", []byte(`{"contents":[{"role":"user","parts":[{"inline_data":{"mime_type":"image/png","data":"aGVsbG8="}}]}]}`), false) + out, _ := ConvertGeminiRequestToOpenAI("gpt-test", []byte(`{"contents":[{"role":"user","parts":[{"inline_data":{"mime_type":"image/png","data":"aGVsbG8="}}]}]}`), false) if got := gjson.GetBytes(out, "messages.0.content.0.image_url.url").String(); got != "data:image/png;base64,aGVsbG8=" { t.Fatalf("image url = %q, want data:image/png;base64,aGVsbG8=. Output: %s", got, string(out)) } } func TestConvertGeminiRequestToOpenAI_SplitsNonImageInlineDataByMIME(t *testing.T) { - out := ConvertGeminiRequestToOpenAI("gpt-test", []byte(`{"contents":[{"role":"user","parts":[{"inlineData":{"mimeType":"audio/wav","data":"UklGRg=="}},{"inlineData":{"mimeType":"video/mp4","data":"AAAAIGZ0eXA="}},{"inlineData":{"mimeType":"application/pdf","data":"JVBERi0="}}]}]}`), false) + out, _ := ConvertGeminiRequestToOpenAI("gpt-test", []byte(`{"contents":[{"role":"user","parts":[{"inlineData":{"mimeType":"audio/wav","data":"UklGRg=="}},{"inlineData":{"mimeType":"video/mp4","data":"AAAAIGZ0eXA="}},{"inlineData":{"mimeType":"application/pdf","data":"JVBERi0="}}]}]}`), false) if got := gjson.GetBytes(out, "messages.0.content.0.type").String(); got != "input_audio" { t.Fatalf("audio content type = %q, want input_audio. Output: %s", got, string(out)) @@ -178,7 +178,7 @@ func TestConvertGeminiRequestToOpenAI_SplitsNonImageInlineDataByMIME(t *testing. func TestConvertGeminiRequestToOpenAI_DropsHiddenThoughtParts(t *testing.T) { t.Run("thought-only turn", func(t *testing.T) { - out := ConvertGeminiRequestToOpenAI("openai-test", []byte(`{ + out, _ := ConvertGeminiRequestToOpenAI("openai-test", []byte(`{ "contents":[ {"role":"model","parts":[{"thought":true,"text":"internal reasoning","thoughtSignature":"opaque-provider-state"}]}, {"role":"user","parts":[{"text":"continue"}]} @@ -192,7 +192,7 @@ func TestConvertGeminiRequestToOpenAI_DropsHiddenThoughtParts(t *testing.T) { }) t.Run("mixed turn", func(t *testing.T) { - out := ConvertGeminiRequestToOpenAI("openai-test", []byte(`{ + out, _ := ConvertGeminiRequestToOpenAI("openai-test", []byte(`{ "contents":[{"role":"model","parts":[ {"thought":true,"text":"internal reasoning","thoughtSignature":"opaque-provider-state"}, {"text":"visible answer"} @@ -226,7 +226,7 @@ func TestConvertGeminiRequestToOpenAI_DeterministicToolCallIDs(t *testing.T) { ] }`) - firstOut := ConvertGeminiRequestToOpenAI("test-model", inputJSON, false) + firstOut, _ := ConvertGeminiRequestToOpenAI("test-model", inputJSON, false) firstCall0 := gjson.GetBytes(firstOut, "messages.0.tool_calls.0.id").String() firstCall1 := gjson.GetBytes(firstOut, "messages.0.tool_calls.1.id").String() firstResp0 := gjson.GetBytes(firstOut, "messages.1.tool_call_id").String() @@ -243,7 +243,7 @@ func TestConvertGeminiRequestToOpenAI_DeterministicToolCallIDs(t *testing.T) { } for i := 0; i < 100; i++ { - out := ConvertGeminiRequestToOpenAI("test-model", inputJSON, false) + out, _ := ConvertGeminiRequestToOpenAI("test-model", inputJSON, false) if got := gjson.GetBytes(out, "messages.0.tool_calls.0.id").String(); got != firstCall0 { t.Fatalf("iteration %d: tool_calls.0.id = %q, want %q", i, got, firstCall0) } @@ -279,7 +279,7 @@ func TestConvertGeminiRequestToOpenAI_SameNameCallsInSameMessageDistinct(t *test ] }`) - out := ConvertGeminiRequestToOpenAI("test-model", inputJSON, false) + out, _ := ConvertGeminiRequestToOpenAI("test-model", inputJSON, false) id0 := gjson.GetBytes(out, "messages.0.tool_calls.0.id").String() id1 := gjson.GetBytes(out, "messages.0.tool_calls.1.id").String() @@ -324,7 +324,7 @@ func TestConvertGeminiRequestToOpenAI_InterleavedPerNameFIFOMatching(t *testing. ] }`) - out := ConvertGeminiRequestToOpenAI("test-model", inputJSON, false) + out, _ := ConvertGeminiRequestToOpenAI("test-model", inputJSON, false) callA1 := gjson.GetBytes(out, "messages.0.tool_calls.0.id").String() callB1 := gjson.GetBytes(out, "messages.0.tool_calls.1.id").String() callA2 := gjson.GetBytes(out, "messages.0.tool_calls.2.id").String() @@ -361,14 +361,14 @@ func TestConvertGeminiRequestToOpenAI_DeterministicFallbackOrphanResponse(t *tes ] }`) - firstOut := ConvertGeminiRequestToOpenAI("test-model", inputJSON, false) + firstOut, _ := ConvertGeminiRequestToOpenAI("test-model", inputJSON, false) firstID := gjson.GetBytes(firstOut, "messages.0.tool_call_id").String() if !strings.HasPrefix(firstID, "call_") { t.Fatalf("expected fallback tool_call_id with call_ prefix, got %q", firstID) } for i := 0; i < 100; i++ { - out := ConvertGeminiRequestToOpenAI("test-model", inputJSON, false) + out, _ := ConvertGeminiRequestToOpenAI("test-model", inputJSON, false) if got := gjson.GetBytes(out, "messages.0.tool_call_id").String(); got != firstID { t.Fatalf("iteration %d: orphan fallback tool_call_id = %q, want %q", i, got, firstID) } @@ -393,7 +393,7 @@ func TestConvertGeminiRequestToOpenAI_ExplicitCallInheritedByImplicitResponse(t ] }`) - out := ConvertGeminiRequestToOpenAI("test-model", inputJSON, false) + out, _ := ConvertGeminiRequestToOpenAI("test-model", inputJSON, false) if got := gjson.GetBytes(out, "messages.0.tool_calls.0.id").String(); got != "explicit_call_1" { t.Fatalf("tool call ID = %q, want explicit_call_1", got) } @@ -427,7 +427,7 @@ func TestConvertGeminiRequestToOpenAI_OutOrderExplicitResponseDoesNotDuplicateID ] }`) - out := ConvertGeminiRequestToOpenAI("test-model", inputJSON, false) + out, _ := ConvertGeminiRequestToOpenAI("test-model", inputJSON, false) resp1 := gjson.GetBytes(out, "messages.1.tool_call_id").String() resp2 := gjson.GetBytes(out, "messages.2.tool_call_id").String() resp3 := gjson.GetBytes(out, "messages.3.tool_call_id").String() diff --git a/internal/translator/openai/interactions/chat-completions/init.go b/internal/translator/openai/interactions/chat-completions/init.go index fd2e6ae6144..c6a895b87e6 100644 --- a/internal/translator/openai/interactions/chat-completions/init.go +++ b/internal/translator/openai/interactions/chat-completions/init.go @@ -4,20 +4,18 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" - sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( OpenAI, Interactions, - nil, + ConvertOpenAIRequestToInteractions, interfaces.TranslateResponse{ Stream: ConvertInteractionsResponseToOpenAI, NonStream: ConvertInteractionsResponseToOpenAINonStream, }, ) - sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatOpenAI, sdktranslator.FormatInteractions, convertOpenAIRequestToInteractions) translator.Register( Interactions, OpenAI, diff --git a/internal/translator/openai/interactions/chat-completions/interactions_openai_request.go b/internal/translator/openai/interactions/chat-completions/interactions_openai_request.go index fc25189b672..501b037da2d 100644 --- a/internal/translator/openai/interactions/chat-completions/interactions_openai_request.go +++ b/internal/translator/openai/interactions/chat-completions/interactions_openai_request.go @@ -9,7 +9,7 @@ import ( "github.com/tidwall/sjson" ) -func ConvertInteractionsRequestToOpenAI(modelName string, inputRawJSON []byte, stream bool) []byte { +func ConvertInteractionsRequestToOpenAI(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { root := gjson.ParseBytes(inputRawJSON) out := []byte(`{"model":"","messages":[]}`) model := firstNonEmpty(modelName, root.Get("model").String()) @@ -29,7 +29,7 @@ func ConvertInteractionsRequestToOpenAI(modelName string, inputRawJSON []byte, s out = copyInteractionsToolsToOpenAI(out, root, forAntigravity) out = copyInteractionsGenerationConfigToOpenAI(out, root) out = copyInteractionsOpenAITopLevel(out, root) - return out + return out, nil } func appendInteractionsSystemToOpenAI(items *[][]byte, root gjson.Result) { diff --git a/internal/translator/openai/interactions/chat-completions/interactions_openai_request_test.go b/internal/translator/openai/interactions/chat-completions/interactions_openai_request_test.go index a3a10a9e0a0..ee6f3bd98c8 100644 --- a/internal/translator/openai/interactions/chat-completions/interactions_openai_request_test.go +++ b/internal/translator/openai/interactions/chat-completions/interactions_openai_request_test.go @@ -7,7 +7,7 @@ import ( ) func TestConvertInteractionsRequestToOpenAIPreservesExpressibleFields(t *testing.T) { - out := ConvertInteractionsRequestToOpenAI("gpt-test", []byte(`{"model":"gpt-test","tool_choice":{"type":"function","function":{"name":"lookup"}},"response_modalities":["text","image"],"service_tier":"priority","input":"hi"}`), false) + out, _ := ConvertInteractionsRequestToOpenAI("gpt-test", []byte(`{"model":"gpt-test","tool_choice":{"type":"function","function":{"name":"lookup"}},"response_modalities":["text","image"],"service_tier":"priority","input":"hi"}`), false) if got := gjson.GetBytes(out, "tool_choice.type").String(); got != "function" { t.Fatalf("tool_choice.type = %q, want function. Output: %s", got, string(out)) } @@ -27,7 +27,7 @@ func TestConvertInteractionsRequestToOpenAIPreservesExpressibleFields(t *testing func TestConvertOpenAIRequestToInteractionsMapsMessagesToolsAndStream(t *testing.T) { raw := []byte(`{"model":"gemini-3.1-flash-lite","stream":true,"messages":[{"role":"system","content":"be brief"},{"role":"user","content":"今天北京的天气怎么样?"}],"tools":[{"type":"function","function":{"name":"get_weather","description":"weather","parameters":{"type":"object","properties":{"location":{"type":"string"}},"required":["location"]}}}],"tool_choice":"auto","max_completion_tokens":128}`) - out := ConvertOpenAIRequestToInteractions("gemini-3.1-flash-lite", raw, false) + out, _ := ConvertOpenAIRequestToInteractions("gemini-3.1-flash-lite", raw, false) if got := gjson.GetBytes(out, "model").String(); got != "gemini-3.1-flash-lite" { t.Fatalf("model = %q, want gemini-3.1-flash-lite. Output: %s", got, string(out)) } @@ -62,7 +62,7 @@ func TestConvertOpenAIRequestToInteractionsMapsMessagesToolsAndStream(t *testing func TestConvertOpenAIRequestToInteractionsMapsToolCallsAndResults(t *testing.T) { raw := []byte(`{"model":"gemini-3.1-flash-lite","messages":[{"role":"assistant","tool_calls":[{"id":"call_1","type":"function","function":{"name":"lookup","arguments":"{\"q\":\"x\"}"}}]},{"role":"tool","tool_call_id":"call_1","content":"ok"}]}`) - out := ConvertOpenAIRequestToInteractions("gemini-3.1-flash-lite", raw, false) + out, _ := ConvertOpenAIRequestToInteractions("gemini-3.1-flash-lite", raw, false) if got := gjson.GetBytes(out, "input.0.type").String(); got != "function_call" { t.Fatalf("input.0.type = %q, want function_call. Output: %s", got, string(out)) } @@ -107,7 +107,7 @@ func TestConvertOpenAIRequestToInteractionsInfersToolNamesForOutOfOrderResults(t {"role": "tool", "tool_call_id": "call_1", "content": "found"} ] }`) - out := ConvertOpenAIRequestToInteractions("gemini-3.1-flash-lite", raw, false) + out, _ := ConvertOpenAIRequestToInteractions("gemini-3.1-flash-lite", raw, false) // input.0: function_call call_1 (lookup) // input.1: function_call call_2 (weather) // input.2: function_result call_2 (weather) @@ -127,7 +127,7 @@ func TestConvertOpenAIRequestToInteractionsInfersToolNamesForOutOfOrderResults(t } func TestConvertInteractionsRequestToOpenAIAcceptsImageContent(t *testing.T) { - out := ConvertInteractionsRequestToOpenAI("gpt-test", []byte(`{"model":"gpt-test","input":[{"type":"user_input","content":[{"type":"image","mime_type":"image/png","data":"aGVsbG8="}]}]}`), false) + out, _ := ConvertInteractionsRequestToOpenAI("gpt-test", []byte(`{"model":"gpt-test","input":[{"type":"user_input","content":[{"type":"image","mime_type":"image/png","data":"aGVsbG8="}]}]}`), false) if got := gjson.GetBytes(out, "messages.0.content.0.type").String(); got != "image_url" { t.Fatalf("content type = %q, want image_url. Output: %s", got, string(out)) } @@ -137,7 +137,7 @@ func TestConvertInteractionsRequestToOpenAIAcceptsImageContent(t *testing.T) { } func TestConvertInteractionsRequestToOpenAIPreservesNonImageMediaContent(t *testing.T) { - out := ConvertInteractionsRequestToOpenAI("gpt-test", []byte(`{"model":"gpt-test","input":[{"type":"user_input","content":[{"type":"audio","mime_type":"audio/wav","data":"UklGRg=="},{"type":"video","mime_type":"video/mp4","data":"AAAAIGZ0eXA="},{"type":"document","mime_type":"application/pdf","data":"JVBERi0="}]}]}`), false) + out, _ := ConvertInteractionsRequestToOpenAI("gpt-test", []byte(`{"model":"gpt-test","input":[{"type":"user_input","content":[{"type":"audio","mime_type":"audio/wav","data":"UklGRg=="},{"type":"video","mime_type":"video/mp4","data":"AAAAIGZ0eXA="},{"type":"document","mime_type":"application/pdf","data":"JVBERi0="}]}]}`), false) if got := gjson.GetBytes(out, "messages.0.content.0.type").String(); got != "input_audio" { t.Fatalf("audio content type = %q, want input_audio. Output: %s", got, string(out)) @@ -154,7 +154,7 @@ func TestConvertInteractionsRequestToOpenAIPreservesNonImageMediaContent(t *test } func TestConvertInteractionsRequestToOpenAIWithToolMessagesDirect(t *testing.T) { - out := ConvertInteractionsRequestToOpenAI("gpt-test", []byte(`{"model":"gpt-test","input":[{"type":"user_input","content":[{"type":"text","text":"hi"}]},{"type":"function_call","name":"lookup","call_id":"call_1","arguments":{"q":"x"}},{"type":"function_result","name":"lookup","call_id":"call_1","result":{"ok":true}}]}`), false) + out, _ := ConvertInteractionsRequestToOpenAI("gpt-test", []byte(`{"model":"gpt-test","input":[{"type":"user_input","content":[{"type":"text","text":"hi"}]},{"type":"function_call","name":"lookup","call_id":"call_1","arguments":{"q":"x"}},{"type":"function_result","name":"lookup","call_id":"call_1","result":{"ok":true}}]}`), false) if got := gjson.GetBytes(out, "messages.1.tool_calls.0.function.name").String(); got != "lookup" { t.Fatalf("tool call name = %q, want lookup. Output: %s", got, string(out)) } @@ -175,7 +175,7 @@ func TestConvertOpenAIRequestToInteractions_AntigravitySanitizesGenerationConfig "top_p":0.9, "tools":[{"type":"function","function":{"name":"search","parameters":{"type":"object"}}}] }`) - out := ConvertOpenAIRequestToInteractions("antigravity-preview-05-2026", raw, false) + out, _ := ConvertOpenAIRequestToInteractions("antigravity-preview-05-2026", raw, false) // generation_config should not contain temperature, top_p, max_output_tokens for _, knob := range []string{"temperature", "top_p", "top_k", "stop_sequences", "max_output_tokens"} { if gjson.GetBytes(out, "generation_config."+knob).Exists() { @@ -194,7 +194,7 @@ func TestConvertOpenAIRequestToInteractions_PreservesEnvironmentIDAndPreviousInt "previous_response_id":"v1_prev123", "environment_id":"env_456" }`) - out := ConvertOpenAIRequestToInteractions("antigravity-preview-05-2026", raw, false) + out, _ := ConvertOpenAIRequestToInteractions("antigravity-preview-05-2026", raw, false) if got := gjson.GetBytes(out, "previous_interaction_id").String(); got != "v1_prev123" { t.Fatalf("previous_interaction_id = %q, want v1_prev123. Output: %s", got, string(out)) } @@ -210,7 +210,7 @@ func TestConvertOpenAIRequestToInteractionsRenamesConflictingAntigravityTools(t {"type":"function","function":{"name":"execute_code","description":"e","parameters":{"type":"object"}}}, {"type":"function","function":{"name":"web_search","description":"s","parameters":{"type":"object"}}} ]}`) - out := ConvertOpenAIRequestToInteractions("antigravity-preview-05-2026", raw, false) + out, _ := ConvertOpenAIRequestToInteractions("antigravity-preview-05-2026", raw, false) if got := gjson.GetBytes(out, "tools.0.name").String(); got != "external_read_file" { t.Fatalf("tools.0.name = %q, want external_read_file. Output: %s", got, string(out)) } @@ -223,7 +223,7 @@ func TestConvertOpenAIRequestToInteractionsRenamesConflictingAntigravityTools(t if got := gjson.GetBytes(out, "tools.3.name").String(); got != "web_search" { t.Fatalf("tools.3.name = %q, want web_search (unchanged). Output: %s", got, string(out)) } - outNonAnti := ConvertOpenAIRequestToInteractions("gemini-3.1-flash-lite", raw, false) + outNonAnti, _ := ConvertOpenAIRequestToInteractions("gemini-3.1-flash-lite", raw, false) if got := gjson.GetBytes(outNonAnti, "tools.0.name").String(); got != "read_file" { t.Fatalf("gemini tools.0.name = %q, want read_file (no rename). Output: %s", got, string(outNonAnti)) } @@ -237,7 +237,7 @@ func TestConvertOpenAIRequestToInteractionsRenamesConflictingAntigravityToolCall ],"tools":[ {"type":"function","function":{"name":"read_file","parameters":{"type":"object"}}} ]}`) - out := ConvertOpenAIRequestToInteractions("antigravity-preview-05-2026", raw, false) + out, _ := ConvertOpenAIRequestToInteractions("antigravity-preview-05-2026", raw, false) if got := gjson.GetBytes(out, "input.1.name").String(); got != "external_read_file" { t.Fatalf("input.1.name (function_call) = %q, want external_read_file. Output: %s", got, string(out)) } @@ -253,11 +253,11 @@ func TestConvertOpenAIRequestToInteractionsRenamesConflictingToolChoice(t *testi "tools":[{"type":"function","function":{"name":"read_file","parameters":{"type":"object"}}}], "tool_choice":{"type":"function","function":{"name":"read_file"}} }`) - out := ConvertOpenAIRequestToInteractions("antigravity-preview-05-2026", raw, false) + out, _ := ConvertOpenAIRequestToInteractions("antigravity-preview-05-2026", raw, false) if got := gjson.GetBytes(out, "generation_config.tool_choice.function.name").String(); got != "external_read_file" { t.Fatalf("generation_config.tool_choice.function.name = %q, want external_read_file. Output: %s", got, string(out)) } - outNonAnti := ConvertOpenAIRequestToInteractions("gemini-3.1-flash-lite", raw, false) + outNonAnti, _ := ConvertOpenAIRequestToInteractions("gemini-3.1-flash-lite", raw, false) if got := gjson.GetBytes(outNonAnti, "generation_config.tool_choice.function.name").String(); got != "read_file" { t.Fatalf("gemini tool_choice.function.name = %q, want read_file (no rename). Output: %s", got, string(outNonAnti)) } diff --git a/internal/translator/openai/interactions/chat-completions/openai_interactions_file_data_test.go b/internal/translator/openai/interactions/chat-completions/openai_interactions_file_data_test.go index 0bc53934a8c..a0a64736bbc 100644 --- a/internal/translator/openai/interactions/chat-completions/openai_interactions_file_data_test.go +++ b/internal/translator/openai/interactions/chat-completions/openai_interactions_file_data_test.go @@ -9,7 +9,7 @@ import ( func TestConvertOpenAIRequestToInteractionsNormalizesFileDataURL(t *testing.T) { input := []byte(`{"model":"gemini-3.5-flash","messages":[{"role":"user","content":[{"type":"file","file":{"filename":"test.pdf","file_data":"data:application/pdf;base64,JVBERi0xLjQK"}}]}]}`) - out := ConvertOpenAIRequestToInteractions("gemini-3.5-flash", input, false) + out, _ := ConvertOpenAIRequestToInteractions("gemini-3.5-flash", input, false) document := gjson.GetBytes(out, "input.0.content.0") if got := document.Get("mime_type").String(); got != "application/pdf" { t.Fatalf("document.mime_type = %q, want application/pdf. Output: %s", got, out) @@ -22,7 +22,7 @@ func TestConvertOpenAIRequestToInteractionsNormalizesFileDataURL(t *testing.T) { func TestConvertOpenAIRequestToInteractionsPreservesRawFileDataWithMIMEType(t *testing.T) { input := []byte(`{"model":"gemini-3.5-flash","messages":[{"role":"user","content":[{"type":"document","mime_type":"application/pdf","data":"JVBERi0xLjQK"}]}]}`) - out := ConvertOpenAIRequestToInteractions("gemini-3.5-flash", input, false) + out, _ := ConvertOpenAIRequestToInteractions("gemini-3.5-flash", input, false) document := gjson.GetBytes(out, "input.0.content.0") if got := document.Get("mime_type").String(); got != "application/pdf" { t.Fatalf("document.mime_type = %q, want application/pdf. Output: %s", got, out) diff --git a/internal/translator/openai/interactions/chat-completions/openai_interactions_request.go b/internal/translator/openai/interactions/chat-completions/openai_interactions_request.go index b9436e3b697..5a938fa7530 100644 --- a/internal/translator/openai/interactions/chat-completions/openai_interactions_request.go +++ b/internal/translator/openai/interactions/chat-completions/openai_interactions_request.go @@ -8,9 +8,9 @@ import ( "github.com/tidwall/sjson" ) -func ConvertOpenAIRequestToInteractions(modelName string, inputRawJSON []byte, stream bool) []byte { - body, _ := convertOpenAIRequestToInteractions(modelName, inputRawJSON, stream) - return body +func ConvertOpenAIRequestToInteractions(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { + return convertOpenAIRequestToInteractions(modelName, inputRawJSON, stream) + } // convertOpenAIRequestToInteractions also reports a file or audio part that diff --git a/internal/translator/openai/interactions/chat-completions/openai_interactions_user_turn_test.go b/internal/translator/openai/interactions/chat-completions/openai_interactions_user_turn_test.go index bf98700722f..d6ac7b515d3 100644 --- a/internal/translator/openai/interactions/chat-completions/openai_interactions_user_turn_test.go +++ b/internal/translator/openai/interactions/chat-completions/openai_interactions_user_turn_test.go @@ -127,7 +127,7 @@ func TestConvertOpenAIRequestToInteractions_FileURLStaysAFile(t *testing.T) { func TestConvertOpenAIRequestToInteractions_ExportedWrapperKeepsAJSONBody(t *testing.T) { input := []byte(`{"model":"gemini-3.5-flash","messages":[{"role":"user","content":[` + userTurnFileID + `]}]}`) - if body := ConvertOpenAIRequestToInteractions("gemini-3.5-flash", input, false); !gjson.ValidBytes(body) { + if body, _ := ConvertOpenAIRequestToInteractions("gemini-3.5-flash", input, false); !gjson.ValidBytes(body) { t.Fatalf("body is not JSON: %q", body) } } diff --git a/internal/translator/openai/interactions/responses/apply_patch_test.go b/internal/translator/openai/interactions/responses/apply_patch_test.go index 36ac1c8b39b..7d338597f39 100644 --- a/internal/translator/openai/interactions/responses/apply_patch_test.go +++ b/internal/translator/openai/interactions/responses/apply_patch_test.go @@ -35,7 +35,11 @@ func patchSend(param *any, raw []byte) []gjson.Result { func TestInteractionsApplyPatchDeclarationAndHistory(t *testing.T) { request := gjson.Parse(patchRequest).Value().(map[string]any) request["input"] = []any{map[string]any{"type": "custom_tool_call", "name": "apply_patch", "namespace": "functions", "call_id": "c1", "input": patchText}, map[string]any{"type": "custom_tool_call_output", "call_id": "c1", "output": "ok"}} - out := gjson.ParseBytes(ConvertOpenAIResponsesRequestToInteractions("devin/swe-2", patchJSON(request), false)) + body1, errConvert1 := ConvertOpenAIResponsesRequestToInteractions("devin/swe-2", patchJSON(request), false) + if errConvert1 != nil { + t.Fatal(errConvert1) + } + out := gjson.ParseBytes(body1) if !strings.Contains(out.Get("tools.0.description").String(), "*** Begin Patch") || out.Get("tools.0.parameters.additionalProperties").Bool() || !out.Get("tools.0.parameters.additionalProperties").Exists() { t.Fatalf("missing patch contract: %s", out.Raw) } @@ -214,7 +218,11 @@ func TestInteractionsApplyPatchWinningDeclarationAndNegativeCompatibility(t *tes for _, test := range cases { t.Run(test.name, func(t *testing.T) { request := []byte(test.request) - translated := gjson.ParseBytes(ConvertOpenAIResponsesRequestToInteractions("devin/swe-2", request, false)) + body2, errConvert2 := ConvertOpenAIResponsesRequestToInteractions("devin/swe-2", request, false) + if errConvert2 != nil { + t.Fatal(errConvert2) + } + translated := gjson.ParseBytes(body2) declaration := translated.Get("tools.0") if strings.Contains(declaration.Get("description").String(), "*** Begin Patch") != test.patch { t.Fatalf("wrong contract: %s", translated.Raw) diff --git a/internal/translator/openai/interactions/responses/init.go b/internal/translator/openai/interactions/responses/init.go index 8ac3a5de184..92d70942103 100644 --- a/internal/translator/openai/interactions/responses/init.go +++ b/internal/translator/openai/interactions/responses/init.go @@ -4,20 +4,18 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" - sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( OpenaiResponse, Interactions, - nil, + ConvertOpenAIResponsesRequestToInteractions, interfaces.TranslateResponse{ Stream: ConvertInteractionsResponseToOpenAIResponses, NonStream: ConvertInteractionsResponseToOpenAIResponsesNonStream, }, ) - sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatOpenAIResponse, sdktranslator.FormatInteractions, convertOpenAIResponsesRequestToInteractions) translator.Register( Interactions, OpenaiResponse, diff --git a/internal/translator/openai/interactions/responses/interactions_openai_responses_request.go b/internal/translator/openai/interactions/responses/interactions_openai_responses_request.go index c0975cb8eee..63d35f8673c 100644 --- a/internal/translator/openai/interactions/responses/interactions_openai_responses_request.go +++ b/internal/translator/openai/interactions/responses/interactions_openai_responses_request.go @@ -10,9 +10,9 @@ import ( "github.com/tidwall/sjson" ) -func ConvertOpenAIResponsesRequestToInteractions(modelName string, inputRawJSON []byte, stream bool) []byte { - body, _ := convertOpenAIResponsesRequestToInteractions(modelName, inputRawJSON, stream) - return body +func ConvertOpenAIResponsesRequestToInteractions(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { + return convertOpenAIResponsesRequestToInteractions(modelName, inputRawJSON, stream) + } // convertOpenAIResponsesRequestToInteractions also reports a file, audio or video @@ -115,7 +115,7 @@ func convertOpenAIResponsesRequestToInteractions(modelName string, inputRawJSON return out, drops.Err() } -func ConvertInteractionsRequestToOpenAIResponses(modelName string, inputRawJSON []byte, stream bool) []byte { +func ConvertInteractionsRequestToOpenAIResponses(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { root := gjson.ParseBytes(inputRawJSON) out := []byte(`{"model":"","input":[]}`) model := requestModel(modelName, root) @@ -160,7 +160,7 @@ func ConvertInteractionsRequestToOpenAIResponses(modelName string, inputRawJSON if format := root.Get("response_format"); format.Exists() { out, _ = sjson.SetRawBytes(out, "text.format", []byte(format.Raw)) } - return out + return out, nil } func requestModel(modelName string, root gjson.Result) string { diff --git a/internal/translator/openai/interactions/responses/interactions_openai_responses_request_test.go b/internal/translator/openai/interactions/responses/interactions_openai_responses_request_test.go index bc1d14161da..d25bb289cef 100644 --- a/internal/translator/openai/interactions/responses/interactions_openai_responses_request_test.go +++ b/internal/translator/openai/interactions/responses/interactions_openai_responses_request_test.go @@ -23,7 +23,7 @@ func TestConvertOpenAIResponsesRequestToInteractions(t *testing.T) { "response_format":{"type":"json_object"}, "stream":true }`) - out := ConvertOpenAIResponsesRequestToInteractions("gpt-test", raw, true) + out, _ := ConvertOpenAIResponsesRequestToInteractions("gpt-test", raw, true) if got := gjson.GetBytes(out, "input.0.type").String(); got != "user_input" { t.Fatalf("input.0.type = %q, want user_input. Output: %s", got, string(out)) } @@ -70,19 +70,19 @@ func TestConvertOpenAIResponsesRequestToInteractions(t *testing.T) { } func TestConvertOpenAIResponsesRequestToInteractionsPreservesRequestStream(t *testing.T) { - out := ConvertOpenAIResponsesRequestToInteractions("gpt-test", []byte(`{"model":"gpt-test","input":"hi","stream":true}`), false) + out, _ := ConvertOpenAIResponsesRequestToInteractions("gpt-test", []byte(`{"model":"gpt-test","input":"hi","stream":true}`), false) if got := gjson.GetBytes(out, "stream").Bool(); !got { t.Fatalf("stream = %v, want true. Output: %s", got, string(out)) } - out = ConvertOpenAIResponsesRequestToInteractions("gpt-test", []byte(`{"model":"gpt-test","input":"hi","stream":false}`), true) + out, _ = ConvertOpenAIResponsesRequestToInteractions("gpt-test", []byte(`{"model":"gpt-test","input":"hi","stream":false}`), true) if got := gjson.GetBytes(out, "stream").Bool(); got { t.Fatalf("stream = %v, want false. Output: %s", got, string(out)) } } func TestConvertOpenAIResponsesRequestToInteractionsPreservesPreviousResponseID(t *testing.T) { - out := ConvertOpenAIResponsesRequestToInteractions("gpt-test", []byte(`{"model":"gpt-test","input":"hi","previous_response_id":"resp_123"}`), false) + out, _ := ConvertOpenAIResponsesRequestToInteractions("gpt-test", []byte(`{"model":"gpt-test","input":"hi","previous_response_id":"resp_123"}`), false) if got := gjson.GetBytes(out, "previous_interaction_id").String(); got != "resp_123" { t.Fatalf("previous_interaction_id = %q, want resp_123. Output: %s", got, string(out)) } @@ -90,7 +90,7 @@ func TestConvertOpenAIResponsesRequestToInteractionsPreservesPreviousResponseID( func TestConvertInteractionsRequestToOpenAIResponsesWithToolMessages(t *testing.T) { raw := []byte(`{"model":"gpt-test","input":[{"type":"user_input","content":[{"type":"text","text":"hi"}]},{"type":"function_call","name":"lookup","call_id":"call_1","arguments":{"q":"x"}},{"type":"function_result","name":"lookup","call_id":"call_1","result":{"ok":true}}]}`) - out := ConvertInteractionsRequestToOpenAIResponses("gpt-test", raw, false) + out, _ := ConvertInteractionsRequestToOpenAIResponses("gpt-test", raw, false) foundFunctionCall := false foundFunctionOutput := false @@ -116,7 +116,7 @@ func TestConvertInteractionsRequestToOpenAIResponsesWithToolMessages(t *testing. func TestConvertInteractionsRequestToOpenAIResponsesPreservesStringSystemAndThinkingConfig(t *testing.T) { raw := []byte(`{"model":"gpt-test","system_instruction":"You are a helpful assistant.","input":[{"type":"user_input","content":[{"type":"text","text":"hi"}]}],"tools":[{"name":"lookup","type":"function","parameters":{"type":"object"}}],"generation_config":{"tool_choice":"auto","thinking_level":"high","thinking_summaries":"auto"},"stream":true}`) - out := ConvertInteractionsRequestToOpenAIResponses("gpt-test", raw, true) + out, _ := ConvertInteractionsRequestToOpenAIResponses("gpt-test", raw, true) if got := gjson.GetBytes(out, "instructions").String(); got != "You are a helpful assistant." { t.Fatalf("instructions = %q, want system instruction. Output: %s", got, string(out)) } @@ -132,21 +132,21 @@ func TestConvertInteractionsRequestToOpenAIResponsesPreservesStringSystemAndThin } func TestConvertInteractionsRequestToOpenAIResponsesPreservesInteractionStream(t *testing.T) { - out := ConvertInteractionsRequestToOpenAIResponses("gpt-test", []byte(`{"model":"gpt-test","input":"hi","stream":true}`), false) + out, _ := ConvertInteractionsRequestToOpenAIResponses("gpt-test", []byte(`{"model":"gpt-test","input":"hi","stream":true}`), false) if got := gjson.GetBytes(out, "stream").Bool(); !got { t.Fatalf("stream = %v, want true. Output: %s", got, string(out)) } } func TestConvertInteractionsRequestToOpenAIResponsesPreservesPreviousInteractionID(t *testing.T) { - out := ConvertInteractionsRequestToOpenAIResponses("gpt-test", []byte(`{"model":"gpt-test","input":"hi","previous_interaction_id":"interaction_123"}`), false) + out, _ := ConvertInteractionsRequestToOpenAIResponses("gpt-test", []byte(`{"model":"gpt-test","input":"hi","previous_interaction_id":"interaction_123"}`), false) if got := gjson.GetBytes(out, "previous_response_id").String(); got != "interaction_123" { t.Fatalf("previous_response_id = %q, want interaction_123. Output: %s", got, string(out)) } } func TestConvertInteractionsRequestToOpenAIResponsesPreservesToolCallID(t *testing.T) { - out := ConvertInteractionsRequestToOpenAIResponses("gpt-test", []byte(`{"model":"gpt-test","input":[{"type":"function_call","name":"lookup","call_id":"call_gateway","arguments":{"q":"x"}},{"type":"function_result","name":"lookup","call_id":"call_gateway","result":{"ok":true}}]}`), false) + out, _ := ConvertInteractionsRequestToOpenAIResponses("gpt-test", []byte(`{"model":"gpt-test","input":[{"type":"function_call","name":"lookup","call_id":"call_gateway","arguments":{"q":"x"}},{"type":"function_result","name":"lookup","call_id":"call_gateway","result":{"ok":true}}]}`), false) foundFunctionCall := false foundFunctionOutput := false @@ -174,7 +174,7 @@ func TestConvertInteractionsRequestToOpenAIResponsesPreservesToolCallID(t *testi } func TestConvertInteractionsRequestToOpenAIResponsesConvertsSimpleTools(t *testing.T) { - out := ConvertInteractionsRequestToOpenAIResponses("gpt-test", []byte(`{"model":"gpt-test","tools":[{"name":"lookup","description":"Find data","parameters":{"type":"object","properties":{"q":{"type":"string"}}}}],"input":"hi"}`), false) + out, _ := ConvertInteractionsRequestToOpenAIResponses("gpt-test", []byte(`{"model":"gpt-test","tools":[{"name":"lookup","description":"Find data","parameters":{"type":"object","properties":{"q":{"type":"string"}}}}],"input":"hi"}`), false) if got := gjson.GetBytes(out, "tools.0.type").String(); got != "function" { t.Fatalf("tools.0.type = %q, want function. Output: %s", got, string(out)) } @@ -190,7 +190,7 @@ func TestConvertInteractionsRequestToOpenAIResponsesConvertsSimpleTools(t *testi } func TestConvertInteractionsRequestToOpenAIResponsesConvertsFunctionDeclarationsTools(t *testing.T) { - out := ConvertInteractionsRequestToOpenAIResponses("gpt-test", []byte(`{"model":"gpt-test","tools":[{"function_declarations":[{"name":"lookup","description":"Find data","parameters":{"type":"object","properties":{"q":{"type":"string"}}}}]}],"input":"hi"}`), false) + out, _ := ConvertInteractionsRequestToOpenAIResponses("gpt-test", []byte(`{"model":"gpt-test","tools":[{"function_declarations":[{"name":"lookup","description":"Find data","parameters":{"type":"object","properties":{"q":{"type":"string"}}}}]}],"input":"hi"}`), false) if got := gjson.GetBytes(out, "tools.0.type").String(); got != "function" { t.Fatalf("tools.0.type = %q, want function. Output: %s", got, string(out)) } @@ -204,7 +204,7 @@ func TestConvertInteractionsRequestToOpenAIResponsesConvertsFunctionDeclarations func TestConvertInteractionsRequestToOpenAIResponsesWithImageContent(t *testing.T) { raw := []byte(`{"model":"gpt-test","input":[{"type":"user_input","content":[{"type":"text","text":"describe"},{"type":"image","mime_type":"image/png","data":"aGVsbG8="}]}]}`) - out := ConvertInteractionsRequestToOpenAIResponses("gpt-test", raw, false) + out, _ := ConvertInteractionsRequestToOpenAIResponses("gpt-test", raw, false) if got := gjson.GetBytes(out, "input.0.content.1.type").String(); got != "input_image" { t.Fatalf("content.1.type = %q, want input_image", got) } @@ -214,7 +214,7 @@ func TestConvertInteractionsRequestToOpenAIResponsesWithImageContent(t *testing. } func TestConvertInteractionsRequestToOpenAIResponsesPreservesNonImageMediaContent(t *testing.T) { - out := ConvertInteractionsRequestToOpenAIResponses("gpt-test", []byte(`{"model":"gpt-test","input":[{"type":"model_output","content":[{"type":"audio","mime_type":"audio/wav","data":"UklGRg=="},{"type":"video","mime_type":"video/mp4","data":"AAAAIGZ0eXA="},{"type":"document","mime_type":"application/pdf","data":"JVBERi0="}]}]}`), false) + out, _ := ConvertInteractionsRequestToOpenAIResponses("gpt-test", []byte(`{"model":"gpt-test","input":[{"type":"model_output","content":[{"type":"audio","mime_type":"audio/wav","data":"UklGRg=="},{"type":"video","mime_type":"video/mp4","data":"AAAAIGZ0eXA="},{"type":"document","mime_type":"application/pdf","data":"JVBERi0="}]}]}`), false) if got := gjson.GetBytes(out, "input.0.content.0.type").String(); got != "output_text" { t.Fatalf("audio fallback type = %q, want output_text. Output: %s", got, string(out)) @@ -232,7 +232,7 @@ func TestConvertInteractionsRequestToOpenAIResponsesPreservesNonImageMediaConten func TestConvertInteractionsRequestToOpenAIResponsesWithAssistantTextContent(t *testing.T) { raw := []byte(`{"model":"gpt-test","input":[{"type":"model_output","content":[{"type":"text","text":"hello"}]}]}`) - out := ConvertInteractionsRequestToOpenAIResponses("gpt-test", raw, false) + out, _ := ConvertInteractionsRequestToOpenAIResponses("gpt-test", raw, false) if got := gjson.GetBytes(out, "input.0.content.0.type").String(); got != "output_text" { t.Fatalf("content.0.type = %q, want output_text", got) } @@ -243,7 +243,7 @@ func TestConvertInteractionsRequestToOpenAIResponsesWithAssistantTextContent(t * func TestConvertInteractionsRequestToOpenAIResponsesWithUserObjectContent(t *testing.T) { raw := []byte(`{"model":"gpt-test","input":[{"type":"user_input","content":[{"type":"text","text":"hi"}]}]}`) - out := ConvertInteractionsRequestToOpenAIResponses("gpt-test", raw, false) + out, _ := ConvertInteractionsRequestToOpenAIResponses("gpt-test", raw, false) if got := gjson.GetBytes(out, "input.0.content.0.type").String(); got != "input_text" { t.Fatalf("content.0.type = %q, want input_text", got) } @@ -254,7 +254,7 @@ func TestConvertInteractionsRequestToOpenAIResponsesWithUserObjectContent(t *tes func TestConvertInteractionsRequestToOpenAIResponsesWithStringFunctionArguments(t *testing.T) { raw := []byte(`{"model":"gpt-test","input":[{"type":"function_call","name":"lookup","call_id":"call_1","arguments":{"q":"x"}},{"type":"function_result","name":"lookup","call_id":"call_1","result":{"ok":true}}]}`) - out := ConvertInteractionsRequestToOpenAIResponses("gpt-test", raw, false) + out, _ := ConvertInteractionsRequestToOpenAIResponses("gpt-test", raw, false) found := false gjson.GetBytes(out, "input").ForEach(func(_, item gjson.Result) bool { @@ -275,7 +275,7 @@ func TestConvertInteractionsRequestToOpenAIResponsesWithStringFunctionArguments( } func TestConvertInteractionsRequestToOpenAIResponsesPreservesExpressibleFields(t *testing.T) { - out := ConvertInteractionsRequestToOpenAIResponses("gpt-test", []byte(`{"model":"gpt-test","tool_choice":{"type":"function","function":{"name":"lookup"}},"response_modalities":["text","image"],"service_tier":"priority","store":true,"background":true,"webhook_config":{"url":"https://example.com"},"input":"hi"}`), false) + out, _ := ConvertInteractionsRequestToOpenAIResponses("gpt-test", []byte(`{"model":"gpt-test","tool_choice":{"type":"function","function":{"name":"lookup"}},"response_modalities":["text","image"],"service_tier":"priority","store":true,"background":true,"webhook_config":{"url":"https://example.com"},"input":"hi"}`), false) if got := gjson.GetBytes(out, "tool_choice.type").String(); got != "function" { t.Fatalf("tool_choice.type = %q, want function. Output: %s", got, string(out)) } @@ -299,7 +299,7 @@ func TestConvertInteractionsRequestToOpenAIResponsesPreservesExpressibleFields(t } func TestConvertOpenAIResponsesRequestToInteractions_PreservesEnvironmentID(t *testing.T) { - out := ConvertOpenAIResponsesRequestToInteractions("gpt-test", []byte(`{"model":"gpt-test","input":"hi","previous_response_id":"resp_123","environment_id":"env_abc456"}`), false) + out, _ := ConvertOpenAIResponsesRequestToInteractions("gpt-test", []byte(`{"model":"gpt-test","input":"hi","previous_response_id":"resp_123","environment_id":"env_abc456"}`), false) if got := gjson.GetBytes(out, "previous_interaction_id").String(); got != "resp_123" { t.Fatalf("previous_interaction_id = %q, want resp_123. Output: %s", got, string(out)) } @@ -309,7 +309,7 @@ func TestConvertOpenAIResponsesRequestToInteractions_PreservesEnvironmentID(t *t } func TestConvertInteractionsRequestToOpenAIResponses_PreservesEnvironmentID(t *testing.T) { - out := ConvertInteractionsRequestToOpenAIResponses("gpt-test", []byte(`{"model":"gpt-test","input":"hi","previous_interaction_id":"interaction_123","environment_id":"env_abc456"}`), false) + out, _ := ConvertInteractionsRequestToOpenAIResponses("gpt-test", []byte(`{"model":"gpt-test","input":"hi","previous_interaction_id":"interaction_123","environment_id":"env_abc456"}`), false) if got := gjson.GetBytes(out, "previous_response_id").String(); got != "interaction_123" { t.Fatalf("previous_response_id = %q, want interaction_123. Output: %s", got, string(out)) } @@ -329,7 +329,7 @@ func TestConvertOpenAIResponsesRequestToInteractions_AntigravitySanitizesGenerat "top_p":0.95, "tools":[{"type":"function","name":"web_search","parameters":{"type":"object"}}] }`) - out := ConvertOpenAIResponsesRequestToInteractions("antigravity-preview-05-2026", raw, false) + out, _ := ConvertOpenAIResponsesRequestToInteractions("antigravity-preview-05-2026", raw, false) if got := gjson.GetBytes(out, "previous_interaction_id").String(); got != "v1_Chd3..." { t.Fatalf("previous_interaction_id = %q, want v1_Chd3.... Output: %s", got, string(out)) } @@ -359,7 +359,7 @@ func TestConvertOpenAIResponsesRequestToInteractionsRenamesConflictingAntigravit {"type":"function","name":"web_search","parameters":{"type":"object"}} ] }`) - out := ConvertOpenAIResponsesRequestToInteractions("antigravity-preview-05-2026", raw, false) + out, _ := ConvertOpenAIResponsesRequestToInteractions("antigravity-preview-05-2026", raw, false) if got := gjson.GetBytes(out, "tools.0.name").String(); got != "external_read_file" { t.Fatalf("tools.0.name = %q, want external_read_file. Output: %s", got, string(out)) } @@ -372,7 +372,7 @@ func TestConvertOpenAIResponsesRequestToInteractionsRenamesConflictingAntigravit if got := gjson.GetBytes(out, "tools.3.name").String(); got != "web_search" { t.Fatalf("tools.3.name = %q, want web_search (unchanged). Output: %s", got, string(out)) } - outNonAnti := ConvertOpenAIResponsesRequestToInteractions("gemini-3.1-flash-lite", raw, false) + outNonAnti, _ := ConvertOpenAIResponsesRequestToInteractions("gemini-3.1-flash-lite", raw, false) if got := gjson.GetBytes(outNonAnti, "tools.0.name").String(); got != "read_file" { t.Fatalf("gemini tools.0.name = %q, want read_file. Output: %s", got, string(outNonAnti)) } @@ -390,7 +390,7 @@ func TestConvertOpenAIResponsesRequestToInteractionsRenamesConflictingAntigravit {"type":"function","name":"read_file","parameters":{"type":"object"}} ] }`) - out := ConvertOpenAIResponsesRequestToInteractions("antigravity-preview-05-2026", raw, false) + out, _ := ConvertOpenAIResponsesRequestToInteractions("antigravity-preview-05-2026", raw, false) if got := gjson.GetBytes(out, "input.1.name").String(); got != "external_read_file" { t.Fatalf("input.1.name = %q, want external_read_file. Output: %s", got, string(out)) } @@ -406,11 +406,11 @@ func TestConvertOpenAIResponsesRequestToInteractionsRenamesConflictingToolChoice "tools":[{"type":"function","name":"read_file","parameters":{"type":"object"}}], "tool_choice":{"type":"function","name":"read_file"} }`) - out := ConvertOpenAIResponsesRequestToInteractions("antigravity-preview-05-2026", raw, false) + out, _ := ConvertOpenAIResponsesRequestToInteractions("antigravity-preview-05-2026", raw, false) if got := gjson.GetBytes(out, "generation_config.tool_choice.name").String(); got != "external_read_file" { t.Fatalf("generation_config.tool_choice.name = %q, want external_read_file. Output: %s", got, string(out)) } - outNonAnti := ConvertOpenAIResponsesRequestToInteractions("gemini-3.1-flash-lite", raw, false) + outNonAnti, _ := ConvertOpenAIResponsesRequestToInteractions("gemini-3.1-flash-lite", raw, false) if got := gjson.GetBytes(outNonAnti, "generation_config.tool_choice.name").String(); got != "read_file" { t.Fatalf("gemini tool_choice.name = %q, want read_file (no rename). Output: %s", got, string(outNonAnti)) } @@ -424,7 +424,7 @@ func TestConvertOpenAIResponsesRequestToInteractions_NonAntigravityGenerationCon "temperature":0.7, "top_p":0.95 }`) - out := ConvertOpenAIResponsesRequestToInteractions("devin/swe-2", raw, false) + out, _ := ConvertOpenAIResponsesRequestToInteractions("devin/swe-2", raw, false) if got := gjson.GetBytes(out, "generation_config.max_output_tokens").Int(); got != 400 { t.Fatalf("generation_config.max_output_tokens = %d, want 400. Output: %s", got, string(out)) } @@ -496,7 +496,7 @@ func TestConvertOpenAIResponsesRequestToInteractions_FlattensNamespaceTools(t *t } }`) - out := ConvertOpenAIResponsesRequestToInteractions("devin/gemini-3-7-flash", raw, false) + out, _ := ConvertOpenAIResponsesRequestToInteractions("devin/gemini-3-7-flash", raw, false) tools := gjson.GetBytes(out, "tools").Array() if len(tools) != 4 { t.Fatalf("expected 4 flattened tools, got %d. Output: %s", len(tools), string(out)) @@ -573,7 +573,7 @@ func TestConvertOpenAIResponsesRequestToInteractions_HistoryNamespaceAndCustomTo ] }`) - out := ConvertOpenAIResponsesRequestToInteractions("devin/gemini-3-7-flash", raw, false) + out, _ := ConvertOpenAIResponsesRequestToInteractions("devin/gemini-3-7-flash", raw, false) // Step 0: function_call with qualified name if got := gjson.GetBytes(out, "input.0.name").String(); got != "multi_agent_v1__close_agent" { @@ -612,7 +612,7 @@ func TestConvertOpenAIResponsesRequestToInteractions_AntigravityCustomToolRename {"type": "custom", "name": "read_file", "description": "Read file"} ] }`) - out := ConvertOpenAIResponsesRequestToInteractions("antigravity-preview-05-2026", raw, false) + out, _ := ConvertOpenAIResponsesRequestToInteractions("antigravity-preview-05-2026", raw, false) if got := gjson.GetBytes(out, "tools.0.name").String(); got != "external_read_file" { t.Fatalf("tools.0.name = %q, want external_read_file", got) } @@ -644,7 +644,7 @@ func TestConvertOpenAIResponsesRequestToInteractions_FixedFixtureFullNamespaceEx ] }` - out := ConvertOpenAIResponsesRequestToInteractions("devin/gemini-3-7-flash", []byte(fixture), false) + out, _ := ConvertOpenAIResponsesRequestToInteractions("devin/gemini-3-7-flash", []byte(fixture), false) tools := gjson.GetBytes(out, "tools").Array() expectedNames := []string{ "top_fn_1", @@ -699,7 +699,7 @@ func TestConvertOpenAIResponsesRequestToInteractions_LogFilePayload(t *testing.T }` } - out := ConvertOpenAIResponsesRequestToInteractions("devin/gemini-3-7-flash", []byte(reqBody), false) + out, _ := ConvertOpenAIResponsesRequestToInteractions("devin/gemini-3-7-flash", []byte(reqBody), false) tools := gjson.GetBytes(out, "tools").Array() if len(tools) == 0 { @@ -778,7 +778,7 @@ func TestConvertOpenAIResponsesRequestToInteractions_DevinToolsFilterAndObfuscat ] }`) - out := ConvertOpenAIResponsesRequestToInteractions("devin/swe-2", responsesPayload, false) + out, _ := ConvertOpenAIResponsesRequestToInteractions("devin/swe-2", responsesPayload, false) tools := gjson.GetBytes(out, "tools").Array() toolNames := make([]string, 0, len(tools)) @@ -858,7 +858,7 @@ func TestConvertOpenAIResponsesRequestToInteractions_AntigravityDoesNotFilterDev "input": "hello" }`) - out := ConvertOpenAIResponsesRequestToInteractions("antigravity-preview-05-2026", responsesPayload, false) + out, _ := ConvertOpenAIResponsesRequestToInteractions("antigravity-preview-05-2026", responsesPayload, false) // In Antigravity, mcp__codex_app__automation_update should NOT be filtered by Devin rules foundAuto := false diff --git a/internal/translator/openai/interactions/responses/interactions_openai_responses_user_turn_test.go b/internal/translator/openai/interactions/responses/interactions_openai_responses_user_turn_test.go index 7b7ad74204b..65c49266701 100644 --- a/internal/translator/openai/interactions/responses/interactions_openai_responses_user_turn_test.go +++ b/internal/translator/openai/interactions/responses/interactions_openai_responses_user_turn_test.go @@ -178,7 +178,7 @@ func TestConvertOpenAIResponsesRequestToInteractions_DeveloperAttachmentIsNotAUs func TestConvertOpenAIResponsesRequestToInteractions_ExportedWrapperKeepsAJSONBody(t *testing.T) { input := interactionsTurnPayload("", interactionsUserTurn("user", interactionsTurnFileID)) - if body := ConvertOpenAIResponsesRequestToInteractions("gemini-3.5-flash", input, false); !gjson.ValidBytes(body) { + if body, _ := ConvertOpenAIResponsesRequestToInteractions("gemini-3.5-flash", input, false); !gjson.ValidBytes(body) { t.Fatalf("body is not JSON: %q", body) } } diff --git a/internal/translator/openai/openai/chat-completions/openai_openai_request.go b/internal/translator/openai/openai/chat-completions/openai_openai_request.go index dd3ee5ab9d5..bb97e243363 100644 --- a/internal/translator/openai/openai/chat-completions/openai_openai_request.go +++ b/internal/translator/openai/openai/chat-completions/openai_openai_request.go @@ -17,10 +17,10 @@ import ( // // Returns: // - []byte: The transformed request data in OpenAI API format -func ConvertOpenAIRequestToOpenAI(modelName string, inputRawJSON []byte, _ bool) []byte { +func ConvertOpenAIRequestToOpenAI(modelName string, inputRawJSON []byte, _ bool) ([]byte, error) { currentModel := gjson.GetBytes(inputRawJSON, "model") if currentModel.Type == gjson.String && currentModel.String() == modelName { - return inputRawJSON + return inputRawJSON, nil } // Update the "model" field in the JSON payload with the provided modelName @@ -30,7 +30,7 @@ func ConvertOpenAIRequestToOpenAI(modelName string, inputRawJSON []byte, _ bool) // If there's an error, return the original JSON or handle the error appropriately. // For now, we'll return the original, but in a real scenario, logging or a more robust error // handling mechanism would be needed. - return inputRawJSON + return inputRawJSON, nil } - return updatedJSON + return updatedJSON, nil } diff --git a/internal/translator/openai/openai/chat-completions/openai_openai_request_test.go b/internal/translator/openai/openai/chat-completions/openai_openai_request_test.go index 80a71a28a58..b721a256982 100644 --- a/internal/translator/openai/openai/chat-completions/openai_openai_request_test.go +++ b/internal/translator/openai/openai/chat-completions/openai_openai_request_test.go @@ -9,7 +9,7 @@ import ( func TestConvertOpenAIRequestToOpenAIReusesMatchingModelPayload(t *testing.T) { input := []byte(`{"model":"gpt-test","messages":[{"role":"user","content":"hello"}]}`) - output := ConvertOpenAIRequestToOpenAI("gpt-test", input, false) + output, _ := ConvertOpenAIRequestToOpenAI("gpt-test", input, false) if &output[0] != &input[0] { t.Fatal("matching model caused a payload copy") @@ -19,7 +19,7 @@ func TestConvertOpenAIRequestToOpenAIReusesMatchingModelPayload(t *testing.T) { func TestConvertOpenAIRequestToOpenAIUpdatesDifferentModel(t *testing.T) { input := []byte(`{"model":"old-model","messages":[]}`) - output := ConvertOpenAIRequestToOpenAI("new-model", input, false) + output, _ := ConvertOpenAIRequestToOpenAI("new-model", input, false) if model := gjson.GetBytes(output, "model").String(); model != "new-model" { t.Fatalf("model = %q, want new-model", model) diff --git a/internal/translator/openai/openai/responses/custom_tool_namespace_recovery_test.go b/internal/translator/openai/openai/responses/custom_tool_namespace_recovery_test.go index 4ca24f78769..43a47543fdd 100644 --- a/internal/translator/openai/openai/responses/custom_tool_namespace_recovery_test.go +++ b/internal/translator/openai/openai/responses/custom_tool_namespace_recovery_test.go @@ -68,7 +68,7 @@ func assertRecoveredCustomCall(t *testing.T, item gjson.Result, withInput bool) func TestCustomToolReplayPreservesNamespaceAndResultPair(t *testing.T) { for _, namespace := range []string{`,"namespace":"functions"`, ""} { request := strings.TrimSuffix(namespaceRecoveryRequest, "]}") + fmt.Sprintf(`,{"type":"custom_tool_call","name":"exec"%s,"call_id":"call_fixture","input":"text(1);"},{"type":"custom_tool_call_output","call_id":"call_fixture","output":[{"type":"input_text","text":"1"}]}]}`, namespace) - body := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("fixture", []byte(request), false) + body, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("fixture", []byte(request), false) if got := gjson.GetBytes(body, "messages.0.tool_calls.0.function.name").String(); got != "functions__exec" { t.Fatalf("replay name %q: %s", got, body) } diff --git a/internal/translator/openai/openai/responses/init.go b/internal/translator/openai/openai/responses/init.go index 06e0de7c7cc..96a5d1ed965 100644 --- a/internal/translator/openai/openai/responses/init.go +++ b/internal/translator/openai/openai/responses/init.go @@ -4,18 +4,16 @@ import ( . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/translator" - sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) func init() { translator.Register( OpenaiResponse, OpenAI, - nil, + ConvertOpenAIResponsesRequestToOpenAIChatCompletions, interfaces.TranslateResponse{ Stream: ConvertOpenAIChatCompletionsResponseToOpenAIResponses, NonStream: ConvertOpenAIChatCompletionsResponseToOpenAIResponsesNonStream, }, ) - sdktranslator.Default().RegisterCheckedRequest(sdktranslator.FormatOpenAIResponse, sdktranslator.FormatOpenAI, convertOpenAIResponsesRequestToOpenAIChatCompletions) } diff --git a/internal/translator/openai/openai/responses/openai_openai-responses_request.go b/internal/translator/openai/openai/responses/openai_openai-responses_request.go index 87ed9697daa..c27cd6eb5d0 100644 --- a/internal/translator/openai/openai/responses/openai_openai-responses_request.go +++ b/internal/translator/openai/openai/responses/openai_openai-responses_request.go @@ -27,9 +27,9 @@ import ( // // Returns: // - []byte: The transformed request data in OpenAI chat completions format -func ConvertOpenAIResponsesRequestToOpenAIChatCompletions(modelName string, inputRawJSON []byte, stream bool) []byte { - body, _ := convertOpenAIResponsesRequestToOpenAIChatCompletions(modelName, inputRawJSON, stream) - return body +func ConvertOpenAIResponsesRequestToOpenAIChatCompletions(modelName string, inputRawJSON []byte, stream bool) ([]byte, error) { + return convertOpenAIResponsesRequestToOpenAIChatCompletions(modelName, inputRawJSON, stream) + } // convertOpenAIResponsesRequestToOpenAIChatCompletions also reports a file or diff --git a/internal/translator/openai/openai/responses/openai_openai-responses_request_test.go b/internal/translator/openai/openai/responses/openai_openai-responses_request_test.go index 1ca1ea56ded..878567cd5a9 100644 --- a/internal/translator/openai/openai/responses/openai_openai-responses_request_test.go +++ b/internal/translator/openai/openai/responses/openai_openai-responses_request_test.go @@ -32,7 +32,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_MergeConsecutiveFu }`) t.Logf("input json:\n%s", prettyJSONForTest(raw)) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("kimi-k2.6", raw, true) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("kimi-k2.6", raw, true) t.Logf("output json:\n%s", prettyJSONForTest(out)) msgs := gjson.GetBytes(out, "messages") @@ -74,7 +74,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_SplitFunctionCalls }`) t.Logf("input json:\n%s", prettyJSONForTest(raw)) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("kimi-k2.6", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("kimi-k2.6", raw, false) t.Logf("output json:\n%s", prettyJSONForTest(out)) if got := len(gjson.GetBytes(out, "messages").Array()); got != 3 { @@ -99,7 +99,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_DefersMessageUntil }`) t.Logf("input json:\n%s", prettyJSONForTest(raw)) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("kimi-k2.6", raw, true) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("kimi-k2.6", raw, true) t.Logf("output json:\n%s", prettyJSONForTest(out)) if got := len(gjson.GetBytes(out, "messages").Array()); got != 4 { @@ -160,7 +160,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_UnwrapsStringified ] }`, tt.output)) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("k3", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("k3", raw, false) content := gjson.GetBytes(out, "messages.1.content") if !content.IsArray() { t.Fatalf("expected tool content array, got %s; output=%s", content.Raw, out) @@ -199,7 +199,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_UnwrapsStringified ] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("kimi-k3", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("kimi-k3", raw, false) content := gjson.GetBytes(out, "messages.1.content") if !content.IsArray() { t.Fatalf("expected custom tool content array, got %s; output=%s", content.Raw, out) @@ -235,7 +235,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_PreservesCustomToo ] }`, tt.output)) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("kimi-k3", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("kimi-k3", raw, false) content := gjson.GetBytes(out, "messages.1.content") if content.Type != gjson.String { t.Fatalf("expected custom tool content string, got %s; output=%s", content.Raw, out) @@ -262,7 +262,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_ConvertsStructured ] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("k3", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("k3", raw, false) content := gjson.GetBytes(out, "messages.1.content") if !content.IsArray() { t.Fatalf("expected tool content array, got %s; output=%s", content.Raw, out) @@ -303,7 +303,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_KeepsNonImageToolO ] }`, tt.output)) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("k3", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("k3", raw, false) content := gjson.GetBytes(out, "messages.1.content") if content.Type != gjson.String { t.Fatalf("expected tool content string, got %s; output=%s", content.Raw, out) @@ -336,7 +336,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_AttachesReasoningT }`) t.Logf("input json:\n%s", prettyJSONForTest(raw)) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", raw, false) t.Logf("output json:\n%s", prettyJSONForTest(out)) if got := gjson.GetBytes(out, "messages.#").Int(); got != 2 { @@ -374,7 +374,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_PreservesAssistant ] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("kimi-k3", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("kimi-k3", raw, false) messages := gjson.GetBytes(out, "messages").Array() if got := len(messages); got != 2 { @@ -408,7 +408,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_DoesNotMergeToolCa ] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("kimi-k3", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("kimi-k3", raw, false) messages := gjson.GetBytes(out, "messages").Array() if got := len(messages); got != 4 { @@ -435,7 +435,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_MergesDistinctReas ] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("kimi-k3", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("kimi-k3", raw, false) messages := gjson.GetBytes(out, "messages").Array() if got := len(messages); got != 1 { @@ -458,7 +458,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_ReplacesUnavailabl ] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("kimi-k3", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("kimi-k3", raw, false) messages := gjson.GetBytes(out, "messages").Array() if got := len(messages); got != 1 { @@ -483,7 +483,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_AttachesReasoningT }`) t.Logf("input json:\n%s", prettyJSONForTest(raw)) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", raw, true) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", raw, true) t.Logf("output json:\n%s", prettyJSONForTest(out)) if got := gjson.GetBytes(out, "messages.#").Int(); got != 2 { @@ -512,7 +512,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_KeepsReasoningBefo }`) t.Logf("input json:\n%s", prettyJSONForTest(raw)) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", raw, false) t.Logf("output json:\n%s", prettyJSONForTest(out)) if got := gjson.GetBytes(out, "messages.#").Int(); got != 2 { @@ -549,7 +549,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_PreservesReasoning ] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4.1-flash", raw, true) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4.1-flash", raw, true) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 8 { @@ -589,7 +589,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_FallsBackToPlaceho ] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4.1-flash", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4.1-flash", raw, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 2 { @@ -610,7 +610,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_EffortNoneDoesNotI ] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-4o", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-4o", raw, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 2 { @@ -634,7 +634,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_PreservesReasoning ] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4.1-flash", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4.1-flash", raw, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 4 { @@ -662,7 +662,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_ResetsReasoningAcr ] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4.1-flash", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4.1-flash", raw, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 5 { @@ -707,7 +707,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_FlattensNamespaceT }`) t.Logf("input json:\n%s", prettyJSONForTest(raw)) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", raw, false) t.Logf("output json:\n%s", prettyJSONForTest(out)) if got := gjson.GetBytes(out, "tools.#").Int(); got != 1 { @@ -742,7 +742,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_QualifiesNamespace ] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", raw, false) gotHistoryName := gjson.GetBytes(out, "messages.0.tool_calls.0.function.name").String() gotDeclaredName := gjson.GetBytes(out, "tools.0.function.name").String() @@ -786,7 +786,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_FlattensNamespaceC for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5.4", tt.raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5.4", tt.raw, false) if got := gjson.GetBytes(out, "tools.#").Int(); got != 1 { t.Fatalf("tools count = %d, want 1; output=%s", got, out) @@ -831,7 +831,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_PreservesStructure }`) t.Logf("input json:\n%s", prettyJSONForTest(raw)) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5.4", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5.4", raw, false) t.Logf("output json:\n%s", prettyJSONForTest(out)) if got := gjson.GetBytes(out, "tool_choice.type").String(); got != "function" { @@ -861,7 +861,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_ConvertsCanonicalR "max_output_tokens": 512 }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5.4", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5.4", raw, false) if got := gjson.GetBytes(out, "tool_choice.type").String(); got != "function" { t.Fatalf("tool_choice.type = %q, want function; output=%s", got, string(out)) @@ -897,7 +897,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_ConvertsNamespaceA } }`) - outNamespace := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5.4", rawNamespace, false) + outNamespace, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5.4", rawNamespace, false) if got := gjson.GetBytes(outNamespace, "tool_choice.type").String(); got != "function" { t.Fatalf("tool_choice.type = %q, want function; output=%s", got, string(outNamespace)) } @@ -934,7 +934,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_ConvertsNamespaceA } }`) - outExplicitNamespace := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5.4", rawExplicitNamespace, false) + outExplicitNamespace, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5.4", rawExplicitNamespace, false) if got := gjson.GetBytes(outExplicitNamespace, "tool_choice.function.name").String(); got != "service_tools__lookup" { t.Fatalf("explicit namespace tool_choice.function.name = %q, want service_tools__lookup; output=%s", got, string(outExplicitNamespace)) } @@ -961,7 +961,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_ConvertsNamespaceA } }`) - outCustom := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5.4", rawCustom, false) + outCustom, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5.4", rawCustom, false) if got := gjson.GetBytes(outCustom, "tool_choice.type").String(); got != "function" { t.Fatalf("tool_choice.type = %q, want function; output=%s", got, string(outCustom)) } @@ -982,7 +982,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_ConvertsNamespaceA ], "tool_choice": ` + scalar + ` }`) - outScalar := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5.4", rawScalar, false) + outScalar, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5.4", rawScalar, false) if got := gjson.GetBytes(outScalar, "tool_choice").Raw; got != scalar { t.Fatalf("tool_choice = %q, want %s; output=%s", got, scalar, string(outScalar)) } @@ -1015,7 +1015,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_OmitsToolSettingsW for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("grok-4.5", tt.raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("grok-4.5", tt.raw, false) for _, field := range []string{"tools", "tool_choice", "parallel_tool_calls"} { if got := gjson.GetBytes(out, field); got.Exists() { @@ -1038,7 +1038,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_PreservesParallelT "parallel_tool_calls": false }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("grok-4.5", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("grok-4.5", raw, false) if got := gjson.GetBytes(out, "parallel_tool_calls"); !got.Exists() || got.Bool() { t.Fatalf("parallel_tool_calls = %v, want false; output=%s", got.Value(), out) @@ -1065,7 +1065,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_PreservesJSONSchem } }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", raw, false) if got := gjson.GetBytes(out, "response_format.type").String(); got != "json_schema" { t.Fatalf("response_format.type = %q, want json_schema; output=%s", got, out) @@ -1093,7 +1093,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_PreservesJSONSchem func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_PreservesJSONObjectTextFormat(t *testing.T) { raw := []byte(`{"text":{"format":{"type":"json_object"}}}`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", raw, false) if got := gjson.GetBytes(out, "response_format.type").String(); got != "json_object" { t.Fatalf("response_format.type = %q, want json_object; output=%s", got, out) @@ -1106,7 +1106,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_PreservesJSONObjec func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_OmitsResponseFormatWithoutTextFormat(t *testing.T) { raw := []byte(`{"input":"Return plain text."}`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", raw, false) if got := gjson.GetBytes(out, "response_format"); got.Exists() { t.Fatalf("response_format should be omitted, got %s; output=%s", got.Raw, out) @@ -1142,7 +1142,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_NormalizesInputIma ] }`, tt.detailJSON)) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5.4", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5.4", raw, false) if got := gjson.GetBytes(out, "messages.0.content.0.image_url.url").String(); got != "https://example.com/image.png" { t.Fatalf("image URL = %q, want https://example.com/image.png; output=%s", got, out) } @@ -1177,7 +1177,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_DeduplicatesToolsA }`) t.Logf("input json:\n%s", prettyJSONForTest(raw)) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", raw, false) t.Logf("output json:\n%s", prettyJSONForTest(out)) if got := gjson.GetBytes(out, "tools.#").Int(); got != 1 { @@ -1210,7 +1210,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_DeduplicatesNamesp }`) t.Logf("input json:\n%s", prettyJSONForTest(raw)) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", raw, false) t.Logf("output json:\n%s", prettyJSONForTest(out)) if got := gjson.GetBytes(out, "tools.#").Int(); got != 1 { @@ -1240,7 +1240,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_KeepsDistinctTools }`) t.Logf("input json:\n%s", prettyJSONForTest(raw)) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", raw, false) t.Logf("output json:\n%s", prettyJSONForTest(out)) want := []string{"get_time", "get_weather", "get_date"} @@ -1484,7 +1484,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_FunctionCallOutput ] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", inputJSON, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", inputJSON, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 2 { t.Fatalf("expected 2 messages (assistant, tool), got %d; output=%s", len(messages), string(out)) @@ -1526,7 +1526,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_MixedMissingAndExp ] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", inputJSON, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", inputJSON, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 3 { t.Fatalf("expected 3 messages (assistant, tool_b, tool_a), got %d; output=%s", len(messages), string(out)) @@ -1557,7 +1557,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_DefersMessageUntil ] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", inputJSON, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", inputJSON, false) messages := gjson.GetBytes(out, "messages").Array() if len(messages) != 3 { t.Fatalf("expected 3 messages (assistant, tool, user), got %d; output=%s", len(messages), string(out)) @@ -1600,7 +1600,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_MixedMissingAndExp ] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", inputJSON, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4-flash", inputJSON, false) messages := gjson.GetBytes(out, "messages").Array() resultMap := make(map[string]string) @@ -1629,7 +1629,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_OrphanFunctionCall ] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4.1-flash", inputJSON, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4.1-flash", inputJSON, false) messages := gjson.GetBytes(out, "messages").Array() delegationFound := false @@ -1668,7 +1668,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_UnpairedExplicitCa ] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4.1-flash", inputJSON, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4.1-flash", inputJSON, false) messages := gjson.GetBytes(out, "messages").Array() delegationFound := false @@ -1718,7 +1718,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_CapsLongNamespaceT ] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", raw, false) tools := gjson.GetBytes(out, "tools").Array() if len(tools) != 4 { t.Fatalf("tools count = %d, want 4; output=%s", len(tools), out) @@ -1759,7 +1759,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_DisambiguatesTrunc ] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", raw, false) tools := gjson.GetBytes(out, "tools").Array() if len(tools) != 2 { t.Fatalf("tools count = %d, want 2; output=%s", len(tools), out) @@ -1795,7 +1795,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_DisambiguatesTrunc } ] }`) - replayOut := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", merged, false) + replayOut, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", merged, false) replayedName := "" for _, m := range gjson.GetBytes(replayOut, "messages").Array() { if m.Get("role").String() == "assistant" { @@ -1830,7 +1830,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_LongDeclarationDoe {"type":"function","name":"` + flatName + `","parameters":{"type":"object"}} ]` - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", []byte(`{ + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", []byte(`{ "input": [{"role":"user","content":"hi"}], "tools": `+toolsJSON+` }`), false) @@ -1860,7 +1860,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_LongDeclarationDoe ], "tools": ` + toolsJSON + ` }`) - replayOut := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", replay, false) + replayOut, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", replay, false) for _, m := range gjson.GetBytes(replayOut, "messages").Array() { if m.Get("role").String() == "assistant" { if got := m.Get("tool_calls.0.function.name").String(); got != flatName { @@ -1869,7 +1869,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_LongDeclarationDoe } } - forcedOut := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", []byte(`{ + forcedOut, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", []byte(`{ "input": [{"role":"user","content":"hi"}], "tools": `+toolsJSON+`, "tool_choice": {"type":"function","function":{"name":"`+flatName+`"}} @@ -1889,7 +1889,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_LongDeclarationDoe ], "tools": ` + toolsJSON + ` }`) - longReplayOut := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", longReplay, false) + longReplayOut, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", longReplay, false) for _, m := range gjson.GetBytes(longReplayOut, "messages").Array() { if m.Get("role").String() == "assistant" { if got := m.Get("tool_calls.0.function.name").String(); got != suffixed { @@ -1925,7 +1925,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_AmbiguousLongLocal ], "tools": ` + toolsJSON + ` }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", replay, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", replay, false) declaredAliases := map[string]bool{} for _, tool := range gjson.GetBytes(out, "tools").Array() { @@ -1971,7 +1971,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_LongAliasDoesNotDi } ]` - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", []byte(`{ + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", []byte(`{ "input": [{"role":"user","content":"hi"}], "tools": `+toolsJSON+` }`), false) @@ -1998,7 +1998,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_LongAliasDoesNotDi ], "tools": ` + toolsJSON + ` }`) - replayOut := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", replay, false) + replayOut, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", replay, false) for _, m := range gjson.GetBytes(replayOut, "messages").Array() { if m.Get("role").String() == "assistant" { if got := m.Get("tool_calls.0.function.name").String(); got != namespacedAlias { @@ -2008,7 +2008,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_LongAliasDoesNotDi } // tool_choice carrying the bare local name must resolve the same way. - forcedOut := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", []byte(`{ + forcedOut, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", []byte(`{ "input": [{"role":"user","content":"hi"}], "tools": `+toolsJSON+`, "tool_choice": {"type":"function","function":{"name":"`+localName+`"}} @@ -2046,7 +2046,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_SharedLocalNameIsN } ]` - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", []byte(`{ + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", []byte(`{ "input": [{"role":"user","content":"hi"}], "tools": `+toolsJSON+` }`), false) @@ -2079,7 +2079,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_SharedLocalNameIsN {"mcp__alpha", alphaAlias}, {"mcp__beta", betaAlias}, } { - namespacedOut := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", []byte(`{ + namespacedOut, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", []byte(`{ "input": [ {"type":"function_call","call_id":"call_1","namespace":"`+tc.namespace+`","name":"`+sharedLocal+`","arguments":"{}"}, {"type":"function_call_output","call_id":"call_1","output":"ok"} @@ -2099,7 +2099,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_SharedLocalNameIsN // A namespace-less replayed call or tool_choice carrying the ambiguous // bare name must stay unresolved rather than pick a winner. - bareOut := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", []byte(`{ + bareOut, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", []byte(`{ "input": [ {"type":"function_call","call_id":"call_1","name":"`+sharedLocal+`","arguments":"{}"}, {"type":"function_call_output","call_id":"call_1","output":"ok"} @@ -2118,7 +2118,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_SharedLocalNameIsN t.Fatalf("ambiguous replayed call resolved to declared alias %q, silently invoking one namespace's tool; output=%s", got, bareOut) } } - bareForced := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", []byte(`{ + bareForced, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", []byte(`{ "input": [{"role":"user","content":"hi"}], "tools": `+toolsJSON+`, "tool_choice": {"type":"function","function":{"name":"`+sharedLocal+`"}} @@ -2126,7 +2126,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_SharedLocalNameIsN if got := gjson.GetBytes(bareForced, "tool_choice.function.name").String(); aliases[got] { t.Fatalf("ambiguous tool_choice resolved to declared alias %q, silently invoking one namespace's tool; output=%s", got, bareForced) } - forcedAlpha := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", []byte(`{ + forcedAlpha, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", []byte(`{ "input": [{"role":"user","content":"hi"}], "tools": `+toolsJSON+`, "tool_choice": {"type":"function","namespace":"mcp__beta","function":{"name":"`+sharedLocal+`"}} @@ -2166,7 +2166,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_QualifiedIdentityO } ]` - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", []byte(`{ + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", []byte(`{ "input": [{"role":"user","content":"hi"}], "tools": `+toolsJSON+` }`), false) @@ -2186,7 +2186,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_QualifiedIdentityO } // Bare qualified name: provenance points at the alpha declaration. - bareOut := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", []byte(`{ + bareOut, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", []byte(`{ "input": [ {"type":"function_call","call_id":"call_1","name":"`+qualified+`","arguments":"{}"}, {"type":"function_call_output","call_id":"call_1","output":"ok"} @@ -2201,7 +2201,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_QualifiedIdentityO t.Fatalf("bare qualified name resolved to %q, want the identity owner's alias %q (beta's alias is %q); output=%s", got, alphaAlias, betaAlias, bareOut) } } - bareForced := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", []byte(`{ + bareForced, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", []byte(`{ "input": [{"role":"user","content":"hi"}], "tools": `+toolsJSON+`, "tool_choice": {"type":"function","function":{"name":"`+qualified+`"}} @@ -2219,7 +2219,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_QualifiedIdentityO {"alpha_ns", longChild, alphaAlias}, {"beta_ns", qualified, betaAlias}, } { - namespacedOut := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", []byte(`{ + namespacedOut, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("z-ai/glm-5.3-free", []byte(`{ "input": [ {"type":"function_call","call_id":"call_1","namespace":"`+tc.namespace+`","name":"`+tc.name+`","arguments":"{}"}, {"type":"function_call_output","call_id":"call_1","output":"ok"} @@ -2252,7 +2252,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_IncompleteToolCall ] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4.1-flash", inputJSON, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4.1-flash", inputJSON, false) messages := gjson.GetBytes(out, "messages").Array() roles := make([]string, 0, len(messages)) @@ -2287,7 +2287,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_CompleteToolCallsD ] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4.1-flash", inputJSON, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4.1-flash", inputJSON, false) messages := gjson.GetBytes(out, "messages").Array() roles := make([]string, 0, len(messages)) @@ -2327,7 +2327,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_MixedEmptyIDDoesNo ] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4.1-flash", inputJSON, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4.1-flash", inputJSON, false) messages := gjson.GetBytes(out, "messages").Array() roles := make([]string, 0, len(messages)) @@ -2356,7 +2356,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_DuplicateCallIDDoe ] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4.1-flash", inputJSON, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4.1-flash", inputJSON, false) messages := gjson.GetBytes(out, "messages").Array() roles := make([]string, 0, len(messages)) @@ -2385,7 +2385,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_DuplicateOutputCal ] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4.1-flash", inputJSON, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4.1-flash", inputJSON, false) messages := gjson.GetBytes(out, "messages").Array() roles := make([]string, 0, len(messages)) @@ -2417,7 +2417,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_DuplicateCustomOut ] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4.1-flash", inputJSON, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4.1-flash", inputJSON, false) messages := gjson.GetBytes(out, "messages").Array() roles := make([]string, 0, len(messages)) @@ -2451,7 +2451,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_MultipleOutputsWit ] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4.1-flash", inputJSON, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4.1-flash", inputJSON, false) messages := gjson.GetBytes(out, "messages").Array() roles := make([]string, 0, len(messages)) @@ -2500,7 +2500,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_MultipleOutputsWit ] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4.1-flash", inputJSON, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("deepseek-v4.1-flash", inputJSON, false) messages := gjson.GetBytes(out, "messages").Array() roles := make([]string, 0, len(messages)) @@ -2534,7 +2534,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_MapsMaxOutputToken "max_output_tokens": 1024 }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5.4", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5.4", raw, false) if got := gjson.GetBytes(out, "max_tokens").Int(); got != 1024 { t.Fatalf("max_tokens = %d, want 1024; output=%s", got, string(out)) @@ -2548,7 +2548,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_MapsMaxOutputToken "input": "hello" }`) - outWithoutLimit := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5.4", rawWithoutLimit, false) + outWithoutLimit, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5.4", rawWithoutLimit, false) if gjson.GetBytes(outWithoutLimit, "max_completion_tokens").Exists() { t.Fatalf("max_completion_tokens should be absent when omitted; output=%s", string(outWithoutLimit)) } @@ -2562,7 +2562,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_MapsMaxOutputToken "max_output_tokens": null }`) - outNull := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5.4", rawNull, false) + outNull, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5.4", rawNull, false) if got := gjson.GetBytes(outNull, "max_tokens"); !got.Exists() || got.Type != gjson.Null { t.Fatalf("max_tokens = %v, want null; output=%s", got, string(outNull)) } @@ -2599,7 +2599,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_NamespaceToolPrefi "input": [] }`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5.4", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5.4", raw, false) tools := gjson.GetBytes(out, "tools").Array() if len(tools) != 2 { t.Fatalf("len(tools) = %d, want 2; output=%s", len(tools), string(out)) @@ -2621,7 +2621,11 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_NamespaceToolPrefi func TestApplyPatchChatRequestContractAndHistory(t *testing.T) { request := []byte(`{"tools":[{"type":"namespace","name":"editor","tools":[{"type":"custom","name":"apply_patch","description":"Edit files. This is a FREEFORM tool, so do not wrap the patch in JSON.","format":{"type":"grammar","syntax":"lark","definition":"start: patch"},"cache_control":{"type":"ephemeral"}}]}],"input":[{"type":"custom_tool_call","namespace":"editor","name":"apply_patch","call_id":"c1","input":"*** Begin Patch\n*** Add File: a.txt\n+hello\n*** End Patch"},{"type":"custom_tool_call_output","call_id":"c1","output":"done"}]}`) - result := gjson.ParseBytes(ConvertOpenAIResponsesRequestToOpenAIChatCompletions("test", request, false)) + body1, errConvert1 := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("test", request, false) + if errConvert1 != nil { + t.Fatal(errConvert1) + } + result := gjson.ParseBytes(body1) tool := result.Get("tools.0.function") description := tool.Get("description").String() schema := tool.Get("parameters") diff --git a/internal/translator/openai/openai/responses/openai_openai-responses_user_turn_test.go b/internal/translator/openai/openai/responses/openai_openai-responses_user_turn_test.go index cd409745e48..f587603e62e 100644 --- a/internal/translator/openai/openai/responses/openai_openai-responses_user_turn_test.go +++ b/internal/translator/openai/openai/responses/openai_openai-responses_user_turn_test.go @@ -156,7 +156,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_MappedAttachmentBe func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_ExportedWrapperKeepsAJSONBody(t *testing.T) { input := chatPayload("", chatUserTurn(chatTurnFileURL)) - if body := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5", input, false); !gjson.ValidBytes(body) { + if body, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("gpt-5", input, false); !gjson.ValidBytes(body) { t.Fatalf("body is not JSON: %q", body) } } diff --git a/internal/translator/openai/openai/responses/openai_openai-responses_video_test.go b/internal/translator/openai/openai/responses/openai_openai-responses_video_test.go index 85dc99504bb..1df4689f2c2 100644 --- a/internal/translator/openai/openai/responses/openai_openai-responses_video_test.go +++ b/internal/translator/openai/openai/responses/openai_openai-responses_video_test.go @@ -61,7 +61,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_VideoInput(t *test for _, stream := range []bool{false, true} { t.Run(fmt.Sprintf("%s/stream=%t", tt.name, stream), func(t *testing.T) { raw := []byte(`{"input":[{"role":"user","content":[` + tt.part + `]}]}`) - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("video-model", raw, stream) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("video-model", raw, stream) content := gjson.GetBytes(out, "messages.0.content").Array() if len(content) != 1 { t.Fatalf("video content was lost: got %d parts, want 1; output=%s", len(content), out) @@ -97,7 +97,7 @@ func TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_MixedVideoInputOrd if err := json.Unmarshal([]byte(wantJSON), &want); err != nil { t.Fatal(err) } - out := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("video-model", raw, false) + out, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("video-model", raw, false) if got := gjson.GetBytes(out, "messages.0.content").Value(); !reflect.DeepEqual(got, want) { t.Fatalf("mixed content order or media changed: output=%s", out) } diff --git a/internal/translator/openai/openai/responses/responses_compatibility_digest_test.go b/internal/translator/openai/openai/responses/responses_compatibility_digest_test.go index 3e6f7660cbd..55d927853ea 100644 --- a/internal/translator/openai/openai/responses/responses_compatibility_digest_test.go +++ b/internal/translator/openai/openai/responses/responses_compatibility_digest_test.go @@ -19,7 +19,11 @@ func TestResponsesCompatibilityDigest(t *testing.T) { hash := sha256.New() ctx := context.Background() for _, request := range requests { - hash.Write(ConvertOpenAIResponsesRequestToOpenAIChatCompletions("test", request, true)) + body1, errConvert1 := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("test", request, true) + if errConvert1 != nil { + t.Fatal(errConvert1) + } + hash.Write(body1) for _, name := range []string{"editor__read", "read", "editor__patch", "patch", "unknown"} { var state any chunks := []string{ diff --git a/internal/translator/openai/openai/responses/shell_tool_test.go b/internal/translator/openai/openai/responses/shell_tool_test.go index 3cf36f01e0a..b081abed32f 100644 --- a/internal/translator/openai/openai/responses/shell_tool_test.go +++ b/internal/translator/openai/openai/responses/shell_tool_test.go @@ -13,7 +13,7 @@ import ( func TestLocalShellDeclarationSurvivesChatTranslation(t *testing.T) { request := []byte(`{"tools":[{"type":"shell","environment":{"type":"local"}}],"tool_choice":"auto","input":"Run echo SHELL_OK"}`) - got := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("test", request, false) + got, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("test", request, false) if gjson.GetBytes(got, "tools.#").Int() != 1 { t.Fatalf("local shell declaration was dropped from chat request: %s", got) } @@ -66,7 +66,7 @@ func shellStream(request []byte, name, args string) []gjson.Result { func TestLocalShellRoundTrip(t *testing.T) { request := []byte(shellRequest) - chat := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("test", request, false) + chat, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("test", request, false) name := gjson.GetBytes(chat, "tools.0.function.name").String() if name == "" || name == "__cpa_local_shell" || name == "__cpa_local_shell_1" || gjson.GetBytes(chat, "tools.#").Int() != 4 { t.Fatalf("synthetic tool collided with user tools: %s", chat) @@ -100,7 +100,7 @@ func TestLocalShellRoundTrip(t *testing.T) { } output := `{"type":"shell_call_output","call_id":"call_shell","max_output_length":4096,"output":[{"stdout":"SHELL_OK\n","stderr":"warning","outcome":{"type":"exit","exit_code":0}},{"stdout":"partial","stderr":"","outcome":{"type":"timeout"}}]}` replay, _ := sjson.SetRawBytes(request, "input", []byte("["+item.Raw+`,`+`{"type":"function_call","call_id":"call_user","name":"__cpa_local_shell","arguments":"{}"},`+output+`,`+`{"type":"function_call_output","call_id":"call_user","output":"ok"}]`)) - replayed := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("test", replay, false) + replayed, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("test", replay, false) if gjson.GetBytes(replayed, "messages.0.tool_calls.#").Int() != 2 || gjson.GetBytes(replayed, "messages.0.tool_calls.0.function.name").String() != name || gjson.GetBytes(replayed, "messages.0.tool_calls.0.function.arguments").String() != args { t.Fatalf("shell history not grouped/replayed: %s", replayed) } @@ -147,14 +147,14 @@ func TestLocalShellInvalidActions(t *testing.T) { func TestLocalShellOnlyExplicitLocalEnvironment(t *testing.T) { for _, environment := range []string{`{"type":"container_auto"}`, `{"type":"container_reference","container_id":"cntr_x"}`, `{}`} { request := []byte(`{"tools":[{"type":"shell","environment":` + environment + `}]}`) - got := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("test", request, false) + got, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("test", request, false) if gjson.GetBytes(got, "tools.#").Int() != 0 { t.Fatalf("hosted shell represented as local: %s", got) } } for _, choice := range []string{`"auto"`, `"required"`, `"none"`} { request := []byte(`{"tools":[{"type":"shell","environment":{"type":"local"}}],"tool_choice":` + choice + `}`) - got := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("test", request, false) + got, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("test", request, false) var expected string if errUnmarshal := json.Unmarshal([]byte(choice), &expected); errUnmarshal != nil { t.Fatal(errUnmarshal) @@ -168,7 +168,7 @@ func TestLocalShellOnlyExplicitLocalEnvironment(t *testing.T) { func TestLocalShellHistoryWithoutDeclaration(t *testing.T) { for _, tools := range []string{``, `,"tools":[]`, `,"tools":[{"type":"function","name":"__cpa_local_shell_1","parameters":{}}]`} { request := []byte(`{"input":[{"type":"shell_call","call_id":"shell_1","action":{"commands":["pwd"]}},{"type":"shell_call_output","call_id":"shell_1","output":[{"stdout":"/workspace","stderr":"","outcome":{"type":"exit","exit_code":0}}]},{"type":"function_call","call_id":"user_1","name":"__cpa_local_shell","arguments":"{}"},{"type":"function_call_output","call_id":"user_1","output":"ok"}]` + tools + `}`) - got := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("test", request, false) + got, _ := ConvertOpenAIResponsesRequestToOpenAIChatCompletions("test", request, false) calls := gjson.GetBytes(got, "messages.0.tool_calls").Array() if len(calls) != 1 || calls[0].Get("id").String() != "shell_1" || gjson.GetBytes(got, "messages.2.tool_calls.0.id").String() != "user_1" { t.Fatalf("shell history dropped without declaration: %s", got) diff --git a/sdk/api/handlers/openai/openai_handlers.go b/sdk/api/handlers/openai/openai_handlers.go index de21739f750..ff775d44e4e 100644 --- a/sdk/api/handlers/openai/openai_handlers.go +++ b/sdk/api/handlers/openai/openai_handlers.go @@ -134,7 +134,7 @@ func (h *OpenAIAPIHandler) ChatCompletions(c *gin.Context) { // Convert them to Chat Completions so downstream translators preserve tool metadata. if shouldTreatAsResponsesFormat(rawJSON) { modelName := gjson.GetBytes(rawJSON, "model").String() - rawJSON = responsesconverter.ConvertOpenAIResponsesRequestToOpenAIChatCompletions(modelName, rawJSON, stream) + rawJSON, _ = responsesconverter.ConvertOpenAIResponsesRequestToOpenAIChatCompletions(modelName, rawJSON, stream) stream = gjson.GetBytes(rawJSON, "stream").Bool() } diff --git a/sdk/translator/registry.go b/sdk/translator/registry.go index c05371649ad..95af51341fb 100644 --- a/sdk/translator/registry.go +++ b/sdk/translator/registry.go @@ -36,7 +36,7 @@ func (r *Registry) Register(from, to Format, request RequestTransform, response } if request != nil { r.requests[from][to] = func(_ context.Context, req RequestEnvelope) RequestEnvelope { - req.Body = request(req.Model, req.Body, req.Stream) + req.Body, req.Err = request(req.Model, req.Body, req.Stream) return req } } @@ -60,15 +60,6 @@ func (r *Registry) RegisterRequestEnvelope(from, to Format, request RequestEnvel } } -// RegisterCheckedRequest stores a request translator that may refuse a request, -// carrying the refusal on the envelope next to the legacy-shaped body. -func (r *Registry) RegisterCheckedRequest(from, to Format, request func(model string, body []byte, stream bool) ([]byte, error)) { - r.RegisterRequestEnvelope(from, to, func(_ context.Context, req RequestEnvelope) RequestEnvelope { - req.Body, req.Err = request(req.Model, req.Body, req.Stream) - return req - }) -} - // Unregister removes the request and response transforms for one format pair. // Empty parent maps are dropped so a temporary registration can be restored. func (r *Registry) Unregister(from, to Format) { diff --git a/sdk/translator/registry_summary_test.go b/sdk/translator/registry_summary_test.go index 75ab1cd5aa6..df23767dd05 100644 --- a/sdk/translator/registry_summary_test.go +++ b/sdk/translator/registry_summary_test.go @@ -80,8 +80,8 @@ func TestRegistryTranslateRequestAppliesSummaryIntent(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { registry := NewRegistry() - registry.Register(test.from, test.to, func(_ string, _ []byte, _ bool) []byte { - return []byte(test.translated) + registry.Register(test.from, test.to, func(_ string, _ []byte, _ bool) ([]byte, error) { + return []byte(test.translated), nil }, ResponseTransform{}) out := registry.TranslateRequest(test.from, test.to, "model", []byte(test.input), false) result := gjson.GetBytes(out, test.path) @@ -97,8 +97,8 @@ func TestRegistryTranslateRequestAppliesSummaryIntent(t *testing.T) { func TestRegistryTranslateRequestActivatesClaudeForEnabledSummary(t *testing.T) { registry := NewRegistry() - registry.Register(FormatOpenAIResponse, FormatClaude, func(_ string, _ []byte, _ bool) []byte { - return []byte(`{"model":"claude-opus-5","max_tokens":32000}`) + registry.Register(FormatOpenAIResponse, FormatClaude, func(_ string, _ []byte, _ bool) ([]byte, error) { + return []byte(`{"model":"claude-opus-5","max_tokens":32000}`), nil }, ResponseTransform{}) out := registry.TranslateRequest( FormatOpenAIResponse, @@ -117,8 +117,8 @@ func TestRegistryTranslateRequestActivatesClaudeForEnabledSummary(t *testing.T) func TestRegistryTranslateRequestDoesNotActivateClaudeForDisabledSummary(t *testing.T) { registry := NewRegistry() - registry.Register(FormatOpenAIResponse, FormatClaude, func(_ string, _ []byte, _ bool) []byte { - return []byte(`{"model":"claude-opus-5","max_tokens":32000}`) + registry.Register(FormatOpenAIResponse, FormatClaude, func(_ string, _ []byte, _ bool) ([]byte, error) { + return []byte(`{"model":"claude-opus-5","max_tokens":32000}`), nil }, ResponseTransform{}) out := registry.TranslateRequest( FormatOpenAIResponse, @@ -241,8 +241,8 @@ func TestRegistryTranslateRequestPluginNormalizerOwnsSourceSummaryIntent(t *test func TestRegistryTranslateRequestNormalizerOwnsFinalSummaryField(t *testing.T) { registry := NewRegistry() - registry.Register(FormatOpenAIResponse, FormatGemini, func(_ string, _ []byte, _ bool) []byte { - return []byte(`{"generationConfig":{"thinkingConfig":{"thinkingLevel":"high"}}}`) + registry.Register(FormatOpenAIResponse, FormatGemini, func(_ string, _ []byte, _ bool) ([]byte, error) { + return []byte(`{"generationConfig":{"thinkingConfig":{"thinkingLevel":"high"}}}`), nil }, ResponseTransform{}) hooks := &fakePluginHooks{normalizeRequest: func(body []byte) []byte { if !gjson.GetBytes(body, "generationConfig.thinkingConfig.includeThoughts").Bool() { diff --git a/sdk/translator/registry_test.go b/sdk/translator/registry_test.go index eea44e905b9..9dd2eb30d8f 100644 --- a/sdk/translator/registry_test.go +++ b/sdk/translator/registry_test.go @@ -150,8 +150,8 @@ func TestTranslateRequest_RegisteredTransformTakesPrecedence(t *testing.T) { from := Format("openai-response") to := Format("openai-response") - r.Register(from, to, func(model string, rawJSON []byte, stream bool) []byte { - return []byte(`{"model":"from-transform"}`) + r.Register(from, to, func(model string, rawJSON []byte, stream bool) ([]byte, error) { + return []byte(`{"model":"from-transform"}`), nil }, ResponseTransform{}) input := []byte(`{"model":"copilot/gpt-5-mini","input":"ping"}`) @@ -172,8 +172,8 @@ func TestHasRequestTransformer(t *testing.T) { t.Fatal("request transformer exists before registration") } - r.Register(from, to, func(model string, rawJSON []byte, stream bool) []byte { - return rawJSON + r.Register(from, to, func(model string, rawJSON []byte, stream bool) ([]byte, error) { + return rawJSON, nil }, ResponseTransform{}) if !r.HasRequestTransformer(from, to) { @@ -186,8 +186,8 @@ func TestHasResponseTransformerIgnoresEmptyRegistration(t *testing.T) { from := Format("from") to := Format("to") - r.Register(from, to, func(model string, rawJSON []byte, stream bool) []byte { - return rawJSON + r.Register(from, to, func(model string, rawJSON []byte, stream bool) ([]byte, error) { + return rawJSON, nil }, ResponseTransform{}) if r.HasResponseTransformer(from, to) { @@ -270,8 +270,8 @@ func TestTranslateRequest_PluginTranslatorOnlyWhenNativeMissing(t *testing.T) { requestTranslateOK: true, } withNative.SetPluginHooks(nativeHooks) - withNative.Register(from, to, func(model string, rawJSON []byte, stream bool) []byte { - return []byte(`{"model":"native-request"}`) + withNative.Register(from, to, func(model string, rawJSON []byte, stream bool) ([]byte, error) { + return []byte(`{"model":"native-request"}`), nil }, ResponseTransform{}) gotNative := withNative.TranslateRequest(from, to, "resolved", []byte(`{"model":"prefixed/resolved"}`), false) @@ -401,8 +401,8 @@ func TestRequestEnvelopePreservesRegisteredTransformDispatch(t *testing.T) { } // A custom registration replaces the envelope-aware native route. - r.Register(from, to, func(string, []byte, bool) []byte { - return []byte(`{"source":"custom"}`) + r.Register(from, to, func(string, []byte, bool) ([]byte, error) { + return []byte(`{"source":"custom"}`), nil }, ResponseTransform{}) for _, payload := range [][]byte{ []byte(`{"input":"hello"}`), @@ -443,8 +443,8 @@ func TestPluginNormalizersChainAfterNative(t *testing.T) { }, } r.SetPluginHooks(hooks) - r.Register(from, to, func(model string, rawJSON []byte, stream bool) []byte { - return []byte(`{"stage":"native-request"}`) + r.Register(from, to, func(model string, rawJSON []byte, stream bool) ([]byte, error) { + return []byte(`{"stage":"native-request"}`), nil }, ResponseTransform{}) r.Register(to, from, nil, ResponseTransform{ NonStream: func(ctx context.Context, model string, originalRequestRawJSON, requestRawJSON, rawJSON []byte, param *any) []byte { @@ -476,8 +476,8 @@ func TestUnregisterRestoresFormatPair(t *testing.T) { if HasRequestTransformer(from, to) || HasRequestTransformer(from, other) { t.Fatal("test formats are already registered") } - identity := func(_ string, rawJSON []byte, _ bool) []byte { - return append([]byte(nil), rawJSON...) + identity := func(_ string, rawJSON []byte, _ bool) ([]byte, error) { + return append([]byte(nil), rawJSON...), nil } Register(from, to, identity, ResponseTransform{ NonStream: func(context.Context, string, []byte, []byte, []byte, *any) []byte { diff --git a/sdk/translator/types.go b/sdk/translator/types.go index c4e52a65ed4..81b4decec76 100644 --- a/sdk/translator/types.go +++ b/sdk/translator/types.go @@ -3,10 +3,11 @@ package translator import "context" -// RequestTransform is a function type that converts a request payload from a source schema to a target schema. -// It takes the model name, the raw JSON payload of the request, and a boolean indicating if the request is for a streaming response. -// It returns the converted request payload as a byte slice. -type RequestTransform func(model string, rawJSON []byte, stream bool) []byte +// RequestTransform converts a request payload from a source schema to a target schema. +// A non-nil error is a request-scoped refusal. Registry.Register stores it on +// RequestEnvelope.Err so executors can reject the request before calling upstream. +// TranslateRequest still returns only the body for legacy callers. +type RequestTransform func(model string, rawJSON []byte, stream bool) ([]byte, error) // RequestEnvelopeTransform translates a request while preserving request-scoped metadata. type RequestEnvelopeTransform func(ctx context.Context, req RequestEnvelope) RequestEnvelope From 2d5351b3e5822ad60c34410c5e62a88897f00b38 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Thu, 8 Oct 2026 12:39:31 +0800 Subject: [PATCH 095/142] feat(vertex): add support for native gemini interactions api - Extract shared Gemini Interactions helpers for payload translation, input sanitization, thinking, and SSE streaming - Add `interactions` configuration option to Vertex credentials - Support native non-streaming and streaming Interactions API execution in Gemini Vertex executor Closes: #6445 --- config.example.yaml | 1 + internal/config/vertex_compat.go | 3 + internal/runtime/executor/gemini_executor.go | 120 +--- .../executor/gemini_vertex_executor.go | 387 +++++++++++++ ...emini_vertex_executor_interactions_test.go | 543 ++++++++++++++++++ .../executor/helps/gemini_interactions.go | 187 ++++++ internal/watcher/synthesizer/config.go | 3 + .../gemini/interactions_handlers_test.go | 59 ++ 8 files changed, 1193 insertions(+), 110 deletions(-) create mode 100644 internal/runtime/executor/gemini_vertex_executor_interactions_test.go create mode 100644 internal/runtime/executor/helps/gemini_interactions.go diff --git a/config.example.yaml b/config.example.yaml index b645afe8efb..1e29f439586 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -559,6 +559,7 @@ upstream: # base-url: "https://example.com/api" # optional, e.g. https://zenmux.ai/api; falls back to Google Vertex when omitted # proxy-url: "socks5://proxy.example.com:1080" # optional per-key proxy override # # proxy-url: "direct" # optional: explicit direct connect for this credential +# # interactions: true # optional: opt into native Vertex Interactions API routing (/v1beta1/interactions). For service account JSON files under auths/, add "interactions": true at the root of the file. # headers: # X-Custom-Header: "custom-value" # # Values starting with "$" dynamically copy the header value from downstream client requests. diff --git a/internal/config/vertex_compat.go b/internal/config/vertex_compat.go index cd70e23c3d7..ae96a7703ab 100644 --- a/internal/config/vertex_compat.go +++ b/internal/config/vertex_compat.go @@ -53,6 +53,9 @@ type VertexCompatKey struct { // RequestRetry optionally overrides the global request-retry for this credential. // Nil or a negative value means "use the global request-retry". 0 disables additional retry rounds. RequestRetry *int `yaml:"request-retry,omitempty" json:"request-retry,omitempty"` + + // Interactions optionally enables native Vertex Interactions API routing for this key. + Interactions *bool `yaml:"interactions,omitempty" json:"interactions,omitempty"` } func (k VertexCompatKey) GetAPIKey() string { return k.APIKey } diff --git a/internal/runtime/executor/gemini_executor.go b/internal/runtime/executor/gemini_executor.go index 95b74cef1fc..00127ca30bd 100644 --- a/internal/runtime/executor/gemini_executor.go +++ b/internal/runtime/executor/gemini_executor.go @@ -34,10 +34,7 @@ const ( glAPIVersion = "v1beta" // streamScannerBuffer is the buffer size for SSE stream scanning. - streamScannerBuffer = 52_428_800 - - // geminiInteractionsAPIRevision is the default API revision for native Interactions requests. - geminiInteractionsAPIRevision = "2026-05-20" + streamScannerBuffer = helps.StreamScannerBuffer ) // GeminiExecutor is a stateless executor for the official Gemini API using API keys. @@ -874,42 +871,11 @@ func nativeInteractionsSourceFormat(format sdktranslator.Format) bool { // - `function_result` (FunctionResultStep) requires `call_id` and rejects `id` // - other steps and content parts do not support `id` func sanitizeGeminiInteractionsUnsupportedInputIDs(body []byte) []byte { - input := gjson.GetBytes(body, "input") - if !input.IsArray() { - return body - } - for i, item := range input.Array() { - stepType := item.Get("type").String() - if stepType == "function_call" { - if !item.Get("id").Exists() && item.Get("call_id").Exists() { - body, _ = sjson.SetBytes(body, fmt.Sprintf("input.%d.id", i), item.Get("call_id").String()) - } - if item.Get("call_id").Exists() { - body, _ = sjson.DeleteBytes(body, fmt.Sprintf("input.%d.call_id", i)) - } - } else { - if item.Get("id").Exists() { - body, _ = sjson.DeleteBytes(body, fmt.Sprintf("input.%d.id", i)) - } - } - content := item.Get("content") - if !content.IsArray() { - continue - } - for j, part := range content.Array() { - if part.Get("id").Exists() { - body, _ = sjson.DeleteBytes(body, fmt.Sprintf("input.%d.content.%d.id", i, j)) - } - } - } - return body + return helps.SanitizeGeminiInteractionsUnsupportedInputIDs(body) } func translateGeminiInteractionsRequestBody(ctx context.Context, cfg *config.Config, model string, payload []byte, opts cliproxyexecutor.Options, stream, isCompat bool) ([]byte, error) { - if opts.SourceFormat == "" || opts.SourceFormat == sdktranslator.FormatInteractions { - return bytes.Clone(payload), nil - } - return helps.TranslateRequestReturningError(ctx, opts.Headers, cfg, opts.SourceFormat, sdktranslator.FormatInteractions, model, payload, stream, isCompat) + return helps.TranslateGeminiInteractionsRequestBody(ctx, cfg, model, payload, opts, stream, isCompat) } // translateGeminiInteractionsRequestPair translates the working payload and the @@ -919,18 +885,11 @@ func translateGeminiInteractionsRequestBody(ctx context.Context, cfg *config.Con // inputs keep the existing order: working payload first, then the payload-config // source. func translateGeminiInteractionsRequestPair(ctx context.Context, cfg *config.Config, model string, payload []byte, opts cliproxyexecutor.Options, stream, isCompat bool) (original, working []byte, err error) { - source := geminiInteractionsPayloadConfigInput(opts, payload) - if geminiInteractionsSameByteSlice(payload, source) { - original, err = translateGeminiInteractionsRequestBody(ctx, cfg, model, payload, opts, stream, isCompat) - return original, bytes.Clone(original), err - } - working, err = translateGeminiInteractionsRequestBody(ctx, cfg, model, payload, opts, stream, isCompat) - original, _ = geminiInteractionsPayloadConfigSource(ctx, cfg, model, payload, opts, stream, isCompat) - return original, working, err + return helps.TranslateGeminiInteractionsRequestPair(ctx, cfg, model, payload, opts, stream, isCompat) } func geminiInteractionsPayloadConfigSource(ctx context.Context, cfg *config.Config, model string, payload []byte, opts cliproxyexecutor.Options, stream, isCompat bool) ([]byte, error) { - return translateGeminiInteractionsRequestBody(ctx, cfg, model, geminiInteractionsPayloadConfigInput(opts, payload), opts, stream, isCompat) + return helps.TranslateGeminiInteractionsRequestBody(ctx, cfg, model, geminiInteractionsPayloadConfigInput(opts, payload), opts, stream, isCompat) } func geminiInteractionsPayloadConfigInput(opts cliproxyexecutor.Options, payload []byte) []byte { @@ -961,82 +920,23 @@ func isNativeInteractionsAuth(auth *cliproxyauth.Auth) bool { } func applyGeminiInteractionsThinking(body []byte, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) ([]byte, error) { - fromFormat := opts.SourceFormat.String() - if strings.TrimSpace(fromFormat) == "" { - fromFormat = sdktranslator.FormatInteractions.String() - } - return helps.ApplyRequestThinking(body, req, opts, fromFormat, sdktranslator.FormatInteractions.String(), "gemini") + return helps.ApplyGeminiInteractionsThinking(body, req, opts) } func applyGeminiInteractionsRevisionHeader(req *http.Request) { - if req == nil { - return - } - if req.Header.Get("Api-Revision") == "" { - req.Header.Set("Api-Revision", geminiInteractionsAPIRevision) - } + helps.ApplyGeminiInteractionsRevisionHeader(req) } func applyGeminiInteractionsRequestHeaders(req *http.Request, headers http.Header) { - if req == nil || headers == nil || req.Header.Get("Api-Revision") != "" { - return - } - if revision := headers.Get("Api-Revision"); revision != "" { - req.Header.Set("Api-Revision", revision) - } + helps.ApplyGeminiInteractionsRequestHeaders(req, headers) } func geminiInteractionsSSEPayload(frame []byte) []byte { - trimmed := bytes.TrimSpace(frame) - if len(trimmed) == 0 { - return nil - } - if bytes.HasPrefix(trimmed, []byte("{")) { - return trimmed - } - lines := bytes.Split(frame, []byte{'\n'}) - var payload []byte - for _, line := range lines { - line = bytes.TrimRight(line, "\r") - if !bytes.HasPrefix(bytes.TrimSpace(line), []byte("data:")) { - continue - } - data := bytes.TrimSpace(line[bytes.Index(line, []byte("data:"))+len("data:"):]) - if len(data) == 0 || bytes.Equal(data, []byte("[DONE]")) { - continue - } - if len(payload) > 0 { - payload = append(payload, '\n') - } - payload = append(payload, data...) - } - if len(payload) == 0 { - return nil - } - return payload + return helps.GeminiInteractionsSSEPayload(frame) } func geminiInteractionsSSEDone(frame []byte) bool { - trimmed := bytes.TrimSpace(frame) - if bytes.Equal(trimmed, []byte("[DONE]")) { - return true - } - lines := bytes.Split(frame, []byte{'\n'}) - sawDoneEvent := false - for _, line := range lines { - line = bytes.TrimSpace(bytes.TrimRight(line, "\r")) - if bytes.EqualFold(line, []byte("event: done")) { - sawDoneEvent = true - continue - } - if bytes.HasPrefix(line, []byte("data:")) { - data := bytes.TrimSpace(line[len("data:"):]) - if bytes.Equal(data, []byte("[DONE]")) { - return true - } - } - } - return sawDoneEvent + return helps.GeminiInteractionsSSEDone(frame) } func geminiAuthLogFields(auth *cliproxyauth.Auth) (string, string, string, string) { diff --git a/internal/runtime/executor/gemini_vertex_executor.go b/internal/runtime/executor/gemini_vertex_executor.go index c8a932d4007..a11f4b79fd9 100644 --- a/internal/runtime/executor/gemini_vertex_executor.go +++ b/internal/runtime/executor/gemini_vertex_executor.go @@ -269,6 +269,9 @@ func (e *GeminiVertexExecutor) Execute(ctx context.Context, auth *cliproxyauth.A if opts.Alt == "responses/compact" { return resp, statusErr{code: http.StatusNotImplemented, msg: "/responses/compact not supported"} } + if shouldExecuteVertexInteractions(auth, opts) { + return e.executeInteractions(ctx, auth, req, opts) + } // Try API key authentication first apiKey, baseURL := vertexAPICreds(auth) @@ -291,6 +294,9 @@ func (e *GeminiVertexExecutor) ExecuteStream(ctx context.Context, auth *cliproxy if opts.Alt == "responses/compact" { return nil, statusErr{code: http.StatusNotImplemented, msg: "/responses/compact not supported"} } + if shouldExecuteVertexInteractions(auth, opts) { + return e.executeInteractionsStream(ctx, auth, req, opts) + } // Try API key authentication first apiKey, baseURL := vertexAPICreds(auth) @@ -1308,3 +1314,384 @@ func (e *GeminiVertexExecutor) resolveVertexConfig(auth *cliproxyauth.Auth) *con // SupportsApplyPatch reports the actual executor contract, independent of its provider name. func (e *GeminiVertexExecutor) SupportsApplyPatch() bool { return e != nil } + +func shouldExecuteVertexInteractions(auth *cliproxyauth.Auth, opts cliproxyexecutor.Options) bool { + return opts.SourceFormat == sdktranslator.FormatInteractions && isNativeVertexInteractionsAuth(auth) +} + +func isNativeVertexInteractionsAuth(auth *cliproxyauth.Auth) bool { + if auth == nil { + return false + } + if auth.Attributes != nil { + if v := strings.TrimSpace(auth.Attributes["interactions"]); strings.EqualFold(v, "true") || strings.EqualFold(v, "1") { + return true + } + } + if auth.Metadata != nil { + if v, ok := auth.Metadata["interactions"].(bool); ok && v { + return true + } + if v, ok := auth.Metadata["native_interactions"].(bool); ok && v { + return true + } + } + return false +} + +func vertexInteractionsURL(baseURL, projectID string, isStream bool) string { + base := strings.TrimSpace(baseURL) + if base == "" { + base = "https://aiplatform.googleapis.com" + } + base = strings.TrimRight(base, "/") + var url string + if strings.TrimSpace(projectID) != "" { + url = fmt.Sprintf("%s/v1beta1/projects/%s/locations/global/interactions", base, strings.TrimSpace(projectID)) + } else { + url = fmt.Sprintf("%s/v1beta1/interactions", base) + } + if isStream { + url = url + "?alt=sse" + } + return url +} + +func (e *GeminiVertexExecutor) executeInteractions(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (resp cliproxyexecutor.Response, err error) { + targetName := thinking.ParseSuffix(req.Model).ModelName + reporter := helps.NewExecutorUsageReporter(ctx, e, targetName, auth) + defer reporter.TrackFailure(ctx, &err) + + isCompat := helps.APIKeyModelIsCompat(req) + originalTranslated, body, errTranslate := helps.TranslateGeminiInteractionsRequestPair(ctx, e.cfg, targetName, req.Payload, opts, false, isCompat) + if errTranslate != nil { + return resp, errTranslate + } + if gjson.GetBytes(body, "model").Exists() && targetName != "" { + body = helps.SetStringIfDifferent(body, "model", targetName) + } + var errThinking error + body, errThinking = helps.ApplyGeminiInteractionsThinking(body, req, opts) + if errThinking != nil { + return resp, errThinking + } + requestedModel := helps.PayloadRequestedModel(opts, req.Model) + requestPath := helps.PayloadRequestPath(opts) + fromProtocol := opts.SourceFormat.String() + body = helps.SanitizeGeminiInteractionsUnsupportedInputIDs(body) + + apiKey, baseURL := vertexAPICreds(auth) + var projectID string + var saJSON []byte + if apiKey == "" { + var errCreds error + projectID, _, saJSON, errCreds = vertexCreds(auth) + if errCreds != nil { + return resp, errCreds + } + if auth != nil && auth.Attributes != nil && auth.Attributes["base_url"] != "" { + baseURL = strings.TrimSpace(auth.Attributes["base_url"]) + } + } else if auth != nil && auth.Metadata != nil { + if pid, ok := auth.Metadata["project_id"].(string); ok { + projectID = pid + } + } + + url := vertexInteractionsURL(baseURL, projectID, false) + + body = helps.ApplyPayloadConfigWithRequest(e.cfg, targetName, "interactions", fromProtocol, "", body, originalTranslated, requestedModel, requestPath, opts.Headers) + + httpReq, errRequest := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) + if errRequest != nil { + return resp, errRequest + } + httpReq.Header.Set("Content-Type", "application/json") + if apiKey != "" { + httpReq.Header.Set("x-goog-api-key", apiKey) + } else { + token, errTok := vertexAccessToken(ctx, e.cfg, auth, saJSON) + if errTok != nil { + log.Errorf("vertex executor: interactions access token error: %v", errTok) + return resp, statusErr{code: 500, msg: "internal server error"} + } + if strings.TrimSpace(token) == "" { + return resp, statusErr{code: http.StatusUnauthorized, msg: "missing access token"} + } + httpReq.Header.Set("Authorization", "Bearer "+token) + } + applyGeminiHeaders(httpReq, auth, opts.Headers) + helps.ApplyGeminiInteractionsRequestHeaders(httpReq, opts.Headers) + helps.ApplyGeminiInteractionsRevisionHeader(httpReq) + + var attrs map[string]string + if auth != nil { + attrs = auth.Attributes + } + util.ApplyCustomHeadersFromAttrs(httpReq, attrs, opts.Headers) + + var authID, authLabel, authType, authValue string + if auth != nil { + authID = auth.ID + authLabel = auth.Label + authType, authValue = auth.AccountInfo() + } + helps.RecordAPIRequest(ctx, e.cfg, helps.UpstreamRequestLog{ + URL: url, + Method: http.MethodPost, + Headers: httpReq.Header.Clone(), + Body: body, + Provider: e.Identifier(), + AuthID: authID, + AuthLabel: authLabel, + AuthType: authType, + AuthValue: authValue, + }) + + httpClient := reporter.TrackHTTPClient(helps.NewProxyAwareHTTPClient(ctx, e.cfg, auth, 0)) + httpResp, errDo := httpClient.Do(httpReq) + if errDo != nil { + helps.RecordAPIResponseError(ctx, e.cfg, errDo) + return resp, errDo + } + defer func() { + if errClose := httpResp.Body.Close(); errClose != nil { + log.Errorf("vertex executor: close interactions response body error: %v", errClose) + } + }() + helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) + data, errRead := io.ReadAll(httpResp.Body) + if errRead != nil { + helps.RecordAPIResponseError(ctx, e.cfg, errRead) + return resp, errRead + } + helps.AppendAPIResponseChunk(ctx, e.cfg, data) + if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { + helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), data)) + err = statusErr{code: httpResp.StatusCode, msg: string(data)} + return resp, err + } + reporter.ObserveResponseModel(data) + targetFormat := cliproxyexecutor.ResponseFormatOrSource(opts) + var param any + out := sdktranslator.TranslateNonStream(ctx, sdktranslator.FormatInteractions, targetFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), body, data, ¶m) + if helps.ApplyPatchTranslationError(param) != nil || len(out) == 0 { + return cliproxyexecutor.Response{}, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage} + } + reporter.Publish(ctx, helps.ParseInteractionsUsage(data)) + if targetFormat == sdktranslator.FormatOpenAIResponse { + out = helps.EnsureResponsesUsageDetails(out) + } + return cliproxyexecutor.Response{Payload: out, Headers: httpResp.Header.Clone()}, nil +} + +func (e *GeminiVertexExecutor) executeInteractionsStream(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (_ *cliproxyexecutor.StreamResult, err error) { + targetName := thinking.ParseSuffix(req.Model).ModelName + reporter := helps.NewExecutorUsageReporter(ctx, e, targetName, auth) + defer reporter.TrackFailure(ctx, &err) + + isCompat := helps.APIKeyModelIsCompat(req) + originalTranslated, body, errTranslate := helps.TranslateGeminiInteractionsRequestPair(ctx, e.cfg, targetName, req.Payload, opts, true, isCompat) + if errTranslate != nil { + return nil, errTranslate + } + if gjson.GetBytes(body, "model").Exists() && targetName != "" { + body = helps.SetStringIfDifferent(body, "model", targetName) + } + var errThinking error + body, errThinking = helps.ApplyGeminiInteractionsThinking(body, req, opts) + if errThinking != nil { + return nil, errThinking + } + requestedModel := helps.PayloadRequestedModel(opts, req.Model) + requestPath := helps.PayloadRequestPath(opts) + fromProtocol := opts.SourceFormat.String() + body = helps.SanitizeGeminiInteractionsUnsupportedInputIDs(body) + body = helps.SetBoolIfDifferent(body, "stream", true) + + apiKey, baseURL := vertexAPICreds(auth) + var projectID string + var saJSON []byte + if apiKey == "" { + var errCreds error + projectID, _, saJSON, errCreds = vertexCreds(auth) + if errCreds != nil { + return nil, errCreds + } + if auth != nil && auth.Attributes != nil && auth.Attributes["base_url"] != "" { + baseURL = strings.TrimSpace(auth.Attributes["base_url"]) + } + } else if auth != nil && auth.Metadata != nil { + if pid, ok := auth.Metadata["project_id"].(string); ok { + projectID = pid + } + } + + url := vertexInteractionsURL(baseURL, projectID, true) + + body = helps.ApplyPayloadConfigWithRequest(e.cfg, targetName, "interactions", fromProtocol, "", body, originalTranslated, requestedModel, requestPath, opts.Headers) + + httpReq, errRequest := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) + if errRequest != nil { + return nil, errRequest + } + httpReq.Header.Set("Content-Type", "application/json") + if apiKey != "" { + httpReq.Header.Set("x-goog-api-key", apiKey) + } else { + token, errTok := vertexAccessToken(ctx, e.cfg, auth, saJSON) + if errTok != nil { + log.Errorf("vertex executor: interactions access token error: %v", errTok) + return nil, statusErr{code: 500, msg: "internal server error"} + } + if strings.TrimSpace(token) == "" { + return nil, statusErr{code: http.StatusUnauthorized, msg: "missing access token"} + } + httpReq.Header.Set("Authorization", "Bearer "+token) + } + applyGeminiHeaders(httpReq, auth, opts.Headers) + helps.ApplyGeminiInteractionsRequestHeaders(httpReq, opts.Headers) + helps.ApplyGeminiInteractionsRevisionHeader(httpReq) + + var attrs map[string]string + if auth != nil { + attrs = auth.Attributes + } + util.ApplyCustomHeadersFromAttrs(httpReq, attrs, opts.Headers) + + var authID, authLabel, authType, authValue string + if auth != nil { + authID = auth.ID + authLabel = auth.Label + authType, authValue = auth.AccountInfo() + } + helps.RecordAPIRequest(ctx, e.cfg, helps.UpstreamRequestLog{ + URL: url, + Method: http.MethodPost, + Headers: httpReq.Header.Clone(), + Body: body, + Provider: e.Identifier(), + AuthID: authID, + AuthLabel: authLabel, + AuthType: authType, + AuthValue: authValue, + }) + + httpClient := reporter.TrackHTTPClient(helps.NewProxyAwareHTTPClient(ctx, e.cfg, auth, 0)) + httpResp, errDo := httpClient.Do(httpReq) + if errDo != nil { + helps.RecordAPIResponseError(ctx, e.cfg, errDo) + return nil, errDo + } + helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) + if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { + data, _ := io.ReadAll(httpResp.Body) + if errClose := httpResp.Body.Close(); errClose != nil { + log.Errorf("vertex executor: close interactions error response body error: %v", errClose) + } + helps.AppendAPIResponseChunk(ctx, e.cfg, data) + return nil, statusErr{code: httpResp.StatusCode, msg: string(data)} + } + + out := make(chan cliproxyexecutor.StreamChunk) + responseFormat := cliproxyexecutor.ResponseFormatOrSource(opts) + go func() { + defer close(out) + defer reporter.EnsurePublished(ctx) + defer func() { + if errClose := httpResp.Body.Close(); errClose != nil { + log.Errorf("vertex executor: close interactions stream body error: %v", errClose) + } + }() + scanner := bufio.NewScanner(httpResp.Body) + scanner.Buffer(nil, helps.StreamScannerBuffer) + originalRequest := opts.OriginalRequest + if len(originalRequest) == 0 { + originalRequest = req.Payload + } + claudeInputTokens := helps.NewClaudeInputTokenState(opts.SourceFormat, sdktranslator.FormatInteractions, responseFormat, originalRequest) + var streamUsage helps.StreamUsageBuffer + defer streamUsage.Publish(ctx, reporter) + var param any + helps.InitializeApplyPatchStream(ctx, sdktranslator.FormatInteractions, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), body, ¶m) + var frame []byte + emitFrame := func() bool { + rawFrame := bytes.Clone(frame) + trimmed := bytes.TrimSpace(rawFrame) + frame = frame[:0] + if len(trimmed) == 0 { + return true + } + payload := helps.GeminiInteractionsSSEPayload(rawFrame) + if len(payload) == 0 && helps.GeminiInteractionsSSEDone(rawFrame) { + payload = []byte("[DONE]") + } + if len(payload) > 0 { + reporter.ObserveResponseModel(payload) + if detail, ok := helps.ParseInteractionsStreamUsage(payload); ok { + streamUsage.Observe(detail, true) + } + } + if responseFormat == sdktranslator.FormatInteractions { + visibleFrame := append(bytes.TrimRight(rawFrame, "\r\n"), '\n', '\n') + select { + case out <- cliproxyexecutor.StreamChunk{Payload: visibleFrame}: + case <-ctx.Done(): + return false + } + return true + } + if len(payload) == 0 { + return true + } + var lines [][]byte + lines = helps.TranslateStreamWithClaudeInputTokens(ctx, sdktranslator.FormatInteractions, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), body, payload, ¶m, claudeInputTokens) + helps.RecordApplyPatchStreamFailure(ctx, param, reporter, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) + for i := range lines { + select { + case out <- cliproxyexecutor.StreamChunk{Payload: lines[i]}: + case <-ctx.Done(): + return false + } + } + if helps.StopApplyPatchStream(ctx, param, reporter, out, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) { + return false + } + return true + } + for scanner.Scan() { + line := scanner.Bytes() + helps.AppendAPIResponseChunk(ctx, e.cfg, line) + trimmed := bytes.TrimSpace(line) + if len(trimmed) == 0 { + if !emitFrame() { + return + } + continue + } + if len(frame) > 0 { + frame = append(frame, '\n') + } + frame = append(frame, line...) + } + if !emitFrame() { + return + } + if helps.EndApplyPatchStream(ctx, param, reporter, out, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) { + return + } + if errScan := scanner.Err(); errScan != nil { + helps.RecordAPIResponseError(ctx, e.cfg, errScan) + reporter.PublishFailure(ctx, errScan) + select { + case out <- cliproxyexecutor.StreamChunk{Err: errScan}: + case <-ctx.Done(): + } + } + }() + + return &cliproxyexecutor.StreamResult{ + Chunks: out, + Headers: httpResp.Header.Clone(), + }, nil +} diff --git a/internal/runtime/executor/gemini_vertex_executor_interactions_test.go b/internal/runtime/executor/gemini_vertex_executor_interactions_test.go new file mode 100644 index 00000000000..1c49c49d754 --- /dev/null +++ b/internal/runtime/executor/gemini_vertex_executor_interactions_test.go @@ -0,0 +1,543 @@ +package executor + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +func TestGeminiVertexInteractions_ServiceAccount_Execute(t *testing.T) { + var mu sync.Mutex + var gotPath string + var gotMethod string + var gotAuth string + var gotRevision string + var upstreamBody []byte + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/token" { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"access_token":"mock-vertex-sa-token","token_type":"Bearer","expires_in":3600}`)) + return + } + mu.Lock() + gotPath = r.URL.Path + gotMethod = r.Method + gotAuth = r.Header.Get("Authorization") + gotRevision = r.Header.Get("Api-Revision") + body, _ := io.ReadAll(r.Body) + upstreamBody = body + mu.Unlock() + + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{ + "id":"interaction_vertex_1", + "object":"interaction", + "status":"completed", + "steps":[{"type":"model_output","content":[{"text":"vertex interactions response"}]}], + "usage":{"input_tokens":10,"output_tokens":20,"total_tokens":30} + }`)) + })) + defer server.Close() + + targetURL, errParse := url.Parse(server.URL) + if errParse != nil { + t.Fatal(errParse) + } + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.Proxy = nil + t.Cleanup(transport.CloseIdleConnections) + + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", issue6258RedirectTransport{ + target: targetURL, + base: transport, + }) + + var sa map[string]any + if errUnmarshal := json.Unmarshal(testVertexServiceAccountJSON(t, server.URL+"/token"), &sa); errUnmarshal != nil { + t.Fatal(errUnmarshal) + } + + auth := &cliproxyauth.Auth{ + ID: "vertex-sa-interactions", + Provider: "vertex", + Metadata: map[string]any{ + "project_id": "proxy-test", + "location": "global", + "interactions": true, + "service_account": sa, + }, + } + + exec := NewGeminiVertexExecutor(&config.Config{}) + req := cliproxyexecutor.Request{ + Model: "gemini-3.8-flash", + Payload: []byte(`{"model":"gemini-3.8-flash","input":"hi vertex interactions"}`), + } + opts := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatInteractions, + ResponseFormat: sdktranslator.FormatInteractions, + } + + resp, errExecute := exec.Execute(ctx, auth, req, opts) + if errExecute != nil { + t.Fatalf("Execute() error = %v", errExecute) + } + + mu.Lock() + defer mu.Unlock() + + expectedPath := "/v1beta1/projects/proxy-test/locations/global/interactions" + if gotPath != expectedPath { + t.Fatalf("got path = %q, want %q", gotPath, expectedPath) + } + if gotMethod != http.MethodPost { + t.Fatalf("got method = %q, want %q", gotMethod, http.MethodPost) + } + if gotAuth != "Bearer mock-vertex-sa-token" { + t.Fatalf("got auth = %q, want Bearer mock-vertex-sa-token", gotAuth) + } + if gotRevision != "2026-05-20" { + t.Fatalf("got Api-Revision = %q, want 2026-05-20", gotRevision) + } + if !gjson.GetBytes(upstreamBody, "input").Exists() { + t.Fatalf("expected input in upstream body, got: %s", string(upstreamBody)) + } + if gotID := gjson.GetBytes(resp.Payload, "id").String(); gotID != "interaction_vertex_1" { + t.Fatalf("got response id = %q, want interaction_vertex_1", gotID) + } +} + +func TestGeminiVertexInteractions_ServiceAccount_ExecuteStream(t *testing.T) { + var mu sync.Mutex + var gotPath string + var gotQuery string + var gotRevision string + + // Generate a 1MB payload to verify StreamScannerBuffer handles large frames without bufio.ErrTooLong + largeOutput := strings.Repeat("A", 1024*1024) + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/token" { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"access_token":"mock-vertex-sa-token","token_type":"Bearer","expires_in":3600}`)) + return + } + mu.Lock() + gotPath = r.URL.Path + gotQuery = r.URL.RawQuery + gotRevision = r.Header.Get("Api-Revision") + mu.Unlock() + + w.Header().Set("Content-Type", "text/event-stream") + _, _ = w.Write([]byte("event: interaction.created\ndata: {\"id\":\"interaction_vertex_stream\",\"object\":\"interaction\",\"status\":\"in_progress\"}\n\n")) + largeCompleted := fmt.Sprintf("event: interaction.completed\ndata: {\"id\":\"interaction_vertex_stream\",\"object\":\"interaction\",\"status\":\"completed\",\"steps\":[{\"type\":\"model_output\",\"content\":[{\"text\":%q}]}],\"usage\":{\"input_tokens\":5,\"output_tokens\":1000,\"total_tokens\":1005}}\n\n", largeOutput) + _, _ = w.Write([]byte(largeCompleted)) + })) + defer server.Close() + + targetURL, errParse := url.Parse(server.URL) + if errParse != nil { + t.Fatal(errParse) + } + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.Proxy = nil + t.Cleanup(transport.CloseIdleConnections) + + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", issue6258RedirectTransport{ + target: targetURL, + base: transport, + }) + + var sa map[string]any + if errUnmarshal := json.Unmarshal(testVertexServiceAccountJSON(t, server.URL+"/token"), &sa); errUnmarshal != nil { + t.Fatal(errUnmarshal) + } + + auth := &cliproxyauth.Auth{ + ID: "vertex-sa-interactions-stream", + Provider: "vertex", + Metadata: map[string]any{ + "project_id": "proxy-test", + "location": "global", + "interactions": true, + "service_account": sa, + }, + } + + exec := NewGeminiVertexExecutor(&config.Config{}) + req := cliproxyexecutor.Request{ + Model: "gemini-3.8-flash", + Payload: []byte(`{"model":"gemini-3.8-flash","input":"hi vertex interactions stream"}`), + } + opts := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatInteractions, + ResponseFormat: sdktranslator.FormatInteractions, + } + + stream, errStream := exec.ExecuteStream(ctx, auth, req, opts) + if errStream != nil { + t.Fatalf("ExecuteStream() error = %v", errStream) + } + + var chunkCount int + for chunk := range stream.Chunks { + if chunk.Err != nil { + t.Fatalf("stream chunk error (scanner buffer overflow?): %v", chunk.Err) + } + chunkCount++ + } + + mu.Lock() + defer mu.Unlock() + + expectedPath := "/v1beta1/projects/proxy-test/locations/global/interactions" + if gotPath != expectedPath { + t.Fatalf("got path = %q, want %q", gotPath, expectedPath) + } + if !strings.Contains(gotQuery, "alt=sse") { + t.Fatalf("got query = %q, want query containing alt=sse", gotQuery) + } + if gotRevision != "2026-05-20" { + t.Fatalf("got Api-Revision = %q, want 2026-05-20", gotRevision) + } + if chunkCount == 0 { + t.Fatal("expected at least 1 stream chunk, got 0") + } +} + +func TestGeminiVertexInteractions_ServiceAccount_WithoutOptIn_UsesGenerateContent(t *testing.T) { + var mu sync.Mutex + var gotPath string + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/token" { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"access_token":"mock-vertex-sa-token","token_type":"Bearer","expires_in":3600}`)) + return + } + mu.Lock() + gotPath = r.URL.Path + mu.Unlock() + + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"responseId":"resp1","candidates":[{"content":{"parts":[{"text":"global generateContent ok"}]},"finishReason":"STOP"}]}`)) + })) + defer server.Close() + + targetURL, errParse := url.Parse(server.URL) + if errParse != nil { + t.Fatal(errParse) + } + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.Proxy = nil + t.Cleanup(transport.CloseIdleConnections) + + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", issue6258RedirectTransport{ + target: targetURL, + base: transport, + }) + + var sa map[string]any + if errUnmarshal := json.Unmarshal(testVertexServiceAccountJSON(t, server.URL+"/token"), &sa); errUnmarshal != nil { + t.Fatal(errUnmarshal) + } + + // Service account has location: "global" but NO explicit interactions opt-in + auth := &cliproxyauth.Auth{ + ID: "vertex-sa-global-no-optin", + Provider: "vertex", + Metadata: map[string]any{ + "project_id": "proxy-test", + "location": "global", + "service_account": sa, + }, + } + + exec := NewGeminiVertexExecutor(&config.Config{}) + req := cliproxyexecutor.Request{ + Model: "gemini-3.8-flash", + Payload: []byte(`{"model":"gemini-3.8-flash","input":"hi no optin"}`), + } + opts := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatInteractions, + ResponseFormat: sdktranslator.FormatInteractions, + } + + _, errExecute := exec.Execute(ctx, auth, req, opts) + if errExecute != nil { + t.Fatalf("Execute() error = %v", errExecute) + } + + mu.Lock() + defer mu.Unlock() + + expectedPath := "/v1/projects/proxy-test/locations/global/publishers/google/models/gemini-3.8-flash:generateContent" + if gotPath != expectedPath { + t.Fatalf("got path = %q, want global generateContent path %q", gotPath, expectedPath) + } +} + +func TestGeminiVertexInteractions_RegionalServiceAccount_UsesStandardBridge(t *testing.T) { + var mu sync.Mutex + var gotPath string + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/token" { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"access_token":"mock-vertex-sa-token","token_type":"Bearer","expires_in":3600}`)) + return + } + mu.Lock() + gotPath = r.URL.Path + mu.Unlock() + + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"responseId":"resp1","candidates":[{"content":{"parts":[{"text":"regional ok"}]},"finishReason":"STOP"}]}`)) + })) + defer server.Close() + + targetURL, errParse := url.Parse(server.URL) + if errParse != nil { + t.Fatal(errParse) + } + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.Proxy = nil + t.Cleanup(transport.CloseIdleConnections) + + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", issue6258RedirectTransport{ + target: targetURL, + base: transport, + }) + + var sa map[string]any + if errUnmarshal := json.Unmarshal(testVertexServiceAccountJSON(t, server.URL+"/token"), &sa); errUnmarshal != nil { + t.Fatal(errUnmarshal) + } + + // Regional service account without explicit interactions opt-in + auth := &cliproxyauth.Auth{ + ID: "vertex-sa-regional", + Provider: "vertex", + Metadata: map[string]any{ + "project_id": "proxy-test", + "location": "europe-west1", + "service_account": sa, + }, + } + + exec := NewGeminiVertexExecutor(&config.Config{}) + req := cliproxyexecutor.Request{ + Model: "gemini-3.8-flash", + Payload: []byte(`{"model":"gemini-3.8-flash","input":"hi regional"}`), + } + opts := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatInteractions, + ResponseFormat: sdktranslator.FormatInteractions, + } + + _, errExecute := exec.Execute(ctx, auth, req, opts) + if errExecute != nil { + t.Fatalf("Execute() error = %v", errExecute) + } + + mu.Lock() + defer mu.Unlock() + + expectedRegionalPath := "/v1/projects/proxy-test/locations/europe-west1/publishers/google/models/gemini-3.8-flash:generateContent" + if gotPath != expectedRegionalPath { + t.Fatalf("got path = %q, want regional generateContent path %q", gotPath, expectedRegionalPath) + } +} + +func TestGeminiVertexInteractions_APIKey_Execute(t *testing.T) { + var mu sync.Mutex + var gotPath string + var gotKey string + var gotRevision string + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + gotPath = r.URL.Path + gotKey = r.Header.Get("x-goog-api-key") + gotRevision = r.Header.Get("Api-Revision") + mu.Unlock() + + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{ + "id":"interaction_vertex_key", + "object":"interaction", + "status":"completed", + "steps":[{"type":"model_output","content":[{"text":"key ok"}]}], + "usage":{"input_tokens":1,"output_tokens":2,"total_tokens":3} + }`)) + })) + defer server.Close() + + auth := &cliproxyauth.Auth{ + ID: "vertex-apikey-interactions", + Provider: "vertex", + Attributes: map[string]string{ + "api_key": "test-vertex-key", + "base_url": server.URL, + "interactions": "true", + }, + } + + exec := NewGeminiVertexExecutor(&config.Config{}) + req := cliproxyexecutor.Request{ + Model: "gemini-3.8-flash", + Payload: []byte(`{"model":"gemini-3.8-flash","input":"hi vertex key"}`), + } + opts := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatInteractions, + ResponseFormat: sdktranslator.FormatInteractions, + } + + resp, errExecute := exec.Execute(context.Background(), auth, req, opts) + if errExecute != nil { + t.Fatalf("Execute() error = %v", errExecute) + } + + mu.Lock() + defer mu.Unlock() + + if !strings.HasSuffix(gotPath, "interactions") { + t.Fatalf("got path = %q, want path ending with interactions", gotPath) + } + if gotKey != "test-vertex-key" { + t.Fatalf("got key = %q, want test-vertex-key", gotKey) + } + if gotRevision != "2026-05-20" { + t.Fatalf("got Api-Revision = %q, want 2026-05-20", gotRevision) + } + if gotID := gjson.GetBytes(resp.Payload, "id").String(); gotID != "interaction_vertex_key" { + t.Fatalf("got response id = %q, want interaction_vertex_key", gotID) + } +} + +func TestGeminiVertexInteractions_APIKey_WithoutOptIn_UsesGenerateContent(t *testing.T) { + var mu sync.Mutex + var gotPath string + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + gotPath = r.URL.Path + mu.Unlock() + + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"responseId":"resp1","candidates":[{"content":{"parts":[{"text":"relay ok"}]},"finishReason":"STOP"}]}`)) + })) + defer server.Close() + + // Third-party relay API key without interactions: true + auth := &cliproxyauth.Auth{ + ID: "vertex-relay-key", + Provider: "vertex", + Attributes: map[string]string{ + "api_key": "test-relay-key", + "base_url": server.URL, + }, + } + + exec := NewGeminiVertexExecutor(&config.Config{}) + req := cliproxyexecutor.Request{ + Model: "gemini-3.8-flash", + Payload: []byte(`{"model":"gemini-3.8-flash","input":"hi relay"}`), + } + opts := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatInteractions, + ResponseFormat: sdktranslator.FormatInteractions, + } + + _, errExecute := exec.Execute(context.Background(), auth, req, opts) + if errExecute != nil { + t.Fatalf("Execute() error = %v", errExecute) + } + + mu.Lock() + defer mu.Unlock() + + expectedRelayPath := "/v1/publishers/google/models/gemini-3.8-flash:generateContent" + if gotPath != expectedRelayPath { + t.Fatalf("got path = %q, want relay generateContent path %q", gotPath, expectedRelayPath) + } +} + +func TestGeminiVertexInteractions_PayloadRulesOrdering(t *testing.T) { + var mu sync.Mutex + var upstreamBody []byte + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + body, errRead := io.ReadAll(r.Body) + if errRead != nil { + t.Fatalf("read request body: %v", errRead) + } + upstreamBody = body + mu.Unlock() + + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"id":"interaction_1","object":"interaction","status":"completed","steps":[{"type":"model_output","content":[{"text":"ok"}]}]}`)) + })) + defer server.Close() + + exec := NewGeminiVertexExecutor(&config.Config{ + Payload: config.PayloadConfig{ + Override: []config.PayloadRule{ + { + Models: []config.PayloadModelRule{ + {Name: "gemini-3.8-flash", Protocol: "interactions", FromProtocol: "interactions"}, + }, + Params: map[string]any{ + "custom_rule_param": "enforced_after_all_transforms", + }, + }, + }, + }, + }) + auth := &cliproxyauth.Auth{ + ID: "vertex-apikey-interactions-rules", + Provider: "vertex", + Attributes: map[string]string{ + "api_key": "test-key", + "base_url": server.URL, + "interactions": "true", + }, + } + req := cliproxyexecutor.Request{ + Model: "gemini-3.8-flash", + Payload: []byte(`{ + "model":"gemini-3.8-flash", + "input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}] + }`), + } + + _, errExecute := exec.Execute(context.Background(), auth, req, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatInteractions, + ResponseFormat: sdktranslator.FormatInteractions, + }) + if errExecute != nil { + t.Fatalf("Execute() error = %v", errExecute) + } + + mu.Lock() + defer mu.Unlock() + + if got := gjson.GetBytes(upstreamBody, "custom_rule_param").String(); got != "enforced_after_all_transforms" { + t.Fatalf("custom_rule_param = %q, want enforced_after_all_transforms. Body: %s", got, string(upstreamBody)) + } +} diff --git a/internal/runtime/executor/helps/gemini_interactions.go b/internal/runtime/executor/helps/gemini_interactions.go new file mode 100644 index 00000000000..86e7d48fbe4 --- /dev/null +++ b/internal/runtime/executor/helps/gemini_interactions.go @@ -0,0 +1,187 @@ +package helps + +import ( + "bytes" + "context" + "fmt" + "net/http" + "strings" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +const ( + // GeminiInteractionsAPIRevision is the Api-Revision header required for the Interactions API. + GeminiInteractionsAPIRevision = "2026-05-20" + // StreamScannerBuffer sets the scanner buffer capacity for streaming response chunks (50MB). + StreamScannerBuffer = 52_428_800 +) + +// SanitizeGeminiInteractionsUnsupportedInputIDs aligns input step IDs with the +// official Gemini Interactions API schema: +// - `function_call` (FunctionCallStep) requires `id` and rejects `call_id` +// - `function_result` (FunctionResultStep) requires `call_id` and rejects `id` +// - other steps and content parts do not support `id` +func SanitizeGeminiInteractionsUnsupportedInputIDs(body []byte) []byte { + input := gjson.GetBytes(body, "input") + if !input.IsArray() { + return body + } + for i, item := range input.Array() { + stepType := item.Get("type").String() + if stepType == "function_call" { + if !item.Get("id").Exists() && item.Get("call_id").Exists() { + body, _ = sjson.SetBytes(body, fmt.Sprintf("input.%d.id", i), item.Get("call_id").String()) + } + if item.Get("call_id").Exists() { + body, _ = sjson.DeleteBytes(body, fmt.Sprintf("input.%d.call_id", i)) + } + } else { + if item.Get("id").Exists() { + body, _ = sjson.DeleteBytes(body, fmt.Sprintf("input.%d.id", i)) + } + } + content := item.Get("content") + if !content.IsArray() { + continue + } + for j, part := range content.Array() { + if part.Get("id").Exists() { + body, _ = sjson.DeleteBytes(body, fmt.Sprintf("input.%d.content.%d.id", i, j)) + } + } + } + return body +} + +// TranslateGeminiInteractionsRequestBody translates a request payload to FormatInteractions. +func TranslateGeminiInteractionsRequestBody(ctx context.Context, cfg *config.Config, model string, payload []byte, opts cliproxyexecutor.Options, stream, isCompat bool) ([]byte, error) { + if opts.SourceFormat == "" || opts.SourceFormat == sdktranslator.FormatInteractions { + return bytes.Clone(payload), nil + } + return TranslateRequestReturningError(ctx, opts.Headers, cfg, opts.SourceFormat, sdktranslator.FormatInteractions, model, payload, stream, isCompat) +} + +// TranslateGeminiInteractionsRequestPair translates the working payload and the +// payload-config baseline. Identical inputs are translated once, including plugin +// hooks. The baseline is captured before model and thinking mutations, and the +// working buffer is a separate copy so those mutations cannot change it. +func TranslateGeminiInteractionsRequestPair(ctx context.Context, cfg *config.Config, model string, payload []byte, opts cliproxyexecutor.Options, stream, isCompat bool) (original, working []byte, err error) { + source := geminiInteractionsPayloadConfigInput(opts, payload) + if geminiInteractionsSameByteSlice(payload, source) { + original, err = TranslateGeminiInteractionsRequestBody(ctx, cfg, model, payload, opts, stream, isCompat) + return original, bytes.Clone(original), err + } + working, err = TranslateGeminiInteractionsRequestBody(ctx, cfg, model, payload, opts, stream, isCompat) + original, _ = geminiInteractionsPayloadConfigSource(ctx, cfg, model, payload, opts, stream, isCompat) + return original, working, err +} + +func geminiInteractionsPayloadConfigSource(ctx context.Context, cfg *config.Config, model string, payload []byte, opts cliproxyexecutor.Options, stream, isCompat bool) ([]byte, error) { + return TranslateGeminiInteractionsRequestBody(ctx, cfg, model, geminiInteractionsPayloadConfigInput(opts, payload), opts, stream, isCompat) +} + +func geminiInteractionsPayloadConfigInput(opts cliproxyexecutor.Options, payload []byte) []byte { + if len(opts.OriginalRequest) == 0 { + return payload + } + return opts.OriginalRequest +} + +func geminiInteractionsSameByteSlice(a, b []byte) bool { + if len(a) != len(b) { + return false + } + if len(a) == 0 { + return true + } + return &a[0] == &b[0] +} + +// ApplyGeminiInteractionsThinking applies thinking/reasoning configuration to the interactions payload. +func ApplyGeminiInteractionsThinking(body []byte, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) ([]byte, error) { + fromFormat := opts.SourceFormat.String() + if strings.TrimSpace(fromFormat) == "" { + fromFormat = sdktranslator.FormatInteractions.String() + } + return ApplyRequestThinking(body, req, opts, fromFormat, sdktranslator.FormatInteractions.String(), "gemini") +} + +// ApplyGeminiInteractionsRevisionHeader sets the default Api-Revision header on outgoing HTTP requests. +func ApplyGeminiInteractionsRevisionHeader(req *http.Request) { + if req == nil { + return + } + if req.Header.Get("Api-Revision") == "" { + req.Header.Set("Api-Revision", GeminiInteractionsAPIRevision) + } +} + +// ApplyGeminiInteractionsRequestHeaders forwards any incoming Api-Revision header to upstream requests. +func ApplyGeminiInteractionsRequestHeaders(req *http.Request, headers http.Header) { + if req == nil || headers == nil || req.Header.Get("Api-Revision") != "" { + return + } + if revision := headers.Get("Api-Revision"); revision != "" { + req.Header.Set("Api-Revision", revision) + } +} + +// GeminiInteractionsSSEPayload extracts SSE data payload from raw SSE frames. +func GeminiInteractionsSSEPayload(frame []byte) []byte { + trimmed := bytes.TrimSpace(frame) + if len(trimmed) == 0 { + return nil + } + if bytes.HasPrefix(trimmed, []byte("{")) { + return trimmed + } + lines := bytes.Split(frame, []byte{'\n'}) + var payload []byte + for _, line := range lines { + line = bytes.TrimRight(line, "\r") + if !bytes.HasPrefix(bytes.TrimSpace(line), []byte("data:")) { + continue + } + data := bytes.TrimSpace(line[bytes.Index(line, []byte("data:"))+len("data:"):]) + if len(data) == 0 || bytes.Equal(data, []byte("[DONE]")) { + continue + } + if len(payload) > 0 { + payload = append(payload, '\n') + } + payload = append(payload, data...) + } + if len(payload) == 0 { + return nil + } + return payload +} + +// GeminiInteractionsSSEDone reports whether the SSE frame signals stream completion. +func GeminiInteractionsSSEDone(frame []byte) bool { + trimmed := bytes.TrimSpace(frame) + if bytes.Equal(trimmed, []byte("[DONE]")) { + return true + } + lines := bytes.Split(frame, []byte{'\n'}) + sawDoneEvent := false + for _, line := range lines { + line = bytes.TrimSpace(bytes.TrimRight(line, "\r")) + if bytes.EqualFold(line, []byte("event: done")) { + sawDoneEvent = true + continue + } + if bytes.HasPrefix(line, []byte("data:")) { + data := bytes.TrimSpace(line[len("data:"):]) + if bytes.Equal(data, []byte("[DONE]")) { + return true + } + } + } + return sawDoneEvent +} diff --git a/internal/watcher/synthesizer/config.go b/internal/watcher/synthesizer/config.go index 4d07e163a6d..ae9e015700b 100644 --- a/internal/watcher/synthesizer/config.go +++ b/internal/watcher/synthesizer/config.go @@ -434,6 +434,9 @@ func (s *ConfigSynthesizer) synthesizeVertexCompat(ctx *SynthesisContext) []*cor if hash := diff.ComputeVertexCompatModelsHash(compat.Models); hash != "" { attrs["models_hash"] = hash } + if compat.Interactions != nil && *compat.Interactions { + attrs["interactions"] = "true" + } addConfigHeadersToAttrs(compat.Headers, attrs) metadata := map[string]any{} if compat.DisableCooling != nil { diff --git a/sdk/api/handlers/gemini/interactions_handlers_test.go b/sdk/api/handlers/gemini/interactions_handlers_test.go index 6d0a9fe9526..45bc381428a 100644 --- a/sdk/api/handlers/gemini/interactions_handlers_test.go +++ b/sdk/api/handlers/gemini/interactions_handlers_test.go @@ -300,6 +300,65 @@ func TestInteractionsAntigravityModelUsesTranslatorBridge(t *testing.T) { } } +func TestInteractionsVertexModelUsesNativeInteractionsEndpoint(t *testing.T) { + gin.SetMode(gin.TestMode) + model := "gemini-3.8-flash" + var gotPath string + var upstreamBody []byte + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotPath = r.URL.Path + body, errRead := io.ReadAll(r.Body) + if errRead != nil { + http.Error(w, errRead.Error(), http.StatusBadRequest) + return + } + upstreamBody = body + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"id":"interaction_v1","object":"interaction","status":"completed","steps":[{"type":"model_output","content":[{"text":"vertex-ok"}]}],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}`)) + })) + defer server.Close() + + manager := coreauth.NewManager(nil, nil, nil) + manager.RegisterExecutor(executor.NewGeminiVertexExecutor(&config.Config{RequestRetry: 1})) + auth := &coreauth.Auth{ + ID: "interactions-vertex-auth", + Provider: "vertex", + Status: coreauth.StatusActive, + Attributes: map[string]string{ + "api_key": "test-vertex-key", + "base_url": server.URL, + "interactions": "true", + }, + } + if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil { + t.Fatalf("manager.Register(): %v", errRegister) + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, auth.Provider, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(auth.ID) + }) + + rec := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(rec) + ctx.Request = httptest.NewRequest(http.MethodPost, "/v1beta/interactions", strings.NewReader(`{"model":"`+model+`","input":"hi vertex"}`)) + h := NewGeminiAPIHandler(handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, manager)) + + h.Interactions(ctx) + + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String()) + } + if !strings.HasSuffix(gotPath, "interactions") { + t.Fatalf("upstream path = %q, want path ending with interactions", gotPath) + } + if got := gjson.GetBytes(upstreamBody, "input").String(); got != "hi vertex" { + t.Fatalf("upstream input = %q, want hi vertex. Body: %s", got, string(upstreamBody)) + } + if got := gjson.GetBytes(rec.Body.Bytes(), "steps.0.content.0.text").String(); got != "vertex-ok" { + t.Fatalf("response text = %q, want vertex-ok. Body: %s", got, rec.Body.String()) + } +} + func TestForwardInteractionsStreamWrapsBareJSONAsSSEData(t *testing.T) { gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() From 249e9ef97611cbd99eee422821cfa3a939dca88e Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Thu, 8 Oct 2026 13:03:21 +0800 Subject: [PATCH 096/142] fix(meta): preserve foreign reasoning encrypted content in responses requests - Introduce `sanitizeOpenAIResponsesReasoningEncryptedContentKeepForeign` to retain unknown-format reasoning signatures - Update Meta executor to preserve foreign reasoning encrypted payloads for third-party models like Muse Closes: #6450 --- .../runtime/executor/meta_executor_execute.go | 2 +- .../runtime/executor/meta_executor_test.go | 87 +++++++++++++++++++ .../executor/openai_responses_signature.go | 17 +++- .../openai_responses_signature_test.go | 45 ++++++++++ 4 files changed, 146 insertions(+), 5 deletions(-) diff --git a/internal/runtime/executor/meta_executor_execute.go b/internal/runtime/executor/meta_executor_execute.go index c78db800a88..b322a509dae 100644 --- a/internal/runtime/executor/meta_executor_execute.go +++ b/internal/runtime/executor/meta_executor_execute.go @@ -71,7 +71,7 @@ func (e *MetaExecutor) prepareResponsesRequest(ctx context.Context, req cliproxy return nil, errNormalizePatch } body = normalizeCodexInstructions(body) - body = sanitizeOpenAIResponsesReasoningEncryptedContent(ctx, "meta executor", body) + body = sanitizeOpenAIResponsesReasoningEncryptedContentKeepForeign(ctx, "meta executor", body) body = helps.SanitizeMetaWebSearchTools(body) body = helps.NormalizeCodexToolIntegerTypes(body, opts.Headers) diff --git a/internal/runtime/executor/meta_executor_test.go b/internal/runtime/executor/meta_executor_test.go index e58126216b5..7fa19128d9d 100644 --- a/internal/runtime/executor/meta_executor_test.go +++ b/internal/runtime/executor/meta_executor_test.go @@ -1586,3 +1586,90 @@ func TestMetaExecutor_NormalizesToolFieldsForCodexUserAgent(t *testing.T) { func TestMetaApplyPatchResponsesExecutor(t *testing.T) { testApplyPatchResponsesExecutor(t, "meta", NewMetaExecutor(&config.Config{}), "muse-spark-1.3") } + +func TestMetaExecutor_Execute_PreservesMuseReasoningEncryptedContent_Issue6450(t *testing.T) { + var gotBody []byte + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var errRead error + gotBody, errRead = io.ReadAll(r.Body) + if errRead != nil { + t.Fatalf("read body: %v", errRead) + } + writeMetaResponsesOK(w, "ok") + })) + defer server.Close() + + exec := NewMetaExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{ + Provider: "meta", + Attributes: map[string]string{ + "api_key": "meta-token", + "base_url": server.URL, + }, + } + + const museEncryptedContent = "Q-PaDg-mock-muse-spark-encrypted-reasoning-payload" + reqPayload := []byte(`{"model":"muse-spark-1.3","store":false,"input":[` + + `{"id":"rs_1","type":"reasoning","encrypted_content":"` + museEncryptedContent + `","content":[{"type":"reasoning_text","text":"thinking step"}],"summary":[]},` + + `{"id":"rs_claude","type":"reasoning","encrypted_content":"` + testClaudeCAISSample + `","summary":[]},` + + `{"id":"msg_1","type":"message","role":"user","content":[{"type":"input_text","text":"hello"}]}` + + `]}`) + + _, err := exec.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "muse-spark-1.3", + Payload: reqPayload, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FromString("codex"), + }) + if err != nil { + t.Fatalf("Execute() error = %v", err) + } + + if gotEC := gjson.GetBytes(gotBody, "input.0.encrypted_content").String(); gotEC != museEncryptedContent { + t.Fatalf("encrypted_content = %q, want %q; body=%s", gotEC, museEncryptedContent, gotBody) + } + if gotID := gjson.GetBytes(gotBody, "input.0.id").String(); gotID != "rs_1" { + t.Fatalf("reasoning id = %q, want rs_1; body=%s", gotID, gotBody) + } + assertEmptyReasoningContent(t, gotBody, "input.0.content") + if gotSummary := gjson.GetBytes(gotBody, "input.0.summary.0.text").String(); gotSummary != "thinking step" { + t.Fatalf("summary = %q, want 'thinking step'; body=%s", gotSummary, gotBody) + } + // Verify Claude signature stripped and id dropped when store=false + if gjson.GetBytes(gotBody, "input.1.encrypted_content").Exists() { + t.Fatalf("Claude signature should be stripped: %s", gotBody) + } + if gjson.GetBytes(gotBody, "input.1.id").Exists() { + t.Fatalf("Claude reasoning id should be dropped: %s", gotBody) + } + + gotBody = nil + streamResult, errStream := exec.ExecuteStream(context.Background(), auth, cliproxyexecutor.Request{ + Model: "muse-spark-1.3", + Payload: reqPayload, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FromString("codex"), + }) + if errStream != nil { + t.Fatalf("ExecuteStream() error = %v", errStream) + } + for range streamResult.Chunks { + } + if gotEC := gjson.GetBytes(gotBody, "input.0.encrypted_content").String(); gotEC != museEncryptedContent { + t.Fatalf("stream encrypted_content = %q, want %q; body=%s", gotEC, museEncryptedContent, gotBody) + } + if gotID := gjson.GetBytes(gotBody, "input.0.id").String(); gotID != "rs_1" { + t.Fatalf("stream reasoning id = %q, want rs_1; body=%s", gotID, gotBody) + } + assertEmptyReasoningContent(t, gotBody, "input.0.content") + if gotSummary := gjson.GetBytes(gotBody, "input.0.summary.0.text").String(); gotSummary != "thinking step" { + t.Fatalf("stream summary = %q, want 'thinking step'; body=%s", gotSummary, gotBody) + } + if gjson.GetBytes(gotBody, "input.1.encrypted_content").Exists() { + t.Fatalf("stream Claude signature should be stripped: %s", gotBody) + } + if gjson.GetBytes(gotBody, "input.1.id").Exists() { + t.Fatalf("stream Claude reasoning id should be dropped: %s", gotBody) + } +} diff --git a/internal/runtime/executor/openai_responses_signature.go b/internal/runtime/executor/openai_responses_signature.go index 80b8dec295e..e6e03d99d39 100644 --- a/internal/runtime/executor/openai_responses_signature.go +++ b/internal/runtime/executor/openai_responses_signature.go @@ -49,10 +49,18 @@ func promoteOpenAIResponsesReasoningTextToSummary(itemRaw string, content gjson. } func sanitizeOpenAIResponsesReasoningEncryptedContent(ctx context.Context, provider string, body []byte) []byte { - return sanitizeOpenAIResponsesReasoningEncryptedContentWithCompat(ctx, provider, body, false) + return sanitizeOpenAIResponsesReasoningEncryptedContentWithOptions(ctx, provider, body, false, false) } func sanitizeOpenAIResponsesReasoningEncryptedContentWithCompat(ctx context.Context, provider string, body []byte, isCompat bool) []byte { + return sanitizeOpenAIResponsesReasoningEncryptedContentWithOptions(ctx, provider, body, isCompat, isCompat) +} + +func sanitizeOpenAIResponsesReasoningEncryptedContentKeepForeign(ctx context.Context, provider string, body []byte) []byte { + return sanitizeOpenAIResponsesReasoningEncryptedContentWithOptions(ctx, provider, body, false, true) +} + +func sanitizeOpenAIResponsesReasoningEncryptedContentWithOptions(ctx context.Context, provider string, body []byte, isCompat bool, keepForeign bool) []byte { inputResult := util.GetGJSONBytesNoCopy(body, "input") if !inputResult.Exists() || !inputResult.IsArray() { return body @@ -168,9 +176,10 @@ func sanitizeOpenAIResponsesReasoningEncryptedContentWithCompat(ctx context.Cont if rawSignature != strings.TrimSpace(rawSignature) { reason = "encrypted_content has leading or trailing whitespace" } else if _, err := signature.InspectGPTReasoningSignature(rawSignature); err != nil { - // When isCompat is true, third-party Responses models (such as Muse) - // expect their own unknown-format encrypted_content to be replayed. - if !isCompat || rawSignature == "" || signature.DetectSignatureProvider(rawSignature) != signature.SignatureProviderUnknown { + // When keepForeign is true (compat callers enable it via WithCompat), + // third-party Responses models (such as Muse) expect their own + // unknown-format encrypted_content to be replayed. + if !keepForeign || rawSignature == "" || signature.DetectSignatureProvider(rawSignature) != signature.SignatureProviderUnknown { reason = err.Error() } } diff --git a/internal/runtime/executor/openai_responses_signature_test.go b/internal/runtime/executor/openai_responses_signature_test.go index ae9914634cc..d27a3056d3b 100644 --- a/internal/runtime/executor/openai_responses_signature_test.go +++ b/internal/runtime/executor/openai_responses_signature_test.go @@ -215,6 +215,51 @@ func TestSanitizeOpenAIResponsesReasoningEncryptedContentWithCompat_PreservesUnk } } +func TestSanitizeOpenAIResponsesReasoningEncryptedContentKeepForeign_Issue6450(t *testing.T) { + const museSig = "Q-PaDg-mock-muse-spark-encrypted-reasoning-payload" + body := []byte(`{"store":false,"input":[` + + `{"id":"rs_muse","type":"reasoning","summary":[],"content":[{"type":"reasoning_text","text":"cleartext thinking"}],"encrypted_content":"` + museSig + `"},` + + `{"id":"rs_claude","type":"reasoning","summary":[],"content":null,"encrypted_content":"` + testClaudeCAISSample + `"},` + + `{"id":"rs_empty","type":"reasoning","summary":[],"content":null,"encrypted_content":""},` + + `{"id":"rs_orphan","type":"reasoning","summary":[]}` + + `]}`) + + got := sanitizeOpenAIResponsesReasoningEncryptedContentKeepForeign(context.Background(), "test", body) + + // rs_muse: unknown format signature preserved, cleartext content moved to summary, id kept + assertEmptyReasoningContent(t, got, "input.0.content") + if gotSig := gjson.GetBytes(got, "input.0.encrypted_content").String(); gotSig != museSig { + t.Fatalf("keepForeign encrypted_content = %q, want %q; body=%s", gotSig, museSig, got) + } + if gotID := gjson.GetBytes(got, "input.0.id").String(); gotID != "rs_muse" { + t.Fatalf("keepForeign reasoning id = %q, want rs_muse; body=%s", gotID, got) + } + if gotSummary := gjson.GetBytes(got, "input.0.summary.0.text").String(); gotSummary != "cleartext thinking" { + t.Fatalf("keepForeign summary = %q, want 'cleartext thinking'; body=%s", gotSummary, got) + } + + // rs_claude: known foreign signature stripped, id dropped when store=false + if gjson.GetBytes(got, "input.1.encrypted_content").Exists() { + t.Fatalf("Claude signature should be stripped: %s", got) + } + if gjson.GetBytes(got, "input.1.id").Exists() { + t.Fatalf("Claude reasoning id should be dropped: %s", got) + } + + // rs_empty: empty signature stripped, id dropped + if gjson.GetBytes(got, "input.2.encrypted_content").Exists() { + t.Fatalf("empty signature should be stripped: %s", got) + } + if gjson.GetBytes(got, "input.2.id").Exists() { + t.Fatalf("empty reasoning id should be dropped: %s", got) + } + + // rs_orphan: missing signature, id dropped when store=false + if gjson.GetBytes(got, "input.3.id").Exists() { + t.Fatalf("orphan reasoning id should be dropped: %s", got) + } +} + func BenchmarkSanitizeOpenAIResponsesReasoningEncryptedContentLargeNoopPayload(b *testing.B) { body := []byte(`{"store":false,"input":[{"type":"message","role":"user","content":"` + strings.Repeat("x", 8<<20) + `"}]}`) b.ReportAllocs() From 0a23627d229f02ab6f7fa0ff596342b3cdb19cdd Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Thu, 8 Oct 2026 13:20:41 +0800 Subject: [PATCH 097/142] fix(config): normalize collection styles and unquote mapping keys in v8 api - Export `NormalizeCollectionNodeStyles` to traverse document nodes and clear double quotes from string mapping keys - Apply collection style normalization before YAML marshaling in the v8 management config handler Closes: #6451 --- internal/api/handlers/management/config_v8.go | 1 + .../api/handlers/management/config_v8_test.go | 134 ++++++++++++++++++ internal/config/config_yaml.go | 26 +++- 3 files changed, 154 insertions(+), 7 deletions(-) diff --git a/internal/api/handlers/management/config_v8.go b/internal/api/handlers/management/config_v8.go index 7bf13575966..60c571fdbd9 100644 --- a/internal/api/handlers/management/config_v8.go +++ b/internal/api/handlers/management/config_v8.go @@ -158,6 +158,7 @@ func (h *Handler) ConfigV8(c *gin.Context) { } } stripAPIKeysAuthIndexesFromRoot(root) + config.NormalizeCollectionNodeStyles(root) data, err = yaml.Marshal(&doc) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid_config", "message": err.Error()}) diff --git a/internal/api/handlers/management/config_v8_test.go b/internal/api/handlers/management/config_v8_test.go index 554f5faa8df..fb675f09cd0 100644 --- a/internal/api/handlers/management/config_v8_test.go +++ b/internal/api/handlers/management/config_v8_test.go @@ -756,3 +756,137 @@ plugins: request(http.MethodDelete, path, http.StatusNotFound, "") } } + +func TestConfigV8SaveNormalizesCollectionStylesToBlockYAML(t *testing.T) { + gin.SetMode(gin.TestMode) + file := filepath.Join(t.TempDir(), "config.yaml") + raw := `config-version: 8 +server: + port: 8317 +api-keys: + openai-compatibility: + - name: compat-provider + base-url: "https://api.example.com" + headers: + User-Agent: "$User-Agent" + models: + - alias: "coding" + name: "gpt-4o" + keys: + - api-key: "sk-compat-1" +` + if errWrite := os.WriteFile(file, []byte(raw), 0600); errWrite != nil { + t.Fatal(errWrite) + } + cfg, errLoad := config.LoadConfig(file) + if errLoad != nil { + t.Fatal(errLoad) + } + h := &Handler{cfg: cfg, configFilePath: file} + router := gin.New() + router.PUT("/v8/management/config", h.ConfigV8) + router.PUT("/v8/management/config/*path", h.ConfigV8) + router.PATCH("/v8/management/config", h.ConfigV8) + + // Send JSON update simulating v8 management panel saving complex items + jsonUpdate := `[{"name":"compat-provider","base-url":"https://api.example.com","headers":{"User-Agent":"$User-Agent"},"models":[{"alias":"coding","name":"gpt-4o"}],"keys":[{"api-key":"sk-compat-1"}]}]` + w := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPut, "/v8/management/config/api-keys/openai-compatibility", strings.NewReader(jsonUpdate)) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Fatalf("PUT failed: status=%d body=%s", w.Code, w.Body.String()) + } + + saved, errRead := os.ReadFile(file) + if errRead != nil { + t.Fatal(errRead) + } + savedStr := string(saved) + + // Ensure the saved config does NOT contain inline JSON / flow style for complex collections + if strings.Contains(savedStr, "[{") || strings.Contains(savedStr, `headers: {`) || strings.Contains(savedStr, `models: [{`) { + t.Fatalf("config contains flow style / inline JSON collections:\n%s", savedStr) + } + if !strings.Contains(savedStr, "openai-compatibility:") || !strings.Contains(savedStr, "- name:") || !strings.Contains(savedStr, "base-url:") { + t.Fatalf("expected block style sequence with unquoted keys for openai-compatibility, got:\n%s", savedStr) + } + if strings.Contains(savedStr, `"name":`) || strings.Contains(savedStr, `"base-url":`) { + t.Fatalf("expected keys to be unquoted in block YAML, got:\n%s", savedStr) + } + + // Also test PATCH at root /v8/management/config with JSON + patchJSON := `{"api-keys":{"openai-compatibility":[{"name":"compat-provider-2","base-url":"https://api.example2.com","headers":{"User-Agent":"$User-Agent-2"},"models":[{"alias":"coding-2","name":"gpt-4o-mini"}],"keys":[{"api-key":"sk-compat-2"}]}]}}` + w = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodPatch, "/v8/management/config", strings.NewReader(patchJSON)) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Fatalf("PATCH failed: status=%d body=%s", w.Code, w.Body.String()) + } + saved, errRead = os.ReadFile(file) + if errRead != nil { + t.Fatal(errRead) + } + savedStr = string(saved) + if strings.Contains(savedStr, "[{") || strings.Contains(savedStr, `headers: {`) || strings.Contains(savedStr, `models: [{`) { + t.Fatalf("PATCH saved config contains flow style / inline JSON collections:\n%s", savedStr) + } + if !strings.Contains(savedStr, "openai-compatibility:") || !strings.Contains(savedStr, "- name:") { + t.Fatalf("expected block style sequence after PATCH for openai-compatibility, got:\n%s", savedStr) + } + + // Verify that empty sequence retains flow style [] + emptyJSON := `{"server":{"trusted-proxies":[]}}` + w = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodPatch, "/v8/management/config", strings.NewReader(emptyJSON)) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Fatalf("PATCH with empty sequence failed: status=%d body=%s", w.Code, w.Body.String()) + } + saved, errRead = os.ReadFile(file) + if errRead != nil { + t.Fatal(errRead) + } + savedStr = string(saved) + if !strings.Contains(savedStr, "trusted-proxies: []") { + t.Fatalf("expected empty sequence to retain flow style [], got:\n%s", savedStr) + } + + // Also test root PUT with entire JSON document + rootPutJSON := `{"config-version":8,"server":{"port":8317},"api-keys":{"openai-compatibility":[{"name":"compat-provider-root","base-url":"https://api.example3.com","headers":{"User-Agent":"$User-Agent-3"},"models":[{"alias":"coding-3","name":"gpt-4o"}],"keys":[{"api-key":"sk-compat-3"}]}]}}` + w = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodPut, "/v8/management/config", strings.NewReader(rootPutJSON)) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Fatalf("root PUT failed: status=%d body=%s", w.Code, w.Body.String()) + } + saved, errRead = os.ReadFile(file) + if errRead != nil { + t.Fatal(errRead) + } + savedStr = string(saved) + if strings.Contains(savedStr, "[{") || strings.Contains(savedStr, `headers: {`) || strings.Contains(savedStr, `models: [{`) { + t.Fatalf("root PUT saved config contains flow style / inline JSON collections:\n%s", savedStr) + } + if strings.Contains(savedStr, `"config-version":`) || strings.Contains(savedStr, `"server":`) || strings.Contains(savedStr, `"api-keys":`) { + t.Fatalf("root PUT saved config contains quoted keys:\n%s", savedStr) + } + if !strings.Contains(savedStr, "compat-provider-root") { + t.Fatalf("expected compat-provider-root in saved config, got:\n%s", savedStr) + } + + // Verify the final saved file loads correctly into Config + loaded, errLoaded := config.LoadConfig(file) + if errLoaded != nil { + t.Fatalf("LoadConfig failed on normalized saved YAML: %v", errLoaded) + } + if len(loaded.OpenAICompatibility) != 1 || loaded.OpenAICompatibility[0].Name != "compat-provider-root" { + t.Fatalf("unexpected loaded config content: %+v", loaded.OpenAICompatibility) + } + if loaded.OpenAICompatibility[0].Headers["User-Agent"] != "$User-Agent-3" { + t.Fatalf("unexpected loaded headers: %+v", loaded.OpenAICompatibility[0].Headers) + } +} diff --git a/internal/config/config_yaml.go b/internal/config/config_yaml.go index c1c3547bb62..96b55e867fe 100644 --- a/internal/config/config_yaml.go +++ b/internal/config/config_yaml.go @@ -88,7 +88,7 @@ func SaveConfigPreserveComments(configFile string, cfg *Config, migrateV8 ...boo setYAMLPathWithComments(original.Content[0], alias.old, copy) } } - normalizeCollectionNodeStyles(original.Content[0]) + NormalizeCollectionNodeStyles(original.Content[0]) // Encode and validate the layout before opening the destination for writing. var buf bytes.Buffer @@ -840,18 +840,30 @@ func shouldPruneNestedMappingKeys(path []string) bool { } } -// normalizeCollectionNodeStyles forces YAML collections to use block notation, keeping +// NormalizeCollectionNodeStyles forces YAML collections to use block notation, keeping // lists and maps readable. Empty sequences retain flow style ([]) so empty list markers -// remain compact. -func normalizeCollectionNodeStyles(node *yaml.Node) { +// remain compact. It also clears double quotes from string mapping keys so JSON-derived +// keys render as standard unquoted YAML keys. +func NormalizeCollectionNodeStyles(node *yaml.Node) { if node == nil { return } switch node.Kind { + case yaml.DocumentNode: + for i := range node.Content { + NormalizeCollectionNodeStyles(node.Content[i]) + } case yaml.MappingNode: node.Style = 0 - for i := range node.Content { - normalizeCollectionNodeStyles(node.Content[i]) + for i := 0; i < len(node.Content); i += 2 { + key := node.Content[i] + if key != nil && key.Kind == yaml.ScalarNode && key.Tag == "!!str" && key.Style == yaml.DoubleQuotedStyle { + key.Style = 0 + } + NormalizeCollectionNodeStyles(key) + if i+1 < len(node.Content) { + NormalizeCollectionNodeStyles(node.Content[i+1]) + } } case yaml.SequenceNode: if len(node.Content) == 0 { @@ -860,7 +872,7 @@ func normalizeCollectionNodeStyles(node *yaml.Node) { node.Style = 0 } for i := range node.Content { - normalizeCollectionNodeStyles(node.Content[i]) + NormalizeCollectionNodeStyles(node.Content[i]) } default: // Scalars keep their existing style to preserve quoting From 77f10d5949bd7f9fb69b17887dea04e28ddf1533 Mon Sep 17 00:00:00 2001 From: Supra4E8C Date: Thu, 8 Oct 2026 16:43:33 +0800 Subject: [PATCH 098/142] feat(quota): update xAI quota rendering to show shared usage breakdown and adjust related tests --- .../quota/providers/xai/XaiQuotaBody.tsx | 38 +++++++--------- src/features/quota/quotaTimelineModel.ts | 11 +---- src/i18n/locales/en.json | 1 + src/i18n/locales/ru.json | 1 + src/i18n/locales/vi.json | 1 + src/i18n/locales/zh-CN.json | 1 + src/i18n/locales/zh-TW.json | 1 + tests/quotaTimeline.test.ts | 6 +-- tests/xaiQuotaUnavailable.test.ts | 43 +++++++++++++++++++ 9 files changed, 68 insertions(+), 35 deletions(-) diff --git a/src/features/quota/providers/xai/XaiQuotaBody.tsx b/src/features/quota/providers/xai/XaiQuotaBody.tsx index 20bc309618c..dedd541efc3 100644 --- a/src/features/quota/providers/xai/XaiQuotaBody.tsx +++ b/src/features/quota/providers/xai/XaiQuotaBody.tsx @@ -220,28 +220,20 @@ export function XaiQuotaBody({ quota, classes }: QuotaBodyProps) )}
)} - {billing.productUsage.map((item, index) => { - const used = - item.usagePercent === null ? null : Math.max(0, Math.min(100, item.usagePercent)); - const remainingPercent = used === null ? null : Math.max(0, Math.min(100, 100 - used)); - return ( -
-
- - {t('xai_quota.product_usage', { product: item.product })} - -
- - {t('xai_quota.used_percent', { - percent: formatXaiPercent(used), - })} - -
+ {billing.productUsage.length > 0 && ( +
+
{t('xai_quota.usage_breakdown')}
+ {billing.productUsage.map((item) => ( +
+ {t('xai_quota.product_usage', { product: item.product })} + {': '} + {item.usagePercent === null + ? t('xai_quota.usage_unavailable') + : formatXaiPercent(Math.max(0, Math.min(100, item.usagePercent)))}
- -
- ); - })} + ))} +
+ )} {onDemandCap > 0 ? (
@@ -254,7 +246,7 @@ export function XaiQuotaBody({ quota, classes }: QuotaBodyProps)
) : ( @@ -278,7 +270,7 @@ export function XaiQuotaBody({ quota, classes }: QuotaBodyProps)
)} diff --git a/src/features/quota/quotaTimelineModel.ts b/src/features/quota/quotaTimelineModel.ts index 726aba23fb1..3e2523cf0c5 100644 --- a/src/features/quota/quotaTimelineModel.ts +++ b/src/features/quota/quotaTimelineModel.ts @@ -465,15 +465,8 @@ export function buildTimelineLane(input: TimelineLaneInput): TimelineLane { // length; weekly is what `periodType` already told us. periodHours: billing.periodHours ?? 24 * 7, remaining, - // Per-product usage is the closest analogue to the other providers' - // per-window breakdown. - limits: (billing.productUsage ?? []) - .map((entry) => ({ - label: entry.product ?? '', - remaining: - typeof entry.usagePercent === 'number' ? clampPercent(100 - entry.usagePercent) : null, - })) - .filter((limit): limit is TimelineLimit => limit.remaining !== null), + // Products contribute to the shared weekly usage, not independent limits. + limits: [], }; } diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json index c706c7f5c56..34844c76410 100644 --- a/src/i18n/locales/en.json +++ b/src/i18n/locales/en.json @@ -626,6 +626,7 @@ "usage_unavailable": "Usage unavailable from xAI", "reset_at": "Resets {{time}}", "product_usage": "{{product}} usage", + "usage_breakdown": "Usage breakdown (shared quota)", "plan_label": "Plan", "resets_label": "Resets", "prepaid": "Prepaid", diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index b1e03819d39..b8a0c6415b6 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -629,6 +629,7 @@ "usage_unavailable": "Данные об использовании недоступны от xAI", "reset_at": "Сброс {{time}}", "product_usage": "Использование {{product}}", + "usage_breakdown": "Распределение использования (общая квота)", "plan_label": "План", "resets_label": "Сброс", "prepaid": "Предоплата", diff --git a/src/i18n/locales/vi.json b/src/i18n/locales/vi.json index c203830923d..5e4ef1caece 100644 --- a/src/i18n/locales/vi.json +++ b/src/i18n/locales/vi.json @@ -581,6 +581,7 @@ "used_percent": "Đã dùng {{percent}}", "reset_at": "Đặt lại lúc {{time}}", "product_usage": "Mức sử dụng {{product}}", + "usage_breakdown": "Chi tiết sử dụng (hạn mức dùng chung)", "plan_label": "Gói", "plan_supergrok": "SuperGrok", "plan_supergrok_heavy": "SuperGrok Heavy", diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index b2b433332e4..2bd2d9d3edb 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -625,6 +625,7 @@ "usage_unavailable": "xAI 用量暂不可用", "reset_at": "重置 {{time}}", "product_usage": "{{product}} 使用", + "usage_breakdown": "用量明细(共享配额)", "plan_label": "套餐", "resets_label": "重置", "prepaid": "预付", diff --git a/src/i18n/locales/zh-TW.json b/src/i18n/locales/zh-TW.json index 182acee89dc..2febf9305ca 100644 --- a/src/i18n/locales/zh-TW.json +++ b/src/i18n/locales/zh-TW.json @@ -625,6 +625,7 @@ "usage_unavailable": "xAI 用量暫不可用", "reset_at": "重置 {{time}}", "product_usage": "{{product}} 使用", + "usage_breakdown": "用量明細(共用配額)", "plan_label": "方案", "resets_label": "重置", "prepaid": "預付", diff --git a/tests/quotaTimeline.test.ts b/tests/quotaTimeline.test.ts index a8433542c74..d1865119127 100644 --- a/tests/quotaTimeline.test.ts +++ b/tests/quotaTimeline.test.ts @@ -414,7 +414,7 @@ describe('buildTimelineLane', () => { expect(lane.limits).toEqual([]); }); - test('xai anchors on the weekly limit, with per-product limits', () => { + test('xai anchors on the shared weekly limit without independent product limits', () => { const lane = buildTimelineLane({ ...base, provider: 'xai', @@ -436,8 +436,8 @@ describe('buildTimelineLane', () => { expect(lane.anchorMs).toBe(9000); expect(lane.periodHours).toBe(168); expect(lane.remaining).toBe(95); - // GrokChat has no percentage, so it is not summarized. - expect(lane.limits).toEqual([{ label: 'GrokBuild', remaining: 95 }]); + // Product usage is a contribution to the total, not a separate quota pool. + expect(lane.limits).toEqual([]); }); test('xai without a weekly limit produces no window at all', () => { diff --git a/tests/xaiQuotaUnavailable.test.ts b/tests/xaiQuotaUnavailable.test.ts index 35ef711c130..b88796305aa 100644 --- a/tests/xaiQuotaUnavailable.test.ts +++ b/tests/xaiQuotaUnavailable.test.ts @@ -201,6 +201,49 @@ describe('XaiQuotaBody unavailable weekly usage', () => { expect(markup).toContain('$0.00 / $0.00'); }); + test('renders product contributions as text with only one shared weekly meter', () => { + const markup = render( + quotaFor( + weeklyConfig({ + creditUsagePercent: 16, + productUsage: [ + { product: 'GrokBuild', usagePercent: 14 }, + { product: 'GrokChat', usagePercent: 2 }, + ], + }), + monthlyConfig() + ) + ); + + expect(markup).toContain('Used 16%'); + expect(markup).toContain('Usage breakdown (shared quota)'); + expect(markup).toContain('GrokBuild usage: 14%'); + expect(markup).toContain('GrokChat usage: 2%'); + expect(markup).toContain('width:84%'); + expect(markup.match(/class="quotaRow"/g)).toHaveLength(1); + expect(markup).not.toContain('width:86%'); + expect(markup).not.toContain('width:98%'); + }); + + test('does not derive a weekly total or product remainder from partial usage', () => { + const markup = render( + quotaFor( + weeklyConfig({ + productUsage: [ + { product: 'GrokBuild', usagePercent: 14 }, + { product: 'GrokChat', usagePercent: null }, + ], + }), + monthlyConfig() + ) + ); + + expect(markup).toContain('GrokBuild usage: 14%'); + expect(markup).toContain('GrokChat usage: Usage unavailable from xAI'); + expect(markup).not.toContain('width:'); + expect(markup).not.toContain('Used 14%'); + }); + test('keeps monthly amount, percentage, and meter in the remaining direction', () => { const markup = render( quotaFor( From 7c2133e201d991d95b9fef5c4f67d34bd75c618a Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Thu, 8 Oct 2026 16:45:45 +0800 Subject: [PATCH 099/142] fix(cliproxy): reconcile concurrent auth updates during batch model registration - Use latest auth state in model registration to prevent applying stale snapshots - Reconcile and re-register auths with updated generations after batch registration tasks complete Closes: #6453 --- sdk/cliproxy/service_auth.go | 19 +- .../service_batch_model_registration_test.go | 306 ++++++++++++++++++ sdk/cliproxy/service_plugins.go | 28 +- 3 files changed, 345 insertions(+), 8 deletions(-) create mode 100644 sdk/cliproxy/service_batch_model_registration_test.go diff --git a/sdk/cliproxy/service_auth.go b/sdk/cliproxy/service_auth.go index 5acfeeddf16..0b81f2436a6 100644 --- a/sdk/cliproxy/service_auth.go +++ b/sdk/cliproxy/service_auth.go @@ -496,24 +496,29 @@ func (s *Service) completeModelRegistrationForAuth(ctx context.Context, auth *co s.completeModelRegistrationForAuthWithCache(ctx, auth, nil) } -func (s *Service) completeModelRegistrationForAuthWithCache(ctx context.Context, auth *coreauth.Auth, compatCache *openAICompatibilityRegistrationCache) { +func (s *Service) completeModelRegistrationForAuthWithCache(ctx context.Context, auth *coreauth.Auth, compatCache *openAICompatibilityRegistrationCache) uint64 { if s == nil || s.coreManager == nil || auth == nil || auth.ID == "" { - return + return 0 } if ctx != nil && ctx.Err() != nil { - return + return 0 } - s.registerModelsForAuthWithCache(ctx, auth, compatCache) + targetAuth := auth + if latest, ok := s.latestAuthForModelRegistration(auth.ID); ok && latest != nil { + targetAuth = latest + } + s.registerModelsForAuthWithCache(ctx, targetAuth, compatCache) if ctx != nil && ctx.Err() != nil { - return + return 0 } - s.reconcileRegisteredModelStates(ctx, auth) + s.reconcileRegisteredModelStates(ctx, targetAuth) // Refresh the scheduler entry so that the auth's supportedModelSet is rebuilt // from the now-populated global model registry. Without this, newly added auths // have an empty supportedModelSet (because Register/Update upserts into the // scheduler before registerModelsForAuth runs) and are invisible to the scheduler. - s.coreManager.RefreshSchedulerEntry(auth.ID) + s.coreManager.RefreshSchedulerEntry(targetAuth.ID) + return targetAuth.Generation } func (s *Service) applyCoreAuthRemoval(ctx context.Context, id string) { diff --git a/sdk/cliproxy/service_batch_model_registration_test.go b/sdk/cliproxy/service_batch_model_registration_test.go new file mode 100644 index 00000000000..4bbad6776ef --- /dev/null +++ b/sdk/cliproxy/service_batch_model_registration_test.go @@ -0,0 +1,306 @@ +package cliproxy + +import ( + "context" + "net/http" + "strings" + "sync/atomic" + "testing" + + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" +) + +type mockBatchTestExecutor struct { + provider string +} + +func (e mockBatchTestExecutor) Identifier() string { return e.provider } +func (e mockBatchTestExecutor) Execute(context.Context, *coreauth.Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + return cliproxyexecutor.Response{}, nil +} +func (e mockBatchTestExecutor) ExecuteStream(context.Context, *coreauth.Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) { + return nil, nil +} +func (e mockBatchTestExecutor) Refresh(context.Context, *coreauth.Auth) (*coreauth.Auth, error) { + return nil, nil +} +func (e mockBatchTestExecutor) CountTokens(context.Context, *coreauth.Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + return cliproxyexecutor.Response{}, nil +} +func (e mockBatchTestExecutor) HttpRequest(context.Context, *coreauth.Auth, *http.Request) (*http.Response, error) { + return nil, nil +} + +func TestRegisterModelsForAuthBatch_StaleSnapshot_Issue6453(t *testing.T) { + ctx := context.Background() + manager := coreauth.NewManager(nil, &coreauth.RoundRobinSelector{}, nil) + manager.RegisterExecutor(mockBatchTestExecutor{provider: "codex"}) + service := &Service{ + cfg: &config.Config{}, + coreManager: manager, + } + + authID := "auth-codex-batch-stale-6453" + auth := &coreauth.Auth{ + ID: authID, + Provider: "codex", + Status: coreauth.StatusActive, + Attributes: map[string]string{ + "auth_kind": "oauth", + "plan_type": "pro", + }, + } + if _, errRegister := manager.Register(ctx, auth); errRegister != nil { + t.Fatalf("failed to register auth: %v", errRegister) + } + + allowedID := "auth-codex-batch-allowed-6453" + allowedAuth := &coreauth.Auth{ + ID: allowedID, + Provider: "codex", + Status: coreauth.StatusActive, + Attributes: map[string]string{ + "auth_kind": "oauth", + "plan_type": "pro", + }, + } + if _, errRegister := manager.Register(ctx, allowedAuth); errRegister != nil { + t.Fatalf("failed to register allowed auth: %v", errRegister) + } + + reg := GlobalModelRegistry() + reg.UnregisterClient(authID) + reg.UnregisterClient(allowedID) + t.Cleanup(func() { + reg.UnregisterClient(authID) + reg.UnregisterClient(allowedID) + }) + + // Capture a stale snapshot of auths before excluded_models is configured on authID + staleSnapshot := manager.List() + + // Update the auth in coreManager to exclude gpt-6-astra and gpt-6.1-sol + updatedAuth := auth.Clone() + updatedAuth.Attributes = map[string]string{ + "auth_kind": "oauth", + "plan_type": "pro", + "excluded_models": "gpt-6-astra,gpt-6.1-sol", + } + if _, errUpdate := manager.Update(ctx, updatedAuth); errUpdate != nil { + t.Fatalf("failed to update auth: %v", errUpdate) + } + + // Run batch registration with the stale snapshot + service.registerModelsForAuthBatch(ctx, staleSnapshot) + + // Verify that the excluded models are not supported for this client + if reg.ClientSupportsModel(authID, "gpt-6-astra") { + t.Errorf("expected gpt-6-astra to be excluded for %s, but registry supports it", authID) + } + if reg.ClientSupportsModel(authID, "gpt-6.1-sol") { + t.Errorf("expected gpt-6.1-sol to be excluded for %s, but registry supports it", authID) + } + + clientModels := reg.GetModelsForClient(authID) + for _, m := range clientModels { + if m != nil && (strings.EqualFold(m.ID, "gpt-6-astra") || strings.EqualFold(m.ID, "gpt-6.1-sol")) { + t.Errorf("model %q should have been excluded from registered models for %s", m.ID, authID) + } + } + + // Verify scheduler selection picks the allowed account and never the masked account + selected, errSelect := manager.SelectAuth(ctx, "codex", "gpt-6-astra", cliproxyexecutor.Options{}) + if errSelect != nil { + t.Fatalf("failed to select auth for gpt-6-astra: %v", errSelect) + } + if selected == nil || selected.ID != allowedID { + t.Errorf("SelectAuth selected %v, want %s (masked auth %s was selected!)", selected, allowedID, authID) + } +} + +func TestRegisterModelsForAuthBatch_ConcurrentUpdateDuringBatch_Issue6453(t *testing.T) { + ctx := context.Background() + manager := coreauth.NewManager(nil, &coreauth.RoundRobinSelector{}, nil) + manager.RegisterExecutor(mockBatchTestExecutor{provider: "codex"}) + service := &Service{ + cfg: &config.Config{}, + coreManager: manager, + } + + authID := "auth-codex-batch-concurrent-6453" + auth := &coreauth.Auth{ + ID: authID, + Provider: "codex", + Status: coreauth.StatusActive, + Attributes: map[string]string{ + "auth_kind": "oauth", + "plan_type": "pro", + }, + } + if _, errRegister := manager.Register(ctx, auth); errRegister != nil { + t.Fatalf("failed to register auth: %v", errRegister) + } + + allowedID := "auth-codex-batch-concurrent-allowed-6453" + allowedAuth := &coreauth.Auth{ + ID: allowedID, + Provider: "codex", + Status: coreauth.StatusActive, + Attributes: map[string]string{ + "auth_kind": "oauth", + "plan_type": "pro", + }, + } + if _, errRegister := manager.Register(ctx, allowedAuth); errRegister != nil { + t.Fatalf("failed to register allowed auth: %v", errRegister) + } + + reg := GlobalModelRegistry() + reg.UnregisterClient(authID) + reg.UnregisterClient(allowedID) + t.Cleanup(func() { + reg.UnregisterClient(authID) + reg.UnregisterClient(allowedID) + modelRegistrationTaskHook = nil + }) + + var updateDone atomic.Bool + modelRegistrationTaskHook = func() { + if updateDone.CompareAndSwap(false, true) { + updatedAuth := auth.Clone() + updatedAuth.Attributes = map[string]string{ + "auth_kind": "oauth", + "plan_type": "pro", + "excluded_models": "gpt-6-astra,gpt-6.1-sol", + } + if _, errUpdate := manager.Update(ctx, updatedAuth); errUpdate != nil { + t.Errorf("failed to update auth in hook: %v", errUpdate) + } + } + } + + // Run batch registration with the initial snapshot + service.registerModelsForAuthBatch(ctx, manager.List()) + + // Verify that the excluded models are not supported for this client after batch registration completes + if reg.ClientSupportsModel(authID, "gpt-6-astra") { + t.Errorf("expected gpt-6-astra to be excluded for %s, but registry supports it", authID) + } + if reg.ClientSupportsModel(authID, "gpt-6.1-sol") { + t.Errorf("expected gpt-6.1-sol to be excluded for %s, but registry supports it", authID) + } + + clientModels := reg.GetModelsForClient(authID) + for _, m := range clientModels { + if m != nil && (strings.EqualFold(m.ID, "gpt-6-astra") || strings.EqualFold(m.ID, "gpt-6.1-sol")) { + t.Errorf("model %q should have been excluded from registered models for %s", m.ID, authID) + } + } + + // Verify scheduler selection picks the allowed account and never the masked account + selected, errSelect := manager.SelectAuth(ctx, "codex", "gpt-6-astra", cliproxyexecutor.Options{}) + if errSelect != nil { + t.Fatalf("failed to select auth for gpt-6-astra: %v", errSelect) + } + if selected == nil || selected.ID != allowedID { + t.Errorf("SelectAuth selected %v, want %s (masked auth %s was selected!)", selected, allowedID, authID) + } +} + +func TestRegisterModelsForAuthBatch_PostBatchReconciliation_Issue6453(t *testing.T) { + ctx := context.Background() + manager := coreauth.NewManager(nil, &coreauth.RoundRobinSelector{}, nil) + manager.RegisterExecutor(mockBatchTestExecutor{provider: "codex"}) + service := &Service{ + cfg: &config.Config{}, + coreManager: manager, + } + + authID := "auth-codex-batch-reconcile-6453" + auth := &coreauth.Auth{ + ID: authID, + Provider: "codex", + Status: coreauth.StatusActive, + Attributes: map[string]string{ + "auth_kind": "oauth", + "plan_type": "pro", + }, + } + if _, errRegister := manager.Register(ctx, auth); errRegister != nil { + t.Fatalf("failed to register auth: %v", errRegister) + } + + allowedID := "auth-codex-batch-reconcile-allowed-6453" + allowedAuth := &coreauth.Auth{ + ID: allowedID, + Provider: "codex", + Status: coreauth.StatusActive, + Attributes: map[string]string{ + "auth_kind": "oauth", + "plan_type": "pro", + }, + } + if _, errRegister := manager.Register(ctx, allowedAuth); errRegister != nil { + t.Fatalf("failed to register allowed auth: %v", errRegister) + } + + reg := GlobalModelRegistry() + reg.UnregisterClient(authID) + reg.UnregisterClient(allowedID) + t.Cleanup(func() { + reg.UnregisterClient(authID) + reg.UnregisterClient(allowedID) + modelRegistrationTaskPostRunHook = nil + }) + + var updateTriggered atomic.Bool + modelRegistrationTaskPostRunHook = func(id string) { + if id == authID && updateTriggered.CompareAndSwap(false, true) { + // After the initial task ran completeModelRegistrationForAuthWithCache with Generation 1, + // update coreManager to Generation 2 with excluded_models before the batch loop finishes. + // This tests that post-batch reconciliation catches the newer generation and re-registers. + updatedAuth := auth.Clone() + updatedAuth.Attributes = map[string]string{ + "auth_kind": "oauth", + "plan_type": "pro", + "excluded_models": "gpt-6-astra,gpt-6.1-sol", + } + if _, errUpdate := manager.Update(ctx, updatedAuth); errUpdate != nil { + t.Errorf("failed to update auth in post-run hook: %v", errUpdate) + } + } + } + + // Run batch registration with the initial snapshot. + service.registerModelsForAuthBatch(ctx, manager.List()) + + if !updateTriggered.Load() { + t.Fatal("expected post-run hook to trigger during batch registration") + } + + // Verify that the post-batch reconciliation corrected the model list so excluded models are not supported + if reg.ClientSupportsModel(authID, "gpt-6-astra") { + t.Errorf("expected gpt-6-astra to be excluded for %s after reconciliation, but registry supports it", authID) + } + if reg.ClientSupportsModel(authID, "gpt-6.1-sol") { + t.Errorf("expected gpt-6.1-sol to be excluded for %s after reconciliation, but registry supports it", authID) + } + + clientModels := reg.GetModelsForClient(authID) + for _, m := range clientModels { + if m != nil && (strings.EqualFold(m.ID, "gpt-6-astra") || strings.EqualFold(m.ID, "gpt-6.1-sol")) { + t.Errorf("model %q should have been excluded from registered models for %s", m.ID, authID) + } + } + + // Verify scheduler selection picks the allowed account and never the masked account + selected, errSelect := manager.SelectAuth(ctx, "codex", "gpt-6-astra", cliproxyexecutor.Options{}) + if errSelect != nil { + t.Fatalf("failed to select auth for gpt-6-astra: %v", errSelect) + } + if selected == nil || selected.ID != allowedID { + t.Errorf("SelectAuth selected %v, want %s (masked auth %s was selected!)", selected, allowedID, authID) + } +} diff --git a/sdk/cliproxy/service_plugins.go b/sdk/cliproxy/service_plugins.go index df9a65a401a..237b2ee41d0 100644 --- a/sdk/cliproxy/service_plugins.go +++ b/sdk/cliproxy/service_plugins.go @@ -54,6 +54,11 @@ var registerPluginExecutors = func(host *pluginhost.Host, manager *coreauth.Mana // holds authUpdateMu. var modelRegistrationTaskHook func() +// modelRegistrationTaskPostRunHook, if set, runs synchronously inside model registration +// tasks after completeModelRegistrationForAuthWithCache completes. Tests use it to inject +// concurrent auth updates before batch registration finishes. +var modelRegistrationTaskPostRunHook func(authID string) + // RegisterUsagePlugin registers a usage plugin on the global usage manager. // This allows external code to monitor API usage and token consumption. // @@ -172,6 +177,7 @@ func (s *Service) registerModelsForAuthBatch(ctx context.Context, auths []*corea if s == nil || s.coreManager == nil || len(auths) == 0 { return } + var registeredGen sync.Map tasks := make([]modelRegistrationTask, 0, len(auths)) for _, auth := range auths { if auth == nil { @@ -182,11 +188,31 @@ func (s *Service) registerModelsForAuthBatch(ctx context.Context, auths []*corea phase: modelRegistrationPhase(authForRegistration), category: modelRegistrationCategory(authForRegistration), run: func(compatCache *openAICompatibilityRegistrationCache) { - s.completeModelRegistrationForAuthWithCache(ctx, authForRegistration, compatCache) + gen := s.completeModelRegistrationForAuthWithCache(ctx, authForRegistration, compatCache) + registeredGen.Store(authForRegistration.ID, gen) + if modelRegistrationTaskPostRunHook != nil { + modelRegistrationTaskPostRunHook(authForRegistration.ID) + } }, }) } s.runModelRegistrationTasks(ctx, tasks) + if ctx != nil && ctx.Err() != nil { + return + } + + compatCache := s.newOpenAICompatibilityRegistrationCache() + for _, latest := range s.coreManager.List() { + if latest == nil || latest.ID == "" { + continue + } + lastGenVal, loaded := registeredGen.Load(latest.ID) + lastGen, _ := lastGenVal.(uint64) + if !loaded || latest.Generation != lastGen { + s.ensureExecutorsForAuthWithContext(ctx, latest, false) + s.completeModelRegistrationForAuthWithCache(ctx, latest, compatCache) + } + } } func (s *Service) runModelRegistrationTasks(ctx context.Context, tasks []modelRegistrationTask) { From f03160ef438ab49671f759fc96632ecff3c07d70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=98=81=EF=B8=8Fdungsil?= Date: Thu, 8 Oct 2026 17:52:37 +0900 Subject: [PATCH 100/142] feat(i18n): add Korean locale (#484) --- src/i18n/index.ts | 2 + src/i18n/locales/en.json | 3 +- src/i18n/locales/ko.json | 2239 +++++++++++++++++++++++++++++++++++ src/i18n/locales/ru.json | 3 +- src/i18n/locales/vi.json | 3 +- src/i18n/locales/zh-CN.json | 3 +- src/i18n/locales/zh-TW.json | 3 +- src/types/common.ts | 2 +- src/utils/constants.ts | 10 +- src/utils/language.ts | 1 + tests/koreanLocale.test.ts | 32 + 11 files changed, 2294 insertions(+), 7 deletions(-) create mode 100644 src/i18n/locales/ko.json create mode 100644 tests/koreanLocale.test.ts diff --git a/src/i18n/index.ts b/src/i18n/index.ts index 8be00f84abd..c62835383c7 100644 --- a/src/i18n/index.ts +++ b/src/i18n/index.ts @@ -9,6 +9,7 @@ import zhTW from './locales/zh-TW.json'; import en from './locales/en.json'; import ru from './locales/ru.json'; import vi from './locales/vi.json'; +import ko from './locales/ko.json'; import { getInitialLanguage } from '@/utils/language'; i18n.use(initReactI18next).init({ @@ -18,6 +19,7 @@ i18n.use(initReactI18next).init({ en: { translation: en }, ru: { translation: ru }, vi: { translation: vi }, + ko: { translation: ko }, }, lng: getInitialLanguage(), fallbackLng: 'zh-CN', diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json index 34844c76410..b5a0c9af8e8 100644 --- a/src/i18n/locales/en.json +++ b/src/i18n/locales/en.json @@ -1812,7 +1812,8 @@ "chinese_tw": "Traditional Chinese (Taiwan)", "english": "English", "russian": "Русский", - "vietnamese": "Tiếng Việt" + "vietnamese": "Tiếng Việt", + "korean": "한국어" }, "theme": { "switch": "Theme", diff --git a/src/i18n/locales/ko.json b/src/i18n/locales/ko.json new file mode 100644 index 00000000000..400e4d22433 --- /dev/null +++ b/src/i18n/locales/ko.json @@ -0,0 +1,2239 @@ +{ + "common": { + "login": "로그인", + "logout": "로그아웃", + "back": "뒤로", + "cancel": "취소", + "confirm": "확인", + "leave": "나가기", + "stay": "머무르기", + "save": "저장", + "delete": "삭제", + "edit": "편집", + "add": "추가", + "update": "업데이트", + "refresh": "새로 고침", + "close": "닫기", + "success": "성공", + "error": "오류", + "info": "정보", + "warning": "경고", + "loading": "로딩 중...", + "connecting": "연결 중...", + "connected": "연결됨", + "disconnected": "연결 끊김", + "connecting_status": "연결 중", + "connected_status": "연결됨", + "disconnected_status": "연결 끊김", + "yes": "예", + "no": "아니요", + "not_set": "설정되지 않음", + "optional": "선택 사항", + "required": "필수", + "api_key": "키", + "base_url": "주소", + "prefix": "접두사", + "proxy_url": "프록시", + "priority": "우선순위", + "alias": "별칭", + "failure": "실패", + "unknown_error": "알 수 없는 오류", + "quota_update_required": "CPA 버전을 업데이트하거나 업데이트를 확인하세요", + "quota_check_credential": "자격 증명 상태를 확인하세요", + "copy": "복사", + "expand": "펼치기", + "collapse": "접기", + "status": "상태", + "action": "작업", + "custom_headers_label": "사용자 지정 헤더", + "custom_headers_hint": "요청과 함께 보낼 선택적 HTTP 헤더입니다. 제거하려면 비워 두세요.", + "custom_headers_add": "헤더 추가", + "custom_headers_key_placeholder": "헤더 이름 (예: X-Custom-Header)", + "custom_headers_value_placeholder": "헤더 값", + "model_name_placeholder": "모델 이름 (예: claude-3-5-sonnet-20241022)", + "model_alias_placeholder": "모델 별칭 (선택 사항)", + "invalid_provider_index": "유효하지 않은 공급자 인덱스입니다.", + "unsaved_changes_title": "저장되지 않은 변경 사항", + "unsaved_changes_message": "저장되지 않은 변경 사항이 있습니다. 지금 나가면 변경 사항이 삭제됩니다. 나가시겠습니까?" + }, + "title": { + "login": "CLI Proxy API 관리 센터", + "abbr": "CPAMC" + }, + "splash": { + "title": "CLI Proxy API", + "subtitle": "관리 센터" + }, + "login": { + "subtitle": "CLI Proxy API v8 이상 버전에 연결", + "connection_current": "현재 URL", + "connection_auto_hint": "시스템이 자동으로 현재 URL을 사용하여 연결합니다", + "custom_connection_label": "사용자 지정 연결 URL:", + "custom_connection_placeholder": "예: https://example.com:8317", + "custom_connection_hint": "기본적으로 현재 URL이 사용됩니다. 필요한 경우 여기서 재정의하세요.", + "remember_password_label": "비밀번호 저장", + "management_key_label": "관리 키:", + "management_key_placeholder": "관리 키를 입력하세요", + "submit_button": "로그인", + "submitting": "연결 중...", + "error_backend_detail": "백엔드 응답", + "error_required": "연결 정보를 모두 입력하세요", + "error_invalid": "연결에 실패했습니다. 서버 주소, 관리 API 및 관리 키를 확인하세요", + "error_network": "네트워크 연결에 실패했습니다. 네트워크 또는 서버 주소를 확인하세요", + "error_timeout": "연결 시간이 초과되었습니다. 서버가 응답하지 않습니다", + "error_unauthorized": "인증에 실패했습니다. 관리 키가 없거나 유효하지 않습니다", + "error_forbidden": "접근이 거부되었습니다. 원격 관리가 비활성화되었거나, 관리 키가 설정되지 않았거나, 이 IP가 일시적으로 차단되었습니다", + "error_not_found": "v8 관리 API를 찾을 수 없습니다. 서버 주소를 확인하고 CLIProxyAPI를 v8 이상으로 업그레이드하세요. v0은 지원되지 않습니다.", + "error_legacy_backend": "이 백엔드는 v0 관리 API를 허용하지만 v8을 제공하지 않습니다. 이 관리 페이지를 사용하려면 CLIProxyAPI를 v8 이상으로 업그레이드하세요.", + "error_server": "백엔드에서 관리 요청을 처리하는 동안 오류가 발생했습니다. 서버 로그를 확인하세요", + "error_cors": "교차 출처 요청(CORS)이 차단되었습니다. 서버 설정을 확인하세요", + "error_ssl": "SSL/TLS 인증서 확인에 실패했습니다" + }, + "header": { + "refresh_all": "모두 새로 고침", + "logout": "로그아웃" + }, + "connection": { + "status": "연결 상태:" + }, + "nav": { + "dashboard": "대시보드", + "quick_start": "빠른 시작", + "ai_providers": "AI 공급자", + "auth_files": "인증 파일", + "oauth": "OAuth 로그인", + "quota_management": "할당량 관리", + "plugins": "플러그인", + "plugin_store": "플러그인 스토어", + "config_management": "설정 패널", + "logs": "로그 뷰어", + "system_info": "관리 센터 정보" + }, + "nav_groups": { + "operate": "운영", + "gateway": "게이트웨이", + "observe": "모니터링", + "plugin_pages": "플러그인", + "control": "제어" + }, + "nav_meta": { + "dashboard": "운영 개요", + "quick_start": "APIKEY.FUN 설정", + "ai_providers": "업스트림 모델 라우팅", + "auth_files": "인증 파일 및 자격 증명", + "oauth": "OAuth 권한 부여", + "quota_management": "API 키 및 한도", + "plugins": "플러그인 설정 및 전환", + "plugin_store": "플러그인 탐색 및 설치", + "logs": "요청 추적", + "config_management": "게이트웨이 설정", + "system_info": "런타임 및 진단" + }, + "dashboard": { + "hero_verdict_good": "모든 시스템 정상", + "hero_verdict_warning": "다소 불안정", + "hero_verdict_critical": "주의 필요", + "hero_verdict_idle": "현재 유휴 상태", + "hero_verdict_offline": "연결 대기 중", + "hero_verdict_connecting": "연결 중", + "hero_period": ".", + "hero_requests_label": "처리된 요청", + "hero_live": "실시간", + "hero_window_meta": "롤링 {{window}} 윈도우 · 10분 단위 버킷", + "hero_spark_label": "최근 {{window}} 동안의 요청량", + "cta_manage_providers": "공급자 관리", + "cta_inspect_logs": "로그 확인", + "stats_aria": "주요 지표", + "success_rate": "성공률", + "stat_success_hint": "윈도우 내 총 {{total}}건의 요청", + "stat_credentials": "자격 증명", + "stat_credentials_hint": "활성 {{active}}개 · 비제공 {{disabled}}개", + "stat_credentials_empty": "자격 증명 파일을 찾을 수 없습니다", + "stat_provider_keys": "공급자 키", + "stat_provider_keys_hint": "모든 브랜드에 설정된 API 키", + "stat_models": "모델", + "stat_models_hint": "프록시 엔드포인트를 통해 제공됨", + "traffic_eyebrow": "실시간 트래픽", + "traffic_title": "10분 단위 처리량", + "traffic_description": "최근 {{window}} 동안 10분 단위 버킷별 성공 및 실패 횟수입니다. 열에 마우스를 올리면 정확한 구성을 확인할 수 있습니다.", + "traffic_table": "데이터 테이블", + "traffic_table_window": "시간 구간", + "traffic_chart_summary": "최근 {{minutes}}분 동안 총 {{total}}건의 요청: 성공 {{success}}건, 실패 {{failed}}건.", + "traffic_unavailable": "아직 기록된 트래픽이 없습니다", + "traffic_unavailable_hint": "프록시가 첫 번째 요청을 처리하면 카운터가 표시됩니다.", + "fleet_eyebrow": "공급자", + "fleet_title": "모든 공급자 비교", + "fleet_description": "동일한 윈도우 내 각 공급자의 요청량 및 성공률입니다.", + "fleet_empty": "아직 기록된 공급자 트래픽이 없습니다.", + "fleet_credentials": "자격 증명: {{value}}", + "fleet_spark_label": "{{provider}} 요청량", + "fleet_requests": "건의 요청", + "provider_unknown": "미분류", + "health_eyebrow": "건전성", + "health_title": "자격 증명 상태", + "health_active": "활성", + "health_unavailable": "사용 불가", + "health_disabled": "비활성화됨", + "health_by_type": "공급자별", + "health_empty": "자격 증명 파일을 찾을 수 없습니다.", + "health_link": "인증 파일 열기", + "runtime_eyebrow": "런타임", + "runtime_title": "설정 한눈에 보기", + "runtime_routing": "라우팅 전략", + "runtime_retry": "요청 재시도", + "runtime_management_keys": "관리 키", + "runtime_version": "서버 버전", + "runtime_build": "빌드 날짜", + "runtime_proxy": "업스트림 프록시", + "runtime_debug": "디버그", + "runtime_file_logging": "파일 로깅", + "runtime_request_log": "요청 로그", + "runtime_ws_auth": "WebSocket 인증", + "runtime_model_prefix": "모델 접두사", + "runtime_link": "설정 편집", + "cta_eyebrow": "다음", + "cta_title": "다음 작업 안내", + "cta_providers_desc": "API 키를 추가하고 우선순위를 설정하며 브랜드를 테스트합니다.", + "cta_auth_files_desc": "OAuth 자격 증명을 업로드, 새로 고침 및 비활성화합니다.", + "cta_config_desc": "라우팅, 재시도, 로깅 및 접근 권한을 조정합니다.", + "cta_quota_desc": "자격 증명별 남은 할당량을 확인합니다.", + "cta_logs_desc": "요청을 실시간 추적하고 오류 보고서를 다운로드합니다.", + "cta_system_desc": "버전 세부 정보 및 관리 센터 정보입니다.", + "window_m": "{{minutes}}분", + "window_h": "{{hours}}시간", + "window_hm": "{{hours}}시간 {{minutes}}분" + }, + "basic_settings": { + "debug_enable": "디버그 모드 활성화", + "proxy_url_label": "프록시 URL:", + "retry_count_label": "재시도 횟수:", + "logging_to_file_enable": "파일 로깅 활성화", + "request_log_title": "요청 로깅", + "request_log_enable": "요청 로깅 활성화", + "request_log_warning": "상세한 문제 해결이 필요한 경우가 아니면 꺼 두세요.", + "ws_auth_enable": "/ws/* 경로에 인증 요구", + "routing_strategy_round_robin": "round-robin (순환)", + "routing_strategy_weighted_round_robin": "weighted-round-robin (가중 순환)", + "routing_strategy_fill_first": "fill-first (우선 채우기)" + }, + "auth_files": { + "title": "인증 파일 관리", + "meta_total": "자격 증명 {{count}}개", + "meta_active": "활성 {{count}}개", + "meta_problem": "문제 {{count}}개", + "empty_title": "아직 자격 증명이 없습니다", + "empty_desc": "시작하려면 인증 파일을 업로드하거나 OAuth로 공급자를 연결하세요.", + "empty_oauth_link": "OAuth로 연결", + "no_results_clear": "필터 초기화", + "title_section": "인증 파일", + "upload_button": "파일 업로드", + "delete_all_button": "모두 삭제", + "search_empty_title": "일치하는 파일이 없습니다", + "search_empty_desc": "필터를 변경하거나 검색어를 지우고 다시 시도해 보세요.", + "file_size": "크기", + "file_modified": "수정 일시", + "card_select": "{{name}} 자격 증명 선택", + "card_toggle": "{{name}} 자격 증명 활성화", + "card_requests": "요청", + "cooldown_unknown": "쿨다운 상태 알 수 없음", + "cooldown_models_one": "{{count}}개 모델 쿨다운 중", + "cooldown_models_other": "{{count}}개 모델 쿨다운 중", + "cooldown_credential": "자격 증명 전체 쿨다운", + "cooldown_credential_and_models_one": "자격 증명 및 {{count}}개 모델 쿨다운 중", + "cooldown_credential_and_models_other": "자격 증명 및 {{count}}개 모델 쿨다운 중", + "cooldown_scope_credential": "전체 자격 증명", + "cooldown_earliest": "가장 빠른 종료까지 약 {{time}}", + "cooldown_elapsed": "쿨다운 타이머 만료됨", + "cooldown_timer_elapsed": "타이머 만료됨", + "cooldown_refresh_hint": "목록을 새로 고쳐 확인하세요", + "cooldown_seconds": "{{count}}초", + "cooldown_minutes": "{{count}}분", + "cooldown_hours": "{{count}}시간", + "cooldown_http_status": "업스트림 HTTP {{status}}", + "cooldown_backoff": "백오프 레벨 {{level}}", + "cooldown_deadline": "타이머 만료 시각", + "cooldown_observed": "스냅샷 시각", + "cooldown_note": "로컬 스케줄링 스냅샷이며 남은 시간은 추정치입니다. 만료가 가용성, 할당량 복구 또는 자동 재시도를 보장하지는 않습니다. 모델 이름은 내부 상태 키이며 백오프 레벨은 실패 횟수가 아닙니다.", + "cooldown_reset_button": "쿨다운 해제", + "cooldown_reset_hint": "이 자격 증명의 로컬 라우팅 쿨다운을 해제합니다", + "cooldown_reset_title": "자격 증명 쿨다운을 해제하시겠습니까?", + "cooldown_reset_confirm": "“{{name}}”의 로컬 라우팅 쿨다운을 해제하시겠습니까? 해제 시 이 자격 증명이 즉시 다른 요청에 사용될 수 있습니다. 업스트림 할당량은 복구되지 않습니다.", + "cooldown_reset_success": "{{name}}의 쿨다운을 해제했습니다.", + "cooldown_reset_failed": "{{name}}의 쿨다운을 해제할 수 없습니다: {{message}}", + "cooldown_reason_quota": "할당량 제한", + "cooldown_reason_credential_quota": "자격 증명 할당량 제한", + "cooldown_reason_cloudflare_challenge": "Cloudflare 챌린지", + "cooldown_reason_invalid_grant": "유효하지 않은 권한 부여", + "cooldown_reason_unauthorized": "권한 없음", + "cooldown_reason_payment_required": "접근 제한됨 (402/403, 결제 진단 결과 아님)", + "cooldown_reason_not_found": "리소스를 찾을 수 없음", + "cooldown_reason_model_not_supported": "지원되지 않는 모델", + "cooldown_reason_transient_error": "일시적인 업스트림 오류", + "cooldown_reason_unknown": "기타 또는 알 수 없는 이유", + "health_status_label": "상태", + "health_status_healthy": "정상", + "health_status_warning": "경고", + "health_status_disabled": "비활성화됨", + "download_button": "다운로드", + "refresh_all_button": "모든 자격 증명 새로 고침", + "refresh_all_confirm": "현재 필터링된 결과뿐만 아니라 서버의 적격한 모든 자격 증명을 새로 고칩니다. 백엔드는 비활성화되었거나 자격이 없는 자격 증명을 건너뜁니다. 이 작업은 목록을 다시 로드하거나 할당량을 초기화하지 않으며 몇 분 정도 걸릴 수 있습니다. 계속하시겠습니까?", + "refresh_all_results": "자격 증명 새로 고침 결과", + "refresh_all_summary": "{{success}}개 새로 고침 완료, {{failed}}개 실패.", + "refresh_all_empty": "새로 고침할 수 있는 적격 자격 증명이 없습니다.", + "refresh_all_failed": "전체 새로 고침 결과를 가져오지 못했습니다: {{message}}. 일부 자격 증명은 이미 새로 고쳐졌을 수 있습니다. 재시도하기 전에 목록을 확인하세요.", + "refresh_result_success": "새로 고침 완료", + "refresh_result_failed": "새로 고침 실패", + "manual_refresh_button": "OAuth 자격 증명 새로 고침", + "manual_refresh_requested": "\"{{name}}\" 자격 증명 새로 고침을 요청했습니다", + "manual_refresh_failed": "\"{{name}}\" 자격 증명 새로 고침 요청에 실패했습니다: {{message}}", + "delete_button": "삭제", + "delete_confirm": "정말 다음 파일을 삭제하시겠습니까:", + "delete_all_confirm": "모든 인증 파일을 삭제하시겠습니까? 이 작업은 취소할 수 없습니다!", + "delete_filtered_confirm": "모든 {{type}} 인증 파일을 삭제하시겠습니까? 이 작업은 취소할 수 없습니다!", + "delete_problem_button": "문제 파일 삭제", + "delete_problem_button_with_type": "문제가 있는 {{type}} 파일 삭제", + "delete_problem_confirm": "문제가 있는 모든 인증 파일을 삭제하시겠습니까? 이 작업은 취소할 수 없습니다!", + "delete_problem_filtered_confirm": "문제가 있는 모든 {{type}} 인증 파일을 삭제하시겠습니까? 이 작업은 취소할 수 없습니다!", + "delete_filtered_result_button": "필터링된 결과 삭제", + "delete_filtered_result_confirm": "현재 필터링된 결과의 인증 파일을 삭제하시겠습니까? 이 작업은 취소할 수 없습니다!", + "upload_error_json": "JSON 파일만 업로드할 수 있습니다", + "upload_error_size": "파일 크기는 {{maxSize}}을(를) 초과할 수 없습니다", + "upload_success": "파일을 성공적으로 업로드했습니다", + "download_success": "파일을 성공적으로 다운로드했습니다", + "delete_success": "파일을 성공적으로 삭제했습니다", + "delete_all_success": "성공적으로 삭제했습니다", + "delete_filtered_success": "{{type}} 인증 파일 {{count}}개를 성공적으로 삭제했습니다", + "delete_filtered_partial": "{{type}} 인증 파일 삭제 완료: 성공 {{success}}개, 실패 {{failed}}개", + "delete_filtered_none": "현재 필터({{type}})에서 삭제할 수 있는 인증 파일이 없습니다", + "delete_problem_success": "문제가 있는 인증 파일 {{count}}개를 성공적으로 삭제했습니다", + "delete_problem_filtered_success": "문제가 있는 {{type}} 인증 파일 {{count}}개를 성공적으로 삭제했습니다", + "delete_problem_partial": "문제가 있는 인증 파일 삭제 완료: 성공 {{success}}개, 실패 {{failed}}개", + "delete_problem_filtered_partial": "문제가 있는 {{type}} 인증 파일 삭제 완료: 성공 {{success}}개, 실패 {{failed}}개", + "delete_problem_none": "현재 필터에서 삭제할 수 있는 문제가 있는 인증 파일이 없습니다", + "delete_problem_filtered_none": "현재 필터({{type}})에서 삭제할 수 있는 문제가 있는 인증 파일이 없습니다", + "delete_filtered_result_success": "필터링된 결과에서 인증 파일 {{count}}개를 성공적으로 삭제했습니다", + "delete_filtered_result_partial": "필터링된 결과 삭제 완료: 성공 {{success}}개, 실패 {{failed}}개", + "delete_filtered_result_none": "현재 필터링된 결과에 삭제할 수 있는 인증 파일이 없습니다", + "pagination_prev": "이전", + "pagination_next": "다음", + "pagination_info": "{{current}} / {{total}} 페이지 · {{count}}개 파일", + "search_label": "이름, 계정, 유형, 공급자 또는 오류 메시지로 자격 증명 검색", + "search_placeholder": "이름, 계정, 유형, 공급자 또는 오류(403, 429, invalid) 검색. 와일드카드로 * 사용 가능", + "problem_filter_label": "상태 필터", + "problem_filter_all": "전체", + "problem_filter_enabled": "활성화", + "problem_filter_problem": "문제", + "problem_filter_disabled": "비활성화", + "display_options_label": "표시 옵션", + "compact_mode_label": "컴팩트 모드", + "sort_label": "정렬", + "sort_default": "기본", + "sort_az": "이름 (A-Z)", + "sort_priority": "우선순위", + "priority_display": "우선순위", + "weight_display": "WRR 가중치", + "page_size_label": "페이지당", + "filter_all": "전체", + "filter_qwen": "Qwen", + "filter_gemini": "Gemini", + "filter_kimi": "Kimi", + "filter_aistudio": "AIStudio", + "filter_claude": "Claude", + "filter_codex": "Codex", + "filter_meta": "Muse (Meta)", + "filter_devin": "Devin", + "filter_antigravity": "Antigravity", + "filter_xai": "xAI", + "filter_iflow": "iFlow", + "filter_vertex": "Vertex", + "filter_empty": "빈 파일", + "filter_unknown": "기타", + "type_virtual": "가상 인증 파일", + "models_button": "모델", + "models_title": "지원되는 모델", + "models_loading": "모델 목록을 불러오는 중...", + "models_empty": "이 자격 증명에 사용 가능한 모델이 없습니다", + "models_empty_desc": "서버에서 아직 이 자격 증명을 로드하지 않았거나 연결된 모델이 없을 수 있습니다.", + "models_unsupported": "현재 버전에서는 이 기능을 지원하지 않습니다", + "models_unsupported_desc": "CLI Proxy API를 최신 버전으로 업데이트한 후 다시 시도하세요", + "models_excluded_badge": "비활성화됨", + "models_excluded_hint": "이 OAuth 모델은 비활성화되어 있습니다", + "status_toggle_label": "활성화", + "status_enabled_success": "\"{{name}}\"을(를) 활성화했습니다", + "status_disabled_success": "\"{{name}}\"을(를) 비활성화했습니다", + "batch_status_success": "{{count}}개 파일을 성공적으로 업데이트했습니다", + "batch_status_partial": "{{success}}개 성공, {{failed}}개 실패", + "batch_delete_title": "선택한 파일 삭제", + "batch_delete_confirm": "{{count}}개 파일을 삭제하시겠습니까?", + "batch_selected": "{{count}}개 선택됨", + "batch_toolbar_label": "일괄 작업", + "batch_select_all": "전체 선택", + "batch_select_page": "현재 페이지 선택", + "batch_select_filtered": "필터링된 항목 선택", + "batch_invert_page": "현재 페이지 반전", + "batch_deselect": "선택 해제", + "batch_download": "선택 항목 다운로드", + "batch_download_success": "{{count}}개 파일 다운로드를 시작했습니다", + "batch_download_partial": "다운로드 완료: {{success}}개 성공, {{failed}}개 실패", + "batch_enable": "활성화", + "batch_disable": "비활성화", + "prefix_proxy_button": "인증 파일 상세 / 편집", + "prefix_proxy_loading": "인증 파일 불러오는 중...", + "prefix_proxy_info_label": "인증 파일 정보 (info)", + "prefix_proxy_source_label": "인증 파일 JSON (미리보기)", + "prefix_proxy_invalid_content_label": "다운로드된 내용 (잘림)", + "prefix_label": "접두사 (prefix)", + "proxy_url_label": "프록시 URL (proxy_url)", + "proxy_url_placeholder": "socks5://username:password@proxy_ip:port/", + "priority_label": "우선순위 (priority)", + "priority_placeholder": "예: 10 또는 -1", + "priority_hint": "정수만 지원됩니다. 유효하지 않은 값은 무시됩니다. 값이 클수록 우선순위가 높습니다.", + "weight_label": "스케줄링 가중치 (weight)", + "weight_tooltip": "기본값은 1입니다. 0 이하의 값은 가중치 스케줄링에서 이 자격 증명을 제외합니다. 최대값은 1,000,000입니다. 값을 입력한 후 가중 라운드 로빈을 활성화해야 적용됩니다.", + "weight_hint": "기본값은 1입니다. 0 이하의 값은 가중치 스케줄링에서 이 자격 증명을 제외합니다. 최대값은 1,000,000입니다. 값을 입력한 후 가중 라운드 로빈을 활성화해야 적용됩니다.", + "weight_invalid_integer": "가중치는 정수여야 합니다.", + "weight_invalid_max": "가중치는 1,000,000을 초과할 수 없습니다.", + "disable_cooling_label": "지수 쿨다운 비활성화 (disable_cooling)", + "disable_cooling_hint": "이 자격 증명에 대해서만 실패 쿨다운 및 지수 백오프를 건너뜁니다. 다른 자격 증명에는 영향을 주지 않습니다.", + "websockets_label": "WebSockets (websockets)", + "websockets_hint": "이 자격 증명에 대해 Responses API WebSocket 전송을 활성화합니다.", + "using_api_label": "공식 API 사용 (using_api)", + "using_api_hint": "활성화 시 공식 xAI API를 사용하고, 비활성화 시 Grok CLI chat-proxy를 사용합니다.", + "policy_alias_name": "별칭", + "policy_alias_display_name": "표시 이름", + "policy_alias_fork": "목록에 원본 모델 유지", + "policy_alias_force_mapping": "응답 모델을 별칭으로 재작성", + "policy_unsupported": "기존 데이터는 이 양식으로 편집할 수 없으며 그대로 보존됩니다. 삭제하려면 상속을 선택하거나, 새 목록을 시작하려면 교체하세요.", + "policy_replace": "기존 데이터 교체", + "policy_retry_label": "자격 증명 요청 재시도", + "policy_inherit": "상속", + "policy_custom": "사용자 정의", + "policy_retry_count": "재시도 횟수", + "policy_retry_hint": "상속은 전역 request-retry 설정을 사용합니다. 사용자 정의 0은 이 자격 증명에 대한 요청 재시도를 명시적으로 비활성화합니다.", + "policy_aliases_label": "계정 모델 별칭", + "policy_aliases_hint": "계정 별칭이 먼저 확인되며, 일치하지 않는 별칭은 채널 별칭으로 폴백됩니다. 상속 또는 빈 목록은 계정 별칭만 삭제합니다.", + "policy_rules_label": "계정 오류 규칙", + "policy_rules_hint": "사용자 정의 규칙은 목록 순서대로 우선 적용됩니다. 상속 또는 빈 목록은 상속된 규칙을 사용하며 규칙을 비활성화하지는 않습니다. 정규식 패턴은 Go 구문을 사용합니다.", + "policy_retry_invalid": "0 이상의 안전한 정수를 입력하거나 상속을 선택하세요.", + "policy_aliases_invalid": "새로 추가하거나 수정한 각 행에 비어 있지 않은 모델 이름과 별칭을 입력하세요.", + "policy_rules_invalid": "수정된 각 규칙에 양수 상태 코드, 동작 및 하나 이상의 비어 있지 않은 일치 조건을 입력하세요.", + "note_label": "메모", + "note_placeholder": "메모를 입력하세요(예: John의 계정)", + "note_hint": "선택 사항입니다. 이 자격 증명의 용도나 소유자를 설명하는 데 사용되며, 생략하려면 비워 두세요.", + "excluded_models_label": "제외 모델 (excluded_models)", + "headers_label": "사용자 정의 헤더 (headers)", + "headers_placeholder": "{\n \"Header-Name\": \"value\"\n}", + "headers_hint": "사용자 정의 HTTP 헤더를 JSON 객체로 입력하세요(예: {\"X-My-Header\": \"value\"}).", + "headers_invalid_json": "사용자 정의 헤더는 유효한 JSON이어야 합니다.", + "headers_invalid_object": "사용자 정의 헤더는 JSON 객체여야 합니다.", + "headers_invalid_value": "각 사용자 정의 헤더 값은 문자열이어야 합니다.", + "prefix_proxy_invalid_json": "이 인증 파일은 JSON 객체가 아니므로 필드를 편집할 수 없습니다.", + "prefix_proxy_html_challenge": "다운로드된 내용이 인증 JSON 객체가 아닌 HTML 챌린지 페이지입니다. 필드를 편집하기 전에 다시 인증하거나 이 인증 파일을 교체하세요.", + "prefix_proxy_saved_success": "인증 파일 \"{{name}}\"을(를) 성공적으로 업데이트했습니다", + "quota_refresh_single": "할당량 새로 고침", + "quota_refresh_hint": "이 자격 증명의 할당량만 새로 고침합니다", + "quota_refresh_success": "\"{{name}}\"의 할당량을 새로 고쳤습니다", + "quota_refresh_failed": "\"{{name}}\"의 할당량 새로 고침 실패: {{message}}" + }, + "antigravity_subscription": { + "plan_unknown": "알 수 없음", + "plan_free": "Free", + "plan_pro": "Pro", + "plan_ultra": "Ultra", + "plan_ultra_lite": "Ultra Lite" + }, + "antigravity_quota": { + "title": "Antigravity 할당량", + "empty_title": "Antigravity 인증 파일 없음", + "empty_desc": "남은 할당량을 확인하려면 Antigravity 자격 증명을 업로드하세요.", + "idle": "할당량을 새로 고치려면 여기를 클릭하세요", + "loading": "할당량 불러오는 중...", + "load_failed": "할당량 불러오기 실패: {{message}}", + "missing_auth_index": "인증 파일에 auth_index가 없습니다", + "missing_project_id": "Antigravity 자격 증명에 project_id가 없습니다. 프로젝트를 찾으려면 다시 로그인하거나 자격 증명을 새로 고침하세요.", + "empty_models": "사용 가능한 할당량 데이터가 없습니다", + "plan_label": "플랜", + "group_gemini_models": "Gemini 모델", + "group_claude_gpt_models": "Claude 및 GPT 모델", + "group_models_description": "이 그룹의 모델: {{models}}", + "weekly_limit": "주간 한도", + "daily_limit": "일일 한도", + "five_hour_limit": "5시간 한도", + "monthly_limit": "월간 한도", + "quota_available": "할당량 사용 가능", + "remaining_percent": "{{percent}}% 남음", + "refreshes_in": "{{duration}} 후 초기화", + "refresh_available": "초기화 가능", + "duration_day_hour": "{{days}}일 {{hours}}시간", + "duration_hour_minute": "{{hours}}시간 {{minutes}}분", + "duration_minute": "{{minutes}}분", + "duration_less_than_minute": "<1분", + "refresh_button": "할당량 새로 고침", + "fetch_all": "전체 가져오기" + }, + "claude_quota": { + "title": "Claude 할당량", + "empty_title": "Claude OAuth 인증 파일 없음", + "empty_desc": "할당량을 확인하려면 Claude OAuth로 로그인하세요.", + "idle": "할당량을 새로 고치려면 여기를 클릭하세요", + "loading": "할당량 불러오는 중...", + "load_failed": "할당량 불러오기 실패: {{message}}", + "missing_auth_index": "인증 파일에 auth_index가 없습니다", + "empty_windows": "사용 가능한 할당량 데이터가 없습니다", + "refresh_button": "할당량 새로 고침", + "fetch_all": "전체 가져오기", + "five_hour": "5시간 한도", + "seven_day": "7일 한도", + "seven_day_oauth_apps": "7일 OAuth 앱", + "seven_day_opus": "7일 Opus", + "seven_day_sonnet": "7일 Sonnet", + "seven_day_cowork": "7일 Cowork", + "iguana_necktie": "Iguana Necktie", + "seven_day_fable": "7일 Fable 5", + "cloud_session_credits": "클라우드 세션 크레딧", + "extra_usage_label": "추가 사용량", + "plan_label": "플랜", + "plan_unknown": "알 수 없음", + "plan_free": "Free", + "plan_pro": "Pro", + "plan_max": "Max", + "plan_max5": "Max 5x", + "plan_max20": "Max 20x", + "plan_team": "Team" + }, + "codex_quota": { + "title": "Codex 할당량", + "empty_title": "Codex 인증 파일 없음", + "empty_desc": "할당량을 확인하려면 Codex 자격 증명을 업로드하세요.", + "idle": "할당량을 새로 고치려면 여기를 클릭하세요", + "loading": "할당량 불러오는 중...", + "load_failed": "할당량 불러오기 실패: {{message}}", + "missing_auth_index": "인증 파일에 auth_index가 없습니다", + "missing_account_id": "Codex 자격 증명에 ChatGPT 계정 ID가 없습니다", + "empty_windows": "사용 가능한 할당량 데이터가 없습니다", + "no_access": "이 자격 증명에는 Codex 접근 권한이 없습니다(플랜: Free).", + "refresh_button": "할당량 새로 고침", + "fetch_all": "전체 가져오기", + "primary_window": "5시간 한도", + "secondary_window": "주간 한도", + "team_secondary_window": "월간 한도", + "code_review_primary_window": "코드 리뷰 5시간 한도", + "code_review_secondary_window": "코드 리뷰 주간 한도", + "code_review_team_secondary_window": "코드 리뷰 월간 한도", + "additional_primary_window": "{{name}} 5시간 한도", + "additional_secondary_window": "{{name}} 주간 한도", + "additional_team_secondary_window": "{{name}} 월간 한도", + "plan_label": "플랜", + "expires_label": "갱신 시간", + "credit_balance_label": "크레딧 잔액", + "credit_unlimited": "무제한", + "reset_credits_label": "수동 초기화 횟수", + "reset_credits_expiry_label": "수동 초기화 만료 시각 ({{timezone}})", + "reset_credit_number": "초기화 {{index}}", + "reset_credits_expiry_failed": "수동 초기화 만료 시간을 불러오지 못했습니다: {{message}}", + "reset_credits_invalid_payload": "수동 초기화 만료 시간 응답이 올바르지 않습니다.", + "reset_button": "할당량 초기화", + "reset_confirm_title": "Codex 할당량 초기화", + "reset_confirm_message": "수동 초기화 1회를 소모하여 \"{{name}}\"의 Codex 할당량을 초기화합니다. 계속하시겠습니까?", + "reset_confirm_button": "할당량 초기화", + "reset_not_confirmed": "할당량 초기화가 확인되지 않았습니다. 할당량을 새로 고친 후 다시 시도하세요.", + "reset_cooldown_failed": "할당량은 초기화되었지만 게이트웨이 쿨다운을 해제하지 못했습니다. 기존 연결의 자격 증명 페이지에서 '쿨다운 해제'를 사용하고, 추가로 초기화를 사용하지 마세요.", + "reset_success": "\"{{name}}\"의 Codex 할당량을 초기화했습니다.", + "reset_failed": "\"{{name}}\"의 Codex 할당량 초기화 실패: {{message}}", + "plan_plus": "Plus", + "plan_team": "Team", + "plan_free": "Free", + "plan_pro": "Pro 200", + "plan_prolite": "Pro 100", + "plan_business_premium": "Business Premium" + }, + "devin_quota": { + "daily": "일일 잔여 할당량", + "weekly": "주간 잔여 할당량", + "plan_label": "플랜", + "plan_end": "구독 만료", + "unavailable": "정보 없음", + "reset_unknown": "초기화 시간 정보 없음", + "observed_at": "할당량 확인 시각: {{time}}", + "observed_unknown": "할당량 확인 시간 정보 없음", + "missing_identity": "자격 증명 이름 또는 인증 인덱스가 누락되었습니다. 자격 증명 목록을 다시 불러오세요.", + "stale_request": "연결 또는 자격 증명이 변경되었습니다. 다시 시도해 주세요.", + "empty_data": "Devin에서 사용할 수 있는 할당량 데이터를 반환하지 않았습니다.", + "loading": "Devin 할당량 조회 중…", + "idle": "클릭하여 Devin 할당량 조회", + "load_failed": "할당량 조회 실패: {{message}}", + "empty_title": "Devin 자격 증명 없음", + "empty_desc": "Devin 자격 증명 파일을 업로드하거나 백엔드 CLI로 로그인하여 할당량을 조회하세요." + }, + "meta_quota": { + "title": "Muse (Meta) 할당량", + "empty_title": "Muse 자격 증명 없음", + "empty_desc": "Muse OAuth로 로그인하거나 Meta 자격 증명 파일을 업로드하여 할당량을 조회하세요.", + "idle": "클릭하여 Muse 할당량 조회", + "loading": "Muse 할당량 조회 중…", + "load_failed": "할당량 조회 실패: {{message}}", + "missing_auth_index": "인증 파일에 auth_index가 없습니다.", + "empty_data": "할당량을 알 수 없습니다. 아직 모델 요청을 보내지 않았을 수 있습니다.", + "invalid_response": "Muse에서 유효하지 않은 할당량 응답을 반환했습니다.", + "request_failed": "Muse 할당량 요청에 실패했습니다. DCA 자격 증명이 유효한지 확인하세요.", + "missing_file": "할당량을 조회하려면 다운로드 가능한 Meta 인증 파일이 필요합니다.", + "missing_dca_token": "인증 파일에 유효한 dca_token이 없습니다. Muse OAuth로 다시 로그인하세요.", + "invalid_auth_file": "다운로드한 인증 파일이 유효한 JSON이 아닙니다.", + "download_failed": "할당량 조회를 위한 인증 파일을 다운로드할 수 없습니다.", + "stale_request": "연결 또는 자격 증명이 변경되었습니다. 다시 시도해 주세요.", + "plan": "플랜", + "active": "구독 활성", + "inactive": "구독 비활성", + "window": "사용 주기", + "window_duration": "{{minutes}}분 주기", + "weekly": "주간 할당량", + "unknown": "알 수 없음", + "remaining": "{{percent}}% 남음" + }, + "kimi_quota": { + "title": "Kimi 할당량", + "empty_title": "Kimi 인증 파일 없음", + "empty_desc": "남은 할당량을 확인하려면 Kimi 자격 증명을 업로드하세요.", + "domain_unavailable": "Kimi 자격 증명의 도메인을 읽을 수 없습니다. 다운로드 가능한 유효한 인증 파일이 필요합니다.", + "stale_request": "연결 또는 자격 증명이 변경되었습니다. 다시 시도해 주세요.", + "idle": "할당량을 새로 고치려면 여기를 클릭하세요", + "loading": "할당량 불러오는 중...", + "load_failed": "할당량을 불러오지 못했습니다: {{message}}", + "missing_auth_index": "인증 파일에 auth_index가 없습니다.", + "empty_data": "할당량 데이터가 없습니다.", + "refresh_button": "할당량 새로 고침", + "fetch_all": "모두 가져오기", + "weekly_limit": "주간 한도", + "monthly_limit": "월간 한도", + "limit_window": "{{duration}} 한도", + "limit_index": "한도 #{{index}}", + "reset_hint": "{{hint}} 후 초기화" + }, + "xai_quota": { + "title": "Grok 할당량", + "empty_title": "xAI/Grok 인증 파일 없음", + "empty_desc": "xAI OAuth로 로그인하여 Grok 할당량을 확인하세요.", + "idle": "할당량을 새로 고치려면 여기를 클릭하세요", + "loading": "할당량 불러오는 중...", + "load_failed": "할당량을 불러오지 못했습니다: {{message}}", + "missing_auth_index": "인증 파일에 auth_index가 없습니다.", + "empty_data": "할당량 데이터가 없습니다.", + "refresh_button": "할당량 새로 고침", + "fetch_all": "모두 가져오기", + "weekly_limit": "주간 한도", + "monthly_credits": "월간 크레딧", + "used_percent": "{{percent}} 사용됨", + "usage_unavailable": "xAI에서 사용량 정보를 제공하지 않음", + "reset_at": "{{time}} 초기화", + "product_usage": "{{product}} 사용량", + "plan_label": "플랜", + "resets_label": "초기화", + "prepaid": "선불", + "plan_supergrok": "SuperGrok", + "plan_supergrok_heavy": "SuperGrok Heavy", + "plan_paid": "유료", + "paid_health": "유료 API 채팅을 사용할 수 있습니다. xAI는 이 OAuth 자격 증명에 대한 할당량 총합을 제공하지 않습니다.", + "pay_as_you_go_label": "종량제", + "pay_as_you_go_enabled": "활성화됨, 한도 {{cap}}", + "pay_as_you_go_disabled": "비활성화됨" + }, + "vertex_import": { + "title": "Vertex JSON 로그인", + "description": "Google 서비스 계정 JSON을 업로드하여 CLI vertex-import 도우미와 동일한 규칙으로 auth-dir/vertex-.json에 저장합니다.", + "location_label": "리전 (선택 사항)", + "location_placeholder": "us-central1", + "location_hint": "기본 리전인 us-central1을(를) 사용하려면 비워 두세요.", + "file_label": "서비스 계정 키 JSON", + "file_hint": "Google Cloud 서비스 계정 키 JSON 파일만 허용됩니다.", + "file_placeholder": "선택된 파일 없음", + "choose_file": "파일 선택", + "import_button": "Vertex 자격 증명 가져오기", + "file_required": "먼저 .json 자격 증명 파일을 선택하세요.", + "success": "Vertex 자격 증명을 성공적으로 가져왔습니다.", + "result_title": "자격 증명 저장됨", + "result_project": "프로젝트 ID", + "result_email": "서비스 계정", + "result_location": "리전", + "result_file": "저장된 파일" + }, + "oauth_excluded": { + "editor_description": "개별 선택 또는 와일드카드 규칙을 사용하여 공급자가 노출할 모델을 선택합니다.", + "models_hint": "목록을 펼쳐 모델을 선택하거나 아래에 와일드카드 규칙을 입력하세요.", + "title": "OAuth 모델 비활성화", + "description": "공급자별 모델 비활성화가 카드로 표시됩니다. 카드를 클릭하여 수정하거나 삭제하세요. 와일드카드 * 가 지원되며 범위는 인증 파일 필터를 따릅니다.", + "add": "비활성화 추가", + "add_title": "공급자 모델 비활성화 추가", + "edit_title": "{{provider}}의 모델 비활성화 수정", + "provider_label": "공급자", + "provider_placeholder": "예: codex / openai", + "provider_hint": "기본값은 현재 필터입니다. 기존 공급자를 선택하거나 새 이름을 입력하세요.", + "models_label": "비활성화할 모델", + "save": "저장/업데이트", + "save_success": "모델 비활성화가 업데이트되었습니다.", + "save_failed": "모델 비활성화 업데이트에 실패했습니다.", + "delete": "공급자 삭제", + "delete_confirm": "{{provider}}의 모델 비활성화를 삭제하시겠습니까?", + "delete_success": "공급자 모델 비활성화가 제거되었습니다.", + "delete_failed": "모델 비활성화 삭제에 실패했습니다.", + "no_models": "비활성화된 모델이 설정되지 않았습니다.", + "model_count": "모델 {{count}}개 비활성화됨", + "list_empty_all": "아직 공급자 모델 비활성화 설정이 없습니다. “비활성화 추가”를 클릭하여 생성하세요.", + "provider_required": "먼저 공급자를 입력하세요.", + "upgrade_required": "현재 CPA 버전에서는 OAuth 모델 비활성화를 지원하지 않습니다. 업그레이드하세요.", + "upgrade_required_title": "CLI Proxy API를 업그레이드하세요", + "upgrade_required_desc": "현재 서버 버전은 OAuth 모델 비활성화 조회를 지원하지 않습니다. 최신 CPA(CLI Proxy API) 버전으로 업그레이드한 후 다시 시도하세요." + }, + "excluded_models": { + "trigger_summary": "{{excluded}}개 제외됨 · {{available}}개 사용 가능", + "trigger_summary_rules": "{{n}}개 규칙", + "trigger_empty": "제외된 모델 없음", + "meter_aria": "전체 {{total}}개 모델 중 {{excluded}}개 제외됨", + "search_placeholder": "모델 검색…", + "search_aria": "제외할 모델 검색", + "list_aria": "모델", + "no_results": "“{{query}}”와(과) 일치하는 모델이 없습니다", + "catalog_loading": "모델을 불러오는 중…", + "catalog_unavailable": "모델 목록을 불러올 수 없지만 규칙은 계속 적용됩니다.", + "catalog_error": "모델을 불러오지 못했습니다.", + "catalog_retry": "재시도", + "catalog_empty": "표시할 모델이 없습니다.", + "footer_count": "{{excluded}} / {{total}} 제외됨", + "select_all": "모두 제외", + "clear": "초기화", + "clear_aria": "선택한 모델 초기화(와일드카드 규칙 유지됨)", + "badge_wildcard": "규칙 적용", + "badge_unknown": "목록에 없음", + "wildcard_reason": "규칙 {{rule}}에 의해 일치함", + "wildcard_locked": "규칙 {{rule}}에 의해 제외됨: 아래에서 규칙을 수정하세요", + "also_wildcard": "규칙 {{rule}}과(와)도 일치함", + "chips_more": "+{{n}}개 더보기", + "chip_remove": "{{rule}} 제외 취소", + "rules_label": "와일드카드 규칙", + "rules_placeholder": "한 줄에 규칙 하나씩 입력(예: gpt-5-*)", + "rules_hint": "*은(는) 모든 문자와 일치합니다. 대소문자를 구분하지 않습니다.", + "rules_match_count": "{{n}}개 모델과 일치", + "rules_match_none": "목록의 어떤 모델과도 일치하지 않음", + "rules_reserved": "“*”은(는) 공급자 전체를 비활성화합니다. 대신 '비활성화됨' 스위치를 사용하세요" + }, + "oauth_model_alias": { + "editor_description": "클라이언트에서 사용할 수 있도록 공급자 모델에 일관된 이름을 지정합니다.", + "edit_title": "{{provider}}의 모델 별칭 편집", + "mapping_hint": "원본 모델을 선택한 후 클라이언트에서 사용할 별칭을 입력하세요.", + "mapping_row": "별칭 매핑 {{number}}", + "remove_mapping": "별칭 매핑 {{number}} 삭제", + "title": "OAuth 모델 별칭", + "add": "별칭 추가", + "add_title": "공급자 모델 별칭 추가", + "provider_label": "공급자", + "provider_placeholder": "예: codex / vertex", + "provider_hint": "현재 필터의 공급자가 기본으로 지정됩니다. 기존 공급자를 선택하거나 새 이름을 입력하세요.", + "model_source_loading": "모델을 불러오는 중...", + "model_source_unsupported": "현재 CPA 버전은 모델 목록 가져오기를 지원하지 않습니다(수동 입력은 가능).", + "model_source_loaded": "{{count}}개 모델을 불러왔습니다. '원본 모델 이름' 드롭다운을 사용하거나 직접 값을 입력하세요. 목록을 비운 채로 저장하면 해당 공급자가 삭제됩니다. '원본 유지'를 활성화하면 원본 이름을 유지하면서 별칭을 추가합니다.", + "alias_label": "모델 별칭", + "alias_name_placeholder": "원본 모델 이름", + "alias_placeholder": "별칭(필수)", + "duplicate_alias": "이 공급자 내에서 각 별칭은 고유해야 합니다.", + "alias_fork_label": "원본 유지", + "add_alias": "별칭 추가", + "save": "저장/업데이트", + "save_success": "모델 별칭이 업데이트되었습니다", + "save_failed": "모델 별칭 업데이트에 실패했습니다", + "delete": "공급자 삭제", + "delete_confirm": "{{provider}}의 모델 별칭을 삭제하시겠습니까?", + "delete_link_title": "매핑 연결 해제", + "delete_link_confirm": "{{sourceModel}}({{provider}})에서 별칭 {{alias}}(으)로의 매핑 연결을 해제하시겠습니까?", + "delete_alias_title": "별칭 삭제", + "delete_alias_confirm": "별칭 {{alias}}을(를) 삭제하고 연결된 모든 모델의 매핑을 해제하시겠습니까?", + "delete_success": "모델 별칭이 삭제되었습니다", + "delete_failed": "모델 별칭 삭제에 실패했습니다", + "no_models": "모델 별칭 없음", + "model_count": "{{count}}개 별칭", + "list_empty_all": "아직 모델 별칭이 없습니다. “별칭 추가”를 사용하여 만들어 보세요.", + "chart_title": "전체 매핑 개요", + "diagram_providers": "공급자", + "diagram_source_models": "원본 모델", + "diagram_aliases": "별칭", + "diagram_expand": "펼치기", + "diagram_collapse": "접기", + "diagram_add_alias": "별칭 추가", + "diagram_rename": "이름 변경", + "diagram_rename_alias_title": "별칭 이름 변경", + "diagram_rename_alias_label": "새 별칭 이름", + "diagram_rename_placeholder": "별칭 이름을 입력하세요...", + "diagram_delete_link": "{{provider}} / {{name}} 연결 해제", + "diagram_delete_alias": "별칭 삭제", + "diagram_please_enter_alias": "별칭 이름을 입력하세요.", + "diagram_alias_exists": "이미 존재하는 별칭입니다.", + "diagram_add_alias_title": "별칭 추가", + "diagram_add_alias_label": "별칭 이름", + "diagram_add_placeholder": "새 별칭 이름을 입력하세요...", + "diagram_rename_btn": "이름 변경", + "diagram_add_btn": "추가", + "diagram_settings": "설정", + "diagram_settings_title": "별칭 설정: {{alias}}", + "diagram_settings_source_title": "원본 모델 설정", + "diagram_settings_empty": "이 별칭에 대한 매핑이 아직 없습니다.", + "diagram_tap_hint": "터치 기기: 원본 모델을 탭한 후 별칭을 탭하여 연결하세요.", + "view_mode_diagram": "다이어그램", + "view_mode_list": "목록", + "provider_required": "먼저 공급자를 입력하세요", + "upgrade_required": "이 기능은 최신 버전의 CLI Proxy API(CPA)가 필요합니다. 업그레이드하세요.", + "upgrade_required_title": "CLI Proxy API를 업그레이드하세요", + "upgrade_required_desc": "현재 서버는 OAuth 모델 별칭 API를 지원하지 않습니다. 최신 버전의 CLI Proxy API(CPA)로 업그레이드하세요." + }, + "auth_login": { + "devin_oauth_cancel": "Devin 로그인 취소", + "devin_oauth_cancelled": "Devin 로그인이 취소되었습니다.", + "devin_oauth_cancel_error": "Devin 로그인 취소 실패:", + "devin_oauth_retry_hint": "서버가 여전히 인증을 기다리고 있을 수 있습니다. 다시 시작하기 전에 이 로그인을 취소하세요.", + "devin_oauth_title": "Devin OAuth", + "devin_oauth_button": "Devin 로그인 시작", + "devin_oauth_hint": "브라우저 OAuth를 통해 Devin / Cognition에 로그인하여 인증 파일을 저장합니다. CLI Proxy API v7.3.1 이상이 필요하며 5분 이내에 인증을 완료하세요.", + "devin_oauth_url_label": "인증 URL:", + "devin_copy_link": "링크 복사", + "devin_open_link": "링크 열기", + "devin_oauth_status_waiting": "Devin 인증 대기 중...", + "devin_oauth_status_success": "Devin 인증에 성공했습니다!", + "devin_oauth_status_error": "Devin 인증 실패:", + "devin_oauth_start_error": "Devin OAuth 시작 실패:", + "devin_callback_hint": "원격 서버: 루프백 페이지에 접속할 수 없더라도 브라우저 주소창에서 /devin/callback?…(으)로 끝나는 최종 전체 URL을 복사하세요. 포트, http/https, code 및 state를 변경하지 않고 유지해야 합니다. 여기에 URL을 제출한 후 인증이 완료될 때까지 기다리세요.", + "devin_callback_placeholder": "http://127.0.0.1:/devin/callback?code=...&state=...", + "devin_callback_invalid": "state 및 인증 코드 또는 오류가 포함된 완전한 http/https 콜백 URL을 붙여넣으세요.", + "devin_callback_state_mismatch": "이 콜백은 현재 Devin 로그인에 해당하지 않습니다. 이전 콜백을 재사용하지 말고 이번 시도의 최종 URL을 사용하세요.", + "recommended_provider_section": "추천 공급자", + "recommended_provider_badge": "추천 공급자", + "other_oauth_providers": "기타 OAuth 공급자", + "other_login_methods": "기타 로그인 방식", + "codex_oauth_title": "Codex OAuth", + "codex_oauth_button": "Codex 로그인 시작", + "codex_oauth_hint": "OAuth 흐름을 통해 Codex 서비스에 로그인하여 인증 파일을 자동으로 가져오고 저장합니다.", + "codex_oauth_url_label": "인증 URL:", + "codex_open_link": "링크 열기", + "codex_copy_link": "링크 복사", + "codex_oauth_status_waiting": "인증 대기 중...", + "codex_oauth_status_success": "인증에 성공했습니다!", + "codex_oauth_status_error": "인증 실패:", + "codex_oauth_start_error": "Codex OAuth 시작 실패:", + "codex_oauth_polling_error": "인증 상태 확인 실패:", + "anthropic_oauth_title": "Anthropic OAuth", + "anthropic_oauth_button": "Anthropic 로그인 시작", + "anthropic_oauth_hint": "OAuth 흐름을 통해 Anthropic(Claude) 서비스에 로그인하여 인증 파일을 자동으로 가져오고 저장합니다.", + "anthropic_oauth_url_label": "인증 URL:", + "anthropic_open_link": "링크 열기", + "anthropic_copy_link": "링크 복사", + "anthropic_oauth_status_waiting": "인증 대기 중...", + "anthropic_oauth_status_success": "인증에 성공했습니다!", + "anthropic_oauth_status_error": "인증 실패:", + "anthropic_oauth_start_error": "Anthropic OAuth 시작 실패:", + "anthropic_oauth_polling_error": "인증 상태 확인 실패:", + "antigravity_oauth_title": "Antigravity OAuth", + "antigravity_oauth_button": "Antigravity 로그인 시작", + "antigravity_oauth_hint": "OAuth 흐름을 통해 Antigravity(Google 계정) 서비스에 로그인하여 인증 파일을 자동으로 가져오고 저장합니다.", + "antigravity_oauth_url_label": "인증 URL:", + "antigravity_open_link": "링크 열기", + "antigravity_copy_link": "링크 복사", + "antigravity_oauth_status_waiting": "인증 대기 중...", + "antigravity_oauth_status_success": "인증에 성공했습니다!", + "antigravity_oauth_status_error": "인증 실패:", + "antigravity_oauth_start_error": "Antigravity OAuth 시작 실패:", + "antigravity_oauth_polling_error": "인증 상태 확인 실패:", + "meta_oauth_title": "Muse (Meta) OAuth", + "meta_oauth_button": "Muse로 로그인", + "meta_oauth_hint": "인증 링크를 열고 안내가 나타나면 기기 코드를 입력하세요. 인증이 완료되면 인증 파일이 자동으로 저장됩니다.", + "meta_oauth_url_label": "인증 URL:", + "meta_open_link": "링크 열기", + "meta_copy_link": "링크 복사", + "meta_oauth_status_waiting": "인증 대기 중...", + "meta_oauth_status_success": "인증에 성공했습니다!", + "meta_oauth_status_error": "인증 실패:", + "meta_oauth_start_error": "Muse OAuth 시작 실패:", + "meta_oauth_polling_error": "인증 상태 확인 실패:", + "device_code_label": "기기 코드:", + "device_code_copy": "기기 코드 복사", + "kimi_ai_oauth_title": "Kimi 글로벌(kimi.ai)", + "kimi_ai_oauth_button": "Kimi 글로벌 로그인", + "kimi_ai_oauth_hint": "기기 로그인을 통해 kimi.ai 글로벌 계정을 인증합니다. 별도의 kimi-ai 인증 파일이 자동으로 저장됩니다. 중국 계정과 글로벌 계정은 호환되지 않습니다.", + "kimi_ai_oauth_url_label": "인증 URL:", + "kimi_ai_open_link": "링크 열기", + "kimi_ai_copy_link": "링크 복사", + "kimi_ai_oauth_status_waiting": "인증 대기 중...", + "kimi_ai_oauth_status_success": "인증에 성공했습니다!", + "kimi_ai_oauth_status_error": "인증 실패:", + "kimi_ai_oauth_start_error": "Kimi 글로벌 로그인 시작 실패:", + "kimi_ai_oauth_polling_error": "인증 상태 확인 실패:", + "kimi_oauth_title": "Kimi 중국(kimi.com)", + "kimi_oauth_button": "Kimi 중국 로그인", + "kimi_sign_up_button": "지금 가입하기", + "kimi_oauth_hint": "기기 로그인을 통해 kimi.com 중국 계정을 인증합니다. 인증 파일이 자동으로 저장됩니다. 글로벌 계정은 별도의 kimi.ai 로그인을 사용해야 합니다.", + "kimi_oauth_url_label": "인증 URL:", + "kimi_open_link": "링크 열기", + "kimi_copy_link": "링크 복사", + "kimi_oauth_status_waiting": "인증 대기 중...", + "kimi_oauth_status_success": "인증에 성공했습니다!", + "kimi_oauth_status_error": "인증 실패:", + "kimi_oauth_start_error": "Kimi OAuth 시작 실패:", + "kimi_oauth_polling_error": "인증 상태 확인 실패:", + "xai_oauth_title": "xAI OAuth", + "xai_oauth_button": "xAI 로그인 시작", + "xai_oauth_hint": "OAuth 흐름을 통해 xAI Grok 서비스에 로그인하여 인증 파일을 자동으로 가져오고 저장합니다.", + "xai_oauth_url_label": "인증 URL:", + "xai_open_link": "링크 열기", + "xai_copy_link": "링크 복사", + "xai_oauth_status_waiting": "인증 대기 중...", + "xai_oauth_status_success": "인증에 성공했습니다!", + "xai_oauth_status_error": "인증 실패:", + "xai_oauth_start_error": "xAI OAuth 시작 실패:", + "xai_oauth_polling_error": "인증 상태 확인 실패:", + "plugin_oauth_title": "{{name}} OAuth", + "plugin_oauth_button": "{{name}} 로그인 시작", + "plugin_oauth_hint": "플러그인 OAuth 흐름을 통해 {{name}}에 로그인하여 인증 파일을 자동으로 가져오고 저장합니다.", + "plugin_oauth_url_label": "인증 URL:", + "plugin_open_link": "링크 열기", + "plugin_copy_link": "링크 복사", + "plugin_oauth_status_waiting": "인증 대기 중...", + "plugin_oauth_status_success": "인증에 성공했습니다!", + "plugin_oauth_status_error": "인증 실패:", + "plugin_oauth_start_error": "플러그인 OAuth 시작 실패:", + "xai_callback_label": "콜백 URL 또는 코드", + "xai_callback_placeholder": "Grok에 표시된 코드 또는 전체 콜백 URL을 붙여넣으세요", + "xai_callback_hint": "Grok 페이지에 코드만 표시될 수 있습니다. 해당 코드를 직접 붙여넣으면 앱이 http://127.0.0.1:56121/callback?... 형식으로 자동 제출합니다.", + "xai_callback_required": "먼저 Grok에 표시된 코드 또는 전체 콜백 URL을 붙여넣으세요.", + "xai_callback_state_missing": "이번 xAI 로그인의 state 값이 없습니다. xAI 로그인을 다시 시작한 후 코드를 제출하세요.", + "oauth_callback_label": "콜백 URL", + "oauth_callback_placeholder": "http://localhost:1455/auth/callback?code=...&state=...", + "oauth_callback_hint": "원격 브라우저 모드: 공급자가 http://localhost:... 로 리디렉션한 후 전체 URL을 복사하여 여기에 제출하세요.", + "oauth_callback_button": "콜백 URL 제출", + "oauth_callback_required": "먼저 전체 리디렉션 URL을 붙여넣으세요.", + "oauth_callback_success": "콜백 URL이 제출되었습니다. 계속해서 인증을 기다려 주세요.", + "oauth_callback_error": "콜백 URL 제출 실패:", + "oauth_callback_upgrade_hint": "CLI Proxy API를 업데이트하거나 연결을 확인하세요.", + "oauth_callback_status_success": "콜백 URL이 제출되었습니다. 인증 대기 중...", + "oauth_callback_status_error": "콜백 URL 제출 실패:", + "missing_state": "인증 상태 매개변수를 가져올 수 없습니다", + "login_another_account": "다른 계정으로 로그인", + "view_auth_files": "인증 파일 보기", + "iflow_oauth_title": "iFlow OAuth", + "iflow_oauth_button": "iFlow 로그인 시작", + "iflow_oauth_hint": "OAuth 흐름을 통해 iFlow 서비스에 로그인하여 인증 파일을 자동으로 가져오고 저장합니다.", + "iflow_oauth_url_label": "인증 URL:", + "iflow_open_link": "링크 열기", + "iflow_copy_link": "링크 복사", + "iflow_oauth_status_waiting": "인증 대기 중...", + "iflow_oauth_status_success": "인증에 성공했습니다!", + "iflow_oauth_status_error": "인증 실패:", + "iflow_oauth_start_error": "iFlow OAuth 시작 실패:", + "iflow_oauth_polling_error": "인증 상태 확인 실패:", + "remote_access_disabled": "원격 접속에서는 이 로그인 방식을 사용할 수 없습니다. 로컬(localhost)에서 접속하세요." + }, + "stats": { + "success": "성공", + "failure": "실패" + }, + "status_bar": { + "success_short": "✓", + "failure_short": "✗", + "no_requests": "요청 없음" + }, + "logs": { + "preview_too_large": "이 요청 로그는 2 MiB 미리보기 제한을 초과합니다. 다운로드하여 확인하세요.", + "read_status_live": "지속 읽기 중", + "read_status_paused": "읽기 일시 중지됨", + "read_status_catching_up": "밀린 로그 동기화 중", + "last_updated": "최근 성공 업데이트: {{time}}", + "buffer_scope": "로드된 로그만 검색: {{count}}줄 캐시됨, {{matched}}줄 일치", + "buffer_evicted": "이전 로그가 캐시에서 삭제되어 여기에서 검색할 수 없습니다.", + "cursor_reset_notice": "로그가 순환되거나 초기화되었습니다. 최신 내용을 다시 로드했습니다.", + "history_evicted": "읽던 위치가 더 이상 캐시되지 않습니다. 새 위치를 선택하세요.", + "resume_following": "최신 위치로 이동 · 새 줄: {{count}}", + "level_filter": "로그 레벨", + "all_levels": "모든 레벨", + "view_request": "요청 {{id}} 로그 보기", + "copy_line": "이 줄 복사", + "request_log_missing": "요청 로그를 찾을 수 없습니다: 기록되지 않았거나 정리되었을 수 있습니다. 요청 로깅이 비활성화된 경우 대개 오류 요청 로그만 보관됩니다.", + "download_cached": "캐시된 로그 다운로드", + "clear_application_confirm": "서버의 애플리케이션 로그를 지우시겠습니까? 요청 로그 파일은 삭제되지 않습니다. 이 작업은 취소할 수 없습니다.", + "clear_search": "검색 지우기", + "reading_enabled": "지속 읽기", + "filter_load_more": "일치하는 로그 더 보기", + "title": "로그 뷰어", + "refresh_button": "로그 새로 고침", + "clear_button": "로그 지우기", + "fullscreen_button": "전체 화면", + "exit_fullscreen_button": "전체 화면 종료", + "download_button": "로그 다운로드", + "error_logs_modal_title": "오류 요청 로그", + "error_logs_description": "열거나 다운로드할 오류 요청 로그 파일을 선택하세요(요청 로깅이 꺼져 있을 때만 생성됨).", + "error_logs_request_log_enabled": "요청 로깅이 활성화되어 있으므로 이 목록은 항상 비어 있습니다. 오류 로그를 보려면 요청 로깅을 비활성화하고 새로 고침하세요.", + "error_logs_empty": "오류 요청 로그 파일이 없습니다", + "error_logs_load_error": "오류 로그 목록 로드 실패", + "error_logs_size": "크기", + "error_logs_modified": "최종 수정일", + "error_logs_open": "열기", + "error_logs_download": "다운로드", + "error_log_view_title": "오류 요청 로그 상세", + "error_log_open_failed": "오류 로그 열기 실패", + "error_log_empty_content": "이 오류 로그는 비어 있습니다", + "error_log_copy_success": "오류 로그 내용을 복사했습니다", + "error_log_download_success": "오류 로그를 성공적으로 다운로드했습니다", + "request_log_download_title": "요청 로그 다운로드", + "request_log_download_confirm": "ID {{id}}의 요청 로그를 다운로드하시겠습니까?", + "request_log_download_success": "요청 로그를 성공적으로 다운로드했습니다", + "empty_title": "표시할 로그 없음", + "empty_desc": "\"파일 로깅 활성화\"를 활성화하면 여기에 로그가 표시됩니다", + "cpa_file_logging_required": "현재 연결된 런타임은 CPA입니다. 로그를 확인하려면 먼저 파일 로깅을 활성화해야 합니다.", + "cpa_file_logging_required_title": "파일 로깅 필요", + "cpa_file_logging_required_desc": "CPA는 로컬 로그 파일에서 이 로그 뷰를 읽습니다. 설정에서 logging-to-file을 활성화한 후 새로 고침하세요.", + "file_logging_required": "이 로그 엔드포인트에서 파일 로그를 읽으려면 먼저 파일 로깅을 활성화해야 합니다.", + "file_logging_required_title": "파일 로깅 필요", + "file_logging_required_desc": "이 로그 엔드포인트는 로컬 로그 파일을 읽습니다. 설정에서 logging-to-file을 활성화한 후 새로 고침하세요.", + "log_content": "로그 내용", + "loading": "로그 로드 중...", + "load_error": "로그를 로드하지 못했습니다", + "clear_confirm": "모든 로그를 지우시겠습니까? 이 작업은 되돌릴 수 없습니다!", + "clear_success": "로그를 성공적으로 지웠습니다", + "download_success": "로그를 성공적으로 다운로드했습니다", + "auto_refresh": "자동 새로 고침", + "load_more_hint": "더 불러오려면 위로 스크롤하세요", + "hidden_lines": "숨김: {{count}}줄", + "loaded_lines": "로드됨: {{count}}줄", + "filtered_lines": "필터링됨: {{count}}줄", + "hide_management_logs": "{{prefix}} 로그 숨기기", + "show_raw_logs": "원본 로그 표시", + "show_raw_logs_hint": "여러 줄을 쉽게 복사할 수 있도록 원본 로그 텍스트를 표시합니다", + "search_placeholder": "내용 또는 키워드로 로그 검색", + "filter_panel_title": "필터 및 표시", + "wrap_lines": "긴 줄 자동 줄바꿈", + "filter_panel_expand": "구조화된 필터 펼치기", + "filter_panel_collapse": "구조화된 필터 접기", + "filter_panel_active_count": "{{count}}개 활성", + "filter_method": "메서드", + "filter_status": "상태", + "filter_path": "경로", + "filter_path_empty": "경로 후보 없음", + "filter_status_2xx": "2xx", + "filter_status_3xx": "3xx", + "filter_status_4xx": "4xx", + "filter_status_5xx": "5xx", + "clear_filters": "필터 초기화", + "search_empty_title": "일치하는 로그 없음", + "search_empty_desc": "다른 키워드를 시도하거나 필터를 초기화하세요.", + "double_click_copy_hint": "더블클릭하여 원본 로그 줄을 복사하세요", + "copy_success": "로그를 클립보드에 복사했습니다", + "copy_failed": "복사에 실패했습니다" + }, + "config_management": { + "title": "설정 패널", + "meta_fields": "설정 {{count}}개", + "meta_dirty": "저장되지 않음 {{count}}개", + "meta_dirty_source": "저장되지 않은 소스 수정 사항", + "meta_errors": "유효성 검사 오류 {{count}}개", + "meta_synced": "동기화됨", + "actions": { + "discard": "변경 사항 취소", + "save": "변경 사항 저장" + }, + "discard_confirm_message": "저장되지 않은 모든 변경 사항을 취소하고 마지막 서버 버전으로 복원하시겠습니까?", + "mode": { + "label": "편집기 모드", + "visual": "시각", + "source": "소스" + }, + "reload": "다시 로드", + "reload_confirm_message": "다시 로드하면 저장되지 않은 변경 사항이 취소됩니다. 계속하시겠습니까?", + "save": "저장", + "status_loading": "설정 로드 중...", + "status_loading_short": "로드 중", + "status_loaded": "설정 로드됨", + "status_loaded_short": "로드됨", + "status_dirty": "저장되지 않은 변경 사항", + "status_dirty_short": "저장되지 않음", + "status_disconnected": "설정을 로드하려면 서버에 연결하세요", + "status_disconnected_short": "연결 끊김", + "status_load_failed": "로드 실패", + "status_load_failed_short": "실패", + "status_saving": "설정 저장 중...", + "status_saving_short": "저장 중", + "save_success": "설정을 성공적으로 저장했습니다", + "visual_mode_unavailable": "YAML 구문 오류를 수정하기 전에는 시각 편집기를 사용할 수 없습니다", + "visual_mode_unavailable_short": "YAML 오류", + "validation_blocked_short": "오류 수정 필요", + "visual_mode_unavailable_detail": "설정에 잘못된 YAML이 포함되어 있어 시각 편집기를 사용할 수 없습니다: {{message}}", + "visual_mode_save_blocked": "YAML 구문 오류를 수정하기 전에는 시각 모드에서 저장할 수 없습니다", + "source_changes_before_visual": "시각 모드로 전환하기 전에 저장되지 않은 소스 수정 사항을 저장하거나 취소하세요.", + "precise_save_incomplete": "정밀 저장이 완료되지 않았습니다. 일부 변경 사항이 이미 적용되었을 수 있습니다. 초안은 유지됩니다. 다시 저장하여 남은 서버 차이점을 검토하세요.", + "concurrent_list_conflict": "서버 목록 {{path}}이(가) 초안 기준점 이후에 변경되었습니다. 해당 변경 사항을 덮어쓰지 않도록 저장이 차단되었습니다. 초안은 유지됩니다. 수정한 내용을 메모한 후 설정을 다시 로드하여 조정하세요.", + "precise_save_recovery_required": "저장 결과를 다시 읽어오지 못했습니다. 편집이 일시 중지되었습니다. 다시 저장하여 초안 기준점을 복구하거나 설정을 다시 로드하세요.", + "visual_mode_latest_yaml_invalid": "서버의 최신 설정에 잘못된 YAML이 포함되어 있습니다. 시각적 변경 사항을 저장하기 전에 소스 모드에서 검토하세요: {{message}}", + "editor_placeholder": "key: value", + "search_placeholder": "설정 검색...", + "search_button": "검색", + "search_no_results": "결과 없음", + "search_prev": "이전", + "search_next": "다음", + "diff": { + "title": "변경 사항 검토", + "confirm": "저장 확인", + "no_changes": "감지된 변경 사항 없음" + }, + "visual": { + "serverExtras": { + "trustedProxies": { + "label": "신뢰할 수 있는 프록시", + "hint": "IP 주소 또는 CIDR입니다. 비워 두면 전달된 헤더를 신뢰하지 않습니다. 모든 주소 범위를 신뢰하면 클라이언트 IP 위조 위험이 있습니다. 백엔드 재시작이 필요합니다." + }, + "discoveryEnabled": { + "label": "검색 활성화", + "hint": "LAN에서 mDNS / DNS-SD를 통해 브로드캐스트합니다. 기본값은 꺼짐이며, 재시작 없이 변경 사항이 적용됩니다." + }, + "discoveryServiceName": { + "label": "서비스 이름 접두사", + "hint": "백엔드가 짧은 ID를 덧붙입니다. 비워 두면 CPA-를 사용합니다." + }, + "discoveryServiceType": { + "label": "서비스 유형", + "hint": "비워 두면 _ai-gateway._tcp를 사용합니다." + }, + "discoverySubtypes": { + "label": "프로토콜 하위 유형", + "hint": "비워 두면 기본 5가지 프로토콜을 사용합니다. 앞쪽의 _가 누락되면 추가되며, 잘못된 항목은 무시됩니다." + }, + "discoveryInterfacesInclude": { + "label": "포함할 인터페이스", + "hint": "비워 두면 물리적 LAN 인터페이스를 자동으로 선택합니다. 이름이나 *로 끝나는 접두사 패턴을 사용하세요." + }, + "discoveryInterfacesExclude": { + "label": "제외할 인터페이스", + "hint": "이름이나 *로 끝나는 접두사 패턴을 사용하세요. 제외 규칙이 포함 규칙보다 우선합니다." + }, + "discoveryAuthRequired": { + "label": "인증 요구 사항 알림", + "hint": "기본값은 켜짐입니다. 메타데이터만 브로드캐스트하며 실제 API 인증은 변경하지 않습니다." + }, + "discoveryAdvertiseManagement": { + "label": "관리 서비스 알림", + "hint": "기본값은 꺼짐입니다. 관리 서비스가 있음을 알리기만 하며 원격 액세스 권한은 변경하지 않습니다." + }, + "discoveryTitle": "LAN 검색", + "discoveryHint": "멀티캐스트를 지원하는 물리적 인터페이스와 루프백이 아닌 수신 대기 주소가 필요합니다. Docker는 일반적으로 호스트 네트워킹이 필요하며 연결 가능성이 보장되지 않습니다." + }, + "additions": { + "oauthTitle": "OAuth 공급자 동작", + "oauthHint": "이 공급자 설정은 OAuth/파일 기반 자격 증명에만 적용되며, API 키 자격 증명에는 적용되지 않습니다.", + "claudeTitle": "Claude", + "codexTitle": "Codex", + "antigravityTitle": "Antigravity", + "xaiTitle": "xAI", + "liveRelayTitle": "Codex Live 미디어 릴레이", + "liveRelayHint": "프록시 프로세스에서 WebRTC 오디오 및 DataChannel 트래픽을 릴레이합니다. 인바운드 UDP에 연결할 수 있어야 합니다. ICE 자격 증명이 스크린샷이나 로그에 노출되지 않도록 주의하세요.", + "iceAdd": "ICE 서버 추가", + "iceRemove": "ICE 서버 {{index}} 제거", + "iceURLs": "STUN/TURN URL", + "iceUsername": "TURN 사용자 이름", + "iceCredential": "TURN 비밀번호", + "iceServer": "ICE 서버 {{index}}", + "routingSessionAffinitySubagents": { + "label": "서브에이전트 세션 어피니티", + "hint": "기본적으로 활성화되어 있으며 세션 어피니티가 활성화된 경우에만 적용됩니다. 서브에이전트는 캐시를 재사용하기 위해 부모의 자격 증명을 상속합니다. 더 높은 동시성을 위해 자격 증명 풀 전체에 서브에이전트를 분산하려면 비활성화하세요." + }, + "saveCooldownStatus": { + "label": "쿨다운 상태 영속화", + "hint": "자격 증명별 쿨다운 상태를 인증 파일 옆의 .cds 파일에 저장합니다. 기본값은 비활성화이며, 비활성화 시 상태는 메모리에만 유지됩니다." + }, + "transientErrorCooldownSeconds": { + "label": "일시적 오류 쿨다운 (초)", + "hint": "업스트림 408/500/502/503/504/520–526 오류에 대한 쿨다운입니다. 0을 입력하면 기본값인 60초가 적용되며, 음수 값은 이 쿨다운을 비활성화합니다." + }, + "videoResultAuthCacheTTL": { + "label": "비디오 결과 자격 증명 캐시 TTL", + "hint": "비디오 ID가 해당 ID를 생성한 자격 증명에 바인딩된 상태로 유지되는 기간입니다. 30m, 3h와 같은 기간 형식을 사용하며, 기본값은 3h입니다." + }, + "claudeHeaderTimezone": { + "label": "폴백 시간대", + "hint": "위장된 currentDate에 사용할 IANA 시간대입니다(예: Asia/Singapore, 백엔드 호스트 시간대는 Local). 자격 증명 JSON의 timezone이 우선 적용됩니다." + }, + "claudeModelLevelCooling": { + "label": "모델별 쿨다운", + "hint": "해당 자격 증명을 공유하는 모든 모델 대신, 요청된 모델에만 Claude 할당량 쿨다운을 적용합니다. 기본값은 비활성화입니다." + }, + "claudeDisableCloakMode": { + "label": "요청 위장 비활성화", + "hint": "Claude Code CLI 신원 위장 및 시스템 프롬프트 교체를 비활성화하고 원본 시스템 프롬프트를 그대로 전달합니다. 자격 증명 파일에서 cloak_mode로 이를 재정의할 수 있습니다. 기본값: false(Claude Code가 아닌 클라이언트에 대해 자동 위장)." + }, + "claudeCodeDisableCloakingModelList": { + "label": "모델 ID 위장 비활성화", + "hint": "Anthropic 모델 목록 응답에서 위장된 ID 대신 원본 모델 ID를 반환합니다. 기본값은 비활성화입니다." + }, + "codexDisableCloaking": { + "label": "요청 위장 비활성화", + "hint": "HTTP/SSE 및 WebSocket 요청에 공식 Codex User-Agent와 Originator 헤더를 강제로 적용하지 않습니다. 기본값은 비활성화입니다." + }, + "codexModelLevelCooling": { + "label": "모델별 쿨다운", + "hint": "해당 자격 증명을 공유하는 모든 모델 대신, 요청된 모델에만 usage_limit_reached 할당량 쿨다운을 적용합니다. 기본값은 비활성화입니다." + }, + "codexStreamBootstrapBuffering": { + "label": "스트림 부트스트랩 버퍼링", + "hint": "초기 과부하 또는 속도 제한 거부 시 자격 증명 장애 조치가 가능하도록 초기 빈 이벤트와 하트비트를 대기합니다. 기본값은 비활성화입니다. 응답 헤더가 지연되어 클라이언트 또는 리버스 프록시 타임아웃이 발생할 수 있으며, 버퍼링에는 프레임 및 바이트 예산이 적용됩니다." + }, + "codexStreamBootstrapTimeout": { + "label": "스트림 부트스트랩 타임아웃", + "hint": "선택적 버퍼링 시간 제한입니다(예: 20s). 기본값: 0(무제한 시간, 프레임 및 바이트 예산은 여전히 적용됨). 업스트림 프레임이 도착할 때 확인되며, 모든 네트워크 지연 상황에 대한 엄격한 마감 시간은 아닙니다. 헤더는 변환된 출력을 기다릴 수 있습니다." + }, + "codexOptimizeMultiAgentV2": { + "label": "멀티 에이전트 v2 최적화", + "hint": "공식 Codex 멀티 에이전트 요청을 최적화합니다. spawn_agent 모델 세부 정보를 새로 고치고, 메시지 매개변수 암호화를 제거하며, agent_message 콘텐츠를 정규화하고, 비 Codex 프로토콜의 경우 사용자 메시지로 변환합니다. 기본값은 비활성화입니다." + }, + "codexOrphanDelegationCompatibility": { + "label": "고아 위임 호환성", + "hint": "X-Openai-Subagent: collab_spawn 요청의 경우, 유효한 일치 호출이 없는 고아 codex_app/create_thread 및 codex_app/send_message_to_thread 출력을 사용자 메시지로 변환합니다. 기본값은 비활성화입니다." + }, + "codexResponseSteering": { + "label": "응답 스티어링", + "hint": "실험적인 전이중 Codex Responses WebSocket입니다. 각 소켓은 하나의 업스트림 계정 및 모델에 바인딩된 상태를 유지하며, 수락된 입력은 재전송되지 않습니다. 기본값은 비활성화입니다." + }, + "antigravityConnectionPoolEnabled": { + "label": "연결 풀링 활성화", + "hint": "업스트림 HTTP/1.1 연결을 재사용합니다. 기본값: false(단기 연결)." + }, + "antigravityConnectionPoolIdleTimeout": { + "label": "유휴 연결 타임아웃", + "hint": "유휴 연결이 풀에 유지되는 기간입니다. 기본값: 30s, 최대 210s. 0 또는 음수 값으로 지정하면 단기 연결로 전환됩니다." + }, + "antigravityConnectionPoolMaxIdleConnsPerHost": { + "label": "호스트당 최대 유휴 연결 수", + "hint": "자격 증명당 업스트림 호스트별로 유지되는 최대 유휴 연결 수입니다. 기본값: 2, 최대 100. 0은 Go 기본값인 2를 사용하며, 음수 값은 단기 연결로 전환됩니다." + }, + "xaiInjectXSearch": { + "label": "x_search 주입", + "hint": "요청에 xAI 네이티브 x_search 도구가 없을 때 자동으로 추가하며, 해당하는 경우 tool_choice.allowed_tools에도 포함합니다. 기본값은 비활성화입니다." + }, + "codexLiveMediaRelayEnabled": { + "label": "미디어 릴레이 활성화", + "hint": "이 프로세스에서 Codex Live WebRTC 미디어를 종단하고 릴레이합니다. 인바운드 UDP 접근성이 필요합니다. 직접 미디어 연결을 유지하기 위해 기본값은 비활성화입니다." + }, + "codexLiveMediaRelayMaxSessions": { + "label": "최대 동시 미디어 세션 수", + "hint": "비워 두거나 0을 입력하면 기본값인 32개 세션이 사용됩니다. 사용자 지정 UDP 포트 범위는 세션당 최소 2개의 포트를 제공해야 합니다." + }, + "codexLiveMediaRelayDisablePrivateRemoteIPs": { + "label": "사설 원격 IP 후보 차단", + "hint": "기본값: false(로컬 또는 신뢰할 수 있는 네트워크 클라이언트에 대해 사설 후보를 허용함). 활성화하면 사설, 루프백, 링크 로컬 또는 지정되지 않은 IP를 가리키는 다운스트림 SDP 후보를 거부하여 내부 네트워크 노출을 줄입니다. 로컬 연결이 실패할 수 있습니다." + }, + "codexLiveMediaRelayPublicIP": { + "label": "통보할 공인 IP", + "hint": "프록시가 1:1 NAT 뒤에 있을 때 통보할 선택적 공인 IPv4 또는 IPv6 주소입니다. 호스트 이름이 아닌 IP 주소를 입력하세요." + }, + "codexLiveMediaRelayUDPPortMin": { + "label": "최소 UDP 포트", + "hint": "시스템에 할당을 맡기려면 두 UDP 경계값을 모두 0으로 설정하거나, 포트 수가 유효 세션 제한의 최소 2배 이상인 양 끝을 포함하는 연속 범위를 지정하세요." + }, + "codexLiveMediaRelayUDPPortMax": { + "label": "최대 UDP 포트", + "hint": "최소 포트 이상이어야 합니다. 두 경계값은 모두 0이거나 둘 다 0이 아니어야 합니다. 사용자 지정 범위는 세션당 최소 2개의 포트가 필요합니다(기본 32개 세션의 경우 64개)." + }, + "codexLiveMediaRelayICEServers": { + "label": "ICE 서버", + "hint": "stun:, stuns:, turn:, turns: URL을 사용하는 선택적 STUN/TURN 서버입니다. TURN 자격 증명은 JSON 설정 API에서 생략됩니다. 자격 증명을 비밀번호로 입력하고 스크린샷이나 로그에 비밀 정보가 노출되지 않도록 주의하세요." + } + }, + "search": { + "placeholder": "설정 검색 (라벨 또는 YAML 키)", + "no_results": "일치하는 설정이 없습니다" + }, + "sections": { + "common": { + "title": "일반", + "description": "전체 섹션과 동일한 데이터를 기반으로 하는 가장 자주 사용하는 설정" + }, + "connectivity": { + "title": "접속 및 인증", + "description": "서버 주소, 포트, 인증 디렉터리 및 API 키" + }, + "logging": { + "title": "로깅 및 진단", + "description": "디버그, 로그 출력 및 사용량 통계" + }, + "advanced": { + "title": "고급 및 실험", + "description": "헤더 위장, 서명 캐시, 플러그인 소스 및 거의 변경되지 않는 기타 설정", + "plugins_title": "플러그인", + "antigravity_title": "Antigravity", + "devin_title": "Devin", + "signature_title": "서명 검증" + }, + "server": { + "github_token": "전역 GitHub 토큰", + "github_token_hint": "패널 업데이트, 플러그인 다운로드 등의 서버 측 GitHub 요청에 사용됩니다. GITHUB_TOKEN보다 우선 적용됩니다. 비워 두면 환경 자격 증명을 사용하며, 설정된 자격 증명이 없으면 인증되지 않은 요청을 수행합니다. 일치하는 플러그인 스토어 인증 규칙이 우선 적용됩니다.", + "host": "호스트 주소", + "port": "포트" + }, + "tls": { + "title": "TLS/SSL 설정", + "description": "HTTPS 보안 연결 설정", + "enable": "TLS 활성화", + "enable_desc": "HTTPS 보안 연결 활성화", + "cert": "인증서 파일 경로", + "key": "개인 키 파일 경로" + }, + "remote": { + "title": "원격 관리", + "description": "원격 액세스 및 제어판 설정", + "allow_remote": "원격 액세스 허용", + "allow_remote_desc": "다른 호스트에서의 관리 액세스 허용", + "disable_panel": "제어판 비활성화", + "disable_panel_desc": "내장 웹 제어판 비활성화", + "disable_auto_update_panel": "패널 자동 업데이트 비활성화", + "disable_auto_update_panel_desc": "처음 누락되었을 때는 패널을 다운로드하지만 GitHub에서 자동으로 업데이트하지는 않습니다.", + "secret_key": "관리 키", + "secret_key_placeholder": "관리 키를 설정하세요", + "panel_repo": "패널 저장소" + }, + "auth": { + "auth_dir": "OAuth 자격 증명 디렉터리 (oauth.auth-dir)", + "auth_dir_hint": "인증 파일 디렉터리 경로 (~ 지원)" + }, + "system": { + "debug": "디버그 모드", + "debug_desc": "상세 디버그 로깅을 활성화합니다.", + "commercial_mode": "상용 모드", + "commercial_mode_desc": "높은 동시성을 지원하기 위해 오버헤드가 큰 미들웨어를 비활성화합니다.", + "logging_to_file": "파일에 로그 기록", + "logging_to_file_desc": "로그를 파일에 저장합니다.", + "plugins_enabled": "플러그인 시스템 활성화", + "plugins_enabled_desc": "표준 동적 라이브러리 플러그인 로드를 활성화합니다. 개별 플러그인 인스턴스는 플러그인 페이지에서 관리됩니다.", + "plugin_store_sources": "서드파티 플러그인 소스", + "plugin_store_sources_desc": "플러그인 스토어 레지스트리 소스를 추가합니다. 기본 제공 공식 소스는 항상 유지됩니다.", + "plugin_store_sources_label": "플러그인 소스 레지스트리 URL (plugins.store-sources)", + "plugin_store_sources_placeholder": "https://example.com/cliproxy-plugins/registry.json", + "plugin_store_sources_hint": "한 줄에 하나의 registry.json URL을 입력하세요. 빈 줄은 저장 시 제외됩니다.", + "plugin_store_auth": "플러그인 스토어 인증 규칙", + "plugin_store_auth_desc": "비공개 레지스트리, GitHub Release 메타데이터 또는 아티팩트 다운로드를 위한 인증 헤더를 설정합니다.", + "plugin_store_auth_hint": "실제 토큰이 아닌 환경 변수 이름만 입력하세요. 백엔드가 런타임 환경에서 값을 읽어옵니다.", + "store_auth_empty": "구성된 인증 규칙이 없습니다. 공개 플러그인 소스에는 필요하지 않습니다.", + "store_auth_rule": "인증 규칙", + "store_auth_add": "인증 규칙 추가", + "store_auth_match": "일치하는 URL 접두사", + "store_auth_type": "인증 유형", + "store_auth_apply_to": "적용 대상", + "store_auth_apply_to_hint": "선택하지 않으면 모든 요청 유형에 규칙이 적용됩니다.", + "store_auth_apply_registry": "Registry", + "store_auth_apply_metadata": "Metadata", + "store_auth_apply_artifact": "Artifact", + "store_auth_type_none": "없음", + "store_auth_type_bearer": "Bearer", + "store_auth_type_basic": "Basic", + "store_auth_type_header": "사용자 정의 헤더", + "store_auth_type_github_token": "GitHub 토큰", + "store_auth_token_env": "토큰 환경 변수", + "store_auth_username_env": "사용자 이름 환경 변수", + "store_auth_password_env": "비밀번호 환경 변수", + "store_auth_header_name": "헤더 이름", + "store_auth_header_value_env": "헤더 값 환경 변수", + "store_auth_allow_insecure": "안전하지 않은 HTTP URL 허용", + "logs_max_size": "로그 파일 크기 제한 (MB)", + "error_logs_max_files": "오류 로그 보관 파일 수", + "usage_statistics_enabled": "인메모리 사용량 통계 활성화", + "usage_statistics_enabled_desc": "메모리에서 요청 사용량 통계를 집계합니다.", + "redis_usage_retention": "Redis 사용량 큐 보존 시간 (초)", + "redis_usage_retention_hint": "RESP LPOP/RPOP 사용량 출력을 위한 인메모리 보존 시간으로 최대 3600초입니다.", + "antigravity_sensitive_words": "민감한 단어 난독화", + "antigravity_sensitive_words_desc": "Antigravity 시스템 지침에서 일치하는 단어에 너비가 0인 문자를 삽입하여 업스트림의 정확한 키워드 일치를 줄입니다.", + "antigravity_sensitive_words_label": "OAuth 민감한 단어 (oauth.providers.antigravity.sensitive-words)", + "antigravity_sensitive_words_placeholder": "proxy", + "antigravity_sensitive_words_hint": "한 줄에 하나의 단어 또는 구문을 입력하세요. 대소문자를 구분하지 않으며, 빈 항목은 제거되고 2자 미만의 항목은 백엔드에서 무시됩니다.", + "devin_sensitive_words": "Devin 시스템 프롬프트 민감한 단어", + "devin_sensitive_words_desc": "Devin 시스템 프롬프트에서만 설정된 단어가 포함된 전체 줄을 제거하고, 남은 시스템 프롬프트는 난독화됩니다. 일반 메시지와 도구 인수는 변경되지 않습니다.", + "devin_sensitive_words_label": "OAuth 민감한 단어 (oauth.providers.devin.sensitive-words)", + "devin_sensitive_words_placeholder": "민감한 구문", + "devin_sensitive_words_hint": "한 줄에 하나의 단어 또는 구문을 입력하세요. 일치하는 내용이 있으면 시스템 프롬프트의 해당 줄 전체가 삭제되므로 주의하여 설정하세요. 저장 시 빈 항목은 제거됩니다.", + "antigravity_signature_cache": "Antigravity 서명 캐시 활성화", + "antigravity_signature_cache_desc": "캐시된 사고 블록 서명을 우선 사용하고 검증합니다.", + "antigravity_signature_strict": "엄격한 바이패스 서명 검증", + "antigravity_signature_strict_desc": "서명 캐시가 비활성화된 경우에만 적용되며, 전체 Claude protobuf 트리를 검증합니다." + }, + "headers": { + "title": "헤더 기본값", + "description": "클라이언트에서 생략된 경우 Claude 및 Codex OAuth 요청에 사용할 기본 헤더입니다.", + "claude_title": "Claude OAuth 헤더 기본값", + "codex_title": "Codex OAuth 헤더 기본값", + "user_agent": "User-Agent", + "package_version": "Package Version", + "runtime_version": "Runtime Version", + "os": "OS", + "arch": "Arch", + "timeout": "Timeout", + "stabilize_device": "기기 프로필 안정화", + "stabilize_device_desc": "자격 증명/API 키별로 OS/Arch를 고정하고 소프트웨어 지문을 안정화합니다.", + "beta_features": "Beta Features" + }, + "network": { + "title": "네트워크 설정", + "description": "프록시, 재시도 및 라우팅 설정", + "proxy_url": "프록시 URL", + "proxy_url_sponsor_hint": "적합한 프록시가 없나요?", + "request_retry": "요청 재시도 횟수", + "max_retry_credentials": "최대 재시도 자격 증명 수", + "max_retry_credentials_hint": "설정하지 않으려면 비워 두세요. 사용 가능한 모든 자격 증명을 시도하려면 0 또는 음의 정수를 입력하세요.", + "max_retry_interval": "최대 재시도 간격(초)", + "max_retry_interval_hint": "재시도 라운드 간 쿨다운 대기를 건너뛰려면 0 또는 음의 정수를 입력하세요.", + "auth_auto_refresh_workers": "인증 자동 새로 고침 워커 수", + "auth_auto_refresh_workers_hint": "양의 정수는 워커 수를 재정의하며, 0, 음의 정수 또는 빈 필드는 기본값(16)을 사용합니다.", + "disable_image_generation": "이미지 생성 비활성화", + "disable_image_generation_hint": "false는 활성화, true는 모든 이미지 생성 비활성화, chat은 비이미지 엔드포인트 주입 비활성화, passthrough는 주입 없이 클라이언트 도구 목록을 유지합니다.", + "disable_image_generation_false": "false (활성화)", + "disable_image_generation_true": "true (모두 비활성화)", + "disable_image_generation_chat": "chat (채팅 주입만 비활성화)", + "disable_image_generation_passthrough": "passthrough (클라이언트 도구 목록 유지)", + "gpt_image_2_base_model": "GPT Image 2 기본 모델", + "gpt_image_2_base_model_hint": "gpt-image-2 이미지 요청을 프록시할 때 사용하는 메인라인 모델입니다. 비어 있거나 유효하지 않으면 백엔드 기본값을 사용합니다.", + "routing_strategy": "라우팅 전략", + "routing_strategy_hint": "자격 증명 선택 전략을 선택하세요", + "strategy_round_robin": "라운드 로빈", + "strategy_weighted_round_robin": "가중 라운드 로빈", + "strategy_fill_first": "채우기 우선", + "session_affinity_ttl": "세션 어피니티 TTL", + "force_model_prefix": "모델 접두사 강제", + "force_model_prefix_desc": "접두사가 없는 모델 요청은 접두사가 없는 자격 증명만 사용합니다.", + "passthrough_headers": "업스트림 헤더 전달", + "passthrough_headers_desc": "필터링된 업스트림 응답 헤더를 다운스트림 클라이언트에 전달합니다.", + "disable_cooling": "쿨다운 비활성화", + "disable_cooling_desc": "실패 후 인증/모델 쿨다운 기간을 전역적으로 비활성화합니다.", + "session_affinity": "세션 어피니티 라우팅", + "ws_auth": "WebSocket 인증", + "ws_auth_desc": "AI Studio WebSocket 연결에 인증을 요구합니다 (oauth.providers.aistudio.ws-auth)" + }, + "quota": { + "title": "할당량 폴백", + "description": "할당량이 초과되었을 때의 폴백 전략", + "switch_project": "프로젝트 전환", + "switch_project_desc": "할당량이 초과되면 다른 프로젝트로 자동 전환합니다.", + "switch_preview_model": "프리뷰 모델로 전환", + "switch_preview_model_desc": "할당량이 초과되면 프리뷰 모델 버전으로 전환합니다.", + "antigravity_credits": "Antigravity 크레딧 사용" + }, + "streaming": { + "title": "스트리밍 설정", + "description": "Keepalive 및 부트스트랩 재시도 설정", + "keepalive_seconds": "Keepalive 시간(초)", + "keepalive_hint": "keepalive를 비활성화하려면 0, 음의 정수로 설정하거나 비워 두세요.", + "bootstrap_retries": "부트스트랩 재시도 횟수", + "bootstrap_hint": "첫 번째 바이트 전의 재시도 횟수입니다. 0, 음의 정수 또는 빈 필드는 부트스트랩 재시도를 비활성화합니다.", + "nonstream_keepalive": "비스트리밍 Keepalive 간격(초)", + "nonstream_keepalive_hint": "비스트리밍 응답 시 N초마다 빈 줄을 전송합니다. 0, 음의 정수 또는 빈 필드는 keepalive를 비활성화합니다.", + "disabled": "비활성화됨" + }, + "payload": { + "title": "페이로드 설정", + "description": "기본값, 원시 JSON 규칙, 재정의 규칙 및 필터 규칙", + "default_rules": "기본 규칙", + "default_rules_desc": "요청에 매개변수가 지정되지 않은 경우 이 기본값을 사용합니다.", + "default_raw_rules": "기본 Raw 규칙", + "default_raw_rules_desc": "매개변수가 누락된 경우 true, 123, \"high\" 또는 {\"type\":\"object\"}와 같은 원시 JSON 조각으로 이 값을 작성합니다.", + "override_rules": "재정의 규칙", + "override_rules_desc": "요청의 매개변수 값을 강제로 재정의합니다.", + "override_raw_rules": "재정의 Raw 규칙", + "override_raw_rules_desc": "매개변수 값을 항상 원시 JSON 조각으로 덮어씁니다. response_format, 스키마 및 기타 복잡한 필드에 유용합니다.", + "filter_rules": "필터 규칙", + "filter_rules_desc": "JSON Path를 통해 업스트림 요청 본문을 사전 필터링하고 규격에 맞지 않거나 중복된 매개변수를 자동으로 제거합니다 (Request Sanitization)." + } + }, + "api_keys": { + "label": "클라이언트 API 키 (access.api-keys)", + "add": "API 키 추가", + "generate": "생성", + "empty": "API 키 없음", + "hint": "각 항목은 하나의 API 키를 나타냅니다 ('API 키 관리' 페이지 스타일과 일치).", + "edit_title": "API 키 편집", + "add_title": "API 키 추가", + "input_label": "API 키", + "input_placeholder": "API 키를 붙여넣으세요", + "name_label": "이름 / 설명 (선택 사항)", + "name_placeholder": "예: Alice의 노트북", + "name_hint": "이 브라우저에만 즉시 저장되며 서버별로 구분됩니다. 서버 설정에는 포함되지 않습니다. 이름을 제거하려면 이 필드를 비우세요.", + "name_save_error": "브라우저 저장소에 이름을 저장할 수 없습니다. 브라우저 저장소 설정을 확인하세요.", + "input_hint": "설정을 저장한 후 변경 사항이 적용됩니다. 업스트림 공급자 키는 별도로 관리됩니다.", + "error_empty": "API 키를 입력하세요", + "error_invalid": "API 키에 유효하지 않은 문자가 포함되어 있습니다", + "strength": { + "label": "API 키 강도", + "empty": "입력되지 않음", + "weak": "약함", + "fair": "보통", + "good": "좋음", + "strong": "강함" + } + }, + "payload_rules": { + "rule": "규칙", + "models": "적용 가능한 모델", + "model_name": "모델 이름", + "provider_type": "공급자 유형", + "add_model": "모델 추가", + "params": "매개변수 설정", + "remove_params": "매개변수 제거", + "json_path": "JSON Path (예: temperature)", + "json_path_filter": "JSON Path (gjson/sjson), 예: generationConfig.thinkingConfig.thinkingBudget", + "param_type": "매개변수 유형", + "param_value": "매개변수 값", + "add_param": "매개변수 추가", + "no_rules": "규칙 없음", + "add_rule": "규칙 추가", + "provider_default": "기본", + "provider_openai": "OpenAI", + "provider_openai_response": "OpenAI Response", + "provider_responses": "Responses", + "provider_gemini": "Gemini", + "provider_claude": "Claude", + "provider_codex": "Codex", + "provider_antigravity": "Antigravity", + "advanced": "고급", + "hide_advanced": "고급 숨기기", + "from_protocol": "소스 프로토콜 (from-protocol)", + "headers": "요청 헤더 일치", + "header_name": "헤더 이름", + "header_value": "헤더 값", + "add_header": "헤더 추가", + "match": "필수 일치 (match)", + "notMatch": "금지 일치 (not-match)", + "exist": "필수 경로 (exist)", + "notExist": "금지 경로 (not-exist)", + "condition_path": "일치 경로", + "condition_value": "일치 값", + "add_condition": "조건 추가", + "value_type_string": "문자열", + "value_type_number": "숫자", + "value_type_boolean": "불리언", + "value_type_json": "JSON", + "value_string": "문자열 값", + "value_number": "숫자 값 (예: 0.7)", + "value_boolean": "true 또는 false", + "value_json": "JSON 값", + "value_raw_json": "원시 JSON 조각, 예: true, 123, \"high\" 또는 {\"type\":\"object\"}", + "value_default": "값", + "boolean_true": "true", + "boolean_false": "false" + }, + "validation": { + "invalid_trusted_proxies": "각 신뢰할 수 있는 프록시는 유효한 IP 주소 또는 CIDR이어야 합니다.", + "invalid_discovery_service_type": "_name._tcp 형식을 사용하세요: 이름은 1~15자의 영문자, 숫자 또는 하이픈이어야 하며, 시작이나 끝에 하이픈이 올 수 없습니다.", + "validation_blocked": "저장하기 전에 유효성 검사 오류를 수정하세요", + "invalid_duration": "30s 또는 3h와 같은 유효한 기간을 입력하세요", + "positive_duration": "0보다 큰 기간을 입력하세요", + "invalid_timezone": "Asia/Singapore과 같은 유효한 IANA 표준 시간대를 입력하세요", + "invalid_ip": "유효한 IPv4 또는 IPv6 주소를 입력하세요", + "udp_port_pair": "두 UDP 포트를 모두 0으로 설정하거나, 최솟값이 최댓값을 초과하지 않도록 둘 다 설정하세요", + "udp_port_capacity": "UDP 포트 범위는 유효 최대 세션 수의 최소 2배 이상의 포트를 포함해야 합니다(세션 수가 0인 경우 32 사용).", + "invalid_ice_servers": "각 ICE 서버에는 유효한 stun:, stuns:, turn: 또는 turns: URL이 하나 이상 필요합니다", + "integer_range_0_65535": "0에서 65535 사이의 정수를 입력하세요", + "port_range": "1에서 65535 사이의 유효한 포트를 입력하세요", + "integer": "정수를 입력하세요", + "non_negative_integer": "0 이상의 정수를 입력하세요", + "integer_range_1_3600": "1에서 3600 사이의 정수를 입력하세요", + "payload_invalid_number": "유효한 숫자를 입력하세요", + "payload_invalid_boolean": "true 또는 false를 선택하세요", + "payload_invalid_json": "유효한 JSON을 입력하세요" + }, + "common": { + "edit": "편집", + "delete": "삭제", + "cancel": "취소", + "update": "업데이트", + "add": "추가" + } + } + }, + "quota_management": { + "search_label": "계정 검색", + "search_placeholder": "파일명 또는 이메일로 검색", + "search_empty_title": "일치하는 계정 없음", + "search_empty_desc": "다른 파일명이나 이메일을 입력하거나 검색을 초기화하세요.", + "search_clear": "검색 초기화", + "title": "할당량 관리", + "description": "Antigravity, Codex, Claude, Kimi 및 xAI 자격 증명의 OAuth 할당량 상태를 모니터링합니다.", + "refresh_all_credentials": "모든 자격 증명 새로 고침", + "sort_label": "정렬", + "sort_default": "기본값", + "sort_soonest": "가장 빠른 복구순", + "meta_credentials": "자격 증명 {{count}}개", + "meta_loaded": "{{count}}개 로드됨", + "meta_attention": "{{count}}개 주의 필요", + "empty_title": "할당량 확인 가능한 자격 증명 없음", + "empty_desc": "여기에서 할당량을 추적하려면 Antigravity, Claude, Codex, xAI 또는 Kimi 자격 증명을 연결하세요.", + "windows_title": "할당량 윈도우", + "windows_span_weekly": "2주", + "windows_span_session": "3일", + "windows_current": "현재", + "windows_today": "오늘", + "windows_prev": "이전", + "windows_next": "다음", + "windows_mode_weekly": "주간", + "windows_mode_session": "5시간", + "windows_credential": "자격 증명", + "windows_idle": "카운트다운 중인 윈도우 없음", + "windows_empty_session": "이 페이지의 어떤 자격 증명도 5시간 할당량 윈도우를 보고하지 않습니다.", + "windows_legend_current": "현재 윈도우", + "windows_legend_upcoming": "예정", + "windows_legend_elapsed": "경과됨", + "windows_legend_reset_credit": "수동 초기화 만료", + "soonest_row_hint": "이 자격 증명에서 가장 먼저 복구됨", + "windows_reset_credit": "수동 초기화", + "windows_credit_granted": "부여 일시", + "windows_credit_expires": "만료 일시", + "windows_note_weekly": "각 막대는 시작된 시점부터 초기화될 때까지의 전체 할당량 윈도우 하나를 나타냅니다. 함께 끝나는 레인은 동일한 날짜를 두고 경쟁합니다.", + "windows_note_session": "각 막대는 5시간 윈도우 하나를 나타냅니다. 카운트다운 중인 윈도우가 있는 자격 증명만 투영할 수 있으며, 나머지는 임의로 만들어내지 않고 빈 상태로 유지됩니다.", + "weekday_sun": "일", + "weekday_mon": "월", + "weekday_tue": "화", + "weekday_wed": "수", + "weekday_thu": "목", + "weekday_fri": "금", + "weekday_sat": "토" + }, + "plugin_management": { + "title": "플러그인 관리", + "description": "발견 및 등록된 플러그인을 검토하고, 인스턴스 토글, 설정 필드 및 리소스 링크를 관리합니다.", + "refresh": "새로 고침", + "load_failed": "플러그인을 불러오지 못했습니다", + "config_load_failed": "플러그인 설정을 읽지 못했습니다", + "config_not_found": "백엔드에서 이 플러그인을 찾을 수 없어 플러그인 설정을 읽을 수 없습니다.", + "unsupported_backend": "현재 백엔드가 플러그인 관리 API를 노출하지 않습니다. 플러그인 관리 엔드포인트가 포함된 최신 백엔드 빌드를 사용한 후 서비스를 다시 시작하세요.", + "global_status": "전역 상태", + "global_enabled": "활성화됨", + "global_disabled": "비활성화됨", + "global_disabled_hint": "plugins.enabled가 false이므로 활성화된 플러그인 인스턴스가 적용되지 않습니다.", + "plugins_dir": "플러그인 디렉터리", + "discovered": "발견됨", + "effective": "적용됨", + "search_placeholder": "플러그인 ID, 이름, 작성자 또는 리소스 검색...", + "search_label": "플러그인 검색", + "no_plugins": "플러그인 없음", + "no_plugins_desc": "플러그인 디렉터리 또는 런타임 레지스트리에서 플러그인을 찾을 수 없습니다.", + "configured": "설정됨", + "not_configured": "미설정", + "registered": "등록됨", + "not_registered": "미등록", + "oauth": "OAuth", + "status_effective": "적용 중", + "status_inactive": "미적용", + "edit_config": "설정 편집", + "open_repository": "저장소 열기", + "config_title": "{{name}} 설정", + "base_settings": "기본 설정", + "enabled": "활성화", + "enabled_hint": "plugins.configs에서 이 플러그인 인스턴스의 enabled 필드를 제어합니다.", + "priority": "우선순위", + "config_fields": "설정 필드", + "no_config_fields": "이 플러그인은 시각 설정 필드를 선언하지 않았습니다.", + "select_placeholder": "선택하세요", + "array_item_placeholder": "배열 항목을 입력하세요", + "add_array_item": "배열 항목 추가", + "remove_array_item": "배열 항목 삭제", + "delete_plugin": "삭제", + "delete_confirm_title": "플러그인 삭제", + "delete_confirm_message": "{{name}}({{id}})을(를) 삭제하시겠습니까? 로컬 플러그인 파일과 저장된 설정이 삭제됩니다.", + "delete_success": "플러그인을 삭제했습니다", + "delete_failed": "플러그인 삭제에 실패했습니다", + "delete_restart_required": "로드된 플러그인은 백엔드를 재시작해야 제거할 수 있습니다.", + "toggle_success": "플러그인 상태를 업데이트했습니다", + "toggle_failed": "플러그인 상태 업데이트에 실패했습니다", + "runtime_pending": "플러그인 변경 사항이 저장되었지만 런타임 상태는 아직 보류 중입니다. 나중에 새로 고침하거나 백엔드 로그를 확인하세요.", + "save_success": "플러그인 설정을 저장했습니다", + "save_failed": "플러그인 설정 저장에 실패했습니다", + "validation_failed": "플러그인 설정 양식의 오류를 먼저 수정하세요", + "invalid_priority": "정수 우선순위를 입력하세요", + "invalid_number": "유효한 숫자를 입력하세요", + "invalid_integer": "유효한 정수를 입력하세요", + "invalid_json": "유효한 JSON을 입력하세요", + "expected_array": "JSON 배열을 입력하세요", + "expected_object": "JSON 객체를 입력하세요", + "invalid_enum": "선언된 열거형 값 중 하나를 선택하세요" + }, + "plugin_store": { + "title": "플러그인 스토어", + "description": "플러그인 레지스트리를 탐색하고 현재 백엔드용 플러그인을 설치하거나 업데이트합니다.", + "description_show_more": "더 보기", + "description_show_less": "간략히 보기", + "source_name": "소스: {{source}}", + "cli_proxy_api_source": "CLIProxyAPI 소스", + "refresh": "새로 고침", + "retry": "재시도", + "load_failed": "플러그인 스토어를 불러오지 못했습니다", + "unsupported_backend": "현재 백엔드는 플러그인 스토어 API를 노출하지 않습니다. 플러그인 스토어 엔드포인트가 포함된 최신 백엔드 빌드를 사용한 후 서비스를 재시작하세요.", + "registry_failed": "플러그인 레지스트리에 연결하지 못했습니다", + "global_status": "전역 상태", + "global_enabled": "활성화됨", + "global_disabled": "비활성화됨", + "global_disabled_hint": "plugins.enabled가 false이므로 설치된 플러그인이 적용되지 않습니다.", + "plugins_dir": "플러그인 디렉터리", + "stat_available": "사용 가능", + "search_placeholder": "플러그인 ID, 이름, 작성자 또는 태그 검색...", + "search_label": "플러그인 스토어 검색", + "filter_label": "설치 상태별 필터", + "filter_all": "전체", + "filter_installed": "설치됨", + "filter_not_installed": "미설치", + "filter_updates": "업데이트 가능", + "badge_installed": "설치됨", + "badge_update": "업데이트 가능", + "badge_effective": "적용 중", + "version_arrow": "v{{from}} → v{{to}}", + "install_type": "설치 방식: {{type}}", + "platforms": "플랫폼: {{platforms}}", + "auth_required": "인증 필요", + "auth_configured": "인증 설정됨", + "auth_required_hint": "이 소스 또는 아티팩트 URL에서 설치하기 전에 plugins.store-auth를 설정하세요", + "source_errors_title": "일부 플러그인 소스를 불러오지 못했습니다", + "install": "설치", + "update": "업데이트", + "manage": "관리", + "install_confirm_title": "플러그인 설치", + "install_confirm_message": "플러그인 레지스트리에서 {{target}}을(를) 다운로드하여 로컬 플러그인 디렉터리에 설치하시겠습니까?", + "update_confirm_title": "플러그인 업데이트", + "update_confirm_message": "{{target}}을(를) 다운로드하여 설치하시겠습니까?", + "install_version_label": "버전", + "install_version_latest": "최신", + "install_version_latest_mode": "최신 안정 버전", + "install_version_latest_hint": "설치 시 백엔드에서 결정됩니다. 현재 표시된 버전: {{version}}.", + "install_version_release_mode": "릴리스 선택", + "install_version_release_hint": "GitHub Releases에서 설치 가능한 태그를 읽어옵니다.", + "install_version_manual_mode": "수동 릴리스 태그", + "install_version_manual_hint": "릴리스를 자동으로 불러올 수 없는 경우에만 사용하세요.", + "install_versions_loading": "GitHub Releases 불러오는 중...", + "install_versions_load_failed": "릴리스 버전을 불러오지 못했습니다", + "install_version_non_github": "이 플러그인 저장소는 GitHub 저장소가 아닙니다", + "install_versions_empty": "선택할 수 있는 릴리스가 없습니다.", + "install_versions_only_prerelease": "사전 릴리스 버전만 사용할 수 있습니다. 선택하려면 사전 릴리스를 표시하세요.", + "install_version_release_select": "릴리스 버전 선택", + "install_version_release_placeholder": "릴리스 버전을 선택하세요", + "install_version_prerelease_badge": "사전 릴리스", + "install_version_assets_count": "에셋 {{count}}개", + "install_version_show_prerelease": "사전 릴리스 버전 표시", + "install_version_manual_placeholder": "예: v0.1.4", + "install_version_manual_error": "릴리스 태그에는 영문자, 숫자, 마침표, 밑줄, 더하기 기호, 하이픈만 포함할 수 있으며 공백과 슬래시는 허용되지 않습니다.", + "install_version_current_selected": "{{version}}이(가) 이미 설치되어 있습니다. 다른 버전을 선택하세요.", + "install_version_releases_link": "GitHub Releases 보기", + "install_success": "플러그인을 설치했습니다", + "update_success": "플러그인을 업데이트했습니다", + "install_failed": "플러그인 설치에 실패했습니다", + "update_failed": "플러그인 업데이트에 실패했습니다", + "status_pending": "플러그인 파일이 업데이트되었지만 로컬 상태가 아직 새로 고쳐지지 않았습니다. 나중에 새로 고침하거나 백엔드 로그를 확인하세요.", + "registration_pending": "플러그인 파일이 업데이트되었지만 등록이 아직 보류 중입니다. 나중에 새로 고침하거나 백엔드 로그를 확인하세요.", + "restart_required_notice": "새 플러그인 버전을 로드하려면 서비스를 재시작하세요", + "restart_required_banner": "다음 플러그인의 새 버전을 적용하려면 서비스를 재시작하세요: {{plugins}}", + "open_repository": "저장소 열기", + "open_homepage": "홈페이지 열기", + "no_plugins": "레지스트리가 비어 있습니다", + "no_plugins_desc": "플러그인 레지스트리에서 반환된 플러그인이 없습니다.", + "no_matches": "일치하는 플러그인이 없습니다", + "no_matches_desc": "현재 검색 또는 필터와 일치하는 플러그인이 없습니다.", + "clear_filters": "필터 초기화", + "security_banner_title": "서드파티 플러그인은 전체 백엔드 접근 권한으로 실행됩니다", + "security_banner_text": "플러그인은 프록시 서비스 내부에서 코드를 실행하며 사용자의 자격 증명과 트래픽을 읽을 수 있습니다. 신뢰할 수 있는 플러그인만 설치하세요. 공식 router-for-me 조직에서 게시하지 않은 플러그인은 특히 주의해야 합니다.", + "badge_untrusted": "서드파티", + "gate_title": "{{name}} 설치", + "gate_title_update": "{{name}} 업데이트", + "gate_warning": "이 내용을 읽지 않으면 예상치 못한 유해한 상황이 발생할 수 있습니다.", + "gate_effect_runs_code": "이 플러그인은 프록시 백엔드 내부에서 인증되지 않은 서드파티 코드를 실행합니다. 시스템이 해당 동작을 격리하거나 감사할 수 없으며, 민감한 자격 증명, 네트워크 요청 및 응답 데이터에 접근할 수 있습니다.", + "gate_effect_no_review": "이 플러그인은 공식 router-for-me 조직에서 게시하거나 검토하지 않았습니다. 공식 조직은 이 플러그인의 안정성, 보안, 규정 준수 또는 향후 버전에서의 동작 변경에 대해 어떠한 명시적 또는 묵시적 보증도 하지 않습니다.", + "gate_effect_restart": "설치 시 로컬 플러그인 디렉터리가 변경되며 적용을 위해 서비스를 재시작해야 할 수 있습니다.", + "gate_untrusted_alert": "이 플러그인은 공식 router-for-me 조직의 플러그인이 아닙니다. 작성자와 소스를 완전히 신뢰하는 경우에만 계속 진행하세요.", + "gate_repository_label": "저장소", + "gate_source_label": "소스", + "gate_step1_action": "이 플러그인을 설치하겠습니다", + "gate_step2_action": "이러한 위험을 읽었으며 이해했습니다", + "gate_step3_prompt": "확인하려면 아래 입력란에 \"{{token}}\"을(를) 입력하세요", + "gate_step3_action": "이 플러그인 설치", + "gate_step3_hint": "설치를 활성화하려면 위에 표시된 식별자를 정확히 입력하세요." + }, + "plugin_resource": { + "page_count": "페이지 {{count}}개", + "load_failed": "플러그인 페이지를 불러오지 못했습니다", + "unavailable": "플러그인 페이지를 사용할 수 없습니다", + "not_found": "플러그인 페이지를 찾을 수 없습니다", + "not_found_desc": "이 플러그인 페이지는 현재 백엔드 플러그인 목록에 선언되어 있지 않습니다.", + "empty_src": "플러그인 페이지 URL이 비어 있습니다", + "empty_src_desc": "이 플러그인 메뉴는 포함 가능한 페이지 URL을 제공하지 않습니다." + }, + "system_info": { + "title": "관리 센터 정보", + "about_title": "CLI Proxy API 관리 센터", + "models_title": "사용 가능한 모델", + "models_desc": "/models 응답을 표시하며 저장된 API 키를 사용하여 자동으로 인증합니다.", + "models_loading": "사용 가능한 모델을 불러오는 중...", + "models_empty": "/models에서 반환된 모델이 없습니다", + "models_error": "모델 목록을 불러오지 못했습니다", + "models_count": "사용 가능한 모델 {{count}}개", + "version_check_button": "업데이트 확인", + "version_update_available": "새 버전을 사용할 수 있습니다: {{version}}", + "version_is_latest": "최신 버전을 사용하고 있습니다", + "version_check_error": "업데이트 확인에 실패했습니다", + "version_current_missing": "서버 버전을 확인할 수 없어 비교할 수 없습니다", + "version_unknown": "알 수 없음", + "quick_links_title": "빠른 링크", + "quick_links_desc": "도움말과 업데이트를 확인하려면 프로젝트 저장소 및 문서를 참조하세요.", + "link_main_repo": "메인 저장소", + "link_main_repo_desc": "CLI Proxy API 핵심 프로그램 소스 코드", + "link_webui_repo": "WebUI 저장소", + "link_webui_repo_desc": "관리 센터 프런트엔드 소스 코드", + "link_docs": "문서", + "link_docs_desc": "설정 튜토리얼 및 가이드", + "clear_login_title": "로컬 로그인 데이터", + "clear_login_desc": "로컬에 저장된 로그인 데이터를 지우고 로그아웃합니다.", + "clear_login_button": "로그인 데이터 지우기", + "clear_login_confirm": "로컬 로그인 데이터를 지우고 지금 로그아웃하시겠습니까?" + }, + "notification": { + "trusted_proxies_restart_required": "신뢰할 수 있는 프록시 설정이 저장되었습니다. 적용하려면 백엔드를 재시작하세요.", + "region_label": "알림", + "type_success": "성공", + "type_info": "정보", + "type_warning": "경고", + "type_error": "오류", + "request_log_updated": "요청 로깅 설정이 업데이트되었습니다", + "login_storage_cleared": "로컬 로그인 데이터가 삭제되었습니다", + "data_refreshed": "데이터를 성공적으로 새로 고쳤습니다", + "connection_required": "먼저 연결을 설정하세요", + "refresh_failed": "새로 고침 실패", + "update_failed": "업데이트 실패", + "add_failed": "추가 실패", + "delete_failed": "삭제 실패", + "upload_failed": "업로드 실패", + "download_failed": "다운로드 실패", + "login_failed": "로그인 실패", + "commercial_mode_restart_required": "상업 모드 설정이 변경되었습니다. 적용하려면 서비스를 재시작하세요", + "copy_failed": "복사 실패", + "link_copied": "링크가 클립보드에 복사되었습니다" + }, + "language": { + "switch": "언어", + "chinese": "中文", + "chinese_tw": "번체 중국어(대만)", + "english": "English", + "russian": "Русский", + "vietnamese": "Tiếng Việt", + "korean": "한국어" + }, + "theme": { + "switch": "테마", + "light": "양모 종이", + "white": "순백", + "dark": "다크", + "auto": "시스템 설정 따름" + }, + "sidebar": { + "toggle_expand": "사이드바 펼치기", + "toggle_collapse": "사이드바 접기", + "expand": "펼치기", + "collapse": "접기", + "subtitle": "CLI Proxy API 콘솔", + "auth_files_count": "인증 파일: {{count}}개" + }, + "footer": { + "api_version": "CLI Proxy API 버전", + "build_date": "빌드 시간", + "version": "관리 UI 버전" + }, + "providersPage": { + "behavior": { + "title": "공급자 전용 동작", + "alphaSearch": "Alpha Search 활성화", + "alphaSearchHint": "이 Codex 키가 Alpha Search를 처리하도록 허용합니다. 업스트림에서 이를 지원해야 합니다.", + "codexCloaking": "Codex 요청 위장", + "codexCloakingHint": "이 API 키에 대한 공식 Codex 식별 헤더를 재정의합니다. 기본값은 자격 증명 재정의를 제거하며, OAuth 전용 설정은 여기에 적용되지 않습니다.", + "useDefault": "백엔드 기본값 사용", + "cloakingEnabled": "위장 활성화", + "cloakingDisabled": "위장 비활성화", + "rebuildMidSystemMessage": "시스템 메시지 재구성", + "rebuildMidSystemMessageHint": "role이 system인 Claude 메시지를 최상위 system 필드로 이동합니다.", + "supportPromptCacheKey": "프롬프트 캐시 키 주입", + "supportPromptCacheKeyHint": "호환되는 요청에 대해 prompt_cache_key를 파생하고 주입합니다. 업스트림에서 이 필드를 지원하는 경우에만 활성화하세요." + }, + "modelOptions": { + "displayName": "표시 이름", + "maxContextLength": "컨텍스트 길이", + "contextHint": "음이 아닌 정수여야 합니다. 기본값을 사용하려면 비워 두세요.", + "forceMapping": "응답 모델 이름을 별칭으로 재작성", + "isCompat": "호환 모드", + "supportConfigurationUpdate": "설정 업데이트 허용", + "inputModalitiesText": "입력 모달리티", + "outputModalitiesText": "출력 모달리티", + "modalitiesHint": "쉼표 또는 공백으로 값을 구분하세요. 사용자 지정 모달리티 이름은 유지됩니다.", + "useMaxCompletionTokens": "max_completion_tokens 사용", + "thinkingMode": "사고 설정 재정의", + "useDefault": "기본값 사용", + "custom": "사용자 지정", + "thinkingHint": "기본값은 백엔드 동작을 상속하며, 빈 사용자 지정 재정의는 명시적인 {}입니다. 사고 예산과 추론 강도는 동시에 지정할 수 있습니다. 두 예산이 모두 0이거나 비어 있는 경우에만 숫자 범위가 지정되지 않습니다. 양수인 최솟값을 설정하는 경우 최댓값은 최솟값 이상이어야 합니다.", + "thinkingMin": "최소 사고 예산", + "thinkingMax": "최대 사고 예산", + "thinkingZeroAllowed": "0 예산 허용", + "thinkingDynamicAllowed": "동적 예산 허용", + "invalidContext": "컨텍스트 길이는 음이 아닌 안전한 정수여야 합니다.", + "invalidThinking": "사고 설정은 유효한 JSON 객체여야 합니다.", + "invalidBudget": "사고 예산은 음이 아닌 안전한 정수여야 합니다.", + "invalidRange": "최소 사고 예산은 최댓값을 초과할 수 없습니다. 비어 있는 경계는 0으로 간주됩니다.", + "removeModel": "모델 삭제", + "modelName": "모델 이름", + "modelAlias": "별칭(선택 사항)" + }, + "runtimePolicy": { + "title": "고급 런타임 정책", + "description": "상속은 상위 그룹 정책을 따르고, 그 후 백엔드 기본값을 사용합니다. 재정의는 이 항목에만 적용됩니다.", + "cooling": "쿨다운", + "inherit": "상속", + "coolingEnabled": "쿨다운 활성화", + "coolingDisabled": "쿨다운 비활성화", + "retry": "요청 재시도", + "retryHint": "비워 두면 그룹 설정을 상속합니다. 정수를 입력하세요. 0은 재시도를 비활성화하고, 음수는 그룹 정책 대신 전역 재시도 정책을 사용합니다.", + "errorsMode": "요청 오류 규칙", + "override": "재정의", + "errorsHint": "상속은 상위 정책을 따릅니다. 재정의는 전체 목록을 대체하며 빈 목록일 수도 있습니다. 모드를 전환해도 작성 중인 규칙 초안은 유지됩니다.", + "invalidRetry": "재시도 횟수는 안전한 정수이거나 상속을 위해 비어 있어야 합니다." + }, + "errorRules": { + "hint": "순서대로 첫 번째 일치하는 규칙을 적용합니다. 상태 코드가 같으면 어느 조건이라도 일치하면 적용됩니다.", + "empty": "규칙이 없습니다. 빈 목록을 저장할 수 있습니다.", + "rule": "규칙 {{number}}", + "status": "상태 코드", + "action": "동작", + "selectAction": "동작 선택", + "moveUp": "규칙 위로 이동", + "moveDown": "규칙 아래로 이동", + "removeRule": "규칙 삭제", + "matchType": "일치 유형", + "text": "텍스트 포함", + "regex": "정규식", + "matchValue": "조건", + "regexHint": "Go 정규식", + "removeMatch": "조건 삭제", + "addMatch": "조건 추가", + "addRule": "규칙 추가", + "invalidStatus": "상태 코드는 양의 안전한 정수여야 합니다.", + "invalidAction": "유효한 동작을 선택하세요.", + "invalidMatch": "일치 조건은 비워 둘 수 없습니다.", + "missingMatch": "일치 조건을 하나 이상 추가하세요.", + "actions": { + "stop": "중지", + "stop-and-cooldown": "중지 및 쿨다운", + "continue": "계속", + "continue-and-cooldown": "계속 및 쿨다운" + } + }, + "header": { + "title": "AI 공급자", + "activeResources": "활성 리소스 {{active}}/{{total}}개", + "providerFamilies": "공급자 제품군 {{count}}개", + "updatedAt": "{{time}} 업데이트됨" + }, + "actions": { + "refresh": "새로 고침", + "syncing": "동기화 중", + "new": "새로 만들기", + "edit": "편집", + "view": "보기", + "delete": "삭제", + "cancel": "취소", + "save": "저장", + "create": "생성", + "enable": "활성화", + "disable": "비활성화" + }, + "categories": { + "title": "공급자", + "quickFill": "빠른 입력", + "activeCount": "활성 {{active}}/{{total}}" + }, + "providerNames": { + "meta": "Muse (Meta)", + "gemini": "Gemini", + "interactions": "Interactions API", + "codex": "Codex", + "xai": "xAI", + "claude": "Claude", + "vertex": "Vertex", + "openaiCompatibility": "OpenAI 호환", + "apikeyFun": "APIKEY.FUN", + "fennoAI": "FennoAI", + "qiniuCloud": "Qiniu Cloud", + "kimi": "Kimi" + }, + "table": { + "key": "키", + "baseUrl": "기본 URL", + "prefix": "접두사", + "models": "모델/헤더", + "status": "상태", + "actions": "작업", + "metrics": { + "models": "모델", + "keys": "키", + "headers": "헤더" + }, + "websocketsTag": "WebSockets", + "cloakTag": "Cloak", + "cliProfileTag": "CLI 프로필", + "empty": "아직 리소스가 없습니다. \"새로 만들기\"를 클릭하여 추가하세요.", + "filterPlaceholder": "키, URL, 접두사 검색…", + "description": "{{route}}의 리소스를 관리합니다." + }, + "sponsor": { + "protocolSummary": "Anthropic / OpenAI / Gemini / Codex API (Responses)", + "detailHint": "{{provider}} 공급자는 프로토콜별로 일치하는 API 키 설정에 저장되며, 이 화면에서 통합 관리합니다.", + "registerLink": "여기서 등록", + "registerNow": "지금 등록", + "kimiPromo": "신규 사용자는 첫 충전 성공 시 충전 금액의 10%에 해당하는 API 크레딧(최대 ¥1000)을 받을 수 있습니다. 혜택은 9월 30일에 종료됩니다.", + "dashboardLink": "대시보드", + "emptyRegisterHint": "아직 설정이 없습니다.", + "apiKeyHint": "이 키는 선택한 그룹/프로토콜 설정에만 저장됩니다.", + "usageCheck": "사용량 확인", + "usageChecking": "확인 중", + "usageRemaining": "남은 사용량: {{amount}} {{unit}}", + "usageBreakdown": "사용 {{used}} / 한도 {{limit}}", + "usageStatus": "상태: {{status}}", + "usageInvalid": "유효하지 않은 키", + "usageEmpty": "엔드포인트에서 사용량 데이터를 반환하지 않았습니다.", + "usageApiKeyRequired": "API 키가 필요합니다.", + "aggregationConflict": "이 그룹화된 공급자에는 여러 백엔드 설정 또는 OpenAI 키가 포함되어 있습니다. 데이터 손실을 방지하려면 소스 설정에서 편집하세요.", + "partialMutationWarning": "하나 이상의 프로토콜이 업데이트된 후 작업이 실패했을 수 있습니다. 최신 설정을 다시 불러왔으니 다시 시도하기 전에 검토하세요.", + "groupedKeysTitle": "그룹 키", + "groupedKeysHint": "플랫폼 키 생성 시 특정 그룹에 바인딩될 수 있습니다. 여기의 각 그룹 키는 하나의 프로토콜만 관리하며, 모델 검색은 해당 프로토콜만 사용합니다.", + "groupedKey": "그룹 키 #{{index}}", + "addGroupedKey": "그룹 키 추가", + "removeGroupedKey": "그룹 키 삭제", + "protocol": "그룹/프로토콜", + "protocolHint": "이 키에 해당하는 그룹/프로토콜을 선택하세요.", + "protocolEndpoint": "현재 프로토콜 엔드포인트", + "urlMode": "{{provider}} URL", + "urlHint": "모든 URL은 동일한 API 규칙을 사용합니다. 저장 시 현재 그룹화된 프로토콜의 엔드포인트만 기록됩니다.", + "urlOptions": { + "standard": "표준 URL", + "direct": "직접 연결 URL", + "domestic": "중국 본토 경로", + "overseas": "해외 경로", + "mainlandChina": "중국 본토 (권장)", + "global": "글로벌" + }, + "urlOptionDescriptions": { + "domestic": "중국 본토의 사용자 및 워크로드용입니다. 본토 네트워크에서 일반적으로 대기 시간이 더 짧습니다.", + "overseas": "해외 배포, 국경 간 액세스 또는 해외 모델이 필요한 워크로드용입니다.", + "mainlandChinaRecommended": "중국 본토 네트워크의 사용자 및 워크로드에 권장됩니다.", + "global": "기타 모든 지역의 사용자 및 워크로드용입니다." + }, + "modelsTitle": "프로토콜 모델 설정", + "modelsHint": "Codex API, Anthropic, Gemini 및 OpenAI 호환 경로에 대한 모델 허용 목록 또는 별칭을 개별적으로 설정하세요.", + "protocolModels": { + "codex": "Codex API 모델", + "anthropic": "Anthropic 모델", + "gemini": "Gemini 모델", + "openai": "OpenAI 호환 모델" + }, + "protocolModelHints": { + "codex": "Codex API 설정의 models에 저장됩니다. /v1/models에서 가져온 후 필요한 경우 별칭을 설정하세요.", + "anthropic": "Anthropic 설정의 models에 저장됩니다. /v1/models에서 가져온 후 필요한 경우 별칭을 설정하세요.", + "gemini": "Gemini 설정의 models에 저장됩니다. /v1beta/models에서 가져온 후 필요한 경우 별칭을 설정하세요.", + "openai": "OpenAI 호환 설정의 models에 저장됩니다. /models에서 가져온 후 필요한 경우 별칭을 설정하세요." + }, + "validation": { + "keyRequired": "모든 그룹 키에 API 키를 입력하세요.", + "protocolDuplicate": "각 프로토콜에는 그룹 키를 하나만 지정할 수 있습니다." + }, + "openaiEntries": "OpenAI 호환 키", + "codexEntries": "Codex API 키", + "anthropicEntries": "Anthropic 키", + "geminiEntries": "Gemini 키", + "protocols": { + "anthropic": "Anthropic", + "openai": "OpenAI 호환", + "gemini": "Gemini", + "codexResponses": "Codex API (Responses)" + } + }, + "status": { + "active": "활성", + "disabled": "비활성화됨", + "notSet": "설정되지 않음", + "none": "없음", + "notConfigured": "구성되지 않음", + "defaultSuffix": "(기본값)" + }, + "detail": { + "title": "상세 정보", + "metadataTitle": "메타데이터", + "fields": { + "identifier": "식별자", + "baseUrl": "기본 URL", + "proxyUrl": "프록시 URL", + "prefix": "접두사", + "models": "모델", + "headers": "헤더", + "authIndex": "Auth Index", + "excludedModels": "제외 모델", + "apiKeyEntries": "API 키 항목" + } + }, + "form": { + "createEyebrow": "새로 만들기", + "editEyebrow": "편집", + "name": "이름", + "apiKey": "API 키", + "apiKeyCreatePlaceholder": "API 키를 입력하세요", + "apiKeyEditPlaceholder": "변경하지 않으려면 비워 두세요", + "baseUrl": "기본 URL", + "baseUrlRequiredHint": "이 공급자에는 필수 항목입니다.", + "proxyUrl": "프록시 URL", + "prefix": "접두사", + "priority": "우선순위", + "weight": "스케줄링 가중치", + "weightHint": "기본값 1 · ≤ 0인 경우 제외 · 최대 1,000,000", + "disabled": "이 항목 비활성화", + "disabledHint": "비활성화된 항목은 게이트웨이에서 사용되지 않습니다.", + "websockets": "WebSockets 활성화", + "testModel": "테스트 모델", + "testModelHint": "연결 테스트용으로만 사용되며 저장되지 않습니다.", + "testModelAutoWith": "자동 · {{name}}", + "testModelAutoEmpty": "자동 (아직 추가된 모델 없음)", + "testModelCustom": "{{name}} (사용자 정의)", + "modelsSection": "사용자 정의 모델", + "addModel": "모델 추가", + "headersSection": "요청 헤더", + "addHeader": "헤더 추가", + "excludedSection": "제외 모델", + "excludedDisabledNote": "“*”는 전체 공급자가 비활성화됨을 의미합니다. 대신 위의 비활성화 스위치를 사용하세요.", + "cloakSection": "Cloak 설정", + "cloakMode": "모드", + "cloakStrict": "엄격 모드", + "cloakSensitiveWords": "민감한 단어 (한 줄에 하나씩)", + "apiKeyEntriesSection": "API 키 항목", + "apiKeyEntry": "키 #{{index}}", + "addApiKeyEntry": "키 항목 추가", + "showApiKey": "API 키 표시", + "hideApiKey": "API 키 숨기기", + "disableCooling": "쿨다운 비활성화", + "disableCoolingHint": "이 자격 증명 또는 공급자에 대해서만 실패 쿨다운 대기 시간을 비활성화합니다.", + "modelImage": "이미지 엔드포인트 허용", + "modelImageHint": "이 모델을 /v1/images/generations 및 /v1/images/edits에서 허용합니다.", + "showAllEntries": "전체 표시 ({{count}})", + "showFewerEntries": "간략히 표시", + "proxyBadge": "프록시", + "modelBadgeImage": "이미지", + "modelBadgeThinking": "사고", + "thinkingConfig": "사고 기능", + "thinkingExistingHint": "추론 강도 단계를 변경해도 예산 및 수정되지 않은 기타 설정은 유지됩니다.", + "thinkingLevels": { + "none": "사고 비활성화", + "minimal": "최소", + "low": "낮음", + "medium": "중간", + "high": "높음", + "xhigh": "매우 높음", + "max": "최대", + "auto": "자동" + }, + "cloakCacheUserId": "user_id 캐시", + "cloakCacheUserIdHint": "API 키별로 Claude cloak user_id를 재사용합니다.", + "fingerprintProfile": "요청 지문", + "fingerprintProfileDefault": "기본값(호출자 제어)", + "fingerprintProfileClaudeCodeCli": "Claude Code CLI", + "fingerprintProfileHint": "기본적으로 호출자의 프롬프트와 헤더를 유지하거나, Claude Code CLI 요청 지문을 사용하도록 선택합니다.", + "validation": { + "nameRequired": "이름은 필수입니다.", + "apiKeyRequired": "API 키를 하나 이상 입력해야 합니다.", + "baseUrlRequired": "기본 URL은 필수입니다.", + "weightInteger": "스케줄링 가중치는 정수여야 합니다.", + "weightMax": "스케줄링 가중치는 {{max}}을(를) 초과할 수 없습니다." + } + }, + "delete": { + "title": "리소스 삭제", + "confirm": "{{name}}을(를) 삭제하시겠습니까? 이 작업은 취소할 수 없습니다." + }, + "toast": { + "created": "생성됨", + "updated": "업데이트됨", + "deleted": "삭제됨", + "enabled": "활성화됨", + "disabled": "비활성화됨", + "toggleFailed": "상태 업데이트에 실패했습니다." + }, + "unsavedChanges": { + "title": "저장되지 않은 변경 사항을 취소하시겠습니까?", + "message": "이 양식에 저장되지 않은 수정 사항이 있습니다. 닫으면 변경 사항이 취소됩니다.", + "discard": "변경 사항 취소", + "keepEditing": "계속 편집" + }, + "connectivity": { + "test": "테스트", + "testAll": "모두 테스트", + "success": "연결 가능", + "baseUrlRequired": "기본 URL은 필수입니다.", + "endpointInvalid": "엔드포인트 URL이 올바르지 않습니다.", + "apiKeyRequired": "API 키는 필수입니다.", + "modelRequired": "테스트 모델은 필수입니다.", + "timeout": "{{seconds}}초 후 시간 초과되었습니다.", + "requestFailed": "요청에 실패했습니다." + }, + "discovery": { + "openButton": "엔드포인트에서 가져오기", + "searchPlaceholder": "모델 검색", + "reload": "다시 로드", + "loading": "모델을 로드하는 중…", + "empty": "엔드포인트에서 반환된 모델이 없습니다.", + "notLoaded": "모델을 가져오려면 다시 로드를 클릭하세요.", + "selectAll": "모두 선택", + "clearAll": "선택 해제", + "selectedCount": "{{selected}} / {{total}}", + "alreadyAdded": "이미 추가됨", + "close": "닫기", + "apply": "적용 ({{count}})" + }, + "toolbar": { + "sortBy": "정렬 기준", + "sort": { + "name": "이름", + "priority": "우선순위", + "recentSuccess": "최근 성공", + "directionAsc": "오름차순", + "directionDesc": "내림차순" + }, + "filter": { + "allModels": "모든 모델", + "selectedModels": "{{selected}}/{{total}}개 모델", + "selectAll": "모두 선택", + "clear": "선택 해제", + "empty": "아직 설정된 모델이 없습니다." + } + }, + "modelCatalog": { + "notLoaded": "로드되지 않음" + } + }, + "claude_reset": { + "expiry_title": "수동 초기화 만료 시각 ({{timezone}})", + "grant_number": "초기화 권한 {{index}}", + "expiry_unknown": "만료 시각 알 수 없음", + "retry_confirm": "“{{name}}”의 상태를 알 수 없는 초기화를 원래 요청 ID로 재시도하시겠습니까? 이미 초기화가 소진되었을 수 있습니다. 10분 이내에 재시도하세요. 페이지를 새로 고치거나 다른 탭에서 새 요청을 시작하지 마세요.", + "remaining": "남은 초기화 횟수", + "title": "적립된 초기화", + "scope": "제한된 초기화 권한을 사용하여 조건에 맞는 Claude 사용량 한도를 초기화합니다. 초기화를 사용하려는 경우에만 확인하세요. 복구는 이 탭/세션으로 제한되므로, 결과를 알 수 없는 동안에는 새로 고침을 하거나 다른 탭을 사용하지 마세요.", + "loading": "로드 중…", + "read_error": "초기화 권한 정보를 불러오지 못했습니다. 초기화 요청은 전송되지 않았습니다.", + "blocked": "초기화 요청을 전송하지 않았습니다: 자격, 계정 식별 정보 또는 세션을 확인할 수 없습니다. 새로 고친 후 다시 확인하세요.", + "unknown": "결과를 알 수 없습니다. 초기화가 이미 사용되었을 수 있습니다. 동일한 요청 ID를 사용하여 10분 이내에 재시도하세요. 다른 곳에서 새 요청을 시작하지 마세요.", + "expired": "재시도 가능 시간이 만료되었습니다. 이 세션에서는 추가 요청이 차단됩니다. 추가 작업을 진행하기 전에 Claude 계정을 확인하세요.", + "retry": "동일한 요청 재시도", + "empty": "적립된 초기화 권한이 없습니다.", + "count": "남은 초기화 {{left}} / {{total}}회", + "ends": "만료: {{date}}", + "use": "한도 초기화", + "confirm": "초기화 확인", + "confirm_text": "초기화를 1회 사용하여 “{{name}}”의 대상 사용량 제한을 초기화하시겠습니까? 제한된 초기화 권한이 사용됩니다.", + "reset": "사용량 제한이 초기화되었습니다.", + "already_used": "이 권한은 이미 사용되었습니다.", + "not_limited": "초기화되지 않음: 계정이 현재 제한 상태가 아닙니다.", + "cooldown": "초기화되지 않음: 쿨다운이 진행 중입니다.", + "ineligible": "이 계정은 자격 요건을 충족하지 않습니다.", + "unavailable": "현재 초기화를 사용할 수 없습니다.", + "rate_limited": "요청 속도가 제한되었습니다.", + "auth_error": "인증이 거부되었습니다." + } +} diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index b8a0c6415b6..b044cf04980 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -1806,7 +1806,8 @@ "chinese_tw": "繁體中文(台灣)", "english": "English", "russian": "Русский", - "vietnamese": "Tiếng Việt" + "vietnamese": "Tiếng Việt", + "korean": "한국어" }, "theme": { "switch": "Тема", diff --git a/src/i18n/locales/vi.json b/src/i18n/locales/vi.json index 5e4ef1caece..f8eb0cf4e9d 100644 --- a/src/i18n/locales/vi.json +++ b/src/i18n/locales/vi.json @@ -1768,7 +1768,8 @@ "chinese_tw": "繁體中文(台灣)", "english": "English", "russian": "Русский", - "vietnamese": "Tiếng Việt" + "vietnamese": "Tiếng Việt", + "korean": "한국어" }, "theme": { "switch": "Giao diện", diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index 2bd2d9d3edb..a3e6c4fcd8a 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -1811,7 +1811,8 @@ "chinese_tw": "繁體中文(台灣)", "english": "English", "russian": "Русский", - "vietnamese": "Tiếng Việt" + "vietnamese": "Tiếng Việt", + "korean": "한국어" }, "theme": { "switch": "主题", diff --git a/src/i18n/locales/zh-TW.json b/src/i18n/locales/zh-TW.json index 2febf9305ca..a5415bb8df1 100644 --- a/src/i18n/locales/zh-TW.json +++ b/src/i18n/locales/zh-TW.json @@ -1837,7 +1837,8 @@ "chinese_tw": "繁體中文(台灣)", "english": "英文", "russian": "俄文", - "vietnamese": "Tiếng Việt" + "vietnamese": "Tiếng Việt", + "korean": "한국어" }, "theme": { "switch": "主題", diff --git a/src/types/common.ts b/src/types/common.ts index 38213a2cc85..44af55a4dd1 100644 --- a/src/types/common.ts +++ b/src/types/common.ts @@ -4,7 +4,7 @@ export type Theme = 'light' | 'white' | 'dark' | 'auto'; -export type Language = 'zh-CN' | 'zh-TW' | 'en' | 'ru' | 'vi'; +export type Language = 'zh-CN' | 'zh-TW' | 'en' | 'ru' | 'vi' | 'ko'; export type NotificationType = 'info' | 'success' | 'warning' | 'error'; diff --git a/src/utils/constants.ts b/src/utils/constants.ts index 3636ff9f49a..df715fda42c 100644 --- a/src/utils/constants.ts +++ b/src/utils/constants.ts @@ -34,13 +34,21 @@ export const STORAGE_KEY_THEME = 'cli-proxy-theme'; export const STORAGE_KEY_LANGUAGE = 'cli-proxy-language'; // 语言配置 -export const LANGUAGE_ORDER = defineLanguageOrder(['zh-CN', 'zh-TW', 'en', 'ru', 'vi'] as const); +export const LANGUAGE_ORDER = defineLanguageOrder([ + 'zh-CN', + 'zh-TW', + 'en', + 'ru', + 'vi', + 'ko', +] as const); export const LANGUAGE_LABEL_KEYS: Record = { 'zh-CN': 'language.chinese', 'zh-TW': 'language.chinese_tw', en: 'language.english', ru: 'language.russian', vi: 'language.vietnamese', + ko: 'language.korean', }; export const SUPPORTED_LANGUAGES = LANGUAGE_ORDER; diff --git a/src/utils/language.ts b/src/utils/language.ts index 7de8b52ed59..83d56ae4e4f 100644 --- a/src/utils/language.ts +++ b/src/utils/language.ts @@ -46,6 +46,7 @@ const getBrowserLanguage = (): Language => { if (lower.startsWith('zh')) return 'zh-CN'; if (lower.startsWith('ru')) return 'ru'; if (lower.startsWith('vi')) return 'vi'; + if (lower.startsWith('ko')) return 'ko'; return 'en'; }; diff --git a/tests/koreanLocale.test.ts b/tests/koreanLocale.test.ts new file mode 100644 index 00000000000..f4830807d77 --- /dev/null +++ b/tests/koreanLocale.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, test } from 'bun:test'; + +const flattenLeaves = (value: unknown, prefix = ''): Record => { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return prefix ? { [prefix]: String(value ?? '') } : {}; + } + + return Object.entries(value).reduce>((leaves, [key, child]) => { + const path = prefix ? `${prefix}.${key}` : key; + return { ...leaves, ...flattenLeaves(child, path) }; + }, {}); +}; + +const interpolationTokens = (value: string): string[] => value.match(/\{\{[^}]+\}\}/g) ?? []; + +describe('Korean locale', () => { + test('covers every current English key with matching interpolation tokens', async () => { + const english = flattenLeaves(await Bun.file('src/i18n/locales/en.json').json()); + const korean = flattenLeaves(await Bun.file('src/i18n/locales/ko.json').json()); + const missing = Object.keys(english).filter((key) => !(key in korean)); + const mismatches = Object.keys(english) + .filter((key) => key in korean) + .filter( + (key) => + interpolationTokens(english[key]).sort().join('|') !== + interpolationTokens(korean[key]).sort().join('|') + ); + + expect(missing).toEqual([]); + expect(mismatches).toEqual([]); + }); +}); From 346eaa2367d17e83b3361f5381953ba6ab99d085 Mon Sep 17 00:00:00 2001 From: Supra4E8C Date: Thu, 8 Oct 2026 16:54:38 +0800 Subject: [PATCH 101/142] feat(i18n): add cloud session credits label to Vietnamese locale --- src/i18n/locales/vi.json | 1 + 1 file changed, 1 insertion(+) diff --git a/src/i18n/locales/vi.json b/src/i18n/locales/vi.json index f8eb0cf4e9d..d62f7bae757 100644 --- a/src/i18n/locales/vi.json +++ b/src/i18n/locales/vi.json @@ -490,6 +490,7 @@ "seven_day_cowork": "Cowork 7 ngày", "iguana_necktie": "Iguana Necktie", "seven_day_fable": "Fable 5 · 7 ngày", + "cloud_session_credits": "Tín dụng phiên đám mây", "extra_usage_label": "Sử dụng thêm", "plan_label": "Gói", "plan_unknown": "Không rõ", From 5aa1ad64a6494e3741e7d7ffec737107400a62b4 Mon Sep 17 00:00:00 2001 From: Supra4E8C Date: Thu, 8 Oct 2026 16:55:25 +0800 Subject: [PATCH 102/142] feat(i18n): add usage breakdown label for shared quota in Korean locale --- src/i18n/locales/ko.json | 1 + 1 file changed, 1 insertion(+) diff --git a/src/i18n/locales/ko.json b/src/i18n/locales/ko.json index 400e4d22433..813734ed452 100644 --- a/src/i18n/locales/ko.json +++ b/src/i18n/locales/ko.json @@ -626,6 +626,7 @@ "usage_unavailable": "xAI에서 사용량 정보를 제공하지 않음", "reset_at": "{{time}} 초기화", "product_usage": "{{product}} 사용량", + "usage_breakdown": "사용량 상세 내역 (공유 할당량)", "plan_label": "플랜", "resets_label": "초기화", "prepaid": "선불", From 54946fa3dfa29c6ca7312ac141a92cdd5e413771 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Thu, 8 Oct 2026 20:04:31 +0800 Subject: [PATCH 103/142] docs(readme): remove full QQ group in README_CN --- README_CN.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_CN.md b/README_CN.md index 272368ad94e..94ca944cdd6 100644 --- a/README_CN.md +++ b/README_CN.md @@ -330,7 +330,7 @@ CLIProxyAPI 的 Rust 移植版,读取相同的 `config.yaml` 和认证文件 ## 写给所有中国网友的 -QQ 群:188637136(满)、1081218164 +QQ 群:1081218164 或 From 6331b38bba2cb716480fe78b6638b87db45e521d Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Thu, 8 Oct 2026 21:32:26 +0800 Subject: [PATCH 104/142] feat(openai): support response.interrupt in responses websocket handling - Intercept and process `response.interrupt` control frames immediately on the downstream websocket reader - Forward interrupts to active upstream Codex websocket sessions without starting a new turn or rewriting payload fields - Support canceling in-flight HTTP turns via local interrupt handling - Allow session-staged Home credentials to authorize interrupts Closes: #6456 --- .../executor/codex_websockets_executor.go | 59 +++ .../codex_websockets_interrupt_test.go | 74 +++ .../openai/openai_responses_interrupt_test.go | 481 ++++++++++++++++++ .../openai/openai_responses_websocket.go | 42 +- .../openai_responses_websocket_forward.go | 44 +- .../openai_responses_websocket_input.go | 128 ++++- sdk/cliproxy/executor/websocket_input.go | 8 +- 7 files changed, 812 insertions(+), 24 deletions(-) create mode 100644 internal/runtime/executor/codex_websockets_interrupt_test.go create mode 100644 sdk/api/handlers/openai/openai_responses_interrupt_test.go diff --git a/internal/runtime/executor/codex_websockets_executor.go b/internal/runtime/executor/codex_websockets_executor.go index e6ae2cc5956..c63b5c30acc 100644 --- a/internal/runtime/executor/codex_websockets_executor.go +++ b/internal/runtime/executor/codex_websockets_executor.go @@ -12,6 +12,7 @@ import ( "github.com/router-for-me/CLIProxyAPI/v8/internal/config" cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + log "github.com/sirupsen/logrus" ) // CodexWebsocketsExecutor executes Codex Responses requests using a WebSocket transport. @@ -154,3 +155,61 @@ func codexWebsocketsEnabled(auth *cliproxyauth.Auth) bool { func (e *CodexAutoExecutor) SupportsApplyPatch() bool { return e != nil && e.httpExec != nil && e.wsExec != nil && e.httpExec.SupportsApplyPatch() && e.wsExec.SupportsApplyPatch() } + +// InterruptExecutionSession forwards a response.interrupt control frame on the +// current upstream socket. It does not dial, replay, or select another credential. +func (e *CodexAutoExecutor) InterruptExecutionSession(ctx context.Context, sessionID string, payload []byte) error { + if e == nil || e.wsExec == nil { + return cliproxyexecutor.ErrNoActiveUpstreamWebsocket + } + return e.wsExec.InterruptExecutionSession(ctx, sessionID, payload) +} + +// InterruptExecutionSession writes the original interrupt payload to the session +// socket captured for this execution. Payload rules and response.create defaults +// must not rewrite response_id, mode, or extension fields. +func (e *CodexWebsocketsExecutor) InterruptExecutionSession(ctx context.Context, sessionID string, payload []byte) error { + if e == nil { + return cliproxyexecutor.ErrNoActiveUpstreamWebsocket + } + if ctx != nil { + if errCtx := ctx.Err(); errCtx != nil { + return errCtx + } + } + sessionID = strings.TrimSpace(sessionID) + if sessionID == "" { + return cliproxyexecutor.ErrNoActiveUpstreamWebsocket + } + store := e.store + if store == nil { + store = globalCodexWebsocketSessionStore + } + store.mu.Lock() + sess := store.sessions[sessionID] + store.mu.Unlock() + if sess == nil { + return cliproxyexecutor.ErrNoActiveUpstreamWebsocket + } + sess.connMu.Lock() + conn := sess.conn + authID := sess.authID + wsURL := sess.wsURL + sess.connMu.Unlock() + if conn == nil { + return cliproxyexecutor.ErrNoActiveUpstreamWebsocket + } + // A retained socket from an earlier turn is not the current upstream. + // HTTP turns must fall through to local cancellation instead. + if readCh, _ := sess.activeForConn(conn); readCh == nil { + return cliproxyexecutor.ErrNoActiveUpstreamWebsocket + } + if !cliproxyexecutor.WebsocketAuthEnabled(ctx, authID) { + return fmt.Errorf("websocket credential is no longer enabled") + } + if errWrite := writeCodexWebsocketMessage(sess, conn, payload); errWrite != nil { + return errWrite + } + log.Infof("codex websockets: request forwarded session=%s auth=%s url=%s event=response.interrupt", sessionID, authID, wsURL) + return nil +} diff --git a/internal/runtime/executor/codex_websockets_interrupt_test.go b/internal/runtime/executor/codex_websockets_interrupt_test.go new file mode 100644 index 00000000000..1235d638619 --- /dev/null +++ b/internal/runtime/executor/codex_websockets_interrupt_test.go @@ -0,0 +1,74 @@ +package executor + +import ( + "bytes" + "context" + "errors" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/gorilla/websocket" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" +) + +func TestInterruptExecutionSessionRequiresActiveRead(t *testing.T) { + received := make(chan []byte, 1) + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, errUpgrade := (&websocket.Upgrader{}).Upgrade(w, r, nil) + if errUpgrade != nil { + t.Errorf("upgrade: %v", errUpgrade) + return + } + defer func() { _ = conn.Close() }() + _ = conn.SetReadDeadline(time.Now().Add(2 * time.Second)) + _, payload, errRead := conn.ReadMessage() + if errRead != nil { + return + } + received <- payload + })) + defer upstream.Close() + + client, _, errDial := websocket.DefaultDialer.Dial("ws"+upstream.URL[len("http"):], nil) + if errDial != nil { + t.Fatal(errDial) + } + defer func() { _ = client.Close() }() + + const sessionID = "interrupt-requires-active-read" + executor := NewCodexWebsocketsExecutor(nil) + defer executor.CloseExecutionSession(sessionID) + sess := executor.getOrCreateSession(sessionID) + sess.connMu.Lock() + sess.conn = client + sess.authID = "auth" + sess.wsURL = upstream.URL + sess.connMu.Unlock() + + interrupt := []byte(`{"type":"response.interrupt","response_id":"r1","mode":"discard_partial_items"}`) + errIdle := executor.InterruptExecutionSession(context.Background(), sessionID, interrupt) + if !errors.Is(errIdle, cliproxyexecutor.ErrNoActiveUpstreamWebsocket) { + t.Fatalf("idle socket error = %v, want ErrNoActiveUpstreamWebsocket", errIdle) + } + select { + case payload := <-received: + t.Fatalf("idle socket was written: %s", payload) + case <-time.After(200 * time.Millisecond): + } + + readCh := sess.activate(client) + defer sess.clearActive(client, readCh) + if errActive := executor.InterruptExecutionSession(context.Background(), sessionID, interrupt); errActive != nil { + t.Fatal(errActive) + } + select { + case payload := <-received: + if !bytes.Equal(payload, interrupt) { + t.Fatalf("active interrupt = %s", payload) + } + case <-time.After(2 * time.Second): + t.Fatal("active socket did not receive the interrupt") + } +} diff --git a/sdk/api/handlers/openai/openai_responses_interrupt_test.go b/sdk/api/handlers/openai/openai_responses_interrupt_test.go new file mode 100644 index 00000000000..f53fd269013 --- /dev/null +++ b/sdk/api/handlers/openai/openai_responses_interrupt_test.go @@ -0,0 +1,481 @@ +package openai + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "maps" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/gorilla/websocket" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + runtimeexecutor "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers" + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executionregistry" + coreexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + "github.com/tidwall/gjson" +) + +// TestResponsesInterruptInFlight verifies that a Codex response.interrupt sent while +// generation is running is forwarded unchanged to the current upstream socket, and that +// the same socket accepts the next response.create. Idle, malformed, and disabled-auth +// interrupts must fail locally without opening or writing that socket. +func TestResponsesInterruptInFlight(t *testing.T) { + for _, steering := range []bool{false, true} { + t.Run(fmt.Sprintf("steering_%t", steering), func(t *testing.T) { + interrupt := []byte(`{"type":"response.interrupt","response_id":"r1","mode":"discard_partial_items","extension":"keep"}`) + var connections atomic.Int32 + upstreamDone := make(chan struct{}) + var upstreamDoneOnce sync.Once + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + connections.Add(1) + defer upstreamDoneOnce.Do(func() { close(upstreamDone) }) + c, errUpgrade := (&websocket.Upgrader{}).Upgrade(w, r, nil) + if errUpgrade != nil { + t.Errorf("upgrade upstream: %v", errUpgrade) + return + } + defer func() { _ = c.Close() }() + _ = c.SetReadDeadline(time.Now().Add(5 * time.Second)) + read := func() []byte { + _, payload, errRead := c.ReadMessage() + if errRead != nil { + t.Errorf("upstream read: %v", errRead) + } + return payload + } + write := func(payload string) { + if errWrite := c.WriteMessage(websocket.TextMessage, []byte(payload)); errWrite != nil { + t.Errorf("upstream write: %v", errWrite) + } + } + if payload := read(); gjson.GetBytes(payload, "type").String() != "response.create" { + t.Errorf("expected response.create, got %s", payload) + return + } + write(`{"type":"response.created","response":{"id":"r1"}}`) + // Hold completion until the in-flight interrupt arrives unchanged. + if payload := read(); !bytes.Equal(payload, interrupt) { + t.Errorf("interrupt changed: %s", payload) + return + } + write(`{"type":"response.incomplete","response":{"id":"r1","status":"incomplete","incomplete_details":{"reason":"interrupted"},"usage":{"output_tokens":7},"output":[]}}`) + if payload := read(); gjson.GetBytes(payload, "type").String() != "response.create" { + t.Errorf("expected follow-up response.create, got %s", payload) + return + } + write(`{"type":"response.created","response":{"id":"r2"}}`) + write(`{"type":"response.completed","response":{"id":"r2","status":"completed","output":[]}}`) + _, _, _ = c.ReadMessage() + })) + defer upstream.Close() + + cfg := &config.Config{} + cfg.Codex.ResponseSteering = steering + cfg.CodexResponseSteering = steering + manager := coreauth.NewManager(nil, nil, nil) + manager.SetConfig(cfg) + manager.RegisterExecutor(runtimeexecutor.NewCodexAutoExecutor(cfg)) + authID := fmt.Sprintf("interrupt-%t", steering) + model := "interrupt-model-" + authID + _, errRegister := manager.Register(context.Background(), &coreauth.Auth{ + ID: authID, + Provider: "codex", + Status: coreauth.StatusActive, + Attributes: map[string]string{ + "api_key": "test-key", + "base_url": upstream.URL, + "websockets": "true", + }, + }) + if errRegister != nil { + t.Fatal(errRegister) + } + registry.GetGlobalRegistry().RegisterClient(authID, "codex", []*registry.ModelInfo{{ID: model}}) + defer registry.GetGlobalRegistry().UnregisterClient(authID) + + handler := NewOpenAIResponsesAPIHandler(handlers.NewBaseAPIHandlers(&cfg.SDKConfig, manager)) + router := gin.New() + router.GET("/v1/responses", handler.ResponsesWebsocket) + downstream := httptest.NewServer(router) + defer downstream.Close() + + client, _, errDial := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(downstream.URL, "http")+"/v1/responses", nil) + if errDial != nil { + t.Fatal(errDial) + } + defer func() { _ = client.Close() }() + _ = client.SetReadDeadline(time.Now().Add(8 * time.Second)) + send := func(payload []byte) { + t.Helper() + if errSend := client.WriteMessage(websocket.TextMessage, payload); errSend != nil { + t.Fatal(errSend) + } + } + expect := func(event string) { + t.Helper() + _, payload, errRead := client.ReadMessage() + if errRead != nil { + t.Fatal(errRead) + } + if got := gjson.GetBytes(payload, "type").String(); got != event { + t.Fatalf("expected %s, got %s", event, payload) + } + } + + send([]byte(`{"type":"response.interrupt"}`)) + expect("error") + send(interrupt) + expect("error") + if connections.Load() != 0 { + t.Fatal("idle interrupt opened an upstream connection") + } + + send([]byte(fmt.Sprintf(`{"type":"response.create","model":%q,"input":[]}`, model))) + expect("response.created") + send([]byte(`{"type":"response.interrupt","response_id":42}`)) + expect("error") + auth, _ := manager.GetByID(authID) + auth.Disabled = true + if _, errUpdate := manager.Update(context.Background(), auth); errUpdate != nil { + t.Fatal(errUpdate) + } + send(interrupt) + expect("error") + auth.Disabled = false + if _, errUpdate := manager.Update(context.Background(), auth); errUpdate != nil { + t.Fatal(errUpdate) + } + send(interrupt) + expect("response.incomplete") + send([]byte(fmt.Sprintf(`{"type":"response.create","model":%q,"previous_response_id":"r1","input":[]}`, model))) + expect("response.created") + expect("response.completed") + _ = client.Close() + select { + case <-upstreamDone: + case <-time.After(5 * time.Second): + t.Fatal("upstream did not close") + } + if got := connections.Load(); got != 1 { + t.Fatalf("upstream connections=%d, want 1", got) + } + }) + } +} + +type homeInterruptDispatcher struct{} + +func (homeInterruptDispatcher) HeartbeatOK() bool { return true } + +func (homeInterruptDispatcher) RPopAuth(context.Context, string, string, http.Header, int) ([]byte, error) { + return json.Marshal(coreauth.Auth{ + ID: "home-interrupt-auth", + Provider: "codex", + Status: coreauth.StatusActive, + Attributes: map[string]string{ + "websockets": "true", + }, + }) +} + +func (homeInterruptDispatcher) AbortAmbiguousDispatch() {} + +// homeInterruptExecutor records whether an interrupt was accepted for a Home +// session credential that is not present in the global auth map. +type homeInterruptExecutor struct { + mu sync.Mutex + metadata []map[string]any + interrupted [][]byte + release chan struct{} + releaseOnce sync.Once +} + +func (*homeInterruptExecutor) Identifier() string { return "codex" } + +func (*homeInterruptExecutor) Execute(context.Context, *coreauth.Auth, coreexecutor.Request, coreexecutor.Options) (coreexecutor.Response, error) { + return coreexecutor.Response{}, errors.New("not implemented") +} + +func (e *homeInterruptExecutor) ExecuteStream(ctx context.Context, _ *coreauth.Auth, _ coreexecutor.Request, opts coreexecutor.Options) (*coreexecutor.StreamResult, error) { + e.mu.Lock() + e.metadata = append(e.metadata, maps.Clone(opts.Metadata)) + if e.release == nil { + e.release = make(chan struct{}) + } + release := e.release + e.mu.Unlock() + if lifecycle, ok := opts.ExecutionLifecycle.(interface{ Retain() }); ok { + lifecycle.Retain() + } + chunks := make(chan coreexecutor.StreamChunk, 2) + go func() { + defer close(chunks) + chunks <- coreexecutor.StreamChunk{Payload: []byte(`{"type":"response.created","response":{"id":"r1"}}`)} + select { + case <-release: + case <-ctx.Done(): + return + } + chunks <- coreexecutor.StreamChunk{Payload: []byte(`{"type":"response.completed","response":{"id":"r1","status":"completed","output":[]}}`)} + }() + return &coreexecutor.StreamResult{Chunks: chunks}, nil +} + +func (*homeInterruptExecutor) Refresh(context.Context, *coreauth.Auth) (*coreauth.Auth, error) { + return nil, errors.New("not implemented") +} + +func (*homeInterruptExecutor) CountTokens(context.Context, *coreauth.Auth, coreexecutor.Request, coreexecutor.Options) (coreexecutor.Response, error) { + return coreexecutor.Response{}, errors.New("not implemented") +} + +func (*homeInterruptExecutor) HttpRequest(context.Context, *coreauth.Auth, *http.Request) (*http.Response, error) { + return nil, errors.New("not implemented") +} + +func (e *homeInterruptExecutor) InterruptExecutionSession(ctx context.Context, sessionID string, payload []byte) error { + if !coreexecutor.WebsocketAuthEnabled(ctx, "home-interrupt-auth") { + return fmt.Errorf("websocket credential is no longer enabled") + } + e.mu.Lock() + var want string + if len(e.metadata) > 0 { + want, _ = e.metadata[0][coreexecutor.ExecutionSessionMetadataKey].(string) + } + e.mu.Unlock() + if want == "" || sessionID != want { + return fmt.Errorf("interrupt session = %q, want %q", sessionID, want) + } + e.mu.Lock() + e.interrupted = append(e.interrupted, bytes.Clone(payload)) + e.mu.Unlock() + e.releaseOnce.Do(func() { + if e.release != nil { + close(e.release) + } + }) + return nil +} + +type blockingHTTPInterruptExecutor struct { + calls atomic.Int32 + canceled atomic.Bool +} + +func (*blockingHTTPInterruptExecutor) Identifier() string { return "codex" } + +func (*blockingHTTPInterruptExecutor) Execute(context.Context, *coreauth.Auth, coreexecutor.Request, coreexecutor.Options) (coreexecutor.Response, error) { + return coreexecutor.Response{}, errors.New("not implemented") +} + +func (e *blockingHTTPInterruptExecutor) ExecuteStream(ctx context.Context, _ *coreauth.Auth, _ coreexecutor.Request, _ coreexecutor.Options) (*coreexecutor.StreamResult, error) { + call := e.calls.Add(1) + chunks := make(chan coreexecutor.StreamChunk, 2) + go func() { + defer close(chunks) + if call > 1 { + chunks <- coreexecutor.StreamChunk{Payload: []byte(`{"type":"response.created","response":{"id":"r-http-2"}}`)} + chunks <- coreexecutor.StreamChunk{Payload: []byte(`{"type":"response.completed","response":{"id":"r-http-2","status":"completed","output":[]}}`)} + return + } + chunks <- coreexecutor.StreamChunk{Payload: []byte(`{"type":"response.created","response":{"id":"r-http"}}`)} + <-ctx.Done() + e.canceled.Store(true) + }() + return &coreexecutor.StreamResult{Chunks: chunks}, nil +} + +func (*blockingHTTPInterruptExecutor) Refresh(context.Context, *coreauth.Auth) (*coreauth.Auth, error) { + return nil, errors.New("not implemented") +} + +func (*blockingHTTPInterruptExecutor) CountTokens(context.Context, *coreauth.Auth, coreexecutor.Request, coreexecutor.Options) (coreexecutor.Response, error) { + return coreexecutor.Response{}, errors.New("not implemented") +} + +func (*blockingHTTPInterruptExecutor) HttpRequest(context.Context, *coreauth.Auth, *http.Request) (*http.Response, error) { + return nil, errors.New("not implemented") +} + +func (*blockingHTTPInterruptExecutor) InterruptExecutionSession(context.Context, string, []byte) error { + return coreexecutor.ErrNoActiveUpstreamWebsocket +} + +// TestResponsesInterruptStopsHTTPUpstream verifies that an in-flight interrupt +// cancels an HTTP upstream turn and lets the same socket continue. +func TestResponsesInterruptStopsHTTPUpstream(t *testing.T) { + gin.SetMode(gin.TestMode) + executor := &blockingHTTPInterruptExecutor{} + manager := coreauth.NewManager(nil, nil, nil) + manager.SetConfig(&config.Config{}) + manager.RegisterExecutor(executor) + const authID = "interrupt-http-auth" + const model = "interrupt-http-model" + _, errRegister := manager.Register(context.Background(), &coreauth.Auth{ + ID: authID, + Provider: "codex", + Status: coreauth.StatusActive, + Attributes: map[string]string{"api_key": "test-key"}, + }) + if errRegister != nil { + t.Fatal(errRegister) + } + registry.GetGlobalRegistry().RegisterClient(authID, "codex", []*registry.ModelInfo{{ID: model}}) + defer registry.GetGlobalRegistry().UnregisterClient(authID) + + handler := NewOpenAIResponsesAPIHandler(handlers.NewBaseAPIHandlers(&config.SDKConfig{}, manager)) + router := gin.New() + router.GET("/v1/responses", handler.ResponsesWebsocket) + downstream := httptest.NewServer(router) + defer downstream.Close() + client, _, errDial := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(downstream.URL, "http")+"/v1/responses", nil) + if errDial != nil { + t.Fatal(errDial) + } + defer func() { _ = client.Close() }() + _ = client.SetReadDeadline(time.Now().Add(5 * time.Second)) + if errSend := client.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf(`{"type":"response.create","model":%q,"input":[]}`, model))); errSend != nil { + t.Fatal(errSend) + } + _, created, errRead := client.ReadMessage() + if errRead != nil { + t.Fatal(errRead) + } + if got := gjson.GetBytes(created, "type").String(); got != "response.created" { + t.Fatalf("expected response.created, got %s", created) + } + if errSend := client.WriteMessage(websocket.TextMessage, []byte(`{"type":"response.interrupt","response_id":"r-http","mode":"discard_partial_items"}`)); errSend != nil { + t.Fatal(errSend) + } + _, interrupted, errInterrupted := client.ReadMessage() + if errInterrupted != nil { + t.Fatal(errInterrupted) + } + if got := gjson.GetBytes(interrupted, "type").String(); got != "response.incomplete" { + t.Fatalf("expected response.incomplete, got %s", interrupted) + } + if got := gjson.GetBytes(interrupted, "response.id").String(); got != "r-http" { + t.Fatalf("interrupted response id = %q", got) + } + if got := gjson.GetBytes(interrupted, "response.incomplete_details.reason").String(); got != "interrupted" { + t.Fatalf("interrupt reason = %q, payload %s", got, interrupted) + } + if !executor.canceled.Load() { + t.Fatal("http upstream was not canceled") + } + if errSend := client.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf(`{"type":"response.create","model":%q,"previous_response_id":"r-http","input":[]}`, model))); errSend != nil { + t.Fatal(errSend) + } + _, followCreated, errFollow := client.ReadMessage() + if errFollow != nil { + t.Fatal(errFollow) + } + if got := gjson.GetBytes(followCreated, "type").String(); got != "response.created" { + t.Fatalf("expected follow-up response.created, got %s", followCreated) + } + _, followDone, errDone := client.ReadMessage() + if errDone != nil { + t.Fatal(errDone) + } + if got := gjson.GetBytes(followDone, "type").String(); got != "response.completed" { + t.Fatalf("expected follow-up response.completed, got %s", followDone) + } +} + +// TestResponsesInterruptUsesHomeSessionAuth verifies that a credential staged only +// on the Home execution session can still authorize response.interrupt. +func TestResponsesInterruptUsesHomeSessionAuth(t *testing.T) { + gin.SetMode(gin.TestMode) + manager := coreauth.NewManager(nil, nil, nil) + manager.SetConfig(&config.Config{Home: config.HomeConfig{Enabled: true}}) + manager.PublishHomeDispatch(homeInterruptDispatcher{}, executionregistry.New(), 1) + executor := &homeInterruptExecutor{} + manager.RegisterExecutor(executor) + const authID = "home-interrupt-auth" + const model = "home-interrupt-model" + registry.GetGlobalRegistry().RegisterClient(authID, "codex", []*registry.ModelInfo{{ID: model}}) + defer registry.GetGlobalRegistry().UnregisterClient(authID) + + handler := NewOpenAIResponsesAPIHandler(handlers.NewBaseAPIHandlers(&config.SDKConfig{}, manager)) + router := gin.New() + router.GET("/v1/responses", handler.ResponsesWebsocket) + downstream := httptest.NewServer(router) + defer downstream.Close() + + client, _, errDial := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(downstream.URL, "http")+"/v1/responses", nil) + if errDial != nil { + t.Fatal(errDial) + } + defer func() { _ = client.Close() }() + _ = client.SetReadDeadline(time.Now().Add(8 * time.Second)) + if errSend := client.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf(`{"type":"response.create","model":%q,"input":[]}`, model))); errSend != nil { + t.Fatal(errSend) + } + _, payload, errRead := client.ReadMessage() + if errRead != nil { + t.Fatal(errRead) + } + if got := gjson.GetBytes(payload, "type").String(); got != "response.created" { + t.Fatalf("expected response.created, got %s", payload) + } + if _, ok := manager.GetByID(authID); ok { + t.Fatal("home credential leaked into the global auth map") + } + executor.mu.Lock() + if len(executor.metadata) != 1 { + executor.mu.Unlock() + t.Fatalf("executor calls = %d, want 1", len(executor.metadata)) + } + sessionID, _ := executor.metadata[0][coreexecutor.ExecutionSessionMetadataKey].(string) + executor.mu.Unlock() + if _, ok := manager.GetExecutionSessionAuthByID(sessionID, authID); !ok { + t.Fatal("home session auth was not staged") + } + + interrupt := []byte(`{"type":"response.interrupt","response_id":"r1","mode":"discard_partial_items","extension":"keep"}`) + if errSend := client.WriteMessage(websocket.TextMessage, interrupt); errSend != nil { + t.Fatal(errSend) + } + _, completed, errCompleted := client.ReadMessage() + if errCompleted != nil { + t.Fatal(errCompleted) + } + if got := gjson.GetBytes(completed, "type").String(); got != "response.completed" { + t.Fatalf("expected response.completed after interrupt, got %s", completed) + } + executor.mu.Lock() + gotInterrupt := append([][]byte(nil), executor.interrupted...) + executor.mu.Unlock() + if len(gotInterrupt) != 1 || !bytes.Equal(gotInterrupt[0], interrupt) { + t.Fatalf("interrupt payload = %#v, want %s", gotInterrupt, interrupt) + } + if errSend := client.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf(`{"type":"response.create","model":%q,"input":[]}`, model))); errSend != nil { + t.Fatal(errSend) + } + _, followCreated, errFollow := client.ReadMessage() + if errFollow != nil { + t.Fatal(errFollow) + } + if got := gjson.GetBytes(followCreated, "type").String(); got != "response.created" { + t.Fatalf("expected follow-up response.created, got %s", followCreated) + } + _, followDone, errDone := client.ReadMessage() + if errDone != nil { + t.Fatal(errDone) + } + if got := gjson.GetBytes(followDone, "type").String(); got != "response.completed" { + t.Fatalf("expected follow-up response.completed, got %s", followDone) + } +} diff --git a/sdk/api/handlers/openai/openai_responses_websocket.go b/sdk/api/handlers/openai/openai_responses_websocket.go index 280c3f55d06..fc0875947c1 100644 --- a/sdk/api/handlers/openai/openai_responses_websocket.go +++ b/sdk/api/handlers/openai/openai_responses_websocket.go @@ -264,21 +264,28 @@ func truncateWebsocketCloseReason(reason string, maxBytes int) string { // ResponsesWebsocket handles websocket requests for /v1/responses. // It accepts `response.create` and `response.append` requests and streams -// response events back as JSON websocket text messages. +// response events back as JSON websocket text messages. `response.interrupt` +// is forwarded to the current Codex upstream socket without starting a new turn. func (h *OpenAIResponsesAPIHandler) ResponsesWebsocket(c *gin.Context) { conn, err := responsesWebsocketUpgrader.Upgrade(c.Writer, c.Request, websocketUpgradeHeaders(c.Request)) if err != nil { return } + writer := newResponsesWebsocketWriter(conn) + passthroughSessionID := uuid.NewString() + socketCtx, cancelSocket := context.WithCancelCause(c.Request.Context()) + defer cancelSocket(nil) + c.Request = c.Request.WithContext(socketCtx) + // The reader owns the client socket so an in-flight interrupt is not stuck + // behind the response currently being forwarded. + localInterrupt := newResponsesLocalInterrupt() + input := readResponsesWebsocketInput(socketCtx, cancelSocket, conn, func(payload []byte) error { + return h.forwardResponsesWebsocketInterrupt(socketCtx, passthroughSessionID, payload) + }, localInterrupt, writer) var duplexInput <-chan cliproxyexecutor.WebsocketInput if h != nil && h.Cfg != nil && h.Cfg.CodexResponseSteering { - socketCtx, cancelSocket := context.WithCancel(c.Request.Context()) - defer cancelSocket() - c.Request = c.Request.WithContext(socketCtx) - duplexInput = readResponsesWebsocketInput(socketCtx, cancelSocket, conn) + duplexInput = input } - writer := newResponsesWebsocketWriter(conn) - passthroughSessionID := uuid.NewString() downstreamSessionKey := websocketDownstreamSessionKey(c.Request) retainResponsesWebsocketToolCaches(downstreamSessionKey) clientIP := websocketClientAddress(c) @@ -407,18 +414,18 @@ func (h *OpenAIResponsesAPIHandler) ResponsesWebsocket(c *gin.Context) { var msgType int var payload []byte var errReadMessage error - if duplexInput == nil { - msgType, payload, errReadMessage = conn.ReadMessage() - } else { - select { - case message, ok := <-duplexInput: - if !ok { - return - } + select { + case message, ok := <-input: + if !ok { + errReadMessage = context.Cause(socketCtx) + } else { msgType, payload, errReadMessage = websocket.TextMessage, message.Payload, message.Err - case <-c.Request.Context().Done(): - return } + case <-socketCtx.Done(): + errReadMessage = context.Cause(socketCtx) + } + if errReadMessage != nil && errors.Is(errReadMessage, context.Canceled) { + return } if errReadMessage != nil { wsTerminateErr = errReadMessage @@ -755,6 +762,7 @@ func (h *OpenAIResponsesAPIHandler) ResponsesWebsocket(c *gin.Context) { duplexStream: codexDuplexStream.Load, toolCacheTurn: toolCacheTurn, suppressError: replayPinnedAuthFailure, + localInterrupt: localInterrupt, }, ) if errForward != nil { diff --git a/sdk/api/handlers/openai/openai_responses_websocket_forward.go b/sdk/api/handlers/openai/openai_responses_websocket_forward.go index 4bcdfd685ae..a6a6084e4c6 100644 --- a/sdk/api/handlers/openai/openai_responses_websocket_forward.go +++ b/sdk/api/handlers/openai/openai_responses_websocket_forward.go @@ -27,6 +27,7 @@ type responsesWebsocketForwardOptions struct { toolCacheTurn *responsesWebsocketToolCacheTurn suppressError func(*interfaces.ErrorMessage) bool keepAliveInterval *time.Duration + localInterrupt *responsesLocalInterrupt } func (h *OpenAIResponsesAPIHandler) forwardResponsesWebsocket( @@ -70,9 +71,16 @@ func (h *OpenAIResponsesAPIHandler) forwardResponsesWebsocket( defer keepAliveTicker.Stop() keepAliveC = keepAliveTicker.C } + if opts.localInterrupt != nil { + opts.localInterrupt.begin() + defer opts.localInterrupt.end() + } + localFrames := opts.localInterrupt.framesChan() for { select { + case interruptPayload := <-localFrames: + return completeResponsesWebsocketLocalInterrupt(writer, wsTimelineLog, cancel, interruptPayload, outputItemsByIndex, outputItemsFallback, pendingToolCallIDs) case <-c.Request.Context().Done(): cancel(c.Request.Context().Err()) return completedOutput, completedResponseID, sortedStringSet(pendingToolCallIDs), nil, c.Request.Context().Err() @@ -184,7 +192,10 @@ func (h *OpenAIResponsesAPIHandler) forwardResponsesWebsocket( cancel(payloadErrMsg.Error) return completedOutput, completedResponseID, sortedStringSet(pendingToolCallIDs), payloadErrMsg, nil } - } else if isResponsesWebsocketCompletionEvent(eventType) { + } else if isResponsesWebsocketCompletionEvent(eventType) || eventType == "response.incomplete" { + // response.incomplete ends the turn too. Codex uses it, with + // reason "interrupted", to acknowledge response.interrupt. Closing + // the client socket here would block the follow-up request. completed = true completedOutput = responseCompletedOutputFromPayload(payloads[i], outputItemsByIndex, outputItemsFallback) completedResponseID = responseCompletedIDFromPayload(payloads[i]) @@ -233,6 +244,37 @@ func (h *OpenAIResponsesAPIHandler) forwardResponsesWebsocket( } } +func completeResponsesWebsocketLocalInterrupt( + writer *responsesWebsocketWriter, + wsTimelineLog websocketTimelineAppender, + cancel handlers.APIHandlerCancelFunc, + payload []byte, + outputItemsByIndex map[int64][]byte, + outputItemsFallback [][]byte, + pendingToolCallIDs map[string]struct{}, +) ([]byte, string, []string, *interfaces.ErrorMessage, error) { + responseID := strings.TrimSpace(gjson.GetBytes(payload, "response_id").String()) + output := responseCompletedOutputFromPayload([]byte(`{"response":{"output":[]}}`), outputItemsByIndex, outputItemsFallback) + incomplete := []byte(`{"type":"response.incomplete","response":{"status":"incomplete","incomplete_details":{"reason":"interrupted"}}}`) + var errSet error + incomplete, errSet = sjson.SetBytes(incomplete, "response.id", responseID) + if errSet != nil { + cancel(errSet) + return output, responseID, sortedStringSet(pendingToolCallIDs), nil, errSet + } + incomplete, errSet = sjson.SetRawBytes(incomplete, "response.output", output) + if errSet != nil { + cancel(errSet) + return output, responseID, sortedStringSet(pendingToolCallIDs), nil, errSet + } + if errWrite := writeResponsesWebsocketPayload(writer, wsTimelineLog, incomplete, time.Now()); errWrite != nil { + cancel(errWrite) + return output, responseID, sortedStringSet(pendingToolCallIDs), nil, errWrite + } + cancel(context.Canceled) + return output, responseID, sortedStringSet(pendingToolCallIDs), nil, nil +} + func responsesWebsocketErrorStatus(errMsg *interfaces.ErrorMessage) int { if errMsg == nil { return 0 diff --git a/sdk/api/handlers/openai/openai_responses_websocket_input.go b/sdk/api/handlers/openai/openai_responses_websocket_input.go index 0d378c04327..12855ca4b9d 100644 --- a/sdk/api/handlers/openai/openai_responses_websocket_input.go +++ b/sdk/api/handlers/openai/openai_responses_websocket_input.go @@ -1,27 +1,116 @@ package openai import ( + "bytes" "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + "sync" "github.com/gorilla/websocket" + "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + "github.com/tidwall/gjson" ) -// readResponsesWebsocketInput is the only downstream reader in duplex mode. +// responsesLocalInterrupt cancels an in-flight HTTP turn. A websocket upstream +// does not use it; that interrupt is written to the existing socket instead. +type responsesLocalInterrupt struct { + mu sync.Mutex + active bool + frames chan []byte +} + +func newResponsesLocalInterrupt() *responsesLocalInterrupt { + return &responsesLocalInterrupt{frames: make(chan []byte, 1)} +} + +func (s *responsesLocalInterrupt) begin() { + if s == nil { + return + } + s.mu.Lock() + s.active = true + s.mu.Unlock() +} + +func (s *responsesLocalInterrupt) end() { + if s == nil { + return + } + s.mu.Lock() + s.active = false + select { + case <-s.frames: + default: + } + s.mu.Unlock() +} + +func (s *responsesLocalInterrupt) deliver(payload []byte) bool { + if s == nil { + return false + } + s.mu.Lock() + defer s.mu.Unlock() + if !s.active { + return false + } + select { + case s.frames <- bytes.Clone(payload): + default: + } + return true +} + +func (s *responsesLocalInterrupt) framesChan() <-chan []byte { + if s == nil { + return nil + } + return s.frames +} + +// readResponsesWebsocketInput is the only downstream reader. Interrupts are +// handled immediately so they are not queued behind an active response. // The bounded queue backpressures clients instead of retaining unlimited input. -func readResponsesWebsocketInput(ctx context.Context, cancel context.CancelFunc, conn *websocket.Conn) <-chan cliproxyexecutor.WebsocketInput { +func readResponsesWebsocketInput(ctx context.Context, cancel context.CancelCauseFunc, conn *websocket.Conn, interrupt func([]byte) error, local *responsesLocalInterrupt, writer *responsesWebsocketWriter) <-chan cliproxyexecutor.WebsocketInput { input := make(chan cliproxyexecutor.WebsocketInput, 16) go func() { defer close(input) for { - kind, payload, err := conn.ReadMessage() - if err != nil { - cancel() + kind, payload, errRead := conn.ReadMessage() + if errRead != nil { + cancel(errRead) return } if kind != websocket.TextMessage && kind != websocket.BinaryMessage { continue } + // Control frames bypass response.create normalization. The original + // response_id, mode, and extension fields must reach upstream unchanged. + if json.Valid(payload) && gjson.GetBytes(payload, "type").String() == "response.interrupt" { + errInterrupt := interrupt(payload) + switch { + case errInterrupt == nil: + continue + case errors.Is(errInterrupt, cliproxyexecutor.ErrNoActiveUpstreamWebsocket) && local.deliver(payload): + continue + default: + _, errWrite := writeResponsesWebsocketError(writer, nil, &interfaces.ErrorMessage{ + StatusCode: http.StatusBadRequest, + Error: errInterrupt, + }) + if errWrite != nil { + cancel(errWrite) + return + } + continue + } + } select { case input <- cliproxyexecutor.WebsocketInput{Payload: payload}: case <-ctx.Done(): @@ -31,3 +120,32 @@ func readResponsesWebsocketInput(ctx context.Context, cancel context.CancelFunc, }() return input } + +func (h *OpenAIResponsesAPIHandler) forwardResponsesWebsocketInterrupt(ctx context.Context, sessionID string, payload []byte) error { + responseID := gjson.GetBytes(payload, "response_id") + if responseID.Type != gjson.String || strings.TrimSpace(responseID.String()) == "" { + return fmt.Errorf("response.interrupt requires response_id") + } + if h == nil || h.AuthManager == nil { + return cliproxyexecutor.ErrNoActiveUpstreamWebsocket + } + exec, ok := h.AuthManager.Executor("codex") + if !ok || exec == nil { + return cliproxyexecutor.ErrNoActiveUpstreamWebsocket + } + sender, ok := exec.(interface { + InterruptExecutionSession(context.Context, string, []byte) error + }) + if !ok || sender == nil { + return fmt.Errorf("upstream executor does not support response.interrupt") + } + ctx = cliproxyexecutor.WithWebsocketAuthCheck(ctx, func(authID string) bool { + // Home runtime credentials live on the execution session, not in the global map. + auth, found := h.AuthManager.GetByID(authID) + if !found || auth == nil { + auth, found = h.AuthManager.GetExecutionSessionAuthByID(sessionID, authID) + } + return found && auth != nil && !auth.Disabled && auth.Status != coreauth.StatusDisabled + }) + return sender.InterruptExecutionSession(ctx, sessionID, payload) +} diff --git a/sdk/cliproxy/executor/websocket_input.go b/sdk/cliproxy/executor/websocket_input.go index 4129d5e7cd8..d6bd3478a90 100644 --- a/sdk/cliproxy/executor/websocket_input.go +++ b/sdk/cliproxy/executor/websocket_input.go @@ -1,6 +1,12 @@ package executor -import "context" +import ( + "context" + "errors" +) + +// ErrNoActiveUpstreamWebsocket means response.interrupt has no live upstream socket. +var ErrNoActiveUpstreamWebsocket = errors.New("no active upstream websocket for response.interrupt") // WebsocketInput is a frame from the single downstream reader. Err terminates // the connection; Payload is owned by the receiver and must not be replayed. From 00bb5a3b225ee591ac556ef79fcc42b68fda60df Mon Sep 17 00:00:00 2001 From: Bob Date: Thu, 8 Oct 2026 21:34:54 +0800 Subject: [PATCH 105/142] fix(oauth): resume status polling after an accepted callback (#486) A failed status request (a proxy 502, a network drop or a timeout) stops polling and marks the card failed, but keeps the callback field. If the user then submits the callback URL, the backend accepts it, since the login is still pending, and saves the credential. Nothing polls again, so the card keeps showing the old error. The backend accepts callbacks only for pending logins, so resume polling after an accepted callback when it is not already running. Attempts track whether their poll loop is active. Signed-off-by: bob --- src/pages/OAuthPage.tsx | 7 +++++ src/pages/oauthAttempts.ts | 10 ++++++- tests/oauthAttempts.test.ts | 59 +++++++++++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+), 1 deletion(-) diff --git a/src/pages/OAuthPage.tsx b/src/pages/OAuthPage.tsx index cbb4b7d62a6..e4730f8c88a 100644 --- a/src/pages/OAuthPage.tsx +++ b/src/pages/OAuthPage.tsx @@ -580,6 +580,13 @@ export function OAuthPage() { if (!attempt.isCurrent()) return; updateProviderState(provider, { callbackSubmitting: false, callbackStatus: 'success' }); showNotification(t('auth_login.oauth_callback_success'), 'success'); + // The backend only accepts callbacks for pending logins. If a failed status + // request stopped polling, resume it so the card can report the outcome. + const loginState = states[provider]?.state; + if (loginState && !attempt.isPolling()) { + updateProviderState(provider, { status: 'waiting', error: undefined, polling: true }); + startPolling(provider, loginState, attempt); + } } catch (err: unknown) { if (!attempt.isCurrent()) return; const status = getErrorStatus(err); diff --git a/src/pages/oauthAttempts.ts b/src/pages/oauthAttempts.ts index 076a93f53ba..5bf6ec8b5f5 100644 --- a/src/pages/oauthAttempts.ts +++ b/src/pages/oauthAttempts.ts @@ -1,6 +1,8 @@ export interface OAuthAttempt { readonly signal: AbortSignal; isCurrent: () => boolean; + /** True from poll() until a terminal result, a request error or invalidation. */ + isPolling: () => boolean; invalidate: () => void; schedule: (callback: () => void, delay: number) => void; poll: ( @@ -24,10 +26,12 @@ export function createOAuthAttempts(scheduler: Scheduler) { const begin = (provider: string): OAuthAttempt => { attempts.get(provider)?.invalidate(); let timer: number | undefined; + let polling = false; const controller = new AbortController(); const attempt: OAuthAttempt = { signal: controller.signal, isCurrent: () => attempts.get(provider) === attempt, + isPolling: () => polling && attempt.isCurrent(), invalidate: () => { if (timer !== undefined) scheduler.clearTimeout(timer); timer = undefined; @@ -43,13 +47,17 @@ export function createOAuthAttempts(scheduler: Scheduler) { }, delay); }, poll: (request, onResult, onError, delay) => { + polling = true; const tick = async () => { try { const result = await request(); if (!attempt.isCurrent()) return; if (onResult(result)) attempt.schedule(() => void tick(), delay); + else polling = false; } catch (error: unknown) { - if (attempt.isCurrent()) onError(error); + if (!attempt.isCurrent()) return; + polling = false; + onError(error); } }; attempt.schedule(() => void tick(), delay); diff --git a/tests/oauthAttempts.test.ts b/tests/oauthAttempts.test.ts index 7e0c652ea82..97eff6407b7 100644 --- a/tests/oauthAttempts.test.ts +++ b/tests/oauthAttempts.test.ts @@ -210,6 +210,65 @@ describe('OAuth attempt lifecycle', () => { } }); + test('a failed status request ends polling and the same attempt can resume it', async () => { + const { attempts, tasks, tick } = setup(); + const responses: Array<() => Promise> = [ + async () => { + throw new Error('Request failed with status code 502'); + }, + async () => 'wait', + async () => 'ok', + ]; + const results: string[] = []; + let errors = 0; + const attempt = attempts.begin('codex'); + const poll = () => + attempt.poll( + () => responses.shift()!(), + (result) => { + results.push(result); + return result === 'wait'; + }, + () => errors++, + 3000 + ); + expect(attempt.isPolling()).toBe(false); + poll(); + expect(attempt.isPolling()).toBe(true); + tick(); + await flush(); + expect(errors).toBe(1); + expect(attempt.isPolling()).toBe(false); + expect(tasks.size).toBe(0); + + // An accepted callback resumes polling on the attempt that still owns the login. + poll(); + expect(attempt.isPolling()).toBe(true); + tick(); + await flush(); + expect(attempt.isPolling()).toBe(true); + tick(); + await flush(); + expect(results).toEqual(['wait', 'ok']); + expect(attempt.isPolling()).toBe(false); + expect(tasks.size).toBe(0); + }); + + test('an invalidated attempt never reports an active poll', () => { + const { attempts } = setup(); + const old = attempts.begin('codex'); + old.poll( + async () => 'wait', + () => true, + () => {}, + 3000 + ); + expect(old.isPolling()).toBe(true); + const next = attempts.begin('codex'); + expect(old.isPolling()).toBe(false); + expect(next.isPolling()).toBe(false); + }); + test('terminal results and request errors do not schedule another poll', async () => { for (const fail of [false, true]) { const { attempts, tasks, tick } = setup(); From ab151f5d04dc47d2fa8a35ef32f15ac81baac533 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Thu, 8 Oct 2026 21:46:26 +0800 Subject: [PATCH 106/142] fix(antigravity): include thoughts token count in openai completion tokens - Add `thoughtsTokenCount` to `candidatesTokenCount` when calculating `usage.completion_tokens` for Antigravity OpenAI response translation Closes: #6463 --- .../antigravity_openai_response.go | 2 +- .../antigravity_openai_response_test.go | 49 ++++++++++++++----- 2 files changed, 39 insertions(+), 12 deletions(-) diff --git a/internal/translator/antigravity/openai/chat-completions/antigravity_openai_response.go b/internal/translator/antigravity/openai/chat-completions/antigravity_openai_response.go index f3fbf4e8965..5469f5f03ec 100644 --- a/internal/translator/antigravity/openai/chat-completions/antigravity_openai_response.go +++ b/internal/translator/antigravity/openai/chat-completions/antigravity_openai_response.go @@ -285,7 +285,7 @@ func resolveOpenAIFinishReason(params *convertCliResponseToOpenAIChatParams) (fi func setOpenAIUsageMetadata(template []byte, usageResult gjson.Result) []byte { cachedTokenCount := usageResult.Get("cachedContentTokenCount").Int() - template, _ = sjson.SetBytes(template, "usage.completion_tokens", usageResult.Get("candidatesTokenCount").Int()) + template, _ = sjson.SetBytes(template, "usage.completion_tokens", usageResult.Get("candidatesTokenCount").Int()+usageResult.Get("thoughtsTokenCount").Int()) if totalTokenCountResult := usageResult.Get("totalTokenCount"); totalTokenCountResult.Exists() { template, _ = sjson.SetBytes(template, "usage.total_tokens", totalTokenCountResult.Int()) } diff --git a/internal/translator/antigravity/openai/chat-completions/antigravity_openai_response_test.go b/internal/translator/antigravity/openai/chat-completions/antigravity_openai_response_test.go index 6cfd5a6b913..230f638764a 100644 --- a/internal/translator/antigravity/openai/chat-completions/antigravity_openai_response_test.go +++ b/internal/translator/antigravity/openai/chat-completions/antigravity_openai_response_test.go @@ -128,17 +128,44 @@ func TestNoFinishReasonOnIntermediateChunks(t *testing.T) { } } -func TestConvertAntigravityResponseToOpenAIIncludesZeroCompletionTokensWhenMissing(t *testing.T) { - var param any - chunk := []byte(`{"response":{"usageMetadata":{"promptTokenCount":16,"thoughtsTokenCount":42,"totalTokenCount":58}}}`) - - result := ConvertAntigravityResponseToOpenAI(context.Background(), "model", nil, nil, chunk, ¶m) - if len(result) != 1 { - t.Fatalf("expected 1 result, got %d", len(result)) - } - completionTokens := gjson.GetBytes(result[0], "usage.completion_tokens") - if !completionTokens.Exists() || completionTokens.Int() != 0 { - t.Fatalf("completion_tokens = %s, want present with value 0. Output: %s", completionTokens.Raw, result[0]) +func TestConvertAntigravityResponseToOpenAICompletionTokensIncludeThoughts(t *testing.T) { + tests := []struct { + name string + chunk string + wantOutput int64 + }{ + { + name: "candidates and thoughts", + chunk: `{"response":{"usageMetadata":{"promptTokenCount":16,"candidatesTokenCount":5,"thoughtsTokenCount":42,"totalTokenCount":63}}}`, + wantOutput: 47, + }, + { + name: "thoughts without candidates", + chunk: `{"response":{"usageMetadata":{"promptTokenCount":16,"thoughtsTokenCount":42,"totalTokenCount":58}}}`, + wantOutput: 42, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var param any + result := ConvertAntigravityResponseToOpenAI(context.Background(), "model", nil, nil, []byte(tt.chunk), ¶m) + if len(result) != 1 { + t.Fatalf("expected 1 result, got %d", len(result)) + } + completionTokens := gjson.GetBytes(result[0], "usage.completion_tokens") + if !completionTokens.Exists() || completionTokens.Int() != tt.wantOutput { + t.Fatalf("completion_tokens = %s, want present with value %d. Output: %s", completionTokens.Raw, tt.wantOutput, result[0]) + } + if got := gjson.GetBytes(result[0], "usage.completion_tokens_details.reasoning_tokens").Int(); got != 42 { + t.Fatalf("reasoning_tokens = %d, want 42. Output: %s", got, result[0]) + } + promptTokens := gjson.GetBytes(result[0], "usage.prompt_tokens").Int() + totalTokens := gjson.GetBytes(result[0], "usage.total_tokens").Int() + if promptTokens+completionTokens.Int() != totalTokens { + t.Fatalf("prompt_tokens + completion_tokens = %d, total_tokens = %d", promptTokens+completionTokens.Int(), totalTokens) + } + }) } } From 80809679914f376605e2ae6aa2c5d68f140f98d3 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Thu, 8 Oct 2026 22:14:59 +0800 Subject: [PATCH 107/142] fix(claude): ignore overage billing resets in unified rate limit parsing - Ignore unified reset timestamps matching overage reset boundaries to prevent cooling down credentials until monthly billing reset - Filter candidate rate limit deadlines exceeding the 7-day window limit - Treat rejected overage claims with absent or healthy shared utilization as model-scoped rejections Closes: #6465 --- .../executor/helps/claude_ratelimit.go | 65 ++++++- .../executor/helps/claude_ratelimit_test.go | 180 ++++++++++++++++++ 2 files changed, 240 insertions(+), 5 deletions(-) diff --git a/internal/runtime/executor/helps/claude_ratelimit.go b/internal/runtime/executor/helps/claude_ratelimit.go index 12264fcd3a7..e4aa4592c5b 100644 --- a/internal/runtime/executor/helps/claude_ratelimit.go +++ b/internal/runtime/executor/helps/claude_ratelimit.go @@ -15,6 +15,10 @@ import ( const ( defaultClaudeRateLimitFuzzMinSeconds = 1 defaultClaudeRateLimitFuzzMaxSeconds = 30 + // maxClaudeRateLimitWindow is the longest Anthropic rate-limit window (7 days) + // plus a small clock-skew allowance. A later header timestamp is a billing + // boundary, not a recoverable rate limit. + maxClaudeRateLimitWindow = 7*24*time.Hour + time.Hour ) // ClaudeHeadersIndicateUnifiedRateLimitRejection reports whether response headers explicitly @@ -38,14 +42,14 @@ func ClaudeHeadersIndicateUnifiedRateLimitRejection(headers http.Header) bool { return false } status7dOI := strings.ToLower(strings.TrimSpace(getHeaderCaseInsensitive(headers, "Anthropic-Ratelimit-Unified-7d_oi-Status"))) - return !isOverageOrFableOnlyRejection(headers, status5h, status7d, status7dOI) + return !isOverageOrFableOnlyRejection(headers, unifiedStatus, status5h, status7d, status7dOI) } func isClaudeWindowAllowed(status string) bool { return status == "allowed" || status == "allowed_warning" } -func isOverageOrFableOnlyRejection(headers http.Header, status5h, status7d, status7dOI string) bool { +func isOverageOrFableOnlyRejection(headers http.Header, unifiedStatus, status5h, status7d, status7dOI string) bool { if status5h == "rejected" || status7d == "rejected" { return false } @@ -85,6 +89,20 @@ func isOverageOrFableOnlyRejection(headers http.Header, status5h, status7d, stat } } + // Anthropic omits both shared-window headers when it did not evaluate them. + // Only a rejected overage claim uses that absence. An allowed or missing + // unified status must still honor a short Retry-After. Other signals + // (overage disabled, overage status rejected) do not widen this exception. + if unifiedStatus == "rejected" && status5h == "" && status7d == "" && strings.Contains(representativeClaim, "overage") { + util5h := getHeaderCaseInsensitive(headers, "Anthropic-Ratelimit-Unified-5h-Utilization") + util7d := getHeaderCaseInsensitive(headers, "Anthropic-Ratelimit-Unified-7d-Utilization") + util5hAbsentOrHealthy := strings.TrimSpace(util5h) == "" || isClaudeUtilizationHealthy(util5h) + util7dAbsentOrHealthy := strings.TrimSpace(util7d) == "" || isClaudeUtilizationHealthy(util7d) + if util5hAbsentOrHealthy && util7dAbsentOrHealthy { + return true + } + } + return false } @@ -117,7 +135,7 @@ func parseClaudeRateLimitResetWithFuzz(headers http.Header, now time.Time, minFu status5h := strings.ToLower(strings.TrimSpace(getHeaderCaseInsensitive(headers, "Anthropic-Ratelimit-Unified-5h-Status"))) status7d := strings.ToLower(strings.TrimSpace(getHeaderCaseInsensitive(headers, "Anthropic-Ratelimit-Unified-7d-Status"))) status7dOI := strings.ToLower(strings.TrimSpace(getHeaderCaseInsensitive(headers, "Anthropic-Ratelimit-Unified-7d_oi-Status"))) - overageOnlyRejection := isOverageOrFableOnlyRejection(headers, status5h, status7d, status7dOI) + overageOnlyRejection := isOverageOrFableOnlyRejection(headers, unifiedStatus, status5h, status7d, status7dOI) var candidateDeadlines []time.Time var rejectedWindows []string @@ -183,12 +201,18 @@ func parseClaudeRateLimitResetWithFuzz(headers http.Header, now time.Time, minFu if !containsString(rejectedWindows, "unified") { rejectedWindows = append(rejectedWindows, "unified") } - if t, ok := parseUnixOrTimestamp(raw); ok && t.After(now) { - candidateDeadlines = append(candidateDeadlines, t) + // When the representative claim is overage and this timestamp matches + // the overage reset, it is the billing-period boundary, not a rate-limit + // recovery time. + if !claudeUnifiedResetIsOverageBillingBoundary(headers, raw) { + if resetAt, ok := parseUnixOrTimestamp(raw); ok && resetAt.After(now) { + candidateDeadlines = append(candidateDeadlines, resetAt) + } } } } + candidateDeadlines = filterClaudeRateLimitDeadlines(candidateDeadlines, now) if len(candidateDeadlines) == 0 { if len(rejectedWindows) > 0 { log.WithFields(log.Fields{ @@ -232,6 +256,37 @@ func parseClaudeRateLimitResetWithFuzz(headers http.Header, now time.Time, minFu return &effectiveDuration } +func claudeUnifiedResetIsOverageBillingBoundary(headers http.Header, unifiedReset string) bool { + claim := strings.ToLower(strings.TrimSpace(getHeaderCaseInsensitive(headers, "Anthropic-Ratelimit-Unified-Representative-Claim"))) + if !strings.Contains(claim, "overage") { + return false + } + overageReset := getHeaderCaseInsensitive(headers, "Anthropic-Ratelimit-Unified-Overage-Reset") + unifiedAt, okUnified := parseUnixOrTimestamp(unifiedReset) + overageAt, okOverage := parseUnixOrTimestamp(overageReset) + if !okUnified || !okOverage { + return false + } + return unifiedAt.Equal(overageAt) +} + +func filterClaudeRateLimitDeadlines(deadlines []time.Time, now time.Time) []time.Time { + if len(deadlines) == 0 { + return deadlines + } + kept := deadlines[:0] + for _, deadline := range deadlines { + if !deadline.After(now) { + continue + } + if deadline.Sub(now) > maxClaudeRateLimitWindow { + continue + } + kept = append(kept, deadline) + } + return kept +} + func containsString(list []string, target string) bool { for _, item := range list { if item == target { diff --git a/internal/runtime/executor/helps/claude_ratelimit_test.go b/internal/runtime/executor/helps/claude_ratelimit_test.go index a4eeaae3fc6..9477d76e2cd 100644 --- a/internal/runtime/executor/helps/claude_ratelimit_test.go +++ b/internal/runtime/executor/helps/claude_ratelimit_test.go @@ -367,3 +367,183 @@ func TestClaudeHeadersIndicateUnifiedRateLimitRejection_OverageRejection_Utiliza }) } } + +// Issue #6465: an overage claim with no shared-window headers must not bench +// the credential until Anthropic's monthly billing reset. +func TestOverageClaimWithoutSharedWindowsDoesNotCoolUntilBillingReset_Issue6465(t *testing.T) { + now := time.Date(2026, 10, 7, 20, 46, 4, 0, time.UTC) + headers := http.Header{ + "Anthropic-Ratelimit-Unified-Status": []string{"rejected"}, + "Anthropic-Ratelimit-Unified-Representative-Claim": []string{"overage"}, + "Anthropic-Ratelimit-Unified-Reset": []string{"1793491200"}, + "Anthropic-Ratelimit-Unified-Overage-Status": []string{"allowed"}, + "Anthropic-Ratelimit-Unified-Overage-Reset": []string{"1793491200"}, + "Anthropic-Ratelimit-Unified-Overage-Utilization": []string{"0.11"}, + } + + if ClaudeHeadersIndicateUnifiedRateLimitRejection(headers) { + t.Fatal("overage claim with no shared-window headers was treated as a credential-wide rejection") + } + got := parseClaudeRateLimitResetWithFuzz(headers, now, 0, 0) + if got != nil { + t.Fatalf("cooldown = %v, want nil; monthly billing reset must not become a rate-limit deadline", *got) + } +} + +func TestRejectedFiveHourWindowIgnoresMonthlyUnifiedReset_Issue6465(t *testing.T) { + now := time.Date(2026, 10, 7, 20, 46, 4, 0, time.UTC) + fiveHourReset := strconv.FormatInt(now.Add(5*time.Hour).Unix(), 10) + headers := http.Header{ + "Anthropic-Ratelimit-Unified-Status": []string{"rejected"}, + "Anthropic-Ratelimit-Unified-5h-Status": []string{"rejected"}, + "Anthropic-Ratelimit-Unified-5h-Reset": []string{fiveHourReset}, + "Anthropic-Ratelimit-Unified-Reset": []string{"1793491200"}, + "Anthropic-Ratelimit-Unified-Representative-Claim": []string{"five_hour"}, + } + + got := parseClaudeRateLimitResetWithFuzz(headers, now, 0, 0) + if got == nil { + t.Fatal("expected the rejected 5h window reset") + } + if *got < 5*time.Hour-time.Second || *got > 5*time.Hour+time.Second { + t.Fatalf("cooldown = %v, want ~5h; monthly unified reset must not outrank the rejected window", *got) + } +} + +func TestUnifiedResetMatchingOverageResetDoesNotOverrideRetryAfter_Issue6465(t *testing.T) { + now := time.Date(2026, 10, 29, 0, 0, 0, 0, time.UTC) + billingReset := strconv.FormatInt(now.Add(48*time.Hour).Unix(), 10) + headers := http.Header{ + "Anthropic-Ratelimit-Unified-Status": []string{"rejected"}, + "Anthropic-Ratelimit-Unified-Representative-Claim": []string{"overage"}, + "Anthropic-Ratelimit-Unified-7d-Status": []string{"allowed"}, + "Anthropic-Ratelimit-Unified-7d-Utilization": []string{"0.69"}, + "Anthropic-Ratelimit-Unified-Reset": []string{billingReset}, + "Anthropic-Ratelimit-Unified-Overage-Status": []string{"rejected"}, + "Anthropic-Ratelimit-Unified-Overage-Reset": []string{billingReset}, + "Retry-After": []string{"60"}, + } + + if !ClaudeHeadersIndicateUnifiedRateLimitRejection(headers) { + t.Fatal("missing 5h utilization should stay a credential-wide rejection") + } + got := parseClaudeRateLimitResetWithFuzz(headers, now, 0, 0) + if got == nil { + t.Fatal("expected Retry-After to remain after ignoring the billing reset") + } + if *got != 60*time.Second { + t.Fatalf("cooldown = %v, want 60s; unified reset equal to overage reset is not a rate-limit deadline", *got) + } +} + +func TestFiveHourClaimWithOverageDisabledReasonStaysCredentialScoped_Issue6465(t *testing.T) { + now := time.Date(2026, 10, 7, 20, 46, 4, 0, time.UTC) + headers := http.Header{ + "Anthropic-Ratelimit-Unified-Status": []string{"rejected"}, + "Anthropic-Ratelimit-Unified-Representative-Claim": []string{"five_hour"}, + "Anthropic-Ratelimit-Unified-Overage-Disabled-Reason": []string{"org_level_disabled"}, + "Retry-After": []string{"10800"}, + } + + if !ClaudeHeadersIndicateUnifiedRateLimitRejection(headers) { + t.Fatal("five_hour rejection with overage disabled was treated as model-scoped") + } + got := parseClaudeRateLimitResetWithFuzz(headers, now, 0, 0) + if got == nil || *got != 3*time.Hour { + var gotDesc string + if got == nil { + gotDesc = "nil" + } else { + gotDesc = got.String() + } + t.Fatalf("cooldown = %s, want 3h; Retry-After must survive when the claim is not overage", gotDesc) + } +} + +func TestOverageClaimWithExhaustedSharedUtilizationStaysCredentialScoped_Issue6465(t *testing.T) { + now := time.Date(2026, 10, 7, 20, 46, 4, 0, time.UTC) + headers := http.Header{ + "Anthropic-Ratelimit-Unified-Status": []string{"rejected"}, + "Anthropic-Ratelimit-Unified-Representative-Claim": []string{"overage"}, + "Anthropic-Ratelimit-Unified-5h-Utilization": []string{"1.0"}, + "Retry-After": []string{"10800"}, + } + + if !ClaudeHeadersIndicateUnifiedRateLimitRejection(headers) { + t.Fatal("overage claim with exhausted 5h utilization was treated as model-scoped") + } + got := parseClaudeRateLimitResetWithFuzz(headers, now, 0, 0) + if got == nil || *got != 3*time.Hour { + var gotDesc string + if got == nil { + gotDesc = "nil" + } else { + gotDesc = got.String() + } + t.Fatalf("cooldown = %s, want 3h; exhausted shared utilization must keep Retry-After", gotDesc) + } +} + +func TestOverageClaimWithHealthyUtilizationStaysModelScoped_Issue6465(t *testing.T) { + now := time.Date(2026, 10, 7, 20, 46, 4, 0, time.UTC) + headers := http.Header{ + "Anthropic-Ratelimit-Unified-Status": []string{"rejected"}, + "Anthropic-Ratelimit-Unified-Representative-Claim": []string{"overage"}, + "Anthropic-Ratelimit-Unified-5h-Utilization": []string{"0.00"}, + "Anthropic-Ratelimit-Unified-Reset": []string{"1793491200"}, + "Anthropic-Ratelimit-Unified-Overage-Reset": []string{"1793491200"}, + "Retry-After": []string{"10800"}, + } + + if ClaudeHeadersIndicateUnifiedRateLimitRejection(headers) { + t.Fatal("overage claim with healthy omitted-window utilization was treated as credential-scoped") + } + got := parseClaudeRateLimitResetWithFuzz(headers, now, 0, 0) + if got != nil { + t.Fatalf("cooldown = %v, want nil; healthy utilization must not adopt the billing reset or Retry-After", *got) + } +} + +func TestRetryAfterBeyondSevenDaysFallsBack_Issue6465(t *testing.T) { + now := time.Date(2026, 10, 7, 20, 46, 4, 0, time.UTC) + headers := http.Header{ + "Anthropic-Ratelimit-Unified-Status": []string{"rejected"}, + "Anthropic-Ratelimit-Unified-5h-Status": []string{"rejected"}, + "Retry-After": []string{"2034192"}, + } + + got := parseClaudeRateLimitResetWithFuzz(headers, now, 0, 0) + if got != nil { + t.Fatalf("cooldown = %v, want nil; Retry-After beyond 7 days is not a rate-limit window", *got) + } +} + +func TestAllowedUnifiedOverageClaimKeepsShortRetryAfter_Issue6465(t *testing.T) { + now := time.Date(2026, 10, 7, 20, 46, 4, 0, time.UTC) + for _, unifiedStatus := range []string{"allowed", ""} { + t.Run(unifiedStatus, func(t *testing.T) { + headers := http.Header{ + "Anthropic-Ratelimit-Unified-Representative-Claim": []string{"overage"}, + "Anthropic-Ratelimit-Unified-Overage-Status": []string{"allowed"}, + "Retry-After": []string{"30"}, + } + if unifiedStatus != "" { + headers.Set("Anthropic-Ratelimit-Unified-Status", unifiedStatus) + } + + if ClaudeHeadersIndicateUnifiedRateLimitRejection(headers) { + t.Fatal("non-rejected unified status was treated as a credential rejection") + } + got := parseClaudeRateLimitResetWithFuzz(headers, now, 0, 0) + if got == nil || *got != 30*time.Second { + var gotDesc string + if got == nil { + gotDesc = "nil" + } else { + gotDesc = got.String() + } + t.Fatalf("cooldown = %s, want 30s; a short Retry-After must survive when unified status is not rejected", gotDesc) + } + }) + } +} From 2bc236d2fcc1b43d4405b85cd8155b4b8561e149 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Fri, 9 Oct 2026 03:24:45 +0800 Subject: [PATCH 108/142] feat(claude): support responses compaction in claude executor - Handle compaction trigger requests by generating summaries and sealing antigravity compaction capsules - Expand replayed compaction capsules into message history before translation and filter foreign compaction items - Preserve tool definitions with `tool_choice: none` or flatten tool blocks when tool definitions are missing - Support streaming compaction execution and map cache creation and read token usage Closes: #6466 --- .../executor/claude_executor_compaction.go | 300 +++++++++++ .../claude_executor_compaction_test.go | 490 ++++++++++++++++++ .../executor/claude_executor_execute.go | 10 +- .../executor/claude_executor_stream.go | 7 +- .../executor/helps/antigravity_compaction.go | 5 + 5 files changed, 808 insertions(+), 4 deletions(-) create mode 100644 internal/runtime/executor/claude_executor_compaction.go create mode 100644 internal/runtime/executor/claude_executor_compaction_test.go diff --git a/internal/runtime/executor/claude_executor_compaction.go b/internal/runtime/executor/claude_executor_compaction.go new file mode 100644 index 00000000000..f5a90c3747b --- /dev/null +++ b/internal/runtime/executor/claude_executor_compaction.go @@ -0,0 +1,300 @@ +package executor + +import ( + "bytes" + "context" + "fmt" + "net/http" + "strings" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps" + "github.com/router-for-me/CLIProxyAPI/v8/internal/thinking" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + log "github.com/sirupsen/logrus" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +type claudeCompactionSummaryContextKey struct{} + +// expandClaudeResponsesCompaction rewrites sealed compaction items into context +// before translation. Unrecognized capsules fail the request instead of being dropped. +func expandClaudeResponsesCompaction(req *cliproxyexecutor.Request, opts *cliproxyexecutor.Options) error { + if req != nil { + req.Payload = dropForeignClaudeCompactionItems(req.Payload) + if helps.HasResponsesCompactionItem(req.Payload) { + expanded, errExpand := helps.ExpandAntigravityCompactionCapsules(req.Payload) + if errExpand != nil { + return errExpand + } + req.Payload = expanded + } + } + if opts != nil { + opts.OriginalRequest = dropForeignClaudeCompactionItems(opts.OriginalRequest) + if helps.HasResponsesCompactionItem(opts.OriginalRequest) { + expanded, errExpand := helps.ExpandAntigravityCompactionCapsules(opts.OriginalRequest) + if errExpand != nil { + return errExpand + } + opts.OriginalRequest = expanded + } + } + return nil +} + +func dropForeignClaudeCompactionItems(payload []byte) []byte { + input := gjson.GetBytes(payload, "input") + if !input.IsArray() { + return payload + } + dropped := 0 + items := make([]string, 0, len(input.Array())) + for _, item := range input.Array() { + if item.Get("type").String() == "compaction" && !helps.RecognizedAntigravityCompactionCapsule(item.Get("encrypted_content").String()) { + dropped++ + continue + } + items = append(items, item.Raw) + } + if dropped == 0 { + return payload + } + log.Warnf("claude compaction: dropped %d non-CPA compaction item(s)", dropped) + out, _ := sjson.SetRawBytes(payload, "input", []byte("["+strings.Join(items, ",")+"]")) + return out +} + +func claudeResponsesCompactionRequested(req cliproxyexecutor.Request, opts cliproxyexecutor.Options) bool { + return opts.Alt == "responses/compact" || + helps.HasResponsesCompactionTrigger(req.Payload) || + helps.HasResponsesCompactionTrigger(opts.OriginalRequest) +} + +func claudeCompactionSourcePayload(req cliproxyexecutor.Request, opts cliproxyexecutor.Options) []byte { + payload := req.Payload + if !helps.HasResponsesCompactionTrigger(payload) && helps.HasResponsesCompactionTrigger(opts.OriginalRequest) { + payload = opts.OriginalRequest + } + if len(payload) == 0 && len(opts.OriginalRequest) > 0 { + payload = opts.OriginalRequest + } + return payload +} + +func (e *ClaudeExecutor) executeClaudeCompaction(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + var resp cliproxyexecutor.Response + baseModel := thinking.ParseSuffix(req.Model).ModelName + summaryPayload := prepareClaudeCompactionSummaryPayload(claudeCompactionSourcePayload(req, opts), baseModel) + summaryReq := cliproxyexecutor.Request{ + Model: req.Model, + Payload: summaryPayload, + Metadata: req.Metadata, + } + summaryOpts := opts + summaryOpts.Alt = "" + summaryOpts.Stream = false + summaryOpts.OriginalRequest = nil + summaryOpts.SourceFormat = sdktranslator.FormatOpenAIResponse + summaryOpts.ResponseFormat = sdktranslator.FormatClaude + + summaryResp, errSummary := e.Execute(withClaudeCompactionSummary(ctx), auth, summaryReq, summaryOpts) + if errSummary != nil { + return resp, errSummary + } + summaryText, errExtract := helps.ExtractAntigravitySummaryText(summaryResp.Payload) + if errExtract != nil { + return resp, fmt.Errorf("extract summary: %w", errExtract) + } + capsule, errSeal := helps.SealAntigravityCompaction(summaryText, baseModel) + if errSeal != nil { + return resp, fmt.Errorf("seal compaction capsule: %w", errSeal) + } + + inputTokens, outputTokens, totalTokens, cachedTokens := claudeCompactionResponsesUsage(summaryResp.Payload) + respPayload := helps.BuildAntigravityCompactionResponse(baseModel, capsule, inputTokens, outputTokens, totalTokens) + respPayload, _ = sjson.SetBytes(respPayload, "usage.input_tokens_details.cached_tokens", cachedTokens) + return cliproxyexecutor.Response{ + Payload: respPayload, + Headers: summaryResp.Headers, + }, nil +} + +func (e *ClaudeExecutor) executeClaudeCompactionStream(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) { + baseModel := thinking.ParseSuffix(req.Model).ModelName + summaryResp, errSummary := e.executeClaudeCompaction(ctx, auth, req, opts) + if errSummary != nil { + return nil, errSummary + } + // Reuse the capsule and usage already sealed for the non-stream response. + item := gjson.GetBytes(summaryResp.Payload, "output.0") + capsule := item.Get("encrypted_content").String() + if item.Get("type").String() != "compaction" || capsule == "" { + return nil, fmt.Errorf("extract summary: compaction item missing") + } + inputTokens := int(gjson.GetBytes(summaryResp.Payload, "usage.input_tokens").Int()) + outputTokens := int(gjson.GetBytes(summaryResp.Payload, "usage.output_tokens").Int()) + totalTokens := int(gjson.GetBytes(summaryResp.Payload, "usage.total_tokens").Int()) + cachedTokens := int(gjson.GetBytes(summaryResp.Payload, "usage.input_tokens_details.cached_tokens").Int()) + chunks := helps.BuildAntigravityCompactionStreamChunks(baseModel, capsule, inputTokens, outputTokens, totalTokens) + for i := range chunks { + chunks[i] = patchClaudeCompactionStreamUsage(chunks[i], inputTokens, outputTokens, totalTokens, cachedTokens) + } + out := make(chan cliproxyexecutor.StreamChunk, len(chunks)) + for _, chunk := range chunks { + out <- cliproxyexecutor.StreamChunk{Payload: chunk} + } + close(out) + + headers := summaryResp.Headers.Clone() + if headers == nil { + headers = make(http.Header) + } + headers.Set("Content-Type", "text/event-stream") + return &cliproxyexecutor.StreamResult{Headers: headers, Chunks: out}, nil +} + +func withClaudeCompactionSummary(ctx context.Context) context.Context { + if ctx == nil { + ctx = context.Background() + } + return context.WithValue(ctx, claudeCompactionSummaryContextKey{}, true) +} + +func claudeCompactionSummaryFromContext(ctx context.Context) bool { + if ctx == nil { + return false + } + flag, ok := ctx.Value(claudeCompactionSummaryContextKey{}).(bool) + return ok && flag +} + +// prepareClaudeCompactionSummaryPayload keeps tool definitions that Claude needs +// in order to accept tool_use history, while still asking for a text summary. +func prepareClaudeCompactionSummaryPayload(payload []byte, modelName string) []byte { + tools := gjson.GetBytes(payload, "tools") + additionalTools := gjson.GetBytes(payload, "additional_tools") + out := helps.PrepareAntigravityCompactionSummaryPayload(payload, modelName) + if tools.Exists() { + out, _ = sjson.SetRawBytes(out, "tools", []byte(tools.Raw)) + } + if additionalTools.Exists() { + out, _ = sjson.SetRawBytes(out, "additional_tools", []byte(additionalTools.Raw)) + } + return out +} + +// finalizeClaudeCompactionSummaryBody runs after built-in translation and before +// user payload rules. Tool history stays structured when definitions exist, and +// tool_choice none stops the summary turn from calling a tool. History without +// definitions is flattened so Anthropic does not reject orphan tool blocks. +func finalizeClaudeCompactionSummaryBody(body []byte) []byte { + if claudeBodyHasToolDefinitions(body) { + body, _ = sjson.SetRawBytes(body, "tool_choice", []byte(`{"type":"none"}`)) + return body + } + return flattenClaudeToolBlocksForCompaction(body) +} + +func claudeBodyHasToolDefinitions(body []byte) bool { + tools := gjson.GetBytes(body, "tools") + return tools.IsArray() && len(tools.Array()) > 0 +} + +func flattenClaudeToolBlocksForCompaction(body []byte) []byte { + messages := gjson.GetBytes(body, "messages") + if !messages.IsArray() { + return body + } + changed := false + rewritten := make([]string, 0, len(messages.Array())) + for _, msg := range messages.Array() { + content := msg.Get("content") + if !content.IsArray() { + rewritten = append(rewritten, msg.Raw) + continue + } + parts := make([]string, 0, len(content.Array())) + msgChanged := false + for _, part := range content.Array() { + switch part.Get("type").String() { + case "tool_use": + text := fmt.Sprintf("Tool call %s (%s): %s", part.Get("name").String(), part.Get("id").String(), part.Get("input").Raw) + block, _ := sjson.SetBytes([]byte(`{"type":"text","text":""}`), "text", text) + parts = append(parts, string(block)) + msgChanged = true + case "tool_result": + result := part.Get("content") + resultText := result.Raw + if result.Type == gjson.String { + resultText = result.String() + } + text := fmt.Sprintf("Tool result %s: %s", part.Get("tool_use_id").String(), resultText) + block, _ := sjson.SetBytes([]byte(`{"type":"text","text":""}`), "text", text) + parts = append(parts, string(block)) + msgChanged = true + default: + parts = append(parts, part.Raw) + } + } + if !msgChanged { + rewritten = append(rewritten, msg.Raw) + continue + } + changed = true + updated, _ := sjson.SetRawBytes([]byte(msg.Raw), "content", []byte("["+strings.Join(parts, ",")+"]")) + rewritten = append(rewritten, string(updated)) + } + if !changed { + return body + } + body, _ = sjson.SetRawBytes(body, "messages", []byte("["+strings.Join(rewritten, ",")+"]")) + return body +} + +// claudeCompactionResponsesUsage matches the Responses translator: input includes +// cache creation and cache read, cached_tokens is cache read, and total is their sum. +func claudeCompactionResponsesUsage(payload []byte) (inputTokens, outputTokens, totalTokens, cachedTokens int) { + usage := gjson.GetBytes(payload, "usage") + if !usage.Exists() { + parsed := helps.ParseOpenAIUsage(payload) + return int(parsed.InputTokens), int(parsed.OutputTokens), int(parsed.TotalTokens), 0 + } + rawInput := int(usage.Get("input_tokens").Int()) + outputTokens = int(usage.Get("output_tokens").Int()) + cacheCreation := int(usage.Get("cache_creation_input_tokens").Int()) + cachedTokens = int(usage.Get("cache_read_input_tokens").Int()) + inputTokens = rawInput + cacheCreation + cachedTokens + totalTokens = inputTokens + outputTokens + return inputTokens, outputTokens, totalTokens, cachedTokens +} + +func patchClaudeCompactionStreamUsage(chunk []byte, inputTokens, outputTokens, totalTokens, cachedTokens int) []byte { + const dataPrefix = "data: " + idx := bytes.Index(chunk, []byte(dataPrefix)) + if idx < 0 { + return chunk + } + data := bytes.TrimSpace(chunk[idx+len(dataPrefix):]) + path := "" + switch { + case gjson.GetBytes(data, "response.usage").Exists(): + path = "response.usage" + case gjson.GetBytes(data, "usage").Exists(): + path = "usage" + default: + return chunk + } + data, _ = sjson.SetBytes(data, path+".input_tokens", inputTokens) + data, _ = sjson.SetBytes(data, path+".output_tokens", outputTokens) + data, _ = sjson.SetBytes(data, path+".total_tokens", totalTokens) + data, _ = sjson.SetBytes(data, path+".input_tokens_details.cached_tokens", cachedTokens) + var buf bytes.Buffer + buf.Write(chunk[:idx]) + buf.WriteString(dataPrefix) + buf.Write(data) + buf.WriteString("\n\n") + return buf.Bytes() +} diff --git a/internal/runtime/executor/claude_executor_compaction_test.go b/internal/runtime/executor/claude_executor_compaction_test.go new file mode 100644 index 00000000000..aefd0b44beb --- /dev/null +++ b/internal/runtime/executor/claude_executor_compaction_test.go @@ -0,0 +1,490 @@ +package executor + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "github.com/tidwall/gjson" +) + +const ( + claudeCompactionSummaryPrompt = "Please provide a concise and comprehensive summary" + claudeCompactionSummaryText = "Sealed summary of the build." +) + +func TestClaudeExecutor_CompactionTriggerReturnsSingleCompactionItem(t *testing.T) { + var seen []byte + server := httptest.NewServer(claudeCompactionUpstream(t, &seen)) + defer server.Close() + + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{Attributes: map[string]string{ + "api_key": "key-compaction", + "base_url": server.URL, + }} + payload := []byte(`{"model":"claude-haiku-4-5-20251001","stream":false,"input":[` + + `{"type":"message","role":"user","content":[{"type":"input_text","text":"Check the build next."}]},` + + `{"type":"message","role":"assistant","content":[{"type":"output_text","text":"OK, I will check the build."}]},` + + `{"type":"compaction_trigger"}]}`) + + resp, errExecute := executor.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "claude-haiku-4-5-20251001", + Payload: payload, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + OriginalRequest: payload, + }) + if errExecute != nil { + t.Fatalf("Execute() error = %v", errExecute) + } + assertSingleCompactionOutput(t, resp.Payload) + assertClaudeCompactionSummaryRequest(t, seen) +} + +func TestClaudeExecutor_CompactionTriggerStreamReturnsSingleCompactionItem(t *testing.T) { + var seen []byte + server := httptest.NewServer(claudeCompactionUpstream(t, &seen)) + defer server.Close() + + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{Attributes: map[string]string{ + "api_key": "key-compaction", + "base_url": server.URL, + }} + payload := []byte(`{"model":"claude-haiku-4-5-20251001","stream":true,"input":[` + + `{"type":"message","role":"user","content":[{"type":"input_text","text":"Check the build next."}]},` + + `{"type":"message","role":"assistant","content":[{"type":"output_text","text":"OK, I will check the build."}]},` + + `{"type":"compaction_trigger"}]}`) + + streamResult, errStream := executor.ExecuteStream(context.Background(), auth, cliproxyexecutor.Request{ + Model: "claude-haiku-4-5-20251001", + Payload: payload, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + Stream: true, + OriginalRequest: payload, + }) + if errStream != nil { + t.Fatalf("ExecuteStream() error = %v", errStream) + } + + var buf bytes.Buffer + for chunk := range streamResult.Chunks { + if chunk.Err != nil { + t.Fatalf("chunk error: %v", chunk.Err) + } + buf.Write(chunk.Payload) + } + completed := claudeCompactionCompletedResponse(t, buf.String()) + assertSingleCompactionOutput(t, []byte(completed.Raw)) + assertClaudeCompactionSummaryRequest(t, seen) +} + +func TestClaudeExecutor_ReplayedCompactionCapsuleIsExpanded(t *testing.T) { + capsule, errSeal := helps.SealAntigravityCompaction(claudeCompactionSummaryText, "claude-haiku-4-5-20251001") + if errSeal != nil { + t.Fatalf("SealAntigravityCompaction() error = %v", errSeal) + } + + var seen []byte + server := httptest.NewServer(claudeCompactionUpstream(t, &seen)) + defer server.Close() + + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{Attributes: map[string]string{ + "api_key": "key-compaction", + "base_url": server.URL, + }} + payload := []byte(`{"model":"claude-haiku-4-5-20251001","stream":false,"input":[` + + `{"type":"compaction","encrypted_content":` + gjson.Get(`{"v":"`+capsule+`"}`, "v").Raw + `},` + + `{"type":"message","role":"user","content":[{"type":"input_text","text":"continue"}]}]}`) + + _, errExecute := executor.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "claude-haiku-4-5-20251001", + Payload: payload, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + OriginalRequest: payload, + }) + if errExecute != nil { + t.Fatalf("Execute() error = %v", errExecute) + } + if !bytes.Contains(seen, []byte(claudeCompactionSummaryText)) { + t.Fatalf("replayed compaction summary missing from upstream request: %s", seen) + } + if bytes.Contains(seen, []byte(`"type":"compaction"`)) || bytes.Contains(seen, []byte(`"type": "compaction"`)) { + t.Fatalf("compaction item reached upstream request: %s", seen) + } +} + +func TestClaudeExecutor_CompactionTriggerKeepsToolsForToolHistory(t *testing.T) { + var seen []byte + server := httptest.NewServer(claudeCompactionUpstream(t, &seen)) + defer server.Close() + + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{Attributes: map[string]string{ + "api_key": "key-compaction", + "base_url": server.URL, + }} + payload := []byte(`{"model":"claude-haiku-4-5-20251001","stream":false,"tools":[{"type":"function","name":"check_build","description":"Check the build","parameters":{"type":"object","properties":{}}}],"input":[` + + `{"type":"message","role":"user","content":[{"type":"input_text","text":"Check the build next."}]},` + + `{"type":"function_call","call_id":"call_1","name":"check_build","arguments":"{}"},` + + `{"type":"function_call_output","call_id":"call_1","output":"build ok"},` + + `{"type":"compaction_trigger"}]}`) + + resp, errExecute := executor.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "claude-haiku-4-5-20251001", + Payload: payload, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + OriginalRequest: payload, + }) + if errExecute != nil { + t.Fatalf("Execute() error = %v", errExecute) + } + assertSingleCompactionOutput(t, resp.Payload) + assertClaudeCompactionSummaryRequest(t, seen) + if !bytes.Contains(seen, []byte("check_build")) { + t.Fatalf("tool definition missing from summary request: %s", seen) + } + if !bytes.Contains(seen, []byte(`"type":"tool_use"`)) || !bytes.Contains(seen, []byte(`"type":"tool_result"`)) { + t.Fatalf("tool history missing from summary request: %s", seen) + } + if got := gjson.GetBytes(seen, "tool_choice.type").String(); got != "none" { + t.Fatalf("tool_choice.type = %q, want none so the summary cannot call tools: %s", got, seen) + } +} + +func TestClaudeExecutor_CompactionTriggerFlattensToolHistoryWithoutTools(t *testing.T) { + var seen []byte + server := httptest.NewServer(claudeCompactionUpstream(t, &seen)) + defer server.Close() + + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{Attributes: map[string]string{ + "api_key": "key-compaction", + "base_url": server.URL, + }} + payload := []byte(`{"model":"claude-haiku-4-5-20251001","stream":false,"input":[` + + `{"type":"message","role":"user","content":[{"type":"input_text","text":"Check the build next."}]},` + + `{"type":"function_call","call_id":"call_1","name":"check_build","arguments":"{\"target\":\"api\"}"},` + + `{"type":"function_call_output","call_id":"call_1","output":"build ok"},` + + `{"type":"compaction_trigger"}]}`) + + _, errExecute := executor.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "claude-haiku-4-5-20251001", + Payload: payload, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + OriginalRequest: payload, + }) + if errExecute != nil { + t.Fatalf("Execute() error = %v", errExecute) + } + if bytes.Contains(seen, []byte(`"type":"tool_use"`)) || bytes.Contains(seen, []byte(`"type":"tool_result"`)) { + t.Fatalf("tool blocks reached summary request without tool definitions: %s", seen) + } + if !bytes.Contains(seen, []byte("build ok")) || !bytes.Contains(seen, []byte("check_build")) { + t.Fatalf("flattened tool history missing from summary request: %s", seen) + } +} + +func TestClaudeExecutor_CompactionSummaryPayloadRuleIsLast(t *testing.T) { + var seen []byte + server := httptest.NewServer(claudeCompactionUpstream(t, &seen)) + defer server.Close() + + executor := NewClaudeExecutor(&config.Config{ + Payload: config.PayloadConfig{ + Override: []config.PayloadRule{{ + Models: []config.PayloadModelRule{{Name: "claude-haiku-4-5-20251001"}}, + Params: map[string]any{ + "max_tokens": 1234, + "tool_choice": map[string]any{"type": "auto"}, + }, + }}, + }, + }) + auth := &cliproxyauth.Auth{Attributes: map[string]string{ + "api_key": "key-compaction", + "base_url": server.URL, + }} + payload := []byte(`{"model":"claude-haiku-4-5-20251001","stream":false,"tools":[{"type":"function","name":"check_build","description":"Check the build","parameters":{"type":"object","properties":{}}}],"input":[` + + `{"type":"message","role":"user","content":[{"type":"input_text","text":"Check the build next."}]},` + + `{"type":"function_call","call_id":"call_1","name":"check_build","arguments":"{}"},` + + `{"type":"function_call_output","call_id":"call_1","output":"build ok"},` + + `{"type":"compaction_trigger"}]}`) + + _, errExecute := executor.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "claude-haiku-4-5-20251001", + Payload: payload, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + OriginalRequest: payload, + }) + if errExecute != nil { + t.Fatalf("Execute() error = %v", errExecute) + } + if got := gjson.GetBytes(seen, "max_tokens").Int(); got != 1234 { + t.Fatalf("max_tokens = %d, want payload rule 1234; body=%s", got, seen) + } + if got := gjson.GetBytes(seen, "tool_choice.type").String(); got != "auto" { + t.Fatalf("tool_choice.type = %q, want payload rule auto to win over built-in none; body=%s", got, seen) + } +} + +func TestClaudeExecutor_CompactionTriggerIncludesPreviousCapsule(t *testing.T) { + capsule, errSeal := helps.SealAntigravityCompaction("Earlier sealed summary.", "claude-haiku-4-5-20251001") + if errSeal != nil { + t.Fatalf("SealAntigravityCompaction() error = %v", errSeal) + } + var seen []byte + server := httptest.NewServer(claudeCompactionUpstream(t, &seen)) + defer server.Close() + + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{Attributes: map[string]string{ + "api_key": "key-compaction", + "base_url": server.URL, + }} + payload := []byte(`{"model":"claude-haiku-4-5-20251001","stream":false,"input":[` + + `{"type":"compaction","encrypted_content":` + gjson.Get(`{"v":"`+capsule+`"}`, "v").Raw + `},` + + `{"type":"message","role":"user","content":[{"type":"input_text","text":"continue"}]},` + + `{"type":"message","role":"assistant","content":[{"type":"output_text","text":"continued"}]},` + + `{"type":"compaction_trigger"}]}`) + + resp, errExecute := executor.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "claude-haiku-4-5-20251001", + Payload: payload, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + OriginalRequest: payload, + }) + if errExecute != nil { + t.Fatalf("Execute() error = %v", errExecute) + } + assertSingleCompactionOutput(t, resp.Payload) + if !bytes.Contains(seen, []byte("Earlier sealed summary.")) { + t.Fatalf("previous capsule missing from the next summary request: %s", seen) + } + assertClaudeCompactionSummaryRequest(t, seen) +} + +func TestClaudeExecutor_ForeignCompactionCapsuleIsDropped(t *testing.T) { + var seen []byte + server := httptest.NewServer(claudeCompactionUpstream(t, &seen)) + defer server.Close() + + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{Attributes: map[string]string{ + "api_key": "key-compaction", + "base_url": server.URL, + }} + payload := []byte(`{"model":"claude-haiku-4-5-20251001","stream":false,"input":[` + + `{"type":"compaction","encrypted_content":"gAAAAA-openai-native"},` + + `{"type":"message","role":"user","content":[{"type":"input_text","text":"continue"}]},` + + `{"type":"compaction_trigger"}]}`) + + resp, errExecute := executor.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "claude-haiku-4-5-20251001", + Payload: payload, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + OriginalRequest: payload, + }) + if errExecute != nil { + t.Fatalf("Execute() error = %v", errExecute) + } + assertSingleCompactionOutput(t, resp.Payload) + if bytes.Contains(seen, []byte("gAAAAA-openai-native")) { + t.Fatalf("foreign compaction capsule reached upstream: %s", seen) + } + assertClaudeCompactionSummaryRequest(t, seen) +} + +func TestClaudeExecutor_CompactionUsageMatchesResponsesAccounting(t *testing.T) { + var seen []byte + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, errRead := io.ReadAll(r.Body) + if errRead != nil { + t.Errorf("read upstream body: %v", errRead) + } + seen = body + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"id":"msg_compact","type":"message","role":"assistant","model":"claude-haiku-4-5-20251001","content":[{"type":"text","text":"Sealed summary of the build."}],"stop_reason":"end_turn","usage":{"input_tokens":11,"output_tokens":7,"cache_creation_input_tokens":3,"cache_read_input_tokens":100}}`)) + })) + defer server.Close() + + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{Attributes: map[string]string{ + "api_key": "key-compaction", + "base_url": server.URL, + }} + payload := []byte(`{"model":"claude-haiku-4-5-20251001","stream":false,"input":[` + + `{"type":"message","role":"user","content":[{"type":"input_text","text":"Check the build next."}]},` + + `{"type":"compaction_trigger"}]}`) + + resp, errExecute := executor.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "claude-haiku-4-5-20251001", + Payload: payload, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + OriginalRequest: payload, + }) + if errExecute != nil { + t.Fatalf("Execute() error = %v", errExecute) + } + usage := gjson.GetBytes(resp.Payload, "usage") + if usage.Get("input_tokens").Int() != 114 || usage.Get("output_tokens").Int() != 7 || usage.Get("total_tokens").Int() != 121 || usage.Get("input_tokens_details.cached_tokens").Int() != 100 { + t.Fatalf("usage = %s, want input 114 output 7 total 121 cached 100", usage.Raw) + } + _ = seen +} + +func TestClaudeExecutor_InvalidCompactionCapsuleReturns400(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Errorf("invalid compaction capsule must not reach upstream") + w.WriteHeader(http.StatusOK) + })) + defer server.Close() + + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{Attributes: map[string]string{ + "api_key": "key-compaction", + "base_url": server.URL, + }} + payload := []byte(`{"model":"claude-haiku-4-5-20251001","stream":false,"input":[` + + `{"type":"compaction","encrypted_content":"cpa-ag-compact-v1:not-valid-base64"},` + + `{"type":"message","role":"user","content":[{"type":"input_text","text":"continue"}]}]}`) + + _, errExecute := executor.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "claude-haiku-4-5-20251001", + Payload: payload, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + OriginalRequest: payload, + }) + if errExecute == nil { + t.Fatal("Execute() error = nil, want 400") + } + assertStatusErr(t, errExecute, http.StatusBadRequest) +} + +func claudeCompactionUpstream(t *testing.T, seen *[]byte) http.Handler { + t.Helper() + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, errRead := io.ReadAll(r.Body) + if errRead != nil { + t.Errorf("read upstream body: %v", errRead) + http.Error(w, "read", http.StatusBadRequest) + return + } + *seen = body + if gjson.GetBytes(body, "stream").Bool() { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = w.Write([]byte(strings.Join([]string{ + `event: message_start`, + `data: {"type":"message_start","message":{"id":"msg_compact","type":"message","role":"assistant","model":"claude-haiku-4-5-20251001","usage":{"input_tokens":11,"output_tokens":0}}}`, + `event: content_block_start`, + `data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`, + `event: content_block_delta`, + `data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Let me examine the current build status."}}`, + `event: content_block_stop`, + `data: {"type":"content_block_stop","index":0}`, + `event: message_delta`, + `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":7}}`, + `event: message_stop`, + `data: {"type":"message_stop"}`, + ``, + }, "\n"))) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"id":"msg_compact","type":"message","role":"assistant","model":"claude-haiku-4-5-20251001","content":[{"type":"text","text":"Sealed summary of the build."}],"stop_reason":"end_turn","usage":{"input_tokens":11,"output_tokens":7}}`)) + }) +} + +func assertSingleCompactionOutput(t *testing.T, payload []byte) { + t.Helper() + output := gjson.GetBytes(payload, "output") + if !output.Exists() { + output = gjson.GetBytes(payload, "response.output") + } + items := output.Array() + if len(items) != 1 || items[0].Get("type").String() != "compaction" { + t.Fatalf("output types = %s, want exactly one compaction; payload=%s", compactionOutputTypes(items), payload) + } + plain, errUnseal := helps.UnsealAntigravityCompaction(items[0].Get("encrypted_content").String()) + if errUnseal != nil { + t.Fatalf("unseal compaction capsule: %v", errUnseal) + } + if plain != claudeCompactionSummaryText { + t.Fatalf("capsule summary = %q, want %q", plain, claudeCompactionSummaryText) + } + usage := gjson.GetBytes(payload, "usage") + if !usage.Exists() { + usage = gjson.GetBytes(payload, "response.usage") + } + if usage.Get("input_tokens").Int() != 11 || usage.Get("output_tokens").Int() != 7 || usage.Get("total_tokens").Int() != 18 { + t.Fatalf("usage = %s, want input 11 output 7 total 18", usage.Raw) + } +} + +func compactionOutputTypes(items []gjson.Result) string { + if len(items) == 0 { + return "" + } + types := make([]string, 0, len(items)) + for _, item := range items { + types = append(types, item.Get("type").String()) + } + return strings.Join(types, ",") +} + +func assertClaudeCompactionSummaryRequest(t *testing.T, body []byte) { + t.Helper() + if !bytes.Contains(body, []byte(claudeCompactionSummaryPrompt)) { + t.Fatalf("upstream body missing summary prompt %q: %s", claudeCompactionSummaryPrompt, body) + } + if bytes.Contains(body, []byte("compaction_trigger")) { + t.Fatalf("compaction_trigger reached upstream: %s", body) + } +} + +func claudeCompactionCompletedResponse(t *testing.T, stream string) gjson.Result { + t.Helper() + for _, frame := range strings.Split(stream, "\n\n") { + if !strings.Contains(frame, "event: response.completed") { + continue + } + for _, line := range strings.Split(frame, "\n") { + if !strings.HasPrefix(line, "data:") { + continue + } + return gjson.Parse(strings.TrimSpace(strings.TrimPrefix(line, "data:"))) + } + } + t.Fatalf("response.completed missing from stream: %s", stream) + return gjson.Result{} +} diff --git a/internal/runtime/executor/claude_executor_execute.go b/internal/runtime/executor/claude_executor_execute.go index 0e5b6f31dc7..3512e984f6e 100644 --- a/internal/runtime/executor/claude_executor_execute.go +++ b/internal/runtime/executor/claude_executor_execute.go @@ -18,8 +18,11 @@ import ( func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (resp cliproxyexecutor.Response, err error) { ctx = helps.EnsureSessionContext(ctx, opts, req.Payload) - if opts.Alt == "responses/compact" { - return resp, statusErr{code: http.StatusNotImplemented, msg: "/responses/compact not supported"} + if errExpand := expandClaudeResponsesCompaction(&req, &opts); errExpand != nil { + return resp, statusErr{code: http.StatusBadRequest, msg: errExpand.Error()} + } + if claudeResponsesCompactionRequested(req, opts) { + return e.executeClaudeCompaction(ctx, auth, req, opts) } baseModel := thinking.ParseSuffix(req.Model).ModelName upstreamModel := e.upstreamModel(baseModel) @@ -233,6 +236,9 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r } } bodyForUpstream = stripDefaultKimiClaudeCodeAttribution(auth, url, fp.ProfileClaudeCodeCLI, bodyForUpstream) + if claudeCompactionSummaryFromContext(ctx) { + bodyForUpstream = finalizeClaudeCompactionSummaryBody(bodyForUpstream) + } // User rules match the fully prepared business body and are applied only once. var touchedPayloadPaths map[string]bool bodyForUpstream, touchedPayloadPaths = helps.ApplyPayloadConfigWithTrackedPaths( diff --git a/internal/runtime/executor/claude_executor_stream.go b/internal/runtime/executor/claude_executor_stream.go index 436536f44cd..248457437fa 100644 --- a/internal/runtime/executor/claude_executor_stream.go +++ b/internal/runtime/executor/claude_executor_stream.go @@ -20,8 +20,11 @@ import ( func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (_ *cliproxyexecutor.StreamResult, err error) { ctx = helps.EnsureSessionContext(ctx, opts, req.Payload) - if opts.Alt == "responses/compact" { - return nil, statusErr{code: http.StatusNotImplemented, msg: "/responses/compact not supported"} + if errExpand := expandClaudeResponsesCompaction(&req, &opts); errExpand != nil { + return nil, statusErr{code: http.StatusBadRequest, msg: errExpand.Error()} + } + if claudeResponsesCompactionRequested(req, opts) { + return e.executeClaudeCompactionStream(ctx, auth, req, opts) } baseModel := thinking.ParseSuffix(req.Model).ModelName upstreamModel := e.upstreamModel(baseModel) diff --git a/internal/runtime/executor/helps/antigravity_compaction.go b/internal/runtime/executor/helps/antigravity_compaction.go index 60d4329d1a3..a5189b8edb2 100644 --- a/internal/runtime/executor/helps/antigravity_compaction.go +++ b/internal/runtime/executor/helps/antigravity_compaction.go @@ -28,6 +28,11 @@ type antigravityCompactionCapsuleData struct { CreatedAt int64 `json:"created_at"` } +// RecognizedAntigravityCompactionCapsule reports whether encrypted content uses the CPA capsule prefix. +func RecognizedAntigravityCompactionCapsule(encryptedContent string) bool { + return strings.HasPrefix(strings.TrimSpace(encryptedContent), antigravityCompactionCapsulePrefix) +} + // HasResponsesCompactionTrigger checks whether input contains a compaction_trigger item. func HasResponsesCompactionTrigger(payload []byte) bool { input := gjson.GetBytes(payload, "input") From a881c0361c2ea5174f5e261fae07c77b6fd76481 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Fri, 9 Oct 2026 03:43:34 +0800 Subject: [PATCH 109/142] fix(claude): respect registry completion limit for default responses max tokens - Use registered model `MaxCompletionTokens` limit when `max_output_tokens` is omitted, allowing limits above the 32k default - Preserve conservative ceiling for Fable models Closes: #6468 --- .../claude_openai-responses_request.go | 16 ++++++-- .../claude_openai-responses_request_test.go | 40 +++++++++++++++++++ 2 files changed, 52 insertions(+), 4 deletions(-) diff --git a/internal/translator/claude/openai/responses/claude_openai-responses_request.go b/internal/translator/claude/openai/responses/claude_openai-responses_request.go index e8bb19b962e..d634d4a4da9 100644 --- a/internal/translator/claude/openai/responses/claude_openai-responses_request.go +++ b/internal/translator/claude/openai/responses/claude_openai-responses_request.go @@ -652,14 +652,22 @@ func convertOpenAIResponsesRequestToClaude(modelName string, inputRawJSON []byte } func defaultClaudeResponsesMaxTokensForModel(modelName string) int { + normalized := strings.ToLower(strings.TrimSpace(modelName)) maxTokens := defaultClaudeResponsesMaxTokens - if strings.Contains(strings.ToLower(strings.TrimSpace(modelName)), "fable") { + if strings.Contains(normalized, "fable") { maxTokens = defaultFableResponsesMaxTokens } - if info := registry.LookupModelInfo(modelName, "claude"); info != nil && info.MaxCompletionTokens > 0 && info.MaxCompletionTokens < maxTokens { - return info.MaxCompletionTokens + info := registry.LookupModelInfo(modelName, "claude") + if info == nil || info.MaxCompletionTokens <= 0 { + return maxTokens + } + // Fable keeps its conservative omitted-field ceiling. Every other registered + // model uses its output limit, including when that limit is above the + // historical 32000 default. + if strings.Contains(normalized, "fable") && info.MaxCompletionTokens >= maxTokens { + return maxTokens } - return maxTokens + return info.MaxCompletionTokens } // isResponsesSystemLevelRole reports whether an input item carries system-level diff --git a/internal/translator/claude/openai/responses/claude_openai-responses_request_test.go b/internal/translator/claude/openai/responses/claude_openai-responses_request_test.go index fef478b2f06..ae60ea01aff 100644 --- a/internal/translator/claude/openai/responses/claude_openai-responses_request_test.go +++ b/internal/translator/claude/openai/responses/claude_openai-responses_request_test.go @@ -100,6 +100,46 @@ func TestConvertOpenAIResponsesRequestToClaude_FableMaxTokens(t *testing.T) { }) } +func TestConvertOpenAIResponsesRequestToClaude_OmittedMaxOutputTokensUsesRegistryLimit(t *testing.T) { + tests := []struct { + name string + model string + raw string + wantLimit int64 + }{ + { + name: "opus 5.5 omitted field uses 128k registry limit", + model: "claude-opus-5-5", + raw: `{"model":"claude-opus-5-5","input":"hello"}`, + wantLimit: 128000, + }, + { + name: "opus 5.5 null field uses 128k registry limit", + model: "claude-opus-5-5", + raw: `{"model":"claude-opus-5-5","max_output_tokens":null,"input":"hello"}`, + wantLimit: 128000, + }, + { + name: "sonnet 4.6 omitted field uses 64k registry limit", + model: "claude-sonnet-4-6", + raw: `{"model":"claude-sonnet-4-6","input":"hello"}`, + wantLimit: 64000, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + out, errConvert := ConvertOpenAIResponsesRequestToClaude(tc.model, []byte(tc.raw), false) + if errConvert != nil { + t.Fatalf("convert: %v", errConvert) + } + if got := gjson.GetBytes(out, "max_tokens").Int(); got != tc.wantLimit { + t.Fatalf("max_tokens = %d, want %d; output=%s", got, tc.wantLimit, out) + } + }) + } +} + func TestConvertOpenAIResponsesRequestToClaude_ReasoningItemToThinkingBlock(t *testing.T) { rawSignature, expectedSignature := testClaudeResponsesThinkingSignature(t) raw := []byte(`{ From 67465884ca179a8f9098328d03a361b50003fdd7 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Fri, 9 Oct 2026 04:04:08 +0800 Subject: [PATCH 110/142] fix(pluginhost): detach unselected plugins on config apply - Automatically detach and shut down plugins that are disabled or unselected during configuration reload - Unload all active plugins when the plugin system is globally disabled Closes: #6471 --- internal/pluginhost/host.go | 69 +++++++++++++++++ internal/pluginhost/host_test.go | 122 ++++++++++++++++++++++++++----- 2 files changed, 173 insertions(+), 18 deletions(-) diff --git a/internal/pluginhost/host.go b/internal/pluginhost/host.go index b9cf9d0f083..a1bca7f614e 100644 --- a/internal/pluginhost/host.go +++ b/internal/pluginhost/host.go @@ -224,6 +224,7 @@ func (h *Host) ApplyConfig(ctx context.Context, cfg *config.Config) { h.mu.Unlock() if !rc.Enabled { + h.detachUnselectedPlugins(ctx, nil) h.mu.Lock() h.managementRoutes = make(map[string]managementRouteRecord) h.resourceRoutes = make(map[string]resourceRouteRecord) @@ -248,6 +249,7 @@ func (h *Host) ApplyConfig(ctx context.Context, cfg *config.Config) { return } files = h.withLoadedPluginFallbacks(files, rc.Items, desiredVersions) + h.detachUnselectedPlugins(ctx, enabledPluginIDs(files, rc.Items)) records := make([]capabilityRecord, 0, len(files)) loadedFiles := make([]pluginFile, 0, len(files)) @@ -654,6 +656,21 @@ func (h *Host) UnloadPluginContext(ctx context.Context, id string) bool { return false } defer h.unlockApply() + return h.detachPlugin(ctx, id) +} + +// detachPlugin shuts down one loaded plugin. Caller must hold the apply lock. +func (h *Host) detachPlugin(ctx context.Context, id string) bool { + if h == nil { + return false + } + id = strings.TrimSpace(id) + if id == "" { + return false + } + if ctx == nil { + ctx = context.Background() + } targets := make([]pluginUnloadTarget, 0) h.mu.Lock() @@ -710,6 +727,58 @@ func (h *Host) UnloadPluginContext(ctx context.Context, id string) bool { return true } +// detachUnselectedPlugins stops plugins that are no longer enabled. nil keeps none. +// Caller must hold the apply lock. +func (h *Host) detachUnselectedPlugins(ctx context.Context, selected map[string]struct{}) { + if h == nil { + return + } + h.mu.Lock() + ids := make([]string, 0, len(h.loaded)+len(h.retired)+len(h.loading)) + for id := range h.loaded { + ids = append(ids, id) + } + for id := range h.retired { + ids = append(ids, id) + } + for id := range h.loading { + ids = append(ids, id) + } + h.mu.Unlock() + sort.Strings(ids) + + seen := make(map[string]struct{}, len(ids)) + for _, id := range ids { + if _, ok := seen[id]; ok { + continue + } + seen[id] = struct{}{} + if _, ok := selected[id]; ok { + continue + } + h.detachPlugin(ctx, id) + } +} + +func enabledPluginIDs(files []pluginFile, items map[string]runtimeItemConfig) map[string]struct{} { + ids := make(map[string]struct{}, len(files)) + for _, file := range files { + id := strings.TrimSpace(file.ID) + if id == "" { + continue + } + item, ok := items[id] + if !ok { + item = defaultRuntimeItemConfig(id) + } + if !item.Enabled { + continue + } + ids[id] = struct{}{} + } + return ids +} + // ShutdownAll removes active plugin capabilities and closes all loaded dynamic libraries. func (h *Host) ShutdownAll() { h.ShutdownAllContext(context.Background()) diff --git a/internal/pluginhost/host_test.go b/internal/pluginhost/host_test.go index 7c439d7ee22..9531687b596 100644 --- a/internal/pluginhost/host_test.go +++ b/internal/pluginhost/host_test.go @@ -87,11 +87,98 @@ plugins: if h.PluginRegistered("alpha") { t.Fatal("PluginRegistered(alpha) = true, want false after disable") } + if h.PluginLoaded("alpha") { + t.Fatal("PluginLoaded(alpha) = true, want false after global disable") + } + if lookup := loader.lookups["alpha"]; lookup == nil || lookup.shutdownCalls != 1 { + shutdownCalls := 0 + if lookup != nil { + shutdownCalls = lookup.shutdownCalls + } + t.Fatalf("alpha shutdown calls = %d, want 1 after global disable", shutdownCalls) + } if snap := h.Snapshot(); snap.enabled || len(snap.records) != 0 { t.Fatalf("Snapshot() = %+v, want empty disabled snapshot", snap) } } +func TestHostApplyConfigStopsDisabledPluginAndKeepsSibling(t *testing.T) { + loader := newTestSymbolLoader() + alphaPlugin := &testPlugin{ + registerResult: validTestPlugin("alpha"), + reconfigureResult: validTestPlugin("alpha"), + } + bravoPlugin := &testPlugin{ + registerResult: validTestPlugin("bravo"), + reconfigureResult: validTestPlugin("bravo"), + } + alphaLookup := newTestSymbolLookup(alphaPlugin) + bravoLookup := newTestSymbolLookup(bravoPlugin) + loader.lookups["alpha"] = alphaLookup + loader.lookups["bravo"] = bravoLookup + h := NewForTest(loader) + t.Cleanup(h.ShutdownAll) + + pluginsDir := makePluginDir(t, "alpha", "bravo") + enabledCfg := &config.Config{ + Plugins: config.PluginsConfig{ + Enabled: true, + Dir: pluginsDir, + Configs: enabledPluginConfigs("alpha", "bravo"), + }, + } + h.ApplyConfig(context.Background(), enabledCfg) + if !h.PluginRegistered("alpha") || !h.PluginLoaded("alpha") { + t.Fatal("alpha was not loaded before disable") + } + if !h.PluginRegistered("bravo") || !h.PluginLoaded("bravo") { + t.Fatal("bravo was not loaded before disable") + } + + disabled := false + stillEnabled := true + h.ApplyConfig(context.Background(), &config.Config{ + Plugins: config.PluginsConfig{ + Enabled: true, + Dir: pluginsDir, + Configs: map[string]config.PluginInstanceConfig{ + "alpha": {Enabled: &disabled}, + "bravo": {Enabled: &stillEnabled}, + }, + }, + }) + + if h.PluginRegistered("alpha") { + t.Fatal("PluginRegistered(alpha) = true, want false after disable") + } + if h.PluginLoaded("alpha") { + t.Fatal("PluginLoaded(alpha) = true, want false after disable") + } + if alphaLookup.shutdownCalls != 1 { + t.Fatalf("alpha shutdown calls = %d, want 1", alphaLookup.shutdownCalls) + } + if !h.PluginRegistered("bravo") || !h.PluginLoaded("bravo") { + t.Fatal("bravo was detached while disabling alpha") + } + if bravoLookup.shutdownCalls != 0 { + t.Fatalf("bravo shutdown calls = %d, want 0", bravoLookup.shutdownCalls) + } + + h.ApplyConfig(context.Background(), enabledCfg) + if !h.PluginRegistered("alpha") || !h.PluginLoaded("alpha") { + t.Fatal("alpha was not loaded again after re-enable") + } + if alphaLookup.shutdownCalls != 1 { + t.Fatalf("alpha shutdown calls = %d, want 1 after re-enable", alphaLookup.shutdownCalls) + } + if alphaPlugin.registerCalls != 2 { + t.Fatalf("alpha register calls = %d, want 2", alphaPlugin.registerCalls) + } + if bravoLookup.shutdownCalls != 0 || bravoPlugin.registerCalls != 1 { + t.Fatalf("bravo changed during alpha re-enable: shutdown=%d register=%d", bravoLookup.shutdownCalls, bravoPlugin.registerCalls) + } +} + func TestHostApplyConfig_ExpandsPluginsDirLeadingTilde(t *testing.T) { loader := newTestSymbolLoader() plugin := &testPlugin{ @@ -177,14 +264,15 @@ func TestHostApplyConfig_DefaultDisabledPluginSkipsLoad(t *testing.T) { } } -func TestPluginLoadedTracksLoadedPluginAfterDisabled(t *testing.T) { +func TestHostApplyConfigDisableStopsLoadedPluginHTTPOperations(t *testing.T) { disabled := false loader := newTestSymbolLoader() plugin := &testPlugin{ registerResult: validTestPlugin("alpha"), reconfigureResult: validTestPlugin("alpha"), } - loader.lookups["alpha"] = newTestSymbolLookup(plugin) + lookup := newTestSymbolLookup(plugin) + loader.lookups["alpha"] = lookup h := NewForTest(loader) t.Cleanup(h.ShutdownAll) pluginsDir := makePluginDir(t, "alpha") @@ -206,6 +294,13 @@ func TestPluginLoadedTracksLoadedPluginAfterDisabled(t *testing.T) { if len(h.RegisteredPlugins()) != 1 { t.Fatalf("RegisteredPlugins() len = %d, want 1", len(h.RegisteredPlugins())) } + h.mu.Lock() + instance := h.loaded["alpha"].callbackInstance + h.mu.Unlock() + operationID, operation, openedOperation := h.httpOperations.open("alpha", instance, "", context.Background()) + if !openedOperation { + t.Fatal("failed to open alpha HTTP operation before disable") + } h.ApplyConfig(context.Background(), &config.Config{ Plugins: config.PluginsConfig{ @@ -223,34 +318,25 @@ func TestPluginLoadedTracksLoadedPluginAfterDisabled(t *testing.T) { if h.PluginRegistered("alpha") { t.Fatal("PluginRegistered(alpha) = true, want false after disable") } - if !h.PluginLoaded("alpha") { - t.Fatal("PluginLoaded(alpha) = false, want true while library remains loaded") + if h.PluginLoaded("alpha") { + t.Fatal("PluginLoaded(alpha) = true, want false after disable") } - h.mu.Lock() - instance := h.loaded["alpha"].callbackInstance - h.mu.Unlock() - operationID, operation, openedOperation := h.httpOperations.open("alpha", instance, "", context.Background()) - if !openedOperation { - t.Fatal("failed to open alpha HTTP operation before shutdown") + if lookup.shutdownCalls != 1 { + t.Fatalf("shutdown calls = %d, want 1 after disable", lookup.shutdownCalls) } - - h.ShutdownAll() lateOpenContext := withHostCallbackIdentity(context.Background(), "alpha", instance) if lateOperationID, errOpen := h.openHostHTTPOperation(lateOpenContext, ""); errOpen == nil { h.httpOperations.cancel("alpha", instance, lateOperationID) - t.Fatal("opened an HTTP operation after host shutdown") + t.Fatal("opened an HTTP operation after disable") } if operation.ctx.Err() != context.Canceled { - t.Fatalf("HTTP operation context error = %v, want context.Canceled after shutdown", operation.ctx.Err()) + t.Fatalf("HTTP operation context error = %v, want context.Canceled after disable", operation.ctx.Err()) } h.httpOperations.mu.Lock() _, operationOpen := h.httpOperations.operations[hostHTTPOperationKey{pluginID: "alpha", operationID: operationID}] h.httpOperations.mu.Unlock() if operationOpen { - t.Fatal("HTTP operation remained registered after shutdown") - } - if h.PluginLoaded("alpha") { - t.Fatal("PluginLoaded(alpha) = true, want false after ShutdownAll") + t.Fatal("HTTP operation remained registered after disable") } } From 51bde0ff9609d98108c04235e4426bb42cc4ef23 Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Fri, 9 Oct 2026 10:10:50 +0800 Subject: [PATCH 111/142] fix(codex): preserve resolved upstream model in direct openai image requests - Check configured upstream models and aliases before normalizing direct OpenAI image model names - Support requested model resolution across JSON and multipart image payloads Closes: #6458 --- .../runtime/executor/codex_openai_images.go | 49 ++++- .../executor/codex_openai_images_test.go | 167 ++++++++++++++++++ 2 files changed, 209 insertions(+), 7 deletions(-) diff --git a/internal/runtime/executor/codex_openai_images.go b/internal/runtime/executor/codex_openai_images.go index 98e7c48e8ef..fd30f0170a2 100644 --- a/internal/runtime/executor/codex_openai_images.go +++ b/internal/runtime/executor/codex_openai_images.go @@ -321,7 +321,7 @@ func (e *CodexExecutor) executeOpenAIImageStream(ctx context.Context, auth *clip } func (e *CodexExecutor) executeDirectOpenAIImage(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, endpointPath string) (resp cliproxyexecutor.Response, err error) { - body, contentType, model, errPrepare := codexPrepareDirectOpenAIImageBody(req, opts, false) + body, contentType, model, errPrepare := e.prepareDirectOpenAIImageBody(auth, req, opts, false) if errPrepare != nil { return resp, errPrepare } @@ -388,7 +388,7 @@ func (e *CodexExecutor) executeDirectOpenAIImage(ctx context.Context, auth *clip } func (e *CodexExecutor) executeDirectOpenAIImageStream(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, endpointPath string) (_ *cliproxyexecutor.StreamResult, err error) { - body, contentType, model, errPrepare := codexPrepareDirectOpenAIImageBody(req, opts, true) + body, contentType, model, errPrepare := e.prepareDirectOpenAIImageBody(auth, req, opts, true) if errPrepare != nil { return nil, errPrepare } @@ -490,7 +490,7 @@ func (e *CodexExecutor) executeDirectOpenAIImageStream(ctx context.Context, auth } func codexDirectOpenAIImageEndpoint(req cliproxyexecutor.Request, opts cliproxyexecutor.Options) string { - if codexDirectOpenAIImageModel(req) == "" { + if codexDirectOpenAIImageRouteModel(req, opts) == "" { return "" } path := helps.PayloadRequestPath(opts) @@ -503,8 +503,8 @@ func codexDirectOpenAIImageEndpoint(req cliproxyexecutor.Request, opts cliproxye return "" } -func codexPrepareDirectOpenAIImageBody(req cliproxyexecutor.Request, opts cliproxyexecutor.Options, stream bool) ([]byte, string, string, error) { - model := codexDirectOpenAIImageModel(req) +func (e *CodexExecutor) prepareDirectOpenAIImageBody(auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, stream bool) ([]byte, string, string, error) { + model := e.directOpenAIImageModel(auth, req, opts) if model == "" { return nil, "", "", fmt.Errorf("unsupported direct OpenAI image model %q", req.Model) } @@ -656,8 +656,14 @@ func codexOpenAIImageEditFormJSONPath(key string) string { } } -func codexDirectOpenAIImageModel(req cliproxyexecutor.Request) string { - for _, model := range []string{gjson.GetBytes(req.Payload, "model").String(), req.Model} { +func codexDirectOpenAIImageRouteModel(req cliproxyexecutor.Request, opts cliproxyexecutor.Options) string { + // Multipart handlers supply the requested model separately from the raw form. + requestedModel := helps.PayloadRequestedModel(opts, "") + payloadModel := "" + if json.Valid(req.Payload) { + payloadModel = gjson.GetBytes(req.Payload, "model").String() + } + for _, model := range []string{requestedModel, payloadModel, req.Model} { baseModel := codexOpenAIImageBaseModel(model) if codexIsDirectOpenAIImageModel(baseModel) { return baseModel @@ -666,6 +672,35 @@ func codexDirectOpenAIImageModel(req cliproxyexecutor.Request) string { return "" } +func (e *CodexExecutor) directOpenAIImageModel(auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) string { + routeModel := codexDirectOpenAIImageRouteModel(req, opts) + if routeModel == "" { + return "" + } + model := strings.TrimSpace(thinking.ParseSuffix(req.Model).ModelName) + if model == "" { + return routeModel + } + + // Explicit upstream names are not routing prefixes, even when their base is builtin. + if entry := e.resolveCodexConfig(auth); entry != nil { + for _, configured := range entry.Models { + name := strings.TrimSpace(configured.Name) + if name == "" { + name = strings.TrimSpace(configured.Alias) + } + if strings.EqualFold(strings.TrimSpace(thinking.ParseSuffix(name).ModelName), model) { + return model + } + } + } + // Preserve legacy builtin route normalization only without an explicit upstream. + if baseModel := codexOpenAIImageBaseModel(model); codexIsDirectOpenAIImageModel(baseModel) { + return baseModel + } + return model +} + func codexOpenAIImageBaseModel(model string) string { model = strings.TrimSpace(thinking.ParseSuffix(model).ModelName) if idx := strings.LastIndex(model, "/"); idx >= 0 && idx < len(model)-1 { diff --git a/internal/runtime/executor/codex_openai_images_test.go b/internal/runtime/executor/codex_openai_images_test.go index 5bcc970546c..e138e5d343e 100644 --- a/internal/runtime/executor/codex_openai_images_test.go +++ b/internal/runtime/executor/codex_openai_images_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "fmt" "io" "mime/multipart" "net/http" @@ -38,6 +39,172 @@ func codexOpenAIImageTestOptions(path string, stream bool) cliproxyexecutor.Opti } } +func TestCodexImagePayloadPreservesResolvedAlias(t *testing.T) { + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprintf("stream=%v", stream), func(t *testing.T) { + req := cliproxyexecutor.Request{ + Model: "openai/gpt-image-2-cpr", + Payload: []byte(`{"model":"gpt-image-2","prompt":"diagnostic"}`), + } + body, _, _, errPrepare := NewCodexExecutor(&config.Config{}).prepareDirectOpenAIImageBody(nil, req, codexOpenAIImageTestOptions(codexImagesGenerationsPath, stream), stream) + if errPrepare != nil { + t.Fatal(errPrepare) + } + if got := gjson.GetBytes(body, "model").String(); got != "openai/gpt-image-2-cpr" { + t.Fatalf("upstream model = %q, want %q", got, "openai/gpt-image-2-cpr") + } + }) + } +} + +func TestCodexImageResolvedModelOnWire(t *testing.T) { + for _, tc := range []struct { + name string + requested string + resolved string + configured string + want string + payloadRule string + }{ + {"custom upstream", "gpt-image-2", "openai/gpt-image-2-cpr", "openai/gpt-image-2-cpr", "openai/gpt-image-2-cpr", ""}, + {"prefixed builtin upstream", "gpt-image-2", "openai/gpt-image-2", "openai/gpt-image-2", "openai/gpt-image-2", ""}, + {"case sensitive upstream", "gpt-image-2", "OpenAI/GPT-Image-2", "OpenAI/GPT-Image-2", "OpenAI/GPT-Image-2", ""}, + {"other builtin upstream", "gpt-image-2", "gpt-image-1.5", "gpt-image-1.5", "gpt-image-1.5", ""}, + {"configured routing-like prefix", "gpt-image-2", "codex/gpt-image-2", "codex/gpt-image-2", "codex/gpt-image-2", ""}, + {"configured name requested directly", "openai/gpt-image-2", "openai/gpt-image-2", "openai/gpt-image-2", "openai/gpt-image-2", ""}, + {"routing and thinking suffix", "tenant/gpt-image-2(high)", "OpenAI/GPT-Image-2(high)", "OpenAI/GPT-Image-2", "OpenAI/GPT-Image-2", ""}, + {"legacy builtin prefix", "codex/gpt-image-1.5(high)", "codex/gpt-image-1.5(high)", "", "gpt-image-1.5", ""}, + {"legacy builtin case", "CODEX/GPT-Image-2(high)", "CODEX/GPT-Image-2(high)", "", "gpt-image-2", ""}, + {"final payload override", "gpt-image-2", "openai/gpt-image-2-cpr", "openai/gpt-image-2-cpr", "policy/image-model", "override"}, + {"final payload filter", "gpt-image-2", "openai/gpt-image-2-cpr", "openai/gpt-image-2-cpr", "", "filter"}, + } { + for _, format := range []string{"generation JSON", "edit JSON", "edit multipart"} { + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/%s/stream=%v", tc.name, format, stream), func(t *testing.T) { + var gotBody []byte + var gotPath, gotContentType string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotPath, gotContentType = r.URL.Path, r.Header.Get("Content-Type") + var errRead error + gotBody, errRead = io.ReadAll(r.Body) + if errRead != nil { + t.Errorf("read upstream body: %v", errRead) + w.WriteHeader(http.StatusBadRequest) + return + } + if stream { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "event: image_generation.completed\ndata: {\"type\":\"image_generation.completed\",\"b64_json\":\"AA==\"}\n\n") + } else { + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"created":1713833628,"data":[{"b64_json":"AA=="}]}`) + } + })) + defer server.Close() + + cfg := &config.Config{} + if tc.configured != "" { + cfg.CodexKey = []config.CodexKey{{ + APIKey: "codex-token", BaseURL: server.URL, Prefix: "tenant", + Models: []config.CodexModel{{Name: tc.configured, Alias: "gpt-image-2"}}, + }} + } + models := []config.PayloadModelRule{{ + Name: "openai/gpt-image-2-cpr", Protocol: "openai", + Match: []map[string]any{{"model": "openai/gpt-image-2-cpr"}}, + }} + if tc.payloadRule == "override" { + cfg.Payload.Override = []config.PayloadRule{ + {Models: models, Params: map[string]any{"model": "policy/image-model"}}, + {Models: []config.PayloadModelRule{{Name: "*"}}, Params: map[string]any{"audit.-1": "once"}}, + } + } else if tc.payloadRule == "filter" { + cfg.Payload.Filter = []config.PayloadFilterRule{{Models: models, Params: []string{"model"}}} + } + path, wantPath := codexImagesGenerationsPath, "/images/generations" + if format != "generation JSON" { + path, wantPath = codexImagesEditsPath, "/images/edits" + } + opts := codexOpenAIImageTestOptions(path, stream) + opts.Metadata[cliproxyexecutor.RequestedModelMetadataKey] = tc.requested + payload, errMarshal := json.Marshal(map[string]any{ + "model": tc.requested, "prompt": "diagnostic", "stream": !stream, + "images": []map[string]string{{"file_id": "source-image"}}, + }) + if errMarshal != nil { + t.Fatal(errMarshal) + } + if format == "edit multipart" { + var form bytes.Buffer + writer := multipart.NewWriter(&form) + for key, value := range map[string]string{"model": tc.requested, "prompt": "diagnostic", "stream": "true"} { + if errWrite := writer.WriteField(key, value); errWrite != nil { + t.Fatal(errWrite) + } + } + part, errCreate := writer.CreateFormFile("image", "source.png") + if errCreate != nil { + t.Fatal(errCreate) + } + if _, errWrite := part.Write([]byte("png-data")); errWrite != nil { + t.Fatal(errWrite) + } + if errClose := writer.Close(); errClose != nil { + t.Fatal(errClose) + } + payload = form.Bytes() + opts.Headers = http.Header{"Content-Type": []string{writer.FormDataContentType()}} + } + req := cliproxyexecutor.Request{Model: tc.resolved, Payload: payload} + executor := NewCodexExecutor(cfg) + auth := newCodexOpenAIImageTestAuth(server.URL) + if stream { + result, errStream := executor.ExecuteStream(context.Background(), auth, req, opts) + if errStream != nil { + t.Fatal(errStream) + } + for chunk := range result.Chunks { + if chunk.Err != nil { + t.Fatal(chunk.Err) + } + } + } else if _, errExecute := executor.Execute(context.Background(), auth, req, opts); errExecute != nil { + t.Fatal(errExecute) + } + if gotPath != wantPath { + t.Fatalf("upstream path = %q, want %q", gotPath, wantPath) + } + if gotContentType != "application/json" || !json.Valid(gotBody) { + t.Fatalf("invalid upstream JSON: Content-Type=%q body=%s", gotContentType, gotBody) + } + if got := gjson.GetBytes(gotBody, "model").String(); got != tc.want { + t.Errorf("upstream model = %q, want %q; body=%s", got, tc.want, gotBody) + } + if tc.payloadRule == "override" && gjson.GetBytes(gotBody, "audit").Raw != `["once"]` { + t.Errorf("payload override must run exactly once: %s", gotBody) + } + if tc.payloadRule == "filter" && gjson.GetBytes(gotBody, "model").Exists() { + t.Errorf("filtered model must not be restored: %s", gotBody) + } + if got := gjson.GetBytes(gotBody, "prompt").String(); got != "diagnostic" { + t.Errorf("prompt = %q, want diagnostic", got) + } + if flag := gjson.GetBytes(gotBody, "stream"); flag.Exists() != stream || flag.Bool() != stream { + t.Errorf("unexpected stream flag: %s", gotBody) + } + if format == "edit multipart" { + if got := gjson.GetBytes(gotBody, "images.0.image_url").String(); got != "data:application/octet-stream;base64,cG5nLWRhdGE=" { + t.Errorf("image URL = %q, want original file data URL", got) + } + } else if format == "edit JSON" && gjson.GetBytes(gotBody, "images.0.file_id").String() != "source-image" { + t.Errorf("original image missing: %s", gotBody) + } + }) + } + } + } +} + func TestCodexExecutorDirectOpenAIImageGenerationUsesImagesEndpoint(t *testing.T) { var gotPath string var gotAuth string From 9a7db8e36daea095bfdd4deff7dd60cad6a6d13a Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Fri, 9 Oct 2026 12:50:06 +0800 Subject: [PATCH 112/142] fix(claude): defer stream message delta emission to trailing usage chunk - Avoid emitting `message_delta` early when chunks contain a `finish_reason` alongside preliminary usage - Preserve authoritative token metrics such as `cached_tokens` received in trailing usage-only chunks Closes: #6475 --- .../openai/claude/openai_claude_response.go | 8 +- .../claude/openai_claude_response_test.go | 75 +++++++++++++++++++ 2 files changed, 80 insertions(+), 3 deletions(-) diff --git a/internal/translator/openai/claude/openai_claude_response.go b/internal/translator/openai/claude/openai_claude_response.go index a7fdad25db6..d416d41690f 100644 --- a/internal/translator/openai/claude/openai_claude_response.go +++ b/internal/translator/openai/claude/openai_claude_response.go @@ -404,12 +404,14 @@ func convertOpenAIStreamingChunkToAnthropic(rawJSON []byte, param *ConvertOpenAI } // Emit message_delta and message_stop only when generation is finished: - // 1. Upstream provided a finish_reason, or - // 2. Upstream sent a trailing usage-only chunk (choices array is empty or absent) after content/tools started. + // - Upstream sent a trailing usage-only chunk (choices array is empty or absent) after content/tools started, or + // - Upstream sent [DONE] (handled in convertOpenAIDoneToAnthropic). + // Content chunks with finish_reason and preliminary usage must not emit message_delta early, + // because authoritative token counts (such as cached_tokens) can arrive in the trailing usage-only chunk. isTrailingUsageChunk := hasUsage && !root.Get("choices.0").Exists() && (param.FinishReason != "" || param.SawToolCall || param.TextContentBlockStarted || param.ThinkingContentBlockStarted || param.ContentAccumulator.Len() > 0 || len(param.InterleavedContentChunks) > 0) - if !param.MessageDeltaSent && (param.FinishReason != "" || isTrailingUsageChunk) && hasUsage { + if !param.MessageDeltaSent && isTrailingUsageChunk { finalizeOpenAIAnthropicContentBlocks(param, &results) emitAnthropicMessageDelta(param, &results, param.UsageInputTokens, param.UsageOutputTokens, param.UsageCachedTokens, param.UsageCacheWriteTokens) emitMessageStopIfNeeded(param, &results) diff --git a/internal/translator/openai/claude/openai_claude_response_test.go b/internal/translator/openai/claude/openai_claude_response_test.go index b655e3b5505..6dc811238a7 100644 --- a/internal/translator/openai/claude/openai_claude_response_test.go +++ b/internal/translator/openai/claude/openai_claude_response_test.go @@ -123,6 +123,81 @@ func TestStreaming_LateUsageOnlyDoesNotEmitAfterMessageStop(t *testing.T) { } } +func TestStreaming_SplitUsageFinishReasonThenTrailingUsageChunk_PreservesCachedTokens(t *testing.T) { + tests := []struct { + name string + firstChunks []string + finishChunk string + wantStopType string + }{ + { + name: "text content with stop finish_reason", + firstChunks: []string{ + `{"id":"c1","model":"m","choices":[{"index":0,"delta":{"role":"assistant","content":"hello"},"finish_reason":null}]}`, + }, + finishChunk: `{"id":"c1","model":"m","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":140025,"completion_tokens":741,"total_tokens":140766,"prompt_tokens_details":{}}}`, + wantStopType: "end_turn", + }, + { + name: "tool call with tool_calls finish_reason", + firstChunks: []string{ + `{"id":"c1","model":"m","choices":[{"index":0,"delta":{"role":"assistant","tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"a.txt\"}"}}]},"finish_reason":null}]}`, + }, + finishChunk: `{"id":"c1","model":"m","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":140025,"completion_tokens":741,"total_tokens":140766,"prompt_tokens_details":{}}}`, + wantStopType: "tool_use", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + trailingUsageChunk := `{"id":"c1","model":"m","choices":[],"usage":{"prompt_tokens":140025,"completion_tokens":741,"total_tokens":140766,"prompt_tokens_details":{"cached_tokens":139136}}}` + allChunks := append(append([]string{}, tt.firstChunks...), tt.finishChunk, trailingUsageChunk) + + events := runStream(t, streamReq, allChunks...) + + if got := countByType(events, "message_delta"); got != 1 { + t.Fatalf("expected exactly one message_delta, got %d (events=%+v)", got, events) + } + if got := countByType(events, "message_stop"); got != 1 { + t.Fatalf("expected exactly one message_stop, got %d (events=%+v)", got, events) + } + if len(events) == 0 || events[len(events)-1].Type != "message_stop" { + t.Fatalf("message_stop must be the last semantic event (events=%+v)", events) + } + + var deltaPayload string + for _, e := range events { + if e.Type == "message_delta" { + deltaPayload = e.Payload + break + } + } + if deltaPayload == "" { + t.Fatalf("missing message_delta event in %+v", events) + } + + if gotStop := gjson.Get(deltaPayload, "delta.stop_reason").String(); gotStop != tt.wantStopType { + t.Fatalf("stop_reason = %q, want %q", gotStop, tt.wantStopType) + } + + cached := gjson.Get(deltaPayload, "usage.cache_read_input_tokens").Int() + if cached != 139136 { + t.Fatalf("expected cache_read_input_tokens = 139136, got %d (payload=%s)", cached, deltaPayload) + } + + input := gjson.Get(deltaPayload, "usage.input_tokens").Int() + if input != 889 { + t.Fatalf("expected deducted input_tokens = 889, got %d (payload=%s)", input, deltaPayload) + } + + output := gjson.Get(deltaPayload, "usage.output_tokens").Int() + if output != 741 { + t.Fatalf("expected output_tokens = 741, got %d (payload=%s)", output, deltaPayload) + } + }) + } +} + func TestConvertOpenAIResponseToClaude_StreamIgnoresNullToolNameDelta(t *testing.T) { originalRequest := []byte(streamReq) var param any From c332bc900e8d28d513eeb907def808cd52cae580 Mon Sep 17 00:00:00 2001 From: Supra4E8C Date: Fri, 9 Oct 2026 16:55:57 +0800 Subject: [PATCH 113/142] feat(ui): let ToggleSwitch take an external label and show keyboard focus Accept an id and aria-describedby so a separate