@valerypopoff/rivet2-core 2.12.0 → 2.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/cjs/bundle.cjs +781 -245
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/esm/exports.js +1 -0
  4. package/dist/esm/model/GraphInputStream.js +70 -0
  5. package/dist/esm/model/GraphProcessor.js +257 -16
  6. package/dist/esm/model/NodeExecutionPlanner.js +4 -4
  7. package/dist/esm/model/Nodes.js +3 -0
  8. package/dist/esm/model/ProcessContextBuilder.js +2 -1
  9. package/dist/esm/model/StreamingOutputWatch.js +5 -0
  10. package/dist/esm/model/StreamingWatchTopology.js +191 -0
  11. package/dist/esm/model/nodes/AssembleMessageNode.js +2 -2
  12. package/dist/esm/model/nodes/AssemblePromptNode.js +46 -17
  13. package/dist/esm/model/nodes/GraphInputNode.js +15 -19
  14. package/dist/esm/model/nodes/MatchCaseNode.js +2 -2
  15. package/dist/esm/model/nodes/ProjectNameNode.js +37 -0
  16. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +1 -0
  17. package/dist/esm/model/nodes/SubGraphNode.js +1 -0
  18. package/dist/esm/model/nodes/variadicPortIndex.js +1 -1
  19. package/dist/types/exports.d.ts +2 -0
  20. package/dist/types/model/GraphInputStream.d.ts +23 -0
  21. package/dist/types/model/GraphProcessor.d.ts +3 -0
  22. package/dist/types/model/NodeExecutionPlanner.d.ts +1 -1
  23. package/dist/types/model/Nodes.d.ts +3 -2
  24. package/dist/types/model/ProcessContext.d.ts +3 -0
  25. package/dist/types/model/ProcessContextBuilder.d.ts +2 -1
  26. package/dist/types/model/StreamingOutputWatch.d.ts +2 -0
  27. package/dist/types/model/StreamingWatchTopology.d.ts +20 -0
  28. package/dist/types/model/nodes/AssemblePromptNode.d.ts +4 -3
  29. package/dist/types/model/nodes/GraphInputNode.d.ts +2 -0
  30. package/dist/types/model/nodes/MatchCaseNode.d.ts +1 -1
  31. package/dist/types/model/nodes/ProjectNameNode.d.ts +12 -0
  32. package/dist/types/model/nodes/variadicPortIndex.d.ts +1 -0
  33. package/package.json +1 -1
@@ -6,6 +6,7 @@ export * from './model/DataValue.js';
6
6
  export * from './model/NodeBase.js';
7
7
  export * from './model/NodeGraph.js';
8
8
  export * from './model/NodePrefabResolver.js';
9
+ export * from './model/StreamingWatchTopology.js';
9
10
  export { getGraphBoundary } from './model/GraphBoundaryCache.js';
10
11
  export * from './model/UiGraph.js';
11
12
  export * from './model/UiGraphNormalization.js';
