mapigate 0.5.130 → 0.5.136

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.
Files changed (56) hide show
  1. package/README.md +1 -1
  2. package/dist/core/adapters/anthropic/requestAnthropicToOpenAi.js +59 -11
  3. package/dist/core/adapters/anthropicAdapter.js +2 -2
  4. package/dist/providers/catalog/commandcode/converter.js +215 -0
  5. package/dist/providers/catalog/commandcode/executor.js +305 -0
  6. package/dist/providers/catalog/commandcode/headers.js +76 -0
  7. package/dist/providers/catalog/commandcode/metadata.js +4 -1
  8. package/dist/providers/catalog/commandcode/ndjson.js +161 -0
  9. package/dist/providers/catalog/commandcode/provider.js +18 -35
  10. package/dist/providers/catalog/commandcode/routes.js +75 -0
  11. package/dist/providers/catalog/opencode-go/metadata.js +4 -2
  12. package/dist/providers/catalog/opencode-go/models.js +1 -0
  13. package/dist/providers/catalog/opencode-go/provider.js +114 -0
  14. package/dist/providers/catalog/opencode-go/quota.js +106 -0
  15. package/dist/providers/catalog/opencode-go/responses.js +301 -0
  16. package/dist/providers/catalog/opencode-go/responsesPayload.js +228 -0
  17. package/dist/providers/catalog/sensenova/metadata.js +35 -0
  18. package/dist/providers/core/base/baseProvider.js +3 -0
  19. package/dist/providers/core/base/openAiProvider.js +3 -1
  20. package/dist/providers/generated/routesRegistry.generated.js +2 -0
  21. package/dist/providers/runtime/antigravity/schema.js +19 -1
  22. package/dist/providers/runtime/codebuddy/provider.js +21 -6
  23. package/dist/providers/runtime/kiro/converter.js +2 -1
  24. package/dist/providers/runtime/kiro/executor.js +15 -9
  25. package/dist/providers/runtime/kiro/metadata.js +3 -3
  26. package/dist/providers/runtime/kiro/models.js +11 -0
  27. package/dist/providers/runtime/kiro/provider.js +12 -8
  28. package/dist/providers/runtime/kiro/quota.js +4 -4
  29. package/dist/providers/runtime/opencode/tools.js +38 -16
  30. package/dist/server/proxy/proxyDispatcher.js +136 -17
  31. package/dist/server/proxy/singleModelExecutor.js +14 -2
  32. package/dist/server/routes/apiModels.js +15 -6
  33. package/dist/shared/utils/dnsResolver.js +69 -27
  34. package/dist/web/assets/{CliToolsTab-Ck8EuOcF.js → CliToolsTab-CkzwuwaC.js} +1 -1
  35. package/dist/web/assets/CombosTab-C5RzRwwr.js +1 -0
  36. package/dist/web/assets/{ConfirmModal-1KqBoeRh.js → ConfirmModal-DGvcf0gB.js} +1 -1
  37. package/dist/web/assets/{ConsoleLogTab-DC2FAcl1.js → ConsoleLogTab-84Ens8T5.js} +1 -1
  38. package/dist/web/assets/{EditAccountModal-1EbG3eyM.js → EditAccountModal-D-_omvev.js} +1 -1
  39. package/dist/web/assets/{EndpointTab-C-gwVRmb.js → EndpointTab-7nBfEdYE.js} +1 -1
  40. package/dist/web/assets/{MitmTab-C2kTKbAV.js → MitmTab-CqS6mXHZ.js} +1 -1
  41. package/dist/web/assets/{ModelAutocompleteInput-K8-vMnIb.js → ModelAutocompleteInput-B9syrV1O.js} +1 -1
  42. package/dist/web/assets/ProviderDetailPage-DGZceQ2d.js +6 -0
  43. package/dist/web/assets/{ProvidersTab-w9OOjPmA.js → ProvidersTab-CiYbqRou.js} +1 -1
  44. package/dist/web/assets/{QuotaTab-C43xP8JP.js → QuotaTab-DFr0DWAU.js} +1 -1
  45. package/dist/web/assets/{SettingsTab-BMs0BtId.js → SettingsTab-4c0ksNJa.js} +1 -1
  46. package/dist/web/assets/{UsageTab-C5MbpcRp.js → UsageTab-BQcPmvtQ.js} +1 -1
  47. package/dist/web/assets/{index-DVeDwPjn.js → index-C4NTQZ40.js} +2 -2
  48. package/dist/web/assets/{index-BisuNW2y.css → index-HnsyZg0I.css} +1 -1
  49. package/dist/web/assets/metadataRegistry-B91sal4r.js +1 -0
  50. package/dist/web/assets/providersData-DkVCRBsJ.js +1 -0
  51. package/dist/web/index.html +2 -2
  52. package/package.json +1 -1
  53. package/dist/web/assets/CombosTab-CLPru5aK.js +0 -1
  54. package/dist/web/assets/ProviderDetailPage-BSqwg2fW.js +0 -6
  55. package/dist/web/assets/metadataRegistry-BMKXREeE.js +0 -1
  56. package/dist/web/assets/providersData-D7kilpPx.js +0 -1
