@valerypopoff/rivet2-core 2.25.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.
- package/dist/cjs/bundle.cjs +471 -203
- package/dist/cjs/bundle.cjs.map +4 -4
- 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 +156 -0
- package/dist/esm/model/Nodes.js +3 -0
- package/dist/esm/model/RunCostLedger.js +63 -32
- 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 +113 -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/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,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
|
+
}
|
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
|
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { nanoid } from 'nanoid/non-secure';
|
|
2
|
+
import { NodeImpl } from '../NodeImpl.js';
|
|
3
|
+
import { nodeDefinition } from '../NodeDefinition.js';
|
|
4
|
+
import { addWarning } from '../../utils/outputs.js';
|
|
5
|
+
export class AICostNodeImpl extends NodeImpl {
|
|
6
|
+
static create() {
|
|
7
|
+
return {
|
|
8
|
+
type: 'aiCost',
|
|
9
|
+
title: 'AI Cost',
|
|
10
|
+
id: nanoid(),
|
|
11
|
+
visualData: { x: 0, y: 0, width: 250 },
|
|
12
|
+
data: {},
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
getInputDefinitions() {
|
|
16
|
+
return [];
|
|
17
|
+
}
|
|
18
|
+
getOutputDefinitions() {
|
|
19
|
+
return [
|
|
20
|
+
{ id: 'llmCost', title: 'LLM cost', dataType: 'number' },
|
|
21
|
+
{ id: 'decisionAICost', title: 'Decision AI cost', dataType: 'number' },
|
|
22
|
+
{ id: 'totalCost', title: 'Sum cost', dataType: 'number' },
|
|
23
|
+
];
|
|
24
|
+
}
|
|
25
|
+
static getUIData() {
|
|
26
|
+
return {
|
|
27
|
+
contextMenuTitle: 'AI Cost',
|
|
28
|
+
infoBoxTitle: 'AI Cost',
|
|
29
|
+
group: ['Debug'],
|
|
30
|
+
infoBoxBody: 'Returns observed AI cost estimates in USD for the current project invocation and projects it calls, excluding callers and sibling invocations. Uses the same accounting as Run statistics. Enable Conditional node to control when it runs; use Did Run to wait for multiple branches. In-flight and future calls are not yet included; unknown prices are not free.',
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
getBody() {
|
|
34
|
+
return 'Observed AI estimates (USD)\nCurrent project subtree';
|
|
35
|
+
}
|
|
36
|
+
getRunActivityDescriptor() {
|
|
37
|
+
return { primaryOutputPortId: 'totalCost' };
|
|
38
|
+
}
|
|
39
|
+
async process(_inputs, context) {
|
|
40
|
+
if (!context.getRunCostBreakdown)
|
|
41
|
+
throw new Error('AI Cost accounting is unavailable in this execution environment.');
|
|
42
|
+
const costs = context.getRunCostBreakdown();
|
|
43
|
+
const value = (cost) => cost.knownCostUsd === null
|
|
44
|
+
? { type: 'control-flow-excluded', value: undefined }
|
|
45
|
+
: { type: 'number', value: cost.knownCostUsd };
|
|
46
|
+
const outputs = {
|
|
47
|
+
['llmCost']: value(costs.llm),
|
|
48
|
+
['decisionAICost']: value(costs.decisionAI),
|
|
49
|
+
['totalCost']: value(costs.total),
|
|
50
|
+
};
|
|
51
|
+
if (costs.total.status !== 'complete')
|
|
52
|
+
addWarning(outputs, 'Some observed AI costs are unknown. Numeric outputs are known subtotals; unavailable amounts are not zero.');
|
|
53
|
+
return outputs;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
export const aiCostNode = nodeDefinition(AICostNodeImpl, 'AI Cost');
|
package/dist/types/exports.d.ts
CHANGED
|
@@ -57,6 +57,7 @@ export declare class GraphInvocationState {
|
|
|
57
57
|
createAbortController: () => AbortController;
|
|
58
58
|
loadedProjects: Record<ProjectId, Project>;
|
|
59
59
|
sharedOverride?: Pick<GraphInvocationState, 'graphOutputs' | 'attachedNodeData' | 'graphInputNodeValues'>;
|
|
60
|
+
costLedger?: RunCostLedger;
|
|
60
61
|
}): void;
|
|
61
62
|
}
|
|
62
63
|
/** Shared by every child kind; retained caches/globals deliberately keep existing reuse semantics. */
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import type { ProcessEventMessageMap } from './ExecutorProtocol.js';
|
|
2
|
+
/** Managed latest-debugger routing labels are not credentials. */
|
|
3
|
+
export type LatestDebuggerChannel = string | null;
|
|
4
|
+
export type LatestDebuggerTarget = {
|
|
5
|
+
rootRunId: string;
|
|
6
|
+
projectId: string;
|
|
7
|
+
owner: string;
|
|
8
|
+
incarnation: string;
|
|
9
|
+
};
|
|
10
|
+
export type LatestDebuggerScope = LatestDebuggerTarget & {
|
|
11
|
+
channel: LatestDebuggerChannel;
|
|
12
|
+
promptId?: string;
|
|
13
|
+
admittedAt?: number;
|
|
14
|
+
/** This owner emits authoritative prompt closure in the same ordered stream. */
|
|
15
|
+
promptLifecycle?: 1;
|
|
16
|
+
};
|
|
17
|
+
export type LatestDebuggerPromptClosedMessage = {
|
|
18
|
+
message: 'latest-prompt-closed';
|
|
19
|
+
rivetScope: LatestDebuggerScope;
|
|
20
|
+
data: {
|
|
21
|
+
promptId: string;
|
|
22
|
+
};
|
|
23
|
+
};
|
|
24
|
+
export type LatestDebuggerPrompt = {
|
|
25
|
+
target: LatestDebuggerScope;
|
|
26
|
+
promptId: string;
|
|
27
|
+
};
|
|
28
|
+
export type LatestDebuggerSessionMessage = {
|
|
29
|
+
message: 'latest-session';
|
|
30
|
+
data: {
|
|
31
|
+
protocol: 2;
|
|
32
|
+
channel: LatestDebuggerChannel;
|
|
33
|
+
channelIsolation: true;
|
|
34
|
+
runScopedControls: true;
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
export type LatestDebuggerControlMessage = {
|
|
38
|
+
type: 'latest-control';
|
|
39
|
+
data: {
|
|
40
|
+
commandId: string;
|
|
41
|
+
target: LatestDebuggerScope;
|
|
42
|
+
} & ({
|
|
43
|
+
action: 'pause' | 'resume' | 'abort';
|
|
44
|
+
} | {
|
|
45
|
+
action: 'user-input';
|
|
46
|
+
promptId: string;
|
|
47
|
+
answers: {
|
|
48
|
+
type: 'string[]';
|
|
49
|
+
value: string[];
|
|
50
|
+
};
|
|
51
|
+
});
|
|
52
|
+
};
|
|
53
|
+
export type LatestDebuggerControlResult = {
|
|
54
|
+
status: 'accepted' | 'rejected' | 'outcome-unknown';
|
|
55
|
+
reason?: string;
|
|
56
|
+
};
|
|
57
|
+
export type LatestDebuggerControlResultMessage = {
|
|
58
|
+
message: 'latest-control-result';
|
|
59
|
+
data: LatestDebuggerControlResult & {
|
|
60
|
+
commandId: string;
|
|
61
|
+
};
|
|
62
|
+
};
|
|
63
|
+
export type LatestDebuggerSettledMessage = {
|
|
64
|
+
message: 'latest-settled';
|
|
65
|
+
rivetScope: LatestDebuggerScope;
|
|
66
|
+
data: Record<string, never>;
|
|
67
|
+
};
|
|
68
|
+
export type LatestDebuggerLifecycleMessage = LatestDebuggerPromptClosedMessage | LatestDebuggerSettledMessage;
|
|
69
|
+
export type LatestDebuggerProcessMessage = {
|
|
70
|
+
[K in keyof ProcessEventMessageMap]: {
|
|
71
|
+
message: K;
|
|
72
|
+
data: ProcessEventMessageMap[K];
|
|
73
|
+
rivetScope: LatestDebuggerScope;
|
|
74
|
+
};
|
|
75
|
+
}[keyof ProcessEventMessageMap];
|
|
76
|
+
export type LatestDebuggerExecutionMessage = (LatestDebuggerProcessMessage | LatestDebuggerLifecycleMessage) & {
|
|
77
|
+
rivetEventId?: string;
|
|
78
|
+
};
|
|
79
|
+
declare const diagnosticCodes: readonly ["history-truncated", "history-gap", "event-too-large", "owner-unavailable"];
|
|
80
|
+
export type LatestDebuggerDiagnosticCode = (typeof diagnosticCodes)[number];
|
|
81
|
+
export type LatestDebuggerDiagnosticMessage = {
|
|
82
|
+
message: 'latest-diagnostic';
|
|
83
|
+
data: {
|
|
84
|
+
protocol: 1;
|
|
85
|
+
code: LatestDebuggerDiagnosticCode;
|
|
86
|
+
};
|
|
87
|
+
};
|
|
88
|
+
export type LatestDebuggerServerMessage = LatestDebuggerSessionMessage | LatestDebuggerExecutionMessage | LatestDebuggerDiagnosticMessage | LatestDebuggerControlResultMessage;
|
|
89
|
+
export type LatestDebuggerMessage = LatestDebuggerServerMessage | LatestDebuggerControlMessage;
|
|
90
|
+
export declare const LATEST_DEBUGGER_PATH = "/ws/latest-debugger";
|
|
91
|
+
export declare function isLatestDebuggerExecutionMessage(message: string): boolean;
|
|
92
|
+
/** Preserve historical writer ordering while readers accept arbitrary JSON ordering. */
|
|
93
|
+
export declare function encodeLatestDebuggerEnvelope(serialized: string, scope?: LatestDebuggerScope, eventId?: string): string;
|
|
94
|
+
export declare function createLatestDebuggerSession(channel: LatestDebuggerChannel): LatestDebuggerSessionMessage;
|
|
95
|
+
export declare function isLatestDebuggerSession(value: unknown): value is LatestDebuggerSessionMessage;
|
|
96
|
+
/** Validate the routing contract only. Authored data and decoded sentinels stay intact. */
|
|
97
|
+
export declare function readLatestDebuggerExecution(value: unknown): LatestDebuggerExecutionMessage | undefined;
|
|
98
|
+
export declare function createLatestDebuggerDiagnostic(code: LatestDebuggerDiagnosticCode): LatestDebuggerDiagnosticMessage;
|
|
99
|
+
export declare function isLatestDebuggerDiagnostic(value: unknown): value is LatestDebuggerDiagnosticMessage;
|
|
100
|
+
export declare function createLatestDebuggerControlResult(commandId: string, result: LatestDebuggerControlResult): LatestDebuggerControlResultMessage;
|
|
101
|
+
/** Validate only the wire control contract, never authored graph payloads. */
|
|
102
|
+
export declare function readLatestDebuggerControl(value: unknown): LatestDebuggerControlMessage | undefined;
|
|
103
|
+
export declare function readLatestDebuggerEventId(value: unknown): string | undefined;
|
|
104
|
+
export declare function isLatestDebuggerControlResult(value: unknown): value is LatestDebuggerControlResultMessage;
|
|
105
|
+
/** Input is a decoded single path segment. Never decode it again. */
|
|
106
|
+
export declare function parseLatestEndpointSegment(segment: string): {
|
|
107
|
+
endpointName: string;
|
|
108
|
+
channel: LatestDebuggerChannel;
|
|
109
|
+
};
|
|
110
|
+
/** URL.pathname is still encoded. Decode exactly once, rejecting path separators. */
|
|
111
|
+
export declare function parseLatestDebuggerPath(pathname: string): LatestDebuggerChannel;
|
|
112
|
+
export declare function isLatestDebuggerScope(value: unknown): value is LatestDebuggerScope;
|
|
113
|
+
export {};
|