mapigate 0.5.133 → 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 (51) 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/executor.js +7 -4
  24. package/dist/providers/runtime/kiro/models.js +11 -0
  25. package/dist/providers/runtime/kiro/provider.js +7 -7
  26. package/dist/providers/runtime/opencode/tools.js +38 -16
  27. package/dist/server/proxy/proxyDispatcher.js +136 -17
  28. package/dist/server/proxy/singleModelExecutor.js +14 -2
  29. package/dist/shared/utils/dnsResolver.js +69 -27
  30. package/dist/web/assets/{CliToolsTab-D4DkK7Rn.js → CliToolsTab-CkzwuwaC.js} +1 -1
  31. package/dist/web/assets/{CombosTab-X1C_OmzI.js → CombosTab-C5RzRwwr.js} +1 -1
  32. package/dist/web/assets/{ConfirmModal-CuQ7ARxt.js → ConfirmModal-DGvcf0gB.js} +1 -1
  33. package/dist/web/assets/{ConsoleLogTab-B2sfhYZW.js → ConsoleLogTab-84Ens8T5.js} +1 -1
  34. package/dist/web/assets/{EditAccountModal-BusNJLvX.js → EditAccountModal-D-_omvev.js} +1 -1
  35. package/dist/web/assets/{EndpointTab-DQCezUA9.js → EndpointTab-7nBfEdYE.js} +1 -1
  36. package/dist/web/assets/{MitmTab-DxEuD0DW.js → MitmTab-CqS6mXHZ.js} +1 -1
  37. package/dist/web/assets/{ModelAutocompleteInput-CgJ2FlEf.js → ModelAutocompleteInput-B9syrV1O.js} +1 -1
  38. package/dist/web/assets/ProviderDetailPage-DGZceQ2d.js +6 -0
  39. package/dist/web/assets/{ProvidersTab-pZoM69s4.js → ProvidersTab-CiYbqRou.js} +1 -1
  40. package/dist/web/assets/{QuotaTab-CvXGyICr.js → QuotaTab-DFr0DWAU.js} +1 -1
  41. package/dist/web/assets/{SettingsTab-D7YF7rTP.js → SettingsTab-4c0ksNJa.js} +1 -1
  42. package/dist/web/assets/{UsageTab-B0YCftIJ.js → UsageTab-BQcPmvtQ.js} +1 -1
  43. package/dist/web/assets/{index-DTRst7wN.js → index-C4NTQZ40.js} +2 -2
  44. package/dist/web/assets/{index-BisuNW2y.css → index-HnsyZg0I.css} +1 -1
  45. package/dist/web/assets/metadataRegistry-B91sal4r.js +1 -0
  46. package/dist/web/assets/providersData-DkVCRBsJ.js +1 -0
  47. package/dist/web/index.html +2 -2
  48. package/package.json +1 -1
  49. package/dist/web/assets/ProviderDetailPage-DMA1DVSN.js +0 -6
  50. package/dist/web/assets/metadataRegistry-BPZSXiBy.js +0 -1
  51. package/dist/web/assets/providersData-Bsv7o5VV.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();
@@ -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
- targetUrl = `https://codewhisperer.${region}.amazonaws.com/generateAssistantResponse`;
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
- targetUrl = `https://q.${region}.amazonaws.com/generateAssistantResponse`;
87
+ const qRegion = resolveKiroServiceRegion("q", region);
88
+ targetUrl = `https://q.${qRegion}.amazonaws.com/generateAssistantResponse`;
87
89
  }
88
90
  else {
89
- targetUrl = `https://runtime.${region}.kiro.dev/generateAssistantResponse`;
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);
@@ -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) {
@@ -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 };
@@ -4,6 +4,21 @@ import { Agent as UndiciAgent, fetch as undiciFetch } from "undici";
4
4
  // ── Shared Public DNS Resolver (Bypasses local hosts file 127.0.0.1 / ::1 loops) ──
5
5
  const cachedTargetIPs = {};
