@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,5 +1,5 @@
1
1
  import {} from './DataValue.js';
2
- import {} from './NodeBase.js';
2
+ import { IF_PORT, } from './NodeBase.js';
3
3
  import PQueue from '../utils/pQueueCompat.js';
4
4
  import { getError } from '../utils/errors.js';
5
5
  import Emittery from 'emittery';
@@ -10,7 +10,8 @@ import { getPluginConfig } from '../utils/index.js';
10
10
  import { isGraphExecutionPlan, preprocessGraphState, toReusableGraphExecutionPlan, } from './GraphPreprocessor.js';
11
11
  import { getGraphBoundary } from './GraphBoundaryCache.js';
12
12
  import { createGraphOutputSelection } from './GraphOutputSelection.js';
13
- import { applyFrozenGraphBoundaryEffects, ensureGraphCostOutput } from './GraphBoundaryEffects.js';
13
+ import { applyFrozenGraphBoundaryEffects, commitGraphOutputValue, ensureGraphCostOutput, } from './GraphBoundaryEffects.js';
14
+ import { coerceGraphOutputValue } from './nodes/GraphOutputNode.js';
14
15
  import { replayExecutionRecording } from './RecordingPlayer.js';
15
16
  import { didLoopControllerBreak, LOOP_NOT_BROKEN_SENTINEL } from './loopControllerBreak.js';
16
17
  import { buildNodeProcessContext } from './ProcessContextBuilder.js';
@@ -29,14 +30,29 @@ import { buildDelegatedToolCallOutputs, isDelegatedToolCallRecord } from './node
29
30
  import { ToolCallContinuationCoordinator, } from './ToolCallContinuationCoordinator.js';
30
31
  import { createToolCallContinuationBranchPlanner, } from './ToolCallContinuationBranchPlanner.js';
31
32
  import { ManagedAsyncBranches } from './ManagedAsyncBranches.js';
33
+ import { StreamingOutputWatch, } from './StreamingOutputWatch.js';
34
+ import { StreamingOutputWatchHistory, } from './StreamingOutputWatchHistory.js';
35
+ import { cloneExecutionOutputs } from './ExecutionOutputClone.js';
32
36
  import { KnowledgeStoreController } from '../integrations/KnowledgeStoreProvider.js';
33
37
  import { isDataBusTopologyNode } from './DataBusTopology.js';
34
38
  import { resolveNodePrefabInstance } from './NodePrefabResolver.js';
35
39
  import { ConnectedToolContinuationHost, } from './ConnectedToolContinuationHost.js';
40
+ import { resolveProjectGlobalVariables } from './GlobalVariables.js';
41
+ import { loadProjectReferenceTree } from './ProjectReferenceLoader.js';
36
42
  // eslint-disable-next-line import/no-cycle -- There has to be a cycle because CodeRunner needs to import the entirety of Rivet
37
43
  import { IsomorphicCodeRunner } from '../integrations/CodeRunner.js';
38
44
  const graphProcessorGraphOverride = Symbol('graphProcessorGraphOverride');
39
45
  const consumedAsyncBranchTriggerOverride = Symbol('consumedAsyncBranchTriggerOverride');
