@valerypopoff/rivet2-core 2.22.1 → 2.25.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 +1438 -824
- package/dist/cjs/bundle.cjs.map +4 -4
- package/dist/cjs/interpolationRuntime.cjs +23 -0
- package/dist/cjs/interpolationRuntime.cjs.map +3 -3
- package/dist/cjs/serialization.cjs +1 -0
- package/dist/cjs/serialization.cjs.map +2 -2
- package/dist/cjs/webAppRuntime.cjs +4 -1
- package/dist/cjs/webAppRuntime.cjs.map +2 -2
- package/dist/esm/exports.js +3 -1
- package/dist/esm/index.js +3 -0
- package/dist/esm/integrations/CodeRunner.js +6 -3
- package/dist/esm/integrations/CodeRunnerNamespace.js +10 -0
- package/dist/esm/model/AgentResponseTracePresentation.js +5 -1
- package/dist/esm/model/ChildInvocationOwnership.js +51 -0
- package/dist/esm/model/DatasetOwnership.js +9 -0
- package/dist/esm/model/GraphExecutionState.js +3 -0
- package/dist/esm/model/GraphProcessor.js +94 -55
- package/dist/esm/model/NodeRegistration.js +2 -6
- package/dist/esm/model/RunCostLedger.js +58 -0
- package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -2
- package/dist/esm/model/chat-v2/chatV2Outputs.js +1 -1
- package/dist/esm/model/chat-v2/chatV2Pipeline.js +5 -0
- package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +3 -0
- package/dist/esm/model/chat-v2/llmModelCandidate.js +3 -0
- package/dist/esm/model/chat-v2/llmProfile.js +2 -0
- package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +1 -0
- package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +2 -1
- package/dist/esm/model/chat-v2/modelRegistry.js +12 -3
- package/dist/esm/model/classifier/baseten.js +78 -0
- package/dist/esm/model/classifier/credentials.js +17 -9
- package/dist/esm/model/classifier/images.js +4 -4
- package/dist/esm/model/classifier/jev.js +45 -0
- package/dist/esm/model/classifier/json.js +1 -1
- package/dist/esm/model/classifier/limits.js +13 -13
- package/dist/esm/model/classifier/openai.js +20 -2
- package/dist/esm/model/classifier/preparation.js +5 -5
- package/dist/esm/model/classifier/profile.js +24 -15
- package/dist/esm/model/classifier/profileExecution.js +28 -24
- package/dist/esm/model/classifier/providers.js +194 -87
- package/dist/esm/model/classifier/questionHelpers.js +21 -2
- package/dist/esm/model/classifier/questions.js +37 -7
- package/dist/esm/model/classifier/response.js +8 -2
- package/dist/esm/model/classifier/state.js +2 -2
- package/dist/esm/model/classifier/subq.js +51 -0
- package/dist/esm/model/nodes/ClassifierEvaluateNode.js +48 -66
- package/dist/esm/model/nodes/ClassifierProfileNode.js +11 -9
- package/dist/esm/model/nodes/ClassifierQuestionNode.js +53 -34
- package/dist/esm/model/tokenPricing.js +52 -0
- package/dist/esm/model/tokenPricingEditor.js +9 -0
- package/dist/types/exports.d.ts +3 -0
- package/dist/types/index.d.ts +1 -1
- package/dist/types/integrations/CodeRunner.d.ts +4 -1
- package/dist/types/integrations/CodeRunnerNamespace.d.ts +5 -0
- package/dist/types/model/AgentResponseTracePresentation.d.ts +2 -0
- package/dist/types/model/ChildInvocationOwnership.d.ts +36 -0
- package/dist/types/model/DatasetOwnership.d.ts +5 -0
- package/dist/types/model/GraphExecutionState.d.ts +2 -0
- package/dist/types/model/GraphProcessor.d.ts +3 -0
- package/dist/types/model/RunCostLedger.d.ts +19 -0
- package/dist/types/model/chat-v2/chatV2Outputs.d.ts +1 -1
- package/dist/types/model/chat-v2/chatV2Types.d.ts +2 -0
- package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +3 -1
- package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +7 -5
- package/dist/types/model/chat-v2/modelRegistry.d.ts +7 -1
- package/dist/types/model/classifier/baseten.d.ts +8 -0
- package/dist/types/model/classifier/credentials.d.ts +2 -0
- package/dist/types/model/classifier/jev.d.ts +9 -0
- package/dist/types/model/classifier/profile.d.ts +3 -1
- package/dist/types/model/classifier/profileExecution.d.ts +2 -1
- package/dist/types/model/classifier/providers.d.ts +30 -6
- package/dist/types/model/classifier/questionHelpers.d.ts +3 -1
- package/dist/types/model/classifier/questions.d.ts +2 -1
- package/dist/types/model/classifier/state.d.ts +1 -0
- package/dist/types/model/classifier/subq.d.ts +8 -0
- package/dist/types/model/classifier/types.d.ts +9 -2
- package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +2 -4
- package/dist/types/model/nodes/ClassifierQuestionNode.d.ts +2 -2
- package/dist/types/model/tokenPricing.d.ts +18 -0
- package/dist/types/model/tokenPricingEditor.d.ts +4 -0
- package/package.json +2 -2
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { coerceTypeOptional } from '../../utils/coerceType.js';
|
|
2
|
+
import { validateTokenPricing } from '../tokenPricing.js';
|
|
2
3
|
import { getInputOrData } from '../../utils/inputs.js';
|
|
3
4
|
import { resolveChatV2Credential } from './chatV2ProviderProfile.js';
|
|
4
5
|
import { resolveLLMChatV2ExtraProviderOptions, resolveLLMChatV2GenerationParameters, resolveLLMChatV2Headers, } from './chatV2RuntimeOptions.js';
|
|
@@ -81,7 +82,7 @@ export function resolveLLMProfileNodeValue(params) {
|
|
|
81
82
|
return {
|
|
82
83
|
version: LLM_PROFILE_VALUE_VERSION,
|
|
83
84
|
credential,
|
|
84
|
-
configuration,
|
|
85
|
+
configuration: { ...configuration, tokenPricing: validateTokenPricing(configuration.tokenPricing) },
|
|
85
86
|
...(profileName === '' ? {} : { profileName }),
|
|
86
87
|
...(projectId == null
|
|
87
88
|
? {}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { anthropicModels } from '../../plugins/anthropic/anthropic.js';
|
|
2
2
|
import { generativeAiGoogleModels } from '../../plugins/google/google.js';
|
|
3
3
|
import { openaiModels } from '../../utils/openai.js';
|
|
4
|
+
import { calculateTokenUsageCost, isReportedTokenCount } from '../tokenPricing.js';
|
|
4
5
|
const TOKENS_PER_THOUSAND = 1_000;
|
|
5
6
|
function isFiniteNonNegative(value) {
|
|
6
7
|
return typeof value === 'number' && Number.isFinite(value) && value >= 0;
|
|
@@ -55,9 +56,15 @@ export function getChatV2ModelInfo(provider, modelId) {
|
|
|
55
56
|
const providerModels = chatV2ModelRegistry[provider];
|
|
56
57
|
return providerModels[modelId];
|
|
57
58
|
}
|
|
59
|
+
export function getChatV2SystemTokenPricing(provider, modelId) {
|
|
60
|
+
const cost = getChatV2ModelInfo(provider, modelId.trim())?.cost;
|
|
61
|
+
return cost == null
|
|
62
|
+
? undefined
|
|
63
|
+
: { inputPerMillionTokens: cost.prompt * 1_000_000, outputPerMillionTokens: cost.completion * 1_000_000 };
|
|
64
|
+
}
|
|
58
65
|
export function calculateChatV2Cost(provider, modelId, promptTokens, completionTokens) {
|
|
59
66
|
const model = getChatV2ModelInfo(provider, modelId);
|
|
60
|
-
if (model?.cost == null || !
|
|
67
|
+
if (model?.cost == null || !isReportedTokenCount(promptTokens) || !isReportedTokenCount(completionTokens)) {
|
|
61
68
|
return undefined;
|
|
62
69
|
}
|
|
63
70
|
const cost = model.cost.prompt * promptTokens + model.cost.completion * completionTokens;
|
|
@@ -68,7 +75,9 @@ export function calculateChatV2Cost(provider, modelId, promptTokens, completionT
|
|
|
68
75
|
* billable text-token counts are available. Cache discounts, long-context
|
|
69
76
|
* premiums, and provider tool fees are not modeled in those estimates.
|
|
70
77
|
*/
|
|
71
|
-
export function calculateChatV2UsageCost(provider, modelId, usage, providerMetadata) {
|
|
78
|
+
export function calculateChatV2UsageCost(provider, modelId, usage, providerMetadata, tokenPricing) {
|
|
79
|
+
if (tokenPricing !== undefined)
|
|
80
|
+
return calculateTokenUsageCost(tokenPricing, usage);
|
|
72
81
|
if (provider === 'openrouter') {
|
|
73
82
|
const reportedUsage = providerMetadata?.openrouter?.usage;
|
|
74
83
|
const cost = reportedUsage != null && typeof reportedUsage === 'object'
|
|
@@ -76,7 +85,7 @@ export function calculateChatV2UsageCost(provider, modelId, usage, providerMetad
|
|
|
76
85
|
: undefined;
|
|
77
86
|
return isFiniteNonNegative(cost) ? cost : undefined;
|
|
78
87
|
}
|
|
79
|
-
if (
|
|
88
|
+
if (usage?.inputTokens == null || usage.outputTokens == null) {
|
|
80
89
|
return undefined;
|
|
81
90
|
}
|
|
82
91
|
return calculateChatV2Cost(provider, modelId, usage.inputTokens, usage.outputTokens);
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { inspectClassifierImage } from './images.js';
|
|
2
|
+
/** Native Model API slugs, not Hugging Face or gateway IDs. Verified 2026-10-26. */
|
|
3
|
+
export const BASETEN_DECISION_MODELS = [
|
|
4
|
+
'decision-models/baseten-elephant-9b-latest',
|
|
5
|
+
'decision-models/baseten-mammoth-27b-latest',
|
|
6
|
+
];
|
|
7
|
+
/** Baseten uses inline user-message image parts, never top-level images/placeholders. */
|
|
8
|
+
export function basetenDecisionState(state) {
|
|
9
|
+
if (state.kind === 'json')
|
|
10
|
+
return state.value;
|
|
11
|
+
return {
|
|
12
|
+
messages: state.messages.map(({ parts }) => ({
|
|
13
|
+
role: 'user',
|
|
14
|
+
content: parts.map((part) => part.type === 'text'
|
|
15
|
+
? { type: 'text', text: part.text }
|
|
16
|
+
: { type: 'image_url', image_url: { url: part.dataUrl } }),
|
|
17
|
+
})),
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
21
|
+
/** https://docs.baseten.co/reference/inference-api/system-one */
|
|
22
|
+
export function assertBasetenDecisionLimits({ model, state, questions }, check) {
|
|
23
|
+
let options = 0;
|
|
24
|
+
for (const question of questions) {
|
|
25
|
+
check();
|
|
26
|
+
options += question.type === 'noul' ? 2 : Object.keys(question.criteria ?? {}).length;
|
|
27
|
+
}
|
|
28
|
+
if (options > 512)
|
|
29
|
+
throw new Error('Baseten supports at most 512 options across all questions; Noul counts as two.');
|
|
30
|
+
const wire = basetenDecisionState(state);
|
|
31
|
+
let characters = 0, images = 0;
|
|
32
|
+
const text = (value) => {
|
|
33
|
+
for (const _character of value) {
|
|
34
|
+
check();
|
|
35
|
+
if (++characters > 50000)
|
|
36
|
+
throw new Error('Baseten rendered State must fit within 50,000 characters.');
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
if (!record(wire) || !Array.isArray(wire.messages)) {
|
|
40
|
+
text(typeof wire === 'string' ? wire : JSON.stringify(wire));
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
// Explicit JSON conversation State is interpreted natively by Baseten too.
|
|
44
|
+
// Inspect it as well, so JSON cannot bypass the same model/image limits.
|
|
45
|
+
for (const message of wire.messages) {
|
|
46
|
+
check();
|
|
47
|
+
if (!record(message) || (message.role !== 'user' && message.role !== 'assistant'))
|
|
48
|
+
throw new Error('Baseten State messages must have user or assistant roles.');
|
|
49
|
+
if (typeof message.content === 'string') {
|
|
50
|
+
text(message.content);
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
if (!Array.isArray(message.content))
|
|
54
|
+
throw new Error('Baseten message content must be text or content parts.');
|
|
55
|
+
for (const part of message.content) {
|
|
56
|
+
check();
|
|
57
|
+
if (!record(part))
|
|
58
|
+
throw new Error('Invalid Baseten State content part.');
|
|
59
|
+
if (part.type === 'text' && typeof part.text === 'string') {
|
|
60
|
+
text(part.text);
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
if (part.type !== 'image_url' || !record(part.image_url))
|
|
64
|
+
throw new Error('Baseten State supports text and image_url parts only.');
|
|
65
|
+
if (message.role !== 'user')
|
|
66
|
+
throw new Error('Baseten accepts images in user messages only.');
|
|
67
|
+
if (!BASETEN_DECISION_MODELS.some((id) => id === model))
|
|
68
|
+
throw new Error('Image support is not known for this Baseten model.');
|
|
69
|
+
if (++images > 4)
|
|
70
|
+
throw new Error('Baseten supports at most four images per request.');
|
|
71
|
+
if (part.image_url.detail !== undefined && part.image_url.detail !== 'auto')
|
|
72
|
+
throw new Error('Baseten image detail must be auto or omitted.');
|
|
73
|
+
const image = inspectClassifierImage(part.image_url.url, check);
|
|
74
|
+
if (!['image/png', 'image/jpeg', 'image/webp'].includes(image.mediaType))
|
|
75
|
+
throw new Error('Baseten accepts PNG, JPEG and WebP images, not GIF.');
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
@@ -22,6 +22,14 @@ export const PERPLEXITY_DEFAULT_CREDENTIAL_NAMES = {
|
|
|
22
22
|
programmaticName: 'perplexityApiKey',
|
|
23
23
|
environmentVariableName: 'PERPLEXITY_API_KEY',
|
|
24
24
|
};
|
|
25
|
+
export const SUBQ_DEFAULT_CREDENTIAL_NAMES = {
|
|
26
|
+
programmaticName: 'subqApiKey',
|
|
27
|
+
environmentVariableName: 'SUBQ_API_KEY',
|
|
28
|
+
};
|
|
29
|
+
export const BASETEN_DEFAULT_CREDENTIAL_NAMES = {
|
|
30
|
+
programmaticName: 'basetenApiKey',
|
|
31
|
+
environmentVariableName: 'BASETEN_API_KEY',
|
|
32
|
+
};
|
|
25
33
|
const programmaticNamePattern = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
26
34
|
const environmentVariableNamePattern = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
27
35
|
export function isValidClassifierProgrammaticCredentialName(name) {
|
|
@@ -32,22 +40,22 @@ export function isValidClassifierEnvironmentCredentialName(name) {
|
|
|
32
40
|
}
|
|
33
41
|
export function normalizeClassifierCredentialNames(value, defaults = JEV_DEFAULT_CREDENTIAL_NAMES) {
|
|
34
42
|
if (value != null && (typeof value !== 'object' || Array.isArray(value))) {
|
|
35
|
-
throw new Error('
|
|
43
|
+
throw new Error('Decision AI API key names must be an object.');
|
|
36
44
|
}
|
|
37
45
|
const raw = value;
|
|
38
46
|
if (raw?.programmaticName != null && typeof raw.programmaticName !== 'string') {
|
|
39
|
-
throw new Error('
|
|
47
|
+
throw new Error('Decision AI programmatic API key name must be a string.');
|
|
40
48
|
}
|
|
41
49
|
if (raw?.environmentVariableName != null && typeof raw.environmentVariableName !== 'string') {
|
|
42
|
-
throw new Error('
|
|
50
|
+
throw new Error('Decision AI API key environment variable must be a string.');
|
|
43
51
|
}
|
|
44
52
|
const programmaticName = raw?.programmaticName?.trim() || defaults.programmaticName;
|
|
45
53
|
const environmentVariableName = raw?.environmentVariableName?.trim() || defaults.environmentVariableName;
|
|
46
54
|
if (!isValidClassifierProgrammaticCredentialName(programmaticName)) {
|
|
47
|
-
throw new Error('
|
|
55
|
+
throw new Error('Decision AI programmatic API key name must be a JavaScript-style identifier without a leading digit.');
|
|
48
56
|
}
|
|
49
57
|
if (!isValidClassifierEnvironmentCredentialName(environmentVariableName)) {
|
|
50
|
-
throw new Error('
|
|
58
|
+
throw new Error('Decision AI API key environment variable must contain letters, digits, and _ without a leading digit.');
|
|
51
59
|
}
|
|
52
60
|
return { programmaticName, environmentVariableName };
|
|
53
61
|
}
|
|
@@ -66,11 +74,11 @@ export function isDefaultClassifierCredentialNames(names, defaults = JEV_DEFAULT
|
|
|
66
74
|
export function resolveClassifierApiKey({ apiKeyNames, apiKeySource, context, defaults, inputs, providerId, }) {
|
|
67
75
|
if (apiKeySource === 'classifier-settings') {
|
|
68
76
|
const read = (value, key) => value !== null && typeof value === 'object'
|
|
69
|
-
? classifierDataProperty(value, key, '
|
|
77
|
+
? classifierDataProperty(value, key, 'Decision AI settings credentials')
|
|
70
78
|
: undefined;
|
|
71
79
|
const saved = getNonEmptyString(read(read(read(context.settings, 'classifierProviders'), providerId), 'apiKey'));
|
|
72
80
|
if (!saved)
|
|
73
|
-
throw new ClassifierCredentialMissingError(`
|
|
81
|
+
throw new ClassifierCredentialMissingError(`Decision AI settings API key for ${providerId} is not set. No automatic fallback is used.`);
|
|
74
82
|
return saved;
|
|
75
83
|
}
|
|
76
84
|
if (apiKeySource === 'input') {
|
|
@@ -80,7 +88,7 @@ export function resolveClassifierApiKey({ apiKeyNames, apiKeySource, context, de
|
|
|
80
88
|
return value;
|
|
81
89
|
}
|
|
82
90
|
if (apiKeySource !== undefined && apiKeySource !== 'configured')
|
|
83
|
-
throw new Error('Unknown
|
|
91
|
+
throw new Error('Unknown Decision AI API key source.');
|
|
84
92
|
const names = normalizeClassifierCredentialNames(apiKeyNames, defaults);
|
|
85
93
|
const namedValue = resolveNamedClassifierApiKey(context, names, providerId === 'openai' && isDefaultClassifierCredentialNames(names, defaults));
|
|
86
94
|
if (namedValue)
|
|
@@ -96,7 +104,7 @@ export function resolveClassifierApiKey({ apiKeyNames, apiKeySource, context, de
|
|
|
96
104
|
return legacyValue;
|
|
97
105
|
}
|
|
98
106
|
}
|
|
99
|
-
throw new ClassifierCredentialMissingError(`${providerId === 'jev' ? 'Jev' : '
|
|
107
|
+
throw new ClassifierCredentialMissingError(`${providerId === 'jev' ? 'Jev' : 'Decision AI'} API key is not set. Pass ${names.programmaticName}, configure ${names.environmentVariableName}, or set the configured key in Settings > Decision AI.`);
|
|
100
108
|
}
|
|
101
109
|
function resolveNamedClassifierApiKey(context, names, useLegacyOpenAIKey = false) {
|
|
102
110
|
const programmaticValue = getNonEmptyString(context.settings?.[names.programmaticName]);
|
|
@@ -139,7 +139,7 @@ export function classifierImageFromText(value, check) {
|
|
|
139
139
|
export function prepareClassifierImageText(value, check) {
|
|
140
140
|
check?.();
|
|
141
141
|
if (value.length > CLASSIFIER_LIMITS.requestBytes)
|
|
142
|
-
throw new Error('
|
|
142
|
+
throw new Error('Decision AI image/text exceeds the 32 MiB input limit.');
|
|
143
143
|
if (value.startsWith('data:image/')) {
|
|
144
144
|
return { ...inspectClassifierImage(value, check), dataUrl: value };
|
|
145
145
|
}
|
|
@@ -163,14 +163,14 @@ export function assertClassifierImages(value, check) {
|
|
|
163
163
|
}
|
|
164
164
|
export function assertLiquidImageLimits(images, check) {
|
|
165
165
|
if (images.length > 8)
|
|
166
|
-
throw new Error('Liquid
|
|
166
|
+
throw new Error('Liquid Decision AI State must contain at most 8 images.');
|
|
167
167
|
let patches = 0;
|
|
168
168
|
for (const { width, height } of images) {
|
|
169
169
|
check?.();
|
|
170
170
|
if (Math.max(width, height) / Math.min(width, height) > 100)
|
|
171
|
-
throw new Error('Liquid
|
|
171
|
+
throw new Error('Liquid Decision AI images must have an aspect ratio at most 100:1.');
|
|
172
172
|
patches += Math.ceil(width / 32) * Math.ceil(height / 32);
|
|
173
173
|
}
|
|
174
174
|
if (patches > 10_000)
|
|
175
|
-
throw new Error('Liquid
|
|
175
|
+
throw new Error('Liquid Decision AI images must contain at most 10,000 patches of 32 by 32 pixels in total.');
|
|
176
176
|
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { createQuestionMap } from './questions.js';
|
|
2
|
+
/** Experimental image contract, verified 2026-10-24: https://docs.typesafe.ai/images */
|
|
3
|
+
export const JEV_IMAGE_MODELS = ['jev-latest', 'jev-preview', 'jev-1.13.0', 'jev-1.14.0'];
|
|
4
|
+
/** https://docs.typesafe.ai/primitives/box — Box requires Jev 1.14, not 1.13. */
|
|
5
|
+
export const JEV_BOX_MODELS = ['jev-latest', 'jev-preview', 'jev-1.14.0'];
|
|
6
|
+
export function assertJevImageLimits(images, check) {
|
|
7
|
+
for (const { dataUrl, mediaType, width, height } of images) {
|
|
8
|
+
check();
|
|
9
|
+
if (mediaType !== 'image/png' && mediaType !== 'image/jpeg')
|
|
10
|
+
throw new Error('Jev images must be still PNG or JPEG. Convert other formats upstream.');
|
|
11
|
+
if (Math.min(width, height) < 280 || Math.max(width, height) > 1568)
|
|
12
|
+
throw new Error('Jev image width and height must each be between 280 and 1568 pixels. Resize upstream.');
|
|
13
|
+
const payload = dataUrl.slice(dataUrl.indexOf(',') + 1);
|
|
14
|
+
const bytes = (payload.length / 4) * 3 - (payload.endsWith('==') ? 2 : payload.endsWith('=') ? 1 : 0);
|
|
15
|
+
if (bytes > 16 * 1024 * 1024)
|
|
16
|
+
throw new Error('Jev image files must not exceed 16 MiB decoded.');
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/** Jev substitutes opaque asset references, not Liquid's numbered image placeholders. */
|
|
20
|
+
export function createJevDecisionRequest({ model, state, questions, }) {
|
|
21
|
+
const references = new Map();
|
|
22
|
+
const assets = {};
|
|
23
|
+
const messagesText = (messages) => messages
|
|
24
|
+
.map(({ parts }) => parts
|
|
25
|
+
.map((part) => {
|
|
26
|
+
if (part.type === 'text')
|
|
27
|
+
return part.text;
|
|
28
|
+
let reference = references.get(part.dataUrl);
|
|
29
|
+
if (!reference) {
|
|
30
|
+
reference = globalThis.crypto.randomUUID();
|
|
31
|
+
references.set(part.dataUrl, reference);
|
|
32
|
+
assets[reference] = {
|
|
33
|
+
type: 'image',
|
|
34
|
+
format: part.dataUrl.startsWith('data:image/png;') ? 'png' : 'jpg',
|
|
35
|
+
data_base64: part.dataUrl.slice(part.dataUrl.indexOf(',') + 1),
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
return reference;
|
|
39
|
+
})
|
|
40
|
+
.join('\n'))
|
|
41
|
+
.join('\n\n');
|
|
42
|
+
const value = state.kind === 'json' ? state.value : messagesText(state.messages);
|
|
43
|
+
const questionMap = createQuestionMap(questions, (question) => question.instructionsMessages ? messagesText(question.instructionsMessages) : question.instructions);
|
|
44
|
+
return { model, state: value, questions: questionMap, ...(references.size ? { assets } : {}) };
|
|
45
|
+
}
|
|
@@ -8,7 +8,7 @@ export function classifierDataProperty(value, key, label = 'State') {
|
|
|
8
8
|
}
|
|
9
9
|
/** Snapshot only the selected port's wrapper; never read unrelated input getters. */
|
|
10
10
|
export function classifierInputDataValue(inputs, port) {
|
|
11
|
-
const label = `
|
|
11
|
+
const label = `Decision AI ${port} input`;
|
|
12
12
|
const input = classifierDataProperty(inputs, port, label);
|
|
13
13
|
if (input === undefined)
|
|
14
14
|
return undefined;
|
|
@@ -25,7 +25,7 @@ export function classifierPreparationCheck(signal, deadline, timeoutMs) {
|
|
|
25
25
|
return () => {
|
|
26
26
|
signal.throwIfAborted();
|
|
27
27
|
if (Date.now() >= deadline)
|
|
28
|
-
throw new Error(`
|
|
28
|
+
throw new Error(`Decision AI preparation/request timed out${timeoutMs === undefined ? '' : ` after ${timeoutMs} ms`}.`);
|
|
29
29
|
};
|
|
30
30
|
}
|
|
31
31
|
/** Bound expanded work before JSON serialization or image encoding, without reading getters. */
|
|
@@ -41,7 +41,7 @@ export class ClassifierValueBudget {
|
|
|
41
41
|
constructor(check = () => { }, maxBytes = CLASSIFIER_LIMITS.requestBytes) {
|
|
42
42
|
this.check = check;
|
|
43
43
|
if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0)
|
|
44
|
-
throw new ClassifierResourceLimitError('
|
|
44
|
+
throw new ClassifierResourceLimitError('Decision AI byte limit must be a positive safe integer.');
|
|
45
45
|
this.maxBytes = Math.min(maxBytes, CLASSIFIER_LIMITS.requestBytes);
|
|
46
46
|
}
|
|
47
47
|
get remainingBytes() {
|
|
@@ -56,7 +56,7 @@ export class ClassifierValueBudget {
|
|
|
56
56
|
? `${maxBytes / (1024 * 1024)} MiB`
|
|
57
57
|
: `${maxBytes / 1_000_000} MB`
|
|
58
58
|
: `${maxBytes}-byte`;
|
|
59
|
-
throw new ClassifierResourceLimitError(`
|
|
59
|
+
throw new ClassifierResourceLimitError(`Decision AI input exceeds the ${size} resource limit. Reduce input content or image size.`);
|
|
60
60
|
}
|
|
61
61
|
}
|
|
62
62
|
string(text) {
|
|
@@ -90,9 +90,9 @@ export class ClassifierValueBudget {
|
|
|
90
90
|
value(depth) {
|
|
91
91
|
this.check();
|
|
92
92
|
if (++this.values > CLASSIFIER_LIMITS.values)
|
|
93
|
-
throw new ClassifierResourceLimitError('
|
|
93
|
+
throw new ClassifierResourceLimitError('Decision AI input has too many expanded values.');
|
|
94
94
|
if (depth > CLASSIFIER_LIMITS.depth)
|
|
95
|
-
throw new ClassifierResourceLimitError('
|
|
95
|
+
throw new ClassifierResourceLimitError('Decision AI input exceeds the maximum nesting depth of 64.');
|
|
96
96
|
}
|
|
97
97
|
inspect(value, json) {
|
|
98
98
|
const startBytes = this.bytes;
|
|
@@ -124,13 +124,13 @@ export class ClassifierValueBudget {
|
|
|
124
124
|
throw new Error(`${json.label} must not contain JSON serialization hooks.`);
|
|
125
125
|
}
|
|
126
126
|
if (path.has(item))
|
|
127
|
-
throw new Error('
|
|
127
|
+
throw new Error('Decision AI input contains a circular reference.');
|
|
128
128
|
path.add(item);
|
|
129
129
|
this.add(2);
|
|
130
130
|
const copy = json?.copy ? (Array.isArray(item) ? [] : {}) : undefined;
|
|
131
131
|
if (Array.isArray(item)) {
|
|
132
132
|
if (item.length > CLASSIFIER_LIMITS.values)
|
|
133
|
-
throw new ClassifierResourceLimitError('
|
|
133
|
+
throw new ClassifierResourceLimitError('Decision AI input has too many expanded values.');
|
|
134
134
|
for (let i = 0; i < item.length; i++) {
|
|
135
135
|
if (i > 0)
|
|
136
136
|
this.add(1);
|
|
@@ -149,7 +149,7 @@ export class ClassifierValueBudget {
|
|
|
149
149
|
else {
|
|
150
150
|
const keys = Object.keys(item);
|
|
151
151
|
if (keys.length > CLASSIFIER_LIMITS.values)
|
|
152
|
-
throw new ClassifierResourceLimitError('
|
|
152
|
+
throw new ClassifierResourceLimitError('Decision AI input has too many expanded values.');
|
|
153
153
|
let index = 0;
|
|
154
154
|
for (const key of keys) {
|
|
155
155
|
// Omitted wire fields still cost preparation work and snapshot memory.
|
|
@@ -208,7 +208,7 @@ export function checkClassifierJsonWork(text, check, label = 'response') {
|
|
|
208
208
|
quoted = true;
|
|
209
209
|
else if (character === '{' || character === '[') {
|
|
210
210
|
if (++depth > CLASSIFIER_LIMITS.depth)
|
|
211
|
-
throw new ClassifierResourceLimitError(`
|
|
211
|
+
throw new ClassifierResourceLimitError(`Decision AI ${label} exceeds the maximum nesting depth of 64.`);
|
|
212
212
|
separators++;
|
|
213
213
|
}
|
|
214
214
|
else if (character === '}' || character === ']')
|
|
@@ -218,14 +218,14 @@ export function checkClassifierJsonWork(text, check, label = 'response') {
|
|
|
218
218
|
// A conservative token guard bounds JSON.parse allocation. The exact
|
|
219
219
|
// expanded-value guard runs on the parsed object afterward.
|
|
220
220
|
if (separators > CLASSIFIER_LIMITS.values * 2)
|
|
221
|
-
throw new ClassifierResourceLimitError(`
|
|
221
|
+
throw new ClassifierResourceLimitError(`Decision AI ${label} has too many values.`);
|
|
222
222
|
}
|
|
223
223
|
}
|
|
224
224
|
/** Consume decoded response bytes incrementally; Content-Length is not trusted. */
|
|
225
225
|
export async function readClassifierResponse(response, signal, check = () => signal.throwIfAborted(), onBody) {
|
|
226
226
|
const length = response.headers.get('content-length');
|
|
227
227
|
if (length && Number(length) > CLASSIFIER_LIMITS.responseBytes)
|
|
228
|
-
throw new ClassifierResourceLimitError('
|
|
228
|
+
throw new ClassifierResourceLimitError('Decision AI response exceeds the 8 MiB response limit.');
|
|
229
229
|
if (!response.body)
|
|
230
230
|
return JSON.parse('');
|
|
231
231
|
const reader = response.body.getReader();
|
|
@@ -241,7 +241,7 @@ export async function readClassifierResponse(response, signal, check = () => sig
|
|
|
241
241
|
for (;;) {
|
|
242
242
|
check();
|
|
243
243
|
const { done, value } = await reader.read().catch((cause) => {
|
|
244
|
-
throw new ClassifierResponseReadError('
|
|
244
|
+
throw new ClassifierResponseReadError('Decision AI response body could not be read.', { cause });
|
|
245
245
|
});
|
|
246
246
|
check();
|
|
247
247
|
if (done)
|
|
@@ -249,7 +249,7 @@ export async function readClassifierResponse(response, signal, check = () => sig
|
|
|
249
249
|
const chunk = classifierByteView(value);
|
|
250
250
|
bytes += chunk.byteLength;
|
|
251
251
|
if (bytes > CLASSIFIER_LIMITS.responseBytes)
|
|
252
|
-
throw new ClassifierResourceLimitError('
|
|
252
|
+
throw new ClassifierResourceLimitError('Decision AI response exceeds the 8 MiB response limit.');
|
|
253
253
|
pending += decoder.decode(chunk, { stream: true });
|
|
254
254
|
if (pending.length >= 64 * 1024) {
|
|
255
255
|
text.push(pending);
|
|
@@ -18,7 +18,17 @@ export function createOpenAIDecisionRequest(args) {
|
|
|
18
18
|
? state.value
|
|
19
19
|
: JSON.stringify(state.value),
|
|
20
20
|
questions: args.questions.map((question) => {
|
|
21
|
-
|
|
21
|
+
if (question.type === 'box')
|
|
22
|
+
throw new Error('OpenAI Decisions does not support Bounding Box questions.');
|
|
23
|
+
const instructions = question.instructionsMessages
|
|
24
|
+
? question.instructionsMessages.flatMap(({ parts }, index) => [
|
|
25
|
+
...(index ? [{ type: 'input_text', text: '\n\n' }] : []),
|
|
26
|
+
...parts.map((part) => part.type === 'text'
|
|
27
|
+
? { type: 'input_text', text: part.text }
|
|
28
|
+
: { type: 'input_image', image_url: part.dataUrl }),
|
|
29
|
+
])
|
|
30
|
+
: text(question.instructions);
|
|
31
|
+
const common = { name: question.questionId, instructions };
|
|
22
32
|
if (question.type === 'choice')
|
|
23
33
|
return {
|
|
24
34
|
...common,
|
|
@@ -39,7 +49,15 @@ export function createOpenAIDecisionRequest(args) {
|
|
|
39
49
|
...common,
|
|
40
50
|
type: 'predicate',
|
|
41
51
|
instructions: criteria
|
|
42
|
-
?
|
|
52
|
+
? typeof instructions === 'string'
|
|
53
|
+
? `${instructions}\n\nTrue criterion: ${text(criteria.true)}\nFalse criterion: ${text(criteria.false)}`
|
|
54
|
+
: [
|
|
55
|
+
...instructions,
|
|
56
|
+
{
|
|
57
|
+
type: 'input_text',
|
|
58
|
+
text: `\n\nTrue criterion: ${text(criteria.true)}\nFalse criterion: ${text(criteria.false)}`,
|
|
59
|
+
},
|
|
60
|
+
]
|
|
43
61
|
: common.instructions,
|
|
44
62
|
};
|
|
45
63
|
}),
|
|
@@ -13,7 +13,7 @@ export class ClassifierQuestionPreparation {
|
|
|
13
13
|
check = () => {
|
|
14
14
|
this.deadlineCheck();
|
|
15
15
|
if (++this.operations > CLASSIFIER_LIMITS.values * 10)
|
|
16
|
-
throw new ClassifierResourceLimitError('
|
|
16
|
+
throw new ClassifierResourceLimitError('Decision AI question preparation has too much expanded work.');
|
|
17
17
|
};
|
|
18
18
|
capture(value) {
|
|
19
19
|
this.inspect(value, false);
|
|
@@ -35,7 +35,7 @@ export class ClassifierQuestionPreparation {
|
|
|
35
35
|
// Reject before concatenation. Exact UTF-8/JSON bytes are charged when
|
|
36
36
|
// the completed entry is captured; this bounds intermediate allocations.
|
|
37
37
|
if (fragment.length + previousLength > this.budget.remainingBytes)
|
|
38
|
-
throw new ClassifierResourceLimitError('
|
|
38
|
+
throw new ClassifierResourceLimitError('Decision AI question interpolation exceeds its remaining byte budget.');
|
|
39
39
|
};
|
|
40
40
|
processing = (input, name, parameter) => {
|
|
41
41
|
this.check();
|
|
@@ -50,7 +50,7 @@ export class ClassifierQuestionPreparation {
|
|
|
50
50
|
((name === 'chain' || name === 'wrap') && nextWhitespace && !whitespace) ||
|
|
51
51
|
(name !== 'chain' && name !== 'wrap' && input[i] === '\n')) {
|
|
52
52
|
if (++pieces > CLASSIFIER_LIMITS.values)
|
|
53
|
-
throw new ClassifierResourceLimitError('
|
|
53
|
+
throw new ClassifierResourceLimitError('Decision AI interpolation processor has too many expanded pieces.');
|
|
54
54
|
}
|
|
55
55
|
whitespace = nextWhitespace;
|
|
56
56
|
}
|
|
@@ -60,7 +60,7 @@ export class ClassifierQuestionPreparation {
|
|
|
60
60
|
const value = parameter ?? (name === 'indent' ? 0 : 1);
|
|
61
61
|
const prefix = name === 'indent' ? value : name === 'quote' ? value * 2 : (value - 1) * 2 + 2;
|
|
62
62
|
if (!Number.isSafeInteger(value) || value < (name === 'list' ? 1 : 0))
|
|
63
|
-
throw new Error(`Invalid
|
|
63
|
+
throw new Error(`Invalid Decision AI interpolation ${name} parameter.`);
|
|
64
64
|
let lines = 1;
|
|
65
65
|
for (let i = 0; i < input.length; i++) {
|
|
66
66
|
if ((i & 4095) === 0)
|
|
@@ -69,6 +69,6 @@ export class ClassifierQuestionPreparation {
|
|
|
69
69
|
lines++;
|
|
70
70
|
}
|
|
71
71
|
if (input.length + lines * prefix > this.budget.remainingBytes)
|
|
72
|
-
throw new ClassifierResourceLimitError('
|
|
72
|
+
throw new ClassifierResourceLimitError('Decision AI interpolation processor exceeds its remaining byte budget.');
|
|
73
73
|
};
|
|
74
74
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import CryptoJS from 'crypto-js';
|
|
2
|
+
import { validateTokenPricing } from '../tokenPricing.js';
|
|
2
3
|
import stableStringify from 'safe-stable-stringify';
|
|
3
4
|
import { classifierInputDataValue, snapshotClassifierJson } from './json.js';
|
|
4
5
|
import { ClassifierValueBudget } from './limits.js';
|
|
@@ -10,6 +11,7 @@ export const DEFAULT_CLASSIFIER_PROFILE_FAILURE_WINDOW_MS = 300_000;
|
|
|
10
11
|
export const DEFAULT_CLASSIFIER_PROFILE_OPEN_DURATION_MS = 300_000;
|
|
11
12
|
export const classifierProfileInputIds = ['model', 'apiKey'];
|
|
12
13
|
export const classifierProfileDataKeys = [
|
|
14
|
+
'tokenPricing',
|
|
13
15
|
'provider',
|
|
14
16
|
'model',
|
|
15
17
|
'useModelInput',
|
|
@@ -28,7 +30,7 @@ export function pickClassifierProfileData(data) {
|
|
|
28
30
|
function positive(value, fallback, label, maximum = 600_000) {
|
|
29
31
|
const result = value ?? fallback;
|
|
30
32
|
if (!Number.isSafeInteger(result) || result < 1 || result > maximum)
|
|
31
|
-
throw new Error(`
|
|
33
|
+
throw new Error(`Decision AI Profile ${label} must be an integer between 1 and ${maximum}.`);
|
|
32
34
|
return result;
|
|
33
35
|
}
|
|
34
36
|
export function classifierProfileResponseTimeout(configuration) {
|
|
@@ -45,7 +47,7 @@ export function classifierProfileHealthPolicy(configuration) {
|
|
|
45
47
|
};
|
|
46
48
|
}
|
|
47
49
|
export function normalizeClassifierProfileValue(value) {
|
|
48
|
-
return normalizeDetachedProfile(snapshotClassifierJson(value, '
|
|
50
|
+
return normalizeDetachedProfile(snapshotClassifierJson(value, 'Decision AI Profile', new ClassifierValueBudget(), true));
|
|
49
51
|
}
|
|
50
52
|
function normalizeDetachedProfile(value) {
|
|
51
53
|
const profile = value;
|
|
@@ -57,30 +59,32 @@ function normalizeDetachedProfile(value) {
|
|
|
57
59
|
!profile.credential ||
|
|
58
60
|
typeof profile.credential !== 'object' ||
|
|
59
61
|
Array.isArray(profile.credential))
|
|
60
|
-
throw new Error('
|
|
62
|
+
throw new Error('Decision AI Profiles input requires a version 1 Decision AI Profile.');
|
|
61
63
|
const { configuration, credential } = profile;
|
|
62
64
|
if (typeof configuration.provider !== 'string' ||
|
|
63
65
|
typeof configuration.model !== 'string' ||
|
|
64
66
|
!configuration.model.trim())
|
|
65
|
-
throw new Error('
|
|
67
|
+
throw new Error('Decision AI Profile requires a provider and a nonblank model.');
|
|
66
68
|
getClassifierProvider(configuration.provider);
|
|
67
69
|
if (credential.value !== undefined && (typeof credential.value !== 'string' || /[\r\n]/.test(credential.value)))
|
|
68
|
-
throw new Error('
|
|
70
|
+
throw new Error('Decision AI Profile credential must be a string without line breaks.');
|
|
69
71
|
if (profile.profileName !== undefined && typeof profile.profileName !== 'string')
|
|
70
|
-
throw new Error('Invalid
|
|
72
|
+
throw new Error('Invalid Decision AI Profile name.');
|
|
71
73
|
if (profile.sourceNodeId !== undefined && (typeof profile.sourceNodeId !== 'string' || !profile.sourceNodeId.trim()))
|
|
72
|
-
throw new Error('Invalid
|
|
74
|
+
throw new Error('Invalid Decision AI Profile source node.');
|
|
73
75
|
if (configuration.enableCircuitBreaker !== undefined && typeof configuration.enableCircuitBreaker !== 'boolean')
|
|
74
|
-
throw new Error('
|
|
76
|
+
throw new Error('Decision AI Profile automatic suspension must be a boolean.');
|
|
75
77
|
if (configuration.apiKeySource !== undefined &&
|
|
76
78
|
!['configured', 'classifier-settings', 'input'].includes(configuration.apiKeySource))
|
|
77
|
-
throw new Error('Unknown
|
|
79
|
+
throw new Error('Unknown Decision AI API key source.');
|
|
78
80
|
classifierProfileResponseTimeout(configuration);
|
|
79
81
|
classifierProfileHealthPolicy(configuration);
|
|
82
|
+
configuration.tokenPricing = validateTokenPricing(configuration.tokenPricing);
|
|
80
83
|
return {
|
|
81
84
|
version: 1,
|
|
82
|
-
sourceNodeId: profile.sourceNodeId,
|
|
83
|
-
|
|
85
|
+
...(profile.sourceNodeId === undefined ? {} : { sourceNodeId: profile.sourceNodeId }),
|
|
86
|
+
// Blank names are absent, but authored whitespace must survive exact-default display aliases.
|
|
87
|
+
...(profile.profileName?.trim() ? { profileName: profile.profileName } : {}),
|
|
84
88
|
credential: credential.value === undefined ? {} : { value: credential.value.trim() },
|
|
85
89
|
configuration: {
|
|
86
90
|
...pickClassifierProfileData(configuration),
|
|
@@ -92,10 +96,10 @@ function normalizeDetachedProfile(value) {
|
|
|
92
96
|
}
|
|
93
97
|
export function normalizeClassifierProfiles(value, check) {
|
|
94
98
|
if (Array.isArray(value) && (value.length === 0 || value.length > 128))
|
|
95
|
-
throw new Error('
|
|
99
|
+
throw new Error('Decision AI Profiles requires between 1 and 128 profiles.');
|
|
96
100
|
// One deadline-aware traversal bounds, validates and detaches the whole
|
|
97
101
|
// chain. Do not rescan each candidate with a fresh resource budget.
|
|
98
|
-
const detached = snapshotClassifierJson(value, '
|
|
102
|
+
const detached = snapshotClassifierJson(value, 'Decision AI Profiles', new ClassifierValueBudget(check), true);
|
|
99
103
|
return (Array.isArray(detached) ? detached : [detached]).map(normalizeDetachedProfile);
|
|
100
104
|
}
|
|
101
105
|
export function resolveClassifierProfile(data, inputs, context) {
|
|
@@ -104,7 +108,7 @@ export function resolveClassifierProfile(data, inputs, context) {
|
|
|
104
108
|
? classifierInputDataValue(inputs, 'model')?.value
|
|
105
109
|
: data.model?.trim() || provider.defaultModel;
|
|
106
110
|
if (typeof model !== 'string' || !model.trim())
|
|
107
|
-
throw new Error('
|
|
111
|
+
throw new Error('Decision AI Profile model is required.');
|
|
108
112
|
let value;
|
|
109
113
|
// Missing credentials are a candidate failure, not an upstream graph failure.
|
|
110
114
|
// Invalid credential-name configuration still fails while authoring the profile.
|
|
@@ -124,7 +128,12 @@ export function resolveClassifierProfile(data, inputs, context) {
|
|
|
124
128
|
}
|
|
125
129
|
return normalizeClassifierProfileValue({
|
|
126
130
|
version: 1,
|
|
127
|
-
configuration: {
|
|
131
|
+
configuration: {
|
|
132
|
+
...pickClassifierProfileData({ ...data, tokenPricing: validateTokenPricing(data.tokenPricing) }),
|
|
133
|
+
provider: provider.id,
|
|
134
|
+
model,
|
|
135
|
+
useModelInput: false,
|
|
136
|
+
},
|
|
128
137
|
credential: value === undefined ? {} : { value },
|
|
129
138
|
profileName: context.node.title,
|
|
130
139
|
sourceNodeId: context.node.id,
|