@valerypopoff/rivet2-core 2.0.8 → 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 (51) hide show
  1. package/dist/cjs/bundle.cjs +1056 -462
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/esm/api/createProcessor.js +1 -0
  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 +88 -30
  10. package/dist/esm/model/GraphProcessor.js +295 -96
  11. package/dist/esm/model/NodeImpl.js +6 -4
  12. package/dist/esm/model/ProcessContextBuilder.js +2 -17
  13. package/dist/esm/model/RecordingPlayer.js +27 -7
  14. package/dist/esm/model/SplitRunProcessor.js +48 -9
  15. package/dist/esm/model/SubprocessorBridge.js +30 -23
  16. package/dist/esm/model/nodes/GetGlobalNode.js +14 -4
  17. package/dist/esm/model/nodes/GraphOutputNode.js +31 -2
  18. package/dist/esm/model/nodes/LoopUntilNode.js +18 -45
  19. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +24 -63
  20. package/dist/esm/model/nodes/SetGlobalNode.js +2 -1
  21. package/dist/esm/model/nodes/SubGraphNode.js +22 -63
  22. package/dist/esm/recording/ExecutionRecorder.js +19 -6
  23. package/dist/esm/utils/emitDetached.js +2 -2
  24. package/dist/esm/utils/interpolation.js +41 -1
  25. package/dist/esm/utils/serialization/serialization.js +6 -5
  26. package/dist/esm/utils/serialization/serializationHelpers.js +2 -2
  27. package/dist/esm/utils/serialization/serializationInput.js +48 -0
  28. package/dist/esm/utils/serialization/serializationUtils.js +2 -33
  29. package/dist/esm/utils/serialization/serialization_v2.js +8 -8
  30. package/dist/types/api/createProcessor.d.ts +1 -0
  31. package/dist/types/api/streaming.d.ts +1 -0
  32. package/dist/types/exports.d.ts +1 -0
  33. package/dist/types/model/DebuggerTransportSentinel.d.ts +21 -0
  34. package/dist/types/model/EditorDefinition.d.ts +2 -0
  35. package/dist/types/model/ExecutorProtocol.d.ts +5 -0
  36. package/dist/types/model/GraphAbortReasons.d.ts +23 -0
  37. package/dist/types/model/GraphBoundaryCache.d.ts +27 -0
  38. package/dist/types/model/GraphPreprocessor.d.ts +3 -1
  39. package/dist/types/model/GraphProcessor.d.ts +8 -0
  40. package/dist/types/model/NodeImpl.d.ts +10 -5
  41. package/dist/types/model/Nodes.d.ts +2 -2
  42. package/dist/types/model/ProcessContext.d.ts +3 -0
  43. package/dist/types/model/ProcessContextBuilder.d.ts +4 -20
  44. package/dist/types/model/SplitRunProcessor.d.ts +8 -3
  45. package/dist/types/model/nodes/LoopUntilNode.d.ts +5 -4
  46. package/dist/types/model/nodes/ReferencedGraphAliasNode.d.ts +5 -4
  47. package/dist/types/model/nodes/SubGraphNode.d.ts +6 -5
  48. package/dist/types/recording/RecordedEvents.d.ts +4 -0
  49. package/dist/types/utils/emitDetached.d.ts +2 -2
  50. package/dist/types/utils/serialization/serializationInput.d.ts +7 -0
  51. 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 { buildExecutionPlan, 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,6 +2333,7 @@ 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) => {
@@ -2334,6 +2372,7 @@ function toReusableGraphExecutionPlan(preprocessedGraph) {
2334
2372
  cycleIndexByNode: preprocessedGraph.cycleIndexByNode,
2335
2373
  definitions: preprocessedGraph.definitions,
2336
2374
  graphNodes: preprocessedGraph.graphNodes,
2375
+ nodeIds: preprocessedGraph.nodeIds,
2337
2376
  inputConnectionByNodeAndPort: preprocessedGraph.inputConnectionByNodeAndPort,
2338
2377
  inputConnectionsByNode: preprocessedGraph.inputConnectionsByNode,
2339
2378
  inputNodesByNode: preprocessedGraph.inputNodesByNode,
@@ -2347,62 +2386,140 @@ function toReusableGraphExecutionPlan(preprocessedGraph) {
2347
2386
  };
2348
2387
  }
2349
2388
  function loadInputOutputDefinitions(options2) {
2350
- const { connections, loadedProjects, nodeInstances, nodesById, project, warnOnInvalidGraph } = options2;
2389
+ const { connections, definitionContext, loadedProjects, nodeInstances, nodesById, project, warnOnInvalidGraph } = options2;
2351
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
+ }
2352
2447
  for (const node of values(nodesById)) {
2353
2448
  const connectionsForNode = connections[node.id] ?? [];
2354
- const inputDefinitions = nodeInstances[node.id].getInputDefinitionsIncludingBuiltIn(
2449
+ const nodeDefinitionContext = usesGraphBoundaryDefinitionContext(node) ? definitionContext : void 0;
2450
+ const inputDefinitions = nodeDefinitionContext ? nodeInstances[node.id].getInputDefinitionsIncludingBuiltIn(
2355
2451
  connectionsForNode,
2356
2452
  nodesById,
2357
2453
  project,
2358
- loadedProjects
2359
- );
2360
- const outputDefinitions = nodeInstances[node.id].getOutputDefinitions(
2454
+ loadedProjects,
2455
+ nodeDefinitionContext
2456
+ ) : nodeInstances[node.id].getInputDefinitionsIncludingBuiltIn(
2361
2457
  connectionsForNode,
2362
2458
  nodesById,
2363
2459
  project,
2364
2460
  loadedProjects
2365
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);
2366
2469
  definitions[node.id] = {
2367
2470
  inputs: inputDefinitions,
2368
2471
  outputs: outputDefinitions
2369
2472
  };
2370
- const invalidConnections = connectionsForNode.filter((connection) => {
2371
- if (connection.inputNodeId === node.id) {
2372
- const inputDefinition = inputDefinitions.find((definition) => definition.id === connection.inputId);
2373
- if (!inputDefinition) {
2374
- if (warnOnInvalidGraph) {
2375
- const sourceNode = nodesById[connection.outputNodeId];
2376
- console.warn(
2377
- `[Warn] Invalid connection going from "${sourceNode == null ? void 0 : sourceNode.title}".${connection.outputId} to "${node.title}".${connection.inputId}`
2378
- );
2379
- }
2380
- return true;
2381
- }
2382
- } else {
2383
- const outputDefinition = outputDefinitions.find((definition) => definition.id === connection.outputId);
2384
- if (!outputDefinition) {
2385
- if (warnOnInvalidGraph) {
2386
- const targetNode = nodesById[connection.inputNodeId];
2387
- console.warn(
2388
- `[Warn] Invalid connection going from "${node.title}".${connection.outputId} to "${targetNode == null ? void 0 : targetNode.title}".${connection.inputId}`
2389
- );
2390
- }
2391
- 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
+ );
2392
2495
  }
2496
+ return true;
2393
2497
  }
2394
- return false;
2395
- });
2396
- if (invalidConnections.length > 0) {
2397
- for (const invalidConnection of invalidConnections) {
2398
- removeConnectionFromNode(connections, invalidConnection, invalidConnection.inputNodeId);
2399
- if (invalidConnection.outputNodeId !== invalidConnection.inputNodeId) {
2400
- removeConnectionFromNode(connections, invalidConnection, invalidConnection.outputNodeId);
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
+ );
2401
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);
2402
2517
  }
2403
2518
  }
2404
2519
  }
2405
- return definitions;
2520
+ }
2521
+ function usesGraphBoundaryDefinitionContext(node) {
2522
+ return node.type === "subGraph" || node.type === "referencedGraphAlias" || node.type === "loopUntil";
2406
2523
  }
