@valerypopoff/rivet2-core 2.15.0 → 2.19.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 (187) hide show
  1. package/dist/cjs/bundle.cjs +7906 -3980
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/interpolationRuntime.cjs +62 -7
  4. package/dist/cjs/interpolationRuntime.cjs.map +3 -3
  5. package/dist/cjs/interpolationSyntax.cjs +9 -5
  6. package/dist/cjs/interpolationSyntax.cjs.map +2 -2
  7. package/dist/cjs/serialization.cjs +1880 -0
  8. package/dist/cjs/serialization.cjs.map +7 -0
  9. package/dist/cjs/webAppRuntime.cjs +168 -6
  10. package/dist/cjs/webAppRuntime.cjs.map +3 -3
  11. package/dist/esm/api/createProcessor.js +5 -2
  12. package/dist/esm/api/processSettings.js +1 -0
  13. package/dist/esm/exports.js +4 -0
  14. package/dist/esm/model/AgentResponseTrace.js +99 -34
  15. package/dist/esm/model/AgentResponseTracePresentation.js +130 -0
  16. package/dist/esm/model/DataValue.js +11 -2
  17. package/dist/esm/model/GlobalVariables.js +2 -1
  18. package/dist/esm/model/GraphBoundaryCache.js +2 -1
  19. package/dist/esm/model/GraphBoundaryEffects.js +38 -1
  20. package/dist/esm/model/GraphExecutionState.js +81 -0
  21. package/dist/esm/model/GraphProcessor.js +825 -884
  22. package/dist/esm/model/GraphSchedulerBoundaryState.js +64 -0
  23. package/dist/esm/model/Nodes.js +15 -0
  24. package/dist/esm/model/ProjectBundle.js +248 -0
  25. package/dist/esm/model/ProjectBundleRuntime.js +54 -0
  26. package/dist/esm/model/SchedulerBoundaryPlanner.js +233 -0
  27. package/dist/esm/model/SplitRunProcessor.js +28 -7
  28. package/dist/esm/model/StreamingWatchTopology.js +118 -8
  29. package/dist/esm/model/SubgraphProjectTarget.js +7 -0
  30. package/dist/esm/model/SubprocessorBridge.js +125 -87
  31. package/dist/esm/model/ToolCallContinuationCoordinator.js +1 -1
  32. package/dist/esm/model/chat-v2/aiSdkBridge.js +22 -17
  33. package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -4
  34. package/dist/esm/model/chat-v2/chatV2CredentialNames.js +5 -1
  35. package/dist/esm/model/chat-v2/chatV2Outputs.js +2 -2
  36. package/dist/esm/model/chat-v2/chatV2Pipeline.js +24 -9
  37. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +3 -2
  38. package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +46 -6
  39. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +26 -1
  40. package/dist/esm/model/chat-v2/chatV2Shared.js +2 -1
  41. package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +10 -0
  42. package/dist/esm/model/chat-v2/llmChatV2Body.js +13 -10
  43. package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +5 -2
  44. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +3 -0
  45. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +33 -9
  46. package/dist/esm/model/chat-v2/llmChatV2NodeMigration.js +22 -2
  47. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +10 -2
  48. package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +17 -0
  49. package/dist/esm/model/chat-v2/llmModelCandidate.js +2 -1
  50. package/dist/esm/model/chat-v2/llmProfile.js +5 -1
  51. package/dist/esm/model/chat-v2/llmProfileBody.js +11 -2
  52. package/dist/esm/model/chat-v2/llmProfileFallback.js +7 -4
  53. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +2 -1
  54. package/dist/esm/model/chat-v2/llmProfileHealthStore.js +16 -3
  55. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +1 -1
  56. package/dist/esm/model/chat-v2/messageConverter.js +18 -16
  57. package/dist/esm/model/chat-v2/modelRegistry.js +14 -4
  58. package/dist/esm/model/chat-v2/openRouterModel.js +73 -0
  59. package/dist/esm/model/chat-v2/parallelToolCalls.js +2 -0
  60. package/dist/esm/model/chat-v2/providerOptions.js +30 -25
  61. package/dist/esm/model/chat-v2/temperature.js +9 -0
  62. package/dist/esm/model/classifier/credentials.js +42 -6
  63. package/dist/esm/model/classifier/images.js +176 -0
  64. package/dist/esm/model/classifier/json.js +57 -0
  65. package/dist/esm/model/classifier/limits.js +300 -0
  66. package/dist/esm/model/classifier/openai.js +118 -0
  67. package/dist/esm/model/classifier/perplexity.js +63 -0
  68. package/dist/esm/model/classifier/preparation.js +74 -0
  69. package/dist/esm/model/classifier/profile.js +151 -0
  70. package/dist/esm/model/classifier/profileExecution.js +294 -0
  71. package/dist/esm/model/classifier/providers.js +454 -192
  72. package/dist/esm/model/classifier/questionHelpers.js +29 -45
  73. package/dist/esm/model/classifier/questions.js +53 -0
  74. package/dist/esm/model/classifier/response.js +75 -0
  75. package/dist/esm/model/classifier/state.js +207 -0
  76. package/dist/esm/model/classifier/types.js +11 -1
  77. package/dist/esm/model/nodeRunFailure.js +54 -0
  78. package/dist/esm/model/nodes/CallGraphNode.js +6 -0
  79. package/dist/esm/model/nodes/CatchStreamingChunksNode.js +42 -0
  80. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +385 -154
  81. package/dist/esm/model/nodes/ClassifierProfileNode.js +133 -0
  82. package/dist/esm/model/nodes/ClassifierQuestionNode.js +59 -15
  83. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +1 -1
  84. package/dist/esm/model/nodes/GetGlobalNode.js +2 -2
  85. package/dist/esm/model/nodes/HttpCallNode.js +44 -75
  86. package/dist/esm/model/nodes/ImageNode.js +44 -3
  87. package/dist/esm/model/nodes/LLMChatV2Node.js +26 -4
  88. package/dist/esm/model/nodes/ObjectNode.js +29 -18
  89. package/dist/esm/model/nodes/PromptNode.js +2 -1
  90. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +4 -1
  91. package/dist/esm/model/nodes/SetGlobalNode.js +5 -3
  92. package/dist/esm/model/nodes/StopWatchingStreamingOutputNode.js +8 -8
  93. package/dist/esm/model/nodes/StreamValueNode.js +38 -0
  94. package/dist/esm/model/nodes/SubGraphNode.js +199 -35
  95. package/dist/esm/model/nodes/ToBase64Node.js +106 -0
  96. package/dist/esm/model/nodes/WatchStreamingOutputNode.js +7 -7
  97. package/dist/esm/model/nodes/toolCallDelegation.js +5 -1
  98. package/dist/esm/model/profileSuspensionHints.js +8 -0
  99. package/dist/esm/recording/ExecutionRecorder.js +26 -0
  100. package/dist/esm/serialization.js +2 -0
  101. package/dist/esm/utils/base64.js +18 -15
  102. package/dist/esm/utils/coerceType.js +11 -1
  103. package/dist/esm/utils/errors.js +41 -0
  104. package/dist/esm/utils/interpolation.js +44 -22
  105. package/dist/esm/utils/interpolationSyntax.js +15 -6
  106. package/dist/esm/utils/serialization/serialization.js +3 -2
  107. package/dist/esm/utils/serialization/serializationUtils.js +6 -0
  108. package/dist/esm/utils/serialization/serialization_v4.js +15 -3
  109. package/dist/esm/webAppRuntime.js +1 -0
  110. package/dist/types/api/createProcessor.d.ts +7 -1
  111. package/dist/types/exports.d.ts +4 -0
  112. package/dist/types/model/AgentResponseTrace.d.ts +15 -4
  113. package/dist/types/model/AgentResponseTracePresentation.d.ts +15 -0
  114. package/dist/types/model/CycleDetector.d.ts +1 -2
  115. package/dist/types/model/DataValue.d.ts +12 -8
  116. package/dist/types/model/ExecutorProtocol.d.ts +9 -0
  117. package/dist/types/model/GraphBoundaryCache.d.ts +2 -0
  118. package/dist/types/model/GraphBoundaryEffects.d.ts +10 -1
  119. package/dist/types/model/GraphExecutionState.d.ts +68 -0
  120. package/dist/types/model/GraphProcessor.d.ts +2 -0
  121. package/dist/types/model/GraphSchedulerBoundaryState.d.ts +96 -0
  122. package/dist/types/model/Nodes.d.ts +11 -4
  123. package/dist/types/model/ProcessContext.d.ts +24 -3
  124. package/dist/types/model/ProjectBundle.d.ts +59 -0
  125. package/dist/types/model/ProjectBundleRuntime.d.ts +24 -0
  126. package/dist/types/model/ProjectReferenceLoader.d.ts +3 -0
  127. package/dist/types/model/RivetUIContext.d.ts +1 -1
  128. package/dist/types/model/SchedulerBoundaryPlanner.d.ts +42 -0
  129. package/dist/types/model/Settings.d.ts +1 -0
  130. package/dist/types/model/StreamingWatchTopology.d.ts +11 -1
  131. package/dist/types/model/SubgraphProjectTarget.d.ts +38 -0
  132. package/dist/types/model/SubprocessorBridge.d.ts +2 -0
  133. package/dist/types/model/chat-v2/chatV2CredentialNames.d.ts +4 -0
  134. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +1 -1
  135. package/dist/types/model/chat-v2/chatV2ProviderRegistry.d.ts +79 -1
  136. package/dist/types/model/chat-v2/chatV2ProviderTypes.d.ts +1 -1
  137. package/dist/types/model/chat-v2/chatV2Shared.d.ts +1 -1
  138. package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +2 -0
  139. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +4 -1
  140. package/dist/types/model/chat-v2/llmChatV2NodeMigration.d.ts +3 -1
  141. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +2 -0
  142. package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +2 -0
  143. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +51 -3
  144. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +10 -7
  145. package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +6 -2
  146. package/dist/types/model/chat-v2/modelRegistry.d.ts +5 -4
  147. package/dist/types/model/chat-v2/openRouterModel.d.ts +2 -0
  148. package/dist/types/model/chat-v2/providerOptions.d.ts +2 -13
  149. package/dist/types/model/chat-v2/temperature.d.ts +2 -0
  150. package/dist/types/model/classifier/credentials.d.ts +7 -1
  151. package/dist/types/model/classifier/images.d.ts +18 -0
  152. package/dist/types/model/classifier/json.d.ts +19 -0
  153. package/dist/types/model/classifier/limits.d.ts +45 -0
  154. package/dist/types/model/classifier/openai.d.ts +5 -0
  155. package/dist/types/model/classifier/perplexity.d.ts +7 -0
  156. package/dist/types/model/classifier/preparation.d.ts +16 -0
  157. package/dist/types/model/classifier/profile.d.ts +46 -0
  158. package/dist/types/model/classifier/profileExecution.d.ts +32 -0
  159. package/dist/types/model/classifier/providers.d.ts +98 -9
  160. package/dist/types/model/classifier/questionHelpers.d.ts +6 -4
  161. package/dist/types/model/classifier/questions.d.ts +4 -0
  162. package/dist/types/model/classifier/response.d.ts +4 -0
  163. package/dist/types/model/classifier/state.d.ts +37 -0
  164. package/dist/types/model/classifier/types.d.ts +11 -0
  165. package/dist/types/model/nodeRunFailure.d.ts +13 -0
  166. package/dist/types/model/nodes/CatchStreamingChunksNode.d.ts +20 -0
  167. package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +17 -12
  168. package/dist/types/model/nodes/ClassifierProfileNode.d.ts +20 -0
  169. package/dist/types/model/nodes/GetGlobalNode.d.ts +7 -0
  170. package/dist/types/model/nodes/ImageNode.d.ts +4 -0
  171. package/dist/types/model/nodes/LLMChatV2Node.d.ts +1 -0
  172. package/dist/types/model/nodes/ObjectNode.d.ts +2 -1
  173. package/dist/types/model/nodes/StreamValueNode.d.ts +14 -0
  174. package/dist/types/model/nodes/SubGraphNode.d.ts +21 -2
  175. package/dist/types/model/nodes/ToBase64Node.d.ts +12 -0
  176. package/dist/types/model/nodes/toolCallDelegation.d.ts +3 -1
  177. package/dist/types/model/profileSuspensionHints.d.ts +8 -0
  178. package/dist/types/recording/ExecutionRecorder.d.ts +8 -2
  179. package/dist/types/serialization.d.ts +2 -0
  180. package/dist/types/utils/base64.d.ts +1 -1
  181. package/dist/types/utils/errors.d.ts +4 -0
  182. package/dist/types/utils/interpolation.d.ts +13 -2
  183. package/dist/types/utils/interpolationSyntax.d.ts +1 -1
  184. package/dist/types/utils/serialization/serialization.d.ts +3 -1
  185. package/dist/types/utils/serialization/serializationUtils.d.ts +1 -0
  186. package/dist/types/webAppRuntime.d.ts +1 -0
  187. package/package.json +7 -1
@@ -1,3 +1,6 @@
1
+ import { GraphInvocationState, GraphSharedExecutionState } from './GraphExecutionState.js';
2
+ import { planStreamingWatchTopology, planAsyncBranchTopology, getAsyncBranchWatchViolation, } from './SchedulerBoundaryPlanner.js';
3
+ import { GraphSchedulerBoundaryState, } from './GraphSchedulerBoundaryState.js';
1
4
  import {} from './DataValue.js';
2
5
  import { IF_PORT, } from './NodeBase.js';
3
6
  import PQueue from '../utils/pQueueCompat.js';
@@ -10,14 +13,14 @@ import { getPluginConfig } from '../utils/index.js';
10
13
  import { isGraphExecutionPlan, preprocessGraphState, toReusableGraphExecutionPlan, } from './GraphPreprocessor.js';
11
14
  import { getGraphBoundary } from './GraphBoundaryCache.js';
12
15
  import { createGraphOutputSelection } from './GraphOutputSelection.js';
13
- import { applyFrozenGraphBoundaryEffects, commitGraphOutputValue, ensureGraphCostOutput, } from './GraphBoundaryEffects.js';
16
+ import { applyFrozenGraphBoundaryEffects, commitGraphOutputValue, ensureGraphCostOutput, addGraphCostBreakdown, readGraphCostBreakdown, graphCostBreakdownMatchesCost, } from './GraphBoundaryEffects.js';
14
17
  import { coerceGraphOutputValue } from './nodes/GraphOutputNode.js';
15
18
  import { replayExecutionRecording } from './RecordingPlayer.js';
16
19
  import { didLoopControllerBreak, LOOP_NOT_BROKEN_SENTINEL } from './loopControllerBreak.js';
17
20
  import { buildNodeProcessContext } from './ProcessContextBuilder.js';
18
21
  import { processSplitRunNode } from './SplitRunProcessor.js';
19
22
  import { getInputNodesTo, getMissingRequiredInputs, getOutputNodesFrom, getStartNodes, getWaitingForInputNode, hasErroredInputNode, } from './NodeExecutionPlanner.js';
20
- import { wireSubprocessorEvents, wireSubprocessorLifecycle } from './SubprocessorBridge.js';
23
+ import { cleanupSubprocessorBindings, wireSubprocessorEvents, wireSubprocessorLifecycle, } from './SubprocessorBridge.js';
21
24
  import { createGraphAbortError, createGraphAbortErrorFromSignal, createGraphAbortReason, getAbortSignalReason, getGraphAbortReasonFromError, getGraphAbortReasonFromSignal, isAbortLikeError, isRaceLoserGraphAbortReason, isSuccessfulNonRaceGraphAbortReason, RACE_LOSER_EXCLUSION_REASON, SUCCESSFUL_GRAPH_ABORT_EXCLUSION_REASON, } from './GraphAbortReasons.js';
22
25
  import { emitDetached } from '../utils/emitDetached.js';
23
26
  import { GraphRunLifecycle } from './GraphRunLifecycle.js';
@@ -42,6 +45,9 @@ import { resolveNodePrefabInstance } from './NodePrefabResolver.js';
42
45
  import { ConnectedToolContinuationHost, } from './ConnectedToolContinuationHost.js';
43
46
  import { resolveProjectGlobalVariables } from './GlobalVariables.js';
44
47
  import { loadProjectReferenceTree } from './ProjectReferenceLoader.js';
48
+ import { getSubgraphProjectKey, isSubgraphProjectKey } from './SubgraphProjectTarget.js';
49
+ import { MAX_CAUGHT_STREAMING_CHUNKS } from './nodes/CatchStreamingChunksNode.js';
50
+ import { isEqual } from 'lodash-es';
45
51
  // eslint-disable-next-line import/no-cycle -- There has to be a cycle because CodeRunner needs to import the entirety of Rivet
46
52
  import { IsomorphicCodeRunner } from '../integrations/CodeRunner.js';
47
53
  const graphProcessorGraphOverride = Symbol('graphProcessorGraphOverride');
@@ -109,6 +115,7 @@ const FAST_ACYCLIC_UNSUPPORTED_NODE_TYPES = new Set([
109
115
  'startBackgroundBranch',
110
116
  'watchStreamingOutput',
111
117
  'stopWatchingStreamingOutput',
118
+ 'catchStreamingChunks',
112
119
  'userInput',
113
120
  'waitForEvent',
114
121
  ]);
@@ -147,6 +154,9 @@ function replaceRecordContents(target, source) {
147
154
  Object.assign(target, source);
148
155
  }
