nolo-cli 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (239) hide show
  1. package/README.md +32 -0
  2. package/agentRuntimeCommands.ts +3 -3
  3. package/ai/agent/_executeModel.ts +118 -0
  4. package/ai/agent/agentSlice.ts +525 -0
  5. package/ai/agent/appWorkingMemory.ts +126 -0
  6. package/ai/agent/avatarUtils.ts +24 -0
  7. package/ai/agent/buildEditingContext.ts +373 -0
  8. package/ai/agent/buildSystemPrompt.ts +532 -0
  9. package/ai/agent/cleanAgentMessages.ts +140 -0
  10. package/ai/agent/cliChatClient.ts +119 -0
  11. package/ai/agent/cliExecutor.ts +733 -0
  12. package/ai/agent/cliPrompt.ts +10 -0
  13. package/ai/agent/contextCompiler.ts +107 -0
  14. package/ai/agent/contextLayerContract.ts +44 -0
  15. package/ai/agent/createAgentSchema.ts +234 -0
  16. package/ai/agent/executeToolCall.ts +58 -0
  17. package/ai/agent/fetchAgentContexts.ts +42 -0
  18. package/ai/agent/generatePrompt.ts +3 -0
  19. package/ai/agent/getFullChatContextKeys.ts +168 -0
  20. package/ai/agent/hooks/fetchPublicAgents.ts +133 -0
  21. package/ai/agent/hooks/useAgentConfig.ts +61 -0
  22. package/ai/agent/hooks/useAgentDialog.ts +35 -0
  23. package/ai/agent/hooks/useAgentFormValidation.ts +202 -0
  24. package/ai/agent/hooks/usePublicAgents.ts +473 -0
  25. package/ai/agent/machineRunPermissions.ts +95 -0
  26. package/ai/agent/persistMessageWithFixedId.ts +37 -0
  27. package/ai/agent/planSlice.ts +259 -0
  28. package/ai/agent/referenceUtils.ts +229 -0
  29. package/ai/agent/runAgentBackground.ts +238 -0
  30. package/ai/agent/runAgentClientLoop.ts +138 -0
  31. package/ai/agent/runtimeGuidance.ts +97 -0
  32. package/ai/agent/runtimeServerBase.ts +37 -0
  33. package/ai/agent/server/fetchPublicAgents.ts +128 -0
  34. package/ai/agent/startParallelAgentStreams.ts +424 -0
  35. package/ai/agent/startupProtocol.ts +53 -0
  36. package/ai/agent/streamAgentChatTurn.ts +1278 -0
  37. package/ai/agent/streamAgentChatTurnUtils.ts +738 -0
  38. package/ai/agent/types.ts +71 -0
  39. package/ai/agent/utils/imageOutput.ts +33 -0
  40. package/ai/agent/utils/sortUtils.ts +250 -0
  41. package/ai/agent/web/referencePickerUtils.ts +146 -0
  42. package/ai/ai.locale.ts +1079 -0
  43. package/ai/chat/accumulateToolCallChunks.ts +95 -0
  44. package/ai/chat/fetchUtils.native.ts +276 -0
  45. package/ai/chat/fetchUtils.ts +153 -0
  46. package/ai/chat/parseApiError.ts +64 -0
  47. package/ai/chat/parseMultilineSSE.ts +95 -0
  48. package/ai/chat/sendOpenAICompletionsRequest.native.ts +682 -0
  49. package/ai/chat/sendOpenAICompletionsRequest.ts +703 -0
  50. package/ai/chat/sendOpenAIResponseRequest.ts +491 -0
  51. package/ai/chat/shouldUseServerProxy.ts +18 -0
  52. package/ai/chat/sseClient.native.ts +91 -0
  53. package/ai/chat/sseClient.ts +67 -0
  54. package/ai/chat/streamReader.native.ts +31 -0
  55. package/ai/chat/streamReader.ts +62 -0
  56. package/ai/chat/updateTotalUsage.ts +72 -0
  57. package/ai/context/buildReferenceContext.ts +437 -0
  58. package/ai/context/calculateContextUsage.ts +133 -0
  59. package/ai/context/retention.ts +165 -0
  60. package/ai/context/tokenUtils.ts +78 -0
  61. package/ai/index.ts +1 -0
  62. package/ai/llm/calculateGeminiImageTokens.ts +57 -0
  63. package/ai/llm/deepinfra.ts +28 -0
  64. package/ai/llm/fireworks.ts +50 -0
  65. package/ai/llm/generateRequestBody.ts +165 -0
  66. package/ai/llm/getModelContextWindow.ts +84 -0
  67. package/ai/llm/getNoloKey.ts +31 -0
  68. package/ai/llm/getPricing.ts +199 -0
  69. package/ai/llm/hooks/useModelPricing.ts +75 -0
  70. package/ai/llm/imagePricing.ts +40 -0
  71. package/ai/llm/isResponseAPIModel.ts +13 -0
  72. package/ai/llm/mimo.ts +71 -0
  73. package/ai/llm/mistral.ts +22 -0
  74. package/ai/llm/modelAvatar.ts +427 -0
  75. package/ai/llm/models.ts +45 -0
  76. package/ai/llm/openrouterModels.ts +269 -0
  77. package/ai/llm/providers.ts +306 -0
  78. package/ai/llm/reasoningModels.ts +28 -0
  79. package/ai/llm/types.ts +59 -0
  80. package/ai/llm/usageRequestOptions.ts +59 -0
  81. package/ai/memory/capture.ts +148 -0
  82. package/ai/memory/consolidate.ts +104 -0
  83. package/ai/memory/delete.ts +147 -0
  84. package/ai/memory/overlay.ts +84 -0
  85. package/ai/memory/query.ts +38 -0
  86. package/ai/memory/queryShared.ts +160 -0
  87. package/ai/memory/rank.ts +105 -0
  88. package/ai/memory/recentRelationshipRecap.ts +249 -0
  89. package/ai/memory/remember.ts +167 -0
  90. package/ai/memory/runtime.ts +76 -0
  91. package/ai/memory/store.ts +20 -0
  92. package/ai/memory/storeShared.ts +76 -0
  93. package/ai/memory/types.ts +46 -0
  94. package/ai/memory/understanding.ts +349 -0
  95. package/ai/memory/understandingGreeting.ts +264 -0
  96. package/ai/messages/type.ts +20 -0
  97. package/ai/policy/personalizationDialog.ts +333 -0
  98. package/ai/policy/runtimePolicy.ts +440 -0
  99. package/ai/policy/selfUpdateFields.ts +48 -0
  100. package/ai/policy/types.ts +64 -0
  101. package/ai/skills/referenceRuntime.ts +274 -0
  102. package/ai/skills/skillDiagnostics.ts +251 -0
  103. package/ai/skills/skillDocBuilder.ts +139 -0
  104. package/ai/skills/skillDocProtocol.ts +434 -0
  105. package/ai/skills/skillReferenceSummary.ts +63 -0
  106. package/ai/skills/skillSummaryMarker.ts +26 -0
  107. package/ai/token/calculatePrice.ts +544 -0
  108. package/ai/token/db.ts +98 -0
  109. package/ai/token/externalToolCost.ts +330 -0
  110. package/ai/token/hooks/useRecords.ts +65 -0
  111. package/ai/token/missingUsageEstimate.ts +42 -0
  112. package/ai/token/modelUsageQuery.ts +252 -0
  113. package/ai/token/normalizeUsage.ts +84 -0
  114. package/ai/token/openaiImageGenerationUsage.ts +56 -0
  115. package/ai/token/prepareTokenUsageData.ts +88 -0
  116. package/ai/token/query.ts +88 -0
  117. package/ai/token/queryUserTokens.ts +59 -0
  118. package/ai/token/resolveBillingTarget.ts +52 -0
  119. package/ai/token/saveTokenRecord.ts +53 -0
  120. package/ai/token/serverDialogProjection.ts +78 -0
  121. package/ai/token/serverTokenWriter.ts +143 -0
  122. package/ai/token/stats.ts +21 -0
  123. package/ai/token/tokenThunks.ts +24 -0
  124. package/ai/token/types.ts +93 -0
  125. package/ai/tools/agent/agentTools.ts +176 -0
  126. package/ai/tools/agent/agentUpdateShared.ts +311 -0
  127. package/ai/tools/agent/callAgentTool.ts +139 -0
  128. package/ai/tools/agent/createAgentTool.ts +512 -0
  129. package/ai/tools/agent/createDialogTool.ts +69 -0
  130. package/ai/tools/agent/createSkillAgentTool.ts +62 -0
  131. package/ai/tools/agent/parallelBudget.ts +221 -0
  132. package/ai/tools/agent/presets/appBuilderPreset.ts +145 -0
  133. package/ai/tools/agent/runLlmTool.ts +96 -0
  134. package/ai/tools/agent/runStreamingAgentTool.ts +73 -0
  135. package/ai/tools/agent/skillAgentArgs.ts +106 -0
  136. package/ai/tools/agent/skillAgentPreset.ts +89 -0
  137. package/ai/tools/agent/streamParallelAgentsTool.ts +122 -0
  138. package/ai/tools/agent/updateAgentTool.ts +96 -0
  139. package/ai/tools/agent/updateSelfTool.ts +113 -0
  140. package/ai/tools/amazonProductScraperTool.ts +86 -0
  141. package/ai/tools/apifyActorClient.ts +45 -0
  142. package/ai/tools/appEditGuard.ts +372 -0
  143. package/ai/tools/appReadSnapshot.ts +153 -0
  144. package/ai/tools/appTools.ts +1549 -0
  145. package/ai/tools/applyEditTool.ts +256 -0
  146. package/ai/tools/applyLineEditsTool.ts +312 -0
  147. package/ai/tools/browserTools/click.ts +33 -0
  148. package/ai/tools/browserTools/closeSession.ts +29 -0
  149. package/ai/tools/browserTools/common.ts +27 -0
  150. package/ai/tools/browserTools/openSession.ts +48 -0
  151. package/ai/tools/browserTools/readContent.ts +38 -0
  152. package/ai/tools/browserTools/selectOption.ts +46 -0
  153. package/ai/tools/browserTools/typeText.ts +42 -0
  154. package/ai/tools/category/createCategoryTool.ts +66 -0
  155. package/ai/tools/category/queryContentsByCategoryTool.ts +69 -0
  156. package/ai/tools/category/updateContentCategoryTool.ts +75 -0
  157. package/ai/tools/cfBrowserTools.ts +319 -0
  158. package/ai/tools/cfSpeechToTextTool.ts +49 -0
  159. package/ai/tools/checkEnvTool.ts +65 -0
  160. package/ai/tools/cloudflareCrawlTool.ts +289 -0
  161. package/ai/tools/codeSearchTool.ts +111 -0
  162. package/ai/tools/codeTools.ts +101 -0
  163. package/ai/tools/createDocTool.ts +132 -0
  164. package/ai/tools/createPlanTool.ts +999 -0
  165. package/ai/tools/createSkillDocTool.ts +155 -0
  166. package/ai/tools/createWorkflowTool.ts +154 -0
  167. package/ai/tools/deepseekOcrTool.ts +34 -0
  168. package/ai/tools/delayTool.ts +31 -0
  169. package/ai/tools/deleteSpacesTool.ts +325 -0
  170. package/ai/tools/deleteSpacesToolModel.ts +159 -0
  171. package/ai/tools/devReloadUtils.ts +29 -0
  172. package/ai/tools/dialogMessageSearch.ts +137 -0
  173. package/ai/tools/doctorSkillTool.ts +72 -0
  174. package/ai/tools/ecommerceScraperTool.ts +86 -0
  175. package/ai/tools/emailTools.ts +549 -0
  176. package/ai/tools/evalSkillTool.ts +92 -0
  177. package/ai/tools/exaSearchTool.ts +64 -0
  178. package/ai/tools/execBashTool.ts +379 -0
  179. package/ai/tools/executeSqlTool.ts +192 -0
  180. package/ai/tools/fetchWebpageSupport.ts +309 -0
  181. package/ai/tools/fetchWebpageTool.ts +84 -0
  182. package/ai/tools/geminiImagePreviewTool.ts +361 -0
  183. package/ai/tools/generateDocxTool.ts +215 -0
  184. package/ai/tools/googleSearchScraperTool.ts +106 -0
  185. package/ai/tools/importDataTool.ts +133 -0
  186. package/ai/tools/importSkillTool.ts +162 -0
  187. package/ai/tools/index.ts +1858 -0
  188. package/ai/tools/listFilesTool.ts +82 -0
  189. package/ai/tools/listUserSpacesTool.ts +113 -0
  190. package/ai/tools/modelUsageTools.ts +142 -0
  191. package/ai/tools/olmOcrTool.ts +34 -0
  192. package/ai/tools/openaiImageTool.ts +218 -0
  193. package/ai/tools/paddleOcrTool.ts +34 -0
  194. package/ai/tools/prepareTools.ts +23 -0
  195. package/ai/tools/readDocTool.ts +84 -0
  196. package/ai/tools/readFileTool.ts +211 -0
  197. package/ai/tools/readTool.ts +163 -0
  198. package/ai/tools/readXPostTool.ts +233 -0
  199. package/ai/tools/rememberMemoryTool.ts +84 -0
  200. package/ai/tools/remotionVideoTool.ts +151 -0
  201. package/ai/tools/searchDialogMessagesTool.ts +222 -0
  202. package/ai/tools/searchRepoTool.ts +115 -0
  203. package/ai/tools/searchWorkspaceTool.ts +259 -0
  204. package/ai/tools/skillFollowup.ts +86 -0
  205. package/ai/tools/surfWeatherTool.ts +169 -0
  206. package/ai/tools/table/addTableRowTool.ts +217 -0
  207. package/ai/tools/table/createTableTool.ts +315 -0
  208. package/ai/tools/table/rowTools.ts +366 -0
  209. package/ai/tools/table/schemaTools.ts +244 -0
  210. package/ai/tools/table/shareTableTool.ts +148 -0
  211. package/ai/tools/table/toolShared.ts +129 -0
  212. package/ai/tools/toolApiClient.ts +198 -0
  213. package/ai/tools/toolNameAliases.ts +57 -0
  214. package/ai/tools/toolResultError.ts +42 -0
  215. package/ai/tools/toolRunSlice.ts +303 -0
  216. package/ai/tools/toolSchemaCompatibility.ts +53 -0
  217. package/ai/tools/toolVisibility.ts +4 -0
  218. package/ai/tools/types.ts +20 -0
  219. package/ai/tools/uiAskChoiceTool.ts +104 -0
  220. package/ai/tools/updateContentTitleTool.ts +84 -0
  221. package/ai/tools/updateDocTool.ts +105 -0
  222. package/ai/tools/updateUserPreferenceProfileTool.ts +145 -0
  223. package/ai/tools/whisperTool.ts +77 -0
  224. package/ai/tools/writeFileTool.ts +210 -0
  225. package/ai/tools/youtubeScraperTool.ts +116 -0
  226. package/ai/tools/ziweiChartTool.ts +678 -0
  227. package/ai/types.ts +55 -0
  228. package/ai/workflow/workflowExecutor.ts +323 -0
  229. package/ai/workflow/workflowSlice.ts +73 -0
  230. package/ai/workflow/workflowTypes.ts +106 -0
  231. package/client/compactDialog.ts +222 -0
  232. package/connector-experimental/capabilities.ts +73 -0
  233. package/connector-experimental/codexBinary.ts +41 -0
  234. package/connector-experimental/heartbeatLoop.ts +22 -0
  235. package/connector-experimental/index.ts +5 -0
  236. package/connector-experimental/machineInfo.ts +46 -0
  237. package/connector-experimental/protocol.ts +54 -0
  238. package/machineCommands.ts +4 -4
  239. package/package.json +22 -6
