@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
@@ -58,6 +58,8 @@ export * from './plugins.js';
58
58
  export * from './model/classifier/credentials.js';
59
59
  export * from './model/classifier/migration.js';
60
60
  export * from './model/classifier/providers.js';
61
+ export * from './model/tokenPricing.js';
62
+ export { getChatV2SystemTokenPricing } from './model/chat-v2/modelRegistry.js';
61
63
  export * from './model/classifier/types.js';
62
64
  export * from './model/NodeRegistration.js';
63
65
  export * from './model/RegistryAssembly.js';
@@ -66,6 +68,7 @@ export * from './model/NodeBodySpec.js';
66
68
  export * from './model/interpolationInputDefinition.js';
67
69
  export * from './integrations/DatasetProvider.js';
68
70
  export * from './model/Dataset.js';
71
+ export { remapOwnedDatasets } from './model/DatasetOwnership.js';
69
72
  export * from './api/streaming.js';
70
73
  export * from './api/createProcessor.js';
71
74
  export * from './api/processSettings.js';
@@ -81,3 +84,4 @@ export { scanInterpolationTokenSpans } from './utils/interpolationSyntax.js';
81
84
  export { WarningsPort } from './utils/symbols.js';
82
85
  import * as openai from './utils/openai.js';
83
86
  export { openai };
87
+ export * from './model/LatestDebuggerProtocol.js';
@@ -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 = options.costLedger ?? new RunCostLedger();
61
64
  this.nodeAbortControllers = new Map();
62
65
  this.loadedProjects = options.loadedProjects;
63
66
  this.graphInputNodeValues = options.sharedOverride?.graphInputNodeValues ?? {};
@@ -171,6 +171,8 @@ export class GraphProcessor {
171
171
  slowMode = false;
172
172
  #parent;
173
173
  #recordingProjectScope;
174
+ /** Captures the caller invocation, independently of lifecycle-parent rewiring. */
175
+ #projectCostScope;
174
176
  #abortOwnerOverride;
175
177
  #sameGraphRunOwnerOverride;
176
178
  #suppressGraphPartialOutputs = false;
@@ -676,6 +678,11 @@ export class GraphProcessor {
676
678
  createAbortController: () => this.#newAbortController(),
677
679
  loadedProjects: this.#cacheLoadedProjects && this.#runtimeCache?.loadedProjects ? { ...this.#runtimeCache.loadedProjects } : {},
678
680
  sharedOverride: this.#sharedRunStateOverride,
681
+ costLedger: this.#projectCostScope
682
+ ? this.#projectCostScope.startsProject
683
+ ? this.#projectCostScope.parentLedger.createProjectScope()
684
+ : this.#projectCostScope.parentLedger
685
+ : undefined,
679
686
  });
680
687
  this.#shared.executionCache ??= new Map();
681
688
  this.#connectedToolContinuationHost.reset();
