@valerypopoff/rivet2-core 2.15.0 → 2.19.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 (187) hide show
  1. package/dist/cjs/bundle.cjs +7906 -3980
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/interpolationRuntime.cjs +62 -7
  4. package/dist/cjs/interpolationRuntime.cjs.map +3 -3
  5. package/dist/cjs/interpolationSyntax.cjs +9 -5
  6. package/dist/cjs/interpolationSyntax.cjs.map +2 -2
  7. package/dist/cjs/serialization.cjs +1880 -0
  8. package/dist/cjs/serialization.cjs.map +7 -0
  9. package/dist/cjs/webAppRuntime.cjs +168 -6
  10. package/dist/cjs/webAppRuntime.cjs.map +3 -3
  11. package/dist/esm/api/createProcessor.js +5 -2
  12. package/dist/esm/api/processSettings.js +1 -0
  13. package/dist/esm/exports.js +4 -0
  14. package/dist/esm/model/AgentResponseTrace.js +99 -34
  15. package/dist/esm/model/AgentResponseTracePresentation.js +130 -0
  16. package/dist/esm/model/DataValue.js +11 -2
  17. package/dist/esm/model/GlobalVariables.js +2 -1
  18. package/dist/esm/model/GraphBoundaryCache.js +2 -1
  19. package/dist/esm/model/GraphBoundaryEffects.js +38 -1
  20. package/dist/esm/model/GraphExecutionState.js +81 -0
  21. package/dist/esm/model/GraphProcessor.js +825 -884
  22. package/dist/esm/model/GraphSchedulerBoundaryState.js +64 -0
  23. package/dist/esm/model/Nodes.js +15 -0
  24. package/dist/esm/model/ProjectBundle.js +248 -0
  25. package/dist/esm/model/ProjectBundleRuntime.js +54 -0
  26. package/dist/esm/model/SchedulerBoundaryPlanner.js +233 -0
  27. package/dist/esm/model/SplitRunProcessor.js +28 -7
  28. package/dist/esm/model/StreamingWatchTopology.js +118 -8
  29. package/dist/esm/model/SubgraphProjectTarget.js +7 -0
  30. package/dist/esm/model/SubprocessorBridge.js +125 -87
  31. package/dist/esm/model/ToolCallContinuationCoordinator.js +1 -1
  32. package/dist/esm/model/chat-v2/aiSdkBridge.js +22 -17
  33. package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -4
  34. package/dist/esm/model/chat-v2/chatV2CredentialNames.js +5 -1
  35. package/dist/esm/model/chat-v2/chatV2Outputs.js +2 -2
  36. package/dist/esm/model/chat-v2/chatV2Pipeline.js +24 -9
  37. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +3 -2
  38. package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +46 -6
  39. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +26 -1
  40. package/dist/esm/model/chat-v2/chatV2Shared.js +2 -1
  41. package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +10 -0
  42. package/dist/esm/model/chat-v2/llmChatV2Body.js +13 -10
  43. package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +5 -2
  44. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +3 -0
  45. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +33 -9
  46. package/dist/esm/model/chat-v2/llmChatV2NodeMigration.js +22 -2
  47. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +10 -2
  48. package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +17 -0
  49. package/dist/esm/model/chat-v2/llmModelCandidate.js +2 -1
  50. package/dist/esm/model/chat-v2/llmProfile.js +5 -1
  51. package/dist/esm/model/chat-v2/llmProfileBody.js +11 -2
  52. package/dist/esm/model/chat-v2/llmProfileFallback.js +7 -4
  53. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +2 -1
  54. package/dist/esm/model/chat-v2/llmProfileHealthStore.js +16 -3
  55. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +1 -1
  56. package/dist/esm/model/chat-v2/messageConverter.js +18 -16
  57. package/dist/esm/model/chat-v2/modelRegistry.js +14 -4
  58. package/dist/esm/model/chat-v2/openRouterModel.js +73 -0
  59. package/dist/esm/model/chat-v2/parallelToolCalls.js +2 -0
  60. package/dist/esm/model/chat-v2/providerOptions.js +30 -25
  61. package/dist/esm/model/chat-v2/temperature.js +9 -0
  62. package/dist/esm/model/classifier/credentials.js +42 -6
  63. package/dist/esm/model/classifier/images.js +176 -0
  64. package/dist/esm/model/classifier/json.js +57 -0
  65. package/dist/esm/model/classifier/limits.js +300 -0
  66. package/dist/esm/model/classifier/openai.js +118 -0
  67. package/dist/esm/model/classifier/perplexity.js +63 -0
  68. package/dist/esm/model/classifier/preparation.js +74 -0
  69. package/dist/esm/model/classifier/profile.js +151 -0
  70. package/dist/esm/model/classifier/profileExecution.js +294 -0
  71. package/dist/esm/model/classifier/providers.js +454 -192
  72. package/dist/esm/model/classifier/questionHelpers.js +29 -45
  73. package/dist/esm/model/classifier/questions.js +53 -0
  74. package/dist/esm/model/classifier/response.js +75 -0
  75. package/dist/esm/model/classifier/state.js +207 -0
  76. package/dist/esm/model/classifier/types.js +11 -1
  77. package/dist/esm/model/nodeRunFailure.js +54 -0
  78. package/dist/esm/model/nodes/CallGraphNode.js +6 -0
  79. package/dist/esm/model/nodes/CatchStreamingChunksNode.js +42 -0
  80. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +385 -154
  81. package/dist/esm/model/nodes/ClassifierProfileNode.js +133 -0
  82. package/dist/esm/model/nodes/ClassifierQuestionNode.js +59 -15
  83. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +1 -1
  84. package/dist/esm/model/nodes/GetGlobalNode.js +2 -2
  85. package/dist/esm/model/nodes/HttpCallNode.js +44 -75
  86. package/dist/esm/model/nodes/ImageNode.js +44 -3
  87. package/dist/esm/model/nodes/LLMChatV2Node.js +26 -4
  88. package/dist/esm/model/nodes/ObjectNode.js +29 -18
  89. package/dist/esm/model/nodes/PromptNode.js +2 -1
  90. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +4 -1
  91. package/dist/esm/model/nodes/SetGlobalNode.js +5 -3
  92. package/dist/esm/model/nodes/StopWatchingStreamingOutputNode.js +8 -8
  93. package/dist/esm/model/nodes/StreamValueNode.js +38 -0
  94. package/dist/esm/model/nodes/SubGraphNode.js +199 -35
  95. package/dist/esm/model/nodes/ToBase64Node.js +106 -0
  96. package/dist/esm/model/nodes/WatchStreamingOutputNode.js +7 -7
  97. package/dist/esm/model/nodes/toolCallDelegation.js +5 -1
  98. package/dist/esm/model/profileSuspensionHints.js +8 -0
  99. package/dist/esm/recording/ExecutionRecorder.js +26 -0
  100. package/dist/esm/serialization.js +2 -0
  101. package/dist/esm/utils/base64.js +18 -15
  102. package/dist/esm/utils/coerceType.js +11 -1
  103. package/dist/esm/utils/errors.js +41 -0
  104. package/dist/esm/utils/interpolation.js +44 -22
  105. package/dist/esm/utils/interpolationSyntax.js +15 -6
  106. package/dist/esm/utils/serialization/serialization.js +3 -2
  107. package/dist/esm/utils/serialization/serializationUtils.js +6 -0
  108. package/dist/esm/utils/serialization/serialization_v4.js +15 -3
  109. package/dist/esm/webAppRuntime.js +1 -0
  110. package/dist/types/api/createProcessor.d.ts +7 -1
  111. package/dist/types/exports.d.ts +4 -0
  112. package/dist/types/model/AgentResponseTrace.d.ts +15 -4
  113. package/dist/types/model/AgentResponseTracePresentation.d.ts +15 -0
  114. package/dist/types/model/CycleDetector.d.ts +1 -2
  115. package/dist/types/model/DataValue.d.ts +12 -8
  116. package/dist/types/model/ExecutorProtocol.d.ts +9 -0
  117. package/dist/types/model/GraphBoundaryCache.d.ts +2 -0
  118. package/dist/types/model/GraphBoundaryEffects.d.ts +10 -1
  119. package/dist/types/model/GraphExecutionState.d.ts +68 -0
  120. package/dist/types/model/GraphProcessor.d.ts +2 -0
  121. package/dist/types/model/GraphSchedulerBoundaryState.d.ts +96 -0
  122. package/dist/types/model/Nodes.d.ts +11 -4
  123. package/dist/types/model/ProcessContext.d.ts +24 -3
  124. package/dist/types/model/ProjectBundle.d.ts +59 -0
  125. package/dist/types/model/ProjectBundleRuntime.d.ts +24 -0
  126. package/dist/types/model/ProjectReferenceLoader.d.ts +3 -0
  127. package/dist/types/model/RivetUIContext.d.ts +1 -1
  128. package/dist/types/model/SchedulerBoundaryPlanner.d.ts +42 -0
  129. package/dist/types/model/Settings.d.ts +1 -0
  130. package/dist/types/model/StreamingWatchTopology.d.ts +11 -1
  131. package/dist/types/model/SubgraphProjectTarget.d.ts +38 -0
  132. package/dist/types/model/SubprocessorBridge.d.ts +2 -0
  133. package/dist/types/model/chat-v2/chatV2CredentialNames.d.ts +4 -0
  134. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +1 -1
  135. package/dist/types/model/chat-v2/chatV2ProviderRegistry.d.ts +79 -1
  136. package/dist/types/model/chat-v2/chatV2ProviderTypes.d.ts +1 -1
  137. package/dist/types/model/chat-v2/chatV2Shared.d.ts +1 -1
  138. package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +2 -0
  139. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +4 -1
  140. package/dist/types/model/chat-v2/llmChatV2NodeMigration.d.ts +3 -1
  141. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +2 -0
  142. package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +2 -0
  143. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +51 -3
  144. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +10 -7
  145. package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +6 -2
  146. package/dist/types/model/chat-v2/modelRegistry.d.ts +5 -4
  147. package/dist/types/model/chat-v2/openRouterModel.d.ts +2 -0
  148. package/dist/types/model/chat-v2/providerOptions.d.ts +2 -13
  149. package/dist/types/model/chat-v2/temperature.d.ts +2 -0
  150. package/dist/types/model/classifier/credentials.d.ts +7 -1
  151. package/dist/types/model/classifier/images.d.ts +18 -0
  152. package/dist/types/model/classifier/json.d.ts +19 -0
  153. package/dist/types/model/classifier/limits.d.ts +45 -0
  154. package/dist/types/model/classifier/openai.d.ts +5 -0
  155. package/dist/types/model/classifier/perplexity.d.ts +7 -0
  156. package/dist/types/model/classifier/preparation.d.ts +16 -0
  157. package/dist/types/model/classifier/profile.d.ts +46 -0
  158. package/dist/types/model/classifier/profileExecution.d.ts +32 -0
  159. package/dist/types/model/classifier/providers.d.ts +98 -9
  160. package/dist/types/model/classifier/questionHelpers.d.ts +6 -4
  161. package/dist/types/model/classifier/questions.d.ts +4 -0
  162. package/dist/types/model/classifier/response.d.ts +4 -0
  163. package/dist/types/model/classifier/state.d.ts +37 -0
  164. package/dist/types/model/classifier/types.d.ts +11 -0
  165. package/dist/types/model/nodeRunFailure.d.ts +13 -0
  166. package/dist/types/model/nodes/CatchStreamingChunksNode.d.ts +20 -0
  167. package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +17 -12
  168. package/dist/types/model/nodes/ClassifierProfileNode.d.ts +20 -0
  169. package/dist/types/model/nodes/GetGlobalNode.d.ts +7 -0
  170. package/dist/types/model/nodes/ImageNode.d.ts +4 -0
  171. package/dist/types/model/nodes/LLMChatV2Node.d.ts +1 -0
  172. package/dist/types/model/nodes/ObjectNode.d.ts +2 -1
  173. package/dist/types/model/nodes/StreamValueNode.d.ts +14 -0
  174. package/dist/types/model/nodes/SubGraphNode.d.ts +21 -2
  175. package/dist/types/model/nodes/ToBase64Node.d.ts +12 -0
  176. package/dist/types/model/nodes/toolCallDelegation.d.ts +3 -1
  177. package/dist/types/model/profileSuspensionHints.d.ts +8 -0
  178. package/dist/types/recording/ExecutionRecorder.d.ts +8 -2
  179. package/dist/types/serialization.d.ts +2 -0
  180. package/dist/types/utils/base64.d.ts +1 -1
  181. package/dist/types/utils/errors.d.ts +4 -0
  182. package/dist/types/utils/interpolation.d.ts +13 -2
  183. package/dist/types/utils/interpolationSyntax.d.ts +1 -1
  184. package/dist/types/utils/serialization/serialization.d.ts +3 -1
  185. package/dist/types/utils/serialization/serializationUtils.d.ts +1 -0
  186. package/dist/types/webAppRuntime.d.ts +1 -0
  187. package/package.json +7 -1
