@valerypopoff/rivet2-core 2.1.9 → 2.3.0

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 (188) hide show
  1. package/README.md +1 -1
  2. package/dist/cjs/bundle.cjs +5618 -2533
  3. package/dist/cjs/bundle.cjs.map +4 -4
  4. package/dist/cjs/webAppRuntime.cjs +333 -22
  5. package/dist/cjs/webAppRuntime.cjs.map +4 -4
  6. package/dist/esm/api/createProcessor.js +2 -0
  7. package/dist/esm/exports.js +1 -0
  8. package/dist/esm/integrations/CodeRunner.js +2 -7
  9. package/dist/esm/integrations/CodeRunnerOptions.js +7 -0
  10. package/dist/esm/model/AgentResponseTrace.js +558 -0
  11. package/dist/esm/model/ConnectedToolContinuationHost.js +33 -0
  12. package/dist/esm/model/GraphProcessor.js +165 -74
  13. package/dist/esm/model/NodeImpl.js +6 -0
  14. package/dist/esm/model/ProcessContextBuilder.js +3 -1
  15. package/dist/esm/model/RecordingPlayer.js +212 -25
  16. package/dist/esm/model/SplitRunProcessor.js +49 -8
  17. package/dist/esm/model/SubprocessorBridge.js +3 -0
  18. package/dist/esm/model/ToolCallContinuationCoordinator.js +7 -3
  19. package/dist/esm/model/UiGraph.js +21 -0
  20. package/dist/esm/model/UiGraphActionProtocol.js +3 -0
  21. package/dist/esm/model/UiGraphBrowserRuntime.js +133 -4
  22. package/dist/esm/model/UiGraphRendererStyles.js +221 -0
  23. package/dist/esm/model/UiGraphRuntimeModel.js +9 -3
  24. package/dist/esm/model/UiGraphSchema.js +7 -1
  25. package/dist/esm/model/chat/aiSdkTools.js +3 -2
  26. package/dist/esm/model/chat-v2/aiSdkBridge.js +146 -14
  27. package/dist/esm/model/chat-v2/chatV2CallObserver.js +11 -5
  28. package/dist/esm/model/chat-v2/chatV2CredentialNames.js +93 -0
  29. package/dist/esm/model/chat-v2/chatV2EditorCache.js +47 -20
  30. package/dist/esm/model/chat-v2/chatV2Errors.js +7 -19
  31. package/dist/esm/model/chat-v2/chatV2FeatureCompatibility.js +1 -1
  32. package/dist/esm/model/chat-v2/chatV2Outputs.js +48 -108
  33. package/dist/esm/model/chat-v2/chatV2Pipeline.js +101 -149
  34. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +39 -4
  35. package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +9 -0
  36. package/dist/esm/model/chat-v2/chatV2RequestPlan.js +2 -3
  37. package/dist/esm/model/chat-v2/chatV2ResponseBodyCapture.js +63 -0
  38. package/dist/esm/model/chat-v2/chatV2ResponseFormat.js +8 -4
  39. package/dist/esm/model/chat-v2/chatV2Retry.js +4 -3
  40. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +7 -7
  41. package/dist/esm/model/chat-v2/chatV2Shared.js +1 -1
  42. package/dist/esm/model/chat-v2/chatV2Types.js +20 -8
  43. package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +78 -0
  44. package/dist/esm/model/chat-v2/customProviderApi.js +40 -0
  45. package/dist/esm/model/chat-v2/index.js +15 -0
  46. package/dist/esm/model/chat-v2/llmChatV2Body.js +289 -0
  47. package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +32 -0
  48. package/dist/esm/model/chat-v2/llmChatV2CachePolicy.js +25 -0
  49. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +13 -50
  50. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +117 -24
  51. package/dist/esm/model/chat-v2/llmChatV2NodeMigration.js +24 -0
  52. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +150 -199
  53. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +60 -0
  54. package/dist/esm/model/chat-v2/llmInvocationDecision.js +11 -0
  55. package/dist/esm/model/chat-v2/llmInvocationJournal.js +43 -0
  56. package/dist/esm/model/chat-v2/llmInvocationPlan.js +68 -0
  57. package/dist/esm/model/chat-v2/llmInvocationProjections.js +5 -0
  58. package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +48 -0
  59. package/dist/esm/model/chat-v2/llmModelCandidate.js +79 -0
  60. package/dist/esm/model/chat-v2/llmProfile.js +52 -65
  61. package/dist/esm/model/chat-v2/llmProfileBody.js +193 -0
  62. package/dist/esm/model/chat-v2/llmProfileFallback.js +442 -100
  63. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +74 -0
  64. package/dist/esm/model/chat-v2/llmProfileHealthStore.js +326 -0
  65. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +55 -33
  66. package/dist/esm/model/chat-v2/llmProfileTypes.js +1 -18
  67. package/dist/esm/model/chat-v2/llmResponseMaterializer.js +42 -0
  68. package/dist/esm/model/chat-v2/modelRegistry.js +54 -4
  69. package/dist/esm/model/chat-v2/parallelToolCalls.js +9 -2
  70. package/dist/esm/model/chat-v2/providerOptions.js +116 -24
  71. package/dist/esm/model/chat-v2/rivetToolRegistry.js +9 -0
  72. package/dist/esm/model/chat-v2/toolCallCodec.js +52 -0
  73. package/dist/esm/model/chat-v2/toolContinuation.js +72 -35
  74. package/dist/esm/model/chat-v2/toolHandlerResolver.js +23 -0
  75. package/dist/esm/model/chat-v2/toolRoundExecutor.js +12 -0
  76. package/dist/esm/model/nodes/ChatNode.js +6 -0
  77. package/dist/esm/model/nodes/ChatNodeBase.js +1 -0
  78. package/dist/esm/model/nodes/CodeNewNode.js +5 -47
  79. package/dist/esm/model/nodes/CodeNode.js +4 -46
  80. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +19 -6
  81. package/dist/esm/model/nodes/ExpressionNode.js +5 -8
  82. package/dist/esm/model/nodes/LLMChatV2Node.js +121 -229
  83. package/dist/esm/model/nodes/LLMProfileNode.js +27 -8
  84. package/dist/esm/model/nodes/MatchNode.js +86 -41
  85. package/dist/esm/model/nodes/PromptNode.js +7 -0
  86. package/dist/esm/model/nodes/ToolNode.js +7 -0
  87. package/dist/esm/model/nodes/toolCallDelegation.js +177 -110
  88. package/dist/esm/plugins/anthropic/anthropic.js +4 -4
  89. package/dist/esm/plugins/anthropic/nodes/ChatAnthropicNode.js +7 -0
  90. package/dist/esm/plugins/gentrace/gentraceSdk.js +0 -1
  91. package/dist/esm/plugins/gentrace/index.js +0 -1
  92. package/dist/esm/plugins/gentrace/plugin.js +61 -179
  93. package/dist/esm/plugins/google/google.js +5 -9
  94. package/dist/esm/plugins/google/nodes/ChatGoogleNode.js +4 -1
  95. package/dist/esm/plugins.js +1 -2
  96. package/dist/esm/recording/ExecutionRecorder.js +62 -13
  97. package/dist/esm/utils/emitDetached.js +6 -3
  98. package/dist/esm/utils/openai.js +60 -16
  99. package/dist/esm/utils/serialization/serialization.js +2 -19
  100. package/dist/esm/webAppRuntime.js +3 -2
  101. package/dist/types/api/createProcessor.d.ts +3 -0
  102. package/dist/types/exports.d.ts +1 -0
  103. package/dist/types/integrations/CodeRunner.d.ts +10 -7
  104. package/dist/types/integrations/CodeRunnerOptions.d.ts +15 -0
  105. package/dist/types/model/AgentResponseTrace.d.ts +123 -0
  106. package/dist/types/model/ConnectedToolContinuationHost.d.ts +34 -0
  107. package/dist/types/model/EditorDefinition.d.ts +16 -0
  108. package/dist/types/model/ExecutorProtocol.d.ts +32 -11
  109. package/dist/types/model/GraphProcessor.d.ts +41 -9
  110. package/dist/types/model/NodeBase.d.ts +0 -10
  111. package/dist/types/model/NodeImpl.d.ts +18 -1
  112. package/dist/types/model/Nodes.d.ts +2 -2
  113. package/dist/types/model/ProcessContext.d.ts +99 -0
  114. package/dist/types/model/ProcessContextBuilder.d.ts +3 -1
  115. package/dist/types/model/RecordingPlayer.d.ts +6 -0
  116. package/dist/types/model/SplitRunProcessor.d.ts +10 -3
  117. package/dist/types/model/UiGraph.d.ts +8 -0
  118. package/dist/types/model/UiGraphActionProtocol.d.ts +3 -0
  119. package/dist/types/model/UiGraphBrowserRuntime.d.ts +11 -2
  120. package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
  121. package/dist/types/model/UiGraphRuntimeModel.d.ts +2 -0
  122. package/dist/types/model/UiGraphSchema.d.ts +1 -0
  123. package/dist/types/model/chat-v2/chatV2CallObserver.d.ts +2 -0
  124. package/dist/types/model/chat-v2/chatV2CredentialNames.d.ts +30 -0
  125. package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +2 -3
  126. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +6 -16
  127. package/dist/types/model/chat-v2/chatV2Pipeline.d.ts +13 -17
  128. package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +7 -0
  129. package/dist/types/model/chat-v2/chatV2ProviderRegistry.d.ts +8 -0
  130. package/dist/types/model/chat-v2/chatV2RequestPlan.d.ts +2 -2
  131. package/dist/types/model/chat-v2/chatV2ResponseBodyCapture.d.ts +25 -0
  132. package/dist/types/model/chat-v2/chatV2ResponseFormat.d.ts +3 -2
  133. package/dist/types/model/chat-v2/chatV2Retry.d.ts +2 -0
  134. package/dist/types/model/chat-v2/chatV2RuntimeOptions.d.ts +3 -8
  135. package/dist/types/model/chat-v2/chatV2Types.d.ts +44 -10
  136. package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +14 -0
  137. package/dist/types/model/chat-v2/customProviderApi.d.ts +22 -0
  138. package/dist/types/model/chat-v2/index.d.ts +15 -0
  139. package/dist/types/model/chat-v2/llmChatV2Body.d.ts +24 -0
  140. package/dist/types/model/chat-v2/llmChatV2CacheBoundary.d.ts +10 -0
  141. package/dist/types/model/chat-v2/llmChatV2CachePolicy.d.ts +13 -0
  142. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +19 -3
  143. package/dist/types/model/chat-v2/llmChatV2NodeMigration.d.ts +8 -0
  144. package/dist/types/model/chat-v2/llmChatV2NodeRuntime.d.ts +14 -16
  145. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +16 -0
  146. package/dist/types/model/chat-v2/llmInvocationDecision.d.ts +21 -0
  147. package/dist/types/model/chat-v2/llmInvocationJournal.d.ts +38 -0
  148. package/dist/types/model/chat-v2/llmInvocationPlan.d.ts +41 -0
  149. package/dist/types/model/chat-v2/llmInvocationProjections.d.ts +3 -0
  150. package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +26 -0
  151. package/dist/types/model/chat-v2/llmModelCandidate.d.ts +20 -0
  152. package/dist/types/model/chat-v2/llmProfile.d.ts +14 -0
  153. package/dist/types/model/chat-v2/llmProfileBody.d.ts +20 -0
  154. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +36 -49
  155. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +209 -0
  156. package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +111 -0
  157. package/dist/types/model/chat-v2/llmProfileNodeRuntime.d.ts +1 -1
  158. package/dist/types/model/chat-v2/llmProfileTypes.d.ts +4 -1
  159. package/dist/types/model/chat-v2/llmResponseMaterializer.d.ts +20 -0
  160. package/dist/types/model/chat-v2/modelRegistry.d.ts +17 -187
  161. package/dist/types/model/chat-v2/parallelToolCalls.d.ts +3 -1
  162. package/dist/types/model/chat-v2/providerOptions.d.ts +12 -0
  163. package/dist/types/model/chat-v2/rivetToolRegistry.d.ts +11 -0
  164. package/dist/types/model/chat-v2/toolCallCodec.d.ts +7 -0
  165. package/dist/types/model/chat-v2/toolContinuation.d.ts +3 -3
  166. package/dist/types/model/chat-v2/toolHandlerResolver.d.ts +25 -0
  167. package/dist/types/model/chat-v2/toolRoundExecutor.d.ts +18 -0
  168. package/dist/types/model/nodes/ChatNode.d.ts +2 -1
  169. package/dist/types/model/nodes/CodeNewNode.d.ts +0 -5
  170. package/dist/types/model/nodes/CodeNode.d.ts +0 -5
  171. package/dist/types/model/nodes/DelegateFunctionCallNode.d.ts +2 -1
  172. package/dist/types/model/nodes/LLMChatV2Node.d.ts +2 -1
  173. package/dist/types/model/nodes/LLMProfileNode.d.ts +2 -1
  174. package/dist/types/model/nodes/MatchNode.d.ts +6 -0
  175. package/dist/types/model/nodes/PromptNode.d.ts +4 -1
  176. package/dist/types/model/nodes/ToolNode.d.ts +2 -1
  177. package/dist/types/model/nodes/toolCallDelegation.d.ts +10 -3
  178. package/dist/types/plugins/anthropic/anthropic.d.ts +1 -0
  179. package/dist/types/plugins/gentrace/gentraceSdk.d.ts +0 -1
  180. package/dist/types/plugins/gentrace/plugin.d.ts +55 -9
  181. package/dist/types/plugins/google/google.d.ts +2 -8
  182. package/dist/types/plugins.d.ts +1 -1
  183. package/dist/types/recording/ExecutionRecorder.d.ts +7 -1
  184. package/dist/types/recording/RecordedEvents.d.ts +6 -0
  185. package/dist/types/utils/emitDetached.d.ts +3 -2
  186. package/dist/types/utils/openai.d.ts +49 -0
  187. package/dist/types/webAppRuntime.d.ts +4 -2
  188. package/package.json +2 -2
