mapigate 0.5.141 → 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 (79) hide show
  1. package/README.md +8 -8
  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 +13 -6
  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/catalog/coarena/index.js +3 -0
  13. package/dist/providers/catalog/coarena/metadata.js +104 -0
  14. package/dist/providers/catalog/coarena/provider.js +91 -0
  15. package/dist/providers/catalog/coarena/quota.js +119 -0
  16. package/dist/providers/generated/chunks/chunk1.js +2 -2
  17. package/dist/providers/generated/chunks/chunk2.js +2 -2
  18. package/dist/providers/generated/chunks/chunk3.js +2 -2
  19. package/dist/providers/generated/chunks/chunk4.js +2 -0
  20. package/dist/providers/generated/runtime/chunk1.js +2 -2
  21. package/dist/providers/generated/runtime/chunk2.js +2 -2
  22. package/dist/providers/generated/runtime/chunk3.js +2 -2
  23. package/dist/providers/generated/runtime/chunk4.js +2 -0
  24. package/dist/providers/runtime/antigravity/executor.js +1 -1
  25. package/dist/providers/runtime/antigravity/metadata.js +2 -2
  26. package/dist/providers/runtime/antigravity/models.js +2 -0
  27. package/dist/providers/runtime/antigravity/provider.js +2 -2
  28. package/dist/providers/runtime/antigravity/routes.js +2 -2
  29. package/dist/providers/runtime/antigravity/types.js +4 -2
  30. package/dist/providers/runtime/gemini/metadata.js +1 -1
  31. package/dist/providers/runtime/gemini/provider.js +2 -2
  32. package/dist/providers/runtime/gemini-cli/provider.js +2 -2
  33. package/dist/providers/runtime/trae/index.js +1 -0
  34. package/dist/providers/runtime/trae/metadata.js +1 -0
  35. package/dist/providers/runtime/trae/provider.js +7 -0
  36. package/dist/providers/runtime/trae/quota.js +99 -0
  37. package/dist/providers/runtime/zed/metadata.js +1 -1
  38. package/dist/providers/runtime/zed/models.js +68 -8
  39. package/dist/providers/runtime/zed/provider.js +60 -15
  40. package/dist/providers/runtime/zed/quota.js +69 -12
  41. package/dist/providers/runtime/zed/routes.js +7 -0
  42. package/dist/server/lifecycle.js +2 -2
  43. package/dist/server/proxy/executorHelpers.js +52 -4
  44. package/dist/server/routes/apiModels.js +141 -8
  45. package/dist/server/routes/apiProviders.js +21 -14
  46. package/dist/server/routes/mitmRouterTargetHelper.js +14 -1
  47. package/dist/shared/constants/quotaOrder.js +5 -0
  48. package/dist/shared/utils/modelUtils.js +64 -0
  49. package/dist/storage/database.js +14 -0
  50. package/dist/storage/repositories/accountModelRepo.js +14 -1
  51. package/dist/storage/repositories/providerRepo.js +66 -38
  52. package/dist/storage/repositories/settingsRepo.js +41 -0
  53. package/dist/storage/repositories/toolMappingRepo.js +29 -0
  54. package/dist/web/assets/{CliToolsTab-rKSWLJC3.js → CliToolsTab-D_MUwimj.js} +1 -1
  55. package/dist/web/assets/CombosTab-EWUYC3TU.js +1 -0
  56. package/dist/web/assets/{ConfirmModal-OWeauwYv.js → ConfirmModal-CMfDss7P.js} +1 -1
  57. package/dist/web/assets/{ConsoleLogTab-rZe8zCb_.js → ConsoleLogTab-BSMXSYrR.js} +1 -1
  58. package/dist/web/assets/{EditAccountModal-CAg-yIOn.js → EditAccountModal-OrvqLLBP.js} +1 -1
  59. package/dist/web/assets/{EndpointTab-B-Jb4wAG.js → EndpointTab-BwtzqXUN.js} +1 -1
  60. package/dist/web/assets/MitmTab-C7g7GUXW.js +14 -0
  61. package/dist/web/assets/ModelAutocompleteInput-DEb_clZC.js +1 -0
  62. package/dist/web/assets/ProviderDetailPage-BIfOQupC.js +6 -0
  63. package/dist/web/assets/{ProvidersTab-yzmb4w0D.js → ProvidersTab-CwJo_EUX.js} +1 -1
  64. package/dist/web/assets/QuotaTab-PFvP6yAb.js +1 -0
  65. package/dist/web/assets/{SettingsTab-LkByv4Sg.js → SettingsTab-DwAbjIW3.js} +1 -1
  66. package/dist/web/assets/{UsageTab-Hr8XPZD4.js → UsageTab-85tTb2_C.js} +1 -1
  67. package/dist/web/assets/{index-CKuvklEr.js → index-CWkEEbms.js} +2 -2
  68. package/dist/web/assets/metadataRegistry-FuJXbCt4.js +1 -0
  69. package/dist/web/assets/providers/coarena/icon.png +0 -0
  70. package/dist/web/assets/providers/coarena/icon.svg +3 -0
  71. package/dist/web/assets/{providersData-DS1-ETBi.js → providersData-Y57rBt5o.js} +1 -1
  72. package/dist/web/index.html +1 -1
  73. package/package.json +1 -1
  74. package/dist/web/assets/CombosTab-D1_cfssh.js +0 -1
  75. package/dist/web/assets/MitmTab-5dKeNi4T.js +0 -14
  76. package/dist/web/assets/ModelAutocompleteInput-CoinzdsW.js +0 -1
  77. package/dist/web/assets/ProviderDetailPage-D-fodBhz.js +0 -6
  78. package/dist/web/assets/QuotaTab-BXevQzen.js +0 -1
  79. package/dist/web/assets/metadataRegistry-NuDSSkP9.js +0 -1
