@valerypopoff/rivet2-core 2.1.7 → 2.1.8

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 (79) hide show
  1. package/dist/cjs/bundle.cjs +3412 -1844
  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 +163 -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/ToolCallContinuationBranchPlanner.js +165 -0
  17. package/dist/esm/model/ToolCallContinuationCoordinator.js +201 -0
  18. package/dist/esm/model/chat-v2/chatV2CallObserver.js +140 -0
  19. package/dist/esm/model/chat-v2/chatV2Errors.js +23 -6
  20. package/dist/esm/model/chat-v2/chatV2Pipeline.js +47 -14
  21. package/dist/esm/model/chat-v2/chatV2ProviderTypes.js +1 -0
  22. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +2 -2
  23. package/dist/esm/model/chat-v2/index.js +1 -0
  24. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +52 -0
  25. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +38 -13
  26. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +42 -34
  27. package/dist/esm/model/chat-v2/llmProfile.js +191 -0
  28. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +73 -0
  29. package/dist/esm/model/chat-v2/llmProfileTypes.js +45 -0
  30. package/dist/esm/model/nodes/DataBusNode.js +81 -0
  31. package/dist/esm/model/nodes/GetGlobalNode.js +7 -11
  32. package/dist/esm/model/nodes/GetKnowledgeSourceStatusNode.js +1 -1
  33. package/dist/esm/model/nodes/LLMChatV2Node.js +44 -10
  34. package/dist/esm/model/nodes/LLMProfileNode.js +132 -0
  35. package/dist/esm/model/nodes/PassthroughNode.js +1 -11
  36. package/dist/esm/model/nodes/SearchKnowledgeNode.js +1 -1
  37. package/dist/esm/model/nodes/SetGlobalNode.js +6 -6
  38. package/dist/esm/model/nodes/SyncKnowledgeSourceNode.js +0 -1
  39. package/dist/esm/model/nodes/toolCallDelegation.js +13 -2
  40. package/dist/esm/plugins/pinecone/PineconeKnowledgeStore.js +0 -4
  41. package/dist/esm/plugins/pinecone/plugin.js +1 -1
  42. package/dist/esm/utils/coerceType.js +84 -41
  43. package/dist/esm/utils/expectType.js +45 -8
  44. package/dist/esm/utils/fetchEventSource.js +18 -0
  45. package/dist/esm/utils/serialization/serialization.js +18 -7
  46. package/dist/esm/vendor/fnv1a.js +6 -3
  47. package/dist/types/api/createProcessor.d.ts +2 -0
  48. package/dist/types/exports.d.ts +2 -0
  49. package/dist/types/integrations/KnowledgeStore.d.ts +0 -2
  50. package/dist/types/integrations/KnowledgeStoreFieldPolicy.d.ts +38 -0
  51. package/dist/types/integrations/KnowledgeStoreProvider.d.ts +6 -3
  52. package/dist/types/model/DataBusPorts.d.ts +6 -0
  53. package/dist/types/model/DataBusTopology.d.ts +16 -0
  54. package/dist/types/model/DataValue.d.ts +15 -5
  55. package/dist/types/model/GraphPreprocessor.d.ts +2 -1
  56. package/dist/types/model/GraphProcessor.d.ts +4 -3
  57. package/dist/types/model/NodeIO.d.ts +5 -0
  58. package/dist/types/model/NodePrefabResolver.d.ts +9 -0
  59. package/dist/types/model/Nodes.d.ts +5 -2
  60. package/dist/types/model/ProcessContext.d.ts +60 -0
  61. package/dist/types/model/ToolCallContinuationBranchPlanner.d.ts +43 -0
  62. package/dist/types/model/ToolCallContinuationCoordinator.d.ts +70 -0
  63. package/dist/types/model/chat-v2/chatV2CallObserver.d.ts +10 -0
  64. package/dist/types/model/chat-v2/chatV2ProviderTypes.d.ts +1 -0
  65. package/dist/types/model/chat-v2/chatV2RuntimeOptions.d.ts +8 -0
  66. package/dist/types/model/chat-v2/chatV2Types.d.ts +3 -3
  67. package/dist/types/model/chat-v2/index.d.ts +1 -0
  68. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +6 -0
  69. package/dist/types/model/chat-v2/llmChatV2NodeEditors.d.ts +5 -1
  70. package/dist/types/model/chat-v2/llmProfile.d.ts +3 -0
  71. package/dist/types/model/chat-v2/llmProfileNodeRuntime.d.ts +9 -0
  72. package/dist/types/model/chat-v2/llmProfileTypes.d.ts +18 -0
  73. package/dist/types/model/nodes/DataBusNode.d.ts +19 -0
  74. package/dist/types/model/nodes/LLMProfileNode.d.ts +20 -0
  75. package/dist/types/model/nodes/PassthroughNode.d.ts +2 -15
  76. package/dist/types/model/nodes/SetGlobalNode.d.ts +2 -2
  77. package/dist/types/model/nodes/toolCallDelegation.d.ts +9 -0
  78. package/dist/types/vendor/fnv1a.d.ts +5 -5
  79. 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)
