@valerypopoff/rivet2-core 2.17.0 → 2.21.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 (120) hide show
  1. package/dist/cjs/bundle.cjs +3197 -1461
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/interpolationRuntime.cjs +40 -4
  4. package/dist/cjs/interpolationRuntime.cjs.map +2 -2
  5. package/dist/cjs/serialization.cjs +1880 -0
  6. package/dist/cjs/serialization.cjs.map +7 -0
  7. package/dist/cjs/webAppRuntime.cjs +168 -6
  8. package/dist/cjs/webAppRuntime.cjs.map +3 -3
  9. package/dist/esm/api/processSettings.js +1 -0
  10. package/dist/esm/exports.js +3 -0
  11. package/dist/esm/model/AgentResponseTrace.js +99 -34
  12. package/dist/esm/model/AgentResponseTracePresentation.js +130 -0
  13. package/dist/esm/model/DataValue.js +11 -2
  14. package/dist/esm/model/GlobalVariables.js +2 -1
  15. package/dist/esm/model/GraphBoundaryEffects.js +38 -1
  16. package/dist/esm/model/GraphExecutionState.js +81 -0
  17. package/dist/esm/model/GraphProcessor.js +625 -943
  18. package/dist/esm/model/GraphSchedulerBoundaryState.js +64 -0
  19. package/dist/esm/model/Nodes.js +5 -0
  20. package/dist/esm/model/ProjectBundle.js +69 -11
  21. package/dist/esm/model/ProjectBundleRuntime.js +54 -0
  22. package/dist/esm/model/ProjectGraphCallSites.js +46 -0
  23. package/dist/esm/model/SchedulerBoundaryPlanner.js +233 -0
  24. package/dist/esm/model/SubprocessorBridge.js +125 -87
  25. package/dist/esm/model/ToolCallContinuationCoordinator.js +1 -1
  26. package/dist/esm/model/chat-v2/aiSdkBridge.js +15 -12
  27. package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -4
  28. package/dist/esm/model/chat-v2/chatV2CredentialNames.js +5 -1
  29. package/dist/esm/model/chat-v2/chatV2Outputs.js +2 -2
  30. package/dist/esm/model/chat-v2/chatV2Pipeline.js +11 -1
  31. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +3 -2
  32. package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +46 -6
  33. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +7 -0
  34. package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +10 -0
  35. package/dist/esm/model/chat-v2/llmChatV2Body.js +3 -3
  36. package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +5 -2
  37. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +1 -0
  38. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +25 -15
  39. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +10 -2
  40. package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +17 -0
  41. package/dist/esm/model/chat-v2/llmModelCandidate.js +2 -1
  42. package/dist/esm/model/chat-v2/llmProfile.js +2 -1
  43. package/dist/esm/model/chat-v2/llmProfileBody.js +9 -0
  44. package/dist/esm/model/chat-v2/llmProfileFallback.js +7 -4
  45. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +1 -0
  46. package/dist/esm/model/chat-v2/llmProfileHealthStore.js +16 -3
  47. package/dist/esm/model/chat-v2/messageConverter.js +18 -16
  48. package/dist/esm/model/chat-v2/modelRegistry.js +14 -4
  49. package/dist/esm/model/chat-v2/openRouterModel.js +73 -0
  50. package/dist/esm/model/chat-v2/parallelToolCalls.js +2 -0
  51. package/dist/esm/model/chat-v2/providerOptions.js +30 -25
  52. package/dist/esm/model/classifier/credentials.js +13 -3
  53. package/dist/esm/model/classifier/limits.js +33 -3
  54. package/dist/esm/model/classifier/perplexity.js +63 -0
  55. package/dist/esm/model/classifier/profile.js +151 -0
  56. package/dist/esm/model/classifier/profileExecution.js +294 -0
  57. package/dist/esm/model/classifier/providers.js +217 -30
  58. package/dist/esm/model/classifier/state.js +4 -1
  59. package/dist/esm/model/classifier/types.js +11 -1
  60. package/dist/esm/model/nodeRunFailure.js +8 -1
  61. package/dist/esm/model/nodes/CallGraphNode.js +6 -0
  62. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +257 -66
  63. package/dist/esm/model/nodes/ClassifierProfileNode.js +133 -0
  64. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +1 -1
  65. package/dist/esm/model/nodes/LLMChatV2Node.js +2 -1
  66. package/dist/esm/model/nodes/SubGraphNode.js +4 -0
  67. package/dist/esm/model/nodes/toolCallDelegation.js +5 -1
  68. package/dist/esm/model/profileSuspensionHints.js +8 -0
  69. package/dist/esm/serialization.js +2 -0
  70. package/dist/esm/utils/coerceType.js +11 -1
  71. package/dist/esm/webAppRuntime.js +1 -0
  72. package/dist/types/exports.d.ts +3 -0
  73. package/dist/types/model/AgentResponseTrace.d.ts +15 -4
  74. package/dist/types/model/AgentResponseTracePresentation.d.ts +15 -0
  75. package/dist/types/model/DataValue.d.ts +12 -8
  76. package/dist/types/model/ExecutorProtocol.d.ts +14 -2
  77. package/dist/types/model/GraphBoundaryEffects.d.ts +10 -1
  78. package/dist/types/model/GraphExecutionState.d.ts +68 -0
  79. package/dist/types/model/GraphProcessor.d.ts +1 -0
  80. package/dist/types/model/GraphSchedulerBoundaryState.d.ts +96 -0
  81. package/dist/types/model/Nodes.d.ts +7 -4
  82. package/dist/types/model/ProcessContext.d.ts +12 -3
  83. package/dist/types/model/ProjectBundle.d.ts +18 -4
  84. package/dist/types/model/ProjectBundleRuntime.d.ts +24 -0
  85. package/dist/types/model/ProjectGraphCallSites.d.ts +12 -0
  86. package/dist/types/model/RivetUIContext.d.ts +1 -1
  87. package/dist/types/model/SchedulerBoundaryPlanner.d.ts +42 -0
  88. package/dist/types/model/Settings.d.ts +1 -0
  89. package/dist/types/model/SubgraphProjectTarget.d.ts +6 -0
  90. package/dist/types/model/SubprocessorBridge.d.ts +2 -0
  91. package/dist/types/model/chat-v2/chatV2CredentialNames.d.ts +4 -0
  92. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +1 -1
  93. package/dist/types/model/chat-v2/chatV2ProviderRegistry.d.ts +79 -1
  94. package/dist/types/model/chat-v2/chatV2ProviderTypes.d.ts +1 -1
  95. package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +2 -0
  96. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +2 -1
  97. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +2 -0
  98. package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +2 -0
  99. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +51 -3
  100. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +9 -6
  101. package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +6 -2
  102. package/dist/types/model/chat-v2/modelRegistry.d.ts +5 -4
  103. package/dist/types/model/chat-v2/openRouterModel.d.ts +2 -0
  104. package/dist/types/model/chat-v2/providerOptions.d.ts +2 -13
  105. package/dist/types/model/classifier/credentials.d.ts +4 -0
  106. package/dist/types/model/classifier/limits.d.ts +4 -1
  107. package/dist/types/model/classifier/perplexity.d.ts +7 -0
  108. package/dist/types/model/classifier/profile.d.ts +46 -0
  109. package/dist/types/model/classifier/profileExecution.d.ts +32 -0
  110. package/dist/types/model/classifier/providers.d.ts +32 -1
  111. package/dist/types/model/classifier/types.d.ts +9 -0
  112. package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +14 -12
  113. package/dist/types/model/nodes/ClassifierProfileNode.d.ts +20 -0
  114. package/dist/types/model/nodes/SubGraphNode.d.ts +1 -1
  115. package/dist/types/model/nodes/toolCallDelegation.d.ts +3 -1
  116. package/dist/types/model/profileSuspensionHints.d.ts +8 -0
  117. package/dist/types/recording/ExecutionRecorder.d.ts +5 -1
  118. package/dist/types/serialization.d.ts +2 -0
  119. package/dist/types/webAppRuntime.d.ts +1 -0
  120. package/package.json +7 -1