@@ -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 = {
@@ -132,6 +132,11 @@ const FALLBACK_QUOTA_ORDER_MAP = {
132
132
  "Monthly Tokens",
133
133
  "Weekly Quota",
134
134
  ],
135
+ trae: [
136
+ "Dollar Usage",
137
+ "Autocomplete",
138
+ "Fast Requests",
139
+ ],
135
140
  };
136
141
  /**
137
142
  * Proxy that pulls quotaOrder dynamically from provider metadata in metadataRegistry,
@@ -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();
@@ -164,6 +164,8 @@ export class SettingsRepository {
164
164
  return updated;
165
165
  }
166
166
  // --- Client Gateway API Keys Management ---
167
+ static MITM_KEY_ID = "key_mitm_default";
168
+ static MITM_KEY_NAME = "MITM Interceptor";
167
169
  static getGatewayApiKeys() {
168
170
  const raw = this.getSetting("gatewayApiKeys");
169
171
  if (!Array.isArray(raw)) {
@@ -176,8 +178,39 @@ export class SettingsRepository {
176
178
  isActive: k.isActive !== false,
177
179
  createdAt: Number(k.createdAt) || Date.now(),
178
180
  lastUsedAt: k.lastUsedAt ? Number(k.lastUsedAt) : undefined,
181
+ isSystem: Boolean(k.isSystem || k.id === this.MITM_KEY_ID),
179
182
  }));
180
183
  }
184
+ static getOrCreateMitmApiKey() {
185
+ const keys = this.getGatewayApiKeys();
186
+ const existing = keys.find((k) => k.id === this.MITM_KEY_ID || k.name === this.MITM_KEY_NAME);
187
+ if (existing) {
188
+ let needsSave = false;
189
+ if (!existing.isActive) {
190
+ existing.isActive = true;
191
+ needsSave = true;
192
+ }
193
+ if (!existing.isSystem) {
194
+ existing.isSystem = true;
195
+ needsSave = true;
196
+ }
197
+ if (needsSave) {
198
+ this.setSetting("gatewayApiKeys", keys);
199
+ }
200
+ return existing;
201
+ }
202
+ const newKey = {
203
+ id: this.MITM_KEY_ID,
204
+ key: "sk-rt-" + randomBytes(24).toString("hex"),
205
+ name: this.MITM_KEY_NAME,
206
+ isActive: true,
207
+ createdAt: Date.now(),
208
+ isSystem: true,
209
+ };
210
+ keys.push(newKey);
211
+ this.setSetting("gatewayApiKeys", keys);
212
+ return newKey;
213
+ }
181
214
  static createGatewayApiKey(name) {
182
215
  const keys = this.getGatewayApiKeys();
183
216
  const id = "key_" + randomBytes(8).toString("hex");
@@ -195,6 +228,10 @@ export class SettingsRepository {
195
228
  }
196
229
  static deleteGatewayApiKey(id) {
197
230
  const keys = this.getGatewayApiKeys();
231
+ const target = keys.find((k) => k.id === id || k.key === id);
232
+ if (target?.isSystem || target?.id === this.MITM_KEY_ID) {
233
+ return false;
234
+ }
198
235
  const initialLen = keys.length;
199
236
  const filtered = keys.filter((k) => k.id !== id && k.key !== id);
200
237
  if (filtered.length !== initialLen) {
@@ -208,6 +245,10 @@ export class SettingsRepository {
208
245
  const index = keys.findIndex((k) => k.id === id || k.key === id);
209
246
  if (index === -1)
210
247
  return undefined;
248
+ if (keys[index].isSystem || keys[index].id === this.MITM_KEY_ID) {
249
+ // System keys remain active to ensure internal subsystems stay operational
250
+ return keys[index];
251
+ }
211
252
  keys[index].isActive = !keys[index].isActive;
212
253
  this.setSetting("gatewayApiKeys", keys);
213
254
  return keys[index];