@valerypopoff/rivet2-core 2.1.9 → 2.1.10

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 (155) hide show
  1. package/dist/cjs/bundle.cjs +3596 -1745
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/webAppRuntime.cjs +298 -21
  4. package/dist/cjs/webAppRuntime.cjs.map +4 -4
  5. package/dist/esm/exports.js +1 -0
  6. package/dist/esm/model/AgentResponseTrace.js +448 -0
  7. package/dist/esm/model/ConnectedToolContinuationHost.js +33 -0
  8. package/dist/esm/model/GraphProcessor.js +151 -74
  9. package/dist/esm/model/NodeImpl.js +6 -0
  10. package/dist/esm/model/ProcessContextBuilder.js +3 -1
  11. package/dist/esm/model/RecordingPlayer.js +164 -22
  12. package/dist/esm/model/SplitRunProcessor.js +49 -8
  13. package/dist/esm/model/SubprocessorBridge.js +2 -0
  14. package/dist/esm/model/ToolCallContinuationCoordinator.js +7 -3
  15. package/dist/esm/model/UiGraph.js +21 -0
  16. package/dist/esm/model/UiGraphActionProtocol.js +2 -0
  17. package/dist/esm/model/UiGraphBrowserRuntime.js +133 -4
  18. package/dist/esm/model/UiGraphRendererStyles.js +221 -0
  19. package/dist/esm/model/UiGraphRuntimeModel.js +9 -3
  20. package/dist/esm/model/UiGraphSchema.js +7 -1
  21. package/dist/esm/model/chat/aiSdkTools.js +3 -2
  22. package/dist/esm/model/chat-v2/chatV2CallObserver.js +9 -5
  23. package/dist/esm/model/chat-v2/chatV2EditorCache.js +42 -16
  24. package/dist/esm/model/chat-v2/chatV2Errors.js +7 -19
  25. package/dist/esm/model/chat-v2/chatV2FeatureCompatibility.js +1 -1
  26. package/dist/esm/model/chat-v2/chatV2Outputs.js +48 -108
  27. package/dist/esm/model/chat-v2/chatV2Pipeline.js +61 -146
  28. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +8 -2
  29. package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +9 -0
  30. package/dist/esm/model/chat-v2/chatV2RequestPlan.js +2 -3
  31. package/dist/esm/model/chat-v2/chatV2ResponseBodyCapture.js +55 -0
  32. package/dist/esm/model/chat-v2/chatV2ResponseFormat.js +8 -4
  33. package/dist/esm/model/chat-v2/chatV2Retry.js +4 -3
  34. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +6 -1
  35. package/dist/esm/model/chat-v2/chatV2Types.js +5 -9
  36. package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +78 -0
  37. package/dist/esm/model/chat-v2/customProviderApi.js +42 -0
  38. package/dist/esm/model/chat-v2/index.js +12 -0
  39. package/dist/esm/model/chat-v2/llmChatV2Body.js +281 -0
  40. package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +32 -0
  41. package/dist/esm/model/chat-v2/llmChatV2CachePolicy.js +20 -0
  42. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +6 -50
  43. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +25 -13
  44. package/dist/esm/model/chat-v2/llmChatV2NodeMigration.js +24 -0
  45. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +121 -193
  46. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +60 -0
  47. package/dist/esm/model/chat-v2/llmInvocationDecision.js +11 -0
  48. package/dist/esm/model/chat-v2/llmInvocationJournal.js +43 -0
  49. package/dist/esm/model/chat-v2/llmInvocationPlan.js +68 -0
  50. package/dist/esm/model/chat-v2/llmInvocationProjections.js +5 -0
  51. package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +48 -0
  52. package/dist/esm/model/chat-v2/llmModelCandidate.js +75 -0
  53. package/dist/esm/model/chat-v2/llmProfile.js +10 -65
  54. package/dist/esm/model/chat-v2/llmProfileBody.js +183 -0
  55. package/dist/esm/model/chat-v2/llmProfileFallback.js +55 -99
  56. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +67 -0
  57. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +3 -0
  58. package/dist/esm/model/chat-v2/llmProfileTypes.js +1 -18
  59. package/dist/esm/model/chat-v2/llmResponseMaterializer.js +42 -0
  60. package/dist/esm/model/chat-v2/modelRegistry.js +54 -4
  61. package/dist/esm/model/chat-v2/parallelToolCalls.js +9 -2
  62. package/dist/esm/model/chat-v2/providerOptions.js +86 -20
  63. package/dist/esm/model/chat-v2/rivetToolRegistry.js +9 -0
  64. package/dist/esm/model/chat-v2/toolCallCodec.js +52 -0
  65. package/dist/esm/model/chat-v2/toolContinuation.js +72 -35
  66. package/dist/esm/model/chat-v2/toolHandlerResolver.js +23 -0
  67. package/dist/esm/model/chat-v2/toolRoundExecutor.js +12 -0
  68. package/dist/esm/model/nodes/ChatNode.js +6 -0
  69. package/dist/esm/model/nodes/ChatNodeBase.js +1 -0
  70. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +19 -6
  71. package/dist/esm/model/nodes/LLMChatV2Node.js +112 -229
  72. package/dist/esm/model/nodes/LLMProfileNode.js +27 -8
  73. package/dist/esm/model/nodes/PromptNode.js +7 -0
  74. package/dist/esm/model/nodes/ToolNode.js +7 -0
  75. package/dist/esm/model/nodes/toolCallDelegation.js +177 -110
  76. package/dist/esm/plugins/anthropic/anthropic.js +4 -4
  77. package/dist/esm/plugins/anthropic/nodes/ChatAnthropicNode.js +7 -0
  78. package/dist/esm/plugins/google/google.js +5 -9
  79. package/dist/esm/plugins/google/nodes/ChatGoogleNode.js +4 -1
  80. package/dist/esm/recording/ExecutionRecorder.js +13 -5
  81. package/dist/esm/utils/emitDetached.js +6 -3
  82. package/dist/esm/utils/openai.js +60 -16
  83. package/dist/esm/utils/serialization/serialization.js +2 -19
  84. package/dist/esm/webAppRuntime.js +3 -2
  85. package/dist/types/exports.d.ts +1 -0
  86. package/dist/types/model/AgentResponseTrace.d.ts +110 -0
  87. package/dist/types/model/ConnectedToolContinuationHost.d.ts +34 -0
  88. package/dist/types/model/ExecutorProtocol.d.ts +25 -7
  89. package/dist/types/model/GraphProcessor.d.ts +27 -5
  90. package/dist/types/model/NodeImpl.d.ts +18 -1
  91. package/dist/types/model/Nodes.d.ts +2 -2
  92. package/dist/types/model/ProcessContext.d.ts +47 -0
  93. package/dist/types/model/ProcessContextBuilder.d.ts +3 -1
  94. package/dist/types/model/RecordingPlayer.d.ts +6 -0
  95. package/dist/types/model/SplitRunProcessor.d.ts +10 -3
  96. package/dist/types/model/UiGraph.d.ts +8 -0
  97. package/dist/types/model/UiGraphActionProtocol.d.ts +2 -0
  98. package/dist/types/model/UiGraphBrowserRuntime.d.ts +11 -2
  99. package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
  100. package/dist/types/model/UiGraphRuntimeModel.d.ts +2 -0
  101. package/dist/types/model/UiGraphSchema.d.ts +1 -0
  102. package/dist/types/model/chat-v2/chatV2CallObserver.d.ts +2 -0
  103. package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +1 -3
  104. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +6 -16
  105. package/dist/types/model/chat-v2/chatV2Pipeline.d.ts +13 -17
  106. package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +4 -0
  107. package/dist/types/model/chat-v2/chatV2ProviderRegistry.d.ts +8 -0
  108. package/dist/types/model/chat-v2/chatV2RequestPlan.d.ts +2 -2
  109. package/dist/types/model/chat-v2/chatV2ResponseBodyCapture.d.ts +19 -0
  110. package/dist/types/model/chat-v2/chatV2ResponseFormat.d.ts +3 -2
  111. package/dist/types/model/chat-v2/chatV2Retry.d.ts +2 -0
  112. package/dist/types/model/chat-v2/chatV2Types.d.ts +20 -10
  113. package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +14 -0
  114. package/dist/types/model/chat-v2/customProviderApi.d.ts +23 -0
  115. package/dist/types/model/chat-v2/index.d.ts +12 -0
  116. package/dist/types/model/chat-v2/llmChatV2Body.d.ts +24 -0
  117. package/dist/types/model/chat-v2/llmChatV2CacheBoundary.d.ts +10 -0
  118. package/dist/types/model/chat-v2/llmChatV2CachePolicy.d.ts +13 -0
  119. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +10 -3
  120. package/dist/types/model/chat-v2/llmChatV2NodeMigration.d.ts +8 -0
  121. package/dist/types/model/chat-v2/llmChatV2NodeRuntime.d.ts +14 -16
  122. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +16 -0
  123. package/dist/types/model/chat-v2/llmInvocationDecision.d.ts +21 -0
  124. package/dist/types/model/chat-v2/llmInvocationJournal.d.ts +38 -0
  125. package/dist/types/model/chat-v2/llmInvocationPlan.d.ts +41 -0
  126. package/dist/types/model/chat-v2/llmInvocationProjections.d.ts +3 -0
  127. package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +26 -0
  128. package/dist/types/model/chat-v2/llmModelCandidate.d.ts +18 -0
  129. package/dist/types/model/chat-v2/llmProfileBody.d.ts +20 -0
  130. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +17 -49
  131. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +189 -0
  132. package/dist/types/model/chat-v2/llmProfileTypes.d.ts +1 -1
  133. package/dist/types/model/chat-v2/llmResponseMaterializer.d.ts +20 -0
  134. package/dist/types/model/chat-v2/modelRegistry.d.ts +17 -187
  135. package/dist/types/model/chat-v2/parallelToolCalls.d.ts +3 -1
  136. package/dist/types/model/chat-v2/providerOptions.d.ts +10 -0
  137. package/dist/types/model/chat-v2/rivetToolRegistry.d.ts +11 -0
  138. package/dist/types/model/chat-v2/toolCallCodec.d.ts +7 -0
  139. package/dist/types/model/chat-v2/toolContinuation.d.ts +3 -3
  140. package/dist/types/model/chat-v2/toolHandlerResolver.d.ts +25 -0
  141. package/dist/types/model/chat-v2/toolRoundExecutor.d.ts +18 -0
  142. package/dist/types/model/nodes/ChatNode.d.ts +2 -1
  143. package/dist/types/model/nodes/DelegateFunctionCallNode.d.ts +2 -1
  144. package/dist/types/model/nodes/LLMChatV2Node.d.ts +2 -1
  145. package/dist/types/model/nodes/LLMProfileNode.d.ts +2 -1
  146. package/dist/types/model/nodes/PromptNode.d.ts +4 -1
  147. package/dist/types/model/nodes/ToolNode.d.ts +2 -1
  148. package/dist/types/model/nodes/toolCallDelegation.d.ts +10 -3
  149. package/dist/types/plugins/anthropic/anthropic.d.ts +1 -0
  150. package/dist/types/plugins/google/google.d.ts +2 -8
  151. package/dist/types/recording/RecordedEvents.d.ts +6 -0
  152. package/dist/types/utils/emitDetached.d.ts +3 -2
  153. package/dist/types/utils/openai.d.ts +49 -0
  154. package/dist/types/webAppRuntime.d.ts +4 -2
  155. package/package.json +2 -2
