@valerypopoff/rivet2-core 2.1.9 → 2.3.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 (188) hide show
  1. package/README.md +1 -1
  2. package/dist/cjs/bundle.cjs +5618 -2533
  3. package/dist/cjs/bundle.cjs.map +4 -4
  4. package/dist/cjs/webAppRuntime.cjs +333 -22
  5. package/dist/cjs/webAppRuntime.cjs.map +4 -4
  6. package/dist/esm/api/createProcessor.js +2 -0
  7. package/dist/esm/exports.js +1 -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 +558 -0
  11. package/dist/esm/model/ConnectedToolContinuationHost.js +33 -0
  12. package/dist/esm/model/GraphProcessor.js +165 -74
  13. package/dist/esm/model/NodeImpl.js +6 -0
  14. package/dist/esm/model/ProcessContextBuilder.js +3 -1
  15. package/dist/esm/model/RecordingPlayer.js +212 -25
  16. package/dist/esm/model/SplitRunProcessor.js +49 -8
  17. package/dist/esm/model/SubprocessorBridge.js +3 -0
  18. package/dist/esm/model/ToolCallContinuationCoordinator.js +7 -3
  19. package/dist/esm/model/UiGraph.js +21 -0
  20. package/dist/esm/model/UiGraphActionProtocol.js +3 -0
  21. package/dist/esm/model/UiGraphBrowserRuntime.js +133 -4
  22. package/dist/esm/model/UiGraphRendererStyles.js +221 -0
  23. package/dist/esm/model/UiGraphRuntimeModel.js +9 -3
  24. package/dist/esm/model/UiGraphSchema.js +7 -1
  25. package/dist/esm/model/chat/aiSdkTools.js +3 -2
  26. package/dist/esm/model/chat-v2/aiSdkBridge.js +146 -14
  27. package/dist/esm/model/chat-v2/chatV2CallObserver.js +11 -5
  28. package/dist/esm/model/chat-v2/chatV2CredentialNames.js +93 -0
  29. package/dist/esm/model/chat-v2/chatV2EditorCache.js +47 -20
  30. package/dist/esm/model/chat-v2/chatV2Errors.js +7 -19
  31. package/dist/esm/model/chat-v2/chatV2FeatureCompatibility.js +1 -1
  32. package/dist/esm/model/chat-v2/chatV2Outputs.js +48 -108
  33. package/dist/esm/model/chat-v2/chatV2Pipeline.js +101 -149
  34. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +39 -4
  35. package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +9 -0
  36. package/dist/esm/model/chat-v2/chatV2RequestPlan.js +2 -3
  37. package/dist/esm/model/chat-v2/chatV2ResponseBodyCapture.js +63 -0
  38. package/dist/esm/model/chat-v2/chatV2ResponseFormat.js +8 -4
  39. package/dist/esm/model/chat-v2/chatV2Retry.js +4 -3
  40. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +7 -7
  41. package/dist/esm/model/chat-v2/chatV2Shared.js +1 -1
  42. package/dist/esm/model/chat-v2/chatV2Types.js +20 -8
  43. package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +78 -0
  44. package/dist/esm/model/chat-v2/customProviderApi.js +40 -0
  45. package/dist/esm/model/chat-v2/index.js +15 -0
  46. package/dist/esm/model/chat-v2/llmChatV2Body.js +289 -0
  47. package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +32 -0
  48. package/dist/esm/model/chat-v2/llmChatV2CachePolicy.js +25 -0
  49. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +13 -50
  50. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +117 -24
  51. package/dist/esm/model/chat-v2/llmChatV2NodeMigration.js +24 -0
  52. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +150 -199
  53. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +60 -0
  54. package/dist/esm/model/chat-v2/llmInvocationDecision.js +11 -0
  55. package/dist/esm/model/chat-v2/llmInvocationJournal.js +43 -0
  56. package/dist/esm/model/chat-v2/llmInvocationPlan.js +68 -0
  57. package/dist/esm/model/chat-v2/llmInvocationProjections.js +5 -0
  58. package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +48 -0
  59. package/dist/esm/model/chat-v2/llmModelCandidate.js +79 -0
  60. package/dist/esm/model/chat-v2/llmProfile.js +52 -65
  61. package/dist/esm/model/chat-v2/llmProfileBody.js +193 -0
  62. package/dist/esm/model/chat-v2/llmProfileFallback.js +442 -100
  63. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +74 -0
  64. package/dist/esm/model/chat-v2/llmProfileHealthStore.js +326 -0
  65. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +55 -33
  66. package/dist/esm/model/chat-v2/llmProfileTypes.js +1 -18
  67. package/dist/esm/model/chat-v2/llmResponseMaterializer.js +42 -0
  68. package/dist/esm/model/chat-v2/modelRegistry.js +54 -4
  69. package/dist/esm/model/chat-v2/parallelToolCalls.js +9 -2
  70. package/dist/esm/model/chat-v2/providerOptions.js +116 -24
  71. package/dist/esm/model/chat-v2/rivetToolRegistry.js +9 -0
  72. package/dist/esm/model/chat-v2/toolCallCodec.js +52 -0
  73. package/dist/esm/model/chat-v2/toolContinuation.js +72 -35
  74. package/dist/esm/model/chat-v2/toolHandlerResolver.js +23 -0
  75. package/dist/esm/model/chat-v2/toolRoundExecutor.js +12 -0
  76. package/dist/esm/model/nodes/ChatNode.js +6 -0
  77. package/dist/esm/model/nodes/ChatNodeBase.js +1 -0
  78. package/dist/esm/model/nodes/CodeNewNode.js +5 -47
  79. package/dist/esm/model/nodes/CodeNode.js +4 -46
  80. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +19 -6
  81. package/dist/esm/model/nodes/ExpressionNode.js +5 -8
  82. package/dist/esm/model/nodes/LLMChatV2Node.js +121 -229
  83. package/dist/esm/model/nodes/LLMProfileNode.js +27 -8
  84. package/dist/esm/model/nodes/MatchNode.js +86 -41
  85. package/dist/esm/model/nodes/PromptNode.js +7 -0
  86. package/dist/esm/model/nodes/ToolNode.js +7 -0
  87. package/dist/esm/model/nodes/toolCallDelegation.js +177 -110
  88. package/dist/esm/plugins/anthropic/anthropic.js +4 -4
  89. package/dist/esm/plugins/anthropic/nodes/ChatAnthropicNode.js +7 -0
  90. package/dist/esm/plugins/gentrace/gentraceSdk.js +0 -1
  91. package/dist/esm/plugins/gentrace/index.js +0 -1
  92. package/dist/esm/plugins/gentrace/plugin.js +61 -179
  93. package/dist/esm/plugins/google/google.js +5 -9
  94. package/dist/esm/plugins/google/nodes/ChatGoogleNode.js +4 -1
  95. package/dist/esm/plugins.js +1 -2
  96. package/dist/esm/recording/ExecutionRecorder.js +62 -13
  97. package/dist/esm/utils/emitDetached.js +6 -3
  98. package/dist/esm/utils/openai.js +60 -16
  99. package/dist/esm/utils/serialization/serialization.js +2 -19
  100. package/dist/esm/webAppRuntime.js +3 -2
  101. package/dist/types/api/createProcessor.d.ts +3 -0
  102. package/dist/types/exports.d.ts +1 -0
  103. package/dist/types/integrations/CodeRunner.d.ts +10 -7
  104. package/dist/types/integrations/CodeRunnerOptions.d.ts +15 -0
  105. package/dist/types/model/AgentResponseTrace.d.ts +123 -0
  106. package/dist/types/model/ConnectedToolContinuationHost.d.ts +34 -0
  107. package/dist/types/model/EditorDefinition.d.ts +16 -0
  108. package/dist/types/model/ExecutorProtocol.d.ts +32 -11
  109. package/dist/types/model/GraphProcessor.d.ts +41 -9
  110. package/dist/types/model/NodeBase.d.ts +0 -10
  111. package/dist/types/model/NodeImpl.d.ts +18 -1
  112. package/dist/types/model/Nodes.d.ts +2 -2
  113. package/dist/types/model/ProcessContext.d.ts +99 -0
  114. package/dist/types/model/ProcessContextBuilder.d.ts +3 -1
  115. package/dist/types/model/RecordingPlayer.d.ts +6 -0
  116. package/dist/types/model/SplitRunProcessor.d.ts +10 -3
  117. package/dist/types/model/UiGraph.d.ts +8 -0
  118. package/dist/types/model/UiGraphActionProtocol.d.ts +3 -0
  119. package/dist/types/model/UiGraphBrowserRuntime.d.ts +11 -2
  120. package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
  121. package/dist/types/model/UiGraphRuntimeModel.d.ts +2 -0
  122. package/dist/types/model/UiGraphSchema.d.ts +1 -0
  123. package/dist/types/model/chat-v2/chatV2CallObserver.d.ts +2 -0
  124. package/dist/types/model/chat-v2/chatV2CredentialNames.d.ts +30 -0
  125. package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +2 -3
  126. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +6 -16
  127. package/dist/types/model/chat-v2/chatV2Pipeline.d.ts +13 -17
  128. package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +7 -0
  129. package/dist/types/model/chat-v2/chatV2ProviderRegistry.d.ts +8 -0
  130. package/dist/types/model/chat-v2/chatV2RequestPlan.d.ts +2 -2
  131. package/dist/types/model/chat-v2/chatV2ResponseBodyCapture.d.ts +25 -0
  132. package/dist/types/model/chat-v2/chatV2ResponseFormat.d.ts +3 -2
  133. package/dist/types/model/chat-v2/chatV2Retry.d.ts +2 -0
  134. package/dist/types/model/chat-v2/chatV2RuntimeOptions.d.ts +3 -8
  135. package/dist/types/model/chat-v2/chatV2Types.d.ts +44 -10
  136. package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +14 -0
  137. package/dist/types/model/chat-v2/customProviderApi.d.ts +22 -0
  138. package/dist/types/model/chat-v2/index.d.ts +15 -0
  139. package/dist/types/model/chat-v2/llmChatV2Body.d.ts +24 -0
  140. package/dist/types/model/chat-v2/llmChatV2CacheBoundary.d.ts +10 -0
  141. package/dist/types/model/chat-v2/llmChatV2CachePolicy.d.ts +13 -0
  142. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +19 -3
  143. package/dist/types/model/chat-v2/llmChatV2NodeMigration.d.ts +8 -0
  144. package/dist/types/model/chat-v2/llmChatV2NodeRuntime.d.ts +14 -16
  145. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +16 -0
  146. package/dist/types/model/chat-v2/llmInvocationDecision.d.ts +21 -0
  147. package/dist/types/model/chat-v2/llmInvocationJournal.d.ts +38 -0
  148. package/dist/types/model/chat-v2/llmInvocationPlan.d.ts +41 -0
  149. package/dist/types/model/chat-v2/llmInvocationProjections.d.ts +3 -0
  150. package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +26 -0
  151. package/dist/types/model/chat-v2/llmModelCandidate.d.ts +20 -0
  152. package/dist/types/model/chat-v2/llmProfile.d.ts +14 -0
  153. package/dist/types/model/chat-v2/llmProfileBody.d.ts +20 -0
  154. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +36 -49
  155. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +209 -0
  156. package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +111 -0
  157. package/dist/types/model/chat-v2/llmProfileNodeRuntime.d.ts +1 -1
  158. package/dist/types/model/chat-v2/llmProfileTypes.d.ts +4 -1
  159. package/dist/types/model/chat-v2/llmResponseMaterializer.d.ts +20 -0
  160. package/dist/types/model/chat-v2/modelRegistry.d.ts +17 -187
  161. package/dist/types/model/chat-v2/parallelToolCalls.d.ts +3 -1
  162. package/dist/types/model/chat-v2/providerOptions.d.ts +12 -0
  163. package/dist/types/model/chat-v2/rivetToolRegistry.d.ts +11 -0
  164. package/dist/types/model/chat-v2/toolCallCodec.d.ts +7 -0
  165. package/dist/types/model/chat-v2/toolContinuation.d.ts +3 -3
  166. package/dist/types/model/chat-v2/toolHandlerResolver.d.ts +25 -0
  167. package/dist/types/model/chat-v2/toolRoundExecutor.d.ts +18 -0
  168. package/dist/types/model/nodes/ChatNode.d.ts +2 -1
  169. package/dist/types/model/nodes/CodeNewNode.d.ts +0 -5
  170. package/dist/types/model/nodes/CodeNode.d.ts +0 -5
  171. package/dist/types/model/nodes/DelegateFunctionCallNode.d.ts +2 -1
  172. package/dist/types/model/nodes/LLMChatV2Node.d.ts +2 -1
  173. package/dist/types/model/nodes/LLMProfileNode.d.ts +2 -1
  174. package/dist/types/model/nodes/MatchNode.d.ts +6 -0
  175. package/dist/types/model/nodes/PromptNode.d.ts +4 -1
  176. package/dist/types/model/nodes/ToolNode.d.ts +2 -1
  177. package/dist/types/model/nodes/toolCallDelegation.d.ts +10 -3
  178. package/dist/types/plugins/anthropic/anthropic.d.ts +1 -0
  179. package/dist/types/plugins/gentrace/gentraceSdk.d.ts +0 -1
  180. package/dist/types/plugins/gentrace/plugin.d.ts +55 -9
  181. package/dist/types/plugins/google/google.d.ts +2 -8
  182. package/dist/types/plugins.d.ts +1 -1
  183. package/dist/types/recording/ExecutionRecorder.d.ts +7 -1
  184. package/dist/types/recording/RecordedEvents.d.ts +6 -0
  185. package/dist/types/utils/emitDetached.d.ts +3 -2
  186. package/dist/types/utils/openai.d.ts +49 -0
  187. package/dist/types/webAppRuntime.d.ts +4 -2
  188. package/package.json +2 -2
