@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.
- package/README.md +1 -1
- package/dist/cjs/bundle.cjs +2101 -867
- package/dist/cjs/bundle.cjs.map +4 -4
- package/dist/cjs/webAppRuntime.cjs +37 -3
- package/dist/cjs/webAppRuntime.cjs.map +2 -2
- package/dist/esm/api/createProcessor.js +2 -0
- package/dist/esm/integrations/CodeRunner.js +2 -7
- package/dist/esm/integrations/CodeRunnerOptions.js +7 -0
- package/dist/esm/model/AgentResponseTrace.js +121 -11
- package/dist/esm/model/GraphProcessor.js +14 -0
- package/dist/esm/model/RecordingPlayer.js +50 -5
- package/dist/esm/model/SubprocessorBridge.js +1 -0
- package/dist/esm/model/UiGraphActionProtocol.js +1 -0
- package/dist/esm/model/chat-v2/aiSdkBridge.js +146 -14
- package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -0
- package/dist/esm/model/chat-v2/chatV2CredentialNames.js +93 -0
- package/dist/esm/model/chat-v2/chatV2EditorCache.js +6 -5
- package/dist/esm/model/chat-v2/chatV2Pipeline.js +41 -4
- package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +31 -2
- package/dist/esm/model/chat-v2/chatV2ResponseBodyCapture.js +10 -2
- package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +6 -11
- package/dist/esm/model/chat-v2/chatV2Shared.js +1 -1
- package/dist/esm/model/chat-v2/chatV2Types.js +16 -0
- package/dist/esm/model/chat-v2/customProviderApi.js +0 -2
- package/dist/esm/model/chat-v2/index.js +3 -0
- package/dist/esm/model/chat-v2/llmChatV2Body.js +9 -1
- package/dist/esm/model/chat-v2/llmChatV2CachePolicy.js +5 -0
- package/dist/esm/model/chat-v2/llmChatV2NodeData.js +7 -0
- package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +95 -14
- package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +32 -9
- package/dist/esm/model/chat-v2/llmModelCandidate.js +5 -1
- package/dist/esm/model/chat-v2/llmProfile.js +42 -0
- package/dist/esm/model/chat-v2/llmProfileBody.js +10 -0
- package/dist/esm/model/chat-v2/llmProfileFallback.js +390 -4
- package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +7 -0
- package/dist/esm/model/chat-v2/llmProfileHealthStore.js +326 -0
- package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +53 -34
- package/dist/esm/model/chat-v2/providerOptions.js +33 -7
- package/dist/esm/model/nodes/CodeNewNode.js +5 -47
- package/dist/esm/model/nodes/CodeNode.js +4 -46
- package/dist/esm/model/nodes/ExpressionNode.js +5 -8
- package/dist/esm/model/nodes/LLMChatV2Node.js +10 -1
- package/dist/esm/model/nodes/MatchNode.js +86 -41
- package/dist/esm/plugins/gentrace/gentraceSdk.js +0 -1
- package/dist/esm/plugins/gentrace/index.js +0 -1
- package/dist/esm/plugins/gentrace/plugin.js +61 -179
- package/dist/esm/plugins.js +1 -2
- package/dist/esm/recording/ExecutionRecorder.js +49 -8
- package/dist/types/api/createProcessor.d.ts +3 -0
- package/dist/types/integrations/CodeRunner.d.ts +10 -7
- package/dist/types/integrations/CodeRunnerOptions.d.ts +15 -0
- package/dist/types/model/AgentResponseTrace.d.ts +14 -1
- package/dist/types/model/EditorDefinition.d.ts +16 -0
- package/dist/types/model/ExecutorProtocol.d.ts +9 -6
- package/dist/types/model/GraphProcessor.d.ts +15 -5
- package/dist/types/model/NodeBase.d.ts +0 -10
- package/dist/types/model/Nodes.d.ts +2 -2
- package/dist/types/model/ProcessContext.d.ts +52 -0
- package/dist/types/model/UiGraphActionProtocol.d.ts +1 -0
- package/dist/types/model/chat-v2/chatV2CredentialNames.d.ts +30 -0
- package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +1 -0
- package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +3 -0
- package/dist/types/model/chat-v2/chatV2ResponseBodyCapture.d.ts +8 -2
- package/dist/types/model/chat-v2/chatV2RuntimeOptions.d.ts +3 -8
- package/dist/types/model/chat-v2/chatV2Types.d.ts +24 -0
- package/dist/types/model/chat-v2/customProviderApi.d.ts +0 -1
- package/dist/types/model/chat-v2/index.d.ts +3 -0
- package/dist/types/model/chat-v2/llmChatV2CachePolicy.d.ts +1 -1
- package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +10 -1
- package/dist/types/model/chat-v2/llmModelCandidate.d.ts +2 -0
- package/dist/types/model/chat-v2/llmProfile.d.ts +14 -0
- package/dist/types/model/chat-v2/llmProfileBody.d.ts +1 -1
- package/dist/types/model/chat-v2/llmProfileFallback.d.ts +21 -2
- package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +26 -6
- package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +111 -0
- package/dist/types/model/chat-v2/llmProfileNodeRuntime.d.ts +1 -1
- package/dist/types/model/chat-v2/llmProfileTypes.d.ts +3 -0
- package/dist/types/model/chat-v2/providerOptions.d.ts +2 -0
- package/dist/types/model/nodes/CodeNewNode.d.ts +0 -5
- package/dist/types/model/nodes/CodeNode.d.ts +0 -5
- package/dist/types/model/nodes/MatchNode.d.ts +6 -0
- package/dist/types/plugins/gentrace/gentraceSdk.d.ts +0 -1
- package/dist/types/plugins/gentrace/plugin.d.ts +55 -9
- package/dist/types/plugins.d.ts +1 -1
- package/dist/types/recording/ExecutionRecorder.d.ts +7 -1
- package/package.json +2 -2
|
@@ -0,0 +1,326 @@
|
|
|
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
|
+
// Circuit health belongs to the physical provider route and credentials,
|
|
47
|
+
// not to generation policy. A temperature/cooldown edit must not silently
|
|
48
|
+
// create a fresh circuit, while changing the model, endpoint, auth, or
|
|
49
|
+
// routing headers must never inherit another route's outage history.
|
|
50
|
+
const routingConfiguration = {
|
|
51
|
+
provider: params.configuration.provider,
|
|
52
|
+
model: params.configuration.model,
|
|
53
|
+
...(params.configuration.provider !== 'custom'
|
|
54
|
+
? {}
|
|
55
|
+
: {
|
|
56
|
+
customProviderApi: params.configuration.customProviderApi ?? 'completions',
|
|
57
|
+
customProviderBaseURL: params.configuration.customProviderBaseURL,
|
|
58
|
+
}),
|
|
59
|
+
headers: canonicalizeEffectiveRoutingHeaders(params.chatNodeHeaders, params.configuration.headers),
|
|
60
|
+
};
|
|
61
|
+
const serialized = stableStringify({
|
|
62
|
+
routingConfiguration,
|
|
63
|
+
credential: params.credential,
|
|
64
|
+
}) ?? '';
|
|
65
|
+
const configurationFingerprint = sha256(serialized);
|
|
66
|
+
const projectId = params.projectId == null ? undefined : String(params.projectId);
|
|
67
|
+
const profileNodeId = params.profileNodeId == null ? undefined : String(params.profileNodeId);
|
|
68
|
+
const key = sha256(stableStringify({
|
|
69
|
+
kind: 'rivet-llm-profile-health',
|
|
70
|
+
projectId,
|
|
71
|
+
profileNodeId,
|
|
72
|
+
configurationFingerprint,
|
|
73
|
+
}) ?? '');
|
|
74
|
+
return {
|
|
75
|
+
key: `llm-profile:${key}`,
|
|
76
|
+
...(params.projectId == null ? {} : { projectId: params.projectId }),
|
|
77
|
+
...(params.profileNodeId == null ? {} : { profileNodeId: params.profileNodeId }),
|
|
78
|
+
provider: params.configuration.provider,
|
|
79
|
+
model: params.configuration.model,
|
|
80
|
+
...(params.configuration.provider !== 'custom'
|
|
81
|
+
? {}
|
|
82
|
+
: { customProviderApi: params.configuration.customProviderApi ?? 'completions' }),
|
|
83
|
+
configurationFingerprint,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
function canonicalizeEffectiveRoutingHeaders(chatNodeHeaders, profileHeaders) {
|
|
87
|
+
// Provider resolution spreads project-wide headers first and profile
|
|
88
|
+
// headers second. Normalize names here because HTTP field names are
|
|
89
|
+
// case-insensitive, while preserving that same profile-wins precedence.
|
|
90
|
+
// Values remain confined to the SHA-256 input and never enter the public
|
|
91
|
+
// identity or store key in plaintext.
|
|
92
|
+
const headers = new Map();
|
|
93
|
+
for (const [key, value] of Object.entries(chatNodeHeaders ?? {})) {
|
|
94
|
+
const normalizedKey = key.trim().toLowerCase();
|
|
95
|
+
if (normalizedKey)
|
|
96
|
+
headers.set(normalizedKey, value);
|
|
97
|
+
}
|
|
98
|
+
for (const { key, value } of profileHeaders) {
|
|
99
|
+
const normalizedKey = key.trim().toLowerCase();
|
|
100
|
+
if (normalizedKey)
|
|
101
|
+
headers.set(normalizedKey, value);
|
|
102
|
+
}
|
|
103
|
+
return [...headers.entries()].sort(([left], [right]) => left.localeCompare(right));
|
|
104
|
+
}
|
|
105
|
+
function requireMatchingProjectScope(existing, identity) {
|
|
106
|
+
const storedProjectId = existing.identity.projectId == null ? undefined : String(existing.identity.projectId);
|
|
107
|
+
const requestProjectId = identity.projectId == null ? undefined : String(identity.projectId);
|
|
108
|
+
if (storedProjectId !== requestProjectId) {
|
|
109
|
+
throw new Error(`LLM profile reliability key ${identity.key} belongs to a different project scope.`);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
function closedPermitRetentionMs(policy) {
|
|
113
|
+
return Math.max(LLM_PROFILE_CLOSED_PERMIT_MIN_RETENTION_MS, policy.failureWindowMs, policy.openDurationMs, policy.halfOpenLeaseMs);
|
|
114
|
+
}
|
|
115
|
+
function pruneClosedPermits(entry, now) {
|
|
116
|
+
for (const [permitId, expiresAt] of entry.closedPermits) {
|
|
117
|
+
if (expiresAt <= now)
|
|
118
|
+
entry.closedPermits.delete(permitId);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
function pruneFailures(entry, policy, now) {
|
|
122
|
+
const windowStart = now - policy.failureWindowMs;
|
|
123
|
+
entry.failureTimestamps = entry.failureTimestamps.filter((timestamp) => timestamp >= windowStart);
|
|
124
|
+
}
|
|
125
|
+
function getState(entry, now) {
|
|
126
|
+
if (entry.openUntil == null)
|
|
127
|
+
return 'closed';
|
|
128
|
+
if (entry.openUntil > now)
|
|
129
|
+
return 'open';
|
|
130
|
+
return 'half-open';
|
|
131
|
+
}
|
|
132
|
+
function toSnapshot(entry, policy, now) {
|
|
133
|
+
pruneFailures(entry, policy, now);
|
|
134
|
+
const state = getState(entry, now);
|
|
135
|
+
return {
|
|
136
|
+
identity: entry.identity,
|
|
137
|
+
state,
|
|
138
|
+
failureCount: entry.failureTimestamps.length,
|
|
139
|
+
...(entry.openUntil == null ? {} : { openUntil: entry.openUntil }),
|
|
140
|
+
...(state !== 'half-open' || entry.halfOpenLeaseUntil == null
|
|
141
|
+
? {}
|
|
142
|
+
: { halfOpenLeaseUntil: entry.halfOpenLeaseUntil }),
|
|
143
|
+
updatedAt: entry.updatedAt,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
/** Process-local reference implementation used when a host does not supply durable shared storage. */
|
|
147
|
+
export class InMemoryRivetLLMProfileHealthStore {
|
|
148
|
+
#entries = new Map();
|
|
149
|
+
#now;
|
|
150
|
+
constructor(options = {}) {
|
|
151
|
+
this.#now = options.now ?? Date.now;
|
|
152
|
+
}
|
|
153
|
+
#pruneStaleEntries(now) {
|
|
154
|
+
for (const [key, entry] of this.#entries) {
|
|
155
|
+
pruneFailures(entry, entry.policy, now);
|
|
156
|
+
pruneClosedPermits(entry, now);
|
|
157
|
+
const isEmptyClosedEntry = entry.failureTimestamps.length === 0 &&
|
|
158
|
+
entry.openUntil == null &&
|
|
159
|
+
entry.halfOpenPermitId == null &&
|
|
160
|
+
entry.closedPermits.size === 0;
|
|
161
|
+
if (isEmptyClosedEntry && entry.updatedAt + closedPermitRetentionMs(entry.policy) <= now) {
|
|
162
|
+
this.#entries.delete(key);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
begin(request) {
|
|
167
|
+
const { identity, policy } = request;
|
|
168
|
+
const now = this.#now();
|
|
169
|
+
this.#pruneStaleEntries(now);
|
|
170
|
+
let entry = this.#entries.get(identity.key);
|
|
171
|
+
if (entry == null) {
|
|
172
|
+
entry = { identity, failureTimestamps: [], updatedAt: now, policy, closedPermits: new Map() };
|
|
173
|
+
this.#entries.set(identity.key, entry);
|
|
174
|
+
}
|
|
175
|
+
else {
|
|
176
|
+
requireMatchingProjectScope(entry, identity);
|
|
177
|
+
entry.identity = identity;
|
|
178
|
+
entry.policy = policy;
|
|
179
|
+
}
|
|
180
|
+
pruneFailures(entry, policy, now);
|
|
181
|
+
pruneClosedPermits(entry, now);
|
|
182
|
+
if (entry.openUntil != null && entry.openUntil > now) {
|
|
183
|
+
return {
|
|
184
|
+
disposition: 'deny',
|
|
185
|
+
state: 'open',
|
|
186
|
+
retryAt: entry.openUntil,
|
|
187
|
+
snapshot: toSnapshot(entry, policy, now),
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
if (entry.openUntil != null) {
|
|
191
|
+
if (entry.halfOpenPermitId != null && (entry.halfOpenLeaseUntil ?? 0) > now) {
|
|
192
|
+
return {
|
|
193
|
+
disposition: 'deny',
|
|
194
|
+
state: 'half-open',
|
|
195
|
+
retryAt: entry.halfOpenLeaseUntil,
|
|
196
|
+
snapshot: toSnapshot(entry, policy, now),
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
const permitId = nanoid();
|
|
200
|
+
entry.halfOpenPermitId = permitId;
|
|
201
|
+
entry.halfOpenLeaseUntil = now + policy.halfOpenLeaseMs;
|
|
202
|
+
entry.updatedAt = now;
|
|
203
|
+
return {
|
|
204
|
+
disposition: 'allow',
|
|
205
|
+
state: 'half-open',
|
|
206
|
+
permitId,
|
|
207
|
+
snapshot: toSnapshot(entry, policy, now),
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
const permitId = nanoid();
|
|
211
|
+
entry.closedPermits.set(permitId, now + closedPermitRetentionMs(policy));
|
|
212
|
+
entry.updatedAt = now;
|
|
213
|
+
return {
|
|
214
|
+
disposition: 'allow',
|
|
215
|
+
state: 'closed',
|
|
216
|
+
permitId,
|
|
217
|
+
snapshot: toSnapshot(entry, policy, now),
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
finish(request) {
|
|
221
|
+
const { identity, policy, permitId, outcome } = request;
|
|
222
|
+
const now = this.#now();
|
|
223
|
+
this.#pruneStaleEntries(now);
|
|
224
|
+
const entry = this.#entries.get(identity.key);
|
|
225
|
+
if (entry == null) {
|
|
226
|
+
return {
|
|
227
|
+
identity,
|
|
228
|
+
state: 'closed',
|
|
229
|
+
failureCount: 0,
|
|
230
|
+
updatedAt: now,
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
requireMatchingProjectScope(entry, identity);
|
|
234
|
+
entry.identity = identity;
|
|
235
|
+
entry.policy = policy;
|
|
236
|
+
pruneFailures(entry, policy, now);
|
|
237
|
+
pruneClosedPermits(entry, now);
|
|
238
|
+
const ownsHalfOpenLease = entry.halfOpenPermitId === permitId;
|
|
239
|
+
const ownsClosedPermit = entry.closedPermits.delete(permitId);
|
|
240
|
+
if (!ownsHalfOpenLease && !ownsClosedPermit) {
|
|
241
|
+
return toSnapshot(entry, policy, now);
|
|
242
|
+
}
|
|
243
|
+
if (outcome === 'healthy' && ownsHalfOpenLease) {
|
|
244
|
+
entry.failureTimestamps = [];
|
|
245
|
+
entry.openUntil = undefined;
|
|
246
|
+
entry.halfOpenPermitId = undefined;
|
|
247
|
+
entry.halfOpenLeaseUntil = undefined;
|
|
248
|
+
// Requests admitted before the circuit opened belong to the previous
|
|
249
|
+
// health generation. Once the single recovery probe succeeds, their
|
|
250
|
+
// eventual results must not immediately poison the recovered circuit.
|
|
251
|
+
entry.closedPermits.clear();
|
|
252
|
+
}
|
|
253
|
+
else if (outcome === 'unhealthy') {
|
|
254
|
+
const wasOpen = entry.openUntil != null;
|
|
255
|
+
entry.failureTimestamps.push(now);
|
|
256
|
+
if (ownsHalfOpenLease || (!wasOpen && entry.failureTimestamps.length >= policy.failureThreshold)) {
|
|
257
|
+
entry.openUntil = now + policy.openDurationMs;
|
|
258
|
+
}
|
|
259
|
+
if (ownsHalfOpenLease) {
|
|
260
|
+
entry.halfOpenPermitId = undefined;
|
|
261
|
+
entry.halfOpenLeaseUntil = undefined;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
else if (outcome === 'ignored' && ownsHalfOpenLease) {
|
|
265
|
+
entry.halfOpenPermitId = undefined;
|
|
266
|
+
entry.halfOpenLeaseUntil = undefined;
|
|
267
|
+
}
|
|
268
|
+
entry.updatedAt = now;
|
|
269
|
+
return toSnapshot(entry, policy, now);
|
|
270
|
+
}
|
|
271
|
+
renew(request) {
|
|
272
|
+
const now = this.#now();
|
|
273
|
+
this.#pruneStaleEntries(now);
|
|
274
|
+
const entry = this.#entries.get(request.identity.key);
|
|
275
|
+
if (entry == null) {
|
|
276
|
+
return {
|
|
277
|
+
identity: request.identity,
|
|
278
|
+
state: 'closed',
|
|
279
|
+
failureCount: 0,
|
|
280
|
+
updatedAt: now,
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
requireMatchingProjectScope(entry, request.identity);
|
|
284
|
+
if (entry.halfOpenPermitId === request.permitId) {
|
|
285
|
+
entry.halfOpenLeaseUntil = Math.max(entry.halfOpenLeaseUntil ?? 0, now + request.leaseDurationMs);
|
|
286
|
+
entry.updatedAt = now;
|
|
287
|
+
}
|
|
288
|
+
else if (entry.closedPermits.has(request.permitId)) {
|
|
289
|
+
entry.closedPermits.set(request.permitId, Math.max(entry.closedPermits.get(request.permitId) ?? 0, now + closedPermitRetentionMs(entry.policy)));
|
|
290
|
+
entry.updatedAt = now;
|
|
291
|
+
}
|
|
292
|
+
return toSnapshot(entry, entry.policy, now);
|
|
293
|
+
}
|
|
294
|
+
reset(request) {
|
|
295
|
+
if (request.key != null) {
|
|
296
|
+
this.#entries.delete(request.key);
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
for (const [key, entry] of this.#entries) {
|
|
300
|
+
if (entry.identity.projectId === request.projectId) {
|
|
301
|
+
this.#entries.delete(key);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
list(request = {}) {
|
|
306
|
+
const now = this.#now();
|
|
307
|
+
this.#pruneStaleEntries(now);
|
|
308
|
+
return [...this.#entries.entries()]
|
|
309
|
+
.filter(([, entry]) => request.projectId == null || entry.identity.projectId === request.projectId)
|
|
310
|
+
.map(([, entry]) => {
|
|
311
|
+
pruneFailures(entry, entry.policy, now);
|
|
312
|
+
pruneClosedPermits(entry, now);
|
|
313
|
+
const state = getState(entry, now);
|
|
314
|
+
return {
|
|
315
|
+
identity: entry.identity,
|
|
316
|
+
state,
|
|
317
|
+
failureCount: entry.failureTimestamps.length,
|
|
318
|
+
...(entry.openUntil == null ? {} : { openUntil: entry.openUntil }),
|
|
319
|
+
...(state !== 'half-open' || entry.halfOpenLeaseUntil == null
|
|
320
|
+
? {}
|
|
321
|
+
: { halfOpenLeaseUntil: entry.halfOpenLeaseUntil }),
|
|
322
|
+
updatedAt: entry.updatedAt,
|
|
323
|
+
};
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
}
|
|
@@ -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,63 @@ 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;
|
|
38
79
|
return {
|
|
39
80
|
version: LLM_PROFILE_VALUE_VERSION,
|
|
40
81
|
credential,
|
|
41
|
-
configuration
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
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
|
-
},
|
|
82
|
+
configuration,
|
|
83
|
+
...(projectId == null
|
|
84
|
+
? {}
|
|
85
|
+
: {
|
|
86
|
+
healthIdentity: createRivetLLMProfileHealthIdentity({
|
|
87
|
+
configuration,
|
|
88
|
+
credential,
|
|
89
|
+
chatNodeHeaders: context.settings.chatNodeHeaders,
|
|
90
|
+
projectId,
|
|
91
|
+
profileNodeId: context.node.id,
|
|
92
|
+
}),
|
|
93
|
+
}),
|
|
75
94
|
};
|
|
76
95
|
}
|
|
@@ -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 =
|
|
195
|
-
const
|
|
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 =
|
|
226
|
+
let processedInit = shouldSerializeProcessedBody
|
|
203
227
|
? {
|
|
204
228
|
...init,
|
|
205
|
-
body: serializeTransformedFetchBody(
|
|
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
|
-
|
|
210
|
-
|
|
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
|
|
@@ -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) {
|
|
@@ -7,6 +7,8 @@ import {} from '../NodeBodySpec.js';
|
|
|
7
7
|
import { nodeDefinition } from '../NodeDefinition.js';
|
|
8
8
|
import { resolveUniqueValueDerivedPortIds } from '../../utils/orderedStringPortIds.js';
|
|
9
9
|
import { appendCodeNodeSourceUrl, buildCodeNodeSourceUrl, enrichCodeNodeErrorWithLocation, } from './codeNodeErrorDiagnostics.js';
|
|
10
|
+
import { ALL_CODE_RUNNER_OPTIONS } from '../../integrations/CodeRunnerOptions.js';
|
|
11
|
+
const CODE_RUNTIME_HELPER_MESSAGE = 'Node execution also provides "require" and "process". Browser execution provides "fetch", "console", and "Rivet".';
|
|
10
12
|
export class CodeNodeImpl extends NodeImpl {
|
|
11
13
|
static create() {
|
|
12
14
|
const chartNode = {
|
|
@@ -32,11 +34,6 @@ export class CodeNodeImpl extends NodeImpl {
|
|
|
32
34
|
`,
|
|
33
35
|
inputNames: 'input1',
|
|
34
36
|
outputNames: 'output1',
|
|
35
|
-
allowFetch: false,
|
|
36
|
-
allowRequire: false,
|
|
37
|
-
allowRivet: false,
|
|
38
|
-
allowProcess: false,
|
|
39
|
-
allowConsole: false,
|
|
40
37
|
},
|
|
41
38
|
};
|
|
42
39
|
return chartNode;
|
|
@@ -81,6 +78,7 @@ export class CodeNodeImpl extends NodeImpl {
|
|
|
81
78
|
{
|
|
82
79
|
type: 'code',
|
|
83
80
|
label: '',
|
|
81
|
+
helperMessage: CODE_RUNTIME_HELPER_MESSAGE,
|
|
84
82
|
dataKey: 'code',
|
|
85
83
|
language: 'javascript',
|
|
86
84
|
enableFolding: true,
|
|
@@ -107,40 +105,6 @@ export class CodeNodeImpl extends NodeImpl {
|
|
|
107
105
|
valueToPortId: 'sanitize-identifier',
|
|
108
106
|
},
|
|
109
107
|
},
|
|
110
|
-
{
|
|
111
|
-
type: 'group',
|
|
112
|
-
label: 'Runtime permissions',
|
|
113
|
-
defaultOpen: true,
|
|
114
|
-
editors: [
|
|
115
|
-
{
|
|
116
|
-
type: 'toggle',
|
|
117
|
-
label: 'Allow "fetch"',
|
|
118
|
-
dataKey: 'allowFetch',
|
|
119
|
-
},
|
|
120
|
-
{
|
|
121
|
-
type: 'toggle',
|
|
122
|
-
label: 'Allow "Rivet"',
|
|
123
|
-
dataKey: 'allowRivet',
|
|
124
|
-
},
|
|
125
|
-
{
|
|
126
|
-
type: 'toggle',
|
|
127
|
-
label: 'Allow "console"',
|
|
128
|
-
dataKey: 'allowConsole',
|
|
129
|
-
},
|
|
130
|
-
{
|
|
131
|
-
type: 'toggle',
|
|
132
|
-
label: 'Allow "require"',
|
|
133
|
-
dataKey: 'allowRequire',
|
|
134
|
-
helperMessage: 'Only available with the Node executor',
|
|
135
|
-
},
|
|
136
|
-
{
|
|
137
|
-
type: 'toggle',
|
|
138
|
-
label: 'Allow "process"',
|
|
139
|
-
dataKey: 'allowProcess',
|
|
140
|
-
helperMessage: 'Only available with the Node executor',
|
|
141
|
-
},
|
|
142
|
-
],
|
|
143
|
-
},
|
|
144
108
|
];
|
|
145
109
|
}
|
|
146
110
|
getBody() {
|
|
@@ -167,13 +131,7 @@ export class CodeNodeImpl extends NodeImpl {
|
|
|
167
131
|
const sourceUrl = buildCodeNodeSourceUrl(this.chartNode.id);
|
|
168
132
|
let outputs;
|
|
169
133
|
try {
|
|
170
|
-
outputs = await context.codeRunner.runCode(appendCodeNodeSourceUrl(this.data.code, sourceUrl), inputs,
|
|
171
|
-
includeFetch: this.data.allowFetch ?? false,
|
|
172
|
-
includeRequire: this.data.allowRequire ?? false,
|
|
173
|
-
includeRivet: this.data.allowRivet ?? false,
|
|
174
|
-
includeProcess: this.data.allowProcess ?? false,
|
|
175
|
-
includeConsole: this.data.allowConsole ?? false,
|
|
176
|
-
}, context.graphInputNodeValues, context.contextValues);
|
|
134
|
+
outputs = await context.codeRunner.runCode(appendCodeNodeSourceUrl(this.data.code, sourceUrl), inputs, ALL_CODE_RUNNER_OPTIONS, context.graphInputNodeValues, context.contextValues);
|
|
177
135
|
}
|
|
178
136
|
catch (error) {
|
|
179
137
|
throw await enrichCodeNodeErrorWithLocation({
|