@valerypopoff/rivet2-core 2.1.10 → 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 (86) hide show
  1. package/README.md +1 -1
  2. package/dist/cjs/bundle.cjs +2101 -867
  3. package/dist/cjs/bundle.cjs.map +4 -4
  4. package/dist/cjs/webAppRuntime.cjs +37 -3
  5. package/dist/cjs/webAppRuntime.cjs.map +2 -2
  6. package/dist/esm/api/createProcessor.js +2 -0
  7. package/dist/esm/integrations/CodeRunner.js +2 -7
  8. package/dist/esm/integrations/CodeRunnerOptions.js +7 -0
  9. package/dist/esm/model/AgentResponseTrace.js +121 -11
  10. package/dist/esm/model/GraphProcessor.js +14 -0
  11. package/dist/esm/model/RecordingPlayer.js +50 -5
  12. package/dist/esm/model/SubprocessorBridge.js +1 -0
  13. package/dist/esm/model/UiGraphActionProtocol.js +1 -0
  14. package/dist/esm/model/chat-v2/aiSdkBridge.js +146 -14
  15. package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -0
  16. package/dist/esm/model/chat-v2/chatV2CredentialNames.js +93 -0
  17. package/dist/esm/model/chat-v2/chatV2EditorCache.js +6 -5
  18. package/dist/esm/model/chat-v2/chatV2Pipeline.js +41 -4
  19. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +31 -2
  20. package/dist/esm/model/chat-v2/chatV2ResponseBodyCapture.js +10 -2
  21. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +6 -11
  22. package/dist/esm/model/chat-v2/chatV2Shared.js +1 -1
  23. package/dist/esm/model/chat-v2/chatV2Types.js +16 -0
  24. package/dist/esm/model/chat-v2/customProviderApi.js +0 -2
  25. package/dist/esm/model/chat-v2/index.js +3 -0
  26. package/dist/esm/model/chat-v2/llmChatV2Body.js +9 -1
  27. package/dist/esm/model/chat-v2/llmChatV2CachePolicy.js +5 -0
  28. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +7 -0
  29. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +95 -14
  30. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +32 -9
  31. package/dist/esm/model/chat-v2/llmModelCandidate.js +5 -1
  32. package/dist/esm/model/chat-v2/llmProfile.js +42 -0
  33. package/dist/esm/model/chat-v2/llmProfileBody.js +10 -0
  34. package/dist/esm/model/chat-v2/llmProfileFallback.js +390 -4
  35. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +7 -0
  36. package/dist/esm/model/chat-v2/llmProfileHealthStore.js +326 -0
  37. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +53 -34
  38. package/dist/esm/model/chat-v2/providerOptions.js +33 -7
  39. package/dist/esm/model/nodes/CodeNewNode.js +5 -47
  40. package/dist/esm/model/nodes/CodeNode.js +4 -46
  41. package/dist/esm/model/nodes/ExpressionNode.js +5 -8
  42. package/dist/esm/model/nodes/LLMChatV2Node.js +10 -1
  43. package/dist/esm/model/nodes/MatchNode.js +86 -41
  44. package/dist/esm/plugins/gentrace/gentraceSdk.js +0 -1
  45. package/dist/esm/plugins/gentrace/index.js +0 -1
  46. package/dist/esm/plugins/gentrace/plugin.js +61 -179
  47. package/dist/esm/plugins.js +1 -2
  48. package/dist/esm/recording/ExecutionRecorder.js +49 -8
  49. package/dist/types/api/createProcessor.d.ts +3 -0
  50. package/dist/types/integrations/CodeRunner.d.ts +10 -7
  51. package/dist/types/integrations/CodeRunnerOptions.d.ts +15 -0
  52. package/dist/types/model/AgentResponseTrace.d.ts +14 -1
  53. package/dist/types/model/EditorDefinition.d.ts +16 -0
  54. package/dist/types/model/ExecutorProtocol.d.ts +9 -6
  55. package/dist/types/model/GraphProcessor.d.ts +15 -5
  56. package/dist/types/model/NodeBase.d.ts +0 -10
  57. package/dist/types/model/Nodes.d.ts +2 -2
  58. package/dist/types/model/ProcessContext.d.ts +52 -0
  59. package/dist/types/model/UiGraphActionProtocol.d.ts +1 -0
  60. package/dist/types/model/chat-v2/chatV2CredentialNames.d.ts +30 -0
  61. package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +1 -0
  62. package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +3 -0
  63. package/dist/types/model/chat-v2/chatV2ResponseBodyCapture.d.ts +8 -2
  64. package/dist/types/model/chat-v2/chatV2RuntimeOptions.d.ts +3 -8
  65. package/dist/types/model/chat-v2/chatV2Types.d.ts +24 -0
  66. package/dist/types/model/chat-v2/customProviderApi.d.ts +0 -1
  67. package/dist/types/model/chat-v2/index.d.ts +3 -0
  68. package/dist/types/model/chat-v2/llmChatV2CachePolicy.d.ts +1 -1
  69. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +10 -1
  70. package/dist/types/model/chat-v2/llmModelCandidate.d.ts +2 -0
  71. package/dist/types/model/chat-v2/llmProfile.d.ts +14 -0
  72. package/dist/types/model/chat-v2/llmProfileBody.d.ts +1 -1
  73. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +21 -2
  74. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +26 -6
  75. package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +111 -0
  76. package/dist/types/model/chat-v2/llmProfileNodeRuntime.d.ts +1 -1
  77. package/dist/types/model/chat-v2/llmProfileTypes.d.ts +3 -0
  78. package/dist/types/model/chat-v2/providerOptions.d.ts +2 -0
  79. package/dist/types/model/nodes/CodeNewNode.d.ts +0 -5
  80. package/dist/types/model/nodes/CodeNode.d.ts +0 -5
  81. package/dist/types/model/nodes/MatchNode.d.ts +6 -0
  82. package/dist/types/plugins/gentrace/gentraceSdk.d.ts +0 -1
  83. package/dist/types/plugins/gentrace/plugin.d.ts +55 -9
  84. package/dist/types/plugins.d.ts +1 -1
  85. package/dist/types/recording/ExecutionRecorder.d.ts +7 -1
  86. 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
