@valerypopoff/rivet2-core 2.15.0 → 2.17.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 (111) hide show
  1. package/dist/cjs/bundle.cjs +4350 -2077
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/interpolationRuntime.cjs +22 -3
  4. package/dist/cjs/interpolationRuntime.cjs.map +3 -3
  5. package/dist/cjs/interpolationSyntax.cjs +9 -5
  6. package/dist/cjs/interpolationSyntax.cjs.map +2 -2
  7. package/dist/esm/api/createProcessor.js +5 -2
  8. package/dist/esm/exports.js +2 -0
  9. package/dist/esm/model/GraphBoundaryCache.js +2 -1
  10. package/dist/esm/model/GraphProcessor.js +268 -6
  11. package/dist/esm/model/Nodes.js +10 -0
  12. package/dist/esm/model/ProjectBundle.js +235 -0
  13. package/dist/esm/model/SplitRunProcessor.js +28 -7
  14. package/dist/esm/model/StreamingWatchTopology.js +118 -8
  15. package/dist/esm/model/SubgraphProjectTarget.js +7 -0
  16. package/dist/esm/model/chat-v2/aiSdkBridge.js +7 -5
  17. package/dist/esm/model/chat-v2/chatV2Pipeline.js +13 -8
  18. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +19 -1
  19. package/dist/esm/model/chat-v2/chatV2Shared.js +2 -1
  20. package/dist/esm/model/chat-v2/llmChatV2Body.js +11 -8
  21. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +2 -0
  22. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +15 -1
  23. package/dist/esm/model/chat-v2/llmChatV2NodeMigration.js +22 -2
  24. package/dist/esm/model/chat-v2/llmProfile.js +3 -0
  25. package/dist/esm/model/chat-v2/llmProfileBody.js +2 -2
  26. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +1 -1
  27. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +1 -1
  28. package/dist/esm/model/chat-v2/temperature.js +9 -0
  29. package/dist/esm/model/classifier/credentials.js +30 -4
  30. package/dist/esm/model/classifier/images.js +176 -0
  31. package/dist/esm/model/classifier/json.js +57 -0
  32. package/dist/esm/model/classifier/limits.js +270 -0
  33. package/dist/esm/model/classifier/openai.js +118 -0
  34. package/dist/esm/model/classifier/preparation.js +74 -0
  35. package/dist/esm/model/classifier/providers.js +260 -185
  36. package/dist/esm/model/classifier/questionHelpers.js +29 -45
  37. package/dist/esm/model/classifier/questions.js +53 -0
  38. package/dist/esm/model/classifier/response.js +75 -0
  39. package/dist/esm/model/classifier/state.js +204 -0
  40. package/dist/esm/model/nodeRunFailure.js +47 -0
  41. package/dist/esm/model/nodes/CatchStreamingChunksNode.js +42 -0
  42. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +178 -138
  43. package/dist/esm/model/nodes/ClassifierQuestionNode.js +59 -15
  44. package/dist/esm/model/nodes/GetGlobalNode.js +2 -2
  45. package/dist/esm/model/nodes/HttpCallNode.js +44 -75
  46. package/dist/esm/model/nodes/ImageNode.js +44 -3
  47. package/dist/esm/model/nodes/LLMChatV2Node.js +24 -3
  48. package/dist/esm/model/nodes/ObjectNode.js +29 -18
  49. package/dist/esm/model/nodes/PromptNode.js +2 -1
  50. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +4 -1
  51. package/dist/esm/model/nodes/SetGlobalNode.js +5 -3
  52. package/dist/esm/model/nodes/StopWatchingStreamingOutputNode.js +8 -8
  53. package/dist/esm/model/nodes/StreamValueNode.js +38 -0
  54. package/dist/esm/model/nodes/SubGraphNode.js +196 -35
  55. package/dist/esm/model/nodes/ToBase64Node.js +106 -0
  56. package/dist/esm/model/nodes/WatchStreamingOutputNode.js +7 -7
  57. package/dist/esm/recording/ExecutionRecorder.js +26 -0
  58. package/dist/esm/utils/base64.js +18 -15
  59. package/dist/esm/utils/errors.js +41 -0
  60. package/dist/esm/utils/interpolation.js +44 -22
  61. package/dist/esm/utils/interpolationSyntax.js +15 -6
  62. package/dist/esm/utils/serialization/serialization.js +3 -2
  63. package/dist/esm/utils/serialization/serializationUtils.js +6 -0
  64. package/dist/esm/utils/serialization/serialization_v4.js +15 -3
  65. package/dist/types/api/createProcessor.d.ts +7 -1
  66. package/dist/types/exports.d.ts +2 -0
  67. package/dist/types/model/CycleDetector.d.ts +1 -2
  68. package/dist/types/model/ExecutorProtocol.d.ts +2 -0
  69. package/dist/types/model/GraphBoundaryCache.d.ts +2 -0
  70. package/dist/types/model/GraphProcessor.d.ts +1 -0
  71. package/dist/types/model/Nodes.d.ts +6 -2
  72. package/dist/types/model/ProcessContext.d.ts +12 -0
  73. package/dist/types/model/ProjectBundle.d.ts +54 -0
  74. package/dist/types/model/ProjectReferenceLoader.d.ts +3 -0
  75. package/dist/types/model/StreamingWatchTopology.d.ts +11 -1
  76. package/dist/types/model/SubgraphProjectTarget.d.ts +38 -0
  77. package/dist/types/model/chat-v2/chatV2Shared.d.ts +1 -1
  78. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +3 -1
  79. package/dist/types/model/chat-v2/llmChatV2NodeMigration.d.ts +3 -1
  80. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +6 -6
  81. package/dist/types/model/chat-v2/temperature.d.ts +2 -0
  82. package/dist/types/model/classifier/credentials.d.ts +3 -1
  83. package/dist/types/model/classifier/images.d.ts +18 -0
  84. package/dist/types/model/classifier/json.d.ts +19 -0
  85. package/dist/types/model/classifier/limits.d.ts +42 -0
  86. package/dist/types/model/classifier/openai.d.ts +5 -0
  87. package/dist/types/model/classifier/preparation.d.ts +16 -0
  88. package/dist/types/model/classifier/providers.d.ts +67 -9
  89. package/dist/types/model/classifier/questionHelpers.d.ts +6 -4
  90. package/dist/types/model/classifier/questions.d.ts +4 -0
  91. package/dist/types/model/classifier/response.d.ts +4 -0
  92. package/dist/types/model/classifier/state.d.ts +37 -0
  93. package/dist/types/model/classifier/types.d.ts +2 -0
  94. package/dist/types/model/nodeRunFailure.d.ts +13 -0
  95. package/dist/types/model/nodes/CatchStreamingChunksNode.d.ts +20 -0
  96. package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +3 -0
  97. package/dist/types/model/nodes/GetGlobalNode.d.ts +7 -0
  98. package/dist/types/model/nodes/ImageNode.d.ts +4 -0
  99. package/dist/types/model/nodes/LLMChatV2Node.d.ts +1 -0
  100. package/dist/types/model/nodes/ObjectNode.d.ts +2 -1
  101. package/dist/types/model/nodes/StreamValueNode.d.ts +14 -0
  102. package/dist/types/model/nodes/SubGraphNode.d.ts +21 -2
  103. package/dist/types/model/nodes/ToBase64Node.d.ts +12 -0
  104. package/dist/types/recording/ExecutionRecorder.d.ts +8 -2
  105. package/dist/types/utils/base64.d.ts +1 -1
  106. package/dist/types/utils/errors.d.ts +4 -0
  107. package/dist/types/utils/interpolation.d.ts +13 -2
  108. package/dist/types/utils/interpolationSyntax.d.ts +1 -1
  109. package/dist/types/utils/serialization/serialization.d.ts +3 -1
  110. package/dist/types/utils/serialization/serializationUtils.d.ts +1 -0
  111. package/package.json +1 -1
