@valerypopoff/rivet2-core 2.13.0 → 2.15.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 (48) hide show
  1. package/dist/cjs/bundle.cjs +2485 -425
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/esm/api/createProcessor.js +5 -0
  4. package/dist/esm/api/processSettings.js +1 -0
  5. package/dist/esm/exports.js +4 -0
  6. package/dist/esm/model/GraphProcessor.js +10 -16
  7. package/dist/esm/model/MarkdownSanitizationPolicy.js +2 -0
  8. package/dist/esm/model/NodeImpl.js +1 -1
  9. package/dist/esm/model/Nodes.js +6 -0
  10. package/dist/esm/model/StreamingWatchTopology.js +98 -61
  11. package/dist/esm/model/classifier/credentials.js +81 -0
  12. package/dist/esm/model/classifier/migration.js +97 -0
  13. package/dist/esm/model/classifier/providers.js +347 -0
  14. package/dist/esm/model/classifier/questionHelpers.js +125 -0
  15. package/dist/esm/model/classifier/types.js +1 -0
  16. package/dist/esm/model/nodeBodyMarkdown.js +37 -0
  17. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +392 -0
  18. package/dist/esm/model/nodes/ClassifierQuestionNode.js +569 -0
  19. package/dist/esm/model/nodes/CodeNewNode.js +33 -9
  20. package/dist/esm/model/nodes/LLMChatV2Node.js +3 -12
  21. package/dist/esm/model/nodes/LLMProfileNode.js +6 -12
  22. package/dist/esm/model/nodes/MatchCaseNode.js +76 -1
  23. package/dist/esm/model/nodes/MatchCaseNodeBase.js +24 -2
  24. package/dist/esm/model/nodes/ObjectNode.js +48 -41
  25. package/dist/esm/model/nodes/PassthroughNode.js +1 -1
  26. package/dist/esm/model/nodes/codeOutputInference.js +292 -0
  27. package/dist/esm/utils/serialization/serialization.js +4 -0
  28. package/dist/types/exports.d.ts +4 -0
  29. package/dist/types/model/EditorDefinition.d.ts +24 -0
  30. package/dist/types/model/MarkdownSanitizationPolicy.d.ts +1 -1
  31. package/dist/types/model/NodeImpl.d.ts +3 -1
  32. package/dist/types/model/Nodes.d.ts +6 -4
  33. package/dist/types/model/Settings.d.ts +4 -0
  34. package/dist/types/model/StreamingWatchTopology.d.ts +6 -0
  35. package/dist/types/model/classifier/credentials.d.ts +24 -0
  36. package/dist/types/model/classifier/migration.d.ts +18 -0
  37. package/dist/types/model/classifier/providers.d.ts +78 -0
  38. package/dist/types/model/classifier/questionHelpers.d.ts +31 -0
  39. package/dist/types/model/classifier/types.d.ts +58 -0
  40. package/dist/types/model/nodeBodyMarkdown.d.ts +19 -0
  41. package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +47 -0
  42. package/dist/types/model/nodes/ClassifierQuestionNode.d.ts +60 -0
  43. package/dist/types/model/nodes/CodeNewNode.d.ts +6 -0
  44. package/dist/types/model/nodes/MatchCaseNode.d.ts +8 -1
  45. package/dist/types/model/nodes/MatchCaseNodeBase.d.ts +13 -1
  46. package/dist/types/model/nodes/ObjectNode.d.ts +5 -0
  47. package/dist/types/model/nodes/codeOutputInference.d.ts +31 -0
  48. package/package.json +1 -1
