@valerypopoff/rivet2-core 2.22.0 → 2.24.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 (49) hide show
  1. package/dist/cjs/bundle.cjs +1166 -797
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/webAppRuntime.cjs +4 -1
  4. package/dist/cjs/webAppRuntime.cjs.map +2 -2
  5. package/dist/esm/exports.js +0 -1
  6. package/dist/esm/index.js +3 -0
  7. package/dist/esm/integrations/CodeRunner.js +6 -3
  8. package/dist/esm/integrations/CodeRunnerNamespace.js +10 -0
  9. package/dist/esm/model/AgentResponseTracePresentation.js +5 -1
  10. package/dist/esm/model/ChildInvocationOwnership.js +51 -0
  11. package/dist/esm/model/GraphProcessor.js +32 -54
  12. package/dist/esm/model/NodeRegistration.js +2 -6
  13. package/dist/esm/model/classifier/baseten.js +78 -0
  14. package/dist/esm/model/classifier/credentials.js +17 -9
  15. package/dist/esm/model/classifier/images.js +4 -4
  16. package/dist/esm/model/classifier/jev.js +45 -0
  17. package/dist/esm/model/classifier/json.js +1 -1
  18. package/dist/esm/model/classifier/limits.js +13 -13
  19. package/dist/esm/model/classifier/openai.js +20 -2
  20. package/dist/esm/model/classifier/preparation.js +5 -5
  21. package/dist/esm/model/classifier/profile.js +14 -13
  22. package/dist/esm/model/classifier/profileExecution.js +26 -23
  23. package/dist/esm/model/classifier/providers.js +170 -74
  24. package/dist/esm/model/classifier/questionHelpers.js +21 -2
  25. package/dist/esm/model/classifier/questions.js +37 -7
  26. package/dist/esm/model/classifier/response.js +8 -2
  27. package/dist/esm/model/classifier/state.js +2 -2
  28. package/dist/esm/model/classifier/subq.js +51 -0
  29. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +32 -61
  30. package/dist/esm/model/nodes/ClassifierProfileNode.js +9 -9
  31. package/dist/esm/model/nodes/ClassifierQuestionNode.js +53 -34
  32. package/dist/types/index.d.ts +1 -1
  33. package/dist/types/integrations/CodeRunner.d.ts +4 -1
  34. package/dist/types/integrations/CodeRunnerNamespace.d.ts +5 -0
  35. package/dist/types/model/AgentResponseTracePresentation.d.ts +2 -0
  36. package/dist/types/model/ChildInvocationOwnership.d.ts +36 -0
  37. package/dist/types/model/classifier/baseten.d.ts +8 -0
  38. package/dist/types/model/classifier/credentials.d.ts +2 -0
  39. package/dist/types/model/classifier/jev.d.ts +9 -0
  40. package/dist/types/model/classifier/profileExecution.d.ts +1 -1
  41. package/dist/types/model/classifier/providers.d.ts +26 -5
  42. package/dist/types/model/classifier/questionHelpers.d.ts +3 -1
  43. package/dist/types/model/classifier/questions.d.ts +2 -1
  44. package/dist/types/model/classifier/state.d.ts +1 -0
  45. package/dist/types/model/classifier/subq.d.ts +8 -0
  46. package/dist/types/model/classifier/types.d.ts +9 -2
  47. package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +2 -4
  48. package/dist/types/model/nodes/ClassifierQuestionNode.d.ts +2 -2
  49. package/package.json +2 -2