@@ -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,201 @@
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(['output', 'message']),
157
+ availableNodeOutputs: preToolBranch.nodeOutputs,
158
+ deferGraphOutputCommit: true,
159
+ excludedNodeIds: continuationBranchBoundaries,
160
+ failOnUnsafeReadyNode: false,
161
+ signal: nodeAbortController.signal,
162
+ sourceNode: delegateNode,
163
+ sourceOutputs: outputs,
164
+ })
165
+ : createEmptyBranchResult();
166
+ return { finalBranch, outputs, preToolBranch, toolResult };
167
+ }
168
+ catch (error) {
169
+ if (delegateStarted && !delegateFinished) {
170
+ await this.#adapter.emitDelegateError(delegateNode, error, processId, timingStart);
171
+ }
172
+ throw error;
173
+ }
174
+ };
175
+ const outcomes = await Promise.allSettled(toolCalls.map((toolCall, toolCallIndex) => abortSiblingOnFailure(runInvocation(toolCall, toolCallIndex))));
176
+ if (hasFailure) {
177
+ throw firstFailure;
178
+ }
179
+ const invocations = outcomes.map((outcome) => {
180
+ if (outcome.status === 'rejected') {
181
+ throw outcome.reason;
182
+ }
183
+ return outcome.value;
184
+ });
185
+ return {
186
+ invocations,
187
+ results: invocations.map(({ toolResult }) => ({
188
+ message: toolResult.message,
189
+ record: toolResult.record,
190
+ })),
191
+ };
192
+ }
193
+ finally {
194
+ llmSignal.removeEventListener('abort', abortFromLLM);
195
+ nodeAbortControllers.forEach((controller) => this.#adapter.unregisterNodeAbortController(delegateNode.id, controller));
196
+ }
197
+ }
198
+ }
199
+ function createEmptyBranchResult() {
200
+ return { graphOutputWrites: {}, nodeOutputs: new Map() };
201
+ }
@@ -0,0 +1,140 @@
1
+ import { nanoid } from 'nanoid/non-secure';
2
+ import { calculateChatV2Cost, getChatV2ModelInfo } from './modelRegistry.js';
3
+ function toUsageNumber(value) {
4
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;
5
+ }
6
+ function copyRawUsage(usage) {
7
+ if (usage == null) {
8
+ return undefined;
9
+ }
10
+ const inputTokens = toUsageNumber(usage.inputTokens);
11
+ const outputTokens = toUsageNumber(usage.outputTokens);
12
+ const totalTokens = toUsageNumber(usage.totalTokens);
13
+ const cacheReadTokens = toUsageNumber(usage.inputTokenDetails?.cacheReadTokens);
14
+ const cacheWriteTokens = toUsageNumber(usage.inputTokenDetails?.cacheWriteTokens);
15
+ const noCacheTokens = toUsageNumber(usage.inputTokenDetails?.noCacheTokens);
16
+ const reasoningTokens = toUsageNumber(usage.outputTokenDetails?.reasoningTokens);
17
+ const textTokens = toUsageNumber(usage.outputTokenDetails?.textTokens);
18
+ const inputTokenDetails = {
19
+ ...(cacheReadTokens == null ? {} : { cacheReadTokens }),
20
+ ...(cacheWriteTokens == null ? {} : { cacheWriteTokens }),
21
+ ...(noCacheTokens == null ? {} : { noCacheTokens }),
22
+ };
23
+ const outputTokenDetails = {
24
+ ...(reasoningTokens == null ? {} : { reasoningTokens }),
25
+ ...(textTokens == null ? {} : { textTokens }),
26
+ };
27
+ const copied = {
28
+ ...(inputTokens == null ? {} : { inputTokens }),
29
+ ...(outputTokens == null ? {} : { outputTokens }),
30
+ ...(totalTokens == null ? {} : { totalTokens }),
31
+ ...(Object.keys(inputTokenDetails).length === 0 ? {} : { inputTokenDetails }),
32
+ ...(Object.keys(outputTokenDetails).length === 0 ? {} : { outputTokenDetails }),
33
+ };
34
+ return Object.keys(copied).length === 0 ? undefined : copied;
35
+ }
36
+ function normalizeObservedUsage(rawUsage) {
37
+ if (rawUsage == null) {
38
+ return undefined;
39
+ }
40
+ const promptTokens = rawUsage.inputTokens;
41
+ const completionTokens = rawUsage.outputTokens;
42
+ const totalTokens = rawUsage.totalTokens ??
43
+ (promptTokens != null && completionTokens != null ? promptTokens + completionTokens : undefined);
44
+ const cacheReadTokens = rawUsage.inputTokenDetails?.cacheReadTokens;
45
+ const cacheWriteTokens = rawUsage.inputTokenDetails?.cacheWriteTokens;
46
+ const cachedTokens = cacheReadTokens != null && cacheWriteTokens != null ? cacheReadTokens + cacheWriteTokens : undefined;
47
+ const reasoningTokens = rawUsage.outputTokenDetails?.reasoningTokens;
48
+ const normalized = {
49
+ ...(promptTokens == null ? {} : { promptTokens }),
50
+ ...(completionTokens == null ? {} : { completionTokens }),
51
+ ...(totalTokens == null ? {} : { totalTokens }),
52
+ ...(cachedTokens == null ? {} : { cachedTokens }),
53
+ ...(reasoningTokens == null ? {} : { reasoningTokens }),
54
+ };
55
+ return Object.keys(normalized).length === 0 ? undefined : normalized;
56
+ }
57
+ function getErrorProperty(error, key, guard) {
58
+ if (error == null || (typeof error !== 'object' && typeof error !== 'function')) {
59
+ return undefined;
60
+ }
61
+ try {
62
+ const value = error[key];
63
+ return guard(value) ? value : undefined;
64
+ }
65
+ catch {
66
+ return undefined;
67
+ }
68
+ }
69
+ function safelyRead(read) {
70
+ try {
71
+ return read();
72
+ }
73
+ catch {
74
+ return undefined;
75
+ }
76
+ }
77
+ function containUnexpectedObserverPromise(value) {
78
+ if (value == null || (typeof value !== 'object' && typeof value !== 'function')) {
79
+ return;
80
+ }
81
+ try {
82
+ if (typeof value.then === 'function') {
83
+ void Promise.resolve(value).catch(() => undefined);
84
+ }
85
+ }
86
+ catch {
87
+ // Accessing a malformed thenable must not change graph behavior either.
88
+ }
89
+ }
90
+ function isUsage(value) {
91
+ return value != null && typeof value === 'object';
92
+ }
93
+ export function createObservedChatV2CallId(options) {
94
+ return options.context.onChatV2CallFinished != null &&
95
+ options.context.node?.id != null &&
96
+ options.context.processId != null
97
+ ? nanoid()
98
+ : undefined;
99
+ }
100
+ export function notifyChatV2CallFinished(options, params) {
101
+ const observer = options.context.onChatV2CallFinished;
102
+ const nodeId = options.context.node?.id;
103
+ const processId = options.context.processId;
104
+ if (observer == null || nodeId == null || processId == null || params.callId == null) {
105
+ return;
106
+ }
107
+ const resultUsage = safelyRead(() => params.result?.usage);
108
+ const errorUsage = getErrorProperty(params.error, 'usage', isUsage);
109
+ const rawUsage = safelyRead(() => copyRawUsage(resultUsage ?? errorUsage));
110
+ const normalizedUsage = safelyRead(() => normalizeObservedUsage(rawUsage));
111
+ const modelInfo = safelyRead(() => getChatV2ModelInfo(options.provider, options.modelId));
112
+ const calculatedCost = modelInfo != null && normalizedUsage?.promptTokens != null && normalizedUsage.completionTokens != null
113
+ ? safelyRead(() => calculateChatV2Cost(options.provider, options.modelId, normalizedUsage.promptTokens, normalizedUsage.completionTokens))
114
+ : undefined;
115
+ const costUsd = toUsageNumber(calculatedCost);
116
+ const finishReason = safelyRead(() => params.result?.finishReason) ??
117
+ getErrorProperty(params.error, 'finishReason', (value) => typeof value === 'string');
118
+ const event = {
119
+ callId: params.callId,
120
+ attemptIndex: params.attemptIndex,
121
+ nodeId,
122
+ processId,
123
+ provider: options.provider,
124
+ model: options.modelId,
125
+ outcome: params.outcome,
126
+ ...(finishReason == null ? {} : { finishReason }),
127
+ ...(rawUsage == null ? {} : { rawUsage }),
128
+ ...(normalizedUsage == null ? {} : { normalizedUsage }),
129
+ pricing: {
130
+ status: modelInfo == null ? 'unknown' : 'known',
131
+ ...(costUsd == null ? {} : { costUsd }),
132
+ },
133
+ };
134
+ try {
135
+ containUnexpectedObserverPromise(observer(event));
136
+ }
137
+ catch {
138
+ // Host observers must never change graph behavior.
139
+ }
140
+ }
@@ -14,7 +14,23 @@ function compact(value, maxLength = 500) {
14
14
  return normalized.length > maxLength ? `${normalized.slice(0, maxLength - 3)}...` : normalized;
15
15
  }