@@ -0,0 +1,569 @@
1
+ import { nanoid } from 'nanoid/non-secure';
2
+ import { nodeDefinition } from '../NodeDefinition.js';
3
+ import { NodeImpl } from '../NodeImpl.js';
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: '' }];
7
+ const defaultLevels = () => ['', ''];
8
+ const defaultScoreCriteria = () => [createScoreCriterion(), createScoreCriterion()];
9
+ const entryTypeOptions = [
10
+ { value: 'text', label: 'Text' },
11
+ { value: 'lines', label: 'List of lines' },
12
+ { value: 'object', label: 'Object' },
13
+ ];
14
+ function createScoreCriterion() {
15
+ return { id: nanoid(), type: 'text', text: '', lines: [''], objectTemplate: '{}' };
16
+ }
17
+ function createChoiceCriterion() {
18
+ return { id: nanoid(), key: '', text: '', lines: [''], objectTemplate: '{}' };
19
+ }
20
+ export class ClassifierQuestionNodeImpl extends NodeImpl {
21
+ static create() {
22
+ return {
23
+ type: 'classifierQuestion',
24
+ title: 'Classifier Question',
25
+ id: nanoid(),
26
+ visualData: { x: 0, y: 0, width: 280 },
27
+ data: {
28
+ questionType: 'choice',
29
+ questionId: 'choice',
30
+ instructions: '',
31
+ instructionsType: 'text',
32
+ instructionsLines: [''],
33
+ instructionsObjectTemplate: '{}',
34
+ criteriaType: 'text',
35
+ options: defaultOptions(),
36
+ choiceCriteria: [createChoiceCriterion(), createChoiceCriterion()],
37
+ scoreCriteria: defaultScoreCriteria(),
38
+ noulTrueCriteria: '',
39
+ noulFalseCriteria: '',
40
+ noulTrueCriteriaLines: [''],
41
+ noulFalseCriteriaLines: [''],
42
+ noulTrueCriteriaObjectTemplate: '{}',
43
+ noulFalseCriteriaObjectTemplate: '{}',
44
+ },
45
+ };
46
+ }
47
+ getInputDefinitions() {
48
+ const data = this.data;
49
+ const inputs = [];
50
+ if (data.useInstructionsInput)
51
+ inputs.push(getInstructionsInputDefinition());
52
+ if (data.useCriteriaInput) {
53
+ inputs.push(getCriteriaInputDefinition(getCriteriaInputTypes(data.questionType)));
54
+ }
55
+ else if (data.questionType === 'noul') {
56
+ const criteriaType = getCriteriaType(data);
57
+ if (data.useNoulTrueCriteriaInput)
58
+ inputs.push(getNoulCriteriaInputDefinition('criteriaTrue', 'true', criteriaType));
59
+ if (data.useNoulFalseCriteriaInput)
60
+ inputs.push(getNoulCriteriaInputDefinition('criteriaFalse', 'false', criteriaType));
61
+ }
62
+ const templates = data.useInstructionsInput ? [] : getEntryTemplates(data.instructionsType, data.instructions, data.instructionsLines, data.instructionsObjectTemplate);
63
+ if (!data.useCriteriaInput) {
64
+ if (data.questionType === 'choice') {
65
+ if (getCriteriaType(data) === 'text')
66
+ templates.push(...(data.options ?? []).map((option) => option.value));
67
+ else {
68
+ for (const criterion of getChoiceCriteria(data)) {
69
+ templates.push(...getEntryTemplates(getCriteriaType(data), criterion.text, criterion.lines, criterion.objectTemplate));
70
+ }
71
+ }
72
+ }
73
+ else if (data.questionType === 'score') {
74
+ for (const criterion of getScoreCriteria(data)) {
75
+ templates.push(...getEntryTemplates(data.criteriaType ?? criterion.type, criterion.text, criterion.lines, criterion.objectTemplate));
76
+ }
77
+ }
78
+ else {
79
+ if (!data.useNoulTrueCriteriaInput)
80
+ templates.push(...getNoulCriteriaTemplates(data, 'true'));
81
+ if (!data.useNoulFalseCriteriaInput)
82
+ templates.push(...getNoulCriteriaTemplates(data, 'false'));
83
+ }
84
+ }
85
+ inputs.push(...getInterpolationInputDefinitions(templates, new Set(inputs.map((input) => input.id))));
86
+ return inputs;
87
+ }
88
+ getOutputDefinitions() {
89
+ return [{ id: 'question', title: 'Question', dataType: 'object' }];
90
+ }
91
+ getEditors() {
92
+ return [
93
+ {
94
+ type: 'segmented',
95
+ label: 'Question type',
96
+ ariaLabel: 'Question type',
97
+ dataKey: 'questionType',
98
+ options: [
99
+ { value: 'noul', label: 'Noul' },
100
+ { value: 'choice', label: 'Choice' },
101
+ { value: 'score', label: 'Score' },
102
+ ],
103
+ defaultValue: 'choice',
104
+ allowOptionWrap: false,
105
+ },
106
+ { type: 'string', label: 'Question ID', dataKey: 'questionId' },
107
+ {
108
+ type: 'group',
109
+ label: 'Instructions',
110
+ presentation: 'section',
111
+ editors: [
112
+ {
113
+ type: 'dropdown',
114
+ label: '',
115
+ ariaLabel: 'Instructions type',
116
+ dataKey: 'instructionsType',
117
+ options: entryTypeOptions,
118
+ defaultValue: 'text',
119
+ },
120
+ {
121
+ type: 'code',
122
+ label: '',
123
+ dataKey: 'instructions',
124
+ useInputToggleDataKey: 'useInstructionsInput',
125
+ language: 'prompt-interpolation-markdown',
126
+ theme: 'prompt-interpolation',
127
+ height: 100,
128
+ hideIf: (data) => (data.instructionsType ?? 'text') !== 'text',
129
+ },
130
+ {
131
+ type: 'stringList',
132
+ label: '',
133
+ dataKey: 'instructionsLines',
134
+ useInputToggleDataKey: 'useInstructionsInput',
135
+ placeholder: 'Instruction line',
136
+ highlightInterpolationTokens: true,
137
+ inputFontFamily: 'monospace',
138
+ minimumItems: 1,
139
+ reorderable: true,
140
+ hideIf: (data) => data.instructionsType !== 'lines',
141
+ },
142
+ {
143
+ type: 'code',
144
+ label: '',
145
+ dataKey: 'instructionsObjectTemplate',
146
+ useInputToggleDataKey: 'useInstructionsInput',
147
+ language: 'json',
148
+ interpolationSyntax: 'json-template',
149
+ theme: 'prompt-interpolation',
150
+ enableFolding: true,
151
+ defaultValue: '{}',
152
+ height: 200,
153
+ hideIf: (data) => data.instructionsType !== 'object',
154
+ },
155
+ ],
156
+ },
157
+ {
158
+ type: 'group',
159
+ label: 'Criteria',
160
+ presentation: 'section',
161
+ hideIf: (data) => data.questionType === 'noul' && Boolean(data.useCriteriaInput),
162
+ editors: [
163
+ {
164
+ type: 'dropdown',
165
+ label: '',
166
+ ariaLabel: 'Criteria type',
167
+ dataKey: 'criteriaType',
168
+ options: entryTypeOptions,
169
+ defaultValue: 'text',
170
+ },
171
+ {
172
+ type: 'keyValuePair',
173
+ label: '',
174
+ dataKey: 'options',
175
+ useInputToggleDataKey: 'useCriteriaInput',
176
+ keyPlaceholder: 'Name',
177
+ valuePlaceholder: 'Optional description',
178
+ itemLabel: 'criterion',
179
+ reorderable: true,
180
+ highlightInterpolationTokens: true,
181
+ hideIf: (data) => data.questionType !== 'choice' || getCriteriaType(data) !== 'text',
182
+ },
183
+ {
184
+ type: 'custom',
185
+ customEditorId: 'ClassifierChoiceCriteria',
186
+ label: '',
187
+ dataKey: 'choiceCriteria',
188
+ useInputToggleDataKey: 'useCriteriaInput',
189
+ hideIf: (data) => data.questionType !== 'choice' || getCriteriaType(data) === 'text',
190
+ },
191
+ {
192
+ type: 'custom',
193
+ customEditorId: 'ClassifierScoreCriteria',
194
+ label: '',
195
+ dataKey: 'scoreCriteria',
196
+ useInputToggleDataKey: 'useCriteriaInput',
197
+ hideIf: (data) => data.questionType !== 'score',
198
+ },
199
+ {
200
+ type: 'code',
201
+ label: 'true',
202
+ dataKey: 'noulTrueCriteria',
203
+ useInputToggleDataKey: 'useNoulTrueCriteriaInput',
204
+ language: 'prompt-interpolation-markdown',
205
+ theme: 'prompt-interpolation',
206
+ height: 80,
207
+ hideIf: (data) => data.questionType !== 'noul' || getCriteriaType(data) !== 'text',
208
+ },
209
+ {
210
+ type: 'code',
211
+ label: 'false',
212
+ dataKey: 'noulFalseCriteria',
213
+ useInputToggleDataKey: 'useNoulFalseCriteriaInput',
214
+ language: 'prompt-interpolation-markdown',
215
+ theme: 'prompt-interpolation',
216
+ height: 80,
217
+ hideIf: (data) => data.questionType !== 'noul' || getCriteriaType(data) !== 'text',
218
+ },
219
+ {
220
+ type: 'stringList',
221
+ label: 'true',
222
+ dataKey: 'noulTrueCriteriaLines',
223
+ useInputToggleDataKey: 'useNoulTrueCriteriaInput',
224
+ placeholder: 'Criterion line',
225
+ highlightInterpolationTokens: true,
226
+ inputFontFamily: 'monospace',
227
+ minimumItems: 1,
228
+ reorderable: true,
229
+ hideIf: (data) => data.questionType !== 'noul' || getCriteriaType(data) !== 'lines',
230
+ },
231
+ {
232
+ type: 'stringList',
233
+ label: 'false',
234
+ dataKey: 'noulFalseCriteriaLines',
235
+ useInputToggleDataKey: 'useNoulFalseCriteriaInput',
236
+ placeholder: 'Criterion line',
237
+ highlightInterpolationTokens: true,
238
+ inputFontFamily: 'monospace',
239
+ minimumItems: 1,
240
+ reorderable: true,
241
+ hideIf: (data) => data.questionType !== 'noul' || getCriteriaType(data) !== 'lines',
242
+ },
243
+ {
244
+ type: 'code',
245
+ label: 'true',
246
+ dataKey: 'noulTrueCriteriaObjectTemplate',
247
+ useInputToggleDataKey: 'useNoulTrueCriteriaInput',
248
+ language: 'json',
249
+ interpolationSyntax: 'json-template',
250
+ theme: 'prompt-interpolation',
251
+ enableFolding: true,
252
+ defaultValue: '{}',
253
+ height: 200,
254
+ hideIf: (data) => data.questionType !== 'noul' || getCriteriaType(data) !== 'object',
255
+ },
256
+ {
257
+ type: 'code',
258
+ label: 'false',
259
+ dataKey: 'noulFalseCriteriaObjectTemplate',
260
+ useInputToggleDataKey: 'useNoulFalseCriteriaInput',
261
+ language: 'json',
262
+ interpolationSyntax: 'json-template',
263
+ theme: 'prompt-interpolation',
264
+ enableFolding: true,
265
+ defaultValue: '{}',
266
+ height: 200,
267
+ hideIf: (data) => data.questionType !== 'noul' || getCriteriaType(data) !== 'object',
268
+ },
269
+ ],
270
+ },
271
+ ];
272
+ }
273
+ getBody() {
274
+ const sections = getClassifierQuestionBodySections(this.data);
275
+ const identity = sections[0];
276
+ const instructions = sections[1];
277
+ const criteria = sections[2];
278
+ return {
279
+ type: 'markdown',
280
+ disableLinks: true,
281
+ text: [
282
+ ...identity.fields.map((field) => formatNodeBodyMarkdownField(field.label, field.value)),
283
+ formatNodeBodyMarkdownSeparator(),
284
+ ...(instructions.summary === undefined
285
+ ? instructions.fields.map((field) => formatNodeBodyMarkdownField(field.label, field.value))
286
+ : [formatNodeBodyMarkdownTextRow(instructions.summary)]),
287
+ formatNodeBodyMarkdownSeparator(),
288
+ ...criteria.fields.map((field) => formatNodeBodyMarkdownField(field.label, field.value)),
289
+ ].join(''),
290
+ };
291
+ }
292
+ static getUIData() {
293
+ return {
294
+ contextMenuTitle: 'Classifier Question',
295
+ infoBoxTitle: 'Classifier Question',
296
+ infoBoxBody: 'Builds one typed classifier question without making a network request.',
297
+ group: ['Classifier'],
298
+ };
299
+ }
300
+ async process(inputs, context) {
301
+ const data = this.data;
302
+ const questionId = requireQuestionId(data.questionId);
303
+ const instructions = data.useInstructionsInput
304
+ ? getStructuredInput(inputs, 'instructions', 'Instructions')
305
+ : resolveAuthoredClassifierEntry({
306
+ type: data.instructionsType,
307
+ text: data.instructions,
308
+ lines: data.instructionsLines,
309
+ objectTemplate: data.instructionsObjectTemplate,
310
+ inputs,
311
+ context,
312
+ label: 'Instructions',
313
+ });
314
+ assertClassifierInstructions(instructions);
315
+ const question = createQuestionDefinition(data, inputs, context, questionId, instructions);
316
+ return { ['question']: { type: 'object', value: question } };
317
+ }
318
+ }
319
+ function getCriteriaInputTypes(questionType) {
320
+ return questionType === 'score' ? ['object[]', 'any', 'any[]'] : ['object', 'any'];
321
+ }
322
+ function getNoulCriteriaInputDefinition(id, title, criteriaType) {
323
+ return {
324
+ id: id,
325
+ title,
326
+ dataType: criteriaType === 'text' ? 'string' : ['string', 'object', 'object[]', 'any', 'any[]'],
327
+ required: true,
328
+ splitRunBehavior: criteriaType === 'text' ? undefined : 'preserve-array',
329
+ description: `Description for the Noul ${title} criterion.`,
330
+ };
331
+ }
332
+ function getQuestionTypeLabel(questionType) {
333
+ return questionType === 'noul' ? 'Noul' : questionType[0].toUpperCase() + questionType.slice(1);
334
+ }
335
+ /**
336
+ * Shared presentation model for the app's Classifier card. Keep this data-only
337
+ * so the Core Markdown fallback and the app's LLM-style React body cannot
338
+ * disagree about what a saved question represents.
339
+ */
340
+ export function getClassifierQuestionBodySections(data) {
341
+ const instructions = getInstructionsBodySection(data);
342
+ return [
343
+ {
344
+ id: 'identity',
345
+ fields: [
346
+ { label: 'Type', value: getQuestionTypeLabel(data.questionType) },
347
+ { label: 'ID', value: data.questionId || '(required)' },
348
+ ],
349
+ },
350
+ instructions,
351
+ {
352
+ id: 'criteria',
353
+ fields: [{ label: 'Criteria', value: data.useCriteriaInput ? 'input' : getCriteriaSummary(data) }],
354
+ },
355
+ ];
356
+ }
357
+ function getCriteriaSummary(data) {
358
+ if (data.questionType === 'choice') {
359
+ return `${getCriteriaType(data) === 'text' ? (data.options ?? []).length : getChoiceCriteria(data).length} choices`;
360
+ }
361
+ if (data.questionType === 'score')
362
+ return `${getScoreCriteria(data).length} ordered criteria`;
363
+ const count = Number(data.useNoulTrueCriteriaInput || hasAuthoredNoulCriteria(data, 'true')) +
364
+ Number(data.useNoulFalseCriteriaInput || hasAuthoredNoulCriteria(data, 'false'));
365
+ return `${count} descriptions`;
366
+ }
367
+ function getInstructionsBodySection(data) {
368
+ if (data.useInstructionsInput)
369
+ return { id: 'instructions', fields: [{ label: 'Instructions', value: 'input' }] };
370
+ if (data.instructionsType === 'lines') {
371
+ return {
372
+ id: 'instructions',
373
+ fields: [{ label: 'Instructions', value: `${Math.max(1, data.instructionsLines?.length ?? 0)} lines` }],
374
+ };
375
+ }
376
+ if (data.instructionsType === 'object')
377
+ return { id: 'instructions', fields: [{ label: 'Instructions', value: 'object' }] };
378
+ return { id: 'instructions', fields: [], summary: abbreviate(data.instructions) || '(required)' };
379
+ }
380
+ function createQuestionDefinition(data, inputs, context, questionId, instructions) {
381
+ if (data.questionType === 'choice') {
382
+ return createChoiceQuestion(data, inputs, context, questionId, instructions);
383
+ }
384
+ if (data.questionType === 'score') {
385
+ return createScoreQuestion(data, inputs, context, questionId, instructions);
386
+ }
387
+ return createNoulQuestion(data, inputs, context, questionId, instructions);
388
+ }
389
+ function createChoiceQuestion(data, inputs, context, questionId, instructions) {
390
+ let criteria;
391
+ if (data.useCriteriaInput) {
392
+ const value = getStructuredInput(inputs, 'criteria', 'Criteria');
393
+ if (value === null || Array.isArray(value) || typeof value !== 'object') {
394
+ throw new Error('Choice criteria must be an object.');
395
+ }
396
+ criteria = Object.create(null);
397
+ for (const [key, entry] of Object.entries(value)) {
398
+ Object.defineProperty(criteria, key, { enumerable: true, value: entry });
399
+ }
400
+ }
401
+ else {
402
+ const criteriaType = getCriteriaType(data);
403
+ const options = criteriaType === 'text' ? data.options ?? defaultOptions() : getChoiceCriteria(data);
404
+ if (options.length < 2 || options.length > 255)
405
+ throw new Error('Choice questions require 2 to 255 options.');
406
+ criteria = Object.create(null);
407
+ for (const option of options) {
408
+ if (option.key.trim() === '')
409
+ throw new Error('Choice criterion names must not be empty.');
410
+ if (Object.prototype.hasOwnProperty.call(criteria, option.key)) {
411
+ throw new Error(`Choice criterion name '${option.key}' is duplicated.`);
412
+ }
413
+ Object.defineProperty(criteria, option.key, {
414
+ enumerable: true,
415
+ value: criteriaType === 'text'
416
+ ? interpolateQuestionText(option.value, inputs, context) || null
417
+ : resolveAuthoredClassifierEntry({
418
+ type: criteriaType,
419
+ text: option.text,
420
+ lines: option.lines,
421
+ objectTemplate: option.objectTemplate,
422
+ inputs,
423
+ context,
424
+ label: `Criteria.${option.key}`,
425
+ }),
426
+ });
427
+ }
428
+ }
429
+ const keys = Object.keys(criteria);
430
+ if (keys.length < 2 || keys.length > 255)
431
+ throw new Error('Choice questions require 2 to 255 unique options.');
432
+ for (const [key, entry] of Object.entries(criteria))
433
+ assertClassifierEntry(entry, `Criteria.${key}`);
434
+ return { questionId, type: 'choice', instructions, criteria };
435
+ }
436
+ function createScoreQuestion(data, inputs, context, questionId, instructions) {
437
+ let criteria;
438
+ if (data.useCriteriaInput) {
439
+ const value = getStructuredInput(inputs, 'criteria', 'Criteria');
440
+ if (!Array.isArray(value))
441
+ throw new Error('Score criteria must be an array.');
442
+ criteria = value;
443
+ }
444
+ else {
445
+ criteria = getScoreCriteria(data).map((criterion, index) => resolveAuthoredClassifierEntry({
446
+ type: data.criteriaType ?? criterion.type,
447
+ text: criterion.text,
448
+ lines: criterion.lines,
449
+ objectTemplate: criterion.objectTemplate,
450
+ inputs,
451
+ context,
452
+ label: `Criteria[${index}]`,
453
+ }));
454
+ }
455
+ if (criteria.length < 2 || criteria.length > 10)
456
+ throw new Error('Score questions require 2 to 10 levels.');
457
+ criteria.forEach((entry, index) => assertClassifierEntry(entry, `Criteria[${index}]`));
458
+ return { questionId, type: 'score', instructions, criteria };
459
+ }
460
+ function createNoulQuestion(data, inputs, context, questionId, instructions) {
461
+ let criteria;
462
+ if (data.useCriteriaInput) {
463
+ const value = getStructuredInput(inputs, 'criteria', 'Criteria');
464
+ if (value === null ||
465
+ Array.isArray(value) ||
466
+ typeof value !== 'object' ||
467
+ !Object.prototype.hasOwnProperty.call(value, 'true') ||
468
+ !Object.prototype.hasOwnProperty.call(value, 'false')) {
469
+ throw new Error('Noul criteria must contain both true and false entries.');
470
+ }
471
+ criteria = { true: value.true, false: value.false };
472
+ }
473
+ else {
474
+ const trueCriteria = resolveNoulCriteria(data, 'true', inputs, context);
475
+ const falseCriteria = resolveNoulCriteria(data, 'false', inputs, context);
476
+ if (hasClassifierCriteriaValue(trueCriteria) || hasClassifierCriteriaValue(falseCriteria)) {
477
+ if (!hasClassifierCriteriaValue(trueCriteria) || !hasClassifierCriteriaValue(falseCriteria)) {
478
+ throw new Error('Provide both true and false criteria, or neither.');
479
+ }
480
+ criteria = {
481
+ true: trueCriteria,
482
+ false: falseCriteria,
483
+ };
484
+ }
485
+ }
486
+ if (criteria) {
487
+ assertClassifierEntry(criteria.true, 'Criteria.true');
488
+ assertClassifierEntry(criteria.false, 'Criteria.false');
489
+ }
490
+ return { questionId, type: 'noul', instructions, ...(criteria ? { criteria } : {}) };
491
+ }
492
+ function getEntryTemplates(type, text, lines, objectTemplate) {
493
+ if (type === 'lines')
494
+ return [...(lines ?? [])];
495
+ if (type === 'object')
496
+ return [objectTemplate ?? '{}'];
497
+ return [text ?? ''];
498
+ }
499
+ function getScoreCriteria(data) {
500
+ if (data.scoreCriteria)
501
+ return data.scoreCriteria;
502
+ return (data.levels ?? defaultLevels()).map((text) => ({ ...createScoreCriterion(), text }));
503
+ }
504
+ function getChoiceCriteria(data) {
505
+ if (data.choiceCriteria)
506
+ return data.choiceCriteria;
507
+ return (data.options ?? defaultOptions()).map((option) => ({
508
+ ...createChoiceCriterion(),
509
+ key: option.key,
510
+ text: option.value,
511
+ lines: [option.value],
512
+ }));
513
+ }
514
+ function getCriteriaType(data) {
515
+ return data.criteriaType ?? 'text';
516
+ }
517
+ function getNoulTrueCriteria(data) {
518
+ return data.noulTrueCriteria ?? data.yesMeans ?? '';
519
+ }
520
+ function getNoulFalseCriteria(data) {
521
+ return data.noulFalseCriteria ?? data.noMeans ?? '';
522
+ }
523
+ function getNoulCriteriaTemplates(data, truthValue) {
524
+ const type = getCriteriaType(data);
525
+ return getEntryTemplates(type, truthValue === 'true' ? getNoulTrueCriteria(data) : getNoulFalseCriteria(data), truthValue === 'true' ? data.noulTrueCriteriaLines : data.noulFalseCriteriaLines, truthValue === 'true' ? data.noulTrueCriteriaObjectTemplate : data.noulFalseCriteriaObjectTemplate);
526
+ }
527
+ function hasAuthoredNoulCriteria(data, truthValue) {
528
+ const type = getCriteriaType(data);
529
+ if (type === 'lines') {
530
+ const lines = truthValue === 'true' ? data.noulTrueCriteriaLines : data.noulFalseCriteriaLines;
531
+ return lines?.some((line) => line.trim() !== '') ?? false;
532
+ }
533
+ if (type === 'object') {
534
+ const template = truthValue === 'true' ? data.noulTrueCriteriaObjectTemplate : data.noulFalseCriteriaObjectTemplate;
535
+ const normalizedTemplate = template?.trim();
536
+ return normalizedTemplate !== undefined && normalizedTemplate !== '' && normalizedTemplate !== '{}';
537
+ }
538
+ return (truthValue === 'true' ? getNoulTrueCriteria(data) : getNoulFalseCriteria(data)).trim() !== '';
539
+ }
540
+ function resolveNoulCriteria(data, truthValue, inputs, context) {
541
+ const useInput = truthValue === 'true' ? data.useNoulTrueCriteriaInput : data.useNoulFalseCriteriaInput;
542
+ const label = `${truthValue} criteria`;
543
+ if (useInput) {
544
+ return getCriteriaType(data) === 'text'
545
+ ? getStringInput(inputs, `criteria${truthValue === 'true' ? 'True' : 'False'}`, label)
546
+ : getStructuredInput(inputs, `criteria${truthValue === 'true' ? 'True' : 'False'}`, label);
547
+ }
548
+ return resolveAuthoredClassifierEntry({
549
+ type: getCriteriaType(data),
550
+ text: truthValue === 'true' ? getNoulTrueCriteria(data) : getNoulFalseCriteria(data),
551
+ lines: truthValue === 'true' ? data.noulTrueCriteriaLines : data.noulFalseCriteriaLines,
552
+ objectTemplate: truthValue === 'true' ? data.noulTrueCriteriaObjectTemplate : data.noulFalseCriteriaObjectTemplate,
553
+ inputs,
554
+ context,
555
+ label,
556
+ });
557
+ }
558
+ function hasClassifierCriteriaValue(value) {
559
+ if (typeof value === 'string')
560
+ return value.trim() !== '';
561
+ if (Array.isArray(value))
562
+ return value.some(hasClassifierCriteriaValue);
563
+ if (value === null || value === undefined)
564
+ return false;
565
+ if (typeof value !== 'object')
566
+ return true;
567
+ return Object.keys(value).length > 0;
568
+ }
569
+ export const classifierQuestionNode = nodeDefinition(ClassifierQuestionNodeImpl, 'Classifier Question');
@@ -5,14 +5,16 @@ import { nodeDefinition } from '../NodeDefinition.js';
5
5
  import { NodeImpl } from '../NodeImpl.js';
