@valerypopoff/rivet2-core 2.1.7 → 2.1.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 (115) hide show
  1. package/dist/cjs/bundle.cjs +4911 -2546
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/esm/api/createProcessor.js +45 -4
  4. package/dist/esm/exports.js +2 -0
  5. package/dist/esm/integrations/KnowledgeStoreFieldPolicy.js +216 -0
  6. package/dist/esm/integrations/KnowledgeStoreProvider.js +14 -90
  7. package/dist/esm/integrations/ManagedKnowledgeStore.js +0 -8
  8. package/dist/esm/model/DataBusPorts.js +26 -0
  9. package/dist/esm/model/DataBusTopology.js +207 -0
  10. package/dist/esm/model/DataValue.js +22 -7
  11. package/dist/esm/model/GraphPreprocessor.js +9 -3
  12. package/dist/esm/model/GraphProcessor.js +164 -366
  13. package/dist/esm/model/NodeIO.js +1 -0
  14. package/dist/esm/model/NodePrefabResolver.js +16 -0
  15. package/dist/esm/model/Nodes.js +7 -0
  16. package/dist/esm/model/SplitRunProcessor.js +19 -10
  17. package/dist/esm/model/ToolCallContinuationBranchPlanner.js +165 -0
  18. package/dist/esm/model/ToolCallContinuationCoordinator.js +206 -0
  19. package/dist/esm/model/chat/aiSdkMessages.js +8 -0
  20. package/dist/esm/model/chat-v2/chatV2CallObserver.js +142 -0
  21. package/dist/esm/model/chat-v2/chatV2EditorCache.js +22 -0
  22. package/dist/esm/model/chat-v2/chatV2Errors.js +23 -6
  23. package/dist/esm/model/chat-v2/chatV2Outputs.js +41 -31
  24. package/dist/esm/model/chat-v2/chatV2Pipeline.js +167 -56
  25. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +1 -0
  26. package/dist/esm/model/chat-v2/chatV2ProviderTypes.js +1 -0
  27. package/dist/esm/model/chat-v2/chatV2RequestPlan.js +6 -5
  28. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +2 -2
  29. package/dist/esm/model/chat-v2/chatV2Shared.js +1 -6
  30. package/dist/esm/model/chat-v2/chatV2Types.js +11 -1
  31. package/dist/esm/model/chat-v2/developerMessageRoles.js +45 -0
  32. package/dist/esm/model/chat-v2/index.js +1 -0
  33. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +53 -3
  34. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +53 -19
  35. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +232 -68
  36. package/dist/esm/model/chat-v2/llmProfile.js +212 -0
  37. package/dist/esm/model/chat-v2/llmProfileFallback.js +288 -0
  38. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +73 -0
  39. package/dist/esm/model/chat-v2/llmProfileTypes.js +45 -0
  40. package/dist/esm/model/chat-v2/messageConverter.js +14 -0
  41. package/dist/esm/model/chat-v2/providerOptions.js +44 -11
  42. package/dist/esm/model/chat-v2/toolContinuation.js +0 -4
  43. package/dist/esm/model/nodes/AssembleMessageNode.js +6 -0
  44. package/dist/esm/model/nodes/DataBusNode.js +81 -0
  45. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +12 -0
  46. package/dist/esm/model/nodes/GetGlobalNode.js +7 -11
  47. package/dist/esm/model/nodes/GetKnowledgeSourceStatusNode.js +1 -1
  48. package/dist/esm/model/nodes/LLMChatV2Node.js +156 -18
  49. package/dist/esm/model/nodes/LLMProfileNode.js +132 -0
  50. package/dist/esm/model/nodes/PassthroughNode.js +1 -11
  51. package/dist/esm/model/nodes/PromptNode.js +9 -2
  52. package/dist/esm/model/nodes/SearchKnowledgeNode.js +1 -1
  53. package/dist/esm/model/nodes/SetGlobalNode.js +6 -6
  54. package/dist/esm/model/nodes/SyncKnowledgeSourceNode.js +0 -1
  55. package/dist/esm/model/nodes/toolCallDelegation.js +31 -4
  56. package/dist/esm/plugins/anthropic/nodes/ChatAnthropicNode.js +22 -28
  57. package/dist/esm/plugins/google/google.js +20 -9
  58. package/dist/esm/plugins/google/nodes/ChatGoogleNode.js +17 -6
  59. package/dist/esm/plugins/pinecone/PineconeKnowledgeStore.js +0 -4
  60. package/dist/esm/plugins/pinecone/plugin.js +1 -1
  61. package/dist/esm/utils/chatMessageToOpenAIChatCompletionMessage.js +4 -0
  62. package/dist/esm/utils/coerceType.js +84 -41
  63. package/dist/esm/utils/expectType.js +45 -8
  64. package/dist/esm/utils/fetchEventSource.js +18 -0
  65. package/dist/esm/utils/serialization/serialization.js +37 -7
  66. package/dist/esm/vendor/fnv1a.js +6 -3
  67. package/dist/types/api/createProcessor.d.ts +2 -0
  68. package/dist/types/exports.d.ts +2 -0
  69. package/dist/types/integrations/KnowledgeStore.d.ts +0 -2
  70. package/dist/types/integrations/KnowledgeStoreFieldPolicy.d.ts +38 -0
  71. package/dist/types/integrations/KnowledgeStoreProvider.d.ts +6 -3
  72. package/dist/types/model/DataBusPorts.d.ts +6 -0
  73. package/dist/types/model/DataBusTopology.d.ts +16 -0
  74. package/dist/types/model/DataValue.d.ts +22 -6
  75. package/dist/types/model/GraphPreprocessor.d.ts +2 -1
  76. package/dist/types/model/GraphProcessor.d.ts +4 -3
  77. package/dist/types/model/NodeBase.d.ts +6 -0
  78. package/dist/types/model/NodeIO.d.ts +5 -0
  79. package/dist/types/model/NodePrefabResolver.d.ts +9 -0
  80. package/dist/types/model/Nodes.d.ts +5 -2
  81. package/dist/types/model/ProcessContext.d.ts +64 -0
  82. package/dist/types/model/SplitRunProcessor.d.ts +2 -1
  83. package/dist/types/model/ToolCallContinuationBranchPlanner.d.ts +43 -0
  84. package/dist/types/model/ToolCallContinuationCoordinator.d.ts +70 -0
  85. package/dist/types/model/chat-v2/chatV2CallObserver.d.ts +10 -0
  86. package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +4 -0
  87. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +5 -5
  88. package/dist/types/model/chat-v2/chatV2Pipeline.d.ts +33 -0
  89. package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +1 -0
  90. package/dist/types/model/chat-v2/chatV2ProviderTypes.d.ts +1 -0
  91. package/dist/types/model/chat-v2/chatV2RequestPlan.d.ts +2 -2
  92. package/dist/types/model/chat-v2/chatV2RuntimeOptions.d.ts +8 -0
  93. package/dist/types/model/chat-v2/chatV2Shared.d.ts +0 -1
  94. package/dist/types/model/chat-v2/chatV2Types.d.ts +27 -3
  95. package/dist/types/model/chat-v2/developerMessageRoles.d.ts +10 -0
  96. package/dist/types/model/chat-v2/index.d.ts +1 -0
  97. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +10 -1
  98. package/dist/types/model/chat-v2/llmChatV2NodeEditors.d.ts +5 -1
  99. package/dist/types/model/chat-v2/llmChatV2NodeRuntime.d.ts +18 -2
  100. package/dist/types/model/chat-v2/llmProfile.d.ts +10 -0
  101. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +79 -0
  102. package/dist/types/model/chat-v2/llmProfileNodeRuntime.d.ts +9 -0
  103. package/dist/types/model/chat-v2/llmProfileTypes.d.ts +18 -0
  104. package/dist/types/model/chat-v2/providerOptions.d.ts +1 -0
  105. package/dist/types/model/nodes/AssembleMessageNode.d.ts +2 -1
  106. package/dist/types/model/nodes/DataBusNode.d.ts +19 -0
  107. package/dist/types/model/nodes/LLMProfileNode.d.ts +20 -0
  108. package/dist/types/model/nodes/PassthroughNode.d.ts +2 -15
  109. package/dist/types/model/nodes/PromptNode.d.ts +2 -2
  110. package/dist/types/model/nodes/SetGlobalNode.d.ts +2 -2
  111. package/dist/types/model/nodes/toolCallDelegation.d.ts +9 -0
  112. package/dist/types/plugins/google/google.d.ts +12 -1
  113. package/dist/types/plugins/google/nodes/ChatGoogleNode.d.ts +2 -1
  114. package/dist/types/vendor/fnv1a.d.ts +5 -5
  115. package/package.json +1 -1
