mapigate 0.5.133 → 0.5.141
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/cli/commands/logs.js +0 -1
- package/dist/core/adapters/anthropic/requestAnthropicToOpenAi.js +59 -11
- package/dist/core/adapters/anthropic/requestOpenAiToAnthropic.js +1 -1
- package/dist/core/adapters/anthropicAdapter.js +2 -2
- package/dist/core/adapters/helpers/toolCallRescue.js +1 -1
- package/dist/core/adapters/responsesAdapter.js +11 -0
- package/dist/core/capabilities/modelDictionary.js +1 -0
- package/dist/core/scanner/modelScanner.js +2 -1
- package/dist/core/scanner/payloadExtractor.js +1 -1
- package/dist/core/scanner/urlResolver.js +16 -0
- package/dist/core/tokenSaver/methods/rtk/autodetect.js +1 -1
- package/dist/core/tokenSaver/methods/rtk/filters/gitLog.js +1 -1
- package/dist/core/usage/pricing.js +98 -42
- package/dist/core/usage/tokenExtractor.js +59 -0
- package/dist/mitm/handlers/antigravity/config.js +22 -0
- package/dist/mitm/handlers/antigravity/modelInjector.js +2 -2
- package/dist/providers/catalog/commandcode/converter.js +215 -0
- package/dist/providers/catalog/commandcode/executor.js +305 -0
- package/dist/providers/catalog/commandcode/headers.js +76 -0
- package/dist/providers/catalog/commandcode/metadata.js +4 -1
- package/dist/providers/catalog/commandcode/ndjson.js +161 -0
- package/dist/providers/catalog/commandcode/provider.js +18 -35
- package/dist/providers/catalog/commandcode/routes.js +75 -0
- package/dist/providers/catalog/iflow/provider.js +1 -1
- package/dist/providers/catalog/iteracompute/metadata.js +154 -13
- package/dist/providers/catalog/iteracompute/provider.js +111 -0
- package/dist/providers/catalog/opencode-go/metadata.js +4 -2
- package/dist/providers/catalog/opencode-go/models.js +1 -0
- package/dist/providers/catalog/opencode-go/provider.js +114 -0
- package/dist/providers/catalog/opencode-go/quota.js +106 -0
- package/dist/providers/catalog/opencode-go/responses.js +301 -0
- package/dist/providers/catalog/opencode-go/responsesPayload.js +228 -0
- package/dist/providers/catalog/openrouter/metadata.js +1 -0
- package/dist/providers/catalog/sensenova/metadata.js +35 -0
- package/dist/providers/core/base/baseProvider.js +8 -3
- package/dist/providers/core/base/openAiProvider.js +3 -1
- package/dist/providers/generated/routesRegistry.generated.js +2 -0
- package/dist/providers/runtime/antigravity/executor.js +2 -2
- package/dist/providers/runtime/antigravity/metadata.js +2 -2
- package/dist/providers/runtime/antigravity/models.js +9 -0
- package/dist/providers/runtime/antigravity/provider.js +2 -2
- package/dist/providers/runtime/antigravity/routes.js +2 -2
- package/dist/providers/runtime/antigravity/schema.js +20 -2
- package/dist/providers/runtime/antigravity/types.js +10 -2
- package/dist/providers/runtime/codebuddy/provider.js +21 -6
- package/dist/providers/runtime/gemini/provider.js +77 -0
- package/dist/providers/runtime/gemini-cli/provider.js +2 -2
- package/dist/providers/runtime/github/routes.js +1 -1
- package/dist/providers/runtime/grok/provider.js +1 -1
- package/dist/providers/runtime/kiro/executor.js +7 -4
- package/dist/providers/runtime/kiro/models.js +11 -0
- package/dist/providers/runtime/kiro/provider.js +8 -8
- package/dist/providers/runtime/minimax/routes.js +0 -1
- package/dist/providers/runtime/opencode/tools.js +39 -17
- package/dist/providers/runtime/windsurf/routes.js +0 -2
- package/dist/providers/runtime/xkiro/quota.js +4 -1
- package/dist/server/proxy/executorHelpers.js +1 -1
- package/dist/server/proxy/index.js +1 -1
- package/dist/server/proxy/pipeline.js +12 -6
- package/dist/server/proxy/proxyDispatcher.js +136 -17
- package/dist/server/proxy/responseHandlers.js +2 -18
- package/dist/server/proxy/singleModelExecutor.js +15 -3
- package/dist/server/proxy/streaming/sseStreamer.js +3 -10
- package/dist/server/routes/apiMitm.js +1 -1
- package/dist/server/routes/apiModels.js +17 -12
- package/dist/server/utils/consoleLogBuffer.js +3 -3
- package/dist/shared/constants/index.js +2 -2
- package/dist/shared/logger.js +2 -2
- package/dist/shared/utils/dnsResolver.js +69 -27
- package/dist/storage/repositories/logRepo.js +3 -23
- package/dist/storage/repositories/requestDetailsRepo.js +1 -1
- package/dist/storage/repositories/usageRepo.js +136 -74
- package/dist/web/assets/{CliToolsTab-D4DkK7Rn.js → CliToolsTab-rKSWLJC3.js} +1 -1
- package/dist/web/assets/CombosTab-D1_cfssh.js +1 -0
- package/dist/web/assets/{ConfirmModal-CuQ7ARxt.js → ConfirmModal-OWeauwYv.js} +1 -1
- package/dist/web/assets/{ConsoleLogTab-B2sfhYZW.js → ConsoleLogTab-rZe8zCb_.js} +1 -1
- package/dist/web/assets/{EditAccountModal-BusNJLvX.js → EditAccountModal-CAg-yIOn.js} +1 -1
- package/dist/web/assets/{EndpointTab-DQCezUA9.js → EndpointTab-B-Jb4wAG.js} +1 -1
- package/dist/web/assets/{MitmTab-DxEuD0DW.js → MitmTab-5dKeNi4T.js} +5 -5
- package/dist/web/assets/{ModelAutocompleteInput-CgJ2FlEf.js → ModelAutocompleteInput-CoinzdsW.js} +1 -1
- package/dist/web/assets/ProviderDetailPage-D-fodBhz.js +6 -0
- package/dist/web/assets/ProvidersTab-yzmb4w0D.js +1 -0
- package/dist/web/assets/{QuotaTab-CvXGyICr.js → QuotaTab-BXevQzen.js} +1 -1
- package/dist/web/assets/{SettingsTab-D7YF7rTP.js → SettingsTab-LkByv4Sg.js} +1 -1
- package/dist/web/assets/UsageTab-Hr8XPZD4.js +1 -0
- package/dist/web/assets/index-CKuvklEr.js +2 -0
- package/dist/web/assets/{index-BisuNW2y.css → index-HnsyZg0I.css} +1 -1
- package/dist/web/assets/metadataRegistry-NuDSSkP9.js +1 -0
- package/dist/web/assets/providers/openrouter/icon.png +0 -0
- package/dist/web/assets/providersData-DS1-ETBi.js +1 -0
- package/dist/web/index.html +2 -2
- package/package.json +9 -1
- package/dist/web/assets/CombosTab-X1C_OmzI.js +0 -1
- package/dist/web/assets/ProviderDetailPage-DMA1DVSN.js +0 -6
- package/dist/web/assets/ProvidersTab-pZoM69s4.js +0 -1
- package/dist/web/assets/UsageTab-B0YCftIJ.js +0 -1
- package/dist/web/assets/index-DTRst7wN.js +0 -2
- package/dist/web/assets/metadataRegistry-BPZSXiBy.js +0 -1
- package/dist/web/assets/providers/openrouter/openrouter.png +0 -0
- package/dist/web/assets/providersData-Bsv7o5VV.js +0 -1
|
@@ -4,7 +4,7 @@ import { createResponsesStreamState, openAiChunkToResponsesEvents, finalizeRespo
|
|
|
4
4
|
import { decodeEventStreamChunk } from "../bedrock/eventStream.js";
|
|
5
5
|
import { extractTokenFromAccount } from "../../core/base/tokenExtractor.js";
|
|
6
6
|
import { buildKiroPayload } from "./converter.js";
|
|
7
|
-
import { normalizeKiroUpstreamModelId } from "./models.js";
|
|
7
|
+
import { normalizeKiroUpstreamModelId, resolveKiroServiceRegion } from "./models.js";
|
|
8
8
|
import { refreshKiroToken } from "./auth.js";
|
|
9
9
|
import { resolveDefaultProfileArn } from "./quota.js";
|
|
10
10
|
import { ResponseLogger } from "../../../server/proxy/responseLogger.js";
|
|
@@ -80,13 +80,16 @@ export async function executeKiro(context, _providerInstance) {
|
|
|
80
80
|
let targetUrl = accountBase || providerBase;
|
|
81
81
|
if (!targetUrl) {
|
|
82
82
|
if (authMethod === "external_idp") {
|
|
83
|
-
|
|
83
|
+
const cwRegion = resolveKiroServiceRegion("codewhisperer", region);
|
|
84
|
+
targetUrl = `https://codewhisperer.${cwRegion}.amazonaws.com/generateAssistantResponse`;
|
|
84
85
|
}
|
|
85
86
|
else if (authMethod === "api-key" || authMethod === "api_key") {
|
|
86
|
-
|
|
87
|
+
const qRegion = resolveKiroServiceRegion("q", region);
|
|
88
|
+
targetUrl = `https://q.${qRegion}.amazonaws.com/generateAssistantResponse`;
|
|
87
89
|
}
|
|
88
90
|
else {
|
|
89
|
-
|
|
91
|
+
const runtimeRegion = resolveKiroServiceRegion("runtime", region);
|
|
92
|
+
targetUrl = `https://runtime.${runtimeRegion}.kiro.dev/generateAssistantResponse`;
|
|
90
93
|
}
|
|
91
94
|
}
|
|
92
95
|
if (targetUrl.includes("://codewhisperer.")) {
|
|
@@ -49,6 +49,17 @@ export const models = [
|
|
|
49
49
|
{ "id": "gpt-5.6-luna-thinking-agentic", "name": "GPT 5.6 Luna (Thinking + Agentic)", "upstreamModelId": "gpt-5.6-luna", "isDefault": false, "contextLength": 272000 },
|
|
50
50
|
];
|
|
51
51
|
const ANTHROPIC_SNAPSHOT_SUFFIX = /-\d{8}$/;
|
|
52
|
+
export const KIRO_SERVICE_REGIONS = {
|
|
53
|
+
q: new Set(["us-east-1", "eu-central-1"]),
|
|
54
|
+
runtime: new Set(["us-east-1", "eu-central-1"]),
|
|
55
|
+
management: new Set(["us-east-1", "eu-central-1"]),
|
|
56
|
+
codewhisperer: new Set(["us-east-1"]),
|
|
57
|
+
};
|
|
58
|
+
export function resolveKiroServiceRegion(service, requestedRegion) {
|
|
59
|
+
const clean = (requestedRegion || "us-east-1").trim() || "us-east-1";
|
|
60
|
+
const covered = KIRO_SERVICE_REGIONS[service];
|
|
61
|
+
return covered && covered.has(clean) ? clean : "us-east-1";
|
|
62
|
+
}
|
|
52
63
|
export function normalizeKiroUpstreamModelId(model) {
|
|
53
64
|
if (typeof model !== "string" || !model)
|
|
54
65
|
return model || "";
|
|
@@ -6,7 +6,7 @@ import { fetch as undiciFetch } from "undici";
|
|
|
6
6
|
import { extractModelsFromPayload } from "../../../core/scanner/payloadExtractor.js";
|
|
7
7
|
import { executeKiro } from "./executor.js";
|
|
8
8
|
import { refreshKiroToken } from "./auth.js";
|
|
9
|
-
import { normalizeKiroUpstreamModelId } from "./models.js";
|
|
9
|
+
import { normalizeKiroUpstreamModelId, resolveKiroServiceRegion } from "./models.js";
|
|
10
10
|
export { normalizeKiroUpstreamModelId };
|
|
11
11
|
export class KiroProvider extends OpenAiCompatibleProvider {
|
|
12
12
|
id = "kiro";
|
|
@@ -41,15 +41,15 @@ export class KiroProvider extends OpenAiCompatibleProvider {
|
|
|
41
41
|
const authMethod = psd.authMethod;
|
|
42
42
|
const region = psd.region || "us-east-1";
|
|
43
43
|
if (authMethod === "external_idp") {
|
|
44
|
-
return `https://codewhisperer.${region}.amazonaws.com/generateAssistantResponse`;
|
|
44
|
+
return `https://codewhisperer.${resolveKiroServiceRegion("codewhisperer", region)}.amazonaws.com/generateAssistantResponse`;
|
|
45
45
|
}
|
|
46
46
|
if (authMethod === "api-key" || authMethod === "api_key") {
|
|
47
|
-
return `https://q.${region}.amazonaws.com/generateAssistantResponse`;
|
|
47
|
+
return `https://q.${resolveKiroServiceRegion("q", region)}.amazonaws.com/generateAssistantResponse`;
|
|
48
48
|
}
|
|
49
49
|
const provBase = (context.provider?.baseUrl || "").trim();
|
|
50
50
|
if (provBase)
|
|
51
51
|
return provBase;
|
|
52
|
-
return `https://runtime.${region}.kiro.dev/generateAssistantResponse`;
|
|
52
|
+
return `https://runtime.${resolveKiroServiceRegion("runtime", region)}.kiro.dev/generateAssistantResponse`;
|
|
53
53
|
}
|
|
54
54
|
async buildHeaders(context) {
|
|
55
55
|
const headers = await super.buildHeaders(context);
|
|
@@ -76,7 +76,7 @@ export class KiroProvider extends OpenAiCompatibleProvider {
|
|
|
76
76
|
async probeModels(context) {
|
|
77
77
|
const timeoutMs = context.timeoutMs || 8000;
|
|
78
78
|
const region = context.region || context.account?.providerSpecificData?.region || "us-east-1";
|
|
79
|
-
|
|
79
|
+
const token = (context.apiKey || context.account?.providerSpecificData?.accessToken || context.account?.rawApiKey || "").trim();
|
|
80
80
|
const profileArn = context.account?.providerSpecificData?.profileArn || resolveDefaultProfileArn(context.account?.providerSpecificData?.authMethod);
|
|
81
81
|
// Enforce Coral JSON RPC headers (customHeaders must not override Content-Type or Accept)
|
|
82
82
|
const reqHeaders = {
|
|
@@ -97,9 +97,9 @@ export class KiroProvider extends OpenAiCompatibleProvider {
|
|
|
97
97
|
reqHeaders["TokenType"] = "EXTERNAL_IDP";
|
|
98
98
|
}
|
|
99
99
|
const candidateUrls = [
|
|
100
|
-
`https://management.${region}.kiro.dev`,
|
|
101
|
-
`https://codewhisperer.${region}.amazonaws.com`,
|
|
102
|
-
`https://q.${region}.amazonaws.com`,
|
|
100
|
+
`https://management.${resolveKiroServiceRegion("management", region)}.kiro.dev`,
|
|
101
|
+
`https://codewhisperer.${resolveKiroServiceRegion("codewhisperer", region)}.amazonaws.com`,
|
|
102
|
+
`https://q.${resolveKiroServiceRegion("q", region)}.amazonaws.com`,
|
|
103
103
|
];
|
|
104
104
|
let lastError;
|
|
105
105
|
for (const url of candidateUrls) {
|
|
@@ -4,7 +4,6 @@ import { OAuthHandlerRegistry } from "../../core/oauthRegistry.js";
|
|
|
4
4
|
import { generatePKCE } from "../../../shared/utils/pkce.js";
|
|
5
5
|
const minimaxPendingVerifiers = new Map();
|
|
6
6
|
export async function requestMinimaxDeviceCode(params) {
|
|
7
|
-
const pId = (params?.provider || "minimax-code").toLowerCase();
|
|
8
7
|
const region = params?.region || params?.extraData?.region;
|
|
9
8
|
const isCn = region === "cn";
|
|
10
9
|
const url = isCn
|
|
@@ -48,6 +48,14 @@ export function withFingerprintDefinition(tool, key, isClaude = false) {
|
|
|
48
48
|
? { ...tool, function: { ...fn, name: key, description, parameters } }
|
|
49
49
|
: { ...tool, name: key, description, parameters };
|
|
50
50
|
}
|
|
51
|
+
export const GATED_TOOL_NAME_RE = /terminal/i;
|
|
52
|
+
const GATED_TOOL_ALIAS = "run_command";
|
|
53
|
+
function withToolName(tool, alias) {
|
|
54
|
+
const fn = chatFunctionOf(tool);
|
|
55
|
+
return fn
|
|
56
|
+
? { ...tool, function: { ...fn, name: alias } }
|
|
57
|
+
: { ...tool, name: alias };
|
|
58
|
+
}
|
|
51
59
|
export function concealFingerprintToolNames(tools, isClaude = false) {
|
|
52
60
|
const map = new Map();
|
|
53
61
|
if (!Array.isArray(tools) || tools.length === 0)
|
|
@@ -61,6 +69,16 @@ export function concealFingerprintToolNames(tools, isClaude = false) {
|
|
|
61
69
|
continue;
|
|
62
70
|
}
|
|
63
71
|
const current = toolNameOf(tool);
|
|
72
|
+
if (GATED_TOOL_NAME_RE.test(current)) {
|
|
73
|
+
let alias = GATED_TOOL_ALIAS;
|
|
74
|
+
for (let i = 2; taken.has(alias); i++) {
|
|
75
|
+
alias = `${GATED_TOOL_ALIAS}${i}`;
|
|
76
|
+
}
|
|
77
|
+
taken.add(alias);
|
|
78
|
+
map.set(alias, current);
|
|
79
|
+
out.push(withToolName(tool, alias));
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
64
82
|
const key = fingerprintToolKey(current);
|
|
65
83
|
if (!key) {
|
|
66
84
|
out.push(tool);
|
|
@@ -88,13 +106,7 @@ export function concealFingerprintToolNames(tools, isClaude = false) {
|
|
|
88
106
|
}
|
|
89
107
|
taken.add(alias);
|
|
90
108
|
map.set(alias, current);
|
|
91
|
-
|
|
92
|
-
if (fn) {
|
|
93
|
-
out.push({ ...tool, function: { ...fn, name: alias } });
|
|
94
|
-
}
|
|
95
|
-
else {
|
|
96
|
-
out.push({ ...tool, name: alias });
|
|
97
|
-
}
|
|
109
|
+
out.push(withToolName(tool, alias));
|
|
98
110
|
}
|
|
99
111
|
return { tools: out, map };
|
|
100
112
|
}
|
|
@@ -240,29 +252,39 @@ export function applyEnvFingerprint(body, flat, { claude = false } = {}) {
|
|
|
240
252
|
return false;
|
|
241
253
|
}
|
|
242
254
|
}
|
|
243
|
-
export function retargetToolChoice(body, map,
|
|
255
|
+
export function retargetToolChoice(body, map, _format = "openai") {
|
|
244
256
|
if (!body || typeof body !== "object" || !map?.size)
|
|
245
257
|
return;
|
|
246
258
|
const choice = body.tool_choice;
|
|
247
259
|
if (!choice || typeof choice !== "object" || Array.isArray(choice))
|
|
248
260
|
return;
|
|
249
|
-
|
|
250
|
-
const key = fingerprintToolKey(
|
|
261
|
+
const resolveAlias = (name) => {
|
|
262
|
+
const key = fingerprintToolKey(name);
|
|
251
263
|
if (key && map.has(key))
|
|
252
|
-
|
|
264
|
+
return key;
|
|
265
|
+
for (const [alias, orig] of map.entries()) {
|
|
266
|
+
if (orig === name)
|
|
267
|
+
return alias;
|
|
268
|
+
}
|
|
269
|
+
return null;
|
|
270
|
+
};
|
|
271
|
+
if (choice.type === "tool" && typeof choice.name === "string") {
|
|
272
|
+
const target = resolveAlias(choice.name);
|
|
273
|
+
if (target)
|
|
274
|
+
choice.name = target;
|
|
253
275
|
return;
|
|
254
276
|
}
|
|
255
277
|
if (typeof choice.name === "string") {
|
|
256
|
-
const
|
|
257
|
-
if (
|
|
258
|
-
body.tool_choice = { ...choice, name:
|
|
278
|
+
const target = resolveAlias(choice.name);
|
|
279
|
+
if (target)
|
|
280
|
+
body.tool_choice = { ...choice, name: target };
|
|
259
281
|
return;
|
|
260
282
|
}
|
|
261
283
|
const fn = choice.function;
|
|
262
284
|
if (fn && typeof fn === "object" && !Array.isArray(fn) && typeof fn.name === "string") {
|
|
263
|
-
const
|
|
264
|
-
if (
|
|
265
|
-
body.tool_choice = { ...choice, function: { ...fn, name:
|
|
285
|
+
const target = resolveAlias(fn.name);
|
|
286
|
+
if (target) {
|
|
287
|
+
body.tool_choice = { ...choice, function: { ...fn, name: target } };
|
|
266
288
|
}
|
|
267
289
|
}
|
|
268
290
|
}
|
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
import crypto from "node:crypto";
|
|
2
2
|
import { OAuthHandlerRegistry } from "../../core/oauthRegistry.js";
|
|
3
3
|
import { ProviderRepository } from "../../../storage/repositories/providerRepo.js";
|
|
4
|
-
import { resolvePublicCred } from "../../../shared/utils/publicCreds.js";
|
|
5
|
-
const WINDSURF_CLIENT_ID = resolvePublicCred("windsurf_client_id");
|
|
6
4
|
const WINDSURF_REGISTER_URL = "https://register.windsurf.com/exa.seat_management_pb.SeatManagementService/RegisterUser";
|
|
7
5
|
const DEVIN_AUTH_CODE_URL = "https://app.devin.ai/auth/windsurf/show-auth-code";
|
|
8
6
|
function parseWindsurfCallback(raw) {
|
|
@@ -50,7 +50,10 @@ export function parseXKiroUsageData(data) {
|
|
|
50
50
|
const limit = Number(ft.limit_per_day);
|
|
51
51
|
if (Number.isFinite(limit) && limit > 0) {
|
|
52
52
|
const used = Number(ft.used_today) || 0;
|
|
53
|
-
const
|
|
53
|
+
const parsedRemaining = Number(ft.remaining);
|
|
54
|
+
const remaining = ft.remaining !== undefined && ft.remaining !== null && Number.isFinite(parsedRemaining)
|
|
55
|
+
? parsedRemaining
|
|
56
|
+
: Math.max(0, limit - used);
|
|
54
57
|
const remainingPercentage = Math.max(0, Math.min(100, Math.round((remaining / limit) * 100)));
|
|
55
58
|
const now = new Date();
|
|
56
59
|
const nextUtcMidnight = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() + 1, 0, 0, 0));
|
|
@@ -48,7 +48,7 @@ export function resolveTargetModelAndProvider(modelStr) {
|
|
|
48
48
|
const rawProvider = effective.slice(0, slash);
|
|
49
49
|
targetModel = effective.slice(slash + 1);
|
|
50
50
|
// Parse provider[tag] syntax, e.g. claude[pro] -> provider: claude, tag: pro
|
|
51
|
-
const tagMatch = rawProvider.match(/^([
|
|
51
|
+
const tagMatch = rawProvider.match(/^([^[\]]+)\[([^[\]]+)\]$/);
|
|
52
52
|
if (tagMatch) {
|
|
53
53
|
providerId = tagMatch[1];
|
|
54
54
|
targetTag = tagMatch[2];
|
|
@@ -32,7 +32,7 @@ export async function handleProxyRequest(req, res, clientFormat) {
|
|
|
32
32
|
providedKey = apiKeyHeader.trim();
|
|
33
33
|
}
|
|
34
34
|
// Resolve client gateway API key if provided
|
|
35
|
-
|
|
35
|
+
const matchedKey = providedKey ? allKeys.find((k) => safeCompareKeys(k.key, providedKey)) : undefined;
|
|
36
36
|
if (endpointSettings.requireApiKey) {
|
|
37
37
|
const activeKeys = allKeys.filter((k) => k.isActive);
|
|
38
38
|
if (activeKeys.length === 0 || !matchedKey || !matchedKey.isActive) {
|
|
@@ -14,6 +14,7 @@ import { AnthropicAdapter } from "../../core/adapters/anthropicAdapter.js";
|
|
|
14
14
|
import { convertOpenAiResponseToResponsesApi } from "../../core/adapters/responsesAdapter.js";
|
|
15
15
|
import { sanitizeErrorMessage } from "../../shared/utils/errorSanitizer.js";
|
|
16
16
|
import { resolveTargetModelAndProvider } from "./executorHelpers.js";
|
|
17
|
+
import { extractUsageTokens } from "../../core/usage/tokenExtractor.js";
|
|
17
18
|
import crypto from "node:crypto";
|
|
18
19
|
export function formatProxyErrorResponse(status, message, clientFormat) {
|
|
19
20
|
if (clientFormat === "anthropic") {
|
|
@@ -255,10 +256,15 @@ export async function runProxyPipeline(req, res, clientFormat) {
|
|
|
255
256
|
let promptTokens = 0;
|
|
256
257
|
let completionTokens = 0;
|
|
257
258
|
let cachedTokens = 0;
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
259
|
+
let cacheCreationTokens = 0;
|
|
260
|
+
let reasoningTokens = 0;
|
|
261
|
+
if (typeof respData === "object" && respData !== null && (respData.usage || respData.usageMetadata)) {
|
|
262
|
+
const extracted = extractUsageTokens(respData);
|
|
263
|
+
promptTokens = extracted.promptTokens;
|
|
264
|
+
completionTokens = extracted.completionTokens;
|
|
265
|
+
cachedTokens = extracted.cachedTokens;
|
|
266
|
+
cacheCreationTokens = extracted.cacheCreationTokens;
|
|
267
|
+
reasoningTokens = extracted.reasoningTokens;
|
|
262
268
|
}
|
|
263
269
|
ResponseLogger.logSuccess({
|
|
264
270
|
requestId,
|
|
@@ -273,8 +279,8 @@ export async function runProxyPipeline(req, res, clientFormat) {
|
|
|
273
279
|
promptTokens,
|
|
274
280
|
completionTokens,
|
|
275
281
|
cachedTokens,
|
|
276
|
-
cacheCreationTokens
|
|
277
|
-
reasoningTokens
|
|
282
|
+
cacheCreationTokens,
|
|
283
|
+
reasoningTokens,
|
|
278
284
|
tokensSavedByRtk: rtkStats.tokensSaved,
|
|
279
285
|
is1mContext,
|
|
280
286
|
requestHeaders: req.headers,
|
|
@@ -1,11 +1,93 @@
|
|
|
1
|
-
import { fetch as undiciFetch, ProxyAgent } from "undici";
|
|
2
|
-
import { getPublicDnsAgent } from "../../shared/utils/dnsResolver.js";
|
|
1
|
+
import { Agent as UndiciAgent, fetch as undiciFetch, ProxyAgent } from "undici";
|
|
2
|
+
import { EYEBALLS_CONNECT, FRESH_RETRY_KEEPALIVE_TIMEOUT_MS, TLS_ECDH_CURVE, clearPublicDnsAgents, getPublicDnsAgent, resolveKeepAliveTimeouts, } from "../../shared/utils/dnsResolver.js";
|
|
3
3
|
import { isMitmHost } from "../../mitm/toolsHelper.js";
|
|
4
4
|
const defaultGlobalFetch = globalThis.fetch;
|
|
5
5
|
const MAX_PROXY_DISPATCHERS = 50;
|
|
6
6
|
const proxyDispatchers = new Map();
|
|
7
|
-
|
|
8
|
-
|
|
7
|
+
const directDispatchers = new Map();
|
|
8
|
+
// Dead keep-alive sockets surface as these codes/substrings; DNS, connect-refused and TLS
|
|
9
|
+
// failures are excluded so a real unreachable host is never mistaken for a stale socket.
|
|
10
|
+
export const STALE_SOCKET_ERROR_CODES = new Set([
|
|
11
|
+
"UND_ERR_SOCKET",
|
|
12
|
+
"ECONNRESET",
|
|
13
|
+
"EPIPE",
|
|
14
|
+
"UND_ERR_HEADERS_TIMEOUT",
|
|
15
|
+
]);
|
|
16
|
+
export const NON_STALE_SOCKET_ERROR_CODES = new Set([
|
|
17
|
+
"ENOTFOUND",
|
|
18
|
+
"EAI_AGAIN",
|
|
19
|
+
"ECONNREFUSED",
|
|
20
|
+
"EHOSTUNREACH",
|
|
21
|
+
"ENETUNREACH",
|
|
22
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
23
|
+
"UND_ERR_INVALID_ARG",
|
|
24
|
+
]);
|
|
25
|
+
// Deliberately excludes a bare "fetch failed": with no error code the upstream may already
|
|
26
|
+
// hold the request, and replaying it would send (and bill) the same completion twice.
|
|
27
|
+
export const STALE_SOCKET_ERROR_SUBSTRINGS = [
|
|
28
|
+
"other side closed",
|
|
29
|
+
"socket hang up",
|
|
30
|
+
];
|
|
31
|
+
export function isFreshSocketReplayEnabled() {
|
|
32
|
+
const raw = String(process.env.MAPIGATE_FETCH_FRESH_RETRY ?? "").trim().toLowerCase();
|
|
33
|
+
return !(raw === "off" || raw === "0" || raw === "false" || raw === "no");
|
|
34
|
+
}
|
|
35
|
+
export function isStaleSocketError(error) {
|
|
36
|
+
if (!error || error.name === "AbortError")
|
|
37
|
+
return false;
|
|
38
|
+
const code = error?.cause?.code || error?.code || "";
|
|
39
|
+
if (typeof code === "string" && code.startsWith("ERR_TLS_"))
|
|
40
|
+
return false;
|
|
41
|
+
if (NON_STALE_SOCKET_ERROR_CODES.has(code))
|
|
42
|
+
return false;
|
|
43
|
+
if (STALE_SOCKET_ERROR_CODES.has(code))
|
|
44
|
+
return true;
|
|
45
|
+
const msg = `${error?.message || ""} ${error?.cause?.message || ""}`.toLowerCase();
|
|
46
|
+
return STALE_SOCKET_ERROR_SUBSTRINGS.some((sub) => msg.includes(sub));
|
|
47
|
+
}
|
|
48
|
+
function buildDirectAgent(key, insecure, keepAliveTimeout, keepAliveMaxTimeout) {
|
|
49
|
+
const cached = directDispatchers.get(key);
|
|
50
|
+
if (cached) {
|
|
51
|
+
directDispatchers.delete(key);
|
|
52
|
+
directDispatchers.set(key, cached);
|
|
53
|
+
return cached;
|
|
54
|
+
}
|
|
55
|
+
if (directDispatchers.size >= MAX_PROXY_DISPATCHERS) {
|
|
56
|
+
const oldestKey = directDispatchers.keys().next().value;
|
|
57
|
+
if (oldestKey) {
|
|
58
|
+
const oldAgent = directDispatchers.get(oldestKey);
|
|
59
|
+
directDispatchers.delete(oldestKey);
|
|
60
|
+
try {
|
|
61
|
+
oldAgent?.destroy?.();
|
|
62
|
+
oldAgent?.close?.();
|
|
63
|
+
}
|
|
64
|
+
catch { }
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
const agent = new UndiciAgent({
|
|
68
|
+
connect: {
|
|
69
|
+
...EYEBALLS_CONNECT,
|
|
70
|
+
ecdhCurve: TLS_ECDH_CURVE,
|
|
71
|
+
...(insecure ? { rejectUnauthorized: false } : {}),
|
|
72
|
+
},
|
|
73
|
+
keepAliveTimeout,
|
|
74
|
+
keepAliveMaxTimeout,
|
|
75
|
+
});
|
|
76
|
+
directDispatchers.set(key, agent);
|
|
77
|
+
return agent;
|
|
78
|
+
}
|
|
79
|
+
export function getDirectDispatcher(insecure = false) {
|
|
80
|
+
const { keepAliveTimeout, keepAliveMaxTimeout } = resolveKeepAliveTimeouts();
|
|
81
|
+
const key = `direct::${insecure ? "insecure" : "secure"}::${keepAliveTimeout}::${keepAliveMaxTimeout}`;
|
|
82
|
+
return buildDirectAgent(key, insecure, keepAliveTimeout, keepAliveMaxTimeout);
|
|
83
|
+
}
|
|
84
|
+
export function getFreshRetryDispatcher(insecure = false) {
|
|
85
|
+
const key = `fresh::${insecure ? "insecure" : "secure"}`;
|
|
86
|
+
return buildDirectAgent(key, insecure, FRESH_RETRY_KEEPALIVE_TIMEOUT_MS, FRESH_RETRY_KEEPALIVE_TIMEOUT_MS);
|
|
87
|
+
}
|
|
88
|
+
export function getProxyDispatcher(proxyUrl, insecure = false) {
|
|
89
|
+
const key = `${proxyUrl}::${insecure ? "insecure" : "secure"}`;
|
|
90
|
+
let dispatcher = proxyDispatchers.get(key);
|
|
9
91
|
if (!dispatcher) {
|
|
10
92
|
if (proxyDispatchers.size >= MAX_PROXY_DISPATCHERS) {
|
|
11
93
|
const oldestKey = proxyDispatchers.keys().next().value;
|
|
@@ -19,27 +101,35 @@ export function getProxyDispatcher(proxyUrl) {
|
|
|
19
101
|
catch { }
|
|
20
102
|
}
|
|
21
103
|
}
|
|
22
|
-
dispatcher = new ProxyAgent(
|
|
23
|
-
|
|
104
|
+
dispatcher = new ProxyAgent({
|
|
105
|
+
uri: proxyUrl,
|
|
106
|
+
connect: { ...EYEBALLS_CONNECT },
|
|
107
|
+
requestTls: {
|
|
108
|
+
ecdhCurve: TLS_ECDH_CURVE,
|
|
109
|
+
...(insecure ? { rejectUnauthorized: false } : {}),
|
|
110
|
+
},
|
|
111
|
+
});
|
|
112
|
+
proxyDispatchers.set(key, dispatcher);
|
|
24
113
|
}
|
|
25
114
|
else {
|
|
26
|
-
proxyDispatchers.delete(
|
|
27
|
-
proxyDispatchers.set(
|
|
115
|
+
proxyDispatchers.delete(key);
|
|
116
|
+
proxyDispatchers.set(key, dispatcher);
|
|
28
117
|
}
|
|
29
118
|
return dispatcher;
|
|
30
119
|
}
|
|
31
|
-
|
|
120
|
+
async function performSingleUpstreamFetch(url, options, proxyUrl, forceFreshSocket = false) {
|
|
121
|
+
const { forceFreshSocket: _ignored, ...fetchOpts } = options || {};
|
|
32
122
|
// If globalThis.fetch was mocked (e.g. in unit tests), honor the mock
|
|
33
|
-
if (globalThis.fetch !== defaultGlobalFetch && !proxyUrl && !
|
|
34
|
-
return (await globalThis.fetch(url,
|
|
123
|
+
if (globalThis.fetch !== defaultGlobalFetch && !proxyUrl && !fetchOpts.dispatcher) {
|
|
124
|
+
return (await globalThis.fetch(url, fetchOpts));
|
|
35
125
|
}
|
|
36
126
|
const effectiveProxy = proxyUrl?.trim();
|
|
37
127
|
if (effectiveProxy) {
|
|
38
128
|
const dispatcher = getProxyDispatcher(effectiveProxy);
|
|
39
|
-
return (await undiciFetch(url, { ...
|
|
129
|
+
return (await undiciFetch(url, { ...fetchOpts, dispatcher }));
|
|
40
130
|
}
|
|
41
|
-
if (
|
|
42
|
-
return (await undiciFetch(url,
|
|
131
|
+
if (fetchOpts.dispatcher) {
|
|
132
|
+
return (await undiciFetch(url, fetchOpts));
|
|
43
133
|
}
|
|
44
134
|
let hostname = "";
|
|
45
135
|
try {
|
|
@@ -47,10 +137,30 @@ export async function executeUpstreamFetch(url, options, proxyUrl) {
|
|
|
47
137
|
}
|
|
48
138
|
catch { }
|
|
49
139
|
if (isMitmHost(hostname)) {
|
|
50
|
-
const publicAgent = getPublicDnsAgent();
|
|
51
|
-
return (await undiciFetch(url, { ...
|
|
140
|
+
const publicAgent = getPublicDnsAgent({ forceFreshSocket });
|
|
141
|
+
return (await undiciFetch(url, { ...fetchOpts, dispatcher: publicAgent }));
|
|
142
|
+
}
|
|
143
|
+
const directDispatcher = forceFreshSocket ? getFreshRetryDispatcher(false) : getDirectDispatcher(false);
|
|
144
|
+
return (await undiciFetch(url, { ...fetchOpts, dispatcher: directDispatcher }));
|
|
145
|
+
}
|
|
146
|
+
function isReplayableBody(body) {
|
|
147
|
+
return body == null || typeof body === "string" || ArrayBuffer.isView(body) || body instanceof ArrayBuffer;
|
|
148
|
+
}
|
|
149
|
+
export async function executeUpstreamFetch(url, options, proxyUrl) {
|
|
150
|
+
const forceFresh = options?.forceFreshSocket === true;
|
|
151
|
+
try {
|
|
152
|
+
return await performSingleUpstreamFetch(url, options, proxyUrl, forceFresh);
|
|
153
|
+
}
|
|
154
|
+
catch (err) {
|
|
155
|
+
if (!forceFresh &&
|
|
156
|
+
!options?.dispatcher &&
|
|
157
|
+
isReplayableBody(options?.body) &&
|
|
158
|
+
isFreshSocketReplayEnabled() &&
|
|
159
|
+
isStaleSocketError(err)) {
|
|
160
|
+
return await performSingleUpstreamFetch(url, options, proxyUrl, true);
|
|
161
|
+
}
|
|
162
|
+
throw err;
|
|
52
163
|
}
|
|
53
|
-
return (await globalThis.fetch(url, options));
|
|
54
164
|
}
|
|
55
165
|
export function clearProxyDispatchers() {
|
|
56
166
|
for (const dispatcher of proxyDispatchers.values()) {
|
|
@@ -61,4 +171,13 @@ export function clearProxyDispatchers() {
|
|
|
61
171
|
catch { }
|
|
62
172
|
}
|
|
63
173
|
proxyDispatchers.clear();
|
|
174
|
+
for (const agent of directDispatchers.values()) {
|
|
175
|
+
try {
|
|
176
|
+
agent?.destroy?.();
|
|
177
|
+
agent?.close?.();
|
|
178
|
+
}
|
|
179
|
+
catch { }
|
|
180
|
+
}
|
|
181
|
+
directDispatchers.clear();
|
|
182
|
+
clearPublicDnsAgents();
|
|
64
183
|
}
|
|
@@ -7,6 +7,7 @@ import { reasoningCache } from "../../core/caching/reasoningCache.js";
|
|
|
7
7
|
import { OpenAiAdapter } from "../../core/adapters/openAiAdapter.js";
|
|
8
8
|
import { AnthropicAdapter } from "../../core/adapters/anthropicAdapter.js";
|
|
9
9
|
import { convertOpenAiResponseToResponsesApi } from "../../core/adapters/responsesAdapter.js";
|
|
10
|
+
import { extractUsageTokens } from "../../core/usage/tokenExtractor.js";
|
|
10
11
|
export async function handleNonStreamingResponse(upstreamRes, res, context, provider, meta) {
|
|
11
12
|
const { startTime, targetModel, rawModel, clientTool, rtkStats, is1mContext, req, account } = context;
|
|
12
13
|
const durationMs = Date.now() - startTime;
|
|
@@ -42,24 +43,7 @@ export async function handleNonStreamingResponse(upstreamRes, res, context, prov
|
|
|
42
43
|
else {
|
|
43
44
|
res.status(200).send(responseBody);
|
|
44
45
|
}
|
|
45
|
-
const
|
|
46
|
-
let promptTokens = usage.prompt_tokens ?? usage.input_tokens ?? usage.prompt_eval_count ?? rtkStats.compressedTokens ?? 0;
|
|
47
|
-
const completionTokens = usage.completion_tokens ?? usage.output_tokens ?? usage.eval_count ?? 0;
|
|
48
|
-
const cachedTokens = usage.prompt_tokens_details?.cached_tokens ??
|
|
49
|
-
usage.input_tokens_details?.cached_tokens ??
|
|
50
|
-
usage.prompt_cache_hit_tokens ??
|
|
51
|
-
usage.cache_read_input_tokens ??
|
|
52
|
-
usage.cachedContentTokenCount ??
|
|
53
|
-
usage.cached_tokens ??
|
|
54
|
-
0;
|
|
55
|
-
const cacheCreationTokens = usage.cache_creation_input_tokens ?? 0;
|
|
56
|
-
const reasoningTokens = usage.completion_tokens_details?.reasoning_tokens ??
|
|
57
|
-
usage.output_tokens_details?.reasoning_tokens ??
|
|
58
|
-
usage.reasoning_tokens ??
|
|
59
|
-
0;
|
|
60
|
-
if (usage.input_tokens !== undefined && usage.prompt_tokens === undefined) {
|
|
61
|
-
promptTokens = (usage.input_tokens || 0) + cachedTokens + cacheCreationTokens;
|
|
62
|
-
}
|
|
46
|
+
const { promptTokens, completionTokens, cachedTokens, cacheCreationTokens, reasoningTokens, } = extractUsageTokens(responseBody, rtkStats.compressedTokens ?? 0);
|
|
63
47
|
const calculatedCost = ResponseLogger.logSuccess({
|
|
64
48
|
requestId: context.requestId,
|
|
65
49
|
startTime,
|
|
@@ -54,7 +54,7 @@ function cloneBodyForUpstream(body) {
|
|
|
54
54
|
export async function executeSingleModel(options) {
|
|
55
55
|
const { req, res, body, modelStr, clientFormat, isPanel = false, requestId, startTime, clientTool, rawModel, rtkStats, is1mContext: optionIs1m, reqTag = options.req.reqTag || tagForSession(options.requestId), apiKeyId, apiKeyName, } = options;
|
|
56
56
|
const resolved = resolveTargetModelAndProvider(modelStr);
|
|
57
|
-
|
|
57
|
+
const targetModel = resolved.targetModel;
|
|
58
58
|
const providerId = resolved.providerId;
|
|
59
59
|
const targetTag = resolved.targetTag;
|
|
60
60
|
const is1mContext = Boolean(optionIs1m || resolved.is1mContext);
|
|
@@ -86,12 +86,16 @@ export async function executeSingleModel(options) {
|
|
|
86
86
|
const provider = ProviderRegistry.get(providerConfig.id);
|
|
87
87
|
const adjustedBody = body;
|
|
88
88
|
const prefixHash = extractConversationPrefixHash(adjustedBody);
|
|
89
|
-
let targetFormat =
|
|
89
|
+
let targetFormat = provider.resolveTargetFormat?.(targetModel, clientFormat) ||
|
|
90
|
+
providerConfig.format ||
|
|
91
|
+
provider.defaultFormat ||
|
|
92
|
+
"openai";
|
|
90
93
|
if (provider.id === "opencode" || provider.id === "oc") {
|
|
91
94
|
targetFormat = targetModel.includes("union-alpha") ? "claude" : "openai";
|
|
92
95
|
}
|
|
93
96
|
const triedAccountIds = new Set();
|
|
94
97
|
let lastFailureResult;
|
|
98
|
+
let forceFreshNextAttempt = false;
|
|
95
99
|
const targetProviderId = providerConfig.id || provider.id;
|
|
96
100
|
const sessionId = extractSessionId(req, body);
|
|
97
101
|
while (true) {
|
|
@@ -146,7 +150,7 @@ export async function executeSingleModel(options) {
|
|
|
146
150
|
clientTool, rawModel, rtkStats,
|
|
147
151
|
apiKeyId, apiKeyName,
|
|
148
152
|
};
|
|
149
|
-
if (provider.execute && provider.id !== "combo") {
|
|
153
|
+
if (provider.execute && provider.id !== "combo" && (!provider.shouldExecute || provider.shouldExecute(context))) {
|
|
150
154
|
const dispatchSingleModel = async (mBody, mStr, isP = false) => {
|
|
151
155
|
return executeSingleModel({ ...options, body: mBody, modelStr: mStr, isPanel: isP });
|
|
152
156
|
};
|
|
@@ -196,6 +200,9 @@ export async function executeSingleModel(options) {
|
|
|
196
200
|
if (targetFormat === "openai" && upstreamBody && upstreamBody.stream !== false) {
|
|
197
201
|
upstreamBody.stream_options = { ...(upstreamBody.stream_options || {}), include_usage: true };
|
|
198
202
|
}
|
|
203
|
+
else if (upstreamBody && upstreamBody.stream === false) {
|
|
204
|
+
delete upstreamBody.stream_options;
|
|
205
|
+
}
|
|
199
206
|
}
|
|
200
207
|
else {
|
|
201
208
|
upstreamBody.stream = false;
|
|
@@ -239,7 +246,9 @@ export async function executeSingleModel(options) {
|
|
|
239
246
|
headers: outgoingHeaders,
|
|
240
247
|
body: JSON.stringify(upstreamBody),
|
|
241
248
|
signal: combinedSignal,
|
|
249
|
+
...(forceFreshNextAttempt ? { forceFreshSocket: true } : {}),
|
|
242
250
|
};
|
|
251
|
+
forceFreshNextAttempt = false;
|
|
243
252
|
if (logger.isDebugEnabled()) {
|
|
244
253
|
const accLabel = account?.name || account?.id ? `account: '${account?.name || account?.id}'` : "no account";
|
|
245
254
|
logger.debug("UPSTREAM", `[${reqTag}] Dispatching to ${providerConfig.name} (${targetProviderId}/${targetModel}) · ${accLabel} · stream: ${upstreamBody?.stream !== false}`);
|
|
@@ -366,6 +375,9 @@ export async function executeSingleModel(options) {
|
|
|
366
375
|
upstreamRes.status === 403 ||
|
|
367
376
|
upstreamRes.status === 404;
|
|
368
377
|
if (shouldFailover && account) {
|
|
378
|
+
if (upstreamRes.status === 502) {
|
|
379
|
+
forceFreshNextAttempt = true;
|
|
380
|
+
}
|
|
369
381
|
const cdMs = resFailure.cooldownMs || (resFailure.rateLimited ? 60_000 : 5000);
|
|
370
382
|
if (tryFailover(targetProviderId, account, upstreamRes.status, cdMs, triedAccountIds, targetModel, reqTag, false, prefixHash || undefined, sessionId)) {
|
|
371
383
|
lastFailureResult = { ok: false, status: upstreamRes.status, text: cleanErrText, error: cleanErrText };
|
|
@@ -84,16 +84,9 @@ export async function pipeSseStream(upstreamRes, clientRes, context, provider) {
|
|
|
84
84
|
}
|
|
85
85
|
};
|
|
86
86
|
// 1. Read and verify initial chunk before committing HTTP headers to client
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
const firstRead = await reader.read();
|
|
91
|
-
firstReadDone = firstRead.done;
|
|
92
|
-
firstReadValue = firstRead.value;
|
|
93
|
-
}
|
|
94
|
-
catch (err) {
|
|
95
|
-
throw err;
|
|
96
|
-
}
|
|
87
|
+
const firstRead = await reader.read();
|
|
88
|
+
const firstReadDone = firstRead.done;
|
|
89
|
+
const firstReadValue = firstRead.value;
|
|
97
90
|
if (firstReadDone && !firstReadValue) {
|
|
98
91
|
throw new Error("Upstream stream ended immediately without sending any data");
|
|
99
92
|
}
|