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