@@ -0,0 +1 @@
1
+ export {};
@@ -43,6 +43,22 @@ export function resolveNodePrefabInstance(project, node) {
43
43
  },
44
44
  };
45
45
  }
46
+ /**
47
+ * Turns a valid graph-local library link into its current effective node.
48
+ *
49
+ * The returned node keeps the link's id and graph-local geometry, so existing
50
+ * connections remain valid. All node behavior and settings are cloned from
51
+ * the library source. Missing or invalid sources cannot be detached because
52
+ * there is no concrete node definition to preserve.
53
+ */
54
+ export function detachNodePrefabInstance(project, node) {
55
+ const prefabId = getNodePrefabInstancePrefabId(node);
56
+ const sourceNode = prefabId ? project.nodePrefabs?.[prefabId]?.sourceNode : undefined;
57
+ if (!sourceNode || !canUseNodeAsPrefabSource(sourceNode)) {
58
+ return undefined;
59
+ }
60
+ return resolveNodePrefabInstance(project, node);
61
+ }
46
62
  export function resolveNodePrefabInstances(project, nodes) {
47
63
  return nodes.map((node) => resolveNodePrefabInstance(project, node));
48
64
  }
@@ -8,6 +8,8 @@ export * from './nodes/ChatNode.js';
8
8
  export * from './nodes/ChatNodeBase.js';
