@valerypopoff/rivet2-core 2.24.0 → 2.25.0

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 (43) hide show
  1. package/dist/cjs/bundle.cjs +273 -28
  2. package/dist/cjs/bundle.cjs.map +3 -3
  3. package/dist/cjs/interpolationRuntime.cjs +23 -0
  4. package/dist/cjs/interpolationRuntime.cjs.map +3 -3
  5. package/dist/cjs/serialization.cjs +1 -0
  6. package/dist/cjs/serialization.cjs.map +2 -2
  7. package/dist/esm/exports.js +3 -0
  8. package/dist/esm/model/DatasetOwnership.js +9 -0
  9. package/dist/esm/model/GraphExecutionState.js +3 -0
  10. package/dist/esm/model/GraphProcessor.js +62 -1
  11. package/dist/esm/model/RunCostLedger.js +58 -0
  12. package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -2
  13. package/dist/esm/model/chat-v2/chatV2Outputs.js +1 -1
  14. package/dist/esm/model/chat-v2/chatV2Pipeline.js +5 -0
  15. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +3 -0
  16. package/dist/esm/model/chat-v2/llmModelCandidate.js +3 -0
  17. package/dist/esm/model/chat-v2/llmProfile.js +2 -0
  18. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +1 -0
  19. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +2 -1
  20. package/dist/esm/model/chat-v2/modelRegistry.js +12 -3
  21. package/dist/esm/model/classifier/profile.js +11 -3
  22. package/dist/esm/model/classifier/profileExecution.js +2 -1
  23. package/dist/esm/model/classifier/providers.js +25 -14
  24. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +16 -5
  25. package/dist/esm/model/nodes/ClassifierProfileNode.js +2 -0
  26. package/dist/esm/model/tokenPricing.js +52 -0
  27. package/dist/esm/model/tokenPricingEditor.js +9 -0
  28. package/dist/types/exports.d.ts +3 -0
  29. package/dist/types/model/DatasetOwnership.d.ts +5 -0
  30. package/dist/types/model/GraphExecutionState.d.ts +2 -0
  31. package/dist/types/model/GraphProcessor.d.ts +3 -0
  32. package/dist/types/model/RunCostLedger.d.ts +19 -0
  33. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +1 -1
  34. package/dist/types/model/chat-v2/chatV2Types.d.ts +2 -0
  35. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +3 -1
  36. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +7 -5
  37. package/dist/types/model/chat-v2/modelRegistry.d.ts +7 -1
  38. package/dist/types/model/classifier/profile.d.ts +3 -1
  39. package/dist/types/model/classifier/profileExecution.d.ts +1 -0
  40. package/dist/types/model/classifier/providers.d.ts +4 -1
  41. package/dist/types/model/tokenPricing.d.ts +18 -0
  42. package/dist/types/model/tokenPricingEditor.d.ts +4 -0
  43. package/package.json +1 -1
@@ -0,0 +1,52 @@
1
+ /** Provider token counts must be exact, nonnegative integers before applying rates. */
2
+ export function isReportedTokenCount(value) {
3
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
4
+ }
5
+ export function validateTokenPricing(value) {
6
+ if (value === undefined)
7
+ return undefined;
8
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
9
+ throw new Error('Token pricing override must be an object.');
10
+ const result = {};
11
+ for (const key of [
12
+ 'inputPerMillionTokens',
13
+ 'outputPerMillionTokens',
14
+ 'cacheReadPerMillionTokens',
15
+ 'cacheWritePerMillionTokens',
16
+ ]) {
17
+ const rate = value[key];
18
+ if (rate === undefined && key.startsWith('cache'))
19
+ continue;
20
+ if (typeof rate !== 'number' || !Number.isFinite(rate) || rate < 0)
21
+ throw new Error(`Token pricing ${key} must be a finite, non-negative USD rate.`);
22
+ result[key] = rate;
23
+ }
24
+ return result;
25
+ }
26
+ export function calculateTokenUsageCost(pricing, usage) {
27
+ try {
28
+ const validated = validateTokenPricing(pricing);
29
+ if (!validated)
30
+ return undefined;
31
+ pricing = validated;
32
+ }
33
+ catch {
34
+ return undefined;
35
+ }
36
+ const { inputTokens, outputTokens, inputTokenDetails } = usage ?? {};
37
+ const read = inputTokenDetails?.cacheReadTokens === undefined ? 0 : inputTokenDetails.cacheReadTokens;
38
+ const write = inputTokenDetails?.cacheWriteTokens === undefined ? 0 : inputTokenDetails.cacheWriteTokens;
39
+ if (!isReportedTokenCount(inputTokens) ||
40
+ !isReportedTokenCount(outputTokens) ||
41
+ !isReportedTokenCount(read) ||
42
+ !isReportedTokenCount(write))
43
+ return undefined;
44
+ if (read + write > inputTokens)
45
+ return undefined;
46
+ const total = ((inputTokens - read - write) * pricing.inputPerMillionTokens +
47
+ read * (pricing.cacheReadPerMillionTokens ?? pricing.inputPerMillionTokens) +
48
+ write * (pricing.cacheWritePerMillionTokens ?? pricing.inputPerMillionTokens) +
49
+ outputTokens * pricing.outputPerMillionTokens) /
50
+ 1_000_000;
51
+ return Number.isFinite(total) && total >= 0 ? total : undefined;
52
+ }
@@ -0,0 +1,9 @@
1
+ /** Shared settings section for inline configurations and separate profile nodes. */
2
+ export function getTokenPricingEditor() {
3
+ return {
4
+ type: 'group',
5
+ label: 'Token pricing',
6
+ defaultOpen: false,
7
+ editors: [{ type: 'custom', label: 'Token pricing', customEditorId: 'AIProfilePricing' }],
8
+ };
9
+ }
@@ -60,6 +60,8 @@ export * from './plugins.js';
60
60
  export * from './model/classifier/credentials.js';
61
61
  export * from './model/classifier/migration.js';
62
62
  export * from './model/classifier/providers.js';
63
+ export * from './model/tokenPricing.js';
64
+ export { getChatV2SystemTokenPricing } from './model/chat-v2/modelRegistry.js';
63
65
  export * from './model/classifier/types.js';