6
6
  const CACHE_TTL_MS = 5 * 60 * 1000;
7
+ // ISP DPI (e.g. VN -> api.anthropic.com) RSTs Node's default TLS ClientHello curve
8
+ // list; a single X25519 curve rewrites the fingerprint enough to pass.
9
+ export const TLS_ECDH_CURVE = process.env.MAPIGATE_TLS_ECDH_CURVE || "X25519";
10
+ // Happy Eyeballs (RFC 8305): race IPv4/IPv6 with a 250ms fallback window.
11
+ export const EYEBALLS_CONNECT = {
12
+ autoSelectFamily: true,
13
+ autoSelectFamilyAttemptTimeout: 250,
14
+ };
15
+ export const DEFAULT_KEEPALIVE_TIMEOUT_MS = 4 * 1000;
16
+ export const FRESH_RETRY_KEEPALIVE_TIMEOUT_MS = 1;
17
+ export function resolveKeepAliveTimeouts() {
18
+ const raw = Number(process.env.MAPIGATE_FETCH_KEEPALIVE_TIMEOUT_MS);
19
+ const timeout = Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_KEEPALIVE_TIMEOUT_MS;
20
+ return { keepAliveTimeout: timeout, keepAliveMaxTimeout: timeout };
21
+ }
7
22
  let publicResolver = null;
8
23
  let publicResolverAsync = null;
9
24
  function getResolver() {
@@ -35,40 +50,67 @@ export async function resolveTargetIP(hostname) {
35
50
  }
36
51
  }
37
52
  let publicDnsAgentInstance = null;
53
+ let publicDnsFreshAgentInstance = null;
54
+ function createPublicDnsAgent(keepAliveTimeout, keepAliveMaxTimeout) {
55
+ const { resolve4 } = getResolver();
56
+ return new UndiciAgent({
57
+ keepAliveTimeout,
58
+ keepAliveMaxTimeout,
59
+ connect: {
60
+ ...EYEBALLS_CONNECT,
61
+ ecdhCurve: TLS_ECDH_CURVE,
62
+ lookup: (hostname, opts, cb) => {
63
+ let callback = cb;
64
+ let options = opts;
65
+ if (typeof options === "function") {
66
+ callback = options;
67
+ options = {};
68
+ }
69
+ resolve4(hostname)
70
+ .then((ips) => {
71
+ if (options && options.all) {
72
+ callback(null, ips.map((ip) => ({ address: ip, family: 4 })));
73
+ }
74
+ else {
75
+ callback(null, ips[0], 4);
76
+ }
77
+ })
78
+ .catch(() => {
79
+ dns.lookup(hostname, options, callback);
80
+ });
81
+ },
82
+ },
83
+ });
84
+ }
38
85
  /**
39
86
  * Returns an undici Agent that resolves DNS via public resolvers,
40
- * completely avoiding local hosts file redirections (e.g. 127.0.0.1 for MITM tools).
87
+ * completely avoiding local hosts file redirections (e.g. 127.0.0.1 for MITM tools),
88
+ * with capped keep-alive TTL and DPI-safe TLS curve options.
41
89
  */
