@valerypopoff/rivet2-core 2.5.0 → 2.7.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 (88) hide show
  1. package/dist/cjs/bundle.cjs +3104 -850
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/interpolationRuntime.cjs +7 -3
  4. package/dist/cjs/interpolationRuntime.cjs.map +2 -2
  5. package/dist/cjs/webAppRuntime.cjs.map +2 -2
  6. package/dist/esm/api/createProcessor.js +3 -0
  7. package/dist/esm/exports.js +2 -1
  8. package/dist/esm/integrations/CodeRunner.js +6 -2
  9. package/dist/esm/integrations/mcp/MCPBase.js +2 -1
  10. package/dist/esm/model/AgentResponseTrace.js +8 -3
  11. package/dist/esm/model/ExecutionOutputClone.js +46 -0
  12. package/dist/esm/model/GlobalVariables.js +452 -0
  13. package/dist/esm/model/GraphBoundaryEffects.js +12 -4
  14. package/dist/esm/model/GraphProcessor.js +865 -46
  15. package/dist/esm/model/Nodes.js +6 -0
  16. package/dist/esm/model/ProcessContextBuilder.js +4 -1
  17. package/dist/esm/model/ProjectReferenceLoader.js +36 -1
  18. package/dist/esm/model/RecordingPlayer.js +58 -14
  19. package/dist/esm/model/SplitRunProcessor.js +37 -16
  20. package/dist/esm/model/StreamingOutputWatch.js +262 -0
  21. package/dist/esm/model/StreamingOutputWatchHistory.js +161 -0
  22. package/dist/esm/model/SubprocessorBridge.js +29 -19
  23. package/dist/esm/model/UiGraphRendererStyles.js +20 -0
  24. package/dist/esm/model/chat/aiSdkStreaming.js +3 -2
  25. package/dist/esm/model/chat-v2/aiSdkBridge.js +63 -5
  26. package/dist/esm/model/chat-v2/chatV2Pipeline.js +66 -3
  27. package/dist/esm/model/chat-v2/llmChatV2OutputClone.js +3 -42
  28. package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +20 -7
  29. package/dist/esm/model/chat-v2/llmProfileFallback.js +12 -4
  30. package/dist/esm/model/nodes/CodeNewNode.js +4 -1
  31. package/dist/esm/model/nodes/ExpressionNode.js +4 -1
  32. package/dist/esm/model/nodes/ExtractObjectPathNode.js +4 -4
  33. package/dist/esm/model/nodes/GraphOutputNode.js +13 -8
  34. package/dist/esm/model/nodes/LLMChatV2Node.js +30 -4
  35. package/dist/esm/model/nodes/MCPGetPromptNode.js +2 -1
  36. package/dist/esm/model/nodes/MCPToolCallNode.js +2 -1
  37. package/dist/esm/model/nodes/ObjectNode.js +5 -3
  38. package/dist/esm/model/nodes/PromptNode.js +5 -2
  39. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +9 -1
  40. package/dist/esm/model/nodes/StopWatchingStreamingOutputNode.js +48 -0
  41. package/dist/esm/model/nodes/SubGraphNode.js +11 -1
  42. package/dist/esm/model/nodes/TextNode.js +5 -2
  43. package/dist/esm/model/nodes/ToTreeNode.js +10 -3
  44. package/dist/esm/model/nodes/ToolNode.js +5 -2
  45. package/dist/esm/model/nodes/WatchStreamingOutputNode.js +126 -0
  46. package/dist/esm/model/nodes/jsListCallbackHelpers.js +7 -1
  47. package/dist/esm/model/nodes/jsValueInterpolation.js +21 -4
  48. package/dist/esm/plugins/openai/nodes/ThreadMessageNode.js +2 -1
  49. package/dist/esm/recording/ExecutionRecorder.js +71 -30
  50. package/dist/esm/utils/interpolation.js +35 -2
  51. package/dist/esm/utils/serialization/serializationUtils.js +9 -0
  52. package/dist/esm/utils/serialization/serialization_v4.js +7 -0
  53. package/dist/types/exports.d.ts +2 -1
  54. package/dist/types/integrations/CodeRunner.d.ts +3 -3
  55. package/dist/types/integrations/CodeRunnerOptions.d.ts +5 -0
  56. package/dist/types/integrations/mcp/MCPBase.d.ts +1 -1
  57. package/dist/types/model/AgentResponseTrace.d.ts +2 -0
  58. package/dist/types/model/ExecutionOutputClone.d.ts +11 -0
  59. package/dist/types/model/ExecutorProtocol.d.ts +12 -2
  60. package/dist/types/model/GlobalVariables.d.ts +29 -0
  61. package/dist/types/model/GraphBoundaryEffects.d.ts +7 -1
  62. package/dist/types/model/GraphProcessor.d.ts +55 -3
  63. package/dist/types/model/Nodes.d.ts +4 -2
  64. package/dist/types/model/ProcessContext.d.ts +20 -0
  65. package/dist/types/model/ProcessContextBuilder.d.ts +4 -1
  66. package/dist/types/model/Project.d.ts +7 -1
  67. package/dist/types/model/ProjectReferenceLoader.d.ts +15 -1
  68. package/dist/types/model/SplitRunProcessor.d.ts +2 -1
  69. package/dist/types/model/StreamingOutputWatch.d.ts +74 -0
  70. package/dist/types/model/StreamingOutputWatchHistory.d.ts +58 -0
  71. package/dist/types/model/SubprocessorBridge.d.ts +2 -0
  72. package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
  73. package/dist/types/model/chat/aiSdkStreaming.d.ts +1 -1
  74. package/dist/types/model/chat-v2/chatV2RequestPlan.d.ts +1 -1
  75. package/dist/types/model/chat-v2/chatV2Types.d.ts +29 -0
  76. package/dist/types/model/chat-v2/llmChatV2OutputClone.d.ts +3 -3
  77. package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +5 -1
  78. package/dist/types/model/nodes/ExtractObjectPathNode.d.ts +1 -1
  79. package/dist/types/model/nodes/GraphOutputNode.d.ts +8 -1
  80. package/dist/types/model/nodes/ObjectNode.d.ts +1 -1
  81. package/dist/types/model/nodes/StopWatchingStreamingOutputNode.d.ts +14 -0
  82. package/dist/types/model/nodes/ToTreeNode.d.ts +5 -1
  83. package/dist/types/model/nodes/WatchStreamingOutputNode.d.ts +17 -0
  84. package/dist/types/model/nodes/jsValueInterpolation.d.ts +10 -1
  85. package/dist/types/recording/ExecutionRecorder.d.ts +6 -1
  86. package/dist/types/recording/RecordedEvents.d.ts +9 -0
  87. package/dist/types/utils/interpolation.d.ts +14 -5
  88. package/package.json +1 -1
