@valerypopoff/rivet2-core 2.1.10 → 2.4.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 (111) hide show
  1. package/README.md +1 -1
  2. package/dist/cjs/bundle.cjs +2604 -949
  3. package/dist/cjs/bundle.cjs.map +4 -4
  4. package/dist/cjs/webAppRuntime.cjs +1549 -99
  5. package/dist/cjs/webAppRuntime.cjs.map +4 -4
  6. package/dist/esm/api/createProcessor.js +4 -0
  7. package/dist/esm/exports.js +2 -0
  8. package/dist/esm/integrations/CodeRunner.js +2 -7
  9. package/dist/esm/integrations/CodeRunnerOptions.js +7 -0
  10. package/dist/esm/model/AgentResponseTrace.js +137 -11
  11. package/dist/esm/model/GraphProcessor.js +28 -0
  12. package/dist/esm/model/NodeExclusionPolicy.js +9 -1
  13. package/dist/esm/model/ProcessContextBuilder.js +2 -1
  14. package/dist/esm/model/RecordingPlayer.js +58 -5
  15. package/dist/esm/model/SubprocessorBridge.js +2 -0
  16. package/dist/esm/model/UiGraphActionProtocol.js +47 -4
  17. package/dist/esm/model/UiGraphBrowserRuntime.js +15 -1
  18. package/dist/esm/model/UiGraphIndexedDbPersistence.js +523 -0
  19. package/dist/esm/model/UiGraphRendererStyles.js +14 -0
  20. package/dist/esm/model/WebAppBrowserStorage.js +653 -0
  21. package/dist/esm/model/WebAppBrowserStorageRpc.js +200 -0
  22. package/dist/esm/model/chat-v2/aiSdkBridge.js +146 -14
  23. package/dist/esm/model/chat-v2/chatV2CallObserver.js +3 -0
  24. package/dist/esm/model/chat-v2/chatV2CredentialNames.js +93 -0
  25. package/dist/esm/model/chat-v2/chatV2EditorCache.js +8 -38
  26. package/dist/esm/model/chat-v2/chatV2Pipeline.js +41 -4
  27. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +31 -2
  28. package/dist/esm/model/chat-v2/chatV2ResponseBodyCapture.js +10 -2
  29. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +6 -11
  30. package/dist/esm/model/chat-v2/chatV2Shared.js +1 -1
  31. package/dist/esm/model/chat-v2/chatV2Types.js +16 -0
  32. package/dist/esm/model/chat-v2/customProviderApi.js +0 -2
  33. package/dist/esm/model/chat-v2/index.js +3 -0
  34. package/dist/esm/model/chat-v2/llmChatV2Body.js +9 -1
  35. package/dist/esm/model/chat-v2/llmChatV2CachePolicy.js +5 -0
  36. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +7 -0
  37. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +95 -14
  38. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +33 -9
  39. package/dist/esm/model/chat-v2/llmChatV2OutputClone.js +42 -0
  40. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +31 -2
  41. package/dist/esm/model/chat-v2/llmModelCandidate.js +5 -1
  42. package/dist/esm/model/chat-v2/llmProfile.js +58 -0
  43. package/dist/esm/model/chat-v2/llmProfileBody.js +10 -0
  44. package/dist/esm/model/chat-v2/llmProfileFallback.js +406 -8
  45. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +7 -0
  46. package/dist/esm/model/chat-v2/llmProfileHealthStore.js +328 -0
  47. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +57 -34
  48. package/dist/esm/model/chat-v2/providerOptions.js +33 -7
  49. package/dist/esm/model/chat-v2/toolContinuation.js +27 -1
  50. package/dist/esm/model/nodes/CodeNewNode.js +5 -47
  51. package/dist/esm/model/nodes/CodeNode.js +4 -46
  52. package/dist/esm/model/nodes/ExpressionNode.js +5 -8
  53. package/dist/esm/model/nodes/LLMChatV2Node.js +31 -3
  54. package/dist/esm/model/nodes/MatchNode.js +86 -41
  55. package/dist/esm/plugins/gentrace/gentraceSdk.js +0 -1
  56. package/dist/esm/plugins/gentrace/index.js +0 -1
  57. package/dist/esm/plugins/gentrace/plugin.js +61 -179
  58. package/dist/esm/plugins.js +1 -2
  59. package/dist/esm/recording/ExecutionRecorder.js +50 -8
  60. package/dist/esm/webAppRuntime.js +5 -2
  61. package/dist/types/api/createProcessor.d.ts +5 -0
  62. package/dist/types/exports.d.ts +2 -0
  63. package/dist/types/integrations/CodeRunner.d.ts +10 -7
  64. package/dist/types/integrations/CodeRunnerOptions.d.ts +15 -0
  65. package/dist/types/model/AgentResponseTrace.d.ts +15 -1
  66. package/dist/types/model/EditorDefinition.d.ts +16 -0
  67. package/dist/types/model/ExecutorProtocol.d.ts +17 -6
  68. package/dist/types/model/GraphProcessor.d.ts +17 -5
  69. package/dist/types/model/NodeBase.d.ts +0 -10
  70. package/dist/types/model/NodeExclusionPolicy.d.ts +6 -0
  71. package/dist/types/model/Nodes.d.ts +2 -2
  72. package/dist/types/model/ProcessContext.d.ts +85 -0
  73. package/dist/types/model/ProcessContextBuilder.d.ts +2 -1
  74. package/dist/types/model/UiGraphActionProtocol.d.ts +9 -3
  75. package/dist/types/model/UiGraphBrowserRuntime.d.ts +6 -0
  76. package/dist/types/model/UiGraphIndexedDbPersistence.d.ts +50 -0
  77. package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
  78. package/dist/types/model/WebAppBrowserStorage.d.ts +90 -0
  79. package/dist/types/model/WebAppBrowserStorageRpc.d.ts +85 -0
  80. package/dist/types/model/chat-v2/chatV2CredentialNames.d.ts +30 -0
  81. package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +1 -0
  82. package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +3 -0
  83. package/dist/types/model/chat-v2/chatV2ResponseBodyCapture.d.ts +8 -2
  84. package/dist/types/model/chat-v2/chatV2RuntimeOptions.d.ts +3 -8
  85. package/dist/types/model/chat-v2/chatV2Types.d.ts +27 -1
  86. package/dist/types/model/chat-v2/customProviderApi.d.ts +0 -1
  87. package/dist/types/model/chat-v2/index.d.ts +3 -0
  88. package/dist/types/model/chat-v2/llmChatV2CachePolicy.d.ts +1 -1
  89. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +10 -1
  90. package/dist/types/model/chat-v2/llmChatV2OutputClone.d.ts +3 -0
  91. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +5 -1
  92. package/dist/types/model/chat-v2/llmModelCandidate.d.ts +2 -0
  93. package/dist/types/model/chat-v2/llmProfile.d.ts +14 -0
  94. package/dist/types/model/chat-v2/llmProfileBody.d.ts +1 -1
  95. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +25 -2
  96. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +26 -6
  97. package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +121 -0
  98. package/dist/types/model/chat-v2/llmProfileNodeRuntime.d.ts +1 -1
  99. package/dist/types/model/chat-v2/llmProfileTypes.d.ts +9 -0
  100. package/dist/types/model/chat-v2/providerOptions.d.ts +2 -0
  101. package/dist/types/model/chat-v2/toolContinuation.d.ts +14 -0
  102. package/dist/types/model/nodes/CodeNewNode.d.ts +0 -5
  103. package/dist/types/model/nodes/CodeNode.d.ts +0 -5
  104. package/dist/types/model/nodes/MatchNode.d.ts +6 -0
  105. package/dist/types/plugins/gentrace/gentraceSdk.d.ts +0 -1
  106. package/dist/types/plugins/gentrace/plugin.d.ts +55 -9
  107. package/dist/types/plugins.d.ts +1 -1
  108. package/dist/types/recording/ExecutionRecorder.d.ts +7 -1
  109. package/dist/types/recording/RecordedEvents.d.ts +11 -0
  110. package/dist/types/webAppRuntime.d.ts +8 -2
  111. package/package.json +2 -2
