@valerypopoff/rivet2-core 2.1.8 → 2.1.9

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 (55) hide show
  1. package/dist/cjs/bundle.cjs +1922 -1125
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/esm/model/GraphProcessor.js +1 -0
  4. package/dist/esm/model/SplitRunProcessor.js +19 -10
  5. package/dist/esm/model/ToolCallContinuationCoordinator.js +6 -1
  6. package/dist/esm/model/chat/aiSdkMessages.js +8 -0
  7. package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -0
  8. package/dist/esm/model/chat-v2/chatV2EditorCache.js +22 -0
  9. package/dist/esm/model/chat-v2/chatV2Outputs.js +41 -31
  10. package/dist/esm/model/chat-v2/chatV2Pipeline.js +122 -44
  11. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +1 -0
  12. package/dist/esm/model/chat-v2/chatV2RequestPlan.js +6 -5
  13. package/dist/esm/model/chat-v2/chatV2Shared.js +1 -6
  14. package/dist/esm/model/chat-v2/chatV2Types.js +11 -1
  15. package/dist/esm/model/chat-v2/developerMessageRoles.js +45 -0
  16. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +3 -5
  17. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +22 -13
  18. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +224 -68
  19. package/dist/esm/model/chat-v2/llmProfile.js +21 -0
  20. package/dist/esm/model/chat-v2/llmProfileFallback.js +288 -0
  21. package/dist/esm/model/chat-v2/messageConverter.js +14 -0
  22. package/dist/esm/model/chat-v2/providerOptions.js +44 -11
  23. package/dist/esm/model/chat-v2/toolContinuation.js +0 -4
  24. package/dist/esm/model/nodes/AssembleMessageNode.js +6 -0
  25. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +12 -0
  26. package/dist/esm/model/nodes/LLMChatV2Node.js +115 -11
  27. package/dist/esm/model/nodes/PromptNode.js +9 -2
  28. package/dist/esm/model/nodes/toolCallDelegation.js +18 -2
  29. package/dist/esm/plugins/anthropic/nodes/ChatAnthropicNode.js +22 -28
  30. package/dist/esm/plugins/google/google.js +20 -9
  31. package/dist/esm/plugins/google/nodes/ChatGoogleNode.js +17 -6
  32. package/dist/esm/utils/chatMessageToOpenAIChatCompletionMessage.js +4 -0
  33. package/dist/esm/utils/serialization/serialization.js +19 -0
  34. package/dist/types/model/DataValue.d.ts +7 -1
  35. package/dist/types/model/NodeBase.d.ts +6 -0
  36. package/dist/types/model/ProcessContext.d.ts +4 -0
  37. package/dist/types/model/SplitRunProcessor.d.ts +2 -1
  38. package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +4 -0
  39. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +5 -5
  40. package/dist/types/model/chat-v2/chatV2Pipeline.d.ts +33 -0
  41. package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +1 -0
  42. package/dist/types/model/chat-v2/chatV2RequestPlan.d.ts +2 -2
  43. package/dist/types/model/chat-v2/chatV2Shared.d.ts +0 -1
  44. package/dist/types/model/chat-v2/chatV2Types.d.ts +24 -0
  45. package/dist/types/model/chat-v2/developerMessageRoles.d.ts +10 -0
  46. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +4 -1
  47. package/dist/types/model/chat-v2/llmChatV2NodeRuntime.d.ts +18 -2
  48. package/dist/types/model/chat-v2/llmProfile.d.ts +7 -0
  49. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +79 -0
  50. package/dist/types/model/chat-v2/providerOptions.d.ts +1 -0
  51. package/dist/types/model/nodes/AssembleMessageNode.d.ts +2 -1
  52. package/dist/types/model/nodes/PromptNode.d.ts +2 -2
  53. package/dist/types/plugins/google/google.d.ts +12 -1
  54. package/dist/types/plugins/google/nodes/ChatGoogleNode.d.ts +2 -1
  55. package/package.json +1 -1
