@valerypopoff/rivet2-core 2.15.0 → 2.19.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 (187) hide show
  1. package/dist/cjs/bundle.cjs +7906 -3980
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/interpolationRuntime.cjs +62 -7
  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/cjs/serialization.cjs +1880 -0
  8. package/dist/cjs/serialization.cjs.map +7 -0
  9. package/dist/cjs/webAppRuntime.cjs +168 -6
  10. package/dist/cjs/webAppRuntime.cjs.map +3 -3
  11. package/dist/esm/api/createProcessor.js +5 -2
  12. package/dist/esm/api/processSettings.js +1 -0
  13. package/dist/esm/exports.js +4 -0
  14. package/dist/esm/model/AgentResponseTrace.js +99 -34
  15. package/dist/esm/model/AgentResponseTracePresentation.js +130 -0
  16. package/dist/esm/model/DataValue.js +11 -2
  17. package/dist/esm/model/GlobalVariables.js +2 -1
  18. package/dist/esm/model/GraphBoundaryCache.js +2 -1
  19. package/dist/esm/model/GraphBoundaryEffects.js +38 -1
  20. package/dist/esm/model/GraphExecutionState.js +81 -0
  21. package/dist/esm/model/GraphProcessor.js +825 -884
  22. package/dist/esm/model/GraphSchedulerBoundaryState.js +64 -0
  23. package/dist/esm/model/Nodes.js +15 -0
  24. package/dist/esm/model/ProjectBundle.js +248 -0
  25. package/dist/esm/model/ProjectBundleRuntime.js +54 -0
  26. package/dist/esm/model/SchedulerBoundaryPlanner.js +233 -0
  27. package/dist/esm/model/SplitRunProcessor.js +28 -7
  28. package/dist/esm/model/StreamingWatchTopology.js +118 -8
  29. package/dist/esm/model/SubgraphProjectTarget.js +7 -0
  30. package/dist/esm/model/SubprocessorBridge.js +125 -87
  31. package/dist/esm/model/ToolCallContinuationCoordinator.js +1 -1
  32. package/dist/esm/model/chat-v2/aiSdkBridge.js +22 -17
  33. package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -4
  34. package/dist/esm/model/chat-v2/chatV2CredentialNames.js +5 -1
  35. package/dist/esm/model/chat-v2/chatV2Outputs.js +2 -2
  36. package/dist/esm/model/chat-v2/chatV2Pipeline.js +24 -9
  37. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +3 -2
  38. package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +46 -6
  39. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +26 -1
  40. package/dist/esm/model/chat-v2/chatV2Shared.js +2 -1
  41. package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +10 -0
  42. package/dist/esm/model/chat-v2/llmChatV2Body.js +13 -10
  43. package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +5 -2
  44. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +3 -0
  45. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +33 -9
  46. package/dist/esm/model/chat-v2/llmChatV2NodeMigration.js +22 -2
  47. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +10 -2
  48. package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +17 -0
  49. package/dist/esm/model/chat-v2/llmModelCandidate.js +2 -1
  50. package/dist/esm/model/chat-v2/llmProfile.js +5 -1
  51. package/dist/esm/model/chat-v2/llmProfileBody.js +11 -2
  52. package/dist/esm/model/chat-v2/llmProfileFallback.js +7 -4
  53. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +2 -1
  54. package/dist/esm/model/chat-v2/llmProfileHealthStore.js +16 -3
  55. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +1 -1
  56. package/dist/esm/model/chat-v2/messageConverter.js +18 -16
  57. package/dist/esm/model/chat-v2/modelRegistry.js +14 -4
  58. package/dist/esm/model/chat-v2/openRouterModel.js +73 -0
  59. package/dist/esm/model/chat-v2/parallelToolCalls.js +2 -0
  60. package/dist/esm/model/chat-v2/providerOptions.js +30 -25
  61. package/dist/esm/model/chat-v2/temperature.js +9 -0
  62. package/dist/esm/model/classifier/credentials.js +42 -6
  63. package/dist/esm/model/classifier/images.js +176 -0
  64. package/dist/esm/model/classifier/json.js +57 -0
  65. package/dist/esm/model/classifier/limits.js +300 -0
  66. package/dist/esm/model/classifier/openai.js +118 -0
  67. package/dist/esm/model/classifier/perplexity.js +63 -0
  68. package/dist/esm/model/classifier/preparation.js +74 -0
  69. package/dist/esm/model/classifier/profile.js +151 -0
  70. package/dist/esm/model/classifier/profileExecution.js +294 -0
  71. package/dist/esm/model/classifier/providers.js +454 -192
  72. package/dist/esm/model/classifier/questionHelpers.js +29 -45
  73. package/dist/esm/model/classifier/questions.js +53 -0
  74. package/dist/esm/model/classifier/response.js +75 -0
  75. package/dist/esm/model/classifier/state.js +207 -0
  76. package/dist/esm/model/classifier/types.js +11 -1
  77. package/dist/esm/model/nodeRunFailure.js +54 -0
  78. package/dist/esm/model/nodes/CallGraphNode.js +6 -0
  79. package/dist/esm/model/nodes/CatchStreamingChunksNode.js +42 -0
  80. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +385 -154
  81. package/dist/esm/model/nodes/ClassifierProfileNode.js +133 -0
  82. package/dist/esm/model/nodes/ClassifierQuestionNode.js +59 -15
  83. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +1 -1
  84. package/dist/esm/model/nodes/GetGlobalNode.js +2 -2
  85. package/dist/esm/model/nodes/HttpCallNode.js +44 -75
  86. package/dist/esm/model/nodes/ImageNode.js +44 -3
  87. package/dist/esm/model/nodes/LLMChatV2Node.js +26 -4
  88. package/dist/esm/model/nodes/ObjectNode.js +29 -18
  89. package/dist/esm/model/nodes/PromptNode.js +2 -1
  90. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +4 -1
  91. package/dist/esm/model/nodes/SetGlobalNode.js +5 -3
  92. package/dist/esm/model/nodes/StopWatchingStreamingOutputNode.js +8 -8
  93. package/dist/esm/model/nodes/StreamValueNode.js +38 -0
  94. package/dist/esm/model/nodes/SubGraphNode.js +199 -35
  95. package/dist/esm/model/nodes/ToBase64Node.js +106 -0
  96. package/dist/esm/model/nodes/WatchStreamingOutputNode.js +7 -7
  97. package/dist/esm/model/nodes/toolCallDelegation.js +5 -1
  98. package/dist/esm/model/profileSuspensionHints.js +8 -0
  99. package/dist/esm/recording/ExecutionRecorder.js +26 -0
  100. package/dist/esm/serialization.js +2 -0
  101. package/dist/esm/utils/base64.js +18 -15
  102. package/dist/esm/utils/coerceType.js +11 -1
  103. package/dist/esm/utils/errors.js +41 -0
  104. package/dist/esm/utils/interpolation.js +44 -22
  105. package/dist/esm/utils/interpolationSyntax.js +15 -6
  106. package/dist/esm/utils/serialization/serialization.js +3 -2
  107. package/dist/esm/utils/serialization/serializationUtils.js +6 -0
  108. package/dist/esm/utils/serialization/serialization_v4.js +15 -3
  109. package/dist/esm/webAppRuntime.js +1 -0
  110. package/dist/types/api/createProcessor.d.ts +7 -1
  111. package/dist/types/exports.d.ts +4 -0
  112. package/dist/types/model/AgentResponseTrace.d.ts +15 -4
  113. package/dist/types/model/AgentResponseTracePresentation.d.ts +15 -0
  114. package/dist/types/model/CycleDetector.d.ts +1 -2
  115. package/dist/types/model/DataValue.d.ts +12 -8
  116. package/dist/types/model/ExecutorProtocol.d.ts +9 -0
  117. package/dist/types/model/GraphBoundaryCache.d.ts +2 -0
  118. package/dist/types/model/GraphBoundaryEffects.d.ts +10 -1
  119. package/dist/types/model/GraphExecutionState.d.ts +68 -0
  120. package/dist/types/model/GraphProcessor.d.ts +2 -0
  121. package/dist/types/model/GraphSchedulerBoundaryState.d.ts +96 -0
  122. package/dist/types/model/Nodes.d.ts +11 -4
  123. package/dist/types/model/ProcessContext.d.ts +24 -3
  124. package/dist/types/model/ProjectBundle.d.ts +59 -0
  125. package/dist/types/model/ProjectBundleRuntime.d.ts +24 -0
  126. package/dist/types/model/ProjectReferenceLoader.d.ts +3 -0
  127. package/dist/types/model/RivetUIContext.d.ts +1 -1
  128. package/dist/types/model/SchedulerBoundaryPlanner.d.ts +42 -0
  129. package/dist/types/model/Settings.d.ts +1 -0
  130. package/dist/types/model/StreamingWatchTopology.d.ts +11 -1
  131. package/dist/types/model/SubgraphProjectTarget.d.ts +38 -0
  132. package/dist/types/model/SubprocessorBridge.d.ts +2 -0
  133. package/dist/types/model/chat-v2/chatV2CredentialNames.d.ts +4 -0
  134. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +1 -1
  135. package/dist/types/model/chat-v2/chatV2ProviderRegistry.d.ts +79 -1
  136. package/dist/types/model/chat-v2/chatV2ProviderTypes.d.ts +1 -1
  137. package/dist/types/model/chat-v2/chatV2Shared.d.ts +1 -1
  138. package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +2 -0
  139. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +4 -1
  140. package/dist/types/model/chat-v2/llmChatV2NodeMigration.d.ts +3 -1
  141. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +2 -0
  142. package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +2 -0
  143. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +51 -3
  144. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +10 -7
  145. package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +6 -2
  146. package/dist/types/model/chat-v2/modelRegistry.d.ts +5 -4
  147. package/dist/types/model/chat-v2/openRouterModel.d.ts +2 -0
  148. package/dist/types/model/chat-v2/providerOptions.d.ts +2 -13
  149. package/dist/types/model/chat-v2/temperature.d.ts +2 -0
  150. package/dist/types/model/classifier/credentials.d.ts +7 -1
  151. package/dist/types/model/classifier/images.d.ts +18 -0
  152. package/dist/types/model/classifier/json.d.ts +19 -0
  153. package/dist/types/model/classifier/limits.d.ts +45 -0
  154. package/dist/types/model/classifier/openai.d.ts +5 -0
  155. package/dist/types/model/classifier/perplexity.d.ts +7 -0
  156. package/dist/types/model/classifier/preparation.d.ts +16 -0
  157. package/dist/types/model/classifier/profile.d.ts +46 -0
  158. package/dist/types/model/classifier/profileExecution.d.ts +32 -0
  159. package/dist/types/model/classifier/providers.d.ts +98 -9
  160. package/dist/types/model/classifier/questionHelpers.d.ts +6 -4
  161. package/dist/types/model/classifier/questions.d.ts +4 -0
  162. package/dist/types/model/classifier/response.d.ts +4 -0
  163. package/dist/types/model/classifier/state.d.ts +37 -0
  164. package/dist/types/model/classifier/types.d.ts +11 -0
  165. package/dist/types/model/nodeRunFailure.d.ts +13 -0
  166. package/dist/types/model/nodes/CatchStreamingChunksNode.d.ts +20 -0
  167. package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +17 -12
  168. package/dist/types/model/nodes/ClassifierProfileNode.d.ts +20 -0
  169. package/dist/types/model/nodes/GetGlobalNode.d.ts +7 -0
  170. package/dist/types/model/nodes/ImageNode.d.ts +4 -0
  171. package/dist/types/model/nodes/LLMChatV2Node.d.ts +1 -0
  172. package/dist/types/model/nodes/ObjectNode.d.ts +2 -1
  173. package/dist/types/model/nodes/StreamValueNode.d.ts +14 -0
  174. package/dist/types/model/nodes/SubGraphNode.d.ts +21 -2
  175. package/dist/types/model/nodes/ToBase64Node.d.ts +12 -0
  176. package/dist/types/model/nodes/toolCallDelegation.d.ts +3 -1
  177. package/dist/types/model/profileSuspensionHints.d.ts +8 -0
  178. package/dist/types/recording/ExecutionRecorder.d.ts +8 -2
  179. package/dist/types/serialization.d.ts +2 -0
  180. package/dist/types/utils/base64.d.ts +1 -1
  181. package/dist/types/utils/errors.d.ts +4 -0
  182. package/dist/types/utils/interpolation.d.ts +13 -2
  183. package/dist/types/utils/interpolationSyntax.d.ts +1 -1
  184. package/dist/types/utils/serialization/serialization.d.ts +3 -1
  185. package/dist/types/utils/serialization/serializationUtils.d.ts +1 -0
  186. package/dist/types/webAppRuntime.d.ts +1 -0
  187. package/package.json +7 -1