@@ -0,0 +1,544 @@
1
+ // 路径: ai/token/calculatePrice.ts
2
+
3
+ import { nolotusId } from "core/init";
4
+ import { Model, ModelPrice } from "ai/llm/types";
5
+ import { getModelConfig } from "ai/llm/providers";
6
+ import {
7
+ isOpenAIFlexPricedModel,
8
+ type OpenAIServiceTier,
9
+ resolveOpenAIServiceTier,
10
+ } from "integrations/openai/flexTier";
11
+
12
+ // ==================== 接口定义 ====================
13
+
14
+ /**
15
+ * 这里的 Usage 是「已经 normalize 过」的结构
16
+ * ——来自 normalizeUsage,字段名统一成这几个
17
+ */
18
+ export interface Usage {
19
+ input_tokens: number;
20
+ output_tokens: number;
21
+ cache_creation_input_tokens: number;
22
+ cache_read_input_tokens: number;
23
+ /**
24
+ * 对于 OpenRouter 等支持 usage.cost 的 provider:
25
+ * usage.cost 是 provider 返回的账户扣费金额。
26
+ * OpenRouter 官方 credits 以 USD 为基准,本仓库仍需再换算成平台 credits。
27
+ */
28
+ cost?: number;
29
+ billing_service_tier?: string;
30
+ image_generation_count?: number;
31
+ }
32
+
33
+ export interface ExternalPrice {
34
+ input: number;
35
+ output: number;
36
+ creatorId?: string;
37
+ }
38
+
39
+ interface CalculatePriceParams {
40
+ modelName: string;
41
+ usage: Usage;
42
+ externalPrice?: ExternalPrice;
43
+ /**
44
+ * provider 名称(deepseek / openrouter / anthropic 等)。
45
+ * apiSource="custom" 的 agent 不填此字段,传 undefined 即可。
46
+ * 注意:不要依赖参数默认值,调用方应显式传值或不传。
47
+ */
48
+ provider?: string;
49
+ billingServiceTier?: string;
50
+ sharingLevel?: "default" | "split" | "full";
51
+ }
52
+
53
+ export interface PriceResult {
54
+ cost: number;
55
+ pay: Record<string, number>;
56
+ }
57
+
58
+ export interface CostBreakdown {
59
+ regular: number;
60
+ charge: number;
61
+ details?: {
62
+ inputCost: number;
63
+ outputCost: number;
64
+ cachingWriteCost: number;
65
+ cachingReadCost: number;
66
+ };
67
+ }
68
+
69
+ const OPENAI_BUILTIN_IMAGE_FALLBACK_MODEL = "gpt-image-2";
70
+
71
+ const resolveOpenAIBuiltInImageSurcharge = (
72
+ model: Model,
73
+ usage: Usage,
74
+ provider?: string
75
+ ): number => {
76
+ if (provider !== "openai" || model.hasImageOutput) return 0;
77
+ const imageGenerationCount =
78
+ typeof usage.image_generation_count === "number" &&
79
+ Number.isFinite(usage.image_generation_count)
80
+ ? usage.image_generation_count
81
+ : 0;
82
+ if (imageGenerationCount <= 0) return 0;
83
+
84
+ try {
85
+ const imageModel = getModelConfig("openai", OPENAI_BUILTIN_IMAGE_FALLBACK_MODEL);
86
+ if (typeof imageModel.pricePerImage !== "number") return 0;
87
+ return imageModel.pricePerImage * imageGenerationCount;
88
+ } catch {
89
+ return 0;
90
+ }
91
+ };
92
+
93
+ // ==================== 核心逻辑:阶梯定价解析 ====================
94
+
95
+ const resolveModelPrice = (model: Model, usage: Usage): ModelPrice => {
96
+ let activePrice = { ...model.price };
97
+
98
+ if (model.pricingStrategy?.type === "tiered_context") {
99
+ const contextSize = usage.input_tokens || 0;
100
+ const tiers = model.pricingStrategy.tiers || [];
101
+
102
+ const sortedTiers = [...tiers].sort((a, b) => a.minContext - b.minContext);
103
+
104
+ for (const tier of sortedTiers) {
105
+ if (contextSize >= tier.minContext) {
106
+ activePrice = { ...tier.price };
107
+ }
108
+ }
109
+ }
110
+
111
+ return activePrice;
112
+ };
113
+
114
+ const scaleModelPrice = (price: ModelPrice, multiplier: number): ModelPrice => ({
115
+ input: price.input * multiplier,
116
+ output: price.output * multiplier,
117
+ ...(typeof price.cachingWrite === "number"
118
+ ? { cachingWrite: price.cachingWrite * multiplier }
119
+ : {}),
120
+ ...(typeof price.cachingRead === "number"
121
+ ? { cachingRead: price.cachingRead * multiplier }
122
+ : {}),
123
+ ...(typeof price.inputCacheHit === "number"
124
+ ? { inputCacheHit: price.inputCacheHit * multiplier }
125
+ : {}),
126
+ });
127
+
128
+ const scaleModelInputOutputPrice = (
129
+ price: ModelPrice,
130
+ multiplier: number
131
+ ): ModelPrice => ({
132
+ ...price,
133
+ input: price.input * multiplier,
134
+ output: price.output * multiplier,
135
+ });
136
+
137
+ const resolveGoogleServiceTierPrice = (
138
+ model: Model,
139
+ price: ModelPrice,
140
+ billingServiceTier?: string
141
+ ): ModelPrice => {
142
+ const normalizedTier =
143
+ typeof billingServiceTier === "string"
144
+ ? billingServiceTier.trim().toLowerCase()
145
+ : "";
146
+ const imageOutputPrice =
147
+ typeof model.imageTokenPricePerMillion === "number"
148
+ ? model.imageTokenPricePerMillion
149
+ : undefined;
150
+ const priceWithImageOutput =
151
+ typeof imageOutputPrice === "number"
152
+ ? { ...price, output: imageOutputPrice }
153
+ : price;
154
+
155
+ if (normalizedTier === "flex" || normalizedTier === "batch") {
156
+ return scaleModelInputOutputPrice(priceWithImageOutput, 0.5);
157
+ }
158
+
159
+ if (normalizedTier === "priority") {
160
+ return scaleModelInputOutputPrice(priceWithImageOutput, 1.8);
161
+ }
162
+
163
+ return priceWithImageOutput;
164
+ };
165
+
166
+ const resolveEffectiveModelPrice = ({
167
+ model,
168
+ usage,
169
+ provider,
170
+ billingServiceTier,
171
+ }: {
172
+ model: Model;
173
+ usage: Usage;
174
+ provider: string;
175
+ billingServiceTier?: string;
176
+ }): ModelPrice => {
177
+ const resolvedPrice = resolveModelPrice(model, usage);
178
+ if (provider === "google") {
179
+ return resolveGoogleServiceTierPrice(model, resolvedPrice, billingServiceTier);
180
+ }
181
+ const effectiveOpenAIServiceTier = resolveOpenAIServiceTier({
182
+ providerName: provider,
183
+ model: model.name,
184
+ requestedServiceTier: billingServiceTier as OpenAIServiceTier | undefined,
185
+ });
186
+
187
+ if (provider === "openai" && effectiveOpenAIServiceTier === "flex") {
188
+ if (isOpenAIFlexPricedModel(model.name)) {
189
+ return resolvedPrice;
190
+ }
191
+ return scaleModelPrice(resolvedPrice, 0.5);
192
+ }
193
+
194
+ return resolvedPrice;
195
+ };
196
+
197
+ // ==================== 辅助逻辑:价格保护 ====================
198
+
199
+ const getEffectivePrices = (
200
+ resolvedPrice: ModelPrice,
201
+ externalPrice?: ExternalPrice
202
+ ): {
203
+ input: number;
204
+ output: number;
205
+ cachingWrite: number;
206
+ cachingRead: number;
207
+ } => {
208
+ const effectiveInputPrice = Math.max(
209
+ externalPrice?.input || 0,
210
+ resolvedPrice.input
211
+ );
212
+ const effectiveOutputPrice = Math.max(
213
+ externalPrice?.output || 0,
214
+ resolvedPrice.output
215
+ );
216
+
217
+ return {
218
+ input: effectiveInputPrice,
219
+ output: effectiveOutputPrice,
220
+ cachingWrite: resolvedPrice.cachingWrite || 0,
221
+ cachingRead: resolvedPrice.cachingRead || 0,
222
+ };
223
+ };
224
+
225
+ // ==================== 具体计算函数 ====================
226
+
227
+ const calculateAnthropicCost = (
228
+ resolvedPrice: ModelPrice,
229
+ usage: Usage,
230
+ externalPrice?: ExternalPrice
231
+ ): CostBreakdown => {
232
+ const {
233
+ input_tokens,
234
+ output_tokens,
235
+ cache_creation_input_tokens,
236
+ cache_read_input_tokens,
237
+ } = usage;
238
+
239
+ const {
240
+ input: effectiveInputPrice,
241
+ output: effectiveOutputPrice,
242
+ cachingWrite: effectiveCachingWritePrice,
243
+ cachingRead: effectiveCachingReadPrice,
244
+ } = getEffectivePrices(resolvedPrice, externalPrice);
245
+
246
+ const regularInputTokens = input_tokens - cache_read_input_tokens;
247
+
248
+ const regularTotal =
249
+ (regularInputTokens * resolvedPrice.input +
250
+ output_tokens * resolvedPrice.output +
251
+ cache_creation_input_tokens * (resolvedPrice.cachingWrite || 0) +
252
+ cache_read_input_tokens * (resolvedPrice.cachingRead || 0)) /
253
+ 1_000_000;
254
+
255
+ const chargeTotal =
256
+ (regularInputTokens * effectiveInputPrice +
257
+ output_tokens * effectiveOutputPrice +
258
+ cache_creation_input_tokens * effectiveCachingWritePrice +
259
+ cache_read_input_tokens * effectiveCachingReadPrice) /
260
+ 1_000_000;
261
+
262
+ return {
263
+ regular: regularTotal,
264
+ charge: chargeTotal,
265
+ details: {
266
+ inputCost: (regularInputTokens * resolvedPrice.input) / 1_000_000,
267
+ outputCost: (output_tokens * resolvedPrice.output) / 1_000_000,
268
+ cachingWriteCost:
269
+ (cache_creation_input_tokens * (resolvedPrice.cachingWrite || 0)) /
270
+ 1_000_000,
271
+ cachingReadCost:
272
+ (cache_read_input_tokens * (resolvedPrice.cachingRead || 0)) /
273
+ 1_000_000,
274
+ },
275
+ };
276
+ };
277
+
278
+ const calculateCacheBasedCost = (
279
+ resolvedPrice: ModelPrice,
280
+ usage: Usage,
281
+ externalPrice?: ExternalPrice
282
+ ): CostBreakdown => {
283
+ const { input_tokens, output_tokens, cache_read_input_tokens } = usage;
284
+ const { input: effectiveInputPrice, output: effectiveOutputPrice } =
285
+ getEffectivePrices(resolvedPrice, externalPrice);
286
+
287
+ const cacheMissTokens = input_tokens - cache_read_input_tokens;
288
+ const cacheHitPrice = resolvedPrice.inputCacheHit || 0;
289
+
290
+ const regularTotal =
291
+ (cacheMissTokens * resolvedPrice.input +
292
+ cache_read_input_tokens * cacheHitPrice +
293
+ output_tokens * resolvedPrice.output) /
294
+ 1_000_000;
295
+
296
+ const chargeTotal =
297
+ (cacheMissTokens * effectiveInputPrice +
298
+ cache_read_input_tokens * cacheHitPrice +
299
+ output_tokens * effectiveOutputPrice) /
300
+ 1_000_000;
301
+
302
+ return {
303
+ regular: regularTotal,
304
+ charge: chargeTotal,
305
+ details: {
306
+ inputCost: (cacheMissTokens * resolvedPrice.input) / 1_000_000,
307
+ outputCost: (output_tokens * resolvedPrice.output) / 1_000_000,
308
+ cachingReadCost: (cache_read_input_tokens * cacheHitPrice) / 1_000_000,
309
+ cachingWriteCost: 0,
310
+ },
311
+ };
312
+ };
313
+
314
+ const calculateSimpleCost = (
315
+ resolvedPrice: ModelPrice,
316
+ usage: Usage,
317
+ externalPrice?: ExternalPrice
318
+ ): CostBreakdown => {
319
+ const { input_tokens, output_tokens } = usage;
320
+ const { input: effectiveInputPrice, output: effectiveOutputPrice } =
321
+ getEffectivePrices(resolvedPrice, externalPrice);
322
+
323
+ const regularTotal =
324
+ (input_tokens * resolvedPrice.input +
325
+ output_tokens * resolvedPrice.output) /
326
+ 1_000_000;
327
+
328
+ const chargeTotal =
329
+ (input_tokens * effectiveInputPrice +
330
+ output_tokens * effectiveOutputPrice) /
331
+ 1_000_000;
332
+
333
+ return {
334
+ regular: regularTotal,
335
+ charge: chargeTotal,
336
+ details: {
337
+ inputCost: (input_tokens * resolvedPrice.input) / 1_000_000,
338
+ outputCost: (output_tokens * resolvedPrice.output) / 1_000_000,
339
+ cachingWriteCost: 0,
340
+ cachingReadCost: 0,
341
+ },
342
+ };
343
+ };
344
+
345
+ const calculateOpenRouterFallbackCost = (
346
+ resolvedPrice: ModelPrice,
347
+ usage: Usage,
348
+ externalPrice?: ExternalPrice
349
+ ): CostBreakdown => {
350
+ if (
351
+ typeof resolvedPrice.cachingWrite === "number" ||
352
+ typeof resolvedPrice.cachingRead === "number"
353
+ ) {
354
+ return calculateAnthropicCost(resolvedPrice, usage, externalPrice);
355
+ }
356
+
357
+ if (typeof resolvedPrice.inputCacheHit === "number") {
358
+ return calculateCacheBasedCost(resolvedPrice, usage, externalPrice);
359
+ }
360
+
361
+ return calculateSimpleCost(resolvedPrice, usage, externalPrice);
362
+ };
363
+
364
+ // OpenRouter usage.cost 是按其账户 credit(USD 基准)返回,
365
+ // 本平台统一按 1 USD = 8 credits 记账,因此这里仍需做一次换算。
366
+ const OPENROUTER_COST_MULTIPLIER = 8;
367
+
368
+ const calculateOpenRouterCost = (usage: Usage): CostBreakdown => {
369
+ if (!usage || typeof usage.cost !== "number" || usage.cost <= 0) {
370
+ return {
371
+ regular: 0,
372
+ charge: 0,
373
+ details: {
374
+ inputCost: 0,
375
+ outputCost: 0,
376
+ cachingWriteCost: 0,
377
+ cachingReadCost: 0,
378
+ },
379
+ };
380
+ }
381
+
382
+ const regular = usage.cost * OPENROUTER_COST_MULTIPLIER;
383
+
384
+ return {
385
+ regular,
386
+ charge: regular,
387
+ details: {
388
+ inputCost: regular,
389
+ outputCost: 0,
390
+ cachingWriteCost: 0,
391
+ cachingReadCost: 0,
392
+ },
393
+ };
394
+ };
395
+
396
+ // ==================== 路由与分发 ====================
397
+
398
+ const calculateBasicCost = (
399
+ model: Model,
400
+ usage: Usage,
401
+ provider: string,
402
+ externalPrice?: ExternalPrice,
403
+ billingServiceTier?: OpenAIServiceTier
404
+ ): CostBreakdown => {
405
+ if (!usage || typeof usage.input_tokens !== "number") {
406
+ throw new Error("Invalid usage data");
407
+ }
408
+
409
+ const resolvedPrice = resolveEffectiveModelPrice({
410
+ model,
411
+ usage,
412
+ provider,
413
+ billingServiceTier,
414
+ });
415
+
416
+ switch (provider) {
417
+ case "deepseek":
418
+ case "openai":
419
+ case "deepinfra":
420
+ return calculateCacheBasedCost(resolvedPrice, usage, externalPrice);
421
+
422
+ case "anthropic":
423
+ return calculateAnthropicCost(resolvedPrice, usage, externalPrice);
424
+
425
+ case "google":
426
+ if (model.name.includes("gemini-3")) {
427
+ return calculateAnthropicCost(resolvedPrice, usage, externalPrice);
428
+ }
429
+ return calculateSimpleCost(resolvedPrice, usage, externalPrice);
430
+
431
+ case "openrouter": {
432
+ const orCost = calculateOpenRouterCost(usage);
433
+ if (orCost.regular > 0) return orCost;
434
+ return calculateOpenRouterFallbackCost(
435
+ resolvedPrice,
436
+ usage,
437
+ externalPrice
438
+ );
439
+ }
440
+
441
+ case "mistral":
442
+ case "xai":
443
+ case "fireworks":
444
+ default:
445
+ return calculateSimpleCost(resolvedPrice, usage, externalPrice);
446
+ }
447
+ };
448
+
449
+ const calculatePayDistribution = (
450
+ costs: CostBreakdown,
451
+ externalPrice?: ExternalPrice,
452
+ sharingLevel: "default" | "split" | "full"
453
+ ): Record<string, number> => {
454
+ const pay: Record<string, number> = {};
455
+
456
+ pay[nolotusId] = costs.regular;
457
+
458
+ const sharingRatios = {
459
+ default: 0,
460
+ split: 0.5,
461
+ full: 1,
462
+ };
463
+
464
+ if (externalPrice?.creatorId) {
465
+ const profit = Math.max(0, costs.charge - costs.regular);
466
+
467
+ if (profit > 0) {
468
+ switch (sharingLevel) {
469
+ case "split":
470
+ pay[externalPrice.creatorId] = profit * sharingRatios.split;
471
+ break;
472
+ case "full":
473
+ pay[externalPrice.creatorId] = profit;
474
+ break;
475
+ default:
476
+ break;
477
+ }
478
+ }
479
+ }
480
+
481
+ return Object.fromEntries(
482
+ Object.entries(pay).map(([key, value]) => [
483
+ key,
484
+ Number(value.toFixed(6)),
485
+ ])
486
+ );
487
+ };
488
+
489
+ export const calculatePrice = ({
490
+ modelName,
491
+ usage,
492
+ externalPrice,
493
+ // 不设默认值,undefined 表示 custom/未知 provider,走 zeroCostModel 路径
494
+ provider,
495
+ billingServiceTier,
496
+ sharingLevel = "default",
497
+ }: CalculatePriceParams): PriceResult => {
498
+ // apiSource="custom" 的 agent 不一定有 provider,或 provider 不在 MODEL_MAP 里。
499
+ // 此时平台不承担 API 成本(由 agent owner 自费),但 agent 可能对外设有 inputPrice/outputPrice,
500
+ // 仍需走 externalPrice 计费路径向用户收费并分成给创作者。
501
+ // 用零成本的虚拟 model 代替,让 calculateBasicCost 正常走 externalPrice 分支。
502
+ let model: ReturnType<typeof getModelConfig>;
503
+ try {
504
+ model = getModelConfig(provider, modelName);
505
+ } catch {
506
+ const zeroCostModel: Model = {
507
+ name: modelName,
508
+ hasVision: false,
509
+ price: { input: 0, output: 0 },
510
+ };
511
+ const costs = calculateBasicCost(
512
+ zeroCostModel,
513
+ usage,
514
+ "custom",
515
+ externalPrice,
516
+ billingServiceTier
517
+ );
518
+ const pay = calculatePayDistribution(costs, externalPrice, sharingLevel);
519
+ return { cost: Number(costs.charge.toFixed(6)), pay };
520
+ }
521
+
522
+ const costs = calculateBasicCost(
523
+ model,
524
+ usage,
525
+ provider,
526
+ externalPrice,
527
+ billingServiceTier
528
+ );
529
+ const openaiBuiltInImageSurcharge = resolveOpenAIBuiltInImageSurcharge(
530
+ model,
531
+ usage,
532
+ provider
533
+ );
534
+ if (openaiBuiltInImageSurcharge > 0) {
535
+ costs.regular += openaiBuiltInImageSurcharge;
536
+ costs.charge += openaiBuiltInImageSurcharge;
537
+ }
538
+ const pay = calculatePayDistribution(costs, externalPrice, sharingLevel);
539
+
540
+ return {
541
+ cost: Number(costs.charge.toFixed(6)),
542
+ pay,
543
+ };
544
+ };
package/ai/token/db.ts ADDED
@@ -0,0 +1,98 @@
1
+ import { createTokenStatsKey } from "database/keys";
2
+ import { TokenUsageData } from "./types";
3
+ import { ulid } from "ulid";
4
+ import { createInitialDayStats } from "./stats";
5
+ import { format } from "date-fns";
6
+ import { pino } from "pino";
7
+ import { DataType } from "create/types";
8
+ import { read, write } from "database/dbSlice";
9
+
10
+ interface TokenCount {
11
+ input: number;
12
+ output: number;
13
+ }
14
+
15
+ interface ModelStats {
16
+ count: number;
17
+ tokens: TokenCount;
18
+ cost: number;
19
+ }
20
+
21
+ interface DayStats {
22
+ userId: string;
23
+ period: "day";
24
+ timeKey: string;
25
+ total: { count: number; tokens: TokenCount; cost: number };
26
+ models: Record<string, ModelStats>;
27
+ providers: Record<string, ModelStats>;
28
+ }
29
+
30
+ const logger = pino({ name: "token-db" });
31
+
32
+ const updateStats = (
33
+ data: TokenUsageData,
34
+ stats: ModelStats = { count: 0, tokens: { input: 0, output: 0 }, cost: 0 }
35
+ ) => ({
36
+ count: stats.count + 1,
37
+ tokens: {
38
+ input: stats.tokens.input + data.input_tokens,
39
+ output: stats.tokens.output + data.output_tokens,
40
+ },
41
+ cost: stats.cost + data.cost,
42
+ });
43
+
44
+ export const saveTokenUsage = async (data: TokenUsageData, thunkApi) => {
45
+ try {
46
+ const dateKey = format(Date.now(), "yyyy-MM-dd");
47
+ const key = createTokenStatsKey(data.userId, dateKey);
48
+
49
+ // Get current stats or create initial stats
50
+ const currentStats = await thunkApi.dispatch(read({
51
+ dbKey: key
52
+ })).unwrap();
53
+ const stats = currentStats?.total
54
+ ? currentStats
55
+ : createInitialDayStats(data.userId, dateKey);
56
+
57
+ // Update stats with new data
58
+ const cleanModels = { ...stats.models };
59
+ ["unknown", "undefined"].forEach((key) => delete cleanModels[key]);
60
+
61
+ const modelName = data.model || "unknown";
62
+ const providerName = data.provider || "unknown";
63
+
64
+ const updatedStats = {
65
+ ...stats,
66
+ total: updateStats(data, stats.total),
67
+ models: {
68
+ ...cleanModels,
69
+ [modelName]: updateStats(data, cleanModels[modelName]),
70
+ },
71
+ providers: {
72
+ ...stats.providers,
73
+ [providerName]: updateStats(data, stats.providers[providerName]),
74
+ },
75
+ };
76
+
77
+ logger.info({ updatedStats }, "Updated day stats");
78
+
79
+ // Save updated stats
80
+ await thunkApi.dispatch(
81
+ write({
82
+ data: { ...updatedStats, id: key, type: DataType.TOKEN },
83
+ customKey: key,
84
+ })
85
+ );
86
+
87
+ logger.info({ currentStats, updatedStats }, "Saved day stats");
88
+
89
+ return {
90
+ success: true,
91
+ id: ulid(Date.now()),
92
+ record: updatedStats,
93
+ };
94
+ } catch (error) {
95
+ logger.error({ error }, "Failed to save token usage");
96
+ throw error;
97
+ }
98
+ };