@valerypopoff/rivet2-core 2.0.7 → 2.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/cjs/bundle.cjs +1757 -789
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/esm/api/createProcessor.js +9 -2
  4. package/dist/esm/api/streaming.js +1 -0
  5. package/dist/esm/exports.js +1 -0
  6. package/dist/esm/model/DebuggerTransportSentinel.js +78 -0
  7. package/dist/esm/model/GraphAbortReasons.js +69 -0
  8. package/dist/esm/model/GraphBoundaryCache.js +92 -0
  9. package/dist/esm/model/GraphPreprocessor.js +212 -32
  10. package/dist/esm/model/GraphProcessor.js +493 -172
  11. package/dist/esm/model/NodeExclusionPolicy.js +67 -0
  12. package/dist/esm/model/NodeExecutionPlanner.js +66 -22
  13. package/dist/esm/model/NodeImpl.js +6 -4
  14. package/dist/esm/model/ProcessContextBuilder.js +2 -17
  15. package/dist/esm/model/RecordingPlayer.js +27 -7
  16. package/dist/esm/model/SplitRunProcessor.js +48 -9
  17. package/dist/esm/model/SubprocessorBridge.js +30 -23
  18. package/dist/esm/model/chat-v2/chatV2Outputs.js +183 -0
  19. package/dist/esm/model/chat-v2/chatV2Pipeline.js +30 -212
  20. package/dist/esm/model/nodes/CodeNewNode.js +1 -1
  21. package/dist/esm/model/nodes/CodeNode.js +1 -1
  22. package/dist/esm/model/nodes/GetGlobalNode.js +14 -4
  23. package/dist/esm/model/nodes/GraphOutputNode.js +31 -2
  24. package/dist/esm/model/nodes/HttpCallNode.js +20 -18
  25. package/dist/esm/model/nodes/LoopUntilNode.js +18 -45
  26. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +24 -63
  27. package/dist/esm/model/nodes/SetGlobalNode.js +2 -1
  28. package/dist/esm/model/nodes/SubGraphNode.js +22 -63
  29. package/dist/esm/model/nodes/codeNodeErrorDiagnostics.js +2 -3
  30. package/dist/esm/recording/ExecutionRecorder.js +19 -6
  31. package/dist/esm/utils/emitDetached.js +2 -2
  32. package/dist/esm/utils/interpolation.js +41 -1
  33. package/dist/esm/utils/serialization/serialization.js +6 -5
  34. package/dist/esm/utils/serialization/serializationHelpers.js +2 -2
  35. package/dist/esm/utils/serialization/serializationInput.js +48 -0
  36. package/dist/esm/utils/serialization/serializationUtils.js +2 -33
  37. package/dist/esm/utils/serialization/serialization_v2.js +8 -8
  38. package/dist/types/api/createProcessor.d.ts +9 -2
  39. package/dist/types/api/streaming.d.ts +1 -0
  40. package/dist/types/exports.d.ts +1 -0
  41. package/dist/types/model/DebuggerTransportSentinel.d.ts +21 -0
  42. package/dist/types/model/EditorDefinition.d.ts +2 -0
  43. package/dist/types/model/ExecutorProtocol.d.ts +5 -0
  44. package/dist/types/model/GraphAbortReasons.d.ts +23 -0
  45. package/dist/types/model/GraphBoundaryCache.d.ts +27 -0
  46. package/dist/types/model/GraphPreprocessor.d.ts +39 -3
  47. package/dist/types/model/GraphProcessor.d.ts +20 -1
  48. package/dist/types/model/NodeExclusionPolicy.d.ts +21 -0
  49. package/dist/types/model/NodeExecutionPlanner.d.ts +3 -8
  50. package/dist/types/model/NodeImpl.d.ts +10 -5
  51. package/dist/types/model/Nodes.d.ts +2 -2
  52. package/dist/types/model/ProcessContext.d.ts +3 -0
  53. package/dist/types/model/ProcessContextBuilder.d.ts +4 -20
  54. package/dist/types/model/SplitRunProcessor.d.ts +8 -3
  55. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +29 -0
  56. package/dist/types/model/nodes/LoopUntilNode.d.ts +5 -4
  57. package/dist/types/model/nodes/ReferencedGraphAliasNode.d.ts +5 -4
  58. package/dist/types/model/nodes/SubGraphNode.d.ts +6 -5
  59. package/dist/types/model/nodes/codeNodeErrorDiagnostics.d.ts +1 -2
  60. package/dist/types/recording/RecordedEvents.d.ts +4 -0
  61. package/dist/types/utils/emitDetached.d.ts +2 -2
  62. package/dist/types/utils/serialization/serializationInput.d.ts +7 -0
  63. package/package.json +1 -1
