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.
- package/README.md +7 -1
- package/dist/core/adapters/anthropic/streamAnthropicToOpenAi.js +94 -13
- package/dist/core/adapters/anthropic/types.js +3 -1
- package/dist/core/adapters/anthropicAdapter.js +2 -2
- package/dist/core/adapters/helpers/toolCallRescue.js +224 -10
- package/dist/core/adapters/responsesAdapter.js +56 -3
- package/dist/core/resilience/index.js +5 -0
- package/dist/core/router/earliestResetComparator.js +14 -4
- package/dist/core/router/loadBalancer.js +27 -3
- package/dist/core/scanner/modelScanner.js +8 -1
- package/dist/core/scanner/payloadExtractor.js +8 -3
- package/dist/core/scanner/urlResolver.js +10 -2
- package/dist/core/usage/quotaService.js +3 -1
- package/dist/providers/catalog/xiaomi-tokenplan/metadata.js +6 -1
- package/dist/providers/catalog/xiaomi-tokenplan/provider.js +71 -1
- package/dist/providers/core/base/baseProvider.js +1 -0
- package/dist/providers/runtime/antigravity/executor.js +1 -1
- package/dist/providers/runtime/antigravity/metadata.js +4 -3
- package/dist/providers/runtime/antigravity/provider.js +2 -2
- package/dist/providers/runtime/antigravity/quota.js +9 -3
- package/dist/providers/runtime/antigravity/routes.js +2 -2
- package/dist/providers/runtime/antigravity/types.js +10 -2
- package/dist/providers/runtime/antigravity/weekly.js +1 -1
- package/dist/providers/runtime/codex/models.js +1 -6
- package/dist/providers/runtime/codex/routes.js +40 -24
- package/dist/providers/runtime/cursor/cursorChecksum.js +80 -0
- package/dist/providers/runtime/cursor/cursorModels.js +194 -0
- package/dist/providers/runtime/cursor/cursorProtobuf.js +193 -0
- package/dist/providers/runtime/cursor/cursorSession.js +118 -0
- package/dist/providers/runtime/cursor/cursorStreamer.js +250 -0
- package/dist/providers/runtime/cursor/cursorWire.js +243 -0
- package/dist/providers/runtime/cursor/executor.js +129 -0
- package/dist/providers/runtime/cursor/index.js +6 -0
- package/dist/providers/runtime/cursor/provider.js +34 -10
- package/dist/providers/runtime/cursor-api/auth.js +47 -102
- package/dist/providers/runtime/cursor-api/metadata.js +4 -4
- package/dist/providers/runtime/cursor-api/provider.js +58 -21
- package/dist/providers/runtime/gemini-cli/provider.js +2 -2
- package/dist/providers/runtime/kiro/executor.js +4 -2
- package/dist/providers/runtime/kiro/metadata.js +2 -2
- package/dist/providers/runtime/mimo/metadata.js +1 -0
- package/dist/providers/runtime/mimo/provider.js +56 -0
- package/dist/server/index.js +10 -1
- package/dist/server/proxy/executorHelpers.js +12 -2
- package/dist/server/proxy/singleModelExecutor.js +2 -0
- package/dist/server/proxy/streaming/sseStreamer.js +7 -2
- package/dist/server/routes/apiModels.js +60 -0
- package/dist/server/routes/apiProviders.js +50 -9
- package/dist/server/routes/apiServer.js +110 -0
- package/dist/server/routes/apiSettings.js +35 -7
- package/dist/server/routes/apiUsage.js +5 -3
- package/dist/shared/constants/quotaOrder.js +1 -0
- package/dist/storage/database.js +31 -0
- package/dist/storage/repositories/accountModelRepo.js +108 -0
- package/dist/storage/repositories/logRepo.js +71 -10
- package/dist/storage/repositories/providerRepo.js +69 -59
- package/dist/storage/repositories/requestDetailsRepo.js +8 -0
- package/dist/storage/repositories/settingsRepo.js +17 -0
- package/dist/storage/repositories/usageRepo.js +228 -72
- package/dist/web/assets/{CliToolsTab-DE48Y4QZ.js → CliToolsTab-BzhczMaa.js} +1 -1
- package/dist/web/assets/{CombosTab-dsZhV95u.js → CombosTab-Cz8KYH4M.js} +1 -1
- package/dist/web/assets/{ConfirmModal-BTwfpfgO.js → ConfirmModal-BU1PPpF0.js} +1 -1
- package/dist/web/assets/{ConsoleLogTab-DtUTPoi7.js → ConsoleLogTab-CFvXde1l.js} +1 -1
- package/dist/web/assets/EditAccountModal-CS2TR4bt.js +1 -0
- package/dist/web/assets/{EndpointTab-Ya1KYJSp.js → EndpointTab-DZCRpAbh.js} +1 -1
- package/dist/web/assets/{MitmTab-Bl-E-IDY.js → MitmTab-CTfwqdey.js} +1 -1
- package/dist/web/assets/{ModelAutocompleteInput-COe36ge6.js → ModelAutocompleteInput-CAi2R2s9.js} +1 -1
- package/dist/web/assets/ProviderDetailPage-Dv2LpFj_.js +6 -0
- package/dist/web/assets/{ProvidersTab-COC-cJXg.js → ProvidersTab-DwHMHdPu.js} +1 -1
- package/dist/web/assets/QuotaTab-DS1y9gGp.js +1 -0
- package/dist/web/assets/SettingsTab-DULcs9O4.js +1 -0
- package/dist/web/assets/UsageTab-DKBaBAeT.js +1 -0
- package/dist/web/assets/index-BisuNW2y.css +1 -0
- package/dist/web/assets/index-DPdrZakW.js +2 -0
- package/dist/web/assets/metadataRegistry-7DDoxaR3.js +1 -0
- package/dist/web/assets/{providersData-DRVJJUB4.js → providersData-Br5RocnM.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/web/assets/EditAccountModal-65P5phzh.js +0 -1
- package/dist/web/assets/ProviderDetailPage-BnQ7kK6s.js +0 -6
- package/dist/web/assets/QuotaTab-DkRBaW79.js +0 -1
- package/dist/web/assets/SettingsTab-DPcPmPUd.js +0 -1
- package/dist/web/assets/UsageTab-Danjts5j.js +0 -1
- package/dist/web/assets/index-CeC7GeyM.js +0 -2
- package/dist/web/assets/index-YgSWkEbZ.css +0 -1
- package/dist/web/assets/metadataRegistry-Dxrq24qH.js +0 -1
|
@@ -6,6 +6,7 @@ import { COMMUNITY_PROVIDERS_CATALOG, getCommunityCatalogProvider, } from "../..
|
|
|
6
6
|
import { scanProviderModels } from "../../core/scanner/modelScanner.js";
|
|
7
7
|
import { testProviderConnection, testMultipleConnections } from "../../core/scanner/connectionTester.js";
|
|
8
8
|
import { maskSensitivePsd } from "../../shared/utils/security.js";
|
|
9
|
+
import { AccountModelRepository } from "../../storage/repositories/accountModelRepo.js";
|
|
9
10
|
import crypto from "node:crypto";
|
|
10
11
|
export const providerRouter = Router();
|
|
11
12
|
// GET community providers catalog (P3 on-demand catalog)
|
|
@@ -392,6 +393,28 @@ providerRouter.post("/:id/scan-models", async (req, res) => {
|
|
|
392
393
|
res.status(isAuth ? 401 : 400).json(result);
|
|
393
394
|
return;
|
|
394
395
|
}
|
|
396
|
+
// Automatically persist discovered models to provider in SQLite so they survive reloads
|
|
397
|
+
if (result.models && result.models.length > 0) {
|
|
398
|
+
try {
|
|
399
|
+
const prov = ProviderRepository.ensureProviderExists(providerId);
|
|
400
|
+
const existingSet = new Set(Array.isArray(prov.models) ? prov.models : []);
|
|
401
|
+
let hasNew = false;
|
|
402
|
+
for (const m of result.models) {
|
|
403
|
+
if (!existingSet.has(m.id)) {
|
|
404
|
+
existingSet.add(m.id);
|
|
405
|
+
hasNew = true;
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
if (hasNew) {
|
|
409
|
+
prov.models = Array.from(existingSet);
|
|
410
|
+
prov.updatedAt = Date.now();
|
|
411
|
+
ProviderRepository.saveProvider(prov);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
catch {
|
|
415
|
+
// Fail-open
|
|
416
|
+
}
|
|
417
|
+
}
|
|
395
418
|
res.json(result);
|
|
396
419
|
}
|
|
397
420
|
catch (err) {
|
|
@@ -410,15 +433,20 @@ providerRouter.get("/:id", (req, res) => {
|
|
|
410
433
|
res.json({
|
|
411
434
|
...provider,
|
|
412
435
|
accountsCount: accounts.length,
|
|
413
|
-
accounts: accounts.map((a) =>
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
436
|
+
accounts: accounts.map((a) => {
|
|
437
|
+
const modelsSet = AccountModelRepository.getAccountModels(a.id);
|
|
438
|
+
return {
|
|
439
|
+
id: a.id,
|
|
440
|
+
name: a.name,
|
|
441
|
+
tag: a.tag || a.providerSpecificData?.tag,
|
|
442
|
+
supportedModelsCount: modelsSet ? modelsSet.size : null,
|
|
443
|
+
isActive: a.isActive,
|
|
444
|
+
rateLimitHits: a.rateLimitHits,
|
|
445
|
+
lastUsedAt: a.lastUsedAt,
|
|
446
|
+
sortOrder: a.sortOrder,
|
|
447
|
+
providerSpecificData: maskSensitivePsd(a.providerSpecificData),
|
|
448
|
+
};
|
|
449
|
+
}),
|
|
422
450
|
});
|
|
423
451
|
});
|
|
424
452
|
// PUT reorder accounts
|
|
@@ -456,6 +484,10 @@ providerRouter.put("/:id/accounts/:accountId", (req, res) => {
|
|
|
456
484
|
isActive,
|
|
457
485
|
providerSpecificData: mergedPsd,
|
|
458
486
|
});
|
|
487
|
+
// If API key was explicitly updated with a new non-empty key, clear cached models so account is fresh
|
|
488
|
+
if (apiKey !== undefined && apiKey !== existing.rawApiKey) {
|
|
489
|
+
AccountModelRepository.clearAccountModels(accountId);
|
|
490
|
+
}
|
|
459
491
|
const updated = ProviderRepository.getAccountById(accountId);
|
|
460
492
|
res.json({
|
|
461
493
|
success: true,
|
|
@@ -481,6 +513,15 @@ providerRouter.delete("/:id/accounts/:accountId", (req, res) => {
|
|
|
481
513
|
ProviderRepository.deleteAccount(req.params.accountId);
|
|
482
514
|
res.json({ success: true });
|
|
483
515
|
});
|
|
516
|
+
// GET single account supported models
|
|
517
|
+
providerRouter.get("/:id/accounts/:accountId/models", (req, res) => {
|
|
518
|
+
const modelsSet = AccountModelRepository.getAccountModels(req.params.accountId);
|
|
519
|
+
if (!modelsSet) {
|
|
520
|
+
res.json({ scanned: false, models: [] });
|
|
521
|
+
return;
|
|
522
|
+
}
|
|
523
|
+
res.json({ scanned: true, models: Array.from(modelsSet).sort() });
|
|
524
|
+
});
|
|
484
525
|
// PUT strategy and sticky limit
|
|
485
526
|
providerRouter.put("/:id/strategy", (req, res) => {
|
|
486
527
|
const { strategy, stickyLimit } = req.body;
|
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import { Router } from "express";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
2
3
|
import { serverLifecycle } from "../lifecycle.js";
|
|
4
|
+
import { checkForUpdates } from "../../shared/utils/versionChecker.js";
|
|
5
|
+
import { APP_NAME, APP_VERSION } from "../../shared/constants/index.js";
|
|
3
6
|
export const serverRouter = Router();
|
|
7
|
+
let isUpgradeInProgress = false;
|
|
4
8
|
export const handleShutdownRequest = async (_req, res) => {
|
|
5
9
|
res.json({
|
|
6
10
|
success: true,
|
|
@@ -27,5 +31,111 @@ export const handleRestartRequest = async (_req, res) => {
|
|
|
27
31
|
console.error("[Lifecycle] Server restart error:", err);
|
|
28
32
|
});
|
|
29
33
|
};
|
|
34
|
+
export const handleUpgradeRequest = async (req, res) => {
|
|
35
|
+
if (isUpgradeInProgress) {
|
|
36
|
+
res.status(409).json({
|
|
37
|
+
success: false,
|
|
38
|
+
error: "An upgrade is already in progress.",
|
|
39
|
+
});
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
isUpgradeInProgress = true;
|
|
43
|
+
const isTest = process.env.NODE_ENV === "test" ||
|
|
44
|
+
Boolean(process.env.NODE_TEST_CONTEXT) ||
|
|
45
|
+
process.argv.some((arg) => arg.includes("test"));
|
|
46
|
+
try {
|
|
47
|
+
if (isTest && req.body?.mockTest) {
|
|
48
|
+
isUpgradeInProgress = false;
|
|
49
|
+
res.json({
|
|
50
|
+
success: true,
|
|
51
|
+
message: "Test upgrade completed successfully.",
|
|
52
|
+
fromVersion: APP_VERSION,
|
|
53
|
+
toVersion: req.body.mockVersion || "99.9.9",
|
|
54
|
+
});
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
const updateInfo = await checkForUpdates(true);
|
|
58
|
+
if (!updateInfo.latestVersion) {
|
|
59
|
+
isUpgradeInProgress = false;
|
|
60
|
+
res.status(502).json({
|
|
61
|
+
success: false,
|
|
62
|
+
error: "Could not fetch latest version from npm registry. Please check your internet connection.",
|
|
63
|
+
});
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
if (!updateInfo.hasUpdate && !req.body?.force) {
|
|
67
|
+
isUpgradeInProgress = false;
|
|
68
|
+
res.json({
|
|
69
|
+
success: true,
|
|
70
|
+
message: `You are already running the latest version of ${APP_NAME} (v${APP_VERSION}).`,
|
|
71
|
+
currentVersion: APP_VERSION,
|
|
72
|
+
latestVersion: updateInfo.latestVersion,
|
|
73
|
+
alreadyLatest: true,
|
|
74
|
+
});
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
const target = `mapigate@${updateInfo.latestVersion}`;
|
|
78
|
+
const isWindows = process.platform === "win32";
|
|
79
|
+
const npmCmd = isWindows ? "npm.cmd" : "npm";
|
|
80
|
+
await new Promise((resolve, reject) => {
|
|
81
|
+
let stderr = "";
|
|
82
|
+
let stdout = "";
|
|
83
|
+
const child = spawn(npmCmd, ["install", "-g", target], {
|
|
84
|
+
shell: isWindows,
|
|
85
|
+
windowsHide: true,
|
|
86
|
+
});
|
|
87
|
+
child.stdout?.on("data", (data) => {
|
|
88
|
+
stdout += data.toString();
|
|
89
|
+
if (stdout.length > 4000)
|
|
90
|
+
stdout = stdout.slice(-4000);
|
|
91
|
+
});
|
|
92
|
+
child.stderr?.on("data", (data) => {
|
|
93
|
+
stderr += data.toString();
|
|
94
|
+
if (stderr.length > 4000)
|
|
95
|
+
stderr = stderr.slice(-4000);
|
|
96
|
+
});
|
|
97
|
+
const timer = setTimeout(() => {
|
|
98
|
+
try {
|
|
99
|
+
child.kill();
|
|
100
|
+
}
|
|
101
|
+
catch { }
|
|
102
|
+
reject(new Error("Upgrade timed out after 180 seconds."));
|
|
103
|
+
}, 180000);
|
|
104
|
+
child.on("close", (code) => {
|
|
105
|
+
clearTimeout(timer);
|
|
106
|
+
if (code === 0) {
|
|
107
|
+
resolve();
|
|
108
|
+
}
|
|
109
|
+
else {
|
|
110
|
+
const detail = (stderr || stdout).trim();
|
|
111
|
+
reject(new Error(`Upgrade failed with exit code ${code}${detail ? `: ${detail}` : ""}`));
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
child.on("error", (err) => {
|
|
115
|
+
clearTimeout(timer);
|
|
116
|
+
reject(err);
|
|
117
|
+
});
|
|
118
|
+
});
|
|
119
|
+
isUpgradeInProgress = false;
|
|
120
|
+
res.json({
|
|
121
|
+
success: true,
|
|
122
|
+
message: `Successfully upgraded ${APP_NAME} to v${updateInfo.latestVersion}! Server is restarting...`,
|
|
123
|
+
fromVersion: APP_VERSION,
|
|
124
|
+
toVersion: updateInfo.latestVersion,
|
|
125
|
+
});
|
|
126
|
+
// Gracefully restart the server to load newly installed package
|
|
127
|
+
serverLifecycle.restartServer({ delayMs: 400, exitProcess: !isTest }).catch((err) => {
|
|
128
|
+
console.error("[Lifecycle] Server restart after upgrade error:", err);
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
catch (err) {
|
|
132
|
+
isUpgradeInProgress = false;
|
|
133
|
+
res.status(500).json({
|
|
134
|
+
success: false,
|
|
135
|
+
error: err?.message || "Failed to upgrade Mapigate.",
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
};
|
|
30
139
|
serverRouter.post("/shutdown", handleShutdownRequest);
|
|
31
140
|
serverRouter.post("/restart", handleRestartRequest);
|
|
141
|
+
serverRouter.post("/upgrade", handleUpgradeRequest);
|
|
@@ -52,6 +52,7 @@ settingsRouter.get("/logging", (_req, res) => {
|
|
|
52
52
|
res.json({
|
|
53
53
|
logLevel: logger.getLevelName(),
|
|
54
54
|
availableLevels: ["trace", "debug", "info", "warn", "error"],
|
|
55
|
+
logRetentionDays: SettingsRepository.getLogRetentionDays(),
|
|
55
56
|
});
|
|
56
57
|
}
|
|
57
58
|
catch (error) {
|
|
@@ -61,15 +62,24 @@ settingsRouter.get("/logging", (_req, res) => {
|
|
|
61
62
|
// PUT /api/settings/logging - Update logging settings
|
|
62
63
|
settingsRouter.put("/logging", (req, res) => {
|
|
63
64
|
try {
|
|
64
|
-
const { logLevel } = req.body || {};
|
|
65
|
+
const { logLevel, logRetentionDays } = req.body || {};
|
|
66
|
+
let updatedLevel = logger.getLevelName();
|
|
65
67
|
if (logLevel && typeof logLevel === "string") {
|
|
66
68
|
const parsed = parseLogLevel(logLevel);
|
|
67
69
|
logger.setLevel(parsed);
|
|
68
|
-
|
|
69
|
-
SettingsRepository.setLogLevel(
|
|
70
|
-
return res.json({ logLevel: name });
|
|
70
|
+
updatedLevel = logger.getLevelName();
|
|
71
|
+
SettingsRepository.setLogLevel(updatedLevel);
|
|
71
72
|
}
|
|
72
|
-
|
|
73
|
+
if (logRetentionDays !== undefined) {
|
|
74
|
+
const days = Number(logRetentionDays);
|
|
75
|
+
if (!isNaN(days) && days >= 0) {
|
|
76
|
+
SettingsRepository.setLogRetentionDays(days);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return res.json({
|
|
80
|
+
logLevel: updatedLevel,
|
|
81
|
+
logRetentionDays: SettingsRepository.getLogRetentionDays(),
|
|
82
|
+
});
|
|
73
83
|
}
|
|
74
84
|
catch (error) {
|
|
75
85
|
res.status(400).json({ error: error.message || "Failed to update logging settings" });
|
|
@@ -222,10 +232,12 @@ settingsRouter.get("/", (_req, res) => {
|
|
|
222
232
|
const capacityAdapter = SettingsRepository.getCapacityAdapterSettings();
|
|
223
233
|
const endpoint = SettingsRepository.getEndpointSettings();
|
|
224
234
|
const tokenSaver = SettingsRepository.getTokenSaverSettings();
|
|
235
|
+
const logRetentionDays = SettingsRepository.getLogRetentionDays();
|
|
225
236
|
res.json({
|
|
226
237
|
capacityAdapter,
|
|
227
238
|
endpoint,
|
|
228
239
|
tokenSaver,
|
|
240
|
+
logRetentionDays,
|
|
229
241
|
});
|
|
230
242
|
}
|
|
231
243
|
catch (error) {
|
|
@@ -261,8 +273,14 @@ settingsRouter.patch("/", (req, res) => {
|
|
|
261
273
|
if (body.tokenSaver) {
|
|
262
274
|
SettingsRepository.setTokenSaverSettings(body.tokenSaver);
|
|
263
275
|
}
|
|
276
|
+
if (body.logRetentionDays !== undefined) {
|
|
277
|
+
const days = Number(body.logRetentionDays);
|
|
278
|
+
if (!isNaN(days) && days >= 0) {
|
|
279
|
+
SettingsRepository.setLogRetentionDays(days);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
264
282
|
for (const [key, val] of Object.entries(body)) {
|
|
265
|
-
if (key !== "capacityAdapter" && key !== "endpoint" && key !== "tokenSaver") {
|
|
283
|
+
if (key !== "capacityAdapter" && key !== "endpoint" && key !== "tokenSaver" && key !== "logRetentionDays") {
|
|
266
284
|
if (!isAllowedSettingKey(key)) {
|
|
267
285
|
continue;
|
|
268
286
|
}
|
|
@@ -272,10 +290,12 @@ settingsRouter.patch("/", (req, res) => {
|
|
|
272
290
|
const capacityAdapter = SettingsRepository.getCapacityAdapterSettings();
|
|
273
291
|
const endpoint = SettingsRepository.getEndpointSettings();
|
|
274
292
|
const tokenSaver = SettingsRepository.getTokenSaverSettings();
|
|
293
|
+
const logRetentionDays = SettingsRepository.getLogRetentionDays();
|
|
275
294
|
res.json({
|
|
276
295
|
capacityAdapter,
|
|
277
296
|
endpoint,
|
|
278
297
|
tokenSaver,
|
|
298
|
+
logRetentionDays,
|
|
279
299
|
});
|
|
280
300
|
}
|
|
281
301
|
catch (error) {
|
|
@@ -295,8 +315,14 @@ settingsRouter.put("/", (req, res) => {
|
|
|
295
315
|
if (body.tokenSaver) {
|
|
296
316
|
SettingsRepository.setTokenSaverSettings(body.tokenSaver);
|
|
297
317
|
}
|
|
318
|
+
if (body.logRetentionDays !== undefined) {
|
|
319
|
+
const days = Number(body.logRetentionDays);
|
|
320
|
+
if (!isNaN(days) && days >= 0) {
|
|
321
|
+
SettingsRepository.setLogRetentionDays(days);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
298
324
|
for (const [key, val] of Object.entries(body)) {
|
|
299
|
-
if (key !== "capacityAdapter" && key !== "endpoint" && key !== "tokenSaver") {
|
|
325
|
+
if (key !== "capacityAdapter" && key !== "endpoint" && key !== "tokenSaver" && key !== "logRetentionDays") {
|
|
300
326
|
if (!isAllowedSettingKey(key)) {
|
|
301
327
|
continue;
|
|
302
328
|
}
|
|
@@ -306,10 +332,12 @@ settingsRouter.put("/", (req, res) => {
|
|
|
306
332
|
const capacityAdapter = SettingsRepository.getCapacityAdapterSettings();
|
|
307
333
|
const endpoint = SettingsRepository.getEndpointSettings();
|
|
308
334
|
const tokenSaver = SettingsRepository.getTokenSaverSettings();
|
|
335
|
+
const logRetentionDays = SettingsRepository.getLogRetentionDays();
|
|
309
336
|
res.json({
|
|
310
337
|
capacityAdapter,
|
|
311
338
|
endpoint,
|
|
312
339
|
tokenSaver,
|
|
340
|
+
logRetentionDays,
|
|
313
341
|
});
|
|
314
342
|
}
|
|
315
343
|
catch (error) {
|
|
@@ -2,7 +2,7 @@ import { Router } from "express";
|
|
|
2
2
|
import { UsageRepository, usageEventEmitter } from "../../storage/repositories/usageRepo.js";
|
|
3
3
|
import { RequestDetailsRepository } from "../../storage/repositories/requestDetailsRepo.js";
|
|
4
4
|
export const usageRouter = Router();
|
|
5
|
-
const VALID_PERIODS = new Set(["today", "24h", "7d", "30d", "60d", "all"]);
|
|
5
|
+
const VALID_PERIODS = new Set(["today", "24h", "7d", "30d", "60d", "90d", "all"]);
|
|
6
6
|
// GET /api/usage/stats?period=today|24h|7d|30d|60d|all
|
|
7
7
|
usageRouter.get("/stats", (req, res) => {
|
|
8
8
|
try {
|
|
@@ -94,6 +94,8 @@ usageRouter.get("/stream", (req, res) => {
|
|
|
94
94
|
res.setHeader("Cache-Control", "no-cache");
|
|
95
95
|
res.setHeader("Connection", "keep-alive");
|
|
96
96
|
res.setHeader("X-Accel-Buffering", "no");
|
|
97
|
+
const rawPeriod = String(req.query.period || "7d").toLowerCase();
|
|
98
|
+
const period = VALID_PERIODS.has(rawPeriod) ? rawPeriod : "7d";
|
|
97
99
|
let isClosed = false;
|
|
98
100
|
let cachedStats = null;
|
|
99
101
|
const sendEvent = (event, data) => {
|
|
@@ -110,7 +112,7 @@ usageRouter.get("/stream", (req, res) => {
|
|
|
110
112
|
if (isClosed)
|
|
111
113
|
return;
|
|
112
114
|
try {
|
|
113
|
-
const stats = UsageRepository.getUsageStats(
|
|
115
|
+
const stats = UsageRepository.getUsageStats(period);
|
|
114
116
|
cachedStats = stats;
|
|
115
117
|
sendEvent("stats", stats);
|
|
116
118
|
}
|
|
@@ -127,7 +129,7 @@ usageRouter.get("/stream", (req, res) => {
|
|
|
127
129
|
};
|
|
128
130
|
// Push immediate initial stats
|
|
129
131
|
try {
|
|
130
|
-
cachedStats = UsageRepository.getUsageStats(
|
|
132
|
+
cachedStats = UsageRepository.getUsageStats(period);
|
|
131
133
|
sendEvent("stats", cachedStats);
|
|
132
134
|
}
|
|
133
135
|
catch { }
|
package/dist/storage/database.js
CHANGED
|
@@ -214,6 +214,15 @@ function initSchema(db) {
|
|
|
214
214
|
FOREIGN KEY (provider_id) REFERENCES providers(id) ON DELETE CASCADE
|
|
215
215
|
);
|
|
216
216
|
|
|
217
|
+
CREATE TABLE IF NOT EXISTS account_supported_models (
|
|
218
|
+
account_id TEXT NOT NULL,
|
|
219
|
+
model_id TEXT NOT NULL,
|
|
220
|
+
scanned_at INTEGER NOT NULL,
|
|
221
|
+
PRIMARY KEY (account_id, model_id),
|
|
222
|
+
FOREIGN KEY (account_id) REFERENCES provider_accounts(id) ON DELETE CASCADE
|
|
223
|
+
);
|
|
224
|
+
CREATE INDEX IF NOT EXISTS idx_account_models_acc ON account_supported_models(account_id);
|
|
225
|
+
|
|
217
226
|
CREATE TABLE IF NOT EXISTS model_rules (
|
|
218
227
|
id TEXT PRIMARY KEY,
|
|
219
228
|
alias TEXT UNIQUE NOT NULL,
|
|
@@ -303,6 +312,28 @@ function initSchema(db) {
|
|
|
303
312
|
PRIMARY KEY (scope, key)
|
|
304
313
|
);
|
|
305
314
|
|
|
315
|
+
CREATE TABLE IF NOT EXISTS daily_usage_stats (
|
|
316
|
+
date TEXT NOT NULL,
|
|
317
|
+
provider_id TEXT NOT NULL,
|
|
318
|
+
actual_model TEXT NOT NULL,
|
|
319
|
+
account_id TEXT NOT NULL DEFAULT '',
|
|
320
|
+
account_name TEXT NOT NULL DEFAULT '',
|
|
321
|
+
api_key_id TEXT NOT NULL DEFAULT '',
|
|
322
|
+
api_key_name TEXT NOT NULL DEFAULT '',
|
|
323
|
+
requests INTEGER NOT NULL DEFAULT 0,
|
|
324
|
+
prompt_tokens INTEGER NOT NULL DEFAULT 0,
|
|
325
|
+
completion_tokens INTEGER NOT NULL DEFAULT 0,
|
|
326
|
+
cached_tokens INTEGER NOT NULL DEFAULT 0,
|
|
327
|
+
tokens_saved_by_rtk INTEGER NOT NULL DEFAULT 0,
|
|
328
|
+
cost REAL NOT NULL DEFAULT 0,
|
|
329
|
+
last_used INTEGER NOT NULL DEFAULT 0,
|
|
330
|
+
PRIMARY KEY (date, provider_id, actual_model, account_id, api_key_id)
|
|
331
|
+
);
|
|
332
|
+
|
|
333
|
+
CREATE INDEX IF NOT EXISTS idx_daily_usage_date ON daily_usage_stats(date);
|
|
334
|
+
CREATE INDEX IF NOT EXISTS idx_daily_usage_provider ON daily_usage_stats(provider_id);
|
|
335
|
+
CREATE INDEX IF NOT EXISTS idx_daily_usage_model ON daily_usage_stats(actual_model);
|
|
336
|
+
|
|
306
337
|
CREATE INDEX IF NOT EXISTS idx_request_logs_timestamp ON request_logs(timestamp);
|
|
307
338
|
CREATE INDEX IF NOT EXISTS idx_request_logs_provider ON request_logs(provider_id);
|
|
308
339
|
CREATE INDEX IF NOT EXISTS idx_request_logs_api_key_id ON request_logs(api_key_id);
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { getDatabase } from "../database.js";
|
|
2
|
+
export class AccountModelRepository {
|
|
3
|
+
/**
|
|
4
|
+
* Replaces all supported models for a specific account.
|
|
5
|
+
*/
|
|
6
|
+
static setAccountModels(accountId, modelIds) {
|
|
7
|
+
if (!accountId || accountId.startsWith("acc_virtual") || accountId === "explicit")
|
|
8
|
+
return;
|
|
9
|
+
const db = getDatabase();
|
|
10
|
+
const now = Date.now();
|
|
11
|
+
try {
|
|
12
|
+
db.exec("BEGIN TRANSACTION;");
|
|
13
|
+
db.run("DELETE FROM account_supported_models WHERE account_id = ?", accountId);
|
|
14
|
+
for (const mId of modelIds) {
|
|
15
|
+
if (!mId)
|
|
16
|
+
continue;
|
|
17
|
+
db.run("INSERT OR IGNORE INTO account_supported_models (account_id, model_id, scanned_at) VALUES (?, ?, ?)", accountId, mId.trim(), now);
|
|
18
|
+
}
|
|
19
|
+
db.exec("COMMIT;");
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
try {
|
|
23
|
+
db.exec("ROLLBACK;");
|
|
24
|
+
}
|
|
25
|
+
catch { }
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Adds a single model to an account's supported models (auto-learning on success).
|
|
30
|
+
*/
|
|
31
|
+
static addAccountModel(accountId, modelId) {
|
|
32
|
+
if (!accountId || !modelId || accountId.startsWith("acc_virtual") || accountId === "explicit")
|
|
33
|
+
return;
|
|
34
|
+
try {
|
|
35
|
+
const db = getDatabase();
|
|
36
|
+
db.run("INSERT OR IGNORE INTO account_supported_models (account_id, model_id, scanned_at) VALUES (?, ?, ?)", accountId, modelId.trim(), Date.now());
|
|
37
|
+
}
|
|
38
|
+
catch { }
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Clears all models for an account (e.g. when API key / credentials are changed).
|
|
42
|
+
*/
|
|
43
|
+
static clearAccountModels(accountId) {
|
|
44
|
+
if (!accountId)
|
|
45
|
+
return;
|
|
46
|
+
try {
|
|
47
|
+
const db = getDatabase();
|
|
48
|
+
db.run("DELETE FROM account_supported_models WHERE account_id = ?", accountId);
|
|
49
|
+
}
|
|
50
|
+
catch { }
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Gets all supported models for an account. Returns null if account has never been scanned.
|
|
54
|
+
*/
|
|
55
|
+
static getAccountModels(accountId) {
|
|
56
|
+
if (!accountId)
|
|
57
|
+
return null;
|
|
58
|
+
const db = getDatabase();
|
|
59
|
+
const rows = db.all("SELECT model_id FROM account_supported_models WHERE account_id = ?", accountId);
|
|
60
|
+
if (!rows || rows.length === 0) {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
return new Set(rows.map((r) => r.model_id));
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Classifies a list of candidate account IDs for a given target model:
|
|
67
|
+
* - supported: account explicitly has this model
|
|
68
|
+
* - unscanned: account has no records in account_supported_models
|
|
69
|
+
* - unsupported: account has records but does NOT include this model
|
|
70
|
+
*/
|
|
71
|
+
static classifyAccounts(accountIds, targetModel) {
|
|
72
|
+
const supported = new Set();
|
|
73
|
+
const unscanned = new Set();
|
|
74
|
+
const unsupported = new Set();
|
|
75
|
+
if (!accountIds || accountIds.length === 0 || !targetModel) {
|
|
76
|
+
for (const id of accountIds || [])
|
|
77
|
+
unscanned.add(id);
|
|
78
|
+
return { supported, unscanned, unsupported };
|
|
79
|
+
}
|
|
80
|
+
const db = getDatabase();
|
|
81
|
+
const cleanTarget = targetModel.toLowerCase().trim();
|
|
82
|
+
// Query distinct models for given account IDs in one batch
|
|
83
|
+
const placeholders = accountIds.map(() => "?").join(",");
|
|
84
|
+
const rows = db.all(`SELECT account_id, model_id FROM account_supported_models WHERE account_id IN (${placeholders})`, ...accountIds);
|
|
85
|
+
const accountModelsMap = new Map();
|
|
86
|
+
for (const r of rows) {
|
|
87
|
+
let set = accountModelsMap.get(r.account_id);
|
|
88
|
+
if (!set) {
|
|
89
|
+
set = new Set();
|
|
90
|
+
accountModelsMap.set(r.account_id, set);
|
|
91
|
+
}
|
|
92
|
+
set.add(r.model_id.toLowerCase());
|
|
93
|
+
}
|
|
94
|
+
for (const id of accountIds) {
|
|
95
|
+
const set = accountModelsMap.get(id);
|
|
96
|
+
if (!set || set.size === 0) {
|
|
97
|
+
unscanned.add(id);
|
|
98
|
+
}
|
|
99
|
+
else if (set.has(cleanTarget)) {
|
|
100
|
+
supported.add(id);
|
|
101
|
+
}
|
|
102
|
+
else {
|
|
103
|
+
unsupported.add(id);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return { supported, unscanned, unsupported };
|
|
107
|
+
}
|
|
108
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { getDatabase } from "../database.js";
|
|
2
|
+
import { SettingsRepository } from "./settingsRepo.js";
|
|
2
3
|
export class LogRepository {
|
|
3
4
|
static saveLog(log) {
|
|
4
5
|
const db = getDatabase();
|
|
@@ -8,9 +9,46 @@ export class LogRepository {
|
|
|
8
9
|
cached_tokens, cache_creation_tokens, cost, account_id, account_name,
|
|
9
10
|
api_key_id, api_key_name, duration_ms, status, error_message
|
|
10
11
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, log.id, log.timestamp, log.clientTool, log.requestedModel, log.actualModel, log.providerId, log.promptTokens || 0, log.completionTokens || 0, log.tokensSavedByRtk || 0, log.cachedTokens || 0, log.cacheCreationTokens || 0, log.cost || 0, log.accountId || null, log.accountName || null, log.apiKeyId || null, log.apiKeyName || null, log.durationMs || 0, log.status, log.errorMessage || null);
|
|
12
|
+
// Roll up into daily_usage_stats for perpetual history (only for requests with actual token usage)
|
|
13
|
+
const hasTokens = (log.promptTokens || 0) + (log.completionTokens || 0) > 0;
|
|
14
|
+
if (hasTokens) {
|
|
15
|
+
try {
|
|
16
|
+
const d = new Date(log.timestamp);
|
|
17
|
+
const dateStr = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
|
|
18
|
+
const providerId = log.providerId || "unknown";
|
|
19
|
+
const actualModel = log.actualModel || log.requestedModel || "unknown";
|
|
20
|
+
const accountId = log.accountId || "";
|
|
21
|
+
const accountName = log.accountName || "";
|
|
22
|
+
const apiKeyId = log.apiKeyId || "";
|
|
23
|
+
const apiKeyName = log.apiKeyName || "";
|
|
24
|
+
db.run(`INSERT INTO daily_usage_stats (
|
|
25
|
+
date, provider_id, actual_model, account_id, account_name,
|
|
26
|
+
api_key_id, api_key_name, requests, prompt_tokens,
|
|
27
|
+
completion_tokens, cached_tokens, tokens_saved_by_rtk, cost, last_used
|
|
28
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?)
|
|
29
|
+
ON CONFLICT(date, provider_id, actual_model, account_id, api_key_id) DO UPDATE SET
|
|
30
|
+
requests = requests + 1,
|
|
31
|
+
prompt_tokens = prompt_tokens + excluded.prompt_tokens,
|
|
32
|
+
completion_tokens = completion_tokens + excluded.completion_tokens,
|
|
33
|
+
cached_tokens = cached_tokens + excluded.cached_tokens,
|
|
34
|
+
tokens_saved_by_rtk = tokens_saved_by_rtk + excluded.tokens_saved_by_rtk,
|
|
35
|
+
cost = cost + excluded.cost,
|
|
36
|
+
account_name = CASE WHEN excluded.account_name != '' THEN excluded.account_name ELSE daily_usage_stats.account_name END,
|
|
37
|
+
api_key_name = CASE WHEN excluded.api_key_name != '' THEN excluded.api_key_name ELSE daily_usage_stats.api_key_name END,
|
|
38
|
+
last_used = MAX(last_used, excluded.last_used)`, dateStr, providerId, actualModel, accountId, accountName, apiKeyId, apiKeyName, log.promptTokens || 0, log.completionTokens || 0, log.cachedTokens || 0, log.tokensSavedByRtk || 0, log.cost || 0, log.timestamp);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
// Best effort rollup
|
|
42
|
+
}
|
|
43
|
+
}
|
|
11
44
|
// Periodic retention prune (1 in 50 writes) to keep database lean and prevent unbounded table growth
|
|
12
45
|
if (Math.random() < 0.02) {
|
|
13
46
|
try {
|
|
47
|
+
const retentionDays = SettingsRepository.getLogRetentionDays();
|
|
48
|
+
if (retentionDays > 0) {
|
|
49
|
+
const cutoffTs = Date.now() - retentionDays * 24 * 60 * 60 * 1000;
|
|
50
|
+
db.run("DELETE FROM request_logs WHERE timestamp < ?", cutoffTs);
|
|
51
|
+
}
|
|
14
52
|
const maxLogs = Number(process.env.MAPIGATE_MAX_LOGS) || 20000;
|
|
15
53
|
const countRow = db.get("SELECT COUNT(*) as count FROM request_logs");
|
|
16
54
|
if (countRow && countRow.count > maxLogs) {
|
|
@@ -50,16 +88,28 @@ export class LogRepository {
|
|
|
50
88
|
}
|
|
51
89
|
static getTokenStats() {
|
|
52
90
|
const db = getDatabase();
|
|
53
|
-
const
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
91
|
+
const hasDaily = Boolean(db.get("SELECT 1 as c FROM daily_usage_stats LIMIT 1"));
|
|
92
|
+
const row = hasDaily
|
|
93
|
+
? db.get(`
|
|
94
|
+
SELECT
|
|
95
|
+
COALESCE(SUM(requests), 0) as total_requests,
|
|
96
|
+
COALESCE(SUM(prompt_tokens), 0) as total_prompt,
|
|
97
|
+
COALESCE(SUM(completion_tokens), 0) as total_completion,
|
|
98
|
+
COALESCE(SUM(tokens_saved_by_rtk), 0) as total_saved,
|
|
99
|
+
COALESCE(SUM(cached_tokens), 0) as total_cached,
|
|
100
|
+
COALESCE(SUM(cost), 0) as total_cost
|
|
101
|
+
FROM daily_usage_stats
|
|
102
|
+
`)
|
|
103
|
+
: db.get(`
|
|
104
|
+
SELECT
|
|
105
|
+
COUNT(*) as total_requests,
|
|
106
|
+
COALESCE(SUM(prompt_tokens), 0) as total_prompt,
|
|
107
|
+
COALESCE(SUM(completion_tokens), 0) as total_completion,
|
|
108
|
+
COALESCE(SUM(tokens_saved_by_rtk), 0) as total_saved,
|
|
109
|
+
COALESCE(SUM(cached_tokens), 0) as total_cached,
|
|
110
|
+
COALESCE(SUM(cost), 0) as total_cost
|
|
111
|
+
FROM request_logs
|
|
112
|
+
`);
|
|
63
113
|
const totalSaved = Number(row?.total_saved || 0);
|
|
64
114
|
// Estimated average cost per 1M tokens saved: ~$3.00 USD
|
|
65
115
|
const estimatedCostSavedUsd = Number(((totalSaved / 1_000_000) * 3.0).toFixed(4));
|
|
@@ -83,6 +133,17 @@ export class LogRepository {
|
|
|
83
133
|
const db = getDatabase();
|
|
84
134
|
const now = new Date();
|
|
85
135
|
const monthStartMs = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1);
|
|
136
|
+
const monthStartStr = `${now.getUTCFullYear()}-${String(now.getUTCMonth() + 1).padStart(2, "0")}-01`;
|
|
137
|
+
const hasDaily = Boolean(db.get("SELECT 1 as c FROM daily_usage_stats LIMIT 1"));
|
|
138
|
+
if (hasDaily) {
|
|
139
|
+
const row = db.get(`SELECT COALESCE(SUM(prompt_tokens), 0)
|
|
140
|
+
+ COALESCE(SUM(completion_tokens), 0)
|
|
141
|
+
+ COALESCE(SUM(cached_tokens), 0) AS total
|
|
142
|
+
FROM daily_usage_stats
|
|
143
|
+
WHERE (account_id = ? OR (account_id = '' AND provider_id = ?))
|
|
144
|
+
AND date >= ?`, accountId, providerId || "", monthStartStr);
|
|
145
|
+
return Math.max(0, Number(row?.total || 0));
|
|
146
|
+
}
|
|
86
147
|
const row = db.get(`SELECT COALESCE(SUM(prompt_tokens), 0)
|
|
87
148
|
+ COALESCE(SUM(completion_tokens), 0)
|
|
88
149
|
+ COALESCE(SUM(cached_tokens), 0)
|