@valerypopoff/rivet2-core 2.15.0 → 2.17.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 (111) hide show
  1. package/dist/cjs/bundle.cjs +4350 -2077
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/interpolationRuntime.cjs +22 -3
  4. package/dist/cjs/interpolationRuntime.cjs.map +3 -3
  5. package/dist/cjs/interpolationSyntax.cjs +9 -5
  6. package/dist/cjs/interpolationSyntax.cjs.map +2 -2
  7. package/dist/esm/api/createProcessor.js +5 -2
  8. package/dist/esm/exports.js +2 -0
  9. package/dist/esm/model/GraphBoundaryCache.js +2 -1
  10. package/dist/esm/model/GraphProcessor.js +268 -6
  11. package/dist/esm/model/Nodes.js +10 -0
  12. package/dist/esm/model/ProjectBundle.js +235 -0
  13. package/dist/esm/model/SplitRunProcessor.js +28 -7
  14. package/dist/esm/model/StreamingWatchTopology.js +118 -8
  15. package/dist/esm/model/SubgraphProjectTarget.js +7 -0
  16. package/dist/esm/model/chat-v2/aiSdkBridge.js +7 -5
  17. package/dist/esm/model/chat-v2/chatV2Pipeline.js +13 -8
  18. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +19 -1
  19. package/dist/esm/model/chat-v2/chatV2Shared.js +2 -1
  20. package/dist/esm/model/chat-v2/llmChatV2Body.js +11 -8
  21. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +2 -0
  22. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +15 -1
  23. package/dist/esm/model/chat-v2/llmChatV2NodeMigration.js +22 -2
  24. package/dist/esm/model/chat-v2/llmProfile.js +3 -0
  25. package/dist/esm/model/chat-v2/llmProfileBody.js +2 -2
  26. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +1 -1
  27. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +1 -1
  28. package/dist/esm/model/chat-v2/temperature.js +9 -0
  29. package/dist/esm/model/classifier/credentials.js +30 -4
  30. package/dist/esm/model/classifier/images.js +176 -0
  31. package/dist/esm/model/classifier/json.js +57 -0
  32. package/dist/esm/model/classifier/limits.js +270 -0
  33. package/dist/esm/model/classifier/openai.js +118 -0
  34. package/dist/esm/model/classifier/preparation.js +74 -0
  35. package/dist/esm/model/classifier/providers.js +260 -185
  36. package/dist/esm/model/classifier/questionHelpers.js +29 -45
  37. package/dist/esm/model/classifier/questions.js +53 -0
  38. package/dist/esm/model/classifier/response.js +75 -0
  39. package/dist/esm/model/classifier/state.js +204 -0
  40. package/dist/esm/model/nodeRunFailure.js +47 -0
  41. package/dist/esm/model/nodes/CatchStreamingChunksNode.js +42 -0
  42. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +178 -138
  43. package/dist/esm/model/nodes/ClassifierQuestionNode.js +59 -15
  44. package/dist/esm/model/nodes/GetGlobalNode.js +2 -2
  45. package/dist/esm/model/nodes/HttpCallNode.js +44 -75
  46. package/dist/esm/model/nodes/ImageNode.js +44 -3
  47. package/dist/esm/model/nodes/LLMChatV2Node.js +24 -3
  48. package/dist/esm/model/nodes/ObjectNode.js +29 -18
  49. package/dist/esm/model/nodes/PromptNode.js +2 -1
  50. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +4 -1
  51. package/dist/esm/model/nodes/SetGlobalNode.js +5 -3
  52. package/dist/esm/model/nodes/StopWatchingStreamingOutputNode.js +8 -8
  53. package/dist/esm/model/nodes/StreamValueNode.js +38 -0
  54. package/dist/esm/model/nodes/SubGraphNode.js +196 -35
  55. package/dist/esm/model/nodes/ToBase64Node.js +106 -0
  56. package/dist/esm/model/nodes/WatchStreamingOutputNode.js +7 -7
  57. package/dist/esm/recording/ExecutionRecorder.js +26 -0
  58. package/dist/esm/utils/base64.js +18 -15
  59. package/dist/esm/utils/errors.js +41 -0
  60. package/dist/esm/utils/interpolation.js +44 -22
  61. package/dist/esm/utils/interpolationSyntax.js +15 -6
  62. package/dist/esm/utils/serialization/serialization.js +3 -2
  63. package/dist/esm/utils/serialization/serializationUtils.js +6 -0
  64. package/dist/esm/utils/serialization/serialization_v4.js +15 -3
  65. package/dist/types/api/createProcessor.d.ts +7 -1
  66. package/dist/types/exports.d.ts +2 -0
  67. package/dist/types/model/CycleDetector.d.ts +1 -2
  68. package/dist/types/model/ExecutorProtocol.d.ts +2 -0
  69. package/dist/types/model/GraphBoundaryCache.d.ts +2 -0
  70. package/dist/types/model/GraphProcessor.d.ts +1 -0
  71. package/dist/types/model/Nodes.d.ts +6 -2
  72. package/dist/types/model/ProcessContext.d.ts +12 -0
  73. package/dist/types/model/ProjectBundle.d.ts +54 -0
  74. package/dist/types/model/ProjectReferenceLoader.d.ts +3 -0
  75. package/dist/types/model/StreamingWatchTopology.d.ts +11 -1
  76. package/dist/types/model/SubgraphProjectTarget.d.ts +38 -0
  77. package/dist/types/model/chat-v2/chatV2Shared.d.ts +1 -1
  78. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +3 -1
  79. package/dist/types/model/chat-v2/llmChatV2NodeMigration.d.ts +3 -1
  80. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +6 -6
  81. package/dist/types/model/chat-v2/temperature.d.ts +2 -0
  82. package/dist/types/model/classifier/credentials.d.ts +3 -1
  83. package/dist/types/model/classifier/images.d.ts +18 -0
  84. package/dist/types/model/classifier/json.d.ts +19 -0
  85. package/dist/types/model/classifier/limits.d.ts +42 -0
  86. package/dist/types/model/classifier/openai.d.ts +5 -0
  87. package/dist/types/model/classifier/preparation.d.ts +16 -0
  88. package/dist/types/model/classifier/providers.d.ts +67 -9
  89. package/dist/types/model/classifier/questionHelpers.d.ts +6 -4
  90. package/dist/types/model/classifier/questions.d.ts +4 -0
  91. package/dist/types/model/classifier/response.d.ts +4 -0
  92. package/dist/types/model/classifier/state.d.ts +37 -0
  93. package/dist/types/model/classifier/types.d.ts +2 -0
  94. package/dist/types/model/nodeRunFailure.d.ts +13 -0
  95. package/dist/types/model/nodes/CatchStreamingChunksNode.d.ts +20 -0
  96. package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +3 -0
  97. package/dist/types/model/nodes/GetGlobalNode.d.ts +7 -0
  98. package/dist/types/model/nodes/ImageNode.d.ts +4 -0
  99. package/dist/types/model/nodes/LLMChatV2Node.d.ts +1 -0
  100. package/dist/types/model/nodes/ObjectNode.d.ts +2 -1
  101. package/dist/types/model/nodes/StreamValueNode.d.ts +14 -0
  102. package/dist/types/model/nodes/SubGraphNode.d.ts +21 -2
  103. package/dist/types/model/nodes/ToBase64Node.d.ts +12 -0
  104. package/dist/types/recording/ExecutionRecorder.d.ts +8 -2
  105. package/dist/types/utils/base64.d.ts +1 -1
  106. package/dist/types/utils/errors.d.ts +4 -0
  107. package/dist/types/utils/interpolation.d.ts +13 -2
  108. package/dist/types/utils/interpolationSyntax.d.ts +1 -1
  109. package/dist/types/utils/serialization/serialization.d.ts +3 -1
  110. package/dist/types/utils/serialization/serializationUtils.d.ts +1 -0
  111. package/package.json +1 -1
