@valerypopoff/rivet2-core 2.1.10 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/README.md +1 -1
  2. package/dist/cjs/bundle.cjs +2604 -949
  3. package/dist/cjs/bundle.cjs.map +4 -4
  4. package/dist/cjs/webAppRuntime.cjs +1549 -99
  5. package/dist/cjs/webAppRuntime.cjs.map +4 -4
  6. package/dist/esm/api/createProcessor.js +4 -0
  7. package/dist/esm/exports.js +2 -0
  8. package/dist/esm/integrations/CodeRunner.js +2 -7
  9. package/dist/esm/integrations/CodeRunnerOptions.js +7 -0
  10. package/dist/esm/model/AgentResponseTrace.js +137 -11
  11. package/dist/esm/model/GraphProcessor.js +28 -0
  12. package/dist/esm/model/NodeExclusionPolicy.js +9 -1
  13. package/dist/esm/model/ProcessContextBuilder.js +2 -1
  14. package/dist/esm/model/RecordingPlayer.js +58 -5
  15. package/dist/esm/model/SubprocessorBridge.js +2 -0
  16. package/dist/esm/model/UiGraphActionProtocol.js +47 -4
  17. package/dist/esm/model/UiGraphBrowserRuntime.js +15 -1
  18. package/dist/esm/model/UiGraphIndexedDbPersistence.js +523 -0
  19. package/dist/esm/model/UiGraphRendererStyles.js +14 -0
  20. package/dist/esm/model/WebAppBrowserStorage.js +653 -0
  21. package/dist/esm/model/WebAppBrowserStorageRpc.js +200 -0
  22. package/dist/esm/model/chat-v2/aiSdkBridge.js +146 -14
  23. package/dist/esm/model/chat-v2/chatV2CallObserver.js +3 -0
  24. package/dist/esm/model/chat-v2/chatV2CredentialNames.js +93 -0
  25. package/dist/esm/model/chat-v2/chatV2EditorCache.js +8 -38
  26. package/dist/esm/model/chat-v2/chatV2Pipeline.js +41 -4
  27. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +31 -2
  28. package/dist/esm/model/chat-v2/chatV2ResponseBodyCapture.js +10 -2
  29. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +6 -11
  30. package/dist/esm/model/chat-v2/chatV2Shared.js +1 -1
  31. package/dist/esm/model/chat-v2/chatV2Types.js +16 -0
  32. package/dist/esm/model/chat-v2/customProviderApi.js +0 -2
  33. package/dist/esm/model/chat-v2/index.js +3 -0
  34. package/dist/esm/model/chat-v2/llmChatV2Body.js +9 -1
  35. package/dist/esm/model/chat-v2/llmChatV2CachePolicy.js +5 -0
  36. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +7 -0
  37. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +95 -14
  38. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +33 -9
  39. package/dist/esm/model/chat-v2/llmChatV2OutputClone.js +42 -0
  40. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +31 -2
  41. package/dist/esm/model/chat-v2/llmModelCandidate.js +5 -1
  42. package/dist/esm/model/chat-v2/llmProfile.js +58 -0
  43. package/dist/esm/model/chat-v2/llmProfileBody.js +10 -0
  44. package/dist/esm/model/chat-v2/llmProfileFallback.js +406 -8
  45. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +7 -0
  46. package/dist/esm/model/chat-v2/llmProfileHealthStore.js +328 -0
  47. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +57 -34
  48. package/dist/esm/model/chat-v2/providerOptions.js +33 -7
  49. package/dist/esm/model/chat-v2/toolContinuation.js +27 -1
  50. package/dist/esm/model/nodes/CodeNewNode.js +5 -47
  51. package/dist/esm/model/nodes/CodeNode.js +4 -46
  52. package/dist/esm/model/nodes/ExpressionNode.js +5 -8
  53. package/dist/esm/model/nodes/LLMChatV2Node.js +31 -3
  54. package/dist/esm/model/nodes/MatchNode.js +86 -41
  55. package/dist/esm/plugins/gentrace/gentraceSdk.js +0 -1
  56. package/dist/esm/plugins/gentrace/index.js +0 -1
  57. package/dist/esm/plugins/gentrace/plugin.js +61 -179
  58. package/dist/esm/plugins.js +1 -2
  59. package/dist/esm/recording/ExecutionRecorder.js +50 -8
  60. package/dist/esm/webAppRuntime.js +5 -2
  61. package/dist/types/api/createProcessor.d.ts +5 -0
  62. package/dist/types/exports.d.ts +2 -0
  63. package/dist/types/integrations/CodeRunner.d.ts +10 -7
  64. package/dist/types/integrations/CodeRunnerOptions.d.ts +15 -0
  65. package/dist/types/model/AgentResponseTrace.d.ts +15 -1
  66. package/dist/types/model/EditorDefinition.d.ts +16 -0
  67. package/dist/types/model/ExecutorProtocol.d.ts +17 -6
  68. package/dist/types/model/GraphProcessor.d.ts +17 -5
  69. package/dist/types/model/NodeBase.d.ts +0 -10
  70. package/dist/types/model/NodeExclusionPolicy.d.ts +6 -0
  71. package/dist/types/model/Nodes.d.ts +2 -2
  72. package/dist/types/model/ProcessContext.d.ts +85 -0
  73. package/dist/types/model/ProcessContextBuilder.d.ts +2 -1
  74. package/dist/types/model/UiGraphActionProtocol.d.ts +9 -3
  75. package/dist/types/model/UiGraphBrowserRuntime.d.ts +6 -0
  76. package/dist/types/model/UiGraphIndexedDbPersistence.d.ts +50 -0
  77. package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
  78. package/dist/types/model/WebAppBrowserStorage.d.ts +90 -0
  79. package/dist/types/model/WebAppBrowserStorageRpc.d.ts +85 -0
  80. package/dist/types/model/chat-v2/chatV2CredentialNames.d.ts +30 -0
  81. package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +1 -0
  82. package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +3 -0
  83. package/dist/types/model/chat-v2/chatV2ResponseBodyCapture.d.ts +8 -2
  84. package/dist/types/model/chat-v2/chatV2RuntimeOptions.d.ts +3 -8
  85. package/dist/types/model/chat-v2/chatV2Types.d.ts +27 -1
  86. package/dist/types/model/chat-v2/customProviderApi.d.ts +0 -1
  87. package/dist/types/model/chat-v2/index.d.ts +3 -0
  88. package/dist/types/model/chat-v2/llmChatV2CachePolicy.d.ts +1 -1
  89. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +10 -1
  90. package/dist/types/model/chat-v2/llmChatV2OutputClone.d.ts +3 -0
  91. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +5 -1
  92. package/dist/types/model/chat-v2/llmModelCandidate.d.ts +2 -0
  93. package/dist/types/model/chat-v2/llmProfile.d.ts +14 -0
  94. package/dist/types/model/chat-v2/llmProfileBody.d.ts +1 -1
  95. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +25 -2
  96. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +26 -6
  97. package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +121 -0
  98. package/dist/types/model/chat-v2/llmProfileNodeRuntime.d.ts +1 -1
  99. package/dist/types/model/chat-v2/llmProfileTypes.d.ts +9 -0
  100. package/dist/types/model/chat-v2/providerOptions.d.ts +2 -0
  101. package/dist/types/model/chat-v2/toolContinuation.d.ts +14 -0
  102. package/dist/types/model/nodes/CodeNewNode.d.ts +0 -5
  103. package/dist/types/model/nodes/CodeNode.d.ts +0 -5
  104. package/dist/types/model/nodes/MatchNode.d.ts +6 -0
  105. package/dist/types/plugins/gentrace/gentraceSdk.d.ts +0 -1
  106. package/dist/types/plugins/gentrace/plugin.d.ts +55 -9
  107. package/dist/types/plugins.d.ts +1 -1
  108. package/dist/types/recording/ExecutionRecorder.d.ts +7 -1
  109. package/dist/types/recording/RecordedEvents.d.ts +11 -0
  110. package/dist/types/webAppRuntime.d.ts +8 -2
  111. package/package.json +2 -2