@@ -1,6 +1,14 @@
1
1
  import { omit } from 'lodash-es';
2
2
  import { coerceTypeOptional } from '../../utils/coerceType.js';
3
3
  import { getError } from '../../utils/errors.js';
4
+ import { createDelegatedToolCallRecord, createToolResultMessage, normalizeToolCall, stringifyToolResult, } from '../chat-v2/toolCallCodec.js';
5
+ import { findAutoDelegateGraphCandidate, resolveToolHandler } from '../chat-v2/toolHandlerResolver.js';
6
+ /**
7
+ * Reserved inputs belong to Rivet's tool invocation envelope. Model-produced
8
+ * arguments must never replace them, otherwise a handler can observe a tool
9
+ * name or argument object that does not match the invocation being delegated.
10
+ */
11
+ const RIVET_TOOL_CALL_INPUT_IDS = new Set(['_function_name', '_arguments', '_rivet_tool_call']);
4
12
  /**
5
13
  * Finds an Auto Delegate handler from an ordered set of graph-like candidates.
6
14
  *
@@ -9,10 +17,7 @@ import { getError } from '../../utils/errors.js';
9
17
  * entries and uses their map keys. Keeping that distinction here preserves the
10
18
  * existing behavior for malformed projects where those identities disagree.
11
19
  */
