@valerypopoff/rivet2-core 2.22.1 → 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 (80) hide show
  1. package/dist/cjs/bundle.cjs +1438 -824
  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/cjs/webAppRuntime.cjs +4 -1
  8. package/dist/cjs/webAppRuntime.cjs.map +2 -2
  9. package/dist/esm/exports.js +3 -1
  10. package/dist/esm/index.js +3 -0
  11. package/dist/esm/integrations/CodeRunner.js +6 -3
  12. package/dist/esm/integrations/CodeRunnerNamespace.js +10 -0
  13. package/dist/esm/model/AgentResponseTracePresentation.js +5 -1
  14. package/dist/esm/model/ChildInvocationOwnership.js +51 -0
  15. package/dist/esm/model/DatasetOwnership.js +9 -0
  16. package/dist/esm/model/GraphExecutionState.js +3 -0
  17. package/dist/esm/model/GraphProcessor.js +94 -55
  18. package/dist/esm/model/NodeRegistration.js +2 -6
  19. package/dist/esm/model/RunCostLedger.js +58 -0
  20. package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -2
  21. package/dist/esm/model/chat-v2/chatV2Outputs.js +1 -1
  22. package/dist/esm/model/chat-v2/chatV2Pipeline.js +5 -0
  23. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +3 -0
  24. package/dist/esm/model/chat-v2/llmModelCandidate.js +3 -0
  25. package/dist/esm/model/chat-v2/llmProfile.js +2 -0
  26. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +1 -0
  27. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +2 -1
  28. package/dist/esm/model/chat-v2/modelRegistry.js +12 -3
  29. package/dist/esm/model/classifier/baseten.js +78 -0
  30. package/dist/esm/model/classifier/credentials.js +17 -9
  31. package/dist/esm/model/classifier/images.js +4 -4
  32. package/dist/esm/model/classifier/jev.js +45 -0
  33. package/dist/esm/model/classifier/json.js +1 -1
  34. package/dist/esm/model/classifier/limits.js +13 -13
  35. package/dist/esm/model/classifier/openai.js +20 -2
  36. package/dist/esm/model/classifier/preparation.js +5 -5
  37. package/dist/esm/model/classifier/profile.js +24 -15
  38. package/dist/esm/model/classifier/profileExecution.js +28 -24
  39. package/dist/esm/model/classifier/providers.js +194 -87
  40. package/dist/esm/model/classifier/questionHelpers.js +21 -2
  41. package/dist/esm/model/classifier/questions.js +37 -7
  42. package/dist/esm/model/classifier/response.js +8 -2
  43. package/dist/esm/model/classifier/state.js +2 -2
  44. package/dist/esm/model/classifier/subq.js +51 -0
  45. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +48 -66
  46. package/dist/esm/model/nodes/ClassifierProfileNode.js +11 -9
  47. package/dist/esm/model/nodes/ClassifierQuestionNode.js +53 -34
  48. package/dist/esm/model/tokenPricing.js +52 -0
  49. package/dist/esm/model/tokenPricingEditor.js +9 -0
  50. package/dist/types/exports.d.ts +3 -0
  51. package/dist/types/index.d.ts +1 -1
  52. package/dist/types/integrations/CodeRunner.d.ts +4 -1
  53. package/dist/types/integrations/CodeRunnerNamespace.d.ts +5 -0
  54. package/dist/types/model/AgentResponseTracePresentation.d.ts +2 -0
  55. package/dist/types/model/ChildInvocationOwnership.d.ts +36 -0
  56. package/dist/types/model/DatasetOwnership.d.ts +5 -0
  57. package/dist/types/model/GraphExecutionState.d.ts +2 -0
  58. package/dist/types/model/GraphProcessor.d.ts +3 -0
  59. package/dist/types/model/RunCostLedger.d.ts +19 -0
  60. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +1 -1
  61. package/dist/types/model/chat-v2/chatV2Types.d.ts +2 -0
  62. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +3 -1
  63. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +7 -5
  64. package/dist/types/model/chat-v2/modelRegistry.d.ts +7 -1
  65. package/dist/types/model/classifier/baseten.d.ts +8 -0
  66. package/dist/types/model/classifier/credentials.d.ts +2 -0
  67. package/dist/types/model/classifier/jev.d.ts +9 -0
  68. package/dist/types/model/classifier/profile.d.ts +3 -1
  69. package/dist/types/model/classifier/profileExecution.d.ts +2 -1
  70. package/dist/types/model/classifier/providers.d.ts +30 -6
  71. package/dist/types/model/classifier/questionHelpers.d.ts +3 -1
  72. package/dist/types/model/classifier/questions.d.ts +2 -1
  73. package/dist/types/model/classifier/state.d.ts +1 -0
  74. package/dist/types/model/classifier/subq.d.ts +8 -0
  75. package/dist/types/model/classifier/types.d.ts +9 -2
  76. package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +2 -4
  77. package/dist/types/model/nodes/ClassifierQuestionNode.d.ts +2 -2
  78. package/dist/types/model/tokenPricing.d.ts +18 -0
  79. package/dist/types/model/tokenPricingEditor.d.ts +4 -0
  80. package/package.json +2 -2
@@ -1,5 +1,4 @@
1
1
  export * from './utils/index.js';
