@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,23 +1,72 @@
1
1
  import { getGraphAbortReasonFromSignal } from './GraphAbortReasons.js';
2
+ import { logRuntimeWarn } from '../utils/runtimeLogging.js';
3
+ /** Drain before invoking disposers so cleanup is exhaustive and reentrant/idempotent. */
4
+ function releaseSubscriptions(...groups) {
5
+ const errors = [];
6
+ const subscriptions = groups.flatMap((group) => group.splice(0));
7
+ for (const unsubscribe of subscriptions) {
8
+ try {
9
+ unsubscribe();
10
+ }
11
+ catch (error) {
12
+ errors.push(error);
13
+ }
14
+ }
15
+ if (errors.length)
16
+ throw new AggregateError(errors, 'Failed to release child execution subscriptions');
17
+ }
18
+ function rollbackSubscriptions(error, ...groups) {
19
+ try {
20
+ releaseSubscriptions(...groups);
21
+ }
22
+ catch {
23
+ // Setup failure remains authoritative; every acquired disposer was attempted.
24
+ }
25
+ throw error;
26
+ }
27
+ /** Cleanup must not replace an execution/setup failure already being propagated. */
28
+ export function cleanupSubprocessorBindings(lifecycle, events, executionFailed) {
29
+ try {
30
+ releaseSubscriptions(lifecycle ? [lifecycle] : [], events ? [events] : []);
31
+ }
32
+ catch (error) {
33
+ if (!executionFailed)
34
+ throw error;
35
+ // Disposer errors may contain authored data. Keep secondary failure visible
36
+ // without logging messages or changing the primary Error identity.
37
+ try {
38
+ logRuntimeWarn('Child execution cleanup failed after an execution or setup failure.', {
39
+ failedBindings: error instanceof AggregateError ? error.errors.length : 1,
40
+ });
41
+ }
42
+ catch {
43
+ // A host-provided logger must not replace the primary failure either.
44
+ }
45
+ }
46
+ }
2
47
  function subscribeOwnGraphRunLifecycle(processor, onLifecycleEvent) {
3
48
  let ownGraphRunId;
4
- const unsubscribeGraphStart = processor.on('graphStart', (event) => {
5
- ownGraphRunId ??= event.execution.graphRunId;
6
- });
7
- const onPossibleLifecycleEvent = (event) => {
49
+ const onPossibleLifecycleEvent = (event, executionFailed) => {
8
50
  if (ownGraphRunId != null && event.execution.graphRunId === ownGraphRunId) {
9
- onLifecycleEvent();
51
+ if (executionFailed)
52
+ cleanupSubprocessorBindings(onLifecycleEvent, undefined, true);
53
+ else
54
+ onLifecycleEvent();
10
55
  }
11
56
  };
12
- const unsubscribeGraphFinish = processor.on('graphFinish', onPossibleLifecycleEvent);
13
- const unsubscribeGraphAbort = processor.on('graphAbort', onPossibleLifecycleEvent);
14
- const unsubscribeGraphError = processor.on('graphError', onPossibleLifecycleEvent);
15
- return () => {
16
- unsubscribeGraphStart();
17
- unsubscribeGraphFinish();
18
- unsubscribeGraphAbort();
19
- unsubscribeGraphError();
20
- };
57
+ const subscriptions = [];
58
+ try {
59
+ subscriptions.push(processor.on('graphStart', (event) => {
60
+ ownGraphRunId ??= event.execution.graphRunId;
61
+ }));
62
+ subscriptions.push(processor.on('graphFinish', (event) => onPossibleLifecycleEvent(event, false)));
63
+ subscriptions.push(processor.on('graphAbort', (event) => onPossibleLifecycleEvent(event, !event.successful)));
64
+ subscriptions.push(processor.on('graphError', (event) => onPossibleLifecycleEvent(event, true)));
65
+ }
66
+ catch (error) {
67
+ rollbackSubscriptions(error, subscriptions);
68
+ }
69
+ return () => releaseSubscriptions(subscriptions);
21
70
  }
22
71
  export function wireSubprocessorEvents(processor, parentEmitter, parentState) {
23
72
  const forward = (event, data) => {
@@ -33,60 +82,54 @@ export function wireSubprocessorEvents(processor, parentEmitter, parentState) {
33
82
  // graph-level terminal event. Keep passive forwarding alive for the
34
83
  // subprocessor object lifetime so remote-debugger/recorder consumers do not
35
84
  // miss those node terminals.
36
- const passiveUnsubscribers = [
37
- processor.on('nodeError', (event) => forward('nodeError', event)),
38
- processor.on('nodeFinish', (event) => forward('nodeFinish', event)),
39
- processor.on('partialOutput', (event) => forward('partialOutput', event)),
40
- processor.on('progress', (event) => forward('progress', event)),
41
- processor.on('llmCallFinished', (event) => forward('llmCallFinished', event)),
42
- processor.on('llmChatOutputSnapshot', (event) => forward('llmChatOutputSnapshot', event)),
43
- processor.on('llmProfileAttempt', (event) => forward('llmProfileAttempt', event)),
44
- processor.on('toolCallFinished', (event) => forward('toolCallFinished', event)),
45
- processor.on('nodeExcluded', (event) => forward('nodeExcluded', event)),
46
- processor.on('nodeStart', (event) => forward('nodeStart', event)),
47
- processor.on('graphAbort', (event) => forward('graphAbort', event)),
48
- processor.on('graphError', (event) => forward('graphError', event)),
49
- processor.on('userInput', (event) => forward('userInput', event)),
50
- processor.on('graphStart', (event) => forward('graphStart', event)),
51
- processor.on('graphFinish', (event) => forward('graphFinish', event)),
52
- processor.on('nodeOutputsCleared', (event) => forward('nodeOutputsCleared', event)),
53
- processor.on('streamingOutputWatchSummary', (event) => forward('streamingOutputWatchSummary', event)),
54
- processor.on('globalSet', (event) => forward('globalSet', event)),
55
- processor.on('newAbortController', (event) => forward('newAbortController', event)),
56
- ];
57
- const controlUnsubscribers = [
58
- processor.on('pause', () => {
59
- if (!parentState.isPaused()) {
85
+ const passiveUnsubscribers = [];
86
+ const controlUnsubscribers = [];
87
+ const cleanupControls = () => releaseSubscriptions(controlUnsubscribers);
88
+ try {
89
+ const passiveEvents = [
90
+ 'nodeError',
91
+ 'nodeFinish',
92
+ 'partialOutput',
93
+ 'progress',
94
+ 'llmCallFinished',
95
+ 'llmChatOutputSnapshot',
96
+ 'llmProfileAttempt',
97
+ 'toolCallFinished',
98
+ 'nodeExcluded',
99
+ 'nodeStart',
100
+ 'graphAbort',
101
+ 'graphError',
102
+ 'userInput',
103
+ 'graphStart',
104
+ 'graphFinish',
105
+ 'nodeOutputsCleared',
106
+ 'streamingOutputWatchSummary',
107
+ 'globalSet',
108
+ 'newAbortController',
109
+ ];
110
+ for (const event of passiveEvents) {
111
+ passiveUnsubscribers.push(processor.on(event, (data) => forward(event, data)));
112
+ }
113
+ controlUnsubscribers.push(processor.on('pause', () => {
114
+ if (!parentState.isPaused())
60
115
  parentState.pause();
61
- }
62
- }),
63
- processor.on('resume', () => {
64
- if (parentState.isPaused()) {
116
+ }));
117
+ controlUnsubscribers.push(processor.on('resume', () => {
118
+ if (parentState.isPaused())
65
119
  parentState.resume();
66
- }
67
- }),
68
- ];
69
- const unsubscribeAny = processor.onAny((event, data) => {
70
- if (event.startsWith('globalSet:')) {
71
- void forward(event, data);
72
- }
73
- });
74
- let controlsCleanedUp = false;
75
- const cleanupControls = () => {
76
- if (controlsCleanedUp) {
77
- return;
120
+ }));
121
+ passiveUnsubscribers.push(processor.onAny((event, data) => {
122
+ if (event.startsWith('globalSet:'))
123
+ void forward(event, data);
124
+ }));
125
+ if (parentState.autoCleanup !== false) {
126
+ controlUnsubscribers.push(subscribeOwnGraphRunLifecycle(processor, cleanupControls));
78
127
  }
79
- controlsCleanedUp = true;
80
- controlUnsubscribers.forEach((unsubscribe) => unsubscribe());
81
- };
82
- if (parentState.autoCleanup !== false) {
83
- controlUnsubscribers.push(subscribeOwnGraphRunLifecycle(processor, cleanupControls));
84
128
  }
85
- return () => {
86
- cleanupControls();
87
- passiveUnsubscribers.forEach((unsubscribe) => unsubscribe());
88
- unsubscribeAny();
89
- };
129
+ catch (error) {
130
+ rollbackSubscriptions(error, controlUnsubscribers, passiveUnsubscribers);
131
+ }
132
+ return () => releaseSubscriptions(controlUnsubscribers, passiveUnsubscribers);
90
133
  }
91
134
  export function wireSubprocessorLifecycle(processor, options) {
92
135
  let unsubscribePendingAbort;
@@ -115,31 +158,26 @@ export function wireSubprocessorLifecycle(processor, options) {
115
158
  const resumeProcessor = () => {
116
159
  void processor.resume();
117
160
  };
118
- options.signal?.addEventListener('abort', abortFromSignal, { once: true });
119
- options.parentAbortSignal.addEventListener('abort', abortFromParent, { once: true });
120
- const unsubscribers = [
121
- () => options.signal?.removeEventListener('abort', abortFromSignal),
122
- () => options.parentAbortSignal.removeEventListener('abort', abortFromParent),
123
- () => unsubscribePendingAbort?.(),
124
- options.onParentPause(pauseProcessor),
125
- options.onParentResume(resumeProcessor),
126
- ];
127
- let cleanedUp = false;
128
- const cleanup = () => {
129
- if (cleanedUp) {
130
- return;
161
+ const unsubscribers = [];
162
+ const cleanup = () => releaseSubscriptions(unsubscribers);
163
+ try {
164
+ options.signal?.addEventListener('abort', abortFromSignal, { once: true });
165
+ unsubscribers.push(() => options.signal?.removeEventListener('abort', abortFromSignal));
166
+ options.parentAbortSignal.addEventListener('abort', abortFromParent, { once: true });
167
+ unsubscribers.push(() => options.parentAbortSignal.removeEventListener('abort', abortFromParent));
168
+ unsubscribers.push(() => unsubscribePendingAbort?.());
169
+ unsubscribers.push(options.onParentPause(pauseProcessor));
170
+ unsubscribers.push(options.onParentResume(resumeProcessor));
171
+ if (options.autoCleanup !== false) {
172
+ unsubscribers.push(subscribeOwnGraphRunLifecycle(processor, cleanup));
131
173
  }
132
- cleanedUp = true;
133
- unsubscribers.forEach((unsubscribe) => unsubscribe());
134
- };
135
- if (options.autoCleanup !== false) {
136
- unsubscribers.push(subscribeOwnGraphRunLifecycle(processor, cleanup));
137
- }
138
- if (options.signal?.aborted) {
139
- abortFromSignal();
174
+ if (options.signal?.aborted)
175
+ abortFromSignal();
176
+ else if (options.parentAbortSignal.aborted)
177
+ abortFromParent();
140
178
  }
141
- else if (options.parentAbortSignal.aborted) {
142
- abortFromParent();
179
+ catch (error) {
180
+ rollbackSubscriptions(error, unsubscribers);
143
181
  }
144
182
  return cleanup;
145
183
  }
@@ -150,7 +150,7 @@ export class ToolCallContinuationCoordinator {
150
150
  if (nodeAbortController.signal.aborted) {
151
151
  throw createGraphAbortErrorFromSignal(nodeAbortController.signal, 'Delegate Tool Call aborted');
152
152
  }
153
- const outputs = buildDelegatedToolCallOutputs([toolResult.record], hasAssistantMessage ? assistantMessage : undefined, toolResult.cost);
153
+ const outputs = buildDelegatedToolCallOutputs([toolResult.record], hasAssistantMessage ? assistantMessage : undefined, toolResult.cost, toolResult.costBreakdown);
154
154
  this.#adapter.accumulateCost(outputs);
155
155
  await this.#adapter.emitDelegateFinish(delegateNode, outputs, processId, timingStart);
156
156
  delegateFinished = true;
@@ -65,7 +65,7 @@ async function resolveGenerateStructuredOutput(result, responseOutput, finishRea
65
65
  return undefined;
66
66
  }
67
67
  }
68
- function recoverGenerateStructuredOutputError(error, options, toolCalls) {
68
+ function recoverGenerateStructuredOutputError(error, options, evidence) {
69
69
  if (options.responseOutput == null || !isChatV2StructuredResponseFormat(options.responseFormat)) {
70
70
  return undefined;
71
71
  }
@@ -80,25 +80,28 @@ function recoverGenerateStructuredOutputError(error, options, toolCalls) {
80
80
  return {
81
81
  responseText,
82
82
  structuredOutput: undefined,
83
- functionCalls: toStreamedFunctionCalls(toolCalls),
83
+ functionCalls: toStreamedFunctionCalls(evidence.toolCalls),
84
84
  usage: error.usage,
85
85
  reasoning: '',
86
86
  finishReason: error.finishReason == null ? undefined : String(error.finishReason),
87
- providerMetadata: undefined,
87
+ // Output parsing runs after onStepFinish. Keep the actual provider billing
88
+ // metadata even when the SDK rejects the generated structured value.
89
+ providerMetadata: evidence.providerMetadata,
88
90
  requestStatus: undefined,
89
91
  };
90
92
  }
91
- function attachGenerateStepToolCallCollector(args) {
92
- const toolCalls = [];
93
+ function attachGenerateStepCollector(args) {
94
+ const evidence = { toolCalls: [] };
93
95
  const previousOnStepFinish = args.onStepFinish;
94
96
  args.onStepFinish = async (event) => {
95
- const stepToolCalls = event.toolCalls;
96
- if (stepToolCalls != null) {
97
- toolCalls.push(...stepToolCalls);
97
+ const step = event;
98
+ if (step.toolCalls != null) {
99
+ evidence.toolCalls.push(...step.toolCalls);
98
100
  }
101
+ evidence.providerMetadata = step.providerMetadata;
99
102
  await previousOnStepFinish?.(event);
100
103
  };
101
- return toolCalls;
104
+ return evidence;
102
105
  }
103
106
  function collapseRepeatedStructuredJsonText(responseText) {
104
107
  if (responseText.length === 0 || responseText.length % 2 !== 0) {
@@ -363,7 +366,7 @@ export async function streamChatV2(options) {
363
366
  }
364
367
  export async function generateChatV2(options) {
365
368
  const args = buildTextArgs(options);
366
- const stepToolCalls = attachGenerateStepToolCallCollector(args);
369
+ const stepEvidence = attachGenerateStepCollector(args);
367
370
  try {
368
371
  options.onRequestStarted?.();
369
372
  }
@@ -375,7 +378,7 @@ export async function generateChatV2(options) {
375
378
  result = await waitForGeneratedResponse(Promise.resolve((options.executeGenerate ?? defaultGenerateExecutor)(args)), options);
376
379
  }
377
380
  catch (error) {
378
- const recovered = recoverGenerateStructuredOutputError(error, options, stepToolCalls);
381
+ const recovered = recoverGenerateStructuredOutputError(error, options, stepEvidence);
379
382
  if (recovered != null) {
380
383
  return recovered;
381
384
  }
@@ -383,7 +386,7 @@ export async function generateChatV2(options) {
383
386
  }
384
387
  const isStructuredOutput = isChatV2StructuredResponseFormat(options.responseFormat);
385
388
  const responseText = isStructuredOutput ? collapseRepeatedStructuredJsonText(result.text) : result.text;
386
- const functionCalls = toStreamedFunctionCalls(result.toolCalls != null && result.toolCalls.length > 0 ? result.toolCalls : stepToolCalls);
389
+ const functionCalls = toStreamedFunctionCalls(result.toolCalls != null && result.toolCalls.length > 0 ? result.toolCalls : stepEvidence.toolCalls);
387
390
  const reasoningPromise = resolveGenerateReasoning(result);
388
391
  const usagePromise = resolveGenerateUsage(result);
389
392
  let evidence = { text: responseText, functionCalls, reasoning: '' };
@@ -109,11 +109,9 @@ export function notifyChatV2CallFinished(options, params) {
109
109
  const rawUsage = safelyRead(() => copyRawUsage(resultUsage ?? errorUsage));
110
110
  const normalizedUsage = safelyRead(() => normalizeObservedUsage(rawUsage));
111
111
  const modelInfo = safelyRead(() => getChatV2ModelInfo(options.provider, options.modelId));
112
- const hasKnownPricing = modelInfo?.cost != null;
113
- const calculatedCost = hasKnownPricing
114
- ? safelyRead(() => calculateChatV2UsageCost(options.provider, options.modelId, rawUsage))
115
- : undefined;
112
+ const calculatedCost = safelyRead(() => calculateChatV2UsageCost(options.provider, options.modelId, rawUsage, params.result?.providerMetadata));
116
113
  const costUsd = toUsageNumber(calculatedCost);
114
+ const hasKnownPricing = modelInfo?.cost != null || (options.provider === 'openrouter' && costUsd != null);
117
115
  const finishReason = safelyRead(() => params.result?.finishReason) ??
118
116
  getErrorProperty(params.error, 'finishReason', (value) => typeof value === 'string');
119
117
  const event = {
@@ -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) {
@@ -290,7 +290,7 @@ export async function runChatV2PipelineExecution(options) {
290
290
  },
291
291
  };
292
292
  }
293
- const usage = normalizeChatV2Usage(chatResponse.result.usage, options);
293
+ const usage = normalizeChatV2Usage(chatResponse.result.usage, options, chatResponse.result.providerMetadata);
294
294
  const requestStatus = chatResponse.result.requestStatus ?? 200;
295
295
  const commonOutputs = createChatV2CommonOutputs({
296
296
  requestMessages,
@@ -313,6 +313,16 @@ export async function runChatV2PipelineExecution(options) {
313
313
  if (allMessagesOutput?.type !== 'chat-message[]') {
314
314
  throw new Error('Chat v2 pipeline expected all-messages output to be chat-message[].');
315
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
+ }
316
326
  const result = {
317
327
  commonOutputs,
318
328
  requestMessages,
@@ -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
  }
@@ -60,6 +60,12 @@ export function resolveLLMChatV2ExtraProviderOptions(data, inputs) {
60
60
  }
61
61
  function resolveProviderOptions(data, inputs) {
62
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
+ }
63
69
  if (data.provider === 'openai') {
64
70
  const previousResponseId = data.useOpenAIPreviousResponseIdInput && inputs['previousResponseId'] != null
65
71
  ? coerceTypeOptional(inputs['previousResponseId'], 'string')
@@ -230,6 +236,7 @@ export function resolveLLMChatV2BuiltInTools(data, context, config, apiKey) {
230
236
  return tools;
231
237
  }
232
238
  case 'anthropic':
239
+ case 'openrouter':
233
240
  return undefined;
234
241
  case 'custom':
235
242
  return undefined;
@@ -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
@@ -181,7 +181,7 @@ function getErrorBodyFields(data) {
181
181
  const cooldownMs = data.retryOnNon200CooldownMs ?? DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_COOLDOWN_MS;
182
182
  return [
183
183
  ...(data.errorOnNon200 !== false ? [{ label: 'Throw on non-2XX', value: 'Enabled' }] : []),
184
- ...(data.catchRequestFailed ? [{ label: 'Catch all failures', value: 'Enabled' }] : []),
184
+ ...(data.catchRequestFailed ? [{ label: 'Catch all exceptions', value: 'Enabled' }] : []),
185
185
  ...(data.retryOnNon200
186
186
  ? [
187
187
  { label: 'Retry on non-200', value: 'Enabled' },
@@ -235,8 +235,8 @@ function getInlineModelBodyFields(data) {
235
235
  ].filter((field) => field !== undefined);
236
236
  }
237
237
  function getParameterBodyFields(data) {
238
- const reasoningEffort = data.provider === 'openai'
239
- ? getOptionLabel(openAIReasoningEffortOptions, data.openAIReasoningEffort)
238
+ const reasoningEffort = data.provider === 'openai' || data.provider === 'openrouter'
239
+ ? getOptionLabel(openAIReasoningEffortOptions, data.provider === 'openrouter' ? data.openRouterReasoningEffort : data.openAIReasoningEffort)
240
240
  : data.provider === 'anthropic'
241
241
  ? getOptionLabel(anthropicEffortOptions, data.anthropicEffort)
242
242
  : data.provider === 'google'
@@ -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,