@@ -42,6 +42,9 @@ import { resolveNodePrefabInstance } from './NodePrefabResolver.js';
42
42
  import { ConnectedToolContinuationHost, } from './ConnectedToolContinuationHost.js';
43
43
  import { resolveProjectGlobalVariables } from './GlobalVariables.js';
44
44
  import { loadProjectReferenceTree } from './ProjectReferenceLoader.js';
45
+ import { getSubgraphProjectKey, isSubgraphProjectKey, } from './SubgraphProjectTarget.js';
46
+ import { MAX_CAUGHT_STREAMING_CHUNKS } from './nodes/CatchStreamingChunksNode.js';
47
+ import { isEqual } from 'lodash-es';
45
48
  // eslint-disable-next-line import/no-cycle -- There has to be a cycle because CodeRunner needs to import the entirety of Rivet
46
49
  import { IsomorphicCodeRunner } from '../integrations/CodeRunner.js';
47
50
  const graphProcessorGraphOverride = Symbol('graphProcessorGraphOverride');
@@ -109,6 +112,7 @@ const FAST_ACYCLIC_UNSUPPORTED_NODE_TYPES = new Set([
109
112
  'startBackgroundBranch',
110
113
  'watchStreamingOutput',
111
114
  'stopWatchingStreamingOutput',
115
+ 'catchStreamingChunks',
112
116
  'userInput',
113
117
  'waitForEvent',
114
118
  ]);
