@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
@@ -0,0 +1,328 @@
1
+ import { nanoid } from 'nanoid/non-secure';
2
+ import CryptoJS from 'crypto-js';
3
+ import stableStringify from 'safe-stable-stringify';
4
+ export const DEFAULT_LLM_PROFILE_FIRST_OUTPUT_TIMEOUT_MS = 30_000;
5
+ export const DEFAULT_LLM_PROFILE_STREAM_INACTIVITY_TIMEOUT_MS = 30_000;
6
+ export const DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_THRESHOLD = 3;
7
+ export const DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_WINDOW_MS = 300_000;
8
+ export const DEFAULT_LLM_PROFILE_CIRCUIT_OPEN_DURATION_MS = 300_000;
9
+ const LLM_PROFILE_HALF_OPEN_LEASE_SAFETY_MARGIN_MS = 5_000;
10
+ const LLM_PROFILE_CLOSED_PERMIT_MIN_RETENTION_MS = 24 * 60 * 60 * 1_000;
11
+ export class RivetLLMProfileHealthPolicyError extends Error {
12
+ constructor(message) {
13
+ super(`LLM profile suspension policy is invalid: ${message}`);
14
+ this.name = 'RivetLLMProfileHealthPolicyError';
15
+ }
16
+ }
17
+ function requirePositiveInteger(value, label) {
18
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) {
19
+ throw new RivetLLMProfileHealthPolicyError(`${label} must be a positive integer.`);
20
+ }
21
+ return value;
22
+ }
23
+ export function resolveRivetLLMProfileCircuitBreakerPolicy(configuration) {
24
+ if (configuration.enableCircuitBreaker !== true) {
25
+ return undefined;
26
+ }
27
+ const firstOutputTimeoutMs = requirePositiveInteger(configuration.firstOutputTimeoutMs ?? DEFAULT_LLM_PROFILE_FIRST_OUTPUT_TIMEOUT_MS, 'Useful output wait time');
28
+ const streamInactivityTimeoutMs = requirePositiveInteger(configuration.streamInactivityTimeoutMs ?? DEFAULT_LLM_PROFILE_STREAM_INACTIVITY_TIMEOUT_MS, 'Stream inactivity timeout');
29
+ const failureThreshold = requirePositiveInteger(configuration.circuitBreakerFailureThreshold ?? DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_THRESHOLD, 'Failures before suspension');
30
+ const failureWindowMs = requirePositiveInteger(configuration.circuitBreakerFailureWindowMs ?? DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_WINDOW_MS, 'Failure window');
31
+ const openDurationMs = requirePositiveInteger(configuration.circuitBreakerOpenDurationMs ?? DEFAULT_LLM_PROFILE_CIRCUIT_OPEN_DURATION_MS, 'Suspension duration');
32
+ return {
33
+ failureThreshold,
34
+ failureWindowMs,
35
+ openDurationMs,
36
+ // A live streaming probe renews this lease on useful output. The bounded
37
+ // safety margin lets a dead owner recover promptly without coupling the
38
+ // probe lease to the (usually much longer) circuit cooldown.
39
+ halfOpenLeaseMs: Math.max(firstOutputTimeoutMs, streamInactivityTimeoutMs) + LLM_PROFILE_HALF_OPEN_LEASE_SAFETY_MARGIN_MS,
40
+ };
41
+ }
42
+ function sha256(value) {
43
+ return `sha256:${CryptoJS.SHA256(value).toString(CryptoJS.enc.Hex)}`;
44
+ }
45
+ export function createRivetLLMProfileHealthIdentity(params) {
46
+ const profileName = params.profileName?.trim();
47
+ // Circuit health belongs to the physical provider route and credentials,
48
+ // not to generation policy. A temperature/cooldown edit must not silently
49
+ // create a fresh circuit, while changing the model, endpoint, auth, or
50
+ // routing headers must never inherit another route's outage history.
51
+ const routingConfiguration = {
52
+ provider: params.configuration.provider,
53
+ model: params.configuration.model,
54
+ ...(params.configuration.provider !== 'custom'
55
+ ? {}
56
+ : {
57
+ customProviderApi: params.configuration.customProviderApi ?? 'completions',
58
+ customProviderBaseURL: params.configuration.customProviderBaseURL,
59
+ }),
60
+ headers: canonicalizeEffectiveRoutingHeaders(params.chatNodeHeaders, params.configuration.headers),
61
+ };
62
+ const serialized = stableStringify({
63
+ routingConfiguration,
64
+ credential: params.credential,
65
+ }) ?? '';
66
+ const configurationFingerprint = sha256(serialized);
67
+ const projectId = params.projectId == null ? undefined : String(params.projectId);
68
+ const profileNodeId = params.profileNodeId == null ? undefined : String(params.profileNodeId);
69
+ const key = sha256(stableStringify({
70
+ kind: 'rivet-llm-profile-health',
71
+ projectId,
72
+ profileNodeId,
73
+ configurationFingerprint,
74
+ }) ?? '');
75
+ return {
76
+ key: `llm-profile:${key}`,
77
+ ...(params.projectId == null ? {} : { projectId: params.projectId }),
78
+ ...(params.profileNodeId == null ? {} : { profileNodeId: params.profileNodeId }),
79
+ ...(profileName === '' || profileName == null ? {} : { profileName }),
80
+ provider: params.configuration.provider,
81
+ model: params.configuration.model,
82
+ ...(params.configuration.provider !== 'custom'
83
+ ? {}
84
+ : { customProviderApi: params.configuration.customProviderApi ?? 'completions' }),
85
+ configurationFingerprint,
86
+ };
87
+ }
88
+ function canonicalizeEffectiveRoutingHeaders(chatNodeHeaders, profileHeaders) {
89
+ // Provider resolution spreads project-wide headers first and profile
90
+ // headers second. Normalize names here because HTTP field names are
91
+ // case-insensitive, while preserving that same profile-wins precedence.
92
+ // Values remain confined to the SHA-256 input and never enter the public
93
+ // identity or store key in plaintext.
94
+ const headers = new Map();
95
+ for (const [key, value] of Object.entries(chatNodeHeaders ?? {})) {
96
+ const normalizedKey = key.trim().toLowerCase();
97
+ if (normalizedKey)
98
+ headers.set(normalizedKey, value);
99
+ }
100
+ for (const { key, value } of profileHeaders) {
101
+ const normalizedKey = key.trim().toLowerCase();
102
+ if (normalizedKey)
103
+ headers.set(normalizedKey, value);
104
+ }
105
+ return [...headers.entries()].sort(([left], [right]) => left.localeCompare(right));
106
+ }
107
+ function requireMatchingProjectScope(existing, identity) {
108
+ const storedProjectId = existing.identity.projectId == null ? undefined : String(existing.identity.projectId);
109
+ const requestProjectId = identity.projectId == null ? undefined : String(identity.projectId);
110
+ if (storedProjectId !== requestProjectId) {
111
+ throw new Error(`LLM profile reliability key ${identity.key} belongs to a different project scope.`);
112
+ }
113
+ }
114
+ function closedPermitRetentionMs(policy) {
115
+ return Math.max(LLM_PROFILE_CLOSED_PERMIT_MIN_RETENTION_MS, policy.failureWindowMs, policy.openDurationMs, policy.halfOpenLeaseMs);
116
+ }
117
+ function pruneClosedPermits(entry, now) {
118
+ for (const [permitId, expiresAt] of entry.closedPermits) {
119
+ if (expiresAt <= now)
120
+ entry.closedPermits.delete(permitId);
121
+ }
122
+ }
123
+ function pruneFailures(entry, policy, now) {
124
+ const windowStart = now - policy.failureWindowMs;
125
+ entry.failureTimestamps = entry.failureTimestamps.filter((timestamp) => timestamp >= windowStart);
126
+ }
127
+ function getState(entry, now) {
128
+ if (entry.openUntil == null)
129
+ return 'closed';
130
+ if (entry.openUntil > now)
131
+ return 'open';
132
+ return 'half-open';
133
+ }
134
+ function toSnapshot(entry, policy, now) {
135
+ pruneFailures(entry, policy, now);
136
+ const state = getState(entry, now);
137
+ return {
138
+ identity: entry.identity,
139
+ state,
140
+ failureCount: entry.failureTimestamps.length,
141
+ ...(entry.openUntil == null ? {} : { openUntil: entry.openUntil }),
142
+ ...(state !== 'half-open' || entry.halfOpenLeaseUntil == null
143
+ ? {}
144
+ : { halfOpenLeaseUntil: entry.halfOpenLeaseUntil }),
145
+ updatedAt: entry.updatedAt,
146
+ };
147
+ }
148
+ /** Process-local reference implementation used when a host does not supply durable shared storage. */
149
+ export class InMemoryRivetLLMProfileHealthStore {
150
+ #entries = new Map();
151
+ #now;
152
+ constructor(options = {}) {
153
+ this.#now = options.now ?? Date.now;
154
+ }
155
+ #pruneStaleEntries(now) {
156
+ for (const [key, entry] of this.#entries) {
157
+ pruneFailures(entry, entry.policy, now);
158
+ pruneClosedPermits(entry, now);
159
+ const isEmptyClosedEntry = entry.failureTimestamps.length === 0 &&
160
+ entry.openUntil == null &&
161
+ entry.halfOpenPermitId == null &&
162
+ entry.closedPermits.size === 0;
163
+ if (isEmptyClosedEntry && entry.updatedAt + closedPermitRetentionMs(entry.policy) <= now) {
164
+ this.#entries.delete(key);
165
+ }
166
+ }
167
+ }
168
+ begin(request) {
169
+ const { identity, policy } = request;
170
+ const now = this.#now();
171
+ this.#pruneStaleEntries(now);
172
+ let entry = this.#entries.get(identity.key);
173
+ if (entry == null) {
174
+ entry = { identity, failureTimestamps: [], updatedAt: now, policy, closedPermits: new Map() };
175
+ this.#entries.set(identity.key, entry);
176
+ }
177
+ else {
178
+ requireMatchingProjectScope(entry, identity);
179
+ entry.identity = identity;
180
+ entry.policy = policy;
181
+ }
182
+ pruneFailures(entry, policy, now);
183
+ pruneClosedPermits(entry, now);
184
+ if (entry.openUntil != null && entry.openUntil > now) {
185
+ return {
186
+ disposition: 'deny',
187
+ state: 'open',
188
+ retryAt: entry.openUntil,
189
+ snapshot: toSnapshot(entry, policy, now),
190
+ };
191
+ }
192
+ if (entry.openUntil != null) {
193
+ if (entry.halfOpenPermitId != null && (entry.halfOpenLeaseUntil ?? 0) > now) {
194
+ return {
195
+ disposition: 'deny',
196
+ state: 'half-open',
197
+ retryAt: entry.halfOpenLeaseUntil,
198
+ snapshot: toSnapshot(entry, policy, now),
199
+ };
200
+ }
201
+ const permitId = nanoid();
202
+ entry.halfOpenPermitId = permitId;
203
+ entry.halfOpenLeaseUntil = now + policy.halfOpenLeaseMs;
204
+ entry.updatedAt = now;
205
+ return {
206
+ disposition: 'allow',
207
+ state: 'half-open',
208
+ permitId,
209
+ snapshot: toSnapshot(entry, policy, now),
210
+ };
211
+ }
212
+ const permitId = nanoid();
213
+ entry.closedPermits.set(permitId, now + closedPermitRetentionMs(policy));
214
+ entry.updatedAt = now;
215
+ return {
216
+ disposition: 'allow',
217
+ state: 'closed',
218
+ permitId,
219
+ snapshot: toSnapshot(entry, policy, now),
220
+ };
221
+ }
222
+ finish(request) {
223
+ const { identity, policy, permitId, outcome } = request;
224
+ const now = this.#now();
225
+ this.#pruneStaleEntries(now);
226
+ const entry = this.#entries.get(identity.key);
227
+ if (entry == null) {
228
+ return {
229
+ identity,
230
+ state: 'closed',
231
+ failureCount: 0,
232
+ updatedAt: now,
233
+ };
234
+ }
235
+ requireMatchingProjectScope(entry, identity);
236
+ entry.identity = identity;
237
+ entry.policy = policy;
238
+ pruneFailures(entry, policy, now);
239
+ pruneClosedPermits(entry, now);
240
+ const ownsHalfOpenLease = entry.halfOpenPermitId === permitId;
241
+ const ownsClosedPermit = entry.closedPermits.delete(permitId);
242
+ if (!ownsHalfOpenLease && !ownsClosedPermit) {
243
+ return toSnapshot(entry, policy, now);
244
+ }
245
+ if (outcome === 'healthy' && ownsHalfOpenLease) {
246
+ entry.failureTimestamps = [];
247
+ entry.openUntil = undefined;
248
+ entry.halfOpenPermitId = undefined;
249
+ entry.halfOpenLeaseUntil = undefined;
250
+ // Requests admitted before the circuit opened belong to the previous
251
+ // health generation. Once the single recovery probe succeeds, their
252
+ // eventual results must not immediately poison the recovered circuit.
253
+ entry.closedPermits.clear();
254
+ }
255
+ else if (outcome === 'unhealthy') {
256
+ const wasOpen = entry.openUntil != null;
257
+ entry.failureTimestamps.push(now);
258
+ if (ownsHalfOpenLease || (!wasOpen && entry.failureTimestamps.length >= policy.failureThreshold)) {
259
+ entry.openUntil = now + policy.openDurationMs;
260
+ }
261
+ if (ownsHalfOpenLease) {
262
+ entry.halfOpenPermitId = undefined;
263
+ entry.halfOpenLeaseUntil = undefined;
264
+ }
265
+ }
266
+ else if (outcome === 'ignored' && ownsHalfOpenLease) {
267
+ entry.halfOpenPermitId = undefined;
268
+ entry.halfOpenLeaseUntil = undefined;
269
+ }
270
+ entry.updatedAt = now;
271
+ return toSnapshot(entry, policy, now);
272
+ }
273
+ renew(request) {
274
+ const now = this.#now();
275
+ this.#pruneStaleEntries(now);
276
+ const entry = this.#entries.get(request.identity.key);
277
+ if (entry == null) {
278
+ return {
279
+ identity: request.identity,
280
+ state: 'closed',
281
+ failureCount: 0,
282
+ updatedAt: now,
283
+ };
284
+ }
285
+ requireMatchingProjectScope(entry, request.identity);
286
+ if (entry.halfOpenPermitId === request.permitId) {
287
+ entry.halfOpenLeaseUntil = Math.max(entry.halfOpenLeaseUntil ?? 0, now + request.leaseDurationMs);
288
+ entry.updatedAt = now;
289
+ }
290
+ else if (entry.closedPermits.has(request.permitId)) {
291
+ entry.closedPermits.set(request.permitId, Math.max(entry.closedPermits.get(request.permitId) ?? 0, now + closedPermitRetentionMs(entry.policy)));
292
+ entry.updatedAt = now;
293
+ }
294
+ return toSnapshot(entry, entry.policy, now);
295
+ }
296
+ reset(request) {
297
+ if (request.key != null) {
298
+ this.#entries.delete(request.key);
299
+ return;
300
+ }
301
+ for (const [key, entry] of this.#entries) {
302
+ if (entry.identity.projectId === request.projectId) {
303
+ this.#entries.delete(key);
304
+ }
305
+ }
306
+ }
307
+ list(request = {}) {
308
+ const now = this.#now();
309
+ this.#pruneStaleEntries(now);
310
+ return [...this.#entries.entries()]
311
+ .filter(([, entry]) => request.projectId == null || entry.identity.projectId === request.projectId)
312
+ .map(([, entry]) => {
313
+ pruneFailures(entry, entry.policy, now);
314
+ pruneClosedPermits(entry, now);
315
+ const state = getState(entry, now);
316
+ return {
317
+ identity: entry.identity,
318
+ state,
319
+ failureCount: entry.failureTimestamps.length,
320
+ ...(entry.openUntil == null ? {} : { openUntil: entry.openUntil }),
321
+ ...(state !== 'half-open' || entry.halfOpenLeaseUntil == null
322
+ ? {}
323
+ : { halfOpenLeaseUntil: entry.halfOpenLeaseUntil }),
324
+ updatedAt: entry.updatedAt,
325
+ };
326
+ });
327
+ }
328
+ }
@@ -4,6 +4,7 @@ import { resolveChatV2Credential } from './chatV2ProviderProfile.js';
4
4
  import { resolveLLMChatV2ExtraProviderOptions, resolveLLMChatV2GenerationParameters, resolveLLMChatV2Headers, } from './chatV2RuntimeOptions.js';