46
+ const consumedStreamingWatchNodeOverride = Symbol('consumedStreamingWatchNodeOverride');
47
+ /**
48
+ * These nodes expose a child graph's named Graph Output ports verbatim. Other
49
+ * nodes that happen to run a graph (for example Call Graph or Loop Until)
50
+ * aggregate or transform child outputs, so streaming through them would not
51
+ * have the same terminal semantics.
52
+ */
53
+ function isNamedGraphBoundaryCaller(node) {
54
+ return node.type === 'subGraph' || node.type === 'referencedGraphAlias';
55
+ }
40
56
  function createGraphOutputsOverlay(parent) {
41
57
  const writes = {};
42
58
  const view = new Proxy(writes, {
@@ -75,7 +91,7 @@ export function createFrozenNodeOutputResolver(outputsByGraph) {
75
91
  return undefined;
76
92
  }
77
93
  const countersByGraphRunAndNode = new Map();
78
- return ({ execution, graphId, node }) => {
94
+ const resolver = ({ execution, graphId, node }) => {
79
95
  const outputInstances = outputsByGraph?.[graphId]?.[node.id];
80
96
  if (!outputInstances?.length) {
81
97
  return undefined;
@@ -85,6 +101,8 @@ export function createFrozenNodeOutputResolver(outputsByGraph) {
85
101
  countersByGraphRunAndNode.set(counterKey, currentIndex + 1);
86
102
  return cloneFrozenNodeOutputs(outputInstances[Math.min(currentIndex, outputInstances.length - 1)]);
87
103
  };
104
+ resolver.hasFrozenNodeOutput = ({ graphId, node }) => (outputsByGraph?.[graphId]?.[node.id]?.length ?? 0) > 0;
105
+ return resolver;
88
106
  }
89
107
  const DEFAULT_NODE_CONCURRENCY = 8;
90
108
  export const DEFAULT_SPLIT_RUN_CONCURRENCY = 4;
@@ -94,6 +112,8 @@ const FAST_ACYCLIC_UNSUPPORTED_NODE_TYPES = new Set([
94
112
  'loopUntil',
95
113
  'raceInputs',
96
114
  'startBackgroundBranch',
115
+ 'watchStreamingOutput',
116
+ 'stopWatchingStreamingOutput',
97
117
  'userInput',
98
118
  'waitForEvent',
99
119
  ]);
@@ -157,6 +177,13 @@ export class GraphProcessor {
157
177
  #effectiveConnectionsForRun;
158
178
  #asyncBranchPlansByTriggerNodeId = new Map();
159
179
  #consumedAsyncBranchTriggerNodeId;
180
+ #streamingWatchPlansBySourceNodeId = new Map();
181
+ #streamingWatchPlansByWatchNodeId = new Map();
182
+ #streamingOutputWatches = new Map();
183
+ #graphOutputPartialBindingsBySourceNodeId = new Map();
184
+ #graphOutputPartialListener;
185
+ #consumedStreamingWatchNodeId;
186
+ #streamingWatchInvocation;
160
187
  #registry;
161
188
  #concurrency;
162
189
  #executionPlanCacheMode;
@@ -186,6 +213,7 @@ export class GraphProcessor {
186
213
  warnOnInvalidGraph = false;
187
214
  // Per-process state
188
215
  #erroredNodes = undefined; // Values are strings in recordings
216
+ #failureOutputsByProcessId = undefined;
189
217
  #remainingNodes = undefined;
190
218
  #visitedNodes = undefined;
191
219
  #currentlyProcessing = undefined;
@@ -201,6 +229,10 @@ export class GraphProcessor {
201
229
  #subprocessors = undefined;
202
230
  #contextValues = undefined;
203
231
  #globals = undefined;
232
+ /** IDs assigned by the previous root invocation, retained only to reset project globals on reuse. */
233
+ #projectGlobalVariableIdsAssignedByPreviousRootRun = new Set();
234
+ /** Snapshot for lifecycle recording, populated only while a root run starts. */
235
+ #initialProjectGlobalVariablesForRun = new Map();
204
236
  #storedValueController = undefined;
205
237
  #knowledgeStoreController = undefined;
206
238
  #attachedNodeData = undefined;
@@ -217,6 +249,7 @@ export class GraphProcessor {
217
249
  #graphOutputSelection;
218
250
  #managedAsyncBranches;
219
251
  #managedAsyncBranchFailures = [];
252
+ #streamingWatchFailures = [];
220
253
  #runCompletionPromise;
221
254
  #nodesNotInCycle = undefined;
222
255
  #executionGraphNodes = undefined;
@@ -296,6 +329,7 @@ export class GraphProcessor {
296
329
  this.#runtimeProfiler = options?.runtimeProfiler;
297
330
  this.#captureNodeTimings = options?.captureNodeTimings ?? false;
298
331
  this.#consumedAsyncBranchTriggerNodeId = options?.[consumedAsyncBranchTriggerOverride];
332
+ this.#consumedStreamingWatchNodeId = options?.[consumedStreamingWatchNodeOverride];
299
333
  this.#emitter.bindMethods(this, ['on', 'off', 'once', 'onAny', 'offAny']);
300
334
  this.setExternalFunction('echo', async (value) => ({ type: 'any', value }));
301
335
  this.setExternalFunction(RIVET_WEB_APP_STATUS_FUNCTION_NAME, rivetWebAppStatusExternalFunction);
@@ -473,6 +507,7 @@ export class GraphProcessor {
473
507
  const abortReason = createGraphAbortReason(successful, error);
474
508
  this.#abortController.abort(abortReason);
475
509
  this.#abortActiveNodeControllers(abortReason);
510
+ this.#cancelStreamingOutputWatches();
476
511
  if (!this.#suppressGraphLifecycleEvents) {
477
512
  emitDetached(this.#emitter, 'graphAbort', this.#withExecution({ successful, error, graph: this.#graph }));
478
513
  if (!this.#isSubProcessor) {
@@ -483,6 +518,7 @@ export class GraphProcessor {
483
518
  if (!this.#isSubProcessor) {
484
519
  await this.#managedAsyncBranches?.drain();
485
520
  }
521
+ await this.#drainStreamingOutputWatches();
486
522
  }
487
523
  pause() {
488
524
  if (this.#lifecycle.pause()) {
@@ -544,6 +580,7 @@ export class GraphProcessor {
544
580
  throw new Error(`Invalid data value for node ${nodeId}, must be a DataValue`);
545
581
  }
546
582
  }
583
+ this.#assertStreamingOutputWatchPreloadCanBeAdded(nodeId);
547
584
  this.#preloadedNodeResults.set(nodeId, data);
548
585
  this.#hasPreloadedData = true;
549
586
  // Preserve the historical ability to preload an idle processor as well as
@@ -642,6 +679,7 @@ export class GraphProcessor {
642
679
  this.#visitedNodes = new Set(this.#preloadedNodeResults.keys());
643
680
  this.#hasPreloadedData = this.#preloadedNodeResults.size > 0;
644
681
  this.#erroredNodes = new Map();
682
+ this.#failureOutputsByProcessId = new Map();
645
683
  this.#currentlyProcessing = new Set();
646
684
  // A processor may be constructed with a reusable execution plan. In that
647
685
  // case preprocessing happened before this run, so retain the compiled
@@ -657,6 +695,10 @@ export class GraphProcessor {
657
695
  this.#continuationCompletionOwnerByNodeId = new Map();
658
696
  this.#effectiveConnectionsForRun = undefined;
659
697
  this.#asyncBranchPlansByTriggerNodeId = new Map();
698
+ this.#streamingWatchPlansBySourceNodeId = new Map();
699
+ this.#streamingWatchPlansByWatchNodeId = new Map();
700
+ this.#streamingOutputWatches = new Map();
701
+ this.#graphOutputPartialBindingsBySourceNodeId = new Map();
660
702
  this.#loopControllersSeen = new Set();
661
703
  this.#subprocessors = new Set();
662
704
  this.#attachedNodeData = this.#sharedRunStateOverride?.attachedNodeData ?? new Map();
@@ -673,6 +715,7 @@ export class GraphProcessor {
673
715
  this.#managedAsyncBranches = new ManagedAsyncBranches();
674
716
  this.#managedAsyncBranchFailures = [];
675
717
  }
718
+ this.#streamingWatchFailures = [];
676
719
  this.#abortController = this.#newAbortController();
677
720
  this.#successfulAbortTerminalProcessIds = new Set();
678
721
  this.#totalCost = 0;
@@ -699,6 +742,7 @@ export class GraphProcessor {
699
742
  throw new Error('Cannot process graph while already processing');
700
743
  }
701
744
  const requestedGraphOutputIds = options.requestedGraphOutputIds?.slice();
745
+ this.#graphOutputPartialListener = options.onGraphOutputPartial;
702
746
  let resolveOutputsReady;
703
747
  let rejectOutputsReady;
704
748
  const outputsReadyPromise = options.returnWhenGraphOutputsReady === true
@@ -713,6 +757,7 @@ export class GraphProcessor {
713
757
  try {
714
758
  this.#profileRuntimeSync('initializeGraphRun', () => this.#initializeGraphRun(context, inputs, contextValues));
715
759
  await this.#profileRuntimeAsync('loadProjectReferences', () => this.#loadProjectReferences());
760
+ this.#profileRuntimeSync('initializeProjectGlobalVariables', () => this.#initializeProjectGlobalVariablesForRootRun());
716
761
  this.#profileRuntimeSync('prepareNodeProcessContextBase', () => this.#prepareNodeProcessContextBase());
717
762
  const shouldUseSeededExecutionPlan = this.#seededExecutionPlanForNextRun() != null;
718
763
  this.#useSeededExecutionPlanOnNextRun = false;
@@ -733,6 +778,8 @@ export class GraphProcessor {
733
778
  }
734
779
  }
735
780
  this.#prepareAsyncBranchTopology();
781
+ this.#prepareStreamingWatchTopology();
782
+ this.#prepareGraphOutputPartialTopology();
736
783
  }
737
784
  catch (error) {
738
785
  const normalizedError = getError(error);
@@ -740,6 +787,7 @@ export class GraphProcessor {
740
787
  throw normalizedError;
741
788
  }
742
789
  await this.#profileRuntimeAsync('emitGraphStart', () => this.#emitGraphStart());
790
+ await this.#profileRuntimeAsync('emitInitialProjectGlobalVariables', () => this.#emitInitialProjectGlobalVariables());
743
791
  await this.#profileRuntimeAsync('emitPreloadedNodeResults', () => this.#emitPreloadedNodeResults());
744
792
  await this.#profileRuntimeAsync('waitUntilUnpaused', () => this.#waitUntilUnpaused());
745
793
  if (this.#canUseFastAcyclicScheduler()) {
@@ -750,7 +798,8 @@ export class GraphProcessor {
750
798
  }
751
799
  if (options.returnWhenGraphOutputsReady === true &&
752
800
  !this.#isSubProcessor &&
753
- this.#managedAsyncBranches.hasPending) {
801
+ !this.#hasUnresolvedForegroundOutputStreamingWatch() &&
802
+ (this.#managedAsyncBranches.hasPending || this.#hasPendingStreamingOutputWatches())) {
754
803
  await this.#profileRuntimeAsync('throwIfGraphErrored', () => this.#throwIfGraphErrored(false));
755
804
  // Publish a snapshot instead of the live root output object. In particular,
756
805
  // the provisional cost must not occupy the root cost port before managed
@@ -761,16 +810,13 @@ export class GraphProcessor {
761
810
  outputsWerePublishedEarly = true;
762
811
  resolveOutputsReady?.(outputsReady);
763
812
  }
764
- if (!this.#isSubProcessor) {
765
- await this.#profileRuntimeAsync('drainManagedAsyncBranches', () => this.#managedAsyncBranches.drain());
766
- }
813
+ await this.#drainSchedulerBoundaries();
767
814
  await this.#profileRuntimeAsync('throwIfGraphErrored', () => this.#throwIfGraphErrored());
768
815
  return await this.#profileRuntimeAsync('finalizeGraphRun', () => this.#finalizeGraphRun());
769
816
  }
770
817
  finally {
771
- if (!this.#isSubProcessor) {
772
- await this.#managedAsyncBranches?.drain();
773
- }
818
+ await this.#drainSchedulerBoundaries();
819
+ this.#graphOutputPartialListener = undefined;
774
820
  this.#lifecycle.complete();
775
821
  this.#cleanupTokenizerErrorListener();
776
822
  await this.#profileRuntimeAsync('emitFinish', () => this.#emitFinishIfNeeded());
@@ -811,6 +857,22 @@ export class GraphProcessor {
811
857
  this.#unsubscribeTokenizerError =
812
858
  typeof unsubscribeTokenizerError === 'function' ? unsubscribeTokenizerError : undefined;
813
859
  }
860
+ #initializeProjectGlobalVariablesForRootRun() {
861
+ this.#initialProjectGlobalVariablesForRun = new Map();
862
+ if (this.#isSubProcessor)
863
+ return;
864
+ // Resolve before touching the shared map. An invalid reference or definition
865
+ // must fail startup without leaving a partial new set of authored globals.
866
+ const resolved = resolveProjectGlobalVariables(this.#project, this.#loadedProjects);
867
+ for (const id of this.#projectGlobalVariableIdsAssignedByPreviousRootRun) {
868
+ this.#globals.delete(id);
869
+ }
870
+ for (const [id, value] of resolved) {
871
+ this.#globals.set(id, value);
872
+ }
873
+ this.#projectGlobalVariableIdsAssignedByPreviousRootRun = new Set(resolved.keys());
874
+ this.#initialProjectGlobalVariablesForRun = resolved;
875
+ }
814
876
  #initializeExecutionIdentity() {
815
877
  if (this.#executionIdentityOverride) {
816
878
  this.#rootRunId = this.#executionIdentityOverride.rootRunId;
@@ -966,6 +1028,13 @@ export class GraphProcessor {
966
1028
  }
967
1029
  await this.#emitter.emit('graphStart', this.#withExecution({ graph: this.#graph, inputs: this.#graphInputs }));
968
1030
  }
1031
+ async #emitInitialProjectGlobalVariables() {
1032
+ if (this.#isSubProcessor || this.#suppressGraphLifecycleEvents)
1033
+ return;
1034
+ for (const [id, value] of this.#initialProjectGlobalVariablesForRun) {
1035
+ await this.#emitter.emit('globalSet', this.#withExecution({ id, value, processId: 'initial-project-global-variable' }));
1036
+ }
1037
+ }
969
1038
  async #emitPreloadedNodeResults() {
970
1039
  if (!this.#hasPreloadedData) {
971
1040
  return;
@@ -977,6 +1046,10 @@ export class GraphProcessor {
977
1046
  if (this.#suppressedPreloadedNodeIds.has(node.id)) {
978
1047
  continue;
979
1048
  }
1049
+ const outputs = this.#nodeResults.get(node.id);
1050
+ // A preloaded producer is complete evidence, not a reconstructed token
1051
+ // stream. Watch receives it once as the producer's final snapshot.
1052
+ this.#assertStreamingOutputWatchFinalOutputs(node, outputs);
980
1053
  this.#emitTraceEvent(`Node ${node.title} has preloaded data`);
981
1054
  await this.#emitter.emit('nodeStart', this.#withExecution({
982
1055
  node,
@@ -986,10 +1059,11 @@ export class GraphProcessor {
986
1059
  }));
987
1060
  await this.#emitter.emit('nodeFinish', this.#withExecution({
988
1061
  node,
989
- outputs: this.#nodeResults.get(node.id),
1062
+ outputs,
990
1063
  processId: 'preload',
991
1064
  resultOrigin: 'preloaded',
992
1065
  }));
1066
+ this.#finishStreamingOutputWatches(node, outputs);
993
1067
  }
994
1068
  }
995
1069
  async #queueStartNodes(startNodes) {
@@ -1127,13 +1201,13 @@ export class GraphProcessor {
1127
1201
  return erroredNodeAttachedData.races == null || erroredNodeAttachedData.races.completed === false;
1128
1202
  });
1129
1203
  }
1130
- #createGraphError(erroredNodes, managedAsyncFailures = []) {
1204
+ #createGraphError(erroredNodes, branchFailures = []) {
1131
1205
  if (this.#lifecycle.abortError) {
1132
1206
  return this.#lifecycle.getAbortError();
1133
1207
  }
1134
1208
  const errors = [
1135
1209
  ...erroredNodes.map(([nodeId, error]) => ({ error, node: this.#nodesById[nodeId] })),
1136
- ...managedAsyncFailures.flatMap((failure) => failure.nodeErrors.length > 0 ? failure.nodeErrors : [{ error: failure.error, node: failure.triggerNode }]),
1210
+ ...branchFailures.flatMap((failure) => failure.nodeErrors.length > 0 ? failure.nodeErrors : [{ error: failure.error, node: failure.triggerNode }]),
1137
1211
  ];
1138
1212
  const message = `Graph ${this.#graph.metadata.name} (${this.#graph.metadata.id}) failed to process due to errors in nodes:\n${errors
1139
1213
  .map(({ node }) => `- ${node.title} (${node.id})`)
@@ -1145,11 +1219,15 @@ export class GraphProcessor {
1145
1219
  }
1146
1220
  async #throwIfGraphErrored(includeManagedAsyncFailures = true) {
1147
1221
  const erroredNodes = this.#getUnhandledErroredNodes();
1148
- const managedAsyncFailures = includeManagedAsyncFailures ? this.#managedAsyncBranchFailures : [];
1149
- if ((!erroredNodes.length && !managedAsyncFailures.length) || this.#lifecycle.abortSuccessful) {
1222
+ const branchFailures = [
1223
+ ...(includeManagedAsyncFailures ? this.#managedAsyncBranchFailures : []),
1224
+ ...this.#streamingWatchFailures,
1225
+ ];
1226
+ if (this.#lifecycle.abortSuccessful ||
1227
+ (!this.#lifecycle.isAborted && !erroredNodes.length && !branchFailures.length)) {
1150
1228
  return;
1151
1229
  }
1152
- const error = this.#createGraphError(erroredNodes, managedAsyncFailures);
1230
+ const error = this.#createGraphError(erroredNodes, branchFailures);
1153
1231
  if (!this.#suppressGraphLifecycleEvents) {
1154
1232
  await this.#emitter.emit('graphError', this.#withExecution({ graph: this.#graph, error }));
1155
1233
  }
@@ -1160,7 +1238,6 @@ export class GraphProcessor {
1160
1238
  }
1161
1239
  async #finalizeGraphRun() {
1162
1240
  const outputValues = this.#graphOutputs;
1163
- this.#lifecycle.complete();
1164
1241
  if (this.#suppressGraphLifecycleEvents) {
1165
1242
  return outputValues;
1166
1243
  }
@@ -1168,7 +1245,6 @@ export class GraphProcessor {
1168
1245
  await this.#emitter.emit('graphFinish', this.#withExecution({ graph: this.#graph, outputs: outputValues }));
1169
1246
  if (!this.#isSubProcessor) {
1170
1247
  await this.#emitter.emit('done', { results: outputValues });
1171
- await this.#emitFinishIfNeeded();
1172
1248
  }
1173
1249
  return outputValues;
1174
1250
  }
@@ -1181,21 +1257,7 @@ export class GraphProcessor {
1181
1257
  if (!this.#context.projectReferenceLoader) {
1182
1258
  throw new Error('Project references are set, but no projectReferenceLoader is set in the context. Since this project uses project references, you must provide a projectReferenceLoader in the context.');
1183
1259
  }
1184
- const seenProjectIds = new Set();
1185
- const loadProject = async (ref) => {
1186
- if (seenProjectIds.has(ref.id)) {
1187
- return;
1188
- }
1189
- seenProjectIds.add(ref.id);
1190
- const project = await this.#context.projectReferenceLoader.loadProject(this.#context.projectPath, ref);
1191
- this.#loadedProjects[project.metadata.id] = project;
1192
- for (const reference of project.references ?? []) {
1193
- await loadProject(reference);
1194
- }
1195
- };
1196
- for (const reference of this.#project.references) {
1197
- await loadProject(reference);
1198
- }
1260
+ this.#loadedProjects = await loadProjectReferenceTree(this.#project, this.#context.projectPath, this.#context.projectReferenceLoader);
1199
1261
  if (this.#cacheLoadedProjects && this.#runtimeCache) {
1200
1262
  this.#runtimeCache.loadedProjects = { ...this.#loadedProjects };
1201
1263
  }
@@ -1311,6 +1373,18 @@ export class GraphProcessor {
1311
1373
  if (missingRequiredInputs.length > 0) {
1312
1374
  return this.#excludeNodeWithMissingRequiredInputs(node, inputValues, missingRequiredInputs, { queueOutputNodes });
1313
1375
  }
1376
+ // Topology validation catches this before a Watch invocation starts. Keep
1377
+ // the same guard at the execution boundary so a dynamically reached or
1378
+ // otherwise malformed subprocessor can never hand detached work to the
1379
+ // root-managed async scheduler. A trigger without an active output has no
1380
+ // branch to hand off, so it is a harmless unfinished authoring state.
1381
+ const managedAsyncBranchWatchViolation = node.type === 'startBackgroundBranch' && this.#getActiveOutputPortIds(node).size > 0
1382
+ ? this.#getManagedAsyncBranchWatchViolation(node)
1383
+ : undefined;
1384
+ if (managedAsyncBranchWatchViolation) {
1385
+ await this.#nodeErrored(node, managedAsyncBranchWatchViolation, nanoid());
1386
+ return [];
1387
+ }
1314
1388
  if (this.#beginNodeProcessing(node, attachedData) === false) {
1315
1389
  return [];
1316
1390
  }
@@ -1526,6 +1600,15 @@ export class GraphProcessor {
1526
1600
  if (!plan) {
1527
1601
  return;
1528
1602
  }
1603
+ const watchViolation = this.#getManagedAsyncBranchWatchViolation(triggerNode);
1604
+ if (watchViolation) {
1605
+ // The pre-dispatch guard above is the normal reporting path. Retain a
1606
+ // final guard here because this is the only handoff to the root-owned
1607
+ // scheduler: silently dropping the branch would make a malformed run
1608
+ // look successful, while enqueueing it would bypass Watch bounds.
1609
+ this.getRootProcessor().#recordManagedAsyncBranchFailure(triggerNode, undefined, watchViolation);
1610
+ return;
1611
+ }
1529
1612
  const root = this.getRootProcessor();
1530
1613
  root.#managedAsyncBranches ??= new ManagedAsyncBranches();
1531
1614
  const queueKey = `${this.#project.metadata?.id ?? 'project'}:${this.#graph.metadata?.id ?? 'graph'}:${triggerNode.id}`;
@@ -1645,18 +1728,34 @@ export class GraphProcessor {
1645
1728
  }
1646
1729
  }
1647
1730
  #recordManagedAsyncBranchFailure(triggerNode, processor, error) {
1648
- const nodeErrors = processor && processor.#erroredNodes
1649
- ? [...processor.#erroredNodes.entries()].flatMap(([nodeId, nodeError]) => {
1650
- const node = processor.#nodesById[nodeId];
1651
- return node ? [{ error: nodeError, node }] : [];
1652
- })
1653
- : [];
1654
1731
  this.#managedAsyncBranchFailures.push({
1655
1732
  error: getError(error),
1656
- nodeErrors,
1733
+ nodeErrors: this.#getSubprocessorNodeErrors(processor),
1657
1734
  triggerNode,
1658
1735
  });
1659
1736
  }
1737
+ #getSubprocessorNodeErrors(processor) {
1738
+ if (!processor || !processor.#erroredNodes) {
1739
+ return [];
1740
+ }
1741
+ return [...processor.#erroredNodes.entries()].flatMap(([nodeId, nodeError]) => {
1742
+ const node = processor.#nodesById[nodeId];
1743
+ return node ? [{ error: nodeError, node }] : [];
1744
+ });
1745
+ }
1746
+ #recordStreamingWatchFailure(watchNode, error, processor) {
1747
+ if (this.#streamingWatchFailures.some((failure) => failure.error === error)) {
1748
+ return;
1749
+ }
1750
+ // The child processor already emitted the precise nodeError before its
1751
+ // failure reaches the coordinator. Keep a root-owned failure too so the
1752
+ // normal graphError/error lifecycle remains truthful after draining.
1753
+ this.#streamingWatchFailures.push({
1754
+ error,
1755
+ nodeErrors: this.#getSubprocessorNodeErrors(processor),
1756
+ triggerNode: watchNode,
1757
+ });
1758
+ }
1660
1759
  #getAttachedDataTo(node) {
1661
1760
  const nodeId = typeof node === 'string' ? node : node.id;
1662
1761
  let nodeData = this.#attachedNodeData.get(nodeId);
@@ -1674,7 +1773,10 @@ export class GraphProcessor {
1674
1773
  return { processId, shouldQueueOutputNodes: false };
1675
1774
  }
1676
1775
  const frozenOutputs = this.#resolveFrozenNodeOutputs(node, inputValues, processId);
1677
- if (frozenOutputs && node.type === 'startBackgroundBranch') {
1776
+ if (frozenOutputs && this.#isStreamingOutputWatchBoundary(node)) {
1777
+ await this.#nodeErrored(node, new Error(`${node.title} cannot use frozen outputs because replaying a streaming boundary would bypass its scheduler.`), processId, undefined, undefined, 'frozen');
1778
+ }
1779
+ else if (frozenOutputs && node.type === 'startBackgroundBranch') {
1678
1780
  await this.#nodeErrored(node, new Error('Start Async Branch cannot use frozen outputs because replaying it could repeat async side effects.'), processId, undefined, undefined, 'frozen');
1679
1781
  }
1680
1782
  else if (frozenOutputs) {
@@ -1700,7 +1802,8 @@ export class GraphProcessor {
1700
1802
  accumulateCost: (output) => this.#accumulateCost(output),
1701
1803
  setNodeResults: (nodeId, outputs) => this.#nodeResults.set(nodeId, outputs),
1702
1804
  markNodeVisited: (nodeId) => this.#visitedNodes.add(nodeId),
1703
- nodeErrored: (n, err, pid, durationMs, splitRunDurationMs, resultOrigin) => this.#nodeErrored(n, err, pid, durationMs, splitRunDurationMs, resultOrigin),
1805
+ nodeErrored: (n, err, pid, durationMs, splitRunDurationMs, resultOrigin, splitOutputs) => this.#nodeErrored(n, err, pid, durationMs, splitRunDurationMs, resultOrigin, undefined, splitOutputs),
1806
+ takeFailureOutputs: (pid, index) => this.#takeFailureOutputs(pid, index),
1704
1807
  isAborted: () => this.#lifecycle.isAborted,
1705
1808
  getAbortError: () => createGraphAbortErrorFromSignal(this.#abortController.signal),
1706
1809
  emit: (event, data) => {
@@ -1708,7 +1811,13 @@ export class GraphProcessor {
1708
1811
  emitDetached(this.#emitter, event, this.#withExecution(data));
1709
1812
  return;
1710
1813
  }
1711
- return this.#emitter.emit(event, this.#withExecution(data));
1814
+ return this.#emitter.emit(event, this.#withExecution(data)).then(() => {
1815
+ if (event === 'nodeFinish') {
1816
+ // SplitRunDeps exposes overloaded event payloads; the runtime event
1817
+ // discriminator guarantees this is the terminal-output shape.
1818
+ this.#commitStreamingWatchStop(node, data.outputs);
1819
+ }
1820
+ });
1712
1821
  },
1713
1822
  startNodeTiming: this.#captureNodeTimings ? () => this.#startNodeTiming() : undefined,
1714
1823
  finishNodeTiming: this.#captureNodeTimings ? (start) => this.#finishNodeTiming(start) : undefined,
@@ -1736,12 +1845,14 @@ export class GraphProcessor {
1736
1845
  this.#visitedNodes.add(node.id);
1737
1846
  this.#accumulateCost(outputValues);
1738
1847
  await this.#applyFrozenNodeDataflowEffects(node, outputValues, processId);
1848
+ this.#assertStreamingOutputWatchFinalOutputs(node, outputValues);
1739
1849
  await this.#emitter.emit('nodeFinish', this.#withExecution(withOptionalDuration({
1740
1850
  node,
1741
1851
  outputs: outputValues,
1742
1852
  processId,
1743
1853
  resultOrigin: 'frozen',
1744
1854
  }, this.#finishNodeTiming(timingStart))));
1855
+ this.#finishStreamingOutputWatches(node, outputValues);
1745
1856
  }
1746
1857
  async #applyFrozenNodeDataflowEffects(node, outputValues, processId) {
1747
1858
  const effect = applyFrozenGraphBoundaryEffects(this.#graphOutputs, node, outputValues);
@@ -1774,32 +1885,67 @@ export class GraphProcessor {
1774
1885
  this.#nodeResults.set(node.id, outputValues);
1775
1886
  this.#visitedNodes.add(node.id);
1776
1887
  this.#accumulateCost(outputValues);
1888
+ this.#assertStreamingOutputWatchFinalOutputs(node, outputValues);
1777
1889
  await this.#emitter.emit('nodeFinish', this.#withExecution(withOptionalDuration({
1778
1890
  node,
1779
1891
  outputs: outputValues,
1780
1892
  processId,
1781
1893
  resultOrigin,
1782
1894
  }, this.#finishNodeTiming(timingStart))));
1895
+ this.#finishStreamingOutputWatches(node, outputValues);
1896
+ this.#commitStreamingWatchStop(node, outputValues);
1783
1897
  }
1784
1898
  catch (error) {
1785
- await this.#nodeErrored(node, error, processId, this.#finishNodeTiming(timingStart), undefined, resultOrigin);
1899
+ await this.#nodeErrored(node, error, processId, this.#finishNodeTiming(timingStart), undefined, resultOrigin, this.#takeFailureOutputs(processId, 0));
1786
1900
  }
1787
1901
  }
1788
- async #nodeErrored(node, e, processId, durationMs, splitRunDurationMs, resultOrigin = 'executed') {
1902
+ async #nodeErrored(node, e, processId, durationMs, splitRunDurationMs, resultOrigin = 'executed', outputs, splitOutputs) {
1789
1903
  const error = getError(e);
1904
+ // Most callers are ordinary (non-split) node executions. Let those retain
1905
+ // any checkpoint without requiring every error path to know about the
1906
+ // internal map. Split callers provide their per-index map explicitly.
1907
+ const retainedOutputs = splitOutputs === undefined ? outputs ?? this.#takeFailureOutputs(processId, 0) : outputs;
1790
1908
  const exclusionReason = this.#getErrorExclusionReason(node, error, processId);
1791
1909
  if (exclusionReason) {
1792
1910
  await this.#emitNodeExcluded(node, processId, this.#getInputValuesForNode(node), exclusionReason, resultOrigin);
1793
1911
  this.#emitTraceEvent(`Node ${node.title} (${node.id}-${processId}) was excluded: ${exclusionReason}`);
1794
1912
  return;
1795
1913
  }
1914
+ this.#cancelStreamingOutputWatchesForSource(node.id);
1796
1915
  this.#erroredNodes.set(node.id, error);
1797
- await this.#emitter.emit('nodeError', this.#withExecution(withOptionalDuration({ node, error, processId, resultOrigin }, durationMs, splitRunDurationMs)));
1916
+ await this.#emitter.emit('nodeError', this.#withExecution(withOptionalDuration({
1917
+ node,
1918
+ error,
1919
+ processId,
1920
+ resultOrigin,
1921
+ ...(retainedOutputs === undefined ? {} : { outputs: retainedOutputs }),
1922
+ ...(splitOutputs === undefined ? {} : { splitOutputs }),
1923
+ }, durationMs, splitRunDurationMs)));
1798
1924
  this.#emitTraceEvent(`Node ${node.title} (${node.id}-${processId}) errored: ${error.stack}`);
1799
1925
  }
1800
1926
  #emitNodePartialOutput(node, outputs, index, processId) {
1801
1927
  emitDetached(this.#emitter, 'partialOutput', this.#withExecution({ node, outputs, index, processId, resultOrigin: 'executed' }));
1802
1928
  }
1929
+ #setFailureOutputs(processId, index, outputs) {
1930
+ let outputsByIndex = this.#failureOutputsByProcessId.get(processId);
1931
+ if (!outputsByIndex) {
1932
+ outputsByIndex = new Map();
1933
+ this.#failureOutputsByProcessId.set(processId, outputsByIndex);
1934
+ }
1935
+ outputsByIndex.set(index, outputs);
1936
+ }
1937
+ #takeFailureOutputs(processId, index) {
1938
+ const outputsByIndex = this.#failureOutputsByProcessId.get(processId);
1939
+ const outputs = outputsByIndex?.get(index);
1940
+ outputsByIndex?.delete(index);
1941
+ if (outputsByIndex?.size === 0) {
1942
+ this.#failureOutputsByProcessId.delete(processId);
1943
+ }
1944
+ return outputs;
1945
+ }
1946
+ #discardFailureOutputs(processId, index) {
1947
+ this.#takeFailureOutputs(processId, index);
1948
+ }
1803
1949
  #getErrorExclusionReason(node, error, processId) {
1804
1950
  if (this.#getAttachedDataTo(node).races?.completed) {
1805
1951
  return RACE_LOSER_EXCLUSION_REASON;
@@ -1830,6 +1976,24 @@ export class GraphProcessor {
1830
1976
  }
1831
1977
  return processor;
1832
1978
  }
1979
+ #getEnclosingStreamingWatchInvocation() {
1980
+ let processor = this;
1981
+ while (processor) {
1982
+ if (processor.#streamingWatchInvocation) {
1983
+ return processor.#streamingWatchInvocation;
1984
+ }
1985
+ processor = processor.#parent;
1986
+ }
1987
+ return undefined;
1988
+ }
1989
+ #getManagedAsyncBranchWatchViolation(triggerNode) {
1990
+ const invocation = this.#getEnclosingStreamingWatchInvocation();
1991
+ if (!invocation) {
1992
+ return undefined;
1993
+ }
1994
+ return new Error(`Start Async Branch "${triggerNode.title}" cannot run inside Watch Streaming Output "${invocation.plan.watchNode.title}". ` +
1995
+ 'A Watch invocation must keep all work within the Watch scheduler. Move Start Async Branch after Stop Watching Streaming Output, or run the work directly inside the watched branch.');
1996
+ }
1833
1997
  /** Raise a user event on the processor, all subprocessors, and their children. */
