mapigate 0.5.146 → 0.5.150

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 (54) hide show
  1. package/README.md +1 -1
  2. package/dist/cli/commands/restart.js +9 -1
  3. package/dist/cli/commands/start.js +15 -2
  4. package/dist/core/capabilities/index.js +8 -2
  5. package/dist/core/capabilities/modelDictionary.js +23 -7
  6. package/dist/core/router/ruleEngine.js +11 -1
  7. package/dist/core/usage/pricing.js +52 -24
  8. package/dist/mitm/handlers/antigravity/config.js +6 -0
  9. package/dist/mitm/handlers/base.js +18 -8
  10. package/dist/mitm/server.js +19 -4
  11. package/dist/mitm/toolsHelper.js +2 -0
  12. package/dist/providers/runtime/antigravity/executor.js +1 -1
  13. package/dist/providers/runtime/antigravity/metadata.js +2 -2
  14. package/dist/providers/runtime/antigravity/models.js +2 -0
  15. package/dist/providers/runtime/antigravity/provider.js +2 -2
  16. package/dist/providers/runtime/antigravity/routes.js +2 -2
  17. package/dist/providers/runtime/antigravity/types.js +4 -2
  18. package/dist/providers/runtime/gemini/metadata.js +1 -1
  19. package/dist/providers/runtime/gemini/provider.js +2 -2
  20. package/dist/providers/runtime/gemini-cli/provider.js +2 -2
  21. package/dist/server/lifecycle.js +2 -2
  22. package/dist/server/proxy/executorHelpers.js +52 -4
  23. package/dist/server/routes/apiModels.js +141 -8
  24. package/dist/server/routes/apiProviders.js +21 -14
  25. package/dist/server/routes/mitmRouterTargetHelper.js +14 -1
  26. package/dist/shared/utils/modelUtils.js +64 -0
  27. package/dist/storage/database.js +14 -0
  28. package/dist/storage/repositories/accountModelRepo.js +14 -1
  29. package/dist/storage/repositories/providerRepo.js +66 -38
  30. package/dist/storage/repositories/settingsRepo.js +41 -0
  31. package/dist/storage/repositories/toolMappingRepo.js +29 -0
  32. package/dist/web/assets/{CliToolsTab-BYO-wJ7y.js → CliToolsTab-D_MUwimj.js} +1 -1
  33. package/dist/web/assets/CombosTab-EWUYC3TU.js +1 -0
  34. package/dist/web/assets/{ConfirmModal-BS3mAUd5.js → ConfirmModal-CMfDss7P.js} +1 -1
  35. package/dist/web/assets/{ConsoleLogTab-CSgZxPGW.js → ConsoleLogTab-BSMXSYrR.js} +1 -1
  36. package/dist/web/assets/{EditAccountModal-BhPOk3Ya.js → EditAccountModal-OrvqLLBP.js} +1 -1
  37. package/dist/web/assets/{EndpointTab-BRVjAng2.js → EndpointTab-BwtzqXUN.js} +1 -1
  38. package/dist/web/assets/MitmTab-C7g7GUXW.js +14 -0
  39. package/dist/web/assets/ModelAutocompleteInput-DEb_clZC.js +1 -0
  40. package/dist/web/assets/ProviderDetailPage-BIfOQupC.js +6 -0
  41. package/dist/web/assets/{ProvidersTab-BFdg0gXr.js → ProvidersTab-CwJo_EUX.js} +1 -1
  42. package/dist/web/assets/{QuotaTab-DXg3adeS.js → QuotaTab-PFvP6yAb.js} +1 -1
  43. package/dist/web/assets/{SettingsTab-DoYGKtDn.js → SettingsTab-DwAbjIW3.js} +1 -1
  44. package/dist/web/assets/{UsageTab-O6OK0i38.js → UsageTab-85tTb2_C.js} +1 -1
  45. package/dist/web/assets/{index-5TzViNxR.js → index-CWkEEbms.js} +2 -2
  46. package/dist/web/assets/metadataRegistry-FuJXbCt4.js +1 -0
  47. package/dist/web/assets/{providersData-BI_7MaUL.js → providersData-Y57rBt5o.js} +1 -1
  48. package/dist/web/index.html +1 -1
  49. package/package.json +1 -1
  50. package/dist/web/assets/CombosTab-CujUAbYQ.js +0 -1
  51. package/dist/web/assets/MitmTab-ZOoWyRnb.js +0 -14
  52. package/dist/web/assets/ModelAutocompleteInput-DJkxW2yD.js +0 -1
  53. package/dist/web/assets/ProviderDetailPage-CnWjM-0J.js +0 -6
  54. package/dist/web/assets/metadataRegistry-W75_wn57.js +0 -1
@@ -2,7 +2,9 @@ import { stripModelContextMarker, RuleEngine } from "../../core/router/ruleEngin
2
2
  import { LoadBalancer } from "../../core/router/loadBalancer.js";