@@ -0,0 +1,67 @@
1
+ import { getScalarTypeOf } from './DataValue.js';
2
+ import { IF_PORT, } from './NodeBase.js';
3
+ import { coerceTypeOptional } from '../utils/coerceType.js';
4
+ import { entries } from '../utils/typeSafety.js';
5
+ import { LOOP_NOT_BROKEN_SENTINEL } from './loopControllerBreak.js';
6
+ const nodesAllowedToConsumeExcludedValue = new Set([
7
+ 'if',
8
+ 'ifElse',
9
+ 'coalesce',
10
+ 'graphOutput',
11
+ 'raceInputs',
12
+ 'loopController',
13
+ ]);
14
+ function isControlFlowExcluded(value) {
15
+ return value != null && getScalarTypeOf(value.type) === 'control-flow-excluded';
16
+ }
17
+ export function getControlFlowExclusionDecision({ inputValues, node, typeOfExclusion, }) {
18
+ if (node.disabled) {
19
+ return {
20
+ action: 'exclude',
21
+ reason: 'disabled',
22
+ traceMessage: `Excluding node ${node.title} because it's disabled`,
23
+ };
24
+ }
25
+ if (node.isConditional && typeOfExclusion === undefined) {
26
+ const ifValue = coerceTypeOptional(inputValues[IF_PORT.id], 'boolean');
27
+ if (ifValue === false) {
28
+ return {
29
+ action: 'exclude',
30
+ reason: 'if port is false',
31
+ traceMessage: `Excluding node ${node.title} because if port is false`,
32
+ };
33
+ }
34
+ }
35
+ const controlFlowExcludedValues = entries(inputValues).filter(([, value]) => isControlFlowExcluded(value) && (typeOfExclusion === undefined || value.value === typeOfExclusion));
36
+ const isWaitingForLoop = controlFlowExcludedValues.some(([, value]) => value?.value === LOOP_NOT_BROKEN_SENTINEL);
37
+ const allowedToConsumeExcludedValue = nodesAllowedToConsumeExcludedValue.has(node.type) && !isWaitingForLoop;
38
+ if (controlFlowExcludedValues.length === 0 || allowedToConsumeExcludedValue) {
39
+ return { action: 'continue' };
40
+ }
41
+ if (isWaitingForLoop) {
42
+ return { action: 'defer' };
43
+ }
44
+ return {
45
+ action: 'exclude',
46
+ reason: 'input is excluded value',
47
+ traceMessage: `Excluding node ${node.title} because of control flow. Input is has excluded value: ${controlFlowExcludedValues[0]?.[0]}`,
48
+ };
49
+ }
50
+ export function getMissingRequiredInputExclusion(node, missingRequiredInputs) {
51
+ const missingInputNames = missingRequiredInputs.map((input) => input.title || input.id).join(', ');
52
+ return {
53
+ action: 'exclude',
54
+ reason: 'missing required input',
55
+ traceMessage: `Excluding node ${node.title} because required inputs are not connected: ${missingInputNames}`,
56
+ };
57
+ }
58
+ export function createExcludedNodeOutputs(node, outputDefinitions) {
59
+ const outputs = {};
60
+ for (const output of outputDefinitions) {
61
+ outputs[output.id] = { type: 'control-flow-excluded', value: undefined };
62
+ }
63
+ if (node.type === 'loopController') {
64
+ outputs['break'] = { type: 'control-flow-excluded', value: LOOP_NOT_BROKEN_SENTINEL };
65
+ }
66
+ return outputs;
67
+ }
@@ -1,40 +1,71 @@
1
- import { uniqBy } from 'lodash-es';
2
1
  import { getScalarTypeOf } from './DataValue.js';
3
- import { isNotNull } from '../utils/genericUtilFunctions.js';
4
2
  export function getStartNodes(state, graphNodes, runToNodeIds) {
5
- return runToNodeIds
6
- ? graphNodes.filter((node) => runToNodeIds.includes(node.id))
7
- : graphNodes.filter((node) => getOutputNodesFrom(state, node).nodes.length === 0);
3
+ if (runToNodeIds) {
4
+ return graphNodes.filter((node) => runToNodeIds.includes(node.id));
5
+ }
6
+ return state.executionPlan?.startNodes ?? graphNodes.filter((node) => getOutputNodesFrom(state, node).nodes.length === 0);
8
7
  }