@@ -1,10 +1,14 @@
1
1
  import { nanoid } from 'nanoid/non-secure';
2
2
  import { nodeDefinition } from '../NodeDefinition.js';
3
3
  import { NodeImpl } from '../NodeImpl.js';
4
+ import { createExcludedNodeOutputs } from '../NodeExclusionPolicy.js';
4
5
  import { formatNodeBodyMarkdownField, formatNodeBodyMarkdownSeparator } from '../nodeBodyMarkdown.js';
6
+ import { createCaughtRunFailureOutputs, getRunFailureOutputDefinitions, shouldCatchRunFailure, withRunSuccessOutputs, } from '../nodeRunFailure.js';
5
7
  import { getNextVariadicPortIndex } from './variadicPortIndex.js';
6
8
  import { resolveClassifierApiKey, } from '../classifier/credentials.js';
7
- import { assertClassifierEntry, assertClassifierInstructions } from '../classifier/questionHelpers.js';
9
+ import { classifierArrayValues, classifierInputDataValue } from '../classifier/json.js';
10
+ import { normalizeClassifierState } from '../classifier/state.js';
11
+ import { CLASSIFIER_LIMITS, classifierPreparationCheck, ClassifierValueBudget } from '../classifier/limits.js';
8
12
  import { calculateClassifierUsageCost, classifierProviders, DEFAULT_CLASSIFIER_RETRY_ON_NON_200_COOLDOWN_MS, DEFAULT_CLASSIFIER_RETRY_ON_NON_200_REPEAT_TIMES, getClassifierProvider, normalizeClassifierNon200RetryCooldownMs, normalizeClassifierNon200RetryCount, } from '../classifier/providers.js';
9
13
  const QUESTION_TYPES = ['object', 'object[]', 'any', 'any[]'];
10
14
  export class ClassifierEvaluateNodeImpl extends NodeImpl {
@@ -17,7 +21,7 @@ export class ClassifierEvaluateNodeImpl extends NodeImpl {
17
21
  // Keep the default model in the provider descriptor rather than
18
22
  // serializing Jev's model into every new node. A future provider then
19
23
  // receives its own default when an author changes the Provider field.
20
- data: { provider: 'jev', timeoutMs: 30_000 },
24
+ data: { provider: 'jev', timeoutMs: 30_000, errorOnNon200: true, catchRequestFailed: false },
21
25
  };
22
26
  }
