@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
@@ -1,5 +1,5 @@
1
1
  import { DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_COOLDOWN_MS, DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_REPEAT_TIMES, } from './chatV2Retry.js';
2
- import { anthropicCacheControlTtlOptions, anthropicEffortOptions, anthropicThinkingModeOptions, chatV2ProviderOptions, getChatV2ModelOptions, googleThinkingLevelOptions, openAIReasoningEffortOptions, openAIWebSearchContextSizeOptions, } from './providerOptions.js';
2
+ import { anthropicCacheControlTtlOptions, anthropicEffortOptions, anthropicThinkingModeOptions, chatV2ProviderOptions, customProviderApiOptions, getChatV2ModelOptions, googleThinkingLevelOptions, openAIReasoningEffortOptions, openAIWebSearchContextSizeOptions, } from './providerOptions.js';
3
3
  import { LLM_CHAT_V2_PARALLEL_TOOL_CALLS_HELPER_MESSAGE, supportsLLMChatV2ParallelToolCalls, } from './parallelToolCalls.js';
4
4
  const hideUnlessProvider = (provider) => (data) => data.provider !== provider;
5
5
  function group(label, editors, defaultOpen) {
@@ -61,7 +61,16 @@ function getModelEditors(modelOptions) {
61
61
  dataKey: 'customProviderBaseURL',
62
62
  useInputToggleDataKey: 'useCustomProviderBaseURLInput',
63
63
  placeholder: 'https://api.cerebras.ai/v1',
64
- helperMessage: 'OpenAI-compatible provider base URL. Full /chat/completions URLs are accepted and normalized.',
64
+ helperMessage: 'OpenAI-compatible provider base URL. Full /chat/completions or /responses URLs are accepted and normalized.',
65
+ hideIf: hideUnlessProvider('custom'),
66
+ },
67
+ {
68
+ type: 'segmented',
69
+ label: 'API',
70
+ ariaLabel: 'Custom provider API',
71
+ dataKey: 'customProviderApi',
72
+ defaultValue: 'completions',
73
+ options: [...customProviderApiOptions],
65
74
  hideIf: hideUnlessProvider('custom'),
66
75
  },
67
76
  {
@@ -103,11 +112,7 @@ function getModelEditors(modelOptions) {
103
112
  ], true);
104
113
  }
105
114
  function getProviderEditors() {
106
- return [
107
- getOpenAIProviderEditors(),
108
- getAnthropicProviderEditors(),
109
- getGoogleProviderEditors(),
110
- ];
115
+ return [getOpenAIProviderEditors(), getAnthropicProviderEditors(), getGoogleProviderEditors()];
111
116
  }