@@ -1,11 +1,14 @@
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 { 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
2
  import { assertLiquidImageLimits } from './images.js';
3
- import { prepareClassifierState, systemOneState, } from './state.js';
3
+ import { prepareClassifierState, inspectStateMessages, systemOneState, } from './state.js';
4
4
  import { validateClassifierEvaluationResponse } from './response.js';
5
5
  import { createOpenAIDecisionRequest, validateOpenAIDecisionResponse } from './openai.js';
6
6
  import { assertPerplexityDecisionLimits, perplexityDecisionState, PERPLEXITY_DECISION_MODELS } from './perplexity.js';
7
- import { prepareClassifierQuestion } from './questions.js';
7
+ import { prepareClassifierQuestion, createQuestionMap } from './questions.js';
8
+ import { assertJevImageLimits, JEV_IMAGE_MODELS, JEV_BOX_MODELS, createJevDecisionRequest } from './jev.js';
9
+ import { assertSubQDecisionLimits, SUBQ_DECISION_MODELS, subqDecisionState } from './subq.js';
8
10
  import { classifierArrayValues } from './json.js';
11
+ import { assertBasetenDecisionLimits, BASETEN_DECISION_MODELS, basetenDecisionState } from './baseten.js';
9
12
  import { assertClassifierResourceLimits, ClassifierValueBudget, CLASSIFIER_LIMITS, ClassifierResourceLimitError, ClassifierResponseReadError, readClassifierResponse, } from './limits.js';
10
13
  export { validateApiCompatibleClassifierResponse } from './response.js';
11
14
  export const JEV_SYSTEM_ONE_ENDPOINT = 'https://api.typesafe.ai/v1/systemone';
@@ -13,14 +16,16 @@ export const LIQUID_SYSTEM_ONE_ENDPOINT = 'https://api.liquid.ai/decisions/v1/sy
13
16
  export const OPENAI_DECISIONS_ENDPOINT = 'https://api.openai.com/v1/decisions';
14
17
  export const OPENROUTER_DECISIONS_ENDPOINT = 'https://openrouter.ai/api/alpha/decisions';
15
18
  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. */
19
+ export const SUBQ_DECISIONS_ENDPOINT = 'https://api.subq.ai/v1/systemone';
20
+ export const BASETEN_DECISIONS_ENDPOINT = 'https://inference.baseten.co/v1/systemone';
21
+ /** Jev 1.13/1.14 USD rates, verified 2026-10-24: https://docs.typesafe.ai/models */
17
22
  export const JEV_TOKEN_PRICING = {
18
23
  inputPerMillionTokens: 0.042,
19
24
  outputPerMillionTokens: 0,
20
25
  };
21
- /** Liquid d1's published USD rates: https://www.liquid.ai/blog/d1-decision-model */
26
+ /** Liquid d1 USD rates, verified 2026-10-26: https://www.liquid.ai/pricing */
22
27
  export const LIQUID_TOKEN_PRICING = {
23
- inputPerMillionTokens: 0.04,
28
+ inputPerMillionTokens: 0.02,
24
29
  outputPerMillionTokens: 0,
25
30
  };
26
31
  const TOKENS_PER_MILLION = 1_000_000;
@@ -46,22 +51,46 @@ export function createApiCompatibleClassifierProvider(config) {
46
51
  validateResponse: validateClassifierEvaluationResponse,
47
52
  });
48
53
  }
