@valerypopoff/rivet2-core 2.1.8 → 2.1.10

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 (168) hide show
  1. package/dist/cjs/bundle.cjs +4457 -1809
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/webAppRuntime.cjs +298 -21
  4. package/dist/cjs/webAppRuntime.cjs.map +4 -4
  5. package/dist/esm/exports.js +1 -0
  6. package/dist/esm/model/AgentResponseTrace.js +448 -0
  7. package/dist/esm/model/ConnectedToolContinuationHost.js +33 -0
  8. package/dist/esm/model/GraphProcessor.js +152 -74
  9. package/dist/esm/model/NodeImpl.js +6 -0
  10. package/dist/esm/model/ProcessContextBuilder.js +3 -1
  11. package/dist/esm/model/RecordingPlayer.js +164 -22
  12. package/dist/esm/model/SplitRunProcessor.js +68 -18
  13. package/dist/esm/model/SubprocessorBridge.js +2 -0
  14. package/dist/esm/model/ToolCallContinuationCoordinator.js +13 -4
  15. package/dist/esm/model/UiGraph.js +21 -0
  16. package/dist/esm/model/UiGraphActionProtocol.js +2 -0
  17. package/dist/esm/model/UiGraphBrowserRuntime.js +133 -4
  18. package/dist/esm/model/UiGraphRendererStyles.js +221 -0
  19. package/dist/esm/model/UiGraphRuntimeModel.js +9 -3
  20. package/dist/esm/model/UiGraphSchema.js +7 -1
  21. package/dist/esm/model/chat/aiSdkMessages.js +8 -0
  22. package/dist/esm/model/chat/aiSdkTools.js +3 -2
  23. package/dist/esm/model/chat-v2/chatV2CallObserver.js +11 -5
  24. package/dist/esm/model/chat-v2/chatV2EditorCache.js +58 -10
  25. package/dist/esm/model/chat-v2/chatV2Errors.js +7 -19
  26. package/dist/esm/model/chat-v2/chatV2FeatureCompatibility.js +1 -1
  27. package/dist/esm/model/chat-v2/chatV2Outputs.js +56 -106
  28. package/dist/esm/model/chat-v2/chatV2Pipeline.js +142 -149
  29. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +9 -2
  30. package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +9 -0
  31. package/dist/esm/model/chat-v2/chatV2RequestPlan.js +5 -5
  32. package/dist/esm/model/chat-v2/chatV2ResponseBodyCapture.js +55 -0
  33. package/dist/esm/model/chat-v2/chatV2ResponseFormat.js +8 -4
  34. package/dist/esm/model/chat-v2/chatV2Retry.js +4 -3
  35. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +6 -1
  36. package/dist/esm/model/chat-v2/chatV2Shared.js +1 -6
  37. package/dist/esm/model/chat-v2/chatV2Types.js +7 -1
  38. package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +78 -0
  39. package/dist/esm/model/chat-v2/customProviderApi.js +42 -0
  40. package/dist/esm/model/chat-v2/developerMessageRoles.js +45 -0
  41. package/dist/esm/model/chat-v2/index.js +12 -0
  42. package/dist/esm/model/chat-v2/llmChatV2Body.js +281 -0
  43. package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +32 -0
  44. package/dist/esm/model/chat-v2/llmChatV2CachePolicy.js +20 -0
  45. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +8 -54
  46. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +41 -20
  47. package/dist/esm/model/chat-v2/llmChatV2NodeMigration.js +24 -0
  48. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +178 -94
  49. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +60 -0
  50. package/dist/esm/model/chat-v2/llmInvocationDecision.js +11 -0
  51. package/dist/esm/model/chat-v2/llmInvocationJournal.js +43 -0
  52. package/dist/esm/model/chat-v2/llmInvocationPlan.js +68 -0
  53. package/dist/esm/model/chat-v2/llmInvocationProjections.js +5 -0
  54. package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +48 -0
  55. package/dist/esm/model/chat-v2/llmModelCandidate.js +75 -0
  56. package/dist/esm/model/chat-v2/llmProfile.js +31 -65
  57. package/dist/esm/model/chat-v2/llmProfileBody.js +183 -0
  58. package/dist/esm/model/chat-v2/llmProfileFallback.js +244 -0
  59. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +67 -0
  60. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +3 -0
  61. package/dist/esm/model/chat-v2/llmProfileTypes.js +1 -18
  62. package/dist/esm/model/chat-v2/llmResponseMaterializer.js +42 -0
  63. package/dist/esm/model/chat-v2/messageConverter.js +14 -0
  64. package/dist/esm/model/chat-v2/modelRegistry.js +54 -4
  65. package/dist/esm/model/chat-v2/parallelToolCalls.js +9 -2
  66. package/dist/esm/model/chat-v2/providerOptions.js +120 -21
  67. package/dist/esm/model/chat-v2/rivetToolRegistry.js +9 -0
  68. package/dist/esm/model/chat-v2/toolCallCodec.js +52 -0
  69. package/dist/esm/model/chat-v2/toolContinuation.js +72 -39
  70. package/dist/esm/model/chat-v2/toolHandlerResolver.js +23 -0
  71. package/dist/esm/model/chat-v2/toolRoundExecutor.js +12 -0
  72. package/dist/esm/model/nodes/AssembleMessageNode.js +6 -0
  73. package/dist/esm/model/nodes/ChatNode.js +6 -0
  74. package/dist/esm/model/nodes/ChatNodeBase.js +1 -0
  75. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +26 -1
  76. package/dist/esm/model/nodes/LLMChatV2Node.js +131 -144
  77. package/dist/esm/model/nodes/LLMProfileNode.js +27 -8
  78. package/dist/esm/model/nodes/PromptNode.js +16 -2
  79. package/dist/esm/model/nodes/ToolNode.js +7 -0
  80. package/dist/esm/model/nodes/toolCallDelegation.js +193 -110
  81. package/dist/esm/plugins/anthropic/anthropic.js +4 -4
  82. package/dist/esm/plugins/anthropic/nodes/ChatAnthropicNode.js +29 -28
  83. package/dist/esm/plugins/google/google.js +25 -18
  84. package/dist/esm/plugins/google/nodes/ChatGoogleNode.js +21 -7
  85. package/dist/esm/recording/ExecutionRecorder.js +13 -5
  86. package/dist/esm/utils/chatMessageToOpenAIChatCompletionMessage.js +4 -0
  87. package/dist/esm/utils/emitDetached.js +6 -3
  88. package/dist/esm/utils/openai.js +60 -16
  89. package/dist/esm/utils/serialization/serialization.js +2 -0
  90. package/dist/esm/webAppRuntime.js +3 -2
  91. package/dist/types/exports.d.ts +1 -0
  92. package/dist/types/model/AgentResponseTrace.d.ts +110 -0
  93. package/dist/types/model/ConnectedToolContinuationHost.d.ts +34 -0
  94. package/dist/types/model/DataValue.d.ts +7 -1
  95. package/dist/types/model/ExecutorProtocol.d.ts +25 -7
  96. package/dist/types/model/GraphProcessor.d.ts +27 -5
  97. package/dist/types/model/NodeBase.d.ts +6 -0
  98. package/dist/types/model/NodeImpl.d.ts +18 -1
  99. package/dist/types/model/Nodes.d.ts +2 -2
  100. package/dist/types/model/ProcessContext.d.ts +51 -0
  101. package/dist/types/model/ProcessContextBuilder.d.ts +3 -1
  102. package/dist/types/model/RecordingPlayer.d.ts +6 -0
  103. package/dist/types/model/SplitRunProcessor.d.ts +11 -3
  104. package/dist/types/model/UiGraph.d.ts +8 -0
  105. package/dist/types/model/UiGraphActionProtocol.d.ts +2 -0
  106. package/dist/types/model/UiGraphBrowserRuntime.d.ts +11 -2
  107. package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
  108. package/dist/types/model/UiGraphRuntimeModel.d.ts +2 -0
  109. package/dist/types/model/UiGraphSchema.d.ts +1 -0
  110. package/dist/types/model/chat-v2/chatV2CallObserver.d.ts +2 -0
  111. package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +3 -1
  112. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +7 -17
  113. package/dist/types/model/chat-v2/chatV2Pipeline.d.ts +29 -0
  114. package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +5 -0
  115. package/dist/types/model/chat-v2/chatV2ProviderRegistry.d.ts +8 -0
  116. package/dist/types/model/chat-v2/chatV2RequestPlan.d.ts +2 -2
  117. package/dist/types/model/chat-v2/chatV2ResponseBodyCapture.d.ts +19 -0
  118. package/dist/types/model/chat-v2/chatV2ResponseFormat.d.ts +3 -2
  119. package/dist/types/model/chat-v2/chatV2Retry.d.ts +2 -0
  120. package/dist/types/model/chat-v2/chatV2Shared.d.ts +0 -1
  121. package/dist/types/model/chat-v2/chatV2Types.d.ts +35 -1
  122. package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +14 -0
  123. package/dist/types/model/chat-v2/customProviderApi.d.ts +23 -0
  124. package/dist/types/model/chat-v2/developerMessageRoles.d.ts +10 -0
  125. package/dist/types/model/chat-v2/index.d.ts +12 -0
  126. package/dist/types/model/chat-v2/llmChatV2Body.d.ts +24 -0
  127. package/dist/types/model/chat-v2/llmChatV2CacheBoundary.d.ts +10 -0
  128. package/dist/types/model/chat-v2/llmChatV2CachePolicy.d.ts +13 -0
  129. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +13 -3
  130. package/dist/types/model/chat-v2/llmChatV2NodeMigration.d.ts +8 -0
  131. package/dist/types/model/chat-v2/llmChatV2NodeRuntime.d.ts +18 -4
  132. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +16 -0
  133. package/dist/types/model/chat-v2/llmInvocationDecision.d.ts +21 -0
  134. package/dist/types/model/chat-v2/llmInvocationJournal.d.ts +38 -0
  135. package/dist/types/model/chat-v2/llmInvocationPlan.d.ts +41 -0
  136. package/dist/types/model/chat-v2/llmInvocationProjections.d.ts +3 -0
  137. package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +26 -0
  138. package/dist/types/model/chat-v2/llmModelCandidate.d.ts +18 -0
  139. package/dist/types/model/chat-v2/llmProfile.d.ts +7 -0
  140. package/dist/types/model/chat-v2/llmProfileBody.d.ts +20 -0
  141. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +47 -0
  142. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +189 -0
  143. package/dist/types/model/chat-v2/llmProfileTypes.d.ts +1 -1
  144. package/dist/types/model/chat-v2/llmResponseMaterializer.d.ts +20 -0
  145. package/dist/types/model/chat-v2/modelRegistry.d.ts +17 -187
  146. package/dist/types/model/chat-v2/parallelToolCalls.d.ts +3 -1
  147. package/dist/types/model/chat-v2/providerOptions.d.ts +11 -0
  148. package/dist/types/model/chat-v2/rivetToolRegistry.d.ts +11 -0
  149. package/dist/types/model/chat-v2/toolCallCodec.d.ts +7 -0
  150. package/dist/types/model/chat-v2/toolContinuation.d.ts +3 -3
  151. package/dist/types/model/chat-v2/toolHandlerResolver.d.ts +25 -0
  152. package/dist/types/model/chat-v2/toolRoundExecutor.d.ts +18 -0
  153. package/dist/types/model/nodes/AssembleMessageNode.d.ts +2 -1
  154. package/dist/types/model/nodes/ChatNode.d.ts +2 -1
  155. package/dist/types/model/nodes/DelegateFunctionCallNode.d.ts +2 -1
  156. package/dist/types/model/nodes/LLMChatV2Node.d.ts +2 -1
  157. package/dist/types/model/nodes/LLMProfileNode.d.ts +2 -1
  158. package/dist/types/model/nodes/PromptNode.d.ts +6 -3
  159. package/dist/types/model/nodes/ToolNode.d.ts +2 -1
  160. package/dist/types/model/nodes/toolCallDelegation.d.ts +10 -3
  161. package/dist/types/plugins/anthropic/anthropic.d.ts +1 -0
  162. package/dist/types/plugins/google/google.d.ts +14 -9
  163. package/dist/types/plugins/google/nodes/ChatGoogleNode.d.ts +2 -1
  164. package/dist/types/recording/RecordedEvents.d.ts +6 -0
  165. package/dist/types/utils/emitDetached.d.ts +3 -2
  166. package/dist/types/utils/openai.d.ts +49 -0
  167. package/dist/types/webAppRuntime.d.ts +4 -2
  168. package/package.json +2 -2
