@valerypopoff/rivet2-core 2.1.8 → 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 (168) hide show
  1. package/dist/cjs/bundle.cjs +4457 -1809
  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 +152 -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 +68 -18
  13. package/dist/esm/model/SubprocessorBridge.js +2 -0
  14. package/dist/esm/model/ToolCallContinuationCoordinator.js +13 -4
  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/aiSdkMessages.js +8 -0
  22. package/dist/esm/model/chat/aiSdkTools.js +3 -2
  23. package/dist/esm/model/chat-v2/chatV2CallObserver.js +11 -5
  24. package/dist/esm/model/chat-v2/chatV2EditorCache.js +58 -10
  25. package/dist/esm/model/chat-v2/chatV2Errors.js +7 -19
  26. package/dist/esm/model/chat-v2/chatV2FeatureCompatibility.js +1 -1
  27. package/dist/esm/model/chat-v2/chatV2Outputs.js +56 -106
  28. package/dist/esm/model/chat-v2/chatV2Pipeline.js +142 -149
  29. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +9 -2
  30. package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +9 -0
  31. package/dist/esm/model/chat-v2/chatV2RequestPlan.js +5 -5
  32. package/dist/esm/model/chat-v2/chatV2ResponseBodyCapture.js +55 -0
  33. package/dist/esm/model/chat-v2/chatV2ResponseFormat.js +8 -4
  34. package/dist/esm/model/chat-v2/chatV2Retry.js +4 -3
  35. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +6 -1
  36. package/dist/esm/model/chat-v2/chatV2Shared.js +1 -6
  37. package/dist/esm/model/chat-v2/chatV2Types.js +7 -1
  38. package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +78 -0
  39. package/dist/esm/model/chat-v2/customProviderApi.js +42 -0
  40. package/dist/esm/model/chat-v2/developerMessageRoles.js +45 -0
  41. package/dist/esm/model/chat-v2/index.js +12 -0
  42. package/dist/esm/model/chat-v2/llmChatV2Body.js +281 -0
  43. package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +32 -0
  44. package/dist/esm/model/chat-v2/llmChatV2CachePolicy.js +20 -0
  45. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +8 -54
  46. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +41 -20
  47. package/dist/esm/model/chat-v2/llmChatV2NodeMigration.js +24 -0
  48. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +178 -94
  49. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +60 -0
  50. package/dist/esm/model/chat-v2/llmInvocationDecision.js +11 -0
  51. package/dist/esm/model/chat-v2/llmInvocationJournal.js +43 -0
  52. package/dist/esm/model/chat-v2/llmInvocationPlan.js +68 -0
  53. package/dist/esm/model/chat-v2/llmInvocationProjections.js +5 -0
  54. package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +48 -0
  55. package/dist/esm/model/chat-v2/llmModelCandidate.js +75 -0
  56. package/dist/esm/model/chat-v2/llmProfile.js +31 -65
  57. package/dist/esm/model/chat-v2/llmProfileBody.js +183 -0
  58. package/dist/esm/model/chat-v2/llmProfileFallback.js +244 -0
  59. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +67 -0
  60. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +3 -0
  61. package/dist/esm/model/chat-v2/llmProfileTypes.js +1 -18
  62. package/dist/esm/model/chat-v2/llmResponseMaterializer.js +42 -0
  63. package/dist/esm/model/chat-v2/messageConverter.js +14 -0
  64. package/dist/esm/model/chat-v2/modelRegistry.js +54 -4
  65. package/dist/esm/model/chat-v2/parallelToolCalls.js +9 -2
  66. package/dist/esm/model/chat-v2/providerOptions.js +120 -21
  67. package/dist/esm/model/chat-v2/rivetToolRegistry.js +9 -0
  68. package/dist/esm/model/chat-v2/toolCallCodec.js +52 -0
  69. package/dist/esm/model/chat-v2/toolContinuation.js +72 -39
  70. package/dist/esm/model/chat-v2/toolHandlerResolver.js +23 -0
  71. package/dist/esm/model/chat-v2/toolRoundExecutor.js +12 -0
  72. package/dist/esm/model/nodes/AssembleMessageNode.js +6 -0
  73. package/dist/esm/model/nodes/ChatNode.js +6 -0
  74. package/dist/esm/model/nodes/ChatNodeBase.js +1 -0
  75. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +26 -1
  76. package/dist/esm/model/nodes/LLMChatV2Node.js +131 -144
  77. package/dist/esm/model/nodes/LLMProfileNode.js +27 -8
  78. package/dist/esm/model/nodes/PromptNode.js +16 -2
  79. package/dist/esm/model/nodes/ToolNode.js +7 -0
  80. package/dist/esm/model/nodes/toolCallDelegation.js +193 -110
  81. package/dist/esm/plugins/anthropic/anthropic.js +4 -4
  82. package/dist/esm/plugins/anthropic/nodes/ChatAnthropicNode.js +29 -28
  83. package/dist/esm/plugins/google/google.js +25 -18
  84. package/dist/esm/plugins/google/nodes/ChatGoogleNode.js +21 -7
  85. package/dist/esm/recording/ExecutionRecorder.js +13 -5
  86. package/dist/esm/utils/chatMessageToOpenAIChatCompletionMessage.js +4 -0
  87. package/dist/esm/utils/emitDetached.js +6 -3
  88. package/dist/esm/utils/openai.js +60 -16
  89. package/dist/esm/utils/serialization/serialization.js +2 -0
  90. package/dist/esm/webAppRuntime.js +3 -2
  91. package/dist/types/exports.d.ts +1 -0
  92. package/dist/types/model/AgentResponseTrace.d.ts +110 -0
  93. package/dist/types/model/ConnectedToolContinuationHost.d.ts +34 -0
  94. package/dist/types/model/DataValue.d.ts +7 -1
  95. package/dist/types/model/ExecutorProtocol.d.ts +25 -7
  96. package/dist/types/model/GraphProcessor.d.ts +27 -5
  97. package/dist/types/model/NodeBase.d.ts +6 -0
  98. package/dist/types/model/NodeImpl.d.ts +18 -1
  99. package/dist/types/model/Nodes.d.ts +2 -2
  100. package/dist/types/model/ProcessContext.d.ts +51 -0
  101. package/dist/types/model/ProcessContextBuilder.d.ts +3 -1
  102. package/dist/types/model/RecordingPlayer.d.ts +6 -0
  103. package/dist/types/model/SplitRunProcessor.d.ts +11 -3
  104. package/dist/types/model/UiGraph.d.ts +8 -0
  105. package/dist/types/model/UiGraphActionProtocol.d.ts +2 -0
  106. package/dist/types/model/UiGraphBrowserRuntime.d.ts +11 -2
  107. package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
  108. package/dist/types/model/UiGraphRuntimeModel.d.ts +2 -0
  109. package/dist/types/model/UiGraphSchema.d.ts +1 -0
  110. package/dist/types/model/chat-v2/chatV2CallObserver.d.ts +2 -0
  111. package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +3 -1
  112. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +7 -17
  113. package/dist/types/model/chat-v2/chatV2Pipeline.d.ts +29 -0
  114. package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +5 -0
  115. package/dist/types/model/chat-v2/chatV2ProviderRegistry.d.ts +8 -0
  116. package/dist/types/model/chat-v2/chatV2RequestPlan.d.ts +2 -2
  117. package/dist/types/model/chat-v2/chatV2ResponseBodyCapture.d.ts +19 -0
  118. package/dist/types/model/chat-v2/chatV2ResponseFormat.d.ts +3 -2
  119. package/dist/types/model/chat-v2/chatV2Retry.d.ts +2 -0
  120. package/dist/types/model/chat-v2/chatV2Shared.d.ts +0 -1
  121. package/dist/types/model/chat-v2/chatV2Types.d.ts +35 -1
  122. package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +14 -0
  123. package/dist/types/model/chat-v2/customProviderApi.d.ts +23 -0
  124. package/dist/types/model/chat-v2/developerMessageRoles.d.ts +10 -0
  125. package/dist/types/model/chat-v2/index.d.ts +12 -0
  126. package/dist/types/model/chat-v2/llmChatV2Body.d.ts +24 -0
  127. package/dist/types/model/chat-v2/llmChatV2CacheBoundary.d.ts +10 -0
  128. package/dist/types/model/chat-v2/llmChatV2CachePolicy.d.ts +13 -0
  129. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +13 -3
  130. package/dist/types/model/chat-v2/llmChatV2NodeMigration.d.ts +8 -0
  131. package/dist/types/model/chat-v2/llmChatV2NodeRuntime.d.ts +18 -4
  132. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +16 -0
  133. package/dist/types/model/chat-v2/llmInvocationDecision.d.ts +21 -0
  134. package/dist/types/model/chat-v2/llmInvocationJournal.d.ts +38 -0
  135. package/dist/types/model/chat-v2/llmInvocationPlan.d.ts +41 -0
  136. package/dist/types/model/chat-v2/llmInvocationProjections.d.ts +3 -0
  137. package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +26 -0
  138. package/dist/types/model/chat-v2/llmModelCandidate.d.ts +18 -0
  139. package/dist/types/model/chat-v2/llmProfile.d.ts +7 -0
  140. package/dist/types/model/chat-v2/llmProfileBody.d.ts +20 -0
  141. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +47 -0
  142. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +189 -0
  143. package/dist/types/model/chat-v2/llmProfileTypes.d.ts +1 -1
  144. package/dist/types/model/chat-v2/llmResponseMaterializer.d.ts +20 -0
  145. package/dist/types/model/chat-v2/modelRegistry.d.ts +17 -187
  146. package/dist/types/model/chat-v2/parallelToolCalls.d.ts +3 -1
  147. package/dist/types/model/chat-v2/providerOptions.d.ts +11 -0
  148. package/dist/types/model/chat-v2/rivetToolRegistry.d.ts +11 -0
  149. package/dist/types/model/chat-v2/toolCallCodec.d.ts +7 -0
  150. package/dist/types/model/chat-v2/toolContinuation.d.ts +3 -3
  151. package/dist/types/model/chat-v2/toolHandlerResolver.d.ts +25 -0
  152. package/dist/types/model/chat-v2/toolRoundExecutor.d.ts +18 -0
  153. package/dist/types/model/nodes/AssembleMessageNode.d.ts +2 -1
  154. package/dist/types/model/nodes/ChatNode.d.ts +2 -1
  155. package/dist/types/model/nodes/DelegateFunctionCallNode.d.ts +2 -1
  156. package/dist/types/model/nodes/LLMChatV2Node.d.ts +2 -1
  157. package/dist/types/model/nodes/LLMProfileNode.d.ts +2 -1
  158. package/dist/types/model/nodes/PromptNode.d.ts +6 -3
  159. package/dist/types/model/nodes/ToolNode.d.ts +2 -1
  160. package/dist/types/model/nodes/toolCallDelegation.d.ts +10 -3
  161. package/dist/types/plugins/anthropic/anthropic.d.ts +1 -0
  162. package/dist/types/plugins/google/google.d.ts +14 -9
  163. package/dist/types/plugins/google/nodes/ChatGoogleNode.d.ts +2 -1
  164. package/dist/types/recording/RecordedEvents.d.ts +6 -0
  165. package/dist/types/utils/emitDetached.d.ts +3 -2
  166. package/dist/types/utils/openai.d.ts +49 -0
  167. package/dist/types/webAppRuntime.d.ts +4 -2
  168. 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,140 +46,172 @@ 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
  ? {
69
+ ['tool-name']: {
70
+ type: 'string',
71
+ value: records[0].name,
72
+ },
73
+ ['tool-arguments']: {
74
+ type: 'object',
75
+ value: records[0].arguments,
76
+ },
77
+ ['assistant-message']: preToolMessageOutput,
46
78
  ['output']: {
47
79
  type: 'string',
48
80
  value: records[0].output,
49
81
  },
82
+ ['execution-time']: executionTimeOutput,
50
83
  ['message']: {
51
84
  type: 'chat-message',
52
85
  value: records[0].message,
53
86
  },
54
- ['assistant-message']: preToolMessageOutput,
55
87
  }
