nolo-cli 0.1.9 → 0.1.11

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 (240) hide show
  1. package/README.md +0 -32
  2. package/agentRuntimeCommands.ts +3 -3
  3. package/commandRegistry.ts +2 -2
  4. package/machineCommands.ts +31 -6
  5. package/package.json +6 -8
  6. package/ai/agent/_executeModel.ts +0 -118
  7. package/ai/agent/agentSlice.ts +0 -525
  8. package/ai/agent/appWorkingMemory.ts +0 -126
  9. package/ai/agent/avatarUtils.ts +0 -24
  10. package/ai/agent/buildEditingContext.ts +0 -373
  11. package/ai/agent/buildSystemPrompt.ts +0 -532
  12. package/ai/agent/cleanAgentMessages.ts +0 -140
  13. package/ai/agent/cliChatClient.ts +0 -119
  14. package/ai/agent/cliExecutor.ts +0 -733
  15. package/ai/agent/cliPrompt.ts +0 -10
  16. package/ai/agent/contextCompiler.ts +0 -107
  17. package/ai/agent/contextLayerContract.ts +0 -44
  18. package/ai/agent/createAgentSchema.ts +0 -234
  19. package/ai/agent/executeToolCall.ts +0 -58
  20. package/ai/agent/fetchAgentContexts.ts +0 -42
  21. package/ai/agent/generatePrompt.ts +0 -3
  22. package/ai/agent/getFullChatContextKeys.ts +0 -168
  23. package/ai/agent/hooks/fetchPublicAgents.ts +0 -133
  24. package/ai/agent/hooks/useAgentConfig.ts +0 -61
  25. package/ai/agent/hooks/useAgentDialog.ts +0 -35
  26. package/ai/agent/hooks/useAgentFormValidation.ts +0 -202
  27. package/ai/agent/hooks/usePublicAgents.ts +0 -473
  28. package/ai/agent/machineRunPermissions.ts +0 -95
  29. package/ai/agent/persistMessageWithFixedId.ts +0 -37
  30. package/ai/agent/planSlice.ts +0 -259
  31. package/ai/agent/referenceUtils.ts +0 -229
  32. package/ai/agent/runAgentBackground.ts +0 -238
  33. package/ai/agent/runAgentClientLoop.ts +0 -138
  34. package/ai/agent/runtimeGuidance.ts +0 -97
  35. package/ai/agent/runtimeServerBase.ts +0 -37
  36. package/ai/agent/server/fetchPublicAgents.ts +0 -128
  37. package/ai/agent/startParallelAgentStreams.ts +0 -424
  38. package/ai/agent/startupProtocol.ts +0 -53
  39. package/ai/agent/streamAgentChatTurn.ts +0 -1278
  40. package/ai/agent/streamAgentChatTurnUtils.ts +0 -738
  41. package/ai/agent/types.ts +0 -71
  42. package/ai/agent/utils/imageOutput.ts +0 -33
  43. package/ai/agent/utils/sortUtils.ts +0 -250
  44. package/ai/agent/web/referencePickerUtils.ts +0 -146
  45. package/ai/ai.locale.ts +0 -1075
  46. package/ai/chat/accumulateToolCallChunks.ts +0 -95
  47. package/ai/chat/fetchUtils.native.ts +0 -276
  48. package/ai/chat/fetchUtils.ts +0 -153
  49. package/ai/chat/parseApiError.ts +0 -64
  50. package/ai/chat/parseMultilineSSE.ts +0 -95
  51. package/ai/chat/sendOpenAICompletionsRequest.native.ts +0 -682
  52. package/ai/chat/sendOpenAICompletionsRequest.ts +0 -703
  53. package/ai/chat/sendOpenAIResponseRequest.ts +0 -491
  54. package/ai/chat/shouldUseServerProxy.ts +0 -18
  55. package/ai/chat/sseClient.native.ts +0 -91
  56. package/ai/chat/sseClient.ts +0 -67
  57. package/ai/chat/streamReader.native.ts +0 -31
  58. package/ai/chat/streamReader.ts +0 -62
  59. package/ai/chat/updateTotalUsage.ts +0 -72
  60. package/ai/context/buildReferenceContext.ts +0 -437
  61. package/ai/context/calculateContextUsage.ts +0 -133
  62. package/ai/context/retention.ts +0 -165
  63. package/ai/context/tokenUtils.ts +0 -78
  64. package/ai/index.ts +0 -1
  65. package/ai/llm/calculateGeminiImageTokens.ts +0 -57
  66. package/ai/llm/deepinfra.ts +0 -28
  67. package/ai/llm/fireworks.ts +0 -50
  68. package/ai/llm/generateRequestBody.ts +0 -165
  69. package/ai/llm/getModelContextWindow.ts +0 -84
  70. package/ai/llm/getNoloKey.ts +0 -31
  71. package/ai/llm/getPricing.ts +0 -199
  72. package/ai/llm/hooks/useModelPricing.ts +0 -75
  73. package/ai/llm/imagePricing.ts +0 -40
  74. package/ai/llm/isResponseAPIModel.ts +0 -13
  75. package/ai/llm/mimo.ts +0 -71
  76. package/ai/llm/mistral.ts +0 -22
  77. package/ai/llm/modelAvatar.ts +0 -427
  78. package/ai/llm/models.ts +0 -45
  79. package/ai/llm/openrouterModels.ts +0 -269
  80. package/ai/llm/providers.ts +0 -306
  81. package/ai/llm/reasoningModels.ts +0 -28
  82. package/ai/llm/types.ts +0 -59
  83. package/ai/llm/usageRequestOptions.ts +0 -59
  84. package/ai/memory/capture.ts +0 -148
  85. package/ai/memory/consolidate.ts +0 -104
  86. package/ai/memory/delete.ts +0 -147
  87. package/ai/memory/overlay.ts +0 -84
  88. package/ai/memory/query.ts +0 -38
  89. package/ai/memory/queryShared.ts +0 -160
  90. package/ai/memory/rank.ts +0 -105
  91. package/ai/memory/recentRelationshipRecap.ts +0 -249
  92. package/ai/memory/remember.ts +0 -167
  93. package/ai/memory/runtime.ts +0 -76
  94. package/ai/memory/store.ts +0 -20
  95. package/ai/memory/storeShared.ts +0 -76
  96. package/ai/memory/types.ts +0 -46
  97. package/ai/memory/understanding.ts +0 -349
  98. package/ai/memory/understandingGreeting.ts +0 -264
  99. package/ai/messages/type.ts +0 -20
  100. package/ai/policy/personalizationDialog.ts +0 -333
  101. package/ai/policy/runtimePolicy.ts +0 -440
  102. package/ai/policy/selfUpdateFields.ts +0 -48
  103. package/ai/policy/types.ts +0 -64
  104. package/ai/skills/referenceRuntime.ts +0 -274
  105. package/ai/skills/skillDiagnostics.ts +0 -251
  106. package/ai/skills/skillDocBuilder.ts +0 -139
  107. package/ai/skills/skillDocProtocol.ts +0 -434
  108. package/ai/skills/skillReferenceSummary.ts +0 -63
  109. package/ai/skills/skillSummaryMarker.ts +0 -26
  110. package/ai/token/calculatePrice.ts +0 -544
  111. package/ai/token/db.ts +0 -98
  112. package/ai/token/externalToolCost.ts +0 -330
  113. package/ai/token/hooks/useRecords.ts +0 -65
  114. package/ai/token/missingUsageEstimate.ts +0 -42
  115. package/ai/token/modelUsageQuery.ts +0 -252
  116. package/ai/token/normalizeUsage.ts +0 -84
  117. package/ai/token/openaiImageGenerationUsage.ts +0 -56
  118. package/ai/token/prepareTokenUsageData.ts +0 -88
  119. package/ai/token/query.ts +0 -88
  120. package/ai/token/queryUserTokens.ts +0 -59
  121. package/ai/token/resolveBillingTarget.ts +0 -52
  122. package/ai/token/saveTokenRecord.ts +0 -53
  123. package/ai/token/serverDialogProjection.ts +0 -78
  124. package/ai/token/serverTokenWriter.ts +0 -143
  125. package/ai/token/stats.ts +0 -21
  126. package/ai/token/tokenThunks.ts +0 -24
  127. package/ai/token/types.ts +0 -93
  128. package/ai/tools/agent/agentTools.ts +0 -176
  129. package/ai/tools/agent/agentUpdateShared.ts +0 -311
  130. package/ai/tools/agent/callAgentTool.ts +0 -139
  131. package/ai/tools/agent/createAgentTool.ts +0 -512
  132. package/ai/tools/agent/createDialogTool.ts +0 -69
  133. package/ai/tools/agent/createSkillAgentTool.ts +0 -62
  134. package/ai/tools/agent/parallelBudget.ts +0 -221
  135. package/ai/tools/agent/presets/appBuilderPreset.ts +0 -145
  136. package/ai/tools/agent/runLlmTool.ts +0 -96
  137. package/ai/tools/agent/runStreamingAgentTool.ts +0 -73
  138. package/ai/tools/agent/skillAgentArgs.ts +0 -106
  139. package/ai/tools/agent/skillAgentPreset.ts +0 -89
  140. package/ai/tools/agent/streamParallelAgentsTool.ts +0 -122
  141. package/ai/tools/agent/updateAgentTool.ts +0 -96
  142. package/ai/tools/agent/updateSelfTool.ts +0 -113
  143. package/ai/tools/amazonProductScraperTool.ts +0 -86
  144. package/ai/tools/apifyActorClient.ts +0 -45
  145. package/ai/tools/appEditGuard.ts +0 -372
  146. package/ai/tools/appReadSnapshot.ts +0 -153
  147. package/ai/tools/appTools.ts +0 -1549
  148. package/ai/tools/applyEditTool.ts +0 -256
  149. package/ai/tools/applyLineEditsTool.ts +0 -312
  150. package/ai/tools/browserTools/click.ts +0 -33
  151. package/ai/tools/browserTools/closeSession.ts +0 -29
  152. package/ai/tools/browserTools/common.ts +0 -27
  153. package/ai/tools/browserTools/openSession.ts +0 -48
  154. package/ai/tools/browserTools/readContent.ts +0 -38
  155. package/ai/tools/browserTools/selectOption.ts +0 -46
  156. package/ai/tools/browserTools/typeText.ts +0 -42
  157. package/ai/tools/category/createCategoryTool.ts +0 -66
  158. package/ai/tools/category/queryContentsByCategoryTool.ts +0 -69
  159. package/ai/tools/category/updateContentCategoryTool.ts +0 -75
  160. package/ai/tools/cfBrowserTools.ts +0 -319
  161. package/ai/tools/cfSpeechToTextTool.ts +0 -49
  162. package/ai/tools/checkEnvTool.ts +0 -65
  163. package/ai/tools/cloudflareCrawlTool.ts +0 -289
  164. package/ai/tools/codeSearchTool.ts +0 -111
  165. package/ai/tools/codeTools.ts +0 -101
  166. package/ai/tools/createDocTool.ts +0 -132
  167. package/ai/tools/createPlanTool.ts +0 -999
  168. package/ai/tools/createSkillDocTool.ts +0 -155
  169. package/ai/tools/createWorkflowTool.ts +0 -154
  170. package/ai/tools/deepseekOcrTool.ts +0 -34
  171. package/ai/tools/delayTool.ts +0 -31
  172. package/ai/tools/deleteSpacesTool.ts +0 -325
  173. package/ai/tools/deleteSpacesToolModel.ts +0 -159
  174. package/ai/tools/devReloadUtils.ts +0 -29
  175. package/ai/tools/dialogMessageSearch.ts +0 -137
  176. package/ai/tools/doctorSkillTool.ts +0 -72
  177. package/ai/tools/ecommerceScraperTool.ts +0 -86
  178. package/ai/tools/emailTools.ts +0 -549
  179. package/ai/tools/evalSkillTool.ts +0 -92
  180. package/ai/tools/exaSearchTool.ts +0 -64
  181. package/ai/tools/execBashTool.ts +0 -379
  182. package/ai/tools/executeSqlTool.ts +0 -192
  183. package/ai/tools/fetchWebpageSupport.ts +0 -309
  184. package/ai/tools/fetchWebpageTool.ts +0 -84
  185. package/ai/tools/geminiImagePreviewTool.ts +0 -361
  186. package/ai/tools/generateDocxTool.ts +0 -215
  187. package/ai/tools/googleSearchScraperTool.ts +0 -106
  188. package/ai/tools/importDataTool.ts +0 -133
  189. package/ai/tools/importSkillTool.ts +0 -162
  190. package/ai/tools/index.ts +0 -1858
  191. package/ai/tools/listFilesTool.ts +0 -82
  192. package/ai/tools/listUserSpacesTool.ts +0 -113
  193. package/ai/tools/modelUsageTools.ts +0 -142
  194. package/ai/tools/olmOcrTool.ts +0 -34
  195. package/ai/tools/openaiImageTool.ts +0 -218
  196. package/ai/tools/paddleOcrTool.ts +0 -34
  197. package/ai/tools/prepareTools.ts +0 -23
  198. package/ai/tools/readDocTool.ts +0 -84
  199. package/ai/tools/readFileTool.ts +0 -211
  200. package/ai/tools/readTool.ts +0 -163
  201. package/ai/tools/readXPostTool.ts +0 -233
  202. package/ai/tools/rememberMemoryTool.ts +0 -84
  203. package/ai/tools/remotionVideoTool.ts +0 -151
  204. package/ai/tools/searchDialogMessagesTool.ts +0 -222
  205. package/ai/tools/searchRepoTool.ts +0 -115
  206. package/ai/tools/searchWorkspaceTool.ts +0 -259
  207. package/ai/tools/skillFollowup.ts +0 -86
  208. package/ai/tools/surfWeatherTool.ts +0 -169
  209. package/ai/tools/table/addTableRowTool.ts +0 -217
  210. package/ai/tools/table/createTableTool.ts +0 -315
  211. package/ai/tools/table/rowTools.ts +0 -366
  212. package/ai/tools/table/schemaTools.ts +0 -244
  213. package/ai/tools/table/shareTableTool.ts +0 -148
  214. package/ai/tools/table/toolShared.ts +0 -129
  215. package/ai/tools/toolApiClient.ts +0 -198
  216. package/ai/tools/toolNameAliases.ts +0 -57
  217. package/ai/tools/toolResultError.ts +0 -42
  218. package/ai/tools/toolRunSlice.ts +0 -303
  219. package/ai/tools/toolSchemaCompatibility.ts +0 -53
  220. package/ai/tools/toolVisibility.ts +0 -4
  221. package/ai/tools/types.ts +0 -20
  222. package/ai/tools/uiAskChoiceTool.ts +0 -104
  223. package/ai/tools/updateContentTitleTool.ts +0 -84
  224. package/ai/tools/updateDocTool.ts +0 -105
  225. package/ai/tools/updateUserPreferenceProfileTool.ts +0 -145
  226. package/ai/tools/whisperTool.ts +0 -77
  227. package/ai/tools/writeFileTool.ts +0 -210
  228. package/ai/tools/youtubeScraperTool.ts +0 -116
  229. package/ai/tools/ziweiChartTool.ts +0 -678
  230. package/ai/types.ts +0 -55
  231. package/ai/workflow/workflowExecutor.ts +0 -323
  232. package/ai/workflow/workflowSlice.ts +0 -73
  233. package/ai/workflow/workflowTypes.ts +0 -106
  234. package/client/compactDialog.ts +0 -222
  235. package/connector-experimental/capabilities.ts +0 -73
  236. package/connector-experimental/codexBinary.ts +0 -41
  237. package/connector-experimental/heartbeatLoop.ts +0 -22
  238. package/connector-experimental/index.ts +0 -5
  239. package/connector-experimental/machineInfo.ts +0 -46
  240. package/connector-experimental/protocol.ts +0 -54
