nolo-cli 0.1.13 → 0.1.15
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 +9 -2
- package/agent-runtime/hostAdapter.ts +53 -0
- package/agent-runtime/index.ts +28 -0
- package/agent-runtime/localLoop.ts +62 -0
- package/agent-runtime/runtimeDecision.ts +70 -0
- package/agent-runtime/types.ts +87 -0
- package/agentRunCommand.ts +104 -0
- package/agentRuntimeCommands.ts +139 -22
- package/agentRuntimeLocal.ts +7 -0
- package/ai/agent/_executeModel.ts +118 -0
- package/ai/agent/agentSlice.ts +544 -1
- package/ai/agent/appWorkingMemory.ts +126 -0
- package/ai/agent/avatarUtils.ts +24 -0
- package/ai/agent/buildEditingContext.ts +373 -0
- package/ai/agent/buildSystemPrompt.ts +532 -0
- package/ai/agent/cleanAgentMessages.ts +140 -0
- package/ai/agent/cliChatClient.ts +119 -0
- package/ai/agent/contextCompiler.ts +107 -0
- package/ai/agent/contextLayerContract.ts +44 -0
- package/ai/agent/createAgentSchema.ts +234 -0
- package/ai/agent/executeToolCall.ts +58 -0
- package/ai/agent/fetchAgentContexts.ts +42 -0
- package/ai/agent/generatePrompt.ts +3 -0
- package/ai/agent/getFullChatContextKeys.ts +168 -0
- package/ai/agent/hooks/fetchPublicAgents.ts +133 -0
- package/ai/agent/hooks/useAgentConfig.ts +61 -0
- package/ai/agent/hooks/useAgentDialog.ts +35 -0
- package/ai/agent/hooks/useAgentFormValidation.ts +202 -0
- package/ai/agent/hooks/usePublicAgents.ts +473 -0
- package/ai/agent/persistMessageWithFixedId.ts +37 -0
- package/ai/agent/planSlice.ts +259 -0
- package/ai/agent/referenceUtils.ts +229 -0
- package/ai/agent/runAgentBackground.ts +238 -0
- package/ai/agent/runAgentClientLoop.ts +138 -0
- package/ai/agent/runtimeGuidance.ts +97 -0
- package/ai/agent/runtimeServerBase.ts +37 -0
- package/ai/agent/server/fetchPublicAgents.ts +128 -0
- package/ai/agent/startParallelAgentStreams.ts +424 -0
- package/ai/agent/startupProtocol.ts +53 -0
- package/ai/agent/streamAgentChatTurn.ts +1299 -0
- package/ai/agent/streamAgentChatTurnUtils.ts +738 -0
- package/ai/agent/types.ts +71 -0
- package/ai/agent/utils/imageOutput.ts +39 -0
- package/ai/agent/utils/publicImageAgentMode.ts +26 -0
- package/ai/agent/utils/sortUtils.ts +250 -0
- package/ai/agent/web/referencePickerUtils.ts +146 -0
- package/ai/ai.locale.ts +1083 -0
- package/ai/chat/accumulateToolCallChunks.ts +95 -0
- package/ai/chat/fetchUtils.native.ts +276 -0
- package/ai/chat/fetchUtils.ts +153 -0
- package/ai/chat/inlineImageUrlsForCustomProvider.ts +117 -0
- package/ai/chat/parseApiError.ts +64 -0
- package/ai/chat/parseMultilineSSE.ts +95 -0
- package/ai/chat/sendOpenAICompletionsRequest.native.ts +682 -0
- package/ai/chat/sendOpenAICompletionsRequest.ts +712 -0
- package/ai/chat/sendOpenAIResponseRequest.ts +512 -0
- package/ai/chat/shouldUseServerProxy.ts +18 -0
- package/ai/chat/sseClient.native.ts +91 -0
- package/ai/chat/sseClient.ts +67 -0
- package/ai/chat/streamReader.native.ts +31 -0
- package/ai/chat/streamReader.ts +62 -0
- package/ai/chat/updateTotalUsage.ts +72 -0
- package/ai/context/buildReferenceContext.ts +437 -0
- package/ai/context/calculateContextUsage.ts +133 -0
- package/ai/context/retention.ts +165 -0
- package/ai/context/tokenUtils.ts +78 -0
- package/ai/index.ts +1 -1
- package/ai/llm/agentCapabilities.ts +74 -0
- package/ai/llm/calculateGeminiImageTokens.ts +57 -0
- package/ai/llm/deepinfra.ts +28 -0
- package/ai/llm/fireworks.ts +68 -0
- package/ai/llm/generateRequestBody.ts +165 -0
- package/ai/llm/getModelContextWindow.ts +84 -0
- package/ai/llm/getNoloKey.ts +37 -0
- package/ai/llm/getPricing.ts +232 -0
- package/ai/llm/hooks/useModelPricing.ts +75 -0
- package/ai/llm/imagePricing.ts +66 -0
- package/ai/llm/isResponseAPIModel.ts +13 -0
- package/ai/llm/kimi.ts +18 -0
- package/ai/llm/mimo.ts +71 -0
- package/ai/llm/mistral.ts +22 -0
- package/ai/llm/modelAvatar.ts +427 -0
- package/ai/llm/models.ts +45 -0
- package/ai/llm/openrouterModels.ts +141 -0
- package/ai/llm/providers.ts +307 -0
- package/ai/llm/reasoningModels.ts +28 -0
- package/ai/llm/types.ts +59 -0
- package/ai/llm/usageRequestOptions.ts +59 -0
- package/ai/memory/capture.ts +148 -0
- package/ai/memory/consolidate.ts +104 -0
- package/ai/memory/delete.ts +147 -0
- package/ai/memory/overlay.ts +84 -0
- package/ai/memory/query.ts +38 -0
- package/ai/memory/queryShared.ts +160 -0
- package/ai/memory/rank.ts +105 -0
- package/ai/memory/recentRelationshipRecap.ts +247 -0
- package/ai/memory/remember.ts +167 -0
- package/ai/memory/runtime.ts +76 -0
- package/ai/memory/store.ts +20 -0
- package/ai/memory/storeShared.ts +76 -0
- package/ai/memory/types.ts +46 -0
- package/ai/memory/understanding.ts +349 -0
- package/ai/memory/understandingGreeting.ts +264 -0
- package/ai/messages/type.ts +20 -0
- package/ai/policy/personalizationDialog.ts +333 -0
- package/ai/policy/runtimePolicy.ts +440 -0
- package/ai/policy/selfUpdateFields.ts +48 -0
- package/ai/policy/types.ts +64 -0
- package/ai/skills/referenceRuntime.ts +274 -0
- package/ai/skills/skillDiagnostics.ts +251 -0
- package/ai/skills/skillDocBuilder.ts +139 -0
- package/ai/skills/skillDocProtocol.ts +434 -0
- package/ai/skills/skillReferenceSummary.ts +63 -0
- package/ai/skills/skillSummaryMarker.ts +26 -0
- package/ai/token/calculatePrice.ts +546 -0
- package/ai/token/db.ts +98 -0
- package/ai/token/externalToolCost.ts +321 -0
- package/ai/token/hooks/useRecords.ts +65 -0
- package/ai/token/missingUsageEstimate.ts +42 -0
- package/ai/token/modelUsageQuery.ts +252 -0
- package/ai/token/normalizeUsage.ts +84 -0
- package/ai/token/openaiImageGenerationUsage.ts +56 -0
- package/ai/token/prepareTokenUsageData.ts +88 -0
- package/ai/token/query.ts +88 -0
- package/ai/token/queryUserTokens.ts +59 -0
- package/ai/token/resolveBillingTarget.ts +52 -0
- package/ai/token/saveTokenRecord.ts +53 -0
- package/ai/token/serverDialogProjection.ts +78 -0
- package/ai/token/serverTokenWriter.ts +143 -0
- package/ai/token/stats.ts +21 -0
- package/ai/token/tokenThunks.ts +24 -0
- package/ai/token/types.ts +93 -0
- package/ai/tools/agent/agentTools.ts +176 -0
- package/ai/tools/agent/agentUpdateShared.ts +311 -0
- package/ai/tools/agent/callAgentTool.ts +139 -0
- package/ai/tools/agent/createAgentTool.ts +512 -0
- package/ai/tools/agent/createDialogTool.ts +69 -0
- package/ai/tools/agent/createSkillAgentTool.ts +62 -0
- package/ai/tools/agent/parallelBudget.ts +221 -0
- package/ai/tools/agent/presets/appBuilderPreset.ts +147 -0
- package/ai/tools/agent/runLlmTool.ts +96 -0
- package/ai/tools/agent/runStreamingAgentTool.ts +73 -0
- package/ai/tools/agent/skillAgentArgs.ts +106 -0
- package/ai/tools/agent/skillAgentPreset.ts +89 -0
- package/ai/tools/agent/streamParallelAgentsTool.ts +122 -0
- package/ai/tools/agent/updateAgentTool.ts +96 -0
- package/ai/tools/agent/updateSelfTool.ts +113 -0
- package/ai/tools/amazonProductScraperTool.ts +86 -0
- package/ai/tools/apifyActorClient.ts +45 -0
- package/ai/tools/appEditGuard.ts +372 -0
- package/ai/tools/appReadSnapshot.ts +153 -0
- package/ai/tools/appTools.ts +1549 -0
- package/ai/tools/applyEditTool.ts +256 -0
- package/ai/tools/applyLineEditsTool.ts +312 -0
- package/ai/tools/browserTools/click.ts +33 -0
- package/ai/tools/browserTools/closeSession.ts +29 -0
- package/ai/tools/browserTools/common.ts +27 -0
- package/ai/tools/browserTools/openSession.ts +48 -0
- package/ai/tools/browserTools/readContent.ts +38 -0
- package/ai/tools/browserTools/selectOption.ts +46 -0
- package/ai/tools/browserTools/typeText.ts +42 -0
- package/ai/tools/category/createCategoryTool.ts +66 -0
- package/ai/tools/category/queryContentsByCategoryTool.ts +69 -0
- package/ai/tools/category/updateContentCategoryTool.ts +75 -0
- package/ai/tools/cfBrowserTools.ts +319 -0
- package/ai/tools/cfSpeechToTextTool.ts +49 -0
- package/ai/tools/checkEnvTool.ts +65 -0
- package/ai/tools/cloudflareCrawlTool.ts +289 -0
- package/ai/tools/codeSearchTool.ts +111 -0
- package/ai/tools/codeTools.ts +101 -0
- package/ai/tools/createDocTool.ts +132 -0
- package/ai/tools/createPlanTool.ts +999 -0
- package/ai/tools/createSkillDocTool.ts +155 -0
- package/ai/tools/createWorkflowTool.ts +154 -0
- package/ai/tools/deepseekOcrTool.ts +34 -0
- package/ai/tools/delayTool.ts +31 -0
- package/ai/tools/deleteSpacesTool.ts +325 -0
- package/ai/tools/deleteSpacesToolModel.ts +159 -0
- package/ai/tools/devReloadUtils.ts +29 -0
- package/ai/tools/dialogMessageSearch.ts +137 -0
- package/ai/tools/doctorSkillTool.ts +72 -0
- package/ai/tools/ecommerceScraperTool.ts +86 -0
- package/ai/tools/emailTools.ts +549 -0
- package/ai/tools/evalSkillTool.ts +92 -0
- package/ai/tools/exaSearchTool.ts +64 -0
- package/ai/tools/execBashTool.ts +379 -0
- package/ai/tools/executeSqlTool.ts +192 -0
- package/ai/tools/fetchWebpageSupport.ts +309 -0
- package/ai/tools/fetchWebpageTool.ts +84 -0
- package/ai/tools/geminiImagePreviewTool.ts +361 -0
- package/ai/tools/generateDocxTool.ts +215 -0
- package/ai/tools/googleSearchScraperTool.ts +106 -0
- package/ai/tools/importDataTool.ts +133 -0
- package/ai/tools/importSkillTool.ts +162 -0
- package/ai/tools/index.ts +1927 -0
- package/ai/tools/listFilesTool.ts +82 -0
- package/ai/tools/listUserSpacesTool.ts +113 -0
- package/ai/tools/modelUsageTools.ts +199 -0
- package/ai/tools/olmOcrTool.ts +34 -0
- package/ai/tools/openaiImageTool.ts +267 -0
- package/ai/tools/prepareTools.ts +23 -0
- package/ai/tools/readDocTool.ts +84 -0
- package/ai/tools/readFileTool.ts +211 -0
- package/ai/tools/readTool.ts +163 -0
- package/ai/tools/readXPostTool.ts +233 -0
- package/ai/tools/rememberMemoryTool.ts +84 -0
- package/ai/tools/remotionVideoTool.ts +151 -0
- package/ai/tools/searchDialogMessagesTool.ts +222 -0
- package/ai/tools/searchRepoTool.ts +115 -0
- package/ai/tools/searchWorkspaceTool.ts +259 -0
- package/ai/tools/skillFollowup.ts +86 -0
- package/ai/tools/surfWeatherTool.ts +169 -0
- package/ai/tools/table/addTableRowTool.ts +217 -0
- package/ai/tools/table/createTableTool.ts +315 -0
- package/ai/tools/table/rowTools.ts +366 -0
- package/ai/tools/table/schemaTools.ts +244 -0
- package/ai/tools/table/shareTableTool.ts +148 -0
- package/ai/tools/table/toolShared.ts +129 -0
- package/ai/tools/toolApiClient.ts +198 -0
- package/ai/tools/toolNameAliases.ts +57 -0
- package/ai/tools/toolResultError.ts +42 -0
- package/ai/tools/toolRunSlice.ts +303 -0
- package/ai/tools/toolSchemaCompatibility.ts +53 -0
- package/ai/tools/toolVisibility.ts +4 -0
- package/ai/tools/types.ts +20 -0
- package/ai/tools/uiAskChoiceTool.ts +104 -0
- package/ai/tools/updateContentTitleTool.ts +84 -0
- package/ai/tools/updateDocTool.ts +105 -0
- package/ai/tools/updateUserPreferenceProfileTool.ts +145 -0
- package/ai/tools/whisperTool.ts +77 -0
- package/ai/tools/writeFileTool.ts +210 -0
- package/ai/tools/youtubeScraperTool.ts +116 -0
- package/ai/tools/ziweiChartTool.ts +678 -0
- package/ai/types.ts +55 -0
- package/ai/workflow/workflowExecutor.ts +323 -0
- package/ai/workflow/workflowSlice.ts +73 -0
- package/ai/workflow/workflowTypes.ts +106 -0
- package/client/agentRun.test.ts +240 -0
- package/client/agentRun.ts +182 -19
- package/client/compactDialog.test.ts +238 -0
- package/client/localRuntimeAdapter.test.ts +135 -0
- package/client/localRuntimeAdapter.ts +244 -0
- package/client/profileConfig.test.ts +40 -0
- package/client/streamingOutput.test.ts +22 -0
- package/client/streamingOutput.ts +38 -0
- package/commandRegistry.ts +11 -2
- package/connector-experimental/index.ts +5 -0
- package/database/actions/cacheMergedUserData.ts +64 -0
- package/database/actions/common.ts +242 -0
- package/database/actions/deleteFile.ts +40 -0
- package/database/actions/fetchUserData.ts +16 -0
- package/database/actions/fileContent.ts +125 -0
- package/database/actions/patch.ts +155 -0
- package/database/actions/read.ts +337 -0
- package/database/actions/readAndWait.ts +224 -0
- package/database/actions/readRequestManager.ts +120 -0
- package/database/actions/remove.ts +94 -0
- package/database/actions/replication.ts +366 -0
- package/database/actions/upload.ts +174 -0
- package/database/actions/upsert.ts +56 -0
- package/database/actions/write.ts +126 -0
- package/database/client/db.native.ts +73 -0
- package/database/client/db.ts +51 -0
- package/database/client/fetchUserData.ts +61 -0
- package/database/client/handleError.ts +19 -0
- package/database/client/queryRequest.ts +21 -0
- package/database/config.ts +21 -0
- package/database/dbActionThunks.ts +1 -0
- package/database/dbSlice.ts +149 -0
- package/database/email.ts +42 -0
- package/database/fileRing.ts +51 -0
- package/database/fileSharding.ts +70 -0
- package/database/fileStorage.native.ts +92 -0
- package/database/fileStorage.ts +232 -0
- package/database/fileUrl.ts +34 -0
- package/database/hooks/useUserData.ts +489 -0
- package/database/index.ts +1 -0
- package/database/keys.ts +765 -0
- package/database/queryPrefixes.ts +14 -0
- package/database/requests.ts +443 -0
- package/database/runtimeServerContext.ts +35 -0
- package/database/server/MemoryDB.ts +76 -0
- package/database/server/actorAccess.ts +76 -0
- package/database/server/agentDelegation.ts +124 -0
- package/database/server/coreDataOwnership.ts +13 -0
- package/database/server/coreDataProxy.ts +76 -0
- package/database/server/cybotReadonly.ts +18 -0
- package/database/server/dataHandlers.ts +111 -0
- package/database/server/db.ts +118 -0
- package/database/server/dbPath.ts +20 -0
- package/database/server/delete.ts +499 -0
- package/database/server/emailRepository.ts +1480 -0
- package/database/server/ensureDbOpen.ts +12 -0
- package/database/server/fileRead.ts +337 -0
- package/database/server/fileService.ts +436 -0
- package/database/server/handleTransaction.ts +86 -0
- package/database/server/patch.ts +282 -0
- package/database/server/query.ts +138 -0
- package/database/server/read.ts +325 -0
- package/database/server/resourceAccess.ts +211 -0
- package/database/server/routes.ts +110 -0
- package/database/server/spaceMemberAuthority.ts +67 -0
- package/database/server/upload.ts +159 -0
- package/database/server/write.ts +494 -0
- package/database/server/writeAuthority.ts +133 -0
- package/database/sqliteDb.ts +46 -0
- package/database/table/deleteTable.ts +120 -0
- package/database/tenantPlacement.ts +57 -0
- package/database/tombstones.ts +52 -0
- package/database/userDataLoadDecision.ts +17 -0
- package/database/userDataMerge.ts +95 -0
- package/database/userPreferenceRegister.ts +108 -0
- package/database/utils/dbPath.ts +47 -0
- package/database/utils/ulid.native.ts +6 -0
- package/database/utils/ulid.ts +1 -0
- package/index.ts +37 -19
- package/localRuntimeDb.ts +28 -0
- package/package.json +17 -4
- package/runtimeModeArgs.ts +33 -0
- package/tui/readlineWorkspace.ts +1 -0
- package/tui/session.ts +22 -0
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* externalToolCost.ts
|
|
3
|
+
*
|
|
4
|
+
* 外部 API 工具(OCR、搜索、浏览器等)的统一计费抽象。
|
|
5
|
+
*
|
|
6
|
+
* 价格单位:credits / 1M tokens(token 类),或 credits / 次调用(perCall 类)。
|
|
7
|
+
* 换算关系:1 USD = 8 credits(与 fireworks/openrouter 一致)。
|
|
8
|
+
*
|
|
9
|
+
* 如何添加新工具:
|
|
10
|
+
* 在 EXTERNAL_TOOL_PRICING 中增加一条记录,然后在 handler 里调用
|
|
11
|
+
* chargeExternalTool({ userId, toolId, ... })。
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { ulid } from "ulid";
|
|
15
|
+
import { format } from "date-fns";
|
|
16
|
+
import serverDb from "database/server/db";
|
|
17
|
+
import { createKey, createTokenKey, createTokenStatsKey } from "database/keys";
|
|
18
|
+
import { deductUserBalance } from "auth/server/deduct";
|
|
19
|
+
import { DataType } from "create/types";
|
|
20
|
+
import pino from "pino";
|
|
21
|
+
import { applyServerDialogProjectionDelta } from "./serverDialogProjection";
|
|
22
|
+
|
|
23
|
+
const logger = pino({ name: "external-tool-cost" });
|
|
24
|
+
|
|
25
|
+
// ─────────────────────────────────────────
|
|
26
|
+
// 价格注册表(所有外部工具)
|
|
27
|
+
// ─────────────────────────────────────────
|
|
28
|
+
|
|
29
|
+
type TokenPrice = {
|
|
30
|
+
type: "token";
|
|
31
|
+
/** credits / 1M input tokens (USD/1M × 8) */
|
|
32
|
+
input: number;
|
|
33
|
+
/** credits / 1M output tokens (USD/1M × 8) */
|
|
34
|
+
output: number;
|
|
35
|
+
provider: string;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
type PerCallPrice = {
|
|
39
|
+
type: "perCall";
|
|
40
|
+
/** credits / 次调用 */
|
|
41
|
+
cost: number;
|
|
42
|
+
provider: string;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
type PerMinutePrice = {
|
|
46
|
+
type: "perMinute";
|
|
47
|
+
/** credits / 分钟 */
|
|
48
|
+
cost: number;
|
|
49
|
+
provider: string;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
type ToolPrice = TokenPrice | PerCallPrice | PerMinutePrice;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 外部工具价格表。
|
|
56
|
+
* 修改价格只需改这里,无需改动任何 handler。
|
|
57
|
+
*
|
|
58
|
+
* OCR 价格来自 DeepInfra 官网(截图,2026-03):
|
|
59
|
+
* olmOCR $0.09/$0.19 /1M → ×8
|
|
60
|
+
* DeepSeek $0.03/$0.10 /1M → ×8
|
|
61
|
+
*
|
|
62
|
+
* Exa 价格:$0.01/次(含 contents)× 8
|
|
63
|
+
*/
|
|
64
|
+
export const EXTERNAL_TOOL_PRICING: Record<string, ToolPrice> = {
|
|
65
|
+
// ── OCR (DeepInfra, token-based) ──────────────────────
|
|
66
|
+
"allenai/olmOCR-2-7B-1025": {
|
|
67
|
+
type: "token",
|
|
68
|
+
input: 0.09 * 8, // 0.72
|
|
69
|
+
output: 0.19 * 8, // 1.52
|
|
70
|
+
provider: "deepinfra",
|
|
71
|
+
},
|
|
72
|
+
|
|
73
|
+
// ── Web Search ────────────────────────────────────────
|
|
74
|
+
"exa_search": {
|
|
75
|
+
type: "perCall",
|
|
76
|
+
cost: 0.01 * 8, // 0.08
|
|
77
|
+
provider: "exa",
|
|
78
|
+
},
|
|
79
|
+
|
|
80
|
+
// ── ASR / Whisper (DeepInfra, per-minute) ─────────────
|
|
81
|
+
"openai/whisper-large-v3-turbo": {
|
|
82
|
+
type: "perMinute",
|
|
83
|
+
cost: 0.00020 * 8, // 0.0016 credits/min
|
|
84
|
+
provider: "deepinfra",
|
|
85
|
+
},
|
|
86
|
+
"openai/whisper-large-v3": {
|
|
87
|
+
type: "perMinute",
|
|
88
|
+
cost: 0.00045 * 8, // 0.0036 credits/min
|
|
89
|
+
provider: "deepinfra",
|
|
90
|
+
},
|
|
91
|
+
|
|
92
|
+
// ── Apify Actors (per-run) ─────────────────────────────
|
|
93
|
+
// Apify 按 compute unit 计费,轻量爬虫 ~0.05–0.5 CU,$0.50/CU
|
|
94
|
+
// 保守取 $0.25/run 作为默认基准,建议高消耗 Actor 单独定价
|
|
95
|
+
"apify_actor_run": {
|
|
96
|
+
type: "perCall",
|
|
97
|
+
cost: 0.25 * 8, // 2.0 credits/run
|
|
98
|
+
provider: "apify",
|
|
99
|
+
},
|
|
100
|
+
|
|
101
|
+
// ── Gemini Image Generation (per-image) ───────────────
|
|
102
|
+
// 2.5 Flash Image: ~$0.04/image(Flash 系列,文生图)
|
|
103
|
+
// 3 Pro Image Preview: ~$0.15/image(Pro 系列,多图编辑)
|
|
104
|
+
"gemini-2.5-flash-image": {
|
|
105
|
+
type: "perCall",
|
|
106
|
+
cost: 0.04 * 8, // 0.32 credits/image
|
|
107
|
+
provider: "google",
|
|
108
|
+
},
|
|
109
|
+
// OpenAI image generation currently goes through the images API instead of
|
|
110
|
+
// token accounting, so register a per-image fallback price here.
|
|
111
|
+
"gpt-image-1.5": {
|
|
112
|
+
type: "perCall",
|
|
113
|
+
cost: 0.04 * 8, // 0.32 credits/image
|
|
114
|
+
provider: "openai",
|
|
115
|
+
},
|
|
116
|
+
"gpt-image-2": {
|
|
117
|
+
type: "perCall",
|
|
118
|
+
cost: 0.04 * 8, // 0.32 credits/image placeholder
|
|
119
|
+
provider: "openai",
|
|
120
|
+
},
|
|
121
|
+
"gemini-3-pro-image-preview": {
|
|
122
|
+
type: "perCall",
|
|
123
|
+
cost: 0.15 * 8, // 1.2 credits/image
|
|
124
|
+
provider: "google",
|
|
125
|
+
},
|
|
126
|
+
"gemini-3.1-flash-image-preview": {
|
|
127
|
+
type: "perCall",
|
|
128
|
+
cost: 0.067 * 8, // fallback only; Gemini handler overrides by image size
|
|
129
|
+
provider: "google",
|
|
130
|
+
},
|
|
131
|
+
|
|
132
|
+
// ── Cloudflare Browser Rendering (per-minute) ─────────
|
|
133
|
+
"cf_browser_rendering": {
|
|
134
|
+
type: "perMinute",
|
|
135
|
+
cost: 0.001 * 8, // $0.008/min
|
|
136
|
+
provider: "cloudflare",
|
|
137
|
+
},
|
|
138
|
+
|
|
139
|
+
// ── Cloudflare Workers AI Whisper (per-minute) ────────
|
|
140
|
+
// @cf/openai/whisper,价格与 DeepInfra whisper-large-v3 相近
|
|
141
|
+
"@cf/openai/whisper": {
|
|
142
|
+
type: "perMinute",
|
|
143
|
+
cost: 0.00045 * 8, // $0.0036 credits/min
|
|
144
|
+
provider: "cloudflare",
|
|
145
|
+
},
|
|
146
|
+
"@cf/myshell-ai/melotts": {
|
|
147
|
+
type: "perMinute",
|
|
148
|
+
cost: 0.00020 * 8, // $0.0016 credits/min
|
|
149
|
+
provider: "cloudflare",
|
|
150
|
+
},
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
// ─────────────────────────────────────────
|
|
154
|
+
// 计费入口
|
|
155
|
+
// ─────────────────────────────────────────
|
|
156
|
+
|
|
157
|
+
export interface ChargeExternalToolOpts {
|
|
158
|
+
userId: string;
|
|
159
|
+
/** 工具 ID,对应 EXTERNAL_TOOL_PRICING 的 key */
|
|
160
|
+
toolId: string;
|
|
161
|
+
/** 若工具调用发生在某个对话内,则回写到该 dialog 的累计成本 */
|
|
162
|
+
dialogId?: string;
|
|
163
|
+
/** token 类工具:来自 API 响应的 prompt_tokens / completion_tokens */
|
|
164
|
+
inputTokens?: number;
|
|
165
|
+
outputTokens?: number;
|
|
166
|
+
/** perMinute 类工具:音频实际时长(分钟) */
|
|
167
|
+
durationMinutes?: number;
|
|
168
|
+
/** perCall 类工具:调用次数(如按图片数量计费时传 imageCount),默认 1 */
|
|
169
|
+
count?: number;
|
|
170
|
+
/** 已由调用方基于模型配置算好的总费用(credits)。 */
|
|
171
|
+
costOverride?: number;
|
|
172
|
+
/** 扣费原因(用于事务日志) */
|
|
173
|
+
reason?: string;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export interface ChargeResult {
|
|
177
|
+
cost: number;
|
|
178
|
+
skipped: boolean;
|
|
179
|
+
reason?: string;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* 计算费用、扣余额、写 usage 记录,三步合一。
|
|
184
|
+
* 若 toolId 未注册,跳过扣费并打 warn 日志。
|
|
185
|
+
*/
|
|
186
|
+
export async function chargeExternalTool(
|
|
187
|
+
opts: ChargeExternalToolOpts
|
|
188
|
+
): Promise<ChargeResult> {
|
|
189
|
+
const {
|
|
190
|
+
userId,
|
|
191
|
+
toolId,
|
|
192
|
+
dialogId,
|
|
193
|
+
inputTokens = 0,
|
|
194
|
+
outputTokens = 0,
|
|
195
|
+
durationMinutes = 0,
|
|
196
|
+
count = 1,
|
|
197
|
+
costOverride,
|
|
198
|
+
reason,
|
|
199
|
+
} = opts;
|
|
200
|
+
|
|
201
|
+
const pricing = EXTERNAL_TOOL_PRICING[toolId];
|
|
202
|
+
if (!pricing) {
|
|
203
|
+
logger.warn({ toolId }, "Unknown external tool, skipping charge");
|
|
204
|
+
return { cost: 0, skipped: true, reason: "unknown_tool" };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// 计算 cost
|
|
208
|
+
let cost: number;
|
|
209
|
+
if (typeof costOverride === "number" && Number.isFinite(costOverride)) {
|
|
210
|
+
cost = costOverride;
|
|
211
|
+
} else if (pricing.type === "token") {
|
|
212
|
+
cost =
|
|
213
|
+
(inputTokens * pricing.input + outputTokens * pricing.output) / 1_000_000;
|
|
214
|
+
} else if (pricing.type === "perMinute") {
|
|
215
|
+
cost = durationMinutes * pricing.cost;
|
|
216
|
+
} else {
|
|
217
|
+
cost = pricing.cost * count;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
cost = Number(cost.toFixed(6));
|
|
221
|
+
if (cost <= 0) return { cost: 0, skipped: true, reason: "zero_cost" };
|
|
222
|
+
|
|
223
|
+
// 扣余额
|
|
224
|
+
const deductReason = reason ?? toolId;
|
|
225
|
+
await deductUserBalance(userId, cost, deductReason);
|
|
226
|
+
|
|
227
|
+
// 写 usage 记录(与 LLM token 记录同格式,显示在 Usage 页面)
|
|
228
|
+
await writeUsageRecord({
|
|
229
|
+
userId,
|
|
230
|
+
toolId,
|
|
231
|
+
dialogId,
|
|
232
|
+
inputTokens,
|
|
233
|
+
outputTokens,
|
|
234
|
+
cost,
|
|
235
|
+
provider: pricing.provider,
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
if (dialogId) {
|
|
239
|
+
try {
|
|
240
|
+
await applyServerDialogProjectionDelta({
|
|
241
|
+
userId,
|
|
242
|
+
dialogId,
|
|
243
|
+
inputTokensDelta: inputTokens,
|
|
244
|
+
outputTokensDelta: outputTokens,
|
|
245
|
+
costDelta: cost,
|
|
246
|
+
});
|
|
247
|
+
} catch (error) {
|
|
248
|
+
logger.warn(
|
|
249
|
+
{ err: error, userId, toolId, dialogId, cost },
|
|
250
|
+
"External tool charge persisted but dialog projection update failed",
|
|
251
|
+
);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
logger.info({ userId, toolId, inputTokens, outputTokens, cost }, "External tool charged");
|
|
256
|
+
return { cost, skipped: false };
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// ─────────────────────────────────────────
|
|
260
|
+
// 内部:写 usage 记录到 LevelDB
|
|
261
|
+
// ─────────────────────────────────────────
|
|
262
|
+
|
|
263
|
+
async function writeUsageRecord(opts: {
|
|
264
|
+
userId: string;
|
|
265
|
+
toolId: string;
|
|
266
|
+
dialogId?: string;
|
|
267
|
+
inputTokens: number;
|
|
268
|
+
outputTokens: number;
|
|
269
|
+
cost: number;
|
|
270
|
+
provider: string;
|
|
271
|
+
}): Promise<void> {
|
|
272
|
+
const { userId, toolId, dialogId, inputTokens, outputTokens, cost, provider } = opts;
|
|
273
|
+
const timestamp = Date.now();
|
|
274
|
+
const dateKey = format(timestamp, "yyyy-MM-dd");
|
|
275
|
+
const recordKey = createTokenKey.record(userId, timestamp);
|
|
276
|
+
const tokenId = ulid(timestamp);
|
|
277
|
+
|
|
278
|
+
const record = {
|
|
279
|
+
id: tokenId,
|
|
280
|
+
type: DataType.TOKEN,
|
|
281
|
+
userId,
|
|
282
|
+
username: "",
|
|
283
|
+
cybotId: "external_tool",
|
|
284
|
+
model: toolId,
|
|
285
|
+
provider,
|
|
286
|
+
dialogId: dialogId ?? `tool-${tokenId}`,
|
|
287
|
+
input_tokens: inputTokens,
|
|
288
|
+
output_tokens: outputTokens,
|
|
289
|
+
cache_creation_input_tokens: 0,
|
|
290
|
+
cache_read_input_tokens: 0,
|
|
291
|
+
cost,
|
|
292
|
+
pay: null,
|
|
293
|
+
createdAt: timestamp,
|
|
294
|
+
timestamp,
|
|
295
|
+
dateKey,
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
const statsKey = createTokenStatsKey(userId, dateKey);
|
|
299
|
+
let stats: any = null;
|
|
300
|
+
try { stats = await serverDb.get(statsKey); } catch { /* init below */ }
|
|
301
|
+
|
|
302
|
+
const inc = (s: any = { count: 0, tokens: { input: 0, output: 0 }, cost: 0 }) => ({
|
|
303
|
+
count: s.count + 1,
|
|
304
|
+
tokens: { input: s.tokens.input + inputTokens, output: s.tokens.output + outputTokens },
|
|
305
|
+
cost: s.cost + cost,
|
|
306
|
+
});
|
|
307
|
+
|
|
308
|
+
const base = stats ?? { userId, period: "day", timeKey: dateKey, total: { count: 0, tokens: { input: 0, output: 0 }, cost: 0 }, models: {}, providers: {} };
|
|
309
|
+
const newStats = {
|
|
310
|
+
...base,
|
|
311
|
+
id: statsKey,
|
|
312
|
+
type: DataType.TOKEN,
|
|
313
|
+
total: inc(base.total),
|
|
314
|
+
models: { ...base.models, [toolId]: inc(base.models?.[toolId]) },
|
|
315
|
+
providers: { ...base.providers, [provider]: inc(base.providers?.[provider]) },
|
|
316
|
+
};
|
|
317
|
+
await serverDb.batch([
|
|
318
|
+
{ type: "put", key: recordKey, value: record },
|
|
319
|
+
{ type: "put", key: statsKey, value: newStats },
|
|
320
|
+
]);
|
|
321
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { useState, useCallback, useEffect } from "react";
|
|
2
|
+
import { useAppDispatch } from "app/store";
|
|
3
|
+
import { queryUserTokensThunk } from "ai/token/tokenThunks";
|
|
4
|
+
import { TokenRecord } from "ai/token/types";
|
|
5
|
+
import { startOfDay, parseISO } from "date-fns";
|
|
6
|
+
|
|
7
|
+
const ITEMS_PER_PAGE = 10;
|
|
8
|
+
|
|
9
|
+
export interface RecordsFilter {
|
|
10
|
+
date: string; // 格式: YYYY-MM-DD
|
|
11
|
+
model: string;
|
|
12
|
+
currentPage: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
interface UseRecordsReturn {
|
|
16
|
+
records: TokenRecord[];
|
|
17
|
+
loading: boolean;
|
|
18
|
+
totalCount: number; // 现在使用后端返回的总数
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export const useRecords = (
|
|
22
|
+
userId: string,
|
|
23
|
+
filter: RecordsFilter
|
|
24
|
+
): UseRecordsReturn => {
|
|
25
|
+
const dispatch = useAppDispatch();
|
|
26
|
+
const [records, setRecords] = useState<TokenRecord[]>([]);
|
|
27
|
+
const [totalCount, setTotalCount] = useState(0);
|
|
28
|
+
const [loading, setLoading] = useState(false);
|
|
29
|
+
|
|
30
|
+
const fetchRecords = useCallback(async () => {
|
|
31
|
+
try {
|
|
32
|
+
setLoading(true);
|
|
33
|
+
// 将日期字符串解析为UTC时间
|
|
34
|
+
const date = parseISO(filter.date);
|
|
35
|
+
// 获取UTC日期的开始时间
|
|
36
|
+
const startTime = startOfDay(date).getTime();
|
|
37
|
+
|
|
38
|
+
const result = await dispatch(queryUserTokensThunk({
|
|
39
|
+
userId,
|
|
40
|
+
startTime,
|
|
41
|
+
model: filter.model === "全部模型" ? undefined : filter.model,
|
|
42
|
+
offset: ITEMS_PER_PAGE * (filter.currentPage - 1),
|
|
43
|
+
pageSize: ITEMS_PER_PAGE,
|
|
44
|
+
})).unwrap();
|
|
45
|
+
|
|
46
|
+
setRecords(result.records);
|
|
47
|
+
setTotalCount(result.total);
|
|
48
|
+
} catch (err) {
|
|
49
|
+
// 移除日志记录
|
|
50
|
+
} finally {
|
|
51
|
+
setLoading(false);
|
|
52
|
+
}
|
|
53
|
+
}, [userId, filter, dispatch]);
|
|
54
|
+
|
|
55
|
+
useEffect(() => {
|
|
56
|
+
fetchRecords();
|
|
57
|
+
}, [fetchRecords]);
|
|
58
|
+
|
|
59
|
+
return {
|
|
60
|
+
records,
|
|
61
|
+
loading,
|
|
62
|
+
totalCount,
|
|
63
|
+
};
|
|
64
|
+
};
|
|
65
|
+
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { RawUsage } from "./types";
|
|
2
|
+
|
|
3
|
+
const APPROX_CHARS_PER_TOKEN = 4;
|
|
4
|
+
|
|
5
|
+
const stringifyContent = (content: unknown): string => {
|
|
6
|
+
if (typeof content === "string") return content;
|
|
7
|
+
if (Array.isArray(content)) {
|
|
8
|
+
return content
|
|
9
|
+
.map((part) => {
|
|
10
|
+
if (typeof part === "string") return part;
|
|
11
|
+
if (part && typeof part === "object" && "text" in part) {
|
|
12
|
+
return String((part as any).text ?? "");
|
|
13
|
+
}
|
|
14
|
+
return "";
|
|
15
|
+
})
|
|
16
|
+
.join("\n");
|
|
17
|
+
}
|
|
18
|
+
if (content == null) return "";
|
|
19
|
+
return String(content);
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export const estimateMissingUsage = ({
|
|
23
|
+
content,
|
|
24
|
+
minimumOutputTokens = 1,
|
|
25
|
+
}: {
|
|
26
|
+
content: unknown;
|
|
27
|
+
minimumOutputTokens?: number;
|
|
28
|
+
}): RawUsage => {
|
|
29
|
+
const text = stringifyContent(content);
|
|
30
|
+
const estimatedOutputTokens = Math.max(
|
|
31
|
+
minimumOutputTokens,
|
|
32
|
+
Math.ceil(text.length / APPROX_CHARS_PER_TOKEN)
|
|
33
|
+
);
|
|
34
|
+
|
|
35
|
+
return {
|
|
36
|
+
input_tokens: 1,
|
|
37
|
+
output_tokens: estimatedOutputTokens,
|
|
38
|
+
cache_creation_input_tokens: 0,
|
|
39
|
+
cache_read_input_tokens: 0,
|
|
40
|
+
billing_estimated: true,
|
|
41
|
+
};
|
|
42
|
+
};
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import { createKey, createTokenKey } from "database/keys";
|
|
2
|
+
import { DataType } from "create/types";
|
|
3
|
+
|
|
4
|
+
type UsageScope = "user" | "all" | "space";
|
|
5
|
+
|
|
6
|
+
export type ModelUsageQueryParams = {
|
|
7
|
+
requestUserId: string;
|
|
8
|
+
isAdmin?: boolean;
|
|
9
|
+
scope?: UsageScope;
|
|
10
|
+
userId?: string;
|
|
11
|
+
spaceId?: string;
|
|
12
|
+
provider?: string;
|
|
13
|
+
model?: string;
|
|
14
|
+
serviceTier?: string;
|
|
15
|
+
startDate?: string;
|
|
16
|
+
endDate?: string;
|
|
17
|
+
currency?: string;
|
|
18
|
+
creditsPerUsd?: number;
|
|
19
|
+
thresholdCredits?: number;
|
|
20
|
+
thresholdUsd?: number;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
type TokenRecordLike = {
|
|
24
|
+
type?: string;
|
|
25
|
+
userId?: string;
|
|
26
|
+
timestamp?: number;
|
|
27
|
+
createdAt?: number | string;
|
|
28
|
+
dateKey?: string;
|
|
29
|
+
provider?: string;
|
|
30
|
+
model?: string;
|
|
31
|
+
billing_service_tier?: string;
|
|
32
|
+
input_tokens?: number;
|
|
33
|
+
output_tokens?: number;
|
|
34
|
+
cache_creation_input_tokens?: number;
|
|
35
|
+
cache_read_input_tokens?: number;
|
|
36
|
+
cost?: number;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
export type UsageBucket = {
|
|
40
|
+
count: number;
|
|
41
|
+
inputTokens: number;
|
|
42
|
+
outputTokens: number;
|
|
43
|
+
cacheCreationInputTokens: number;
|
|
44
|
+
cacheReadInputTokens: number;
|
|
45
|
+
costCredits: number;
|
|
46
|
+
costUsd: number;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
export type ModelUsageQueryResult = {
|
|
50
|
+
scope: Exclude<UsageScope, "space">;
|
|
51
|
+
userId: string | null;
|
|
52
|
+
startDate: string;
|
|
53
|
+
endDate: string;
|
|
54
|
+
currency: string;
|
|
55
|
+
filters: {
|
|
56
|
+
provider: string | null;
|
|
57
|
+
model: string | null;
|
|
58
|
+
serviceTier: string | null;
|
|
59
|
+
};
|
|
60
|
+
total: UsageBucket;
|
|
61
|
+
providers: Record<string, UsageBucket>;
|
|
62
|
+
models: Record<string, UsageBucket>;
|
|
63
|
+
serviceTiers: Record<string, UsageBucket>;
|
|
64
|
+
threshold: {
|
|
65
|
+
costCredits: number | null;
|
|
66
|
+
costUsd: number | null;
|
|
67
|
+
exceeded: boolean;
|
|
68
|
+
};
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
const emptyBucket = (): UsageBucket => ({
|
|
72
|
+
count: 0,
|
|
73
|
+
inputTokens: 0,
|
|
74
|
+
outputTokens: 0,
|
|
75
|
+
cacheCreationInputTokens: 0,
|
|
76
|
+
cacheReadInputTokens: 0,
|
|
77
|
+
costCredits: 0,
|
|
78
|
+
costUsd: 0,
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
const toNumber = (value: unknown): number =>
|
|
82
|
+
typeof value === "number" && Number.isFinite(value) ? value : 0;
|
|
83
|
+
|
|
84
|
+
const round6 = (value: number): number => Number(value.toFixed(6));
|
|
85
|
+
|
|
86
|
+
const normalizeDateKey = (value: unknown): string | null => {
|
|
87
|
+
if (typeof value !== "string" || !value.trim()) return null;
|
|
88
|
+
const trimmed = value.trim();
|
|
89
|
+
if (/^\d{4}-\d{2}-\d{2}$/.test(trimmed)) return trimmed;
|
|
90
|
+
const parsed = Date.parse(trimmed);
|
|
91
|
+
if (!Number.isFinite(parsed)) return null;
|
|
92
|
+
return new Date(parsed).toISOString().slice(0, 10);
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
const todayDateKey = (): string => new Date().toISOString().slice(0, 10);
|
|
96
|
+
|
|
97
|
+
const recordDateKey = (record: TokenRecordLike): string | null => {
|
|
98
|
+
const explicit = normalizeDateKey(record.dateKey);
|
|
99
|
+
if (explicit) return explicit;
|
|
100
|
+
const timestamp = toNumber(record.timestamp);
|
|
101
|
+
if (timestamp > 0) return new Date(timestamp).toISOString().slice(0, 10);
|
|
102
|
+
if (typeof record.createdAt === "number" && record.createdAt > 0) {
|
|
103
|
+
return new Date(record.createdAt).toISOString().slice(0, 10);
|
|
104
|
+
}
|
|
105
|
+
return normalizeDateKey(record.createdAt);
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
const normalizeScope = (scope: unknown): UsageScope =>
|
|
109
|
+
scope === "all" || scope === "space" || scope === "user" ? scope : "user";
|
|
110
|
+
|
|
111
|
+
const normalizeCreditsPerUsd = (value: unknown): number => {
|
|
112
|
+
const numeric = toNumber(value);
|
|
113
|
+
return numeric > 0 ? numeric : 8;
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
const addToBucket = (
|
|
117
|
+
bucket: UsageBucket,
|
|
118
|
+
record: TokenRecordLike,
|
|
119
|
+
creditsPerUsd: number,
|
|
120
|
+
) => {
|
|
121
|
+
const costCredits = toNumber(record.cost);
|
|
122
|
+
bucket.count += 1;
|
|
123
|
+
bucket.inputTokens += toNumber(record.input_tokens);
|
|
124
|
+
bucket.outputTokens += toNumber(record.output_tokens);
|
|
125
|
+
bucket.cacheCreationInputTokens += toNumber(record.cache_creation_input_tokens);
|
|
126
|
+
bucket.cacheReadInputTokens += toNumber(record.cache_read_input_tokens);
|
|
127
|
+
bucket.costCredits = round6(bucket.costCredits + costCredits);
|
|
128
|
+
bucket.costUsd = round6(bucket.costCredits / creditsPerUsd);
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
const addNamedBucket = (
|
|
132
|
+
buckets: Record<string, UsageBucket>,
|
|
133
|
+
name: string | undefined,
|
|
134
|
+
record: TokenRecordLike,
|
|
135
|
+
creditsPerUsd: number,
|
|
136
|
+
) => {
|
|
137
|
+
const key = typeof name === "string" && name.trim() ? name.trim() : "unknown";
|
|
138
|
+
buckets[key] ??= emptyBucket();
|
|
139
|
+
addToBucket(buckets[key], record, creditsPerUsd);
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
const tokenRecordRange = (scope: "user" | "all", userId: string | null) => {
|
|
143
|
+
if (scope === "user" && userId) {
|
|
144
|
+
const { start, end } = createTokenKey.rangeOfUser(userId);
|
|
145
|
+
return { gte: start, lte: end };
|
|
146
|
+
}
|
|
147
|
+
return { gte: createKey("token", ""), lte: createKey("token", "\uffff") };
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
const isTokenRecordKey = (key: string): boolean =>
|
|
151
|
+
key.startsWith(createKey("token", "")) &&
|
|
152
|
+
!key.startsWith(createKey("token", "stats", ""));
|
|
153
|
+
|
|
154
|
+
const matchesFilter = (
|
|
155
|
+
record: TokenRecordLike,
|
|
156
|
+
params: ModelUsageQueryParams,
|
|
157
|
+
startDate: string,
|
|
158
|
+
endDate: string,
|
|
159
|
+
): boolean => {
|
|
160
|
+
if (record.type !== DataType.TOKEN) return false;
|
|
161
|
+
const dateKey = recordDateKey(record);
|
|
162
|
+
if (!dateKey || dateKey < startDate || dateKey > endDate) return false;
|
|
163
|
+
if (params.provider && record.provider !== params.provider) return false;
|
|
164
|
+
if (params.model && record.model !== params.model) return false;
|
|
165
|
+
if (params.serviceTier && record.billing_service_tier !== params.serviceTier) {
|
|
166
|
+
return false;
|
|
167
|
+
}
|
|
168
|
+
return true;
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
export async function queryModelUsage(
|
|
172
|
+
db: any,
|
|
173
|
+
params: ModelUsageQueryParams,
|
|
174
|
+
): Promise<ModelUsageQueryResult> {
|
|
175
|
+
const requestUserId = params.requestUserId?.trim();
|
|
176
|
+
if (!requestUserId) {
|
|
177
|
+
throw new Error("MODEL_USAGE_FORBIDDEN: missing request user");
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const scope = normalizeScope(params.scope);
|
|
181
|
+
if (scope === "space") {
|
|
182
|
+
// TODO(space): implement usage ownership by space once token records reliably carry spaceId.
|
|
183
|
+
throw new Error("MODEL_USAGE_SPACE_SCOPE_TODO");
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
if (scope === "all" && !params.isAdmin) {
|
|
187
|
+
throw new Error("MODEL_USAGE_FORBIDDEN: all-site usage requires admin");
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const targetUserId = scope === "all" ? null : (params.userId || requestUserId).trim();
|
|
191
|
+
if (targetUserId && targetUserId !== requestUserId && !params.isAdmin) {
|
|
192
|
+
throw new Error("MODEL_USAGE_FORBIDDEN: cannot query another user");
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const startDate = normalizeDateKey(params.startDate) ?? todayDateKey();
|
|
196
|
+
const endDate = normalizeDateKey(params.endDate) ?? startDate;
|
|
197
|
+
const creditsPerUsd = normalizeCreditsPerUsd(params.creditsPerUsd);
|
|
198
|
+
const currency = typeof params.currency === "string" && params.currency.trim()
|
|
199
|
+
? params.currency.trim().toUpperCase()
|
|
200
|
+
: "CREDITS";
|
|
201
|
+
|
|
202
|
+
const total = emptyBucket();
|
|
203
|
+
const providers: Record<string, UsageBucket> = {};
|
|
204
|
+
const models: Record<string, UsageBucket> = {};
|
|
205
|
+
const serviceTiers: Record<string, UsageBucket> = {};
|
|
206
|
+
const range = tokenRecordRange(scope, targetUserId);
|
|
207
|
+
|
|
208
|
+
for await (const [key, value] of db.iterator(range)) {
|
|
209
|
+
if (typeof key !== "string" || !isTokenRecordKey(key)) continue;
|
|
210
|
+
const record = value as TokenRecordLike;
|
|
211
|
+
if (!matchesFilter(record, params, startDate, endDate)) continue;
|
|
212
|
+
addToBucket(total, record, creditsPerUsd);
|
|
213
|
+
addNamedBucket(providers, record.provider, record, creditsPerUsd);
|
|
214
|
+
addNamedBucket(models, record.model, record, creditsPerUsd);
|
|
215
|
+
addNamedBucket(serviceTiers, record.billing_service_tier, record, creditsPerUsd);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const thresholdCredits =
|
|
219
|
+
typeof params.thresholdCredits === "number" && Number.isFinite(params.thresholdCredits)
|
|
220
|
+
? params.thresholdCredits
|
|
221
|
+
: typeof params.thresholdUsd === "number" && Number.isFinite(params.thresholdUsd)
|
|
222
|
+
? round6(params.thresholdUsd * creditsPerUsd)
|
|
223
|
+
: null;
|
|
224
|
+
const thresholdUsd =
|
|
225
|
+
typeof params.thresholdUsd === "number" && Number.isFinite(params.thresholdUsd)
|
|
226
|
+
? params.thresholdUsd
|
|
227
|
+
: thresholdCredits == null
|
|
228
|
+
? null
|
|
229
|
+
: round6(thresholdCredits / creditsPerUsd);
|
|
230
|
+
|
|
231
|
+
return {
|
|
232
|
+
scope,
|
|
233
|
+
userId: targetUserId,
|
|
234
|
+
startDate,
|
|
235
|
+
endDate,
|
|
236
|
+
currency,
|
|
237
|
+
filters: {
|
|
238
|
+
provider: params.provider ?? null,
|
|
239
|
+
model: params.model ?? null,
|
|
240
|
+
serviceTier: params.serviceTier ?? null,
|
|
241
|
+
},
|
|
242
|
+
total,
|
|
243
|
+
providers,
|
|
244
|
+
models,
|
|
245
|
+
serviceTiers,
|
|
246
|
+
threshold: {
|
|
247
|
+
costCredits: thresholdCredits,
|
|
248
|
+
costUsd: thresholdUsd,
|
|
249
|
+
exceeded: thresholdCredits == null ? false : total.costCredits > thresholdCredits,
|
|
250
|
+
},
|
|
251
|
+
};
|
|
252
|
+
}
|