2
- // eslint-disable-next-line import/no-cycle -- GraphProcessor depends on CodeRunner, which exposes the top-level Rivet export surface.
3
2
  export * from './model/GraphProcessor.js';
4
3
  export { canConsumeControlFlowExcludedInput } from './model/NodeExclusionPolicy.js';
5
4
  export * from './model/DataValue.js';
@@ -59,6 +58,8 @@ export * from './plugins.js';
59
58
  export * from './model/classifier/credentials.js';
60
59
  export * from './model/classifier/migration.js';
61
60
  export * from './model/classifier/providers.js';
61
+ export * from './model/tokenPricing.js';
62
+ export { getChatV2SystemTokenPricing } from './model/chat-v2/modelRegistry.js';
62
63
  export * from './model/classifier/types.js';
63
64
  export * from './model/NodeRegistration.js';
64
65
  export * from './model/RegistryAssembly.js';
@@ -67,6 +68,7 @@ export * from './model/NodeBodySpec.js';
67
68
  export * from './model/interpolationInputDefinition.js';
68
69
  export * from './integrations/DatasetProvider.js';
69
70
  export * from './model/Dataset.js';
71
+ export { remapOwnedDatasets } from './model/DatasetOwnership.js';
70
72
  export * from './api/streaming.js';
71
73
  export * from './api/createProcessor.js';
72
74
  export * from './api/processSettings.js';
package/dist/esm/index.js CHANGED
@@ -1,2 +1,5 @@
1
+ import * as RivetTypes from './exports.js';
2
+ import { installCodeRunnerNamespace } from './integrations/CodeRunnerNamespace.js';
3
+ installCodeRunnerNamespace(RivetTypes);
1
4
  export * from './exports.js';
2
5
  export const Rivet = undefined;
@@ -1,8 +1,11 @@
1
1
  import { resolveCodeInterpolationExpression } from '../utils/interpolation.js';
2
- // eslint-disable-next-line import/no-cycle -- Authored code receives the complete public Rivet namespace at execution time.
3
- import * as Rivet from '../exports.js';
2
+ import { getCodeRunnerNamespace } from './CodeRunnerNamespace.js';
4
3
  export { ALL_CODE_RUNNER_OPTIONS } from './CodeRunnerOptions.js';