@@ -11,6 +11,10 @@ export const CHAT_V2_DEFAULT_CREDENTIAL_NAMES = {
11
11
  programmaticName: 'googleApiKey',
12
12
  environmentVariableName: 'GOOGLE_GENERATIVE_AI_API_KEY',
13
13
  },
14
+ openrouter: {
15
+ programmaticName: 'openRouterApiKey',
16
+ environmentVariableName: 'OPENROUTER_API_KEY',
17
+ },
14
18
  };
15
19
  const programmaticNamePattern = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
16
20
  const environmentVariableNamePattern = /^[A-Za-z_][A-Za-z0-9_]*$/;
@@ -68,7 +72,7 @@ export function normalizeChatV2CredentialNamesByProvider(value) {
68
72
  throw new Error(`Unsupported provider API key names entry: ${unsupportedProvider}.`);
69
73
  }
70
74
  const normalized = {};
71
- for (const provider of ['openai', 'anthropic', 'google']) {
75
+ for (const provider of ['openai', 'anthropic', 'google', 'openrouter']) {
72
76
  if (raw[provider] != null) {
73
77
  normalized[provider] = normalizeChatV2CredentialNames(provider, raw[provider]);
74
78
  }
@@ -28,7 +28,7 @@ function createControlFlowExcludedOutput() {
28
28
  value: undefined,
29
29
  };
30
30
  }
31
- export function normalizeChatV2Usage(usage, options) {
31
+ export function normalizeChatV2Usage(usage, options, providerMetadata) {
32
32
  if (usage == null) {
33
33
  return undefined;
34
34
  }
@@ -55,7 +55,7 @@ export function normalizeChatV2Usage(usage, options) {
55
55
  totalTokens,
56
56
  cachedTokens,
57
57
  reasoningTokens,
58
- totalCost: calculateChatV2UsageCost(options.provider, options.modelId, usage),
58
+ totalCost: calculateChatV2UsageCost(options.provider, options.modelId, usage, providerMetadata),
59
59
  };
60
60
  }
61
61
  export function createChatV2ResponseOutput(response, structuredOutput, responseFormat) {
@@ -5,9 +5,9 @@ import { chatMessagesToModelMessages } from './messageConverter.js';
5
5
  import { isChatV2ProviderTimeoutError } from './chatV2Types.js';
6
6
  import { chatV2ToolsToAiSdk } from './toolConverter.js';
7
7
  import { buildChatV2RequestPlan } from './chatV2RequestPlan.js';
8
- import { getChatV2ProviderErrorStatusCode, normalizeChatV2ProviderError, } from './chatV2Errors.js';
8
+ import { getChatV2ProviderErrorStatusCode, normalizeChatV2ProviderError } from './chatV2Errors.js';
9
9
  import { createLLMChatV2RetryAbortError, waitForLLMChatV2RetryCooldown } from './chatV2Retry.js';
10
- import { createChatV2CommonOutputs, normalizeChatV2Usage, } from './chatV2Outputs.js';
10
+ import { createChatV2CommonOutputs, normalizeChatV2Usage } from './chatV2Outputs.js';
11
11
  import { materializeLLMResponse } from './llmResponseMaterializer.js';
12
12
  /** Identifies legacy pipeline results that represent a terminal provider failure. */
13
13
  export function isChatV2PipelineProviderFailureResult(result) {
@@ -64,6 +64,7 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
64
64
  }
65
65
  };
66
66
  for (let attempt = 0;; attempt++) {
67
+ signal.throwIfAborted();
67
68
  const callId = createObservedChatV2CallId(options);
68
69
  const callStartedAt = Date.now();
69
70
  let callWasObserved = false;
@@ -115,13 +116,16 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
115
116
  const result = transportMode === 'generate'
116
117
  ? await generateChatV2(attemptChatOptions)
117
118
  : await streamChatV2(attemptChatOptions);
119
+ signal.throwIfAborted();
118
120
  await options.responseBodyCapture?.flush();
121
+ signal.throwIfAborted();
119
122
  publishAndRetireResponseEvidence();
120
123
  const statusCode = result.requestStatus ?? 200;
124
+ const statusSucceeded = statusCode >= 200 && statusCode < 300;
121
125
  notifyChatV2CallFinished(options, {
122
126
  callId,
123
127
  attemptIndex: attempt,
124
- outcome: statusCode === 200 ? 'success' : 'provider-failure',
128
+ outcome: statusSucceeded ? 'success' : 'provider-failure',
125
129
  result,
126
130
  startedAt: callStartedAt,
127
131
  durationMs: Math.max(0, Date.now() - callStartedAt),
@@ -129,16 +133,16 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
129
133
  callWasObserved = true;
130
134
  notifyProviderAttempt(options, {
131
135
  attemptIndex: attempt,
132
- outcome: statusCode === 200 ? 'success' : 'provider-failure',
136
+ outcome: statusSucceeded ? 'success' : 'provider-failure',
133
137
  status: statusCode,
134
- ...(statusCode === 200 ? {} : { error: buildNon200StatusError(statusCode) }),
138
+ ...(statusSucceeded ? {} : { error: buildNon200StatusError(statusCode) }),
135
139
  });
136
140
  if (!retryPlan.enabled || statusCode === 200) {
137
141
  return { result };
138
142
  }
139
143
  const responseError = buildNon200StatusError(statusCode);
140
144
  if (attempt >= retryPlan.repeatTimes) {
141
- return { result, responseError };
145
+ return { result, ...(statusSucceeded ? {} : { responseError }) };
142
146
  }
143
147
  await prepareProviderRetry();
144
148
  await waitForLLMChatV2RetryCooldown(retryPlan.cooldownMs, signal);
@@ -172,7 +176,7 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
172
176
  // The provider may reject concurrently with graph cancellation. The
173
177
  // cancellation wins: it must neither retry nor masquerade as a
174
178
  // provider failure to profile fallback and run activity.
175
- throw createLLMChatV2RetryAbortError();
179
+ throw signal.reason ?? createLLMChatV2RetryAbortError();
176
180
  }
177
181
  if (isChatV2ProviderTimeoutError(error) || !retryPlan.enabled || statusCode == null || statusCode === 200) {
178
182
  throw error;
@@ -286,7 +290,7 @@ export async function runChatV2PipelineExecution(options) {
286
290
  },
287
291
  };
288
292
  }
289
- const usage = normalizeChatV2Usage(chatResponse.result.usage, options);
293
+ const usage = normalizeChatV2Usage(chatResponse.result.usage, options, chatResponse.result.providerMetadata);
290
294
  const requestStatus = chatResponse.result.requestStatus ?? 200;
291
295
  const commonOutputs = createChatV2CommonOutputs({
292
296
  requestMessages,
@@ -309,6 +313,16 @@ export async function runChatV2PipelineExecution(options) {
309
313
  if (allMessagesOutput?.type !== 'chat-message[]') {
310
314
  throw new Error('Chat v2 pipeline expected all-messages output to be chat-message[].');
311
315
  }
316
+ // Tool continuation and All Messages re-entry rebuild SDK messages. Preserve
317
+ // only the provider's reasoning continuity, not arbitrary response metadata.
318
+ const reasoningDetails = chatResponse.result.providerMetadata?.openrouter?.reasoning_details;
319
+ const assistant = allMessagesOutput.value.at(-1);
320
+ if (options.provider === 'openrouter' &&
321
+ assistant?.type === 'assistant' &&
322
+ Array.isArray(reasoningDetails) &&
323
+ reasoningDetails.length > 0) {
324
+ assistant.openRouterReasoningDetails = structuredClone(reasoningDetails);
325
+ }
312
326
  const result = {
313
327
  commonOutputs,
314
328
  requestMessages,
@@ -322,7 +336,8 @@ export async function runChatV2PipelineExecution(options) {
322
336
  providerMetadata: chatResponse.result.providerMetadata,
323
337
  requestStatus,
324
338
  };
325
- const providerRoundFailure = chatResponse.responseError ?? (requestStatus === 200 ? undefined : buildNon200StatusError(requestStatus));
339
+ const providerRoundFailure = chatResponse.responseError ??
340
+ (requestStatus >= 200 && requestStatus < 300 ? undefined : buildNon200StatusError(requestStatus));
326
341
  if (providerRoundFailure != null) {
327
342
  const rawError = providerRoundFailure;
328
343
  return {
@@ -9,8 +9,9 @@ function getStringSetting(settings, key) {
9
9
  return getNonEmptyString(settings[key]);
10
10
  }
11
11
  function resolveConfiguredCredential(provider, context, options) {
12
- if (isChatV2BuiltInProvider(provider) && options.providerApiKeyNames?.[provider] != null) {
13
- const names = normalizeChatV2CredentialNames(provider, options.providerApiKeyNames[provider]);
12
+ if (isChatV2BuiltInProvider(provider) &&
13
+ (provider === 'openrouter' || options.providerApiKeyNames?.[provider] != null)) {
14
+ const names = normalizeChatV2CredentialNames(provider, options.providerApiKeyNames?.[provider]);
14
15
  const programmaticValue = getStringSetting(context.settings, names.programmaticName);
15
16
  if (programmaticValue) {
16
17
  return {
@@ -1,9 +1,49 @@
1
- const providerCapabilities = {
2
- openai: { builtInTools: true, parallelToolCalls: true, structuredOutput: true },
3
- anthropic: { builtInTools: false, parallelToolCalls: true, structuredOutput: true },
4
- google: { builtInTools: true, parallelToolCalls: false, structuredOutput: true },
5
- custom: { builtInTools: false, parallelToolCalls: true, structuredOutput: true },
1
+ import { CHAT_V2_DEFAULT_CREDENTIAL_NAMES } from './chatV2CredentialNames.js';
2
+ /** Adapter metadata, not a promise about every model served by that adapter.
3
+ * SDKs, credential resolution and provider-native options have separate owners. */
4
+ export const chatV2ProviderDescriptors = {
5
+ openai: {
6
+ label: 'OpenAI',
7
+ defaultModel: 'gpt-5',
8
+ catalog: 'registry',
9
+ credentialNames: CHAT_V2_DEFAULT_CREDENTIAL_NAMES.openai,
10
+ capabilities: { builtInTools: true, parallelToolCalls: true, structuredOutput: true },
11
+ },
12
+ anthropic: {
13
+ label: 'Anthropic',
14
+ defaultModel: 'claude-sonnet-4-20250514',
15
+ catalog: 'registry',
16
+ credentialNames: CHAT_V2_DEFAULT_CREDENTIAL_NAMES.anthropic,
17
+ capabilities: { builtInTools: false, parallelToolCalls: true, structuredOutput: true },
18
+ },
19
+ google: {
20
+ label: 'Google',
21
+ defaultModel: 'gemini-2.5-flash',
22
+ catalog: 'registry',
23
+ credentialNames: CHAT_V2_DEFAULT_CREDENTIAL_NAMES.google,
24
+ capabilities: { builtInTools: true, parallelToolCalls: false, structuredOutput: true },
25
+ },
26
+ openrouter: {
27
+ label: 'OpenRouter',
28
+ defaultModel: 'openrouter/auto',
29
+ catalog: [{ value: 'openrouter/auto', label: 'OpenRouter Auto' }],
30
+ credentialNames: CHAT_V2_DEFAULT_CREDENTIAL_NAMES.openrouter,
31
+ capabilities: { builtInTools: false, parallelToolCalls: true, structuredOutput: true },
32
+ },
33
+ custom: {
34
+ label: 'Custom provider',
35
+ defaultModel: 'model-id',
36
+ catalog: 'registry',
37
+ capabilities: { builtInTools: false, parallelToolCalls: true, structuredOutput: true },
38
+ },
6
39
  };
40
+ export const chatV2ProviderOptions = Object.keys(chatV2ProviderDescriptors).map((value) => ({
41
+ value,
42
+ label: chatV2ProviderDescriptors[value].label,
43
+ }));
44
+ export function isChatV2Provider(value) {
45
+ return Object.hasOwn(chatV2ProviderDescriptors, value);
46
+ }
7
47
  export function getChatV2ProviderCapabilities(provider) {
8
- return providerCapabilities[provider];
48
+ return chatV2ProviderDescriptors[provider].capabilities;
9
49
  }
@@ -5,6 +5,7 @@ import { cleanHeaders, getInputOrData } from '../../utils/inputs.js';
5
5
  import { cloneRivetStoredValue } from '../StoredValueStore.js';
6
6
  import { resolveChatV2Credential } from './chatV2ProviderProfile.js';
7
7
  import { applyLLMChatV2ParallelToolCallProviderOptions } from './parallelToolCalls.js';
8
+ import { normalizeTemperature } from './temperature.js';
8
9
  export function resolveLLMChatV2Headers(data, inputs) {
9
10
  const resolvedHeaders = data.useHeadersInput && inputs['headers'] != null
10
11
  ? coerceTypeOptional(inputs['headers'], 'object')
@@ -59,6 +60,12 @@ export function resolveLLMChatV2ExtraProviderOptions(data, inputs) {
59
60
  }
60
61
  function resolveProviderOptions(data, inputs) {
61
62
  const providerOptions = {};
63
+ if (data.provider === 'openrouter' && data.openRouterReasoningEffort) {
64
+ if (!['none', 'minimal', 'low', 'medium', 'high', 'xhigh'].includes(data.openRouterReasoningEffort)) {
65
+ throw new Error('Unsupported OpenRouter reasoning effort.');
66
+ }
67
+ providerOptions.openrouter = { reasoning: { effort: data.openRouterReasoningEffort } };
68
+ }
62
69
  if (data.provider === 'openai') {
63
70
  const previousResponseId = data.useOpenAIPreviousResponseIdInput && inputs['previousResponseId'] != null
64
71
  ? coerceTypeOptional(inputs['previousResponseId'], 'string')
@@ -159,9 +166,26 @@ function resolveStopSequences(data, inputs) {
159
166
  return normalizeStopSequences(stopSequences);
160
167
  }
161
168
  export function resolveLLMChatV2GenerationParameters(data, inputs) {
169
+ const temperatureInput = data.useTemperatureInput ? inputs['temperature'] : undefined;
170
+ let temperature;
171
+ if (temperatureInput != null) {
172
+ const resolved = temperatureInput.type === 'string'
173
+ ? temperatureInput.value.trim() === ''
174
+ ? undefined
175
+ : Number(temperatureInput.value)
176
+ : coerceTypeOptional(temperatureInput, 'number');
177
+ // A connected malformed input must not silently fall back to node data.
178
+ if (typeof resolved !== 'number' || !Number.isFinite(resolved)) {
179
+ throw new Error('Temperature input must be a finite number.');
180
+ }
181
+ temperature = resolved;
182
+ }
183
+ else {
184
+ temperature = normalizeTemperature(data.temperature);
185
+ }
162
186
  return {
163
187
  maxTokens: getInputOrData(data, inputs, 'maxTokens', 'number'),
164
- temperature: getInputOrData(data, inputs, 'temperature', 'number'),
188
+ temperature,
165
189
  topP: getInputOrData(data, inputs, 'topP', 'number'),
166
190
  topK: getInputOrData(data, inputs, 'topK', 'number'),
167
191
  presencePenalty: getInputOrData(data, inputs, 'presencePenalty', 'number'),
@@ -212,6 +236,7 @@ export function resolveLLMChatV2BuiltInTools(data, context, config, apiKey) {
212
236
  return tools;
213
237
  }
214
238
  case 'anthropic':
239
+ case 'openrouter':
215
240
  return undefined;
216
241
  case 'custom':
217
242
  return undefined;
@@ -179,9 +179,10 @@ export function getCommonChatV2Editors(modelOptions) {
179
179
  {
180
180
  type: 'number',
181
181
  label: 'Temperature',
182
- helperMessage: 'Provider-dependent; some reasoning models may ignore this setting.',
182
+ helperMessage: 'Leave blank to use the provider default. Some reasoning models may ignore this setting.',
183
183
  dataKey: 'temperature',
184
184
  useInputToggleDataKey: 'useTemperatureInput',
185
+ allowEmpty: true,
185
186
  min: 0,
186
187
  max: 2,
187
188
  step: 0.1,
@@ -6,6 +6,16 @@
6
6
  export function isChatV2FiniteNonNegativeNumber(value) {
7
7
  return typeof value === 'number' && Number.isFinite(value) && value >= 0;
8
8
  }
9
+ /** Known USD subtotal, independent of whether Usage details are displayed. */
10
+ export function sumChatV2PhysicalCallCost(events) {
11
+ let total;
12
+ for (const event of new Map(events.map((event) => [event.callId, event])).values()) {
13
+ if (event.pricing.status === 'known' && isChatV2FiniteNonNegativeNumber(event.pricing.costUsd)) {
14
+ total = (total ?? 0) + event.pricing.costUsd;
15
+ }
16
+ }
17
+ return total;
18
+ }
9
19
  /**
10
20
  * Aggregates one node invocation's physical provider calls into its portable
11
21
  * Usage output. The call id is a stable transport identity, so a redelivered
@@ -47,7 +47,7 @@ function getOptionalNumberBodyField(label, value, usesInput) {
47
47
  if (usesInput) {
48
48
  return { label, value: '(Using Input)' };
49
49
  }
50
- return value === undefined ? undefined : { label, value: `${value}` };
50
+ return value == null || !Number.isFinite(value) ? undefined : { label, value: `${value}` };
51
51
  }
52
52
  function getOptionalStringBodyField(label, value, usesInput) {
53
53
  if (usesInput) {
@@ -177,15 +177,18 @@ function getBehaviorBodyFields(data) {
177
177
  ];
178
178
  }
179
179
  function getErrorBodyFields(data) {
180
- if (!data.retryOnNon200) {
181
- return [];
182
- }
183
180
  const repeatTimes = data.retryOnNon200RepeatTimes ?? DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_REPEAT_TIMES;
184
181
  const cooldownMs = data.retryOnNon200CooldownMs ?? DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_COOLDOWN_MS;
185
182
  return [
186
- { label: 'Retry on non-200', value: 'Enabled' },
187
- { label: 'Repeat times', value: `${repeatTimes}` },
188
- { label: 'Cooldown, ms', value: `${cooldownMs}` },
183
+ ...(data.errorOnNon200 !== false ? [{ label: 'Throw on non-2XX', value: 'Enabled' }] : []),
184
+ ...(data.catchRequestFailed ? [{ label: 'Catch all failures', value: 'Enabled' }] : []),
185
+ ...(data.retryOnNon200
186
+ ? [
187
+ { label: 'Retry on non-200', value: 'Enabled' },
188
+ { label: 'Repeat times', value: `${repeatTimes}` },
189
+ { label: 'Cooldown, ms', value: `${cooldownMs}` },
190
+ ]
191
+ : []),
189
192
  ];
190
193
  }
191
194
  function getAdvancedBodySection(data) {
@@ -232,8 +235,8 @@ function getInlineModelBodyFields(data) {
232
235
  ].filter((field) => field !== undefined);
233
236
  }
234
237
  function getParameterBodyFields(data) {
235
- const reasoningEffort = data.provider === 'openai'
236
- ? getOptionLabel(openAIReasoningEffortOptions, data.openAIReasoningEffort)
238
+ const reasoningEffort = data.provider === 'openai' || data.provider === 'openrouter'
239
+ ? getOptionLabel(openAIReasoningEffortOptions, data.provider === 'openrouter' ? data.openRouterReasoningEffort : data.openAIReasoningEffort)
237
240
  : data.provider === 'anthropic'
238
241
  ? getOptionLabel(anthropicEffortOptions, data.anthropicEffort)
239
242
  : data.provider === 'google'
@@ -241,7 +244,7 @@ function getParameterBodyFields(data) {
241
244
  : undefined;
242
245
  return [
243
246
  ...(reasoningEffort ? [{ label: 'Reasoning effort', value: reasoningEffort }] : []),
244
- { label: 'Temperature', value: data.useTemperatureInput ? '(Using Input)' : `${data.temperature}` },
247
+ getOptionalNumberBodyField('Temperature', data.temperature, data.useTemperatureInput),
245
248
  { label: 'Max output tokens', value: data.useMaxTokensInput ? '(Using Input)' : `${data.maxTokens}` },
246
249
  getOptionalNumberBodyField('Top P', data.topP, data.useTopPInput),
247
250
  getOptionalNumberBodyField('Top K', data.topK, data.useTopKInput),
@@ -2,9 +2,12 @@ import { isChatV2PipelineProviderFailureResult } from './chatV2Pipeline.js';
2
2
  import { cloneLLMChatV2EditorCacheOutputs } from './chatV2EditorCache.js';
3
3
  /** Projects cache hits as current-run output without inventing provider work. */
4
4
  export function projectLLMChatV2EditorCacheHit(runtime) {
5
- const outputs = runtime.cachedOutputs;
6
- if (outputs == null)
5
+ if (runtime.cachedOutputs == null)
7
6
  return undefined;
7
+ // Keep cached response/Usage evidence, but account only work performed in
8
+ // this invocation. Neither the model nor its delegated tools run on a hit.
9
+ const outputs = { ...runtime.cachedOutputs, ['cost']: { type: 'number', value: 0 } };
10
+ delete outputs['costBreakdown'];
8
11
  if (runtime.getProfileSummary != null) {
9
12
  outputs['llmProfileSummary'] = {
10
13
  type: 'string',
@@ -24,6 +24,7 @@ export function createLLMChatV2NodeData() {
24
24
  extraProviderOptions: '',
25
25
  useExtraProviderOptionsInput: false,
26
26
  openAIReasoningEffort: '',
27
+ openRouterReasoningEffort: '',
27
28
  openAIReasoningSummary: '',
28
29
  openAIPreviousResponseId: '',
29
30
  useOpenAIPreviousResponseIdInput: false,
@@ -58,6 +59,8 @@ export function createLLMChatV2NodeData() {
58
59
  autoContinueToolCalls: false,
59
60
  maxToolRounds: 3,
60
61
  retryOnNon200: false,
62
+ errorOnNon200: true,
63
+ catchRequestFailed: false,
61
64
  retryOnNon200RepeatTimes: DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_REPEAT_TIMES,
62
65
  retryOnNon200CooldownMs: DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_COOLDOWN_MS,
63
66
  outputLLMAttempts: false,
@@ -1,3 +1,4 @@
1
+ import { profileSuspensionHints } from '../profileSuspensionHints.js';
1
2
  import { STREAM_RESPONSE_HELPER_MESSAGE } from './chatV2Shared.js';
2
3
  import { DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_COOLDOWN_MS, DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_REPEAT_TIMES, } from './chatV2Retry.js';
3
4
  import { anthropicCacheControlTtlOptions, anthropicEffortOptions, anthropicThinkingModeOptions, chatV2ProviderOptions, customProviderApiOptions, getChatV2ModelOptions, googleThinkingLevelOptions, openAIReasoningEffortOptions, openAIWebSearchContextSizeOptions, } from './providerOptions.js';
@@ -37,7 +38,8 @@ function getApiKeySourceHelperMessage(data) {
37
38
  switch (data.provider) {
38
39
  case 'openai':
39
40
  case 'anthropic':
40
- case 'google': {
41
+ case 'google':
42
+ case 'openrouter': {
41
43
  const names = getChatV2CredentialNamesForDisplay(data.provider, data.providerApiKeyNames?.[data.provider]);
42
44
  const hasOverride = data.providerApiKeyNames?.[data.provider] != null;
43
45
  return hasOverride
@@ -131,13 +133,13 @@ function getCircuitBreakerEditors() {
131
133
  {
132
134
  type: 'info',
133
135
  label: "It's a hosted runtime capability",
134
- helperMessage: 'This configuration is enforced by Rivet Studio Server or another host that explicitly provides shared LLM profile reliability. It has no effect in standalone Rivet.',
136
+ helperMessage: profileSuspensionHints.host,
135
137
  },
136
138
  {
137
139
  type: 'toggle',
138
140
  label: 'Enable automatic suspension',
139
141
  dataKey: 'enableCircuitBreaker',
140
- helperMessage: 'After provider failures or timeouts, temporarily suspend this profile in the LLM profiles fallback chain. When the suspension ends, one recovery attempt checks whether the profile can resume.',
142
+ helperMessage: profileSuspensionHints.enable,
141
143
  },
142
144
  {
143
145
  type: 'number',
@@ -147,7 +149,7 @@ function getCircuitBreakerEditors() {
147
149
  storageMultiplier: 1_000,
148
150
  min: 1_000,
149
151
  step: 1_000,
150
- helperMessage: 'Maximum wait time for a non-stream response (or the first useful streamed output). A call that reaches this deadline falls back immediately, even before this profile is suspended.',
152
+ helperMessage: 'Time to receive a response or first useful streamed output; then try the next profile.',
151
153
  hideIf: (data) => data.enableCircuitBreaker !== true,
152
154
  },
153
155
  {
@@ -158,7 +160,7 @@ function getCircuitBreakerEditors() {
158
160
  storageMultiplier: 1_000,
159
161
  min: 1_000,
160
162
  step: 1_000,
161
- helperMessage: 'Maximum gap between streamed response events before falling back.',
163
+ helperMessage: 'Maximum gap between streamed events before trying the next profile.',
162
164
  hideIf: (data) => data.enableCircuitBreaker !== true,
163
165
  },
164
166
  {
@@ -168,7 +170,7 @@ function getCircuitBreakerEditors() {
168
170
  defaultValue: DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_THRESHOLD,
169
171
  min: 1,
170
172
  step: 1,
171
- helperMessage: 'Failed or timed-out profile attempts required within the failure window before suspending this profile.',
173
+ helperMessage: profileSuspensionHints.threshold,
172
174
  hideIf: (data) => data.enableCircuitBreaker !== true,
173
175
  },
174
176
  {
@@ -179,7 +181,7 @@ function getCircuitBreakerEditors() {
179
181
  storageMultiplier: 1_000,
180
182
  min: 1_000,
181
183
  step: 1_000,
182
- helperMessage: 'Failed or timed-out profile attempts inside this rolling window count toward suspension.',
184
+ helperMessage: profileSuspensionHints.window,
183
185
  hideIf: (data) => data.enableCircuitBreaker !== true,
184
186
  },
185
187
  {
@@ -190,7 +192,7 @@ function getCircuitBreakerEditors() {
190
192
  storageMultiplier: 1_000,
191
193
  min: 1_000,
192
194
  step: 1_000,
193
- helperMessage: 'How long the fallback chain skips this profile before allowing one recovery attempt.',
195
+ helperMessage: profileSuspensionHints.duration,
194
196
  hideIf: (data) => data.enableCircuitBreaker !== true,
195
197
  },
196
198
  ]);
@@ -252,9 +254,10 @@ function getParameterEditors() {
252
254
  {
253
255
  type: 'number',
254
256
  label: 'Temperature',
255
- helperMessage: 'Provider-dependent; some reasoning models may ignore this setting.',
257
+ helperMessage: 'Leave blank to use the provider default. Some reasoning models may ignore this setting.',
256
258
  dataKey: 'temperature',
257
259
  useInputToggleDataKey: 'useTemperatureInput',
260
+ allowEmpty: true,
258
261
  min: 0,
259
262
  max: 2,
260
263
  step: 0.1,
@@ -328,6 +331,14 @@ function getParameterEditors() {
328
331
  }
329
332
  function getReasoningEditors() {
330
333
  return group('Reasoning', [
334
+ {
335
+ type: 'dropdown',
336
+ label: 'Reasoning effort',
337
+ dataKey: 'openRouterReasoningEffort',
338
+ options: openAIReasoningEffortOptions,
339
+ helperMessage: 'Reasoning depth for models that support it. Unsupported settings fail instead of being ignored.',
340
+ hideIf: hideUnlessProvider('openrouter'),
341
+ },
331
342
  {
332
343
  type: 'dropdown',
333
344
  label: 'Reasoning effort',
@@ -559,6 +570,19 @@ function getProviderAdvancedEditors() {
559
570
  }
560
571
  function getErrorBehaviorEditors() {
561
572
  return group('Error behavior', [
573
+ {
574
+ type: 'toggle',
575
+ label: 'Fail on non-2XX status code',
576
+ dataKey: 'errorOnNon200',
577
+ defaultValue: true,
578
+ helperMessage: 'After retries and profile fallback, throw on a rejected HTTP request. When disabled, return Run failed and Run error; unavailable response outputs are excluded.',
579
+ },
580
+ {
581
+ type: 'toggle',
582
+ label: 'Catch all failures',
583
+ dataKey: 'catchRequestFailed',
584
+ helperMessage: 'Return any node execution failure through Run failed and Run error instead of stopping the graph. Explicit graph cancellation is never caught.',
585
+ },
562
586
  {
563
587
  type: 'toggle',
564
588
  label: 'Retry on non-200',
@@ -1,14 +1,34 @@
1
+ /** Repair legacy payloads on read or Save without mutating the supplied data. */
2
+ export function normalizeSerializedLLMTemperatureData(nodeType, data) {
3
+ if (!['llmChatV2', 'llmProfile'].includes(nodeType) || data == null || typeof data !== 'object')
4
+ return data;
5
+ const record = data;
6
+ if (!Object.hasOwn(record, 'temperature'))
7
+ return data;
8
+ if (record.temperature != null && !(typeof record.temperature === 'number' && Number.isNaN(record.temperature)))
9
+ return data;
10
+ const copy = { ...record };
11
+ delete copy.temperature;
12
+ return copy;
13
+ }
1
14
  /**
2
- * Serialized LLM Chat migrations live beside the node contract, rather than
15
+ * Serialized LLM Chat/Profile migrations live beside the node contract, rather than
3
16
  * making generic project serialization understand LLM-specific settings.
4
17
  * This is deliberately idempotent because deserialization can normalize a
5
18
  * graph more than once while it is imported or embedded in a prefab.
6
19
  */
7
20
  export function normalizeSerializedLLMChatV2Node(node) {
8
- if (node.type !== 'llmChatV2' || node.data == null || typeof node.data !== 'object') {
21
+ if (!['llmChatV2', 'llmProfile'].includes(node.type))
9
22
  return;
23
+ for (const variant of node.variants ?? []) {
24
+ variant.data = normalizeSerializedLLMTemperatureData(node.type, variant.data);
10
25
  }
26
+ node.data = normalizeSerializedLLMTemperatureData(node.type, node.data);
27
+ if (node.data == null || typeof node.data !== 'object')
28
+ return;
11
29
  const data = node.data;
30
+ if (node.type !== 'llmChatV2')
31
+ return;
12
32
  const hadLegacyRequestDiagnostics = data.outputRequestStatus === true || data.outputRequestError === true;
13
33
  if (hadLegacyRequestDiagnostics && !Object.hasOwn(data, 'outputLLMAttempts')) {
14
34
  data.outputLLMAttempts = true;
@@ -1,6 +1,7 @@
1
1
  import { delegateToolCall } from '../nodes/toolCallDelegation.js';
2
- import { runChatV2PipelineWithToolContinuation, } from './toolContinuation.js';
2
+ import { runChatV2PipelineWithToolContinuation } from './toolContinuation.js';
3
3
  import { isChatV2PipelineProviderFailureResult } from './chatV2Pipeline.js';
4
+ import { addGraphCostBreakdown, graphCostBreakdownMatchesCost, } from '../GraphBoundaryEffects.js';
4
5
  /**
5
6
  * Owns the LLM-level recovery and continuation decision boundary. The node
6
7
  * boundary provides a resolved runtime and GraphProcessor supplies only the
@@ -8,6 +9,7 @@ import { isChatV2PipelineProviderFailureResult } from './chatV2Pipeline.js';
8
9
  */
9
10
  export async function executeLLMInvocation(params) {
10
11
  const { context, journal, runtime, toolCallContinuation } = params;
12
+ let toolCost;
11
13
  try {
12
14
  let terminalSnapshot;
13
15
  const result = runtime.shouldAutoContinueToolCalls
@@ -36,6 +38,12 @@ export async function executeLLMInvocation(params) {
36
38
  passthroughErrors: true,
37
39
  });
38
40
  journal.recordToolRound({ kind: 'internal', count: 1 });
41
+ if (delegated.cost != null && Number.isFinite(delegated.cost) && delegated.cost >= 0) {
42
+ const carried = delegated.costBreakdown;
43
+ toolCost = addGraphCostBreakdown(toolCost, carried && graphCostBreakdownMatchesCost(carried, delegated.cost)
44
+ ? carried
45
+ : { llm: 0, classifier: 0, other: delegated.cost });
46
+ }
39
47
  return {
40
48
  type: 'chat-message',
41
49
  value: delegated.message,
@@ -80,7 +88,7 @@ export async function executeLLMInvocation(params) {
80
88
  ? 'released-unresolved-calls'
81
89
  : 'final-model-answer',
82
90
  });
83
- return { result, terminalSnapshot };
91
+ return { result, terminalSnapshot, toolCost };
84
92
  }
85
93
  catch (error) {
86
94
  journal.recordTerminal({ kind: context.signal.aborted ? 'cancelled' : 'failed' });
@@ -1,5 +1,7 @@
1
1
  import { projectLLMInvocationUsage } from './llmInvocationProjections.js';
2
2
  import { createChatV2CapturedBodyOutputs } from './chatV2Outputs.js';
3
+ import { sumChatV2PhysicalCallCost, isChatV2FiniteNonNegativeNumber } from './chatV2UsageAccounting.js';
4
+ import { isChatV2PipelineProviderFailureResult } from './chatV2Pipeline.js';
3
5
  /**
4
6
  * Projects invocation facts that remain useful even when the node fails.
5
7
  * Captured HTTP bodies are emitted only through their opt-in ports, while
@@ -37,6 +39,21 @@ function projectLLMInvocationMetadata(params) {
37
39
  /** Applies existing public LLM Chat output shapes from invocation facts. */
38
40
  export function projectLLMInvocationResult(params) {
39
41
  const { result, modelCalls, outputUsage, outputLLMAttempts, llmAttempts, profileSummary } = params;
42
+ if (!isChatV2PipelineProviderFailureResult(result)) {
43
+ const knownCost = sumChatV2PhysicalCallCost(modelCalls);
44
+ const llmCost = knownCost ?? (isChatV2FiniteNonNegativeNumber(result.usage?.totalCost) ? result.usage.totalCost : undefined);
45
+ if (params.toolCost) {
46
+ const breakdown = { ...params.toolCost, llm: params.toolCost.llm + (llmCost ?? 0) };
47
+ result.commonOutputs['cost'] = {
48
+ type: 'number',
49
+ value: breakdown.llm + breakdown.classifier + breakdown.other,
50
+ };
51
+ result.commonOutputs['costBreakdown'] = { type: 'object', value: breakdown };
52
+ }
53
+ else if (llmCost != null) {
54
+ result.commonOutputs['cost'] = { type: 'number', value: llmCost };
55
+ }
56
+ }
40
57
  const usage = getLLMInvocationUsage({ modelCalls, outputUsage });
41
58
  if (usage != null) {
42
59
  result.usage = usage;
@@ -30,7 +30,8 @@ export async function resolveLLMModelCandidate(params) {
30
30
  customProgrammaticName: effectiveData.customProviderApiKeyProgrammaticName,
31
31
  customEnvironmentName: effectiveData.customProviderApiKeyEnvVarName,
32
32
  });
33
- const transformRequestBody = (provider === 'openai' || provider === 'custom') && plan.instructionRoles.includes('developer')
33
+ const transformRequestBody = (provider === 'openai' || provider === 'custom' || provider === 'openrouter') &&
34
+ plan.instructionRoles.includes('developer')
34
35
  ? (body) => restoreOpenAICompatibleInstructionRoles(body, plan.instructionRoles)
35
36
  : undefined;
36
37
  const resolvedProvider = await createResolvedChatV2Provider({