9
9
  import { llmChatV2Node } from './nodes/LLMChatV2Node.js';
10
10
  export * from './nodes/LLMChatV2Node.js';
11
+ import { llmProfileNode } from './nodes/LLMProfileNode.js';
12
+ export * from './nodes/LLMProfileNode.js';
11
13
  import { promptNode } from './nodes/PromptNode.js';
12
14
  export * from './nodes/PromptNode.js';
13
15
  import { extractRegexNode } from './nodes/ExtractRegexNode.js';
@@ -64,6 +66,9 @@ import { didRunNode } from './nodes/DidRunNode.js';
64
66
  export * from './nodes/DidRunNode.js';
65
67
  import { passthroughNode } from './nodes/PassthroughNode.js';
66
68
  export * from './nodes/PassthroughNode.js';
69
+ import { dataBusNode } from './nodes/DataBusNode.js';
70
+ export * from './nodes/DataBusNode.js';
71
+ export * from './DataBusTopology.js';
67
72
  import { startBackgroundBranchNode } from './nodes/StartBackgroundBranchNode.js';
68
73
  export * from './nodes/StartBackgroundBranchNode.js';
69
74
  import { popNode } from './nodes/PopNode.js';
@@ -206,6 +211,7 @@ export const registerBuiltInNodes = (registry) => {
206
211
  .register(userInputNode)
207
212
  .register(textNode)
208
213
  .register(llmChatV2Node)
214
+ .register(llmProfileNode)
209
215
  .register(chatNode)
210
216
  .register(promptNode)
211
217
  .register(extractRegexNode)
@@ -235,6 +241,7 @@ export const registerBuiltInNodes = (registry) => {
235
241
  .register(coalesceNode)
236
242
  .register(didRunNode)
237
243
  .register(passthroughNode)
244
+ .register(dataBusNode)
238
245
  .register(startBackgroundBranchNode)
239
246
  .register(popNode)
240
247
  .register(setGlobalNode)
@@ -4,7 +4,7 @@ import {} from './NodeBase.js';
4
4
  import { getGraphAbortReasonFromError, isAbortLikeError } from './GraphAbortReasons.js';
5
5
  import { getError } from '../utils/errors.js';
6
6
  import PQueue from '../utils/pQueueCompat.js';
7
- import { entries, fromEntries, values } from '../utils/typeSafety.js';
7
+ import { entries, fromEntries } from '../utils/typeSafety.js';
8
8
  function withOptionalDuration(payload, durationMs, splitRunDurationMs) {
9
9
  return {
10
10
  ...payload,
@@ -17,17 +17,22 @@ export async function processSplitRunNode(node, processId, deps) {
17
17
  if (deps.isExcludedDueToControlFlow(node, inputValues, processId)) {
18
18
  return;
19
19
  }
20
- const splittingAmount = Math.min(max(values(inputValues).map((value) => (Array.isArray(value?.value) ? value?.value.length : 1))) ?? 1, node.splitRunMax ?? 10);
20
+ const inputDefinitionsById = new Map(deps.getInputDefinitions(node).map((definition) => [definition.id, definition]));
21
+ const splittingAmount = Math.min(max(entries(inputValues).map(([portId, value]) => inputDefinitionsById.get(portId)?.splitRunBehavior === 'preserve-array'
22
+ ? 1
23
+ : Array.isArray(value?.value)
24
+ ? value.value.length
25
+ : 1)) ?? 1, node.splitRunMax ?? 10);
21
26
  await deps.emit('nodeStart', { node, inputs: inputValues, processId });
22
27
  const timingStart = deps.startNodeTiming?.();
23
28
  let splitRunDurationMs;
24
29
  try {
25
30
  let results;
26
31
  if (node.isSplitSequential) {
27
- results = await runSequential(node, inputValues, splittingAmount, processId, deps);
32
+ results = await runSequential(node, inputValues, inputDefinitionsById, splittingAmount, processId, deps);
28
33
  }
29
34
  else {
30
- results = await runParallel(node, inputValues, splittingAmount, processId, deps);
35
+ results = await runParallel(node, inputValues, inputDefinitionsById, splittingAmount, processId, deps);
31
36
  }
32
37
  splitRunDurationMs = getSplitRunDurationMs(results);
33
38
  const errors = results.filter((r) => r.type === 'error').map((r) => r.error);
@@ -53,13 +58,13 @@ export async function processSplitRunNode(node, processId, deps) {
53
58
  await deps.nodeErrored(node, error, processId, deps.finishNodeTiming?.(timingStart), splitRunDurationMs);
54
59
  }
55
60
  }
56
- async function runSequential(node, inputValues, splittingAmount, processId, deps) {
61
+ async function runSequential(node, inputValues, inputDefinitionsById, splittingAmount, processId, deps) {
57
62
  const results = [];
58
63
  for (let i = 0; i < splittingAmount; i++) {
59
64
  if (deps.isAborted()) {
60
65
  throw deps.getAbortError();
61
66
  }
62
- const inputs = splitInputsAtIndex(inputValues, i);
67
+ const inputs = splitInputsAtIndex(inputValues, inputDefinitionsById, i);
63
68
  const splitTimingStart = deps.startNodeTiming?.();
64
69
  try {
65
70
  const output = await deps.processNodeWithInputData(node, inputs, i, processId, (n, partialOutputs, index) => {
@@ -74,7 +79,7 @@ async function runSequential(node, inputValues, splittingAmount, processId, deps
74
79
  }
75
80
  return results;
76
81
  }
77
- async function runParallel(node, inputValues, splittingAmount, processId, deps) {
82
+ async function runParallel(node, inputValues, inputDefinitionsById, splittingAmount, processId, deps) {
78
83
  const queue = new PQueue({ concurrency: getParallelSplitRunConcurrency(node, deps.splitRunConcurrency) });
79
84
  return Promise.all(range(0, splittingAmount).map(async (i) => {
80
85
  const result = await queue.add(async () => {
@@ -83,7 +88,7 @@ async function runParallel(node, inputValues, splittingAmount, processId, deps)
83
88
  if (deps.isAborted()) {
84
89
  throw deps.getAbortError();
85
90
  }
86
- const inputs = splitInputsAtIndex(inputValues, i);
91
+ const inputs = splitInputsAtIndex(inputValues, inputDefinitionsById, i);
87
92
  const output = await deps.processNodeWithInputData(node, inputs, i, processId, (n, partialOutputs, index) => {
88
93
  deps.emit('partialOutput', { node: n, outputs: partialOutputs, index, processId });
89
94
  });
@@ -108,10 +113,14 @@ function getParallelSplitRunConcurrency(node, defaultConcurrency) {
108
113
  const value = node.splitRunConcurrency;
109
114
  return typeof value === 'number' && Number.isFinite(value) && value >= 2 ? Math.floor(value) : defaultConcurrency;
110
115
  }
111
- function splitInputsAtIndex(inputValues, index) {
116
+ function splitInputsAtIndex(inputValues, inputDefinitionsById, index) {
112
117
  return fromEntries(entries(inputValues).map(([port, value]) => [
113
118
  port,
114
- isArrayDataValue(value) ? arrayizeDataValue(value)[index] ?? undefined : value,
119
+ inputDefinitionsById.get(port)?.splitRunBehavior === 'preserve-array'
120
+ ? value
121
+ : isArrayDataValue(value)
122
+ ? arrayizeDataValue(value)[index] ?? undefined
123
+ : value,
115
124
  ]));
116
125
  }
117
126
  function aggregateOutputs(results) {
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Pure continuation-branch topology. Runtime state is supplied for each plan
3
+ * so a final branch can see outputs that completed while an early branch ran.
4
+ */
5
+ export function createToolCallContinuationBranchPlanner(options) {
6
+ const outgoingConnectionsByNode = new Map();
7
+ const incomingConnectionsByNode = new Map();
8
+ for (const connection of options.effectiveConnections) {
9
+ const outgoing = outgoingConnectionsByNode.get(connection.outputNodeId) ?? [];
10
+ outgoing.push(connection);
11
+ outgoingConnectionsByNode.set(connection.outputNodeId, outgoing);
12
+ const incoming = incomingConnectionsByNode.get(connection.inputNodeId) ?? [];
13
+ incoming.push(connection);
14
+ incomingConnectionsByNode.set(connection.inputNodeId, incoming);
15
+ }
16
+ const unsafeNodeIds = getUnsafeNodeIds(options);
17
+ return {
18
+ unsafeNodeIds,
19
+ plan: ({ activeOutputPortIds, availableNodeOutputs, excludedNodeIds, failOnUnsafeReadyNode = false, sourceNode, sourceOutputs, state, }) => {
20
+ const hasAvailableSourceOutput = (outputId) => {
21
+ const output = sourceOutputs[outputId];
22
+ return output != null && output.type !== 'control-flow-excluded';
23
+ };
24
+ const getAvailableNodeOutputs = (nodeId) => {
25
+ if (excludedNodeIds.has(nodeId) || unsafeNodeIds.has(nodeId) || state.erroredNodeIds.has(nodeId)) {
26
+ return undefined;
27
+ }
28
+ return availableNodeOutputs.get(nodeId) ?? state.nodeOutputs.get(nodeId);
29
+ };
30
+ const canConsiderNode = (nodeId) => {
31
+ const node = options.nodesById[nodeId];
32
+ return (node != null &&
33
+ !node.disabled &&
34
+ !state.visitedNodeIds.has(nodeId) &&
35
+ (!state.runToRelevantNodeIds || state.runToRelevantNodeIds.has(nodeId)));
36
+ };
37
+ const isUnsafeNode = (nodeId) => excludedNodeIds.has(nodeId) || unsafeNodeIds.has(nodeId);
38
+ const reachableNodeIds = new Set();
39
+ const candidateNodeIds = new Set();
40
+ for (const connection of outgoingConnectionsByNode.get(sourceNode.id) ?? []) {
41
+ if (activeOutputPortIds.has(connection.outputId) && canConsiderNode(connection.inputNodeId)) {
42
+ candidateNodeIds.add(connection.inputNodeId);
43
+ }
44
+ }
45
+ const boundaryNodeIds = new Set();
46
+ let addedNode = true;
47
+ while (addedNode) {
48
+ addedNode = false;
49
+ for (const candidateNodeId of [...candidateNodeIds]) {
50
+ const incomingConnections = incomingConnectionsByNode.get(candidateNodeId) ?? [];
51
+ const isReady = incomingConnections.every((connection) => {
52
+ if (connection.outputNodeId === sourceNode.id) {
53
+ return activeOutputPortIds.has(connection.outputId) || hasAvailableSourceOutput(connection.outputId);
54
+ }
55
+ return (reachableNodeIds.has(connection.outputNodeId) || getAvailableNodeOutputs(connection.outputNodeId) != null);
56
+ });
57
+ if (!isReady) {
58
+ continue;
59
+ }
60
+ candidateNodeIds.delete(candidateNodeId);
61
+ if (isUnsafeNode(candidateNodeId)) {
62
+ if (failOnUnsafeReadyNode) {
63
+ const unsafeNode = options.nodesById[candidateNodeId];
64
+ throw new Error(`Delegate Tool Call "${sourceNode.title}" cannot fire its pre-tool Message branch through unsupported node "${unsafeNode.title}". Move cycles, races, loops, and foreground rejoin points outside that branch.`);
65
+ }
66
+ continue;
67
+ }
68
+ reachableNodeIds.add(candidateNodeId);
69
+ addedNode = true;
70
+ for (const connection of incomingConnections) {
71
+ if (connection.outputNodeId !== sourceNode.id &&
72
+ !reachableNodeIds.has(connection.outputNodeId) &&
73
+ getAvailableNodeOutputs(connection.outputNodeId) != null) {
74
+ boundaryNodeIds.add(connection.outputNodeId);
75
+ }
76
+ }
77
+ if (options.nodesById[candidateNodeId]?.type === 'startBackgroundBranch') {
78
+ continue;
79
+ }
80
+ for (const connection of outgoingConnectionsByNode.get(candidateNodeId) ?? []) {
81
+ if (connection.inputNodeId !== sourceNode.id &&
82
+ !reachableNodeIds.has(connection.inputNodeId) &&
83
+ canConsiderNode(connection.inputNodeId)) {
84
+ candidateNodeIds.add(connection.inputNodeId);
85
+ }
86
+ }
87
+ }
88
+ }
89
+ if (reachableNodeIds.size === 0) {
90
+ return undefined;
91
+ }
92
+ const includedNodeIds = new Set([sourceNode.id, ...reachableNodeIds, ...boundaryNodeIds]);
93
+ const asyncBranchConnections = [];
94
+ for (const nodeId of reachableNodeIds) {
95
+ if (options.nodesById[nodeId]?.type !== 'startBackgroundBranch') {
96
+ continue;
97
+ }
98
+ const asyncPlan = options.asyncBranchPlansByTriggerNodeId.get(nodeId);
99
+ if (!asyncPlan) {
100
+ continue;
101
+ }
102
+ for (const node of asyncPlan.graph.nodes) {
103
+ includedNodeIds.add(node.id);
104
+ }
105
+ asyncBranchConnections.push(...asyncPlan.graph.connections);
106
+ }
107
+ const foregroundBranchConnections = options.effectiveConnections.filter((connection) => {
108
+ if (!reachableNodeIds.has(connection.inputNodeId)) {
109
+ return false;
110
+ }
111
+ if (connection.outputNodeId === sourceNode.id) {
112
+ return activeOutputPortIds.has(connection.outputId) || hasAvailableSourceOutput(connection.outputId);
113
+ }
114
+ return includedNodeIds.has(connection.outputNodeId);
115
+ });
116
+ const seenConnections = new Set();
117
+ const connections = [...foregroundBranchConnections, ...asyncBranchConnections].filter((connection) => {
118
+ const key = `${connection.outputNodeId}:${connection.outputId}:${connection.inputNodeId}:${connection.inputId}`;
119
+ if (seenConnections.has(key)) {
120
+ return false;
121
+ }
122
+ seenConnections.add(key);
123
+ return true;
124
+ });
125
+ const graph = {
126
+ metadata: options.graph.metadata ? { ...options.graph.metadata } : undefined,
127
+ nodes: Object.values(options.nodesById).filter((node) => node != null && includedNodeIds.has(node.id)),
128
+ connections,
129
+ };
130
+ const preloadedOutputs = new Map([[sourceNode.id, sourceOutputs]]);
131
+ for (const nodeId of boundaryNodeIds) {
132
+ preloadedOutputs.set(nodeId, getAvailableNodeOutputs(nodeId));
133
+ }
134
+ return { graph, preloadedOutputs };
135
+ },
136
+ };
137
+ }
138
+ function getUnsafeNodeIds(options) {
139
+ const unsafeNodeIds = new Set();
140
+ for (const component of options.stronglyConnectedComponents) {
141
+ if (component.length > 1) {
142
+ component.forEach((node) => unsafeNodeIds.add(node.id));
143
+ }
144
+ }
145
+ for (const node of Object.values(options.nodesById)) {
146
+ if (!node) {
147
+ continue;
148
+ }
149
+ const attachedData = options.attachedNodeDataByNodeId.get(node.id);
150
+ if (node.type === 'loopController' ||
151
+ node.type === 'raceInputs' ||
152
+ (attachedData != null && Object.values(attachedData).some(Boolean))) {
153
+ unsafeNodeIds.add(node.id);
154
+ }
155
+ }
156
+ // SCC preprocessing sees every persisted edge, including secondary edges
157
+ // that still participate in scheduler readiness. Preserve the same view
158
+ // when detecting a one-node cycle.
159
+ for (const connection of options.graph.connections) {
160
+ if (connection.inputNodeId === connection.outputNodeId && options.isDefinitionValidConnection(connection)) {
161
+ unsafeNodeIds.add(connection.inputNodeId);
162
+ }
163
+ }
164
+ return unsafeNodeIds;
165
+ }
@@ -0,0 +1,206 @@
1
+ import { nanoid } from 'nanoid/non-secure';
2
+ import { createGraphAbortErrorFromSignal, getAbortSignalReason } from './GraphAbortReasons.js';
3
+ import { DELEGATE_TOOL_CALL_INPUT_ID } from './chat-v2/toolContinuationConnection.js';
4
+ import { buildDelegatedToolCallOutputs, delegateToolCall } from './nodes/toolCallDelegation.js';
5
+ export class ToolCallContinuationCoordinator {
6
+ #adapter;
7
+ constructor(adapter) {
8
+ this.#adapter = adapter;
9
+ }
10
+ async run(options) {
11
+ const { assistantMessage, delegateNode, llmNode, llmSignal, toolCalls } = options;
12
+ if (toolCalls.length === 0) {
13
+ return { invocations: [], results: [] };
14
+ }
15
+ if (this.#adapter.rootAbortSignal.aborted) {
16
+ throw createGraphAbortErrorFromSignal(this.#adapter.rootAbortSignal);
17
+ }
18
+ const processIds = toolCalls.map(() => nanoid());
19
+ const inputsByCall = toolCalls.map((toolCall) => ({
20
+ [DELEGATE_TOOL_CALL_INPUT_ID]: {
21
+ type: 'object',
22
+ value: toolCall,
23
+ },
24
+ }));
25
+ const nodeAbortControllers = toolCalls.map(() => this.#adapter.createNodeAbortController());
26
+ nodeAbortControllers.forEach((controller) => this.#adapter.registerNodeAbortController(delegateNode.id, controller));
27
+ const abortAllCalls = (reason) => {
28
+ for (const controller of nodeAbortControllers) {
29
+ if (!controller.signal.aborted) {
30
+ controller.abort(reason);
31
+ }
32
+ }
33
+ };
34
+ const abortFromLLM = () => {
35
+ abortAllCalls(getAbortSignalReason(llmSignal));
36
+ };
37
+ llmSignal.addEventListener('abort', abortFromLLM, { once: true });
38
+ if (this.#adapter.rootAbortSignal.aborted) {
39
+ abortAllCalls(getAbortSignalReason(this.#adapter.rootAbortSignal));
40
+ }
41
+ else if (llmSignal.aborted) {
42
+ abortFromLLM();
43
+ }
44
+ try {
45
+ await this.#adapter.waitUntilUnpaused();
46
+ const abortedController = nodeAbortControllers.find((controller) => controller.signal.aborted);
47
+ if (abortedController) {
48
+ throw createGraphAbortErrorFromSignal(abortedController.signal, 'Delegate Tool Call aborted');
49
+ }
50
+ // Snapshot topology only after the parent is runnable. A paused parent
51
+ // may still receive graph-state updates before this continuation round.
52
+ const branchAdapter = this.#adapter.createBranchAdapter();
53
+ const hasAssistantMessage = assistantMessage.trim().length > 0;
54
+ const canRunContinuationBranches = branchAdapter.canRunContinuationBranches(llmNode, delegateNode);
55
+ const assistantOutputs = {
56
+ ['assistant-message']: {
57
+ type: 'string',
58
+ value: assistantMessage,
59
+ },
60
+ };
61
+ const preToolOutputPortIds = new Set(['assistant-message']);
62
+ const hasActivePreToolBranch = hasAssistantMessage && this.#adapter.getActiveOutputPortIds(delegateNode).has('assistant-message');
63
+ const continuationBranchBoundaries = new Set(this.#adapter.getContinuationBranchBoundaryNodeIds(llmNode));
64
+ // Validate the complete round before parallel calls can cause side effects.
65
+ // The first invocation still produces a real Delegate error run for diagnostics.
66
+ try {
67
+ if (this.#adapter.hasPreloadedOrFrozenDelegateOutput(delegateNode, inputsByCall[0], processIds[0])) {
68
+ throw new Error(`Delegate Tool Call "${delegateNode.title}" is the active auto-continuation handler and cannot use preloaded or frozen outputs. Clear its preload or unfreeze it before running this graph.`);
69
+ }
70
+ if (hasActivePreToolBranch) {
71
+ if (!canRunContinuationBranches) {
72
+ throw new Error(`Delegate Tool Call "${delegateNode.title}" cannot fire its pre-tool Message branch because the LLM/Delegate continuation is inside an unsupported cycle, race, or loop.`);
73
+ }
74
+ branchAdapter.validatePreToolBranch({
75
+ activeOutputPortIds: preToolOutputPortIds,
76
+ excludedNodeIds: continuationBranchBoundaries,
77
+ sourceNode: delegateNode,
78
+ sourceOutputs: assistantOutputs,
79
+ });
80
+ }
81
+ }
82
+ catch (error) {
83
+ const processId = processIds[0];
84
+ const inputs = inputsByCall[0];
85
+ await this.#adapter.emitDelegateStart(delegateNode, inputs, processId);
86
+ await this.#adapter.emitDelegateError(delegateNode, error, processId, this.#adapter.startNodeTiming());
87
+ throw error;
88
+ }
89
+ let firstFailure;
90
+ let hasFailure = false;
91
+ const abortSiblingOnFailure = async (work) => {
92
+ try {
93
+ return await work;
94
+ }
95
+ catch (error) {
96
+ if (!hasFailure) {
97
+ hasFailure = true;
98
+ firstFailure = error;
99
+ }
100
+ abortAllCalls(error);
101
+ throw error;
102
+ }
103
+ };
104
+ const runInvocation = async (toolCall, toolCallIndex) => {
105
+ const processId = processIds[toolCallIndex];
106
+ const inputs = inputsByCall[toolCallIndex];
107
+ const nodeAbortController = nodeAbortControllers[toolCallIndex];
108
+ let timingStart;
109
+ let delegateStarted = false;
110
+ let delegateFinished = false;
111
+ try {
112
+ await this.#adapter.waitUntilUnpaused();
113
+ if (nodeAbortController.signal.aborted) {
114
+ throw createGraphAbortErrorFromSignal(nodeAbortController.signal, 'Delegate Tool Call aborted');
115
+ }
116
+ await this.#adapter.emitDelegateStart(delegateNode, inputs, processId);
117
+ delegateStarted = true;
118
+ timingStart = this.#adapter.startNodeTiming();
119
+ const delegateContext = this.#adapter.createDelegateProcessContext(delegateNode, inputs, processId, nodeAbortController);
120
+ if (hasAssistantMessage) {
121
+ this.#adapter.emitDelegatePartialOutput(delegateNode, assistantOutputs, processId);
122
+ }
123
+ const preToolBranchPromise = hasActivePreToolBranch
124
+ ? branchAdapter.runOutputBranch({
125
+ activeOutputPortIds: preToolOutputPortIds,
126
+ availableNodeOutputs: new Map(),
127
+ deferGraphOutputCommit: true,
128
+ excludedNodeIds: continuationBranchBoundaries,
129
+ failOnUnsafeReadyNode: true,
130
+ signal: nodeAbortController.signal,
131
+ sourceNode: delegateNode,
132
+ sourceOutputs: assistantOutputs,
133
+ })
134
+ : Promise.resolve(createEmptyBranchResult());
135
+ // Do not await the early Message branch before tool work: it is an
136
+ // independent side-effect branch and must overlap every scalar call.
137
+ const [toolOutcome, preToolBranchOutcome] = await Promise.allSettled([
138
+ abortSiblingOnFailure(delegateToolCall(toolCall, delegateContext, delegateNode.data)),
139
+ abortSiblingOnFailure(preToolBranchPromise),
140
+ ]);
141
+ if (toolOutcome.status === 'rejected')
142
+ throw toolOutcome.reason;
143
+ if (preToolBranchOutcome.status === 'rejected')
144
+ throw preToolBranchOutcome.reason;
145
+ const toolResult = toolOutcome.value;
146
+ const preToolBranch = preToolBranchOutcome.value;
147
+ if (nodeAbortController.signal.aborted) {
148
+ throw createGraphAbortErrorFromSignal(nodeAbortController.signal, 'Delegate Tool Call aborted');
149
+ }
150
+ const outputs = buildDelegatedToolCallOutputs([toolResult.record], hasAssistantMessage ? assistantMessage : undefined, toolResult.cost);
151
+ this.#adapter.accumulateCost(outputs);
152
+ await this.#adapter.emitDelegateFinish(delegateNode, outputs, processId, timingStart);
153
+ delegateFinished = true;
154
+ const finalBranch = canRunContinuationBranches
155
+ ? await branchAdapter.runOutputBranch({
156
+ activeOutputPortIds: new Set([
157
+ 'tool-name',
158
+ 'tool-arguments',
159
+ 'output',
160
+ 'message',
161
+ ]),
162
+ availableNodeOutputs: preToolBranch.nodeOutputs,
163
+ deferGraphOutputCommit: true,
164
+ excludedNodeIds: continuationBranchBoundaries,
165
+ failOnUnsafeReadyNode: false,
166
+ signal: nodeAbortController.signal,
167
+ sourceNode: delegateNode,
168
+ sourceOutputs: outputs,
169
+ })
170
+ : createEmptyBranchResult();
171
+ return { finalBranch, outputs, preToolBranch, toolResult };
172
+ }
173
+ catch (error) {
174
+ if (delegateStarted && !delegateFinished) {
175
+ await this.#adapter.emitDelegateError(delegateNode, error, processId, timingStart);
176
+ }
177
+ throw error;
178
+ }
179
+ };
180
+ const outcomes = await Promise.allSettled(toolCalls.map((toolCall, toolCallIndex) => abortSiblingOnFailure(runInvocation(toolCall, toolCallIndex))));
181
+ if (hasFailure) {
182
+ throw firstFailure;
183
+ }
184
+ const invocations = outcomes.map((outcome) => {
185
+ if (outcome.status === 'rejected') {
186
+ throw outcome.reason;
187
+ }
188
+ return outcome.value;
189
+ });
190
+ return {
191
+ invocations,
192
+ results: invocations.map(({ toolResult }) => ({
193
+ message: toolResult.message,
194
+ record: toolResult.record,
195
+ })),
196
+ };
197
+ }
198
+ finally {
199
+ llmSignal.removeEventListener('abort', abortFromLLM);
200
+ nodeAbortControllers.forEach((controller) => this.#adapter.unregisterNodeAbortController(delegateNode.id, controller));
201
+ }
202
+ }
203
+ }
204
+ function createEmptyBranchResult() {
205
+ return { graphOutputWrites: {}, nodeOutputs: new Map() };
206
+ }
@@ -43,6 +43,14 @@ export async function rivetMessagesToAiSdk(messages) {
43
43
  });
44
44
  break;
45
45
  }
46
+ case 'developer': {
47
+ // ModelMessage has no provider-neutral developer role.
48
+ result.push({
49
+ role: 'system',
50
+ content: stringifyParts(msg.message),
51
+ });
52
+ break;
53
+ }
46
54
  case 'user': {
47
55
  const parts = Array.isArray(msg.message) ? msg.message : [msg.message];
48
56
  if (parts.length === 1 && typeof parts[0] === 'string') {