2407
2524
  function removeConnectionFromNode(connections, connection, nodeId) {
2408
2525
  const nodeConnections = connections[nodeId];
@@ -2489,6 +2606,7 @@ function buildGraphExecutionPlan(options2) {
2489
2606
  return {
2490
2607
  cycleIndexByNode,
2491
2608
  graphNodes,
2609
+ nodeIds: graphNodes.map((node) => node.id),
2492
2610
  inputConnectionByNodeAndPort,
2493
2611
  inputConnectionsByNode,
2494
2612
  inputNodesByNode,
@@ -2502,6 +2620,99 @@ function buildGraphExecutionPlan(options2) {
2502
2620
  };
2503
2621
  }
2504
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;
2714
+ }
2715
+
2505
2716
  // src/model/RecordingPlayer.ts
2506
2717
  var import_non_secure3 = require("nanoid/non-secure");
2507
2718
 
@@ -2511,6 +2722,13 @@ function emitDetached(emitter, event, data) {
2511
2722
  }
2512
2723
 
2513
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
+ }
2514
2732
  async function replayExecutionRecording(options2) {
2515
2733
  var _a, _b, _c, _d, _e, _f, _g, _h;
2516
2734
  const {
@@ -2562,6 +2780,7 @@ async function replayExecutionRecording(options2) {
2562
2780
  try {
2563
2781
  const legacyRootRunId = (0, import_non_secure3.nanoid)();
2564
2782
  const legacyGraphRunsByGraphId = /* @__PURE__ */ new Map();
2783
+ const nodeStartTimestamps = /* @__PURE__ */ new Map();
2565
2784
  const getExecution = (graphId, recordedExecution) => {
2566
2785
  if (recordedExecution) {
2567
2786
  return recordedExecution;
@@ -2577,6 +2796,14 @@ async function replayExecutionRecording(options2) {
2577
2796
  rootRunId: legacyRootRunId
2578
2797
  };
2579
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
+ };
2580
2807
  for (const event of recorder.events) {
2581
2808
  if (isAborted()) {
2582
2809
  break;
@@ -2668,11 +2895,13 @@ async function replayExecutionRecording(options2) {
2668
2895
  case "nodeStart": {
2669
2896
  const { data } = event;
2670
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);
2671
2900
  emitDetached(emitter, "nodeStart", {
2672
2901
  node,
2673
2902
  inputs: data.inputs,
2674
2903
  processId: data.processId,
2675
- execution: getExecution(((_b = data.execution) == null ? void 0 : _b.graphId) ?? getGraphIdForNode(data.nodeId), data.execution)
2904
+ execution
2676
2905
  });
2677
2906
  if (node.type === "chat") {
2678
2907
  await new Promise((resolve) => setTimeout(resolve, recordingPlaybackChatLatency));
@@ -2682,12 +2911,21 @@ async function replayExecutionRecording(options2) {
2682
2911
  case "nodeFinish": {
2683
2912
  const { data } = event;
2684
2913
  const node = getNode(data.nodeId);
2685
- emitDetached(emitter, "nodeFinish", {
2686
- node,
2687
- outputs: data.outputs,
2688
- processId: data.processId,
2689
- execution: getExecution(((_c = data.execution) == null ? void 0 : _c.graphId) ?? getGraphIdForNode(data.nodeId), data.execution)
2690
- });
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
+ );
2691
2929
  nodeResults.set(data.nodeId, data.outputs);
2692
2930
  visitedNodes.add(data.nodeId);
2693
2931
  break;
@@ -2695,12 +2933,21 @@ async function replayExecutionRecording(options2) {
2695
2933
  case "nodeError": {
2696
2934
  const { data } = event;
2697
2935
  const node = getNode(data.nodeId);
2698
- emitDetached(emitter, "nodeError", {
2699
- node,
2700
- error: data.error,
2701
- processId: data.processId,
2702
- execution: getExecution(((_d = data.execution) == null ? void 0 : _d.graphId) ?? getGraphIdForNode(data.nodeId), data.execution)
2703
- });
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
+ );
2704
2951
  erroredNodes.set(data.nodeId, data.error);
2705
2952
  visitedNodes.add(data.nodeId);
2706
2953
  break;
@@ -2802,69 +3049,113 @@ function didLoopControllerBreak(breakValue) {
2802
3049
  function buildNodeProcessContext(options2) {
2803
3050
  const {
2804
3051
  attachedData,
2805
- codeRunner,
2806
- context,
2807
- contextValues,
3052
+ base,
2808
3053
  createSubProcessor,
2809
3054
  execution,
2810
- executionCache,
2811
- executor,
2812
3055
  externalFunctions,
2813
- getGlobal,
2814
3056
  getPluginConfig: getPluginConfig2,
2815
- graphInputNodeValues,
2816
- graphInputs,
2817
- graphOutputs,
2818
- loadedProjects,
2819
3057
  node,
2820
3058
  nodeAbortController,
2821
3059
  onPartialOutputs,
2822
3060
  processId,
2823
- project,
2824
- raiseEvent,
2825
3061
  requestUserInput,
2826
3062
  setGlobal,
2827
- tokenizer,
2828
- trace,
2829
- waitEvent,
2830
- waitForGlobal,
2831
- abortGraph
3063
+ waitEvent
2832
3064
  } = options2;
2833
3065
  return {
2834
- ...context,
3066
+ ...base,
2835
3067
  node,
2836
- tokenizer,
2837
- executor,
2838
- project,
2839
- executionCache,
2840
- graphInputs,
2841
- graphOutputs,
2842
3068
  attachedData,
2843
- codeRunner,
2844
- referencedProjects: loadedProjects,
2845
3069
  waitEvent,
2846
- raiseEvent,
2847
- contextValues,
2848
3070
  externalFunctions: { ...externalFunctions },
2849
3071
  onPartialOutputs,
2850
3072
  signal: nodeAbortController.signal,
2851
3073
  processId,
2852
- getGlobal,
2853
3074
  setGlobal,
2854
- waitForGlobal,
2855
3075
  createSubProcessor,
2856
- trace,
2857
- abortGraph,
2858
3076
  getPluginConfig: getPluginConfig2,
2859
3077
  requestUserInput,
2860
- graphInputNodeValues,
2861
3078
  execution
2862
3079
  };
2863
3080
  }
2864
3081
 
2865
3082
  // src/model/SplitRunProcessor.ts
2866
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
+ }
2867
3157
  async function processSplitRunNode(node, processId, deps) {
3158
+ var _a, _b, _c;
2868
3159
  const inputValues = deps.getInputValues(node);
2869
3160
  if (deps.isExcludedDueToControlFlow(node, inputValues, processId)) {
2870
3161
  return;
@@ -2873,7 +3164,9 @@ async function processSplitRunNode(node, processId, deps) {
2873
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,
2874
3165
  node.splitRunMax ?? 10
2875
3166
  );
2876
- 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;
2877
3170
  try {
2878
3171
  let results;
2879
3172
  if (node.isSplitSequential) {
@@ -2881,35 +3174,52 @@ async function processSplitRunNode(node, processId, deps) {
2881
3174
  } else {
2882
3175
  results = await runParallel(node, inputValues, splittingAmount, processId, deps);
2883
3176
  }
3177
+ splitRunDurationMs = getSplitRunDurationMs(results);
2884
3178
  const errors = results.filter((r) => r.type === "error").map((r) => r.error);
2885
3179
  if (errors.length === 1) {
2886
3180
  throw errors[0];
2887
3181
  } else if (errors.length > 0) {
3182
+ if (deps.isAborted() && errors.every(isGraphAbortOrAbortLikeError)) {
3183
+ throw deps.getAbortError();
3184
+ }
2888
3185
  throw new AggregateError(errors);
2889
3186
  }
2890
3187
  const aggregateResults = aggregateOutputs(results);
2891
3188
  deps.setNodeResults(node.id, aggregateResults);
2892
3189
  deps.markNodeVisited(node.id);
2893
- 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
+ );
2894
3202
  } catch (error) {
2895
- deps.nodeErrored(node, error, processId);
3203
+ await deps.nodeErrored(node, error, processId, (_c = deps.finishNodeTiming) == null ? void 0 : _c.call(deps, timingStart), splitRunDurationMs);
2896
3204
  }
2897
3205
  }
2898
3206
  async function runSequential(node, inputValues, splittingAmount, processId, deps) {
3207
+ var _a, _b, _c;
2899
3208
  const results = [];
2900
3209
  for (let i = 0; i < splittingAmount; i++) {
2901
3210
  if (deps.isAborted()) {
2902
- throw new Error("Processing aborted");
3211
+ throw deps.getAbortError();
2903
3212
  }
2904
3213
  const inputs = splitInputsAtIndex(inputValues, i);
3214
+ const splitTimingStart = (_a = deps.startNodeTiming) == null ? void 0 : _a.call(deps);
2905
3215
  try {
2906
3216
  const output = await deps.processNodeWithInputData(node, inputs, i, processId, (n, partialOutputs, index) => {
2907
3217
  deps.emit("partialOutput", { node: n, outputs: partialOutputs, index, processId });
2908
3218
  });
2909
3219
  deps.accumulateCost(output);
2910
- results.push({ type: "output", output });
3220
+ results.push({ type: "output", output, durationMs: (_b = deps.finishNodeTiming) == null ? void 0 : _b.call(deps, splitTimingStart) });
2911
3221
  } catch (error) {
2912
- 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) });
2913
3223
  }
2914
3224
  }
2915
3225
  return results;
@@ -2919,15 +3229,24 @@ async function runParallel(node, inputValues, splittingAmount, processId, deps)
2919
3229
  return Promise.all(
2920
3230
  (0, import_lodash_es3.range)(0, splittingAmount).map(async (i) => {
2921
3231
  const result = await queue.add(async () => {
2922
- const inputs = splitInputsAtIndex(inputValues, i);
3232
+ var _a, _b, _c;
3233
+ const splitTimingStart = (_a = deps.startNodeTiming) == null ? void 0 : _a.call(deps);
2923
3234
  try {
3235
+ if (deps.isAborted()) {
3236
+ throw deps.getAbortError();
3237
+ }
3238
+ const inputs = splitInputsAtIndex(inputValues, i);
2924
3239
  const output = await deps.processNodeWithInputData(node, inputs, i, processId, (n, partialOutputs, index) => {
2925
3240
  deps.emit("partialOutput", { node: n, outputs: partialOutputs, index, processId });
2926
3241
  });
2927
3242
  deps.accumulateCost(output);
2928
- return { type: "output", output };
3243
+ return { type: "output", output, durationMs: (_b = deps.finishNodeTiming) == null ? void 0 : _b.call(deps, splitTimingStart) };
2929
3244
  } catch (error) {
2930
- 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
+ };
2931
3250
  }
2932
3251
  });
2933
3252
  if (!result) {
@@ -2958,6 +3277,18 @@ function aggregateOutputs(results) {
2958
3277
  return acc;
2959
3278
  }, {});
2960
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
+ }
2961
3292
 
2962
3293
  // src/model/NodeExecutionPlanner.ts
2963
3294
  function getStartNodes(state, graphNodes, runToNodeIds) {
@@ -3112,20 +3443,20 @@ function subscribeOwnGraphRunLifecycle(processor, onLifecycleEvent) {
3112
3443
  };
3113
3444
  }
3114
3445
  function wireSubprocessorEvents(processor, parentEmitter, parentState) {
3115
- const unsubscribers = [
3116
- processor.on("nodeError", (event) => parentEmitter.emit("nodeError", event)),
3117
- processor.on("nodeFinish", (event) => parentEmitter.emit("nodeFinish", event)),
3118
- processor.on("partialOutput", (event) => parentEmitter.emit("partialOutput", event)),
3119
- processor.on("nodeExcluded", (event) => parentEmitter.emit("nodeExcluded", event)),
3120
- processor.on("nodeStart", (event) => parentEmitter.emit("nodeStart", event)),
3121
- processor.on("graphAbort", (event) => parentEmitter.emit("graphAbort", event)),
3122
- processor.on("graphError", (event) => parentEmitter.emit("graphError", event)),
3123
- processor.on("userInput", (event) => parentEmitter.emit("userInput", event)),
3124
- processor.on("graphStart", (event) => parentEmitter.emit("graphStart", event)),
3125
- processor.on("graphFinish", (event) => parentEmitter.emit("graphFinish", event)),
3126
- processor.on("nodeOutputsCleared", (event) => parentEmitter.emit("nodeOutputsCleared", event)),
3127
- processor.on("globalSet", (event) => parentEmitter.emit("globalSet", event)),
3128
- 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 = [
3129
3460
  processor.on("pause", () => {
3130
3461
  if (!parentState.isPaused()) {
3131
3462
  parentState.pause();
@@ -3137,28 +3468,30 @@ function wireSubprocessorEvents(processor, parentEmitter, parentState) {
3137
3468
  }
3138
3469
  })
3139
3470
  ];
3140
- const unsubscribeAny = processor.onAny((event, data) => {
3471
+ processor.onAny((event, data) => {
3141
3472
  if (event.startsWith("globalSet:")) {
3142
3473
  void parentEmitter.emit(event, data);
3143
3474
  }
3144
3475
  });
3145
- let cleanedUp = false;
3146
- const cleanup = () => {
3147
- if (cleanedUp) {
3476
+ let controlsCleanedUp = false;
3477
+ const cleanupControls = () => {
3478
+ if (controlsCleanedUp) {
3148
3479
  return;
3149
3480
  }
3150
- cleanedUp = true;
3151
- unsubscribers.forEach((unsubscribe) => unsubscribe());
3481
+ controlsCleanedUp = true;
3482
+ controlUnsubscribers.forEach((unsubscribe) => unsubscribe());
3152
3483
  };
3153
- unsubscribers.push(unsubscribeAny, subscribeOwnGraphRunLifecycle(processor, cleanup));
3484
+ controlUnsubscribers.push(subscribeOwnGraphRunLifecycle(processor, cleanupControls));
3154
3485
  }
3155
3486
  function wireSubprocessorLifecycle(processor, options2) {
3156
3487
  var _a;
3157
3488
  const abortFromSignal = () => {
3158
- 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);
3159
3491
  };
3160
3492
  const abortFromParent = () => {
3161
- 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);
3162
3495
  };
3163
3496
  const pauseProcessor = () => {
3164
3497
  void processor.pause();
@@ -3307,6 +3640,7 @@ var NotAllowedCodeRunner = class {
3307
3640
  // src/model/GraphProcessor.ts
3308
3641
  var DEFAULT_NODE_CONCURRENCY = 8;
3309
3642
  var DEFAULT_SPLIT_RUN_CONCURRENCY = 4;
3643
+ var DEFAULT_ISOMORPHIC_CODE_RUNNER = new IsomorphicCodeRunner();
3310
3644
  var FAST_ACYCLIC_UNSUPPORTED_NODE_TYPES = /* @__PURE__ */ new Set([
3311
3645
  "loopController",
3312
3646
  "loopUntil",
@@ -3314,6 +3648,17 @@ var FAST_ACYCLIC_UNSUPPORTED_NODE_TYPES = /* @__PURE__ */ new Set([
3314
3648
  "userInput",
3315
3649
  "waitForEvent"
3316
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
+ }
3317
3662
  function normalizeConcurrencyValue(value, fallback) {
3318
3663
  return typeof value === "number" && Number.isFinite(value) && value >= 1 ? Math.floor(value) : fallback;
3319
3664
  }
@@ -3323,6 +3668,21 @@ function resolveGraphProcessorConcurrency(concurrency) {
3323
3668
  splitRunConcurrency: normalizeConcurrencyValue(concurrency == null ? void 0 : concurrency.splitRunConcurrency, DEFAULT_SPLIT_RUN_CONCURRENCY)
3324
3669
  };
3325
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
+ }
3326
3686
  var GraphProcessor = class _GraphProcessor {
3327
3687
  // Per-instance state
3328
3688
  #graph;
@@ -3343,6 +3703,8 @@ var GraphProcessor = class _GraphProcessor {
3343
3703
  #runtimeCache;
3344
3704
  #cacheLoadedProjects;
3345
3705
  #scheduler;
3706
+ #captureNodeTimings;
3707
+ #useSeededExecutionPlanOnNextRun = false;
3346
3708
  id = (0, import_non_secure4.nanoid)();
3347
3709
  #includeTrace = true;
3348
3710
  executor;
@@ -3380,6 +3742,7 @@ var GraphProcessor = class _GraphProcessor {
3380
3742
  #aborted = false;
3381
3743
  #abortSuccessfully = false;
3382
3744
  #abortError = void 0;
3745
+ #successfulAbortTerminalProcessIds = void 0;
3383
3746
  #totalCost = 0;
3384
3747
  #ignoreNodes = void 0;
3385
3748
  #hasPreloadedData = false;
@@ -3387,6 +3750,7 @@ var GraphProcessor = class _GraphProcessor {
3387
3750
  #definitions = void 0;
3388
3751
  #scc = void 0;
3389
3752
  #graphExecutionPlan;
3753
+ #nodeProcessContextBase = void 0;
3390
3754
  #nodesNotInCycle = void 0;
3391
3755
  #nodeAbortControllers = /* @__PURE__ */ new Map();
3392
3756
  #graphInputNodeValues = {};
@@ -3397,9 +3761,18 @@ var GraphProcessor = class _GraphProcessor {
3397
3761
  get isRunning() {
3398
3762
  return this.#running;
3399
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
+ }
3400
3773
  constructor(project, graphId, registry, includeTrace, options2) {
3401
3774
  this.#project = project;
3402
- const graph = graphId ? project.graphs[graphId] : project.metadata.mainGraphId ? project.graphs[project.metadata.mainGraphId] : void 0;
3775
+ const graph = resolveProcessorGraph(project, graphId);
3403
3776
  if (!graph) {
3404
3777
  throw new Error(`Graph ${graphId} not found in project`);
3405
3778
  }
@@ -3414,11 +3787,16 @@ var GraphProcessor = class _GraphProcessor {
3414
3787
  this.#runtimeCache = options2 == null ? void 0 : options2.runtimeCache;
3415
3788
  this.#cacheLoadedProjects = (options2 == null ? void 0 : options2.cacheLoadedProjects) ?? false;
3416
3789
  this.#scheduler = (options2 == null ? void 0 : options2.scheduler) ?? "compatible";
3790
+ this.#captureNodeTimings = (options2 == null ? void 0 : options2.captureNodeTimings) ?? false;
3417
3791
  this.#emitter.bindMethods(this, ["on", "off", "once", "onAny", "offAny"]);
3418
3792
  this.setExternalFunction("echo", async (value) => ({ type: "any", value }));
3419
3793
  this.#emitter.on("globalSet", ({ id, value }) => {
3420
3794
  emitDetached(this.#emitter, `globalSet:${id}`, value);
3421
3795
  });
3796
+ if (options2 == null ? void 0 : options2.initialExecutionPlan) {
3797
+ this.#applyPreprocessedGraph(options2.initialExecutionPlan, { recreateNodeInstances: true });
3798
+ this.#useSeededExecutionPlanOnNextRun = true;
3799
+ }
3422
3800
  }
3423
3801
  #preprocessGraph() {
3424
3802
  var _a;
@@ -3435,7 +3813,10 @@ var GraphProcessor = class _GraphProcessor {
3435
3813
  project: this.#project,
3436
3814
  registry: this.#registry,
3437
3815
  warnOnInvalidGraph: this.warnOnInvalidGraph,
3438
- buildExecutionPlan: shouldUseRuntimeCache
3816
+ buildExecutionPlan: shouldUseRuntimeCache,
3817
+ definitionContext: this.#runtimeCache ? {
3818
+ getGraphBoundary: (project, graphId) => this.#getGraphBoundary(project, graphId)
3819
+ } : void 0
3439
3820
  });
3440
3821
  if (shouldUseRuntimeCache && isGraphExecutionPlan(preprocessedGraph)) {
3441
3822
  runtimeCache.executionPlans ??= /* @__PURE__ */ new WeakMap();
@@ -3444,30 +3825,50 @@ var GraphProcessor = class _GraphProcessor {
3444
3825
  this.#applyPreprocessedGraph(preprocessedGraph);
3445
3826
  }
3446
3827
  #canUseRuntimeExecutionPlanCache() {
3828
+ return this.#canUseRuntimeExecutionPlanCacheFor(this.#project, this.#isSubProcessor);
3829
+ }
3830
+ #canUseRuntimeExecutionPlanCacheFor(project, isSubProcessor) {
3447
3831
  var _a;
3448
3832
  if (this.warnOnInvalidGraph || this.#runtimeCache == null) {
3449
3833
  return false;
3450
3834
  }
3451
- if (this.#executionPlanCacheMode === "subprocessors" && !this.#isSubProcessor) {
3835
+ if (this.#executionPlanCacheMode === "subprocessors" && !isSubProcessor) {
3452
3836
  return false;
3453
3837
  }
3454
- if (!this.#cacheLoadedProjects && (((_a = this.#project.references) == null ? void 0 : _a.length) ?? 0) > 0) {
3838
+ if (!this.#cacheLoadedProjects && (((_a = project.references) == null ? void 0 : _a.length) ?? 0) > 0) {
3455
3839
  return false;
3456
3840
  }
3457
3841
  return true;
3458
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
+ }
3459
3850
  #applyPreprocessedGraph(preprocessedGraph, options2 = {}) {
3460
3851
  const nodeInstances = options2.recreateNodeInstances || !("nodeInstances" in preprocessedGraph) ? this.#createNodeInstances(isGraphExecutionPlan(preprocessedGraph) ? preprocessedGraph.graphNodes : this.#graph.nodes) : preprocessedGraph.nodeInstances;
3461
- Object.assign(this.#nodeInstances, nodeInstances);
3462
- Object.assign(this.#nodesById, preprocessedGraph.nodesById);
3463
- Object.assign(this.#connections, preprocessedGraph.connections);
3852
+ replaceRecordContents(this.#nodeInstances, nodeInstances);
3853
+ replaceRecordContents(this.#nodesById, preprocessedGraph.nodesById);
3854
+ replaceRecordContents(this.#connections, preprocessedGraph.connections);
3464
3855
  this.#definitions = preprocessedGraph.definitions;
3465
3856
  this.#scc = preprocessedGraph.stronglyConnectedComponents;
3466
3857
  this.#nodesNotInCycle = preprocessedGraph.nodesNotInCycle;
3467
3858
  this.#graphExecutionPlan = isGraphExecutionPlan(preprocessedGraph) ? preprocessedGraph : void 0;
3468
3859
  }
3860
+ #seededExecutionPlanForNextRun() {
3861
+ if (!this.#useSeededExecutionPlanOnNextRun || this.warnOnInvalidGraph) {
3862
+ return void 0;
3863
+ }
3864
+ return this.#graphExecutionPlan;
3865
+ }
3469
3866
  #createNodeInstances(nodes) {
3470
- return Object.fromEntries(nodes.map((node) => [node.id, this.#registry.createDynamicImpl(node)]));
3867
+ const nodeInstances = {};
3868
+ for (const node of nodes) {
3869
+ nodeInstances[node.id] = this.#registry.createDynamicImpl(node);
3870
+ }
3871
+ return nodeInstances;
3471
3872
  }
3472
3873
  #emitTraceEvent(eventData) {
3473
3874
  if (this.#includeTrace) {
@@ -3534,7 +3935,9 @@ var GraphProcessor = class _GraphProcessor {
3534
3935
  }
3535
3936
  this.#abortSuccessfully = successful;
3536
3937
  this.#abortError = error;
3537
- this.#abortController.abort();
3938
+ const abortReason = createGraphAbortReason(successful, error);
3939
+ this.#abortController.abort(abortReason);
3940
+ this.#abortActiveNodeControllers(abortReason);
3538
3941
  emitDetached(this.#emitter, "graphAbort", this.#withExecution({ successful, error, graph: this.#graph }));
3539
3942
  if (!this.#isSubProcessor) {
3540
3943
  emitDetached(this.#emitter, "abort", { successful, error });
@@ -3669,7 +4072,7 @@ var GraphProcessor = class _GraphProcessor {
3669
4072
  return this.#graphOutputs;
3670
4073
  }
3671
4074
  #initProcessState() {
3672
- var _a;
4075
+ var _a, _b;
3673
4076
  this.#running = true;
3674
4077
  this.#finishEmitted = false;
3675
4078
  if (!this.#hasPreloadedData) {
@@ -3678,7 +4081,10 @@ var GraphProcessor = class _GraphProcessor {
3678
4081
  }
3679
4082
  this.#erroredNodes = /* @__PURE__ */ new Map();
3680
4083
  this.#currentlyProcessing = /* @__PURE__ */ new Set();
3681
- 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
+ );
3682
4088
  this.#pendingUserInputs = {};
3683
4089
  this.#processingQueue = new pQueueCompat_default({ concurrency: this.#concurrency.nodeConcurrency });
3684
4090
  this.#graphOutputs = {};
@@ -3689,6 +4095,7 @@ var GraphProcessor = class _GraphProcessor {
3689
4095
  this.#attachedNodeData = /* @__PURE__ */ new Map();
3690
4096
  this.#globals ??= /* @__PURE__ */ new Map();
3691
4097
  this.#ignoreNodes = /* @__PURE__ */ new Set();
4098
+ this.#nodeProcessContextBase = void 0;
3692
4099
  this.#abortController = this.#newAbortController();
3693
4100
  this.#abortController.signal.addEventListener("abort", () => {
3694
4101
  this.#aborted = true;
@@ -3696,8 +4103,14 @@ var GraphProcessor = class _GraphProcessor {
3696
4103
  this.#aborted = false;
3697
4104
  this.#abortError = void 0;
3698
4105
  this.#abortSuccessfully = false;
4106
+ this.#successfulAbortTerminalProcessIds = /* @__PURE__ */ new Set();
3699
4107
  this.#nodeAbortControllers = /* @__PURE__ */ new Map();
3700
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
+ }
3701
4114
  this.#graphInputNodeValues = {};
3702
4115
  }
3703
4116
  /** Main function for running a graph. Runs a graph and returns the outputs from the output nodes of the graph. */
@@ -3708,7 +4121,12 @@ var GraphProcessor = class _GraphProcessor {
3708
4121
  try {
3709
4122
  this.#initializeGraphRun(context, inputs, contextValues);
3710
4123
  await this.#loadProjectReferences();
3711
- this.#preprocessGraph();
4124
+ this.#prepareNodeProcessContextBase();
4125
+ const shouldUseSeededExecutionPlan = this.#seededExecutionPlanForNextRun() != null;
4126
+ this.#useSeededExecutionPlanOnNextRun = false;
4127
+ if (!shouldUseSeededExecutionPlan) {
4128
+ this.#preprocessGraph();
4129
+ }
3712
4130
  await this.#emitGraphStart();
3713
4131
  await this.#emitPreloadedNodeResults();
3714
4132
  await this.#waitUntilUnpaused();
@@ -3748,6 +4166,39 @@ var GraphProcessor = class _GraphProcessor {
3748
4166
  });
3749
4167
  this.#unsubscribeTokenizerError = typeof unsubscribeTokenizerError === "function" ? unsubscribeTokenizerError : void 0;
3750
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
+ }
3751
4202
  #cleanupTokenizerErrorListener() {
3752
4203
  const unsubscribeTokenizerError = this.#unsubscribeTokenizerError;
3753
4204
  this.#unsubscribeTokenizerError = void 0;
@@ -4079,7 +4530,8 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
4079
4530
  if (this.#beginNodeProcessing(node, attachedData) === false) {
4080
4531
  return [];
4081
4532
  }
4082
- const processId = await this.#processNode(node);
4533
+ const processResult = await this.#processNode(node);
4534
+ const { processId } = processResult;
4083
4535
  if (this.slowMode) {
4084
4536
  await new Promise((resolve) => setTimeout(resolve, 250));
4085
4537
  }
@@ -4090,14 +4542,16 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
4090
4542
  const outputNodes = getOutputNodesFrom(this.#executionState, node);
4091
4543
  this.#handleLoopControllerPostProcess(node, attachedData);
4092
4544
  this.#handleCompletedRace(node);
4093
- if (!this.#assignChildLoopInfo(node, builtInNode, attachedData, processId)) {
4545
+ const childLoopInfoError = this.#assignChildLoopInfo(node, builtInNode, attachedData);
4546
+ if (childLoopInfoError) {
4547
+ await this.#nodeErrored(node, childLoopInfoError, processId);
4094
4548
  return [];
4095
4549
  }
4096
4550
  this.#propagateAttachedDataToOutputNodes(node, attachedData, outputNodes.connectionsToNodes);
4097
- if (queueOutputNodes) {
4551
+ if (queueOutputNodes && processResult.shouldQueueOutputNodes) {
4098
4552
  this.#queueOutputNodes(node, outputNodes.nodes);
4099
4553
  }
4100
- return outputNodes.nodes;
4554
+ return processResult.shouldQueueOutputNodes ? outputNodes.nodes : [];
4101
4555
  }
4102
4556
  #shouldSkipNodeProcessing(node, inputNodes) {
4103
4557
  if (this.#ignoreNodes.has(node.id)) {
@@ -4183,32 +4637,31 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
4183
4637
  var _a;
4184
4638
  if (node.type !== "raceInputs") {
4185
4639
  return;
4186
- }
4187
- const allNodesForRace = [...this.#attachedNodeData.entries()].filter(
4188
- ([, { races }]) => races == null ? void 0 : races.raceIds.includes(`race-${node.id}`)
4189
- );
4190
- for (const [nodeId] of allNodesForRace) {
4191
- for (const [key, abortController] of this.#nodeAbortControllers.entries()) {
4192
- if (key.startsWith(nodeId)) {
4193
- this.#emitTraceEvent(`Aborting node ${nodeId} because other race branch won`);
4194
- abortController.abort();
4195
- }
4196
- }
4197
- for (const [, nodeAttachedData] of [...this.#attachedNodeData.entries()]) {
4198
- if ((_a = nodeAttachedData.races) == null ? void 0 : _a.raceIds.includes(`race-${node.id}`)) {
4199
- nodeAttachedData.races.completed = true;
4200
- }
4640
+ }
4641
+ const raceId = `race-${node.id}`;
4642
+ const allNodesForRace = [...this.#attachedNodeData.entries()].filter(
4643
+ ([, { races }]) => races == null ? void 0 : races.raceIds.includes(raceId)
4644
+ );
4645
+ for (const [, nodeAttachedData] of allNodesForRace) {
4646
+ if ((_a = nodeAttachedData.races) == null ? void 0 : _a.raceIds.includes(raceId)) {
4647
+ nodeAttachedData.races.completed = true;
4201
4648
  }
4202
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
+ }
4203
4657
  }
4204
- #assignChildLoopInfo(node, builtInNode, attachedData, processId) {
4658
+ #assignChildLoopInfo(node, builtInNode, attachedData) {
4205
4659
  if (builtInNode.type !== "loopController") {
4206
- return true;
4660
+ return void 0;
4207
4661
  }
4208
4662
  let childLoopInfo = attachedData.loopInfo;
4209
4663
  if (childLoopInfo != null && childLoopInfo.loopControllerId !== builtInNode.id) {
4210
- this.#nodeErrored(node, new Error("Nested loops are not supported"), processId);
4211
- return false;
4664
+ return new Error("Nested loops are not supported");
4212
4665
  }
4213
4666
  childLoopInfo = {
4214
4667
  propagate: (parent, connectionsFromParent) => {
@@ -4222,7 +4675,7 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
4222
4675
  iterationCount: ((childLoopInfo == null ? void 0 : childLoopInfo.iterationCount) ?? 0) + 1
4223
4676
  };
4224
4677
  attachedData.loopInfo = childLoopInfo;
4225
- return true;
4678
+ return void 0;
4226
4679
  }
4227
4680
  #propagateAttachedDataToOutputNodes(node, attachedData, outputConnections) {
4228
4681
  for (const { node: outputNode, connections: connectionsToOutputNode } of outputConnections) {
@@ -4261,24 +4714,17 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
4261
4714
  async #processNode(node) {
4262
4715
  const processId = (0, import_non_secure4.nanoid)();
4263
4716
  if (this.#abortController.signal.aborted) {
4264
- this.#nodeErrored(node, new Error("Processing aborted"), processId);
4265
- return processId;
4266
- }
4267
- const inputNodes = getInputNodesTo(this.#executionState, node);
4268
- const erroredInputNodes = inputNodes.filter((inputNode) => this.#erroredNodes.has(inputNode.id));
4269
- if (erroredInputNodes.length > 0) {
4270
- const error = new Error(
4271
- `Cannot process node ${node.title} (${node.id}) because it depends on errored nodes: ${erroredInputNodes.map((n) => `${n.title} (${n.id})`).join(", ")}`
4272
- );
4273
- this.#nodeErrored(node, error, processId);
4274
- return processId;
4717
+ await this.#nodeErrored(node, createGraphAbortErrorFromSignal(this.#abortController.signal), processId);
4718
+ this.#successfulAbortTerminalProcessIds.delete(processId);
4719
+ return { processId, shouldQueueOutputNodes: false };
4275
4720
  }
4276
4721
  if (node.isSplitRun) {
4277
4722
  await this.#processSplitRunNode(node, processId);
4278
4723
  } else {
4279
4724
  await this.#processNormalNode(node, processId);
4280
4725
  }
4281
- return processId;
4726
+ const successfulAbortTerminal = this.#successfulAbortTerminalProcessIds.delete(processId);
4727
+ return { processId, shouldQueueOutputNodes: !successfulAbortTerminal };
4282
4728
  }
4283
4729
  async #processSplitRunNode(node, processId) {
4284
4730
  return processSplitRunNode(node, processId, {
@@ -4289,11 +4735,18 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
4289
4735
  accumulateCost: (output) => this.#accumulateCost(output),
4290
4736
  setNodeResults: (nodeId, outputs) => this.#nodeResults.set(nodeId, outputs),
4291
4737
  markNodeVisited: (nodeId) => this.#visitedNodes.add(nodeId),
4292
- nodeErrored: (n, err, pid) => this.#nodeErrored(n, err, pid),
4738
+ nodeErrored: (n, err, pid, durationMs, splitRunDurationMs) => this.#nodeErrored(n, err, pid, durationMs, splitRunDurationMs),
4293
4739
  isAborted: () => this.#aborted,
4740
+ getAbortError: () => createGraphAbortErrorFromSignal(this.#abortController.signal),
4294
4741
  emit: (event, data) => {
4295
- emitDetached(this.#emitter, event, this.#withExecution(data));
4296
- }
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
4297
4750
  });
4298
4751
  }
4299
4752
  async #processNormalNode(node, processId) {
@@ -4302,6 +4755,7 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
4302
4755
  return;
4303
4756
  }
4304
4757
  await this.#emitter.emit("nodeStart", this.#withExecution({ node, inputs: inputValues, processId }));
4758
+ const timingStart = this.#startNodeTiming();
4305
4759
  try {
4306
4760
  const outputValues = await this.#processNodeWithInputData(
4307
4761
  node,
@@ -4319,16 +4773,59 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
4319
4773
  this.#nodeResults.set(node.id, outputValues);
4320
4774
  this.#visitedNodes.add(node.id);
4321
4775
  this.#accumulateCost(outputValues);
4322
- 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
+ );
4323
4789
  } catch (error) {
4324
- this.#nodeErrored(node, error, processId);
4790
+ await this.#nodeErrored(node, error, processId, this.#finishNodeTiming(timingStart));
4325
4791
  }
4326
4792
  }
4327
- #nodeErrored(node, e, processId) {
4793
+ async #nodeErrored(node, e, processId, durationMs, splitRunDurationMs) {
4328
4794
  const error = getError(e);
4329
- emitDetached(this.#emitter, "nodeError", this.#withExecution({ node, error, processId }));
4330
- 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
+ }
4331
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;
4332
4829
  }
4333
4830
  getRootProcessor() {
4334
4831
  let processor = this;
@@ -4349,14 +4846,71 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
4349
4846
  emitDetached(this.#emitter, "newAbortController", controller);
4350
4847
  return controller;
4351
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
+ }
4352
4907
  async #processNodeWithInputData(node, inputValues, index, processId, partialOutput) {
4353
4908
  const instance = this.#nodeInstances[node.id];
4354
4909
  const nodeAbortController = this.#newAbortController();
4355
- const abortListener = () => {
4356
- nodeAbortController.abort();
4357
- };
4358
- this.#nodeAbortControllers.set(`${node.id}-${processId}`, nodeAbortController);
4359
- 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
+ }
4360
4914
  const context = this.#createNodeProcessContext(
4361
4915
  node,
4362
4916
  inputValues,
@@ -4365,16 +4919,20 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
4365
4919
  nodeAbortController,
4366
4920
  partialOutput
4367
4921
  );
4368
- await this.#waitUntilUnpaused();
4369
4922
  let results;
4370
4923
  try {
4924
+ await this.#waitUntilUnpaused();
4371
4925
  results = await instance.process(inputValues, context);
4372
4926
  } finally {
4373
- this.#nodeAbortControllers.delete(`${node.id}-${processId}`);
4374
- this.#abortController.signal.removeEventListener("abort", abortListener);
4927
+ this.#unregisterNodeAbortController(node.id, nodeAbortController);
4375
4928
  }
4929
+ const abortReason = getGraphAbortReasonFromSignal(nodeAbortController.signal);
4376
4930
  if (nodeAbortController.signal.aborted) {
4377
- throw new Error("Aborted");
4931
+ if (isSuccessfulNonRaceGraphAbortReason(abortReason)) {
4932
+ this.#successfulAbortTerminalProcessIds.add(processId);
4933
+ } else {
4934
+ throw createGraphAbortError(abortReason, "Aborted");
4935
+ }
4378
4936
  }
4379
4937
  return results;
4380
4938
  }
@@ -4384,24 +4942,12 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
4384
4942
  #createNodeProcessContext(node, inputValues, index, processId, nodeAbortController, partialOutput) {
4385
4943
  const plugin = this.#registry.getPluginFor(node.type);
4386
4944
  return buildNodeProcessContext({
4387
- abortGraph: (error) => {
4388
- void this.abort(error === void 0, error);
4389
- },
4390
4945
  attachedData: this.#getAttachedDataTo(node),
4391
- codeRunner: this.#context.codeRunner ?? new IsomorphicCodeRunner(),
4392
- context: this.#context,
4393
- contextValues: this.#contextValues,
4946
+ base: this.#nodeProcessContextBase,
4394
4947
  createSubProcessor: (subGraphId, options2 = {}) => this.#createSubProcessor(node, index, processId, subGraphId, options2),
4395
4948
  execution: this.#buildExecutionMetadata(),
4396
- executionCache: this.#executionCache,
4397
- executor: this.executor ?? "nodejs",
4398
4949
  externalFunctions: this.#externalFunctions,
4399
- getGlobal: (id) => this.#globals.get(id),
4400
4950
  getPluginConfig: (name) => getPluginConfig(plugin, this.#context.settings, name),
4401
- graphInputNodeValues: this.#graphInputNodeValues,
4402
- graphInputs: this.#graphInputs,
4403
- graphOutputs: this.#graphOutputs,
4404
- loadedProjects: this.#loadedProjects,
4405
4951
  node,
4406
4952
  nodeAbortController,
4407
4953
  onPartialOutputs: (partialOutputs) => {
@@ -4409,36 +4955,21 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
4409
4955
  this.#emitGraphPartialOutputIfNeeded(node, partialOutputs);
4410
4956
  },
4411
4957
  processId,
4412
- project: this.#project,
4413
- raiseEvent: (event, data) => {
4414
- this.getRootProcessor().raiseEvent(event, data);
4415
- },
4416
4958
  requestUserInput: async (inputStrings, renderingType) => this.#requestUserInput(node, inputStrings, inputValues, renderingType, processId),
4417
4959
  setGlobal: (id, value) => {
4418
4960
  this.#globals.set(id, value);
4419
4961
  emitDetached(this.#emitter, "globalSet", this.#withExecution({ id, value, processId }));
4420
4962
  },
4421
- tokenizer: this.#getTokenizer(),
4422
- trace: (message) => {
4423
- this.#emitTraceEvent(message);
4424
- },
4425
4963
  waitEvent: async (event) => {
4426
4964
  return new Promise((resolve, reject) => {
4427
4965
  const abortListener = () => {
4428
- reject(new Error("Process aborted"));
4966
+ reject(createGraphAbortErrorFromSignal(nodeAbortController.signal, "Process aborted"));
4429
4967
  };
4430
4968
  this.#emitter.once(`userEvent:${event}`).then(resolve).catch(reject).finally(() => {
4431
4969
  nodeAbortController.signal.removeEventListener("abort", abortListener);
4432
4970
  });
4433
4971
  nodeAbortController.signal.addEventListener("abort", abortListener, { once: true });
4434
4972
  });
4435
- },
4436
- waitForGlobal: async (id) => {
4437
- if (this.#globals.has(id)) {
4438
- return this.#globals.get(id);
4439
- }
4440
- await this.getRootProcessor().#emitter.once(`globalSet:${id}`);
4441
- return this.#globals.get(id);
4442
4973
  }
4443
4974
  });
4444
4975
  }
@@ -4461,10 +4992,16 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
4461
4992
  });
4462
4993
  }
4463
4994
  #createSubProcessor(node, index, processId, subGraphId, { signal, project } = {}) {
4464
- const processor = new _GraphProcessor(project ?? this.#project, subGraphId, this.#registry, this.#includeTrace, {
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, {
4465
5000
  cacheLoadedProjects: this.#cacheLoadedProjects,
5001
+ captureNodeTimings: this.#captureNodeTimings,
4466
5002
  concurrency: this.#concurrency,
4467
5003
  executionPlanCacheMode: this.#executionPlanCacheMode,
5004
+ initialExecutionPlan,
4468
5005
  runtimeCache: this.#runtimeCache,
4469
5006
  scheduler: this.#scheduler
4470
5007
  });
@@ -4513,7 +5050,7 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
4513
5050
  return await new Promise((resolve, reject) => {
4514
5051
  const abortListener = () => {
4515
5052
  delete this.#pendingUserInputs[node.id];
4516
- reject(new Error("Processing aborted"));
5053
+ reject(createGraphAbortErrorFromSignal(this.#abortController.signal));
4517
5054
  };
4518
5055
  this.#pendingUserInputs[node.id] = {
4519
5056
  resolve,
@@ -4565,19 +5102,21 @@ ${erroredNodes.map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})
4565
5102
  return outputNodes.nodes;
4566
5103
  }
4567
5104
  #markAsExcluded(node, processId, inputValues, reason) {
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) {
4568
5111
  const outputs = createExcludedNodeOutputs(node, this.#definitions[node.id].outputs);
4569
5112
  this.#nodeResults.set(node.id, outputs);
4570
- emitDetached(
4571
- this.#emitter,
4572
- "nodeExcluded",
4573
- this.#withExecution({
4574
- node,
4575
- processId,
4576
- inputs: inputValues,
4577
- outputs,
4578
- reason
4579
- })
4580
- );
5113
+ return this.#withExecution({
5114
+ node,
5115
+ processId,
5116
+ inputs: inputValues,
5117
+ outputs,
5118
+ reason
5119
+ });
4581
5120
  }
4582
5121
  #getInputValuesForNode(node) {
4583
5122
  const connections = this.#connections[node.id];
@@ -4631,8 +5170,8 @@ var NodeImpl = class {
4631
5170
  get data() {
4632
5171
  return this.chartNode.data;
4633
5172
  }
4634
- getInputDefinitionsIncludingBuiltIn(connections, nodes, project, referencedProjects) {
4635
- 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)];
4636
5175
  if (this.chartNode.isConditional) {
4637
5176
  ports.push(IF_PORT);
4638
5177
  }
@@ -4651,10 +5190,10 @@ var PluginNodeImplClass = class extends NodeImpl {
4651
5190
  super(chartNode);
4652
5191
  this.impl = impl;
4653
5192
  }
4654
- getInputDefinitions(connections, nodes, project) {
5193
+ getInputDefinitions(connections, nodes, project, _referencedProjects, _definitionContext) {
4655
5194
  return this.impl.getInputDefinitions(this.data, connections, nodes, project);
4656
5195
  }
4657
- getOutputDefinitions(connections, nodes, project) {
5196
+ getOutputDefinitions(connections, nodes, project, _referencedProjects, _definitionContext) {
4658
5197
  return this.impl.getOutputDefinitions(this.data, connections, nodes, project);
4659
5198
  }
4660
5199
  process(inputData, context) {
@@ -4940,6 +5479,12 @@ var import_ts_dedent3 = require("ts-dedent");
4940
5479
  var import_lodash_es5 = require("lodash");
4941
5480
  var ESCAPED_TOKEN_REGEX = /\{\{\{([^}]+?)\}\}\}/g;
4942
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;
4943
5488
  var processingFunctions = {
4944
5489
  indent: (input, spaces = 0) => {
4945
5490
  const indent = " ".repeat(spaces);
@@ -5166,6 +5711,13 @@ function interpolate(template, variables, graphInputValues, contextValues) {
5166
5711
  });
5167
5712
  }
5168
5713
  function extractInterpolationVariables(template) {
5714
+ if (!template.includes("{{")) {
5715
+ return [];
5716
+ }
5717
+ const cachedVariables = getCachedInterpolationVariables(template);
5718
+ if (cachedVariables) {
5719
+ return [...cachedVariables];
5720
+ }
5169
5721
  const protectedTemplate = protectEscapedInterpolationTokens(template);
5170
5722
  const variables = /* @__PURE__ */ new Set();
5171
5723
  for (const match10 of findInterpolationTokenSpans(protectedTemplate)) {
@@ -5174,7 +5726,32 @@ function extractInterpolationVariables(template) {
5174
5726
  variables.add(token);
5175
5727
  }
5176
5728
  }
5177
- 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;
5178
5755
  }
5179
5756
 
5180
5757
  // src/model/interpolationInputDefinition.ts
@@ -13345,6 +13922,34 @@ var graphInputNode = nodeDefinition(GraphInputNodeImpl, "Graph Input");
13345
13922
  // src/model/nodes/GraphOutputNode.ts
13346
13923
  var import_non_secure21 = require("nanoid/non-secure");
13347
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
+ }
13348
13953
  var GraphOutputNodeImpl = class extends NodeImpl {
13349
13954
  static create() {
13350
13955
  const chartNode = {
@@ -13413,14 +14018,15 @@ var GraphOutputNodeImpl = class extends NodeImpl {
13413
14018
  }
13414
14019
  async process(inputs, context) {
13415
14020
  var _a;
13416
- 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);
13417
14023
  const isExcluded = value.type === "control-flow-excluded";
13418
14024
  if (isExcluded && context.graphOutputs[this.data.id] == null) {
13419
14025
  context.graphOutputs[this.data.id] = {
13420
14026
  type: "control-flow-excluded",
13421
14027
  value: void 0
13422
14028
  };
13423
- } 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) {
13424
14030
  context.graphOutputs[this.data.id] = value;
13425
14031
  }
13426
14032
  if (isExcluded) {
@@ -13460,40 +14066,17 @@ var SubGraphNodeImpl = class extends NodeImpl {
13460
14066
  };
13461
14067
  return chartNode;
13462
14068
  }
13463
- getInputDefinitions(_connections, _nodes, project) {
13464
- const graph = project.graphs[this.data.graphId];
13465
- if (!graph) {
13466
- return [];
13467
- }
13468
- const inputNodes = graph.nodes.filter((node) => node.type === "graphInput");
13469
- const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();
13470
- return inputIds.map(
13471
- (id) => ({
13472
- id,
13473
- title: id,
13474
- dataType: inputNodes.find((node) => node.data.id === id).data.dataType
13475
- })
13476
- );
14069
+ getInputDefinitions(_connections, _nodes, project, _referencedProjects, definitionContext) {
14070
+ const boundary = this.getBoundary(project, definitionContext);
14071
+ return boundary ? getGraphBoundaryInputDefinitions(boundary) : [];
13477
14072
  }
13478
- getGraphOutputs(project) {
13479
- const graph = project.graphs[this.data.graphId];
13480
- if (!graph) {
13481
- return [];
13482
- }
13483
- const outputNodes = graph.nodes.filter((node) => node.type === "graphOutput");
13484
- const outputIds = [...new Set(outputNodes.map((node) => node.data.id))].sort();
13485
- const outputs = outputIds.map(
13486
- (id) => ({
13487
- id,
13488
- title: id,
13489
- dataType: outputNodes.find((node) => node.data.id === id).data.dataType
13490
- })
13491
- );
13492
- return outputs;
14073
+ getGraphOutputs(project, definitionContext) {
14074
+ const boundary = this.getBoundary(project, definitionContext);
14075
+ return boundary ? getGraphBoundaryOutputDefinitions(boundary) : [];
13493
14076
  }
13494
- getOutputDefinitions(_connections, _nodes, project) {
14077
+ getOutputDefinitions(_connections, _nodes, project, _referencedProjects, definitionContext) {
13495
14078
  const outputs = [];
13496
- outputs.push(...this.getGraphOutputs(project));
14079
+ outputs.push(...this.getGraphOutputs(project, definitionContext));
13497
14080
  if (this.data.useErrorOutput) {
13498
14081
  outputs.push({
13499
14082
  id: "error",
@@ -13503,6 +14086,9 @@ var SubGraphNodeImpl = class extends NodeImpl {
13503
14086
  }
13504
14087
  return outputs;
13505
14088
  }
14089
+ getBoundary(project, definitionContext) {
14090
+ return (definitionContext == null ? void 0 : definitionContext.getGraphBoundary(project, this.data.graphId)) ?? getGraphBoundary(project, this.data.graphId);
14091
+ }
13506
14092
  getEditors(context) {
13507
14093
  const definitions = [
13508
14094
  {
@@ -13517,19 +14103,16 @@ var SubGraphNodeImpl = class extends NodeImpl {
13517
14103
  }
13518
14104
  ];
13519
14105
  if (this.data.graphId) {
13520
- const graph = context.project.graphs[this.data.graphId];
13521
- if (graph) {
13522
- const inputNodes = graph.nodes.filter((node) => node.type === "graphInput");
13523
- const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();
13524
- for (const inputId of inputIds) {
13525
- 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) {
13526
14109
  definitions.push({
13527
14110
  type: "dynamic",
13528
14111
  dataKey: "inputData",
13529
- dynamicDataKey: inputNode.data.id,
13530
- dataType: inputNode.data.dataType,
13531
- label: inputNode.data.id,
13532
- editor: inputNode.data.editor ?? "auto"
14112
+ dynamicDataKey: input.id,
14113
+ dataType: input.dataType,
14114
+ label: input.id,
14115
+ editor: input.editor ?? "auto"
13533
14116
  });
13534
14117
  }
13535
14118
  }
@@ -13547,6 +14130,7 @@ var SubGraphNodeImpl = class extends NodeImpl {
13547
14130
  };
13548
14131
  }
13549
14132
  async process(inputs, context) {
14133
+ var _a;
13550
14134
  const { project } = context;
13551
14135
  if (!project) {
13552
14136
  throw new Error("SubGraphNode requires a project to be set in the context.");
@@ -13555,24 +14139,8 @@ var SubGraphNodeImpl = class extends NodeImpl {
13555
14139
  if (!graph) {
13556
14140
  throw new Error(`SubGraphNode requires a graph with id ${this.data.graphId} to be present in the project.`);
13557
14141
  }
13558
- const inputNodes = graph.nodes.filter((node) => node.type === "graphInput");
13559
- const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();
13560
- const inputData = inputIds.reduce((obj, id) => {
13561
- var _a;
13562
- if (inputs[id] != null) {
13563
- return {
13564
- ...obj,
13565
- [id]: inputs[id]
13566
- };
13567
- }
13568
- if (((_a = this.data.inputData) == null ? void 0 : _a[id]) != null) {
13569
- return {
13570
- ...obj,
13571
- [id]: this.data.inputData[id]
13572
- };
13573
- }
13574
- return obj;
13575
- }, {});
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);
13576
14144
  const subGraphProcessor = context.createSubProcessor(this.data.graphId, { signal: context.signal });
13577
14145
  try {
13578
14146
  const startTime = Date.now();
@@ -13599,16 +14167,7 @@ var SubGraphNodeImpl = class extends NodeImpl {
13599
14167
  if (!this.data.useErrorOutput) {
13600
14168
  throw err;
13601
14169
  }
13602
- const outputs = this.getGraphOutputs(context.project).reduce(
13603
- (obj, output) => ({
13604
- ...obj,
13605
- [output.id]: {
13606
- type: "control-flow-excluded",
13607
- value: void 0
13608
- }
13609
- }),
13610
- {}
13611
- );
14170
+ const outputs = buildExcludedGraphBoundaryOutputs(boundary);
13612
14171
  outputs["error"] = {
13613
14172
  type: "string",
13614
14173
  value: getError(err).message
@@ -15489,7 +16048,8 @@ var SetGlobalNodeImpl = class extends NodeImpl {
15489
16048
  type: "string",
15490
16049
  dataKey: "id",
15491
16050
  useInputToggleDataKey: "useIdInput",
15492
- label: "ID"
16051
+ label: "ID",
16052
+ includeInGraphSearch: true
15493
16053
  },
15494
16054
  {
15495
16055
  type: "dataTypeSelector",
@@ -15524,7 +16084,7 @@ var SetGlobalNodeImpl = class extends NodeImpl {
15524
16084
  if (!id) {
15525
16085
  throw new Error("Missing variable ID");
15526
16086
  }
15527
- let previousValue = context.getGlobal(this.data.id);
16087
+ let previousValue = context.getGlobal(id);
15528
16088
  if (!previousValue && isArrayDataType(this.data.dataType)) {
15529
16089
  previousValue = { type: this.data.dataType, value: [] };
15530
16090
  } else if (!previousValue && isScalarDataType(this.data.dataType)) {
@@ -15558,9 +16118,9 @@ var GetGlobalNodeImpl = class extends NodeImpl {
15558
16118
  data: {
15559
16119
  id: "variable-name",
15560
16120
  dataType: "string",
15561
- onDemand: true,
16121
+ onDemand: false,
15562
16122
  useIdInput: false,
15563
- wait: false
16123
+ wait: true
15564
16124
  }
15565
16125
  };
15566
16126
  return chartNode;
@@ -15571,7 +16131,7 @@ var GetGlobalNodeImpl = class extends NodeImpl {
15571
16131
  {
15572
16132
  id: "id",
15573
16133
  title: "Variable ID",
15574
- dataType: this.data.dataType
16134
+ dataType: "string"
15575
16135
  }
15576
16136
  ];
15577
16137
  }
@@ -15594,11 +16154,18 @@ var GetGlobalNodeImpl = class extends NodeImpl {
15594
16154
  }
15595
16155
  getEditors() {
15596
16156
  return [
16157
+ {
16158
+ type: "custom",
16159
+ label: "Search Global Variables",
16160
+ customEditorId: "GetGlobalVariableSelector",
16161
+ autoFocus: true
16162
+ },
15597
16163
  {
15598
16164
  type: "string",
15599
16165
  label: "Variable ID",
15600
16166
  dataKey: "id",
15601
- useInputToggleDataKey: "useIdInput"
16167
+ useInputToggleDataKey: "useIdInput",
16168
+ includeInGraphSearch: true
15602
16169
  },
15603
16170
  {
15604
16171
  type: "dataTypeSelector",
@@ -15608,12 +16175,14 @@ var GetGlobalNodeImpl = class extends NodeImpl {
15608
16175
  {
15609
16176
  type: "toggle",
15610
16177
  label: "On Demand",
15611
- dataKey: "onDemand"
16178
+ dataKey: "onDemand",
16179
+ turnOffDataKeysWhenEnabled: ["wait"]
15612
16180
  },
15613
16181
  {
15614
16182
  type: "toggle",
15615
16183
  label: "Wait",
15616
- dataKey: "wait"
16184
+ dataKey: "wait",
16185
+ turnOffDataKeysWhenEnabled: ["onDemand"]
15617
16186
  }
15618
16187
  ];
15619
16188
  }
@@ -15639,11 +16208,11 @@ var GetGlobalNodeImpl = class extends NodeImpl {
15639
16208
  if (this.data.wait) {
15640
16209
  throw new Error("Cannot use onDemand and wait together");
15641
16210
  }
16211
+ const id2 = this.data.useIdInput ? coerceType(inputs["id"], "string") : this.data.id;
15642
16212
  return {
15643
16213
  ["value"]: {
15644
16214
  type: `fn<${this.data.dataType}>`,
15645
16215
  value: () => {
15646
- const id2 = this.data.useIdInput ? coerceType(inputs["id"], "string") : this.data.id;
15647
16216
  const value2 = context.getGlobal(id2);
15648
16217
  if (value2) {
15649
16218
  return value2.value;
@@ -15653,7 +16222,8 @@ var GetGlobalNodeImpl = class extends NodeImpl {
15653
16222
  }
15654
16223
  return scalarDefaults[this.data.dataType];
15655
16224
  }
15656
- }
16225
+ },
16226
+ ["variable_id_out"]: { type: "string", value: id2 }
15657
16227
  };
15658
16228
  }
15659
16229
  const id = this.data.useIdInput ? coerceType(inputs["id"], "string") : this.data.id;
@@ -21801,38 +22371,13 @@ var LoopUntilNodeImpl = class extends NodeImpl {
21801
22371
  };
21802
22372
  return chartNode;
21803
22373
  }
21804
- getInputDefinitions(_connections, _nodes, project) {
21805
- const inputs = [];
21806
- const graph = project.graphs[this.data.targetGraph ?? ""];
21807
- if (graph) {
21808
- const inputNodes = graph.nodes.filter((node) => node.type === "graphInput");
21809
- const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();
21810
- inputIds.forEach((id) => {
21811
- const inputNode = inputNodes.find((node) => node.data.id === id);
21812
- inputs.push({
21813
- id,
21814
- title: id,
21815
- dataType: inputNode.data.dataType
21816
- });
21817
- });
21818
- }
21819
- return inputs;
22374
+ getInputDefinitions(_connections, _nodes, project, _referencedProjects, definitionContext) {
22375
+ const boundary = this.getBoundary(project, definitionContext);
22376
+ return boundary ? getGraphBoundaryInputDefinitions(boundary) : [];
21820
22377
  }
21821
- getOutputDefinitions(_connections, _nodes, project) {
21822
- const outputs = [];
21823
- const graph = project.graphs[this.data.targetGraph ?? ""];
21824
- if (graph) {
21825
- const outputNodes = graph.nodes.filter((node) => node.type === "graphOutput");
21826
- const outputIds = [...new Set(outputNodes.map((node) => node.data.id))].sort();
21827
- outputIds.forEach((id) => {
21828
- const outputNode = outputNodes.find((node) => node.data.id === id);
21829
- outputs.push({
21830
- id,
21831
- title: id,
21832
- dataType: outputNode.data.dataType
21833
- });
21834
- });
21835
- }
22378
+ getOutputDefinitions(_connections, _nodes, project, _referencedProjects, definitionContext) {
22379
+ const boundary = this.getBoundary(project, definitionContext);
22380
+ const outputs = boundary ? getGraphBoundaryOutputDefinitions(boundary) : [];
21836
22381
  outputs.push(
21837
22382
  {
21838
22383
  id: "iteration",
@@ -21891,19 +22436,16 @@ var LoopUntilNodeImpl = class extends NodeImpl {
21891
22436
  );
21892
22437
  }
21893
22438
  if (this.data.targetGraph) {
21894
- const graph = context.project.graphs[this.data.targetGraph];
21895
- if (graph) {
21896
- const inputNodes = graph.nodes.filter((node) => node.type === "graphInput");
21897
- const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();
21898
- for (const inputId of inputIds) {
21899
- 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) {
21900
22442
  definitions.push({
21901
22443
  type: "dynamic",
21902
22444
  dataKey: "inputData",
21903
- dynamicDataKey: inputNode.data.id,
21904
- dataType: inputNode.data.dataType,
21905
- label: inputNode.data.id,
21906
- editor: inputNode.data.editor ?? "auto"
22445
+ dynamicDataKey: input.id,
22446
+ dataType: input.dataType,
22447
+ label: input.id,
22448
+ editor: input.editor ?? "auto"
21907
22449
  });
21908
22450
  }
21909
22451
  }
@@ -21934,6 +22476,9 @@ Max iterations: ${this.data.maxIterations}` : "";
21934
22476
  return `Executes ${graphName}
21935
22477
  until ${condition}${maxIterations}`;
21936
22478
  }
22479
+ getBoundary(project, definitionContext) {
22480
+ return (definitionContext == null ? void 0 : definitionContext.getGraphBoundary(project, this.data.targetGraph)) ?? getGraphBoundary(project, this.data.targetGraph);
22481
+ }
21937
22482
  shouldBreak(outputs) {
21938
22483
  var _a;
21939
22484
  if (this.data.conditionType === "allOutputsSet") {
@@ -22765,48 +23310,25 @@ var ReferencedGraphAliasNodeImpl = class extends NodeImpl {
22765
23310
  };
22766
23311
  return chartNode;
22767
23312
  }
22768
- getInputDefinitions(_connections, _nodes, _project, referencedProjects) {
23313
+ getInputDefinitions(_connections, _nodes, _project, referencedProjects, definitionContext) {
22769
23314
  const referencedProject = referencedProjects[this.data.projectId];
22770
23315
  if (!referencedProject) {
22771
23316
  return [];
22772
23317
  }
22773
- const graph = referencedProject.graphs[this.data.graphId];
22774
- if (!graph) {
22775
- return [];
22776
- }
22777
- const inputNodes = graph.nodes.filter((node) => node.type === "graphInput");
22778
- const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();
22779
- return inputIds.map(
22780
- (id) => ({
22781
- id,
22782
- title: id,
22783
- dataType: inputNodes.find((node) => node.data.id === id).data.dataType
22784
- })
22785
- );
23318
+ const boundary = this.getBoundary(referencedProject, definitionContext);
23319
+ return boundary ? getGraphBoundaryInputDefinitions(boundary) : [];
22786
23320
  }
22787
- getGraphOutputs(referencedProject) {
22788
- const graph = referencedProject.graphs[this.data.graphId];
22789
- if (!graph) {
22790
- return [];
22791
- }
22792
- const outputNodes = graph.nodes.filter((node) => node.type === "graphOutput");
22793
- const outputIds = [...new Set(outputNodes.map((node) => node.data.id))].sort();
22794
- const outputs = outputIds.map(
22795
- (id) => ({
22796
- id,
22797
- title: id,
22798
- dataType: outputNodes.find((node) => node.data.id === id).data.dataType
22799
- })
22800
- );
22801
- return outputs;
23321
+ getGraphOutputs(referencedProject, definitionContext) {
23322
+ const boundary = this.getBoundary(referencedProject, definitionContext);
23323
+ return boundary ? getGraphBoundaryOutputDefinitions(boundary) : [];
22802
23324
  }
22803
- getOutputDefinitions(_connections, _nodes, _project, referencedProjects) {
23325
+ getOutputDefinitions(_connections, _nodes, _project, referencedProjects, definitionContext) {
22804
23326
  const outputs = [];
22805
23327
  const referencedProject = referencedProjects[this.data.projectId];
22806
23328
  if (!referencedProject) {
22807
23329
  return outputs;
22808
23330
  }
22809
- outputs.push(...this.getGraphOutputs(referencedProject));
23331
+ outputs.push(...this.getGraphOutputs(referencedProject, definitionContext));
22810
23332
  if (this.data.useErrorOutput) {
22811
23333
  outputs.push({
22812
23334
  id: "error",
@@ -22816,6 +23338,9 @@ var ReferencedGraphAliasNodeImpl = class extends NodeImpl {
22816
23338
  }
22817
23339
  return outputs;
22818
23340
  }
23341
+ getBoundary(referencedProject, definitionContext) {
23342
+ return (definitionContext == null ? void 0 : definitionContext.getGraphBoundary(referencedProject, this.data.graphId)) ?? getGraphBoundary(referencedProject, this.data.graphId);
23343
+ }
22819
23344
  getEditors(context) {
22820
23345
  const definitions = [
22821
23346
  {
@@ -22831,19 +23356,16 @@ var ReferencedGraphAliasNodeImpl = class extends NodeImpl {
22831
23356
  ];
22832
23357
  const referencedProject = context.referencedProjects[this.data.projectId];
22833
23358
  if (referencedProject) {
22834
- const graph = referencedProject.graphs[this.data.graphId];
22835
- if (graph) {
22836
- const inputNodes = graph.nodes.filter((node) => node.type === "graphInput");
22837
- const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();
22838
- for (const inputId of inputIds) {
22839
- 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) {
22840
23362
  definitions.push({
22841
23363
  type: "dynamic",
22842
23364
  dataKey: "inputData",
22843
- dynamicDataKey: inputNode.data.id,
22844
- dataType: inputNode.data.dataType,
22845
- label: inputNode.data.id,
22846
- editor: inputNode.data.editor ?? "auto"
23365
+ dynamicDataKey: input.id,
23366
+ dataType: input.dataType,
23367
+ label: input.id,
23368
+ editor: input.editor ?? "auto"
22847
23369
  });
22848
23370
  }
22849
23371
  }
@@ -22865,6 +23387,7 @@ var ReferencedGraphAliasNodeImpl = class extends NodeImpl {
22865
23387
  };
22866
23388
  }
22867
23389
  async process(inputs, context) {
23390
+ var _a;
22868
23391
  const referencedProject = context.referencedProjects[this.data.projectId];
22869
23392
  if (!referencedProject) {
22870
23393
  throw new Error(
@@ -22877,24 +23400,8 @@ var ReferencedGraphAliasNodeImpl = class extends NodeImpl {
22877
23400
  `ReferencedGraphAliasNode requires a graph with id ${this.data.graphId} to be present in the referenced project.`
22878
23401
  );
22879
23402
  }
22880
- const inputNodes = graph.nodes.filter((node) => node.type === "graphInput");
22881
- const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();
22882
- const inputData = inputIds.reduce((obj, id) => {
22883
- var _a;
22884
- if (inputs[id] != null) {
22885
- return {
22886
- ...obj,
22887
- [id]: inputs[id]
22888
- };
22889
- }
22890
- if (((_a = this.data.inputData) == null ? void 0 : _a[id]) != null) {
22891
- return {
22892
- ...obj,
22893
- [id]: this.data.inputData[id]
22894
- };
22895
- }
22896
- return obj;
22897
- }, {});
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);
22898
23405
  const subGraphProcessor = context.createSubProcessor(this.data.graphId, {
22899
23406
  signal: context.signal,
22900
23407
  project: referencedProject
@@ -22928,16 +23435,7 @@ var ReferencedGraphAliasNodeImpl = class extends NodeImpl {
22928
23435
  if (!this.data.useErrorOutput) {
22929
23436
  throw err;
22930
23437
  }
22931
- const outputs = this.getGraphOutputs(referencedProject).reduce(
22932
- (obj, output) => ({
22933
- ...obj,
22934
- [output.id]: {
22935
- type: "control-flow-excluded",
22936
- value: void 0
22937
- }
22938
- }),
22939
- {}
22940
- );
23438
+ const outputs = buildExcludedGraphBoundaryOutputs(boundary);
22941
23439
  outputs["error"] = {
22942
23440
  type: "string",
22943
23441
  value: getError(err).message
@@ -23013,6 +23511,82 @@ var BrowserNativeApi = class {
23013
23511
  }
23014
23512
  };
23015
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
+
23016
23590
  // src/integrations/openai/OpenAIEmbeddingGenerator.ts
23017
23591
  var import_openai6 = require("openai");
23018
23592
  var OpenAIEmbeddingGenerator = class {
@@ -23107,6 +23681,13 @@ function fnv1a(value, { size = 32, utf8Buffer } = {}) {
23107
23681
  function withExecution(base, execution) {
23108
23682
  return execution == null ? base : { ...base, execution };
23109
23683
  }
23684
+ function withDuration(base, durationMs, splitRunDurationMs) {
23685
+ return {
23686
+ ...base,
23687
+ ...durationMs === void 0 ? {} : { durationMs },
23688
+ ...splitRunDurationMs === void 0 ? {} : { splitRunDurationMs }
23689
+ };
23690
+ }
23110
23691
  var toRecordedEventMap = {
23111
23692
  graphStart: ({ graph, inputs, execution }) => withExecution({ graphId: graph.metadata.id, inputs }, execution),
23112
23693
  graphFinish: ({ graph, outputs, execution }) => withExecution({ graphId: graph.metadata.id, outputs }, execution),
@@ -23119,16 +23700,16 @@ var toRecordedEventMap = {
23119
23700
  inputs,
23120
23701
  processId
23121
23702
  }, execution),
23122
- nodeFinish: ({ node, outputs, processId, execution }) => withExecution({
23703
+ nodeFinish: ({ node, outputs, processId, durationMs, splitRunDurationMs, execution }) => withExecution(withDuration({
23123
23704
  nodeId: node.id,
23124
23705
  outputs,
23125
23706
  processId
23126
- }, execution),
23127
- nodeError: ({ node, error, processId, execution }) => withExecution({
23707
+ }, durationMs, splitRunDurationMs), execution),
23708
+ nodeError: ({ node, error, processId, durationMs, splitRunDurationMs, execution }) => withExecution(withDuration({
23128
23709
  nodeId: node.id,
23129
23710
  error: typeof error === "string" ? error : error.stack,
23130
23711
  processId
23131
- }, execution),
23712
+ }, durationMs, splitRunDurationMs), execution),
23132
23713
  abort: ({ successful, error }) => ({ successful, error: typeof error === "string" ? error : error == null ? void 0 : error.stack }),
23133
23714
  graphAbort: ({ successful, error, graph, execution }) => withExecution({
23134
23715
  successful,
@@ -23306,7 +23887,7 @@ var ExecutionRecorder = class _ExecutionRecorder {
23306
23887
  return;
23307
23888
  }
23308
23889
  this.#events.push(toRecordedEvent(message, data));
23309
- if (message === "done" || message === "abort" || message === "error") {
23890
+ if (isRecordingTerminalEvent(message, data)) {
23310
23891
  emitDetached(this.#emitter, "finish", {
23311
23892
  recording: this.getRecording()
23312
23893
  });
@@ -23327,7 +23908,7 @@ var ExecutionRecorder = class _ExecutionRecorder {
23327
23908
  return;
23328
23909
  }
23329
23910
  this.#events.push(toRecordedEvent(event, data));
23330
- if (event === "done" || event === "abort" || event === "error") {
23911
+ if (isRecordingTerminalEvent(event, data)) {
23331
23912
  emitDetached(this.#emitter, "finish", {
23332
23913
  recording: this.getRecording()
23333
23914
  });
@@ -23372,6 +23953,12 @@ var ExecutionRecorder = class _ExecutionRecorder {
23372
23953
  return (0, import_json_stream_es.stringifyJsonStream)(serializeToObject(this.getRecording()));
23373
23954
  }
23374
23955
  };
23956
+ function isRecordingTerminalEvent(event, data) {
23957
+ if (event === "done" || event === "error") {
23958
+ return true;
23959
+ }
23960
+ return event === "abort" && data.successful !== true;
23961
+ }
23375
23962
 
23376
23963
  // src/plugins/anthropic/nodes/ChatAnthropicNode.ts
23377
23964
  var import_non_secure85 = require("nanoid/non-secure");
@@ -29341,7 +29928,8 @@ async function* getProcessorEvents(processor, spec) {
29341
29928
  type: "nodeFinish",
29342
29929
  outputs: event.outputs,
29343
29930
  nodeId: event.node.id,
29344
- nodeTitle: event.node.title
29931
+ nodeTitle: event.node.title,
29932
+ ...event.durationMs === void 0 ? {} : { durationMs: event.durationMs }
29345
29933
  };
29346
29934
  }
29347
29935
  }
@@ -29428,6 +30016,7 @@ function coreCreateProcessor(project, options2, internalOptions = {}) {
29428
30016
  options2.includeTrace,
29429
30017
  {
29430
30018
  cacheLoadedProjects: internalOptions.cacheLoadedProjects,
30019
+ captureNodeTimings: options2.captureNodeTimings,
29431
30020
  concurrency: options2.concurrency,
29432
30021
  executionPlanCacheMode: internalOptions.executionPlanCacheMode,
29433
30022
  runtimeCache: internalOptions.runtimeCache,
@@ -29700,12 +30289,16 @@ var Rivet = void 0;
29700
30289
  createChatV2Model,
29701
30290
  createChatV2ResponseOutput,
29702
30291
  createDatasetNode,
30292
+ createDebuggerTransportEscapedSentinel,
30293
+ createDebuggerTransportEscapedSentinelEnvelope,
30294
+ createDebuggerTransportUndefinedSentinel,
29703
30295
  createInterpolationInputDefinition,
29704
30296
  createsLLMChatV2ToolResponseFormatConflictForEdit,
29705
30297
  cronNode,
29706
30298
  dataTypeDisplayNames,
29707
30299
  dataTypes,
29708
30300
  datasetNearestNeighborsNode,
30301
+ decodeDebuggerTransportSentinels,
29709
30302
  dedent,
29710
30303
  delayNode,
29711
30304
  delegateFunctionCallNode,
@@ -29789,6 +30382,7 @@ var Rivet = void 0;
29789
30382
  isChatV2StructuredResponseFormat,
29790
30383
  isDataTypeAccepted,
29791
30384
  isDataTypeCompatible,
30385
+ isDebuggerTransportSentinelEnvelope,
29792
30386
  isFunctionDataType,
29793
30387
  isFunctionDataValue,
29794
30388
  isInterpolationInputDefinition,