nolo-cli 0.1.13 → 0.1.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -2
- package/agent-runtime/hostAdapter.ts +53 -0
- package/agent-runtime/index.ts +28 -0
- package/agent-runtime/localLoop.ts +62 -0
- package/agent-runtime/runtimeDecision.ts +70 -0
- package/agent-runtime/types.ts +87 -0
- package/agentRuntimeCommands.ts +139 -22
- package/agentRuntimeLocal.ts +7 -0
- package/ai/agent/_executeModel.ts +118 -0
- package/ai/agent/agentSlice.ts +544 -1
- package/ai/agent/appWorkingMemory.ts +126 -0
- package/ai/agent/avatarUtils.ts +24 -0
- package/ai/agent/buildEditingContext.ts +373 -0
- package/ai/agent/buildSystemPrompt.ts +532 -0
- package/ai/agent/cleanAgentMessages.ts +140 -0
- package/ai/agent/cliChatClient.ts +119 -0
- package/ai/agent/contextCompiler.ts +107 -0
- package/ai/agent/contextLayerContract.ts +44 -0
- package/ai/agent/createAgentSchema.ts +234 -0
- package/ai/agent/executeToolCall.ts +58 -0
- package/ai/agent/fetchAgentContexts.ts +42 -0
- package/ai/agent/generatePrompt.ts +3 -0
- package/ai/agent/getFullChatContextKeys.ts +168 -0
- package/ai/agent/hooks/fetchPublicAgents.ts +133 -0
- package/ai/agent/hooks/useAgentConfig.ts +61 -0
- package/ai/agent/hooks/useAgentDialog.ts +35 -0
- package/ai/agent/hooks/useAgentFormValidation.ts +202 -0
- package/ai/agent/hooks/usePublicAgents.ts +473 -0
- package/ai/agent/persistMessageWithFixedId.ts +37 -0
- package/ai/agent/planSlice.ts +259 -0
- package/ai/agent/referenceUtils.ts +229 -0
- package/ai/agent/runAgentBackground.ts +238 -0
- package/ai/agent/runAgentClientLoop.ts +138 -0
- package/ai/agent/runtimeGuidance.ts +97 -0
- package/ai/agent/runtimeServerBase.ts +37 -0
- package/ai/agent/server/fetchPublicAgents.ts +128 -0
- package/ai/agent/startParallelAgentStreams.ts +424 -0
- package/ai/agent/startupProtocol.ts +53 -0
- package/ai/agent/streamAgentChatTurn.ts +1299 -0
- package/ai/agent/streamAgentChatTurnUtils.ts +738 -0
- package/ai/agent/types.ts +71 -0
- package/ai/agent/utils/imageOutput.ts +39 -0
- package/ai/agent/utils/publicImageAgentMode.ts +26 -0
- package/ai/agent/utils/sortUtils.ts +250 -0
- package/ai/agent/web/referencePickerUtils.ts +146 -0
- package/ai/ai.locale.ts +1083 -0
- package/ai/chat/accumulateToolCallChunks.ts +95 -0
- package/ai/chat/fetchUtils.native.ts +276 -0
- package/ai/chat/fetchUtils.ts +153 -0
- package/ai/chat/inlineImageUrlsForCustomProvider.ts +117 -0
- package/ai/chat/parseApiError.ts +64 -0
- package/ai/chat/parseMultilineSSE.ts +95 -0
- package/ai/chat/sendOpenAICompletionsRequest.native.ts +682 -0
- package/ai/chat/sendOpenAICompletionsRequest.ts +712 -0
- package/ai/chat/sendOpenAIResponseRequest.ts +512 -0
- package/ai/chat/shouldUseServerProxy.ts +18 -0
- package/ai/chat/sseClient.native.ts +91 -0
- package/ai/chat/sseClient.ts +67 -0
- package/ai/chat/streamReader.native.ts +31 -0
- package/ai/chat/streamReader.ts +62 -0
- package/ai/chat/updateTotalUsage.ts +72 -0
- package/ai/context/buildReferenceContext.ts +437 -0
- package/ai/context/calculateContextUsage.ts +133 -0
- package/ai/context/retention.ts +165 -0
- package/ai/context/tokenUtils.ts +78 -0
- package/ai/index.ts +1 -1
- package/ai/llm/agentCapabilities.ts +74 -0
- package/ai/llm/calculateGeminiImageTokens.ts +57 -0
- package/ai/llm/deepinfra.ts +28 -0
- package/ai/llm/fireworks.ts +68 -0
- package/ai/llm/generateRequestBody.ts +165 -0
- package/ai/llm/getModelContextWindow.ts +84 -0
- package/ai/llm/getNoloKey.ts +37 -0
- package/ai/llm/getPricing.ts +232 -0
- package/ai/llm/hooks/useModelPricing.ts +75 -0
- package/ai/llm/imagePricing.ts +66 -0
- package/ai/llm/isResponseAPIModel.ts +13 -0
- package/ai/llm/kimi.ts +18 -0
- package/ai/llm/mimo.ts +71 -0
- package/ai/llm/mistral.ts +22 -0
- package/ai/llm/modelAvatar.ts +427 -0
- package/ai/llm/models.ts +45 -0
- package/ai/llm/openrouterModels.ts +141 -0
- package/ai/llm/providers.ts +307 -0
- package/ai/llm/reasoningModels.ts +28 -0
- package/ai/llm/types.ts +59 -0
- package/ai/llm/usageRequestOptions.ts +59 -0
- package/ai/memory/capture.ts +148 -0
- package/ai/memory/consolidate.ts +104 -0
- package/ai/memory/delete.ts +147 -0
- package/ai/memory/overlay.ts +84 -0
- package/ai/memory/query.ts +38 -0
- package/ai/memory/queryShared.ts +160 -0
- package/ai/memory/rank.ts +105 -0
- package/ai/memory/recentRelationshipRecap.ts +247 -0
- package/ai/memory/remember.ts +167 -0
- package/ai/memory/runtime.ts +76 -0
- package/ai/memory/store.ts +20 -0
- package/ai/memory/storeShared.ts +76 -0
- package/ai/memory/types.ts +46 -0
- package/ai/memory/understanding.ts +349 -0
- package/ai/memory/understandingGreeting.ts +264 -0
- package/ai/messages/type.ts +20 -0
- package/ai/policy/personalizationDialog.ts +333 -0
- package/ai/policy/runtimePolicy.ts +440 -0
- package/ai/policy/selfUpdateFields.ts +48 -0
- package/ai/policy/types.ts +64 -0
- package/ai/skills/referenceRuntime.ts +274 -0
- package/ai/skills/skillDiagnostics.ts +251 -0
- package/ai/skills/skillDocBuilder.ts +139 -0
- package/ai/skills/skillDocProtocol.ts +434 -0
- package/ai/skills/skillReferenceSummary.ts +63 -0
- package/ai/skills/skillSummaryMarker.ts +26 -0
- package/ai/token/calculatePrice.ts +546 -0
- package/ai/token/db.ts +98 -0
- package/ai/token/externalToolCost.ts +321 -0
- package/ai/token/hooks/useRecords.ts +65 -0
- package/ai/token/missingUsageEstimate.ts +42 -0
- package/ai/token/modelUsageQuery.ts +252 -0
- package/ai/token/normalizeUsage.ts +84 -0
- package/ai/token/openaiImageGenerationUsage.ts +56 -0
- package/ai/token/prepareTokenUsageData.ts +88 -0
- package/ai/token/query.ts +88 -0
- package/ai/token/queryUserTokens.ts +59 -0
- package/ai/token/resolveBillingTarget.ts +52 -0
- package/ai/token/saveTokenRecord.ts +53 -0
- package/ai/token/serverDialogProjection.ts +78 -0
- package/ai/token/serverTokenWriter.ts +143 -0
- package/ai/token/stats.ts +21 -0
- package/ai/token/tokenThunks.ts +24 -0
- package/ai/token/types.ts +93 -0
- package/ai/tools/agent/agentTools.ts +176 -0
- package/ai/tools/agent/agentUpdateShared.ts +311 -0
- package/ai/tools/agent/callAgentTool.ts +139 -0
- package/ai/tools/agent/createAgentTool.ts +512 -0
- package/ai/tools/agent/createDialogTool.ts +69 -0
- package/ai/tools/agent/createSkillAgentTool.ts +62 -0
- package/ai/tools/agent/parallelBudget.ts +221 -0
- package/ai/tools/agent/presets/appBuilderPreset.ts +147 -0
- package/ai/tools/agent/runLlmTool.ts +96 -0
- package/ai/tools/agent/runStreamingAgentTool.ts +73 -0
- package/ai/tools/agent/skillAgentArgs.ts +106 -0
- package/ai/tools/agent/skillAgentPreset.ts +89 -0
- package/ai/tools/agent/streamParallelAgentsTool.ts +122 -0
- package/ai/tools/agent/updateAgentTool.ts +96 -0
- package/ai/tools/agent/updateSelfTool.ts +113 -0
- package/ai/tools/amazonProductScraperTool.ts +86 -0
- package/ai/tools/apifyActorClient.ts +45 -0
- package/ai/tools/appEditGuard.ts +372 -0
- package/ai/tools/appReadSnapshot.ts +153 -0
- package/ai/tools/appTools.ts +1549 -0
- package/ai/tools/applyEditTool.ts +256 -0
- package/ai/tools/applyLineEditsTool.ts +312 -0
- package/ai/tools/browserTools/click.ts +33 -0
- package/ai/tools/browserTools/closeSession.ts +29 -0
- package/ai/tools/browserTools/common.ts +27 -0
- package/ai/tools/browserTools/openSession.ts +48 -0
- package/ai/tools/browserTools/readContent.ts +38 -0
- package/ai/tools/browserTools/selectOption.ts +46 -0
- package/ai/tools/browserTools/typeText.ts +42 -0
- package/ai/tools/category/createCategoryTool.ts +66 -0
- package/ai/tools/category/queryContentsByCategoryTool.ts +69 -0
- package/ai/tools/category/updateContentCategoryTool.ts +75 -0
- package/ai/tools/cfBrowserTools.ts +319 -0
- package/ai/tools/cfSpeechToTextTool.ts +49 -0
- package/ai/tools/checkEnvTool.ts +65 -0
- package/ai/tools/cloudflareCrawlTool.ts +289 -0
- package/ai/tools/codeSearchTool.ts +111 -0
- package/ai/tools/codeTools.ts +101 -0
- package/ai/tools/createDocTool.ts +132 -0
- package/ai/tools/createPlanTool.ts +999 -0
- package/ai/tools/createSkillDocTool.ts +155 -0
- package/ai/tools/createWorkflowTool.ts +154 -0
- package/ai/tools/deepseekOcrTool.ts +34 -0
- package/ai/tools/delayTool.ts +31 -0
- package/ai/tools/deleteSpacesTool.ts +325 -0
- package/ai/tools/deleteSpacesToolModel.ts +159 -0
- package/ai/tools/devReloadUtils.ts +29 -0
- package/ai/tools/dialogMessageSearch.ts +137 -0
- package/ai/tools/doctorSkillTool.ts +72 -0
- package/ai/tools/ecommerceScraperTool.ts +86 -0
- package/ai/tools/emailTools.ts +549 -0
- package/ai/tools/evalSkillTool.ts +92 -0
- package/ai/tools/exaSearchTool.ts +64 -0
- package/ai/tools/execBashTool.ts +379 -0
- package/ai/tools/executeSqlTool.ts +192 -0
- package/ai/tools/fetchWebpageSupport.ts +309 -0
- package/ai/tools/fetchWebpageTool.ts +84 -0
- package/ai/tools/geminiImagePreviewTool.ts +361 -0
- package/ai/tools/generateDocxTool.ts +215 -0
- package/ai/tools/googleSearchScraperTool.ts +106 -0
- package/ai/tools/importDataTool.ts +133 -0
- package/ai/tools/importSkillTool.ts +162 -0
- package/ai/tools/index.ts +1927 -0
- package/ai/tools/listFilesTool.ts +82 -0
- package/ai/tools/listUserSpacesTool.ts +113 -0
- package/ai/tools/modelUsageTools.ts +199 -0
- package/ai/tools/olmOcrTool.ts +34 -0
- package/ai/tools/openaiImageTool.ts +267 -0
- package/ai/tools/prepareTools.ts +23 -0
- package/ai/tools/readDocTool.ts +84 -0
- package/ai/tools/readFileTool.ts +211 -0
- package/ai/tools/readTool.ts +163 -0
- package/ai/tools/readXPostTool.ts +233 -0
- package/ai/tools/rememberMemoryTool.ts +84 -0
- package/ai/tools/remotionVideoTool.ts +151 -0
- package/ai/tools/searchDialogMessagesTool.ts +222 -0
- package/ai/tools/searchRepoTool.ts +115 -0
- package/ai/tools/searchWorkspaceTool.ts +259 -0
- package/ai/tools/skillFollowup.ts +86 -0
- package/ai/tools/surfWeatherTool.ts +169 -0
- package/ai/tools/table/addTableRowTool.ts +217 -0
- package/ai/tools/table/createTableTool.ts +315 -0
- package/ai/tools/table/rowTools.ts +366 -0
- package/ai/tools/table/schemaTools.ts +244 -0
- package/ai/tools/table/shareTableTool.ts +148 -0
- package/ai/tools/table/toolShared.ts +129 -0
- package/ai/tools/toolApiClient.ts +198 -0
- package/ai/tools/toolNameAliases.ts +57 -0
- package/ai/tools/toolResultError.ts +42 -0
- package/ai/tools/toolRunSlice.ts +303 -0
- package/ai/tools/toolSchemaCompatibility.ts +53 -0
- package/ai/tools/toolVisibility.ts +4 -0
- package/ai/tools/types.ts +20 -0
- package/ai/tools/uiAskChoiceTool.ts +104 -0
- package/ai/tools/updateContentTitleTool.ts +84 -0
- package/ai/tools/updateDocTool.ts +105 -0
- package/ai/tools/updateUserPreferenceProfileTool.ts +145 -0
- package/ai/tools/whisperTool.ts +77 -0
- package/ai/tools/writeFileTool.ts +210 -0
- package/ai/tools/youtubeScraperTool.ts +116 -0
- package/ai/tools/ziweiChartTool.ts +678 -0
- package/ai/types.ts +55 -0
- package/ai/workflow/workflowExecutor.ts +323 -0
- package/ai/workflow/workflowSlice.ts +73 -0
- package/ai/workflow/workflowTypes.ts +106 -0
- package/client/agentRun.test.ts +240 -0
- package/client/agentRun.ts +182 -19
- package/client/compactDialog.test.ts +238 -0
- package/client/localRuntimeAdapter.test.ts +135 -0
- package/client/localRuntimeAdapter.ts +244 -0
- package/client/profileConfig.test.ts +40 -0
- package/client/streamingOutput.test.ts +22 -0
- package/client/streamingOutput.ts +38 -0
- package/commandRegistry.ts +9 -2
- package/connector-experimental/index.ts +5 -0
- package/database/actions/cacheMergedUserData.ts +64 -0
- package/database/actions/common.ts +242 -0
- package/database/actions/deleteFile.ts +40 -0
- package/database/actions/fetchUserData.ts +16 -0
- package/database/actions/fileContent.ts +125 -0
- package/database/actions/patch.ts +155 -0
- package/database/actions/read.ts +337 -0
- package/database/actions/readAndWait.ts +224 -0
- package/database/actions/readRequestManager.ts +120 -0
- package/database/actions/remove.ts +94 -0
- package/database/actions/replication.ts +366 -0
- package/database/actions/upload.ts +174 -0
- package/database/actions/upsert.ts +56 -0
- package/database/actions/write.ts +126 -0
- package/database/client/db.native.ts +73 -0
- package/database/client/db.ts +51 -0
- package/database/client/fetchUserData.ts +61 -0
- package/database/client/handleError.ts +19 -0
- package/database/client/queryRequest.ts +21 -0
- package/database/config.ts +21 -0
- package/database/dbActionThunks.ts +1 -0
- package/database/dbSlice.ts +149 -0
- package/database/email.ts +42 -0
- package/database/fileRing.ts +51 -0
- package/database/fileSharding.ts +70 -0
- package/database/fileStorage.native.ts +92 -0
- package/database/fileStorage.ts +232 -0
- package/database/fileUrl.ts +34 -0
- package/database/hooks/useUserData.ts +489 -0
- package/database/index.ts +1 -0
- package/database/keys.ts +765 -0
- package/database/queryPrefixes.ts +14 -0
- package/database/requests.ts +443 -0
- package/database/runtimeServerContext.ts +35 -0
- package/database/server/MemoryDB.ts +76 -0
- package/database/server/actorAccess.ts +76 -0
- package/database/server/agentDelegation.ts +124 -0
- package/database/server/coreDataOwnership.ts +13 -0
- package/database/server/coreDataProxy.ts +76 -0
- package/database/server/cybotReadonly.ts +18 -0
- package/database/server/dataHandlers.ts +111 -0
- package/database/server/db.ts +118 -0
- package/database/server/dbPath.ts +20 -0
- package/database/server/delete.ts +499 -0
- package/database/server/emailRepository.ts +1480 -0
- package/database/server/ensureDbOpen.ts +12 -0
- package/database/server/fileRead.ts +337 -0
- package/database/server/fileService.ts +436 -0
- package/database/server/handleTransaction.ts +86 -0
- package/database/server/patch.ts +282 -0
- package/database/server/query.ts +138 -0
- package/database/server/read.ts +325 -0
- package/database/server/resourceAccess.ts +211 -0
- package/database/server/routes.ts +110 -0
- package/database/server/spaceMemberAuthority.ts +67 -0
- package/database/server/upload.ts +159 -0
- package/database/server/write.ts +494 -0
- package/database/server/writeAuthority.ts +133 -0
- package/database/sqliteDb.ts +46 -0
- package/database/table/deleteTable.ts +120 -0
- package/database/tenantPlacement.ts +57 -0
- package/database/tombstones.ts +52 -0
- package/database/userDataLoadDecision.ts +17 -0
- package/database/userDataMerge.ts +95 -0
- package/database/userPreferenceRegister.ts +108 -0
- package/database/utils/dbPath.ts +47 -0
- package/database/utils/ulid.native.ts +6 -0
- package/database/utils/ulid.ts +1 -0
- package/index.ts +25 -15
- package/localRuntimeDb.ts +28 -0
- package/package.json +16 -4
- package/runtimeModeArgs.ts +33 -0
- package/tui/readlineWorkspace.ts +1 -0
- package/tui/session.ts +22 -0
|
@@ -0,0 +1,84 @@
|
|
|
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
|
+
...(typeof imageGenerationCount === "number"
|
|
75
|
+
? { image_generation_count: imageGenerationCount }
|
|
76
|
+
: {}),
|
|
77
|
+
...(billingProvider ? { billing_provider: billingProvider } : {}),
|
|
78
|
+
...(billingModel ? { billing_model: billingModel } : {}),
|
|
79
|
+
...(billingServiceTier
|
|
80
|
+
? { billing_service_tier: billingServiceTier }
|
|
81
|
+
: {}),
|
|
82
|
+
...(billingEstimated ? { billing_estimated: true } : {}),
|
|
83
|
+
};
|
|
84
|
+
};
|
|
@@ -0,0 +1,56 @@
|
|
|
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);
|
|
@@ -0,0 +1,88 @@
|
|
|
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
|
+
};
|
|
@@ -0,0 +1,88 @@
|
|
|
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
|
+
|
|
@@ -0,0 +1,59 @@
|
|
|
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
|
+
};
|
|
@@ -0,0 +1,52 @@
|
|
|
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
|
+
};
|
|
@@ -0,0 +1,53 @@
|
|
|
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
|
+
};
|
|
@@ -0,0 +1,78 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
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
|
+
}
|