@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.
Files changed (80) hide show
  1. package/dist/cjs/bundle.cjs +1438 -824
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/interpolationRuntime.cjs +23 -0
  4. package/dist/cjs/interpolationRuntime.cjs.map +3 -3
  5. package/dist/cjs/serialization.cjs +1 -0
  6. package/dist/cjs/serialization.cjs.map +2 -2
  7. package/dist/cjs/webAppRuntime.cjs +4 -1
  8. package/dist/cjs/webAppRuntime.cjs.map +2 -2
  9. package/dist/esm/exports.js +3 -1
  10. package/dist/esm/index.js +3 -0
  11. package/dist/esm/integrations/CodeRunner.js +6 -3
  12. package/dist/esm/integrations/CodeRunnerNamespace.js +10 -0
  13. package/dist/esm/model/AgentResponseTracePresentation.js +5 -1
  14. package/dist/esm/model/ChildInvocationOwnership.js +51 -0
  15. package/dist/esm/model/DatasetOwnership.js +9 -0
  16. package/dist/esm/model/GraphExecutionState.js +3 -0
  17. package/dist/esm/model/GraphProcessor.js +94 -55
  18. package/dist/esm/model/NodeRegistration.js +2 -6
  19. package/dist/esm/model/RunCostLedger.js +58 -0
  20. package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -2
  21. package/dist/esm/model/chat-v2/chatV2Outputs.js +1 -1
  22. package/dist/esm/model/chat-v2/chatV2Pipeline.js +5 -0
  23. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +3 -0
  24. package/dist/esm/model/chat-v2/llmModelCandidate.js +3 -0
  25. package/dist/esm/model/chat-v2/llmProfile.js +2 -0
  26. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +1 -0
  27. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +2 -1
  28. package/dist/esm/model/chat-v2/modelRegistry.js +12 -3
  29. package/dist/esm/model/classifier/baseten.js +78 -0
  30. package/dist/esm/model/classifier/credentials.js +17 -9
  31. package/dist/esm/model/classifier/images.js +4 -4
  32. package/dist/esm/model/classifier/jev.js +45 -0
  33. package/dist/esm/model/classifier/json.js +1 -1
  34. package/dist/esm/model/classifier/limits.js +13 -13
  35. package/dist/esm/model/classifier/openai.js +20 -2
  36. package/dist/esm/model/classifier/preparation.js +5 -5
  37. package/dist/esm/model/classifier/profile.js +24 -15
  38. package/dist/esm/model/classifier/profileExecution.js +28 -24
  39. package/dist/esm/model/classifier/providers.js +194 -87
  40. package/dist/esm/model/classifier/questionHelpers.js +21 -2
  41. package/dist/esm/model/classifier/questions.js +37 -7
  42. package/dist/esm/model/classifier/response.js +8 -2
  43. package/dist/esm/model/classifier/state.js +2 -2
  44. package/dist/esm/model/classifier/subq.js +51 -0
  45. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +48 -66
  46. package/dist/esm/model/nodes/ClassifierProfileNode.js +11 -9
  47. package/dist/esm/model/nodes/ClassifierQuestionNode.js +53 -34
  48. package/dist/esm/model/tokenPricing.js +52 -0
  49. package/dist/esm/model/tokenPricingEditor.js +9 -0
  50. package/dist/types/exports.d.ts +3 -0
  51. package/dist/types/index.d.ts +1 -1
  52. package/dist/types/integrations/CodeRunner.d.ts +4 -1
  53. package/dist/types/integrations/CodeRunnerNamespace.d.ts +5 -0
  54. package/dist/types/model/AgentResponseTracePresentation.d.ts +2 -0
  55. package/dist/types/model/ChildInvocationOwnership.d.ts +36 -0
  56. package/dist/types/model/DatasetOwnership.d.ts +5 -0
  57. package/dist/types/model/GraphExecutionState.d.ts +2 -0
  58. package/dist/types/model/GraphProcessor.d.ts +3 -0
  59. package/dist/types/model/RunCostLedger.d.ts +19 -0
  60. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +1 -1
  61. package/dist/types/model/chat-v2/chatV2Types.d.ts +2 -0
  62. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +3 -1
  63. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +7 -5
  64. package/dist/types/model/chat-v2/modelRegistry.d.ts +7 -1
  65. package/dist/types/model/classifier/baseten.d.ts +8 -0
  66. package/dist/types/model/classifier/credentials.d.ts +2 -0
  67. package/dist/types/model/classifier/jev.d.ts +9 -0
  68. package/dist/types/model/classifier/profile.d.ts +3 -1
  69. package/dist/types/model/classifier/profileExecution.d.ts +2 -1
  70. package/dist/types/model/classifier/providers.d.ts +30 -6
  71. package/dist/types/model/classifier/questionHelpers.d.ts +3 -1
  72. package/dist/types/model/classifier/questions.d.ts +2 -1
  73. package/dist/types/model/classifier/state.d.ts +1 -0
  74. package/dist/types/model/classifier/subq.d.ts +8 -0
  75. package/dist/types/model/classifier/types.d.ts +9 -2
  76. package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +2 -4
  77. package/dist/types/model/nodes/ClassifierQuestionNode.d.ts +2 -2
  78. package/dist/types/model/tokenPricing.d.ts +18 -0
  79. package/dist/types/model/tokenPricingEditor.d.ts +4 -0
  80. package/package.json +2 -2
