wyxrouter 0.4.71
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/CHANGELOG.md +222 -0
- package/LICENSE +21 -0
- package/README.md +96 -0
- package/README.zh-CN.md +1311 -0
- package/assets/pixel-router-2d.png +0 -0
- package/cli/LICENSE +42 -0
- package/cli/README.md +125 -0
- package/cli/app/package.json +58 -0
- package/cli/cli.js +806 -0
- package/cli/package.json +48 -0
- package/i18n/README.ja-JP.md +1209 -0
- package/i18n/README.ru.md +1311 -0
- package/i18n/README.vi.md +1310 -0
- package/i18n/README.zh-CN.md +1306 -0
- package/images/9router.png +0 -0
- package/jsconfig.json +12 -0
- package/next.config.mjs +71 -0
- package/open-sse/config/appConstants.js +203 -0
- package/open-sse/config/codexInstructions.js +119 -0
- package/open-sse/config/constants.js +4 -0
- package/open-sse/config/defaultThinkingSignature.js +12 -0
- package/open-sse/config/errorConfig.js +85 -0
- package/open-sse/config/googleTtsLanguages.js +62 -0
- package/open-sse/config/kiroConstants.js +322 -0
- package/open-sse/config/models.js +13 -0
- package/open-sse/config/ollamaModels.js +19 -0
- package/open-sse/config/providerModels.js +944 -0
- package/open-sse/config/providers.js +458 -0
- package/open-sse/config/runtimeConfig.js +72 -0
- package/open-sse/config/ttsModels.js +129 -0
- package/open-sse/executors/antigravity.js +504 -0
- package/open-sse/executors/azure.js +57 -0
- package/open-sse/executors/base.js +185 -0
- package/open-sse/executors/codex.js +469 -0
- package/open-sse/executors/commandcode.js +88 -0
- package/open-sse/executors/cursor.js +795 -0
- package/open-sse/executors/default.js +497 -0
- package/open-sse/executors/gemini-cli.js +89 -0
- package/open-sse/executors/github.js +379 -0
- package/open-sse/executors/grok-web.js +345 -0
- package/open-sse/executors/iflow.js +108 -0
- package/open-sse/executors/index.js +75 -0
- package/open-sse/executors/kiro.js +508 -0
- package/open-sse/executors/ollama-local.js +14 -0
- package/open-sse/executors/opencode-go.js +41 -0
- package/open-sse/executors/opencode.js +32 -0
- package/open-sse/executors/perplexity-web.js +507 -0
- package/open-sse/executors/qoder.js +450 -0
- package/open-sse/executors/qwen.js +129 -0
- package/open-sse/executors/vertex.js +131 -0
- package/open-sse/executors/xiaomi-tokenplan.js +19 -0
- package/open-sse/handlers/chatCore/nonStreamingHandler.js +230 -0
- package/open-sse/handlers/chatCore/requestDetail.js +102 -0
- package/open-sse/handlers/chatCore/sseToJsonHandler.js +231 -0
- package/open-sse/handlers/chatCore/streamingHandler.js +103 -0
- package/open-sse/handlers/chatCore.js +287 -0
- package/open-sse/handlers/embeddingProviders/_base.js +4 -0
- package/open-sse/handlers/embeddingProviders/gemini.js +54 -0
- package/open-sse/handlers/embeddingProviders/index.js +23 -0
- package/open-sse/handlers/embeddingProviders/openai.js +39 -0
- package/open-sse/handlers/embeddingProviders/openaiCompatNode.js +13 -0
- package/open-sse/handlers/embeddingsCore.js +126 -0
- package/open-sse/handlers/fetch/index.js +237 -0
- package/open-sse/handlers/imageGenerationCore.js +189 -0
- package/open-sse/handlers/imageProviders/_base.js +31 -0
- package/open-sse/handlers/imageProviders/blackForestLabs.js +43 -0
- package/open-sse/handlers/imageProviders/cloudflareAi.js +178 -0
- package/open-sse/handlers/imageProviders/codex.js +198 -0
- package/open-sse/handlers/imageProviders/comfyui.js +8 -0
- package/open-sse/handlers/imageProviders/falAi.js +41 -0
- package/open-sse/handlers/imageProviders/gemini.js +25 -0
- package/open-sse/handlers/imageProviders/huggingface.js +22 -0
- package/open-sse/handlers/imageProviders/index.js +40 -0
- package/open-sse/handlers/imageProviders/nanobanana.js +58 -0
- package/open-sse/handlers/imageProviders/openai.js +40 -0
- package/open-sse/handlers/imageProviders/runwayml.js +47 -0
- package/open-sse/handlers/imageProviders/sdwebui.js +17 -0
- package/open-sse/handlers/imageProviders/stabilityAi.js +34 -0
- package/open-sse/handlers/responsesHandler.js +103 -0
- package/open-sse/handlers/search/callers.js +371 -0
- package/open-sse/handlers/search/chatSearch.js +409 -0
- package/open-sse/handlers/search/index.js +201 -0
- package/open-sse/handlers/search/normalizers.js +223 -0
- package/open-sse/handlers/sttCore.js +194 -0
- package/open-sse/handlers/ttsCore.js +74 -0
- package/open-sse/handlers/ttsProviders/_base.js +39 -0
- package/open-sse/handlers/ttsProviders/edgeTts.js +89 -0
- package/open-sse/handlers/ttsProviders/elevenlabs.js +48 -0
- package/open-sse/handlers/ttsProviders/gemini.js +117 -0
- package/open-sse/handlers/ttsProviders/genericFormats.js +169 -0
- package/open-sse/handlers/ttsProviders/googleTts.js +54 -0
- package/open-sse/handlers/ttsProviders/index.js +50 -0
- package/open-sse/handlers/ttsProviders/localDevice.js +87 -0
- package/open-sse/handlers/ttsProviders/minimax.js +59 -0
- package/open-sse/handlers/ttsProviders/openai.js +30 -0
- package/open-sse/handlers/ttsProviders/openrouter.js +70 -0
- package/open-sse/index.js +82 -0
- package/open-sse/rtk/applyFilter.js +15 -0
- package/open-sse/rtk/autodetect.js +111 -0
- package/open-sse/rtk/caveman.js +100 -0
- package/open-sse/rtk/cavemanPrompts.js +78 -0
- package/open-sse/rtk/constants.js +55 -0
- package/open-sse/rtk/filters/buildOutput.js +127 -0
- package/open-sse/rtk/filters/dedupLog.js +44 -0
- package/open-sse/rtk/filters/find.js +49 -0
- package/open-sse/rtk/filters/gitDiff.js +92 -0
- package/open-sse/rtk/filters/gitStatus.js +117 -0
- package/open-sse/rtk/filters/grep.js +48 -0
- package/open-sse/rtk/filters/ls.js +79 -0
- package/open-sse/rtk/filters/readNumbered.js +27 -0
- package/open-sse/rtk/filters/searchList.js +52 -0
- package/open-sse/rtk/filters/smartTruncate.js +15 -0
- package/open-sse/rtk/filters/tree.js +32 -0
- package/open-sse/rtk/index.js +155 -0
- package/open-sse/rtk/registry.js +38 -0
- package/open-sse/services/accountFallback.js +238 -0
- package/open-sse/services/combo.js +198 -0
- package/open-sse/services/compact.js +71 -0
- package/open-sse/services/kiroModels.js +332 -0
- package/open-sse/services/model.js +261 -0
- package/open-sse/services/oauthCredentialManager.js +151 -0
- package/open-sse/services/projectId.js +306 -0
- package/open-sse/services/provider.js +356 -0
- package/open-sse/services/qoderModels.js +214 -0
- package/open-sse/services/tokenRefresh.js +939 -0
- package/open-sse/services/usage.js +1496 -0
- package/open-sse/transformer/responsesTransformer.js +439 -0
- package/open-sse/transformer/streamToJsonConverter.js +103 -0
- package/open-sse/translator/formats.js +36 -0
- package/open-sse/translator/helpers/claudeHelper.js +216 -0
- package/open-sse/translator/helpers/geminiHelper.js +372 -0
- package/open-sse/translator/helpers/imageHelper.js +34 -0
- package/open-sse/translator/helpers/maxTokensHelper.js +27 -0
- package/open-sse/translator/helpers/openaiHelper.js +130 -0
- package/open-sse/translator/helpers/responsesApiHelper.js +139 -0
- package/open-sse/translator/helpers/toolCallHelper.js +148 -0
- package/open-sse/translator/index.js +251 -0
- package/open-sse/translator/request/antigravity-to-openai.js +229 -0
- package/open-sse/translator/request/claude-to-openai.js +232 -0
- package/open-sse/translator/request/gemini-to-openai.js +147 -0
- package/open-sse/translator/request/openai-responses.js +318 -0
- package/open-sse/translator/request/openai-to-claude.js +401 -0
- package/open-sse/translator/request/openai-to-commandcode.js +170 -0
- package/open-sse/translator/request/openai-to-cursor.js +183 -0
- package/open-sse/translator/request/openai-to-gemini.js +470 -0
- package/open-sse/translator/request/openai-to-kiro.js +629 -0
- package/open-sse/translator/request/openai-to-kiro.old.js +278 -0
- package/open-sse/translator/request/openai-to-ollama.js +192 -0
- package/open-sse/translator/request/openai-to-vertex.js +42 -0
- package/open-sse/translator/response/claude-to-openai.js +206 -0
- package/open-sse/translator/response/commandcode-to-openai.js +197 -0
- package/open-sse/translator/response/cursor-to-openai.js +30 -0
- package/open-sse/translator/response/gemini-to-openai.js +245 -0
- package/open-sse/translator/response/kiro-to-openai.js +195 -0
- package/open-sse/translator/response/ollama-to-openai.js +152 -0
- package/open-sse/translator/response/openai-responses.js +590 -0
- package/open-sse/translator/response/openai-to-antigravity.js +122 -0
- package/open-sse/translator/response/openai-to-claude.js +266 -0
- package/open-sse/utils/bypassHandler.js +298 -0
- package/open-sse/utils/claudeCloaking.js +155 -0
- package/open-sse/utils/claudeHeaderCache.js +70 -0
- package/open-sse/utils/clientDetector.js +63 -0
- package/open-sse/utils/cursorChecksum.js +149 -0
- package/open-sse/utils/cursorProtobuf.js +904 -0
- package/open-sse/utils/debugLog.js +14 -0
- package/open-sse/utils/error.js +147 -0
- package/open-sse/utils/ollamaTransform.js +85 -0
- package/open-sse/utils/proxyFetch.js +368 -0
- package/open-sse/utils/reasoningContentInjector.js +79 -0
- package/open-sse/utils/requestLogger.js +260 -0
- package/open-sse/utils/responsesStreamHelpers.js +49 -0
- package/open-sse/utils/sessionManager.js +82 -0
- package/open-sse/utils/stream.js +462 -0
- package/open-sse/utils/streamHandler.js +250 -0
- package/open-sse/utils/streamHelpers.js +122 -0
- package/open-sse/utils/toolDeduper.js +49 -0
- package/open-sse/utils/usageTracking.js +347 -0
- package/package.json +100 -0
- package/postcss.config.mjs +12 -0
- package/public/favicon.svg +11 -0
- package/public/file.svg +1 -0
- package/public/globe.svg +1 -0
- package/public/i18n/literals/ar.json +195 -0
- package/public/i18n/literals/bn.json +195 -0
- package/public/i18n/literals/cs.json +195 -0
- package/public/i18n/literals/da.json +195 -0
- package/public/i18n/literals/de.json +195 -0
- package/public/i18n/literals/el.json +195 -0
- package/public/i18n/literals/es.json +195 -0
- package/public/i18n/literals/fi.json +195 -0
- package/public/i18n/literals/fr.json +195 -0
- package/public/i18n/literals/he.json +195 -0
- package/public/i18n/literals/hi.json +195 -0
- package/public/i18n/literals/hu.json +195 -0
- package/public/i18n/literals/id.json +195 -0
- package/public/i18n/literals/it.json +195 -0
- package/public/i18n/literals/ja.json +195 -0
- package/public/i18n/literals/ko.json +195 -0
- package/public/i18n/literals/nl.json +195 -0
- package/public/i18n/literals/no.json +195 -0
- package/public/i18n/literals/pl.json +195 -0
- package/public/i18n/literals/pt-BR.json +195 -0
- package/public/i18n/literals/pt-PT.json +195 -0
- package/public/i18n/literals/ro.json +195 -0
- package/public/i18n/literals/ru.json +195 -0
- package/public/i18n/literals/sv.json +195 -0
- package/public/i18n/literals/th.json +195 -0
- package/public/i18n/literals/tl.json +195 -0
- package/public/i18n/literals/tr.json +195 -0
- package/public/i18n/literals/uk.json +195 -0
- package/public/i18n/literals/ur.json +195 -0
- package/public/i18n/literals/vi.json +195 -0
- package/public/i18n/literals/zh-CN.json +772 -0
- package/public/i18n/literals/zh-TW.json +195 -0
- package/public/icons/discord.svg +4 -0
- package/public/icons/icon-192.svg +4 -0
- package/public/icons/icon-512.svg +4 -0
- package/public/next.svg +1 -0
- package/public/providers/alicode-intl.png +0 -0
- package/public/providers/alicode.png +0 -0
- package/public/providers/amp.png +0 -0
- package/public/providers/anthropic-m.png +0 -0
- package/public/providers/anthropic.png +0 -0
- package/public/providers/antigravity.png +0 -0
- package/public/providers/assemblyai.png +0 -0
- package/public/providers/aws-polly.png +0 -0
- package/public/providers/azure.png +0 -0
- package/public/providers/black-forest-labs.png +0 -0
- package/public/providers/blackbox.png +0 -0
- package/public/providers/brave-search.png +0 -0
- package/public/providers/byteplus.png +0 -0
- package/public/providers/cartesia.png +0 -0
- package/public/providers/cerebras.png +0 -0
- package/public/providers/chutes.png +0 -0
- package/public/providers/claude.png +0 -0
- package/public/providers/cline.png +0 -0
- package/public/providers/cloudflare-ai.png +0 -0
- package/public/providers/codebuddy.svg +37 -0
- package/public/providers/codex.png +0 -0
- package/public/providers/cohere.png +0 -0
- package/public/providers/comfyui.png +0 -0
- package/public/providers/commandcode.png +0 -0
- package/public/providers/continue.png +0 -0
- package/public/providers/copilot.png +0 -0
- package/public/providers/coqui.png +0 -0
- package/public/providers/cursor.png +0 -0
- package/public/providers/deepgram.png +0 -0
- package/public/providers/deepseek-tui.png +0 -0
- package/public/providers/deepseek.png +0 -0
- package/public/providers/droid.png +0 -0
- package/public/providers/edge-tts.png +0 -0
- package/public/providers/elevenlabs.png +0 -0
- package/public/providers/exa.png +0 -0
- package/public/providers/fal-ai.png +0 -0
- package/public/providers/firecrawl.png +0 -0
- package/public/providers/fireworks.png +0 -0
- package/public/providers/gemini-cli.png +0 -0
- package/public/providers/gemini.png +0 -0
- package/public/providers/github.png +0 -0
- package/public/providers/glm-cn.png +0 -0
- package/public/providers/glm.png +0 -0
- package/public/providers/google-pse.png +0 -0
- package/public/providers/google-tts.png +0 -0
- package/public/providers/grok-web.png +0 -0
- package/public/providers/groq.png +0 -0
- package/public/providers/hermes.png +0 -0
- package/public/providers/huggingface.png +0 -0
- package/public/providers/hyperbolic.png +0 -0
- package/public/providers/iflow.png +0 -0
- package/public/providers/inworld.png +0 -0
- package/public/providers/jcode.png +0 -0
- package/public/providers/jina-ai.png +0 -0
- package/public/providers/jina-reader.png +0 -0
- package/public/providers/kilocode.png +0 -0
- package/public/providers/kimi-coding.png +0 -0
- package/public/providers/kimi.png +0 -0
- package/public/providers/kiro.png +0 -0
- package/public/providers/linkup.png +0 -0
- package/public/providers/local-device.png +0 -0
- package/public/providers/minimax-cn.png +0 -0
- package/public/providers/minimax.png +0 -0
- package/public/providers/mistral.png +0 -0
- package/public/providers/nanobanana.png +0 -0
- package/public/providers/nebius.png +0 -0
- package/public/providers/nvidia.png +0 -0
- package/public/providers/oai-cc.png +0 -0
- package/public/providers/oai-r.png +0 -0
- package/public/providers/ollama-local.png +0 -0
- package/public/providers/ollama.png +0 -0
- package/public/providers/openai.png +0 -0
- package/public/providers/openclaw.png +0 -0
- package/public/providers/opencode-go.png +0 -0
- package/public/providers/opencode.png +0 -0
- package/public/providers/openrouter.png +0 -0
- package/public/providers/perplexity-web.png +0 -0
- package/public/providers/perplexity.png +0 -0
- package/public/providers/playht.png +0 -0
- package/public/providers/qoder.png +0 -0
- package/public/providers/qwen.png +0 -0
- package/public/providers/recraft.png +0 -0
- package/public/providers/roo.png +0 -0
- package/public/providers/runwayml.png +0 -0
- package/public/providers/sdwebui.png +0 -0
- package/public/providers/searchapi.png +0 -0
- package/public/providers/searxng.png +0 -0
- package/public/providers/serper.png +0 -0
- package/public/providers/siliconflow.png +0 -0
- package/public/providers/stability-ai.png +0 -0
- package/public/providers/tavily.png +0 -0
- package/public/providers/together.png +0 -0
- package/public/providers/topaz.png +0 -0
- package/public/providers/tortoise.png +0 -0
- package/public/providers/vertex-partner.png +0 -0
- package/public/providers/vertex.png +0 -0
- package/public/providers/volcengine-ark.png +0 -0
- package/public/providers/voyage-ai.png +0 -0
- package/public/providers/xai.png +0 -0
- package/public/providers/xiaomi-mimo.png +0 -0
- package/public/providers/xiaomi-tokenplan.png +0 -0
- package/public/providers/youcom.png +0 -0
- package/public/sw.js +22 -0
- package/public/vercel.svg +1 -0
- package/public/window.svg +1 -0
- package/scripts/compact-request-details.mjs +71 -0
- package/scripts/import-codex-gptjson.mjs +342 -0
- package/scripts/start-standalone.mjs +25 -0
- package/scripts/translate-readme.js +201 -0
- package/src/app/(dashboard)/dashboard/automation/page.js +294 -0
- package/src/app/(dashboard)/dashboard/basic-chat/BasicChatPageClient.js +967 -0
- package/src/app/(dashboard)/dashboard/basic-chat/page.js +5 -0
- package/src/app/(dashboard)/dashboard/cli-tools/CLIToolsPageClient.js +66 -0
- package/src/app/(dashboard)/dashboard/cli-tools/[toolId]/ToolDetailClient.js +173 -0
- package/src/app/(dashboard)/dashboard/cli-tools/[toolId]/page.js +11 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/AntigravityToolCard.js +481 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/ApiKeySelect.js +66 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/BaseUrlSelect.js +174 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/ClaudeToolCard.js +390 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/ClineToolCard.js +301 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/CodexToolCard.js +458 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/CopilotToolCard.js +323 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/CoworkToolCard.js +640 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/DeepSeekTuiToolCard.js +338 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/DefaultToolCard.js +271 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/DroidToolCard.js +410 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/EndpointPresetControl.js +128 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/HermesToolCard.js +317 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/JcodeToolCard.js +380 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/KiloToolCard.js +275 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/MitmLinkCard.js +40 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/MitmServerCard.js +329 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/MitmToolCard.js +318 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/OpenClawToolCard.js +388 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/OpenCodeToolCard.js +500 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/ToolSummaryCard.js +39 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/cliEndpointMatch.js +13 -0
- package/src/app/(dashboard)/dashboard/cli-tools/components/index.js +19 -0
- package/src/app/(dashboard)/dashboard/cli-tools/page.js +7 -0
- package/src/app/(dashboard)/dashboard/combos/page.js +612 -0
- package/src/app/(dashboard)/dashboard/console-log/ConsoleLogClient.js +91 -0
- package/src/app/(dashboard)/dashboard/console-log/page.js +8 -0
- package/src/app/(dashboard)/dashboard/endpoint/EndpointPageClient.js +1555 -0
- package/src/app/(dashboard)/dashboard/endpoint/page.js +7 -0
- package/src/app/(dashboard)/dashboard/media-providers/[kind]/[id]/page.js +1903 -0
- package/src/app/(dashboard)/dashboard/media-providers/[kind]/page.js +289 -0
- package/src/app/(dashboard)/dashboard/media-providers/combo/[id]/page.js +410 -0
- package/src/app/(dashboard)/dashboard/media-providers/web/page.js +209 -0
- package/src/app/(dashboard)/dashboard/mitm/MitmPageClient.js +117 -0
- package/src/app/(dashboard)/dashboard/mitm/page.js +5 -0
- package/src/app/(dashboard)/dashboard/page.js +7 -0
- package/src/app/(dashboard)/dashboard/profile/page.js +1140 -0
- package/src/app/(dashboard)/dashboard/providers/[id]/AddApiKeyModal.js +389 -0
- package/src/app/(dashboard)/dashboard/providers/[id]/AddCustomModelModal.js +125 -0
- package/src/app/(dashboard)/dashboard/providers/[id]/CompatibleModelsSection.js +250 -0
- package/src/app/(dashboard)/dashboard/providers/[id]/ConnectionRow.js +299 -0
- package/src/app/(dashboard)/dashboard/providers/[id]/CooldownTimer.js +42 -0
- package/src/app/(dashboard)/dashboard/providers/[id]/EditCompatibleNodeModal.js +161 -0
- package/src/app/(dashboard)/dashboard/providers/[id]/ModelRow.js +95 -0
- package/src/app/(dashboard)/dashboard/providers/[id]/PassthroughModelsSection.js +183 -0
- package/src/app/(dashboard)/dashboard/providers/[id]/page.js +2053 -0
- package/src/app/(dashboard)/dashboard/providers/[id]/page.new.js +1724 -0
- package/src/app/(dashboard)/dashboard/providers/components/ConnectionsCard.js +497 -0
- package/src/app/(dashboard)/dashboard/providers/components/ModelAvailabilityBadge.js +185 -0
- package/src/app/(dashboard)/dashboard/providers/components/ModelsCard.js +294 -0
- package/src/app/(dashboard)/dashboard/providers/new/page.js +220 -0
- package/src/app/(dashboard)/dashboard/providers/page.js +1365 -0
- package/src/app/(dashboard)/dashboard/proxy-pools/page.js +1092 -0
- package/src/app/(dashboard)/dashboard/quota/page.js +11 -0
- package/src/app/(dashboard)/dashboard/skills/page.js +112 -0
- package/src/app/(dashboard)/dashboard/translator/page.js +303 -0
- package/src/app/(dashboard)/dashboard/usage/components/OverviewCards.js +35 -0
- package/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/ProviderLimitCard.js +185 -0
- package/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/QuotaProgressBar.js +127 -0
- package/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/QuotaTable.js +259 -0
- package/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/index.js +1394 -0
- package/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/utils.js +244 -0
- package/src/app/(dashboard)/dashboard/usage/components/ProviderTopology.js +327 -0
- package/src/app/(dashboard)/dashboard/usage/components/RequestDetailsTab.js +433 -0
- package/src/app/(dashboard)/dashboard/usage/components/UsageChart.js +141 -0
- package/src/app/(dashboard)/dashboard/usage/components/UsageTable.js +247 -0
- package/src/app/(dashboard)/dashboard/usage/page.js +75 -0
- package/src/app/(dashboard)/layout.js +6 -0
- package/src/app/api/auth/login/route.js +76 -0
- package/src/app/api/auth/logout/route.js +12 -0
- package/src/app/api/auth/oidc/callback/route.js +87 -0
- package/src/app/api/auth/oidc/start/route.js +52 -0
- package/src/app/api/auth/oidc/test/route.js +84 -0
- package/src/app/api/auth/status/route.js +45 -0
- package/src/app/api/cli-tools/all-statuses/route.js +46 -0
- package/src/app/api/cli-tools/antigravity-mitm/alias/route.js +53 -0
- package/src/app/api/cli-tools/antigravity-mitm/route.js +202 -0
- package/src/app/api/cli-tools/claude-settings/route.js +203 -0
- package/src/app/api/cli-tools/cline-settings/route.js +133 -0
- package/src/app/api/cli-tools/codex-gateway/accounts/route.js +16 -0
- package/src/app/api/cli-tools/codex-settings/route.js +239 -0
- package/src/app/api/cli-tools/copilot-settings/route.js +148 -0
- package/src/app/api/cli-tools/cowork-mcp-registry/route.js +77 -0
- package/src/app/api/cli-tools/cowork-mcp-tools/route.js +95 -0
- package/src/app/api/cli-tools/cowork-settings/route.js +412 -0
- package/src/app/api/cli-tools/deepseek-tui-settings/route.js +164 -0
- package/src/app/api/cli-tools/droid-settings/route.js +213 -0
- package/src/app/api/cli-tools/hermes-settings/route.js +175 -0
- package/src/app/api/cli-tools/jcode-settings/route.js +216 -0
- package/src/app/api/cli-tools/kilo-settings/route.js +131 -0
- package/src/app/api/cli-tools/openclaw-settings/route.js +292 -0
- package/src/app/api/cli-tools/opencode-settings/route.js +259 -0
- package/src/app/api/combos/[id]/route.js +81 -0
- package/src/app/api/combos/route.js +48 -0
- package/src/app/api/health/route.js +15 -0
- package/src/app/api/init/route.js +4 -0
- package/src/app/api/keys/[id]/route.js +58 -0
- package/src/app/api/keys/route.js +42 -0
- package/src/app/api/locale/route.js +30 -0
- package/src/app/api/mcp/[plugin]/message/route.js +21 -0
- package/src/app/api/mcp/[plugin]/sse/route.js +37 -0
- package/src/app/api/media-providers/tts/deepgram/voices/route.js +65 -0
- package/src/app/api/media-providers/tts/elevenlabs/voices/route.js +71 -0
- package/src/app/api/media-providers/tts/inworld/voices/route.js +61 -0
- package/src/app/api/media-providers/tts/minimax/voices/route.js +113 -0
- package/src/app/api/media-providers/tts/voices/route.js +99 -0
- package/src/app/api/models/alias/route.js +53 -0
- package/src/app/api/models/availability/route.js +103 -0
- package/src/app/api/models/custom/route.js +48 -0
- package/src/app/api/models/disabled/route.js +50 -0
- package/src/app/api/models/route.js +64 -0
- package/src/app/api/models/test/ping.js +191 -0
- package/src/app/api/models/test/route.js +14 -0
- package/src/app/api/oauth/[provider]/[action]/route.js +343 -0
- package/src/app/api/oauth/codebuddy/bulk-import/[jobId]/cancel/route.js +19 -0
- package/src/app/api/oauth/codebuddy/bulk-import/[jobId]/manual/[workerId]/route.js +30 -0
- package/src/app/api/oauth/codebuddy/bulk-import/[jobId]/route.js +23 -0
- package/src/app/api/oauth/codebuddy/bulk-import/latest/route.js +25 -0
- package/src/app/api/oauth/codebuddy/bulk-import/route.js +49 -0
- package/src/app/api/oauth/codebuddy/quota-cookie/route.js +133 -0
- package/src/app/api/oauth/codex/import-token/route.js +96 -0
- package/src/app/api/oauth/cursor/auto-import/route.js +258 -0
- package/src/app/api/oauth/cursor/import/route.js +100 -0
- package/src/app/api/oauth/gitlab/pat/route.js +62 -0
- package/src/app/api/oauth/iflow/cookie/route.js +137 -0
- package/src/app/api/oauth/kiro/auto-import/route.js +85 -0
- package/src/app/api/oauth/kiro/bulk-import/[jobId]/cancel/route.js +18 -0
- package/src/app/api/oauth/kiro/bulk-import/[jobId]/manual/[workerId]/route.js +29 -0
- package/src/app/api/oauth/kiro/bulk-import/[jobId]/route.js +22 -0
- package/src/app/api/oauth/kiro/bulk-import/latest/route.js +25 -0
- package/src/app/api/oauth/kiro/bulk-import/route.js +49 -0
- package/src/app/api/oauth/kiro/import/route.js +110 -0
- package/src/app/api/oauth/kiro/social-authorize/route.js +27 -0
- package/src/app/api/oauth/kiro/social-exchange/route.js +41 -0
- package/src/app/api/pricing/route.js +134 -0
- package/src/app/api/provider-nodes/[id]/route.js +101 -0
- package/src/app/api/provider-nodes/route.js +104 -0
- package/src/app/api/provider-nodes/validate/route.js +201 -0
- package/src/app/api/providers/[id]/models/route.js +526 -0
- package/src/app/api/providers/[id]/route.js +189 -0
- package/src/app/api/providers/[id]/test/route.js +23 -0
- package/src/app/api/providers/[id]/test/testUtils.js +714 -0
- package/src/app/api/providers/[id]/test-models/route.js +66 -0
- package/src/app/api/providers/client/route.js +126 -0
- package/src/app/api/providers/kilo/free-models/route.js +55 -0
- package/src/app/api/providers/route.js +206 -0
- package/src/app/api/providers/suggested-models/filters.js +20 -0
- package/src/app/api/providers/suggested-models/route.js +32 -0
- package/src/app/api/providers/test-batch/route.js +131 -0
- package/src/app/api/providers/validate/route.js +637 -0
- package/src/app/api/proxy-pools/[id]/route.js +123 -0
- package/src/app/api/proxy-pools/[id]/test/route.js +70 -0
- package/src/app/api/proxy-pools/cloudflare-deploy/route.js +145 -0
- package/src/app/api/proxy-pools/deno-deploy/route.js +175 -0
- package/src/app/api/proxy-pools/route.js +93 -0
- package/src/app/api/proxy-pools/vercel-deploy/route.js +142 -0
- package/src/app/api/settings/database/route.js +36 -0
- package/src/app/api/settings/proxy-test/route.js +23 -0
- package/src/app/api/settings/require-login/route.js +15 -0
- package/src/app/api/settings/route.js +100 -0
- package/src/app/api/shutdown/route.js +24 -0
- package/src/app/api/tags/route.js +18 -0
- package/src/app/api/translator/console-logs/route.js +24 -0
- package/src/app/api/translator/console-logs/stream/route.js +79 -0
- package/src/app/api/translator/load/route.js +45 -0
- package/src/app/api/translator/save/route.js +44 -0
- package/src/app/api/translator/send/route.js +94 -0
- package/src/app/api/translator/translate/route.js +90 -0
- package/src/app/api/tunnel/disable/route.js +12 -0
- package/src/app/api/tunnel/enable/route.js +16 -0
- package/src/app/api/tunnel/status/route.js +13 -0
- package/src/app/api/tunnel/tailscale-check/route.js +50 -0
- package/src/app/api/tunnel/tailscale-disable/route.js +12 -0
- package/src/app/api/tunnel/tailscale-enable/route.js +12 -0
- package/src/app/api/tunnel/tailscale-install/route.js +72 -0
- package/src/app/api/usage/[connectionId]/route.js +188 -0
- package/src/app/api/usage/chart/route.js +21 -0
- package/src/app/api/usage/history/route.js +12 -0
- package/src/app/api/usage/logs/route.js +12 -0
- package/src/app/api/usage/providers/route.js +42 -0
- package/src/app/api/usage/request-details/route.js +57 -0
- package/src/app/api/usage/request-logs/route.js +13 -0
- package/src/app/api/usage/stats/route.js +23 -0
- package/src/app/api/usage/stream/route.js +79 -0
- package/src/app/api/v1/api/chat/route.js +37 -0
- package/src/app/api/v1/audio/speech/route.js +16 -0
- package/src/app/api/v1/audio/transcriptions/route.js +19 -0
- package/src/app/api/v1/audio/voices/route.js +68 -0
- package/src/app/api/v1/chat/completions/route.js +35 -0
- package/src/app/api/v1/embeddings/route.js +21 -0
- package/src/app/api/v1/images/generations/route.js +16 -0
- package/src/app/api/v1/messages/count_tokens/route.js +52 -0
- package/src/app/api/v1/messages/route.js +36 -0
- package/src/app/api/v1/models/[kind]/route.js +55 -0
- package/src/app/api/v1/models/info/route.js +110 -0
- package/src/app/api/v1/models/route.js +451 -0
- package/src/app/api/v1/responses/compact/route.js +37 -0
- package/src/app/api/v1/responses/route.js +30 -0
- package/src/app/api/v1/route.js +1 -0
- package/src/app/api/v1/search/route.js +21 -0
- package/src/app/api/v1/web/fetch/route.js +21 -0
- package/src/app/api/v1beta/models/[...path]/route.js +328 -0
- package/src/app/api/v1beta/models/route.js +44 -0
- package/src/app/api/version/route.js +45 -0
- package/src/app/api/version/shutdown/route.js +15 -0
- package/src/app/api/version/update/route.js +21 -0
- package/src/app/callback/page.js +148 -0
- package/src/app/dashboard/settings/pricing/page.js +173 -0
- package/src/app/favicon.ico +0 -0
- package/src/app/globals.css +496 -0
- package/src/app/landing/components/AnimatedBackground.js +57 -0
- package/src/app/landing/components/Features.js +133 -0
- package/src/app/landing/components/FlowAnimation.js +175 -0
- package/src/app/landing/components/Footer.js +61 -0
- package/src/app/landing/components/GetStarted.js +97 -0
- package/src/app/landing/components/HeroSection.js +47 -0
- package/src/app/landing/components/HowItWorks.js +66 -0
- package/src/app/landing/components/Navigation.js +72 -0
- package/src/app/landing/page.js +106 -0
- package/src/app/layout.js +49 -0
- package/src/app/login/page.js +197 -0
- package/src/app/manifest.js +30 -0
- package/src/app/page.js +5 -0
- package/src/dashboardGuard.js +242 -0
- package/src/i18n/RuntimeI18nProvider.js +27 -0
- package/src/i18n/config.js +146 -0
- package/src/i18n/runtime.js +162 -0
- package/src/lib/appUpdater.js +200 -0
- package/src/lib/auth/dashboardSession.js +68 -0
- package/src/lib/auth/loginLimiter.js +52 -0
- package/src/lib/auth/oidc.js +234 -0
- package/src/lib/consoleLogBuffer.js +79 -0
- package/src/lib/dataDir.js +29 -0
- package/src/lib/db/adapters/betterSqliteAdapter.js +55 -0
- package/src/lib/db/adapters/bunSqliteAdapter.js +63 -0
- package/src/lib/db/adapters/nodeSqliteAdapter.js +84 -0
- package/src/lib/db/adapters/sqljsAdapter.js +115 -0
- package/src/lib/db/backup.js +35 -0
- package/src/lib/db/driver.js +85 -0
- package/src/lib/db/helpers/jsonCol.js +9 -0
- package/src/lib/db/helpers/kvStore.js +39 -0
- package/src/lib/db/helpers/metaStore.js +22 -0
- package/src/lib/db/index.js +171 -0
- package/src/lib/db/migrate.js +286 -0
- package/src/lib/db/migrations/001-initial.js +14 -0
- package/src/lib/db/migrations/index.js +10 -0
- package/src/lib/db/paths.js +18 -0
- package/src/lib/db/repos/aliasRepo.js +62 -0
- package/src/lib/db/repos/apiKeysRepo.js +75 -0
- package/src/lib/db/repos/combosRepo.js +73 -0
- package/src/lib/db/repos/connectionsRepo.js +226 -0
- package/src/lib/db/repos/disabledModelsRepo.js +56 -0
- package/src/lib/db/repos/nodesRepo.js +95 -0
- package/src/lib/db/repos/pricingRepo.js +108 -0
- package/src/lib/db/repos/proxyPoolsRepo.js +103 -0
- package/src/lib/db/repos/requestDetailsRepo.js +259 -0
- package/src/lib/db/repos/settingsRepo.js +104 -0
- package/src/lib/db/repos/usageRepo.js +731 -0
- package/src/lib/db/schema.js +157 -0
- package/src/lib/db/version.js +21 -0
- package/src/lib/disabledModelsDb.js +4 -0
- package/src/lib/localDb.js +21 -0
- package/src/lib/mcp/stdioSseBridge.js +198 -0
- package/src/lib/mitmAliasCache.js +46 -0
- package/src/lib/network/connectionProxy.js +160 -0
- package/src/lib/network/initOutboundProxy.js +25 -0
- package/src/lib/network/outboundProxy.js +68 -0
- package/src/lib/network/proxyTest.js +91 -0
- package/src/lib/oauth/constants/oauth.js +284 -0
- package/src/lib/oauth/constants/xai.js +61 -0
- package/src/lib/oauth/providers.js +1506 -0
- package/src/lib/oauth/services/antigravity.js +321 -0
- package/src/lib/oauth/services/claude.js +136 -0
- package/src/lib/oauth/services/codebuddyBulkImportManager.js +454 -0
- package/src/lib/oauth/services/codex.js +144 -0
- package/src/lib/oauth/services/cursor.js +179 -0
- package/src/lib/oauth/services/gemini.js +240 -0
- package/src/lib/oauth/services/github.js +225 -0
- package/src/lib/oauth/services/iflow.js +202 -0
- package/src/lib/oauth/services/index.js +17 -0
- package/src/lib/oauth/services/kiro.js +334 -0
- package/src/lib/oauth/services/kiroBulkImportManager.js +778 -0
- package/src/lib/oauth/services/kiroConnections.js +93 -0
- package/src/lib/oauth/services/kiroGoogleAutomation.js +1136 -0
- package/src/lib/oauth/services/oauth.js +157 -0
- package/src/lib/oauth/services/openai.js +123 -0
- package/src/lib/oauth/services/qoder.js +216 -0
- package/src/lib/oauth/services/qwen.js +170 -0
- package/src/lib/oauth/services/xai.js +238 -0
- package/src/lib/oauth/utils/banner.js +63 -0
- package/src/lib/oauth/utils/pkce.js +39 -0
- package/src/lib/oauth/utils/server.js +415 -0
- package/src/lib/oauth/utils/ui.js +48 -0
- package/src/lib/providerNormalization.js +45 -0
- package/src/lib/qoder/constants.js +64 -0
- package/src/lib/qoder/cosy.js +175 -0
- package/src/lib/qoder/encoding.js +55 -0
- package/src/lib/requestDetailsDb.js +4 -0
- package/src/lib/tunnel/cloudflare/cloudflared.js +449 -0
- package/src/lib/tunnel/cloudflare/config.js +9 -0
- package/src/lib/tunnel/cloudflare/healthCheck.js +29 -0
- package/src/lib/tunnel/cloudflare/manager.js +151 -0
- package/src/lib/tunnel/cloudflare/pid.js +23 -0
- package/src/lib/tunnel/index.js +48 -0
- package/src/lib/tunnel/shared/dnsResolver.js +17 -0
- package/src/lib/tunnel/shared/internetCheck.js +26 -0
- package/src/lib/tunnel/shared/state.js +41 -0
- package/src/lib/tunnel/shared/watchdogConfig.js +8 -0
- package/src/lib/tunnel/tailscale/config.js +7 -0
- package/src/lib/tunnel/tailscale/healthCheck.js +29 -0
- package/src/lib/tunnel/tailscale/manager.js +129 -0
- package/src/lib/tunnel/tailscale/tailscale.js +790 -0
- package/src/lib/updater/updater.js +235 -0
- package/src/lib/usage/fetcher.js +208 -0
- package/src/lib/usageDb.js +7 -0
- package/src/mitm/antigravityIdeVersion.js +50 -0
- package/src/mitm/cert/generate.js +32 -0
- package/src/mitm/cert/install.js +269 -0
- package/src/mitm/cert/rootCA.js +173 -0
- package/src/mitm/config.js +87 -0
- package/src/mitm/dbReader.js +22 -0
- package/src/mitm/dns/dnsConfig.js +266 -0
- package/src/mitm/handlers/antigravity.js +33 -0
- package/src/mitm/handlers/base.js +226 -0
- package/src/mitm/handlers/copilot.js +35 -0
- package/src/mitm/handlers/cursor.js +15 -0
- package/src/mitm/handlers/kiro.js +526 -0
- package/src/mitm/logger.js +106 -0
- package/src/mitm/manager.js +851 -0
- package/src/mitm/paths.js +32 -0
- package/src/mitm/server.js +435 -0
- package/src/mitm/winElevated.js +81 -0
- package/src/models/index.js +38 -0
- package/src/proxy.js +5 -0
- package/src/shared/components/AddCustomEmbeddingModal.js +183 -0
- package/src/shared/components/Avatar.js +88 -0
- package/src/shared/components/Badge.js +54 -0
- package/src/shared/components/BulkAccountAutomationModal.js +508 -0
- package/src/shared/components/Button.js +56 -0
- package/src/shared/components/Card.js +116 -0
- package/src/shared/components/ChangelogModal.js +97 -0
- package/src/shared/components/CodeBuddyQuotaCookieModal.js +109 -0
- package/src/shared/components/ComboFormModal.js +176 -0
- package/src/shared/components/CursorAuthModal.js +212 -0
- package/src/shared/components/DonateModal.js +136 -0
- package/src/shared/components/Drawer.js +82 -0
- package/src/shared/components/EditConnectionModal.js +286 -0
- package/src/shared/components/Footer.js +132 -0
- package/src/shared/components/GitLabAuthModal.js +194 -0
- package/src/shared/components/Header.js +380 -0
- package/src/shared/components/HeaderLanguage.js +46 -0
- package/src/shared/components/HeaderMenu.js +126 -0
- package/src/shared/components/IFlowCookieModal.js +132 -0
- package/src/shared/components/Input.js +65 -0
- package/src/shared/components/KiroAuthModal.js +1171 -0
- package/src/shared/components/KiroOAuthWrapper.js +149 -0
- package/src/shared/components/KiroSocialOAuthModal.js +205 -0
- package/src/shared/components/LanguageSwitcher.js +190 -0
- package/src/shared/components/Loading.js +75 -0
- package/src/shared/components/ManualConfigModal.js +44 -0
- package/src/shared/components/McpMarketplaceModal.js +255 -0
- package/src/shared/components/Modal.js +146 -0
- package/src/shared/components/ModelSelectModal.js +537 -0
- package/src/shared/components/NineRemoteButton.js +23 -0
- package/src/shared/components/NineRemotePromoModal.js +99 -0
- package/src/shared/components/NoAuthProxyCard.js +86 -0
- package/src/shared/components/OAuthModal.js +682 -0
- package/src/shared/components/Pagination.js +150 -0
- package/src/shared/components/PricingModal.js +208 -0
- package/src/shared/components/ProviderIcon.js +63 -0
- package/src/shared/components/ProviderInfoCard.js +82 -0
- package/src/shared/components/RequestLogger.js +121 -0
- package/src/shared/components/SegmentedControl.js +48 -0
- package/src/shared/components/Select.js +67 -0
- package/src/shared/components/Sidebar.js +441 -0
- package/src/shared/components/ThemeProvider.js +15 -0
- package/src/shared/components/ThemeToggle.js +42 -0
- package/src/shared/components/Toggle.js +69 -0
- package/src/shared/components/Tooltip.js +25 -0
- package/src/shared/components/UsageStats.js +505 -0
- package/src/shared/components/index.js +46 -0
- package/src/shared/components/layouts/AuthLayout.js +29 -0
- package/src/shared/components/layouts/DashboardLayout.js +104 -0
- package/src/shared/components/layouts/index.js +4 -0
- package/src/shared/constants/cliTools.js +397 -0
- package/src/shared/constants/colors.js +77 -0
- package/src/shared/constants/config.js +99 -0
- package/src/shared/constants/coworkPlugins.js +75 -0
- package/src/shared/constants/index.js +4 -0
- package/src/shared/constants/locales.js +36 -0
- package/src/shared/constants/mitmToolHosts.js +12 -0
- package/src/shared/constants/models.js +38 -0
- package/src/shared/constants/pricing.js +303 -0
- package/src/shared/constants/providers.js +289 -0
- package/src/shared/constants/skills.js +78 -0
- package/src/shared/constants/ttsProviders.js +138 -0
- package/src/shared/hooks/index.js +2 -0
- package/src/shared/hooks/useCopyToClipboard.js +43 -0
- package/src/shared/hooks/useTheme.js +60 -0
- package/src/shared/services/bootstrap.js +12 -0
- package/src/shared/services/initializeApp.js +268 -0
- package/src/shared/utils/api.js +93 -0
- package/src/shared/utils/apiKey.js +98 -0
- package/src/shared/utils/clineAuth.js +37 -0
- package/src/shared/utils/cn.js +11 -0
- package/src/shared/utils/connectionStatus.js +162 -0
- package/src/shared/utils/index.js +40 -0
- package/src/shared/utils/machine.js +6 -0
- package/src/shared/utils/machineId.js +66 -0
- package/src/shared/utils/providerModelsFetcher.js +30 -0
- package/src/sse/handlers/chat.js +261 -0
- package/src/sse/handlers/embeddings.js +141 -0
- package/src/sse/handlers/fetch.js +213 -0
- package/src/sse/handlers/imageGeneration.js +142 -0
- package/src/sse/handlers/search.js +206 -0
- package/src/sse/handlers/stt.js +88 -0
- package/src/sse/handlers/tts.js +114 -0
- package/src/sse/services/auth.js +346 -0
- package/src/sse/services/codexGateway.js +215 -0
- package/src/sse/services/model.js +99 -0
- package/src/sse/services/tokenRefresh.js +319 -0
- package/src/sse/utils/logger.js +75 -0
- package/src/store/headerSearchStore.js +19 -0
- package/src/store/index.js +6 -0
- package/src/store/notificationStore.js +45 -0
- package/src/store/providerStore.js +55 -0
- package/src/store/settingsStore.js +51 -0
- package/src/store/themeStore.js +54 -0
- package/src/store/userStore.js +20 -0
- package/start.sh +4 -0
|
@@ -0,0 +1,731 @@
|
|
|
1
|
+
import { EventEmitter } from "events";
|
|
2
|
+
import { getAdapter } from "../driver.js";
|
|
3
|
+
import { parseJson, stringifyJson } from "../helpers/jsonCol.js";
|
|
4
|
+
import { getMeta, setMeta } from "../helpers/metaStore.js";
|
|
5
|
+
|
|
6
|
+
const PENDING_TIMEOUT_MS = 60 * 1000;
|
|
7
|
+
const RING_CAP = 50;
|
|
8
|
+
const CONN_CACHE_TTL_MS = 30 * 1000;
|
|
9
|
+
const PERIOD_MS = { "24h": 86400000, "7d": 604800000, "30d": 2592000000, "60d": 5184000000 };
|
|
10
|
+
|
|
11
|
+
// In-memory state shared across Next.js modules
|
|
12
|
+
if (!global._pendingRequests) global._pendingRequests = { byModel: {}, byAccount: {} };
|
|
13
|
+
if (!global._lastErrorProvider) global._lastErrorProvider = { provider: "", ts: 0 };
|
|
14
|
+
if (!global._statsEmitter) {
|
|
15
|
+
global._statsEmitter = new EventEmitter();
|
|
16
|
+
global._statsEmitter.setMaxListeners(50);
|
|
17
|
+
}
|
|
18
|
+
if (!global._pendingTimers) global._pendingTimers = {};
|
|
19
|
+
if (!global._recentRing) global._recentRing = { items: [], initialized: false };
|
|
20
|
+
if (!global._connectionMapCache) global._connectionMapCache = { map: {}, ts: 0 };
|
|
21
|
+
|
|
22
|
+
const pendingRequests = global._pendingRequests;
|
|
23
|
+
const lastErrorProvider = global._lastErrorProvider;
|
|
24
|
+
const pendingTimers = global._pendingTimers;
|
|
25
|
+
const recentRing = global._recentRing;
|
|
26
|
+
const connCache = global._connectionMapCache;
|
|
27
|
+
|
|
28
|
+
export const statsEmitter = global._statsEmitter;
|
|
29
|
+
|
|
30
|
+
function getLocalDateKey(timestamp) {
|
|
31
|
+
const d = timestamp ? new Date(timestamp) : new Date();
|
|
32
|
+
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function addToCounter(target, key, values) {
|
|
36
|
+
if (!target[key]) target[key] = { requests: 0, promptTokens: 0, completionTokens: 0, cost: 0 };
|
|
37
|
+
target[key].requests += values.requests || 1;
|
|
38
|
+
target[key].promptTokens += values.promptTokens || 0;
|
|
39
|
+
target[key].completionTokens += values.completionTokens || 0;
|
|
40
|
+
target[key].cost += values.cost || 0;
|
|
41
|
+
if (values.meta) Object.assign(target[key], values.meta);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function aggregateEntryToDay(day, entry) {
|
|
45
|
+
const promptTokens = entry.tokens?.prompt_tokens || entry.tokens?.input_tokens || 0;
|
|
46
|
+
const completionTokens = entry.tokens?.completion_tokens || entry.tokens?.output_tokens || 0;
|
|
47
|
+
const cost = entry.cost || 0;
|
|
48
|
+
const vals = { promptTokens, completionTokens, cost };
|
|
49
|
+
|
|
50
|
+
day.requests = (day.requests || 0) + 1;
|
|
51
|
+
day.promptTokens = (day.promptTokens || 0) + promptTokens;
|
|
52
|
+
day.completionTokens = (day.completionTokens || 0) + completionTokens;
|
|
53
|
+
day.cost = (day.cost || 0) + cost;
|
|
54
|
+
|
|
55
|
+
day.byProvider ||= {};
|
|
56
|
+
day.byModel ||= {};
|
|
57
|
+
day.byAccount ||= {};
|
|
58
|
+
day.byApiKey ||= {};
|
|
59
|
+
day.byEndpoint ||= {};
|
|
60
|
+
|
|
61
|
+
if (entry.provider) addToCounter(day.byProvider, entry.provider, vals);
|
|
62
|
+
|
|
63
|
+
const modelKey = entry.provider ? `${entry.model}|${entry.provider}` : entry.model;
|
|
64
|
+
addToCounter(day.byModel, modelKey, { ...vals, meta: { rawModel: entry.model, provider: entry.provider } });
|
|
65
|
+
|
|
66
|
+
if (entry.connectionId) {
|
|
67
|
+
addToCounter(day.byAccount, entry.connectionId, { ...vals, meta: { rawModel: entry.model, provider: entry.provider } });
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const apiKeyVal = entry.apiKey && typeof entry.apiKey === "string" ? entry.apiKey : "local-no-key";
|
|
71
|
+
const akModelKey = `${apiKeyVal}|${entry.model}|${entry.provider || "unknown"}`;
|
|
72
|
+
addToCounter(day.byApiKey, akModelKey, { ...vals, meta: { rawModel: entry.model, provider: entry.provider, apiKey: entry.apiKey || null } });
|
|
73
|
+
|
|
74
|
+
const endpoint = entry.endpoint || "Unknown";
|
|
75
|
+
const epKey = `${endpoint}|${entry.model}|${entry.provider || "unknown"}`;
|
|
76
|
+
addToCounter(day.byEndpoint, epKey, { ...vals, meta: { endpoint, rawModel: entry.model, provider: entry.provider } });
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function pushToRing(entry) {
|
|
80
|
+
recentRing.items.push(entry);
|
|
81
|
+
if (recentRing.items.length > RING_CAP) {
|
|
82
|
+
recentRing.items = recentRing.items.slice(-RING_CAP);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function getConnectionMapCached() {
|
|
87
|
+
if (Date.now() - connCache.ts < CONN_CACHE_TTL_MS) return connCache.map;
|
|
88
|
+
try {
|
|
89
|
+
const { getProviderConnections } = await import("./connectionsRepo.js");
|
|
90
|
+
const all = await getProviderConnections();
|
|
91
|
+
const map = {};
|
|
92
|
+
for (const c of all) map[c.id] = c.name || c.email || c.id;
|
|
93
|
+
connCache.map = map;
|
|
94
|
+
connCache.ts = Date.now();
|
|
95
|
+
} catch {}
|
|
96
|
+
return connCache.map;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async function ensureRingInitialized() {
|
|
100
|
+
if (recentRing.initialized) return;
|
|
101
|
+
recentRing.initialized = true;
|
|
102
|
+
try {
|
|
103
|
+
const db = await getAdapter();
|
|
104
|
+
const rows = db.all(`SELECT timestamp, provider, model, connectionId, apiKey, endpoint, cost, status, tokens FROM usageHistory ORDER BY id DESC LIMIT ?`, [RING_CAP]);
|
|
105
|
+
recentRing.items = rows.reverse().map((r) => ({
|
|
106
|
+
timestamp: r.timestamp, provider: r.provider, model: r.model, connectionId: r.connectionId,
|
|
107
|
+
apiKey: r.apiKey, endpoint: r.endpoint, cost: r.cost, status: r.status,
|
|
108
|
+
tokens: parseJson(r.tokens, {}),
|
|
109
|
+
}));
|
|
110
|
+
} catch {}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async function calculateCost(provider, model, tokens) {
|
|
114
|
+
if (!tokens || !provider || !model) return 0;
|
|
115
|
+
try {
|
|
116
|
+
const { getPricingForModel } = await import("./pricingRepo.js");
|
|
117
|
+
const pricing = await getPricingForModel(provider, model);
|
|
118
|
+
if (!pricing) return 0;
|
|
119
|
+
|
|
120
|
+
let cost = 0;
|
|
121
|
+
const inputTokens = tokens.prompt_tokens || tokens.input_tokens || 0;
|
|
122
|
+
const cachedTokens = tokens.cached_tokens || tokens.cache_read_input_tokens || 0;
|
|
123
|
+
const nonCachedInput = Math.max(0, inputTokens - cachedTokens);
|
|
124
|
+
cost += nonCachedInput * (pricing.input / 1000000);
|
|
125
|
+
|
|
126
|
+
if (cachedTokens > 0) {
|
|
127
|
+
const cachedRate = pricing.cached || pricing.input;
|
|
128
|
+
cost += cachedTokens * (cachedRate / 1000000);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const outputTokens = tokens.completion_tokens || tokens.output_tokens || 0;
|
|
132
|
+
cost += outputTokens * (pricing.output / 1000000);
|
|
133
|
+
|
|
134
|
+
const reasoningTokens = tokens.reasoning_tokens || 0;
|
|
135
|
+
if (reasoningTokens > 0) {
|
|
136
|
+
const rate = pricing.reasoning || pricing.output;
|
|
137
|
+
cost += reasoningTokens * (rate / 1000000);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const cacheCreationTokens = tokens.cache_creation_input_tokens || 0;
|
|
141
|
+
if (cacheCreationTokens > 0) {
|
|
142
|
+
const rate = pricing.cache_creation || pricing.input;
|
|
143
|
+
cost += cacheCreationTokens * (rate / 1000000);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
return cost;
|
|
147
|
+
} catch (e) {
|
|
148
|
+
console.error("Error calculating cost:", e);
|
|
149
|
+
return 0;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function trackPendingRequest(model, provider, connectionId, started, error = false) {
|
|
154
|
+
const modelKey = provider ? `${model} (${provider})` : model;
|
|
155
|
+
const timerKey = `${connectionId}|${modelKey}`;
|
|
156
|
+
|
|
157
|
+
if (!pendingRequests.byModel[modelKey]) pendingRequests.byModel[modelKey] = 0;
|
|
158
|
+
pendingRequests.byModel[modelKey] = Math.max(0, pendingRequests.byModel[modelKey] + (started ? 1 : -1));
|
|
159
|
+
if (pendingRequests.byModel[modelKey] === 0) delete pendingRequests.byModel[modelKey];
|
|
160
|
+
|
|
161
|
+
if (connectionId) {
|
|
162
|
+
if (!pendingRequests.byAccount[connectionId]) pendingRequests.byAccount[connectionId] = {};
|
|
163
|
+
if (!pendingRequests.byAccount[connectionId][modelKey]) pendingRequests.byAccount[connectionId][modelKey] = 0;
|
|
164
|
+
pendingRequests.byAccount[connectionId][modelKey] = Math.max(0, pendingRequests.byAccount[connectionId][modelKey] + (started ? 1 : -1));
|
|
165
|
+
if (pendingRequests.byAccount[connectionId][modelKey] === 0) {
|
|
166
|
+
delete pendingRequests.byAccount[connectionId][modelKey];
|
|
167
|
+
if (Object.keys(pendingRequests.byAccount[connectionId]).length === 0) {
|
|
168
|
+
delete pendingRequests.byAccount[connectionId];
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
if (started) {
|
|
174
|
+
clearTimeout(pendingTimers[timerKey]);
|
|
175
|
+
pendingTimers[timerKey] = setTimeout(() => {
|
|
176
|
+
delete pendingTimers[timerKey];
|
|
177
|
+
if (pendingRequests.byModel[modelKey] > 0) pendingRequests.byModel[modelKey] = 0;
|
|
178
|
+
if (connectionId && pendingRequests.byAccount[connectionId]?.[modelKey] > 0) {
|
|
179
|
+
pendingRequests.byAccount[connectionId][modelKey] = 0;
|
|
180
|
+
}
|
|
181
|
+
statsEmitter.emit("pending");
|
|
182
|
+
}, PENDING_TIMEOUT_MS);
|
|
183
|
+
} else {
|
|
184
|
+
clearTimeout(pendingTimers[timerKey]);
|
|
185
|
+
delete pendingTimers[timerKey];
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
if (!started && error && provider) {
|
|
189
|
+
lastErrorProvider.provider = provider.toLowerCase();
|
|
190
|
+
lastErrorProvider.ts = Date.now();
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const t = new Date().toLocaleTimeString("en-US", { hour12: false, hour: "2-digit", minute: "2-digit", second: "2-digit" });
|
|
194
|
+
console.log(`[${t}] [PENDING] ${started ? "START" : "END"}${error ? " (ERROR)" : ""} | provider=${provider} | model=${model}`);
|
|
195
|
+
statsEmitter.emit("pending");
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export async function getActiveRequests() {
|
|
199
|
+
const activeRequests = [];
|
|
200
|
+
const connectionMap = await getConnectionMapCached();
|
|
201
|
+
|
|
202
|
+
for (const [connectionId, models] of Object.entries(pendingRequests.byAccount)) {
|
|
203
|
+
for (const [modelKey, count] of Object.entries(models)) {
|
|
204
|
+
if (count > 0) {
|
|
205
|
+
const accountName = connectionMap[connectionId] || `Account ${connectionId.slice(0, 8)}...`;
|
|
206
|
+
const match = modelKey.match(/^(.*) \((.*)\)$/);
|
|
207
|
+
activeRequests.push({
|
|
208
|
+
model: match ? match[1] : modelKey,
|
|
209
|
+
provider: match ? match[2] : "unknown",
|
|
210
|
+
account: accountName, count,
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
await ensureRingInitialized();
|
|
217
|
+
const seen = new Set();
|
|
218
|
+
const recentRequests = [...recentRing.items]
|
|
219
|
+
.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
|
|
220
|
+
.map((e) => {
|
|
221
|
+
const t = e.tokens || {};
|
|
222
|
+
return {
|
|
223
|
+
timestamp: e.timestamp, model: e.model, provider: e.provider || "",
|
|
224
|
+
promptTokens: t.prompt_tokens || t.input_tokens || 0,
|
|
225
|
+
completionTokens: t.completion_tokens || t.output_tokens || 0,
|
|
226
|
+
status: e.status || "ok",
|
|
227
|
+
};
|
|
228
|
+
})
|
|
229
|
+
.filter((e) => {
|
|
230
|
+
if (e.promptTokens === 0 && e.completionTokens === 0) return false;
|
|
231
|
+
const minute = e.timestamp ? e.timestamp.slice(0, 16) : "";
|
|
232
|
+
const key = `${e.model}|${e.provider}|${e.promptTokens}|${e.completionTokens}|${minute}`;
|
|
233
|
+
if (seen.has(key)) return false;
|
|
234
|
+
seen.add(key);
|
|
235
|
+
return true;
|
|
236
|
+
})
|
|
237
|
+
.slice(0, 20);
|
|
238
|
+
|
|
239
|
+
const errorProvider = (Date.now() - lastErrorProvider.ts < 10000) ? lastErrorProvider.provider : "";
|
|
240
|
+
return { activeRequests, recentRequests, errorProvider };
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export async function saveRequestUsage(entry) {
|
|
244
|
+
try {
|
|
245
|
+
const db = await getAdapter();
|
|
246
|
+
|
|
247
|
+
if (!entry.timestamp) entry.timestamp = new Date().toISOString();
|
|
248
|
+
entry.cost = await calculateCost(entry.provider, entry.model, entry.tokens);
|
|
249
|
+
|
|
250
|
+
const tokens = entry.tokens || {};
|
|
251
|
+
const promptTokens = tokens.prompt_tokens || tokens.input_tokens || 0;
|
|
252
|
+
const completionTokens = tokens.completion_tokens || tokens.output_tokens || 0;
|
|
253
|
+
|
|
254
|
+
// All 3 writes (history insert, daily upsert, lifetime counter) in ONE transaction.
|
|
255
|
+
// better-sqlite3 is sync → no JS yield mid-transaction → no race in same process.
|
|
256
|
+
db.transaction(() => {
|
|
257
|
+
db.run(
|
|
258
|
+
`INSERT INTO usageHistory(timestamp, provider, model, connectionId, apiKey, endpoint, promptTokens, completionTokens, cost, status, tokens, meta) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
259
|
+
[
|
|
260
|
+
entry.timestamp, entry.provider || null, entry.model || null,
|
|
261
|
+
entry.connectionId || null, entry.apiKey || null, entry.endpoint || null,
|
|
262
|
+
promptTokens, completionTokens, entry.cost || 0, entry.status || "ok",
|
|
263
|
+
stringifyJson(tokens), stringifyJson({}),
|
|
264
|
+
]
|
|
265
|
+
);
|
|
266
|
+
|
|
267
|
+
const dateKey = getLocalDateKey(entry.timestamp);
|
|
268
|
+
const row = db.get(`SELECT data FROM usageDaily WHERE dateKey = ?`, [dateKey]);
|
|
269
|
+
const day = row ? parseJson(row.data, {}) : {
|
|
270
|
+
requests: 0, promptTokens: 0, completionTokens: 0, cost: 0,
|
|
271
|
+
byProvider: {}, byModel: {}, byAccount: {}, byApiKey: {}, byEndpoint: {},
|
|
272
|
+
};
|
|
273
|
+
aggregateEntryToDay(day, entry);
|
|
274
|
+
db.run(`INSERT INTO usageDaily(dateKey, data) VALUES(?, ?) ON CONFLICT(dateKey) DO UPDATE SET data = excluded.data`, [dateKey, stringifyJson(day)]);
|
|
275
|
+
|
|
276
|
+
// Atomic counter increment in same transaction
|
|
277
|
+
const cur = db.get(`SELECT value FROM _meta WHERE key = 'totalRequestsLifetime'`);
|
|
278
|
+
const next = (cur ? parseInt(cur.value, 10) : 0) + 1;
|
|
279
|
+
db.run(`INSERT INTO _meta(key, value) VALUES('totalRequestsLifetime', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`, [String(next)]);
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
pushToRing(entry);
|
|
283
|
+
statsEmitter.emit("update");
|
|
284
|
+
} catch (e) {
|
|
285
|
+
console.error("Failed to save usage stats:", e);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
export async function getUsageHistory(filter = {}) {
|
|
290
|
+
const db = await getAdapter();
|
|
291
|
+
const conds = [];
|
|
292
|
+
const params = [];
|
|
293
|
+
|
|
294
|
+
if (filter.provider) { conds.push("provider = ?"); params.push(filter.provider); }
|
|
295
|
+
if (filter.model) { conds.push("model = ?"); params.push(filter.model); }
|
|
296
|
+
if (filter.startDate) { conds.push("timestamp >= ?"); params.push(new Date(filter.startDate).toISOString()); }
|
|
297
|
+
if (filter.endDate) { conds.push("timestamp <= ?"); params.push(new Date(filter.endDate).toISOString()); }
|
|
298
|
+
|
|
299
|
+
const where = conds.length ? `WHERE ${conds.join(" AND ")}` : "";
|
|
300
|
+
const rows = db.all(`SELECT timestamp, provider, model, connectionId, apiKey, endpoint, cost, status, tokens FROM usageHistory ${where} ORDER BY id ASC`, params);
|
|
301
|
+
|
|
302
|
+
return rows.map((r) => ({
|
|
303
|
+
timestamp: r.timestamp, provider: r.provider, model: r.model,
|
|
304
|
+
connectionId: r.connectionId, apiKey: r.apiKey, endpoint: r.endpoint,
|
|
305
|
+
cost: r.cost, status: r.status, tokens: parseJson(r.tokens, {}),
|
|
306
|
+
}));
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function loadDaysInRange(adapter, maxDays) {
|
|
310
|
+
if (maxDays == null) {
|
|
311
|
+
return adapter.all(`SELECT dateKey, data FROM usageDaily`);
|
|
312
|
+
}
|
|
313
|
+
const today = new Date();
|
|
314
|
+
const cutoff = new Date(today.getFullYear(), today.getMonth(), today.getDate() - maxDays + 1);
|
|
315
|
+
const cutoffKey = `${cutoff.getFullYear()}-${String(cutoff.getMonth() + 1).padStart(2, "0")}-${String(cutoff.getDate()).padStart(2, "0")}`;
|
|
316
|
+
return adapter.all(`SELECT dateKey, data FROM usageDaily WHERE dateKey >= ?`, [cutoffKey]);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
export async function getUsageStats(period = "all") {
|
|
320
|
+
const db = await getAdapter();
|
|
321
|
+
|
|
322
|
+
const [{ getProviderConnections }, { getApiKeys }, { getProviderNodes }] = await Promise.all([
|
|
323
|
+
import("./connectionsRepo.js"),
|
|
324
|
+
import("./apiKeysRepo.js"),
|
|
325
|
+
import("./nodesRepo.js"),
|
|
326
|
+
]);
|
|
327
|
+
|
|
328
|
+
let allConnections = [];
|
|
329
|
+
try { allConnections = await getProviderConnections(); } catch {}
|
|
330
|
+
const connectionMap = {};
|
|
331
|
+
for (const c of allConnections) connectionMap[c.id] = c.name || c.email || c.id;
|
|
332
|
+
|
|
333
|
+
const providerNodeNameMap = {};
|
|
334
|
+
try {
|
|
335
|
+
const nodes = await getProviderNodes();
|
|
336
|
+
for (const n of nodes) if (n.id && n.name) providerNodeNameMap[n.id] = n.name;
|
|
337
|
+
} catch {}
|
|
338
|
+
|
|
339
|
+
let allApiKeys = [];
|
|
340
|
+
try { allApiKeys = await getApiKeys(); } catch {}
|
|
341
|
+
const apiKeyMap = {};
|
|
342
|
+
for (const k of allApiKeys) apiKeyMap[k.key] = { name: k.name, id: k.id, createdAt: k.createdAt };
|
|
343
|
+
|
|
344
|
+
// recentRequests from live history (last 100 entries enough for 20 deduped)
|
|
345
|
+
const recentRows = db.all(`SELECT timestamp, provider, model, tokens, status FROM usageHistory ORDER BY id DESC LIMIT 100`);
|
|
346
|
+
const seen = new Set();
|
|
347
|
+
const recentRequests = recentRows
|
|
348
|
+
.map((r) => {
|
|
349
|
+
const t = parseJson(r.tokens, {}) || {};
|
|
350
|
+
return {
|
|
351
|
+
timestamp: r.timestamp, model: r.model, provider: r.provider || "",
|
|
352
|
+
promptTokens: t.prompt_tokens || t.input_tokens || 0,
|
|
353
|
+
completionTokens: t.completion_tokens || t.output_tokens || 0,
|
|
354
|
+
status: r.status || "ok",
|
|
355
|
+
};
|
|
356
|
+
})
|
|
357
|
+
.filter((e) => {
|
|
358
|
+
if (e.promptTokens === 0 && e.completionTokens === 0) return false;
|
|
359
|
+
const minute = e.timestamp ? e.timestamp.slice(0, 16) : "";
|
|
360
|
+
const key = `${e.model}|${e.provider}|${e.promptTokens}|${e.completionTokens}|${minute}`;
|
|
361
|
+
if (seen.has(key)) return false;
|
|
362
|
+
seen.add(key);
|
|
363
|
+
return true;
|
|
364
|
+
})
|
|
365
|
+
.slice(0, 20);
|
|
366
|
+
|
|
367
|
+
const stats = {
|
|
368
|
+
totalRequests: 0,
|
|
369
|
+
totalPromptTokens: 0, totalCompletionTokens: 0, totalCost: 0,
|
|
370
|
+
byProvider: {}, byModel: {}, byAccount: {}, byApiKey: {}, byEndpoint: {},
|
|
371
|
+
last10Minutes: [],
|
|
372
|
+
pending: pendingRequests,
|
|
373
|
+
activeRequests: [],
|
|
374
|
+
recentRequests,
|
|
375
|
+
errorProvider: (Date.now() - lastErrorProvider.ts < 10000) ? lastErrorProvider.provider : "",
|
|
376
|
+
};
|
|
377
|
+
|
|
378
|
+
// Active requests
|
|
379
|
+
for (const [connectionId, models] of Object.entries(pendingRequests.byAccount)) {
|
|
380
|
+
for (const [modelKey, count] of Object.entries(models)) {
|
|
381
|
+
if (count > 0) {
|
|
382
|
+
const accountName = connectionMap[connectionId] || `Account ${connectionId.slice(0, 8)}...`;
|
|
383
|
+
const match = modelKey.match(/^(.*) \((.*)\)$/);
|
|
384
|
+
stats.activeRequests.push({
|
|
385
|
+
model: match ? match[1] : modelKey,
|
|
386
|
+
provider: match ? match[2] : "unknown",
|
|
387
|
+
account: accountName, count,
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// last10Minutes — query 10min window
|
|
394
|
+
const now = new Date();
|
|
395
|
+
const currentMinuteStart = new Date(Math.floor(now.getTime() / 60000) * 60000);
|
|
396
|
+
const tenMinutesAgo = new Date(currentMinuteStart.getTime() - 9 * 60 * 1000);
|
|
397
|
+
const bucketMap = {};
|
|
398
|
+
for (let i = 0; i < 10; i++) {
|
|
399
|
+
const ts = currentMinuteStart.getTime() - (9 - i) * 60 * 1000;
|
|
400
|
+
bucketMap[ts] = { requests: 0, promptTokens: 0, completionTokens: 0, cost: 0 };
|
|
401
|
+
stats.last10Minutes.push(bucketMap[ts]);
|
|
402
|
+
}
|
|
403
|
+
const recent10 = db.all(
|
|
404
|
+
`SELECT timestamp, promptTokens, completionTokens, cost FROM usageHistory WHERE timestamp >= ? AND timestamp <= ?`,
|
|
405
|
+
[tenMinutesAgo.toISOString(), now.toISOString()]
|
|
406
|
+
);
|
|
407
|
+
for (const r of recent10) {
|
|
408
|
+
const tt = new Date(r.timestamp).getTime();
|
|
409
|
+
const minuteStart = Math.floor(tt / 60000) * 60000;
|
|
410
|
+
if (bucketMap[minuteStart]) {
|
|
411
|
+
bucketMap[minuteStart].requests++;
|
|
412
|
+
bucketMap[minuteStart].promptTokens += r.promptTokens || 0;
|
|
413
|
+
bucketMap[minuteStart].completionTokens += r.completionTokens || 0;
|
|
414
|
+
bucketMap[minuteStart].cost += r.cost || 0;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
const useDailySummary = period !== "24h" && period !== "today";
|
|
419
|
+
|
|
420
|
+
if (useDailySummary) {
|
|
421
|
+
const periodDays = { "7d": 7, "30d": 30, "60d": 60 };
|
|
422
|
+
const maxDays = periodDays[period] || null;
|
|
423
|
+
const dayRows = loadDaysInRange(db, maxDays);
|
|
424
|
+
|
|
425
|
+
for (const dr of dayRows) {
|
|
426
|
+
const dateKey = dr.dateKey;
|
|
427
|
+
const day = parseJson(dr.data, {});
|
|
428
|
+
stats.totalPromptTokens += day.promptTokens || 0;
|
|
429
|
+
stats.totalCompletionTokens += day.completionTokens || 0;
|
|
430
|
+
stats.totalCost += day.cost || 0;
|
|
431
|
+
|
|
432
|
+
for (const [prov, p] of Object.entries(day.byProvider || {})) {
|
|
433
|
+
if (!stats.byProvider[prov]) stats.byProvider[prov] = { requests: 0, promptTokens: 0, completionTokens: 0, cost: 0 };
|
|
434
|
+
stats.byProvider[prov].requests += p.requests || 0;
|
|
435
|
+
stats.byProvider[prov].promptTokens += p.promptTokens || 0;
|
|
436
|
+
stats.byProvider[prov].completionTokens += p.completionTokens || 0;
|
|
437
|
+
stats.byProvider[prov].cost += p.cost || 0;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
for (const [mk, m] of Object.entries(day.byModel || {})) {
|
|
441
|
+
const rawModel = m.rawModel || mk.split("|")[0];
|
|
442
|
+
const provider = m.provider || mk.split("|")[1] || "";
|
|
443
|
+
const statsKey = provider ? `${rawModel} (${provider})` : rawModel;
|
|
444
|
+
const providerDisplayName = providerNodeNameMap[provider] || provider;
|
|
445
|
+
if (!stats.byModel[statsKey]) {
|
|
446
|
+
stats.byModel[statsKey] = { requests: 0, promptTokens: 0, completionTokens: 0, cost: 0, rawModel, provider: providerDisplayName, lastUsed: dateKey };
|
|
447
|
+
}
|
|
448
|
+
stats.byModel[statsKey].requests += m.requests || 0;
|
|
449
|
+
stats.byModel[statsKey].promptTokens += m.promptTokens || 0;
|
|
450
|
+
stats.byModel[statsKey].completionTokens += m.completionTokens || 0;
|
|
451
|
+
stats.byModel[statsKey].cost += m.cost || 0;
|
|
452
|
+
if (dateKey > (stats.byModel[statsKey].lastUsed || "")) stats.byModel[statsKey].lastUsed = dateKey;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
for (const [connId, a] of Object.entries(day.byAccount || {})) {
|
|
456
|
+
const accountName = connectionMap[connId] || `Account ${connId.slice(0, 8)}...`;
|
|
457
|
+
const rawModel = a.rawModel || "";
|
|
458
|
+
const provider = a.provider || "";
|
|
459
|
+
const providerDisplayName = providerNodeNameMap[provider] || provider;
|
|
460
|
+
const accountKey = `${rawModel} (${provider} - ${accountName})`;
|
|
461
|
+
if (!stats.byAccount[accountKey]) {
|
|
462
|
+
stats.byAccount[accountKey] = { requests: 0, promptTokens: 0, completionTokens: 0, cost: 0, rawModel, provider: providerDisplayName, connectionId: connId, accountName, lastUsed: dateKey };
|
|
463
|
+
}
|
|
464
|
+
stats.byAccount[accountKey].requests += a.requests || 0;
|
|
465
|
+
stats.byAccount[accountKey].promptTokens += a.promptTokens || 0;
|
|
466
|
+
stats.byAccount[accountKey].completionTokens += a.completionTokens || 0;
|
|
467
|
+
stats.byAccount[accountKey].cost += a.cost || 0;
|
|
468
|
+
if (dateKey > (stats.byAccount[accountKey].lastUsed || "")) stats.byAccount[accountKey].lastUsed = dateKey;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
for (const [akKey, ak] of Object.entries(day.byApiKey || {})) {
|
|
472
|
+
const rawModel = ak.rawModel || "";
|
|
473
|
+
const provider = ak.provider || "";
|
|
474
|
+
const providerDisplayName = providerNodeNameMap[provider] || provider;
|
|
475
|
+
const apiKeyVal = ak.apiKey;
|
|
476
|
+
const keyInfo = apiKeyVal ? apiKeyMap[apiKeyVal] : null;
|
|
477
|
+
const keyName = keyInfo?.name || (apiKeyVal ? apiKeyVal.slice(0, 8) + "..." : "Local (No API Key)");
|
|
478
|
+
const apiKeyKey = apiKeyVal || "local-no-key";
|
|
479
|
+
if (!stats.byApiKey[akKey]) {
|
|
480
|
+
stats.byApiKey[akKey] = { requests: 0, promptTokens: 0, completionTokens: 0, cost: 0, rawModel, provider: providerDisplayName, apiKey: apiKeyVal, keyName, apiKeyKey, lastUsed: dateKey };
|
|
481
|
+
}
|
|
482
|
+
stats.byApiKey[akKey].requests += ak.requests || 0;
|
|
483
|
+
stats.byApiKey[akKey].promptTokens += ak.promptTokens || 0;
|
|
484
|
+
stats.byApiKey[akKey].completionTokens += ak.completionTokens || 0;
|
|
485
|
+
stats.byApiKey[akKey].cost += ak.cost || 0;
|
|
486
|
+
if (dateKey > (stats.byApiKey[akKey].lastUsed || "")) stats.byApiKey[akKey].lastUsed = dateKey;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
for (const [epKey, ep] of Object.entries(day.byEndpoint || {})) {
|
|
490
|
+
const endpoint = ep.endpoint || epKey.split("|")[0] || "Unknown";
|
|
491
|
+
const rawModel = ep.rawModel || "";
|
|
492
|
+
const provider = ep.provider || "";
|
|
493
|
+
const providerDisplayName = providerNodeNameMap[provider] || provider;
|
|
494
|
+
if (!stats.byEndpoint[epKey]) {
|
|
495
|
+
stats.byEndpoint[epKey] = { requests: 0, promptTokens: 0, completionTokens: 0, cost: 0, endpoint, rawModel, provider: providerDisplayName, lastUsed: dateKey };
|
|
496
|
+
}
|
|
497
|
+
stats.byEndpoint[epKey].requests += ep.requests || 0;
|
|
498
|
+
stats.byEndpoint[epKey].promptTokens += ep.promptTokens || 0;
|
|
499
|
+
stats.byEndpoint[epKey].completionTokens += ep.completionTokens || 0;
|
|
500
|
+
stats.byEndpoint[epKey].cost += ep.cost || 0;
|
|
501
|
+
if (dateKey > (stats.byEndpoint[epKey].lastUsed || "")) stats.byEndpoint[epKey].lastUsed = dateKey;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
// Overlay precise lastUsed timestamps from history
|
|
506
|
+
const overlayCutoff = maxDays ? Date.now() - maxDays * 86400000 : 0;
|
|
507
|
+
const histRows = db.all(
|
|
508
|
+
`SELECT timestamp, provider, model, connectionId, apiKey, endpoint FROM usageHistory WHERE timestamp >= ?`,
|
|
509
|
+
[new Date(overlayCutoff).toISOString()]
|
|
510
|
+
);
|
|
511
|
+
for (const e of histRows) {
|
|
512
|
+
const ts = e.timestamp;
|
|
513
|
+
const modelKey = e.provider ? `${e.model} (${e.provider})` : e.model;
|
|
514
|
+
if (stats.byModel[modelKey] && new Date(ts) > new Date(stats.byModel[modelKey].lastUsed)) stats.byModel[modelKey].lastUsed = ts;
|
|
515
|
+
|
|
516
|
+
if (e.connectionId) {
|
|
517
|
+
const accountName = connectionMap[e.connectionId] || `Account ${e.connectionId.slice(0, 8)}...`;
|
|
518
|
+
const accountKey = `${e.model} (${e.provider} - ${accountName})`;
|
|
519
|
+
if (stats.byAccount[accountKey] && new Date(ts) > new Date(stats.byAccount[accountKey].lastUsed)) stats.byAccount[accountKey].lastUsed = ts;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
const apiKeyKey = (e.apiKey && typeof e.apiKey === "string")
|
|
523
|
+
? `${e.apiKey}|${e.model}|${e.provider || "unknown"}`
|
|
524
|
+
: "local-no-key";
|
|
525
|
+
if (stats.byApiKey[apiKeyKey] && new Date(ts) > new Date(stats.byApiKey[apiKeyKey].lastUsed)) stats.byApiKey[apiKeyKey].lastUsed = ts;
|
|
526
|
+
|
|
527
|
+
const endpoint = e.endpoint || "Unknown";
|
|
528
|
+
const endpointKey = `${endpoint}|${e.model}|${e.provider || "unknown"}`;
|
|
529
|
+
if (stats.byEndpoint[endpointKey] && new Date(ts) > new Date(stats.byEndpoint[endpointKey].lastUsed)) stats.byEndpoint[endpointKey].lastUsed = ts;
|
|
530
|
+
}
|
|
531
|
+
} else {
|
|
532
|
+
// 24h / today: live history
|
|
533
|
+
let cutoff;
|
|
534
|
+
if (period === "today") {
|
|
535
|
+
const startOfDay = new Date();
|
|
536
|
+
startOfDay.setHours(0, 0, 0, 0);
|
|
537
|
+
cutoff = startOfDay.toISOString();
|
|
538
|
+
} else {
|
|
539
|
+
cutoff = new Date(Date.now() - PERIOD_MS["24h"]).toISOString();
|
|
540
|
+
}
|
|
541
|
+
const filtered = db.all(
|
|
542
|
+
`SELECT timestamp, provider, model, connectionId, apiKey, endpoint, promptTokens, completionTokens, cost, tokens FROM usageHistory WHERE timestamp >= ?`,
|
|
543
|
+
[cutoff]
|
|
544
|
+
);
|
|
545
|
+
|
|
546
|
+
for (const r of filtered) {
|
|
547
|
+
const tokens = parseJson(r.tokens, {}) || {};
|
|
548
|
+
const promptTokens = tokens.prompt_tokens || 0;
|
|
549
|
+
const completionTokens = tokens.completion_tokens || 0;
|
|
550
|
+
const entryCost = r.cost || 0;
|
|
551
|
+
const providerDisplayName = providerNodeNameMap[r.provider] || r.provider;
|
|
552
|
+
|
|
553
|
+
stats.totalPromptTokens += promptTokens;
|
|
554
|
+
stats.totalCompletionTokens += completionTokens;
|
|
555
|
+
stats.totalCost += entryCost;
|
|
556
|
+
|
|
557
|
+
if (!stats.byProvider[r.provider]) stats.byProvider[r.provider] = { requests: 0, promptTokens: 0, completionTokens: 0, cost: 0 };
|
|
558
|
+
stats.byProvider[r.provider].requests++;
|
|
559
|
+
stats.byProvider[r.provider].promptTokens += promptTokens;
|
|
560
|
+
stats.byProvider[r.provider].completionTokens += completionTokens;
|
|
561
|
+
stats.byProvider[r.provider].cost += entryCost;
|
|
562
|
+
|
|
563
|
+
const modelKey = r.provider ? `${r.model} (${r.provider})` : r.model;
|
|
564
|
+
if (!stats.byModel[modelKey]) {
|
|
565
|
+
stats.byModel[modelKey] = { requests: 0, promptTokens: 0, completionTokens: 0, cost: 0, rawModel: r.model, provider: providerDisplayName, lastUsed: r.timestamp };
|
|
566
|
+
}
|
|
567
|
+
stats.byModel[modelKey].requests++;
|
|
568
|
+
stats.byModel[modelKey].promptTokens += promptTokens;
|
|
569
|
+
stats.byModel[modelKey].completionTokens += completionTokens;
|
|
570
|
+
stats.byModel[modelKey].cost += entryCost;
|
|
571
|
+
if (new Date(r.timestamp) > new Date(stats.byModel[modelKey].lastUsed)) stats.byModel[modelKey].lastUsed = r.timestamp;
|
|
572
|
+
|
|
573
|
+
if (r.connectionId) {
|
|
574
|
+
const accountName = connectionMap[r.connectionId] || `Account ${r.connectionId.slice(0, 8)}...`;
|
|
575
|
+
const accountKey = `${r.model} (${r.provider} - ${accountName})`;
|
|
576
|
+
if (!stats.byAccount[accountKey]) {
|
|
577
|
+
stats.byAccount[accountKey] = { requests: 0, promptTokens: 0, completionTokens: 0, cost: 0, rawModel: r.model, provider: providerDisplayName, connectionId: r.connectionId, accountName, lastUsed: r.timestamp };
|
|
578
|
+
}
|
|
579
|
+
stats.byAccount[accountKey].requests++;
|
|
580
|
+
stats.byAccount[accountKey].promptTokens += promptTokens;
|
|
581
|
+
stats.byAccount[accountKey].completionTokens += completionTokens;
|
|
582
|
+
stats.byAccount[accountKey].cost += entryCost;
|
|
583
|
+
if (new Date(r.timestamp) > new Date(stats.byAccount[accountKey].lastUsed)) stats.byAccount[accountKey].lastUsed = r.timestamp;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
if (r.apiKey && typeof r.apiKey === "string") {
|
|
587
|
+
const keyInfo = apiKeyMap[r.apiKey];
|
|
588
|
+
const keyName = keyInfo?.name || r.apiKey.slice(0, 8) + "...";
|
|
589
|
+
const akKey = `${r.apiKey}|${r.model}|${r.provider || "unknown"}`;
|
|
590
|
+
if (!stats.byApiKey[akKey]) {
|
|
591
|
+
stats.byApiKey[akKey] = { requests: 0, promptTokens: 0, completionTokens: 0, cost: 0, rawModel: r.model, provider: providerDisplayName, apiKey: r.apiKey, keyName, apiKeyKey: r.apiKey, lastUsed: r.timestamp };
|
|
592
|
+
}
|
|
593
|
+
const ake = stats.byApiKey[akKey];
|
|
594
|
+
ake.requests++; ake.promptTokens += promptTokens; ake.completionTokens += completionTokens; ake.cost += entryCost;
|
|
595
|
+
if (new Date(r.timestamp) > new Date(ake.lastUsed)) ake.lastUsed = r.timestamp;
|
|
596
|
+
} else {
|
|
597
|
+
if (!stats.byApiKey["local-no-key"]) {
|
|
598
|
+
stats.byApiKey["local-no-key"] = { requests: 0, promptTokens: 0, completionTokens: 0, cost: 0, rawModel: r.model, provider: providerDisplayName, apiKey: null, keyName: "Local (No API Key)", apiKeyKey: "local-no-key", lastUsed: r.timestamp };
|
|
599
|
+
}
|
|
600
|
+
const ake = stats.byApiKey["local-no-key"];
|
|
601
|
+
ake.requests++; ake.promptTokens += promptTokens; ake.completionTokens += completionTokens; ake.cost += entryCost;
|
|
602
|
+
if (new Date(r.timestamp) > new Date(ake.lastUsed)) ake.lastUsed = r.timestamp;
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
const endpoint = r.endpoint || "Unknown";
|
|
606
|
+
const epKey = `${endpoint}|${r.model}|${r.provider || "unknown"}`;
|
|
607
|
+
if (!stats.byEndpoint[epKey]) {
|
|
608
|
+
stats.byEndpoint[epKey] = { requests: 0, promptTokens: 0, completionTokens: 0, cost: 0, endpoint, rawModel: r.model, provider: providerDisplayName, lastUsed: r.timestamp };
|
|
609
|
+
}
|
|
610
|
+
const epe = stats.byEndpoint[epKey];
|
|
611
|
+
epe.requests++; epe.promptTokens += promptTokens; epe.completionTokens += completionTokens; epe.cost += entryCost;
|
|
612
|
+
if (new Date(r.timestamp) > new Date(epe.lastUsed)) epe.lastUsed = r.timestamp;
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
stats.totalRequests = Object.values(stats.byProvider).reduce((sum, p) => sum + (p.requests || 0), 0);
|
|
617
|
+
return stats;
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
export async function getChartData(period = "7d") {
|
|
621
|
+
const db = await getAdapter();
|
|
622
|
+
const now = Date.now();
|
|
623
|
+
|
|
624
|
+
if (period === "today") {
|
|
625
|
+
const bucketCount = 24;
|
|
626
|
+
const bucketMs = 3600000;
|
|
627
|
+
const startOfDay = new Date();
|
|
628
|
+
startOfDay.setHours(0, 0, 0, 0);
|
|
629
|
+
const startTime = startOfDay.getTime();
|
|
630
|
+
const endTime = startTime + bucketCount * bucketMs;
|
|
631
|
+
const labelFn = (ts) => new Date(ts).toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit", hour12: false });
|
|
632
|
+
const buckets = Array.from({ length: bucketCount }, (_, i) => ({ label: labelFn(startTime + i * bucketMs), tokens: 0, cost: 0 }));
|
|
633
|
+
|
|
634
|
+
const rows = db.all(
|
|
635
|
+
`SELECT timestamp, promptTokens, completionTokens, cost FROM usageHistory WHERE timestamp >= ?`,
|
|
636
|
+
[new Date(startTime).toISOString()]
|
|
637
|
+
);
|
|
638
|
+
for (const r of rows) {
|
|
639
|
+
const t = new Date(r.timestamp).getTime();
|
|
640
|
+
if (t < startTime || t >= endTime) continue;
|
|
641
|
+
const idx = Math.floor((t - startTime) / bucketMs);
|
|
642
|
+
if (idx >= 0 && idx < bucketCount) {
|
|
643
|
+
buckets[idx].tokens += (r.promptTokens || 0) + (r.completionTokens || 0);
|
|
644
|
+
buckets[idx].cost += r.cost || 0;
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
return buckets;
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
if (period === "24h") {
|
|
651
|
+
const bucketCount = 24;
|
|
652
|
+
const bucketMs = 3600000;
|
|
653
|
+
const labelFn = (ts) => new Date(ts).toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit", hour12: false });
|
|
654
|
+
const startTime = now - bucketCount * bucketMs;
|
|
655
|
+
const buckets = Array.from({ length: bucketCount }, (_, i) => ({ label: labelFn(startTime + i * bucketMs), tokens: 0, cost: 0 }));
|
|
656
|
+
|
|
657
|
+
const rows = db.all(
|
|
658
|
+
`SELECT timestamp, promptTokens, completionTokens, cost FROM usageHistory WHERE timestamp >= ?`,
|
|
659
|
+
[new Date(startTime).toISOString()]
|
|
660
|
+
);
|
|
661
|
+
for (const r of rows) {
|
|
662
|
+
const t = new Date(r.timestamp).getTime();
|
|
663
|
+
if (t < startTime || t > now) continue;
|
|
664
|
+
const idx = Math.min(Math.floor((t - startTime) / bucketMs), bucketCount - 1);
|
|
665
|
+
buckets[idx].tokens += (r.promptTokens || 0) + (r.completionTokens || 0);
|
|
666
|
+
buckets[idx].cost += r.cost || 0;
|
|
667
|
+
}
|
|
668
|
+
return buckets;
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
const bucketCount = period === "7d" ? 7 : period === "30d" ? 30 : 60;
|
|
672
|
+
const today = new Date();
|
|
673
|
+
const labelFn = (d) => d.toLocaleDateString("en-US", { month: "short", day: "numeric" });
|
|
674
|
+
|
|
675
|
+
// Build map of dateKey → day data
|
|
676
|
+
const dayRows = loadDaysInRange(db, bucketCount);
|
|
677
|
+
const dayMap = {};
|
|
678
|
+
for (const r of dayRows) dayMap[r.dateKey] = parseJson(r.data, {});
|
|
679
|
+
|
|
680
|
+
return Array.from({ length: bucketCount }, (_, i) => {
|
|
681
|
+
const d = new Date(today);
|
|
682
|
+
d.setDate(d.getDate() - (bucketCount - 1 - i));
|
|
683
|
+
const dateKey = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
|
|
684
|
+
const dayData = dayMap[dateKey];
|
|
685
|
+
return {
|
|
686
|
+
label: labelFn(d),
|
|
687
|
+
tokens: dayData ? (dayData.promptTokens || 0) + (dayData.completionTokens || 0) : 0,
|
|
688
|
+
cost: dayData ? (dayData.cost || 0) : 0,
|
|
689
|
+
};
|
|
690
|
+
});
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
function formatLogDate(date = new Date()) {
|
|
694
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
695
|
+
return `${pad(date.getDate())}-${pad(date.getMonth() + 1)}-${date.getFullYear()} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
// No-op: request log is now derived from usageHistory table on read.
|
|
699
|
+
export async function appendRequestLog() {}
|
|
700
|
+
|
|
701
|
+
export async function getRecentLogs(limit = 200) {
|
|
702
|
+
try {
|
|
703
|
+
const db = getAdapter();
|
|
704
|
+
const rows = db.all(
|
|
705
|
+
`SELECT timestamp, provider, model, connectionId, promptTokens, completionTokens, status, tokens FROM usageHistory ORDER BY id DESC LIMIT ?`,
|
|
706
|
+
[limit],
|
|
707
|
+
);
|
|
708
|
+
if (!rows.length) return [];
|
|
709
|
+
|
|
710
|
+
const connMap = {};
|
|
711
|
+
try {
|
|
712
|
+
const { getProviderConnections } = await import("./connectionsRepo.js");
|
|
713
|
+
const connections = await getProviderConnections();
|
|
714
|
+
for (const c of connections) connMap[c.id] = c.name || c.email || "";
|
|
715
|
+
} catch {}
|
|
716
|
+
|
|
717
|
+
return rows.map((r) => {
|
|
718
|
+
const ts = formatLogDate(new Date(r.timestamp));
|
|
719
|
+
const p = r.provider?.toUpperCase() || "-";
|
|
720
|
+
const m = r.model || "-";
|
|
721
|
+
const account = connMap[r.connectionId] || (r.connectionId ? r.connectionId.slice(0, 8) : "-");
|
|
722
|
+
const tk = r.tokens ? parseJson(r.tokens, {}) : {};
|
|
723
|
+
const sent = r.promptTokens ?? tk.prompt_tokens ?? "-";
|
|
724
|
+
const received = r.completionTokens ?? tk.completion_tokens ?? "-";
|
|
725
|
+
return `${ts} | ${m} | ${p} | ${account} | ${sent} | ${received} | ${r.status || "-"}`;
|
|
726
|
+
});
|
|
727
|
+
} catch (e) {
|
|
728
|
+
console.error("[usageRepo] getRecentLogs failed:", e.message);
|
|
729
|
+
return [];
|
|
730
|
+
}
|
|
731
|
+
}
|