@@ -0,0 +1,70 @@
1
+ import { cloneExecutionOutputs } from './ExecutionOutputClone.js';
2
+ /** One invocation/port, one subscriber, bounded pre-start snapshot, one terminal. */
3
+ export class GraphInputStreamRelay {
4
+ result;
5
+ settled;
6
+ #resolve;
7
+ #listener;
8
+ #latest;
9
+ #coalesced = 0;
10
+ #disposed = false;
11
+ constructor() {
12
+ this.settled = new Promise((resolve) => {
13
+ this.#resolve = resolve;
14
+ });
15
+ }
16
+ publish(value, coalesced = 0) {
17
+ if (this.result || this.#disposed)
18
+ return;
19
+ const snapshot = cloneExecutionOutputs({ ['value']: value })['value'];
20
+ if (this.#listener)
21
+ this.#listener(snapshot, coalesced);
22
+ else {
23
+ this.#coalesced += coalesced;
24
+ if (this.#latest)
25
+ this.#coalesced++;
26
+ this.#latest = snapshot;
27
+ }
28
+ }
29
+ finish(result) {
30
+ if (this.result)
31
+ return;
32
+ this.result = result.error
33
+ ? result
34
+ : {
35
+ value: cloneExecutionOutputs({ ['value']: result.value })['value'],
36
+ };
37
+ if (result.error || result.value?.type === 'control-flow-excluded') {
38
+ this.#latest = undefined;
39
+ this.#coalesced = 0;
40
+ }
41
+ this.#resolve(this.result);
42
+ }
43
+ subscribe(listener) {
44
+ if (this.#disposed)
45
+ return () => { };
46
+ if (this.#listener)
47
+ throw new Error('Graph input stream already has a subscriber');
48
+ this.#listener = listener;
49
+ const dispose = () => {
50
+ if (this.#listener !== listener)
51
+ return;
52
+ this.#listener = undefined;
53
+ this.#disposed = true;
54
+ this.#latest = undefined;
55
+ };
56
+ try {
57
+ if (this.#latest)
58
+ listener(this.#latest, this.#coalesced);
59
+ return dispose;
60
+ }
61
+ catch (error) {
62
+ dispose();
63
+ throw error;
64
+ }
65
+ finally {
66
+ this.#latest = undefined;
67
+ this.#coalesced = 0;
68
+ }
69
+ }
70
+ }
@@ -33,6 +33,9 @@ import { ManagedAsyncBranches } from './ManagedAsyncBranches.js';
33
33
  import { StreamingOutputWatch, } from './StreamingOutputWatch.js';
34
34
  import { StreamingOutputWatchHistory, } from './StreamingOutputWatchHistory.js';
35
35
  import { cloneExecutionOutputs } from './ExecutionOutputClone.js';
36
+ import { GraphInputStreamRelay } from './GraphInputStream.js';
37
+ import { canStreamThroughGraphCaller, canStreamThroughGraphInput, getProjectStreamingOutputWatchConnections, } from './StreamingWatchTopology.js';
38
+ import { resolveGraphInputValue } from './nodes/GraphInputNode.js';
36
39
  import { KnowledgeStoreController } from '../integrations/KnowledgeStoreProvider.js';
37
40
  import { isDataBusTopologyNode } from './DataBusTopology.js';
38
41
  import { resolveNodePrefabInstance } from './NodePrefabResolver.js';
@@ -45,15 +48,6 @@ const graphProcessorGraphOverride = Symbol('graphProcessorGraphOverride');
45
48
  const consumedAsyncBranchTriggerOverride = Symbol('consumedAsyncBranchTriggerOverride');
46
49
  const asyncBranchInputAnchorsOverride = Symbol('asyncBranchInputAnchorsOverride');
47
50
  const consumedStreamingWatchNodeOverride = Symbol('consumedStreamingWatchNodeOverride');
48
- /**
49
- * These nodes expose a child graph's named Graph Output ports verbatim. Other
50
- * nodes that happen to run a graph (for example Call Graph or Loop Until)
51
- * aggregate or transform child outputs, so streaming through them would not
52
- * have the same terminal semantics.
53
- */
54
- function isNamedGraphBoundaryCaller(node) {
55
- return node.type === 'subGraph' || node.type === 'referencedGraphAlias';
56
- }
57
51
  function createGraphOutputsOverlay(parent) {
58
52
  const writes = {};
59
53
  const view = new Proxy(writes, {
@@ -187,6 +181,12 @@ export class GraphProcessor {
187
181
  #graphOutputPartialListener;
188
182
  #consumedStreamingWatchNodeId;
189
183
  #streamingWatchInvocation;
184
+ #graphInputStreams = {};
185
+ #callerInputStreams = new Map();
186
+ #inputStreamRoutes = new Map();
187
+ #streamCallerTasks = new Set();
188
+ #inputStreamDisposers = [];
189
+ #pendingGraphInputFinals = new Map();
190
190
  #registry;
191
191
  #concurrency;
192
192
  #executionPlanCacheMode;
@@ -768,6 +768,12 @@ export class GraphProcessor {
768
768
  try {
769
769
  try {
770
770
  this.#profileRuntimeSync('initializeGraphRun', () => this.#initializeGraphRun(context, inputs, contextValues));
771
+ this.#graphInputStreams = options.graphInputStreams ?? {};
772
+ this.#callerInputStreams = new Map();
773
+ this.#inputStreamRoutes = new Map();
774
+ this.#streamCallerTasks = new Set();
775
+ this.#inputStreamDisposers = [];
776
+ this.#pendingGraphInputFinals = new Map();
771
777
  await this.#profileRuntimeAsync('loadProjectReferences', () => this.#loadProjectReferences());
772
778
  this.#profileRuntimeSync('initializeProjectGlobalVariables', () => this.#initializeProjectGlobalVariablesForRootRun());
773
779
  this.#profileRuntimeSync('prepareNodeProcessContextBase', () => this.#prepareNodeProcessContextBase());
@@ -792,6 +798,7 @@ export class GraphProcessor {
792
798
  this.#prepareAsyncBranchTopology();
793
799
  this.#prepareStreamingWatchTopology();
794
800
  this.#prepareGraphOutputPartialTopology();
801
+ this.#prepareGraphInputStreamRoutes();
795
802
  }
796
803
  catch (error) {
797
804
  const normalizedError = getError(error);
@@ -799,6 +806,7 @@ export class GraphProcessor {
799
806
  throw normalizedError;
800
807
  }
801
808
  await this.#profileRuntimeAsync('emitGraphStart', () => this.#emitGraphStart());
809
+ this.#subscribeGraphInputStreams();
802
810
  await this.#profileRuntimeAsync('emitInitialProjectGlobalVariables', () => this.#emitInitialProjectGlobalVariables());
803
811
  await this.#profileRuntimeAsync('emitPreloadedNodeResults', () => this.#emitPreloadedNodeResults());
804
812
  await this.#profileRuntimeAsync('waitUntilUnpaused', () => this.#waitUntilUnpaused());
@@ -827,6 +835,13 @@ export class GraphProcessor {
827
835
  return await this.#profileRuntimeAsync('finalizeGraphRun', () => this.#finalizeGraphRun());
828
836
  }
829
837
  finally {
838
+ for (const dispose of this.#inputStreamDisposers)
839
+ dispose();
840
+ this.#pendingGraphInputFinals.clear();
841
+ for (const streams of this.#callerInputStreams.values()) {
842
+ for (const relay of Object.values(streams))
843
+ relay.finish({ error: new Error('Graph input stream owner finished') });
844
+ }
830
845
  await this.#drainSchedulerBoundaries();
831
846
  this.#graphOutputPartialListener = undefined;
832
847
  this.#lifecycle.complete();
@@ -1090,6 +1105,37 @@ export class GraphProcessor {
1090
1105
  await this.#queueStartNodes(this.#graphOutputSelection?.startNodes ??
1091
1106
  getStartNodes(this.#executionState, this.#executionGraphNodes, this.runToNodeIds));
1092
1107
  await this.#processingQueue.onIdle();
1108
+ if (Object.keys(this.#graphInputStreams).length) {
1109
+ await this.#waitForGraphInputStreams();
1110
+ for (const [nodeId, outputs] of this.#pendingGraphInputFinals) {
1111
+ this.#finishStreamingOutputWatches(this.#nodesById[nodeId], outputs);
1112
+ }
1113
+ this.#pendingGraphInputFinals.clear();
1114
+ for (const node of this.#executionGraphNodes) {
1115
+ if (!this.#isNodeSelected(node.id))
1116
+ continue;
1117
+ void this.#processingQueue.add(() => this.#processNodeIfAllInputsAvailable(node));
1118
+ }
1119
+ await this.#processingQueue.onIdle();
1120
+ }
1121
+ while (this.#streamCallerTasks.size) {
1122
+ // A producer skipped transitively after an upstream failure never emits
1123
+ // nodeError itself. Settle its consumers once ordinary work is quiescent.
1124
+ for (const [sourceId, routes] of this.#inputStreamRoutes) {
1125
+ if (this.#currentlyProcessing.has(sourceId) || routes.every(({ relay }) => relay.result))
1126
+ continue;
1127
+ const failedDependency = this.getDependencyNodesDeep(sourceId).find((id) => this.#erroredNodes.has(id));
1128
+ if (failedDependency) {
1129
+ const error = getError(this.#erroredNodes.get(failedDependency));
1130
+ for (const { relay } of routes)
1131
+ relay.finish({ error });
1132
+ }
1133
+ }
1134
+ // Recheck skipped producers after each caller settles; another caller may
1135
+ // depend on ordinary nodes skipped because this caller failed.
1136
+ await Promise.race(this.#streamCallerTasks);
1137
+ await this.#processingQueue.onIdle();
1138
+ }
1093
1139
  this.#markUnqueuedNodesIgnored();
1094
1140
  }
1095
1141
  #canUseFastAcyclicScheduler() {
@@ -1097,6 +1143,8 @@ export class GraphProcessor {
1097
1143
  return false;
1098
1144
  }
1099
1145
  if (this.#graphOutputSelection ||
1146
+ this.#callerInputStreams.size > 0 ||
1147
+ Object.keys(this.#graphInputStreams).length > 0 ||
1100
1148
  this.#hasPreloadedData ||
1101
1149
  this.runToNodeIds ||
1102
1150
  this.slowMode ||
@@ -1347,6 +1395,13 @@ export class GraphProcessor {
1347
1395
  async #processNodeIfAllInputsAvailable(node, options = {}) {
1348
1396
  if (!this.#isNodeSelected(node.id))
1349
1397
  return [];
1398
+ // Waiting graph callers must not occupy a queue slot needed by their producer.
1399
+ if (this.#callerInputStreams.has(node.id) && !options.streamingDispatch) {
1400
+ const task = this.#processNodeIfAllInputsAvailable(node, { ...options, streamingDispatch: true }).catch((error) => this.#nodeErrored(node, error, nanoid()));
1401
+ this.#streamCallerTasks.add(task);
1402
+ void task.then(() => this.#streamCallerTasks.delete(task), () => this.#streamCallerTasks.delete(task));
1403
+ return [];
1404
+ }
1350
1405
  const { queueOutputNodes = true } = options;
1351
1406
  const builtInNode = node;
1352
1407
  const inputNodesProfileStart = this.#startRuntimeProfile();
@@ -1359,6 +1414,38 @@ export class GraphProcessor {
1359
1414
  if (this.#shouldSkipNodeProcessing(node, inputNodes)) {
1360
1415
  return [];
1361
1416
  }
1417
+ const namedInput = node.type === 'graphInput' ? node.data.id : undefined;
1418
+ const inputStream = namedInput != null && Object.hasOwn(this.#graphInputStreams, namedInput)
1419
+ ? this.#graphInputStreams[namedInput]
1420
+ : undefined;
1421
+ if (inputStream) {
1422
+ const terminals = Object.values(this.#graphInputStreams).map((stream) => stream.result);
1423
+ // A containing invocation cannot release a successful final into a deeper
1424
+ // caller when another required input failed or was excluded.
1425
+ const terminal = terminals.find((result) => result?.error) ??
1426
+ terminals.find((result) => result?.value?.type === 'control-flow-excluded') ??
1427
+ inputStream.result;
1428
+ if (!terminal)
1429
+ return [];
1430
+ if (terminal.error) {
1431
+ await this.#nodeErrored(node, terminal.error, nanoid());
1432
+ return [];
1433
+ }
1434
+ if (terminal.value.type === 'control-flow-excluded') {
1435
+ return this.#excludeNode(node, nanoid(), {}, 'streamed input is excluded', { queueOutputNodes });
1436
+ }
1437
+ // Final boundary results retain the invocation's original readiness barrier.
1438
+ // Otherwise a deeper caller could finish its ordinary work while a sibling
1439
+ // input to this invocation is still streaming.
1440
+ if (terminals.some((result) => !result))
1441
+ return [];
1442
+ }
1443
+ else if (node.type !== 'graphInput' &&
1444
+ !this.#callerInputStreams.has(node.id) &&
1445
+ Object.values(this.#graphInputStreams).some((stream) => !stream.result || stream.result.error || stream.result.value?.type === 'control-flow-excluded')) {
1446
+ // Only streaming boundary plumbing runs early; ordinary side effects wait.
1447
+ return [];
1448
+ }
1362
1449
  const attachedData = this.#getAttachedDataTo(node);
1363
1450
  if (this.#shouldSkipCompletedRaceNode(node, attachedData)) {
1364
1451
  return [];
@@ -1371,9 +1458,13 @@ export class GraphProcessor {
1371
1458
  this.#emitTraceEvent(`Node ${node.title} is excluded due to control flow`);
1372
1459
  return loopExclusion === true ? [] : loopExclusion;
1373
1460
  }
1374
- const waitingForInputNode = getWaitingForInputNode(this.#executionState, node, inputNodes, inputValues);
1461
+ const streamedInputs = this.#callerInputStreams.get(node.id);
1462
+ const blockingInputNodes = streamedInputs
1463
+ ? inputNodes.filter((inputNode) => this.#getInputConnectionsForNode(node).some((edge) => edge.outputNodeId === inputNode.id && !streamedInputs[edge.inputId]))
1464
+ : inputNodes;
1465
+ const waitingForInputNode = getWaitingForInputNode(this.#executionState, node, blockingInputNodes, inputValues);
1375
1466
  if (waitingForInputNode) {
1376
- this.#emitTraceEvent(`Node ${node.title} is waiting for input node ${waitingForInputNode}`);
1467
+ this.#emitTraceEvent(`Node ${node.title} is waiting for input node ${waitingForInputNode.title || waitingForInputNode.id}`);
1377
1468
  return [];
1378
1469
  }
1379
1470
  const exclusion = this.#excludedDueToControlFlow(node, inputValues, nanoid(), undefined, {
@@ -1840,9 +1931,7 @@ export class GraphProcessor {
1840
1931
  const stopClaim = event === 'nodeFinish'
1841
1932
  ? this.#claimStreamingWatchStopFromInvocation(node, data.outputs)
1842
1933
  : undefined;
1843
- const eventData = event === 'nodeFinish' && stopClaim
1844
- ? { ...data, streamingWatchTerminal: true }
1845
- : data;
1934
+ const eventData = event === 'nodeFinish' && stopClaim ? { ...data, streamingWatchTerminal: true } : data;
1846
1935
  return this.#emitter.emit(event, this.#withExecution(eventData)).then(() => stopClaim?.commit());
1847
1936
  },
1848
1937
  startNodeTiming: this.#captureNodeTimings ? () => this.#startNodeTiming() : undefined,
@@ -1929,6 +2018,8 @@ export class GraphProcessor {
1929
2018
  }
1930
2019
  async #nodeErrored(node, e, processId, durationMs, splitRunDurationMs, resultOrigin = 'executed', outputs, splitOutputs) {
1931
2020
  const error = getError(e);
2021
+ for (const route of this.#inputStreamRoutes.get(node.id) ?? [])
2022
+ route.relay.finish({ error });
1932
2023
  // Most callers are ordinary (non-split) node executions. Let those retain
1933
2024
  // any checkpoint without requiring every error path to know about the
1934
2025
  // internal map. Split callers provide their per-index map explicitly.
@@ -2155,12 +2246,22 @@ export class GraphProcessor {
2155
2246
  }
2156
2247
  #createNodeProcessContext(node, inputValues, index, processId, nodeAbortController, partialOutput, toolCallTraceSource, markResultAsEditorCacheHit) {
2157
2248
  const plugin = this.#registry.getPluginFor(node.type);
2158
- const onGraphOutputPartial = isNamedGraphBoundaryCaller(node) &&
2249
+ const acceptsPartialOutputs = () => {
2250
+ if (nodeAbortController.signal.aborted)
2251
+ return false;
2252
+ const active = this.#nodeAbortControllers.get(node.id);
2253
+ return active === nodeAbortController || (active instanceof Set && active.has(nodeAbortController));
2254
+ };
2255
+ const onGraphOutputPartial = canStreamThroughGraphCaller(node) &&
2159
2256
  (this.#streamingWatchPlansBySourceNodeId.has(node.id) ||
2257
+ this.#inputStreamRoutes.has(node.id) ||
2160
2258
  this.#graphOutputPartialBindingsBySourceNodeId.has(node.id))
2161
2259
  ? (partialOutputs) => {
2260
+ if (!acceptsPartialOutputs())
2261
+ return;
2162
2262
  this.#publishStreamingOutputWatchPartial(node, partialOutputs);
2163
2263
  this.#publishGraphOutputPartial(node, partialOutputs);
2264
+ this.#publishGraphInputStreamPartial(node, partialOutputs);
2164
2265
  }
2165
2266
  : undefined;
2166
2267
  const toolCallContinuation = this.#getToolCallContinuationContext(node, nodeAbortController.signal, processId, index);
@@ -2177,9 +2278,13 @@ export class GraphProcessor {
2177
2278
  node,
2178
2279
  nodeAbortController,
2179
2280
  onGraphOutputPartial,
2281
+ graphInputStreams: this.#callerInputStreams.get(node.id),
2180
2282
  onPartialOutputs: (partialOutputs) => {
2283
+ if (!acceptsPartialOutputs())
2284
+ return;
2181
2285
  partialOutput?.(node, partialOutputs, index);
2182
2286
  this.#publishStreamingOutputWatchPartial(node, partialOutputs);
2287
+ this.#publishGraphInputStreamPartial(node, partialOutputs);
2183
2288
  this.#publishGraphOutputPartial(node, partialOutputs);
2184
2289
  this.#emitGraphPartialOutputIfNeeded(node, partialOutputs);
2185
2290
  },
@@ -2743,7 +2848,7 @@ export class GraphProcessor {
2743
2848
  }
2744
2849
  }
2745
2850
  }
2746
- #publishStreamingOutputWatchPartial(node, partialOutputs) {
2851
+ #publishStreamingOutputWatchPartial(node, partialOutputs, coalesced = 0) {
2747
2852
  for (const plan of this.#streamingWatchPlansBySourceNodeId.get(node.id) ?? []) {
2748
2853
  const value = partialOutputs[plan.sourceOutputId];
2749
2854
  if (value == null || value.type === 'control-flow-excluded') {
@@ -2753,10 +2858,123 @@ export class GraphProcessor {
2753
2858
  if (!watch || watch.stopped) {
2754
2859
  continue;
2755
2860
  }
2861
+ watch.accountCoalescedUpdates(coalesced);
2862
+ plan.nextUpdateIndex += coalesced;
2756
2863
  const updateIndex = this.#nextStreamingWatchUpdateIndex(plan);
2757
2864
  watch.publish(this.#createStreamingOutputWatchSnapshot(plan, value, updateIndex, false));
2758
2865
  }
2759
2866
  }
2867
+ #prepareGraphInputStreamRoutes() {
2868
+ if (!this.#executionGraphNodes.some((node) => canStreamThroughGraphCaller(node) && this.#isNodeSelected(node.id)))
2869
+ return;
2870
+ const marked = getProjectStreamingOutputWatchConnections({
2871
+ project: this.#project,
2872
+ graph: this.#graph,
2873
+ referencedProjects: this.#loadedProjects,
2874
+ registry: this.#registry,
2875
+ fullGraphCallers: new Set(this.runToNodeIds ?? []),
2876
+ isNodeFrozen: (_owner, candidate, node) => this.#frozenNodeOutputResolver != null &&
2877
+ this.#frozenNodeOutputResolver.hasFrozenNodeOutput?.({ graphId: candidate.metadata.id, node }) !== false,
2878
+ });
2879
+ const inputKeys = new Map();
2880
+ for (const edge of marked) {
2881
+ const ports = inputKeys.get(edge.inputNodeId) ?? new Set();
2882
+ ports.add(edge.inputId);
2883
+ inputKeys.set(edge.inputNodeId, ports);
2884
+ }
2885
+ for (const node of this.#executionGraphNodes) {
2886
+ if (!this.#isNodeSelected(node.id) ||
2887
+ !canStreamThroughGraphCaller(node) ||
2888
+ this.#hasFrozenNodeOutputOrUnknownResolver(node))
2889
+ continue;
2890
+ const streams = Object.create(null);
2891
+ const incoming = this.#getInputConnectionsForNode(node).filter((edge) => this.#isDefinitionValidConnection(edge));
2892
+ for (const edge of incoming) {
2893
+ const source = this.#nodesById[edge.outputNodeId];
2894
+ if (!inputKeys.get(node.id)?.has(edge.inputId) ||
2895
+ !source ||
2896
+ source.disabled ||
2897
+ source.isSplitRun ||
2898
+ incoming.filter((other) => other.inputId === edge.inputId).length !== 1)
2899
+ continue;
2900
+ const relay = new GraphInputStreamRelay();
2901
+ streams[edge.inputId] = relay;
2902
+ const routes = this.#inputStreamRoutes.get(source.id) ?? [];
2903
+ routes.push({ port: edge.outputId, relay });
2904
+ this.#inputStreamRoutes.set(source.id, routes);
2905
+ }
2906
+ if (Object.keys(streams).length)
2907
+ this.#callerInputStreams.set(node.id, streams);
2908
+ }
2909
+ const abort = () => {
2910
+ const error = createGraphAbortErrorFromSignal(this.#abortController.signal);
2911
+ for (const streams of this.#callerInputStreams.values()) {
2912
+ for (const relay of Object.values(streams))
2913
+ relay.finish({ error });
2914
+ }
2915
+ };
2916
+ this.#abortController.signal.addEventListener('abort', abort, { once: true });
2917
+ this.#inputStreamDisposers.push(() => this.#abortController.signal.removeEventListener('abort', abort));
2918
+ }
2919
+ #publishGraphInputStreamPartial(node, outputs, coalesced = 0) {
2920
+ for (const { port, relay } of this.#inputStreamRoutes.get(node.id) ?? []) {
2921
+ const value = outputs[port];
2922
+ if (value && value.type !== 'control-flow-excluded')
2923
+ relay.publish(value, coalesced);
2924
+ }
2925
+ }
2926
+ #subscribeGraphInputStreams() {
2927
+ for (const [name, stream] of Object.entries(this.#graphInputStreams)) {
2928
+ const inputs = this.#executionGraphNodes.filter((node) => node.type === 'graphInput' &&
2929
+ node.data.id === name &&
2930
+ !node.disabled &&
2931
+ this.#isNodeSelected(node.id));
2932
+ let active = true;
2933
+ const unsubscribe = stream.subscribe((value, coalesced) => {
2934
+ if (!active || this.#abortController.signal.aborted)
2935
+ return;
2936
+ for (const node of inputs) {
2937
+ if (!canStreamThroughGraphInput(node) || this.#hasFrozenNodeOutputOrUnknownResolver(node))
2938
+ continue;
2939
+ const output = {
2940
+ ['data']: resolveGraphInputValue(node.data, value),
2941
+ };
2942
+ this.#publishStreamingOutputWatchPartial(node, output, coalesced);
2943
+ this.#publishGraphInputStreamPartial(node, output, coalesced);
2944
+ }
2945
+ });
2946
+ this.#inputStreamDisposers.push(() => {
2947
+ active = false;
2948
+ unsubscribe();
2949
+ });
2950
+ void stream.settled.then((result) => {
2951
+ if (!active || this.#abortController.signal.aborted)
2952
+ return;
2953
+ if (result.value)
2954
+ this.#graphInputs[name] = result.value;
2955
+ for (const node of inputs)
2956
+ void this.#processingQueue.add(() => this.#processNodeIfAllInputsAvailable(node));
2957
+ });
2958
+ }
2959
+ }
2960
+ async #waitForGraphInputStreams() {
2961
+ const signal = this.#abortController.signal;
2962
+ if (signal.aborted)
2963
+ throw createGraphAbortErrorFromSignal(signal);
2964
+ let abort;
2965
+ try {
2966
+ await Promise.race([
2967
+ Promise.all(Object.values(this.#graphInputStreams).map((stream) => stream.settled)),
2968
+ new Promise((_resolve, reject) => {
2969
+ abort = () => reject(createGraphAbortErrorFromSignal(signal));
2970
+ signal.addEventListener('abort', abort, { once: true });
2971
+ }),
2972
+ ]);
2973
+ }
2974
+ finally {
2975
+ signal.removeEventListener('abort', abort);
2976
+ }
2977
+ }
2760
2978
  #prepareGraphOutputPartialTopology() {
2761
2979
  if (!this.#graphOutputPartialListener) {
2762
2980
  return;
@@ -2849,6 +3067,29 @@ export class GraphProcessor {
2849
3067
  }
2850
3068
  }
2851
3069
  #finishStreamingOutputWatches(node, outputs) {
3070
+ if (node.type === 'graphInput') {
3071
+ const terminals = Object.values(this.#graphInputStreams).map((stream) => stream.result);
3072
+ if (terminals.some((result) => !result)) {
3073
+ // Defaults/non-streamed arguments may be needed for caller startup, but
3074
+ // their final Watch delivery must not release ordinary nested work early.
3075
+ this.#pendingGraphInputFinals.set(node.id, cloneExecutionOutputs(outputs));
3076
+ return;
3077
+ }
3078
+ const failure = terminals.find((result) => result?.error);
3079
+ if (failure?.error) {
3080
+ for (const route of this.#inputStreamRoutes.get(node.id) ?? [])
3081
+ route.relay.finish({ error: failure.error });
3082
+ this.#cancelStreamingOutputWatchesForSource(node.id);
3083
+ return;
3084
+ }
3085
+ if (terminals.some((result) => result?.value?.type === 'control-flow-excluded')) {
3086
+ outputs = Object.fromEntries(Object.keys(outputs).map((port) => [port, { type: 'control-flow-excluded', value: undefined }]));
3087
+ }
3088
+ }
3089
+ for (const { port, relay } of this.#inputStreamRoutes.get(node.id) ?? []) {
3090
+ const value = outputs[port];
3091
+ relay.finish(value ? { value } : { error: new Error(`Missing final streamed output ${port}`) });
3092
+ }
2852
3093
  for (const plan of this.#streamingWatchPlansBySourceNodeId.get(node.id) ?? []) {
2853
3094
  const value = outputs[plan.sourceOutputId];
2854
3095
  const watch = this.#streamingOutputWatches.get(plan.watchNode.id);
@@ -96,7 +96,7 @@ export function getMissingRequiredInputs(state, node) {
96
96
  });
97
97
  }
98
98
  export function getWaitingForInputNode(state, node, inputNodes, inputValues) {
99
- let waitingForInputNode = false;
99
+ let waitingForInputNode;
100
100
  const anyInputIsValid = Object.values(inputValues).some((value) => value && !isControlFlowExcluded(value));
101
101
  for (const inputNode of inputNodes) {
102
102
  if (node.type === 'loopController' &&
@@ -105,11 +105,11 @@ export function getWaitingForInputNode(state, node, inputNodes, inputValues) {
105
105
  continue;
106
106
  }
107
107
  if (node.type === 'raceInputs' && state.visitedNodes.has(inputNode.id) && anyInputIsValid) {
108
- waitingForInputNode = false;
108
+ waitingForInputNode = undefined;
109
109
  break;
110
110
  }
111
- if (waitingForInputNode === false && state.visitedNodes.has(inputNode.id) === false) {
112
- waitingForInputNode = inputNode.title;
111
+ if (waitingForInputNode === undefined && state.visitedNodes.has(inputNode.id) === false) {
112
+ waitingForInputNode = inputNode;
113
113
  }
114
114
  }
115
115
  return waitingForInputNode;
@@ -64,6 +64,8 @@ import { contextNode } from './nodes/ContextNode.js';
64
64
  export * from './nodes/ContextNode.js';
65
65
  import { graphCallPathNode } from './nodes/GraphCallPathNode.js';
66
66
  export * from './nodes/GraphCallPathNode.js';
67
+ import { projectNameNode } from './nodes/ProjectNameNode.js';
68
+ export * from './nodes/ProjectNameNode.js';
67
69
  import { coalesceNode } from './nodes/CoalesceNode.js';
68
70
  export * from './nodes/CoalesceNode.js';
69
71
  import { coalesceNewNode } from './nodes/CoalesceNewNode.js';
@@ -250,6 +252,7 @@ export const registerBuiltInNodes = (registry) => {
250
252
  .register(reportProgressNode)
251
253
  .register(contextNode)
252
254
  .register(graphCallPathNode)
255
+ .register(projectNameNode)
253
256
  .register(coalesceNode)
254
257
  .register(coalesceNewNode)
255
258
  .register(didRunNode)
@@ -1,5 +1,5 @@
1
1
  export function buildNodeProcessContext(options) {
2
- const { attachedData, activeOutputPortIds, acceptStreamingWatchStop, base, createSubProcessor, execution, externalFunctions, getPluginConfig, isDirectRunTarget, markResultAsEditorCacheHit, node, nodeAbortController, onGraphOutputPartial, onPartialOutputs, setFailureOutputs, processId, requestUserInput, reportProgress, setGlobal, splitIndex, toolCallContinuation, toolCallTraceSource, waitEvent, } = options;
2
+ const { attachedData, activeOutputPortIds, acceptStreamingWatchStop, base, createSubProcessor, execution, externalFunctions, getPluginConfig, isDirectRunTarget, markResultAsEditorCacheHit, node, nodeAbortController, onGraphOutputPartial, graphInputStreams, onPartialOutputs, setFailureOutputs, processId, requestUserInput, reportProgress, setGlobal, splitIndex, toolCallContinuation, toolCallTraceSource, waitEvent, } = options;
3
3
  return {
4
4
  ...base,
5
5
  node,
@@ -13,6 +13,7 @@ export function buildNodeProcessContext(options) {
13
13
  waitForStoredValue: (key, signal = nodeAbortController.signal) => base.waitForStoredValue(key, signal),
14
14
  externalFunctions: { ...externalFunctions },
15
15
  onGraphOutputPartial,
16
+ graphInputStreams,
16
17
  onPartialOutputs,
17
18
  setFailureOutputs,
18
19
  signal: nodeAbortController.signal,
@@ -57,6 +57,11 @@ export class StreamingOutputWatch {
57
57
  this.#run = run;
58
58
  this.#onFailure = onFailure;
59
59
  }
60
+ /** Updates superseded before the receiving graph could start. */
61
+ accountCoalescedUpdates(count) {
62
+ this.#receivedUpdates += count;
63
+ this.#coalescedUpdates += count;
64
+ }
60
65
  get hasPending() {
61
66
  // Stop prevents new delivery, but accepted and failing invocations still
62
67
  // belong to the root lifecycle until they settle. Hiding those active runs