@@ -1,84 +0,0 @@
1
- // 文件路径: ai/token/normalizeUsage.ts
2
-
3
- import { RawUsage, NormalizedUsage } from "./types";
4
-
5
- /**
6
- * 规范化 usage 数据
7
- */
8
- export const normalizeUsage = (usage: RawUsage): NormalizedUsage => {
9
- const inputTokens =
10
- "input_tokens" in usage
11
- ? usage.input_tokens
12
- : "prompt_tokens" in usage
13
- ? usage.prompt_tokens
14
- : 0;
15
-
16
- const outputTokens =
17
- "output_tokens" in usage
18
- ? usage.output_tokens
19
- : "completion_tokens" in usage
20
- ? usage.completion_tokens
21
- : 0;
22
-
23
- const cacheCreationInputTokens =
24
- "cache_creation_input_tokens" in usage
25
- ? usage.cache_creation_input_tokens
26
- : "prompt_cache_miss_tokens" in usage
27
- ? usage.prompt_cache_miss_tokens
28
- : 0;
29
-
30
- const cacheReadInputTokens =
31
- "cache_read_input_tokens" in usage
32
- ? usage.cache_read_input_tokens
33
- : "prompt_cache_hit_tokens" in usage
34
- ? usage.prompt_cache_hit_tokens
35
- : 0;
36
-
37
- // ✅ 如果 provider 返回 usage.cost,则先原样透传;
38
- // 后续由 calculatePrice 按各 provider 的账单单位再做换算。
39
- let cost = 0;
40
- if ("cost" in usage && typeof (usage as any).cost === "number") {
41
- cost = (usage as any).cost;
42
- }
43
-
44
- const billingProvider =
45
- "billing_provider" in usage && typeof usage.billing_provider === "string"
46
- ? usage.billing_provider.trim() || undefined
47
- : undefined;
48
-
49
- const billingModel =
50
- "billing_model" in usage && typeof usage.billing_model === "string"
51
- ? usage.billing_model.trim() || undefined
52
- : undefined;
53
-
54
- const billingServiceTier =
55
- "billing_service_tier" in usage &&
56
- typeof usage.billing_service_tier === "string"
57
- ? usage.billing_service_tier.trim() || undefined
58
- : undefined;
59
- const billingEstimated =
60
- "billing_estimated" in usage && usage.billing_estimated === true;
61
- const imageGenerationCount =
62
- "image_generation_count" in usage &&
63
- typeof usage.image_generation_count === "number" &&
64
- Number.isFinite(usage.image_generation_count)
65
- ? usage.image_generation_count
66
- : undefined;
67
-
68
- return {
69
- input_tokens: inputTokens,
70
- output_tokens: outputTokens,
71
- cache_creation_input_tokens: cacheCreationInputTokens,
72
- cache_read_input_tokens: cacheReadInputTokens,
73
- cost,
74
- ...(billingProvider ? { billing_provider: billingProvider } : {}),
75
- ...(billingModel ? { billing_model: billingModel } : {}),
76
- ...(billingServiceTier
77
- ? { billing_service_tier: billingServiceTier }
78
- : {}),
79
- ...(billingEstimated ? { billing_estimated: true } : {}),
80
- ...(typeof imageGenerationCount === "number"
81
- ? { image_generation_count: imageGenerationCount }
82
- : {}),
83
- };
84
- };
@@ -1,56 +0,0 @@
1
- import { getModelInfo } from "ai/llm/getModelContextWindow";
2
- import { countImageParts } from "chat/messages/messageContract";
3
-
4
- type AgentLike = {
5
- provider?: string | null;
6
- model?: string | null;
7
- imageConfig?: { enabled?: boolean } | null;
8
- };
9
-
10
- type UsageLike = Record<string, any> | null | undefined;
11
-
12
- type TraceMessageLike = {
13
- role?: string;
14
- content?: string | any[] | null;
15
- };
16
-
17
- export const isOpenAIBuiltInImageGenerationAgent = (
18
- agentConfig: AgentLike | null | undefined
19
- ): boolean =>
20
- String(agentConfig?.provider || "").toLowerCase() === "openai" &&
21
- !getModelInfo(String(agentConfig?.model || ""))?.hasImageOutput &&
22
- !!agentConfig?.imageConfig?.enabled;
23
-
24
- export const withImageGenerationCount = <T extends UsageLike>(
25
- usage: T,
26
- imageGenerationCount: number
27
- ): T => {
28
- if (!usage || !Number.isFinite(imageGenerationCount) || imageGenerationCount <= 0) {
29
- return usage;
30
- }
31
-
32
- const existingCount =
33
- typeof usage.image_generation_count === "number" &&
34
- Number.isFinite(usage.image_generation_count)
35
- ? usage.image_generation_count
36
- : 0;
37
-
38
- return {
39
- ...usage,
40
- image_generation_count: Math.max(existingCount, imageGenerationCount),
41
- };
42
- };
43
-
44
- export const countAssistantImageGenerationOutputs = (
45
- trace: TraceMessageLike[] | null | undefined
46
- ): number => {
47
- if (!Array.isArray(trace)) return 0;
48
- return trace.reduce((total, message) => {
49
- if (message?.role !== "assistant") return total;
50
- return total + countImageParts(message.content ?? null);
51
- }, 0);
52
- };
53
-
54
- export const countImageGenerationOutputsInContent = (
55
- content: string | any[] | null | undefined
56
- ): number => countImageParts(content);
@@ -1,88 +0,0 @@
1
- import { extractUserId } from "core/prefix";
2
- import { calculatePrice } from "./calculatePrice";
3
- import { normalizeUsage } from "./normalizeUsage";
4
- import { resolveBillingTarget } from "./resolveBillingTarget";
5
- import type { RawUsage, TokenUsageData } from "./types";
6
-
7
- interface BillingAgentConfig {
8
- model: string;
9
- provider?: string;
10
- apiSource?: string;
11
- inputPrice?: number;
12
- outputPrice?: number;
13
- id?: string;
14
- }
15
-
16
- interface PrepareTokenUsageDataParams {
17
- rawUsage: RawUsage;
18
- agentConfig: BillingAgentConfig;
19
- userId?: string;
20
- username?: string;
21
- cybotId: string;
22
- dialogId: string;
23
- timestamp?: number;
24
- }
25
-
26
- export interface PreparedTokenUsageData {
27
- usage: ReturnType<typeof normalizeUsage>;
28
- billedProvider?: string;
29
- billedModel: string;
30
- billedServiceTier?: string;
31
- recordProvider: string;
32
- tokenData: TokenUsageData;
33
- }
34
-
35
- export const prepareTokenUsageData = ({
36
- rawUsage,
37
- agentConfig,
38
- userId,
39
- username,
40
- cybotId,
41
- dialogId,
42
- timestamp = Date.now(),
43
- }: PrepareTokenUsageDataParams): PreparedTokenUsageData => {
44
- const usage = normalizeUsage(rawUsage);
45
- const billingTarget = resolveBillingTarget({
46
- usage,
47
- fallbackProvider: agentConfig.provider,
48
- fallbackModel: agentConfig.model,
49
- });
50
- const billedProvider = billingTarget.provider;
51
- const billedModel = billingTarget.model;
52
- const billedServiceTier = billingTarget.serviceTier;
53
- const recordProvider = billedProvider ?? agentConfig.provider ?? "unknown";
54
- const { cost, pay } = calculatePrice({
55
- provider: billedProvider,
56
- modelName: billedModel,
57
- billingServiceTier: billedServiceTier,
58
- usage,
59
- externalPrice: agentConfig.id
60
- ? {
61
- input: agentConfig.inputPrice ?? 0,
62
- output: agentConfig.outputPrice ?? 0,
63
- creatorId: extractUserId(agentConfig.id),
64
- }
65
- : undefined,
66
- });
67
-
68
- return {
69
- usage,
70
- billedProvider,
71
- billedModel,
72
- billedServiceTier,
73
- recordProvider,
74
- tokenData: {
75
- ...usage,
76
- userId,
77
- username,
78
- cybotId,
79
- model: billedModel,
80
- provider: recordProvider,
81
- billing_service_tier: billedServiceTier,
82
- dialogId,
83
- cost,
84
- pay,
85
- timestamp,
86
- },
87
- };
88
- };
package/ai/token/query.ts DELETED
@@ -1,88 +0,0 @@
1
- import { createTokenStatsKey } from "database/keys";
2
-
3
-
4
-
5
-
6
-
7
- export interface QueryParams {
8
- userId: string;
9
- startTime?: number; // UTC timestamp
10
- endTime?: number; // UTC timestamp
11
- model?: string;
12
- limit?: number;
13
- offset?: number;
14
- }
15
-
16
- export interface TokenStats {
17
- total: number;
18
- date: string; // UTC YYYY-MM-DD
19
- inputTokens: number;
20
- outputTokens: number;
21
- cost: number;
22
- }
23
-
24
- export interface StatsParams {
25
- userId: string;
26
- period: "day";
27
- startDate: string; // UTC YYYY-MM-DD
28
- endDate: string; // UTC YYYY-MM-DD
29
- }
30
-
31
- // 通用数据库迭代器
32
- const iterateDb = async <T>(
33
- db: any,
34
- options: any,
35
- filter: (v: T) => boolean
36
- ): Promise<T[]> => {
37
- const records: T[] = [];
38
- const { offset = 0, limit } = options;
39
- let count = 0;
40
-
41
- try {
42
- for await (const [_, value] of db.iterator(options)) {
43
- if (filter(value)) {
44
- if (count >= offset) {
45
- records.push(value);
46
- if (limit && records.length >= limit) {
47
- break;
48
- }
49
- }
50
- count++;
51
- }
52
- }
53
- return records;
54
- } catch (err) {
55
- throw err;
56
- }
57
- };
58
-
59
- /**
60
- * 获取Token统计数据
61
- * @param db - 数据库实例
62
- * @param params.userId - 用户ID
63
- * @param params.startDate - 开始日期 YYYY-MM-DD (UTC)
64
- * @param params.endDate - 结束日期 YYYY-MM-DD (UTC)
65
- * @param params.period - 统计周期,目前支持 "day"
66
- */
67
- export const getTokenStats = async (
68
- db: any,
69
- params: StatsParams
70
- ): Promise<TokenStats[]> => {
71
- const { userId, startDate, endDate } = params;
72
-
73
- // 统计数据按UTC日期(00:00:00)存储
74
- const startKey = createTokenStatsKey(userId, startDate);
75
- const endKey = createTokenStatsKey(userId, endDate);
76
-
77
- const records = await iterateDb<TokenStats>(
78
- db,
79
- {
80
- gte: startKey,
81
- lte: endKey,
82
- },
83
- (record) => Boolean(record?.total)
84
- );
85
-
86
- return records;
87
- };
88
-
@@ -1,59 +0,0 @@
1
- import { TokenRecord } from "./types";
2
- import { createTokenKey } from "database/keys";
3
-
4
-
5
-
6
- export interface QueryParams {
7
- userId: string;
8
- startTime?: number; // 不传则查询当天
9
- model?: string;
10
- pageSize?: number;
11
- offset?: number;
12
- }
13
-
14
- export interface QueryResult {
15
- records: TokenRecord[];
16
- total: number;
17
- }
18
-
19
- /**
20
- * 查询用户token使用记录
21
- * @param db 数据库实例
22
- * @param params 查询参数,包含用户ID、起始时间(默认当天)、模型、分页参数
23
- * @returns 包含记录列表和总数的结果
24
- */
25
- export const queryUserTokens = async (
26
- db: any,
27
- params: QueryParams
28
- ): Promise<QueryResult> => {
29
- const { userId, startTime, model, pageSize = 100, offset = 0 } = params;
30
- const { start, end } = createTokenKey.range(userId, startTime || Date.now());
31
- const records: TokenRecord[] = [];
32
-
33
- try {
34
- // 单次扫描:同时计总数与收集分页数据
35
- let count = 0;
36
- for await (const [_, value] of db.iterator({
37
- gte: start,
38
- lte: end,
39
- reverse: true,
40
- })) {
41
- if (!model || value.model === model) {
42
- if (count >= offset && records.length < pageSize) {
43
- records.push({
44
- ...value,
45
- createdAt:
46
- typeof value.createdAt === "number"
47
- ? value.createdAt
48
- : value.timestamp,
49
- });
50
- }
51
- count++;
52
- }
53
- }
54
-
55
- return { records, total: count };
56
- } catch (err) {
57
- throw err;
58
- }
59
- };
@@ -1,52 +0,0 @@
1
- import { resolveOpenAIServiceTier } from "integrations/openai/flexTier";
2
- import type { NormalizedUsage, RawUsage } from "./types";
3
-
4
- type BillingUsage = Pick<
5
- RawUsage | NormalizedUsage,
6
- "billing_provider" | "billing_model" | "billing_service_tier"
7
- >;
8
-
9
- const normalizeString = (value?: string) => {
10
- const trimmed = typeof value === "string" ? value.trim() : "";
11
- return trimmed || undefined;
12
- };
13
-
14
- const resolveBillingModel = (
15
- usageModel?: string,
16
- fallbackModel?: string
17
- ) => {
18
- const model = normalizeString(usageModel) ?? normalizeString(fallbackModel);
19
- if (!model) {
20
- throw new Error("Billing model is required");
21
- }
22
- return model;
23
- };
24
-
25
- export const resolveBillingTarget = ({
26
- usage,
27
- fallbackProvider,
28
- fallbackModel,
29
- }: {
30
- usage?: BillingUsage | null;
31
- fallbackProvider?: string;
32
- fallbackModel: string;
33
- }) => {
34
- const provider =
35
- normalizeString(usage?.billing_provider) ?? normalizeString(fallbackProvider);
36
- const model = resolveBillingModel(usage?.billing_model, fallbackModel);
37
- const requestedServiceTier = normalizeString(usage?.billing_service_tier);
38
- const serviceTier =
39
- provider === "google"
40
- ? requestedServiceTier
41
- : resolveOpenAIServiceTier({
42
- providerName: provider,
43
- model,
44
- requestedServiceTier,
45
- });
46
-
47
- return {
48
- provider,
49
- model,
50
- serviceTier,
51
- };
52
- };
@@ -1,53 +0,0 @@
1
- import { TokenUsageData, TokenRecord } from "ai/token/types";
2
- import { DataType } from "create/types";
3
- import { createTokenKey } from "database/keys";
4
- import { write } from "database/dbSlice";
5
- import { toast } from "app/utils/toast";
6
- import { pino } from "pino";
7
-
8
- const logger = pino({ name: "token-record", level: "info" });
9
-
10
- type TokenCount = { input: number; output: number };
11
-
12
- export interface ModelStats {
13
- count: number;
14
- tokens: TokenCount;
15
- cost: number;
16
- }
17
-
18
- export const createTokenRecord = (
19
- data: TokenUsageData,
20
- { cost, inputPrice, outputPrice }: Partial<TokenRecord> = {}
21
- ): TokenRecord => ({
22
- ...data,
23
- cost: cost || data.cost,
24
- inputPrice,
25
- outputPrice,
26
- });
27
-
28
- export const saveTokenRecord = async (
29
- tokenData: TokenUsageData,
30
- record: TokenRecord,
31
- thunkApi
32
- ) => {
33
- const key = createTokenKey.record(tokenData.userId, tokenData.timestamp);
34
- try {
35
- await thunkApi.dispatch(
36
- write({
37
- data: { ...record, id: key, type: DataType.TOKEN },
38
- customKey: key,
39
- })
40
- );
41
- } catch (error) {
42
- logger.error(
43
- {
44
- key,
45
- userId: tokenData.userId,
46
- error: error.message,
47
- },
48
- "Failed to save token record"
49
- );
50
- toast.error("Failed to save token record");
51
- throw error;
52
- }
53
- };
@@ -1,78 +0,0 @@
1
- import pino from "pino";
2
-
3
- import serverDb from "database/server/db";
4
- import { createKey } from "database/keys";
5
- import { DataType } from "create/types";
6
- import { isLevelNotFoundError } from "share/helpers";
7
-
8
- const logger = pino({ name: "server-dialog-projection" });
9
- const dialogProjectionQueue = new Map<string, Promise<void>>();
10
-
11
- interface ApplyServerDialogProjectionDeltaOpts {
12
- userId: string;
13
- dialogId: string;
14
- inputTokensDelta?: number;
15
- outputTokensDelta?: number;
16
- costDelta?: number;
17
- }
18
-
19
- export async function applyServerDialogProjectionDelta(
20
- opts: ApplyServerDialogProjectionDeltaOpts,
21
- ): Promise<void> {
22
- const {
23
- userId,
24
- dialogId,
25
- inputTokensDelta = 0,
26
- outputTokensDelta = 0,
27
- costDelta = 0,
28
- } = opts;
29
-
30
- if (!dialogId) return;
31
- if (inputTokensDelta === 0 && outputTokensDelta === 0 && costDelta === 0) return;
32
-
33
- const dialogKey = createKey(DataType.DIALOG, userId, dialogId);
34
- const previousTask = dialogProjectionQueue.get(dialogKey) ?? Promise.resolve();
35
- const nextTask = previousTask.catch(() => undefined).then(async () => {
36
- let existingDialog: any;
37
- try {
38
- existingDialog = await serverDb.get(dialogKey);
39
- } catch (error) {
40
- if (isLevelNotFoundError(error)) {
41
- logger.warn(
42
- {
43
- userId,
44
- dialogId,
45
- dialogKey,
46
- inputTokensDelta,
47
- outputTokensDelta,
48
- costDelta,
49
- },
50
- "Skipping dialog projection update because dialog record is missing",
51
- );
52
- return;
53
- }
54
- throw error;
55
- }
56
-
57
- await serverDb.put(dialogKey, {
58
- ...existingDialog,
59
- inputTokens: (existingDialog.inputTokens ?? 0) + inputTokensDelta,
60
- outputTokens: (existingDialog.outputTokens ?? 0) + outputTokensDelta,
61
- totalCost: Number(((existingDialog.totalCost ?? 0) + costDelta).toFixed(6)),
62
- });
63
- });
64
- const queueEntry = nextTask.then(
65
- () => undefined,
66
- () => undefined,
67
- );
68
-
69
- dialogProjectionQueue.set(dialogKey, queueEntry);
70
-
71
- try {
72
- await nextTask;
73
- } finally {
74
- if (dialogProjectionQueue.get(dialogKey) === queueEntry) {
75
- dialogProjectionQueue.delete(dialogKey);
76
- }
77
- }
78
- }
@@ -1,143 +0,0 @@
1
- // ai/token/serverTokenWriter.ts
2
- // 服务端直接写 LevelDB 的 token 记录(对应客户端 saveTokenRecord + saveTokenUsage)
3
- // 用于 agentRun 等纯服务端调用场景,无 Redux 依赖
4
-
5
- import { ulid } from "ulid";
6
- import { format } from "date-fns";
7
- import serverDb from "database/server/db";
8
- import { createKey, createTokenKey, createTokenStatsKey } from "database/keys";
9
- import { DataType } from "create/types";
10
- import type { RawUsage } from "./types";
11
- import pino from "pino";
12
- import { prepareTokenUsageData } from "./prepareTokenUsageData";
13
- import { applyServerDialogProjectionDelta } from "./serverDialogProjection";
14
-
15
- const logger = pino({ name: "server-token-writer" });
16
-
17
- interface WriteTokenOpts {
18
- userId: string;
19
- username?: string;
20
- agentKey: string; // 对应 cybotId
21
- agentConfig: {
22
- model: string;
23
- // apiSource="custom" 的 agent 没有 provider 字段,允许 undefined
24
- provider?: string;
25
- apiSource?: string;
26
- inputPrice?: number;
27
- outputPrice?: number;
28
- id?: string;
29
- };
30
- runId: string; // 对应 dialogId
31
- rawUsage: RawUsage;
32
- }
33
-
34
- export async function writeServerTokenRecord(opts: WriteTokenOpts): Promise<{ cost: number }> {
35
- const { userId, username = "", agentKey, agentConfig, runId, rawUsage } = opts;
36
-
37
- const prepared = prepareTokenUsageData({
38
- rawUsage,
39
- agentConfig,
40
- userId,
41
- username,
42
- cybotId: agentKey,
43
- dialogId: runId,
44
- });
45
- const {
46
- usage,
47
- billedModel,
48
- billedServiceTier,
49
- recordProvider,
50
- tokenData,
51
- } = prepared;
52
- const { cost, pay } = tokenData;
53
-
54
- const timestamp = Date.now();
55
- const dateKey = format(timestamp, "yyyy-MM-dd");
56
- const tokenId = ulid(timestamp);
57
-
58
- // 1. 写单条 token 明细记录(key: token-{userId}-{timestamp})
59
- const recordKey = createTokenKey.record(userId, timestamp);
60
- const tokenRecord = {
61
- id: tokenId,
62
- type: DataType.TOKEN,
63
- userId,
64
- username,
65
- cybotId: agentKey,
66
- model: billedModel,
67
- provider: recordProvider,
68
- billing_service_tier: billedServiceTier,
69
- // 记录 apiSource 便于后续分析 custom/platform 的收益分布
70
- apiSource: agentConfig.apiSource,
71
- dialogId: runId, // runId 作为 dialogId,便于与 RunRecord 关联
72
- input_tokens: usage.input_tokens,
73
- output_tokens: usage.output_tokens,
74
- cache_creation_input_tokens: usage.cache_creation_input_tokens,
75
- cache_read_input_tokens: usage.cache_read_input_tokens,
76
- cost,
77
- pay,
78
- createdAt: timestamp,
79
- timestamp,
80
- dateKey,
81
- };
82
-
83
- // 2. 读/更新每日统计(key: token-stats-day-user-{userId}-{date})
84
- const statsKey = createTokenStatsKey(userId, dateKey);
85
- let stats: any;
86
- try {
87
- stats = await serverDb.get(statsKey);
88
- } catch {
89
- stats = null;
90
- }
91
-
92
- const modelName = billedModel || "unknown";
93
- const providerName = recordProvider;
94
- const inc = (s: any = { count: 0, tokens: { input: 0, output: 0 }, cost: 0 }) => ({
95
- count: s.count + 1,
96
- tokens: {
97
- input: s.tokens.input + usage.input_tokens,
98
- output: s.tokens.output + usage.output_tokens,
99
- },
100
- cost: s.cost + cost,
101
- });
102
-
103
- const updatedStats = stats ?? {
104
- userId,
105
- period: "day",
106
- timeKey: dateKey,
107
- total: { count: 0, tokens: { input: 0, output: 0 }, cost: 0 },
108
- models: {},
109
- providers: {},
110
- };
111
-
112
- const newStats = {
113
- ...updatedStats,
114
- id: statsKey,
115
- type: DataType.TOKEN,
116
- total: inc(updatedStats.total),
117
- models: { ...updatedStats.models, [modelName]: inc(updatedStats.models?.[modelName]) },
118
- providers: { ...updatedStats.providers, [providerName]: inc(updatedStats.providers?.[providerName]) },
119
- };
120
-
121
- await serverDb.batch([
122
- { type: "put", key: recordKey, value: tokenRecord },
123
- { type: "put", key: statsKey, value: newStats },
124
- ]);
125
-
126
- try {
127
- await applyServerDialogProjectionDelta({
128
- userId,
129
- dialogId: runId,
130
- inputTokensDelta: usage.input_tokens,
131
- outputTokensDelta: usage.output_tokens,
132
- costDelta: cost,
133
- });
134
- } catch (error) {
135
- logger.warn(
136
- { err: error, userId, runId, cost },
137
- "Server token record persisted but dialog projection update failed",
138
- );
139
- }
140
-
141
- logger.info({ userId, agentKey, cost, model: billedModel, provider: recordProvider }, "Token record written");
142
- return { cost };
143
- }