@@ -1576,6 +1576,7 @@ export class GraphProcessor {
1576
1576
  async #processSplitRunNode(node, processId) {
1577
1577
  return processSplitRunNode(node, processId, {
1578
1578
  getInputValues: (n) => this.#getInputValuesForNode(n),
1579
+ getInputDefinitions: (n) => this.#definitions[n.id]?.inputs ?? [],
1579
1580
  isExcludedDueToControlFlow: (n, inputs, pid) => this.#excludedDueToControlFlow(n, inputs, pid) !== false,
1580
1581
  processNodeWithInputData: (n, inputs, idx, pid, partial) => this.#processNodeWithInputData(n, inputs, idx, pid, partial),
1581
1582
  splitRunConcurrency: this.#concurrency.splitRunConcurrency,
@@ -4,7 +4,7 @@ import {} from './NodeBase.js';
4
4
  import { getGraphAbortReasonFromError, isAbortLikeError } from './GraphAbortReasons.js';
5
5
  import { getError } from '../utils/errors.js';
6
6
  import PQueue from '../utils/pQueueCompat.js';
7
- import { entries, fromEntries, values } from '../utils/typeSafety.js';
7
+ import { entries, fromEntries } from '../utils/typeSafety.js';
8
8
  function withOptionalDuration(payload, durationMs, splitRunDurationMs) {
9
9
  return {
10
10
  ...payload,
@@ -17,17 +17,22 @@ export async function processSplitRunNode(node, processId, deps) {
17
17
  if (deps.isExcludedDueToControlFlow(node, inputValues, processId)) {
18
18
  return;
19
19
  }
20
- const splittingAmount = Math.min(max(values(inputValues).map((value) => (Array.isArray(value?.value) ? value?.value.length : 1))) ?? 1, node.splitRunMax ?? 10);
20
+ const inputDefinitionsById = new Map(deps.getInputDefinitions(node).map((definition) => [definition.id, definition]));
21
+ const splittingAmount = Math.min(max(entries(inputValues).map(([portId, value]) => inputDefinitionsById.get(portId)?.splitRunBehavior === 'preserve-array'
22
+ ? 1
23
+ : Array.isArray(value?.value)
24
+ ? value.value.length
25
+ : 1)) ?? 1, node.splitRunMax ?? 10);
21
26
  await deps.emit('nodeStart', { node, inputs: inputValues, processId });
22
27
  const timingStart = deps.startNodeTiming?.();
23
28
  let splitRunDurationMs;
24
29
  try {
25
30
  let results;
26
31
  if (node.isSplitSequential) {
27
- results = await runSequential(node, inputValues, splittingAmount, processId, deps);
32
+ results = await runSequential(node, inputValues, inputDefinitionsById, splittingAmount, processId, deps);
28
33
  }
29
34
  else {
30
- results = await runParallel(node, inputValues, splittingAmount, processId, deps);
35
+ results = await runParallel(node, inputValues, inputDefinitionsById, splittingAmount, processId, deps);
31
36
  }
32
37
  splitRunDurationMs = getSplitRunDurationMs(results);
33
38
  const errors = results.filter((r) => r.type === 'error').map((r) => r.error);
@@ -53,13 +58,13 @@ export async function processSplitRunNode(node, processId, deps) {
53
58
  await deps.nodeErrored(node, error, processId, deps.finishNodeTiming?.(timingStart), splitRunDurationMs);
54
59
  }
55
60
  }
56
- async function runSequential(node, inputValues, splittingAmount, processId, deps) {
61
+ async function runSequential(node, inputValues, inputDefinitionsById, splittingAmount, processId, deps) {
57
62
  const results = [];
58
63
  for (let i = 0; i < splittingAmount; i++) {
59
64
  if (deps.isAborted()) {
60
65
  throw deps.getAbortError();
61
66
  }
62
- const inputs = splitInputsAtIndex(inputValues, i);
67
+ const inputs = splitInputsAtIndex(inputValues, inputDefinitionsById, i);
63
68
  const splitTimingStart = deps.startNodeTiming?.();
64
69
  try {
65
70
  const output = await deps.processNodeWithInputData(node, inputs, i, processId, (n, partialOutputs, index) => {
@@ -74,7 +79,7 @@ async function runSequential(node, inputValues, splittingAmount, processId, deps
74
79
  }
75
80
  return results;
76
81
  }
77
- async function runParallel(node, inputValues, splittingAmount, processId, deps) {
82
+ async function runParallel(node, inputValues, inputDefinitionsById, splittingAmount, processId, deps) {
78
83
  const queue = new PQueue({ concurrency: getParallelSplitRunConcurrency(node, deps.splitRunConcurrency) });
79
84
  return Promise.all(range(0, splittingAmount).map(async (i) => {
80
85
  const result = await queue.add(async () => {
@@ -83,7 +88,7 @@ async function runParallel(node, inputValues, splittingAmount, processId, deps)
83
88
  if (deps.isAborted()) {
84
89
  throw deps.getAbortError();
85
90
  }
86
- const inputs = splitInputsAtIndex(inputValues, i);
91
+ const inputs = splitInputsAtIndex(inputValues, inputDefinitionsById, i);
87
92
  const output = await deps.processNodeWithInputData(node, inputs, i, processId, (n, partialOutputs, index) => {
88
93
  deps.emit('partialOutput', { node: n, outputs: partialOutputs, index, processId });
89
94
  });
@@ -108,10 +113,14 @@ function getParallelSplitRunConcurrency(node, defaultConcurrency) {
108
113
  const value = node.splitRunConcurrency;
109
114
  return typeof value === 'number' && Number.isFinite(value) && value >= 2 ? Math.floor(value) : defaultConcurrency;
110
115
  }
111
- function splitInputsAtIndex(inputValues, index) {
116
+ function splitInputsAtIndex(inputValues, inputDefinitionsById, index) {
112
117
  return fromEntries(entries(inputValues).map(([port, value]) => [
113
118
  port,
114
- isArrayDataValue(value) ? arrayizeDataValue(value)[index] ?? undefined : value,
119
+ inputDefinitionsById.get(port)?.splitRunBehavior === 'preserve-array'
120
+ ? value
121
+ : isArrayDataValue(value)
122
+ ? arrayizeDataValue(value)[index] ?? undefined
123
+ : value,
115
124
  ]));
116
125
  }
117
126
  function aggregateOutputs(results) {
@@ -153,7 +153,12 @@ export class ToolCallContinuationCoordinator {
153
153
  delegateFinished = true;
154
154
  const finalBranch = canRunContinuationBranches
155
155
  ? await branchAdapter.runOutputBranch({
156
- activeOutputPortIds: new Set(['output', 'message']),
156
+ activeOutputPortIds: new Set([
157
+ 'tool-name',
158
+ 'tool-arguments',
159
+ 'output',
160
+ 'message',
161
+ ]),
157
162
  availableNodeOutputs: preToolBranch.nodeOutputs,
158
163
  deferGraphOutputCommit: true,
159
164
  excludedNodeIds: continuationBranchBoundaries,
@@ -43,6 +43,14 @@ export async function rivetMessagesToAiSdk(messages) {
43
43
  });
44
44
  break;
45
45
  }
46
+ case 'developer': {
47
+ // ModelMessage has no provider-neutral developer role.
48
+ result.push({
49
+ role: 'system',
50
+ content: stringifyParts(msg.message),
51
+ });
52
+ break;
53
+ }
46
54
  case 'user': {
47
55
  const parts = Array.isArray(msg.message) ? msg.message : [msg.message];
48
56
  if (parts.length === 1 && typeof parts[0] === 'string') {
@@ -118,6 +118,8 @@ export function notifyChatV2CallFinished(options, params) {
118
118
  const event = {
119
119
  callId: params.callId,
120
120
  attemptIndex: params.attemptIndex,
121
+ ...(options.profileIndex == null ? {} : { profileIndex: options.profileIndex }),
122
+ ...(options.roundIndex == null ? {} : { roundIndex: options.roundIndex }),
121
123
  nodeId,
122
124
  processId,
123
125
  provider: options.provider,
@@ -78,6 +78,22 @@ function fingerprintProviderOptionsForCache(providerOptions) {
78
78
  }
79
79
  return fingerprintSecret(stableStringify(providerOptions) ?? '');
80
80
  }
81
+ function fingerprintProfileChainForCache(data, profiles) {
82
+ if (profiles == null) {
83
+ return undefined;
84
+ }
85
+ return profiles.map((profile) => ({
86
+ configuration: fingerprintNodeDataForCache({
87
+ ...data,
88
+ ...profile.configuration,
89
+ configurationMode: 'profile',
90
+ }),
91
+ credential: {
92
+ reference: profile.credential.reference,
93
+ value: fingerprintSecret(profile.credential.value),
94
+ },
95
+ }));
96
+ }
81
97
  export function resolveLLMChatV2EditorCache(params) {
82
98
  const { editorCache } = params;
83
99
  if (editorCache == null) {
@@ -97,6 +113,12 @@ export function resolveLLMChatV2EditorCache(params) {
97
113
  responseFormatParameters: params.responseFormatParameters,
98
114
  providerOptions: fingerprintProviderOptionsForCache(params.providerOptions),
99
115
  toolChoice: params.toolChoice,
116
+ profileChain: params.profileChain == null
117
+ ? undefined
118
+ : {
119
+ inputWasArray: params.profileChainUsesArray ?? false,
120
+ profiles: fingerprintProfileChainForCache(params.data, params.profileChain),
121
+ },
100
122
  });
101
123
  return {
102
124
  cacheKey,
@@ -2,6 +2,7 @@ import { inferType } from '../../utils/coerceType.js';
2
2
  import { createAssistantMessagesOutput } from '../chat/streamChatResponse.js';
3
3
  import { isChatV2StructuredResponseFormat } from './chatV2ResponseFormat.js';
4
4
  import { calculateChatV2Cost } from './modelRegistry.js';
5
+ import { shouldOutputChatV2RequestBody, shouldOutputChatV2RequestError, } from './chatV2Types.js';
5
6
  const CHAT_V2_REQUEST_STATUS_PORT_ID = 'requestStatus';
6
7
  const CHAT_V2_REQUEST_ERROR_PORT_ID = 'requestError';
7
8
  const CHAT_V2_REQUEST_BODY_PORT_ID = 'requestBody';
@@ -92,23 +93,22 @@ function createChatV2RetryAttemptOutput(type, values) {
92
93
  }
93
94
  : createControlFlowExcludedOutput();
94
95
  }
95
- export function createChatV2CommonOutputs({ requestMessages, response, structuredOutput, functionCalls, usage, reasoning, requestStatus, responseError, requestStatuses, requestErrors, requestBodies, outputUsage, outputReasoning, outputRequestStatus, includeFunctionCalls, functionCallMode, retryOnNon200, responseFormat, }) {
96
+ export function createChatV2CommonOutputs({ requestMessages, response, structuredOutput, functionCalls, usage, reasoning, requestStatus, responseError, requestStatuses, requestErrors, requestBodies, outputUsage, outputReasoning, outputRequestStatus, outputRequestError, outputRequestBody, includeFunctionCalls, functionCallMode, retryOnNon200, responseFormat, }) {
96
97
  const outputs = {
97
98
  ['response']: createChatV2ResponseOutput(response, structuredOutput, responseFormat),
98
99
  ['in-messages']: { type: 'chat-message[]', value: requestMessages },
99
100
  ['all-messages']: createAssistantMessagesOutput(requestMessages, response, functionCalls, {
100
101
  functionCallMode,
101
102
  }),
102
- ['responseTokens']: { type: 'number', value: usage?.completionTokens ?? 0 },
103
103
  };
104
- if (functionCalls.length > 0) {
105
- outputs['function-calls'] = {
106
- type: 'object[]',
107
- value: functionCalls.map(toFunctionCallOutputValue),
108
- };
109
- }
110
- else if (includeFunctionCalls) {
111
- outputs['function-calls'] = createControlFlowExcludedOutput();
104
+ if (includeFunctionCalls) {
105
+ outputs['function-calls'] =
106
+ functionCalls.length > 0
107
+ ? {
108
+ type: 'object[]',
109
+ value: functionCalls.map(toFunctionCallOutputValue),
110
+ }
111
+ : createControlFlowExcludedOutput();
112
112
  }
113
113
  if (outputUsage) {
114
114
  outputs['usage'] = {
@@ -129,13 +129,19 @@ export function createChatV2CommonOutputs({ requestMessages, response, structure
129
129
  if (outputRequestStatus) {
130
130
  if (retryOnNon200) {
131
131
  outputs[CHAT_V2_REQUEST_STATUS_PORT_ID] = createChatV2RetryAttemptOutput('number[]', requestStatuses.length > 0 ? requestStatuses : [requestStatus ?? 200]);
132
- outputs[CHAT_V2_REQUEST_ERROR_PORT_ID] = createChatV2RetryAttemptOutput('string[]', requestErrors);
133
132
  }
134
133
  else {
135
134
  outputs[CHAT_V2_REQUEST_STATUS_PORT_ID] = {
136
135
  type: 'number',
137
136
  value: requestStatus ?? 200,
138
137
  };
138
+ }
139
+ }
140
+ if (shouldOutputChatV2RequestError({ outputRequestStatus, outputRequestError })) {
141
+ if (retryOnNon200) {
142
+ outputs[CHAT_V2_REQUEST_ERROR_PORT_ID] = createChatV2RetryAttemptOutput('string[]', requestErrors);
143
+ }
144
+ else {
139
145
  outputs[CHAT_V2_REQUEST_ERROR_PORT_ID] =
140
146
  responseError != null
141
147
  ? {
@@ -144,29 +150,14 @@ export function createChatV2CommonOutputs({ requestMessages, response, structure
144
150
  }
145
151
  : createControlFlowExcludedOutput();
146
152
  }
153
+ }
154
+ if (shouldOutputChatV2RequestBody({ outputRequestStatus, outputRequestBody })) {
147
155
  outputs[CHAT_V2_REQUEST_BODY_PORT_ID] = createChatV2RequestBodyOutput(requestBodies);
148
156
  }
149
157
  return outputs;
150
158
  }
151
- export function createChatV2ProviderFailureOutputs({ requestMessages, responseStatus, responseError, requestStatuses, requestErrors, requestBodies, outputUsage, outputReasoning, includeFunctionCalls, retryOnNon200, }) {
159
+ export function createChatV2ProviderFailureOutputs({ requestMessages, responseStatus, responseError, requestStatuses, requestErrors, requestBodies, outputUsage, outputReasoning, outputRequestStatus, outputRequestError, outputRequestBody, includeFunctionCalls, retryOnNon200, }) {
152
160
  const outputs = {
153
- [CHAT_V2_REQUEST_ERROR_PORT_ID]: retryOnNon200
154
- ? createChatV2RetryAttemptOutput('string[]', requestErrors)
155
- : {
156
- type: 'string',
157
- value: responseError,
158
- },
159
- [CHAT_V2_REQUEST_STATUS_PORT_ID]: retryOnNon200
160
- ? createChatV2RetryAttemptOutput('number[]', requestStatuses)
161
- : responseStatus == null
162
- ? {
163
- type: 'control-flow-excluded',
164
- value: undefined,
165
- }
166
- : {
167
- type: 'number',
168
- value: responseStatus,
169
- },
170
161
  ['response']: createControlFlowExcludedOutput(),
171
162
  ['in-messages']: {
172
163
  type: 'chat-message[]',
@@ -176,9 +167,28 @@ export function createChatV2ProviderFailureOutputs({ requestMessages, responseSt
176
167
  type: 'chat-message[]',
177
168
  value: requestMessages,
178
169
  },
179
- ['responseTokens']: createControlFlowExcludedOutput(),
180
170
  };
181
- outputs[CHAT_V2_REQUEST_BODY_PORT_ID] = createChatV2RequestBodyOutput(requestBodies);
171
+ if (outputRequestStatus) {
172
+ outputs[CHAT_V2_REQUEST_STATUS_PORT_ID] = retryOnNon200
173
+ ? createChatV2RetryAttemptOutput('number[]', requestStatuses)
174
+ : responseStatus == null
175
+ ? createControlFlowExcludedOutput()
176
+ : {
177
+ type: 'number',
178
+ value: responseStatus,
179
+ };
180
+ }
181
+ if (shouldOutputChatV2RequestError({ outputRequestStatus, outputRequestError })) {
182
+ outputs[CHAT_V2_REQUEST_ERROR_PORT_ID] = retryOnNon200
183
+ ? createChatV2RetryAttemptOutput('string[]', requestErrors)
184
+ : {
185
+ type: 'string',
186
+ value: responseError,
187
+ };
188
+ }
189
+ if (shouldOutputChatV2RequestBody({ outputRequestStatus, outputRequestBody })) {
190
+ outputs[CHAT_V2_REQUEST_BODY_PORT_ID] = createChatV2RequestBodyOutput(requestBodies);
191
+ }
182
192
  if (includeFunctionCalls) {
183
193
  outputs['function-calls'] = createControlFlowExcludedOutput();
184
194
  }
@@ -61,6 +61,14 @@ function normalizeProviderFailure(error, options) {
61
61
  function normalizeProviderFailureMessages(errors, options) {
62
62
  return errors.map((error) => normalizeProviderFailureMessage(error, options));
63
63
  }
64
+ function notifyProviderAttempt(options, attempt) {
65
+ try {
66
+ options.onProviderAttempt?.(attempt);
67
+ }
68
+ catch {
69
+ // Attempt diagnostics are observational and must never affect the request.
70
+ }
71
+ }
64
72
  async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, transportMode) {
65
73
  const requestStatuses = [];
66
74
  const requestErrors = [];
@@ -77,6 +85,12 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
77
85
  result,
78
86
  });
79
87
  callWasObserved = true;
88
+ notifyProviderAttempt(options, {
89
+ attemptIndex: attempt,
90
+ outcome: statusCode === 200 ? 'success' : 'provider-failure',
91
+ status: statusCode,
92
+ ...(statusCode === 200 ? {} : { error: buildNon200StatusError(statusCode) }),
93
+ });
80
94
  if (retryPlan.enabled) {
81
95
  requestStatuses.push(statusCode);
82
96
  }
@@ -100,6 +114,12 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
100
114
  });
101
115
  }
102
116
  const statusCode = getChatV2ProviderErrorStatusCode(error);
117
+ notifyProviderAttempt(options, {
118
+ attemptIndex: attempt,
119
+ outcome: 'provider-failure',
120
+ ...(statusCode == null ? {} : { status: statusCode }),
121
+ error,
122
+ });
103
123
  if (!retryPlan.enabled || statusCode == null || statusCode === 200) {
104
124
  throw error;
105
125
  }
@@ -113,7 +133,7 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
113
133
  }
114
134
  }
115
135
  function buildProviderFailureResult(requestMessages, options, plan, normalizedError, rawError, requestStatuses, requestErrors) {
116
- if (!plan.output.outputRequestStatus) {
136
+ if (!plan.output.outputRequestStatus && !plan.output.outputRequestError) {
117
137
  return undefined;
118
138
  }
119
139
  const statusCode = getChatV2ProviderErrorStatusCode(normalizedError);
@@ -138,6 +158,9 @@ function buildProviderFailureResult(requestMessages, options, plan, normalizedEr
138
158
  requestBodies: options.requestBodies,
139
159
  outputUsage: plan.output.outputUsage,
140
160
  outputReasoning: plan.output.outputReasoning,
161
+ outputRequestStatus: plan.output.outputRequestStatus,
162
+ outputRequestError: plan.output.outputRequestError,
163
+ outputRequestBody: plan.output.outputRequestBody,
141
164
  includeFunctionCalls: plan.output.includeFunctionCalls,
142
165
  retryOnNon200: plan.retry.enabled,
143
166
  });
@@ -159,7 +182,13 @@ function buildProviderFailureResult(requestMessages, options, plan, normalizedEr
159
182
  requestStatus: statusCode,
160
183
  };
161
184
  }
162
- export async function runChatV2Pipeline(options) {
185
+ /**
186
+ * Runs one provider/model round without deciding whether a provider failure
187
+ * should become diagnostic outputs or should advance an LLM Profile fallback
188
+ * chain. Shared prompt/schema/tool construction errors deliberately continue
189
+ * to throw: they are graph configuration errors, not a profile failure.
190
+ */
191
+ export async function runChatV2PipelineExecution(options) {
163
192
  const requestMessages = prependSystemPrompt(coercePromptToChatMessages(options.prompt, { requirePrompt: true }), options.systemPrompt);
164
193
  const modelMessages = await chatMessagesToModelMessages(requestMessages, {
165
194
  provider: options.provider,
@@ -177,49 +206,59 @@ export async function runChatV2Pipeline(options) {
177
206
  tools,
178
207
  });
179
208
  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) => {
209
+ let chatResponse;
210
+ try {
211
+ chatResponse = await runChatV2WithRetry(options, {
212
+ ...plan.request,
213
+ abortSignal: options.context.signal,
214
+ executeStream: options.executeStream,
215
+ executeGenerate: options.executeGenerate,
216
+ onPartialOutput: !shouldStreamResponse
217
+ ? undefined
218
+ : ({ text, functionCalls }) => {
219
+ options.context.onPartialOutputs?.(createChatV2CommonOutputs({
220
+ requestMessages,
221
+ response: text,
222
+ structuredOutput: undefined,
223
+ functionCalls,
224
+ usage: undefined,
225
+ reasoning: '',
226
+ requestStatus: undefined,
227
+ responseError: undefined,
228
+ requestStatuses: [],
229
+ requestErrors: [],
230
+ requestBodies: undefined,
231
+ outputUsage: false,
232
+ outputReasoning: false,
233
+ outputRequestStatus: false,
234
+ outputRequestError: false,
235
+ outputRequestBody: false,
236
+ includeFunctionCalls: plan.output.includeFunctionCalls,
237
+ functionCallMode: plan.output.functionCallMode,
238
+ retryOnNon200: false,
239
+ responseFormat: undefined,
240
+ }));
241
+ },
242
+ }, plan.retry, options.context.signal, plan.transportMode);
243
+ }
244
+ catch (caughtError) {
245
+ if (options.context.signal.aborted) {
246
+ throw caughtError;
247
+ }
210
248
  const retryFailure = isChatV2RetryFailure(caughtError) ? caughtError : undefined;
211
249
  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;
218
- }
219
- throw normalizedError;
220
- });
221
- if ('commonOutputs' in chatResponse) {
222
- return chatResponse;
250
+ return {
251
+ outcome: 'provider-failure',
252
+ failure: {
253
+ requestMessages,
254
+ options,
255
+ plan,
256
+ normalizedError: normalizeProviderFailure(rawError, options),
257
+ rawError,
258
+ requestStatuses: retryFailure?.requestStatuses ?? [],
259
+ requestErrors: normalizeProviderFailureMessages(retryFailure?.requestErrors ?? [], options),
260
+ },
261
+ };
223
262
  }
224
263
  const usage = normalizeChatV2Usage(chatResponse.result.usage, options);
225
264
  const requestStatuses = chatResponse.requestStatuses;
@@ -243,6 +282,8 @@ export async function runChatV2Pipeline(options) {
243
282
  outputUsage: plan.output.outputUsage,
244
283
  outputReasoning: plan.output.outputReasoning,
245
284
  outputRequestStatus: plan.output.outputRequestStatus,
285
+ outputRequestError: plan.output.outputRequestError,
286
+ outputRequestBody: plan.output.outputRequestBody,
246
287
  includeFunctionCalls: plan.output.includeFunctionCalls,
247
288
  functionCallMode: plan.output.functionCallMode,
248
289
  retryOnNon200: plan.retry.enabled,
@@ -252,7 +293,7 @@ export async function runChatV2Pipeline(options) {
252
293
  if (allMessagesOutput?.type !== 'chat-message[]') {
253
294
  throw new Error('Chat v2 pipeline expected all-messages output to be chat-message[].');
254
295
  }
255
- return {
296
+ const result = {
256
297
  commonOutputs,
257
298
  requestMessages,
258
299
  allMessages: allMessagesOutput.value,
@@ -265,4 +306,41 @@ export async function runChatV2Pipeline(options) {
265
306
  providerMetadata: chatResponse.result.providerMetadata,
266
307
  requestStatus,
267
308
  };
309
+ const providerRoundFailure = chatResponse.responseError ?? (requestStatus === 200 ? undefined : buildNon200StatusError(requestStatus));
310
+ if (providerRoundFailure != null) {
311
+ const rawError = providerRoundFailure;
312
+ return {
313
+ outcome: 'provider-failure',
314
+ failure: {
315
+ requestMessages,
316
+ options,
317
+ plan,
318
+ normalizedError: normalizeProviderFailure(rawError, options),
319
+ rawError,
320
+ requestStatuses: chatResponse.requestStatuses,
321
+ requestErrors: normalizeProviderFailureMessages(chatResponse.requestErrors, options),
322
+ diagnosticResult: result,
323
+ },
324
+ };
325
+ }
326
+ return { outcome: 'success', result };
327
+ }
328
+ /**
329
+ * Retains the established single-profile behavior: request-detail mode can
330
+ * turn a provider failure into normal excluded outputs; otherwise it remains
331
+ * a thrown normalized provider error.
332
+ */
333
+ export function materializeChatV2PipelineFailure(failure) {
334
+ if (failure.diagnosticResult != null) {
335
+ return failure.diagnosticResult;
336
+ }
337
+ const failureResult = buildProviderFailureResult(failure.requestMessages, failure.options, failure.plan, failure.normalizedError, failure.rawError, failure.requestStatuses, failure.requestErrors);
338
+ if (failureResult != null) {
339
+ return failureResult;
340
+ }
341
+ throw failure.normalizedError;
342
+ }
343
+ export async function runChatV2Pipeline(options) {
344
+ const execution = await runChatV2PipelineExecution(options);
345
+ return execution.outcome === 'success' ? execution.result : materializeChatV2PipelineFailure(execution.failure);
268
346
  }
@@ -79,6 +79,7 @@ export async function createResolvedChatV2Provider(options) {
79
79
  ...config,
80
80
  apiKey: options.credential.value,
81
81
  onRequestBody: options.onRequestBody,
82
+ transformRequestBody: options.transformRequestBody,
82
83
  });
83
84
  return {
84
85
  profile: {
@@ -1,4 +1,5 @@
1
- import { normalizeLLMChatV2RetryCooldownMs, normalizeLLMChatV2RetryCount, } from './chatV2Retry.js';
1
+ import { normalizeLLMChatV2RetryCooldownMs, normalizeLLMChatV2RetryCount } from './chatV2Retry.js';
2
+ import { shouldOutputChatV2RequestBody, shouldOutputChatV2RequestError } 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,9 @@ export function buildChatV2RequestPlan(options) {
33
32
  output: {
34
33
  outputUsage: options.outputUsage,
35
34
  outputReasoning: options.outputReasoning,
36
- outputRequestStatus: options.outputRequestStatus,
35
+ outputRequestStatus: options.outputRequestStatus === true,
36
+ outputRequestError: shouldOutputChatV2RequestError(options),
37
+ outputRequestBody: shouldOutputChatV2RequestBody(options),
37
38
  includeFunctionCalls: options.includeFunctionCalls,
38
39
  functionCallMode: options.functionCallMode,
39
40
  },
@@ -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,11 @@
1
- export {};
1
+ /**
2
+ * Older LLM Chat nodes used Output request details as one switch for status,
3
+ * error, and request body. Keep that saved contract intact while newly saved
4
+ * nodes use the independent controls.
5
+ */
6
+ export function shouldOutputChatV2RequestError(options) {
7
+ return options.outputRequestError ?? options.outputRequestStatus ?? false;
8
+ }
9
+ export function shouldOutputChatV2RequestBody(options) {
10
+ return options.outputRequestBody ?? options.outputRequestStatus ?? false;
11
+ }
@@ -0,0 +1,45 @@
1
+ export function getInstructionMessageRoles(messages) {
2
+ return messages
3
+ .filter((message) => message.type === 'system' || message.type === 'developer')
4
+ .map((message) => message.type);
5
+ }
6
+ /**
7
+ * AI SDK's provider-neutral ModelMessage represents both Rivet system and
8
+ * developer instructions with role `system`. Restore the explicit Rivet roles
9
+ * only at OpenAI-compatible wire boundaries, after the provider has built its
10
+ * request body.
11
+ */
12
+ export function restoreOpenAICompatibleInstructionRoles(body, roles) {
13
+ if (roles.length === 0) {
14
+ return body;
15
+ }
16
+ if (body == null || typeof body !== 'object' || Array.isArray(body)) {
17
+ throw new Error('Could not preserve developer messages: provider request body is not a JSON object.');
18
+ }
19
+ const record = body;
20
+ const listKey = Array.isArray(record.messages) ? 'messages' : Array.isArray(record.input) ? 'input' : undefined;
21
+ if (listKey == null) {
22
+ throw new Error('Could not preserve developer messages: provider request body has no messages or input array.');
23
+ }
24
+ const items = record[listKey];
25
+ const instructionIndexes = items.flatMap((item, index) => item != null &&
26
+ typeof item === 'object' &&
27
+ !Array.isArray(item) &&
28
+ (item.role === 'system' || item.role === 'developer')
29
+ ? [index]
30
+ : []);
31
+ if (instructionIndexes.length !== roles.length) {
32
+ throw new Error(`Could not preserve developer messages: expected ${roles.length} instruction message(s), but the provider request contains ${instructionIndexes.length}.`);
33
+ }
34
+ const rewrittenItems = [...items];
35
+ instructionIndexes.forEach((itemIndex, roleIndex) => {
36
+ rewrittenItems[itemIndex] = {
37
+ ...rewrittenItems[itemIndex],
38
+ role: roles[roleIndex],
39
+ };
40
+ });
41
+ return {
42
+ ...record,
43
+ [listKey]: rewrittenItems,
44
+ };
45
+ }