@@ -1,11 +1,15 @@
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';
1
+ import { calculateTokenUsageCost, isReportedTokenCount, validateTokenPricing, } from '../tokenPricing.js';
2
+ import { JEV_DEFAULT_CREDENTIAL_NAMES, LIQUID_DEFAULT_CREDENTIAL_NAMES, OPENAI_DEFAULT_CREDENTIAL_NAMES, OPENROUTER_DEFAULT_CREDENTIAL_NAMES, PERPLEXITY_DEFAULT_CREDENTIAL_NAMES, SUBQ_DEFAULT_CREDENTIAL_NAMES, BASETEN_DEFAULT_CREDENTIAL_NAMES, } from './credentials.js';
2
3
  import { assertLiquidImageLimits } from './images.js';
3
- import { prepareClassifierState, systemOneState, } from './state.js';
4
+ import { prepareClassifierState, inspectStateMessages, systemOneState, } from './state.js';
4
5
  import { validateClassifierEvaluationResponse } from './response.js';
5
6
  import { createOpenAIDecisionRequest, validateOpenAIDecisionResponse } from './openai.js';
6
7
  import { assertPerplexityDecisionLimits, perplexityDecisionState, PERPLEXITY_DECISION_MODELS } from './perplexity.js';
7
- import { prepareClassifierQuestion } from './questions.js';
8
+ import { prepareClassifierQuestion, createQuestionMap } from './questions.js';
9
+ import { assertJevImageLimits, JEV_IMAGE_MODELS, JEV_BOX_MODELS, createJevDecisionRequest } from './jev.js';
10
+ import { assertSubQDecisionLimits, SUBQ_DECISION_MODELS, subqDecisionState } from './subq.js';
8
11
  import { classifierArrayValues } from './json.js';
12
+ import { assertBasetenDecisionLimits, BASETEN_DECISION_MODELS, basetenDecisionState } from './baseten.js';
9
13
  import { assertClassifierResourceLimits, ClassifierValueBudget, CLASSIFIER_LIMITS, ClassifierResourceLimitError, ClassifierResponseReadError, readClassifierResponse, } from './limits.js';
10
14
  export { validateApiCompatibleClassifierResponse } from './response.js';
11
15
  export const JEV_SYSTEM_ONE_ENDPOINT = 'https://api.typesafe.ai/v1/systemone';
@@ -13,14 +17,16 @@ export const LIQUID_SYSTEM_ONE_ENDPOINT = 'https://api.liquid.ai/decisions/v1/sy
13
17
  export const OPENAI_DECISIONS_ENDPOINT = 'https://api.openai.com/v1/decisions';
14
18
  export const OPENROUTER_DECISIONS_ENDPOINT = 'https://openrouter.ai/api/alpha/decisions';
15
19
  export const PERPLEXITY_DECISIONS_ENDPOINT = 'https://api.perplexity.ai/v1/decisions';
16
- /** Jev's published USD rates. Keep this Core-owned rather than graph-authored. */
20
+ export const SUBQ_DECISIONS_ENDPOINT = 'https://api.subq.ai/v1/systemone';
21
+ export const BASETEN_DECISIONS_ENDPOINT = 'https://inference.baseten.co/v1/systemone';
22
+ /** Jev 1.13/1.14 USD rates, verified 2026-10-24: https://docs.typesafe.ai/models */
17
23
  export const JEV_TOKEN_PRICING = {
18
24
  inputPerMillionTokens: 0.042,
19
25
  outputPerMillionTokens: 0,
20
26
  };
21
- /** Liquid d1's published USD rates: https://www.liquid.ai/blog/d1-decision-model */
27
+ /** Liquid d1 USD rates, verified 2026-10-26: https://www.liquid.ai/pricing */
22
28
  export const LIQUID_TOKEN_PRICING = {
23
- inputPerMillionTokens: 0.04,
29
+ inputPerMillionTokens: 0.02,
24
30
  outputPerMillionTokens: 0,
25
31
  };
26
32
  const TOKENS_PER_MILLION = 1_000_000;
@@ -46,22 +52,46 @@ export function createApiCompatibleClassifierProvider(config) {
46
52
  validateResponse: validateClassifierEvaluationResponse,
47
53
  });
48
54
  }