64
66
  export * from './model/NodeRegistration.js';
65
67
  export * from './model/RegistryAssembly.js';
@@ -69,6 +71,7 @@ export * from './model/NodeBodySpec.js';
69
71
  export * from './model/interpolationInputDefinition.js';
70
72
  export * from './integrations/DatasetProvider.js';
71
73
  export * from './model/Dataset.js';
74
+ export { remapOwnedDatasets } from './model/DatasetOwnership.js';
72
75
  export type { DatasetRequestMap, DatasetRequestMessage, DatasetRequestPayload, CodeConsoleLevel, CodeConsoleMessage, GraphUploadAllowedMessage, IncomingMessage, OutgoingMessage, OutgoingMessageMap, ProcessEventMessage, ProcessEventMessageMap, RemoteRunRequestId, SerializedProcessEventMap, } from './model/ExecutorProtocol.js';
73
76
  export * from './api/streaming.js';
74
77
  export * from './api/createProcessor.js';
@@ -0,0 +1,5 @@
1
+ import type { ProjectId } from './Project.js';
2
+ import type { CombinedDataset } from '../utils/serialization/serialization.js';
3
+ /** Change only the owner of already validated sidecars. Reference/version
4
+ * rewiring is an operation-specific policy, not part of dataset ownership. */
5
+ export declare function remapOwnedDatasets(datasets: readonly CombinedDataset[], sourceId: ProjectId, targetId: ProjectId): CombinedDataset[];
@@ -10,6 +10,7 @@ import type { RivetStoredValueController } from './StoredValueStore.js';
10
10
  import type { KnowledgeStoreController } from '../integrations/KnowledgeStoreProvider.js';
11
11
  import type { ResolvedSubgraphProject } from './SubgraphProjectTarget.js';
12
12
  import type { GraphCostBreakdown } from './GraphBoundaryEffects.js';
13
+ import { RunCostLedger } from './RunCostLedger.js';
13
14
  /** Invocation-owned fields; GraphProcessor resets them at the established initialization boundaries. */
14
15
  export declare class GraphInvocationState {
15
16
  rootRunId: RootRunId;
@@ -35,6 +36,7 @@ export declare class GraphInvocationState {
35
36
  successfulAbortTerminalProcessIds: Set<ProcessId>;
36
37
  totalCost: number;
37
38
  costBreakdown: GraphCostBreakdown | undefined;
39
+ costLedger: RunCostLedger;
38
40
  ignoreNodes: Set<NodeId>;
39
41
  hasPreloadedData: boolean;
40
42
  loadedProjects: Record<ProjectId, Project>;
@@ -1,3 +1,4 @@
1
+ import type { RunCostSnapshot } from './RunCostLedger.js';
1
2
  import { type DataValue, type StringArrayDataValue, type ScalarOrArrayDataValue } from './DataValue.js';
2
3
  import type { NodeInputs, NodeOutputs } from './NodeIO.js';
3
4
  import { type ChartNode, type NodeConnection, type NodeId } from './NodeBase.js';
@@ -366,6 +367,8 @@ export declare class GraphProcessor {
366
367
  graphInputStreams?: Readonly<Record<string, GraphInputStream>>;
367
368
  }): Promise<GraphOutputs>;
368
369
  getRootProcessor(): GraphProcessor;
370
+ /** Snapshot the root execution's observed provider estimates after completion. */
371
+ getRunCostSnapshot(): RunCostSnapshot;
369
372
  /** Raise a user event on the processor, all subprocessors, and their children. */
370
373
  raiseEvent(event: string, data: DataValue): void;
371
374
  }
@@ -0,0 +1,19 @@
1
+ import type { ChatV2CallFinishedEvent, LLMProfileAttemptTraceEvent } from './ProcessContext.js';
2
+ /** Run-owned provider estimates. It is not an invoice or a graph output. */
3
+ export type RunCostSnapshot = {
4
+ status: 'complete' | 'partial';
5
+ knownCostUsd: number;
6
+ } | {
7
+ status: 'unknown';
8
+ knownCostUsd: null;
9
+ };
10
+ /** Receives physical-call observations directly, before display/recording filters. */
11
+ export declare class RunCostLedger {
12
+ #private;
13
+ observeChat(event: ChatV2CallFinishedEvent): void;
14
+ observeClassifier(event: LLMProfileAttemptTraceEvent): void;
15
+ /** Legacy Chat does not expose complete per-attempt accounting. */
16
+ observeLegacy(key: string, value: unknown): void;
17
+ markUnobserved(): void;
18
+ snapshot(executionPending?: boolean): RunCostSnapshot;
19
+ }
@@ -14,7 +14,7 @@ type CreateChatV2CommonOutputsOptions = ChatV2CommonOutputOptions & {
14
14
  requestBodies?: unknown[] | undefined;
15
15
  responseBodies?: unknown[] | undefined;
16
16
  };
17
- export declare function normalizeChatV2Usage(usage: LanguageModelUsage | undefined, options: Pick<RunChatV2PipelineOptions, 'provider' | 'modelId'>, providerMetadata?: Record<string, Record<string, unknown>>): ChatV2NormalizedUsage | undefined;
17
+ export declare function normalizeChatV2Usage(usage: LanguageModelUsage | undefined, options: Pick<RunChatV2PipelineOptions, 'provider' | 'modelId' | 'tokenPricing'>, providerMetadata?: Record<string, Record<string, unknown>>): ChatV2NormalizedUsage | undefined;
18
18
  export declare function createChatV2ResponseOutput(response: string, structuredOutput: unknown | undefined, responseFormat: RunChatV2PipelineOptions['responseFormat']): DataValue;
19
19
  export declare function createChatV2CapturedBodyOutputs(options: Pick<RunChatV2PipelineOptions, 'requestBodies' | 'responseBodies' | 'outputRequestBody' | 'outputResponseBody'>): Outputs;
20
20
  export declare function createChatV2CommonOutputs({ requestMessages, response, structuredOutput, functionCalls, usage, reasoning, requestBodies, responseBodies, outputUsage, outputReasoning, outputRequestBody, outputResponseBody, includeFunctionCalls, functionCallMode, responseFormat, }: CreateChatV2CommonOutputsOptions): Outputs;
