nolo-cli 0.1.10 → 0.1.12

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 (232) hide show
  1. package/README.md +0 -32
  2. package/agentRuntimeCommands.ts +1 -1
  3. package/client/compactDialog.ts +2 -5
  4. package/commandRegistry.ts +2 -2
  5. package/machineCommands.ts +28 -3
  6. package/package.json +5 -25
  7. package/ai/agent/_executeModel.ts +0 -118
  8. package/ai/agent/agentSlice.ts +0 -525
  9. package/ai/agent/appWorkingMemory.ts +0 -126
  10. package/ai/agent/avatarUtils.ts +0 -24
  11. package/ai/agent/buildEditingContext.ts +0 -373
  12. package/ai/agent/buildSystemPrompt.ts +0 -532
  13. package/ai/agent/cleanAgentMessages.ts +0 -140
  14. package/ai/agent/cliChatClient.ts +0 -119
  15. package/ai/agent/contextCompiler.ts +0 -107
  16. package/ai/agent/contextLayerContract.ts +0 -44
  17. package/ai/agent/createAgentSchema.ts +0 -234
  18. package/ai/agent/executeToolCall.ts +0 -58
  19. package/ai/agent/fetchAgentContexts.ts +0 -42
  20. package/ai/agent/generatePrompt.ts +0 -3
  21. package/ai/agent/getFullChatContextKeys.ts +0 -168
  22. package/ai/agent/hooks/fetchPublicAgents.ts +0 -133
  23. package/ai/agent/hooks/useAgentConfig.ts +0 -61
  24. package/ai/agent/hooks/useAgentDialog.ts +0 -35
  25. package/ai/agent/hooks/useAgentFormValidation.ts +0 -202
  26. package/ai/agent/hooks/usePublicAgents.ts +0 -473
  27. package/ai/agent/persistMessageWithFixedId.ts +0 -37
  28. package/ai/agent/planSlice.ts +0 -259
  29. package/ai/agent/referenceUtils.ts +0 -229
  30. package/ai/agent/runAgentBackground.ts +0 -238
  31. package/ai/agent/runAgentClientLoop.ts +0 -138
  32. package/ai/agent/runtimeGuidance.ts +0 -97
  33. package/ai/agent/runtimeServerBase.ts +0 -37
  34. package/ai/agent/server/fetchPublicAgents.ts +0 -128
  35. package/ai/agent/startParallelAgentStreams.ts +0 -424
  36. package/ai/agent/startupProtocol.ts +0 -53
  37. package/ai/agent/streamAgentChatTurn.ts +0 -1278
  38. package/ai/agent/streamAgentChatTurnUtils.ts +0 -738
  39. package/ai/agent/types.ts +0 -71
  40. package/ai/agent/utils/imageOutput.ts +0 -33
  41. package/ai/agent/utils/sortUtils.ts +0 -250
  42. package/ai/agent/web/referencePickerUtils.ts +0 -146
  43. package/ai/ai.locale.ts +0 -1079
  44. package/ai/chat/accumulateToolCallChunks.ts +0 -95
  45. package/ai/chat/fetchUtils.native.ts +0 -276
  46. package/ai/chat/fetchUtils.ts +0 -153
  47. package/ai/chat/parseApiError.ts +0 -64
  48. package/ai/chat/parseMultilineSSE.ts +0 -95
  49. package/ai/chat/sendOpenAICompletionsRequest.native.ts +0 -682
  50. package/ai/chat/sendOpenAICompletionsRequest.ts +0 -703
  51. package/ai/chat/sendOpenAIResponseRequest.ts +0 -491
  52. package/ai/chat/shouldUseServerProxy.ts +0 -18
  53. package/ai/chat/sseClient.native.ts +0 -91
  54. package/ai/chat/sseClient.ts +0 -67
  55. package/ai/chat/streamReader.native.ts +0 -31
  56. package/ai/chat/streamReader.ts +0 -62
  57. package/ai/chat/updateTotalUsage.ts +0 -72
  58. package/ai/context/buildReferenceContext.ts +0 -437
  59. package/ai/context/calculateContextUsage.ts +0 -133
  60. package/ai/context/retention.ts +0 -165
  61. package/ai/context/tokenUtils.ts +0 -78
  62. package/ai/index.ts +0 -1
  63. package/ai/llm/calculateGeminiImageTokens.ts +0 -57
  64. package/ai/llm/deepinfra.ts +0 -28
  65. package/ai/llm/fireworks.ts +0 -50
  66. package/ai/llm/generateRequestBody.ts +0 -165
  67. package/ai/llm/getModelContextWindow.ts +0 -84
  68. package/ai/llm/getNoloKey.ts +0 -31
  69. package/ai/llm/getPricing.ts +0 -199
  70. package/ai/llm/hooks/useModelPricing.ts +0 -75
  71. package/ai/llm/imagePricing.ts +0 -40
  72. package/ai/llm/isResponseAPIModel.ts +0 -13
  73. package/ai/llm/mimo.ts +0 -71
  74. package/ai/llm/mistral.ts +0 -22
  75. package/ai/llm/modelAvatar.ts +0 -427
  76. package/ai/llm/models.ts +0 -45
  77. package/ai/llm/openrouterModels.ts +0 -269
  78. package/ai/llm/providers.ts +0 -306
  79. package/ai/llm/reasoningModels.ts +0 -28
  80. package/ai/llm/types.ts +0 -59
  81. package/ai/llm/usageRequestOptions.ts +0 -59
  82. package/ai/memory/capture.ts +0 -148
  83. package/ai/memory/consolidate.ts +0 -104
  84. package/ai/memory/delete.ts +0 -147
  85. package/ai/memory/overlay.ts +0 -84
  86. package/ai/memory/query.ts +0 -38
  87. package/ai/memory/queryShared.ts +0 -160
  88. package/ai/memory/rank.ts +0 -105
  89. package/ai/memory/recentRelationshipRecap.ts +0 -249
  90. package/ai/memory/remember.ts +0 -167
  91. package/ai/memory/runtime.ts +0 -76
  92. package/ai/memory/store.ts +0 -20
  93. package/ai/memory/storeShared.ts +0 -76
  94. package/ai/memory/types.ts +0 -46
  95. package/ai/memory/understanding.ts +0 -349
  96. package/ai/memory/understandingGreeting.ts +0 -264
  97. package/ai/messages/type.ts +0 -20
  98. package/ai/policy/personalizationDialog.ts +0 -333
  99. package/ai/policy/runtimePolicy.ts +0 -440
  100. package/ai/policy/selfUpdateFields.ts +0 -48
  101. package/ai/policy/types.ts +0 -64
  102. package/ai/skills/referenceRuntime.ts +0 -274
  103. package/ai/skills/skillDiagnostics.ts +0 -251
  104. package/ai/skills/skillDocBuilder.ts +0 -139
  105. package/ai/skills/skillDocProtocol.ts +0 -434
  106. package/ai/skills/skillReferenceSummary.ts +0 -63
  107. package/ai/skills/skillSummaryMarker.ts +0 -26
  108. package/ai/token/calculatePrice.ts +0 -544
  109. package/ai/token/db.ts +0 -98
  110. package/ai/token/externalToolCost.ts +0 -330
  111. package/ai/token/hooks/useRecords.ts +0 -65
  112. package/ai/token/missingUsageEstimate.ts +0 -42
  113. package/ai/token/modelUsageQuery.ts +0 -252
  114. package/ai/token/normalizeUsage.ts +0 -84
  115. package/ai/token/openaiImageGenerationUsage.ts +0 -56
  116. package/ai/token/prepareTokenUsageData.ts +0 -88
  117. package/ai/token/query.ts +0 -88
  118. package/ai/token/queryUserTokens.ts +0 -59
  119. package/ai/token/resolveBillingTarget.ts +0 -52
  120. package/ai/token/saveTokenRecord.ts +0 -53
  121. package/ai/token/serverDialogProjection.ts +0 -78
  122. package/ai/token/serverTokenWriter.ts +0 -143
  123. package/ai/token/stats.ts +0 -21
  124. package/ai/token/tokenThunks.ts +0 -24
  125. package/ai/token/types.ts +0 -93
  126. package/ai/tools/agent/agentTools.ts +0 -176
  127. package/ai/tools/agent/agentUpdateShared.ts +0 -311
  128. package/ai/tools/agent/callAgentTool.ts +0 -139
  129. package/ai/tools/agent/createAgentTool.ts +0 -512
  130. package/ai/tools/agent/createDialogTool.ts +0 -69
  131. package/ai/tools/agent/createSkillAgentTool.ts +0 -62
  132. package/ai/tools/agent/parallelBudget.ts +0 -221
  133. package/ai/tools/agent/presets/appBuilderPreset.ts +0 -145
  134. package/ai/tools/agent/runLlmTool.ts +0 -96
  135. package/ai/tools/agent/runStreamingAgentTool.ts +0 -73
  136. package/ai/tools/agent/skillAgentArgs.ts +0 -106
  137. package/ai/tools/agent/skillAgentPreset.ts +0 -89
  138. package/ai/tools/agent/streamParallelAgentsTool.ts +0 -122
  139. package/ai/tools/agent/updateAgentTool.ts +0 -96
  140. package/ai/tools/agent/updateSelfTool.ts +0 -113
  141. package/ai/tools/amazonProductScraperTool.ts +0 -86
  142. package/ai/tools/apifyActorClient.ts +0 -45
  143. package/ai/tools/appEditGuard.ts +0 -372
  144. package/ai/tools/appReadSnapshot.ts +0 -153
  145. package/ai/tools/appTools.ts +0 -1549
  146. package/ai/tools/applyEditTool.ts +0 -256
  147. package/ai/tools/applyLineEditsTool.ts +0 -312
  148. package/ai/tools/browserTools/click.ts +0 -33
  149. package/ai/tools/browserTools/closeSession.ts +0 -29
  150. package/ai/tools/browserTools/common.ts +0 -27
  151. package/ai/tools/browserTools/openSession.ts +0 -48
  152. package/ai/tools/browserTools/readContent.ts +0 -38
  153. package/ai/tools/browserTools/selectOption.ts +0 -46
  154. package/ai/tools/browserTools/typeText.ts +0 -42
  155. package/ai/tools/category/createCategoryTool.ts +0 -66
  156. package/ai/tools/category/queryContentsByCategoryTool.ts +0 -69
  157. package/ai/tools/category/updateContentCategoryTool.ts +0 -75
  158. package/ai/tools/cfBrowserTools.ts +0 -319
  159. package/ai/tools/cfSpeechToTextTool.ts +0 -49
  160. package/ai/tools/checkEnvTool.ts +0 -65
  161. package/ai/tools/cloudflareCrawlTool.ts +0 -289
  162. package/ai/tools/codeSearchTool.ts +0 -111
  163. package/ai/tools/codeTools.ts +0 -101
  164. package/ai/tools/createDocTool.ts +0 -132
  165. package/ai/tools/createPlanTool.ts +0 -999
  166. package/ai/tools/createSkillDocTool.ts +0 -155
  167. package/ai/tools/createWorkflowTool.ts +0 -154
  168. package/ai/tools/deepseekOcrTool.ts +0 -34
  169. package/ai/tools/delayTool.ts +0 -31
  170. package/ai/tools/deleteSpacesTool.ts +0 -325
  171. package/ai/tools/deleteSpacesToolModel.ts +0 -159
  172. package/ai/tools/devReloadUtils.ts +0 -29
  173. package/ai/tools/dialogMessageSearch.ts +0 -137
  174. package/ai/tools/doctorSkillTool.ts +0 -72
  175. package/ai/tools/ecommerceScraperTool.ts +0 -86
  176. package/ai/tools/emailTools.ts +0 -549
  177. package/ai/tools/evalSkillTool.ts +0 -92
  178. package/ai/tools/exaSearchTool.ts +0 -64
  179. package/ai/tools/execBashTool.ts +0 -379
  180. package/ai/tools/executeSqlTool.ts +0 -192
  181. package/ai/tools/fetchWebpageSupport.ts +0 -309
  182. package/ai/tools/fetchWebpageTool.ts +0 -84
  183. package/ai/tools/geminiImagePreviewTool.ts +0 -361
  184. package/ai/tools/generateDocxTool.ts +0 -215
  185. package/ai/tools/googleSearchScraperTool.ts +0 -106
  186. package/ai/tools/importDataTool.ts +0 -133
  187. package/ai/tools/importSkillTool.ts +0 -162
  188. package/ai/tools/index.ts +0 -1858
  189. package/ai/tools/listFilesTool.ts +0 -82
  190. package/ai/tools/listUserSpacesTool.ts +0 -113
  191. package/ai/tools/modelUsageTools.ts +0 -142
  192. package/ai/tools/olmOcrTool.ts +0 -34
  193. package/ai/tools/openaiImageTool.ts +0 -218
  194. package/ai/tools/paddleOcrTool.ts +0 -34
  195. package/ai/tools/prepareTools.ts +0 -23
  196. package/ai/tools/readDocTool.ts +0 -84
  197. package/ai/tools/readFileTool.ts +0 -211
  198. package/ai/tools/readTool.ts +0 -163
  199. package/ai/tools/readXPostTool.ts +0 -233
  200. package/ai/tools/rememberMemoryTool.ts +0 -84
  201. package/ai/tools/remotionVideoTool.ts +0 -151
  202. package/ai/tools/searchDialogMessagesTool.ts +0 -222
  203. package/ai/tools/searchRepoTool.ts +0 -115
  204. package/ai/tools/searchWorkspaceTool.ts +0 -259
  205. package/ai/tools/skillFollowup.ts +0 -86
  206. package/ai/tools/surfWeatherTool.ts +0 -169
  207. package/ai/tools/table/addTableRowTool.ts +0 -217
  208. package/ai/tools/table/createTableTool.ts +0 -315
  209. package/ai/tools/table/rowTools.ts +0 -366
  210. package/ai/tools/table/schemaTools.ts +0 -244
  211. package/ai/tools/table/shareTableTool.ts +0 -148
  212. package/ai/tools/table/toolShared.ts +0 -129
  213. package/ai/tools/toolApiClient.ts +0 -198
  214. package/ai/tools/toolNameAliases.ts +0 -57
  215. package/ai/tools/toolResultError.ts +0 -42
  216. package/ai/tools/toolRunSlice.ts +0 -303
  217. package/ai/tools/toolSchemaCompatibility.ts +0 -53
  218. package/ai/tools/toolVisibility.ts +0 -4
  219. package/ai/tools/types.ts +0 -20
  220. package/ai/tools/uiAskChoiceTool.ts +0 -104
  221. package/ai/tools/updateContentTitleTool.ts +0 -84
  222. package/ai/tools/updateDocTool.ts +0 -105
  223. package/ai/tools/updateUserPreferenceProfileTool.ts +0 -145
  224. package/ai/tools/whisperTool.ts +0 -77
  225. package/ai/tools/writeFileTool.ts +0 -210
  226. package/ai/tools/youtubeScraperTool.ts +0 -116
  227. package/ai/tools/ziweiChartTool.ts +0 -678
  228. package/ai/types.ts +0 -55
  229. package/ai/workflow/workflowExecutor.ts +0 -323
  230. package/ai/workflow/workflowSlice.ts +0 -73
  231. package/ai/workflow/workflowTypes.ts +0 -106
  232. package/connector-experimental/index.ts +0 -5
