@valerypopoff/rivet2-core 2.15.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 +7906 -3980
- package/dist/cjs/bundle.cjs.map +4 -4
- package/dist/cjs/interpolationRuntime.cjs +62 -7
- package/dist/cjs/interpolationRuntime.cjs.map +3 -3
- package/dist/cjs/interpolationSyntax.cjs +9 -5
- package/dist/cjs/interpolationSyntax.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/createProcessor.js +5 -2
- package/dist/esm/api/processSettings.js +1 -0
- package/dist/esm/exports.js +4 -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/GraphBoundaryCache.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 +825 -884
- package/dist/esm/model/GraphSchedulerBoundaryState.js +64 -0
- package/dist/esm/model/Nodes.js +15 -0
- package/dist/esm/model/ProjectBundle.js +248 -0
- package/dist/esm/model/ProjectBundleRuntime.js +54 -0
- package/dist/esm/model/SchedulerBoundaryPlanner.js +233 -0
- package/dist/esm/model/SplitRunProcessor.js +28 -7
- package/dist/esm/model/StreamingWatchTopology.js +118 -8
- package/dist/esm/model/SubgraphProjectTarget.js +7 -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 +22 -17
- 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 +24 -9
- 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 +26 -1
- package/dist/esm/model/chat-v2/chatV2Shared.js +2 -1
- package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +10 -0
- package/dist/esm/model/chat-v2/llmChatV2Body.js +13 -10
- package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +5 -2
- package/dist/esm/model/chat-v2/llmChatV2NodeData.js +3 -0
- package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +33 -9
- package/dist/esm/model/chat-v2/llmChatV2NodeMigration.js +22 -2
- 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 +5 -1
- package/dist/esm/model/chat-v2/llmProfileBody.js +11 -2
- package/dist/esm/model/chat-v2/llmProfileFallback.js +7 -4
- package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +2 -1
- package/dist/esm/model/chat-v2/llmProfileHealthStore.js +16 -3
- package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +1 -1
- 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/chat-v2/temperature.js +9 -0
- package/dist/esm/model/classifier/credentials.js +42 -6
- package/dist/esm/model/classifier/images.js +176 -0
- package/dist/esm/model/classifier/json.js +57 -0
- package/dist/esm/model/classifier/limits.js +300 -0
- package/dist/esm/model/classifier/openai.js +118 -0
- package/dist/esm/model/classifier/perplexity.js +63 -0
- package/dist/esm/model/classifier/preparation.js +74 -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 +454 -192
- package/dist/esm/model/classifier/questionHelpers.js +29 -45
- package/dist/esm/model/classifier/questions.js +53 -0
- package/dist/esm/model/classifier/response.js +75 -0
- package/dist/esm/model/classifier/state.js +207 -0
- package/dist/esm/model/classifier/types.js +11 -1
- package/dist/esm/model/nodeRunFailure.js +54 -0
- package/dist/esm/model/nodes/CallGraphNode.js +6 -0
- package/dist/esm/model/nodes/CatchStreamingChunksNode.js +42 -0
- package/dist/esm/model/nodes/ClassifierEvaluateNode.js +385 -154
- package/dist/esm/model/nodes/ClassifierProfileNode.js +133 -0
- package/dist/esm/model/nodes/ClassifierQuestionNode.js +59 -15
- package/dist/esm/model/nodes/DelegateFunctionCallNode.js +1 -1
- package/dist/esm/model/nodes/GetGlobalNode.js +2 -2
- package/dist/esm/model/nodes/HttpCallNode.js +44 -75
- package/dist/esm/model/nodes/ImageNode.js +44 -3
- package/dist/esm/model/nodes/LLMChatV2Node.js +26 -4
- package/dist/esm/model/nodes/ObjectNode.js +29 -18
- package/dist/esm/model/nodes/PromptNode.js +2 -1
- package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +4 -1
- package/dist/esm/model/nodes/SetGlobalNode.js +5 -3
- package/dist/esm/model/nodes/StopWatchingStreamingOutputNode.js +8 -8
- package/dist/esm/model/nodes/StreamValueNode.js +38 -0
- package/dist/esm/model/nodes/SubGraphNode.js +199 -35
- package/dist/esm/model/nodes/ToBase64Node.js +106 -0
- package/dist/esm/model/nodes/WatchStreamingOutputNode.js +7 -7
- package/dist/esm/model/nodes/toolCallDelegation.js +5 -1
- package/dist/esm/model/profileSuspensionHints.js +8 -0
- package/dist/esm/recording/ExecutionRecorder.js +26 -0
- package/dist/esm/serialization.js +2 -0
- package/dist/esm/utils/base64.js +18 -15
- package/dist/esm/utils/coerceType.js +11 -1
- package/dist/esm/utils/errors.js +41 -0
- package/dist/esm/utils/interpolation.js +44 -22
- package/dist/esm/utils/interpolationSyntax.js +15 -6
- package/dist/esm/utils/serialization/serialization.js +3 -2
- package/dist/esm/utils/serialization/serializationUtils.js +6 -0
- package/dist/esm/utils/serialization/serialization_v4.js +15 -3
- package/dist/esm/webAppRuntime.js +1 -0
- package/dist/types/api/createProcessor.d.ts +7 -1
- package/dist/types/exports.d.ts +4 -0
- package/dist/types/model/AgentResponseTrace.d.ts +15 -4
- package/dist/types/model/AgentResponseTracePresentation.d.ts +15 -0
- package/dist/types/model/CycleDetector.d.ts +1 -2
- package/dist/types/model/DataValue.d.ts +12 -8
- package/dist/types/model/ExecutorProtocol.d.ts +9 -0
- package/dist/types/model/GraphBoundaryCache.d.ts +2 -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 +2 -0
- package/dist/types/model/GraphSchedulerBoundaryState.d.ts +96 -0
- package/dist/types/model/Nodes.d.ts +11 -4
- package/dist/types/model/ProcessContext.d.ts +24 -3
- package/dist/types/model/ProjectBundle.d.ts +59 -0
- package/dist/types/model/ProjectBundleRuntime.d.ts +24 -0
- package/dist/types/model/ProjectReferenceLoader.d.ts +3 -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/StreamingWatchTopology.d.ts +11 -1
- package/dist/types/model/SubgraphProjectTarget.d.ts +38 -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/chatV2Shared.d.ts +1 -1
- package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +2 -0
- package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +4 -1
- package/dist/types/model/chat-v2/llmChatV2NodeMigration.d.ts +3 -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 +10 -7
- 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/chat-v2/temperature.d.ts +2 -0
- package/dist/types/model/classifier/credentials.d.ts +7 -1
- package/dist/types/model/classifier/images.d.ts +18 -0
- package/dist/types/model/classifier/json.d.ts +19 -0
- package/dist/types/model/classifier/limits.d.ts +45 -0
- package/dist/types/model/classifier/openai.d.ts +5 -0
- package/dist/types/model/classifier/perplexity.d.ts +7 -0
- package/dist/types/model/classifier/preparation.d.ts +16 -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 +98 -9
- package/dist/types/model/classifier/questionHelpers.d.ts +6 -4
- package/dist/types/model/classifier/questions.d.ts +4 -0
- package/dist/types/model/classifier/response.d.ts +4 -0
- package/dist/types/model/classifier/state.d.ts +37 -0
- package/dist/types/model/classifier/types.d.ts +11 -0
- package/dist/types/model/nodeRunFailure.d.ts +13 -0
- package/dist/types/model/nodes/CatchStreamingChunksNode.d.ts +20 -0
- package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +17 -12
- package/dist/types/model/nodes/ClassifierProfileNode.d.ts +20 -0
- package/dist/types/model/nodes/GetGlobalNode.d.ts +7 -0
- package/dist/types/model/nodes/ImageNode.d.ts +4 -0
- package/dist/types/model/nodes/LLMChatV2Node.d.ts +1 -0
- package/dist/types/model/nodes/ObjectNode.d.ts +2 -1
- package/dist/types/model/nodes/StreamValueNode.d.ts +14 -0
- package/dist/types/model/nodes/SubGraphNode.d.ts +21 -2
- package/dist/types/model/nodes/ToBase64Node.d.ts +12 -0
- package/dist/types/model/nodes/toolCallDelegation.d.ts +3 -1
- package/dist/types/model/profileSuspensionHints.d.ts +8 -0
- package/dist/types/recording/ExecutionRecorder.d.ts +8 -2
- package/dist/types/serialization.d.ts +2 -0
- package/dist/types/utils/base64.d.ts +1 -1
- package/dist/types/utils/errors.d.ts +4 -0
- package/dist/types/utils/interpolation.d.ts +13 -2
- package/dist/types/utils/interpolationSyntax.d.ts +1 -1
- package/dist/types/utils/serialization/serialization.d.ts +3 -1
- package/dist/types/utils/serialization/serializationUtils.d.ts +1 -0
- package/dist/types/webAppRuntime.d.ts +1 -0
- package/package.json +7 -1
|
@@ -1,12 +1,31 @@
|
|
|
1
|
-
import { JEV_DEFAULT_CREDENTIAL_NAMES } from './credentials.js';
|
|
1
|
+
import { JEV_DEFAULT_CREDENTIAL_NAMES, LIQUID_DEFAULT_CREDENTIAL_NAMES, OPENAI_DEFAULT_CREDENTIAL_NAMES, OPENROUTER_DEFAULT_CREDENTIAL_NAMES, PERPLEXITY_DEFAULT_CREDENTIAL_NAMES, } from './credentials.js';
|
|
2
|
+
import { assertLiquidImageLimits } from './images.js';
|
|
3
|
+
import { prepareClassifierState, systemOneState, } from './state.js';
|
|
4
|
+
import { validateClassifierEvaluationResponse } from './response.js';
|
|
5
|
+
import { createOpenAIDecisionRequest, validateOpenAIDecisionResponse } from './openai.js';
|
|
6
|
+
import { assertPerplexityDecisionLimits, perplexityDecisionState, PERPLEXITY_DECISION_MODELS } from './perplexity.js';
|
|
7
|
+
import { prepareClassifierQuestion } from './questions.js';
|
|
8
|
+
import { classifierArrayValues } from './json.js';
|
|
9
|
+
import { assertClassifierResourceLimits, ClassifierValueBudget, CLASSIFIER_LIMITS, ClassifierResourceLimitError, ClassifierResponseReadError, readClassifierResponse, } from './limits.js';
|
|
10
|
+
export { validateApiCompatibleClassifierResponse } from './response.js';
|
|
2
11
|
export const JEV_SYSTEM_ONE_ENDPOINT = 'https://api.typesafe.ai/v1/systemone';
|
|
12
|
+
export const LIQUID_SYSTEM_ONE_ENDPOINT = 'https://api.liquid.ai/decisions/v1/systemone';
|
|
13
|
+
export const OPENAI_DECISIONS_ENDPOINT = 'https://api.openai.com/v1/decisions';
|
|
14
|
+
export const OPENROUTER_DECISIONS_ENDPOINT = 'https://openrouter.ai/api/alpha/decisions';
|
|
15
|
+
export const PERPLEXITY_DECISIONS_ENDPOINT = 'https://api.perplexity.ai/v1/decisions';
|
|
3
16
|
/** Jev's published USD rates. Keep this Core-owned rather than graph-authored. */
|
|
4
17
|
export const JEV_TOKEN_PRICING = {
|
|
5
18
|
inputPerMillionTokens: 0.042,
|
|
6
19
|
outputPerMillionTokens: 0,
|
|
7
20
|
};
|
|
21
|
+
/** Liquid d1's published USD rates: https://www.liquid.ai/blog/d1-decision-model */
|
|
22
|
+
export const LIQUID_TOKEN_PRICING = {
|
|
23
|
+
inputPerMillionTokens: 0.04,
|
|
24
|
+
outputPerMillionTokens: 0,
|
|
25
|
+
};
|
|
8
26
|
const TOKENS_PER_MILLION = 1_000_000;
|
|
9
27
|
const MAX_AUTOMATIC_ATTEMPTS = 3;
|
|
28
|
+
const MAX_TIMER_DELAY_MS = 2_147_483_647;
|
|
10
29
|
const RETRYABLE_STATUSES = new Set([429, 529]);
|
|
11
30
|
export const DEFAULT_CLASSIFIER_RETRY_ON_NON_200_REPEAT_TIMES = 1;
|
|
12
31
|
export const DEFAULT_CLASSIFIER_RETRY_ON_NON_200_COOLDOWN_MS = 0;
|
|
@@ -16,34 +35,16 @@ export const DEFAULT_CLASSIFIER_RETRY_ON_NON_200_COOLDOWN_MS = 0;
|
|
|
16
35
|
* to which compatible provider is selected.
|
|
17
36
|
*/
|
|
18
37
|
export function createApiCompatibleClassifierProvider(config) {
|
|
19
|
-
return {
|
|
20
|
-
|
|
21
|
-
label: config.label,
|
|
22
|
-
defaultModel: config.defaultModel,
|
|
23
|
-
credentialNames: config.credentialNames,
|
|
38
|
+
return createClassifierProvider({
|
|
39
|
+
...config,
|
|
24
40
|
browserExecutionSupported: config.browserExecutionSupported ?? false,
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
return await callApiCompatibleClassifier({
|
|
33
|
-
apiKey,
|
|
34
|
-
endpoint: config.endpoint,
|
|
35
|
-
fetchImplementation,
|
|
36
|
-
providerLabel: config.label,
|
|
37
|
-
questions,
|
|
38
|
-
request,
|
|
39
|
-
retryOnNon200,
|
|
40
|
-
retryOnNon200CooldownMs,
|
|
41
|
-
retryOnNon200RepeatTimes,
|
|
42
|
-
signal,
|
|
43
|
-
timeoutMs,
|
|
44
|
-
});
|
|
45
|
-
},
|
|
46
|
-
};
|
|
41
|
+
buildRequest: ({ model, questions, state }) => ({
|
|
42
|
+
...systemOneState(state.kind === 'json' ? { state: state.value } : { state: '', stateMessages: state.messages }),
|
|
43
|
+
model,
|
|
44
|
+
questions: createQuestionMap(questions),
|
|
45
|
+
}),
|
|
46
|
+
validateResponse: validateClassifierEvaluationResponse,
|
|
47
|
+
});
|
|
47
48
|
}
|
|
48
49
|
export const jevClassifierProvider = createApiCompatibleClassifierProvider({
|
|
49
50
|
id: 'jev',
|
|
@@ -51,10 +52,191 @@ export const jevClassifierProvider = createApiCompatibleClassifierProvider({
|
|
|
51
52
|
defaultModel: 'jev-latest',
|
|
52
53
|
credentialNames: JEV_DEFAULT_CREDENTIAL_NAMES,
|
|
53
54
|
endpoint: JEV_SYSTEM_ONE_ENDPOINT,
|
|
54
|
-
pricing: JEV_TOKEN_PRICING,
|
|
55
|
+
modelPricing: [{ models: ['jev-latest', 'jev-preview', 'jev-1.13.0'], pricing: JEV_TOKEN_PRICING }],
|
|
56
|
+
});
|
|
57
|
+
export const liquidClassifierProvider = createApiCompatibleClassifierProvider({
|
|
58
|
+
id: 'liquid',
|
|
59
|
+
label: 'Liquid AI',
|
|
60
|
+
defaultModel: 'd1',
|
|
61
|
+
credentialNames: LIQUID_DEFAULT_CREDENTIAL_NAMES,
|
|
62
|
+
endpoint: LIQUID_SYSTEM_ONE_ENDPOINT,
|
|
63
|
+
modelPricing: [{ models: ['d1'], pricing: LIQUID_TOKEN_PRICING }],
|
|
64
|
+
supportsImages: (model) => model === 'd1',
|
|
65
|
+
maxRequestBytes: 4_500_000,
|
|
66
|
+
checkState: (state, check) => {
|
|
67
|
+
if (state.kind === 'messages')
|
|
68
|
+
assertLiquidImageLimits(state.images, check);
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
/** Native Decisions API, not chat completions. Microsoft Decision-1 is text-only.
|
|
72
|
+
* https://openrouter.ai/microsoft/microsoft-decision-1
|
|
73
|
+
*/
|
|
74
|
+
export const openrouterClassifierProvider = createApiCompatibleClassifierProvider({
|
|
75
|
+
id: 'openrouter',
|
|
76
|
+
label: 'OpenRouter',
|
|
77
|
+
defaultModel: 'microsoft/microsoft-decision-1',
|
|
78
|
+
credentialNames: OPENROUTER_DEFAULT_CREDENTIAL_NAMES,
|
|
79
|
+
endpoint: OPENROUTER_DECISIONS_ENDPOINT,
|
|
80
|
+
modelPricing: [
|
|
81
|
+
{
|
|
82
|
+
models: ['microsoft/microsoft-decision-1'],
|
|
83
|
+
pricing: { inputPerMillionTokens: 0.042, outputPerMillionTokens: 0 },
|
|
84
|
+
},
|
|
85
|
+
],
|
|
86
|
+
});
|
|
87
|
+
/** Decisions-specific rates, not GPT-6 Luna's Chat/Responses cache/output rates.
|
|
88
|
+
* https://developers.openai.com/api/docs/guides/decisions#pricing-and-availability
|
|
89
|
+
*/
|
|
90
|
+
export const openaiClassifierProvider = createClassifierProvider({
|
|
91
|
+
id: 'openai',
|
|
92
|
+
label: 'OpenAI',
|
|
93
|
+
defaultModel: 'gpt-6-luna',
|
|
94
|
+
credentialNames: OPENAI_DEFAULT_CREDENTIAL_NAMES,
|
|
95
|
+
browserExecutionSupported: false,
|
|
96
|
+
endpoint: OPENAI_DECISIONS_ENDPOINT,
|
|
97
|
+
supportsImages: (model) => model === 'gpt-6-luna',
|
|
98
|
+
modelPricing: [
|
|
99
|
+
{
|
|
100
|
+
models: ['gpt-6-luna'],
|
|
101
|
+
pricing: {
|
|
102
|
+
inputPerMillionTokens: 0.1,
|
|
103
|
+
outputPerMillionTokens: 0,
|
|
104
|
+
longContext: { aboveInputTokens: 272_000, inputPerMillionTokens: 0.2, outputPerMillionTokens: 0 },
|
|
105
|
+
},
|
|
106
|
+
},
|
|
107
|
+
],
|
|
108
|
+
buildRequest: createOpenAIDecisionRequest,
|
|
109
|
+
validateResponse: validateOpenAIDecisionResponse,
|
|
110
|
+
});
|
|
111
|
+
/** https://docs.perplexity.ai/docs/decisions/quickstart */
|
|
112
|
+
export const perplexityClassifierProvider = createClassifierProvider({
|
|
113
|
+
id: 'perplexity',
|
|
114
|
+
label: 'Perplexity',
|
|
115
|
+
defaultModel: 'pplx-decider-v1.1-27b',
|
|
116
|
+
credentialNames: PERPLEXITY_DEFAULT_CREDENTIAL_NAMES,
|
|
117
|
+
browserExecutionSupported: false,
|
|
118
|
+
endpoint: PERPLEXITY_DECISIONS_ENDPOINT,
|
|
119
|
+
supportsImages: (model) => PERPLEXITY_DECISION_MODELS.includes(model),
|
|
120
|
+
modelPricing: [
|
|
121
|
+
{
|
|
122
|
+
models: PERPLEXITY_DECISION_MODELS,
|
|
123
|
+
pricing: { inputPerMillionTokens: 0.02, outputPerMillionTokens: 0 },
|
|
124
|
+
},
|
|
125
|
+
],
|
|
126
|
+
checkRequest: assertPerplexityDecisionLimits,
|
|
127
|
+
buildRequest: ({ model, state, questions }) => ({
|
|
128
|
+
model,
|
|
129
|
+
state: perplexityDecisionState(state),
|
|
130
|
+
questions: createQuestionMap(questions),
|
|
131
|
+
}),
|
|
132
|
+
validateResponse: validateClassifierEvaluationResponse,
|
|
55
133
|
});
|
|
56
|
-
/** Ordered so adding
|
|
57
|
-
export const classifierProviders = [
|
|
134
|
+
/** Ordered so adding compatible providers does not alter authored IDs. */
|
|
135
|
+
export const classifierProviders = [
|
|
136
|
+
jevClassifierProvider,
|
|
137
|
+
liquidClassifierProvider,
|
|
138
|
+
openaiClassifierProvider,
|
|
139
|
+
openrouterClassifierProvider,
|
|
140
|
+
perplexityClassifierProvider,
|
|
141
|
+
];
|
|
142
|
+
export class ClassifierProviderError extends Error {
|
|
143
|
+
kind;
|
|
144
|
+
statusCode;
|
|
145
|
+
constructor(message, kind, statusCode, options) {
|
|
146
|
+
super(message, options);
|
|
147
|
+
this.kind = kind;
|
|
148
|
+
this.statusCode = statusCode;
|
|
149
|
+
this.name = 'ClassifierProviderError';
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
export function classifierFailureKind(kind, status) {
|
|
153
|
+
return kind === 'http' && (status === 401 || status === 403) ? 'authentication' : kind;
|
|
154
|
+
}
|
|
155
|
+
/** Bounded preparation/provider explanation, without traversing causes or capturing response bodies. */
|
|
156
|
+
export function classifierErrorMessage(error, apiKey) {
|
|
157
|
+
try {
|
|
158
|
+
const text = error instanceof Error ? error.message : typeof error === 'string' ? error : 'Classifier request failed.';
|
|
159
|
+
return (apiKey ? text.split(apiKey).join('[redacted]') : text).slice(0, 2000);
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
return 'Classifier request failed with unreadable error metadata.';
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
function createOperation(args, label) {
|
|
166
|
+
if (!Number.isFinite(args.timeoutMs) ||
|
|
167
|
+
args.timeoutMs <= 0 ||
|
|
168
|
+
(args.deadline !== undefined && !Number.isFinite(args.deadline)))
|
|
169
|
+
throw new Error('Classifier timeout and deadline must be finite, with a positive timeout.');
|
|
170
|
+
const now = Date.now();
|
|
171
|
+
const deadline = Math.min(now + args.timeoutMs, args.deadline ?? Infinity);
|
|
172
|
+
// Node turns overflowing setTimeout delays into 1 ms, not a long timeout.
|
|
173
|
+
if (deadline - now > MAX_TIMER_DELAY_MS)
|
|
174
|
+
throw new Error(`Classifier effective timeout must not exceed ${MAX_TIMER_DELAY_MS} ms.`);
|
|
175
|
+
const timeoutError = () => new ClassifierProviderError(`${label} request timed out after ${args.timeoutMs} ms.`, 'timeout');
|
|
176
|
+
return {
|
|
177
|
+
signal: args.signal,
|
|
178
|
+
deadline,
|
|
179
|
+
check(attemptSignal) {
|
|
180
|
+
throwIfAborted(args.signal, label);
|
|
181
|
+
if (Date.now() >= deadline || attemptSignal?.aborted)
|
|
182
|
+
throw timeoutError();
|
|
183
|
+
},
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
/** A plain specification and one runner for both graph and direct provider inputs. */
|
|
187
|
+
function createClassifierProvider(spec) {
|
|
188
|
+
const { endpoint, buildRequest, validateResponse, checkState, checkRequest, ...provider } = spec;
|
|
189
|
+
const evaluate = async (input) => {
|
|
190
|
+
// Reject removed evidence fields before object spread can read a getter or
|
|
191
|
+
// discard non-enumerable/inherited content.
|
|
192
|
+
if ('images' in input)
|
|
193
|
+
throw new Error('Pass image evidence through State, not a separate images field.');
|
|
194
|
+
const args = { ...input, fetchImplementation: input.fetchImplementation ?? fetch };
|
|
195
|
+
const operation = createOperation(args, provider.label);
|
|
196
|
+
operation.check();
|
|
197
|
+
if (typeof args.model !== 'string')
|
|
198
|
+
throw new Error('Classifier model must be a nonblank string.');
|
|
199
|
+
const budget = new ClassifierValueBudget(operation.check, provider.maxRequestBytes);
|
|
200
|
+
budget.inspect(args.model);
|
|
201
|
+
if (args.model.trim() === '')
|
|
202
|
+
throw new Error('Classifier model must be a nonblank string.');
|
|
203
|
+
if (typeof args.apiKey !== 'string' || args.apiKey.trim() === '' || /[\r\n]/.test(args.apiKey))
|
|
204
|
+
throw new Error('Classifier API key must be a nonblank string without line breaks.');
|
|
205
|
+
if (!Array.isArray(args.questions) || args.questions.length === 0)
|
|
206
|
+
throw new Error('Classifier Evaluate requires at least one question.');
|
|
207
|
+
if (args.questions.length > CLASSIFIER_LIMITS.questions)
|
|
208
|
+
throw new Error('Classifier Evaluate supports at most 1000 questions.');
|
|
209
|
+
const state = prepareClassifierState(args, budget);
|
|
210
|
+
const questions = [];
|
|
211
|
+
const ids = new Set();
|
|
212
|
+
for (const value of classifierArrayValues(args.questions, 'Questions')) {
|
|
213
|
+
const question = prepareClassifierQuestion(value, budget);
|
|
214
|
+
if (ids.has(question.questionId))
|
|
215
|
+
throw new Error(`Question ID '${question.questionId}' is duplicated in this evaluation.`);
|
|
216
|
+
ids.add(question.questionId);
|
|
217
|
+
questions.push(question);
|
|
218
|
+
}
|
|
219
|
+
if (state.kind === 'messages' && state.images.length && !provider.supportsImages?.(args.model))
|
|
220
|
+
throw new ClassifierProviderError(`${provider.label} model '${args.model}' does not support classifier images.`, 'capability');
|
|
221
|
+
try {
|
|
222
|
+
checkState?.(state, operation.check);
|
|
223
|
+
checkRequest?.({ model: args.model, state, questions }, operation.check);
|
|
224
|
+
}
|
|
225
|
+
catch (error) {
|
|
226
|
+
operation.check();
|
|
227
|
+
throw new ClassifierProviderError(error instanceof Error ? error.message : `${provider.label} does not support this classifier evidence.`, 'capability', undefined, { cause: error });
|
|
228
|
+
}
|
|
229
|
+
operation.check();
|
|
230
|
+
const result = await callClassifierHttp(args, { ...provider, endpoint, validateResponse }, { model: args.model, state, questions }, buildRequest, operation);
|
|
231
|
+
operation.check();
|
|
232
|
+
return result;
|
|
233
|
+
};
|
|
234
|
+
return { ...provider, evaluate, evaluateInput: evaluate };
|
|
235
|
+
}
|
|
236
|
+
function normalizeModelPricing(provider) {
|
|
237
|
+
return (provider.modelPricing ??
|
|
238
|
+
(provider.pricing && provider.defaultModel ? [{ models: [provider.defaultModel], pricing: provider.pricing }] : []));
|
|
239
|
+
}
|
|
58
240
|
export function getClassifierProvider(id) {
|
|
59
241
|
const provider = classifierProviders.find((candidate) => candidate.id === (id || jevClassifierProvider.id));
|
|
60
242
|
if (!provider)
|
|
@@ -65,23 +247,34 @@ export function getClassifierProviderEnvironmentVariableNames() {
|
|
|
65
247
|
return [...new Set(classifierProviders.map((provider) => provider.credentialNames.environmentVariableName))];
|
|
66
248
|
}
|
|
67
249
|
/**
|
|
68
|
-
* Returns a USD cost only
|
|
69
|
-
* the token counts are safe non-negative integers.
|
|
70
|
-
*
|
|
250
|
+
* Returns a USD cost only for a recognized requested/returned model pair and
|
|
251
|
+
* the token counts are safe non-negative integers. Provider input_tokens already
|
|
252
|
+
* includes billed text/image work across questions; never multiply by question
|
|
253
|
+
* count or add image tokens again. Decisions has no separate cache charges.
|
|
254
|
+
* Callers must not treat an unpriced provider as free.
|
|
71
255
|
*/
|
|
72
|
-
export function calculateClassifierUsageCost(provider, usage) {
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
256
|
+
export function calculateClassifierUsageCost(provider, usage, models) {
|
|
257
|
+
if (!models)
|
|
258
|
+
return undefined;
|
|
259
|
+
const entries = normalizeModelPricing(provider);
|
|
260
|
+
const entry = entries.find(({ models: names }) => names.includes(models.requestedModel) && names.includes(models.responseModel));
|
|
261
|
+
const base = entry?.pricing;
|
|
262
|
+
const tier = base?.longContext;
|
|
263
|
+
const validRates = (rates) => Number.isFinite(rates.inputPerMillionTokens) &&
|
|
264
|
+
rates.inputPerMillionTokens >= 0 &&
|
|
265
|
+
Number.isFinite(rates.outputPerMillionTokens) &&
|
|
266
|
+
rates.outputPerMillionTokens >= 0;
|
|
267
|
+
if (base == null ||
|
|
268
|
+
!validRates(base) ||
|
|
269
|
+
(tier != null &&
|
|
270
|
+
(!Number.isSafeInteger(tier.aboveInputTokens) || tier.aboveInputTokens < 0 || !validRates(tier))) ||
|
|
79
271
|
!Number.isSafeInteger(usage.input_tokens) ||
|
|
80
272
|
usage.input_tokens < 0 ||
|
|
81
273
|
!Number.isSafeInteger(usage.output_tokens) ||
|
|
82
274
|
usage.output_tokens < 0) {
|
|
83
275
|
return undefined;
|
|
84
276
|
}
|
|
277
|
+
const pricing = tier && usage.input_tokens > tier.aboveInputTokens ? tier : base;
|
|
85
278
|
const totalCost = (usage.input_tokens * pricing.inputPerMillionTokens + usage.output_tokens * pricing.outputPerMillionTokens) /
|
|
86
279
|
TOKENS_PER_MILLION;
|
|
87
280
|
return Number.isFinite(totalCost) && totalCost >= 0 ? totalCost : undefined;
|
|
@@ -96,25 +289,56 @@ function createQuestionMap(questions) {
|
|
|
96
289
|
}
|
|
97
290
|
return result;
|
|
98
291
|
}
|
|
99
|
-
async function
|
|
100
|
-
const
|
|
101
|
-
const
|
|
102
|
-
|
|
103
|
-
|
|
292
|
+
async function callClassifierHttp(args, spec, prepared, buildRequest, operation) {
|
|
293
|
+
const { apiKey, fetchImplementation, retryOnNon200, retryOnNon200CooldownMs, retryOnNon200RepeatTimes } = args;
|
|
294
|
+
const { endpoint, label: providerLabel, validateResponse, maxRequestBytes } = spec;
|
|
295
|
+
const { signal, deadline } = operation;
|
|
296
|
+
const request = buildRequest(prepared);
|
|
297
|
+
const configuredRetryCount = retryOnNon200 ? normalizeClassifierNon200RetryCount(retryOnNon200RepeatTimes) : 0;
|
|
104
298
|
const configuredCooldownMs = normalizeClassifierNon200RetryCooldownMs(retryOnNon200CooldownMs);
|
|
105
299
|
let automaticRetryCount = 0;
|
|
106
300
|
let configuredRetryCountUsed = 0;
|
|
107
|
-
//
|
|
108
|
-
//
|
|
109
|
-
|
|
110
|
-
// retries and make the diagnostic disagree with the wire payload.
|
|
301
|
+
// The transformed protocol can expand content (notably escaped JSON in OpenAI).
|
|
302
|
+
// This final wire check is distinct from validating/detaching untrusted inputs.
|
|
303
|
+
assertClassifierResourceLimits(request, operation.check);
|
|
111
304
|
const requestJson = JSON.stringify(request);
|
|
112
|
-
|
|
305
|
+
if (maxRequestBytes !== undefined && new TextEncoder().encode(requestJson).byteLength >= maxRequestBytes) {
|
|
306
|
+
throw new ClassifierProviderError(`${providerLabel} request must be smaller than ${maxRequestBytes / 1_000_000} MB, including State, images, and questions. Resize images or reduce input content.`, 'capability');
|
|
307
|
+
}
|
|
308
|
+
let requestBody;
|
|
309
|
+
let attemptIndex = -1;
|
|
310
|
+
let attemptStartedAt = 0;
|
|
311
|
+
const report = (outcome, status, kind, classifierUsage, error) => {
|
|
312
|
+
try {
|
|
313
|
+
args.onAttempt?.({
|
|
314
|
+
attemptIndex,
|
|
315
|
+
durationMs: Math.max(0, Date.now() - attemptStartedAt),
|
|
316
|
+
outcome,
|
|
317
|
+
status,
|
|
318
|
+
kind,
|
|
319
|
+
...(classifierUsage ? { classifierUsage } : {}),
|
|
320
|
+
...(error ? { error: classifierErrorMessage(error, apiKey) } : {}),
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
catch {
|
|
324
|
+
/* Observers cannot alter execution. */
|
|
325
|
+
}
|
|
326
|
+
};
|
|
327
|
+
operation.check();
|
|
113
328
|
for (;;) {
|
|
114
|
-
|
|
329
|
+
operation.check();
|
|
330
|
+
attemptIndex++;
|
|
331
|
+
attemptStartedAt = Date.now();
|
|
332
|
+
if (args.onRequestBody) {
|
|
333
|
+
try {
|
|
334
|
+
args.onRequestBody(() => (requestBody ??= JSON.parse(requestJson)));
|
|
335
|
+
}
|
|
336
|
+
catch {
|
|
337
|
+
/* Observation only. */
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
operation.check();
|
|
115
341
|
const remainingMs = deadline - Date.now();
|
|
116
|
-
if (remainingMs <= 0)
|
|
117
|
-
throw new Error(`${providerLabel} request timed out after ${timeoutMs} ms.`);
|
|
118
342
|
const controller = new AbortController();
|
|
119
343
|
const onAbort = () => controller.abort(signal.reason);
|
|
120
344
|
signal.addEventListener('abort', onAbort, { once: true });
|
|
@@ -123,82 +347,220 @@ async function callApiCompatibleClassifier({ apiKey, endpoint, fetchImplementati
|
|
|
123
347
|
clearTimeout(timer);
|
|
124
348
|
signal.removeEventListener('abort', onAbort);
|
|
125
349
|
};
|
|
350
|
+
const assertAttemptActive = () => operation.check(controller.signal);
|
|
126
351
|
let response;
|
|
127
352
|
try {
|
|
128
|
-
response = await fetchImplementation(endpoint, {
|
|
353
|
+
response = await waitForAttempt(fetchImplementation(endpoint, {
|
|
129
354
|
method: 'POST',
|
|
355
|
+
redirect: 'error',
|
|
130
356
|
headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
|
|
131
357
|
body: requestJson,
|
|
132
358
|
signal: controller.signal,
|
|
133
|
-
});
|
|
359
|
+
}), controller.signal, discardResponseBody);
|
|
134
360
|
}
|
|
135
|
-
catch {
|
|
361
|
+
catch (error) {
|
|
136
362
|
cleanupAttempt();
|
|
137
|
-
if (signal.aborted)
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
throw new Error(`${providerLabel} request timed out after ${timeoutMs} ms.`);
|
|
363
|
+
if (signal.aborted) {
|
|
364
|
+
report('aborted', undefined, undefined, undefined, `${providerLabel} request was canceled.`);
|
|
365
|
+
operation.check();
|
|
141
366
|
}
|
|
367
|
+
const kind = controller.signal.aborted && !signal.aborted ? 'timeout' : 'transport';
|
|
368
|
+
report('failure', undefined, kind, undefined, kind === 'timeout'
|
|
369
|
+
? `${providerLabel} request timed out after ${args.timeoutMs} ms.`
|
|
370
|
+
: `${providerLabel} transport request failed.`);
|
|
371
|
+
operation.check(controller.signal);
|
|
142
372
|
if (automaticRetryCount >= MAX_AUTOMATIC_ATTEMPTS - 1) {
|
|
143
|
-
throw new
|
|
373
|
+
throw new ClassifierProviderError(`${providerLabel} request failed after ${MAX_AUTOMATIC_ATTEMPTS} attempts due to a transport error.`, 'transport', undefined, { cause: error });
|
|
144
374
|
}
|
|
145
375
|
automaticRetryCount += 1;
|
|
146
376
|
await waitForRetry(Math.min(250 * 2 ** (automaticRetryCount - 1), deadline - Date.now()), signal, providerLabel);
|
|
147
377
|
continue;
|
|
148
378
|
}
|
|
379
|
+
try {
|
|
380
|
+
assertAttemptActive();
|
|
381
|
+
}
|
|
382
|
+
catch (error) {
|
|
383
|
+
cleanupAttempt();
|
|
384
|
+
discardResponseBody(response);
|
|
385
|
+
report(signal.aborted ? 'aborted' : 'failure', response.status, signal.aborted ? undefined : 'timeout', undefined, signal.aborted
|
|
386
|
+
? `${providerLabel} request was canceled.`
|
|
387
|
+
: `${providerLabel} request timed out after ${args.timeoutMs} ms.`);
|
|
388
|
+
throw error;
|
|
389
|
+
}
|
|
149
390
|
if (!response.ok) {
|
|
391
|
+
report('failure', response.status, 'http', undefined, response.status === 401 || response.status === 403
|
|
392
|
+
? `${providerLabel} authentication failed (HTTP ${response.status}). Check the ${providerLabel} API key.`
|
|
393
|
+
: `${providerLabel} rejected the request (HTTP ${response.status}).`);
|
|
394
|
+
const retryable = RETRYABLE_STATUSES.has(response.status);
|
|
395
|
+
const permanent = [400, 401, 402, 403, 413, 422].includes(response.status);
|
|
396
|
+
const willRetry = (retryable && automaticRetryCount < MAX_AUTOMATIC_ATTEMPTS - 1) ||
|
|
397
|
+
(!retryable && !permanent && configuredRetryCountUsed < configuredRetryCount);
|
|
398
|
+
if (args.onResponseBody && !willRetry) {
|
|
399
|
+
// Opt-in diagnostics must not hold up fallback on a stalled error body.
|
|
400
|
+
const diagnosticTimer = setTimeout(() => controller.abort(), Math.min(1000, deadline - Date.now()));
|
|
401
|
+
try {
|
|
402
|
+
await waitForAttempt(readClassifierResponse(response, controller.signal, assertAttemptActive, args.onResponseBody), controller.signal);
|
|
403
|
+
}
|
|
404
|
+
catch {
|
|
405
|
+
// Missing, malformed, oversized or interrupted diagnostics cannot replace the HTTP rejection.
|
|
406
|
+
}
|
|
407
|
+
finally {
|
|
408
|
+
clearTimeout(diagnosticTimer);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
150
411
|
cleanupAttempt();
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
412
|
+
// Rejected bodies are not answer outputs. Release every response, not just
|
|
413
|
+
// retries, so caught terminal failures cannot leave connections occupied.
|
|
414
|
+
// Initiate cancellation without awaiting a hostile stream's cleanup;
|
|
415
|
+
// neither the final error nor the next bounded retry may depend on it.
|
|
416
|
+
discardResponseBody(response);
|
|
417
|
+
// Diagnostic collection introduces an await after receiving the rejection.
|
|
418
|
+
// Caller cancellation and the overall deadline still outrank HTTP suppression.
|
|
419
|
+
// Do not check the diagnostic-only controller: its 1 s cap preserves the HTTP error.
|
|
420
|
+
operation.check();
|
|
421
|
+
if (willRetry) {
|
|
422
|
+
let delayMs;
|
|
423
|
+
if (retryable) {
|
|
424
|
+
automaticRetryCount += 1;
|
|
425
|
+
delayMs = getRetryDelayMs(response.headers.get('retry-after'), automaticRetryCount, deadline);
|
|
426
|
+
}
|
|
427
|
+
else {
|
|
428
|
+
configuredRetryCountUsed += 1;
|
|
429
|
+
delayMs = Math.min(configuredCooldownMs, deadline - Date.now());
|
|
430
|
+
}
|
|
155
431
|
await waitForRetry(delayMs, signal, providerLabel);
|
|
156
432
|
continue;
|
|
157
433
|
}
|
|
158
434
|
if (response.status === 401 || response.status === 403) {
|
|
159
|
-
throw new
|
|
435
|
+
throw new ClassifierProviderError(`${providerLabel} authentication failed. Check the ${providerLabel} API key.`, 'http', response.status);
|
|
160
436
|
}
|
|
161
|
-
|
|
162
|
-
|
|
437
|
+
// Repeating an unchanged invalid/oversized request or an unfunded account
|
|
438
|
+
// cannot recover. These remain HTTP failures so profile fallback works.
|
|
439
|
+
if ([400, 402, 413, 422].includes(response.status)) {
|
|
440
|
+
throw new ClassifierProviderError(`${providerLabel} rejected the request (HTTP ${response.status}).`, 'http', response.status);
|
|
163
441
|
}
|
|
164
|
-
|
|
165
|
-
configuredRetryCountUsed += 1;
|
|
166
|
-
await response.body?.cancel().catch(() => undefined);
|
|
167
|
-
await waitForRetry(Math.min(configuredCooldownMs, deadline - Date.now()), signal, providerLabel);
|
|
168
|
-
continue;
|
|
169
|
-
}
|
|
170
|
-
throw new Error(`${providerLabel} request failed (HTTP ${response.status}).`);
|
|
442
|
+
throw new ClassifierProviderError(`${providerLabel} request failed (HTTP ${response.status}).`, 'http', response.status);
|
|
171
443
|
}
|
|
172
444
|
let body;
|
|
173
445
|
try {
|
|
174
|
-
body = await response.
|
|
446
|
+
body = await waitForAttempt(readClassifierResponse(response, controller.signal, assertAttemptActive, args.onResponseBody), controller.signal);
|
|
447
|
+
assertAttemptActive();
|
|
175
448
|
}
|
|
176
|
-
catch {
|
|
177
|
-
if (signal.aborted)
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
449
|
+
catch (error) {
|
|
450
|
+
if (signal.aborted) {
|
|
451
|
+
report('aborted', response.status, undefined, undefined, `${providerLabel} request was canceled.`);
|
|
452
|
+
discardResponseBody(response);
|
|
453
|
+
operation.check();
|
|
181
454
|
}
|
|
182
|
-
|
|
455
|
+
const kind = controller.signal.aborted && !signal.aborted
|
|
456
|
+
? 'timeout'
|
|
457
|
+
: error instanceof ClassifierResponseReadError
|
|
458
|
+
? 'transport'
|
|
459
|
+
: 'response-parsing';
|
|
460
|
+
report('failure', response.status, kind, undefined, kind === 'timeout'
|
|
461
|
+
? `${providerLabel} request timed out after ${args.timeoutMs} ms.`
|
|
462
|
+
: error instanceof ClassifierResourceLimitError
|
|
463
|
+
? error.message
|
|
464
|
+
: kind === 'transport'
|
|
465
|
+
? `${providerLabel} response body could not be read.`
|
|
466
|
+
: `${providerLabel} returned an invalid JSON response.`);
|
|
467
|
+
discardResponseBody(response);
|
|
468
|
+
operation.check(controller.signal);
|
|
469
|
+
if (error instanceof ClassifierResourceLimitError)
|
|
470
|
+
throw error;
|
|
471
|
+
throw new ClassifierProviderError(kind === 'transport'
|
|
472
|
+
? `${providerLabel} response body could not be read.`
|
|
473
|
+
: `${providerLabel} returned an invalid JSON response.`, kind, undefined, { cause: error });
|
|
183
474
|
}
|
|
184
475
|
finally {
|
|
185
476
|
cleanupAttempt();
|
|
186
477
|
}
|
|
187
|
-
|
|
478
|
+
let validatedResponse;
|
|
479
|
+
try {
|
|
480
|
+
validatedResponse = validateResponse(body, prepared.questions, providerLabel);
|
|
481
|
+
}
|
|
482
|
+
catch (error) {
|
|
483
|
+
report('failure', response.status, 'response-validation', classifierAttemptUsage(body, spec, args.model), error instanceof Error ? error.message : `${providerLabel} returned an invalid classifier response.`);
|
|
484
|
+
throw new ClassifierProviderError(error instanceof Error ? error.message : `${providerLabel} returned an invalid classifier response.`, 'response-validation', undefined, { cause: error });
|
|
485
|
+
}
|
|
486
|
+
report('success', response.status, undefined, classifierAttemptUsage(body, spec, args.model));
|
|
188
487
|
return {
|
|
189
|
-
|
|
488
|
+
// Preserve the direct-provider result contract, but graph runs with the
|
|
489
|
+
// diagnostic disabled never allocate this second representation.
|
|
490
|
+
get requestBody() {
|
|
491
|
+
return (requestBody ??= JSON.parse(requestJson));
|
|
492
|
+
},
|
|
493
|
+
set requestBody(value) {
|
|
494
|
+
requestBody = value;
|
|
495
|
+
},
|
|
190
496
|
response: validatedResponse,
|
|
191
|
-
//
|
|
192
|
-
//
|
|
193
|
-
|
|
194
|
-
responseBody: validatedResponse,
|
|
497
|
+
// Expose native JSON, not the adapter's Rivet answer projection. The
|
|
498
|
+
// validators accept only object-shaped provider envelopes.
|
|
499
|
+
responseBody: body,
|
|
195
500
|
};
|
|
196
501
|
}
|
|
197
502
|
}
|
|
503
|
+
/** The bounded reader produced plain JSON; do not require valid answers to retain usable usage. */
|
|
504
|
+
function classifierAttemptUsage(body, provider, requestedModel) {
|
|
505
|
+
if (!body || typeof body !== 'object' || Array.isArray(body) || !Object.hasOwn(body, 'usage'))
|
|
506
|
+
return;
|
|
507
|
+
const { usage, model } = body;
|
|
508
|
+
if (!usage ||
|
|
509
|
+
typeof usage !== 'object' ||
|
|
510
|
+
Array.isArray(usage) ||
|
|
511
|
+
!Object.hasOwn(usage, 'input_tokens') ||
|
|
512
|
+
!Object.hasOwn(usage, 'output_tokens') ||
|
|
513
|
+
!Number.isSafeInteger(usage.input_tokens) ||
|
|
514
|
+
usage.input_tokens < 0 ||
|
|
515
|
+
!Number.isSafeInteger(usage.output_tokens) ||
|
|
516
|
+
usage.output_tokens < 0)
|
|
517
|
+
return;
|
|
518
|
+
const estimatedCostUsd = typeof model === 'string' && Object.hasOwn(body, 'model')
|
|
519
|
+
? calculateClassifierUsageCost(provider, usage, { requestedModel, responseModel: model })
|
|
520
|
+
: undefined;
|
|
521
|
+
return {
|
|
522
|
+
inputTokens: usage.input_tokens,
|
|
523
|
+
outputTokens: usage.output_tokens,
|
|
524
|
+
...(estimatedCostUsd === undefined ? {} : { estimatedCostUsd }),
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
/** Bound awaiting even when a custom transport ignores its abort signal. */
|
|
528
|
+
function waitForAttempt(promise, signal, onLateResult) {
|
|
529
|
+
return new Promise((resolve, reject) => {
|
|
530
|
+
let aborted = false;
|
|
531
|
+
const cleanup = () => signal.removeEventListener('abort', onAbort);
|
|
532
|
+
const onAbort = () => {
|
|
533
|
+
aborted = true;
|
|
534
|
+
cleanup();
|
|
535
|
+
reject(signal.reason);
|
|
536
|
+
};
|
|
537
|
+
// Attach both handlers even after cancellation: late errors are consumed
|
|
538
|
+
// and a late HTTP response is disposed, never accepted by another attempt.
|
|
539
|
+
promise.then((value) => {
|
|
540
|
+
cleanup();
|
|
541
|
+
if (aborted)
|
|
542
|
+
onLateResult?.(value);
|
|
543
|
+
else
|
|
544
|
+
resolve(value);
|
|
545
|
+
}, (error) => {
|
|
546
|
+
cleanup();
|
|
547
|
+
reject(error);
|
|
548
|
+
});
|
|
549
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
550
|
+
if (signal.aborted)
|
|
551
|
+
onAbort();
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
function discardResponseBody(response) {
|
|
555
|
+
try {
|
|
556
|
+
void response.body?.cancel().catch(() => undefined);
|
|
557
|
+
}
|
|
558
|
+
catch {
|
|
559
|
+
// Cleanup is observational, including custom fetch/body implementations.
|
|
560
|
+
}
|
|
561
|
+
}
|
|
198
562
|
export function normalizeClassifierNon200RetryCount(value) {
|
|
199
|
-
const retryCount = typeof value === 'number' && Number.isFinite(value)
|
|
200
|
-
? value
|
|
201
|
-
: DEFAULT_CLASSIFIER_RETRY_ON_NON_200_REPEAT_TIMES;
|
|
563
|
+
const retryCount = typeof value === 'number' && Number.isFinite(value) ? value : DEFAULT_CLASSIFIER_RETRY_ON_NON_200_REPEAT_TIMES;
|
|
202
564
|
return Math.max(1, Math.floor(retryCount));
|
|
203
565
|
}
|
|
204
566
|
export function normalizeClassifierNon200RetryCooldownMs(value) {
|
|
@@ -245,103 +607,3 @@ function getRetryDelayMs(retryAfter, attempt, deadline) {
|
|
|
245
607
|
}
|
|
246
608
|
return Math.max(0, Math.min(requestedMs ?? 250 * 2 ** (attempt - 1), deadline - Date.now()));
|
|
247
609
|
}
|
|
248
|
-
function isRecord(value) {
|
|
249
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
250
|
-
}
|
|
251
|
-
function requireFiniteUnit(value, label, providerLabel) {
|
|
252
|
-
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1) {
|
|
253
|
-
throw new Error(`${providerLabel} response has invalid ${label}.`);
|
|
254
|
-
}
|
|
255
|
-
return value;
|
|
256
|
-
}
|
|
257
|
-
function requireProbabilityMap(value, expectedKeys, label, providerLabel) {
|
|
258
|
-
if (!isRecord(value))
|
|
259
|
-
throw new Error(`${providerLabel} response has invalid ${label}.`);
|
|
260
|
-
const actualKeys = Object.keys(value);
|
|
261
|
-
if (actualKeys.length !== expectedKeys.length ||
|
|
262
|
-
expectedKeys.some((key) => !Object.prototype.hasOwnProperty.call(value, key))) {
|
|
263
|
-
throw new Error(`${providerLabel} response has inconsistent ${label} keys.`);
|
|
264
|
-
}
|
|
265
|
-
let total = 0;
|
|
266
|
-
for (const key of expectedKeys)
|
|
267
|
-
total += requireFiniteUnit(value[key], `${label}.${key}`, providerLabel);
|
|
268
|
-
if (Math.abs(total - 1) > 0.001)
|
|
269
|
-
throw new Error(`${providerLabel} response ${label} must sum to 1.`);
|
|
270
|
-
return value;
|
|
271
|
-
}
|
|
272
|
-
function structurallyEqual(left, right) {
|
|
273
|
-
if (Object.is(left, right))
|
|
274
|
-
return true;
|
|
275
|
-
if (Array.isArray(left) || Array.isArray(right)) {
|
|
276
|
-
return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((item, index) => structurallyEqual(item, right[index]));
|
|
277
|
-
}
|
|
278
|
-
if (!isRecord(left) || !isRecord(right))
|
|
279
|
-
return false;
|
|
280
|
-
const leftKeys = Object.keys(left);
|
|
281
|
-
const rightKeys = Object.keys(right);
|
|
282
|
-
return leftKeys.length === rightKeys.length && leftKeys.every((key) => Object.prototype.hasOwnProperty.call(right, key) && structurallyEqual(left[key], right[key]));
|
|
283
|
-
}
|
|
284
|
-
export function validateApiCompatibleClassifierResponse(body, questions, providerLabel = 'Classifier provider') {
|
|
285
|
-
if (!isRecord(body) ||
|
|
286
|
-
typeof body.model !== 'string' ||
|
|
287
|
-
body.model.trim() === '' ||
|
|
288
|
-
!isRecord(body.answers) ||
|
|
289
|
-
!isRecord(body.usage)) {
|
|
290
|
-
throw new Error(`${providerLabel} returned an invalid response shape.`);
|
|
291
|
-
}
|
|
292
|
-
const expectedIds = questions.map((question) => question.questionId);
|
|
293
|
-
const answerIds = Object.keys(body.answers);
|
|
294
|
-
if (answerIds.length !== expectedIds.length ||
|
|
295
|
-
expectedIds.some((id) => !Object.prototype.hasOwnProperty.call(body.answers, id))) {
|
|
296
|
-
throw new Error(`${providerLabel} response does not match the submitted question IDs.`);
|
|
297
|
-
}
|
|
298
|
-
for (const question of questions) {
|
|
299
|
-
const answer = body.answers[question.questionId];
|
|
300
|
-
if (!isRecord(answer) || answer.type !== question.type) {
|
|
301
|
-
throw new Error(`${providerLabel} response type does not match question '${question.questionId}'.`);
|
|
302
|
-
}
|
|
303
|
-
if (question.type === 'choice') {
|
|
304
|
-
const choiceQuestion = question;
|
|
305
|
-
const keys = Object.keys(choiceQuestion.criteria);
|
|
306
|
-
if (typeof answer.choice !== 'string' ||
|
|
307
|
-
!Object.prototype.hasOwnProperty.call(choiceQuestion.criteria, answer.choice)) {
|
|
308
|
-
throw new Error(`${providerLabel} response chose an unknown option for '${question.questionId}'.`);
|
|
309
|
-
}
|
|
310
|
-
requireFiniteUnit(answer.confidence, `${question.questionId}.confidence`, providerLabel);
|
|
311
|
-
requireProbabilityMap(answer.probabilities, keys, `${question.questionId}.probabilities`, providerLabel);
|
|
312
|
-
}
|
|
313
|
-
else if (question.type === 'score') {
|
|
314
|
-
const scoreQuestion = question;
|
|
315
|
-
if (typeof answer.score !== 'number' ||
|
|
316
|
-
!Number.isFinite(answer.score) ||
|
|
317
|
-
answer.score < 0 ||
|
|
318
|
-
answer.score > scoreQuestion.criteria.length - 1) {
|
|
319
|
-
throw new Error(`${providerLabel} response has invalid score for '${question.questionId}'.`);
|
|
320
|
-
}
|
|
321
|
-
requireFiniteUnit(answer.confidence, `${question.questionId}.confidence`, providerLabel);
|
|
322
|
-
const keys = scoreQuestion.criteria.map((_, index) => String(index));
|
|
323
|
-
requireProbabilityMap(answer.probabilities, keys, `${question.questionId}.probabilities`, providerLabel);
|
|
324
|
-
const legend = answer.legend;
|
|
325
|
-
if (!isRecord(legend) ||
|
|
326
|
-
Object.keys(legend).length !== keys.length ||
|
|
327
|
-
keys.some((key, index) => !Object.prototype.hasOwnProperty.call(legend, key) ||
|
|
328
|
-
!structurallyEqual(legend[key], scoreQuestion.criteria[index]))) {
|
|
329
|
-
throw new Error(`${providerLabel} response has inconsistent legend for '${question.questionId}'.`);
|
|
330
|
-
}
|
|
331
|
-
}
|
|
332
|
-
else {
|
|
333
|
-
requireFiniteUnit(answer.noul, `${question.questionId}.noul`, providerLabel);
|
|
334
|
-
}
|
|
335
|
-
}
|
|
336
|
-
const inputTokens = body.usage.input_tokens;
|
|
337
|
-
const outputTokens = body.usage.output_tokens;
|
|
338
|
-
if (typeof inputTokens !== 'number' ||
|
|
339
|
-
!Number.isSafeInteger(inputTokens) ||
|
|
340
|
-
inputTokens < 0 ||
|
|
341
|
-
typeof outputTokens !== 'number' ||
|
|
342
|
-
!Number.isSafeInteger(outputTokens) ||
|
|
343
|
-
outputTokens < 0) {
|
|
344
|
-
throw new Error(`${providerLabel} response has invalid usage values.`);
|
|
345
|
-
}
|
|
346
|
-
return body;
|
|
347
|
-
}
|