@valerypopoff/rivet2-core 2.17.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 (115) hide show
  1. package/dist/cjs/bundle.cjs +3093 -1440
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/interpolationRuntime.cjs +40 -4
  4. package/dist/cjs/interpolationRuntime.cjs.map +2 -2
  5. package/dist/cjs/serialization.cjs +1880 -0
  6. package/dist/cjs/serialization.cjs.map +7 -0
  7. package/dist/cjs/webAppRuntime.cjs +168 -6
  8. package/dist/cjs/webAppRuntime.cjs.map +3 -3
  9. package/dist/esm/api/processSettings.js +1 -0
  10. package/dist/esm/exports.js +2 -0
  11. package/dist/esm/model/AgentResponseTrace.js +99 -34
  12. package/dist/esm/model/AgentResponseTracePresentation.js +130 -0
  13. package/dist/esm/model/DataValue.js +11 -2
  14. package/dist/esm/model/GlobalVariables.js +2 -1
  15. package/dist/esm/model/GraphBoundaryEffects.js +38 -1
  16. package/dist/esm/model/GraphExecutionState.js +81 -0
  17. package/dist/esm/model/GraphProcessor.js +621 -942
  18. package/dist/esm/model/GraphSchedulerBoundaryState.js +64 -0
  19. package/dist/esm/model/Nodes.js +5 -0
  20. package/dist/esm/model/ProjectBundle.js +23 -10
  21. package/dist/esm/model/ProjectBundleRuntime.js +54 -0
  22. package/dist/esm/model/SchedulerBoundaryPlanner.js +233 -0
  23. package/dist/esm/model/SubprocessorBridge.js +125 -87
  24. package/dist/esm/model/ToolCallContinuationCoordinator.js +1 -1
  25. package/dist/esm/model/chat-v2/aiSdkBridge.js +15 -12
  26. package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -4
  27. package/dist/esm/model/chat-v2/chatV2CredentialNames.js +5 -1
  28. package/dist/esm/model/chat-v2/chatV2Outputs.js +2 -2
  29. package/dist/esm/model/chat-v2/chatV2Pipeline.js +11 -1
  30. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +3 -2
  31. package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +46 -6
  32. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +7 -0
  33. package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +10 -0
  34. package/dist/esm/model/chat-v2/llmChatV2Body.js +2 -2
  35. package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +5 -2
  36. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +1 -0
  37. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +18 -8
  38. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +10 -2
  39. package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +17 -0
  40. package/dist/esm/model/chat-v2/llmModelCandidate.js +2 -1
  41. package/dist/esm/model/chat-v2/llmProfile.js +2 -1
  42. package/dist/esm/model/chat-v2/llmProfileBody.js +9 -0
  43. package/dist/esm/model/chat-v2/llmProfileFallback.js +7 -4
  44. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +1 -0
  45. package/dist/esm/model/chat-v2/llmProfileHealthStore.js +16 -3
  46. package/dist/esm/model/chat-v2/messageConverter.js +18 -16
  47. package/dist/esm/model/chat-v2/modelRegistry.js +14 -4
  48. package/dist/esm/model/chat-v2/openRouterModel.js +73 -0
  49. package/dist/esm/model/chat-v2/parallelToolCalls.js +2 -0
  50. package/dist/esm/model/chat-v2/providerOptions.js +30 -25
  51. package/dist/esm/model/classifier/credentials.js +13 -3
  52. package/dist/esm/model/classifier/limits.js +33 -3
  53. package/dist/esm/model/classifier/perplexity.js +63 -0
  54. package/dist/esm/model/classifier/profile.js +151 -0
  55. package/dist/esm/model/classifier/profileExecution.js +294 -0
  56. package/dist/esm/model/classifier/providers.js +217 -30
  57. package/dist/esm/model/classifier/state.js +4 -1
  58. package/dist/esm/model/classifier/types.js +11 -1
  59. package/dist/esm/model/nodeRunFailure.js +8 -1
  60. package/dist/esm/model/nodes/CallGraphNode.js +6 -0
  61. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +250 -59
  62. package/dist/esm/model/nodes/ClassifierProfileNode.js +133 -0
  63. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +1 -1
  64. package/dist/esm/model/nodes/LLMChatV2Node.js +2 -1
  65. package/dist/esm/model/nodes/SubGraphNode.js +3 -0
  66. package/dist/esm/model/nodes/toolCallDelegation.js +5 -1
  67. package/dist/esm/model/profileSuspensionHints.js +8 -0
  68. package/dist/esm/serialization.js +2 -0
  69. package/dist/esm/utils/coerceType.js +11 -1
  70. package/dist/esm/webAppRuntime.js +1 -0
  71. package/dist/types/exports.d.ts +2 -0
  72. package/dist/types/model/AgentResponseTrace.d.ts +15 -4
  73. package/dist/types/model/AgentResponseTracePresentation.d.ts +15 -0
  74. package/dist/types/model/DataValue.d.ts +12 -8
  75. package/dist/types/model/ExecutorProtocol.d.ts +7 -0
  76. package/dist/types/model/GraphBoundaryEffects.d.ts +10 -1
  77. package/dist/types/model/GraphExecutionState.d.ts +68 -0
  78. package/dist/types/model/GraphProcessor.d.ts +1 -0
  79. package/dist/types/model/GraphSchedulerBoundaryState.d.ts +96 -0
  80. package/dist/types/model/Nodes.d.ts +7 -4
  81. package/dist/types/model/ProcessContext.d.ts +12 -3
  82. package/dist/types/model/ProjectBundle.d.ts +9 -4
  83. package/dist/types/model/ProjectBundleRuntime.d.ts +24 -0
  84. package/dist/types/model/RivetUIContext.d.ts +1 -1
  85. package/dist/types/model/SchedulerBoundaryPlanner.d.ts +42 -0
  86. package/dist/types/model/Settings.d.ts +1 -0
  87. package/dist/types/model/SubprocessorBridge.d.ts +2 -0
  88. package/dist/types/model/chat-v2/chatV2CredentialNames.d.ts +4 -0
  89. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +1 -1
  90. package/dist/types/model/chat-v2/chatV2ProviderRegistry.d.ts +79 -1
  91. package/dist/types/model/chat-v2/chatV2ProviderTypes.d.ts +1 -1
  92. package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +2 -0
  93. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +2 -1
  94. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +2 -0
  95. package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +2 -0
  96. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +51 -3
  97. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +9 -6
  98. package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +6 -2
  99. package/dist/types/model/chat-v2/modelRegistry.d.ts +5 -4
  100. package/dist/types/model/chat-v2/openRouterModel.d.ts +2 -0
  101. package/dist/types/model/chat-v2/providerOptions.d.ts +2 -13
  102. package/dist/types/model/classifier/credentials.d.ts +4 -0
  103. package/dist/types/model/classifier/limits.d.ts +4 -1
  104. package/dist/types/model/classifier/perplexity.d.ts +7 -0
  105. package/dist/types/model/classifier/profile.d.ts +46 -0
  106. package/dist/types/model/classifier/profileExecution.d.ts +32 -0
  107. package/dist/types/model/classifier/providers.d.ts +32 -1
  108. package/dist/types/model/classifier/types.d.ts +9 -0
  109. package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +14 -12
  110. package/dist/types/model/nodes/ClassifierProfileNode.d.ts +20 -0
  111. package/dist/types/model/nodes/toolCallDelegation.d.ts +3 -1
  112. package/dist/types/model/profileSuspensionHints.d.ts +8 -0
  113. package/dist/types/serialization.d.ts +2 -0
  114. package/dist/types/webAppRuntime.d.ts +1 -0
  115. 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,7 +45,7 @@ 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';
45
- import { getSubgraphProjectKey, isSubgraphProjectKey, } from './SubgraphProjectTarget.js';
48
+ import { getSubgraphProjectKey, isSubgraphProjectKey } from './SubgraphProjectTarget.js';
46
49
  import { MAX_CAUGHT_STREAMING_CHUNKS } from './nodes/CatchStreamingChunksNode.js';
47
50
  import { isEqual } from 'lodash-es';
48
51
  // eslint-disable-next-line import/no-cycle -- There has to be a cycle because CodeRunner needs to import the entirety of Rivet
@@ -151,6 +154,9 @@ function replaceRecordContents(target, source) {
151
154
  Object.assign(target, source);
152
155
  }