5
5
  import { LLM_PROFILE_VALUE_VERSION } from './llmProfileTypes.js';
6
6
  import { parseCustomProviderApi } from './customProviderApi.js';
7
+ import { createRivetLLMProfileHealthIdentity } from './llmProfileHealthStore.js';
7
8
  export function resolveLLMProfileNodeValue(params) {
8
9
  const { data, inputs, context } = params;
9
10
  const runtimeData = data;
@@ -32,45 +33,67 @@ export function resolveLLMProfileNodeValue(params) {
32
33
  context,
33
34
  apiKeySource: data.apiKeySource === 'input' ? 'input' : 'configured',
34
35
  inputs,
36
+ providerApiKeyNames: data.providerApiKeyNames,
35
37
  customProgrammaticName: data.customProviderApiKeyProgrammaticName,
36
38
  customEnvironmentName: data.customProviderApiKeyEnvVarName,
37
39
  });
40
+ const configuration = {
41
+ ...data,
42
+ model,
43
+ useModelInput: false,
44
+ temperature: generation.temperature ?? data.temperature,
45
+ useTemperatureInput: false,
46
+ maxTokens: generation.maxTokens ?? data.maxTokens,
47
+ useMaxTokensInput: false,
48
+ topP: generation.topP,
49
+ useTopPInput: false,
50
+ topK: generation.topK,
51
+ useTopKInput: false,
52
+ presencePenalty: generation.presencePenalty,
53
+ usePresencePenaltyInput: false,
54
+ frequencyPenalty: generation.frequencyPenalty,
55
+ useFrequencyPenaltyInput: false,
56
+ stopSequences: generation.stopSequences ?? [],
57
+ useStopSequencesInput: false,
58
+ seed: generation.seed,
59
+ useSeedInput: false,
60
+ customProviderBaseURL,
61
+ useCustomProviderBaseURLInput: false,
62
+ customProviderApi,
63
+ openAIPreviousResponseId,
64
+ useOpenAIPreviousResponseIdInput: false,
65
+ headers: Object.entries(headers ?? {}).map(([key, value]) => ({ key, value })),
66
+ useHeadersInput: false,
67
+ extraProviderOptions: extraProviderOptions == null ? '' : JSON.stringify(extraProviderOptions),
68
+ useExtraProviderOptionsInput: false,
69
+ anthropicThinkingBudget,
70
+ useAnthropicThinkingBudgetInput: false,
71
+ googleThinkingBudget,
72
+ useGoogleThinkingBudgetInput: false,
73
+ };
74
+ // A profile can be resolved outside a loaded project, for example by a
75
+ // programmatic caller or a focused node test. Its health identity is
76
+ // project-scoped, so defer attaching it until LLM Chat binds the profile to
77
+ // the executing project in that case.
78
+ const projectId = context.project?.metadata?.id;
79
+ const profileTitle = context.node?.title;
80
+ const profileName = typeof profileTitle === 'string' ? profileTitle.trim() : '';
38
81
  return {
39
82
  version: LLM_PROFILE_VALUE_VERSION,
40
83
  credential,
41
- configuration: {
42
- ...data,
43
- model,
44
- useModelInput: false,
45
- temperature: generation.temperature ?? data.temperature,
46
- useTemperatureInput: false,
47
- maxTokens: generation.maxTokens ?? data.maxTokens,
48
- useMaxTokensInput: false,
49
- topP: generation.topP,
50
- useTopPInput: false,
51
- topK: generation.topK,
52
- useTopKInput: false,
53
- presencePenalty: generation.presencePenalty,
54
- usePresencePenaltyInput: false,
55
- frequencyPenalty: generation.frequencyPenalty,
56
- useFrequencyPenaltyInput: false,
57
- stopSequences: generation.stopSequences ?? [],
58
- useStopSequencesInput: false,
59
- seed: generation.seed,
60
- useSeedInput: false,
61
- customProviderBaseURL,
62
- useCustomProviderBaseURLInput: false,
63
- customProviderApi,
64
- openAIPreviousResponseId,
65
- useOpenAIPreviousResponseIdInput: false,
66
- headers: Object.entries(headers ?? {}).map(([key, value]) => ({ key, value })),
67
- useHeadersInput: false,
68
- extraProviderOptions: extraProviderOptions == null ? '' : JSON.stringify(extraProviderOptions),
69
- useExtraProviderOptionsInput: false,
70
- anthropicThinkingBudget,
71
- useAnthropicThinkingBudgetInput: false,
72
- googleThinkingBudget,
73
- useGoogleThinkingBudgetInput: false,
74
- },
84
+ configuration,
85
+ ...(profileName === '' ? {} : { profileName }),
86
+ ...(projectId == null
87
+ ? {}
88
+ : {
89
+ healthIdentity: createRivetLLMProfileHealthIdentity({
90
+ configuration,
91
+ credential,
92
+ chatNodeHeaders: context.settings.chatNodeHeaders,
93
+ projectId,
94
+ profileNodeId: context.node.id,
95
+ ...(profileName === '' ? {} : { profileName }),
96
+ }),
97
+ }),
75
98
  };