@@ -160,6 +164,7 @@ export class GraphProcessor {
160
164
  #externalFunctions = {};
161
165
  slowMode = false;
162
166
  #parent;
167
+ #recordingProjectScope;
163
168
  #abortOwnerOverride;
164
169
  #sameGraphRunOwnerOverride;
165
170
  #suppressGraphPartialOutputs = false;
@@ -177,6 +182,8 @@ export class GraphProcessor {
177
182
  #streamingWatchPlansBySourceNodeId = new Map();
178
183
  #streamingWatchPlansByWatchNodeId = new Map();
179
184
  #streamingOutputWatches = new Map();
185
+ #streamingCatchPlansBySourceNodeId = new Map();
186
+ #streamingCatchTasks = new Set();
180
187
  #graphOutputPartialBindingsBySourceNodeId = new Map();
181
188
  #graphOutputPartialListener;
182
189
  #consumedStreamingWatchNodeId;
@@ -249,6 +256,7 @@ export class GraphProcessor {
249
256
  #ignoreNodes = undefined;
250
257
  #hasPreloadedData = false;
251
258
  #loadedProjects = undefined;
259
+ #subgraphTargetCache = new Map();
252
260
  #definitions = undefined;
253
261
  #scc = undefined;
254
262
  #graphExecutionPlan;
@@ -402,6 +410,14 @@ export class GraphProcessor {
402
410
  if (!this.#cacheLoadedProjects && (project.references?.length ?? 0) > 0) {
403
411
  return false;
404
412
  }
413
+ // A target's Saved latest or Published pointer can change while the caller
414
+ // graph object remains identical. Its boundary definitions must be rebuilt.
415
+ if (Object.values(project.graphs).some((graph) => graph.nodes.some((authored) => {
416
+ const node = resolveNodePrefabInstance(project, authored);
417
+ return node.type === 'subGraph' && node.data.targetProjectId;
418
+ }))) {
419
+ return false;
420
+ }
405
421
  return true;
406
422
  }
407
423
  #getGraphBoundary(project, graphId) {
@@ -426,7 +442,9 @@ export class GraphProcessor {
426
442
  this.#graphExecutionPlan = isGraphExecutionPlan(preprocessedGraph) ? preprocessedGraph : undefined;
427
443
  }
428
444
  #seededExecutionPlanForNextRun() {
429
- if (!this.#useSeededExecutionPlanOnNextRun || this.warnOnInvalidGraph) {
445
+ if (!this.#useSeededExecutionPlanOnNextRun ||
446
+ this.warnOnInvalidGraph ||
447
+ !this.#canUseRuntimeExecutionPlanCacheFor(this.#project, this.#isSubProcessor)) {
430
448
  return undefined;
431
449
  }
432
450
  return this.#graphExecutionPlan;
@@ -448,6 +466,7 @@ export class GraphProcessor {
448
466
  rootRunId: this.#rootRunId,
449
467
  graphRunId: this.#graphRunId,
450
468
  graphId: this.#graph.metadata.id,
469
+ ...(this.#recordingProjectScope ? { projectScope: this.#recordingProjectScope } : {}),
451
470
  parentGraphRunId: this.#parentGraphRunId,
452
471
  executor: this.#executor
453
472
  ? {
@@ -460,6 +479,9 @@ export class GraphProcessor {
460
479
  ...(this.#context?.evaluation === undefined ? {} : { evaluation: this.#context.evaluation }),
461
480
  };
462
481
  }
482
+ get recordingProjectScope() {
483
+ return this.#recordingProjectScope;
484
+ }
463
485
  #withExecution(data, execution = this.#buildExecutionMetadata()) {
464
486
  return {
465
487
  ...data,
@@ -710,6 +732,8 @@ export class GraphProcessor {
710
732
  this.#streamingWatchPlansBySourceNodeId = new Map();
711
733
  this.#streamingWatchPlansByWatchNodeId = new Map();
712
734
  this.#streamingOutputWatches = new Map();
735
+ this.#streamingCatchPlansBySourceNodeId = new Map();
736
+ this.#streamingCatchTasks = new Set();
713
737
  this.#graphOutputPartialBindingsBySourceNodeId = new Map();
714
738
  this.#loopControllersSeen = new Set();
715
739
  this.#subprocessors = new Set();
@@ -734,6 +758,10 @@ export class GraphProcessor {
734
758
  this.#nodeAbortControllers = new Map();
735
759
  this.#loadedProjects =
736
760
  this.#cacheLoadedProjects && this.#runtimeCache?.loadedProjects ? { ...this.#runtimeCache.loadedProjects } : {};
761
+ if (!this.#isSubProcessor) {
762
+ // Latest and Published are selected afresh for each root invocation.
763
+ this.#subgraphTargetCache = new Map();
764
+ }
737
765
  // Referenced projects can be reloaded per run when loaded-project caching is disabled.
738
766
  if (!this.#cacheLoadedProjects && (this.#project.references?.length ?? 0) > 0) {
739
767
  if (this.#runtimeCache) {
@@ -797,6 +825,7 @@ export class GraphProcessor {
797
825
  }
798
826
  this.#prepareAsyncBranchTopology();
799
827
  this.#prepareStreamingWatchTopology();
828
+ this.#prepareStreamingCatchTopology();
800
829
  this.#prepareGraphOutputPartialTopology();
801
830
  this.#prepareGraphInputStreamRoutes();
802
831
  }
@@ -890,7 +919,8 @@ export class GraphProcessor {
890
919
  return;
891
920
  // Resolve before touching the shared map. An invalid reference or definition
892
921
  // must fail startup without leaving a partial new set of authored globals.
893
- const resolved = resolveProjectGlobalVariables(this.#project, this.#loadedProjects);
922
+ const legacyProjects = Object.fromEntries(Object.entries(this.#loadedProjects).filter(([key]) => !isSubgraphProjectKey(key)));
923
+ const resolved = resolveProjectGlobalVariables(this.#project, legacyProjects);
894
924
  for (const id of this.#projectGlobalVariableIdsAssignedByPreviousRootRun) {
895
925
  this.#globals.delete(id);
896
926
  }
@@ -1136,6 +1166,7 @@ export class GraphProcessor {
1136
1166
  await Promise.race(this.#streamCallerTasks);
1137
1167
  await this.#processingQueue.onIdle();
1138
1168
  }
1169
+ await this.#drainStreamingCatchTasks();
1139
1170
  this.#markUnqueuedNodesIgnored();
1140
1171
  }
1141
1172
  #canUseFastAcyclicScheduler() {
@@ -1314,6 +1345,7 @@ export class GraphProcessor {
1314
1345
  if ((this.#project.references?.length ?? 0) > 0) {
1315
1346
  if (this.#cacheLoadedProjects && this.#runtimeCache?.loadedProjects) {
1316
1347
  this.#loadedProjects = { ...this.#runtimeCache.loadedProjects };
1348
+ await this.#loadSubgraphProjectTargets();
1317
1349
  return;
1318
1350
  }
1319
1351
  if (!this.#context.projectReferenceLoader) {
@@ -1324,6 +1356,88 @@ export class GraphProcessor {
1324
1356
  this.#runtimeCache.loadedProjects = { ...this.#loadedProjects };
1325
1357
  }
1326
1358
  }
1359
+ await this.#loadSubgraphProjectTargets();
1360
+ }
1361
+ async #loadSubgraphProjectTargets() {
1362
+ const visited = new WeakMap();
1363
+ const active = new WeakMap();
1364
+ const visit = async (owner, graphId, depth, enteredFromOtherProject = false) => {
1365
+ if (depth > 64)
1366
+ throw new Error('Subgraph project dependency depth exceeds 64. Check for a project cycle.');
1367
+ const graph = owner.graphs[graphId];
1368
+ if (!graph)
1369
+ throw new Error(`Subgraph target graph ${graphId} is missing from project ${owner.metadata.id}.`);
1370
+ if (active.get(owner)?.has(graphId)) {
1371
+ if (enteredFromOtherProject)
1372
+ throw new Error(`Subgraph project dependency cycle reaches graph ${graphId} in project ${owner.metadata.id}.`);
1373
+ return;
1374
+ }
1375
+ const visitedGraphs = visited.get(owner) ?? new Set();
1376
+ if (visitedGraphs.has(graphId))
1377
+ return;
1378
+ visitedGraphs.add(graphId);
1379
+ visited.set(owner, visitedGraphs);
1380
+ const activeGraphs = active.get(owner) ?? new Set();
1381
+ activeGraphs.add(graphId);
1382
+ active.set(owner, activeGraphs);
1383
+ try {
1384
+ for (const authored of graph.nodes) {
1385
+ const candidate = resolveNodePrefabInstance(owner, authored);
1386
+ if (candidate.type !== 'subGraph' || candidate.disabled)
1387
+ continue;
1388
+ const node = candidate;
1389
+ if (node.data.targetScope === 'other-projects' && !node.data.targetProjectId) {
1390
+ throw new Error('Select a project and graph for this Subgraph before running it.');
1391
+ }
1392
+ let childOwner = owner;
1393
+ if (node.data.targetProjectId) {
1394
+ const target = {
1395
+ projectId: node.data.targetProjectId,
1396
+ version: node.data.targetVersion ?? 'latest',
1397
+ };
1398
+ const key = getSubgraphProjectKey(target);
1399
+ let resolved = this.#subgraphTargetCache.get(key);
1400
+ if (!resolved) {
1401
+ if (!this.#context.subgraphProjectLoader) {
1402
+ throw new Error('Subgraph calls to another project require a subgraphProjectLoader. Use a project bundle locally or run through Rivet Studio Server.');
1403
+ }
1404
+ resolved = await this.#context.subgraphProjectLoader.loadTarget(target);
1405
+ if (resolved.project.metadata.id !== target.projectId) {
1406
+ throw new Error(`Subgraph target ${target.projectId} resolved to a different project.`);
1407
+ }
1408
+ this.#subgraphTargetCache.set(key, resolved);
1409
+ }
1410
+ childOwner = resolved.project;
1411
+ if (Object.hasOwn(this.#loadedProjects, key) && this.#loadedProjects[key] !== childOwner) {
1412
+ throw new Error('Subgraph target collides with an existing project reference.');
1413
+ }
1414
+ Object.defineProperty(this.#loadedProjects, key, {
1415
+ configurable: true,
1416
+ enumerable: true,
1417
+ value: childOwner,
1418
+ writable: true,
1419
+ });
1420
+ }
1421
+ await visit(childOwner, node.data.graphId, depth + 1, Boolean(node.data.targetProjectId));
1422
+ }
1423
+ }
1424
+ finally {
1425
+ activeGraphs.delete(graphId);
1426
+ }
1427
+ };
1428
+ await visit(this.#project, this.#graph.metadata.id, 0);
1429
+ // Streaming topology may visit any resolved target, including a version of
1430
+ // a project with the same metadata ID as another selected target.
1431
+ for (const [key, resolved] of this.#subgraphTargetCache) {
1432
+ if (!Object.hasOwn(this.#loadedProjects, key)) {
1433
+ Object.defineProperty(this.#loadedProjects, key, {
1434
+ configurable: true,
1435
+ enumerable: true,
1436
+ value: resolved.project,
1437
+ writable: true,
1438
+ });
1439
+ }
1440
+ }
1327
1441
  }
1328
1442
  /** Returns true if any input node has errored. Optionally emits a trace event. */
1329
1443
  #hasErroredInputNode(node, inputNodes, trace = false) {
@@ -1765,6 +1879,8 @@ export class GraphProcessor {
1765
1879
  onProcessorCreated(processor);
1766
1880
  processor.executor = this.executor;
1767
1881
  processor.#isSubProcessor = true;
1882
+ processor.#subgraphTargetCache = this.#subgraphTargetCache;
1883
+ processor.#recordingProjectScope = this.#recordingProjectScope;
1768
1884
  processor.#executionCache = this.#executionCache;
1769
1885
  processor.#externalFunctions = this.#externalFunctions;
1770
1886
  processor.#contextValues = this.#contextValues;
@@ -2031,6 +2147,7 @@ export class GraphProcessor {
2031
2147
  return;
2032
2148
  }
2033
2149
  this.#cancelStreamingOutputWatchesForSource(node.id);
2150
+ this.#cancelStreamingCatchesForSource(node.id);
2034
2151
  this.#erroredNodes.set(node.id, error);
2035
2152
  await this.#emitter.emit('nodeError', this.#withExecution(withOptionalDuration({
2036
2153
  node,
@@ -2254,6 +2371,7 @@ export class GraphProcessor {
2254
2371
  };
2255
2372
  const onGraphOutputPartial = canForwardGraphCallerOutputPartials(node) &&
2256
2373
  (this.#streamingWatchPlansBySourceNodeId.has(node.id) ||
2374
+ this.#streamingCatchPlansBySourceNodeId.has(node.id) ||
2257
2375
  this.#inputStreamRoutes.has(node.id) ||
2258
2376
  this.#graphOutputPartialBindingsBySourceNodeId.has(node.id))
2259
2377
  ? (partialOutputs) => {
@@ -2265,7 +2383,7 @@ export class GraphProcessor {
2265
2383
  }
2266
2384
  : undefined;
2267
2385
  const toolCallContinuation = this.#getToolCallContinuationContext(node, nodeAbortController.signal, processId, index);
2268
- return buildNodeProcessContext({
2386
+ const processContext = buildNodeProcessContext({
2269
2387
  activeOutputPortIds: this.#getActiveOutputPortIds(node),
2270
2388
  attachedData: this.#getAttachedDataTo(node),
2271
2389
  base: this.#nodeProcessContextBase,
@@ -2336,6 +2454,14 @@ export class GraphProcessor {
2336
2454
  });
2337
2455
  },
2338
2456
  });
2457
+ if (node.type === 'subGraph' && node.data.targetProjectId) {
2458
+ const data = node.data;
2459
+ processContext.subgraphTarget = this.#subgraphTargetCache.get(getSubgraphProjectKey({
2460
+ projectId: data.targetProjectId,
2461
+ version: data.targetVersion ?? 'latest',
2462
+ }));
2463
+ }
2464
+ return processContext;
2339
2465
  }
2340
2466
  #getToolCallContinuationContext(node, llmSignal, processId, index) {
2341
2467
  if (node.type !== 'llmChatV2') {
@@ -2482,10 +2608,12 @@ export class GraphProcessor {
2482
2608
  });
2483
2609
  processor.executor = this.executor;
2484
2610
  processor.#isSubProcessor = true;
2611
+ processor.#subgraphTargetCache = this.#subgraphTargetCache;
2485
2612
  processor.#executionCache = this.#executionCache;
2486
2613
  processor.#externalFunctions = this.#externalFunctions;
2487
2614
  processor.#contextValues = this.#contextValues;
2488
2615
  processor.#parent = this;
2616
+ processor.#recordingProjectScope = this.#recordingProjectScope;
2489
2617
  processor.#graphCallPath = this.#graphCallPath;
2490
2618
  processor.#abortOwnerOverride = this.#abortOwnerOverride ?? this;
2491
2619
  processor.#sameGraphRunOwnerOverride = this.#sameGraphRunOwnerOverride ?? this;
@@ -2714,6 +2842,10 @@ export class GraphProcessor {
2714
2842
  if (node.type === 'watchStreamingOutput') {
2715
2843
  throw new Error(`Watch Streaming Output "${watchNode.title}" cannot contain another Watch Streaming Output node.`);
2716
2844
  }
2845
+ if (node.type === 'catchStreamingChunks') {
2846
+ throw new Error(`Watch Streaming Output "${watchNode.title}" cannot contain Catch streaming chunks "${node.title}". ` +
2847
+ 'Put Catch streaming chunks outside the repeated Watch branch.');
2848
+ }
2717
2849
  if (node.type === 'graphOutput') {
2718
2850
  throw new Error(`Watch Streaming Output "${watchNode.title}" must reach Stop Watching Streaming Output before Graph Output "${node.title}".`);
2719
2851
  }
@@ -2793,8 +2925,52 @@ export class GraphProcessor {
2793
2925
  }
2794
2926
  this.#assertStreamingOutputWatchPreloadsAreSafe();
2795
2927
  }
2928
+ #prepareStreamingCatchTopology() {
2929
+ const relevantNodeIds = this.#getExecutionRelevantNodeIds();
2930
+ const connections = this.#getEffectiveConnections().filter((connection) => this.#isDefinitionValidConnection(connection));
2931
+ for (const node of this.#executionGraphNodes) {
2932
+ if (node.type !== 'catchStreamingChunks' ||
2933
+ node.disabled ||
2934
+ (relevantNodeIds && !relevantNodeIds.has(node.id)))
2935
+ continue;
2936
+ // A saved Catch result is an ordinary once-only value. Run-from may reuse
2937
+ // it, but a live Catch still needs its own streaming coordinator.
2938
+ if (this.#nodeResults.has(node.id))
2939
+ continue;
2940
+ if (node.isConditional || node.isSplitRun) {
2941
+ throw new Error(`Catch streaming chunks "${node.title}" cannot use Conditional or Many runs.`);
2942
+ }
2943
+ const incoming = connections.filter((connection) => connection.inputNodeId === node.id);
2944
+ if (incoming.length === 0) {
2945
+ this.#ignoreNodes.add(node.id);
2946
+ continue;
2947
+ }
2948
+ if (incoming.length !== 1 || incoming[0].inputId !== 'stream') {
2949
+ throw new Error(`Catch streaming chunks "${node.title}" must have exactly one Streaming Output input connection.`);
2950
+ }
2951
+ const source = this.#nodesById[incoming[0].outputNodeId];
2952
+ if (!source || source.disabled || source.isSplitRun) {
2953
+ throw new Error(`Catch streaming chunks "${node.title}" needs one runnable, non-split streaming source.`);
2954
+ }
2955
+ const rawCount = node.data.count;
2956
+ const count = Number.isFinite(rawCount)
2957
+ ? Math.min(MAX_CAUGHT_STREAMING_CHUNKS, Math.max(1, Math.floor(rawCount)))
2958
+ : 1;
2959
+ const plan = {
2960
+ node: node,
2961
+ sourceOutputId: incoming[0].outputId,
2962
+ count,
2963
+ chunks: [],
2964
+ settled: false,
2965
+ };
2966
+ const plans = this.#streamingCatchPlansBySourceNodeId.get(source.id) ?? [];
2967
+ plans.push(plan);
2968
+ this.#streamingCatchPlansBySourceNodeId.set(source.id, plans);
2969
+ this.#ignoreNodes.add(node.id);
2970
+ }
2971
+ }
2796
2972
  #isStreamingOutputWatchBoundary(node) {
2797
- return node.type === 'watchStreamingOutput' || node.type === 'stopWatchingStreamingOutput';
2973
+ return node.type === 'watchStreamingOutput' || node.type === 'stopWatchingStreamingOutput' || node.type === 'catchStreamingChunks';
2798
2974
  }
2799
2975
  #assertStreamingOutputWatchPreloadCanBeAdded(nodeId) {
2800
2976
  // Before initialization, referenced projects and the effective graph are
@@ -2826,7 +3002,7 @@ export class GraphProcessor {
2826
3002
  if (!node || !this.#isNodeSelected(node.id) || node.id === this.#consumedStreamingWatchNodeId) {
2827
3003
  continue;
2828
3004
  }
2829
- if (this.#isStreamingOutputWatchBoundary(node)) {
3005
+ if (this.#isStreamingOutputWatchBoundary(node) && node.type !== 'catchStreamingChunks') {
2830
3006
  throw new Error(`Cannot preload ${node.title} because a streaming boundary must be scheduled. ` +
2831
3007
  "Run from Watch Streaming Output to reuse a producer's saved final value, or run from the producer to stream again.");
2832
3008
  }
@@ -2849,6 +3025,17 @@ export class GraphProcessor {
2849
3025
  }
2850
3026
  }
2851
3027
  #publishStreamingOutputWatchPartial(node, partialOutputs, coalesced = 0) {
3028
+ for (const plan of this.#streamingCatchPlansBySourceNodeId.get(node.id) ?? []) {
3029
+ if (plan.settled)
3030
+ continue;
3031
+ const value = partialOutputs[plan.sourceOutputId];
3032
+ if (!value || value.type === 'control-flow-excluded')
3033
+ continue;
3034
+ const chunk = cloneExecutionOutputs({ ['value']: value })['value'];
3035
+ plan.chunks.push(chunk);
3036
+ if (plan.chunks.length >= plan.count)
3037
+ this.#scheduleStreamingCatchCompletion(plan);
3038
+ }
2852
3039
  for (const plan of this.#streamingWatchPlansBySourceNodeId.get(node.id) ?? []) {
2853
3040
  const value = partialOutputs[plan.sourceOutputId];
2854
3041
  if (value == null || value.type === 'control-flow-excluded') {
@@ -2864,6 +3051,43 @@ export class GraphProcessor {
2864
3051
  watch.publish(this.#createStreamingOutputWatchSnapshot(plan, value, updateIndex, false));
2865
3052
  }
2866
3053
  }
3054
+ #scheduleStreamingCatchCompletion(plan) {
3055
+ if (plan.settled)
3056
+ return;
3057
+ plan.settled = true;
3058
+ const task = this.#completeStreamingCatch(plan).catch((error) => this.#nodeErrored(plan.node, error, nanoid()));
3059
+ this.#streamingCatchTasks.add(task);
3060
+ void task.then(() => this.#streamingCatchTasks.delete(task), () => this.#streamingCatchTasks.delete(task));
3061
+ }
3062
+ async #completeStreamingCatch(plan) {
3063
+ if (this.#abortController.signal.aborted)
3064
+ return;
3065
+ const node = plan.node;
3066
+ const processId = nanoid();
3067
+ const chunks = plan.chunks.slice(0, plan.count);
3068
+ const output = plan.count === 1
3069
+ ? chunks[0]
3070
+ : { type: 'any[]', value: chunks.map((chunk) => chunk.value) };
3071
+ const outputs = { ['value']: output };
3072
+ plan.chunks.length = 0;
3073
+ await this.#emitter.emit('nodeStart', this.#withExecution({ node, inputs: {}, processId, resultOrigin: 'executed' }));
3074
+ if (this.#abortController.signal.aborted)
3075
+ return;
3076
+ this.#nodeResults.set(node.id, outputs);
3077
+ this.#visitedNodes.add(node.id);
3078
+ this.#remainingNodes.delete(node.id);
3079
+ await this.#emitter.emit('nodeFinish', this.#withExecution({ node, outputs, processId, resultOrigin: 'executed' }));
3080
+ this.#finishStreamingOutputWatches(node, outputs);
3081
+ const outputNodes = getOutputNodesFrom(this.#executionState, node);
3082
+ this.#propagateAttachedDataToOutputNodes(node, this.#getAttachedDataTo(node), outputNodes.connectionsToNodes);
3083
+ this.#queueOutputNodes(node, outputNodes.nodes);
3084
+ }
3085
+ async #drainStreamingCatchTasks() {
3086
+ while (this.#streamingCatchTasks.size > 0) {
3087
+ await Promise.all([...this.#streamingCatchTasks]);
3088
+ await this.#processingQueue.onIdle();
3089
+ }
3090
+ }
2867
3091
  #prepareGraphInputStreamRoutes() {
2868
3092
  if (!this.#executionGraphNodes.some((node) => canStreamThroughGraphCaller(node) && this.#isNodeSelected(node.id)))
2869
3093
  return;
@@ -3074,12 +3298,30 @@ export class GraphProcessor {
3074
3298
  for (const route of this.#inputStreamRoutes.get(node.id) ?? [])
3075
3299
  route.relay.finish({ error: failure.error });
3076
3300
  this.#cancelStreamingOutputWatchesForSource(node.id);
3301
+ this.#cancelStreamingCatchesForSource(node.id);
3077
3302
  return;
3078
3303
  }
3079
3304
  if (terminals.some((result) => result?.value?.type === 'control-flow-excluded')) {
3080
3305
  outputs = Object.fromEntries(Object.keys(outputs).map((port) => [port, { type: 'control-flow-excluded', value: undefined }]));
3081
3306
  }
3082
3307
  }
3308
+ for (const plan of this.#streamingCatchPlansBySourceNodeId.get(node.id) ?? []) {
3309
+ if (plan.settled)
3310
+ continue;
3311
+ const finalValue = outputs[plan.sourceOutputId];
3312
+ if (finalValue &&
3313
+ finalValue.type !== 'control-flow-excluded' &&
3314
+ !isEqual(plan.chunks.at(-1), finalValue)) {
3315
+ plan.chunks.push(cloneExecutionOutputs({ ['value']: finalValue })['value']);
3316
+ }
3317
+ if (plan.chunks.length > 0) {
3318
+ this.#scheduleStreamingCatchCompletion(plan);
3319
+ }
3320
+ else {
3321
+ plan.settled = true;
3322
+ this.#excludeNode(plan.node, nanoid(), {}, 'stream completed without a value');
3323
+ }
3324
+ }
3083
3325
  for (const { port, relay } of this.#inputStreamRoutes.get(node.id) ?? []) {
3084
3326
  const value = outputs[port];
3085
3327
  relay.finish(value ? { value } : { error: new Error(`Missing final streamed output ${port}`) });
@@ -3201,10 +3443,12 @@ export class GraphProcessor {
3201
3443
  });
3202
3444
  processor.executor = this.executor;
3203
3445
  processor.#isSubProcessor = true;
3446
+ processor.#subgraphTargetCache = this.#subgraphTargetCache;
3204
3447
  processor.#executionCache = this.#executionCache;
3205
3448
  processor.#externalFunctions = this.#externalFunctions;
3206
3449
  processor.#contextValues = this.#contextValues;
3207
3450
  processor.#parent = this;
3451
+ processor.#recordingProjectScope = this.#recordingProjectScope;
3208
3452
  processor.#graphCallPath = this.#graphCallPath;
3209
3453
  processor.#abortOwnerOverride = root;
3210
3454
  processor.#suppressGraphPartialOutputs = true;
@@ -3357,6 +3601,14 @@ export class GraphProcessor {
3357
3601
  this.#streamingOutputWatches.get(plan.watchNode.id)?.stop();
3358
3602
  }
3359
3603
  }
3604
+ #cancelStreamingCatchesForSource(nodeId) {
3605
+ for (const plan of this.#streamingCatchPlansBySourceNodeId.get(nodeId) ?? []) {
3606
+ if (plan.settled)
3607
+ continue;
3608
+ plan.settled = true;
3609
+ plan.chunks.length = 0;
3610
+ }
3611
+ }
3360
3612
  #cancelStreamingOutputWatches() {
3361
3613
  for (const watch of this.#streamingOutputWatches.values()) {
3362
3614
  watch.stop();
@@ -3376,12 +3628,14 @@ export class GraphProcessor {
3376
3628
  }
3377
3629
  async #drainSchedulerBoundaries() {
3378
3630
  do {
3631
+ await this.#drainStreamingCatchTasks();
3379
3632
  if (!this.#isSubProcessor) {
3380
3633
  await this.#profileRuntimeAsync('drainManagedAsyncBranches', () => this.#managedAsyncBranches.drain());
3381
3634
  }
3382
3635
  await this.#profileRuntimeAsync('drainStreamingOutputWatches', () => this.#drainStreamingOutputWatches());
3383
3636
  } while ((!this.#isSubProcessor && this.#managedAsyncBranches.hasPending) ||
3384
- this.#hasDrainableStreamingOutputWatches());
3637
+ this.#hasDrainableStreamingOutputWatches() ||
3638
+ this.#streamingCatchTasks.size > 0);
3385
3639
  }
3386
3640
  async #drainStreamingOutputWatches() {
3387
3641
  do {
@@ -3677,10 +3931,18 @@ export class GraphProcessor {
3677
3931
  }
3678
3932
  processor.executor = this.executor;
3679
3933
  processor.#isSubProcessor = true;
3934
+ processor.#subgraphTargetCache = this.#subgraphTargetCache;
3680
3935
  processor.#executionCache = this.#executionCache;
3681
3936
  processor.#externalFunctions = this.#externalFunctions;
3682
3937
  processor.#contextValues = this.#contextValues;
3683
3938
  processor.#parent = this;
3939
+ processor.#recordingProjectScope =
3940
+ node.type === 'subGraph' && node.data.targetProjectId
3941
+ ? getSubgraphProjectKey({
3942
+ projectId: node.data.targetProjectId,
3943
+ version: node.data.targetVersion ?? 'latest',
3944
+ })
3945
+ : this.#recordingProjectScope;
3684
3946
  processor.#graphCallPath = Object.freeze([
3685
3947
  ...this.#graphCallPath,
3686
3948
  processor.#graph.metadata?.name || '(Unnamed Graph)',
@@ -3,6 +3,7 @@ import { userInputNode } from './nodes/UserInputNode.js';
3
3
  export * from './nodes/UserInputNode.js';
4
4
  import { textNode } from './nodes/TextNode.js';
5
5
  export * from './nodes/TextNode.js';
6
+ export { buildNodeBodyPreview } from './nodes/nodeBodyPreview.js';
6
7
  import { chatNode } from './nodes/ChatNode.js';
7
8
  export * from './nodes/ChatNode.js';
8
9
  export * from './nodes/ChatNodeBase.js';
@@ -83,6 +84,10 @@ import { watchStreamingOutputNode } from './nodes/WatchStreamingOutputNode.js';
83
84
  export * from './nodes/WatchStreamingOutputNode.js';
84
85
  import { stopWatchingStreamingOutputNode } from './nodes/StopWatchingStreamingOutputNode.js';
85
86
  export * from './nodes/StopWatchingStreamingOutputNode.js';
87
+ import { streamValueNode } from './nodes/StreamValueNode.js';
88
+ export * from './nodes/StreamValueNode.js';
89
+ import { catchStreamingChunksNode } from './nodes/CatchStreamingChunksNode.js';
90
+ export * from './nodes/CatchStreamingChunksNode.js';
86
91
  import { popNode } from './nodes/PopNode.js';
87
92
  export * from './nodes/PopNode.js';
88
93
  import { setGlobalNode } from './nodes/SetGlobalNode.js';
@@ -125,6 +130,8 @@ import { raceInputsNode } from './nodes/RaceInputsNode.js';
125
130
  export * from './nodes/RaceInputsNode.js';
126
131
  import { toJsonNode } from './nodes/ToJsonNode.js';
127
132
  export * from './nodes/ToJsonNode.js';
133
+ import { toBase64Node } from './nodes/ToBase64Node.js';
134
+ export * from './nodes/ToBase64Node.js';
128
135
  import { joinNode } from './nodes/JoinNode.js';
129
136
  export * from './nodes/JoinNode.js';
130
137
  import { filterNode } from './nodes/FilterNode.js';
@@ -265,6 +272,8 @@ export const registerBuiltInNodes = (registry) => {
265
272
  .register(startBackgroundBranchNode)
266
273
  .register(watchStreamingOutputNode)
267
274
  .register(stopWatchingStreamingOutputNode)
275
+ .register(streamValueNode)
276
+ .register(catchStreamingChunksNode)
268
277
  .register(popNode)
269
278
  .register(setGlobalNode)
270
279
  .register(getGlobalNode)
@@ -285,6 +294,7 @@ export const registerBuiltInNodes = (registry) => {
285
294
  .register(abortGraphNode)
286
295
  .register(raceInputsNode)
287
296
  .register(toJsonNode)
297
+ .register(toBase64Node)
288
298
  .register(joinNode)
289
299
  .register(filterNode)
290
300
  .register(jsFilterNode)