mapigate 0.5.98 → 0.5.120

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 (86) hide show
  1. package/README.md +7 -1
  2. package/dist/core/adapters/anthropic/streamAnthropicToOpenAi.js +94 -13
  3. package/dist/core/adapters/anthropic/types.js +3 -1
  4. package/dist/core/adapters/anthropicAdapter.js +2 -2
  5. package/dist/core/adapters/helpers/toolCallRescue.js +224 -10
  6. package/dist/core/adapters/responsesAdapter.js +56 -3
  7. package/dist/core/resilience/index.js +5 -0
  8. package/dist/core/router/earliestResetComparator.js +14 -4
  9. package/dist/core/router/loadBalancer.js +27 -3
  10. package/dist/core/scanner/modelScanner.js +8 -1
  11. package/dist/core/scanner/payloadExtractor.js +8 -3
  12. package/dist/core/scanner/urlResolver.js +10 -2
  13. package/dist/core/usage/quotaService.js +3 -1
  14. package/dist/providers/catalog/xiaomi-tokenplan/metadata.js +6 -1
  15. package/dist/providers/catalog/xiaomi-tokenplan/provider.js +71 -1
  16. package/dist/providers/core/base/baseProvider.js +1 -0
  17. package/dist/providers/runtime/antigravity/executor.js +1 -1
  18. package/dist/providers/runtime/antigravity/metadata.js +4 -3
  19. package/dist/providers/runtime/antigravity/provider.js +2 -2
  20. package/dist/providers/runtime/antigravity/quota.js +9 -3
  21. package/dist/providers/runtime/antigravity/routes.js +2 -2
  22. package/dist/providers/runtime/antigravity/types.js +10 -2
  23. package/dist/providers/runtime/antigravity/weekly.js +1 -1
  24. package/dist/providers/runtime/codex/models.js +1 -6
  25. package/dist/providers/runtime/codex/routes.js +40 -24
  26. package/dist/providers/runtime/cursor/cursorChecksum.js +80 -0
  27. package/dist/providers/runtime/cursor/cursorModels.js +194 -0
  28. package/dist/providers/runtime/cursor/cursorProtobuf.js +193 -0
  29. package/dist/providers/runtime/cursor/cursorSession.js +118 -0
  30. package/dist/providers/runtime/cursor/cursorStreamer.js +250 -0
  31. package/dist/providers/runtime/cursor/cursorWire.js +243 -0
  32. package/dist/providers/runtime/cursor/executor.js +129 -0
  33. package/dist/providers/runtime/cursor/index.js +6 -0
  34. package/dist/providers/runtime/cursor/provider.js +34 -10
  35. package/dist/providers/runtime/cursor-api/auth.js +47 -102
  36. package/dist/providers/runtime/cursor-api/metadata.js +4 -4
  37. package/dist/providers/runtime/cursor-api/provider.js +58 -21
  38. package/dist/providers/runtime/gemini-cli/provider.js +2 -2
  39. package/dist/providers/runtime/kiro/executor.js +4 -2
  40. package/dist/providers/runtime/kiro/metadata.js +2 -2
  41. package/dist/providers/runtime/mimo/metadata.js +1 -0
  42. package/dist/providers/runtime/mimo/provider.js +56 -0
  43. package/dist/server/index.js +10 -1
  44. package/dist/server/proxy/executorHelpers.js +12 -2
  45. package/dist/server/proxy/singleModelExecutor.js +2 -0
  46. package/dist/server/proxy/streaming/sseStreamer.js +7 -2
  47. package/dist/server/routes/apiModels.js +60 -0
  48. package/dist/server/routes/apiProviders.js +50 -9
  49. package/dist/server/routes/apiServer.js +110 -0
  50. package/dist/server/routes/apiSettings.js +35 -7
  51. package/dist/server/routes/apiUsage.js +5 -3
  52. package/dist/shared/constants/quotaOrder.js +1 -0
  53. package/dist/storage/database.js +31 -0
  54. package/dist/storage/repositories/accountModelRepo.js +108 -0
  55. package/dist/storage/repositories/logRepo.js +71 -10
  56. package/dist/storage/repositories/providerRepo.js +69 -59
  57. package/dist/storage/repositories/requestDetailsRepo.js +8 -0
  58. package/dist/storage/repositories/settingsRepo.js +17 -0
  59. package/dist/storage/repositories/usageRepo.js +228 -72
  60. package/dist/web/assets/{CliToolsTab-DE48Y4QZ.js → CliToolsTab-BzhczMaa.js} +1 -1
  61. package/dist/web/assets/{CombosTab-dsZhV95u.js → CombosTab-Cz8KYH4M.js} +1 -1
  62. package/dist/web/assets/{ConfirmModal-BTwfpfgO.js → ConfirmModal-BU1PPpF0.js} +1 -1
  63. package/dist/web/assets/{ConsoleLogTab-DtUTPoi7.js → ConsoleLogTab-CFvXde1l.js} +1 -1
  64. package/dist/web/assets/EditAccountModal-CS2TR4bt.js +1 -0
  65. package/dist/web/assets/{EndpointTab-Ya1KYJSp.js → EndpointTab-DZCRpAbh.js} +1 -1
  66. package/dist/web/assets/{MitmTab-Bl-E-IDY.js → MitmTab-CTfwqdey.js} +1 -1
  67. package/dist/web/assets/{ModelAutocompleteInput-COe36ge6.js → ModelAutocompleteInput-CAi2R2s9.js} +1 -1
  68. package/dist/web/assets/ProviderDetailPage-Dv2LpFj_.js +6 -0
  69. package/dist/web/assets/{ProvidersTab-COC-cJXg.js → ProvidersTab-DwHMHdPu.js} +1 -1
  70. package/dist/web/assets/QuotaTab-DS1y9gGp.js +1 -0
  71. package/dist/web/assets/SettingsTab-DULcs9O4.js +1 -0
  72. package/dist/web/assets/UsageTab-DKBaBAeT.js +1 -0
  73. package/dist/web/assets/index-BisuNW2y.css +1 -0
  74. package/dist/web/assets/index-DPdrZakW.js +2 -0
  75. package/dist/web/assets/metadataRegistry-7DDoxaR3.js +1 -0
  76. package/dist/web/assets/{providersData-DRVJJUB4.js → providersData-Br5RocnM.js} +1 -1
  77. package/dist/web/index.html +2 -2
  78. package/package.json +1 -1
  79. package/dist/web/assets/EditAccountModal-65P5phzh.js +0 -1
  80. package/dist/web/assets/ProviderDetailPage-BnQ7kK6s.js +0 -6
  81. package/dist/web/assets/QuotaTab-DkRBaW79.js +0 -1
  82. package/dist/web/assets/SettingsTab-DPcPmPUd.js +0 -1
  83. package/dist/web/assets/UsageTab-Danjts5j.js +0 -1
  84. package/dist/web/assets/index-CeC7GeyM.js +0 -2
  85. package/dist/web/assets/index-YgSWkEbZ.css +0 -1
  86. package/dist/web/assets/metadataRegistry-Dxrq24qH.js +0 -1