49
- export const jevClassifierProvider = createApiCompatibleClassifierProvider({
55
+ export const jevClassifierProvider = createClassifierProvider({
50
56
  id: 'jev',
51
57
  label: 'Jev',
52
58
  defaultModel: 'jev-latest',
59
+ modelOptions: ['jev-latest', 'jev-preview', 'jev-1.14.0', 'jev-1.13.0'].map((value) => ({ value, label: value })),
60
+ modelHelp: 'Jev images are experimental: use still PNG/JPEG, 280–1568 pixels per side. Image requests enable TypeSafe’s experimental image API.',
53
61
  credentialNames: JEV_DEFAULT_CREDENTIAL_NAMES,
54
62
  endpoint: JEV_SYSTEM_ONE_ENDPOINT,
55
- modelPricing: [{ models: ['jev-latest', 'jev-preview', 'jev-1.13.0'], pricing: JEV_TOKEN_PRICING }],
63
+ browserExecutionSupported: false,
64
+ modelPricing: [{ models: ['jev-latest', 'jev-preview', 'jev-1.13.0', 'jev-1.14.0'], pricing: JEV_TOKEN_PRICING }],
65
+ supportsImages: (model) => JEV_IMAGE_MODELS.includes(model),
66
+ supportsQuestionImages: (model) => JEV_IMAGE_MODELS.includes(model),
67
+ supportsBoxQuestions: (model) => JEV_BOX_MODELS.includes(model),
68
+ checkState: (state, check) => {
69
+ if (state.kind === 'messages')
70
+ assertJevImageLimits(state.images, check);
71
+ },
72
+ checkRequest: ({ questions }, check) => {
73
+ for (const question of questions)
74
+ if (question.instructionsMessages)
75
+ assertJevImageLimits(inspectStateMessages(question.instructionsMessages, check), check);
76
+ },
77
+ buildRequest: createJevDecisionRequest,
78
+ requestHeaders: ({ state, questions }) => (state.kind === 'messages' && state.images.length) ||
79
+ questions.some((question) => question.type === 'box' ||
80
+ question.instructionsMessages?.some(({ parts }) => parts.some((part) => part.type === 'image')))
81
+ ? { 'TypeSafe-Danger-Zone-Images': 'true' }
82
+ : {},
83
+ validateResponse: validateClassifierEvaluationResponse,
56
84
  });
57
85
  export const liquidClassifierProvider = createApiCompatibleClassifierProvider({
58
86
  id: 'liquid',
59
87
  label: 'Liquid AI',
60
88
  defaultModel: 'd1',
89
+ modelOptions: ['d1', 'd1.1'].map((value) => ({ value, label: value })),
90
+ modelHelp: 'Images belong in shared State, not Question Instructions.',
61
91
  credentialNames: LIQUID_DEFAULT_CREDENTIAL_NAMES,
62
92
  endpoint: LIQUID_SYSTEM_ONE_ENDPOINT,
63
93
  modelPricing: [{ models: ['d1'], pricing: LIQUID_TOKEN_PRICING }],
64
- supportsImages: (model) => model === 'd1',
94
+ supportsImages: (model) => model === 'd1' || model === 'd1.1',
65
95
  maxRequestBytes: 4_500_000,
66
96
  checkState: (state, check) => {
67
97
  if (state.kind === 'messages')
@@ -75,6 +105,7 @@ export const openrouterClassifierProvider = createApiCompatibleClassifierProvide
75
105
  id: 'openrouter',
76
106
  label: 'OpenRouter',
77
107
  defaultModel: 'microsoft/microsoft-decision-1',
108
+ modelOptions: [{ value: 'microsoft/microsoft-decision-1', label: 'Microsoft Decision-1' }],
78
109
  credentialNames: OPENROUTER_DEFAULT_CREDENTIAL_NAMES,
79
110
  endpoint: OPENROUTER_DECISIONS_ENDPOINT,
80
111
  modelPricing: [
@@ -91,10 +122,12 @@ export const openaiClassifierProvider = createClassifierProvider({
91
122
  id: 'openai',
92
123
  label: 'OpenAI',
93
124
  defaultModel: 'gpt-6-luna',
125
+ modelOptions: [{ value: 'gpt-6-luna', label: 'gpt-6-luna' }],
94
126
  credentialNames: OPENAI_DEFAULT_CREDENTIAL_NAMES,
95
127
  browserExecutionSupported: false,
96
128
  endpoint: OPENAI_DECISIONS_ENDPOINT,
97
129
  supportsImages: (model) => model === 'gpt-6-luna',
130
+ supportsQuestionImages: (model) => model === 'gpt-6-luna',
98
131
  modelPricing: [
99
132
  {
100
133
  models: ['gpt-6-luna'],
@@ -113,6 +146,7 @@ export const perplexityClassifierProvider = createClassifierProvider({
113
146
  id: 'perplexity',
114
147
  label: 'Perplexity',
115
148
  defaultModel: 'pplx-decider-v1.1-27b',
149
+ modelOptions: PERPLEXITY_DECISION_MODELS.map((value) => ({ value, label: value })),
116
150
  credentialNames: PERPLEXITY_DEFAULT_CREDENTIAL_NAMES,
117
151
  browserExecutionSupported: false,
118
152
  endpoint: PERPLEXITY_DECISIONS_ENDPOINT,
@@ -131,6 +165,51 @@ export const perplexityClassifierProvider = createClassifierProvider({
131
165
  }),
132
166
  validateResponse: validateClassifierEvaluationResponse,
133
167
  });
168
+ /** Current model catalog rate, not the older launch article's $0.05/MTok.
169
+ * https://docs.subq.ai/using-the-api/models/ (verified 2026-10-24).
170
+ */
171
+ export const subqClassifierProvider = createClassifierProvider({
172
+ id: 'subq',
173
+ label: 'SubQ',
174
+ defaultModel: 'subq-snap-1.1',
175
+ modelOptions: SUBQ_DECISION_MODELS.map((value) => ({ value, label: value })),
176
+ credentialNames: SUBQ_DEFAULT_CREDENTIAL_NAMES,
177
+ browserExecutionSupported: false,
178
+ endpoint: SUBQ_DECISIONS_ENDPOINT,
179
+ supportsImages: (model) => SUBQ_DECISION_MODELS.includes(model),
180
+ modelPricing: [{ models: SUBQ_DECISION_MODELS, pricing: { inputPerMillionTokens: 0.04, outputPerMillionTokens: 0 } }],
181
+ maxRequestBytes: 13 * 1024 * 1024,
182
+ checkRequest: assertSubQDecisionLimits,
183
+ buildRequest: ({ model, state, questions }) => ({
184
+ model,
185
+ ...subqDecisionState(state),
186
+ questions: createQuestionMap(questions),
187
+ }),
188
+ validateResponse: validateClassifierEvaluationResponse,
189
+ });
190
+ /** Native Baseten API reference uses Bearer authentication (not dedicated-deployment Api-Key). */
191
+ export const basetenClassifierProvider = createClassifierProvider({
192
+ id: 'baseten',
193
+ label: 'Baseten',
194
+ defaultModel: BASETEN_DECISION_MODELS[0],
195
+ modelOptions: [
196
+ { value: BASETEN_DECISION_MODELS[0], label: 'Elephant-1' },
197
+ { value: BASETEN_DECISION_MODELS[1], label: 'Mammoth-1' },
198
+ ],
199
+ modelHelp: 'Images belong in shared State, not Question Instructions.',
200
+ credentialNames: BASETEN_DEFAULT_CREDENTIAL_NAMES,
201
+ browserExecutionSupported: false,
202
+ endpoint: BASETEN_DECISIONS_ENDPOINT,
203
+ supportsImages: (model) => BASETEN_DECISION_MODELS.some((id) => id === model),
204
+ checkRequest: assertBasetenDecisionLimits,
205
+ buildRequest: ({ model, state, questions }) => ({
206
+ model,
207
+ state: basetenDecisionState(state),
208
+ questions: createQuestionMap(questions),
209
+ }),
210
+ validateResponse: validateClassifierEvaluationResponse,
211
+ // A temporary free promotion is not permanent pricing. Unknown cost stays unknown.
212
+ });
134
213
  /** Ordered so adding compatible providers does not alter authored IDs. */
135
214
  export const classifierProviders = [
136
215
  jevClassifierProvider,
@@ -138,6 +217,8 @@ export const classifierProviders = [
138
217
  openaiClassifierProvider,
139
218
  openrouterClassifierProvider,
140
219
  perplexityClassifierProvider,
220
+ subqClassifierProvider,
221
+ basetenClassifierProvider,
141
222
  ];
142
223
  export class ClassifierProviderError extends Error {
143
224
  kind;
@@ -146,7 +227,7 @@ export class ClassifierProviderError extends Error {
146
227
  super(message, options);
147
228
  this.kind = kind;
148
229
  this.statusCode = statusCode;
149
- this.name = 'ClassifierProviderError';
230
+ this.name = 'DecisionAIProviderError';
150
231
  }
151
232
  }
152
233
  export function classifierFailureKind(kind, status) {
@@ -155,57 +236,61 @@ export function classifierFailureKind(kind, status) {
155
236
  /** Bounded preparation/provider explanation, without traversing causes or capturing response bodies. */
156
237
  export function classifierErrorMessage(error, apiKey) {
157
238
  try {
158
- const text = error instanceof Error ? error.message : typeof error === 'string' ? error : 'Classifier request failed.';
239
+ const text = error instanceof Error ? error.message : typeof error === 'string' ? error : 'Decision AI request failed.';
159
240
  return (apiKey ? text.split(apiKey).join('[redacted]') : text).slice(0, 2000);
160
241
  }
161
242
  catch {
162
- return 'Classifier request failed with unreadable error metadata.';
243
+ return 'Decision AI request failed with unreadable error metadata.';
163
244
  }
164
245
  }
165
246
  function createOperation(args, label) {
166
- if (!Number.isFinite(args.timeoutMs) ||
167
- args.timeoutMs <= 0 ||
247
+ if ((args.timeoutMs !== undefined && (!Number.isFinite(args.timeoutMs) || args.timeoutMs <= 0)) ||
168
248
  (args.deadline !== undefined && !Number.isFinite(args.deadline)))
169
- throw new Error('Classifier timeout and deadline must be finite, with a positive timeout.');
249
+ throw new Error('Decision AI timeout and deadline must be finite, with a positive timeout.');
170
250
  const now = Date.now();
171
- const deadline = Math.min(now + args.timeoutMs, args.deadline ?? Infinity);
251
+ const deadline = Math.min(args.timeoutMs === undefined ? Infinity : now + args.timeoutMs, args.deadline ?? Infinity);
172
252
  // 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');
253
+ if (Number.isFinite(deadline) && deadline - now > MAX_TIMER_DELAY_MS)
254
+ throw new Error(`Decision AI effective timeout must not exceed ${MAX_TIMER_DELAY_MS} ms.`);
255
+ const timeoutMessage = `${label} request timed out${args.timeoutMs === undefined ? '' : ` after ${args.timeoutMs} ms`}.`;
176
256
  return {
177
257
  signal: args.signal,
178
258
  deadline,
259
+ timeoutMessage,
179
260
  check(attemptSignal) {
180
261
  throwIfAborted(args.signal, label);
181
262
  if (Date.now() >= deadline || attemptSignal?.aborted)
182
- throw timeoutError();
263
+ throw new ClassifierProviderError(timeoutMessage, 'timeout');
183
264
  },
184
265
  };
185
266
  }
186
267
  /** A plain specification and one runner for both graph and direct provider inputs. */
187
268
  function createClassifierProvider(spec) {
188
- const { endpoint, buildRequest, validateResponse, checkState, checkRequest, ...provider } = spec;
269
+ const { endpoint, buildRequest, requestHeaders, validateResponse, checkState, checkRequest, ...provider } = spec;
189
270
  const evaluate = async (input) => {
190
271
  // Reject removed evidence fields before object spread can read a getter or
191
272
  // discard non-enumerable/inherited content.
192
273
  if ('images' in input)
193
274
  throw new Error('Pass image evidence through State, not a separate images field.');
194
- const args = { ...input, fetchImplementation: input.fetchImplementation ?? fetch };
275
+ const args = {
276
+ ...input,
277
+ tokenPricing: validateTokenPricing(input.tokenPricing),
278
+ fetchImplementation: input.fetchImplementation ?? fetch,
279
+ };
195
280
  const operation = createOperation(args, provider.label);
196
281
  operation.check();
197
282
  if (typeof args.model !== 'string')
198
- throw new Error('Classifier model must be a nonblank string.');
283
+ throw new Error('Decision AI model must be a nonblank string.');
199
284
  const budget = new ClassifierValueBudget(operation.check, provider.maxRequestBytes);
200
285
  budget.inspect(args.model);
201
286
  if (args.model.trim() === '')
202
- throw new Error('Classifier model must be a nonblank string.');
287
+ throw new Error('Decision AI model must be a nonblank string.');
203
288
  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.');
289
+ throw new Error('Decision AI API key must be a nonblank string without line breaks.');
205
290
  if (!Array.isArray(args.questions) || args.questions.length === 0)
206
- throw new Error('Classifier Evaluate requires at least one question.');
291
+ throw new Error('Decision AI run requires at least one question.');
207
292
  if (args.questions.length > CLASSIFIER_LIMITS.questions)
208
- throw new Error('Classifier Evaluate supports at most 1000 questions.');
293
+ throw new Error('Decision AI run supports at most 1000 questions.');
209
294
  const state = prepareClassifierState(args, budget);
210
295
  const questions = [];
211
296
  const ids = new Set();
@@ -216,18 +301,35 @@ function createClassifierProvider(spec) {
216
301
  ids.add(question.questionId);
217
302
  questions.push(question);
218
303
  }
304
+ let imageCount = state.kind === 'messages' ? state.images.length : 0;
305
+ for (const question of questions) {
306
+ const images = question.instructionsMessages
307
+ ? inspectStateMessages(question.instructionsMessages, operation.check)
308
+ : [];
309
+ imageCount += images.length;
310
+ if (question.type === 'box') {
311
+ if (!provider.supportsBoxQuestions?.(args.model))
312
+ throw new ClassifierProviderError(`${provider.label} model '${args.model}' does not support Bounding Box questions.`, 'capability');
313
+ if (!(state.kind === 'messages' && state.images.length) && !images.length)
314
+ throw new ClassifierProviderError(`Bounding Box question '${question.questionId}' requires an image in shared State or its own Instructions.`, 'capability');
315
+ }
316
+ if (images.length && !provider.supportsQuestionImages?.(args.model))
317
+ throw new ClassifierProviderError(`${provider.label} model '${args.model}' does not support images in question instructions. Use a compatible Jev or OpenAI profile.`, 'capability');
318
+ }
319
+ if (imageCount > 128)
320
+ throw new Error('State and questions together must contain at most 128 images.');
219
321
  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');
322
+ throw new ClassifierProviderError(`${provider.label} model '${args.model}' does not support Decision AI images.`, 'capability');
221
323
  try {
222
324
  checkState?.(state, operation.check);
223
325
  checkRequest?.({ model: args.model, state, questions }, operation.check);
224
326
  }
225
327
  catch (error) {
226
328
  operation.check();
227
- throw new ClassifierProviderError(error instanceof Error ? error.message : `${provider.label} does not support this classifier evidence.`, 'capability', undefined, { cause: error });
329
+ throw new ClassifierProviderError(error instanceof Error ? error.message : `${provider.label} does not support this Decision AI evidence.`, 'capability', undefined, { cause: error });
228
330
  }
229
331
  operation.check();
230
- const result = await callClassifierHttp(args, { ...provider, endpoint, validateResponse }, { model: args.model, state, questions }, buildRequest, operation);
332
+ const result = await callClassifierHttp(args, { ...provider, endpoint, requestHeaders, validateResponse }, { model: args.model, state, questions }, buildRequest, operation);
231
333
  operation.check();
232
334
  return result;
233
335
  };
@@ -237,10 +339,15 @@ function normalizeModelPricing(provider) {
237
339
  return (provider.modelPricing ??
238
340
  (provider.pricing && provider.defaultModel ? [{ models: [provider.defaultModel], pricing: provider.pricing }] : []));
239
341
  }
342
+ export function getClassifierSystemTokenPricing(providerId, model) {
343
+ const provider = getClassifierProvider(providerId);
344
+ return normalizeModelPricing(provider).find((entry) => entry.models.includes(model?.trim() || provider.defaultModel))
345
+ ?.pricing;
346
+ }
240
347
  export function getClassifierProvider(id) {
241
348
  const provider = classifierProviders.find((candidate) => candidate.id === (id || jevClassifierProvider.id));
242
349
  if (!provider)
243
- throw new Error(`Unknown classifier provider '${id}'.`);
350
+ throw new Error(`Unknown Decision AI provider '${id}'.`);
244
351
  return provider;
245
352
  }
246
353
  export function getClassifierProviderEnvironmentVariableNames() {
@@ -253,7 +360,12 @@ export function getClassifierProviderEnvironmentVariableNames() {
253
360
  * count or add image tokens again. Decisions has no separate cache charges.
254
361
  * Callers must not treat an unpriced provider as free.
255
362
  */
256
- export function calculateClassifierUsageCost(provider, usage, models) {
363
+ export function calculateClassifierUsageCost(provider, usage, models, tokenPricing) {
364
+ if (tokenPricing !== undefined)
365
+ return calculateTokenUsageCost(tokenPricing, {
366
+ inputTokens: usage.input_tokens,
367
+ outputTokens: usage.output_tokens,
368
+ });
257
369
  if (!models)
258
370
  return undefined;
259
371
  const entries = normalizeModelPricing(provider);
@@ -268,10 +380,8 @@ export function calculateClassifierUsageCost(provider, usage, models) {
268
380
  !validRates(base) ||
269
381
  (tier != null &&
270
382
  (!Number.isSafeInteger(tier.aboveInputTokens) || tier.aboveInputTokens < 0 || !validRates(tier))) ||
271
- !Number.isSafeInteger(usage.input_tokens) ||
272
- usage.input_tokens < 0 ||
273
- !Number.isSafeInteger(usage.output_tokens) ||
274
- usage.output_tokens < 0) {
383
+ !isReportedTokenCount(usage.input_tokens) ||
384
+ !isReportedTokenCount(usage.output_tokens)) {
275
385
  return undefined;
276
386
  }
277
387
  const pricing = tier && usage.input_tokens > tier.aboveInputTokens ? tier : base;
@@ -279,21 +389,12 @@ export function calculateClassifierUsageCost(provider, usage, models) {
279
389
  TOKENS_PER_MILLION;
280
390
  return Number.isFinite(totalCost) && totalCost >= 0 ? totalCost : undefined;
281
391
  }
282
- function createQuestionMap(questions) {
283
- const result = Object.create(null);
284
- for (const question of questions) {
285
- const providerQuestion = question.type === 'noul' && question.criteria === undefined
286
- ? { type: question.type, instructions: question.instructions }
287
- : { type: question.type, instructions: question.instructions, criteria: question.criteria };
288
- Object.defineProperty(result, question.questionId, { enumerable: true, value: providerQuestion });
289
- }
290
- return result;
291
- }
292
392
  async function callClassifierHttp(args, spec, prepared, buildRequest, operation) {
293
393
  const { apiKey, fetchImplementation, retryOnNon200, retryOnNon200CooldownMs, retryOnNon200RepeatTimes } = args;
294
394
  const { endpoint, label: providerLabel, validateResponse, maxRequestBytes } = spec;
295
- const { signal, deadline } = operation;
395
+ const { signal, deadline, timeoutMessage } = operation;
296
396
  const request = buildRequest(prepared);
397
+ const requestHeaders = spec.requestHeaders?.(prepared);
297
398
  const configuredRetryCount = retryOnNon200 ? normalizeClassifierNon200RetryCount(retryOnNon200RepeatTimes) : 0;
298
399
  const configuredCooldownMs = normalizeClassifierNon200RetryCooldownMs(retryOnNon200CooldownMs);
299
400
  let automaticRetryCount = 0;
@@ -342,7 +443,9 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
342
443
  const controller = new AbortController();
343
444
  const onAbort = () => controller.abort(signal.reason);
344
445
  signal.addEventListener('abort', onAbort, { once: true });
345
- const timer = setTimeout(() => controller.abort(new Error(`${providerLabel} request timeout`)), remainingMs);
446
+ const timer = Number.isFinite(remainingMs)
447
+ ? setTimeout(() => controller.abort(new Error(`${providerLabel} request timeout`)), remainingMs)
448
+ : undefined;
346
449
  const cleanupAttempt = () => {
347
450
  clearTimeout(timer);
348
451
  signal.removeEventListener('abort', onAbort);
@@ -353,7 +456,7 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
353
456
  response = await waitForAttempt(fetchImplementation(endpoint, {
354
457
  method: 'POST',
355
458
  redirect: 'error',
356
- headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
459
+ headers: { ...requestHeaders, Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
357
460
  body: requestJson,
358
461
  signal: controller.signal,
359
462
  }), controller.signal, discardResponseBody);
@@ -365,9 +468,7 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
365
468
  operation.check();
366
469
  }
367
470
  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.`);
471
+ report('failure', undefined, kind, undefined, kind === 'timeout' ? timeoutMessage : `${providerLabel} transport request failed.`);
371
472
  operation.check(controller.signal);
372
473
  if (automaticRetryCount >= MAX_AUTOMATIC_ATTEMPTS - 1) {
373
474
  throw new ClassifierProviderError(`${providerLabel} request failed after ${MAX_AUTOMATIC_ATTEMPTS} attempts due to a transport error.`, 'transport', undefined, { cause: error });
@@ -382,15 +483,18 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
382
483
  catch (error) {
383
484
  cleanupAttempt();
384
485
  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.`);
486
+ report(signal.aborted ? 'aborted' : 'failure', response.status, signal.aborted ? undefined : 'timeout', undefined, signal.aborted ? `${providerLabel} request was canceled.` : timeoutMessage);
388
487
  throw error;
389
488
  }
390
489
  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}).`);
490
+ // A valid key can lack access to a model. Do not diagnose 403 as an invalid key.
491
+ const accessDeniedMessage = response.status === 403
492
+ ? `${providerLabel} access denied (HTTP 403). Check API key permissions and requested model access.`
493
+ : undefined;
494
+ report('failure', response.status, 'http', undefined, accessDeniedMessage ??
495
+ (response.status === 401
496
+ ? `${providerLabel} authentication failed (HTTP ${response.status}). Check the ${providerLabel} API key.`
497
+ : `${providerLabel} rejected the request (HTTP ${response.status}).`));
394
498
  const retryable = RETRYABLE_STATUSES.has(response.status);
395
499
  const permanent = [400, 401, 402, 403, 413, 422].includes(response.status);
396
500
  const willRetry = (retryable && automaticRetryCount < MAX_AUTOMATIC_ATTEMPTS - 1) ||
@@ -415,7 +519,7 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
415
519
  // neither the final error nor the next bounded retry may depend on it.
416
520
  discardResponseBody(response);
417
521
  // Diagnostic collection introduces an await after receiving the rejection.
418
- // Caller cancellation and the overall deadline still outrank HTTP suppression.
522
+ // Caller cancellation and any active request deadline outrank HTTP suppression.
419
523
  // Do not check the diagnostic-only controller: its 1 s cap preserves the HTTP error.
420
524
  operation.check();
421
525
  if (willRetry) {
@@ -432,7 +536,7 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
432
536
  continue;
433
537
  }
434
538
  if (response.status === 401 || response.status === 403) {
435
- throw new ClassifierProviderError(`${providerLabel} authentication failed. Check the ${providerLabel} API key.`, 'http', response.status);
539
+ throw new ClassifierProviderError(accessDeniedMessage ?? `${providerLabel} authentication failed. Check the ${providerLabel} API key.`, 'http', response.status);
436
540
  }
437
541
  // Repeating an unchanged invalid/oversized request or an unfunded account
438
542
  // cannot recover. These remain HTTP failures so profile fallback works.
@@ -458,7 +562,7 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
458
562
  ? 'transport'
459
563
  : 'response-parsing';
460
564
  report('failure', response.status, kind, undefined, kind === 'timeout'
461
- ? `${providerLabel} request timed out after ${args.timeoutMs} ms.`
565
+ ? timeoutMessage
462
566
  : error instanceof ClassifierResourceLimitError
463
567
  ? error.message
464
568
  : kind === 'transport'
@@ -480,10 +584,10 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
480
584
  validatedResponse = validateResponse(body, prepared.questions, providerLabel);
481
585
  }
482
586
  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 });
587
+ report('failure', response.status, 'response-validation', classifierAttemptUsage(body, spec, args.model, args.tokenPricing), error instanceof Error ? error.message : `${providerLabel} returned an invalid Decision AI response.`);
588
+ throw new ClassifierProviderError(error instanceof Error ? error.message : `${providerLabel} returned an invalid Decision AI response.`, 'response-validation', undefined, { cause: error });
485
589
  }
486
- report('success', response.status, undefined, classifierAttemptUsage(body, spec, args.model));
590
+ report('success', response.status, undefined, classifierAttemptUsage(body, spec, args.model, args.tokenPricing));
487
591
  return {
488
592
  // Preserve the direct-provider result contract, but graph runs with the
489
593
  // diagnostic disabled never allocate this second representation.
@@ -501,7 +605,7 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
501
605
  }
502
606
  }
503
607
  /** The bounded reader produced plain JSON; do not require valid answers to retain usable usage. */
504
- function classifierAttemptUsage(body, provider, requestedModel) {
608
+ function classifierAttemptUsage(body, provider, requestedModel, tokenPricing) {
505
609
  if (!body || typeof body !== 'object' || Array.isArray(body) || !Object.hasOwn(body, 'usage'))
506
610
  return;
507
611
  const { usage, model } = body;
@@ -510,13 +614,11 @@ function classifierAttemptUsage(body, provider, requestedModel) {
510
614
  Array.isArray(usage) ||
511
615
  !Object.hasOwn(usage, 'input_tokens') ||
512
616
  !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)
617
+ !isReportedTokenCount(usage.input_tokens) ||
618
+ !isReportedTokenCount(usage.output_tokens))
517
619
  return;
518
620
  const estimatedCostUsd = typeof model === 'string' && Object.hasOwn(body, 'model')
519
- ? calculateClassifierUsageCost(provider, usage, { requestedModel, responseModel: model })
621
+ ? calculateClassifierUsageCost(provider, usage, { requestedModel, responseModel: model }, tokenPricing)
520
622
  : undefined;
521
623
  return {
522
624
  inputTokens: usage.input_tokens,
@@ -574,24 +676,29 @@ function throwIfAborted(signal, providerLabel) {
574
676
  function throwAbort(signal, providerLabel) {
575
677
  throw signal.reason instanceof Error ? signal.reason : new Error(`${providerLabel} request aborted.`);
576
678
  }
577
- function waitForRetry(delayMs, signal, providerLabel) {
679
+ async function waitForRetry(delayMs, signal, providerLabel) {
578
680
  throwIfAborted(signal, providerLabel);
579
- if (delayMs <= 0)
580
- return Promise.resolve();
581
- return new Promise((resolve, reject) => {
582
- const onAbort = () => {
583
- clearTimeout(timer);
584
- signal.removeEventListener('abort', onAbort);
585
- reject(signal.reason instanceof Error ? signal.reason : new Error(`${providerLabel} request aborted.`));
586
- };
587
- const timer = setTimeout(() => {
588
- signal.removeEventListener('abort', onAbort);
589
- resolve();
590
- }, delayMs);
591
- signal.addEventListener('abort', onAbort, { once: true });
592
- if (signal.aborted)
593
- onAbort();
594
- });
681
+ // Without a request deadline, authored/provider waits can exceed one timer.
682
+ // Chunk the wait instead of overflowing to 1 ms or retrying before it expires.
683
+ while (delayMs > 0) {
684
+ const chunkMs = Math.min(delayMs, MAX_TIMER_DELAY_MS);
685
+ await new Promise((resolve, reject) => {
686
+ const onAbort = () => {
687
+ clearTimeout(timer);
688
+ signal.removeEventListener('abort', onAbort);
689
+ reject(signal.reason instanceof Error ? signal.reason : new Error(`${providerLabel} request aborted.`));
690
+ };
691
+ const timer = setTimeout(() => {
692
+ signal.removeEventListener('abort', onAbort);
693
+ resolve();
694
+ }, chunkMs);
695
+ signal.addEventListener('abort', onAbort, { once: true });
696
+ if (signal.aborted)
697
+ onAbort();
698
+ });
699
+ throwIfAborted(signal, providerLabel);
700
+ delayMs -= chunkMs;
701
+ }
595
702
  }
596
703
  function getRetryDelayMs(retryAfter, attempt, deadline) {
597
704
  let requestedMs;
@@ -3,18 +3,37 @@ import { extractInterpolationVariableReferences, getInterpolationGlobalValues, i
3
3
  import { interpolateJsonTemplate } from '../nodes/ObjectNode.js';
4
4
  import { assertClassifierEntry, classifierDataProperty } from './json.js';
5
5
  import { checkClassifierJsonWork } from './limits.js';
6
+ import { normalizeClassifierState } from './state.js';
6
7
  export { assertClassifierEntry, assertClassifierInstructions } from './json.js';
7
8
  const STRUCTURED_ENTRY_TYPES = ['string', 'object', 'object[]', 'any', 'any[]'];
8
9
  export function getInstructionsInputDefinition() {
9
10
  return {
10
11
  id: 'instructions',
11
12
  title: 'Instructions',
12
- dataType: STRUCTURED_ENTRY_TYPES,
13
+ dataType: [...STRUCTURED_ENTRY_TYPES, 'string[]', 'image', 'image[]', 'chat-message', 'chat-message[]'],
13
14
  required: true,
14
15
  splitRunBehavior: 'preserve-array',
15
- description: 'String or JSON structure describing the independent question.',
16
+ description: 'Text/JSON, an image, or assembled User messages. Question images require Jev or OpenAI.',
16
17
  };
17
18
  }
19
+ /** Reuse State's bounded native-image/message normalization, without promoting content to shared State. */
20
+ export function getQuestionInstructionsInput(inputs, preparation) {
21
+ const input = classifierDataProperty(inputs, 'instructions', 'Instructions');
22
+ if (!input)
23
+ throw new Error('Instructions input is required.');
24
+ const normalized = normalizeClassifierState(input, preparation.check);
25
+ if (normalized.stateMessages &&
26
+ (input.type !== 'string[]' ||
27
+ normalized.stateMessages.some(({ parts }) => parts.some((part) => part.type === 'image'))))
28
+ return { instructions: '', instructionsMessages: normalized.stateMessages };
29
+ if (input.type === 'image[]' || input.type === 'chat-message[]')
30
+ throw new Error('Instructions must not contain empty image or User-message arrays.');
31
+ if (!normalized.stateMessages)
32
+ return { instructions: normalized.state };
33
+ // Keep legacy JSON/list semantics; image-looking fields in an Object remain ordinary data.
34
+ // Only text-only String Array needs its original list representation, not message flattening.
35
+ return { instructions: getStructuredInput(inputs, 'instructions', 'Instructions') };
36
+ }
18
37
  export function getCriteriaInputDefinition(dataTypes) {
19
38
  return {
20
39
  id: 'criteria',