@@ -1,273 +1,224 @@
1
- import { coerceTypeOptional } from '../../utils/coerceType.js';
2
- import { cleanHeaders, getInputOrData } from '../../utils/inputs.js';
3
- import { coercePromptToChatMessages, prependSystemPrompt } from '../chat/chatMessages.js';
4
- import { getInstructionMessageRoles, restoreOpenAICompatibleInstructionRoles } from './developerMessageRoles.js';
5
- import { createChatV2ResponseOutput, mergeCustomProviderResponseFormatOptions, resolveChatV2ResponseFormatParameters, } from './chatV2ResponseFormat.js';
6
- import { hasLLMChatV2ToolResponseFormatConflict, LLM_CHAT_V2_TOOL_RESPONSE_FORMAT_CONFLICT_COPY, } from './chatV2FeatureCompatibility.js';
7
- import { createLLMProfileFallbackRunner } from './llmProfileFallback.js';
8
- import { applyLLMProfileToNodeData, normalizeLLMProfileChainInput } from './llmProfile.js';
9
- import { parseChatV2Provider, resolveChatV2ProviderConfig } from './providerOptions.js';
10
- import { createResolvedChatV2Provider, resolveChatV2Credential } from './chatV2ProviderProfile.js';
11
- import { shouldOutputChatV2RequestBody, shouldOutputChatV2RequestError, } from './chatV2Types.js';
1
+ import { cleanHeaders } from '../../utils/inputs.js';
2
+ import { createLLMProfileFallbackRunner, getLLMAttemptErrorMessage } from './llmProfileFallback.js';
3
+ import { applyLLMProfileToNodeData, normalizeLLMProfileChainInput, scopeLLMProfileHealthIdentity, } from './llmProfile.js';
4
+ import { buildLLMInvocationPlan, buildLLMInvocationRunOptions } from './llmInvocationPlan.js';
5
+ import { resolveLLMModelCandidate } from './llmModelCandidate.js';
6
+ import { mergeCustomProviderResponseFormatOptions } from './chatV2ResponseFormat.js';
7
+ import { getLLMChatV2EditorCacheEligibility } from './llmChatV2CachePolicy.js';
8
+ import { parseChatV2Provider } from './providerOptions.js';
9
+ import { parseCustomProviderApi } from './customProviderApi.js';
12
10
  import { buildLLMChatV2EditorCacheKey, cloneLLMChatV2EditorCacheOutputs, resolveLLMChatV2EditorCache, } from './chatV2EditorCache.js';
