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
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
feat(usageTracking): make usage token buffer configurable
Mikhail Salnikovf7fbe3946d79
diff --git a/open-sse/utils/usageTracking.ts b/open-sse/utils/usageTracking.tsindex ccf08709ce..3eb5b8cc76 100644--- a/open-sse/utils/usageTracking.ts+++ b/open-sse/utils/usageTracking.ts@@ -23,10 +23,74 @@ export const COLORS = {/*** Safety buffer added to reported token usage to prevent clients from hitting- * context window limits. 2000 tokens accounts for overhead from system prompts,+ * context window limits. Accounts for overhead from system prompts,* tool definitions, and format translation that may not be reflected in raw usage.+ *+ * Configurable via:+ * - Settings API / Dashboard: `usageTokenBuffer` (persisted in DB)+ * - Environment variable: `USAGE_TOKEN_BUFFER`+ * - Defaults to 2000 if neither is set+ *+ * Set to 0 to disable the buffer entirely (raw provider token counts).*/-const BUFFER_TOKENS = 2000;+const DEFAULT_BUFFER_TOKENS = 2000;++let _cachedBuffer: number | null = null;+let _cacheTimestamp = 0;+const CACHE_TTL_MS = 30_000; // Re-read from DB/env every 30s++function getBufferTokens(): number {+ const now = Date.now();+ const isExpired = _cachedBuffer !== null && now - _cacheTimestamp >= CACHE_TTL_MS;++ if (_cachedBuffer !== null && !isExpired) {+ return _cachedBuffer;+ }++ // Priority: env var > cached DB value > default+ const envVal = process.env.USAGE_TOKEN_BUFFER;+ if (envVal !== undefined) {+ const parsed = parseInt(envVal, 10);+ if (!isNaN(parsed) && parsed >= 0) {+ _cachedBuffer = parsed;+ _cacheTimestamp = now;+ return parsed;+ }+ }++ // Return cached value or default; kick off async DB read to update cache.+ // On first call (_cachedBuffer is null), use the default.+ // On TTL expiry (_cachedBuffer is stale), continue returning the stale value+ // while refreshing asynchronously — prevents blocking the hot path.+ if (_cachedBuffer === null || isExpired) {+ if (_cachedBuffer === null) {+ _cachedBuffer = DEFAULT_BUFFER_TOKENS;+ }+ _cacheTimestamp = now;+ _loadBufferFromDb();+ }+ return _cachedBuffer;+}++async function _loadBufferFromDb(): Promise<void> {+ try {+ const { getSettings } = await import("@/lib/db/settings");+ const settings = await getSettings();+ const val = settings.usageTokenBuffer;+ if (typeof val === "number" && val >= 0) {+ _cachedBuffer = val;+ _cacheTimestamp = Date.now();+ }+ } catch {+ // DB not ready yet or settings unavailable — keep current value+ }+}++/** Force-refresh the buffer from settings (e.g. after a settings update). */+export function invalidateBufferTokensCache(): void {+ _cachedBuffer = null;+ _cacheTimestamp = 0;+}// Get HH:MM:SS timestampfunction getTimeString() {@@ -46,21 +110,24 @@ function getTimeString() {export function addBufferToUsage(usage) {if (!usage || typeof usage !== "object") return usage;+ const buffer = getBufferTokens();+ if (buffer === 0) return usage;+const result = { ...usage };// Claude formatif (result.input_tokens !== undefined) {- result.input_tokens += BUFFER_TOKENS;+ result.input_tokens += buffer;}// OpenAI formatif (result.prompt_tokens !== undefined) {- result.prompt_tokens += BUFFER_TOKENS;+ result.prompt_tokens += buffer;}// Calculate or update total_tokensif (result.total_tokens !== undefined) {- result.total_tokens += BUFFER_TOKENS;+ result.total_tokens += buffer;} else if (result.prompt_tokens !== undefined && result.completion_tokens !== undefined) {// Calculate total_tokens if not existsresult.total_tokens = result.prompt_tokens + result.completion_tokens;diff --git a/src/app/(dashboard)/dashboard/settings/components/ProxyTab.tsx b/src/app/(dashboard)/dashboard/settings/components/ProxyTab.tsxindex 6d3ffafee1..889037313f 100644--- a/src/app/(dashboard)/dashboard/settings/components/ProxyTab.tsx+++ b/src/app/(dashboard)/dashboard/settings/components/ProxyTab.tsx@@ -12,6 +12,9 @@ export default function ProxyTab() {const t = useTranslations("settings");const tc = useTranslations("common");const [debugMode, setDebugMode] = useState(false);+ const [usageTokenBuffer, setUsageTokenBuffer] = useState<number | null>(null);+ const [bufferInput, setBufferInput] = useState("");+ const [bufferSaving, setBufferSaving] = useState(false);const [loading, setLoading] = useState(true);const loadGlobalProxy = async () => {@@ -39,6 +42,26 @@ export default function ProxyTab() {}};+ const updateUsageTokenBuffer = async () => {+ const val = parseInt(bufferInput, 10);+ if (isNaN(val) || val < 0 || val > 50000) return;+ setBufferSaving(true);+ try {+ const res = await fetch("/api/settings", {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ usageTokenBuffer: val }),+ });+ if (res.ok) {+ setUsageTokenBuffer(val);+ }+ } catch (err) {+ console.error("Failed to update usageTokenBuffer:", err);+ } finally {+ setBufferSaving(false);+ }+ };+useEffect(() => {mountedRef.current = true;async function init() {@@ -65,6 +88,9 @@ export default function ProxyTab() {}).then((data) => {setDebugMode(data.debugMode === true);+ const buf = typeof data.usageTokenBuffer === "number" ? data.usageTokenBuffer : 2000;+ setUsageTokenBuffer(buf);+ setBufferInput(String(buf));setLoading(false);}).catch(() => setLoading(false));@@ -120,6 +146,49 @@ export default function ProxyTab() {/></div></Card>+ <Card className="p-6 mt-4">+ <div className="flex flex-col gap-3">+ <div>+ <p className="font-medium">Usage Token Buffer</p>+ <p className="text-sm text-text-muted mt-1">+ Extra tokens added to reported usage to account for system prompt overhead. Set to 0+ to report raw provider token counts. Default: 2000. Changes take effect within 30+ seconds.+ </p>+ </div>+ <div className="flex items-center gap-3">+ <input+ type="number"+ min={0}+ max={50000}+ value={bufferInput}+ onChange={(e) => setBufferInput(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") updateUsageTokenBuffer();+ }}+ className="w-32 px-3 py-1.5 rounded bg-surface-2 border border-border text-sm text-text-primary"+ disabled={loading}+ />+ <Button+ size="sm"+ variant="primary"+ onClick={updateUsageTokenBuffer}+ disabled={+ bufferSaving ||+ loading ||+ parseInt(bufferInput, 10) === usageTokenBuffer+ }+ >+ {bufferSaving ? tc("saving") : tc("save")}+ </Button>+ {usageTokenBuffer !== null && parseInt(bufferInput, 10) !== usageTokenBuffer && (+ <span className="text-xs text-text-muted">+ Current: {usageTokenBuffer}+ </span>+ )}+ </div>+ </div>+ </Card></div><ProxyConfigModaldiff --git a/src/app/api/settings/route.ts b/src/app/api/settings/route.tsindex 525bcf849d..514c57bd00 100644--- a/src/app/api/settings/route.ts+++ b/src/app/api/settings/route.ts@@ -115,6 +115,13 @@ export async function PATCH(request) {);}}+ // Sync usage token buffer to runtime cache+ if ("usageTokenBuffer" in body) {+ const { invalidateBufferTokensCache } =+ await import("@omniroute/open-sse/utils/usageTracking.ts");+ invalidateBufferTokensCache();+ }+if (cpaFallback !== undefined || cpaUrl !== undefined) {const enabled =cpaFallback ?? (settings as Record<string, unknown>).cliproxyapi_fallback_enabled;diff --git a/src/shared/validation/settingsSchemas.ts b/src/shared/validation/settingsSchemas.tsindex de5c1fc53c..84f8d15b99 100644--- a/src/shared/validation/settingsSchemas.ts+++ b/src/shared/validation/settingsSchemas.ts@@ -53,6 +53,9 @@ export const updateSettingsSchema = z.object({alwaysPreserveClientCache: z.enum(["auto", "always", "never"]).optional(),// Adaptive Volume RoutingadaptiveVolumeRouting: z.boolean().optional(),+ // Usage token buffer — safety margin added to reported prompt/input token counts.+ // Prevents CLI tools from overrunning context windows. Set to 0 to disable.+ usageTokenBuffer: z.number().int().min(0).max(50000).optional(),// Custom CLI agent definitions for ACPcustomAgents: z.array(