@valerypopoff/rivet2-core 2.0.7 → 2.0.9

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 (63) hide show
  1. package/dist/cjs/bundle.cjs +1757 -789
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/esm/api/createProcessor.js +9 -2
  4. package/dist/esm/api/streaming.js +1 -0
  5. package/dist/esm/exports.js +1 -0
  6. package/dist/esm/model/DebuggerTransportSentinel.js +78 -0
  7. package/dist/esm/model/GraphAbortReasons.js +69 -0
  8. package/dist/esm/model/GraphBoundaryCache.js +92 -0
  9. package/dist/esm/model/GraphPreprocessor.js +212 -32
  10. package/dist/esm/model/GraphProcessor.js +493 -172
  11. package/dist/esm/model/NodeExclusionPolicy.js +67 -0
  12. package/dist/esm/model/NodeExecutionPlanner.js +66 -22
  13. package/dist/esm/model/NodeImpl.js +6 -4
  14. package/dist/esm/model/ProcessContextBuilder.js +2 -17
  15. package/dist/esm/model/RecordingPlayer.js +27 -7
  16. package/dist/esm/model/SplitRunProcessor.js +48 -9
  17. package/dist/esm/model/SubprocessorBridge.js +30 -23
  18. package/dist/esm/model/chat-v2/chatV2Outputs.js +183 -0
  19. package/dist/esm/model/chat-v2/chatV2Pipeline.js +30 -212
  20. package/dist/esm/model/nodes/CodeNewNode.js +1 -1
  21. package/dist/esm/model/nodes/CodeNode.js +1 -1
  22. package/dist/esm/model/nodes/GetGlobalNode.js +14 -4
  23. package/dist/esm/model/nodes/GraphOutputNode.js +31 -2
  24. package/dist/esm/model/nodes/HttpCallNode.js +20 -18
  25. package/dist/esm/model/nodes/LoopUntilNode.js +18 -45
  26. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +24 -63
  27. package/dist/esm/model/nodes/SetGlobalNode.js +2 -1
  28. package/dist/esm/model/nodes/SubGraphNode.js +22 -63
  29. package/dist/esm/model/nodes/codeNodeErrorDiagnostics.js +2 -3
  30. package/dist/esm/recording/ExecutionRecorder.js +19 -6
  31. package/dist/esm/utils/emitDetached.js +2 -2
  32. package/dist/esm/utils/interpolation.js +41 -1
  33. package/dist/esm/utils/serialization/serialization.js +6 -5
  34. package/dist/esm/utils/serialization/serializationHelpers.js +2 -2
  35. package/dist/esm/utils/serialization/serializationInput.js +48 -0
  36. package/dist/esm/utils/serialization/serializationUtils.js +2 -33
  37. package/dist/esm/utils/serialization/serialization_v2.js +8 -8
  38. package/dist/types/api/createProcessor.d.ts +9 -2
  39. package/dist/types/api/streaming.d.ts +1 -0
  40. package/dist/types/exports.d.ts +1 -0
  41. package/dist/types/model/DebuggerTransportSentinel.d.ts +21 -0
  42. package/dist/types/model/EditorDefinition.d.ts +2 -0
  43. package/dist/types/model/ExecutorProtocol.d.ts +5 -0
  44. package/dist/types/model/GraphAbortReasons.d.ts +23 -0
  45. package/dist/types/model/GraphBoundaryCache.d.ts +27 -0
  46. package/dist/types/model/GraphPreprocessor.d.ts +39 -3
  47. package/dist/types/model/GraphProcessor.d.ts +20 -1
  48. package/dist/types/model/NodeExclusionPolicy.d.ts +21 -0
  49. package/dist/types/model/NodeExecutionPlanner.d.ts +3 -8
  50. package/dist/types/model/NodeImpl.d.ts +10 -5
  51. package/dist/types/model/Nodes.d.ts +2 -2
  52. package/dist/types/model/ProcessContext.d.ts +3 -0
  53. package/dist/types/model/ProcessContextBuilder.d.ts +4 -20
  54. package/dist/types/model/SplitRunProcessor.d.ts +8 -3
  55. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +29 -0
  56. package/dist/types/model/nodes/LoopUntilNode.d.ts +5 -4
  57. package/dist/types/model/nodes/ReferencedGraphAliasNode.d.ts +5 -4
  58. package/dist/types/model/nodes/SubGraphNode.d.ts +6 -5
  59. package/dist/types/model/nodes/codeNodeErrorDiagnostics.d.ts +1 -2
  60. package/dist/types/recording/RecordedEvents.d.ts +4 -0
  61. package/dist/types/utils/emitDetached.d.ts +2 -2
  62. package/dist/types/utils/serialization/serializationInput.d.ts +7 -0
  63. package/package.json +1 -1