49
- export const jevClassifierProvider = createApiCompatibleClassifierProvider({
54
+ export const jevClassifierProvider = createClassifierProvider({
50
55
  id: 'jev',
51
56
  label: 'Jev',
52
57
  defaultModel: 'jev-latest',
58
+ modelOptions: ['jev-latest', 'jev-preview', 'jev-1.14.0', 'jev-1.13.0'].map((value) => ({ value, label: value })),
59
+ modelHelp: 'Jev images are experimental: use still PNG/JPEG, 280–1568 pixels per side. Image requests enable TypeSafe’s experimental image API.',
53
60
  credentialNames: JEV_DEFAULT_CREDENTIAL_NAMES,
54
61
  endpoint: JEV_SYSTEM_ONE_ENDPOINT,
55
- modelPricing: [{ models: ['jev-latest', 'jev-preview', 'jev-1.13.0'], pricing: JEV_TOKEN_PRICING }],
62
+ browserExecutionSupported: false,
63
+ modelPricing: [{ models: ['jev-latest', 'jev-preview', 'jev-1.13.0', 'jev-1.14.0'], pricing: JEV_TOKEN_PRICING }],
64
+ supportsImages: (model) => JEV_IMAGE_MODELS.includes(model),
65
+ supportsQuestionImages: (model) => JEV_IMAGE_MODELS.includes(model),
66
+ supportsBoxQuestions: (model) => JEV_BOX_MODELS.includes(model),
67
+ checkState: (state, check) => {
68
+ if (state.kind === 'messages')
69
+ assertJevImageLimits(state.images, check);
70
+ },
71
+ checkRequest: ({ questions }, check) => {
72
+ for (const question of questions)
73
+ if (question.instructionsMessages)
74
+ assertJevImageLimits(inspectStateMessages(question.instructionsMessages, check), check);
75
+ },
76
+ buildRequest: createJevDecisionRequest,
77
+ requestHeaders: ({ state, questions }) => (state.kind === 'messages' && state.images.length) ||
78
+ questions.some((question) => question.type === 'box' ||
79
+ question.instructionsMessages?.some(({ parts }) => parts.some((part) => part.type === 'image')))
80
+ ? { 'TypeSafe-Danger-Zone-Images': 'true' }
81
+ : {},
82
+ validateResponse: validateClassifierEvaluationResponse,
56
83
  });
57
84
  export const liquidClassifierProvider = createApiCompatibleClassifierProvider({
58
85
  id: 'liquid',
59
86
  label: 'Liquid AI',
60
87
  defaultModel: 'd1',
88
+ modelOptions: ['d1', 'd1.1'].map((value) => ({ value, label: value })),
89
+ modelHelp: 'Images belong in shared State, not Question Instructions.',
61
90
  credentialNames: LIQUID_DEFAULT_CREDENTIAL_NAMES,
62
91
  endpoint: LIQUID_SYSTEM_ONE_ENDPOINT,
63
92
  modelPricing: [{ models: ['d1'], pricing: LIQUID_TOKEN_PRICING }],
64
- supportsImages: (model) => model === 'd1',
93
+ supportsImages: (model) => model === 'd1' || model === 'd1.1',
65
94
  maxRequestBytes: 4_500_000,
66
95
  checkState: (state, check) => {
67
96
  if (state.kind === 'messages')
@@ -75,6 +104,7 @@ export const openrouterClassifierProvider = createApiCompatibleClassifierProvide
75
104
  id: 'openrouter',
76
105
  label: 'OpenRouter',
77
106
  defaultModel: 'microsoft/microsoft-decision-1',
107
+ modelOptions: [{ value: 'microsoft/microsoft-decision-1', label: 'Microsoft Decision-1' }],
78
108
  credentialNames: OPENROUTER_DEFAULT_CREDENTIAL_NAMES,
79
109
  endpoint: OPENROUTER_DECISIONS_ENDPOINT,
80
110
  modelPricing: [
@@ -91,10 +121,12 @@ export const openaiClassifierProvider = createClassifierProvider({
91
121
  id: 'openai',
92
122
  label: 'OpenAI',
93
123
  defaultModel: 'gpt-6-luna',
124
+ modelOptions: [{ value: 'gpt-6-luna', label: 'gpt-6-luna' }],
94
125
  credentialNames: OPENAI_DEFAULT_CREDENTIAL_NAMES,
95
126
  browserExecutionSupported: false,
96
127
  endpoint: OPENAI_DECISIONS_ENDPOINT,
97
128
  supportsImages: (model) => model === 'gpt-6-luna',
129
+ supportsQuestionImages: (model) => model === 'gpt-6-luna',
98
130
  modelPricing: [
99
131
  {
100
132
  models: ['gpt-6-luna'],
@@ -113,6 +145,7 @@ export const perplexityClassifierProvider = createClassifierProvider({
113
145
  id: 'perplexity',
114
146
  label: 'Perplexity',
115
147
  defaultModel: 'pplx-decider-v1.1-27b',
148
+ modelOptions: PERPLEXITY_DECISION_MODELS.map((value) => ({ value, label: value })),
116
149
  credentialNames: PERPLEXITY_DEFAULT_CREDENTIAL_NAMES,
117
150
  browserExecutionSupported: false,
118
151
  endpoint: PERPLEXITY_DECISIONS_ENDPOINT,
@@ -131,6 +164,51 @@ export const perplexityClassifierProvider = createClassifierProvider({
131
164
  }),
132
165
  validateResponse: validateClassifierEvaluationResponse,
133
166
  });
167
+ /** Current model catalog rate, not the older launch article's $0.05/MTok.
168
+ * https://docs.subq.ai/using-the-api/models/ (verified 2026-10-24).
169
+ */
170
+ export const subqClassifierProvider = createClassifierProvider({
171
+ id: 'subq',
172
+ label: 'SubQ',
173
+ defaultModel: 'subq-snap-1.1',
174
+ modelOptions: SUBQ_DECISION_MODELS.map((value) => ({ value, label: value })),
175
+ credentialNames: SUBQ_DEFAULT_CREDENTIAL_NAMES,
176
+ browserExecutionSupported: false,
177
+ endpoint: SUBQ_DECISIONS_ENDPOINT,
178
+ supportsImages: (model) => SUBQ_DECISION_MODELS.includes(model),
179
+ modelPricing: [{ models: SUBQ_DECISION_MODELS, pricing: { inputPerMillionTokens: 0.04, outputPerMillionTokens: 0 } }],
180
+ maxRequestBytes: 13 * 1024 * 1024,
181
+ checkRequest: assertSubQDecisionLimits,
182
+ buildRequest: ({ model, state, questions }) => ({
183
+ model,
184
+ ...subqDecisionState(state),
185
+ questions: createQuestionMap(questions),
186
+ }),
187
+ validateResponse: validateClassifierEvaluationResponse,
188
+ });
189
+ /** Native Baseten API reference uses Bearer authentication (not dedicated-deployment Api-Key). */
190
+ export const basetenClassifierProvider = createClassifierProvider({
191
+ id: 'baseten',
192
+ label: 'Baseten',
193
+ defaultModel: BASETEN_DECISION_MODELS[0],
194
+ modelOptions: [
195
+ { value: BASETEN_DECISION_MODELS[0], label: 'Elephant-1' },
196
+ { value: BASETEN_DECISION_MODELS[1], label: 'Mammoth-1' },
197
+ ],
198
+ modelHelp: 'Images belong in shared State, not Question Instructions.',
199
+ credentialNames: BASETEN_DEFAULT_CREDENTIAL_NAMES,
200
+ browserExecutionSupported: false,
201
+ endpoint: BASETEN_DECISIONS_ENDPOINT,
202
+ supportsImages: (model) => BASETEN_DECISION_MODELS.some((id) => id === model),
203
+ checkRequest: assertBasetenDecisionLimits,
204
+ buildRequest: ({ model, state, questions }) => ({
205
+ model,
206
+ state: basetenDecisionState(state),
207
+ questions: createQuestionMap(questions),
208
+ }),
209
+ validateResponse: validateClassifierEvaluationResponse,
210
+ // A temporary free promotion is not permanent pricing. Unknown cost stays unknown.
211
+ });
134
212
  /** Ordered so adding compatible providers does not alter authored IDs. */
135
213
  export const classifierProviders = [
136
214
  jevClassifierProvider,
@@ -138,6 +216,8 @@ export const classifierProviders = [
138
216
  openaiClassifierProvider,
139
217
  openrouterClassifierProvider,
140
218
  perplexityClassifierProvider,
219
+ subqClassifierProvider,
220
+ basetenClassifierProvider,
141
221
  ];
142
222
  export class ClassifierProviderError extends Error {
143
223
  kind;
@@ -146,7 +226,7 @@ export class ClassifierProviderError extends Error {
146
226
  super(message, options);
147
227
  this.kind = kind;
148
228
  this.statusCode = statusCode;
149
- this.name = 'ClassifierProviderError';
229
+ this.name = 'DecisionAIProviderError';
150
230
  }
151
231
  }
152
232
  export function classifierFailureKind(kind, status) {
@@ -155,37 +235,37 @@ export function classifierFailureKind(kind, status) {
155
235
  /** Bounded preparation/provider explanation, without traversing causes or capturing response bodies. */
156
236
  export function classifierErrorMessage(error, apiKey) {
157
237
  try {
158
- const text = error instanceof Error ? error.message : typeof error === 'string' ? error : 'Classifier request failed.';
238
+ const text = error instanceof Error ? error.message : typeof error === 'string' ? error : 'Decision AI request failed.';
159
239
  return (apiKey ? text.split(apiKey).join('[redacted]') : text).slice(0, 2000);
160
240
  }
161
241
  catch {
162
- return 'Classifier request failed with unreadable error metadata.';
242
+ return 'Decision AI request failed with unreadable error metadata.';
163
243
  }
164
244
  }
165
245
  function createOperation(args, label) {
166
- if (!Number.isFinite(args.timeoutMs) ||
167
- args.timeoutMs <= 0 ||
246
+ if ((args.timeoutMs !== undefined && (!Number.isFinite(args.timeoutMs) || args.timeoutMs <= 0)) ||
168
247
  (args.deadline !== undefined && !Number.isFinite(args.deadline)))
169
- throw new Error('Classifier timeout and deadline must be finite, with a positive timeout.');
248
+ throw new Error('Decision AI timeout and deadline must be finite, with a positive timeout.');
170
249
  const now = Date.now();
171
- const deadline = Math.min(now + args.timeoutMs, args.deadline ?? Infinity);
250
+ const deadline = Math.min(args.timeoutMs === undefined ? Infinity : now + args.timeoutMs, args.deadline ?? Infinity);
172
251
  // 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');
252
+ if (Number.isFinite(deadline) && deadline - now > MAX_TIMER_DELAY_MS)
253
+ throw new Error(`Decision AI effective timeout must not exceed ${MAX_TIMER_DELAY_MS} ms.`);
254
+ const timeoutMessage = `${label} request timed out${args.timeoutMs === undefined ? '' : ` after ${args.timeoutMs} ms`}.`;
176
255
  return {
177
256
  signal: args.signal,
178
257
  deadline,
258
+ timeoutMessage,
179
259
  check(attemptSignal) {
180
260
  throwIfAborted(args.signal, label);
181
261
  if (Date.now() >= deadline || attemptSignal?.aborted)
182
- throw timeoutError();
262
+ throw new ClassifierProviderError(timeoutMessage, 'timeout');
183
263
  },
184
264
  };
185
265
  }
186
266
  /** A plain specification and one runner for both graph and direct provider inputs. */
187
267
  function createClassifierProvider(spec) {
188
- const { endpoint, buildRequest, validateResponse, checkState, checkRequest, ...provider } = spec;
268
+ const { endpoint, buildRequest, requestHeaders, validateResponse, checkState, checkRequest, ...provider } = spec;
189
269
  const evaluate = async (input) => {
190
270
  // Reject removed evidence fields before object spread can read a getter or
191
271
  // discard non-enumerable/inherited content.
@@ -195,17 +275,17 @@ function createClassifierProvider(spec) {
195
275
  const operation = createOperation(args, provider.label);
196
276
  operation.check();
197
277
  if (typeof args.model !== 'string')
198
- throw new Error('Classifier model must be a nonblank string.');
278
+ throw new Error('Decision AI model must be a nonblank string.');
199
279
  const budget = new ClassifierValueBudget(operation.check, provider.maxRequestBytes);
200
280
  budget.inspect(args.model);
201
281
  if (args.model.trim() === '')
202
- throw new Error('Classifier model must be a nonblank string.');
282
+ throw new Error('Decision AI model must be a nonblank string.');
203
283
  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.');
284
+ throw new Error('Decision AI API key must be a nonblank string without line breaks.');
205
285
  if (!Array.isArray(args.questions) || args.questions.length === 0)
206
- throw new Error('Classifier Evaluate requires at least one question.');
286
+ throw new Error('Decision AI run requires at least one question.');
207
287
  if (args.questions.length > CLASSIFIER_LIMITS.questions)
208
- throw new Error('Classifier Evaluate supports at most 1000 questions.');
288
+ throw new Error('Decision AI run supports at most 1000 questions.');
209
289
  const state = prepareClassifierState(args, budget);
210
290
  const questions = [];
211
291
  const ids = new Set();
@@ -216,18 +296,35 @@ function createClassifierProvider(spec) {
216
296
  ids.add(question.questionId);
217
297
  questions.push(question);
218
298
  }
299
+ let imageCount = state.kind === 'messages' ? state.images.length : 0;
300
+ for (const question of questions) {
301
+ const images = question.instructionsMessages
302
+ ? inspectStateMessages(question.instructionsMessages, operation.check)
303
+ : [];
304
+ imageCount += images.length;
305
+ if (question.type === 'box') {
306
+ if (!provider.supportsBoxQuestions?.(args.model))
307
+ throw new ClassifierProviderError(`${provider.label} model '${args.model}' does not support Bounding Box questions.`, 'capability');
308
+ if (!(state.kind === 'messages' && state.images.length) && !images.length)
309
+ throw new ClassifierProviderError(`Bounding Box question '${question.questionId}' requires an image in shared State or its own Instructions.`, 'capability');
310
+ }
311
+ if (images.length && !provider.supportsQuestionImages?.(args.model))
312
+ throw new ClassifierProviderError(`${provider.label} model '${args.model}' does not support images in question instructions. Use a compatible Jev or OpenAI profile.`, 'capability');
313
+ }
314
+ if (imageCount > 128)
315
+ throw new Error('State and questions together must contain at most 128 images.');
219
316
  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');
317
+ throw new ClassifierProviderError(`${provider.label} model '${args.model}' does not support Decision AI images.`, 'capability');
221
318
  try {
222
319
  checkState?.(state, operation.check);
223
320
  checkRequest?.({ model: args.model, state, questions }, operation.check);
224
321
  }
225
322
  catch (error) {
226
323
  operation.check();
227
- throw new ClassifierProviderError(error instanceof Error ? error.message : `${provider.label} does not support this classifier evidence.`, 'capability', undefined, { cause: error });
324
+ throw new ClassifierProviderError(error instanceof Error ? error.message : `${provider.label} does not support this Decision AI evidence.`, 'capability', undefined, { cause: error });
228
325
  }
229
326
  operation.check();
230
- const result = await callClassifierHttp(args, { ...provider, endpoint, validateResponse }, { model: args.model, state, questions }, buildRequest, operation);
327
+ const result = await callClassifierHttp(args, { ...provider, endpoint, requestHeaders, validateResponse }, { model: args.model, state, questions }, buildRequest, operation);
231
328
  operation.check();
232
329
  return result;
233
330
  };
@@ -240,7 +337,7 @@ function normalizeModelPricing(provider) {
240
337
  export function getClassifierProvider(id) {
241
338
  const provider = classifierProviders.find((candidate) => candidate.id === (id || jevClassifierProvider.id));
242
339
  if (!provider)
243
- throw new Error(`Unknown classifier provider '${id}'.`);
340
+ throw new Error(`Unknown Decision AI provider '${id}'.`);
244
341
  return provider;
245
342
  }
246
343
  export function getClassifierProviderEnvironmentVariableNames() {
@@ -279,21 +376,12 @@ export function calculateClassifierUsageCost(provider, usage, models) {
279
376
  TOKENS_PER_MILLION;
280
377
  return Number.isFinite(totalCost) && totalCost >= 0 ? totalCost : undefined;
281
378
  }
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
379
  async function callClassifierHttp(args, spec, prepared, buildRequest, operation) {
293
380
  const { apiKey, fetchImplementation, retryOnNon200, retryOnNon200CooldownMs, retryOnNon200RepeatTimes } = args;
294
381
  const { endpoint, label: providerLabel, validateResponse, maxRequestBytes } = spec;
295
- const { signal, deadline } = operation;
382
+ const { signal, deadline, timeoutMessage } = operation;
296
383
  const request = buildRequest(prepared);
384
+ const requestHeaders = spec.requestHeaders?.(prepared);
297
385
  const configuredRetryCount = retryOnNon200 ? normalizeClassifierNon200RetryCount(retryOnNon200RepeatTimes) : 0;
298
386
  const configuredCooldownMs = normalizeClassifierNon200RetryCooldownMs(retryOnNon200CooldownMs);
299
387
  let automaticRetryCount = 0;
@@ -342,7 +430,9 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
342
430
  const controller = new AbortController();
343
431
  const onAbort = () => controller.abort(signal.reason);
344
432
  signal.addEventListener('abort', onAbort, { once: true });
345
- const timer = setTimeout(() => controller.abort(new Error(`${providerLabel} request timeout`)), remainingMs);
433
+ const timer = Number.isFinite(remainingMs)
434
+ ? setTimeout(() => controller.abort(new Error(`${providerLabel} request timeout`)), remainingMs)
435
+ : undefined;
346
436
  const cleanupAttempt = () => {
347
437
  clearTimeout(timer);
348
438
  signal.removeEventListener('abort', onAbort);
@@ -353,7 +443,7 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
353
443
  response = await waitForAttempt(fetchImplementation(endpoint, {
354
444
  method: 'POST',
355
445
  redirect: 'error',
356
- headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
446
+ headers: { ...requestHeaders, Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
357
447
  body: requestJson,
358
448
  signal: controller.signal,
359
449
  }), controller.signal, discardResponseBody);
@@ -365,9 +455,7 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
365
455
  operation.check();
366
456
  }
367
457
  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.`);
458
+ report('failure', undefined, kind, undefined, kind === 'timeout' ? timeoutMessage : `${providerLabel} transport request failed.`);
371
459
  operation.check(controller.signal);
372
460
  if (automaticRetryCount >= MAX_AUTOMATIC_ATTEMPTS - 1) {
373
461
  throw new ClassifierProviderError(`${providerLabel} request failed after ${MAX_AUTOMATIC_ATTEMPTS} attempts due to a transport error.`, 'transport', undefined, { cause: error });
@@ -382,15 +470,18 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
382
470
  catch (error) {
383
471
  cleanupAttempt();
384
472
  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.`);
473
+ report(signal.aborted ? 'aborted' : 'failure', response.status, signal.aborted ? undefined : 'timeout', undefined, signal.aborted ? `${providerLabel} request was canceled.` : timeoutMessage);
388
474
  throw error;
389
475
  }
390
476
  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}).`);
477
+ // A valid key can lack access to a model. Do not diagnose 403 as an invalid key.
478
+ const accessDeniedMessage = response.status === 403
479
+ ? `${providerLabel} access denied (HTTP 403). Check API key permissions and requested model access.`
480
+ : undefined;
481
+ report('failure', response.status, 'http', undefined, accessDeniedMessage ??
482
+ (response.status === 401
483
+ ? `${providerLabel} authentication failed (HTTP ${response.status}). Check the ${providerLabel} API key.`
484
+ : `${providerLabel} rejected the request (HTTP ${response.status}).`));
394
485
  const retryable = RETRYABLE_STATUSES.has(response.status);
395
486
  const permanent = [400, 401, 402, 403, 413, 422].includes(response.status);
396
487
  const willRetry = (retryable && automaticRetryCount < MAX_AUTOMATIC_ATTEMPTS - 1) ||
@@ -415,7 +506,7 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
415
506
  // neither the final error nor the next bounded retry may depend on it.
416
507
  discardResponseBody(response);
417
508
  // Diagnostic collection introduces an await after receiving the rejection.
418
- // Caller cancellation and the overall deadline still outrank HTTP suppression.
509
+ // Caller cancellation and any active request deadline outrank HTTP suppression.
419
510
  // Do not check the diagnostic-only controller: its 1 s cap preserves the HTTP error.
420
511
  operation.check();
421
512
  if (willRetry) {
@@ -432,7 +523,7 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
432
523
  continue;
433
524
  }
434
525
  if (response.status === 401 || response.status === 403) {
435
- throw new ClassifierProviderError(`${providerLabel} authentication failed. Check the ${providerLabel} API key.`, 'http', response.status);
526
+ throw new ClassifierProviderError(accessDeniedMessage ?? `${providerLabel} authentication failed. Check the ${providerLabel} API key.`, 'http', response.status);
436
527
  }
437
528
  // Repeating an unchanged invalid/oversized request or an unfunded account
438
529
  // cannot recover. These remain HTTP failures so profile fallback works.
@@ -458,7 +549,7 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
458
549
  ? 'transport'
459
550
  : 'response-parsing';
460
551
  report('failure', response.status, kind, undefined, kind === 'timeout'
461
- ? `${providerLabel} request timed out after ${args.timeoutMs} ms.`
552
+ ? timeoutMessage
462
553
  : error instanceof ClassifierResourceLimitError
463
554
  ? error.message
464
555
  : kind === 'transport'
@@ -480,8 +571,8 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
480
571
  validatedResponse = validateResponse(body, prepared.questions, providerLabel);
481
572
  }
482
573
  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 });
574
+ report('failure', response.status, 'response-validation', classifierAttemptUsage(body, spec, args.model), error instanceof Error ? error.message : `${providerLabel} returned an invalid Decision AI response.`);
575
+ throw new ClassifierProviderError(error instanceof Error ? error.message : `${providerLabel} returned an invalid Decision AI response.`, 'response-validation', undefined, { cause: error });
485
576
  }
486
577
  report('success', response.status, undefined, classifierAttemptUsage(body, spec, args.model));
487
578
  return {
@@ -574,24 +665,29 @@ function throwIfAborted(signal, providerLabel) {
574
665
  function throwAbort(signal, providerLabel) {
575
666
  throw signal.reason instanceof Error ? signal.reason : new Error(`${providerLabel} request aborted.`);
576
667
  }
577
- function waitForRetry(delayMs, signal, providerLabel) {
668
+ async function waitForRetry(delayMs, signal, providerLabel) {
578
669
  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
- });
670
+ // Without a request deadline, authored/provider waits can exceed one timer.
671
+ // Chunk the wait instead of overflowing to 1 ms or retrying before it expires.
672
+ while (delayMs > 0) {
673
+ const chunkMs = Math.min(delayMs, MAX_TIMER_DELAY_MS);
674
+ await new Promise((resolve, reject) => {
675
+ const onAbort = () => {
676
+ clearTimeout(timer);
677
+ signal.removeEventListener('abort', onAbort);
678
+ reject(signal.reason instanceof Error ? signal.reason : new Error(`${providerLabel} request aborted.`));
679
+ };
680
+ const timer = setTimeout(() => {
681
+ signal.removeEventListener('abort', onAbort);
682
+ resolve();
683
+ }, chunkMs);
684
+ signal.addEventListener('abort', onAbort, { once: true });
685
+ if (signal.aborted)
686
+ onAbort();
687
+ });
688
+ throwIfAborted(signal, providerLabel);
689
+ delayMs -= chunkMs;
690
+ }
595
691
  }
596
692
  function getRetryDelayMs(retryAfter, attempt, deadline) {
597
693
  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',
@@ -1,27 +1,57 @@
1
1
  import { assertClassifierEntryKind, assertClassifierInstructionsKind, snapshotClassifierJson, classifierArrayValues, } from './json.js';
2
+ import { inspectStateMessages, systemOneState } from './state.js';
3
+ export function createQuestionMap(questions, instructionsFor = (question) => question.instructionsMessages
4
+ ? systemOneState({ state: '', stateMessages: question.instructionsMessages }).state
5
+ : question.instructions) {
6
+ const result = Object.create(null);
7
+ for (const question of questions) {
8
+ const instructions = instructionsFor(question);
9
+ const providerQuestion = (question.type === 'noul' || question.type === 'box') && question.criteria === undefined
10
+ ? { type: question.type, instructions }
11
+ : { type: question.type, instructions, criteria: question.criteria };
12
+ Object.defineProperty(result, question.questionId, { enumerable: true, value: providerQuestion });
13
+ }
14
+ return result;
15
+ }
2
16
  /** Shared by node execution and direct provider calls, before taking the request snapshot. */
3
17
  export function prepareClassifierQuestion(value, budget) {
4
18
  if (value === null || typeof value !== 'object' || Array.isArray(value))
5
19
  throw new Error('Question inputs must contain question definition objects.');
6
20
  if ('images' in value)
7
- throw new Error("Question-level images are not supported. Connect images to Classifier Evaluate's State input.");
21
+ throw new Error("Question-level images fields are not supported. Connect images to Question Instructions (Jev/OpenAI), or to Decision AI run's State input for shared evidence.");
22
+ if ('instructionsMessages' in value) {
23
+ const descriptor = Object.getOwnPropertyDescriptor(value, 'instructionsMessages');
24
+ if (!descriptor?.enumerable || !('value' in descriptor))
25
+ throw new Error('Question instructionsMessages must be an own, enumerable data field.');
26
+ }
8
27
  for (const key of ['questionId', 'type', 'instructions']) {
9
28
  if (!Object.prototype.propertyIsEnumerable.call(value, key))
10
- throw new Error(`Every classifier question must have an own, enumerable '${key}' field.`);
29
+ throw new Error(`Every Decision AI question must have an own, enumerable '${key}' field.`);
11
30
  }
12
31
  const criteriaProperty = Object.getOwnPropertyDescriptor(value, 'criteria');
13
32
  if (criteriaProperty && (!criteriaProperty.enumerable || !('value' in criteriaProperty)))
14
- throw new Error('Classifier question criteria must be an own, enumerable field.');
33
+ throw new Error('Decision AI question criteria must be an own, enumerable field.');
15
34
  // Optional envelope properties may be undefined; structured entries themselves must be exact JSON.
16
35
  const question = snapshotClassifierJson(value, 'Question', budget, true);
17
36
  if (typeof question.questionId !== 'string' || question.questionId.trim() === '')
18
- throw new Error('Every classifier question must have a non-empty Question ID.');
19
- if (!['choice', 'score', 'noul'].includes(question.type))
37
+ throw new Error('Every Decision AI question must have a non-empty Question ID.');
38
+ if (!['choice', 'score', 'noul', 'box'].includes(question.type))
20
39
  throw new Error(`Question '${question.questionId}' has an unsupported type.`);
21
40
  // The whole question has already passed recursive JSON/resource validation.
22
41
  // Check only entry kinds here; do not scan each structured entry again.
23
- assertClassifierInstructionsKind(question.instructions, `Question '${question.questionId}' instructions`);
42
+ if (question.instructionsMessages !== undefined) {
43
+ if (question.instructions !== '')
44
+ throw new Error('Question instructions and instructionsMessages cannot be supplied together.');
45
+ inspectStateMessages(question.instructionsMessages, budget.check);
46
+ if (!question.instructionsMessages.some(({ parts }) => parts.some((part) => part.type === 'image' || part.text.trim() !== '')))
47
+ throw new Error(`Question '${question.questionId}' instructions must not be empty.`);
48
+ }
49
+ else {
50
+ assertClassifierInstructionsKind(question.instructions, `Question '${question.questionId}' instructions`);
51
+ }
24
52
  const criteria = question.criteria;
53
+ if (question.type === 'box' && criteria !== undefined)
54
+ throw new Error(`Bounding Box question '${question.questionId}' does not accept criteria.`);
25
55
  if (question.type === 'choice') {
26
56
  if (typeof criteria !== 'object' || criteria === null || Array.isArray(criteria))
27
57
  throw new Error(`Choice question '${question.questionId}' requires object criteria.`);
@@ -38,7 +68,7 @@ export function prepareClassifierQuestion(value, budget) {
38
68
  for (const entry of classifierArrayValues(criteria, 'Criteria'))
39
69
  assertClassifierEntryKind(entry, `Question '${question.questionId}' criteria[${index++}]`);
40
70
  }
41
- else if (criteria !== undefined) {
71
+ else if (question.type === 'noul' && criteria !== undefined) {
42
72
  if (typeof criteria !== 'object' ||
43
73
  criteria === null ||
44
74
  Array.isArray(criteria) ||
@@ -27,11 +27,11 @@ function requireProbabilityMap(value, keys, label, providerLabel) {
27
27
  for (const key of keys)
28
28
  requireResponseNumber(probabilities[key], `${label}.${key}`, providerLabel);
29
29
  }
30
- export function validateApiCompatibleClassifierResponse(body, questions, providerLabel = 'Classifier provider') {
30
+ export function validateApiCompatibleClassifierResponse(body, questions, providerLabel = 'Decision AI provider') {
31
31
  return validateClassifierEvaluationResponse(body, questions, providerLabel);
32
32
  }
33
33
  /** Validate the common Rivet result, independently of the provider's wire protocol. */
34
- export function validateClassifierEvaluationResponse(body, questions, providerLabel = 'Classifier provider') {
34
+ export function validateClassifierEvaluationResponse(body, questions, providerLabel = 'Decision AI provider') {
35
35
  const model = isRecord(body) ? responseField(body, 'model') : undefined;
36
36
  const answers = isRecord(body) ? responseField(body, 'answers') : undefined;
37
37
  const usage = isRecord(body) ? responseField(body, 'usage') : undefined;
@@ -65,6 +65,12 @@ export function validateClassifierEvaluationResponse(body, questions, providerLa
65
65
  requireProbabilityMap(responseField(answer, 'probabilities'), keys, `${question.questionId}.probabilities`, providerLabel);
66
66
  requireResponseMap(responseField(answer, 'legend'), keys, `${question.questionId}.legend`, providerLabel);
67
67
  }
68
+ else if (question.type === 'box') {
69
+ const box = requireResponseMap(responseField(answer, 'box'), ['top', 'bottom', 'left', 'right'], `${question.questionId}.box`, providerLabel);
70
+ for (const edge of ['top', 'bottom', 'left', 'right'])
71
+ requireResponseNumber(box[edge], `${question.questionId}.box.${edge}`, providerLabel);
72
+ requireResponseNumber(responseField(answer, 'confidence'), `${question.questionId}.confidence`, providerLabel);
73
+ }
68
74
  else {
69
75
  requireResponseNumber(responseField(answer, 'noul'), `${question.questionId}.noul`, providerLabel);
70
76
  }
@@ -140,7 +140,7 @@ function prepareRivetState(input, budget) {
140
140
  }
141
141
  else if (message(item)) {
142
142
  if (classifierDataProperty(item, 'type') !== 'user' || 'function_call' in item || 'function_calls' in item)
143
- throw new Error('Classifier State supports only user messages, not system, developer, assistant, or tool messages.');
143
+ throw new Error('Decision AI State supports only user messages, not system, developer, assistant, or tool messages.');
144
144
  flush();
145
145
  if (messages.length >= CLASSIFIER_LIMITS.messages)
146
146
  throw new Error('State has too many messages.');
@@ -161,7 +161,7 @@ function prepareRivetState(input, budget) {
161
161
  flush();
162
162
  return messages.length ? { kind: 'messages', messages, images } : { kind: 'json', value: '' };
163
163
  }
164
- function inspectStateMessages(messages, check) {
164
+ export function inspectStateMessages(messages, check) {
165
165
  if (!Array.isArray(messages))
166
166
  throw new Error('State messages must be an array.');
167
167
  if (messages.length > CLASSIFIER_LIMITS.messages)