9
8
  export function getInputNodesTo(state, node) {
9
+ const plannedInputNodes = state.executionPlan?.inputNodesByNode[node.id];
10
+ if (plannedInputNodes) {
11
+ return plannedInputNodes;
12
+ }
10
13
  const connections = state.connections[node.id];
11
14
  if (!connections) {
12
15
  return [];
13
16
  }
14
- const connectionsToNode = connections.filter((conn) => conn.inputNodeId === node.id).filter(isNotNull);
15
17
  const inputDefinitions = state.definitions[node.id]?.inputs ?? [];
16
- return connectionsToNode
17
- .filter((connection) => {
18
- const connectionDefinition = inputDefinitions.find((def) => def.id === connection.inputId);
19
- return connectionDefinition != null;
20
- })
21
- .map((conn) => state.nodesById[conn.outputNodeId])
22
- .filter(isNotNull);
18
+ const validInputIds = new Set(inputDefinitions.map((definition) => definition.id));
19
+ const inputNodes = [];
20
+ for (const connection of connections) {
21
+ if (connection.inputNodeId !== node.id || !validInputIds.has(connection.inputId)) {
22
+ continue;
23
+ }
24
+ const inputNode = state.nodesById[connection.outputNodeId];
25
+ if (inputNode) {
26
+ inputNodes.push(inputNode);
27
+ }
28
+ }
29
+ return inputNodes;
23
30
  }
