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