@@ -191,12 +191,16 @@ __export(src_exports, {
191
191
  createChatV2Model: () => createChatV2Model,
192
192
  createChatV2ResponseOutput: () => createChatV2ResponseOutput,
193
193
  createDatasetNode: () => createDatasetNode,
194
+ createDebuggerTransportEscapedSentinel: () => createDebuggerTransportEscapedSentinel,
195
+ createDebuggerTransportEscapedSentinelEnvelope: () => createDebuggerTransportEscapedSentinelEnvelope,
196
+ createDebuggerTransportUndefinedSentinel: () => createDebuggerTransportUndefinedSentinel,
194
197
  createInterpolationInputDefinition: () => createInterpolationInputDefinition,
195
198
  createsLLMChatV2ToolResponseFormatConflictForEdit: () => createsLLMChatV2ToolResponseFormatConflictForEdit,
196
199
  cronNode: () => cronNode,
197
200
  dataTypeDisplayNames: () => dataTypeDisplayNames,
198
201
  dataTypes: () => dataTypes,
199
202
  datasetNearestNeighborsNode: () => datasetNearestNeighborsNode,
203
+ decodeDebuggerTransportSentinels: () => decodeDebuggerTransportSentinels,
200
204
  dedent: () => import_ts_dedent.dedent,
201
205
  delayNode: () => delayNode,
202
206
  delegateFunctionCallNode: () => delegateFunctionCallNode,
@@ -280,6 +284,7 @@ __export(src_exports, {
280
284
  isChatV2StructuredResponseFormat: () => isChatV2StructuredResponseFormat,
281
285
  isDataTypeAccepted: () => isDataTypeAccepted,
282
286
  isDataTypeCompatible: () => isDataTypeCompatible,
287
+ isDebuggerTransportSentinelEnvelope: () => isDebuggerTransportSentinelEnvelope,
283
288
  isFunctionDataType: () => isFunctionDataType,
284
289
  isFunctionDataValue: () => isFunctionDataValue,
285
290
  isInterpolationInputDefinition: () => isInterpolationInputDefinition,
@@ -549,12 +554,16 @@ __export(exports_exports, {
549
554
  createChatV2Model: () => createChatV2Model,
550
555
  createChatV2ResponseOutput: () => createChatV2ResponseOutput,
551
556
  createDatasetNode: () => createDatasetNode,
557
+ createDebuggerTransportEscapedSentinel: () => createDebuggerTransportEscapedSentinel,
558
+ createDebuggerTransportEscapedSentinelEnvelope: () => createDebuggerTransportEscapedSentinelEnvelope,
559
+ createDebuggerTransportUndefinedSentinel: () => createDebuggerTransportUndefinedSentinel,
552
560
  createInterpolationInputDefinition: () => createInterpolationInputDefinition,
553
561
  createsLLMChatV2ToolResponseFormatConflictForEdit: () => createsLLMChatV2ToolResponseFormatConflictForEdit,
554
562
  cronNode: () => cronNode,
555
563
  dataTypeDisplayNames: () => dataTypeDisplayNames,
556
564
  dataTypes: () => dataTypes,
557
565
  datasetNearestNeighborsNode: () => datasetNearestNeighborsNode,
566
+ decodeDebuggerTransportSentinels: () => decodeDebuggerTransportSentinels,
558
567
  dedent: () => import_ts_dedent.dedent,
559
568
  delayNode: () => delayNode,
560
569
  delegateFunctionCallNode: () => delegateFunctionCallNode,
@@ -638,6 +647,7 @@ __export(exports_exports, {
638
647
  isChatV2StructuredResponseFormat: () => isChatV2StructuredResponseFormat,
639
648
  isDataTypeAccepted: () => isDataTypeAccepted,
640
649
  isDataTypeCompatible: () => isDataTypeCompatible,
650
+ isDebuggerTransportSentinelEnvelope: () => isDebuggerTransportSentinelEnvelope,
641
651
  isFunctionDataType: () => isFunctionDataType,
642
652
  isFunctionDataValue: () => isFunctionDataValue,
643
653
  isInterpolationInputDefinition: () => isInterpolationInputDefinition,
@@ -1364,8 +1374,56 @@ var yaml3 = __toESM(require("yaml"), 1);
1364
1374
  // src/utils/serialization/serialization_v3.ts
1365
1375
  var import_lodash_es = require("lodash");
1366
1376
 
1367
- // src/utils/serialization/serializationUtils.ts
1377
+ // src/utils/serialization/serializationInput.ts
1368
1378
  var YAML = __toESM(require("yaml"), 1);
1379
+ function prepareSerializedInput(data) {
1380
+ if (typeof data !== "string") {
1381
+ return {
1382
+ deserializerInput: data,
1383
+ version: 1
1384
+ };
1385
+ }
1386
+ const trimmed = data.trim();
1387
+ if (!trimmed) {
1388
+ return {
1389
+ deserializerInput: data,
1390
+ version: 1
1391
+ };
1392
+ }
1393
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
1394
+ try {
1395
+ const parsed2 = JSON.parse(trimmed);
1396
+ const version2 = getParsedSerializationVersion(parsed2);
1397
+ return {
1398
+ deserializerInput: version2 === 1 ? data : parsed2,
1399
+ version: version2
1400
+ };
1401
+ } catch {
1402
+ return {
1403
+ deserializerInput: data,
1404
+ version: 1
1405
+ };
1406
+ }
1407
+ }
1408
+ const parsed = YAML.parse(trimmed);
1409
+ const version = getParsedSerializationVersion(parsed);
1410
+ return {
1411
+ deserializerInput: version === 1 ? data : parsed,
1412
+ version
1413
+ };
1414
+ }
1415
+ function getParsedSerializationVersion(parsed) {
1416
+ if (!parsed || typeof parsed !== "object") {
1417
+ return 1;
1418
+ }
1419
+ const version = parsed.version;
1420
+ if (version === 2 || version === 3 || version === 4) {
1421
+ return version;
1422
+ }
1423
+ return 1;
1424
+ }
1425
+
1426
+ // src/utils/serialization/serializationUtils.ts
1369
1427
  function validateProject(project) {
1370
1428
  const errors = [];
1371
1429
  const warnings = [];
@@ -1436,29 +1494,7 @@ function yamlProblem(err) {
1436
1494
  throw new Error(`YAML error: ${code} ${message} at ${pos} ${linePos}`);
1437
1495
  }
1438
1496
  function detectSerializationVersion(data) {
1439
- if (typeof data !== "string") {
1440
- return 1;
1441
- }
1442
- const trimmed = data.trim();
1443
- if (!trimmed) {
1444
- return 1;
1445
- }
1446
- if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
1447
- try {
1448
- const parsed2 = JSON.parse(trimmed);
1449
- if (typeof parsed2 === "object" && parsed2 != null && typeof parsed2.version === "number" && parsed2.version >= 2 && parsed2.version <= 4) {
1450
- return parsed2.version;
1451
- }
1452
- return 1;
1453
- } catch {
1454
- return 1;
1455
- }
1456
- }
1457
- const parsed = YAML.parse(trimmed);
1458
- if (parsed && typeof parsed === "object" && typeof parsed.version === "number" && parsed.version >= 2 && parsed.version <= 4) {
1459
- return parsed.version;
1460
- }
1461
- return 1;
1497
+ return prepareSerializedInput(data).version;
1462
1498
  }
1463
1499
 
1464
1500
  // src/utils/serialization/serializationHelpers.ts
@@ -1506,10 +1542,10 @@ function wrapInYamlEnvelope(version, data) {
1506
1542
  return yaml.stringify({ version, data: stabilized }, null, { indent: 2 });
1507
1543
  }
1508
1544
  function unwrapYamlEnvelope(raw, expectedVersion, label) {
1509
- if (typeof raw !== "string") {
1545
+ if (typeof raw !== "string" && (!raw || typeof raw !== "object" || Array.isArray(raw))) {
1510
1546
  throw new Error(`${label} deserializer requires a string`);
1511
1547
  }
1512
- const parsed = yaml.parse(raw);
1548
+ const parsed = typeof raw === "string" ? yaml.parse(raw) : raw;
1513
1549
  if (parsed.version !== expectedVersion) {
1514
1550
  throw new Error(`${label} deserializer requires a version ${expectedVersion} ${label.toLowerCase()}`);
1515
1551
  }
@@ -1780,10 +1816,7 @@ function datasetV4Deserializer(serializedDatasets) {
1780
1816
  // src/utils/serialization/serialization_v2.ts
1781
1817
  var yaml2 = __toESM(require("yaml"), 1);
1782
1818
  function projectV2Deserializer(data) {
1783
- if (typeof data !== "string") {
1784
- throw new Error("Project v2 deserializer requires a string");
1785
- }
1786
- const project = yaml2.parse(data);
1819
+ const project = unwrapV2Envelope(data, "Project v2");
1787
1820
  if (project.version !== 2) {
1788
1821
  throw new Error("Project v2 deserializer requires a version 2 project");
1789
1822
  }
@@ -1791,15 +1824,18 @@ function projectV2Deserializer(data) {
1791
1824
  return project.data;
1792
1825
  }
1793
1826
  function graphV2Deserializer(data) {
1794
- if (typeof data !== "string") {
1795
- throw new Error("Graph v2 deserializer requires a string");
1796
- }
1797
- const graph = yaml2.parse(data);
1827
+ const graph = unwrapV2Envelope(data, "Graph v2");
1798
1828
  if (graph.version !== 2) {
1799
1829
  throw new Error("Graph v2 deserializer requires a version 2 graph");
1800
1830
  }
1801
1831
  return graph.data;
1802
1832
  }
1833
+ function unwrapV2Envelope(data, label) {
1834
+ if (typeof data !== "string" && (!data || typeof data !== "object" || Array.isArray(data))) {
1835
+ throw new Error(`${label} deserializer requires a string`);
1836
+ }
1837
+ return typeof data === "string" ? yaml2.parse(data) : data;
1838
+ }
1803
1839
 
1804
1840
  // src/utils/serialization/serialization_v1.ts
1805
1841
  function projectV1Deserializer(data) {
@@ -1828,9 +1864,9 @@ function serializeProject(project, attachedData) {
1828
1864
  var errMessage = (err) => `${getError(err).message}
1829
1865
  ${getError(err).stack}`;
1830
1866
  function deserializeProject(serializedProject, path = null) {
1831
- const version = detectSerializationVersion(serializedProject);
1867
+ const { deserializerInput, version } = prepareSerializedInput(serializedProject);
1832
1868
  try {
1833
- const result = deserializeProjectByVersion(serializedProject, version);
1869
+ const result = deserializeProjectByVersion(deserializerInput, version);
1834
1870
  normalizeProjectDefaultNodeTitles(result[0]);
1835
1871
  if (path !== null) {
1836
1872
  result[0].metadata.path = path;
@@ -1848,9 +1884,9 @@ function serializeGraph(graph) {
1848
1884
  return graphV4Serializer(graph);
1849
1885
  }
1850
1886
  function deserializeGraph(serializedGraph) {
1851
- const version = detectSerializationVersion(serializedGraph);
1887
+ const { deserializerInput, version } = prepareSerializedInput(serializedGraph);
1852
1888
  try {
1853
- const graph = deserializeGraphByVersion(serializedGraph, version);
1889
+ const graph = deserializeGraphByVersion(deserializerInput, version);
1854
1890
  normalizeGraphDefaultNodeTitles(graph);
1855
1891
  return graph;
1856
1892
  } catch (err) {
@@ -2262,7 +2298,8 @@ function findStronglyConnectedComponents(nodes, getAdjacentNodes) {
2262
2298
  // src/model/GraphPreprocessor.ts
2263
2299
  function preprocessGraphState(options2) {
2264
2300
  var _a, _b;
2265
- const { graph, loadedProjects, project, registry, warnOnInvalidGraph } = options2;
2301
+ const { buildExecutionPlan, definitionContext, graph, loadedProjects, project, registry, warnOnInvalidGraph } = options2;
2302
+ const effectiveDefinitionContext = definitionContext && graph.nodes.some(usesGraphBoundaryDefinitionContext) ? definitionContext : void 0;
2266
2303
  const nodeInstances = {};
2267
2304
  const nodesById = {};
2268
2305
  const connections = {};
@@ -2296,78 +2333,384 @@ function preprocessGraphState(options2) {
2296
2333
  nodeInstances,
2297
2334
  nodesById,
2298
2335
  project,
2336
+ definitionContext: effectiveDefinitionContext,
2299
2337
  warnOnInvalidGraph
2300
2338
  });
2301
2339
  const stronglyConnectedComponents = findStronglyConnectedComponents(graph.nodes, (node) => {
2302
2340
  const nodeConnections = connections[node.id] ?? [];
2303
2341
  return nodeConnections.filter((connection) => connection.outputNodeId === node.id).map((connection) => nodesById[connection.inputNodeId]).filter(Boolean);
2304
2342
  });
2305
- return {
2343
+ const nodesNotInCycle = stronglyConnectedComponents.filter((component) => component.length === 1).flat();
2344
+ const result = {
2306
2345
  connections,
2307
2346
  definitions,
2308
2347
  nodeInstances,
2309
2348
  nodesById,
2310
- nodesNotInCycle: stronglyConnectedComponents.filter((component) => component.length === 1).flat(),
2349
+ nodesNotInCycle,
2311
2350
  stronglyConnectedComponents
2312
2351
  };
2352
+ if (!buildExecutionPlan) {
2353
+ return result;
2354
+ }
2355
+ return {
2356
+ ...result,
2357
+ ...buildGraphExecutionPlan({
2358
+ connections,
2359
+ definitions,
2360
+ graphNodes: graph.nodes,
2361
+ nodesById,
2362
+ stronglyConnectedComponents
2363
+ })
2364
+ };
2365
+ }
2366
+ function isGraphExecutionPlan(preprocessedGraph) {
2367
+ return "inputConnectionByNodeAndPort" in preprocessedGraph;
2368
+ }
2369
+ function toReusableGraphExecutionPlan(preprocessedGraph) {
2370
+ return {
2371
+ connections: preprocessedGraph.connections,
2372
+ cycleIndexByNode: preprocessedGraph.cycleIndexByNode,
2373
+ definitions: preprocessedGraph.definitions,
2374
+ graphNodes: preprocessedGraph.graphNodes,
2375
+ nodeIds: preprocessedGraph.nodeIds,
2376
+ inputConnectionByNodeAndPort: preprocessedGraph.inputConnectionByNodeAndPort,
2377
+ inputConnectionsByNode: preprocessedGraph.inputConnectionsByNode,
2378
+ inputNodesByNode: preprocessedGraph.inputNodesByNode,
2379
+ missingRequiredInputsByNode: preprocessedGraph.missingRequiredInputsByNode,
2380
+ nodesById: preprocessedGraph.nodesById,
2381
+ nodesNotInCycle: preprocessedGraph.nodesNotInCycle,
2382
+ outputConnectionsByNodeAndPort: preprocessedGraph.outputConnectionsByNodeAndPort,
2383
+ outputNodeResultsByNode: preprocessedGraph.outputNodeResultsByNode,
2384
+ startNodes: preprocessedGraph.startNodes,
2385
+ stronglyConnectedComponents: preprocessedGraph.stronglyConnectedComponents
2386
+ };
2313
2387
  }
2314
2388
  function loadInputOutputDefinitions(options2) {
2315
- const { connections, loadedProjects, nodeInstances, nodesById, project, warnOnInvalidGraph } = options2;
2389
+ const { connections, definitionContext, loadedProjects, nodeInstances, nodesById, project, warnOnInvalidGraph } = options2;
2316
2390
  const definitions = {};
2391
+ if (!definitionContext) {
2392
+ for (const node of values(nodesById)) {
2393
+ const connectionsForNode = connections[node.id] ?? [];
2394
+ const inputDefinitions = nodeInstances[node.id].getInputDefinitionsIncludingBuiltIn(
2395
+ connectionsForNode,
2396
+ nodesById,
2397
+ project,
2398
+ loadedProjects
2399
+ );
2400
+ const outputDefinitions = nodeInstances[node.id].getOutputDefinitions(
2401
+ connectionsForNode,
2402
+ nodesById,
2403
+ project,
2404
+ loadedProjects
2405
+ );
2406
+ definitions[node.id] = {
2407
+ inputs: inputDefinitions,
2408
+ outputs: outputDefinitions
2409
+ };
2410
+ const invalidConnections = connectionsForNode.filter((connection) => {
2411
+ if (connection.inputNodeId === node.id) {
2412
+ const inputDefinition = inputDefinitions.find((definition) => definition.id === connection.inputId);
2413
+ if (!inputDefinition) {
2414
+ if (warnOnInvalidGraph) {
2415
+ const sourceNode = nodesById[connection.outputNodeId];
2416
+ console.warn(
2417
+ `[Warn] Invalid connection going from "${sourceNode == null ? void 0 : sourceNode.title}".${connection.outputId} to "${node.title}".${connection.inputId}`
2418
+ );
2419
+ }
2420
+ return true;
2421
+ }
2422
+ } else {
2423
+ const outputDefinition = outputDefinitions.find((definition) => definition.id === connection.outputId);
2424
+ if (!outputDefinition) {
2425
+ if (warnOnInvalidGraph) {
2426
+ const targetNode = nodesById[connection.inputNodeId];
2427
+ console.warn(
2428
+ `[Warn] Invalid connection going from "${node.title}".${connection.outputId} to "${targetNode == null ? void 0 : targetNode.title}".${connection.inputId}`
2429
+ );
2430
+ }
2431
+ return true;
2432
+ }
2433
+ }
2434
+ return false;
2435
+ });
2436
+ if (invalidConnections.length > 0) {
2437
+ for (const invalidConnection of invalidConnections) {
2438
+ removeConnectionFromNode(connections, invalidConnection, invalidConnection.inputNodeId);
2439
+ if (invalidConnection.outputNodeId !== invalidConnection.inputNodeId) {
2440
+ removeConnectionFromNode(connections, invalidConnection, invalidConnection.outputNodeId);
2441
+ }
2442
+ }
2443
+ }
2444
+ }
2445
+ return definitions;
2446
+ }
2317
2447
  for (const node of values(nodesById)) {
2318
2448
  const connectionsForNode = connections[node.id] ?? [];
2319
- const inputDefinitions = nodeInstances[node.id].getInputDefinitionsIncludingBuiltIn(
2449
+ const nodeDefinitionContext = usesGraphBoundaryDefinitionContext(node) ? definitionContext : void 0;
2450
+ const inputDefinitions = nodeDefinitionContext ? nodeInstances[node.id].getInputDefinitionsIncludingBuiltIn(
2320
2451
  connectionsForNode,
2321
2452
  nodesById,
2322
2453
  project,
2323
- loadedProjects
2324
- );
2325
- const outputDefinitions = nodeInstances[node.id].getOutputDefinitions(
2454
+ loadedProjects,
2455
+ nodeDefinitionContext
2456
+ ) : nodeInstances[node.id].getInputDefinitionsIncludingBuiltIn(
2326
2457
  connectionsForNode,
2327
2458
  nodesById,
2328
2459
  project,
2329
2460
  loadedProjects
2330
2461
  );
2462
+ const outputDefinitions = nodeDefinitionContext ? nodeInstances[node.id].getOutputDefinitions(
2463
+ connectionsForNode,
2464
+ nodesById,
2465
+ project,
2466
+ loadedProjects,
2467
+ nodeDefinitionContext
2468
+ ) : nodeInstances[node.id].getOutputDefinitions(connectionsForNode, nodesById, project, loadedProjects);
2331
2469
  definitions[node.id] = {
2332
2470
  inputs: inputDefinitions,
2333
2471
  outputs: outputDefinitions
2334
2472
  };
2335
- const invalidConnections = connectionsForNode.filter((connection) => {
2336
- if (connection.inputNodeId === node.id) {
2337
- const inputDefinition = inputDefinitions.find((definition) => definition.id === connection.inputId);
2338
- if (!inputDefinition) {
2339
- if (warnOnInvalidGraph) {
2340
- const sourceNode = nodesById[connection.outputNodeId];
2341
- console.warn(
2342
- `[Warn] Invalid connection going from "${sourceNode == null ? void 0 : sourceNode.title}".${connection.outputId} to "${node.title}".${connection.inputId}`
2343
- );
2344
- }
2345
- return true;
2346
- }
2347
- } else {
2348
- const outputDefinition = outputDefinitions.find((definition) => definition.id === connection.outputId);
2349
- if (!outputDefinition) {
2350
- if (warnOnInvalidGraph) {
2351
- const targetNode = nodesById[connection.inputNodeId];
2352
- console.warn(
2353
- `[Warn] Invalid connection going from "${node.title}".${connection.outputId} to "${targetNode == null ? void 0 : targetNode.title}".${connection.inputId}`
2354
- );
2355
- }
2356
- return true;
2473
+ removeInvalidDefinitionConnections(
2474
+ connections,
2475
+ connectionsForNode,
2476
+ inputDefinitions,
2477
+ node,
2478
+ nodesById,
2479
+ outputDefinitions,
2480
+ warnOnInvalidGraph
2481
+ );
2482
+ }
2483
+ return definitions;
2484
+ }
2485
+ function removeInvalidDefinitionConnections(connections, connectionsForNode, inputDefinitions, node, nodesById, outputDefinitions, warnOnInvalidGraph) {
2486
+ const invalidConnections = connectionsForNode.filter((connection) => {
2487
+ if (connection.inputNodeId === node.id) {
2488
+ const inputDefinition = inputDefinitions.find((definition) => definition.id === connection.inputId);
2489
+ if (!inputDefinition) {
2490
+ if (warnOnInvalidGraph) {
2491
+ const sourceNode = nodesById[connection.outputNodeId];
2492
+ console.warn(
2493
+ `[Warn] Invalid connection going from "${sourceNode == null ? void 0 : sourceNode.title}".${connection.outputId} to "${node.title}".${connection.inputId}`
2494
+ );
2357
2495
  }
2496
+ return true;
2358
2497
  }
2359
- return false;
2360
- });
2361
- for (const nodeConnections of values(connections)) {
2362
- for (const invalidConnection of invalidConnections) {
2363
- const invalidConnectionIndex = nodeConnections.indexOf(invalidConnection);
2364
- if (invalidConnectionIndex !== -1) {
2365
- nodeConnections.splice(invalidConnectionIndex, 1);
2498
+ } else {
2499
+ const outputDefinition = outputDefinitions.find((definition) => definition.id === connection.outputId);
2500
+ if (!outputDefinition) {
2501
+ if (warnOnInvalidGraph) {
2502
+ const targetNode = nodesById[connection.inputNodeId];
2503
+ console.warn(
2504
+ `[Warn] Invalid connection going from "${node.title}".${connection.outputId} to "${targetNode == null ? void 0 : targetNode.title}".${connection.inputId}`
2505
+ );
2366
2506
  }
2507
+ return true;
2508
+ }
2509
+ }
2510
+ return false;
2511
+ });
2512
+ if (invalidConnections.length > 0) {
2513
+ for (const invalidConnection of invalidConnections) {
2514
+ removeConnectionFromNode(connections, invalidConnection, invalidConnection.inputNodeId);
2515
+ if (invalidConnection.outputNodeId !== invalidConnection.inputNodeId) {
2516
+ removeConnectionFromNode(connections, invalidConnection, invalidConnection.outputNodeId);
2367
2517
  }
2368
2518
  }
2369
2519
  }
2370
- return definitions;
2520
+ }
2521
+ function usesGraphBoundaryDefinitionContext(node) {
2522
+ return node.type === "subGraph" || node.type === "referencedGraphAlias" || node.type === "loopUntil";
2523
+ }
2524
+ function removeConnectionFromNode(connections, connection, nodeId) {
2525
+ const nodeConnections = connections[nodeId];
2526
+ if (!nodeConnections) {
2527
+ return;
2528
+ }
2529
+ const invalidConnectionIndex = nodeConnections.indexOf(connection);
2530
+ if (invalidConnectionIndex !== -1) {
2531
+ nodeConnections.splice(invalidConnectionIndex, 1);
2532
+ }
2533
+ }
2534
+ function buildGraphExecutionPlan(options2) {
2535
+ var _a, _b;
2536
+ const { connections, definitions, graphNodes, nodesById, stronglyConnectedComponents } = options2;
2537
+ const cycleIndexByNode = {};
2538
+ const inputConnectionByNodeAndPort = {};
2539
+ const inputConnectionsByNode = {};
2540
+ const inputNodesByNode = {};
2541
+ const missingRequiredInputsByNode = {};
2542
+ const outputConnectionsByNodeAndPort = {};
2543
+ const outputNodeResultsByNode = {};
2544
+ stronglyConnectedComponents.forEach((component, index) => {
2545
+ for (const node of component) {
2546
+ cycleIndexByNode[node.id] = index;
2547
+ }
2548
+ });
2549
+ for (const node of graphNodes) {
2550
+ const nodeConnections = connections[node.id] ?? [];
2551
+ const inputDefinitions = ((_a = definitions[node.id]) == null ? void 0 : _a.inputs) ?? [];
2552
+ const outputDefinitions = ((_b = definitions[node.id]) == null ? void 0 : _b.outputs) ?? [];
2553
+ const validInputIds = new Set(inputDefinitions.map((definition) => definition.id));
2554
+ const validOutputIds = new Set(outputDefinitions.map((definition) => definition.id));
2555
+ const inputConnections = nodeConnections.filter(
2556
+ (connection) => connection.inputNodeId === node.id && validInputIds.has(connection.inputId)
2557
+ );
2558
+ const outputConnections = nodeConnections.filter(
2559
+ (connection) => connection.outputNodeId === node.id && validOutputIds.has(connection.outputId)
2560
+ );
2561
+ inputConnectionsByNode[node.id] = inputConnections;
2562
+ outputConnectionsByNodeAndPort[node.id] = {};
2563
+ inputConnectionByNodeAndPort[node.id] = {};
2564
+ for (const connection of inputConnections) {
2565
+ inputConnectionByNodeAndPort[node.id][connection.inputId] ??= connection;
2566
+ }
2567
+ for (const connection of outputConnections) {
2568
+ outputConnectionsByNodeAndPort[node.id][connection.outputId] ??= [];
2569
+ outputConnectionsByNodeAndPort[node.id][connection.outputId].push(connection);
2570
+ }
2571
+ inputNodesByNode[node.id] = inputConnections.map((connection) => nodesById[connection.outputNodeId]).filter((inputNode) => inputNode != null);
2572
+ missingRequiredInputsByNode[node.id] = inputDefinitions.filter(
2573
+ (input) => {
2574
+ var _a2;
2575
+ return input.required && ((_a2 = inputConnectionByNodeAndPort[node.id]) == null ? void 0 : _a2[input.id]) == null;
2576
+ }
2577
+ );
2578
+ const outputNodes = [];
2579
+ const seenOutputNodeIds = /* @__PURE__ */ new Set();
2580
+ const outputConnectionsByNode = /* @__PURE__ */ new Map();
2581
+ for (const connection of outputConnections) {
2582
+ const outputNode = nodesById[connection.inputNodeId];
2583
+ if (!outputNode) {
2584
+ continue;
2585
+ }
2586
+ if (!seenOutputNodeIds.has(outputNode.id)) {
2587
+ outputNodes.push(outputNode);
2588
+ seenOutputNodeIds.add(outputNode.id);
2589
+ }
2590
+ const nodeConnections2 = outputConnectionsByNode.get(outputNode.id);
2591
+ if (nodeConnections2) {
2592
+ nodeConnections2.push(connection);
2593
+ } else {
2594
+ outputConnectionsByNode.set(outputNode.id, [connection]);
2595
+ }
2596
+ }
2597
+ outputNodeResultsByNode[node.id] = {
2598
+ connections: outputConnections,
2599
+ connectionsToNodes: outputNodes.map((outputNode) => ({
2600
+ connections: outputConnectionsByNode.get(outputNode.id) ?? [],
2601
+ node: outputNode
2602
+ })),
2603
+ nodes: outputNodes
2604
+ };
2605
+ }
2606
+ return {
2607
+ cycleIndexByNode,
2608
+ graphNodes,
2609
+ nodeIds: graphNodes.map((node) => node.id),
2610
+ inputConnectionByNodeAndPort,
2611
+ inputConnectionsByNode,
2612
+ inputNodesByNode,
2613
+ missingRequiredInputsByNode,
2614
+ outputConnectionsByNodeAndPort,
2615
+ outputNodeResultsByNode,
2616
+ startNodes: graphNodes.filter((node) => {
2617
+ var _a2;
2618
+ return ((_a2 = outputNodeResultsByNode[node.id]) == null ? void 0 : _a2.nodes.length) === 0;
2619
+ })
2620
+ };
2621
+ }
2622
+
2623
+ // src/model/GraphBoundaryCache.ts
2624
+ function getGraphBoundary(project, graphId, cache4) {
2625
+ if (!graphId) {
2626
+ return void 0;
2627
+ }
2628
+ const graph = project.graphs[graphId];
2629
+ if (!graph) {
2630
+ return void 0;
2631
+ }
2632
+ if (!cache4) {
2633
+ return deriveGraphBoundary(graph);
2634
+ }
2635
+ const cached = cache4.get(graph);
2636
+ if (cached) {
2637
+ return cached;
2638
+ }
2639
+ const boundary = deriveGraphBoundary(graph);
2640
+ cache4.set(graph, boundary);
2641
+ return boundary;
2642
+ }
2643
+ function getGraphBoundaryInputDefinitions(boundary) {
2644
+ return boundary.inputs.map(
2645
+ (input) => ({
2646
+ id: input.portId,
2647
+ title: input.id,
2648
+ dataType: input.dataType
2649
+ })
2650
+ );
2651
+ }
2652
+ function getGraphBoundaryOutputDefinitions(boundary) {
2653
+ return boundary.outputs.map(
2654
+ (output) => ({
2655
+ id: output.portId,
2656
+ title: output.id,
2657
+ dataType: output.dataType
2658
+ })
2659
+ );
2660
+ }
2661
+ function buildGraphBoundaryInputData(boundary, inputs, defaults) {
2662
+ const inputData = {};
2663
+ for (const input of boundary.inputs) {
2664
+ const inputValue = inputs[input.portId];
2665
+ if (inputValue != null) {
2666
+ inputData[input.portId] = inputValue;
2667
+ continue;
2668
+ }
2669
+ const defaultValue = defaults == null ? void 0 : defaults[input.id];
2670
+ if (defaultValue != null) {
2671
+ inputData[input.portId] = defaultValue;
2672
+ }
2673
+ }
2674
+ return inputData;
2675
+ }
2676
+ function buildExcludedGraphBoundaryOutputs(boundary) {
2677
+ const outputs = {};
2678
+ for (const output of boundary.outputs) {
2679
+ outputs[output.portId] = {
2680
+ type: "control-flow-excluded",
2681
+ value: void 0
2682
+ };
2683
+ }
2684
+ return outputs;
2685
+ }
2686
+ function deriveGraphBoundary(graph) {
2687
+ const inputsById = /* @__PURE__ */ new Map();
2688
+ const outputsById = /* @__PURE__ */ new Map();
2689
+ for (const node of graph.nodes) {
2690
+ if (node.type === "graphInput" && !inputsById.has(getBoundaryNodeId(node))) {
2691
+ const inputNode = node;
2692
+ inputsById.set(inputNode.data.id, {
2693
+ dataType: inputNode.data.dataType,
2694
+ editor: inputNode.data.editor,
2695
+ id: inputNode.data.id,
2696
+ portId: inputNode.data.id
2697
+ });
2698
+ } else if (node.type === "graphOutput" && !outputsById.has(getBoundaryNodeId(node))) {
2699
+ const outputNode = node;
2700
+ outputsById.set(outputNode.data.id, {
2701
+ dataType: outputNode.data.dataType,
2702
+ id: outputNode.data.id,
2703
+ portId: outputNode.data.id
2704
+ });
2705
+ }
2706
+ }
2707
+ return {
2708
+ inputs: Array.from(inputsById.keys()).sort().map((id) => inputsById.get(id)),
2709
+ outputs: Array.from(outputsById.keys()).sort().map((id) => outputsById.get(id))
2710
+ };
2711
+ }
2712
+ function getBoundaryNodeId(node) {
2713
+ return node.data.id;
2371
2714
  }
2372
2715
 
2373
2716
  // src/model/RecordingPlayer.ts
@@ -2379,6 +2722,13 @@ function emitDetached(emitter, event, data) {
2379
2722
  }
2380
2723
 
2381
2724
  // src/model/RecordingPlayer.ts
2725
+ function withOptionalDuration(payload, durationMs, splitRunDurationMs) {
2726
+ return {
2727
+ ...payload,
2728
+ ...durationMs === void 0 ? {} : { durationMs },
2729
+ ...splitRunDurationMs === void 0 ? {} : { splitRunDurationMs }
2730
+ };
2731
+ }
2382
2732
  async function replayExecutionRecording(options2) {
2383
2733
  var _a, _b, _c, _d, _e, _f, _g, _h;
2384
2734
  const {
@@ -2430,6 +2780,7 @@ async function replayExecutionRecording(options2) {
2430
2780
  try {
2431
2781
  const legacyRootRunId = (0, import_non_secure3.nanoid)();
2432
2782
  const legacyGraphRunsByGraphId = /* @__PURE__ */ new Map();
2783
+ const nodeStartTimestamps = /* @__PURE__ */ new Map();
2433
2784
  const getExecution = (graphId, recordedExecution) => {
2434
2785
  if (recordedExecution) {
2435
2786
  return recordedExecution;
@@ -2445,6 +2796,14 @@ async function replayExecutionRecording(options2) {
2445
2796
  rootRunId: legacyRootRunId
2446
2797
  };
2447
2798
  };
2799
+ const getNodeRunKey = (execution, nodeId, processId) => `${execution.rootRunId}:${execution.graphRunId}:${nodeId}:${processId}`;
2800
+ const getRecordedDuration = (recordedDuration, execution, nodeId, processId, terminalTs) => {
2801
+ if (recordedDuration !== void 0) {
2802
+ return recordedDuration;
2803
+ }
2804
+ const startedAt = nodeStartTimestamps.get(getNodeRunKey(execution, nodeId, processId));
2805
+ return startedAt === void 0 ? void 0 : Math.max(0, terminalTs - startedAt);
2806
+ };
2448
2807
  for (const event of recorder.events) {
2449
2808
  if (isAborted()) {
2450
2809
  break;
@@ -2536,11 +2895,13 @@ async function replayExecutionRecording(options2) {
2536
2895
  case "nodeStart": {
2537
2896
  const { data } = event;
2538
2897
  const node = getNode(data.nodeId);
2898
+ const execution = getExecution(((_b = data.execution) == null ? void 0 : _b.graphId) ?? getGraphIdForNode(data.nodeId), data.execution);
2899
+ nodeStartTimestamps.set(getNodeRunKey(execution, data.nodeId, data.processId), event.ts);
2539
2900
  emitDetached(emitter, "nodeStart", {
2540
2901
  node,
2541
2902
  inputs: data.inputs,
2542
2903
  processId: data.processId,
2543
- execution: getExecution(((_b = data.execution) == null ? void 0 : _b.graphId) ?? getGraphIdForNode(data.nodeId), data.execution)
2904
+ execution
2544
2905
  });
2545
2906
  if (node.type === "chat") {
2546
2907
  await new Promise((resolve) => setTimeout(resolve, recordingPlaybackChatLatency));
@@ -2550,12 +2911,21 @@ async function replayExecutionRecording(options2) {
2550
2911
  case "nodeFinish": {
2551
2912
  const { data } = event;
2552
2913
  const node = getNode(data.nodeId);
2553
- emitDetached(emitter, "nodeFinish", {
2554
- node,
2555
- outputs: data.outputs,
2556
- processId: data.processId,
2557
- execution: getExecution(((_c = data.execution) == null ? void 0 : _c.graphId) ?? getGraphIdForNode(data.nodeId), data.execution)
2558
- });
2914
+ const execution = getExecution(((_c = data.execution) == null ? void 0 : _c.graphId) ?? getGraphIdForNode(data.nodeId), data.execution);
2915
+ emitDetached(
2916
+ emitter,
2917
+ "nodeFinish",
2918
+ withOptionalDuration(
2919
+ {
2920
+ node,
2921
+ outputs: data.outputs,
2922
+ processId: data.processId,
2923
+ execution
2924
+ },
2925
+ getRecordedDuration(data.durationMs, execution, data.nodeId, data.processId, event.ts),
2926
+ data.splitRunDurationMs
2927
+ )
2928
+ );
2559
2929
  nodeResults.set(data.nodeId, data.outputs);
2560
2930
  visitedNodes.add(data.nodeId);
2561
2931
  break;
@@ -2563,12 +2933,21 @@ async function replayExecutionRecording(options2) {
2563
2933
  case "nodeError": {
2564
2934
  const { data } = event;
2565
2935
  const node = getNode(data.nodeId);
2566
- emitDetached(emitter, "nodeError", {
2567
- node,
2568
- error: data.error,
2569
- processId: data.processId,
2570
- execution: getExecution(((_d = data.execution) == null ? void 0 : _d.graphId) ?? getGraphIdForNode(data.nodeId), data.execution)
2571
- });
2936
+ const execution = getExecution(((_d = data.execution) == null ? void 0 : _d.graphId) ?? getGraphIdForNode(data.nodeId), data.execution);
2937
+ emitDetached(
2938
+ emitter,
2939
+ "nodeError",
2940
+ withOptionalDuration(
2941
+ {
2942
+ node,
2943
+ error: data.error,
2944
+ processId: data.processId,
2945
+ execution
2946
+ },
2947
+ getRecordedDuration(data.durationMs, execution, data.nodeId, data.processId, event.ts),
2948
+ data.splitRunDurationMs
2949
+ )
2950
+ );
2572
2951
  erroredNodes.set(data.nodeId, data.error);
2573
2952
  visitedNodes.add(data.nodeId);
2574
2953
  break;
@@ -2670,69 +3049,113 @@ function didLoopControllerBreak(breakValue) {
2670
3049
  function buildNodeProcessContext(options2) {
2671
3050
  const {
2672
3051
  attachedData,
2673
- codeRunner,
2674
- context,
2675
- contextValues,
3052
+ base,
2676
3053
  createSubProcessor,
2677
3054
  execution,
2678
- executionCache,
2679
- executor,
2680
3055
  externalFunctions,
2681
- getGlobal,
2682
3056
  getPluginConfig: getPluginConfig2,
2683
- graphInputNodeValues,
2684
- graphInputs,
2685
- graphOutputs,
2686
- loadedProjects,
2687
3057
  node,
2688
3058
  nodeAbortController,
2689
3059
  onPartialOutputs,
2690
3060
  processId,
2691
- project,
2692
- raiseEvent,
2693
3061
  requestUserInput,
2694
3062
  setGlobal,
2695
- tokenizer,
2696
- trace,
2697
- waitEvent,
2698
- waitForGlobal,
2699
- abortGraph
3063
+ waitEvent
2700
3064
  } = options2;
2701
3065
  return {
2702
- ...context,
3066
+ ...base,
2703
3067
  node,
2704
- tokenizer,
2705
- executor,
2706
- project,
2707
- executionCache,
2708
- graphInputs,
2709
- graphOutputs,
2710
3068
  attachedData,
2711
- codeRunner,
2712
- referencedProjects: loadedProjects,
2713
3069
  waitEvent,
2714
- raiseEvent,
2715
- contextValues,
2716
3070
  externalFunctions: { ...externalFunctions },
2717
3071
  onPartialOutputs,
2718
3072
  signal: nodeAbortController.signal,
2719
3073
  processId,
2720
- getGlobal,
2721
3074
  setGlobal,
2722
- waitForGlobal,
2723
3075
  createSubProcessor,
2724
- trace,
2725
- abortGraph,
2726
3076
  getPluginConfig: getPluginConfig2,
2727
3077
  requestUserInput,
2728
- graphInputNodeValues,
2729
3078
  execution
2730
3079
  };
2731
3080
  }
2732
3081
 
2733
3082
  // src/model/SplitRunProcessor.ts
2734
3083
  var import_lodash_es3 = require("lodash");
3084
+
3085
+ // src/model/GraphAbortReasons.ts
3086
+ var RACE_LOSER_EXCLUSION_REASON = "Race branch lost";
3087
+ var SUCCESSFUL_GRAPH_ABORT_EXCLUSION_REASON = "Graph aborted successfully";
3088
+ var GRAPH_ABORT_ERROR_MARKER = "rivet:graph-abort-error";
3089
+ var GRAPH_ABORT_REASON_MARKER = "rivet:graph-abort-reason";
3090
+ function createGraphAbortReason(successful, error) {
3091
+ return {
3092
+ error,
3093
+ marker: GRAPH_ABORT_REASON_MARKER,
3094
+ successful
3095
+ };
3096
+ }
3097
+ function createGraphAbortError(reason, message = "Processing aborted") {
3098
+ const error = new Error(message);
3099
+ Object.defineProperties(error, {
3100
+ graphAbortReason: {
3101
+ configurable: true,
3102
+ value: reason
3103
+ },
3104
+ marker: {
3105
+ configurable: true,
3106
+ value: GRAPH_ABORT_ERROR_MARKER
3107
+ }
3108
+ });
3109
+ return error;
3110
+ }
3111
+ function createGraphAbortErrorFromSignal(signal, message = "Processing aborted") {
3112
+ return createGraphAbortError(getGraphAbortReasonFromSignal(signal), message);
3113
+ }
3114
+ function getAbortSignalReason(signal) {
3115
+ return signal ? signal.reason : void 0;
3116
+ }
3117
+ function getGraphAbortReasonFromSignal(signal) {
3118
+ return getGraphAbortReason(getAbortSignalReason(signal));
3119
+ }
3120
+ function getGraphAbortReasonFromError(error) {
3121
+ if (!isGraphAbortError(error)) {
3122
+ return void 0;
3123
+ }
3124
+ return error.graphAbortReason;
3125
+ }
3126
+ function isRaceLoserGraphAbortReason(reason) {
3127
+ return (reason == null ? void 0 : reason.successful) === true && reason.error === RACE_LOSER_EXCLUSION_REASON;
3128
+ }
3129
+ function isSuccessfulNonRaceGraphAbortReason(reason) {
3130
+ return (reason == null ? void 0 : reason.successful) === true && !isRaceLoserGraphAbortReason(reason);
3131
+ }
3132
+ function isAbortLikeError(error) {
3133
+ const normalized = `${error.name}: ${error.message}`.trim();
3134
+ return /^(Error:\s*)?(Aborted|Processing aborted|Process aborted)\.?$/i.test(error.message.trim()) || /^AbortError\b/i.test(normalized) || /\boperation was aborted\.?$/i.test(error.message.trim());
3135
+ }
3136
+ function getGraphAbortReason(reason) {
3137
+ if (!isGraphAbortReason(reason)) {
3138
+ return void 0;
3139
+ }
3140
+ return reason;
3141
+ }
3142
+ function isGraphAbortReason(reason) {
3143
+ return typeof reason === "object" && reason != null && reason.marker === GRAPH_ABORT_REASON_MARKER && typeof reason.successful === "boolean";
3144
+ }
3145
+ function isGraphAbortError(error) {
3146
+ return typeof error === "object" && error != null && error.marker === GRAPH_ABORT_ERROR_MARKER;
3147
+ }
3148
+
3149
+ // src/model/SplitRunProcessor.ts
3150
+ function withOptionalDuration2(payload, durationMs, splitRunDurationMs) {
3151
+ return {
3152
+ ...payload,
3153
+ ...durationMs === void 0 ? {} : { durationMs },
3154
+ ...splitRunDurationMs === void 0 ? {} : { splitRunDurationMs }
3155
+ };
3156
+ }
2735
3157
  async function processSplitRunNode(node, processId, deps) {
3158
+ var _a, _b, _c;
2736
3159
  const inputValues = deps.getInputValues(node);
2737
3160
  if (deps.isExcludedDueToControlFlow(node, inputValues, processId)) {
2738
3161
  return;
@@ -2741,7 +3164,9 @@ async function processSplitRunNode(node, processId, deps) {
2741
3164
  (0, import_lodash_es3.max)(values(inputValues).map((value) => Array.isArray(value == null ? void 0 : value.value) ? value == null ? void 0 : value.value.length : 1)) ?? 1,
2742
3165
  node.splitRunMax ?? 10
2743
3166
  );
2744
- deps.emit("nodeStart", { node, inputs: inputValues, processId });
3167
+ await deps.emit("nodeStart", { node, inputs: inputValues, processId });
3168
+ const timingStart = (_a = deps.startNodeTiming) == null ? void 0 : _a.call(deps);
3169
+ let splitRunDurationMs;
2745
3170
  try {
2746
3171
  let results;
2747
3172
  if (node.isSplitSequential) {
@@ -2749,35 +3174,52 @@ async function processSplitRunNode(node, processId, deps) {
2749
3174
  } else {
2750
3175
  results = await runParallel(node, inputValues, splittingAmount, processId, deps);
2751
3176
  }
3177
+ splitRunDurationMs = getSplitRunDurationMs(results);
2752
3178
  const errors = results.filter((r) => r.type === "error").map((r) => r.error);
2753
3179
  if (errors.length === 1) {
2754
3180
  throw errors[0];
2755
3181
  } else if (errors.length > 0) {
3182
+ if (deps.isAborted() && errors.every(isGraphAbortOrAbortLikeError)) {
3183
+ throw deps.getAbortError();
3184
+ }
2756
3185
  throw new AggregateError(errors);
2757
3186
  }
2758
3187
  const aggregateResults = aggregateOutputs(results);
2759
3188
  deps.setNodeResults(node.id, aggregateResults);
2760
3189
  deps.markNodeVisited(node.id);
2761
- deps.emit("nodeFinish", { node, outputs: aggregateResults, processId });
3190
+ await deps.emit(
3191
+ "nodeFinish",
3192
+ withOptionalDuration2(
3193
+ {
3194
+ node,
3195
+ outputs: aggregateResults,
3196
+ processId
3197
+ },
3198
+ (_b = deps.finishNodeTiming) == null ? void 0 : _b.call(deps, timingStart),
3199
+ splitRunDurationMs
3200
+ )
3201
+ );
2762
3202
  } catch (error) {
2763
- deps.nodeErrored(node, error, processId);
3203
+ await deps.nodeErrored(node, error, processId, (_c = deps.finishNodeTiming) == null ? void 0 : _c.call(deps, timingStart), splitRunDurationMs);
2764
3204
  }
2765
3205
  }
2766
3206
  async function runSequential(node, inputValues, splittingAmount, processId, deps) {
3207
+ var _a, _b, _c;
2767
3208
  const results = [];
2768
3209
  for (let i = 0; i < splittingAmount; i++) {
2769
3210
  if (deps.isAborted()) {
2770
- throw new Error("Processing aborted");
3211
+ throw deps.getAbortError();
2771
3212
  }
2772
3213
  const inputs = splitInputsAtIndex(inputValues, i);
3214
+ const splitTimingStart = (_a = deps.startNodeTiming) == null ? void 0 : _a.call(deps);
2773
3215
  try {
2774
3216
  const output = await deps.processNodeWithInputData(node, inputs, i, processId, (n, partialOutputs, index) => {
2775
3217
  deps.emit("partialOutput", { node: n, outputs: partialOutputs, index, processId });
2776
3218
  });
2777
3219
  deps.accumulateCost(output);
2778
- results.push({ type: "output", output });
3220
+ results.push({ type: "output", output, durationMs: (_b = deps.finishNodeTiming) == null ? void 0 : _b.call(deps, splitTimingStart) });
2779
3221
  } catch (error) {
2780
- results.push({ type: "error", error: getError(error) });
3222
+ results.push({ type: "error", error: getError(error), durationMs: (_c = deps.finishNodeTiming) == null ? void 0 : _c.call(deps, splitTimingStart) });
2781
3223
  }
2782
3224
  }
2783
3225
  return results;
@@ -2787,15 +3229,24 @@ async function runParallel(node, inputValues, splittingAmount, processId, deps)
2787
3229
  return Promise.all(
2788
3230
  (0, import_lodash_es3.range)(0, splittingAmount).map(async (i) => {
2789
3231
  const result = await queue.add(async () => {
2790
- const inputs = splitInputsAtIndex(inputValues, i);
3232
+ var _a, _b, _c;
3233
+ const splitTimingStart = (_a = deps.startNodeTiming) == null ? void 0 : _a.call(deps);
2791
3234
  try {
3235
+ if (deps.isAborted()) {
3236
+ throw deps.getAbortError();
3237
+ }
3238
+ const inputs = splitInputsAtIndex(inputValues, i);
2792
3239
  const output = await deps.processNodeWithInputData(node, inputs, i, processId, (n, partialOutputs, index) => {
2793
3240
  deps.emit("partialOutput", { node: n, outputs: partialOutputs, index, processId });
2794
3241
  });
2795
3242
  deps.accumulateCost(output);
2796
- return { type: "output", output };
3243
+ return { type: "output", output, durationMs: (_b = deps.finishNodeTiming) == null ? void 0 : _b.call(deps, splitTimingStart) };
2797
3244
  } catch (error) {
2798
- return { type: "error", error: getError(error) };
3245
+ return {
3246
+ type: "error",
3247
+ error: getError(error),
3248
+ durationMs: (_c = deps.finishNodeTiming) == null ? void 0 : _c.call(deps, splitTimingStart)
3249
+ };
2799
3250
  }
2800
3251
  });
2801
3252
  if (!result) {
@@ -2826,43 +3277,89 @@ function aggregateOutputs(results) {
2826
3277
  return acc;
2827
3278
  }, {});
2828
3279
  }
3280
+ function getSplitRunDurationMs(results) {
3281
+ const durations = {};
3282
+ for (const [index, result] of results.entries()) {
3283
+ if (result.durationMs !== void 0) {
3284
+ durations[index] = result.durationMs;
3285
+ }
3286
+ }
3287
+ return Object.keys(durations).length > 0 ? durations : void 0;
3288
+ }
3289
+ function isGraphAbortOrAbortLikeError(error) {
3290
+ return getGraphAbortReasonFromError(error) != null || isAbortLikeError(error);
3291
+ }
2829
3292
 
2830
3293
  // src/model/NodeExecutionPlanner.ts
2831
- var import_lodash_es4 = require("lodash");
2832
3294
  function getStartNodes(state, graphNodes, runToNodeIds) {
2833
- return runToNodeIds ? graphNodes.filter((node) => runToNodeIds.includes(node.id)) : graphNodes.filter((node) => getOutputNodesFrom(state, node).nodes.length === 0);
3295
+ var _a;
3296
+ if (runToNodeIds) {
3297
+ return graphNodes.filter((node) => runToNodeIds.includes(node.id));
3298
+ }
3299
+ return ((_a = state.executionPlan) == null ? void 0 : _a.startNodes) ?? graphNodes.filter((node) => getOutputNodesFrom(state, node).nodes.length === 0);
2834
3300
  }
2835
3301
  function getInputNodesTo(state, node) {
2836
- var _a;
3302
+ var _a, _b;
3303
+ const plannedInputNodes = (_a = state.executionPlan) == null ? void 0 : _a.inputNodesByNode[node.id];
3304
+ if (plannedInputNodes) {
3305
+ return plannedInputNodes;
3306
+ }
2837
3307
  const connections = state.connections[node.id];
2838
3308
  if (!connections) {
2839
3309
  return [];
2840
3310
  }
2841
- const connectionsToNode = connections.filter((conn) => conn.inputNodeId === node.id).filter(isNotNull);
2842
- const inputDefinitions = ((_a = state.definitions[node.id]) == null ? void 0 : _a.inputs) ?? [];
2843
- return connectionsToNode.filter((connection) => {
2844
- const connectionDefinition = inputDefinitions.find((def) => def.id === connection.inputId);
2845
- return connectionDefinition != null;
2846
- }).map((conn) => state.nodesById[conn.outputNodeId]).filter(isNotNull);
3311
+ const inputDefinitions = ((_b = state.definitions[node.id]) == null ? void 0 : _b.inputs) ?? [];
3312
+ const validInputIds = new Set(inputDefinitions.map((definition) => definition.id));
3313
+ const inputNodes = [];
3314
+ for (const connection of connections) {
3315
+ if (connection.inputNodeId !== node.id || !validInputIds.has(connection.inputId)) {
3316
+ continue;
3317
+ }
3318
+ const inputNode = state.nodesById[connection.outputNodeId];
3319
+ if (inputNode) {
3320
+ inputNodes.push(inputNode);
3321
+ }
3322
+ }
3323
+ return inputNodes;
2847
3324
  }
2848
3325
  function getOutputNodesFrom(state, node) {
2849
- var _a;
3326
+ var _a, _b;
3327
+ const plannedOutputNodes = (_a = state.executionPlan) == null ? void 0 : _a.outputNodeResultsByNode[node.id];
3328
+ if (plannedOutputNodes) {
3329
+ return plannedOutputNodes;
3330
+ }
2850
3331
  const connections = state.connections[node.id];
2851
3332
  if (!connections) {
2852
3333
  return { nodes: [], connections: [], connectionsToNodes: [] };
2853
3334
  }
2854
- const connectionsFromNode = connections.filter((conn) => conn.outputNodeId === node.id);
2855
- const outputDefinitions = ((_a = state.definitions[node.id]) == null ? void 0 : _a.outputs) ?? [];
2856
- const outputConnections = connectionsFromNode.filter((connection) => {
2857
- const connectionDefinition = outputDefinitions.find((def) => def.id === connection.outputId);
2858
- return connectionDefinition != null;
2859
- });
2860
- const outputNodes = (0, import_lodash_es4.uniqBy)(
2861
- outputConnections.map((conn) => state.nodesById[conn.inputNodeId]).filter(isNotNull),
2862
- (candidate) => candidate.id
2863
- );
3335
+ const outputDefinitions = ((_b = state.definitions[node.id]) == null ? void 0 : _b.outputs) ?? [];
3336
+ const validOutputIds = new Set(outputDefinitions.map((definition) => definition.id));
3337
+ const outputConnections = [];
3338
+ const outputConnectionsByNode = /* @__PURE__ */ new Map();
3339
+ const outputNodes = [];
3340
+ const seenOutputNodeIds = /* @__PURE__ */ new Set();
3341
+ for (const connection of connections) {
3342
+ if (connection.outputNodeId !== node.id || !validOutputIds.has(connection.outputId)) {
3343
+ continue;
3344
+ }
3345
+ outputConnections.push(connection);
3346
+ const outputNode = state.nodesById[connection.inputNodeId];
3347
+ if (!outputNode) {
3348
+ continue;
3349
+ }
3350
+ if (!seenOutputNodeIds.has(outputNode.id)) {
3351
+ outputNodes.push(outputNode);
3352
+ seenOutputNodeIds.add(outputNode.id);
3353
+ }
3354
+ const nodeConnections = outputConnectionsByNode.get(outputNode.id);
3355
+ if (nodeConnections) {
3356
+ nodeConnections.push(connection);
3357
+ } else {
3358
+ outputConnectionsByNode.set(outputNode.id, [connection]);
3359
+ }
3360
+ }
2864
3361
  const connectionsToNodes = outputNodes.map((outputNode) => ({
2865
- connections: outputConnections.filter((conn) => conn.inputNodeId === outputNode.id),
3362
+ connections: outputConnectionsByNode.get(outputNode.id) ?? [],
2866
3363
  node: outputNode
2867
3364
  }));
2868
3365
  return { nodes: outputNodes, connections: outputConnections, connectionsToNodes };
@@ -2877,10 +3374,20 @@ function hasErroredInputNode(state, node, inputNodes, onTrace) {
2877
3374
  return false;
2878
3375
  }
2879
3376
  function getMissingRequiredInputs(state, node) {
3377
+ var _a;
3378
+ const plannedMissingInputs = (_a = state.executionPlan) == null ? void 0 : _a.missingRequiredInputsByNode[node.id];
3379
+ if (plannedMissingInputs) {
3380
+ return plannedMissingInputs;
3381
+ }
2880
3382
  const connections = state.connections[node.id] ?? [];
3383
+ const connectedInputIds = /* @__PURE__ */ new Set();
3384
+ for (const connection of connections) {
3385
+ if (connection.inputNodeId === node.id) {
3386
+ connectedInputIds.add(connection.inputId);
3387
+ }
3388
+ }
2881
3389
  return state.definitions[node.id].inputs.filter((input) => {
2882
- const connectionToInput = connections.find((conn) => conn.inputId === input.id && conn.inputNodeId === node.id);
2883
- return input.required && !connectionToInput;
3390
+ return input.required && !connectedInputIds.has(input.id);
2884
3391
  });
2885
3392
  }
2886
3393
  function getWaitingForInputNode(state, node, inputNodes, inputValues) {
@@ -2901,6 +3408,11 @@ function getWaitingForInputNode(state, node, inputNodes, inputValues) {
2901
3408
  return waitingForInputNode;
2902
3409
  }
2903
3410
  function nodesAreInSameCycle(state, a, b) {
3411
+ var _a;
3412
+ const plannedCycleIndexByNode = (_a = state.executionPlan) == null ? void 0 : _a.cycleIndexByNode;
3413
+ if (plannedCycleIndexByNode) {
3414
+ return plannedCycleIndexByNode[a] != null && plannedCycleIndexByNode[a] === plannedCycleIndexByNode[b];
3415
+ }
2904
3416
  return state.stronglyConnectedComponents.find(
2905
3417
  (cycle) => cycle.find((node) => node.id === a) && cycle.find((node) => node.id === b)
2906
3418
  );
@@ -2931,20 +3443,20 @@ function subscribeOwnGraphRunLifecycle(processor, onLifecycleEvent) {
2931
3443
  };
2932
3444
  }
2933
3445
  function wireSubprocessorEvents(processor, parentEmitter, parentState) {
2934
- const unsubscribers = [
2935
- processor.on("nodeError", (event) => parentEmitter.emit("nodeError", event)),
2936
- processor.on("nodeFinish", (event) => parentEmitter.emit("nodeFinish", event)),
2937
- processor.on("partialOutput", (event) => parentEmitter.emit("partialOutput", event)),
2938
- processor.on("nodeExcluded", (event) => parentEmitter.emit("nodeExcluded", event)),
2939
- processor.on("nodeStart", (event) => parentEmitter.emit("nodeStart", event)),
2940
- processor.on("graphAbort", (event) => parentEmitter.emit("graphAbort", event)),
2941
- processor.on("graphError", (event) => parentEmitter.emit("graphError", event)),
2942
- processor.on("userInput", (event) => parentEmitter.emit("userInput", event)),
2943
- processor.on("graphStart", (event) => parentEmitter.emit("graphStart", event)),
2944
- processor.on("graphFinish", (event) => parentEmitter.emit("graphFinish", event)),
2945
- processor.on("nodeOutputsCleared", (event) => parentEmitter.emit("nodeOutputsCleared", event)),
2946
- processor.on("globalSet", (event) => parentEmitter.emit("globalSet", event)),
2947
- processor.on("newAbortController", (event) => parentEmitter.emit("newAbortController", event)),
3446
+ processor.on("nodeError", (event) => parentEmitter.emit("nodeError", event));
3447
+ processor.on("nodeFinish", (event) => parentEmitter.emit("nodeFinish", event));
3448
+ processor.on("partialOutput", (event) => parentEmitter.emit("partialOutput", event));
3449
+ processor.on("nodeExcluded", (event) => parentEmitter.emit("nodeExcluded", event));
3450
+ processor.on("nodeStart", (event) => parentEmitter.emit("nodeStart", event));
3451
+ processor.on("graphAbort", (event) => parentEmitter.emit("graphAbort", event));
3452
+ processor.on("graphError", (event) => parentEmitter.emit("graphError", event));
3453
+ processor.on("userInput", (event) => parentEmitter.emit("userInput", event));
3454
+ processor.on("graphStart", (event) => parentEmitter.emit("graphStart", event));
3455
+ processor.on("graphFinish", (event) => parentEmitter.emit("graphFinish", event));
3456
+ processor.on("nodeOutputsCleared", (event) => parentEmitter.emit("nodeOutputsCleared", event));
3457
+ processor.on("globalSet", (event) => parentEmitter.emit("globalSet", event));
3458
+ processor.on("newAbortController", (event) => parentEmitter.emit("newAbortController", event));
3459
+ const controlUnsubscribers = [
2948
3460
  processor.on("pause", () => {
2949
3461
  if (!parentState.isPaused()) {
2950
3462
  parentState.pause();
@@ -2956,28 +3468,30 @@ function wireSubprocessorEvents(processor, parentEmitter, parentState) {
2956
3468
  }
2957
3469
  })
2958
3470
  ];
2959
- const unsubscribeAny = processor.onAny((event, data) => {
3471
+ processor.onAny((event, data) => {
2960
3472
  if (event.startsWith("globalSet:")) {
2961
3473
  void parentEmitter.emit(event, data);
2962
3474
  }
2963
3475
  });
2964
- let cleanedUp = false;
2965
- const cleanup = () => {
2966
- if (cleanedUp) {
3476
+ let controlsCleanedUp = false;
3477
+ const cleanupControls = () => {
3478
+ if (controlsCleanedUp) {
2967
3479
  return;
2968
3480
  }
2969
- cleanedUp = true;
2970
- unsubscribers.forEach((unsubscribe) => unsubscribe());
3481
+ controlsCleanedUp = true;
3482
+ controlUnsubscribers.forEach((unsubscribe) => unsubscribe());
2971
3483
  };
2972
- unsubscribers.push(unsubscribeAny, subscribeOwnGraphRunLifecycle(processor, cleanup));
3484
+ controlUnsubscribers.push(subscribeOwnGraphRunLifecycle(processor, cleanupControls));
2973
3485
  }
2974
3486
  function wireSubprocessorLifecycle(processor, options2) {
2975
3487
  var _a;
2976
3488
  const abortFromSignal = () => {
2977
- void processor.abort();
3489
+ const abortReason = getGraphAbortReasonFromSignal(options2.signal);
3490
+ void processor.abort((abortReason == null ? void 0 : abortReason.successful) ?? false, abortReason == null ? void 0 : abortReason.error);
2978
3491
  };
2979
3492
  const abortFromParent = () => {
2980
- void processor.abort();
3493
+ const abortReason = getGraphAbortReasonFromSignal(options2.parentAbortSignal);
3494
+ void processor.abort((abortReason == null ? void 0 : abortReason.successful) ?? false, abortReason == null ? void 0 : abortReason.error);
2981
3495
  };
2982
3496
  const pauseProcessor = () => {
2983
3497
  void processor.pause();
@@ -3007,6 +3521,77 @@ function wireSubprocessorLifecycle(processor, options2) {
3007
3521
  unsubscribers.push(subscribeOwnGraphRunLifecycle(processor, cleanup));
3008
3522
  }
3009
3523
 
3524
+ // src/model/NodeExclusionPolicy.ts
3525
+ var nodesAllowedToConsumeExcludedValue = /* @__PURE__ */ new Set([
3526
+ "if",
3527
+ "ifElse",
3528
+ "coalesce",
3529
+ "graphOutput",
3530
+ "raceInputs",
3531
+ "loopController"
3532
+ ]);
3533
+ function isControlFlowExcluded2(value) {
3534
+ return value != null && getScalarTypeOf(value.type) === "control-flow-excluded";
3535
+ }
3536
+ function getControlFlowExclusionDecision({
3537
+ inputValues,
3538
+ node,
3539
+ typeOfExclusion
3540
+ }) {
3541
+ var _a;
3542
+ if (node.disabled) {
3543
+ return {
3544
+ action: "exclude",
3545
+ reason: "disabled",
3546
+ traceMessage: `Excluding node ${node.title} because it's disabled`
3547
+ };
3548
+ }
3549
+ if (node.isConditional && typeOfExclusion === void 0) {
3550
+ const ifValue = coerceTypeOptional(inputValues[IF_PORT.id], "boolean");
3551
+ if (ifValue === false) {
3552
+ return {
3553
+ action: "exclude",
3554
+ reason: "if port is false",
3555
+ traceMessage: `Excluding node ${node.title} because if port is false`
3556
+ };
3557
+ }
3558
+ }
3559
+ const controlFlowExcludedValues = entries(inputValues).filter(
3560
+ ([, value]) => isControlFlowExcluded2(value) && (typeOfExclusion === void 0 || value.value === typeOfExclusion)
3561
+ );
3562
+ const isWaitingForLoop = controlFlowExcludedValues.some(([, value]) => (value == null ? void 0 : value.value) === LOOP_NOT_BROKEN_SENTINEL);
3563
+ const allowedToConsumeExcludedValue = nodesAllowedToConsumeExcludedValue.has(node.type) && !isWaitingForLoop;
3564
+ if (controlFlowExcludedValues.length === 0 || allowedToConsumeExcludedValue) {
3565
+ return { action: "continue" };
3566
+ }
3567
+ if (isWaitingForLoop) {
3568
+ return { action: "defer" };
3569
+ }
3570
+ return {
3571
+ action: "exclude",
3572
+ reason: "input is excluded value",
3573
+ traceMessage: `Excluding node ${node.title} because of control flow. Input is has excluded value: ${(_a = controlFlowExcludedValues[0]) == null ? void 0 : _a[0]}`
3574
+ };
3575
+ }
3576
+ function getMissingRequiredInputExclusion(node, missingRequiredInputs) {
3577
+ const missingInputNames = missingRequiredInputs.map((input) => input.title || input.id).join(", ");
3578
+ return {
3579
+ action: "exclude",
3580
+ reason: "missing required input",
3581
+ traceMessage: `Excluding node ${node.title} because required inputs are not connected: ${missingInputNames}`
3582
+ };
3583
+ }
3584
+ function createExcludedNodeOutputs(node, outputDefinitions) {
3585
+ const outputs = {};
3586
+ for (const output of outputDefinitions) {
3587
+ outputs[output.id] = { type: "control-flow-excluded", value: void 0 };
3588
+ }
3589
+ if (node.type === "loopController") {
3590
+ outputs["break"] = { type: "control-flow-excluded", value: LOOP_NOT_BROKEN_SENTINEL };
3591
+ }
3592
+ return outputs;
3593
+ }
3594
+
3010
3595
  // src/integrations/CodeRunner.ts
3011
3596
  var IsomorphicCodeRunner = class {
3012
3597
  async runCode(code, inputs, options2, graphInputs, contextValues) {
@@ -3055,6 +3640,25 @@ var NotAllowedCodeRunner = class {
3055
3640
  // src/model/GraphProcessor.ts
3056
3641
  var DEFAULT_NODE_CONCURRENCY = 8;
3057
3642
  var DEFAULT_SPLIT_RUN_CONCURRENCY = 4;
3643
+ var DEFAULT_ISOMORPHIC_CODE_RUNNER = new IsomorphicCodeRunner();
3644
+ var FAST_ACYCLIC_UNSUPPORTED_NODE_TYPES = /* @__PURE__ */ new Set([
3645
+ "loopController",
3646
+ "loopUntil",
3647
+ "raceInputs",
3648
+ "userInput",
3649
+ "waitForEvent"
3650
+ ]);
3651
+ function getMonotonicTimeMs() {
3652
+ var _a, _b;
3653
+ return ((_b = (_a = globalThis.performance) == null ? void 0 : _a.now) == null ? void 0 : _b.call(_a)) ?? Date.now();
3654
+ }
3655
+ function withOptionalDuration3(payload, durationMs, splitRunDurationMs) {
3656
+ return {
3657
+ ...payload,
3658
+ ...durationMs === void 0 ? {} : { durationMs },
3659
+ ...splitRunDurationMs === void 0 ? {} : { splitRunDurationMs }
3660
+ };
3661
+ }
3058
3662
  function normalizeConcurrencyValue(value, fallback) {
3059
3663
  return typeof value === "number" && Number.isFinite(value) && value >= 1 ? Math.floor(value) : fallback;
3060
3664
  }
@@ -3064,6 +3668,21 @@ function resolveGraphProcessorConcurrency(concurrency) {
3064
3668
  splitRunConcurrency: normalizeConcurrencyValue(concurrency == null ? void 0 : concurrency.splitRunConcurrency, DEFAULT_SPLIT_RUN_CONCURRENCY)
3065
3669
  };
3066
3670
  }
3671
+ function resolveProcessorGraph(project, graphId) {
3672
+ if (graphId) {
3673
+ return project.graphs[graphId];
3674
+ }
3675
+ return project.metadata.mainGraphId ? project.graphs[project.metadata.mainGraphId] : void 0;
3676
+ }
3677
+ function replaceRecordContents(target, source) {
3678
+ if (target === source) {
3679
+ return;
3680
+ }
3681
+ for (const key of Object.keys(target)) {
3682
+ delete target[key];
3683
+ }
3684
+ Object.assign(target, source);
3685
+ }
3067
3686
  var GraphProcessor = class _GraphProcessor {
3068
3687
  // Per-instance state
3069
3688
  #graph;
@@ -3080,6 +3699,12 @@ var GraphProcessor = class _GraphProcessor {
3080
3699
  #parent;
3081
3700
  #registry;
3082
3701
  #concurrency;
3702
+ #executionPlanCacheMode;
3703
+ #runtimeCache;
3704
+ #cacheLoadedProjects;
3705
+ #scheduler;
3706
+ #captureNodeTimings;
3707
+ #useSeededExecutionPlanOnNextRun = false;
3083
3708
  id = (0, import_non_secure4.nanoid)();
3084
3709
  #includeTrace = true;
3085
3710
  executor;
@@ -3117,13 +3742,15 @@ var GraphProcessor = class _GraphProcessor {
3117
3742
  #aborted = false;
3118
3743
  #abortSuccessfully = false;
3119
3744
  #abortError = void 0;
3745
+ #successfulAbortTerminalProcessIds = void 0;
3120
3746
  #totalCost = 0;
3121
3747
  #ignoreNodes = void 0;
3122
3748
  #hasPreloadedData = false;
3123
3749
  #loadedProjects = void 0;
3124
3750
  #definitions = void 0;
3125
3751
  #scc = void 0;
3126
- // @ts-expect-error
3752
+ #graphExecutionPlan;
3753
+ #nodeProcessContextBase = void 0;
3127
3754
  #nodesNotInCycle = void 0;
3128
3755
  #nodeAbortControllers = /* @__PURE__ */ new Map();
3129
3756
  #graphInputNodeValues = {};
@@ -3134,9 +3761,18 @@ var GraphProcessor = class _GraphProcessor {
3134
3761
  get isRunning() {
3135
3762
  return this.#running;
3136
3763
  }
3764
+ #startNodeTiming() {
3765
+ return this.#captureNodeTimings ? getMonotonicTimeMs() : void 0;
3766
+ }
3767
+ #finishNodeTiming(start) {
3768
+ if (start == null) {
3769
+ return void 0;
3770
+ }
3771
+ return Math.max(0, getMonotonicTimeMs() - start);
3772
+ }
3137
3773
  constructor(project, graphId, registry, includeTrace, options2) {
3138
3774
  this.#project = project;
3139
- const graph = graphId ? project.graphs[graphId] : project.metadata.mainGraphId ? project.graphs[project.metadata.mainGraphId] : void 0;
3775
+ const graph = resolveProcessorGraph(project, graphId);
3140
3776
  if (!graph) {
3141
3777
  throw new Error(`Graph ${graphId} not found in project`);
3142
3778
  }
@@ -3147,26 +3783,92 @@ var GraphProcessor = class _GraphProcessor {
3147
3783
  this.#nodesById = {};
3148
3784
  this.#registry = registry;
3149
3785
  this.#concurrency = resolveGraphProcessorConcurrency(options2 == null ? void 0 : options2.concurrency);
3786
+ this.#executionPlanCacheMode = (options2 == null ? void 0 : options2.executionPlanCacheMode) ?? "all";
3787
+ this.#runtimeCache = options2 == null ? void 0 : options2.runtimeCache;
3788
+ this.#cacheLoadedProjects = (options2 == null ? void 0 : options2.cacheLoadedProjects) ?? false;
3789
+ this.#scheduler = (options2 == null ? void 0 : options2.scheduler) ?? "compatible";
3790
+ this.#captureNodeTimings = (options2 == null ? void 0 : options2.captureNodeTimings) ?? false;
3150
3791
  this.#emitter.bindMethods(this, ["on", "off", "once", "onAny", "offAny"]);
3151
3792
  this.setExternalFunction("echo", async (value) => ({ type: "any", value }));
3152
3793
  this.#emitter.on("globalSet", ({ id, value }) => {
3153
3794
  emitDetached(this.#emitter, `globalSet:${id}`, value);
3154
3795
  });
3796
+ if (options2 == null ? void 0 : options2.initialExecutionPlan) {
3797
+ this.#applyPreprocessedGraph(options2.initialExecutionPlan, { recreateNodeInstances: true });
3798
+ this.#useSeededExecutionPlanOnNextRun = true;
3799
+ }
3155
3800
  }
3156
3801
  #preprocessGraph() {
3802
+ var _a;
3803
+ const runtimeCache = this.#canUseRuntimeExecutionPlanCache() ? this.#runtimeCache : void 0;
3804
+ const shouldUseRuntimeCache = runtimeCache != null;
3805
+ const cachedPlan = (_a = runtimeCache == null ? void 0 : runtimeCache.executionPlans) == null ? void 0 : _a.get(this.#graph);
3806
+ if (cachedPlan) {
3807
+ this.#applyPreprocessedGraph(cachedPlan, { recreateNodeInstances: true });
3808
+ return;
3809
+ }
3157
3810
  const preprocessedGraph = preprocessGraphState({
3158
3811
  graph: this.#graph,
3159
3812
  loadedProjects: this.#loadedProjects,
3160
3813
  project: this.#project,
3161
3814
  registry: this.#registry,
3162
- warnOnInvalidGraph: this.warnOnInvalidGraph
3815
+ warnOnInvalidGraph: this.warnOnInvalidGraph,
3816
+ buildExecutionPlan: shouldUseRuntimeCache,
3817
+ definitionContext: this.#runtimeCache ? {
3818
+ getGraphBoundary: (project, graphId) => this.#getGraphBoundary(project, graphId)
3819
+ } : void 0
3163
3820
  });
3164
- Object.assign(this.#nodeInstances, preprocessedGraph.nodeInstances);
3165
- Object.assign(this.#nodesById, preprocessedGraph.nodesById);
3166
- Object.assign(this.#connections, preprocessedGraph.connections);
3821
+ if (shouldUseRuntimeCache && isGraphExecutionPlan(preprocessedGraph)) {
3822
+ runtimeCache.executionPlans ??= /* @__PURE__ */ new WeakMap();
3823
+ runtimeCache.executionPlans.set(this.#graph, toReusableGraphExecutionPlan(preprocessedGraph));
3824
+ }
3825
+ this.#applyPreprocessedGraph(preprocessedGraph);
3826
+ }
3827
+ #canUseRuntimeExecutionPlanCache() {
3828
+ return this.#canUseRuntimeExecutionPlanCacheFor(this.#project, this.#isSubProcessor);
3829
+ }
3830
+ #canUseRuntimeExecutionPlanCacheFor(project, isSubProcessor) {
3831
+ var _a;
3832
+ if (this.warnOnInvalidGraph || this.#runtimeCache == null) {
3833
+ return false;
3834
+ }
3835
+ if (this.#executionPlanCacheMode === "subprocessors" && !isSubProcessor) {
3836
+ return false;
3837
+ }
3838
+ if (!this.#cacheLoadedProjects && (((_a = project.references) == null ? void 0 : _a.length) ?? 0) > 0) {
3839
+ return false;
3840
+ }
3841
+ return true;
3842
+ }
3843
+ #getGraphBoundary(project, graphId) {
3844
+ if (!this.#runtimeCache) {
3845
+ return getGraphBoundary(project, graphId);
3846
+ }
3847
+ this.#runtimeCache.graphBoundaries ??= /* @__PURE__ */ new WeakMap();
3848
+ return getGraphBoundary(project, graphId, this.#runtimeCache.graphBoundaries);
3849
+ }
3850
+ #applyPreprocessedGraph(preprocessedGraph, options2 = {}) {
3851
+ const nodeInstances = options2.recreateNodeInstances || !("nodeInstances" in preprocessedGraph) ? this.#createNodeInstances(isGraphExecutionPlan(preprocessedGraph) ? preprocessedGraph.graphNodes : this.#graph.nodes) : preprocessedGraph.nodeInstances;
3852
+ replaceRecordContents(this.#nodeInstances, nodeInstances);
3853
+ replaceRecordContents(this.#nodesById, preprocessedGraph.nodesById);
3854
+ replaceRecordContents(this.#connections, preprocessedGraph.connections);
3167
3855
  this.#definitions = preprocessedGraph.definitions;
3168
3856
  this.#scc = preprocessedGraph.stronglyConnectedComponents;
3169
3857
  this.#nodesNotInCycle = preprocessedGraph.nodesNotInCycle;
3858
+ this.#graphExecutionPlan = isGraphExecutionPlan(preprocessedGraph) ? preprocessedGraph : void 0;
3859
+ }
3860
+ #seededExecutionPlanForNextRun() {
3861
+ if (!this.#useSeededExecutionPlanOnNextRun || this.warnOnInvalidGraph) {
3862
+ return void 0;
3863
+ }
3864
+ return this.#graphExecutionPlan;
3865
+ }
3866
+ #createNodeInstances(nodes) {
3867
+ const nodeInstances = {};
3868
+ for (const node of nodes) {
3869
+ nodeInstances[node.id] = this.#registry.createDynamicImpl(node);
3870
+ }
3871
+ return nodeInstances;
3170
3872
  }
3171
3873
  #emitTraceEvent(eventData) {
3172
3874
  if (this.#includeTrace) {
@@ -3233,7 +3935,9 @@ var GraphProcessor = class _GraphProcessor {
3233
3935
  }
3234
3936
  this.#abortSuccessfully = successful;
3235
3937
  this.#abortError = error;
3236
- this.#abortController.abort();
3938
+ const abortReason = createGraphAbortReason(successful, error);
3939
+ this.#abortController.abort(abortReason);
3940
+ this.#abortActiveNodeControllers(abortReason);
3237
3941
  emitDetached(this.#emitter, "graphAbort", this.#withExecution({ successful, error, graph: this.#graph }));
3238
3942
  if (!this.#isSubProcessor) {
3239
3943
  emitDetached(this.#emitter, "abort", { successful, error });
@@ -3322,6 +4026,7 @@ var GraphProcessor = class _GraphProcessor {
3322
4026
  this.#preprocessGraph();
3323
4027
  }
3324
4028
  #collectDependencyNodesDeep(nodeId, dependencyNodes) {
4029
+ var _a;
3325
4030
  if (dependencyNodes.has(nodeId)) {
3326
4031
  return;
3327
4032
  }
@@ -3330,7 +4035,7 @@ var GraphProcessor = class _GraphProcessor {
3330
4035
  return;
3331
4036
  }
3332
4037
  dependencyNodes.add(nodeId);
3333
- const connections = this.#connections[nodeId] ?? [];
4038
+ const connections = ((_a = this.#graphExecutionPlan) == null ? void 0 : _a.inputConnectionsByNode[nodeId]) ?? this.#connections[nodeId] ?? [];
3334
4039
  for (const connection of connections) {
3335
4040
  if (connection.inputNodeId === nodeId) {
3336
4041
  this.#collectDependencyNodesDeep(connection.outputNodeId, dependencyNodes);
@@ -3367,6 +4072,7 @@ var GraphProcessor = class _GraphProcessor {
3367
4072
  return this.#graphOutputs;
3368
4073
  }
3369
4074
  #initProcessState() {
4075
+ var _a, _b;
3370
4076
  this.#running = true;
3371
4077
  this.#finishEmitted = false;
3372
4078
  if (!this.#hasPreloadedData) {
@@ -3375,7 +4081,10 @@ var GraphProcessor = class _GraphProcessor {
3375
4081
  }
3376
4082
  this.#erroredNodes = /* @__PURE__ */ new Map();
3377
4083
  this.#currentlyProcessing = /* @__PURE__ */ new Set();
3378
- this.#remainingNodes = new Set(this.#graph.nodes.map((n) => n.id));
4084
+ const seededExecutionPlan = this.#seededExecutionPlanForNextRun();
4085
+ this.#remainingNodes = new Set(
4086
+ seededExecutionPlan ? seededExecutionPlan.nodeIds : this.#graph.nodes.map((node) => node.id)
4087
+ );
3379
4088
  this.#pendingUserInputs = {};
3380
4089
  this.#processingQueue = new pQueueCompat_default({ concurrency: this.#concurrency.nodeConcurrency });
3381
4090
  this.#graphOutputs = {};
@@ -3386,6 +4095,7 @@ var GraphProcessor = class _GraphProcessor {
3386
4095
  this.#attachedNodeData = /* @__PURE__ */ new Map();
3387
4096
  this.#globals ??= /* @__PURE__ */ new Map();
3388
4097
  this.#ignoreNodes = /* @__PURE__ */ new Set();
4098
+ this.#nodeProcessContextBase = void 0;
3389
4099
  this.#abortController = this.#newAbortController();
3390
4100
  this.#abortController.signal.addEventListener("abort", () => {
3391
4101
  this.#aborted = true;
@@ -3393,8 +4103,14 @@ var GraphProcessor = class _GraphProcessor {
3393
4103
  this.#aborted = false;
3394
4104
  this.#abortError = void 0;
3395
4105
  this.#abortSuccessfully = false;
4106
+ this.#successfulAbortTerminalProcessIds = /* @__PURE__ */ new Set();
3396
4107
  this.#nodeAbortControllers = /* @__PURE__ */ new Map();
3397
- this.#loadedProjects = {};
4108
+ this.#loadedProjects = this.#cacheLoadedProjects && ((_a = this.#runtimeCache) == null ? void 0 : _a.loadedProjects) ? { ...this.#runtimeCache.loadedProjects } : {};
4109
+ if (!this.#cacheLoadedProjects && (((_b = this.#project.references) == null ? void 0 : _b.length) ?? 0) > 0) {
4110
+ if (this.#runtimeCache) {
4111
+ this.#runtimeCache.graphBoundaries = void 0;
4112
+ }
4113
+ }
3398
4114
  this.#graphInputNodeValues = {};
3399
4115
  }
3400
4116
  /** Main function for running a graph. Runs a graph and returns the outputs from the output nodes of the graph. */
@@ -3405,13 +4121,22 @@ var GraphProcessor = class _GraphProcessor {
3405
4121
  try {
3406
4122
  this.#initializeGraphRun(context, inputs, contextValues);
3407
4123
  await this.#loadProjectReferences();
3408
- this.#preprocessGraph();
4124
+ this.#prepareNodeProcessContextBase();
4125
+ const shouldUseSeededExecutionPlan = this.#seededExecutionPlanForNextRun() != null;
4126
+ this.#useSeededExecutionPlanOnNextRun = false;
4127
+ if (!shouldUseSeededExecutionPlan) {
4128
+ this.#preprocessGraph();
4129
+ }
3409
4130
  await this.#emitGraphStart();
3410
4131
  await this.#emitPreloadedNodeResults();
3411
4132
  await this.#waitUntilUnpaused();
3412
- await this.#queueStartNodes(getStartNodes(this.#executionState, this.#graph.nodes, this.runToNodeIds));
3413
- await this.#processingQueue.onIdle();
3414
- this.#markUnqueuedNodesIgnored();
4133
+ if (this.#canUseFastAcyclicScheduler()) {
4134
+ await this.#processFastAcyclicGraph();
4135
+ } else {
4136
+ await this.#queueStartNodes(getStartNodes(this.#executionState, this.#graph.nodes, this.runToNodeIds));
4137
+ await this.#processingQueue.onIdle();
4138
+ this.#markUnqueuedNodesIgnored();
4139
+ }
3415
4140
  await this.#throwIfGraphErrored();
3416
4141
  return await this.#finalizeGraphRun();
3417
4142
  } finally {
@@ -3441,6 +4166,39 @@ var GraphProcessor = class _GraphProcessor {
3441
4166
  });
3442
4167
  this.#unsubscribeTokenizerError = typeof unsubscribeTokenizerError === "function" ? unsubscribeTokenizerError : void 0;
3443
4168
  }
4169
+ #prepareNodeProcessContextBase() {
4170
+ this.#nodeProcessContextBase = {
4171
+ ...this.#context,
4172
+ abortGraph: (error) => {
4173
+ void this.abort(error === void 0, error);
4174
+ },
4175
+ codeRunner: this.#context.codeRunner ?? DEFAULT_ISOMORPHIC_CODE_RUNNER,
4176
+ contextValues: this.#contextValues,
4177
+ executionCache: this.#executionCache,
4178
+ executor: this.executor ?? "nodejs",
4179
+ getGlobal: (id) => this.#globals.get(id),
4180
+ getGraphBoundary: (project, graphId) => this.#getGraphBoundary(project, graphId),
4181
+ graphInputNodeValues: this.#graphInputNodeValues,
4182
+ graphInputs: this.#graphInputs,
4183
+ graphOutputs: this.#graphOutputs,
4184
+ project: this.#project,
4185
+ raiseEvent: (event, data) => {
4186
+ this.getRootProcessor().raiseEvent(event, data);
4187
+ },
4188
+ referencedProjects: this.#loadedProjects,
4189
+ tokenizer: this.#getTokenizer(),
4190
+ trace: (message) => {
4191
+ this.#emitTraceEvent(message);
4192
+ },
4193
+ waitForGlobal: async (id) => {
4194
+ if (this.#globals.has(id)) {
4195
+ return this.#globals.get(id);
4196
+ }
4197
+ await this.getRootProcessor().#emitter.once(`globalSet:${id}`);
4198
+ return this.#globals.get(id);
4199
+ }
4200
+ };
4201
+ }
3444
4202
  #cleanupTokenizerErrorListener() {
3445
4203
  const unsubscribeTokenizerError = this.#unsubscribeTokenizerError;
3446
4204
  this.#unsubscribeTokenizerError = void 0;
@@ -3498,6 +4256,87 @@ var GraphProcessor = class _GraphProcessor {
3498
4256
  });
3499
4257
  }
3500
4258
  }
4259
+ #canUseFastAcyclicScheduler() {
4260
+ if (this.#scheduler !== "fast-acyclic") {
4261
+ return false;
4262
+ }
4263
+ if (this.#hasPreloadedData || this.runToNodeIds || this.slowMode || this.#includeTrace) {
4264
+ return false;
4265
+ }
4266
+ if (this.#nodesNotInCycle.length !== this.#graph.nodes.length) {
4267
+ return false;
4268
+ }
4269
+ if (this.#graph.connections.some((connection) => connection.inputNodeId === connection.outputNodeId)) {
4270
+ return false;
4271
+ }
4272
+ return this.#graph.nodes.every((node) => {
4273
+ if (node.isSplitRun) {
4274
+ return false;
4275
+ }
4276
+ return !FAST_ACYCLIC_UNSUPPORTED_NODE_TYPES.has(node.type);
4277
+ });
4278
+ }
4279
+ async #processFastAcyclicGraph() {
4280
+ const remainingInputsByNode = /* @__PURE__ */ new Map();
4281
+ const readyNodes = [];
4282
+ const queuedNodeIds = /* @__PURE__ */ new Set();
4283
+ for (const node of this.#graph.nodes) {
4284
+ const inputNodeIds = /* @__PURE__ */ new Set();
4285
+ for (const inputNode of getInputNodesTo(this.#executionState, node)) {
4286
+ inputNodeIds.add(inputNode.id);
4287
+ }
4288
+ const inputCount = inputNodeIds.size;
4289
+ remainingInputsByNode.set(node.id, inputCount);
4290
+ if (inputCount === 0) {
4291
+ readyNodes.push(node);
4292
+ queuedNodeIds.add(node.id);
4293
+ }
4294
+ }
4295
+ await new Promise((resolve, reject) => {
4296
+ let activeCount = 0;
4297
+ let settled = false;
4298
+ const queueReadyOutputs = (outputNodes) => {
4299
+ for (const outputNode of outputNodes) {
4300
+ const remainingInputs = (remainingInputsByNode.get(outputNode.id) ?? 0) - 1;
4301
+ remainingInputsByNode.set(outputNode.id, remainingInputs);
4302
+ if (remainingInputs <= 0 && !queuedNodeIds.has(outputNode.id)) {
4303
+ readyNodes.push(outputNode);
4304
+ queuedNodeIds.add(outputNode.id);
4305
+ }
4306
+ }
4307
+ };
4308
+ const settle = () => {
4309
+ if (settled) {
4310
+ return;
4311
+ }
4312
+ if (activeCount === 0 && readyNodes.length === 0) {
4313
+ settled = true;
4314
+ resolve();
4315
+ }
4316
+ };
4317
+ const pump = () => {
4318
+ if (settled) {
4319
+ return;
4320
+ }
4321
+ while (activeCount < this.#concurrency.nodeConcurrency && readyNodes.length > 0) {
4322
+ const node = readyNodes.shift();
4323
+ activeCount += 1;
4324
+ void this.#processNodeIfAllInputsAvailable(node, { queueOutputNodes: false }).then(queueReadyOutputs).then(() => {
4325
+ activeCount -= 1;
4326
+ pump();
4327
+ settle();
4328
+ }).catch((error) => {
4329
+ if (!settled) {
4330
+ settled = true;
4331
+ reject(error);
4332
+ }
4333
+ });
4334
+ }
4335
+ settle();
4336
+ };
4337
+ pump();
4338
+ });
4339
+ }
3501
4340
  #markUnqueuedNodesIgnored() {
3502
4341
  if (!this.runToNodeIds) {
3503
4342
  return;
@@ -3558,8 +4397,12 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
3558
4397
  return outputValues;
3559
4398
  }
3560
4399
  async #loadProjectReferences() {
3561
- var _a;
4400
+ var _a, _b;
3562
4401
  if ((((_a = this.#project.references) == null ? void 0 : _a.length) ?? 0) > 0) {
4402
+ if (this.#cacheLoadedProjects && ((_b = this.#runtimeCache) == null ? void 0 : _b.loadedProjects)) {
4403
+ this.#loadedProjects = { ...this.#runtimeCache.loadedProjects };
4404
+ return;
4405
+ }
3563
4406
  if (!this.#context.projectReferenceLoader) {
3564
4407
  throw new Error(
3565
4408
  "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."
@@ -3580,6 +4423,9 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
3580
4423
  for (const reference of this.#project.references) {
3581
4424
  await loadProject(reference);
3582
4425
  }
4426
+ if (this.#cacheLoadedProjects && this.#runtimeCache) {
4427
+ this.#runtimeCache.loadedProjects = { ...this.#loadedProjects };
4428
+ }
3583
4429
  }
3584
4430
  }
3585
4431
  /** Returns true if any input node has errored. Optionally emits a trace event. */
@@ -3602,10 +4448,6 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
3602
4448
  this.#totalCost += coerceTypeOptional(output["cost"], "number") ?? 0;
3603
4449
  }
3604
4450
  }
3605
- /** Checks if a data value represents a control-flow-excluded signal. */
3606
- #isControlFlowExcluded(value) {
3607
- return value != null && getScalarTypeOf(value.type) === "control-flow-excluded";
3608
- }
3609
4451
  async #fetchNodeDataAndProcessNode(node) {
3610
4452
  var _a;
3611
4453
  if (this.#currentlyProcessing.has(node.id) || this.#queuedNodes.has(node.id)) {
@@ -3646,39 +4488,50 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
3646
4488
  await this.#processNodeIfAllInputsAvailable(node);
3647
4489
  }
3648
4490
  /** If all inputs are present, all conditions met, processes the node. */
3649
- async #processNodeIfAllInputsAvailable(node) {
4491
+ async #processNodeIfAllInputsAvailable(node, options2 = {}) {
4492
+ const { queueOutputNodes = true } = options2;
3650
4493
  const builtInNode = node;
3651
4494
  const inputNodes = getInputNodesTo(this.#executionState, node);
3652
4495
  if (this.#shouldSkipNodeProcessing(node, inputNodes)) {
3653
- return;
4496
+ return [];
3654
4497
  }
3655
4498
  const attachedData = this.#getAttachedDataTo(node);
3656
4499
  if (this.#shouldSkipCompletedRaceNode(node, attachedData)) {
3657
- return;
4500
+ return [];
3658
4501
  }
3659
4502
  const inputValues = this.#getInputValuesForNode(node);
3660
- if (this.#excludedDueToControlFlow(node, inputValues, (0, import_non_secure4.nanoid)(), LOOP_NOT_BROKEN_SENTINEL)) {
4503
+ const loopExclusion = this.#excludedDueToControlFlow(
4504
+ node,
4505
+ inputValues,
4506
+ (0, import_non_secure4.nanoid)(),
4507
+ LOOP_NOT_BROKEN_SENTINEL,
4508
+ { queueOutputNodes }
4509
+ );
4510
+ if (loopExclusion) {
3661
4511
  this.#emitTraceEvent(`Node ${node.title} is excluded due to control flow`);
3662
- return;
4512
+ return loopExclusion === true ? [] : loopExclusion;
3663
4513
  }
3664
4514
  const waitingForInputNode = getWaitingForInputNode(this.#executionState, node, inputNodes, inputValues);
3665
4515
  if (waitingForInputNode) {
3666
4516
  this.#emitTraceEvent(`Node ${node.title} is waiting for input node ${waitingForInputNode}`);
3667
- return;
4517
+ return [];
3668
4518
  }
3669
- if (this.#excludedDueToControlFlow(node, inputValues, (0, import_non_secure4.nanoid)())) {
4519
+ const exclusion = this.#excludedDueToControlFlow(node, inputValues, (0, import_non_secure4.nanoid)(), void 0, {
4520
+ queueOutputNodes
4521
+ });
4522
+ if (exclusion) {
3670
4523
  this.#emitTraceEvent(`Node ${node.title} is excluded due to control flow`);
3671
- return;
4524
+ return exclusion === true ? [] : exclusion;
3672
4525
  }
3673
4526
  const missingRequiredInputs = this.#getMissingRequiredInputs(node);
3674
4527
  if (missingRequiredInputs.length > 0) {
3675
- this.#excludeNodeWithMissingRequiredInputs(node, inputValues, missingRequiredInputs);
3676
- return;
4528
+ return this.#excludeNodeWithMissingRequiredInputs(node, inputValues, missingRequiredInputs, { queueOutputNodes });
3677
4529
  }
3678
4530
  if (this.#beginNodeProcessing(node, attachedData) === false) {
3679
- return;
4531
+ return [];
3680
4532
  }
3681
- const processId = await this.#processNode(node);
4533
+ const processResult = await this.#processNode(node);
4534
+ const { processId } = processResult;
3682
4535
  if (this.slowMode) {
3683
4536
  await new Promise((resolve) => setTimeout(resolve, 250));
3684
4537
  }
@@ -3689,11 +4542,16 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
3689
4542
  const outputNodes = getOutputNodesFrom(this.#executionState, node);
3690
4543
  this.#handleLoopControllerPostProcess(node, attachedData);
3691
4544
  this.#handleCompletedRace(node);
3692
- if (!this.#assignChildLoopInfo(node, builtInNode, attachedData, processId)) {
3693
- return;
4545
+ const childLoopInfoError = this.#assignChildLoopInfo(node, builtInNode, attachedData);
4546
+ if (childLoopInfoError) {
4547
+ await this.#nodeErrored(node, childLoopInfoError, processId);
4548
+ return [];
3694
4549
  }
3695
4550
  this.#propagateAttachedDataToOutputNodes(node, attachedData, outputNodes.connectionsToNodes);
3696
- this.#queueOutputNodes(node, outputNodes.nodes);
4551
+ if (queueOutputNodes && processResult.shouldQueueOutputNodes) {
4552
+ this.#queueOutputNodes(node, outputNodes.nodes);
4553
+ }
4554
+ return processResult.shouldQueueOutputNodes ? outputNodes.nodes : [];
3697
4555
  }
3698
4556
  #shouldSkipNodeProcessing(node, inputNodes) {
3699
4557
  if (this.#ignoreNodes.has(node.id)) {
@@ -3724,11 +4582,11 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
3724
4582
  }
3725
4583
  return false;
3726
4584
  }
3727
- #excludeNodeWithMissingRequiredInputs(node, inputValues, missingRequiredInputs) {
3728
- const missingInputNames = missingRequiredInputs.map((input) => input.title || input.id).join(", ");
4585
+ #excludeNodeWithMissingRequiredInputs(node, inputValues, missingRequiredInputs, options2 = {}) {
4586
+ const exclusion = getMissingRequiredInputExclusion(node, missingRequiredInputs);
3729
4587
  const processId = (0, import_non_secure4.nanoid)();
3730
- this.#emitTraceEvent(`Excluding node ${node.title} because required inputs are not connected: ${missingInputNames}`);
3731
- this.#excludeNode(node, processId, inputValues, "missing required input");
4588
+ this.#emitTraceEvent(exclusion.traceMessage);
4589
+ return this.#excludeNode(node, processId, inputValues, exclusion.reason, options2);
3732
4590
  }
3733
4591
  #beginNodeProcessing(node, attachedData) {
3734
4592
  if (this.#shouldSkipCompletedRaceNode(node, attachedData)) {
@@ -3780,31 +4638,30 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
3780
4638
  if (node.type !== "raceInputs") {
3781
4639
  return;
3782
4640
  }
4641
+ const raceId = `race-${node.id}`;
3783
4642
  const allNodesForRace = [...this.#attachedNodeData.entries()].filter(
3784
- ([, { races }]) => races == null ? void 0 : races.raceIds.includes(`race-${node.id}`)
4643
+ ([, { races }]) => races == null ? void 0 : races.raceIds.includes(raceId)
3785
4644
  );
3786
- for (const [nodeId] of allNodesForRace) {
3787
- for (const [key, abortController] of this.#nodeAbortControllers.entries()) {
3788
- if (key.startsWith(nodeId)) {
3789
- this.#emitTraceEvent(`Aborting node ${nodeId} because other race branch won`);
3790
- abortController.abort();
3791
- }
3792
- }
3793
- for (const [, nodeAttachedData] of [...this.#attachedNodeData.entries()]) {
3794
- if ((_a = nodeAttachedData.races) == null ? void 0 : _a.raceIds.includes(`race-${node.id}`)) {
3795
- nodeAttachedData.races.completed = true;
3796
- }
4645
+ for (const [, nodeAttachedData] of allNodesForRace) {
4646
+ if ((_a = nodeAttachedData.races) == null ? void 0 : _a.raceIds.includes(raceId)) {
4647
+ nodeAttachedData.races.completed = true;
3797
4648
  }
3798
4649
  }
4650
+ for (const [nodeId] of allNodesForRace) {
4651
+ this.#abortNodeControllersForNode(
4652
+ nodeId,
4653
+ `Aborting node ${nodeId} because other race branch won`,
4654
+ createGraphAbortReason(true, RACE_LOSER_EXCLUSION_REASON)
4655
+ );
4656
+ }
3799
4657
  }
3800
- #assignChildLoopInfo(node, builtInNode, attachedData, processId) {
4658
+ #assignChildLoopInfo(node, builtInNode, attachedData) {
3801
4659
  if (builtInNode.type !== "loopController") {
3802
- return true;
4660
+ return void 0;
3803
4661
  }
3804
4662
  let childLoopInfo = attachedData.loopInfo;
3805
4663
  if (childLoopInfo != null && childLoopInfo.loopControllerId !== builtInNode.id) {
3806
- this.#nodeErrored(node, new Error("Nested loops are not supported"), processId);
3807
- return false;
4664
+ return new Error("Nested loops are not supported");
3808
4665
  }
3809
4666
  childLoopInfo = {
3810
4667
  propagate: (parent, connectionsFromParent) => {
@@ -3818,7 +4675,7 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
3818
4675
  iterationCount: ((childLoopInfo == null ? void 0 : childLoopInfo.iterationCount) ?? 0) + 1
3819
4676
  };
3820
4677
  attachedData.loopInfo = childLoopInfo;
3821
- return true;
4678
+ return void 0;
3822
4679
  }
3823
4680
  #propagateAttachedDataToOutputNodes(node, attachedData, outputConnections) {
3824
4681
  for (const { node: outputNode, connections: connectionsToOutputNode } of outputConnections) {
@@ -3857,39 +4714,39 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
3857
4714
  async #processNode(node) {
3858
4715
  const processId = (0, import_non_secure4.nanoid)();
3859
4716
  if (this.#abortController.signal.aborted) {
3860
- this.#nodeErrored(node, new Error("Processing aborted"), processId);
3861
- return processId;
3862
- }
3863
- const inputNodes = getInputNodesTo(this.#executionState, node);
3864
- const erroredInputNodes = inputNodes.filter((inputNode) => this.#erroredNodes.has(inputNode.id));
3865
- if (erroredInputNodes.length > 0) {
3866
- const error = new Error(
3867
- `Cannot process node ${node.title} (${node.id}) because it depends on errored nodes: ${erroredInputNodes.map((n) => `${n.title} (${n.id})`).join(", ")}`
3868
- );
3869
- this.#nodeErrored(node, error, processId);
3870
- return processId;
4717
+ await this.#nodeErrored(node, createGraphAbortErrorFromSignal(this.#abortController.signal), processId);
4718
+ this.#successfulAbortTerminalProcessIds.delete(processId);
4719
+ return { processId, shouldQueueOutputNodes: false };
3871
4720
  }
3872
4721
  if (node.isSplitRun) {
3873
4722
  await this.#processSplitRunNode(node, processId);
3874
4723
  } else {
3875
4724
  await this.#processNormalNode(node, processId);
3876
4725
  }
3877
- return processId;
4726
+ const successfulAbortTerminal = this.#successfulAbortTerminalProcessIds.delete(processId);
4727
+ return { processId, shouldQueueOutputNodes: !successfulAbortTerminal };
3878
4728
  }
3879
4729
  async #processSplitRunNode(node, processId) {
3880
4730
  return processSplitRunNode(node, processId, {
3881
4731
  getInputValues: (n) => this.#getInputValuesForNode(n),
3882
- isExcludedDueToControlFlow: (n, inputs, pid) => this.#excludedDueToControlFlow(n, inputs, pid),
4732
+ isExcludedDueToControlFlow: (n, inputs, pid) => this.#excludedDueToControlFlow(n, inputs, pid) !== false,
3883
4733
  processNodeWithInputData: (n, inputs, idx, pid, partial) => this.#processNodeWithInputData(n, inputs, idx, pid, partial),
3884
4734
  splitRunConcurrency: this.#concurrency.splitRunConcurrency,
3885
4735
  accumulateCost: (output) => this.#accumulateCost(output),
3886
4736
  setNodeResults: (nodeId, outputs) => this.#nodeResults.set(nodeId, outputs),
3887
4737
  markNodeVisited: (nodeId) => this.#visitedNodes.add(nodeId),
3888
- nodeErrored: (n, err, pid) => this.#nodeErrored(n, err, pid),
4738
+ nodeErrored: (n, err, pid, durationMs, splitRunDurationMs) => this.#nodeErrored(n, err, pid, durationMs, splitRunDurationMs),
3889
4739
  isAborted: () => this.#aborted,
4740
+ getAbortError: () => createGraphAbortErrorFromSignal(this.#abortController.signal),
3890
4741
  emit: (event, data) => {
3891
- emitDetached(this.#emitter, event, this.#withExecution(data));
3892
- }
4742
+ if (event === "partialOutput") {
4743
+ emitDetached(this.#emitter, event, this.#withExecution(data));
4744
+ return;
4745
+ }
4746
+ return this.#emitter.emit(event, this.#withExecution(data));
4747
+ },
4748
+ startNodeTiming: this.#captureNodeTimings ? () => this.#startNodeTiming() : void 0,
4749
+ finishNodeTiming: this.#captureNodeTimings ? (start) => this.#finishNodeTiming(start) : void 0
3893
4750
  });
3894
4751
  }
3895
4752
  async #processNormalNode(node, processId) {
@@ -3898,6 +4755,7 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
3898
4755
  return;
3899
4756
  }
3900
4757
  await this.#emitter.emit("nodeStart", this.#withExecution({ node, inputs: inputValues, processId }));
4758
+ const timingStart = this.#startNodeTiming();
3901
4759
  try {
3902
4760
  const outputValues = await this.#processNodeWithInputData(
3903
4761
  node,
@@ -3915,16 +4773,59 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
3915
4773
  this.#nodeResults.set(node.id, outputValues);
3916
4774
  this.#visitedNodes.add(node.id);
3917
4775
  this.#accumulateCost(outputValues);
3918
- await this.#emitter.emit("nodeFinish", this.#withExecution({ node, outputs: outputValues, processId }));
4776
+ await this.#emitter.emit(
4777
+ "nodeFinish",
4778
+ this.#withExecution(
4779
+ withOptionalDuration3(
4780
+ {
4781
+ node,
4782
+ outputs: outputValues,
4783
+ processId
4784
+ },
4785
+ this.#finishNodeTiming(timingStart)
4786
+ )
4787
+ )
4788
+ );
3919
4789
  } catch (error) {
3920
- this.#nodeErrored(node, error, processId);
4790
+ await this.#nodeErrored(node, error, processId, this.#finishNodeTiming(timingStart));
3921
4791
  }
3922
4792
  }
3923
- #nodeErrored(node, e, processId) {
4793
+ async #nodeErrored(node, e, processId, durationMs, splitRunDurationMs) {
3924
4794
  const error = getError(e);
3925
- emitDetached(this.#emitter, "nodeError", this.#withExecution({ node, error, processId }));
3926
- this.#emitTraceEvent(`Node ${node.title} (${node.id}-${processId}) errored: ${error.stack}`);
4795
+ const exclusionReason = this.#getErrorExclusionReason(node, error, processId);
4796
+ if (exclusionReason) {
4797
+ await this.#emitNodeExcluded(node, processId, this.#getInputValuesForNode(node), exclusionReason);
4798
+ this.#emitTraceEvent(`Node ${node.title} (${node.id}-${processId}) was excluded: ${exclusionReason}`);
4799
+ return;
4800
+ }
3927
4801
  this.#erroredNodes.set(node.id, error);
4802
+ await this.#emitter.emit(
4803
+ "nodeError",
4804
+ this.#withExecution(withOptionalDuration3({ node, error, processId }, durationMs, splitRunDurationMs))
4805
+ );
4806
+ this.#emitTraceEvent(`Node ${node.title} (${node.id}-${processId}) errored: ${error.stack}`);
4807
+ }
4808
+ #getErrorExclusionReason(node, error, processId) {
4809
+ var _a;
4810
+ if ((_a = this.#getAttachedDataTo(node).races) == null ? void 0 : _a.completed) {
4811
+ return RACE_LOSER_EXCLUSION_REASON;
4812
+ }
4813
+ const abortReason = getGraphAbortReasonFromError(error);
4814
+ if (isRaceLoserGraphAbortReason(abortReason)) {
4815
+ return RACE_LOSER_EXCLUSION_REASON;
4816
+ }
4817
+ if (isSuccessfulNonRaceGraphAbortReason(abortReason)) {
4818
+ this.#successfulAbortTerminalProcessIds.add(processId);
4819
+ return SUCCESSFUL_GRAPH_ABORT_EXCLUSION_REASON;
4820
+ }
4821
+ if (this.#abortSuccessfully && isAbortLikeError(error)) {
4822
+ const exclusionReason = this.#abortError === RACE_LOSER_EXCLUSION_REASON ? RACE_LOSER_EXCLUSION_REASON : SUCCESSFUL_GRAPH_ABORT_EXCLUSION_REASON;
4823
+ if (exclusionReason === SUCCESSFUL_GRAPH_ABORT_EXCLUSION_REASON) {
4824
+ this.#successfulAbortTerminalProcessIds.add(processId);
4825
+ }
4826
+ return exclusionReason;
4827
+ }
4828
+ return void 0;
3928
4829
  }
3929
4830
  getRootProcessor() {
3930
4831
  let processor = this;
@@ -3945,14 +4846,71 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
3945
4846
  emitDetached(this.#emitter, "newAbortController", controller);
3946
4847
  return controller;
3947
4848
  }
4849
+ #registerNodeAbortController(nodeId, abortController) {
4850
+ const existingAbortControllers = this.#nodeAbortControllers.get(nodeId);
4851
+ if (!existingAbortControllers) {
4852
+ this.#nodeAbortControllers.set(nodeId, abortController);
4853
+ return;
4854
+ }
4855
+ if (existingAbortControllers instanceof Set) {
4856
+ existingAbortControllers.add(abortController);
4857
+ return;
4858
+ }
4859
+ if (existingAbortControllers === abortController) {
4860
+ return;
4861
+ }
4862
+ this.#nodeAbortControllers.set(nodeId, /* @__PURE__ */ new Set([existingAbortControllers, abortController]));
4863
+ }
4864
+ #unregisterNodeAbortController(nodeId, abortController) {
4865
+ const existingAbortControllers = this.#nodeAbortControllers.get(nodeId);
4866
+ if (!existingAbortControllers) {
4867
+ return;
4868
+ }
4869
+ if (existingAbortControllers === abortController) {
4870
+ this.#nodeAbortControllers.delete(nodeId);
4871
+ return;
4872
+ }
4873
+ if (!(existingAbortControllers instanceof Set)) {
4874
+ return;
4875
+ }
4876
+ existingAbortControllers.delete(abortController);
4877
+ if (existingAbortControllers.size === 0) {
4878
+ this.#nodeAbortControllers.delete(nodeId);
4879
+ } else if (existingAbortControllers.size === 1) {
4880
+ this.#nodeAbortControllers.set(nodeId, existingAbortControllers.values().next().value);
4881
+ }
4882
+ }
4883
+ #abortNodeControllersForNode(nodeId, traceMessage, reason) {
4884
+ const abortControllerEntry = this.#nodeAbortControllers.get(nodeId);
4885
+ if (!abortControllerEntry) {
4886
+ return;
4887
+ }
4888
+ if (!(abortControllerEntry instanceof Set)) {
4889
+ if (traceMessage) {
4890
+ this.#emitTraceEvent(traceMessage);
4891
+ }
4892
+ abortControllerEntry.abort(reason);
4893
+ return;
4894
+ }
4895
+ for (const abortController of abortControllerEntry) {
4896
+ if (traceMessage) {
4897
+ this.#emitTraceEvent(traceMessage);
4898
+ }
4899
+ abortController.abort(reason);
4900
+ }
4901
+ }
4902
+ #abortActiveNodeControllers(reason) {
4903
+ for (const nodeId of [...this.#nodeAbortControllers.keys()]) {
4904
+ this.#abortNodeControllersForNode(nodeId, void 0, reason);
4905
+ }
4906
+ }
3948
4907
  async #processNodeWithInputData(node, inputValues, index, processId, partialOutput) {
3949
4908
  const instance = this.#nodeInstances[node.id];
3950
4909
  const nodeAbortController = this.#newAbortController();
3951
- const abortListener = () => {
3952
- nodeAbortController.abort();
3953
- };
3954
- this.#nodeAbortControllers.set(`${node.id}-${processId}`, nodeAbortController);
3955
- this.#abortController.signal.addEventListener("abort", abortListener);
4910
+ this.#registerNodeAbortController(node.id, nodeAbortController);
4911
+ if (this.#abortController.signal.aborted) {
4912
+ nodeAbortController.abort(getAbortSignalReason(this.#abortController.signal));
4913
+ }
3956
4914
  const context = this.#createNodeProcessContext(
3957
4915
  node,
3958
4916
  inputValues,
@@ -3961,16 +4919,20 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
3961
4919
  nodeAbortController,
3962
4920
  partialOutput
3963
4921
  );
3964
- await this.#waitUntilUnpaused();
3965
4922
  let results;
3966
4923
  try {
4924
+ await this.#waitUntilUnpaused();
3967
4925
  results = await instance.process(inputValues, context);
3968
4926
  } finally {
3969
- this.#nodeAbortControllers.delete(`${node.id}-${processId}`);
3970
- this.#abortController.signal.removeEventListener("abort", abortListener);
4927
+ this.#unregisterNodeAbortController(node.id, nodeAbortController);
3971
4928
  }
4929
+ const abortReason = getGraphAbortReasonFromSignal(nodeAbortController.signal);
3972
4930
  if (nodeAbortController.signal.aborted) {
3973
- throw new Error("Aborted");
4931
+ if (isSuccessfulNonRaceGraphAbortReason(abortReason)) {
4932
+ this.#successfulAbortTerminalProcessIds.add(processId);
4933
+ } else {
4934
+ throw createGraphAbortError(abortReason, "Aborted");
4935
+ }
3974
4936
  }
3975
4937
  return results;
3976
4938
  }
@@ -3980,24 +4942,12 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
3980
4942
  #createNodeProcessContext(node, inputValues, index, processId, nodeAbortController, partialOutput) {
3981
4943
  const plugin = this.#registry.getPluginFor(node.type);
3982
4944
  return buildNodeProcessContext({
3983
- abortGraph: (error) => {
3984
- void this.abort(error === void 0, error);
3985
- },
3986
4945
  attachedData: this.#getAttachedDataTo(node),
3987
- codeRunner: this.#context.codeRunner ?? new IsomorphicCodeRunner(),
3988
- context: this.#context,
3989
- contextValues: this.#contextValues,
4946
+ base: this.#nodeProcessContextBase,
3990
4947
  createSubProcessor: (subGraphId, options2 = {}) => this.#createSubProcessor(node, index, processId, subGraphId, options2),
3991
4948
  execution: this.#buildExecutionMetadata(),
3992
- executionCache: this.#executionCache,
3993
- executor: this.executor ?? "nodejs",
3994
4949
  externalFunctions: this.#externalFunctions,
3995
- getGlobal: (id) => this.#globals.get(id),
3996
4950
  getPluginConfig: (name) => getPluginConfig(plugin, this.#context.settings, name),
3997
- graphInputNodeValues: this.#graphInputNodeValues,
3998
- graphInputs: this.#graphInputs,
3999
- graphOutputs: this.#graphOutputs,
4000
- loadedProjects: this.#loadedProjects,
4001
4951
  node,
4002
4952
  nodeAbortController,
4003
4953
  onPartialOutputs: (partialOutputs) => {
@@ -4005,36 +4955,21 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
4005
4955
  this.#emitGraphPartialOutputIfNeeded(node, partialOutputs);
4006
4956
  },
4007
4957
  processId,
4008
- project: this.#project,
4009
- raiseEvent: (event, data) => {
4010
- this.getRootProcessor().raiseEvent(event, data);
4011
- },
4012
4958
  requestUserInput: async (inputStrings, renderingType) => this.#requestUserInput(node, inputStrings, inputValues, renderingType, processId),
4013
4959
  setGlobal: (id, value) => {
4014
4960
  this.#globals.set(id, value);
4015
4961
  emitDetached(this.#emitter, "globalSet", this.#withExecution({ id, value, processId }));
4016
4962
  },
4017
- tokenizer: this.#getTokenizer(),
4018
- trace: (message) => {
4019
- this.#emitTraceEvent(message);
4020
- },
4021
4963
  waitEvent: async (event) => {
4022
4964
  return new Promise((resolve, reject) => {
4023
4965
  const abortListener = () => {
4024
- reject(new Error("Process aborted"));
4966
+ reject(createGraphAbortErrorFromSignal(nodeAbortController.signal, "Process aborted"));
4025
4967
  };
4026
4968
  this.#emitter.once(`userEvent:${event}`).then(resolve).catch(reject).finally(() => {
4027
4969
  nodeAbortController.signal.removeEventListener("abort", abortListener);
4028
4970
  });
4029
4971
  nodeAbortController.signal.addEventListener("abort", abortListener, { once: true });
4030
4972
  });
4031
- },
4032
- waitForGlobal: async (id) => {
4033
- if (this.#globals.has(id)) {
4034
- return this.#globals.get(id);
4035
- }
4036
- await this.getRootProcessor().#emitter.once(`globalSet:${id}`);
4037
- return this.#globals.get(id);
4038
4973
  }
4039
4974
  });
4040
4975
  }
@@ -4057,8 +4992,18 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
4057
4992
  });
4058
4993
  }
4059
4994
  #createSubProcessor(node, index, processId, subGraphId, { signal, project } = {}) {
4060
- const processor = new _GraphProcessor(project ?? this.#project, subGraphId, this.#registry, this.#includeTrace, {
4061
- concurrency: this.#concurrency
4995
+ var _a, _b;
4996
+ const subprocessorProject = project ?? this.#project;
4997
+ const subprocessorGraph = resolveProcessorGraph(subprocessorProject, subGraphId);
4998
+ const initialExecutionPlan = subprocessorGraph && this.#canUseRuntimeExecutionPlanCacheFor(subprocessorProject, true) ? (_b = (_a = this.#runtimeCache) == null ? void 0 : _a.executionPlans) == null ? void 0 : _b.get(subprocessorGraph) : void 0;
4999
+ const processor = new _GraphProcessor(subprocessorProject, subGraphId, this.#registry, this.#includeTrace, {
5000
+ cacheLoadedProjects: this.#cacheLoadedProjects,
5001
+ captureNodeTimings: this.#captureNodeTimings,
5002
+ concurrency: this.#concurrency,
5003
+ executionPlanCacheMode: this.#executionPlanCacheMode,
5004
+ initialExecutionPlan,
5005
+ runtimeCache: this.#runtimeCache,
5006
+ scheduler: this.#scheduler
4062
5007
  });
4063
5008
  processor.executor = this.executor;
4064
5009
  processor.#isSubProcessor = true;
@@ -4105,7 +5050,7 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
4105
5050
  return await new Promise((resolve, reject) => {
4106
5051
  const abortListener = () => {
4107
5052
  delete this.#pendingUserInputs[node.id];
4108
- reject(new Error("Processing aborted"));
5053
+ reject(createGraphAbortErrorFromSignal(this.#abortController.signal));
4109
5054
  };
4110
5055
  this.#pendingUserInputs[node.id] = {
4111
5056
  resolve,
@@ -4130,53 +5075,19 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
4130
5075
  );
4131
5076
  });
4132
5077
  }
4133
- #excludedDueToControlFlow(node, inputValues, processId, typeOfExclusion = void 0) {
4134
- var _a;
4135
- if (node.disabled) {
4136
- this.#emitTraceEvent(`Excluding node ${node.title} because it's disabled`);
4137
- this.#excludeNode(node, processId, inputValues, "disabled");
4138
- return true;
4139
- }
4140
- if (node.isConditional && typeOfExclusion === void 0) {
4141
- const ifValue = coerceTypeOptional(inputValues[IF_PORT.id], "boolean");
4142
- if (ifValue === false) {
4143
- this.#emitTraceEvent(`Excluding node ${node.title} because if port is false`);
4144
- this.#excludeNode(node, processId, inputValues, "if port is false");
4145
- return true;
4146
- }
5078
+ #excludedDueToControlFlow(node, inputValues, processId, typeOfExclusion, options2 = {}) {
5079
+ const exclusion = getControlFlowExclusionDecision({ node, inputValues, typeOfExclusion });
5080
+ if (exclusion.action === "continue") {
5081
+ return false;
4147
5082
  }
4148
- const inputsWithValues = entries(inputValues);
4149
- const controlFlowExcludedValues = inputsWithValues.filter(
4150
- ([, value]) => this.#isControlFlowExcluded(value) && (!typeOfExclusion || value.value === typeOfExclusion)
4151
- );
4152
- const inputIsExcludedValue = inputsWithValues.length > 0 && controlFlowExcludedValues.length > 0;
4153
- const isWaitingForLoop = controlFlowExcludedValues.some((value) => {
4154
- var _a2;
4155
- return ((_a2 = value == null ? void 0 : value[1]) == null ? void 0 : _a2.value) === LOOP_NOT_BROKEN_SENTINEL;
4156
- });
4157
- const nodesAllowedToConsumeExcludedValue = [
4158
- "if",
4159
- "ifElse",
4160
- "coalesce",
4161
- "graphOutput",
4162
- "raceInputs",
4163
- "loopController"
4164
- ];
4165
- const allowedToConsumedExcludedValue = nodesAllowedToConsumeExcludedValue.includes(node.type) && !isWaitingForLoop;
4166
- if (inputIsExcludedValue && !allowedToConsumedExcludedValue) {
4167
- if (!isWaitingForLoop) {
4168
- if (inputIsExcludedValue) {
4169
- this.#emitTraceEvent(
4170
- `Excluding node ${node.title} because of control flow. Input is has excluded value: ${(_a = controlFlowExcludedValues[0]) == null ? void 0 : _a[0]}`
4171
- );
4172
- }
4173
- this.#excludeNode(node, processId, inputValues, "input is excluded value");
4174
- }
4175
- return true;
5083
+ if (exclusion.action === "exclude") {
5084
+ this.#emitTraceEvent(exclusion.traceMessage);
5085
+ return this.#excludeNode(node, processId, inputValues, exclusion.reason, options2);
4176
5086
  }
4177
- return false;
5087
+ return true;
4178
5088
  }
4179
- #excludeNode(node, processId, inputValues, reason) {
5089
+ #excludeNode(node, processId, inputValues, reason, options2 = {}) {
5090
+ const { queueOutputNodes = true } = options2;
4180
5091
  const attachedData = this.#getAttachedDataTo(node);
4181
5092
  this.#registerNodeInActiveLoop(node, attachedData);
4182
5093
  this.#visitedNodes.add(node.id);
@@ -4185,37 +5096,34 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
4185
5096
  this.#remainingNodes.delete(node.id);
4186
5097
  const outputNodes = getOutputNodesFrom(this.#executionState, node);
4187
5098
  this.#propagateAttachedDataToOutputNodes(node, attachedData, outputNodes.connectionsToNodes);
4188
- this.#queueOutputNodes(node, outputNodes.nodes);
5099
+ if (queueOutputNodes) {
5100
+ this.#queueOutputNodes(node, outputNodes.nodes);
5101
+ }
5102
+ return outputNodes.nodes;
4189
5103
  }
4190
5104
  #markAsExcluded(node, processId, inputValues, reason) {
4191
- const outputs = {};
4192
- for (const output of this.#definitions[node.id].outputs) {
4193
- outputs[output.id] = { type: "control-flow-excluded", value: void 0 };
4194
- }
4195
- if (node.type === "loopController") {
4196
- outputs["break"] = { type: "control-flow-excluded", value: LOOP_NOT_BROKEN_SENTINEL };
4197
- }
5105
+ emitDetached(this.#emitter, "nodeExcluded", this.#createNodeExcludedEvent(node, processId, inputValues, reason));
5106
+ }
5107
+ async #emitNodeExcluded(node, processId, inputValues, reason) {
5108
+ await this.#emitter.emit("nodeExcluded", this.#createNodeExcludedEvent(node, processId, inputValues, reason));
5109
+ }
5110
+ #createNodeExcludedEvent(node, processId, inputValues, reason) {
5111
+ const outputs = createExcludedNodeOutputs(node, this.#definitions[node.id].outputs);
4198
5112
  this.#nodeResults.set(node.id, outputs);
4199
- emitDetached(
4200
- this.#emitter,
4201
- "nodeExcluded",
4202
- this.#withExecution({
4203
- node,
4204
- processId,
4205
- inputs: inputValues,
4206
- outputs,
4207
- reason
4208
- })
4209
- );
5113
+ return this.#withExecution({
5114
+ node,
5115
+ processId,
5116
+ inputs: inputValues,
5117
+ outputs,
5118
+ reason
5119
+ });
4210
5120
  }
4211
5121
  #getInputValuesForNode(node) {
4212
5122
  const connections = this.#connections[node.id];
4213
5123
  return this.#definitions[node.id].inputs.reduce(
4214
5124
  (values2, input) => {
4215
- if (!connections) {
4216
- return values2;
4217
- }
4218
- const connection = connections.find((conn) => conn.inputId === input.id && conn.inputNodeId === node.id);
5125
+ var _a, _b;
5126
+ const connection = ((_b = (_a = this.#graphExecutionPlan) == null ? void 0 : _a.inputConnectionByNodeAndPort[node.id]) == null ? void 0 : _b[input.id]) ?? (connections == null ? void 0 : connections.find((conn) => conn.inputId === input.id && conn.inputNodeId === node.id));
4219
5127
  if (connection) {
4220
5128
  const outputNode = this.#nodeInstances[connection.outputNodeId].chartNode;
4221
5129
  const outputNodeOutputs = this.#nodeResults.get(outputNode.id);
@@ -4232,6 +5140,7 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
4232
5140
  connections: this.#connections,
4233
5141
  definitions: this.#definitions,
4234
5142
  erroredNodes: this.#erroredNodes,
5143
+ executionPlan: this.#graphExecutionPlan,
4235
5144
  loopControllersSeen: this.#loopControllersSeen,
4236
5145
  nodesById: this.#nodesById,
4237
5146
  stronglyConnectedComponents: this.#scc,
@@ -4261,8 +5170,8 @@ var NodeImpl = class {
4261
5170
  get data() {
4262
5171
  return this.chartNode.data;
4263
5172
  }
4264
- getInputDefinitionsIncludingBuiltIn(connections, nodes, project, referencedProjects) {
4265
- const ports = [...this.getInputDefinitions(connections, nodes, project, referencedProjects)];
5173
+ getInputDefinitionsIncludingBuiltIn(connections, nodes, project, referencedProjects, definitionContext) {
5174
+ const ports = definitionContext ? [...this.getInputDefinitions(connections, nodes, project, referencedProjects, definitionContext)] : [...this.getInputDefinitions(connections, nodes, project, referencedProjects)];
4266
5175
  if (this.chartNode.isConditional) {
4267
5176
  ports.push(IF_PORT);
4268
5177
  }
@@ -4281,10 +5190,10 @@ var PluginNodeImplClass = class extends NodeImpl {
4281
5190
  super(chartNode);
4282
5191
  this.impl = impl;
4283
5192
  }
4284
- getInputDefinitions(connections, nodes, project) {
5193
+ getInputDefinitions(connections, nodes, project, _referencedProjects, _definitionContext) {
4285
5194
  return this.impl.getInputDefinitions(this.data, connections, nodes, project);
4286
5195
  }
4287
- getOutputDefinitions(connections, nodes, project) {
5196
+ getOutputDefinitions(connections, nodes, project, _referencedProjects, _definitionContext) {
4288
5197
  return this.impl.getOutputDefinitions(this.data, connections, nodes, project);
4289
5198
  }
4290
5199
  process(inputData, context) {
@@ -4457,7 +5366,7 @@ var NodeRegistration = class {
4457
5366
 
4458
5367
  // src/model/nodes/UserInputNode.ts
4459
5368
  var import_non_secure5 = require("nanoid/non-secure");
4460
- var import_lodash_es5 = require("lodash");
5369
+ var import_lodash_es4 = require("lodash");
4461
5370
  var import_ts_dedent2 = require("ts-dedent");
4462
5371
  var UserInputNodeImpl = class extends NodeImpl {
4463
5372
  static create() {
@@ -4554,7 +5463,7 @@ var UserInputNodeImpl = class extends NodeImpl {
4554
5463
  },
4555
5464
  ["questionsAndAnswers"]: {
4556
5465
  type: "string[]",
4557
- value: (0, import_lodash_es5.zip)(questions, response.value).map(([q, a]) => `${q}
5466
+ value: (0, import_lodash_es4.zip)(questions, response.value).map(([q, a]) => `${q}
4558
5467
  ${a}`)
4559
5468
  }
4560
5469
  };
@@ -4567,9 +5476,15 @@ var import_non_secure6 = require("nanoid/non-secure");
4567
5476
  var import_ts_dedent3 = require("ts-dedent");
4568
5477
 
4569
5478
  // src/utils/interpolation.ts
4570
- var import_lodash_es6 = require("lodash");
5479
+ var import_lodash_es5 = require("lodash");
4571
5480
  var ESCAPED_TOKEN_REGEX = /\{\{\{([^}]+?)\}\}\}/g;
4572
5481
  var ESCAPED_ESCAPED_TOKEN_REGEX = /\\\{\\\{([^}]+?)\\\}\\\}/g;
5482
+ var EXTRACT_INTERPOLATION_VARIABLES_CACHE_MAX_ENTRIES = 2048;
5483
+ var EXTRACT_INTERPOLATION_VARIABLES_CACHE_MAX_TEMPLATE_LENGTH = 64 * 1024;
5484
+ var EXTRACT_INTERPOLATION_VARIABLES_CACHE_MAX_TEMPLATE_CHARS = 1024 * 1024;
5485
+ var extractedInterpolationVariablesCache = /* @__PURE__ */ new Map();
5486
+ var extractedInterpolationVariablesCacheTemplateChars = 0;
5487
+ var lastUncachedInterpolationVariableTemplate;
4573
5488
  var processingFunctions = {
4574
5489
  indent: (input, spaces = 0) => {
4575
5490
  const indent = " ".repeat(spaces);
@@ -4657,7 +5572,7 @@ function resolveExpressionRawValue(source, expression, sourceType) {
4657
5572
  let finalValue;
4658
5573
  if (path) {
4659
5574
  try {
4660
- finalValue = (0, import_lodash_es6.get)(baseValue, path);
5575
+ finalValue = (0, import_lodash_es5.get)(baseValue, path);
4661
5576
  finalValue = unwrapPotentialDataValue(finalValue);
4662
5577
  } catch (error) {
4663
5578
  console.warn(`Error accessing path "${path}" in ${sourceType} value for key "${key}":`, error);
@@ -4796,6 +5711,13 @@ function interpolate(template, variables, graphInputValues, contextValues) {
4796
5711
  });
4797
5712
  }
4798
5713
  function extractInterpolationVariables(template) {
5714
+ if (!template.includes("{{")) {
5715
+ return [];
5716
+ }
5717
+ const cachedVariables = getCachedInterpolationVariables(template);
5718
+ if (cachedVariables) {
5719
+ return [...cachedVariables];
5720
+ }
4799
5721
  const protectedTemplate = protectEscapedInterpolationTokens(template);
4800
5722
  const variables = /* @__PURE__ */ new Set();
4801
5723
  for (const match10 of findInterpolationTokenSpans(protectedTemplate)) {
@@ -4804,7 +5726,32 @@ function extractInterpolationVariables(template) {
4804
5726
  variables.add(token);
4805
5727
  }
4806
5728
  }
4807
- return Array.from(variables);
5729
+ const extractedVariables = Array.from(variables);
5730
+ cacheInterpolationVariables(template, extractedVariables);
5731
+ return extractedVariables;
5732
+ }
5733
+ function getCachedInterpolationVariables(template) {
5734
+ var _a;
5735
+ return (_a = extractedInterpolationVariablesCache.get(template)) == null ? void 0 : _a.variables;
5736
+ }
5737
+ function cacheInterpolationVariables(template, variables) {
5738
+ if (template.length > EXTRACT_INTERPOLATION_VARIABLES_CACHE_MAX_TEMPLATE_LENGTH) {
5739
+ return;
5740
+ }
5741
+ if (extractedInterpolationVariablesCache.size >= EXTRACT_INTERPOLATION_VARIABLES_CACHE_MAX_ENTRIES || extractedInterpolationVariablesCacheTemplateChars + template.length > EXTRACT_INTERPOLATION_VARIABLES_CACHE_MAX_TEMPLATE_CHARS) {
5742
+ if (lastUncachedInterpolationVariableTemplate !== template) {
5743
+ lastUncachedInterpolationVariableTemplate = template;
5744
+ return;
5745
+ }
5746
+ extractedInterpolationVariablesCache.clear();
5747
+ extractedInterpolationVariablesCacheTemplateChars = 0;
5748
+ }
5749
+ lastUncachedInterpolationVariableTemplate = void 0;
5750
+ extractedInterpolationVariablesCache.set(template, {
5751
+ templateLength: template.length,
5752
+ variables: Object.freeze([...variables])
5753
+ });
5754
+ extractedInterpolationVariablesCacheTemplateChars += template.length;
4808
5755
  }
4809
5756
 
4810
5757
  // src/model/interpolationInputDefinition.ts
@@ -4999,7 +5946,7 @@ __export(openai_exports, {
4999
5946
  openaiModels: () => openaiModels,
5000
5947
  streamChatCompletions: () => streamChatCompletions
5001
5948
  });
5002
- var import_lodash_es7 = require("lodash");
5949
+ var import_lodash_es6 = require("lodash");
5003
5950
 
5004
5951
  // src/utils/fetchEventSource.ts
5005
5952
  var EventSourceResponse = class extends Response {
@@ -5244,7 +6191,7 @@ var openaiModels = {
5244
6191
  displayName: "Local Model"
5245
6192
  }
5246
6193
  };
5247
- var openAiModelOptions = (0, import_lodash_es7.orderBy)(
6194
+ var openAiModelOptions = (0, import_lodash_es6.orderBy)(
5248
6195
  Object.entries(openaiModels).map(([id, { displayName }]) => ({
5249
6196
  value: id,
5250
6197
  label: displayName
@@ -9677,21 +10624,9 @@ function normalizeChatV2ProviderError(error, context) {
9677
10624
  return normalized;
9678
10625
  }
9679
10626
 
9680
- // src/model/chat-v2/chatV2Pipeline.ts
9681
- var REQUEST_STATUS_PORT_ID = "requestStatus";
9682
- var REQUEST_ERROR_PORT_ID = "requestError";
9683
- var StreamChatV2RetryFailure = class extends Error {
9684
- constructor(error, requestStatuses, requestErrors) {
9685
- super("Chat v2 retry attempts failed");
9686
- this.error = error;
9687
- this.requestStatuses = requestStatuses;
9688
- this.requestErrors = requestErrors;
9689
- this.name = "StreamChatV2RetryFailure";
9690
- }
9691
- };
9692
- function isStreamChatV2RetryFailure(error) {
9693
- return error instanceof StreamChatV2RetryFailure;
9694
- }
10627
+ // src/model/chat-v2/chatV2Outputs.ts
10628
+ var CHAT_V2_REQUEST_STATUS_PORT_ID = "requestStatus";
10629
+ var CHAT_V2_REQUEST_ERROR_PORT_ID = "requestError";
9695
10630
  function toFunctionCallOutputValue(functionCall) {
9696
10631
  let argumentsValue = functionCall.lastParsedArguments;
9697
10632
  if (argumentsValue == null) {
@@ -9707,7 +10642,13 @@ function toFunctionCallOutputValue(functionCall) {
9707
10642
  id: functionCall.id
9708
10643
  };
9709
10644
  }
9710
- function normalizeUsage(usage, options2) {
10645
+ function createControlFlowExcludedOutput() {
10646
+ return {
10647
+ type: "control-flow-excluded",
10648
+ value: void 0
10649
+ };
10650
+ }
10651
+ function normalizeChatV2Usage(usage, options2) {
9711
10652
  var _a, _b, _c;
9712
10653
  if (usage == null) {
9713
10654
  return void 0;
@@ -9733,19 +10674,57 @@ function tryParseStructuredResponseText(response) {
9733
10674
  return void 0;
9734
10675
  }
9735
10676
  }
9736
- function buildResponseOutput(response, structuredOutput, responseFormat) {
10677
+ function createChatV2ResponseOutput2(response, structuredOutput, responseFormat) {
9737
10678
  if (!isChatV2StructuredResponseFormat(responseFormat)) {
9738
10679
  return { type: "string", value: response };
9739
10680
  }
9740
10681
  const parsedOutput = structuredOutput !== void 0 ? structuredOutput : tryParseStructuredResponseText(response);
9741
10682
  return parsedOutput !== void 0 ? inferType(parsedOutput) : { type: "string", value: response };
9742
10683
  }
9743
- function buildCommonOutputs(requestMessages, response, structuredOutput, functionCalls, usage, reasoning, requestStatus, responseError, requestStatuses, requestErrors, options2) {
10684
+ function createChatV2ReasoningOutput(reasoning) {
10685
+ if (Array.isArray(reasoning)) {
10686
+ const nonEmptyReasoning = reasoning.filter((part) => typeof part === "string" && part.trim().length > 0);
10687
+ return nonEmptyReasoning.length > 0 ? {
10688
+ type: "string[]",
10689
+ value: nonEmptyReasoning
10690
+ } : createControlFlowExcludedOutput();
10691
+ }
10692
+ const reasoningText = typeof reasoning === "string" ? reasoning : "";
10693
+ return reasoningText.trim().length > 0 ? {
10694
+ type: "string",
10695
+ value: reasoningText
10696
+ } : createControlFlowExcludedOutput();
10697
+ }
10698
+ function createChatV2RetryAttemptOutput(type, values2) {
10699
+ return values2.length > 0 ? {
10700
+ type,
10701
+ value: values2
10702
+ } : createControlFlowExcludedOutput();
10703
+ }
10704
+ function createChatV2CommonOutputs({
10705
+ requestMessages,
10706
+ response,
10707
+ structuredOutput,
10708
+ functionCalls,
10709
+ usage,
10710
+ reasoning,
10711
+ requestStatus,
10712
+ responseError,
10713
+ requestStatuses,
10714
+ requestErrors,
10715
+ outputUsage,
10716
+ outputReasoning,
10717
+ outputRequestStatus,
10718
+ includeFunctionCalls,
10719
+ functionCallMode,
10720
+ retryOnNon200,
10721
+ responseFormat
10722
+ }) {
9744
10723
  const outputs = {
9745
- ["response"]: buildResponseOutput(response, structuredOutput, options2.responseFormat),
10724
+ ["response"]: createChatV2ResponseOutput2(response, structuredOutput, responseFormat),
9746
10725
  ["in-messages"]: { type: "chat-message[]", value: requestMessages },
9747
10726
  ["all-messages"]: createAssistantMessagesOutput(requestMessages, response, functionCalls, {
9748
- functionCallMode: options2.functionCallMode
10727
+ functionCallMode
9749
10728
  }),
9750
10729
  ["responseTokens"]: { type: "number", value: (usage == null ? void 0 : usage.completionTokens) ?? 0 }
9751
10730
  };
@@ -9754,13 +10733,10 @@ function buildCommonOutputs(requestMessages, response, structuredOutput, functio
9754
10733
  type: "object[]",
9755
10734
  value: functionCalls.map(toFunctionCallOutputValue)
9756
10735
  };
9757
- } else if (options2.includeFunctionCalls) {
9758
- outputs["function-calls"] = {
9759
- type: "control-flow-excluded",
9760
- value: void 0
9761
- };
10736
+ } else if (includeFunctionCalls) {
10737
+ outputs["function-calls"] = createControlFlowExcludedOutput();
9762
10738
  }
9763
- if (options2.outputUsage) {
10739
+ if (outputUsage) {
9764
10740
  outputs["usage"] = {
9765
10741
  type: "object",
9766
10742
  value: usage ?? {
@@ -9771,78 +10747,55 @@ function buildCommonOutputs(requestMessages, response, structuredOutput, functio
9771
10747
  reasoningTokens: 0,
9772
10748
  totalCost: void 0
9773
10749
  }
9774
- };
9775
- }
9776
- if (options2.outputReasoning) {
9777
- outputs["reasoning"] = buildReasoningOutput(reasoning);
9778
- }
9779
- if (options2.outputRequestStatus) {
9780
- if (options2.retryOnNon200) {
9781
- outputs[REQUEST_STATUS_PORT_ID] = buildRetryAttemptOutput(
9782
- "number[]",
9783
- requestStatuses.length > 0 ? requestStatuses : [requestStatus ?? 200]
9784
- );
9785
- outputs[REQUEST_ERROR_PORT_ID] = buildRetryAttemptOutput("string[]", requestErrors);
9786
- } else {
9787
- outputs[REQUEST_STATUS_PORT_ID] = {
9788
- type: "number",
9789
- value: requestStatus ?? 200
9790
- };
9791
- outputs[REQUEST_ERROR_PORT_ID] = responseError != null ? {
9792
- type: "string",
9793
- value: responseError
9794
- } : {
9795
- type: "control-flow-excluded",
9796
- value: void 0
9797
- };
9798
- }
9799
- }
9800
- return outputs;
9801
- }
9802
- function buildReasoningOutput(reasoning) {
9803
- if (Array.isArray(reasoning)) {
9804
- const nonEmptyReasoning = reasoning.filter((part) => typeof part === "string" && part.trim().length > 0);
9805
- return nonEmptyReasoning.length > 0 ? {
9806
- type: "string[]",
9807
- value: nonEmptyReasoning
9808
- } : {
9809
- type: "control-flow-excluded",
9810
- value: void 0
9811
- };
9812
- }
9813
- const reasoningText = typeof reasoning === "string" ? reasoning : "";
9814
- return reasoningText.trim().length > 0 ? {
9815
- type: "string",
9816
- value: reasoningText
9817
- } : {
9818
- type: "control-flow-excluded",
9819
- value: void 0
9820
- };
9821
- }
9822
- function getProviderFailureMessage(error) {
9823
- if (error instanceof Error) {
9824
- return error.message;
10750
+ };
9825
10751
  }
9826
- return String(error);
10752
+ if (outputReasoning) {
10753
+ outputs["reasoning"] = createChatV2ReasoningOutput(reasoning);
10754
+ }
10755
+ if (outputRequestStatus) {
10756
+ if (retryOnNon200) {
10757
+ outputs[CHAT_V2_REQUEST_STATUS_PORT_ID] = createChatV2RetryAttemptOutput(
10758
+ "number[]",
10759
+ requestStatuses.length > 0 ? requestStatuses : [requestStatus ?? 200]
10760
+ );
10761
+ outputs[CHAT_V2_REQUEST_ERROR_PORT_ID] = createChatV2RetryAttemptOutput("string[]", requestErrors);
10762
+ } else {
10763
+ outputs[CHAT_V2_REQUEST_STATUS_PORT_ID] = {
10764
+ type: "number",
10765
+ value: requestStatus ?? 200
10766
+ };
10767
+ outputs[CHAT_V2_REQUEST_ERROR_PORT_ID] = responseError != null ? {
10768
+ type: "string",
10769
+ value: responseError
10770
+ } : createControlFlowExcludedOutput();
10771
+ }
10772
+ }
10773
+ return outputs;
9827
10774
  }
9828
- function buildProviderFailureOutputs(requestMessages, responseStatus, responseError, requestStatuses, requestErrors, options2) {
9829
- const outputs = {};
9830
- Object.assign(outputs, {
9831
- [REQUEST_ERROR_PORT_ID]: options2.retryOnNon200 ? buildRetryAttemptOutput("string[]", requestErrors) : {
10775
+ function createChatV2ProviderFailureOutputs({
10776
+ requestMessages,
10777
+ responseStatus,
10778
+ responseError,
10779
+ requestStatuses,
10780
+ requestErrors,
10781
+ outputUsage,
10782
+ outputReasoning,
10783
+ includeFunctionCalls,
10784
+ retryOnNon200
10785
+ }) {
10786
+ const outputs = {
10787
+ [CHAT_V2_REQUEST_ERROR_PORT_ID]: retryOnNon200 ? createChatV2RetryAttemptOutput("string[]", requestErrors) : {
9832
10788
  type: "string",
9833
10789
  value: responseError
9834
10790
  },
9835
- [REQUEST_STATUS_PORT_ID]: options2.retryOnNon200 ? buildRetryAttemptOutput("number[]", requestStatuses) : responseStatus == null ? {
10791
+ [CHAT_V2_REQUEST_STATUS_PORT_ID]: retryOnNon200 ? createChatV2RetryAttemptOutput("number[]", requestStatuses) : responseStatus == null ? {
9836
10792
  type: "control-flow-excluded",
9837
10793
  value: void 0
9838
10794
  } : {
9839
10795
  type: "number",
9840
10796
  value: responseStatus
9841
10797
  },
9842
- ["response"]: {
9843
- type: "control-flow-excluded",
9844
- value: void 0
9845
- },
10798
+ ["response"]: createControlFlowExcludedOutput(),
9846
10799
  ["in-messages"]: {
9847
10800
  type: "chat-message[]",
9848
10801
  value: requestMessages
@@ -9851,39 +10804,38 @@ function buildProviderFailureOutputs(requestMessages, responseStatus, responseEr
9851
10804
  type: "chat-message[]",
9852
10805
  value: requestMessages
9853
10806
  },
9854
- ["responseTokens"]: {
9855
- type: "control-flow-excluded",
9856
- value: void 0
9857
- }
9858
- });
9859
- if (options2.includeFunctionCalls) {
9860
- outputs["function-calls"] = {
9861
- type: "control-flow-excluded",
9862
- value: void 0
9863
- };
10807
+ ["responseTokens"]: createControlFlowExcludedOutput()
10808
+ };
10809
+ if (includeFunctionCalls) {
10810
+ outputs["function-calls"] = createControlFlowExcludedOutput();
9864
10811
  }
9865
- if (options2.outputUsage) {
9866
- outputs["usage"] = {
9867
- type: "control-flow-excluded",
9868
- value: void 0
9869
- };
10812
+ if (outputUsage) {
10813
+ outputs["usage"] = createControlFlowExcludedOutput();
9870
10814
  }
9871
- if (options2.outputReasoning) {
9872
- outputs["reasoning"] = {
9873
- type: "control-flow-excluded",
9874
- value: void 0
9875
- };
10815
+ if (outputReasoning) {
10816
+ outputs["reasoning"] = createControlFlowExcludedOutput();
9876
10817
  }
9877
10818
  return outputs;
9878
10819
  }
9879
- function buildRetryAttemptOutput(type, values2) {
9880
- return values2.length > 0 ? {
9881
- type,
9882
- value: values2
9883
- } : {
9884
- type: "control-flow-excluded",
9885
- value: void 0
9886
- };
10820
+
10821
+ // src/model/chat-v2/chatV2Pipeline.ts
10822
+ var StreamChatV2RetryFailure = class extends Error {
10823
+ constructor(error, requestStatuses, requestErrors) {
10824
+ super("Chat v2 retry attempts failed");
10825
+ this.error = error;
10826
+ this.requestStatuses = requestStatuses;
10827
+ this.requestErrors = requestErrors;
10828
+ this.name = "StreamChatV2RetryFailure";
10829
+ }
10830
+ };
10831
+ function isStreamChatV2RetryFailure(error) {
10832
+ return error instanceof StreamChatV2RetryFailure;
10833
+ }
10834
+ function getProviderFailureMessage(error) {
10835
+ if (error instanceof Error) {
10836
+ return error.message;
10837
+ }
10838
+ return String(error);
9887
10839
  }
9888
10840
  function buildNon200StatusError(statusCode) {
9889
10841
  const error = new Error(`Provider request returned non-200 status: ${statusCode}`);
@@ -9948,19 +10900,17 @@ function buildProviderFailureResult(requestMessages, options2, normalizedError,
9948
10900
  const responseError = getProviderFailureMessage(normalizedError);
9949
10901
  const retryRequestStatuses = options2.retryOnNon200 ? requestStatuses.length > 0 ? requestStatuses : statusCode == null ? [] : [statusCode] : [];
9950
10902
  const retryRequestErrors = options2.retryOnNon200 ? requestErrors.length > 0 ? requestErrors : [responseError] : [];
9951
- const commonOutputs = buildProviderFailureOutputs(
10903
+ const commonOutputs = createChatV2ProviderFailureOutputs({
9952
10904
  requestMessages,
9953
- statusCode,
10905
+ responseStatus: statusCode,
9954
10906
  responseError,
9955
- retryRequestStatuses,
9956
- retryRequestErrors,
9957
- {
9958
- outputUsage: options2.outputUsage,
9959
- outputReasoning: options2.outputReasoning,
9960
- includeFunctionCalls: options2.includeFunctionCalls,
9961
- retryOnNon200: options2.retryOnNon200
9962
- }
9963
- );
10907
+ requestStatuses: retryRequestStatuses,
10908
+ requestErrors: retryRequestErrors,
10909
+ outputUsage: options2.outputUsage,
10910
+ outputReasoning: options2.outputReasoning,
10911
+ includeFunctionCalls: options2.includeFunctionCalls,
10912
+ retryOnNon200: options2.retryOnNon200
10913
+ });
9964
10914
  const allMessagesOutput = commonOutputs["all-messages"];
9965
10915
  if ((allMessagesOutput == null ? void 0 : allMessagesOutput.type) !== "chat-message[]") {
9966
10916
  throw new Error("Chat v2 provider failure expected all-messages output to be chat-message[].");
@@ -10013,27 +10963,25 @@ async function runChatV2Pipeline(options2) {
10013
10963
  var _a, _b;
10014
10964
  (_b = (_a = options2.context).onPartialOutputs) == null ? void 0 : _b.call(
10015
10965
  _a,
10016
- buildCommonOutputs(
10966
+ createChatV2CommonOutputs({
10017
10967
  requestMessages,
10018
- text,
10019
- void 0,
10968
+ response: text,
10969
+ structuredOutput: void 0,
10020
10970
  functionCalls,
10021
- void 0,
10022
- "",
10023
- void 0,
10024
- void 0,
10025
- [],
10026
- [],
10027
- {
10028
- outputUsage: false,
10029
- outputReasoning: false,
10030
- outputRequestStatus: false,
10031
- includeFunctionCalls: options2.includeFunctionCalls,
10032
- functionCallMode: options2.functionCallMode,
10033
- retryOnNon200: false,
10034
- responseFormat: void 0
10035
- }
10036
- )
10971
+ usage: void 0,
10972
+ reasoning: "",
10973
+ requestStatus: void 0,
10974
+ responseError: void 0,
10975
+ requestStatuses: [],
10976
+ requestErrors: [],
10977
+ outputUsage: false,
10978
+ outputReasoning: false,
10979
+ outputRequestStatus: false,
10980
+ includeFunctionCalls: options2.includeFunctionCalls,
10981
+ functionCallMode: options2.functionCallMode,
10982
+ retryOnNon200: false,
10983
+ responseFormat: void 0
10984
+ })
10037
10985
  );
10038
10986
  }
10039
10987
  },
@@ -10063,31 +11011,29 @@ async function runChatV2Pipeline(options2) {
10063
11011
  if ("commonOutputs" in streamed) {
10064
11012
  return streamed;
10065
11013
  }
10066
- const usage = normalizeUsage(streamed.result.usage, options2);
11014
+ const usage = normalizeChatV2Usage(streamed.result.usage, options2);
10067
11015
  const requestStatuses = streamed.requestStatuses;
10068
11016
  const requestErrors = normalizeProviderFailureMessages(streamed.requestErrors, options2);
10069
11017
  const responseError = streamed.responseError ? normalizeProviderFailureMessage(streamed.responseError, options2) : void 0;
10070
- const commonOutputs = buildCommonOutputs(
11018
+ const commonOutputs = createChatV2CommonOutputs({
10071
11019
  requestMessages,
10072
- streamed.result.responseText,
10073
- streamed.result.structuredOutput,
10074
- streamed.result.functionCalls,
11020
+ response: streamed.result.responseText,
11021
+ structuredOutput: streamed.result.structuredOutput,
11022
+ functionCalls: streamed.result.functionCalls,
10075
11023
  usage,
10076
- streamed.result.reasoning,
10077
- streamed.result.requestStatus,
11024
+ reasoning: streamed.result.reasoning,
11025
+ requestStatus: streamed.result.requestStatus,
10078
11026
  responseError,
10079
11027
  requestStatuses,
10080
11028
  requestErrors,
10081
- {
10082
- outputUsage: options2.outputUsage,
10083
- outputReasoning: options2.outputReasoning,
10084
- outputRequestStatus: options2.outputRequestStatus,
10085
- includeFunctionCalls: options2.includeFunctionCalls,
10086
- functionCallMode: options2.functionCallMode,
10087
- retryOnNon200: options2.retryOnNon200,
10088
- responseFormat: options2.responseFormat
10089
- }
10090
- );
11029
+ outputUsage: options2.outputUsage,
11030
+ outputReasoning: options2.outputReasoning,
11031
+ outputRequestStatus: options2.outputRequestStatus,
11032
+ includeFunctionCalls: options2.includeFunctionCalls,
11033
+ functionCallMode: options2.functionCallMode,
11034
+ retryOnNon200: options2.retryOnNon200,
11035
+ responseFormat: options2.responseFormat
11036
+ });
10091
11037
  const allMessagesOutput = commonOutputs["all-messages"];
10092
11038
  if ((allMessagesOutput == null ? void 0 : allMessagesOutput.type) !== "chat-message[]") {
10093
11039
  throw new Error("Chat v2 pipeline expected all-messages output to be chat-message[].");
@@ -10220,7 +11166,7 @@ async function runChatV2PipelineWithToolContinuation(options2) {
10220
11166
  }
10221
11167
 
10222
11168
  // src/model/nodes/toolCallDelegation.ts
10223
- var import_lodash_es8 = require("lodash");
11169
+ var import_lodash_es7 = require("lodash");
10224
11170
  function isDelegatedToolCallRecord(input) {
10225
11171
  const maybeRecord = input;
10226
11172
  const maybeMessage = maybeRecord == null ? void 0 : maybeRecord.message;
@@ -10308,7 +11254,7 @@ async function delegateToolCall(rawFunctionCall, context, config) {
10308
11254
  const externalFunction = context.externalFunctions[functionCall.name];
10309
11255
  if (externalFunction) {
10310
11256
  try {
10311
- const externalContext = (0, import_lodash_es8.omit)(context, ["setGlobal"]);
11257
+ const externalContext = (0, import_lodash_es7.omit)(context, ["setGlobal"]);
10312
11258
  const result = await externalFunction(externalContext, functionCall.arguments ?? {});
10313
11259
  const outputString2 = stringifyToolOutput(result);
10314
11260
  return {
@@ -11061,9 +12007,8 @@ function escapeRegExp(value) {
11061
12007
  function sanitizeSourceUrlPart(value) {
11062
12008
  return String(value).replace(/[^a-zA-Z0-9_-]/g, "_");
11063
12009
  }
11064
- function buildCodeNodeSourceUrl(nodeId, processId) {
11065
- const processPart = processId ? `-${sanitizeSourceUrlPart(processId)}` : "";
11066
- return `rivet-code-node-${sanitizeSourceUrlPart(nodeId)}${processPart}.js`;
12010
+ function buildCodeNodeSourceUrl(nodeId) {
12011
+ return `rivet-code-node-${sanitizeSourceUrlPart(nodeId)}.js`;
11067
12012
  }
11068
12013
  function appendCodeNodeSourceUrl(code, sourceUrl) {
11069
12014
  return `${code}
@@ -11320,7 +12265,7 @@ var CodeNodeImpl = class extends NodeImpl {
11320
12265
  };
11321
12266
  }
11322
12267
  async process(inputs, context) {
11323
- const sourceUrl = buildCodeNodeSourceUrl(this.chartNode.id, context.processId);
12268
+ const sourceUrl = buildCodeNodeSourceUrl(this.chartNode.id);
11324
12269
  let outputs;
11325
12270
  try {
11326
12271
  outputs = await context.codeRunner.runCode(
@@ -11770,7 +12715,7 @@ var CodeNewNodeImpl = class extends NodeImpl {
11770
12715
  };
11771
12716
  }
11772
12717
  async process(inputs, context) {
11773
- const sourceUrl = buildCodeNodeSourceUrl(this.chartNode.id, context.processId);
12718
+ const sourceUrl = buildCodeNodeSourceUrl(this.chartNode.id);
11774
12719
  const interpolationContext = getJsValueInterpolationRuntimeContext(this.data.code, CODE_NEW_INPUTS_IDENTIFIER);
11775
12720
  const { inputNames, inputsIdentifier } = interpolationContext;
11776
12721
  const { source, userCodeLineOffset } = buildCodeNewWrapper(this.data.code, interpolationContext);
@@ -12977,6 +13922,34 @@ var graphInputNode = nodeDefinition(GraphInputNodeImpl, "Graph Input");
12977
13922
  // src/model/nodes/GraphOutputNode.ts
12978
13923
  var import_non_secure21 = require("nanoid/non-secure");
12979
13924
  var import_ts_dedent19 = require("ts-dedent");
13925
+ function isPlainObjectRecordValue(value) {
13926
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
13927
+ return false;
13928
+ }
13929
+ const prototype = Object.getPrototypeOf(value);
13930
+ return prototype === Object.prototype || prototype === null;
13931
+ }
13932
+ function coerceAnyGraphOutputValue(value, dataType) {
13933
+ if (value.type === "control-flow-excluded" || dataType === "any" || value.type === dataType) {
13934
+ return value;
13935
+ }
13936
+ if (value.type !== "any") {
13937
+ return value;
13938
+ }
13939
+ if (dataType === "object" && isPlainObjectRecordValue(value.value)) {
13940
+ return {
13941
+ type: "object",
13942
+ value: value.value
13943
+ };
13944
+ }
13945
+ if (dataType === "object[]" && Array.isArray(value.value) && value.value.every(isPlainObjectRecordValue)) {
13946
+ return {
13947
+ type: "object[]",
13948
+ value: value.value
13949
+ };
13950
+ }
13951
+ return value;
13952
+ }
12980
13953
  var GraphOutputNodeImpl = class extends NodeImpl {
12981
13954
  static create() {
12982
13955
  const chartNode = {
@@ -13045,14 +14018,15 @@ var GraphOutputNodeImpl = class extends NodeImpl {
13045
14018
  }
13046
14019
  async process(inputs, context) {
13047
14020
  var _a;
13048
- const value = inputs["value"] ?? { type: "any", value: void 0 };
14021
+ const inputValue = inputs["value"];
14022
+ const value = coerceAnyGraphOutputValue(inputValue ?? { type: "any", value: void 0 }, this.data.dataType);
13049
14023
  const isExcluded = value.type === "control-flow-excluded";
13050
14024
  if (isExcluded && context.graphOutputs[this.data.id] == null) {
13051
14025
  context.graphOutputs[this.data.id] = {
13052
14026
  type: "control-flow-excluded",
13053
14027
  value: void 0
13054
14028
  };
13055
- } else if ((context.graphOutputs[this.data.id] == null || ((_a = context.graphOutputs[this.data.id]) == null ? void 0 : _a.type) === "control-flow-excluded") && inputs["value"]) {
14029
+ } else if ((context.graphOutputs[this.data.id] == null || ((_a = context.graphOutputs[this.data.id]) == null ? void 0 : _a.type) === "control-flow-excluded") && inputValue) {
13056
14030
  context.graphOutputs[this.data.id] = value;
13057
14031
  }
13058
14032
  if (isExcluded) {
@@ -13092,40 +14066,17 @@ var SubGraphNodeImpl = class extends NodeImpl {
13092
14066
  };
13093
14067
  return chartNode;
13094
14068
  }
13095
- getInputDefinitions(_connections, _nodes, project) {
13096
- const graph = project.graphs[this.data.graphId];
13097
- if (!graph) {
13098
- return [];
13099
- }
13100
- const inputNodes = graph.nodes.filter((node) => node.type === "graphInput");
13101
- const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();
13102
- return inputIds.map(
13103
- (id) => ({
13104
- id,
13105
- title: id,
13106
- dataType: inputNodes.find((node) => node.data.id === id).data.dataType
13107
- })
13108
- );
14069
+ getInputDefinitions(_connections, _nodes, project, _referencedProjects, definitionContext) {
14070
+ const boundary = this.getBoundary(project, definitionContext);
14071
+ return boundary ? getGraphBoundaryInputDefinitions(boundary) : [];
13109
14072
  }
13110
- getGraphOutputs(project) {
13111
- const graph = project.graphs[this.data.graphId];
13112
- if (!graph) {
13113
- return [];
13114
- }
13115
- const outputNodes = graph.nodes.filter((node) => node.type === "graphOutput");
13116
- const outputIds = [...new Set(outputNodes.map((node) => node.data.id))].sort();
13117
- const outputs = outputIds.map(
13118
- (id) => ({
13119
- id,
13120
- title: id,
13121
- dataType: outputNodes.find((node) => node.data.id === id).data.dataType
13122
- })
13123
- );
13124
- return outputs;
14073
+ getGraphOutputs(project, definitionContext) {
14074
+ const boundary = this.getBoundary(project, definitionContext);
14075
+ return boundary ? getGraphBoundaryOutputDefinitions(boundary) : [];
13125
14076
  }
13126
- getOutputDefinitions(_connections, _nodes, project) {
14077
+ getOutputDefinitions(_connections, _nodes, project, _referencedProjects, definitionContext) {
13127
14078
  const outputs = [];
13128
- outputs.push(...this.getGraphOutputs(project));
14079
+ outputs.push(...this.getGraphOutputs(project, definitionContext));
13129
14080
  if (this.data.useErrorOutput) {
13130
14081
  outputs.push({
13131
14082
  id: "error",
@@ -13135,6 +14086,9 @@ var SubGraphNodeImpl = class extends NodeImpl {
13135
14086
  }
13136
14087
  return outputs;
13137
14088
  }
14089
+ getBoundary(project, definitionContext) {
14090
+ return (definitionContext == null ? void 0 : definitionContext.getGraphBoundary(project, this.data.graphId)) ?? getGraphBoundary(project, this.data.graphId);
14091
+ }
13138
14092
  getEditors(context) {
13139
14093
  const definitions = [
13140
14094
  {
@@ -13149,19 +14103,16 @@ var SubGraphNodeImpl = class extends NodeImpl {
13149
14103
  }
13150
14104
  ];
13151
14105
  if (this.data.graphId) {
13152
- const graph = context.project.graphs[this.data.graphId];
13153
- if (graph) {
13154
- const inputNodes = graph.nodes.filter((node) => node.type === "graphInput");
13155
- const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();
13156
- for (const inputId of inputIds) {
13157
- const inputNode = inputNodes.find((node) => node.data.id === inputId);
14106
+ const boundary = getGraphBoundary(context.project, this.data.graphId);
14107
+ if (boundary) {
14108
+ for (const input of boundary.inputs) {
13158
14109
  definitions.push({
13159
14110
  type: "dynamic",
13160
14111
  dataKey: "inputData",
13161
- dynamicDataKey: inputNode.data.id,
13162
- dataType: inputNode.data.dataType,
13163
- label: inputNode.data.id,
13164
- editor: inputNode.data.editor ?? "auto"
14112
+ dynamicDataKey: input.id,
14113
+ dataType: input.dataType,
14114
+ label: input.id,
14115
+ editor: input.editor ?? "auto"
13165
14116
  });
13166
14117
  }
13167
14118
  }
@@ -13179,6 +14130,7 @@ var SubGraphNodeImpl = class extends NodeImpl {
13179
14130
  };
13180
14131
  }
13181
14132
  async process(inputs, context) {
14133
+ var _a;
13182
14134
  const { project } = context;
13183
14135
  if (!project) {
13184
14136
  throw new Error("SubGraphNode requires a project to be set in the context.");
@@ -13187,24 +14139,8 @@ var SubGraphNodeImpl = class extends NodeImpl {
13187
14139
  if (!graph) {
13188
14140
  throw new Error(`SubGraphNode requires a graph with id ${this.data.graphId} to be present in the project.`);
13189
14141
  }
13190
- const inputNodes = graph.nodes.filter((node) => node.type === "graphInput");
13191
- const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();
13192
- const inputData = inputIds.reduce((obj, id) => {
13193
- var _a;
13194
- if (inputs[id] != null) {
13195
- return {
13196
- ...obj,
13197
- [id]: inputs[id]
13198
- };
13199
- }
13200
- if (((_a = this.data.inputData) == null ? void 0 : _a[id]) != null) {
13201
- return {
13202
- ...obj,
13203
- [id]: this.data.inputData[id]
13204
- };
13205
- }
13206
- return obj;
13207
- }, {});
14142
+ const boundary = ((_a = context.getGraphBoundary) == null ? void 0 : _a.call(context, project, this.data.graphId)) ?? getGraphBoundary(project, this.data.graphId);
14143
+ const inputData = buildGraphBoundaryInputData(boundary, inputs, this.data.inputData);
13208
14144
  const subGraphProcessor = context.createSubProcessor(this.data.graphId, { signal: context.signal });
13209
14145
  try {
13210
14146
  const startTime = Date.now();
@@ -13231,16 +14167,7 @@ var SubGraphNodeImpl = class extends NodeImpl {
13231
14167
  if (!this.data.useErrorOutput) {
13232
14168
  throw err;
13233
14169
  }
13234
- const outputs = this.getGraphOutputs(context.project).reduce(
13235
- (obj, output) => ({
13236
- ...obj,
13237
- [output.id]: {
13238
- type: "control-flow-excluded",
13239
- value: void 0
13240
- }
13241
- }),
13242
- {}
13243
- );
14170
+ const outputs = buildExcludedGraphBoundaryOutputs(boundary);
13244
14171
  outputs["error"] = {
13245
14172
  type: "string",
13246
14173
  value: getError(err).message
@@ -13253,7 +14180,7 @@ var subGraphNode = nodeDefinition(SubGraphNodeImpl, "Subgraph");
13253
14180
 
13254
14181
  // src/model/nodes/ArrayNode.ts
13255
14182
  var import_non_secure23 = require("nanoid/non-secure");
13256
- var import_lodash_es9 = require("lodash");
14183
+ var import_lodash_es8 = require("lodash");
13257
14184
  var import_ts_dedent21 = require("ts-dedent");
13258
14185
  var ArrayNodeImpl = class extends NodeImpl {
13259
14186
  static create() {
@@ -13359,7 +14286,7 @@ var ArrayNodeImpl = class extends NodeImpl {
13359
14286
  if (Array.isArray(input == null ? void 0 : input.value)) {
13360
14287
  for (const value of (input == null ? void 0 : input.value) ?? []) {
13361
14288
  if (this.data.flattenDeep) {
13362
- outputArray.push(...Array.isArray(value) ? (0, import_lodash_es9.flattenDeep)(value) : [value]);
14289
+ outputArray.push(...Array.isArray(value) ? (0, import_lodash_es8.flattenDeep)(value) : [value]);
13363
14290
  } else {
13364
14291
  outputArray.push(value);
13365
14292
  }
@@ -13516,7 +14443,7 @@ function createMatchedOutput(value) {
13516
14443
 
13517
14444
  // src/model/nodes/AssemblePromptNode.ts
13518
14445
  var import_non_secure25 = require("nanoid/non-secure");
13519
- var import_lodash_es10 = require("lodash");
14446
+ var import_lodash_es9 = require("lodash");
13520
14447
  var import_ts_dedent23 = require("ts-dedent");
13521
14448
  var AssemblePromptNodeImpl = class extends NodeImpl {
13522
14449
  static create() {
@@ -13623,7 +14550,7 @@ var AssemblePromptNodeImpl = class extends NodeImpl {
13623
14550
  const output = {};
13624
14551
  const isLastMessageCacheBreakpoint = getInputOrData(this.data, inputs, "isLastMessageCacheBreakpoint", "boolean");
13625
14552
  const outMessages = [];
13626
- const inputMessages = (0, import_lodash_es10.orderBy)(
14553
+ const inputMessages = (0, import_lodash_es9.orderBy)(
13627
14554
  Object.entries(inputs).filter(([key]) => key.startsWith("message")),
13628
14555
  ([key]) => key,
13629
14556
  "asc"
@@ -14177,7 +15104,7 @@ var trimChatMessagesNode = nodeDefinition(TrimChatMessagesNodeImpl, "Trim Chat M
14177
15104
 
14178
15105
  // src/model/nodes/ExternalCallNode.ts
14179
15106
  var import_non_secure29 = require("nanoid/non-secure");
14180
- var import_lodash_es11 = require("lodash");
15107
+ var import_lodash_es10 = require("lodash");
14181
15108
  var import_ts_dedent27 = require("ts-dedent");
14182
15109
  var ExternalCallNodeImpl = class extends NodeImpl {
14183
15110
  static create() {
@@ -14272,7 +15199,7 @@ var ExternalCallNodeImpl = class extends NodeImpl {
14272
15199
  }
14273
15200
  }
14274
15201
  const fn = context.externalFunctions[functionName];
14275
- const externalContext = (0, import_lodash_es11.omit)(context, ["setGlobal"]);
15202
+ const externalContext = (0, import_lodash_es10.omit)(context, ["setGlobal"]);
14276
15203
  if (!fn) {
14277
15204
  if (this.data.useErrorOutput) {
14278
15205
  return {
@@ -15121,7 +16048,8 @@ var SetGlobalNodeImpl = class extends NodeImpl {
15121
16048
  type: "string",
15122
16049
  dataKey: "id",
15123
16050
  useInputToggleDataKey: "useIdInput",
15124
- label: "ID"
16051
+ label: "ID",
16052
+ includeInGraphSearch: true
15125
16053
  },
15126
16054
  {
15127
16055
  type: "dataTypeSelector",
@@ -15156,7 +16084,7 @@ var SetGlobalNodeImpl = class extends NodeImpl {
15156
16084
  if (!id) {
15157
16085
  throw new Error("Missing variable ID");
15158
16086
  }
15159
- let previousValue = context.getGlobal(this.data.id);
16087
+ let previousValue = context.getGlobal(id);
15160
16088
  if (!previousValue && isArrayDataType(this.data.dataType)) {
15161
16089
  previousValue = { type: this.data.dataType, value: [] };
15162
16090
  } else if (!previousValue && isScalarDataType(this.data.dataType)) {
@@ -15190,9 +16118,9 @@ var GetGlobalNodeImpl = class extends NodeImpl {
15190
16118
  data: {
15191
16119
  id: "variable-name",
15192
16120
  dataType: "string",
15193
- onDemand: true,
16121
+ onDemand: false,
15194
16122
  useIdInput: false,
15195
- wait: false
16123
+ wait: true
15196
16124
  }
15197
16125
  };
15198
16126
  return chartNode;
@@ -15203,7 +16131,7 @@ var GetGlobalNodeImpl = class extends NodeImpl {
15203
16131
  {
15204
16132
  id: "id",
15205
16133
  title: "Variable ID",
15206
- dataType: this.data.dataType
16134
+ dataType: "string"
15207
16135
  }
15208
16136
  ];
15209
16137
  }
@@ -15226,11 +16154,18 @@ var GetGlobalNodeImpl = class extends NodeImpl {
15226
16154
  }
15227
16155
  getEditors() {
15228
16156
  return [
16157
+ {
16158
+ type: "custom",
16159
+ label: "Search Global Variables",
16160
+ customEditorId: "GetGlobalVariableSelector",
16161
+ autoFocus: true
16162
+ },
15229
16163
  {
15230
16164
  type: "string",
15231
16165
  label: "Variable ID",
15232
16166
  dataKey: "id",
15233
- useInputToggleDataKey: "useIdInput"
16167
+ useInputToggleDataKey: "useIdInput",
16168
+ includeInGraphSearch: true
15234
16169
  },
15235
16170
  {
15236
16171
  type: "dataTypeSelector",
@@ -15240,12 +16175,14 @@ var GetGlobalNodeImpl = class extends NodeImpl {
15240
16175
  {
15241
16176
  type: "toggle",
15242
16177
  label: "On Demand",
15243
- dataKey: "onDemand"
16178
+ dataKey: "onDemand",
16179
+ turnOffDataKeysWhenEnabled: ["wait"]
15244
16180
  },
15245
16181
  {
15246
16182
  type: "toggle",
15247
16183
  label: "Wait",
15248
- dataKey: "wait"
16184
+ dataKey: "wait",
16185
+ turnOffDataKeysWhenEnabled: ["onDemand"]
15249
16186
  }
15250
16187
  ];
15251
16188
  }
@@ -15271,11 +16208,11 @@ var GetGlobalNodeImpl = class extends NodeImpl {
15271
16208
  if (this.data.wait) {
15272
16209
  throw new Error("Cannot use onDemand and wait together");
15273
16210
  }
16211
+ const id2 = this.data.useIdInput ? coerceType(inputs["id"], "string") : this.data.id;
15274
16212
  return {
15275
16213
  ["value"]: {
15276
16214
  type: `fn<${this.data.dataType}>`,
15277
16215
  value: () => {
15278
- const id2 = this.data.useIdInput ? coerceType(inputs["id"], "string") : this.data.id;
15279
16216
  const value2 = context.getGlobal(id2);
15280
16217
  if (value2) {
15281
16218
  return value2.value;
@@ -15285,7 +16222,8 @@ var GetGlobalNodeImpl = class extends NodeImpl {
15285
16222
  }
15286
16223
  return scalarDefaults[this.data.dataType];
15287
16224
  }
15288
- }
16225
+ },
16226
+ ["variable_id_out"]: { type: "string", value: id2 }
15289
16227
  };
15290
16228
  }
15291
16229
  const id = this.data.useIdInput ? coerceType(inputs["id"], "string") : this.data.id;
@@ -16461,7 +17399,7 @@ var joinNode = nodeDefinition(JoinNodeImpl, "Coalesce");
16461
17399
 
16462
17400
  // src/model/nodes/FilterNode.ts
16463
17401
  var import_non_secure50 = require("nanoid/non-secure");
16464
- var import_lodash_es12 = require("lodash");
17402
+ var import_lodash_es11 = require("lodash");
16465
17403
  var import_ts_dedent48 = require("ts-dedent");
16466
17404
  var FilterNodeImpl = class extends NodeImpl {
16467
17405
  static create() {
@@ -16517,7 +17455,7 @@ var FilterNodeImpl = class extends NodeImpl {
16517
17455
  var _a;
16518
17456
  const array = coerceType(inputs["array"], "any[]");
16519
17457
  const include = coerceType(inputs["include"], "boolean[]");
16520
- const zipped = (0, import_lodash_es12.zip)(array, include);
17458
+ const zipped = (0, import_lodash_es11.zip)(array, include);
16521
17459
  const filtered = zipped.filter(([_, include2]) => include2).map(([value, _]) => value);
16522
17460
  return {
16523
17461
  ["filtered"]: {
@@ -17120,7 +18058,7 @@ var booleanNode = nodeDefinition(BooleanNodeImpl, "Boolean");
17120
18058
 
17121
18059
  // src/model/nodes/CompareNode.ts
17122
18060
  var import_non_secure55 = require("nanoid/non-secure");
17123
- var import_lodash_es13 = require("lodash");
18061
+ var import_lodash_es12 = require("lodash");
17124
18062
  var import_ts_pattern5 = require("ts-pattern");
17125
18063
  var import_ts_dedent54 = require("ts-dedent");
17126
18064
  var CompareNodeImpl = class extends NodeImpl {
@@ -17233,7 +18171,7 @@ var CompareNodeImpl = class extends NodeImpl {
17233
18171
  return {
17234
18172
  ["output"]: {
17235
18173
  type: "boolean",
17236
- value: (0, import_ts_pattern5.match)(comparisonFunction).with("==", () => (0, import_lodash_es13.isEqual)(value1, value2)).with("!=", () => !(0, import_lodash_es13.isEqual)(value1, value2)).with("<", () => compareValues(value1, value2)["<"]).with(">", () => compareValues(value1, value2)[">"]).with("<=", () => compareValues(value1, value2)["<="]).with(">=", () => compareValues(value1, value2)[">="]).with("and", () => !!(value1 && value2)).with("or", () => !!(value1 || value2)).with("xor", () => !!(value1 ? !value2 : value2)).with("nand", () => !(value1 && value2)).with("nor", () => !(value1 || value2)).with("xnor", () => !(value1 ? !value2 : value2)).exhaustive()
18174
+ value: (0, import_ts_pattern5.match)(comparisonFunction).with("==", () => (0, import_lodash_es12.isEqual)(value1, value2)).with("!=", () => !(0, import_lodash_es12.isEqual)(value1, value2)).with("<", () => compareValues(value1, value2)["<"]).with(">", () => compareValues(value1, value2)[">"]).with("<=", () => compareValues(value1, value2)["<="]).with(">=", () => compareValues(value1, value2)[">="]).with("and", () => !!(value1 && value2)).with("or", () => !!(value1 || value2)).with("xor", () => !!(value1 ? !value2 : value2)).with("nand", () => !(value1 && value2)).with("nor", () => !(value1 || value2)).with("xnor", () => !(value1 ? !value2 : value2)).exhaustive()
17237
18175
  }
17238
18176
  };
17239
18177
  }
@@ -17553,7 +18491,7 @@ var randomNumberNode = nodeDefinition(RandomNumberNodeImpl, "Random number");
17553
18491
 
17554
18492
  // src/model/nodes/ShuffleNode.ts
17555
18493
  var import_non_secure59 = require("nanoid/non-secure");
17556
- var import_lodash_es14 = require("lodash");
18494
+ var import_lodash_es13 = require("lodash");
17557
18495
  var import_ts_dedent58 = require("ts-dedent");
17558
18496
  var ShuffleNodeImpl = class extends NodeImpl {
17559
18497
  static create() {
@@ -17602,7 +18540,7 @@ var ShuffleNodeImpl = class extends NodeImpl {
17602
18540
  var _a;
17603
18541
  const input = inputs["array"];
17604
18542
  const items = input ? isArrayDataValue(input) ? input.value : [input.value] : [];
17605
- const shuffled = (0, import_lodash_es14.shuffle)(items);
18543
+ const shuffled = (0, import_lodash_es13.shuffle)(items);
17606
18544
  return {
17607
18545
  ["shuffled"]: {
17608
18546
  type: ((_a = inputs["array"]) == null ? void 0 : _a.type) ?? "any[]",
@@ -17950,7 +18888,7 @@ function recordHttpCallThrownAttempt(attempts, error, signal) {
17950
18888
  attempts.requestFailedValues.push(true);
17951
18889
  attempts.requestErrorMessages.push(formatCaughtRequestFailureError(error));
17952
18890
  }
17953
- function buildRetryAttemptOutput2(type, values2) {
18891
+ function buildRetryAttemptOutput(type, values2) {
17954
18892
  return values2.length > 0 ? {
17955
18893
  type,
17956
18894
  value: values2
@@ -18025,7 +18963,7 @@ async function waitForRetryCooldown(cooldownMs, signal) {
18025
18963
  }
18026
18964
  function buildRequestFailedOutputs(params) {
18027
18965
  const sharedOutputs = {
18028
- [STATUS_CODE_OUTPUT_ID]: params.retryOnNon200 ? buildRetryAttemptOutput2("number[]", params.attempts.statusCodeValues) : {
18966
+ [STATUS_CODE_OUTPUT_ID]: params.retryOnNon200 ? buildRetryAttemptOutput("number[]", params.attempts.statusCodeValues) : {
18029
18967
  type: "control-flow-excluded",
18030
18968
  value: void 0
18031
18969
  },
@@ -18058,11 +18996,11 @@ function buildRequestFailedOutputs(params) {
18058
18996
  function buildCaughtRequestFailedResult(params) {
18059
18997
  const attempts = params.retryOnNon200 ? withCaughtFailureAttemptFallback(params.attempts, params.error) : params.attempts;
18060
18998
  const outputs = {
18061
- [REQUEST_ERROR_OUTPUT_ID]: params.retryOnNon200 ? buildRetryAttemptOutput2("string[]", attempts.requestErrorMessages) : {
18999
+ [REQUEST_ERROR_OUTPUT_ID]: params.retryOnNon200 ? buildRetryAttemptOutput("string[]", attempts.requestErrorMessages) : {
18062
19000
  type: "string",
18063
19001
  value: formatCaughtRequestFailureError(params.error)
18064
19002
  },
18065
- [REQUEST_FAILED_OUTPUT_ID]: params.retryOnNon200 ? buildRetryAttemptOutput2("boolean[]", attempts.requestFailedValues) : {
19003
+ [REQUEST_FAILED_OUTPUT_ID]: params.retryOnNon200 ? buildRetryAttemptOutput("boolean[]", attempts.requestFailedValues) : {
18066
19004
  type: "boolean",
18067
19005
  value: true
18068
19006
  },
@@ -18307,7 +19245,7 @@ var HttpCallNodeImpl = class extends NodeImpl {
18307
19245
  }
18308
19246
  async process(inputs, context) {
18309
19247
  var _a;
18310
- const requestAttempts = createHttpCallRequestAttempts();
19248
+ const requestAttempts = this.data.retryOnNon200 ? createHttpCallRequestAttempts() : void 0;
18311
19249
  try {
18312
19250
  const method = getInputOrData(this.data, inputs, "method", "string");
18313
19251
  const url = getInputOrData(this.data, inputs, "url", "string");
@@ -18365,7 +19303,7 @@ var HttpCallNodeImpl = class extends NodeImpl {
18365
19303
  throw err;
18366
19304
  }
18367
19305
  };
18368
- const performTrackedRequest = async () => {
19306
+ const performTrackedRequest = requestAttempts ? async () => {
18369
19307
  try {
18370
19308
  const response2 = await performRequest();
18371
19309
  recordHttpCallResponseAttempt(requestAttempts, response2);
@@ -18374,9 +19312,9 @@ var HttpCallNodeImpl = class extends NodeImpl {
18374
19312
  recordHttpCallThrownAttempt(requestAttempts, error, context.signal);
18375
19313
  throw error;
18376
19314
  }
18377
- };
19315
+ } : performRequest;
18378
19316
  let response = await performTrackedRequest();
18379
- if (this.data.retryOnNon200) {
19317
+ if (requestAttempts) {
18380
19318
  const repeatTimes = normalizeHttpRetryCount(this.data.retryOnNon200RepeatTimes);
18381
19319
  const cooldownMs = normalizeHttpRetryCooldownMs(this.data.retryOnNon200CooldownMs);
18382
19320
  for (let attempt = 0; response.status !== 200 && attempt < repeatTimes; attempt++) {
@@ -18388,7 +19326,7 @@ var HttpCallNodeImpl = class extends NodeImpl {
18388
19326
  throw buildNon2xxStatusCodeError(response.status);
18389
19327
  }
18390
19328
  const output = {
18391
- [STATUS_CODE_OUTPUT_ID]: this.data.retryOnNon200 ? buildRetryAttemptOutput2("number[]", requestAttempts.statusCodeValues) : {
19329
+ [STATUS_CODE_OUTPUT_ID]: requestAttempts ? buildRetryAttemptOutput("number[]", requestAttempts.statusCodeValues) : {
18392
19330
  type: "number",
18393
19331
  value: response.status
18394
19332
  },
@@ -18422,12 +19360,12 @@ var HttpCallNodeImpl = class extends NodeImpl {
18422
19360
  };
18423
19361
  }
18424
19362
  }
18425
- if (this.data.catchRequestFailed || this.data.retryOnNon200) {
18426
- output[REQUEST_FAILED_OUTPUT_ID] = this.data.retryOnNon200 ? buildRetryAttemptOutput2("boolean[]", requestAttempts.requestFailedValues) : {
19363
+ if (this.data.catchRequestFailed || requestAttempts) {
19364
+ output[REQUEST_FAILED_OUTPUT_ID] = requestAttempts ? buildRetryAttemptOutput("boolean[]", requestAttempts.requestFailedValues) : {
18427
19365
  type: "boolean",
18428
19366
  value: false
18429
19367
  };
18430
- output[REQUEST_ERROR_OUTPUT_ID] = this.data.retryOnNon200 ? buildRetryAttemptOutput2("string[]", requestAttempts.requestErrorMessages) : {
19368
+ output[REQUEST_ERROR_OUTPUT_ID] = requestAttempts ? buildRetryAttemptOutput("string[]", requestAttempts.requestErrorMessages) : {
18431
19369
  type: "control-flow-excluded",
18432
19370
  value: void 0
18433
19371
  };
@@ -18438,8 +19376,8 @@ var HttpCallNodeImpl = class extends NodeImpl {
18438
19376
  return buildCaughtRequestFailedResult({
18439
19377
  isBinaryOutput: Boolean(this.data.isBinaryOutput),
18440
19378
  error,
18441
- retryOnNon200: Boolean(this.data.retryOnNon200),
18442
- attempts: requestAttempts
19379
+ retryOnNon200: requestAttempts != null,
19380
+ attempts: requestAttempts ?? createHttpCallRequestAttempts()
18443
19381
  });
18444
19382
  }
18445
19383
  throw error;
@@ -19356,7 +20294,7 @@ var extractMarkdownCodeBlocksNode = nodeDefinition(
19356
20294
 
19357
20295
  // src/model/nodes/AssembleMessageNode.ts
19358
20296
  var import_non_secure68 = require("nanoid/non-secure");
19359
- var import_lodash_es15 = require("lodash");
20297
+ var import_lodash_es14 = require("lodash");
19360
20298
  var import_ts_pattern7 = require("ts-pattern");
19361
20299
  var messageTypeToTitle = {
19362
20300
  assistant: "Assistant",
@@ -19513,7 +20451,7 @@ var AssembleMessageNodeImpl = class extends NodeImpl {
19513
20451
  ).otherwise(() => {
19514
20452
  throw new Error(`Invalid type: ${type}`);
19515
20453
  });
19516
- const inputParts = (0, import_lodash_es15.orderBy)(
20454
+ const inputParts = (0, import_lodash_es14.orderBy)(
19517
20455
  Object.entries(inputs).filter(([key]) => key.startsWith("part")),
19518
20456
  ([key]) => key,
19519
20457
  "asc"
@@ -20047,9 +20985,9 @@ var import_non_secure73 = require("nanoid/non-secure");
20047
20985
  var import_ts_dedent67 = require("ts-dedent");
20048
20986
 
20049
20987
  // src/api/looseDataValue.ts
20050
- var import_lodash_es16 = require("lodash");
20988
+ var import_lodash_es15 = require("lodash");
20051
20989
  function looseDataValuesToDataValues(values2) {
20052
- return (0, import_lodash_es16.mapValues)(values2, (val) => looseDataValueToDataValue(val));
20990
+ return (0, import_lodash_es15.mapValues)(values2, (val) => looseDataValueToDataValue(val));
20053
20991
  }
20054
20992
  function looseDataValueToDataValue(value) {
20055
20993
  if (typeof value === "string") {
@@ -21289,7 +22227,7 @@ var cronNode = nodeDefinition(CronNodeImpl, "Cron");
21289
22227
  // src/model/nodes/ToTreeNode.ts
21290
22228
  var import_non_secure79 = require("nanoid/non-secure");
21291
22229
  var import_ts_dedent73 = require("ts-dedent");
21292
- var import_lodash_es17 = require("lodash");
22230
+ var import_lodash_es16 = require("lodash");
21293
22231
  var ToTreeNodeImpl = class extends NodeImpl {
21294
22232
  static create() {
21295
22233
  const chartNode = {
@@ -21375,7 +22313,7 @@ var ToTreeNodeImpl = class extends NodeImpl {
21375
22313
  if (!Array.isArray(objects) || objects.length === 0)
21376
22314
  return "";
21377
22315
  let result = "";
21378
- const sortedObjects = this.data.useSortAlphabetically ? (0, import_lodash_es17.sortBy)(objects, (obj) => String((0, import_lodash_es17.get)(obj, "path", ""))) : objects;
22316
+ const sortedObjects = this.data.useSortAlphabetically ? (0, import_lodash_es16.sortBy)(objects, (obj) => String((0, import_lodash_es16.get)(obj, "path", ""))) : objects;
21379
22317
  sortedObjects.forEach((obj, index) => {
21380
22318
  const isLastItem = index === sortedObjects.length - 1;
21381
22319
  const prefix = level === 0 ? "" : isLast ? "\u2514\u2500\u2500 " : "\u251C\u2500\u2500 ";
@@ -21384,14 +22322,14 @@ var ToTreeNodeImpl = class extends NodeImpl {
21384
22322
  const interpolationVars = matches.reduce(
21385
22323
  (acc, match10) => {
21386
22324
  const key = match10;
21387
- acc[key] = String((0, import_lodash_es17.get)(obj, key, ""));
22325
+ acc[key] = String((0, import_lodash_es16.get)(obj, key, ""));
21388
22326
  return acc;
21389
22327
  },
21390
22328
  {}
21391
22329
  );
21392
22330
  const formattedNode = interpolate(this.data.format, interpolationVars);
21393
22331
  result += indent + prefix + formattedNode + "\n";
21394
- const children = (0, import_lodash_es17.get)(obj, this.data.childrenProperty);
22332
+ const children = (0, import_lodash_es16.get)(obj, this.data.childrenProperty);
21395
22333
  if (Array.isArray(children) && children.length > 0) {
21396
22334
  const newPath = parentPath ? `${parentPath}/${formattedNode}` : formattedNode;
21397
22335
  result += this.buildTree(children, newPath, level + 1, isLastItem);
@@ -21433,38 +22371,13 @@ var LoopUntilNodeImpl = class extends NodeImpl {
21433
22371
  };
21434
22372
  return chartNode;
21435
22373
  }
21436
- getInputDefinitions(_connections, _nodes, project) {
21437
- const inputs = [];
21438
- const graph = project.graphs[this.data.targetGraph ?? ""];
21439
- if (graph) {
21440
- const inputNodes = graph.nodes.filter((node) => node.type === "graphInput");
21441
- const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();
21442
- inputIds.forEach((id) => {
21443
- const inputNode = inputNodes.find((node) => node.data.id === id);
21444
- inputs.push({
21445
- id,
21446
- title: id,
21447
- dataType: inputNode.data.dataType
21448
- });
21449
- });
21450
- }
21451
- return inputs;
22374
+ getInputDefinitions(_connections, _nodes, project, _referencedProjects, definitionContext) {
22375
+ const boundary = this.getBoundary(project, definitionContext);
22376
+ return boundary ? getGraphBoundaryInputDefinitions(boundary) : [];
21452
22377
  }
21453
- getOutputDefinitions(_connections, _nodes, project) {
21454
- const outputs = [];
21455
- const graph = project.graphs[this.data.targetGraph ?? ""];
21456
- if (graph) {
21457
- const outputNodes = graph.nodes.filter((node) => node.type === "graphOutput");
21458
- const outputIds = [...new Set(outputNodes.map((node) => node.data.id))].sort();
21459
- outputIds.forEach((id) => {
21460
- const outputNode = outputNodes.find((node) => node.data.id === id);
21461
- outputs.push({
21462
- id,
21463
- title: id,
21464
- dataType: outputNode.data.dataType
21465
- });
21466
- });
21467
- }
22378
+ getOutputDefinitions(_connections, _nodes, project, _referencedProjects, definitionContext) {
22379
+ const boundary = this.getBoundary(project, definitionContext);
22380
+ const outputs = boundary ? getGraphBoundaryOutputDefinitions(boundary) : [];
21468
22381
  outputs.push(
21469
22382
  {
21470
22383
  id: "iteration",
@@ -21523,19 +22436,16 @@ var LoopUntilNodeImpl = class extends NodeImpl {
21523
22436
  );
21524
22437
  }
21525
22438
  if (this.data.targetGraph) {
21526
- const graph = context.project.graphs[this.data.targetGraph];
21527
- if (graph) {
21528
- const inputNodes = graph.nodes.filter((node) => node.type === "graphInput");
21529
- const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();
21530
- for (const inputId of inputIds) {
21531
- const inputNode = inputNodes.find((node) => node.data.id === inputId);
22439
+ const boundary = getGraphBoundary(context.project, this.data.targetGraph);
22440
+ if (boundary) {
22441
+ for (const input of boundary.inputs) {
21532
22442
  definitions.push({
21533
22443
  type: "dynamic",
21534
22444
  dataKey: "inputData",
21535
- dynamicDataKey: inputNode.data.id,
21536
- dataType: inputNode.data.dataType,
21537
- label: inputNode.data.id,
21538
- editor: inputNode.data.editor ?? "auto"
22445
+ dynamicDataKey: input.id,
22446
+ dataType: input.dataType,
22447
+ label: input.id,
22448
+ editor: input.editor ?? "auto"
21539
22449
  });
21540
22450
  }
21541
22451
  }
@@ -21566,6 +22476,9 @@ Max iterations: ${this.data.maxIterations}` : "";
21566
22476
  return `Executes ${graphName}
21567
22477
  until ${condition}${maxIterations}`;
21568
22478
  }
22479
+ getBoundary(project, definitionContext) {
22480
+ return (definitionContext == null ? void 0 : definitionContext.getGraphBoundary(project, this.data.targetGraph)) ?? getGraphBoundary(project, this.data.targetGraph);
22481
+ }
21569
22482
  shouldBreak(outputs) {
21570
22483
  var _a;
21571
22484
  if (this.data.conditionType === "allOutputsSet") {
@@ -22397,48 +23310,25 @@ var ReferencedGraphAliasNodeImpl = class extends NodeImpl {
22397
23310
  };
22398
23311
  return chartNode;
22399
23312
  }
22400
- getInputDefinitions(_connections, _nodes, _project, referencedProjects) {
23313
+ getInputDefinitions(_connections, _nodes, _project, referencedProjects, definitionContext) {
22401
23314
  const referencedProject = referencedProjects[this.data.projectId];
22402
23315
  if (!referencedProject) {
22403
23316
  return [];
22404
23317
  }
22405
- const graph = referencedProject.graphs[this.data.graphId];
22406
- if (!graph) {
22407
- return [];
22408
- }
22409
- const inputNodes = graph.nodes.filter((node) => node.type === "graphInput");
22410
- const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();
22411
- return inputIds.map(
22412
- (id) => ({
22413
- id,
22414
- title: id,
22415
- dataType: inputNodes.find((node) => node.data.id === id).data.dataType
22416
- })
22417
- );
23318
+ const boundary = this.getBoundary(referencedProject, definitionContext);
23319
+ return boundary ? getGraphBoundaryInputDefinitions(boundary) : [];
22418
23320
  }
22419
- getGraphOutputs(referencedProject) {
22420
- const graph = referencedProject.graphs[this.data.graphId];
22421
- if (!graph) {
22422
- return [];
22423
- }
22424
- const outputNodes = graph.nodes.filter((node) => node.type === "graphOutput");
22425
- const outputIds = [...new Set(outputNodes.map((node) => node.data.id))].sort();
22426
- const outputs = outputIds.map(
22427
- (id) => ({
22428
- id,
22429
- title: id,
22430
- dataType: outputNodes.find((node) => node.data.id === id).data.dataType
22431
- })
22432
- );
22433
- return outputs;
23321
+ getGraphOutputs(referencedProject, definitionContext) {
23322
+ const boundary = this.getBoundary(referencedProject, definitionContext);
23323
+ return boundary ? getGraphBoundaryOutputDefinitions(boundary) : [];
22434
23324
  }
22435
- getOutputDefinitions(_connections, _nodes, _project, referencedProjects) {
23325
+ getOutputDefinitions(_connections, _nodes, _project, referencedProjects, definitionContext) {
22436
23326
  const outputs = [];
22437
23327
  const referencedProject = referencedProjects[this.data.projectId];
22438
23328
  if (!referencedProject) {
22439
23329
  return outputs;
22440
23330
  }
22441
- outputs.push(...this.getGraphOutputs(referencedProject));
23331
+ outputs.push(...this.getGraphOutputs(referencedProject, definitionContext));
22442
23332
  if (this.data.useErrorOutput) {
22443
23333
  outputs.push({
22444
23334
  id: "error",
@@ -22448,6 +23338,9 @@ var ReferencedGraphAliasNodeImpl = class extends NodeImpl {
22448
23338
  }
22449
23339
  return outputs;
22450
23340
  }
23341
+ getBoundary(referencedProject, definitionContext) {
23342
+ return (definitionContext == null ? void 0 : definitionContext.getGraphBoundary(referencedProject, this.data.graphId)) ?? getGraphBoundary(referencedProject, this.data.graphId);
23343
+ }
22451
23344
  getEditors(context) {
22452
23345
  const definitions = [
22453
23346
  {
@@ -22463,19 +23356,16 @@ var ReferencedGraphAliasNodeImpl = class extends NodeImpl {
22463
23356
  ];
22464
23357
  const referencedProject = context.referencedProjects[this.data.projectId];
22465
23358
  if (referencedProject) {
22466
- const graph = referencedProject.graphs[this.data.graphId];
22467
- if (graph) {
22468
- const inputNodes = graph.nodes.filter((node) => node.type === "graphInput");
22469
- const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();
22470
- for (const inputId of inputIds) {
22471
- const inputNode = inputNodes.find((node) => node.data.id === inputId);
23359
+ const boundary = getGraphBoundary(referencedProject, this.data.graphId);
23360
+ if (boundary) {
23361
+ for (const input of boundary.inputs) {
22472
23362
  definitions.push({
22473
23363
  type: "dynamic",
22474
23364
  dataKey: "inputData",
22475
- dynamicDataKey: inputNode.data.id,
22476
- dataType: inputNode.data.dataType,
22477
- label: inputNode.data.id,
22478
- editor: inputNode.data.editor ?? "auto"
23365
+ dynamicDataKey: input.id,
23366
+ dataType: input.dataType,
23367
+ label: input.id,
23368
+ editor: input.editor ?? "auto"
22479
23369
  });
22480
23370
  }
22481
23371
  }
@@ -22497,6 +23387,7 @@ var ReferencedGraphAliasNodeImpl = class extends NodeImpl {
22497
23387
  };
22498
23388
  }
22499
23389
  async process(inputs, context) {
23390
+ var _a;
22500
23391
  const referencedProject = context.referencedProjects[this.data.projectId];
22501
23392
  if (!referencedProject) {
22502
23393
  throw new Error(
@@ -22509,24 +23400,8 @@ var ReferencedGraphAliasNodeImpl = class extends NodeImpl {
22509
23400
  `ReferencedGraphAliasNode requires a graph with id ${this.data.graphId} to be present in the referenced project.`
22510
23401
  );
22511
23402
  }
22512
- const inputNodes = graph.nodes.filter((node) => node.type === "graphInput");
22513
- const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();
22514
- const inputData = inputIds.reduce((obj, id) => {
22515
- var _a;
22516
- if (inputs[id] != null) {
22517
- return {
22518
- ...obj,
22519
- [id]: inputs[id]
22520
- };
22521
- }
22522
- if (((_a = this.data.inputData) == null ? void 0 : _a[id]) != null) {
22523
- return {
22524
- ...obj,
22525
- [id]: this.data.inputData[id]
22526
- };
22527
- }
22528
- return obj;
22529
- }, {});
23403
+ const boundary = ((_a = context.getGraphBoundary) == null ? void 0 : _a.call(context, referencedProject, this.data.graphId)) ?? getGraphBoundary(referencedProject, this.data.graphId);
23404
+ const inputData = buildGraphBoundaryInputData(boundary, inputs, this.data.inputData);
22530
23405
  const subGraphProcessor = context.createSubProcessor(this.data.graphId, {
22531
23406
  signal: context.signal,
22532
23407
  project: referencedProject
@@ -22560,16 +23435,7 @@ var ReferencedGraphAliasNodeImpl = class extends NodeImpl {
22560
23435
  if (!this.data.useErrorOutput) {
22561
23436
  throw err;
22562
23437
  }
22563
- const outputs = this.getGraphOutputs(referencedProject).reduce(
22564
- (obj, output) => ({
22565
- ...obj,
22566
- [output.id]: {
22567
- type: "control-flow-excluded",
22568
- value: void 0
22569
- }
22570
- }),
22571
- {}
22572
- );
23438
+ const outputs = buildExcludedGraphBoundaryOutputs(boundary);
22573
23439
  outputs["error"] = {
22574
23440
  type: "string",
22575
23441
  value: getError(err).message
@@ -22645,6 +23511,82 @@ var BrowserNativeApi = class {
22645
23511
  }
22646
23512
  };
22647
23513
 
23514
+ // src/model/DebuggerTransportSentinel.ts
23515
+ var DEBUGGER_TRANSPORT_SENTINEL_KEY = "__rivetDebuggerTransportSentinel";
23516
+ var DEBUGGER_TRANSPORT_SENTINEL_VERSION = 1;
23517
+ function createDebuggerTransportUndefinedSentinel() {
23518
+ return {
23519
+ [DEBUGGER_TRANSPORT_SENTINEL_KEY]: {
23520
+ type: "undefined",
23521
+ version: DEBUGGER_TRANSPORT_SENTINEL_VERSION
23522
+ }
23523
+ };
23524
+ }
23525
+ function createDebuggerTransportEscapedSentinel(value) {
23526
+ return {
23527
+ [DEBUGGER_TRANSPORT_SENTINEL_KEY]: {
23528
+ type: "escaped-sentinel",
23529
+ version: DEBUGGER_TRANSPORT_SENTINEL_VERSION,
23530
+ value
23531
+ }
23532
+ };
23533
+ }
23534
+ function createDebuggerTransportEscapedSentinelEnvelope(value) {
23535
+ return createDebuggerTransportEscapedSentinel(getDebuggerTransportSentinel(value) ?? value);
23536
+ }
23537
+ function isDebuggerTransportSentinelEnvelope(value) {
23538
+ return getDebuggerTransportSentinel(value) != null;
23539
+ }
23540
+ function decodeDebuggerTransportSentinels(value) {
23541
+ return decodeDebuggerTransportSentinelsInner(value);
23542
+ }
23543
+ function decodeDebuggerTransportSentinelsInner(value) {
23544
+ const sentinel = getDebuggerTransportSentinel(value);
23545
+ if (sentinel) {
23546
+ if (sentinel.type === "undefined") {
23547
+ return void 0;
23548
+ }
23549
+ if (sentinel.type === "escaped-sentinel") {
23550
+ return {
23551
+ [DEBUGGER_TRANSPORT_SENTINEL_KEY]: decodeDebuggerTransportSentinelsInner(sentinel.value)
23552
+ };
23553
+ }
23554
+ }
23555
+ if (Array.isArray(value)) {
23556
+ return value.map((item) => decodeDebuggerTransportSentinelsInner(item));
23557
+ }
23558
+ if (typeof value !== "object" || value == null) {
23559
+ return value;
23560
+ }
23561
+ const decoded = {};
23562
+ for (const [key, item] of Object.entries(value)) {
23563
+ decoded[key] = decodeDebuggerTransportSentinelsInner(item);
23564
+ }
23565
+ return decoded;
23566
+ }
23567
+ function getDebuggerTransportSentinel(value) {
23568
+ if (typeof value !== "object" || value == null || Array.isArray(value)) {
23569
+ return void 0;
23570
+ }
23571
+ const valueKeys = Object.keys(value);
23572
+ if (valueKeys.length !== 1 || valueKeys[0] !== DEBUGGER_TRANSPORT_SENTINEL_KEY) {
23573
+ return void 0;
23574
+ }
23575
+ const sentinel = value[DEBUGGER_TRANSPORT_SENTINEL_KEY];
23576
+ if (typeof sentinel !== "object" || sentinel == null || Array.isArray(sentinel)) {
23577
+ return void 0;
23578
+ }
23579
+ const typedSentinel = sentinel;
23580
+ const sentinelKeys = Object.keys(typedSentinel);
23581
+ if (typedSentinel.type === "undefined") {
23582
+ return sentinelKeys.length === 2 && typedSentinel.version === DEBUGGER_TRANSPORT_SENTINEL_VERSION ? typedSentinel : void 0;
23583
+ }
23584
+ if (typedSentinel.type === "escaped-sentinel") {
23585
+ return sentinelKeys.length === 3 && typedSentinel.version === DEBUGGER_TRANSPORT_SENTINEL_VERSION ? typedSentinel : void 0;
23586
+ }
23587
+ return void 0;
23588
+ }
23589
+
22648
23590
  // src/integrations/openai/OpenAIEmbeddingGenerator.ts
22649
23591
  var import_openai6 = require("openai");
22650
23592
  var OpenAIEmbeddingGenerator = class {
@@ -22675,7 +23617,7 @@ registerIntegration("embeddingGenerator", "openai", (context) => new OpenAIEmbed
22675
23617
  // src/recording/ExecutionRecorder.ts
22676
23618
  var import_non_secure84 = require("nanoid/non-secure");
22677
23619
  var import_emittery2 = __toESM(require("emittery-0-13"), 1);
22678
- var import_lodash_es18 = require("lodash");
23620
+ var import_lodash_es17 = require("lodash");
22679
23621
  var import_json_stream_es = require("json-stream-es");
22680
23622
 
22681
23623
  // src/vendor/fnv1a.js
@@ -22739,6 +23681,13 @@ function fnv1a(value, { size = 32, utf8Buffer } = {}) {
22739
23681
  function withExecution(base, execution) {
22740
23682
  return execution == null ? base : { ...base, execution };
22741
23683
  }
23684
+ function withDuration(base, durationMs, splitRunDurationMs) {
23685
+ return {
23686
+ ...base,
23687
+ ...durationMs === void 0 ? {} : { durationMs },
23688
+ ...splitRunDurationMs === void 0 ? {} : { splitRunDurationMs }
23689
+ };
23690
+ }
22742
23691
  var toRecordedEventMap = {
22743
23692
  graphStart: ({ graph, inputs, execution }) => withExecution({ graphId: graph.metadata.id, inputs }, execution),
22744
23693
  graphFinish: ({ graph, outputs, execution }) => withExecution({ graphId: graph.metadata.id, outputs }, execution),
@@ -22751,16 +23700,16 @@ var toRecordedEventMap = {
22751
23700
  inputs,
22752
23701
  processId
22753
23702
  }, execution),
22754
- nodeFinish: ({ node, outputs, processId, execution }) => withExecution({
23703
+ nodeFinish: ({ node, outputs, processId, durationMs, splitRunDurationMs, execution }) => withExecution(withDuration({
22755
23704
  nodeId: node.id,
22756
23705
  outputs,
22757
23706
  processId
22758
- }, execution),
22759
- nodeError: ({ node, error, processId, execution }) => withExecution({
23707
+ }, durationMs, splitRunDurationMs), execution),
23708
+ nodeError: ({ node, error, processId, durationMs, splitRunDurationMs, execution }) => withExecution(withDuration({
22760
23709
  nodeId: node.id,
22761
23710
  error: typeof error === "string" ? error : error.stack,
22762
23711
  processId
22763
- }, execution),
23712
+ }, durationMs, splitRunDurationMs), execution),
22764
23713
  abort: ({ successful, error }) => ({ successful, error: typeof error === "string" ? error : error == null ? void 0 : error.stack }),
22765
23714
  graphAbort: ({ successful, error, graph, execution }) => withExecution({
22766
23715
  successful,
@@ -22836,16 +23785,16 @@ function toRecordedEvent(event, data) {
22836
23785
  function mapValuesDeep(obj, fn) {
22837
23786
  if (Array.isArray(obj)) {
22838
23787
  return obj.map((value) => {
22839
- if ((0, import_lodash_es18.isPlainObject)(value) || Array.isArray(value)) {
23788
+ if ((0, import_lodash_es17.isPlainObject)(value) || Array.isArray(value)) {
22840
23789
  return mapValuesDeep(value, fn);
22841
23790
  }
22842
23791
  return fn(value);
22843
23792
  });
22844
23793
  }
22845
- if ((0, import_lodash_es18.isPlainObject)(obj)) {
23794
+ if ((0, import_lodash_es17.isPlainObject)(obj)) {
22846
23795
  return Object.fromEntries(
22847
23796
  Object.entries(obj).map(([key, value]) => {
22848
- if ((0, import_lodash_es18.isPlainObject)(value) || Array.isArray(value)) {
23797
+ if ((0, import_lodash_es17.isPlainObject)(value) || Array.isArray(value)) {
22849
23798
  return [key, mapValuesDeep(value, fn)];
22850
23799
  }
22851
23800
  return [key, fn(value)];
@@ -22938,7 +23887,7 @@ var ExecutionRecorder = class _ExecutionRecorder {
22938
23887
  return;
22939
23888
  }
22940
23889
  this.#events.push(toRecordedEvent(message, data));
22941
- if (message === "done" || message === "abort" || message === "error") {
23890
+ if (isRecordingTerminalEvent(message, data)) {
22942
23891
  emitDetached(this.#emitter, "finish", {
22943
23892
  recording: this.getRecording()
22944
23893
  });
@@ -22959,7 +23908,7 @@ var ExecutionRecorder = class _ExecutionRecorder {
22959
23908
  return;
22960
23909
  }
22961
23910
  this.#events.push(toRecordedEvent(event, data));
22962
- if (event === "done" || event === "abort" || event === "error") {
23911
+ if (isRecordingTerminalEvent(event, data)) {
22963
23912
  emitDetached(this.#emitter, "finish", {
22964
23913
  recording: this.getRecording()
22965
23914
  });
@@ -23004,6 +23953,12 @@ var ExecutionRecorder = class _ExecutionRecorder {
23004
23953
  return (0, import_json_stream_es.stringifyJsonStream)(serializeToObject(this.getRecording()));
23005
23954
  }
23006
23955
  };
23956
+ function isRecordingTerminalEvent(event, data) {
23957
+ if (event === "done" || event === "error") {
23958
+ return true;
23959
+ }
23960
+ return event === "abort" && data.successful !== true;
23961
+ }
23007
23962
 
23008
23963
  // src/plugins/anthropic/nodes/ChatAnthropicNode.ts
23009
23964
  var import_non_secure85 = require("nanoid/non-secure");
@@ -25181,7 +26136,7 @@ var pinecone_default = pineconePlugin;
25181
26136
 
25182
26137
  // src/plugins/gentrace/plugin.ts
25183
26138
  var import_core = require("@gentrace/core");
25184
- var import_lodash_es19 = require("lodash");
26139
+ var import_lodash_es18 = require("lodash");
25185
26140
 
25186
26141
  // src/integrations/GptTokenizerTokenizer.ts
25187
26142
  var import_emittery3 = __toESM(require("emittery-0-13"), 1);
@@ -25279,7 +26234,7 @@ var runGentraceTests = async (gentracePipelineSlug, settings, project, graph, na
25279
26234
  slug: gentracePipelineSlug
25280
26235
  });
25281
26236
  const runner = pipeline.start();
25282
- const rivetFormattedInputs = (0, import_lodash_es19.mapValues)(testCase.inputs, inferType);
26237
+ const rivetFormattedInputs = (0, import_lodash_es18.mapValues)(testCase.inputs, inferType);
25283
26238
  const tempProject = {
25284
26239
  ...project,
25285
26240
  graphs: {
@@ -25291,7 +26246,7 @@ var runGentraceTests = async (gentracePipelineSlug, settings, project, graph, na
25291
26246
  const processor = new GraphProcessor(tempProject, graphId, globalRivetNodeRegistry);
25292
26247
  processor.executor = "browser";
25293
26248
  recorder.record(processor);
25294
- const runContextValues = (0, import_lodash_es19.cloneDeep)(contextValues);
26249
+ const runContextValues = (0, import_lodash_es18.cloneDeep)(contextValues);
25295
26250
  await processor.processGraph(
25296
26251
  {
25297
26252
  settings,
@@ -25329,7 +26284,7 @@ var runRemoteGentraceTests = async (gentracePipelineSlug, settings, project, gra
25329
26284
  slug: gentracePipelineSlug
25330
26285
  });
25331
26286
  const runner = pipeline.start();
25332
- const rivetFormattedInputs = (0, import_lodash_es19.mapValues)(testCase.inputs, inferType);
26287
+ const rivetFormattedInputs = (0, import_lodash_es18.mapValues)(testCase.inputs, inferType);
25333
26288
  const fullRecording = await runAndRecord(rivetFormattedInputs);
25334
26289
  const stepRuns = convertRecordingToStepRuns(fullRecording, project, graphId);
25335
26290
  for (const stepRun of stepRuns) {
@@ -28009,7 +28964,7 @@ ${additional.join("\n")}`;
28009
28964
  var runThreadNode = pluginNodeDefinition(RunThreadNodeImpl, "Run Thread");
28010
28965
 
28011
28966
  // src/plugins/openai/nodes/ThreadMessageNode.ts
28012
- var import_lodash_es20 = require("lodash");
28967
+ var import_lodash_es19 = require("lodash");
28013
28968
  var ThreadMessageNodeImpl = {
28014
28969
  create() {
28015
28970
  return {
@@ -28132,7 +29087,7 @@ var ThreadMessageNodeImpl = {
28132
29087
  if (data.useMetadataInput && inputData["metadata"]) {
28133
29088
  metadata = coerceTypeOptional(inputData["metadata"], "object");
28134
29089
  }
28135
- const inputMap = (0, import_lodash_es20.mapValues)(inputData, (input) => coerceType(input, "string"));
29090
+ const inputMap = (0, import_lodash_es19.mapValues)(inputData, (input) => coerceType(input, "string"));
28136
29091
  const interpolated = interpolate(text, inputMap);
28137
29092
  return {
28138
29093
  ["message"]: {
@@ -28185,7 +29140,7 @@ var import_ts_dedent85 = require("ts-dedent");
28185
29140
  var import_p_retry3 = __toESM(require("p-retry-4"), 1);
28186
29141
  var import_ts_pattern9 = require("ts-pattern");
28187
29142
  var import_genai2 = require("@google/genai");
28188
- var import_lodash_es21 = require("lodash");
29143
+ var import_lodash_es20 = require("lodash");
28189
29144
  function toGoogleSchemaType(type) {
28190
29145
  switch (type) {
28191
29146
  case "string":
@@ -28557,7 +29512,7 @@ var ChatGoogleNodeImpl = {
28557
29512
  description: tool.description,
28558
29513
  parameters: Object.keys(parameters.properties ?? {}).length === 0 ? void 0 : {
28559
29514
  type: import_genai2.Type.OBJECT,
28560
- properties: (0, import_lodash_es21.mapValues)(parameters.properties ?? {}, (property) => ({
29515
+ properties: (0, import_lodash_es20.mapValues)(parameters.properties ?? {}, (property) => ({
28561
29516
  // gemini doesn't support union property types, it uses openapi style not jsonschema, what a mess
28562
29517
  type: toGoogleSchemaType(
28563
29518
  Array.isArray(property.type) ? property.type.find((type) => type !== "null") : property.type
@@ -28840,7 +29795,7 @@ async function assembleRegistry(specs, loadPlugin) {
28840
29795
  }
28841
29796
 
28842
29797
  // src/integrations/DatasetProvider.ts
28843
- var import_lodash_es22 = require("lodash");
29798
+ var import_lodash_es21 = require("lodash");
28844
29799
  var InMemoryDatasetProvider = class {
28845
29800
  #datasets;
28846
29801
  constructor(datasets) {
@@ -28920,7 +29875,7 @@ var InMemoryDatasetProvider = class {
28920
29875
  return sorted.slice(0, k).map((r) => ({ ...r.row, distance: r.similarity }));
28921
29876
  }
28922
29877
  async exportDatasetsForProject(_projectId) {
28923
- return (0, import_lodash_es22.cloneDeep)(this.#datasets);
29878
+ return (0, import_lodash_es21.cloneDeep)(this.#datasets);
28924
29879
  }
28925
29880
  };
28926
29881
  var dotProductSimilarity = (a, b) => {
@@ -28973,7 +29928,8 @@ async function* getProcessorEvents(processor, spec) {
28973
29928
  type: "nodeFinish",
28974
29929
  outputs: event.outputs,
28975
29930
  nodeId: event.node.id,
28976
- nodeTitle: event.node.title
29931
+ nodeTitle: event.node.title,
29932
+ ...event.durationMs === void 0 ? {} : { durationMs: event.durationMs }
28977
29933
  };
28978
29934
  }
28979
29935
  }
@@ -29043,7 +29999,7 @@ function resolveProcessSettings(settings = {}, fallbacks = {}) {
29043
29999
  }
29044
30000
 
29045
30001
  // src/api/createProcessor.ts
29046
- function coreCreateProcessor(project, options2) {
30002
+ function coreCreateProcessor(project, options2, internalOptions = {}) {
29047
30003
  var _a, _b, _c;
29048
30004
  const { graph, inputs = {}, context = {} } = options2;
29049
30005
  const graphId = graph ? graph in project.graphs ? graph : (_b = (_a = Object.values(project.graphs).find((g) => {
@@ -29058,7 +30014,14 @@ function coreCreateProcessor(project, options2) {
29058
30014
  graphId,
29059
30015
  options2.registry ?? globalRivetNodeRegistry,
29060
30016
  options2.includeTrace,
29061
- { concurrency: options2.concurrency }
30017
+ {
30018
+ cacheLoadedProjects: internalOptions.cacheLoadedProjects,
30019
+ captureNodeTimings: options2.captureNodeTimings,
30020
+ concurrency: options2.concurrency,
30021
+ executionPlanCacheMode: internalOptions.executionPlanCacheMode,
30022
+ runtimeCache: internalOptions.runtimeCache,
30023
+ scheduler: internalOptions.scheduler
30024
+ }
29062
30025
  );
29063
30026
  if (options2.onStart) {
29064
30027
  processor.on("start", options2.onStart);
@@ -29326,12 +30289,16 @@ var Rivet = void 0;
29326
30289
  createChatV2Model,
29327
30290
  createChatV2ResponseOutput,
29328
30291
  createDatasetNode,
30292
+ createDebuggerTransportEscapedSentinel,
30293
+ createDebuggerTransportEscapedSentinelEnvelope,
30294
+ createDebuggerTransportUndefinedSentinel,
29329
30295
  createInterpolationInputDefinition,
29330
30296
  createsLLMChatV2ToolResponseFormatConflictForEdit,
29331
30297
  cronNode,
29332
30298
  dataTypeDisplayNames,
29333
30299
  dataTypes,
29334
30300
  datasetNearestNeighborsNode,
30301
+ decodeDebuggerTransportSentinels,
29335
30302
  dedent,
29336
30303
  delayNode,
29337
30304
  delegateFunctionCallNode,
@@ -29415,6 +30382,7 @@ var Rivet = void 0;
29415
30382
  isChatV2StructuredResponseFormat,
29416
30383
  isDataTypeAccepted,
29417
30384
  isDataTypeCompatible,
30385
+ isDebuggerTransportSentinelEnvelope,
29418
30386
  isFunctionDataType,
29419
30387
  isFunctionDataValue,
29420
30388
  isInterpolationInputDefinition,