@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
@@ -0,0 +1,176 @@
1
+ import { base64ToUint8Array, uint8ArrayToBase64Sync } from '../../utils/base64.js';
2
+ import { classifierDataProperty } from './json.js';
3
+ import { assertClassifierResourceLimits, classifierByteView, CLASSIFIER_LIMITS, } from './limits.js';
4
+ class InvalidClassifierImageError extends Error {
5
+ }
6
+ const invalidImage = () => new InvalidClassifierImageError('State images must contain inline base64 PNG, JPEG, GIF or WebP image data with valid headers and matching media type.');
7
+ function isBase64(value) {
8
+ // Avoid repeated regexp groups: they overflow the regexp stack on large images.
9
+ return value.length > 0 && value.length % 4 === 0 && /^[A-Za-z0-9+/]+={0,2}$/.test(value);
10
+ }
11
+ function jpegInfo(size, read, check) {
12
+ const byte = (offset) => read(offset, 1)[0];
13
+ const uint16 = (offset) => {
14
+ const bytes = read(offset, 2);
15
+ return (bytes[0] << 8) + bytes[1];
16
+ };
17
+ let offset = 2;
18
+ while (offset + 4 <= size) {
19
+ check?.();
20
+ if (byte(offset++) !== 0xff)
21
+ break;
22
+ while (byte(offset) === 0xff) {
23
+ if ((offset & 4095) === 0)
24
+ check?.();
25
+ offset++;
26
+ }
27
+ const marker = byte(offset++);
28
+ if (marker === undefined || marker === 0xda || marker === 0xd9)
29
+ break;
30
+ if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7))
31
+ continue;
32
+ if (offset + 2 > size)
33
+ break;
34
+ const length = uint16(offset);
35
+ if (length < 2 || offset + length > size)
36
+ break;
37
+ if ([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf].includes(marker) && length >= 8)
38
+ return { mediaType: 'image/jpeg', width: uint16(offset + 5), height: uint16(offset + 3) };
39
+ offset += length;
40
+ }
41
+ return undefined;
42
+ }
43
+ /** Read image headers without a browser, filesystem access, or a decoder dependency. */
44
+ function imageInfo(bytes, check) {
45
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
46
+ const ascii = (offset, length) => String.fromCharCode(...bytes.subarray(offset, offset + length));
47
+ let info;
48
+ if (bytes.length >= 33 &&
49
+ ascii(0, 8) === '\x89PNG\r\n\x1a\n' &&
50
+ view.getUint32(8) === 13 &&
51
+ ascii(12, 4) === 'IHDR') {
52
+ info = { mediaType: 'image/png', width: view.getUint32(16), height: view.getUint32(20) };
53
+ }
54
+ else if (bytes.length >= 13 && ['GIF87a', 'GIF89a'].includes(ascii(0, 6))) {
55
+ info = { mediaType: 'image/gif', width: view.getUint16(6, true), height: view.getUint16(8, true) };
56
+ }
57
+ else if (bytes.length >= 25 && ascii(0, 4) === 'RIFF' && ascii(8, 4) === 'WEBP') {
58
+ const chunk = ascii(12, 4);
59
+ const uint24 = (offset) => bytes[offset] + (bytes[offset + 1] << 8) + (bytes[offset + 2] << 16);
60
+ if (chunk === 'VP8X' && bytes.length >= 30)
61
+ info = { mediaType: 'image/webp', width: uint24(24) + 1, height: uint24(27) + 1 };
62
+ else if (chunk === 'VP8 ' && bytes.length >= 30 && ascii(23, 3) === '\x9d\x01\x2a')
63
+ info = {
64
+ mediaType: 'image/webp',
65
+ width: view.getUint16(26, true) & 0x3fff,
66
+ height: view.getUint16(28, true) & 0x3fff,
67
+ };
68
+ else if (chunk === 'VP8L' && bytes[20] === 0x2f) {
69
+ const bits = view.getUint32(21, true);
70
+ info = { mediaType: 'image/webp', width: (bits & 0x3fff) + 1, height: ((bits >>> 14) & 0x3fff) + 1 };
71
+ }
72
+ }
73
+ else if (bytes.length >= 4 && bytes[0] === 0xff && bytes[1] === 0xd8) {
74
+ info = jpegInfo(bytes.length, (offset, length) => bytes.subarray(offset, offset + length), check);
75
+ }
76
+ if (!info || info.width === 0 || info.height === 0)
77
+ throw invalidImage();
78
+ return info;
79
+ }
80
+ function base64ImageInfo(payload, check) {
81
+ // JPEG metadata may precede its dimensions. Skip segment bodies and decode
82
+ // only the byte windows needed by the same parser used for native images.
83
+ if (payload.startsWith('/9j/')) {
84
+ const size = (payload.length / 4) * 3 - (payload.endsWith('==') ? 2 : payload.endsWith('=') ? 1 : 0);
85
+ let start = -1;
86
+ let window = new Uint8Array();
87
+ const info = jpegInfo(size, (offset, length) => {
88
+ if (offset < start || offset + length > start + window.length) {
89
+ start = Math.floor(offset / 3) * 3;
90
+ // A small cache also bounds decoder calls for runs of JPEG fill bytes.
91
+ window = base64ToUint8Array(payload.slice((start / 3) * 4, (start / 3) * 4 + 4096));
92
+ }
93
+ return window.subarray(offset - start, offset - start + length);
94
+ }, check);
95
+ if (!info || info.width === 0 || info.height === 0)
96
+ throw invalidImage();
97
+ return info;
98
+ }
99
+ // PNG/GIF/WebP dimensions are in the first 36 bytes.
100
+ return imageInfo(base64ToUint8Array(payload.slice(0, 48)));
101
+ }
102
+ export function prepareNativeClassifierImage(value, check) {
103
+ if (!value || typeof value !== 'object')
104
+ throw invalidImage();
105
+ const data = classifierDataProperty(value, 'data');
106
+ const mediaType = classifierDataProperty(value, 'mediaType');
107
+ if (!(data instanceof Uint8Array))
108
+ throw invalidImage();
109
+ const bytes = classifierByteView(data);
110
+ assertClassifierResourceLimits(bytes, check);
111
+ const info = imageInfo(bytes, check);
112
+ if (info.mediaType !== mediaType)
113
+ throw invalidImage();
114
+ check?.();
115
+ return { ...info, dataUrl: `data:${info.mediaType};base64,${uint8ArrayToBase64Sync(bytes)}` };
116
+ }
117
+ export function nativeClassifierImage(value, check) {
118
+ return prepareNativeClassifierImage(value, check).dataUrl;
119
+ }
120
+ export function inspectClassifierImage(value, check) {
121
+ check?.();
122
+ if (typeof value !== 'string')
123
+ throw invalidImage();
124
+ const prefix = /^data:(image\/(?:png|jpeg|gif|webp));base64,/.exec(value);
125
+ if (!prefix)
126
+ throw invalidImage();
127
+ const payload = value.slice(prefix[0].length);
128
+ if (!isBase64(payload))
129
+ throw invalidImage();
130
+ const info = base64ImageInfo(payload, check);
131
+ if (info.mediaType !== prefix[1])
132
+ throw invalidImage();
133
+ return info;
134
+ }
135
+ /** Recognize image bytes, not merely strings using the base64 alphabet. */
136
+ export function classifierImageFromText(value, check) {
137
+ return prepareClassifierImageText(value, check)?.dataUrl;
138
+ }
139
+ export function prepareClassifierImageText(value, check) {
140
+ check?.();
141
+ if (value.length > CLASSIFIER_LIMITS.requestBytes)
142
+ throw new Error('Classifier image/text exceeds the 32 MiB input limit.');
143
+ if (value.startsWith('data:image/')) {
144
+ return { ...inspectClassifierImage(value, check), dataUrl: value };
145
+ }
146
+ if (!/^(?:iVBOR|\/9j\/|R0lGOD|UklGR)/.test(value) || !isBase64(value))
147
+ return undefined;
148
+ try {
149
+ const info = base64ImageInfo(value, check);
150
+ return { ...info, dataUrl: `data:${info.mediaType};base64,${value}` };
151
+ }
152
+ catch (error) {
153
+ if (error instanceof InvalidClassifierImageError)
154
+ return undefined;
155
+ throw error;
156
+ }
157
+ }
158
+ export function assertClassifierImages(value, check) {
159
+ if (!Array.isArray(value) || value.length > 128)
160
+ throw new Error('State must contain at most 128 images.');
161
+ for (const image of value)
162
+ inspectClassifierImage(image, check);
163
+ }
164
+ export function assertLiquidImageLimits(images, check) {
165
+ if (images.length > 8)
166
+ throw new Error('Liquid d1 State must contain at most 8 images.');
167
+ let patches = 0;
168
+ for (const { width, height } of images) {
169
+ check?.();
170
+ if (Math.max(width, height) / Math.min(width, height) > 100)
171
+ throw new Error('Liquid d1 images must have an aspect ratio at most 100:1.');
172
+ patches += Math.ceil(width / 32) * Math.ceil(height / 32);
173
+ }
174
+ if (patches > 10_000)
175
+ throw new Error('Liquid d1 images must contain at most 10,000 patches of 32 by 32 pixels in total.');
176
+ }
@@ -0,0 +1,57 @@
1
+ import { ClassifierValueBudget } from './limits.js';
2
+ /** Read evidence fields without invoking getters or accepting prototype-provided content. */
3
+ export function classifierDataProperty(value, key, label = 'State') {
4
+ const property = Object.getOwnPropertyDescriptor(value, key);
5
+ if (property ? !('value' in property) : key in value)
6
+ throw new Error(`${label} must use own data properties, not accessors or inherited fields.`);
7
+ return property?.value;
8
+ }
9
+ /** Snapshot only the selected port's wrapper; never read unrelated input getters. */
10
+ export function classifierInputDataValue(inputs, port) {
11
+ const label = `Classifier ${port} input`;
12
+ const input = classifierDataProperty(inputs, port, label);
13
+ if (input === undefined)
14
+ return undefined;
15
+ if (input === null || typeof input !== 'object' || Array.isArray(input))
16
+ throw new Error(`${label} must contain a Rivet data value.`);
17
+ return {
18
+ type: classifierDataProperty(input, 'type', label),
19
+ value: classifierDataProperty(input, 'value', label),
20
+ };
21
+ }
22
+ /** Match JSON array order; never invoke a caller-provided iterator or index getter. */
23
+ export function* classifierArrayValues(value, label) {
24
+ for (let index = 0; index < value.length; index++) {
25
+ const property = Object.getOwnPropertyDescriptor(value, String(index));
26
+ if (!property || !('value' in property))
27
+ throw new Error(`${label} is not JSON-compatible: use own data properties, not accessors or sparse arrays.`);
28
+ yield property.value;
29
+ }
30
+ }
31
+ /** Validate the data JSON.stringify will read, without invoking property getters or array iterators. */
32
+ export function assertClassifierJson(value, label = 'State', allowUndefinedProperties = false, check, maxBytes) {
33
+ return new ClassifierValueBudget(check, maxBytes).inspect(value, { label, allowUndefinedProperties }).bytes;
34
+ }
35
+ /** Validate, account and detach JSON in one bounded walk, without serialization hooks. */
36
+ export function snapshotClassifierJson(value, label, budget, allowUndefinedProperties = false) {
37
+ return budget.inspect(value, { label, allowUndefinedProperties, copy: true }).value;
38
+ }
39
+ /** Root entry kinds are narrower than the JSON values allowed inside structured entries. */
40
+ export function assertClassifierEntryKind(value, label) {
41
+ if (value !== null && typeof value !== 'string' && typeof value !== 'object')
42
+ throw new Error(`${label} must contain only strings, null, objects, and arrays.`);
43
+ }
44
+ export function assertClassifierEntry(value, label) {
45
+ assertClassifierEntryKind(value, label);
46
+ assertClassifierJson(value, label);
47
+ }
48
+ export function assertClassifierInstructionsKind(value, label = 'Instructions') {
49
+ assertClassifierEntryKind(value, label);
50
+ if (value === null || (typeof value === 'string' && value.trim() === ''))
51
+ throw new Error(`${label} are required.`);
52
+ }
53
+ export function assertClassifierInstructions(value, label = 'Instructions') {
54
+ // Bound strings before trim(), which can otherwise scan an oversized authored value.
55
+ assertClassifierEntry(value, label);
56
+ assertClassifierInstructionsKind(value, label);
57
+ }
@@ -0,0 +1,300 @@
1
+ /** Core safety limits, not provider capacity claims. Stricter provider limits still apply. */
2
+ export const CLASSIFIER_LIMITS = {
3
+ requestBytes: 32 * 1024 * 1024,
4
+ responseBytes: 8 * 1024 * 1024,
5
+ depth: 64,
6
+ values: 100_000,
7
+ questions: 1000,
8
+ messages: 1024,
9
+ parts: 4096,
10
+ };
11
+ export class ClassifierResourceLimitError extends Error {
12
+ }
13
+ /** Receipt failed before JSON decoding/validation, rather than malformed evidence. */
14
+ export class ClassifierResponseReadError extends Error {
15
+ }
16
+ const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
17
+ const byteBuffer = Object.getOwnPropertyDescriptor(typedArrayPrototype, 'buffer').get;
18
+ const byteOffset = Object.getOwnPropertyDescriptor(typedArrayPrototype, 'byteOffset').get;
19
+ const byteLength = Object.getOwnPropertyDescriptor(typedArrayPrototype, 'byteLength').get;
20
+ /** A plain view uses real byte geometry and cannot execute authored byte accessors/methods. */
21
+ export function classifierByteView(value) {
22
+ return new Uint8Array(byteBuffer.call(value), byteOffset.call(value), byteLength.call(value));
23
+ }
24
+ export function classifierPreparationCheck(signal, deadline, timeoutMs) {
25
+ return () => {
26
+ signal.throwIfAborted();
27
+ if (Date.now() >= deadline)
28
+ throw new Error(`Classifier preparation/request timed out${timeoutMs === undefined ? '' : ` after ${timeoutMs} ms`}.`);
29
+ };
30
+ }
31
+ /** Bound expanded work before JSON serialization or image encoding, without reading getters. */
32
+ export function assertClassifierResourceLimits(value, check = () => { }, maxBytes = CLASSIFIER_LIMITS.requestBytes) {
33
+ return new ClassifierValueBudget(check, maxBytes).inspect(value).bytes;
34
+ }
35
+ /** One traversal can account, validate plain JSON, and detach it before IO. */
36
+ export class ClassifierValueBudget {
37
+ check;
38
+ bytes = 0;
39
+ values = 0;
40
+ maxBytes;
41
+ constructor(check = () => { }, maxBytes = CLASSIFIER_LIMITS.requestBytes) {
42
+ this.check = check;
43
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0)
44
+ throw new ClassifierResourceLimitError('Classifier byte limit must be a positive safe integer.');
45
+ this.maxBytes = Math.min(maxBytes, CLASSIFIER_LIMITS.requestBytes);
46
+ }
47
+ get remainingBytes() {
48
+ return this.maxBytes - this.bytes;
49
+ }
50
+ add(count) {
51
+ this.bytes += count;
52
+ if (this.bytes > this.maxBytes) {
53
+ const maxBytes = this.maxBytes;
54
+ const size = maxBytes >= 1_000_000
55
+ ? maxBytes % (1024 * 1024) === 0
56
+ ? `${maxBytes / (1024 * 1024)} MiB`
57
+ : `${maxBytes / 1_000_000} MB`
58
+ : `${maxBytes}-byte`;
59
+ throw new ClassifierResourceLimitError(`Classifier input exceeds the ${size} resource limit. Reduce input content or image size.`);
60
+ }
61
+ }
62
+ string(text) {
63
+ // Every UTF-16 unit occupies at least one JSON byte; reject before scanning huge strings.
64
+ this.add(text.length + 2);
65
+ for (let i = 0; i < text.length; i++) {
66
+ if ((i & 4095) === 0)
67
+ this.check();
68
+ const code = text.charCodeAt(i);
69
+ if (code === 34 || code === 92)
70
+ this.add(1);
71
+ else if (code < 32)
72
+ this.add([8, 9, 10, 12, 13].includes(code) ? 1 : 5);
73
+ else if (code < 128)
74
+ continue;
75
+ else if (code < 2048)
76
+ this.add(1);
77
+ else if (code >= 0xd800 && code <= 0xdfff) {
78
+ const next = text.charCodeAt(i + 1);
79
+ if (code <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) {
80
+ this.add(2);
81
+ i++;
82
+ }
83
+ else
84
+ this.add(5); // JSON.stringify escapes lone surrogates.
85
+ }
86
+ else
87
+ this.add(2);
88
+ }
89
+ }
90
+ value(depth) {
91
+ this.check();
92
+ if (++this.values > CLASSIFIER_LIMITS.values)
93
+ throw new ClassifierResourceLimitError('Classifier input has too many expanded values.');
94
+ if (depth > CLASSIFIER_LIMITS.depth)
95
+ throw new ClassifierResourceLimitError('Classifier input exceeds the maximum nesting depth of 64.');
96
+ }
97
+ inspect(value, json) {
98
+ const startBytes = this.bytes;
99
+ const path = new Set();
100
+ const invalid = () => new Error(`${json.label} is not JSON-compatible: use own data properties, not accessors or sparse arrays.`);
101
+ const visit = (item, depth) => {
102
+ this.value(depth);
103
+ if (typeof item === 'string') {
104
+ this.string(item);
105
+ return item;
106
+ }
107
+ if (!json && item instanceof Uint8Array) {
108
+ this.add(4 * Math.ceil(classifierByteView(item).byteLength / 3) + 40);
109
+ return item;
110
+ }
111
+ if (item === null || typeof item !== 'object') {
112
+ if (json && item !== null && typeof item !== 'boolean' && !(typeof item === 'number' && Number.isFinite(item)))
113
+ throw new Error(`${json.label} is not JSON-compatible.`);
114
+ this.add(typeof item === 'number' ? String(item).length : 5);
115
+ return item;
116
+ }
117
+ if (json) {
118
+ const prototype = Object.getPrototypeOf(item);
119
+ if (prototype !== (Array.isArray(item) ? Array.prototype : Object.prototype) && prototype !== null)
120
+ throw new Error(`${json.label} must contain plain JSON objects.`);
121
+ const hook = Object.getOwnPropertyDescriptor(item, 'toJSON') ??
122
+ (prototype && Object.getOwnPropertyDescriptor(prototype, 'toJSON'));
123
+ if (hook && (!('value' in hook) || typeof hook.value === 'function'))
124
+ throw new Error(`${json.label} must not contain JSON serialization hooks.`);
125
+ }
126
+ if (path.has(item))
127
+ throw new Error('Classifier input contains a circular reference.');
128
+ path.add(item);
129
+ this.add(2);
130
+ const copy = json?.copy ? (Array.isArray(item) ? [] : {}) : undefined;
131
+ if (Array.isArray(item)) {
132
+ if (item.length > CLASSIFIER_LIMITS.values)
133
+ throw new ClassifierResourceLimitError('Classifier input has too many expanded values.');
134
+ for (let i = 0; i < item.length; i++) {
135
+ if (i > 0)
136
+ this.add(1);
137
+ const descriptor = Object.getOwnPropertyDescriptor(item, String(i));
138
+ if (!descriptor || !('value' in descriptor)) {
139
+ if (json)
140
+ throw invalid();
141
+ visit(undefined, depth + 1);
142
+ continue;
143
+ }
144
+ const entry = visit(descriptor.value, depth + 1);
145
+ if (copy)
146
+ copy.push(entry);
147
+ }
148
+ }
149
+ else {
150
+ const keys = Object.keys(item);
151
+ if (keys.length > CLASSIFIER_LIMITS.values)
152
+ throw new ClassifierResourceLimitError('Classifier input has too many expanded values.');
153
+ let index = 0;
154
+ for (const key of keys) {
155
+ // Omitted wire fields still cost preparation work and snapshot memory.
156
+ this.string(key);
157
+ this.add(index++ === 0 ? 1 : 2);
158
+ const descriptor = Object.getOwnPropertyDescriptor(item, key);
159
+ if (!descriptor || !('value' in descriptor)) {
160
+ if (json)
161
+ throw invalid();
162
+ visit(undefined, depth + 1);
163
+ continue;
164
+ }
165
+ let entry;
166
+ if (descriptor.value === undefined && json) {
167
+ if (!(depth === 0 && json.allowUndefinedProperties))
168
+ throw invalid();
169
+ this.value(depth + 1);
170
+ this.add(5);
171
+ // Typed template values distinguish a missing value from an absent property.
172
+ // JSON.stringify will still omit optional undefined fields on the wire.
173
+ }
174
+ else {
175
+ entry = visit(descriptor.value, depth + 1);
176
+ }
177
+ if (copy)
178
+ Object.defineProperty(copy, key, { enumerable: true, writable: true, configurable: true, value: entry });
179
+ }
180
+ }
181
+ path.delete(item);
182
+ return copy ?? item;
183
+ };
184
+ const result = visit(value, 0);
185
+ this.check();
186
+ return { value: result, bytes: this.bytes - startBytes };
187
+ }
188
+ }
189
+ /** Bound parser allocation without interpreting brackets or separators inside strings. */
190
+ export function checkClassifierJsonWork(text, check, label = 'response') {
191
+ let quoted = false;
192
+ let escaped = false;
193
+ let depth = 0;
194
+ let separators = 0;
195
+ for (let i = 0; i < text.length; i++) {
196
+ if ((i & 4095) === 0)
197
+ check();
198
+ const character = text[i];
199
+ if (quoted) {
200
+ if (escaped)
201
+ escaped = false;
202
+ else if (character === '\\')
203
+ escaped = true;
204
+ else if (character === '"')
205
+ quoted = false;
206
+ }
207
+ else if (character === '"')
208
+ quoted = true;
209
+ else if (character === '{' || character === '[') {
210
+ if (++depth > CLASSIFIER_LIMITS.depth)
211
+ throw new ClassifierResourceLimitError(`Classifier ${label} exceeds the maximum nesting depth of 64.`);
212
+ separators++;
213
+ }
214
+ else if (character === '}' || character === ']')
215
+ depth--;
216
+ else if (character === ',' || character === ':')
217
+ separators++;
218
+ // A conservative token guard bounds JSON.parse allocation. The exact
219
+ // expanded-value guard runs on the parsed object afterward.
220
+ if (separators > CLASSIFIER_LIMITS.values * 2)
221
+ throw new ClassifierResourceLimitError(`Classifier ${label} has too many values.`);
222
+ }
223
+ }
224
+ /** Consume decoded response bytes incrementally; Content-Length is not trusted. */
225
+ export async function readClassifierResponse(response, signal, check = () => signal.throwIfAborted(), onBody) {
226
+ const length = response.headers.get('content-length');
227
+ if (length && Number(length) > CLASSIFIER_LIMITS.responseBytes)
228
+ throw new ClassifierResourceLimitError('Classifier response exceeds the 8 MiB response limit.');
229
+ if (!response.body)
230
+ return JSON.parse('');
231
+ const reader = response.body.getReader();
232
+ const cancel = () => {
233
+ void reader.cancel().catch(() => { });
234
+ };
235
+ signal.addEventListener('abort', cancel, { once: true });
236
+ const decoder = new TextDecoder('utf-8', { fatal: true });
237
+ const text = [];
238
+ let pending = '';
239
+ let bytes = 0;
240
+ try {
241
+ for (;;) {
242
+ check();
243
+ const { done, value } = await reader.read().catch((cause) => {
244
+ throw new ClassifierResponseReadError('Classifier response body could not be read.', { cause });
245
+ });
246
+ check();
247
+ if (done)
248
+ break;
249
+ const chunk = classifierByteView(value);
250
+ bytes += chunk.byteLength;
251
+ if (bytes > CLASSIFIER_LIMITS.responseBytes)
252
+ throw new ClassifierResourceLimitError('Classifier response exceeds the 8 MiB response limit.');
253
+ pending += decoder.decode(chunk, { stream: true });
254
+ if (pending.length >= 64 * 1024) {
255
+ text.push(pending);
256
+ pending = '';
257
+ }
258
+ }
259
+ text.push(pending + decoder.decode());
260
+ check();
261
+ const json = text.join('');
262
+ checkClassifierJsonWork(json, check);
263
+ let body;
264
+ try {
265
+ body = JSON.parse(json);
266
+ }
267
+ catch (error) {
268
+ check();
269
+ try {
270
+ onBody?.(json);
271
+ }
272
+ catch {
273
+ /* Observation only. */
274
+ }
275
+ check();
276
+ throw error;
277
+ }
278
+ assertClassifierResourceLimits(body, check, CLASSIFIER_LIMITS.responseBytes);
279
+ check();
280
+ try {
281
+ // Diagnostics must not modify the private response before validation or pricing.
282
+ // Only opt-in observers allocate a detached copy of this bounded, plain JSON.
283
+ if (onBody)
284
+ onBody(structuredClone(body));
285
+ }
286
+ catch {
287
+ /* Observation only. */
288
+ }
289
+ check();
290
+ return body;
291
+ }
292
+ catch (error) {
293
+ cancel();
294
+ throw error;
295
+ }
296
+ finally {
297
+ signal.removeEventListener('abort', cancel);
298
+ reader.releaseLock();
299
+ }
300
+ }
@@ -0,0 +1,118 @@
1
+ import { validateClassifierEvaluationResponse } from './response.js';
2
+ function text(value) {
3
+ return typeof value === 'string' ? value : JSON.stringify(value);
4
+ }
5
+ /** OpenAI's Decisions schema is not the System One protocol. */
6
+ export function createOpenAIDecisionRequest(args) {
7
+ const state = args.state;
8
+ return {
9
+ model: args.model,
10
+ input: state.kind === 'messages'
11
+ ? state.messages.map(({ parts }) => ({
12
+ role: 'user',
13
+ content: parts.map((part) => part.type === 'text'
14
+ ? { type: 'input_text', text: part.text }
15
+ : { type: 'input_image', image_url: part.dataUrl }),
16
+ }))
17
+ : typeof state.value === 'string'
18
+ ? state.value
19
+ : JSON.stringify(state.value),
20
+ questions: args.questions.map((question) => {
21
+ const common = { name: question.questionId, instructions: text(question.instructions) };
22
+ if (question.type === 'choice')
23
+ return {
24
+ ...common,
25
+ type: 'choice',
26
+ choices: Object.entries(question.criteria).map(([value, description]) => ({
27
+ value,
28
+ ...(description === null ? {} : { description: text(description) }),
29
+ })),
30
+ };
31
+ if (question.type === 'score')
32
+ return {
33
+ ...common,
34
+ type: 'score',
35
+ levels: question.criteria.map((entry) => ({ label: text(entry) })),
36
+ };
37
+ const criteria = question.criteria;
38
+ return {
39
+ ...common,
40
+ type: 'predicate',
41
+ instructions: criteria
42
+ ? `${common.instructions}\n\nTrue criterion: ${text(criteria.true)}\nFalse criterion: ${text(criteria.false)}`
43
+ : common.instructions,
44
+ };
45
+ }),
46
+ };
47
+ }
48
+ function record(value) {
49
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
50
+ }
51
+ function field(value, name) {
52
+ return Object.prototype.hasOwnProperty.call(value, name) ? value[name] : undefined;
53
+ }
54
+ export function validateOpenAIDecisionResponse(body, questions, providerLabel = 'OpenAI') {
55
+ const nativeAnswers = record(body) ? field(body, 'answers') : undefined;
56
+ if (!record(body) || !Array.isArray(nativeAnswers) || nativeAnswers.length !== questions.length) {
57
+ throw new Error(`${providerLabel} returned an invalid response shape.`);
58
+ }
59
+ const answers = Object.create(null);
60
+ for (let index = 0; index < questions.length; index++) {
61
+ const question = questions[index];
62
+ const answer = nativeAnswers[index];
63
+ if (!record(answer) || field(answer, 'name') !== question.questionId) {
64
+ throw new Error(`${providerLabel} response does not match the submitted question IDs/order.`);
65
+ }
66
+ const type = field(answer, 'type');
67
+ if (type === 'refusal')
68
+ throw new Error(`${providerLabel} refused question '${question.questionId}'.`);
69
+ if (type !== (question.type === 'noul' ? 'predicate' : question.type)) {
70
+ throw new Error(`${providerLabel} response type does not match question '${question.questionId}'.`);
71
+ }
72
+ let mapped;
73
+ if (question.type === 'noul')
74
+ mapped = { type: 'noul', noul: field(answer, 'probability') };
75
+ else {
76
+ const entries = field(answer, 'probabilities');
77
+ if (!Array.isArray(entries))
78
+ throw new Error(`${providerLabel} response has invalid probabilities.`);
79
+ const probabilities = Object.create(null);
80
+ const legend = Object.create(null);
81
+ for (const entry of entries) {
82
+ if (!record(entry))
83
+ throw new Error(`${providerLabel} response has invalid probability entry.`);
84
+ const value = field(entry, 'value');
85
+ if (question.type === 'choice'
86
+ ? typeof value !== 'string'
87
+ : typeof value !== 'number' || !Number.isSafeInteger(value)) {
88
+ throw new Error(`${providerLabel} response has invalid probability key.`);
89
+ }
90
+ const key = String(value);
91
+ if (Object.prototype.hasOwnProperty.call(probabilities, key)) {
92
+ throw new Error(`${providerLabel} response has duplicate probability keys.`);
93
+ }
94
+ Object.defineProperty(probabilities, key, { enumerable: true, value: field(entry, 'probability') });
95
+ if (question.type === 'score') {
96
+ const label = field(entry, 'label');
97
+ if (typeof label !== 'string')
98
+ throw new Error(`${providerLabel} response has invalid score label.`);
99
+ Object.defineProperty(legend, key, { enumerable: true, value: label });
100
+ }
101
+ }
102
+ mapped = {
103
+ type: question.type,
104
+ confidence: field(answer, 'confidence'),
105
+ probabilities,
106
+ ...(question.type === 'choice'
107
+ ? { choice: field(answer, 'choice') }
108
+ : { score: field(answer, 'score'), legend }),
109
+ };
110
+ }
111
+ Object.defineProperty(answers, question.questionId, { enumerable: true, value: mapped });
112
+ }
113
+ return validateClassifierEvaluationResponse({
114
+ model: field(body, 'model'),
115
+ answers,
116
+ usage: field(body, 'usage'),
117
+ }, questions, providerLabel);
118
+ }