@@ -1,11 +1,39 @@
1
1
  import { coerceTypeOptional } from '../../utils/coerceType.js';
2
2
  import { createChatV2Model, resolveChatV2ProviderConfig, } from './providerOptions.js';
3
3
  import { getChatV2ProviderCapabilities } from './chatV2ProviderRegistry.js';
4
- function getStringSetting(settings, key) {
5
- const value = settings[key];
4
+ import { isChatV2BuiltInProvider, normalizeChatV2CredentialNames, } from './chatV2CredentialNames.js';
5
+ function getNonEmptyString(value) {
6
6
  return typeof value === 'string' && value.trim() ? value : undefined;
7
7
  }
8
+ function getStringSetting(settings, key) {
9
+ return getNonEmptyString(settings[key]);
10
+ }
8
11
  function resolveConfiguredCredential(provider, context, options) {
12
+ if (isChatV2BuiltInProvider(provider) && options.providerApiKeyNames?.[provider] != null) {
13
+ const names = normalizeChatV2CredentialNames(provider, options.providerApiKeyNames[provider]);
14
+ const programmaticValue = getStringSetting(context.settings, names.programmaticName);
15
+ if (programmaticValue) {
16
+ return {
17
+ value: programmaticValue,
18
+ reference: { source: 'programmatic', name: names.programmaticName },
19
+ };
20
+ }
21
+ const pluginEnvValue = getNonEmptyString(context.settings.pluginEnv?.[names.environmentVariableName]);
22
+ if (pluginEnvValue) {
23
+ return {
24
+ value: pluginEnvValue,
25
+ reference: { source: 'environment', name: names.environmentVariableName },
26
+ };
27
+ }
28
+ const processValue = getNonEmptyString(globalThis.process?.env?.[names.environmentVariableName]);
29
+ if (processValue) {
30
+ return {
31
+ value: processValue,
32
+ reference: { source: 'environment', name: names.environmentVariableName },
33
+ };
34
+ }
35
+ throw new Error(`${provider} API key is not set. Pass ${names.programmaticName} programmatically or configure ${names.environmentVariableName}.`);
36
+ }
9
37
  switch (provider) {
10
38
  case 'openai': {
11
39
  const value = context.settings.openAiApiKey || context.settings.openAiKey || undefined;
@@ -82,6 +110,7 @@ export async function createResolvedChatV2Provider(options) {
82
110
  onRequestBody: options.onRequestBody,
83
111
  onResponseBody: options.onResponseBody,
84
112
  transformRequestBody: options.transformRequestBody,
113
+ requestBodyOverlay: options.requestBodyOverlay,
85
114
  customProviderApi: options.customProviderApi,
86
115
  });
87
116
  return {
@@ -15,6 +15,9 @@ function parseResponseBody(text) {
15
15
  export function createChatV2ResponseBodyCapture() {
16
16
  const entries = [];
17
17
  const bodies = [];
18
+ const publishSettledBodies = () => {
19
+ bodies.splice(0, bodies.length, ...entries.filter((entry) => entry.captured).map((entry) => entry.value));
20
+ };
18
21
  return {
19
22
  bodies,
20
23
  capture(response) {
@@ -31,6 +34,7 @@ export function createChatV2ResponseBodyCapture() {
31
34
  .then((text) => {
32
35
  entry.value = parseResponseBody(text);
33
36
  entry.captured = true;
37
+ publishSettledBodies();
34
38
  })
35
39
  .catch(() => {
36
40
  // The original response remains owned by the provider SDK.
@@ -40,7 +44,11 @@ export function createChatV2ResponseBodyCapture() {
40
44
  // A malformed or already-consumed Response has no safe diagnostic body.
41
45
  }
42
46
  },
43
- async flush() {
47
+ async flush(options = {}) {
48
+ if (options.waitForPending === false) {
49
+ publishSettledBodies();
50
+ return;
51
+ }
44
52
  // New fetches are normally sequential, but continue until no capture was
45
53
  // added while an earlier clone was settling.
46
54
  let observedEntryCount = 0;
@@ -49,7 +57,7 @@ export function createChatV2ResponseBodyCapture() {
49
57
  observedEntryCount = entries.length;
50
58
  await Promise.allSettled(pending.map((entry) => entry.settled));
51
59
  }
52
- bodies.splice(0, bodies.length, ...entries.filter((entry) => entry.captured).map((entry) => entry.value));
60
+ publishSettledBodies();
53
61
  },
54
62
  };
55
63
  }
@@ -2,9 +2,9 @@ import { createGoogleGenerativeAI } from '@ai-sdk/google';
2
2
  import { createOpenAI } from '@ai-sdk/openai';
3
3
  import { coerceTypeOptional } from '../../utils/coerceType.js';
4
4
  import { cleanHeaders, getInputOrData } from '../../utils/inputs.js';
5
+ import { cloneRivetStoredValue } from '../StoredValueStore.js';
5
6
  import { resolveChatV2Credential } from './chatV2ProviderProfile.js';
6
7
  import { applyLLMChatV2ParallelToolCallProviderOptions } from './parallelToolCalls.js';
7
- import { getCustomProviderApiContract } from './customProviderApi.js';
8
8
  export function resolveLLMChatV2Headers(data, inputs) {
9
9
  const resolvedHeaders = data.useHeadersInput && inputs['headers'] != null
10
10
  ? coerceTypeOptional(inputs['headers'], 'object')
@@ -18,6 +18,7 @@ export function resolveLLMChatV2ApiKey(data, inputs, context) {
18
18
  context,
19
19
  apiKeySource: data.apiKeySource === 'input' ? 'input' : 'configured',
20
20
  inputs,
21
+ providerApiKeyNames: data.providerApiKeyNames,
21
22
  customProgrammaticName: data.customProviderApiKeyProgrammaticName,
22
23
  customEnvironmentName: data.customProviderApiKeyEnvVarName,
23
24
  }).value;
@@ -38,16 +39,17 @@ function parseExtraProviderOptionsText(rawText) {
38
39
  return normalizeExtraProviderOptions(parsed);
39
40
  }
40
41
  function normalizeExtraProviderOptions(value) {
41
- if (value == null) {
42
+ if (value === undefined) {
42
43
  return undefined;
43
44
  }
44
45
  if (typeof value === 'string') {
45
46
  return parseExtraProviderOptionsText(value);
46
47
  }
47
- if (typeof value !== 'object' || Array.isArray(value)) {
48
+ const cloned = cloneRivetStoredValue(value, 'Extra provider options');
49
+ if (cloned === null || typeof cloned !== 'object' || Array.isArray(cloned)) {
48
50
  throw new Error('Extra provider options must be a JSON object.');
49
51
  }
50
- return value;
52
+ return cloned;
51
53
  }
52
54
  export function resolveLLMChatV2ExtraProviderOptions(data, inputs) {
53
55
  if (!data.useExtraProviderOptionsInput) {
@@ -57,13 +59,6 @@ export function resolveLLMChatV2ExtraProviderOptions(data, inputs) {
57
59
  }
58
60
  function resolveProviderOptions(data, inputs) {
59
61
  const providerOptions = {};
60
- const extraProviderOptions = resolveLLMChatV2ExtraProviderOptions(data, inputs);
61
- const providerOptionsKey = data.provider === 'custom'
62
- ? getCustomProviderApiContract(data.customProviderApi).providerOptionsKey
63
- : data.provider;
64
- if (extraProviderOptions) {
65
- providerOptions[providerOptionsKey] = extraProviderOptions;
66
- }
67
62
  if (data.provider === 'openai') {
68
63
  const previousResponseId = data.useOpenAIPreviousResponseIdInput && inputs['previousResponseId'] != null
69
64
  ? coerceTypeOptional(inputs['previousResponseId'], 'string')
@@ -22,7 +22,7 @@ export function createChatV2CommonNodeData(overrides = {}) {
22
22
  outputUsage: false,
23
23
  outputReasoning: false,
24
24
  cache: false,
25
- useAsGraphPartialOutput: true,
25
+ useAsGraphPartialOutput: false,
26
26
  ...overrides,
27
27
  };
28
28
  }
@@ -1,3 +1,19 @@
1
+ export class ChatV2ProviderTimeoutError extends Error {
2
+ timeoutKind;
3
+ timeoutMs;
4
+ code = 'RIVET_LLM_PROVIDER_TIMEOUT';
5
+ constructor(timeoutKind, timeoutMs) {
6
+ super(timeoutKind === 'first-output'
7
+ ? `LLM provider did not produce a useful response within ${timeoutMs} ms.`
8
+ : `LLM provider stream produced no activity for ${timeoutMs} ms.`);
9
+ this.timeoutKind = timeoutKind;
10
+ this.timeoutMs = timeoutMs;
11
+ this.name = 'ChatV2ProviderTimeoutError';
12
+ }
13
+ }
14
+ export function isChatV2ProviderTimeoutError(error) {
15
+ return error instanceof ChatV2ProviderTimeoutError;
16
+ }
1
17
  export function shouldOutputChatV2RequestBody(options) {
2
18
  return options.outputRequestBody === true;
3
19
  }
@@ -6,7 +6,6 @@ const customProviderApiContracts = {
6
6
  completions: {
7
7
  api: 'completions',
8
8
  adapter: 'openai-compatible',
9
- providerOptionsKey: 'custom',
10
9
  endpointPath: '/chat/completions',
11
10
  label: 'Custom Completions',
12
11
  structuredOutput: 'raw-response-format',
@@ -15,7 +14,6 @@ const customProviderApiContracts = {
15
14
  responses: {
16
15
  api: 'responses',
17
16
  adapter: 'openai-responses',
18
- providerOptionsKey: 'openai',
19
17
  endpointPath: '/responses',
20
18
  label: 'Custom Responses',
21
19
  structuredOutput: 'sdk-output',
@@ -2,11 +2,13 @@ export * from './aiSdkBridge.js';
2
2
  export * from './chatV2FeatureCompatibility.js';
3
3
  export * from './chatV2Pipeline.js';
4
4
  export * from './chatV2ProviderProfile.js';
5
+ export * from './chatV2CredentialNames.js';
5
6
  export * from './chatV2RequestPlan.js';
6
7
  export * from './chatV2ResponseFormat.js';
7
8
  export * from './chatV2Shared.js';
8
9
  export * from './chatV2Types.js';
9
10
  export * from './llmProfileTypes.js';
11
+ export * from './llmProfileHealthStore.js';
10
12
  export * from './llmProfileBody.js';
11
13
  export * from './llmChatV2Body.js';
12
14
  export * from './messageConverter.js';
@@ -16,6 +18,7 @@ export * from './toolConverter.js';
16
18
  export * from './toolContinuationConnection.js';
17
19
  export * from './chatV2ProviderRegistry.js';
18
20
  export * from './llmChatV2NodeMigration.js';
21
+ export * from './llmChatV2NodeData.js';
19
22
  export * from './llmInvocationCoordinator.js';
20
23
  export * from './llmInvocationProjections.js';
21
24
  export * from './llmInvocationDecision.js';
@@ -1,4 +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 { getNonDefaultChatV2CredentialNames } from './chatV2CredentialNames.js';
2
3
  import { getChatV2ModelInfo } from './modelRegistry.js';
3
4
  import { anthropicCacheControlTtlOptions, anthropicEffortOptions, anthropicThinkingModeOptions, getChatV2ProviderLabel, getCustomProviderApiContract, googleThinkingLevelOptions, openAIReasoningEffortOptions, openAIWebSearchContextSizeOptions, } from './providerOptions.js';
4
5
  function getOptionLabel(options, value) {
@@ -171,7 +172,7 @@ function getToolBodyFields(data) {
171
172
  }
172
173
  function getBehaviorBodyFields(data) {
173
174
  return [
174
- ...(data.useAsGraphPartialOutput === false ? [{ label: 'Stream response', value: 'Disabled' }] : []),
175
+ ...(data.useAsGraphPartialOutput ? [{ label: 'Stream response', value: 'Enabled' }] : []),
175
176
  ...(data.cache ? [{ label: 'Editor cache (legacy)', value: 'Enabled' }] : []),
176
177
  ];
177
178
  }
@@ -204,12 +205,19 @@ function getAdvancedBodySection(data) {
204
205
  }
205
206
  function getInlineModelBodyFields(data) {
206
207
  const customBaseURL = getCustomProviderBaseURLBodyValue(data);
208
+ const credentialNames = getNonDefaultChatV2CredentialNames(data.provider, data.providerApiKeyNames);
207
209
  return [
208
210
  { label: 'Provider', value: getProviderBodyLabel(data) },
209
211
  getCustomProviderApiBodyField(data),
210
212
  customBaseURL ? { label: 'Base URL', value: customBaseURL } : undefined,
211
213
  { label: 'Model', value: getModelBodyValue(data) },
212
214
  ...(data.apiKeySource === 'input' ? [{ label: 'API key source', value: 'Input port' }] : []),
215
+ ...(credentialNames != null && data.apiKeySource !== 'input'
216
+ ? [
217
+ { label: 'Programmatic API key name', value: credentialNames.programmaticName },
218
+ { label: 'API key environment variable', value: credentialNames.environmentVariableName },
219
+ ]
220
+ : []),
213
221
  ...(data.provider === 'custom' && data.apiKeySource !== 'input'
214
222
  ? [
215
223
  data.customProviderApiKeyProgrammaticName?.trim()
@@ -7,6 +7,11 @@ export function getLLMChatV2EditorCacheEligibility(data) {
7
7
  if (!data.cache) {
8
8
  return { eligible: false, reason: 'disabled' };
9
9
  }
10
+ if (data.enableCircuitBreaker === true) {
11
+ // Cross-run provider health is mutable external state. Replaying a cached
12
+ // response would bypass the health gate and make recovery diagnostics lie.
13
+ return { eligible: false, reason: 'circuit-breaker' };
14
+ }
10
15
  if (data.useToolCalling) {
11
16
  return { eligible: false, reason: 'rivet-tools' };
12
17
  }
@@ -1,6 +1,7 @@
1
1
  import { createChatV2CommonNodeData } from './chatV2Shared.js';
2
2
  import { DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_COOLDOWN_MS, DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_REPEAT_TIMES, } from './chatV2Retry.js';
3
3
  import { llmProfileDataKeys } from './llmProfileFieldRegistry.js';
4
+ import { DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_THRESHOLD, DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_WINDOW_MS, DEFAULT_LLM_PROFILE_CIRCUIT_OPEN_DURATION_MS, DEFAULT_LLM_PROFILE_FIRST_OUTPUT_TIMEOUT_MS, DEFAULT_LLM_PROFILE_STREAM_INACTIVITY_TIMEOUT_MS, } from './llmProfileHealthStore.js';
4
5
  /** @deprecated Use llmProfileDataKeys from llmProfileFieldRegistry instead. */
5
6
  export const llmChatV2ProfileDataKeys = llmProfileDataKeys;
6
7
  export function createLLMChatV2NodeData() {
@@ -40,6 +41,12 @@ export function createLLMChatV2NodeData() {
40
41
  googleIncludeThoughts: false,
41
42
  enableGoogleSearchGrounding: false,
42
43
  enableGoogleUrlContext: false,
44
+ enableCircuitBreaker: false,
45
+ firstOutputTimeoutMs: DEFAULT_LLM_PROFILE_FIRST_OUTPUT_TIMEOUT_MS,
46
+ streamInactivityTimeoutMs: DEFAULT_LLM_PROFILE_STREAM_INACTIVITY_TIMEOUT_MS,
47
+ circuitBreakerFailureThreshold: DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_THRESHOLD,
48
+ circuitBreakerFailureWindowMs: DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_WINDOW_MS,
49
+ circuitBreakerOpenDurationMs: DEFAULT_LLM_PROFILE_CIRCUIT_OPEN_DURATION_MS,
43
50
  responseFormat: '',
44
51
  responseSchemaName: '',
45
52
  useResponseSchemaNameInput: false,
@@ -1,6 +1,8 @@
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
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
+ import { DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_THRESHOLD, DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_WINDOW_MS, DEFAULT_LLM_PROFILE_CIRCUIT_OPEN_DURATION_MS, DEFAULT_LLM_PROFILE_FIRST_OUTPUT_TIMEOUT_MS, DEFAULT_LLM_PROFILE_STREAM_INACTIVITY_TIMEOUT_MS, } from './llmProfileHealthStore.js';
5
+ import { getChatV2CredentialNamesForDisplay, isChatV2BuiltInProvider } from './chatV2CredentialNames.js';
4
6
  const hideUnlessProvider = (provider) => (data) => data.provider !== provider;
5
7
  function group(label, editors, defaultOpen) {
6
8
  return {
@@ -33,11 +35,14 @@ function getApiKeySourceHelperMessage(data) {
33
35
  }
34
36
  switch (data.provider) {
35
37
  case 'openai':
36
- return 'Configured key uses Settings > LLM > OpenAI API Key in the Rivet editor, with OPENAI_API_KEY as a desktop/Node fallback. Programmatic runs can pass openAiApiKey or set OPENAI_API_KEY.';
37
38
  case 'anthropic':
38
- return 'Configured key uses Settings > LLM > Anthropic API Key in the Rivet editor, with ANTHROPIC_API_KEY as a desktop/Node fallback. Programmatic runs can pass anthropicApiKey or set ANTHROPIC_API_KEY.';
39
- case 'google':
40
- return 'Configured key uses Settings > LLM > Google API Key in the Rivet editor, with GOOGLE_GENERATIVE_AI_API_KEY as a desktop/Node fallback. Programmatic runs can pass googleApiKey or set GOOGLE_GENERATIVE_AI_API_KEY.';
39
+ case 'google': {
40
+ const names = getChatV2CredentialNamesForDisplay(data.provider, data.providerApiKeyNames?.[data.provider]);
41
+ const hasOverride = data.providerApiKeyNames?.[data.provider] != null;
42
+ return hasOverride
43
+ ? `Configured key checks ${names.programmaticName} first, then ${names.environmentVariableName}. This explicit override does not fall back to the shared provider key.`
44
+ : `Configured key uses ${names.programmaticName} or ${names.environmentVariableName}, including the existing Settings > LLM provider key.`;
45
+ }
41
46
  case 'custom': {
42
47
  const programmaticName = data.customProviderApiKeyProgrammaticName?.trim();
43
48
  const envVarName = data.customProviderApiKeyEnvVarName?.trim() || 'CUSTOM_PROVIDER_API_KEY';
@@ -93,6 +98,12 @@ function getModelEditors(modelOptions) {
93
98
  ],
94
99
  helperMessage: getApiKeySourceHelperMessage,
95
100
  },
101
+ {
102
+ type: 'custom',
103
+ label: 'Configured API key names',
104
+ customEditorId: 'LLMChatV2CredentialNames',
105
+ hideIf: (data) => !isChatV2BuiltInProvider(data.provider) || data.apiKeySource === 'input',
106
+ },
96
107
  {
97
108
  type: 'string',
98
109
  label: 'Alternative programmatic key name',
@@ -114,6 +125,75 @@ function getModelEditors(modelOptions) {
114
125
  function getProviderEditors() {
115
126
  return [getOpenAIProviderEditors(), getAnthropicProviderEditors(), getGoogleProviderEditors()];
116
127
  }
128
+ function getCircuitBreakerEditors() {
129
+ return group('LLM profile suspension', [
130
+ {
131
+ type: 'info',
132
+ label: "It's a hosted runtime capability",
133
+ helperMessage: 'This configuration is enforced by Rivet Studio Server or another host that explicitly provides shared LLM profile reliability. It has no effect in standalone Rivet.',
134
+ },
135
+ {
136
+ type: 'toggle',
137
+ label: 'Enable automatic suspension',
138
+ dataKey: 'enableCircuitBreaker',
139
+ helperMessage: 'After provider failures or timeouts, temporarily suspend this profile in the LLM profiles fallback chain. When the suspension ends, one recovery attempt checks whether the profile can resume.',
140
+ },
141
+ {
142
+ type: 'number',
143
+ label: 'Useful output wait time, seconds',
144
+ dataKey: 'firstOutputTimeoutMs',
145
+ defaultValue: DEFAULT_LLM_PROFILE_FIRST_OUTPUT_TIMEOUT_MS,
146
+ storageMultiplier: 1_000,
147
+ min: 1_000,
148
+ step: 1_000,
149
+ helperMessage: 'Maximum wait time for a non-stream response (or the first useful streamed output). A call that reaches this deadline falls back immediately, even before this profile is suspended.',
150
+ hideIf: (data) => data.enableCircuitBreaker !== true,
151
+ },
152
+ {
153
+ type: 'number',
154
+ label: 'Stream inactivity timeout, seconds',
155
+ dataKey: 'streamInactivityTimeoutMs',
156
+ defaultValue: DEFAULT_LLM_PROFILE_STREAM_INACTIVITY_TIMEOUT_MS,
157
+ storageMultiplier: 1_000,
158
+ min: 1_000,
159
+ step: 1_000,
160
+ helperMessage: 'Maximum gap between streamed response events before falling back.',
161
+ hideIf: (data) => data.enableCircuitBreaker !== true,
162
+ },
163
+ {
164
+ type: 'number',
165
+ label: 'Failures before suspension',
166
+ dataKey: 'circuitBreakerFailureThreshold',
167
+ defaultValue: DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_THRESHOLD,
168
+ min: 1,
169
+ step: 1,
170
+ helperMessage: 'Failed or timed-out profile attempts required within the failure window before suspending this profile.',
171
+ hideIf: (data) => data.enableCircuitBreaker !== true,
172
+ },
173
+ {
174
+ type: 'number',
175
+ label: 'Failure window, seconds',
176
+ dataKey: 'circuitBreakerFailureWindowMs',
177
+ defaultValue: DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_WINDOW_MS,
178
+ storageMultiplier: 1_000,
179
+ min: 1_000,
180
+ step: 1_000,
181
+ helperMessage: 'Failed or timed-out profile attempts inside this rolling window count toward suspension.',
182
+ hideIf: (data) => data.enableCircuitBreaker !== true,
183
+ },
184
+ {
185
+ type: 'number',
186
+ label: 'Suspension duration, seconds',
187
+ dataKey: 'circuitBreakerOpenDurationMs',
188
+ defaultValue: DEFAULT_LLM_PROFILE_CIRCUIT_OPEN_DURATION_MS,
189
+ storageMultiplier: 1_000,
190
+ min: 1_000,
191
+ step: 1_000,
192
+ helperMessage: 'How long the fallback chain skips this profile before allowing one recovery attempt.',
193
+ hideIf: (data) => data.enableCircuitBreaker !== true,
194
+ },
195
+ ]);
196
+ }
117
197
  function getOpenAIProviderEditors() {
118
198
  return providerGroup('openai', 'OpenAI', [
119
199
  {
@@ -318,8 +398,8 @@ function getReasoningEditors() {
318
398
  },
319
399
  ]);
320
400
  }
321
- function getResponseFormatEditors() {
322
- return group('Response format', [
401
+ function getResponseSettingsEditors() {
402
+ return group('Response settings', [
323
403
  {
324
404
  type: 'dropdown',
325
405
  label: 'Response format',
@@ -333,6 +413,12 @@ function getResponseFormatEditors() {
333
413
  defaultValue: '',
334
414
  helperMessage: 'Uses Vercel AI SDK structured-output response formatting when supported by the provider. JSON schema adds a Response Schema input port.',
335
415
  },
416
+ {
417
+ type: 'toggle',
418
+ label: 'Stream response',
419
+ dataKey: 'useAsGraphPartialOutput',
420
+ helperMessage: 'Shows streamed response updates in the node output while running in the editor. Other nodes only receive the final response after it is complete.',
421
+ },
336
422
  {
337
423
  type: 'string',
338
424
  label: 'Schema name',
@@ -440,12 +526,6 @@ function getOutputEditors() {
440
526
  dataKey: 'outputResponseBody',
441
527
  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
528
  },
443
- {
444
- type: 'toggle',
445
- label: 'Stream response',
446
- dataKey: 'useAsGraphPartialOutput',
447
- helperMessage: 'Shows streamed response updates in the node output while running in the editor. Other nodes only receive the final response after it is complete.',
448
- },
449
529
  {
450
530
  type: 'toggle',
451
531
  label: 'Cache outputs (editor only) (legacy)',
@@ -471,7 +551,7 @@ function getProviderAdvancedEditors() {
471
551
  dataKey: 'extraProviderOptions',
472
552
  useInputToggleDataKey: 'useExtraProviderOptionsInput',
473
553
  language: 'json',
474
- helperMessage: 'Power-user Vercel providerOptions for the selected provider. Enter a JSON object; visible settings above override conflicting fields.',
554
+ helperMessage: 'Adds these exact top-level JSON fields to the provider request body. Field names are preserved, and these values override generated request fields with the same name.',
475
555
  enableFolding: true,
476
556
  },
477
557
  ]);
@@ -524,7 +604,7 @@ export async function getLLMChatV2Editors(data, context) {
524
604
  ...(data.provider === 'custom' ? [] : [getReasoningEditors()]),
525
605
  ]
526
606
  : []),
527
- getResponseFormatEditors(),
607
+ getResponseSettingsEditors(),
528
608
  getToolEditors(),
529
609
  getOutputEditors(),
530
610
  ...(!usesProfile ? [getProviderAdvancedEditors()] : []),
@@ -538,6 +618,7 @@ export async function getLLMProfileEditors(data, context) {
538
618
  ...getProviderEditors(),
539
619
  getParameterEditors(),
540
620
  ...(profileData.provider === 'custom' ? [] : [getReasoningEditors()]),
621
+ getCircuitBreakerEditors(),
541
622
  getProviderAdvancedEditors(),
542
623
  ];
543
624
  }
@@ -1,6 +1,6 @@
1
1
  import { cleanHeaders } from '../../utils/inputs.js';
2
2
  import { createLLMProfileFallbackRunner, getLLMAttemptErrorMessage } from './llmProfileFallback.js';
3
- import { applyLLMProfileToNodeData, normalizeLLMProfileChainInput } from './llmProfile.js';
3
+ import { applyLLMProfileToNodeData, normalizeLLMProfileChainInput, scopeLLMProfileHealthIdentity, } from './llmProfile.js';
4
4
  import { buildLLMInvocationPlan, buildLLMInvocationRunOptions } from './llmInvocationPlan.js';
5
5
  import { resolveLLMModelCandidate } from './llmModelCandidate.js';
6
6
  import { mergeCustomProviderResponseFormatOptions } from './chatV2ResponseFormat.js';
@@ -11,6 +11,7 @@ import { buildLLMChatV2EditorCacheKey, cloneLLMChatV2EditorCacheOutputs, resolve
11
11
  import { resolveLLMChatV2GenerationParameters, resolveLLMChatV2RuntimeProviderOptions, } from './chatV2RuntimeOptions.js';
12
12
  import {} from './llmChatV2NodeData.js';
13
13
  import { isChatV2ResponseValidationError, runChatV2Pipeline } from './chatV2Pipeline.js';
14
+ import { DEFAULT_LLM_PROFILE_FIRST_OUTPUT_TIMEOUT_MS, DEFAULT_LLM_PROFILE_STREAM_INACTIVITY_TIMEOUT_MS, resolveRivetLLMProfileCircuitBreakerPolicy, } from './llmProfileHealthStore.js';
14
15
  export { buildLLMChatV2EditorCacheKey, cloneLLMChatV2EditorCacheOutputs };
15
16
  export { resolveLLMChatV2RuntimeProviderOptions } from './chatV2RuntimeOptions.js';
16
17
  export async function resolveLLMChatV2RuntimeConfig(params) {
@@ -49,6 +50,7 @@ export async function resolveLLMChatV2RuntimeConfig(params) {
49
50
  provider: inlineRunOptions.provider,
50
51
  providerConfig: inlineCandidate.providerConfig,
51
52
  providerOptions: inlineRunOptions.providerOptions,
53
+ requestBodyOverlay: inlineCandidate.requestBodyOverlay,
52
54
  responseFormatParameters: plan.responseFormatParameters,
53
55
  systemPrompt: plan.systemPrompt,
54
56
  toolChoice: plan.toolChoice,
@@ -121,7 +123,13 @@ export async function resolveLLMChatV2RuntimeConfig(params) {
121
123
  isProfileFallbackExhausted: () => false,
122
124
  };
123
125
  }
124
- const profiles = normalizeLLMProfileChainInput(profileInput?.value);
126
+ const profiles = normalizeLLMProfileChainInput(profileInput?.value).map((profile) => profile.configuration.enableCircuitBreaker !== true
127
+ ? profile
128
+ : scopeLLMProfileHealthIdentity(profile, {
129
+ projectId: context.project.metadata.id,
130
+ profileNodeId: nodeId,
131
+ chatNodeHeaders: context.settings.chatNodeHeaders,
132
+ }));
125
133
  // Profile-owned provider-native capabilities are resolved only after the
126
134
  // input profile is normalized. One cache entry covers the complete fallback
127
135
  // chain, so every possible candidate must be replay-safe.
@@ -147,19 +155,34 @@ export async function resolveLLMChatV2RuntimeConfig(params) {
147
155
  anthropicCacheControlTtl: firstProvider === 'anthropic' ? firstProfileData.anthropicCacheControlTtl || undefined : undefined,
148
156
  });
149
157
  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
- })),
158
+ candidates: profiles.map((profile) => {
159
+ const policy = resolveRivetLLMProfileCircuitBreakerPolicy(profile.configuration);
160
+ return {
161
+ provider: parseChatV2Provider(profile.configuration.provider),
162
+ model: profile.configuration.model,
163
+ ...(profile.profileName == null ? {} : { profileName: profile.profileName }),
164
+ ...(profile.configuration.provider === 'custom'
165
+ ? { customProviderApi: parseCustomProviderApi(profile.configuration.customProviderApi) }
166
+ : {}),
167
+ ...(policy == null
168
+ ? {}
169
+ : {
170
+ health: {
171
+ identity: profile.healthIdentity,
172
+ policy,
173
+ firstOutputTimeoutMs: profile.configuration.firstOutputTimeoutMs ?? DEFAULT_LLM_PROFILE_FIRST_OUTPUT_TIMEOUT_MS,
174
+ streamInactivityTimeoutMs: profile.configuration.streamInactivityTimeoutMs ?? DEFAULT_LLM_PROFILE_STREAM_INACTIVITY_TIMEOUT_MS,
175
+ },
176
+ }),
177
+ };
178
+ }),
157
179
  resolveCandidate: (profileIndex, roundOptions) => resolveLLMModelCandidate({
158
180
  plan,
159
181
  profile: profiles[profileIndex],
160
182
  roundOptions,
161
183
  }).then((candidate) => candidate.runOptions),
162
184
  onAttempt: params.onLLMAttempt,
185
+ healthStore: context.llmProfileHealthStore,
163
186
  });
164
187
  const { cacheKey, cachedOutputs } = resolveLLMChatV2EditorCache({
165
188
  apiKey: undefined,
@@ -177,6 +200,7 @@ export async function resolveLLMChatV2RuntimeConfig(params) {
177
200
  // global-header edit cannot reuse a stale profile-mode editor cache entry.
178
201
  providerConfig: { headers: cleanHeaders(context.settings?.chatNodeHeaders ?? {}) },
179
202
  providerOptions: undefined,
203
+ requestBodyOverlay: undefined,
180
204
  responseFormatParameters: plan.responseFormatParameters,
181
205
  systemPrompt: plan.systemPrompt,
182
206
  toolChoice: plan.toolChoice,
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Copies displayed LLM Chat outputs at an ownership boundary. Provider and
3
+ * continuation code intentionally continues to accumulate messages, usage,
4
+ * reasoning, and direct results after intermediate rounds complete; historical
5
+ * pages must therefore never retain those mutable references.
6
+ */
7
+ function cloneOutputValue(value, seen = new WeakMap()) {
8
+ if (value == null || typeof value !== 'object') {
9
+ return value;
10
+ }
11
+ if (value instanceof Uint8Array) {
12
+ return new Uint8Array(value);
13
+ }
14
+ const existing = seen.get(value);
15
+ if (existing != null) {
16
+ return existing;
17
+ }
18
+ if (Array.isArray(value)) {
19
+ const clone = [];
20
+ seen.set(value, clone);
21
+ clone.push(...value.map((item) => cloneOutputValue(item, seen)));
22
+ return clone;
23
+ }
24
+ const clone = {};
25
+ seen.set(value, clone);
26
+ for (const [key, item] of Object.entries(value)) {
27
+ clone[key] = cloneOutputValue(item, seen);
28
+ }
29
+ return clone;
30
+ }
31
+ /** Cycle-safe clone shared by the editor cache and LLM logical-round snapshots. */
32
+ export function cloneLLMChatV2Outputs(outputs) {
33
+ if (typeof structuredClone === 'function') {
34
+ try {
35
+ return structuredClone(outputs);
36
+ }
37
+ catch {
38
+ // Fall through for values structuredClone cannot copy.
39
+ }
40
+ }
41
+ return cloneOutputValue(outputs);
42
+ }
@@ -1,5 +1,5 @@
1
1
  import { delegateToolCall } from '../nodes/toolCallDelegation.js';
2
- import { runChatV2PipelineWithToolContinuation } from './toolContinuation.js';
2
+ import { runChatV2PipelineWithToolContinuation, } from './toolContinuation.js';
3
3
  import { isChatV2PipelineProviderFailureResult } from './chatV2Pipeline.js';
4
4
  /**
5
5
  * Owns the LLM-level recovery and continuation decision boundary. The node
@@ -9,6 +9,7 @@ import { isChatV2PipelineProviderFailureResult } from './chatV2Pipeline.js';
9
9
  export async function executeLLMInvocation(params) {
10
10
  const { context, journal, runtime, toolCallContinuation } = params;
11
11
  try {
12
+ let terminalSnapshot;
12
13
  const result = runtime.shouldAutoContinueToolCalls
13
14
  ? await runChatV2PipelineWithToolContinuation({
14
15
  ...runtime.runOptions,
@@ -42,8 +43,36 @@ export async function executeLLMInvocation(params) {
42
43
  };
43
44
  },
44
45
  runPipeline: runtime.runPipeline,
46
+ onCompletedModelRound: (snapshot) => {
47
+ try {
48
+ const observerResult = context.onLLMChatOutputSnapshot?.({
49
+ ...snapshot,
50
+ nodeId: context.node.id,
51
+ processId: context.processId,
52
+ splitIndex: context.splitIndex ?? 0,
53
+ });
54
+ // GraphProcessor already isolates its own observer. Preserve the
55
+ // same guarantee for direct node callers that provide an async
56
+ // observer themselves.
57
+ void Promise.resolve(observerResult).catch(() => undefined);
58
+ }
59
+ catch {
60
+ // History is observational; snapshot delivery cannot affect a graph run.
61
+ }
62
+ },
63
+ onTerminalRound: (snapshot) => {
64
+ terminalSnapshot = snapshot;
65
+ },
45
66
  })
46
67
  : await runtime.runPipeline(runtime.runOptions);
68
+ if (!runtime.shouldAutoContinueToolCalls && !isChatV2PipelineProviderFailureResult(result)) {
69
+ terminalSnapshot = {
70
+ entryId: 'model-round:0',
71
+ roundIndex: 0,
72
+ kind: 'model-round',
73
+ outcome: result.functionCalls.length > 0 ? 'unresolved-tool-calls' : 'final-answer',
74
+ };
75
+ }
47
76
  journal.recordTerminal({
48
77
  kind: isChatV2PipelineProviderFailureResult(result)
49
78
  ? 'failed'
@@ -51,7 +80,7 @@ export async function executeLLMInvocation(params) {
51
80
  ? 'released-unresolved-calls'
52
81
  : 'final-model-answer',
53
82
  });
54
- return result;
83
+ return { result, terminalSnapshot };
55
84
  }
56
85
  catch (error) {
57
86
  journal.recordTerminal({ kind: context.signal.aborted ? 'cancelled' : 'failed' });