mapigate 0.5.120 → 0.5.127

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 (36) hide show
  1. package/README.md +1 -1
  2. package/dist/core/adapters/anthropic/requestOpenAiToAnthropic.js +36 -2
  3. package/dist/core/adapters/anthropicAdapter.js +2 -2
  4. package/dist/core/adapters/helpers/toolCallRescue.js +6 -1
  5. package/dist/core/capabilities/constants.js +12 -0
  6. package/dist/core/capabilities/patterns.js +25 -13
  7. package/dist/mitm/handlers/base.js +58 -18
  8. package/dist/mitm/manager.js +6 -2
  9. package/dist/mitm/portConflict.js +38 -19
  10. package/dist/providers/catalog/xiaomi-tokenplan/provider.js +44 -11
  11. package/dist/providers/core/base/anthropicProvider.js +1 -1
  12. package/dist/providers/runtime/bedrock/provider.js +1 -1
  13. package/dist/providers/runtime/mimo/provider.js +43 -10
  14. package/dist/server/proxy/singleModelExecutor.js +7 -1
  15. package/dist/server/routes/apiMitm.js +50 -0
  16. package/dist/server/routes/mitmRouterTargetHelper.js +109 -0
  17. package/dist/storage/repositories/mitmRepo.js +44 -0
  18. package/dist/web/assets/{CliToolsTab-BzhczMaa.js → CliToolsTab--_BDAxpc.js} +1 -1
  19. package/dist/web/assets/{CombosTab-Cz8KYH4M.js → CombosTab-CK0CrOWr.js} +1 -1
  20. package/dist/web/assets/{ConfirmModal-BU1PPpF0.js → ConfirmModal-BkkI8yej.js} +1 -1
  21. package/dist/web/assets/{ConsoleLogTab-CFvXde1l.js → ConsoleLogTab-CuqPUkXq.js} +1 -1
  22. package/dist/web/assets/{EditAccountModal-CS2TR4bt.js → EditAccountModal-CtWFLt1J.js} +1 -1
  23. package/dist/web/assets/{EndpointTab-DZCRpAbh.js → EndpointTab-BpWmu2u2.js} +1 -1
  24. package/dist/web/assets/MitmTab-D8qh-Ng3.js +14 -0
  25. package/dist/web/assets/ModelAutocompleteInput-C5YopybP.js +1 -0
  26. package/dist/web/assets/ProviderDetailPage-DRz6xsUD.js +6 -0
  27. package/dist/web/assets/{ProvidersTab-DwHMHdPu.js → ProvidersTab-B4NLxZtO.js} +1 -1
  28. package/dist/web/assets/{QuotaTab-DS1y9gGp.js → QuotaTab-ByMCdVsx.js} +1 -1
  29. package/dist/web/assets/{SettingsTab-DULcs9O4.js → SettingsTab-Bm4ndn4C.js} +1 -1
  30. package/dist/web/assets/{UsageTab-DKBaBAeT.js → UsageTab-0xMr9ziL.js} +1 -1
  31. package/dist/web/assets/{index-DPdrZakW.js → index-DrTal_uX.js} +2 -2
  32. package/dist/web/index.html +1 -1
  33. package/package.json +1 -1
  34. package/dist/web/assets/MitmTab-CTfwqdey.js +0 -14
  35. package/dist/web/assets/ModelAutocompleteInput-CAi2R2s9.js +0 -1
  36. package/dist/web/assets/ProviderDetailPage-Dv2LpFj_.js +0 -6