@@ -3,13 +3,28 @@ import { OpenAiCompatibleProvider } from "../../core/base/openAiProvider.js";
3
3
  import { metadata } from "./metadata.js";
4
4
  import { getCodeBuddyUsage } from "./quota.js";
5
5
  const NEUTRAL_PROMPT = "You are a helpful AI assistant that helps with software engineering tasks.";
6
- function sanitizePromptForCodeBuddy(body) {
6
+ const AGENT_IDENTITY_PATTERN = /you are claude code|claude.?code.+official.+cli|anthropic.+official.+cli|anxthxropic.+official.+cli|you are (?:cursor|windsurf|cline|aider|continue|copilot|cody)|you are an? (?:ai )?(?:coding |code )?agent|cc_entrypoint\s*=\s*(?:cli|vscode|jetbrains|gui)|claude.?code.+issues|give feedback.+claude.?code|you are .{0,30}(?:powerful )?ai agent|orchestration capabilities|OhMyOpenCode|<agent-identity>|<Role>|<Behavior_Instructions>/i;
7
+ function extractSystemText(content) {
8
+ if (typeof content === "string")
9
+ return content;
10
+ if (Array.isArray(content)) {
11
+ return content
12
+ .map((part) => (typeof part === "string" ? part : part?.text || ""))
13
+ .filter(Boolean)
14
+ .join("\n");
15
+ }
16
+ return "";
17
+ }
18
+ export function sanitizePromptForCodeBuddy(body) {
7
19
  if (!body || typeof body !== "object")
8
20
  return body;
9
21
  const clone = { ...body };
10
22
  if (Array.isArray(clone.messages)) {
11
23
  clone.messages = clone.messages.map((msg) => {
12
- if (msg.role === "system" && typeof msg.content === "string") {
24
+ if (!msg || (msg.role !== "system" && msg.role !== "developer"))
25
+ return msg;
26
+ const text = extractSystemText(msg.content);
27
+ if (text && AGENT_IDENTITY_PATTERN.test(text)) {
13
28
  return { ...msg, content: NEUTRAL_PROMPT };
14
29
  }
15
30
  return msg;
@@ -43,10 +58,10 @@ export class CodebuddyProvider extends OpenAiCompatibleProvider {
43
58
  return headers;
44
59
  }
45
60
  transformRequestBody(context) {
46
- const sanitized = sanitizePromptForCodeBuddy(context.body);
47
- const converted = super.transformRequestBody({ ...context, body: sanitized });
48
- converted.model = context.targetModel;
49
- return converted;
61
+ const converted = super.transformRequestBody(context);
62
+ const sanitized = sanitizePromptForCodeBuddy(converted);
63
+ sanitized.model = context.targetModel;
64
+ return sanitized;
50
65
  }
51
66
  async probeModels(context) {
52
67
  const token = (context.apiKey || context.account?.rawApiKey || "").trim();
@@ -55,6 +55,7 @@ export function normalizeKiroToolSpecs(tools) {
55
55
  }
56
56
  return specs;
57
57
  }
58
+ import { resolveDefaultProfileArn } from "./quota.js";
58
59
  export function buildKiroPayload(body, targetModel, account, requestId) {
59
60
  if (body?.conversationState?.currentMessage?.userInputMessage) {
60
61
  const cs = body.conversationState;
@@ -264,7 +265,7 @@ export function buildKiroPayload(body, targetModel, account, requestId) {
264
265
  },
265
266
  };
266
267
  const psd = (account?.providerSpecificData || {});
267
- const profileArn = (psd.profileArn || "").trim();
268
+ const profileArn = (psd.profileArn || "").trim() || (account ? resolveDefaultProfileArn(psd.authMethod) : "");
268
269
  const payload = {
269
270
  conversationState: {
270
271
  chatTriggerType: "MANUAL",
@@ -4,8 +4,9 @@ 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
+ import { resolveDefaultProfileArn } from "./quota.js";
9
10
  import { ResponseLogger } from "../../../server/proxy/responseLogger.js";
10
11
  import { logger, LogSymbol, formatDoneLine } from "../../../shared/logger.js";
11
12
  function serializeToolInput(tool) {
@@ -53,8 +54,8 @@ export async function executeKiro(context, _providerInstance) {
53
54
  const headers = {
54
55
  "Content-Type": "application/json",
55
56
  Accept: "application/vnd.amazon.eventstream",
56
- "User-Agent": "aws-sdk-js/3.0.0 KiroIDE",
57
- "x-amz-user-agent": "aws-sdk-js/3.0.0 KiroIDE",
57
+ "User-Agent": "aws-sdk-js/3.0.0 KiroIDE/1.4.154 KAS/0.66.92-hotfix.5 os/win32 md/appVersion-1.4.154",
58
+ "x-amz-user-agent": "aws-sdk-js/3.0.0 KiroIDE/1.4.154 KAS/0.66.92-hotfix.5 os/win32 md/appVersion-1.4.154",
58
59
  "x-amzn-kiro-agent-mode": "spec",
59
60
  "x-amzn-codewhisperer-machine-id": "kiro-desktop",
60
61
  ...provCustomHeaders,
@@ -69,21 +70,26 @@ export async function executeKiro(context, _providerInstance) {
69
70
  else if (authMethod === "external_idp") {
70
71
  headers["TokenType"] = "EXTERNAL_IDP";
71
72
  }
72
- if (profileArn) {
73
- headers["x-amzn-codewhisperer-profile-arn"] = profileArn;
73
+ const effectiveProfileArn = profileArn || resolveDefaultProfileArn(authMethod);
74
+ if (effectiveProfileArn) {
75
+ headers["x-amzn-codewhisperer-profile-arn"] = effectiveProfileArn;
74
76
  }
75
77
  // 3. Resolve Target Endpoint URL
76
78
  const accountBase = (psd.baseUrl || "").trim();
77
- let targetUrl = accountBase;
79
+ const providerBase = (context.provider?.baseUrl || "").trim();
80
+ let targetUrl = accountBase || providerBase;
78
81
  if (!targetUrl) {
79
82
  if (authMethod === "external_idp") {
80
- targetUrl = `https://codewhisperer.${region}.amazonaws.com/generateAssistantResponse`;
83
+ const cwRegion = resolveKiroServiceRegion("codewhisperer", region);
84
+ targetUrl = `https://codewhisperer.${cwRegion}.amazonaws.com/generateAssistantResponse`;
81
85
  }
82
86
  else if (authMethod === "api-key" || authMethod === "api_key") {
83
- targetUrl = `https://q.${region}.amazonaws.com/generateAssistantResponse`;
87
+ const qRegion = resolveKiroServiceRegion("q", region);
88
+ targetUrl = `https://q.${qRegion}.amazonaws.com/generateAssistantResponse`;
84
89
  }
85
90
  else {
86
- targetUrl = `https://codewhisperer.${region}.amazonaws.com/generateAssistantResponse`;
91
+ const runtimeRegion = resolveKiroServiceRegion("runtime", region);
92
+ targetUrl = `https://runtime.${runtimeRegion}.kiro.dev/generateAssistantResponse`;
87
93
  }
88
94
  }
89
95
  if (targetUrl.includes("://codewhisperer.")) {
@@ -26,13 +26,13 @@ export const metadata = {
26
26
  "https://codewhisperer.us-east-1.amazonaws.com/generateAssistantResponse",
27
27
  "https://q.us-east-1.amazonaws.com/generateAssistantResponse"
28
28
  ],
29
- "validateUrl": "https://codewhisperer.us-east-1.amazonaws.com",
29
+ "validateUrl": "https://management.us-east-1.kiro.dev",
30
30
  "format": "kiro",
31
31
  "defaultHeaders": {
32
32
  "Content-Type": "application/json",
33
33
  "Accept": "application/vnd.amazon.eventstream",
34
- "User-Agent": "aws-sdk-js/3.0.0 KiroIDE",
35
- "X-Amz-User-Agent": "aws-sdk-js/3.0.0 KiroIDE"
34
+ "User-Agent": "aws-sdk-js/3.0.0 KiroIDE/1.4.154 KAS/0.66.92-hotfix.5 os/win32 md/appVersion-1.4.154",
35
+ "X-Amz-User-Agent": "aws-sdk-js/3.0.0 KiroIDE/1.4.154 KAS/0.66.92-hotfix.5 os/win32 md/appVersion-1.4.154"
36
36
  },
37
37
  "thinkingMode": "auto",
38
38
  "oauth": {
@@ -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,12 +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
- return super.buildUrl(context);
49
+ const provBase = (context.provider?.baseUrl || "").trim();
50
+ if (provBase)
51
+ return provBase;
52
+ return `https://runtime.${resolveKiroServiceRegion("runtime", region)}.kiro.dev/generateAssistantResponse`;
50
53
  }
51
54
  async buildHeaders(context) {
52
55
  const headers = await super.buildHeaders(context);
@@ -79,8 +82,8 @@ export class KiroProvider extends OpenAiCompatibleProvider {
79
82
  const reqHeaders = {
80
83
  ...(context.customHeaders || {}),
81
84
  "x-amz-target": "AmazonCodeWhispererService.ListAvailableModels",
82
- "x-amz-user-agent": "aws-sdk-js/1.0.0 KiroIDE",
83
- "user-agent": "aws-sdk-js/1.0.0 KiroIDE",
85
+ "x-amz-user-agent": "aws-sdk-js/3.0.0 KiroIDE/1.4.154 KAS/0.66.92-hotfix.5 os/win32 md/appVersion-1.4.154",
86
+ "user-agent": "aws-sdk-js/3.0.0 KiroIDE/1.4.154 KAS/0.66.92-hotfix.5 os/win32 md/appVersion-1.4.154",
84
87
  "Content-Type": "application/x-amz-json-1.0",
85
88
  "Accept": "application/json",
86
89
  };
@@ -94,8 +97,9 @@ export class KiroProvider extends OpenAiCompatibleProvider {
94
97
  reqHeaders["TokenType"] = "EXTERNAL_IDP";
95
98
  }
96
99
  const candidateUrls = [
97
- `https://codewhisperer.${region}.amazonaws.com`,
98
- `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`,
99
103
  ];
100
104
  let lastError;
101
105
  for (const url of candidateUrls) {
@@ -98,8 +98,8 @@ export async function getKiroUsage(accessToken, providerSpecificData, options) {
98
98
  headers: {
99
99
  Authorization: `Bearer ${token}`,
100
100
  Accept: "application/json",
101
- "x-amz-user-agent": "aws-sdk-js/1.0.0 KiroIDE",
102
- "user-agent": "aws-sdk-js/1.0.0 KiroIDE",
101
+ "x-amz-user-agent": "aws-sdk-js/3.0.0 KiroIDE/1.4.154 KAS/0.66.92-hotfix.5 os/win32 md/appVersion-1.4.154",
102
+ "user-agent": "aws-sdk-js/3.0.0 KiroIDE/1.4.154 KAS/0.66.92-hotfix.5 os/win32 md/appVersion-1.4.154",
103
103
  ...apiKeyHeaders,
104
104
  ...externalIdpHeaders,
105
105
  },
@@ -139,8 +139,8 @@ export async function getKiroUsage(accessToken, providerSpecificData, options) {
139
139
  headers: {
140
140
  Authorization: `Bearer ${token}`,
141
141
  Accept: "application/json",
142
- "x-amz-user-agent": "aws-sdk-js/1.0.0 KiroIDE",
143
- "user-agent": "aws-sdk-js/1.0.0 KiroIDE",
142
+ "x-amz-user-agent": "aws-sdk-js/3.0.0 KiroIDE/1.4.154 KAS/0.66.92-hotfix.5 os/win32 md/appVersion-1.4.154",
143
+ "user-agent": "aws-sdk-js/3.0.0 KiroIDE/1.4.154 KAS/0.66.92-hotfix.5 os/win32 md/appVersion-1.4.154",
144
144
  ...apiKeyHeaders,
145
145
  ...externalIdpHeaders,
146
146
  },
@@ -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
- const fn = chatFunctionOf(tool);
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
  }
@@ -246,23 +258,33 @@ export function retargetToolChoice(body, map, format = "openai") {
246
258
  const choice = body.tool_choice;
247
259
  if (!choice || typeof choice !== "object" || Array.isArray(choice))
248
260
  return;
249
- if (choice.type === "tool" && typeof choice.name === "string") {
250
- const key = fingerprintToolKey(choice.name);
261
+ const resolveAlias = (name) => {
262
+ const key = fingerprintToolKey(name);
251
263
  if (key && map.has(key))
252
- choice.name = key;
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 key = fingerprintToolKey(choice.name);
257
- if (key && map.has(key))
258
- body.tool_choice = { ...choice, name: key };
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 key = fingerprintToolKey(fn.name);
264
- if (key && map.has(key)) {
265
- body.tool_choice = { ...choice, function: { ...fn, name: key } };
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,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
- export function getProxyDispatcher(proxyUrl) {
8
- let dispatcher = proxyDispatchers.get(proxyUrl);
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(proxyUrl);
23
- proxyDispatchers.set(proxyUrl, dispatcher);
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(proxyUrl);
27
- proxyDispatchers.set(proxyUrl, dispatcher);
115
+ proxyDispatchers.delete(key);
116
+ proxyDispatchers.set(key, dispatcher);
28
117
  }
29
118
  return dispatcher;
30
119
  }
31
- export async function executeUpstreamFetch(url, options, proxyUrl) {
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 && !options?.dispatcher) {
34
- return (await globalThis.fetch(url, options));
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, { ...options, dispatcher }));
129
+ return (await undiciFetch(url, { ...fetchOpts, dispatcher }));
40
130
  }
41
- if (options?.dispatcher) {
42
- return (await undiciFetch(url, options));
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, { ...options, dispatcher: publicAgent }));
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
  }
@@ -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 = providerConfig.format || provider.defaultFormat || "openai";
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 };
@@ -79,7 +79,8 @@ modelRouter.get("/available", (req, res) => {
79
79
  const seenValues = new Set();
80
80
  // Include active combos
81
81
  const allCombos = ComboRepository.getAllCombos();
82
- for (const combo of allCombos) {
82
+ const sortedCombos = [...allCombos].sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: "base" }));
83
+ for (const combo of sortedCombos) {
83
84
  if (!combo.isActive)
84
85
  continue;
85
86
  let comboHasConnected = false;
@@ -151,10 +152,16 @@ modelRouter.get("/available", (req, res) => {
151
152
  });
152
153
  }
153
154
  // 1. Prioritize models configured in SQLite (dbProviders)
154
- for (const p of dbProviders) {
155
- const pModels = Array.isArray(p.models) ? p.models : [];
156
- if (pModels.length === 0)
155
+ const sortedDbProviders = [...dbProviders].sort((a, b) => (a.name || a.id).localeCompare(b.name || b.id, undefined, { sensitivity: "base" }));
156
+ for (const p of sortedDbProviders) {
157
+ const pModelsRaw = Array.isArray(p.models) ? p.models : [];
158
+ if (pModelsRaw.length === 0)
157
159
  continue;
160
+ const pModels = [...pModelsRaw].sort((a, b) => {
161
+ const aName = typeof a === "string" ? a : (a.name || a.id);
162
+ const bName = typeof b === "string" ? b : (b.name || b.id);
163
+ return aName.localeCompare(bName, undefined, { sensitivity: "base" });
164
+ });
158
165
  const accountsCount = getProviderAccountsCount(p.id);
159
166
  const hasConnectedAccount = accountsCount > 0;
160
167
  if (connectedOnly && !hasConnectedAccount)
@@ -210,7 +217,8 @@ modelRouter.get("/available", (req, res) => {
210
217
  }
211
218
  }
212
219
  // 2. Fall back to static PROVIDER_REGISTRY presets if provider has no DB models
213
- for (const provider of Object.values(PROVIDER_REGISTRY)) {
220
+ const sortedStaticProviders = Object.values(PROVIDER_REGISTRY).sort((a, b) => (a.name || a.id).localeCompare(b.name || b.id, undefined, { sensitivity: "base" }));
221
+ for (const provider of sortedStaticProviders) {
214
222
  if (!provider || !provider.models)
215
223
  continue;
216
224
  if (hasDbConfiguredModels(provider.id, provider)) {
@@ -221,7 +229,8 @@ modelRouter.get("/available", (req, res) => {
221
229
  if (connectedOnly && !hasConnectedAccount) {
222
230
  continue;
223
231
  }
224
- for (const model of provider.models) {
232
+ const sortedModels = [...provider.models].sort((a, b) => (a.name || a.id).localeCompare(b.name || b.id, undefined, { sensitivity: "base" }));
233
+ for (const model of sortedModels) {
225
234
  const val = model.id.startsWith(`${provider.id}/`) ? model.id : `${provider.id}/${model.id}`;
226
235
  if (seenValues.has(val))
227
236
  continue;