@@ -1,4 +1,5 @@
1
1
  import { dedent } from 'ts-dedent';
2
+ import { getInterpolationGlobalValues } from '../../utils/interpolation.js';
2
3
  import { buildClonedInputValueAssignments, buildJsValueInterpolatedSource, buildJsValueInputClonePreamble, buildJsValuePreview, getJsValueInterpolationCodeRunnerOptions, getJsValueInterpolationInputDefinitions, getJsValueInterpolationRuntimeContext, interpolateJsValuePreviewSource, sanitizeGeneratedJsValueError, } from './jsValueInterpolation.js';
3
4
  const MAX_CALLBACK_PREVIEW_BODY_LINES = 13;
4
5
  const JS_LIST_CALLBACK_SIGNATURE = '(item, index, array)';
@@ -37,6 +38,9 @@ function buildJSListRuntimePreamble(interpolationContext) {
37
38
  cacheIdentifier: interpolationContext.cloneCacheIdentifier,
38
39
  contextIdentifier: interpolationContext.contextIdentifier,
39
40
  graphInputsIdentifier: interpolationContext.graphInputsIdentifier,
41
+ globalValuesCloneIdentifier: interpolationContext.globalValuesCloneIdentifier,
42
+ globalValuesIdentifier: interpolationContext.globalValuesIdentifier,
43
+ usesGlobalValues: interpolationContext.requiresGlobalValues,
40
44
  inputsIdentifier: interpolationContext.inputsIdentifier,
41
45
  })}
42
46
  const array = cloneJsInputValue(inputs.array?.value, ${interpolationContext.cloneCacheIdentifier});