13
- import { resolveLLMChatV2BuiltInTools, resolveLLMChatV2GenerationParameters, resolveLLMChatV2Headers, resolveLLMChatV2RuntimeProviderOptions, resolveLLMChatV2ToolChoice, } from './chatV2RuntimeOptions.js';
14
- import { shouldIncludeLLMChatV2ToolCalls, } from './llmChatV2NodeData.js';
15
- import { runChatV2Pipeline } from './chatV2Pipeline.js';
11
+ import { resolveLLMChatV2GenerationParameters, resolveLLMChatV2RuntimeProviderOptions, } from './chatV2RuntimeOptions.js';
12
+ import {} from './llmChatV2NodeData.js';
13
+ import { isChatV2ResponseValidationError, runChatV2Pipeline } from './chatV2Pipeline.js';
14
+ import { DEFAULT_LLM_PROFILE_FIRST_OUTPUT_TIMEOUT_MS, DEFAULT_LLM_PROFILE_STREAM_INACTIVITY_TIMEOUT_MS, resolveRivetLLMProfileCircuitBreakerPolicy, } from './llmProfileHealthStore.js';
16
15
  export { buildLLMChatV2EditorCacheKey, cloneLLMChatV2EditorCacheOutputs };
17
16
  export { resolveLLMChatV2RuntimeProviderOptions } from './chatV2RuntimeOptions.js';