1834
1998
  raiseEvent(event, data) {
1835
1999
  emitDetached(this.#emitter, `userEvent:${event}`, data);
@@ -1939,6 +2103,7 @@ export class GraphProcessor {
1939
2103
  if (nodeAbortController.signal.aborted) {
1940
2104
  if (isSuccessfulNonRaceGraphAbortReason(abortReason)) {
1941
2105
  this.#successfulAbortTerminalProcessIds.add(processId);
2106
+ this.#discardFailureOutputs(processId, index);
1942
2107
  return results;
1943
2108
  }
1944
2109
  else {
@@ -1947,6 +2112,7 @@ export class GraphProcessor {
1947
2112
  }
1948
2113
  this.#finalizeToolCallContinuation(processId, index, results);
1949
2114
  continuationFinalized = true;
2115
+ this.#discardFailureOutputs(processId, index);
1950
2116
  return results;
1951
2117
  }
1952
2118
  finally {
@@ -1961,6 +2127,14 @@ export class GraphProcessor {
1961
2127
  }
1962
2128
  #createNodeProcessContext(node, inputValues, index, processId, nodeAbortController, partialOutput, toolCallTraceSource, markResultAsEditorCacheHit) {
1963
2129
  const plugin = this.#registry.getPluginFor(node.type);
2130
+ const onGraphOutputPartial = isNamedGraphBoundaryCaller(node) &&
2131
+ (this.#streamingWatchPlansBySourceNodeId.has(node.id) ||
2132
+ this.#graphOutputPartialBindingsBySourceNodeId.has(node.id))
2133
+ ? (partialOutputs) => {
2134
+ this.#publishStreamingOutputWatchPartial(node, partialOutputs);
2135
+ this.#publishGraphOutputPartial(node, partialOutputs);
2136
+ }
2137
+ : undefined;
1964
2138
  const toolCallContinuation = this.#getToolCallContinuationContext(node, nodeAbortController.signal, processId, index);
1965
2139
  return buildNodeProcessContext({
1966
2140
  activeOutputPortIds: this.#getActiveOutputPortIds(node),
@@ -1974,10 +2148,21 @@ export class GraphProcessor {
1974
2148
  markResultAsEditorCacheHit,
1975
2149
  node,
1976
2150
  nodeAbortController,
2151
+ onGraphOutputPartial,
1977
2152
  onPartialOutputs: (partialOutputs) => {
1978
2153
  partialOutput?.(node, partialOutputs, index);
2154
+ this.#publishStreamingOutputWatchPartial(node, partialOutputs);
2155
+ this.#publishGraphOutputPartial(node, partialOutputs);
1979
2156
  this.#emitGraphPartialOutputIfNeeded(node, partialOutputs);
1980
2157
  },
2158
+ acceptStreamingWatchStop: this.#streamingWatchInvocation?.plan.stopNodeId === node.id
2159
+ ? () => {
2160
+ if (this.#streamingWatchInvocation) {
2161
+ this.#streamingWatchInvocation.stopReached = true;
2162
+ }
2163
+ }
2164
+ : undefined,
2165
+ setFailureOutputs: (outputs) => this.#setFailureOutputs(processId, index, outputs),
1981
2166
  processId,
1982
2167
  requestUserInput: async (inputStrings, renderingType) => this.#requestUserInput(node, inputStrings, inputValues, renderingType, processId, nodeAbortController.signal),
1983
2168
  reportProgress: (progress) => {
@@ -2323,6 +2508,622 @@ export class GraphProcessor {
2323
2508
  });
2324
2509
  return this.#effectiveConnectionsForRun;
2325
2510
  }
2511
+ #prepareStreamingWatchTopology() {
2512
+ const connections = this.#getEffectiveConnections().filter((connection) => this.#isDefinitionValidConnection(connection));
2513
+ const outgoingByNodeId = new Map();
2514
+ const incomingByNodeId = new Map();
2515
+ const relevantNodeIds = this.#getExecutionRelevantNodeIds();
2516
+ const isRelevant = (nodeId) => !relevantNodeIds || relevantNodeIds.has(nodeId);
2517
+ for (const connection of connections) {
2518
+ const outgoing = outgoingByNodeId.get(connection.outputNodeId) ?? [];
2519
+ outgoing.push(connection);
2520
+ outgoingByNodeId.set(connection.outputNodeId, outgoing);
2521
+ const incoming = incomingByNodeId.get(connection.inputNodeId) ?? [];
2522
+ incoming.push(connection);
2523
+ incomingByNodeId.set(connection.inputNodeId, incoming);
2524
+ }
2525
+ for (const watchNode of Object.values(this.#nodesById)) {
2526
+ if (watchNode.type !== 'watchStreamingOutput' || watchNode.disabled || !isRelevant(watchNode.id)) {
2527
+ continue;
2528
+ }
2529
+ if (watchNode.id === this.#consumedStreamingWatchNodeId) {
2530
+ continue;
2531
+ }
2532
+ const enclosingWatchInvocation = this.#getEnclosingStreamingWatchInvocation();
2533
+ if (enclosingWatchInvocation) {
2534
+ throw new Error(`Watch Streaming Output "${watchNode.title}" cannot run inside Watch Streaming Output ` +
2535
+ `"${enclosingWatchInvocation.plan.watchNode.title}". A Watch branch cannot contain another Watch, including through Subgraph.`);
2536
+ }
2537
+ if (this.#nodeResults.has(watchNode.id)) {
2538
+ throw new Error(`Cannot preload ${watchNode.title} because a streaming boundary must be scheduled. ` +
2539
+ "Run from Watch Streaming Output to reuse a producer's saved final value, or run from the producer to stream again.");
2540
+ }
2541
+ const incoming = incomingByNodeId.get(watchNode.id) ?? [];
2542
+ if (incoming.length === 0) {
2543
+ // An unattached Watch is an ordinary in-progress authoring state. Keep
2544
+ // it dormant rather than making an incomplete canvas fail to run.
2545
+ this.#ignoreNodes.add(watchNode.id);
2546
+ continue;
2547
+ }
2548
+ if (incoming.length !== 1 || incoming[0].inputId !== 'stream') {
2549
+ throw new Error(`Watch Streaming Output "${watchNode.title}" must have exactly one Streaming Output input connection.`);
2550
+ }
2551
+ const sourceConnection = incoming[0];
2552
+ const sourceNode = this.#nodesById[sourceConnection.outputNodeId];
2553
+ if (!sourceNode || sourceNode.disabled || !isRelevant(sourceNode.id)) {
2554
+ throw new Error(`Watch Streaming Output "${watchNode.title}" has no runnable streaming source.`);
2555
+ }
2556
+ if (sourceNode.isSplitRun) {
2557
+ throw new Error(`Watch Streaming Output "${watchNode.title}" cannot watch split-run node "${sourceNode.title}". ` +
2558
+ 'Assemble a single streaming value before the watch boundary.');
2559
+ }
2560
+ const branchNodeIds = new Set();
2561
+ const pendingNodeIds = (outgoingByNodeId.get(watchNode.id) ?? [])
2562
+ .map((connection) => connection.inputNodeId)
2563
+ .filter(isRelevant);
2564
+ let stopNodeId;
2565
+ while (pendingNodeIds.length > 0) {
2566
+ const nodeId = pendingNodeIds.pop();
2567
+ if (nodeId === watchNode.id) {
2568
+ throw new Error(`Watch Streaming Output "${watchNode.title}" cannot reconnect to itself.`);
2569
+ }
2570
+ if (branchNodeIds.has(nodeId)) {
2571
+ continue;
2572
+ }
2573
+ const node = this.#nodesById[nodeId];
2574
+ if (!node || !isRelevant(nodeId)) {
2575
+ continue;
2576
+ }
2577
+ if (node.disabled) {
2578
+ throw new Error(`Watch Streaming Output "${watchNode.title}" cannot include disabled node "${node.title}".`);
2579
+ }
2580
+ if (node.type === 'watchStreamingOutput') {
2581
+ throw new Error(`Watch Streaming Output "${watchNode.title}" cannot contain another Watch Streaming Output node.`);
2582
+ }
2583
+ if (node.type === 'graphOutput') {
2584
+ throw new Error(`Watch Streaming Output "${watchNode.title}" must reach Stop Watching Streaming Output before Graph Output "${node.title}".`);
2585
+ }
2586
+ if (node.type === 'startBackgroundBranch') {
2587
+ throw new Error(`Watch Streaming Output "${watchNode.title}" cannot contain Start Async Branch. ` +
2588
+ 'Keep watched work in the bounded watch branch instead.');
2589
+ }
2590
+ branchNodeIds.add(nodeId);
2591
+ if (node.type === 'stopWatchingStreamingOutput') {
2592
+ if (stopNodeId && stopNodeId !== nodeId) {
2593
+ throw new Error(`Watch Streaming Output "${watchNode.title}" must have one Stop Watching Streaming Output boundary.`);
2594
+ }
2595
+ stopNodeId = nodeId;
2596
+ continue;
2597
+ }
2598
+ for (const connection of outgoingByNodeId.get(nodeId) ?? []) {
2599
+ if (isRelevant(connection.inputNodeId)) {
2600
+ pendingNodeIds.push(connection.inputNodeId);
2601
+ }
2602
+ }
2603
+ }
2604
+ if (branchNodeIds.size === 0) {
2605
+ // Source -> Watch is also a useful intermediate authoring state. There
2606
+ // is no downstream work to schedule yet, so do not create a coordinator.
2607
+ this.#ignoreNodes.add(watchNode.id);
2608
+ continue;
2609
+ }
2610
+ if (stopNodeId) {
2611
+ const reentry = (outgoingByNodeId.get(stopNodeId) ?? []).find((connection) => connection.inputNodeId === watchNode.id || branchNodeIds.has(connection.inputNodeId));
2612
+ if (reentry) {
2613
+ const stopNode = this.#nodesById[stopNodeId];
2614
+ throw new Error(`Stop Watching Streaming Output "${stopNode.title}" cannot reconnect to its own Watch Streaming Output branch. ` +
2615
+ 'Connect it only to ordinary downstream execution.');
2616
+ }
2617
+ }
2618
+ for (const nodeId of branchNodeIds) {
2619
+ const externalInput = (incomingByNodeId.get(nodeId) ?? []).find((connection) => connection.outputNodeId !== watchNode.id && !branchNodeIds.has(connection.outputNodeId));
2620
+ if (externalInput) {
2621
+ const node = this.#nodesById[nodeId];
2622
+ const externalNode = this.#nodesById[externalInput.outputNodeId];
2623
+ throw new Error(`Watch Streaming Output "${watchNode.title}" cannot run "${node.title}" because it also depends on ` +
2624
+ `"${externalNode?.title ?? externalInput.outputNodeId}" outside the watch branch. ` +
2625
+ 'Assemble every required value inside the watch boundary.');
2626
+ }
2627
+ }
2628
+ const graph = {
2629
+ metadata: this.#graph.metadata ? { ...this.#graph.metadata } : undefined,
2630
+ nodes: this.#executionGraphNodes.filter((node) => node.id === watchNode.id || branchNodeIds.has(node.id)),
2631
+ connections: connections.filter((connection) => connection.inputNodeId === watchNode.id ||
2632
+ (branchNodeIds.has(connection.inputNodeId) &&
2633
+ (connection.outputNodeId === watchNode.id || branchNodeIds.has(connection.outputNodeId)))),
2634
+ };
2635
+ const plan = {
2636
+ graph,
2637
+ includeAllStreamedOutput: connections.some((connection) => connection.outputNodeId === watchNode.id &&
2638
+ connection.outputId === 'allStreamedOutput' &&
2639
+ branchNodeIds.has(connection.inputNodeId)),
2640
+ sourceOutputId: sourceConnection.outputId,
2641
+ stopNodeId,
2642
+ streamedOutput: [],
2643
+ previousStreamedValue: undefined,
2644
+ watchNode,
2645
+ nextUpdateIndex: 0,
2646
+ history: new StreamingOutputWatchHistory(),
2647
+ historySummaryEmitted: false,
2648
+ };
2649
+ const plans = this.#streamingWatchPlansBySourceNodeId.get(sourceNode.id) ?? [];
2650
+ plans.push(plan);
2651
+ this.#streamingWatchPlansBySourceNodeId.set(sourceNode.id, plans);
2652
+ this.#streamingWatchPlansByWatchNodeId.set(watchNode.id, plan);
2653
+ const watch = new StreamingOutputWatch(watchNode.data, (snapshot, registerCancel) => this.#runStreamingOutputWatchInvocation(plan, snapshot, registerCancel), (error) => this.#recordStreamingWatchFailure(watchNode, error), { requiresAcceptedStop: stopNodeId != null });
2654
+ this.#streamingOutputWatches.set(watchNode.id, watch);
2655
+ for (const nodeId of [watchNode.id, ...branchNodeIds]) {
2656
+ this.#ignoreNodes.add(nodeId);
2657
+ }
2658
+ }
2659
+ this.#assertStreamingOutputWatchPreloadsAreSafe();
2660
+ }
2661
+ #isStreamingOutputWatchBoundary(node) {
2662
+ return node.type === 'watchStreamingOutput' || node.type === 'stopWatchingStreamingOutput';
2663
+ }
2664
+ #assertStreamingOutputWatchPreloadCanBeAdded(nodeId) {
2665
+ // Before initialization, referenced projects and the effective graph are
2666
+ // not available yet. Startup validation below owns that case. During a
2667
+ // live run, reject injection before it can mutate the result map.
2668
+ if (!this.#lifecycle.isRunning) {
2669
+ return;
2670
+ }
2671
+ const node = this.#nodesById[nodeId];
2672
+ if (!node || !this.#isNodeSelected(node.id) || node.id === this.#consumedStreamingWatchNodeId) {
2673
+ return;
2674
+ }
2675
+ if (this.#isStreamingOutputWatchBoundary(node)) {
2676
+ throw new Error(`Cannot preload ${node.title} while it is running because a streaming boundary must be scheduled. ` +
2677
+ 'Preload the producer before starting a new run instead.');
2678
+ }
2679
+ for (const [sourceNodeId, plans] of this.#streamingWatchPlansBySourceNodeId) {
2680
+ for (const plan of plans) {
2681
+ if (sourceNodeId === node.id || plan.graph.nodes.some((branchNode) => branchNode.id === node.id)) {
2682
+ throw new Error(`Cannot preload ${node.title} while Watch Streaming Output "${plan.watchNode.title}" is running. ` +
2683
+ 'Start a new run so the watch can own its snapshots and branch invocations.');
2684
+ }
2685
+ }
2686
+ }
2687
+ }
2688
+ #assertStreamingOutputWatchPreloadsAreSafe() {
2689
+ for (const [nodeId] of this.#preloadedNodeResults) {
2690
+ const node = this.#nodesById[nodeId];
2691
+ if (!node || !this.#isNodeSelected(node.id) || node.id === this.#consumedStreamingWatchNodeId) {
2692
+ continue;
2693
+ }
2694
+ if (this.#isStreamingOutputWatchBoundary(node)) {
2695
+ throw new Error(`Cannot preload ${node.title} because a streaming boundary must be scheduled. ` +
2696
+ "Run from Watch Streaming Output to reuse a producer's saved final value, or run from the producer to stream again.");
2697
+ }
2698
+ }
2699
+ for (const [sourceNodeId, plans] of this.#streamingWatchPlansBySourceNodeId) {
2700
+ const sourceOutputs = this.#preloadedNodeResults.get(sourceNodeId);
2701
+ for (const plan of plans) {
2702
+ const preloadedBranchNode = plan.graph.nodes.find((node) => node.id !== this.#consumedStreamingWatchNodeId && this.#preloadedNodeResults.has(node.id));
2703
+ if (preloadedBranchNode) {
2704
+ throw new Error(`Cannot preload ${preloadedBranchNode.title} because it belongs to the repeated branch of ` +
2705
+ `Watch Streaming Output "${plan.watchNode.title}". ` +
2706
+ "Run from Watch Streaming Output to reuse a producer's saved final value, or run from the producer to stream again.");
2707
+ }
2708
+ if (sourceOutputs && sourceOutputs[plan.sourceOutputId] == null) {
2709
+ const sourceNode = this.#nodesById[sourceNodeId];
2710
+ throw new Error(`Preloaded source "${sourceNode.title}" has no final "${plan.sourceOutputId}" output for ` +
2711
+ `Watch Streaming Output "${plan.watchNode.title}".`);
2712
+ }
2713
+ }
2714
+ }
2715
+ }
2716
+ #publishStreamingOutputWatchPartial(node, partialOutputs) {
2717
+ for (const plan of this.#streamingWatchPlansBySourceNodeId.get(node.id) ?? []) {
2718
+ const value = partialOutputs[plan.sourceOutputId];
2719
+ if (value == null || value.type === 'control-flow-excluded') {
2720
+ continue;
2721
+ }
2722
+ const watch = this.#streamingOutputWatches.get(plan.watchNode.id);
2723
+ if (!watch || watch.stopped) {
2724
+ continue;
2725
+ }
2726
+ const updateIndex = this.#nextStreamingWatchUpdateIndex(plan);
2727
+ watch.publish(this.#createStreamingOutputWatchSnapshot(plan, value, updateIndex, false));
2728
+ }
2729
+ }
2730
+ #prepareGraphOutputPartialTopology() {
2731
+ if (!this.#graphOutputPartialListener) {
2732
+ return;
2733
+ }
2734
+ const relevantNodeIds = this.#getExecutionRelevantNodeIds();
2735
+ const graphOutputCountsById = new Map();
2736
+ for (const node of Object.values(this.#nodesById)) {
2737
+ if (node.type !== 'graphOutput' || node.disabled || (relevantNodeIds != null && !relevantNodeIds.has(node.id))) {
2738
+ continue;
2739
+ }
2740
+ const outputId = node.data.id;
2741
+ graphOutputCountsById.set(outputId, (graphOutputCountsById.get(outputId) ?? 0) + 1);
2742
+ }
2743
+ for (const connection of this.#getEffectiveConnections()) {
2744
+ if (!this.#isDefinitionValidConnection(connection) || connection.inputId !== 'value') {
2745
+ continue;
2746
+ }
2747
+ const graphOutput = this.#nodesById[connection.inputNodeId];
2748
+ if (graphOutput?.type !== 'graphOutput' ||
2749
+ graphOutput.disabled ||
2750
+ (relevantNodeIds != null && !relevantNodeIds.has(graphOutput.id))) {
2751
+ continue;
2752
+ }
2753
+ const graphOutputData = graphOutput.data;
2754
+ // Graph Outputs with the same public ID retain their long-standing
2755
+ // first-terminal-value-wins behavior. Before that winner is known, a
2756
+ // partial value would be ambiguous, so let the parent Watch receive
2757
+ // only the ordinary final named-boundary output.
2758
+ if (graphOutputCountsById.get(graphOutputData.id) > 1) {
2759
+ continue;
2760
+ }
2761
+ const sourceNode = this.#nodesById[connection.outputNodeId];
2762
+ if (!sourceNode || !this.#canStreamAcrossGraphOutput(graphOutput, sourceNode)) {
2763
+ continue;
2764
+ }
2765
+ const bindings = this.#graphOutputPartialBindingsBySourceNodeId.get(connection.outputNodeId) ?? [];
2766
+ bindings.push({
2767
+ dataType: graphOutputData.dataType,
2768
+ graphOutputId: graphOutputData.id,
2769
+ sourceOutputId: connection.outputId,
2770
+ });
2771
+ this.#graphOutputPartialBindingsBySourceNodeId.set(connection.outputNodeId, bindings);
2772
+ }
2773
+ }
2774
+ /**
2775
+ * A named Graph Output can forward a partial only when its terminal result
2776
+ * is determined by that same direct producer. Conditions, split aggregation,
2777
+ * and frozen replay each introduce an independent boundary decision, so they
2778
+ * remain final-only just like an ordinary intermediate node.
2779
+ */
2780
+ #canStreamAcrossGraphOutput(graphOutput, sourceNode) {
2781
+ if (graphOutput.isConditional || graphOutput.isSplitRun || sourceNode.isSplitRun) {
2782
+ return false;
2783
+ }
2784
+ return !this.#hasFrozenNodeOutputOrUnknownResolver(graphOutput);
2785
+ }
2786
+ #hasFrozenNodeOutputOrUnknownResolver(node) {
2787
+ const resolver = this.#frozenNodeOutputResolver;
2788
+ if (!resolver) {
2789
+ return false;
2790
+ }
2791
+ // Do not call a resolver during topology preparation: generated resolvers
2792
+ // advance a per-node replay cursor, and arbitrary resolvers may have side
2793
+ // effects. The built-in resolver answers precisely; an opaque custom
2794
+ // resolver is final-only until execution resolves its value normally.
2795
+ return resolver.hasFrozenNodeOutput?.({ graphId: this.#graph.metadata.id, node }) !== false;
2796
+ }
2797
+ /**
2798
+ * A Graph Output is a named boundary, so only a direct effective connection
2799
+ * may make its source node stream across a Subgraph. The preprocessed
2800
+ * connections also cover Data Bus routes while excluding ordinary
2801
+ * intermediate nodes, which must still wait for their normal final input.
2802
+ */
2803
+ #publishGraphOutputPartial(node, partialOutputs) {
2804
+ const listener = this.#graphOutputPartialListener;
2805
+ const bindings = this.#graphOutputPartialBindingsBySourceNodeId.get(node.id);
2806
+ if (!listener || !bindings) {
2807
+ return;
2808
+ }
2809
+ const outputs = {};
2810
+ for (const binding of bindings) {
2811
+ const partialValue = partialOutputs[binding.sourceOutputId];
2812
+ if (partialValue == null || partialValue.type === 'control-flow-excluded') {
2813
+ continue;
2814
+ }
2815
+ outputs[binding.graphOutputId] = coerceGraphOutputValue(partialValue, binding.dataType);
2816
+ }
2817
+ if (Object.keys(outputs).length > 0) {
2818
+ listener(outputs);
2819
+ }
2820
+ }
2821
+ #finishStreamingOutputWatches(node, outputs) {
2822
+ for (const plan of this.#streamingWatchPlansBySourceNodeId.get(node.id) ?? []) {
2823
+ const value = outputs[plan.sourceOutputId];
2824
+ const watch = this.#streamingOutputWatches.get(plan.watchNode.id);
2825
+ if (!watch || watch.stopped) {
2826
+ continue;
2827
+ }
2828
+ if (value == null) {
2829
+ // This is guarded before nodeFinish so a bad producer has one
2830
+ // coherent terminal lifecycle (nodeError, never nodeFinish + error).
2831
+ continue;
2832
+ }
2833
+ if (value.type === 'control-flow-excluded') {
2834
+ watch.stop();
2835
+ if (plan.stopNodeId) {
2836
+ this.#excludeNode(this.#nodesById[plan.stopNodeId], nanoid(), {}, 'watched output is excluded');
2837
+ }
2838
+ continue;
2839
+ }
2840
+ const updateIndex = this.#nextStreamingWatchUpdateIndex(plan);
2841
+ watch.finish(this.#createStreamingOutputWatchSnapshot(plan, value, updateIndex, true));
2842
+ }
2843
+ }
2844
+ #assertStreamingOutputWatchFinalOutputs(node, outputs) {
2845
+ for (const plan of this.#streamingWatchPlansBySourceNodeId.get(node.id) ?? []) {
2846
+ const watch = this.#streamingOutputWatches.get(plan.watchNode.id);
2847
+ if (!watch || watch.stopped || outputs[plan.sourceOutputId] != null) {
2848
+ continue;
2849
+ }
2850
+ throw new Error(`Watch Streaming Output "${plan.watchNode.title}" did not receive final output from "${node.title}".`);
2851
+ }
2852
+ }
2853
+ #nextStreamingWatchUpdateIndex(plan) {
2854
+ plan.nextUpdateIndex += 1;
2855
+ return plan.nextUpdateIndex;
2856
+ }
2857
+ #createStreamingOutputWatchSnapshot(plan, value, updateIndex, isFinal) {
2858
+ const snapshotValue = cloneExecutionOutputs({ ['value']: value })['value'];
2859
+ let streamedOutputLength;
2860
+ if (plan.includeAllStreamedOutput) {
2861
+ const streamedValue = snapshotValue.value;
2862
+ const previousValue = plan.previousStreamedValue;
2863
+ plan.previousStreamedValue = streamedValue;
2864
+ // LLM Chat publishes accumulated response text for every token. Store
2865
+ // only the suffix here so this history is linear in the response size,
2866
+ // while still supporting providers that publish independent chunks.
2867
+ const increment = typeof previousValue === 'string' &&
2868
+ typeof streamedValue === 'string' &&
2869
+ streamedValue.startsWith(previousValue)
2870
+ ? streamedValue.slice(previousValue.length)
2871
+ : streamedValue;
2872
+ if (increment !== '') {
2873
+ plan.streamedOutput.push(increment);
2874
+ }
2875
+ streamedOutputLength = plan.streamedOutput.length;
2876
+ }
2877
+ const outputs = {
2878
+ ['isFinal']: { type: 'boolean', value: isFinal },
2879
+ ['updateIndex']: { type: 'number', value: updateIndex },
2880
+ ['value']: snapshotValue,
2881
+ };
2882
+ return {
2883
+ outputs,
2884
+ isFinal,
2885
+ updateIndex,
2886
+ ...(streamedOutputLength === undefined
2887
+ ? {}
2888
+ : {
2889
+ streamedOutput: plan.streamedOutput,
2890
+ streamedOutputLength,
2891
+ }),
2892
+ };
2893
+ }
2894
+ #materializeStreamingOutputWatchSnapshot(snapshot) {
2895
+ if (snapshot.streamedOutput == null || snapshot.streamedOutputLength == null) {
2896
+ return snapshot.outputs;
2897
+ }
2898
+ // Construct cumulative chunks only for a branch that actually starts. A
2899
+ // coalesced interval update or a queue-dropped update therefore performs no
2900
+ // quadratic history copy merely because All Chunks is connected.
2901
+ return {
2902
+ ...snapshot.outputs,
2903
+ ['allStreamedOutput']: cloneExecutionOutputs({
2904
+ ['allStreamedOutput']: {
2905
+ type: 'any[]',
2906
+ value: snapshot.streamedOutput.slice(0, snapshot.streamedOutputLength),
2907
+ },
2908
+ })['allStreamedOutput'],
2909
+ };
2910
+ }
2911
+ async #runStreamingOutputWatchInvocation(plan, snapshot, registerCancel) {
2912
+ const root = this.getRootProcessor();
2913
+ if (root.#abortController.signal.aborted) {
2914
+ throw createGraphAbortErrorFromSignal(root.#abortController.signal, 'Streaming watch branch aborted before it started');
2915
+ }
2916
+ const graphId = plan.graph.metadata?.id;
2917
+ if (!graphId) {
2918
+ throw new Error('Cannot start a streaming watch branch because the current graph has no ID.');
2919
+ }
2920
+ const historyIteration = plan.history.start(nanoid(), snapshot.updateIndex);
2921
+ const branchRuntimeCache = {
2922
+ ...this.#runtimeCache,
2923
+ graphBoundaries: undefined,
2924
+ loadedProjects: { ...this.#loadedProjects },
2925
+ };
2926
+ const processor = new GraphProcessor(this.#project, graphId, this.#registry, this.#includeTrace, {
2927
+ cacheLoadedProjects: true,
2928
+ captureNodeTimings: this.#captureNodeTimings,
2929
+ concurrency: this.#concurrency,
2930
+ executionPlanCacheMode: this.#executionPlanCacheMode,
2931
+ runtimeCache: branchRuntimeCache,
2932
+ runtimeProfiler: this.#runtimeProfiler,
2933
+ scheduler: this.#scheduler,
2934
+ [consumedStreamingWatchNodeOverride]: plan.watchNode.id,
2935
+ [graphProcessorGraphOverride]: plan.graph,
2936
+ });
2937
+ processor.executor = this.executor;
2938
+ processor.#isSubProcessor = true;
2939
+ processor.#executionCache = this.#executionCache;
2940
+ processor.#externalFunctions = this.#externalFunctions;
2941
+ processor.#contextValues = this.#contextValues;
2942
+ processor.#parent = this;
2943
+ processor.#abortOwnerOverride = root;
2944
+ processor.#suppressGraphPartialOutputs = true;
2945
+ processor.#globals = this.#globals;
2946
+ processor.#storedValueController = this.#storedValueController;
2947
+ processor.#knowledgeStoreController = this.#knowledgeStoreController;
2948
+ processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
2949
+ processor.#executor = this.#executor;
2950
+ processor.#suppressGraphLifecycleEvents = true;
2951
+ processor.#sharedRunStateOverride = {
2952
+ // Repeated node IDs do not imply shared race/loop state between snapshots.
2953
+ attachedNodeData: new Map(),
2954
+ graphInputNodeValues: { ...this.#graphInputNodeValues },
2955
+ graphOutputs: {},
2956
+ };
2957
+ processor.#executionIdentityOverride = {
2958
+ rootRunId: root.#rootRunId,
2959
+ graphRunId: historyIteration.graphRunId,
2960
+ parentGraphRunId: this.#graphRunId,
2961
+ };
2962
+ processor.#streamingWatchInvocation = {
2963
+ plan,
2964
+ historyIteration,
2965
+ acceptStop: (value) => this.#acceptStreamingWatchStop(plan, historyIteration, value, snapshot.updateIndex),
2966
+ stopReached: false,
2967
+ };
2968
+ processor.preloadNodeData(plan.watchNode.id, this.#materializeStreamingOutputWatchSnapshot(snapshot));
2969
+ processor.#suppressedPreloadedNodeIds.add(plan.watchNode.id);
2970
+ let cancellationRequested = false;
2971
+ registerCancel(() => {
2972
+ cancellationRequested = true;
2973
+ if (processor.isRunning) {
2974
+ void processor.abort(true);
2975
+ }
2976
+ });
2977
+ const unwireEvents = wireSubprocessorEvents(processor, root.#emitter, {
2978
+ autoCleanup: false,
2979
+ isPaused: () => root.#lifecycle.isPaused,
2980
+ pause: () => {
2981
+ void root.pause();
2982
+ },
2983
+ resume: () => {
2984
+ void root.resume();
2985
+ },
2986
+ forwardEvent: (event, data) => {
2987
+ // Interactive/global control events are side effects, not execution
2988
+ // history. They must remain live even when their enclosing iteration
2989
+ // is not selected for retained evidence.
2990
+ if (event === 'userInput' ||
2991
+ event === 'globalSet' ||
2992
+ event === 'newAbortController' ||
2993
+ event.startsWith('globalSet:')) {
2994
+ return root.#emitter.emit(event, data);
2995
+ }
2996
+ return plan.history.forward(historyIteration, event, data, (nextEvent, nextData) => root.#emitter.emit(nextEvent, nextData));
2997
+ },
2998
+ });
2999
+ const unwireLifecycle = wireSubprocessorLifecycle(processor, {
3000
+ autoCleanup: false,
3001
+ signal: this.#abortController.signal,
3002
+ parentAbortSignal: root.#abortController.signal,
3003
+ onParentPause: (listener) => {
3004
+ root.on('pause', listener);
3005
+ return () => root.off('pause', listener);
3006
+ },
3007
+ onParentResume: (listener) => {
3008
+ root.on('resume', listener);
3009
+ return () => root.off('resume', listener);
3010
+ },
3011
+ });
3012
+ root.#subprocessors.add(processor);
3013
+ try {
3014
+ if (root.#lifecycle.isPaused) {
3015
+ processor.pause();
3016
+ }
3017
+ await processor.processGraph(this.#context, this.#graphInputs, this.#contextValues);
3018
+ }
3019
+ catch (error) {
3020
+ const normalizedError = getError(error);
3021
+ const wasCancelled = isAbortLikeError(normalizedError) || root.#abortController.signal.aborted || cancellationRequested;
3022
+ if (wasCancelled) {
3023
+ plan.history.cancel(historyIteration);
3024
+ }
3025
+ else {
3026
+ plan.history.fail(historyIteration);
3027
+ this.#recordStreamingWatchFailure(plan.watchNode, normalizedError, processor);
3028
+ }
3029
+ // Preserve one Error identity across the child processor, scheduler, and
3030
+ // root failure collector. A user node may throw a string or another
3031
+ // non-Error value; allowing the scheduler to wrap it again would make
3032
+ // that one branch failure appear twice in the root aggregate.
3033
+ throw normalizedError;
3034
+ }
3035
+ finally {
3036
+ if (cancellationRequested) {
3037
+ plan.history.cancel(historyIteration);
3038
+ }
3039
+ plan.history.complete(historyIteration);
3040
+ this.#totalCost += processor.#totalCost;
3041
+ unwireLifecycle();
3042
+ unwireEvents();
3043
+ root.#subprocessors.delete(processor);
3044
+ }
3045
+ }
3046
+ #commitStreamingWatchStop(node, outputs) {
3047
+ const invocation = this.#streamingWatchInvocation;
3048
+ const completedValue = outputs['value'];
3049
+ if (invocation?.plan.stopNodeId === node.id &&
3050
+ invocation.stopReached &&
3051
+ completedValue !== undefined &&
3052
+ !this.#getUnhandledErroredNodes().length) {
3053
+ invocation.acceptStop(completedValue);
3054
+ }
3055
+ }
3056
+ #acceptStreamingWatchStop(plan, historyIteration, value, updateIndex) {
3057
+ const stopNodeId = plan.stopNodeId;
3058
+ if (!stopNodeId) {
3059
+ return;
3060
+ }
3061
+ const watch = this.#streamingOutputWatches.get(plan.watchNode.id);
3062
+ if (!watch || watch.stopped) {
3063
+ return;
3064
+ }
3065
+ plan.history.acceptStop(historyIteration);
3066
+ watch.stop(updateIndex);
3067
+ const stopNode = this.#nodesById[stopNodeId];
3068
+ if (!stopNode) {
3069
+ throw new Error(`Watch Streaming Output "${plan.watchNode.title}" lost its Stop Watching Streaming Output node.`);
3070
+ }
3071
+ const acceptedValue = cloneExecutionOutputs({ ['value']: value })['value'];
3072
+ this.#nodeResults.set(stopNode.id, { ['value']: acceptedValue });
3073
+ this.#visitedNodes.add(stopNode.id);
3074
+ this.#remainingNodes.delete(stopNode.id);
3075
+ const attachedData = this.#getAttachedDataTo(stopNode);
3076
+ const outputNodes = getOutputNodesFrom(this.#executionState, stopNode);
3077
+ this.#propagateAttachedDataToOutputNodes(stopNode, attachedData, outputNodes.connectionsToNodes);
3078
+ this.#queueOutputNodes(stopNode, outputNodes.nodes);
3079
+ }
3080
+ #cancelStreamingOutputWatchesForSource(nodeId) {
3081
+ for (const plan of this.#streamingWatchPlansBySourceNodeId.get(nodeId) ?? []) {
3082
+ this.#streamingOutputWatches.get(plan.watchNode.id)?.stop();
3083
+ }
3084
+ }
3085
+ #cancelStreamingOutputWatches() {
3086
+ for (const watch of this.#streamingOutputWatches.values()) {
3087
+ watch.stop();
3088
+ }
3089
+ }
3090
+ #hasPendingStreamingOutputWatches() {
3091
+ return [...this.#streamingOutputWatches.values()].some((watch) => watch.hasPending);
3092
+ }
3093
+ #hasUnresolvedForegroundOutputStreamingWatch() {
3094
+ return [...this.#streamingOutputWatches.values()].some((watch) => !watch.stopped && watch.canAffectForegroundOutputs);
3095
+ }
3096
+ #hasDrainableStreamingOutputWatches() {
3097
+ return [...this.#streamingOutputWatches.values()].some((watch) => watch.hasPending && !watch.isAwaitingProducer);
3098
+ }
3099
+ async #drainSchedulerBoundaries() {
3100
+ do {
3101
+ if (!this.#isSubProcessor) {
3102
+ await this.#profileRuntimeAsync('drainManagedAsyncBranches', () => this.#managedAsyncBranches.drain());
3103
+ }
3104
+ await this.#profileRuntimeAsync('drainStreamingOutputWatches', () => this.#drainStreamingOutputWatches());
3105
+ } while ((!this.#isSubProcessor && this.#managedAsyncBranches.hasPending) ||
3106
+ this.#hasDrainableStreamingOutputWatches());
3107
+ }
3108
+ async #drainStreamingOutputWatches() {
3109
+ do {
3110
+ for (const watch of this.#streamingOutputWatches.values()) {
3111
+ await watch.drain();
3112
+ }
3113
+ // Accepting Stop happens in a child run. It can enqueue ordinary parent
3114
+ // work after the compatible scheduler has returned, so wait for that work
3115
+ // before deciding every Watch boundary is quiet.
3116
+ await this.#processingQueue.onIdle();
3117
+ } while (this.#hasDrainableStreamingOutputWatches());
3118
+ for (const [watchNodeId, watch] of this.#streamingOutputWatches) {
3119
+ const plan = this.#streamingWatchPlansByWatchNodeId.get(watchNodeId);
3120
+ if (!plan || plan.historySummaryEmitted || !watch.isSettled)
3121
+ continue;
3122
+ const summary = await plan.history.finalize(watch.runtimeSummary, (event, data) => this.#emitter.emit(event, data));
3123
+ plan.historySummaryEmitted = true;
3124
+ await this.#emitter.emit('streamingOutputWatchSummary', this.#withExecution({ watchNode: plan.watchNode, summary }));
3125
+ }
3126
+ }
2326
3127
  #prepareAsyncBranchTopology() {
2327
3128
  const connections = this.#getEffectiveConnections().filter((connection) => this.#isDefinitionValidConnection(connection));
2328
3129
  const outgoingByNodeId = new Map();
@@ -2385,6 +3186,10 @@ export class GraphProcessor {
2385
3186
  if (nodeIds.size === 0) {
2386
3187
  continue;
2387
3188
  }
3189
+ const managedAsyncBranchWatchViolation = this.#getManagedAsyncBranchWatchViolation(triggerNode);
3190
+ if (managedAsyncBranchWatchViolation) {
3191
+ throw managedAsyncBranchWatchViolation;
3192
+ }
2388
3193
  const preloadedNodeId = [...nodeIds].find((nodeId) => this.#nodeResults.has(nodeId));
2389
3194
  if (preloadedNodeId) {
2390
3195
  const preloadedNode = this.#nodesById[preloadedNodeId];
@@ -2685,6 +3490,7 @@ export class GraphProcessor {
2685
3490
  this.#registerNodeInActiveLoop(node, attachedData);
2686
3491
  this.#visitedNodes.add(node.id);
2687
3492
  this.#markAsExcluded(node, processId, inputValues, reason);
3493
+ this.#finishStreamingOutputWatches(node, this.#nodeResults.get(node.id));
2688
3494
  this.#currentlyProcessing.delete(node.id);
2689
3495
  this.#remainingNodes.delete(node.id);
2690
3496
  const outputNodes = getOutputNodesFrom(this.#executionState, node);
@@ -2699,10 +3505,12 @@ export class GraphProcessor {
2699
3505
  }
2700
3506
  async #emitNodeExcluded(node, processId, inputValues, reason, resultOrigin = 'executed') {
2701
3507
  await this.#emitter.emit('nodeExcluded', this.#createNodeExcludedEvent(node, processId, inputValues, reason, resultOrigin));
3508
+ this.#finishStreamingOutputWatches(node, this.#nodeResults.get(node.id));
2702
3509
  }
2703
3510
  #createNodeExcludedEvent(node, processId, inputValues, reason, resultOrigin = 'executed') {
2704
3511
  const outputs = createExcludedNodeOutputs(node, this.#definitions[node.id].outputs);
2705
3512
  this.#nodeResults.set(node.id, outputs);
3513
+ this.#commitExcludedGraphOutput(node, inputValues, outputs);
2706
3514
  return this.#withExecution({
2707
3515
  node,
2708
3516
  processId,
@@ -2712,6 +3520,17 @@ export class GraphProcessor {
2712
3520
  resultOrigin,
2713
3521
  });
2714
3522
  }
3523
+ #commitExcludedGraphOutput(node, inputs, outputs) {
3524
+ const isFalseCondition = node.isConditional && coerceTypeOptional(inputs[IF_PORT.id], 'boolean') === false;
3525
+ if (node.type !== 'graphOutput' || (inputs['value'] == null && !isFalseCondition)) {
3526
+ return;
3527
+ }
3528
+ const outputId = node.data.id;
3529
+ const value = outputs['valueOutput'];
3530
+ if (value) {
3531
+ commitGraphOutputValue(this.#graphOutputs, outputId, value);
3532
+ }
3533
+ }
2715
3534
  #getInputValuesForNode(node) {
2716
3535
  const connections = this.#connections[node.id];
2717
3536
  return this.#definitions[node.id].inputs.reduce((values, input) => {