@@ -1,5 +1,76 @@
1
- import { materializeChatV2PipelineFailure, runChatV2PipelineExecution, } from './chatV2Pipeline.js';
2
- import { shouldOutputChatV2RequestError, } from './chatV2Types.js';
1
+ import { isChatV2ResponseValidationError, runChatV2PipelineExecution } from './chatV2Pipeline.js';
2
+ import {} from './chatV2Types.js';
3
+ import { getCustomProviderApiContract } from './customProviderApi.js';
4
+ import {} from './llmProfileHealthStore.js';
5
+ import { getChatV2ProviderErrorStatusCode, isChatV2ProviderApiCallError, isChatV2ProviderFetchError, } from './chatV2Errors.js';
6
+ import { isChatV2ProviderTimeoutError } from './chatV2Types.js';
7
+ const DEFAULT_LLM_PROFILE_HEALTH_OPERATION_TIMEOUT_MS = 2_000;
8
+ class LLMProfileHealthOperationTimeoutError extends Error {
9
+ constructor(operation, timeoutMs) {
10
+ super(`LLM profile reliability service ${operation} timed out after ${timeoutMs} ms.`);
11
+ this.name = 'LLMProfileHealthOperationTimeoutError';
12
+ }
13
+ }
14
+ /**
15
+ * Health persistence is deliberately fail-open, including when a remote
16
+ * implementation never settles. Invoke the operation before racing so a
17
+ * synchronous local store can still release a permit during cancellation;
18
+ * the attached handlers also consume any rejection that arrives after the
19
+ * deadline or caller abort won the race.
20
+ */
21
+ function runBoundedHealthOperation(params) {
22
+ const operationSignal = params.runWhenAborted ? undefined : params.signal;
23
+ if (operationSignal?.aborted) {
24
+ return Promise.reject(operationSignal.reason instanceof Error ? operationSignal.reason : new Error('LLM Chat request was aborted.'));
25
+ }
26
+ let result;
27
+ try {
28
+ result = params.run();
29
+ }
30
+ catch (error) {
31
+ return Promise.reject(error);
32
+ }
33
+ const operationPromise = Promise.resolve(result);
34
+ return new Promise((resolve, reject) => {
35
+ let settled = false;
36
+ const finish = (callback) => {
37
+ if (settled)
38
+ return;
39
+ settled = true;
40
+ clearTimeout(timer);
41
+ operationSignal?.removeEventListener('abort', onAbort);
42
+ callback();
43
+ };
44
+ const onAbort = () => finish(() => reject(operationSignal?.reason instanceof Error
45
+ ? operationSignal.reason
46
+ : new Error('LLM Chat request was aborted.')));
47
+ const timer = setTimeout(() => finish(() => reject(new LLMProfileHealthOperationTimeoutError(params.operation, params.timeoutMs))), params.timeoutMs);
48
+ if (operationSignal?.aborted) {
49
+ onAbort();
50
+ }
51
+ else {
52
+ operationSignal?.addEventListener('abort', onAbort, { once: true });
53
+ }
54
+ void operationPromise.then((value) => {
55
+ if (settled) {
56
+ try {
57
+ void Promise.resolve(params.onLateResolve?.(value)).catch(() => undefined);
58
+ }
59
+ catch {
60
+ // A late cleanup is observational and cannot affect the caller.
61
+ }
62
+ return;
63
+ }
64
+ finish(() => resolve(value));
65
+ }, (error) => finish(() => reject(error)));
66
+ });
67
+ }
68
+ function formatCandidateIdentity(candidate) {
69
+ const providerLabel = candidate.provider === 'custom'
70
+ ? getCustomProviderApiContract(candidate.customProviderApi).label
71
+ : candidate.provider;
72
+ return `${providerLabel}/${candidate.model}`;
73
+ }
3
74
  export class LLMProfileFallbackExhaustedError extends Error {
4
75
  attempts;
5
76
  constructor(attempts) {
@@ -8,32 +79,29 @@ export class LLMProfileFallbackExhaustedError extends Error {
8
79
  this.name = 'LLMProfileFallbackExhaustedError';
9
80
  }
10
81
  }
11
- function getSafeErrorMessage(error, candidate) {
12
- let message;
82
+ export function getLLMAttemptErrorMessage(error) {
13
83
  try {
14
- message = error instanceof Error ? error.message : String(error);
84
+ return error instanceof Error ? error.message : String(error);
15
85
  }
16
86
  catch {
17
- message = 'Provider request failed with unreadable error metadata.';
87
+ return 'Provider request failed with unreadable error metadata.';
18
88
  }
19
- // Replace longer values first so one secret which contains another cannot
20
- // leave a meaningful suffix behind. Header values can be credentials too;
21
- // callers deliberately provide every known sensitive request value here.
22
- const redactionValues = [candidate.credential, ...(candidate.redactionValues ?? [])]
23
- .filter((value) => typeof value === 'string' && value.length > 0)
24
- .sort((left, right) => right.length - left.length);
25
- for (const value of new Set(redactionValues)) {
26
- message = message.split(value).join('[redacted]');
27
- }
28
- return message.length > 1_000 ? `${message.slice(0, 997)}...` : message;
29
89
  }
30
90
  function buildExhaustedMessage(attempts) {
31
91
  const details = attempts
32
92
  .map((attempt) => {
33
- const request = attempt.attemptIndex == null ? '' : ` attempt ${attempt.attemptIndex}`;
93
+ const stage = attempt.stage === 'request'
94
+ ? `request${attempt.attemptIndex == null ? '' : ` attempt ${attempt.attemptIndex}`}`
95
+ : attempt.stage === 'response-validation'
96
+ ? 'response validation'
97
+ : attempt.stage === 'health-gate'
98
+ ? 'reliability check'
99
+ : attempt.stage === 'health-update'
100
+ ? 'reliability update'
101
+ : 'configuration';
34
102
  const status = attempt.status == null ? '' : ` (${attempt.status})`;
35
- const error = attempt.error ? `: ${attempt.error}` : '';
36
- return `Profile ${attempt.profileIndex} (${attempt.provider}/${attempt.model}), round ${attempt.roundIndex}${request}${status}${error}`;
103
+ const error = attempt.error ? `: ${attempt.error.replace(/\r\n|\r|\n/g, '\n ')}` : '';
104
+ return `Profile ${attempt.profileIndex} (${formatCandidateIdentity(attempt)}), round ${attempt.roundIndex}, ${stage} ${attempt.outcome}${status}${error}`;
37
105
  })
38
106
  .join('\n');
39
107
  return details
@@ -52,18 +120,27 @@ export function buildLLMProfileFallbackSummary(candidates, attempts) {
52
120
  return candidates
53
121
  .map((candidate, profileIndex) => {
54
122
  const profileAttempts = attempts.filter((attempt) => attempt.profileIndex === profileIndex);
55
- const identity = `Profile ${profileIndex} (${candidate.provider}/${candidate.model})`;
123
+ const identity = `Profile ${profileIndex} (${formatCandidateIdentity(candidate)})`;
56
124
  if (profileAttempts.length === 0) {
57
125
  return `${identity}: not attempted.`;
58
126
  }
59
127
  const successfulRounds = [
60
128
  ...new Set(profileAttempts
61
- .filter((attempt) => attempt.stage === 'request' && attempt.outcome === 'success')
129
+ .filter((attempt) => attempt.stage === 'request' &&
130
+ attempt.outcome === 'success' &&
131
+ !profileAttempts.some((candidate) => candidate.stage === 'response-validation' && candidate.roundIndex === attempt.roundIndex))
62
132
  .map((attempt) => attempt.roundIndex)),
63
133
  ];
64
134
  const failedConfiguration = profileAttempts.some((attempt) => attempt.stage === 'configuration' && attempt.outcome === 'failure');
65
135
  const failedRequestAttempts = profileAttempts.filter((attempt) => attempt.stage === 'request' && attempt.outcome === 'failure');
136
+ const hasSuccessfulRequest = profileAttempts.some((attempt) => attempt.stage === 'request' && attempt.outcome === 'success');
137
+ const failedResponseValidations = profileAttempts.filter((attempt) => attempt.stage === 'response-validation' && attempt.outcome === 'failure');
138
+ const latestHealthUpdate = profileAttempts
139
+ .filter((attempt) => attempt.stage === 'health-update' && attempt.outcome === 'success')
140
+ .at(-1);
66
141
  const clauses = [];
142
+ const skippedHealthGates = profileAttempts.filter((attempt) => attempt.stage === 'health-gate' && attempt.outcome === 'skipped');
143
+ const failedHealthOperations = profileAttempts.filter((attempt) => (attempt.stage === 'health-gate' || attempt.stage === 'health-update') && attempt.outcome === 'failure');
67
144
  if (successfulRounds.length > 0) {
68
145
  clauses.push(`succeeded in model ${pluralize(successfulRounds.length, 'round')} (${successfulRounds.join(', ')})`);
69
146
  }
@@ -73,49 +150,34 @@ export function buildLLMProfileFallbackSummary(candidates, attempts) {
73
150
  if (failedRequestAttempts.length > 0) {
74
151
  const lastFailedRequest = failedRequestAttempts.at(-1);
75
152
  const status = lastFailedRequest.status == null ? '' : `; last status ${lastFailedRequest.status}`;
76
- clauses.push(`failed after ${pluralize(failedRequestAttempts.length, 'provider attempt')}${status}`);
153
+ const timeout = lastFailedRequest.timeoutKind === 'first-output'
154
+ ? '; last failure timed out waiting for first useful output'
155
+ : lastFailedRequest.timeoutKind === 'stream-inactivity'
156
+ ? '; last failure timed out on stream inactivity'
157
+ : '';
158
+ clauses.push(hasSuccessfulRequest
159
+ ? `had ${pluralize(failedRequestAttempts.length, 'failed provider attempt')}${status}${timeout}`
160
+ : `failed after ${pluralize(failedRequestAttempts.length, 'provider attempt')}${status}${timeout}`);
77
161
  }
78
- return `${identity}: ${clauses.join('; ')}.`;
79
- })
80
- .join('\n');
81
- }
82
- export function buildLLMProfileRequestDiagnostics(profileCount, attempts) {
83
- const statuses = Array.from({ length: profileCount }, () => []);
84
- const errors = Array.from({ length: profileCount }, () => []);
85
- for (const attempt of attempts) {
86
- if (attempt.stage !== 'request' || attempt.profileIndex < 0 || attempt.profileIndex >= profileCount) {
87
- continue;
162
+ if (failedResponseValidations.length > 0) {
163
+ clauses.push(`failed response validation in ${pluralize(failedResponseValidations.length, 'model round')}`);
88
164
  }
89
- if (attempt.status != null) {
90
- statuses[attempt.profileIndex].push(attempt.status);
165
+ if (skippedHealthGates.length > 0) {
166
+ const retryAt = skippedHealthGates.at(-1)?.retryAt;
167
+ clauses.push(`suspended in ${pluralize(skippedHealthGates.length, 'model round')}${retryAt == null ? '' : `; next recovery attempt after ${new Date(retryAt).toISOString()}`}`);
91
168
  }
92
- if (attempt.error != null) {
93
- errors[attempt.profileIndex].push(attempt.error);
169
+ if (failedHealthOperations.length > 0) {
170
+ clauses.push(`reliability service unavailable ${pluralize(failedHealthOperations.length, 'time')}; profile was tried normally`);
94
171
  }
95
- }
96
- return {
97
- statuses: compactLLMProfileRequestStatuses(statuses),
98
- errors: compactLLMProfileRequestErrors(errors),
99
- };
100
- }
101
- /**
102
- * Preserves one profile slot per input profile while making a single physical
103
- * request easy to read. This also repairs cache entries made before the
104
- * scalar-single-status contract was introduced.
105
- */
106
- export function compactLLMProfileRequestStatuses(statuses) {
107
- return statuses.map((profileStatuses) => Array.isArray(profileStatuses) && profileStatuses.length === 1 ? profileStatuses[0] : profileStatuses);
108
- }
109
- /**
110
- * Keeps Response Error readable for profile-array fallback chains and repairs
111
- * editor-cache entries written before that compact presentation contract.
112
- */
113
- export function compactLLMProfileRequestErrors(errors) {
114
- if (errors.every((profileErrors) => Array.isArray(profileErrors) && profileErrors.length === 0)) {
115
- return [];
116
- }
117
- const compacted = errors.map((profileErrors) => Array.isArray(profileErrors) && profileErrors.length === 1 ? profileErrors[0] : profileErrors);
118
- return compacted.length === 1 ? compacted[0] ?? [] : compacted;
172
+ if (latestHealthUpdate?.healthState === 'open') {
173
+ clauses.push('profile is suspended');
174
+ }
175
+ else if (latestHealthUpdate?.healthState === 'half-open') {
176
+ clauses.push('recovery attempt is in progress');
177
+ }
178
+ return `${identity}: ${clauses.join('; ')}.`;
179
+ })
180
+ .join('\n');
119
181
  }
120
182
  function clearPartialResponse(options) {
121
183
  if (!options.emitPartialOutputs) {
@@ -133,6 +195,175 @@ function clearPartialResponse(options) {
133
195
  // A presentation callback must not prevent recovery through a fallback profile.
134
196
  }
135
197
  }
198
+ function chainStreamActivity(first, second) {
199
+ if (first == null)
200
+ return second;
201
+ if (second == null)
202
+ return first;
203
+ return () => {
204
+ first();
205
+ second();
206
+ };
207
+ }
208
+ const PROVIDER_NETWORK_ERROR_CODES = new Set([
209
+ 'ECONNABORTED',
210
+ 'ECONNREFUSED',
211
+ 'ECONNRESET',
212
+ 'EHOSTUNREACH',
213
+ 'ENETDOWN',
214
+ 'ENETUNREACH',
215
+ 'ENOTFOUND',
216
+ 'ETIMEDOUT',
217
+ 'EAI_AGAIN',
218
+ 'UND_ERR_CONNECT_TIMEOUT',
219
+ 'UND_ERR_HEADERS_TIMEOUT',
220
+ 'UND_ERR_SOCKET',
221
+ ]);
222
+ function isKnownProviderNetworkError(error) {
223
+ if (error == null || typeof error !== 'object')
224
+ return false;
225
+ const code = error.code;
226
+ return typeof code === 'string' && PROVIDER_NETWORK_ERROR_CODES.has(code.toUpperCase());
227
+ }
228
+ function findProviderFailure(error, seen = new Set()) {
229
+ if (error == null || seen.has(error))
230
+ return undefined;
231
+ seen.add(error);
232
+ if (isChatV2ProviderTimeoutError(error) ||
233
+ isChatV2ProviderFetchError(error) ||
234
+ isChatV2ProviderApiCallError(error) ||
235
+ isKnownProviderNetworkError(error)) {
236
+ return error;
237
+ }
238
+ if (typeof error !== 'object')
239
+ return undefined;
240
+ return findProviderFailure(error.cause, seen);
241
+ }
242
+ /** Classifies only provider availability failures, never local/configuration errors. */
243
+ export function isUnhealthyLLMProfileProviderFailure(error) {
244
+ const providerFailure = findProviderFailure(error);
245
+ if (providerFailure == null)
246
+ return false;
247
+ if (isChatV2ProviderTimeoutError(providerFailure) ||
248
+ isChatV2ProviderFetchError(providerFailure) ||
249
+ isKnownProviderNetworkError(providerFailure)) {
250
+ return true;
251
+ }
252
+ const status = getChatV2ProviderErrorStatusCode(providerFailure);
253
+ return status === 408 || status === 429 || (status != null && status >= 500);
254
+ }
255
+ function createHealthPermit(params) {
256
+ const { candidate, healthStore, permitId, state, roundIndex, profileIndex, operationTimeoutMs, signal, recordAttempt, } = params;
257
+ let finished = false;
258
+ let renewalInFlight = false;
259
+ let lastRenewalAt = 0;
260
+ const renewalIntervalMs = Math.max(25, Math.floor(candidate.health.policy.halfOpenLeaseMs / 3));
261
+ const baseAttempt = {
262
+ roundIndex,
263
+ profileIndex,
264
+ provider: candidate.provider,
265
+ model: candidate.model,
266
+ ...(candidate.customProviderApi == null ? {} : { customProviderApi: candidate.customProviderApi }),
267
+ profileHealthKey: candidate.health.identity.key,
268
+ };
269
+ const renewLease = async (leaseDurationMs) => {
270
+ try {
271
+ await runBoundedHealthOperation({
272
+ operation: 'renew',
273
+ timeoutMs: operationTimeoutMs,
274
+ signal,
275
+ run: () => healthStore.renew({
276
+ identity: candidate.health.identity,
277
+ permitId,
278
+ leaseDurationMs,
279
+ }),
280
+ });
281
+ }
282
+ catch (error) {
283
+ recordAttempt({
284
+ ...baseAttempt,
285
+ stage: 'health-update',
286
+ outcome: 'failure',
287
+ healthDisposition: 'fail-open',
288
+ error: getLLMAttemptErrorMessage(error),
289
+ });
290
+ }
291
+ };
292
+ // A half-open permit covers the complete logical candidate, including
293
+ // asynchronous configuration resolution, retry cooldowns, and non-streaming
294
+ // requests. Keep the lease alive independently of model output so no second
295
+ // process can enter while the legitimate probe is still working. Expiry
296
+ // remains the recovery mechanism if this owner dies.
297
+ const heartbeat = state === 'half-open'
298
+ ? setInterval(() => {
299
+ if (finished || renewalInFlight)
300
+ return;
301
+ lastRenewalAt = Date.now();
302
+ renewalInFlight = true;
303
+ void renewLease(candidate.health.policy.halfOpenLeaseMs).finally(() => {
304
+ renewalInFlight = false;
305
+ });
306
+ }, renewalIntervalMs)
307
+ : undefined;
308
+ heartbeat?.unref?.();
309
+ return {
310
+ permitId,
311
+ state,
312
+ renew: () => {
313
+ if (state !== 'half-open' || finished || renewalInFlight)
314
+ return;
315
+ const now = Date.now();
316
+ if (now - lastRenewalAt < renewalIntervalMs)
317
+ return;
318
+ lastRenewalAt = now;
319
+ renewalInFlight = true;
320
+ void renewLease(candidate.health.policy.halfOpenLeaseMs).finally(() => {
321
+ renewalInFlight = false;
322
+ });
323
+ },
324
+ renewForRetry: (cooldownMs) => state === 'half-open'
325
+ ? renewLease(candidate.health.policy.halfOpenLeaseMs + Math.max(0, cooldownMs))
326
+ : Promise.resolve(),
327
+ finish: async (outcome) => {
328
+ if (finished)
329
+ return;
330
+ finished = true;
331
+ if (heartbeat != null)
332
+ clearInterval(heartbeat);
333
+ try {
334
+ const snapshot = await runBoundedHealthOperation({
335
+ operation: 'finish',
336
+ timeoutMs: operationTimeoutMs,
337
+ signal,
338
+ runWhenAborted: true,
339
+ run: () => healthStore.finish({
340
+ identity: candidate.health.identity,
341
+ policy: candidate.health.policy,
342
+ permitId,
343
+ outcome,
344
+ }),
345
+ });
346
+ recordAttempt({
347
+ ...baseAttempt,
348
+ stage: 'health-update',
349
+ outcome: 'success',
350
+ healthState: snapshot.state,
351
+ healthOutcome: outcome,
352
+ });
353
+ }
354
+ catch (error) {
355
+ recordAttempt({
356
+ ...baseAttempt,
357
+ stage: 'health-update',
358
+ outcome: 'failure',
359
+ healthDisposition: 'fail-open',
360
+ healthOutcome: outcome,
361
+ error: getLLMAttemptErrorMessage(error),
362
+ });
363
+ }
364
+ },
365
+ };
366
+ }
136
367
  function throwIfAborted(signal) {
137
368
  if (!signal.aborted) {
138
369
  return;
@@ -149,55 +380,180 @@ function throwIfAborted(signal) {
149
380
  */
150
381
  export function createLLMProfileFallbackRunner(params) {
151
382
  const attempts = [];
383
+ const recordAttempt = (attempt) => {
384
+ attempts.push(attempt);
385
+ try {
386
+ params.onAttempt?.(attempt);
387
+ }
388
+ catch {
389
+ // Diagnostics must not alter profile recovery.
390
+ }
391
+ };
152
392
  let activeProfileIndex = 0;
153
393
  let nextRoundIndex = 0;
154
394
  let exhausted = false;
395
+ const healthOperationTimeoutMs = Math.max(1, params.healthOperationTimeoutMs ?? DEFAULT_LLM_PROFILE_HEALTH_OPERATION_TIMEOUT_MS);
155
396
  return {
156
397
  attempts,
157
398
  summary: () => buildLLMProfileFallbackSummary(params.candidates, attempts),
158
399
  wasExhausted: () => exhausted,
159
400
  run: async (roundOptions) => {
160
401
  const roundIndex = nextRoundIndex;
161
- // Only a provider failure from the terminal candidate may become normal
162
- // request-detail outputs. If a later candidate instead fails while being
163
- // configured, returning diagnostics from an earlier provider would lie
164
- // about which profile terminally failed.
165
- let terminalProviderFailure;
166
402
  let lastError;
167
403
  for (let profileIndex = activeProfileIndex; profileIndex < params.candidates.length; profileIndex++) {
168
404
  throwIfAborted(roundOptions.context.signal);
169
405
  const candidate = params.candidates[profileIndex];
406
+ // Reliability is a host-activated capability. Saved profile policy is
407
+ // intentionally inert unless the current runtime explicitly supplies
408
+ // a health store; standalone Rivet must not create process-local
409
+ // suspension state or apply the policy's provider deadlines.
410
+ const activeHealth = params.healthStore == null ? undefined : candidate.health;
411
+ const healthStore = activeHealth == null ? undefined : params.healthStore;
412
+ let healthPermit;
413
+ if (activeHealth != null && healthStore != null) {
414
+ const candidateHealth = activeHealth;
415
+ try {
416
+ const begin = await runBoundedHealthOperation({
417
+ operation: 'begin',
418
+ timeoutMs: healthOperationTimeoutMs,
419
+ signal: roundOptions.context.signal,
420
+ onLateResolve: async (lateBegin) => {
421
+ if (lateBegin.disposition !== 'allow' || !lateBegin.permitId)
422
+ return;
423
+ await healthStore.finish({
424
+ identity: candidateHealth.identity,
425
+ policy: candidateHealth.policy,
426
+ permitId: lateBegin.permitId,
427
+ outcome: 'ignored',
428
+ });
429
+ },
430
+ run: () => healthStore.begin({
431
+ identity: candidateHealth.identity,
432
+ policy: candidateHealth.policy,
433
+ }),
434
+ });
435
+ if (begin.disposition === 'deny') {
436
+ recordAttempt({
437
+ roundIndex,
438
+ profileIndex,
439
+ provider: candidate.provider,
440
+ model: candidate.model,
441
+ ...(candidate.customProviderApi == null ? {} : { customProviderApi: candidate.customProviderApi }),
442
+ stage: 'health-gate',
443
+ outcome: 'skipped',
444
+ profileHealthKey: activeHealth.identity.key,
445
+ healthState: begin.state,
446
+ healthDisposition: 'deny',
447
+ ...(begin.retryAt == null ? {} : { retryAt: begin.retryAt }),
448
+ });
449
+ clearPartialResponse(roundOptions);
450
+ continue;
451
+ }
452
+ const permitId = begin.permitId;
453
+ if (!permitId) {
454
+ throw new Error('LLM profile reliability service allowed a request without returning a permit.');
455
+ }
456
+ recordAttempt({
457
+ roundIndex,
458
+ profileIndex,
459
+ provider: candidate.provider,
460
+ model: candidate.model,
461
+ ...(candidate.customProviderApi == null ? {} : { customProviderApi: candidate.customProviderApi }),
462
+ stage: 'health-gate',
463
+ outcome: 'success',
464
+ profileHealthKey: activeHealth.identity.key,
465
+ healthState: begin.state,
466
+ healthDisposition: 'allow',
467
+ });
468
+ healthPermit = createHealthPermit({
469
+ candidate: { ...candidate, health: activeHealth },
470
+ healthStore,
471
+ permitId,
472
+ state: begin.state,
473
+ roundIndex,
474
+ profileIndex,
475
+ operationTimeoutMs: healthOperationTimeoutMs,
476
+ signal: roundOptions.context.signal,
477
+ recordAttempt,
478
+ });
479
+ }
480
+ catch (error) {
481
+ if (roundOptions.context.signal.aborted) {
482
+ throwIfAborted(roundOptions.context.signal);
483
+ }
484
+ recordAttempt({
485
+ roundIndex,
486
+ profileIndex,
487
+ provider: candidate.provider,
488
+ model: candidate.model,
489
+ ...(candidate.customProviderApi == null ? {} : { customProviderApi: candidate.customProviderApi }),
490
+ stage: 'health-gate',
491
+ outcome: 'failure',
492
+ profileHealthKey: activeHealth.identity.key,
493
+ healthDisposition: 'fail-open',
494
+ error: getLLMAttemptErrorMessage(error),
495
+ });
496
+ }
497
+ }
498
+ if (roundOptions.context.signal.aborted) {
499
+ await healthPermit?.finish('ignored');
500
+ throwIfAborted(roundOptions.context.signal);
501
+ }
170
502
  let candidateOptions;
171
503
  try {
172
504
  candidateOptions = await params.resolveCandidate(profileIndex, roundOptions);
173
505
  }
174
506
  catch (error) {
175
507
  if (roundOptions.context.signal.aborted) {
508
+ await healthPermit?.finish('ignored');
176
509
  throw error;
177
510
  }
178
511
  lastError = error;
179
- terminalProviderFailure = undefined;
180
- attempts.push({
512
+ recordAttempt({
181
513
  roundIndex,
182
514
  profileIndex,
183
515
  provider: candidate.provider,
184
516
  model: candidate.model,
517
+ ...(candidate.customProviderApi == null ? {} : { customProviderApi: candidate.customProviderApi }),
185
518
  stage: 'configuration',
186
519
  outcome: 'failure',
187
- error: getSafeErrorMessage(error, candidate),
520
+ error: getLLMAttemptErrorMessage(error),
188
521
  });
189
522
  clearPartialResponse(roundOptions);
523
+ await healthPermit?.finish('ignored');
190
524
  continue;
191
525
  }
192
526
  // Candidate resolution can be asynchronous (for example, plugin or
193
527
  // provider configuration). Do not start a physical request if the
194
528
  // graph was cancelled while that resolution was in flight.
195
- throwIfAborted(roundOptions.context.signal);
529
+ if (roundOptions.context.signal.aborted) {
530
+ await healthPermit?.finish('ignored');
531
+ throwIfAborted(roundOptions.context.signal);
532
+ }
533
+ // Candidate resolution can consume a meaningful part of a half-open
534
+ // lease. Refresh it immediately before the first physical request in
535
+ // addition to the lifecycle heartbeat so the request starts with a
536
+ // complete deadline window.
537
+ await healthPermit?.renewForRetry(0);
196
538
  const previousOnProviderAttempt = candidateOptions.onProviderAttempt;
197
539
  candidateOptions = {
198
540
  ...candidateOptions,
199
541
  profileIndex,
200
542
  roundIndex,
543
+ ...(activeHealth == null
544
+ ? {}
545
+ : {
546
+ profileHealthKey: activeHealth.identity.key,
547
+ ...(healthPermit == null ? {} : { profileHealthState: healthPermit.state }),
548
+ }),
549
+ ...(activeHealth == null
550
+ ? {}
551
+ : {
552
+ firstOutputTimeoutMs: activeHealth.firstOutputTimeoutMs,
553
+ streamInactivityTimeoutMs: activeHealth.streamInactivityTimeoutMs,
554
+ onStreamActivity: chainStreamActivity(candidateOptions.onStreamActivity, healthPermit?.renew),
555
+ onBeforeProviderRetry: healthPermit?.renewForRetry,
556
+ }),
201
557
  onProviderAttempt: (attempt) => {
202
558
  try {
203
559
  previousOnProviderAttempt?.(attempt);
@@ -206,16 +562,18 @@ export function createLLMProfileFallbackRunner(params) {
206
562
  // A caller-owned observer must not prevent this runner from
207
563
  // retaining the profile-chain diagnostics it owns.
208
564
  }
209
- attempts.push({
565
+ recordAttempt({
210
566
  roundIndex,
211
567
  profileIndex,
212
568
  provider: candidate.provider,
213
569
  model: candidate.model,
570
+ ...(candidate.customProviderApi == null ? {} : { customProviderApi: candidate.customProviderApi }),
214
571
  stage: 'request',
215
- outcome: attempt.outcome === 'success' ? 'success' : 'failure',
572
+ outcome: attempt.outcome === 'success' ? 'success' : attempt.outcome === 'aborted' ? 'aborted' : 'failure',
216
573
  attemptIndex: attempt.attemptIndex,
217
574
  ...(attempt.status == null ? {} : { status: attempt.status }),
218
- ...(attempt.error == null ? {} : { error: getSafeErrorMessage(attempt.error, candidate) }),
575
+ ...(attempt.error == null ? {} : { error: getLLMAttemptErrorMessage(attempt.error) }),
576
+ ...(isChatV2ProviderTimeoutError(attempt.error) ? { timeoutKind: attempt.error.timeoutKind } : {}),
219
577
  });
220
578
  },
221
579
  };
@@ -225,6 +583,7 @@ export function createLLMProfileFallbackRunner(params) {
225
583
  }
226
584
  catch (error) {
227
585
  if (roundOptions.context.signal.aborted) {
586
+ await healthPermit?.finish('ignored');
228
587
  throw error;
229
588
  }
230
589
  // The candidate's provider/model is part of request construction.
@@ -232,56 +591,39 @@ export function createLLMProfileFallbackRunner(params) {
232
591
  // exactly what a fallback chain is intended to recover from. This
233
592
  // also lets a later profile whose provider supports the same shared
234
593
  // prompt/schema continue. If every candidate has the same graph
235
- // configuration problem, the aggregate error retains a safe record
236
- // of every failed candidate.
594
+ // configuration problem, the aggregate error retains every failed
595
+ // candidate diagnostic.
237
596
  lastError = error;
238
- terminalProviderFailure = undefined;
239
- attempts.push({
597
+ const responseValidationFailure = isChatV2ResponseValidationError(error);
598
+ recordAttempt({
240
599
  roundIndex,
241
600
  profileIndex,
242
601
  provider: candidate.provider,
243
602
  model: candidate.model,
244
- stage: 'configuration',
603
+ ...(candidate.customProviderApi == null ? {} : { customProviderApi: candidate.customProviderApi }),
604
+ stage: responseValidationFailure ? 'response-validation' : 'configuration',
245
605
  outcome: 'failure',
246
- error: getSafeErrorMessage(error, candidate),
606
+ error: getLLMAttemptErrorMessage(error),
247
607
  });
248
608
  clearPartialResponse(roundOptions);
609
+ await healthPermit?.finish('ignored');
249
610
  continue;
250
611
  }
251
612
  if (execution.outcome === 'success') {
613
+ await healthPermit?.finish('healthy');
252
614
  activeProfileIndex = profileIndex;
253
615
  nextRoundIndex += 1;
254
616
  return execution.result;
255
617
  }
256
- terminalProviderFailure = execution.failure;
257
618
  lastError = execution.failure.normalizedError;
619
+ await healthPermit?.finish(isUnhealthyLLMProfileProviderFailure(execution.failure.normalizedError) ? 'unhealthy' : 'ignored');
258
620
  clearPartialResponse(roundOptions);
259
621
  }
260
622
  exhausted = true;
261
- if (params.candidates.length === 1 && terminalProviderFailure != null) {
262
- return materializeChatV2PipelineFailure(terminalProviderFailure);
263
- }
264
- // A scalar profile must preserve the legacy error surface for setup or
265
- // request-planning failures that occurred before the pipeline could
266
- // produce a provider-failure result.
623
+ // A scalar profile keeps its underlying provider/configuration error.
267
624
  if (params.candidates.length === 1 && lastError !== undefined) {
268
625
  throw lastError;
269
626
  }
270
- if (terminalProviderFailure != null &&
271
- (terminalProviderFailure.options.outputRequestStatus ||
272
- shouldOutputChatV2RequestError(terminalProviderFailure.options))) {
273
- try {
274
- return materializeChatV2PipelineFailure(terminalProviderFailure);
275
- }
276
- catch {
277
- // Some response-generation failures intentionally remain node errors
278
- // even when request details are enabled. The chain error below keeps
279
- // the complete profile history without hiding that failure.
280
- }
281
- }
282
- // `lastError` can contain raw provider metadata. The attempt records are
283
- // intentionally redacted, so do not attach the raw error as `cause` and
284
- // accidentally expose it through node/error serialization.
285
627
  throw new LLMProfileFallbackExhaustedError(attempts);
286
628
  },
287
629
  };