@valerypopoff/rivet2-core 2.6.0 → 2.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/bundle.cjs +2735 -767
- 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 +825 -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 +21 -4
- package/dist/esm/model/StreamingOutputWatch.js +262 -0
- package/dist/esm/model/StreamingOutputWatchHistory.js +161 -0
- package/dist/esm/model/SubprocessorBridge.js +29 -19
- package/dist/esm/model/chat-v2/llmChatV2OutputClone.js +3 -42
- package/dist/esm/model/nodes/CodeNewNode.js +4 -1
- package/dist/esm/model/nodes/ExpressionNode.js +4 -1
- package/dist/esm/model/nodes/ExtractObjectPathNode.js +4 -4
- package/dist/esm/model/nodes/GraphOutputNode.js +13 -8
- 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 +16 -7
- 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 +8 -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 +47 -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 +58 -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/ExtractObjectPathNode.d.ts +1 -1
- package/dist/types/model/nodes/GraphOutputNode.d.ts +8 -1
- 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 +7 -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,13 @@ export class GraphProcessor {
|
|
|
1709
1811
|
emitDetached(this.#emitter, event, this.#withExecution(data));
|
|
1710
1812
|
return;
|
|
1711
1813
|
}
|
|
1712
|
-
return this.#emitter.emit(event, this.#withExecution(data))
|
|
1814
|
+
return this.#emitter.emit(event, this.#withExecution(data)).then(() => {
|
|
1815
|
+
if (event === 'nodeFinish') {
|
|
1816
|
+
// SplitRunDeps exposes overloaded event payloads; the runtime event
|
|
1817
|
+
// discriminator guarantees this is the terminal-output shape.
|
|
1818
|
+
this.#commitStreamingWatchStop(node, data.outputs);
|
|
1819
|
+
}
|
|
1820
|
+
});
|
|
1713
1821
|
},
|
|
1714
1822
|
startNodeTiming: this.#captureNodeTimings ? () => this.#startNodeTiming() : undefined,
|
|
1715
1823
|
finishNodeTiming: this.#captureNodeTimings ? (start) => this.#finishNodeTiming(start) : undefined,
|
|
@@ -1737,12 +1845,14 @@ export class GraphProcessor {
|
|
|
1737
1845
|
this.#visitedNodes.add(node.id);
|
|
1738
1846
|
this.#accumulateCost(outputValues);
|
|
1739
1847
|
await this.#applyFrozenNodeDataflowEffects(node, outputValues, processId);
|
|
1848
|
+
this.#assertStreamingOutputWatchFinalOutputs(node, outputValues);
|
|
1740
1849
|
await this.#emitter.emit('nodeFinish', this.#withExecution(withOptionalDuration({
|
|
1741
1850
|
node,
|
|
1742
1851
|
outputs: outputValues,
|
|
1743
1852
|
processId,
|
|
1744
1853
|
resultOrigin: 'frozen',
|
|
1745
1854
|
}, this.#finishNodeTiming(timingStart))));
|
|
1855
|
+
this.#finishStreamingOutputWatches(node, outputValues);
|
|
1746
1856
|
}
|
|
1747
1857
|
async #applyFrozenNodeDataflowEffects(node, outputValues, processId) {
|
|
1748
1858
|
const effect = applyFrozenGraphBoundaryEffects(this.#graphOutputs, node, outputValues);
|
|
@@ -1775,12 +1885,15 @@ export class GraphProcessor {
|
|
|
1775
1885
|
this.#nodeResults.set(node.id, outputValues);
|
|
1776
1886
|
this.#visitedNodes.add(node.id);
|
|
1777
1887
|
this.#accumulateCost(outputValues);
|
|
1888
|
+
this.#assertStreamingOutputWatchFinalOutputs(node, outputValues);
|
|
1778
1889
|
await this.#emitter.emit('nodeFinish', this.#withExecution(withOptionalDuration({
|
|
1779
1890
|
node,
|
|
1780
1891
|
outputs: outputValues,
|
|
1781
1892
|
processId,
|
|
1782
1893
|
resultOrigin,
|
|
1783
1894
|
}, this.#finishNodeTiming(timingStart))));
|
|
1895
|
+
this.#finishStreamingOutputWatches(node, outputValues);
|
|
1896
|
+
this.#commitStreamingWatchStop(node, outputValues);
|
|
1784
1897
|
}
|
|
1785
1898
|
catch (error) {
|
|
1786
1899
|
await this.#nodeErrored(node, error, processId, this.#finishNodeTiming(timingStart), undefined, resultOrigin, this.#takeFailureOutputs(processId, 0));
|
|
@@ -1791,13 +1904,14 @@ export class GraphProcessor {
|
|
|
1791
1904
|
// Most callers are ordinary (non-split) node executions. Let those retain
|
|
1792
1905
|
// any checkpoint without requiring every error path to know about the
|
|
1793
1906
|
// internal map. Split callers provide their per-index map explicitly.
|
|
1794
|
-
const retainedOutputs = splitOutputs === undefined ?
|
|
1907
|
+
const retainedOutputs = splitOutputs === undefined ? outputs ?? this.#takeFailureOutputs(processId, 0) : outputs;
|
|
1795
1908
|
const exclusionReason = this.#getErrorExclusionReason(node, error, processId);
|
|
1796
1909
|
if (exclusionReason) {
|
|
1797
1910
|
await this.#emitNodeExcluded(node, processId, this.#getInputValuesForNode(node), exclusionReason, resultOrigin);
|
|
1798
1911
|
this.#emitTraceEvent(`Node ${node.title} (${node.id}-${processId}) was excluded: ${exclusionReason}`);
|
|
1799
1912
|
return;
|
|
1800
1913
|
}
|
|
1914
|
+
this.#cancelStreamingOutputWatchesForSource(node.id);
|
|
1801
1915
|
this.#erroredNodes.set(node.id, error);
|
|
1802
1916
|
await this.#emitter.emit('nodeError', this.#withExecution(withOptionalDuration({
|
|
1803
1917
|
node,
|
|
@@ -1862,6 +1976,24 @@ export class GraphProcessor {
|
|
|
1862
1976
|
}
|
|
1863
1977
|
return processor;
|
|
1864
1978
|
}
|
|
1979
|
+
#getEnclosingStreamingWatchInvocation() {
|
|
1980
|
+
let processor = this;
|
|
1981
|
+
while (processor) {
|
|
1982
|
+
if (processor.#streamingWatchInvocation) {
|
|
1983
|
+
return processor.#streamingWatchInvocation;
|
|
1984
|
+
}
|
|
1985
|
+
processor = processor.#parent;
|
|
1986
|
+
}
|
|
1987
|
+
return undefined;
|
|
1988
|
+
}
|
|
1989
|
+
#getManagedAsyncBranchWatchViolation(triggerNode) {
|
|
1990
|
+
const invocation = this.#getEnclosingStreamingWatchInvocation();
|
|
1991
|
+
if (!invocation) {
|
|
1992
|
+
return undefined;
|
|
1993
|
+
}
|
|
1994
|
+
return new Error(`Start Async Branch "${triggerNode.title}" cannot run inside Watch Streaming Output "${invocation.plan.watchNode.title}". ` +
|
|
1995
|
+
'A Watch invocation must keep all work within the Watch scheduler. Move Start Async Branch after Stop Watching Streaming Output, or run the work directly inside the watched branch.');
|
|
1996
|
+
}
|
|
1865
1997
|
/** Raise a user event on the processor, all subprocessors, and their children. */
|
|
1866
1998
|
raiseEvent(event, data) {
|
|
1867
1999
|
emitDetached(this.#emitter, `userEvent:${event}`, data);
|
|
@@ -1995,6 +2127,14 @@ export class GraphProcessor {
|
|
|
1995
2127
|
}
|
|
1996
2128
|
#createNodeProcessContext(node, inputValues, index, processId, nodeAbortController, partialOutput, toolCallTraceSource, markResultAsEditorCacheHit) {
|
|
1997
2129
|
const plugin = this.#registry.getPluginFor(node.type);
|
|
2130
|
+
const onGraphOutputPartial = isNamedGraphBoundaryCaller(node) &&
|
|
2131
|
+
(this.#streamingWatchPlansBySourceNodeId.has(node.id) ||
|
|
2132
|
+
this.#graphOutputPartialBindingsBySourceNodeId.has(node.id))
|
|
2133
|
+
? (partialOutputs) => {
|
|
2134
|
+
this.#publishStreamingOutputWatchPartial(node, partialOutputs);
|
|
2135
|
+
this.#publishGraphOutputPartial(node, partialOutputs);
|
|
2136
|
+
}
|
|
2137
|
+
: undefined;
|
|
1998
2138
|
const toolCallContinuation = this.#getToolCallContinuationContext(node, nodeAbortController.signal, processId, index);
|
|
1999
2139
|
return buildNodeProcessContext({
|
|
2000
2140
|
activeOutputPortIds: this.#getActiveOutputPortIds(node),
|
|
@@ -2008,10 +2148,20 @@ export class GraphProcessor {
|
|
|
2008
2148
|
markResultAsEditorCacheHit,
|
|
2009
2149
|
node,
|
|
2010
2150
|
nodeAbortController,
|
|
2151
|
+
onGraphOutputPartial,
|
|
2011
2152
|
onPartialOutputs: (partialOutputs) => {
|
|
2012
2153
|
partialOutput?.(node, partialOutputs, index);
|
|
2154
|
+
this.#publishStreamingOutputWatchPartial(node, partialOutputs);
|
|
2155
|
+
this.#publishGraphOutputPartial(node, partialOutputs);
|
|
2013
2156
|
this.#emitGraphPartialOutputIfNeeded(node, partialOutputs);
|
|
2014
2157
|
},
|
|
2158
|
+
acceptStreamingWatchStop: this.#streamingWatchInvocation?.plan.stopNodeId === node.id
|
|
2159
|
+
? () => {
|
|
2160
|
+
if (this.#streamingWatchInvocation) {
|
|
2161
|
+
this.#streamingWatchInvocation.stopReached = true;
|
|
2162
|
+
}
|
|
2163
|
+
}
|
|
2164
|
+
: undefined,
|
|
2015
2165
|
setFailureOutputs: (outputs) => this.#setFailureOutputs(processId, index, outputs),
|
|
2016
2166
|
processId,
|
|
2017
2167
|
requestUserInput: async (inputStrings, renderingType) => this.#requestUserInput(node, inputStrings, inputValues, renderingType, processId, nodeAbortController.signal),
|
|
@@ -2358,6 +2508,622 @@ export class GraphProcessor {
|
|
|
2358
2508
|
});
|
|
2359
2509
|
return this.#effectiveConnectionsForRun;
|
|
2360
2510
|
}
|
|
2511
|
+
#prepareStreamingWatchTopology() {
|
|
2512
|
+
const connections = this.#getEffectiveConnections().filter((connection) => this.#isDefinitionValidConnection(connection));
|
|
2513
|
+
const outgoingByNodeId = new Map();
|
|
2514
|
+
const incomingByNodeId = new Map();
|
|
2515
|
+
const relevantNodeIds = this.#getExecutionRelevantNodeIds();
|
|
2516
|
+
const isRelevant = (nodeId) => !relevantNodeIds || relevantNodeIds.has(nodeId);
|
|
2517
|
+
for (const connection of connections) {
|
|
2518
|
+
const outgoing = outgoingByNodeId.get(connection.outputNodeId) ?? [];
|
|
2519
|
+
outgoing.push(connection);
|
|
2520
|
+
outgoingByNodeId.set(connection.outputNodeId, outgoing);
|
|
2521
|
+
const incoming = incomingByNodeId.get(connection.inputNodeId) ?? [];
|
|
2522
|
+
incoming.push(connection);
|
|
2523
|
+
incomingByNodeId.set(connection.inputNodeId, incoming);
|
|
2524
|
+
}
|
|
2525
|
+
for (const watchNode of Object.values(this.#nodesById)) {
|
|
2526
|
+
if (watchNode.type !== 'watchStreamingOutput' || watchNode.disabled || !isRelevant(watchNode.id)) {
|
|
2527
|
+
continue;
|
|
2528
|
+
}
|
|
2529
|
+
if (watchNode.id === this.#consumedStreamingWatchNodeId) {
|
|
2530
|
+
continue;
|
|
2531
|
+
}
|
|
2532
|
+
const enclosingWatchInvocation = this.#getEnclosingStreamingWatchInvocation();
|
|
2533
|
+
if (enclosingWatchInvocation) {
|
|
2534
|
+
throw new Error(`Watch Streaming Output "${watchNode.title}" cannot run inside Watch Streaming Output ` +
|
|
2535
|
+
`"${enclosingWatchInvocation.plan.watchNode.title}". A Watch branch cannot contain another Watch, including through Subgraph.`);
|
|
2536
|
+
}
|
|
2537
|
+
if (this.#nodeResults.has(watchNode.id)) {
|
|
2538
|
+
throw new Error(`Cannot preload ${watchNode.title} because a streaming boundary must be scheduled. ` +
|
|
2539
|
+
"Run from Watch Streaming Output to reuse a producer's saved final value, or run from the producer to stream again.");
|
|
2540
|
+
}
|
|
2541
|
+
const incoming = incomingByNodeId.get(watchNode.id) ?? [];
|
|
2542
|
+
if (incoming.length === 0) {
|
|
2543
|
+
// An unattached Watch is an ordinary in-progress authoring state. Keep
|
|
2544
|
+
// it dormant rather than making an incomplete canvas fail to run.
|
|
2545
|
+
this.#ignoreNodes.add(watchNode.id);
|
|
2546
|
+
continue;
|
|
2547
|
+
}
|
|
2548
|
+
if (incoming.length !== 1 || incoming[0].inputId !== 'stream') {
|
|
2549
|
+
throw new Error(`Watch Streaming Output "${watchNode.title}" must have exactly one Streaming Output input connection.`);
|
|
2550
|
+
}
|
|
2551
|
+
const sourceConnection = incoming[0];
|
|
2552
|
+
const sourceNode = this.#nodesById[sourceConnection.outputNodeId];
|
|
2553
|
+
if (!sourceNode || sourceNode.disabled || !isRelevant(sourceNode.id)) {
|
|
2554
|
+
throw new Error(`Watch Streaming Output "${watchNode.title}" has no runnable streaming source.`);
|
|
2555
|
+
}
|
|
2556
|
+
if (sourceNode.isSplitRun) {
|
|
2557
|
+
throw new Error(`Watch Streaming Output "${watchNode.title}" cannot watch split-run node "${sourceNode.title}". ` +
|
|
2558
|
+
'Assemble a single streaming value before the watch boundary.');
|
|
2559
|
+
}
|
|
2560
|
+
const branchNodeIds = new Set();
|
|
2561
|
+
const pendingNodeIds = (outgoingByNodeId.get(watchNode.id) ?? [])
|
|
2562
|
+
.map((connection) => connection.inputNodeId)
|
|
2563
|
+
.filter(isRelevant);
|
|
2564
|
+
let stopNodeId;
|
|
2565
|
+
while (pendingNodeIds.length > 0) {
|
|
2566
|
+
const nodeId = pendingNodeIds.pop();
|
|
2567
|
+
if (nodeId === watchNode.id) {
|
|
2568
|
+
throw new Error(`Watch Streaming Output "${watchNode.title}" cannot reconnect to itself.`);
|
|
2569
|
+
}
|
|
2570
|
+
if (branchNodeIds.has(nodeId)) {
|
|
2571
|
+
continue;
|
|
2572
|
+
}
|
|
2573
|
+
const node = this.#nodesById[nodeId];
|
|
2574
|
+
if (!node || !isRelevant(nodeId)) {
|
|
2575
|
+
continue;
|
|
2576
|
+
}
|
|
2577
|
+
if (node.disabled) {
|
|
2578
|
+
throw new Error(`Watch Streaming Output "${watchNode.title}" cannot include disabled node "${node.title}".`);
|
|
2579
|
+
}
|
|
2580
|
+
if (node.type === 'watchStreamingOutput') {
|
|
2581
|
+
throw new Error(`Watch Streaming Output "${watchNode.title}" cannot contain another Watch Streaming Output node.`);
|
|
2582
|
+
}
|
|
2583
|
+
if (node.type === 'graphOutput') {
|
|
2584
|
+
throw new Error(`Watch Streaming Output "${watchNode.title}" must reach Stop Watching Streaming Output before Graph Output "${node.title}".`);
|
|
2585
|
+
}
|
|
2586
|
+
if (node.type === 'startBackgroundBranch') {
|
|
2587
|
+
throw new Error(`Watch Streaming Output "${watchNode.title}" cannot contain Start Async Branch. ` +
|
|
2588
|
+
'Keep watched work in the bounded watch branch instead.');
|
|
2589
|
+
}
|
|
2590
|
+
branchNodeIds.add(nodeId);
|
|
2591
|
+
if (node.type === 'stopWatchingStreamingOutput') {
|
|
2592
|
+
if (stopNodeId && stopNodeId !== nodeId) {
|
|
2593
|
+
throw new Error(`Watch Streaming Output "${watchNode.title}" must have one Stop Watching Streaming Output boundary.`);
|
|
2594
|
+
}
|
|
2595
|
+
stopNodeId = nodeId;
|
|
2596
|
+
continue;
|
|
2597
|
+
}
|
|
2598
|
+
for (const connection of outgoingByNodeId.get(nodeId) ?? []) {
|
|
2599
|
+
if (isRelevant(connection.inputNodeId)) {
|
|
2600
|
+
pendingNodeIds.push(connection.inputNodeId);
|
|
2601
|
+
}
|
|
2602
|
+
}
|
|
2603
|
+
}
|
|
2604
|
+
if (branchNodeIds.size === 0) {
|
|
2605
|
+
// Source -> Watch is also a useful intermediate authoring state. There
|
|
2606
|
+
// is no downstream work to schedule yet, so do not create a coordinator.
|
|
2607
|
+
this.#ignoreNodes.add(watchNode.id);
|
|
2608
|
+
continue;
|
|
2609
|
+
}
|
|
2610
|
+
if (stopNodeId) {
|
|
2611
|
+
const reentry = (outgoingByNodeId.get(stopNodeId) ?? []).find((connection) => connection.inputNodeId === watchNode.id || branchNodeIds.has(connection.inputNodeId));
|
|
2612
|
+
if (reentry) {
|
|
2613
|
+
const stopNode = this.#nodesById[stopNodeId];
|
|
2614
|
+
throw new Error(`Stop Watching Streaming Output "${stopNode.title}" cannot reconnect to its own Watch Streaming Output branch. ` +
|
|
2615
|
+
'Connect it only to ordinary downstream execution.');
|
|
2616
|
+
}
|
|
2617
|
+
}
|
|
2618
|
+
for (const nodeId of branchNodeIds) {
|
|
2619
|
+
const externalInput = (incomingByNodeId.get(nodeId) ?? []).find((connection) => connection.outputNodeId !== watchNode.id && !branchNodeIds.has(connection.outputNodeId));
|
|
2620
|
+
if (externalInput) {
|
|
2621
|
+
const node = this.#nodesById[nodeId];
|
|
2622
|
+
const externalNode = this.#nodesById[externalInput.outputNodeId];
|
|
2623
|
+
throw new Error(`Watch Streaming Output "${watchNode.title}" cannot run "${node.title}" because it also depends on ` +
|
|
2624
|
+
`"${externalNode?.title ?? externalInput.outputNodeId}" outside the watch branch. ` +
|
|
2625
|
+
'Assemble every required value inside the watch boundary.');
|
|
2626
|
+
}
|
|
2627
|
+
}
|
|
2628
|
+
const graph = {
|
|
2629
|
+
metadata: this.#graph.metadata ? { ...this.#graph.metadata } : undefined,
|
|
2630
|
+
nodes: this.#executionGraphNodes.filter((node) => node.id === watchNode.id || branchNodeIds.has(node.id)),
|
|
2631
|
+
connections: connections.filter((connection) => connection.inputNodeId === watchNode.id ||
|
|
2632
|
+
(branchNodeIds.has(connection.inputNodeId) &&
|
|
2633
|
+
(connection.outputNodeId === watchNode.id || branchNodeIds.has(connection.outputNodeId)))),
|
|
2634
|
+
};
|
|
2635
|
+
const plan = {
|
|
2636
|
+
graph,
|
|
2637
|
+
includeAllStreamedOutput: connections.some((connection) => connection.outputNodeId === watchNode.id &&
|
|
2638
|
+
connection.outputId === 'allStreamedOutput' &&
|
|
2639
|
+
branchNodeIds.has(connection.inputNodeId)),
|
|
2640
|
+
sourceOutputId: sourceConnection.outputId,
|
|
2641
|
+
stopNodeId,
|
|
2642
|
+
streamedOutput: [],
|
|
2643
|
+
previousStreamedValue: undefined,
|
|
2644
|
+
watchNode,
|
|
2645
|
+
nextUpdateIndex: 0,
|
|
2646
|
+
history: new StreamingOutputWatchHistory(),
|
|
2647
|
+
historySummaryEmitted: false,
|
|
2648
|
+
};
|
|
2649
|
+
const plans = this.#streamingWatchPlansBySourceNodeId.get(sourceNode.id) ?? [];
|
|
2650
|
+
plans.push(plan);
|
|
2651
|
+
this.#streamingWatchPlansBySourceNodeId.set(sourceNode.id, plans);
|
|
2652
|
+
this.#streamingWatchPlansByWatchNodeId.set(watchNode.id, plan);
|
|
2653
|
+
const watch = new StreamingOutputWatch(watchNode.data, (snapshot, registerCancel) => this.#runStreamingOutputWatchInvocation(plan, snapshot, registerCancel), (error) => this.#recordStreamingWatchFailure(watchNode, error), { requiresAcceptedStop: stopNodeId != null });
|
|
2654
|
+
this.#streamingOutputWatches.set(watchNode.id, watch);
|
|
2655
|
+
for (const nodeId of [watchNode.id, ...branchNodeIds]) {
|
|
2656
|
+
this.#ignoreNodes.add(nodeId);
|
|
2657
|
+
}
|
|
2658
|
+
}
|
|
2659
|
+
this.#assertStreamingOutputWatchPreloadsAreSafe();
|
|
2660
|
+
}
|
|
2661
|
+
#isStreamingOutputWatchBoundary(node) {
|
|
2662
|
+
return node.type === 'watchStreamingOutput' || node.type === 'stopWatchingStreamingOutput';
|
|
2663
|
+
}
|
|
2664
|
+
#assertStreamingOutputWatchPreloadCanBeAdded(nodeId) {
|
|
2665
|
+
// Before initialization, referenced projects and the effective graph are
|
|
2666
|
+
// not available yet. Startup validation below owns that case. During a
|
|
2667
|
+
// live run, reject injection before it can mutate the result map.
|
|
2668
|
+
if (!this.#lifecycle.isRunning) {
|
|
2669
|
+
return;
|
|
2670
|
+
}
|
|
2671
|
+
const node = this.#nodesById[nodeId];
|
|
2672
|
+
if (!node || !this.#isNodeSelected(node.id) || node.id === this.#consumedStreamingWatchNodeId) {
|
|
2673
|
+
return;
|
|
2674
|
+
}
|
|
2675
|
+
if (this.#isStreamingOutputWatchBoundary(node)) {
|
|
2676
|
+
throw new Error(`Cannot preload ${node.title} while it is running because a streaming boundary must be scheduled. ` +
|
|
2677
|
+
'Preload the producer before starting a new run instead.');
|
|
2678
|
+
}
|
|
2679
|
+
for (const [sourceNodeId, plans] of this.#streamingWatchPlansBySourceNodeId) {
|
|
2680
|
+
for (const plan of plans) {
|
|
2681
|
+
if (sourceNodeId === node.id || plan.graph.nodes.some((branchNode) => branchNode.id === node.id)) {
|
|
2682
|
+
throw new Error(`Cannot preload ${node.title} while Watch Streaming Output "${plan.watchNode.title}" is running. ` +
|
|
2683
|
+
'Start a new run so the watch can own its snapshots and branch invocations.');
|
|
2684
|
+
}
|
|
2685
|
+
}
|
|
2686
|
+
}
|
|
2687
|
+
}
|
|
2688
|
+
#assertStreamingOutputWatchPreloadsAreSafe() {
|
|
2689
|
+
for (const [nodeId] of this.#preloadedNodeResults) {
|
|
2690
|
+
const node = this.#nodesById[nodeId];
|
|
2691
|
+
if (!node || !this.#isNodeSelected(node.id) || node.id === this.#consumedStreamingWatchNodeId) {
|
|
2692
|
+
continue;
|
|
2693
|
+
}
|
|
2694
|
+
if (this.#isStreamingOutputWatchBoundary(node)) {
|
|
2695
|
+
throw new Error(`Cannot preload ${node.title} because a streaming boundary must be scheduled. ` +
|
|
2696
|
+
"Run from Watch Streaming Output to reuse a producer's saved final value, or run from the producer to stream again.");
|
|
2697
|
+
}
|
|
2698
|
+
}
|
|
2699
|
+
for (const [sourceNodeId, plans] of this.#streamingWatchPlansBySourceNodeId) {
|
|
2700
|
+
const sourceOutputs = this.#preloadedNodeResults.get(sourceNodeId);
|
|
2701
|
+
for (const plan of plans) {
|
|
2702
|
+
const preloadedBranchNode = plan.graph.nodes.find((node) => node.id !== this.#consumedStreamingWatchNodeId && this.#preloadedNodeResults.has(node.id));
|
|
2703
|
+
if (preloadedBranchNode) {
|
|
2704
|
+
throw new Error(`Cannot preload ${preloadedBranchNode.title} because it belongs to the repeated branch of ` +
|
|
2705
|
+
`Watch Streaming Output "${plan.watchNode.title}". ` +
|
|
2706
|
+
"Run from Watch Streaming Output to reuse a producer's saved final value, or run from the producer to stream again.");
|
|
2707
|
+
}
|
|
2708
|
+
if (sourceOutputs && sourceOutputs[plan.sourceOutputId] == null) {
|
|
2709
|
+
const sourceNode = this.#nodesById[sourceNodeId];
|
|
2710
|
+
throw new Error(`Preloaded source "${sourceNode.title}" has no final "${plan.sourceOutputId}" output for ` +
|
|
2711
|
+
`Watch Streaming Output "${plan.watchNode.title}".`);
|
|
2712
|
+
}
|
|
2713
|
+
}
|
|
2714
|
+
}
|
|
2715
|
+
}
|
|
2716
|
+
#publishStreamingOutputWatchPartial(node, partialOutputs) {
|
|
2717
|
+
for (const plan of this.#streamingWatchPlansBySourceNodeId.get(node.id) ?? []) {
|
|
2718
|
+
const value = partialOutputs[plan.sourceOutputId];
|
|
2719
|
+
if (value == null || value.type === 'control-flow-excluded') {
|
|
2720
|
+
continue;
|
|
2721
|
+
}
|
|
2722
|
+
const watch = this.#streamingOutputWatches.get(plan.watchNode.id);
|
|
2723
|
+
if (!watch || watch.stopped) {
|
|
2724
|
+
continue;
|
|
2725
|
+
}
|
|
2726
|
+
const updateIndex = this.#nextStreamingWatchUpdateIndex(plan);
|
|
2727
|
+
watch.publish(this.#createStreamingOutputWatchSnapshot(plan, value, updateIndex, false));
|
|
2728
|
+
}
|
|
2729
|
+
}
|
|
2730
|
+
#prepareGraphOutputPartialTopology() {
|
|
2731
|
+
if (!this.#graphOutputPartialListener) {
|
|
2732
|
+
return;
|
|
2733
|
+
}
|
|
2734
|
+
const relevantNodeIds = this.#getExecutionRelevantNodeIds();
|
|
2735
|
+
const graphOutputCountsById = new Map();
|
|
2736
|
+
for (const node of Object.values(this.#nodesById)) {
|
|
2737
|
+
if (node.type !== 'graphOutput' || node.disabled || (relevantNodeIds != null && !relevantNodeIds.has(node.id))) {
|
|
2738
|
+
continue;
|
|
2739
|
+
}
|
|
2740
|
+
const outputId = node.data.id;
|
|
2741
|
+
graphOutputCountsById.set(outputId, (graphOutputCountsById.get(outputId) ?? 0) + 1);
|
|
2742
|
+
}
|
|
2743
|
+
for (const connection of this.#getEffectiveConnections()) {
|
|
2744
|
+
if (!this.#isDefinitionValidConnection(connection) || connection.inputId !== 'value') {
|
|
2745
|
+
continue;
|
|
2746
|
+
}
|
|
2747
|
+
const graphOutput = this.#nodesById[connection.inputNodeId];
|
|
2748
|
+
if (graphOutput?.type !== 'graphOutput' ||
|
|
2749
|
+
graphOutput.disabled ||
|
|
2750
|
+
(relevantNodeIds != null && !relevantNodeIds.has(graphOutput.id))) {
|
|
2751
|
+
continue;
|
|
2752
|
+
}
|
|
2753
|
+
const graphOutputData = graphOutput.data;
|
|
2754
|
+
// Graph Outputs with the same public ID retain their long-standing
|
|
2755
|
+
// first-terminal-value-wins behavior. Before that winner is known, a
|
|
2756
|
+
// partial value would be ambiguous, so let the parent Watch receive
|
|
2757
|
+
// only the ordinary final named-boundary output.
|
|
2758
|
+
if (graphOutputCountsById.get(graphOutputData.id) > 1) {
|
|
2759
|
+
continue;
|
|
2760
|
+
}
|
|
2761
|
+
const sourceNode = this.#nodesById[connection.outputNodeId];
|
|
2762
|
+
if (!sourceNode || !this.#canStreamAcrossGraphOutput(graphOutput, sourceNode)) {
|
|
2763
|
+
continue;
|
|
2764
|
+
}
|
|
2765
|
+
const bindings = this.#graphOutputPartialBindingsBySourceNodeId.get(connection.outputNodeId) ?? [];
|
|
2766
|
+
bindings.push({
|
|
2767
|
+
dataType: graphOutputData.dataType,
|
|
2768
|
+
graphOutputId: graphOutputData.id,
|
|
2769
|
+
sourceOutputId: connection.outputId,
|
|
2770
|
+
});
|
|
2771
|
+
this.#graphOutputPartialBindingsBySourceNodeId.set(connection.outputNodeId, bindings);
|
|
2772
|
+
}
|
|
2773
|
+
}
|
|
2774
|
+
/**
|
|
2775
|
+
* A named Graph Output can forward a partial only when its terminal result
|
|
2776
|
+
* is determined by that same direct producer. Conditions, split aggregation,
|
|
2777
|
+
* and frozen replay each introduce an independent boundary decision, so they
|
|
2778
|
+
* remain final-only just like an ordinary intermediate node.
|
|
2779
|
+
*/
|
|
2780
|
+
#canStreamAcrossGraphOutput(graphOutput, sourceNode) {
|
|
2781
|
+
if (graphOutput.isConditional || graphOutput.isSplitRun || sourceNode.isSplitRun) {
|
|
2782
|
+
return false;
|
|
2783
|
+
}
|
|
2784
|
+
return !this.#hasFrozenNodeOutputOrUnknownResolver(graphOutput);
|
|
2785
|
+
}
|
|
2786
|
+
#hasFrozenNodeOutputOrUnknownResolver(node) {
|
|
2787
|
+
const resolver = this.#frozenNodeOutputResolver;
|
|
2788
|
+
if (!resolver) {
|
|
2789
|
+
return false;
|
|
2790
|
+
}
|
|
2791
|
+
// Do not call a resolver during topology preparation: generated resolvers
|
|
2792
|
+
// advance a per-node replay cursor, and arbitrary resolvers may have side
|
|
2793
|
+
// effects. The built-in resolver answers precisely; an opaque custom
|
|
2794
|
+
// resolver is final-only until execution resolves its value normally.
|
|
2795
|
+
return resolver.hasFrozenNodeOutput?.({ graphId: this.#graph.metadata.id, node }) !== false;
|
|
2796
|
+
}
|
|
2797
|
+
/**
|
|
2798
|
+
* A Graph Output is a named boundary, so only a direct effective connection
|
|
2799
|
+
* may make its source node stream across a Subgraph. The preprocessed
|
|
2800
|
+
* connections also cover Data Bus routes while excluding ordinary
|
|
2801
|
+
* intermediate nodes, which must still wait for their normal final input.
|
|
2802
|
+
*/
|
|
2803
|
+
#publishGraphOutputPartial(node, partialOutputs) {
|
|
2804
|
+
const listener = this.#graphOutputPartialListener;
|
|
2805
|
+
const bindings = this.#graphOutputPartialBindingsBySourceNodeId.get(node.id);
|
|
2806
|
+
if (!listener || !bindings) {
|
|
2807
|
+
return;
|
|
2808
|
+
}
|
|
2809
|
+
const outputs = {};
|
|
2810
|
+
for (const binding of bindings) {
|
|
2811
|
+
const partialValue = partialOutputs[binding.sourceOutputId];
|
|
2812
|
+
if (partialValue == null || partialValue.type === 'control-flow-excluded') {
|
|
2813
|
+
continue;
|
|
2814
|
+
}
|
|
2815
|
+
outputs[binding.graphOutputId] = coerceGraphOutputValue(partialValue, binding.dataType);
|
|
2816
|
+
}
|
|
2817
|
+
if (Object.keys(outputs).length > 0) {
|
|
2818
|
+
listener(outputs);
|
|
2819
|
+
}
|
|
2820
|
+
}
|
|
2821
|
+
#finishStreamingOutputWatches(node, outputs) {
|
|
2822
|
+
for (const plan of this.#streamingWatchPlansBySourceNodeId.get(node.id) ?? []) {
|
|
2823
|
+
const value = outputs[plan.sourceOutputId];
|
|
2824
|
+
const watch = this.#streamingOutputWatches.get(plan.watchNode.id);
|
|
2825
|
+
if (!watch || watch.stopped) {
|
|
2826
|
+
continue;
|
|
2827
|
+
}
|
|
2828
|
+
if (value == null) {
|
|
2829
|
+
// This is guarded before nodeFinish so a bad producer has one
|
|
2830
|
+
// coherent terminal lifecycle (nodeError, never nodeFinish + error).
|
|
2831
|
+
continue;
|
|
2832
|
+
}
|
|
2833
|
+
if (value.type === 'control-flow-excluded') {
|
|
2834
|
+
watch.stop();
|
|
2835
|
+
if (plan.stopNodeId) {
|
|
2836
|
+
this.#excludeNode(this.#nodesById[plan.stopNodeId], nanoid(), {}, 'watched output is excluded');
|
|
2837
|
+
}
|
|
2838
|
+
continue;
|
|
2839
|
+
}
|
|
2840
|
+
const updateIndex = this.#nextStreamingWatchUpdateIndex(plan);
|
|
2841
|
+
watch.finish(this.#createStreamingOutputWatchSnapshot(plan, value, updateIndex, true));
|
|
2842
|
+
}
|
|
2843
|
+
}
|
|
2844
|
+
#assertStreamingOutputWatchFinalOutputs(node, outputs) {
|
|
2845
|
+
for (const plan of this.#streamingWatchPlansBySourceNodeId.get(node.id) ?? []) {
|
|
2846
|
+
const watch = this.#streamingOutputWatches.get(plan.watchNode.id);
|
|
2847
|
+
if (!watch || watch.stopped || outputs[plan.sourceOutputId] != null) {
|
|
2848
|
+
continue;
|
|
2849
|
+
}
|
|
2850
|
+
throw new Error(`Watch Streaming Output "${plan.watchNode.title}" did not receive final output from "${node.title}".`);
|
|
2851
|
+
}
|
|
2852
|
+
}
|
|
2853
|
+
#nextStreamingWatchUpdateIndex(plan) {
|
|
2854
|
+
plan.nextUpdateIndex += 1;
|
|
2855
|
+
return plan.nextUpdateIndex;
|
|
2856
|
+
}
|
|
2857
|
+
#createStreamingOutputWatchSnapshot(plan, value, updateIndex, isFinal) {
|
|
2858
|
+
const snapshotValue = cloneExecutionOutputs({ ['value']: value })['value'];
|
|
2859
|
+
let streamedOutputLength;
|
|
2860
|
+
if (plan.includeAllStreamedOutput) {
|
|
2861
|
+
const streamedValue = snapshotValue.value;
|
|
2862
|
+
const previousValue = plan.previousStreamedValue;
|
|
2863
|
+
plan.previousStreamedValue = streamedValue;
|
|
2864
|
+
// LLM Chat publishes accumulated response text for every token. Store
|
|
2865
|
+
// only the suffix here so this history is linear in the response size,
|
|
2866
|
+
// while still supporting providers that publish independent chunks.
|
|
2867
|
+
const increment = typeof previousValue === 'string' &&
|
|
2868
|
+
typeof streamedValue === 'string' &&
|
|
2869
|
+
streamedValue.startsWith(previousValue)
|
|
2870
|
+
? streamedValue.slice(previousValue.length)
|
|
2871
|
+
: streamedValue;
|
|
2872
|
+
if (increment !== '') {
|
|
2873
|
+
plan.streamedOutput.push(increment);
|
|
2874
|
+
}
|
|
2875
|
+
streamedOutputLength = plan.streamedOutput.length;
|
|
2876
|
+
}
|
|
2877
|
+
const outputs = {
|
|
2878
|
+
['isFinal']: { type: 'boolean', value: isFinal },
|
|
2879
|
+
['updateIndex']: { type: 'number', value: updateIndex },
|
|
2880
|
+
['value']: snapshotValue,
|
|
2881
|
+
};
|
|
2882
|
+
return {
|
|
2883
|
+
outputs,
|
|
2884
|
+
isFinal,
|
|
2885
|
+
updateIndex,
|
|
2886
|
+
...(streamedOutputLength === undefined
|
|
2887
|
+
? {}
|
|
2888
|
+
: {
|
|
2889
|
+
streamedOutput: plan.streamedOutput,
|
|
2890
|
+
streamedOutputLength,
|
|
2891
|
+
}),
|
|
2892
|
+
};
|
|
2893
|
+
}
|
|
2894
|
+
#materializeStreamingOutputWatchSnapshot(snapshot) {
|
|
2895
|
+
if (snapshot.streamedOutput == null || snapshot.streamedOutputLength == null) {
|
|
2896
|
+
return snapshot.outputs;
|
|
2897
|
+
}
|
|
2898
|
+
// Construct cumulative chunks only for a branch that actually starts. A
|
|
2899
|
+
// coalesced interval update or a queue-dropped update therefore performs no
|
|
2900
|
+
// quadratic history copy merely because All Chunks is connected.
|
|
2901
|
+
return {
|
|
2902
|
+
...snapshot.outputs,
|
|
2903
|
+
['allStreamedOutput']: cloneExecutionOutputs({
|
|
2904
|
+
['allStreamedOutput']: {
|
|
2905
|
+
type: 'any[]',
|
|
2906
|
+
value: snapshot.streamedOutput.slice(0, snapshot.streamedOutputLength),
|
|
2907
|
+
},
|
|
2908
|
+
})['allStreamedOutput'],
|
|
2909
|
+
};
|
|
2910
|
+
}
|
|
2911
|
+
async #runStreamingOutputWatchInvocation(plan, snapshot, registerCancel) {
|
|
2912
|
+
const root = this.getRootProcessor();
|
|
2913
|
+
if (root.#abortController.signal.aborted) {
|
|
2914
|
+
throw createGraphAbortErrorFromSignal(root.#abortController.signal, 'Streaming watch branch aborted before it started');
|
|
2915
|
+
}
|
|
2916
|
+
const graphId = plan.graph.metadata?.id;
|
|
2917
|
+
if (!graphId) {
|
|
2918
|
+
throw new Error('Cannot start a streaming watch branch because the current graph has no ID.');
|
|
2919
|
+
}
|
|
2920
|
+
const historyIteration = plan.history.start(nanoid(), snapshot.updateIndex);
|
|
2921
|
+
const branchRuntimeCache = {
|
|
2922
|
+
...this.#runtimeCache,
|
|
2923
|
+
graphBoundaries: undefined,
|
|
2924
|
+
loadedProjects: { ...this.#loadedProjects },
|
|
2925
|
+
};
|
|
2926
|
+
const processor = new GraphProcessor(this.#project, graphId, this.#registry, this.#includeTrace, {
|
|
2927
|
+
cacheLoadedProjects: true,
|
|
2928
|
+
captureNodeTimings: this.#captureNodeTimings,
|
|
2929
|
+
concurrency: this.#concurrency,
|
|
2930
|
+
executionPlanCacheMode: this.#executionPlanCacheMode,
|
|
2931
|
+
runtimeCache: branchRuntimeCache,
|
|
2932
|
+
runtimeProfiler: this.#runtimeProfiler,
|
|
2933
|
+
scheduler: this.#scheduler,
|
|
2934
|
+
[consumedStreamingWatchNodeOverride]: plan.watchNode.id,
|
|
2935
|
+
[graphProcessorGraphOverride]: plan.graph,
|
|
2936
|
+
});
|
|
2937
|
+
processor.executor = this.executor;
|
|
2938
|
+
processor.#isSubProcessor = true;
|
|
2939
|
+
processor.#executionCache = this.#executionCache;
|
|
2940
|
+
processor.#externalFunctions = this.#externalFunctions;
|
|
2941
|
+
processor.#contextValues = this.#contextValues;
|
|
2942
|
+
processor.#parent = this;
|
|
2943
|
+
processor.#abortOwnerOverride = root;
|
|
2944
|
+
processor.#suppressGraphPartialOutputs = true;
|
|
2945
|
+
processor.#globals = this.#globals;
|
|
2946
|
+
processor.#storedValueController = this.#storedValueController;
|
|
2947
|
+
processor.#knowledgeStoreController = this.#knowledgeStoreController;
|
|
2948
|
+
processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
|
|
2949
|
+
processor.#executor = this.#executor;
|
|
2950
|
+
processor.#suppressGraphLifecycleEvents = true;
|
|
2951
|
+
processor.#sharedRunStateOverride = {
|
|
2952
|
+
// Repeated node IDs do not imply shared race/loop state between snapshots.
|
|
2953
|
+
attachedNodeData: new Map(),
|
|
2954
|
+
graphInputNodeValues: { ...this.#graphInputNodeValues },
|
|
2955
|
+
graphOutputs: {},
|
|
2956
|
+
};
|
|
2957
|
+
processor.#executionIdentityOverride = {
|
|
2958
|
+
rootRunId: root.#rootRunId,
|
|
2959
|
+
graphRunId: historyIteration.graphRunId,
|
|
2960
|
+
parentGraphRunId: this.#graphRunId,
|
|
2961
|
+
};
|
|
2962
|
+
processor.#streamingWatchInvocation = {
|
|
2963
|
+
plan,
|
|
2964
|
+
historyIteration,
|
|
2965
|
+
acceptStop: (value) => this.#acceptStreamingWatchStop(plan, historyIteration, value, snapshot.updateIndex),
|
|
2966
|
+
stopReached: false,
|
|
2967
|
+
};
|
|
2968
|
+
processor.preloadNodeData(plan.watchNode.id, this.#materializeStreamingOutputWatchSnapshot(snapshot));
|
|
2969
|
+
processor.#suppressedPreloadedNodeIds.add(plan.watchNode.id);
|
|
2970
|
+
let cancellationRequested = false;
|
|
2971
|
+
registerCancel(() => {
|
|
2972
|
+
cancellationRequested = true;
|
|
2973
|
+
if (processor.isRunning) {
|
|
2974
|
+
void processor.abort(true);
|
|
2975
|
+
}
|
|
2976
|
+
});
|
|
2977
|
+
const unwireEvents = wireSubprocessorEvents(processor, root.#emitter, {
|
|
2978
|
+
autoCleanup: false,
|
|
2979
|
+
isPaused: () => root.#lifecycle.isPaused,
|
|
2980
|
+
pause: () => {
|
|
2981
|
+
void root.pause();
|
|
2982
|
+
},
|
|
2983
|
+
resume: () => {
|
|
2984
|
+
void root.resume();
|
|
2985
|
+
},
|
|
2986
|
+
forwardEvent: (event, data) => {
|
|
2987
|
+
// Interactive/global control events are side effects, not execution
|
|
2988
|
+
// history. They must remain live even when their enclosing iteration
|
|
2989
|
+
// is not selected for retained evidence.
|
|
2990
|
+
if (event === 'userInput' ||
|
|
2991
|
+
event === 'globalSet' ||
|
|
2992
|
+
event === 'newAbortController' ||
|
|
2993
|
+
event.startsWith('globalSet:')) {
|
|
2994
|
+
return root.#emitter.emit(event, data);
|
|
2995
|
+
}
|
|
2996
|
+
return plan.history.forward(historyIteration, event, data, (nextEvent, nextData) => root.#emitter.emit(nextEvent, nextData));
|
|
2997
|
+
},
|
|
2998
|
+
});
|
|
2999
|
+
const unwireLifecycle = wireSubprocessorLifecycle(processor, {
|
|
3000
|
+
autoCleanup: false,
|
|
3001
|
+
signal: this.#abortController.signal,
|
|
3002
|
+
parentAbortSignal: root.#abortController.signal,
|
|
3003
|
+
onParentPause: (listener) => {
|
|
3004
|
+
root.on('pause', listener);
|
|
3005
|
+
return () => root.off('pause', listener);
|
|
3006
|
+
},
|
|
3007
|
+
onParentResume: (listener) => {
|
|
3008
|
+
root.on('resume', listener);
|
|
3009
|
+
return () => root.off('resume', listener);
|
|
3010
|
+
},
|
|
3011
|
+
});
|
|
3012
|
+
root.#subprocessors.add(processor);
|
|
3013
|
+
try {
|
|
3014
|
+
if (root.#lifecycle.isPaused) {
|
|
3015
|
+
processor.pause();
|
|
3016
|
+
}
|
|
3017
|
+
await processor.processGraph(this.#context, this.#graphInputs, this.#contextValues);
|
|
3018
|
+
}
|
|
3019
|
+
catch (error) {
|
|
3020
|
+
const normalizedError = getError(error);
|
|
3021
|
+
const wasCancelled = isAbortLikeError(normalizedError) || root.#abortController.signal.aborted || cancellationRequested;
|
|
3022
|
+
if (wasCancelled) {
|
|
3023
|
+
plan.history.cancel(historyIteration);
|
|
3024
|
+
}
|
|
3025
|
+
else {
|
|
3026
|
+
plan.history.fail(historyIteration);
|
|
3027
|
+
this.#recordStreamingWatchFailure(plan.watchNode, normalizedError, processor);
|
|
3028
|
+
}
|
|
3029
|
+
// Preserve one Error identity across the child processor, scheduler, and
|
|
3030
|
+
// root failure collector. A user node may throw a string or another
|
|
3031
|
+
// non-Error value; allowing the scheduler to wrap it again would make
|
|
3032
|
+
// that one branch failure appear twice in the root aggregate.
|
|
3033
|
+
throw normalizedError;
|
|
3034
|
+
}
|
|
3035
|
+
finally {
|
|
3036
|
+
if (cancellationRequested) {
|
|
3037
|
+
plan.history.cancel(historyIteration);
|
|
3038
|
+
}
|
|
3039
|
+
plan.history.complete(historyIteration);
|
|
3040
|
+
this.#totalCost += processor.#totalCost;
|
|
3041
|
+
unwireLifecycle();
|
|
3042
|
+
unwireEvents();
|
|
3043
|
+
root.#subprocessors.delete(processor);
|
|
3044
|
+
}
|
|
3045
|
+
}
|
|
3046
|
+
#commitStreamingWatchStop(node, outputs) {
|
|
3047
|
+
const invocation = this.#streamingWatchInvocation;
|
|
3048
|
+
const completedValue = outputs['value'];
|
|
3049
|
+
if (invocation?.plan.stopNodeId === node.id &&
|
|
3050
|
+
invocation.stopReached &&
|
|
3051
|
+
completedValue !== undefined &&
|
|
3052
|
+
!this.#getUnhandledErroredNodes().length) {
|
|
3053
|
+
invocation.acceptStop(completedValue);
|
|
3054
|
+
}
|
|
3055
|
+
}
|
|
3056
|
+
#acceptStreamingWatchStop(plan, historyIteration, value, updateIndex) {
|
|
3057
|
+
const stopNodeId = plan.stopNodeId;
|
|
3058
|
+
if (!stopNodeId) {
|
|
3059
|
+
return;
|
|
3060
|
+
}
|
|
3061
|
+
const watch = this.#streamingOutputWatches.get(plan.watchNode.id);
|
|
3062
|
+
if (!watch || watch.stopped) {
|
|
3063
|
+
return;
|
|
3064
|
+
}
|
|
3065
|
+
plan.history.acceptStop(historyIteration);
|
|
3066
|
+
watch.stop(updateIndex);
|
|
3067
|
+
const stopNode = this.#nodesById[stopNodeId];
|
|
3068
|
+
if (!stopNode) {
|
|
3069
|
+
throw new Error(`Watch Streaming Output "${plan.watchNode.title}" lost its Stop Watching Streaming Output node.`);
|
|
3070
|
+
}
|
|
3071
|
+
const acceptedValue = cloneExecutionOutputs({ ['value']: value })['value'];
|
|
3072
|
+
this.#nodeResults.set(stopNode.id, { ['value']: acceptedValue });
|
|
3073
|
+
this.#visitedNodes.add(stopNode.id);
|
|
3074
|
+
this.#remainingNodes.delete(stopNode.id);
|
|
3075
|
+
const attachedData = this.#getAttachedDataTo(stopNode);
|
|
3076
|
+
const outputNodes = getOutputNodesFrom(this.#executionState, stopNode);
|
|
3077
|
+
this.#propagateAttachedDataToOutputNodes(stopNode, attachedData, outputNodes.connectionsToNodes);
|
|
3078
|
+
this.#queueOutputNodes(stopNode, outputNodes.nodes);
|
|
3079
|
+
}
|
|
3080
|
+
#cancelStreamingOutputWatchesForSource(nodeId) {
|
|
3081
|
+
for (const plan of this.#streamingWatchPlansBySourceNodeId.get(nodeId) ?? []) {
|
|
3082
|
+
this.#streamingOutputWatches.get(plan.watchNode.id)?.stop();
|
|
3083
|
+
}
|
|
3084
|
+
}
|
|
3085
|
+
#cancelStreamingOutputWatches() {
|
|
3086
|
+
for (const watch of this.#streamingOutputWatches.values()) {
|
|
3087
|
+
watch.stop();
|
|
3088
|
+
}
|
|
3089
|
+
}
|
|
3090
|
+
#hasPendingStreamingOutputWatches() {
|
|
3091
|
+
return [...this.#streamingOutputWatches.values()].some((watch) => watch.hasPending);
|
|
3092
|
+
}
|
|
3093
|
+
#hasUnresolvedForegroundOutputStreamingWatch() {
|
|
3094
|
+
return [...this.#streamingOutputWatches.values()].some((watch) => !watch.stopped && watch.canAffectForegroundOutputs);
|
|
3095
|
+
}
|
|
3096
|
+
#hasDrainableStreamingOutputWatches() {
|
|
3097
|
+
return [...this.#streamingOutputWatches.values()].some((watch) => watch.hasPending && !watch.isAwaitingProducer);
|
|
3098
|
+
}
|
|
3099
|
+
async #drainSchedulerBoundaries() {
|
|
3100
|
+
do {
|
|
3101
|
+
if (!this.#isSubProcessor) {
|
|
3102
|
+
await this.#profileRuntimeAsync('drainManagedAsyncBranches', () => this.#managedAsyncBranches.drain());
|
|
3103
|
+
}
|
|
3104
|
+
await this.#profileRuntimeAsync('drainStreamingOutputWatches', () => this.#drainStreamingOutputWatches());
|
|
3105
|
+
} while ((!this.#isSubProcessor && this.#managedAsyncBranches.hasPending) ||
|
|
3106
|
+
this.#hasDrainableStreamingOutputWatches());
|
|
3107
|
+
}
|
|
3108
|
+
async #drainStreamingOutputWatches() {
|
|
3109
|
+
do {
|
|
3110
|
+
for (const watch of this.#streamingOutputWatches.values()) {
|
|
3111
|
+
await watch.drain();
|
|
3112
|
+
}
|
|
3113
|
+
// Accepting Stop happens in a child run. It can enqueue ordinary parent
|
|
3114
|
+
// work after the compatible scheduler has returned, so wait for that work
|
|
3115
|
+
// before deciding every Watch boundary is quiet.
|
|
3116
|
+
await this.#processingQueue.onIdle();
|
|
3117
|
+
} while (this.#hasDrainableStreamingOutputWatches());
|
|
3118
|
+
for (const [watchNodeId, watch] of this.#streamingOutputWatches) {
|
|
3119
|
+
const plan = this.#streamingWatchPlansByWatchNodeId.get(watchNodeId);
|
|
3120
|
+
if (!plan || plan.historySummaryEmitted || !watch.isSettled)
|
|
3121
|
+
continue;
|
|
3122
|
+
const summary = await plan.history.finalize(watch.runtimeSummary, (event, data) => this.#emitter.emit(event, data));
|
|
3123
|
+
plan.historySummaryEmitted = true;
|
|
3124
|
+
await this.#emitter.emit('streamingOutputWatchSummary', this.#withExecution({ watchNode: plan.watchNode, summary }));
|
|
3125
|
+
}
|
|
3126
|
+
}
|
|
2361
3127
|
#prepareAsyncBranchTopology() {
|
|
2362
3128
|
const connections = this.#getEffectiveConnections().filter((connection) => this.#isDefinitionValidConnection(connection));
|
|
2363
3129
|
const outgoingByNodeId = new Map();
|
|
@@ -2420,6 +3186,10 @@ export class GraphProcessor {
|
|
|
2420
3186
|
if (nodeIds.size === 0) {
|
|
2421
3187
|
continue;
|
|
2422
3188
|
}
|
|
3189
|
+
const managedAsyncBranchWatchViolation = this.#getManagedAsyncBranchWatchViolation(triggerNode);
|
|
3190
|
+
if (managedAsyncBranchWatchViolation) {
|
|
3191
|
+
throw managedAsyncBranchWatchViolation;
|
|
3192
|
+
}
|
|
2423
3193
|
const preloadedNodeId = [...nodeIds].find((nodeId) => this.#nodeResults.has(nodeId));
|
|
2424
3194
|
if (preloadedNodeId) {
|
|
2425
3195
|
const preloadedNode = this.#nodesById[preloadedNodeId];
|
|
@@ -2720,6 +3490,7 @@ export class GraphProcessor {
|
|
|
2720
3490
|
this.#registerNodeInActiveLoop(node, attachedData);
|
|
2721
3491
|
this.#visitedNodes.add(node.id);
|
|
2722
3492
|
this.#markAsExcluded(node, processId, inputValues, reason);
|
|
3493
|
+
this.#finishStreamingOutputWatches(node, this.#nodeResults.get(node.id));
|
|
2723
3494
|
this.#currentlyProcessing.delete(node.id);
|
|
2724
3495
|
this.#remainingNodes.delete(node.id);
|
|
2725
3496
|
const outputNodes = getOutputNodesFrom(this.#executionState, node);
|
|
@@ -2734,10 +3505,12 @@ export class GraphProcessor {
|
|
|
2734
3505
|
}
|
|
2735
3506
|
async #emitNodeExcluded(node, processId, inputValues, reason, resultOrigin = 'executed') {
|
|
2736
3507
|
await this.#emitter.emit('nodeExcluded', this.#createNodeExcludedEvent(node, processId, inputValues, reason, resultOrigin));
|
|
3508
|
+
this.#finishStreamingOutputWatches(node, this.#nodeResults.get(node.id));
|
|
2737
3509
|
}
|
|
2738
3510
|
#createNodeExcludedEvent(node, processId, inputValues, reason, resultOrigin = 'executed') {
|
|
2739
3511
|
const outputs = createExcludedNodeOutputs(node, this.#definitions[node.id].outputs);
|
|
2740
3512
|
this.#nodeResults.set(node.id, outputs);
|
|
3513
|
+
this.#commitExcludedGraphOutput(node, inputValues, outputs);
|
|
2741
3514
|
return this.#withExecution({
|
|
2742
3515
|
node,
|
|
2743
3516
|
processId,
|
|
@@ -2747,6 +3520,17 @@ export class GraphProcessor {
|
|
|
2747
3520
|
resultOrigin,
|
|
2748
3521
|
});
|
|
2749
3522
|
}
|
|
3523
|
+
#commitExcludedGraphOutput(node, inputs, outputs) {
|
|
3524
|
+
const isFalseCondition = node.isConditional && coerceTypeOptional(inputs[IF_PORT.id], 'boolean') === false;
|
|
3525
|
+
if (node.type !== 'graphOutput' || (inputs['value'] == null && !isFalseCondition)) {
|
|
3526
|
+
return;
|
|
3527
|
+
}
|
|
3528
|
+
const outputId = node.data.id;
|
|
3529
|
+
const value = outputs['valueOutput'];
|
|
3530
|
+
if (value) {
|
|
3531
|
+
commitGraphOutputValue(this.#graphOutputs, outputId, value);
|
|
3532
|
+
}
|
|
3533
|
+
}
|
|
2750
3534
|
#getInputValuesForNode(node) {
|
|
2751
3535
|
const connections = this.#connections[node.id];
|
|
2752
3536
|
return this.#definitions[node.id].inputs.reduce((values, input) => {
|