56
88
  : {
89
+ ['tool-name']: {
90
+ type: 'string[]',
91
+ value: records.map((record) => record.name),
92
+ },
93
+ ['tool-arguments']: {
94
+ type: 'object[]',
95
+ value: records.map((record) => record.arguments),
96
+ },
97
+ ['assistant-message']: preToolMessageOutput,
57
98
  ['output']: {
58
99
  type: 'string[]',
59
100
  value: records.map((record) => record.output),
60
101
  },
102
+ ['execution-time']: executionTimeOutput,
61
103
  ['message']: {
62
104
  type: 'chat-message[]',
63
105
  value: records.map((record) => record.message),
64
106
  },
65
- ['assistant-message']: preToolMessageOutput,
66
107
  };
67
108
  if (cost != null) {
68
109
  outputs['cost'] = { type: 'number', value: cost };
69
110
  }
70
111
  return outputs;
71
112
  }
72
- export function normalizeFunctionCallInput(input) {
73
- if (Array.isArray(input)) {
74
- if (input.length !== 1) {
75
- 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.`);
76
- }
77
- return normalizeFunctionCallInput(input[0]);
78
- }
79
- if (typeof input !== 'object' || input == null) {
80
- throw new Error('Delegate Tool Call expected a tool call object.');
81
- }
82
- const rawFunctionCall = input;
83
- const name = rawFunctionCall.name;
84
- if (typeof name !== 'string' || name.length === 0) {
85
- throw new Error('Delegate Tool Call expected the tool call to include a name.');
86
- }
87
- const id = typeof rawFunctionCall.id === 'string' ? rawFunctionCall.id : undefined;
88
- const rawArguments = rawFunctionCall.arguments;
89
- if (rawArguments == null) {
90
- return { id, name, arguments: {} };
91
- }
92
- if (typeof rawArguments === 'string') {
93
- try {
94
- const parsedArguments = JSON.parse(rawArguments);
95
- if (typeof parsedArguments === 'object' && parsedArguments != null && !Array.isArray(parsedArguments)) {
96
- return { id, name, arguments: parsedArguments };
97
- }
98
- }
99
- catch {
100
- // Fall through to the explicit error below.
101
- }
102
- 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;
103
143
  }
104
- if (typeof rawArguments === 'object' && !Array.isArray(rawArguments)) {
105
- 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;
106
156
  }
107
- throw new Error(`Delegate Tool Call expected "${name}" arguments to be an object.`);
108
157
  }
109
- function buildToolResultMessage(functionCall, outputString) {
110
- return {
111
- type: 'function',
112
- message: outputString,
113
- name: functionCall.id ?? '',
114
- toolName: functionCall.name,
115
- };
116
- }
117
- 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
+ }
118
163
  return {
119
- delegatedToolCall: true,
120
- name: functionCall.name,
121
- arguments: functionCall.arguments,
122
- id: functionCall.id,
123
- output: outputString,
124
- message: buildToolResultMessage(functionCall, outputString),
164
+ nodeId: node.id,
165
+ processId: context.processId,
166
+ outputPortId: 'output',
125
167
  };
126
168
  }
127
- function stringifyToolOutput(output) {
128
- if (typeof output === 'string') {
129
- return output;
130
- }
131
- return JSON.stringify(output) ?? String(output);
132
- }
133
- export async function delegateToolCall(rawFunctionCall, context, config) {
134
- 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
+ });
135
176
  let handler;
136
- if (config.autoDelegate) {
137
- const graphs = Object.values(context.project.graphs);
138
- const matchingGraph = findAutoDelegateGraphCandidate(graphs, functionCall.name, (graph) => graph.metadata?.name);
139
- if (matchingGraph) {
140
- handler = { key: undefined, value: matchingGraph.metadata.id };
141
- }
142
- }
143
- else {
144
- handler = config.handlers.find((handler) => handler.key === functionCall.name);
145
- }
146
- if (!handler) {
147
- if (config.autoDelegate && config.fallBackToExternalCall) {
148
- const externalFunction = context.externalFunctions[functionCall.name];
149
- if (externalFunction) {
150
- try {
151
- const externalContext = omit(context, ['setGlobal']);
152
- const result = await externalFunction(externalContext, functionCall.arguments ?? {});
153
- 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;
154
199
  return {
155
200
  outputString,
156
- message: buildToolResultMessage(functionCall, outputString),
157
- record: buildDelegatedToolCallRecord(functionCall, outputString),
158
- cost: result.cost,
201
+ message: createToolResultMessage(functionCall, outputString),
202
+ record: createDelegatedToolCallRecord(functionCall, outputString, executionTimeMs),
203
+ traceOutcome: 'passthrough-error',
159
204
  };
160
205
  }
161
- catch (error) {
162
- if (config.passthroughErrors) {
163
- const outputString = `Error: ${getError(error).message}`;
164
- return {
165
- outputString,
166
- message: buildToolResultMessage(functionCall, outputString),
167
- record: buildDelegatedToolCallRecord(functionCall, outputString),
168
- };
169
- }
170
- throw new Error(`External function call failed for ${functionCall.name}: ${getError(error).message}`);
171
- }
206
+ throw new Error(`External function call failed for ${functionCall.name}: ${getError(error).message}`);
172
207
  }
173
208
  }
174
- if (config.unknownHandler) {
175
- handler = { key: undefined, value: config.unknownHandler };
176
- }
177
- 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) {
178
215
  const errorMessage = config.fallBackToExternalCall
179
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.`
180
217
  : `No handler found for tool call: ${functionCall.name}, no graph containing the name "${functionCall.name}" was found.`;
@@ -184,30 +221,76 @@ export async function delegateToolCall(rawFunctionCall, context, config) {
184
221
  throw new Error(`No handler found for tool call: ${functionCall.name}`);
185
222
  }
186
223
  }
187
- const subgraphInputs = {
188
- _function_name: {
189
- type: 'string',
190
- value: functionCall.name,
191
- },
192
- _arguments: {
193
- type: 'object',
194
- 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,
195
243
  },
196
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
+ }
197
251
  for (const [argName, argument] of Object.entries(functionCall.arguments ?? {})) {
252
+ if (RIVET_TOOL_CALL_INPUT_IDS.has(argName)) {
253
+ continue;
254
+ }
198
255
  subgraphInputs[argName] = {
199
256
  type: 'any',
200
257
  value: argument,
201
258
  };
202
259
  }
203
260
  const subprocessor = context.createSubProcessor(handler.value, { signal: context.signal });
261
+ const executionStart = getCurrentTimeMs();
204
262
  const outputs = await subprocessor.processGraph(context, subgraphInputs, context.contextValues);
205
- 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
+ }
206
272
  const cost = coerceTypeOptional(outputs['cost'], 'number');
207
273
  return {
208
274
  outputString,
209
- message: buildToolResultMessage(functionCall, outputString),
210
- record: buildDelegatedToolCallRecord(functionCall, outputString),
275
+ message: createToolResultMessage(functionCall, outputString),
276
+ record: createDelegatedToolCallRecord(functionCall, outputString, executionTimeMs),
211
277
  cost,
212
278
  };
213
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')) {
@@ -338,15 +344,16 @@ export const ChatAnthropicNodeImpl = {
338
344
  return acc;
339
345
  }, '');