@@ -1,330 +0,0 @@
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
- * PaddleOCR $0.14/$0.80 /1M → ×8
60
- * olmOCR $0.09/$0.19 /1M → ×8
61
- * DeepSeek $0.03/$0.10 /1M → ×8
62
- *
63
- * Exa 价格:$0.01/次(含 contents)× 8
64
- */
65
- export const EXTERNAL_TOOL_PRICING: Record<string, ToolPrice> = {
66
- // ── OCR (DeepInfra, token-based) ──────────────────────
67
- "PaddlePaddle/PaddleOCR-VL-0.9B": {
68
- type: "token",
69
- input: 0.14 * 8, // 1.12
70
- output: 0.80 * 8, // 6.4
71
- provider: "deepinfra",
72
- },
73
- "allenai/olmOCR-2-7B-1025": {
74
- type: "token",
75
- input: 0.09 * 8, // 0.72
76
- output: 0.19 * 8, // 1.52
77
- provider: "deepinfra",
78
- },
79
-
80
- // ── Web Search ────────────────────────────────────────
81
- "exa_search": {
82
- type: "perCall",
83
- cost: 0.01 * 8, // 0.08
84
- provider: "exa",
85
- },
86
-
87
- // ── ASR / Whisper (DeepInfra, per-minute) ─────────────
88
- "openai/whisper-large-v3-turbo": {
89
- type: "perMinute",
90
- cost: 0.00020 * 8, // 0.0016 credits/min
91
- provider: "deepinfra",
92
- },
93
- "openai/whisper-large-v3": {
94
- type: "perMinute",
95
- cost: 0.00045 * 8, // 0.0036 credits/min
96
- provider: "deepinfra",
97
- },
98
-
99
- // ── Apify Actors (per-run) ─────────────────────────────
100
- // Apify 按 compute unit 计费,轻量爬虫 ~0.05–0.5 CU,$0.50/CU
101
- // 保守取 $0.25/run 作为默认基准,建议高消耗 Actor 单独定价
102
- "apify_actor_run": {
103
- type: "perCall",
104
- cost: 0.25 * 8, // 2.0 credits/run
105
- provider: "apify",
106
- },
107
-
108
- // ── Gemini Image Generation (per-image) ───────────────
109
- // 2.5 Flash Image: ~$0.04/image(Flash 系列,文生图)
110
- // 3 Pro Image Preview: ~$0.15/image(Pro 系列,多图编辑)
111
- "gemini-2.5-flash-image": {
112
- type: "perCall",
113
- cost: 0.04 * 8, // 0.32 credits/image
114
- provider: "google",
115
- },
116
- // OpenAI image generation currently goes through the images API instead of
117
- // token accounting, so register a per-image fallback price here.
118
- "gpt-image-1.5": {
119
- type: "perCall",
120
- cost: 0.04 * 8, // 0.32 credits/image
121
- provider: "openai",
122
- },
123
- "gpt-image-2": {
124
- type: "perCall",
125
- cost: 0.04 * 8, // 0.32 credits/image placeholder
126
- provider: "openai",
127
- },
128
- "gemini-3-pro-image-preview": {
129
- type: "perCall",
130
- cost: 0.15 * 8, // 1.2 credits/image
131
- provider: "google",
132
- },
133
- "gemini-3.1-flash-image-preview": {
134
- type: "perCall",
135
- cost: 0.067 * 8, // fallback only; Gemini handler overrides by image size
136
- provider: "google",
137
- },
138
-
139
- // ── Cloudflare Browser Rendering (per-minute) ─────────
140
- // CF REST API 按浏览器实际占用时间计费,X-Browser-Ms-Used 响应头返回毫秒数
141
- // 公开价格约 $0.001/min,× 8 平台加成
142
- "cf_browser_rendering": {
143
- type: "perMinute",
144
- cost: 0.001 * 8, // $0.008/min
145
- provider: "cloudflare",
146
- },
147
-
148
- // ── Cloudflare Workers AI Whisper (per-minute) ────────
149
- // @cf/openai/whisper,价格与 DeepInfra whisper-large-v3 相近
150
- "@cf/openai/whisper": {
151
- type: "perMinute",
152
- cost: 0.00045 * 8, // $0.0036 credits/min
153
- provider: "cloudflare",
154
- },
155
- "@cf/myshell-ai/melotts": {
156
- type: "perMinute",
157
- cost: 0.00020 * 8, // $0.0016 credits/min
158
- provider: "cloudflare",
159
- },
160
- };
161
-
162
- // ─────────────────────────────────────────
163
- // 计费入口
164
- // ─────────────────────────────────────────
165
-
166
- export interface ChargeExternalToolOpts {
167
- userId: string;
168
- /** 工具 ID,对应 EXTERNAL_TOOL_PRICING 的 key */
169
- toolId: string;
170
- /** 若工具调用发生在某个对话内,则回写到该 dialog 的累计成本 */
171
- dialogId?: string;
172
- /** token 类工具:来自 API 响应的 prompt_tokens / completion_tokens */
173
- inputTokens?: number;
174
- outputTokens?: number;
175
- /** perMinute 类工具:音频实际时长(分钟) */
176
- durationMinutes?: number;
177
- /** perCall 类工具:调用次数(如按图片数量计费时传 imageCount),默认 1 */
178
- count?: number;
179
- /** 已由调用方基于模型配置算好的总费用(credits)。 */
180
- costOverride?: number;
181
- /** 扣费原因(用于事务日志) */
182
- reason?: string;
183
- }
184
-
185
- export interface ChargeResult {
186
- cost: number;
187
- skipped: boolean;
188
- reason?: string;
189
- }
190
-
191
- /**
192
- * 计算费用、扣余额、写 usage 记录,三步合一。
193
- * 若 toolId 未注册,跳过扣费并打 warn 日志。
194
- */
195
- export async function chargeExternalTool(
196
- opts: ChargeExternalToolOpts
197
- ): Promise<ChargeResult> {
198
- const {
199
- userId,
200
- toolId,
201
- dialogId,
202
- inputTokens = 0,
203
- outputTokens = 0,
204
- durationMinutes = 0,
205
- count = 1,
206
- costOverride,
207
- reason,
208
- } = opts;
209
-
210
- const pricing = EXTERNAL_TOOL_PRICING[toolId];
211
- if (!pricing) {
212
- logger.warn({ toolId }, "Unknown external tool, skipping charge");
213
- return { cost: 0, skipped: true, reason: "unknown_tool" };
214
- }
215
-
216
- // 计算 cost
217
- let cost: number;
218
- if (typeof costOverride === "number" && Number.isFinite(costOverride)) {
219
- cost = costOverride;
220
- } else if (pricing.type === "token") {
221
- cost =
222
- (inputTokens * pricing.input + outputTokens * pricing.output) / 1_000_000;
223
- } else if (pricing.type === "perMinute") {
224
- cost = durationMinutes * pricing.cost;
225
- } else {
226
- cost = pricing.cost * count;
227
- }
228
-
229
- cost = Number(cost.toFixed(6));
230
- if (cost <= 0) return { cost: 0, skipped: true, reason: "zero_cost" };
231
-
232
- // 扣余额
233
- const deductReason = reason ?? toolId;
234
- await deductUserBalance(userId, cost, deductReason);
235
-
236
- // 写 usage 记录(与 LLM token 记录同格式,显示在 Usage 页面)
237
- await writeUsageRecord({
238
- userId,
239
- toolId,
240
- dialogId,
241
- inputTokens,
242
- outputTokens,
243
- cost,
244
- provider: pricing.provider,
245
- });
246
-
247
- if (dialogId) {
248
- try {
249
- await applyServerDialogProjectionDelta({
250
- userId,
251
- dialogId,
252
- inputTokensDelta: inputTokens,
253
- outputTokensDelta: outputTokens,
254
- costDelta: cost,
255
- });
256
- } catch (error) {
257
- logger.warn(
258
- { err: error, userId, toolId, dialogId, cost },
259
- "External tool charge persisted but dialog projection update failed",
260
- );
261
- }
262
- }
263
-
264
- logger.info({ userId, toolId, inputTokens, outputTokens, cost }, "External tool charged");
265
- return { cost, skipped: false };
266
- }
267
-
268
- // ─────────────────────────────────────────
269
- // 内部:写 usage 记录到 LevelDB
270
- // ─────────────────────────────────────────
271
-
272
- async function writeUsageRecord(opts: {
273
- userId: string;
274
- toolId: string;
275
- dialogId?: string;
276
- inputTokens: number;
277
- outputTokens: number;
278
- cost: number;
279
- provider: string;
280
- }): Promise<void> {
281
- const { userId, toolId, dialogId, inputTokens, outputTokens, cost, provider } = opts;
282
- const timestamp = Date.now();
283
- const dateKey = format(timestamp, "yyyy-MM-dd");
284
- const recordKey = createTokenKey.record(userId, timestamp);
285
- const tokenId = ulid(timestamp);
286
-
287
- const record = {
288
- id: tokenId,
289
- type: DataType.TOKEN,
290
- userId,
291
- username: "",
292
- cybotId: "external_tool",
293
- model: toolId,
294
- provider,
295
- dialogId: dialogId ?? `tool-${tokenId}`,
296
- input_tokens: inputTokens,
297
- output_tokens: outputTokens,
298
- cache_creation_input_tokens: 0,
299
- cache_read_input_tokens: 0,
300
- cost,
301
- pay: null,
302
- createdAt: timestamp,
303
- timestamp,
304
- dateKey,
305
- };
306
-
307
- const statsKey = createTokenStatsKey(userId, dateKey);
308
- let stats: any = null;
309
- try { stats = await serverDb.get(statsKey); } catch { /* init below */ }
310
-
311
- const inc = (s: any = { count: 0, tokens: { input: 0, output: 0 }, cost: 0 }) => ({
312
- count: s.count + 1,
313
- tokens: { input: s.tokens.input + inputTokens, output: s.tokens.output + outputTokens },
314
- cost: s.cost + cost,
315
- });
316
-
317
- const base = stats ?? { userId, period: "day", timeKey: dateKey, total: { count: 0, tokens: { input: 0, output: 0 }, cost: 0 }, models: {}, providers: {} };
318
- const newStats = {
319
- ...base,
320
- id: statsKey,
321
- type: DataType.TOKEN,
322
- total: inc(base.total),
323
- models: { ...base.models, [toolId]: inc(base.models?.[toolId]) },
324
- providers: { ...base.providers, [provider]: inc(base.providers?.[provider]) },
325
- };
326
- await serverDb.batch([
327
- { type: "put", key: recordKey, value: record },
328
- { type: "put", key: statsKey, value: newStats },
329
- ]);
330
- }
@@ -1,65 +0,0 @@
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
-
@@ -1,42 +0,0 @@
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
- };
@@ -1,252 +0,0 @@
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
- }