refactor(open-sse): translator DRY + schema enums, bug fixes, dead code cleanup

- Bug B1-B7: media UI m.kind||m.type, serviceKinds, gemini mediaPriority, schema kind, models/info lookup by kind
- Dead code D1-D6: safeParseJSON, drop PROVIDER_ENDPOINTS, orphan fetcher, GITHUB_CONFIG derive, getProviderConfig internal, legacy kiro file
- Translator concerns: toOpenAIUsage, toOpenAIFinish (gemini/kiro/ollama + fix kiro tool finish), thinking effort maps
- Reorg helpers/ → concerns/ (logic) + formats/ (per-format) + schema/ (pure enums: roles/blocks/finishReasons/defaults)
- Wire ~280 hardcoded role/block/finish/default literals to schema enums across 20+ files
- collapseTextParts + extractTextContent dedup
- Normalize translator fn names to openaiToXRequest / xToOpenAIResponse
- Golden tests lock behavior; 0 regression (byte-for-byte providers/alias, 26=26 known fails)

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
decolua 2026-06-14 18:49:38 +07:00
parent c5c9061eac
commit d3f61aac2f
145 changed files with 1252 additions and 1160 deletions

View file

@ -5,7 +5,7 @@ import { OAUTH_ENDPOINTS, ANTIGRAVITY_HEADERS, INTERNAL_REQUEST_HEADER, AG_DEFAU
import { HTTP_STATUS } from "../config/runtimeConfig.js"; import { HTTP_STATUS } from "../config/runtimeConfig.js";
import { deriveSessionId } from "../utils/sessionManager.js"; import { deriveSessionId } from "../utils/sessionManager.js";
import { proxyAwareFetch } from "../utils/proxyFetch.js"; import { proxyAwareFetch } from "../utils/proxyFetch.js";
import { cleanJSONSchemaForAntigravity } from "../translator/helpers/geminiHelper.js"; import { cleanJSONSchemaForAntigravity } from "../translator/formats/gemini.js";
// Sanitize function name: Gemini requires [a-zA-Z_][a-zA-Z0-9_.:\-]{0,63} // Sanitize function name: Gemini requires [a-zA-Z_][a-zA-Z0-9_.:\-]{0,63}
function sanitizeFunctionName(name) { function sanitizeFunctionName(name) {

View file

@ -6,8 +6,8 @@ import {
refreshProviderCredentials, refreshProviderCredentials,
shouldRefreshCredentials, shouldRefreshCredentials,
} from "../services/oauthCredentialManager.js"; } from "../services/oauthCredentialManager.js";
import { normalizeResponsesInput } from "../translator/helpers/responsesApiHelper.js"; import { normalizeResponsesInput } from "../translator/formats/responsesApi.js";
import { fetchImageAsBase64 } from "../translator/helpers/imageHelper.js"; import { fetchImageAsBase64 } from "../translator/concerns/image.js";
import { getModelUpstreamId } from "../config/providerModels.js"; import { getModelUpstreamId } from "../config/providerModels.js";
import { getConsistentMachineId } from "../shared/machineId.js"; import { getConsistentMachineId } from "../shared/machineId.js";
import { DEFAULT_RETRY_CONFIG, resolveRetryEntry } from "../config/runtimeConfig.js"; import { DEFAULT_RETRY_CONFIG, resolveRetryEntry } from "../config/runtimeConfig.js";

View file

@ -1,7 +1,7 @@
import { randomUUID } from "crypto"; import { randomUUID } from "crypto";
import { BaseExecutor } from "./base.js"; import { BaseExecutor } from "./base.js";
import { PROVIDERS } from "../config/providers.js"; import { PROVIDERS } from "../config/providers.js";
import { convertCommandCodeToOpenAI } from "../translator/response/commandcode-to-openai.js"; import { commandCodeToOpenAIResponse } from "../translator/response/commandcode-to-openai.js";
import { SSE_DONE } from "../utils/sseConstants.js"; import { SSE_DONE } from "../utils/sseConstants.js";
/** /**
@ -71,13 +71,13 @@ function wrapNdjsonAsOpenAISse(originalResponse, model) {
const trimmed = line.trim(); const trimmed = line.trim();
if (!trimmed) continue; if (!trimmed) continue;
// Translate AI SDK v5 NDJSON line to one or more OpenAI chunks // Translate AI SDK v5 NDJSON line to one or more OpenAI chunks
emitChunks(convertCommandCodeToOpenAI(trimmed, state), controller); emitChunks(commandCodeToOpenAIResponse(trimmed, state), controller);
} }
}, },
flush(controller) { flush(controller) {
const trimmed = buffer.trim(); const trimmed = buffer.trim();
if (trimmed) { if (trimmed) {
emitChunks(convertCommandCodeToOpenAI(trimmed, state), controller); emitChunks(commandCodeToOpenAIResponse(trimmed, state), controller);
} }
controller.enqueue(encoder.encode(SSE_DONE)); controller.enqueue(encoder.encode(SSE_DONE));
}, },

View file

@ -142,7 +142,7 @@ export class CursorExecutor extends BaseExecutor {
transformRequest(model, body, stream, credentials) { transformRequest(model, body, stream, credentials) {
// Messages are already translated by chatCore (claude→openai→cursor) // Messages are already translated by chatCore (claude→openai→cursor)
// Do NOT call buildCursorRequest again — double-translation drops tool_results // Do NOT call openaiToCursorRequest again — double-translation drops tool_results
const messages = body.messages || []; const messages = body.messages || [];
const tools = body.tools || []; const tools = body.tools || [];
const reasoningEffort = body.reasoning_effort || null; const reasoningEffort = body.reasoning_effort || null;

View file

@ -1,7 +1,7 @@
import { detectFormat, getTargetFormat } from "../services/provider.js"; import { detectFormat, getTargetFormat } from "../services/provider.js";
import { translateRequest } from "../translator/index.js"; import { translateRequest } from "../translator/index.js";
import { FORMATS } from "../translator/formats.js"; import { FORMATS } from "../translator/formats.js";
import { normalizeClaudePassthrough } from "../translator/helpers/claudeHelper.js"; import { normalizeClaudePassthrough } from "../translator/formats/claude.js";
import { COLORS } from "../utils/stream.js"; import { COLORS } from "../utils/stream.js";
import { createStreamController } from "../utils/streamHandler.js"; import { createStreamController } from "../utils/streamHandler.js";
import { refreshWithRetry } from "../services/tokenRefresh.js"; import { refreshWithRetry } from "../services/tokenRefresh.js";

View file

@ -4,7 +4,7 @@
*/ */
import { handleChatCore } from "./chatCore.js"; import { handleChatCore } from "./chatCore.js";
import { convertResponsesApiFormat } from "../translator/helpers/responsesApiHelper.js"; import { convertResponsesApiFormat } from "../translator/formats/responsesApi.js";
import { createResponsesApiTransformStream } from "../transformer/responsesTransformer.js"; import { createResponsesApiTransformStream } from "../transformer/responsesTransformer.js";
import { convertResponsesStreamToJson } from "../transformer/streamToJsonConverter.js"; import { convertResponsesStreamToJson } from "../transformer/streamToJsonConverter.js";
import { SSE_HEADERS_CORS } from "../utils/sseConstants.js"; import { SSE_HEADERS_CORS } from "../utils/sseConstants.js";

View file

@ -30,7 +30,6 @@ export {
// Services // Services
export { export {
detectFormat, detectFormat,
getProviderConfig,
getTargetFormat getTargetFormat
} from "./services/provider.js"; } from "./services/provider.js";

View file

@ -1,8 +1,8 @@
import { deriveModelName } from "./namePatterns.js"; import { deriveModelName } from "./namePatterns.js";
// Model defaults centralized (was scattered as `m.type || "llm"`, `quotaFamily || "normal"`, etc.) // Model defaults centralized (was scattered as `m.kind || "llm"`, `quotaFamily || "normal"`, etc.)
export const MODEL_DEFAULTS = { export const MODEL_DEFAULTS = {
type: "llm", kind: "llm",
quotaFamily: "normal", quotaFamily: "normal",
strip: [], strip: [],
targetFormat: null targetFormat: null
@ -16,9 +16,9 @@ export function normalizeModel(raw) {
return { ...model, name: deriveModelName(model.id) }; return { ...model, name: deriveModelName(model.id) };
} }
// Resolve a single field with its default (keeps accessor call-sites one-liners) // Resolve model kind with default (accepts legacy `type` field)
export function modelType(model) { export function modelKind(model) {
return model?.type || MODEL_DEFAULTS.type; return model?.kind || model?.type || MODEL_DEFAULTS.kind;
} }
export function modelQuotaFamily(model) { export function modelQuotaFamily(model) {
return model?.quotaFamily || MODEL_DEFAULTS.quotaFamily; return model?.quotaFamily || MODEL_DEFAULTS.quotaFamily;

View file

@ -1,5 +1,6 @@
export default { export default {
id: "alicode-intl", id: "alicode-intl",
priority: 10,
alias: "alicode-intl", alias: "alicode-intl",
display: { display: {
name: "Alibaba Intl", name: "Alibaba Intl",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "alicode", id: "alicode",
priority: 20,
alias: "alicode", alias: "alicode",
display: { display: {
name: "Alibaba", name: "Alibaba",

View file

@ -2,6 +2,7 @@ import { CLAUDE_API_HEADERS } from "../shared.js";
export default { export default {
id: "anthropic", id: "anthropic",
priority: 30,
alias: "anthropic", alias: "anthropic",
display: { display: {
name: "Anthropic", name: "Anthropic",

View file

@ -3,6 +3,7 @@ import { ANTIGRAVITY_OAUTH_CLIENT } from "../shared.js";
export default { export default {
id: "antigravity", id: "antigravity",
priority: 20,
alias: "ag", alias: "ag",
uiAlias: "ag", uiAlias: "ag",
display: { display: {

View file

@ -1,5 +1,6 @@
export default { export default {
id: "assemblyai", id: "assemblyai",
priority: 30,
alias: "assemblyai", alias: "assemblyai",
aliases: [ aliases: [
"aai", "aai",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "azure", id: "azure",
priority: 40,
alias: "azure", alias: "azure",
display: { display: {
name: "Azure OpenAI", name: "Azure OpenAI",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "black-forest-labs", id: "black-forest-labs",
priority: 50,
alias: "black-forest-labs", alias: "black-forest-labs",
aliases: [ aliases: [
"bfl", "bfl",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "blackbox", id: "blackbox",
priority: 50,
alias: "blackbox", alias: "blackbox",
aliases: [ aliases: [
"bb", "bb",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "byteplus", id: "byteplus",
priority: 150,
alias: "byteplus", alias: "byteplus",
aliases: [ aliases: [
"bpm", "bpm",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "cerebras", id: "cerebras",
priority: 60,
alias: "cerebras", alias: "cerebras",
display: { display: {
name: "Cerebras", name: "Cerebras",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "chutes", id: "chutes",
priority: 70,
alias: "chutes", alias: "chutes",
aliases: [ aliases: [
"ch", "ch",

View file

@ -2,6 +2,7 @@ import { CLAUDE_CLI_SPOOF_HEADERS } from "../shared.js";
export default { export default {
id: "claude", id: "claude",
priority: 10,
alias: "cc", alias: "cc",
uiAlias: "cc", uiAlias: "cc",
display: { display: {

View file

@ -1,5 +1,6 @@
export default { export default {
id: "cline", id: "cline",
priority: 70,
alias: "cl", alias: "cl",
uiAlias: "cl", uiAlias: "cl",
display: { display: {

View file

@ -1,5 +1,7 @@
export default { export default {
id: "cloudflare-ai", id: "cloudflare-ai",
priority: 20,
hasFree: true,
alias: "cloudflare-ai", alias: "cloudflare-ai",
aliases: [ aliases: [
"cf", "cf",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "codebuddy", id: "codebuddy",
priority: 80,
display: { display: {
name: "CodeBuddy", name: "CodeBuddy",
icon: "smart_toy", icon: "smart_toy",

View file

@ -2,6 +2,7 @@ import { withCodexReviewModels } from "../models/helpers.js";
export default { export default {
id: "codex", id: "codex",
priority: 30,
alias: "cx", alias: "cx",
uiAlias: "cx", uiAlias: "cx",
display: { display: {

View file

@ -1,5 +1,6 @@
export default { export default {
id: "cohere", id: "cohere",
priority: 90,
alias: "cohere", alias: "cohere",
display: { display: {
name: "Cohere", name: "Cohere",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "comfyui", id: "comfyui",
priority: 120,
alias: "comfyui", alias: "comfyui",
display: { display: {
name: "ComfyUI", name: "ComfyUI",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "commandcode", id: "commandcode",
priority: 100,
alias: "commandcode", alias: "commandcode",
aliases: [ aliases: [
"cmc", "cmc",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "cursor", id: "cursor",
priority: 40,
alias: "cu", alias: "cu",
uiAlias: "cu", uiAlias: "cu",
display: { display: {

View file

@ -1,5 +1,6 @@
export default { export default {
id: "deepgram", id: "deepgram",
priority: 20,
alias: "deepgram", alias: "deepgram",
aliases: [ aliases: [
"dg", "dg",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "deepseek", id: "deepseek",
priority: 110,
alias: "deepseek", alias: "deepseek",
aliases: [ aliases: [
"ds", "ds",

View file

@ -1,5 +1,7 @@
export default { export default {
id: "fal-ai", id: "fal-ai",
priority: 90,
hasFree: true,
alias: "fal-ai", alias: "fal-ai",
aliases: [ aliases: [
"fal", "fal",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "fireworks", id: "fireworks",
priority: 50,
alias: "fireworks", alias: "fireworks",
display: { display: {
name: "Fireworks AI", name: "Fireworks AI",
@ -23,5 +24,6 @@ export default {
{ id: "accounts/fireworks/models/qwen3-235b-a22b", name: "Qwen3 235B" }, { id: "accounts/fireworks/models/qwen3-235b-a22b", name: "Qwen3 235B" },
{ id: "nomic-ai/nomic-embed-text-v1.5", name: "Nomic Embed Text v1.5", kind: "embedding" }, { id: "nomic-ai/nomic-embed-text-v1.5", name: "Nomic Embed Text v1.5", kind: "embedding" },
], ],
serviceKinds: ["llm", "embedding"],
embeddingConfig: { baseUrl: "https://api.fireworks.ai/inference/v1/embeddings" }, embeddingConfig: { baseUrl: "https://api.fireworks.ai/inference/v1/embeddings" },
}; };

View file

@ -2,6 +2,8 @@ import { GOOGLE_OAUTH_CLIENT } from "../shared.js";
export default { export default {
id: "gemini-cli", id: "gemini-cli",
priority: 130,
hasFree: true,
alias: "gc", alias: "gc",
uiAlias: "gc", uiAlias: "gc",
display: { display: {

View file

@ -2,6 +2,8 @@ import { GOOGLE_OAUTH_CLIENT } from "../shared.js";
export default { export default {
id: "gemini", id: "gemini",
priority: 10,
hasFree: true,
alias: "gemini", alias: "gemini",
display: { display: {
name: "Gemini", name: "Gemini",
@ -12,9 +14,9 @@ export default {
notice: { notice: {
apiKeyUrl: "https://aistudio.google.com/app/apikey", apiKeyUrl: "https://aistudio.google.com/app/apikey",
}, },
mediaPriority: 1,
}, },
category: "freeTier", category: "freeTier",
mediaPriority: 1,
transport: { transport: {
baseUrl: "https://generativelanguage.googleapis.com/v1beta/models", baseUrl: "https://generativelanguage.googleapis.com/v1beta/models",
format: "gemini", format: "gemini",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "github", id: "github",
priority: 50,
alias: "gh", alias: "gh",
uiAlias: "gh", uiAlias: "gh",
display: { display: {

View file

@ -1,5 +1,6 @@
export default { export default {
id: "gitlab", id: "gitlab",
priority: 120,
display: { display: {
name: "GitLab Duo", name: "GitLab Duo",
icon: "code", icon: "code",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "glm-cn", id: "glm-cn",
priority: 130,
alias: "glm-cn", alias: "glm-cn",
display: { display: {
name: "GLM (China)", name: "GLM (China)",

View file

@ -2,6 +2,7 @@ import { CLAUDE_API_HEADERS } from "../shared.js";
export default { export default {
id: "glm", id: "glm",
priority: 140,
alias: "glm", alias: "glm",
display: { display: {
name: "GLM Coding", name: "GLM Coding",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "grok-web", id: "grok-web",
priority: 150,
alias: "grok-web", alias: "grok-web",
aliases: [ aliases: [
"gw", "gw",

View file

@ -1,5 +1,7 @@
export default { export default {
id: "groq", id: "groq",
priority: 60,
hasFree: true,
alias: "groq", alias: "groq",
display: { display: {
name: "Groq", name: "Groq",

View file

@ -1,5 +1,7 @@
export default { export default {
id: "huggingface", id: "huggingface",
priority: 70,
hasFree: true,
alias: "huggingface", alias: "huggingface",
aliases: [ aliases: [
"hf", "hf",
@ -27,5 +29,6 @@ export default {
{ id: "openai/whisper-large-v3", name: "Whisper Large v3 (HF)", params: ["language"], kind: "stt" }, { id: "openai/whisper-large-v3", name: "Whisper Large v3 (HF)", params: ["language"], kind: "stt" },
{ id: "openai/whisper-small", name: "Whisper Small (HF)", params: ["language"], kind: "stt" }, { id: "openai/whisper-small", name: "Whisper Small (HF)", params: ["language"], kind: "stt" },
], ],
serviceKinds: ["image", "stt"],
imageConfig: { baseUrl: "https://api-inference.huggingface.co/models" }, imageConfig: { baseUrl: "https://api-inference.huggingface.co/models" },
}; };

View file

@ -1,5 +1,6 @@
export default { export default {
id: "hyperbolic", id: "hyperbolic",
priority: 160,
alias: "hyperbolic", alias: "hyperbolic",
aliases: [ aliases: [
"hyp", "hyp",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "iflow", id: "iflow",
priority: 170,
alias: "if", alias: "if",
display: { display: {
name: "iFlow AI", name: "iFlow AI",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "kilocode", id: "kilocode",
priority: 60,
alias: "kc", alias: "kc",
uiAlias: "kc", uiAlias: "kc",
display: { display: {

View file

@ -2,6 +2,7 @@ import { CLAUDE_API_HEADERS, KIMI_CODING_BASE_URL } from "../shared.js";
export default { export default {
id: "kimi-coding", id: "kimi-coding",
priority: 180,
alias: "kmc", alias: "kmc",
display: { display: {
name: "Kimi Coding", name: "Kimi Coding",

View file

@ -2,6 +2,7 @@ import { CLAUDE_API_HEADERS, KIMI_CODING_BASE_URL } from "../shared.js";
export default { export default {
id: "kimi", id: "kimi",
priority: 170,
alias: "kimi", alias: "kimi",
display: { display: {
name: "Kimi", name: "Kimi",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "kiro", id: "kiro",
priority: 80,
alias: "kr", alias: "kr",
uiAlias: "kr", uiAlias: "kr",
display: { display: {

View file

@ -1,5 +1,7 @@
export default { export default {
id: "mimo-free", id: "mimo-free",
priority: 120,
hasFree: true,
alias: "mmf", alias: "mmf",
uiAlias: "mmf", uiAlias: "mmf",
display: { display: {

View file

@ -2,6 +2,7 @@ import { CLAUDE_API_HEADERS } from "../shared.js";
export default { export default {
id: "minimax-cn", id: "minimax-cn",
priority: 190,
alias: "minimax-cn", alias: "minimax-cn",
display: { display: {
name: "Minimax (China)", name: "Minimax (China)",

View file

@ -2,6 +2,7 @@ import { CLAUDE_API_HEADERS } from "../shared.js";
export default { export default {
id: "minimax", id: "minimax",
priority: 90,
alias: "minimax", alias: "minimax",
display: { display: {
name: "Minimax Coding", name: "Minimax Coding",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "mistral", id: "mistral",
priority: 80,
alias: "mistral", alias: "mistral",
display: { display: {
name: "Mistral", name: "Mistral",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "mmf", id: "mmf",
priority: 200,
display: { display: {
name: "MMF", name: "MMF",
icon: "hub", icon: "hub",

View file

@ -1,5 +1,7 @@
export default { export default {
id: "nanobanana", id: "nanobanana",
priority: 80,
hasFree: true,
alias: "nanobanana", alias: "nanobanana",
aliases: [ aliases: [
"nb", "nb",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "nebius", id: "nebius",
priority: 70,
alias: "nebius", alias: "nebius",
display: { display: {
name: "Nebius AI", name: "Nebius AI",
@ -21,5 +22,6 @@ export default {
{ id: "meta-llama/Llama-3.3-70B-Instruct", name: "Llama 3.3 70B Instruct" }, { id: "meta-llama/Llama-3.3-70B-Instruct", name: "Llama 3.3 70B Instruct" },
{ id: "Qwen/Qwen3-Embedding-8B", name: "Qwen3 Embedding 8B", kind: "embedding" }, { id: "Qwen/Qwen3-Embedding-8B", name: "Qwen3 Embedding 8B", kind: "embedding" },
], ],
serviceKinds: ["llm", "embedding"],
embeddingConfig: { baseUrl: "https://api.tokenfactory.nebius.com/v1/embeddings" }, embeddingConfig: { baseUrl: "https://api.tokenfactory.nebius.com/v1/embeddings" },
}; };

View file

@ -1,5 +1,7 @@
export default { export default {
id: "nvidia", id: "nvidia",
priority: 100,
hasFree: true,
alias: "nvidia", alias: "nvidia",
display: { display: {
name: "NVIDIA NIM", name: "NVIDIA NIM",

View file

@ -1,5 +1,7 @@
export default { export default {
id: "ollama-local", id: "ollama-local",
priority: 50,
hasFree: true,
alias: "ollama-local", alias: "ollama-local",
display: { display: {
name: "Ollama Local", name: "Ollama Local",

View file

@ -1,5 +1,7 @@
export default { export default {
id: "ollama", id: "ollama",
priority: 40,
hasFree: true,
alias: "ollama", alias: "ollama",
display: { display: {
name: "Ollama Cloud", name: "Ollama Cloud",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "openai", id: "openai",
priority: 30,
alias: "openai", alias: "openai",
display: { display: {
name: "OpenAI", name: "OpenAI",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "opencode-go", id: "opencode-go",
priority: 210,
alias: "opencode-go", alias: "opencode-go",
aliases: [ aliases: [
"ocg", "ocg",

View file

@ -1,5 +1,7 @@
export default { export default {
id: "opencode", id: "opencode",
priority: 110,
hasFree: true,
alias: "oc", alias: "oc",
uiAlias: "oc", uiAlias: "oc",
display: { display: {

View file

@ -1,5 +1,7 @@
export default { export default {
id: "openrouter", id: "openrouter",
priority: 30,
hasFree: true,
alias: "openrouter", alias: "openrouter",
display: { display: {
name: "OpenRouter", name: "OpenRouter",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "perplexity-web", id: "perplexity-web",
priority: 220,
alias: "perplexity-web", alias: "perplexity-web",
aliases: [ aliases: [
"pw", "pw",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "perplexity", id: "perplexity",
priority: 180,
alias: "perplexity", alias: "perplexity",
aliases: [ aliases: [
"pplx", "pplx",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "qoder", id: "qoder",
priority: 230,
alias: "qd", alias: "qd",
uiAlias: "qd", uiAlias: "qd",
display: { display: {

View file

@ -1,5 +1,6 @@
export default { export default {
id: "qwen", id: "qwen",
priority: 240,
alias: "qw", alias: "qw",
display: { display: {
name: "Qwen Code", name: "Qwen Code",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "recraft", id: "recraft",
priority: 70,
alias: "recraft", alias: "recraft",
display: { display: {
name: "Recraft", name: "Recraft",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "runwayml", id: "runwayml",
priority: 80,
alias: "runwayml", alias: "runwayml",
aliases: [ aliases: [
"runway", "runway",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "sdwebui", id: "sdwebui",
priority: 110,
alias: "sdwebui", alias: "sdwebui",
display: { display: {
name: "SD WebUI", name: "SD WebUI",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "siliconflow", id: "siliconflow",
priority: 250,
alias: "siliconflow", alias: "siliconflow",
display: { display: {
name: "SiliconFlow", name: "SiliconFlow",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "stability-ai", id: "stability-ai",
priority: 60,
alias: "stability-ai", alias: "stability-ai",
aliases: [ aliases: [
"stability", "stability",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "together", id: "together",
priority: 60,
alias: "together", alias: "together",
display: { display: {
name: "Together AI", name: "Together AI",
@ -25,5 +26,6 @@ export default {
{ id: "BAAI/bge-large-en-v1.5", name: "BGE Large EN v1.5", kind: "embedding" }, { id: "BAAI/bge-large-en-v1.5", name: "BGE Large EN v1.5", kind: "embedding" },
{ id: "togethercomputer/m2-bert-80M-8k-retrieval", name: "M2 BERT 80M 8K", kind: "embedding" }, { id: "togethercomputer/m2-bert-80M-8k-retrieval", name: "M2 BERT 80M 8K", kind: "embedding" },
], ],
serviceKinds: ["llm", "embedding"],
embeddingConfig: { baseUrl: "https://api.together.xyz/v1/embeddings" }, embeddingConfig: { baseUrl: "https://api.together.xyz/v1/embeddings" },
}; };

View file

@ -1,5 +1,6 @@
export default { export default {
id: "vercel-ai-gateway", id: "vercel-ai-gateway",
priority: 160,
alias: "vercel-ai-gateway", alias: "vercel-ai-gateway",
aliases: [ aliases: [
"vercel", "vercel",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "vertex-partner", id: "vertex-partner",
priority: 260,
alias: "vertex-partner", alias: "vertex-partner",
aliases: [ aliases: [
"vxp", "vxp",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "vertex", id: "vertex",
priority: 140,
alias: "vertex", alias: "vertex",
aliases: [ aliases: [
"vx", "vx",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "volcengine-ark", id: "volcengine-ark",
priority: 270,
alias: "volcengine-ark", alias: "volcengine-ark",
aliases: [ aliases: [
"ark", "ark",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "voyage-ai", id: "voyage-ai",
priority: 40,
alias: "voyage-ai", alias: "voyage-ai",
uiAlias: "voyage", uiAlias: "voyage",
display: { display: {

View file

@ -1,5 +1,6 @@
export default { export default {
id: "xai", id: "xai",
priority: 280,
alias: "xai", alias: "xai",
display: { display: {
name: "xAI (Grok)", name: "xAI (Grok)",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "xiaomi-mimo", id: "xiaomi-mimo",
priority: 290,
alias: "xiaomi-mimo", alias: "xiaomi-mimo",
aliases: [ aliases: [
"mimo", "mimo",

View file

@ -1,5 +1,6 @@
export default { export default {
id: "xiaomi-tokenplan", id: "xiaomi-tokenplan",
priority: 300,
alias: "xiaomi-tokenplan", alias: "xiaomi-tokenplan",
aliases: [ aliases: [
"xmtp", "xmtp",

View file

@ -104,8 +104,8 @@ export function detectFormat(body) {
return "openai"; return "openai";
} }
// Get provider config // Get provider config (internal — no external runtime consumer)
export function getProviderConfig(provider) { function getProviderConfig(provider) {
if (isOpenAICompatible(provider)) { if (isOpenAICompatible(provider)) {
const apiType = getOpenAICompatibleType(provider); const apiType = getOpenAICompatibleType(provider);
return { return {

View file

@ -6,15 +6,15 @@ import { CLIENT_METADATA, getPlatformUserAgent } from "../config/appConstants.js
import { proxyAwareFetch } from "../utils/proxyFetch.js"; import { proxyAwareFetch } from "../utils/proxyFetch.js";
import { resolveDefaultProfileArn } from "../config/kiroConstants.js"; import { resolveDefaultProfileArn } from "../config/kiroConstants.js";
import { ANTIGRAVITY_OAUTH_CLIENT, ANTHROPIC_API_VERSION } from "../providers/shared.js"; import { ANTIGRAVITY_OAUTH_CLIENT, ANTHROPIC_API_VERSION } from "../providers/shared.js";
import { PROVIDERS } from "../providers/index.js"; import { PROVIDERS, PROVIDER_OAUTH } from "../providers/index.js";
// usage endpoints: single source from registry transport.usage // usage endpoints: single source from registry transport.usage
const U = (id) => PROVIDERS[id]?.usage || {}; const U = (id) => PROVIDERS[id]?.usage || {};
// GitHub API config // GitHub API config — single source from registry oauth block
const GITHUB_CONFIG = { const GITHUB_CONFIG = {
apiVersion: "2022-11-28", apiVersion: PROVIDER_OAUTH.github?.apiVersion,
userAgent: "GitHubCopilotChat/0.26.7", userAgent: PROVIDER_OAUTH.github?.userAgent,
}; };
// GLM quota endpoints (region-aware) — url from registry transport.usage // GLM quota endpoints (region-aware) — url from registry transport.usage

View file

@ -0,0 +1,63 @@
// Concern #6: finish_reason / stop_reason mapping.
// One entry per direction; switch by special format, default handles common providers.
import { OPENAI_FINISH, CLAUDE_STOP, GEMINI_FINISH } from "../schema/finishReasons.js";
// upstream finish/stop reason → OpenAI finish_reason
export function toOpenAIFinish(reason, format) {
switch (format) {
case "claude":
switch (reason) {
case CLAUDE_STOP.END_TURN: return OPENAI_FINISH.STOP;
case CLAUDE_STOP.MAX_TOKENS: return OPENAI_FINISH.LENGTH;
case CLAUDE_STOP.TOOL_USE: return OPENAI_FINISH.TOOL_CALLS;
case CLAUDE_STOP.STOP_SEQUENCE: return OPENAI_FINISH.STOP;
default: return OPENAI_FINISH.STOP;
}
case "commandcode":
switch (reason) {
case "stop": return OPENAI_FINISH.STOP;
case "length": return OPENAI_FINISH.LENGTH;
case "tool-calls":
case "tool_use": return OPENAI_FINISH.TOOL_CALLS;
case "content-filter": return OPENAI_FINISH.CONTENT_FILTER;
case "error": return OPENAI_FINISH.STOP;
default: return reason || OPENAI_FINISH.STOP;
}
case "gemini":
switch (String(reason).toUpperCase()) {
case GEMINI_FINISH.STOP: return OPENAI_FINISH.STOP;
case GEMINI_FINISH.MAX_TOKENS: return OPENAI_FINISH.LENGTH;
case GEMINI_FINISH.SAFETY:
case GEMINI_FINISH.RECITATION:
case GEMINI_FINISH.BLOCKLIST:
case GEMINI_FINISH.PROHIBITED_CONTENT: return OPENAI_FINISH.CONTENT_FILTER;
default: return OPENAI_FINISH.STOP;
}
case "kiro":
case "ollama":
switch (reason) {
case "tool_calls":
case "tool_use": return OPENAI_FINISH.TOOL_CALLS;
case "length":
case "max_tokens": return OPENAI_FINISH.LENGTH;
default: return OPENAI_FINISH.STOP;
}
default:
return reason || OPENAI_FINISH.STOP;
}
}
// OpenAI finish_reason → upstream stop reason
export function fromOpenAIFinish(reason, format) {
switch (format) {
case "claude":
switch (reason) {
case OPENAI_FINISH.STOP: return CLAUDE_STOP.END_TURN;
case OPENAI_FINISH.LENGTH: return CLAUDE_STOP.MAX_TOKENS;
case OPENAI_FINISH.TOOL_CALLS: return CLAUDE_STOP.TOOL_USE;
default: return CLAUDE_STOP.END_TURN;
}
default:
return reason;
}
}

View file

@ -1,43 +0,0 @@
// Concern #6: finish_reason / stop_reason mapping.
// One entry per direction; switch by special format, default handles common providers.
// upstream finish/stop reason → OpenAI finish_reason
export function toOpenAIFinish(reason, format) {
switch (format) {
case "claude":
switch (reason) {
case "end_turn": return "stop";
case "max_tokens": return "length";
case "tool_use": return "tool_calls";
case "stop_sequence": return "stop";
default: return "stop";
}
case "commandcode":
switch (reason) {
case "stop": return "stop";
case "length": return "length";
case "tool-calls":
case "tool_use": return "tool_calls";
case "content-filter": return "content_filter";
case "error": return "stop";
default: return reason || "stop";
}
default:
return reason || "stop";
}
}
// OpenAI finish_reason → upstream stop reason
export function fromOpenAIFinish(reason, format) {
switch (format) {
case "claude":
switch (reason) {
case "stop": return "end_turn";
case "length": return "max_tokens";
case "tool_calls": return "tool_use";
default: return "end_turn";
}
default:
return reason;
}
}

View file

@ -0,0 +1,7 @@
import { OPENAI_BLOCK } from "../schema/index.js";
// Collapse an OpenAI content-part array: a lone text part becomes a plain string,
// otherwise the array is returned as-is. Matches existing translator behavior.
export function collapseTextParts(parts) {
return parts.length === 1 && parts[0].type === OPENAI_BLOCK.TEXT ? parts[0].text : parts;
}

View file

@ -1,6 +1,8 @@
import { ROLE } from "../schema/index.js";
// Build OpenAI delta carrying reasoning_content (optional leading assistant role) // Build OpenAI delta carrying reasoning_content (optional leading assistant role)
export function reasoningDelta(text, withRole = false) { export function reasoningDelta(text, withRole = false) {
return withRole return withRole
? { role: "assistant", reasoning_content: text } ? { role: ROLE.ASSISTANT, reasoning_content: text }
: { reasoning_content: text }; : { reasoning_content: text };
} }

View file

@ -0,0 +1,29 @@
// Concern: reasoning_effort ↔ provider-native thinking config.
// Each provider expresses "how much to think" differently — centralize the maps here.
// Streaming reasoning delta shape lives in reasoning.js; this file is request-side config only.
// OpenAI reasoning_effort → Claude thinking.budget_tokens
const EFFORT_TO_BUDGET = { none: 0, low: 4096, medium: 8192, high: 16384, xhigh: 32768 };
// Returns budget_tokens for a reasoning_effort, or undefined if unknown effort.
// 0 means "no thinking" (caller skips enabling); undefined means "effort not recognized".
export function effortToBudget(effort) {
if (!effort) return undefined;
return EFFORT_TO_BUDGET[String(effort).toLowerCase()];
}
// OpenAI reasoning_effort → Gemini thinkingLevel (gemini-3 enum: minimal|low|medium|high).
// Gemini 3 cannot fully disable thinking; "none"/"off" map to "minimal" (closest to off).
export function effortToThinkingLevel(effort) {
const e = String(effort).toLowerCase().trim();
return e === "none" || e === "off" ? "minimal" : e;
}
// Gemini thinkingBudget (numeric) → OpenAI reasoning_effort (antigravity reverse map).
// Returns null when budget <= 0 (no reasoning).
export function budgetToEffort(budget) {
if (!budget || budget <= 0) return null;
if (budget <= 2048) return "low";
if (budget <= 16384) return "medium";
return "high";
}

View file

@ -0,0 +1,60 @@
// Build OpenAI usage object. Caller computes prompt/completion/total (provider math).
// Optional details added only when > 0 (matches existing claude/gemini/codex behavior).
export function buildUsage({ promptTokens, completionTokens, totalTokens, cachedTokens = 0, cacheCreationTokens = 0, reasoningTokens = 0 }) {
const usage = { prompt_tokens: promptTokens, completion_tokens: completionTokens, total_tokens: totalTokens };
if (cachedTokens > 0 || cacheCreationTokens > 0) {
usage.prompt_tokens_details = {};
if (cachedTokens > 0) usage.prompt_tokens_details.cached_tokens = cachedTokens;
if (cacheCreationTokens > 0) usage.prompt_tokens_details.cache_creation_tokens = cacheCreationTokens;
}
if (reasoningTokens > 0) {
usage.completion_tokens_details = { reasoning_tokens: reasoningTokens };
}
return usage;
}
const n = (v) => (typeof v === "number" ? v : 0);
// Per-provider raw token field-map + math. Returns buildUsage() args (NOT the usage object).
// Keeps each provider's exact semantics: claude/gemini fold cache+reasoning, others don't.
const USAGE_EXTRACTORS = {
claude(raw) {
const input = n(raw.input_tokens), output = n(raw.output_tokens);
const cacheRead = n(raw.cache_read_input_tokens), cacheCreate = n(raw.cache_creation_input_tokens);
const prompt = input + cacheRead + cacheCreate;
return { promptTokens: prompt, completionTokens: output, totalTokens: prompt + output, cachedTokens: cacheRead, cacheCreationTokens: cacheCreate };
},
gemini(raw) {
const cached = n(raw.cachedContentTokenCount);
const prompt = n(raw.promptTokenCount);
const thoughts = n(raw.thoughtsTokenCount);
const total = n(raw.totalTokenCount);
let candidates = n(raw.candidatesTokenCount);
// Fallback: derive candidates from total when upstream omits it
if (candidates === 0 && total > 0) {
candidates = total - prompt - thoughts;
if (candidates < 0) candidates = 0;
}
return { promptTokens: prompt, completionTokens: candidates + thoughts, totalTokens: total, cachedTokens: cached, reasoningTokens: thoughts };
},
kiro(raw) {
const input = n(raw.inputTokens), output = n(raw.outputTokens);
return { promptTokens: input, completionTokens: output, totalTokens: input + output };
},
ollama(raw) {
const input = n(raw.prompt_eval_count), output = n(raw.eval_count);
return { promptTokens: input, completionTokens: output, totalTokens: input + output };
},
commandcode(raw) {
const input = n(raw.inputTokens), output = n(raw.outputTokens);
const total = typeof raw.totalTokens === "number" ? raw.totalTokens : input + output;
return { promptTokens: input, completionTokens: output, totalTokens: total };
},
};
// Convert provider-native usage object → OpenAI usage. Returns null if no extractor/raw.
export function toOpenAIUsage(raw, kind) {
const extract = USAGE_EXTRACTORS[kind];
if (!extract || !raw || typeof raw !== "object") return null;
return buildUsage(extract(raw));
}

View file

@ -1,6 +1,7 @@
// Claude helper functions for translator // Claude helper functions for translator
import { DEFAULT_THINKING_CLAUDE_SIGNATURE } from "../../config/defaultThinkingSignature.js"; import { DEFAULT_THINKING_CLAUDE_SIGNATURE } from "../../config/defaultThinkingSignature.js";
import { adjustMaxTokens } from "./maxTokensHelper.js"; import { ROLE, CLAUDE_BLOCK } from "../schema/index.js";
import { adjustMaxTokens } from "./maxTokens.js";
import { applyCloaking } from "../../utils/claudeCloaking.js"; import { applyCloaking } from "../../utils/claudeCloaking.js";
import { deriveSessionId } from "../../utils/sessionManager.js"; import { deriveSessionId } from "../../utils/sessionManager.js";
import { PROVIDERS } from "../../providers/index.js"; import { PROVIDERS } from "../../providers/index.js";
@ -10,9 +11,9 @@ export function hasValidContent(msg) {
if (typeof msg.content === "string" && msg.content.trim()) return true; if (typeof msg.content === "string" && msg.content.trim()) return true;
if (Array.isArray(msg.content)) { if (Array.isArray(msg.content)) {
return msg.content.some(block => return msg.content.some(block =>
(block.type === "text" && block.text?.trim()) || (block.type === CLAUDE_BLOCK.TEXT && block.text?.trim()) ||
block.type === "tool_use" || block.type === CLAUDE_BLOCK.TOOL_USE ||
block.type === "tool_result" block.type === CLAUDE_BLOCK.TOOL_RESULT
); );
} }
return false; return false;
@ -26,18 +27,18 @@ export function fixToolUseOrdering(messages) {
// Pass 1: Fix assistant messages with tool_use - remove text after tool_use // Pass 1: Fix assistant messages with tool_use - remove text after tool_use
for (const msg of messages) { for (const msg of messages) {
if (msg.role === "assistant" && Array.isArray(msg.content)) { if (msg.role === ROLE.ASSISTANT && Array.isArray(msg.content)) {
const hasToolUse = msg.content.some(b => b.type === "tool_use"); const hasToolUse = msg.content.some(b => b.type === CLAUDE_BLOCK.TOOL_USE);
if (hasToolUse) { if (hasToolUse) {
// Keep only: thinking blocks + tool_use blocks (remove text blocks after tool_use) // Keep only: thinking blocks + tool_use blocks (remove text blocks after tool_use)
const newContent = []; const newContent = [];
let foundToolUse = false; let foundToolUse = false;
for (const block of msg.content) { for (const block of msg.content) {
if (block.type === "tool_use") { if (block.type === CLAUDE_BLOCK.TOOL_USE) {
foundToolUse = true; foundToolUse = true;
newContent.push(block); newContent.push(block);
} else if (block.type === "thinking" || block.type === "redacted_thinking") { } else if (block.type === CLAUDE_BLOCK.THINKING || block.type === CLAUDE_BLOCK.REDACTED_THINKING) {
newContent.push(block); newContent.push(block);
} else if (!foundToolUse) { } else if (!foundToolUse) {
// Keep text blocks BEFORE tool_use // Keep text blocks BEFORE tool_use
@ -59,17 +60,17 @@ export function fixToolUseOrdering(messages) {
if (last && last.role === msg.role) { if (last && last.role === msg.role) {
// Merge content arrays // Merge content arrays
const lastContent = Array.isArray(last.content) ? last.content : [{ type: "text", text: last.content }]; const lastContent = Array.isArray(last.content) ? last.content : [{ type: CLAUDE_BLOCK.TEXT, text: last.content }];
const msgContent = Array.isArray(msg.content) ? msg.content : [{ type: "text", text: msg.content }]; const msgContent = Array.isArray(msg.content) ? msg.content : [{ type: CLAUDE_BLOCK.TEXT, text: msg.content }];
// Put tool_result first, then other content // Put tool_result first, then other content
const toolResults = [...lastContent.filter(b => b.type === "tool_result"), ...msgContent.filter(b => b.type === "tool_result")]; const toolResults = [...lastContent.filter(b => b.type === CLAUDE_BLOCK.TOOL_RESULT), ...msgContent.filter(b => b.type === CLAUDE_BLOCK.TOOL_RESULT)];
const otherContent = [...lastContent.filter(b => b.type !== "tool_result"), ...msgContent.filter(b => b.type !== "tool_result")]; const otherContent = [...lastContent.filter(b => b.type !== CLAUDE_BLOCK.TOOL_RESULT), ...msgContent.filter(b => b.type !== CLAUDE_BLOCK.TOOL_RESULT)];
last.content = [...toolResults, ...otherContent]; last.content = [...toolResults, ...otherContent];
} else { } else {
// Ensure content is array // Ensure content is array
const content = Array.isArray(msg.content) ? msg.content : [{ type: "text", text: msg.content }]; const content = Array.isArray(msg.content) ? msg.content : [{ type: CLAUDE_BLOCK.TEXT, text: msg.content }];
merged.push({ role: msg.role, content: [...content] }); merged.push({ role: msg.role, content: [...content] });
} }
} }
@ -97,13 +98,13 @@ export function normalizeClaudePassthrough(body, model = "") {
const systemBlocks = []; const systemBlocks = [];
const messages = []; const messages = [];
for (const msg of body.messages) { for (const msg of body.messages) {
if (msg.role === "system") { if (msg.role === ROLE.SYSTEM) {
const text = typeof msg.content === "string" const text = typeof msg.content === "string"
? msg.content ? msg.content
: Array.isArray(msg.content) : Array.isArray(msg.content)
? msg.content.map(b => (typeof b === "string" ? b : b?.text || "")).join("\n") ? msg.content.map(b => (typeof b === "string" ? b : b?.text || "")).join("\n")
: ""; : "";
if (text.trim()) systemBlocks.push({ type: "text", text }); if (text.trim()) systemBlocks.push({ type: CLAUDE_BLOCK.TEXT, text });
continue; continue;
} }
messages.push(msg); messages.push(msg);
@ -191,7 +192,7 @@ export function prepareClaudeRequest(body, provider = null, apiKey = null, conne
if (!lastAssistantProcessed && msg.content.length > 0) { if (!lastAssistantProcessed && msg.content.length > 0) {
for (let j = msg.content.length - 1; j >= 0; j--) { for (let j = msg.content.length - 1; j >= 0; j--) {
const block = msg.content[j]; const block = msg.content[j];
if (block.type !== "thinking" && block.type !== "redacted_thinking") { if (block.type !== CLAUDE_BLOCK.THINKING && block.type !== CLAUDE_BLOCK.REDACTED_THINKING) {
block.cache_control = { type: "ephemeral" }; block.cache_control = { type: "ephemeral" };
break; break;
} }
@ -206,17 +207,17 @@ export function prepareClaudeRequest(body, provider = null, apiKey = null, conne
// Always replace signature for all thinking blocks // Always replace signature for all thinking blocks
for (const block of msg.content) { for (const block of msg.content) {
if (block.type === "thinking" || block.type === "redacted_thinking") { if (block.type === CLAUDE_BLOCK.THINKING || block.type === CLAUDE_BLOCK.REDACTED_THINKING) {
block.signature = DEFAULT_THINKING_CLAUDE_SIGNATURE; block.signature = DEFAULT_THINKING_CLAUDE_SIGNATURE;
hasThinking = true; hasThinking = true;
} }
if (block.type === "tool_use") hasToolUse = true; if (block.type === CLAUDE_BLOCK.TOOL_USE) hasToolUse = true;
} }
// Add thinking block if thinking enabled + has tool_use but no thinking // Add thinking block if thinking enabled + has tool_use but no thinking
if (thinkingEnabled && !hasThinking && hasToolUse) { if (thinkingEnabled && !hasThinking && hasToolUse) {
msg.content.unshift({ msg.content.unshift({
type: "thinking", type: CLAUDE_BLOCK.THINKING,
thinking: ".", thinking: ".",
signature: DEFAULT_THINKING_CLAUDE_SIGNATURE signature: DEFAULT_THINKING_CLAUDE_SIGNATURE
}); });

View file

@ -1,6 +1,7 @@
// Gemini helper functions for translator // Gemini helper functions for translator
import { safeParseJSON } from "./jsonUtil.js"; import { safeParseJSON } from "../concerns/json.js";
import { OPENAI_BLOCK } from "../schema/index.js";
// Unsupported JSON Schema constraints that should be removed for Antigravity // Unsupported JSON Schema constraints that should be removed for Antigravity
export const UNSUPPORTED_SCHEMA_CONSTRAINTS = [ export const UNSUPPORTED_SCHEMA_CONSTRAINTS = [
@ -41,9 +42,9 @@ export function convertOpenAIContentToParts(content) {
parts.push({ text: content }); parts.push({ text: content });
} else if (Array.isArray(content)) { } else if (Array.isArray(content)) {
for (const item of content) { for (const item of content) {
if (item.type === "text") { if (item.type === OPENAI_BLOCK.TEXT) {
parts.push({ text: item.text }); parts.push({ text: item.text });
} else if (item.type === "image_url" && item.image_url?.url?.startsWith("data:")) { } else if (item.type === OPENAI_BLOCK.IMAGE_URL && item.image_url?.url?.startsWith("data:")) {
const url = item.image_url.url; const url = item.image_url.url;
const commaIndex = url.indexOf(","); const commaIndex = url.indexOf(",");
if (commaIndex !== -1) { if (commaIndex !== -1) {
@ -55,17 +56,17 @@ export function convertOpenAIContentToParts(content) {
inlineData: { mime_type: mimeType, data: data } inlineData: { mime_type: mimeType, data: data }
}); });
} }
} else if (item.type === "image_url" && item.image_url?.url && (item.image_url.url.startsWith("http://") || item.image_url.url.startsWith("https://"))) { } else if (item.type === OPENAI_BLOCK.IMAGE_URL && item.image_url?.url && (item.image_url.url.startsWith("http://") || item.image_url.url.startsWith("https://"))) {
parts.push({ parts.push({
fileData: { fileUri: item.image_url.url, mimeType: "image/*" } fileData: { fileUri: item.image_url.url, mimeType: "image/*" }
}); });
} else if (item.type === "input_audio" && item.input_audio?.data) { } else if (item.type === OPENAI_BLOCK.INPUT_AUDIO && item.input_audio?.data) {
const format = item.input_audio.format || "wav"; const format = item.input_audio.format || "wav";
const mimeType = format === "mp3" ? "audio/mpeg" : `audio/${format}`; const mimeType = format === "mp3" ? "audio/mpeg" : `audio/${format}`;
parts.push({ parts.push({
inlineData: { mime_type: mimeType, data: item.input_audio.data } inlineData: { mime_type: mimeType, data: item.input_audio.data }
}); });
} else if (item.type === "audio_url" && item.audio_url?.url?.startsWith("data:")) { } else if (item.type === OPENAI_BLOCK.AUDIO_URL && item.audio_url?.url?.startsWith("data:")) {
const url = item.audio_url.url; const url = item.audio_url.url;
const commaIndex = url.indexOf(","); const commaIndex = url.indexOf(",");
if (commaIndex !== -1) { if (commaIndex !== -1) {
@ -84,10 +85,10 @@ export function convertOpenAIContentToParts(content) {
} }
// Extract text content from OpenAI content // Extract text content from OpenAI content
export function extractTextContent(content) { export function extractTextContent(content, separator = "") {
if (typeof content === "string") return content; if (typeof content === "string") return content;
if (Array.isArray(content)) { if (Array.isArray(content)) {
return content.filter(c => c.type === "text").map(c => c.text).join(""); return content.filter(c => c.type === OPENAI_BLOCK.TEXT).map(c => c.text).join(separator);
} }
return ""; return "";
} }

View file

@ -1,8 +1,8 @@
// OpenAI helper functions for translator // OpenAI helper functions for translator
import { ROLE, OPENAI_BLOCK, CLAUDE_BLOCK, VALID_OPENAI_CONTENT_TYPES, VALID_OPENAI_MESSAGE_TYPES } from "../schema/index.js";
// Valid OpenAI content block types // Re-export valid-type lists (moved to schema/blocks.js) to keep existing importers working.
export const VALID_OPENAI_CONTENT_TYPES = ["text", "image_url", "image", "input_audio", "audio_url"]; export { VALID_OPENAI_CONTENT_TYPES, VALID_OPENAI_MESSAGE_TYPES };
export const VALID_OPENAI_MESSAGE_TYPES = ["text", "image_url", "image", "tool_calls", "tool_result"];
// Filter messages to OpenAI standard format // Filter messages to OpenAI standard format
// Remove: thinking, redacted_thinking, signature, and other non-OpenAI blocks // Remove: thinking, redacted_thinking, signature, and other non-OpenAI blocks
@ -11,13 +11,13 @@ export function filterToOpenAIFormat(body) {
body.messages = body.messages.map(msg => { body.messages = body.messages.map(msg => {
// Normalize developer role to system (many providers don't support developer) // Normalize developer role to system (many providers don't support developer)
if (msg.role === "developer") msg = { ...msg, role: "system" }; if (msg.role === ROLE.DEVELOPER) msg = { ...msg, role: ROLE.SYSTEM };
// Keep tool messages as-is (OpenAI format) // Keep tool messages as-is (OpenAI format)
if (msg.role === "tool") return msg; if (msg.role === ROLE.TOOL) return msg;
// Keep assistant messages with tool_calls as-is // Keep assistant messages with tool_calls as-is
if (msg.role === "assistant" && msg.tool_calls) return msg; if (msg.role === ROLE.ASSISTANT && msg.tool_calls) return msg;
// Handle string content // Handle string content
if (typeof msg.content === "string") return msg; if (typeof msg.content === "string") return msg;
@ -28,17 +28,17 @@ export function filterToOpenAIFormat(body) {
for (const block of msg.content) { for (const block of msg.content) {
// Skip thinking blocks // Skip thinking blocks
if (block.type === "thinking" || block.type === "redacted_thinking") continue; if (block.type === CLAUDE_BLOCK.THINKING || block.type === CLAUDE_BLOCK.REDACTED_THINKING) continue;
// Only keep valid OpenAI content types // Only keep valid OpenAI content types
if (VALID_OPENAI_CONTENT_TYPES.includes(block.type)) { if (VALID_OPENAI_CONTENT_TYPES.includes(block.type)) {
// Remove signature field if exists // Remove signature field if exists
const { signature, cache_control, ...cleanBlock } = block; const { signature, cache_control, ...cleanBlock } = block;
filteredContent.push(cleanBlock); filteredContent.push(cleanBlock);
} else if (block.type === "tool_use") { } else if (block.type === CLAUDE_BLOCK.TOOL_USE) {
// Convert tool_use to tool_calls format (handled separately) // Convert tool_use to tool_calls format (handled separately)
continue; continue;
} else if (block.type === "tool_result") { } else if (block.type === CLAUDE_BLOCK.TOOL_RESULT) {
// Keep tool_result but clean it // Keep tool_result but clean it
const { signature, cache_control, ...cleanBlock } = block; const { signature, cache_control, ...cleanBlock } = block;
filteredContent.push(cleanBlock); filteredContent.push(cleanBlock);
@ -47,7 +47,7 @@ export function filterToOpenAIFormat(body) {
// If all content was filtered, add empty text // If all content was filtered, add empty text
if (filteredContent.length === 0) { if (filteredContent.length === 0) {
filteredContent.push({ type: "text", text: "" }); filteredContent.push({ type: OPENAI_BLOCK.TEXT, text: "" });
} }
return { ...msg, content: filteredContent }; return { ...msg, content: filteredContent };
@ -59,15 +59,15 @@ export function filterToOpenAIFormat(body) {
// Filter out messages with only empty text (but NEVER filter tool messages) // Filter out messages with only empty text (but NEVER filter tool messages)
body.messages = body.messages.filter(msg => { body.messages = body.messages.filter(msg => {
// Always keep tool messages // Always keep tool messages
if (msg.role === "tool") return true; if (msg.role === ROLE.TOOL) return true;
// Always keep assistant messages with tool_calls // Always keep assistant messages with tool_calls
if (msg.role === "assistant" && msg.tool_calls) return true; if (msg.role === ROLE.ASSISTANT && msg.tool_calls) return true;
if (typeof msg.content === "string") return msg.content.trim() !== ""; if (typeof msg.content === "string") return msg.content.trim() !== "";
if (Array.isArray(msg.content)) { if (Array.isArray(msg.content)) {
return msg.content.some(b => return msg.content.some(b =>
(b.type === "text" && b.text?.trim()) || (b.type === OPENAI_BLOCK.TEXT && b.text?.trim()) ||
b.type !== "text" b.type !== OPENAI_BLOCK.TEXT
); );
} }
return true; return true;
@ -82,12 +82,12 @@ export function filterToOpenAIFormat(body) {
if (body.tools && Array.isArray(body.tools) && body.tools.length > 0) { if (body.tools && Array.isArray(body.tools) && body.tools.length > 0) {
body.tools = body.tools.map(tool => { body.tools = body.tools.map(tool => {
// Already OpenAI format // Already OpenAI format
if (tool.type === "function" && tool.function) return tool; if (tool.type === OPENAI_BLOCK.FUNCTION && tool.function) return tool;
// Claude format: {name, description, input_schema} // Claude format: {name, description, input_schema}
if (tool.name && (tool.input_schema || tool.description)) { if (tool.name && (tool.input_schema || tool.description)) {
return { return {
type: "function", type: OPENAI_BLOCK.FUNCTION,
function: { function: {
name: tool.name, name: tool.name,
description: String(tool.description || ""), description: String(tool.description || ""),
@ -99,7 +99,7 @@ export function filterToOpenAIFormat(body) {
// Gemini format: {functionDeclarations: [{name, description, parameters}]} // Gemini format: {functionDeclarations: [{name, description, parameters}]}
if (tool.functionDeclarations && Array.isArray(tool.functionDeclarations)) { if (tool.functionDeclarations && Array.isArray(tool.functionDeclarations)) {
return tool.functionDeclarations.map(fn => ({ return tool.functionDeclarations.map(fn => ({
type: "function", type: OPENAI_BLOCK.FUNCTION,
function: { function: {
name: fn.name, name: fn.name,
description: String(fn.description || ""), description: String(fn.description || ""),
@ -121,7 +121,7 @@ export function filterToOpenAIFormat(body) {
} else if (choice.type === "any") { } else if (choice.type === "any") {
body.tool_choice = "required"; body.tool_choice = "required";
} else if (choice.type === "tool" && choice.name) { } else if (choice.type === "tool" && choice.name) {
body.tool_choice = { type: "function", function: { name: choice.name } }; body.tool_choice = { type: OPENAI_BLOCK.FUNCTION, function: { name: choice.name } };
} }
} }

View file

@ -1,3 +1,5 @@
import { ROLE, OPENAI_BLOCK, RESPONSES_ITEM } from "../schema/index.js";
/** /**
* Normalize Responses API input to array format. * Normalize Responses API input to array format.
* Accepts string or array, returns array of message items. * Accepts string or array, returns array of message items.
@ -9,12 +11,12 @@
export function normalizeResponsesInput(input) { export function normalizeResponsesInput(input) {
if (typeof input === "string") { if (typeof input === "string") {
const text = input.trim() === "" ? "..." : input; const text = input.trim() === "" ? "..." : input;
return [{ type: "message", role: "user", content: [{ type: "input_text", text }] }]; return [{ type: RESPONSES_ITEM.MESSAGE, role: ROLE.USER, content: [{ type: RESPONSES_ITEM.INPUT_TEXT, text }] }];
} }
if (Array.isArray(input)) { if (Array.isArray(input)) {
// Empty input[] would produce messages:[] which all providers reject (#389) // Empty input[] would produce messages:[] which all providers reject (#389)
if (input.length === 0) { if (input.length === 0) {
return [{ type: "message", role: "user", content: [{ type: "input_text", text: "..." }] }]; return [{ type: RESPONSES_ITEM.MESSAGE, role: ROLE.USER, content: [{ type: RESPONSES_ITEM.INPUT_TEXT, text: "..." }] }];
} }
return input; return input;
} }
@ -34,7 +36,7 @@ export function convertResponsesApiFormat(body) {
// Convert instructions to system message // Convert instructions to system message
if (body.instructions) { if (body.instructions) {
result.messages.push({ role: "system", content: body.instructions }); result.messages.push({ role: ROLE.SYSTEM, content: body.instructions });
} }
// Group items by conversation turn // Group items by conversation turn
@ -48,9 +50,9 @@ export function convertResponsesApiFormat(body) {
for (const item of inputItems) { for (const item of inputItems) {
// Determine item type - Droid CLI sends role-based items without 'type' field // Determine item type - Droid CLI sends role-based items without 'type' field
// Fallback: if no type but has role property, treat as message // Fallback: if no type but has role property, treat as message
const itemType = item.type || (item.role ? "message" : null); const itemType = item.type || (item.role ? RESPONSES_ITEM.MESSAGE : null);
if (itemType === "message") { if (itemType === RESPONSES_ITEM.MESSAGE) {
// Flush any pending assistant message with tool calls // Flush any pending assistant message with tool calls
if (currentAssistantMsg) { if (currentAssistantMsg) {
result.messages.push(currentAssistantMsg); result.messages.push(currentAssistantMsg);
@ -67,22 +69,22 @@ export function convertResponsesApiFormat(body) {
// Convert content: input_text → text, output_text → text, input_image → image_url // Convert content: input_text → text, output_text → text, input_image → image_url
const content = Array.isArray(item.content) const content = Array.isArray(item.content)
? item.content.map(c => { ? item.content.map(c => {
if (c.type === "input_text") return { type: "text", text: c.text }; if (c.type === RESPONSES_ITEM.INPUT_TEXT) return { type: OPENAI_BLOCK.TEXT, text: c.text };
if (c.type === "output_text") return { type: "text", text: c.text }; if (c.type === RESPONSES_ITEM.OUTPUT_TEXT) return { type: OPENAI_BLOCK.TEXT, text: c.text };
if (c.type === "input_image") { if (c.type === RESPONSES_ITEM.INPUT_IMAGE) {
const url = c.image_url || c.file_id || ""; const url = c.image_url || c.file_id || "";
return { type: "image_url", image_url: { url, detail: c.detail || "auto" } }; return { type: OPENAI_BLOCK.IMAGE_URL, image_url: { url, detail: c.detail || "auto" } };
} }
return c; return c;
}) })
: item.content; : item.content;
result.messages.push({ role: item.role, content }); result.messages.push({ role: item.role, content });
} }
else if (itemType === "function_call") { else if (itemType === RESPONSES_ITEM.FUNCTION_CALL) {
// Start or append to assistant message with tool_calls // Start or append to assistant message with tool_calls
if (!currentAssistantMsg) { if (!currentAssistantMsg) {
currentAssistantMsg = { currentAssistantMsg = {
role: "assistant", role: ROLE.ASSISTANT,
content: null, content: null,
tool_calls: [] tool_calls: []
}; };
@ -91,14 +93,14 @@ export function convertResponsesApiFormat(body) {
if (!item.name || typeof item.name !== "string" || item.name.trim() === "") continue; if (!item.name || typeof item.name !== "string" || item.name.trim() === "") continue;
currentAssistantMsg.tool_calls.push({ currentAssistantMsg.tool_calls.push({
id: item.call_id, id: item.call_id,
type: "function", type: OPENAI_BLOCK.FUNCTION,
function: { function: {
name: item.name, name: item.name,
arguments: item.arguments arguments: item.arguments
} }
}); });
} }
else if (itemType === "function_call_output") { else if (itemType === RESPONSES_ITEM.FUNCTION_CALL_OUTPUT) {
// Flush assistant message first if exists // Flush assistant message first if exists
if (currentAssistantMsg) { if (currentAssistantMsg) {
result.messages.push(currentAssistantMsg); result.messages.push(currentAssistantMsg);
@ -106,12 +108,12 @@ export function convertResponsesApiFormat(body) {
} }
// Add tool result // Add tool result
pendingToolResults.push({ pendingToolResults.push({
role: "tool", role: ROLE.TOOL,
tool_call_id: item.call_id, tool_call_id: item.call_id,
content: typeof item.output === "string" ? item.output : JSON.stringify(item.output) content: typeof item.output === "string" ? item.output : JSON.stringify(item.output)
}); });
} }
else if (itemType === "reasoning") { else if (itemType === RESPONSES_ITEM.REASONING) {
// Skip reasoning items - they are for display only // Skip reasoning items - they are for display only
continue; continue;
} }

View file

@ -1,14 +0,0 @@
// Build OpenAI usage object. Caller computes prompt/completion/total (provider math).
// Optional details added only when > 0 (matches existing claude/gemini/codex behavior).
export function buildUsage({ promptTokens, completionTokens, totalTokens, cachedTokens = 0, cacheCreationTokens = 0, reasoningTokens = 0 }) {
const usage = { prompt_tokens: promptTokens, completion_tokens: completionTokens, total_tokens: totalTokens };
if (cachedTokens > 0 || cacheCreationTokens > 0) {
usage.prompt_tokens_details = {};
if (cachedTokens > 0) usage.prompt_tokens_details.cached_tokens = cachedTokens;
if (cacheCreationTokens > 0) usage.prompt_tokens_details.cache_creation_tokens = cacheCreationTokens;
}
if (reasoningTokens > 0) {
usage.completion_tokens_details = { reasoning_tokens: reasoningTokens };
}
return usage;
}

View file

@ -1,8 +1,8 @@
import { FORMATS } from "./formats.js"; import { FORMATS } from "./formats.js";
import { ensureToolCallIds, fixMissingToolResponses } from "./helpers/toolCallHelper.js"; import { ensureToolCallIds, fixMissingToolResponses } from "./concerns/toolCall.js";
import { prepareClaudeRequest } from "./helpers/claudeHelper.js"; import { prepareClaudeRequest } from "./formats/claude.js";
import { cloakClaudeTools } from "../utils/claudeCloaking.js"; import { cloakClaudeTools } from "../utils/claudeCloaking.js";
import { filterToOpenAIFormat } from "./helpers/openaiHelper.js"; import { filterToOpenAIFormat } from "./formats/openai.js";
import { normalizeThinkingConfig } from "../services/provider.js"; import { normalizeThinkingConfig } from "../services/provider.js";
import { AntigravityExecutor } from "../executors/antigravity.js"; import { AntigravityExecutor } from "../executors/antigravity.js";
import { PROVIDERS } from "../providers/index.js"; import { PROVIDERS } from "../providers/index.js";

View file

@ -1,7 +1,10 @@
import { register } from "../index.js"; import { register } from "../index.js";
import { FORMATS } from "../formats.js"; import { FORMATS } from "../formats.js";
import { adjustMaxTokens } from "../helpers/maxTokensHelper.js"; import { adjustMaxTokens } from "../formats/maxTokens.js";
import { encodeDataUri } from "../helpers/imageHelper.js"; import { encodeDataUri } from "../concerns/image.js";
import { ROLE, GEMINI_ROLE, OPENAI_BLOCK } from "../schema/index.js";
import { budgetToEffort } from "../concerns/thinking.js";
import { collapseTextParts } from "../concerns/message.js";
// Convert Antigravity request to OpenAI format // Convert Antigravity request to OpenAI format
// Antigravity body: { project, model, userAgent, requestType, requestId, request: { contents, systemInstruction, tools, toolConfig, generationConfig, sessionId } } // Antigravity body: { project, model, userAgent, requestType, requestId, request: { contents, systemInstruction, tools, toolConfig, generationConfig, sessionId } }
@ -32,16 +35,8 @@ export function antigravityToOpenAIRequest(model, body, stream) {
// Thinking config → reasoning_effort // Thinking config → reasoning_effort
if (config.thinkingConfig) { if (config.thinkingConfig) {
const budget = config.thinkingConfig.thinkingBudget || 0; const effort = budgetToEffort(config.thinkingConfig.thinkingBudget || 0);
if (budget > 0) { if (effort) result.reasoning_effort = effort;
if (budget <= 2048) {
result.reasoning_effort = "low";
} else if (budget <= 16384) {
result.reasoning_effort = "medium";
} else {
result.reasoning_effort = "high";
}
}
} }
} }
@ -49,7 +44,7 @@ export function antigravityToOpenAIRequest(model, body, stream) {
if (req.systemInstruction) { if (req.systemInstruction) {
const systemText = extractText(req.systemInstruction); const systemText = extractText(req.systemInstruction);
if (systemText) { if (systemText) {
result.messages.push({ role: "system", content: systemText }); result.messages.push({ role: ROLE.SYSTEM, content: systemText });
} }
} }
@ -74,7 +69,7 @@ export function antigravityToOpenAIRequest(model, body, stream) {
if (tool.functionDeclarations) { if (tool.functionDeclarations) {
for (const func of tool.functionDeclarations) { for (const func of tool.functionDeclarations) {
result.tools.push({ result.tools.push({
type: "function", type: OPENAI_BLOCK.FUNCTION,
function: { function: {
name: func.name, name: func.name,
description: func.description || "", description: func.description || "",
@ -123,7 +118,7 @@ function normalizeSchemaTypes(schema) {
// Convert Antigravity content to OpenAI message // Convert Antigravity content to OpenAI message
// Handles: text, thought, thoughtSignature, functionCall, functionResponse, inlineData // Handles: text, thought, thoughtSignature, functionCall, functionResponse, inlineData
function convertContent(content) { function convertContent(content) {
const role = content.role === "model" ? "assistant" : content.role === "user" ? "user" : content.role; const role = content.role === GEMINI_ROLE.MODEL ? ROLE.ASSISTANT : content.role === GEMINI_ROLE.USER ? ROLE.USER : content.role;
if (!content.parts || !Array.isArray(content.parts)) { if (!content.parts || !Array.isArray(content.parts)) {
return null; return null;
@ -143,19 +138,19 @@ function convertContent(content) {
// Text with thoughtSignature = regular text after thinking // Text with thoughtSignature = regular text after thinking
if (part.thoughtSignature && part.text !== undefined) { if (part.thoughtSignature && part.text !== undefined) {
textParts.push({ type: "text", text: part.text }); textParts.push({ type: OPENAI_BLOCK.TEXT, text: part.text });
continue; continue;
} }
// Regular text // Regular text
if (part.text !== undefined) { if (part.text !== undefined) {
textParts.push({ type: "text", text: part.text }); textParts.push({ type: OPENAI_BLOCK.TEXT, text: part.text });
} }
// Inline data (images) // Inline data (images)
if (part.inlineData) { if (part.inlineData) {
textParts.push({ textParts.push({
type: "image_url", type: OPENAI_BLOCK.IMAGE_URL,
image_url: { image_url: {
url: encodeDataUri(part.inlineData.mimeType, part.inlineData.data) url: encodeDataUri(part.inlineData.mimeType, part.inlineData.data)
} }
@ -166,7 +161,7 @@ function convertContent(content) {
if (part.functionCall) { if (part.functionCall) {
toolCalls.push({ toolCalls.push({
id: part.functionCall.id || `call_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`, id: part.functionCall.id || `call_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
type: "function", type: OPENAI_BLOCK.FUNCTION,
function: { function: {
name: part.functionCall.name, name: part.functionCall.name,
arguments: JSON.stringify(part.functionCall.args || {}) arguments: JSON.stringify(part.functionCall.args || {})
@ -177,7 +172,7 @@ function convertContent(content) {
// Function response → collect all, each becomes a separate tool message // Function response → collect all, each becomes a separate tool message
if (part.functionResponse) { if (part.functionResponse) {
toolResults.push({ toolResults.push({
role: "tool", role: ROLE.TOOL,
tool_call_id: part.functionResponse.id || part.functionResponse.name, tool_call_id: part.functionResponse.id || part.functionResponse.name,
content: JSON.stringify(part.functionResponse.response?.result || part.functionResponse.response || {}) content: JSON.stringify(part.functionResponse.response?.result || part.functionResponse.response || {})
}); });
@ -191,9 +186,9 @@ function convertContent(content) {
// Assistant with tool calls // Assistant with tool calls
if (toolCalls.length > 0) { if (toolCalls.length > 0) {
const msg = { role: "assistant" }; const msg = { role: ROLE.ASSISTANT };
if (textParts.length > 0) { if (textParts.length > 0) {
msg.content = textParts.length === 1 && textParts[0].type === "text" ? textParts[0].text : textParts; msg.content = collapseTextParts(textParts);
} }
if (reasoningContent) { if (reasoningContent) {
msg.reasoning_content = reasoningContent; msg.reasoning_content = reasoningContent;
@ -206,7 +201,7 @@ function convertContent(content) {
if (textParts.length > 0 || reasoningContent) { if (textParts.length > 0 || reasoningContent) {
const msg = { role }; const msg = { role };
if (textParts.length > 0) { if (textParts.length > 0) {
msg.content = textParts.length === 1 && textParts[0].type === "text" ? textParts[0].text : textParts; msg.content = collapseTextParts(textParts);
} }
if (reasoningContent) { if (reasoningContent) {
msg.reasoning_content = reasoningContent; msg.reasoning_content = reasoningContent;

View file

@ -1,7 +1,9 @@
import { register } from "../index.js"; import { register } from "../index.js";
import { FORMATS } from "../formats.js"; import { FORMATS } from "../formats.js";
import { adjustMaxTokens } from "../helpers/maxTokensHelper.js"; import { adjustMaxTokens } from "../formats/maxTokens.js";
import { encodeDataUri } from "../helpers/imageHelper.js"; import { encodeDataUri } from "../concerns/image.js";
import { ROLE, OPENAI_BLOCK, CLAUDE_BLOCK } from "../schema/index.js";
import { collapseTextParts } from "../concerns/message.js";
function stripAnthropicBillingHeader(text) { function stripAnthropicBillingHeader(text) {
if (typeof text !== "string") return ""; if (typeof text !== "string") return "";
@ -34,7 +36,7 @@ export function claudeToOpenAIRequest(model, body, stream) {
if (systemContent) { if (systemContent) {
result.messages.push({ result.messages.push({
role: "system", role: ROLE.SYSTEM,
content: systemContent content: systemContent
}); });
} }
@ -58,13 +60,13 @@ export function claudeToOpenAIRequest(model, body, stream) {
// Fix missing tool responses - OpenAI requires every tool_call to have a response. // Fix missing tool responses - OpenAI requires every tool_call to have a response.
// Local variant: scans contiguous tool replies + inserts "[No response received]" // Local variant: scans contiguous tool replies + inserts "[No response received]"
// (distinct from the global immediate-next check in toolCallHelper, runs on the openai leg). // (distinct from the global immediate-next check in concerns/toolCall, runs on the openai leg).
fixMissingToolResponsesOpenAI(result.messages); fixMissingToolResponsesOpenAI(result.messages);
// Tools // Tools
if (body.tools && Array.isArray(body.tools)) { if (body.tools && Array.isArray(body.tools)) {
result.tools = body.tools.map(tool => ({ result.tools = body.tools.map(tool => ({
type: "function", type: OPENAI_BLOCK.FUNCTION,
function: { function: {
name: tool.name, name: tool.name,
description: String(tool.description || ""), description: String(tool.description || ""),
@ -85,7 +87,7 @@ export function claudeToOpenAIRequest(model, body, stream) {
function fixMissingToolResponsesOpenAI(messages) { function fixMissingToolResponsesOpenAI(messages) {
for (let i = 0; i < messages.length; i++) { for (let i = 0; i < messages.length; i++) {
const msg = messages[i]; const msg = messages[i];
if (msg.role === "assistant" && msg.tool_calls && msg.tool_calls.length > 0) { if (msg.role === ROLE.ASSISTANT && msg.tool_calls && msg.tool_calls.length > 0) {
const toolCallIds = msg.tool_calls.map(tc => tc.id); const toolCallIds = msg.tool_calls.map(tc => tc.id);
// Collect all tool response IDs that IMMEDIATELY follow this assistant message // Collect all tool response IDs that IMMEDIATELY follow this assistant message
@ -93,7 +95,7 @@ function fixMissingToolResponsesOpenAI(messages) {
let insertPosition = i + 1; let insertPosition = i + 1;
for (let j = i + 1; j < messages.length; j++) { for (let j = i + 1; j < messages.length; j++) {
const nextMsg = messages[j]; const nextMsg = messages[j];
if (nextMsg.role === "tool" && nextMsg.tool_call_id) { if (nextMsg.role === ROLE.TOOL && nextMsg.tool_call_id) {
respondedIds.add(nextMsg.tool_call_id); respondedIds.add(nextMsg.tool_call_id);
insertPosition = j + 1; insertPosition = j + 1;
} else { } else {
@ -106,7 +108,7 @@ function fixMissingToolResponsesOpenAI(messages) {
if (missingIds.length > 0) { if (missingIds.length > 0) {
const missingResponses = missingIds.map(id => ({ const missingResponses = missingIds.map(id => ({
role: "tool", role: ROLE.TOOL,
tool_call_id: id, tool_call_id: id,
content: "[No response received]" content: "[No response received]"
})); }));
@ -119,7 +121,7 @@ function fixMissingToolResponsesOpenAI(messages) {
// Convert single Claude message - returns single message or array of messages // Convert single Claude message - returns single message or array of messages
function convertClaudeMessage(msg) { function convertClaudeMessage(msg) {
const role = msg.role === "user" || msg.role === "tool" ? "user" : "assistant"; const role = msg.role === ROLE.USER || msg.role === ROLE.TOOL ? ROLE.USER : ROLE.ASSISTANT;
// Simple string content // Simple string content
if (typeof msg.content === "string") { if (typeof msg.content === "string") {
@ -134,14 +136,14 @@ function convertClaudeMessage(msg) {
for (const block of msg.content) { for (const block of msg.content) {
switch (block.type) { switch (block.type) {
case "text": case CLAUDE_BLOCK.TEXT:
parts.push({ type: "text", text: block.text }); parts.push({ type: OPENAI_BLOCK.TEXT, text: block.text });
break; break;
case "image": case CLAUDE_BLOCK.IMAGE:
if (block.source?.type === "base64") { if (block.source?.type === "base64") {
parts.push({ parts.push({
type: "image_url", type: OPENAI_BLOCK.IMAGE_URL,
image_url: { image_url: {
url: encodeDataUri(block.source.media_type, block.source.data) url: encodeDataUri(block.source.media_type, block.source.data)
} }
@ -149,10 +151,10 @@ function convertClaudeMessage(msg) {
} }
break; break;
case "tool_use": case CLAUDE_BLOCK.TOOL_USE:
toolCalls.push({ toolCalls.push({
id: block.id, id: block.id,
type: "function", type: OPENAI_BLOCK.FUNCTION,
function: { function: {
name: block.name, name: block.name,
arguments: JSON.stringify(block.input || {}) arguments: JSON.stringify(block.input || {})
@ -160,13 +162,13 @@ function convertClaudeMessage(msg) {
}); });
break; break;
case "tool_result": case CLAUDE_BLOCK.TOOL_RESULT:
let resultContent = ""; let resultContent = "";
if (typeof block.content === "string") { if (typeof block.content === "string") {
resultContent = block.content; resultContent = block.content;
} else if (Array.isArray(block.content)) { } else if (Array.isArray(block.content)) {
resultContent = block.content resultContent = block.content
.filter(c => c.type === "text") .filter(c => c.type === CLAUDE_BLOCK.TEXT)
.map(c => c.text) .map(c => c.text)
.join("\n") || JSON.stringify(block.content); .join("\n") || JSON.stringify(block.content);
} else if (block.content) { } else if (block.content) {
@ -174,7 +176,7 @@ function convertClaudeMessage(msg) {
} }
toolResults.push({ toolResults.push({
role: "tool", role: ROLE.TOOL,
tool_call_id: block.tool_use_id, tool_call_id: block.tool_use_id,
content: resultContent content: resultContent
}); });
@ -185,21 +187,16 @@ function convertClaudeMessage(msg) {
// If has tool results, return array of tool messages // If has tool results, return array of tool messages
if (toolResults.length > 0) { if (toolResults.length > 0) {
if (parts.length > 0) { if (parts.length > 0) {
const textContent = parts.length === 1 && parts[0].type === "text" return [...toolResults, { role: ROLE.USER, content: collapseTextParts(parts) }];
? parts[0].text
: parts;
return [...toolResults, { role: "user", content: textContent }];
} }
return toolResults; return toolResults;
} }
// If has tool calls, return assistant message with tool_calls // If has tool calls, return assistant message with tool_calls
if (toolCalls.length > 0) { if (toolCalls.length > 0) {
const result = { role: "assistant" }; const result = { role: ROLE.ASSISTANT };
if (parts.length > 0) { if (parts.length > 0) {
result.content = parts.length === 1 && parts[0].type === "text" result.content = collapseTextParts(parts);
? parts[0].text
: parts;
} }
result.tool_calls = toolCalls; result.tool_calls = toolCalls;
return result; return result;
@ -209,7 +206,7 @@ function convertClaudeMessage(msg) {
if (parts.length > 0) { if (parts.length > 0) {
return { return {
role, role,
content: parts.length === 1 && parts[0].type === "text" ? parts[0].text : parts content: collapseTextParts(parts)
}; };
} }
@ -230,7 +227,7 @@ function convertToolChoice(choice) {
switch (choice.type) { switch (choice.type) {
case "auto": return "auto"; case "auto": return "auto";
case "any": return "required"; case "any": return "required";
case "tool": return { type: "function", function: { name: choice.name } }; case "tool": return { type: OPENAI_BLOCK.FUNCTION, function: { name: choice.name } };
default: return "auto"; default: return "auto";
} }
} }

Some files were not shown because too many files have changed in this diff Show more