@@ -1,6 +1,9 @@
1
1
  import { createInterpolationInputDefinition } from '../interpolationInputDefinition.js';
2
- import { extractInterpolationVariableReferences, getInterpolationGlobalValues, interpolate } from '../../utils/interpolation.js';
2
+ import { extractInterpolationVariableReferences, getInterpolationGlobalValues, interpolate, } from '../../utils/interpolation.js';
3
3
  import { interpolateJsonTemplate } from '../nodes/ObjectNode.js';
4
+ import { assertClassifierEntry, classifierDataProperty } from './json.js';
5
+ import { checkClassifierJsonWork } from './limits.js';
6
+ export { assertClassifierEntry, assertClassifierInstructions } from './json.js';
4
7
  const STRUCTURED_ENTRY_TYPES = ['string', 'object', 'object[]', 'any', 'any[]'];
5
8
  export function getInstructionsInputDefinition() {
6
9
  return {
@@ -37,29 +40,35 @@ export function getInterpolationInputDefinitions(templates, reserved) {
37
40
  description: `Interpolated value named '${interpolationName}'.`,
38
41
  }));
39
42
  }
40
- function inputValues(inputs) {
41
- const values = Object.create(null);
42
- for (const [key, value] of Object.entries(inputs))
43
- values[key] = value;
44
- return values;
45
- }
46
- export function interpolateQuestionText(template, inputs, context) {
47
- return interpolate(template, inputValues(inputs), context.graphInputNodeValues, context.contextValues, {
48
- globalValues: getInterpolationGlobalValues(template, context.getGlobal),
43
+ export function interpolateQuestionText(template, inputs, context, preparation) {
44
+ preparation?.capture(template);
45
+ const result = interpolate(template, inputs, context.graphInputNodeValues, context.contextValues, {
46
+ globalValues: getInterpolationGlobalValues(template, context.getGlobal, preparation?.check, preparation?.tokenLimit),
47
+ guard: preparation,
49
48
  });
49
+ preparation?.capture(result);
50
+ return result;
50
51
  }
51
- export function resolveAuthoredClassifierEntry({ type, text, lines, objectTemplate, inputs, context, label, }) {
52
+ export function resolveAuthoredClassifierEntry({ type, text, lines, objectTemplate, inputs, context, label, preparation, }) {
52
53
  if (type === 'lines') {
53
- const resolved = (lines ?? []).map((line) => interpolateQuestionText(line, inputs, context));
54
+ preparation?.capture(lines ?? []);
55
+ const resolved = [];
56
+ for (let index = 0; index < (lines?.length ?? 0); index++) {
57
+ resolved.push(interpolateQuestionText(lines[index], inputs, context, preparation));
58
+ }
54
59
  if (resolved.length === 0)
55
60
  throw new Error(`${label} require at least one line.`);
56
61
  return resolved;
57
62
  }
58
63
  if (type === 'object') {
64
+ preparation?.capture(objectTemplate ?? '{}');
59
65
  const template = objectTemplate?.trim() ? objectTemplate : '{}';
60
66
  let parsed;
61
67
  try {
62
- parsed = JSON.parse(interpolateJsonTemplate(template, Object.fromEntries(Object.entries(inputs).map(([key, value]) => [key, value?.value])), context.graphInputNodeValues, context.contextValues, getInterpolationGlobalValues(template, context.getGlobal)));
68
+ const json = interpolateJsonTemplate(template, inputs, context.graphInputNodeValues, context.contextValues, getInterpolationGlobalValues(template, context.getGlobal, preparation?.check, preparation?.tokenLimit), preparation, true);
69
+ preparation?.capture(json);
70
+ checkClassifierJsonWork(json, preparation?.check ?? (() => { }), 'question template');
71
+ parsed = JSON.parse(json);
63
72
  }
64
73
  catch (error) {
65
74
  throw new Error(`${label} JSON template is invalid: ${error.message}`);
@@ -70,10 +79,14 @@ export function resolveAuthoredClassifierEntry({ type, text, lines, objectTempla
70
79
  assertClassifierEntry(parsed, label);
71
80
  return parsed;
72
81
  }
73
- return interpolateQuestionText(text ?? '', inputs, context);
82
+ return interpolateQuestionText(text ?? '', inputs, context, preparation);
83
+ }
84
+ export function getQuestionInputValue(inputs, portId, label) {
85
+ const input = classifierDataProperty(inputs, portId, label);
86
+ return input && typeof input === 'object' ? classifierDataProperty(input, 'value', label) : undefined;
74
87
  }
75
88
  export function getStringInput(inputs, portId, label) {
76
- const value = inputs[portId]?.value;
89
+ const value = getQuestionInputValue(inputs, portId, label);
77
90
  if (typeof value !== 'string')
78
91
  throw new Error(`${label} input must be a string.`);
79
92
  return value;
@@ -84,41 +97,12 @@ export function requireQuestionId(questionId) {
84
97
  return questionId;
85
98
  }
86
99
  export function getStructuredInput(inputs, portId, label) {
87
- const value = inputs[portId]?.value;
100
+ const value = getQuestionInputValue(inputs, portId, label);
88
101
  if (value === undefined)
89
102
  throw new Error(`${label} input is required.`);
90
103
  assertClassifierEntry(value, label);
91
104
  return value;
92
105
  }
93
- export function assertClassifierEntry(value, label) {
94
- assertClassifierEntryValue(value, label, new Set(), false);
95
- }
96
- export function assertClassifierInstructions(value, label = 'Instructions') {
97
- assertClassifierEntry(value, label);
98
- if (value === null || (typeof value === 'string' && value.trim() === '')) {
99
- throw new Error(`${label} are required.`);
100
- }
101
- }
102
- function assertClassifierEntryValue(value, label, seen, nested) {
103
- if (value === null || typeof value === 'string')
104
- return;
105
- if (nested && (typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value))))
106
- return;
107
- if (typeof value !== 'object')
108
- throw new Error(`${label} must contain only strings, null, objects, and arrays.`);
109
- if (seen.has(value))
110
- throw new Error(`${label} must not contain circular references.`);
111
- seen.add(value);
112
- if (Array.isArray(value)) {
113
- value.forEach((item, index) => assertClassifierEntryValue(item, `${label}[${index}]`, seen, true));
114
- }
115
- else {
116
- for (const [key, item] of Object.entries(value)) {
117
- assertClassifierEntryValue(item, `${label}.${key}`, seen, true);
118
- }
119
- }
120
- seen.delete(value);
121
- }
122
106
  export function abbreviate(value, maximum = 72) {
123
107
  const compact = value.replace(/\s+/g, ' ').trim();
124
108
  return compact.length <= maximum ? compact : `${compact.slice(0, maximum - 3)}...`;
@@ -0,0 +1,53 @@
1
+ import { assertClassifierEntryKind, assertClassifierInstructionsKind, snapshotClassifierJson, classifierArrayValues, } from './json.js';
2
+ /** Shared by node execution and direct provider calls, before taking the request snapshot. */
3
+ export function prepareClassifierQuestion(value, budget) {
4
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
5
+ throw new Error('Question inputs must contain question definition objects.');
6
+ if ('images' in value)
7
+ throw new Error("Question-level images are not supported. Connect images to Classifier Evaluate's State input.");
8
+ for (const key of ['questionId', 'type', 'instructions']) {
9
+ if (!Object.prototype.propertyIsEnumerable.call(value, key))
10
+ throw new Error(`Every classifier question must have an own, enumerable '${key}' field.`);
11
+ }
12
+ const criteriaProperty = Object.getOwnPropertyDescriptor(value, 'criteria');
13
+ if (criteriaProperty && (!criteriaProperty.enumerable || !('value' in criteriaProperty)))
14
+ throw new Error('Classifier question criteria must be an own, enumerable field.');
15
+ // Optional envelope properties may be undefined; structured entries themselves must be exact JSON.
16
+ const question = snapshotClassifierJson(value, 'Question', budget, true);
17
+ 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))
20
+ throw new Error(`Question '${question.questionId}' has an unsupported type.`);
21
+ // The whole question has already passed recursive JSON/resource validation.
22
+ // Check only entry kinds here; do not scan each structured entry again.
23
+ assertClassifierInstructionsKind(question.instructions, `Question '${question.questionId}' instructions`);
24
+ const criteria = question.criteria;
25
+ if (question.type === 'choice') {
26
+ if (typeof criteria !== 'object' || criteria === null || Array.isArray(criteria))
27
+ throw new Error(`Choice question '${question.questionId}' requires object criteria.`);
28
+ const keys = Object.keys(criteria);
29
+ if (keys.length < 2 || keys.length > 255)
30
+ throw new Error(`Choice question '${question.questionId}' requires 2 to 255 options.`);
31
+ for (const key of keys)
32
+ assertClassifierEntryKind(criteria[key], `Question '${question.questionId}' criteria.${key}`);
33
+ }
34
+ else if (question.type === 'score') {
35
+ if (!Array.isArray(criteria) || criteria.length < 2 || criteria.length > 10)
36
+ throw new Error(`Score question '${question.questionId}' requires 2 to 10 levels.`);
37
+ let index = 0;
38
+ for (const entry of classifierArrayValues(criteria, 'Criteria'))
39
+ assertClassifierEntryKind(entry, `Question '${question.questionId}' criteria[${index++}]`);
40
+ }
41
+ else if (criteria !== undefined) {
42
+ if (typeof criteria !== 'object' ||
43
+ criteria === null ||
44
+ Array.isArray(criteria) ||
45
+ !Object.prototype.propertyIsEnumerable.call(criteria, 'true') ||
46
+ !Object.prototype.propertyIsEnumerable.call(criteria, 'false'))
47
+ throw new Error(`Noul question '${question.questionId}' criteria must contain true and false entries.`);
48
+ const entries = criteria;
49
+ assertClassifierEntryKind(entries.true, `Question '${question.questionId}' criteria.true`);
50
+ assertClassifierEntryKind(entries.false, `Question '${question.questionId}' criteria.false`);
51
+ }
52
+ return question;
53
+ }
@@ -0,0 +1,75 @@
1
+ function isRecord(value) {
2
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
3
+ }
4
+ /** Inherited values are not fields of the provider's JSON response. */
5
+ function responseField(record, key) {
6
+ return Object.prototype.hasOwnProperty.call(record, key) ? record[key] : undefined;
7
+ }
8
+ function requireResponseNumber(value, label, providerLabel) {
9
+ // Check JSON-compatible representation only, never the provider's numeric
10
+ // range, normalization, precision or derived relationships.
11
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
12
+ throw new Error(`${providerLabel} response has invalid ${label}.`);
13
+ }
14
+ }
15
+ function requireResponseMap(value, expectedKeys, label, providerLabel) {
16
+ if (!isRecord(value))
17
+ throw new Error(`${providerLabel} response has invalid ${label}.`);
18
+ const actualKeys = Object.keys(value);
19
+ if (actualKeys.length !== expectedKeys.length ||
20
+ expectedKeys.some((key) => !Object.prototype.hasOwnProperty.call(value, key))) {
21
+ throw new Error(`${providerLabel} response has inconsistent ${label} keys.`);
22
+ }
23
+ return value;
24
+ }
25
+ function requireProbabilityMap(value, keys, label, providerLabel) {
26
+ const probabilities = requireResponseMap(value, keys, label, providerLabel);
27
+ for (const key of keys)
28
+ requireResponseNumber(probabilities[key], `${label}.${key}`, providerLabel);
29
+ }
30
+ export function validateApiCompatibleClassifierResponse(body, questions, providerLabel = 'Classifier provider') {
31
+ return validateClassifierEvaluationResponse(body, questions, providerLabel);
32
+ }
33
+ /** Validate the common Rivet result, independently of the provider's wire protocol. */
34
+ export function validateClassifierEvaluationResponse(body, questions, providerLabel = 'Classifier provider') {
35
+ const model = isRecord(body) ? responseField(body, 'model') : undefined;
36
+ const answers = isRecord(body) ? responseField(body, 'answers') : undefined;
37
+ const usage = isRecord(body) ? responseField(body, 'usage') : undefined;
38
+ if (!isRecord(body) || typeof model !== 'string' || model.trim() === '' || !isRecord(answers) || !isRecord(usage)) {
39
+ throw new Error(`${providerLabel} returned an invalid response shape.`);
40
+ }
41
+ const expectedIds = questions.map((question) => question.questionId);
42
+ const answerIds = Object.keys(answers);
43
+ if (answerIds.length !== expectedIds.length ||
44
+ expectedIds.some((id) => !Object.prototype.hasOwnProperty.call(answers, id))) {
45
+ throw new Error(`${providerLabel} response does not match the submitted question IDs.`);
46
+ }
47
+ for (const question of questions) {
48
+ const answer = answers[question.questionId];
49
+ if (!isRecord(answer) || responseField(answer, 'type') !== question.type) {
50
+ throw new Error(`${providerLabel} response type does not match question '${question.questionId}'.`);
51
+ }
52
+ if (question.type === 'choice') {
53
+ const keys = Object.keys(question.criteria);
54
+ const choice = responseField(answer, 'choice');
55
+ if (typeof choice !== 'string' || !Object.prototype.hasOwnProperty.call(question.criteria, choice)) {
56
+ throw new Error(`${providerLabel} response chose an unknown option for '${question.questionId}'.`);
57
+ }
58
+ requireResponseNumber(responseField(answer, 'confidence'), `${question.questionId}.confidence`, providerLabel);
59
+ requireProbabilityMap(responseField(answer, 'probabilities'), keys, `${question.questionId}.probabilities`, providerLabel);
60
+ }
61
+ else if (question.type === 'score') {
62
+ requireResponseNumber(responseField(answer, 'score'), `${question.questionId}.score`, providerLabel);
63
+ requireResponseNumber(responseField(answer, 'confidence'), `${question.questionId}.confidence`, providerLabel);
64
+ const keys = question.criteria.map((_, index) => String(index));
65
+ requireProbabilityMap(responseField(answer, 'probabilities'), keys, `${question.questionId}.probabilities`, providerLabel);
66
+ requireResponseMap(responseField(answer, 'legend'), keys, `${question.questionId}.legend`, providerLabel);
67
+ }
68
+ else {
69
+ requireResponseNumber(responseField(answer, 'noul'), `${question.questionId}.noul`, providerLabel);
70
+ }
71
+ }
72
+ requireResponseNumber(responseField(usage, 'input_tokens'), 'usage.input_tokens', providerLabel);
73
+ requireResponseNumber(responseField(usage, 'output_tokens'), 'usage.output_tokens', providerLabel);
74
+ return body;
75
+ }
@@ -0,0 +1,207 @@
1
+ import { prepareClassifierImageText, prepareNativeClassifierImage, inspectClassifierImage, } from './images.js';
2
+ import { snapshotClassifierJson, classifierArrayValues, classifierDataProperty } from './json.js';
3
+ import { ClassifierValueBudget, CLASSIFIER_LIMITS } from './limits.js';
4
+ const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
5
+ const nativeImage = (value) => record(value) &&
6
+ (classifierDataProperty(value, 'type') === 'image' ||
7
+ ('mediaType' in value && classifierDataProperty(value, 'data') instanceof Uint8Array));
8
+ const message = (value) => record(value) && 'type' in value && 'message' in value;
9
+ /** Graph and direct provider calls converge here; no caller can bypass preparation. */
10
+ export function prepareClassifierState(input, budget) {
11
+ if (input.stateInput !== undefined) {
12
+ if (input.state !== '' || input.stateMessages !== undefined)
13
+ throw new Error('Rivet State input and provider State cannot be supplied together.');
14
+ return prepareRivetState(input.stateInput, budget);
15
+ }
16
+ if (input.stateMessages === undefined) {
17
+ if (typeof input.state !== 'string' && !record(input.state) && !Array.isArray(input.state))
18
+ throw new Error('State must be text, a JSON object or an array.');
19
+ return { kind: 'json', value: snapshotClassifierJson(input.state, 'State', budget) };
20
+ }
21
+ if (input.state !== '')
22
+ throw new Error('Structured State and multimodal State messages cannot be supplied together.');
23
+ const messages = snapshotClassifierJson(input.stateMessages, 'State', budget);
24
+ const images = inspectStateMessages(messages, budget.check);
25
+ return { kind: 'messages', messages: messages, images };
26
+ }
27
+ /** Standalone compatibility helper uses the same preparation, not a separate validator. */
28
+ export function normalizeClassifierState(input, check, maxBytes) {
29
+ const state = input === undefined
30
+ ? { kind: 'json', value: '' }
31
+ : prepareRivetState(input, new ClassifierValueBudget(check, maxBytes));
32
+ return state.kind === 'json' ? { state: state.value } : { state: '', stateMessages: state.messages };
33
+ }
34
+ function prepareRivetState(input, budget) {
35
+ const check = budget.check;
36
+ if (input === null || typeof input !== 'object' || Array.isArray(input))
37
+ throw new Error('State input must contain a Rivet data value.');
38
+ const type = classifierDataProperty(input, 'type');
39
+ const value = classifierDataProperty(input, 'value');
40
+ if (typeof type !== 'string')
41
+ throw new Error('State input type must be a string.');
42
+ if (![
43
+ 'string',
44
+ 'string[]',
45
+ 'image',
46
+ 'image[]',
47
+ 'chat-message',
48
+ 'chat-message[]',
49
+ 'object',
50
+ 'object[]',
51
+ 'any',
52
+ 'any[]',
53
+ ].includes(type))
54
+ throw new Error(`Unsupported State input type '${type}'.`);
55
+ if (type.endsWith('[]') && !Array.isArray(value))
56
+ throw new Error('State array input must contain an array.');
57
+ if (type === 'string' && typeof value !== 'string')
58
+ throw new Error('State string input must contain a string.');
59
+ if (type === 'object' && !record(value) && !Array.isArray(value))
60
+ throw new Error('State object input must contain a JSON object or array.');
61
+ if ((type === 'image' || type === 'chat-message') && Array.isArray(value))
62
+ throw new Error('State scalar input must not contain an array.');
63
+ // Explicit structured evidence needs just one validating/copying traversal.
64
+ if (type === 'object' || type === 'object[]')
65
+ return { kind: 'json', value: snapshotClassifierJson(value, 'State', budget) };
66
+ // Ambiguous/multimodal inputs must be bounded before image inspection/encoding.
67
+ budget.inspect(value);
68
+ const imageTexts = new Map();
69
+ const textImage = (text) => {
70
+ const image = imageTexts.get(text) ?? prepareClassifierImageText(text, check);
71
+ if (image)
72
+ imageTexts.set(text, image);
73
+ return image;
74
+ };
75
+ const hasContent = (item) => nativeImage(item) || message(item) || (typeof item === 'string' && textImage(item) !== undefined);
76
+ const arrayHasContent = () => {
77
+ for (const item of classifierArrayValues(value, 'State')) {
78
+ check();
79
+ if (hasContent(item))
80
+ return true;
81
+ }
82
+ return false;
83
+ };
84
+ const contentType = ['image', 'image[]', 'string[]', 'chat-message', 'chat-message[]'].includes(type);
85
+ const inferredContent = (type === 'any' || type === 'any[]') && (hasContent(value) || (Array.isArray(value) && arrayHasContent()));
86
+ if (!(contentType || inferredContent || (type === 'string' && textImage(value)))) {
87
+ if (typeof value !== 'string' && !record(value) && !Array.isArray(value))
88
+ throw new Error('State must be text, a JSON object/array, images, or user messages.');
89
+ // Text is already detached. Ambiguous JSON additionally needs plain-data validation.
90
+ return {
91
+ kind: 'json',
92
+ value: typeof value === 'string'
93
+ ? value
94
+ : snapshotClassifierJson(value, 'State', new ClassifierValueBudget(check)),
95
+ };
96
+ }
97
+ const values = Array.isArray(value) ? value : [value];
98
+ if (type === 'image[]' && values.length > 128)
99
+ throw new Error('State must contain at most 128 images.');
100
+ const messages = [];
101
+ const images = [];
102
+ let partCount = 0;
103
+ const imagePart = (prepare) => {
104
+ if (images.length >= 128)
105
+ throw new Error('State must contain at most 128 images.');
106
+ const image = prepare();
107
+ images.push(image);
108
+ return { type: 'image', dataUrl: image.dataUrl };
109
+ };
110
+ let parts = [];
111
+ const flush = () => {
112
+ if (parts.length) {
113
+ if (messages.length >= CLASSIFIER_LIMITS.messages)
114
+ throw new Error('State has too many messages.');
115
+ messages.push({ parts });
116
+ parts = [];
117
+ }
118
+ };
119
+ const part = (item) => {
120
+ check();
121
+ if (++partCount > CLASSIFIER_LIMITS.parts)
122
+ throw new Error('State has too many content parts.');
123
+ if (typeof item === 'string') {
124
+ const image = textImage(item);
125
+ return image ? imagePart(() => image) : { type: 'text', text: item };
126
+ }
127
+ if (nativeImage(item))
128
+ return imagePart(() => prepareNativeClassifierImage(item, check));
129
+ throw new Error('Multimodal State accepts only text, native images, image data URLs, and user messages.');
130
+ };
131
+ for (const item of classifierArrayValues(values, 'State')) {
132
+ check();
133
+ if (type === 'image' || type === 'image[]') {
134
+ if (++partCount > CLASSIFIER_LIMITS.parts)
135
+ throw new Error('State has too many content parts.');
136
+ parts.push(imagePart(() => prepareNativeClassifierImage(item, check)));
137
+ }
138
+ else if (type === 'string[]' && typeof item !== 'string') {
139
+ throw new Error('State string array must contain only strings.');
140
+ }
141
+ else if (message(item)) {
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.');
144
+ flush();
145
+ if (messages.length >= CLASSIFIER_LIMITS.messages)
146
+ throw new Error('State has too many messages.');
147
+ const contentValue = classifierDataProperty(item, 'message');
148
+ const content = Array.isArray(contentValue) ? contentValue : [contentValue];
149
+ messages.push({
150
+ parts: content.length
151
+ ? Array.from(classifierArrayValues(content, 'State'), part)
152
+ : [{ type: 'text', text: '' }],
153
+ });
154
+ }
155
+ else {
156
+ if (type === 'chat-message' || type === 'chat-message[]')
157
+ throw new Error('State must contain valid user messages.');
158
+ parts.push(part(item));
159
+ }
160
+ }
161
+ flush();
162
+ return messages.length ? { kind: 'messages', messages, images } : { kind: 'json', value: '' };
163
+ }
164
+ function inspectStateMessages(messages, check) {
165
+ if (!Array.isArray(messages))
166
+ throw new Error('State messages must be an array.');
167
+ if (messages.length > CLASSIFIER_LIMITS.messages)
168
+ throw new Error('State has too many messages.');
169
+ const images = [];
170
+ let parts = 0;
171
+ for (const message of messages) {
172
+ if (!record(message) || !Array.isArray(message.parts))
173
+ throw new Error('State message parts must be an array.');
174
+ for (const part of message.parts) {
175
+ check();
176
+ if (++parts > CLASSIFIER_LIMITS.parts)
177
+ throw new Error('State has too many content parts.');
178
+ if (!record(part))
179
+ throw new Error('Invalid State content part.');
180
+ if (part.type === 'image' && typeof part.dataUrl === 'string') {
181
+ if (images.length >= 128)
182
+ throw new Error('State must contain at most 128 images.');
183
+ images.push({ ...inspectClassifierImage(part.dataUrl, check), dataUrl: part.dataUrl });
184
+ }
185
+ else if (part.type !== 'text' || typeof part.text !== 'string')
186
+ throw new Error('Invalid State content part.');
187
+ }
188
+ }
189
+ return images;
190
+ }
191
+ /** System One separates images; numbered placeholders retain caption/image associations. */
192
+ export function systemOneState(input) {
193
+ if (!input.stateMessages)
194
+ return { state: input.state };
195
+ const images = [];
196
+ const state = input.stateMessages
197
+ .map(({ parts }) => parts
198
+ .map((part) => {
199
+ if (part.type === 'text')
200
+ return part.text;
201
+ images.push(part.dataUrl);
202
+ return `[Image ${images.length}]`;
203
+ })
204
+ .join('\n'))
205
+ .join('\n\n');
206
+ return { state, ...(images.length ? { images } : {}) };
207
+ }
@@ -1 +1,11 @@
1
- export {};
1
+ /** Secret-free classification used by fallback diagnostics and recording traces. */
2
+ export const classifierFailureKinds = [
3
+ 'configuration',
4
+ 'capability',
5
+ 'authentication',
6
+ 'transport',
7
+ 'http',
8
+ 'timeout',
9
+ 'response-parsing',
10
+ 'response-validation',
11
+ ];
@@ -0,0 +1,54 @@
1
+ import { getChatV2ProviderErrorStatusCode } from './chat-v2/chatV2Errors.js';
2
+ import { formatCaughtRunError } from '../utils/errors.js';
3
+ export function hasRunFailureOutputs(data) {
4
+ return data.catchRequestFailed === true || data.errorOnNon200 === false;
5
+ }
6
+ export function getRunFailureOutputDefinitions(data) {
7
+ return hasRunFailureOutputs(data)
8
+ ? [
9
+ { id: 'runFailed', title: 'Run failed', dataType: 'boolean' },
10
+ { id: 'runError', title: 'Run error', dataType: 'string' },
11
+ ]
12
+ : [];
13
+ }
14
+ export function shouldCatchRunFailure(data, error, signal) {
15
+ // Only the caller's signal proves graph cancellation. A provider or tool can
16
+ // throw AbortError for its own interrupted request while the graph stays live.
17
+ if (signal.aborted)
18
+ return false;
19
+ if (data.catchRequestFailed === true)
20
+ return true;
21
+ const status = getChatV2ProviderErrorStatusCode(error);
22
+ return data.errorOnNon200 === false && status != null && (status < 200 || status >= 300);
23
+ }
24
+ export function withRunSuccessOutputs(data, outputs) {
25
+ if (!hasRunFailureOutputs(data))
26
+ return outputs;
27
+ return {
28
+ ...outputs,
29
+ ['runFailed']: { type: 'boolean', value: false },
30
+ ['runError']: { type: 'control-flow-excluded', value: undefined },
31
+ };
32
+ }
33
+ /** Never route a partial model answer or fabricated usage through the success branch. */
34
+ export function createCaughtRunFailureOutputs(definitions, error, evidence) {
35
+ const outputs = {};
36
+ for (const definition of definitions) {
37
+ outputs[definition.id] = { type: 'control-flow-excluded', value: undefined };
38
+ }
39
+ for (const id of [
40
+ 'requestBody',
41
+ 'responseBody',
42
+ 'llmAttempts',
43
+ 'llmProfileSummary',
44
+ 'classifierAttempts',
45
+ 'classifierProfileSummary',
46
+ ]) {
47
+ const port = id;
48
+ if (port in outputs && evidence?.[port] != null)
49
+ outputs[port] = evidence[port];
50
+ }
51
+ outputs['runFailed'] = { type: 'boolean', value: true };
52
+ outputs['runError'] = { type: 'string', value: formatCaughtRunError(error) };
53
+ return outputs;
54
+ }
@@ -102,6 +102,12 @@ export class CallGraphNodeImpl extends NodeImpl {
102
102
  type: 'object',
103
103
  value: graphOutputs,
104
104
  };
105
+ // Carry implicit graph metrics outside the wrapped user outputs so the
106
+ // containing processor accounts this invocation just like a Subgraph.
107
+ for (const metric of ['cost', 'costBreakdown']) {
108
+ if (graphOutputs[metric])
109
+ outputs[metric] = graphOutputs[metric];
110
+ }
105
111
  if (this.data.useErrorOutput) {
106
112
  outputs['error'] = {
107
113
  type: 'control-flow-excluded',
@@ -0,0 +1,42 @@
1
+ import { nanoid } from 'nanoid/non-secure';
2
+ import { nodeDefinition } from '../NodeDefinition.js';
3
+ import { NodeImpl } from '../NodeImpl.js';
4
+ export const MAX_CAUGHT_STREAMING_CHUNKS = 1024;
5
+ /** The processor owns this node's early, once-only output. */
6
+ export class CatchStreamingChunksNodeImpl extends NodeImpl {
7
+ static create() {
8
+ return {
9
+ id: nanoid(),
10
+ type: 'catchStreamingChunks',
11
+ title: 'Catch streaming chunks',
12
+ data: { count: 1 },
13
+ visualData: { x: 0, y: 0, width: 220 },
14
+ };
15
+ }
16
+ getInputDefinitions() {
17
+ return [{ id: 'stream', title: 'Streaming Output', dataType: 'any', required: true }];
18
+ }
19
+ getOutputDefinitions() {
20
+ return [{ id: 'value', title: 'Value', dataType: 'any' }];
21
+ }
22
+ static getUIData() {
23
+ return {
24
+ contextMenuTitle: 'Catch streaming chunks',
25
+ group: ['Streaming'],
26
+ infoBoxTitle: 'Catch streaming chunks node',
27
+ infoBoxBody: 'Returns the first N streaming snapshots as one ordinary value. For N=1 it returns the value itself; for N>1 it returns an array. It completes once and never runs a repeated Watch branch.',
28
+ };
29
+ }
30
+ getEditors() {
31
+ return [{ type: 'number', dataKey: 'count', label: 'Number of chunks', min: 1, max: MAX_CAUGHT_STREAMING_CHUNKS }];
32
+ }
33
+ getBody() {
34
+ return `First ${this.data.count ?? 1} ${this.data.count === 1 ? 'chunk' : 'chunks'}`;
35
+ }
36
+ async process(inputs) {
37
+ // GraphProcessor schedules connected instances at their stream boundary.
38
+ // Retain the ordinary final-only behavior for direct node tests.
39
+ return { ['value']: inputs['stream'] };
40
+ }
41
+ }
42
+ export const catchStreamingChunksNode = nodeDefinition(CatchStreamingChunksNodeImpl, 'Catch streaming chunks');