@@ -887,8 +894,13 @@ export class GraphProcessor {
887
894
  const hostChatV2Observer = this.getRootProcessor().#run.context.onChatV2CallFinished;
888
895
  const hostLLMChatOutputSnapshotObserver = this.getRootProcessor().#run.context.onLLMChatOutputSnapshot;
889
896
  const hostLLMProfileAttemptObserver = this.getRootProcessor().#run.context.onLLMProfileAttempt;
897
+ // Capture the invocation's ledger, not a later run that reuses this processor.
898
+ const costLedger = this.#run.costLedger;
899
+ const { rootRunId, graphRunId } = this.#run;
900
+ const isCurrentInvocation = () => this.#run.rootRunId === rootRunId && this.#run.graphRunId === graphRunId;
890
901
  this.#run.nodeProcessContextBase = {
891
902
  ...this.#run.context,
903
+ getRunCostBreakdown: () => costLedger.breakdown(),
892
904
  abortGraph: (error) => {
893
905
  void (this.#abortOwnerOverride ?? this).abort(error === undefined, error);
894
906
  },
@@ -906,6 +918,12 @@ export class GraphProcessor {
906
918
  graphOutputs: this.#run.graphOutputs,
907
919
  graphCallPath: this.#graphCallPath,
908
920
  onChatV2CallFinished: (event) => {
921
+ try {
922
+ costLedger.observeChat(event);
923
+ }
924
+ catch {
925
+ costLedger.markUnobserved('llm');
926
+ }
909
927
  try {
910
928
  const observerResult = hostChatV2Observer?.(event);
911
929
  if (observerResult != null && typeof observerResult.then === 'function') {
@@ -915,6 +933,8 @@ export class GraphProcessor {
915
933
  catch {
916
934
  // Host observers must never change graph execution.
917
935
  }
936
+ if (!isCurrentInvocation())
937
+ return;
918
938
  // Runtime traces carry only the normalized, provider-neutral usage
919
939
  // contract. The host observer above retains its existing raw accounting
920
940
  // callback, but provider-shaped usage never enters recordings or remote
@@ -932,9 +952,16 @@ export class GraphProcessor {
932
952
  catch {
933
953
  // Snapshot observers are display-only and must never affect execution.
934
954
  }
935
- emitDetached(this.#emitter, 'llmChatOutputSnapshot', this.#withExecution(event));
955
+ if (isCurrentInvocation())
956
+ emitDetached(this.#emitter, 'llmChatOutputSnapshot', this.#withExecution(event));
936
957
  },
937
958
  onLLMProfileAttempt: (event) => {
959
+ try {
960
+ costLedger.observeClassifier(event);
961
+ }
962
+ catch {
963
+ costLedger.markUnobserved('decisionAI');
964
+ }
938
965
  try {
939
966
  const observerResult = hostLLMProfileAttemptObserver?.(event);
940
967
  if (observerResult != null && typeof observerResult.then === 'function') {
@@ -944,10 +971,12 @@ export class GraphProcessor {
944
971
  catch {
945
972
  // Host observers must never change graph execution.
946
973
  }
947
- emitDetached(this.#emitter, 'llmProfileAttempt', this.#withExecution(event));
974
+ if (isCurrentInvocation())
975
+ emitDetached(this.#emitter, 'llmProfileAttempt', this.#withExecution(event));
948
976
  },
949
977
  onToolCallFinished: (event) => {
950
- emitDetached(this.#emitter, 'toolCallFinished', this.#withExecution(event));
978
+ if (isCurrentInvocation())
979
+ emitDetached(this.#emitter, 'toolCallFinished', this.#withExecution(event));
951
980
  },
952
981
  project: this.#project,
953
982
  raiseEvent: (event, data) => {
@@ -2107,6 +2136,11 @@ export class GraphProcessor {
2107
2136
  }
2108
2137
  return processor;
2109
2138
  }
2139
+ /** Snapshot the root execution's observed provider estimates after completion. */
2140
+ getRunCostSnapshot() {
2141
+ const root = this.getRootProcessor();
2142
+ return root.#run.costLedger.snapshot(root.isRunning);
2143
+ }
2110
2144
  #getEnclosingStreamingWatchInvocation() {
2111
2145
  let processor = this;
2112
2146
  while (processor) {
@@ -2204,11 +2238,22 @@ export class GraphProcessor {
2204
2238
  nodeAbortController.abort(getAbortSignalReason(this.#run.abortController.signal));
2205
2239
  }
2206
2240
  let continuationFinalized = false;
2241
+ const costLedger = this.#run.costLedger;
2242
+ const accountingKey = `${this.#run.graphRunId}:${processId}:${index}`;
2243
+ let accountingEntered = false;
2244
+ let observedPhysicalCall = false;
2245
+ let cacheHit = false;
2246
+ let accountingOutputs;
2207
2247
  try {
2208
2248
  const createContextProfileStart = this.#startRuntimeProfile();
2209
2249
  let context;
2210
2250
  try {
2211
- context = this.#createNodeProcessContext(node, inputValues, index, processId, nodeAbortController, partialOutput, undefined, markResultAsEditorCacheHit);
2251
+ context = this.#createNodeProcessContext(node, inputValues, index, processId, nodeAbortController, partialOutput, undefined, markResultAsEditorCacheHit
2252
+ ? () => {
2253
+ cacheHit = true;
2254
+ markResultAsEditorCacheHit();
2255
+ }
2256
+ : undefined);
2212
2257
  }
2213
2258
  finally {
2214
2259
  this.#finishRuntimeProfile('createNodeProcessContext', createContextProfileStart);
@@ -2217,10 +2262,27 @@ export class GraphProcessor {
2217
2262
  if (nodeAbortController.signal.aborted) {
2218
2263
  throw createGraphAbortErrorFromSignal(nodeAbortController.signal);
2219
2264
  }
2265
+ if (node.type === 'llmChatV2') {
2266
+ const observer = context.onChatV2CallFinished;
2267
+ context.onChatV2CallFinished = (event) => {
2268
+ observedPhysicalCall = true;
2269
+ observer?.(event);
2270
+ };
2271
+ }
2272
+ else if (node.type === 'classifierEvaluate') {
2273
+ const observer = context.onLLMProfileAttempt;
2274
+ context.onLLMProfileAttempt = (event) => {
2275
+ if (event.family === 'classifier' && event.attemptIndex !== undefined)
2276
+ observedPhysicalCall = true;
2277
+ observer?.(event);
2278
+ };
2279
+ }
2220
2280
  const implementationProfileStart = this.#startRuntimeProfile();
2221
2281
  let results;
2222
2282
  try {
2283
+ accountingEntered = true;
2223
2284
  results = await instance.process(inputValues, context);
2285
+ accountingOutputs = results;
2224
2286
  }
2225
2287
  finally {
2226
2288
  this.#finishRuntimeProfile('nodeImplementation', implementationProfileStart);
@@ -2242,6 +2304,20 @@ export class GraphProcessor {
2242
2304
  return results;
2243
2305
  }
2244
2306
  finally {
2307
+ if (accountingEntered && !cacheHit) {
2308
+ try {
2309
+ if (['chat', 'chatLoop', 'chatGoogle', 'chatAnthropic', 'chatHuggingFace', 'getEmbedding'].includes(node.type)) {
2310
+ const cost = accountingOutputs?.['cost'];
2311
+ costLedger.observeLegacy(accountingKey, cost?.type === 'number' ? cost.value : undefined);
2312
+ }
2313
+ else if ((node.type === 'llmChatV2' || node.type === 'classifierEvaluate') && !observedPhysicalCall) {
2314
+ costLedger.markUnobserved(node.type === 'classifierEvaluate' ? 'decisionAI' : 'llm');
2315
+ }
2316
+ }
2317
+ catch {
2318
+ costLedger.markUnobserved(node.type === 'classifierEvaluate' ? 'decisionAI' : 'llm');
2319
+ }
2320
+ }
2245
2321
  if (!continuationFinalized) {
2246
2322
  this.#discardToolCallContinuation(processId, index);
2247
2323
  }
@@ -3532,6 +3608,10 @@ export class GraphProcessor {
3532
3608
  processor.#externalFunctions = this.#externalFunctions;
3533
3609
  processor.#contextValues = this.#contextValues;
3534
3610
  processor.#parent = this;
3611
+ processor.#projectCostScope = {
3612
+ parentLedger: this.#run.costLedger,
3613
+ startsProject: ordinary && invocation.startsProject,
3614
+ };
3535
3615
  processor.#recordingProjectScope = this.#recordingProjectScope;
3536
3616
  processor.#graphCallPath = this.#graphCallPath;
3537
3617
  processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
@@ -3615,6 +3695,8 @@ export class GraphProcessor {
3615
3695
  project: subprocessorProject,
3616
3696
  graphId: subGraphId,
3617
3697
  initialExecutionPlan,
3698
+ startsProject: subprocessorProject !== this.#project ||
3699
+ (node.type === 'subGraph' && Boolean(node.data.targetProjectId)),
3618
3700
  });
3619
3701
  }
3620
3702
  finally {
@@ -0,0 +1,156 @@
1
+ const diagnosticCodes = ['history-truncated', 'history-gap', 'event-too-large', 'owner-unavailable'];
2
+ export const LATEST_DEBUGGER_PATH = '/ws/latest-debugger';
3
+ const managedProcessMessages = {
4
+ codeConsole: true,
5
+ nodeStart: true,
6
+ nodeFinish: true,
7
+ nodeError: true,
8
+ nodeExcluded: true,
9
+ userInput: true,
10
+ start: true,
11
+ done: true,
12
+ abort: true,
13
+ graphAbort: true,
14
+ graphStart: true,
15
+ webAppStoragePatch: true,
16
+ graphFinish: true,
17
+ graphOutputsReady: true,
18
+ partialOutput: true,
19
+ progress: true,
20
+ llmCallFinished: true,
21
+ llmChatOutputSnapshot: true,
22
+ llmProfileAttempt: true,
23
+ toolCallFinished: true,
24
+ nodeOutputsCleared: true,
25
+ streamingOutputWatchSummary: true,
26
+ error: true,
27
+ graphError: true,
28
+ trace: true,
29
+ pause: true,
30
+ resume: true,
31
+ };
32
+ export function isLatestDebuggerExecutionMessage(message) {
33
+ return (Object.hasOwn(managedProcessMessages, message) || message === 'latest-settled' || message === 'latest-prompt-closed');
34
+ }
35
+ /** Preserve historical writer ordering while readers accept arbitrary JSON ordering. */
36
+ export function encodeLatestDebuggerEnvelope(serialized, scope, eventId) {
37
+ if (!scope && !eventId)
38
+ return serialized;
39
+ const metadata = JSON.stringify({
40
+ ...(eventId ? { rivetEventId: eventId } : {}),
41
+ ...(scope ? { rivetScope: scope } : {}),
42
+ });
43
+ return `${metadata.slice(0, -1)},${serialized.slice(1)}`;
44
+ }
45
+ export function createLatestDebuggerSession(channel) {
46
+ return { message: 'latest-session', data: { protocol: 2, channel, channelIsolation: true, runScopedControls: true } };
47
+ }
48
+ export function isLatestDebuggerSession(value) {
49
+ const frame = value;
50
+ return (frame?.message === 'latest-session' &&
51
+ frame.data?.protocol === 2 &&
52
+ (frame.data.channel === null ||
53
+ (typeof frame.data.channel === 'string' && /^[A-Za-z0-9_-]{1,32}$/.test(frame.data.channel))) &&
54
+ frame.data.channelIsolation === true &&
55
+ frame.data.runScopedControls === true);
56
+ }
57
+ /** Validate the routing contract only. Authored data and decoded sentinels stay intact. */
58
+ export function readLatestDebuggerExecution(value) {
59
+ const frame = value;
60
+ if (!frame || typeof frame.message !== 'string' || !isLatestDebuggerScope(frame.rivetScope))
61
+ return;
62
+ if (!isLatestDebuggerExecutionMessage(frame.message))
63
+ return;
64
+ if (frame.message === 'latest-prompt-closed') {
65
+ const id = frame.data?.promptId;
66
+ if (typeof id !== 'string' || id.length === 0 || id.length > 200)
67
+ return;
68
+ }
69
+ const root = frame.data?.execution?.rootRunId;
70
+ if (root !== undefined && root !== frame.rivetScope.rootRunId)
71
+ return;
72
+ return value;
73
+ }
74
+ export function createLatestDebuggerDiagnostic(code) {
75
+ return { message: 'latest-diagnostic', data: { protocol: 1, code } };
76
+ }
77
+ export function isLatestDebuggerDiagnostic(value) {
78
+ const frame = value;
79
+ return (frame?.message === 'latest-diagnostic' && frame.data?.protocol === 1 && diagnosticCodes.includes(frame.data.code));
80
+ }
81
+ export function createLatestDebuggerControlResult(commandId, result) {
82
+ return {
83
+ message: 'latest-control-result',
84
+ data: { status: result.status, ...(result.reason === undefined ? {} : { reason: result.reason }), commandId },
85
+ };
86
+ }
87
+ /** Validate only the wire control contract, never authored graph payloads. */
88
+ export function readLatestDebuggerControl(value) {
89
+ const message = value;
90
+ const data = message?.data;
91
+ if (message?.type !== 'latest-control' ||
92
+ !data ||
93
+ typeof data.commandId !== 'string' ||
94
+ !data.commandId ||
95
+ data.commandId.length > 200 ||
96
+ !isLatestDebuggerScope(data.target))
97
+ return;
98
+ if (data.action === 'pause' || data.action === 'resume' || data.action === 'abort')
99
+ return message;
100
+ if (data.action === 'user-input' &&
101
+ typeof data.promptId === 'string' &&
102
+ data.promptId.length > 0 &&
103
+ data.promptId.length <= 200 &&
104
+ data.answers?.type === 'string[]' &&
105
+ Array.isArray(data.answers.value) &&
106
+ data.answers.value.every((answer) => typeof answer === 'string'))
107
+ return message;
108
+ }
109
+ export function readLatestDebuggerEventId(value) {
110
+ if (!value || typeof value !== 'object')
111
+ return;
112
+ const id = value.rivetEventId;
113
+ return typeof id === 'string' && /^[a-z0-9:-]{1,200}$/.test(id) ? id : undefined;
114
+ }
115
+ export function isLatestDebuggerControlResult(value) {
116
+ const message = value;
117
+ return (message?.message === 'latest-control-result' &&
118
+ typeof message.data?.commandId === 'string' &&
119
+ message.data.commandId.length > 0 &&
120
+ message.data.commandId.length <= 200 &&
121
+ ['accepted', 'rejected', 'outcome-unknown'].includes(message.data.status) &&
122
+ (message.data.reason === undefined || typeof message.data.reason === 'string'));
123
+ }
124
+ /** Input is a decoded single path segment. Never decode it again. */
125
+ export function parseLatestEndpointSegment(segment) {
126
+ const [endpointName, channel, extra] = segment.split('@');
127
+ if (!endpointName ||
128
+ !/^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$/.test(endpointName) ||
129
+ extra !== undefined ||
130
+ (channel !== undefined && !/^[A-Za-z0-9_-]{1,32}$/.test(channel)))
131
+ throw new Error('Invalid latest endpoint or debugger channel');
132
+ return { endpointName, channel: channel ?? null };
133
+ }
134
+ /** URL.pathname is still encoded. Decode exactly once, rejecting path separators. */
135
+ export function parseLatestDebuggerPath(pathname) {
136
+ const decoded = decodeURIComponent(pathname);
137
+ if (decoded === LATEST_DEBUGGER_PATH)
138
+ return null;
139
+ if (!decoded.startsWith(`${LATEST_DEBUGGER_PATH}@`))
140
+ throw new Error('Invalid latest debugger path');
141
+ const channel = decoded.slice(LATEST_DEBUGGER_PATH.length + 1);
142
+ if (!/^[A-Za-z0-9_-]{1,32}$/.test(channel))
143
+ throw new Error('Invalid debugger channel');
144
+ return channel;
145
+ }
146
+ export function isLatestDebuggerScope(value) {
147
+ if (!value || typeof value !== 'object')
148
+ return false;
149
+ const scope = value;
150
+ return ((scope.channel === null || (typeof scope.channel === 'string' && /^[A-Za-z0-9_-]{1,32}$/.test(scope.channel))) &&
151
+ [scope.rootRunId, scope.projectId, scope.owner, scope.incarnation].every((v) => typeof v === 'string' && v.length > 0 && v.length <= 200) &&
152
+ (scope.promptId === undefined ||
153
+ (typeof scope.promptId === 'string' && scope.promptId.length > 0 && scope.promptId.length <= 200)) &&
154
+ (scope.admittedAt === undefined || (Number.isSafeInteger(scope.admittedAt) && scope.admittedAt >= 0)) &&
155
+ (scope.promptLifecycle === undefined || scope.promptLifecycle === 1));
156
+ }
@@ -67,6 +67,8 @@ import { graphCallPathNode } from './nodes/GraphCallPathNode.js';
67
67
  export * from './nodes/GraphCallPathNode.js';
68
68
  import { projectNameNode } from './nodes/ProjectNameNode.js';
69
69
  export * from './nodes/ProjectNameNode.js';
70
+ import { aiCostNode } from './nodes/AICostNode.js';
71
+ export * from './nodes/AICostNode.js';
70
72
  import { coalesceNode } from './nodes/CoalesceNode.js';
71
73
  export * from './nodes/CoalesceNode.js';
72
74
  import { coalesceNewNode } from './nodes/CoalesceNewNode.js';
@@ -268,6 +270,7 @@ export const registerBuiltInNodes = (registry) => {
268
270
  .register(contextNode)
269
271
  .register(graphCallPathNode)
270
272
  .register(projectNameNode)
273
+ .register(aiCostNode)
271
274
  .register(coalesceNode)
272
275
  .register(coalesceNewNode)
273
276
  .register(didRunNode)
@@ -0,0 +1,89 @@
1
+ const emptySummary = () => ({ knownCostUsd: 0, hasKnownCost: false, hasUnknownCost: false });
2
+ function addCost(summary, cost) {
3
+ if (cost === null)
4
+ summary.hasUnknownCost = true;
5
+ else {
6
+ summary.knownCostUsd += cost;
7
+ summary.hasKnownCost = true;
8
+ }
9
+ }
10
+ function readSummary(summary, executionPending = false) {
11
+ if (!Number.isFinite(summary.knownCostUsd))
12
+ return { status: 'unknown', knownCostUsd: null };
13
+ if (!summary.hasUnknownCost && !executionPending)
14
+ return { status: 'complete', knownCostUsd: summary.knownCostUsd };
15
+ if (!summary.hasKnownCost)
16
+ return { status: 'unknown', knownCostUsd: null };
17
+ return { status: 'partial', knownCostUsd: summary.knownCostUsd };
18
+ }
19
+ /** One identity set per root run; each scope maintains its inclusive subtotals. */
20
+ export class RunCostLedger {
21
+ #parent;
22
+ #seenCalls;
23
+ #costs = { llm: emptySummary(), decisionAI: emptySummary(), total: emptySummary() };
24
+ constructor(parent) {
25
+ this.#parent = parent;
26
+ this.#seenCalls = parent ? parent.#seenCalls : new Set();
27
+ }
28
+ createProjectScope() {
29
+ return new RunCostLedger(this);
30
+ }
31
+ observeChat(event) {
32
+ if (typeof event.callId !== 'string' || !event.callId) {
33
+ this.markUnobserved('llm');
34
+ return;
35
+ }
36
+ this.#record(`llm:${event.callId}`, 'llm', event.pricing.status === 'known' ? event.pricing.costUsd : undefined);
37
+ }
38
+ observeClassifier(event) {
39
+ if (event.family !== 'classifier' || event.attemptIndex === undefined)
40
+ return;
41
+ if (typeof event.eventId !== 'string' ||
42
+ !event.eventId ||
43
+ !Number.isSafeInteger(event.attemptIndex) ||
44
+ event.attemptIndex < 0) {
45
+ this.markUnobserved('decisionAI');
46
+ return;
47
+ }
48
+ this.#record(`decision:${event.eventId}`, 'decisionAI', event.classifierUsage?.estimatedCostUsd);
49
+ }
50
+ /** Legacy Chat does not expose complete per-attempt accounting. */
51
+ observeLegacy(key, value) {
52
+ if (typeof value === 'number' && Number.isFinite(value) && value > 0)
53
+ this.#record(`legacy:${key}`, 'llm', value);
54
+ this.markUnobserved('llm');
55
+ }
56
+ markUnobserved(family) {
57
+ for (let scope = this; scope; scope = scope.#parent) {
58
+ if (family)
59
+ scope.#costs[family].hasUnknownCost = true;
60
+ else {
61
+ scope.#costs.llm.hasUnknownCost = true;
62
+ scope.#costs.decisionAI.hasUnknownCost = true;
63
+ }
64
+ scope.#costs.total.hasUnknownCost = true;
65
+ }
66
+ }
67
+ snapshot(executionPending = false) {
68
+ return readSummary(this.#costs.total, executionPending);
69
+ }
70
+ /** Observed amounts now, not a prediction of unfinished or future calls. */
71
+ breakdown() {
72
+ return {
73
+ llm: readSummary(this.#costs.llm),
74
+ decisionAI: readSummary(this.#costs.decisionAI),
75
+ total: this.snapshot(),
76
+ };
77
+ }
78
+ #record(id, family, value) {
79
+ if (this.#seenCalls.has(id))
80
+ return;
81
+ this.#seenCalls.add(id);
82
+ const cost = typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;
83
+ for (let scope = this; scope; scope = scope.#parent) {
84
+ // Preserve physical-observation order for both root and subtree totals.
85
+ addCost(scope.#costs.total, cost);
86
+ addCost(scope.#costs[family], cost);
87
+ }
88
+ }
89
+ }
@@ -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' },
@@ -1,4 +1,5 @@
1
1
  import { coerceTypeOptional } from '../../utils/coerceType.js';
2
+ import { validateTokenPricing } from '../tokenPricing.js';
2
3
  import { getInputOrData } from '../../utils/inputs.js';
3
4
  import { resolveChatV2Credential } from './chatV2ProviderProfile.js';
4
5
  import { resolveLLMChatV2ExtraProviderOptions, resolveLLMChatV2GenerationParameters, resolveLLMChatV2Headers, } from './chatV2RuntimeOptions.js';
@@ -81,7 +82,7 @@ export function resolveLLMProfileNodeValue(params) {
81
82
  return {
82
83
  version: LLM_PROFILE_VALUE_VERSION,
83
84
  credential,
84
- configuration,
85
+ configuration: { ...configuration, tokenPricing: validateTokenPricing(configuration.tokenPricing) },
85
86
  ...(profileName === '' ? {} : { profileName }),
86
87
  ...(projectId == null
87
88
  ? {}