@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,6 +1,70 @@
1
1
  import { isChatV2ResponseValidationError, runChatV2PipelineExecution } from './chatV2Pipeline.js';
2
2
  import {} from './chatV2Types.js';
3
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
+ }
4
68
  function formatCandidateIdentity(candidate) {
5
69
  const providerLabel = candidate.provider === 'custom'
6
70
  ? getCustomProviderApiContract(candidate.customProviderApi).label
@@ -23,6 +87,11 @@ export function getLLMAttemptErrorMessage(error) {
23
87
  return 'Provider request failed with unreadable error metadata.';
24
88
  }
25
89
  }
90
+ function formatCandidateProfileIdentity(candidate, profileIndex) {
91
+ const profileName = candidate.profileName?.trim();
92
+ const identity = formatCandidateIdentity(candidate);
93
+ return profileName ? `${profileName} (profile ${profileIndex + 1}; ${identity})` : `Profile ${profileIndex + 1} (${identity})`;
94
+ }
26
95
  function buildExhaustedMessage(attempts) {
27
96
  const details = attempts
28
97
  .map((attempt) => {
@@ -30,10 +99,14 @@ function buildExhaustedMessage(attempts) {
30
99
  ? `request${attempt.attemptIndex == null ? '' : ` attempt ${attempt.attemptIndex}`}`
31
100
  : attempt.stage === 'response-validation'
32
101
  ? 'response validation'
33
- : 'configuration';
102
+ : attempt.stage === 'health-gate'
103
+ ? 'reliability check'
104
+ : attempt.stage === 'health-update'
105
+ ? 'reliability update'
106
+ : 'configuration';
34
107
  const status = attempt.status == null ? '' : ` (${attempt.status})`;
35
108
  const error = attempt.error ? `: ${attempt.error.replace(/\r\n|\r|\n/g, '\n ')}` : '';
36
- return `Profile ${attempt.profileIndex} (${formatCandidateIdentity(attempt)}), round ${attempt.roundIndex}, ${stage} ${attempt.outcome}${status}${error}`;
109
+ return `${formatCandidateProfileIdentity(attempt, attempt.profileIndex ?? 0)}, round ${attempt.roundIndex + 1}, ${stage} ${attempt.outcome}${status}${error}`;
37
110
  })
38
111
  .join('\n');
39
112
  return details
@@ -52,7 +125,7 @@ export function buildLLMProfileFallbackSummary(candidates, attempts) {
52
125
  return candidates
53
126
  .map((candidate, profileIndex) => {
54
127
  const profileAttempts = attempts.filter((attempt) => attempt.profileIndex === profileIndex);
55
- const identity = `Profile ${profileIndex} (${formatCandidateIdentity(candidate)})`;
128
+ const identity = formatCandidateProfileIdentity(candidate, profileIndex);
56
129
  if (profileAttempts.length === 0) {
57
130
  return `${identity}: not attempted.`;
58
131
  }
@@ -67,7 +140,12 @@ export function buildLLMProfileFallbackSummary(candidates, attempts) {
67
140
  const failedRequestAttempts = profileAttempts.filter((attempt) => attempt.stage === 'request' && attempt.outcome === 'failure');
68
141
  const hasSuccessfulRequest = profileAttempts.some((attempt) => attempt.stage === 'request' && attempt.outcome === 'success');
69
142
  const failedResponseValidations = profileAttempts.filter((attempt) => attempt.stage === 'response-validation' && attempt.outcome === 'failure');
143
+ const latestHealthUpdate = profileAttempts
144
+ .filter((attempt) => attempt.stage === 'health-update' && attempt.outcome === 'success')
145
+ .at(-1);
70
146
  const clauses = [];
147
+ const skippedHealthGates = profileAttempts.filter((attempt) => attempt.stage === 'health-gate' && attempt.outcome === 'skipped');
148
+ const failedHealthOperations = profileAttempts.filter((attempt) => (attempt.stage === 'health-gate' || attempt.stage === 'health-update') && attempt.outcome === 'failure');
71
149
  if (successfulRounds.length > 0) {
72
150
  clauses.push(`succeeded in model ${pluralize(successfulRounds.length, 'round')} (${successfulRounds.join(', ')})`);
73
151
  }
@@ -77,13 +155,31 @@ export function buildLLMProfileFallbackSummary(candidates, attempts) {
77
155
  if (failedRequestAttempts.length > 0) {
78
156
  const lastFailedRequest = failedRequestAttempts.at(-1);
79
157
  const status = lastFailedRequest.status == null ? '' : `; last status ${lastFailedRequest.status}`;
158
+ const timeout = lastFailedRequest.timeoutKind === 'first-output'
159
+ ? '; last failure timed out waiting for first useful output'
160
+ : lastFailedRequest.timeoutKind === 'stream-inactivity'
161
+ ? '; last failure timed out on stream inactivity'
162
+ : '';
80
163
  clauses.push(hasSuccessfulRequest
81
- ? `had ${pluralize(failedRequestAttempts.length, 'failed provider attempt')}${status}`
82
- : `failed after ${pluralize(failedRequestAttempts.length, 'provider attempt')}${status}`);
164
+ ? `had ${pluralize(failedRequestAttempts.length, 'failed provider attempt')}${status}${timeout}`
165
+ : `failed after ${pluralize(failedRequestAttempts.length, 'provider attempt')}${status}${timeout}`);
83
166
  }
84
167
  if (failedResponseValidations.length > 0) {
85
168
  clauses.push(`failed response validation in ${pluralize(failedResponseValidations.length, 'model round')}`);
86
169
  }
170
+ if (skippedHealthGates.length > 0) {
171
+ const retryAt = skippedHealthGates.at(-1)?.retryAt;
172
+ clauses.push(`suspended in ${pluralize(skippedHealthGates.length, 'model round')}${retryAt == null ? '' : `; next recovery attempt after ${new Date(retryAt).toISOString()}`}`);
173
+ }
174
+ if (failedHealthOperations.length > 0) {
175
+ clauses.push(`reliability service unavailable ${pluralize(failedHealthOperations.length, 'time')}; profile was tried normally`);
176
+ }
177
+ if (latestHealthUpdate?.healthState === 'open') {
178
+ clauses.push('profile is suspended');
179
+ }
180
+ else if (latestHealthUpdate?.healthState === 'half-open') {
181
+ clauses.push('recovery attempt is in progress');
182
+ }
87
183
  return `${identity}: ${clauses.join('; ')}.`;
88
184
  })
89
185
  .join('\n');
@@ -104,6 +200,176 @@ function clearPartialResponse(options) {
104
200
  // A presentation callback must not prevent recovery through a fallback profile.
105
201
  }
106
202
  }
203
+ function chainStreamActivity(first, second) {
204
+ if (first == null)
205
+ return second;
206
+ if (second == null)
207
+ return first;
208
+ return () => {
209
+ first();
210
+ second();
211
+ };
212
+ }
213
+ const PROVIDER_NETWORK_ERROR_CODES = new Set([
214
+ 'ECONNABORTED',
215
+ 'ECONNREFUSED',
216
+ 'ECONNRESET',
217
+ 'EHOSTUNREACH',
218
+ 'ENETDOWN',
219
+ 'ENETUNREACH',
220
+ 'ENOTFOUND',
221
+ 'ETIMEDOUT',
222
+ 'EAI_AGAIN',
223
+ 'UND_ERR_CONNECT_TIMEOUT',
224
+ 'UND_ERR_HEADERS_TIMEOUT',
225
+ 'UND_ERR_SOCKET',
226
+ ]);
227
+ function isKnownProviderNetworkError(error) {
228
+ if (error == null || typeof error !== 'object')
229
+ return false;
230
+ const code = error.code;
231
+ return typeof code === 'string' && PROVIDER_NETWORK_ERROR_CODES.has(code.toUpperCase());
232
+ }
233
+ function findProviderFailure(error, seen = new Set()) {
234
+ if (error == null || seen.has(error))
235
+ return undefined;
236
+ seen.add(error);
237
+ if (isChatV2ProviderTimeoutError(error) ||
238
+ isChatV2ProviderFetchError(error) ||
239
+ isChatV2ProviderApiCallError(error) ||
240
+ isKnownProviderNetworkError(error)) {
241
+ return error;
242
+ }
243
+ if (typeof error !== 'object')
244
+ return undefined;
245
+ return findProviderFailure(error.cause, seen);
246
+ }
247
+ /** Classifies only provider availability failures, never local/configuration errors. */
248
+ export function isUnhealthyLLMProfileProviderFailure(error) {
249
+ const providerFailure = findProviderFailure(error);
250
+ if (providerFailure == null)
251
+ return false;
252
+ if (isChatV2ProviderTimeoutError(providerFailure) ||
253
+ isChatV2ProviderFetchError(providerFailure) ||
254
+ isKnownProviderNetworkError(providerFailure)) {
255
+ return true;
256
+ }
257
+ const status = getChatV2ProviderErrorStatusCode(providerFailure);
258
+ return status === 408 || status === 429 || (status != null && status >= 500);
259
+ }
260
+ function createHealthPermit(params) {
261
+ const { candidate, healthStore, permitId, state, roundIndex, profileIndex, operationTimeoutMs, executionCorrelationId, signal, recordAttempt, } = params;
262
+ let finished = false;
263
+ let renewalInFlight = false;
264
+ let lastRenewalAt = 0;
265
+ const renewalIntervalMs = Math.max(25, Math.floor(candidate.health.policy.halfOpenLeaseMs / 3));
266
+ const baseAttempt = {
267
+ roundIndex,
268
+ profileIndex,
269
+ provider: candidate.provider,
270
+ model: candidate.model,
271
+ ...(candidate.customProviderApi == null ? {} : { customProviderApi: candidate.customProviderApi }),
272
+ profileHealthKey: candidate.health.identity.key,
273
+ };
274
+ const renewLease = async (leaseDurationMs) => {
275
+ try {
276
+ await runBoundedHealthOperation({
277
+ operation: 'renew',
278
+ timeoutMs: operationTimeoutMs,
279
+ signal,
280
+ run: () => healthStore.renew({
281
+ identity: candidate.health.identity,
282
+ permitId,
283
+ leaseDurationMs,
284
+ }),
285
+ });
286
+ }
287
+ catch (error) {
288
+ recordAttempt({
289
+ ...baseAttempt,
290
+ stage: 'health-update',
291
+ outcome: 'failure',
292
+ healthDisposition: 'fail-open',
293
+ error: getLLMAttemptErrorMessage(error),
294
+ });
295
+ }
296
+ };
297
+ // A half-open permit covers the complete logical candidate, including
298
+ // asynchronous configuration resolution, retry cooldowns, and non-streaming
299
+ // requests. Keep the lease alive independently of model output so no second
300
+ // process can enter while the legitimate probe is still working. Expiry
301
+ // remains the recovery mechanism if this owner dies.
302
+ const heartbeat = state === 'half-open'
303
+ ? setInterval(() => {
304
+ if (finished || renewalInFlight)
305
+ return;
306
+ lastRenewalAt = Date.now();
307
+ renewalInFlight = true;
308
+ void renewLease(candidate.health.policy.halfOpenLeaseMs).finally(() => {
309
+ renewalInFlight = false;
310
+ });
311
+ }, renewalIntervalMs)
312
+ : undefined;
313
+ heartbeat?.unref?.();
314
+ return {
315
+ permitId,
316
+ state,
317
+ renew: () => {
318
+ if (state !== 'half-open' || finished || renewalInFlight)
319
+ return;
320
+ const now = Date.now();
321
+ if (now - lastRenewalAt < renewalIntervalMs)
322
+ return;
323
+ lastRenewalAt = now;
324
+ renewalInFlight = true;
325
+ void renewLease(candidate.health.policy.halfOpenLeaseMs).finally(() => {
326
+ renewalInFlight = false;
327
+ });
328
+ },
329
+ renewForRetry: (cooldownMs) => state === 'half-open'
330
+ ? renewLease(candidate.health.policy.halfOpenLeaseMs + Math.max(0, cooldownMs))
331
+ : Promise.resolve(),
332
+ finish: async (outcome) => {
333
+ if (finished)
334
+ return;
335
+ finished = true;
336
+ if (heartbeat != null)
337
+ clearInterval(heartbeat);
338
+ try {
339
+ const snapshot = await runBoundedHealthOperation({
340
+ operation: 'finish',
341
+ timeoutMs: operationTimeoutMs,
342
+ signal,
343
+ runWhenAborted: true,
344
+ run: () => healthStore.finish({
345
+ identity: candidate.health.identity,
346
+ policy: candidate.health.policy,
347
+ permitId,
348
+ outcome,
349
+ ...(executionCorrelationId == null ? {} : { executionCorrelationId }),
350
+ }),
351
+ });
352
+ recordAttempt({
353
+ ...baseAttempt,
354
+ stage: 'health-update',
355
+ outcome: 'success',
356
+ healthState: snapshot.state,
357
+ healthOutcome: outcome,
358
+ });
359
+ }
360
+ catch (error) {
361
+ recordAttempt({
362
+ ...baseAttempt,
363
+ stage: 'health-update',
364
+ outcome: 'failure',
365
+ healthDisposition: 'fail-open',
366
+ healthOutcome: outcome,
367
+ error: getLLMAttemptErrorMessage(error),
368
+ });
369
+ }
370
+ },
371
+ };
372
+ }
107
373
  function throwIfAborted(signal) {
108
374
  if (!signal.aborted) {
109
375
  return;
@@ -121,9 +387,13 @@ function throwIfAborted(signal) {
121
387
  export function createLLMProfileFallbackRunner(params) {
122
388
  const attempts = [];
123
389
  const recordAttempt = (attempt) => {
124
- attempts.push(attempt);
390
+ const candidate = attempt.profileIndex == null ? undefined : params.candidates[attempt.profileIndex];
391
+ const completedAttempt = attempt.profileName == null && candidate?.profileName != null
392
+ ? { ...attempt, profileName: candidate.profileName }
393
+ : attempt;
394
+ attempts.push(completedAttempt);
125
395
  try {
126
- params.onAttempt?.(attempt);
396
+ params.onAttempt?.(completedAttempt);
127
397
  }
128
398
  catch {
129
399
  // Diagnostics must not alter profile recovery.
@@ -132,6 +402,7 @@ export function createLLMProfileFallbackRunner(params) {
132
402
  let activeProfileIndex = 0;
133
403
  let nextRoundIndex = 0;
134
404
  let exhausted = false;
405
+ const healthOperationTimeoutMs = Math.max(1, params.healthOperationTimeoutMs ?? DEFAULT_LLM_PROFILE_HEALTH_OPERATION_TIMEOUT_MS);
135
406
  return {
136
407
  attempts,
137
408
  summary: () => buildLLMProfileFallbackSummary(params.candidates, attempts),
@@ -142,12 +413,110 @@ export function createLLMProfileFallbackRunner(params) {
142
413
  for (let profileIndex = activeProfileIndex; profileIndex < params.candidates.length; profileIndex++) {
143
414
  throwIfAborted(roundOptions.context.signal);
144
415
  const candidate = params.candidates[profileIndex];
416
+ // Reliability is a host-activated capability. Saved profile policy is
417
+ // intentionally inert unless the current runtime explicitly supplies
418
+ // a health store; standalone Rivet must not create process-local
419
+ // suspension state or apply the policy's provider deadlines.
420
+ const activeHealth = params.healthStore == null ? undefined : candidate.health;
421
+ const healthStore = activeHealth == null ? undefined : params.healthStore;
422
+ let healthPermit;
423
+ if (activeHealth != null && healthStore != null) {
424
+ const candidateHealth = activeHealth;
425
+ try {
426
+ const begin = await runBoundedHealthOperation({
427
+ operation: 'begin',
428
+ timeoutMs: healthOperationTimeoutMs,
429
+ signal: roundOptions.context.signal,
430
+ onLateResolve: async (lateBegin) => {
431
+ if (lateBegin.disposition !== 'allow' || !lateBegin.permitId)
432
+ return;
433
+ await healthStore.finish({
434
+ identity: candidateHealth.identity,
435
+ policy: candidateHealth.policy,
436
+ permitId: lateBegin.permitId,
437
+ outcome: 'ignored',
438
+ });
439
+ },
440
+ run: () => healthStore.begin({
441
+ identity: candidateHealth.identity,
442
+ policy: candidateHealth.policy,
443
+ }),
444
+ });
445
+ if (begin.disposition === 'deny') {
446
+ recordAttempt({
447
+ roundIndex,
448
+ profileIndex,
449
+ provider: candidate.provider,
450
+ model: candidate.model,
451
+ ...(candidate.customProviderApi == null ? {} : { customProviderApi: candidate.customProviderApi }),
452
+ stage: 'health-gate',
453
+ outcome: 'skipped',
454
+ profileHealthKey: activeHealth.identity.key,
455
+ healthState: begin.state,
456
+ healthDisposition: 'deny',
457
+ ...(begin.retryAt == null ? {} : { retryAt: begin.retryAt }),
458
+ });
459
+ clearPartialResponse(roundOptions);
460
+ continue;
461
+ }
462
+ const permitId = begin.permitId;
463
+ if (!permitId) {
464
+ throw new Error('LLM profile reliability service allowed a request without returning a permit.');
465
+ }
466
+ recordAttempt({
467
+ roundIndex,
468
+ profileIndex,
469
+ provider: candidate.provider,
470
+ model: candidate.model,
471
+ ...(candidate.customProviderApi == null ? {} : { customProviderApi: candidate.customProviderApi }),
472
+ stage: 'health-gate',
473
+ outcome: 'success',
474
+ profileHealthKey: activeHealth.identity.key,
475
+ healthState: begin.state,
476
+ healthDisposition: 'allow',
477
+ });
478
+ healthPermit = createHealthPermit({
479
+ candidate: { ...candidate, health: activeHealth },
480
+ healthStore,
481
+ permitId,
482
+ state: begin.state,
483
+ roundIndex,
484
+ profileIndex,
485
+ operationTimeoutMs: healthOperationTimeoutMs,
486
+ executionCorrelationId: roundOptions.context.llmProfileHealthExecutionCorrelationId,
487
+ signal: roundOptions.context.signal,
488
+ recordAttempt,
489
+ });
490
+ }
491
+ catch (error) {
492
+ if (roundOptions.context.signal.aborted) {
493
+ throwIfAborted(roundOptions.context.signal);
494
+ }
495
+ recordAttempt({
496
+ roundIndex,
497
+ profileIndex,
498
+ provider: candidate.provider,
499
+ model: candidate.model,
500
+ ...(candidate.customProviderApi == null ? {} : { customProviderApi: candidate.customProviderApi }),
501
+ stage: 'health-gate',
502
+ outcome: 'failure',
503
+ profileHealthKey: activeHealth.identity.key,
504
+ healthDisposition: 'fail-open',
505
+ error: getLLMAttemptErrorMessage(error),
506
+ });
507
+ }
508
+ }
509
+ if (roundOptions.context.signal.aborted) {
510
+ await healthPermit?.finish('ignored');
511
+ throwIfAborted(roundOptions.context.signal);
512
+ }
145
513
  let candidateOptions;
146
514
  try {
147
515
  candidateOptions = await params.resolveCandidate(profileIndex, roundOptions);
148
516
  }
149
517
  catch (error) {
150
518
  if (roundOptions.context.signal.aborted) {
519
+ await healthPermit?.finish('ignored');
151
520
  throw error;
152
521
  }
153
522
  lastError = error;
@@ -162,17 +531,41 @@ export function createLLMProfileFallbackRunner(params) {
162
531
  error: getLLMAttemptErrorMessage(error),
163
532
  });
164
533
  clearPartialResponse(roundOptions);
534
+ await healthPermit?.finish('ignored');
165
535
  continue;
166
536
  }
167
537
  // Candidate resolution can be asynchronous (for example, plugin or
168
538
  // provider configuration). Do not start a physical request if the
169
539
  // graph was cancelled while that resolution was in flight.
170
- throwIfAborted(roundOptions.context.signal);
540
+ if (roundOptions.context.signal.aborted) {
541
+ await healthPermit?.finish('ignored');
542
+ throwIfAborted(roundOptions.context.signal);
543
+ }
544
+ // Candidate resolution can consume a meaningful part of a half-open
545
+ // lease. Refresh it immediately before the first physical request in
546
+ // addition to the lifecycle heartbeat so the request starts with a
547
+ // complete deadline window.
548
+ await healthPermit?.renewForRetry(0);
171
549
  const previousOnProviderAttempt = candidateOptions.onProviderAttempt;
172
550
  candidateOptions = {
173
551
  ...candidateOptions,
174
552
  profileIndex,
175
553
  roundIndex,
554
+ ...(candidate.profileName == null ? {} : { profileName: candidate.profileName }),
555
+ ...(activeHealth == null
556
+ ? {}
557
+ : {
558
+ profileHealthKey: activeHealth.identity.key,
559
+ ...(healthPermit == null ? {} : { profileHealthState: healthPermit.state }),
560
+ }),
561
+ ...(activeHealth == null
562
+ ? {}
563
+ : {
564
+ firstOutputTimeoutMs: activeHealth.firstOutputTimeoutMs,
565
+ streamInactivityTimeoutMs: activeHealth.streamInactivityTimeoutMs,
566
+ onStreamActivity: chainStreamActivity(candidateOptions.onStreamActivity, healthPermit?.renew),
567
+ onBeforeProviderRetry: healthPermit?.renewForRetry,
568
+ }),
176
569
  onProviderAttempt: (attempt) => {
177
570
  try {
178
571
  previousOnProviderAttempt?.(attempt);
@@ -192,6 +585,7 @@ export function createLLMProfileFallbackRunner(params) {
192
585
  attemptIndex: attempt.attemptIndex,
193
586
  ...(attempt.status == null ? {} : { status: attempt.status }),
194
587
  ...(attempt.error == null ? {} : { error: getLLMAttemptErrorMessage(attempt.error) }),
588
+ ...(isChatV2ProviderTimeoutError(attempt.error) ? { timeoutKind: attempt.error.timeoutKind } : {}),
195
589
  });
196
590
  },
197
591
  };
@@ -201,6 +595,7 @@ export function createLLMProfileFallbackRunner(params) {
201
595
  }
202
596
  catch (error) {
203
597
  if (roundOptions.context.signal.aborted) {
598
+ await healthPermit?.finish('ignored');
204
599
  throw error;
205
600
  }
206
601
  // The candidate's provider/model is part of request construction.
@@ -223,14 +618,17 @@ export function createLLMProfileFallbackRunner(params) {
223
618
  error: getLLMAttemptErrorMessage(error),
224
619
  });
225
620
  clearPartialResponse(roundOptions);
621
+ await healthPermit?.finish('ignored');
226
622
  continue;
227
623
  }
228
624
  if (execution.outcome === 'success') {
625
+ await healthPermit?.finish('healthy');
229
626
  activeProfileIndex = profileIndex;
230
627
  nextRoundIndex += 1;
231
628
  return execution.result;
232
629
  }
233
630
  lastError = execution.failure.normalizedError;
631
+ await healthPermit?.finish(isUnhealthyLLMProfileProviderFailure(execution.failure.normalizedError) ? 'unhealthy' : 'ignored');
234
632
  clearPartialResponse(roundOptions);
235
633
  }
236
634
  exhausted = true;
@@ -19,6 +19,7 @@ export const llmProfileFieldSpecs = [
19
19
  { key: 'useMaxTokensInput', valueKind: 'boolean', resolvedInputToggle: true },
20
20
  { key: 'provider' },
21
21
  { key: 'apiKeySource', inputId: 'apiKey' },
22
+ { key: 'providerApiKeyNames' },
22
23
  { key: 'customProviderApiKeyProgrammaticName', valueKind: 'string' },
23
24
  { key: 'customProviderApiKeyEnvVarName', valueKind: 'string' },
24
25
  { key: 'customProviderBaseURL', inputId: 'customProviderBaseURL', valueKind: 'string' },
@@ -46,6 +47,12 @@ export const llmProfileFieldSpecs = [
46
47
  { key: 'googleIncludeThoughts', valueKind: 'boolean' },
47
48
  { key: 'enableGoogleSearchGrounding', valueKind: 'boolean' },
48
49
  { key: 'enableGoogleUrlContext', valueKind: 'boolean' },
50
+ { key: 'enableCircuitBreaker', valueKind: 'boolean' },
51
+ { key: 'firstOutputTimeoutMs', valueKind: 'required-number' },
52
+ { key: 'streamInactivityTimeoutMs', valueKind: 'required-number' },
53
+ { key: 'circuitBreakerFailureThreshold', valueKind: 'required-number' },
54
+ { key: 'circuitBreakerFailureWindowMs', valueKind: 'required-number' },
55
+ { key: 'circuitBreakerOpenDurationMs', valueKind: 'required-number' },
49
56
  ];
50
57
  export const llmProfileDataKeys = llmProfileFieldSpecs.map((field) => field.key);
51
58
  export const llmProfileInputIds = llmProfileFieldSpecs