@@ -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
  ]);
@@ -329,6 +331,14 @@ function getParameterEditors() {
329
331
  }
330
332
  function getReasoningEditors() {
331
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
+ },
332
342
  {
333
343
  type: 'dropdown',
334
344
  label: 'Reasoning effort',
@@ -500,31 +510,31 @@ function getOutputEditors() {
500
510
  return group('Outputs', [
501
511
  {
502
512
  type: 'toggle',
503
- label: 'Output reasoning',
513
+ label: 'Reasoning',
504
514
  dataKey: 'outputReasoning',
505
515
  helperMessage: 'Adds a Reasoning output when the provider/model exposes reasoning or thinking text through the Vercel AI SDK. Some providers only expose token counts or summaries.',
506
516
  },
507
517
  {
508
518
  type: 'toggle',
509
- label: 'Output usage details',
519
+ label: 'Usage details',
510
520
  dataKey: 'outputUsage',
511
521
  helperMessage: 'Adds a Usage output built from Vercel AI SDK usage metadata: prompt, completion, total, cached, reasoning tokens, and estimated cost when available.',
512
522
  },
513
523
  {
514
524
  type: 'toggle',
515
- label: 'Output LLM attempts',
525
+ label: 'LLM attempts',
516
526
  dataKey: 'outputLLMAttempts',
517
527
  helperMessage: 'Adds one chronological record for every profile configuration, provider request, and response-validation attempt. Records include provider, model, retry status, and provider error details when available.',
518
528
  },
519
529
  {
520
530
  type: 'toggle',
521
- label: 'Output request body',
531
+ label: 'Request body',
522
532
  dataKey: 'outputRequestBody',
523
533
  helperMessage: 'Adds an LLM request body output. It can contain prompts and non-secret provider options; it never includes authorization headers or API keys.',
524
534
  },
525
535
  {
526
536
  type: 'toggle',
527
- label: 'Output response body',
537
+ label: 'Response body',
528
538
  dataKey: 'outputResponseBody',
529
539
  helperMessage: 'Adds the complete LLM response body captured at the provider HTTP boundary. JSON responses are parsed for inspection; other responses remain text. Rivet does not redact or truncate captured content.',
530
540
  },
@@ -562,14 +572,14 @@ function getErrorBehaviorEditors() {
562
572
  return group('Error behavior', [
563
573
  {
564
574
  type: 'toggle',
565
- label: 'Fail on non-2XX status code',
575
+ label: 'Throw exception on non-2XX status code',
566
576
  dataKey: 'errorOnNon200',
567
577
  defaultValue: true,
568
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.',
569
579
  },
570
580
  {
571
581
  type: 'toggle',
572
- label: 'Catch all failures',
582
+ label: 'Catch all exceptions',
573
583
  dataKey: 'catchRequestFailed',
574
584
  helperMessage: 'Return any node execution failure through Run failed and Run error instead of stopping the graph. Explicit graph cancellation is never caught.',
575
585
  },
@@ -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({
@@ -14,7 +14,7 @@ const credentialSources = new Set([
14
14
  'environment',
15
15
  'none',
16
16
  ]);
17
- const profileProviders = new Set(['openai', 'anthropic', 'google', 'custom']);
17
+ const profileProviders = new Set(['openai', 'anthropic', 'google', 'openrouter', 'custom']);
18
18
  export function normalizeLLMProfileValue(value) {
19
19
  if (!isRecord(value)) {
20
20
  throw new Error('LLM Profile input must contain an LLM profile value.');
@@ -138,6 +138,7 @@ function normalizeConfiguration(data) {
138
138
  throw new Error(`Unsupported LLM Profile API key source: ${String(data.apiKeySource)}.`);
139
139
  }
140
140
  assertEnumValue(data.openAIWebSearchContextSize, ['low', 'medium', 'high'], 'OpenAI web search context');
141
+ assertEnumValue(data.openRouterReasoningEffort ?? '', ['', 'none', 'minimal', 'low', 'medium', 'high', 'xhigh'], 'OpenRouter reasoning effort');
141
142
  const customProviderApi = parseCustomProviderApi(data.customProviderApi);
142
143
  assertEnumValue(data.anthropicThinkingMode, ['', 'adaptive', 'enabled', 'disabled'], 'Anthropic thinking mode');
143
144
  assertEnumValue(data.anthropicEffort, ['', 'low', 'medium', 'high', 'max'], 'Anthropic effort');
@@ -40,6 +40,15 @@ function getModelBodyLabel(data) {
40
40
  }
41
41
  function getProviderBodyFields(data) {
42
42
  switch (data.provider) {
43
+ case 'openrouter':
44
+ return data.openRouterReasoningEffort
45
+ ? [
46
+ {
47
+ label: 'Reasoning effort',
48
+ value: getOptionLabel(openAIReasoningEffortOptions, data.openRouterReasoningEffort),
49
+ },
50
+ ]
51
+ : [];
43
52
  case 'openai':
44
53
  return [
45
54
  getOptionalStringBodyField('Previous response ID', data.openAIPreviousResponseId, data.useOpenAIPreviousResponseIdInput),
@@ -18,7 +18,7 @@ class LLMProfileHealthOperationTimeoutError extends Error {
18
18
  * the attached handlers also consume any rejection that arrives after the
19
19
  * deadline or caller abort won the race.
20
20
  */
21
- function runBoundedHealthOperation(params) {
21
+ export function runBoundedHealthOperation(params) {
22
22
  const operationSignal = params.runWhenAborted ? undefined : params.signal;
23
23
  if (operationSignal?.aborted) {
24
24
  return Promise.reject(operationSignal.reason instanceof Error ? operationSignal.reason : new Error('LLM Chat request was aborted.'));
@@ -90,7 +90,9 @@ export function getLLMAttemptErrorMessage(error) {
90
90
  function formatCandidateProfileIdentity(candidate, profileIndex) {
91
91
  const profileName = candidate.profileName?.trim();
92
92
  const identity = formatCandidateIdentity(candidate);
93
- return profileName ? `${profileName} (profile ${profileIndex + 1}; ${identity})` : `Profile ${profileIndex + 1} (${identity})`;
93
+ return profileName
94
+ ? `${profileName} (profile ${profileIndex + 1}; ${identity})`
95
+ : `Profile ${profileIndex + 1} (${identity})`;
94
96
  }
95
97
  function buildExhaustedMessage(attempts) {
96
98
  const details = attempts
@@ -223,6 +225,7 @@ const PROVIDER_NETWORK_ERROR_CODES = new Set([
223
225
  'UND_ERR_CONNECT_TIMEOUT',
224
226
  'UND_ERR_HEADERS_TIMEOUT',
225
227
  'UND_ERR_SOCKET',
228
+ 'ERR_STREAM_PREMATURE_CLOSE',
226
229
  ]);
227
230
  function isKnownProviderNetworkError(error) {
228
231
  if (error == null || typeof error !== 'object')
@@ -257,7 +260,7 @@ export function isUnhealthyLLMProfileProviderFailure(error) {
257
260
  const status = getChatV2ProviderErrorStatusCode(providerFailure);
258
261
  return status === 408 || status === 429 || (status != null && status >= 500);
259
262
  }
260
- function createHealthPermit(params) {
263
+ export function createProfileHealthPermit(params) {
261
264
  const { candidate, healthStore, permitId, state, roundIndex, profileIndex, operationTimeoutMs, executionCorrelationId, signal, recordAttempt, } = params;
262
265
  let finished = false;
263
266
  let renewalInFlight = false;
@@ -477,7 +480,7 @@ export function createLLMProfileFallbackRunner(params) {
477
480
  healthState: begin.state,
478
481
  healthDisposition: 'allow',
479
482
  });
480
- healthPermit = createHealthPermit({
483
+ healthPermit = createProfileHealthPermit({
481
484
  candidate: { ...candidate, health: activeHealth },
482
485
  healthStore,
483
486
  permitId,
@@ -30,6 +30,7 @@ export const llmProfileFieldSpecs = [
30
30
  { key: 'extraProviderOptions', inputId: 'extraProviderOptions', valueKind: 'string' },
31
31
  { key: 'useExtraProviderOptionsInput', valueKind: 'boolean', resolvedInputToggle: true },
32
32
  { key: 'openAIReasoningEffort', valueKind: 'string' },
33
+ { key: 'openRouterReasoningEffort', valueKind: 'string' },
33
34
  { key: 'openAIReasoningSummary', valueKind: 'string' },
34
35
  { key: 'openAIPreviousResponseId', inputId: 'previousResponseId', valueKind: 'string' },
35
36
  { key: 'useOpenAIPreviousResponseIdInput', valueKind: 'boolean', resolvedInputToggle: true },
@@ -48,6 +48,9 @@ export function createRivetLLMProfileHealthIdentity(params) {
48
48
  // not to generation policy. A temperature/cooldown edit must not silently
49
49
  // create a fresh circuit, while changing the model, endpoint, auth, or
50
50
  // routing headers must never inherit another route's outage history.
51
+ const openRouterRouting = params.configuration.provider === 'openrouter' && params.configuration.extraProviderOptions
52
+ ? pickOpenRouterRouting(JSON.parse(params.configuration.extraProviderOptions))
53
+ : {};
51
54
  const routingConfiguration = {
52
55
  provider: params.configuration.provider,
53
56
  model: params.configuration.model,
@@ -58,6 +61,7 @@ export function createRivetLLMProfileHealthIdentity(params) {
58
61
  customProviderBaseURL: params.configuration.customProviderBaseURL,
59
62
  }),
60
63
  headers: canonicalizeEffectiveRoutingHeaders(params.chatNodeHeaders, params.configuration.headers),
64
+ ...(Object.keys(openRouterRouting).length > 0 ? { openRouterRouting } : {}),
61
65
  };
62
66
  const serialized = stableStringify({
63
67
  routingConfiguration,
@@ -85,6 +89,11 @@ export function createRivetLLMProfileHealthIdentity(params) {
85
89
  configurationFingerprint,
86
90
  };
87
91
  }
92
+ function pickOpenRouterRouting(options) {
93
+ return Object.fromEntries(['model', 'provider', 'models', 'route']
94
+ .filter((key) => options[key] !== undefined)
95
+ .map((key) => [key, options[key]]));
96
+ }
88
97
  function canonicalizeEffectiveRoutingHeaders(chatNodeHeaders, profileHeaders) {
89
98
  // Provider resolution spreads project-wide headers first and profile
90
99
  // headers second. Normalize names here because HTTP field names are
@@ -107,7 +116,7 @@ function canonicalizeEffectiveRoutingHeaders(chatNodeHeaders, profileHeaders) {
107
116
  function requireMatchingProjectScope(existing, identity) {
108
117
  const storedProjectId = existing.identity.projectId == null ? undefined : String(existing.identity.projectId);
109
118
  const requestProjectId = identity.projectId == null ? undefined : String(identity.projectId);
110
- if (storedProjectId !== requestProjectId) {
119
+ if (storedProjectId !== requestProjectId || (existing.identity.family ?? 'llm') !== (identity.family ?? 'llm')) {
111
120
  throw new Error(`LLM profile reliability key ${identity.key} belongs to a different project scope.`);
112
121
  }
113
122
  }
@@ -295,11 +304,14 @@ export class InMemoryRivetLLMProfileHealthStore {
295
304
  }
296
305
  reset(request) {
297
306
  if (request.key != null) {
298
- this.#entries.delete(request.key);
307
+ const entry = this.#entries.get(request.key);
308
+ if (request.family == null || (entry?.identity.family ?? 'llm') === request.family)
309
+ this.#entries.delete(request.key);
299
310
  return;
300
311
  }
301
312
  for (const [key, entry] of this.#entries) {
302
- if (entry.identity.projectId === request.projectId) {
313
+ if (entry.identity.projectId === request.projectId &&
314
+ (request.family == null || (entry.identity.family ?? 'llm') === request.family)) {
303
315
  this.#entries.delete(key);
304
316
  }
305
317
  }
@@ -309,6 +321,7 @@ export class InMemoryRivetLLMProfileHealthStore {
309
321
  this.#pruneStaleEntries(now);
310
322
  return [...this.#entries.entries()]
311
323
  .filter(([, entry]) => request.projectId == null || entry.identity.projectId === request.projectId)
324
+ .filter(([, entry]) => request.family == null || (entry.identity.family ?? 'llm') === request.family)
312
325
  .map(([, entry]) => {
313
326
  pruneFailures(entry, entry.policy, now);
314
327
  pruneClosedPermits(entry, now);
@@ -22,15 +22,17 @@ function mergeProviderMetadata(base, extra) {
22
22
  },
23
23
  };
24
24
  }
25
- function getAnthropicCacheMetadata(enabled, ttl) {
26
- if (!enabled) {
25
+ function getCacheMetadata(enabled, options) {
26
+ if (!enabled || (options.provider !== 'anthropic' && options.provider !== 'openrouter')) {
27
27
  return undefined;
28
28
  }
29
29
  return {
30
- anthropic: {
30
+ [options.provider]: {
31
31
  cacheControl: {
32
32
  type: 'ephemeral',
33
- ...(ttl ? { ttl } : {}),
33
+ ...(options.provider === 'anthropic' && options.anthropicCacheControlTtl
34
+ ? { ttl: options.anthropicCacheControlTtl }
35
+ : {}),
34
36
  },
35
37
  },
36
38
  };
@@ -79,7 +81,7 @@ function stringifyParts(parts) {
79
81
  })
80
82
  .join('\n\n');
81
83
  }
82
- function applyAnthropicCacheBreakpoint(parts, enabled, ttl) {
84
+ function applyCacheBreakpoint(parts, enabled, options) {
83
85
  if (!enabled || parts.length === 0) {
84
86
  return parts;
85
87
  }
@@ -87,7 +89,7 @@ function applyAnthropicCacheBreakpoint(parts, enabled, ttl) {
87
89
  if (lastPart == null) {
88
90
  return parts;
89
91
  }
90
- lastPart.providerOptions = mergeProviderMetadata(lastPart.providerOptions, getAnthropicCacheMetadata(true, ttl));
92
+ lastPart.providerOptions = mergeProviderMetadata(lastPart.providerOptions, getCacheMetadata(true, options));
91
93
  return parts;
92
94
  }
93
95
  export async function chatMessagesToModelMessages(messages, options) {
@@ -98,9 +100,7 @@ export async function chatMessagesToModelMessages(messages, options) {
98
100
  result.push({
99
101
  role: 'system',
100
102
  content: stringifyParts(msg.message),
101
- providerOptions: options.provider === 'anthropic'
102
- ? getAnthropicCacheMetadata(!!msg.isCacheBreakpoint, options.anthropicCacheControlTtl)
103
- : undefined,
103
+ providerOptions: getCacheMetadata(!!msg.isCacheBreakpoint, options),
104
104
  });
105
105
  break;
106
106
  }
@@ -112,9 +112,7 @@ export async function chatMessagesToModelMessages(messages, options) {
112
112
  result.push({
113
113
  role: 'system',
114
114
  content: stringifyParts(msg.message),
115
- providerOptions: options.provider === 'anthropic'
116
- ? getAnthropicCacheMetadata(!!msg.isCacheBreakpoint, options.anthropicCacheControlTtl)
117
- : undefined,
115
+ providerOptions: getCacheMetadata(!!msg.isCacheBreakpoint, options),
118
116
  });
119
117
  break;
120
118
  }
@@ -127,7 +125,7 @@ export async function chatMessagesToModelMessages(messages, options) {
127
125
  const content = await Promise.all(parts.map((part) => partToUserContent(part, options)));
128
126
  result.push({
129
127
  role: 'user',
130
- content: applyAnthropicCacheBreakpoint(content, options.provider === 'anthropic' && !!msg.isCacheBreakpoint, options.anthropicCacheControlTtl),
128
+ content: applyCacheBreakpoint(content, !!msg.isCacheBreakpoint, options),
131
129
  });
132
130
  }
133
131
  break;
@@ -135,8 +133,11 @@ export async function chatMessagesToModelMessages(messages, options) {
135
133
  case 'assistant': {
136
134
  const textContent = stringifyParts(msg.message);
137
135
  const toolCalls = msg.function_calls ?? (msg.function_call ? [msg.function_call] : []);
136
+ const providerOptions = options.provider === 'openrouter' && msg.openRouterReasoningDetails?.length
137
+ ? { openrouter: { reasoning_details: msg.openRouterReasoningDetails } }
138
+ : undefined;
138
139
  if (toolCalls.length === 0 && !msg.isCacheBreakpoint) {
139
- result.push({ role: 'assistant', content: textContent });
140
+ result.push({ role: 'assistant', content: textContent, ...(providerOptions ? { providerOptions } : {}) });
140
141
  }
141
142
  else {
142
143
  const content = [];
@@ -160,7 +161,8 @@ export async function chatMessagesToModelMessages(messages, options) {
160
161
  }
161
162
  result.push({
162
163
  role: 'assistant',
163
- content: applyAnthropicCacheBreakpoint(content, options.provider === 'anthropic' && !!msg.isCacheBreakpoint, options.anthropicCacheControlTtl),
164
+ ...(providerOptions ? { providerOptions } : {}),
165
+ content: applyCacheBreakpoint(content, !!msg.isCacheBreakpoint, options),
164
166
  });
165
167
  }
166
168
  break;
@@ -177,7 +179,7 @@ export async function chatMessagesToModelMessages(messages, options) {
177
179
  ];
178
180
  result.push({
179
181
  role: 'tool',
180
- content: applyAnthropicCacheBreakpoint(content, options.provider === 'anthropic' && !!msg.isCacheBreakpoint, options.anthropicCacheControlTtl),
182
+ content: applyCacheBreakpoint(content, !!msg.isCacheBreakpoint, options),
181
183
  });
182
184
  break;
183
185
  }
@@ -43,6 +43,9 @@ const chatV2ModelRegistry = {
43
43
  openai: normalizePerThousandTokenModelRegistry('OpenAI', openaiModels),
44
44
  anthropic: anthropicModels,
45
45
  google: normalizePerThousandTokenModelRegistry('Google', generativeAiGoogleModels),
46
+ // Routing prices vary by upstream endpoint. Use reported call cost, not
47
+ // another provider's static rate for a similarly named model.
48
+ openrouter: {},
46
49
  custom: {},
47
50
  };
48
51
  export function getChatV2ModelRegistry() {
@@ -61,11 +64,18 @@ export function calculateChatV2Cost(provider, modelId, promptTokens, completionT
61
64
  return isFiniteNonNegative(cost) ? cost : undefined;
62
65
  }
63
66
  /**
64
- * Estimates a call only when the provider reported both billable text-token
65
- * counts. Cache discounts, long-context premiums, and provider tool fees stay
66
- * outside this baseline estimate until their billing inputs are modeled.
67
+ * Uses reported OpenRouter cost; estimates other providers only when both
68
+ * billable text-token counts are available. Cache discounts, long-context
69
+ * premiums, and provider tool fees are not modeled in those estimates.
67
70
  */
68
- export function calculateChatV2UsageCost(provider, modelId, usage) {
71
+ export function calculateChatV2UsageCost(provider, modelId, usage, providerMetadata) {
72
+ if (provider === 'openrouter') {
73
+ const reportedUsage = providerMetadata?.openrouter?.usage;
74
+ const cost = reportedUsage != null && typeof reportedUsage === 'object'
75
+ ? reportedUsage.cost
76
+ : undefined;
77
+ return isFiniteNonNegative(cost) ? cost : undefined;
78
+ }
69
79
  if (!isFiniteNonNegative(usage?.inputTokens) || !isFiniteNonNegative(usage.outputTokens)) {
70
80
  return undefined;
71
81
  }
@@ -0,0 +1,73 @@
1
+ import { wrapLanguageModel } from 'ai';
2
+ /** OpenRouter may send a provider error inside an otherwise successful
3
+ * response. Normalize it before the shared SDK consumer would stringify the
4
+ * plain object and lose its message/status. Do not reinterpret other providers. */
5
+ function normalizeEmbeddedError(error) {
6
+ if (error instanceof Error || error == null || typeof error !== 'object' || Array.isArray(error))
7
+ return error;
8
+ const record = error;
9
+ if (typeof record.message !== 'string')
10
+ return error;
11
+ const normalized = new Error(record.message, { cause: error });
12
+ const code = typeof record.code === 'string' && /^\d{3}$/.test(record.code) ? Number(record.code) : record.code;
13
+ if (typeof code === 'number' && Number.isInteger(code) && code >= 400 && code <= 599) {
14
+ return Object.assign(normalized, { name: 'AI_APICallError', statusCode: code });
15
+ }
16
+ return normalized;
17
+ }
18
+ const responseValidation = {
19
+ specificationVersion: 'v3',
20
+ wrapGenerate: async ({ doGenerate }) => {
21
+ try {
22
+ return await doGenerate();
23
+ }
24
+ catch (error) {
25
+ // Non-stream errors in a 200 response are wrapped by the adapter with
26
+ // statusCode=200. Only a valid embedded error code may replace it.
27
+ if (error instanceof Error && error.statusCode === 200) {
28
+ const normalized = normalizeEmbeddedError(error.data);
29
+ if (normalized instanceof Error && 'statusCode' in normalized) {
30
+ normalized.cause = error;
31
+ throw normalized;
32
+ }
33
+ }
34
+ throw error;
35
+ }
36
+ },
37
+ wrapStream: async ({ doStream }) => {
38
+ const result = await doStream();
39
+ let sawError = false;
40
+ return {
41
+ ...result,
42
+ stream: result.stream.pipeThrough(new TransformStream({
43
+ transform(part, controller) {
44
+ if (part.type === 'error') {
45
+ sawError = true;
46
+ controller.enqueue({ ...part, error: normalizeEmbeddedError(part.error) });
47
+ return;
48
+ }
49
+ // The adapter synthesizes a finish event on EOF, and can even infer
50
+ // tool-calls from incomplete arguments. Require a provider finish
51
+ // reason before accepting the response or delegating any tools.
52
+ if (part.type === 'finish' && !sawError) {
53
+ if (part.finishReason.raw == null) {
54
+ sawError = true;
55
+ controller.enqueue({
56
+ type: 'error',
57
+ error: Object.assign(new Error('OpenRouter stream ended before a provider finish reason was received.'), { name: 'OpenRouterIncompleteStreamError', code: 'ERR_STREAM_PREMATURE_CLOSE' }),
58
+ });
59
+ }
60
+ else if (part.finishReason.unified === 'error' || part.finishReason.raw === 'error') {
61
+ sawError = true;
62
+ controller.enqueue({ type: 'error', error: new Error('OpenRouter reported an unsuccessful stream.') });
63
+ }
64
+ }
65
+ controller.enqueue(part);
66
+ },
67
+ })),
68
+ };
69
+ },
70
+ };
71
+ export function withOpenRouterResponseValidation(model) {
72
+ return wrapLanguageModel({ model, middleware: responseValidation });
73
+ }
@@ -19,6 +19,8 @@ export function applyLLMChatV2ParallelToolCallProviderOptions(params) {
19
19
  return providerOptions;
20
20
  }
21
21
  switch (provider) {
22
+ case 'openrouter':
23
+ return mergeProviderOptions(providerOptions, provider, { parallel_tool_calls: !!parallelToolCalls });
22
24
  case 'openai':
23
25
  return mergeProviderOptions(providerOptions, provider, {
24
26
  parallelToolCalls: !!parallelToolCalls,