3
3
  import { ModelRepository } from "../../storage/repositories/modelRepo.js";
4
4
  import { ProviderRepository } from "../../storage/repositories/providerRepo.js";
5
+ import { PROVIDER_REGISTRY, getRegistryProvider } from "../../shared/constants/providerRegistry.js";
5
6
  import { logger, LogSymbol } from "../../shared/logger.js";
7
+ import { normalizeModelCompareKey } from "../../shared/utils/modelUtils.js";
6
8
  export function tryFailover(providerId, account, status, cooldownMs, triedAccountIds, targetModel, reqTag, isCustom = false, prefixHash, sessionId) {
7
9
  const next = LoadBalancer.pickAccount(providerId, {
8
10
  excludeAccountIds: triedAccountIds,
@@ -37,6 +39,17 @@ export function extractSessionId(req, body) {
37
39
  }
38
40
  return undefined;
39
41
  }
42
+ function isKnownProviderOrAlias(pName) {
43
+ if (!pName)
44
+ return false;
45
+ const pLower = pName.toLowerCase().trim();
46
+ if (PROVIDER_REGISTRY[pLower] || getRegistryProvider(pLower))
47
+ return true;
48
+ const dbProv = ProviderRepository.getProviderById(pLower);
49
+ if (dbProv)
50
+ return true;
51
+ return false;
52
+ }
40
53
  export function resolveTargetModelAndProvider(modelStr) {
41
54
  const { model: cleanModelStr, is1mContext } = stripModelContextMarker(modelStr);
42
55
  const effective = cleanModelStr || modelStr;
@@ -46,15 +59,25 @@ export function resolveTargetModelAndProvider(modelStr) {
46
59
  if (effective.includes("/")) {
47
60
  const slash = effective.indexOf("/");
48
61
  const rawProvider = effective.slice(0, slash);
49
- targetModel = effective.slice(slash + 1);
62
+ const candidateModel = effective.slice(slash + 1);
50
63
  // Parse provider[tag] syntax, e.g. claude[pro] -> provider: claude, tag: pro
64
+ let candidateProviderId = rawProvider;
65
+ let candidateTag;
51
66
  const tagMatch = rawProvider.match(/^([^[\]]+)\[([^[\]]+)\]$/);
52
67
  if (tagMatch) {
53
- providerId = tagMatch[1];
54
- targetTag = tagMatch[2];
68
+ candidateProviderId = tagMatch[1];
69
+ candidateTag = tagMatch[2];
70
+ }
71
+ // Only treat the prefix as a provider if candidateProviderId matches a known registered or DB provider
72
+ if (isKnownProviderOrAlias(candidateProviderId)) {
73
+ providerId = candidateProviderId;
74
+ targetTag = candidateTag;
75
+ targetModel = candidateModel;
55
76
  }
56
77
  else {
57
- providerId = rawProvider;
78
+ // The slash is part of the model name itself (e.g. "coarena/gpt-6-luna", "z-ai/glm-5.3-flash")
79
+ targetModel = effective;
80
+ providerId = undefined;
58
81
  }
59
82
  }
60
83
  else {
@@ -74,6 +97,17 @@ export function resolveTargetModelAndProvider(modelStr) {
74
97
  if (exactMatch) {
75
98
  providerId = exactMatch.id;
76
99
  }
100
+ else {
101
+ const targetCompareKey = normalizeModelCompareKey(targetLower);
102
+ const normalizedMatch = activeProviders.find((p) => Array.isArray(p.models) && p.models.some((m) => normalizeModelCompareKey(m) === targetCompareKey));
103
+ if (normalizedMatch) {
104
+ providerId = normalizedMatch.id;
105
+ const canonical = normalizedMatch.models?.find((m) => normalizeModelCompareKey(m) === targetCompareKey);
106
+ if (canonical) {
107
+ targetModel = canonical;
108
+ }
109
+ }
110
+ }
77
111
  // 2. Try matching by well-known model prefix patterns to active providers
78
112
  if (!providerId) {
79
113
  const isClaude = targetLower.startsWith("claude");
@@ -111,5 +145,19 @@ export function resolveTargetModelAndProvider(modelStr) {
111
145
  providerId = activeProviders[0]?.id;
112
146
  }
113
147
  }
148
+ // Canonical targetModel resolution for known provider (Strict exact first, then dot/dash canonical)
149
+ if (providerId) {
150
+ const prov = ProviderRepository.getProviderById(providerId);
151
+ if (prov && Array.isArray(prov.models) && prov.models.length > 0) {
152
+ const hasExact = prov.models.some((m) => m.toLowerCase() === targetModel.toLowerCase());
153
+ if (!hasExact) {
154
+ const targetCompareKey = normalizeModelCompareKey(targetModel);
155
+ const canonical = prov.models.find((m) => normalizeModelCompareKey(m) === targetCompareKey);
156
+ if (canonical) {
157
+ targetModel = canonical;
158
+ }
159
+ }
160
+ }
161
+ }
114
162
  return { targetModel, providerId, targetTag, is1mContext: Boolean(is1mContext) };
115
163
  }
@@ -1,6 +1,7 @@
1
1
  import { Router } from "express";
2
2
  import { ModelRepository } from "../../storage/repositories/modelRepo.js";
3
3
  import { ProviderRepository } from "../../storage/repositories/providerRepo.js";
4
+ import { AccountModelRepository } from "../../storage/repositories/accountModelRepo.js";
4
5
  import { ComboRepository } from "../../storage/repositories/comboRepo.js";
5
6
  import { PROVIDER_REGISTRY, getRegistryProvider } from "../../shared/constants/providerRegistry.js";
6
7
  import { getCapabilitiesForModel, aggregateComboCapabilities } from "../../core/capabilities/index.js";
@@ -35,6 +36,33 @@ modelRouter.get("/available", (req, res) => {
35
36
  }
36
37
  }
37
38
  const dbProviderMap = new Map(dbProviders.map((p) => [p.id, p]));
39
+ const providerAccountIdsMap = new Map();
40
+ for (const acc of accounts) {
41
+ if (acc.isActive) {
42
+ let list = providerAccountIdsMap.get(acc.providerId);
43
+ if (!list) {
44
+ list = [];
45
+ providerAccountIdsMap.set(acc.providerId, list);
46
+ }
47
+ list.push(acc.id);
48
+ }
49
+ }
50
+ const getScannedAccountModelsForProvider = (pId, regItem) => {
51
+ const candidates = new Set([pId]);
52
+ if (regItem?.alias)
53
+ candidates.add(regItem.alias);
54
+ if (Array.isArray(regItem?.aliases)) {
55
+ for (const a of regItem.aliases)
56
+ candidates.add(a);
57
+ }
58
+ const accIds = [];
59
+ for (const id of candidates) {
60
+ const ids = providerAccountIdsMap.get(id);
61
+ if (ids)
62
+ accIds.push(...ids);
63
+ }
64
+ return accIds.length > 0 ? AccountModelRepository.getModelsForAccounts(accIds) : [];
65
+ };
38
66
  const hasDbConfiguredModels = (pId, regItem) => {
39
67
  const candidates = new Set([pId]);
40
68
  if (regItem?.alias)
@@ -49,7 +77,8 @@ modelRouter.get("/available", (req, res) => {
49
77
  return true;
50
78
  }
51
79
  }
52
- return false;
80
+ const scanned = getScannedAccountModelsForProvider(pId, regItem);
81
+ return scanned.length > 0;
53
82
  };
54
83
  const getProviderAccountsCount = (pId) => {
55
84
  let count = activeCounts.get(pId) || 0;
@@ -156,10 +185,48 @@ modelRouter.get("/available", (req, res) => {
156
185
  models: combo.models,
157
186
  });
158
187
  }
159
- // 1. Prioritize models configured in SQLite (dbProviders)
160
- const sortedDbProviders = [...dbProviders].sort((a, b) => (a.name || a.id).localeCompare(b.name || b.id, undefined, { sensitivity: "base" }));
188
+ // 1. Prioritize models configured in SQLite (dbProviders) and account scanned models
189
+ const dbProviderIdSet = new Set(dbProviders.map((p) => p.id));
190
+ const allProvidersToProcess = [...dbProviders];
191
+ for (const [pId, accIds] of providerAccountIdsMap.entries()) {
192
+ if (!dbProviderIdSet.has(pId)) {
193
+ const reg = PROVIDER_REGISTRY[pId] || getRegistryProvider(pId);
194
+ const scanned = AccountModelRepository.getModelsForAccounts(accIds);
195
+ if (scanned.length > 0) {
196
+ allProvidersToProcess.push({
197
+ id: pId,
198
+ name: reg?.name || pId,
199
+ baseUrl: reg?.baseUrl || "",
200
+ format: (reg?.format || "openai"),
201
+ isActive: true,
202
+ priority: 10,
203
+ models: scanned,
204
+ customHeaders: {},
205
+ thinkingMode: "auto",
206
+ strategy: null,
207
+ stickyLimit: 1,
208
+ createdAt: Date.now(),
209
+ updatedAt: Date.now(),
210
+ });
211
+ dbProviderIdSet.add(pId);
212
+ }
213
+ }
214
+ }
215
+ const sortedDbProviders = allProvidersToProcess.sort((a, b) => (a.name || a.id).localeCompare(b.name || b.id, undefined, { sensitivity: "base" }));
161
216
  for (const p of sortedDbProviders) {
162
- const pModelsRaw = Array.isArray(p.models) ? p.models : [];
217
+ const reg = PROVIDER_REGISTRY[p.id] || getRegistryProvider(p.id);
218
+ let pModelsRaw = Array.isArray(p.models) ? [...p.models] : [];
219
+ // Merge scanned models from active accounts if any
220
+ const scannedModels = getScannedAccountModelsForProvider(p.id, reg);
221
+ if (scannedModels.length > 0) {
222
+ const existingSet = new Set(pModelsRaw.map((m) => (typeof m === "string" ? m : m.id)));
223
+ for (const sm of scannedModels) {
224
+ if (!existingSet.has(sm)) {
225
+ pModelsRaw.push(sm);
226
+ existingSet.add(sm);
227
+ }
228
+ }
229
+ }
163
230
  if (pModelsRaw.length === 0)
164
231
  continue;
165
232
  const pModels = [...pModelsRaw].sort((a, b) => {
@@ -346,8 +413,36 @@ export function handleOpenAiModelsList(_req, res) {
346
413
  });
347
414
  }
348
415
  const seen = new Set();
416
+ const accounts = ProviderRepository.getAllAccounts();
349
417
  const dbProviders = ProviderRepository.getAllProviders();
350
418
  const dbProviderMap = new Map(dbProviders.map((p) => [p.id, p]));
419
+ const providerAccountIdsMap = new Map();
420
+ for (const acc of accounts) {
421
+ if (acc.isActive) {
422
+ let list = providerAccountIdsMap.get(acc.providerId);
423
+ if (!list) {
424
+ list = [];
425
+ providerAccountIdsMap.set(acc.providerId, list);
426
+ }
427
+ list.push(acc.id);
428
+ }
429
+ }
430
+ const getScannedAccountModelsForProvider = (pId, regItem) => {
431
+ const candidates = new Set([pId]);
432
+ if (regItem?.alias)
433
+ candidates.add(regItem.alias);
434
+ if (Array.isArray(regItem?.aliases)) {
435
+ for (const a of regItem.aliases)
436
+ candidates.add(a);
437
+ }
438
+ const accIds = [];
439
+ for (const id of candidates) {
440
+ const ids = providerAccountIdsMap.get(id);
441
+ if (ids)
442
+ accIds.push(...ids);
443
+ }
444
+ return accIds.length > 0 ? AccountModelRepository.getModelsForAccounts(accIds) : [];
445
+ };
351
446
  const hasDbConfiguredModels = (pId, regItem) => {
352
447
  const candidates = new Set([pId]);
353
448
  if (regItem?.alias)
@@ -362,11 +457,49 @@ export function handleOpenAiModelsList(_req, res) {
362
457
  return true;
363
458
  }
364
459
  }
365
- return false;
460
+ const scanned = getScannedAccountModelsForProvider(pId, regItem);
461
+ return scanned.length > 0;
366
462
  };
367
- // 1. Prioritize models configured in SQLite (dbProviders)
368
- for (const p of dbProviders) {
369
- const pModels = Array.isArray(p.models) ? p.models : [];
463
+ // 1. Prioritize models configured in SQLite (dbProviders) and account scanned models
464
+ const dbProviderIdSet = new Set(dbProviders.map((p) => p.id));
465
+ const allProvidersToProcess = [...dbProviders];
466
+ for (const [pId, accIds] of providerAccountIdsMap.entries()) {
467
+ if (!dbProviderIdSet.has(pId)) {
468
+ const reg = PROVIDER_REGISTRY[pId] || getRegistryProvider(pId);
469
+ const scanned = AccountModelRepository.getModelsForAccounts(accIds);
470
+ if (scanned.length > 0) {
471
+ allProvidersToProcess.push({
472
+ id: pId,
473
+ name: reg?.name || pId,
474
+ baseUrl: reg?.baseUrl || "",
475
+ format: (reg?.format || "openai"),
476
+ isActive: true,
477
+ priority: 10,
478
+ models: scanned,
479
+ customHeaders: {},
480
+ thinkingMode: "auto",
481
+ strategy: null,
482
+ stickyLimit: 1,
483
+ createdAt: Date.now(),
484
+ updatedAt: Date.now(),
485
+ });
486
+ dbProviderIdSet.add(pId);
487
+ }
488
+ }
489
+ }
490
+ for (const p of allProvidersToProcess) {
491
+ const reg = PROVIDER_REGISTRY[p.id] || getRegistryProvider(p.id);
492
+ let pModels = Array.isArray(p.models) ? [...p.models] : [];
493
+ const scannedModels = getScannedAccountModelsForProvider(p.id, reg);
494
+ if (scannedModels.length > 0) {
495
+ const existingSet = new Set(pModels.map((m) => (typeof m === "string" ? m : m.id)));
496
+ for (const sm of scannedModels) {
497
+ if (!existingSet.has(sm)) {
498
+ pModels.push(sm);
499
+ existingSet.add(sm);
500
+ }
501
+ }
502
+ }
370
503
  for (const m of pModels) {
371
504
  const mId = typeof m === "string" ? m : m.id;
372
505
  const id = mId.startsWith(`${p.id}/`) ? mId : `${p.id}/${mId}`;
@@ -527,7 +527,9 @@ providerRouter.put("/:id/strategy", (req, res) => {
527
527
  const { strategy, stickyLimit } = req.body;
528
528
  const strat = strategy || null;
529
529
  const sticky = stickyLimit != null ? Number(stickyLimit) : null;
530
- ProviderRepository.updateProviderStrategy(req.params.id, strat, sticky);
530
+ const reg = getRegistryProvider(req.params.id);
531
+ const targetId = reg ? reg.id : req.params.id;
532
+ ProviderRepository.updateProviderStrategy(targetId, strat, sticky);
531
533
  res.json({ success: true, strategy: strat, stickyLimit: sticky });
532
534
  });
533
535
  // GET all providers with account counts
@@ -558,22 +560,27 @@ providerRouter.post("/", (req, res) => {
558
560
  res.status(400).json({ error: "Name and baseUrl are required." });
559
561
  return;
560
562
  }
561
- const id = body.id || `prov_${crypto.randomUUID().slice(0, 8)}`;
563
+ const rawId = body.id || `prov_${crypto.randomUUID().slice(0, 8)}`;
564
+ const reg = getRegistryProvider(rawId);
565
+ const id = reg ? reg.id : rawId;
562
566
  const now = Date.now();
567
+ const existing = ProviderRepository.getProviderById(id);
563
568
  const provider = {
564
569
  id,
565
- name: body.name,
566
- baseUrl: body.baseUrl,
567
- format: body.format || "openai",
568
- isActive: body.isActive !== undefined ? Boolean(body.isActive) : true,
569
- priority: Number(body.priority) || 10,
570
- models: Array.isArray(body.models) ? body.models : [],
571
- customHeaders: body.customHeaders || {},
572
- proxyUrl: body.proxyUrl || undefined,
573
- thinkingMode: body.thinkingMode || "auto",
574
- strategy: body.strategy || null,
575
- stickyLimit: body.stickyLimit != null ? Number(body.stickyLimit) : 1,
576
- createdAt: body.createdAt || now,
570
+ name: body.name || existing?.name,
571
+ baseUrl: body.baseUrl || existing?.baseUrl,
572
+ format: body.format || existing?.format || "openai",
573
+ isActive: body.isActive !== undefined ? Boolean(body.isActive) : (existing ? existing.isActive : true),
574
+ priority: body.priority !== undefined && !isNaN(Number(body.priority))
575
+ ? Number(body.priority)
576
+ : (existing?.priority ?? 10),
577
+ models: Array.isArray(body.models) ? body.models : (existing?.models || []),
578
+ customHeaders: body.customHeaders !== undefined ? body.customHeaders : (existing?.customHeaders || {}),
579
+ proxyUrl: body.proxyUrl !== undefined ? (body.proxyUrl || undefined) : existing?.proxyUrl,
580
+ thinkingMode: body.thinkingMode || existing?.thinkingMode || "auto",
581
+ strategy: body.strategy !== undefined ? (body.strategy || null) : (existing?.strategy || null),
582
+ stickyLimit: body.stickyLimit !== undefined ? (body.stickyLimit != null ? Number(body.stickyLimit) : 1) : (existing?.stickyLimit ?? 1),
583
+ createdAt: existing?.createdAt || body.createdAt || now,
577
584
  updatedAt: now,
578
585
  };
579
586
  ProviderRepository.saveProvider(provider);
@@ -1,4 +1,5 @@
1
1
  import { MitmRepository } from "../../storage/repositories/mitmRepo.js";
2
+ import { SettingsRepository } from "../../storage/repositories/settingsRepo.js";
2
3
  import { getMapigateBaseUrl } from "../../shared/constants/cliTools.js";
3
4
  import { serverLifecycle } from "../lifecycle.js";
4
5
  export function getCurrentRouterTarget() {
@@ -20,7 +21,7 @@ export function getCurrentRouterTarget() {
20
21
  export async function testRouterTargetConnection(targetUrl, apiKey) {
21
22
  const current = MitmRepository.getRouterTarget();
22
23
  const urlToTest = (targetUrl !== undefined ? targetUrl : current.baseUrl) || "";
23
- const keyToUse = apiKey !== undefined ? apiKey : (current.apiKey || "");
24
+ let keyToUse = apiKey !== undefined ? apiKey : (current.apiKey || "");
24
25
  let defaultLocal = "";
25
26
  try {
26
27
  defaultLocal = getMapigateBaseUrl(serverLifecycle.getPort());
@@ -29,6 +30,18 @@ export async function testRouterTargetConnection(targetUrl, apiKey) {
29
30
  defaultLocal = getMapigateBaseUrl();
30
31
  }
31
32
  const cleanUrl = (urlToTest.trim() || defaultLocal).replace(/\/+$/, "");
33
+ if (!keyToUse) {
34
+ const isLocal = !urlToTest || urlToTest.includes("127.0.0.1") || urlToTest.includes("localhost") || urlToTest.includes("0.0.0.0");
35
+ if (isLocal) {
36
+ try {
37
+ const mitmKey = SettingsRepository.getOrCreateMitmApiKey();
38
+ if (mitmKey?.key && mitmKey.isActive) {
39
+ keyToUse = mitmKey.key;
40
+ }
41
+ }
42
+ catch { }
43
+ }
44
+ }
32
45
  const start = Date.now();
33
46
  try {
34
47
  const headers = {
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Model Identifier Normalization & Fuzzy Equivalence Utilities
3
+ *
4
+ * Normalizes model names and slugs so that dot-separated versions (e.g. "k3.1", "3.5", "4.5")
5
+ * and dash-separated versions (e.g. "k3-1", "3-5", "4-5") match interchangeably.
6
+ */
7
+ /**
8
+ * Normalizes a model identifier into a canonical comparison key:
9
+ * - Lowercases and trims
10
+ * - Strips leading "models/" prefix
11
+ * - Optionally strips vendor prefixes (e.g. "moonshotai/")
12
+ * - Replaces all dots (.) with dashes (-)
13
+ * - Replaces whitespace and underscores with dashes (-)
14
+ * - Collapses consecutive dashes and trims boundary dashes
15
+ *
16
+ * Examples:
17
+ * "kimi-k3.1-pro" -> "kimi-k3-1-pro"
18
+ * "kimi-k3-1-pro" -> "kimi-k3-1-pro"
19
+ * "Claude Sonnet 4.5" -> "claude-sonnet-4-5"
20
+ * "models/gpt-4.5" -> "gpt-4-5"
21
+ */
22
+ export function normalizeModelCompareKey(model, stripVendor = false) {
23
+ if (!model)
24
+ return "";
25
+ let clean = String(model).trim().toLowerCase();
26
+ clean = clean.replace(/^models\//, "");
27
+ if (stripVendor && clean.includes("/")) {
28
+ clean = clean.split("/").pop();
29
+ }
30
+ return clean
31
+ .replace(/\./g, "-")
32
+ .replace(/[\s_]+/g, "-")
33
+ .replace(/-+/g, "-")
34
+ .replace(/^-+|-+$/g, "");
35
+ }
36
+ /**
37
+ * Checks whether two model identifiers are equivalent, treating '.' and '-' as interchangeable.
38
+ * Also checks vendor-stripped base IDs when one has a vendor prefix and the other does not.
39
+ *
40
+ * Examples:
41
+ * areModelNamesEquivalent("kimi-k3.1-pro", "kimi-k3-1-pro") -> true
42
+ * areModelNamesEquivalent("moonshotai/kimi-k3.1-pro", "kimi-k3-1-pro") -> true
43
+ * areModelNamesEquivalent("Claude Sonnet 4.5", "claude-sonnet-4-5") -> true
44
+ */
45
+ export function areModelNamesEquivalent(modelA, modelB) {
46
+ if (!modelA || !modelB)
47
+ return false;
48
+ if (modelA.toLowerCase() === modelB.toLowerCase())
49
+ return true;
50
+ const keyA = normalizeModelCompareKey(modelA);
51
+ const keyB = normalizeModelCompareKey(modelB);
52
+ if (keyA === keyB)
53
+ return true;
54
+ // Only strip vendor if one side has a vendor prefix and the other does not
55
+ // (e.g. "moonshotai/kimi-k3.1-pro" vs "kimi-k3-1-pro")
56
+ const hasSlashA = modelA.includes("/");
57
+ const hasSlashB = modelB.includes("/");
58
+ if (hasSlashA !== hasSlashB) {
59
+ const baseKeyA = normalizeModelCompareKey(modelA, true);
60
+ const baseKeyB = normalizeModelCompareKey(modelB, true);
61
+ return baseKeyA === baseKeyB;
62
+ }
63
+ return false;
64
+ }
@@ -345,4 +345,18 @@ function initSchema(db) {
345
345
  CREATE INDEX IF NOT EXISTS idx_kv_store_scope ON kv_store(scope);
346
346
  CREATE INDEX IF NOT EXISTS idx_tool_mappings_tool ON tool_mappings(tool_id);
347
347
  `);
348
+ // Ensure legacy databases have strategy and sticky_limit columns on providers
349
+ try {
350
+ const cols = db.all("PRAGMA table_info(providers)");
351
+ const colNames = new Set(cols.map((c) => c.name));
352
+ if (!colNames.has("strategy")) {
353
+ db.exec("ALTER TABLE providers ADD COLUMN strategy TEXT");
354
+ }
355
+ if (!colNames.has("sticky_limit")) {
356
+ db.exec("ALTER TABLE providers ADD COLUMN sticky_limit INTEGER");
357
+ }
358
+ }
359
+ catch {
360
+ // Fail-open
361
+ }
348
362
  }
@@ -1,4 +1,5 @@
1
1
  import { getDatabase } from "../database.js";
2
+ import { normalizeModelCompareKey } from "../../shared/utils/modelUtils.js";
2
3
  export class AccountModelRepository {
3
4
  /**
4
5
  * Replaces all supported models for a specific account.
@@ -91,12 +92,13 @@ export class AccountModelRepository {
91
92
  }
92
93
  set.add(r.model_id.toLowerCase());
93
94
  }
95
+ const targetKey = normalizeModelCompareKey(cleanTarget);
94
96
  for (const id of accountIds) {
95
97
  const set = accountModelsMap.get(id);
96
98
  if (!set || set.size === 0) {
97
99
  unscanned.add(id);
98
100
  }
99
- else if (set.has(cleanTarget)) {
101
+ else if (set.has(cleanTarget) || Array.from(set).some((m) => normalizeModelCompareKey(m) === targetKey)) {
100
102
  supported.add(id);
101
103
  }
102
104
  else {
@@ -105,4 +107,15 @@ export class AccountModelRepository {
105
107
  }
106
108
  return { supported, unscanned, unsupported };
107
109
  }
110
+ /**
111
+ * Gets all distinct model IDs supported across multiple accounts.
112
+ */
113
+ static getModelsForAccounts(accountIds) {
114
+ if (!accountIds || accountIds.length === 0)
115
+ return [];
116
+ const db = getDatabase();
117
+ const placeholders = accountIds.map(() => "?").join(",");
118
+ const rows = db.all(`SELECT DISTINCT model_id FROM account_supported_models WHERE account_id IN (${placeholders}) ORDER BY model_id ASC`, ...accountIds);
119
+ return rows.map((r) => r.model_id);
120
+ }
108
121
  }
@@ -24,25 +24,33 @@ export class ProviderRepository {
24
24
  }
25
25
  static getProviderById(id) {
26
26
  const db = getDatabase();
27
- const r = db.get("SELECT * FROM providers WHERE id = ?", id);
28
- if (!r)
27
+ const cleanId = (id || "").trim();
28
+ if (!cleanId)
29
29
  return undefined;
30
- return {
31
- id: r.id,
32
- name: r.name,
33
- baseUrl: r.base_url,
34
- format: r.format,
35
- isActive: Boolean(r.is_active),
36
- priority: r.priority,
37
- models: JSON.parse(r.models || "[]"),
38
- customHeaders: JSON.parse(r.custom_headers || "{}"),
39
- proxyUrl: r.proxy_url || undefined,
40
- thinkingMode: r.thinking_mode || "auto",
41
- strategy: r.strategy || null,
42
- stickyLimit: r.sticky_limit != null ? Number(r.sticky_limit) : 1,
43
- createdAt: r.created_at,
44
- updatedAt: r.updated_at,
45
- };
30
+ const r = db.get("SELECT * FROM providers WHERE id = ?", cleanId);
31
+ if (r) {
32
+ return {
33
+ id: r.id,
34
+ name: r.name,
35
+ baseUrl: r.base_url,
36
+ format: r.format,
37
+ isActive: Boolean(r.is_active),
38
+ priority: r.priority,
39
+ models: JSON.parse(r.models || "[]"),
40
+ customHeaders: JSON.parse(r.custom_headers || "{}"),
41
+ proxyUrl: r.proxy_url || undefined,
42
+ thinkingMode: r.thinking_mode || "auto",
43
+ strategy: r.strategy || null,
44
+ stickyLimit: r.sticky_limit != null ? Number(r.sticky_limit) : 1,
45
+ createdAt: r.created_at,
46
+ updatedAt: r.updated_at,
47
+ };
48
+ }
49
+ const reg = getRegistryProvider(cleanId);
50
+ if (reg && reg.id !== cleanId) {
51
+ return this.getProviderById(reg.id);
52
+ }
53
+ return undefined;
46
54
  }
47
55
  static getProviderWithDefaults(id) {
48
56
  const reg = getRegistryProvider(id);
@@ -117,6 +125,8 @@ export class ProviderRepository {
117
125
  }
118
126
  static saveProvider(provider) {
119
127
  const db = getDatabase();
128
+ const reg = getRegistryProvider(provider.id);
129
+ const targetId = reg?.id || provider.id;
120
130
  db.run(`INSERT INTO providers (id, name, base_url, format, is_active, priority, models, custom_headers, proxy_url, thinking_mode, strategy, sticky_limit, created_at, updated_at)
121
131
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
122
132
  ON CONFLICT(id) DO UPDATE SET
@@ -131,7 +141,7 @@ export class ProviderRepository {
131
141
  thinking_mode = excluded.thinking_mode,
132
142
  strategy = excluded.strategy,
133
143
  sticky_limit = excluded.sticky_limit,
134
- updated_at = excluded.updated_at`, provider.id, provider.name, provider.baseUrl, provider.format, provider.isActive ? 1 : 0, provider.priority ?? 0, JSON.stringify(provider.models || []), JSON.stringify(provider.customHeaders || {}), provider.proxyUrl || null, provider.thinkingMode || "auto", provider.strategy || null, provider.stickyLimit != null ? provider.stickyLimit : 1, provider.createdAt ?? Date.now(), provider.updatedAt ?? Date.now());
144
+ updated_at = excluded.updated_at`, targetId, provider.name, provider.baseUrl, provider.format, provider.isActive ? 1 : 0, provider.priority ?? 0, JSON.stringify(provider.models || []), JSON.stringify(provider.customHeaders || {}), provider.proxyUrl || null, provider.thinkingMode || "auto", provider.strategy || null, provider.stickyLimit != null ? provider.stickyLimit : 1, provider.createdAt ?? Date.now(), provider.updatedAt ?? Date.now());
135
145
  }
136
146
  static ensureProviderExists(providerId, fallbackName) {
137
147
  const rawId = (providerId || "").trim();
@@ -204,8 +214,11 @@ export class ProviderRepository {
204
214
  if (!reg)
205
215
  continue;
206
216
  let changed = false;
207
- // Sync protocol format if registry has updated format in metadata.ts
208
- if (reg.format && prov.format !== reg.format) {
217
+ // Sync protocol format if registry has updated format in metadata.ts,
218
+ // UNLESS provider supports multiple formats (supportedFormats) and user's choice is one of them!
219
+ const isUserSupportedFormat = Array.isArray(reg.supportedFormats) &&
220
+ reg.supportedFormats.some((f) => (typeof f === "string" ? f : f.value) === prov.format);
221
+ if (reg.format && prov.format !== reg.format && !isUserSupportedFormat) {
209
222
  prov.format = reg.format;
210
223
  changed = true;
211
224
  }
@@ -227,7 +240,9 @@ export class ProviderRepository {
227
240
  const regKeys = Object.keys(regHeaders);
228
241
  const customKeys = Object.keys(prov.customHeaders);
229
242
  // If DB has the exact full set of legacy seeded default keys (and none was explicitly disabled)
230
- const isLegacyFullSnapshot = regKeys.length > 0 &&
243
+ // Note: Only apply full wipe if there are multiple default keys (regKeys.length > 1) and all match default keys,
244
+ // preventing single-header providers (like Anthropic) from wiping legitimate user customizations.
245
+ const isLegacyFullSnapshot = regKeys.length > 1 &&
231
246
  customKeys.length === regKeys.length &&
232
247
  customKeys.every((k) => k in regHeaders && prov.customHeaders[k] !== "");
233
248
  if (isLegacyFullSnapshot) {
@@ -260,24 +275,37 @@ export class ProviderRepository {
260
275
  }
261
276
  }
262
277
  static seedDefaultProviders() {
263
- const coreProviders = [
264
- "claude",
265
- "cursor",
266
- "codex",
267
- "kiro",
268
- "antigravity",
269
- "github",
270
- "openai",
271
- "deepseek",
272
- "gemini",
273
- ];
274
- for (const pId of coreProviders) {
275
- try {
276
- this.ensureProviderExists(pId);
278
+ const db = getDatabase();
279
+ let isSeeded = false;
280
+ try {
281
+ const seededRow = db.get("SELECT value FROM settings WHERE key = 'core_providers_seeded'");
282
+ isSeeded = Boolean(seededRow?.value);
283
+ }
284
+ catch { }
285
+ if (!isSeeded) {
286
+ const coreProviders = [
287
+ "claude",
288
+ "cursor",
289
+ "codex",
290
+ "kiro",
291
+ "antigravity",
292
+ "github",
293
+ "openai",
294
+ "deepseek",
295
+ "gemini",
296
+ ];
297
+ for (const pId of coreProviders) {
298
+ try {
299
+ this.ensureProviderExists(pId);
300
+ }
301
+ catch {
302
+ // Fail-open
303
+ }
277
304
  }
278
- catch {
279
- // Fail-open
305
+ try {
306
+ db.run("INSERT INTO settings (key, value) VALUES ('core_providers_seeded', '1') ON CONFLICT(key) DO NOTHING");
280
307
  }
308
+ catch { }
281
309
  }
282
310
  try {
283
311
  this.syncRegistryDefaults();