6
6
  import {} from '../NodeBodySpec.js';
7
7
  import { appendCodeNodeSourceUrl, buildCodeNodeSourceUrl, enrichCodeNodeErrorWithLocation, } from './codeNodeErrorDiagnostics.js';
8
- import { buildJsValueInterpolatedSource, buildJsValueInputsInitializer, buildJsValuePreview, getJsValueInterpolationCodeRunnerOptions, getJsValueInterpolationInputDefinitions, getJsValueInterpolationRuntimeContext, interpolateJsValuePreviewSource, sanitizeGeneratedJsValueError, } from './jsValueInterpolation.js';
8
+ import { buildJsValueInterpolatedSource, buildJsValueInputsInitializer, buildJsValuePreview, getJsValueInterpolationCodeRunnerOptions, getJsValueInterpolationInputDefinitions, getJsValueInterpolationRuntimeContext, getSafeJsValueInterpolationIdentifier, interpolateJsValuePreviewSource, sanitizeGeneratedJsValueError, } from './jsValueInterpolation.js';
9
9
  import { ALL_CODE_RUNNER_OPTIONS } from '../../integrations/CodeRunnerOptions.js';
10
10
  import { getInterpolationGlobalValues } from '../../utils/interpolation.js';
11
+ import { getCodeOutputFields } from './codeOutputInference.js';
12
+ export { analyzeCodeOutputs, getCodeOutputFields, getCodeOutputKeys, prepareCodeOutputEdit, } from './codeOutputInference.js';
11
13
  const CODE_RUNTIME_HELPER_MESSAGE = 'Node execution also provides "require" and "process". Browser execution provides "fetch", "console", and "Rivet".';