112
117
  function getOpenAIProviderEditors() {
113
118
  return providerGroup('openai', 'OpenAI', [
@@ -379,7 +384,9 @@ function getToolEditors() {
379
384
  type: 'toggle',
380
385
  label: 'Allow parallel toolcalls',
381
386
  dataKey: 'parallelToolCalls',
382
- helperMessage: LLM_CHAT_V2_PARALLEL_TOOL_CALLS_HELPER_MESSAGE,
387
+ helperMessage: (data) => data.configurationMode === 'profile'
388
+ ? `${LLM_CHAT_V2_PARALLEL_TOOL_CALLS_HELPER_MESSAGE} In From profile mode, it applies only to candidates whose providers support parallel tool calls; unsupported candidates ignore it.`
389
+ : LLM_CHAT_V2_PARALLEL_TOOL_CALLS_HELPER_MESSAGE,
383
390
  hideIf: (data) => !data.useToolCalling ||
384
391
  (data.configurationMode !== 'profile' && !supportsLLMChatV2ParallelToolCalls(data.provider)),
385
392
  },
@@ -392,8 +399,9 @@ function getToolEditors() {
392
399
  },
393
400
  {
394
401
  type: 'number',
395
- label: 'Max tool rounds',
402
+ label: 'Maximum tool rounds',
396
403
  dataKey: 'maxToolRounds',
404
+ helperMessage: 'Each round may contain multiple parallel tool calls if not disallowed.',
397
405
  min: 1,
398
406
  step: 1,
399
407
  hideIf: (data) => !data.useToolCalling || !data.autoContinueToolCalls,
@@ -414,6 +422,24 @@ function getOutputEditors() {
414
422
  dataKey: 'outputUsage',
415
423
  helperMessage: 'Adds a Usage output built from Vercel AI SDK usage metadata: prompt, completion, total, cached, reasoning tokens, and estimated cost when available.',
416
424
  },
425
+ {
426
+ type: 'toggle',
427
+ label: 'Output LLM attempts',
428
+ dataKey: 'outputLLMAttempts',
429
+ helperMessage: 'Adds one chronological record for every profile configuration, provider request, and response-validation attempt. Records include provider, model, retry status, and provider error details when available.',
430
+ },
431
+ {
432
+ type: 'toggle',
433
+ label: 'Output request body',
434
+ dataKey: 'outputRequestBody',
435
+ helperMessage: 'Adds an LLM request body output. It can contain prompts and non-secret provider options; it never includes authorization headers or API keys.',
436
+ },
437
+ {
438
+ type: 'toggle',
439
+ label: 'Output response body',
440
+ dataKey: 'outputResponseBody',
441
+ helperMessage: 'Adds the complete LLM response body captured at the provider HTTP boundary. JSON responses are parsed for inspection; other responses remain text. Rivet does not redact or truncate captured content.',
442
+ },
417
443
  {
418
444
  type: 'toggle',
419
445
  label: 'Stream response',
@@ -422,9 +448,10 @@ function getOutputEditors() {
422
448
  },
423
449
  {
424
450
  type: 'toggle',
425
- label: 'Cache outputs (editor only)',
451
+ label: 'Cache outputs (editor only) (legacy)',
426
452
  dataKey: 'cache',
427
- helperMessage: "Reuses this node's previous outputs if the input is the same (provider config, prompt and generation settings). The cache persists while the Rivet app is open.",
453
+ helperMessage: "Legacy editor-only cache. It reuses this node's previous outputs for the same input while the Rivet app is open. Turn it off to retire it from this node.",
454
+ hideIf: (data) => data.cache !== true,
428
455
  },
429
456
  ]);
430
457
  }
@@ -449,8 +476,8 @@ function getProviderAdvancedEditors() {
449
476
  },
450
477
  ]);
451
478
  }
