@valerypopoff/rivet2-core 2.25.0 → 2.27.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.
- package/dist/cjs/bundle.cjs +536 -222
- package/dist/cjs/bundle.cjs.map +4 -4
- package/dist/cjs/webAppRuntime.cjs.map +1 -1
- package/dist/esm/exports.js +1 -0
- package/dist/esm/model/GraphExecutionState.js +1 -1
- package/dist/esm/model/GraphProcessor.js +30 -9
- package/dist/esm/model/LatestDebuggerProtocol.js +179 -0
- package/dist/esm/model/Nodes.js +3 -0
- package/dist/esm/model/RunCostLedger.js +63 -32
- package/dist/esm/model/classifier/baseten.js +2 -1
- package/dist/esm/model/classifier/providers.js +55 -30
- package/dist/esm/model/nodes/AICostNode.js +56 -0
- package/dist/types/exports.d.ts +1 -0
- package/dist/types/model/GraphExecutionState.d.ts +1 -0
- package/dist/types/model/LatestDebuggerProtocol.d.ts +121 -0
- package/dist/types/model/Nodes.d.ts +3 -2
- package/dist/types/model/ProcessContext.d.ts +3 -0
- package/dist/types/model/RunCostLedger.d.ts +12 -2
- package/dist/types/model/classifier/baseten.d.ts +2 -2
- package/dist/types/model/classifier/providers.d.ts +11 -11
- package/dist/types/model/classifier/types.d.ts +5 -0
- package/dist/types/model/nodes/AICostNode.d.ts +15 -0
- package/package.json +1 -1
package/dist/esm/exports.js
CHANGED
|
@@ -60,7 +60,7 @@ export class GraphInvocationState {
|
|
|
60
60
|
this.successfulAbortTerminalProcessIds = new Set();
|
|
61
61
|
this.totalCost = 0;
|
|
62
62
|
this.costBreakdown = undefined;
|
|
63
|
-
this.costLedger = new RunCostLedger();
|
|
63
|
+
this.costLedger = options.costLedger ?? new RunCostLedger();
|
|
64
64
|
this.nodeAbortControllers = new Map();
|
|
65
65
|
this.loadedProjects = options.loadedProjects;
|
|
66
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();
|
|
@@ -888,9 +895,12 @@ export class GraphProcessor {
|
|
|
888
895
|
const hostLLMChatOutputSnapshotObserver = this.getRootProcessor().#run.context.onLLMChatOutputSnapshot;
|
|
889
896
|
const hostLLMProfileAttemptObserver = this.getRootProcessor().#run.context.onLLMProfileAttempt;
|
|
890
897
|
// Capture the invocation's ledger, not a later run that reuses this processor.
|
|
891
|
-
const costLedger = this
|
|
898
|
+
const costLedger = this.#run.costLedger;
|
|
899
|
+
const { rootRunId, graphRunId } = this.#run;
|
|
900
|
+
const isCurrentInvocation = () => this.#run.rootRunId === rootRunId && this.#run.graphRunId === graphRunId;
|
|
892
901
|
this.#run.nodeProcessContextBase = {
|
|
893
902
|
...this.#run.context,
|
|
903
|
+
getRunCostBreakdown: () => costLedger.breakdown(),
|
|
894
904
|
abortGraph: (error) => {
|
|
895
905
|
void (this.#abortOwnerOverride ?? this).abort(error === undefined, error);
|
|
896
906
|
},
|
|
@@ -912,7 +922,7 @@ export class GraphProcessor {
|
|
|
912
922
|
costLedger.observeChat(event);
|
|
913
923
|
}
|
|
914
924
|
catch {
|
|
915
|
-
costLedger.markUnobserved();
|
|
925
|
+
costLedger.markUnobserved('llm');
|
|
916
926
|
}
|
|
917
927
|
try {
|
|
918
928
|
const observerResult = hostChatV2Observer?.(event);
|
|
@@ -923,6 +933,8 @@ export class GraphProcessor {
|
|
|
923
933
|
catch {
|
|
924
934
|
// Host observers must never change graph execution.
|
|
925
935
|
}
|
|
936
|
+
if (!isCurrentInvocation())
|
|
937
|
+
return;
|
|
926
938
|
// Runtime traces carry only the normalized, provider-neutral usage
|
|
927
939
|
// contract. The host observer above retains its existing raw accounting
|
|
928
940
|
// callback, but provider-shaped usage never enters recordings or remote
|
|
@@ -940,14 +952,15 @@ export class GraphProcessor {
|
|
|
940
952
|
catch {
|
|
941
953
|
// Snapshot observers are display-only and must never affect execution.
|
|
942
954
|
}
|
|
943
|
-
|
|
955
|
+
if (isCurrentInvocation())
|
|
956
|
+
emitDetached(this.#emitter, 'llmChatOutputSnapshot', this.#withExecution(event));
|
|
944
957
|
},
|
|
945
958
|
onLLMProfileAttempt: (event) => {
|
|
946
959
|
try {
|
|
947
960
|
costLedger.observeClassifier(event);
|
|
948
961
|
}
|
|
949
962
|
catch {
|
|
950
|
-
costLedger.markUnobserved();
|
|
963
|
+
costLedger.markUnobserved('decisionAI');
|
|
951
964
|
}
|
|
952
965
|
try {
|
|
953
966
|
const observerResult = hostLLMProfileAttemptObserver?.(event);
|
|
@@ -958,10 +971,12 @@ export class GraphProcessor {
|
|
|
958
971
|
catch {
|
|
959
972
|
// Host observers must never change graph execution.
|
|
960
973
|
}
|
|
961
|
-
|
|
974
|
+
if (isCurrentInvocation())
|
|
975
|
+
emitDetached(this.#emitter, 'llmProfileAttempt', this.#withExecution(event));
|
|
962
976
|
},
|
|
963
977
|
onToolCallFinished: (event) => {
|
|
964
|
-
|
|
978
|
+
if (isCurrentInvocation())
|
|
979
|
+
emitDetached(this.#emitter, 'toolCallFinished', this.#withExecution(event));
|
|
965
980
|
},
|
|
966
981
|
project: this.#project,
|
|
967
982
|
raiseEvent: (event, data) => {
|
|
@@ -2223,7 +2238,7 @@ export class GraphProcessor {
|
|
|
2223
2238
|
nodeAbortController.abort(getAbortSignalReason(this.#run.abortController.signal));
|
|
2224
2239
|
}
|
|
2225
2240
|
let continuationFinalized = false;
|
|
2226
|
-
const costLedger = this
|
|
2241
|
+
const costLedger = this.#run.costLedger;
|
|
2227
2242
|
const accountingKey = `${this.#run.graphRunId}:${processId}:${index}`;
|
|
2228
2243
|
let accountingEntered = false;
|
|
2229
2244
|
let observedPhysicalCall = false;
|
|
@@ -2296,11 +2311,11 @@ export class GraphProcessor {
|
|
|
2296
2311
|
costLedger.observeLegacy(accountingKey, cost?.type === 'number' ? cost.value : undefined);
|
|
2297
2312
|
}
|
|
2298
2313
|
else if ((node.type === 'llmChatV2' || node.type === 'classifierEvaluate') && !observedPhysicalCall) {
|
|
2299
|
-
costLedger.markUnobserved();
|
|
2314
|
+
costLedger.markUnobserved(node.type === 'classifierEvaluate' ? 'decisionAI' : 'llm');
|
|
2300
2315
|
}
|
|
2301
2316
|
}
|
|
2302
2317
|
catch {
|
|
2303
|
-
costLedger.markUnobserved();
|
|
2318
|
+
costLedger.markUnobserved(node.type === 'classifierEvaluate' ? 'decisionAI' : 'llm');
|
|
2304
2319
|
}
|
|
2305
2320
|
}
|
|
2306
2321
|
if (!continuationFinalized) {
|
|
@@ -3593,6 +3608,10 @@ export class GraphProcessor {
|
|
|
3593
3608
|
processor.#externalFunctions = this.#externalFunctions;
|
|
3594
3609
|
processor.#contextValues = this.#contextValues;
|
|
3595
3610
|
processor.#parent = this;
|
|
3611
|
+
processor.#projectCostScope = {
|
|
3612
|
+
parentLedger: this.#run.costLedger,
|
|
3613
|
+
startsProject: ordinary && invocation.startsProject,
|
|
3614
|
+
};
|
|
3596
3615
|
processor.#recordingProjectScope = this.#recordingProjectScope;
|
|
3597
3616
|
processor.#graphCallPath = this.#graphCallPath;
|
|
3598
3617
|
processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
|
|
@@ -3676,6 +3695,8 @@ export class GraphProcessor {
|
|
|
3676
3695
|
project: subprocessorProject,
|
|
3677
3696
|
graphId: subGraphId,
|
|
3678
3697
|
initialExecutionPlan,
|
|
3698
|
+
startsProject: subprocessorProject !== this.#project ||
|
|
3699
|
+
(node.type === 'subGraph' && Boolean(node.data.targetProjectId)),
|
|
3679
3700
|
});
|
|
3680
3701
|
}
|
|
3681
3702
|
finally {
|
|
@@ -0,0 +1,179 @@
|
|
|
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, history = false) {
|
|
37
|
+
if (!scope && !eventId && !history)
|
|
38
|
+
return serialized;
|
|
39
|
+
const metadata = JSON.stringify({
|
|
40
|
+
...(eventId ? { rivetEventId: eventId } : {}),
|
|
41
|
+
...(scope ? { rivetScope: scope } : {}),
|
|
42
|
+
...(history ? { rivetHistory: history } : {}),
|
|
43
|
+
});
|
|
44
|
+
return `${metadata.slice(0, -1)},${serialized.slice(1)}`;
|
|
45
|
+
}
|
|
46
|
+
export function createLatestDebuggerSession(channel, historyThrough) {
|
|
47
|
+
return {
|
|
48
|
+
message: 'latest-session',
|
|
49
|
+
data: {
|
|
50
|
+
protocol: 2,
|
|
51
|
+
channel,
|
|
52
|
+
channelIsolation: true,
|
|
53
|
+
runScopedControls: true,
|
|
54
|
+
...(historyThrough ? { historyThrough } : {}),
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
export function isLatestDebuggerSession(value) {
|
|
59
|
+
const frame = value;
|
|
60
|
+
return (frame?.message === 'latest-session' &&
|
|
61
|
+
frame.data?.protocol === 2 &&
|
|
62
|
+
(frame.data.channel === null ||
|
|
63
|
+
(typeof frame.data.channel === 'string' && /^[A-Za-z0-9_-]{1,32}$/.test(frame.data.channel))) &&
|
|
64
|
+
frame.data.channelIsolation === true &&
|
|
65
|
+
frame.data.runScopedControls === true &&
|
|
66
|
+
(frame.data.historyThrough === undefined ||
|
|
67
|
+
(Array.isArray(frame.data.historyThrough) &&
|
|
68
|
+
frame.data.historyThrough.length <= 8192 &&
|
|
69
|
+
frame.data.historyThrough.every((id) => readLatestDebuggerEventPosition(id) !== undefined))));
|
|
70
|
+
}
|
|
71
|
+
/** Validate the routing contract only. Authored data and decoded sentinels stay intact. */
|
|
72
|
+
export function readLatestDebuggerExecution(value) {
|
|
73
|
+
const frame = value;
|
|
74
|
+
if (!frame || typeof frame.message !== 'string' || !isLatestDebuggerScope(frame.rivetScope))
|
|
75
|
+
return;
|
|
76
|
+
if (!isLatestDebuggerExecutionMessage(frame.message))
|
|
77
|
+
return;
|
|
78
|
+
if (frame.message === 'latest-prompt-closed') {
|
|
79
|
+
const id = frame.data?.promptId;
|
|
80
|
+
if (typeof id !== 'string' || id.length === 0 || id.length > 200)
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
const root = frame.data?.execution?.rootRunId;
|
|
84
|
+
if (root !== undefined && root !== frame.rivetScope.rootRunId)
|
|
85
|
+
return;
|
|
86
|
+
return value;
|
|
87
|
+
}
|
|
88
|
+
export function createLatestDebuggerDiagnostic(code) {
|
|
89
|
+
return { message: 'latest-diagnostic', data: { protocol: 1, code } };
|
|
90
|
+
}
|
|
91
|
+
export function isLatestDebuggerDiagnostic(value) {
|
|
92
|
+
const frame = value;
|
|
93
|
+
return (frame?.message === 'latest-diagnostic' && frame.data?.protocol === 1 && diagnosticCodes.includes(frame.data.code));
|
|
94
|
+
}
|
|
95
|
+
export function createLatestDebuggerControlResult(commandId, result) {
|
|
96
|
+
return {
|
|
97
|
+
message: 'latest-control-result',
|
|
98
|
+
data: { status: result.status, ...(result.reason === undefined ? {} : { reason: result.reason }), commandId },
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
/** Validate only the wire control contract, never authored graph payloads. */
|
|
102
|
+
export function readLatestDebuggerControl(value) {
|
|
103
|
+
const message = value;
|
|
104
|
+
const data = message?.data;
|
|
105
|
+
if (message?.type !== 'latest-control' ||
|
|
106
|
+
!data ||
|
|
107
|
+
typeof data.commandId !== 'string' ||
|
|
108
|
+
!data.commandId ||
|
|
109
|
+
data.commandId.length > 200 ||
|
|
110
|
+
!isLatestDebuggerScope(data.target))
|
|
111
|
+
return;
|
|
112
|
+
if (data.action === 'pause' || data.action === 'resume' || data.action === 'abort')
|
|
113
|
+
return message;
|
|
114
|
+
if (data.action === 'user-input' &&
|
|
115
|
+
typeof data.promptId === 'string' &&
|
|
116
|
+
data.promptId.length > 0 &&
|
|
117
|
+
data.promptId.length <= 200 &&
|
|
118
|
+
data.answers?.type === 'string[]' &&
|
|
119
|
+
Array.isArray(data.answers.value) &&
|
|
120
|
+
data.answers.value.every((answer) => typeof answer === 'string'))
|
|
121
|
+
return message;
|
|
122
|
+
}
|
|
123
|
+
export function readLatestDebuggerEventId(value) {
|
|
124
|
+
if (!value || typeof value !== 'object')
|
|
125
|
+
return;
|
|
126
|
+
const id = value.rivetEventId;
|
|
127
|
+
return typeof id === 'string' && /^[a-z0-9:-]{1,200}$/.test(id) ? id : undefined;
|
|
128
|
+
}
|
|
129
|
+
export function readLatestDebuggerEventPosition(value) {
|
|
130
|
+
if (typeof value !== 'string' || value.length > 200 || !/^[a-z0-9:-]+:[1-9]\d{0,15}$/.test(value))
|
|
131
|
+
return;
|
|
132
|
+
const split = value.lastIndexOf(':');
|
|
133
|
+
const sequence = Number(value.slice(split + 1));
|
|
134
|
+
if (!Number.isSafeInteger(sequence))
|
|
135
|
+
return;
|
|
136
|
+
return { origin: value.slice(0, split), sequence };
|
|
137
|
+
}
|
|
138
|
+
export function isLatestDebuggerControlResult(value) {
|
|
139
|
+
const message = value;
|
|
140
|
+
return (message?.message === 'latest-control-result' &&
|
|
141
|
+
typeof message.data?.commandId === 'string' &&
|
|
142
|
+
message.data.commandId.length > 0 &&
|
|
143
|
+
message.data.commandId.length <= 200 &&
|
|
144
|
+
['accepted', 'rejected', 'outcome-unknown'].includes(message.data.status) &&
|
|
145
|
+
(message.data.reason === undefined || typeof message.data.reason === 'string'));
|
|
146
|
+
}
|
|
147
|
+
/** Input is a decoded single path segment. Never decode it again. */
|
|
148
|
+
export function parseLatestEndpointSegment(segment) {
|
|
149
|
+
const [endpointName, channel, extra] = segment.split('@');
|
|
150
|
+
if (!endpointName ||
|
|
151
|
+
!/^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$/.test(endpointName) ||
|
|
152
|
+
extra !== undefined ||
|
|
153
|
+
(channel !== undefined && !/^[A-Za-z0-9_-]{1,32}$/.test(channel)))
|
|
154
|
+
throw new Error('Invalid latest endpoint or debugger channel');
|
|
155
|
+
return { endpointName, channel: channel ?? null };
|
|
156
|
+
}
|
|
157
|
+
/** URL.pathname is still encoded. Decode exactly once, rejecting path separators. */
|
|
158
|
+
export function parseLatestDebuggerPath(pathname) {
|
|
159
|
+
const decoded = decodeURIComponent(pathname);
|
|
160
|
+
if (decoded === LATEST_DEBUGGER_PATH)
|
|
161
|
+
return null;
|
|
162
|
+
if (!decoded.startsWith(`${LATEST_DEBUGGER_PATH}@`))
|
|
163
|
+
throw new Error('Invalid latest debugger path');
|
|
164
|
+
const channel = decoded.slice(LATEST_DEBUGGER_PATH.length + 1);
|
|
165
|
+
if (!/^[A-Za-z0-9_-]{1,32}$/.test(channel))
|
|
166
|
+
throw new Error('Invalid debugger channel');
|
|
167
|
+
return channel;
|
|
168
|
+
}
|
|
169
|
+
export function isLatestDebuggerScope(value) {
|
|
170
|
+
if (!value || typeof value !== 'object')
|
|
171
|
+
return false;
|
|
172
|
+
const scope = value;
|
|
173
|
+
return ((scope.channel === null || (typeof scope.channel === 'string' && /^[A-Za-z0-9_-]{1,32}$/.test(scope.channel))) &&
|
|
174
|
+
[scope.rootRunId, scope.projectId, scope.owner, scope.incarnation].every((v) => typeof v === 'string' && v.length > 0 && v.length <= 200) &&
|
|
175
|
+
(scope.promptId === undefined ||
|
|
176
|
+
(typeof scope.promptId === 'string' && scope.promptId.length > 0 && scope.promptId.length <= 200)) &&
|
|
177
|
+
(scope.admittedAt === undefined || (Number.isSafeInteger(scope.admittedAt) && scope.admittedAt >= 0)) &&
|
|
178
|
+
(scope.promptLifecycle === undefined || scope.promptLifecycle === 1));
|
|
179
|
+
}
|
package/dist/esm/model/Nodes.js
CHANGED
|
@@ -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)
|
|
@@ -1,13 +1,39 @@
|
|
|
1
|
-
|
|
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. */
|
|
2
20
|
export class RunCostLedger {
|
|
3
|
-
#
|
|
4
|
-
#
|
|
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
|
+
}
|
|
5
31
|
observeChat(event) {
|
|
6
32
|
if (typeof event.callId !== 'string' || !event.callId) {
|
|
7
|
-
this.markUnobserved();
|
|
33
|
+
this.markUnobserved('llm');
|
|
8
34
|
return;
|
|
9
35
|
}
|
|
10
|
-
this.#record(`llm:${event.callId}`, event.pricing.status === 'known' ? event.pricing.costUsd : undefined);
|
|
36
|
+
this.#record(`llm:${event.callId}`, 'llm', event.pricing.status === 'known' ? event.pricing.costUsd : undefined);
|
|
11
37
|
}
|
|
12
38
|
observeClassifier(event) {
|
|
13
39
|
if (event.family !== 'classifier' || event.attemptIndex === undefined)
|
|
@@ -16,43 +42,48 @@ export class RunCostLedger {
|
|
|
16
42
|
!event.eventId ||
|
|
17
43
|
!Number.isSafeInteger(event.attemptIndex) ||
|
|
18
44
|
event.attemptIndex < 0) {
|
|
19
|
-
this.markUnobserved();
|
|
45
|
+
this.markUnobserved('decisionAI');
|
|
20
46
|
return;
|
|
21
47
|
}
|
|
22
|
-
this.#record(`decision:${event.eventId}`, event.classifierUsage?.estimatedCostUsd);
|
|
48
|
+
this.#record(`decision:${event.eventId}`, 'decisionAI', event.classifierUsage?.estimatedCostUsd);
|
|
23
49
|
}
|
|
24
50
|
/** Legacy Chat does not expose complete per-attempt accounting. */
|
|
25
51
|
observeLegacy(key, value) {
|
|
26
52
|
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;
|
|
53
|
+
this.#record(`legacy:${key}`, 'llm', value);
|
|
54
|
+
this.markUnobserved('llm');
|
|
32
55
|
}
|
|
33
|
-
|
|
34
|
-
let
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
for (const cost of this.#calls.values()) {
|
|
38
|
-
if (cost === null)
|
|
39
|
-
hasUnknownCost = true;
|
|
56
|
+
markUnobserved(family) {
|
|
57
|
+
for (let scope = this; scope; scope = scope.#parent) {
|
|
58
|
+
if (family)
|
|
59
|
+
scope.#costs[family].hasUnknownCost = true;
|
|
40
60
|
else {
|
|
41
|
-
|
|
42
|
-
|
|
61
|
+
scope.#costs.llm.hasUnknownCost = true;
|
|
62
|
+
scope.#costs.decisionAI.hasUnknownCost = true;
|
|
43
63
|
}
|
|
64
|
+
scope.#costs.total.hasUnknownCost = true;
|
|
44
65
|
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
return {
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
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))
|
|
55
80
|
return;
|
|
56
|
-
this.#
|
|
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
|
+
}
|
|
57
88
|
}
|
|
58
89
|
}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { inspectClassifierImage } from './images.js';
|
|
2
|
-
/** Native Model API slugs, not Hugging Face or gateway IDs. Verified 2026-10-
|
|
2
|
+
/** Native Model API slugs, not Hugging Face or gateway IDs. Verified 2026-10-30. */
|
|
3
3
|
export const BASETEN_DECISION_MODELS = [
|
|
4
4
|
'decision-models/baseten-elephant-9b-latest',
|
|
5
5
|
'decision-models/baseten-mammoth-27b-latest',
|
|
6
|
+
'decision-models/baseten-joey-2b-latest',
|
|
6
7
|
];
|
|
7
8
|
/** Baseten uses inline user-message image parts, never top-level images/placeholders. */
|
|
8
9
|
export function basetenDecisionState(state) {
|
|
@@ -29,7 +29,6 @@ export const LIQUID_TOKEN_PRICING = {
|
|
|
29
29
|
inputPerMillionTokens: 0.02,
|
|
30
30
|
outputPerMillionTokens: 0,
|
|
31
31
|
};
|
|
32
|
-
const TOKENS_PER_MILLION = 1_000_000;
|
|
33
32
|
const MAX_AUTOMATIC_ATTEMPTS = 3;
|
|
34
33
|
const MAX_TIMER_DELAY_MS = 2_147_483_647;
|
|
35
34
|
const RETRYABLE_STATUSES = new Set([429, 529]);
|
|
@@ -56,7 +55,11 @@ export const jevClassifierProvider = createClassifierProvider({
|
|
|
56
55
|
id: 'jev',
|
|
57
56
|
label: 'Jev',
|
|
58
57
|
defaultModel: 'jev-latest',
|
|
59
|
-
modelOptions: ['jev-latest', 'jev-preview', 'jev-1.14.0', 'jev-1.13.0'].map((value) => ({
|
|
58
|
+
modelOptions: ['jev-latest', 'jev-preview', 'jev-1.14.0', 'jev-1.13.0'].map((value) => ({
|
|
59
|
+
value,
|
|
60
|
+
label: value,
|
|
61
|
+
aggregateTokenUsageOnly: true,
|
|
62
|
+
})),
|
|
60
63
|
modelHelp: 'Jev images are experimental: use still PNG/JPEG, 280–1568 pixels per side. Image requests enable TypeSafe’s experimental image API.',
|
|
61
64
|
credentialNames: JEV_DEFAULT_CREDENTIAL_NAMES,
|
|
62
65
|
endpoint: JEV_SYSTEM_ONE_ENDPOINT,
|
|
@@ -86,7 +89,7 @@ export const liquidClassifierProvider = createApiCompatibleClassifierProvider({
|
|
|
86
89
|
id: 'liquid',
|
|
87
90
|
label: 'Liquid AI',
|
|
88
91
|
defaultModel: 'd1',
|
|
89
|
-
modelOptions: ['d1', 'd1.1'].map((value) => ({ value, label: value })),
|
|
92
|
+
modelOptions: ['d1', 'd1.1'].map((value) => ({ value, label: value, aggregateTokenUsageOnly: true })),
|
|
90
93
|
modelHelp: 'Images belong in shared State, not Question Instructions.',
|
|
91
94
|
credentialNames: LIQUID_DEFAULT_CREDENTIAL_NAMES,
|
|
92
95
|
endpoint: LIQUID_SYSTEM_ONE_ENDPOINT,
|
|
@@ -105,7 +108,9 @@ export const openrouterClassifierProvider = createApiCompatibleClassifierProvide
|
|
|
105
108
|
id: 'openrouter',
|
|
106
109
|
label: 'OpenRouter',
|
|
107
110
|
defaultModel: 'microsoft/microsoft-decision-1',
|
|
108
|
-
modelOptions: [
|
|
111
|
+
modelOptions: [
|
|
112
|
+
{ value: 'microsoft/microsoft-decision-1', label: 'Microsoft Decision-1 (9b)', aggregateTokenUsageOnly: true },
|
|
113
|
+
],
|
|
109
114
|
credentialNames: OPENROUTER_DEFAULT_CREDENTIAL_NAMES,
|
|
110
115
|
endpoint: OPENROUTER_DECISIONS_ENDPOINT,
|
|
111
116
|
modelPricing: [
|
|
@@ -115,7 +120,7 @@ export const openrouterClassifierProvider = createApiCompatibleClassifierProvide
|
|
|
115
120
|
},
|
|
116
121
|
],
|
|
117
122
|
});
|
|
118
|
-
/** Decisions-specific rates
|
|
123
|
+
/** Decisions-specific rates; cache reads/writes follow standard Luna ratios (verified 2026-10-30).
|
|
119
124
|
* https://developers.openai.com/api/docs/guides/decisions#pricing-and-availability
|
|
120
125
|
*/
|
|
121
126
|
export const openaiClassifierProvider = createClassifierProvider({
|
|
@@ -125,6 +130,7 @@ export const openaiClassifierProvider = createClassifierProvider({
|
|
|
125
130
|
modelOptions: [{ value: 'gpt-6-luna', label: 'gpt-6-luna' }],
|
|
126
131
|
credentialNames: OPENAI_DEFAULT_CREDENTIAL_NAMES,
|
|
127
132
|
browserExecutionSupported: false,
|
|
133
|
+
cacheTokenUsageSupported: true,
|
|
128
134
|
endpoint: OPENAI_DECISIONS_ENDPOINT,
|
|
129
135
|
supportsImages: (model) => model === 'gpt-6-luna',
|
|
130
136
|
supportsQuestionImages: (model) => model === 'gpt-6-luna',
|
|
@@ -134,7 +140,15 @@ export const openaiClassifierProvider = createClassifierProvider({
|
|
|
134
140
|
pricing: {
|
|
135
141
|
inputPerMillionTokens: 0.1,
|
|
136
142
|
outputPerMillionTokens: 0,
|
|
137
|
-
|
|
143
|
+
cacheReadPerMillionTokens: 0.01,
|
|
144
|
+
cacheWritePerMillionTokens: 0.125,
|
|
145
|
+
longContext: {
|
|
146
|
+
aboveInputTokens: 272_000,
|
|
147
|
+
inputPerMillionTokens: 0.2,
|
|
148
|
+
outputPerMillionTokens: 0,
|
|
149
|
+
cacheReadPerMillionTokens: 0.02,
|
|
150
|
+
cacheWritePerMillionTokens: 0.25,
|
|
151
|
+
},
|
|
138
152
|
},
|
|
139
153
|
},
|
|
140
154
|
],
|
|
@@ -146,7 +160,11 @@ export const perplexityClassifierProvider = createClassifierProvider({
|
|
|
146
160
|
id: 'perplexity',
|
|
147
161
|
label: 'Perplexity',
|
|
148
162
|
defaultModel: 'pplx-decider-v1.1-27b',
|
|
149
|
-
modelOptions: PERPLEXITY_DECISION_MODELS.map((value) => ({
|
|
163
|
+
modelOptions: PERPLEXITY_DECISION_MODELS.map((value) => ({
|
|
164
|
+
value,
|
|
165
|
+
label: value.replace(/-27b$/, ' (27b)'),
|
|
166
|
+
aggregateTokenUsageOnly: true,
|
|
167
|
+
})),
|
|
150
168
|
credentialNames: PERPLEXITY_DEFAULT_CREDENTIAL_NAMES,
|
|
151
169
|
browserExecutionSupported: false,
|
|
152
170
|
endpoint: PERPLEXITY_DECISIONS_ENDPOINT,
|
|
@@ -172,7 +190,7 @@ export const subqClassifierProvider = createClassifierProvider({
|
|
|
172
190
|
id: 'subq',
|
|
173
191
|
label: 'SubQ',
|
|
174
192
|
defaultModel: 'subq-snap-1.1',
|
|
175
|
-
modelOptions: SUBQ_DECISION_MODELS.map((value) => ({ value, label: value })),
|
|
193
|
+
modelOptions: SUBQ_DECISION_MODELS.map((value) => ({ value, label: value, aggregateTokenUsageOnly: true })),
|
|
176
194
|
credentialNames: SUBQ_DEFAULT_CREDENTIAL_NAMES,
|
|
177
195
|
browserExecutionSupported: false,
|
|
178
196
|
endpoint: SUBQ_DECISIONS_ENDPOINT,
|
|
@@ -193,8 +211,9 @@ export const basetenClassifierProvider = createClassifierProvider({
|
|
|
193
211
|
label: 'Baseten',
|
|
194
212
|
defaultModel: BASETEN_DECISION_MODELS[0],
|
|
195
213
|
modelOptions: [
|
|
196
|
-
{ value: BASETEN_DECISION_MODELS[0], label: 'Elephant-1' },
|
|
197
|
-
{ value: BASETEN_DECISION_MODELS[1], label: 'Mammoth-1' },
|
|
214
|
+
{ value: BASETEN_DECISION_MODELS[0], label: 'Elephant-1 (9b)', aggregateTokenUsageOnly: true },
|
|
215
|
+
{ value: BASETEN_DECISION_MODELS[1], label: 'Mammoth-1 (27b)', aggregateTokenUsageOnly: true },
|
|
216
|
+
{ value: BASETEN_DECISION_MODELS[2], label: 'Joey-1 (2b)', aggregateTokenUsageOnly: true },
|
|
198
217
|
],
|
|
199
218
|
modelHelp: 'Images belong in shared State, not Question Instructions.',
|
|
200
219
|
credentialNames: BASETEN_DEFAULT_CREDENTIAL_NAMES,
|
|
@@ -354,40 +373,46 @@ export function getClassifierProviderEnvironmentVariableNames() {
|
|
|
354
373
|
return [...new Set(classifierProviders.map((provider) => provider.credentialNames.environmentVariableName))];
|
|
355
374
|
}
|
|
356
375
|
/**
|
|
357
|
-
* Returns a USD cost
|
|
358
|
-
*
|
|
376
|
+
* Returns a USD cost for safe non-negative integer token counts using authored
|
|
377
|
+
* rates or a recognized requested/returned model pair. Provider input_tokens already
|
|
359
378
|
* includes billed text/image work across questions; never multiply by question
|
|
360
|
-
* count or add image tokens again.
|
|
379
|
+
* count or add image tokens again. Verified cache reads/writes are input subsets.
|
|
361
380
|
* Callers must not treat an unpriced provider as free.
|
|
362
381
|
*/
|
|
363
382
|
export function calculateClassifierUsageCost(provider, usage, models, tokenPricing) {
|
|
383
|
+
let inputTokenDetails;
|
|
384
|
+
if (provider.cacheTokenUsageSupported && usage.input_tokens_details !== undefined) {
|
|
385
|
+
const details = usage.input_tokens_details;
|
|
386
|
+
// A reported breakdown must be complete; missing counters are not known zeros.
|
|
387
|
+
if (details === null ||
|
|
388
|
+
typeof details !== 'object' ||
|
|
389
|
+
Array.isArray(details) ||
|
|
390
|
+
!isReportedTokenCount(details.cached_tokens) ||
|
|
391
|
+
!isReportedTokenCount(details.cache_write_tokens))
|
|
392
|
+
return undefined;
|
|
393
|
+
inputTokenDetails = { cacheReadTokens: details.cached_tokens, cacheWriteTokens: details.cache_write_tokens };
|
|
394
|
+
}
|
|
395
|
+
const reportedUsage = { inputTokens: usage.input_tokens, outputTokens: usage.output_tokens, inputTokenDetails };
|
|
364
396
|
if (tokenPricing !== undefined)
|
|
365
|
-
return calculateTokenUsageCost(tokenPricing,
|
|
366
|
-
inputTokens: usage.input_tokens,
|
|
367
|
-
outputTokens: usage.output_tokens,
|
|
368
|
-
});
|
|
397
|
+
return calculateTokenUsageCost(tokenPricing, reportedUsage);
|
|
369
398
|
if (!models)
|
|
370
399
|
return undefined;
|
|
371
400
|
const entries = normalizeModelPricing(provider);
|
|
372
401
|
const entry = entries.find(({ models: names }) => names.includes(models.requestedModel) && names.includes(models.responseModel));
|
|
373
402
|
const base = entry?.pricing;
|
|
374
403
|
const tier = base?.longContext;
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
!isReportedTokenCount(usage.input_tokens) ||
|
|
384
|
-
!isReportedTokenCount(usage.output_tokens)) {
|
|
404
|
+
if (base == null || (tier != null && !isReportedTokenCount(tier.aboveInputTokens)))
|
|
405
|
+
return undefined;
|
|
406
|
+
try {
|
|
407
|
+
validateTokenPricing(base);
|
|
408
|
+
if (tier != null)
|
|
409
|
+
validateTokenPricing(tier);
|
|
410
|
+
}
|
|
411
|
+
catch {
|
|
385
412
|
return undefined;
|
|
386
413
|
}
|
|
387
414
|
const pricing = tier && usage.input_tokens > tier.aboveInputTokens ? tier : base;
|
|
388
|
-
|
|
389
|
-
TOKENS_PER_MILLION;
|
|
390
|
-
return Number.isFinite(totalCost) && totalCost >= 0 ? totalCost : undefined;
|
|
415
|
+
return calculateTokenUsageCost(pricing, reportedUsage);
|
|
391
416
|
}
|
|
392
417
|
async function callClassifierHttp(args, spec, prepared, buildRequest, operation) {
|
|
393
418
|
const { apiKey, fetchImplementation, retryOnNon200, retryOnNon200CooldownMs, retryOnNon200RepeatTimes } = args;
|