23
27
  getInputDefinitions(connections) {
@@ -25,8 +29,20 @@ export class ClassifierEvaluateNodeImpl extends NodeImpl {
25
29
  {
26
30
  id: 'state',
27
31
  title: 'State',
28
- dataType: ['string', 'object', 'object[]', 'any', 'any[]'],
29
- required: true,
32
+ dataType: [
33
+ 'string',
34
+ 'string[]',
35
+ 'image',
36
+ 'image[]',
37
+ 'chat-message',
38
+ 'chat-message[]',
39
+ 'object',
40
+ 'object[]',
41
+ 'any',
42
+ 'any[]',
43
+ ],
44
+ description: 'Shared text, images, or assembled user messages for every question. Image bytes and base64 images are encoded automatically. JSON objects remain structured state.',
45
+ required: false,
30
46
  splitRunBehavior: 'preserve-array',
31
47
  },
32
48
  ];
@@ -52,48 +68,62 @@ export class ClassifierEvaluateNodeImpl extends NodeImpl {
52
68
  const outputs = [
53
69
  { id: 'answers', title: 'Answers', dataType: 'object' },
54
70
  { id: 'usage', title: 'Usage', dataType: 'object' },
71
+ {
72
+ id: 'cost',
73
+ title: 'Cost',
74
+ dataType: 'number',
75
+ description: 'Estimated USD cost for this successful evaluation. Excluded when pricing cannot be calculated.',
76
+ },
55
77
  ];
56
78
  if (this.data.outputRequestBody === true) {
57
- outputs.push({ id: 'requestBody', title: 'Classifier request body', dataType: 'object' });
79
+ outputs.push({ id: 'requestBody', title: 'Request body', dataType: 'object' });
58
80
  }
59
81
  if (this.data.outputResponseBody === true) {
60
- outputs.push({ id: 'responseBody', title: 'Classifier response body', dataType: 'object' });
82
+ outputs.push({ id: 'responseBody', title: 'Response body', dataType: 'object' });
61
83
  }
62
- return outputs;
84
+ return [...outputs, ...getRunFailureOutputDefinitions({ catchRequestFailed: this.data.catchRequestFailed })];
63
85
  }
64
86
  getEditors() {
65
87
  return [
66
88
  {
67
- type: 'dropdown',
68
- label: 'Provider',
69
- dataKey: 'provider',
70
- defaultValue: 'jev',
71
- options: classifierProviders.map((provider) => ({ value: provider.id, label: provider.label })),
72
- },
73
- {
74
- type: 'string',
89
+ type: 'group',
75
90
  label: 'Model',
76
- dataKey: 'model',
77
- useInputToggleDataKey: 'useModelInput',
78
- placeholder: 'jev-latest',
79
- },
80
- {
81
- type: 'segmented',
82
- label: 'API key source',
83
- ariaLabel: 'API key source',
84
- dataKey: 'apiKeySource',
85
- defaultValue: 'configured',
86
- options: [
87
- { value: 'configured', label: 'Configured key' },
88
- { value: 'input', label: 'Input port' },
91
+ defaultOpen: true,
92
+ editors: [
93
+ {
94
+ type: 'dropdown',
95
+ label: 'Provider',
96
+ dataKey: 'provider',
97
+ defaultValue: 'jev',
98
+ options: classifierProviders.map((provider) => ({ value: provider.id, label: provider.label })),
99
+ },
100
+ {
101
+ type: 'string',
102
+ label: 'Model',
103
+ dataKey: 'model',
104
+ useInputToggleDataKey: 'useModelInput',
105
+ placeholder: getProviderForDisplay(this.data.provider).defaultModel,
106
+ },
107
+ {
108
+ type: 'segmented',
109
+ label: 'API key source',
110
+ ariaLabel: 'API key source',
111
+ dataKey: 'apiKeySource',
112
+ defaultValue: 'configured',
113
+ options: [
114
+ { value: 'configured', label: 'Automatic' },
115
+ { value: 'classifier-settings', label: 'Classifier settings' },
116
+ { value: 'input', label: 'Input port' },
117
+ ],
118
+ helperMessage: getApiKeySourceHelperMessage,
119
+ },
120
+ {
121
+ type: 'custom',
122
+ label: 'Configured API key names',
123
+ customEditorId: 'ClassifierCredentialNames',
124
+ hideIf: (data) => data.apiKeySource === 'input' || data.apiKeySource === 'classifier-settings',
125
+ },
89
126
  ],
90
- helperMessage: getApiKeySourceHelperMessage,
91
- },
92
- {
93
- type: 'custom',
94
- label: 'Configured API key names',
95
- customEditorId: 'ClassifierCredentialNames',
96
- hideIf: (data) => data.apiKeySource === 'input',
97
127
  },
98
128
  {
99
129
  type: 'group',
@@ -103,7 +133,7 @@ export class ClassifierEvaluateNodeImpl extends NodeImpl {
103
133
  type: 'toggle',
104
134
  label: 'Output usage details',
105
135
  dataKey: 'outputUsage',
106
- helperMessage: 'Adds totalCost to Usage when the selected provider has fixed token pricing. Jev input tokens cost $0.042 / MTok; output tokens are free.',
136
+ helperMessage: 'Adds estimated totalCost to Usage only for recognized requested/returned models. Unknown pricing is omitted. Provider-specific premiums are not included.',
107
137
  },
108
138
  {
109
139
  type: 'toggle',
@@ -139,11 +169,24 @@ export class ClassifierEvaluateNodeImpl extends NodeImpl {
139
169
  type: 'group',
140
170
  label: 'Error behavior',
141
171
  editors: [
172
+ {
173
+ type: 'toggle',
174
+ label: 'Fail on non-2XX status code',
175
+ dataKey: 'errorOnNon200',
176
+ defaultValue: true,
177
+ helperMessage: 'After retries, throw on a rejected HTTP request. When disabled, unavailable outputs are excluded. Run failed and Run error are available only when Catch all failures is enabled.',
178
+ },
179
+ {
180
+ type: 'toggle',
181
+ label: 'Catch all failures',
182
+ dataKey: 'catchRequestFailed',
183
+ helperMessage: 'Return any node execution failure through Run failed and Run error instead of stopping the graph. Explicit graph cancellation is never caught.',
184
+ },
142
185
  {
143
186
  type: 'toggle',
144
187
  label: 'Retry on non-200',
145
188
  dataKey: 'retryOnNon200',
146
- helperMessage: 'Retries non-authentication, non-validation provider HTTP responses. Jev rate-limit retries remain automatic.',
189
+ helperMessage: 'Retries non-authentication, non-validation provider HTTP responses. Provider rate-limit retries remain automatic.',
147
190
  },
148
191
  {
149
192
  type: 'number',
@@ -188,11 +231,30 @@ export class ClassifierEvaluateNodeImpl extends NodeImpl {
188
231
  return {
189
232
  contextMenuTitle: 'Classifier Evaluate',
190
233
  infoBoxTitle: 'Classifier Evaluate',
191
- infoBoxBody: 'Evaluates one shared state against a batch of independent typed classifier questions in one request.',
234
+ infoBoxBody: 'Evaluates shared state and optional images against typed classifier questions. Images are shared evidence for every question.',
192
235
  group: ['Classifier'],
193
236
  };
194
237
  }
195
238
  async process(inputs, context) {
239
+ try {
240
+ context.signal.throwIfAborted();
241
+ const outputs = await this.processRun(inputs, context);
242
+ context.signal.throwIfAborted();
243
+ return withRunSuccessOutputs({ catchRequestFailed: this.data.catchRequestFailed }, outputs);
244
+ }
245
+ catch (error) {
246
+ if (!shouldCatchRunFailure(this.data, error, context.signal))
247
+ throw error;
248
+ return this.data.catchRequestFailed === true
249
+ ? createCaughtRunFailureOutputs(this.getOutputDefinitions(), error)
250
+ : createExcludedNodeOutputs(this.chartNode, this.getOutputDefinitions());
251
+ }
252
+ }
253
+ async processRun(inputs, context) {
254
+ const timeoutMs = normalizeTimeout(this.data.timeoutMs);
255
+ const deadline = Date.now() + timeoutMs;
256
+ const checkPreparation = classifierPreparationCheck(context.signal, deadline, timeoutMs);
257
+ checkPreparation();
196
258
  const provider = getClassifierProvider(this.data.provider);
197
259
  if (!provider.browserExecutionSupported && context.executor === 'browser') {
198
260
  throw new Error(`${provider.label} cannot run in the Browser executor. Select the Node executor, or run through Studio Server or remote debugging.`);
@@ -205,31 +267,42 @@ export class ClassifierEvaluateNodeImpl extends NodeImpl {
205
267
  inputs,
206
268
  providerId: provider.id,
207
269
  });
208
- const state = inputs['state']?.value;
209
- assertClassifierState(state);
270
+ const graph = context.project?.graphs[context.execution?.graphId];
271
+ if (classifierInputDataValue(inputs, 'images') !== undefined ||
272
+ graph?.connections.some((connection) => connection.inputNodeId === this.id && connection.inputId === 'images')) {
273
+ throw new Error('The separate Images input has been removed. Connect images or an assembled user message to State.');
274
+ }
275
+ const stateInput = classifierInputDataValue(inputs, 'state');
276
+ // First-party providers prepare the Rivet wrapper at their common boundary.
277
+ // Existing custom descriptors still receive the legacy normalized State contract.
278
+ const state = provider.evaluateInput
279
+ ? { state: '', stateInput }
280
+ : normalizeClassifierState(stateInput, checkPreparation, provider.maxRequestBytes);
281
+ const legacyBudget = provider.evaluateInput
282
+ ? undefined
283
+ : new ClassifierValueBudget(checkPreparation, provider.maxRequestBytes);
284
+ legacyBudget?.inspect(state);
210
285
  const modelValue = this.data.useModelInput
211
- ? inputs['model']?.value
286
+ ? classifierInputDataValue(inputs, 'model')?.value
212
287
  : getStaticModel(this.data.model, provider.defaultModel);
213
288
  if (typeof modelValue !== 'string' || modelValue.trim() === '') {
214
289
  throw new Error(`${provider.label} model is required.`);
215
290
  }
291
+ legacyBudget?.inspect(modelValue);
216
292
  const questions = [];
217
- const questionInputs = Object.entries(inputs).filter(([portId]) => /^question\d+$/.test(portId));
218
- for (const [, input] of questionInputs.sort(compareQuestionPorts)) {
219
- if (input)
220
- flattenQuestions(input.value, questions);
293
+ const flattenWork = { values: 0 };
294
+ const questionInputs = Object.keys(inputs).filter((portId) => /^question\d+$/.test(portId));
295
+ for (const port of questionInputs.sort(compareQuestionPorts)) {
296
+ const input = classifierInputDataValue(inputs, port);
297
+ if (input) {
298
+ // Legacy descriptors do not own the shared preparation boundary.
299
+ legacyBudget?.inspect(input.value);
300
+ flattenQuestions(input.value, questions, checkPreparation, new Set(), 0, flattenWork);
301
+ }
221
302
  }
222
303
  if (questions.length === 0)
223
304
  throw new Error('Classifier Evaluate requires at least one question.');
224
- const ids = new Set();
225
- for (const question of questions) {
226
- validateQuestion(question);
227
- if (ids.has(question.questionId)) {
228
- throw new Error(`Question ID '${question.questionId}' is duplicated in this evaluation.`);
229
- }
230
- ids.add(question.questionId);
231
- }
232
- const result = await provider.evaluate({
305
+ const result = await (provider.evaluateInput ?? provider.evaluate).call(provider, {
233
306
  apiKey,
234
307
  model: modelValue,
235
308
  questions,
@@ -237,20 +310,34 @@ export class ClassifierEvaluateNodeImpl extends NodeImpl {
237
310
  retryOnNon200CooldownMs: this.data.retryOnNon200CooldownMs,
238
311
  retryOnNon200RepeatTimes: this.data.retryOnNon200RepeatTimes,
239
312
  signal: context.signal,
240
- state,
241
- timeoutMs: normalizeTimeout(this.data.timeoutMs),
313
+ ...state,
314
+ timeoutMs,
315
+ deadline,
316
+ });
317
+ // Custom providers still own their asynchronous transport, but no late
318
+ // result may become a successful node output after the original deadline.
319
+ checkPreparation();
320
+ const totalCost = calculateClassifierUsageCost(provider, result.response.usage, {
321
+ requestedModel: modelValue,
322
+ responseModel: result.response.model,
242
323
  });
243
- const totalCost = this.data.outputUsage ? calculateClassifierUsageCost(provider, result.response.usage) : undefined;
244
324
  // The provider's parsed response may also be exposed verbatim through the
245
325
  // diagnostic output. Do not mutate its Usage object while adding Rivet's
246
326
  // calculated accounting detail.
247
- const usage = totalCost === undefined ? result.response.usage : { ...result.response.usage, totalCost };
327
+ const usage = !this.data.outputUsage || totalCost === undefined
328
+ ? result.response.usage
329
+ : { ...result.response.usage, totalCost };
248
330
  const outputs = {
249
331
  ['answers']: { type: 'object', value: result.response.answers },
250
332
  ['usage']: { type: 'object', value: usage },
333
+ ['cost']: totalCost === undefined
334
+ ? { type: 'control-flow-excluded', value: undefined }
335
+ : { type: 'number', value: totalCost },
251
336
  };
252
337
  if (this.data.outputRequestBody === true) {
338
+ checkPreparation();
253
339
  outputs['requestBody'] = { type: 'object', value: result.requestBody };
340
+ checkPreparation();
254
341
  }
255
342
  if (this.data.outputResponseBody === true) {
256
343
  outputs['responseBody'] = { type: 'object', value: result.responseBody };
@@ -281,109 +368,62 @@ export function getClassifierEvaluateBodySections(data) {
281
368
  ],
282
369
  },
283
370
  ];
284
- if (data.retryOnNon200) {
371
+ if (data.errorOnNon200 !== false || data.catchRequestFailed || data.retryOnNon200) {
285
372
  sections.push({
286
373
  id: 'error-behavior',
287
374
  fields: [
288
- { label: 'Retry on non-200', value: 'Enabled' },
289
- { label: 'Repeat times', value: `${normalizeClassifierNon200RetryCount(data.retryOnNon200RepeatTimes)}` },
290
- { label: 'Cooldown, ms', value: `${normalizeClassifierNon200RetryCooldownMs(data.retryOnNon200CooldownMs)}` },
375
+ ...(data.errorOnNon200 !== false ? [{ label: 'Throw on non-2XX', value: 'Enabled' }] : []),
376
+ ...(data.catchRequestFailed ? [{ label: 'Catch all failures', value: 'Enabled' }] : []),
377
+ ...(data.retryOnNon200
378
+ ? [
379
+ { label: 'Retry on non-200', value: 'Enabled' },
380
+ { label: 'Repeat times', value: `${normalizeClassifierNon200RetryCount(data.retryOnNon200RepeatTimes)}` },
381
+ {
382
+ label: 'Cooldown, ms',
383
+ value: `${normalizeClassifierNon200RetryCooldownMs(data.retryOnNon200CooldownMs)}`,
384
+ },
385
+ ]
386
+ : []),
291
387
  ],
292
388
  });
293
389
  }
294
390
  return sections;
295
391
  }
296
- function compareQuestionPorts([left], [right]) {
392
+ function compareQuestionPorts(left, right) {
297
393
  return Number(left.slice('question'.length)) - Number(right.slice('question'.length));
298
394
  }
299
395
  function getApiKeySourceHelperMessage(data) {
300
396
  if (data.apiKeySource === 'input')
301
397
  return 'Uses the API Key input port instead of a configured provider key.';
302
398
  const provider = getProviderForDisplay(data.provider);
303
- return data.apiKeyNamesByProvider?.[provider.id] == null && data.apiKeyNames == null
304
- ? `Configured key checks ${provider.credentialNames.programmaticName} or ${provider.credentialNames.environmentVariableName}, including Settings > Classifier > ${provider.label} API Key.`
305
- : 'Configured key checks the named programmatic setting first, then the named environment variable.';
399
+ if (data.apiKeySource === 'classifier-settings')
400
+ return `Uses only Settings > Classifier > ${provider.label} API Key on the executor. A missing key fails without fallback.`;
401
+ return 'Automatic checks the named programmatic setting, then the named environment variable, then the saved Classifier key (default names only). OpenAI also accepts its legacy general key; Jev accepts its legacy plugin key last. Resolution happens on the executor, not in this editor.';
306
402
  }
307
- function flattenQuestions(value, target) {
403
+ function flattenQuestions(value, target, check, seen = new Set(), depth = 0, work = { values: 0 }) {
404
+ check();
405
+ if (++work.values > CLASSIFIER_LIMITS.values)
406
+ throw new Error('Question inputs have too many expanded values.');
407
+ if (depth > CLASSIFIER_LIMITS.depth)
408
+ throw new Error('Question inputs exceed the maximum nesting depth of 64.');
308
409
  if (Array.isArray(value)) {
309
- for (const item of value)
310
- flattenQuestions(item, target);
410
+ if (seen.has(value))
411
+ throw new Error('Question inputs must not contain circular arrays.');
412
+ seen.add(value);
413
+ if (value.length > CLASSIFIER_LIMITS.questions)
414
+ throw new Error('Classifier Evaluate supports at most 1000 questions.');
415
+ for (const item of classifierArrayValues(value, 'Questions'))
416
+ flattenQuestions(item, target, check, seen, depth + 1, work);
417
+ seen.delete(value);
311
418
  return;
312
419
  }
313
420
  if (typeof value !== 'object' || value === null) {
314
421
  throw new Error('Question inputs must contain question definition objects or nested arrays of definitions.');
315
422
  }
423
+ if (target.length >= CLASSIFIER_LIMITS.questions)
424
+ throw new Error('Classifier Evaluate supports at most 1000 questions.');
316
425
  target.push(value);
317
426
  }
318
- function validateQuestion(question) {
319
- if (typeof question.questionId !== 'string' || question.questionId.trim() === '') {
320
- throw new Error('Every classifier question must have a non-empty Question ID.');
321
- }
322
- if (!['choice', 'score', 'noul'].includes(question.type)) {
323
- throw new Error(`Question '${question.questionId}' has an unsupported type.`);
324
- }
325
- assertClassifierInstructions(question.instructions, `Question '${question.questionId}' instructions`);
326
- if (question.type === 'choice') {
327
- const criteria = question.criteria;
328
- if (typeof criteria !== 'object' || criteria === null || Array.isArray(criteria)) {
329
- throw new Error(`Choice question '${question.questionId}' requires object criteria.`);
330
- }
331
- const keys = Object.keys(criteria);
332
- if (keys.length < 2 || keys.length > 255) {
333
- throw new Error(`Choice question '${question.questionId}' requires 2 to 255 options.`);
334
- }
335
- for (const key of keys)
336
- assertClassifierEntry(criteria[key], `Question '${question.questionId}' criteria.${key}`);
337
- }
338
- else if (question.type === 'score') {
339
- const criteria = question.criteria;
340
- if (!Array.isArray(criteria) || criteria.length < 2 || criteria.length > 10) {
341
- throw new Error(`Score question '${question.questionId}' requires 2 to 10 levels.`);
342
- }
343
- criteria.forEach((entry, index) => assertClassifierEntry(entry, `Question '${question.questionId}' criteria[${index}]`));
344
- }
345
- else {
346
- const criteria = question.criteria;
347
- if (criteria !== undefined) {
348
- if (typeof criteria !== 'object' ||
349
- criteria === null ||
350
- Array.isArray(criteria) ||
351
- !Object.prototype.hasOwnProperty.call(criteria, 'true') ||
352
- !Object.prototype.hasOwnProperty.call(criteria, 'false')) {
353
- throw new Error(`Noul question '${question.questionId}' criteria must contain true and false entries.`);
354
- }
355
- assertClassifierEntry(criteria.true, `Question '${question.questionId}' criteria.true`);
356
- assertClassifierEntry(criteria.false, `Question '${question.questionId}' criteria.false`);
357
- }
358
- }
359
- }
360
- function assertClassifierState(value) {
361
- if (typeof value === 'string')
362
- return;
363
- if (typeof value !== 'object' || value === null)
364
- throw new Error('State must be a string, JSON object, or JSON array.');
365
- assertJsonCompatible(value, 'State', new Set());
366
- }
367
- function assertJsonCompatible(value, label, seen) {
368
- if (value === null || typeof value === 'string' || typeof value === 'boolean')
369
- return;
370
- if (typeof value === 'number') {
371
- if (!Number.isFinite(value))
372
- throw new Error(`${label} contains a non-finite number.`);
373
- return;
374
- }
375
- if (typeof value !== 'object')
376
- throw new Error(`${label} is not JSON-compatible.`);
377
- if (seen.has(value))
378
- throw new Error(`${label} contains a circular reference.`);
379
- seen.add(value);
380
- if (Array.isArray(value))
381
- value.forEach((item, index) => assertJsonCompatible(item, `${label}[${index}]`, seen));
382
- else
383
- for (const [key, item] of Object.entries(value))
384
- assertJsonCompatible(item, `${label}.${key}`, seen);
385
- seen.delete(value);
386
- }
387
427
  function normalizeTimeout(timeoutMs) {
388
428
  return typeof timeoutMs === 'number' && Number.isFinite(timeoutMs) && timeoutMs > 0
389
429
  ? Math.min(timeoutMs, 600_000)
@@ -2,8 +2,13 @@ import { nanoid } from 'nanoid/non-secure';
2
2
  import { nodeDefinition } from '../NodeDefinition.js';
3
3
  import { NodeImpl } from '../NodeImpl.js';
4
4
  import { formatNodeBodyMarkdownField, formatNodeBodyMarkdownSeparator, formatNodeBodyMarkdownTextRow, } from '../nodeBodyMarkdown.js';
5
- import { abbreviate, assertClassifierEntry, assertClassifierInstructions, getCriteriaInputDefinition, getInstructionsInputDefinition, getInterpolationInputDefinitions, getStringInput, getStructuredInput, interpolateQuestionText, requireQuestionId, resolveAuthoredClassifierEntry, } from '../classifier/questionHelpers.js';
6
- const defaultOptions = () => [{ key: '', value: '' }, { key: '', value: '' }];
5
+ import { ClassifierQuestionPreparation } from '../classifier/preparation.js';
6
+ import { assertClassifierJson } from '../classifier/json.js';
7
+ import { abbreviate, assertClassifierEntry, assertClassifierInstructions, getCriteriaInputDefinition, getInstructionsInputDefinition, getInterpolationInputDefinitions, getQuestionInputValue, getStringInput, getStructuredInput, interpolateQuestionText, requireQuestionId, resolveAuthoredClassifierEntry, } from '../classifier/questionHelpers.js';
8
+ const defaultOptions = () => [
9
+ { key: '', value: '' },
10
+ { key: '', value: '' },
11
+ ];
7
12
  const defaultLevels = () => ['', ''];
8
13
  const defaultScoreCriteria = () => [createScoreCriterion(), createScoreCriterion()];
9
14
  const entryTypeOptions = [
@@ -59,7 +64,9 @@ export class ClassifierQuestionNodeImpl extends NodeImpl {
59
64
  if (data.useNoulFalseCriteriaInput)
60
65
  inputs.push(getNoulCriteriaInputDefinition('criteriaFalse', 'false', criteriaType));
61
66
  }
62
- const templates = data.useInstructionsInput ? [] : getEntryTemplates(data.instructionsType, data.instructions, data.instructionsLines, data.instructionsObjectTemplate);
67
+ const templates = data.useInstructionsInput
68
+ ? []
69
+ : getEntryTemplates(data.instructionsType, data.instructions, data.instructionsLines, data.instructionsObjectTemplate);
63
70
  if (!data.useCriteriaInput) {
64
71
  if (data.questionType === 'choice') {
65
72
  if (getCriteriaType(data) === 'text')
@@ -298,7 +305,33 @@ export class ClassifierQuestionNodeImpl extends NodeImpl {
298
305
  };
299
306
  }
300
307
  async process(inputs, context) {
308
+ const preparation = new ClassifierQuestionPreparation(context);
301
309
  const data = this.data;
310
+ preparation.capture(data.questionId);
311
+ // Reject impossible cardinalities before resolving even Instructions.
312
+ const criteria = data.useCriteriaInput ? getQuestionInputValue(inputs, 'criteria', 'Criteria') : undefined;
313
+ if (data.questionType === 'score') {
314
+ const count = data.useCriteriaInput
315
+ ? Array.isArray(criteria)
316
+ ? criteria.length
317
+ : 0
318
+ : (data.scoreCriteria ?? data.levels ?? defaultLevels()).length;
319
+ if (count < 2 || count > 10)
320
+ throw new Error('Score questions require 2 to 10 levels.');
321
+ }
322
+ else if (data.questionType === 'choice') {
323
+ const count = data.useCriteriaInput
324
+ ? criteria && typeof criteria === 'object' && !Array.isArray(criteria)
325
+ ? Object.keys(criteria).length
326
+ : 0
327
+ : (getCriteriaType(data) === 'text'
328
+ ? data.options ?? defaultOptions()
329
+ : data.choiceCriteria ?? data.options ?? defaultOptions()).length;
330
+ if (count < 2 || count > 255)
331
+ throw new Error('Choice questions require 2 to 255 options.');
332
+ }
333
+ if (data.useInstructionsInput)
334
+ preparation.capture(getQuestionInputValue(inputs, 'instructions', 'Instructions'));
302
335
  const questionId = requireQuestionId(data.questionId);
303
336
  const instructions = data.useInstructionsInput
304
337
  ? getStructuredInput(inputs, 'instructions', 'Instructions')
@@ -310,9 +343,12 @@ export class ClassifierQuestionNodeImpl extends NodeImpl {
310
343
  inputs,
311
344
  context,
312
345
  label: 'Instructions',
346
+ preparation,
313
347
  });
314
348
  assertClassifierInstructions(instructions);
315
- const question = createQuestionDefinition(data, inputs, context, questionId, instructions);
349
+ const question = createQuestionDefinition(data, inputs, context, questionId, instructions, preparation);
350
+ assertClassifierJson(question, 'Question', false, preparation.check);
351
+ preparation.check();
316
352
  return { ['question']: { type: 'object', value: question } };
317
353
  }
318
354
  }
@@ -377,18 +413,19 @@ function getInstructionsBodySection(data) {
377
413
  return { id: 'instructions', fields: [{ label: 'Instructions', value: 'object' }] };
378
414
  return { id: 'instructions', fields: [], summary: abbreviate(data.instructions) || '(required)' };
379
415
  }
380
- function createQuestionDefinition(data, inputs, context, questionId, instructions) {
416
+ function createQuestionDefinition(data, inputs, context, questionId, instructions, preparation) {
381
417
  if (data.questionType === 'choice') {
382
- return createChoiceQuestion(data, inputs, context, questionId, instructions);
418
+ return createChoiceQuestion(data, inputs, context, questionId, instructions, preparation);
383
419
  }
384
420
  if (data.questionType === 'score') {
385
- return createScoreQuestion(data, inputs, context, questionId, instructions);
421
+ return createScoreQuestion(data, inputs, context, questionId, instructions, preparation);
386
422
  }
387
- return createNoulQuestion(data, inputs, context, questionId, instructions);
423
+ return createNoulQuestion(data, inputs, context, questionId, instructions, preparation);
388
424
  }
389
- function createChoiceQuestion(data, inputs, context, questionId, instructions) {
425
+ function createChoiceQuestion(data, inputs, context, questionId, instructions, preparation) {
390
426
  let criteria;
391
427
  if (data.useCriteriaInput) {
428
+ preparation.capture(getQuestionInputValue(inputs, 'criteria', 'Criteria'));
392
429
  const value = getStructuredInput(inputs, 'criteria', 'Criteria');
393
430
  if (value === null || Array.isArray(value) || typeof value !== 'object') {
394
431
  throw new Error('Choice criteria must be an object.');
@@ -405,6 +442,7 @@ function createChoiceQuestion(data, inputs, context, questionId, instructions) {
405
442
  throw new Error('Choice questions require 2 to 255 options.');
406
443
  criteria = Object.create(null);
407
444
  for (const option of options) {
445
+ preparation.capture(option.key);
408
446
  if (option.key.trim() === '')
409
447
  throw new Error('Choice criterion names must not be empty.');
410
448
  if (Object.prototype.hasOwnProperty.call(criteria, option.key)) {
@@ -413,7 +451,7 @@ function createChoiceQuestion(data, inputs, context, questionId, instructions) {
413
451
  Object.defineProperty(criteria, option.key, {
414
452
  enumerable: true,
415
453
  value: criteriaType === 'text'
416
- ? interpolateQuestionText(option.value, inputs, context) || null
454
+ ? interpolateQuestionText(option.value, inputs, context, preparation) || null
417
455
  : resolveAuthoredClassifierEntry({
418
456
  type: criteriaType,
419
457
  text: option.text,
@@ -422,6 +460,7 @@ function createChoiceQuestion(data, inputs, context, questionId, instructions) {
422
460
  inputs,
423
461
  context,
424
462
  label: `Criteria.${option.key}`,
463
+ preparation,
425
464
  }),
426
465
  });
427
466
  }
@@ -433,9 +472,10 @@ function createChoiceQuestion(data, inputs, context, questionId, instructions) {
433
472
  assertClassifierEntry(entry, `Criteria.${key}`);
434
473
  return { questionId, type: 'choice', instructions, criteria };
435
474
  }
436
- function createScoreQuestion(data, inputs, context, questionId, instructions) {
475
+ function createScoreQuestion(data, inputs, context, questionId, instructions, preparation) {
437
476
  let criteria;
438
477
  if (data.useCriteriaInput) {
478
+ preparation.capture(getQuestionInputValue(inputs, 'criteria', 'Criteria'));
439
479
  const value = getStructuredInput(inputs, 'criteria', 'Criteria');
440
480
  if (!Array.isArray(value))
441
481
  throw new Error('Score criteria must be an array.');
@@ -450,6 +490,7 @@ function createScoreQuestion(data, inputs, context, questionId, instructions) {
450
490
  inputs,
451
491
  context,
452
492
  label: `Criteria[${index}]`,
493
+ preparation,
453
494
  }));
454
495
  }
455
496
  if (criteria.length < 2 || criteria.length > 10)
@@ -457,9 +498,10 @@ function createScoreQuestion(data, inputs, context, questionId, instructions) {
457
498
  criteria.forEach((entry, index) => assertClassifierEntry(entry, `Criteria[${index}]`));
458
499
  return { questionId, type: 'score', instructions, criteria };
459
500
  }
460
- function createNoulQuestion(data, inputs, context, questionId, instructions) {
501
+ function createNoulQuestion(data, inputs, context, questionId, instructions, preparation) {
461
502
  let criteria;
462
503
  if (data.useCriteriaInput) {
504
+ preparation.capture(getQuestionInputValue(inputs, 'criteria', 'Criteria'));
463
505
  const value = getStructuredInput(inputs, 'criteria', 'Criteria');
464
506
  if (value === null ||
465
507
  Array.isArray(value) ||
@@ -471,8 +513,8 @@ function createNoulQuestion(data, inputs, context, questionId, instructions) {
471
513
  criteria = { true: value.true, false: value.false };
472
514
  }
473
515
  else {
474
- const trueCriteria = resolveNoulCriteria(data, 'true', inputs, context);
475
- const falseCriteria = resolveNoulCriteria(data, 'false', inputs, context);
516
+ const trueCriteria = resolveNoulCriteria(data, 'true', inputs, context, preparation);
517
+ const falseCriteria = resolveNoulCriteria(data, 'false', inputs, context, preparation);
476
518
  if (hasClassifierCriteriaValue(trueCriteria) || hasClassifierCriteriaValue(falseCriteria)) {
477
519
  if (!hasClassifierCriteriaValue(trueCriteria) || !hasClassifierCriteriaValue(falseCriteria)) {
478
520
  throw new Error('Provide both true and false criteria, or neither.');
@@ -537,10 +579,11 @@ function hasAuthoredNoulCriteria(data, truthValue) {
537
579
  }
538
580
  return (truthValue === 'true' ? getNoulTrueCriteria(data) : getNoulFalseCriteria(data)).trim() !== '';
539
581
  }
540
- function resolveNoulCriteria(data, truthValue, inputs, context) {
582
+ function resolveNoulCriteria(data, truthValue, inputs, context, preparation) {
541
583
  const useInput = truthValue === 'true' ? data.useNoulTrueCriteriaInput : data.useNoulFalseCriteriaInput;
542
584
  const label = `${truthValue} criteria`;
543
585
  if (useInput) {
586
+ preparation.capture(getQuestionInputValue(inputs, `criteria${truthValue === 'true' ? 'True' : 'False'}`, label));
544
587
  return getCriteriaType(data) === 'text'
545
588
  ? getStringInput(inputs, `criteria${truthValue === 'true' ? 'True' : 'False'}`, label)
546
589
  : getStructuredInput(inputs, `criteria${truthValue === 'true' ? 'True' : 'False'}`, label);
@@ -553,6 +596,7 @@ function resolveNoulCriteria(data, truthValue, inputs, context) {
553
596
  inputs,
554
597
  context,
555
598
  label,
599
+ preparation,
556
600
  });
557
601
  }
558
602
  function hasClassifierCriteriaValue(value) {
@@ -42,11 +42,11 @@ export class GetGlobalNodeImpl extends NodeImpl {
42
42
  return [];
43
43
  }
44
44
  getOutputDefinitions() {
45
- const { onDemand, dataType } = this.chartNode.data;
45
+ const { id, useIdInput, onDemand, dataType } = this.chartNode.data;
46
46
  return [
47
47
  {
48
48
  id: 'value',
49
- title: 'Value',
49
+ title: !useIdInput && typeof id === 'string' && id.trim() ? id : 'Value',
50
50
  dataType: onDemand ? `fn<${dataType}>` : dataType,
51
51
  },
52
52
  {