452
- function getTechnicalDetailsEditors() {
453
- return group('Technical details', [
479
+ function getErrorBehaviorEditors() {
480
+ return group('Error behavior', [
454
481
  {
455
482
  type: 'toggle',
456
483
  label: 'Retry on non-200',
@@ -479,12 +506,6 @@ function getTechnicalDetailsEditors() {
479
506
  helperMessage: 'Milliseconds to wait between repeats',
480
507
  hideIf: (data) => !data.retryOnNon200,
481
508
  },
482
- {
483
- type: 'toggle',
484
- label: 'Output request details',
485
- dataKey: 'outputRequestStatus',
486
- helperMessage: 'Adds Response Status, Response Error, and LLM request body outputs. Retry mode changes status/error to per-attempt arrays, and LLM request body becomes an array when multiple provider calls are made.',
487
- },
488
509
  ]);
489
510
  }
490
511
  export async function getLLMChatV2Editors(data, context) {
@@ -507,7 +528,7 @@ export async function getLLMChatV2Editors(data, context) {
507
528
  getToolEditors(),
508
529
  getOutputEditors(),
509
530
  ...(!usesProfile ? [getProviderAdvancedEditors()] : []),
510
- getTechnicalDetailsEditors(),
531
+ getErrorBehaviorEditors(),
511
532
  ];
512
533
  }
513
534
  export async function getLLMProfileEditors(data, context) {
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Serialized LLM Chat migrations live beside the node contract, rather than
3
+ * making generic project serialization understand LLM-specific settings.
4
+ * This is deliberately idempotent because deserialization can normalize a
5
+ * graph more than once while it is imported or embedded in a prefab.
6
+ */
7
+ export function normalizeSerializedLLMChatV2Node(node) {
8
+ if (node.type !== 'llmChatV2' || node.data == null || typeof node.data !== 'object') {
9
+ return;
10
+ }
11
+ const data = node.data;
12
+ const hadLegacyRequestDiagnostics = data.outputRequestStatus === true || data.outputRequestError === true;
13
+ if (hadLegacyRequestDiagnostics && !Object.hasOwn(data, 'outputLLMAttempts')) {
14
+ data.outputLLMAttempts = true;
15
+ }
16
+ // The original request-details switch also enabled request-body capture.
17
+ // Preserve that still-supported diagnostic independently from the retired
18
+ // status/error ports.
19
+ if (data.outputRequestStatus === true && !Object.hasOwn(data, 'outputRequestBody')) {
20
+ data.outputRequestBody = true;
21
+ }
22
+ delete data.outputRequestStatus;
23
+ delete data.outputRequestError;
24
+ }
@@ -1,117 +1,201 @@
1
- import { coerceTypeOptional } from '../../utils/coerceType.js';
2
- import { getInputOrData } from '../../utils/inputs.js';
3
- import { createChatV2ResponseOutput, mergeCustomProviderResponseFormatOptions, resolveChatV2ResponseFormatParameters, } from './chatV2ResponseFormat.js';
4
- import { hasLLMChatV2ToolResponseFormatConflict, LLM_CHAT_V2_TOOL_RESPONSE_FORMAT_CONFLICT_COPY, } from './chatV2FeatureCompatibility.js';
1
+ import { cleanHeaders } from '../../utils/inputs.js';
2
+ import { createLLMProfileFallbackRunner, getLLMAttemptErrorMessage } from './llmProfileFallback.js';
3
+ import { applyLLMProfileToNodeData, normalizeLLMProfileChainInput } from './llmProfile.js';
4
+ import { buildLLMInvocationPlan, buildLLMInvocationRunOptions } from './llmInvocationPlan.js';
5
+ import { resolveLLMModelCandidate } from './llmModelCandidate.js';
6
+ import { mergeCustomProviderResponseFormatOptions } from './chatV2ResponseFormat.js';
7
+ import { getLLMChatV2EditorCacheEligibility } from './llmChatV2CachePolicy.js';
5
8
  import { parseChatV2Provider } from './providerOptions.js';
6
- import { createResolvedChatV2Provider, resolveChatV2Credential } from './chatV2ProviderProfile.js';
7
- import { applyLLMProfileToNodeData, normalizeLLMProfileValue } from './llmProfile.js';
9
+ import { parseCustomProviderApi } from './customProviderApi.js';
8
10
  import { buildLLMChatV2EditorCacheKey, cloneLLMChatV2EditorCacheOutputs, resolveLLMChatV2EditorCache, } from './chatV2EditorCache.js';
9
- import { resolveLLMChatV2BuiltInTools, resolveLLMChatV2GenerationParameters, resolveLLMChatV2Headers, resolveLLMChatV2RuntimeProviderOptions, resolveLLMChatV2ToolChoice, } from './chatV2RuntimeOptions.js';
10
- import { shouldIncludeLLMChatV2ToolCalls, } from './llmChatV2NodeData.js';
11
+ import { resolveLLMChatV2GenerationParameters, resolveLLMChatV2RuntimeProviderOptions, } from './chatV2RuntimeOptions.js';
12
+ import {} from './llmChatV2NodeData.js';
13
+ import { isChatV2ResponseValidationError, runChatV2Pipeline } from './chatV2Pipeline.js';
11
14
  export { buildLLMChatV2EditorCacheKey, cloneLLMChatV2EditorCacheOutputs };
12
15
  export { resolveLLMChatV2RuntimeProviderOptions } from './chatV2RuntimeOptions.js';
13
- function resolveLLMChatV2BaseURL(data, inputs) {
14
- return data.provider === 'custom'
15
- ? getInputOrData(data, inputs, 'customProviderBaseURL', 'string', 'useCustomProviderBaseURLInput')?.trim() ||
16
- undefined
17
- : undefined;
18
- }
19
16
  export async function resolveLLMChatV2RuntimeConfig(params) {
20
17
  const { data, nodeId, inputs, context } = params;
21
18
  const profileInput = inputs['llmProfile'];
22
19
  if (data.configurationMode === 'profile' && profileInput == null) {
23
20
  throw new Error('LLM Profile input is required when Configuration is From profile.');
24
21
  }
25
- const profile = data.configurationMode === 'profile' ? normalizeLLMProfileValue(profileInput?.value) : undefined;
26
- const effectiveData = profile ? applyLLMProfileToNodeData(data, profile) : data;
27
- if (hasLLMChatV2ToolResponseFormatConflict(effectiveData)) {
28
- throw new Error(LLM_CHAT_V2_TOOL_RESPONSE_FORMAT_CONFLICT_COPY.paragraphs[0]);
29
- }
30
- const provider = parseChatV2Provider(effectiveData.provider);
31
- const modelId = getInputOrData(effectiveData, inputs, 'model', 'string');
32
- const baseURL = resolveLLMChatV2BaseURL(effectiveData, inputs);
33
- const nodeHeaders = resolveLLMChatV2Headers(effectiveData, inputs);
34
- const credential = profile?.credential ??
35
- resolveChatV2Credential({
36
- provider,
37
- context,
38
- apiKeySource: effectiveData.apiKeySource === 'input' ? 'input' : 'configured',
39
- inputs,
40
- customProgrammaticName: effectiveData.customProviderApiKeyProgrammaticName,
41
- customEnvironmentName: effectiveData.customProviderApiKeyEnvVarName,
22
+ const plan = buildLLMInvocationPlan({ data, inputs, context });
23
+ if (data.configurationMode !== 'profile') {
24
+ // The editor cache cannot faithfully replay tool handlers, connected
25
+ // Delegate runs, provider-native tools, or their side effects. A legacy
26
+ // cache-enabled node therefore remains cacheable only for ordinary model
27
+ // calls without tool use.
28
+ const editorCache = getEligibleEditorCache(data, context);
29
+ const inlineCandidate = await resolveLLMModelCandidate({
30
+ plan,
31
+ profile: undefined,
32
+ roundOptions: buildLLMInvocationRunOptions({
33
+ plan,
34
+ provider: parseChatV2Provider(data.provider),
35
+ modelId: data.model,
36
+ }),
42
37
  });
43
- const apiKey = credential.value;
44
- const requestBodies = effectiveData.outputRequestStatus ? [] : undefined;
45
- const resolvedProvider = await createResolvedChatV2Provider({
46
- provider,
47
- modelId,
48
- context,
49
- baseURL,
50
- headers: nodeHeaders,
51
- credential,
52
- onRequestBody: requestBodies == null ? undefined : (body) => requestBodies.push(body),
53
- });
54
- const providerConfig = resolvedProvider.config;
55
- const model = resolvedProvider.model;
56
- const prompt = inputs['prompt'];
57
- const systemPrompt = inputs['systemPrompt'];
58
- const functions = effectiveData.useToolCalling && inputs['functions'] != null
59
- ? coerceTypeOptional(inputs['functions'], 'gpt-function[]')
38
+ const inlineRunOptions = inlineCandidate.runOptions;
39
+ const generationParameters = resolveLLMChatV2GenerationParameters(data, inputs);
40
+ const { cacheKey, cachedOutputs } = resolveLLMChatV2EditorCache({
41
+ apiKey: inlineCandidate.credential.value,
42
+ data,
43
+ editorCache,
44
+ functions: plan.functions,
45
+ generationParameters,
46
+ modelId: inlineRunOptions.modelId,
47
+ nodeId,
48
+ prompt: plan.prompt,
49
+ provider: inlineRunOptions.provider,
50
+ providerConfig: inlineCandidate.providerConfig,
51
+ providerOptions: inlineRunOptions.providerOptions,
52
+ responseFormatParameters: plan.responseFormatParameters,
53
+ systemPrompt: plan.systemPrompt,
54
+ toolChoice: plan.toolChoice,
55
+ });
56
+ return {
57
+ runOptions: inlineRunOptions,
58
+ runPipeline: async (roundOptions) => {
59
+ try {
60
+ return await runChatV2Pipeline({
61
+ ...roundOptions,
62
+ model: inlineRunOptions.model,
63
+ onProviderAttempt: (attempt) => {
64
+ try {
65
+ roundOptions.onProviderAttempt?.(attempt);
66
+ }
67
+ catch {
68
+ // A caller-owned observer must not affect the physical request.
69
+ }
70
+ try {
71
+ params.onLLMAttempt?.({
72
+ roundIndex: roundOptions.roundIndex ?? 0,
73
+ provider: inlineRunOptions.provider,
74
+ model: inlineRunOptions.modelId,
75
+ ...(inlineRunOptions.customProviderApi == null
76
+ ? {}
77
+ : { customProviderApi: inlineRunOptions.customProviderApi }),
78
+ stage: 'request',
79
+ outcome: attempt.outcome === 'success' ? 'success' : attempt.outcome === 'aborted' ? 'aborted' : 'failure',
80
+ attemptIndex: attempt.attemptIndex,
81
+ ...(attempt.status == null ? {} : { status: attempt.status }),
82
+ ...(attempt.error == null ? {} : { error: getLLMAttemptErrorMessage(attempt.error) }),
83
+ });
84
+ }
85
+ catch {
86
+ // Diagnostics must never affect a model invocation.
87
+ }
88
+ },
89
+ });
90
+ }
91
+ catch (error) {
92
+ if (isChatV2ResponseValidationError(error)) {
93
+ try {
94
+ params.onLLMAttempt?.({
95
+ roundIndex: roundOptions.roundIndex ?? 0,
96
+ provider: inlineRunOptions.provider,
97
+ model: inlineRunOptions.modelId,
98
+ ...(inlineRunOptions.customProviderApi == null
99
+ ? {}
100
+ : { customProviderApi: inlineRunOptions.customProviderApi }),
101
+ stage: 'response-validation',
102
+ outcome: 'failure',
103
+ error: getLLMAttemptErrorMessage(error),
104
+ });
105
+ }
106
+ catch {
107
+ // Diagnostics must never affect a model invocation.
108
+ }
109
+ }
110
+ throw error;
111
+ }
112
+ },
113
+ functions: plan.functions,
114
+ cacheKey,
115
+ cachedOutputs,
116
+ editorCache,
117
+ shouldAutoContinueToolCalls: !!data.autoContinueToolCalls && data.useToolCalling,
118
+ maxToolRounds: data.maxToolRounds ?? 3,
119
+ outputLLMAttempts: data.outputLLMAttempts === true,
120
+ getProfileSummary: undefined,
121
+ isProfileFallbackExhausted: () => false,
122
+ };
123
+ }
124
+ const profiles = normalizeLLMProfileChainInput(profileInput?.value);
125
+ // Profile-owned provider-native capabilities are resolved only after the
126
+ // input profile is normalized. One cache entry covers the complete fallback
127
+ // chain, so every possible candidate must be replay-safe.
128
+ const editorCache = profiles.every((profile) => getLLMChatV2EditorCacheEligibility({ ...data, ...profile.configuration }).eligible)
129
+ ? context.editorExecutionCache
60
130
  : undefined;
61
- const toolChoice = resolveLLMChatV2ToolChoice(effectiveData);
62
- const responseFormatParameters = resolveChatV2ResponseFormatParameters(effectiveData, inputs);
63
- const providerOptions = mergeCustomProviderResponseFormatOptions(provider, resolveLLMChatV2RuntimeProviderOptions(effectiveData, inputs), responseFormatParameters);
64
- const generationParameters = resolveLLMChatV2GenerationParameters(effectiveData, inputs);
65
- const runOptions = {
66
- provider,
67
- model,
68
- modelId,
69
- prompt,
70
- systemPrompt,
71
- functions,
72
- additionalTools: resolveLLMChatV2BuiltInTools(effectiveData, context, providerConfig, apiKey),
73
- ...generationParameters,
74
- responseOutput: createChatV2ResponseOutput(responseFormatParameters, provider),
75
- responseFormat: responseFormatParameters?.responseFormat,
76
- outputUsage: effectiveData.outputUsage,
77
- outputReasoning: effectiveData.outputReasoning,
78
- outputRequestStatus: effectiveData.outputRequestStatus,
79
- includeFunctionCalls: shouldIncludeLLMChatV2ToolCalls(effectiveData),
80
- emitPartialOutputs: effectiveData.useAsGraphPartialOutput,
81
- providerOptions,
82
- toolChoice,
83
- anthropicCacheControlTtl: provider === 'anthropic' ? effectiveData.anthropicCacheControlTtl || undefined : undefined,
84
- requestBodies,
85
- retryOnNon200: effectiveData.retryOnNon200,
86
- retryOnNon200RepeatTimes: effectiveData.retryOnNon200RepeatTimes,
87
- retryOnNon200CooldownMs: effectiveData.retryOnNon200CooldownMs,
88
- context,
131
+ const firstProfile = profiles[0];
132
+ const firstProvider = parseChatV2Provider(firstProfile.configuration.provider);
133
+ // The fallback runner resolves a real model before every physical request.
134
+ // This is deliberately a provider-neutral round template, never a fake
135
+ // executable model state.
136
+ const profileRunOptions = {
137
+ ...buildLLMInvocationRunOptions({
138
+ plan,
139
+ provider: firstProvider,
140
+ modelId: firstProfile.configuration.model,
141
+ }),
89
142
  };
90
- const editorCache = effectiveData.cache ? context.editorExecutionCache : undefined;
143
+ const firstProfileData = applyLLMProfileToNodeData(data, firstProfile);
144
+ Object.assign(profileRunOptions, {
145
+ ...resolveLLMChatV2GenerationParameters(firstProfileData, inputs),
146
+ providerOptions: mergeCustomProviderResponseFormatOptions(firstProvider, resolveLLMChatV2RuntimeProviderOptions(firstProfileData, inputs), plan.responseFormatParameters, firstProfileData.customProviderApi),
147
+ anthropicCacheControlTtl: firstProvider === 'anthropic' ? firstProfileData.anthropicCacheControlTtl || undefined : undefined,
148
+ });
149
+ const fallbackRunner = createLLMProfileFallbackRunner({
150
+ candidates: profiles.map((profile) => ({
151
+ provider: parseChatV2Provider(profile.configuration.provider),
152
+ model: profile.configuration.model,
153
+ ...(profile.configuration.provider === 'custom'
154
+ ? { customProviderApi: parseCustomProviderApi(profile.configuration.customProviderApi) }
155
+ : {}),
156
+ })),
157
+ resolveCandidate: (profileIndex, roundOptions) => resolveLLMModelCandidate({
158
+ plan,
159
+ profile: profiles[profileIndex],
160
+ roundOptions,
161
+ }).then((candidate) => candidate.runOptions),
162
+ onAttempt: params.onLLMAttempt,
163
+ });
91
164
  const { cacheKey, cachedOutputs } = resolveLLMChatV2EditorCache({
92
- apiKey,
93
- data: effectiveData,
165
+ apiKey: undefined,
166
+ data: firstProfileData,
94
167
  editorCache,
95
- functions,
96
- generationParameters,
97
- modelId,
168
+ functions: plan.functions,
169
+ generationParameters: undefined,
170
+ modelId: firstProfile.configuration.model,
98
171
  nodeId,
99
- prompt,
100
- provider,
101
- providerConfig,
102
- providerOptions,
103
- responseFormatParameters,
104
- systemPrompt,
105
- toolChoice,
172
+ prompt: plan.prompt,
173
+ provider: firstProvider,
174
+ // Profile headers are part of the individual profile fingerprints, but
175
+ // provider resolution also merges project-wide Chat headers. Include those
176
+ // values through the normalized provider-config fingerprint so a
177
+ // global-header edit cannot reuse a stale profile-mode editor cache entry.
178
+ providerConfig: { headers: cleanHeaders(context.settings?.chatNodeHeaders ?? {}) },
179
+ providerOptions: undefined,
180
+ responseFormatParameters: plan.responseFormatParameters,
181
+ systemPrompt: plan.systemPrompt,
182
+ toolChoice: plan.toolChoice,
183
+ profileChain: profiles,
106
184
  });
107
185
  return {
108
- providerProfile: resolvedProvider.profile,
109
- runOptions,
110
- functions,
186
+ runOptions: profileRunOptions,
187
+ runPipeline: fallbackRunner.run,
188
+ functions: plan.functions,
111
189
  cacheKey,
112
190
  cachedOutputs,
113
191
  editorCache,
114
- shouldAutoContinueToolCalls: !!effectiveData.autoContinueToolCalls && effectiveData.useToolCalling,
115
- maxToolRounds: effectiveData.maxToolRounds ?? 3,
192
+ shouldAutoContinueToolCalls: !!data.autoContinueToolCalls && data.useToolCalling,
193
+ maxToolRounds: data.maxToolRounds ?? 3,
194
+ outputLLMAttempts: data.outputLLMAttempts === true,
195
+ getProfileSummary: fallbackRunner.summary,
196
+ isProfileFallbackExhausted: fallbackRunner.wasExhausted,
116
197
  };
117
198
  }
199
+ function getEligibleEditorCache(data, context) {
200
+ return getLLMChatV2EditorCacheEligibility(data).eligible ? context.editorExecutionCache : undefined;
201
+ }
@@ -0,0 +1,60 @@
1
+ import { delegateToolCall } from '../nodes/toolCallDelegation.js';
2
+ import { runChatV2PipelineWithToolContinuation } from './toolContinuation.js';
3
+ import { isChatV2PipelineProviderFailureResult } from './chatV2Pipeline.js';
4
+ /**
5
+ * Owns the LLM-level recovery and continuation decision boundary. The node
6
+ * boundary provides a resolved runtime and GraphProcessor supplies only the
7
+ * connected Delegate host; no graph scheduling policy lives here.
8
+ */
9
+ export async function executeLLMInvocation(params) {
10
+ const { context, journal, runtime, toolCallContinuation } = params;
11
+ try {
12
+ const result = runtime.shouldAutoContinueToolCalls
13
+ ? await runChatV2PipelineWithToolContinuation({
14
+ ...runtime.runOptions,
15
+ autoContinue: true,
16
+ maxToolRounds: runtime.maxToolRounds,
17
+ functions: runtime.functions,
18
+ delegateToolCallRound: toolCallContinuation
19
+ ? async (toolCalls, preToolMessage) => {
20
+ const results = await toolCallContinuation.run(toolCalls, preToolMessage);
21
+ journal.recordToolRound({ kind: 'connected', count: results.length });
22
+ return results.map((entry) => ({
23
+ type: 'chat-message',
24
+ value: entry.message,
25
+ delegatedToolCall: entry.record,
26
+ }));
27
+ }
28
+ : undefined,
29
+ delegateToolCall: async (toolCall) => {
30
+ const delegated = await delegateToolCall(toolCall, context, {
31
+ handlers: [],
32
+ unknownHandler: undefined,
33
+ autoDelegate: true,
34
+ fallBackToExternalCall: true,
35
+ passthroughErrors: true,
36
+ });
37
+ journal.recordToolRound({ kind: 'internal', count: 1 });
38
+ return {
39
+ type: 'chat-message',
40
+ value: delegated.message,
41
+ delegatedToolCall: delegated.record,
42
+ };
43
+ },
44
+ runPipeline: runtime.runPipeline,
45
+ })
46
+ : await runtime.runPipeline(runtime.runOptions);
47
+ journal.recordTerminal({
48
+ kind: isChatV2PipelineProviderFailureResult(result)
49
+ ? 'failed'
50
+ : result.functionCalls.length > 0
51
+ ? 'released-unresolved-calls'
52
+ : 'final-model-answer',
53
+ });
54
+ return result;
55
+ }
56
+ catch (error) {
57
+ journal.recordTerminal({ kind: context.signal.aborted ? 'cancelled' : 'failed' });
58
+ throw error;
59
+ }
60
+ }
@@ -0,0 +1,11 @@
1
+ /** Pure terminal/continuation policy, intentionally independent of scheduling. */
2
+ export function decideLLMInvocationRound(params) {
3
+ if (params.calls.length === 0)
4
+ return { kind: 'final-model-answer' };
5
+ if (!params.autoContinue || !params.calls.every((call) => params.knownToolNames.has(call.name))) {
6
+ return { kind: 'release-unresolved-calls' };
7
+ }
8
+ if (params.completedRounds >= params.maxToolRounds)
9
+ return { kind: 'max-rounds-reached' };
10
+ return params.isDirectReturn ? { kind: 'direct-tool-response' } : { kind: 'delegate-tools' };
11
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Invocation-scoped, append-only facts collected from physical provider calls.
3
+ * It stores physical-call accounting alongside the full developer-visible LLM
4
+ * attempt diagnostics selected by the node.
5
+ */
6
+ export class LLMInvocationJournal {
7
+ #modelCalls = [];
8
+ #events = [];
9
+ #llmAttempts = [];
10
+ recordModelCall(event) {
11
+ // The host observer is allowed to inspect the same event after this local
12
+ // observer returns. Preserve an immutable-at-recording-time snapshot so a
13
+ // later observer cannot rewrite this invocation's accounting facts.
14
+ const snapshot = {
15
+ ...event,
16
+ ...(event.rawUsage == null ? {} : { rawUsage: { ...event.rawUsage } }),
17
+ ...(event.normalizedUsage == null ? {} : { normalizedUsage: { ...event.normalizedUsage } }),
18
+ pricing: { ...event.pricing },
19
+ };
20
+ this.#modelCalls.push(snapshot);
21
+ this.#events.push({ type: 'model-call', event: snapshot });
22
+ }
23
+ recordToolRound(event) {
24
+ this.#events.push({ type: 'tool-round', ...event });
25
+ }
26
+ recordLLMAttempt(attempt) {
27
+ const snapshot = { ...attempt };
28
+ this.#llmAttempts.push(snapshot);
29
+ this.#events.push({ type: 'llm-attempt', attempt: snapshot });
30
+ }
31
+ recordTerminal(event) {
32
+ this.#events.push({ type: 'terminal', ...event });
33
+ }
34
+ get modelCalls() {
35
+ return this.#modelCalls;
36
+ }
37
+ get events() {
38
+ return this.#events;
39
+ }
40
+ get llmAttempts() {
41
+ return this.#llmAttempts;
42
+ }
43
+ }
@@ -0,0 +1,68 @@
1
+ import { coerceTypeOptional } from '../../utils/coerceType.js';
2
+ import { getInputOrData } from '../../utils/inputs.js';
3
+ import { coercePromptToChatMessages, prependSystemPrompt } from '../chat/chatMessages.js';
4
+ import { getInstructionMessageRoles } from './developerMessageRoles.js';
5
+ import { createChatV2ResponseOutput, resolveChatV2ResponseFormatParameters, } from './chatV2ResponseFormat.js';
6
+ import { resolveLLMChatV2ToolChoice } from './chatV2RuntimeOptions.js';
7
+ import { shouldIncludeLLMChatV2ToolCalls } from './llmChatV2NodeData.js';
8
+ import { shouldOutputChatV2RequestBody, shouldOutputChatV2ResponseBody, } from './chatV2Types.js';
9
+ import { createChatV2ResponseBodyCapture } from './chatV2ResponseBodyCapture.js';
10
+ export function resolveLLMChatV2BaseURL(data, inputs) {
11
+ return data.provider === 'custom'
12
+ ? getInputOrData(data, inputs, 'customProviderBaseURL', 'string', 'useCustomProviderBaseURLInput')?.trim() ||
13
+ undefined
14
+ : undefined;
15
+ }
16
+ export function buildLLMInvocationPlan(params) {
17
+ const { data, inputs, context } = params;
18
+ const prompt = inputs['prompt'];
19
+ const systemPrompt = inputs['systemPrompt'];
20
+ const responseBodyCapture = shouldOutputChatV2ResponseBody(data) ? createChatV2ResponseBodyCapture() : undefined;
21
+ return {
22
+ data,
23
+ inputs,
24
+ context,
25
+ prompt,
26
+ systemPrompt,
27
+ functions: data.useToolCalling && inputs['functions'] != null
28
+ ? coerceTypeOptional(inputs['functions'], 'gpt-function[]')
29
+ : undefined,
30
+ responseFormatParameters: resolveChatV2ResponseFormatParameters(data, inputs),
31
+ toolChoice: resolveLLMChatV2ToolChoice(data),
32
+ requestBodies: shouldOutputChatV2RequestBody(data) ? [] : undefined,
33
+ responseBodies: responseBodyCapture?.bodies,
34
+ responseBodyCapture,
35
+ instructionRoles: getInstructionMessageRoles(prependSystemPrompt(coercePromptToChatMessages(prompt), systemPrompt)),
36
+ };
37
+ }
38
+ /**
39
+ * Build the provider-neutral portion of an executable round. A model is never
40
+ * fabricated here; candidate resolution supplies it before this reaches the
41
+ * request pipeline.
42
+ */
43
+ export function buildLLMInvocationRunOptions(params) {
44
+ const { plan, provider, modelId } = params;
45
+ return {
46
+ provider,
47
+ modelId,
48
+ prompt: plan.prompt,
49
+ systemPrompt: plan.systemPrompt,
50
+ functions: plan.functions,
51
+ responseOutput: createChatV2ResponseOutput(plan.responseFormatParameters, provider, plan.data.customProviderApi),
52
+ responseFormat: plan.responseFormatParameters?.responseFormat,
53
+ outputUsage: plan.data.outputUsage,
54
+ outputReasoning: plan.data.outputReasoning,
55
+ outputRequestBody: shouldOutputChatV2RequestBody(plan.data),
56
+ outputResponseBody: shouldOutputChatV2ResponseBody(plan.data),
57
+ includeFunctionCalls: shouldIncludeLLMChatV2ToolCalls(plan.data),
58
+ emitPartialOutputs: plan.data.useAsGraphPartialOutput,
59
+ toolChoice: plan.toolChoice,
60
+ requestBodies: plan.requestBodies,
61
+ responseBodies: plan.responseBodies,
62
+ responseBodyCapture: plan.responseBodyCapture,
63
+ retryOnNon200: plan.data.retryOnNon200,
64
+ retryOnNon200RepeatTimes: plan.data.retryOnNon200RepeatTimes,
65
+ retryOnNon200CooldownMs: plan.data.retryOnNon200CooldownMs,
66
+ context: plan.context,
67
+ };
68
+ }
@@ -0,0 +1,5 @@
1
+ import { summarizeChatV2PhysicalCallUsage } from './chatV2UsageAccounting.js';
2
+ /** Pure public-shape projections over privacy-bounded invocation facts. */
3
+ export function projectLLMInvocationUsage(events) {
4
+ return summarizeChatV2PhysicalCallUsage(events);
5
+ }