@@ -2,6 +2,7 @@ import type { generateText, streamText, LanguageModelUsage, ModelMessage, TextSt
2
2
  import type { ChatMessage, GptFunction } from '../DataValue.js';
3
3
  import type { Outputs } from '../GraphProcessor.js';
4
4
  import type { InternalProcessContext } from '../ProcessContext.js';
5
+ import type { TokenPricing } from '../tokenPricing.js';
5
6
  import type { AssistantMessageFunctionCallMode, StreamedFunctionCall } from '../chat/streamChatResponse.js';
6
7
  import type { ChatV2Provider } from './chatV2ProviderTypes.js';
7
8
  import type { ChatV2ResponseBodyCapture } from './chatV2ResponseBodyCapture.js';
@@ -134,6 +135,7 @@ export type StreamChatV2Result = {
134
135
  requestStatus: number | undefined;
135
136
  };
136
137
  export type RunChatV2PipelineOptions = {
138
+ tokenPricing?: TokenPricing | undefined;
137
139
  provider: ChatV2Provider;
138
140
  model: ChatV2Model;
139
141
  modelId: string;
@@ -2,6 +2,7 @@ import type { ChatV2ResponseFormat } from './chatV2ResponseFormat.js';
2
2
  import { type ChatV2CommonNodeData } from './chatV2Shared.js';
3
3
  import type { ChatV2Provider } from './chatV2Types.js';
4
4
  import type { ChartNode, NodeId } from '../NodeBase.js';
5
+ import type { TokenPricing } from '../tokenPricing.js';
5
6
  import type { CustomProviderApi } from './customProviderApi.js';
6
7
  import type { ChatV2CredentialNamesByProvider } from './chatV2CredentialNames.js';
7
8
  export type { CustomProviderApi } from './customProviderApi.js';
@@ -9,6 +10,7 @@ export type LLMChatV2ToolChoiceMode = '' | 'auto' | 'function' | 'required';
9
10
  export type LLMChatV2ApiKeySource = 'environment' | 'input';
10
11
  export type LLMChatV2ConfigurationMode = 'inline' | 'profile';
11
12
  export type LLMChatV2NodeConfigData = ChatV2CommonNodeData & {
13
+ tokenPricing?: TokenPricing;
12
14
  configurationMode?: LLMChatV2ConfigurationMode;
13
15
  provider: ChatV2Provider;
14
16
  apiKeySource?: LLMChatV2ApiKeySource;
@@ -75,7 +77,7 @@ export type LLMChatV2NodeConfigData = ChatV2CommonNodeData & {
75
77
  export type LLMChatV2NodeData = LLMChatV2NodeConfigData;
76
78
  export type LLMChatV2Node = ChartNode<'llmChatV2', LLMChatV2NodeData>;
77
79
  /** @deprecated Use llmProfileDataKeys from llmProfileFieldRegistry instead. */
78
- export declare const llmChatV2ProfileDataKeys: ("provider" | "model" | "useModelInput" | "temperature" | "useTemperatureInput" | "topP" | "useTopPInput" | "topK" | "useTopKInput" | "presencePenalty" | "usePresencePenaltyInput" | "frequencyPenalty" | "useFrequencyPenaltyInput" | "stopSequences" | "useStopSequencesInput" | "seed" | "useSeedInput" | "maxTokens" | "useMaxTokensInput" | "apiKeySource" | "providerApiKeyNames" | "customProviderApiKeyProgrammaticName" | "customProviderApiKeyEnvVarName" | "customProviderBaseURL" | "useCustomProviderBaseURLInput" | "customProviderApi" | "headers" | "useHeadersInput" | "extraProviderOptions" | "useExtraProviderOptionsInput" | "openAIReasoningEffort" | "openRouterReasoningEffort" | "openAIReasoningSummary" | "openAIPreviousResponseId" | "useOpenAIPreviousResponseIdInput" | "enableOpenAIWebSearch" | "openAIWebSearchContextSize" | "enableOpenAICodeInterpreter" | "anthropicThinkingMode" | "anthropicThinkingBudget" | "useAnthropicThinkingBudgetInput" | "anthropicEffort" | "anthropicCacheControlTtl" | "googleThinkingBudget" | "useGoogleThinkingBudgetInput" | "googleThinkingLevel" | "googleIncludeThoughts" | "enableGoogleSearchGrounding" | "enableGoogleUrlContext" | "enableCircuitBreaker" | "firstOutputTimeoutMs" | "streamInactivityTimeoutMs" | "circuitBreakerFailureThreshold" | "circuitBreakerFailureWindowMs" | "circuitBreakerOpenDurationMs")[];
80
+ export declare const llmChatV2ProfileDataKeys: ("provider" | "tokenPricing" | "model" | "useModelInput" | "temperature" | "useTemperatureInput" | "topP" | "useTopPInput" | "topK" | "useTopKInput" | "presencePenalty" | "usePresencePenaltyInput" | "frequencyPenalty" | "useFrequencyPenaltyInput" | "stopSequences" | "useStopSequencesInput" | "seed" | "useSeedInput" | "maxTokens" | "useMaxTokensInput" | "apiKeySource" | "providerApiKeyNames" | "customProviderApiKeyProgrammaticName" | "customProviderApiKeyEnvVarName" | "customProviderBaseURL" | "useCustomProviderBaseURLInput" | "customProviderApi" | "headers" | "useHeadersInput" | "extraProviderOptions" | "useExtraProviderOptionsInput" | "openAIReasoningEffort" | "openRouterReasoningEffort" | "openAIReasoningSummary" | "openAIPreviousResponseId" | "useOpenAIPreviousResponseIdInput" | "enableOpenAIWebSearch" | "openAIWebSearchContextSize" | "enableOpenAICodeInterpreter" | "anthropicThinkingMode" | "anthropicThinkingBudget" | "useAnthropicThinkingBudgetInput" | "anthropicEffort" | "anthropicCacheControlTtl" | "googleThinkingBudget" | "useGoogleThinkingBudgetInput" | "googleThinkingLevel" | "googleIncludeThoughts" | "enableGoogleSearchGrounding" | "enableGoogleUrlContext" | "enableCircuitBreaker" | "firstOutputTimeoutMs" | "streamInactivityTimeoutMs" | "circuitBreakerFailureThreshold" | "circuitBreakerFailureWindowMs" | "circuitBreakerOpenDurationMs")[];
79
81
  export type LLMChatV2ProfileDataKey = (typeof llmChatV2ProfileDataKeys)[number];
80
82
  export type LLMChatV2ProfileData = Pick<LLMChatV2NodeData, LLMChatV2ProfileDataKey>;
81
83
  export type LLMChatV2EditorCacheKeyParts = {
@@ -16,6 +16,8 @@ export type LLMProfileFieldSpec = {
16
16
  resolvedInputToggle?: boolean;
17
17
  };
18
18
  export declare const llmProfileFieldSpecs: readonly [{
19
+ readonly key: "tokenPricing";
20
+ }, {
19
21
  readonly key: "model";
20
22
  readonly inputId: "model";
21
23
  readonly valueKind: "string";
@@ -201,12 +203,12 @@ export declare const llmProfileFieldSpecs: readonly [{
201
203
  readonly key: "circuitBreakerOpenDurationMs";
202
204
  readonly valueKind: "required-number";
203
205
  }];
204
- export declare const llmProfileDataKeys: ("provider" | "model" | "useModelInput" | "temperature" | "useTemperatureInput" | "topP" | "useTopPInput" | "topK" | "useTopKInput" | "presencePenalty" | "usePresencePenaltyInput" | "frequencyPenalty" | "useFrequencyPenaltyInput" | "stopSequences" | "useStopSequencesInput" | "seed" | "useSeedInput" | "maxTokens" | "useMaxTokensInput" | "apiKeySource" | "providerApiKeyNames" | "customProviderApiKeyProgrammaticName" | "customProviderApiKeyEnvVarName" | "customProviderBaseURL" | "useCustomProviderBaseURLInput" | "customProviderApi" | "headers" | "useHeadersInput" | "extraProviderOptions" | "useExtraProviderOptionsInput" | "openAIReasoningEffort" | "openRouterReasoningEffort" | "openAIReasoningSummary" | "openAIPreviousResponseId" | "useOpenAIPreviousResponseIdInput" | "enableOpenAIWebSearch" | "openAIWebSearchContextSize" | "enableOpenAICodeInterpreter" | "anthropicThinkingMode" | "anthropicThinkingBudget" | "useAnthropicThinkingBudgetInput" | "anthropicEffort" | "anthropicCacheControlTtl" | "googleThinkingBudget" | "useGoogleThinkingBudgetInput" | "googleThinkingLevel" | "googleIncludeThoughts" | "enableGoogleSearchGrounding" | "enableGoogleUrlContext" | "enableCircuitBreaker" | "firstOutputTimeoutMs" | "streamInactivityTimeoutMs" | "circuitBreakerFailureThreshold" | "circuitBreakerFailureWindowMs" | "circuitBreakerOpenDurationMs")[];
206
+ export declare const llmProfileDataKeys: ("provider" | "tokenPricing" | "model" | "useModelInput" | "temperature" | "useTemperatureInput" | "topP" | "useTopPInput" | "topK" | "useTopKInput" | "presencePenalty" | "usePresencePenaltyInput" | "frequencyPenalty" | "useFrequencyPenaltyInput" | "stopSequences" | "useStopSequencesInput" | "seed" | "useSeedInput" | "maxTokens" | "useMaxTokensInput" | "apiKeySource" | "providerApiKeyNames" | "customProviderApiKeyProgrammaticName" | "customProviderApiKeyEnvVarName" | "customProviderBaseURL" | "useCustomProviderBaseURLInput" | "customProviderApi" | "headers" | "useHeadersInput" | "extraProviderOptions" | "useExtraProviderOptionsInput" | "openAIReasoningEffort" | "openRouterReasoningEffort" | "openAIReasoningSummary" | "openAIPreviousResponseId" | "useOpenAIPreviousResponseIdInput" | "enableOpenAIWebSearch" | "openAIWebSearchContextSize" | "enableOpenAICodeInterpreter" | "anthropicThinkingMode" | "anthropicThinkingBudget" | "useAnthropicThinkingBudgetInput" | "anthropicEffort" | "anthropicCacheControlTtl" | "googleThinkingBudget" | "useGoogleThinkingBudgetInput" | "googleThinkingLevel" | "googleIncludeThoughts" | "enableGoogleSearchGrounding" | "enableGoogleUrlContext" | "enableCircuitBreaker" | "firstOutputTimeoutMs" | "streamInactivityTimeoutMs" | "circuitBreakerFailureThreshold" | "circuitBreakerFailureWindowMs" | "circuitBreakerOpenDurationMs")[];
205
207
  export declare const llmProfileInputIds: ("model" | "temperature" | "topP" | "topK" | "presencePenalty" | "frequencyPenalty" | "stopSequences" | "seed" | "maxTokens" | "customProviderBaseURL" | "headers" | "extraProviderOptions" | "anthropicThinkingBudget" | "googleThinkingBudget" | "apiKey" | "previousResponseId")[];
206
208
  /** Runtime validation categories for resolved LLM Profile values. */
207
- export declare const llmProfileStringDataKeys: ("provider" | keyof import("./chatV2Shared.js").ChatV2CommonNodeData | "configurationMode" | "apiKeySource" | "providerApiKeyNames" | "customProviderApiKeyProgrammaticName" | "customProviderApiKeyEnvVarName" | "customProviderBaseURL" | "useCustomProviderBaseURLInput" | "customProviderApi" | "baseURL" | "useBaseURLInput" | "headers" | "useHeadersInput" | "extraProviderOptions" | "useExtraProviderOptionsInput" | "openAIReasoningEffort" | "openRouterReasoningEffort" | "openAIReasoningSummary" | "openAIPreviousResponseId" | "useOpenAIPreviousResponseIdInput" | "enableOpenAIWebSearch" | "openAIWebSearchContextSize" | "enableOpenAICodeInterpreter" | "anthropicThinkingMode" | "anthropicThinkingBudget" | "useAnthropicThinkingBudgetInput" | "anthropicEffort" | "anthropicCacheControlTtl" | "googleThinkingBudget" | "useGoogleThinkingBudgetInput" | "googleThinkingLevel" | "googleIncludeThoughts" | "enableGoogleSearchGrounding" | "enableGoogleUrlContext" | "enableCircuitBreaker" | "firstOutputTimeoutMs" | "streamInactivityTimeoutMs" | "circuitBreakerFailureThreshold" | "circuitBreakerFailureWindowMs" | "circuitBreakerOpenDurationMs" | "responseFormat" | "responseSchemaName" | "useResponseSchemaNameInput" | "responseSchemaDescription" | "useResponseSchemaDescriptionInput" | "toolChoice" | "toolChoiceFunction" | "parallelToolCalls" | "autoContinueToolCalls" | "maxToolRounds" | "retryOnNon200" | "errorOnNon200" | "catchRequestFailed" | "retryOnNon200RepeatTimes" | "retryOnNon200CooldownMs" | "outputLLMAttempts" | "outputRequestBody" | "outputResponseBody")[];
208
- export declare const llmProfileBooleanDataKeys: ("provider" | keyof import("./chatV2Shared.js").ChatV2CommonNodeData | "configurationMode" | "apiKeySource" | "providerApiKeyNames" | "customProviderApiKeyProgrammaticName" | "customProviderApiKeyEnvVarName" | "customProviderBaseURL" | "useCustomProviderBaseURLInput" | "customProviderApi" | "baseURL" | "useBaseURLInput" | "headers" | "useHeadersInput" | "extraProviderOptions" | "useExtraProviderOptionsInput" | "openAIReasoningEffort" | "openRouterReasoningEffort" | "openAIReasoningSummary" | "openAIPreviousResponseId" | "useOpenAIPreviousResponseIdInput" | "enableOpenAIWebSearch" | "openAIWebSearchContextSize" | "enableOpenAICodeInterpreter" | "anthropicThinkingMode" | "anthropicThinkingBudget" | "useAnthropicThinkingBudgetInput" | "anthropicEffort" | "anthropicCacheControlTtl" | "googleThinkingBudget" | "useGoogleThinkingBudgetInput" | "googleThinkingLevel" | "googleIncludeThoughts" | "enableGoogleSearchGrounding" | "enableGoogleUrlContext" | "enableCircuitBreaker" | "firstOutputTimeoutMs" | "streamInactivityTimeoutMs" | "circuitBreakerFailureThreshold" | "circuitBreakerFailureWindowMs" | "circuitBreakerOpenDurationMs" | "responseFormat" | "responseSchemaName" | "useResponseSchemaNameInput" | "responseSchemaDescription" | "useResponseSchemaDescriptionInput" | "toolChoice" | "toolChoiceFunction" | "parallelToolCalls" | "autoContinueToolCalls" | "maxToolRounds" | "retryOnNon200" | "errorOnNon200" | "catchRequestFailed" | "retryOnNon200RepeatTimes" | "retryOnNon200CooldownMs" | "outputLLMAttempts" | "outputRequestBody" | "outputResponseBody")[];
209
- export declare const llmProfileRequiredNumberDataKeys: ("provider" | keyof import("./chatV2Shared.js").ChatV2CommonNodeData | "configurationMode" | "apiKeySource" | "providerApiKeyNames" | "customProviderApiKeyProgrammaticName" | "customProviderApiKeyEnvVarName" | "customProviderBaseURL" | "useCustomProviderBaseURLInput" | "customProviderApi" | "baseURL" | "useBaseURLInput" | "headers" | "useHeadersInput" | "extraProviderOptions" | "useExtraProviderOptionsInput" | "openAIReasoningEffort" | "openRouterReasoningEffort" | "openAIReasoningSummary" | "openAIPreviousResponseId" | "useOpenAIPreviousResponseIdInput" | "enableOpenAIWebSearch" | "openAIWebSearchContextSize" | "enableOpenAICodeInterpreter" | "anthropicThinkingMode" | "anthropicThinkingBudget" | "useAnthropicThinkingBudgetInput" | "anthropicEffort" | "anthropicCacheControlTtl" | "googleThinkingBudget" | "useGoogleThinkingBudgetInput" | "googleThinkingLevel" | "googleIncludeThoughts" | "enableGoogleSearchGrounding" | "enableGoogleUrlContext" | "enableCircuitBreaker" | "firstOutputTimeoutMs" | "streamInactivityTimeoutMs" | "circuitBreakerFailureThreshold" | "circuitBreakerFailureWindowMs" | "circuitBreakerOpenDurationMs" | "responseFormat" | "responseSchemaName" | "useResponseSchemaNameInput" | "responseSchemaDescription" | "useResponseSchemaDescriptionInput" | "toolChoice" | "toolChoiceFunction" | "parallelToolCalls" | "autoContinueToolCalls" | "maxToolRounds" | "retryOnNon200" | "errorOnNon200" | "catchRequestFailed" | "retryOnNon200RepeatTimes" | "retryOnNon200CooldownMs" | "outputLLMAttempts" | "outputRequestBody" | "outputResponseBody")[];
210
- export declare const llmProfileOptionalNumberDataKeys: ("provider" | keyof import("./chatV2Shared.js").ChatV2CommonNodeData | "configurationMode" | "apiKeySource" | "providerApiKeyNames" | "customProviderApiKeyProgrammaticName" | "customProviderApiKeyEnvVarName" | "customProviderBaseURL" | "useCustomProviderBaseURLInput" | "customProviderApi" | "baseURL" | "useBaseURLInput" | "headers" | "useHeadersInput" | "extraProviderOptions" | "useExtraProviderOptionsInput" | "openAIReasoningEffort" | "openRouterReasoningEffort" | "openAIReasoningSummary" | "openAIPreviousResponseId" | "useOpenAIPreviousResponseIdInput" | "enableOpenAIWebSearch" | "openAIWebSearchContextSize" | "enableOpenAICodeInterpreter" | "anthropicThinkingMode" | "anthropicThinkingBudget" | "useAnthropicThinkingBudgetInput" | "anthropicEffort" | "anthropicCacheControlTtl" | "googleThinkingBudget" | "useGoogleThinkingBudgetInput" | "googleThinkingLevel" | "googleIncludeThoughts" | "enableGoogleSearchGrounding" | "enableGoogleUrlContext" | "enableCircuitBreaker" | "firstOutputTimeoutMs" | "streamInactivityTimeoutMs" | "circuitBreakerFailureThreshold" | "circuitBreakerFailureWindowMs" | "circuitBreakerOpenDurationMs" | "responseFormat" | "responseSchemaName" | "useResponseSchemaNameInput" | "responseSchemaDescription" | "useResponseSchemaDescriptionInput" | "toolChoice" | "toolChoiceFunction" | "parallelToolCalls" | "autoContinueToolCalls" | "maxToolRounds" | "retryOnNon200" | "errorOnNon200" | "catchRequestFailed" | "retryOnNon200RepeatTimes" | "retryOnNon200CooldownMs" | "outputLLMAttempts" | "outputRequestBody" | "outputResponseBody")[];
209
+ export declare const llmProfileStringDataKeys: ("provider" | "tokenPricing" | keyof import("./chatV2Shared.js").ChatV2CommonNodeData | "configurationMode" | "apiKeySource" | "providerApiKeyNames" | "customProviderApiKeyProgrammaticName" | "customProviderApiKeyEnvVarName" | "customProviderBaseURL" | "useCustomProviderBaseURLInput" | "customProviderApi" | "baseURL" | "useBaseURLInput" | "headers" | "useHeadersInput" | "extraProviderOptions" | "useExtraProviderOptionsInput" | "openAIReasoningEffort" | "openRouterReasoningEffort" | "openAIReasoningSummary" | "openAIPreviousResponseId" | "useOpenAIPreviousResponseIdInput" | "enableOpenAIWebSearch" | "openAIWebSearchContextSize" | "enableOpenAICodeInterpreter" | "anthropicThinkingMode" | "anthropicThinkingBudget" | "useAnthropicThinkingBudgetInput" | "anthropicEffort" | "anthropicCacheControlTtl" | "googleThinkingBudget" | "useGoogleThinkingBudgetInput" | "googleThinkingLevel" | "googleIncludeThoughts" | "enableGoogleSearchGrounding" | "enableGoogleUrlContext" | "enableCircuitBreaker" | "firstOutputTimeoutMs" | "streamInactivityTimeoutMs" | "circuitBreakerFailureThreshold" | "circuitBreakerFailureWindowMs" | "circuitBreakerOpenDurationMs" | "responseFormat" | "responseSchemaName" | "useResponseSchemaNameInput" | "responseSchemaDescription" | "useResponseSchemaDescriptionInput" | "toolChoice" | "toolChoiceFunction" | "parallelToolCalls" | "autoContinueToolCalls" | "maxToolRounds" | "retryOnNon200" | "errorOnNon200" | "catchRequestFailed" | "retryOnNon200RepeatTimes" | "retryOnNon200CooldownMs" | "outputLLMAttempts" | "outputRequestBody" | "outputResponseBody")[];
210
+ export declare const llmProfileBooleanDataKeys: ("provider" | "tokenPricing" | keyof import("./chatV2Shared.js").ChatV2CommonNodeData | "configurationMode" | "apiKeySource" | "providerApiKeyNames" | "customProviderApiKeyProgrammaticName" | "customProviderApiKeyEnvVarName" | "customProviderBaseURL" | "useCustomProviderBaseURLInput" | "customProviderApi" | "baseURL" | "useBaseURLInput" | "headers" | "useHeadersInput" | "extraProviderOptions" | "useExtraProviderOptionsInput" | "openAIReasoningEffort" | "openRouterReasoningEffort" | "openAIReasoningSummary" | "openAIPreviousResponseId" | "useOpenAIPreviousResponseIdInput" | "enableOpenAIWebSearch" | "openAIWebSearchContextSize" | "enableOpenAICodeInterpreter" | "anthropicThinkingMode" | "anthropicThinkingBudget" | "useAnthropicThinkingBudgetInput" | "anthropicEffort" | "anthropicCacheControlTtl" | "googleThinkingBudget" | "useGoogleThinkingBudgetInput" | "googleThinkingLevel" | "googleIncludeThoughts" | "enableGoogleSearchGrounding" | "enableGoogleUrlContext" | "enableCircuitBreaker" | "firstOutputTimeoutMs" | "streamInactivityTimeoutMs" | "circuitBreakerFailureThreshold" | "circuitBreakerFailureWindowMs" | "circuitBreakerOpenDurationMs" | "responseFormat" | "responseSchemaName" | "useResponseSchemaNameInput" | "responseSchemaDescription" | "useResponseSchemaDescriptionInput" | "toolChoice" | "toolChoiceFunction" | "parallelToolCalls" | "autoContinueToolCalls" | "maxToolRounds" | "retryOnNon200" | "errorOnNon200" | "catchRequestFailed" | "retryOnNon200RepeatTimes" | "retryOnNon200CooldownMs" | "outputLLMAttempts" | "outputRequestBody" | "outputResponseBody")[];
211
+ export declare const llmProfileRequiredNumberDataKeys: ("provider" | "tokenPricing" | keyof import("./chatV2Shared.js").ChatV2CommonNodeData | "configurationMode" | "apiKeySource" | "providerApiKeyNames" | "customProviderApiKeyProgrammaticName" | "customProviderApiKeyEnvVarName" | "customProviderBaseURL" | "useCustomProviderBaseURLInput" | "customProviderApi" | "baseURL" | "useBaseURLInput" | "headers" | "useHeadersInput" | "extraProviderOptions" | "useExtraProviderOptionsInput" | "openAIReasoningEffort" | "openRouterReasoningEffort" | "openAIReasoningSummary" | "openAIPreviousResponseId" | "useOpenAIPreviousResponseIdInput" | "enableOpenAIWebSearch" | "openAIWebSearchContextSize" | "enableOpenAICodeInterpreter" | "anthropicThinkingMode" | "anthropicThinkingBudget" | "useAnthropicThinkingBudgetInput" | "anthropicEffort" | "anthropicCacheControlTtl" | "googleThinkingBudget" | "useGoogleThinkingBudgetInput" | "googleThinkingLevel" | "googleIncludeThoughts" | "enableGoogleSearchGrounding" | "enableGoogleUrlContext" | "enableCircuitBreaker" | "firstOutputTimeoutMs" | "streamInactivityTimeoutMs" | "circuitBreakerFailureThreshold" | "circuitBreakerFailureWindowMs" | "circuitBreakerOpenDurationMs" | "responseFormat" | "responseSchemaName" | "useResponseSchemaNameInput" | "responseSchemaDescription" | "useResponseSchemaDescriptionInput" | "toolChoice" | "toolChoiceFunction" | "parallelToolCalls" | "autoContinueToolCalls" | "maxToolRounds" | "retryOnNon200" | "errorOnNon200" | "catchRequestFailed" | "retryOnNon200RepeatTimes" | "retryOnNon200CooldownMs" | "outputLLMAttempts" | "outputRequestBody" | "outputResponseBody")[];
212
+ export declare const llmProfileOptionalNumberDataKeys: ("provider" | "tokenPricing" | keyof import("./chatV2Shared.js").ChatV2CommonNodeData | "configurationMode" | "apiKeySource" | "providerApiKeyNames" | "customProviderApiKeyProgrammaticName" | "customProviderApiKeyEnvVarName" | "customProviderBaseURL" | "useCustomProviderBaseURLInput" | "customProviderApi" | "baseURL" | "useBaseURLInput" | "headers" | "useHeadersInput" | "extraProviderOptions" | "useExtraProviderOptionsInput" | "openAIReasoningEffort" | "openRouterReasoningEffort" | "openAIReasoningSummary" | "openAIPreviousResponseId" | "useOpenAIPreviousResponseIdInput" | "enableOpenAIWebSearch" | "openAIWebSearchContextSize" | "enableOpenAICodeInterpreter" | "anthropicThinkingMode" | "anthropicThinkingBudget" | "useAnthropicThinkingBudgetInput" | "anthropicEffort" | "anthropicCacheControlTtl" | "googleThinkingBudget" | "useGoogleThinkingBudgetInput" | "googleThinkingLevel" | "googleIncludeThoughts" | "enableGoogleSearchGrounding" | "enableGoogleUrlContext" | "enableCircuitBreaker" | "firstOutputTimeoutMs" | "streamInactivityTimeoutMs" | "circuitBreakerFailureThreshold" | "circuitBreakerFailureWindowMs" | "circuitBreakerOpenDurationMs" | "responseFormat" | "responseSchemaName" | "useResponseSchemaNameInput" | "responseSchemaDescription" | "useResponseSchemaDescriptionInput" | "toolChoice" | "toolChoiceFunction" | "parallelToolCalls" | "autoContinueToolCalls" | "maxToolRounds" | "retryOnNon200" | "errorOnNon200" | "catchRequestFailed" | "retryOnNon200RepeatTimes" | "retryOnNon200CooldownMs" | "outputLLMAttempts" | "outputRequestBody" | "outputResponseBody")[];
211
213
  /** A serialized profile must be self-contained, not driven by hidden ports. */
212
214
  export declare const llmProfileResolvedInputToggleDataKeys: Array<keyof LLMChatV2NodeData>;
@@ -1,4 +1,5 @@
1
1
  import type { ChatV2Provider } from './chatV2Types.js';
2
+ import { type TokenPricing } from '../tokenPricing.js';
2
3
  export type ChatV2ModelInfo = {
3
4
  maxTokens: number;
4
5
  displayName: string;
@@ -9,6 +10,10 @@ export type ChatV2ModelInfo = {
9
10
  };
10
11
  };
11
12
  type TokenUsageForCost = {
13
+ inputTokenDetails?: {
14
+ cacheReadTokens?: number | undefined;
15
+ cacheWriteTokens?: number | undefined;
16
+ } | undefined;
12
17
  inputTokens?: number | undefined;
13
18
  outputTokens?: number | undefined;
14
19
  };
@@ -117,11 +122,12 @@ export declare function getChatV2ModelRegistry(): {
117
122
  custom: {};
118
123
  };
119
124
  export declare function getChatV2ModelInfo(provider: ChatV2Provider, modelId: string): ChatV2ModelInfo | undefined;
125
+ export declare function getChatV2SystemTokenPricing(provider: ChatV2Provider, modelId: string): TokenPricing | undefined;
120
126
  export declare function calculateChatV2Cost(provider: ChatV2Provider, modelId: string, promptTokens: number, completionTokens: number): number | undefined;
121
127
  /**
122
128
  * Uses reported OpenRouter cost; estimates other providers only when both
123
129
  * billable text-token counts are available. Cache discounts, long-context
124
130
  * premiums, and provider tool fees are not modeled in those estimates.
125
131
  */
126
- export declare function calculateChatV2UsageCost(provider: ChatV2Provider, modelId: string, usage: TokenUsageForCost | undefined, providerMetadata?: Record<string, Record<string, unknown>>): number | undefined;
132
+ export declare function calculateChatV2UsageCost(provider: ChatV2Provider, modelId: string, usage: TokenUsageForCost | undefined, providerMetadata?: Record<string, Record<string, unknown>>, tokenPricing?: TokenPricing): number | undefined;
127
133
  export {};
@@ -1,3 +1,4 @@
1
+ import { type TokenPricing } from '../tokenPricing.js';
1
2
  import type { NodeId } from '../NodeBase.js';
2
3
  import type { ProjectId } from '../Project.js';
3
4
  import type { InternalProcessContext } from '../ProcessContext.js';
@@ -6,6 +7,7 @@ import { type ClassifierPreparationCheck } from './limits.js';
6
7
  import { type ClassifierApiKeySource, type ClassifierCredentialNames } from './credentials.js';
7
8
  import type { RivetLLMProfileCircuitBreakerPolicy, RivetLLMProfileHealthIdentity } from '../chat-v2/llmProfileHealthStore.js';
8
9
  export type ClassifierProfileConfiguration = {
10
+ tokenPricing?: TokenPricing;
9
11
  provider?: string;
10
12
  model?: string;
11
13
  useModelInput?: boolean;
@@ -36,7 +38,7 @@ export declare const DEFAULT_CLASSIFIER_PROFILE_FAILURE_THRESHOLD = 3;
36
38
  export declare const DEFAULT_CLASSIFIER_PROFILE_FAILURE_WINDOW_MS = 300000;
37
39
  export declare const DEFAULT_CLASSIFIER_PROFILE_OPEN_DURATION_MS = 300000;
38
40
  export declare const classifierProfileInputIds: readonly ["model", "apiKey"];
39
- export declare const classifierProfileDataKeys: readonly ["provider", "model", "useModelInput", "apiKeySource", "apiKeyNamesByProvider", "apiKeyNames", "responseTimeoutMs", "enableCircuitBreaker", "circuitBreakerFailureThreshold", "circuitBreakerFailureWindowMs", "circuitBreakerOpenDurationMs"];
41
+ export declare const classifierProfileDataKeys: readonly ["tokenPricing", "provider", "model", "useModelInput", "apiKeySource", "apiKeyNamesByProvider", "apiKeyNames", "responseTimeoutMs", "enableCircuitBreaker", "circuitBreakerFailureThreshold", "circuitBreakerFailureWindowMs", "circuitBreakerOpenDurationMs"];
40
42
  export declare function pickClassifierProfileData(data: ClassifierProfileConfiguration): ClassifierProfileConfiguration;
41
43
  export declare function classifierProfileResponseTimeout(configuration: ClassifierProfileConfiguration): number;
42
44
  export declare function classifierProfileHealthPolicy(configuration: ClassifierProfileConfiguration): RivetLLMProfileCircuitBreakerPolicy | undefined;
@@ -29,4 +29,5 @@ export declare function runClassifierProfiles(input: {
29
29
  result: ClassifierProviderEvaluationResult;
30
30
  provider: ReturnType<typeof getClassifierProvider>;
31
31
  model: string;
32
+ tokenPricing?: ClassifierProviderEvaluateArgs['tokenPricing'];
32
33
  }>;
@@ -1,4 +1,5 @@
1
1
  import type { ClassifierCredentialNames } from './credentials.js';
2
+ import { type TokenPricing } from '../tokenPricing.js';
2
3
  import type { DataValue } from '../DataValue.js';
3
4
  import { type ClassifierStateMessage, type PreparedClassifierState } from './state.js';
4
5
  import { validateClassifierEvaluationResponse } from './response.js';
@@ -74,6 +75,7 @@ export type ClassifierProviderEvaluationResult = {
74
75
  responseBody: Record<string, unknown>;
75
76
  };
76
77
  export type ClassifierProviderEvaluateArgs = {
78
+ tokenPricing?: TokenPricing;
77
79
  /** Privacy-bounded physical-attempt observer; never includes bodies or credentials. */
78
80
  onAttempt?: (attempt: {
79
81
  attemptIndex: number;
@@ -171,6 +173,7 @@ export declare class ClassifierProviderError extends Error {
171
173
  export declare function classifierFailureKind(kind: ClassifierProviderError['kind'], status?: number): ClassifierFailureKind;
172
174
  /** Bounded preparation/provider explanation, without traversing causes or capturing response bodies. */
173
175
  export declare function classifierErrorMessage(error: unknown, apiKey?: string): string;
176
+ export declare function getClassifierSystemTokenPricing(providerId: string | undefined, model?: string): ClassifierTokenPricing | undefined;
174
177
  export declare function getClassifierProvider(id: string | undefined): ClassifierProvider;
175
178
  export declare function getClassifierProviderEnvironmentVariableNames(): string[];
176
179
  /**
@@ -183,6 +186,6 @@ export declare function getClassifierProviderEnvironmentVariableNames(): string[
183
186
  export declare function calculateClassifierUsageCost(provider: Pick<ClassifierProvider, 'pricing' | 'modelPricing'> & Partial<Pick<ClassifierProvider, 'defaultModel'>>, usage: ClassifierEvaluationResponse['usage'], models?: {
184
187
  requestedModel: string;
185
188
  responseModel: string;
186
- }): number | undefined;
189
+ }, tokenPricing?: TokenPricing): number | undefined;
187
190
  export declare function normalizeClassifierNon200RetryCount(value: number | undefined): number;
188
191
  export declare function normalizeClassifierNon200RetryCooldownMs(value: number | undefined): number;
@@ -0,0 +1,18 @@
1
+ /** All rates are USD per one million tokens. Cache counts are subsets of inputTokens. */
2
+ export type TokenPricing = {
3
+ inputPerMillionTokens: number;
4
+ outputPerMillionTokens: number;
5
+ cacheReadPerMillionTokens?: number;
6
+ cacheWritePerMillionTokens?: number;
7
+ };
8
+ /** Provider token counts must be exact, nonnegative integers before applying rates. */
9
+ export declare function isReportedTokenCount(value: unknown): value is number;
10
+ export declare function validateTokenPricing(value: unknown): TokenPricing | undefined;
11
+ export declare function calculateTokenUsageCost(pricing: TokenPricing, usage: {
12
+ inputTokens?: number;
13
+ outputTokens?: number;
14
+ inputTokenDetails?: {
15
+ cacheReadTokens?: number;
16
+ cacheWriteTokens?: number;
17
+ };
18
+ } | undefined): number | undefined;
@@ -0,0 +1,4 @@
1
+ import type { EditorDefinitionGroup } from './EditorDefinition.js';
2
+ import type { ChartNode } from './NodeBase.js';
3
+ /** Shared settings section for inline configurations and separate profile nodes. */
4
+ export declare function getTokenPricingEditor<T extends ChartNode>(): EditorDefinitionGroup<T>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@valerypopoff/rivet2-core",
3
- "version": "2.24.0",
3
+ "version": "2.25.0",
4
4
  "license": "MIT",
5
5
  "main": "dist/cjs/bundle.cjs",
6
6
  "module": "dist/esm/index.js",