5
4
  export class IsomorphicCodeRunner {
5
+ resolveNamespace;
6
+ constructor(resolveNamespace = getCodeRunnerNamespace) {
7
+ this.resolveNamespace = resolveNamespace;
8
+ }
6
9
  async runCode(code, inputs, options, graphInputs, contextValues, globalValues) {
7
10
  const argNames = ['inputs'];
8
11
  const args = [inputs];
@@ -16,7 +19,7 @@ export class IsomorphicCodeRunner {
16
19
  }
17
20
  if (options.includeRivet) {
18
21
  argNames.push('Rivet');
19
- args.push(Rivet);
22
+ args.push(this.resolveNamespace());
20
23
  }
21
24
  if (graphInputs) {
22
25
  argNames.push('graphInputs');
@@ -0,0 +1,10 @@
1
+ let namespace;
2
+ export function installCodeRunnerNamespace(value) {
3
+ namespace = value;
4
+ }
5
+ export function getCodeRunnerNamespace() {
6
+ if (!namespace) {
7
+ throw new Error('The Rivet code namespace is unavailable. Import the public core entrypoint or supply a code runner.');
8
+ }
9
+ return namespace;
10
+ }
@@ -1,11 +1,15 @@
1
1
  import { getCustomProviderApiContract } from './chat-v2/customProviderApi.js';
2
+ /** Presentation only: family-scoped exact default alias, never a rewrite of authored/recorded names. */
3
+ export function getProfileDisplayName(name, family) {
4
+ return family === 'classifier' && name === 'Classifier Profile' ? 'Decision AI Profile' : name;
5
+ }
2
6
  export function buildAgentProfileAttemptInspectorRows(attempts) {
3
7
  return attempts.map((attempt) => ({
4
8
  eventId: attempt.eventId,
5
9
  providerAndModel: [
6
10
  ...(attempt.profileName == null || attempt.profileName.trim() === ''
7
11
  ? []
8
- : [`Profile: ${attempt.profileName.trim()}`]),
12
+ : [`Profile: ${getProfileDisplayName(attempt.profileName, attempt.family).trim()}`]),
9
13
  `${formatProvider(attempt)} / ${attempt.model}`,
10
14
  ].join(' · '),
11
15
  context: [
@@ -0,0 +1,51 @@
1
+ export function resolveChildInvocationOwnership(mode, context) {
2
+ const { run } = context;
3
+ switch (mode.kind) {
4
+ case 'continuation':
5
+ return {
6
+ parent: context.parent,
7
+ abortOwner: context.abortOwner,
8
+ sameGraphOwner: context.sameGraphOwner,
9
+ suppressPartialOutputs: false,
10
+ suppressLifecycle: true,
11
+ state: {
12
+ attachedNodeData: run.attachedNodeData,
13
+ graphInputNodeValues: run.graphInputNodeValues,
14
+ graphOutputs: mode.graphOutputs,
15
+ },
16
+ identity: { rootRunId: run.rootRunId, graphRunId: run.graphRunId, parentGraphRunId: run.parentGraphRunId },
17
+ };
18
+ case 'async':
19
+ return {
20
+ parent: context.sameGraphOwner,
21
+ abortOwner: context.root,
22
+ suppressPartialOutputs: true,
23
+ suppressLifecycle: context.rootGraphOrigin,
24
+ state: {
25
+ attachedNodeData: run.attachedNodeData,
26
+ graphInputNodeValues: run.graphInputNodeValues,
27
+ graphOutputs: {},
28
+ },
29
+ identity: context.rootGraphOrigin
30
+ ? { rootRunId: run.rootRunId, graphRunId: run.graphRunId, parentGraphRunId: run.parentGraphRunId }
31
+ : {
32
+ rootRunId: context.rootIdentity.rootRunId,
33
+ graphRunId: context.newGraphRunId(),
34
+ parentGraphRunId: context.sameGraphIdentity.graphRunId,
35
+ },
36
+ };
37
+ case 'watch':
38
+ return {
39
+ parent: context.parent,
40
+ abortOwner: context.root,
41
+ suppressPartialOutputs: true,
42
+ suppressLifecycle: true,
43
+ state: { attachedNodeData: new Map(), graphInputNodeValues: { ...run.graphInputNodeValues }, graphOutputs: {} },
44
+ identity: {
45
+ rootRunId: context.rootIdentity.rootRunId,
46
+ graphRunId: mode.graphRunId,
47
+ parentGraphRunId: run.graphRunId,
48
+ },
49
+ };
50
+ }
51
+ }
@@ -0,0 +1,9 @@
1
+ /** Change only the owner of already validated sidecars. Reference/version
2
+ * rewiring is an operation-specific policy, not part of dataset ownership. */
3
+ export function remapOwnedDatasets(datasets, sourceId, targetId) {
4
+ return datasets.map((dataset) => {
5
+ if (dataset.meta.projectId !== sourceId)
6
+ throw new Error('Dataset ownership does not match the source project.');
7
+ return { ...dataset, meta: { ...dataset.meta, projectId: targetId } };
8
+ });
9
+ }
@@ -1,3 +1,4 @@
1
+ import { RunCostLedger } from './RunCostLedger.js';
1
2
  /** Invocation-owned fields; GraphProcessor resets them at the established initialization boundaries. */
2
3
  export class GraphInvocationState {
3
4
  rootRunId = undefined;
@@ -23,6 +24,7 @@ export class GraphInvocationState {
23
24
  successfulAbortTerminalProcessIds = undefined;
24
25
  totalCost = 0;
25
26
  costBreakdown;
27
+ costLedger = new RunCostLedger();
26
28
  ignoreNodes = undefined;
27
29
  hasPreloadedData = false;
28
30
  loadedProjects = undefined;
@@ -58,6 +60,7 @@ export class GraphInvocationState {
58
60
  this.successfulAbortTerminalProcessIds = new Set();
59
61
  this.totalCost = 0;
60
62
  this.costBreakdown = undefined;
63
+ this.costLedger = new RunCostLedger();
61
64
  this.nodeAbortControllers = new Map();
62
65
  this.loadedProjects = options.loadedProjects;
63
66
  this.graphInputNodeValues = options.sharedOverride?.graphInputNodeValues ?? {};
@@ -1,4 +1,5 @@
1
1
  import { GraphInvocationState, GraphSharedExecutionState } from './GraphExecutionState.js';
2
+ import { resolveChildInvocationOwnership } from './ChildInvocationOwnership.js';
2
3
  import { planStreamingWatchTopology, planAsyncBranchTopology, getAsyncBranchWatchViolation, } from './SchedulerBoundaryPlanner.js';
3
4
  import { GraphSchedulerBoundaryState, } from './GraphSchedulerBoundaryState.js';
4
5
  import {} from './DataValue.js';
@@ -48,7 +49,6 @@ import { loadProjectReferenceTree } from './ProjectReferenceLoader.js';
48
49
  import { getSubgraphProjectKey, isSubgraphProjectKey } from './SubgraphProjectTarget.js';
49
50
  import { MAX_CAUGHT_STREAMING_CHUNKS } from './nodes/CatchStreamingChunksNode.js';
50
51
  import { isEqual } from 'lodash-es';
51
- // eslint-disable-next-line import/no-cycle -- There has to be a cycle because CodeRunner needs to import the entirety of Rivet
52
52
  import { IsomorphicCodeRunner } from '../integrations/CodeRunner.js';
53
53
  const graphProcessorGraphOverride = Symbol('graphProcessorGraphOverride');
54
54
  const consumedAsyncBranchTriggerOverride = Symbol('consumedAsyncBranchTriggerOverride');
@@ -887,6 +887,8 @@ export class GraphProcessor {
887
887
  const hostChatV2Observer = this.getRootProcessor().#run.context.onChatV2CallFinished;
888
888
  const hostLLMChatOutputSnapshotObserver = this.getRootProcessor().#run.context.onLLMChatOutputSnapshot;
889
889
  const hostLLMProfileAttemptObserver = this.getRootProcessor().#run.context.onLLMProfileAttempt;
890
+ // Capture the invocation's ledger, not a later run that reuses this processor.
891
+ const costLedger = this.getRootProcessor().#run.costLedger;
890
892
  this.#run.nodeProcessContextBase = {
891
893
  ...this.#run.context,
892
894
  abortGraph: (error) => {
@@ -906,6 +908,12 @@ export class GraphProcessor {
906
908
  graphOutputs: this.#run.graphOutputs,
907
909
  graphCallPath: this.#graphCallPath,
908
910
  onChatV2CallFinished: (event) => {
911
+ try {
912
+ costLedger.observeChat(event);
913
+ }
914
+ catch {
915
+ costLedger.markUnobserved();
916
+ }
909
917
  try {
910
918
  const observerResult = hostChatV2Observer?.(event);
911
919
  if (observerResult != null && typeof observerResult.then === 'function') {
@@ -935,6 +943,12 @@ export class GraphProcessor {
935
943
  emitDetached(this.#emitter, 'llmChatOutputSnapshot', this.#withExecution(event));
936
944
  },
937
945
  onLLMProfileAttempt: (event) => {
946
+ try {
947
+ costLedger.observeClassifier(event);
948
+ }
949
+ catch {
950
+ costLedger.markUnobserved();
951
+ }
938
952
  try {
939
953
  const observerResult = hostLLMProfileAttemptObserver?.(event);
940
954
  if (observerResult != null && typeof observerResult.then === 'function') {
@@ -1324,6 +1338,9 @@ export class GraphProcessor {
1324
1338
  };
1325
1339
  const key = getSubgraphProjectKey(target);
1326
1340
  let resolved = this.#shared.subgraphTargetCache.get(key);
1341
+ // Snapshot reuse is not permission reuse. A descendant can move
1342
+ // bundles after the parent's discovery but before this child starts;
1343
+ // keep this preflight ahead of any child-node side effects.
1327
1344
  if (resolved)
1328
1345
  await this.#run.context.subgraphProjectLoader?.validateTarget?.(target);
1329
1346
  if (!resolved) {
@@ -1809,7 +1826,6 @@ export class GraphProcessor {
1809
1826
  async #runManagedAsyncBranch(triggerNode, triggerOutputs, plan, onProcessorCreated) {
1810
1827
  const root = this.getRootProcessor();
1811
1828
  const sameGraphOwner = this.#sameGraphRunOwnerOverride ?? this;
1812
- const isRootGraphOrigin = !sameGraphOwner.#isSubProcessor;
1813
1829
  if (root.#run.abortController.signal.aborted) {
1814
1830
  throw createGraphAbortErrorFromSignal(root.#run.abortController.signal, 'Async branch aborted before it started');
1815
1831
  }
@@ -1826,31 +1842,8 @@ export class GraphProcessor {
1826
1842
  .map((connection) => [connection.outputNodeId, this.#definitions[connection.outputNodeId]])),
1827
1843
  onCreated: onProcessorCreated,
1828
1844
  });
1829
- processor.#parent = sameGraphOwner;
1830
- processor.#abortOwnerOverride = root;
1831
- processor.#suppressGraphPartialOutputs = true;
1832
- processor.#suppressGraphLifecycleEvents = isRootGraphOrigin;
1833
- processor.#sharedRunStateOverride = {
1834
- attachedNodeData: this.#run.attachedNodeData,
1835
- graphInputNodeValues: this.#run.graphInputNodeValues,
1836
- // Async branches cannot contain Graph Output nodes. Keep their synthetic
1837
- // boundary outputs private so branch finalization cannot seed the root's
1838
- // derived cost output before the root has accumulated every path.
1839
- graphOutputs: {},
1840
- };
1841
1845
  const branchRunToNodeIds = this.runToNodeIds?.filter((nodeId) => plan.nodeIds.has(nodeId));
1842
1846
  processor.runToNodeIds = branchRunToNodeIds?.length ? branchRunToNodeIds : undefined;
1843
- processor.#executionIdentityOverride = isRootGraphOrigin
1844
- ? {
1845
- rootRunId: this.#run.rootRunId,
1846
- graphRunId: this.#run.graphRunId,
1847
- parentGraphRunId: this.#run.parentGraphRunId,
1848
- }
1849
- : {
1850
- rootRunId: root.#run.rootRunId,
1851
- graphRunId: nanoid(),
1852
- parentGraphRunId: sameGraphOwner.#run.graphRunId,
1853
- };
1854
1847
  processor.preloadNodeData(triggerNode.id, triggerOutputs);
1855
1848
  processor.#suppressedPreloadedNodeIds.add(triggerNode.id);
1856
1849
  const unwireEvents = this.#wireChildEvents(processor, root, {
@@ -2128,6 +2121,11 @@ export class GraphProcessor {
2128
2121
  }
2129
2122
  return processor;
2130
2123
  }
2124
+ /** Snapshot the root execution's observed provider estimates after completion. */
2125
+ getRunCostSnapshot() {
2126
+ const root = this.getRootProcessor();
2127
+ return root.#run.costLedger.snapshot(root.isRunning);
2128
+ }
2131
2129
  #getEnclosingStreamingWatchInvocation() {
2132
2130
  let processor = this;
2133
2131
  while (processor) {
@@ -2225,11 +2223,22 @@ export class GraphProcessor {
2225
2223
  nodeAbortController.abort(getAbortSignalReason(this.#run.abortController.signal));
2226
2224
  }
2227
2225
  let continuationFinalized = false;
2226
+ const costLedger = this.getRootProcessor().#run.costLedger;
2227
+ const accountingKey = `${this.#run.graphRunId}:${processId}:${index}`;
2228
+ let accountingEntered = false;
2229
+ let observedPhysicalCall = false;
2230
+ let cacheHit = false;
2231
+ let accountingOutputs;
2228
2232
  try {
2229
2233
  const createContextProfileStart = this.#startRuntimeProfile();
2230
2234
  let context;
2231
2235
  try {
2232
- context = this.#createNodeProcessContext(node, inputValues, index, processId, nodeAbortController, partialOutput, undefined, markResultAsEditorCacheHit);
2236
+ context = this.#createNodeProcessContext(node, inputValues, index, processId, nodeAbortController, partialOutput, undefined, markResultAsEditorCacheHit
2237
+ ? () => {
2238
+ cacheHit = true;
2239
+ markResultAsEditorCacheHit();
2240
+ }
2241
+ : undefined);
2233
2242
  }
2234
2243
  finally {
2235
2244
  this.#finishRuntimeProfile('createNodeProcessContext', createContextProfileStart);
@@ -2238,10 +2247,27 @@ export class GraphProcessor {
2238
2247
  if (nodeAbortController.signal.aborted) {
2239
2248
  throw createGraphAbortErrorFromSignal(nodeAbortController.signal);
2240
2249
  }
2250
+ if (node.type === 'llmChatV2') {
2251
+ const observer = context.onChatV2CallFinished;
2252
+ context.onChatV2CallFinished = (event) => {
2253
+ observedPhysicalCall = true;
2254
+ observer?.(event);
2255
+ };
2256
+ }
2257
+ else if (node.type === 'classifierEvaluate') {
2258
+ const observer = context.onLLMProfileAttempt;
2259
+ context.onLLMProfileAttempt = (event) => {
2260
+ if (event.family === 'classifier' && event.attemptIndex !== undefined)
2261
+ observedPhysicalCall = true;
2262
+ observer?.(event);
2263
+ };
2264
+ }
2241
2265
  const implementationProfileStart = this.#startRuntimeProfile();
2242
2266
  let results;
2243
2267
  try {
2268
+ accountingEntered = true;
2244
2269
  results = await instance.process(inputValues, context);
2270
+ accountingOutputs = results;
2245
2271
  }
2246
2272
  finally {
2247
2273
  this.#finishRuntimeProfile('nodeImplementation', implementationProfileStart);
@@ -2263,6 +2289,20 @@ export class GraphProcessor {
2263
2289
  return results;
2264
2290
  }
2265
2291
  finally {
2292
+ if (accountingEntered && !cacheHit) {
2293
+ try {
2294
+ if (['chat', 'chatLoop', 'chatGoogle', 'chatAnthropic', 'chatHuggingFace', 'getEmbedding'].includes(node.type)) {
2295
+ const cost = accountingOutputs?.['cost'];
2296
+ costLedger.observeLegacy(accountingKey, cost?.type === 'number' ? cost.value : undefined);
2297
+ }
2298
+ else if ((node.type === 'llmChatV2' || node.type === 'classifierEvaluate') && !observedPhysicalCall) {
2299
+ costLedger.markUnobserved();
2300
+ }
2301
+ }
2302
+ catch {
2303
+ costLedger.markUnobserved();
2304
+ }
2305
+ }
2266
2306
  if (!continuationFinalized) {
2267
2307
  this.#discardToolCallContinuation(processId, index);
2268
2308
  }
@@ -2502,23 +2542,14 @@ export class GraphProcessor {
2502
2542
  throw new Error('Cannot execute a tool continuation branch because the current graph has no ID.');
2503
2543
  }
2504
2544
  const branchGraphOutputs = createGraphOutputsOverlay(this.#run.graphOutputs);
2505
- const processor = this.#constructChildInvocation({ kind: 'continuation', graph: branchPlan.graph });
2506
- processor.#abortOwnerOverride = this.#abortOwnerOverride ?? this;
2507
- processor.#sameGraphRunOwnerOverride = this.#sameGraphRunOwnerOverride ?? this;
2508
- processor.#suppressGraphLifecycleEvents = true;
2509
- processor.#sharedRunStateOverride = {
2510
- attachedNodeData: this.#run.attachedNodeData,
2511
- graphInputNodeValues: this.#run.graphInputNodeValues,
2545
+ const processor = this.#constructChildInvocation({
2546
+ kind: 'continuation',
2547
+ graph: branchPlan.graph,
2512
2548
  graphOutputs: branchGraphOutputs.view,
2513
- };
2549
+ });
2514
2550
  const branchNodeIds = new Set(branchPlan.graph.nodes.map((node) => node.id));
2515
2551
  const branchRunToNodeIds = this.runToNodeIds?.filter((nodeId) => branchNodeIds.has(nodeId));
2516
2552
  processor.runToNodeIds = branchRunToNodeIds?.length ? branchRunToNodeIds : undefined;
2517
- processor.#executionIdentityOverride = {
2518
- rootRunId: this.#run.rootRunId,
2519
- graphRunId: this.#run.graphRunId,
2520
- parentGraphRunId: this.#run.parentGraphRunId,
2521
- };
2522
2553
  for (const [nodeId, outputs] of branchPlan.preloadedOutputs) {
2523
2554
  processor.preloadNodeData(nodeId, outputs);
2524
2555
  processor.#suppressedPreloadedNodeIds.add(nodeId);
@@ -3176,21 +3207,8 @@ export class GraphProcessor {
3176
3207
  kind: 'watch',
3177
3208
  graph: plan.graph,
3178
3209
  watchNodeId: plan.watchNode.id,
3179
- });
3180
- processor.#abortOwnerOverride = root;
3181
- processor.#suppressGraphPartialOutputs = true;
3182
- processor.#suppressGraphLifecycleEvents = true;
3183
- processor.#sharedRunStateOverride = {
3184
- // Repeated node IDs do not imply shared race/loop state between snapshots.
3185
- attachedNodeData: new Map(),
3186
- graphInputNodeValues: { ...this.#run.graphInputNodeValues },
3187
- graphOutputs: {},
3188
- };
3189
- processor.#executionIdentityOverride = {
3190
- rootRunId: root.#run.rootRunId,
3191
3210
  graphRunId: historyIteration.graphRunId,
3192
- parentGraphRunId: this.#run.graphRunId,
3193
- };
3211
+ });
3194
3212
  processor.#streamingWatchInvocation = {
3195
3213
  plan,
3196
3214
  historyIteration,
@@ -3538,8 +3556,8 @@ export class GraphProcessor {
3538
3556
  execution: parentExecution,
3539
3557
  });
3540
3558
  }
3541
- /** Common construction only. Aliases, execution identity and terminal commits
3542
- * remain explicit in each invocation path rather than a matrix of flags. */
3559
+ /** One construction boundary applies the discriminated ownership contract;
3560
+ * scheduling and terminal commits remain with their respective branch owner. */
3543
3561
  #constructChildInvocation(invocation) {
3544
3562
  const ordinary = invocation.kind === 'subgraph';
3545
3563
  const processor = new GraphProcessor(ordinary ? invocation.project : this.#project, ordinary ? invocation.graphId : invocation.graph.metadata.id, this.#registry, this.#includeTrace, {
@@ -3579,6 +3597,27 @@ export class GraphProcessor {
3579
3597
  processor.#graphCallPath = this.#graphCallPath;
3580
3598
  processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
3581
3599
  processor.#executor = this.#executor;
3600
+ if (!ordinary) {
3601
+ const sameGraphOwner = this.#sameGraphRunOwnerOverride ?? this;
3602
+ const ownership = resolveChildInvocationOwnership(invocation, {
3603
+ parent: this,
3604
+ root: this.getRootProcessor(),
3605
+ abortOwner: this.#abortOwnerOverride ?? this,
3606
+ sameGraphOwner,
3607
+ rootGraphOrigin: !sameGraphOwner.#isSubProcessor,
3608
+ run: this.#run,
3609
+ rootIdentity: this.getRootProcessor().#run,
3610
+ sameGraphIdentity: sameGraphOwner.#run,
3611
+ newGraphRunId: () => nanoid(),
3612
+ });
3613
+ processor.#parent = ownership.parent;
3614
+ processor.#abortOwnerOverride = ownership.abortOwner;
3615
+ processor.#sameGraphRunOwnerOverride = ownership.sameGraphOwner;
3616
+ processor.#suppressGraphPartialOutputs = ownership.suppressPartialOutputs;
3617
+ processor.#suppressGraphLifecycleEvents = ownership.suppressLifecycle;
3618
+ processor.#sharedRunStateOverride = ownership.state;
3619
+ processor.#executionIdentityOverride = ownership.identity;
3620
+ }
3582
3621
  return processor;
3583
3622
  }
3584
3623
  #wireChildEvents(processor, owner, options = {}) {
@@ -1,6 +1,6 @@
1
1
  import {} from './NodeBase.js';
2
2
  import { PluginNodeImplClass } from './NodeImpl.js';
3
- import { mapValues, values } from '../utils/typeSafety.js';
3
+ import { values } from '../utils/typeSafety.js';
4
4
  import {} from './RivetPlugin.js';
5
5
  import {} from './RivetUIContext.js';
6
6
  export class NodeRegistration {
@@ -77,10 +77,6 @@ export class NodeRegistration {
77
77
  get #dynamicImpls() {
78
78
  return this.#implsMap;
79
79
  }
80
- get #dynamicDisplayNames() {
81
- const displayNameMap = mapValues(this.#infos, (info) => info.displayName);
82
- return displayNameMap;
83
- }
84
80
  registerPlugin(plugin) {
85
81
  if (plugin.register) {
86
82
  plugin.register((definition) => this.registerPluginNode(definition, plugin));
@@ -118,7 +114,7 @@ export class NodeRegistration {
118
114
  return this.#getInfo(type).displayName;
119
115
  }
120
116
  getDynamicDisplayName(type) {
121
- const displayName = this.#dynamicDisplayNames[type];
117
+ const displayName = Object.hasOwn(this.#infos, type) ? this.#infos[type].displayName : undefined;
122
118
  if (!displayName) {
123
119
  throw new Error(`Unknown node type: ${type}`);
124
120
  }
@@ -0,0 +1,58 @@
1
+ /** Receives physical-call observations directly, before display/recording filters. */
2
+ export class RunCostLedger {
3
+ #calls = new Map();
4
+ #hasUnobservedWork = false;
5
+ observeChat(event) {
6
+ if (typeof event.callId !== 'string' || !event.callId) {
7
+ this.markUnobserved();
8
+ return;
9
+ }
10
+ this.#record(`llm:${event.callId}`, event.pricing.status === 'known' ? event.pricing.costUsd : undefined);
11
+ }
12
+ observeClassifier(event) {
13
+ if (event.family !== 'classifier' || event.attemptIndex === undefined)
14
+ return;
15
+ if (typeof event.eventId !== 'string' ||
16
+ !event.eventId ||
17
+ !Number.isSafeInteger(event.attemptIndex) ||
18
+ event.attemptIndex < 0) {
19
+ this.markUnobserved();
20
+ return;
21
+ }
22
+ this.#record(`decision:${event.eventId}`, event.classifierUsage?.estimatedCostUsd);
23
+ }
24
+ /** Legacy Chat does not expose complete per-attempt accounting. */
25
+ observeLegacy(key, value) {
26
+ if (typeof value === 'number' && Number.isFinite(value) && value > 0)
27
+ this.#record(`legacy:${key}`, value);
28
+ this.markUnobserved();
29
+ }
30
+ markUnobserved() {
31
+ this.#hasUnobservedWork = true;
32
+ }
33
+ snapshot(executionPending = false) {
34
+ let known = 0;
35
+ let knownCount = 0;
36
+ let hasUnknownCost = this.#hasUnobservedWork || executionPending;
37
+ for (const cost of this.#calls.values()) {
38
+ if (cost === null)
39
+ hasUnknownCost = true;
40
+ else {
41
+ known += cost;
42
+ knownCount++;
43
+ }
44
+ }
45
+ if (!Number.isFinite(known))
46
+ return { status: 'unknown', knownCostUsd: null };
47
+ if (!hasUnknownCost)
48
+ return { status: 'complete', knownCostUsd: known };
49
+ if (knownCount === 0)
50
+ return { status: 'unknown', knownCostUsd: null };
51
+ return { status: 'partial', knownCostUsd: known };
52
+ }
53
+ #record(id, value) {
54
+ if (this.#calls.has(id))
55
+ return;
56
+ this.#calls.set(id, typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null);
57
+ }
58
+ }
@@ -109,9 +109,9 @@ export function notifyChatV2CallFinished(options, params) {
109
109
  const rawUsage = safelyRead(() => copyRawUsage(resultUsage ?? errorUsage));
110
110
  const normalizedUsage = safelyRead(() => normalizeObservedUsage(rawUsage));
111
111
  const modelInfo = safelyRead(() => getChatV2ModelInfo(options.provider, options.modelId));
112
- const calculatedCost = safelyRead(() => calculateChatV2UsageCost(options.provider, options.modelId, rawUsage, params.result?.providerMetadata));
112
+ const calculatedCost = safelyRead(() => calculateChatV2UsageCost(options.provider, options.modelId, resultUsage ?? errorUsage, params.result?.providerMetadata, options.tokenPricing));
113
113
  const costUsd = toUsageNumber(calculatedCost);
114
- const hasKnownPricing = modelInfo?.cost != null || (options.provider === 'openrouter' && costUsd != null);
114
+ const hasKnownPricing = options.tokenPricing != null || modelInfo?.cost != null || (options.provider === 'openrouter' && costUsd != null);
115
115
  const finishReason = safelyRead(() => params.result?.finishReason) ??
116
116
  getErrorProperty(params.error, 'finishReason', (value) => typeof value === 'string');
117
117
  const event = {
@@ -55,7 +55,7 @@ export function normalizeChatV2Usage(usage, options, providerMetadata) {
55
55
  totalTokens,
56
56
  cachedTokens,
57
57
  reasoningTokens,
58
- totalCost: calculateChatV2UsageCost(options.provider, options.modelId, usage, providerMetadata),
58
+ totalCost: calculateChatV2UsageCost(options.provider, options.modelId, usage, providerMetadata, options.tokenPricing),
59
59
  };
60
60
  }
61
61
  export function createChatV2ResponseOutput(response, structuredOutput, responseFormat) {
@@ -68,6 +68,7 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
68
68
  const callId = createObservedChatV2CallId(options);
69
69
  const callStartedAt = Date.now();
70
70
  let callWasObserved = false;
71
+ let completedResponse;
71
72
  // AI SDK accessors such as usage and reasoning may settle after a request
72
73
  // has otherwise failed. Their diagnostic callbacks belong only to this
73
74
  // physical request: never let a retired retry/fallback candidate overwrite
@@ -116,6 +117,9 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
116
117
  const result = transportMode === 'generate'
117
118
  ? await generateChatV2(attemptChatOptions)
118
119
  : await streamChatV2(attemptChatOptions);
120
+ // Cancellation during diagnostic finalization must not erase usage
121
+ // already returned by this physical attempt. It still wins the outcome.
122
+ completedResponse = result;
119
123
  signal.throwIfAborted();
120
124
  await options.responseBodyCapture?.flush();
121
125
  signal.throwIfAborted();
@@ -160,6 +164,7 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
160
164
  callId,
161
165
  attemptIndex: attempt,
162
166
  outcome: signal.aborted ? 'aborted' : 'provider-failure',
167
+ result: completedResponse,
163
168
  error,
164
169
  startedAt: callStartedAt,
165
170
  durationMs: Math.max(0, Date.now() - callStartedAt),
@@ -1,4 +1,5 @@
1
1
  import { profileSuspensionHints } from '../profileSuspensionHints.js';
2
+ import { getTokenPricingEditor } from '../tokenPricingEditor.js';
2
3
  import { STREAM_RESPONSE_HELPER_MESSAGE } from './chatV2Shared.js';
3
4
  import { DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_COOLDOWN_MS, DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_REPEAT_TIMES, } from './chatV2Retry.js';
4
5
  import { anthropicCacheControlTtlOptions, anthropicEffortOptions, anthropicThinkingModeOptions, chatV2ProviderOptions, customProviderApiOptions, getChatV2ModelOptions, googleThinkingLevelOptions, openAIReasoningEffortOptions, openAIWebSearchContextSizeOptions, } from './providerOptions.js';
@@ -624,6 +625,7 @@ export async function getLLMChatV2Editors(data, context) {
624
625
  ...(!usesProfile
625
626
  ? [
626
627
  getModelEditors(await getResolvedModelOptions(data, context)),
628
+ getTokenPricingEditor(),
627
629
  ...getProviderEditors(),
628
630
  getParameterEditors(),
629
631
  ...(data.provider === 'custom' ? [] : [getReasoningEditors()]),
@@ -640,6 +642,7 @@ export async function getLLMProfileEditors(data, context) {
640
642
  const profileData = data;
641
643
  return [
642
644
  getModelEditors(await getResolvedModelOptions(profileData, context)),
645
+ getTokenPricingEditor(),
643
646
  ...getProviderEditors(),
644
647
  getParameterEditors(),
645
648
  ...(profileData.provider === 'custom' ? [] : [getReasoningEditors()]),
@@ -8,9 +8,11 @@ import { createChatV2ResponseOutput, mergeCustomProviderResponseFormatOptions }
8
8
  import { parseCustomProviderApi } from './customProviderApi.js';
9
9
  import { parseChatV2Provider } from './providerOptions.js';
10
10
  import { restoreOpenAICompatibleInstructionRoles } from './developerMessageRoles.js';
11
+ import { validateTokenPricing } from '../tokenPricing.js';
11
12
  export async function resolveLLMModelCandidate(params) {
12
13
  const { plan, profile } = params;
13
14
  const effectiveData = profile ? applyLLMProfileToNodeData(plan.data, profile) : plan.data;
15
+ const tokenPricing = validateTokenPricing(effectiveData.tokenPricing);
14
16
  if (hasLLMChatV2ToolResponseFormatConflict(effectiveData)) {
15
17
  throw new Error(LLM_CHAT_V2_TOOL_RESPONSE_FORMAT_CONFLICT_COPY.paragraphs[0]);
16
18
  }
@@ -62,6 +64,7 @@ export async function resolveLLMModelCandidate(params) {
62
64
  requestBodyOverlay,
63
65
  runOptions: {
64
66
  ...baseRunOptions,
67
+ tokenPricing,
65
68
  provider,
66
69
  model: resolvedProvider.model,
67
70
  modelId,
@@ -5,6 +5,7 @@ import { LLM_PROFILE_VALUE_VERSION, pickLLMChatV2ProfileData } from './llmProfil
5
5
  import { createRivetLLMProfileHealthIdentity } from './llmProfileHealthStore.js';
6
6
  import { normalizeChatV2CredentialNamesByProvider } from './chatV2CredentialNames.js';
7
7
  import { normalizeTemperature } from './temperature.js';
8
+ import { validateTokenPricing } from '../tokenPricing.js';
8
9
  export { applyLLMProfileToNodeData, createDefaultLLMProfileValue, createLLMProfileNodeData, LLM_PROFILE_VALUE_VERSION, pickLLMChatV2ProfileData, } from './llmProfileTypes.js';
9
10
  const credentialSources = new Set([
10
11
  'input',
@@ -106,6 +107,7 @@ export function scopeLLMProfileHealthIdentity(profile, fallback) {
106
107
  };
107
108
  }
108
109
  function normalizeConfiguration(data) {
110
+ data = { ...data, tokenPricing: validateTokenPricing(data.tokenPricing) };
109
111
  for (const field of llmProfileStringDataKeys) {
110
112
  if (typeof data[field] !== 'string') {
111
113
  throw new Error(`LLM Profile ${field} must be a string.`);
@@ -1,4 +1,5 @@
1
1
  export const llmProfileFieldSpecs = [
2
+ { key: 'tokenPricing' },
2
3
  { key: 'model', inputId: 'model', valueKind: 'string' },
3
4
  { key: 'useModelInput', valueKind: 'boolean', resolvedInputToggle: true },
4
5
  { key: 'temperature', inputId: 'temperature', valueKind: 'optional-number' },