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

fix: resolve multiple issues (#493, #490, #452)

diegosouzapw0a5b005ce598
diff --git a/open-sse/executors/default.ts b/open-sse/executors/default.ts
index cc597bdac9..bacea0ccdf 100644
--- a/open-sse/executors/default.ts
+++ b/open-sse/executors/default.ts
@@ -80,18 +80,14 @@ export class DefaultExecutor extends BaseExecutor {
}
/**
- * For compatible providers, ensure the model name sent upstream
- * is the clean model name without internal routing prefixes.
- * e.g. "openapi-chat-anti/claude-opus-4-6-thinking" → "claude-opus-4-6-thinking"
+ * For compatible providers, the model name is already clean by the time
+ * it reaches the executor (chatCore sets body.model = modelInfo.model,
+ * which is the parsed model ID without any internal routing prefix).
+ *
+ * Models may legitimately contain "/" as part of their ID (e.g. "zai-org/GLM-5-FP8",
+ * "org/model-name") — we must NOT strip path segments. (Fix #493)
*/
transformRequest(model, body, stream, credentials) {
- if (
- this.provider?.startsWith?.("openai-compatible-") ||
- this.provider?.startsWith?.("anthropic-compatible-")
- ) {
- const cleanModel = model.includes("/") ? model.split("/").slice(1).join("/") : model;
- return { ...body, model: cleanModel };
- }
return body;
}
diff --git a/open-sse/services/combo.ts b/open-sse/services/combo.ts
index 265f9ff2ae..d1cc037b0e 100644
--- a/open-sse/services/combo.ts
+++ b/open-sse/services/combo.ts
@@ -447,8 +447,10 @@ export async function handleComboChat({
const handleSingleModelWrapped = combo.context_cache_protection
? async (b, modelStr) => {
const res = await handleSingleModel(b, modelStr);
- // Inject tag only on success and only for non-streaming non-binary responses
- if (res.ok && !b.stream) {
+ if (!res.ok) return res;
+
+ // Non-streaming: inject tag into JSON response (existing logic)
+ if (!b.stream) {
try {
const json = await res.clone().json();
const msgs = Array.isArray(json?.messages) ? json.messages : [];
@@ -460,10 +462,74 @@ export async function handleComboChat({
});
}
} catch {
- /* non-JSON or stream — skip tagging */
+ /* non-JSON — skip tagging */
}
+ return res;
}
- return res;
+
+ // Streaming (Fix #490): append omniModel tag as a final SSE content delta
+ // before the [DONE] marker using TransformStream for zero-copy passthrough
+ if (!res.body) return res;
+ const tagContent = `\n<omniModel>${modelStr}</omniModel>`;
+ const encoder = new TextEncoder();
+ const decoder = new TextDecoder();
+ let buffer = "";
+
+ const transform = new TransformStream({
+ transform(chunk, controller) {
+ // Decode chunk and check for [DONE] marker
+ const text = decoder.decode(chunk, { stream: true });
+ buffer += text;
+
+ // Check if buffer contains the [DONE] marker
+ const doneIdx = buffer.indexOf("data: [DONE]");
+ if (doneIdx === -1) {
+ // No [DONE] yet — flush buffer as-is (keep passthrough latency low)
+ controller.enqueue(encoder.encode(buffer));
+ buffer = "";
+ return;
+ }
+
+ // Found [DONE] — inject tag content delta before it
+ const beforeDone = buffer.slice(0, doneIdx);
+ const afterDone = buffer.slice(doneIdx);
+
+ // Build a synthetic SSE content delta chunk with the tag
+ const tagChunk = `data: ${JSON.stringify({
+ choices: [
+ {
+ delta: { content: tagContent },
+ index: 0,
+ finish_reason: null,
+ },
+ ],
+ })}\n\n`;
+
+ controller.enqueue(encoder.encode(beforeDone + tagChunk + afterDone));
+ buffer = "";
+ },
+ flush(controller) {
+ // If stream ends without [DONE], flush remaining buffer + tag
+ if (buffer.length > 0) {
+ const tagChunk = `data: ${JSON.stringify({
+ choices: [
+ {
+ delta: { content: tagContent },
+ index: 0,
+ finish_reason: null,
+ },
+ ],
+ })}\n\n`;
+ controller.enqueue(encoder.encode(buffer + tagChunk));
+ }
+ },
+ });
+
+ const transformedStream = res.body.pipeThrough(transform);
+ return new Response(transformedStream, {
+ status: res.status,
+ headers: res.headers,
+ });
}
: handleSingleModel;
// ─────────────────────────────────────────────────────────────────────────
diff --git a/src/lib/db/apiKeys.ts b/src/lib/db/apiKeys.ts
index 521a7d0de4..66fc036030 100644
--- a/src/lib/db/apiKeys.ts
+++ b/src/lib/db/apiKeys.ts
@@ -38,6 +38,8 @@ interface ApiKeyMetadata {
autoResolve: boolean;
isActive: boolean;
accessSchedule: AccessSchedule | null;
+ maxRequestsPerDay: number | null;
+ maxRequestsPerMinute: number | null;
}
interface ApiKeyRow extends JsonRecord {
@@ -187,6 +189,14 @@ function ensureApiKeysColumns(db: ApiKeysDbLike) {
db.exec("ALTER TABLE api_keys ADD COLUMN access_schedule TEXT");
console.log("[DB] Added api_keys.access_schedule column");
}
+ if (!columnNames.has("max_requests_per_day")) {
+ db.exec("ALTER TABLE api_keys ADD COLUMN max_requests_per_day INTEGER");
+ console.log("[DB] Added api_keys.max_requests_per_day column");
+ }
+ if (!columnNames.has("max_requests_per_minute")) {
+ db.exec("ALTER TABLE api_keys ADD COLUMN max_requests_per_minute INTEGER");
+ console.log("[DB] Added api_keys.max_requests_per_minute column");
+ }
_schemaChecked = true;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
@@ -212,7 +222,7 @@ function getPreparedStatements(db: ApiKeysDbLike): ApiKeysStatements {
_stmtGetKeyById = db.prepare<ApiKeyRow>("SELECT * FROM api_keys WHERE id = ?");
_stmtValidateKey = db.prepare<JsonRecord>("SELECT 1 FROM api_keys WHERE key = ?");
_stmtGetKeyMetadata = db.prepare<ApiKeyRow>(
- "SELECT id, name, machine_id, allowed_models, allowed_connections, no_log, auto_resolve, is_active, access_schedule FROM api_keys WHERE key = ?"
+ "SELECT id, name, machine_id, allowed_models, allowed_connections, no_log, auto_resolve, is_active, access_schedule, max_requests_per_day, max_requests_per_minute FROM api_keys WHERE key = ?"
);
_stmtInsertKey = db.prepare(
"INSERT INTO api_keys (id, name, key, machine_id, allowed_models, no_log, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)"
@@ -406,6 +416,8 @@ export async function updateApiKeyPermissions(
autoResolve?: boolean;
isActive?: boolean;
accessSchedule?: AccessSchedule | null;
+ maxRequestsPerDay?: number | null;
+ maxRequestsPerMinute?: number | null;
}
) {
const db = getDbInstance() as ApiKeysDbLike;
@@ -422,6 +434,8 @@ export async function updateApiKeyPermissions(
autoResolve: update.autoResolve,
isActive: update.isActive,
accessSchedule: update.accessSchedule,
+ maxRequestsPerDay: update.maxRequestsPerDay,
+ maxRequestsPerMinute: update.maxRequestsPerMinute,
};
if (
@@ -431,7 +445,9 @@ export async function updateApiKeyPermissions(
normalized.noLog === undefined &&
normalized.autoResolve === undefined &&
normalized.isActive === undefined &&
- normalized.accessSchedule === undefined
+ normalized.accessSchedule === undefined &&
+ normalized.maxRequestsPerDay === undefined &&
+ normalized.maxRequestsPerMinute === undefined
) {
return false;
}
@@ -446,6 +462,8 @@ export async function updateApiKeyPermissions(
autoResolve?: number;
isActive?: number;
accessSchedule?: string | null;
+ maxRequestsPerDay?: number | null;
+ maxRequestsPerMinute?: number | null;
} = { id };
if (normalized.name !== undefined) {
@@ -486,6 +504,16 @@ export async function updateApiKeyPermissions(
normalized.accessSchedule !== null ? JSON.stringify(normalized.accessSchedule) : null;
}
+ if (normalized.maxRequestsPerDay !== undefined) {
+ updates.push("max_requests_per_day = @maxRequestsPerDay");
+ params.maxRequestsPerDay = normalized.maxRequestsPerDay;
+ }
+
+ if (normalized.maxRequestsPerMinute !== undefined) {
+ updates.push("max_requests_per_minute = @maxRequestsPerMinute");
+ params.maxRequestsPerMinute = normalized.maxRequestsPerMinute;
+ }
+
const result = db.prepare(`UPDATE api_keys SET ${updates.join(", ")} WHERE id = @id`).run(params);
if (result.changes === 0) return false;
@@ -574,6 +602,9 @@ export async function getApiKeyMetadata(
const machineIdRaw = record.machine_id ?? record.machineId;
const metadataMachineId = typeof machineIdRaw === "string" ? machineIdRaw : null;
+ const rawMaxRPD = record.max_requests_per_day ?? record.maxRequestsPerDay;
+ const rawMaxRPM = record.max_requests_per_minute ?? record.maxRequestsPerMinute;
+
const metadata: ApiKeyMetadata = {
id: metadataId,
name: metadataName,
@@ -586,6 +617,8 @@ export async function getApiKeyMetadata(
autoResolve: parseAutoResolve(record.auto_resolve ?? record.autoResolve),
isActive: parseIsActive(record.is_active ?? record.isActive),
accessSchedule: parseAccessSchedule(record.access_schedule ?? record.accessSchedule),
+ maxRequestsPerDay: typeof rawMaxRPD === "number" && rawMaxRPD > 0 ? rawMaxRPD : null,
+ maxRequestsPerMinute: typeof rawMaxRPM === "number" && rawMaxRPM > 0 ? rawMaxRPM : null,
};
if (!metadata.id) {
diff --git a/src/shared/utils/apiKeyPolicy.ts b/src/shared/utils/apiKeyPolicy.ts
index 2e3eacaa47..a261f1a7e7 100644
--- a/src/shared/utils/apiKeyPolicy.ts
+++ b/src/shared/utils/apiKeyPolicy.ts
@@ -35,6 +35,8 @@ export interface ApiKeyMetadata {
usedBudget?: number;
isActive?: boolean;
accessSchedule?: AccessSchedule | null;
+ maxRequestsPerDay?: number | null;
+ maxRequestsPerMinute?: number | null;
}
/**
@@ -103,6 +105,65 @@ function isWithinSchedule(schedule: AccessSchedule): boolean {
return localMinutes >= fromMinutes && localMinutes < untilMinutes;
}
+// ── In-memory request counter for per-key rate limits (#452) ──
+
+/** Sliding-window request timestamps per API key */
+const _requestTimestamps = new Map<string, number[]>();
+const REQUEST_COUNTER_MAX_KEYS = 5000;
+const REQUEST_DAY_MS = 24 * 60 * 60 * 1000;
+const REQUEST_MINUTE_MS = 60 * 1000;
+
+/** Record a request and check per-key limits. Returns null if OK, or an error message. */
+function checkRequestCountLimits(
+ apiKeyId: string,
+ maxPerDay: number | null | undefined,
+ maxPerMinute: number | null | undefined
+): string | null {
+ if (!maxPerDay && !maxPerMinute) return null;
+
+ const now = Date.now();
+
+ // Get or create timestamp array for this key
+ let timestamps = _requestTimestamps.get(apiKeyId);
+ if (!timestamps) {
+ timestamps = [];
+ _requestTimestamps.set(apiKeyId, timestamps);
+ // Prevent unbounded growth
+ if (_requestTimestamps.size > REQUEST_COUNTER_MAX_KEYS) {
+ const firstKey = _requestTimestamps.keys().next().value;
+ if (firstKey) _requestTimestamps.delete(firstKey);
+ }
+ }
+
+ // Prune timestamps older than 24h
+ const dayAgo = now - REQUEST_DAY_MS;
+ while (timestamps.length > 0 && timestamps[0] < dayAgo) {
+ timestamps.shift();
+ }
+
+ // Check per-minute limit (before recording this request)
+ if (maxPerMinute && maxPerMinute > 0) {
+ const minuteAgo = now - REQUEST_MINUTE_MS;
+ const recentCount = timestamps.filter((t) => t >= minuteAgo).length;
+ if (recentCount >= maxPerMinute) {
+ return `Per-minute request limit exceeded (${maxPerMinute} RPM). Try again in a few seconds.`;
+ }
+ }
+
+ // Check per-day limit
+ if (maxPerDay && maxPerDay > 0) {
+ if (timestamps.length >= maxPerDay) {
+ return `Daily request limit exceeded (${maxPerDay} RPD). Resets in ${Math.ceil(
+ (timestamps[0] + REQUEST_DAY_MS - now) / 60000
+ )} minutes.`;
+ }
+ }
+
+ // All checks passed — record this request
+ timestamps.push(now);
+ return null;
+}
+
export interface ApiKeyPolicyResult {
/** API key string (null if no key provided) */
apiKey: string | null;
@@ -224,5 +285,21 @@ export async function enforceApiKeyPolicy(
}
}
+ // ── Check 5: Request-count limits (#452) ──
+ if (apiKeyInfo.id && (apiKeyInfo.maxRequestsPerDay || apiKeyInfo.maxRequestsPerMinute)) {
+ const limitError = checkRequestCountLimits(
+ apiKeyInfo.id,
+ apiKeyInfo.maxRequestsPerDay,
+ apiKeyInfo.maxRequestsPerMinute
+ );
+ if (limitError) {
+ return {
+ apiKey,
+ apiKeyInfo,
+ rejection: errorResponse(HTTP_STATUS.RATE_LIMITED, limitError),
+ };
+ }
+ }
+
return { apiKey, apiKeyInfo, rejection: null };
}