153
156
  export class GraphProcessor {
157
+ #run = new GraphInvocationState();
158
+ #shared = new GraphSharedExecutionState();
159
+ #boundaries = new GraphSchedulerBoundaryState();
154
160
  // Per-instance state
155
161
  #graph;
156
162
  #graphCallPath;
@@ -179,21 +185,9 @@ export class GraphProcessor {
179
185
  #asyncBranchPlansByTriggerNodeId = new Map();
180
186
  #consumedAsyncBranchTriggerNodeId;
181
187
  #asyncBranchInputAnchors;
182
- #streamingWatchPlansBySourceNodeId = new Map();
183
- #streamingWatchPlansByWatchNodeId = new Map();
184
- #streamingOutputWatches = new Map();
185
- #streamingCatchPlansBySourceNodeId = new Map();
186
- #streamingCatchTasks = new Set();
187
- #graphOutputPartialBindingsBySourceNodeId = new Map();
188
188
  #graphOutputPartialListener;
189
189
  #consumedStreamingWatchNodeId;
190
190
  #streamingWatchInvocation;
191
- #graphInputStreams = {};
192
- #callerInputStreams = new Map();
193
- #inputStreamRoutes = new Map();
194
- #streamCallerTasks = new Set();
195
- #inputStreamDisposers = [];
196
- #pendingGraphInputFinals = new Map();
197
191
  #registry;
198
192
  #concurrency;
199
193
  #executionPlanCacheMode;
@@ -215,64 +209,23 @@ export class GraphProcessor {
215
209
  runFromNodeId;
216
210
  /** The node that is executing this graph, almost always a subgraph node. Undefined for root. */
217
211
  #executor;
218
- #rootRunId = undefined;
219
- #graphRunId = undefined;
220
- #parentGraphRunId = undefined;
221
212
  /** The interval between nodeFinish events when playing back a recording. I.e. how fast the playback is. */
222
213
  recordingPlaybackChatLatency = 1000;
223
214
  warnOnInvalidGraph = false;
224
- // Per-process state
225
- #erroredNodes = undefined; // Values are strings in recordings
226
- #failureOutputsByProcessId = undefined;
227
- #remainingNodes = undefined;
228
- #visitedNodes = undefined;
229
- #currentlyProcessing = undefined;
230
- #context = undefined;
231
- #nodeResults = undefined;
232
- #abortController = undefined;
233
- #processingQueue = undefined;
234
- #graphInputs = undefined;
235
- #graphOutputs = undefined;
236
- #executionCache = undefined;
237
- #queuedNodes = undefined;
238
- /**
239
- * Nodes deferred only because Run To reached its initial scheduler quiescence.
240
- * A streaming Stop can legitimately resume one of those selected paths later.
241
- */
242
- #deferredRunToIgnoredNodes = undefined;
243
- #loopControllersSeen = undefined;
244
- #subprocessors = undefined;
215
+ // Instance configuration and compiled definitions remain outside run state.
245
216
  #contextValues = undefined;
246
- #globals = undefined;
247
217
  /** IDs assigned by the previous root invocation, retained only to reset project globals on reuse. */
248
218
  #projectGlobalVariableIdsAssignedByPreviousRootRun = new Set();
249
219
  /** Snapshot for lifecycle recording, populated only while a root run starts. */
250
220
  #initialProjectGlobalVariablesForRun = new Map();
251
- #storedValueController = undefined;
252
- #knowledgeStoreController = undefined;
253
- #attachedNodeData = undefined;
254
- #successfulAbortTerminalProcessIds = undefined;
255
- #totalCost = 0;
256
- #ignoreNodes = undefined;
257
- #hasPreloadedData = false;
258
- #loadedProjects = undefined;
259
- #subgraphTargetCache = new Map();
260
221
  #definitions = undefined;
261
222
  #scc = undefined;
262
223
  #graphExecutionPlan;
263
- #nodeProcessContextBase = undefined;
264
- #runToRelevantNodeIds;
265
- #graphOutputSelection;
266
224
  #managedAsyncBranches;
267
225
  #managedAsyncBranchFailures = [];
268
- #streamingWatchFailures = [];
269
226
  #runCompletionPromise;
270
227
  #nodesNotInCycle = undefined;
271
228
  #executionGraphNodes = undefined;
272
- #nodeAbortControllers = new Map();
273
- #graphInputNodeValues = {};
274
- /** User input nodes that are pending user input. */
275
- #pendingUserInputs = undefined;
276
229
  #unsubscribeTokenizerError;
277
230
  get isRunning() {
278
231
  return this.#lifecycle.isRunning;
@@ -374,7 +327,7 @@ export class GraphProcessor {
374
327
  const preprocessedGraph = preprocessGraphState({
375
328
  inputAnchorDefinitions: this.#asyncBranchInputAnchors,
376
329
  graph: this.#graph,
377
- loadedProjects: this.#loadedProjects,
330
+ loadedProjects: this.#run.loadedProjects,
378
331
  project: this.#project,
379
332
  registry: this.#registry,
380
333
  warnOnInvalidGraph: this.warnOnInvalidGraph,
@@ -438,7 +391,7 @@ export class GraphProcessor {
438
391
  this.#scc = preprocessedGraph.stronglyConnectedComponents;
439
392
  this.#nodesNotInCycle = preprocessedGraph.nodesNotInCycle;
440
393
  this.#executionGraphNodes = preprocessedGraph.graphNodes;
441
- this.#remainingNodes = new Set(this.#executionGraphNodes.map((node) => node.id));
394
+ this.#run.remainingNodes = new Set(this.#executionGraphNodes.map((node) => node.id));
442
395
  this.#graphExecutionPlan = isGraphExecutionPlan(preprocessedGraph) ? preprocessedGraph : undefined;
443
396
  }
444
397
  #seededExecutionPlanForNextRun() {
@@ -463,11 +416,12 @@ export class GraphProcessor {
463
416
  }
464
417
  #buildExecutionMetadata() {
465
418
  return {
466
- rootRunId: this.#rootRunId,
467
- graphRunId: this.#graphRunId,
419
+ rootRunId: this.#run.rootRunId,
420
+ graphRunId: this.#run.graphRunId,
468
421
  graphId: this.#graph.metadata.id,
422
+ projectId: this.#project.metadata.id,
469
423
  ...(this.#recordingProjectScope ? { projectScope: this.#recordingProjectScope } : {}),
470
- parentGraphRunId: this.#parentGraphRunId,
424
+ parentGraphRunId: this.#run.parentGraphRunId,
471
425
  executor: this.#executor
472
426
  ? {
473
427
  nodeId: this.#executor.nodeId,
@@ -476,7 +430,7 @@ export class GraphProcessor {
476
430
  splitIndex: this.#executor.index,
477
431
  }
478
432
  : undefined,
479
- ...(this.#context?.evaluation === undefined ? {} : { evaluation: this.#context.evaluation }),
433
+ ...(this.#run.context?.evaluation === undefined ? {} : { evaluation: this.#run.context.evaluation }),
480
434
  };
481
435
  }
482
436
  get recordingProjectScope() {
@@ -510,11 +464,11 @@ export class GraphProcessor {
510
464
  }
511
465
  }
512
466
  userInput(nodeId, values) {
513
- const pending = this.#pendingUserInputs[nodeId];
467
+ const pending = this.#run.pendingUserInputs[nodeId];
514
468
  if (pending) {
515
469
  pending.resolve(values);
516
470
  }
517
- for (const processor of this.#subprocessors) {
471
+ for (const processor of this.#run.subprocessors) {
518
472
  processor.userInput(nodeId, values);
519
473
  }
520
474
  }
@@ -538,7 +492,7 @@ export class GraphProcessor {
538
492
  return Promise.resolve();
539
493
  }
540
494
  const abortReason = createGraphAbortReason(successful, error);
541
- this.#abortController.abort(abortReason);
495
+ this.#run.abortController.abort(abortReason);
542
496
  this.#abortActiveNodeControllers(abortReason);
543
497
  this.#cancelStreamingOutputWatches();
544
498
  if (!this.#suppressGraphLifecycleEvents) {
@@ -547,7 +501,7 @@ export class GraphProcessor {
547
501
  emitDetached(this.#emitter, 'abort', { successful, error });
548
502
  }
549
503
  }
550
- await this.#processingQueue.onIdle();
504
+ await this.#run.processingQueue.onIdle();
551
505
  if (!this.#isSubProcessor) {
552
506
  await this.#managedAsyncBranches?.drain();
553
507
  }
@@ -570,7 +524,7 @@ export class GraphProcessor {
570
524
  if (!this.#lifecycle.isPaused) {
571
525
  return;
572
526
  }
573
- if (this.#abortController.signal.aborted) {
527
+ if (this.#run.abortController.signal.aborted) {
574
528
  throw this.#lifecycle.getAbortError();
575
529
  }
576
530
  await new Promise((resolve, reject) => {
@@ -583,10 +537,10 @@ export class GraphProcessor {
583
537
  resolve();
584
538
  });
585
539
  const cleanup = () => {
586
- this.#abortController.signal.removeEventListener('abort', abortListener);
540
+ this.#run.abortController.signal.removeEventListener('abort', abortListener);
587
541
  unsubscribeResume();
588
542
  };
589
- this.#abortController.signal.addEventListener('abort', abortListener, { once: true });
543
+ this.#run.abortController.signal.addEventListener('abort', abortListener, { once: true });
590
544
  });
591
545
  }
592
546
  async *events() {
@@ -615,12 +569,12 @@ export class GraphProcessor {
615
569
  }
616
570
  this.#assertStreamingOutputWatchPreloadCanBeAdded(nodeId);
617
571
  this.#preloadedNodeResults.set(nodeId, data);
618
- this.#hasPreloadedData = true;
572
+ this.#run.hasPreloadedData = true;
619
573
  // Preserve the historical ability to preload an idle processor as well as
620
574
  // inject a boundary into a run that has already initialized.
621
575
  if (this.#lifecycle.isRunning && this.#isNodeSelected(nodeId)) {
622
- this.#nodeResults.set(nodeId, data);
623
- this.#visitedNodes.add(nodeId);
576
+ this.#run.nodeResults.set(nodeId, data);
577
+ this.#run.visitedNodes.add(nodeId);
624
578
  }
625
579
  }
626
580
  setFrozenNodeOutputResolver(resolver) {
@@ -641,7 +595,7 @@ export class GraphProcessor {
641
595
  if (this.#definitions != null) {
642
596
  return;
643
597
  }
644
- this.#loadedProjects ??= {};
598
+ this.#run.loadedProjects ??= {};
645
599
  // This synchronous inspection API can be called before processGraph has
646
600
  // loaded references. Its provisional definitions must never be reused as
647
601
  // a runtime plan for a later fully loaded invocation.
@@ -679,13 +633,13 @@ export class GraphProcessor {
679
633
  this.#initProcessState();
680
634
  return await replayExecutionRecording({
681
635
  emitter: this.#emitter,
682
- erroredNodes: this.#erroredNodes,
683
- graphInputs: this.#graphInputs,
684
- graphOutputs: this.#graphOutputs,
636
+ erroredNodes: this.#run.erroredNodes,
637
+ graphInputs: this.#run.graphInputs,
638
+ graphOutputs: this.#run.graphOutputs,
685
639
  fallbackGraphId: this.#graph.metadata.id,
686
640
  initialReplayExecution: this.#buildExecutionMetadata(),
687
641
  isAborted: () => this.#lifecycle.isAborted,
688
- nodeResults: this.#nodeResults,
642
+ nodeResults: this.#run.nodeResults,
689
643
  project: this.#project,
690
644
  recorder,
691
645
  recordingPlaybackChatLatency: this.recordingPlaybackChatLatency,
@@ -693,82 +647,57 @@ export class GraphProcessor {
693
647
  this.#contextValues = contextValues;
694
648
  },
695
649
  setGraphInputs: (graphInputs) => {
696
- this.#graphInputs = graphInputs;
650
+ this.#run.graphInputs = graphInputs;
697
651
  },
698
652
  setGraphOutputs: (graphOutputs) => {
699
- this.#graphOutputs = graphOutputs;
653
+ this.#run.graphOutputs = graphOutputs;
700
654
  },
701
655
  setRunning: (running) => {
702
656
  if (!running)
703
657
  this.#lifecycle.complete();
704
658
  },
705
- visitedNodes: this.#visitedNodes,
659
+ visitedNodes: this.#run.visitedNodes,
706
660
  waitUntilUnpaused: () => this.#waitUntilUnpaused(),
707
661
  });
708
662
  }
709
663
  #initProcessState() {
710
664
  this.#lifecycle.begin();
711
- this.#nodeResults = new Map(this.#preloadedNodeResults);
712
- this.#visitedNodes = new Set(this.#preloadedNodeResults.keys());
713
- this.#hasPreloadedData = this.#preloadedNodeResults.size > 0;
714
- this.#erroredNodes = new Map();
715
- this.#failureOutputsByProcessId = new Map();
716
- 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();
717
668
  // A processor may be constructed with a reusable execution plan. In that
718
669
  // case preprocessing happened before this run, so retain the compiled
719
670
  // execution-node set rather than restoring the authored graph nodes (which
720
671
  // may include topology-only Data Bus nodes).
721
- this.#remainingNodes = new Set(this.#seededExecutionPlanForNextRun()?.nodeIds ?? []);
722
- this.#pendingUserInputs = {};
723
- this.#processingQueue = new PQueue({ concurrency: this.#concurrency.nodeConcurrency });
724
- this.#graphOutputs = this.#sharedRunStateOverride?.graphOutputs ?? {};
725
- this.#executionCache ??= new Map();
726
- this.#queuedNodes = new Set();
727
- 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();
728
681
  this.#connectedToolContinuationHost.reset();
729
682
  this.#continuationCompletionOwnerByNodeId = new Map();
730
683
  this.#effectiveConnectionsForRun = undefined;
731
684
  this.#asyncBranchPlansByTriggerNodeId = new Map();
732
- this.#streamingWatchPlansBySourceNodeId = new Map();
733
- this.#streamingWatchPlansByWatchNodeId = new Map();
734
- this.#streamingOutputWatches = new Map();
735
- this.#streamingCatchPlansBySourceNodeId = new Map();
736
- this.#streamingCatchTasks = new Set();
737
- this.#graphOutputPartialBindingsBySourceNodeId = new Map();
738
- this.#loopControllersSeen = new Set();
739
- this.#subprocessors = new Set();
740
- this.#attachedNodeData = this.#sharedRunStateOverride?.attachedNodeData ?? new Map();
741
- this.#globals ??= new Map();
685
+ this.#boundaries.resetTopology();
686
+ this.#shared.globals ??= new Map();
742
687
  if (!this.#isSubProcessor) {
743
- this.#storedValueController = new RivetStoredValueController(this.#storedValueStore);
744
- this.#knowledgeStoreController = new KnowledgeStoreController(this.#knowledgeStores);
688
+ this.#shared.storedValueController = new RivetStoredValueController(this.#storedValueStore);
689
+ this.#shared.knowledgeStoreController = new KnowledgeStoreController(this.#knowledgeStores);
745
690
  }
746
- this.#ignoreNodes = new Set();
747
- this.#nodeProcessContextBase = undefined;
748
- this.#runToRelevantNodeIds = undefined;
749
- this.#graphOutputSelection = undefined;
750
691
  if (!this.#isSubProcessor) {
751
692
  this.#managedAsyncBranches = new ManagedAsyncBranches();
752
693
  this.#managedAsyncBranchFailures = [];
753
694
  }
754
- this.#streamingWatchFailures = [];
755
- this.#abortController = this.#newAbortController();
756
- this.#successfulAbortTerminalProcessIds = new Set();
757
- this.#totalCost = 0;
758
- this.#nodeAbortControllers = new Map();
759
- this.#loadedProjects =
760
- this.#cacheLoadedProjects && this.#runtimeCache?.loadedProjects ? { ...this.#runtimeCache.loadedProjects } : {};
761
- if (!this.#isSubProcessor) {
762
- // Latest and Published are selected afresh for each root invocation.
763
- this.#subgraphTargetCache = new Map();
764
- }
765
695
  // Referenced projects can be reloaded per run when loaded-project caching is disabled.
766
696
  if (!this.#cacheLoadedProjects && (this.#project.references?.length ?? 0) > 0) {
767
697
  if (this.#runtimeCache) {
768
698
  this.#runtimeCache.graphBoundaries = undefined;
769
699
  }
770
700
  }
771
- this.#graphInputNodeValues = this.#sharedRunStateOverride?.graphInputNodeValues ?? {};
772
701
  }
773
702
  /** Main function for running a graph. Runs a graph and returns the outputs from the output nodes of the graph. */
774
703
  async processGraph(
@@ -796,12 +725,7 @@ export class GraphProcessor {
796
725
  try {
797
726
  try {
798
727
  this.#profileRuntimeSync('initializeGraphRun', () => this.#initializeGraphRun(context, inputs, contextValues));
799
- this.#graphInputStreams = options.graphInputStreams ?? {};
800
- this.#callerInputStreams = new Map();
801
- this.#inputStreamRoutes = new Map();
802
- this.#streamCallerTasks = new Set();
803
- this.#inputStreamDisposers = [];
804
- this.#pendingGraphInputFinals = new Map();
728
+ this.#boundaries.initializeInputStreams(options.graphInputStreams);
805
729
  await this.#profileRuntimeAsync('loadProjectReferences', () => this.#loadProjectReferences());
806
730
  this.#profileRuntimeSync('initializeProjectGlobalVariables', () => this.#initializeProjectGlobalVariablesForRootRun());
807
731
  this.#profileRuntimeSync('prepareNodeProcessContextBase', () => this.#prepareNodeProcessContextBase());
@@ -815,11 +739,11 @@ export class GraphProcessor {
815
739
  if (this.runToNodeIds !== undefined) {
816
740
  throw new Error('requestedGraphOutputIds cannot be combined with runToNodeIds');
817
741
  }
818
- this.#graphOutputSelection = createGraphOutputSelection({ nodes: this.#executionGraphNodes, connections: this.#getEffectiveConnections() }, requestedGraphOutputIds, (node) => getInputNodesTo(this.#executionState, node));
819
- 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()) {
820
744
  if (!this.#isNodeSelected(nodeId)) {
821
- this.#nodeResults.delete(nodeId);
822
- this.#visitedNodes.delete(nodeId);
745
+ this.#run.nodeResults.delete(nodeId);
746
+ this.#run.visitedNodes.delete(nodeId);
823
747
  }
824
748
  }
825
749
  }
@@ -853,8 +777,8 @@ export class GraphProcessor {
853
777
  // Publish a snapshot instead of the live root output object. In particular,
854
778
  // the provisional cost must not occupy the root cost port before managed
855
779
  // async branches contribute their cost during finalization.
856
- const outputsReady = { ...this.#graphOutputs };
857
- ensureGraphCostOutput(outputsReady, this.#totalCost);
780
+ const outputsReady = { ...this.#run.graphOutputs };
781
+ ensureGraphCostOutput(outputsReady, this.#run.totalCost, this.#run.costBreakdown);
858
782
  await this.#emitter.emit('graphOutputsReady', this.#withExecution({ graph: this.#graph, outputs: outputsReady }));
859
783
  outputsWerePublishedEarly = true;
860
784
  resolveOutputsReady?.(outputsReady);
@@ -864,18 +788,20 @@ export class GraphProcessor {
864
788
  return await this.#profileRuntimeAsync('finalizeGraphRun', () => this.#finalizeGraphRun());
865
789
  }
866
790
  finally {
867
- for (const dispose of this.#inputStreamDisposers)
868
- dispose();
869
- this.#pendingGraphInputFinals.clear();
870
- for (const streams of this.#callerInputStreams.values()) {
871
- for (const relay of Object.values(streams))
872
- 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());
873
804
  }
874
- await this.#drainSchedulerBoundaries();
875
- this.#graphOutputPartialListener = undefined;
876
- this.#lifecycle.complete();
877
- this.#cleanupTokenizerErrorListener();
878
- await this.#profileRuntimeAsync('emitFinish', () => this.#emitFinishIfNeeded());
879
805
  }
880
806
  })();
881
807
  this.#runCompletionPromise = completionPromise;
@@ -903,11 +829,11 @@ export class GraphProcessor {
903
829
  #initializeGraphRun(context, inputs, contextValues) {
904
830
  this.#initializeExecutionIdentity();
905
831
  this.#initProcessState();
906
- this.#context = context;
907
- this.#graphInputs = inputs;
832
+ this.#run.context = context;
833
+ this.#run.graphInputs = inputs;
908
834
  this.#contextValues = contextValues;
909
835
  this.#cleanupTokenizerErrorListener();
910
- const unsubscribeTokenizerError = this.#context.tokenizer.on('error', (error) => {
836
+ const unsubscribeTokenizerError = this.#run.context.tokenizer.on('error', (error) => {
911
837
  emitDetached(this.#emitter, 'error', { error });
912
838
  });
913
839
  this.#unsubscribeTokenizerError =
@@ -919,27 +845,27 @@ export class GraphProcessor {
919
845
  return;
920
846
  // Resolve before touching the shared map. An invalid reference or definition
921
847
  // must fail startup without leaving a partial new set of authored globals.
922
- const legacyProjects = Object.fromEntries(Object.entries(this.#loadedProjects).filter(([key]) => !isSubgraphProjectKey(key)));
848
+ const legacyProjects = Object.fromEntries(Object.entries(this.#run.loadedProjects).filter(([key]) => !isSubgraphProjectKey(key)));
923
849
  const resolved = resolveProjectGlobalVariables(this.#project, legacyProjects);
924
850
  for (const id of this.#projectGlobalVariableIdsAssignedByPreviousRootRun) {
925
- this.#globals.delete(id);
851
+ this.#shared.globals.delete(id);
926
852
  }
927
853
  for (const [id, value] of resolved) {
928
- this.#globals.set(id, value);
854
+ this.#shared.globals.set(id, value);
929
855
  }
930
856
  this.#projectGlobalVariableIdsAssignedByPreviousRootRun = new Set(resolved.keys());
931
857
  this.#initialProjectGlobalVariablesForRun = resolved;
932
858
  }
933
859
  #initializeExecutionIdentity() {
934
860
  if (this.#executionIdentityOverride) {
935
- this.#rootRunId = this.#executionIdentityOverride.rootRunId;
936
- this.#graphRunId = this.#executionIdentityOverride.graphRunId;
937
- 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;
938
864
  }
939
865
  else {
940
- this.#rootRunId = this.#parent ? this.#parent.#rootRunId : nanoid();
941
- this.#graphRunId = nanoid();
942
- 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;
943
869
  }
944
870
  }
945
871
  async #emitRootStartupError(error) {
@@ -958,26 +884,26 @@ export class GraphProcessor {
958
884
  // is already a GraphProcessor wrapper. Always resolve the original host
959
885
  // observer from the root run so nested LLM calls are not emitted once by
960
886
  // every ancestor before their own event is bridged to the root emitter.
961
- const hostChatV2Observer = this.getRootProcessor().#context.onChatV2CallFinished;
962
- const hostLLMChatOutputSnapshotObserver = this.getRootProcessor().#context.onLLMChatOutputSnapshot;
963
- const hostLLMProfileAttemptObserver = this.getRootProcessor().#context.onLLMProfileAttempt;
964
- this.#nodeProcessContextBase = {
965
- ...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,
966
892
  abortGraph: (error) => {
967
893
  void (this.#abortOwnerOverride ?? this).abort(error === undefined, error);
968
894
  },
969
- codeRunner: this.#context.codeRunner ?? DEFAULT_ISOMORPHIC_CODE_RUNNER,
895
+ codeRunner: this.#run.context.codeRunner ?? DEFAULT_ISOMORPHIC_CODE_RUNNER,
970
896
  contextValues: this.#contextValues,
971
- executionCache: this.#executionCache,
897
+ executionCache: this.#shared.executionCache,
972
898
  executor: this.executor ?? 'nodejs',
973
- getGlobal: (id) => this.#globals.get(id),
974
- getCachedStoredValue: (key) => this.#storedValueController.getCached(key),
975
- getStoredValue: (key) => this.#storedValueController.get(key),
976
- 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),
977
903
  getGraphBoundary: (project, graphId) => this.#getGraphBoundary(project, graphId),
978
- graphInputNodeValues: this.#graphInputNodeValues,
979
- graphInputs: this.#graphInputs,
980
- graphOutputs: this.#graphOutputs,
904
+ graphInputNodeValues: this.#run.graphInputNodeValues,
905
+ graphInputs: this.#run.graphInputs,
906
+ graphOutputs: this.#run.graphOutputs,
981
907
  graphCallPath: this.#graphCallPath,
982
908
  onChatV2CallFinished: (event) => {
983
909
  try {
@@ -1027,18 +953,18 @@ export class GraphProcessor {
1027
953
  raiseEvent: (event, data) => {
1028
954
  this.getRootProcessor().raiseEvent(event, data);
1029
955
  },
1030
- referencedProjects: this.#loadedProjects,
956
+ referencedProjects: this.#run.loadedProjects,
1031
957
  tokenizer: this.#getTokenizer(),
1032
958
  trace: (message) => {
1033
959
  this.#emitTraceEvent(message);
1034
960
  },
1035
- setStoredValue: (key, value) => this.#storedValueController.set(key, value),
1036
- 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) => {
1037
963
  if (signal.aborted) {
1038
964
  throw createGraphAbortErrorFromSignal(signal);
1039
965
  }
1040
- if (this.#globals.has(id)) {
1041
- return this.#globals.get(id);
966
+ if (this.#shared.globals.has(id)) {
967
+ return this.#shared.globals.get(id);
1042
968
  }
1043
969
  return await new Promise((resolve, reject) => {
1044
970
  const abortListener = () => {
@@ -1047,7 +973,7 @@ export class GraphProcessor {
1047
973
  };
1048
974
  const unsubscribe = this.getRootProcessor().#emitter.on(`globalSet:${id}`, () => {
1049
975
  cleanup();
1050
- resolve(this.#globals.get(id));
976
+ resolve(this.#shared.globals.get(id));
1051
977
  });
1052
978
  const cleanup = () => {
1053
979
  unsubscribe();
@@ -1059,7 +985,7 @@ export class GraphProcessor {
1059
985
  }
1060
986
  });
1061
987
  },
1062
- waitForStoredValue: (key, signal) => this.#storedValueController.waitForSet(key, signal),
988
+ waitForStoredValue: (key, signal) => this.#shared.storedValueController.waitForSet(key, signal),
1063
989
  };
1064
990
  }
1065
991
  #cleanupTokenizerErrorListener() {
@@ -1079,12 +1005,12 @@ export class GraphProcessor {
1079
1005
  if (!this.#isSubProcessor) {
1080
1006
  await this.#emitter.emit('start', this.#withExecution({
1081
1007
  contextValues: this.#contextValues,
1082
- inputs: this.#graphInputs,
1008
+ inputs: this.#run.graphInputs,
1083
1009
  project: this.#project,
1084
1010
  startGraph: this.#graph,
1085
1011
  }));
1086
1012
  }
1087
- 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 }));
1088
1014
  }
1089
1015
  async #emitInitialProjectGlobalVariables() {
1090
1016
  if (this.#isSubProcessor || this.#suppressGraphLifecycleEvents)
@@ -1094,17 +1020,17 @@ export class GraphProcessor {
1094
1020
  }
1095
1021
  }
1096
1022
  async #emitPreloadedNodeResults() {
1097
- if (!this.#hasPreloadedData) {
1023
+ if (!this.#run.hasPreloadedData) {
1098
1024
  return;
1099
1025
  }
1100
1026
  for (const node of this.#executionGraphNodes) {
1101
- if (!this.#isNodeSelected(node.id) || !this.#nodeResults.has(node.id)) {
1027
+ if (!this.#isNodeSelected(node.id) || !this.#run.nodeResults.has(node.id)) {
1102
1028
  continue;
1103
1029
  }
1104
1030
  if (this.#suppressedPreloadedNodeIds.has(node.id)) {
1105
1031
  continue;
1106
1032
  }
1107
- const outputs = this.#nodeResults.get(node.id);
1033
+ const outputs = this.#run.nodeResults.get(node.id);
1108
1034
  // A preloaded producer is complete evidence, not a reconstructed token
1109
1035
  // stream. Watch receives it once as the producer's final snapshot.
1110
1036
  this.#assertStreamingOutputWatchFinalOutputs(node, outputs);
@@ -1126,45 +1052,45 @@ export class GraphProcessor {
1126
1052
  }
1127
1053
  async #queueStartNodes(startNodes) {
1128
1054
  for (const startNode of startNodes) {
1129
- void this.#processingQueue.add(async () => {
1055
+ void this.#run.processingQueue.add(async () => {
1130
1056
  await this.#fetchNodeDataAndProcessNode(startNode);
1131
1057
  });
1132
1058
  }
1133
1059
  }
1134
1060
  async #processCompatibleGraph() {
1135
- await this.#queueStartNodes(this.#graphOutputSelection?.startNodes ??
1061
+ await this.#queueStartNodes(this.#run.graphOutputSelection?.startNodes ??
1136
1062
  getStartNodes(this.#executionState, this.#executionGraphNodes, this.runToNodeIds));
1137
- await this.#processingQueue.onIdle();
1138
- if (Object.keys(this.#graphInputStreams).length) {
1063
+ await this.#run.processingQueue.onIdle();
1064
+ if (Object.keys(this.#boundaries.graphInputStreams).length) {
1139
1065
  await this.#waitForGraphInputStreams();
1140
- for (const [nodeId, outputs] of this.#pendingGraphInputFinals) {
1066
+ for (const [nodeId, outputs] of this.#boundaries.pendingGraphInputFinals) {
1141
1067
  this.#finishStreamingOutputWatches(this.#nodesById[nodeId], outputs);
1142
1068
  }
1143
- this.#pendingGraphInputFinals.clear();
1069
+ this.#boundaries.pendingGraphInputFinals.clear();
1144
1070
  for (const node of this.#executionGraphNodes) {
1145
1071
  if (!this.#isNodeSelected(node.id))
1146
1072
  continue;
1147
- void this.#processingQueue.add(() => this.#processNodeIfAllInputsAvailable(node));
1073
+ void this.#run.processingQueue.add(() => this.#processNodeIfAllInputsAvailable(node));
1148
1074
  }
1149
- await this.#processingQueue.onIdle();
1075
+ await this.#run.processingQueue.onIdle();
1150
1076
  }
1151
- while (this.#streamCallerTasks.size) {
1077
+ while (this.#boundaries.streamCallerTasks.size) {
1152
1078
  // A producer skipped transitively after an upstream failure never emits
1153
1079
  // nodeError itself. Settle its consumers once ordinary work is quiescent.
1154
- for (const [sourceId, routes] of this.#inputStreamRoutes) {
1155
- 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))
1156
1082
  continue;
1157
- const failedDependency = this.getDependencyNodesDeep(sourceId).find((id) => this.#erroredNodes.has(id));
1083
+ const failedDependency = this.getDependencyNodesDeep(sourceId).find((id) => this.#run.erroredNodes.has(id));
1158
1084
  if (failedDependency) {
1159
- const error = getError(this.#erroredNodes.get(failedDependency));
1085
+ const error = getError(this.#run.erroredNodes.get(failedDependency));
1160
1086
  for (const { relay } of routes)
1161
1087
  relay.finish({ error });
1162
1088
  }
1163
1089
  }
1164
1090
  // Recheck skipped producers after each caller settles; another caller may
1165
1091
  // depend on ordinary nodes skipped because this caller failed.
1166
- await Promise.race(this.#streamCallerTasks);
1167
- await this.#processingQueue.onIdle();
1092
+ await Promise.race(this.#boundaries.streamCallerTasks);
1093
+ await this.#run.processingQueue.onIdle();
1168
1094
  }
1169
1095
  await this.#drainStreamingCatchTasks();
1170
1096
  this.#markUnqueuedNodesIgnored();
@@ -1173,10 +1099,10 @@ export class GraphProcessor {
1173
1099
  if (this.#scheduler !== 'fast-acyclic') {
1174
1100
  return false;
1175
1101
  }
1176
- if (this.#graphOutputSelection ||
1177
- this.#callerInputStreams.size > 0 ||
1178
- Object.keys(this.#graphInputStreams).length > 0 ||
1179
- 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 ||
1180
1106
  this.runToNodeIds ||
1181
1107
  this.slowMode ||
1182
1108
  this.#includeTrace) {
@@ -1282,14 +1208,14 @@ export class GraphProcessor {
1282
1208
  return;
1283
1209
  }
1284
1210
  for (const node of this.#executionGraphNodes) {
1285
- if (this.#queuedNodes.has(node.id) === false && !this.#ignoreNodes.has(node.id)) {
1286
- this.#ignoreNodes.add(node.id);
1287
- 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);
1288
1214
  }
1289
1215
  }
1290
1216
  }
1291
1217
  #getUnhandledErroredNodes() {
1292
- return [...this.#erroredNodes.entries()].filter(([nodeId]) => {
1218
+ return [...this.#run.erroredNodes.entries()].filter(([nodeId]) => {
1293
1219
  const erroredNodeAttachedData = this.#getAttachedDataTo(nodeId);
1294
1220
  return erroredNodeAttachedData.races == null || erroredNodeAttachedData.races.completed === false;
1295
1221
  });
@@ -1314,7 +1240,7 @@ export class GraphProcessor {
1314
1240
  const erroredNodes = this.#getUnhandledErroredNodes();
1315
1241
  const branchFailures = [
1316
1242
  ...(includeManagedAsyncFailures ? this.#managedAsyncBranchFailures : []),
1317
- ...this.#streamingWatchFailures,
1243
+ ...this.#boundaries.streamingWatchFailures,
1318
1244
  ];
1319
1245
  if (this.#lifecycle.abortSuccessful ||
1320
1246
  (!this.#lifecycle.isAborted && !erroredNodes.length && !branchFailures.length)) {
@@ -1330,11 +1256,11 @@ export class GraphProcessor {
1330
1256
  throw error;
1331
1257
  }
1332
1258
  async #finalizeGraphRun() {
1333
- const outputValues = this.#graphOutputs;
1259
+ const outputValues = this.#run.graphOutputs;
1334
1260
  if (this.#suppressGraphLifecycleEvents) {
1335
1261
  return outputValues;
1336
1262
  }
1337
- ensureGraphCostOutput(this.#graphOutputs, this.#totalCost);
1263
+ ensureGraphCostOutput(this.#run.graphOutputs, this.#run.totalCost, this.#run.costBreakdown);
1338
1264
  await this.#emitter.emit('graphFinish', this.#withExecution({ graph: this.#graph, outputs: outputValues }));
1339
1265
  if (!this.#isSubProcessor) {
1340
1266
  await this.#emitter.emit('done', { results: outputValues });
@@ -1344,16 +1270,16 @@ export class GraphProcessor {
1344
1270
  async #loadProjectReferences() {
1345
1271
  if ((this.#project.references?.length ?? 0) > 0) {
1346
1272
  if (this.#cacheLoadedProjects && this.#runtimeCache?.loadedProjects) {
1347
- this.#loadedProjects = { ...this.#runtimeCache.loadedProjects };
1273
+ this.#run.loadedProjects = { ...this.#runtimeCache.loadedProjects };
1348
1274
  await this.#loadSubgraphProjectTargets();
1349
1275
  return;
1350
1276
  }
1351
- if (!this.#context.projectReferenceLoader) {
1277
+ if (!this.#run.context.projectReferenceLoader) {
1352
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.');
1353
1279
  }
1354
- 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);
1355
1281
  if (this.#cacheLoadedProjects && this.#runtimeCache) {
1356
- this.#runtimeCache.loadedProjects = { ...this.#loadedProjects };
1282
+ this.#runtimeCache.loadedProjects = { ...this.#run.loadedProjects };
1357
1283
  }
1358
1284
  }
1359
1285
  await this.#loadSubgraphProjectTargets();
@@ -1396,22 +1322,22 @@ export class GraphProcessor {
1396
1322
  version: node.data.targetVersion ?? 'latest',
1397
1323
  };
1398
1324
  const key = getSubgraphProjectKey(target);
1399
- let resolved = this.#subgraphTargetCache.get(key);
1325
+ let resolved = this.#shared.subgraphTargetCache.get(key);
1400
1326
  if (!resolved) {
1401
- if (!this.#context.subgraphProjectLoader) {
1327
+ if (!this.#run.context.subgraphProjectLoader) {
1402
1328
  throw new Error('Subgraph calls to another project require a subgraphProjectLoader. Use a project bundle locally or run through Rivet Studio Server.');
1403
1329
  }
1404
- resolved = await this.#context.subgraphProjectLoader.loadTarget(target);
1330
+ resolved = await this.#run.context.subgraphProjectLoader.loadTarget(target);
1405
1331
  if (resolved.project.metadata.id !== target.projectId) {
1406
1332
  throw new Error(`Subgraph target ${target.projectId} resolved to a different project.`);
1407
1333
  }
1408
- this.#subgraphTargetCache.set(key, resolved);
1334
+ this.#shared.subgraphTargetCache.set(key, resolved);
1409
1335
  }
1410
1336
  childOwner = resolved.project;
1411
- if (Object.hasOwn(this.#loadedProjects, key) && this.#loadedProjects[key] !== childOwner) {
1337
+ if (Object.hasOwn(this.#run.loadedProjects, key) && this.#run.loadedProjects[key] !== childOwner) {
1412
1338
  throw new Error('Subgraph target collides with an existing project reference.');
1413
1339
  }
1414
- Object.defineProperty(this.#loadedProjects, key, {
1340
+ Object.defineProperty(this.#run.loadedProjects, key, {
1415
1341
  configurable: true,
1416
1342
  enumerable: true,
1417
1343
  value: childOwner,
@@ -1428,9 +1354,9 @@ export class GraphProcessor {
1428
1354
  await visit(this.#project, this.#graph.metadata.id, 0);
1429
1355
  // Streaming topology may visit any resolved target, including a version of
1430
1356
  // a project with the same metadata ID as another selected target.
1431
- for (const [key, resolved] of this.#subgraphTargetCache) {
1432
- if (!Object.hasOwn(this.#loadedProjects, key)) {
1433
- Object.defineProperty(this.#loadedProjects, key, {
1357
+ for (const [key, resolved] of this.#shared.subgraphTargetCache) {
1358
+ if (!Object.hasOwn(this.#run.loadedProjects, key)) {
1359
+ Object.defineProperty(this.#run.loadedProjects, key, {
1434
1360
  configurable: true,
1435
1361
  enumerable: true,
1436
1362
  value: resolved.project,
@@ -1448,9 +1374,40 @@ export class GraphProcessor {
1448
1374
  return getMissingRequiredInputs(this.#executionState, node);
1449
1375
  }
1450
1376
  /** Accumulates cost from a node's output. */
1451
- #accumulateCost(output) {
1452
- if (output['cost']?.type === 'number') {
1453
- 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);
1454
1411
  }
1455
1412
  }
1456
1413
  async #fetchNodeDataAndProcessNode(node) {
@@ -1458,16 +1415,16 @@ export class GraphProcessor {
1458
1415
  return;
1459
1416
  const profileStart = this.#startRuntimeProfile();
1460
1417
  try {
1461
- if (this.#currentlyProcessing.has(node.id)) {
1418
+ if (this.#run.currentlyProcessing.has(node.id)) {
1462
1419
  return;
1463
1420
  }
1464
1421
  if (this.#propagateCompletedContinuationNode(node, true)) {
1465
1422
  return;
1466
1423
  }
1467
- if (this.#queuedNodes.has(node.id)) {
1424
+ if (this.#run.queuedNodes.has(node.id)) {
1468
1425
  return;
1469
1426
  }
1470
- 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)) {
1471
1428
  return;
1472
1429
  }
1473
1430
  const inputNodesProfileStart = this.#startRuntimeProfile();
@@ -1492,8 +1449,8 @@ export class GraphProcessor {
1492
1449
  };
1493
1450
  }
1494
1451
  }
1495
- this.#queuedNodes.add(node.id);
1496
- void this.#processingQueue.addAll(inputNodes.map((inputNode) => {
1452
+ this.#run.queuedNodes.add(node.id);
1453
+ void this.#run.processingQueue.addAll(inputNodes.map((inputNode) => {
1497
1454
  return async () => {
1498
1455
  this.#emitTraceEvent(`Fetching required data for node ${inputNode.title} (${inputNode.id})`);
1499
1456
  await this.#fetchNodeDataAndProcessNode(inputNode);
@@ -1510,10 +1467,10 @@ export class GraphProcessor {
1510
1467
  if (!this.#isNodeSelected(node.id))
1511
1468
  return [];
1512
1469
  // Waiting graph callers must not occupy a queue slot needed by their producer.
1513
- if (this.#callerInputStreams.has(node.id) && !options.streamingDispatch) {
1470
+ if (this.#boundaries.callerInputStreams.has(node.id) && !options.streamingDispatch) {
1514
1471
  const task = this.#processNodeIfAllInputsAvailable(node, { ...options, streamingDispatch: true }).catch((error) => this.#nodeErrored(node, error, nanoid()));
1515
- this.#streamCallerTasks.add(task);
1516
- 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));
1517
1474
  return [];
1518
1475
  }
1519
1476
  const { queueOutputNodes = true } = options;
@@ -1529,11 +1486,11 @@ export class GraphProcessor {
1529
1486
  return [];
1530
1487
  }
1531
1488
  const namedInput = node.type === 'graphInput' ? node.data.id : undefined;
1532
- const inputStream = namedInput != null && Object.hasOwn(this.#graphInputStreams, namedInput)
1533
- ? this.#graphInputStreams[namedInput]
1489
+ const inputStream = namedInput != null && Object.hasOwn(this.#boundaries.graphInputStreams, namedInput)
1490
+ ? this.#boundaries.graphInputStreams[namedInput]
1534
1491
  : undefined;
1535
1492
  if (inputStream) {
1536
- const terminals = Object.values(this.#graphInputStreams).map((stream) => stream.result);
1493
+ const terminals = Object.values(this.#boundaries.graphInputStreams).map((stream) => stream.result);
1537
1494
  // A containing invocation cannot release a successful final into a deeper
1538
1495
  // caller when another required input failed or was excluded.
1539
1496
  const terminal = terminals.find((result) => result?.error) ??
@@ -1555,8 +1512,8 @@ export class GraphProcessor {
1555
1512
  return [];
1556
1513
  }
1557
1514
  else if (node.type !== 'graphInput' &&
1558
- !this.#callerInputStreams.has(node.id) &&
1559
- 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')) {
1560
1517
  // Only streaming boundary plumbing runs early; ordinary side effects wait.
1561
1518
  return [];
1562
1519
  }
@@ -1572,7 +1529,7 @@ export class GraphProcessor {
1572
1529
  this.#emitTraceEvent(`Node ${node.title} is excluded due to control flow`);
1573
1530
  return loopExclusion === true ? [] : loopExclusion;
1574
1531
  }
1575
- const streamedInputs = this.#callerInputStreams.get(node.id);
1532
+ const streamedInputs = this.#boundaries.callerInputStreams.get(node.id);
1576
1533
  const blockingInputNodes = streamedInputs
1577
1534
  ? inputNodes.filter((inputNode) => this.#getInputConnectionsForNode(node).some((edge) => edge.outputNodeId === inputNode.id && !streamedInputs[edge.inputId]))
1578
1535
  : inputNodes;
@@ -1620,9 +1577,9 @@ export class GraphProcessor {
1620
1577
  await new Promise((resolve) => setTimeout(resolve, 250));
1621
1578
  }
1622
1579
  this.#emitTraceEvent(`Finished processing node ${node.title} (${node.id})`);
1623
- this.#visitedNodes.add(node.id);
1624
- this.#currentlyProcessing.delete(node.id);
1625
- 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);
1626
1583
  const outputNodesProfileStart = this.#startRuntimeProfile();
1627
1584
  const outputNodes = getOutputNodesFrom(this.#executionState, node);
1628
1585
  this.#finishRuntimeProfile('getOutputNodesFrom', outputNodesProfileStart);
@@ -1648,7 +1605,7 @@ export class GraphProcessor {
1648
1605
  }
1649
1606
  #propagateCompletedContinuationNode(node, queueOutputNodes) {
1650
1607
  const ownerLLMNodeId = this.#continuationCompletionOwnerByNodeId.get(node.id);
1651
- if (ownerLLMNodeId == null || !this.#nodeResults.has(ownerLLMNodeId)) {
1608
+ if (ownerLLMNodeId == null || !this.#run.nodeResults.has(ownerLLMNodeId)) {
1652
1609
  return undefined;
1653
1610
  }
1654
1611
  this.#continuationCompletionOwnerByNodeId.delete(node.id);
@@ -1662,7 +1619,7 @@ export class GraphProcessor {
1662
1619
  return outputNodes.nodes;
1663
1620
  }
1664
1621
  #shouldSkipNodeProcessing(node, inputNodes) {
1665
- if (this.#ignoreNodes.has(node.id)) {
1622
+ if (this.#run.ignoreNodes.has(node.id)) {
1666
1623
  this.#emitTraceEvent(`Node ${node.title} is ignored`);
1667
1624
  return true;
1668
1625
  }
@@ -1673,15 +1630,15 @@ export class GraphProcessor {
1673
1630
  return true;
1674
1631
  }
1675
1632
  }
1676
- if (this.#currentlyProcessing.has(node.id)) {
1633
+ if (this.#run.currentlyProcessing.has(node.id)) {
1677
1634
  this.#emitTraceEvent(`Node ${node.title} is already being processed`);
1678
1635
  return true;
1679
1636
  }
1680
- if (this.#visitedNodes.has(node.id) && node.type !== 'loopController') {
1637
+ if (this.#run.visitedNodes.has(node.id) && node.type !== 'loopController') {
1681
1638
  this.#emitTraceEvent(`Node ${node.title} has already been processed`);
1682
1639
  return true;
1683
1640
  }
1684
- if (this.#erroredNodes.has(node.id)) {
1641
+ if (this.#run.erroredNodes.has(node.id)) {
1685
1642
  this.#emitTraceEvent(`Node ${node.title} has already errored`);
1686
1643
  return true;
1687
1644
  }
@@ -1700,9 +1657,9 @@ export class GraphProcessor {
1700
1657
  if (this.#shouldSkipCompletedRaceNode(node, attachedData)) {
1701
1658
  return false;
1702
1659
  }
1703
- this.#currentlyProcessing.add(node.id);
1660
+ this.#run.currentlyProcessing.add(node.id);
1704
1661
  if (node.type === 'loopController') {
1705
- this.#loopControllersSeen.add(node.id);
1662
+ this.#run.loopControllersSeen.add(node.id);
1706
1663
  }
1707
1664
  this.#registerNodeInActiveLoop(node, attachedData);
1708
1665
  return true;
@@ -1723,7 +1680,7 @@ export class GraphProcessor {
1723
1680
  if (node.type !== 'loopController') {
1724
1681
  return;
1725
1682
  }
1726
- const loopControllerResults = this.#nodeResults.get(node.id);
1683
+ const loopControllerResults = this.#run.nodeResults.get(node.id);
1727
1684
  const breakValue = loopControllerResults['break'];
1728
1685
  const didBreak = didLoopControllerBreak(breakValue);
1729
1686
  if (didBreak) {
@@ -1733,10 +1690,10 @@ export class GraphProcessor {
1733
1690
  for (const loopNodeId of attachedData.loopInfo?.nodes ?? []) {
1734
1691
  const cycleNode = this.#nodesById[loopNodeId];
1735
1692
  this.#emitTraceEvent(`Clearing cycle node ${cycleNode.title} (${cycleNode.id})`);
1736
- this.#visitedNodes.delete(cycleNode.id);
1737
- this.#currentlyProcessing.delete(cycleNode.id);
1738
- this.#remainingNodes.add(cycleNode.id);
1739
- 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);
1740
1697
  }
1741
1698
  }
1742
1699
  #handleCompletedRace(node) {
@@ -1744,7 +1701,7 @@ export class GraphProcessor {
1744
1701
  return;
1745
1702
  }
1746
1703
  const raceId = `race-${node.id}`;
1747
- const allNodesForRace = [...this.#attachedNodeData.entries()].filter(([, { races }]) => races?.raceIds.includes(raceId));
1704
+ const allNodesForRace = [...this.#run.attachedNodeData.entries()].filter(([, { races }]) => races?.raceIds.includes(raceId));
1748
1705
  for (const [, nodeAttachedData] of allNodesForRace) {
1749
1706
  if (nodeAttachedData.races?.raceIds.includes(raceId)) {
1750
1707
  nodeAttachedData.races.completed = true;
@@ -1794,22 +1751,22 @@ export class GraphProcessor {
1794
1751
  }
1795
1752
  }
1796
1753
  #queueOutputNodes(node, outputNodes) {
1797
- const selectedOutputs = this.#graphOutputSelection
1754
+ const selectedOutputs = this.#run.graphOutputSelection
1798
1755
  ? outputNodes.filter((outputNode) => this.#isNodeSelected(outputNode.id))
1799
1756
  : outputNodes;
1800
1757
  const relevantNodeIds = this.#getExecutionRelevantNodeIds();
1801
1758
  for (const outputNode of selectedOutputs) {
1802
- if (relevantNodeIds?.has(outputNode.id) && this.#deferredRunToIgnoredNodes.delete(outputNode.id)) {
1803
- this.#ignoreNodes.delete(outputNode.id);
1759
+ if (relevantNodeIds?.has(outputNode.id) && this.#run.deferredRunToIgnoredNodes.delete(outputNode.id)) {
1760
+ this.#run.ignoreNodes.delete(outputNode.id);
1804
1761
  }
1805
1762
  }
1806
- void this.#processingQueue.addAll(selectedOutputs.map((outputNode) => async () => {
1763
+ void this.#run.processingQueue.addAll(selectedOutputs.map((outputNode) => async () => {
1807
1764
  this.#emitTraceEvent(`Trying to run output node from ${node.title}: ${outputNode.title} (${outputNode.id})`);
1808
1765
  await this.#processNodeIfAllInputsAvailable(outputNode);
1809
1766
  }));
1810
1767
  }
1811
1768
  #startManagedAsyncBranch(triggerNode) {
1812
- const outputs = this.#nodeResults.get(triggerNode.id);
1769
+ const outputs = this.#run.nodeResults.get(triggerNode.id);
1813
1770
  if (!outputs) {
1814
1771
  return;
1815
1772
  }
@@ -1850,53 +1807,29 @@ export class GraphProcessor {
1850
1807
  const root = this.getRootProcessor();
1851
1808
  const sameGraphOwner = this.#sameGraphRunOwnerOverride ?? this;
1852
1809
  const isRootGraphOrigin = !sameGraphOwner.#isSubProcessor;
1853
- if (root.#abortController.signal.aborted) {
1854
- 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');
1855
1812
  }
1856
1813
  const graphId = plan.graph.metadata?.id;
1857
1814
  if (!graphId) {
1858
1815
  throw new Error('Cannot start an async branch because the current graph has no ID.');
1859
1816
  }
1860
- const branchRuntimeCache = {
1861
- ...this.#runtimeCache,
1862
- graphBoundaries: undefined,
1863
- loadedProjects: { ...this.#loadedProjects },
1864
- };
1865
- const processor = new GraphProcessor(this.#project, graphId, this.#registry, this.#includeTrace, {
1866
- cacheLoadedProjects: true,
1867
- captureNodeTimings: this.#captureNodeTimings,
1868
- concurrency: this.#concurrency,
1869
- executionPlanCacheMode: this.#executionPlanCacheMode,
1870
- runtimeCache: branchRuntimeCache,
1871
- runtimeProfiler: this.#runtimeProfiler,
1872
- scheduler: this.#scheduler,
1873
- [graphProcessorGraphOverride]: plan.graph,
1874
- [consumedAsyncBranchTriggerOverride]: triggerNode.id,
1875
- [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
1876
1822
  .filter((connection) => connection.inputNodeId === triggerNode.id)
1877
1823
  .map((connection) => [connection.outputNodeId, this.#definitions[connection.outputNodeId]])),
1824
+ onCreated: onProcessorCreated,
1878
1825
  });
1879
- onProcessorCreated(processor);
1880
- processor.executor = this.executor;
1881
- processor.#isSubProcessor = true;
1882
- processor.#subgraphTargetCache = this.#subgraphTargetCache;
1883
- processor.#recordingProjectScope = this.#recordingProjectScope;
1884
- processor.#executionCache = this.#executionCache;
1885
- processor.#externalFunctions = this.#externalFunctions;
1886
- processor.#contextValues = this.#contextValues;
1887
1826
  processor.#parent = sameGraphOwner;
1888
- processor.#graphCallPath = this.#graphCallPath;
1889
1827
  processor.#abortOwnerOverride = root;
1890
1828
  processor.#suppressGraphPartialOutputs = true;
1891
- processor.#globals = this.#globals;
1892
- processor.#storedValueController = this.#storedValueController;
1893
- processor.#knowledgeStoreController = this.#knowledgeStoreController;
1894
- processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
1895
- processor.#executor = this.#executor;
1896
1829
  processor.#suppressGraphLifecycleEvents = isRootGraphOrigin;
1897
1830
  processor.#sharedRunStateOverride = {
1898
- attachedNodeData: this.#attachedNodeData,
1899
- graphInputNodeValues: this.#graphInputNodeValues,
1831
+ attachedNodeData: this.#run.attachedNodeData,
1832
+ graphInputNodeValues: this.#run.graphInputNodeValues,
1900
1833
  // Async branches cannot contain Graph Output nodes. Keep their synthetic
1901
1834
  // boundary outputs private so branch finalization cannot seed the root's
1902
1835
  // derived cost output before the root has accumulated every path.
@@ -1906,56 +1839,36 @@ export class GraphProcessor {
1906
1839
  processor.runToNodeIds = branchRunToNodeIds?.length ? branchRunToNodeIds : undefined;
1907
1840
  processor.#executionIdentityOverride = isRootGraphOrigin
1908
1841
  ? {
1909
- rootRunId: this.#rootRunId,
1910
- graphRunId: this.#graphRunId,
1911
- parentGraphRunId: this.#parentGraphRunId,
1842
+ rootRunId: this.#run.rootRunId,
1843
+ graphRunId: this.#run.graphRunId,
1844
+ parentGraphRunId: this.#run.parentGraphRunId,
1912
1845
  }
1913
1846
  : {
1914
- rootRunId: root.#rootRunId,
1847
+ rootRunId: root.#run.rootRunId,
1915
1848
  graphRunId: nanoid(),
1916
- parentGraphRunId: sameGraphOwner.#graphRunId,
1849
+ parentGraphRunId: sameGraphOwner.#run.graphRunId,
1917
1850
  };
1918
1851
  processor.preloadNodeData(triggerNode.id, triggerOutputs);
1919
1852
  processor.#suppressedPreloadedNodeIds.add(triggerNode.id);
1920
- const unwireEvents = wireSubprocessorEvents(processor, root.#emitter, {
1853
+ const unwireEvents = this.#wireChildEvents(processor, root, {
1921
1854
  autoCleanup: false,
1922
- isPaused: () => root.#lifecycle.isPaused,
1923
- pause: () => {
1924
- void root.pause();
1925
- },
1926
- resume: () => {
1927
- void root.resume();
1928
- },
1929
1855
  });
1930
- const unwireLifecycle = wireSubprocessorLifecycle(processor, {
1856
+ const unwireLifecycle = this.#wireChildLifecycle(processor, root, unwireEvents, {
1931
1857
  autoCleanup: false,
1932
- signal: sameGraphOwner === root ? undefined : sameGraphOwner.#abortController.signal,
1933
- parentAbortSignal: root.#abortController.signal,
1934
- onParentPause: (listener) => {
1935
- root.on('pause', listener);
1936
- return () => {
1937
- root.off('pause', listener);
1938
- };
1939
- },
1940
- onParentResume: (listener) => {
1941
- root.on('resume', listener);
1942
- return () => {
1943
- root.off('resume', listener);
1944
- };
1945
- },
1858
+ signal: sameGraphOwner === root ? undefined : sameGraphOwner.#run.abortController.signal,
1946
1859
  });
1947
- root.#subprocessors.add(processor);
1860
+ root.#run.subprocessors.add(processor);
1861
+ let executionFailed = true;
1948
1862
  try {
1949
1863
  if (root.#lifecycle.isPaused) {
1950
1864
  processor.pause();
1951
1865
  }
1952
- await processor.processGraph(this.#context, this.#graphInputs, this.#contextValues);
1866
+ await processor.processGraph(this.#run.context, this.#run.graphInputs, this.#contextValues);
1867
+ executionFailed = false;
1953
1868
  }
1954
1869
  finally {
1955
- root.#totalCost += processor.#totalCost;
1956
- unwireLifecycle();
1957
- unwireEvents();
1958
- root.#subprocessors.delete(processor);
1870
+ root.#accumulateChildCost(processor);
1871
+ this.#releaseChildInvocation(processor, root, unwireLifecycle, unwireEvents, executionFailed);
1959
1872
  }
1960
1873
  }
1961
1874
  #recordManagedAsyncBranchFailure(triggerNode, processor, error) {
@@ -1966,22 +1879,22 @@ export class GraphProcessor {
1966
1879
  });
1967
1880
  }
1968
1881
  #getSubprocessorNodeErrors(processor) {
1969
- if (!processor || !processor.#erroredNodes) {
1882
+ if (!processor || !processor.#run.erroredNodes) {
1970
1883
  return [];
1971
1884
  }
1972
- return [...processor.#erroredNodes.entries()].flatMap(([nodeId, nodeError]) => {
1885
+ return [...processor.#run.erroredNodes.entries()].flatMap(([nodeId, nodeError]) => {
1973
1886
  const node = processor.#nodesById[nodeId];
1974
1887
  return node ? [{ error: nodeError, node }] : [];
1975
1888
  });
1976
1889
  }
1977
1890
  #recordStreamingWatchFailure(watchNode, error, processor) {
1978
- if (this.#streamingWatchFailures.some((failure) => failure.error === error)) {
1891
+ if (this.#boundaries.streamingWatchFailures.some((failure) => failure.error === error)) {
1979
1892
  return;
1980
1893
  }
1981
1894
  // The child processor already emitted the precise nodeError before its
1982
1895
  // failure reaches the coordinator. Keep a root-owned failure too so the
1983
1896
  // normal graphError/error lifecycle remains truthful after draining.
1984
- this.#streamingWatchFailures.push({
1897
+ this.#boundaries.streamingWatchFailures.push({
1985
1898
  error,
1986
1899
  nodeErrors: this.#getSubprocessorNodeErrors(processor),
1987
1900
  triggerNode: watchNode,
@@ -1989,18 +1902,18 @@ export class GraphProcessor {
1989
1902
  }
1990
1903
  #getAttachedDataTo(node) {
1991
1904
  const nodeId = typeof node === 'string' ? node : node.id;
1992
- let nodeData = this.#attachedNodeData.get(nodeId);
1905
+ let nodeData = this.#run.attachedNodeData.get(nodeId);
1993
1906
  if (nodeData == null) {
1994
1907
  nodeData = {};
1995
- this.#attachedNodeData.set(nodeId, nodeData);
1908
+ this.#run.attachedNodeData.set(nodeId, nodeData);
1996
1909
  }
1997
1910
  return nodeData;
1998
1911
  }
1999
1912
  async #processNode(node, inputValues) {
2000
1913
  const processId = nanoid();
2001
- if (this.#abortController.signal.aborted) {
2002
- await this.#nodeErrored(node, createGraphAbortErrorFromSignal(this.#abortController.signal), processId);
2003
- 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);
2004
1917
  return { processId, shouldQueueOutputNodes: false };
2005
1918
  }
2006
1919
  const frozenOutputs = this.#resolveFrozenNodeOutputs(node, inputValues, processId);
@@ -2019,7 +1932,7 @@ export class GraphProcessor {
2019
1932
  else {
2020
1933
  await this.#processNormalNode(node, processId, inputValues);
2021
1934
  }
2022
- const successfulAbortTerminal = this.#successfulAbortTerminalProcessIds.delete(processId);
1935
+ const successfulAbortTerminal = this.#run.successfulAbortTerminalProcessIds.delete(processId);
2023
1936
  return { processId, shouldQueueOutputNodes: !successfulAbortTerminal };
2024
1937
  }
2025
1938
  async #processSplitRunNode(node, processId) {
@@ -2030,13 +1943,13 @@ export class GraphProcessor {
2030
1943
  isExcludedDueToControlFlow: (n, inputs, pid) => this.#excludedDueToControlFlow(n, inputs, pid) !== false,
2031
1944
  processNodeWithInputData: (n, inputs, idx, pid, partial, markResultAsEditorCacheHit) => this.#processNodeWithInputData(n, inputs, idx, pid, partial, markResultAsEditorCacheHit),
2032
1945
  splitRunConcurrency: this.#concurrency.splitRunConcurrency,
2033
- accumulateCost: (output) => this.#accumulateCost(output),
2034
- setNodeResults: (nodeId, outputs) => this.#nodeResults.set(nodeId, outputs),
2035
- 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),
2036
1949
  nodeErrored: (n, err, pid, durationMs, splitRunDurationMs, resultOrigin, splitOutputs) => this.#nodeErrored(n, err, pid, durationMs, splitRunDurationMs, resultOrigin, undefined, splitOutputs),
2037
1950
  takeFailureOutputs: (pid, index) => this.#takeFailureOutputs(pid, index),
2038
1951
  isAborted: () => this.#lifecycle.isAborted,
2039
- getAbortError: () => createGraphAbortErrorFromSignal(this.#abortController.signal),
1952
+ getAbortError: () => createGraphAbortErrorFromSignal(this.#run.abortController.signal),
2040
1953
  emit: (event, data) => {
2041
1954
  if (event === 'partialOutput') {
2042
1955
  emitDetached(this.#emitter, event, this.#withExecution(data));
@@ -2072,9 +1985,9 @@ export class GraphProcessor {
2072
1985
  resultOrigin: 'frozen',
2073
1986
  }));
2074
1987
  const timingStart = this.#startNodeTiming();
2075
- this.#nodeResults.set(node.id, outputValues);
2076
- this.#visitedNodes.add(node.id);
2077
- this.#accumulateCost(outputValues);
1988
+ this.#run.nodeResults.set(node.id, outputValues);
1989
+ this.#run.visitedNodes.add(node.id);
1990
+ this.#accumulateCost(outputValues, node.type);
2078
1991
  await this.#applyFrozenNodeDataflowEffects(node, outputValues, processId);
2079
1992
  this.#assertStreamingOutputWatchFinalOutputs(node, outputValues);
2080
1993
  await this.#emitter.emit('nodeFinish', this.#withExecution(withOptionalDuration({
@@ -2086,15 +1999,15 @@ export class GraphProcessor {
2086
1999
  this.#finishStreamingOutputWatches(node, outputValues);
2087
2000
  }
2088
2001
  async #applyFrozenNodeDataflowEffects(node, outputValues, processId) {
2089
- const effect = applyFrozenGraphBoundaryEffects(this.#graphOutputs, node, outputValues);
2002
+ const effect = applyFrozenGraphBoundaryEffects(this.#run.graphOutputs, node, outputValues);
2090
2003
  if (!effect) {
2091
2004
  return;
2092
2005
  }
2093
2006
  if (effect.type === 'setStoredValue') {
2094
- await this.#storedValueController.seed(effect.key, effect.value);
2007
+ await this.#shared.storedValueController.seed(effect.key, effect.value);
2095
2008
  return;
2096
2009
  }
2097
- this.#globals.set(effect.variableId, effect.value);
2010
+ this.#shared.globals.set(effect.variableId, effect.value);
2098
2011
  emitDetached(this.#emitter, 'globalSet', this.#withExecution({ id: effect.variableId, value: effect.value, processId }));
2099
2012
  }
2100
2013
  async #processNormalNode(node, processId, inputValues) {
@@ -2113,9 +2026,9 @@ export class GraphProcessor {
2113
2026
  const outputValues = await this.#processNodeWithInputData(node, inputValues, 0, processId, (node, partialOutputs, index) => this.#emitNodePartialOutput(node, partialOutputs, index, processId), () => {
2114
2027
  resultOrigin = 'editor-cache';
2115
2028
  });
2116
- this.#nodeResults.set(node.id, outputValues);
2117
- this.#visitedNodes.add(node.id);
2118
- this.#accumulateCost(outputValues);
2029
+ this.#run.nodeResults.set(node.id, outputValues);
2030
+ this.#run.visitedNodes.add(node.id);
2031
+ this.#accumulateCost(outputValues, node.type);
2119
2032
  this.#assertStreamingOutputWatchFinalOutputs(node, outputValues);
2120
2033
  const stopClaim = this.#claimStreamingWatchStopFromInvocation(node, outputValues);
2121
2034
  await this.#emitter.emit('nodeFinish', this.#withExecution(withOptionalDuration({
@@ -2134,7 +2047,7 @@ export class GraphProcessor {
2134
2047
  }
2135
2048
  async #nodeErrored(node, e, processId, durationMs, splitRunDurationMs, resultOrigin = 'executed', outputs, splitOutputs) {
2136
2049
  const error = getError(e);
2137
- for (const route of this.#inputStreamRoutes.get(node.id) ?? [])
2050
+ for (const route of this.#boundaries.inputStreamRoutes.get(node.id) ?? [])
2138
2051
  route.relay.finish({ error });
2139
2052
  // Most callers are ordinary (non-split) node executions. Let those retain
2140
2053
  // any checkpoint without requiring every error path to know about the
@@ -2148,7 +2061,7 @@ export class GraphProcessor {
2148
2061
  }
2149
2062
  this.#cancelStreamingOutputWatchesForSource(node.id);
2150
2063
  this.#cancelStreamingCatchesForSource(node.id);
2151
- this.#erroredNodes.set(node.id, error);
2064
+ this.#run.erroredNodes.set(node.id, error);
2152
2065
  await this.#emitter.emit('nodeError', this.#withExecution(withOptionalDuration({
2153
2066
  node,
2154
2067
  error,
@@ -2163,19 +2076,19 @@ export class GraphProcessor {
2163
2076
  emitDetached(this.#emitter, 'partialOutput', this.#withExecution({ node, outputs, index, processId, resultOrigin: 'executed' }));
2164
2077
  }
2165
2078
  #setFailureOutputs(processId, index, outputs) {
2166
- let outputsByIndex = this.#failureOutputsByProcessId.get(processId);
2079
+ let outputsByIndex = this.#run.failureOutputsByProcessId.get(processId);
2167
2080
  if (!outputsByIndex) {
2168
2081
  outputsByIndex = new Map();
2169
- this.#failureOutputsByProcessId.set(processId, outputsByIndex);
2082
+ this.#run.failureOutputsByProcessId.set(processId, outputsByIndex);
2170
2083
  }
2171
2084
  outputsByIndex.set(index, outputs);
2172
2085
  }
2173
2086
  #takeFailureOutputs(processId, index) {
2174
- const outputsByIndex = this.#failureOutputsByProcessId.get(processId);
2087
+ const outputsByIndex = this.#run.failureOutputsByProcessId.get(processId);
2175
2088
  const outputs = outputsByIndex?.get(index);
2176
2089
  outputsByIndex?.delete(index);
2177
2090
  if (outputsByIndex?.size === 0) {
2178
- this.#failureOutputsByProcessId.delete(processId);
2091
+ this.#run.failureOutputsByProcessId.delete(processId);
2179
2092
  }
2180
2093
  return outputs;
2181
2094
  }
@@ -2191,7 +2104,7 @@ export class GraphProcessor {
2191
2104
  return RACE_LOSER_EXCLUSION_REASON;
2192
2105
  }
2193
2106
  if (isSuccessfulNonRaceGraphAbortReason(abortReason)) {
2194
- this.#successfulAbortTerminalProcessIds.add(processId);
2107
+ this.#run.successfulAbortTerminalProcessIds.add(processId);
2195
2108
  return SUCCESSFUL_GRAPH_ABORT_EXCLUSION_REASON;
2196
2109
  }
2197
2110
  if (this.#lifecycle.abortSuccessful && isAbortLikeError(error)) {
@@ -2199,7 +2112,7 @@ export class GraphProcessor {
2199
2112
  ? RACE_LOSER_EXCLUSION_REASON
2200
2113
  : SUCCESSFUL_GRAPH_ABORT_EXCLUSION_REASON;
2201
2114
  if (exclusionReason === SUCCESSFUL_GRAPH_ABORT_EXCLUSION_REASON) {
2202
- this.#successfulAbortTerminalProcessIds.add(processId);
2115
+ this.#run.successfulAbortTerminalProcessIds.add(processId);
2203
2116
  }
2204
2117
  return exclusionReason;
2205
2118
  }
@@ -2223,17 +2136,12 @@ export class GraphProcessor {
2223
2136
  return undefined;
2224
2137
  }
2225
2138
  #getManagedAsyncBranchWatchViolation(triggerNode) {
2226
- const invocation = this.#getEnclosingStreamingWatchInvocation();
2227
- if (!invocation) {
2228
- return undefined;
2229
- }
2230
- return new Error(`Start Async Branch "${triggerNode.title}" cannot run inside Watch Streaming Output "${invocation.plan.watchNode.title}". ` +
2231
- '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);
2232
2140
  }
2233
2141
  /** Raise a user event on the processor, all subprocessors, and their children. */
2234
2142
  raiseEvent(event, data) {
2235
2143
  emitDetached(this.#emitter, `userEvent:${event}`, data);
2236
- for (const subprocessor of this.#subprocessors) {
2144
+ for (const subprocessor of this.#run.subprocessors) {
2237
2145
  subprocessor.raiseEvent(event, data);
2238
2146
  }
2239
2147
  }
@@ -2243,9 +2151,9 @@ export class GraphProcessor {
2243
2151
  return controller;
2244
2152
  }
2245
2153
  #registerNodeAbortController(nodeId, abortController) {
2246
- const existingAbortControllers = this.#nodeAbortControllers.get(nodeId);
2154
+ const existingAbortControllers = this.#run.nodeAbortControllers.get(nodeId);
2247
2155
  if (!existingAbortControllers) {
2248
- this.#nodeAbortControllers.set(nodeId, abortController);
2156
+ this.#run.nodeAbortControllers.set(nodeId, abortController);
2249
2157
  return;
2250
2158
  }
2251
2159
  if (existingAbortControllers instanceof Set) {
@@ -2255,15 +2163,15 @@ export class GraphProcessor {
2255
2163
  if (existingAbortControllers === abortController) {
2256
2164
  return;
2257
2165
  }
2258
- this.#nodeAbortControllers.set(nodeId, new Set([existingAbortControllers, abortController]));
2166
+ this.#run.nodeAbortControllers.set(nodeId, new Set([existingAbortControllers, abortController]));
2259
2167
  }
2260
2168
  #unregisterNodeAbortController(nodeId, abortController) {
2261
- const existingAbortControllers = this.#nodeAbortControllers.get(nodeId);
2169
+ const existingAbortControllers = this.#run.nodeAbortControllers.get(nodeId);
2262
2170
  if (!existingAbortControllers) {
2263
2171
  return;
2264
2172
  }
2265
2173
  if (existingAbortControllers === abortController) {
2266
- this.#nodeAbortControllers.delete(nodeId);
2174
+ this.#run.nodeAbortControllers.delete(nodeId);
2267
2175
  return;
2268
2176
  }
2269
2177
  if (!(existingAbortControllers instanceof Set)) {
@@ -2271,14 +2179,14 @@ export class GraphProcessor {
2271
2179
  }
2272
2180
  existingAbortControllers.delete(abortController);
2273
2181
  if (existingAbortControllers.size === 0) {
2274
- this.#nodeAbortControllers.delete(nodeId);
2182
+ this.#run.nodeAbortControllers.delete(nodeId);
2275
2183
  }
2276
2184
  else if (existingAbortControllers.size === 1) {
2277
- this.#nodeAbortControllers.set(nodeId, existingAbortControllers.values().next().value);
2185
+ this.#run.nodeAbortControllers.set(nodeId, existingAbortControllers.values().next().value);
2278
2186
  }
2279
2187
  }
2280
2188
  #abortNodeControllersForNode(nodeId, traceMessage, reason) {
2281
- const abortControllerEntry = this.#nodeAbortControllers.get(nodeId);
2189
+ const abortControllerEntry = this.#run.nodeAbortControllers.get(nodeId);
2282
2190
  if (!abortControllerEntry) {
2283
2191
  return;
2284
2192
  }
@@ -2297,7 +2205,7 @@ export class GraphProcessor {
2297
2205
  }
2298
2206
  }
2299
2207
  #abortActiveNodeControllers(reason) {
2300
- for (const nodeId of [...this.#nodeAbortControllers.keys()]) {
2208
+ for (const nodeId of [...this.#run.nodeAbortControllers.keys()]) {
2301
2209
  this.#abortNodeControllersForNode(nodeId, undefined, reason);
2302
2210
  }
2303
2211
  }
@@ -2310,8 +2218,8 @@ export class GraphProcessor {
2310
2218
  const instance = this.#nodeInstances[node.id];
2311
2219
  const nodeAbortController = this.#newAbortController();
2312
2220
  this.#registerNodeAbortController(node.id, nodeAbortController);
2313
- if (this.#abortController.signal.aborted) {
2314
- nodeAbortController.abort(getAbortSignalReason(this.#abortController.signal));
2221
+ if (this.#run.abortController.signal.aborted) {
2222
+ nodeAbortController.abort(getAbortSignalReason(this.#run.abortController.signal));
2315
2223
  }
2316
2224
  let continuationFinalized = false;
2317
2225
  try {
@@ -2338,7 +2246,7 @@ export class GraphProcessor {
2338
2246
  const abortReason = getGraphAbortReasonFromSignal(nodeAbortController.signal);
2339
2247
  if (nodeAbortController.signal.aborted) {
2340
2248
  if (isSuccessfulNonRaceGraphAbortReason(abortReason)) {
2341
- this.#successfulAbortTerminalProcessIds.add(processId);
2249
+ this.#run.successfulAbortTerminalProcessIds.add(processId);
2342
2250
  this.#discardFailureOutputs(processId, index);
2343
2251
  return results;
2344
2252
  }
@@ -2359,21 +2267,21 @@ export class GraphProcessor {
2359
2267
  }
2360
2268
  }
2361
2269
  #getTokenizer() {
2362
- return this.#context.tokenizer;
2270
+ return this.#run.context.tokenizer;
2363
2271
  }
2364
2272
  #createNodeProcessContext(node, inputValues, index, processId, nodeAbortController, partialOutput, toolCallTraceSource, markResultAsEditorCacheHit) {
2365
2273
  const plugin = this.#registry.getPluginFor(node.type);
2366
2274
  const acceptsPartialOutputs = () => {
2367
2275
  if (nodeAbortController.signal.aborted)
2368
2276
  return false;
2369
- const active = this.#nodeAbortControllers.get(node.id);
2277
+ const active = this.#run.nodeAbortControllers.get(node.id);
2370
2278
  return active === nodeAbortController || (active instanceof Set && active.has(nodeAbortController));
2371
2279
  };
2372
2280
  const onGraphOutputPartial = canForwardGraphCallerOutputPartials(node) &&
2373
- (this.#streamingWatchPlansBySourceNodeId.has(node.id) ||
2374
- this.#streamingCatchPlansBySourceNodeId.has(node.id) ||
2375
- this.#inputStreamRoutes.has(node.id) ||
2376
- 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))
2377
2285
  ? (partialOutputs) => {
2378
2286
  if (!acceptsPartialOutputs())
2379
2287
  return;
@@ -2386,17 +2294,17 @@ export class GraphProcessor {
2386
2294
  const processContext = buildNodeProcessContext({
2387
2295
  activeOutputPortIds: this.#getActiveOutputPortIds(node),
2388
2296
  attachedData: this.#getAttachedDataTo(node),
2389
- base: this.#nodeProcessContextBase,
2297
+ base: this.#run.nodeProcessContextBase,
2390
2298
  createSubProcessor: (subGraphId, options = {}) => this.#createSubProcessor(node, index, processId, subGraphId, options),
2391
2299
  execution: this.#buildExecutionMetadata(),
2392
2300
  externalFunctions: this.#externalFunctions,
2393
- getPluginConfig: (name) => getPluginConfig(plugin, this.#context.settings, name),
2301
+ getPluginConfig: (name) => getPluginConfig(plugin, this.#run.context.settings, name),
2394
2302
  isDirectRunTarget: this.runToNodeIds?.includes(node.id) ?? false,
2395
2303
  markResultAsEditorCacheHit,
2396
2304
  node,
2397
2305
  nodeAbortController,
2398
2306
  onGraphOutputPartial,
2399
- graphInputStreams: this.#callerInputStreams.get(node.id),
2307
+ graphInputStreams: this.#boundaries.callerInputStreams.get(node.id),
2400
2308
  onPartialOutputs: (partialOutputs) => {
2401
2309
  if (!acceptsPartialOutputs())
2402
2310
  return;
@@ -2424,7 +2332,7 @@ export class GraphProcessor {
2424
2332
  },
2425
2333
  splitIndex: node.isSplitRun ? index : 0,
2426
2334
  setGlobal: (id, value) => {
2427
- this.#globals.set(id, value);
2335
+ this.#shared.globals.set(id, value);
2428
2336
  emitDetached(this.#emitter, 'globalSet', this.#withExecution({ id, value, processId }));
2429
2337
  },
2430
2338
  toolCallContinuation,
@@ -2456,7 +2364,7 @@ export class GraphProcessor {
2456
2364
  });
2457
2365
  if (node.type === 'subGraph' && node.data.targetProjectId) {
2458
2366
  const data = node.data;
2459
- processContext.subgraphTarget = this.#subgraphTargetCache.get(getSubgraphProjectKey({
2367
+ processContext.subgraphTarget = this.#shared.subgraphTargetCache.get(getSubgraphProjectKey({
2460
2368
  projectId: data.targetProjectId,
2461
2369
  version: data.targetVersion ?? 'latest',
2462
2370
  }));
@@ -2506,9 +2414,9 @@ export class GraphProcessor {
2506
2414
  },
2507
2415
  commit: (invocation) => {
2508
2416
  for (const [nodeId, outputs] of invocation.latestOutputs) {
2509
- this.#nodeResults.set(nodeId, outputs);
2510
- this.#visitedNodes.add(nodeId);
2511
- this.#remainingNodes.delete(nodeId);
2417
+ this.#run.nodeResults.set(nodeId, outputs);
2418
+ this.#run.visitedNodes.add(nodeId);
2419
+ this.#run.remainingNodes.delete(nodeId);
2512
2420
  this.#continuationCompletionOwnerByNodeId.set(nodeId, invocation.llmNodeId);
2513
2421
  }
2514
2422
  },
@@ -2569,10 +2477,10 @@ export class GraphProcessor {
2569
2477
  resultOrigin: 'executed',
2570
2478
  })),
2571
2479
  getActiveOutputPortIds: (node) => this.#getActiveOutputPortIds(node),
2572
- getContinuationBranchBoundaryNodeIds: (llmNode) => new Set([llmNode.id, ...this.#currentlyProcessing]),
2573
- 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,
2574
2482
  registerNodeAbortController: (nodeId, controller) => this.#registerNodeAbortController(nodeId, controller),
2575
- rootAbortSignal: this.#abortController.signal,
2483
+ rootAbortSignal: this.#run.abortController.signal,
2576
2484
  unregisterNodeAbortController: (nodeId, controller) => this.#unregisterNodeAbortController(nodeId, controller),
2577
2485
  startNodeTiming: () => this.#startNodeTiming(),
2578
2486
  waitUntilUnpaused: () => this.#waitUntilUnpaused(),
@@ -2590,116 +2498,69 @@ export class GraphProcessor {
2590
2498
  if (!graphId) {
2591
2499
  throw new Error('Cannot execute a tool continuation branch because the current graph has no ID.');
2592
2500
  }
2593
- const branchRuntimeCache = {
2594
- ...this.#runtimeCache,
2595
- graphBoundaries: undefined,
2596
- loadedProjects: { ...this.#loadedProjects },
2597
- };
2598
- const branchGraphOutputs = createGraphOutputsOverlay(this.#graphOutputs);
2599
- const processor = new GraphProcessor(this.#project, graphId, this.#registry, this.#includeTrace, {
2600
- cacheLoadedProjects: true,
2601
- captureNodeTimings: this.#captureNodeTimings,
2602
- concurrency: this.#concurrency,
2603
- executionPlanCacheMode: this.#executionPlanCacheMode,
2604
- runtimeCache: branchRuntimeCache,
2605
- runtimeProfiler: this.#runtimeProfiler,
2606
- scheduler: this.#scheduler,
2607
- [graphProcessorGraphOverride]: branchPlan.graph,
2608
- });
2609
- processor.executor = this.executor;
2610
- processor.#isSubProcessor = true;
2611
- processor.#subgraphTargetCache = this.#subgraphTargetCache;
2612
- processor.#executionCache = this.#executionCache;
2613
- processor.#externalFunctions = this.#externalFunctions;
2614
- processor.#contextValues = this.#contextValues;
2615
- processor.#parent = this;
2616
- processor.#recordingProjectScope = this.#recordingProjectScope;
2617
- processor.#graphCallPath = this.#graphCallPath;
2501
+ const branchGraphOutputs = createGraphOutputsOverlay(this.#run.graphOutputs);
2502
+ const processor = this.#constructChildInvocation({ kind: 'continuation', graph: branchPlan.graph });
2618
2503
  processor.#abortOwnerOverride = this.#abortOwnerOverride ?? this;
2619
2504
  processor.#sameGraphRunOwnerOverride = this.#sameGraphRunOwnerOverride ?? this;
2620
- processor.#globals = this.#globals;
2621
- processor.#storedValueController = this.#storedValueController;
2622
- processor.#knowledgeStoreController = this.#knowledgeStoreController;
2623
- processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
2624
- processor.#executor = this.#executor;
2625
2505
  processor.#suppressGraphLifecycleEvents = true;
2626
2506
  processor.#sharedRunStateOverride = {
2627
- attachedNodeData: this.#attachedNodeData,
2628
- graphInputNodeValues: this.#graphInputNodeValues,
2507
+ attachedNodeData: this.#run.attachedNodeData,
2508
+ graphInputNodeValues: this.#run.graphInputNodeValues,
2629
2509
  graphOutputs: branchGraphOutputs.view,
2630
2510
  };
2631
2511
  const branchNodeIds = new Set(branchPlan.graph.nodes.map((node) => node.id));
2632
2512
  const branchRunToNodeIds = this.runToNodeIds?.filter((nodeId) => branchNodeIds.has(nodeId));
2633
2513
  processor.runToNodeIds = branchRunToNodeIds?.length ? branchRunToNodeIds : undefined;
2634
2514
  processor.#executionIdentityOverride = {
2635
- rootRunId: this.#rootRunId,
2636
- graphRunId: this.#graphRunId,
2637
- parentGraphRunId: this.#parentGraphRunId,
2515
+ rootRunId: this.#run.rootRunId,
2516
+ graphRunId: this.#run.graphRunId,
2517
+ parentGraphRunId: this.#run.parentGraphRunId,
2638
2518
  };
2639
2519
  for (const [nodeId, outputs] of branchPlan.preloadedOutputs) {
2640
2520
  processor.preloadNodeData(nodeId, outputs);
2641
2521
  processor.#suppressedPreloadedNodeIds.add(nodeId);
2642
2522
  }
2643
- const unwireEvents = wireSubprocessorEvents(processor, this.#emitter, {
2523
+ const unwireEvents = this.#wireChildEvents(processor, this, {
2644
2524
  autoCleanup: false,
2645
- isPaused: () => this.#lifecycle.isPaused,
2646
- pause: () => {
2647
- void this.pause();
2648
- },
2649
- resume: () => {
2650
- void this.resume();
2651
- },
2652
2525
  });
2653
- const unwireLifecycle = wireSubprocessorLifecycle(processor, {
2526
+ const unwireLifecycle = this.#wireChildLifecycle(processor, this, unwireEvents, {
2654
2527
  autoCleanup: false,
2655
2528
  signal,
2656
- parentAbortSignal: this.#abortController.signal,
2657
- onParentPause: (listener) => {
2658
- this.on('pause', listener);
2659
- return () => {
2660
- this.off('pause', listener);
2661
- };
2662
- },
2663
- onParentResume: (listener) => {
2664
- this.on('resume', listener);
2665
- return () => {
2666
- this.off('resume', listener);
2667
- };
2668
- },
2669
2529
  });
2670
- this.#subprocessors.add(processor);
2530
+ this.#run.subprocessors.add(processor);
2531
+ let executionFailed = true;
2671
2532
  try {
2672
2533
  if (signal.aborted) {
2673
2534
  throw createGraphAbortErrorFromSignal(signal, 'Tool continuation branch aborted');
2674
2535
  }
2675
- await processor.processGraph(this.#context, this.#graphInputs, this.#contextValues);
2536
+ await processor.processGraph(this.#run.context, this.#run.graphInputs, this.#contextValues);
2676
2537
  if (!deferGraphOutputCommit) {
2677
2538
  this.#commitContinuationGraphOutputs(branchGraphOutputs.writes);
2678
2539
  }
2679
- return {
2540
+ const result = {
2680
2541
  graphOutputWrites: branchGraphOutputs.writes,
2681
2542
  nodeOutputs: this.#getContinuationBranchResults(processor, branchPlan),
2682
2543
  };
2544
+ executionFailed = false;
2545
+ return result;
2683
2546
  }
2684
2547
  finally {
2685
- this.#totalCost += processor.#totalCost;
2686
- unwireLifecycle();
2687
- unwireEvents();
2688
- this.#subprocessors.delete(processor);
2548
+ this.#accumulateChildCost(processor);
2549
+ this.#releaseChildInvocation(processor, this, unwireLifecycle, unwireEvents, executionFailed);
2689
2550
  }
2690
2551
  }
2691
2552
  #commitContinuationGraphOutputs(writes) {
2692
2553
  for (const [outputId, value] of Object.entries(writes)) {
2693
- const existingValue = this.#graphOutputs[outputId];
2554
+ const existingValue = this.#run.graphOutputs[outputId];
2694
2555
  if (existingValue == null || existingValue.type === 'control-flow-excluded') {
2695
- this.#graphOutputs[outputId] = value;
2556
+ this.#run.graphOutputs[outputId] = value;
2696
2557
  }
2697
2558
  }
2698
2559
  }
2699
2560
  #getContinuationBranchResults(processor, branchPlan) {
2700
2561
  const results = new Map();
2701
- for (const [nodeId, outputs] of processor.#nodeResults) {
2702
- 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)) {
2703
2564
  continue;
2704
2565
  }
2705
2566
  results.set(nodeId, outputs);
@@ -2715,17 +2576,17 @@ export class GraphProcessor {
2715
2576
  sourceNode,
2716
2577
  sourceOutputs,
2717
2578
  state: {
2718
- erroredNodeIds: new Set(this.#erroredNodes.keys()),
2719
- nodeOutputs: this.#nodeResults,
2579
+ erroredNodeIds: new Set(this.#run.erroredNodes.keys()),
2580
+ nodeOutputs: this.#run.nodeResults,
2720
2581
  runToRelevantNodeIds: this.#getExecutionRelevantNodeIds(),
2721
- visitedNodeIds: this.#visitedNodes,
2582
+ visitedNodeIds: this.#run.visitedNodes,
2722
2583
  },
2723
2584
  });
2724
2585
  }
2725
2586
  #createToolCallContinuationBranchPlanner() {
2726
2587
  return createToolCallContinuationBranchPlanner({
2727
2588
  asyncBranchPlansByTriggerNodeId: this.#asyncBranchPlansByTriggerNodeId,
2728
- attachedNodeDataByNodeId: this.#attachedNodeData,
2589
+ attachedNodeDataByNodeId: this.#run.attachedNodeData,
2729
2590
  effectiveConnections: this.#getEffectiveConnections(),
2730
2591
  graph: this.#getExecutionGraph(),
2731
2592
  isDefinitionValidConnection: (connection) => this.#isDefinitionValidConnection(connection),
@@ -2771,140 +2632,26 @@ export class GraphProcessor {
2771
2632
  return this.#effectiveConnectionsForRun;
2772
2633
  }
2773
2634
  #prepareStreamingWatchTopology() {
2774
- const connections = this.#getEffectiveConnections().filter((connection) => this.#isDefinitionValidConnection(connection));
2775
- const outgoingByNodeId = new Map();
2776
- const incomingByNodeId = new Map();
2777
- const relevantNodeIds = this.#getExecutionRelevantNodeIds();
2778
- const isRelevant = (nodeId) => !relevantNodeIds || relevantNodeIds.has(nodeId);
2779
- for (const connection of connections) {
2780
- const outgoing = outgoingByNodeId.get(connection.outputNodeId) ?? [];
2781
- outgoing.push(connection);
2782
- outgoingByNodeId.set(connection.outputNodeId, outgoing);
2783
- const incoming = incomingByNodeId.get(connection.inputNodeId) ?? [];
2784
- incoming.push(connection);
2785
- incomingByNodeId.set(connection.inputNodeId, incoming);
2786
- }
2787
- for (const watchNode of Object.values(this.#nodesById)) {
2788
- if (watchNode.type !== 'watchStreamingOutput' || watchNode.disabled || !isRelevant(watchNode.id)) {
2789
- continue;
2790
- }
2791
- if (watchNode.id === this.#consumedStreamingWatchNodeId) {
2792
- continue;
2793
- }
2794
- const enclosingWatchInvocation = this.#getEnclosingStreamingWatchInvocation();
2795
- if (enclosingWatchInvocation) {
2796
- throw new Error(`Watch Streaming Output "${watchNode.title}" cannot run inside Watch Streaming Output ` +
2797
- `"${enclosingWatchInvocation.plan.watchNode.title}". A Watch branch cannot contain another Watch, including through Subgraph.`);
2798
- }
2799
- if (this.#nodeResults.has(watchNode.id)) {
2800
- throw new Error(`Cannot preload ${watchNode.title} because a streaming boundary must be scheduled. ` +
2801
- "Run from Watch Streaming Output to reuse a producer's saved final value, or run from the producer to stream again.");
2802
- }
2803
- const incoming = incomingByNodeId.get(watchNode.id) ?? [];
2804
- if (incoming.length === 0) {
2805
- // An unattached Watch is an ordinary in-progress authoring state. Keep
2806
- // it dormant rather than making an incomplete canvas fail to run.
2807
- this.#ignoreNodes.add(watchNode.id);
2808
- continue;
2809
- }
2810
- if (incoming.length !== 1 || incoming[0].inputId !== 'stream') {
2811
- throw new Error(`Watch Streaming Output "${watchNode.title}" must have exactly one Streaming Output input connection.`);
2812
- }
2813
- const sourceConnection = incoming[0];
2814
- const sourceNode = this.#nodesById[sourceConnection.outputNodeId];
2815
- if (!sourceNode || sourceNode.disabled || !isRelevant(sourceNode.id)) {
2816
- throw new Error(`Watch Streaming Output "${watchNode.title}" has no runnable streaming source.`);
2817
- }
2818
- if (sourceNode.isSplitRun) {
2819
- throw new Error(`Watch Streaming Output "${watchNode.title}" cannot watch split-run node "${sourceNode.title}". ` +
2820
- 'Assemble a single streaming value before the watch boundary.');
2821
- }
2822
- const branchNodeIds = new Set();
2823
- const pendingNodeIds = (outgoingByNodeId.get(watchNode.id) ?? [])
2824
- .map((connection) => connection.inputNodeId)
2825
- .filter(isRelevant);
2826
- let stopNodeId;
2827
- while (pendingNodeIds.length > 0) {
2828
- const nodeId = pendingNodeIds.pop();
2829
- if (nodeId === watchNode.id) {
2830
- throw new Error(`Watch Streaming Output "${watchNode.title}" cannot reconnect to itself.`);
2831
- }
2832
- if (branchNodeIds.has(nodeId)) {
2833
- continue;
2834
- }
2835
- const node = this.#nodesById[nodeId];
2836
- if (!node || !isRelevant(nodeId)) {
2837
- continue;
2838
- }
2839
- if (node.disabled) {
2840
- throw new Error(`Watch Streaming Output "${watchNode.title}" cannot include disabled node "${node.title}".`);
2841
- }
2842
- if (node.type === 'watchStreamingOutput') {
2843
- throw new Error(`Watch Streaming Output "${watchNode.title}" cannot contain another Watch Streaming Output node.`);
2844
- }
2845
- if (node.type === 'catchStreamingChunks') {
2846
- throw new Error(`Watch Streaming Output "${watchNode.title}" cannot contain Catch streaming chunks "${node.title}". ` +
2847
- 'Put Catch streaming chunks outside the repeated Watch branch.');
2848
- }
2849
- if (node.type === 'graphOutput') {
2850
- throw new Error(`Watch Streaming Output "${watchNode.title}" must reach Stop Watching Streaming Output before Graph Output "${node.title}".`);
2851
- }
2852
- if (node.type === 'startBackgroundBranch') {
2853
- throw new Error(`Watch Streaming Output "${watchNode.title}" cannot contain Start Async Branch. ` +
2854
- 'Keep watched work in the bounded watch branch instead.');
2855
- }
2856
- branchNodeIds.add(nodeId);
2857
- if (node.type === 'stopWatchingStreamingOutput') {
2858
- if (stopNodeId && stopNodeId !== nodeId) {
2859
- throw new Error(`Watch Streaming Output "${watchNode.title}" must have one Stop Watching Streaming Output boundary.`);
2860
- }
2861
- stopNodeId = nodeId;
2862
- continue;
2863
- }
2864
- for (const connection of outgoingByNodeId.get(nodeId) ?? []) {
2865
- if (isRelevant(connection.inputNodeId)) {
2866
- pendingNodeIds.push(connection.inputNodeId);
2867
- }
2868
- }
2869
- }
2870
- if (branchNodeIds.size === 0) {
2871
- // Source -> Watch is also a useful intermediate authoring state. There
2872
- // is no downstream work to schedule yet, so do not create a coordinator.
2873
- 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);
2874
2648
  continue;
2875
2649
  }
2876
- if (stopNodeId) {
2877
- const reentry = (outgoingByNodeId.get(stopNodeId) ?? []).find((connection) => connection.inputNodeId === watchNode.id || branchNodeIds.has(connection.inputNodeId));
2878
- if (reentry) {
2879
- const stopNode = this.#nodesById[stopNodeId];
2880
- throw new Error(`Stop Watching Streaming Output "${stopNode.title}" cannot reconnect to its own Watch Streaming Output branch. ` +
2881
- 'Connect it only to ordinary downstream execution.');
2882
- }
2883
- }
2884
- for (const nodeId of branchNodeIds) {
2885
- const externalInput = (incomingByNodeId.get(nodeId) ?? []).find((connection) => connection.outputNodeId !== watchNode.id && !branchNodeIds.has(connection.outputNodeId));
2886
- if (externalInput) {
2887
- const node = this.#nodesById[nodeId];
2888
- const externalNode = this.#nodesById[externalInput.outputNodeId];
2889
- throw new Error(`Watch Streaming Output "${watchNode.title}" cannot run "${node.title}" because it also depends on ` +
2890
- `"${externalNode?.title ?? externalInput.outputNodeId}" outside the watch branch. ` +
2891
- 'Assemble every required value inside the watch boundary.');
2892
- }
2893
- }
2894
- const graph = {
2895
- metadata: this.#graph.metadata ? { ...this.#graph.metadata } : undefined,
2896
- nodes: this.#executionGraphNodes.filter((node) => node.id === watchNode.id || branchNodeIds.has(node.id)),
2897
- connections: connections.filter((connection) => connection.inputNodeId === watchNode.id ||
2898
- (branchNodeIds.has(connection.inputNodeId) &&
2899
- (connection.outputNodeId === watchNode.id || branchNodeIds.has(connection.outputNodeId)))),
2900
- };
2901
2650
  const plan = {
2902
- graph,
2903
- includeAllStreamedOutput: connections.some((connection) => connection.outputNodeId === watchNode.id &&
2904
- connection.outputId === 'allStreamedOutput' &&
2905
- branchNodeIds.has(connection.inputNodeId)),
2906
- sourceOutputId: sourceConnection.outputId,
2907
- stopNodeId,
2651
+ graph: topology.graph,
2652
+ includeAllStreamedOutput: topology.includeAllStreamedOutput,
2653
+ sourceOutputId: topology.sourceOutputId,
2654
+ stopNodeId: topology.stopNodeId,
2908
2655
  streamedOutput: [],
2909
2656
  previousStreamedValue: undefined,
2910
2657
  watchNode,
@@ -2913,15 +2660,13 @@ export class GraphProcessor {
2913
2660
  historySummaryEmitted: false,
2914
2661
  unmatchedStopResolved: false,
2915
2662
  };
2916
- const plans = this.#streamingWatchPlansBySourceNodeId.get(sourceNode.id) ?? [];
2663
+ const plans = this.#boundaries.streamingWatchPlansBySourceNodeId.get(topology.sourceNodeId) ?? [];
2917
2664
  plans.push(plan);
2918
- this.#streamingWatchPlansBySourceNodeId.set(sourceNode.id, plans);
2919
- this.#streamingWatchPlansByWatchNodeId.set(watchNode.id, plan);
2920
- const watch = new StreamingOutputWatch(watchNode.data, (snapshot, registerCancel) => this.#runStreamingOutputWatchInvocation(plan, snapshot, registerCancel), (error) => this.#recordStreamingWatchFailure(watchNode, error));
2921
- this.#streamingOutputWatches.set(watchNode.id, watch);
2922
- for (const nodeId of [watchNode.id, ...branchNodeIds]) {
2923
- this.#ignoreNodes.add(nodeId);
2924
- }
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);
2925
2670
  }
2926
2671
  this.#assertStreamingOutputWatchPreloadsAreSafe();
2927
2672
  }
@@ -2929,20 +2674,18 @@ export class GraphProcessor {
2929
2674
  const relevantNodeIds = this.#getExecutionRelevantNodeIds();
2930
2675
  const connections = this.#getEffectiveConnections().filter((connection) => this.#isDefinitionValidConnection(connection));
2931
2676
  for (const node of this.#executionGraphNodes) {
2932
- if (node.type !== 'catchStreamingChunks' ||
2933
- node.disabled ||
2934
- (relevantNodeIds && !relevantNodeIds.has(node.id)))
2677
+ if (node.type !== 'catchStreamingChunks' || node.disabled || (relevantNodeIds && !relevantNodeIds.has(node.id)))
2935
2678
  continue;
2936
2679
  // A saved Catch result is an ordinary once-only value. Run-from may reuse
2937
2680
  // it, but a live Catch still needs its own streaming coordinator.
2938
- if (this.#nodeResults.has(node.id))
2681
+ if (this.#run.nodeResults.has(node.id))
2939
2682
  continue;
2940
2683
  if (node.isConditional || node.isSplitRun) {
2941
2684
  throw new Error(`Catch streaming chunks "${node.title}" cannot use Conditional or Many runs.`);
2942
2685
  }
2943
2686
  const incoming = connections.filter((connection) => connection.inputNodeId === node.id);
2944
2687
  if (incoming.length === 0) {
2945
- this.#ignoreNodes.add(node.id);
2688
+ this.#run.ignoreNodes.add(node.id);
2946
2689
  continue;
2947
2690
  }
2948
2691
  if (incoming.length !== 1 || incoming[0].inputId !== 'stream') {
@@ -2963,14 +2706,16 @@ export class GraphProcessor {
2963
2706
  chunks: [],
2964
2707
  settled: false,
2965
2708
  };
2966
- const plans = this.#streamingCatchPlansBySourceNodeId.get(source.id) ?? [];
2709
+ const plans = this.#boundaries.streamingCatchPlansBySourceNodeId.get(source.id) ?? [];
2967
2710
  plans.push(plan);
2968
- this.#streamingCatchPlansBySourceNodeId.set(source.id, plans);
2969
- this.#ignoreNodes.add(node.id);
2711
+ this.#boundaries.streamingCatchPlansBySourceNodeId.set(source.id, plans);
2712
+ this.#run.ignoreNodes.add(node.id);
2970
2713
  }
2971
2714
  }
2972
2715
  #isStreamingOutputWatchBoundary(node) {
2973
- return node.type === 'watchStreamingOutput' || node.type === 'stopWatchingStreamingOutput' || node.type === 'catchStreamingChunks';
2716
+ return (node.type === 'watchStreamingOutput' ||
2717
+ node.type === 'stopWatchingStreamingOutput' ||
2718
+ node.type === 'catchStreamingChunks');
2974
2719
  }
2975
2720
  #assertStreamingOutputWatchPreloadCanBeAdded(nodeId) {
2976
2721
  // Before initialization, referenced projects and the effective graph are
@@ -2987,7 +2732,7 @@ export class GraphProcessor {
2987
2732
  throw new Error(`Cannot preload ${node.title} while it is running because a streaming boundary must be scheduled. ` +
2988
2733
  'Preload the producer before starting a new run instead.');
2989
2734
  }
2990
- for (const [sourceNodeId, plans] of this.#streamingWatchPlansBySourceNodeId) {
2735
+ for (const [sourceNodeId, plans] of this.#boundaries.streamingWatchPlansBySourceNodeId) {
2991
2736
  for (const plan of plans) {
2992
2737
  if (sourceNodeId === node.id || plan.graph.nodes.some((branchNode) => branchNode.id === node.id)) {
2993
2738
  throw new Error(`Cannot preload ${node.title} while Watch Streaming Output "${plan.watchNode.title}" is running. ` +
@@ -3007,7 +2752,7 @@ export class GraphProcessor {
3007
2752
  "Run from Watch Streaming Output to reuse a producer's saved final value, or run from the producer to stream again.");
3008
2753
  }
3009
2754
  }
3010
- for (const [sourceNodeId, plans] of this.#streamingWatchPlansBySourceNodeId) {
2755
+ for (const [sourceNodeId, plans] of this.#boundaries.streamingWatchPlansBySourceNodeId) {
3011
2756
  const sourceOutputs = this.#preloadedNodeResults.get(sourceNodeId);
3012
2757
  for (const plan of plans) {
3013
2758
  const preloadedBranchNode = plan.graph.nodes.find((node) => node.id !== this.#consumedStreamingWatchNodeId && this.#preloadedNodeResults.has(node.id));
@@ -3025,7 +2770,7 @@ export class GraphProcessor {
3025
2770
  }
3026
2771
  }
3027
2772
  #publishStreamingOutputWatchPartial(node, partialOutputs, coalesced = 0) {
3028
- for (const plan of this.#streamingCatchPlansBySourceNodeId.get(node.id) ?? []) {
2773
+ for (const plan of this.#boundaries.streamingCatchPlansBySourceNodeId.get(node.id) ?? []) {
3029
2774
  if (plan.settled)
3030
2775
  continue;
3031
2776
  const value = partialOutputs[plan.sourceOutputId];
@@ -3036,12 +2781,12 @@ export class GraphProcessor {
3036
2781
  if (plan.chunks.length >= plan.count)
3037
2782
  this.#scheduleStreamingCatchCompletion(plan);
3038
2783
  }
3039
- for (const plan of this.#streamingWatchPlansBySourceNodeId.get(node.id) ?? []) {
2784
+ for (const plan of this.#boundaries.streamingWatchPlansBySourceNodeId.get(node.id) ?? []) {
3040
2785
  const value = partialOutputs[plan.sourceOutputId];
3041
2786
  if (value == null || value.type === 'control-flow-excluded') {
3042
2787
  continue;
3043
2788
  }
3044
- const watch = this.#streamingOutputWatches.get(plan.watchNode.id);
2789
+ const watch = this.#boundaries.streamingOutputWatches.get(plan.watchNode.id);
3045
2790
  if (!watch || watch.stopped) {
3046
2791
  continue;
3047
2792
  }
@@ -3056,26 +2801,24 @@ export class GraphProcessor {
3056
2801
  return;
3057
2802
  plan.settled = true;
3058
2803
  const task = this.#completeStreamingCatch(plan).catch((error) => this.#nodeErrored(plan.node, error, nanoid()));
3059
- this.#streamingCatchTasks.add(task);
3060
- void task.then(() => this.#streamingCatchTasks.delete(task), () => this.#streamingCatchTasks.delete(task));
2804
+ this.#boundaries.streamingCatchTasks.add(task);
2805
+ void task.then(() => this.#boundaries.streamingCatchTasks.delete(task), () => this.#boundaries.streamingCatchTasks.delete(task));
3061
2806
  }
3062
2807
  async #completeStreamingCatch(plan) {
3063
- if (this.#abortController.signal.aborted)
2808
+ if (this.#run.abortController.signal.aborted)
3064
2809
  return;
3065
2810
  const node = plan.node;
3066
2811
  const processId = nanoid();
3067
2812
  const chunks = plan.chunks.slice(0, plan.count);
3068
- const output = plan.count === 1
3069
- ? chunks[0]
3070
- : { type: 'any[]', value: chunks.map((chunk) => chunk.value) };
2813
+ const output = plan.count === 1 ? chunks[0] : { type: 'any[]', value: chunks.map((chunk) => chunk.value) };
3071
2814
  const outputs = { ['value']: output };
3072
2815
  plan.chunks.length = 0;
3073
2816
  await this.#emitter.emit('nodeStart', this.#withExecution({ node, inputs: {}, processId, resultOrigin: 'executed' }));
3074
- if (this.#abortController.signal.aborted)
2817
+ if (this.#run.abortController.signal.aborted)
3075
2818
  return;
3076
- this.#nodeResults.set(node.id, outputs);
3077
- this.#visitedNodes.add(node.id);
3078
- this.#remainingNodes.delete(node.id);
2819
+ this.#run.nodeResults.set(node.id, outputs);
2820
+ this.#run.visitedNodes.add(node.id);
2821
+ this.#run.remainingNodes.delete(node.id);
3079
2822
  await this.#emitter.emit('nodeFinish', this.#withExecution({ node, outputs, processId, resultOrigin: 'executed' }));
3080
2823
  this.#finishStreamingOutputWatches(node, outputs);
3081
2824
  const outputNodes = getOutputNodesFrom(this.#executionState, node);
@@ -3083,10 +2826,7 @@ export class GraphProcessor {
3083
2826
  this.#queueOutputNodes(node, outputNodes.nodes);
3084
2827
  }
3085
2828
  async #drainStreamingCatchTasks() {
3086
- while (this.#streamingCatchTasks.size > 0) {
3087
- await Promise.all([...this.#streamingCatchTasks]);
3088
- await this.#processingQueue.onIdle();
3089
- }
2829
+ await this.#boundaries.drainCatchTasks(() => this.#run.processingQueue.onIdle());
3090
2830
  }
3091
2831
  #prepareGraphInputStreamRoutes() {
3092
2832
  if (!this.#executionGraphNodes.some((node) => canStreamThroughGraphCaller(node) && this.#isNodeSelected(node.id)))
@@ -3094,7 +2834,7 @@ export class GraphProcessor {
3094
2834
  const marked = getProjectStreamingOutputWatchConnections({
3095
2835
  project: this.#project,
3096
2836
  graph: this.#graph,
3097
- referencedProjects: this.#loadedProjects,
2837
+ referencedProjects: this.#run.loadedProjects,
3098
2838
  registry: this.#registry,
3099
2839
  fullGraphCallers: new Set(this.runToNodeIds ?? []),
3100
2840
  isNodeFrozen: (_owner, candidate, node) => this.#frozenNodeOutputResolver != null &&
@@ -3128,39 +2868,39 @@ export class GraphProcessor {
3128
2868
  continue;
3129
2869
  const relay = new GraphInputStreamRelay();
3130
2870
  streams[edge.inputId] = relay;
3131
- const routes = this.#inputStreamRoutes.get(source.id) ?? [];
2871
+ const routes = this.#boundaries.inputStreamRoutes.get(source.id) ?? [];
3132
2872
  routes.push({ port: edge.outputId, relay });
3133
- this.#inputStreamRoutes.set(source.id, routes);
2873
+ this.#boundaries.inputStreamRoutes.set(source.id, routes);
3134
2874
  }
3135
2875
  if (Object.keys(streams).length)
3136
- this.#callerInputStreams.set(node.id, streams);
2876
+ this.#boundaries.callerInputStreams.set(node.id, streams);
3137
2877
  }
3138
2878
  const abort = () => {
3139
- const error = createGraphAbortErrorFromSignal(this.#abortController.signal);
3140
- for (const streams of this.#callerInputStreams.values()) {
2879
+ const error = createGraphAbortErrorFromSignal(this.#run.abortController.signal);
2880
+ for (const streams of this.#boundaries.callerInputStreams.values()) {
3141
2881
  for (const relay of Object.values(streams))
3142
2882
  relay.finish({ error });
3143
2883
  }
3144
2884
  };
3145
- this.#abortController.signal.addEventListener('abort', abort, { once: true });
3146
- 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));
3147
2887
  }
3148
2888
  #publishGraphInputStreamPartial(node, outputs, coalesced = 0) {
3149
- for (const { port, relay } of this.#inputStreamRoutes.get(node.id) ?? []) {
2889
+ for (const { port, relay } of this.#boundaries.inputStreamRoutes.get(node.id) ?? []) {
3150
2890
  const value = outputs[port];
3151
2891
  if (value && value.type !== 'control-flow-excluded')
3152
2892
  relay.publish(value, coalesced);
3153
2893
  }
3154
2894
  }
3155
2895
  #subscribeGraphInputStreams() {
3156
- for (const [name, stream] of Object.entries(this.#graphInputStreams)) {
2896
+ for (const [name, stream] of Object.entries(this.#boundaries.graphInputStreams)) {
3157
2897
  const inputs = this.#executionGraphNodes.filter((node) => node.type === 'graphInput' &&
3158
2898
  node.data.id === name &&
3159
2899
  !node.disabled &&
3160
2900
  this.#isNodeSelected(node.id));
3161
2901
  let active = true;
3162
2902
  const unsubscribe = stream.subscribe((value, coalesced) => {
3163
- if (!active || this.#abortController.signal.aborted)
2903
+ if (!active || this.#run.abortController.signal.aborted)
3164
2904
  return;
3165
2905
  for (const node of inputs) {
3166
2906
  if (!canStreamThroughGraphInput(node) || this.#hasFrozenNodeOutputOrUnknownResolver(node))
@@ -3172,28 +2912,28 @@ export class GraphProcessor {
3172
2912
  this.#publishGraphInputStreamPartial(node, output, coalesced);
3173
2913
  }
3174
2914
  });
3175
- this.#inputStreamDisposers.push(() => {
2915
+ this.#boundaries.inputStreamDisposers.push(() => {
3176
2916
  active = false;
3177
2917
  unsubscribe();
3178
2918
  });
3179
2919
  void stream.settled.then((result) => {
3180
- if (!active || this.#abortController.signal.aborted)
2920
+ if (!active || this.#run.abortController.signal.aborted)
3181
2921
  return;
3182
2922
  if (result.value)
3183
- this.#graphInputs[name] = result.value;
2923
+ this.#run.graphInputs[name] = result.value;
3184
2924
  for (const node of inputs)
3185
- void this.#processingQueue.add(() => this.#processNodeIfAllInputsAvailable(node));
2925
+ void this.#run.processingQueue.add(() => this.#processNodeIfAllInputsAvailable(node));
3186
2926
  });
3187
2927
  }
3188
2928
  }
3189
2929
  async #waitForGraphInputStreams() {
3190
- const signal = this.#abortController.signal;
2930
+ const signal = this.#run.abortController.signal;
3191
2931
  if (signal.aborted)
3192
2932
  throw createGraphAbortErrorFromSignal(signal);
3193
2933
  let abort;
3194
2934
  try {
3195
2935
  await Promise.race([
3196
- Promise.all(Object.values(this.#graphInputStreams).map((stream) => stream.settled)),
2936
+ Promise.all(Object.values(this.#boundaries.graphInputStreams).map((stream) => stream.settled)),
3197
2937
  new Promise((_resolve, reject) => {
3198
2938
  abort = () => reject(createGraphAbortErrorFromSignal(signal));
3199
2939
  signal.addEventListener('abort', abort, { once: true });
@@ -3240,13 +2980,13 @@ export class GraphProcessor {
3240
2980
  !canForwardGraphOutputPartials(graphOutput, sourceNode, this.#hasFrozenNodeOutputOrUnknownResolver(graphOutput))) {
3241
2981
  continue;
3242
2982
  }
3243
- const bindings = this.#graphOutputPartialBindingsBySourceNodeId.get(connection.outputNodeId) ?? [];
2983
+ const bindings = this.#boundaries.graphOutputPartialBindingsBySourceNodeId.get(connection.outputNodeId) ?? [];
3244
2984
  bindings.push({
3245
2985
  dataType: graphOutputData.dataType,
3246
2986
  graphOutputId: graphOutputData.id,
3247
2987
  sourceOutputId: connection.outputId,
3248
2988
  });
3249
- this.#graphOutputPartialBindingsBySourceNodeId.set(connection.outputNodeId, bindings);
2989
+ this.#boundaries.graphOutputPartialBindingsBySourceNodeId.set(connection.outputNodeId, bindings);
3250
2990
  }
3251
2991
  }
3252
2992
  #hasFrozenNodeOutputOrUnknownResolver(node) {
@@ -3268,7 +3008,7 @@ export class GraphProcessor {
3268
3008
  */
3269
3009
  #publishGraphOutputPartial(node, partialOutputs) {
3270
3010
  const listener = this.#graphOutputPartialListener;
3271
- const bindings = this.#graphOutputPartialBindingsBySourceNodeId.get(node.id);
3011
+ const bindings = this.#boundaries.graphOutputPartialBindingsBySourceNodeId.get(node.id);
3272
3012
  if (!listener || !bindings) {
3273
3013
  return;
3274
3014
  }
@@ -3286,16 +3026,16 @@ export class GraphProcessor {
3286
3026
  }
3287
3027
  #finishStreamingOutputWatches(node, outputs) {
3288
3028
  if (node.type === 'graphInput') {
3289
- const terminals = Object.values(this.#graphInputStreams).map((stream) => stream.result);
3029
+ const terminals = Object.values(this.#boundaries.graphInputStreams).map((stream) => stream.result);
3290
3030
  if (terminals.some((result) => !result)) {
3291
3031
  // Defaults/non-streamed arguments may be needed for caller startup, but
3292
3032
  // their final Watch delivery must not release ordinary nested work early.
3293
- this.#pendingGraphInputFinals.set(node.id, cloneExecutionOutputs(outputs));
3033
+ this.#boundaries.pendingGraphInputFinals.set(node.id, cloneExecutionOutputs(outputs));
3294
3034
  return;
3295
3035
  }
3296
3036
  const failure = terminals.find((result) => result?.error);
3297
3037
  if (failure?.error) {
3298
- for (const route of this.#inputStreamRoutes.get(node.id) ?? [])
3038
+ for (const route of this.#boundaries.inputStreamRoutes.get(node.id) ?? [])
3299
3039
  route.relay.finish({ error: failure.error });
3300
3040
  this.#cancelStreamingOutputWatchesForSource(node.id);
3301
3041
  this.#cancelStreamingCatchesForSource(node.id);
@@ -3305,13 +3045,11 @@ export class GraphProcessor {
3305
3045
  outputs = Object.fromEntries(Object.keys(outputs).map((port) => [port, { type: 'control-flow-excluded', value: undefined }]));
3306
3046
  }
3307
3047
  }
3308
- for (const plan of this.#streamingCatchPlansBySourceNodeId.get(node.id) ?? []) {
3048
+ for (const plan of this.#boundaries.streamingCatchPlansBySourceNodeId.get(node.id) ?? []) {
3309
3049
  if (plan.settled)
3310
3050
  continue;
3311
3051
  const finalValue = outputs[plan.sourceOutputId];
3312
- if (finalValue &&
3313
- finalValue.type !== 'control-flow-excluded' &&
3314
- !isEqual(plan.chunks.at(-1), finalValue)) {
3052
+ if (finalValue && finalValue.type !== 'control-flow-excluded' && !isEqual(plan.chunks.at(-1), finalValue)) {
3315
3053
  plan.chunks.push(cloneExecutionOutputs({ ['value']: finalValue })['value']);
3316
3054
  }
3317
3055
  if (plan.chunks.length > 0) {
@@ -3322,13 +3060,13 @@ export class GraphProcessor {
3322
3060
  this.#excludeNode(plan.node, nanoid(), {}, 'stream completed without a value');
3323
3061
  }
3324
3062
  }
3325
- for (const { port, relay } of this.#inputStreamRoutes.get(node.id) ?? []) {
3063
+ for (const { port, relay } of this.#boundaries.inputStreamRoutes.get(node.id) ?? []) {
3326
3064
  const value = outputs[port];
3327
3065
  relay.finish(value ? { value } : { error: new Error(`Missing final streamed output ${port}`) });
3328
3066
  }
3329
- for (const plan of this.#streamingWatchPlansBySourceNodeId.get(node.id) ?? []) {
3067
+ for (const plan of this.#boundaries.streamingWatchPlansBySourceNodeId.get(node.id) ?? []) {
3330
3068
  const value = outputs[plan.sourceOutputId];
3331
- const watch = this.#streamingOutputWatches.get(plan.watchNode.id);
3069
+ const watch = this.#boundaries.streamingOutputWatches.get(plan.watchNode.id);
3332
3070
  if (!watch || watch.stopped) {
3333
3071
  continue;
3334
3072
  }
@@ -3349,8 +3087,8 @@ export class GraphProcessor {
3349
3087
  }
3350
3088
  }
3351
3089
  #assertStreamingOutputWatchFinalOutputs(node, outputs) {
3352
- for (const plan of this.#streamingWatchPlansBySourceNodeId.get(node.id) ?? []) {
3353
- 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);
3354
3092
  if (!watch || watch.stopped || outputs[plan.sourceOutputId] != null) {
3355
3093
  continue;
3356
3094
  }
@@ -3417,118 +3155,83 @@ export class GraphProcessor {
3417
3155
  }
3418
3156
  async #runStreamingOutputWatchInvocation(plan, snapshot, registerCancel) {
3419
3157
  const root = this.getRootProcessor();
3420
- if (root.#abortController.signal.aborted) {
3421
- 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');
3422
3160
  }
3423
3161
  const graphId = plan.graph.metadata?.id;
3424
3162
  if (!graphId) {
3425
3163
  throw new Error('Cannot start a streaming watch branch because the current graph has no ID.');
3426
3164
  }
3427
3165
  const historyIteration = plan.history.start(nanoid(), snapshot.updateIndex);
3428
- const branchRuntimeCache = {
3429
- ...this.#runtimeCache,
3430
- graphBoundaries: undefined,
3431
- loadedProjects: { ...this.#loadedProjects },
3432
- };
3433
- const processor = new GraphProcessor(this.#project, graphId, this.#registry, this.#includeTrace, {
3434
- cacheLoadedProjects: true,
3435
- captureNodeTimings: this.#captureNodeTimings,
3436
- concurrency: this.#concurrency,
3437
- executionPlanCacheMode: this.#executionPlanCacheMode,
3438
- runtimeCache: branchRuntimeCache,
3439
- runtimeProfiler: this.#runtimeProfiler,
3440
- scheduler: this.#scheduler,
3441
- [consumedStreamingWatchNodeOverride]: plan.watchNode.id,
3442
- [graphProcessorGraphOverride]: plan.graph,
3443
- });
3444
- processor.executor = this.executor;
3445
- processor.#isSubProcessor = true;
3446
- processor.#subgraphTargetCache = this.#subgraphTargetCache;
3447
- processor.#executionCache = this.#executionCache;
3448
- processor.#externalFunctions = this.#externalFunctions;
3449
- processor.#contextValues = this.#contextValues;
3450
- processor.#parent = this;
3451
- processor.#recordingProjectScope = this.#recordingProjectScope;
3452
- processor.#graphCallPath = this.#graphCallPath;
3453
- processor.#abortOwnerOverride = root;
3454
- processor.#suppressGraphPartialOutputs = true;
3455
- processor.#globals = this.#globals;
3456
- processor.#storedValueController = this.#storedValueController;
3457
- processor.#knowledgeStoreController = this.#knowledgeStoreController;
3458
- processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
3459
- processor.#executor = this.#executor;
3460
- processor.#suppressGraphLifecycleEvents = true;
3461
- processor.#sharedRunStateOverride = {
3462
- // Repeated node IDs do not imply shared race/loop state between snapshots.
3463
- attachedNodeData: new Map(),
3464
- graphInputNodeValues: { ...this.#graphInputNodeValues },
3465
- graphOutputs: {},
3466
- };
3467
- processor.#executionIdentityOverride = {
3468
- rootRunId: root.#rootRunId,
3469
- graphRunId: historyIteration.graphRunId,
3470
- parentGraphRunId: this.#graphRunId,
3471
- };
3472
- processor.#streamingWatchInvocation = {
3473
- plan,
3474
- historyIteration,
3475
- claimStop: (value) => this.#claimAcceptedStreamingWatchStop(plan, historyIteration, value, snapshot.updateIndex),
3476
- stopReached: false,
3477
- };
3478
- processor.preloadNodeData(plan.watchNode.id, this.#materializeStreamingOutputWatchSnapshot(snapshot));
3479
- processor.#suppressedPreloadedNodeIds.add(plan.watchNode.id);
3166
+ let processor;
3167
+ let unwireEvents;
3168
+ let unwireLifecycle;
3480
3169
  let cancellationRequested = false;
3481
- registerCancel(() => {
3482
- cancellationRequested = true;
3483
- if (processor.isRunning) {
3484
- void processor.abort(true);
3485
- }
3486
- });
3487
- const unwireEvents = wireSubprocessorEvents(processor, root.#emitter, {
3488
- autoCleanup: false,
3489
- isPaused: () => root.#lifecycle.isPaused,
3490
- pause: () => {
3491
- void root.pause();
3492
- },
3493
- resume: () => {
3494
- void root.resume();
3495
- },
3496
- forwardEvent: (event, data) => {
3497
- // Interactive/global control events are side effects, not execution
3498
- // history. They must remain live even when their enclosing iteration
3499
- // is not selected for retained evidence.
3500
- if (event === 'userInput' ||
3501
- event === 'globalSet' ||
3502
- event === 'newAbortController' ||
3503
- event.startsWith('globalSet:')) {
3504
- return root.#emitter.emit(event, data);
3505
- }
3506
- return plan.history.forward(historyIteration, event, data, (nextEvent, nextData) => root.#emitter.emit(nextEvent, nextData));
3507
- },
3508
- });
3509
- const unwireLifecycle = wireSubprocessorLifecycle(processor, {
3510
- autoCleanup: false,
3511
- signal: this.#abortController.signal,
3512
- parentAbortSignal: root.#abortController.signal,
3513
- onParentPause: (listener) => {
3514
- root.on('pause', listener);
3515
- return () => root.off('pause', listener);
3516
- },
3517
- onParentResume: (listener) => {
3518
- root.on('resume', listener);
3519
- return () => root.off('resume', listener);
3520
- },
3521
- });
3522
- root.#subprocessors.add(processor);
3170
+ let executionFailed = true;
3523
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);
3524
3226
  if (root.#lifecycle.isPaused) {
3525
3227
  processor.pause();
3526
3228
  }
3527
- await processor.processGraph(this.#context, this.#graphInputs, this.#contextValues);
3229
+ await processor.processGraph(this.#run.context, this.#run.graphInputs, this.#contextValues);
3230
+ executionFailed = false;
3528
3231
  }
3529
3232
  catch (error) {
3530
3233
  const normalizedError = getError(error);
3531
- const wasCancelled = isAbortLikeError(normalizedError) || root.#abortController.signal.aborted || cancellationRequested;
3234
+ const wasCancelled = isAbortLikeError(normalizedError) || root.#run.abortController.signal.aborted || cancellationRequested;
3532
3235
  if (wasCancelled) {
3533
3236
  plan.history.cancel(historyIteration);
3534
3237
  }
@@ -3547,10 +3250,10 @@ export class GraphProcessor {
3547
3250
  plan.history.cancel(historyIteration);
3548
3251
  }
3549
3252
  plan.history.complete(historyIteration);
3550
- this.#totalCost += processor.#totalCost;
3551
- unwireLifecycle();
3552
- unwireEvents();
3553
- root.#subprocessors.delete(processor);
3253
+ if (processor) {
3254
+ this.#accumulateChildCost(processor);
3255
+ this.#releaseChildInvocation(processor, root, unwireLifecycle, unwireEvents, executionFailed);
3256
+ }
3554
3257
  }
3555
3258
  }
3556
3259
  #claimStreamingWatchStopFromInvocation(node, outputs) {
@@ -3569,7 +3272,7 @@ export class GraphProcessor {
3569
3272
  if (!stopNodeId) {
3570
3273
  return undefined;
3571
3274
  }
3572
- const watch = this.#streamingOutputWatches.get(plan.watchNode.id);
3275
+ const watch = this.#boundaries.streamingOutputWatches.get(plan.watchNode.id);
3573
3276
  if (!watch || watch.stopped) {
3574
3277
  return undefined;
3575
3278
  }
@@ -3586,9 +3289,9 @@ export class GraphProcessor {
3586
3289
  if (committed)
3587
3290
  return;
3588
3291
  committed = true;
3589
- this.#nodeResults.set(stopNode.id, { ['value']: acceptedValue });
3590
- this.#visitedNodes.add(stopNode.id);
3591
- 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);
3592
3295
  const attachedData = this.#getAttachedDataTo(stopNode);
3593
3296
  const outputNodes = getOutputNodesFrom(this.#executionState, stopNode);
3594
3297
  this.#propagateAttachedDataToOutputNodes(stopNode, attachedData, outputNodes.connectionsToNodes);
@@ -3597,12 +3300,12 @@ export class GraphProcessor {
3597
3300
  };
3598
3301
  }
3599
3302
  #cancelStreamingOutputWatchesForSource(nodeId) {
3600
- for (const plan of this.#streamingWatchPlansBySourceNodeId.get(nodeId) ?? []) {
3601
- 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();
3602
3305
  }
3603
3306
  }
3604
3307
  #cancelStreamingCatchesForSource(nodeId) {
3605
- for (const plan of this.#streamingCatchPlansBySourceNodeId.get(nodeId) ?? []) {
3308
+ for (const plan of this.#boundaries.streamingCatchPlansBySourceNodeId.get(nodeId) ?? []) {
3606
3309
  if (plan.settled)
3607
3310
  continue;
3608
3311
  plan.settled = true;
@@ -3610,21 +3313,21 @@ export class GraphProcessor {
3610
3313
  }
3611
3314
  }
3612
3315
  #cancelStreamingOutputWatches() {
3613
- for (const watch of this.#streamingOutputWatches.values()) {
3316
+ for (const watch of this.#boundaries.streamingOutputWatches.values()) {
3614
3317
  watch.stop();
3615
3318
  }
3616
3319
  }
3617
3320
  #hasPendingStreamingOutputWatches() {
3618
- return [...this.#streamingOutputWatches.values()].some((watch) => watch.hasPending);
3321
+ return [...this.#boundaries.streamingOutputWatches.values()].some((watch) => watch.hasPending);
3619
3322
  }
3620
3323
  #hasUnresolvedForegroundOutputStreamingWatch() {
3621
- return [...this.#streamingOutputWatches].some(([watchNodeId, watch]) => {
3622
- const plan = this.#streamingWatchPlansByWatchNodeId.get(watchNodeId);
3324
+ return [...this.#boundaries.streamingOutputWatches].some(([watchNodeId, watch]) => {
3325
+ const plan = this.#boundaries.streamingWatchPlansByWatchNodeId.get(watchNodeId);
3623
3326
  return plan?.stopNodeId != null && !plan.unmatchedStopResolved && !watch.stopped;
3624
3327
  });
3625
3328
  }
3626
3329
  #hasDrainableStreamingOutputWatches() {
3627
- return [...this.#streamingOutputWatches.values()].some((watch) => watch.hasPending && !watch.isAwaitingProducer);
3330
+ return [...this.#boundaries.streamingOutputWatches.values()].some((watch) => watch.hasPending && !watch.isAwaitingProducer);
3628
3331
  }
3629
3332
  async #drainSchedulerBoundaries() {
3630
3333
  do {
@@ -3635,25 +3338,25 @@ export class GraphProcessor {
3635
3338
  await this.#profileRuntimeAsync('drainStreamingOutputWatches', () => this.#drainStreamingOutputWatches());
3636
3339
  } while ((!this.#isSubProcessor && this.#managedAsyncBranches.hasPending) ||
3637
3340
  this.#hasDrainableStreamingOutputWatches() ||
3638
- this.#streamingCatchTasks.size > 0);
3341
+ this.#boundaries.streamingCatchTasks.size > 0);
3639
3342
  }
3640
3343
  async #drainStreamingOutputWatches() {
3641
3344
  do {
3642
- for (const watch of this.#streamingOutputWatches.values()) {
3345
+ for (const watch of this.#boundaries.streamingOutputWatches.values()) {
3643
3346
  await watch.drain();
3644
3347
  }
3645
3348
  // Accepting Stop happens in a child run. It can enqueue ordinary parent
3646
3349
  // work after the compatible scheduler has returned, so wait for that work
3647
3350
  // before deciding every Watch boundary is quiet.
3648
- await this.#processingQueue.onIdle();
3351
+ await this.#run.processingQueue.onIdle();
3649
3352
  this.#resolveUnmatchedStreamingWatchStops();
3650
3353
  // Excluding the parent Stop queues its ordinary downstream nodes. Let
3651
3354
  // their normal control-flow rules run before emitting the settled Watch
3652
3355
  // summary or finalizing the root graph.
3653
- await this.#processingQueue.onIdle();
3356
+ await this.#run.processingQueue.onIdle();
3654
3357
  } while (this.#hasDrainableStreamingOutputWatches());
3655
- for (const [watchNodeId, watch] of this.#streamingOutputWatches) {
3656
- const plan = this.#streamingWatchPlansByWatchNodeId.get(watchNodeId);
3358
+ for (const [watchNodeId, watch] of this.#boundaries.streamingOutputWatches) {
3359
+ const plan = this.#boundaries.streamingWatchPlansByWatchNodeId.get(watchNodeId);
3657
3360
  if (!plan || plan.historySummaryEmitted || !watch.isSettled)
3658
3361
  continue;
3659
3362
  const summary = await plan.history.finalize(watch.runtimeSummary, (event, data) => this.#emitter.emit(event, data));
@@ -3662,8 +3365,8 @@ export class GraphProcessor {
3662
3365
  }
3663
3366
  }
3664
3367
  #resolveUnmatchedStreamingWatchStops() {
3665
- for (const [watchNodeId, watch] of this.#streamingOutputWatches) {
3666
- const plan = this.#streamingWatchPlansByWatchNodeId.get(watchNodeId);
3368
+ for (const [watchNodeId, watch] of this.#boundaries.streamingOutputWatches) {
3369
+ const plan = this.#boundaries.streamingWatchPlansByWatchNodeId.get(watchNodeId);
3667
3370
  if (!plan?.stopNodeId || plan.unmatchedStopResolved || !watch.finishedNormally) {
3668
3371
  continue;
3669
3372
  }
@@ -3676,97 +3379,23 @@ export class GraphProcessor {
3676
3379
  }
3677
3380
  }
3678
3381
  #prepareAsyncBranchTopology() {
3679
- const connections = this.#getEffectiveConnections().filter((connection) => this.#isDefinitionValidConnection(connection));
3680
- const outgoingByNodeId = new Map();
3681
- const incomingByNodeId = new Map();
3682
- const relevantNodeIds = this.#getExecutionRelevantNodeIds();
3683
- const isRelevant = (nodeId) => !relevantNodeIds || relevantNodeIds.has(nodeId);
3684
- for (const connection of connections) {
3685
- const outgoing = outgoingByNodeId.get(connection.outputNodeId) ?? [];
3686
- outgoing.push(connection);
3687
- outgoingByNodeId.set(connection.outputNodeId, outgoing);
3688
- const incoming = incomingByNodeId.get(connection.inputNodeId) ?? [];
3689
- incoming.push(connection);
3690
- incomingByNodeId.set(connection.inputNodeId, incoming);
3691
- }
3692
- for (const triggerNode of Object.values(this.#nodesById)) {
3693
- // Input anchors describe the consumed trigger's ports, not executable work.
3694
- // A variadic anchor may itself be an outer async trigger.
3695
- if (this.#asyncBranchInputAnchors?.[triggerNode.id])
3696
- continue;
3697
- if (triggerNode.type !== 'startBackgroundBranch' || triggerNode.disabled || !isRelevant(triggerNode.id)) {
3698
- continue;
3699
- }
3700
- if (triggerNode.id !== this.#consumedAsyncBranchTriggerNodeId && this.#nodeResults.has(triggerNode.id)) {
3701
- throw new Error(`Start Async Branch "${triggerNode.title}" cannot use preloaded outputs because replaying it could repeat async side effects.`);
3702
- }
3703
- const nodeIds = new Set();
3704
- const pendingNodeIds = (outgoingByNodeId.get(triggerNode.id) ?? [])
3705
- .map((connection) => connection.inputNodeId)
3706
- .filter(isRelevant);
3707
- while (pendingNodeIds.length > 0) {
3708
- const nodeId = pendingNodeIds.pop();
3709
- if (nodeId === triggerNode.id) {
3710
- throw new Error(`Start Async Branch "${triggerNode.title}" cannot be part of a cycle or reconnect to its own inputs.`);
3711
- }
3712
- if (nodeIds.has(nodeId)) {
3713
- continue;
3714
- }
3715
- const node = this.#nodesById[nodeId];
3716
- if (!node) {
3717
- continue;
3718
- }
3719
- if (node.disabled) {
3720
- continue;
3721
- }
3722
- if (node.type === 'graphOutput') {
3723
- throw new Error(`Start Async Branch "${triggerNode.title}" cannot contain Graph Output node "${node.title}". Async branches are side-effect-only.`);
3724
- }
3725
- nodeIds.add(nodeId);
3726
- for (const connection of outgoingByNodeId.get(nodeId) ?? []) {
3727
- if (isRelevant(connection.inputNodeId)) {
3728
- pendingNodeIds.push(connection.inputNodeId);
3729
- }
3730
- }
3731
- }
3732
- for (const nodeId of nodeIds) {
3733
- const externalInput = (incomingByNodeId.get(nodeId) ?? []).find((connection) => connection.outputNodeId !== triggerNode.id && !nodeIds.has(connection.outputNodeId));
3734
- if (externalInput) {
3735
- const node = this.#nodesById[nodeId];
3736
- const externalNode = this.#nodesById[externalInput.outputNodeId];
3737
- throw new Error(`Start Async Branch "${triggerNode.title}" cannot run "${node.title}" because it also depends on ` +
3738
- `"${externalNode?.title ?? externalInput.outputNodeId}" outside the async branch. Assemble all required values before the async trigger.`);
3739
- }
3740
- }
3741
- if (nodeIds.size === 0) {
3742
- continue;
3743
- }
3744
- const managedAsyncBranchWatchViolation = this.#getManagedAsyncBranchWatchViolation(triggerNode);
3745
- if (managedAsyncBranchWatchViolation) {
3746
- throw managedAsyncBranchWatchViolation;
3747
- }
3748
- const preloadedNodeId = [...nodeIds].find((nodeId) => this.#nodeResults.has(nodeId));
3749
- if (preloadedNodeId) {
3750
- const preloadedNode = this.#nodesById[preloadedNodeId];
3751
- throw new Error(`Start Async Branch "${triggerNode.title}" cannot contain preloaded node "${preloadedNode.title}". Preloading an async descendant would bypass the trigger boundary.`);
3752
- }
3753
- // The node derives its variadic output definitions from connected inputs.
3754
- // Retain shallow input anchors in the slice even though the trigger itself is preloaded.
3755
- const triggerInputConnections = connections.filter((connection) => connection.inputNodeId === triggerNode.id);
3756
- const inputAnchorNodeIds = new Set(triggerInputConnections.map((connection) => connection.outputNodeId));
3757
- const includedNodeIds = new Set([triggerNode.id, ...nodeIds, ...inputAnchorNodeIds]);
3758
- const graph = {
3759
- metadata: this.#graph.metadata ? { ...this.#graph.metadata } : undefined,
3760
- nodes: this.#executionGraphNodes.filter((node) => includedNodeIds.has(node.id)),
3761
- connections: connections.filter((connection) => connection.inputNodeId === triggerNode.id ||
3762
- (nodeIds.has(connection.inputNodeId) &&
3763
- (connection.outputNodeId === triggerNode.id || nodeIds.has(connection.outputNodeId)))),
3764
- };
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
+ })) {
3765
3395
  this.#asyncBranchPlansByTriggerNodeId.set(triggerNode.id, { graph, nodeIds });
3766
3396
  if (triggerNode.id !== this.#consumedAsyncBranchTriggerNodeId) {
3767
- for (const nodeId of nodeIds) {
3768
- this.#ignoreNodes.add(nodeId);
3769
- }
3397
+ for (const nodeId of nodeIds)
3398
+ this.#run.ignoreNodes.add(nodeId);
3770
3399
  }
3771
3400
  }
3772
3401
  }
@@ -3856,20 +3485,20 @@ export class GraphProcessor {
3856
3485
  }
3857
3486
  }
3858
3487
  #isNodeSelected(nodeId) {
3859
- return !this.#graphOutputSelection || this.#graphOutputSelection.nodeIds.has(nodeId);
3488
+ return !this.#run.graphOutputSelection || this.#run.graphOutputSelection.nodeIds.has(nodeId);
3860
3489
  }
3861
3490
  #getExecutionRelevantNodeIds() {
3862
3491
  if (this.#sameGraphRunOwnerOverride) {
3863
3492
  return this.#sameGraphRunOwnerOverride.#getExecutionRelevantNodeIds();
3864
3493
  }
3865
- return this.#graphOutputSelection?.nodeIds ?? this.#getRunToRelevantNodeIds();
3494
+ return this.#run.graphOutputSelection?.nodeIds ?? this.#getRunToRelevantNodeIds();
3866
3495
  }
3867
3496
  #getRunToRelevantNodeIds() {
3868
3497
  if (!this.runToNodeIds) {
3869
3498
  return undefined;
3870
3499
  }
3871
- if (this.#runToRelevantNodeIds) {
3872
- return this.#runToRelevantNodeIds;
3500
+ if (this.#run.runToRelevantNodeIds) {
3501
+ return this.#run.runToRelevantNodeIds;
3873
3502
  }
3874
3503
  const relevantNodeIds = new Set();
3875
3504
  for (const runToNodeId of this.runToNodeIds) {
@@ -3877,7 +3506,7 @@ export class GraphProcessor {
3877
3506
  relevantNodeIds.add(dependencyNodeId);
3878
3507
  }
3879
3508
  }
3880
- this.#runToRelevantNodeIds = relevantNodeIds;
3509
+ this.#run.runToRelevantNodeIds = relevantNodeIds;
3881
3510
  return relevantNodeIds;
3882
3511
  }
3883
3512
  #emitGraphPartialOutputIfNeeded(node, partialOutputs) {
@@ -3906,6 +3535,91 @@ export class GraphProcessor {
3906
3535
  execution: parentExecution,
3907
3536
  });
3908
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
+ }
3909
3623
  #createSubProcessor(node, index, processId, subGraphId, { signal, project } = {}) {
3910
3624
  const subprocessorProject = project ?? this.#project;
3911
3625
  const subprocessorGraph = resolveProcessorGraph(subprocessorProject, subGraphId);
@@ -3915,42 +3629,29 @@ export class GraphProcessor {
3915
3629
  const createProfileStart = this.#startRuntimeProfile();
3916
3630
  let processor;
3917
3631
  try {
3918
- processor = new GraphProcessor(subprocessorProject, subGraphId, this.#registry, this.#includeTrace, {
3919
- cacheLoadedProjects: this.#cacheLoadedProjects,
3920
- captureNodeTimings: this.#captureNodeTimings,
3921
- concurrency: this.#concurrency,
3922
- executionPlanCacheMode: this.#executionPlanCacheMode,
3632
+ processor = this.#constructChildInvocation({
3633
+ kind: 'subgraph',
3634
+ project: subprocessorProject,
3635
+ graphId: subGraphId,
3923
3636
  initialExecutionPlan,
3924
- runtimeCache: this.#runtimeCache,
3925
- runtimeProfiler: this.#runtimeProfiler,
3926
- scheduler: this.#scheduler,
3927
3637
  });
3928
3638
  }
3929
3639
  finally {
3930
3640
  this.#finishRuntimeProfile('createSubProcessor', createProfileStart);
3931
3641
  }
3932
- processor.executor = this.executor;
3933
- processor.#isSubProcessor = true;
3934
- processor.#subgraphTargetCache = this.#subgraphTargetCache;
3935
- processor.#executionCache = this.#executionCache;
3936
- processor.#externalFunctions = this.#externalFunctions;
3937
- processor.#contextValues = this.#contextValues;
3938
- processor.#parent = this;
3939
3642
  processor.#recordingProjectScope =
3940
3643
  node.type === 'subGraph' && node.data.targetProjectId
3941
3644
  ? getSubgraphProjectKey({
3942
3645
  projectId: node.data.targetProjectId,
3943
3646
  version: node.data.targetVersion ?? 'latest',
3944
3647
  })
3945
- : this.#recordingProjectScope;
3648
+ : subprocessorProject.metadata.id !== this.#project.metadata.id
3649
+ ? getSubgraphProjectKey({ projectId: subprocessorProject.metadata.id, version: 'latest' })
3650
+ : this.#recordingProjectScope;
3946
3651
  processor.#graphCallPath = Object.freeze([
3947
3652
  ...this.#graphCallPath,
3948
3653
  processor.#graph.metadata?.name || '(Unnamed Graph)',
3949
3654
  ]);
3950
- processor.#globals = this.#globals;
3951
- processor.#storedValueController = this.#storedValueController;
3952
- processor.#knowledgeStoreController = this.#knowledgeStoreController;
3953
- processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
3954
3655
  processor.#executor = {
3955
3656
  nodeId: node.id,
3956
3657
  parentGraphId: this.#graph.metadata.id,
@@ -3958,39 +3659,17 @@ export class GraphProcessor {
3958
3659
  processId,
3959
3660
  };
3960
3661
  const wireEventsProfileStart = this.#startRuntimeProfile();
3662
+ let unwireEvents;
3961
3663
  try {
3962
- wireSubprocessorEvents(processor, this.#emitter, {
3963
- isPaused: () => this.#lifecycle.isPaused,
3964
- pause: () => {
3965
- void this.pause();
3966
- },
3967
- resume: () => {
3968
- void this.resume();
3969
- },
3970
- });
3664
+ unwireEvents = this.#wireChildEvents(processor, this);
3971
3665
  }
3972
3666
  finally {
3973
3667
  this.#finishRuntimeProfile('wireSubProcessorEvents', wireEventsProfileStart);
3974
3668
  }
3975
- this.#subprocessors.add(processor);
3669
+ this.#run.subprocessors.add(processor);
3976
3670
  const wireLifecycleProfileStart = this.#startRuntimeProfile();
3977
3671
  try {
3978
- wireSubprocessorLifecycle(processor, {
3979
- signal,
3980
- parentAbortSignal: this.#abortController.signal,
3981
- onParentPause: (listener) => {
3982
- this.on('pause', listener);
3983
- return () => {
3984
- this.off('pause', listener);
3985
- };
3986
- },
3987
- onParentResume: (listener) => {
3988
- this.on('resume', listener);
3989
- return () => {
3990
- this.off('resume', listener);
3991
- };
3992
- },
3993
- });
3672
+ this.#wireChildLifecycle(processor, this, unwireEvents, { signal });
3994
3673
  }
3995
3674
  finally {
3996
3675
  this.#finishRuntimeProfile('wireSubProcessorLifecycle', wireLifecycleProfileStart);
@@ -4005,8 +3684,8 @@ export class GraphProcessor {
4005
3684
  let settled = false;
4006
3685
  const cleanup = () => {
4007
3686
  signal.removeEventListener('abort', abortListener);
4008
- if (this.#pendingUserInputs[node.id] === pending) {
4009
- delete this.#pendingUserInputs[node.id];
3687
+ if (this.#run.pendingUserInputs[node.id] === pending) {
3688
+ delete this.#run.pendingUserInputs[node.id];
4010
3689
  }
4011
3690
  };
4012
3691
  const abortListener = () => {
@@ -4024,7 +3703,7 @@ export class GraphProcessor {
4024
3703
  resolve(results);
4025
3704
  };
4026
3705
  const pending = { resolve: respond };
4027
- this.#pendingUserInputs[node.id] = pending;
3706
+ this.#run.pendingUserInputs[node.id] = pending;
4028
3707
  signal.addEventListener('abort', abortListener, { once: true });
4029
3708
  if (signal.aborted) {
4030
3709
  abortListener();
@@ -4055,11 +3734,11 @@ export class GraphProcessor {
4055
3734
  const { queueOutputNodes = true } = options;
4056
3735
  const attachedData = this.#getAttachedDataTo(node);
4057
3736
  this.#registerNodeInActiveLoop(node, attachedData);
4058
- this.#visitedNodes.add(node.id);
3737
+ this.#run.visitedNodes.add(node.id);
4059
3738
  this.#markAsExcluded(node, processId, inputValues, reason);
4060
- this.#finishStreamingOutputWatches(node, this.#nodeResults.get(node.id));
4061
- this.#currentlyProcessing.delete(node.id);
4062
- 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);
4063
3742
  const outputNodes = getOutputNodesFrom(this.#executionState, node);
4064
3743
  this.#propagateAttachedDataToOutputNodes(node, attachedData, outputNodes.connectionsToNodes);
4065
3744
  if (queueOutputNodes) {
@@ -4072,11 +3751,11 @@ export class GraphProcessor {
4072
3751
  }
4073
3752
  async #emitNodeExcluded(node, processId, inputValues, reason, resultOrigin = 'executed') {
4074
3753
  await this.#emitter.emit('nodeExcluded', this.#createNodeExcludedEvent(node, processId, inputValues, reason, resultOrigin));
4075
- this.#finishStreamingOutputWatches(node, this.#nodeResults.get(node.id));
3754
+ this.#finishStreamingOutputWatches(node, this.#run.nodeResults.get(node.id));
4076
3755
  }
4077
3756
  #createNodeExcludedEvent(node, processId, inputValues, reason, resultOrigin = 'executed') {
4078
3757
  const outputs = createExcludedNodeOutputs(node, this.#definitions[node.id].outputs);
4079
- this.#nodeResults.set(node.id, outputs);
3758
+ this.#run.nodeResults.set(node.id, outputs);
4080
3759
  this.#commitExcludedGraphOutput(node, inputValues, outputs);
4081
3760
  return this.#withExecution({
4082
3761
  node,
@@ -4095,7 +3774,7 @@ export class GraphProcessor {
4095
3774
  const outputId = node.data.id;
4096
3775
  const value = outputs['valueOutput'];
4097
3776
  if (value) {
4098
- commitGraphOutputValue(this.#graphOutputs, outputId, value);
3777
+ commitGraphOutputValue(this.#run.graphOutputs, outputId, value);
4099
3778
  }
4100
3779
  }
4101
3780
  #getInputValuesForNode(node) {
@@ -4105,7 +3784,7 @@ export class GraphProcessor {
4105
3784
  connections?.find((conn) => conn.inputId === input.id && conn.inputNodeId === node.id);
4106
3785
  if (connection) {
4107
3786
  const outputNode = this.#nodeInstances[connection.outputNodeId].chartNode;
4108
- const outputNodeOutputs = this.#nodeResults.get(outputNode.id);
3787
+ const outputNodeOutputs = this.#run.nodeResults.get(outputNode.id);
4109
3788
  const outputResult = outputNodeOutputs?.[connection.outputId];
4110
3789
  values[input.id] = outputResult;
4111
3790
  }
@@ -4126,12 +3805,12 @@ export class GraphProcessor {
4126
3805
  return {
4127
3806
  connections: this.#connections,
4128
3807
  definitions: this.#definitions,
4129
- erroredNodes: this.#erroredNodes,
3808
+ erroredNodes: this.#run.erroredNodes,
4130
3809
  executionPlan: this.#graphExecutionPlan,
4131
- loopControllersSeen: this.#loopControllersSeen,
3810
+ loopControllersSeen: this.#run.loopControllersSeen,
4132
3811
  nodesById: this.#nodesById,
4133
3812
  stronglyConnectedComponents: this.#scc,
4134
- visitedNodes: this.#visitedNodes,
3813
+ visitedNodes: this.#run.visitedNodes,
4135
3814
  };
4136
3815
  }
4137
3816
  }