@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
@@ -71,6 +71,10 @@ export * from './nodes/DataBusNode.js';
71
71
  export * from './DataBusTopology.js';
72
72
  import { startBackgroundBranchNode } from './nodes/StartBackgroundBranchNode.js';
73
73
  export * from './nodes/StartBackgroundBranchNode.js';
74
+ import { watchStreamingOutputNode } from './nodes/WatchStreamingOutputNode.js';
75
+ export * from './nodes/WatchStreamingOutputNode.js';
76
+ import { stopWatchingStreamingOutputNode } from './nodes/StopWatchingStreamingOutputNode.js';
77
+ export * from './nodes/StopWatchingStreamingOutputNode.js';
74
78
  import { popNode } from './nodes/PopNode.js';
75
79
  export * from './nodes/PopNode.js';
76
80
  import { setGlobalNode } from './nodes/SetGlobalNode.js';
@@ -243,6 +247,8 @@ export const registerBuiltInNodes = (registry) => {
243
247
  .register(passthroughNode)
244
248
  .register(dataBusNode)
245
249
  .register(startBackgroundBranchNode)
250
+ .register(watchStreamingOutputNode)
251
+ .register(stopWatchingStreamingOutputNode)
246
252
  .register(popNode)
247
253
  .register(setGlobalNode)
248
254
  .register(getGlobalNode)
@@ -1,17 +1,20 @@
1
1
  export function buildNodeProcessContext(options) {
2
- const { attachedData, activeOutputPortIds, base, createSubProcessor, execution, externalFunctions, getPluginConfig, isDirectRunTarget, markResultAsEditorCacheHit, node, nodeAbortController, onPartialOutputs, processId, requestUserInput, reportProgress, setGlobal, splitIndex, toolCallContinuation, toolCallTraceSource, waitEvent, } = options;
2
+ const { attachedData, activeOutputPortIds, acceptStreamingWatchStop, base, createSubProcessor, execution, externalFunctions, getPluginConfig, isDirectRunTarget, markResultAsEditorCacheHit, node, nodeAbortController, onGraphOutputPartial, onPartialOutputs, setFailureOutputs, processId, requestUserInput, reportProgress, setGlobal, splitIndex, toolCallContinuation, toolCallTraceSource, waitEvent, } = options;
3
3
  return {
4
4
  ...base,
5
5
  node,
6
6
  attachedData,
7
7
  activeOutputPortIds,
8
+ acceptStreamingWatchStop,
8
9
  isDirectRunTarget,
9
10
  markResultAsEditorCacheHit,
10
11
  waitEvent,
11
12
  waitForGlobal: (id, signal = nodeAbortController.signal) => base.waitForGlobal(id, signal),
12
13
  waitForStoredValue: (key, signal = nodeAbortController.signal) => base.waitForStoredValue(key, signal),
13
14
  externalFunctions: { ...externalFunctions },
15
+ onGraphOutputPartial,
14
16
  onPartialOutputs,
17
+ setFailureOutputs,
15
18
  signal: nodeAbortController.signal,
16
19
  processId,
17
20
  splitIndex,
@@ -1 +1,36 @@
1
- export {};
1
+ /**
2
+ * Loads referenced projects depth-first in declared order.
3
+ *
4
+ * The active root is already in memory, so it is visited before traversing
5
+ * references. This keeps legacy cycles compatible without asking a loader to
6
+ * resolve the active project again. The returned record intentionally omits
7
+ * that root; callers already own the authoritative root snapshot.
8
+ */
9
+ export async function loadProjectReferenceTree(rootProject, rootProjectPath, loader) {
10
+ const collected = Object.create(null);
11
+ const seenProjectIds = new Set([rootProject.metadata.id]);
12
+ const loadReference = async (reference) => {
13
+ if (seenProjectIds.has(reference.id))
14
+ return;
15
+ seenProjectIds.add(reference.id);
16
+ const project = await loader.loadProject(rootProjectPath, reference);
17
+ if (project.metadata.id !== reference.id) {
18
+ throw new Error(`Referenced project "${reference.id}" loaded a project with ID "${project.metadata.id}" instead.`);
19
+ }
20
+ // Project IDs are user-controlled strings. Define an own property so IDs
21
+ // such as __proto__ cannot mutate the lookup object's prototype.
22
+ Object.defineProperty(collected, project.metadata.id, {
23
+ configurable: true,
24
+ enumerable: true,
25
+ value: project,
26
+ writable: true,
27
+ });
28
+ for (const childReference of project.references ?? []) {
29
+ await loadReference(childReference);
30
+ }
31
+ };
32
+ for (const reference of rootProject.references ?? []) {
33
+ await loadReference(reference);
34
+ }
35
+ return collected;
36
+ }
@@ -17,7 +17,11 @@ function withReplayRecordedAt(data, replayRecordedAt) {
17
17
  }
18
18
  return { ...data, replayRecordedAt };
19
19
  }
20
- const REPLAY_TIMED_LIFECYCLE_EVENTS = new Set([
20
+ function getRecordedEventOccurrenceAt(event) {
21
+ const { occurredAt, ts } = event;
22
+ return typeof occurredAt === 'number' && Number.isFinite(occurredAt) && occurredAt >= 0 ? occurredAt : ts;
23
+ }
24
+ const REPLAY_TIMED_EVENTS = new Set([
21
25
  'start',
22
26
  'graphStart',
23
27
  'graphOutputsReady',
@@ -32,6 +36,13 @@ const REPLAY_TIMED_LIFECYCLE_EVENTS = new Set([
32
36
  'nodeError',
33
37
  'nodeExcluded',
34
38
  'nodeOutputsCleared',
39
+ 'streamingOutputWatchSummary',
40
+ // These records retain their own physical call timestamps, but the replay
41
+ // timestamp lets observers keep them on the same historical recording
42
+ // timeline without borrowing a provider timestamp as a node lifecycle time.
43
+ 'llmCallFinished',
44
+ 'llmProfileAttempt',
45
+ 'toolCallFinished',
35
46
  ]);
36
47
  export async function replayExecutionRecording(options) {
37
48
  const { emitter, erroredNodes, fallbackGraphId, initialReplayExecution, project, recorder, recordingPlaybackChatLatency, setContextValues, setGraphInputs, setGraphOutputs, setRunning, visitedNodes, waitUntilUnpaused, nodeResults, isAborted, } = options;
@@ -58,9 +69,7 @@ export async function replayExecutionRecording(options) {
58
69
  // playback error remains attached to that root instead of synthesizing a
59
70
  // second one.
60
71
  hasEmittedRunActivityExecution = true;
61
- const payload = REPLAY_TIMED_LIFECYCLE_EVENTS.has(event)
62
- ? withReplayRecordedAt(data, currentReplayRecordedAt)
63
- : data;
72
+ const payload = REPLAY_TIMED_EVENTS.has(event) ? withReplayRecordedAt(data, currentReplayRecordedAt) : data;
64
73
  emitDetached(emitter, event, payload);
65
74
  };
66
75
  const emitReplayTerminalEvent = (event, data) => {
@@ -192,18 +201,24 @@ export async function replayExecutionRecording(options) {
192
201
  };
193
202
  const getNodeRunKey = (execution, nodeId, processId) => `${execution.rootRunId}:${execution.graphRunId}:${nodeId}:${processId}`;
194
203
  const getRecordedDuration = (recordedDuration, execution, nodeId, processId, terminalTs) => {
195
- if (recordedDuration !== undefined) {
204
+ if (isValidRecordedDuration(recordedDuration)) {
196
205
  return recordedDuration;
197
206
  }
198
207
  const startedAt = nodeStartTimestamps.get(getNodeRunKey(execution, nodeId, processId));
199
- return startedAt === undefined ? undefined : Math.max(0, terminalTs - startedAt);
208
+ if (!isValidRecordedTimestamp(startedAt) || !isValidRecordedTimestamp(terminalTs) || terminalTs < startedAt) {
209
+ return undefined;
210
+ }
211
+ return terminalTs - startedAt;
200
212
  };
201
213
  for (const event of recorder.events) {
202
214
  if (isAborted()) {
203
215
  break;
204
216
  }
205
217
  await waitUntilUnpaused();
206
- currentReplayRecordedAt = event.ts;
218
+ // Watch history can defer selected evidence until the scheduler settles.
219
+ // Keep recording order on `ts`, but present and derive timing from when
220
+ // the original event actually occurred.
221
+ currentReplayRecordedAt = getRecordedEventOccurrenceAt(event);
207
222
  switch (event.type) {
208
223
  case 'start': {
209
224
  const { data } = event;
@@ -236,11 +251,13 @@ export async function replayExecutionRecording(options) {
236
251
  }
237
252
  case 'done': {
238
253
  emitFallbackRootTerminal('completed', { outputs: event.data.results });
239
- emitReplayTerminalEvent('done', event.data);
254
+ // Match a live root run: `done` remains inside the active lifecycle
255
+ // so a done listener cannot start work that replay cleanup would
256
+ // clobber. `finish` is emitted once below, after playback releases
257
+ // ownership, so its listener may start a new run.
258
+ await emitter.emit('done', withReplayRecordedAt(event.data, currentReplayRecordedAt));
240
259
  graphOutputs = event.data.results;
241
260
  setGraphOutputs(graphOutputs);
242
- // Keep ownership until playback drains, just like a live graph run.
243
- // A done listener must not start work that final cleanup could clobber.
244
261
  break;
245
262
  }
246
263
  case 'error': {
@@ -316,7 +333,7 @@ export async function replayExecutionRecording(options) {
316
333
  const { data } = event;
317
334
  const node = getNode(data.nodeId);
318
335
  const execution = getExecution(data.execution?.graphId ?? getGraphIdForNode(data.nodeId), data.execution);
319
- nodeStartTimestamps.set(getNodeRunKey(execution, data.nodeId, data.processId), event.ts);
336
+ nodeStartTimestamps.set(getNodeRunKey(execution, data.nodeId, data.processId), getRecordedEventOccurrenceAt(event));
320
337
  emitReplayExecutionEvent('nodeStart', {
321
338
  node,
322
339
  inputs: data.inputs,
@@ -340,7 +357,7 @@ export async function replayExecutionRecording(options) {
340
357
  processId: data.processId,
341
358
  ...(data.resultOrigin === undefined ? {} : { resultOrigin: data.resultOrigin }),
342
359
  execution,
343
- }, getRecordedDuration(data.durationMs, execution, data.nodeId, data.processId, event.ts), data.splitRunDurationMs));
360
+ }, getRecordedDuration(data.durationMs, execution, data.nodeId, data.processId, getRecordedEventOccurrenceAt(event)), data.splitRunDurationMs));
344
361
  nodeResults.set(data.nodeId, data.outputs);
345
362
  visitedNodes.add(data.nodeId);
346
363
  break;
@@ -353,9 +370,11 @@ export async function replayExecutionRecording(options) {
353
370
  node,
354
371
  error: data.error,
355
372
  processId: data.processId,
373
+ ...(data.outputs === undefined ? {} : { outputs: data.outputs }),
374
+ ...(data.splitOutputs === undefined ? {} : { splitOutputs: data.splitOutputs }),
356
375
  ...(data.resultOrigin === undefined ? {} : { resultOrigin: data.resultOrigin }),
357
376
  execution,
358
- }, getRecordedDuration(data.durationMs, execution, data.nodeId, data.processId, event.ts), data.splitRunDurationMs));
377
+ }, getRecordedDuration(data.durationMs, execution, data.nodeId, data.processId, getRecordedEventOccurrenceAt(event)), data.splitRunDurationMs));
359
378
  erroredNodes.set(data.nodeId, data.error);
360
379
  visitedNodes.add(data.nodeId);
361
380
  break;
@@ -388,6 +407,15 @@ export async function replayExecutionRecording(options) {
388
407
  });
389
408
  break;
390
409
  }
410
+ case 'streamingOutputWatchSummary': {
411
+ const { data } = event;
412
+ emitReplayExecutionEvent('streamingOutputWatchSummary', {
413
+ watchNode: getNode(data.watchNodeId),
414
+ summary: data.summary,
415
+ execution: getExecution(data.execution?.graphId ?? getGraphIdForNode(data.watchNodeId), data.execution),
416
+ });
417
+ break;
418
+ }
391
419
  case 'partialOutput': {
392
420
  const { data } = event;
393
421
  const node = getNode(data.nodeId);
@@ -465,7 +493,11 @@ export async function replayExecutionRecording(options) {
465
493
  break;
466
494
  }
467
495
  case 'finish': {
468
- emitDetached(emitter, 'finish', undefined);
496
+ // Current recordings deliberately exclude root `finish`: the
497
+ // recorder uses it only as its sealing signal. Older recordings can
498
+ // contain it, but replay must emit exactly one finish after it has
499
+ // released the lifecycle below, so defer both formats to that one
500
+ // common boundary.
469
501
  break;
470
502
  }
471
503
  default: {
@@ -496,6 +528,18 @@ export async function replayExecutionRecording(options) {
496
528
  }
497
529
  finally {
498
530
  setRunning(false);
531
+ // This must happen after setRunning(false), not merely as a detached
532
+ // emission from the recorded-event loop. A live root finish listener may
533
+ // start the next run; replay has the same contract. It is also the
534
+ // synthetic finish for current recordings, whose recorder omits finish
535
+ // from the replayable event log and uses it only to seal the recording.
536
+ emitDetached(emitter, 'finish', undefined);
499
537
  }
500
538
  return graphOutputs;
501
539
  }
540
+ function isValidRecordedTimestamp(value) {
541
+ return value != null && Number.isFinite(value) && value >= 0;
542
+ }
543
+ function isValidRecordedDuration(value) {
544
+ return value != null && Number.isFinite(value) && value >= 0;
545
+ }
@@ -31,16 +31,14 @@ export async function processSplitRunNode(node, processId, deps) {
31
31
  resultOrigin: 'executed',
32
32
  });
33
33
  const timingStart = deps.startNodeTiming?.();
34
- let splitRunDurationMs;
35
- let results = [];
34
+ const results = [];
36
35
  try {
37
36
  if (node.isSplitSequential) {
38
- results = await runSequential(node, inputValues, inputDefinitionsById, splittingAmount, processId, deps);
37
+ await runSequential(node, inputValues, inputDefinitionsById, splittingAmount, processId, deps, results);
39
38
  }
40
39
  else {
41
- results = await runParallel(node, inputValues, inputDefinitionsById, splittingAmount, processId, deps);
40
+ results.push(...(await runParallel(node, inputValues, inputDefinitionsById, splittingAmount, processId, deps)));
42
41
  }
43
- splitRunDurationMs = getSplitRunDurationMs(results);
44
42
  const errors = results.filter((r) => r.type === 'error').map((r) => r.error);
45
43
  if (errors.length === 1) {
46
44
  throw errors[0];
@@ -51,7 +49,7 @@ export async function processSplitRunNode(node, processId, deps) {
51
49
  }
52
50
  throw new AggregateError(errors);
53
51
  }
54
- const aggregateResults = aggregateOutputs(results);
52
+ const aggregateResults = aggregateOutputs(results.filter(isSplitOutputResult));
55
53
  deps.setNodeResults(node.id, aggregateResults);
56
54
  deps.markNodeVisited(node.id);
57
55
  await deps.emit('nodeFinish', withOptionalDuration({
@@ -59,14 +57,13 @@ export async function processSplitRunNode(node, processId, deps) {
59
57
  outputs: aggregateResults,
60
58
  processId,
61
59
  resultOrigin: getSplitRunResultOrigin(results),
62
- }, deps.finishNodeTiming?.(timingStart), splitRunDurationMs));
60
+ }, deps.finishNodeTiming?.(timingStart), getSplitRunDurationMs(results)));
63
61
  }
64
62
  catch (error) {
65
- await deps.nodeErrored(node, error, processId, deps.finishNodeTiming?.(timingStart), splitRunDurationMs, getSplitRunResultOrigin(results));
63
+ await deps.nodeErrored(node, error, processId, deps.finishNodeTiming?.(timingStart), getSplitRunDurationMs(results), getSplitRunResultOrigin(results), getSplitTerminalOutputs(results));
66
64
  }
67
65
  }
68
- async function runSequential(node, inputValues, inputDefinitionsById, splittingAmount, processId, deps) {
69
- const results = [];
66
+ async function runSequential(node, inputValues, inputDefinitionsById, splittingAmount, processId, deps, results) {
70
67
  for (let i = 0; i < splittingAmount; i++) {
71
68
  if (deps.isAborted()) {
72
69
  throw deps.getAbortError();
@@ -87,29 +84,33 @@ async function runSequential(node, inputValues, inputDefinitionsById, splittingA
87
84
  resultOrigin = 'editor-cache';
88
85
  });
89
86
  deps.accumulateCost(output);
90
- results.push({ type: 'output', output, resultOrigin, durationMs: deps.finishNodeTiming?.(splitTimingStart) });
87
+ results.push({ type: 'output', index: i, output, resultOrigin, durationMs: deps.finishNodeTiming?.(splitTimingStart) });
91
88
  }
92
89
  catch (error) {
93
90
  results.push({
94
91
  type: 'error',
95
92
  error: getError(error),
93
+ index: i,
96
94
  resultOrigin,
97
95
  durationMs: deps.finishNodeTiming?.(splitTimingStart),
96
+ failureOutputs: deps.takeFailureOutputs(processId, i),
98
97
  });
99
98
  }
100
99
  }
101
- return results;
102
100
  }
103
101
  async function runParallel(node, inputValues, inputDefinitionsById, splittingAmount, processId, deps) {
104
102
  const queue = new PQueue({ concurrency: getParallelSplitRunConcurrency(node, deps.splitRunConcurrency) });
105
103
  return Promise.all(range(0, splittingAmount).map(async (i) => {
106
104
  const result = await queue.add(async () => {
107
- const splitTimingStart = deps.startNodeTiming?.();
108
105
  let resultOrigin = 'executed';
106
+ let splitTimingStart;
109
107
  try {
110
108
  if (deps.isAborted()) {
111
109
  throw deps.getAbortError();
112
110
  }
111
+ // Queued items that encounter an already-aborted graph never ran,
112
+ // so they must not receive a synthetic split duration.
113
+ splitTimingStart = deps.startNodeTiming?.();
113
114
  const inputs = splitInputsAtIndex(inputValues, inputDefinitionsById, i);
114
115
  const output = await deps.processNodeWithInputData(node, inputs, i, processId, (n, partialOutputs, index) => {
115
116
  deps.emit('partialOutput', {
@@ -125,6 +126,7 @@ async function runParallel(node, inputValues, inputDefinitionsById, splittingAmo
125
126
  deps.accumulateCost(output);
126
127
  return {
127
128
  type: 'output',
129
+ index: i,
128
130
  output,
129
131
  resultOrigin,
130
132
  durationMs: deps.finishNodeTiming?.(splitTimingStart),
@@ -134,8 +136,10 @@ async function runParallel(node, inputValues, inputDefinitionsById, splittingAmo
134
136
  return {
135
137
  type: 'error',
136
138
  error: getError(error),
139
+ index: i,
137
140
  resultOrigin,
138
- durationMs: deps.finishNodeTiming?.(splitTimingStart),
141
+ durationMs: splitTimingStart === undefined ? undefined : deps.finishNodeTiming?.(splitTimingStart),
142
+ failureOutputs: deps.takeFailureOutputs(processId, i),
139
143
  };
140
144
  }
141
145
  });
@@ -150,6 +154,20 @@ function getSplitRunResultOrigin(results) {
150
154
  ? 'editor-cache'
151
155
  : 'executed';
152
156
  }
157
+ /**
158
+ * A failed split node has no graph-semantic aggregate result, but every item
159
+ * that actually ran still has useful inspection evidence. Keep successful
160
+ * item outputs as well as failed-item checkpoints so a terminal nodeError
161
+ * cannot erase siblings that happened to finish before another item failed.
162
+ */
163
+ function getSplitTerminalOutputs(results) {
164
+ const outputs = Object.fromEntries(results.flatMap((result) => result.type === 'output'
165
+ ? [[result.index, result.output]]
166
+ : result.failureOutputs !== undefined
167
+ ? [[result.index, result.failureOutputs]]
168
+ : []));
169
+ return Object.keys(outputs).length === 0 ? undefined : outputs;
170
+ }
153
171
  function getParallelSplitRunConcurrency(node, defaultConcurrency) {
154
172
  const value = node.splitRunConcurrency;
155
173
  return typeof value === 'number' && Number.isFinite(value) && value >= 2 ? Math.floor(value) : defaultConcurrency;
@@ -173,11 +191,14 @@ function aggregateOutputs(results) {
173
191
  return acc;
174
192
  }, {});
175
193
  }
194
+ function isSplitOutputResult(result) {
195
+ return result.type === 'output';
196
+ }
176
197
  function getSplitRunDurationMs(results) {
177
198
  const durations = {};
178
- for (const [index, result] of results.entries()) {
199
+ for (const result of results) {
179
200
  if (result.durationMs !== undefined) {
180
- durations[index] = result.durationMs;
201
+ durations[result.index] = result.durationMs;
181
202
  }
182
203
  }
183
204
  return Object.keys(durations).length > 0 ? durations : undefined;
@@ -0,0 +1,262 @@
1
+ /** Defaults shared by the persisted node definition and the runtime boundary. */
2
+ export const streamingOutputWatchDefaults = {
3
+ intervalMs: 1_000,
4
+ maxParallelRuns: 4,
5
+ maxQueuedUpdates: 32,
6
+ // Preserve the original fail-closed behavior unless a project explicitly
7
+ // opts into skipping updates that cannot be scheduled.
8
+ queueOverflowBehavior: 'fail',
9
+ };
10
+ /**
11
+ * Hard safety bounds for persisted settings. The node editor exposes the same
12
+ * limits, but the runtime must also defend against manually edited project data.
13
+ */
14
+ export const streamingOutputWatchLimits = {
15
+ intervalMs: 3_600_000,
16
+ maxParallelRuns: 32,
17
+ maxQueuedUpdates: 1_024,
18
+ };
19
+ function normalizePositiveInteger(value, fallback, maximum) {
20
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
21
+ return fallback;
22
+ }
23
+ return Math.min(maximum, Math.max(1, Math.floor(value)));
24
+ }
25
+ /**
26
+ * Owns bounded, cancellable delivery of a streaming node's immutable output
27
+ * snapshots. It deliberately knows nothing about graph topology: the owning
28
+ * GraphProcessor decides how a snapshot runs and whether accepting Stop is
29
+ * required to complete the watch.
30
+ */
31
+ export class StreamingOutputWatch {
32
+ #options;
33
+ #run;
34
+ #onFailure;
35
+ #requiresAcceptedStop;
36
+ #queue = [];
37
+ #activeRuns = new Set();
38
+ #timer;
39
+ #latestIntervalSnapshot;
40
+ #producerFinished = false;
41
+ #finalSnapshotSettled = false;
42
+ #stopped = false;
43
+ #failure;
44
+ #failureKind;
45
+ #receivedUpdates = 0;
46
+ #coalescedUpdates = 0;
47
+ #droppedUpdates = 0;
48
+ #maximumQueuedUpdates = 0;
49
+ constructor(options, run, onFailure, { requiresAcceptedStop = true } = {}) {
50
+ this.#options = {
51
+ triggerMode: options.triggerMode === 'interval' ? 'interval' : 'every-update',
52
+ executionMode: options.executionMode === 'parallel' ? 'parallel' : 'sequential',
53
+ intervalMs: normalizePositiveInteger(options.intervalMs, streamingOutputWatchDefaults.intervalMs, streamingOutputWatchLimits.intervalMs),
54
+ maxParallelRuns: normalizePositiveInteger(options.maxParallelRuns, streamingOutputWatchDefaults.maxParallelRuns, streamingOutputWatchLimits.maxParallelRuns),
55
+ maxQueuedUpdates: normalizePositiveInteger(options.maxQueuedUpdates, streamingOutputWatchDefaults.maxQueuedUpdates, streamingOutputWatchLimits.maxQueuedUpdates),
56
+ queueOverflowBehavior: options.queueOverflowBehavior === 'drop' ? 'drop' : streamingOutputWatchDefaults.queueOverflowBehavior,
57
+ };
58
+ this.#run = run;
59
+ this.#onFailure = onFailure;
60
+ this.#requiresAcceptedStop = requiresAcceptedStop;
61
+ }
62
+ get hasPending() {
63
+ // Stop prevents new delivery, but accepted and failing invocations still
64
+ // belong to the root lifecycle until they settle. Hiding those active runs
65
+ // here lets finalization report a later missing-Stop error instead of the
66
+ // actual child failure.
67
+ return this.#activeRuns.size > 0 || (!this.#stopped && (this.#queue.length > 0 || this.#timer != null));
68
+ }
69
+ get isAwaitingProducer() {
70
+ return (!this.#stopped &&
71
+ !this.#producerFinished &&
72
+ this.#timer != null &&
73
+ this.#queue.length === 0 &&
74
+ this.#activeRuns.size === 0);
75
+ }
76
+ get stopped() {
77
+ return this.#stopped;
78
+ }
79
+ /** True only after this Watch can no longer receive or run a snapshot. */
80
+ get isSettled() {
81
+ return !this.hasPending && (this.#stopped || this.#failure != null || this.#producerFinished);
82
+ }
83
+ get runtimeSummary() {
84
+ return {
85
+ receivedUpdates: this.#receivedUpdates,
86
+ coalescedUpdates: this.#coalescedUpdates,
87
+ droppedUpdates: this.#droppedUpdates,
88
+ maximumQueuedUpdates: this.#maximumQueuedUpdates,
89
+ ...(this.#failureKind === undefined ? {} : { failureKind: this.#failureKind }),
90
+ };
91
+ }
92
+ /**
93
+ * A Stop boundary can enqueue ordinary parent-graph work when its node
94
+ * completes. Until it settles, its result is not safe to expose
95
+ * through the foreground-output boundary.
96
+ */
97
+ get canAffectForegroundOutputs() {
98
+ return this.#requiresAcceptedStop;
99
+ }
100
+ publish(snapshot) {
101
+ // A producer's terminal snapshot closes its partial stream. Ignore a
102
+ // misbehaving late callback rather than scheduling work after a final
103
+ // result has already been offered to Stop and ordinary downstream nodes.
104
+ if (this.#stopped || this.#failure || this.#producerFinished) {
105
+ return;
106
+ }
107
+ this.#receivedUpdates += 1;
108
+ if (this.#options.triggerMode === 'interval' && !snapshot.isFinal) {
109
+ if (this.#latestIntervalSnapshot) {
110
+ this.#coalescedUpdates += 1;
111
+ }
112
+ this.#latestIntervalSnapshot = snapshot;
113
+ this.#scheduleInterval();
114
+ return;
115
+ }
116
+ this.#enqueue(snapshot);
117
+ }
118
+ finish(finalSnapshot) {
119
+ if (this.#stopped || this.#failure || this.#producerFinished) {
120
+ return;
121
+ }
122
+ this.#receivedUpdates += 1;
123
+ this.#producerFinished = true;
124
+ if (this.#timer != null) {
125
+ clearTimeout(this.#timer);
126
+ this.#timer = undefined;
127
+ }
128
+ // The final output supersedes a partial snapshot that was still waiting
129
+ // for its interval. Account for that intentionally omitted update just as
130
+ // we account for a newer partial replacing one before the timer fires.
131
+ if (this.#latestIntervalSnapshot) {
132
+ this.#coalescedUpdates += 1;
133
+ }
134
+ this.#latestIntervalSnapshot = undefined;
135
+ this.#enqueue(finalSnapshot);
136
+ }
137
+ /** Preserve the winning invocation's siblings; later owner cancellation cancels all. */
138
+ stop(acceptedUpdateIndex) {
139
+ this.#stopped = true;
140
+ this.#queue.length = 0;
141
+ this.#latestIntervalSnapshot = undefined;
142
+ if (this.#timer != null) {
143
+ clearTimeout(this.#timer);
144
+ this.#timer = undefined;
145
+ }
146
+ for (const activeRun of this.#activeRuns) {
147
+ if (activeRun.updateIndex !== acceptedUpdateIndex)
148
+ activeRun.cancel();
149
+ }
150
+ }
151
+ async drain() {
152
+ while (this.#queue.length > 0 || this.#activeRuns.size > 0 || this.#timer != null) {
153
+ if (this.#timer != null && this.#activeRuns.size === 0 && this.#queue.length === 0) {
154
+ // A producer that is still running owns the next interval. Do not turn
155
+ // an ordinary wait between updates into a busy loop.
156
+ return;
157
+ }
158
+ await Promise.all([...this.#activeRuns].map((run) => run.promise));
159
+ }
160
+ if (this.#producerFinished && this.#finalSnapshotSettled && !this.#stopped && this.#requiresAcceptedStop) {
161
+ this.#fail(new Error('The watched streaming output completed before Stop Watching Streaming Output accepted a value.'), 'missing-stop');
162
+ }
163
+ }
164
+ #scheduleInterval() {
165
+ if (this.#timer != null) {
166
+ return;
167
+ }
168
+ this.#timer = setTimeout(() => {
169
+ this.#timer = undefined;
170
+ if (this.#stopped || this.#failure) {
171
+ return;
172
+ }
173
+ const snapshot = this.#latestIntervalSnapshot;
174
+ this.#latestIntervalSnapshot = undefined;
175
+ if (snapshot) {
176
+ this.#enqueue(snapshot);
177
+ }
178
+ }, this.#options.intervalMs);
179
+ }
180
+ #enqueue(snapshot) {
181
+ if (this.#queue.length >= this.#options.maxQueuedUpdates) {
182
+ if (this.#options.queueOverflowBehavior === 'drop') {
183
+ if (snapshot.isFinal) {
184
+ // A final snapshot is the only chance for a Stop branch to accept a
185
+ // value after its producer has completed. Keep that contract without
186
+ // relaxing the configured queue bound: discard the stalest waiting
187
+ // partial and retain the final snapshot instead.
188
+ this.#queue.shift();
189
+ this.#droppedUpdates += 1;
190
+ this.#queue.push(snapshot);
191
+ this.#maximumQueuedUpdates = Math.max(this.#maximumQueuedUpdates, this.#queue.length);
192
+ this.#pump();
193
+ }
194
+ else {
195
+ this.#droppedUpdates += 1;
196
+ }
197
+ return;
198
+ }
199
+ this.#fail(new Error(`Watch Streaming Output exceeded its ${this.#options.maxQueuedUpdates}-update queue limit. ` +
200
+ 'Increase the limit, use an interval trigger, or stop the watch sooner.'), 'queue-overflow');
201
+ return;
202
+ }
203
+ this.#queue.push(snapshot);
204
+ this.#maximumQueuedUpdates = Math.max(this.#maximumQueuedUpdates, this.#queue.length);
205
+ this.#pump();
206
+ }
207
+ #pump() {
208
+ const concurrency = this.#options.executionMode === 'parallel' ? this.#options.maxParallelRuns : 1;
209
+ while (!this.#stopped && !this.#failure && this.#queue.length > 0 && this.#activeRuns.size < concurrency) {
210
+ const snapshot = this.#queue.shift();
211
+ let cancel = () => undefined;
212
+ let cancelled = false;
213
+ const activeRun = {
214
+ isFinal: snapshot.isFinal,
215
+ updateIndex: snapshot.updateIndex,
216
+ cancel: () => {
217
+ if (cancelled)
218
+ return;
219
+ cancelled = true;
220
+ cancel();
221
+ },
222
+ promise: Promise.resolve(),
223
+ };
224
+ // Start through a promise boundary so a malformed branch that throws
225
+ // synchronously is still tracked, drained, and reported like an async
226
+ // branch failure.
227
+ activeRun.promise = Promise.resolve()
228
+ .then(() => {
229
+ // stop() may run after this slot is reserved but before its microtask.
230
+ if (this.#stopped)
231
+ return;
232
+ return this.#run(snapshot, (nextCancel) => {
233
+ cancel = nextCancel;
234
+ if (cancelled)
235
+ cancel();
236
+ });
237
+ })
238
+ .catch((error) => {
239
+ if (!this.#stopped) {
240
+ this.#fail(error instanceof Error ? error : new Error(String(error)), 'branch-failure');
241
+ }
242
+ })
243
+ .finally(() => {
244
+ if (activeRun.isFinal) {
245
+ this.#finalSnapshotSettled = true;
246
+ }
247
+ this.#activeRuns.delete(activeRun);
248
+ this.#pump();
249
+ });
250
+ this.#activeRuns.add(activeRun);
251
+ }
252
+ }
253
+ #fail(error, failureKind) {
254
+ if (this.#failure) {
255
+ return;
256
+ }
257
+ this.#failure = error;
258
+ this.#failureKind = failureKind;
259
+ this.#onFailure(error);
260
+ this.stop();
261
+ }
262
+ }