Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

Merge branch 'main' into codex/claude-cache-log-accounting

cai keruiae8d2ac2e1d9
diff --cc next.config.mjs
index 221128c934,b7f4645d40..4308944988
--- a/next.config.mjs
+++ b/next.config.mjs
@@@ -13,9 -13,11 +13,12 @@@ const nextConfig =
},
output: "standalone",
serverExternalPackages: [
+ "pino",
+ "pino-pretty",
+ "thread-stream",
"better-sqlite3",
"keytar",
+ "wreq-js",
"zod",
"child_process",
"fs",
diff --cc open-sse/handlers/chatCore.ts
index 0b5debcd4b,7a58219aba..5e6432b5cb
--- a/open-sse/handlers/chatCore.ts
+++ b/open-sse/handlers/chatCore.ts
@@@ -23,10 -26,17 +26,21 @@@ import
appendRequestLog,
saveCallLog,
} from "@/lib/usageDb";
+import { getLoggedInputTokens, getLoggedOutputTokens } from "@/lib/usage/tokenAccounting";
+import { getModelNormalizeToolCallId, getModelPreserveOpenAIDeveloperRole } from "@/lib/localDb";
+import { getExecutor } from "../executors/index.ts";
+import { CLAUDE_OAUTH_TOOL_PREFIX } from "../translator/request/openai-to-claude.ts";
+ import {
+ getModelNormalizeToolCallId,
+ getModelPreserveOpenAIDeveloperRole,
+ getModelUpstreamExtraHeaders,
+ } from "@/lib/localDb";
+ import { getExecutor } from "../executors/index.ts";
+ import {
+ parseCodexQuotaHeaders,
+ getCodexResetTime,
+ getCodexModelScope,
+ } from "../executors/codex.ts";
import { translateNonStreamingResponse } from "./responseTranslator.ts";
import { extractUsageFromResponse } from "./usageExtractor.ts";
import { parseSSEToOpenAIResponse, parseSSEToResponsesOutput } from "./sseParser.ts";
@@@ -64,202 -80,10 +84,203 @@@ export function shouldUseNativeCodexPas
if (provider !== "codex") return false;
if (sourceFormat !== FORMATS.OPENAI_RESPONSES) return false;
const normalizedEndpoint = String(endpointPath || "").replace(/\/+$/, "");
- return /(?:^|\/)responses(?:\/.*)?$/i.test(normalizedEndpoint);
+ const segments = normalizedEndpoint.split("/");
+ return segments.includes("responses");
}
+function buildClaudePassthroughToolNameMap(body: Record<string, unknown> | null | undefined) {
+ if (!body || !Array.isArray(body.tools)) return null;
+
+ const toolNameMap = new Map<string, string>();
+ for (const tool of body.tools) {
+ const toolRecord = tool as Record<string, unknown>;
+ const toolData =
+ toolRecord?.type === "function" &&
+ toolRecord.function &&
+ typeof toolRecord.function === "object"
+ ? (toolRecord.function as Record<string, unknown>)
+ : toolRecord;
+ const originalName = typeof toolData?.name === "string" ? toolData.name.trim() : "";
+ if (!originalName) continue;
+ toolNameMap.set(`${CLAUDE_OAUTH_TOOL_PREFIX}${originalName}`, originalName);
+ }
+
+ return toolNameMap.size > 0 ? toolNameMap : null;
+}
+
+function restoreClaudePassthroughToolNames(
+ responseBody: Record<string, unknown>,
+ toolNameMap: Map<string, string> | null
+) {
+ if (!toolNameMap || !Array.isArray(responseBody?.content)) return responseBody;
+
+ let changed = false;
+ const content = responseBody.content.map((block: Record<string, unknown>) => {
+ if (block?.type !== "tool_use" || typeof block?.name !== "string") return block;
+ const restoredName = toolNameMap.get(block.name) ?? block.name;
+ if (restoredName === block.name) return block;
+ changed = true;
+ return {
+ ...block,
+ name: restoredName,
+ };
+ });
+
+ if (!changed) return responseBody;
+ return {
+ ...responseBody,
+ content,
+ };
+}
+
+function getHeaderValueCaseInsensitive(
+ headers: Record<string, unknown> | null | undefined,
+ targetName: string
+) {
+ if (!headers || typeof headers !== "object") return null;
+ const lowered = targetName.toLowerCase();
+ for (const [key, value] of Object.entries(headers)) {
+ if (key.toLowerCase() === lowered && typeof value === "string" && value.trim()) {
+ return value.trim();
+ }
+ }
+ return null;
+}
+
+function buildClaudePromptCacheLogMeta(
+ targetFormat: string,
+ finalBody: Record<string, unknown> | null | undefined,
+ providerHeaders: Record<string, unknown> | null | undefined
+) {
+ if (targetFormat !== FORMATS.CLAUDE || !finalBody || typeof finalBody !== "object") return null;
+
+ const describeCacheControl = (cacheControl: Record<string, unknown> | undefined, extra = {}) => ({
+ type:
+ cacheControl && typeof cacheControl.type === "string" && cacheControl.type.trim()
+ ? cacheControl.type.trim()
+ : "ephemeral",
+ ttl:
+ cacheControl && typeof cacheControl.ttl === "string" && cacheControl.ttl.trim()
+ ? cacheControl.ttl.trim()
+ : null,
+ ...extra,
+ });
+
+ const systemBreakpoints = Array.isArray(finalBody.system)
+ ? finalBody.system.flatMap((block, index) => {
+ if (!block || typeof block !== "object") return [];
+ const cacheControl =
+ block.cache_control && typeof block.cache_control === "object" ? block.cache_control : null;
+ return cacheControl ? [describeCacheControl(cacheControl, { index })] : [];
+ })
+ : [];
+
+ const toolBreakpoints = Array.isArray(finalBody.tools)
+ ? finalBody.tools.flatMap((tool, index) => {
+ if (!tool || typeof tool !== "object") return [];
+ const cacheControl =
+ tool.cache_control && typeof tool.cache_control === "object" ? tool.cache_control : null;
+ const name = typeof tool.name === "string" && tool.name.trim() ? tool.name.trim() : null;
+ return cacheControl ? [describeCacheControl(cacheControl, { index, name })] : [];
+ })
+ : [];
+
+ const messageBreakpoints = Array.isArray(finalBody.messages)
+ ? finalBody.messages.flatMap((message, messageIndex) => {
+ if (!message || typeof message !== "object" || !Array.isArray(message.content)) return [];
+ const role =
+ typeof message.role === "string" && message.role.trim() ? message.role.trim() : "unknown";
+ return message.content.flatMap((block, contentIndex) => {
+ if (!block || typeof block !== "object") return [];
+ const cacheControl =
+ block.cache_control && typeof block.cache_control === "object" ? block.cache_control : null;
+ if (!cacheControl) return [];
+ return [
+ describeCacheControl(cacheControl, {
+ messageIndex,
+ contentIndex,
+ role,
+ blockType:
+ typeof block.type === "string" && block.type.trim() ? block.type.trim() : "unknown",
+ }),
+ ];
+ });
+ })
+ : [];
+
+ const totalBreakpoints =
+ systemBreakpoints.length + toolBreakpoints.length + messageBreakpoints.length;
+ const anthropicBeta = getHeaderValueCaseInsensitive(providerHeaders, "Anthropic-Beta");
+
+ if (totalBreakpoints === 0 && !anthropicBeta) return null;
+
+ return {
+ applied: totalBreakpoints > 0,
+ totalBreakpoints,
+ anthropicBeta,
+ systemBreakpoints,
+ toolBreakpoints,
+ messageBreakpoints,
+ };
+}
+
+function toPositiveNumber(value: unknown) {
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
+}
+
+function buildCacheUsageLogMeta(usage: Record<string, unknown> | null | undefined) {
+ if (!usage || typeof usage !== "object") return null;
+ const promptTokenDetails =
+ usage.prompt_tokens_details && typeof usage.prompt_tokens_details === "object"
+ ? (usage.prompt_tokens_details as Record<string, unknown>)
+ : undefined;
+ const hasCacheFields =
+ "cache_read_input_tokens" in usage ||
+ "cached_tokens" in usage ||
+ "cache_creation_input_tokens" in usage ||
+ !!promptTokenDetails &&
+ ("cached_tokens" in promptTokenDetails || "cache_creation_tokens" in promptTokenDetails);
+ const cacheReadTokens = toPositiveNumber(
+ usage.cache_read_input_tokens ??
+ usage.cached_tokens ??
+ promptTokenDetails?.cached_tokens
+ );
+ const cacheCreationTokens = toPositiveNumber(
+ usage.cache_creation_input_tokens ??
+ promptTokenDetails?.cache_creation_tokens
+ );
+ if (!hasCacheFields) return null;
+ return {
+ cacheReadTokens,
+ cacheCreationTokens,
+ };
+}
+
+function attachLogMeta(
+ payload: Record<string, unknown> | null | undefined,
+ meta: Record<string, unknown> | null | undefined
+) {
+ if (!meta || typeof meta !== "object") return payload;
+ const compactMeta = Object.fromEntries(
+ Object.entries(meta).filter(([, value]) => value !== null && value !== undefined)
+ );
+ if (Object.keys(compactMeta).length === 0) return payload;
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
+ return { _omniroute: compactMeta, _payload: payload ?? null };
+ }
+ const existing =
+ payload._omniroute && typeof payload._omniroute === "object" && !Array.isArray(payload._omniroute)
+ ? payload._omniroute
+ : {};
+ return {
+ ...payload,
+ _omniroute: {
+ ...existing,
+ ...compactMeta,
+ },
+ };
+}
+
/**
* Core chat handler - shared between SSE and Worker
* Returns { success, response, status, error } for caller to handle fallback
@@@ -442,7 -415,7 +612,8 @@@ export async function handleChatCore(
FORMATS.OPENAI,
FORMATS.CLAUDE,
model,
+ { ...translatedBody, _disableToolPrefix: true },
+ translatedBody,
stream,
credentials,
provider,
diff --cc open-sse/utils/stream.ts
index 2172d137c2,e3e3898ee9..54e03f352a
--- a/open-sse/utils/stream.ts
+++ b/open-sse/utils/stream.ts
@@@ -238,18 -236,18 +252,19 @@@ export function createSSEStream(options
const extracted = extractUsage(parsed);
if (extracted) {
// Non-destructive merge: never overwrite a positive value with 0
- // message_start carries input_tokens, message_delta carries output_tokens
+ // message_start carries input_tokens, message_delta carries output_tokens;
if (!usage) usage = {};
- if (extracted.prompt_tokens > 0) usage.prompt_tokens = extracted.prompt_tokens;
- if (extracted.completion_tokens > 0)
- usage.completion_tokens = extracted.completion_tokens;
- if (extracted.total_tokens > 0) usage.total_tokens = extracted.total_tokens;
- if (extracted.cache_read_input_tokens)
- usage.cache_read_input_tokens = extracted.cache_read_input_tokens;
- if (extracted.cache_creation_input_tokens)
- usage.cache_creation_input_tokens = extracted.cache_creation_input_tokens;
+ const u = usage;
+ const eu = extracted as UsageTokenRecord;
+ if (eu.prompt_tokens > 0) u.prompt_tokens = eu.prompt_tokens;
+ if (eu.completion_tokens > 0) u.completion_tokens = eu.completion_tokens;
+ if (eu.total_tokens > 0) u.total_tokens = eu.total_tokens;
+ if (eu.cache_read_input_tokens)
+ u.cache_read_input_tokens = eu.cache_read_input_tokens;
+ if (eu.cache_creation_input_tokens)
+ u.cache_creation_input_tokens = eu.cache_creation_input_tokens;
}
+ const restoredToolName = restoreClaudePassthroughToolUseName(parsed, toolNameMap);
// Track content length and accumulate from Claude format
if (parsed.delta?.text) {
totalContentLength += parsed.delta.text.length;