18
- function resolveLLMChatV2BaseURL(data, inputs) {
19
- return data.provider === 'custom'
20
- ? getInputOrData(data, inputs, 'customProviderBaseURL', 'string', 'useCustomProviderBaseURLInput')?.trim() ||
21
- undefined
22
- : undefined;
23
- }
24
- function createSharedRunOptions(params) {
25
- const { shared, provider, modelId } = params;
26
- return {
27
- provider,
28
- // From profile mode replaces this before a provider request. Keeping the
29
- // field populated preserves the established Tool Continuation contract.
30
- model: undefined,
31
- modelId,
32
- prompt: shared.prompt,
33
- systemPrompt: shared.systemPrompt,
34
- functions: shared.functions,
35
- responseOutput: createChatV2ResponseOutput(shared.responseFormatParameters, provider),
36
- responseFormat: shared.responseFormatParameters?.responseFormat,
37
- outputUsage: shared.data.outputUsage,
38
- outputReasoning: shared.data.outputReasoning,
39
- outputRequestStatus: shared.data.outputRequestStatus,
40
- outputRequestError: shouldOutputChatV2RequestError(shared.data),
41
- outputRequestBody: shouldOutputChatV2RequestBody(shared.data),
42
- includeFunctionCalls: shouldIncludeLLMChatV2ToolCalls(shared.data),
43
- emitPartialOutputs: shared.data.useAsGraphPartialOutput,
44
- toolChoice: shared.toolChoice,
45
- requestBodies: shared.requestBodies,
46
- retryOnNon200: shared.data.retryOnNon200,
47
- retryOnNon200RepeatTimes: shared.data.retryOnNon200RepeatTimes,
48
- retryOnNon200CooldownMs: shared.data.retryOnNon200CooldownMs,
49
- context: shared.context,
50
- };
51
- }
52
- function createRuntimeProviderProfile(params) {
53
- const provider = parseChatV2Provider(params.data.provider);
54
- return {
55
- provider,
56
- modelId: getInputOrData(params.data, params.inputs, 'model', 'string'),
57
- baseURL: resolveLLMChatV2BaseURL(params.data, params.inputs),
58
- hasCustomHeaders: Object.keys(resolveLLMChatV2Headers(params.data, params.inputs) ?? {}).length > 0,
59
- credential: params.credential.reference,
60
- capabilities: {
61
- builtInTools: provider === 'openai' || provider === 'google',
62
- structuredOutput: true,
63
- },
64
- };
65
- }
66
- async function resolveCandidateRunOptions(params) {
67
- const { shared, profile, roundOptions } = params;
68
- const effectiveData = profile ? applyLLMProfileToNodeData(shared.data, profile) : shared.data;
69
- if (hasLLMChatV2ToolResponseFormatConflict(effectiveData)) {
70
- throw new Error(LLM_CHAT_V2_TOOL_RESPONSE_FORMAT_CONFLICT_COPY.paragraphs[0]);
71
- }
72
- const provider = parseChatV2Provider(effectiveData.provider);
73
- const modelId = getInputOrData(effectiveData, shared.inputs, 'model', 'string');
74
- const baseURL = resolveLLMChatV2BaseURL(effectiveData, shared.inputs);
75
- const headers = resolveLLMChatV2Headers(effectiveData, shared.inputs);
76
- const credential = profile?.credential ??
77
- resolveChatV2Credential({
78
- provider,
79
- context: shared.context,
80
- apiKeySource: effectiveData.apiKeySource === 'input' ? 'input' : 'configured',
81
- inputs: shared.inputs,
82
- customProgrammaticName: effectiveData.customProviderApiKeyProgrammaticName,
83
- customEnvironmentName: effectiveData.customProviderApiKeyEnvVarName,
84
- });
85
- const transformRequestBody = (provider === 'openai' || provider === 'custom') && shared.instructionRoles.includes('developer')
86
- ? (body) => restoreOpenAICompatibleInstructionRoles(body, shared.instructionRoles)
87
- : undefined;
88
- const resolvedProvider = await createResolvedChatV2Provider({
89
- provider,
90
- modelId,
91
- context: shared.context,
92
- baseURL,
93
- headers,
94
- credential,
95
- onRequestBody: shared.requestBodies == null ? undefined : (body) => shared.requestBodies.push(body),
96
- transformRequestBody,
97
- });
98
- const generationParameters = resolveLLMChatV2GenerationParameters(effectiveData, shared.inputs);
99
- const providerOptions = mergeCustomProviderResponseFormatOptions(provider, resolveLLMChatV2RuntimeProviderOptions(effectiveData, shared.inputs), shared.responseFormatParameters);
100
- return {
101
- ...roundOptions,
102
- provider,
103
- model: resolvedProvider.model,
104
- modelId,
105
- additionalTools: resolveLLMChatV2BuiltInTools(effectiveData, shared.context, resolvedProvider.config, credential.value),
106
- ...generationParameters,
107
- responseOutput: createChatV2ResponseOutput(shared.responseFormatParameters, provider),
108
- responseFormat: shared.responseFormatParameters?.responseFormat,
109
- providerOptions,
110
- anthropicCacheControlTtl: provider === 'anthropic' ? effectiveData.anthropicCacheControlTtl || undefined : undefined,
111
- requestBodies: shared.requestBodies,
112
- };
113
- }
114
- function createSharedRuntimeValues(params) {
115
- const { data, inputs, context } = params;
116
- const prompt = inputs['prompt'];
117
- const systemPrompt = inputs['systemPrompt'];
118
- return {
119
- data,
120
- inputs,
121
- context,
122
- prompt,
123
- systemPrompt,
124
- functions: data.useToolCalling && inputs['functions'] != null
125
- ? coerceTypeOptional(inputs['functions'], 'gpt-function[]')
126
- : undefined,
127
- responseFormatParameters: resolveChatV2ResponseFormatParameters(data, inputs),
128
- toolChoice: resolveLLMChatV2ToolChoice(data),
129
- requestBodies: shouldOutputChatV2RequestBody(data) ? [] : undefined,
130
- instructionRoles: getInstructionMessageRoles(prependSystemPrompt(coercePromptToChatMessages(prompt), systemPrompt)),
131
- };
132
- }
133
17
  export async function resolveLLMChatV2RuntimeConfig(params) {
134
18
  const { data, nodeId, inputs, context } = params;
135
19
  const profileInput = inputs['llmProfile'];
136
20
  if (data.configurationMode === 'profile' && profileInput == null) {
137
21
  throw new Error('LLM Profile input is required when Configuration is From profile.');
138
22
  }
139
- const shared = createSharedRuntimeValues({ data, inputs, context });
140
- const editorCache = data.cache ? context.editorExecutionCache : undefined;
23
+ const plan = buildLLMInvocationPlan({ data, inputs, context });
141
24
  if (data.configurationMode !== 'profile') {
142
- const inlineRunOptions = await resolveCandidateRunOptions({
143
- shared,
25
+ // The editor cache cannot faithfully replay tool handlers, connected
26
+ // Delegate runs, provider-native tools, or their side effects. A legacy
27
+ // cache-enabled node therefore remains cacheable only for ordinary model
28
+ // calls without tool use.
29
+ const editorCache = getEligibleEditorCache(data, context);
30
+ const inlineCandidate = await resolveLLMModelCandidate({
31
+ plan,
144
32
  profile: undefined,
145
- roundOptions: createSharedRunOptions({
146
- shared,
33
+ roundOptions: buildLLMInvocationRunOptions({
34
+ plan,
147
35
  provider: parseChatV2Provider(data.provider),
148
36
  modelId: data.model,
149
37
  }),
150
38
  });
39
+ const inlineRunOptions = inlineCandidate.runOptions;
151
40
  const generationParameters = resolveLLMChatV2GenerationParameters(data, inputs);
152
- const inlineCredential = resolveChatV2Credential({
153
- provider: inlineRunOptions.provider,
154
- context,
155
- apiKeySource: data.apiKeySource === 'input' ? 'input' : 'configured',
156
- inputs,
157
- customProgrammaticName: data.customProviderApiKeyProgrammaticName,
158
- customEnvironmentName: data.customProviderApiKeyEnvVarName,
159
- });
160
- const inlineProviderConfig = await resolveChatV2ProviderConfig(inlineRunOptions.provider, inlineRunOptions.modelId, context, {
161
- baseURL: resolveLLMChatV2BaseURL(data, inputs),
162
- headers: resolveLLMChatV2Headers(data, inputs),
163
- });
164
41
  const { cacheKey, cachedOutputs } = resolveLLMChatV2EditorCache({
165
- apiKey: inlineCredential.value,
42
+ apiKey: inlineCandidate.credential.value,
166
43
  data,
167
44
  editorCache,
168
- functions: shared.functions,
45
+ functions: plan.functions,
169
46
  generationParameters,
170
47
  modelId: inlineRunOptions.modelId,
171
48
  nodeId,
172
- prompt: shared.prompt,
49
+ prompt: plan.prompt,
173
50
  provider: inlineRunOptions.provider,
174
- providerConfig: inlineProviderConfig,
51
+ providerConfig: inlineCandidate.providerConfig,
175
52
  providerOptions: inlineRunOptions.providerOptions,
176
- responseFormatParameters: shared.responseFormatParameters,
177
- systemPrompt: shared.systemPrompt,
178
- toolChoice: shared.toolChoice,
53
+ requestBodyOverlay: inlineCandidate.requestBodyOverlay,
54
+ responseFormatParameters: plan.responseFormatParameters,
55
+ systemPrompt: plan.systemPrompt,
56
+ toolChoice: plan.toolChoice,
179
57
  });
180
58
  return {
181
59
  runOptions: inlineRunOptions,
182
- providerProfile: createRuntimeProviderProfile({
183
- data,
184
- inputs,
185
- credential: inlineCredential,
186
- }),
187
- runPipeline: runChatV2Pipeline,
188
- functions: shared.functions,
60
+ runPipeline: async (roundOptions) => {
61
+ try {
62
+ return await runChatV2Pipeline({
63
+ ...roundOptions,
64
+ model: inlineRunOptions.model,
65
+ onProviderAttempt: (attempt) => {
66
+ try {
67
+ roundOptions.onProviderAttempt?.(attempt);
68
+ }
69
+ catch {
70
+ // A caller-owned observer must not affect the physical request.
71
+ }
72
+ try {
73
+ params.onLLMAttempt?.({
74
+ roundIndex: roundOptions.roundIndex ?? 0,
75
+ provider: inlineRunOptions.provider,
76
+ model: inlineRunOptions.modelId,
77
+ ...(inlineRunOptions.customProviderApi == null
78
+ ? {}
79
+ : { customProviderApi: inlineRunOptions.customProviderApi }),
80
+ stage: 'request',
81
+ outcome: attempt.outcome === 'success' ? 'success' : attempt.outcome === 'aborted' ? 'aborted' : 'failure',
82
+ attemptIndex: attempt.attemptIndex,
83
+ ...(attempt.status == null ? {} : { status: attempt.status }),
84
+ ...(attempt.error == null ? {} : { error: getLLMAttemptErrorMessage(attempt.error) }),
85
+ });
86
+ }
87
+ catch {
88
+ // Diagnostics must never affect a model invocation.
89
+ }
90
+ },
91
+ });
92
+ }
93
+ catch (error) {
94
+ if (isChatV2ResponseValidationError(error)) {
95
+ try {
96
+ params.onLLMAttempt?.({
97
+ roundIndex: roundOptions.roundIndex ?? 0,
98
+ provider: inlineRunOptions.provider,
99
+ model: inlineRunOptions.modelId,
100
+ ...(inlineRunOptions.customProviderApi == null
101
+ ? {}
102
+ : { customProviderApi: inlineRunOptions.customProviderApi }),
103
+ stage: 'response-validation',
104
+ outcome: 'failure',
105
+ error: getLLMAttemptErrorMessage(error),
106
+ });
107
+ }
108
+ catch {
109
+ // Diagnostics must never affect a model invocation.
110
+ }
111
+ }
112
+ throw error;
113
+ }
114
+ },
115
+ functions: plan.functions,
189
116
  cacheKey,
190
117
  cachedOutputs,
191
118
  editorCache,
192
119
  shouldAutoContinueToolCalls: !!data.autoContinueToolCalls && data.useToolCalling,
193
120
  maxToolRounds: data.maxToolRounds ?? 3,
194
- profileAttempts: undefined,
195
- profileChainUsesArray: false,
196
- profileChainLength: undefined,
121
+ outputLLMAttempts: data.outputLLMAttempts === true,
197
122
  getProfileSummary: undefined,
198
123
  isProfileFallbackExhausted: () => false,
199
124
  };
200
125
  }
201
- const profiles = normalizeLLMProfileChainInput(profileInput?.value);
126
+ const profiles = normalizeLLMProfileChainInput(profileInput?.value).map((profile) => profile.configuration.enableCircuitBreaker !== true
127
+ ? profile
128
+ : scopeLLMProfileHealthIdentity(profile, {
129
+ projectId: context.project.metadata.id,
130
+ profileNodeId: nodeId,
131
+ chatNodeHeaders: context.settings.chatNodeHeaders,
132
+ }));
133
+ // Profile-owned provider-native capabilities are resolved only after the
134
+ // input profile is normalized. One cache entry covers the complete fallback
135
+ // chain, so every possible candidate must be replay-safe.
136
+ const editorCache = profiles.every((profile) => getLLMChatV2EditorCacheEligibility({ ...data, ...profile.configuration }).eligible)
137
+ ? context.editorExecutionCache
138
+ : undefined;
202
139
  const firstProfile = profiles[0];
203
140
  const firstProvider = parseChatV2Provider(firstProfile.configuration.provider);
204
- const profileRunOptions = createSharedRunOptions({
205
- shared,
206
- provider: firstProvider,
207
- modelId: firstProfile.configuration.model,
208
- });
141
+ // The fallback runner resolves a real model before every physical request.
142
+ // This is deliberately a provider-neutral round template, never a fake
143
+ // executable model state.
144
+ const profileRunOptions = {
145
+ ...buildLLMInvocationRunOptions({
146
+ plan,
147
+ provider: firstProvider,
148
+ modelId: firstProfile.configuration.model,
149
+ }),
150
+ };
209
151
  const firstProfileData = applyLLMProfileToNodeData(data, firstProfile);
210
152
  Object.assign(profileRunOptions, {
211
153
  ...resolveLLMChatV2GenerationParameters(firstProfileData, inputs),
212
- providerOptions: mergeCustomProviderResponseFormatOptions(firstProvider, resolveLLMChatV2RuntimeProviderOptions(firstProfileData, inputs), shared.responseFormatParameters),
154
+ providerOptions: mergeCustomProviderResponseFormatOptions(firstProvider, resolveLLMChatV2RuntimeProviderOptions(firstProfileData, inputs), plan.responseFormatParameters, firstProfileData.customProviderApi),
213
155
  anthropicCacheControlTtl: firstProvider === 'anthropic' ? firstProfileData.anthropicCacheControlTtl || undefined : undefined,
214
156
  });
215
157
  const fallbackRunner = createLLMProfileFallbackRunner({
216
- candidates: profiles.map((profile) => ({
217
- provider: parseChatV2Provider(profile.configuration.provider),
218
- model: profile.configuration.model,
219
- credential: profile.credential.value,
220
- redactionValues: [
221
- ...profile.configuration.headers.map((header) => header.value),
222
- ...Object.values(cleanHeaders(context.settings?.chatNodeHeaders ?? {})),
223
- ],
224
- })),
225
- resolveCandidate: (profileIndex, roundOptions) => resolveCandidateRunOptions({
226
- shared,
158
+ candidates: profiles.map((profile) => {
159
+ const policy = resolveRivetLLMProfileCircuitBreakerPolicy(profile.configuration);
160
+ return {
161
+ provider: parseChatV2Provider(profile.configuration.provider),
162
+ model: profile.configuration.model,
163
+ ...(profile.configuration.provider === 'custom'
164
+ ? { customProviderApi: parseCustomProviderApi(profile.configuration.customProviderApi) }
165
+ : {}),
166
+ ...(policy == null
167
+ ? {}
168
+ : {
169
+ health: {
170
+ identity: profile.healthIdentity,
171
+ policy,
172
+ firstOutputTimeoutMs: profile.configuration.firstOutputTimeoutMs ?? DEFAULT_LLM_PROFILE_FIRST_OUTPUT_TIMEOUT_MS,
173
+ streamInactivityTimeoutMs: profile.configuration.streamInactivityTimeoutMs ?? DEFAULT_LLM_PROFILE_STREAM_INACTIVITY_TIMEOUT_MS,
174
+ },
175
+ }),
176
+ };
177
+ }),
178
+ resolveCandidate: (profileIndex, roundOptions) => resolveLLMModelCandidate({
179
+ plan,
227
180
  profile: profiles[profileIndex],
228
181
  roundOptions,
229
- }),
182
+ }).then((candidate) => candidate.runOptions),
183
+ onAttempt: params.onLLMAttempt,
184
+ healthStore: context.llmProfileHealthStore,
230
185
  });
231
186
  const { cacheKey, cachedOutputs } = resolveLLMChatV2EditorCache({
232
187
  apiKey: undefined,
233
188
  data: firstProfileData,
234
189
  editorCache,
235
- functions: shared.functions,
190
+ functions: plan.functions,
236
191
  generationParameters: undefined,
237
192
  modelId: firstProfile.configuration.model,
238
193
  nodeId,
239
- prompt: shared.prompt,
194
+ prompt: plan.prompt,
240
195
  provider: firstProvider,
241
196
  // Profile headers are part of the individual profile fingerprints, but
242
197
  // provider resolution also merges project-wide Chat headers. Include those
243
- // values through the existing redacted provider-config fingerprint so a
198
+ // values through the normalized provider-config fingerprint so a
244
199
  // global-header edit cannot reuse a stale profile-mode editor cache entry.
245
200
  providerConfig: { headers: cleanHeaders(context.settings?.chatNodeHeaders ?? {}) },
246
201
  providerOptions: undefined,
247
- responseFormatParameters: shared.responseFormatParameters,
248
- systemPrompt: shared.systemPrompt,
249
- toolChoice: shared.toolChoice,
202
+ requestBodyOverlay: undefined,
203
+ responseFormatParameters: plan.responseFormatParameters,
204
+ systemPrompt: plan.systemPrompt,
205
+ toolChoice: plan.toolChoice,
250
206
  profileChain: profiles,
251
- profileChainUsesArray: Array.isArray(profileInput?.value),
252
207
  });
253
208
  return {
254
209
  runOptions: profileRunOptions,
255
- providerProfile: createRuntimeProviderProfile({
256
- data: firstProfileData,
257
- inputs,
258
- credential: firstProfile.credential,
259
- }),
260
210
  runPipeline: fallbackRunner.run,
261
- functions: shared.functions,
211
+ functions: plan.functions,
262
212
  cacheKey,
263
213
  cachedOutputs,
264
214
  editorCache,
265
215
  shouldAutoContinueToolCalls: !!data.autoContinueToolCalls && data.useToolCalling,
266
216
  maxToolRounds: data.maxToolRounds ?? 3,
267
- profileAttempts: fallbackRunner.attempts,
268
- profileChainUsesArray: Array.isArray(profileInput?.value),
269
- profileChainLength: profiles.length,
217
+ outputLLMAttempts: data.outputLLMAttempts === true,
270
218
  getProfileSummary: fallbackRunner.summary,
271
219
  isProfileFallbackExhausted: fallbackRunner.wasExhausted,
272
220
  };
273
221
  }
222
+ function getEligibleEditorCache(data, context) {
223
+ return getLLMChatV2EditorCacheEligibility(data).eligible ? context.editorExecutionCache : undefined;
224
+ }
@@ -0,0 +1,60 @@
1
+ import { delegateToolCall } from '../nodes/toolCallDelegation.js';
2
+ import { runChatV2PipelineWithToolContinuation } from './toolContinuation.js';
3
+ import { isChatV2PipelineProviderFailureResult } from './chatV2Pipeline.js';
4
+ /**
5
+ * Owns the LLM-level recovery and continuation decision boundary. The node
6
+ * boundary provides a resolved runtime and GraphProcessor supplies only the
7
+ * connected Delegate host; no graph scheduling policy lives here.
8
+ */
9
+ export async function executeLLMInvocation(params) {
10
+ const { context, journal, runtime, toolCallContinuation } = params;
11
+ try {
12
+ const result = runtime.shouldAutoContinueToolCalls
13
+ ? await runChatV2PipelineWithToolContinuation({
14
+ ...runtime.runOptions,
15
+ autoContinue: true,
16
+ maxToolRounds: runtime.maxToolRounds,
17
+ functions: runtime.functions,
18
+ delegateToolCallRound: toolCallContinuation
19
+ ? async (toolCalls, preToolMessage) => {
20
+ const results = await toolCallContinuation.run(toolCalls, preToolMessage);
21
+ journal.recordToolRound({ kind: 'connected', count: results.length });
22
+ return results.map((entry) => ({
23
+ type: 'chat-message',
24
+ value: entry.message,
25
+ delegatedToolCall: entry.record,
26
+ }));
27
+ }
28
+ : undefined,
29
+ delegateToolCall: async (toolCall) => {
30
+ const delegated = await delegateToolCall(toolCall, context, {
31
+ handlers: [],
32
+ unknownHandler: undefined,
33
+ autoDelegate: true,
34
+ fallBackToExternalCall: true,
35
+ passthroughErrors: true,
36
+ });
37
+ journal.recordToolRound({ kind: 'internal', count: 1 });
38
+ return {
39
+ type: 'chat-message',
40
+ value: delegated.message,
41
+ delegatedToolCall: delegated.record,
42
+ };
43
+ },
44
+ runPipeline: runtime.runPipeline,
45
+ })
46
+ : await runtime.runPipeline(runtime.runOptions);
47
+ journal.recordTerminal({
48
+ kind: isChatV2PipelineProviderFailureResult(result)
49
+ ? 'failed'
50
+ : result.functionCalls.length > 0
51
+ ? 'released-unresolved-calls'
52
+ : 'final-model-answer',
53
+ });
54
+ return result;
55
+ }
56
+ catch (error) {
57
+ journal.recordTerminal({ kind: context.signal.aborted ? 'cancelled' : 'failed' });
58
+ throw error;
59
+ }
60
+ }
@@ -0,0 +1,11 @@
1
+ /** Pure terminal/continuation policy, intentionally independent of scheduling. */
2
+ export function decideLLMInvocationRound(params) {
3
+ if (params.calls.length === 0)
4
+ return { kind: 'final-model-answer' };
5
+ if (!params.autoContinue || !params.calls.every((call) => params.knownToolNames.has(call.name))) {
6
+ return { kind: 'release-unresolved-calls' };
7
+ }
8
+ if (params.completedRounds >= params.maxToolRounds)
9
+ return { kind: 'max-rounds-reached' };
10
+ return params.isDirectReturn ? { kind: 'direct-tool-response' } : { kind: 'delegate-tools' };
11
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Invocation-scoped, append-only facts collected from physical provider calls.
3
+ * It stores physical-call accounting alongside the full developer-visible LLM
4
+ * attempt diagnostics selected by the node.
5
+ */
6
+ export class LLMInvocationJournal {
7
+ #modelCalls = [];
8
+ #events = [];
9
+ #llmAttempts = [];
10
+ recordModelCall(event) {
11
+ // The host observer is allowed to inspect the same event after this local
12
+ // observer returns. Preserve an immutable-at-recording-time snapshot so a
13
+ // later observer cannot rewrite this invocation's accounting facts.
14
+ const snapshot = {
15
+ ...event,
16
+ ...(event.rawUsage == null ? {} : { rawUsage: { ...event.rawUsage } }),
17
+ ...(event.normalizedUsage == null ? {} : { normalizedUsage: { ...event.normalizedUsage } }),
18
+ pricing: { ...event.pricing },
19
+ };
20
+ this.#modelCalls.push(snapshot);
21
+ this.#events.push({ type: 'model-call', event: snapshot });
22
+ }
23
+ recordToolRound(event) {
24
+ this.#events.push({ type: 'tool-round', ...event });
25
+ }
26
+ recordLLMAttempt(attempt) {
27
+ const snapshot = { ...attempt };
28
+ this.#llmAttempts.push(snapshot);
29
+ this.#events.push({ type: 'llm-attempt', attempt: snapshot });
30
+ }
31
+ recordTerminal(event) {
32
+ this.#events.push({ type: 'terminal', ...event });
33
+ }
34
+ get modelCalls() {
35
+ return this.#modelCalls;
36
+ }
37
+ get events() {
38
+ return this.#events;
39
+ }
40
+ get llmAttempts() {
41
+ return this.#llmAttempts;
42
+ }
43
+ }
@@ -0,0 +1,68 @@
1
+ import { coerceTypeOptional } from '../../utils/coerceType.js';
2
+ import { getInputOrData } from '../../utils/inputs.js';
3
+ import { coercePromptToChatMessages, prependSystemPrompt } from '../chat/chatMessages.js';
4
+ import { getInstructionMessageRoles } from './developerMessageRoles.js';
5
+ import { createChatV2ResponseOutput, resolveChatV2ResponseFormatParameters, } from './chatV2ResponseFormat.js';
6
+ import { resolveLLMChatV2ToolChoice } from './chatV2RuntimeOptions.js';
7
+ import { shouldIncludeLLMChatV2ToolCalls } from './llmChatV2NodeData.js';
8
+ import { shouldOutputChatV2RequestBody, shouldOutputChatV2ResponseBody, } from './chatV2Types.js';
9
+ import { createChatV2ResponseBodyCapture } from './chatV2ResponseBodyCapture.js';
10
+ export function resolveLLMChatV2BaseURL(data, inputs) {
11
+ return data.provider === 'custom'
12
+ ? getInputOrData(data, inputs, 'customProviderBaseURL', 'string', 'useCustomProviderBaseURLInput')?.trim() ||
13
+ undefined
14
+ : undefined;
15
+ }
16
+ export function buildLLMInvocationPlan(params) {
17
+ const { data, inputs, context } = params;
18
+ const prompt = inputs['prompt'];
19
+ const systemPrompt = inputs['systemPrompt'];
20
+ const responseBodyCapture = shouldOutputChatV2ResponseBody(data) ? createChatV2ResponseBodyCapture() : undefined;
21
+ return {
22
+ data,
23
+ inputs,
24
+ context,
25
+ prompt,
26
+ systemPrompt,
27
+ functions: data.useToolCalling && inputs['functions'] != null
28
+ ? coerceTypeOptional(inputs['functions'], 'gpt-function[]')
29
+ : undefined,
30
+ responseFormatParameters: resolveChatV2ResponseFormatParameters(data, inputs),
31
+ toolChoice: resolveLLMChatV2ToolChoice(data),
32
+ requestBodies: shouldOutputChatV2RequestBody(data) ? [] : undefined,
33
+ responseBodies: responseBodyCapture?.bodies,
34
+ responseBodyCapture,
35
+ instructionRoles: getInstructionMessageRoles(prependSystemPrompt(coercePromptToChatMessages(prompt), systemPrompt)),
36
+ };
37
+ }
38
+ /**
39
+ * Build the provider-neutral portion of an executable round. A model is never
40
+ * fabricated here; candidate resolution supplies it before this reaches the
41
+ * request pipeline.
42
+ */
43
+ export function buildLLMInvocationRunOptions(params) {
44
+ const { plan, provider, modelId } = params;
45
+ return {
46
+ provider,
47
+ modelId,
48
+ prompt: plan.prompt,
49
+ systemPrompt: plan.systemPrompt,
50
+ functions: plan.functions,
51
+ responseOutput: createChatV2ResponseOutput(plan.responseFormatParameters, provider, plan.data.customProviderApi),
52
+ responseFormat: plan.responseFormatParameters?.responseFormat,
53
+ outputUsage: plan.data.outputUsage,
54
+ outputReasoning: plan.data.outputReasoning,
55
+ outputRequestBody: shouldOutputChatV2RequestBody(plan.data),
56
+ outputResponseBody: shouldOutputChatV2ResponseBody(plan.data),
57
+ includeFunctionCalls: shouldIncludeLLMChatV2ToolCalls(plan.data),
58
+ emitPartialOutputs: plan.data.useAsGraphPartialOutput,
59
+ toolChoice: plan.toolChoice,
60
+ requestBodies: plan.requestBodies,
61
+ responseBodies: plan.responseBodies,
62
+ responseBodyCapture: plan.responseBodyCapture,
63
+ retryOnNon200: plan.data.retryOnNon200,
64
+ retryOnNon200RepeatTimes: plan.data.retryOnNon200RepeatTimes,
65
+ retryOnNon200CooldownMs: plan.data.retryOnNon200CooldownMs,
66
+ context: plan.context,
67
+ };
68
+ }
@@ -0,0 +1,5 @@
1
+ import { summarizeChatV2PhysicalCallUsage } from './chatV2UsageAccounting.js';
2
+ /** Pure public-shape projections over privacy-bounded invocation facts. */
3
+ export function projectLLMInvocationUsage(events) {
4
+ return summarizeChatV2PhysicalCallUsage(events);
5
+ }