24
31
  export function getOutputNodesFrom(state, node) {
32
+ const plannedOutputNodes = state.executionPlan?.outputNodeResultsByNode[node.id];
33
+ if (plannedOutputNodes) {
34
+ return plannedOutputNodes;
35
+ }
25
36
  const connections = state.connections[node.id];
26
37
  if (!connections) {
27
38
  return { nodes: [], connections: [], connectionsToNodes: [] };
28
39
  }
29
- const connectionsFromNode = connections.filter((conn) => conn.outputNodeId === node.id);
30
40
  const outputDefinitions = state.definitions[node.id]?.outputs ?? [];
31
- const outputConnections = connectionsFromNode.filter((connection) => {
32
- const connectionDefinition = outputDefinitions.find((def) => def.id === connection.outputId);
33
- return connectionDefinition != null;
34
- });
35
- const outputNodes = uniqBy(outputConnections.map((conn) => state.nodesById[conn.inputNodeId]).filter(isNotNull), (candidate) => candidate.id);
41
+ const validOutputIds = new Set(outputDefinitions.map((definition) => definition.id));
42
+ const outputConnections = [];
43
+ const outputConnectionsByNode = new Map();
44
+ const outputNodes = [];
45
+ const seenOutputNodeIds = new Set();
46
+ for (const connection of connections) {
47
+ if (connection.outputNodeId !== node.id || !validOutputIds.has(connection.outputId)) {
48
+ continue;
49
+ }
50
+ outputConnections.push(connection);
51
+ const outputNode = state.nodesById[connection.inputNodeId];
52
+ if (!outputNode) {
53
+ continue;
54
+ }
55
+ if (!seenOutputNodeIds.has(outputNode.id)) {
56
+ outputNodes.push(outputNode);
57
+ seenOutputNodeIds.add(outputNode.id);
58
+ }
59
+ const nodeConnections = outputConnectionsByNode.get(outputNode.id);
60
+ if (nodeConnections) {
61
+ nodeConnections.push(connection);
62
+ }
63
+ else {
64
+ outputConnectionsByNode.set(outputNode.id, [connection]);
65
+ }
66
+ }
36
67
  const connectionsToNodes = outputNodes.map((outputNode) => ({
37
- connections: outputConnections.filter((conn) => conn.inputNodeId === outputNode.id),
68
+ connections: outputConnectionsByNode.get(outputNode.id) ?? [],
38
69
  node: outputNode,
39
70
  }));
40
71
  return { nodes: outputNodes, connections: outputConnections, connectionsToNodes };
@@ -49,10 +80,19 @@ export function hasErroredInputNode(state, node, inputNodes, onTrace) {
49
80
  return false;
50
81
  }
51
82
  export function getMissingRequiredInputs(state, node) {
83
+ const plannedMissingInputs = state.executionPlan?.missingRequiredInputsByNode[node.id];
84
+ if (plannedMissingInputs) {
85
+ return plannedMissingInputs;
86
+ }
52
87
  const connections = state.connections[node.id] ?? [];
88
+ const connectedInputIds = new Set();
89
+ for (const connection of connections) {
90
+ if (connection.inputNodeId === node.id) {
91
+ connectedInputIds.add(connection.inputId);
92
+ }
93
+ }
53
94
  return state.definitions[node.id].inputs.filter((input) => {
54
- const connectionToInput = connections.find((conn) => conn.inputId === input.id && conn.inputNodeId === node.id);
55
- return input.required && !connectionToInput;
95
+ return input.required && !connectedInputIds.has(input.id);
56
96
  });
57
97
  }
58
98
  export function getWaitingForInputNode(state, node, inputNodes, inputValues) {
@@ -75,6 +115,10 @@ export function getWaitingForInputNode(state, node, inputNodes, inputValues) {
75
115
  return waitingForInputNode;
76
116
  }
77
117
  function nodesAreInSameCycle(state, a, b) {
118
+ const plannedCycleIndexByNode = state.executionPlan?.cycleIndexByNode;
119
+ if (plannedCycleIndexByNode) {
120
+ return plannedCycleIndexByNode[a] != null && plannedCycleIndexByNode[a] === plannedCycleIndexByNode[b];
121
+ }
78
122
  return state.stronglyConnectedComponents.find((cycle) => cycle.find((node) => node.id === a) && cycle.find((node) => node.id === b));
79
123
  }
80
124
  function isControlFlowExcluded(value) {
@@ -19,8 +19,10 @@ export class NodeImpl {
19
19
  get data() {
20
20
  return this.chartNode.data;
21
21
  }
22
- getInputDefinitionsIncludingBuiltIn(connections, nodes, project, referencedProjects) {
23
- const ports = [...this.getInputDefinitions(connections, nodes, project, referencedProjects)];
22
+ getInputDefinitionsIncludingBuiltIn(connections, nodes, project, referencedProjects, definitionContext) {
23
+ const ports = definitionContext
24
+ ? [...this.getInputDefinitions(connections, nodes, project, referencedProjects, definitionContext)]
25
+ : [...this.getInputDefinitions(connections, nodes, project, referencedProjects)];
24
26
  if (this.chartNode.isConditional) {
25
27
  ports.push(IF_PORT);
26
28
  }
@@ -39,10 +41,10 @@ export class PluginNodeImplClass extends NodeImpl {
39
41
  super(chartNode);
40
42
  this.impl = impl;
41
43
  }
42
- getInputDefinitions(connections, nodes, project) {
44
+ getInputDefinitions(connections, nodes, project, _referencedProjects, _definitionContext) {
43
45
  return this.impl.getInputDefinitions(this.data, connections, nodes, project);
44
46
  }
45
- getOutputDefinitions(connections, nodes, project) {
47
+ getOutputDefinitions(connections, nodes, project, _referencedProjects, _definitionContext) {
46
48
  return this.impl.getOutputDefinitions(this.data, connections, nodes, project);
47
49
  }
48
50
  process(inputData, context) {
@@ -1,33 +1,18 @@
1
1
  export function buildNodeProcessContext(options) {
2
- const { attachedData, codeRunner, context, contextValues, createSubProcessor, execution, executionCache, executor, externalFunctions, getGlobal, getPluginConfig, graphInputNodeValues, graphInputs, graphOutputs, loadedProjects, node, nodeAbortController, onPartialOutputs, processId, project, raiseEvent, requestUserInput, setGlobal, tokenizer, trace, waitEvent, waitForGlobal, abortGraph, } = options;
2
+ const { attachedData, base, createSubProcessor, execution, externalFunctions, getPluginConfig, node, nodeAbortController, onPartialOutputs, processId, requestUserInput, setGlobal, waitEvent, } = options;
3
3
  return {
4
- ...context,
4
+ ...base,
5
5
  node,
6
- tokenizer,
7
- executor,
8
- project,
9
- executionCache,
10
- graphInputs,
11
- graphOutputs,
12
6
  attachedData,
13
- codeRunner,
14
- referencedProjects: loadedProjects,
15
7
  waitEvent,
16
- raiseEvent,
17
- contextValues,
18
8
  externalFunctions: { ...externalFunctions },
19
9
  onPartialOutputs,
20
10
  signal: nodeAbortController.signal,
21
11
  processId,
22
- getGlobal,
23
12
  setGlobal,
24
- waitForGlobal,
25
13
  createSubProcessor: createSubProcessor,
26
- trace,
27
- abortGraph,
28
14
  getPluginConfig,
29
15
  requestUserInput,
30
- graphInputNodeValues,
31
16
  execution,
32
17
  };
33
18
  }
@@ -1,6 +1,13 @@
1
1
  import { getError } from '../utils/errors.js';
2
2
  import { nanoid } from 'nanoid/non-secure';
3
3
  import { emitDetached } from '../utils/emitDetached.js';
4
+ function withOptionalDuration(payload, durationMs, splitRunDurationMs) {
5
+ return {
6
+ ...payload,
7
+ ...(durationMs === undefined ? {} : { durationMs }),
8
+ ...(splitRunDurationMs === undefined ? {} : { splitRunDurationMs }),
9
+ };
10
+ }
4
11
  export async function replayExecutionRecording(options) {
5
12
  const { emitter, erroredNodes, graphOutputs, project, recorder, recordingPlaybackChatLatency, setContextValues, setGraphInputs, setGraphOutputs, setRunning, visitedNodes, waitUntilUnpaused, nodeResults, isAborted, } = options;
6
13
  const nodesByIdAllGraphs = {};
@@ -36,6 +43,7 @@ export async function replayExecutionRecording(options) {
36
43
  try {
37
44
  const legacyRootRunId = nanoid();
38
45
  const legacyGraphRunsByGraphId = new Map();
46
+ const nodeStartTimestamps = new Map();
39
47
  const getExecution = (graphId, recordedExecution) => {
40
48
  if (recordedExecution) {
41
49
  return recordedExecution;
@@ -51,6 +59,14 @@ export async function replayExecutionRecording(options) {
51
59
  rootRunId: legacyRootRunId,
52
60
  };
53
61
  };
62
+ const getNodeRunKey = (execution, nodeId, processId) => `${execution.rootRunId}:${execution.graphRunId}:${nodeId}:${processId}`;
63
+ const getRecordedDuration = (recordedDuration, execution, nodeId, processId, terminalTs) => {
64
+ if (recordedDuration !== undefined) {
65
+ return recordedDuration;
66
+ }
67
+ const startedAt = nodeStartTimestamps.get(getNodeRunKey(execution, nodeId, processId));
68
+ return startedAt === undefined ? undefined : Math.max(0, terminalTs - startedAt);
69
+ };
54
70
  for (const event of recorder.events) {
55
71
  if (isAborted()) {
56
72
  break;
@@ -142,11 +158,13 @@ export async function replayExecutionRecording(options) {
142
158
  case 'nodeStart': {
143
159
  const { data } = event;
144
160
  const node = getNode(data.nodeId);
161
+ const execution = getExecution(data.execution?.graphId ?? getGraphIdForNode(data.nodeId), data.execution);
162
+ nodeStartTimestamps.set(getNodeRunKey(execution, data.nodeId, data.processId), event.ts);
145
163
  emitDetached(emitter, 'nodeStart', {
146
164
  node,
147
165
  inputs: data.inputs,
148
166
  processId: data.processId,
149
- execution: getExecution(data.execution?.graphId ?? getGraphIdForNode(data.nodeId), data.execution),
167
+ execution,
150
168
  });
151
169
  if (node.type === 'chat') {
152
170
  await new Promise((resolve) => setTimeout(resolve, recordingPlaybackChatLatency));
@@ -156,12 +174,13 @@ export async function replayExecutionRecording(options) {
156
174
  case 'nodeFinish': {
157
175
  const { data } = event;
158
176
  const node = getNode(data.nodeId);
159
- emitDetached(emitter, 'nodeFinish', {
177
+ const execution = getExecution(data.execution?.graphId ?? getGraphIdForNode(data.nodeId), data.execution);
178
+ emitDetached(emitter, 'nodeFinish', withOptionalDuration({
160
179
  node,
161
180
  outputs: data.outputs,
162
181
  processId: data.processId,
163
- execution: getExecution(data.execution?.graphId ?? getGraphIdForNode(data.nodeId), data.execution),
164
- });
182
+ execution,
183
+ }, getRecordedDuration(data.durationMs, execution, data.nodeId, data.processId, event.ts), data.splitRunDurationMs));
165
184
  nodeResults.set(data.nodeId, data.outputs);
166
185
  visitedNodes.add(data.nodeId);
167
186
  break;
@@ -169,12 +188,13 @@ export async function replayExecutionRecording(options) {
169
188
  case 'nodeError': {
170
189
  const { data } = event;
171
190
  const node = getNode(data.nodeId);
172
- emitDetached(emitter, 'nodeError', {
191
+ const execution = getExecution(data.execution?.graphId ?? getGraphIdForNode(data.nodeId), data.execution);
192
+ emitDetached(emitter, 'nodeError', withOptionalDuration({
173
193
  node,
174
194
  error: data.error,
175
195
  processId: data.processId,
176
- execution: getExecution(data.execution?.graphId ?? getGraphIdForNode(data.nodeId), data.execution),
177
- });
196
+ execution,
197
+ }, getRecordedDuration(data.durationMs, execution, data.nodeId, data.processId, event.ts), data.splitRunDurationMs));
178
198
  erroredNodes.set(data.nodeId, data.error);
179
199
  visitedNodes.add(data.nodeId);
180
200
  break;
@@ -1,16 +1,26 @@
1
1
  import { max, range } from 'lodash-es';
2
2
  import { isArrayDataValue, arrayizeDataValue, } from './DataValue.js';
3
3
  import {} from './NodeBase.js';
4
+ import { getGraphAbortReasonFromError, isAbortLikeError } from './GraphAbortReasons.js';
4
5
  import { getError } from '../utils/errors.js';
5
6
  import PQueue from '../utils/pQueueCompat.js';
6
7
  import { entries, fromEntries, values } from '../utils/typeSafety.js';
8
+ function withOptionalDuration(payload, durationMs, splitRunDurationMs) {
9
+ return {
10
+ ...payload,
11
+ ...(durationMs === undefined ? {} : { durationMs }),
12
+ ...(splitRunDurationMs === undefined ? {} : { splitRunDurationMs }),
13
+ };
14
+ }
7
15
  export async function processSplitRunNode(node, processId, deps) {
8
16
  const inputValues = deps.getInputValues(node);
9
17
  if (deps.isExcludedDueToControlFlow(node, inputValues, processId)) {
10
18
  return;
11
19
  }
12
20
  const splittingAmount = Math.min(max(values(inputValues).map((value) => (Array.isArray(value?.value) ? value?.value.length : 1))) ?? 1, node.splitRunMax ?? 10);
13
- deps.emit('nodeStart', { node, inputs: inputValues, processId });
21
+ await deps.emit('nodeStart', { node, inputs: inputValues, processId });
22
+ const timingStart = deps.startNodeTiming?.();
23
+ let splitRunDurationMs;
14
24
  try {
15
25
  let results;
16
26
  if (node.isSplitSequential) {
@@ -19,38 +29,47 @@ export async function processSplitRunNode(node, processId, deps) {
19
29
  else {
20
30
  results = await runParallel(node, inputValues, splittingAmount, processId, deps);
21
31
  }
32
+ splitRunDurationMs = getSplitRunDurationMs(results);
22
33
  const errors = results.filter((r) => r.type === 'error').map((r) => r.error);
23
34
  if (errors.length === 1) {
24
35
  throw errors[0];
25
36
  }
26
37
  else if (errors.length > 0) {
38
+ if (deps.isAborted() && errors.every(isGraphAbortOrAbortLikeError)) {
39
+ throw deps.getAbortError();
40
+ }
27
41
  throw new AggregateError(errors);
28
42
  }
29
43
  const aggregateResults = aggregateOutputs(results);
30
44
  deps.setNodeResults(node.id, aggregateResults);
31
45
  deps.markNodeVisited(node.id);
32
- deps.emit('nodeFinish', { node, outputs: aggregateResults, processId });
46
+ await deps.emit('nodeFinish', withOptionalDuration({
47
+ node,
48
+ outputs: aggregateResults,
49
+ processId,
50
+ }, deps.finishNodeTiming?.(timingStart), splitRunDurationMs));
33
51
  }
34
52
  catch (error) {
35
- deps.nodeErrored(node, error, processId);
53
+ await deps.nodeErrored(node, error, processId, deps.finishNodeTiming?.(timingStart), splitRunDurationMs);
36
54
  }
37
55
  }
38
56
  async function runSequential(node, inputValues, splittingAmount, processId, deps) {
39
57
  const results = [];
40
58
  for (let i = 0; i < splittingAmount; i++) {
41
59
  if (deps.isAborted()) {
42
- throw new Error('Processing aborted');
60
+ throw deps.getAbortError();
43
61
  }
44
62
  const inputs = splitInputsAtIndex(inputValues, i);
63
+ const splitTimingStart = deps.startNodeTiming?.();
45
64
  try {
46
65
  const output = await deps.processNodeWithInputData(node, inputs, i, processId, (n, partialOutputs, index) => {
47
66
  deps.emit('partialOutput', { node: n, outputs: partialOutputs, index, processId });
48
67
  });
49
68
  deps.accumulateCost(output);
50
- results.push({ type: 'output', output });
69
+ results.push({ type: 'output', output, durationMs: deps.finishNodeTiming?.(splitTimingStart) });
51
70
  }
52
71
  catch (error) {
53
- results.push({ type: 'error', error: getError(error) });
72
+ results.push({ type: 'error', error: getError(error), durationMs: deps.finishNodeTiming?.(splitTimingStart) });
54
73
  }
55
74
  }
56
75
  return results;
@@ -59,16 +78,24 @@ async function runParallel(node, inputValues, splittingAmount, processId, deps)
59
78
  const queue = new PQueue({ concurrency: getParallelSplitRunConcurrency(node, deps.splitRunConcurrency) });
60
79
  return Promise.all(range(0, splittingAmount).map(async (i) => {
61
80
  const result = await queue.add(async () => {
62
- const inputs = splitInputsAtIndex(inputValues, i);
81
+ const splitTimingStart = deps.startNodeTiming?.();
63
82
  try {
83
+ if (deps.isAborted()) {
84
+ throw deps.getAbortError();
85
+ }
86
+ const inputs = splitInputsAtIndex(inputValues, i);
64
87
  const output = await deps.processNodeWithInputData(node, inputs, i, processId, (n, partialOutputs, index) => {
65
88
  deps.emit('partialOutput', { node: n, outputs: partialOutputs, index, processId });
66
89
  });
67
90
  deps.accumulateCost(output);
68
- return { type: 'output', output };
91
+ return { type: 'output', output, durationMs: deps.finishNodeTiming?.(splitTimingStart) };
69
92
  }
70
93
  catch (error) {
71
- return { type: 'error', error: getError(error) };
94
+ return {
95
+ type: 'error',
96
+ error: getError(error),
97
+ durationMs: deps.finishNodeTiming?.(splitTimingStart),
98
+ };
72
99
  }
73
100
  });
74
101
  if (!result) {
@@ -96,3 +123,15 @@ function aggregateOutputs(results) {
96
123
  return acc;
97
124
  }, {});
98
125
  }
126
+ function getSplitRunDurationMs(results) {
127
+ const durations = {};
128
+ for (const [index, result] of results.entries()) {
129
+ if (result.durationMs !== undefined) {
130
+ durations[index] = result.durationMs;
131
+ }
132
+ }
133
+ return Object.keys(durations).length > 0 ? durations : undefined;
134
+ }
135
+ function isGraphAbortOrAbortLikeError(error) {
136
+ return getGraphAbortReasonFromError(error) != null || isAbortLikeError(error);
137
+ }
@@ -1,3 +1,4 @@
1
+ import { getGraphAbortReasonFromSignal } from './GraphAbortReasons.js';
1
2
  function subscribeOwnGraphRunLifecycle(processor, onLifecycleEvent) {
2
3
  let ownGraphRunId;
3
4
  const unsubscribeGraphStart = processor.on('graphStart', (event) => {
@@ -19,20 +20,24 @@ function subscribeOwnGraphRunLifecycle(processor, onLifecycleEvent) {
19
20
  };
20
21
  }
21
22
  export function wireSubprocessorEvents(processor, parentEmitter, parentState) {
22
- const unsubscribers = [
23
- processor.on('nodeError', (event) => parentEmitter.emit('nodeError', event)),
24
- processor.on('nodeFinish', (event) => parentEmitter.emit('nodeFinish', event)),
25
- processor.on('partialOutput', (event) => parentEmitter.emit('partialOutput', event)),
26
- processor.on('nodeExcluded', (event) => parentEmitter.emit('nodeExcluded', event)),
27
- processor.on('nodeStart', (event) => parentEmitter.emit('nodeStart', event)),
28
- processor.on('graphAbort', (event) => parentEmitter.emit('graphAbort', event)),
29
- processor.on('graphError', (event) => parentEmitter.emit('graphError', event)),
30
- processor.on('userInput', (event) => parentEmitter.emit('userInput', event)),
31
- processor.on('graphStart', (event) => parentEmitter.emit('graphStart', event)),
32
- processor.on('graphFinish', (event) => parentEmitter.emit('graphFinish', event)),
33
- processor.on('nodeOutputsCleared', (event) => parentEmitter.emit('nodeOutputsCleared', event)),
34
- processor.on('globalSet', (event) => parentEmitter.emit('globalSet', event)),
35
- processor.on('newAbortController', (event) => parentEmitter.emit('newAbortController', event)),
23
+ // Some successful graph-abort paths can emit node terminals just after their
24
+ // graph-level terminal event. Keep passive forwarding alive for the
25
+ // subprocessor object lifetime so remote-debugger/recorder consumers do not
26
+ // miss those node terminals.
27
+ processor.on('nodeError', (event) => parentEmitter.emit('nodeError', event));
28
+ processor.on('nodeFinish', (event) => parentEmitter.emit('nodeFinish', event));
29
+ processor.on('partialOutput', (event) => parentEmitter.emit('partialOutput', event));
30
+ processor.on('nodeExcluded', (event) => parentEmitter.emit('nodeExcluded', event));
31
+ processor.on('nodeStart', (event) => parentEmitter.emit('nodeStart', event));
32
+ processor.on('graphAbort', (event) => parentEmitter.emit('graphAbort', event));
33
+ processor.on('graphError', (event) => parentEmitter.emit('graphError', event));
34
+ processor.on('userInput', (event) => parentEmitter.emit('userInput', event));
35
+ processor.on('graphStart', (event) => parentEmitter.emit('graphStart', event));
36
+ processor.on('graphFinish', (event) => parentEmitter.emit('graphFinish', event));
37
+ processor.on('nodeOutputsCleared', (event) => parentEmitter.emit('nodeOutputsCleared', event));
38
+ processor.on('globalSet', (event) => parentEmitter.emit('globalSet', event));
39
+ processor.on('newAbortController', (event) => parentEmitter.emit('newAbortController', event));
40
+ const controlUnsubscribers = [
36
41
  processor.on('pause', () => {
37
42
  if (!parentState.isPaused()) {
38
43
  parentState.pause();
@@ -44,27 +49,29 @@ export function wireSubprocessorEvents(processor, parentEmitter, parentState) {
44
49
  }
45
50
  }),
46
51
  ];
47
- const unsubscribeAny = processor.onAny((event, data) => {
52
+ processor.onAny((event, data) => {
48
53
  if (event.startsWith('globalSet:')) {
49
54
  void parentEmitter.emit(event, data);
50
55
  }
51
56
  });
52
- let cleanedUp = false;
53
- const cleanup = () => {
54
- if (cleanedUp) {
57
+ let controlsCleanedUp = false;
58
+ const cleanupControls = () => {
59
+ if (controlsCleanedUp) {
55
60
  return;
56
61
  }
57
- cleanedUp = true;
58
- unsubscribers.forEach((unsubscribe) => unsubscribe());
62
+ controlsCleanedUp = true;
63
+ controlUnsubscribers.forEach((unsubscribe) => unsubscribe());
59
64
  };
60
- unsubscribers.push(unsubscribeAny, subscribeOwnGraphRunLifecycle(processor, cleanup));
65
+ controlUnsubscribers.push(subscribeOwnGraphRunLifecycle(processor, cleanupControls));
61
66
  }
62
67
  export function wireSubprocessorLifecycle(processor, options) {
63
68
  const abortFromSignal = () => {
64
- void processor.abort();
69
+ const abortReason = getGraphAbortReasonFromSignal(options.signal);
70
+ void processor.abort(abortReason?.successful ?? false, abortReason?.error);
65
71
  };
66
72
  const abortFromParent = () => {
67
- void processor.abort();
73
+ const abortReason = getGraphAbortReasonFromSignal(options.parentAbortSignal);
74
+ void processor.abort(abortReason?.successful ?? false, abortReason?.error);
68
75
  };
69
76
  const pauseProcessor = () => {
70
77
  void processor.pause();