@@ -1,130 +1,75 @@
1
- import crypto from "node:crypto";
2
1
  import { fetchWithDnsBypass } from "../../../shared/utils/dnsResolver.js";
3
- export const CURSOR_API_BASE_URL = "https://api2.cursor.sh";
2
+ /**
3
+ * Cursor Cloud Agents API Official Authentication
4
+ * Reference: https://cursor.com/docs/cloud-agent/api/endpoints
5
+ * Reference: https://cursor.com/docs/api#authentication
6
+ */
7
+ export const CURSOR_API_BASE_URL = "https://api.cursor.com";
4
8
  export const CURSOR_API_KEY_PREFIX = "crsr_";
5
- export const CURSOR_API_KEY_EXCHANGE_PATH = "/auth/exchange_user_api_key";
6
- export const CURSOR_API_KEY_EXCHANGE_URL = `${CURSOR_API_BASE_URL}${CURSOR_API_KEY_EXCHANGE_PATH}`;
7
- export const REFRESH_SKEW_MS = 5 * 60 * 1000;
8
- export const FALLBACK_TTL_MS = 55 * 60 * 1000;
9
- export const EXCHANGE_TIMEOUT_MS = 15_000;
10
- export class CursorApiKeyExchangeError extends Error {
9
+ export const CURSOR_API_VERIFY_PATH = "/v1/me";
10
+ export const CURSOR_API_MODELS_PATH = "/v1/models";
11
+ export const VERIFY_TIMEOUT_MS = 10_000;
12
+ export class CursorApiAuthError extends Error {
11
13
  status;
12
14
  constructor(message, status) {
13
15
  super(message);
14
- this.name = "CursorApiKeyExchangeError";
16
+ this.name = "CursorApiAuthError";
15
17
  this.status = status;
16
18
  }
17
19
  }
18
- const sessionCache = new Map();
19
- const inflightExchanges = new Map();
20
20
  export function isCursorApiKey(value) {
21
- return typeof value === "string" && value.startsWith(CURSOR_API_KEY_PREFIX);
21
+ return typeof value === "string" && value.trim().length > 0 && (value.startsWith(CURSOR_API_KEY_PREFIX) ||
22
+ value.startsWith("key_") ||
23
+ value.length >= 20);
22
24
  }
23
- function cacheKeyFor(apiKey) {
24
- return crypto
25
- .createHmac("sha256", "mapigate-cursor-session-cache-fingerprint-v1")
26
- .update(apiKey)
27
- .digest("hex");
28
- }
29
- export function readJwtExpiryMs(token) {
30
- const parts = token.split(".");
31
- if (parts.length !== 3)
32
- return null;
33
- try {
34
- const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
35
- return typeof payload.exp === "number" && Number.isFinite(payload.exp)
36
- ? payload.exp * 1000
37
- : null;
38
- }
39
- catch {
40
- return null;
41
- }
42
- }
43
- function parseExchangeBody(raw) {
44
- let parsed;
45
- try {
46
- parsed = JSON.parse(raw);
47
- }
48
- catch {
49
- throw new CursorApiKeyExchangeError("Cursor API key exchange returned a non-JSON body", 502);
50
- }
51
- if (!parsed || typeof parsed !== "object") {
52
- throw new CursorApiKeyExchangeError("Cursor API key exchange returned an empty body", 502);
53
- }
54
- const { accessToken, refreshToken } = parsed;
55
- if (typeof accessToken !== "string" || accessToken.length === 0) {
56
- throw new CursorApiKeyExchangeError("Cursor API key exchange returned no accessToken", 502);
57
- }
25
+ /**
26
+ * Builds HTTP headers for Cursor Cloud Agents API.
27
+ * Cursor accepts both Bearer and Basic authentication.
28
+ */
29
+ export function buildCursorApiAuthHeaders(apiKey) {
30
+ const cleanKey = apiKey.trim();
58
31
  return {
59
- accessToken,
60
- refreshToken: typeof refreshToken === "string" && refreshToken.length > 0 ? refreshToken : null,
32
+ "Content-Type": "application/json",
33
+ Accept: "application/json",
34
+ ...(cleanKey ? { Authorization: `Bearer ${cleanKey}` } : {}),
61
35
  };
62
36
  }
63
- export async function exchangeCursorApiKey(apiKey, options = {}) {
64
- if (!isCursorApiKey(apiKey)) {
65
- throw new CursorApiKeyExchangeError(`Cursor API keys start with "${CURSOR_API_KEY_PREFIX}"`, 400);
37
+ /**
38
+ * Verifies an API key against Cursor's GET /v1/me endpoint.
39
+ */
40
+ export async function verifyCursorApiKey(apiKey, options = {}) {
41
+ const cleanKey = apiKey.trim();
42
+ if (!cleanKey) {
43
+ throw new CursorApiAuthError("Cursor API key is required", 400);
66
44
  }
45
+ const baseUrl = (options.baseUrl || CURSOR_API_BASE_URL).replace(/\/+$/, "");
46
+ const url = `${baseUrl}${CURSOR_API_VERIFY_PATH}`;
67
47
  const fetchImpl = options.fetchImpl ?? fetchWithDnsBypass;
68
- const now = options.now ?? Date.now;
69
- const signal = options.signal ?? AbortSignal.timeout(EXCHANGE_TIMEOUT_MS);
48
+ const signal = options.signal ?? AbortSignal.timeout(VERIFY_TIMEOUT_MS);
70
49
  let response;
71
50
  try {
72
- response = await fetchImpl(CURSOR_API_KEY_EXCHANGE_URL, {
73
- method: "POST",
74
- headers: {
75
- authorization: `Bearer ${apiKey}`,
76
- "content-type": "application/json",
77
- accept: "application/json",
78
- },
79
- body: "{}",
51
+ response = await fetchImpl(url, {
52
+ method: "GET",
53
+ headers: buildCursorApiAuthHeaders(cleanKey),
80
54
  signal,
81
55
  });
82
56
  }
83
57
  catch (err) {
84
- if (err instanceof CursorApiKeyExchangeError)
85
- throw err;
86
- throw new CursorApiKeyExchangeError(`Cursor API key exchange request failed: ${err?.message || "network error"}`, 502);
58
+ throw new CursorApiAuthError(`Failed to connect to Cursor Cloud API: ${err?.message || "network error"}`, 502);
59
+ }
60
+ if (response.status === 401) {
61
+ throw new CursorApiAuthError("Authentication failed: Invalid Cursor API key", 401);
87
62
  }
88
- if (response.status === 401 || response.status === 403) {
89
- throw new CursorApiKeyExchangeError("Cursor rejected the API key", 401);
63
+ if (response.status === 403) {
64
+ throw new CursorApiAuthError("Access denied (HTTP 403): Cursor Cloud Agents API requires an eligible paid plan (Pro/Business/Enterprise)", 403);
90
65
  }
91
66
  if (!response.ok) {
92
- throw new CursorApiKeyExchangeError(`Cursor API key exchange failed with HTTP ${response.status}`, response.status >= 500 ? 502 : response.status);
67
+ throw new CursorApiAuthError(`Cursor Cloud API returned HTTP ${response.status}: ${response.statusText}`, response.status);
93
68
  }
94
- const rawText = await response.text();
95
- const { accessToken, refreshToken } = parseExchangeBody(rawText);
96
- const expiresAt = readJwtExpiryMs(accessToken) ?? now() + FALLBACK_TTL_MS;
97
- return { accessToken, refreshToken, expiresAt };
98
- }
99
- export function isFresh(token, nowMs) {
100
- return token.expiresAt - REFRESH_SKEW_MS > nowMs;
101
- }
102
- export async function resolveCursorSessionToken(apiKey, options = {}) {
103
- const now = options.now ?? Date.now;
104
- const key = cacheKeyFor(apiKey);
105
- const cached = sessionCache.get(key);
106
- if (cached && isFresh(cached, now())) {
107
- return cached;
69
+ try {
70
+ return (await response.json());
108
71
  }
109
- const pending = inflightExchanges.get(key);
110
- if (pending) {
111
- return pending;
72
+ catch {
73
+ throw new CursorApiAuthError("Cursor Cloud API returned non-JSON response", 502);
112
74
  }
113
- const exchange = exchangeCursorApiKey(apiKey, options)
114
- .then((token) => {
115
- sessionCache.set(key, token);
116
- return token;
117
- })
118
- .finally(() => {
119
- inflightExchanges.delete(key);
120
- });
121
- inflightExchanges.set(key, exchange);
122
- return exchange;
123
- }
124
- export function invalidateCursorSessionToken(apiKey) {
125
- sessionCache.delete(cacheKeyFor(apiKey));
126
- }
127
- export function __resetCursorApiKeyAuthForTest() {
128
- sessionCache.clear();
129
- inflightExchanges.clear();
130
75
  }
@@ -14,15 +14,15 @@ export const metadata = {
14
14
  website: "https://cursor.com/dashboard/api",
15
15
  notice: {
16
16
  apiKeyUrl: "https://cursor.com/dashboard/api",
17
- text: "Cursor User API Key (crsr_...) from cursor.com/dashboard/api. Keys are exchanged automatically for session tokens.",
17
+ text: "Cursor API Key (crsr_...) from cursor.com/dashboard/api. Direct REST API at api.cursor.com. Cloud Agents API requires a Pro/Business plan.",
18
18
  },
19
19
  category: "apikey",
20
20
  authType: "apikey",
21
- baseUrl: "https://api2.cursor.sh",
21
+ baseUrl: "https://api.cursor.com",
22
22
  baseUrls: [
23
- "https://api2.cursor.sh",
23
+ "https://api.cursor.com",
24
24
  ],
25
- validateUrl: "",
25
+ validateUrl: "https://api.cursor.com/v1/models",
26
26
  format: "openai",
27
27
  defaultHeaders: {
28
28
  "content-type": "application/json",
@@ -1,40 +1,77 @@
1
1
  import { OpenAiCompatibleProvider } from "../../core/base/openAiProvider.js";
2
2
  import { metadata } from "./metadata.js";
3
- import { isCursorApiKey, resolveCursorSessionToken, invalidateCursorSessionToken, } from "./auth.js";
3
+ import { buildCursorApiAuthHeaders, CURSOR_API_MODELS_PATH } from "./auth.js";
4
+ import { extractModelsFromPayload } from "../../../core/scanner/payloadExtractor.js";
4
5
  export class CursorApiProvider extends OpenAiCompatibleProvider {
5
6
  id = metadata.id;
6
7
  name = metadata.name;
7
8
  defaultFormat = metadata.format || "openai";
8
9
  async buildHeaders(context) {
9
- const rawKey = context.account?.rawApiKey || "";
10
- let bearerToken = rawKey;
11
- if (isCursorApiKey(rawKey)) {
12
- const session = await resolveCursorSessionToken(rawKey);
13
- bearerToken = session.accessToken;
14
- }
10
+ const rawKey = (context.account?.rawApiKey || "").trim();
15
11
  const outgoingHeaders = {
16
- "Content-Type": "application/json",
17
- ...(bearerToken ? { Authorization: `Bearer ${bearerToken}` } : {}),
12
+ ...buildCursorApiAuthHeaders(rawKey),
18
13
  ...(context.provider?.customHeaders || {}),
19
14
  };
20
15
  this.applyAnthropicClientHeaders(outgoingHeaders, context);
21
16
  return outgoingHeaders;
22
17
  }
23
- async handleAuthRefresh(context, status) {
24
- if (status !== 401 || !context.account?.rawApiKey) {
25
- return false;
26
- }
27
- const rawKey = context.account.rawApiKey;
28
- if (!isCursorApiKey(rawKey)) {
29
- return false;
18
+ async probeModels(context) {
19
+ const rawKey = (context.account?.rawApiKey || context.apiKey || "").trim();
20
+ if (!rawKey) {
21
+ return {
22
+ success: false,
23
+ error: "Cursor API key is required (crsr_...).",
24
+ };
30
25
  }
26
+ const timeoutMs = context.timeoutMs || 10_000;
27
+ const probeUrl = `${metadata.baseUrl}${CURSOR_API_MODELS_PATH}`;
31
28
  try {
32
- invalidateCursorSessionToken(rawKey);
33
- await resolveCursorSessionToken(rawKey);
34
- return true;
29
+ const controller = new AbortController();
30
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
31
+ const res = await fetch(probeUrl, {
32
+ headers: buildCursorApiAuthHeaders(rawKey),
33
+ signal: controller.signal,
34
+ });
35
+ clearTimeout(timer);
36
+ if (res.ok) {
37
+ const data = (await res.json());
38
+ const scanned = extractModelsFromPayload(data, this.id);
39
+ const resolvedModels = scanned.length ? scanned : metadata.models;
40
+ return {
41
+ success: true,
42
+ endpointUrl: probeUrl,
43
+ models: resolvedModels.map((m) => ({
44
+ id: m.id,
45
+ name: m.name || m.id,
46
+ contextLength: m.contextLength || 200000,
47
+ })),
48
+ count: resolvedModels.length,
49
+ };
50
+ }
51
+ if (res.status === 401) {
52
+ return {
53
+ success: false,
54
+ error: "Authentication failed (HTTP 401): Invalid Cursor API key",
55
+ authError: "Authentication failed (HTTP 401): Invalid Cursor API key",
56
+ };
57
+ }
58
+ if (res.status === 403) {
59
+ return {
60
+ success: false,
61
+ error: "Access denied (HTTP 403): Cursor Cloud Agents API requires a Pro/Business plan. Free accounts are not authorized.",
62
+ authError: "Access denied (HTTP 403): Cursor Cloud Agents API requires a Pro/Business plan. Free accounts are not authorized.",
63
+ };
64
+ }
65
+ return {
66
+ success: false,
67
+ error: `Endpoint ${probeUrl} returned HTTP ${res.status}: ${res.statusText}`,
68
+ };
35
69
  }
36
- catch {
37
- return false;
70
+ catch (err) {
71
+ return {
72
+ success: false,
73
+ error: `Failed to connect to ${probeUrl}: ${err.message || String(err)}`,
74
+ };
38
75
  }
39
76
  }
40
77
  }
@@ -44,9 +44,9 @@ export class GeminiCliProvider extends OpenAiCompatibleProvider {
44
44
  ];
45
45
  const reqHeaders = {
46
46
  "Content-Type": "application/json",
47
- "User-Agent": "antigravity/hub/2.28.0 darwin/arm64",
47
+ "User-Agent": "antigravity/hub/2.29.0 darwin/arm64",
48
48
  "X-Client-Name": "antigravity",
49
- "X-Client-Version": "2.28.0",
49
+ "X-Client-Version": "2.29.0",
50
50
  "x-request-source": "local",
51
51
  Accept: "application/json",
52
52
  ...(context.customHeaders || {}),
@@ -49,13 +49,15 @@ export async function executeKiro(context, _providerInstance) {
49
49
  const upstreamPayload = buildKiroPayload(body, upstreamModel, context.account, requestId);
50
50
  // 2. Build Headers
51
51
  const bearerToken = extractTokenFromAccount(context.account);
52
+ const provCustomHeaders = context.provider?.customHeaders || {};
52
53
  const headers = {
53
54
  "Content-Type": "application/json",
54
55
  Accept: "application/vnd.amazon.eventstream",
55
- "User-Agent": "AWS-SDK-JS/3.0.0 kiro-ide/1.0.0",
56
- "x-amz-user-agent": "aws-sdk-js/3.0.0 kiro-ide/1.0.0",
56
+ "User-Agent": "aws-sdk-js/3.0.0 KiroIDE",
57
+ "x-amz-user-agent": "aws-sdk-js/3.0.0 KiroIDE",
57
58
  "x-amzn-kiro-agent-mode": "spec",
58
59
  "x-amzn-codewhisperer-machine-id": "kiro-desktop",
60
+ ...provCustomHeaders,
59
61
  };
60
62
  if (bearerToken) {
61
63
  headers["Authorization"] = bearerToken.startsWith("Bearer ") ? bearerToken : `Bearer ${bearerToken}`;
@@ -31,8 +31,8 @@ export const metadata = {
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 kiro-ide/1.0.0",
35
- "X-Amz-User-Agent": "aws-sdk-js/3.0.0 kiro-ide/1.0.0"
34
+ "User-Agent": "aws-sdk-js/3.0.0 KiroIDE",
35
+ "X-Amz-User-Agent": "aws-sdk-js/3.0.0 KiroIDE"
36
36
  },
37
37
  "thinkingMode": "auto",
38
38
  "oauth": {
@@ -29,6 +29,7 @@ export const metadata = {
29
29
  ],
30
30
  "validateUrl": "https://api.xiaomimimo.com/v1/models",
31
31
  "format": "openai",
32
+ "rescueInlineTools": true,
32
33
  "defaultHeaders": {},
33
34
  "thinkingMode": "auto",
34
35
  "regions": [
@@ -1,5 +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
4
  export class MimoProvider extends OpenAiCompatibleProvider {
4
5
  id = "mimo";
5
6
  name = "Xiaomi MiMo";
@@ -10,5 +11,60 @@ export class MimoProvider extends OpenAiCompatibleProvider {
10
11
  async fetchQuota(context) {
11
12
  return await getMimoUsage(context.account.rawApiKey, context.providerId, context.account.providerSpecificData, context.account.id);
12
13
  }
14
+ transformResponseChunk(chunk, context) {
15
+ if (!chunk?.choices?.length)
16
+ return chunk;
17
+ const choice = chunk.choices[0];
18
+ const delta = choice?.delta;
19
+ if (!delta?.content || typeof delta.content !== "string")
20
+ return chunk;
21
+ const ctx = context;
22
+ if (!ctx._toolRescuer) {
23
+ ctx._toolRescuer = createStreamToolCallRescuer();
24
+ }
25
+ const { calls, cleanText } = ctx._toolRescuer.feed(delta.content);
26
+ if (calls.length > 0) {
27
+ delta.tool_calls = calls.map((c, idx) => ({
28
+ index: idx,
29
+ id: `call_mimo_${Date.now()}_${idx}`,
30
+ type: "function",
31
+ function: {
32
+ name: c.name,
33
+ arguments: c.arguments,
34
+ },
35
+ }));
36
+ delta.content = cleanText || null;
37
+ if (choice.finish_reason === "stop") {
38
+ choice.finish_reason = "tool_calls";
39
+ }
40
+ return chunk;
41
+ }
42
+ delta.content = cleanText;
43
+ return chunk;
44
+ }
45
+ transformResponseBody(body, _context) {
46
+ if (!body || typeof body !== "object")
47
+ return body;
48
+ const choice = body.choices?.[0];
49
+ 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) => ({
54
+ id: `call_mimo_${Date.now()}_${idx}`,
55
+ type: "function",
56
+ function: {
57
+ name: c.name,
58
+ arguments: c.arguments,
59
+ },
60
+ }));
61
+ msg.content = rescue.cleanText || null;
62
+ if (choice.finish_reason === "stop" || !choice.finish_reason) {
63
+ choice.finish_reason = "tool_calls";
64
+ }
65
+ }
66
+ }
67
+ return body;
68
+ }
13
69
  }
14
70
  export default MimoProvider;
@@ -24,7 +24,7 @@ import { usageRouter } from "./routes/apiUsage.js";
24
24
  import { settingsRouter } from "./routes/apiSettings.js";
25
25
  import { authRouter } from "./routes/apiAuth.js";
26
26
  import { masterAuthMiddleware } from "./middlewares/masterAuthMiddleware.js";
27
- import { serverRouter, handleShutdownRequest, handleRestartRequest } from "./routes/apiServer.js";
27
+ import { serverRouter, handleShutdownRequest, handleRestartRequest, handleUpgradeRequest } from "./routes/apiServer.js";
28
28
  import { serverLifecycle } from "./lifecycle.js";
29
29
  import { initTray } from "../cli/tray/tray.js";
30
30
  import { MitmRepository } from "../storage/repositories/mitmRepo.js";
@@ -32,6 +32,7 @@ import { ProviderRepository } from "../storage/repositories/providerRepo.js";
32
32
  import { tokenScheduler } from "../core/scheduler/tokenScheduler.js";
33
33
  import { PidFileManager } from "../cli/daemon/pidFile.js";
34
34
  import { SettingsRepository } from "../storage/repositories/settingsRepo.js";
35
+ import { UsageRepository } from "../storage/repositories/usageRepo.js";
35
36
  import { isHostPatternMatch, DEFAULT_ALLOWED_HOSTS } from "../shared/utils/security.js";
36
37
  import { getRegistryProvider } from "../providers/core/metadataRegistry.js";
37
38
  // Sync persisted log level from settings repository if env is not explicitly set
@@ -237,6 +238,7 @@ app.use("/api/settings", settingsRouter);
237
238
  app.use("/api/server", serverRouter);
238
239
  app.post("/api/shutdown", handleShutdownRequest);
239
240
  app.post("/api/restart", handleRestartRequest);
241
+ app.post("/api/upgrade", handleUpgradeRequest);
240
242
  // OAuth Callback Relay HTML generator
241
243
  function renderOAuthCallbackHtml() {
242
244
  return `<!DOCTYPE html>
@@ -478,6 +480,13 @@ if (!isTest) {
478
480
  // Best-effort
479
481
  }
480
482
  logger.info("SERVER", `[${APP_NAME} v${APP_VERSION}] Gateway running at http://${host}:${port}`);
483
+ // Backfill historical logs into daily_usage_stats if needed
484
+ try {
485
+ UsageRepository.backfillDailyStats();
486
+ }
487
+ catch (err) {
488
+ logger.warn("USAGE", "Failed to backfill daily usage stats:", err);
489
+ }
481
490
  try {
482
491
  const dnsStatus = MitmRepository.getAllToolDnsStatus();
483
492
  logger.info("MITM", "Inspecting tool-level DNS isolation on boot:", dnsStatus);
@@ -42,10 +42,20 @@ export function resolveTargetModelAndProvider(modelStr) {
42
42
  const effective = cleanModelStr || modelStr;
43
43
  let targetModel = effective;
44
44
  let providerId;
45
+ let targetTag;
45
46
  if (effective.includes("/")) {
46
47
  const slash = effective.indexOf("/");
47
- providerId = effective.slice(0, slash);
48
+ const rawProvider = effective.slice(0, slash);
48
49
  targetModel = effective.slice(slash + 1);
50
+ // Parse provider[tag] syntax, e.g. claude[pro] -> provider: claude, tag: pro
51
+ const tagMatch = rawProvider.match(/^([^\[\]]+)\[([^\[\]]+)\]$/);
52
+ if (tagMatch) {
53
+ providerId = tagMatch[1];
54
+ targetTag = tagMatch[2];
55
+ }
56
+ else {
57
+ providerId = rawProvider;
58
+ }
49
59
  }
50
60
  else {
51
61
  const rules = ModelRepository.getAllRules();
@@ -101,5 +111,5 @@ export function resolveTargetModelAndProvider(modelStr) {
101
111
  providerId = activeProviders[0]?.id;
102
112
  }
103
113
  }
104
- return { targetModel, providerId, is1mContext: Boolean(is1mContext) };
114
+ return { targetModel, providerId, targetTag, is1mContext: Boolean(is1mContext) };
105
115
  }
@@ -56,6 +56,7 @@ export async function executeSingleModel(options) {
56
56
  const resolved = resolveTargetModelAndProvider(modelStr);
57
57
  let targetModel = resolved.targetModel;
58
58
  const providerId = resolved.providerId;
59
+ const targetTag = resolved.targetTag;
59
60
  const is1mContext = Boolean(optionIs1m || resolved.is1mContext);
60
61
  if (!providerId) {
61
62
  logger.errorLine(reqTag, LogSymbol.ERROR, `No active provider configured for model '${modelStr}'`);
@@ -97,6 +98,7 @@ export async function executeSingleModel(options) {
97
98
  const account = LoadBalancer.pickAccount(targetProviderId, {
98
99
  excludeAccountIds: triedAccountIds,
99
100
  targetModel,
101
+ targetTag,
100
102
  prefixHash: prefixHash || undefined,
101
103
  sessionId,
102
104
  });
@@ -5,6 +5,7 @@ import { toolSchemaMap } from "../../../core/adapters/helpers/index.js";
5
5
  import { logger, LogSymbol } from "../../../shared/logger.js";
6
6
  import { createStreamTrackingState, extractTokensFromChunk, recordStreamToolCall } from "./streamState.js";
7
7
  import { reasoningCache } from "../../../core/caching/reasoningCache.js";
8
+ import { getRegistryProvider } from "../../../providers/core/metadataRegistry.js";
8
9
  function ensureStreamToolCallIds(chunk, seenIds) {
9
10
  if (!chunk?.choices?.length)
10
11
  return false;
@@ -41,10 +42,14 @@ export async function pipeSseStream(upstreamRes, clientRes, context, provider) {
41
42
  const state = createStreamTrackingState(rtkStats.compressedTokens || 0);
42
43
  const requestTools = context.req?.body?.tools || context.body?.tools;
43
44
  const toolSchemas = toolSchemaMap(requestTools);
45
+ const toolNameSet = new Set(toolSchemas.keys());
46
+ const regMeta = provider?.id ? getRegistryProvider(provider.id) : undefined;
47
+ const shouldRescue = Boolean(context.provider?.rescueInlineTools ?? regMeta?.rescueInlineTools);
48
+ const rescueToolNames = shouldRescue ? toolNameSet : undefined;
44
49
  const openAiToAnthropicState = AnthropicAdapter.createStreamState(requestId, requestTools);
45
- const responsesState = clientFormat === "responses" ? createResponsesStreamState(requestId) : null;
50
+ const responsesState = clientFormat === "responses" ? createResponsesStreamState(requestId, rescueToolNames) : null;
46
51
  const seenToolCallIds = new Map();
47
- const claudeToOpenAiState = AnthropicAdapter.createAnthropicToOpenAiState();
52
+ const claudeToOpenAiState = AnthropicAdapter.createAnthropicToOpenAiState(rescueToolNames);
48
53
  const decoder = new TextDecoder();
49
54
  let buffer = "";
50
55
  let currentEventName = "";
@@ -19,9 +19,19 @@ modelRouter.get("/available", (req, res) => {
19
19
  const accounts = ProviderRepository.getAllAccounts();
20
20
  const dbProviders = ProviderRepository.getAllProviders();
21
21
  const activeCounts = new Map();
22
+ const providerTagsMap = new Map();
22
23
  for (const acc of accounts) {
23
24
  if (acc.isActive) {
24
25
  activeCounts.set(acc.providerId, (activeCounts.get(acc.providerId) || 0) + 1);
26
+ const tag = (acc.tag || acc.providerSpecificData?.tag)?.trim().toLowerCase();
27
+ if (tag) {
28
+ let set = providerTagsMap.get(acc.providerId);
29
+ if (!set) {
30
+ set = new Set();
31
+ providerTagsMap.set(acc.providerId, set);
32
+ }
33
+ set.add(tag);
34
+ }
25
35
  }
26
36
  }
27
37
  const dbProviderMap = new Map(dbProviders.map((p) => [p.id, p]));
@@ -172,6 +182,31 @@ modelRouter.get("/available", (req, res) => {
172
182
  },
173
183
  contextLength: modelCaps.contextWindow || 0,
174
184
  });
185
+ // If provider has tagged accounts, expose tagged variants e.g. claude[pro]/claude-3-7-sonnet
186
+ const tags = providerTagsMap.get(p.id);
187
+ if (tags && tags.size > 0) {
188
+ for (const t of tags) {
189
+ const taggedVal = `${p.id}[${t}]/${modelId}`;
190
+ if (!seenValues.has(taggedVal)) {
191
+ seenValues.add(taggedVal);
192
+ availableModels.push({
193
+ id: modelId,
194
+ value: taggedVal,
195
+ name: `${modelName} [${t}]`,
196
+ providerId: p.id,
197
+ providerName: `${p.name || p.id} [${t}]`,
198
+ hasConnectedAccount: true,
199
+ accountsCount: 1,
200
+ caps: {
201
+ vision: Boolean(modelCaps.vision),
202
+ reasoning: Boolean(modelCaps.reasoning),
203
+ audio: Boolean(modelCaps.audioInput || modelCaps.audioOutput),
204
+ },
205
+ contextLength: modelCaps.contextWindow || 0,
206
+ });
207
+ }
208
+ }
209
+ }
175
210
  }
176
211
  }
177
212
  // 2. Fall back to static PROVIDER_REGISTRY presets if provider has no DB models
@@ -224,6 +259,31 @@ modelRouter.get("/available", (req, res) => {
224
259
  },
225
260
  contextLength: model.contextLength || 0,
226
261
  });
262
+ // If provider has tagged accounts, expose tagged variants e.g. claude[pro]/claude-3-7-sonnet
263
+ const tags = providerTagsMap.get(provider.id);
264
+ if (tags && tags.size > 0) {
265
+ for (const t of tags) {
266
+ const taggedVal = `${provider.id}[${t}]/${model.id}`;
267
+ if (!seenValues.has(taggedVal)) {
268
+ seenValues.add(taggedVal);
269
+ availableModels.push({
270
+ id: model.id,
271
+ value: taggedVal,
272
+ name: `${model.name || model.id} [${t}]`,
273
+ providerId: provider.id,
274
+ providerName: `${provider.name} [${t}]`,
275
+ hasConnectedAccount: true,
276
+ accountsCount: 1,
277
+ caps: {
278
+ vision,
279
+ reasoning,
280
+ audio,
281
+ },
282
+ contextLength: model.contextLength || 0,
283
+ });
284
+ }
285
+ }
286
+ }
227
287
  }
228
288
  }
229
289
  res.json(availableModels);