149
156
  export class GraphProcessor {
157
+ #run = new GraphInvocationState();
158
+ #shared = new GraphSharedExecutionState();
159
+ #boundaries = new GraphSchedulerBoundaryState();
150
160
  // Per-instance state
151
161
  #graph;
152
162
  #graphCallPath;
@@ -160,6 +170,7 @@ export class GraphProcessor {
160
170
  #externalFunctions = {};
161
171
  slowMode = false;
162
172
  #parent;
173
+ #recordingProjectScope;
163
174
  #abortOwnerOverride;
164
175
  #sameGraphRunOwnerOverride;
165
176
  #suppressGraphPartialOutputs = false;
@@ -174,19 +185,9 @@ export class GraphProcessor {
174
185
  #asyncBranchPlansByTriggerNodeId = new Map();
175
186
  #consumedAsyncBranchTriggerNodeId;
176
187
  #asyncBranchInputAnchors;
177
- #streamingWatchPlansBySourceNodeId = new Map();
178
- #streamingWatchPlansByWatchNodeId = new Map();
179
- #streamingOutputWatches = new Map();
180
- #graphOutputPartialBindingsBySourceNodeId = new Map();
181
188
  #graphOutputPartialListener;
182
189
  #consumedStreamingWatchNodeId;
183
190
  #streamingWatchInvocation;
184
- #graphInputStreams = {};
185
- #callerInputStreams = new Map();
186
- #inputStreamRoutes = new Map();
187
- #streamCallerTasks = new Set();
188
- #inputStreamDisposers = [];
189
- #pendingGraphInputFinals = new Map();
190
191
  #registry;
191
192
  #concurrency;
192
193
  #executionPlanCacheMode;
@@ -208,63 +209,23 @@ export class GraphProcessor {
208
209
  runFromNodeId;
209
210
  /** The node that is executing this graph, almost always a subgraph node. Undefined for root. */
210
211
  #executor;
211
- #rootRunId = undefined;
212
- #graphRunId = undefined;
213
- #parentGraphRunId = undefined;
214
212
  /** The interval between nodeFinish events when playing back a recording. I.e. how fast the playback is. */
215
213
  recordingPlaybackChatLatency = 1000;
216
214
  warnOnInvalidGraph = false;
217
- // Per-process state
218
- #erroredNodes = undefined; // Values are strings in recordings
219
- #failureOutputsByProcessId = undefined;
220
- #remainingNodes = undefined;
221
- #visitedNodes = undefined;
222
- #currentlyProcessing = undefined;
223
- #context = undefined;
224
- #nodeResults = undefined;
225
- #abortController = undefined;
226
- #processingQueue = undefined;
227
- #graphInputs = undefined;
228
- #graphOutputs = undefined;
229
- #executionCache = undefined;
230
- #queuedNodes = undefined;
231
- /**
232
- * Nodes deferred only because Run To reached its initial scheduler quiescence.
233
- * A streaming Stop can legitimately resume one of those selected paths later.
234
- */
235
- #deferredRunToIgnoredNodes = undefined;
236
- #loopControllersSeen = undefined;
237
- #subprocessors = undefined;
215
+ // Instance configuration and compiled definitions remain outside run state.
238
216
  #contextValues = undefined;
239
- #globals = undefined;
240
217
  /** IDs assigned by the previous root invocation, retained only to reset project globals on reuse. */
241
218
  #projectGlobalVariableIdsAssignedByPreviousRootRun = new Set();
242
219
  /** Snapshot for lifecycle recording, populated only while a root run starts. */
243
220
  #initialProjectGlobalVariablesForRun = new Map();
244
- #storedValueController = undefined;
245
- #knowledgeStoreController = undefined;
246
- #attachedNodeData = undefined;
247
- #successfulAbortTerminalProcessIds = undefined;
248
- #totalCost = 0;
249
- #ignoreNodes = undefined;
250
- #hasPreloadedData = false;
251
- #loadedProjects = undefined;
252
221
  #definitions = undefined;
253
222
  #scc = undefined;
254
223
  #graphExecutionPlan;
255
- #nodeProcessContextBase = undefined;
256
- #runToRelevantNodeIds;
257
- #graphOutputSelection;
258
224
  #managedAsyncBranches;
259
225
  #managedAsyncBranchFailures = [];
260
- #streamingWatchFailures = [];
261
226
  #runCompletionPromise;
262
227
  #nodesNotInCycle = undefined;
263
228
  #executionGraphNodes = undefined;
264
- #nodeAbortControllers = new Map();
265
- #graphInputNodeValues = {};
266
- /** User input nodes that are pending user input. */
267
- #pendingUserInputs = undefined;
268
229
  #unsubscribeTokenizerError;
269
230
  get isRunning() {
270
231
  return this.#lifecycle.isRunning;
@@ -366,7 +327,7 @@ export class GraphProcessor {
366
327
  const preprocessedGraph = preprocessGraphState({
367
328
  inputAnchorDefinitions: this.#asyncBranchInputAnchors,
368
329
  graph: this.#graph,
369
- loadedProjects: this.#loadedProjects,
330
+ loadedProjects: this.#run.loadedProjects,
370
331
  project: this.#project,
371
332
  registry: this.#registry,
372
333
  warnOnInvalidGraph: this.warnOnInvalidGraph,
@@ -402,6 +363,14 @@ export class GraphProcessor {
402
363
  if (!this.#cacheLoadedProjects && (project.references?.length ?? 0) > 0) {
403
364
  return false;
404
365
  }
366
+ // A target's Saved latest or Published pointer can change while the caller
367
+ // graph object remains identical. Its boundary definitions must be rebuilt.
368
+ if (Object.values(project.graphs).some((graph) => graph.nodes.some((authored) => {
369
+ const node = resolveNodePrefabInstance(project, authored);
370
+ return node.type === 'subGraph' && node.data.targetProjectId;
371
+ }))) {
372
+ return false;
373
+ }
405
374
  return true;
406
375
  }
407
376
  #getGraphBoundary(project, graphId) {
@@ -422,11 +391,13 @@ export class GraphProcessor {
422
391
  this.#scc = preprocessedGraph.stronglyConnectedComponents;
423
392
  this.#nodesNotInCycle = preprocessedGraph.nodesNotInCycle;
424
393
  this.#executionGraphNodes = preprocessedGraph.graphNodes;
425
- this.#remainingNodes = new Set(this.#executionGraphNodes.map((node) => node.id));
394
+ this.#run.remainingNodes = new Set(this.#executionGraphNodes.map((node) => node.id));
426
395
  this.#graphExecutionPlan = isGraphExecutionPlan(preprocessedGraph) ? preprocessedGraph : undefined;
427
396
  }
428
397
  #seededExecutionPlanForNextRun() {
429
- if (!this.#useSeededExecutionPlanOnNextRun || this.warnOnInvalidGraph) {
398
+ if (!this.#useSeededExecutionPlanOnNextRun ||
399
+ this.warnOnInvalidGraph ||
400
+ !this.#canUseRuntimeExecutionPlanCacheFor(this.#project, this.#isSubProcessor)) {
430
401
  return undefined;
431
402
  }
432
403
  return this.#graphExecutionPlan;
@@ -445,10 +416,12 @@ export class GraphProcessor {
445
416
  }
446
417
  #buildExecutionMetadata() {
447
418
  return {
448
- rootRunId: this.#rootRunId,
449
- graphRunId: this.#graphRunId,
419
+ rootRunId: this.#run.rootRunId,
420
+ graphRunId: this.#run.graphRunId,
450
421
  graphId: this.#graph.metadata.id,
451
- parentGraphRunId: this.#parentGraphRunId,
422
+ projectId: this.#project.metadata.id,
423
+ ...(this.#recordingProjectScope ? { projectScope: this.#recordingProjectScope } : {}),
424
+ parentGraphRunId: this.#run.parentGraphRunId,
452
425
  executor: this.#executor
453
426
  ? {
454
427
  nodeId: this.#executor.nodeId,
@@ -457,9 +430,12 @@ export class GraphProcessor {
457
430
  splitIndex: this.#executor.index,
458
431
  }
459
432
  : undefined,
460
- ...(this.#context?.evaluation === undefined ? {} : { evaluation: this.#context.evaluation }),
433
+ ...(this.#run.context?.evaluation === undefined ? {} : { evaluation: this.#run.context.evaluation }),
461
434
  };
462
435
  }
436
+ get recordingProjectScope() {
437
+ return this.#recordingProjectScope;
438
+ }
463
439
  #withExecution(data, execution = this.#buildExecutionMetadata()) {
464
440
  return {
465
441
  ...data,
@@ -488,11 +464,11 @@ export class GraphProcessor {
488
464
  }
489
465
  }
490
466
  userInput(nodeId, values) {
491
- const pending = this.#pendingUserInputs[nodeId];
467
+ const pending = this.#run.pendingUserInputs[nodeId];
492
468
  if (pending) {
493
469
  pending.resolve(values);
494
470
  }
495
- for (const processor of this.#subprocessors) {
471
+ for (const processor of this.#run.subprocessors) {
496
472
  processor.userInput(nodeId, values);
497
473
  }
498
474
  }
@@ -516,7 +492,7 @@ export class GraphProcessor {
516
492
  return Promise.resolve();
517
493
  }
518
494
  const abortReason = createGraphAbortReason(successful, error);
519
- this.#abortController.abort(abortReason);
495
+ this.#run.abortController.abort(abortReason);
520
496
  this.#abortActiveNodeControllers(abortReason);
521
497
  this.#cancelStreamingOutputWatches();
522
498
  if (!this.#suppressGraphLifecycleEvents) {
@@ -525,7 +501,7 @@ export class GraphProcessor {
525
501
  emitDetached(this.#emitter, 'abort', { successful, error });
526
502
  }
527
503
  }
528
- await this.#processingQueue.onIdle();
504
+ await this.#run.processingQueue.onIdle();
529
505
  if (!this.#isSubProcessor) {
530
506
  await this.#managedAsyncBranches?.drain();
531
507
  }
@@ -548,7 +524,7 @@ export class GraphProcessor {
548
524
  if (!this.#lifecycle.isPaused) {
549
525
  return;
550
526
  }
551
- if (this.#abortController.signal.aborted) {
527
+ if (this.#run.abortController.signal.aborted) {
552
528
  throw this.#lifecycle.getAbortError();
553
529
  }
554
530
  await new Promise((resolve, reject) => {
@@ -561,10 +537,10 @@ export class GraphProcessor {
561
537
  resolve();
562
538
  });
563
539
  const cleanup = () => {
564
- this.#abortController.signal.removeEventListener('abort', abortListener);
540
+ this.#run.abortController.signal.removeEventListener('abort', abortListener);
565
541
  unsubscribeResume();
566
542
  };
567
- this.#abortController.signal.addEventListener('abort', abortListener, { once: true });
543
+ this.#run.abortController.signal.addEventListener('abort', abortListener, { once: true });
568
544
  });
569
545
  }
570
546
  async *events() {
@@ -593,12 +569,12 @@ export class GraphProcessor {
593
569
  }
594
570
  this.#assertStreamingOutputWatchPreloadCanBeAdded(nodeId);
595
571
  this.#preloadedNodeResults.set(nodeId, data);
596
- this.#hasPreloadedData = true;
572
+ this.#run.hasPreloadedData = true;
597
573
  // Preserve the historical ability to preload an idle processor as well as
598
574
  // inject a boundary into a run that has already initialized.
599
575
  if (this.#lifecycle.isRunning && this.#isNodeSelected(nodeId)) {
600
- this.#nodeResults.set(nodeId, data);
601
- this.#visitedNodes.add(nodeId);
576
+ this.#run.nodeResults.set(nodeId, data);
577
+ this.#run.visitedNodes.add(nodeId);
602
578
  }
603
579
  }
604
580
  setFrozenNodeOutputResolver(resolver) {
@@ -619,7 +595,7 @@ export class GraphProcessor {
619
595
  if (this.#definitions != null) {
620
596
  return;
621
597
  }
622
- this.#loadedProjects ??= {};
598
+ this.#run.loadedProjects ??= {};
623
599
  // This synchronous inspection API can be called before processGraph has
624
600
  // loaded references. Its provisional definitions must never be reused as
625
601
  // a runtime plan for a later fully loaded invocation.
@@ -657,13 +633,13 @@ export class GraphProcessor {
657
633
  this.#initProcessState();
658
634
  return await replayExecutionRecording({
659
635
  emitter: this.#emitter,
660
- erroredNodes: this.#erroredNodes,
661
- graphInputs: this.#graphInputs,
662
- graphOutputs: this.#graphOutputs,
636
+ erroredNodes: this.#run.erroredNodes,
637
+ graphInputs: this.#run.graphInputs,
638
+ graphOutputs: this.#run.graphOutputs,
663
639
  fallbackGraphId: this.#graph.metadata.id,
664
640
  initialReplayExecution: this.#buildExecutionMetadata(),
665
641
  isAborted: () => this.#lifecycle.isAborted,
666
- nodeResults: this.#nodeResults,
642
+ nodeResults: this.#run.nodeResults,
667
643
  project: this.#project,
668
644
  recorder,
669
645
  recordingPlaybackChatLatency: this.recordingPlaybackChatLatency,
@@ -671,76 +647,57 @@ export class GraphProcessor {
671
647
  this.#contextValues = contextValues;
672
648
  },
673
649
  setGraphInputs: (graphInputs) => {
674
- this.#graphInputs = graphInputs;
650
+ this.#run.graphInputs = graphInputs;
675
651
  },
676
652
  setGraphOutputs: (graphOutputs) => {
677
- this.#graphOutputs = graphOutputs;
653
+ this.#run.graphOutputs = graphOutputs;
678
654
  },
679
655
  setRunning: (running) => {
680
656
  if (!running)
681
657
  this.#lifecycle.complete();
682
658
  },
683
- visitedNodes: this.#visitedNodes,
659
+ visitedNodes: this.#run.visitedNodes,
684
660
  waitUntilUnpaused: () => this.#waitUntilUnpaused(),
685
661
  });
686
662
  }
687
663
  #initProcessState() {
688
664
  this.#lifecycle.begin();
689
- this.#nodeResults = new Map(this.#preloadedNodeResults);
690
- this.#visitedNodes = new Set(this.#preloadedNodeResults.keys());
691
- this.#hasPreloadedData = this.#preloadedNodeResults.size > 0;
692
- this.#erroredNodes = new Map();
693
- this.#failureOutputsByProcessId = new Map();
694
- this.#currentlyProcessing = new Set();
665
+ // Retain the invocation owner; child events and async cost accounting use it.
666
+ if (!this.#isSubProcessor)
667
+ this.#shared = this.#shared.nextRootRun();
695
668
  // A processor may be constructed with a reusable execution plan. In that
696
669
  // case preprocessing happened before this run, so retain the compiled
697
670
  // execution-node set rather than restoring the authored graph nodes (which
698
671
  // may include topology-only Data Bus nodes).
699
- this.#remainingNodes = new Set(this.#seededExecutionPlanForNextRun()?.nodeIds ?? []);
700
- this.#pendingUserInputs = {};
701
- this.#processingQueue = new PQueue({ concurrency: this.#concurrency.nodeConcurrency });
702
- this.#graphOutputs = this.#sharedRunStateOverride?.graphOutputs ?? {};
703
- this.#executionCache ??= new Map();
704
- this.#queuedNodes = new Set();
705
- this.#deferredRunToIgnoredNodes = new Set();
672
+ this.#run.initialize({
673
+ preloadedNodeResults: this.#preloadedNodeResults,
674
+ remainingNodeIds: this.#seededExecutionPlanForNextRun()?.nodeIds ?? [],
675
+ processingQueue: new PQueue({ concurrency: this.#concurrency.nodeConcurrency }),
676
+ createAbortController: () => this.#newAbortController(),
677
+ loadedProjects: this.#cacheLoadedProjects && this.#runtimeCache?.loadedProjects ? { ...this.#runtimeCache.loadedProjects } : {},
678
+ sharedOverride: this.#sharedRunStateOverride,
679
+ });
680
+ this.#shared.executionCache ??= new Map();
706
681
  this.#connectedToolContinuationHost.reset();
707
682
  this.#continuationCompletionOwnerByNodeId = new Map();
708
683
  this.#effectiveConnectionsForRun = undefined;
709
684
  this.#asyncBranchPlansByTriggerNodeId = new Map();
710
- this.#streamingWatchPlansBySourceNodeId = new Map();
711
- this.#streamingWatchPlansByWatchNodeId = new Map();
712
- this.#streamingOutputWatches = new Map();
713
- this.#graphOutputPartialBindingsBySourceNodeId = new Map();
714
- this.#loopControllersSeen = new Set();
715
- this.#subprocessors = new Set();
716
- this.#attachedNodeData = this.#sharedRunStateOverride?.attachedNodeData ?? new Map();
717
- this.#globals ??= new Map();
685
+ this.#boundaries.resetTopology();
686
+ this.#shared.globals ??= new Map();
718
687
  if (!this.#isSubProcessor) {
719
- this.#storedValueController = new RivetStoredValueController(this.#storedValueStore);
720
- this.#knowledgeStoreController = new KnowledgeStoreController(this.#knowledgeStores);
688
+ this.#shared.storedValueController = new RivetStoredValueController(this.#storedValueStore);
689
+ this.#shared.knowledgeStoreController = new KnowledgeStoreController(this.#knowledgeStores);
721
690
  }
722
- this.#ignoreNodes = new Set();
723
- this.#nodeProcessContextBase = undefined;
724
- this.#runToRelevantNodeIds = undefined;
725
- this.#graphOutputSelection = undefined;
726
691
  if (!this.#isSubProcessor) {
727
692
  this.#managedAsyncBranches = new ManagedAsyncBranches();
728
693
  this.#managedAsyncBranchFailures = [];
729
694
  }
730
- this.#streamingWatchFailures = [];
731
- this.#abortController = this.#newAbortController();
732
- this.#successfulAbortTerminalProcessIds = new Set();
733
- this.#totalCost = 0;
734
- this.#nodeAbortControllers = new Map();
735
- this.#loadedProjects =
736
- this.#cacheLoadedProjects && this.#runtimeCache?.loadedProjects ? { ...this.#runtimeCache.loadedProjects } : {};
737
695
  // Referenced projects can be reloaded per run when loaded-project caching is disabled.
738
696
  if (!this.#cacheLoadedProjects && (this.#project.references?.length ?? 0) > 0) {
739
697
  if (this.#runtimeCache) {
740
698
  this.#runtimeCache.graphBoundaries = undefined;
741
699
  }
742
700
  }
743
- this.#graphInputNodeValues = this.#sharedRunStateOverride?.graphInputNodeValues ?? {};
744
701
  }
745
702
  /** Main function for running a graph. Runs a graph and returns the outputs from the output nodes of the graph. */
746
703
  async processGraph(
@@ -768,12 +725,7 @@ export class GraphProcessor {
768
725
  try {
769
726
  try {
770
727
  this.#profileRuntimeSync('initializeGraphRun', () => this.#initializeGraphRun(context, inputs, contextValues));
771
- this.#graphInputStreams = options.graphInputStreams ?? {};
772
- this.#callerInputStreams = new Map();
773
- this.#inputStreamRoutes = new Map();
774
- this.#streamCallerTasks = new Set();
775
- this.#inputStreamDisposers = [];
776
- this.#pendingGraphInputFinals = new Map();
728
+ this.#boundaries.initializeInputStreams(options.graphInputStreams);
777
729
  await this.#profileRuntimeAsync('loadProjectReferences', () => this.#loadProjectReferences());
778
730
  this.#profileRuntimeSync('initializeProjectGlobalVariables', () => this.#initializeProjectGlobalVariablesForRootRun());
779
731
  this.#profileRuntimeSync('prepareNodeProcessContextBase', () => this.#prepareNodeProcessContextBase());
@@ -787,16 +739,17 @@ export class GraphProcessor {
787
739
  if (this.runToNodeIds !== undefined) {
788
740
  throw new Error('requestedGraphOutputIds cannot be combined with runToNodeIds');
789
741
  }
790
- this.#graphOutputSelection = createGraphOutputSelection({ nodes: this.#executionGraphNodes, connections: this.#getEffectiveConnections() }, requestedGraphOutputIds, (node) => getInputNodesTo(this.#executionState, node));
791
- for (const nodeId of this.#nodeResults.keys()) {
742
+ this.#run.graphOutputSelection = createGraphOutputSelection({ nodes: this.#executionGraphNodes, connections: this.#getEffectiveConnections() }, requestedGraphOutputIds, (node) => getInputNodesTo(this.#executionState, node));
743
+ for (const nodeId of this.#run.nodeResults.keys()) {
792
744
  if (!this.#isNodeSelected(nodeId)) {
793
- this.#nodeResults.delete(nodeId);
794
- this.#visitedNodes.delete(nodeId);
745
+ this.#run.nodeResults.delete(nodeId);
746
+ this.#run.visitedNodes.delete(nodeId);
795
747
  }
796
748
  }
797
749
  }
798
750
  this.#prepareAsyncBranchTopology();
799
751
  this.#prepareStreamingWatchTopology();
752
+ this.#prepareStreamingCatchTopology();
800
753
  this.#prepareGraphOutputPartialTopology();
801
754
  this.#prepareGraphInputStreamRoutes();
802
755
  }
@@ -824,8 +777,8 @@ export class GraphProcessor {
824
777
  // Publish a snapshot instead of the live root output object. In particular,
825
778
  // the provisional cost must not occupy the root cost port before managed
826
779
  // async branches contribute their cost during finalization.
827
- const outputsReady = { ...this.#graphOutputs };
828
- ensureGraphCostOutput(outputsReady, this.#totalCost);
780
+ const outputsReady = { ...this.#run.graphOutputs };
781
+ ensureGraphCostOutput(outputsReady, this.#run.totalCost, this.#run.costBreakdown);
829
782
  await this.#emitter.emit('graphOutputsReady', this.#withExecution({ graph: this.#graph, outputs: outputsReady }));
830
783
  outputsWerePublishedEarly = true;
831
784
  resolveOutputsReady?.(outputsReady);
@@ -835,18 +788,20 @@ export class GraphProcessor {
835
788
  return await this.#profileRuntimeAsync('finalizeGraphRun', () => this.#finalizeGraphRun());
836
789
  }
837
790
  finally {
838
- for (const dispose of this.#inputStreamDisposers)
839
- dispose();
840
- this.#pendingGraphInputFinals.clear();
841
- for (const streams of this.#callerInputStreams.values()) {
842
- for (const relay of Object.values(streams))
843
- relay.finish({ error: new Error('Graph input stream owner finished') });
791
+ try {
792
+ try {
793
+ this.#boundaries.releaseInputStreams();
794
+ }
795
+ finally {
796
+ await this.#drainSchedulerBoundaries();
797
+ }
798
+ }
799
+ finally {
800
+ this.#graphOutputPartialListener = undefined;
801
+ this.#lifecycle.complete();
802
+ this.#cleanupTokenizerErrorListener();
803
+ await this.#profileRuntimeAsync('emitFinish', () => this.#emitFinishIfNeeded());
844
804
  }
845
- await this.#drainSchedulerBoundaries();
846
- this.#graphOutputPartialListener = undefined;
847
- this.#lifecycle.complete();
848
- this.#cleanupTokenizerErrorListener();
849
- await this.#profileRuntimeAsync('emitFinish', () => this.#emitFinishIfNeeded());
850
805
  }
851
806
  })();
852
807
  this.#runCompletionPromise = completionPromise;
@@ -874,11 +829,11 @@ export class GraphProcessor {
874
829
  #initializeGraphRun(context, inputs, contextValues) {
875
830
  this.#initializeExecutionIdentity();
876
831
  this.#initProcessState();
877
- this.#context = context;
878
- this.#graphInputs = inputs;
832
+ this.#run.context = context;
833
+ this.#run.graphInputs = inputs;
879
834
  this.#contextValues = contextValues;
880
835
  this.#cleanupTokenizerErrorListener();
881
- const unsubscribeTokenizerError = this.#context.tokenizer.on('error', (error) => {
836
+ const unsubscribeTokenizerError = this.#run.context.tokenizer.on('error', (error) => {
882
837
  emitDetached(this.#emitter, 'error', { error });
883
838
  });
884
839
  this.#unsubscribeTokenizerError =
@@ -890,26 +845,27 @@ export class GraphProcessor {
890
845
  return;
891
846
  // Resolve before touching the shared map. An invalid reference or definition
892
847
  // must fail startup without leaving a partial new set of authored globals.
893
- const resolved = resolveProjectGlobalVariables(this.#project, this.#loadedProjects);
848
+ const legacyProjects = Object.fromEntries(Object.entries(this.#run.loadedProjects).filter(([key]) => !isSubgraphProjectKey(key)));
849
+ const resolved = resolveProjectGlobalVariables(this.#project, legacyProjects);
894
850
  for (const id of this.#projectGlobalVariableIdsAssignedByPreviousRootRun) {
895
- this.#globals.delete(id);
851
+ this.#shared.globals.delete(id);
896
852
  }
897
853
  for (const [id, value] of resolved) {
898
- this.#globals.set(id, value);
854
+ this.#shared.globals.set(id, value);
899
855
  }
900
856
  this.#projectGlobalVariableIdsAssignedByPreviousRootRun = new Set(resolved.keys());
901
857
  this.#initialProjectGlobalVariablesForRun = resolved;
902
858
  }
903
859
  #initializeExecutionIdentity() {
904
860
  if (this.#executionIdentityOverride) {
905
- this.#rootRunId = this.#executionIdentityOverride.rootRunId;
906
- this.#graphRunId = this.#executionIdentityOverride.graphRunId;
907
- this.#parentGraphRunId = this.#executionIdentityOverride.parentGraphRunId;
861
+ this.#run.rootRunId = this.#executionIdentityOverride.rootRunId;
862
+ this.#run.graphRunId = this.#executionIdentityOverride.graphRunId;
863
+ this.#run.parentGraphRunId = this.#executionIdentityOverride.parentGraphRunId;
908
864
  }
909
865
  else {
910
- this.#rootRunId = this.#parent ? this.#parent.#rootRunId : nanoid();
911
- this.#graphRunId = nanoid();
912
- this.#parentGraphRunId = this.#parent ? this.#parent.#graphRunId : undefined;
866
+ this.#run.rootRunId = this.#parent ? this.#parent.#run.rootRunId : nanoid();
867
+ this.#run.graphRunId = nanoid();
868
+ this.#run.parentGraphRunId = this.#parent ? this.#parent.#run.graphRunId : undefined;
913
869
  }
914
870
  }
915
871
  async #emitRootStartupError(error) {
@@ -928,26 +884,26 @@ export class GraphProcessor {
928
884
  // is already a GraphProcessor wrapper. Always resolve the original host
929
885
  // observer from the root run so nested LLM calls are not emitted once by
930
886
  // every ancestor before their own event is bridged to the root emitter.
931
- const hostChatV2Observer = this.getRootProcessor().#context.onChatV2CallFinished;
932
- const hostLLMChatOutputSnapshotObserver = this.getRootProcessor().#context.onLLMChatOutputSnapshot;
933
- const hostLLMProfileAttemptObserver = this.getRootProcessor().#context.onLLMProfileAttempt;
934
- this.#nodeProcessContextBase = {
935
- ...this.#context,
887
+ const hostChatV2Observer = this.getRootProcessor().#run.context.onChatV2CallFinished;
888
+ const hostLLMChatOutputSnapshotObserver = this.getRootProcessor().#run.context.onLLMChatOutputSnapshot;
889
+ const hostLLMProfileAttemptObserver = this.getRootProcessor().#run.context.onLLMProfileAttempt;
890
+ this.#run.nodeProcessContextBase = {
891
+ ...this.#run.context,
936
892
  abortGraph: (error) => {
937
893
  void (this.#abortOwnerOverride ?? this).abort(error === undefined, error);
938
894
  },
939
- codeRunner: this.#context.codeRunner ?? DEFAULT_ISOMORPHIC_CODE_RUNNER,
895
+ codeRunner: this.#run.context.codeRunner ?? DEFAULT_ISOMORPHIC_CODE_RUNNER,
940
896
  contextValues: this.#contextValues,
941
- executionCache: this.#executionCache,
897
+ executionCache: this.#shared.executionCache,
942
898
  executor: this.executor ?? 'nodejs',
943
- getGlobal: (id) => this.#globals.get(id),
944
- getCachedStoredValue: (key) => this.#storedValueController.getCached(key),
945
- getStoredValue: (key) => this.#storedValueController.get(key),
946
- getKnowledgeStore: (connectionId) => this.#knowledgeStoreController.resolve(connectionId, this.#nodeProcessContextBase),
899
+ getGlobal: (id) => this.#shared.globals.get(id),
900
+ getCachedStoredValue: (key) => this.#shared.storedValueController.getCached(key),
901
+ getStoredValue: (key) => this.#shared.storedValueController.get(key),
902
+ getKnowledgeStore: (connectionId) => this.#shared.knowledgeStoreController.resolve(connectionId, this.#run.nodeProcessContextBase),
947
903
  getGraphBoundary: (project, graphId) => this.#getGraphBoundary(project, graphId),
948
- graphInputNodeValues: this.#graphInputNodeValues,
949
- graphInputs: this.#graphInputs,
950
- graphOutputs: this.#graphOutputs,
904
+ graphInputNodeValues: this.#run.graphInputNodeValues,
905
+ graphInputs: this.#run.graphInputs,
906
+ graphOutputs: this.#run.graphOutputs,
951
907
  graphCallPath: this.#graphCallPath,
952
908
  onChatV2CallFinished: (event) => {
953
909
  try {
@@ -997,18 +953,18 @@ export class GraphProcessor {
997
953
  raiseEvent: (event, data) => {
998
954
  this.getRootProcessor().raiseEvent(event, data);
999
955
  },
1000
- referencedProjects: this.#loadedProjects,
956
+ referencedProjects: this.#run.loadedProjects,
1001
957
  tokenizer: this.#getTokenizer(),
1002
958
  trace: (message) => {
1003
959
  this.#emitTraceEvent(message);
1004
960
  },
1005
- setStoredValue: (key, value) => this.#storedValueController.set(key, value),
1006
- waitForGlobal: async (id, signal = this.#abortController.signal) => {
961
+ setStoredValue: (key, value) => this.#shared.storedValueController.set(key, value),
962
+ waitForGlobal: async (id, signal = this.#run.abortController.signal) => {
1007
963
  if (signal.aborted) {
1008
964
  throw createGraphAbortErrorFromSignal(signal);
1009
965
  }
1010
- if (this.#globals.has(id)) {
1011
- return this.#globals.get(id);
966
+ if (this.#shared.globals.has(id)) {
967
+ return this.#shared.globals.get(id);
1012
968
  }
1013
969
  return await new Promise((resolve, reject) => {
1014
970
  const abortListener = () => {
@@ -1017,7 +973,7 @@ export class GraphProcessor {
1017
973
  };
1018
974
  const unsubscribe = this.getRootProcessor().#emitter.on(`globalSet:${id}`, () => {
1019
975
  cleanup();
1020
- resolve(this.#globals.get(id));
976
+ resolve(this.#shared.globals.get(id));
1021
977
  });
1022
978
  const cleanup = () => {
1023
979
  unsubscribe();
@@ -1029,7 +985,7 @@ export class GraphProcessor {
1029
985
  }
1030
986
  });
1031
987
  },
1032
- waitForStoredValue: (key, signal) => this.#storedValueController.waitForSet(key, signal),
988
+ waitForStoredValue: (key, signal) => this.#shared.storedValueController.waitForSet(key, signal),
1033
989
  };
1034
990
  }
1035
991
  #cleanupTokenizerErrorListener() {
@@ -1049,12 +1005,12 @@ export class GraphProcessor {
1049
1005
  if (!this.#isSubProcessor) {
1050
1006
  await this.#emitter.emit('start', this.#withExecution({
1051
1007
  contextValues: this.#contextValues,
1052
- inputs: this.#graphInputs,
1008
+ inputs: this.#run.graphInputs,
1053
1009
  project: this.#project,
1054
1010
  startGraph: this.#graph,
1055
1011
  }));
1056
1012
  }
1057
- await this.#emitter.emit('graphStart', this.#withExecution({ graph: this.#graph, inputs: this.#graphInputs }));
1013
+ await this.#emitter.emit('graphStart', this.#withExecution({ graph: this.#graph, inputs: this.#run.graphInputs }));
1058
1014
  }
1059
1015
  async #emitInitialProjectGlobalVariables() {
1060
1016
  if (this.#isSubProcessor || this.#suppressGraphLifecycleEvents)
@@ -1064,17 +1020,17 @@ export class GraphProcessor {
1064
1020
  }
1065
1021
  }
1066
1022
  async #emitPreloadedNodeResults() {
1067
- if (!this.#hasPreloadedData) {
1023
+ if (!this.#run.hasPreloadedData) {
1068
1024
  return;
1069
1025
  }
1070
1026
  for (const node of this.#executionGraphNodes) {
1071
- if (!this.#isNodeSelected(node.id) || !this.#nodeResults.has(node.id)) {
1027
+ if (!this.#isNodeSelected(node.id) || !this.#run.nodeResults.has(node.id)) {
1072
1028
  continue;
1073
1029
  }
1074
1030
  if (this.#suppressedPreloadedNodeIds.has(node.id)) {
1075
1031
  continue;
1076
1032
  }
1077
- const outputs = this.#nodeResults.get(node.id);
1033
+ const outputs = this.#run.nodeResults.get(node.id);
1078
1034
  // A preloaded producer is complete evidence, not a reconstructed token
1079
1035
  // stream. Watch receives it once as the producer's final snapshot.
1080
1036
  this.#assertStreamingOutputWatchFinalOutputs(node, outputs);
@@ -1096,56 +1052,57 @@ export class GraphProcessor {
1096
1052
  }
1097
1053
  async #queueStartNodes(startNodes) {
1098
1054
  for (const startNode of startNodes) {
1099
- void this.#processingQueue.add(async () => {
1055
+ void this.#run.processingQueue.add(async () => {
1100
1056
  await this.#fetchNodeDataAndProcessNode(startNode);
1101
1057
  });
1102
1058
  }
1103
1059
  }
1104
1060
  async #processCompatibleGraph() {
1105
- await this.#queueStartNodes(this.#graphOutputSelection?.startNodes ??
1061
+ await this.#queueStartNodes(this.#run.graphOutputSelection?.startNodes ??
1106
1062
  getStartNodes(this.#executionState, this.#executionGraphNodes, this.runToNodeIds));
1107
- await this.#processingQueue.onIdle();
1108
- if (Object.keys(this.#graphInputStreams).length) {
1063
+ await this.#run.processingQueue.onIdle();
1064
+ if (Object.keys(this.#boundaries.graphInputStreams).length) {
1109
1065
  await this.#waitForGraphInputStreams();
1110
- for (const [nodeId, outputs] of this.#pendingGraphInputFinals) {
1066
+ for (const [nodeId, outputs] of this.#boundaries.pendingGraphInputFinals) {
1111
1067
  this.#finishStreamingOutputWatches(this.#nodesById[nodeId], outputs);
1112
1068
  }
1113
- this.#pendingGraphInputFinals.clear();
1069
+ this.#boundaries.pendingGraphInputFinals.clear();
1114
1070
  for (const node of this.#executionGraphNodes) {
1115
1071
  if (!this.#isNodeSelected(node.id))
1116
1072
  continue;
1117
- void this.#processingQueue.add(() => this.#processNodeIfAllInputsAvailable(node));
1073
+ void this.#run.processingQueue.add(() => this.#processNodeIfAllInputsAvailable(node));
1118
1074
  }
1119
- await this.#processingQueue.onIdle();
1075
+ await this.#run.processingQueue.onIdle();
1120
1076
  }
1121
- while (this.#streamCallerTasks.size) {
1077
+ while (this.#boundaries.streamCallerTasks.size) {
1122
1078
  // A producer skipped transitively after an upstream failure never emits
1123
1079
  // nodeError itself. Settle its consumers once ordinary work is quiescent.
1124
- for (const [sourceId, routes] of this.#inputStreamRoutes) {
1125
- if (this.#currentlyProcessing.has(sourceId) || routes.every(({ relay }) => relay.result))
1080
+ for (const [sourceId, routes] of this.#boundaries.inputStreamRoutes) {
1081
+ if (this.#run.currentlyProcessing.has(sourceId) || routes.every(({ relay }) => relay.result))
1126
1082
  continue;
1127
- const failedDependency = this.getDependencyNodesDeep(sourceId).find((id) => this.#erroredNodes.has(id));
1083
+ const failedDependency = this.getDependencyNodesDeep(sourceId).find((id) => this.#run.erroredNodes.has(id));
1128
1084
  if (failedDependency) {
1129
- const error = getError(this.#erroredNodes.get(failedDependency));
1085
+ const error = getError(this.#run.erroredNodes.get(failedDependency));
1130
1086
  for (const { relay } of routes)
1131
1087
  relay.finish({ error });
1132
1088
  }
1133
1089
  }
1134
1090
  // Recheck skipped producers after each caller settles; another caller may
1135
1091
  // depend on ordinary nodes skipped because this caller failed.
1136
- await Promise.race(this.#streamCallerTasks);
1137
- await this.#processingQueue.onIdle();
1092
+ await Promise.race(this.#boundaries.streamCallerTasks);
1093
+ await this.#run.processingQueue.onIdle();
1138
1094
  }
1095
+ await this.#drainStreamingCatchTasks();
1139
1096
  this.#markUnqueuedNodesIgnored();
1140
1097
  }
1141
1098
  #canUseFastAcyclicScheduler() {
1142
1099
  if (this.#scheduler !== 'fast-acyclic') {
1143
1100
  return false;
1144
1101
  }
1145
- if (this.#graphOutputSelection ||
1146
- this.#callerInputStreams.size > 0 ||
1147
- Object.keys(this.#graphInputStreams).length > 0 ||
1148
- this.#hasPreloadedData ||
1102
+ if (this.#run.graphOutputSelection ||
1103
+ this.#boundaries.callerInputStreams.size > 0 ||
1104
+ Object.keys(this.#boundaries.graphInputStreams).length > 0 ||
1105
+ this.#run.hasPreloadedData ||
1149
1106
  this.runToNodeIds ||
1150
1107
  this.slowMode ||
1151
1108
  this.#includeTrace) {
@@ -1251,14 +1208,14 @@ export class GraphProcessor {
1251
1208
  return;
1252
1209
  }
1253
1210
  for (const node of this.#executionGraphNodes) {
1254
- if (this.#queuedNodes.has(node.id) === false && !this.#ignoreNodes.has(node.id)) {
1255
- this.#ignoreNodes.add(node.id);
1256
- this.#deferredRunToIgnoredNodes.add(node.id);
1211
+ if (this.#run.queuedNodes.has(node.id) === false && !this.#run.ignoreNodes.has(node.id)) {
1212
+ this.#run.ignoreNodes.add(node.id);
1213
+ this.#run.deferredRunToIgnoredNodes.add(node.id);
1257
1214
  }
1258
1215
  }
1259
1216
  }
1260
1217
  #getUnhandledErroredNodes() {
1261
- return [...this.#erroredNodes.entries()].filter(([nodeId]) => {
1218
+ return [...this.#run.erroredNodes.entries()].filter(([nodeId]) => {
1262
1219
  const erroredNodeAttachedData = this.#getAttachedDataTo(nodeId);
1263
1220
  return erroredNodeAttachedData.races == null || erroredNodeAttachedData.races.completed === false;
1264
1221
  });
@@ -1283,7 +1240,7 @@ export class GraphProcessor {
1283
1240
  const erroredNodes = this.#getUnhandledErroredNodes();
1284
1241
  const branchFailures = [
1285
1242
  ...(includeManagedAsyncFailures ? this.#managedAsyncBranchFailures : []),
1286
- ...this.#streamingWatchFailures,
1243
+ ...this.#boundaries.streamingWatchFailures,
1287
1244
  ];
1288
1245
  if (this.#lifecycle.abortSuccessful ||
1289
1246
  (!this.#lifecycle.isAborted && !erroredNodes.length && !branchFailures.length)) {
@@ -1299,11 +1256,11 @@ export class GraphProcessor {
1299
1256
  throw error;
1300
1257
  }
1301
1258
  async #finalizeGraphRun() {
1302
- const outputValues = this.#graphOutputs;
1259
+ const outputValues = this.#run.graphOutputs;
1303
1260
  if (this.#suppressGraphLifecycleEvents) {
1304
1261
  return outputValues;
1305
1262
  }
1306
- ensureGraphCostOutput(this.#graphOutputs, this.#totalCost);
1263
+ ensureGraphCostOutput(this.#run.graphOutputs, this.#run.totalCost, this.#run.costBreakdown);
1307
1264
  await this.#emitter.emit('graphFinish', this.#withExecution({ graph: this.#graph, outputs: outputValues }));
1308
1265
  if (!this.#isSubProcessor) {
1309
1266
  await this.#emitter.emit('done', { results: outputValues });
@@ -1313,15 +1270,98 @@ export class GraphProcessor {
1313
1270
  async #loadProjectReferences() {
1314
1271
  if ((this.#project.references?.length ?? 0) > 0) {
1315
1272
  if (this.#cacheLoadedProjects && this.#runtimeCache?.loadedProjects) {
1316
- this.#loadedProjects = { ...this.#runtimeCache.loadedProjects };
1273
+ this.#run.loadedProjects = { ...this.#runtimeCache.loadedProjects };
1274
+ await this.#loadSubgraphProjectTargets();
1317
1275
  return;
1318
1276
  }
1319
- if (!this.#context.projectReferenceLoader) {
1277
+ if (!this.#run.context.projectReferenceLoader) {
1320
1278
  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.');
1321
1279
  }
1322
- this.#loadedProjects = await loadProjectReferenceTree(this.#project, this.#context.projectPath, this.#context.projectReferenceLoader);
1280
+ this.#run.loadedProjects = await loadProjectReferenceTree(this.#project, this.#run.context.projectPath, this.#run.context.projectReferenceLoader);
1323
1281
  if (this.#cacheLoadedProjects && this.#runtimeCache) {
1324
- this.#runtimeCache.loadedProjects = { ...this.#loadedProjects };
1282
+ this.#runtimeCache.loadedProjects = { ...this.#run.loadedProjects };
1283
+ }
1284
+ }
1285
+ await this.#loadSubgraphProjectTargets();
1286
+ }
1287
+ async #loadSubgraphProjectTargets() {
1288
+ const visited = new WeakMap();
1289
+ const active = new WeakMap();
1290
+ const visit = async (owner, graphId, depth, enteredFromOtherProject = false) => {
1291
+ if (depth > 64)
1292
+ throw new Error('Subgraph project dependency depth exceeds 64. Check for a project cycle.');
1293
+ const graph = owner.graphs[graphId];
1294
+ if (!graph)
1295
+ throw new Error(`Subgraph target graph ${graphId} is missing from project ${owner.metadata.id}.`);
1296
+ if (active.get(owner)?.has(graphId)) {
1297
+ if (enteredFromOtherProject)
1298
+ throw new Error(`Subgraph project dependency cycle reaches graph ${graphId} in project ${owner.metadata.id}.`);
1299
+ return;
1300
+ }
1301
+ const visitedGraphs = visited.get(owner) ?? new Set();
1302
+ if (visitedGraphs.has(graphId))
1303
+ return;
1304
+ visitedGraphs.add(graphId);
1305
+ visited.set(owner, visitedGraphs);
1306
+ const activeGraphs = active.get(owner) ?? new Set();
1307
+ activeGraphs.add(graphId);
1308
+ active.set(owner, activeGraphs);
1309
+ try {
1310
+ for (const authored of graph.nodes) {
1311
+ const candidate = resolveNodePrefabInstance(owner, authored);
1312
+ if (candidate.type !== 'subGraph' || candidate.disabled)
1313
+ continue;
1314
+ const node = candidate;
1315
+ if (node.data.targetScope === 'other-projects' && !node.data.targetProjectId) {
1316
+ throw new Error('Select a project and graph for this Subgraph before running it.');
1317
+ }
1318
+ let childOwner = owner;
1319
+ if (node.data.targetProjectId) {
1320
+ const target = {
1321
+ projectId: node.data.targetProjectId,
1322
+ version: node.data.targetVersion ?? 'latest',
1323
+ };
1324
+ const key = getSubgraphProjectKey(target);
1325
+ let resolved = this.#shared.subgraphTargetCache.get(key);
1326
+ if (!resolved) {
1327
+ if (!this.#run.context.subgraphProjectLoader) {
1328
+ throw new Error('Subgraph calls to another project require a subgraphProjectLoader. Use a project bundle locally or run through Rivet Studio Server.');
1329
+ }
1330
+ resolved = await this.#run.context.subgraphProjectLoader.loadTarget(target);
1331
+ if (resolved.project.metadata.id !== target.projectId) {
1332
+ throw new Error(`Subgraph target ${target.projectId} resolved to a different project.`);
1333
+ }
1334
+ this.#shared.subgraphTargetCache.set(key, resolved);
1335
+ }
1336
+ childOwner = resolved.project;
1337
+ if (Object.hasOwn(this.#run.loadedProjects, key) && this.#run.loadedProjects[key] !== childOwner) {
1338
+ throw new Error('Subgraph target collides with an existing project reference.');
1339
+ }
1340
+ Object.defineProperty(this.#run.loadedProjects, key, {
1341
+ configurable: true,
1342
+ enumerable: true,
1343
+ value: childOwner,
1344
+ writable: true,
1345
+ });
1346
+ }
1347
+ await visit(childOwner, node.data.graphId, depth + 1, Boolean(node.data.targetProjectId));
1348
+ }
1349
+ }
1350
+ finally {
1351
+ activeGraphs.delete(graphId);
1352
+ }
1353
+ };
1354
+ await visit(this.#project, this.#graph.metadata.id, 0);
1355
+ // Streaming topology may visit any resolved target, including a version of
1356
+ // a project with the same metadata ID as another selected target.
1357
+ for (const [key, resolved] of this.#shared.subgraphTargetCache) {
1358
+ if (!Object.hasOwn(this.#run.loadedProjects, key)) {
1359
+ Object.defineProperty(this.#run.loadedProjects, key, {
1360
+ configurable: true,
1361
+ enumerable: true,
1362
+ value: resolved.project,
1363
+ writable: true,
1364
+ });
1325
1365
  }
1326
1366
  }
1327
1367
  }
@@ -1334,9 +1374,40 @@ export class GraphProcessor {
1334
1374
  return getMissingRequiredInputs(this.#executionState, node);
1335
1375
  }
1336
1376
  /** Accumulates cost from a node's output. */
1337
- #accumulateCost(output) {
1338
- if (output['cost']?.type === 'number') {
1339
- this.#totalCost += coerceTypeOptional(output['cost'], 'number') ?? 0;
1377
+ #accumulateCost(output, nodeType) {
1378
+ const carried = readGraphCostBreakdown(output);
1379
+ // Alias metric visibility must not discard the called graph's accounting.
1380
+ const aliasCost = nodeType === 'referencedGraphAlias' && carried ? carried.llm + carried.classifier + carried.other : undefined;
1381
+ const costOutput = output['cost'];
1382
+ if (costOutput?.type === 'number' || aliasCost != null) {
1383
+ const cost = costOutput?.type === 'number' ? costOutput.value : aliasCost;
1384
+ if (typeof cost !== 'number' ||
1385
+ !Number.isFinite(cost) ||
1386
+ cost < 0 ||
1387
+ !Number.isFinite(this.#run.totalCost + cost))
1388
+ return;
1389
+ this.#run.totalCost += cost;
1390
+ const family = nodeType === 'classifierEvaluate'
1391
+ ? 'classifier'
1392
+ : nodeType === 'llmChatV2' || nodeType === 'chat'
1393
+ ? 'llm'
1394
+ : 'other';
1395
+ // Authored metric-named graph outputs retain ownership. Do not attribute
1396
+ // an unrelated cost value using a child's runtime breakdown.
1397
+ const breakdown = carried && graphCostBreakdownMatchesCost(carried, cost)
1398
+ ? carried
1399
+ : { llm: 0, classifier: 0, other: 0, [family]: cost };
1400
+ if (cost !== 0 || family !== 'other' || carried) {
1401
+ this.#run.costBreakdown = addGraphCostBreakdown(this.#run.costBreakdown, breakdown);
1402
+ }
1403
+ }
1404
+ }
1405
+ #accumulateChildCost(processor) {
1406
+ if (!Number.isFinite(this.#run.totalCost + processor.#run.totalCost))
1407
+ return;
1408
+ this.#run.totalCost += processor.#run.totalCost;
1409
+ if (processor.#run.costBreakdown) {
1410
+ this.#run.costBreakdown = addGraphCostBreakdown(this.#run.costBreakdown, processor.#run.costBreakdown);
1340
1411
  }
1341
1412
  }
1342
1413
  async #fetchNodeDataAndProcessNode(node) {
@@ -1344,16 +1415,16 @@ export class GraphProcessor {
1344
1415
  return;
1345
1416
  const profileStart = this.#startRuntimeProfile();
1346
1417
  try {
1347
- if (this.#currentlyProcessing.has(node.id)) {
1418
+ if (this.#run.currentlyProcessing.has(node.id)) {
1348
1419
  return;
1349
1420
  }
1350
1421
  if (this.#propagateCompletedContinuationNode(node, true)) {
1351
1422
  return;
1352
1423
  }
1353
- if (this.#queuedNodes.has(node.id)) {
1424
+ if (this.#run.queuedNodes.has(node.id)) {
1354
1425
  return;
1355
1426
  }
1356
- if (this.#nodeResults.has(node.id) || this.#erroredNodes.has(node.id)) {
1427
+ if (this.#run.nodeResults.has(node.id) || this.#run.erroredNodes.has(node.id)) {
1357
1428
  return;
1358
1429
  }
1359
1430
  const inputNodesProfileStart = this.#startRuntimeProfile();
@@ -1378,8 +1449,8 @@ export class GraphProcessor {
1378
1449
  };
1379
1450
  }
1380
1451
  }
1381
- this.#queuedNodes.add(node.id);
1382
- void this.#processingQueue.addAll(inputNodes.map((inputNode) => {
1452
+ this.#run.queuedNodes.add(node.id);
1453
+ void this.#run.processingQueue.addAll(inputNodes.map((inputNode) => {
1383
1454
  return async () => {
1384
1455
  this.#emitTraceEvent(`Fetching required data for node ${inputNode.title} (${inputNode.id})`);
1385
1456
  await this.#fetchNodeDataAndProcessNode(inputNode);
@@ -1396,10 +1467,10 @@ export class GraphProcessor {
1396
1467
  if (!this.#isNodeSelected(node.id))
1397
1468
  return [];
1398
1469
  // Waiting graph callers must not occupy a queue slot needed by their producer.
1399
- if (this.#callerInputStreams.has(node.id) && !options.streamingDispatch) {
1470
+ if (this.#boundaries.callerInputStreams.has(node.id) && !options.streamingDispatch) {
1400
1471
  const task = this.#processNodeIfAllInputsAvailable(node, { ...options, streamingDispatch: true }).catch((error) => this.#nodeErrored(node, error, nanoid()));
1401
- this.#streamCallerTasks.add(task);
1402
- void task.then(() => this.#streamCallerTasks.delete(task), () => this.#streamCallerTasks.delete(task));
1472
+ this.#boundaries.streamCallerTasks.add(task);
1473
+ void task.then(() => this.#boundaries.streamCallerTasks.delete(task), () => this.#boundaries.streamCallerTasks.delete(task));
1403
1474
  return [];
1404
1475
  }
1405
1476
  const { queueOutputNodes = true } = options;
@@ -1415,11 +1486,11 @@ export class GraphProcessor {
1415
1486
  return [];
1416
1487
  }
1417
1488
  const namedInput = node.type === 'graphInput' ? node.data.id : undefined;
1418
- const inputStream = namedInput != null && Object.hasOwn(this.#graphInputStreams, namedInput)
1419
- ? this.#graphInputStreams[namedInput]
1489
+ const inputStream = namedInput != null && Object.hasOwn(this.#boundaries.graphInputStreams, namedInput)
1490
+ ? this.#boundaries.graphInputStreams[namedInput]
1420
1491
  : undefined;
1421
1492
  if (inputStream) {
1422
- const terminals = Object.values(this.#graphInputStreams).map((stream) => stream.result);
1493
+ const terminals = Object.values(this.#boundaries.graphInputStreams).map((stream) => stream.result);
1423
1494
  // A containing invocation cannot release a successful final into a deeper
1424
1495
  // caller when another required input failed or was excluded.
1425
1496
  const terminal = terminals.find((result) => result?.error) ??
@@ -1441,8 +1512,8 @@ export class GraphProcessor {
1441
1512
  return [];
1442
1513
  }
1443
1514
  else if (node.type !== 'graphInput' &&
1444
- !this.#callerInputStreams.has(node.id) &&
1445
- Object.values(this.#graphInputStreams).some((stream) => !stream.result || stream.result.error || stream.result.value?.type === 'control-flow-excluded')) {
1515
+ !this.#boundaries.callerInputStreams.has(node.id) &&
1516
+ Object.values(this.#boundaries.graphInputStreams).some((stream) => !stream.result || stream.result.error || stream.result.value?.type === 'control-flow-excluded')) {
1446
1517
  // Only streaming boundary plumbing runs early; ordinary side effects wait.
1447
1518
  return [];
1448
1519
  }
@@ -1458,7 +1529,7 @@ export class GraphProcessor {
1458
1529
  this.#emitTraceEvent(`Node ${node.title} is excluded due to control flow`);
1459
1530
  return loopExclusion === true ? [] : loopExclusion;
1460
1531
  }
1461
- const streamedInputs = this.#callerInputStreams.get(node.id);
1532
+ const streamedInputs = this.#boundaries.callerInputStreams.get(node.id);
1462
1533
  const blockingInputNodes = streamedInputs
1463
1534
  ? inputNodes.filter((inputNode) => this.#getInputConnectionsForNode(node).some((edge) => edge.outputNodeId === inputNode.id && !streamedInputs[edge.inputId]))
1464
1535
  : inputNodes;
@@ -1506,9 +1577,9 @@ export class GraphProcessor {
1506
1577
  await new Promise((resolve) => setTimeout(resolve, 250));
1507
1578
  }
1508
1579
  this.#emitTraceEvent(`Finished processing node ${node.title} (${node.id})`);
1509
- this.#visitedNodes.add(node.id);
1510
- this.#currentlyProcessing.delete(node.id);
1511
- this.#remainingNodes.delete(node.id);
1580
+ this.#run.visitedNodes.add(node.id);
1581
+ this.#run.currentlyProcessing.delete(node.id);
1582
+ this.#run.remainingNodes.delete(node.id);
1512
1583
  const outputNodesProfileStart = this.#startRuntimeProfile();
1513
1584
  const outputNodes = getOutputNodesFrom(this.#executionState, node);
1514
1585
  this.#finishRuntimeProfile('getOutputNodesFrom', outputNodesProfileStart);
@@ -1534,7 +1605,7 @@ export class GraphProcessor {
1534
1605
  }
1535
1606
  #propagateCompletedContinuationNode(node, queueOutputNodes) {
1536
1607
  const ownerLLMNodeId = this.#continuationCompletionOwnerByNodeId.get(node.id);
1537
- if (ownerLLMNodeId == null || !this.#nodeResults.has(ownerLLMNodeId)) {
1608
+ if (ownerLLMNodeId == null || !this.#run.nodeResults.has(ownerLLMNodeId)) {
1538
1609
  return undefined;
1539
1610
  }
1540
1611
  this.#continuationCompletionOwnerByNodeId.delete(node.id);
@@ -1548,7 +1619,7 @@ export class GraphProcessor {
1548
1619
  return outputNodes.nodes;
1549
1620
  }
1550
1621
  #shouldSkipNodeProcessing(node, inputNodes) {
1551
- if (this.#ignoreNodes.has(node.id)) {
1622
+ if (this.#run.ignoreNodes.has(node.id)) {
1552
1623
  this.#emitTraceEvent(`Node ${node.title} is ignored`);
1553
1624
  return true;
1554
1625
  }
@@ -1559,15 +1630,15 @@ export class GraphProcessor {
1559
1630
  return true;
1560
1631
  }
1561
1632
  }
1562
- if (this.#currentlyProcessing.has(node.id)) {
1633
+ if (this.#run.currentlyProcessing.has(node.id)) {
1563
1634
  this.#emitTraceEvent(`Node ${node.title} is already being processed`);
1564
1635
  return true;
1565
1636
  }
1566
- if (this.#visitedNodes.has(node.id) && node.type !== 'loopController') {
1637
+ if (this.#run.visitedNodes.has(node.id) && node.type !== 'loopController') {
1567
1638
  this.#emitTraceEvent(`Node ${node.title} has already been processed`);
1568
1639
  return true;
1569
1640
  }
1570
- if (this.#erroredNodes.has(node.id)) {
1641
+ if (this.#run.erroredNodes.has(node.id)) {
1571
1642
  this.#emitTraceEvent(`Node ${node.title} has already errored`);
1572
1643
  return true;
1573
1644
  }
@@ -1586,9 +1657,9 @@ export class GraphProcessor {
1586
1657
  if (this.#shouldSkipCompletedRaceNode(node, attachedData)) {
1587
1658
  return false;
1588
1659
  }
1589
- this.#currentlyProcessing.add(node.id);
1660
+ this.#run.currentlyProcessing.add(node.id);
1590
1661
  if (node.type === 'loopController') {
1591
- this.#loopControllersSeen.add(node.id);
1662
+ this.#run.loopControllersSeen.add(node.id);
1592
1663
  }
1593
1664
  this.#registerNodeInActiveLoop(node, attachedData);
1594
1665
  return true;
@@ -1609,7 +1680,7 @@ export class GraphProcessor {
1609
1680
  if (node.type !== 'loopController') {
1610
1681
  return;
1611
1682
  }
1612
- const loopControllerResults = this.#nodeResults.get(node.id);
1683
+ const loopControllerResults = this.#run.nodeResults.get(node.id);
1613
1684
  const breakValue = loopControllerResults['break'];
1614
1685
  const didBreak = didLoopControllerBreak(breakValue);
1615
1686
  if (didBreak) {
@@ -1619,10 +1690,10 @@ export class GraphProcessor {
1619
1690
  for (const loopNodeId of attachedData.loopInfo?.nodes ?? []) {
1620
1691
  const cycleNode = this.#nodesById[loopNodeId];
1621
1692
  this.#emitTraceEvent(`Clearing cycle node ${cycleNode.title} (${cycleNode.id})`);
1622
- this.#visitedNodes.delete(cycleNode.id);
1623
- this.#currentlyProcessing.delete(cycleNode.id);
1624
- this.#remainingNodes.add(cycleNode.id);
1625
- this.#nodeResults.delete(cycleNode.id);
1693
+ this.#run.visitedNodes.delete(cycleNode.id);
1694
+ this.#run.currentlyProcessing.delete(cycleNode.id);
1695
+ this.#run.remainingNodes.add(cycleNode.id);
1696
+ this.#run.nodeResults.delete(cycleNode.id);
1626
1697
  }
1627
1698
  }
1628
1699
  #handleCompletedRace(node) {
@@ -1630,7 +1701,7 @@ export class GraphProcessor {
1630
1701
  return;
1631
1702
  }
1632
1703
  const raceId = `race-${node.id}`;
1633
- const allNodesForRace = [...this.#attachedNodeData.entries()].filter(([, { races }]) => races?.raceIds.includes(raceId));
1704
+ const allNodesForRace = [...this.#run.attachedNodeData.entries()].filter(([, { races }]) => races?.raceIds.includes(raceId));
1634
1705
  for (const [, nodeAttachedData] of allNodesForRace) {
1635
1706
  if (nodeAttachedData.races?.raceIds.includes(raceId)) {
1636
1707
  nodeAttachedData.races.completed = true;
@@ -1680,22 +1751,22 @@ export class GraphProcessor {
1680
1751
  }
1681
1752
  }
1682
1753
  #queueOutputNodes(node, outputNodes) {
1683
- const selectedOutputs = this.#graphOutputSelection
1754
+ const selectedOutputs = this.#run.graphOutputSelection
1684
1755
  ? outputNodes.filter((outputNode) => this.#isNodeSelected(outputNode.id))
1685
1756
  : outputNodes;
1686
1757
  const relevantNodeIds = this.#getExecutionRelevantNodeIds();
1687
1758
  for (const outputNode of selectedOutputs) {
1688
- if (relevantNodeIds?.has(outputNode.id) && this.#deferredRunToIgnoredNodes.delete(outputNode.id)) {
1689
- this.#ignoreNodes.delete(outputNode.id);
1759
+ if (relevantNodeIds?.has(outputNode.id) && this.#run.deferredRunToIgnoredNodes.delete(outputNode.id)) {
1760
+ this.#run.ignoreNodes.delete(outputNode.id);
1690
1761
  }
1691
1762
  }
1692
- void this.#processingQueue.addAll(selectedOutputs.map((outputNode) => async () => {
1763
+ void this.#run.processingQueue.addAll(selectedOutputs.map((outputNode) => async () => {
1693
1764
  this.#emitTraceEvent(`Trying to run output node from ${node.title}: ${outputNode.title} (${outputNode.id})`);
1694
1765
  await this.#processNodeIfAllInputsAvailable(outputNode);
1695
1766
  }));
1696
1767
  }
1697
1768
  #startManagedAsyncBranch(triggerNode) {
1698
- const outputs = this.#nodeResults.get(triggerNode.id);
1769
+ const outputs = this.#run.nodeResults.get(triggerNode.id);
1699
1770
  if (!outputs) {
1700
1771
  return;
1701
1772
  }
@@ -1736,51 +1807,29 @@ export class GraphProcessor {
1736
1807
  const root = this.getRootProcessor();
1737
1808
  const sameGraphOwner = this.#sameGraphRunOwnerOverride ?? this;
1738
1809
  const isRootGraphOrigin = !sameGraphOwner.#isSubProcessor;
1739
- if (root.#abortController.signal.aborted) {
1740
- throw createGraphAbortErrorFromSignal(root.#abortController.signal, 'Async branch aborted before it started');
1810
+ if (root.#run.abortController.signal.aborted) {
1811
+ throw createGraphAbortErrorFromSignal(root.#run.abortController.signal, 'Async branch aborted before it started');
1741
1812
  }
1742
1813
  const graphId = plan.graph.metadata?.id;
1743
1814
  if (!graphId) {
1744
1815
  throw new Error('Cannot start an async branch because the current graph has no ID.');
1745
1816
  }
1746
- const branchRuntimeCache = {
1747
- ...this.#runtimeCache,
1748
- graphBoundaries: undefined,
1749
- loadedProjects: { ...this.#loadedProjects },
1750
- };
1751
- const processor = new GraphProcessor(this.#project, graphId, this.#registry, this.#includeTrace, {
1752
- cacheLoadedProjects: true,
1753
- captureNodeTimings: this.#captureNodeTimings,
1754
- concurrency: this.#concurrency,
1755
- executionPlanCacheMode: this.#executionPlanCacheMode,
1756
- runtimeCache: branchRuntimeCache,
1757
- runtimeProfiler: this.#runtimeProfiler,
1758
- scheduler: this.#scheduler,
1759
- [graphProcessorGraphOverride]: plan.graph,
1760
- [consumedAsyncBranchTriggerOverride]: triggerNode.id,
1761
- [asyncBranchInputAnchorsOverride]: Object.fromEntries(plan.graph.connections
1817
+ const processor = this.#constructChildInvocation({
1818
+ kind: 'async',
1819
+ graph: plan.graph,
1820
+ triggerNodeId: triggerNode.id,
1821
+ inputAnchors: Object.fromEntries(plan.graph.connections
1762
1822
  .filter((connection) => connection.inputNodeId === triggerNode.id)
1763
1823
  .map((connection) => [connection.outputNodeId, this.#definitions[connection.outputNodeId]])),
1824
+ onCreated: onProcessorCreated,
1764
1825
  });
1765
- onProcessorCreated(processor);
1766
- processor.executor = this.executor;
1767
- processor.#isSubProcessor = true;
1768
- processor.#executionCache = this.#executionCache;
1769
- processor.#externalFunctions = this.#externalFunctions;
1770
- processor.#contextValues = this.#contextValues;
1771
1826
  processor.#parent = sameGraphOwner;
1772
- processor.#graphCallPath = this.#graphCallPath;
1773
1827
  processor.#abortOwnerOverride = root;
1774
1828
  processor.#suppressGraphPartialOutputs = true;
1775
- processor.#globals = this.#globals;
1776
- processor.#storedValueController = this.#storedValueController;
1777
- processor.#knowledgeStoreController = this.#knowledgeStoreController;
1778
- processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
1779
- processor.#executor = this.#executor;
1780
1829
  processor.#suppressGraphLifecycleEvents = isRootGraphOrigin;
1781
1830
  processor.#sharedRunStateOverride = {
1782
- attachedNodeData: this.#attachedNodeData,
1783
- graphInputNodeValues: this.#graphInputNodeValues,
1831
+ attachedNodeData: this.#run.attachedNodeData,
1832
+ graphInputNodeValues: this.#run.graphInputNodeValues,
1784
1833
  // Async branches cannot contain Graph Output nodes. Keep their synthetic
1785
1834
  // boundary outputs private so branch finalization cannot seed the root's
1786
1835
  // derived cost output before the root has accumulated every path.
@@ -1790,56 +1839,36 @@ export class GraphProcessor {
1790
1839
  processor.runToNodeIds = branchRunToNodeIds?.length ? branchRunToNodeIds : undefined;
1791
1840
  processor.#executionIdentityOverride = isRootGraphOrigin
1792
1841
  ? {
1793
- rootRunId: this.#rootRunId,
1794
- graphRunId: this.#graphRunId,
1795
- parentGraphRunId: this.#parentGraphRunId,
1842
+ rootRunId: this.#run.rootRunId,
1843
+ graphRunId: this.#run.graphRunId,
1844
+ parentGraphRunId: this.#run.parentGraphRunId,
1796
1845
  }
1797
1846
  : {
1798
- rootRunId: root.#rootRunId,
1847
+ rootRunId: root.#run.rootRunId,
1799
1848
  graphRunId: nanoid(),
1800
- parentGraphRunId: sameGraphOwner.#graphRunId,
1849
+ parentGraphRunId: sameGraphOwner.#run.graphRunId,
1801
1850
  };
1802
1851
  processor.preloadNodeData(triggerNode.id, triggerOutputs);
1803
1852
  processor.#suppressedPreloadedNodeIds.add(triggerNode.id);
1804
- const unwireEvents = wireSubprocessorEvents(processor, root.#emitter, {
1853
+ const unwireEvents = this.#wireChildEvents(processor, root, {
1805
1854
  autoCleanup: false,
1806
- isPaused: () => root.#lifecycle.isPaused,
1807
- pause: () => {
1808
- void root.pause();
1809
- },
1810
- resume: () => {
1811
- void root.resume();
1812
- },
1813
1855
  });
1814
- const unwireLifecycle = wireSubprocessorLifecycle(processor, {
1856
+ const unwireLifecycle = this.#wireChildLifecycle(processor, root, unwireEvents, {
1815
1857
  autoCleanup: false,
1816
- signal: sameGraphOwner === root ? undefined : sameGraphOwner.#abortController.signal,
1817
- parentAbortSignal: root.#abortController.signal,
1818
- onParentPause: (listener) => {
1819
- root.on('pause', listener);
1820
- return () => {
1821
- root.off('pause', listener);
1822
- };
1823
- },
1824
- onParentResume: (listener) => {
1825
- root.on('resume', listener);
1826
- return () => {
1827
- root.off('resume', listener);
1828
- };
1829
- },
1858
+ signal: sameGraphOwner === root ? undefined : sameGraphOwner.#run.abortController.signal,
1830
1859
  });
1831
- root.#subprocessors.add(processor);
1860
+ root.#run.subprocessors.add(processor);
1861
+ let executionFailed = true;
1832
1862
  try {
1833
1863
  if (root.#lifecycle.isPaused) {
1834
1864
  processor.pause();
1835
1865
  }
1836
- await processor.processGraph(this.#context, this.#graphInputs, this.#contextValues);
1866
+ await processor.processGraph(this.#run.context, this.#run.graphInputs, this.#contextValues);
1867
+ executionFailed = false;
1837
1868
  }
1838
1869
  finally {
1839
- root.#totalCost += processor.#totalCost;
1840
- unwireLifecycle();
1841
- unwireEvents();
1842
- root.#subprocessors.delete(processor);
1870
+ root.#accumulateChildCost(processor);
1871
+ this.#releaseChildInvocation(processor, root, unwireLifecycle, unwireEvents, executionFailed);
1843
1872
  }
1844
1873
  }
1845
1874
  #recordManagedAsyncBranchFailure(triggerNode, processor, error) {
@@ -1850,22 +1879,22 @@ export class GraphProcessor {
1850
1879
  });
1851
1880
  }
1852
1881
  #getSubprocessorNodeErrors(processor) {
1853
- if (!processor || !processor.#erroredNodes) {
1882
+ if (!processor || !processor.#run.erroredNodes) {
1854
1883
  return [];
1855
1884
  }
1856
- return [...processor.#erroredNodes.entries()].flatMap(([nodeId, nodeError]) => {
1885
+ return [...processor.#run.erroredNodes.entries()].flatMap(([nodeId, nodeError]) => {
1857
1886
  const node = processor.#nodesById[nodeId];
1858
1887
  return node ? [{ error: nodeError, node }] : [];
1859
1888
  });
1860
1889
  }
1861
1890
  #recordStreamingWatchFailure(watchNode, error, processor) {
1862
- if (this.#streamingWatchFailures.some((failure) => failure.error === error)) {
1891
+ if (this.#boundaries.streamingWatchFailures.some((failure) => failure.error === error)) {
1863
1892
  return;
1864
1893
  }
1865
1894
  // The child processor already emitted the precise nodeError before its
1866
1895
  // failure reaches the coordinator. Keep a root-owned failure too so the
1867
1896
  // normal graphError/error lifecycle remains truthful after draining.
1868
- this.#streamingWatchFailures.push({
1897
+ this.#boundaries.streamingWatchFailures.push({
1869
1898
  error,
1870
1899
  nodeErrors: this.#getSubprocessorNodeErrors(processor),
1871
1900
  triggerNode: watchNode,
@@ -1873,18 +1902,18 @@ export class GraphProcessor {
1873
1902
  }
1874
1903
  #getAttachedDataTo(node) {
1875
1904
  const nodeId = typeof node === 'string' ? node : node.id;
1876
- let nodeData = this.#attachedNodeData.get(nodeId);
1905
+ let nodeData = this.#run.attachedNodeData.get(nodeId);
1877
1906
  if (nodeData == null) {
1878
1907
  nodeData = {};
1879
- this.#attachedNodeData.set(nodeId, nodeData);
1908
+ this.#run.attachedNodeData.set(nodeId, nodeData);
1880
1909
  }
1881
1910
  return nodeData;
1882
1911
  }
1883
1912
  async #processNode(node, inputValues) {
1884
1913
  const processId = nanoid();
1885
- if (this.#abortController.signal.aborted) {
1886
- await this.#nodeErrored(node, createGraphAbortErrorFromSignal(this.#abortController.signal), processId);
1887
- this.#successfulAbortTerminalProcessIds.delete(processId);
1914
+ if (this.#run.abortController.signal.aborted) {
1915
+ await this.#nodeErrored(node, createGraphAbortErrorFromSignal(this.#run.abortController.signal), processId);
1916
+ this.#run.successfulAbortTerminalProcessIds.delete(processId);
1888
1917
  return { processId, shouldQueueOutputNodes: false };
1889
1918
  }
1890
1919
  const frozenOutputs = this.#resolveFrozenNodeOutputs(node, inputValues, processId);
@@ -1903,7 +1932,7 @@ export class GraphProcessor {
1903
1932
  else {
1904
1933
  await this.#processNormalNode(node, processId, inputValues);
1905
1934
  }
1906
- const successfulAbortTerminal = this.#successfulAbortTerminalProcessIds.delete(processId);
1935
+ const successfulAbortTerminal = this.#run.successfulAbortTerminalProcessIds.delete(processId);
1907
1936
  return { processId, shouldQueueOutputNodes: !successfulAbortTerminal };
1908
1937
  }
1909
1938
  async #processSplitRunNode(node, processId) {
@@ -1914,13 +1943,13 @@ export class GraphProcessor {
1914
1943
  isExcludedDueToControlFlow: (n, inputs, pid) => this.#excludedDueToControlFlow(n, inputs, pid) !== false,
1915
1944
  processNodeWithInputData: (n, inputs, idx, pid, partial, markResultAsEditorCacheHit) => this.#processNodeWithInputData(n, inputs, idx, pid, partial, markResultAsEditorCacheHit),
1916
1945
  splitRunConcurrency: this.#concurrency.splitRunConcurrency,
1917
- accumulateCost: (output) => this.#accumulateCost(output),
1918
- setNodeResults: (nodeId, outputs) => this.#nodeResults.set(nodeId, outputs),
1919
- markNodeVisited: (nodeId) => this.#visitedNodes.add(nodeId),
1946
+ accumulateCost: (output) => this.#accumulateCost(output, node.type),
1947
+ setNodeResults: (nodeId, outputs) => this.#run.nodeResults.set(nodeId, outputs),
1948
+ markNodeVisited: (nodeId) => this.#run.visitedNodes.add(nodeId),
1920
1949
  nodeErrored: (n, err, pid, durationMs, splitRunDurationMs, resultOrigin, splitOutputs) => this.#nodeErrored(n, err, pid, durationMs, splitRunDurationMs, resultOrigin, undefined, splitOutputs),
1921
1950
  takeFailureOutputs: (pid, index) => this.#takeFailureOutputs(pid, index),
1922
1951
  isAborted: () => this.#lifecycle.isAborted,
1923
- getAbortError: () => createGraphAbortErrorFromSignal(this.#abortController.signal),
1952
+ getAbortError: () => createGraphAbortErrorFromSignal(this.#run.abortController.signal),
1924
1953
  emit: (event, data) => {
1925
1954
  if (event === 'partialOutput') {
1926
1955
  emitDetached(this.#emitter, event, this.#withExecution(data));
@@ -1956,9 +1985,9 @@ export class GraphProcessor {
1956
1985
  resultOrigin: 'frozen',
1957
1986
  }));
1958
1987
  const timingStart = this.#startNodeTiming();
1959
- this.#nodeResults.set(node.id, outputValues);
1960
- this.#visitedNodes.add(node.id);
1961
- this.#accumulateCost(outputValues);
1988
+ this.#run.nodeResults.set(node.id, outputValues);
1989
+ this.#run.visitedNodes.add(node.id);
1990
+ this.#accumulateCost(outputValues, node.type);
1962
1991
  await this.#applyFrozenNodeDataflowEffects(node, outputValues, processId);
1963
1992
  this.#assertStreamingOutputWatchFinalOutputs(node, outputValues);
1964
1993
  await this.#emitter.emit('nodeFinish', this.#withExecution(withOptionalDuration({
@@ -1970,15 +1999,15 @@ export class GraphProcessor {
1970
1999
  this.#finishStreamingOutputWatches(node, outputValues);
1971
2000
  }
1972
2001
  async #applyFrozenNodeDataflowEffects(node, outputValues, processId) {
1973
- const effect = applyFrozenGraphBoundaryEffects(this.#graphOutputs, node, outputValues);
2002
+ const effect = applyFrozenGraphBoundaryEffects(this.#run.graphOutputs, node, outputValues);
1974
2003
  if (!effect) {
1975
2004
  return;
1976
2005
  }
1977
2006
  if (effect.type === 'setStoredValue') {
1978
- await this.#storedValueController.seed(effect.key, effect.value);
2007
+ await this.#shared.storedValueController.seed(effect.key, effect.value);
1979
2008
  return;
1980
2009
  }
1981
- this.#globals.set(effect.variableId, effect.value);
2010
+ this.#shared.globals.set(effect.variableId, effect.value);
1982
2011
  emitDetached(this.#emitter, 'globalSet', this.#withExecution({ id: effect.variableId, value: effect.value, processId }));
1983
2012
  }
1984
2013
  async #processNormalNode(node, processId, inputValues) {
@@ -1997,9 +2026,9 @@ export class GraphProcessor {
1997
2026
  const outputValues = await this.#processNodeWithInputData(node, inputValues, 0, processId, (node, partialOutputs, index) => this.#emitNodePartialOutput(node, partialOutputs, index, processId), () => {
1998
2027
  resultOrigin = 'editor-cache';
1999
2028
  });
2000
- this.#nodeResults.set(node.id, outputValues);
2001
- this.#visitedNodes.add(node.id);
2002
- this.#accumulateCost(outputValues);
2029
+ this.#run.nodeResults.set(node.id, outputValues);
2030
+ this.#run.visitedNodes.add(node.id);
2031
+ this.#accumulateCost(outputValues, node.type);
2003
2032
  this.#assertStreamingOutputWatchFinalOutputs(node, outputValues);
2004
2033
  const stopClaim = this.#claimStreamingWatchStopFromInvocation(node, outputValues);
2005
2034
  await this.#emitter.emit('nodeFinish', this.#withExecution(withOptionalDuration({
@@ -2018,7 +2047,7 @@ export class GraphProcessor {
2018
2047
  }
2019
2048
  async #nodeErrored(node, e, processId, durationMs, splitRunDurationMs, resultOrigin = 'executed', outputs, splitOutputs) {
2020
2049
  const error = getError(e);
2021
- for (const route of this.#inputStreamRoutes.get(node.id) ?? [])
2050
+ for (const route of this.#boundaries.inputStreamRoutes.get(node.id) ?? [])
2022
2051
  route.relay.finish({ error });
2023
2052
  // Most callers are ordinary (non-split) node executions. Let those retain
2024
2053
  // any checkpoint without requiring every error path to know about the
@@ -2031,7 +2060,8 @@ export class GraphProcessor {
2031
2060
  return;
2032
2061
  }
2033
2062
  this.#cancelStreamingOutputWatchesForSource(node.id);
2034
- this.#erroredNodes.set(node.id, error);
2063
+ this.#cancelStreamingCatchesForSource(node.id);
2064
+ this.#run.erroredNodes.set(node.id, error);
2035
2065
  await this.#emitter.emit('nodeError', this.#withExecution(withOptionalDuration({
2036
2066
  node,
2037
2067
  error,
@@ -2046,19 +2076,19 @@ export class GraphProcessor {
2046
2076
  emitDetached(this.#emitter, 'partialOutput', this.#withExecution({ node, outputs, index, processId, resultOrigin: 'executed' }));
2047
2077
  }
2048
2078
  #setFailureOutputs(processId, index, outputs) {
2049
- let outputsByIndex = this.#failureOutputsByProcessId.get(processId);
2079
+ let outputsByIndex = this.#run.failureOutputsByProcessId.get(processId);
2050
2080
  if (!outputsByIndex) {
2051
2081
  outputsByIndex = new Map();
2052
- this.#failureOutputsByProcessId.set(processId, outputsByIndex);
2082
+ this.#run.failureOutputsByProcessId.set(processId, outputsByIndex);
2053
2083
  }
2054
2084
  outputsByIndex.set(index, outputs);
2055
2085
  }
2056
2086
  #takeFailureOutputs(processId, index) {
2057
- const outputsByIndex = this.#failureOutputsByProcessId.get(processId);
2087
+ const outputsByIndex = this.#run.failureOutputsByProcessId.get(processId);
2058
2088
  const outputs = outputsByIndex?.get(index);
2059
2089
  outputsByIndex?.delete(index);
2060
2090
  if (outputsByIndex?.size === 0) {
2061
- this.#failureOutputsByProcessId.delete(processId);
2091
+ this.#run.failureOutputsByProcessId.delete(processId);
2062
2092
  }
2063
2093
  return outputs;
2064
2094
  }
@@ -2074,7 +2104,7 @@ export class GraphProcessor {
2074
2104
  return RACE_LOSER_EXCLUSION_REASON;
2075
2105
  }
2076
2106
  if (isSuccessfulNonRaceGraphAbortReason(abortReason)) {
2077
- this.#successfulAbortTerminalProcessIds.add(processId);
2107
+ this.#run.successfulAbortTerminalProcessIds.add(processId);
2078
2108
  return SUCCESSFUL_GRAPH_ABORT_EXCLUSION_REASON;
2079
2109
  }
2080
2110
  if (this.#lifecycle.abortSuccessful && isAbortLikeError(error)) {
@@ -2082,7 +2112,7 @@ export class GraphProcessor {
2082
2112
  ? RACE_LOSER_EXCLUSION_REASON
2083
2113
  : SUCCESSFUL_GRAPH_ABORT_EXCLUSION_REASON;
2084
2114
  if (exclusionReason === SUCCESSFUL_GRAPH_ABORT_EXCLUSION_REASON) {
2085
- this.#successfulAbortTerminalProcessIds.add(processId);
2115
+ this.#run.successfulAbortTerminalProcessIds.add(processId);
2086
2116
  }
2087
2117
  return exclusionReason;
2088
2118
  }
@@ -2106,17 +2136,12 @@ export class GraphProcessor {
2106
2136
  return undefined;
2107
2137
  }
2108
2138
  #getManagedAsyncBranchWatchViolation(triggerNode) {
2109
- const invocation = this.#getEnclosingStreamingWatchInvocation();
2110
- if (!invocation) {
2111
- return undefined;
2112
- }
2113
- return new Error(`Start Async Branch "${triggerNode.title}" cannot run inside Watch Streaming Output "${invocation.plan.watchNode.title}". ` +
2114
- '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.');
2139
+ return getAsyncBranchWatchViolation(triggerNode, this.#getEnclosingStreamingWatchInvocation()?.plan.watchNode);
2115
2140
  }
2116
2141
  /** Raise a user event on the processor, all subprocessors, and their children. */
2117
2142
  raiseEvent(event, data) {
2118
2143
  emitDetached(this.#emitter, `userEvent:${event}`, data);
2119
- for (const subprocessor of this.#subprocessors) {
2144
+ for (const subprocessor of this.#run.subprocessors) {
2120
2145
  subprocessor.raiseEvent(event, data);
2121
2146
  }
2122
2147
  }
@@ -2126,9 +2151,9 @@ export class GraphProcessor {
2126
2151
  return controller;
2127
2152
  }
2128
2153
  #registerNodeAbortController(nodeId, abortController) {
2129
- const existingAbortControllers = this.#nodeAbortControllers.get(nodeId);
2154
+ const existingAbortControllers = this.#run.nodeAbortControllers.get(nodeId);
2130
2155
  if (!existingAbortControllers) {
2131
- this.#nodeAbortControllers.set(nodeId, abortController);
2156
+ this.#run.nodeAbortControllers.set(nodeId, abortController);
2132
2157
  return;
2133
2158
  }
2134
2159
  if (existingAbortControllers instanceof Set) {
@@ -2138,15 +2163,15 @@ export class GraphProcessor {
2138
2163
  if (existingAbortControllers === abortController) {
2139
2164
  return;
2140
2165
  }
2141
- this.#nodeAbortControllers.set(nodeId, new Set([existingAbortControllers, abortController]));
2166
+ this.#run.nodeAbortControllers.set(nodeId, new Set([existingAbortControllers, abortController]));
2142
2167
  }
2143
2168
  #unregisterNodeAbortController(nodeId, abortController) {
2144
- const existingAbortControllers = this.#nodeAbortControllers.get(nodeId);
2169
+ const existingAbortControllers = this.#run.nodeAbortControllers.get(nodeId);
2145
2170
  if (!existingAbortControllers) {
2146
2171
  return;
2147
2172
  }
2148
2173
  if (existingAbortControllers === abortController) {
2149
- this.#nodeAbortControllers.delete(nodeId);
2174
+ this.#run.nodeAbortControllers.delete(nodeId);
2150
2175
  return;
2151
2176
  }
2152
2177
  if (!(existingAbortControllers instanceof Set)) {
@@ -2154,14 +2179,14 @@ export class GraphProcessor {
2154
2179
  }
2155
2180
  existingAbortControllers.delete(abortController);
2156
2181
  if (existingAbortControllers.size === 0) {
2157
- this.#nodeAbortControllers.delete(nodeId);
2182
+ this.#run.nodeAbortControllers.delete(nodeId);
2158
2183
  }
2159
2184
  else if (existingAbortControllers.size === 1) {
2160
- this.#nodeAbortControllers.set(nodeId, existingAbortControllers.values().next().value);
2185
+ this.#run.nodeAbortControllers.set(nodeId, existingAbortControllers.values().next().value);
2161
2186
  }
2162
2187
  }
2163
2188
  #abortNodeControllersForNode(nodeId, traceMessage, reason) {
2164
- const abortControllerEntry = this.#nodeAbortControllers.get(nodeId);
2189
+ const abortControllerEntry = this.#run.nodeAbortControllers.get(nodeId);
2165
2190
  if (!abortControllerEntry) {
2166
2191
  return;
2167
2192
  }
@@ -2180,7 +2205,7 @@ export class GraphProcessor {
2180
2205
  }
2181
2206
  }
2182
2207
  #abortActiveNodeControllers(reason) {
2183
- for (const nodeId of [...this.#nodeAbortControllers.keys()]) {
2208
+ for (const nodeId of [...this.#run.nodeAbortControllers.keys()]) {
2184
2209
  this.#abortNodeControllersForNode(nodeId, undefined, reason);
2185
2210
  }
2186
2211
  }
@@ -2193,8 +2218,8 @@ export class GraphProcessor {
2193
2218
  const instance = this.#nodeInstances[node.id];
2194
2219
  const nodeAbortController = this.#newAbortController();
2195
2220
  this.#registerNodeAbortController(node.id, nodeAbortController);
2196
- if (this.#abortController.signal.aborted) {
2197
- nodeAbortController.abort(getAbortSignalReason(this.#abortController.signal));
2221
+ if (this.#run.abortController.signal.aborted) {
2222
+ nodeAbortController.abort(getAbortSignalReason(this.#run.abortController.signal));
2198
2223
  }
2199
2224
  let continuationFinalized = false;
2200
2225
  try {
@@ -2221,7 +2246,7 @@ export class GraphProcessor {
2221
2246
  const abortReason = getGraphAbortReasonFromSignal(nodeAbortController.signal);
2222
2247
  if (nodeAbortController.signal.aborted) {
2223
2248
  if (isSuccessfulNonRaceGraphAbortReason(abortReason)) {
2224
- this.#successfulAbortTerminalProcessIds.add(processId);
2249
+ this.#run.successfulAbortTerminalProcessIds.add(processId);
2225
2250
  this.#discardFailureOutputs(processId, index);
2226
2251
  return results;
2227
2252
  }
@@ -2242,20 +2267,21 @@ export class GraphProcessor {
2242
2267
  }
2243
2268
  }
2244
2269
  #getTokenizer() {
2245
- return this.#context.tokenizer;
2270
+ return this.#run.context.tokenizer;
2246
2271
  }
2247
2272
  #createNodeProcessContext(node, inputValues, index, processId, nodeAbortController, partialOutput, toolCallTraceSource, markResultAsEditorCacheHit) {
2248
2273
  const plugin = this.#registry.getPluginFor(node.type);
2249
2274
  const acceptsPartialOutputs = () => {
2250
2275
  if (nodeAbortController.signal.aborted)
2251
2276
  return false;
2252
- const active = this.#nodeAbortControllers.get(node.id);
2277
+ const active = this.#run.nodeAbortControllers.get(node.id);
2253
2278
  return active === nodeAbortController || (active instanceof Set && active.has(nodeAbortController));
2254
2279
  };
2255
2280
  const onGraphOutputPartial = canForwardGraphCallerOutputPartials(node) &&
2256
- (this.#streamingWatchPlansBySourceNodeId.has(node.id) ||
2257
- this.#inputStreamRoutes.has(node.id) ||
2258
- this.#graphOutputPartialBindingsBySourceNodeId.has(node.id))
2281
+ (this.#boundaries.streamingWatchPlansBySourceNodeId.has(node.id) ||
2282
+ this.#boundaries.streamingCatchPlansBySourceNodeId.has(node.id) ||
2283
+ this.#boundaries.inputStreamRoutes.has(node.id) ||
2284
+ this.#boundaries.graphOutputPartialBindingsBySourceNodeId.has(node.id))
2259
2285
  ? (partialOutputs) => {
2260
2286
  if (!acceptsPartialOutputs())
2261
2287
  return;
@@ -2265,20 +2291,20 @@ export class GraphProcessor {
2265
2291
  }
2266
2292
  : undefined;
2267
2293
  const toolCallContinuation = this.#getToolCallContinuationContext(node, nodeAbortController.signal, processId, index);
2268
- return buildNodeProcessContext({
2294
+ const processContext = buildNodeProcessContext({
2269
2295
  activeOutputPortIds: this.#getActiveOutputPortIds(node),
2270
2296
  attachedData: this.#getAttachedDataTo(node),
2271
- base: this.#nodeProcessContextBase,
2297
+ base: this.#run.nodeProcessContextBase,
2272
2298
  createSubProcessor: (subGraphId, options = {}) => this.#createSubProcessor(node, index, processId, subGraphId, options),
2273
2299
  execution: this.#buildExecutionMetadata(),
2274
2300
  externalFunctions: this.#externalFunctions,
2275
- getPluginConfig: (name) => getPluginConfig(plugin, this.#context.settings, name),
2301
+ getPluginConfig: (name) => getPluginConfig(plugin, this.#run.context.settings, name),
2276
2302
  isDirectRunTarget: this.runToNodeIds?.includes(node.id) ?? false,
2277
2303
  markResultAsEditorCacheHit,
2278
2304
  node,
2279
2305
  nodeAbortController,
2280
2306
  onGraphOutputPartial,
2281
- graphInputStreams: this.#callerInputStreams.get(node.id),
2307
+ graphInputStreams: this.#boundaries.callerInputStreams.get(node.id),
2282
2308
  onPartialOutputs: (partialOutputs) => {
2283
2309
  if (!acceptsPartialOutputs())
2284
2310
  return;
@@ -2306,7 +2332,7 @@ export class GraphProcessor {
2306
2332
  },
2307
2333
  splitIndex: node.isSplitRun ? index : 0,
2308
2334
  setGlobal: (id, value) => {
2309
- this.#globals.set(id, value);
2335
+ this.#shared.globals.set(id, value);
2310
2336
  emitDetached(this.#emitter, 'globalSet', this.#withExecution({ id, value, processId }));
2311
2337
  },
2312
2338
  toolCallContinuation,
@@ -2336,6 +2362,14 @@ export class GraphProcessor {
2336
2362
  });
2337
2363
  },
2338
2364
  });
2365
+ if (node.type === 'subGraph' && node.data.targetProjectId) {
2366
+ const data = node.data;
2367
+ processContext.subgraphTarget = this.#shared.subgraphTargetCache.get(getSubgraphProjectKey({
2368
+ projectId: data.targetProjectId,
2369
+ version: data.targetVersion ?? 'latest',
2370
+ }));
2371
+ }
2372
+ return processContext;
2339
2373
  }
2340
2374
  #getToolCallContinuationContext(node, llmSignal, processId, index) {
2341
2375
  if (node.type !== 'llmChatV2') {
@@ -2380,9 +2414,9 @@ export class GraphProcessor {
2380
2414
  },
2381
2415
  commit: (invocation) => {
2382
2416
  for (const [nodeId, outputs] of invocation.latestOutputs) {
2383
- this.#nodeResults.set(nodeId, outputs);
2384
- this.#visitedNodes.add(nodeId);
2385
- this.#remainingNodes.delete(nodeId);
2417
+ this.#run.nodeResults.set(nodeId, outputs);
2418
+ this.#run.visitedNodes.add(nodeId);
2419
+ this.#run.remainingNodes.delete(nodeId);
2386
2420
  this.#continuationCompletionOwnerByNodeId.set(nodeId, invocation.llmNodeId);
2387
2421
  }
2388
2422
  },
@@ -2443,10 +2477,10 @@ export class GraphProcessor {
2443
2477
  resultOrigin: 'executed',
2444
2478
  })),
2445
2479
  getActiveOutputPortIds: (node) => this.#getActiveOutputPortIds(node),
2446
- getContinuationBranchBoundaryNodeIds: (llmNode) => new Set([llmNode.id, ...this.#currentlyProcessing]),
2447
- hasPreloadedOrFrozenDelegateOutput: (node, inputs, processId) => this.#nodeResults.has(node.id) || this.#resolveFrozenNodeOutputs(node, inputs, processId) != null,
2480
+ getContinuationBranchBoundaryNodeIds: (llmNode) => new Set([llmNode.id, ...this.#run.currentlyProcessing]),
2481
+ hasPreloadedOrFrozenDelegateOutput: (node, inputs, processId) => this.#run.nodeResults.has(node.id) || this.#resolveFrozenNodeOutputs(node, inputs, processId) != null,
2448
2482
  registerNodeAbortController: (nodeId, controller) => this.#registerNodeAbortController(nodeId, controller),
2449
- rootAbortSignal: this.#abortController.signal,
2483
+ rootAbortSignal: this.#run.abortController.signal,
2450
2484
  unregisterNodeAbortController: (nodeId, controller) => this.#unregisterNodeAbortController(nodeId, controller),
2451
2485
  startNodeTiming: () => this.#startNodeTiming(),
2452
2486
  waitUntilUnpaused: () => this.#waitUntilUnpaused(),
@@ -2464,114 +2498,69 @@ export class GraphProcessor {
2464
2498
  if (!graphId) {
2465
2499
  throw new Error('Cannot execute a tool continuation branch because the current graph has no ID.');
2466
2500
  }
2467
- const branchRuntimeCache = {
2468
- ...this.#runtimeCache,
2469
- graphBoundaries: undefined,
2470
- loadedProjects: { ...this.#loadedProjects },
2471
- };
2472
- const branchGraphOutputs = createGraphOutputsOverlay(this.#graphOutputs);
2473
- const processor = new GraphProcessor(this.#project, graphId, this.#registry, this.#includeTrace, {
2474
- cacheLoadedProjects: true,
2475
- captureNodeTimings: this.#captureNodeTimings,
2476
- concurrency: this.#concurrency,
2477
- executionPlanCacheMode: this.#executionPlanCacheMode,
2478
- runtimeCache: branchRuntimeCache,
2479
- runtimeProfiler: this.#runtimeProfiler,
2480
- scheduler: this.#scheduler,
2481
- [graphProcessorGraphOverride]: branchPlan.graph,
2482
- });
2483
- processor.executor = this.executor;
2484
- processor.#isSubProcessor = true;
2485
- processor.#executionCache = this.#executionCache;
2486
- processor.#externalFunctions = this.#externalFunctions;
2487
- processor.#contextValues = this.#contextValues;
2488
- processor.#parent = this;
2489
- processor.#graphCallPath = this.#graphCallPath;
2501
+ const branchGraphOutputs = createGraphOutputsOverlay(this.#run.graphOutputs);
2502
+ const processor = this.#constructChildInvocation({ kind: 'continuation', graph: branchPlan.graph });
2490
2503
  processor.#abortOwnerOverride = this.#abortOwnerOverride ?? this;
2491
2504
  processor.#sameGraphRunOwnerOverride = this.#sameGraphRunOwnerOverride ?? this;
2492
- processor.#globals = this.#globals;
2493
- processor.#storedValueController = this.#storedValueController;
2494
- processor.#knowledgeStoreController = this.#knowledgeStoreController;
2495
- processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
2496
- processor.#executor = this.#executor;
2497
2505
  processor.#suppressGraphLifecycleEvents = true;
2498
2506
  processor.#sharedRunStateOverride = {
2499
- attachedNodeData: this.#attachedNodeData,
2500
- graphInputNodeValues: this.#graphInputNodeValues,
2507
+ attachedNodeData: this.#run.attachedNodeData,
2508
+ graphInputNodeValues: this.#run.graphInputNodeValues,
2501
2509
  graphOutputs: branchGraphOutputs.view,
2502
2510
  };
2503
2511
  const branchNodeIds = new Set(branchPlan.graph.nodes.map((node) => node.id));
2504
2512
  const branchRunToNodeIds = this.runToNodeIds?.filter((nodeId) => branchNodeIds.has(nodeId));
2505
2513
  processor.runToNodeIds = branchRunToNodeIds?.length ? branchRunToNodeIds : undefined;
2506
2514
  processor.#executionIdentityOverride = {
2507
- rootRunId: this.#rootRunId,
2508
- graphRunId: this.#graphRunId,
2509
- parentGraphRunId: this.#parentGraphRunId,
2515
+ rootRunId: this.#run.rootRunId,
2516
+ graphRunId: this.#run.graphRunId,
2517
+ parentGraphRunId: this.#run.parentGraphRunId,
2510
2518
  };
2511
2519
  for (const [nodeId, outputs] of branchPlan.preloadedOutputs) {
2512
2520
  processor.preloadNodeData(nodeId, outputs);
2513
2521
  processor.#suppressedPreloadedNodeIds.add(nodeId);
2514
2522
  }
2515
- const unwireEvents = wireSubprocessorEvents(processor, this.#emitter, {
2523
+ const unwireEvents = this.#wireChildEvents(processor, this, {
2516
2524
  autoCleanup: false,
2517
- isPaused: () => this.#lifecycle.isPaused,
2518
- pause: () => {
2519
- void this.pause();
2520
- },
2521
- resume: () => {
2522
- void this.resume();
2523
- },
2524
2525
  });
2525
- const unwireLifecycle = wireSubprocessorLifecycle(processor, {
2526
+ const unwireLifecycle = this.#wireChildLifecycle(processor, this, unwireEvents, {
2526
2527
  autoCleanup: false,
2527
2528
  signal,
2528
- parentAbortSignal: this.#abortController.signal,
2529
- onParentPause: (listener) => {
2530
- this.on('pause', listener);
2531
- return () => {
2532
- this.off('pause', listener);
2533
- };
2534
- },
2535
- onParentResume: (listener) => {
2536
- this.on('resume', listener);
2537
- return () => {
2538
- this.off('resume', listener);
2539
- };
2540
- },
2541
2529
  });
2542
- this.#subprocessors.add(processor);
2530
+ this.#run.subprocessors.add(processor);
2531
+ let executionFailed = true;
2543
2532
  try {
2544
2533
  if (signal.aborted) {
2545
2534
  throw createGraphAbortErrorFromSignal(signal, 'Tool continuation branch aborted');
2546
2535
  }
2547
- await processor.processGraph(this.#context, this.#graphInputs, this.#contextValues);
2536
+ await processor.processGraph(this.#run.context, this.#run.graphInputs, this.#contextValues);
2548
2537
  if (!deferGraphOutputCommit) {
2549
2538
  this.#commitContinuationGraphOutputs(branchGraphOutputs.writes);
2550
2539
  }
2551
- return {
2540
+ const result = {
2552
2541
  graphOutputWrites: branchGraphOutputs.writes,
2553
2542
  nodeOutputs: this.#getContinuationBranchResults(processor, branchPlan),
2554
2543
  };
2544
+ executionFailed = false;
2545
+ return result;
2555
2546
  }
2556
2547
  finally {
2557
- this.#totalCost += processor.#totalCost;
2558
- unwireLifecycle();
2559
- unwireEvents();
2560
- this.#subprocessors.delete(processor);
2548
+ this.#accumulateChildCost(processor);
2549
+ this.#releaseChildInvocation(processor, this, unwireLifecycle, unwireEvents, executionFailed);
2561
2550
  }
2562
2551
  }
2563
2552
  #commitContinuationGraphOutputs(writes) {
2564
2553
  for (const [outputId, value] of Object.entries(writes)) {
2565
- const existingValue = this.#graphOutputs[outputId];
2554
+ const existingValue = this.#run.graphOutputs[outputId];
2566
2555
  if (existingValue == null || existingValue.type === 'control-flow-excluded') {
2567
- this.#graphOutputs[outputId] = value;
2556
+ this.#run.graphOutputs[outputId] = value;
2568
2557
  }
2569
2558
  }
2570
2559
  }
2571
2560
  #getContinuationBranchResults(processor, branchPlan) {
2572
2561
  const results = new Map();
2573
- for (const [nodeId, outputs] of processor.#nodeResults) {
2574
- if (branchPlan.preloadedOutputs.has(nodeId) || !processor.#visitedNodes.has(nodeId)) {
2562
+ for (const [nodeId, outputs] of processor.#run.nodeResults) {
2563
+ if (branchPlan.preloadedOutputs.has(nodeId) || !processor.#run.visitedNodes.has(nodeId)) {
2575
2564
  continue;
2576
2565
  }
2577
2566
  results.set(nodeId, outputs);
@@ -2587,17 +2576,17 @@ export class GraphProcessor {
2587
2576
  sourceNode,
2588
2577
  sourceOutputs,
2589
2578
  state: {
2590
- erroredNodeIds: new Set(this.#erroredNodes.keys()),
2591
- nodeOutputs: this.#nodeResults,
2579
+ erroredNodeIds: new Set(this.#run.erroredNodes.keys()),
2580
+ nodeOutputs: this.#run.nodeResults,
2592
2581
  runToRelevantNodeIds: this.#getExecutionRelevantNodeIds(),
2593
- visitedNodeIds: this.#visitedNodes,
2582
+ visitedNodeIds: this.#run.visitedNodes,
2594
2583
  },
2595
2584
  });
2596
2585
  }
2597
2586
  #createToolCallContinuationBranchPlanner() {
2598
2587
  return createToolCallContinuationBranchPlanner({
2599
2588
  asyncBranchPlansByTriggerNodeId: this.#asyncBranchPlansByTriggerNodeId,
2600
- attachedNodeDataByNodeId: this.#attachedNodeData,
2589
+ attachedNodeDataByNodeId: this.#run.attachedNodeData,
2601
2590
  effectiveConnections: this.#getEffectiveConnections(),
2602
2591
  graph: this.#getExecutionGraph(),
2603
2592
  isDefinitionValidConnection: (connection) => this.#isDefinitionValidConnection(connection),
@@ -2643,136 +2632,26 @@ export class GraphProcessor {
2643
2632
  return this.#effectiveConnectionsForRun;
2644
2633
  }
2645
2634
  #prepareStreamingWatchTopology() {
2646
- const connections = this.#getEffectiveConnections().filter((connection) => this.#isDefinitionValidConnection(connection));
2647
- const outgoingByNodeId = new Map();
2648
- const incomingByNodeId = new Map();
2649
- const relevantNodeIds = this.#getExecutionRelevantNodeIds();
2650
- const isRelevant = (nodeId) => !relevantNodeIds || relevantNodeIds.has(nodeId);
2651
- for (const connection of connections) {
2652
- const outgoing = outgoingByNodeId.get(connection.outputNodeId) ?? [];
2653
- outgoing.push(connection);
2654
- outgoingByNodeId.set(connection.outputNodeId, outgoing);
2655
- const incoming = incomingByNodeId.get(connection.inputNodeId) ?? [];
2656
- incoming.push(connection);
2657
- incomingByNodeId.set(connection.inputNodeId, incoming);
2658
- }
2659
- for (const watchNode of Object.values(this.#nodesById)) {
2660
- if (watchNode.type !== 'watchStreamingOutput' || watchNode.disabled || !isRelevant(watchNode.id)) {
2661
- continue;
2662
- }
2663
- if (watchNode.id === this.#consumedStreamingWatchNodeId) {
2664
- continue;
2665
- }
2666
- const enclosingWatchInvocation = this.#getEnclosingStreamingWatchInvocation();
2667
- if (enclosingWatchInvocation) {
2668
- throw new Error(`Watch Streaming Output "${watchNode.title}" cannot run inside Watch Streaming Output ` +
2669
- `"${enclosingWatchInvocation.plan.watchNode.title}". A Watch branch cannot contain another Watch, including through Subgraph.`);
2670
- }
2671
- if (this.#nodeResults.has(watchNode.id)) {
2672
- throw new Error(`Cannot preload ${watchNode.title} because a streaming boundary must be scheduled. ` +
2673
- "Run from Watch Streaming Output to reuse a producer's saved final value, or run from the producer to stream again.");
2674
- }
2675
- const incoming = incomingByNodeId.get(watchNode.id) ?? [];
2676
- if (incoming.length === 0) {
2677
- // An unattached Watch is an ordinary in-progress authoring state. Keep
2678
- // it dormant rather than making an incomplete canvas fail to run.
2679
- this.#ignoreNodes.add(watchNode.id);
2680
- continue;
2681
- }
2682
- if (incoming.length !== 1 || incoming[0].inputId !== 'stream') {
2683
- throw new Error(`Watch Streaming Output "${watchNode.title}" must have exactly one Streaming Output input connection.`);
2684
- }
2685
- const sourceConnection = incoming[0];
2686
- const sourceNode = this.#nodesById[sourceConnection.outputNodeId];
2687
- if (!sourceNode || sourceNode.disabled || !isRelevant(sourceNode.id)) {
2688
- throw new Error(`Watch Streaming Output "${watchNode.title}" has no runnable streaming source.`);
2689
- }
2690
- if (sourceNode.isSplitRun) {
2691
- throw new Error(`Watch Streaming Output "${watchNode.title}" cannot watch split-run node "${sourceNode.title}". ` +
2692
- 'Assemble a single streaming value before the watch boundary.');
2693
- }
2694
- const branchNodeIds = new Set();
2695
- const pendingNodeIds = (outgoingByNodeId.get(watchNode.id) ?? [])
2696
- .map((connection) => connection.inputNodeId)
2697
- .filter(isRelevant);
2698
- let stopNodeId;
2699
- while (pendingNodeIds.length > 0) {
2700
- const nodeId = pendingNodeIds.pop();
2701
- if (nodeId === watchNode.id) {
2702
- throw new Error(`Watch Streaming Output "${watchNode.title}" cannot reconnect to itself.`);
2703
- }
2704
- if (branchNodeIds.has(nodeId)) {
2705
- continue;
2706
- }
2707
- const node = this.#nodesById[nodeId];
2708
- if (!node || !isRelevant(nodeId)) {
2709
- continue;
2710
- }
2711
- if (node.disabled) {
2712
- throw new Error(`Watch Streaming Output "${watchNode.title}" cannot include disabled node "${node.title}".`);
2713
- }
2714
- if (node.type === 'watchStreamingOutput') {
2715
- throw new Error(`Watch Streaming Output "${watchNode.title}" cannot contain another Watch Streaming Output node.`);
2716
- }
2717
- if (node.type === 'graphOutput') {
2718
- throw new Error(`Watch Streaming Output "${watchNode.title}" must reach Stop Watching Streaming Output before Graph Output "${node.title}".`);
2719
- }
2720
- if (node.type === 'startBackgroundBranch') {
2721
- throw new Error(`Watch Streaming Output "${watchNode.title}" cannot contain Start Async Branch. ` +
2722
- 'Keep watched work in the bounded watch branch instead.');
2723
- }
2724
- branchNodeIds.add(nodeId);
2725
- if (node.type === 'stopWatchingStreamingOutput') {
2726
- if (stopNodeId && stopNodeId !== nodeId) {
2727
- throw new Error(`Watch Streaming Output "${watchNode.title}" must have one Stop Watching Streaming Output boundary.`);
2728
- }
2729
- stopNodeId = nodeId;
2730
- continue;
2731
- }
2732
- for (const connection of outgoingByNodeId.get(nodeId) ?? []) {
2733
- if (isRelevant(connection.inputNodeId)) {
2734
- pendingNodeIds.push(connection.inputNodeId);
2735
- }
2736
- }
2737
- }
2738
- if (branchNodeIds.size === 0) {
2739
- // Source -> Watch is also a useful intermediate authoring state. There
2740
- // is no downstream work to schedule yet, so do not create a coordinator.
2741
- this.#ignoreNodes.add(watchNode.id);
2635
+ for (const topology of planStreamingWatchTopology({
2636
+ graph: this.#graph,
2637
+ executionNodes: this.#executionGraphNodes,
2638
+ nodesById: this.#nodesById,
2639
+ connections: this.#getEffectiveConnections().filter((connection) => this.#isDefinitionValidConnection(connection)),
2640
+ relevantNodeIds: this.#getExecutionRelevantNodeIds(),
2641
+ preloadedNodes: this.#run.nodeResults,
2642
+ consumedWatchNodeId: this.#consumedStreamingWatchNodeId,
2643
+ enclosingWatchNode: this.#getEnclosingStreamingWatchInvocation()?.plan.watchNode,
2644
+ })) {
2645
+ const { watchNode } = topology;
2646
+ if (topology.kind === 'dormant') {
2647
+ this.#run.ignoreNodes.add(watchNode.id);
2742
2648
  continue;
2743
2649
  }
2744
- if (stopNodeId) {
2745
- const reentry = (outgoingByNodeId.get(stopNodeId) ?? []).find((connection) => connection.inputNodeId === watchNode.id || branchNodeIds.has(connection.inputNodeId));
2746
- if (reentry) {
2747
- const stopNode = this.#nodesById[stopNodeId];
2748
- throw new Error(`Stop Watching Streaming Output "${stopNode.title}" cannot reconnect to its own Watch Streaming Output branch. ` +
2749
- 'Connect it only to ordinary downstream execution.');
2750
- }
2751
- }
2752
- for (const nodeId of branchNodeIds) {
2753
- const externalInput = (incomingByNodeId.get(nodeId) ?? []).find((connection) => connection.outputNodeId !== watchNode.id && !branchNodeIds.has(connection.outputNodeId));
2754
- if (externalInput) {
2755
- const node = this.#nodesById[nodeId];
2756
- const externalNode = this.#nodesById[externalInput.outputNodeId];
2757
- throw new Error(`Watch Streaming Output "${watchNode.title}" cannot run "${node.title}" because it also depends on ` +
2758
- `"${externalNode?.title ?? externalInput.outputNodeId}" outside the watch branch. ` +
2759
- 'Assemble every required value inside the watch boundary.');
2760
- }
2761
- }
2762
- const graph = {
2763
- metadata: this.#graph.metadata ? { ...this.#graph.metadata } : undefined,
2764
- nodes: this.#executionGraphNodes.filter((node) => node.id === watchNode.id || branchNodeIds.has(node.id)),
2765
- connections: connections.filter((connection) => connection.inputNodeId === watchNode.id ||
2766
- (branchNodeIds.has(connection.inputNodeId) &&
2767
- (connection.outputNodeId === watchNode.id || branchNodeIds.has(connection.outputNodeId)))),
2768
- };
2769
2650
  const plan = {
2770
- graph,
2771
- includeAllStreamedOutput: connections.some((connection) => connection.outputNodeId === watchNode.id &&
2772
- connection.outputId === 'allStreamedOutput' &&
2773
- branchNodeIds.has(connection.inputNodeId)),
2774
- sourceOutputId: sourceConnection.outputId,
2775
- stopNodeId,
2651
+ graph: topology.graph,
2652
+ includeAllStreamedOutput: topology.includeAllStreamedOutput,
2653
+ sourceOutputId: topology.sourceOutputId,
2654
+ stopNodeId: topology.stopNodeId,
2776
2655
  streamedOutput: [],
2777
2656
  previousStreamedValue: undefined,
2778
2657
  watchNode,
@@ -2781,20 +2660,62 @@ export class GraphProcessor {
2781
2660
  historySummaryEmitted: false,
2782
2661
  unmatchedStopResolved: false,
2783
2662
  };
2784
- const plans = this.#streamingWatchPlansBySourceNodeId.get(sourceNode.id) ?? [];
2663
+ const plans = this.#boundaries.streamingWatchPlansBySourceNodeId.get(topology.sourceNodeId) ?? [];
2785
2664
  plans.push(plan);
2786
- this.#streamingWatchPlansBySourceNodeId.set(sourceNode.id, plans);
2787
- this.#streamingWatchPlansByWatchNodeId.set(watchNode.id, plan);
2788
- const watch = new StreamingOutputWatch(watchNode.data, (snapshot, registerCancel) => this.#runStreamingOutputWatchInvocation(plan, snapshot, registerCancel), (error) => this.#recordStreamingWatchFailure(watchNode, error));
2789
- this.#streamingOutputWatches.set(watchNode.id, watch);
2790
- for (const nodeId of [watchNode.id, ...branchNodeIds]) {
2791
- this.#ignoreNodes.add(nodeId);
2792
- }
2665
+ this.#boundaries.streamingWatchPlansBySourceNodeId.set(topology.sourceNodeId, plans);
2666
+ this.#boundaries.streamingWatchPlansByWatchNodeId.set(watchNode.id, plan);
2667
+ this.#boundaries.streamingOutputWatches.set(watchNode.id, new StreamingOutputWatch(watchNode.data, (snapshot, registerCancel) => this.#runStreamingOutputWatchInvocation(plan, snapshot, registerCancel), (error) => this.#recordStreamingWatchFailure(watchNode, error)));
2668
+ for (const nodeId of [watchNode.id, ...topology.branchNodeIds])
2669
+ this.#run.ignoreNodes.add(nodeId);
2793
2670
  }
2794
2671
  this.#assertStreamingOutputWatchPreloadsAreSafe();
2795
2672
  }
2673
+ #prepareStreamingCatchTopology() {
2674
+ const relevantNodeIds = this.#getExecutionRelevantNodeIds();
2675
+ const connections = this.#getEffectiveConnections().filter((connection) => this.#isDefinitionValidConnection(connection));
2676
+ for (const node of this.#executionGraphNodes) {
2677
+ if (node.type !== 'catchStreamingChunks' || node.disabled || (relevantNodeIds && !relevantNodeIds.has(node.id)))
2678
+ continue;
2679
+ // A saved Catch result is an ordinary once-only value. Run-from may reuse
2680
+ // it, but a live Catch still needs its own streaming coordinator.
2681
+ if (this.#run.nodeResults.has(node.id))
2682
+ continue;
2683
+ if (node.isConditional || node.isSplitRun) {
2684
+ throw new Error(`Catch streaming chunks "${node.title}" cannot use Conditional or Many runs.`);
2685
+ }
2686
+ const incoming = connections.filter((connection) => connection.inputNodeId === node.id);
2687
+ if (incoming.length === 0) {
2688
+ this.#run.ignoreNodes.add(node.id);
2689
+ continue;
2690
+ }
2691
+ if (incoming.length !== 1 || incoming[0].inputId !== 'stream') {
2692
+ throw new Error(`Catch streaming chunks "${node.title}" must have exactly one Streaming Output input connection.`);
2693
+ }
2694
+ const source = this.#nodesById[incoming[0].outputNodeId];
2695
+ if (!source || source.disabled || source.isSplitRun) {
2696
+ throw new Error(`Catch streaming chunks "${node.title}" needs one runnable, non-split streaming source.`);
2697
+ }
2698
+ const rawCount = node.data.count;
2699
+ const count = Number.isFinite(rawCount)
2700
+ ? Math.min(MAX_CAUGHT_STREAMING_CHUNKS, Math.max(1, Math.floor(rawCount)))
2701
+ : 1;
2702
+ const plan = {
2703
+ node: node,
2704
+ sourceOutputId: incoming[0].outputId,
2705
+ count,
2706
+ chunks: [],
2707
+ settled: false,
2708
+ };
2709
+ const plans = this.#boundaries.streamingCatchPlansBySourceNodeId.get(source.id) ?? [];
2710
+ plans.push(plan);
2711
+ this.#boundaries.streamingCatchPlansBySourceNodeId.set(source.id, plans);
2712
+ this.#run.ignoreNodes.add(node.id);
2713
+ }
2714
+ }
2796
2715
  #isStreamingOutputWatchBoundary(node) {
2797
- return node.type === 'watchStreamingOutput' || node.type === 'stopWatchingStreamingOutput';
2716
+ return (node.type === 'watchStreamingOutput' ||
2717
+ node.type === 'stopWatchingStreamingOutput' ||
2718
+ node.type === 'catchStreamingChunks');
2798
2719
  }
2799
2720
  #assertStreamingOutputWatchPreloadCanBeAdded(nodeId) {
2800
2721
  // Before initialization, referenced projects and the effective graph are
@@ -2811,7 +2732,7 @@ export class GraphProcessor {
2811
2732
  throw new Error(`Cannot preload ${node.title} while it is running because a streaming boundary must be scheduled. ` +
2812
2733
  'Preload the producer before starting a new run instead.');
2813
2734
  }
2814
- for (const [sourceNodeId, plans] of this.#streamingWatchPlansBySourceNodeId) {
2735
+ for (const [sourceNodeId, plans] of this.#boundaries.streamingWatchPlansBySourceNodeId) {
2815
2736
  for (const plan of plans) {
2816
2737
  if (sourceNodeId === node.id || plan.graph.nodes.some((branchNode) => branchNode.id === node.id)) {
2817
2738
  throw new Error(`Cannot preload ${node.title} while Watch Streaming Output "${plan.watchNode.title}" is running. ` +
@@ -2826,12 +2747,12 @@ export class GraphProcessor {
2826
2747
  if (!node || !this.#isNodeSelected(node.id) || node.id === this.#consumedStreamingWatchNodeId) {
2827
2748
  continue;
2828
2749
  }
2829
- if (this.#isStreamingOutputWatchBoundary(node)) {
2750
+ if (this.#isStreamingOutputWatchBoundary(node) && node.type !== 'catchStreamingChunks') {
2830
2751
  throw new Error(`Cannot preload ${node.title} because a streaming boundary must be scheduled. ` +
2831
2752
  "Run from Watch Streaming Output to reuse a producer's saved final value, or run from the producer to stream again.");
2832
2753
  }
2833
2754
  }
2834
- for (const [sourceNodeId, plans] of this.#streamingWatchPlansBySourceNodeId) {
2755
+ for (const [sourceNodeId, plans] of this.#boundaries.streamingWatchPlansBySourceNodeId) {
2835
2756
  const sourceOutputs = this.#preloadedNodeResults.get(sourceNodeId);
2836
2757
  for (const plan of plans) {
2837
2758
  const preloadedBranchNode = plan.graph.nodes.find((node) => node.id !== this.#consumedStreamingWatchNodeId && this.#preloadedNodeResults.has(node.id));
@@ -2849,12 +2770,23 @@ export class GraphProcessor {
2849
2770
  }
2850
2771
  }
2851
2772
  #publishStreamingOutputWatchPartial(node, partialOutputs, coalesced = 0) {
2852
- for (const plan of this.#streamingWatchPlansBySourceNodeId.get(node.id) ?? []) {
2773
+ for (const plan of this.#boundaries.streamingCatchPlansBySourceNodeId.get(node.id) ?? []) {
2774
+ if (plan.settled)
2775
+ continue;
2776
+ const value = partialOutputs[plan.sourceOutputId];
2777
+ if (!value || value.type === 'control-flow-excluded')
2778
+ continue;
2779
+ const chunk = cloneExecutionOutputs({ ['value']: value })['value'];
2780
+ plan.chunks.push(chunk);
2781
+ if (plan.chunks.length >= plan.count)
2782
+ this.#scheduleStreamingCatchCompletion(plan);
2783
+ }
2784
+ for (const plan of this.#boundaries.streamingWatchPlansBySourceNodeId.get(node.id) ?? []) {
2853
2785
  const value = partialOutputs[plan.sourceOutputId];
2854
2786
  if (value == null || value.type === 'control-flow-excluded') {
2855
2787
  continue;
2856
2788
  }
2857
- const watch = this.#streamingOutputWatches.get(plan.watchNode.id);
2789
+ const watch = this.#boundaries.streamingOutputWatches.get(plan.watchNode.id);
2858
2790
  if (!watch || watch.stopped) {
2859
2791
  continue;
2860
2792
  }
@@ -2864,13 +2796,45 @@ export class GraphProcessor {
2864
2796
  watch.publish(this.#createStreamingOutputWatchSnapshot(plan, value, updateIndex, false));
2865
2797
  }
2866
2798
  }
2799
+ #scheduleStreamingCatchCompletion(plan) {
2800
+ if (plan.settled)
2801
+ return;
2802
+ plan.settled = true;
2803
+ const task = this.#completeStreamingCatch(plan).catch((error) => this.#nodeErrored(plan.node, error, nanoid()));
2804
+ this.#boundaries.streamingCatchTasks.add(task);
2805
+ void task.then(() => this.#boundaries.streamingCatchTasks.delete(task), () => this.#boundaries.streamingCatchTasks.delete(task));
2806
+ }
2807
+ async #completeStreamingCatch(plan) {
2808
+ if (this.#run.abortController.signal.aborted)
2809
+ return;
2810
+ const node = plan.node;
2811
+ const processId = nanoid();
2812
+ const chunks = plan.chunks.slice(0, plan.count);
2813
+ const output = plan.count === 1 ? chunks[0] : { type: 'any[]', value: chunks.map((chunk) => chunk.value) };
2814
+ const outputs = { ['value']: output };
2815
+ plan.chunks.length = 0;
2816
+ await this.#emitter.emit('nodeStart', this.#withExecution({ node, inputs: {}, processId, resultOrigin: 'executed' }));
2817
+ if (this.#run.abortController.signal.aborted)
2818
+ return;
2819
+ this.#run.nodeResults.set(node.id, outputs);
2820
+ this.#run.visitedNodes.add(node.id);
2821
+ this.#run.remainingNodes.delete(node.id);
2822
+ await this.#emitter.emit('nodeFinish', this.#withExecution({ node, outputs, processId, resultOrigin: 'executed' }));
2823
+ this.#finishStreamingOutputWatches(node, outputs);
2824
+ const outputNodes = getOutputNodesFrom(this.#executionState, node);
2825
+ this.#propagateAttachedDataToOutputNodes(node, this.#getAttachedDataTo(node), outputNodes.connectionsToNodes);
2826
+ this.#queueOutputNodes(node, outputNodes.nodes);
2827
+ }
2828
+ async #drainStreamingCatchTasks() {
2829
+ await this.#boundaries.drainCatchTasks(() => this.#run.processingQueue.onIdle());
2830
+ }
2867
2831
  #prepareGraphInputStreamRoutes() {
2868
2832
  if (!this.#executionGraphNodes.some((node) => canStreamThroughGraphCaller(node) && this.#isNodeSelected(node.id)))
2869
2833
  return;
2870
2834
  const marked = getProjectStreamingOutputWatchConnections({
2871
2835
  project: this.#project,
2872
2836
  graph: this.#graph,
2873
- referencedProjects: this.#loadedProjects,
2837
+ referencedProjects: this.#run.loadedProjects,
2874
2838
  registry: this.#registry,
2875
2839
  fullGraphCallers: new Set(this.runToNodeIds ?? []),
2876
2840
  isNodeFrozen: (_owner, candidate, node) => this.#frozenNodeOutputResolver != null &&
@@ -2904,39 +2868,39 @@ export class GraphProcessor {
2904
2868
  continue;
2905
2869
  const relay = new GraphInputStreamRelay();
2906
2870
  streams[edge.inputId] = relay;
2907
- const routes = this.#inputStreamRoutes.get(source.id) ?? [];
2871
+ const routes = this.#boundaries.inputStreamRoutes.get(source.id) ?? [];
2908
2872
  routes.push({ port: edge.outputId, relay });
2909
- this.#inputStreamRoutes.set(source.id, routes);
2873
+ this.#boundaries.inputStreamRoutes.set(source.id, routes);
2910
2874
  }
2911
2875
  if (Object.keys(streams).length)
2912
- this.#callerInputStreams.set(node.id, streams);
2876
+ this.#boundaries.callerInputStreams.set(node.id, streams);
2913
2877
  }
2914
2878
  const abort = () => {
2915
- const error = createGraphAbortErrorFromSignal(this.#abortController.signal);
2916
- for (const streams of this.#callerInputStreams.values()) {
2879
+ const error = createGraphAbortErrorFromSignal(this.#run.abortController.signal);
2880
+ for (const streams of this.#boundaries.callerInputStreams.values()) {
2917
2881
  for (const relay of Object.values(streams))
2918
2882
  relay.finish({ error });
2919
2883
  }
2920
2884
  };
2921
- this.#abortController.signal.addEventListener('abort', abort, { once: true });
2922
- this.#inputStreamDisposers.push(() => this.#abortController.signal.removeEventListener('abort', abort));
2885
+ this.#run.abortController.signal.addEventListener('abort', abort, { once: true });
2886
+ this.#boundaries.inputStreamDisposers.push(() => this.#run.abortController.signal.removeEventListener('abort', abort));
2923
2887
  }
2924
2888
  #publishGraphInputStreamPartial(node, outputs, coalesced = 0) {
2925
- for (const { port, relay } of this.#inputStreamRoutes.get(node.id) ?? []) {
2889
+ for (const { port, relay } of this.#boundaries.inputStreamRoutes.get(node.id) ?? []) {
2926
2890
  const value = outputs[port];
2927
2891
  if (value && value.type !== 'control-flow-excluded')
2928
2892
  relay.publish(value, coalesced);
2929
2893
  }
2930
2894
  }
2931
2895
  #subscribeGraphInputStreams() {
2932
- for (const [name, stream] of Object.entries(this.#graphInputStreams)) {
2896
+ for (const [name, stream] of Object.entries(this.#boundaries.graphInputStreams)) {
2933
2897
  const inputs = this.#executionGraphNodes.filter((node) => node.type === 'graphInput' &&
2934
2898
  node.data.id === name &&
2935
2899
  !node.disabled &&
2936
2900
  this.#isNodeSelected(node.id));
2937
2901
  let active = true;
2938
2902
  const unsubscribe = stream.subscribe((value, coalesced) => {
2939
- if (!active || this.#abortController.signal.aborted)
2903
+ if (!active || this.#run.abortController.signal.aborted)
2940
2904
  return;
2941
2905
  for (const node of inputs) {
2942
2906
  if (!canStreamThroughGraphInput(node) || this.#hasFrozenNodeOutputOrUnknownResolver(node))
@@ -2948,28 +2912,28 @@ export class GraphProcessor {
2948
2912
  this.#publishGraphInputStreamPartial(node, output, coalesced);
2949
2913
  }
2950
2914
  });
2951
- this.#inputStreamDisposers.push(() => {
2915
+ this.#boundaries.inputStreamDisposers.push(() => {
2952
2916
  active = false;
2953
2917
  unsubscribe();
2954
2918
  });
2955
2919
  void stream.settled.then((result) => {
2956
- if (!active || this.#abortController.signal.aborted)
2920
+ if (!active || this.#run.abortController.signal.aborted)
2957
2921
  return;
2958
2922
  if (result.value)
2959
- this.#graphInputs[name] = result.value;
2923
+ this.#run.graphInputs[name] = result.value;
2960
2924
  for (const node of inputs)
2961
- void this.#processingQueue.add(() => this.#processNodeIfAllInputsAvailable(node));
2925
+ void this.#run.processingQueue.add(() => this.#processNodeIfAllInputsAvailable(node));
2962
2926
  });
2963
2927
  }
2964
2928
  }
2965
2929
  async #waitForGraphInputStreams() {
2966
- const signal = this.#abortController.signal;
2930
+ const signal = this.#run.abortController.signal;
2967
2931
  if (signal.aborted)
2968
2932
  throw createGraphAbortErrorFromSignal(signal);
2969
2933
  let abort;
2970
2934
  try {
2971
2935
  await Promise.race([
2972
- Promise.all(Object.values(this.#graphInputStreams).map((stream) => stream.settled)),
2936
+ Promise.all(Object.values(this.#boundaries.graphInputStreams).map((stream) => stream.settled)),
2973
2937
  new Promise((_resolve, reject) => {
2974
2938
  abort = () => reject(createGraphAbortErrorFromSignal(signal));
2975
2939
  signal.addEventListener('abort', abort, { once: true });
@@ -3016,13 +2980,13 @@ export class GraphProcessor {
3016
2980
  !canForwardGraphOutputPartials(graphOutput, sourceNode, this.#hasFrozenNodeOutputOrUnknownResolver(graphOutput))) {
3017
2981
  continue;
3018
2982
  }
3019
- const bindings = this.#graphOutputPartialBindingsBySourceNodeId.get(connection.outputNodeId) ?? [];
2983
+ const bindings = this.#boundaries.graphOutputPartialBindingsBySourceNodeId.get(connection.outputNodeId) ?? [];
3020
2984
  bindings.push({
3021
2985
  dataType: graphOutputData.dataType,
3022
2986
  graphOutputId: graphOutputData.id,
3023
2987
  sourceOutputId: connection.outputId,
3024
2988
  });
3025
- this.#graphOutputPartialBindingsBySourceNodeId.set(connection.outputNodeId, bindings);
2989
+ this.#boundaries.graphOutputPartialBindingsBySourceNodeId.set(connection.outputNodeId, bindings);
3026
2990
  }
3027
2991
  }
3028
2992
  #hasFrozenNodeOutputOrUnknownResolver(node) {
@@ -3044,7 +3008,7 @@ export class GraphProcessor {
3044
3008
  */
3045
3009
  #publishGraphOutputPartial(node, partialOutputs) {
3046
3010
  const listener = this.#graphOutputPartialListener;
3047
- const bindings = this.#graphOutputPartialBindingsBySourceNodeId.get(node.id);
3011
+ const bindings = this.#boundaries.graphOutputPartialBindingsBySourceNodeId.get(node.id);
3048
3012
  if (!listener || !bindings) {
3049
3013
  return;
3050
3014
  }
@@ -3062,31 +3026,47 @@ export class GraphProcessor {
3062
3026
  }
3063
3027
  #finishStreamingOutputWatches(node, outputs) {
3064
3028
  if (node.type === 'graphInput') {
3065
- const terminals = Object.values(this.#graphInputStreams).map((stream) => stream.result);
3029
+ const terminals = Object.values(this.#boundaries.graphInputStreams).map((stream) => stream.result);
3066
3030
  if (terminals.some((result) => !result)) {
3067
3031
  // Defaults/non-streamed arguments may be needed for caller startup, but
3068
3032
  // their final Watch delivery must not release ordinary nested work early.
3069
- this.#pendingGraphInputFinals.set(node.id, cloneExecutionOutputs(outputs));
3033
+ this.#boundaries.pendingGraphInputFinals.set(node.id, cloneExecutionOutputs(outputs));
3070
3034
  return;
3071
3035
  }
3072
3036
  const failure = terminals.find((result) => result?.error);
3073
3037
  if (failure?.error) {
3074
- for (const route of this.#inputStreamRoutes.get(node.id) ?? [])
3038
+ for (const route of this.#boundaries.inputStreamRoutes.get(node.id) ?? [])
3075
3039
  route.relay.finish({ error: failure.error });
3076
3040
  this.#cancelStreamingOutputWatchesForSource(node.id);
3041
+ this.#cancelStreamingCatchesForSource(node.id);
3077
3042
  return;
3078
3043
  }
3079
3044
  if (terminals.some((result) => result?.value?.type === 'control-flow-excluded')) {
3080
3045
  outputs = Object.fromEntries(Object.keys(outputs).map((port) => [port, { type: 'control-flow-excluded', value: undefined }]));
3081
3046
  }
3082
3047
  }
3083
- for (const { port, relay } of this.#inputStreamRoutes.get(node.id) ?? []) {
3048
+ for (const plan of this.#boundaries.streamingCatchPlansBySourceNodeId.get(node.id) ?? []) {
3049
+ if (plan.settled)
3050
+ continue;
3051
+ const finalValue = outputs[plan.sourceOutputId];
3052
+ if (finalValue && finalValue.type !== 'control-flow-excluded' && !isEqual(plan.chunks.at(-1), finalValue)) {
3053
+ plan.chunks.push(cloneExecutionOutputs({ ['value']: finalValue })['value']);
3054
+ }
3055
+ if (plan.chunks.length > 0) {
3056
+ this.#scheduleStreamingCatchCompletion(plan);
3057
+ }
3058
+ else {
3059
+ plan.settled = true;
3060
+ this.#excludeNode(plan.node, nanoid(), {}, 'stream completed without a value');
3061
+ }
3062
+ }
3063
+ for (const { port, relay } of this.#boundaries.inputStreamRoutes.get(node.id) ?? []) {
3084
3064
  const value = outputs[port];
3085
3065
  relay.finish(value ? { value } : { error: new Error(`Missing final streamed output ${port}`) });
3086
3066
  }
3087
- for (const plan of this.#streamingWatchPlansBySourceNodeId.get(node.id) ?? []) {
3067
+ for (const plan of this.#boundaries.streamingWatchPlansBySourceNodeId.get(node.id) ?? []) {
3088
3068
  const value = outputs[plan.sourceOutputId];
3089
- const watch = this.#streamingOutputWatches.get(plan.watchNode.id);
3069
+ const watch = this.#boundaries.streamingOutputWatches.get(plan.watchNode.id);
3090
3070
  if (!watch || watch.stopped) {
3091
3071
  continue;
3092
3072
  }
@@ -3107,8 +3087,8 @@ export class GraphProcessor {
3107
3087
  }
3108
3088
  }
3109
3089
  #assertStreamingOutputWatchFinalOutputs(node, outputs) {
3110
- for (const plan of this.#streamingWatchPlansBySourceNodeId.get(node.id) ?? []) {
3111
- const watch = this.#streamingOutputWatches.get(plan.watchNode.id);
3090
+ for (const plan of this.#boundaries.streamingWatchPlansBySourceNodeId.get(node.id) ?? []) {
3091
+ const watch = this.#boundaries.streamingOutputWatches.get(plan.watchNode.id);
3112
3092
  if (!watch || watch.stopped || outputs[plan.sourceOutputId] != null) {
3113
3093
  continue;
3114
3094
  }
@@ -3175,116 +3155,83 @@ export class GraphProcessor {
3175
3155
  }
3176
3156
  async #runStreamingOutputWatchInvocation(plan, snapshot, registerCancel) {
3177
3157
  const root = this.getRootProcessor();
3178
- if (root.#abortController.signal.aborted) {
3179
- throw createGraphAbortErrorFromSignal(root.#abortController.signal, 'Streaming watch branch aborted before it started');
3158
+ if (root.#run.abortController.signal.aborted) {
3159
+ throw createGraphAbortErrorFromSignal(root.#run.abortController.signal, 'Streaming watch branch aborted before it started');
3180
3160
  }
3181
3161
  const graphId = plan.graph.metadata?.id;
3182
3162
  if (!graphId) {
3183
3163
  throw new Error('Cannot start a streaming watch branch because the current graph has no ID.');
3184
3164
  }
3185
3165
  const historyIteration = plan.history.start(nanoid(), snapshot.updateIndex);
3186
- const branchRuntimeCache = {
3187
- ...this.#runtimeCache,
3188
- graphBoundaries: undefined,
3189
- loadedProjects: { ...this.#loadedProjects },
3190
- };
3191
- const processor = new GraphProcessor(this.#project, graphId, this.#registry, this.#includeTrace, {
3192
- cacheLoadedProjects: true,
3193
- captureNodeTimings: this.#captureNodeTimings,
3194
- concurrency: this.#concurrency,
3195
- executionPlanCacheMode: this.#executionPlanCacheMode,
3196
- runtimeCache: branchRuntimeCache,
3197
- runtimeProfiler: this.#runtimeProfiler,
3198
- scheduler: this.#scheduler,
3199
- [consumedStreamingWatchNodeOverride]: plan.watchNode.id,
3200
- [graphProcessorGraphOverride]: plan.graph,
3201
- });
3202
- processor.executor = this.executor;
3203
- processor.#isSubProcessor = true;
3204
- processor.#executionCache = this.#executionCache;
3205
- processor.#externalFunctions = this.#externalFunctions;
3206
- processor.#contextValues = this.#contextValues;
3207
- processor.#parent = this;
3208
- processor.#graphCallPath = this.#graphCallPath;
3209
- processor.#abortOwnerOverride = root;
3210
- processor.#suppressGraphPartialOutputs = true;
3211
- processor.#globals = this.#globals;
3212
- processor.#storedValueController = this.#storedValueController;
3213
- processor.#knowledgeStoreController = this.#knowledgeStoreController;
3214
- processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
3215
- processor.#executor = this.#executor;
3216
- processor.#suppressGraphLifecycleEvents = true;
3217
- processor.#sharedRunStateOverride = {
3218
- // Repeated node IDs do not imply shared race/loop state between snapshots.
3219
- attachedNodeData: new Map(),
3220
- graphInputNodeValues: { ...this.#graphInputNodeValues },
3221
- graphOutputs: {},
3222
- };
3223
- processor.#executionIdentityOverride = {
3224
- rootRunId: root.#rootRunId,
3225
- graphRunId: historyIteration.graphRunId,
3226
- parentGraphRunId: this.#graphRunId,
3227
- };
3228
- processor.#streamingWatchInvocation = {
3229
- plan,
3230
- historyIteration,
3231
- claimStop: (value) => this.#claimAcceptedStreamingWatchStop(plan, historyIteration, value, snapshot.updateIndex),
3232
- stopReached: false,
3233
- };
3234
- processor.preloadNodeData(plan.watchNode.id, this.#materializeStreamingOutputWatchSnapshot(snapshot));
3235
- processor.#suppressedPreloadedNodeIds.add(plan.watchNode.id);
3166
+ let processor;
3167
+ let unwireEvents;
3168
+ let unwireLifecycle;
3236
3169
  let cancellationRequested = false;
3237
- registerCancel(() => {
3238
- cancellationRequested = true;
3239
- if (processor.isRunning) {
3240
- void processor.abort(true);
3241
- }
3242
- });
3243
- const unwireEvents = wireSubprocessorEvents(processor, root.#emitter, {
3244
- autoCleanup: false,
3245
- isPaused: () => root.#lifecycle.isPaused,
3246
- pause: () => {
3247
- void root.pause();
3248
- },
3249
- resume: () => {
3250
- void root.resume();
3251
- },
3252
- forwardEvent: (event, data) => {
3253
- // Interactive/global control events are side effects, not execution
3254
- // history. They must remain live even when their enclosing iteration
3255
- // is not selected for retained evidence.
3256
- if (event === 'userInput' ||
3257
- event === 'globalSet' ||
3258
- event === 'newAbortController' ||
3259
- event.startsWith('globalSet:')) {
3260
- return root.#emitter.emit(event, data);
3261
- }
3262
- return plan.history.forward(historyIteration, event, data, (nextEvent, nextData) => root.#emitter.emit(nextEvent, nextData));
3263
- },
3264
- });
3265
- const unwireLifecycle = wireSubprocessorLifecycle(processor, {
3266
- autoCleanup: false,
3267
- signal: this.#abortController.signal,
3268
- parentAbortSignal: root.#abortController.signal,
3269
- onParentPause: (listener) => {
3270
- root.on('pause', listener);
3271
- return () => root.off('pause', listener);
3272
- },
3273
- onParentResume: (listener) => {
3274
- root.on('resume', listener);
3275
- return () => root.off('resume', listener);
3276
- },
3277
- });
3278
- root.#subprocessors.add(processor);
3170
+ let executionFailed = true;
3279
3171
  try {
3172
+ processor = this.#constructChildInvocation({
3173
+ kind: 'watch',
3174
+ graph: plan.graph,
3175
+ watchNodeId: plan.watchNode.id,
3176
+ });
3177
+ processor.#abortOwnerOverride = root;
3178
+ processor.#suppressGraphPartialOutputs = true;
3179
+ processor.#suppressGraphLifecycleEvents = true;
3180
+ processor.#sharedRunStateOverride = {
3181
+ // Repeated node IDs do not imply shared race/loop state between snapshots.
3182
+ attachedNodeData: new Map(),
3183
+ graphInputNodeValues: { ...this.#run.graphInputNodeValues },
3184
+ graphOutputs: {},
3185
+ };
3186
+ processor.#executionIdentityOverride = {
3187
+ rootRunId: root.#run.rootRunId,
3188
+ graphRunId: historyIteration.graphRunId,
3189
+ parentGraphRunId: this.#run.graphRunId,
3190
+ };
3191
+ processor.#streamingWatchInvocation = {
3192
+ plan,
3193
+ historyIteration,
3194
+ claimStop: (value) => this.#claimAcceptedStreamingWatchStop(plan, historyIteration, value, snapshot.updateIndex),
3195
+ stopReached: false,
3196
+ };
3197
+ processor.preloadNodeData(plan.watchNode.id, this.#materializeStreamingOutputWatchSnapshot(snapshot));
3198
+ processor.#suppressedPreloadedNodeIds.add(plan.watchNode.id);
3199
+ const watchProcessor = processor;
3200
+ registerCancel(() => {
3201
+ cancellationRequested = true;
3202
+ if (watchProcessor.isRunning) {
3203
+ void watchProcessor.abort(true);
3204
+ }
3205
+ });
3206
+ unwireEvents = this.#wireChildEvents(processor, root, {
3207
+ autoCleanup: false,
3208
+ forwardEvent: (event, data) => {
3209
+ // Interactive/global control events are side effects, not execution
3210
+ // history. They must remain live even when their enclosing iteration
3211
+ // is not selected for retained evidence.
3212
+ if (event === 'userInput' ||
3213
+ event === 'globalSet' ||
3214
+ event === 'newAbortController' ||
3215
+ event.startsWith('globalSet:')) {
3216
+ return root.#emitter.emit(event, data);
3217
+ }
3218
+ return plan.history.forward(historyIteration, event, data, (nextEvent, nextData) => root.#emitter.emit(nextEvent, nextData));
3219
+ },
3220
+ });
3221
+ unwireLifecycle = this.#wireChildLifecycle(processor, root, unwireEvents, {
3222
+ autoCleanup: false,
3223
+ signal: this.#run.abortController.signal,
3224
+ });
3225
+ root.#run.subprocessors.add(processor);
3280
3226
  if (root.#lifecycle.isPaused) {
3281
3227
  processor.pause();
3282
3228
  }
3283
- await processor.processGraph(this.#context, this.#graphInputs, this.#contextValues);
3229
+ await processor.processGraph(this.#run.context, this.#run.graphInputs, this.#contextValues);
3230
+ executionFailed = false;
3284
3231
  }
3285
3232
  catch (error) {
3286
3233
  const normalizedError = getError(error);
3287
- const wasCancelled = isAbortLikeError(normalizedError) || root.#abortController.signal.aborted || cancellationRequested;
3234
+ const wasCancelled = isAbortLikeError(normalizedError) || root.#run.abortController.signal.aborted || cancellationRequested;
3288
3235
  if (wasCancelled) {
3289
3236
  plan.history.cancel(historyIteration);
3290
3237
  }
@@ -3303,10 +3250,10 @@ export class GraphProcessor {
3303
3250
  plan.history.cancel(historyIteration);
3304
3251
  }
3305
3252
  plan.history.complete(historyIteration);
3306
- this.#totalCost += processor.#totalCost;
3307
- unwireLifecycle();
3308
- unwireEvents();
3309
- root.#subprocessors.delete(processor);
3253
+ if (processor) {
3254
+ this.#accumulateChildCost(processor);
3255
+ this.#releaseChildInvocation(processor, root, unwireLifecycle, unwireEvents, executionFailed);
3256
+ }
3310
3257
  }
3311
3258
  }
3312
3259
  #claimStreamingWatchStopFromInvocation(node, outputs) {
@@ -3325,7 +3272,7 @@ export class GraphProcessor {
3325
3272
  if (!stopNodeId) {
3326
3273
  return undefined;
3327
3274
  }
3328
- const watch = this.#streamingOutputWatches.get(plan.watchNode.id);
3275
+ const watch = this.#boundaries.streamingOutputWatches.get(plan.watchNode.id);
3329
3276
  if (!watch || watch.stopped) {
3330
3277
  return undefined;
3331
3278
  }
@@ -3342,9 +3289,9 @@ export class GraphProcessor {
3342
3289
  if (committed)
3343
3290
  return;
3344
3291
  committed = true;
3345
- this.#nodeResults.set(stopNode.id, { ['value']: acceptedValue });
3346
- this.#visitedNodes.add(stopNode.id);
3347
- this.#remainingNodes.delete(stopNode.id);
3292
+ this.#run.nodeResults.set(stopNode.id, { ['value']: acceptedValue });
3293
+ this.#run.visitedNodes.add(stopNode.id);
3294
+ this.#run.remainingNodes.delete(stopNode.id);
3348
3295
  const attachedData = this.#getAttachedDataTo(stopNode);
3349
3296
  const outputNodes = getOutputNodesFrom(this.#executionState, stopNode);
3350
3297
  this.#propagateAttachedDataToOutputNodes(stopNode, attachedData, outputNodes.connectionsToNodes);
@@ -3353,53 +3300,63 @@ export class GraphProcessor {
3353
3300
  };
3354
3301
  }
3355
3302
  #cancelStreamingOutputWatchesForSource(nodeId) {
3356
- for (const plan of this.#streamingWatchPlansBySourceNodeId.get(nodeId) ?? []) {
3357
- this.#streamingOutputWatches.get(plan.watchNode.id)?.stop();
3303
+ for (const plan of this.#boundaries.streamingWatchPlansBySourceNodeId.get(nodeId) ?? []) {
3304
+ this.#boundaries.streamingOutputWatches.get(plan.watchNode.id)?.stop();
3305
+ }
3306
+ }
3307
+ #cancelStreamingCatchesForSource(nodeId) {
3308
+ for (const plan of this.#boundaries.streamingCatchPlansBySourceNodeId.get(nodeId) ?? []) {
3309
+ if (plan.settled)
3310
+ continue;
3311
+ plan.settled = true;
3312
+ plan.chunks.length = 0;
3358
3313
  }
3359
3314
  }
3360
3315
  #cancelStreamingOutputWatches() {
3361
- for (const watch of this.#streamingOutputWatches.values()) {
3316
+ for (const watch of this.#boundaries.streamingOutputWatches.values()) {
3362
3317
  watch.stop();
3363
3318
  }
3364
3319
  }
3365
3320
  #hasPendingStreamingOutputWatches() {
3366
- return [...this.#streamingOutputWatches.values()].some((watch) => watch.hasPending);
3321
+ return [...this.#boundaries.streamingOutputWatches.values()].some((watch) => watch.hasPending);
3367
3322
  }
3368
3323
  #hasUnresolvedForegroundOutputStreamingWatch() {
3369
- return [...this.#streamingOutputWatches].some(([watchNodeId, watch]) => {
3370
- const plan = this.#streamingWatchPlansByWatchNodeId.get(watchNodeId);
3324
+ return [...this.#boundaries.streamingOutputWatches].some(([watchNodeId, watch]) => {
3325
+ const plan = this.#boundaries.streamingWatchPlansByWatchNodeId.get(watchNodeId);
3371
3326
  return plan?.stopNodeId != null && !plan.unmatchedStopResolved && !watch.stopped;
3372
3327
  });
3373
3328
  }
3374
3329
  #hasDrainableStreamingOutputWatches() {
3375
- return [...this.#streamingOutputWatches.values()].some((watch) => watch.hasPending && !watch.isAwaitingProducer);
3330
+ return [...this.#boundaries.streamingOutputWatches.values()].some((watch) => watch.hasPending && !watch.isAwaitingProducer);
3376
3331
  }
3377
3332
  async #drainSchedulerBoundaries() {
3378
3333
  do {
3334
+ await this.#drainStreamingCatchTasks();
3379
3335
  if (!this.#isSubProcessor) {
3380
3336
  await this.#profileRuntimeAsync('drainManagedAsyncBranches', () => this.#managedAsyncBranches.drain());
3381
3337
  }
3382
3338
  await this.#profileRuntimeAsync('drainStreamingOutputWatches', () => this.#drainStreamingOutputWatches());
3383
3339
  } while ((!this.#isSubProcessor && this.#managedAsyncBranches.hasPending) ||
3384
- this.#hasDrainableStreamingOutputWatches());
3340
+ this.#hasDrainableStreamingOutputWatches() ||
3341
+ this.#boundaries.streamingCatchTasks.size > 0);
3385
3342
  }
3386
3343
  async #drainStreamingOutputWatches() {
3387
3344
  do {
3388
- for (const watch of this.#streamingOutputWatches.values()) {
3345
+ for (const watch of this.#boundaries.streamingOutputWatches.values()) {
3389
3346
  await watch.drain();
3390
3347
  }
3391
3348
  // Accepting Stop happens in a child run. It can enqueue ordinary parent
3392
3349
  // work after the compatible scheduler has returned, so wait for that work
3393
3350
  // before deciding every Watch boundary is quiet.
3394
- await this.#processingQueue.onIdle();
3351
+ await this.#run.processingQueue.onIdle();
3395
3352
  this.#resolveUnmatchedStreamingWatchStops();
3396
3353
  // Excluding the parent Stop queues its ordinary downstream nodes. Let
3397
3354
  // their normal control-flow rules run before emitting the settled Watch
3398
3355
  // summary or finalizing the root graph.
3399
- await this.#processingQueue.onIdle();
3356
+ await this.#run.processingQueue.onIdle();
3400
3357
  } while (this.#hasDrainableStreamingOutputWatches());
3401
- for (const [watchNodeId, watch] of this.#streamingOutputWatches) {
3402
- const plan = this.#streamingWatchPlansByWatchNodeId.get(watchNodeId);
3358
+ for (const [watchNodeId, watch] of this.#boundaries.streamingOutputWatches) {
3359
+ const plan = this.#boundaries.streamingWatchPlansByWatchNodeId.get(watchNodeId);
3403
3360
  if (!plan || plan.historySummaryEmitted || !watch.isSettled)
3404
3361
  continue;
3405
3362
  const summary = await plan.history.finalize(watch.runtimeSummary, (event, data) => this.#emitter.emit(event, data));
@@ -3408,8 +3365,8 @@ export class GraphProcessor {
3408
3365
  }
3409
3366
  }
3410
3367
  #resolveUnmatchedStreamingWatchStops() {
3411
- for (const [watchNodeId, watch] of this.#streamingOutputWatches) {
3412
- const plan = this.#streamingWatchPlansByWatchNodeId.get(watchNodeId);
3368
+ for (const [watchNodeId, watch] of this.#boundaries.streamingOutputWatches) {
3369
+ const plan = this.#boundaries.streamingWatchPlansByWatchNodeId.get(watchNodeId);
3413
3370
  if (!plan?.stopNodeId || plan.unmatchedStopResolved || !watch.finishedNormally) {
3414
3371
  continue;
3415
3372
  }
@@ -3422,97 +3379,23 @@ export class GraphProcessor {
3422
3379
  }
3423
3380
  }
3424
3381
  #prepareAsyncBranchTopology() {
3425
- const connections = this.#getEffectiveConnections().filter((connection) => this.#isDefinitionValidConnection(connection));
3426
- const outgoingByNodeId = new Map();
3427
- const incomingByNodeId = new Map();
3428
- const relevantNodeIds = this.#getExecutionRelevantNodeIds();
3429
- const isRelevant = (nodeId) => !relevantNodeIds || relevantNodeIds.has(nodeId);
3430
- for (const connection of connections) {
3431
- const outgoing = outgoingByNodeId.get(connection.outputNodeId) ?? [];
3432
- outgoing.push(connection);
3433
- outgoingByNodeId.set(connection.outputNodeId, outgoing);
3434
- const incoming = incomingByNodeId.get(connection.inputNodeId) ?? [];
3435
- incoming.push(connection);
3436
- incomingByNodeId.set(connection.inputNodeId, incoming);
3437
- }
3438
- for (const triggerNode of Object.values(this.#nodesById)) {
3439
- // Input anchors describe the consumed trigger's ports, not executable work.
3440
- // A variadic anchor may itself be an outer async trigger.
3441
- if (this.#asyncBranchInputAnchors?.[triggerNode.id])
3442
- continue;
3443
- if (triggerNode.type !== 'startBackgroundBranch' || triggerNode.disabled || !isRelevant(triggerNode.id)) {
3444
- continue;
3445
- }
3446
- if (triggerNode.id !== this.#consumedAsyncBranchTriggerNodeId && this.#nodeResults.has(triggerNode.id)) {
3447
- throw new Error(`Start Async Branch "${triggerNode.title}" cannot use preloaded outputs because replaying it could repeat async side effects.`);
3448
- }
3449
- const nodeIds = new Set();
3450
- const pendingNodeIds = (outgoingByNodeId.get(triggerNode.id) ?? [])
3451
- .map((connection) => connection.inputNodeId)
3452
- .filter(isRelevant);
3453
- while (pendingNodeIds.length > 0) {
3454
- const nodeId = pendingNodeIds.pop();
3455
- if (nodeId === triggerNode.id) {
3456
- throw new Error(`Start Async Branch "${triggerNode.title}" cannot be part of a cycle or reconnect to its own inputs.`);
3457
- }
3458
- if (nodeIds.has(nodeId)) {
3459
- continue;
3460
- }
3461
- const node = this.#nodesById[nodeId];
3462
- if (!node) {
3463
- continue;
3464
- }
3465
- if (node.disabled) {
3466
- continue;
3467
- }
3468
- if (node.type === 'graphOutput') {
3469
- throw new Error(`Start Async Branch "${triggerNode.title}" cannot contain Graph Output node "${node.title}". Async branches are side-effect-only.`);
3470
- }
3471
- nodeIds.add(nodeId);
3472
- for (const connection of outgoingByNodeId.get(nodeId) ?? []) {
3473
- if (isRelevant(connection.inputNodeId)) {
3474
- pendingNodeIds.push(connection.inputNodeId);
3475
- }
3476
- }
3477
- }
3478
- for (const nodeId of nodeIds) {
3479
- const externalInput = (incomingByNodeId.get(nodeId) ?? []).find((connection) => connection.outputNodeId !== triggerNode.id && !nodeIds.has(connection.outputNodeId));
3480
- if (externalInput) {
3481
- const node = this.#nodesById[nodeId];
3482
- const externalNode = this.#nodesById[externalInput.outputNodeId];
3483
- throw new Error(`Start Async Branch "${triggerNode.title}" cannot run "${node.title}" because it also depends on ` +
3484
- `"${externalNode?.title ?? externalInput.outputNodeId}" outside the async branch. Assemble all required values before the async trigger.`);
3485
- }
3486
- }
3487
- if (nodeIds.size === 0) {
3488
- continue;
3489
- }
3490
- const managedAsyncBranchWatchViolation = this.#getManagedAsyncBranchWatchViolation(triggerNode);
3491
- if (managedAsyncBranchWatchViolation) {
3492
- throw managedAsyncBranchWatchViolation;
3493
- }
3494
- const preloadedNodeId = [...nodeIds].find((nodeId) => this.#nodeResults.has(nodeId));
3495
- if (preloadedNodeId) {
3496
- const preloadedNode = this.#nodesById[preloadedNodeId];
3497
- throw new Error(`Start Async Branch "${triggerNode.title}" cannot contain preloaded node "${preloadedNode.title}". Preloading an async descendant would bypass the trigger boundary.`);
3498
- }
3499
- // The node derives its variadic output definitions from connected inputs.
3500
- // Retain shallow input anchors in the slice even though the trigger itself is preloaded.
3501
- const triggerInputConnections = connections.filter((connection) => connection.inputNodeId === triggerNode.id);
3502
- const inputAnchorNodeIds = new Set(triggerInputConnections.map((connection) => connection.outputNodeId));
3503
- const includedNodeIds = new Set([triggerNode.id, ...nodeIds, ...inputAnchorNodeIds]);
3504
- const graph = {
3505
- metadata: this.#graph.metadata ? { ...this.#graph.metadata } : undefined,
3506
- nodes: this.#executionGraphNodes.filter((node) => includedNodeIds.has(node.id)),
3507
- connections: connections.filter((connection) => connection.inputNodeId === triggerNode.id ||
3508
- (nodeIds.has(connection.inputNodeId) &&
3509
- (connection.outputNodeId === triggerNode.id || nodeIds.has(connection.outputNodeId)))),
3510
- };
3382
+ for (const { triggerNode, graph, nodeIds } of planAsyncBranchTopology({
3383
+ graph: this.#graph,
3384
+ executionNodes: this.#executionGraphNodes,
3385
+ nodesById: this.#nodesById,
3386
+ connections: this.#getEffectiveConnections().filter((connection) => this.#isDefinitionValidConnection(connection)),
3387
+ relevantNodeIds: this.#getExecutionRelevantNodeIds(),
3388
+ preloadedNodes: this.#run.nodeResults,
3389
+ consumedTriggerNodeId: this.#consumedAsyncBranchTriggerNodeId,
3390
+ inputAnchorNodeIds: this.#asyncBranchInputAnchors
3391
+ ? new Set(Object.keys(this.#asyncBranchInputAnchors))
3392
+ : undefined,
3393
+ enclosingWatchNode: this.#getEnclosingStreamingWatchInvocation()?.plan.watchNode,
3394
+ })) {
3511
3395
  this.#asyncBranchPlansByTriggerNodeId.set(triggerNode.id, { graph, nodeIds });
3512
3396
  if (triggerNode.id !== this.#consumedAsyncBranchTriggerNodeId) {
3513
- for (const nodeId of nodeIds) {
3514
- this.#ignoreNodes.add(nodeId);
3515
- }
3397
+ for (const nodeId of nodeIds)
3398
+ this.#run.ignoreNodes.add(nodeId);
3516
3399
  }
3517
3400
  }
3518
3401
  }
@@ -3602,20 +3485,20 @@ export class GraphProcessor {
3602
3485
  }
3603
3486
  }
3604
3487
  #isNodeSelected(nodeId) {
3605
- return !this.#graphOutputSelection || this.#graphOutputSelection.nodeIds.has(nodeId);
3488
+ return !this.#run.graphOutputSelection || this.#run.graphOutputSelection.nodeIds.has(nodeId);
3606
3489
  }
3607
3490
  #getExecutionRelevantNodeIds() {
3608
3491
  if (this.#sameGraphRunOwnerOverride) {
3609
3492
  return this.#sameGraphRunOwnerOverride.#getExecutionRelevantNodeIds();
3610
3493
  }
3611
- return this.#graphOutputSelection?.nodeIds ?? this.#getRunToRelevantNodeIds();
3494
+ return this.#run.graphOutputSelection?.nodeIds ?? this.#getRunToRelevantNodeIds();
3612
3495
  }
3613
3496
  #getRunToRelevantNodeIds() {
3614
3497
  if (!this.runToNodeIds) {
3615
3498
  return undefined;
3616
3499
  }
3617
- if (this.#runToRelevantNodeIds) {
3618
- return this.#runToRelevantNodeIds;
3500
+ if (this.#run.runToRelevantNodeIds) {
3501
+ return this.#run.runToRelevantNodeIds;
3619
3502
  }
3620
3503
  const relevantNodeIds = new Set();
3621
3504
  for (const runToNodeId of this.runToNodeIds) {
@@ -3623,7 +3506,7 @@ export class GraphProcessor {
3623
3506
  relevantNodeIds.add(dependencyNodeId);
3624
3507
  }
3625
3508
  }
3626
- this.#runToRelevantNodeIds = relevantNodeIds;
3509
+ this.#run.runToRelevantNodeIds = relevantNodeIds;
3627
3510
  return relevantNodeIds;
3628
3511
  }
3629
3512
  #emitGraphPartialOutputIfNeeded(node, partialOutputs) {
@@ -3652,6 +3535,91 @@ export class GraphProcessor {
3652
3535
  execution: parentExecution,
3653
3536
  });
3654
3537
  }
3538
+ /** Common construction only. Aliases, execution identity and terminal commits
3539
+ * remain explicit in each invocation path rather than a matrix of flags. */
3540
+ #constructChildInvocation(invocation) {
3541
+ const ordinary = invocation.kind === 'subgraph';
3542
+ const processor = new GraphProcessor(ordinary ? invocation.project : this.#project, ordinary ? invocation.graphId : invocation.graph.metadata.id, this.#registry, this.#includeTrace, {
3543
+ cacheLoadedProjects: ordinary ? this.#cacheLoadedProjects : true,
3544
+ captureNodeTimings: this.#captureNodeTimings,
3545
+ concurrency: this.#concurrency,
3546
+ executionPlanCacheMode: this.#executionPlanCacheMode,
3547
+ runtimeCache: ordinary
3548
+ ? this.#runtimeCache
3549
+ : {
3550
+ ...this.#runtimeCache,
3551
+ graphBoundaries: undefined,
3552
+ loadedProjects: { ...this.#run.loadedProjects },
3553
+ },
3554
+ runtimeProfiler: this.#runtimeProfiler,
3555
+ scheduler: this.#scheduler,
3556
+ ...(ordinary
3557
+ ? { initialExecutionPlan: invocation.initialExecutionPlan }
3558
+ : { [graphProcessorGraphOverride]: invocation.graph }),
3559
+ ...(invocation.kind === 'watch' ? { [consumedStreamingWatchNodeOverride]: invocation.watchNodeId } : {}),
3560
+ ...(invocation.kind === 'async'
3561
+ ? {
3562
+ [consumedAsyncBranchTriggerOverride]: invocation.triggerNodeId,
3563
+ [asyncBranchInputAnchorsOverride]: invocation.inputAnchors,
3564
+ }
3565
+ : {}),
3566
+ });
3567
+ if (invocation.kind === 'async')
3568
+ invocation.onCreated(processor);
3569
+ processor.executor = this.executor;
3570
+ processor.#isSubProcessor = true;
3571
+ processor.#shared = this.#shared;
3572
+ processor.#externalFunctions = this.#externalFunctions;
3573
+ processor.#contextValues = this.#contextValues;
3574
+ processor.#parent = this;
3575
+ processor.#recordingProjectScope = this.#recordingProjectScope;
3576
+ processor.#graphCallPath = this.#graphCallPath;
3577
+ processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
3578
+ processor.#executor = this.#executor;
3579
+ return processor;
3580
+ }
3581
+ #wireChildEvents(processor, owner, options = {}) {
3582
+ return wireSubprocessorEvents(processor, owner.#emitter, {
3583
+ ...options,
3584
+ isPaused: () => owner.#lifecycle.isPaused,
3585
+ pause: () => {
3586
+ void owner.pause();
3587
+ },
3588
+ resume: () => {
3589
+ void owner.resume();
3590
+ },
3591
+ });
3592
+ }
3593
+ #releaseChildInvocation(processor, owner, lifecycle, events, executionFailed) {
3594
+ try {
3595
+ cleanupSubprocessorBindings(lifecycle, events, executionFailed);
3596
+ }
3597
+ finally {
3598
+ owner.#run.subprocessors.delete(processor);
3599
+ }
3600
+ }
3601
+ #wireChildLifecycle(processor, owner, unwireEvents, options = {}) {
3602
+ try {
3603
+ return wireSubprocessorLifecycle(processor, {
3604
+ ...options,
3605
+ parentAbortSignal: owner.#run.abortController.signal,
3606
+ onParentPause: (listener) => owner.on('pause', listener),
3607
+ onParentResume: (listener) => owner.on('resume', listener),
3608
+ });
3609
+ }
3610
+ catch (error) {
3611
+ // Lifecycle setup rolls back its own partial bindings. Undo the earlier
3612
+ // event bridge and registration too, preserving the original setup error.
3613
+ try {
3614
+ unwireEvents();
3615
+ }
3616
+ catch {
3617
+ /* Setup failure remains authoritative. */
3618
+ }
3619
+ owner.#run.subprocessors.delete(processor);
3620
+ throw error;
3621
+ }
3622
+ }
3655
3623
  #createSubProcessor(node, index, processId, subGraphId, { signal, project } = {}) {
3656
3624
  const subprocessorProject = project ?? this.#project;
3657
3625
  const subprocessorGraph = resolveProcessorGraph(subprocessorProject, subGraphId);
@@ -3661,34 +3629,29 @@ export class GraphProcessor {
3661
3629
  const createProfileStart = this.#startRuntimeProfile();
3662
3630
  let processor;
3663
3631
  try {
3664
- processor = new GraphProcessor(subprocessorProject, subGraphId, this.#registry, this.#includeTrace, {
3665
- cacheLoadedProjects: this.#cacheLoadedProjects,
3666
- captureNodeTimings: this.#captureNodeTimings,
3667
- concurrency: this.#concurrency,
3668
- executionPlanCacheMode: this.#executionPlanCacheMode,
3632
+ processor = this.#constructChildInvocation({
3633
+ kind: 'subgraph',
3634
+ project: subprocessorProject,
3635
+ graphId: subGraphId,
3669
3636
  initialExecutionPlan,
3670
- runtimeCache: this.#runtimeCache,
3671
- runtimeProfiler: this.#runtimeProfiler,
3672
- scheduler: this.#scheduler,
3673
3637
  });
3674
3638
  }
3675
3639
  finally {
3676
3640
  this.#finishRuntimeProfile('createSubProcessor', createProfileStart);
3677
3641
  }
3678
- processor.executor = this.executor;
3679
- processor.#isSubProcessor = true;
3680
- processor.#executionCache = this.#executionCache;
3681
- processor.#externalFunctions = this.#externalFunctions;
3682
- processor.#contextValues = this.#contextValues;
3683
- processor.#parent = this;
3642
+ processor.#recordingProjectScope =
3643
+ node.type === 'subGraph' && node.data.targetProjectId
3644
+ ? getSubgraphProjectKey({
3645
+ projectId: node.data.targetProjectId,
3646
+ version: node.data.targetVersion ?? 'latest',
3647
+ })
3648
+ : subprocessorProject.metadata.id !== this.#project.metadata.id
3649
+ ? getSubgraphProjectKey({ projectId: subprocessorProject.metadata.id, version: 'latest' })
3650
+ : this.#recordingProjectScope;
3684
3651
  processor.#graphCallPath = Object.freeze([
3685
3652
  ...this.#graphCallPath,
3686
3653
  processor.#graph.metadata?.name || '(Unnamed Graph)',
3687
3654
  ]);
3688
- processor.#globals = this.#globals;
3689
- processor.#storedValueController = this.#storedValueController;
3690
- processor.#knowledgeStoreController = this.#knowledgeStoreController;
3691
- processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
3692
3655
  processor.#executor = {
3693
3656
  nodeId: node.id,
3694
3657
  parentGraphId: this.#graph.metadata.id,
@@ -3696,39 +3659,17 @@ export class GraphProcessor {
3696
3659
  processId,
3697
3660
  };
3698
3661
  const wireEventsProfileStart = this.#startRuntimeProfile();
3662
+ let unwireEvents;
3699
3663
  try {
3700
- wireSubprocessorEvents(processor, this.#emitter, {
3701
- isPaused: () => this.#lifecycle.isPaused,
3702
- pause: () => {
3703
- void this.pause();
3704
- },
3705
- resume: () => {
3706
- void this.resume();
3707
- },
3708
- });
3664
+ unwireEvents = this.#wireChildEvents(processor, this);
3709
3665
  }
3710
3666
  finally {
3711
3667
  this.#finishRuntimeProfile('wireSubProcessorEvents', wireEventsProfileStart);
3712
3668
  }
3713
- this.#subprocessors.add(processor);
3669
+ this.#run.subprocessors.add(processor);
3714
3670
  const wireLifecycleProfileStart = this.#startRuntimeProfile();
3715
3671
  try {
3716
- wireSubprocessorLifecycle(processor, {
3717
- signal,
3718
- parentAbortSignal: this.#abortController.signal,
3719
- onParentPause: (listener) => {
3720
- this.on('pause', listener);
3721
- return () => {
3722
- this.off('pause', listener);
3723
- };
3724
- },
3725
- onParentResume: (listener) => {
3726
- this.on('resume', listener);
3727
- return () => {
3728
- this.off('resume', listener);
3729
- };
3730
- },
3731
- });
3672
+ this.#wireChildLifecycle(processor, this, unwireEvents, { signal });
3732
3673
  }
3733
3674
  finally {
3734
3675
  this.#finishRuntimeProfile('wireSubProcessorLifecycle', wireLifecycleProfileStart);
@@ -3743,8 +3684,8 @@ export class GraphProcessor {
3743
3684
  let settled = false;
3744
3685
  const cleanup = () => {
3745
3686
  signal.removeEventListener('abort', abortListener);
3746
- if (this.#pendingUserInputs[node.id] === pending) {
3747
- delete this.#pendingUserInputs[node.id];
3687
+ if (this.#run.pendingUserInputs[node.id] === pending) {
3688
+ delete this.#run.pendingUserInputs[node.id];
3748
3689
  }
3749
3690
  };
3750
3691
  const abortListener = () => {
@@ -3762,7 +3703,7 @@ export class GraphProcessor {
3762
3703
  resolve(results);
3763
3704
  };
3764
3705
  const pending = { resolve: respond };
3765
- this.#pendingUserInputs[node.id] = pending;
3706
+ this.#run.pendingUserInputs[node.id] = pending;
3766
3707
  signal.addEventListener('abort', abortListener, { once: true });
3767
3708
  if (signal.aborted) {
3768
3709
  abortListener();
@@ -3793,11 +3734,11 @@ export class GraphProcessor {
3793
3734
  const { queueOutputNodes = true } = options;
3794
3735
  const attachedData = this.#getAttachedDataTo(node);
3795
3736
  this.#registerNodeInActiveLoop(node, attachedData);
3796
- this.#visitedNodes.add(node.id);
3737
+ this.#run.visitedNodes.add(node.id);
3797
3738
  this.#markAsExcluded(node, processId, inputValues, reason);
3798
- this.#finishStreamingOutputWatches(node, this.#nodeResults.get(node.id));
3799
- this.#currentlyProcessing.delete(node.id);
3800
- this.#remainingNodes.delete(node.id);
3739
+ this.#finishStreamingOutputWatches(node, this.#run.nodeResults.get(node.id));
3740
+ this.#run.currentlyProcessing.delete(node.id);
3741
+ this.#run.remainingNodes.delete(node.id);
3801
3742
  const outputNodes = getOutputNodesFrom(this.#executionState, node);
3802
3743
  this.#propagateAttachedDataToOutputNodes(node, attachedData, outputNodes.connectionsToNodes);
3803
3744
  if (queueOutputNodes) {
@@ -3810,11 +3751,11 @@ export class GraphProcessor {
3810
3751
  }
3811
3752
  async #emitNodeExcluded(node, processId, inputValues, reason, resultOrigin = 'executed') {
3812
3753
  await this.#emitter.emit('nodeExcluded', this.#createNodeExcludedEvent(node, processId, inputValues, reason, resultOrigin));
3813
- this.#finishStreamingOutputWatches(node, this.#nodeResults.get(node.id));
3754
+ this.#finishStreamingOutputWatches(node, this.#run.nodeResults.get(node.id));
3814
3755
  }
3815
3756
  #createNodeExcludedEvent(node, processId, inputValues, reason, resultOrigin = 'executed') {
3816
3757
  const outputs = createExcludedNodeOutputs(node, this.#definitions[node.id].outputs);
3817
- this.#nodeResults.set(node.id, outputs);
3758
+ this.#run.nodeResults.set(node.id, outputs);
3818
3759
  this.#commitExcludedGraphOutput(node, inputValues, outputs);
3819
3760
  return this.#withExecution({
3820
3761
  node,
@@ -3833,7 +3774,7 @@ export class GraphProcessor {
3833
3774
  const outputId = node.data.id;
3834
3775
  const value = outputs['valueOutput'];
3835
3776
  if (value) {
3836
- commitGraphOutputValue(this.#graphOutputs, outputId, value);
3777
+ commitGraphOutputValue(this.#run.graphOutputs, outputId, value);
3837
3778
  }
3838
3779
  }
3839
3780
  #getInputValuesForNode(node) {
@@ -3843,7 +3784,7 @@ export class GraphProcessor {
3843
3784
  connections?.find((conn) => conn.inputId === input.id && conn.inputNodeId === node.id);
3844
3785
  if (connection) {
3845
3786
  const outputNode = this.#nodeInstances[connection.outputNodeId].chartNode;
3846
- const outputNodeOutputs = this.#nodeResults.get(outputNode.id);
3787
+ const outputNodeOutputs = this.#run.nodeResults.get(outputNode.id);
3847
3788
  const outputResult = outputNodeOutputs?.[connection.outputId];
3848
3789
  values[input.id] = outputResult;
3849
3790
  }
@@ -3864,12 +3805,12 @@ export class GraphProcessor {
3864
3805
  return {
3865
3806
  connections: this.#connections,
3866
3807
  definitions: this.#definitions,
3867
- erroredNodes: this.#erroredNodes,
3808
+ erroredNodes: this.#run.erroredNodes,
3868
3809
  executionPlan: this.#graphExecutionPlan,
3869
- loopControllersSeen: this.#loopControllersSeen,
3810
+ loopControllersSeen: this.#run.loopControllersSeen,
3870
3811
  nodesById: this.#nodesById,
3871
3812
  stronglyConnectedComponents: this.#scc,
3872
- visitedNodes: this.#visitedNodes,
3813
+ visitedNodes: this.#run.visitedNodes,
3873
3814
  };
3874
3815
  }
3875
3816
  }