@@ -54,6 +58,8 @@ function sanitizeJSListError(error, callbackBody, nodeName) {
54
58
  return sanitizeGeneratedJsValueError(error, interpolationContext.inputNames, interpolationContext.inputsIdentifier, fallbackLabel, [
55
59
  interpolationContext.cloneCacheIdentifier,
56
60
  interpolationContext.contextIdentifier,
61
+ interpolationContext.globalValuesCloneIdentifier,
62
+ interpolationContext.globalValuesIdentifier,
57
63
  interpolationContext.graphInputsIdentifier,
58
64
  interpolationContext.interpolationHelperIdentifier,
59
65
  ]);
@@ -186,7 +192,7 @@ export function assertJSListNodeOutputs(outputs, outputId, nodeName) {
186
192
  }
187
193
  export async function runJSListNodeCode({ buildWrapper, callbackBody, context, inputs, nodeName, outputId, }) {
188
194
  try {
189
- const outputs = await context.codeRunner.runCode(buildWrapper(callbackBody), inputs, getJsValueInterpolationCodeRunnerOptions(JS_LIST_CODE_RUNNER_OPTIONS, getJSListInterpolationContext(callbackBody)), context.graphInputNodeValues, context.contextValues);
195
+ const outputs = await context.codeRunner.runCode(buildWrapper(callbackBody), inputs, getJsValueInterpolationCodeRunnerOptions(JS_LIST_CODE_RUNNER_OPTIONS, getJSListInterpolationContext(callbackBody)), context.graphInputNodeValues, context.contextValues, getInterpolationGlobalValues(callbackBody, context.getGlobal));
190
196
  assertJSListNodeOutputs(outputs, outputId, nodeName);
191
197
  return outputs;
192
198
  }
@@ -2,7 +2,8 @@ import { dedent } from 'ts-dedent';
2
2
  import { createInterpolationInputDefinition } from '../interpolationInputDefinition.js';
3
3
  import { getError } from '../../utils/errors.js';
4
4
  import { extractInterpolationVariables, parseInterpolationTemplate, replaceInterpolationTokens, resolveInterpolationExpressionRawValue, } from '../../utils/interpolation.js';
5
- const MISSING_INTERPOLATION_HELPER_MESSAGE = 'This CodeRunner must honor CodeRunnerOptions.interpolationHelperIdentifier to resolve JSONPath or @graphInputs/@context interpolation.';
5
+ const MISSING_INTERPOLATION_HELPER_MESSAGE = 'This CodeRunner must honor CodeRunnerOptions.interpolationHelperIdentifier to resolve JSONPath or @graphInputs/@context/@globals interpolation.';
6
+ const MISSING_GLOBAL_VALUES_MESSAGE = 'This CodeRunner must honor CodeRunnerOptions.globalValuesIdentifier to resolve @globals interpolation.';
6
7
  function escapeRegExp(value) {
7
8
  return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
8
9
  }
@@ -41,7 +42,7 @@ function buildJsValueReference(token, interpolationContext, options) {
41
42
  const sourceInputs = isLocalReference
42
43
  ? `{ ${JSON.stringify(token.reference.baseName)}: { type: 'any', value: ${token.reference.baseName} } }`
43
44
  : interpolationContext.inputsIdentifier;
44
- const resolveExpression = `${interpolationContext.interpolationHelperIdentifier}(${sourceInputs}, ${JSON.stringify(token.tokenName)}, ${interpolationContext.graphInputsIdentifier}, ${interpolationContext.contextIdentifier})`;
45
+ const resolveExpression = `${interpolationContext.interpolationHelperIdentifier}(${sourceInputs}, ${JSON.stringify(token.tokenName)}, ${interpolationContext.graphInputsIdentifier}, ${interpolationContext.contextIdentifier}, ${interpolationContext.globalValuesCloneIdentifier})`;
45
46
  return `(typeof ${interpolationContext.interpolationHelperIdentifier} === 'function'
46
47
  ? ${resolveExpression}
47
48
  : (() => { throw new Error(${JSON.stringify(MISSING_INTERPOLATION_HELPER_MESSAGE)}); })())`;
@@ -84,6 +85,8 @@ export function getJsValueInterpolationRuntimeContext(template, baseInputsIdenti
84
85
  const cloneCacheIdentifier = getSafeJsValueInterpolationIdentifier(`${template}\n${inputsIdentifier}\n${interpolationHelperIdentifier}`, `${baseInputsIdentifier}CloneCache`);
85
86
  const graphInputsIdentifier = getSafeJsValueInterpolationIdentifier(`${template}\n${inputsIdentifier}\n${interpolationHelperIdentifier}\n${cloneCacheIdentifier}`, `${baseInputsIdentifier}GraphInputs`);
86
87
  const contextIdentifier = getSafeJsValueInterpolationIdentifier(`${template}\n${inputsIdentifier}\n${interpolationHelperIdentifier}\n${cloneCacheIdentifier}\n${graphInputsIdentifier}`, `${baseInputsIdentifier}Context`);
88
+ const globalValuesIdentifier = getSafeJsValueInterpolationIdentifier(`${template}\n${inputsIdentifier}\n${interpolationHelperIdentifier}\n${cloneCacheIdentifier}\n${graphInputsIdentifier}\n${contextIdentifier}`, `${baseInputsIdentifier}Globals`);
89
+ const globalValuesCloneIdentifier = getSafeJsValueInterpolationIdentifier(`${template}\n${inputsIdentifier}\n${interpolationHelperIdentifier}\n${cloneCacheIdentifier}\n${graphInputsIdentifier}\n${contextIdentifier}\n${globalValuesIdentifier}`, `${baseInputsIdentifier}GlobalValues`);
87
90
  const parsedTemplate = parseInterpolationTemplate(template);
88
91
  return {
89
92
  inputNames: getJsValueInterpolationInputNames(template, options),
@@ -92,8 +95,11 @@ export function getJsValueInterpolationRuntimeContext(template, baseInputsIdenti
92
95
  cloneCacheIdentifier,
93
96
  graphInputsIdentifier,
94
97
  contextIdentifier,
98
+ globalValuesIdentifier,
99
+ globalValuesCloneIdentifier,
95
100
  requiresInterpolationHelper: parsedTemplate.tokens.some((token) => token.reference !== undefined &&
96
101
  (token.reference.source !== 'variable' || token.reference.jsonPath !== undefined)),
102
+ requiresGlobalValues: parsedTemplate.tokens.some((token) => token.reference?.source === 'globals'),
97
103
  };
98
104
  }
99
105
  export function buildJsValueInterpolatedSource(template, interpolationContext, options = {}) {
@@ -206,7 +212,7 @@ export function buildClonedInputValueAssignments(inputNames, targetIdentifier, c
206
212
  })();`)
207
213
  .join('\n');
208
214
  }
209
- export function buildJsValueInputClonePreamble({ cacheIdentifier, contextIdentifier, graphInputsIdentifier, inputsIdentifier, }) {
215
+ export function buildJsValueInputClonePreamble({ cacheIdentifier, contextIdentifier, graphInputsIdentifier, globalValuesCloneIdentifier, globalValuesIdentifier, usesGlobalValues, inputsIdentifier, }) {
210
216
  return dedent `
211
217
  ${buildCloneJsInputValueFunction()}
212
218
  const ${inputsIdentifier} = Object.create(null);
@@ -217,15 +223,23 @@ export function buildJsValueInputClonePreamble({ cacheIdentifier, contextIdentif
217
223
  const ${contextIdentifier} = typeof context === 'undefined'
218
224
  ? Object.create(null)
219
225
  : cloneJsInputValue(context, ${cacheIdentifier});
226
+ const ${globalValuesCloneIdentifier} = ${usesGlobalValues
227
+ ? `typeof ${globalValuesIdentifier} === 'undefined'
228
+ ? (() => { throw new Error(${JSON.stringify(MISSING_GLOBAL_VALUES_MESSAGE)}); })()
229
+ : cloneJsInputValue(${globalValuesIdentifier}, ${cacheIdentifier})`
230
+ : 'Object.create(null)'};
220
231
  `;
221
232
  }
222
233
  export function buildJsValueInputsInitializer({ interpolationContext, }) {
223
- const { cloneCacheIdentifier, contextIdentifier, graphInputsIdentifier, inputNames, inputsIdentifier } = interpolationContext;
234
+ const { cloneCacheIdentifier, contextIdentifier, globalValuesCloneIdentifier, globalValuesIdentifier, graphInputsIdentifier, inputNames, inputsIdentifier, } = interpolationContext;
224
235
  return dedent `
225
236
  ${buildJsValueInputClonePreamble({
226
237
  cacheIdentifier: cloneCacheIdentifier,
227
238
  contextIdentifier,
228
239
  graphInputsIdentifier,
240
+ globalValuesCloneIdentifier,
241
+ globalValuesIdentifier,
242
+ usesGlobalValues: interpolationContext.requiresGlobalValues,
229
243
  inputsIdentifier,
230
244
  })}
231
245
  ${buildClonedInputValueAssignments(inputNames, inputsIdentifier, cloneCacheIdentifier)}
@@ -238,6 +252,9 @@ export function getJsValueInterpolationCodeRunnerOptions(options, interpolationC
238
252
  return {
239
253
  ...options,
240
254
  interpolationHelperIdentifier: interpolationContext.interpolationHelperIdentifier,
255
+ ...(interpolationContext.requiresGlobalValues
256
+ ? { globalValuesIdentifier: interpolationContext.globalValuesIdentifier }
257
+ : {}),
241
258
  };
242
259
  }
243
260
  export function sanitizeGeneratedJsValueText(text, inputNames, targetIdentifier, fallbackLabel, generatedIdentifiers = []) {
@@ -1,6 +1,6 @@
1
1
  import {} from '../../../index.js';
2
2
  import { newId, coerceTypeOptional, getInputOrData } from '../../../utils/index.js';
3
- import { extractInterpolationVariableReferences, interpolate } from '../../../utils/interpolation.js';
3
+ import { extractInterpolationVariableReferences, getInterpolationGlobalValues, interpolate } from '../../../utils/interpolation.js';
4
4
  import { pluginNodeDefinition } from '../../../model/NodeDefinition.js';
5
5
  import { createInterpolationInputDefinition } from '../../../model/interpolationInputDefinition.js';
6
6
  export const ThreadMessageNodeImpl = {
@@ -127,6 +127,7 @@ export const ThreadMessageNodeImpl = {
127
127
  }
128
128
  const interpolated = interpolate(text, inputData, context?.graphInputNodeValues, context?.contextValues, {
129
129
  coerceBareVariableDataValues: true,
130
+ globalValues: getInterpolationGlobalValues(text, context?.getGlobal),
130
131
  });
131
132
  // Here you would typically make a call to an API to create the message
132
133
  // For the sake of this example, we'll just return the data as is
@@ -37,13 +37,22 @@ const toRecordedEventMap = {
37
37
  processId,
38
38
  ...(resultOrigin === undefined ? {} : { resultOrigin }),
39
39
  }, durationMs, splitRunDurationMs), execution),
40
- nodeError: ({ node, error, processId, resultOrigin, durationMs, splitRunDurationMs, execution }) => withExecution(withDuration({
40
+ nodeError: ({ node, error, processId, outputs, splitOutputs, resultOrigin, durationMs, splitRunDurationMs, execution }) => withExecution(withDuration({
41
41
  nodeId: node.id,
42
42
  error: typeof error === 'string' ? error : error.stack,
43
43
  processId,
44
+ ...(outputs === undefined ? {} : { outputs }),
45
+ ...(splitOutputs === undefined ? {} : { splitOutputs }),
44
46
  ...(resultOrigin === undefined ? {} : { resultOrigin }),
45
47
  }, durationMs, splitRunDurationMs), execution),
46
- abort: ({ successful, error }) => ({ successful, error: typeof error === 'string' ? error : error?.stack }),
48
+ // Older debugger servers sent a null abort payload. Preserve that evidence
49
+ // instead of letting a malformed legacy transport message abort the whole
50
+ // recording. An unknown payload is deliberately treated as unsuccessful;
51
+ // it must never be mistaken for a completed graph run during replay.
52
+ abort: (data) => {
53
+ const { successful, error } = data ?? {};
54
+ return { successful: successful === true, error: typeof error === 'string' ? error : error?.stack };
55
+ },
47
56
  graphAbort: ({ successful, error, graph, execution }) => withExecution({
48
57
  successful,
49
58
  error: typeof error === 'string' ? error : error?.stack,
@@ -85,6 +94,7 @@ const toRecordedEventMap = {
85
94
  nodeId: node.id,
86
95
  processId,
87
96
  }, execution),
97
+ streamingOutputWatchSummary: ({ watchNode, summary, execution }) => withExecution({ watchNodeId: watchNode.id, summary }, execution),
88
98
  error: ({ error }) => ({
89
99
  error: typeof error === 'string' ? error : error.stack,
90
100
  }),
@@ -118,28 +128,40 @@ function toRecordedEvent(event, data) {
118
128
  ts: Date.now(),
119
129
  };
120
130
  }
121
- const recordableData = omitReplayRecordedAt(data);
131
+ const { recordableData, occurredAt } = omitTransientEventTiming(data);
122
132
  const recordedEvent = {
123
133
  type: event,
124
134
  data: toRecordedEventMap[event](recordableData),
125
135
  ts: Date.now(),
136
+ ...(occurredAt === undefined ? {} : { occurredAt }),
126
137
  };
127
138
  return recordedEvent;
128
139
  }
129
140
  /**
130
141
  * 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.
142
+ * itself. A deferred Watch event additionally carries the moment it occurred;
143
+ * persist that separately while retaining the append-time `ts` so recording
144
+ * order remains monotonic and replayable.
133
145
  */
134
- function omitReplayRecordedAt(data) {
146
+ function omitTransientEventTiming(data) {
135
147
  if (data == null || typeof data !== 'object')
136
- return data;
137
- const { replayRecordedAt: _replayRecordedAt, ...recordableData } = data;
138
- return recordableData;
148
+ return { recordableData: data, occurredAt: undefined };
149
+ const { replayRecordedAt: _replayRecordedAt, eventOccurredAt, ...recordableData } = data;
150
+ return {
151
+ recordableData: recordableData,
152
+ occurredAt: isRecordedTimestamp(eventOccurredAt) ? eventOccurredAt : undefined,
153
+ };
154
+ }
155
+ function isRecordedTimestamp(value) {
156
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0;
139
157
  }
140
158
  function isRecordableProcessEvent(message) {
141
159
  return message in toRecordedEventMap || isPrefix(message, 'globalSet:') || isPrefix(message, 'userEvent:');
142
160
  }
161
+ // WebSocket.OPEN/CLOSED are static browser constants. Core is also used by
162
+ // Node transports that can supply a compatible socket without installing that
163
+ // browser global, so compare the standardized ready-state value directly.
164
+ const CLOSED_WEBSOCKET_READY_STATE = 3;
143
165
  function mapValuesDeep(obj, fn) {
144
166
  if (Array.isArray(obj)) {
145
167
  return obj.map((value) => {
@@ -233,14 +255,22 @@ export class ExecutionRecorder {
233
255
  return new Promise((resolve) => {
234
256
  this.recordingId = nanoid();
235
257
  let settled = false;
236
- const finish = () => {
258
+ const finish = (emitFinishedRecording) => {
237
259
  if (settled)
238
260
  return;
239
261
  settled = true;
240
262
  channel.removeEventListener('message', listener);
241
- options.signal?.removeEventListener('abort', finish);
263
+ channel.removeEventListener('close', onClose);
264
+ options.signal?.removeEventListener('abort', onOwnerDisposed);
265
+ if (emitFinishedRecording) {
266
+ emitDetached(this.#emitter, 'finish', {
267
+ recording: this.getRecording(),
268
+ });
269
+ }
242
270
  resolve();
243
271
  };
272
+ const onClose = () => finish(false);
273
+ const onOwnerDisposed = () => finish(false);
244
274
  const listener = (event) => {
245
275
  let payload;
246
276
  try {
@@ -265,24 +295,39 @@ export class ExecutionRecorder {
265
295
  return;
266
296
  }
267
297
  this.#events.push(toRecordedEvent(message, data));
268
- if (isRecordingTerminalEvent(message, data)) {
269
- emitDetached(this.#emitter, 'finish', {
270
- recording: this.getRecording(),
271
- });
272
- finish();
298
+ if (isSocketRecordingTerminalEvent(message)) {
299
+ finish(true);
273
300
  }
274
301
  };
275
302
  if (options.signal?.aborted) {
276
- finish();
303
+ onOwnerDisposed();
277
304
  return;
278
305
  }
279
306
  channel.addEventListener('message', listener);
280
- options.signal?.addEventListener('abort', finish, { once: true });
307
+ channel.addEventListener('close', onClose, { once: true });
308
+ options.signal?.addEventListener('abort', onOwnerDisposed, { once: true });
309
+ if (channel.readyState === CLOSED_WEBSOCKET_READY_STATE) {
310
+ onClose();
311
+ }
281
312
  });
282
313
  }
283
314
  record(processor) {
284
315
  this.recordingId = nanoid();
285
- processor.onAny((event, data) => {
316
+ let settled = false;
317
+ const finish = () => {
318
+ if (settled)
319
+ return;
320
+ settled = true;
321
+ unsubscribeAny();
322
+ unsubscribeFinish();
323
+ emitDetached(this.#emitter, 'finish', {
324
+ recording: this.getRecording(),
325
+ });
326
+ };
327
+ const unsubscribeAny = processor.onAny((event, data) => {
328
+ if (settled || event === 'finish') {
329
+ return;
330
+ }
286
331
  if (this.#includePartialOutputs === false && event === 'partialOutput') {
287
332
  return;
288
333
  }
@@ -290,17 +335,16 @@ export class ExecutionRecorder {
290
335
  return;
291
336
  }
292
337
  this.#events.push(toRecordedEvent(event, data));
293
- if (isRecordingTerminalEvent(event, data)) {
294
- emitDetached(this.#emitter, 'finish', {
295
- recording: this.getRecording(),
296
- });
297
- }
298
338
  });
339
+ const unsubscribeFinish = processor.on('finish', finish);
299
340
  }
300
341
  getRecording() {
301
342
  return {
302
343
  recordingId: this.recordingId,
303
- events: this.#events,
344
+ // Callers persist and replay recordings asynchronously. Returning the
345
+ // live backing array would let a later event mutate an already-finished
346
+ // recording snapshot.
347
+ events: [...this.#events],
304
348
  startTs: this.#events[0]?.ts ?? 0,
305
349
  finishTs: this.#events[this.#events.length - 1]?.ts ?? 0,
306
350
  };
@@ -334,9 +378,6 @@ export class ExecutionRecorder {
334
378
  return stringifyJsonStream(serializeToObject(this.getRecording()));
335
379
  }
336
380
  }
337
- function isRecordingTerminalEvent(event, data) {
338
- if (event === 'done' || event === 'error') {
339
- return true;
340
- }
341
- return event === 'abort' && data.successful !== true;
381
+ function isSocketRecordingTerminalEvent(event) {
382
+ return event === 'done' || event === 'error';
342
383
  }
@@ -269,6 +269,7 @@ function parseInterpolationExpressionUncached(trimmedExpression) {
269
269
  for (const [prefix, source] of [
270
270
  ['@graphInputs', 'graphInputs'],
271
271
  ['@context', 'context'],
272
+ ['@globals', 'globals'],
272
273
  ]) {
273
274
  if (trimmedExpression.startsWith(`${prefix}.`)) {
274
275
  return parseBaseReference(trimmedExpression.slice(prefix.length + 1), source);
@@ -428,7 +429,7 @@ export function replaceInterpolationTokens(template, getReplacement, options = {
428
429
  }
429
430
  /**
430
431
  * Discovers connectable interpolation bases in first-occurrence order. Special
431
- * graph/context references are intentionally omitted because they do not make ports.
432
+ * graph/context/global references are intentionally omitted because they do not make ports.
432
433
  */
433
434
  export function extractInterpolationVariableReferences(template) {
434
435
  if (!template.includes('{{')) {
@@ -452,6 +453,33 @@ export function extractInterpolationVariableReferences(template) {
452
453
  }
453
454
  return Array.from(discovered.values(), (reference) => ({ ...reference }));
454
455
  }
456
+ /**
457
+ * Captures only globals referenced by a template into a safe record. Globals
458
+ * are intentionally snapshotted at node execution: interpolation neither
459
+ * waits for a writer nor creates an execution dependency.
460
+ */
461
+ export function getInterpolationGlobalValues(template, getGlobal) {
462
+ const values = Object.create(null);
463
+ if (!getGlobal || !template.includes('{{')) {
464
+ return values;
465
+ }
466
+ for (const token of parseInterpolationTemplate(template).tokens) {
467
+ const reference = token.reference;
468
+ if (!reference || reference.source !== 'globals' || Object.prototype.hasOwnProperty.call(values, reference.baseName)) {
469
+ continue;
470
+ }
471
+ const value = getGlobal(reference.baseName);
472
+ if (value !== undefined) {
473
+ Object.defineProperty(values, reference.baseName, {
474
+ configurable: true,
475
+ enumerable: true,
476
+ value,
477
+ writable: true,
478
+ });
479
+ }
480
+ }
481
+ return values;
482
+ }
455
483
  /** Extracts base port names only. Prefer `extractInterpolationVariableReferences` when type selection matters. */
456
484
  export function extractInterpolationVariables(template) {
457
485
  return extractInterpolationVariableReferences(template).map((reference) => reference.baseName);
@@ -464,6 +492,8 @@ function getInterpolationSource(reference, sources) {
464
492
  return sources.graphInputValues;
465
493
  case 'context':
466
494
  return sources.contextValues;
495
+ case 'globals':
496
+ return sources.globalValues;
467
497
  }
468
498
  }
469
499
  /**
@@ -503,6 +533,7 @@ export function resolveExpressionRawValue(source, expression, sourceType) {
503
533
  return resolveInterpolationExpressionRawValue(`@${sourceType}.${expression}`, {
504
534
  graphInputValues: sourceType === 'graphInputs' ? source : undefined,
505
535
  contextValues: sourceType === 'context' ? source : undefined,
536
+ globalValues: sourceType === 'globals' ? source : undefined,
506
537
  });
507
538
  }
508
539
  function stringifyInterpolationValue(value) {
@@ -557,6 +588,7 @@ export function interpolate(template, variables, graphInputValues, contextValues
557
588
  variables,
558
589
  graphInputValues,
559
590
  contextValues,
591
+ globalValues: options.globalValues,
560
592
  unwrapVariableDataValues: options.unwrapVariableDataValues,
561
593
  });
562
594
  if (resolvedValue === undefined) {
@@ -574,10 +606,11 @@ export function interpolate(template, variables, graphInputValues, contextValues
574
606
  });
575
607
  }
576
608
  /** Runtime helper injected into JavaScript runners without exposing the whole Rivet API. */
577
- export function resolveCodeInterpolationExpression(inputs, expression, graphInputValues, contextValues) {
609
+ export function resolveCodeInterpolationExpression(inputs, expression, graphInputValues, contextValues, globalValues) {
578
610
  return resolveInterpolationExpressionRawValue(expression, {
579
611
  variables: inputs,
580
612
  graphInputValues,
581
613
  contextValues,
614
+ globalValues,
582
615
  });
583
616
  }
@@ -1,6 +1,7 @@
1
1
  import { formatUiGraphNormalizationIssue, normalizeUiGraphRecord, UiGraphNormalizationError, } from '../../model/UiGraphNormalization.js';
2
2
  import { prepareSerializedInput } from './serializationInput.js';
3
3
  import { isReservedKnowledgeObjectKey, normalizeKnowledgeConnectionId, normalizeKnowledgeMetadata, } from '../../integrations/KnowledgeStoreValidation.js';
4
+ import { validateProjectGlobalVariables } from '../../model/GlobalVariables.js';
4
5
  export class ProjectValidationError extends Error {
5
6
  validation;
6
7
  constructor(validation) {
@@ -29,6 +30,14 @@ export function validateProject(project) {
29
30
  errors.push('Missing project metadata.title');
30
31
  if (meta.knowledgeStores != null)
31
32
  validateKnowledgeStores(meta.knowledgeStores, errors);
33
+ if (meta.globalVariables != null) {
34
+ try {
35
+ validateProjectGlobalVariables(meta.globalVariables);
36
+ }
37
+ catch (error) {
38
+ errors.push(error instanceof Error ? error.message : String(error));
39
+ }
40
+ }
32
41
  }
33
42
  // Graphs checks
34
43
  if (!p.graphs || typeof p.graphs !== 'object') {
@@ -3,6 +3,7 @@ import { doubleCheckProject } from './serializationUtils.js';
3
3
  import { entries } from '../typeSafety.js';
4
4
  import {} from '../../model/Project.js';
5
5
  import { normalizeUiGraphRecord } from '../../model/UiGraphNormalization.js';
6
+ import { validateProjectGlobalVariables } from '../../model/GlobalVariables.js';
6
7
  import { serializeConnection, deserializeConnection, parseVisualData, packVisualDataV4, wrapInYamlEnvelope, unwrapYamlEnvelope, } from './serializationHelpers.js';
7
8
  export function projectV4Deserializer(data) {
8
9
  const serializedProject = unwrapYamlEnvelope(data, 4, 'Project v4');
@@ -15,6 +16,12 @@ export function graphV4Deserializer(data) {
15
16
  return fromSerializedGraph(serializedGraph);
16
17
  }
17
18
  export function projectV4Serializer(project, attachedData) {
19
+ // Project Settings canonicalizes these values, but integrations and callers
20
+ // can author Project objects directly. Never write a project file that will
21
+ // later fail its own project-global validation at load or execution time.
22
+ if (project.metadata.globalVariables != null) {
23
+ validateProjectGlobalVariables(project.metadata.globalVariables);
24
+ }
18
25
  const filteredProject = {
19
26
  ...project,
20
27
  metadata: {
@@ -24,6 +24,7 @@ export * from './model/NodeImpl.js';
24
24
  export * from './model/NodeDefinition.js';
25
25
  export * from './model/Nodes.js';
26
26
  export * from './model/Project.js';
27
+ export * from './model/GlobalVariables.js';
27
28
  export * from './native/BaseDir.js';
28
29
  export * from './native/NativeApi.js';
29
30
  export * from './native/BrowserNativeApi.js';
@@ -68,7 +69,7 @@ export * from './integrations/Tokenizer.js';
68
69
  export * from './integrations/GptTokenizerTokenizer.js';
69
70
  export { JS_LIST_CALLBACK_LOCAL_NAMES, interpolateJSListCallbackBody } from './model/nodes/jsListCallbackHelpers.js';
70
71
  export { findAutoDelegateGraphCandidate } from './model/nodes/toolCallDelegation.js';
71
- export { extractInterpolationVariables, extractInterpolationVariableReferences, findInterpolationTokenSpans, getInterpolationTokenReference, getInterpolationTokenName, interpolate, parseInterpolationExpression, parseInterpolationTemplate, protectEscapedInterpolationTokens, resolveCodeInterpolationExpression, resolveInterpolationExpressionRawValue, resolveInterpolationTokenRawValue, restoreEscapedInterpolationTokens, stringifyInterpolationSourceValue, } from './utils/interpolation.js';
72
+ export { extractInterpolationVariables, extractInterpolationVariableReferences, findInterpolationTokenSpans, getInterpolationGlobalValues, getInterpolationTokenReference, getInterpolationTokenName, interpolate, parseInterpolationExpression, parseInterpolationTemplate, protectEscapedInterpolationTokens, resolveCodeInterpolationExpression, resolveInterpolationExpressionRawValue, resolveInterpolationTokenRawValue, restoreEscapedInterpolationTokens, stringifyInterpolationSourceValue, } from './utils/interpolation.js';
72
73
  export type { InterpolateOptions, InterpolationReferenceSource, InterpolationTokenReplacementInfo, InterpolationTokenSpan, InterpolationValueSources, InterpolationVariableReference, ParsedInterpolationExpression, ParsedInterpolationTemplate, ParsedInterpolationToken, ReplaceInterpolationTokensOptions, } from './utils/interpolation.js';
73
74
  export { scanInterpolationTokenSpans } from './utils/interpolationSyntax.js';
74
75
  export { WarningsPort } from './utils/symbols.js';
@@ -12,11 +12,11 @@ export type { CodeRunnerOptions } from './CodeRunnerOptions.js';
12
12
  */
13
13
  /** An object that can run arbitrary code (evals it). */
14
14
  export interface CodeRunner {
15
- runCode: (code: string, inputs: Inputs, options: CodeRunnerOptions, graphInputs?: Record<string, DataValue>, contextValues?: Record<string, DataValue>) => Promise<Outputs>;
15
+ runCode: (code: string, inputs: Inputs, options: CodeRunnerOptions, graphInputs?: Record<string, DataValue>, contextValues?: Record<string, DataValue>, globalValues?: Record<string, DataValue>) => Promise<Outputs>;
16
16
  }
17
17
  export declare class IsomorphicCodeRunner implements CodeRunner {
18
- runCode(code: string, inputs: Inputs, options: CodeRunnerOptions, graphInputs?: Record<string, DataValue>, contextValues?: Record<string, DataValue>): Promise<Outputs>;
18
+ runCode(code: string, inputs: Inputs, options: CodeRunnerOptions, graphInputs?: Record<string, DataValue>, contextValues?: Record<string, DataValue>, globalValues?: Record<string, DataValue>): Promise<Outputs>;
19
19
  }
20
20
  export declare class NotAllowedCodeRunner implements CodeRunner {
21
- runCode(_code: string, _inputs: Inputs, _options: CodeRunnerOptions, _graphInputs?: Record<string, DataValue>, _contextValues?: Record<string, DataValue>): Promise<Outputs>;
21
+ runCode(_code: string, _inputs: Inputs, _options: CodeRunnerOptions, _graphInputs?: Record<string, DataValue>, _contextValues?: Record<string, DataValue>, _globalValues?: Record<string, DataValue>): Promise<Outputs>;
22
22
  }
@@ -20,5 +20,10 @@ export interface CodeRunnerOptions {
20
20
  * and @graphInputs/@context references depend on that contract.
21
21
  */
22
22
  interpolationHelperIdentifier?: string;
23
+ /**
24
+ * The collision-safe name of the globals snapshot injected beside the
25
+ * interpolation helper. Generated wrappers use it only for @globals paths.
26
+ */
27
+ globalValuesIdentifier?: string;
23
28
  }
24
29
  export declare const ALL_CODE_RUNNER_OPTIONS: CodeRunnerOptions;
@@ -39,5 +39,5 @@ export declare function getMCPServerEditors<T extends ChartNode<string, MCPBaseN
39
39
  export declare function getMCPBaseBody(data: MCPBaseNodeData, context: RivetUIContext): string;
40
40
  export declare function requireMCPProvider(context: InternalProcessContext): MCPProvider;
41
41
  export declare function resolveMCPServer(data: MCPBaseNodeData, inputs: Inputs, context: InternalProcessContext): Promise<MCPResolvedServer | undefined>;
42
- export declare function interpolateMCPArgumentTemplate(template: string, inputs: Inputs, graphInputValues?: Record<string, DataValue>, contextValues?: Record<string, DataValue>): string;
42
+ export declare function interpolateMCPArgumentTemplate(template: string, inputs: Inputs, graphInputValues?: Record<string, DataValue>, contextValues?: Record<string, DataValue>, globalValues?: Record<string, unknown>): string;
43
43
  export declare function getMCPArgumentTemplateInputs(template: string | undefined): NodeInputDefinition[];
@@ -96,6 +96,8 @@ export type BuildAgentResponseTraceOptions = {
96
96
  events: readonly AgentTraceEvent[];
97
97
  nodeId?: NodeId;
98
98
  processId?: ProcessId;
99
+ /** Recorded whole-node duration for an LLM invocation; response traces retain their output-ready duration. */
100
+ invocationDurationMs?: number;
99
101
  startedAt?: number;
100
102
  responseReadyAt?: number;
101
103
  finishedAt?: number;
@@ -0,0 +1,11 @@
1
+ import type { Outputs } from './GraphProcessor.js';
2
+ /**
3
+ * Creates a cycle-safe copy at an execution-data ownership boundary.
4
+ *
5
+ * Providers may continue mutating output objects after a partial event. A
6
+ * snapshot, recorder, or deferred branch must therefore never retain the
7
+ * producer-owned reference.
8
+ */
9
+ export declare function cloneExecutionValue<T>(value: T): T;
10
+ /** Creates a cycle-safe snapshot specifically for a node output map. */
11
+ export declare function cloneExecutionOutputs(outputs: Outputs): Outputs;
@@ -5,8 +5,9 @@ import type { GraphId, NodeGraph } from './NodeGraph.js';
5
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, ReplayEventTiming } from './GraphProcessor.js';
8
+ import type { EventOccurrenceTiming, FrozenNodeOutputsByGraph, NodeResultOrigin, ReplayEventTiming } from './GraphProcessor.js';
9
9
  import type { GraphProgress } from './GraphProgress.js';
10
+ import type { StreamingOutputWatchHistorySummary } from './StreamingOutputWatchHistory.js';
10
11
  import type { RivetWebAppStorage } from './UiGraphWebAppStorage.js';
11
12
  export type GraphInputs = Record<string, DataValue>;
12
13
  export type GraphOutputs = Record<string, DataValue>;
@@ -20,7 +21,7 @@ export type CodeConsoleMessage = {
20
21
  };
21
22
  type WithExecution<T extends object> = T & {
22
23
  execution: GraphExecutionMetadata;
23
- } & ReplayEventTiming;
24
+ } & ReplayEventTiming & EventOccurrenceTiming;
24
25
  export type SerializedProcessEventMap = {
25
26
  start: WithExecution<{
26
27
  project: Project;
@@ -71,6 +72,10 @@ export type SerializedProcessEventMap = {
71
72
  node: ChartNode;
72
73
  error: Error | string;
73
74
  processId: ProcessId;
75
+ /** Display-only outputs retained by a failed non-split invocation. */
76
+ outputs?: Outputs;
77
+ /** Display-only outputs retained by individual failed split invocations. */
78
+ splitOutputs?: Record<number, Outputs>;
74
79
  resultOrigin?: NodeResultOrigin;
75
80
  durationMs?: number;
76
81
  splitRunDurationMs?: Record<number, number>;
@@ -112,6 +117,10 @@ export type SerializedProcessEventMap = {
112
117
  node: ChartNode;
113
118
  processId?: ProcessId;
114
119
  }>;
120
+ streamingOutputWatchSummary: WithExecution<{
121
+ watchNode: ChartNode;
122
+ summary: StreamingOutputWatchHistorySummary;
123
+ }>;
115
124
  error: {
116
125
  error: Error | string;
117
126
  } & ReplayEventTiming;
@@ -167,6 +176,7 @@ export type ProcessEventMessageMap = {
167
176
  llmProfileAttempt: SerializedProcessEventMap['llmProfileAttempt'];
168
177
  toolCallFinished: SerializedProcessEventMap['toolCallFinished'];
169
178
  nodeOutputsCleared: SerializedProcessEventMap['nodeOutputsCleared'];
179
+ streamingOutputWatchSummary: SerializedProcessEventMap['streamingOutputWatchSummary'];
170
180
  error: SerializedProcessEventMap['error'];
171
181
  graphError: SerializedProcessEventMap['graphError'];
172
182
  trace: string;
@@ -0,0 +1,29 @@
1
+ import { type ScalarOrArrayDataType, type ScalarOrArrayDataValue } from './DataValue.js';
2
+ import type { Project, ProjectId } from './Project.js';
3
+ /**
4
+ * A JSON-safe representation of a global value authored in project metadata.
5
+ *
6
+ * The marker is intentionally private to this codec. User objects with the
7
+ * marker key are escaped, so no ordinary object can be mistaken for a value
8
+ * sentinel after a project is saved and loaded again.
9
+ */
10
+ /** Runtime validation, rather than a recursive TypeScript JSON type, keeps Project usable with Immer. */
11
+ export type ProjectGlobalVariableLiteral = unknown;
12
+ export type ProjectGlobalVariableDefinition = {
13
+ type: ScalarOrArrayDataType;
14
+ value: ProjectGlobalVariableLiteral;
15
+ };
16
+ export type ProjectGlobalVariables = Record<string, ProjectGlobalVariableDefinition>;
17
+ /** Encodes a normal global value into a portable project-file definition. */
18
+ export declare function encodeProjectGlobalVariable(value: ScalarOrArrayDataValue): ProjectGlobalVariableDefinition;
19
+ /** Decodes and validates a single portable project-file global definition. */
20
+ export declare function decodeProjectGlobalVariable(value: unknown, label?: string): ScalarOrArrayDataValue;
21
+ /** Validates definitions without retaining decoded runtime values. */
22
+ export declare function validateProjectGlobalVariables(value: unknown, label?: string): void;
23
+ export declare function getProjectGlobalVariableIds(project: Pick<Project, 'metadata'> | undefined): string[];
24
+ /**
25
+ * Resolves referenced projects depth-first in reference order, then the root
26
+ * project. Later definitions intentionally replace earlier ones; the root
27
+ * project therefore always wins a collision with one of its references.
28
+ */
29
+ export declare function resolveProjectGlobalVariables(rootProject: Project, loadedProjects: Readonly<Record<ProjectId, Project>>): Map<string, ScalarOrArrayDataValue>;
@@ -1,4 +1,4 @@
1
- import type { ScalarOrArrayDataValue } from './DataValue.js';
1
+ import type { DataValue, ScalarOrArrayDataValue } from './DataValue.js';
2
2
  import type { GraphOutputs, Outputs } from './GraphProcessor.js';
3
3
  import type { ChartNode } from './NodeBase.js';
4
4
  import type { RivetStoredValue } from './StoredValueStore.js';
@@ -13,5 +13,11 @@ export type FrozenSetStoredValueEffect = {
13
13
  value: RivetStoredValue;
14
14
  };
15
15
  export type FrozenGraphBoundaryEffect = FrozenSetGlobalEffect | FrozenSetStoredValueEffect;
16
+ /**
17
+ * Graph Outputs with the same public ID retain the first non-excluded value.
18
+ * Normal execution, frozen replay, and control-flow exclusion all use this
19
+ * single boundary rule.
20
+ */
21
+ export declare function commitGraphOutputValue(graphOutputs: GraphOutputs, outputId: string, value: DataValue): void;
16
22
  export declare function ensureGraphCostOutput(graphOutputs: GraphOutputs, totalCost: number): void;
17
23
  export declare function applyFrozenGraphBoundaryEffects(graphOutputs: GraphOutputs, node: ChartNode, outputValues: Outputs): FrozenGraphBoundaryEffect | undefined;