16
16
  function isRecord(value) {
17
- return value != null && typeof value === 'object' && !Array.isArray(value);
17
+ if (value == null || typeof value !== 'object') {
18
+ return false;
19
+ }
20
+ try {
21
+ return !Array.isArray(value);
22
+ }
23
+ catch {
24
+ return false;
25
+ }
26
+ }
27
+ function getRecordProperty(record, key) {
28
+ try {
29
+ return record[key];
30
+ }
31
+ catch {
32
+ return undefined;
33
+ }
18
34
  }
19
35
  function stringifyProviderValue(value) {
20
36
  if (value == null) {
@@ -163,7 +179,8 @@ function coerceHttpStatusCode(value) {
163
179
  return undefined;
164
180
  }
165
181
  function getRecordStatusCode(record) {
166
- return coerceHttpStatusCode(record.statusCode) ?? coerceHttpStatusCode(record.status);
182
+ return (coerceHttpStatusCode(getRecordProperty(record, 'statusCode')) ??
183
+ coerceHttpStatusCode(getRecordProperty(record, 'status')));
167
184
  }
168
185
  export function getChatV2ProviderErrorStatusCode(error, seen = new Set()) {
169
186
  if (!isRecord(error)) {
@@ -177,20 +194,20 @@ export function getChatV2ProviderErrorStatusCode(error, seen = new Set()) {
177
194
  if (directStatusCode != null) {
178
195
  return directStatusCode;
179
196
  }
180
- const response = error.response;
197
+ const response = getRecordProperty(error, 'response');
181
198
  if (isRecord(response)) {
182
199
  const responseStatusCode = getRecordStatusCode(response);
183
200
  if (responseStatusCode != null) {
184
201
  return responseStatusCode;
185
202
  }
186
203
  }
187
- const data = error.data;
204
+ const data = getRecordProperty(error, 'data');
188
205
  if (isRecord(data)) {
189
206
  const dataStatusCode = getRecordStatusCode(data);
190
207
  if (dataStatusCode != null) {
191
208
  return dataStatusCode;
192
209
  }
193
- const dataError = data.error;
210
+ const dataError = getRecordProperty(data, 'error');
194
211
  if (isRecord(dataError)) {
195
212
  const dataErrorStatusCode = getRecordStatusCode(dataError);
196
213
  if (dataErrorStatusCode != null) {
@@ -198,7 +215,7 @@ export function getChatV2ProviderErrorStatusCode(error, seen = new Set()) {
198
215
  }
199
216
  }
200
217
  }
201
- return getChatV2ProviderErrorStatusCode(error.cause, seen);
218
+ return getChatV2ProviderErrorStatusCode(getRecordProperty(error, 'cause'), seen);
202
219
  }
203
220
  function formatProviderFetchError(error, context) {
204
221
  return [