@@ -1,12 +1,4 @@
1
- import { Pipeline, StepRun, init, runTest, getPipelines } from './gentraceSdk.js';
2
- import { globalRivetNodeRegistry } from '../../model/Nodes.js';
3
- import { cloneDeep, mapValues } from 'lodash-es';
4
- import { GptTokenizerTokenizer } from '../../integrations/GptTokenizerTokenizer.js';
5
- import { ExecutionRecorder } from '../../recording/ExecutionRecorder.js';
6
- import { inferType } from '../../utils/coerceType.js';
7
- // eslint-disable-next-line import/no-cycle -- Local Gentrace execution intentionally depends on GraphProcessor.
8
- import { GraphProcessor } from '../../model/GraphProcessor.js';
9
- import { resolveProcessSettings } from '../../api/processSettings.js';
1
+ import { Pipeline, StepRun, getPipelines, init } from './gentraceSdk.js';
10
2
  const apiKeyConfigSpec = {
11
3
  type: 'secret',
12
4
  label: 'Gentrace API Key',
@@ -15,183 +7,73 @@ const apiKeyConfigSpec = {
15
7
  helperText: 'Create at https://gentrace.ai/settings/api-keys',
16
8
  };
17
9
  function initializeGentrace(gentraceApiKey) {
18
- init({
19
- apiKey: gentraceApiKey,
20
- });
21
- }
22
- export const runGentraceTests = async (gentracePipelineSlug, settings, project, graph, nativeApi, contextValues = {}) => {
23
- const gentraceApiKey = settings.pluginSettings?.gentrace?.gentraceApiKey;
24
- if (!gentraceApiKey) {
10
+ if (!gentraceApiKey)
25
11
  throw new Error('Gentrace API key not set.');
12
+ init({ apiKey: gentraceApiKey });
13
+ }
14
+ function timestampForTrial(run, durationMs, index) {
15
+ const runStart = Date.parse(run.startedAt);
16
+ const safeStart = Number.isFinite(runStart) ? runStart + index : Date.now();
17
+ const safeDuration = Number.isFinite(durationMs) && durationMs >= 0 ? durationMs : 0;
18
+ return {
19
+ start: new Date(safeStart).toISOString(),
20
+ end: new Date(safeStart + safeDuration).toISOString(),
21
+ };
22
+ }
23
+ /**
24
+ * Exports an already completed Rivet Evaluation as one Gentrace pipeline run.
25
+ * It never fetches Gentrace test cases and never executes a Rivet graph: the
26
+ * generic Evaluations runner remains the sole execution engine.
27
+ */
28
+ export async function exportGentraceEvaluationRun(input) {
29
+ initializeGentrace(input.gentraceApiKey);
30
+ if (!input.pipelineSlug)
31
+ throw new Error('Gentrace pipeline slug is required.');
32
+ if (input.run.executionStatus !== 'completed') {
33
+ throw new Error('Only completed Rivet Evaluation runs can be exported to Gentrace.');
26
34
  }
27
- const graphId = graph.metadata?.id;
28
- if (!graphId) {
29
- throw new Error('Graph ID not set.');
30
- }
31
- initializeGentrace(gentraceApiKey);
32
- const response = await runTest(gentracePipelineSlug, async (testCase) => {
33
- const pipeline = new Pipeline({
34
- slug: gentracePipelineSlug,
35
- });
36
- const runner = pipeline.start();
37
- const rivetFormattedInputs = mapValues(testCase.inputs, inferType);
38
- const tempProject = {
39
- ...project,
40
- graphs: {
41
- ...project.graphs,
42
- [graph.metadata.id]: graph,
43
- },
44
- };
45
- const recorder = new ExecutionRecorder();
46
- const processor = new GraphProcessor(tempProject, graphId, globalRivetNodeRegistry);
47
- processor.executor = 'browser';
48
- recorder.record(processor);
49
- const runContextValues = cloneDeep(contextValues);
50
- await processor.processGraph({
51
- settings: resolveProcessSettings(settings),
52
- nativeApi,
53
- tokenizer: new GptTokenizerTokenizer(),
54
- }, rivetFormattedInputs, runContextValues);
55
- const fullRecording = recorder.getRecording();
56
- const stepRuns = convertRecordingToStepRuns(fullRecording, project, graphId);
57
- for (const stepRun of stepRuns) {
58
- await runner.addStepRunNode(stepRun);
59
- }
60
- if (stepRuns.length === 0) {
61
- throw new Error('No Rivet steps found. You need operations which are not Graph Input or Graph Output nodes.');
62
- }
63
- return ['', runner];
64
- });
65
- return response;
66
- };
67
- export const runRemoteGentraceTests = async (gentracePipelineSlug, settings, project, graph, runAndRecord) => {
68
- const gentraceApiKey = settings.pluginSettings?.gentrace?.gentraceApiKey;
69
- if (!gentraceApiKey) {
70
- throw new Error('Gentrace API key not set.');
71
- }
72
- const graphId = graph.metadata?.id;
73
- if (!graphId) {
74
- throw new Error('Graph ID not set.');
75
- }
76
- initializeGentrace(gentraceApiKey);
77
- const response = await runTest(gentracePipelineSlug, async (testCase) => {
78
- const pipeline = new Pipeline({
79
- slug: gentracePipelineSlug,
80
- });
81
- const runner = pipeline.start();
82
- const rivetFormattedInputs = mapValues(testCase.inputs, inferType);
83
- const fullRecording = await runAndRecord(rivetFormattedInputs);
84
- const stepRuns = convertRecordingToStepRuns(fullRecording, project, graphId);
85
- for (const stepRun of stepRuns) {
86
- await runner.addStepRunNode(stepRun);
87
- }
88
- if (stepRuns.length === 0) {
89
- throw new Error('No Rivet steps found. You need operations which are not Graph Input or Graph Output nodes.');
90
- }
91
- return ['', runner];
92
- });
93
- return response;
94
- };
95
- function convertRecordingToStepRuns(recording, project, graphId) {
96
- const partialProcessStartEndPairs = {};
97
- recording.events.forEach((event) => {
98
- const eventType = event?.type;
99
- if (!eventType) {
100
- return;
101
- }
102
- if (eventType === 'nodeStart' || eventType === 'nodeFinish') {
103
- const processId = event?.data?.processId;
104
- const nodeId = event?.data?.nodeId;
105
- if (!processId) {
106
- return;
107
- }
108
- let existingPair = partialProcessStartEndPairs[processId];
109
- if (!existingPair) {
110
- existingPair = {};
111
- partialProcessStartEndPairs[processId] = existingPair;
112
- }
113
- existingPair.nodeId = nodeId;
114
- if (eventType === 'nodeStart') {
115
- existingPair.start = event.ts;
116
- existingPair.inputs = event.data.inputs;
117
- }
118
- else {
119
- existingPair.end = event.ts;
120
- existingPair.outputs = event.data.outputs;
121
- }
122
- }
35
+ const pipeline = new Pipeline({ slug: input.pipelineSlug });
36
+ const runner = pipeline.start({
37
+ metadata: {
38
+ source: { type: 'string', value: 'rivet-evaluations' },
39
+ evaluationRunId: { type: 'string', value: input.run.id },
40
+ suiteName: { type: 'string', value: input.run.suiteName },
41
+ purpose: { type: 'string', value: input.run.purpose },
42
+ qualityStatus: { type: 'string', value: input.run.qualityStatus },
43
+ qualityReason: { type: 'string', value: input.run.qualityReason.message },
44
+ accountingStatus: { type: 'string', value: input.run.accountingStatus },
45
+ executionStatus: { type: 'string', value: input.run.executionStatus },
46
+ },
123
47
  });
124
- const processStartEndPairs = partialProcessStartEndPairs;
125
- const selectedGraph = project.graphs[graphId];
126
- if (!selectedGraph) {
127
- return [];
128
- }
129
- // Convert to step runs
130
- const stepRuns = [];
131
- for (const [, pair] of Object.entries(processStartEndPairs)) {
132
- const { nodeId } = pair;
133
- const relatedNode = selectedGraph.nodes.find((node) => node.id === nodeId);
134
- const nodeType = relatedNode?.type;
135
- if (!nodeType || !relatedNode.data || nodeType === 'graphInput' || nodeType === 'graphOutput') {
136
- continue;
137
- }
138
- const nodeData = relatedNode.data;
139
- if (relatedNode) {
140
- pair.modelParams = { ...nodeData, ...{ type: nodeType } };
141
- }
142
- if (nodeType === 'chat') {
143
- const modelName = nodeData.model ? nodeData.model : '';
144
- if (modelName.startsWith('gpt')) {
145
- // Convert to OpenAI Gentrace node
146
- const gentraceOpenAIInputs = { ...pair.inputs };
147
- gentraceOpenAIInputs.messages = [
148
- {
149
- content: pair.inputs.prompt.value,
150
- role: 'user',
151
- },
152
- ];
153
- const gentraceOpenAIModelParams = { ...pair.modelParams };
154
- gentraceOpenAIModelParams.model = modelName;
155
- gentraceOpenAIModelParams.frequency_penalty = pair.modelParams.frequencyPenalty || null;
156
- gentraceOpenAIModelParams.max_tokens = pair.modelParams.maxTokens || undefined;
157
- gentraceOpenAIModelParams.presence_penalty = pair.modelParams.presencePenalty || null;
158
- gentraceOpenAIModelParams.stop = pair.modelParams.stop || null;
159
- gentraceOpenAIModelParams.temperature = pair.modelParams.temperature || null;
160
- gentraceOpenAIModelParams.top_p = pair.modelParams.top_p || null;
161
- const gentraceOpenAIOutputs = { ...pair.outputs };
162
- const outputValues = Array.isArray(pair.outputs.response.value)
163
- ? pair.outputs.response.value
164
- : [pair.outputs.response.value];
165
- gentraceOpenAIOutputs.choices = outputValues.map((outputValue, index) => {
166
- return {
167
- index,
168
- message: {
169
- content: outputValue,
170
- role: 'assistant',
171
- },
172
- usage: {
173
- completion_tokens: pair.outputs.responseTokens.value,
174
- prompt_tokens: pair.outputs.requestTokens.value,
175
- total_tokens: pair.outputs.responseTokens.value + pair.outputs.requestTokens.value,
176
- },
177
- };
178
- });
179
- stepRuns.push(new StepRun('openai', 'openai_createChatCompletion', pair.end - pair.start, new Date(pair.start).toISOString(), new Date(pair.end).toISOString(), gentraceOpenAIInputs, gentraceOpenAIModelParams, gentraceOpenAIOutputs, {}, undefined));
180
- continue;
181
- }
182
- }
183
- stepRuns.push(new StepRun('rivet', nodeType ? `rivet_operation_${nodeType}` : 'rivet_operation', pair.end - pair.start, new Date(pair.start).toISOString(), new Date(pair.end).toISOString(), pair.inputs, pair.modelParams, pair.outputs, {}, undefined));
48
+ for (const [index, trial] of input.run.trials.entries()) {
49
+ const durationMs = typeof trial.totalMetrics.durationMs === 'number' ? trial.totalMetrics.durationMs : 0;
50
+ const { start, end } = timestampForTrial(input.run, durationMs, index);
51
+ await runner.addStepRunNode(new StepRun('rivet', 'rivet_evaluation_trial', durationMs, start, end, {
52
+ caseId: trial.caseId,
53
+ caseName: trial.caseName,
54
+ trialIndex: trial.trialIndex,
55
+ inputs: trial.inputs,
56
+ expected: trial.expected,
57
+ }, {
58
+ source: 'rivet-evaluations',
59
+ purpose: input.run.purpose,
60
+ }, {
61
+ executionStatus: trial.executionStatus,
62
+ qualityStatus: trial.qualityStatus,
63
+ qualityReason: trial.qualityReason,
64
+ outputs: trial.outputs,
65
+ observations: trial.observations,
66
+ metrics: trial.totalMetrics,
67
+ }, {}, trial.error));
184
68
  }
185
- return stepRuns;
69
+ return (await runner.submit({ waitForServer: true }));
186
70
  }
187
- export const getGentracePipelines = async (gentraceApiKey) => {
71
+ export async function getGentracePipelines(gentraceApiKey) {
188
72
  initializeGentrace(gentraceApiKey);
189
- return await getPipelines();
190
- };
73
+ return getPipelines();
74
+ }
191
75
  export const gentracePlugin = {
192
76
  id: 'gentrace',
193
77
  name: 'Gentrace',
194
- configSpec: {
195
- gentraceApiKey: apiKeyConfigSpec,
196
- },
78
+ configSpec: { gentraceApiKey: apiKeyConfigSpec },
197
79
  };
@@ -3,9 +3,8 @@ import autoevalsPlugin from './plugins/autoevals/index.js';
3
3
  import assemblyAiPlugin from './plugins/assemblyAi/index.js';
4
4
  import { huggingFacePlugin } from './plugins/huggingface/plugin.js';
5
5
  import pineconePlugin from './plugins/pinecone/index.js';
6
- // eslint-disable-next-line import/no-cycle -- Gentrace depends on GraphProcessor for local test execution.
7
6
  import gentracePlugin from './plugins/gentrace/index.js';
8
- export { getGentracePipelines, runGentraceTests, runRemoteGentraceTests } from './plugins/gentrace/plugin.js';
7
+ export { exportGentraceEvaluationRun, getGentracePipelines } from './plugins/gentrace/plugin.js';
9
8
  import { openAIPlugin } from './plugins/openai/plugin.js';
10
9
  import { googlePlugin } from './plugins/google/plugin.js';
11
10
  export { anthropicPlugin, autoevalsPlugin, assemblyAiPlugin, pineconePlugin, huggingFacePlugin, gentracePlugin, googlePlugin, };
@@ -78,6 +78,8 @@ const toRecordedEventMap = {
78
78
  progress,
79
79
  }, execution),
80
80
  llmCallFinished: ({ execution, ...event }) => ({ ...event, execution }),
81
+ llmChatOutputSnapshot: ({ execution, ...event }) => withExecution(event, execution),
82
+ llmProfileAttempt: ({ execution, ...event }) => ({ ...event, execution }),
81
83
  toolCallFinished: ({ execution, ...event }) => ({ ...event, execution }),
82
84
  nodeOutputsCleared: ({ node, processId, execution }) => withExecution({
83
85
  nodeId: node.id,
@@ -116,13 +118,28 @@ function toRecordedEvent(event, data) {
116
118
  ts: Date.now(),
117
119
  };
118
120
  }
121
+ const recordableData = omitReplayRecordedAt(data);
119
122
  const recordedEvent = {
120
123
  type: event,
121
- data: toRecordedEventMap[event](data),
124
+ data: toRecordedEventMap[event](recordableData),
122
125
  ts: Date.now(),
123
126
  };
124
127
  return recordedEvent;
125
128
  }
129
+ /**
130
+ * Replay provenance belongs to the current delivery, not the historical event
131
+ * itself. If a replay is recorded again, the recorder's own `ts` is the one
132
+ * authoritative timestamp to persist.
133
+ */
134
+ function omitReplayRecordedAt(data) {
135
+ if (data == null || typeof data !== 'object')
136
+ return data;
137
+ const { replayRecordedAt: _replayRecordedAt, ...recordableData } = data;
138
+ return recordableData;
139
+ }
140
+ function isRecordableProcessEvent(message) {
141
+ return message in toRecordedEventMap || isPrefix(message, 'globalSet:') || isPrefix(message, 'userEvent:');
142
+ }
126
143
  function mapValuesDeep(obj, fn) {
127
144
  if (Array.isArray(obj)) {
128
145
  return obj.map((value) => {
@@ -212,18 +229,39 @@ export class ExecutionRecorder {
212
229
  on = undefined;
213
230
  off = undefined;
214
231
  once = undefined;
215
- recordSocket(channel) {
232
+ recordSocket(channel, options = {}) {
216
233
  return new Promise((resolve) => {
217
234
  this.recordingId = nanoid();
235
+ let settled = false;
236
+ const finish = () => {
237
+ if (settled)
238
+ return;
239
+ settled = true;
240
+ channel.removeEventListener('message', listener);
241
+ options.signal?.removeEventListener('abort', finish);
242
+ resolve();
243
+ };
218
244
  const listener = (event) => {
219
- const { message, data } = JSON.parse(event.data);
220
- if (this.#includePartialOutputs === false && message === 'partialOutput') {
245
+ let payload;
246
+ try {
247
+ payload = JSON.parse(event.data);
248
+ }
249
+ catch {
250
+ // A debugger socket can carry control-plane payloads alongside graph
251
+ // events. They are not part of a replayable graph recording.
221
252
  return;
222
253
  }
223
- if (this.#includeTrace === false && message === 'trace') {
254
+ const { message, data, requestId } = payload;
255
+ if (typeof message !== 'string' || !isRecordableProcessEvent(message)) {
224
256
  return;
225
257
  }
226
- if (message === 'codeConsole') {
258
+ if (options.requestId !== undefined && requestId !== options.requestId) {
259
+ return;
260
+ }
261
+ if (this.#includePartialOutputs === false && message === 'partialOutput') {
262
+ return;
263
+ }
264
+ if (this.#includeTrace === false && message === 'trace') {
227
265
  return;
228
266
  }
229
267
  this.#events.push(toRecordedEvent(message, data));
@@ -231,11 +269,15 @@ export class ExecutionRecorder {
231
269
  emitDetached(this.#emitter, 'finish', {
232
270
  recording: this.getRecording(),
233
271
  });
234
- channel.removeEventListener('message', listener);
235
- resolve();
272
+ finish();
236
273
  }
237
274
  };
275
+ if (options.signal?.aborted) {
276
+ finish();
277
+ return;
278
+ }
238
279
  channel.addEventListener('message', listener);
280
+ options.signal?.addEventListener('abort', finish, { once: true });
239
281
  });
240
282
  }
241
283
  record(processor) {
@@ -1,5 +1,8 @@
1
1
  export { isAgentResponseTrace } from './model/AgentResponseTrace.js';
2
- export { createUiGraphChatHistoryFlushStatePatch, createUiGraphChatMessageRemovalStatePatch, createUiGraphChatPinStatePatch, createUiGraphChatSubmissionStatePatch, getUiGraphActionState, getUiGraphChatDraftStateKey, getUiGraphChatMessagesStateKey, } from './model/UiGraph.js';
2
+ export { IndexedDbWebAppBrowserStorage, RIVET_WEB_APP_BROWSER_STORAGE_CHUNK_BYTES, RIVET_WEB_APP_BROWSER_STORAGE_DATABASE, RIVET_WEB_APP_BROWSER_STORAGE_SCHEMA_VERSION, RIVET_WEB_APP_LEGACY_RETENTION_MS, WebAppBrowserStoragePersistenceError, } from './model/WebAppBrowserStorage.js';
3
+ export { decodeRivetWebAppStorageBinaryFrame, deserializeRivetWebAppStoredValue, deserializeRivetWebAppStoredValuePatch, encodeRivetWebAppStorageBinaryFrame, parseRivetWebAppBrowserStorageClientMessage, parseRivetWebAppBrowserStorageServerMessage, RIVET_WEB_APP_BROWSER_STORAGE_BINARY_FRAME_HEADER_BYTES, RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_MAX_ACTION_BYTES, RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_MAX_ACTIVE_BYTES, RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_MAX_VALUE_BYTES, RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_TRANSFER_TIMEOUT_MS, RIVET_WEB_APP_BROWSER_STORAGE_RPC_CAPABILITY, RIVET_WEB_APP_BROWSER_STORAGE_RPC_VERSION, RIVET_WEB_APP_BROWSER_STORAGE_SAFE_FALLBACK_BYTES, RIVET_WEB_APP_BROWSER_STORAGE_TRANSFER_CHUNK_BYTES, serializeRivetWebAppStoredValue, serializeRivetWebAppStoredValuePatch, splitRivetWebAppStorageTransfer, } from './model/WebAppBrowserStorageRpc.js';
4
+ export { UiGraphBrowserPersistence } from './model/UiGraphIndexedDbPersistence.js';
5
+ export { createUiGraphChatHistoryFlushStatePatch, createUiGraphChatMessageRemovalStatePatch, createUiGraphChatPinStatePatch, createUiGraphChatSubmissionStatePatch, getUiGraphActionState, getUiGraphChatDraftStateKey, getUiGraphChatMessagesStateKey, getUiGraphChatPinsStateKey, } from './model/UiGraph.js';
3
6
  export { applyUiGraphStatePatch, createUiGraphActionExecutionController, createUiGraphInteractionController, getUiGraphComponentRenderModel, getUiGraphJsonOutputFilename, getUiGraphProgressiveJsonOutputChunks, } from './model/UiGraphRuntimeModel.js';
4
7
  export { parseRivetWebAppClientMessage, parseRivetWebAppServerMessage, RIVET_WEB_APP_ACTION_PROTOCOL_VERSION, } from './model/UiGraphActionProtocol.js';
5
- export { copyUiGraphText, applyUiGraphWebAppStorageActionPatch, applyUiGraphWebAppStoragePatch, clearUiGraphChatSearchMatches, downloadUiGraphJsonOutput, enhanceUiGraphChatJsonCodeBlocks, hasUiGraphChatPersistentStateChanged, getUiGraphChatPersistentState, getUiGraphChatMessagePresentations, getUiGraphChatStorageKey, getUiGraphWebAppStorageKey, highlightUiGraphChatSearchMatches, loadUiGraphChatPersistentState, loadUiGraphWebAppStorage, observeUiGraphOutputResizeBounds, revealUiGraphChatElement, revealUiGraphChatSearchMatch, saveUiGraphChatPersistentState, saveUiGraphResponseTrace, loadUiGraphResponseTrace, pruneUiGraphResponseTraces, } from './model/UiGraphBrowserRuntime.js';
8
+ export { copyUiGraphText, applyUiGraphWebAppStorageActionPatch, applyUiGraphWebAppStorageActionPatchAsync, applyUiGraphWebAppStoragePatch, clearUiGraphChatSearchMatches, downloadUiGraphJsonOutput, enhanceUiGraphChatJsonCodeBlocks, hasUiGraphChatPersistentStateChanged, getUiGraphChatPersistentState, getUiGraphChatMessagePresentations, getUiGraphChatStorageKey, getUiGraphResponseTraceStorageKey, getUiGraphWebAppStorageKey, highlightUiGraphChatSearchMatches, loadUiGraphChatPersistentState, loadUiGraphWebAppStorage, observeUiGraphOutputResizeBounds, revealUiGraphChatElement, revealUiGraphChatSearchMatch, saveUiGraphChatPersistentState, saveUiGraphResponseTrace, loadUiGraphResponseTrace, pruneUiGraphResponseTraces, } from './model/UiGraphBrowserRuntime.js';
@@ -17,6 +17,7 @@ import { type LooseDataValue } from './looseDataValue.js';
17
17
  import type { ProjectReferenceLoader } from '../model/ProjectReferenceLoader.js';
18
18
  import type { RivetStoredValueStore } from '../model/StoredValueStore.js';
19
19
  import type { RivetKnowledgeStoreRegistry } from '../integrations/KnowledgeStore.js';
20
+ import type { RivetLLMProfileHealthStore } from '../model/chat-v2/llmProfileHealthStore.js';
20
21
  export type RunGraphOptions = {
21
22
  graph?: string;
22
23
  inputs?: Record<string, LooseDataValue>;
@@ -38,6 +39,10 @@ export type RunGraphOptions = {
38
39
  concurrency?: GraphProcessorConcurrency;
39
40
  getChatNodeEndpoint?: ProcessContext['getChatNodeEndpoint'];
40
41
  onChatV2CallFinished?: ProcessContext['onChatV2CallFinished'];
42
+ onLLMChatOutputSnapshot?: ProcessContext['onLLMChatOutputSnapshot'];
43
+ llmProfileHealthStore?: RivetLLMProfileHealthStore;
44
+ llmProfileHealthExecutionCorrelationId?: ProcessContext['llmProfileHealthExecutionCorrelationId'];
45
+ evaluation?: ProcessContext['evaluation'];
41
46
  tokenizer?: Tokenizer;
42
47
  codeRunner?: ProcessContext['codeRunner'];
43
48
  projectPath?: string;
@@ -1,5 +1,6 @@
1
1
  export * from './utils/index.js';
2
2
  export * from './model/GraphProcessor.js';
3
+ export { canConsumeControlFlowExcludedInput } from './model/NodeExclusionPolicy.js';
3
4
  export * from './model/DataValue.js';
4
5
  export * from './model/NodeBase.js';
5
6
  export * from './model/NodeGraph.js';
@@ -15,6 +16,7 @@ export * from './model/UiGraphWebAppStorage.js';
15
16
  export * from './model/StoredValueStore.js';
16
17
  export * from './model/ToolCallContinuation.js';
17
18
  export * from './model/UiGraphActionProtocol.js';
19
+ export * from './model/WebAppBrowserStorageRpc.js';
18
20
  export * from './model/GraphProgress.js';
19
21
  export * from './model/UiGraphRendererStyles.js';
20
22
  export * from './model/MarkdownSanitizationPolicy.js';
@@ -1,12 +1,15 @@
1
1
  import type { Inputs, Outputs } from '../index.js';
2
2
  import type { DataValue } from '../model/DataValue.js';
3
- export interface CodeRunnerOptions {
4
- includeRequire: boolean;
5
- includeFetch: boolean;
6
- includeRivet: boolean;
7
- includeProcess: boolean;
8
- includeConsole: boolean;
9
- }
3
+ import type { CodeRunnerOptions } from './CodeRunnerOptions.js';
4
+ export { ALL_CODE_RUNNER_OPTIONS } from './CodeRunnerOptions.js';
5
+ export type { CodeRunnerOptions } from './CodeRunnerOptions.js';
6
+ /**
7
+ * Code and Expression nodes request every API their executor can provide.
8
+ *
9
+ * This is intentionally not a permission system or a sandbox. Node runners
10
+ * provide the Node-specific APIs, while browser runners only supply the APIs
11
+ * they actually implement.
12
+ */
10
13
  /** An object that can run arbitrary code (evals it). */
11
14
  export interface CodeRunner {
12
15
  runCode: (code: string, inputs: Inputs, options: CodeRunnerOptions, graphInputs?: Record<string, DataValue>, contextValues?: Record<string, DataValue>) => Promise<Outputs>;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The complete capability request used by Code, Code (legacy), and Expression.
3
+ *
4
+ * This deliberately lives apart from the runner implementation: built-in node
5
+ * registration reads this constant during package initialization, while the
6
+ * runner exposes the public `Rivet` namespace at execution time.
7
+ */
8
+ export interface CodeRunnerOptions {
9
+ includeRequire: boolean;
10
+ includeFetch: boolean;
11
+ includeRivet: boolean;
12
+ includeProcess: boolean;
13
+ includeConsole: boolean;
14
+ }
15
+ export declare const ALL_CODE_RUNNER_OPTIONS: CodeRunnerOptions;
@@ -1,9 +1,10 @@
1
- import type { ChatV2CallTraceEvent, GraphExecutionMetadata, GraphRunId, ProcessId, RootRunId, ToolCallFinishedEvent } from './ProcessContext.js';
1
+ import type { ChatV2CallTraceEvent, GraphExecutionMetadata, GraphRunId, LLMProfileAttemptTraceEvent, ProcessId, RootRunId, ToolCallFinishedEvent } from './ProcessContext.js';
2
2
  import type { GraphId } from './NodeGraph.js';
3
3
  import type { NodeId } from './NodeBase.js';
4
4
  import type { GraphProcessor } from './GraphProcessor.js';
5
5
  export declare const AGENT_RESPONSE_TRACE_SCHEMA_VERSION: 1;
6
6
  export declare const AGENT_RESPONSE_TRACE_MAX_MODEL_CALLS = 250;
7
+ export declare const AGENT_RESPONSE_TRACE_MAX_PROFILE_ATTEMPTS = 1000;
7
8
  export declare const AGENT_RESPONSE_TRACE_MAX_TOOL_CALLS = 500;
8
9
  export type AgentModelCallTrace = {
9
10
  callId: string;
@@ -15,6 +16,9 @@ export type AgentModelCallTrace = {
15
16
  outcome: ChatV2CallTraceEvent['outcome'];
16
17
  attemptIndex: number;
17
18
  profileIndex?: number;
19
+ profileName?: string;
20
+ profileHealthKey?: string;
21
+ profileHealthState?: ChatV2CallTraceEvent['profileHealthState'];
18
22
  roundIndex?: number;
19
23
  startedAt?: number;
20
24
  durationMs?: number;
@@ -36,6 +40,9 @@ export type AgentToolCallTrace = {
36
40
  startedAt?: number;
37
41
  durationMs?: number;
38
42
  };
43
+ export type AgentLLMProfileAttemptTrace = Omit<LLMProfileAttemptTraceEvent, 'eventId'> & {
44
+ eventId: string;
45
+ };
39
46
  export type AgentResponseTrace = {
40
47
  schemaVersion: typeof AGENT_RESPONSE_TRACE_SCHEMA_VERSION;
41
48
  traceId: RootRunId;
@@ -65,14 +72,21 @@ export type AgentResponseTrace = {
65
72
  costStatus: 'known' | 'partial' | 'unknown';
66
73
  };
67
74
  modelCalls: AgentModelCallTrace[];
75
+ /** Additive in schema v1; absent in traces produced before profile-health observability. */
76
+ profileAttempts?: AgentLLMProfileAttemptTrace[];
68
77
  toolCalls: AgentToolCallTrace[];
69
78
  omittedModelCallCount: number;
79
+ /** Additive in schema v1; absent in older traces. */
80
+ omittedProfileAttemptCount?: number;
70
81
  omittedToolCallCount: number;
71
82
  };
72
83
  export type AgentTraceEvent = ({
73
84
  type: 'llm-call-finished';
74
85
  execution: GraphExecutionMetadata;
75
86
  } & ChatV2CallTraceEvent) | ({
87
+ type: 'llm-profile-attempt';
88
+ execution: GraphExecutionMetadata;
89
+ } & LLMProfileAttemptTraceEvent) | ({
76
90
  type: 'tool-call-finished';
77
91
  execution: GraphExecutionMetadata;
78
92
  } & ToolCallFinishedEvent);
@@ -84,6 +84,12 @@ export type GraphSelectorEditorDefinition<T extends ChartNode> = SharedEditorDef
84
84
  export type NumberEditorDefinition<T extends ChartNode> = SharedEditorDefinitionProps<T> & {
85
85
  type: 'number';
86
86
  defaultValue?: number;
87
+ /**
88
+ * Multiplier applied between the value shown in the editor and the value
89
+ * stored on the node. For example, a millisecond value can be presented as
90
+ * seconds with a multiplier of 1_000 while preserving its serialized shape.
91
+ */
92
+ storageMultiplier?: number;
87
93
  useInputToggleDataKey?: DataOfType<T, boolean>;
88
94
  min?: number;
89
95
  max?: number;
@@ -166,6 +172,16 @@ export type StringListPortBinding<T extends ChartNode> = {
166
172
  identity: 'stored-stable-id';
167
173
  idDataKey: DataOfType<T, string[]>;
168
174
  legacyPortIdPattern: LegacyOrderedPortIdPattern;
175
+ /**
176
+ * Additional ports whose ids are derived from the stored stable id for
177
+ * the same list row. They are remapped or removed together with the
178
+ * primary bound port when that row is edited.
179
+ */
180
+ companionBindings?: {
181
+ side: 'input' | 'output';
182
+ prefix?: string;
183
+ suffix?: string;
184
+ }[];
169
185
  };
170
186
  export type EditorDefinitionGroup<T extends ChartNode> = SharedEditorDefinitionProps<T> & {
171
187
  type: 'group';
@@ -2,10 +2,10 @@ import type { DataValue, ScalarOrArrayDataValue, StringArrayDataValue } from './
2
2
  import type { Dataset, DatasetId, DatasetMetadata, DatasetRow } from './Dataset.js';
3
3
  import type { ChartNode, NodeConnection, NodeId, PortId } from './NodeBase.js';
4
4
  import type { GraphId, NodeGraph } from './NodeGraph.js';
5
- import type { ChatV2CallTraceEvent, GraphExecutionMetadata, ProcessId, ToolCallFinishedEvent } from './ProcessContext.js';
5
+ import type { ChatV2CallTraceEvent, EvaluationExecutionMetadata, GraphExecutionMetadata, LLMProfileAttemptTraceEvent, LLMChatOutputSnapshotEvent, ProcessId, ToolCallFinishedEvent } from './ProcessContext.js';
6
6
  import type { Project, ProjectId } from './Project.js';
7
7
  import type { Settings } from './Settings.js';
8
- import type { FrozenNodeOutputsByGraph, NodeResultOrigin } from './GraphProcessor.js';
8
+ import type { FrozenNodeOutputsByGraph, NodeResultOrigin, ReplayEventTiming } from './GraphProcessor.js';
9
9
  import type { GraphProgress } from './GraphProgress.js';
10
10
  import type { RivetWebAppStorage } from './UiGraphWebAppStorage.js';
11
11
  export type GraphInputs = Record<string, DataValue>;
@@ -20,7 +20,7 @@ export type CodeConsoleMessage = {
20
20
  };
21
21
  type WithExecution<T extends object> = T & {
22
22
  execution: GraphExecutionMetadata;
23
- };
23
+ } & ReplayEventTiming;
24
24
  export type SerializedProcessEventMap = {
25
25
  start: WithExecution<{
26
26
  project: Project;
@@ -105,6 +105,8 @@ export type SerializedProcessEventMap = {
105
105
  progress: GraphProgress;
106
106
  }>;
107
107
  llmCallFinished: WithExecution<ChatV2CallTraceEvent>;
108
+ llmChatOutputSnapshot: WithExecution<LLMChatOutputSnapshotEvent>;
109
+ llmProfileAttempt: WithExecution<LLMProfileAttemptTraceEvent>;
108
110
  toolCallFinished: WithExecution<ToolCallFinishedEvent>;
109
111
  nodeOutputsCleared: WithExecution<{
110
112
  node: ChartNode;
@@ -112,14 +114,14 @@ export type SerializedProcessEventMap = {
112
114
  }>;
113
115
  error: {
114
116
  error: Error | string;
115
- };
117
+ } & ReplayEventTiming;
116
118
  done: {
117
119
  results: GraphOutputs;
118
- };
120
+ } & ReplayEventTiming;
119
121
  abort: {
120
122
  successful: boolean;
121
123
  error?: string | Error;
122
- };
124
+ } & ReplayEventTiming;
123
125
  finish: void;
124
126
  trace: string;
125
127
  /** Present only when RecordingPlayer re-emits a historical lifecycle transition. */
@@ -161,6 +163,8 @@ export type ProcessEventMessageMap = {
161
163
  partialOutput: SerializedProcessEventMap['partialOutput'];
162
164
  progress: SerializedProcessEventMap['progress'];
163
165
  llmCallFinished: SerializedProcessEventMap['llmCallFinished'];
166
+ llmChatOutputSnapshot: SerializedProcessEventMap['llmChatOutputSnapshot'];
167
+ llmProfileAttempt: SerializedProcessEventMap['llmProfileAttempt'];
164
168
  toolCallFinished: SerializedProcessEventMap['toolCallFinished'];
165
169
  nodeOutputsCleared: SerializedProcessEventMap['nodeOutputsCleared'];
166
170
  error: SerializedProcessEventMap['error'];
@@ -238,6 +242,13 @@ export type OutgoingMessageMap = {
238
242
  projectPath?: string | null;
239
243
  useEditorCache?: boolean;
240
244
  captureNodeTimings?: boolean;
245
+ evaluation?: EvaluationExecutionMetadata;
246
+ /**
247
+ * An opaque, host-owned ID that lets a trusted executor join an unhealthy
248
+ * LLM Profile attempt to a recording persisted after this editor run.
249
+ * It is not graph input and is never forwarded to a model provider.
250
+ */
251
+ llmProfileHealthExecutionCorrelationId?: string;
241
252
  returnWhenGraphOutputsReady?: boolean;
242
253
  webAppStorage?: RivetWebAppStorage;
243
254
  };