package/README.md CHANGED
@@ -13,7 +13,7 @@
13
13
  [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
14
14
  [![Platform](https://img.shields.io/badge/Platform-Windows%20%7C%20Linux%20%7C%20macOS-blueviolet.svg)](#)
15
15
  [![TypeScript](https://img.shields.io/badge/TypeScript-5.7-blue.svg)](https://www.typescriptlang.org/)
16
- [![Version](https://img.shields.io/badge/version-0.5.120-orange.svg)](package.json)
16
+ [![Version](https://img.shields.io/badge/version-0.5.127-orange.svg)](package.json)
17
17
 
18
18
  [**What is Mapigate?**](#-what-is-mapigate) • [**Gateway API**](#-gateway-api) • [**Supported Providers**](#-supported-providers-151) • [**Quick Start**](#-quick-start-get-running-in-60s) • [**Token Saver**](#-feature-1-token-saver-modular-token-optimization) • [**Smart Routing & Combos**](#-feature-2-smart-routing--combo-engine) • [**Connect Coding Tools**](#-feature-3-one-click-connection-for-26-coding-assistants) • [**MITM Interceptor**](#-feature-4-mitm-https-interceptor-for-closed-tools) • [**Web Dashboard**](#-feature-5-web-dashboard-tour) • [**CLI Reference**](#-cli-reference-mapigate--mpg)
19
19
 
@@ -2,10 +2,41 @@ import { repairToolArguments, toolSchemaMap, extractToolNames, } from "../helper
2
2
  import { rescueInlineToolCalls } from "../helpers/toolCallRescue.js";
3
3
  import { normalizeToolParameters } from "../helpers/toolSchemaNormalize.js";
4
4
  import { convertOpenAiContentToAnthropic } from "./imageUtils.js";
5
+ import { getCapabilitiesForModel } from "../../capabilities/index.js";
6
+ export const DEFAULT_MAX_TOKENS = 64000;
7
+ export const DEFAULT_MIN_TOKENS = 32000;
8
+ /**
9
+ * Adjust max_tokens based on request context and model ceiling.
10
+ * Parity with 9router:
11
+ * - Default maxTokens: 64,000 (when client does not pass max_tokens)
12
+ * - Tool calling floor: auto-raise to at least 32,000 to prevent truncated tool args
13
+ * - Thinking buffer: ensure max_tokens > thinking.budget_tokens + 1024
14
+ * - Clamped at model capability maxOutput ceiling
15
+ */
16
+ export function adjustMaxTokens(body, ceiling = DEFAULT_MAX_TOKENS) {
17
+ let maxTokens = body.max_tokens ?? body.max_completion_tokens ?? DEFAULT_MAX_TOKENS;
18
+ // Auto-increase for tool calling to prevent truncated arguments (min never above ceiling)
19
+ if (body.tools && Array.isArray(body.tools) && body.tools.length > 0) {
20
+ if (maxTokens < DEFAULT_MIN_TOKENS) {
21
+ maxTokens = Math.min(DEFAULT_MIN_TOKENS, ceiling);
22
+ }
23
+ }
24
+ // Ensure max_tokens > thinking.budget_tokens (Claude API requirement)
25
+ if (body.thinking?.budget_tokens && maxTokens <= body.thinking.budget_tokens) {
26
+ maxTokens = body.thinking.budget_tokens + 1024;
27
+ }
28
+ // Never exceed the ceiling
29
+ if (maxTokens > ceiling)
30
+ maxTokens = ceiling;
31
+ if (body.thinking?.budget_tokens && body.thinking.budget_tokens >= maxTokens) {
32
+ body.thinking.budget_tokens = Math.max(1024, maxTokens - 1024);
33
+ }
34
+ return maxTokens;
35
+ }
5
36
  /**
6
37
  * Translates OpenAI /v1/chat/completions payload to Anthropic /v1/messages payload
7
38
  */
8
- export function translateOpenAiToAnthropic(openAiBody) {
39
+ export function translateOpenAiToAnthropic(openAiBody, modelOverride, providerId) {
9
40
  let systemPrompt = "";
10
41
  let systemCacheControl = undefined;
11
42
  const anthropicMessages = [];
@@ -216,12 +247,15 @@ export function translateOpenAiToAnthropic(openAiBody) {
216
247
  },
217
248
  ];
218
249
  }
250
+ const targetModel = modelOverride || openAiBody?.model;
251
+ const caps = getCapabilitiesForModel(providerId, targetModel);
252
+ const ceiling = caps?.maxOutput > 0 ? caps.maxOutput : DEFAULT_MAX_TOKENS;
219
253
  const result = {
220
254
  model: openAiBody.model,
221
255
  messages: anthropicMessages,
222
256
  system: formattedSystem,
223
257
  tools: tools && tools.length > 0 ? tools : undefined,
224
- max_tokens: openAiBody.max_tokens || 4096,
258
+ max_tokens: adjustMaxTokens(openAiBody, ceiling),
225
259
  temperature: openAiBody.temperature,
226
260
  stream: Boolean(openAiBody.stream),
227
261
  };
@@ -35,8 +35,8 @@ export class AnthropicAdapter {
35
35
  /**
36
36
  * Convert OpenAI /v1/chat/completions payload to Anthropic /v1/messages payload
37
37
  */
38
- static openAiToAnthropic(openAiBody) {
39
- return translateOpenAiToAnthropic(openAiBody);
38
+ static openAiToAnthropic(openAiBody, modelOverride, providerId) {
39
+ return translateOpenAiToAnthropic(openAiBody, modelOverride, providerId);
40
40
  }
41
41
  /**
42
42
  * Convert OpenAI response chunk to Anthropic SSE event format
@@ -250,7 +250,12 @@ export function parseMimoFunctionAndParameters(inner, toolNames) {
250
250
  export function parseAnyToolBlock(raw, toolNames) {
251
251
  if (!raw || typeof raw !== "string")
252
252
  return null;
253
- const trimmed = raw.trim();
253
+ let trimmed = raw.trim();
254
+ // Strip wrapping <tool_call>...</tool_call> if present
255
+ const toolCallMatch = /^<tool_call>([\s\S]*?)<\/tool_call>$/i.exec(trimmed);
256
+ if (toolCallMatch) {
257
+ trimmed = toolCallMatch[1].trim();
258
+ }
254
259
  // 1. JSON object format: {"name": ..., "arguments"|"parameters": ...}
255
260
  if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
256
261
  const jsonCall = callFromNamedJson(trimmed, toolNames);
@@ -62,8 +62,20 @@ export const MODEL_CAPABILITIES = {
62
62
  "claude-haiku-5.5": { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive", contextWindow: 1000000, maxOutput: 128000 },
63
63
  "claude-haiku-5-5": { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive", contextWindow: 1000000, maxOutput: 128000 },
64
64
  "claude-sonnet-5": { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive", contextWindow: 1000000, maxOutput: 128000 },
65
+ "claude-opus-4.8": { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive", contextWindow: 1000000, maxOutput: 128000 },
66
+ "claude-opus-4-8": { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive", contextWindow: 1000000, maxOutput: 128000 },
67
+ "claude-opus-4.6": { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive", contextWindow: 1000000, maxOutput: 128000 },
68
+ "claude-opus-4-6": { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive", contextWindow: 1000000, maxOutput: 128000 },
69
+ "claude-sonnet-4.6": { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive", contextWindow: 1000000, maxOutput: 128000 },
70
+ "claude-sonnet-4-6": { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive", contextWindow: 1000000, maxOutput: 128000 },
65
71
  "claude-3-7-sonnet": { vision: true, reasoning: true, search: true, thinkingFormat: "claude-budget", contextWindow: 200000, maxOutput: 64000 },
66
72
  "claude-3.7-sonnet": { vision: true, reasoning: true, search: true, thinkingFormat: "claude-budget", contextWindow: 200000, maxOutput: 64000 },
73
+ "claude-3-5-sonnet": { vision: true, search: true, contextWindow: 200000, maxOutput: 8192 },
74
+ "claude-3.5-sonnet": { vision: true, search: true, contextWindow: 200000, maxOutput: 8192 },
75
+ "claude-3-5-haiku": { vision: true, search: true, contextWindow: 200000, maxOutput: 8192 },
76
+ "claude-3.5-haiku": { vision: true, search: true, contextWindow: 200000, maxOutput: 8192 },
77
+ "claude-3-opus": { vision: true, contextWindow: 200000, maxOutput: 4096 },
78
+ "claude-3-haiku": { vision: true, contextWindow: 200000, maxOutput: 4096 },
67
79
  // GLM vision variants
68
80
  "glm-5.3-flash": { vision: true, videoInput: true, pdf: true, reasoning: true, thinkingFormat: "zai", thinkingCanDisable: false, contextWindow: 1000000, maxOutput: 131072 },
69
81
  "glm-4.6v": { vision: true, videoInput: true, reasoning: true, thinkingFormat: "zai", contextWindow: 128000, maxOutput: 32768 },
@@ -32,21 +32,33 @@ export const PATTERN_CAPABILITIES = [
32
32
  { pattern: "*claude*haiku-5-5*", caps: { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive", contextWindow: 1000000, maxOutput: 128000 } },
33
33
  { pattern: "*claude*opus-5*", caps: { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive", contextWindow: 1000000, maxOutput: 128000 } },
34
34
  { pattern: "*claude*sonnet-5*", caps: { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive", contextWindow: 1000000, maxOutput: 128000 } },
35
- { pattern: "*claude*opus-4.6*", caps: { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive" } },
36
- { pattern: "*claude*opus-4.7*", caps: { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive" } },
37
- { pattern: "*claude*opus-4.8*", caps: { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive" } },
38
- { pattern: "*claude*sonnet-4.6*", caps: { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive" } },
39
- { pattern: "*claude*sonnet-4.7*", caps: { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive" } },
35
+ { pattern: "*claude*opus-4.8*", caps: { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive", contextWindow: 1000000, maxOutput: 128000 } },
36
+ { pattern: "*claude*opus-4-8*", caps: { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive", contextWindow: 1000000, maxOutput: 128000 } },
37
+ { pattern: "*claude*opus-4.7*", caps: { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive", contextWindow: 1000000, maxOutput: 128000 } },
38
+ { pattern: "*claude*opus-4-7*", caps: { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive", contextWindow: 1000000, maxOutput: 128000 } },
39
+ { pattern: "*claude*opus-4.6*", caps: { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive", contextWindow: 1000000, maxOutput: 128000 } },
40
+ { pattern: "*claude*opus-4-6*", caps: { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive", contextWindow: 1000000, maxOutput: 128000 } },
41
+ { pattern: "*claude*sonnet-4.7*", caps: { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive", contextWindow: 1000000, maxOutput: 128000 } },
42
+ { pattern: "*claude*sonnet-4-7*", caps: { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive", contextWindow: 1000000, maxOutput: 128000 } },
43
+ { pattern: "*claude*sonnet-4.6*", caps: { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive", contextWindow: 1000000, maxOutput: 128000 } },
44
+ { pattern: "*claude*sonnet-4-6*", caps: { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive", contextWindow: 1000000, maxOutput: 128000 } },
40
45
  { pattern: "*claude*haiku-6*", caps: { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive", contextWindow: 1000000, maxOutput: 128000 } },
41
46
  { pattern: "*claude*haiku-5*", caps: { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive", contextWindow: 1000000, maxOutput: 128000 } },
42
- { pattern: "*claude*haiku-4*", caps: { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-budget" } },
43
- { pattern: "*claude*haiku*", caps: { vision: true, reasoning: true, search: true, thinkingFormat: "claude-budget" } },
44
- { pattern: "*claude*opus*", caps: { vision: true, reasoning: true, search: true, thinkingFormat: "claude-budget" } },
45
- { pattern: "*claude*sonnet*", caps: { vision: true, reasoning: true, search: true, thinkingFormat: "claude-budget" } },
46
- { pattern: "*claude*3.7*", caps: { vision: true, reasoning: true, search: true, thinkingFormat: "claude-budget" } },
47
- { pattern: "*claude*3-7*", caps: { vision: true, reasoning: true, search: true, thinkingFormat: "claude-budget" } },
48
- { pattern: "*claude-3*", caps: { vision: true } },
49
- { pattern: "*claude*", caps: { vision: true, reasoning: true, search: true, thinkingFormat: "claude-budget" } },
47
+ { pattern: "*claude*haiku-4*", caps: { vision: true, pdf: true, reasoning: true, search: true, thinkingFormat: "claude-adaptive", contextWindow: 1000000, maxOutput: 128000 } },
48
+ { pattern: "*claude*3.7*", caps: { vision: true, reasoning: true, search: true, thinkingFormat: "claude-budget", contextWindow: 200000, maxOutput: 64000 } },
49
+ { pattern: "*claude*3-7*", caps: { vision: true, reasoning: true, search: true, thinkingFormat: "claude-budget", contextWindow: 200000, maxOutput: 64000 } },
50
+ { pattern: "*claude*3.5*sonnet*", caps: { vision: true, search: true, contextWindow: 200000, maxOutput: 8192 } },
51
+ { pattern: "*claude*3-5*sonnet*", caps: { vision: true, search: true, contextWindow: 200000, maxOutput: 8192 } },
52
+ { pattern: "*claude*3.5*haiku*", caps: { vision: true, search: true, contextWindow: 200000, maxOutput: 8192 } },
53
+ { pattern: "*claude*3-5*haiku*", caps: { vision: true, search: true, contextWindow: 200000, maxOutput: 8192 } },
54
+ { pattern: "*claude*3*opus*", caps: { vision: true, contextWindow: 200000, maxOutput: 4096 } },
55
+ { pattern: "*claude*3*sonnet*", caps: { vision: true, contextWindow: 200000, maxOutput: 4096 } },
56
+ { pattern: "*claude*3*haiku*", caps: { vision: true, contextWindow: 200000, maxOutput: 4096 } },
57
+ { pattern: "*claude-3*", caps: { vision: true, contextWindow: 200000, maxOutput: 4096 } },
58
+ { pattern: "*claude*haiku*", caps: { vision: true, reasoning: true, search: true, thinkingFormat: "claude-budget", contextWindow: 200000, maxOutput: 8192 } },
59
+ { pattern: "*claude*opus*", caps: { vision: true, reasoning: true, search: true, thinkingFormat: "claude-budget", contextWindow: 200000, maxOutput: 64000 } },
60
+ { pattern: "*claude*sonnet*", caps: { vision: true, reasoning: true, search: true, thinkingFormat: "claude-budget", contextWindow: 200000, maxOutput: 64000 } },
61
+ { pattern: "*claude*", caps: { vision: true, reasoning: true, search: true, thinkingFormat: "claude-budget", contextWindow: 200000, maxOutput: 64000 } },
50
62
  // ── Gemini ──
51
63
  { pattern: "*gemini*image*", caps: { vision: true, imageOutput: true, contextWindow: 1048576 } },
52
64
  { pattern: "*gemini-4*", caps: { vision: true, audioInput: true, videoInput: true, reasoning: true, search: true, thinkingFormat: "gemini-level", thinkingCanDisable: false, contextWindow: 1048576, maxOutput: 65536 } },
@@ -3,25 +3,75 @@ import zlib from "node:zlib";
3
3
  import { HOST_REWRITE } from "../../shared/constants/mitmToolHosts.js";
4
4
  import { serverLifecycle } from "../../server/lifecycle.js";
5
5
  import { SettingsRepository } from "../../storage/repositories/settingsRepo.js";
6
+ import { MitmRepository } from "../../storage/repositories/mitmRepo.js";
6
7
  import { DEFAULT_BASE_URL } from "../../shared/constants/index.js";
7
8
  export const DEFAULT_ROUTER_BASE = DEFAULT_BASE_URL;
8
- export const ROUTER_BASE = String(process.env.MAPIGATE_BASE_URL || DEFAULT_ROUTER_BASE)
9
- .trim()
10
- .replace(/\/+$/, "");
11
- export function getRouterBaseUrl() {
9
+ export function getRouterTarget() {
12
10
  if (process.env.MAPIGATE_BASE_URL) {
13
- return process.env.MAPIGATE_BASE_URL.trim().replace(/\/+$/, "");
11
+ const baseUrl = process.env.MAPIGATE_BASE_URL.trim().replace(/\/+$/, "");
12
+ const apiKey = process.env.ROUTER_API_KEY ? process.env.ROUTER_API_KEY.trim() : "";
13
+ return {
14
+ baseUrl,
15
+ authHeader: apiKey ? `Bearer ${apiKey}` : "",
16
+ isRemote: true,
17
+ };
14
18
  }
19
+ try {
20
+ const configured = MitmRepository.getRouterTarget();
21
+ if (configured.baseUrl) {
22
+ const apiKey = process.env.ROUTER_API_KEY ? process.env.ROUTER_API_KEY.trim() : (configured.apiKey || "");
23
+ let authHeader = apiKey ? `Bearer ${apiKey}` : "";
24
+ // Only fall back to local gateway key if target is local
25
+ if (!authHeader && !configured.isRemote) {
26
+ try {
27
+ const activeKey = SettingsRepository.getGatewayApiKeys().find((k) => k.isActive)?.key;
28
+ if (activeKey) {
29
+ authHeader = `Bearer ${activeKey}`;
30
+ }
31
+ }
32
+ catch { }
33
+ }
34
+ return {
35
+ baseUrl: configured.baseUrl,
36
+ authHeader,
37
+ isRemote: configured.isRemote,
38
+ };
39
+ }
40
+ }
41
+ catch { }
42
+ // Fallback to local gateway
15
43
  try {
16
44
  const port = serverLifecycle.getPort();
17
45
  const host = serverLifecycle.getHost() || "127.0.0.1";
18
46
  const cleanHost = host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host;
19
- return `http://${cleanHost}:${port}`;
47
+ const baseUrl = `http://${cleanHost}:${port}`;
48
+ let authHeader = process.env.ROUTER_API_KEY ? `Bearer ${process.env.ROUTER_API_KEY.trim()}` : "";
49
+ if (!authHeader) {
50
+ try {
51
+ const activeKey = SettingsRepository.getGatewayApiKeys().find((k) => k.isActive)?.key;
52
+ if (activeKey) {
53
+ authHeader = `Bearer ${activeKey}`;
54
+ }
55
+ }
56
+ catch { }
57
+ }
58
+ return {
59
+ baseUrl,
60
+ authHeader,
61
+ isRemote: false,
62
+ };
20
63
  }
21
64
  catch {
22
- return DEFAULT_ROUTER_BASE;
65
+ return {
66
+ baseUrl: DEFAULT_ROUTER_BASE,
67
+ authHeader: process.env.ROUTER_API_KEY ? `Bearer ${process.env.ROUTER_API_KEY.trim()}` : "",
68
+ isRemote: false,
69
+ };
23
70
  }
24
71
  }
72
+ export function getRouterBaseUrl() {
73
+ return getRouterTarget().baseUrl;
74
+ }
25
75
  const STRIP_HEADERS = new Set([
26
76
  "host",
27
77
  "content-length",
@@ -176,17 +226,7 @@ export async function fetchRouter(openaiBody, path = "/v1/chat/completions", cli
176
226
  forwarded[k] = v;
177
227
  }
178
228
  }
179
- const baseUrl = getRouterBaseUrl();
180
- let authHeader = process.env.ROUTER_API_KEY ? `Bearer ${process.env.ROUTER_API_KEY}` : "";
181
- if (!authHeader) {
182
- try {
183
- const activeKey = SettingsRepository.getGatewayApiKeys().find((k) => k.isActive)?.key;
184
- if (activeKey) {
185
- authHeader = `Bearer ${activeKey}`;
186
- }
187
- }
188
- catch { }
189
- }
229
+ const { baseUrl, authHeader } = getRouterTarget();
190
230
  const response = await fetch(`${baseUrl}${path}`, {
191
231
  method: "POST",
192
232
  headers: {
@@ -30,6 +30,8 @@ export class MitmManager {
30
30
  const uninstallCommands = getUninstallCommand(ROOT_CA_CERT_PATH);
31
31
  const liveDns = this.checkLiveDns();
32
32
  const orphanedDns = !serverStatus.running && Object.values(liveDns).some(Boolean);
33
+ const target = MitmRepository.getRouterTarget();
34
+ const routerBaseUrl = target.baseUrl || getMapigateBaseUrl();
33
35
  return {
34
36
  running: serverStatus.running,
35
37
  port: serverStatus.port,
@@ -41,7 +43,9 @@ export class MitmManager {
41
43
  uninstallCommands,
42
44
  dnsStatus: liveDns,
43
45
  orphanedDns,
44
- routerBaseUrl: getMapigateBaseUrl(),
46
+ routerBaseUrl,
47
+ isRemoteRouter: target.isRemote,
48
+ hasRouterApiKey: Boolean(target.apiKey),
45
49
  };
46
50
  }
47
51
  async startServer(options) {
@@ -59,7 +63,7 @@ export class MitmManager {
59
63
  // Pre-flight check: is port already occupied?
60
64
  const portOwner = await inspectPortOwner(targetPort);
61
65
  if (portOwner.inUse) {
62
- const isTimeWait = portOwner.pid === 0 || Boolean(portOwner.processName?.toLowerCase().includes("idle"));
66
+ const isTimeWait = Boolean(portOwner.isTransient) || portOwner.pid === 0 || Boolean(portOwner.processName?.toLowerCase().includes("idle"));
63
67
  if (portOwner.pid === process.pid || isTimeWait) {
64
68
  // Port is held by this Mapigate process or in transient TCP TIME_WAIT from a recent restart.
65
69
  // Polling to let socket release cleanly.
@@ -130,6 +130,12 @@ function inspectPortOwnerNetstat(port) {
130
130
  * Inspect the process currently occupying the given TCP port.
131
131
  */
132
132
  export async function inspectPortOwner(port) {
133
+ // Fast path: Probe whether the port is free to bind on 0.0.0.0.
134
+ // If the socket binds successfully, no process is listening or blocking the port.
135
+ const isFree = await checkPortFree(port);
136
+ if (isFree) {
137
+ return { port, inUse: false };
138
+ }
133
139
  const isWin = process.platform === "win32";
134
140
  if (isWin) {
135
141
  try {
@@ -144,6 +150,8 @@ if ($c) {
144
150
  InUse = $true
145
151
  Pid = [int]$c.OwningProcess
146
152
  ProcessName = if ($p) { [string]$p.ProcessName } else { "" }
153
+ State = [string]$c.State
154
+ ProcessExists = [bool]$p
147
155
  } | ConvertTo-Json -Compress
148
156
  } else {
149
157
  @{ InUse = $false } | ConvertTo-Json -Compress
@@ -163,8 +171,12 @@ if ($c) {
163
171
  const parsed = JSON.parse(psOutput);
164
172
  if (parsed.InUse) {
165
173
  const pid = parsed.Pid;
166
- const isTimeWait = pid === 0;
167
- let processName = isTimeWait
174
+ const state = parsed.State || "";
175
+ const processExists = parsed.ProcessExists !== false;
176
+ const isTransientState = ["TimeWait", "FinWait1", "FinWait2", "CloseWait", "Closing", "LastAck"].includes(state);
177
+ const isDeadProcess = !processExists && pid > 4;
178
+ const isTimeWait = pid === 0 || isTransientState || isDeadProcess;
179
+ const processName = isTimeWait
168
180
  ? "Idle (TIME_WAIT)"
169
181
  : parsed.ProcessName || (pid <= 4 ? "System" : "unknown");
170
182
  const isSystemProcess = !isTimeWait && isProtectedSystemProcess(pid, processName);
@@ -176,10 +188,11 @@ if ($c) {
176
188
  return {
177
189
  port,
178
190
  inUse: true,
179
- pid,
191
+ pid: isTimeWait && isDeadProcess ? 0 : pid,
180
192
  processName,
181
193
  isSystemProcess,
182
194
  remediationHint: hint,
195
+ isTransient: isTimeWait,
183
196
  };
184
197
  }
185
198
  }
@@ -212,22 +225,18 @@ if ($c) {
212
225
  processName,
213
226
  isSystemProcess,
214
227
  remediationHint: hint,
228
+ isTransient: isTimeWait,
215
229
  };
216
230
  }
217
- // Verify if socket is actually free
218
- const isFree = await checkPortFree(port);
219
- if (!isFree) {
220
- // Port in use but PID couldn't be resolved (likely elevated system driver HTTP.sys)
221
- return {
222
- port,
223
- inUse: true,
224
- pid: 4,
225
- processName: "System",
226
- isSystemProcess: true,
227
- remediationHint: SYSTEM_REMEDIATION_HINT,
228
- };
229
- }
230
- return { port, inUse: false };
231
+ // Port in use but PID couldn't be resolved (likely elevated system driver HTTP.sys)
232
+ return {
233
+ port,
234
+ inUse: true,
235
+ pid: 4,
236
+ processName: "System",
237
+ isSystemProcess: true,
238
+ remediationHint: SYSTEM_REMEDIATION_HINT,
239
+ };
231
240
  }
232
241
  // POSIX (Linux/macOS)
233
242
  try {
@@ -288,13 +297,23 @@ export async function killProcessByPid(pid, _force = true, knownProcessName) {
288
297
  const isWin = process.platform === "win32";
289
298
  if (isWin) {
290
299
  await new Promise((resolve, reject) => {
291
- exec(`taskkill /F /PID ${pid}`, { windowsHide: true }, (err) => {
300
+ exec(`taskkill /F /PID ${pid}`, { windowsHide: true }, (err, _stdout, stderr) => {
292
301
  if (!err)
293
302
  return resolve();
303
+ const errStr = `${err.message} ${stderr || ""}`.toLowerCase();
304
+ if (errStr.includes("not found")) {
305
+ // Process has already terminated
306
+ return resolve();
307
+ }
294
308
  // Fallback to PowerShell Stop-Process
295
- exec(`powershell -NoProfile -NonInteractive -Command "Stop-Process -Id ${pid} -Force"`, { windowsHide: true }, (psErr) => {
309
+ exec(`powershell -NoProfile -NonInteractive -Command "Stop-Process -Id ${pid} -Force"`, { windowsHide: true }, (psErr, _psOut, psStderr) => {
296
310
  if (!psErr)
297
311
  return resolve();
312
+ const psErrStr = `${psErr.message} ${psStderr || ""}`.toLowerCase();
313
+ if (psErrStr.includes("cannot find") || psErrStr.includes("not found")) {
314
+ // Process has already terminated
315
+ return resolve();
316
+ }
298
317
  reject(new Error(`Failed to terminate PID ${pid}: ${err.message}`));
299
318
  });
300
319
  });
@@ -2,7 +2,7 @@ import { OpenAiCompatibleProvider } from "../../core/base/openAiProvider.js";
2
2
  import { metadata } from "./metadata.js";
3
3
  import { getMimoUsage } from "../../runtime/mimo/quota.js";
4
4
  import { AnthropicAdapter } from "../../../core/adapters/anthropicAdapter.js";
5
- import { rescueInlineToolCalls, createStreamToolCallRescuer, } from "../../../core/adapters/helpers/toolCallRescue.js";
5
+ import { createStreamToolCallRescuer, } from "../../../core/adapters/helpers/toolCallRescue.js";
6
6
  export class XiaomiTokenplanProvider extends OpenAiCompatibleProvider {
7
7
  id = metadata.id;
8
8
  name = metadata.name;
@@ -19,7 +19,7 @@ export class XiaomiTokenplanProvider extends OpenAiCompatibleProvider {
19
19
  return { ...context.body, model: context.targetModel };
20
20
  }
21
21
  return {
22
- ...AnthropicAdapter.openAiToAnthropic(context.body),
22
+ ...AnthropicAdapter.openAiToAnthropic(context.body, context.targetModel, context.provider?.id || this.id),
23
23
  model: context.targetModel,
24
24
  };
25
25
  }
@@ -66,12 +66,37 @@ export class XiaomiTokenplanProvider extends OpenAiCompatibleProvider {
66
66
  return chunk;
67
67
  const choice = chunk.choices[0];
68
68
  const delta = choice?.delta;
69
- if (!delta?.content || typeof delta.content !== "string")
70
- return chunk;
71
69
  const ctx = context;
72
70
  if (!ctx._toolRescuer) {
73
- ctx._toolRescuer = createStreamToolCallRescuer();
71
+ const tools = context.req?.body?.tools || context.body?.tools;
72
+ const toolNames = Array.isArray(tools)
73
+ ? new Set(tools.map((t) => t.function?.name || t.name).filter(Boolean))
74
+ : undefined;
75
+ ctx._toolRescuer = createStreamToolCallRescuer(toolNames);
76
+ }
77
+ if (choice.finish_reason) {
78
+ const { calls, cleanText } = ctx._toolRescuer.flush();
79
+ if (calls.length > 0) {
80
+ if (!choice.delta)
81
+ choice.delta = {};
82
+ choice.delta.tool_calls = calls.map((c, idx) => ({
83
+ index: idx,
84
+ id: `call_mimo_${Date.now()}_${idx}`,
85
+ type: "function",
86
+ function: {
87
+ name: c.name,
88
+ arguments: c.arguments,
89
+ },
90
+ }));
91
+ choice.finish_reason = "tool_calls";
92
+ }
93
+ if (cleanText && choice.delta) {
94
+ choice.delta.content = (choice.delta.content || "") + cleanText;
95
+ }
96
+ return chunk;
74
97
  }
98
+ if (!delta?.content || typeof delta.content !== "string")
99
+ return chunk;
75
100
  const { calls, cleanText } = ctx._toolRescuer.feed(delta.content);
76
101
  if (calls.length > 0) {
77
102
  delta.tool_calls = calls.map((c, idx) => ({
@@ -92,15 +117,22 @@ export class XiaomiTokenplanProvider extends OpenAiCompatibleProvider {
92
117
  delta.content = cleanText;
93
118
  return chunk;
94
119
  }
95
- transformResponseBody(body, _context) {
120
+ transformResponseBody(body, context) {
96
121
  if (!body || typeof body !== "object")
97
122
  return body;
98
123
  const choice = body.choices?.[0];
99
124
  const msg = choice?.message;
100
- if (msg?.content && typeof msg.content === "string" && msg.content.includes("<tool_call>")) {
101
- const rescue = rescueInlineToolCalls(msg.content, new Set());
102
- if (rescue.detected && rescue.calls && rescue.calls.length > 0) {
103
- msg.tool_calls = rescue.calls.map((c, idx) => ({
125
+ if (msg?.content && typeof msg.content === "string") {
126
+ const tools = context.req?.body?.tools || context.body?.tools;
127
+ const toolNames = Array.isArray(tools)
128
+ ? new Set(tools.map((t) => t.function?.name || t.name).filter(Boolean))
129
+ : undefined;
130
+ const rescuer = createStreamToolCallRescuer(toolNames);
131
+ const r1 = rescuer.feed(msg.content);
132
+ const r2 = rescuer.flush();
133
+ const allCalls = [...r1.calls, ...r2.calls];
134
+ if (allCalls.length > 0) {
135
+ msg.tool_calls = allCalls.map((c, idx) => ({
104
136
  id: `call_mimo_${Date.now()}_${idx}`,
105
137
  type: "function",
106
138
  function: {
@@ -108,7 +140,8 @@ export class XiaomiTokenplanProvider extends OpenAiCompatibleProvider {
108
140
  arguments: c.arguments,
109
141
  },
110
142
  }));
111
- msg.content = rescue.cleanText || null;
143
+ const combinedClean = [r1.cleanText, r2.cleanText].filter(Boolean).join("");
144
+ msg.content = combinedClean.trim() || null;
112
145
  if (choice.finish_reason === "stop" || !choice.finish_reason) {
113
146
  choice.finish_reason = "tool_calls";
114
147
  }
@@ -43,7 +43,7 @@ export class AnthropicCompatibleProvider extends BaseProvider {
43
43
  transformRequestBody(context) {
44
44
  const modelToUse = this.resolveUpstreamModelId(context);
45
45
  if (context.clientFormat === "openai") {
46
- const converted = AnthropicAdapter.openAiToAnthropic(context.body);
46
+ const converted = AnthropicAdapter.openAiToAnthropic(context.body, modelToUse || context.targetModel, context.provider?.id || this.id);
47
47
  converted.model = modelToUse;
48
48
  return converted;
49
49
  }
@@ -17,7 +17,7 @@ export class BedrockProvider extends BaseProvider {
17
17
  transformRequestBody(context) {
18
18
  let body = context.body;
19
19
  if (context.clientFormat === "openai") {
20
- body = AnthropicAdapter.openAiToAnthropic(body);
20
+ body = AnthropicAdapter.openAiToAnthropic(body, context.targetModel, context.provider?.id || this.id);
21
21
  }
22
22
  else {
23
23
  body = { ...body };
@@ -1,6 +1,6 @@
1
1
  import { OpenAiCompatibleProvider } from "../../core/base/openAiProvider.js";
2
2
  import { getMimoUsage } from "./quota.js";
3
- import { rescueInlineToolCalls, createStreamToolCallRescuer, } from "../../../core/adapters/helpers/toolCallRescue.js";
3
+ import { createStreamToolCallRescuer, } from "../../../core/adapters/helpers/toolCallRescue.js";
4
4
  export class MimoProvider extends OpenAiCompatibleProvider {
5
5
  id = "mimo";
6
6
  name = "Xiaomi MiMo";
@@ -16,12 +16,37 @@ export class MimoProvider extends OpenAiCompatibleProvider {
16
16
  return chunk;
17
17
  const choice = chunk.choices[0];
18
18
  const delta = choice?.delta;
19
- if (!delta?.content || typeof delta.content !== "string")
20
- return chunk;
21
19
  const ctx = context;
22
20
  if (!ctx._toolRescuer) {
23
- ctx._toolRescuer = createStreamToolCallRescuer();
21
+ const tools = context.req?.body?.tools || context.body?.tools;
22
+ const toolNames = Array.isArray(tools)
23
+ ? new Set(tools.map((t) => t.function?.name || t.name).filter(Boolean))
24
+ : undefined;
25
+ ctx._toolRescuer = createStreamToolCallRescuer(toolNames);
26
+ }
27
+ if (choice.finish_reason) {
28
+ const { calls, cleanText } = ctx._toolRescuer.flush();
29
+ if (calls.length > 0) {
30
+ if (!choice.delta)
31
+ choice.delta = {};
32
+ choice.delta.tool_calls = calls.map((c, idx) => ({
33
+ index: idx,
34
+ id: `call_mimo_${Date.now()}_${idx}`,
35
+ type: "function",
36
+ function: {
37
+ name: c.name,
38
+ arguments: c.arguments,
39
+ },
40
+ }));
41
+ choice.finish_reason = "tool_calls";
42
+ }
43
+ if (cleanText && choice.delta) {
44
+ choice.delta.content = (choice.delta.content || "") + cleanText;
45
+ }
46
+ return chunk;
24
47
  }
48
+ if (!delta?.content || typeof delta.content !== "string")
49
+ return chunk;
25
50
  const { calls, cleanText } = ctx._toolRescuer.feed(delta.content);
26
51
  if (calls.length > 0) {
27
52
  delta.tool_calls = calls.map((c, idx) => ({
@@ -42,15 +67,22 @@ export class MimoProvider extends OpenAiCompatibleProvider {
42
67
  delta.content = cleanText;
43
68
  return chunk;
44
69
  }
45
- transformResponseBody(body, _context) {
70
+ transformResponseBody(body, context) {
46
71
  if (!body || typeof body !== "object")
47
72
  return body;
48
73
  const choice = body.choices?.[0];
49
74
  const msg = choice?.message;
50
- if (msg?.content && typeof msg.content === "string" && msg.content.includes("<tool_call>")) {
51
- const rescue = rescueInlineToolCalls(msg.content, new Set());
52
- if (rescue.detected && rescue.calls && rescue.calls.length > 0) {
53
- msg.tool_calls = rescue.calls.map((c, idx) => ({
75
+ if (msg?.content && typeof msg.content === "string") {
76
+ const tools = context.req?.body?.tools || context.body?.tools;
77
+ const toolNames = Array.isArray(tools)
78
+ ? new Set(tools.map((t) => t.function?.name || t.name).filter(Boolean))
79
+ : undefined;
80
+ const rescuer = createStreamToolCallRescuer(toolNames);
81
+ const r1 = rescuer.feed(msg.content);
82
+ const r2 = rescuer.flush();
83
+ const allCalls = [...r1.calls, ...r2.calls];
84
+ if (allCalls.length > 0) {
85
+ msg.tool_calls = allCalls.map((c, idx) => ({
54
86
  id: `call_mimo_${Date.now()}_${idx}`,
55
87
  type: "function",
56
88
  function: {
@@ -58,7 +90,8 @@ export class MimoProvider extends OpenAiCompatibleProvider {
58
90
  arguments: c.arguments,
59
91
  },
60
92
  }));
61
- msg.content = rescue.cleanText || null;
93
+ const combinedClean = [r1.cleanText, r2.cleanText].filter(Boolean).join("");
94
+ msg.content = combinedClean.trim() || null;
62
95
  if (choice.finish_reason === "stop" || !choice.finish_reason) {
63
96
  choice.finish_reason = "tool_calls";
64
97
  }
@@ -224,7 +224,13 @@ export async function executeSingleModel(options) {
224
224
  res.once("close", onClientClose);
225
225
  }
226
226
  const upstreamTimeoutMs = Number(process.env.MAPIGATE_UPSTREAM_TIMEOUT_MS) || 180_000;
227
- const timeoutSignal = AbortSignal.timeout(upstreamTimeoutMs);
227
+ const isStreaming = upstreamBody?.stream !== false && !isPanel;
228
+ // Streaming generations with large contexts (e.g. 100k+ tokens) can take many minutes.
229
+ // Use a generous ceiling (30 minutes) for streaming so active token streams aren't aborted mid-sentence at 180s.
230
+ const effectiveTimeoutMs = isStreaming
231
+ ? Math.max(upstreamTimeoutMs, 1_800_000)
232
+ : upstreamTimeoutMs;
233
+ const timeoutSignal = AbortSignal.timeout(effectiveTimeoutMs);
228
234
  const combinedSignal = AbortSignal.any
229
235
  ? AbortSignal.any([abortController.signal, timeoutSignal])
230
236
  : abortController.signal;