@valerypopoff/rivet2-core 2.24.0 → 2.26.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 (50) hide show
  1. package/dist/cjs/bundle.cjs +710 -197
  2. package/dist/cjs/bundle.cjs.map +4 -4
  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 +4 -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 +86 -4
  11. package/dist/esm/model/LatestDebuggerProtocol.js +156 -0
  12. package/dist/esm/model/Nodes.js +3 -0
  13. package/dist/esm/model/RunCostLedger.js +89 -0
  14. package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -2
  15. package/dist/esm/model/chat-v2/chatV2Outputs.js +1 -1
  16. package/dist/esm/model/chat-v2/chatV2Pipeline.js +5 -0
  17. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +3 -0
  18. package/dist/esm/model/chat-v2/llmModelCandidate.js +3 -0
  19. package/dist/esm/model/chat-v2/llmProfile.js +2 -0
  20. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +1 -0
  21. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +2 -1
  22. package/dist/esm/model/chat-v2/modelRegistry.js +12 -3
  23. package/dist/esm/model/classifier/profile.js +11 -3
  24. package/dist/esm/model/classifier/profileExecution.js +2 -1
  25. package/dist/esm/model/classifier/providers.js +25 -14
  26. package/dist/esm/model/nodes/AICostNode.js +56 -0
  27. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +16 -5
  28. package/dist/esm/model/nodes/ClassifierProfileNode.js +2 -0
  29. package/dist/esm/model/tokenPricing.js +52 -0
  30. package/dist/esm/model/tokenPricingEditor.js +9 -0
  31. package/dist/types/exports.d.ts +4 -0
  32. package/dist/types/model/DatasetOwnership.d.ts +5 -0
  33. package/dist/types/model/GraphExecutionState.d.ts +3 -0
  34. package/dist/types/model/GraphProcessor.d.ts +3 -0
  35. package/dist/types/model/LatestDebuggerProtocol.d.ts +113 -0
  36. package/dist/types/model/Nodes.d.ts +3 -2
  37. package/dist/types/model/ProcessContext.d.ts +3 -0
  38. package/dist/types/model/RunCostLedger.d.ts +29 -0
  39. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +1 -1
  40. package/dist/types/model/chat-v2/chatV2Types.d.ts +2 -0
  41. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +3 -1
  42. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +7 -5
  43. package/dist/types/model/chat-v2/modelRegistry.d.ts +7 -1
  44. package/dist/types/model/classifier/profile.d.ts +3 -1
  45. package/dist/types/model/classifier/profileExecution.d.ts +1 -0
  46. package/dist/types/model/classifier/providers.d.ts +4 -1
  47. package/dist/types/model/nodes/AICostNode.d.ts +15 -0
  48. package/dist/types/model/tokenPricing.d.ts +18 -0
  49. package/dist/types/model/tokenPricingEditor.d.ts +4 -0
  50. package/package.json +1 -1
@@ -1,6 +1,7 @@
1
1
  import { anthropicModels } from '../../plugins/anthropic/anthropic.js';
2
2
  import { generativeAiGoogleModels } from '../../plugins/google/google.js';
3
3
  import { openaiModels } from '../../utils/openai.js';
4
+ import { calculateTokenUsageCost, isReportedTokenCount } from '../tokenPricing.js';
4
5
  const TOKENS_PER_THOUSAND = 1_000;