12
14
  const DEFAULT_CODE_NEW = dedent `
13
15
  // This is a Code node. Write JavaScript here and return one value.
14
16
  // Interpolation tokens create input ports and evaluate as connected values.
15
- // The returned value becomes the node's single output.
17
+ // Output carries the returned value; explicit object fields also get ports.
16
18
  const value = {{input}};
17
19
  return value;
18
20
  `;
@@ -43,21 +45,31 @@ function sanitizeCodeNewError(error, interpolationContext) {
43
45
  interpolationContext.interpolationHelperIdentifier,
44
46
  ]);
45
47
  }
46
- function buildCodeNewWrapper(code, interpolationContext) {
48
+ function buildCodeNewWrapper(code, interpolationContext, outputFields) {
49
+ const resultIdentifier = getSafeJsValueInterpolationIdentifier(code, '__codeNewResult');
50
+ const outputsIdentifier = getSafeJsValueInterpolationIdentifier(code, '__codeNewOutputs');
47
51
  const beforeUserCodeLines = [
48
52
  ...buildCodeNewInputsInitializer(interpolationContext).split(/\r?\n/),
49
53
  '',
50
- 'const __codeNewResult = await (async () => {',
54
+ `const ${resultIdentifier} = await (async () => {`,
51
55
  ];
52
56
  const afterUserCodeLines = [
53
57
  '})();',
54
58
  '',
55
- 'return {',
59
+ `const ${outputsIdentifier} = {`,
56
60
  ' output: {',
57
61
  " type: 'any',",
58
- ' value: __codeNewResult,',
62
+ ` value: ${resultIdentifier},`,
59
63
  ' },',
60
64
  '};',
65
+ `for (const { id, key } of ${JSON.stringify(outputFields)}) {`,
66
+ ` const descriptor = ${resultIdentifier} !== null && typeof ${resultIdentifier} === "object" && !Array.isArray(${resultIdentifier})`,
67
+ ` ? Object.getOwnPropertyDescriptor(${resultIdentifier}, key) : undefined;`,
68
+ ` ${outputsIdentifier}[id] = descriptor?.enumerable && Object.prototype.hasOwnProperty.call(descriptor, "value")`,
69
+ ' ? { type: "any", value: descriptor.value }',
70
+ ' : { type: "control-flow-excluded", value: undefined };',
71
+ '}',
72
+ `return ${outputsIdentifier};`,
61
73
  ];
62
74
  return {
63
75
  source: [...beforeUserCodeLines, buildCodeNewRuntimeSource(code, interpolationContext), ...afterUserCodeLines].join('\n'),
@@ -70,7 +82,7 @@ function isDataValueLike(value) {
70
82
  typeof value.type === 'string' &&
71
83
  Object.prototype.hasOwnProperty.call(value, 'value'));
72
84
  }
73
- function validateCodeNewRunnerOutputs(outputs) {
85
+ function validateCodeNewRunnerOutputs(outputs, outputFields) {
74
86
  if (outputs == null || typeof outputs !== 'object' || ('then' in outputs && typeof outputs.then === 'function')) {
75
87
  throw new Error('Code node runner must return an object containing the Output value.');
76
88
  }
@@ -81,6 +93,12 @@ function validateCodeNewRunnerOutputs(outputs) {
81
93
  if (output.type !== 'any') {
82
94
  throw new Error('Code node runner must return an any DataValue for the Output port.');
83
95
  }
96
+ for (const { id, key } of outputFields) {
97
+ const value = outputs[id];
98
+ if (!isDataValueLike(value) || (value.type !== 'any' && value.type !== 'control-flow-excluded')) {
99
+ throw new Error(`Code node runner must return a DataValue for field ${JSON.stringify(key)}.`);
100
+ }
101
+ }
84
102
  return outputs;
85
103
  }
86
104
  export class CodeNewNodeImpl extends NodeImpl {
@@ -109,6 +127,11 @@ export class CodeNewNodeImpl extends NodeImpl {
109
127
  title: 'Output',
110
128
  dataType: 'any',
111
129
  },
130
+ ...getCodeOutputFields(this.data).map(({ id, key }) => ({
131
+ id: id,
132
+ title: key,
133
+ dataType: 'any',
134
+ })),
112
135
  ];
113
136
  }
114
137
  getEditors() {
@@ -147,10 +170,11 @@ export class CodeNewNodeImpl extends NodeImpl {
147
170
  async process(inputs, context) {
148
171
  const sourceUrl = buildCodeNodeSourceUrl(this.chartNode.id);
149
172
  const interpolationContext = getJsValueInterpolationRuntimeContext(this.data.code, CODE_NEW_INPUTS_IDENTIFIER);
150
- const { source, userCodeLineOffset } = buildCodeNewWrapper(this.data.code, interpolationContext);
173
+ const outputFields = getCodeOutputFields(this.data);
174
+ const { source, userCodeLineOffset } = buildCodeNewWrapper(this.data.code, interpolationContext, outputFields);
151
175
  try {
152
176
  const outputs = await context.codeRunner.runCode(appendCodeNodeSourceUrl(source, sourceUrl), inputs, getJsValueInterpolationCodeRunnerOptions(ALL_CODE_RUNNER_OPTIONS, interpolationContext), context.graphInputNodeValues, context.contextValues, getInterpolationGlobalValues(this.data.code, context.getGlobal));
153
- return validateCodeNewRunnerOutputs(outputs);
177
+ return validateCodeNewRunnerOutputs(outputs, outputFields);
154
178
  }
155
179
  catch (error) {
156
180
  const enrichedError = await enrichCodeNodeErrorWithLocation({