@valerypopoff/rivet2-core 2.17.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 (115) hide show
  1. package/dist/cjs/bundle.cjs +3093 -1440
  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 +2 -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 +621 -942
  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 +23 -10
  21. package/dist/esm/model/ProjectBundleRuntime.js +54 -0
  22. package/dist/esm/model/SchedulerBoundaryPlanner.js +233 -0
  23. package/dist/esm/model/SubprocessorBridge.js +125 -87
  24. package/dist/esm/model/ToolCallContinuationCoordinator.js +1 -1
  25. package/dist/esm/model/chat-v2/aiSdkBridge.js +15 -12
  26. package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -4
  27. package/dist/esm/model/chat-v2/chatV2CredentialNames.js +5 -1
  28. package/dist/esm/model/chat-v2/chatV2Outputs.js +2 -2
  29. package/dist/esm/model/chat-v2/chatV2Pipeline.js +11 -1
  30. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +3 -2
  31. package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +46 -6
  32. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +7 -0
  33. package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +10 -0
  34. package/dist/esm/model/chat-v2/llmChatV2Body.js +2 -2
  35. package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +5 -2
  36. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +1 -0
  37. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +18 -8
  38. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +10 -2
  39. package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +17 -0
  40. package/dist/esm/model/chat-v2/llmModelCandidate.js +2 -1
  41. package/dist/esm/model/chat-v2/llmProfile.js +2 -1
  42. package/dist/esm/model/chat-v2/llmProfileBody.js +9 -0
  43. package/dist/esm/model/chat-v2/llmProfileFallback.js +7 -4
  44. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +1 -0
  45. package/dist/esm/model/chat-v2/llmProfileHealthStore.js +16 -3
  46. package/dist/esm/model/chat-v2/messageConverter.js +18 -16
  47. package/dist/esm/model/chat-v2/modelRegistry.js +14 -4
  48. package/dist/esm/model/chat-v2/openRouterModel.js +73 -0
  49. package/dist/esm/model/chat-v2/parallelToolCalls.js +2 -0
  50. package/dist/esm/model/chat-v2/providerOptions.js +30 -25
  51. package/dist/esm/model/classifier/credentials.js +13 -3
  52. package/dist/esm/model/classifier/limits.js +33 -3
  53. package/dist/esm/model/classifier/perplexity.js +63 -0
  54. package/dist/esm/model/classifier/profile.js +151 -0
  55. package/dist/esm/model/classifier/profileExecution.js +294 -0
  56. package/dist/esm/model/classifier/providers.js +217 -30
  57. package/dist/esm/model/classifier/state.js +4 -1
  58. package/dist/esm/model/classifier/types.js +11 -1
  59. package/dist/esm/model/nodeRunFailure.js +8 -1
  60. package/dist/esm/model/nodes/CallGraphNode.js +6 -0
  61. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +250 -59
  62. package/dist/esm/model/nodes/ClassifierProfileNode.js +133 -0
  63. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +1 -1
  64. package/dist/esm/model/nodes/LLMChatV2Node.js +2 -1
  65. package/dist/esm/model/nodes/SubGraphNode.js +3 -0
  66. package/dist/esm/model/nodes/toolCallDelegation.js +5 -1
  67. package/dist/esm/model/profileSuspensionHints.js +8 -0
  68. package/dist/esm/serialization.js +2 -0
  69. package/dist/esm/utils/coerceType.js +11 -1
  70. package/dist/esm/webAppRuntime.js +1 -0
  71. package/dist/types/exports.d.ts +2 -0
  72. package/dist/types/model/AgentResponseTrace.d.ts +15 -4
  73. package/dist/types/model/AgentResponseTracePresentation.d.ts +15 -0
  74. package/dist/types/model/DataValue.d.ts +12 -8
  75. package/dist/types/model/ExecutorProtocol.d.ts +7 -0
  76. package/dist/types/model/GraphBoundaryEffects.d.ts +10 -1
  77. package/dist/types/model/GraphExecutionState.d.ts +68 -0
  78. package/dist/types/model/GraphProcessor.d.ts +1 -0
  79. package/dist/types/model/GraphSchedulerBoundaryState.d.ts +96 -0
  80. package/dist/types/model/Nodes.d.ts +7 -4
  81. package/dist/types/model/ProcessContext.d.ts +12 -3
  82. package/dist/types/model/ProjectBundle.d.ts +9 -4
  83. package/dist/types/model/ProjectBundleRuntime.d.ts +24 -0
  84. package/dist/types/model/RivetUIContext.d.ts +1 -1
  85. package/dist/types/model/SchedulerBoundaryPlanner.d.ts +42 -0
  86. package/dist/types/model/Settings.d.ts +1 -0
  87. package/dist/types/model/SubprocessorBridge.d.ts +2 -0
  88. package/dist/types/model/chat-v2/chatV2CredentialNames.d.ts +4 -0
  89. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +1 -1
  90. package/dist/types/model/chat-v2/chatV2ProviderRegistry.d.ts +79 -1
  91. package/dist/types/model/chat-v2/chatV2ProviderTypes.d.ts +1 -1
  92. package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +2 -0
  93. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +2 -1
  94. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +2 -0
  95. package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +2 -0
  96. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +51 -3
  97. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +9 -6
  98. package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +6 -2
  99. package/dist/types/model/chat-v2/modelRegistry.d.ts +5 -4
  100. package/dist/types/model/chat-v2/openRouterModel.d.ts +2 -0
  101. package/dist/types/model/chat-v2/providerOptions.d.ts +2 -13
  102. package/dist/types/model/classifier/credentials.d.ts +4 -0
  103. package/dist/types/model/classifier/limits.d.ts +4 -1
  104. package/dist/types/model/classifier/perplexity.d.ts +7 -0
  105. package/dist/types/model/classifier/profile.d.ts +46 -0
  106. package/dist/types/model/classifier/profileExecution.d.ts +32 -0
  107. package/dist/types/model/classifier/providers.d.ts +32 -1
  108. package/dist/types/model/classifier/types.d.ts +9 -0
  109. package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +14 -12
  110. package/dist/types/model/nodes/ClassifierProfileNode.d.ts +20 -0
  111. package/dist/types/model/nodes/toolCallDelegation.d.ts +3 -1
  112. package/dist/types/model/profileSuspensionHints.d.ts +8 -0
  113. package/dist/types/serialization.d.ts +2 -0
  114. package/dist/types/webAppRuntime.d.ts +1 -0
  115. package/package.json +7 -1