12
- export function findAutoDelegateGraphCandidate(candidates, toolName, getGraphName) {
13
- return (candidates.find((candidate) => getGraphName(candidate) === toolName) ??
14
- candidates.find((candidate) => getGraphName(candidate)?.includes(toolName)));
15
- }
20
+ export { findAutoDelegateGraphCandidate };
16
21
  export function isDelegatedToolCallRecord(input) {
17
22
  const maybeRecord = input;
18
23
  const maybeMessage = maybeRecord?.message;
@@ -41,9 +46,26 @@ export function buildDelegatedToolCallOutputs(records, preToolMessage, cost) {
41
46
  type: 'string',
42
47
  value: preToolMessage,
43
48
  };
49
+ const executionTimesSeconds = records.map((record) => {
50
+ const executionTimeMs = getExecutionTimeMs(record);
51
+ return executionTimeMs == null ? undefined : executionTimeMs / 1_000;
52
+ });
53
+ const executionTimeOutput = executionTimesSeconds.every((executionTimeSeconds) => executionTimeSeconds != null)
54
+ ? records.length === 1
55
+ ? {
56
+ type: 'number',
57
+ value: executionTimesSeconds[0],
58
+ }
59
+ : {
60
+ type: 'number[]',
61
+ value: executionTimesSeconds,
62
+ }
63
+ : {
64
+ type: 'control-flow-excluded',
65
+ value: undefined,
66
+ };
44
67
  const outputs = records.length === 1
45
68
  ? {
46
- ['assistant-message']: preToolMessageOutput,
47
69
  ['tool-name']: {
48
70
  type: 'string',
49
71
  value: records[0].name,
@@ -52,17 +74,18 @@ export function buildDelegatedToolCallOutputs(records, preToolMessage, cost) {
52
74
  type: 'object',
53
75
  value: records[0].arguments,
54
76
  },
77
+ ['assistant-message']: preToolMessageOutput,
55
78
  ['output']: {
56
79
  type: 'string',
57
80
  value: records[0].output,
58
81
  },
82
+ ['execution-time']: executionTimeOutput,
59
83
  ['message']: {
60
84
  type: 'chat-message',
61
85
  value: records[0].message,
62
86
  },
63
87
  }
64
88
  : {
65
- ['assistant-message']: preToolMessageOutput,
66
89
  ['tool-name']: {
67
90
  type: 'string[]',
68
91
  value: records.map((record) => record.name),
@@ -71,10 +94,12 @@ export function buildDelegatedToolCallOutputs(records, preToolMessage, cost) {
71
94
  type: 'object[]',
72
95
  value: records.map((record) => record.arguments),
73
96
  },
97
+ ['assistant-message']: preToolMessageOutput,
74
98
  ['output']: {
75
99
  type: 'string[]',
76
100
  value: records.map((record) => record.output),
77
101
  },
102
+ ['execution-time']: executionTimeOutput,
78
103
  ['message']: {
79
104
  type: 'chat-message[]',
80
105
  value: records.map((record) => record.message),
@@ -85,112 +110,108 @@ export function buildDelegatedToolCallOutputs(records, preToolMessage, cost) {
85
110
  }
86
111
  return outputs;
87
112
  }
88
- export function normalizeFunctionCallInput(input) {
89
- if (Array.isArray(input)) {
90
- if (input.length !== 1) {
91
- throw new Error(`Delegate Tool Call expected a single tool call, but received ${input.length}. Use Run per item or select one tool call before delegating.`);
92
- }
93
- return normalizeFunctionCallInput(input[0]);
94
- }
95
- if (typeof input !== 'object' || input == null) {
96
- throw new Error('Delegate Tool Call expected a tool call object.');
97
- }
98
- const rawFunctionCall = input;
99
- const name = rawFunctionCall.name;
100
- if (typeof name !== 'string' || name.length === 0) {
101
- throw new Error('Delegate Tool Call expected the tool call to include a name.');
102
- }
103
- const id = typeof rawFunctionCall.id === 'string' ? rawFunctionCall.id : undefined;
104
- const rawArguments = rawFunctionCall.arguments;
105
- if (rawArguments == null) {
106
- return { id, name, arguments: {} };
107
- }
108
- if (typeof rawArguments === 'string') {
109
- try {
110
- const parsedArguments = JSON.parse(rawArguments);
111
- if (typeof parsedArguments === 'object' && parsedArguments != null && !Array.isArray(parsedArguments)) {
112
- return { id, name, arguments: parsedArguments };
113
- }
114
- }
115
- catch {
116
- // Fall through to the explicit error below.
117
- }
118
- throw new Error(`Delegate Tool Call expected "${name}" arguments to be a JSON object.`);
113
+ /** @deprecated Use normalizeToolCall from the canonical chat-v2 codec. */
114
+ export const normalizeFunctionCallInput = normalizeToolCall;
115
+ export async function delegateToolCall(rawFunctionCall, context, config) {
116
+ const functionCall = normalizeToolCall(rawFunctionCall);
117
+ const source = context.toolCallTraceSource ?? {
118
+ nodeId: context.node?.id ?? 'unknown',
119
+ processId: context.processId ?? 'unknown',
120
+ };
121
+ // A connected continuation changes the trace *source* to the LLM Chat, but
122
+ // the Delegate invocation still owns the persisted result. Carry that exact
123
+ // pointer so observers can navigate to the result without matching tool
124
+ // names or scanning potentially evicted input values.
125
+ const resultOwner = getToolCallResultOwner(context);
126
+ const startedAt = Date.now();
127
+ const timingStart = getCurrentTimeMs();
128
+ const trace = { handlerKind: 'unknown' };
129
+ try {
130
+ const result = await delegateResolvedToolCall(functionCall, context, config, trace);
131
+ notifyToolCallFinished(context, {
132
+ ...(functionCall.id == null ? {} : { toolCallId: functionCall.id }),
133
+ toolName: functionCall.name,
134
+ sourceNodeId: source.nodeId,
135
+ sourceProcessId: source.processId,
136
+ ...(resultOwner == null ? {} : { resultOwner }),
137
+ ...trace,
138
+ outcome: result.traceOutcome ?? 'success',
139
+ startedAt,
140
+ durationMs: Math.max(0, getCurrentTimeMs() - timingStart),
141
+ });
142
+ return result;
119
143
  }
120
- if (typeof rawArguments === 'object' && !Array.isArray(rawArguments)) {
121
- return { id, name, arguments: rawArguments };
144
+ catch (error) {
145
+ notifyToolCallFinished(context, {
146
+ ...(functionCall.id == null ? {} : { toolCallId: functionCall.id }),
147
+ toolName: functionCall.name,
148
+ sourceNodeId: source.nodeId,
149
+ sourceProcessId: source.processId,
150
+ ...trace,
151
+ outcome: context.signal.aborted ? 'aborted' : 'failure',
152
+ startedAt,
153
+ durationMs: Math.max(0, getCurrentTimeMs() - timingStart),
154
+ });
155
+ throw error;
122
156
  }
123
- throw new Error(`Delegate Tool Call expected "${name}" arguments to be an object.`);
124
157
  }
125
- function buildToolResultMessage(functionCall, outputString) {
126
- return {
127
- type: 'function',
128
- message: outputString,
129
- name: functionCall.id ?? '',
130
- toolName: functionCall.name,
131
- };
132
- }
133
- function buildDelegatedToolCallRecord(functionCall, outputString) {
158
+ function getToolCallResultOwner(context) {
159
+ const node = context.node;
160
+ if (node?.type !== 'delegateFunctionCall' || typeof node.id !== 'string' || typeof context.processId !== 'string') {
161
+ return undefined;
162
+ }
134
163
  return {
135
- delegatedToolCall: true,
136
- name: functionCall.name,
137
- arguments: functionCall.arguments,
138
- id: functionCall.id,
139
- output: outputString,
140
- message: buildToolResultMessage(functionCall, outputString),
164
+ nodeId: node.id,
165
+ processId: context.processId,
166
+ outputPortId: 'output',
141
167
  };
142
168
  }
143
- function stringifyToolOutput(output) {
144
- if (typeof output === 'string') {
145
- return output;
146
- }
147
- return JSON.stringify(output) ?? String(output);
148
- }
149
- export async function delegateToolCall(rawFunctionCall, context, config) {
150
- const functionCall = normalizeFunctionCallInput(rawFunctionCall);
169
+ async function delegateResolvedToolCall(functionCall, context, config, trace) {
170
+ const resolvedHandler = resolveToolHandler({
171
+ project: context.project,
172
+ toolName: functionCall.name,
173
+ config,
174
+ hasExternalFunction: context.externalFunctions[functionCall.name] != null,
175
+ });
151
176
  let handler;
152
- if (config.autoDelegate) {
153
- const graphs = Object.values(context.project.graphs);
154
- const matchingGraph = findAutoDelegateGraphCandidate(graphs, functionCall.name, (graph) => graph.metadata?.name);
155
- if (matchingGraph) {
156
- handler = { key: undefined, value: matchingGraph.metadata.id };
157
- }
158
- }
159
- else {
160
- handler = config.handlers.find((handler) => handler.key === functionCall.name);
161
- }
162
- if (!handler) {
163
- if (config.autoDelegate && config.fallBackToExternalCall) {
164
- const externalFunction = context.externalFunctions[functionCall.name];
165
- if (externalFunction) {
166
- try {
167
- const externalContext = omit(context, ['setGlobal']);
168
- const result = await externalFunction(externalContext, functionCall.arguments ?? {});
169
- const outputString = stringifyToolOutput(result);
177
+ if (resolvedHandler?.kind === 'external') {
178
+ const externalFunction = context.externalFunctions[functionCall.name];
179
+ if (externalFunction) {
180
+ trace.handlerKind = 'external';
181
+ trace.handlerName = functionCall.name;
182
+ const executionStart = getCurrentTimeMs();
183
+ try {
184
+ const externalContext = omit(context, ['setGlobal']);
185
+ const result = await externalFunction(externalContext, functionCall.arguments ?? {});
186
+ const outputString = stringifyToolResult(result);
187
+ const executionTimeMs = getCurrentTimeMs() - executionStart;
188
+ return {
189
+ outputString,
190
+ message: createToolResultMessage(functionCall, outputString),
191
+ record: createDelegatedToolCallRecord(functionCall, outputString, executionTimeMs),
192
+ cost: result.cost,
193
+ };
194
+ }
195
+ catch (error) {
196
+ if (config.passthroughErrors) {
197
+ const outputString = `Error: ${getError(error).message}`;
198
+ const executionTimeMs = getCurrentTimeMs() - executionStart;
170
199
  return {
171
200
  outputString,
172
- message: buildToolResultMessage(functionCall, outputString),
173
- record: buildDelegatedToolCallRecord(functionCall, outputString),
174
- cost: result.cost,
201
+ message: createToolResultMessage(functionCall, outputString),
202
+ record: createDelegatedToolCallRecord(functionCall, outputString, executionTimeMs),
203
+ traceOutcome: 'passthrough-error',
175
204
  };
176
205
  }
177
- catch (error) {
178
- if (config.passthroughErrors) {
179
- const outputString = `Error: ${getError(error).message}`;
180
- return {
181
- outputString,
182
- message: buildToolResultMessage(functionCall, outputString),
183
- record: buildDelegatedToolCallRecord(functionCall, outputString),
184
- };
185
- }
186
- throw new Error(`External function call failed for ${functionCall.name}: ${getError(error).message}`);
187
- }
206
+ throw new Error(`External function call failed for ${functionCall.name}: ${getError(error).message}`);
188
207
  }
189
208
  }
190
- if (config.unknownHandler) {
191
- handler = { key: undefined, value: config.unknownHandler };
192
- }
193
- else if (config.autoDelegate) {
209
+ }
210
+ if (resolvedHandler?.kind === 'graph' || resolvedHandler?.kind === 'unknown') {
211
+ handler = { value: resolvedHandler.graphId };
212
+ }
213
+ if (!handler) {
214
+ if (config.autoDelegate) {
194
215
  const errorMessage = config.fallBackToExternalCall
195
216
  ? `No handler found for tool call: ${functionCall.name}, no graph containing the name "${functionCall.name}" was found, and no external function with that name was registered.`
196
217
  : `No handler found for tool call: ${functionCall.name}, no graph containing the name "${functionCall.name}" was found.`;
@@ -200,30 +221,76 @@ export async function delegateToolCall(rawFunctionCall, context, config) {
200
221
  throw new Error(`No handler found for tool call: ${functionCall.name}`);
201
222
  }
202
223
  }
203
- const subgraphInputs = {
204
- _function_name: {
205
- type: 'string',
206
- value: functionCall.name,
207
- },
208
- _arguments: {
209
- type: 'object',
210
- value: functionCall.arguments,
224
+ // A null-prototype map prevents model arguments such as `__proto__` from
225
+ // changing the input map's prototype. Retain the legacy top-level argument
226
+ // inputs for existing handler graphs, while also providing one namespaced
227
+ // invocation envelope for new graphs.
228
+ const subgraphInputs = Object.create(null);
229
+ subgraphInputs._function_name = {
230
+ type: 'string',
231
+ value: functionCall.name,
232
+ };
233
+ subgraphInputs._arguments = {
234
+ type: 'object',
235
+ value: functionCall.arguments,
236
+ };
237
+ subgraphInputs._rivet_tool_call = {
238
+ type: 'object',
239
+ value: {
240
+ id: functionCall.id,
241
+ name: functionCall.name,
242
+ arguments: functionCall.arguments,
211
243
  },
212
244
  };
245
+ trace.handlerKind = 'graph';
246
+ trace.handlerGraphId = handler.value;
247
+ const handlerName = context.project.graphs[handler.value]?.metadata?.name;
248
+ if (handlerName != null) {
249
+ trace.handlerName = handlerName;
250
+ }
213
251
  for (const [argName, argument] of Object.entries(functionCall.arguments ?? {})) {
252
+ if (RIVET_TOOL_CALL_INPUT_IDS.has(argName)) {
253
+ continue;
254
+ }
214
255
  subgraphInputs[argName] = {
215
256
  type: 'any',
216
257
  value: argument,
217
258
  };
218
259
  }
219
260
  const subprocessor = context.createSubProcessor(handler.value, { signal: context.signal });
261
+ const executionStart = getCurrentTimeMs();
220
262
  const outputs = await subprocessor.processGraph(context, subgraphInputs, context.contextValues);
221
- const outputString = coerceTypeOptional(outputs['output'], 'string') ?? '';
263
+ const executionTimeMs = getCurrentTimeMs() - executionStart;
264
+ const outputValue = outputs['output'];
265
+ if (outputValue == null) {
266
+ throw new Error(`Tool handler graph "${handlerName ?? handler.value}" must return a string Graph Output named "output".`);
267
+ }
268
+ const outputString = coerceTypeOptional(outputValue, 'string');
269
+ if (outputString == null) {
270
+ throw new Error(`Tool handler graph "${handlerName ?? handler.value}" returned an invalid Graph Output named "output". It must resolve to a string.`);
271
+ }
222
272
  const cost = coerceTypeOptional(outputs['cost'], 'number');
223
273
  return {
224
274
  outputString,
225
- message: buildToolResultMessage(functionCall, outputString),
226
- record: buildDelegatedToolCallRecord(functionCall, outputString),
275
+ message: createToolResultMessage(functionCall, outputString),
276
+ record: createDelegatedToolCallRecord(functionCall, outputString, executionTimeMs),
227
277
  cost,
228
278
  };
229
279
  }
280
+ function notifyToolCallFinished(context, event) {
281
+ try {
282
+ context.onToolCallFinished?.(event);
283
+ }
284
+ catch {
285
+ // Trace observers must never change tool execution behavior.
286
+ }
287
+ }
288
+ function getCurrentTimeMs() {
289
+ return globalThis.performance?.now?.() ?? Date.now();
290
+ }
291
+ function getExecutionTimeMs(record) {
292
+ const { executionTimeMs } = record;
293
+ return typeof executionTimeMs === 'number' && Number.isFinite(executionTimeMs) && executionTimeMs >= 0
294
+ ? executionTimeMs
295
+ : undefined;
296
+ }
@@ -4,8 +4,8 @@ export const anthropicModels = {
4
4
  'claude-instant-1': {
5
5
  maxTokens: 100_000,
6
6
  cost: {
7
- prompt: 0.00163,
8
- completion: 0.00551,
7
+ prompt: 1.63e-6,
8
+ completion: 5.51e-6,
9
9
  },
10
10
  displayName: 'Claude Instant',
11
11
  },
@@ -85,7 +85,7 @@ export const anthropicModels = {
85
85
  maxTokens: 200_000,
86
86
  cost: {
87
87
  prompt: 3e-6,
88
- completion: 3.75e-6,
88
+ completion: 15e-6,
89
89
  },
90
90
  displayName: 'Claude Sonnet 4',
91
91
  },
@@ -93,7 +93,7 @@ export const anthropicModels = {
93
93
  maxTokens: 200_000,
94
94
  cost: {
95
95
  prompt: 15e-6,
96
- completion: 18.75e-6,
96
+ completion: 75e-6,
97
97
  },
98
98
  displayName: 'Claude Opus 4',
99
99
  },
@@ -55,6 +55,12 @@ export const ChatAnthropicNodeImpl = {
55
55
  };
56
56
  return chartNode;
57
57
  },
58
+ getRunActivityDescriptor() {
59
+ return {
60
+ category: 'model',
61
+ primaryOutputPortId: 'response',
62
+ };
63
+ },
58
64
  getInputDefinitions(data) {
59
65
  const inputs = [];
60
66
  if (data.model.startsWith('claude-3')) {
@@ -394,6 +400,7 @@ export const ChatAnthropicNodeImpl = {
394
400
  if (data.cache) {
395
401
  const cached = cache.get(cacheKey);
396
402
  if (cached) {
403
+ context.markResultAsEditorCacheHit?.();
397
404
  return cached;
398
405
  }
399
406
  }
@@ -60,20 +60,16 @@ export const generativeAiGoogleModels = {
60
60
  },
61
61
  'gemini-1.5-pro': {
62
62
  maxTokens: 2097152,
63
- cost: {
64
- prompt: 0, // It's per-character wtf
65
- completion: 0, // It's per-character
66
- },
67
63
  displayName: 'Gemini 1.5 Pro',
64
+ // The retained legacy model stays selectable, but its old catalog did not
65
+ // carry a reliable token rate. Do not turn that absence into a false $0.
66
+ pricing: 'unpriced',
68
67
  },
69
68
  'gemini-1.5-flash': {
70
69
  maxTokens: 1048576,
71
- cost: {
72
- prompt: 0, // It's per-character wtf
73
- completion: 0, // It's per-character
74
- },
75
70
  displayName: 'Gemini 1.5 Flash',
76
- }
71
+ pricing: 'unpriced',
72
+ },
77
73
  };
78
74
  export const googleModelOptionsDeprecated = Object.entries(googleModelsDeprecated).map(([id, { displayName }]) => ({
79
75
  value: id,
@@ -395,7 +395,9 @@ export const ChatGoogleNodeImpl = {
395
395
  type: Type.OBJECT,
396
396
  properties: mapValues(parameters.properties ?? {}, (property) => ({
397
397
  // gemini doesn't support union property types, it uses openapi style not jsonschema, what a mess
398
- type: toGoogleSchemaType(Array.isArray(property.type) ? property.type.find((type) => type !== 'null') : property.type),
398
+ type: toGoogleSchemaType(Array.isArray(property.type)
399
+ ? property.type.find((type) => type !== 'null')
400
+ : property.type),
399
401
  description: property.description,
400
402
  })),
401
403
  required: parameters.required ?? [],
@@ -447,6 +449,7 @@ export const ChatGoogleNodeImpl = {
447
449
  if (data.cache) {
448
450
  const cached = cache.get(cacheKey);
449
451
  if (cached) {
452
+ context.markResultAsEditorCacheHit?.();
450
453
  return cached;
451
454
  }
452
455
  }
@@ -24,20 +24,24 @@ const toRecordedEventMap = {
24
24
  graphId: graph.metadata.id,
25
25
  error: typeof error === 'string' ? error : error.stack,
26
26
  }, execution),
27
- nodeStart: ({ node, inputs, processId, execution }) => withExecution({
27
+ nodeStart: ({ node, inputs, inputConnections, processId, resultOrigin, execution }) => withExecution({
28
28
  nodeId: node.id,
29
29
  inputs,
30
+ ...(inputConnections == null ? {} : { inputConnections }),
30
31
  processId,
32
+ ...(resultOrigin === undefined ? {} : { resultOrigin }),
31
33
  }, execution),
32
- nodeFinish: ({ node, outputs, processId, durationMs, splitRunDurationMs, execution }) => withExecution(withDuration({
34
+ nodeFinish: ({ node, outputs, processId, resultOrigin, durationMs, splitRunDurationMs, execution }) => withExecution(withDuration({
33
35
  nodeId: node.id,
34
36
  outputs,
35
37
  processId,
38
+ ...(resultOrigin === undefined ? {} : { resultOrigin }),
36
39
  }, durationMs, splitRunDurationMs), execution),
37
- nodeError: ({ node, error, processId, durationMs, splitRunDurationMs, execution }) => withExecution(withDuration({
40
+ nodeError: ({ node, error, processId, resultOrigin, durationMs, splitRunDurationMs, execution }) => withExecution(withDuration({
38
41
  nodeId: node.id,
39
42
  error: typeof error === 'string' ? error : error.stack,
40
43
  processId,
44
+ ...(resultOrigin === undefined ? {} : { resultOrigin }),
41
45
  }, durationMs, splitRunDurationMs), execution),
42
46
  abort: ({ successful, error }) => ({ successful, error: typeof error === 'string' ? error : error?.stack }),
43
47
  graphAbort: ({ successful, error, graph, execution }) => withExecution({
@@ -45,12 +49,13 @@ const toRecordedEventMap = {
45
49
  error: typeof error === 'string' ? error : error?.stack,
46
50
  graphId: graph.metadata.id,
47
51
  }, execution),
48
- nodeExcluded: ({ node, processId, inputs, outputs, reason, execution }) => withExecution({
52
+ nodeExcluded: ({ node, processId, inputs, outputs, reason, resultOrigin, execution }) => withExecution({
49
53
  nodeId: node.id,
50
54
  processId,
51
55
  inputs,
52
56
  outputs,
53
57
  reason,
58
+ ...(resultOrigin === undefined ? {} : { resultOrigin }),
54
59
  }, execution),
55
60
  userInput: ({ node, inputs, callback, processId, inputStrings, renderingType, execution }) => withExecution({
56
61
  nodeId: node.id,
@@ -60,17 +65,20 @@ const toRecordedEventMap = {
60
65
  inputStrings,
61
66
  renderingType,
62
67
  }, execution),
63
- partialOutput: ({ node, outputs, index, processId, execution }) => withExecution({
68
+ partialOutput: ({ node, outputs, index, processId, resultOrigin, execution }) => withExecution({
64
69
  nodeId: node.id,
65
70
  outputs,
66
71
  index,
67
72
  processId,
73
+ ...(resultOrigin === undefined ? {} : { resultOrigin }),
68
74
  }, execution),
69
75
  progress: ({ node, processId, progress, execution }) => withExecution({
70
76
  nodeId: node.id,
71
77
  processId,
72
78
  progress,
73
79
  }, execution),
80
+ llmCallFinished: ({ execution, ...event }) => ({ ...event, execution }),
81
+ toolCallFinished: ({ execution, ...event }) => ({ ...event, execution }),
74
82
  nodeOutputsCleared: ({ node, processId, execution }) => withExecution({
75
83
  nodeId: node.id,
76
84
  processId,
@@ -4,9 +4,12 @@
4
4
  * Use this instead of inline `// eslint-disable-next-line @typescript-eslint/no-floating-promises`
5
5
  * to make the "detached async" intent explicit and auditable.
6
6
  *
7
- * The returned promise is intentionally discarded. Call this only for events
8
- * where listener completion does not affect processor ordering.
7
+ * The returned promise is intentionally detached and listener failures are
8
+ * contained. Call this only for observer events where listener completion or
9
+ * failure must not affect processor ordering.
9
10
  */
10
11
  export function emitDetached(emitter, event, data) {
11
- void emitter.emit(event, data);
12
+ void emitter.emit(event, data).catch(() => {
13
+ // Detached observers must not alter or terminate graph execution.
14
+ });
12
15
  }