5
6
  function isFiniteNonNegative(value) {
6
7
  return typeof value === 'number' && Number.isFinite(value) && value >= 0;
@@ -55,9 +56,15 @@ export function getChatV2ModelInfo(provider, modelId) {
55
56
  const providerModels = chatV2ModelRegistry[provider];
56
57
  return providerModels[modelId];
57
58
  }
59
+ export function getChatV2SystemTokenPricing(provider, modelId) {
60
+ const cost = getChatV2ModelInfo(provider, modelId.trim())?.cost;
61
+ return cost == null
62
+ ? undefined
63
+ : { inputPerMillionTokens: cost.prompt * 1_000_000, outputPerMillionTokens: cost.completion * 1_000_000 };
64
+ }
58
65
  export function calculateChatV2Cost(provider, modelId, promptTokens, completionTokens) {
59
66
  const model = getChatV2ModelInfo(provider, modelId);
60
- if (model?.cost == null || !isFiniteNonNegative(promptTokens) || !isFiniteNonNegative(completionTokens)) {
67
+ if (model?.cost == null || !isReportedTokenCount(promptTokens) || !isReportedTokenCount(completionTokens)) {
61
68
  return undefined;
62
69
  }
63
70
  const cost = model.cost.prompt * promptTokens + model.cost.completion * completionTokens;
@@ -68,7 +75,9 @@ export function calculateChatV2Cost(provider, modelId, promptTokens, completionT
68
75
  * billable text-token counts are available. Cache discounts, long-context
69
76
  * premiums, and provider tool fees are not modeled in those estimates.
70
77
  */
71
- export function calculateChatV2UsageCost(provider, modelId, usage, providerMetadata) {
78
+ export function calculateChatV2UsageCost(provider, modelId, usage, providerMetadata, tokenPricing) {
79
+ if (tokenPricing !== undefined)
80
+ return calculateTokenUsageCost(tokenPricing, usage);
72
81
  if (provider === 'openrouter') {
73
82
  const reportedUsage = providerMetadata?.openrouter?.usage;
74
83
  const cost = reportedUsage != null && typeof reportedUsage === 'object'
@@ -76,7 +85,7 @@ export function calculateChatV2UsageCost(provider, modelId, usage, providerMetad
76
85
  : undefined;
77
86
  return isFiniteNonNegative(cost) ? cost : undefined;
78
87
  }
79
- if (!isFiniteNonNegative(usage?.inputTokens) || !isFiniteNonNegative(usage.outputTokens)) {
88
+ if (usage?.inputTokens == null || usage.outputTokens == null) {
80
89
  return undefined;
81
90
  }
82
91
  return calculateChatV2Cost(provider, modelId, usage.inputTokens, usage.outputTokens);
@@ -1,4 +1,5 @@
1
1
  import CryptoJS from 'crypto-js';
2
+ import { validateTokenPricing } from '../tokenPricing.js';
2
3
  import stableStringify from 'safe-stable-stringify';
3
4
  import { classifierInputDataValue, snapshotClassifierJson } from './json.js';
4
5
  import { ClassifierValueBudget } from './limits.js';
@@ -10,6 +11,7 @@ export const DEFAULT_CLASSIFIER_PROFILE_FAILURE_WINDOW_MS = 300_000;
10
11
  export const DEFAULT_CLASSIFIER_PROFILE_OPEN_DURATION_MS = 300_000;
11
12
  export const classifierProfileInputIds = ['model', 'apiKey'];
12
13
  export const classifierProfileDataKeys = [
14
+ 'tokenPricing',
13
15
  'provider',
14
16
  'model',
15
17
  'useModelInput',
@@ -77,11 +79,12 @@ function normalizeDetachedProfile(value) {
77
79
  throw new Error('Unknown Decision AI API key source.');
78
80
  classifierProfileResponseTimeout(configuration);
79
81
  classifierProfileHealthPolicy(configuration);
82
+ configuration.tokenPricing = validateTokenPricing(configuration.tokenPricing);
80
83
  return {
81
84
  version: 1,
82
- sourceNodeId: profile.sourceNodeId,
85
+ ...(profile.sourceNodeId === undefined ? {} : { sourceNodeId: profile.sourceNodeId }),
83
86
  // Blank names are absent, but authored whitespace must survive exact-default display aliases.
84
- profileName: profile.profileName?.trim() ? profile.profileName : undefined,
87
+ ...(profile.profileName?.trim() ? { profileName: profile.profileName } : {}),
85
88
  credential: credential.value === undefined ? {} : { value: credential.value.trim() },
86
89
  configuration: {
87
90
  ...pickClassifierProfileData(configuration),
@@ -125,7 +128,12 @@ export function resolveClassifierProfile(data, inputs, context) {
125
128
  }
126
129
  return normalizeClassifierProfileValue({
127
130
  version: 1,
128
- configuration: { ...pickClassifierProfileData(data), provider: provider.id, model, useModelInput: false },
131
+ configuration: {
132
+ ...pickClassifierProfileData({ ...data, tokenPricing: validateTokenPricing(data.tokenPricing) }),
133
+ provider: provider.id,
134
+ model,
135
+ useModelInput: false,
136
+ },
129
137
  credential: value === undefined ? {} : { value },
130
138
  profileName: context.node.title,
131
139
  sourceNodeId: context.node.id,
@@ -190,6 +190,7 @@ export async function runClassifierProfiles(input) {
190
190
  ...input.state,
191
191
  questions: input.questions,
192
192
  apiKey: profile.credential.value,
193
+ tokenPricing: profile.configuration.tokenPricing,
193
194
  model,
194
195
  ...(Number.isFinite(timeoutMs) ? { timeoutMs } : {}),
195
196
  deadline: input.deadline,
@@ -231,7 +232,7 @@ export async function runClassifierProfiles(input) {
231
232
  skipReason: 'unreached',
232
233
  });
233
234
  }
234
- return { result, provider, model };
235
+ return { result, provider, model, tokenPricing: profile.configuration.tokenPricing };
235
236
  }
236
237
  catch (error) {
237
238
  lastError = error;
@@ -1,3 +1,4 @@
1
+ import { calculateTokenUsageCost, isReportedTokenCount, validateTokenPricing, } from '../tokenPricing.js';
1
2
  import { JEV_DEFAULT_CREDENTIAL_NAMES, LIQUID_DEFAULT_CREDENTIAL_NAMES, OPENAI_DEFAULT_CREDENTIAL_NAMES, OPENROUTER_DEFAULT_CREDENTIAL_NAMES, PERPLEXITY_DEFAULT_CREDENTIAL_NAMES, SUBQ_DEFAULT_CREDENTIAL_NAMES, BASETEN_DEFAULT_CREDENTIAL_NAMES, } from './credentials.js';
2
3
  import { assertLiquidImageLimits } from './images.js';
3
4
  import { prepareClassifierState, inspectStateMessages, systemOneState, } from './state.js';
@@ -271,7 +272,11 @@ function createClassifierProvider(spec) {
271
272
  // discard non-enumerable/inherited content.
272
273
  if ('images' in input)
273
274
  throw new Error('Pass image evidence through State, not a separate images field.');
274
- const args = { ...input, fetchImplementation: input.fetchImplementation ?? fetch };
275
+ const args = {
276
+ ...input,
277
+ tokenPricing: validateTokenPricing(input.tokenPricing),
278
+ fetchImplementation: input.fetchImplementation ?? fetch,
279
+ };
275
280
  const operation = createOperation(args, provider.label);
276
281
  operation.check();
277
282
  if (typeof args.model !== 'string')
@@ -334,6 +339,11 @@ function normalizeModelPricing(provider) {
334
339
  return (provider.modelPricing ??
335
340
  (provider.pricing && provider.defaultModel ? [{ models: [provider.defaultModel], pricing: provider.pricing }] : []));
336
341
  }
342
+ export function getClassifierSystemTokenPricing(providerId, model) {
343
+ const provider = getClassifierProvider(providerId);
344
+ return normalizeModelPricing(provider).find((entry) => entry.models.includes(model?.trim() || provider.defaultModel))
345
+ ?.pricing;
346
+ }
337
347
  export function getClassifierProvider(id) {
338
348
  const provider = classifierProviders.find((candidate) => candidate.id === (id || jevClassifierProvider.id));
339
349
  if (!provider)
@@ -350,7 +360,12 @@ export function getClassifierProviderEnvironmentVariableNames() {
350
360
  * count or add image tokens again. Decisions has no separate cache charges.
351
361
  * Callers must not treat an unpriced provider as free.
352
362
  */
353
- export function calculateClassifierUsageCost(provider, usage, models) {
363
+ export function calculateClassifierUsageCost(provider, usage, models, tokenPricing) {
364
+ if (tokenPricing !== undefined)
365
+ return calculateTokenUsageCost(tokenPricing, {
366
+ inputTokens: usage.input_tokens,
367
+ outputTokens: usage.output_tokens,
368
+ });
354
369
  if (!models)
355
370
  return undefined;
356
371
  const entries = normalizeModelPricing(provider);
@@ -365,10 +380,8 @@ export function calculateClassifierUsageCost(provider, usage, models) {
365
380
  !validRates(base) ||
366
381
  (tier != null &&
367
382
  (!Number.isSafeInteger(tier.aboveInputTokens) || tier.aboveInputTokens < 0 || !validRates(tier))) ||
368
- !Number.isSafeInteger(usage.input_tokens) ||
369
- usage.input_tokens < 0 ||
370
- !Number.isSafeInteger(usage.output_tokens) ||
371
- usage.output_tokens < 0) {
383
+ !isReportedTokenCount(usage.input_tokens) ||
384
+ !isReportedTokenCount(usage.output_tokens)) {
372
385
  return undefined;
373
386
  }
374
387
  const pricing = tier && usage.input_tokens > tier.aboveInputTokens ? tier : base;
@@ -571,10 +584,10 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
571
584
  validatedResponse = validateResponse(body, prepared.questions, providerLabel);
572
585
  }
573
586
  catch (error) {
574
- report('failure', response.status, 'response-validation', classifierAttemptUsage(body, spec, args.model), error instanceof Error ? error.message : `${providerLabel} returned an invalid Decision AI response.`);
587
+ report('failure', response.status, 'response-validation', classifierAttemptUsage(body, spec, args.model, args.tokenPricing), error instanceof Error ? error.message : `${providerLabel} returned an invalid Decision AI response.`);
575
588
  throw new ClassifierProviderError(error instanceof Error ? error.message : `${providerLabel} returned an invalid Decision AI response.`, 'response-validation', undefined, { cause: error });
576
589
  }
577
- report('success', response.status, undefined, classifierAttemptUsage(body, spec, args.model));
590
+ report('success', response.status, undefined, classifierAttemptUsage(body, spec, args.model, args.tokenPricing));
578
591
  return {
579
592
  // Preserve the direct-provider result contract, but graph runs with the
580
593
  // diagnostic disabled never allocate this second representation.
@@ -592,7 +605,7 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
592
605
  }
593
606
  }
594
607
  /** The bounded reader produced plain JSON; do not require valid answers to retain usable usage. */
595
- function classifierAttemptUsage(body, provider, requestedModel) {
608
+ function classifierAttemptUsage(body, provider, requestedModel, tokenPricing) {
596
609
  if (!body || typeof body !== 'object' || Array.isArray(body) || !Object.hasOwn(body, 'usage'))
597
610
  return;
598
611
  const { usage, model } = body;
@@ -601,13 +614,11 @@ function classifierAttemptUsage(body, provider, requestedModel) {
601
614
  Array.isArray(usage) ||
602
615
  !Object.hasOwn(usage, 'input_tokens') ||
603
616
  !Object.hasOwn(usage, 'output_tokens') ||
604
- !Number.isSafeInteger(usage.input_tokens) ||
605
- usage.input_tokens < 0 ||
606
- !Number.isSafeInteger(usage.output_tokens) ||
607
- usage.output_tokens < 0)
617
+ !isReportedTokenCount(usage.input_tokens) ||
618
+ !isReportedTokenCount(usage.output_tokens))
608
619
  return;
609
620
  const estimatedCostUsd = typeof model === 'string' && Object.hasOwn(body, 'model')
610
- ? calculateClassifierUsageCost(provider, usage, { requestedModel, responseModel: model })
621
+ ? calculateClassifierUsageCost(provider, usage, { requestedModel, responseModel: model }, tokenPricing)
611
622
  : undefined;
612
623
  return {
613
624
  inputTokens: usage.input_tokens,
@@ -0,0 +1,56 @@
1
+ import { nanoid } from 'nanoid/non-secure';
2
+ import { NodeImpl } from '../NodeImpl.js';
3
+ import { nodeDefinition } from '../NodeDefinition.js';
4
+ import { addWarning } from '../../utils/outputs.js';
5
+ export class AICostNodeImpl extends NodeImpl {
6
+ static create() {
7
+ return {
8
+ type: 'aiCost',
9
+ title: 'AI Cost',
10
+ id: nanoid(),
11
+ visualData: { x: 0, y: 0, width: 250 },
12
+ data: {},
13
+ };
14
+ }
15
+ getInputDefinitions() {
16
+ return [];
17
+ }
18
+ getOutputDefinitions() {
19
+ return [
20
+ { id: 'llmCost', title: 'LLM cost', dataType: 'number' },
21
+ { id: 'decisionAICost', title: 'Decision AI cost', dataType: 'number' },
22
+ { id: 'totalCost', title: 'Sum cost', dataType: 'number' },
23
+ ];
24
+ }
25
+ static getUIData() {
26
+ return {
27
+ contextMenuTitle: 'AI Cost',
28
+ infoBoxTitle: 'AI Cost',
29
+ group: ['Debug'],
30
+ infoBoxBody: 'Returns observed AI cost estimates in USD for the current project invocation and projects it calls, excluding callers and sibling invocations. Uses the same accounting as Run statistics. Enable Conditional node to control when it runs; use Did Run to wait for multiple branches. In-flight and future calls are not yet included; unknown prices are not free.',
31
+ };
32
+ }
33
+ getBody() {
34
+ return 'Observed AI estimates (USD)\nCurrent project subtree';
35
+ }
36
+ getRunActivityDescriptor() {
37
+ return { primaryOutputPortId: 'totalCost' };
38
+ }
39
+ async process(_inputs, context) {
40
+ if (!context.getRunCostBreakdown)
41
+ throw new Error('AI Cost accounting is unavailable in this execution environment.');
42
+ const costs = context.getRunCostBreakdown();
43
+ const value = (cost) => cost.knownCostUsd === null
44
+ ? { type: 'control-flow-excluded', value: undefined }
45
+ : { type: 'number', value: cost.knownCostUsd };
46
+ const outputs = {
47
+ ['llmCost']: value(costs.llm),
48
+ ['decisionAICost']: value(costs.decisionAI),
49
+ ['totalCost']: value(costs.total),
50
+ };
51
+ if (costs.total.status !== 'complete')
52
+ addWarning(outputs, 'Some observed AI costs are unknown. Numeric outputs are known subtotals; unavailable amounts are not zero.');
53
+ return outputs;
54
+ }
55
+ }
56
+ export const aiCostNode = nodeDefinition(AICostNodeImpl, 'AI Cost');
@@ -8,6 +8,8 @@ import { getNextVariadicPortIndex } from './variadicPortIndex.js';
8
8
  import { resolveClassifierApiKey } from '../classifier/credentials.js';
9
9
  import { classifierArrayValues, classifierInputDataValue } from '../classifier/json.js';
10
10
  import { normalizeClassifierState } from '../classifier/state.js';
11
+ import { validateTokenPricing } from '../tokenPricing.js';
12
+ import { getTokenPricingEditor } from '../tokenPricingEditor.js';
11
13
  import { CLASSIFIER_LIMITS, ClassifierValueBudget } from '../classifier/limits.js';
12
14
  import { calculateClassifierUsageCost, classifierFailureKind, classifierProviders, DEFAULT_CLASSIFIER_RETRY_ON_NON_200_COOLDOWN_MS, DEFAULT_CLASSIFIER_RETRY_ON_NON_200_REPEAT_TIMES, getClassifierProvider, normalizeClassifierNon200RetryCooldownMs, normalizeClassifierNon200RetryCount, } from '../classifier/providers.js';
13
15
  import { normalizeClassifierProfiles } from '../classifier/profile.js';
@@ -112,6 +114,10 @@ export class ClassifierEvaluateNodeImpl extends NodeImpl {
112
114
  return [
113
115
  { type: 'custom', label: 'Configuration', customEditorId: 'ClassifierConfiguration' },
114
116
  { ...getClassifierModelEditor(), hideIf: (data) => data.configurationMode === 'profile' },
117
+ {
118
+ ...getTokenPricingEditor(),
119
+ hideIf: (data) => data.configurationMode === 'profile',
120
+ },
115
121
  {
116
122
  type: 'group',
117
123
  label: 'Outputs',
@@ -120,7 +126,7 @@ export class ClassifierEvaluateNodeImpl extends NodeImpl {
120
126
  type: 'toggle',
121
127
  label: 'Usage details',
122
128
  dataKey: 'outputUsage',
123
- helperMessage: 'Adds estimated totalCost to Usage only for recognized requested/returned models. Unknown pricing is omitted. Provider-specific premiums are not included.',
129
+ helperMessage: 'Adds estimated totalCost to Usage using explicit token prices or known model rates. Unknown pricing is omitted. Provider-specific premiums are not included.',
124
130
  },
125
131
  {
126
132
  type: 'toggle',
@@ -288,6 +294,7 @@ export class ClassifierEvaluateNodeImpl extends NodeImpl {
288
294
  checkPreparation();
289
295
  if (this.data.configurationMode === 'profile')
290
296
  return this.processProfiles(inputs, context, checkPreparation, attempts, diagnostics);
297
+ const tokenPricing = validateTokenPricing(this.data.tokenPricing);
291
298
  const provider = getClassifierProvider(this.data.provider);
292
299
  if (!provider.browserExecutionSupported && context.executor === 'browser') {
293
300
  throw new Error(`${provider.label} cannot run in the Browser executor. Select the Node executor, or run through Studio Server or remote debugging.`);
@@ -337,6 +344,7 @@ export class ClassifierEvaluateNodeImpl extends NodeImpl {
337
344
  throw new Error('Decision AI run requires at least one question.');
338
345
  const result = await (provider.evaluateInput ?? provider.evaluate).call(provider, {
339
346
  apiKey,
347
+ tokenPricing,
340
348
  model: modelValue,
341
349
  questions,
342
350
  retryOnNon200: this.data.retryOnNon200,
@@ -367,13 +375,16 @@ export class ClassifierEvaluateNodeImpl extends NodeImpl {
367
375
  });
368
376
  // Custom providers own their transport; caller cancellation still wins.
369
377
  checkPreparation();
370
- return { ...this.projectResult(provider, modelValue, result, checkPreparation), ...this.profileEvidence(attempts) };
378
+ return {
379
+ ...this.projectResult(provider, modelValue, result, checkPreparation, tokenPricing),
380
+ ...this.profileEvidence(attempts),
381
+ };
371
382
  }
372
- projectResult(provider, modelValue, result, checkPreparation) {
383
+ projectResult(provider, modelValue, result, checkPreparation, tokenPricing) {
373
384
  const totalCost = calculateClassifierUsageCost(provider, result.response.usage, {
374
385
  requestedModel: modelValue,
375
386
  responseModel: result.response.model,
376
- });
387
+ }, tokenPricing);
377
388
  // The provider's parsed response may also be exposed verbatim through the
378
389
  // diagnostic output. Do not mutate its Usage object while adding Rivet's
379
390
  // calculated accounting detail.
@@ -457,7 +468,7 @@ export class ClassifierEvaluateNodeImpl extends NodeImpl {
457
468
  });
458
469
  check();
459
470
  return {
460
- ...this.projectResult(selected.provider, selected.model, selected.result, check),
471
+ ...this.projectResult(selected.provider, selected.model, selected.result, check, selected.tokenPricing),
461
472
  ...this.profileEvidence(attempts, classifierProfileSummary(profiles, attempts)),
462
473
  };
463
474
  }
@@ -5,6 +5,7 @@ import { resolveClassifierProfile, DEFAULT_CLASSIFIER_PROFILE_RESPONSE_TIMEOUT_M
5
5
  import { getClassifierModelEditor, getClassifierEvaluateBodySections } from './ClassifierEvaluateNode.js';
6
6
  import { formatNodeBodyMarkdownField } from '../nodeBodyMarkdown.js';
7
7
  import { profileSuspensionHints } from '../profileSuspensionHints.js';
8
+ import { getTokenPricingEditor } from '../tokenPricingEditor.js';
8
9
  export class ClassifierProfileNodeImpl extends NodeImpl {
9
10
  static create() {
10
11
  return {
@@ -38,6 +39,7 @@ export class ClassifierProfileNodeImpl extends NodeImpl {
38
39
  getEditors() {
39
40
  return [
40
41
  getClassifierModelEditor(),
42
+ getTokenPricingEditor(),
41
43
  {
42
44
  type: 'group',
43
45
  label: 'Decision AI profile suspension',
@@ -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';
@@ -86,3 +89,4 @@ export { scanInterpolationTokenSpans } from './utils/interpolationSyntax.js';
86
89
  export { WarningsPort } from './utils/symbols.js';
87
90
  import * as openai from './utils/openai.js';
88
91
  export { openai };
92
+ export * from './model/LatestDebuggerProtocol.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>;
@@ -55,6 +57,7 @@ export declare class GraphInvocationState {
55
57
  createAbortController: () => AbortController;
56
58
  loadedProjects: Record<ProjectId, Project>;
57
59
  sharedOverride?: Pick<GraphInvocationState, 'graphOutputs' | 'attachedNodeData' | 'graphInputNodeValues'>;
60
+ costLedger?: RunCostLedger;
58
61
  }): void;
59
62
  }
60
63
  /** Shared by every child kind; retained caches/globals deliberately keep existing reuse semantics. */
@@ -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,113 @@
1
+ import type { ProcessEventMessageMap } from './ExecutorProtocol.js';
2
+ /** Managed latest-debugger routing labels are not credentials. */
3
+ export type LatestDebuggerChannel = string | null;
4
+ export type LatestDebuggerTarget = {
5
+ rootRunId: string;
6
+ projectId: string;
7
+ owner: string;
8
+ incarnation: string;
9
+ };
10
+ export type LatestDebuggerScope = LatestDebuggerTarget & {
11
+ channel: LatestDebuggerChannel;
12
+ promptId?: string;
13
+ admittedAt?: number;
14
+ /** This owner emits authoritative prompt closure in the same ordered stream. */
15
+ promptLifecycle?: 1;
16
+ };
17
+ export type LatestDebuggerPromptClosedMessage = {
18
+ message: 'latest-prompt-closed';
19
+ rivetScope: LatestDebuggerScope;
20
+ data: {
21
+ promptId: string;
22
+ };
23
+ };
24
+ export type LatestDebuggerPrompt = {
25
+ target: LatestDebuggerScope;
26
+ promptId: string;
27
+ };
28
+ export type LatestDebuggerSessionMessage = {
29
+ message: 'latest-session';
30
+ data: {
31
+ protocol: 2;
32
+ channel: LatestDebuggerChannel;
33
+ channelIsolation: true;
34
+ runScopedControls: true;
35
+ };
36
+ };
37
+ export type LatestDebuggerControlMessage = {
38
+ type: 'latest-control';
39
+ data: {
40
+ commandId: string;
41
+ target: LatestDebuggerScope;
42
+ } & ({
43
+ action: 'pause' | 'resume' | 'abort';
44
+ } | {
45
+ action: 'user-input';
46
+ promptId: string;
47
+ answers: {
48
+ type: 'string[]';
49
+ value: string[];
50
+ };
51
+ });
52
+ };
53
+ export type LatestDebuggerControlResult = {
54
+ status: 'accepted' | 'rejected' | 'outcome-unknown';
55
+ reason?: string;
56
+ };
57
+ export type LatestDebuggerControlResultMessage = {
58
+ message: 'latest-control-result';
59
+ data: LatestDebuggerControlResult & {
60
+ commandId: string;
61
+ };
62
+ };
63
+ export type LatestDebuggerSettledMessage = {
64
+ message: 'latest-settled';
65
+ rivetScope: LatestDebuggerScope;
66
+ data: Record<string, never>;
67
+ };
68
+ export type LatestDebuggerLifecycleMessage = LatestDebuggerPromptClosedMessage | LatestDebuggerSettledMessage;
69
+ export type LatestDebuggerProcessMessage = {
70
+ [K in keyof ProcessEventMessageMap]: {
71
+ message: K;
72
+ data: ProcessEventMessageMap[K];
73
+ rivetScope: LatestDebuggerScope;
74
+ };
75
+ }[keyof ProcessEventMessageMap];
76
+ export type LatestDebuggerExecutionMessage = (LatestDebuggerProcessMessage | LatestDebuggerLifecycleMessage) & {
77
+ rivetEventId?: string;
78
+ };
79
+ declare const diagnosticCodes: readonly ["history-truncated", "history-gap", "event-too-large", "owner-unavailable"];
80
+ export type LatestDebuggerDiagnosticCode = (typeof diagnosticCodes)[number];
81
+ export type LatestDebuggerDiagnosticMessage = {
82
+ message: 'latest-diagnostic';
83
+ data: {
84
+ protocol: 1;
85
+ code: LatestDebuggerDiagnosticCode;
86
+ };
87
+ };
88
+ export type LatestDebuggerServerMessage = LatestDebuggerSessionMessage | LatestDebuggerExecutionMessage | LatestDebuggerDiagnosticMessage | LatestDebuggerControlResultMessage;
89
+ export type LatestDebuggerMessage = LatestDebuggerServerMessage | LatestDebuggerControlMessage;
90
+ export declare const LATEST_DEBUGGER_PATH = "/ws/latest-debugger";
91
+ export declare function isLatestDebuggerExecutionMessage(message: string): boolean;
92
+ /** Preserve historical writer ordering while readers accept arbitrary JSON ordering. */
93
+ export declare function encodeLatestDebuggerEnvelope(serialized: string, scope?: LatestDebuggerScope, eventId?: string): string;
94
+ export declare function createLatestDebuggerSession(channel: LatestDebuggerChannel): LatestDebuggerSessionMessage;
95
+ export declare function isLatestDebuggerSession(value: unknown): value is LatestDebuggerSessionMessage;
96
+ /** Validate the routing contract only. Authored data and decoded sentinels stay intact. */
97
+ export declare function readLatestDebuggerExecution(value: unknown): LatestDebuggerExecutionMessage | undefined;
98
+ export declare function createLatestDebuggerDiagnostic(code: LatestDebuggerDiagnosticCode): LatestDebuggerDiagnosticMessage;
99
+ export declare function isLatestDebuggerDiagnostic(value: unknown): value is LatestDebuggerDiagnosticMessage;
100
+ export declare function createLatestDebuggerControlResult(commandId: string, result: LatestDebuggerControlResult): LatestDebuggerControlResultMessage;
101
+ /** Validate only the wire control contract, never authored graph payloads. */
102
+ export declare function readLatestDebuggerControl(value: unknown): LatestDebuggerControlMessage | undefined;
103
+ export declare function readLatestDebuggerEventId(value: unknown): string | undefined;
104
+ export declare function isLatestDebuggerControlResult(value: unknown): value is LatestDebuggerControlResultMessage;
105
+ /** Input is a decoded single path segment. Never decode it again. */
106
+ export declare function parseLatestEndpointSegment(segment: string): {
107
+ endpointName: string;
108
+ channel: LatestDebuggerChannel;
109
+ };
110
+ /** URL.pathname is still encoded. Decode exactly once, rejecting path separators. */
111
+ export declare function parseLatestDebuggerPath(pathname: string): LatestDebuggerChannel;
112
+ export declare function isLatestDebuggerScope(value: unknown): value is LatestDebuggerScope;
113
+ export {};