76
99
  }
@@ -137,6 +137,19 @@ function parseFetchBody(body) {
137
137
  }
138
138
  return undefined;
139
139
  }
140
+ async function resolveProviderFetchBody(input, init) {
141
+ if (init?.body != null) {
142
+ return { originalBody: init.body, parsedBody: parseFetchBody(init.body) };
143
+ }
144
+ if (!(input instanceof Request) || input.body == null) {
145
+ return { originalBody: undefined, parsedBody: undefined };
146
+ }
147
+ // Fetch implementations may provide the complete request as a Request
148
+ // object rather than as URL + init. Read a clone so diagnostics and raw
149
+ // overlays do not consume the body that will be sent.
150
+ const bodyText = await input.clone().text();
151
+ return { originalBody: bodyText, parsedBody: parseBodyText(bodyText) };
152
+ }
140
153
  function cloneCapturedRequestBody(body) {
141
154
  if (typeof structuredClone === 'function') {
142
155
  try {
@@ -166,6 +179,15 @@ function serializeTransformedFetchBody(originalBody, transformedBody) {
166
179
  }
167
180
  return serialized;
168
181
  }
182
+ export function applyChatV2RequestBodyOverlay(body, overlay) {
183
+ if (overlay == null) {
184
+ return body;
185
+ }
186
+ if (body === null || typeof body !== 'object' || Array.isArray(body)) {
187
+ throw new Error('Extra provider options could not be applied because the provider request body is not a JSON object.');
188
+ }
189
+ return { ...body, ...overlay };
190
+ }
169
191
  function removeStaleContentLength(headers) {
170
192
  if (headers == null) {
171
193
  return undefined;
@@ -191,23 +213,26 @@ function applyEndpointQuery(input, endpointQuery) {
191
213
  }
192
214
  function createProviderProcessingFetch(options, processing) {
193
215
  return async (input, init) => {
194
- const parsedBody = parseFetchBody(init?.body);
195
- const processedBody = parsedBody !== undefined && options.transformRequestBody != null
216
+ const { originalBody, parsedBody } = await resolveProviderFetchBody(input, init);
217
+ const transformedBody = parsedBody !== undefined && options.transformRequestBody != null
196
218
  ? options.transformRequestBody(parsedBody)
197
219
  : parsedBody;
220
+ const processedBody = applyChatV2RequestBodyOverlay(transformedBody, options.requestBodyOverlay);
221
+ const shouldSerializeProcessedBody = parsedBody !== undefined && (options.transformRequestBody != null || options.requestBodyOverlay != null);
198
222
  if (processedBody !== undefined) {
199
223
  options.onRequestBody?.(cloneCapturedRequestBody(processedBody));
200
224
  }
201
225
  const nativeFetch = globalThis.fetch;
202
- let processedInit = processedBody !== parsedBody
226
+ let processedInit = shouldSerializeProcessedBody
203
227
  ? {
204
228
  ...init,
205
- body: serializeTransformedFetchBody(init?.body, processedBody),
206
- headers: removeStaleContentLength(init?.headers),
229
+ body: serializeTransformedFetchBody(originalBody, processedBody),
230
+ headers: removeStaleContentLength(init?.headers ?? (input instanceof Request ? input.headers : undefined)),
207
231
  }
208
232
  : init;
209
- if (processing.omitGeneratedEmptyBearer && processedInit?.headers != null) {
210
- const headers = new Headers(processedInit.headers);
233
+ const effectiveHeaders = processedInit?.headers ?? (input instanceof Request ? input.headers : undefined);
234
+ if (processing.omitGeneratedEmptyBearer && effectiveHeaders != null) {
235
+ const headers = new Headers(effectiveHeaders);
211
236
  if (headers.get('authorization')?.trim().toLowerCase() === 'bearer') {
212
237
  headers.delete('authorization');
213
238
  processedInit = { ...processedInit, headers };
@@ -230,6 +255,7 @@ function maybeCreateProviderProcessingFetch(options, processing = {}) {
230
255
  return options.onRequestBody == null &&
231
256
  options.onResponseBody == null &&
232
257
  options.transformRequestBody == null &&
258
+ options.requestBodyOverlay == null &&
233
259
  !omitGeneratedEmptyBearer &&
234
260
  endpointQuery.length === 0
235
261
  ? undefined
@@ -3,6 +3,7 @@ import { materializeLLMResponse } from './llmResponseMaterializer.js';
3
3
  import { createCallbackToolRoundExecutor } from './toolRoundExecutor.js';
4
4
  import { decideLLMInvocationRound } from './llmInvocationDecision.js';
5
5
  import { isChatV2PipelineProviderFailureResult } from './chatV2Pipeline.js';
6
+ import { cloneLLMChatV2Outputs } from './llmChatV2OutputClone.js';
6
7
  function shouldReturnToolResultDirectly(functionCalls, registry) {
7
8
  if (functionCalls.length !== 1) {
8
9
  return false;
@@ -74,7 +75,7 @@ function applyTerminalContinuationOutputs(result, delegatedToolCalls, accumulate
74
75
  }
75
76
  }
76
77
  export async function runChatV2PipelineWithToolContinuation(options) {
77
- const { autoContinue, maxToolRounds, functions, delegateToolCall, delegateToolCallRound, runPipeline, ...pipelineOptions } = options;
78
+ const { autoContinue, maxToolRounds, functions, delegateToolCall, delegateToolCallRound, onCompletedModelRound, onTerminalRound, runPipeline, ...pipelineOptions } = options;
78
79
  const toolRegistry = createRivetToolRegistry(functions);
79
80
  const toolRoundExecutor = createCallbackToolRoundExecutor({
80
81
  delegateOne: delegateToolCall,
@@ -127,8 +128,27 @@ export async function runChatV2PipelineWithToolContinuation(options) {
127
128
  outputReasoning: pipelineOptions.outputReasoning,
128
129
  includeFunctionCalls: pipelineOptions.includeFunctionCalls,
129
130
  });
131
+ onTerminalRound?.({
132
+ entryId: `model-round:${completedRounds}`,
133
+ roundIndex: completedRounds,
134
+ kind: 'model-round',
135
+ outcome: decision.kind === 'final-model-answer'
136
+ ? 'final-answer'
137
+ : decision.kind === 'release-unresolved-calls'
138
+ ? 'unresolved-tool-calls'
139
+ : 'max-rounds',
140
+ });
130
141
  return result;
131
142
  }
143
+ // Snapshot before delegate execution: subsequent rounds accumulate tool
144
+ // messages, usage, and reasoning that must not mutate this page.
145
+ onCompletedModelRound?.({
146
+ entryId: `model-round:${completedRounds}`,
147
+ roundIndex: completedRounds,
148
+ kind: 'model-round',
149
+ outcome: 'tool-calls',
150
+ outputs: cloneLLMChatV2Outputs(result.commonOutputs),
151
+ });
132
152
  const toolResultMessages = await toolRoundExecutor.executeRound({
133
153
  calls: result.functionCalls,
134
154
  assistantMessage: result.response,
@@ -170,6 +190,12 @@ export async function runChatV2PipelineWithToolContinuation(options) {
170
190
  }
171
191
  applyAccumulatedUsage(result, accumulatedUsage, pipelineOptions.outputUsage);
172
192
  applyAccumulatedReasoning(result, reasoningRounds, pipelineOptions.outputReasoning);
193
+ onTerminalRound?.({
194
+ entryId: `direct-tool-result:${completedRounds}`,
195
+ roundIndex: completedRounds,
196
+ kind: 'direct-tool-result',
197
+ outcome: 'direct-tool-result',
198
+ });
173
199
  return result;
174
200
  }
175
201
  currentPrompt = {
@@ -6,6 +6,8 @@ import { NodeImpl } from '../NodeImpl.js';
6
6
  import {} from '../NodeBodySpec.js';
7
7
  import { appendCodeNodeSourceUrl, buildCodeNodeSourceUrl, enrichCodeNodeErrorWithLocation, } from './codeNodeErrorDiagnostics.js';
8
8
  import { buildJsValueInterpolatedSource, buildJsValueInputsInitializer, buildJsValuePreview, getJsValueInterpolationInputDefinitions, getJsValueInterpolationRuntimeContext, interpolateJsValuePreviewSource, sanitizeGeneratedJsValueError, } from './jsValueInterpolation.js';
9
+ import { ALL_CODE_RUNNER_OPTIONS } from '../../integrations/CodeRunnerOptions.js';
10
+ const CODE_RUNTIME_HELPER_MESSAGE = 'Node execution also provides "require" and "process". Browser execution provides "fetch", "console", and "Rivet".';
9
11
  const DEFAULT_CODE_NEW = dedent `
10
12
  // This is a Code node. Write JavaScript here and return one value.
11
13
  // Interpolation tokens create input ports and evaluate as connected values.
@@ -90,11 +92,6 @@ export class CodeNewNodeImpl extends NodeImpl {
90
92
  },
91
93
  data: {
92
94
  code: DEFAULT_CODE_NEW,
93
- allowFetch: false,
94
- allowRequire: false,
95
- allowRivet: false,
96
- allowProcess: false,
97
- allowConsole: false,
98
95
  },
99
96
  };
100
97
  }
@@ -115,46 +112,13 @@ export class CodeNewNodeImpl extends NodeImpl {
115
112
  {
116
113
  type: 'code',
117
114
  label: 'Code',
118
- helperMessage: 'Use {{var}} to create input ports. Interpolated variables evaluate as the connected values.',
115
+ helperMessage: 'Use {{var}} to create input ports. Interpolated variables evaluate as the connected values. ' +
116
+ CODE_RUNTIME_HELPER_MESSAGE,
119
117
  dataKey: 'code',
120
118
  language: 'javascript',
121
119
  interpolationSyntax: 'js-value',
122
120
  enableFolding: true,
123
121
  },
124
- {
125
- type: 'group',
126
- label: 'Runtime permissions',
127
- defaultOpen: true,
128
- editors: [
129
- {
130
- type: 'toggle',
131
- label: 'Allow "fetch"',
132
- dataKey: 'allowFetch',
133
- },
134
- {
135
- type: 'toggle',
136
- label: 'Allow "Rivet"',
137
- dataKey: 'allowRivet',
138
- },
139
- {
140
- type: 'toggle',
141
- label: 'Allow "console"',
142
- dataKey: 'allowConsole',
143
- },
144
- {
145
- type: 'toggle',
146
- label: 'Allow "require"',
147
- dataKey: 'allowRequire',
148
- helperMessage: 'Only available with the Node executor',
149
- },
150
- {
151
- type: 'toggle',
152
- label: 'Allow "process"',
153
- dataKey: 'allowProcess',
154
- helperMessage: 'Only available with the Node executor',
155
- },
156
- ],
157
- },
158
122
  ];
159
123
  }
160
124
  getBody() {
@@ -182,13 +146,7 @@ export class CodeNewNodeImpl extends NodeImpl {
182
146
  const { inputNames, inputsIdentifier } = interpolationContext;
183
147
  const { source, userCodeLineOffset } = buildCodeNewWrapper(this.data.code, interpolationContext);
184
148
  try {
185
- const outputs = await context.codeRunner.runCode(appendCodeNodeSourceUrl(source, sourceUrl), inputs, {
186
- includeFetch: this.data.allowFetch ?? false,
187
- includeRequire: this.data.allowRequire ?? false,
188
- includeRivet: this.data.allowRivet ?? false,
189
- includeProcess: this.data.allowProcess ?? false,
190
- includeConsole: this.data.allowConsole ?? false,
191
- }, context.graphInputNodeValues, context.contextValues);
149
+ const outputs = await context.codeRunner.runCode(appendCodeNodeSourceUrl(source, sourceUrl), inputs, ALL_CODE_RUNNER_OPTIONS, context.graphInputNodeValues, context.contextValues);
192
150
  return validateCodeNewRunnerOutputs(outputs);
193
151
  }
194
152
  catch (error) {