340
346
  prompt += '\n\nAssistant:';
341
- // Get the "System" prompt input for Claude 3 models
342
- const system = data.model.startsWith('claude-3') ? getSystemPrompt(inputs) : undefined;
347
+ const useMessageApi = model.startsWith('claude-3') || model.startsWith('claude-sonnet') || model.startsWith('claude-opus');
348
+ const system = useMessageApi ? getSystemPrompt(inputs) : undefined;
343
349
  let { maxTokens } = data;
344
350
  const tokenizerInfo = {
345
351
  node: context.node,
346
352
  model,
347
353
  endpoint: undefined,
348
354
  };
349
- const tokenCountEstimate = await context.tokenizer.getTokenCountForString(prompt, tokenizerInfo);
355
+ const systemText = typeof system === 'string' ? system : system?.map((message) => message.text).join('\n\n');
356
+ const tokenCountEstimate = await context.tokenizer.getTokenCountForString([systemText, prompt].filter(Boolean).join('\n\n'), tokenizerInfo);
350
357
  const modelInfo = anthropicModels[model] ?? {
351
358
  maxTokens: Number.MAX_SAFE_INTEGER,
352
359
  cost: {
@@ -389,11 +396,11 @@ export const ChatAnthropicNodeImpl = {
389
396
  ? tools.map((tool) => ({ name: tool.name, description: tool.description, input_schema: tool.parameters }))
390
397
  : undefined,
391
398
  };
392
- const useMessageApi = model.startsWith('claude-3') || model.startsWith('claude-sonnet') || model.startsWith('claude-opus');
393
399
  const cacheKey = JSON.stringify(useMessageApi ? messageOptions : completionOptions);
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
  }
@@ -618,34 +625,28 @@ export const chatAnthropicNode = pluginNodeDefinition(ChatAnthropicNodeImpl, 'Ch
618
625
  export function getSystemPrompt(inputs) {
619
626
  const systemInput = inputs['system'];
620
627
  const system = coerceTypeOptional(systemInput, 'string');
628
+ const systemMessages = [];
621
629
  if (system) {
622
- return [
623
- {
624
- type: 'text',
625
- text: system,
626
- cache_control: systemInput?.type === 'chat-message'
627
- ? systemInput.value.isCacheBreakpoint
628
- ? { type: 'ephemeral' }
629
- : null
630
- : null,
631
- },
632
- ];
630
+ systemMessages.push({
631
+ type: 'text',
632
+ text: system,
633
+ cache_control: systemInput?.type === 'chat-message'
634
+ ? systemInput.value.isCacheBreakpoint
635
+ ? { type: 'ephemeral' }
636
+ : null
637
+ : null,
638
+ });
633
639
  }
634
- const prompt = inputs['prompt'];
635
- if (prompt && prompt.type === 'chat-message[]') {
636
- const systemMessages = prompt.value.filter((message) => message.type === 'system');
637
- if (systemMessages.length) {
638
- const converted = systemMessages.map((message) => {
639
- return {
640
- type: 'text',
641
- text: coerceType({ type: 'chat-message', value: message }, 'string'),
642
- cache_control: message.isCacheBreakpoint ? { type: 'ephemeral' } : null,
643
- };
640
+ for (const message of coercePromptToChatMessages(inputs['prompt'])) {
641
+ if (message.type === 'system' || message.type === 'developer') {
642
+ systemMessages.push({
643
+ type: 'text',
644
+ text: coerceType({ type: 'chat-message', value: message }, 'string'),
645
+ cache_control: message.isCacheBreakpoint ? { type: 'ephemeral' } : null,
644
646
  });
645
- return converted;
646
647
  }
647
648
  }
648
- return undefined;
649
+ return systemMessages.length > 0 ? systemMessages : undefined;
649
650
  }
650
651
  function getChatMessages(inputs) {
651
652
  const prompt = inputs['prompt'];
@@ -670,7 +671,7 @@ export async function chatMessagesToClaude3ChatMessages(chatMessages) {
670
671
  return combinedMessages;
671
672
  }
672
673
  async function chatMessageToClaude3ChatMessage(message) {
673
- if (message.type === 'system') {
674
+ if (message.type === 'system' || message.type === 'developer') {
674
675
  return undefined;
675
676
  }
676
677
  if (message.type === 'function') {
@@ -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,
@@ -83,6 +79,18 @@ export const generativeAiOptions = Object.entries(generativeAiGoogleModels).map(
83
79
  value: id,
84
80
  label: displayName,
85
81
  }));
82
+ export function getVertexGenerativeModelOptions(options) {
83
+ return {
84
+ model: options.model,
85
+ systemInstruction: options.systemPrompt,
86
+ generationConfig: {
87
+ maxOutputTokens: options.max_output_tokens,
88
+ temperature: options.temperature,
89
+ topP: options.top_p,
90
+ topK: options.top_k,
91
+ },
92
+ };
93
+ }
86
94
  export async function* streamGenerativeAi({ apiKey, model, systemPrompt, prompt, maxOutputTokens, temperature, topP, topK, signal, tools, thinkingBudget, additionalHeaders, }) {
87
95
  const { GoogleGenAI } = await import('@google/genai');
88
96
  const genAi = new GoogleGenAI({ apiKey });
@@ -127,21 +135,20 @@ export async function* streamGenerativeAi({ apiKey, model, systemPrompt, prompt,
127
135
  }
128
136
  }
129
137
  }
130
- export async function* streamChatCompletions({ project, location, applicationCredentials, model, signal, max_output_tokens, temperature, top_p, top_k, prompt, }) {
138
+ export async function* streamChatCompletions({ project, location, applicationCredentials, model, signal, max_output_tokens, temperature, top_p, top_k, systemPrompt, prompt, }) {
131
139
  // Dynamic import: the Google auth library fails under static CJS require.
132
140
  const { VertexAI } = await import('@google-cloud/vertexai');
133
141
  // Can't find a way to pass the credentials path in
134
142
  process.env.GOOGLE_APPLICATION_CREDENTIALS = applicationCredentials;
135
143
  const vertexAi = new VertexAI({ project, location });
136
- const generativeModel = vertexAi.preview.getGenerativeModel({
144
+ const generativeModel = vertexAi.preview.getGenerativeModel(getVertexGenerativeModelOptions({
137
145
  model,
138
- generationConfig: {
139
- maxOutputTokens: max_output_tokens,
140
- temperature,
141
- topP: top_p,
142
- topK: top_k,
143
- },
144
- });
146
+ systemPrompt,
147
+ max_output_tokens,
148
+ temperature,
149
+ top_p,
150
+ top_k,
151
+ }));
145
152
  const response = await generativeModel.generateContentStream({
146
153
  contents: prompt,
147
154
  });