@@ -30,7 +94,11 @@ function buildExhaustedMessage(attempts) {
30
94
  ? `request${attempt.attemptIndex == null ? '' : ` attempt ${attempt.attemptIndex}`}`
31
95
  : attempt.stage === 'response-validation'
32
96
  ? 'response validation'
33
- : 'configuration';
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
103
  const error = attempt.error ? `: ${attempt.error.replace(/\r\n|\r|\n/g, '\n ')}` : '';
36
104
  return `Profile ${attempt.profileIndex} (${formatCandidateIdentity(attempt)}), round ${attempt.roundIndex}, ${stage} ${attempt.outcome}${status}${error}`;
@@ -67,7 +135,12 @@ export function buildLLMProfileFallbackSummary(candidates, attempts) {
67
135
  const failedRequestAttempts = profileAttempts.filter((attempt) => attempt.stage === 'request' && attempt.outcome === 'failure');
68
136
  const hasSuccessfulRequest = profileAttempts.some((attempt) => attempt.stage === 'request' && attempt.outcome === 'success');
69
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);
70
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');
71
144
  if (successfulRounds.length > 0) {
72
145
  clauses.push(`succeeded in model ${pluralize(successfulRounds.length, 'round')} (${successfulRounds.join(', ')})`);
73
146
  }
@@ -77,13 +150,31 @@ export function buildLLMProfileFallbackSummary(candidates, attempts) {
77
150
  if (failedRequestAttempts.length > 0) {
78
151
  const lastFailedRequest = failedRequestAttempts.at(-1);
79
152
  const status = lastFailedRequest.status == null ? '' : `; last status ${lastFailedRequest.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
+ : '';
80
158
  clauses.push(hasSuccessfulRequest
81
- ? `had ${pluralize(failedRequestAttempts.length, 'failed provider attempt')}${status}`
82
- : `failed after ${pluralize(failedRequestAttempts.length, 'provider attempt')}${status}`);
159
+ ? `had ${pluralize(failedRequestAttempts.length, 'failed provider attempt')}${status}${timeout}`
160
+ : `failed after ${pluralize(failedRequestAttempts.length, 'provider attempt')}${status}${timeout}`);
83
161
  }
84
162
  if (failedResponseValidations.length > 0) {
85
163
  clauses.push(`failed response validation in ${pluralize(failedResponseValidations.length, 'model round')}`);
86
164
  }
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()}`}`);
168
+ }
169
+ if (failedHealthOperations.length > 0) {
170
+ clauses.push(`reliability service unavailable ${pluralize(failedHealthOperations.length, 'time')}; profile was tried normally`);
171
+ }
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
+ }
87
178
  return `${identity}: ${clauses.join('; ')}.`;
88
179
  })
89
180
  .join('\n');
@@ -104,6 +195,175 @@ function clearPartialResponse(options) {
104
195
  // A presentation callback must not prevent recovery through a fallback profile.
105
196
  }
106
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
+ }
107
367
  function throwIfAborted(signal) {
108
368
  if (!signal.aborted) {
109
369
  return;
@@ -132,6 +392,7 @@ export function createLLMProfileFallbackRunner(params) {
132
392
  let activeProfileIndex = 0;
133
393
  let nextRoundIndex = 0;
134
394
  let exhausted = false;
395
+ const healthOperationTimeoutMs = Math.max(1, params.healthOperationTimeoutMs ?? DEFAULT_LLM_PROFILE_HEALTH_OPERATION_TIMEOUT_MS);
135
396
  return {
136
397
  attempts,
137
398
  summary: () => buildLLMProfileFallbackSummary(params.candidates, attempts),
@@ -142,12 +403,109 @@ export function createLLMProfileFallbackRunner(params) {
142
403
  for (let profileIndex = activeProfileIndex; profileIndex < params.candidates.length; profileIndex++) {
143
404
  throwIfAborted(roundOptions.context.signal);
144
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
+ }
145
502
  let candidateOptions;
146
503
  try {
147
504
  candidateOptions = await params.resolveCandidate(profileIndex, roundOptions);
148
505
  }
149
506
  catch (error) {
150
507
  if (roundOptions.context.signal.aborted) {
508
+ await healthPermit?.finish('ignored');
151
509
  throw error;
152
510
  }
153
511
  lastError = error;
@@ -162,17 +520,40 @@ export function createLLMProfileFallbackRunner(params) {
162
520
  error: getLLMAttemptErrorMessage(error),
163
521
  });
164
522
  clearPartialResponse(roundOptions);
523
+ await healthPermit?.finish('ignored');
165
524
  continue;
166
525
  }
167
526
  // Candidate resolution can be asynchronous (for example, plugin or
168
527
  // provider configuration). Do not start a physical request if the
169
528
  // graph was cancelled while that resolution was in flight.
170
- 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);
171
538
  const previousOnProviderAttempt = candidateOptions.onProviderAttempt;
172
539
  candidateOptions = {
173
540
  ...candidateOptions,
174
541
  profileIndex,
175
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
+ }),
176
557
  onProviderAttempt: (attempt) => {
177
558
  try {
178
559
  previousOnProviderAttempt?.(attempt);
@@ -192,6 +573,7 @@ export function createLLMProfileFallbackRunner(params) {
192
573
  attemptIndex: attempt.attemptIndex,
193
574
  ...(attempt.status == null ? {} : { status: attempt.status }),
194
575
  ...(attempt.error == null ? {} : { error: getLLMAttemptErrorMessage(attempt.error) }),
576
+ ...(isChatV2ProviderTimeoutError(attempt.error) ? { timeoutKind: attempt.error.timeoutKind } : {}),
195
577
  });
196
578
  },
197
579
  };
@@ -201,6 +583,7 @@ export function createLLMProfileFallbackRunner(params) {
201
583
  }
202
584
  catch (error) {
203
585
  if (roundOptions.context.signal.aborted) {
586
+ await healthPermit?.finish('ignored');
204
587
  throw error;
205
588
  }
206
589
  // The candidate's provider/model is part of request construction.
@@ -223,14 +606,17 @@ export function createLLMProfileFallbackRunner(params) {
223
606
  error: getLLMAttemptErrorMessage(error),
224
607
  });
225
608
  clearPartialResponse(roundOptions);
609
+ await healthPermit?.finish('ignored');
226
610
  continue;
227
611
  }
228
612
  if (execution.outcome === 'success') {
613
+ await healthPermit?.finish('healthy');
229
614
  activeProfileIndex = profileIndex;
230
615
  nextRoundIndex += 1;
231
616
  return execution.result;
232
617
  }
233
618
  lastError = execution.failure.normalizedError;
619
+ await healthPermit?.finish(isUnhealthyLLMProfileProviderFailure(execution.failure.normalizedError) ? 'unhealthy' : 'ignored');
234
620
  clearPartialResponse(roundOptions);
235
621
  }
236
622
  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