@valerypopoff/rivet2-core 2.17.0 → 2.19.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/dist/cjs/bundle.cjs +3093 -1440
- package/dist/cjs/bundle.cjs.map +4 -4
- package/dist/cjs/interpolationRuntime.cjs +40 -4
- package/dist/cjs/interpolationRuntime.cjs.map +2 -2
- package/dist/cjs/serialization.cjs +1880 -0
- package/dist/cjs/serialization.cjs.map +7 -0
- package/dist/cjs/webAppRuntime.cjs +168 -6
- package/dist/cjs/webAppRuntime.cjs.map +3 -3
- package/dist/esm/api/processSettings.js +1 -0
- package/dist/esm/exports.js +2 -0
- package/dist/esm/model/AgentResponseTrace.js +99 -34
- package/dist/esm/model/AgentResponseTracePresentation.js +130 -0
- package/dist/esm/model/DataValue.js +11 -2
- package/dist/esm/model/GlobalVariables.js +2 -1
- package/dist/esm/model/GraphBoundaryEffects.js +38 -1
- package/dist/esm/model/GraphExecutionState.js +81 -0
- package/dist/esm/model/GraphProcessor.js +621 -942
- package/dist/esm/model/GraphSchedulerBoundaryState.js +64 -0
- package/dist/esm/model/Nodes.js +5 -0
- package/dist/esm/model/ProjectBundle.js +23 -10
- package/dist/esm/model/ProjectBundleRuntime.js +54 -0
- package/dist/esm/model/SchedulerBoundaryPlanner.js +233 -0
- package/dist/esm/model/SubprocessorBridge.js +125 -87
- package/dist/esm/model/ToolCallContinuationCoordinator.js +1 -1
- package/dist/esm/model/chat-v2/aiSdkBridge.js +15 -12
- package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -4
- package/dist/esm/model/chat-v2/chatV2CredentialNames.js +5 -1
- package/dist/esm/model/chat-v2/chatV2Outputs.js +2 -2
- package/dist/esm/model/chat-v2/chatV2Pipeline.js +11 -1
- package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +3 -2
- package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +46 -6
- package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +7 -0
- package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +10 -0
- package/dist/esm/model/chat-v2/llmChatV2Body.js +2 -2
- package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +5 -2
- package/dist/esm/model/chat-v2/llmChatV2NodeData.js +1 -0
- package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +18 -8
- package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +10 -2
- package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +17 -0
- package/dist/esm/model/chat-v2/llmModelCandidate.js +2 -1
- package/dist/esm/model/chat-v2/llmProfile.js +2 -1
- package/dist/esm/model/chat-v2/llmProfileBody.js +9 -0
- package/dist/esm/model/chat-v2/llmProfileFallback.js +7 -4
- package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +1 -0
- package/dist/esm/model/chat-v2/llmProfileHealthStore.js +16 -3
- package/dist/esm/model/chat-v2/messageConverter.js +18 -16
- package/dist/esm/model/chat-v2/modelRegistry.js +14 -4
- package/dist/esm/model/chat-v2/openRouterModel.js +73 -0
- package/dist/esm/model/chat-v2/parallelToolCalls.js +2 -0
- package/dist/esm/model/chat-v2/providerOptions.js +30 -25
- package/dist/esm/model/classifier/credentials.js +13 -3
- package/dist/esm/model/classifier/limits.js +33 -3
- package/dist/esm/model/classifier/perplexity.js +63 -0
- package/dist/esm/model/classifier/profile.js +151 -0
- package/dist/esm/model/classifier/profileExecution.js +294 -0
- package/dist/esm/model/classifier/providers.js +217 -30
- package/dist/esm/model/classifier/state.js +4 -1
- package/dist/esm/model/classifier/types.js +11 -1
- package/dist/esm/model/nodeRunFailure.js +8 -1
- package/dist/esm/model/nodes/CallGraphNode.js +6 -0
- package/dist/esm/model/nodes/ClassifierEvaluateNode.js +250 -59
- package/dist/esm/model/nodes/ClassifierProfileNode.js +133 -0
- package/dist/esm/model/nodes/DelegateFunctionCallNode.js +1 -1
- package/dist/esm/model/nodes/LLMChatV2Node.js +2 -1
- package/dist/esm/model/nodes/SubGraphNode.js +3 -0
- package/dist/esm/model/nodes/toolCallDelegation.js +5 -1
- package/dist/esm/model/profileSuspensionHints.js +8 -0
- package/dist/esm/serialization.js +2 -0
- package/dist/esm/utils/coerceType.js +11 -1
- package/dist/esm/webAppRuntime.js +1 -0
- package/dist/types/exports.d.ts +2 -0
- package/dist/types/model/AgentResponseTrace.d.ts +15 -4
- package/dist/types/model/AgentResponseTracePresentation.d.ts +15 -0
- package/dist/types/model/DataValue.d.ts +12 -8
- package/dist/types/model/ExecutorProtocol.d.ts +7 -0
- package/dist/types/model/GraphBoundaryEffects.d.ts +10 -1
- package/dist/types/model/GraphExecutionState.d.ts +68 -0
- package/dist/types/model/GraphProcessor.d.ts +1 -0
- package/dist/types/model/GraphSchedulerBoundaryState.d.ts +96 -0
- package/dist/types/model/Nodes.d.ts +7 -4
- package/dist/types/model/ProcessContext.d.ts +12 -3
- package/dist/types/model/ProjectBundle.d.ts +9 -4
- package/dist/types/model/ProjectBundleRuntime.d.ts +24 -0
- package/dist/types/model/RivetUIContext.d.ts +1 -1
- package/dist/types/model/SchedulerBoundaryPlanner.d.ts +42 -0
- package/dist/types/model/Settings.d.ts +1 -0
- package/dist/types/model/SubprocessorBridge.d.ts +2 -0
- package/dist/types/model/chat-v2/chatV2CredentialNames.d.ts +4 -0
- package/dist/types/model/chat-v2/chatV2Outputs.d.ts +1 -1
- package/dist/types/model/chat-v2/chatV2ProviderRegistry.d.ts +79 -1
- package/dist/types/model/chat-v2/chatV2ProviderTypes.d.ts +1 -1
- package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +2 -0
- package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +2 -1
- package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +2 -0
- package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +2 -0
- package/dist/types/model/chat-v2/llmProfileFallback.d.ts +51 -3
- package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +9 -6
- package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +6 -2
- package/dist/types/model/chat-v2/modelRegistry.d.ts +5 -4
- package/dist/types/model/chat-v2/openRouterModel.d.ts +2 -0
- package/dist/types/model/chat-v2/providerOptions.d.ts +2 -13
- package/dist/types/model/classifier/credentials.d.ts +4 -0
- package/dist/types/model/classifier/limits.d.ts +4 -1
- package/dist/types/model/classifier/perplexity.d.ts +7 -0
- package/dist/types/model/classifier/profile.d.ts +46 -0
- package/dist/types/model/classifier/profileExecution.d.ts +32 -0
- package/dist/types/model/classifier/providers.d.ts +32 -1
- package/dist/types/model/classifier/types.d.ts +9 -0
- package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +14 -12
- package/dist/types/model/nodes/ClassifierProfileNode.d.ts +20 -0
- package/dist/types/model/nodes/toolCallDelegation.d.ts +3 -1
- package/dist/types/model/profileSuspensionHints.d.ts +8 -0
- package/dist/types/serialization.d.ts +2 -0
- package/dist/types/webAppRuntime.d.ts +1 -0
- package/package.json +7 -1
|
@@ -10,6 +10,9 @@ export const CLASSIFIER_LIMITS = {
|
|
|
10
10
|
};
|
|
11
11
|
export class ClassifierResourceLimitError extends Error {
|
|
12
12
|
}
|
|
13
|
+
/** Receipt failed before JSON decoding/validation, rather than malformed evidence. */
|
|
14
|
+
export class ClassifierResponseReadError extends Error {
|
|
15
|
+
}
|
|
13
16
|
const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
|
|
14
17
|
const byteBuffer = Object.getOwnPropertyDescriptor(typedArrayPrototype, 'buffer').get;
|
|
15
18
|
const byteOffset = Object.getOwnPropertyDescriptor(typedArrayPrototype, 'byteOffset').get;
|
|
@@ -219,7 +222,7 @@ export function checkClassifierJsonWork(text, check, label = 'response') {
|
|
|
219
222
|
}
|
|
220
223
|
}
|
|
221
224
|
/** Consume decoded response bytes incrementally; Content-Length is not trusted. */
|
|
222
|
-
export async function readClassifierResponse(response, signal, check = () => signal.throwIfAborted()) {
|
|
225
|
+
export async function readClassifierResponse(response, signal, check = () => signal.throwIfAborted(), onBody) {
|
|
223
226
|
const length = response.headers.get('content-length');
|
|
224
227
|
if (length && Number(length) > CLASSIFIER_LIMITS.responseBytes)
|
|
225
228
|
throw new ClassifierResourceLimitError('Classifier response exceeds the 8 MiB response limit.');
|
|
@@ -237,7 +240,9 @@ export async function readClassifierResponse(response, signal, check = () => sig
|
|
|
237
240
|
try {
|
|
238
241
|
for (;;) {
|
|
239
242
|
check();
|
|
240
|
-
const { done, value } = await reader.read()
|
|
243
|
+
const { done, value } = await reader.read().catch((cause) => {
|
|
244
|
+
throw new ClassifierResponseReadError('Classifier response body could not be read.', { cause });
|
|
245
|
+
});
|
|
241
246
|
check();
|
|
242
247
|
if (done)
|
|
243
248
|
break;
|
|
@@ -255,8 +260,33 @@ export async function readClassifierResponse(response, signal, check = () => sig
|
|
|
255
260
|
check();
|
|
256
261
|
const json = text.join('');
|
|
257
262
|
checkClassifierJsonWork(json, check);
|
|
258
|
-
|
|
263
|
+
let body;
|
|
264
|
+
try {
|
|
265
|
+
body = JSON.parse(json);
|
|
266
|
+
}
|
|
267
|
+
catch (error) {
|
|
268
|
+
check();
|
|
269
|
+
try {
|
|
270
|
+
onBody?.(json);
|
|
271
|
+
}
|
|
272
|
+
catch {
|
|
273
|
+
/* Observation only. */
|
|
274
|
+
}
|
|
275
|
+
check();
|
|
276
|
+
throw error;
|
|
277
|
+
}
|
|
259
278
|
assertClassifierResourceLimits(body, check, CLASSIFIER_LIMITS.responseBytes);
|
|
279
|
+
check();
|
|
280
|
+
try {
|
|
281
|
+
// Diagnostics must not modify the private response before validation or pricing.
|
|
282
|
+
// Only opt-in observers allocate a detached copy of this bounded, plain JSON.
|
|
283
|
+
if (onBody)
|
|
284
|
+
onBody(structuredClone(body));
|
|
285
|
+
}
|
|
286
|
+
catch {
|
|
287
|
+
/* Observation only. */
|
|
288
|
+
}
|
|
289
|
+
check();
|
|
260
290
|
return body;
|
|
261
291
|
}
|
|
262
292
|
catch (error) {
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { systemOneState } from './state.js';
|
|
2
|
+
import { inspectClassifierImage } from './images.js';
|
|
3
|
+
export const PERPLEXITY_DECISION_MODELS = ['pplx-decider-v1.1-27b', 'pplx-decider-v1-27b'];
|
|
4
|
+
/** Native inline image parts; a top-level images field is not accepted. */
|
|
5
|
+
export function perplexityDecisionState(state) {
|
|
6
|
+
if (state.kind === 'json')
|
|
7
|
+
return state.value;
|
|
8
|
+
if (!state.images.length)
|
|
9
|
+
return systemOneState({ state: '', stateMessages: state.messages }).state;
|
|
10
|
+
const parts = [];
|
|
11
|
+
for (const [messageIndex, message] of state.messages.entries()) {
|
|
12
|
+
if (messageIndex)
|
|
13
|
+
parts.push('\n\n');
|
|
14
|
+
for (const [partIndex, part] of message.parts.entries()) {
|
|
15
|
+
if (partIndex)
|
|
16
|
+
parts.push('\n');
|
|
17
|
+
parts.push(part.type === 'text' ? part.text : { type: 'image_url', image_url: { url: part.dataUrl } });
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return parts;
|
|
21
|
+
}
|
|
22
|
+
/** Provider capability limits, not shared input errors or provider outages. */
|
|
23
|
+
export function assertPerplexityDecisionLimits({ model, state, questions }, check) {
|
|
24
|
+
if (questions.length > 128)
|
|
25
|
+
throw new Error('Perplexity Decisions supports at most 128 questions per request.');
|
|
26
|
+
for (const question of questions) {
|
|
27
|
+
check();
|
|
28
|
+
if (question.type === 'score' && question.criteria.includes(null))
|
|
29
|
+
throw new Error('Perplexity Decisions Score levels cannot be null.');
|
|
30
|
+
}
|
|
31
|
+
const inspect = ({ width, height, mediaType }) => {
|
|
32
|
+
check();
|
|
33
|
+
if (!PERPLEXITY_DECISION_MODELS.includes(model))
|
|
34
|
+
throw new Error('Image support is not known for this Perplexity Decisions model.');
|
|
35
|
+
if (!['image/png', 'image/jpeg', 'image/webp'].includes(mediaType))
|
|
36
|
+
throw new Error('Perplexity Decisions accepts PNG, JPEG and WebP images, not GIF.');
|
|
37
|
+
// Round up conservatively: oversized images can hang until a provider 504.
|
|
38
|
+
if (Math.ceil(width / 32) * Math.ceil(height / 32) > 2048)
|
|
39
|
+
throw new Error('Perplexity Decisions images must contain at most 2,048 tiles of 32 by 32 pixels each. Resize upstream.');
|
|
40
|
+
};
|
|
41
|
+
if (state.kind === 'messages') {
|
|
42
|
+
for (const image of state.images)
|
|
43
|
+
inspect(image);
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
// The native API also interprets top-level image_url parts in JSON State.
|
|
47
|
+
// Validate that wire shape without traversing arbitrary nested evidence or
|
|
48
|
+
// letting raw parts bypass the ordinary image capability checks.
|
|
49
|
+
let imageCount = 0;
|
|
50
|
+
for (const part of Array.isArray(state.value) ? state.value : [state.value]) {
|
|
51
|
+
check();
|
|
52
|
+
if (!part || typeof part !== 'object' || Array.isArray(part))
|
|
53
|
+
continue;
|
|
54
|
+
const record = part;
|
|
55
|
+
if (record.type !== 'image_url')
|
|
56
|
+
continue;
|
|
57
|
+
if (++imageCount > 128)
|
|
58
|
+
throw new Error('State must contain at most 128 images.');
|
|
59
|
+
const image = record.image_url;
|
|
60
|
+
const url = image && typeof image === 'object' && !Array.isArray(image) ? image.url : undefined;
|
|
61
|
+
inspect(inspectClassifierImage(url, check));
|
|
62
|
+
}
|
|
63
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import CryptoJS from 'crypto-js';
|
|
2
|
+
import stableStringify from 'safe-stable-stringify';
|
|
3
|
+
import { classifierInputDataValue, snapshotClassifierJson } from './json.js';
|
|
4
|
+
import { ClassifierValueBudget } from './limits.js';
|
|
5
|
+
import { getClassifierProvider } from './providers.js';
|
|
6
|
+
import { ClassifierCredentialMissingError, resolveClassifierApiKey, } from './credentials.js';
|
|
7
|
+
export const DEFAULT_CLASSIFIER_PROFILE_RESPONSE_TIMEOUT_MS = 500;
|
|
8
|
+
export const DEFAULT_CLASSIFIER_PROFILE_FAILURE_THRESHOLD = 3;
|
|
9
|
+
export const DEFAULT_CLASSIFIER_PROFILE_FAILURE_WINDOW_MS = 300_000;
|
|
10
|
+
export const DEFAULT_CLASSIFIER_PROFILE_OPEN_DURATION_MS = 300_000;
|
|
11
|
+
export const classifierProfileInputIds = ['model', 'apiKey'];
|
|
12
|
+
export const classifierProfileDataKeys = [
|
|
13
|
+
'provider',
|
|
14
|
+
'model',
|
|
15
|
+
'useModelInput',
|
|
16
|
+
'apiKeySource',
|
|
17
|
+
'apiKeyNamesByProvider',
|
|
18
|
+
'apiKeyNames',
|
|
19
|
+
'responseTimeoutMs',
|
|
20
|
+
'enableCircuitBreaker',
|
|
21
|
+
'circuitBreakerFailureThreshold',
|
|
22
|
+
'circuitBreakerFailureWindowMs',
|
|
23
|
+
'circuitBreakerOpenDurationMs',
|
|
24
|
+
];
|
|
25
|
+
export function pickClassifierProfileData(data) {
|
|
26
|
+
return Object.fromEntries(classifierProfileDataKeys.filter((key) => data[key] !== undefined).map((key) => [key, data[key]]));
|
|
27
|
+
}
|
|
28
|
+
function positive(value, fallback, label, maximum = 600_000) {
|
|
29
|
+
const result = value ?? fallback;
|
|
30
|
+
if (!Number.isSafeInteger(result) || result < 1 || result > maximum)
|
|
31
|
+
throw new Error(`Classifier Profile ${label} must be an integer between 1 and ${maximum}.`);
|
|
32
|
+
return result;
|
|
33
|
+
}
|
|
34
|
+
export function classifierProfileResponseTimeout(configuration) {
|
|
35
|
+
return positive(configuration.responseTimeoutMs, DEFAULT_CLASSIFIER_PROFILE_RESPONSE_TIMEOUT_MS, 'response timeout');
|
|
36
|
+
}
|
|
37
|
+
export function classifierProfileHealthPolicy(configuration) {
|
|
38
|
+
if (configuration.enableCircuitBreaker !== true)
|
|
39
|
+
return undefined;
|
|
40
|
+
return {
|
|
41
|
+
failureThreshold: positive(configuration.circuitBreakerFailureThreshold, DEFAULT_CLASSIFIER_PROFILE_FAILURE_THRESHOLD, 'failure threshold', 1000),
|
|
42
|
+
failureWindowMs: positive(configuration.circuitBreakerFailureWindowMs, DEFAULT_CLASSIFIER_PROFILE_FAILURE_WINDOW_MS, 'failure window', 86_400_000),
|
|
43
|
+
openDurationMs: positive(configuration.circuitBreakerOpenDurationMs, DEFAULT_CLASSIFIER_PROFILE_OPEN_DURATION_MS, 'suspension duration', 86_400_000),
|
|
44
|
+
halfOpenLeaseMs: classifierProfileResponseTimeout(configuration) + 5000,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
export function normalizeClassifierProfileValue(value) {
|
|
48
|
+
return normalizeDetachedProfile(snapshotClassifierJson(value, 'Classifier Profile', new ClassifierValueBudget(), true));
|
|
49
|
+
}
|
|
50
|
+
function normalizeDetachedProfile(value) {
|
|
51
|
+
const profile = value;
|
|
52
|
+
if (!profile ||
|
|
53
|
+
profile.version !== 1 ||
|
|
54
|
+
!profile.configuration ||
|
|
55
|
+
typeof profile.configuration !== 'object' ||
|
|
56
|
+
Array.isArray(profile.configuration) ||
|
|
57
|
+
!profile.credential ||
|
|
58
|
+
typeof profile.credential !== 'object' ||
|
|
59
|
+
Array.isArray(profile.credential))
|
|
60
|
+
throw new Error('Classifier Profiles input requires a version 1 Classifier Profile.');
|
|
61
|
+
const { configuration, credential } = profile;
|
|
62
|
+
if (typeof configuration.provider !== 'string' ||
|
|
63
|
+
typeof configuration.model !== 'string' ||
|
|
64
|
+
!configuration.model.trim())
|
|
65
|
+
throw new Error('Classifier Profile requires a provider and a nonblank model.');
|
|
66
|
+
getClassifierProvider(configuration.provider);
|
|
67
|
+
if (credential.value !== undefined && (typeof credential.value !== 'string' || /[\r\n]/.test(credential.value)))
|
|
68
|
+
throw new Error('Classifier Profile credential must be a string without line breaks.');
|
|
69
|
+
if (profile.profileName !== undefined && typeof profile.profileName !== 'string')
|
|
70
|
+
throw new Error('Invalid Classifier Profile name.');
|
|
71
|
+
if (profile.sourceNodeId !== undefined && (typeof profile.sourceNodeId !== 'string' || !profile.sourceNodeId.trim()))
|
|
72
|
+
throw new Error('Invalid Classifier Profile source node.');
|
|
73
|
+
if (configuration.enableCircuitBreaker !== undefined && typeof configuration.enableCircuitBreaker !== 'boolean')
|
|
74
|
+
throw new Error('Classifier Profile automatic suspension must be a boolean.');
|
|
75
|
+
if (configuration.apiKeySource !== undefined &&
|
|
76
|
+
!['configured', 'classifier-settings', 'input'].includes(configuration.apiKeySource))
|
|
77
|
+
throw new Error('Unknown classifier API key source.');
|
|
78
|
+
classifierProfileResponseTimeout(configuration);
|
|
79
|
+
classifierProfileHealthPolicy(configuration);
|
|
80
|
+
return {
|
|
81
|
+
version: 1,
|
|
82
|
+
sourceNodeId: profile.sourceNodeId,
|
|
83
|
+
profileName: profile.profileName?.trim() || undefined,
|
|
84
|
+
credential: credential.value === undefined ? {} : { value: credential.value.trim() },
|
|
85
|
+
configuration: {
|
|
86
|
+
...pickClassifierProfileData(configuration),
|
|
87
|
+
provider: configuration.provider,
|
|
88
|
+
model: configuration.model.trim(),
|
|
89
|
+
useModelInput: false,
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
export function normalizeClassifierProfiles(value, check) {
|
|
94
|
+
if (Array.isArray(value) && (value.length === 0 || value.length > 128))
|
|
95
|
+
throw new Error('Classifier Profiles requires between 1 and 128 profiles.');
|
|
96
|
+
// One deadline-aware traversal bounds, validates and detaches the whole
|
|
97
|
+
// chain. Do not rescan each candidate with a fresh resource budget.
|
|
98
|
+
const detached = snapshotClassifierJson(value, 'Classifier Profiles', new ClassifierValueBudget(check), true);
|
|
99
|
+
return (Array.isArray(detached) ? detached : [detached]).map(normalizeDetachedProfile);
|
|
100
|
+
}
|
|
101
|
+
export function resolveClassifierProfile(data, inputs, context) {
|
|
102
|
+
const provider = getClassifierProvider(data.provider);
|
|
103
|
+
const model = data.useModelInput
|
|
104
|
+
? classifierInputDataValue(inputs, 'model')?.value
|
|
105
|
+
: data.model?.trim() || provider.defaultModel;
|
|
106
|
+
if (typeof model !== 'string' || !model.trim())
|
|
107
|
+
throw new Error('Classifier Profile model is required.');
|
|
108
|
+
let value;
|
|
109
|
+
// Missing credentials are a candidate failure, not an upstream graph failure.
|
|
110
|
+
// Invalid credential-name configuration still fails while authoring the profile.
|
|
111
|
+
try {
|
|
112
|
+
value = resolveClassifierApiKey({
|
|
113
|
+
apiKeyNames: data.apiKeyNamesByProvider?.[provider.id] ?? data.apiKeyNames,
|
|
114
|
+
apiKeySource: data.apiKeySource,
|
|
115
|
+
context,
|
|
116
|
+
defaults: provider.credentialNames,
|
|
117
|
+
inputs,
|
|
118
|
+
providerId: provider.id,
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
if (!(error instanceof ClassifierCredentialMissingError))
|
|
123
|
+
throw error;
|
|
124
|
+
}
|
|
125
|
+
return normalizeClassifierProfileValue({
|
|
126
|
+
version: 1,
|
|
127
|
+
configuration: { ...pickClassifierProfileData(data), provider: provider.id, model, useModelInput: false },
|
|
128
|
+
credential: value === undefined ? {} : { value },
|
|
129
|
+
profileName: context.node.title,
|
|
130
|
+
sourceNodeId: context.node.id,
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
export function classifierProfileHealthIdentity(profile, projectId, fallbackNodeId) {
|
|
134
|
+
const hash = (value) => `sha256:${CryptoJS.SHA256(stableStringify(value) ?? '').toString(CryptoJS.enc.Hex)}`;
|
|
135
|
+
const configurationFingerprint = hash({
|
|
136
|
+
provider: profile.configuration.provider,
|
|
137
|
+
model: profile.configuration.model,
|
|
138
|
+
credential: profile.credential,
|
|
139
|
+
});
|
|
140
|
+
const profileNodeId = profile.sourceNodeId ?? fallbackNodeId;
|
|
141
|
+
return {
|
|
142
|
+
key: `classifier-profile:${hash({ projectId, profileNodeId, configurationFingerprint })}`,
|
|
143
|
+
family: 'classifier',
|
|
144
|
+
projectId,
|
|
145
|
+
profileNodeId,
|
|
146
|
+
profileName: profile.profileName,
|
|
147
|
+
provider: profile.configuration.provider,
|
|
148
|
+
model: profile.configuration.model,
|
|
149
|
+
configurationFingerprint,
|
|
150
|
+
};
|
|
151
|
+
}
|
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
import { createProfileHealthPermit, runBoundedHealthOperation, } from '../chat-v2/llmProfileFallback.js';
|
|
2
|
+
import { ClassifierProviderError, classifierFailureKind, classifierErrorMessage, getClassifierProvider, } from './providers.js';
|
|
3
|
+
import { classifierProfileHealthIdentity, classifierProfileHealthPolicy, classifierProfileResponseTimeout, } from './profile.js';
|
|
4
|
+
export function classifierProfileSummary(profiles, attempts) {
|
|
5
|
+
return profiles
|
|
6
|
+
.map((profile, index) => {
|
|
7
|
+
const events = attempts.filter((attempt) => attempt.profileIndex === index);
|
|
8
|
+
const terminal = events
|
|
9
|
+
.filter((event) => event.stage !== 'health-gate' && event.stage !== 'health-update')
|
|
10
|
+
.at(-1);
|
|
11
|
+
const outcome = terminal?.skipReason === 'unreached'
|
|
12
|
+
? 'not reached'
|
|
13
|
+
: terminal?.outcome === 'success'
|
|
14
|
+
? 'succeeded'
|
|
15
|
+
: events.some((event) => event.outcome === 'skipped')
|
|
16
|
+
? 'suspended'
|
|
17
|
+
: events.length
|
|
18
|
+
? 'failed'
|
|
19
|
+
: 'not reached';
|
|
20
|
+
const reason = outcome === 'failed' ? terminal?.error ?? terminal?.failureKind : undefined;
|
|
21
|
+
const requests = events.filter((event) => event.attemptIndex !== undefined);
|
|
22
|
+
const retryAt = events.findLast((event) => event.healthDisposition === 'deny')?.retryAt;
|
|
23
|
+
const recovery = retryAt !== undefined && Number.isFinite(retryAt) && Math.abs(retryAt) <= 8.64e15
|
|
24
|
+
? `; next recovery attempt after ${new Date(retryAt).toISOString()}`
|
|
25
|
+
: '';
|
|
26
|
+
const healthUnavailable = events.some((event) => event.healthDisposition === 'fail-open' || (event.stage === 'health-update' && event.outcome === 'failure'));
|
|
27
|
+
const healthState = events.findLast((event) => event.stage === 'health-update' && event.outcome === 'success')?.healthState;
|
|
28
|
+
const details = [
|
|
29
|
+
reason ? ` — ${reason}` : '',
|
|
30
|
+
requests.length > 1 ? `; ${requests.length} provider attempts` : '',
|
|
31
|
+
outcome === 'suspended' ? recovery : '',
|
|
32
|
+
healthUnavailable ? '; reliability service unavailable; profile was tried normally' : '',
|
|
33
|
+
outcome !== 'suspended' && healthState === 'open' ? '; profile is suspended' : '',
|
|
34
|
+
healthState === 'half-open' ? '; recovery attempt in progress' : '',
|
|
35
|
+
].join('');
|
|
36
|
+
return `${index + 1}. ${profile.profileName || 'Classifier Profile'} (${profile.configuration.provider}/${profile.configuration.model}): ${outcome}${details}`;
|
|
37
|
+
})
|
|
38
|
+
.join('\n');
|
|
39
|
+
}
|
|
40
|
+
export class ClassifierProfileExhaustedError extends Error {
|
|
41
|
+
attempts;
|
|
42
|
+
summary;
|
|
43
|
+
statusCode;
|
|
44
|
+
constructor(attempts, summary, options, statusCode) {
|
|
45
|
+
const details = attempts
|
|
46
|
+
.filter((attempt) => attempt.outcome === 'failure' || attempt.outcome === 'aborted')
|
|
47
|
+
.map((attempt) => {
|
|
48
|
+
const profile = `Profile ${(attempt.profileIndex ?? 0) + 1}${attempt.profileName ? ` (${attempt.profileName})` : ''}`;
|
|
49
|
+
const request = attempt.attemptIndex === undefined ? '' : ` attempt ${attempt.attemptIndex + 1}`;
|
|
50
|
+
const status = attempt.status === undefined ? '' : ` (HTTP ${attempt.status})`;
|
|
51
|
+
const reason = attempt.error ? `: ${attempt.error.replace(/\r\n|\r|\n/g, '\n ')}` : '';
|
|
52
|
+
return `${profile}, ${attempt.failureKind ?? attempt.stage}${request} ${attempt.outcome}${status}${reason}`;
|
|
53
|
+
})
|
|
54
|
+
.join('\n');
|
|
55
|
+
super(`Classifier profile chain exhausted.\n${summary}${details ? `\n\nAttempt details:\n${details}` : ''}`, options);
|
|
56
|
+
this.attempts = attempts;
|
|
57
|
+
this.summary = summary;
|
|
58
|
+
this.statusCode = statusCode;
|
|
59
|
+
this.name = 'ClassifierProfileExhaustedError';
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
export async function runClassifierProfiles(input) {
|
|
63
|
+
const attempts = [];
|
|
64
|
+
const { context } = input;
|
|
65
|
+
let lastError;
|
|
66
|
+
let httpFailuresOnly = true;
|
|
67
|
+
let lastHttpStatus;
|
|
68
|
+
const record = (attempt) => {
|
|
69
|
+
const event = {
|
|
70
|
+
...attempt,
|
|
71
|
+
...(attempt.stage === 'health-update' && attempt.outcome === 'failure'
|
|
72
|
+
? { error: 'Classifier profile health service unavailable.' }
|
|
73
|
+
: {}),
|
|
74
|
+
family: 'classifier',
|
|
75
|
+
profileName: input.profiles[attempt.profileIndex ?? 0]?.profileName,
|
|
76
|
+
};
|
|
77
|
+
attempts.push(event);
|
|
78
|
+
try {
|
|
79
|
+
input.onAttempt(structuredClone(event));
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
/* Observation only. */
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
for (let profileIndex = 0; profileIndex < input.profiles.length; profileIndex++) {
|
|
86
|
+
context.signal.throwIfAborted();
|
|
87
|
+
if (Date.now() >= input.deadline) {
|
|
88
|
+
lastError = new ClassifierProviderError('Classifier overall deadline expired.', 'timeout');
|
|
89
|
+
const profile = input.profiles[profileIndex];
|
|
90
|
+
record({
|
|
91
|
+
roundIndex: 0,
|
|
92
|
+
profileIndex,
|
|
93
|
+
provider: profile.configuration.provider,
|
|
94
|
+
model: profile.configuration.model,
|
|
95
|
+
stage: 'request',
|
|
96
|
+
outcome: 'failure',
|
|
97
|
+
failureKind: 'timeout',
|
|
98
|
+
error: 'Classifier overall deadline expired.',
|
|
99
|
+
});
|
|
100
|
+
httpFailuresOnly = false;
|
|
101
|
+
break;
|
|
102
|
+
}
|
|
103
|
+
const profile = input.profiles[profileIndex];
|
|
104
|
+
const provider = getClassifierProvider(profile.configuration.provider);
|
|
105
|
+
const model = profile.configuration.model;
|
|
106
|
+
const policy = classifierProfileHealthPolicy(profile.configuration);
|
|
107
|
+
const store = context.llmProfileHealthStore;
|
|
108
|
+
const health = policy && store && context.project?.metadata.id
|
|
109
|
+
? { policy, identity: classifierProfileHealthIdentity(profile, context.project.metadata.id, input.nodeId) }
|
|
110
|
+
: undefined;
|
|
111
|
+
const base = { roundIndex: 0, profileIndex, provider: provider.id, model, profileHealthKey: health?.identity.key };
|
|
112
|
+
let observedRequest = false;
|
|
113
|
+
let observedAbort = false;
|
|
114
|
+
let lastPhysicalFailure;
|
|
115
|
+
let permit;
|
|
116
|
+
if (health && store) {
|
|
117
|
+
try {
|
|
118
|
+
const begin = await runBoundedHealthOperation({
|
|
119
|
+
operation: 'begin',
|
|
120
|
+
timeoutMs: Math.max(1, Math.min(2000, input.deadline - Date.now())),
|
|
121
|
+
signal: context.signal,
|
|
122
|
+
run: () => store.begin(health),
|
|
123
|
+
onLateResolve: async (late) => {
|
|
124
|
+
if (late.disposition === 'allow' && late.permitId)
|
|
125
|
+
await store.finish({ ...health, permitId: late.permitId, outcome: 'ignored' });
|
|
126
|
+
},
|
|
127
|
+
});
|
|
128
|
+
if (begin.disposition === 'deny') {
|
|
129
|
+
record({
|
|
130
|
+
...base,
|
|
131
|
+
stage: 'health-gate',
|
|
132
|
+
outcome: 'skipped',
|
|
133
|
+
healthDisposition: 'deny',
|
|
134
|
+
healthState: begin.state,
|
|
135
|
+
retryAt: begin.retryAt,
|
|
136
|
+
error: 'Classifier profile is suspended.',
|
|
137
|
+
});
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
if (!begin.permitId)
|
|
141
|
+
throw new Error('Profile health service did not return a permit.');
|
|
142
|
+
record({
|
|
143
|
+
...base,
|
|
144
|
+
stage: 'health-gate',
|
|
145
|
+
outcome: 'success',
|
|
146
|
+
healthDisposition: 'allow',
|
|
147
|
+
healthState: begin.state,
|
|
148
|
+
});
|
|
149
|
+
permit = createProfileHealthPermit({
|
|
150
|
+
candidate: { ...base, health },
|
|
151
|
+
healthStore: store,
|
|
152
|
+
permitId: begin.permitId,
|
|
153
|
+
state: begin.state,
|
|
154
|
+
roundIndex: 0,
|
|
155
|
+
profileIndex,
|
|
156
|
+
operationTimeoutMs: 2000,
|
|
157
|
+
executionCorrelationId: context.llmProfileHealthExecutionCorrelationId,
|
|
158
|
+
signal: context.signal,
|
|
159
|
+
recordAttempt: record,
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
context.signal.throwIfAborted();
|
|
164
|
+
record({
|
|
165
|
+
...base,
|
|
166
|
+
stage: 'health-gate',
|
|
167
|
+
outcome: 'failure',
|
|
168
|
+
healthDisposition: 'fail-open',
|
|
169
|
+
error: 'Classifier profile health service unavailable.',
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
try {
|
|
174
|
+
context.signal.throwIfAborted();
|
|
175
|
+
if (!provider.browserExecutionSupported && context.executor === 'browser')
|
|
176
|
+
throw new ClassifierProviderError('Classifier provider requires the Node executor.', 'capability');
|
|
177
|
+
if (!profile.credential.value?.trim())
|
|
178
|
+
throw new ClassifierProviderError('Classifier Profile API key is not set.', 'configuration');
|
|
179
|
+
const remainingMs = input.deadline - Date.now();
|
|
180
|
+
// Match LLM profiles: suspension deadlines require enabled, host-backed health.
|
|
181
|
+
const timeoutMs = health
|
|
182
|
+
? Math.min(classifierProfileResponseTimeout(profile.configuration), remainingMs)
|
|
183
|
+
: remainingMs;
|
|
184
|
+
if (timeoutMs <= 0)
|
|
185
|
+
throw new ClassifierProviderError('Classifier overall deadline expired.', 'timeout');
|
|
186
|
+
const result = await provider.evaluate({
|
|
187
|
+
...input.state,
|
|
188
|
+
questions: input.questions,
|
|
189
|
+
apiKey: profile.credential.value,
|
|
190
|
+
model,
|
|
191
|
+
timeoutMs,
|
|
192
|
+
deadline: input.deadline,
|
|
193
|
+
signal: context.signal,
|
|
194
|
+
retryOnNon200: input.retryOnNon200,
|
|
195
|
+
retryOnNon200RepeatTimes: input.retryOnNon200RepeatTimes,
|
|
196
|
+
retryOnNon200CooldownMs: input.retryOnNon200CooldownMs,
|
|
197
|
+
onRequestBody: input.onRequestBody,
|
|
198
|
+
onResponseBody: input.onResponseBody,
|
|
199
|
+
onAttempt: ({ kind, ...attempt }) => {
|
|
200
|
+
observedRequest = true;
|
|
201
|
+
observedAbort = attempt.outcome === 'aborted';
|
|
202
|
+
lastPhysicalFailure = attempt.outcome === 'failure' ? { kind, status: attempt.status } : undefined;
|
|
203
|
+
record({
|
|
204
|
+
...base,
|
|
205
|
+
...attempt,
|
|
206
|
+
stage: kind === 'response-validation' || kind === 'response-parsing' ? 'response-validation' : 'request',
|
|
207
|
+
failureKind: kind ? classifierFailureKind(kind, attempt.status) : undefined,
|
|
208
|
+
timeoutKind: kind === 'timeout' && health ? 'response' : undefined,
|
|
209
|
+
});
|
|
210
|
+
},
|
|
211
|
+
});
|
|
212
|
+
context.signal.throwIfAborted();
|
|
213
|
+
if (Date.now() >= input.deadline)
|
|
214
|
+
throw new ClassifierProviderError('Classifier overall deadline expired.', 'timeout');
|
|
215
|
+
await permit?.finish('healthy');
|
|
216
|
+
context.signal.throwIfAborted();
|
|
217
|
+
if (Date.now() >= input.deadline)
|
|
218
|
+
throw new ClassifierProviderError('Classifier overall deadline expired.', 'timeout');
|
|
219
|
+
for (let unreached = profileIndex + 1; unreached < input.profiles.length; unreached++) {
|
|
220
|
+
const candidate = input.profiles[unreached];
|
|
221
|
+
record({
|
|
222
|
+
roundIndex: 0,
|
|
223
|
+
profileIndex: unreached,
|
|
224
|
+
provider: candidate.configuration.provider,
|
|
225
|
+
model: candidate.configuration.model,
|
|
226
|
+
stage: 'configuration',
|
|
227
|
+
outcome: 'skipped',
|
|
228
|
+
skipReason: 'unreached',
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
return { result, provider, model };
|
|
232
|
+
}
|
|
233
|
+
catch (error) {
|
|
234
|
+
lastError = error;
|
|
235
|
+
const providerError = error instanceof ClassifierProviderError ? error : undefined;
|
|
236
|
+
const httpFailure = providerError?.kind === 'http' &&
|
|
237
|
+
providerError.statusCode !== undefined &&
|
|
238
|
+
(providerError.statusCode < 200 || providerError.statusCode >= 300);
|
|
239
|
+
httpFailuresOnly &&= httpFailure;
|
|
240
|
+
if (httpFailure)
|
|
241
|
+
lastHttpStatus = providerError.statusCode;
|
|
242
|
+
const alreadyReported = (context.signal.aborted && observedAbort) ||
|
|
243
|
+
(providerError &&
|
|
244
|
+
lastPhysicalFailure?.kind === providerError.kind &&
|
|
245
|
+
(providerError.kind !== 'http' || lastPhysicalFailure.status === providerError.statusCode));
|
|
246
|
+
if (!alreadyReported)
|
|
247
|
+
record({
|
|
248
|
+
...base,
|
|
249
|
+
stage: providerError
|
|
250
|
+
? providerError.kind === 'configuration' || providerError.kind === 'capability'
|
|
251
|
+
? 'configuration'
|
|
252
|
+
: providerError.kind === 'response-validation' || providerError.kind === 'response-parsing'
|
|
253
|
+
? 'response-validation'
|
|
254
|
+
: 'request'
|
|
255
|
+
: 'configuration',
|
|
256
|
+
failureKind: context.signal.aborted
|
|
257
|
+
? undefined
|
|
258
|
+
: providerError
|
|
259
|
+
? classifierFailureKind(providerError.kind, providerError.statusCode)
|
|
260
|
+
: 'configuration',
|
|
261
|
+
outcome: context.signal.aborted ? 'aborted' : 'failure',
|
|
262
|
+
status: providerError?.statusCode,
|
|
263
|
+
error: classifierErrorMessage(error, profile.credential.value),
|
|
264
|
+
timeoutKind: !context.signal.aborted && providerError?.kind === 'timeout' && health ? 'response' : undefined,
|
|
265
|
+
});
|
|
266
|
+
const unhealthy = providerError?.kind === 'timeout' ||
|
|
267
|
+
providerError?.kind === 'transport' ||
|
|
268
|
+
(providerError?.kind === 'http' &&
|
|
269
|
+
(providerError.statusCode === 408 ||
|
|
270
|
+
providerError.statusCode === 429 ||
|
|
271
|
+
(providerError.statusCode ?? 0) >= 500));
|
|
272
|
+
await permit?.finish(!context.signal.aborted && observedRequest && unhealthy ? 'unhealthy' : 'ignored');
|
|
273
|
+
context.signal.throwIfAborted();
|
|
274
|
+
if (Date.now() >= input.deadline) {
|
|
275
|
+
httpFailuresOnly = false;
|
|
276
|
+
lastError = new ClassifierProviderError('Classifier overall deadline expired.', 'timeout', undefined, {
|
|
277
|
+
cause: error,
|
|
278
|
+
});
|
|
279
|
+
if (providerError?.kind !== 'timeout')
|
|
280
|
+
record({
|
|
281
|
+
...base,
|
|
282
|
+
stage: 'request',
|
|
283
|
+
outcome: 'failure',
|
|
284
|
+
error: 'Classifier overall deadline expired.',
|
|
285
|
+
failureKind: 'timeout',
|
|
286
|
+
});
|
|
287
|
+
break;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
// Classify terminal candidate failures, not discarded physical retries or
|
|
292
|
+
// observability events. The final cause alone cannot describe a mixed chain.
|
|
293
|
+
throw new ClassifierProfileExhaustedError(attempts, classifierProfileSummary(input.profiles, attempts), { cause: lastError }, httpFailuresOnly ? lastHttpStatus : undefined);
|
|
294
|
+
}
|