42
- export function getPublicDnsAgent() {
90
+ export function getPublicDnsAgent(options) {
91
+ if (options?.forceFreshSocket) {
92
+ if (!publicDnsFreshAgentInstance) {
93
+ publicDnsFreshAgentInstance = createPublicDnsAgent(FRESH_RETRY_KEEPALIVE_TIMEOUT_MS, FRESH_RETRY_KEEPALIVE_TIMEOUT_MS);
94
+ }
95
+ return publicDnsFreshAgentInstance;
96
+ }
43
97
  if (!publicDnsAgentInstance) {
44
- const { resolve4 } = getResolver();
45
- publicDnsAgentInstance = new UndiciAgent({
46
- connect: {
47
- lookup: (hostname, opts, cb) => {
48
- let callback = cb;
49
- let options = opts;
50
- if (typeof options === "function") {
51
- callback = options;
52
- options = {};
53
- }
54
- resolve4(hostname)
55
- .then((ips) => {
56
- if (options && options.all) {
57
- callback(null, ips.map((ip) => ({ address: ip, family: 4 })));
58
- }
59
- else {
60
- callback(null, ips[0], 4);
61
- }
62
- })
63
- .catch(() => {
64
- dns.lookup(hostname, options, callback);
65
- });
66
- },
67
- },
68
- });
98
+ const { keepAliveTimeout, keepAliveMaxTimeout } = resolveKeepAliveTimeouts();
99
+ publicDnsAgentInstance = createPublicDnsAgent(keepAliveTimeout, keepAliveMaxTimeout);
69
100
  }
70
101
  return publicDnsAgentInstance;
71
102
  }
103
+ export function clearPublicDnsAgents() {
104
+ for (const agent of [publicDnsAgentInstance, publicDnsFreshAgentInstance]) {
105
+ try {
106
+ agent?.destroy?.();
107
+ agent?.close?.();
108
+ }
109
+ catch { }
110
+ }
111
+ publicDnsAgentInstance = null;
112
+ publicDnsFreshAgentInstance = null;
113
+ }
72
114
  /**
73
115
  * Fetch wrapper that automatically uses the public DNS dispatcher to bypass local loopback.
74
116
  */
@@ -1,4 +1,4 @@
1
- import{r as n,j as e}from"./vendor-BcOI2aZ9.js";import{b as s,c as f,D as Y,d as se,u as be,P as fe}from"./index-DTRst7wN.js";import{a as ye}from"./providersData-Bsv7o5VV.js";import{T as X}from"./ToolIcon-Cp4gSgFt.js";import{M as ee}from"./ModelAutocompleteInput-CgJ2FlEf.js";import{r as ve,s as Ne}from"./lucide-Cc35htxl.js";import"./metadataRegistry-BPZSXiBy.js";const Ae={id:"amp",name:"Amp CLI",image:"/assets/tools/amp/icon.png",color:"#F97316",description:"Sourcegraph Amp coding assistant CLI",configType:"env",binary:"amp",baseUrlPath:"/v1",defaultModels:["claude-sonnet-4-6","claude-3-7-sonnet","claude-3-5-sonnet","claude-opus-5","claude-fable-5.1","gpt-5.6","gpt-6-astra","glm-5.3-flash","gpt-4o"],envVars:{baseUrl:"OPENAI_BASE_URL",apiKey:"OPENAI_API_KEY"},powershellTemplate:`$env:OPENAI_BASE_URL = "${s}"
1
+ import{r as n,j as e}from"./vendor-BcOI2aZ9.js";import{b as s,c as f,D as Y,d as se,u as be,P as fe}from"./index-C4NTQZ40.js";import{a as ye}from"./providersData-DkVCRBsJ.js";import{T as X}from"./ToolIcon-Cp4gSgFt.js";import{M as ee}from"./ModelAutocompleteInput-B9syrV1O.js";import{r as ve,s as Ne}from"./lucide-Cc35htxl.js";import"./metadataRegistry-B91sal4r.js";const Ae={id:"amp",name:"Amp CLI",image:"/assets/tools/amp/icon.png",color:"#F97316",description:"Sourcegraph Amp coding assistant CLI",configType:"env",binary:"amp",baseUrlPath:"/v1",defaultModels:["claude-sonnet-4-6","claude-3-7-sonnet","claude-3-5-sonnet","claude-opus-5","claude-fable-5.1","gpt-5.6","gpt-6-astra","glm-5.3-flash","gpt-4o"],envVars:{baseUrl:"OPENAI_BASE_URL",apiKey:"OPENAI_API_KEY"},powershellTemplate:`$env:OPENAI_BASE_URL = "${s}"
2
2
  $env:OPENAI_API_KEY = "mapigate-local"
3
3
  amp`,bashTemplate:`export OPENAI_BASE_URL="${s}"
4
4
  export OPENAI_API_KEY="mapigate-local"