@@ -4,49 +4,36 @@ import { createObservedChatV2CallId, notifyChatV2CallFinished } from './chatV2Ca
4
4
  import { chatMessagesToModelMessages } from './messageConverter.js';
5
5
  import { chatV2ToolsToAiSdk } from './toolConverter.js';
6
6
  import { buildChatV2RequestPlan } from './chatV2RequestPlan.js';
7
- import { getChatV2ProviderErrorStatusCode, isChatV2ProviderApiCallError, isChatV2ProviderFetchError, normalizeChatV2ProviderError, } from './chatV2Errors.js';
8
- import { waitForLLMChatV2RetryCooldown } from './chatV2Retry.js';
9
- import { createChatV2CommonOutputs, createChatV2ProviderFailureOutputs, normalizeChatV2Usage, } from './chatV2Outputs.js';
10
- class ChatV2RetryFailure extends Error {
11
- error;
12
- requestStatuses;
13
- requestErrors;
14
- constructor(error, requestStatuses, requestErrors) {
15
- super('Chat v2 retry attempts failed');
16
- this.error = error;
17
- this.requestStatuses = requestStatuses;
18
- this.requestErrors = requestErrors;
19
- this.name = 'ChatV2RetryFailure';
20
- }
21
- }
22
- function isChatV2RetryFailure(error) {
23
- return error instanceof ChatV2RetryFailure;
7
+ import { getChatV2ProviderErrorStatusCode, normalizeChatV2ProviderError, } from './chatV2Errors.js';
8
+ import { createLLMChatV2RetryAbortError, waitForLLMChatV2RetryCooldown } from './chatV2Retry.js';
9
+ import { createChatV2CommonOutputs, normalizeChatV2Usage, } from './chatV2Outputs.js';
10
+ import { materializeLLMResponse } from './llmResponseMaterializer.js';
11
+ /** Identifies legacy pipeline results that represent a terminal provider failure. */
12
+ export function isChatV2PipelineProviderFailureResult(result) {
13
+ return result.terminalOutcome === 'provider-failure';
24
14
  }
25
- function getProviderFailureMessage(error) {
26
- try {
27
- if (error instanceof Error && typeof error.message === 'string') {
28
- return error.message;
29
- }
30
- }
31
- catch {
32
- return 'Provider request failed with unreadable error metadata.';
33
- }
34
- try {
35
- return String(error);
36
- }
37
- catch {
38
- return 'Provider request failed with unreadable error metadata.';
15
+ export class ChatV2ResponseValidationError extends Error {
16
+ responseDataType;
17
+ constructor(responseDataType) {
18
+ super('LLM profile response validation failed.\n' +
19
+ 'Response format: JSON schema\n' +
20
+ `Parsed Response type: ${responseDataType}\n` +
21
+ 'The provider request succeeded, but the final value prepared for the Response port is not an object. ' +
22
+ 'JSON schema response format requires an object, so Rivet rejected this LLM profile. ' +
23
+ 'Retry on non-200 does not apply to this validation failure.');
24
+ this.responseDataType = responseDataType;
25
+ this.name = 'ChatV2ResponseValidationError';
39
26
  }
40
27
  }
28
+ export function isChatV2ResponseValidationError(error) {
29
+ return error instanceof ChatV2ResponseValidationError;
30
+ }
41
31
  function buildNon200StatusError(statusCode) {
42
32
  const error = new Error(`Provider request returned non-200 status: ${statusCode}`);
43
33
  error.name = 'AI_APICallError';
44
34
  error.statusCode = statusCode;
45
35
  return error;
46
36
  }
47
- function normalizeProviderFailureMessage(error, options) {
48
- return getProviderFailureMessage(normalizeProviderFailure(error, options));
49
- }
50
37
  function normalizeProviderFailure(error, options) {
51
38
  try {
52
39
  return normalizeChatV2ProviderError(error, {
@@ -58,108 +45,88 @@ function normalizeProviderFailure(error, options) {
58
45
  return error;
59
46
  }
60
47
  }
61
- function normalizeProviderFailureMessages(errors, options) {
62
- return errors.map((error) => normalizeProviderFailureMessage(error, options));
48
+ function notifyProviderAttempt(options, attempt) {
49
+ try {
50
+ options.onProviderAttempt?.(attempt);
51
+ }
52
+ catch {
53
+ // Attempt diagnostics are observational and must never affect the request.
54
+ }
63
55
  }
64
56
  async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, transportMode) {
65
- const requestStatuses = [];
66
- const requestErrors = [];
67
57
  for (let attempt = 0;; attempt++) {
68
58
  const callId = createObservedChatV2CallId(options);
59
+ const callStartedAt = Date.now();
69
60
  let callWasObserved = false;
70
61
  try {
71
62
  const result = transportMode === 'generate' ? await generateChatV2(chatOptions) : await streamChatV2(chatOptions);
63
+ await options.responseBodyCapture?.flush();
72
64
  const statusCode = result.requestStatus ?? 200;
73
65
  notifyChatV2CallFinished(options, {
74
66
  callId,
75
67
  attemptIndex: attempt,
76
68
  outcome: statusCode === 200 ? 'success' : 'provider-failure',
77
69
  result,
70
+ startedAt: callStartedAt,
71
+ durationMs: Math.max(0, Date.now() - callStartedAt),
78
72
  });
79
73
  callWasObserved = true;
80
- if (retryPlan.enabled) {
81
- requestStatuses.push(statusCode);
82
- }
74
+ notifyProviderAttempt(options, {
75
+ attemptIndex: attempt,
76
+ outcome: statusCode === 200 ? 'success' : 'provider-failure',
77
+ status: statusCode,
78
+ ...(statusCode === 200 ? {} : { error: buildNon200StatusError(statusCode) }),
79
+ });
83
80
  if (!retryPlan.enabled || statusCode === 200) {
84
- return { result, requestStatuses, requestErrors };
81
+ return { result };
85
82
  }
86
83
  const responseError = buildNon200StatusError(statusCode);
87
- requestErrors.push(responseError);
88
84
  if (attempt >= retryPlan.repeatTimes) {
89
- return { result, requestStatuses, requestErrors, responseError };
85
+ return { result, responseError };
90
86
  }
91
87
  await waitForLLMChatV2RetryCooldown(retryPlan.cooldownMs, signal);
92
88
  }
93
89
  catch (error) {
90
+ await options.responseBodyCapture?.flush();
94
91
  if (!callWasObserved) {
95
92
  notifyChatV2CallFinished(options, {
96
93
  callId,
97
94
  attemptIndex: attempt,
98
95
  outcome: signal.aborted ? 'aborted' : 'provider-failure',
99
96
  error,
97
+ startedAt: callStartedAt,
98
+ durationMs: Math.max(0, Date.now() - callStartedAt),
100
99
  });
101
100
  }
102
101
  const statusCode = getChatV2ProviderErrorStatusCode(error);
102
+ notifyProviderAttempt(options, {
103
+ attemptIndex: attempt,
104
+ outcome: signal.aborted ? 'aborted' : 'provider-failure',
105
+ ...(statusCode == null ? {} : { status: statusCode }),
106
+ error,
107
+ });
108
+ if (signal.aborted) {
109
+ // The provider may reject concurrently with graph cancellation. The
110
+ // cancellation wins: it must neither retry nor masquerade as a
111
+ // provider failure to profile fallback and run activity.
112
+ throw createLLMChatV2RetryAbortError();
113
+ }
103
114
  if (!retryPlan.enabled || statusCode == null || statusCode === 200) {
104
115
  throw error;
105
116
  }
106
- requestStatuses.push(statusCode);
107
- requestErrors.push(error);
108
117
  if (attempt >= retryPlan.repeatTimes) {
109
- throw new ChatV2RetryFailure(error, requestStatuses, requestErrors);
118
+ throw error;
110
119
  }
111
120
  await waitForLLMChatV2RetryCooldown(retryPlan.cooldownMs, signal);
112
121
  }
113
122
  }
114
123
  }
115
- function buildProviderFailureResult(requestMessages, options, plan, normalizedError, rawError, requestStatuses, requestErrors) {
116
- if (!plan.output.outputRequestStatus) {
117
- return undefined;
118
- }
119
- const statusCode = getChatV2ProviderErrorStatusCode(normalizedError);
120
- if (statusCode == null && !isChatV2ProviderApiCallError(rawError) && !isChatV2ProviderFetchError(rawError)) {
121
- return undefined;
122
- }
123
- const responseError = getProviderFailureMessage(normalizedError);
124
- const retryRequestStatuses = plan.retry.enabled
125
- ? requestStatuses.length > 0
126
- ? requestStatuses
127
- : statusCode == null
128
- ? []
129
- : [statusCode]
130
- : [];
131
- const retryRequestErrors = plan.retry.enabled ? (requestErrors.length > 0 ? requestErrors : [responseError]) : [];
132
- const commonOutputs = createChatV2ProviderFailureOutputs({
133
- requestMessages,
134
- responseStatus: statusCode,
135
- responseError,
136
- requestStatuses: retryRequestStatuses,
137
- requestErrors: retryRequestErrors,
138
- requestBodies: options.requestBodies,
139
- outputUsage: plan.output.outputUsage,
140
- outputReasoning: plan.output.outputReasoning,
141
- includeFunctionCalls: plan.output.includeFunctionCalls,
142
- retryOnNon200: plan.retry.enabled,
143
- });
144
- const allMessagesOutput = commonOutputs['all-messages'];
145
- if (allMessagesOutput?.type !== 'chat-message[]') {
146
- throw new Error('Chat v2 provider failure expected all-messages output to be chat-message[].');
147
- }
148
- return {
149
- commonOutputs,
150
- requestMessages,
151
- allMessages: allMessagesOutput.value,
152
- response: '',
153
- functionCalls: [],
154
- reasoning: '',
155
- usage: undefined,
156
- rawUsage: undefined,
157
- finishReason: undefined,
158
- providerMetadata: undefined,
159
- requestStatus: statusCode,
160
- };
161
- }
162
- export async function runChatV2Pipeline(options) {
124
+ /**
125
+ * Runs one provider/model round. Provider failures stay distinct from shared
126
+ * graph configuration errors so an LLM Profile fallback chain can advance to
127
+ * its next candidate; terminal failures always remain node errors.
128
+ */
129
+ export async function runChatV2PipelineExecution(options) {
163
130
  const requestMessages = prependSystemPrompt(coercePromptToChatMessages(options.prompt, { requirePrompt: true }), options.systemPrompt);
164
131
  const modelMessages = await chatMessagesToModelMessages(requestMessages, {
165
132
  provider: options.provider,
@@ -177,57 +144,50 @@ export async function runChatV2Pipeline(options) {
177
144
  tools,
178
145
  });
179
146
  const shouldStreamResponse = plan.transportMode === 'stream';
180
- const chatResponse = await runChatV2WithRetry(options, {
181
- ...plan.request,
182
- abortSignal: options.context.signal,
183
- executeStream: options.executeStream,
184
- executeGenerate: options.executeGenerate,
185
- onPartialOutput: !shouldStreamResponse
186
- ? undefined
187
- : ({ text, functionCalls }) => {
188
- options.context.onPartialOutputs?.(createChatV2CommonOutputs({
189
- requestMessages,
190
- response: text,
191
- structuredOutput: undefined,
192
- functionCalls,
193
- usage: undefined,
194
- reasoning: '',
195
- requestStatus: undefined,
196
- responseError: undefined,
197
- requestStatuses: [],
198
- requestErrors: [],
199
- requestBodies: undefined,
200
- outputUsage: false,
201
- outputReasoning: false,
202
- outputRequestStatus: false,
203
- includeFunctionCalls: plan.output.includeFunctionCalls,
204
- functionCallMode: plan.output.functionCallMode,
205
- retryOnNon200: false,
206
- responseFormat: undefined,
207
- }));
208
- },
209
- }, plan.retry, options.context.signal, plan.transportMode).catch((caughtError) => {
210
- const retryFailure = isChatV2RetryFailure(caughtError) ? caughtError : undefined;
211
- const rawError = retryFailure?.error ?? caughtError;
212
- const normalizedError = normalizeProviderFailure(rawError, options);
213
- const requestStatuses = retryFailure?.requestStatuses ?? [];
214
- const requestErrors = normalizeProviderFailureMessages(retryFailure?.requestErrors ?? [], options);
215
- const failureResult = buildProviderFailureResult(requestMessages, options, plan, normalizedError, rawError, requestStatuses, requestErrors);
216
- if (failureResult) {
217
- return failureResult;
147
+ let chatResponse;
148
+ try {
149
+ chatResponse = await runChatV2WithRetry(options, {
150
+ ...plan.request,
151
+ abortSignal: options.context.signal,
152
+ executeStream: options.executeStream,
153
+ executeGenerate: options.executeGenerate,
154
+ onPartialOutput: !shouldStreamResponse
155
+ ? undefined
156
+ : ({ text, functionCalls }) => {
157
+ options.context.onPartialOutputs?.(createChatV2CommonOutputs({
158
+ requestMessages,
159
+ response: text,
160
+ structuredOutput: undefined,
161
+ functionCalls,
162
+ usage: undefined,
163
+ reasoning: '',
164
+ requestBodies: undefined,
165
+ responseBodies: undefined,
166
+ outputUsage: false,
167
+ outputReasoning: false,
168
+ outputRequestBody: false,
169
+ outputResponseBody: false,
170
+ includeFunctionCalls: plan.output.includeFunctionCalls,
171
+ functionCallMode: plan.output.functionCallMode,
172
+ responseFormat: undefined,
173
+ }));
174
+ },
175
+ }, plan.retry, options.context.signal, plan.transportMode);
176
+ }
177
+ catch (caughtError) {
178
+ if (options.context.signal.aborted) {
179
+ throw caughtError;
218
180
  }
219
- throw normalizedError;
220
- });
221
- if ('commonOutputs' in chatResponse) {
222
- return chatResponse;
181
+ return {
182
+ outcome: 'provider-failure',
183
+ failure: {
184
+ options,
185
+ normalizedError: normalizeProviderFailure(caughtError, options),
186
+ },
187
+ };
223
188
  }
224
189
  const usage = normalizeChatV2Usage(chatResponse.result.usage, options);
225
- const requestStatuses = chatResponse.requestStatuses;
226
190
  const requestStatus = chatResponse.result.requestStatus ?? 200;
227
- const requestErrors = normalizeProviderFailureMessages(chatResponse.requestErrors, options);
228
- const responseError = chatResponse.responseError
229
- ? normalizeProviderFailureMessage(chatResponse.responseError, options)
230
- : undefined;
231
191
  const commonOutputs = createChatV2CommonOutputs({
232
192
  requestMessages,
233
193
  response: chatResponse.result.responseText,
@@ -235,24 +195,21 @@ export async function runChatV2Pipeline(options) {
235
195
  functionCalls: chatResponse.result.functionCalls,
236
196
  usage,
237
197
  reasoning: chatResponse.result.reasoning,
238
- requestStatus,
239
- responseError,
240
- requestStatuses,
241
- requestErrors,
242
198
  requestBodies: options.requestBodies,
199
+ responseBodies: options.responseBodies,
243
200
  outputUsage: plan.output.outputUsage,
244
201
  outputReasoning: plan.output.outputReasoning,
245
- outputRequestStatus: plan.output.outputRequestStatus,
202
+ outputRequestBody: plan.output.outputRequestBody,
203
+ outputResponseBody: plan.output.outputResponseBody,
246
204
  includeFunctionCalls: plan.output.includeFunctionCalls,
247
205
  functionCallMode: plan.output.functionCallMode,
248
- retryOnNon200: plan.retry.enabled,
249
206
  responseFormat: plan.request.responseFormat,
250
207
  });
251
208
  const allMessagesOutput = commonOutputs['all-messages'];
252
209
  if (allMessagesOutput?.type !== 'chat-message[]') {
253
210
  throw new Error('Chat v2 pipeline expected all-messages output to be chat-message[].');
254
211
  }
255
- return {
212
+ const result = {
256
213
  commonOutputs,
257
214
  requestMessages,
258
215
  allMessages: allMessagesOutput.value,
@@ -265,4 +222,40 @@ export async function runChatV2Pipeline(options) {
265
222
  providerMetadata: chatResponse.result.providerMetadata,
266
223
  requestStatus,
267
224
  };
225
+ const providerRoundFailure = chatResponse.responseError ?? (requestStatus === 200 ? undefined : buildNon200StatusError(requestStatus));
226
+ if (providerRoundFailure != null) {
227
+ const rawError = providerRoundFailure;
228
+ return {
229
+ outcome: 'provider-failure',
230
+ failure: {
231
+ options,
232
+ normalizedError: normalizeProviderFailure(rawError, options),
233
+ },
234
+ };
235
+ }
236
+ // A tool-request round is not a terminal Response value. Auto-continuation
237
+ // will make another model call after delegated tools finish, so validate the
238
+ // value only once a provider round actually produces the final response.
239
+ if (plan.request.responseFormat === 'json_schema' && chatResponse.result.functionCalls.length === 0) {
240
+ const materialized = materializeLLMResponse({
241
+ rawText: chatResponse.result.responseText,
242
+ structuredOutput: chatResponse.result.structuredOutput,
243
+ responseFormat: plan.request.responseFormat,
244
+ });
245
+ if (materialized.validation === 'invalid') {
246
+ throw new ChatV2ResponseValidationError(materialized.value.type);
247
+ }
248
+ }
249
+ return { outcome: 'success', result };
250
+ }
251
+ /**
252
+ * Terminal provider failures are node errors. The fallback coordinator may
253
+ * still catch this decision boundary and advance to a later LLM Profile.
254
+ */
255
+ export function materializeChatV2PipelineFailure(failure) {
256
+ throw failure.normalizedError;
257
+ }
258
+ export async function runChatV2Pipeline(options) {
259
+ const execution = await runChatV2PipelineExecution(options);
260
+ return execution.outcome === 'success' ? execution.result : materializeChatV2PipelineFailure(execution.failure);
268
261
  }
@@ -1,5 +1,6 @@
1
1
  import { coerceTypeOptional } from '../../utils/coerceType.js';
2
2
  import { createChatV2Model, resolveChatV2ProviderConfig, } from './providerOptions.js';
3
+ import { getChatV2ProviderCapabilities } from './chatV2ProviderRegistry.js';
3
4
  function getStringSetting(settings, key) {
4
5
  const value = settings[key];
5
6
  return typeof value === 'string' && value.trim() ? value : undefined;
@@ -79,17 +80,23 @@ export async function createResolvedChatV2Provider(options) {
79
80
  ...config,
80
81
  apiKey: options.credential.value,
81
82
  onRequestBody: options.onRequestBody,
83
+ onResponseBody: options.onResponseBody,
84
+ transformRequestBody: options.transformRequestBody,
85
+ customProviderApi: options.customProviderApi,
82
86
  });
83
87
  return {
84
88
  profile: {
85
89
  provider: options.provider,
86
90
  modelId: options.modelId,
91
+ ...(options.provider === 'custom' && options.customProviderApi != null
92
+ ? { customProviderApi: options.customProviderApi }
93
+ : {}),
87
94
  baseURL: config.baseURL,
88
95
  hasCustomHeaders: Object.keys(config.headers ?? {}).length > 0,
89
96
  credential: options.credential.reference,
90
97
  capabilities: {
91
- builtInTools: options.provider === 'openai' || options.provider === 'google',
92
- structuredOutput: true,
98
+ builtInTools: getChatV2ProviderCapabilities(options.provider).builtInTools,
99
+ structuredOutput: getChatV2ProviderCapabilities(options.provider).structuredOutput,
93
100
  },
94
101
  },
95
102
  model,
@@ -0,0 +1,9 @@
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 },
6
+ };
7
+ export function getChatV2ProviderCapabilities(provider) {
8
+ return providerCapabilities[provider];
9
+ }
@@ -1,4 +1,5 @@
1
- import { normalizeLLMChatV2RetryCooldownMs, normalizeLLMChatV2RetryCount, } from './chatV2Retry.js';
1
+ import { normalizeLLMChatV2RetryCooldownMs, normalizeLLMChatV2RetryCount } from './chatV2Retry.js';
2
+ import { shouldOutputChatV2RequestBody, shouldOutputChatV2ResponseBody, } from './chatV2Types.js';
2
3
  export function buildChatV2RequestPlan(options) {
3
4
  const shouldStream = options.emitPartialOutputs !== false;
4
5
  return {
@@ -7,9 +8,7 @@ export function buildChatV2RequestPlan(options) {
7
8
  transportMode: shouldStream ? 'stream' : 'generate',
8
9
  retry: {
9
10
  enabled: options.retryOnNon200 === true,
10
- repeatTimes: options.retryOnNon200
11
- ? normalizeLLMChatV2RetryCount(options.retryOnNon200RepeatTimes)
12
- : 0,
11
+ repeatTimes: options.retryOnNon200 ? normalizeLLMChatV2RetryCount(options.retryOnNon200RepeatTimes) : 0,
13
12
  cooldownMs: normalizeLLMChatV2RetryCooldownMs(options.retryOnNon200CooldownMs),
14
13
  },
15
14
  request: {
@@ -33,7 +32,8 @@ export function buildChatV2RequestPlan(options) {
33
32
  output: {
34
33
  outputUsage: options.outputUsage,
35
34
  outputReasoning: options.outputReasoning,
36
- outputRequestStatus: options.outputRequestStatus,
35
+ outputRequestBody: shouldOutputChatV2RequestBody(options),
36
+ outputResponseBody: shouldOutputChatV2ResponseBody(options),
37
37
  includeFunctionCalls: options.includeFunctionCalls,
38
38
  functionCallMode: options.functionCallMode,
39
39
  },
@@ -0,0 +1,55 @@
1
+ function parseResponseBody(text) {
2
+ try {
3
+ return JSON.parse(text);
4
+ }
5
+ catch {
6
+ return text;
7
+ }
8
+ }
9
+ /**
10
+ * A failed clone is intentionally omitted instead of changing provider
11
+ * behavior. Captured diagnostics do not redact or truncate provider content.
12
+ * JSON is parsed only to make it inspectable as structured output; all other
13
+ * bodies remain their original text.
14
+ */
15
+ export function createChatV2ResponseBodyCapture() {
16
+ const entries = [];
17
+ const bodies = [];
18
+ return {
19
+ bodies,
20
+ capture(response) {
21
+ const entry = {
22
+ captured: false,
23
+ value: undefined,
24
+ settled: Promise.resolve(),
25
+ };
26
+ entries.push(entry);
27
+ try {
28
+ const responseClone = response.clone();
29
+ entry.settled = responseClone
30
+ .text()
31
+ .then((text) => {
32
+ entry.value = parseResponseBody(text);
33
+ entry.captured = true;
34
+ })
35
+ .catch(() => {
36
+ // The original response remains owned by the provider SDK.
37
+ });
38
+ }
39
+ catch {
40
+ // A malformed or already-consumed Response has no safe diagnostic body.
41
+ }
42
+ },
43
+ async flush() {
44
+ // New fetches are normally sequential, but continue until no capture was
45
+ // added while an earlier clone was settling.
46
+ let observedEntryCount = 0;
47
+ while (observedEntryCount < entries.length) {
48
+ const pending = entries.slice(observedEntryCount);
49
+ observedEntryCount = entries.length;
50
+ await Promise.allSettled(pending.map((entry) => entry.settled));
51
+ }
52
+ bodies.splice(0, bodies.length, ...entries.filter((entry) => entry.captured).map((entry) => entry.value));
53
+ },
54
+ };
55
+ }
@@ -1,6 +1,7 @@
1
1
  import { Output, jsonSchema } from 'ai';
2
2
  import { coerceTypeOptional } from '../../utils/coerceType.js';
3
3
  import { getInputOrData } from '../../utils/inputs.js';
4
+ import { getCustomProviderApiContract } from './customProviderApi.js';
4
5
  export function isChatV2StructuredResponseFormat(responseFormat) {
5
6
  return responseFormat === 'json' || responseFormat === 'json_schema';
6
7
  }
@@ -73,7 +74,7 @@ export function resolveChatV2ResponseFormatParameters(data, inputs) {
73
74
  schemaDescription,
74
75
  };
75
76
  }
76
- export function createChatV2ResponseOutput(parameters, provider) {
77
+ export function createChatV2ResponseOutput(parameters, provider, customProviderApi = 'completions') {
77
78
  if (parameters == null) {
78
79
  return undefined;
79
80
  }
@@ -81,7 +82,8 @@ export function createChatV2ResponseOutput(parameters, provider) {
81
82
  return Output.text();
82
83
  }
83
84
  if (parameters.responseFormat === 'json') {
84
- if (provider === 'custom') {
85
+ if (provider === 'custom' &&
86
+ getCustomProviderApiContract(customProviderApi).structuredOutput === 'raw-response-format') {
85
87
  return undefined;
86
88
  }
87
89
  return Output.json({
@@ -95,8 +97,10 @@ export function createChatV2ResponseOutput(parameters, provider) {
95
97
  description: parameters.schemaDescription,
96
98
  });
97
99
  }
98
- export function mergeCustomProviderResponseFormatOptions(provider, providerOptions, parameters) {
99
- if (provider !== 'custom' || parameters == null) {
100
+ export function mergeCustomProviderResponseFormatOptions(provider, providerOptions, parameters, customProviderApi = 'completions') {
101
+ if (provider !== 'custom' ||
102
+ getCustomProviderApiContract(customProviderApi).structuredOutput === 'sdk-output' ||
103
+ parameters == null) {
100
104
  return providerOptions;
101
105
  }
102
106
  const customOptions = providerOptions?.custom ?? {};
@@ -8,14 +8,15 @@ export function normalizeLLMChatV2RetryCooldownMs(value) {
8
8
  const cooldownMs = typeof value === 'number' && Number.isFinite(value) ? value : DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_COOLDOWN_MS;
9
9
  return Math.max(0, Math.floor(cooldownMs));
10
10
  }
11
- function buildAbortError() {
11
+ /** Keeps cancellation identity consistent before and during a retry cooldown. */
12
+ export function createLLMChatV2RetryAbortError() {
12
13
  const error = new Error('Aborted');
13
14
  error.name = 'AbortError';
14
15
  return error;
15
16
  }
16
17
  export async function waitForLLMChatV2RetryCooldown(cooldownMs, signal) {
17
18
  if (signal.aborted) {
18
- throw buildAbortError();
19
+ throw createLLMChatV2RetryAbortError();
19
20
  }
20
21
  if (cooldownMs <= 0) {
21
22
  return;
@@ -27,7 +28,7 @@ export async function waitForLLMChatV2RetryCooldown(cooldownMs, signal) {
27
28
  };
28
29
  const onAbort = () => {
29
30
  cleanup();
30
- reject(buildAbortError());
31
+ reject(createLLMChatV2RetryAbortError());
31
32
  };
32
33
  const timeout = setTimeout(() => {
33
34
  cleanup();
@@ -4,6 +4,7 @@ import { coerceTypeOptional } from '../../utils/coerceType.js';
4
4
  import { cleanHeaders, getInputOrData } from '../../utils/inputs.js';
5
5
  import { resolveChatV2Credential } from './chatV2ProviderProfile.js';
6
6
  import { applyLLMChatV2ParallelToolCallProviderOptions } from './parallelToolCalls.js';
7
+ import { getCustomProviderApiContract } from './customProviderApi.js';
7
8
  export function resolveLLMChatV2Headers(data, inputs) {
8
9
  const resolvedHeaders = data.useHeadersInput && inputs['headers'] != null
9
10
  ? coerceTypeOptional(inputs['headers'], 'object')
@@ -57,8 +58,11 @@ export function resolveLLMChatV2ExtraProviderOptions(data, inputs) {
57
58
  function resolveProviderOptions(data, inputs) {
58
59
  const providerOptions = {};
59
60
  const extraProviderOptions = resolveLLMChatV2ExtraProviderOptions(data, inputs);
61
+ const providerOptionsKey = data.provider === 'custom'
62
+ ? getCustomProviderApiContract(data.customProviderApi).providerOptionsKey
63
+ : data.provider;
60
64
  if (extraProviderOptions) {
61
- providerOptions[data.provider] = extraProviderOptions;
65
+ providerOptions[providerOptionsKey] = extraProviderOptions;
62
66
  }
63
67
  if (data.provider === 'openai') {
64
68
  const previousResponseId = data.useOpenAIPreviousResponseIdInput && inputs['previousResponseId'] != null
@@ -128,6 +132,7 @@ export function resolveLLMChatV2RuntimeProviderOptions(data, inputs) {
128
132
  provider: data.provider,
129
133
  useToolCalling: data.useToolCalling,
130
134
  parallelToolCalls: data.parallelToolCalls,
135
+ customProviderApi: data.customProviderApi,
131
136
  providerOptions: resolveProviderOptions(data, inputs),
132
137
  });
133
138
  return providerOptions != null && Object.keys(providerOptions).length > 0 ? providerOptions : undefined;
@@ -121,7 +121,7 @@ export function getCommonChatV2Inputs(data, options = {}) {
121
121
  return inputs;
122
122
  }
123
123
  export function getCommonChatV2Outputs(data, options = {}) {
124
- const { responsePortId = 'response', inMessagesPortId = 'in-messages', allMessagesPortId = 'all-messages', functionCallsPortId = 'function-calls', responseTokensPortId = 'responseTokens', usagePortId = 'usage', reasoningPortId = 'reasoning', includeFunctionCalls = data.useToolCalling, includeUsage = data.outputUsage, includeReasoning = data.outputReasoning, } = options;
124
+ const { responsePortId = 'response', inMessagesPortId = 'in-messages', allMessagesPortId = 'all-messages', functionCallsPortId = 'function-calls', usagePortId = 'usage', reasoningPortId = 'reasoning', includeFunctionCalls = data.useToolCalling, includeUsage = data.outputUsage, includeReasoning = data.outputReasoning, } = options;
125
125
  const outputs = [
126
126
  {
127
127
  id: responsePortId,
@@ -138,11 +138,6 @@ export function getCommonChatV2Outputs(data, options = {}) {
138
138
  title: 'All Messages',
139
139
  dataType: 'chat-message[]',
140
140
  },
141
- {
142
- id: responseTokensPortId,
143
- title: 'Response Tokens',
144
- dataType: 'number',
145
- },
146
141
  ];
147
142
  if (includeFunctionCalls) {
148
143
  outputs.push({
@@ -1 +1,7 @@
1
- export {};
1
+ export function shouldOutputChatV2RequestBody(options) {
2
+ return options.outputRequestBody === true;
3
+ }
4
+ /** New diagnostics are opt-in; old status-detail nodes never expose responses. */
5
+ export function shouldOutputChatV2ResponseBody(options) {
6
+ return options.outputResponseBody === true;
7
+ }