@@ -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,
@@ -2,16 +2,14 @@ import { createAnthropic } from '@ai-sdk/anthropic';
2
2
  import { createGoogleGenerativeAI } from '@ai-sdk/google';
3
3
  import { createOpenAI } from '@ai-sdk/openai';
4
4
  import { createOpenAICompatible } from '@ai-sdk/openai-compatible';
5
+ import { createOpenRouter } from '@openrouter/ai-sdk-provider';
6
+ import { withOpenRouterResponseValidation } from './openRouterModel.js';
5
7
  import { cleanHeaders } from '../../utils/inputs.js';
6
8
  import { getCustomProviderApiContract } from './customProviderApi.js';
7
9
  import { getChatV2ModelRegistry } from './modelRegistry.js';
10
+ import { chatV2ProviderDescriptors, chatV2ProviderOptions, isChatV2Provider } from './chatV2ProviderRegistry.js';
8
11
  export { customProviderApiOptions, getCustomProviderApiContract, parseCustomProviderApi, } from './customProviderApi.js';
9
- export const chatV2ProviderOptions = [
10
- { value: 'openai', label: 'OpenAI' },
11
- { value: 'anthropic', label: 'Anthropic' },
12
- { value: 'google', label: 'Google' },
13
- { value: 'custom', label: 'Custom provider' },
14
- ];
12
+ export { chatV2ProviderOptions };
15
13
  export const openAIReasoningEffortOptions = [
16
14
  { value: '', label: 'Default' },
17
15
  { value: 'none', label: 'None' },
@@ -55,6 +53,9 @@ export function getChatV2ProviderLabel(provider) {
55
53
  return chatV2ProviderOptions.find((option) => option.value === provider)?.label ?? provider;
56
54
  }
57
55
  export function getChatV2ModelOptions(provider) {
56
+ const catalog = chatV2ProviderDescriptors[provider].catalog;
57
+ if (catalog !== 'registry')
58
+ return catalog.map((option) => ({ ...option }));
58
59
  const registry = getChatV2ModelRegistry()[provider];
59
60
  return Object.entries(registry)
60
61
  .map(([value, model]) => ({
@@ -64,27 +65,12 @@ export function getChatV2ModelOptions(provider) {
64
65
  .sort((a, b) => a.label.localeCompare(b.label));
65
66
  }
66
67
  export function getDefaultChatV2Model(provider) {
67
- switch (provider) {
68
- case 'openai':
69
- return 'gpt-5';
70
- case 'anthropic':
71
- return 'claude-sonnet-4-20250514';
72
- case 'google':
73
- return 'gemini-2.5-flash';
74
- case 'custom':
75
- return 'model-id';
76
- }
68
+ return chatV2ProviderDescriptors[provider].defaultModel;
77
69
  }
78
70
  export function parseChatV2Provider(value) {
79
- switch (value) {
80
- case 'openai':
81
- case 'anthropic':
82
- case 'google':
83
- case 'custom':
84
- return value;
85
- default:
86
- throw new Error(`Unsupported LLM Chat provider: ${value}`);
87
- }
71
+ if (isChatV2Provider(value))
72
+ return value;
73
+ throw new Error(`Unsupported LLM Chat provider: ${value}`);
88
74
  }
89
75
  export function normalizeOpenAICompatibleEndpoint(endpoint) {
90
76
  let url;
@@ -267,6 +253,11 @@ export async function resolveChatV2ProviderConfig(provider, _modelId, context, o
267
253
  ...options.headers,
268
254
  });
269
255
  switch (provider) {
256
+ case 'openrouter':
257
+ return {
258
+ baseURL: 'https://openrouter.ai/api/v1',
259
+ headers: Object.keys(headers).length > 0 ? headers : undefined,
260
+ };
270
261
  case 'openai':
271
262
  return {
272
263
  baseURL: undefined,
@@ -297,6 +288,20 @@ export async function resolveChatV2ProviderConfig(provider, _modelId, context, o
297
288
  }
298
289
  export function createChatV2Model(provider, modelId, context, options = {}) {
299
290
  switch (provider) {
291
+ case 'openrouter': {
292
+ const providerInstance = createOpenRouter({
293
+ // Never fall back to the OpenAI/Custom key or an SDK ambient secret.
294
+ apiKey: options.apiKey ?? context.settings.openRouterApiKey ?? '',
295
+ baseURL: 'https://openrouter.ai/api/v1',
296
+ headers: options.headers,
297
+ fetch: maybeCreateProviderProcessingFetch(options),
298
+ });
299
+ return withOpenRouterResponseValidation(providerInstance.chat(modelId, {
300
+ usage: { include: true },
301
+ // Unsupported configured parameters must fail, not be ignored upstream.
302
+ provider: { require_parameters: true },
303
+ }));
304
+ }
300
305
  case 'openai': {
301
306
  const providerInstance = createOpenAI({
302
307
  apiKey: options.apiKey || context.settings.openAiApiKey || context.settings.openAiKey || undefined,
@@ -1,5 +1,7 @@
1
1
  import { coerceTypeOptional } from '../../utils/coerceType.js';
2
2
  import { classifierDataProperty, classifierInputDataValue } from './json.js';
3
+ export class ClassifierCredentialMissingError extends Error {
4
+ }
3
5
  export const JEV_DEFAULT_CREDENTIAL_NAMES = {
4
6
  programmaticName: 'typesafeApiKey',
5
7
  environmentVariableName: 'TYPESAFE_API_KEY',
@@ -12,6 +14,14 @@ export const OPENAI_DEFAULT_CREDENTIAL_NAMES = {
12
14
  programmaticName: 'openAiApiKey',
13
15
  environmentVariableName: 'OPENAI_API_KEY',
14
16
  };
17
+ export const OPENROUTER_DEFAULT_CREDENTIAL_NAMES = {
18
+ programmaticName: 'openRouterApiKey',
19
+ environmentVariableName: 'OPENROUTER_API_KEY',
20
+ };
21
+ export const PERPLEXITY_DEFAULT_CREDENTIAL_NAMES = {
22
+ programmaticName: 'perplexityApiKey',
23
+ environmentVariableName: 'PERPLEXITY_API_KEY',
24
+ };
15
25
  const programmaticNamePattern = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
16
26
  const environmentVariableNamePattern = /^[A-Za-z_][A-Za-z0-9_]*$/;
17
27
  export function isValidClassifierProgrammaticCredentialName(name) {
@@ -60,13 +70,13 @@ export function resolveClassifierApiKey({ apiKeyNames, apiKeySource, context, de
60
70
  : undefined;
61
71
  const saved = getNonEmptyString(read(read(read(context.settings, 'classifierProviders'), providerId), 'apiKey'));
62
72
  if (!saved)
63
- throw new Error(`Classifier settings API key for ${providerId} is not set. No automatic fallback is used.`);
73
+ throw new ClassifierCredentialMissingError(`Classifier settings API key for ${providerId} is not set. No automatic fallback is used.`);
64
74
  return saved;
65
75
  }
66
76
  if (apiKeySource === 'input') {
67
77
  const value = coerceTypeOptional(classifierInputDataValue(inputs, 'apiKey'), 'string')?.trim();
68
78
  if (!value)
69
- throw new Error('API Key input is required when API key source is Input port.');
79
+ throw new ClassifierCredentialMissingError('API Key input is required when API key source is Input port.');
70
80
  return value;
71
81
  }
72
82
  if (apiKeySource !== undefined && apiKeySource !== 'configured')
@@ -86,7 +96,7 @@ export function resolveClassifierApiKey({ apiKeyNames, apiKeySource, context, de
86
96
  return legacyValue;
87
97
  }
88
98
  }
89
- throw new Error(`${providerId === 'jev' ? 'Jev' : 'Classifier'} API key is not set. Pass ${names.programmaticName}, configure ${names.environmentVariableName}, or set the configured key in Settings > Classifier.`);
99
+ throw new ClassifierCredentialMissingError(`${providerId === 'jev' ? 'Jev' : 'Classifier'} API key is not set. Pass ${names.programmaticName}, configure ${names.environmentVariableName}, or set the configured key in Settings > Classifier.`);
90
100
  }
91
101
  function resolveNamedClassifierApiKey(context, names, useLegacyOpenAIKey = false) {
92
102
  const programmaticValue = getNonEmptyString(context.settings?.[names.programmaticName]);