@valerypopoff/rivet2-core 2.15.0 → 2.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/dist/cjs/bundle.cjs +4350 -2077
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/interpolationRuntime.cjs +22 -3
  4. package/dist/cjs/interpolationRuntime.cjs.map +3 -3
  5. package/dist/cjs/interpolationSyntax.cjs +9 -5
  6. package/dist/cjs/interpolationSyntax.cjs.map +2 -2
  7. package/dist/esm/api/createProcessor.js +5 -2
  8. package/dist/esm/exports.js +2 -0
  9. package/dist/esm/model/GraphBoundaryCache.js +2 -1
  10. package/dist/esm/model/GraphProcessor.js +268 -6
  11. package/dist/esm/model/Nodes.js +10 -0
  12. package/dist/esm/model/ProjectBundle.js +235 -0
  13. package/dist/esm/model/SplitRunProcessor.js +28 -7
  14. package/dist/esm/model/StreamingWatchTopology.js +118 -8
  15. package/dist/esm/model/SubgraphProjectTarget.js +7 -0
  16. package/dist/esm/model/chat-v2/aiSdkBridge.js +7 -5
  17. package/dist/esm/model/chat-v2/chatV2Pipeline.js +13 -8
  18. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +19 -1
  19. package/dist/esm/model/chat-v2/chatV2Shared.js +2 -1
  20. package/dist/esm/model/chat-v2/llmChatV2Body.js +11 -8
  21. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +2 -0
  22. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +15 -1
  23. package/dist/esm/model/chat-v2/llmChatV2NodeMigration.js +22 -2
  24. package/dist/esm/model/chat-v2/llmProfile.js +3 -0
  25. package/dist/esm/model/chat-v2/llmProfileBody.js +2 -2
  26. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +1 -1
  27. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +1 -1
  28. package/dist/esm/model/chat-v2/temperature.js +9 -0
  29. package/dist/esm/model/classifier/credentials.js +30 -4
  30. package/dist/esm/model/classifier/images.js +176 -0
  31. package/dist/esm/model/classifier/json.js +57 -0
  32. package/dist/esm/model/classifier/limits.js +270 -0
  33. package/dist/esm/model/classifier/openai.js +118 -0
  34. package/dist/esm/model/classifier/preparation.js +74 -0
  35. package/dist/esm/model/classifier/providers.js +260 -185
  36. package/dist/esm/model/classifier/questionHelpers.js +29 -45
  37. package/dist/esm/model/classifier/questions.js +53 -0
  38. package/dist/esm/model/classifier/response.js +75 -0
  39. package/dist/esm/model/classifier/state.js +204 -0
  40. package/dist/esm/model/nodeRunFailure.js +47 -0
  41. package/dist/esm/model/nodes/CatchStreamingChunksNode.js +42 -0
  42. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +178 -138
  43. package/dist/esm/model/nodes/ClassifierQuestionNode.js +59 -15
  44. package/dist/esm/model/nodes/GetGlobalNode.js +2 -2
  45. package/dist/esm/model/nodes/HttpCallNode.js +44 -75
  46. package/dist/esm/model/nodes/ImageNode.js +44 -3
  47. package/dist/esm/model/nodes/LLMChatV2Node.js +24 -3
  48. package/dist/esm/model/nodes/ObjectNode.js +29 -18
  49. package/dist/esm/model/nodes/PromptNode.js +2 -1
  50. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +4 -1
  51. package/dist/esm/model/nodes/SetGlobalNode.js +5 -3
  52. package/dist/esm/model/nodes/StopWatchingStreamingOutputNode.js +8 -8
  53. package/dist/esm/model/nodes/StreamValueNode.js +38 -0
  54. package/dist/esm/model/nodes/SubGraphNode.js +196 -35
  55. package/dist/esm/model/nodes/ToBase64Node.js +106 -0
  56. package/dist/esm/model/nodes/WatchStreamingOutputNode.js +7 -7
  57. package/dist/esm/recording/ExecutionRecorder.js +26 -0
  58. package/dist/esm/utils/base64.js +18 -15
  59. package/dist/esm/utils/errors.js +41 -0
  60. package/dist/esm/utils/interpolation.js +44 -22
  61. package/dist/esm/utils/interpolationSyntax.js +15 -6
  62. package/dist/esm/utils/serialization/serialization.js +3 -2
  63. package/dist/esm/utils/serialization/serializationUtils.js +6 -0
  64. package/dist/esm/utils/serialization/serialization_v4.js +15 -3
  65. package/dist/types/api/createProcessor.d.ts +7 -1
  66. package/dist/types/exports.d.ts +2 -0
  67. package/dist/types/model/CycleDetector.d.ts +1 -2
  68. package/dist/types/model/ExecutorProtocol.d.ts +2 -0
  69. package/dist/types/model/GraphBoundaryCache.d.ts +2 -0
  70. package/dist/types/model/GraphProcessor.d.ts +1 -0
  71. package/dist/types/model/Nodes.d.ts +6 -2
  72. package/dist/types/model/ProcessContext.d.ts +12 -0
  73. package/dist/types/model/ProjectBundle.d.ts +54 -0
  74. package/dist/types/model/ProjectReferenceLoader.d.ts +3 -0
  75. package/dist/types/model/StreamingWatchTopology.d.ts +11 -1
  76. package/dist/types/model/SubgraphProjectTarget.d.ts +38 -0
  77. package/dist/types/model/chat-v2/chatV2Shared.d.ts +1 -1
  78. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +3 -1
  79. package/dist/types/model/chat-v2/llmChatV2NodeMigration.d.ts +3 -1
  80. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +6 -6
  81. package/dist/types/model/chat-v2/temperature.d.ts +2 -0
  82. package/dist/types/model/classifier/credentials.d.ts +3 -1
  83. package/dist/types/model/classifier/images.d.ts +18 -0
  84. package/dist/types/model/classifier/json.d.ts +19 -0
  85. package/dist/types/model/classifier/limits.d.ts +42 -0
  86. package/dist/types/model/classifier/openai.d.ts +5 -0
  87. package/dist/types/model/classifier/preparation.d.ts +16 -0
  88. package/dist/types/model/classifier/providers.d.ts +67 -9
  89. package/dist/types/model/classifier/questionHelpers.d.ts +6 -4
  90. package/dist/types/model/classifier/questions.d.ts +4 -0
  91. package/dist/types/model/classifier/response.d.ts +4 -0
  92. package/dist/types/model/classifier/state.d.ts +37 -0
  93. package/dist/types/model/classifier/types.d.ts +2 -0
  94. package/dist/types/model/nodeRunFailure.d.ts +13 -0
  95. package/dist/types/model/nodes/CatchStreamingChunksNode.d.ts +20 -0
  96. package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +3 -0
  97. package/dist/types/model/nodes/GetGlobalNode.d.ts +7 -0
  98. package/dist/types/model/nodes/ImageNode.d.ts +4 -0
  99. package/dist/types/model/nodes/LLMChatV2Node.d.ts +1 -0
  100. package/dist/types/model/nodes/ObjectNode.d.ts +2 -1
  101. package/dist/types/model/nodes/StreamValueNode.d.ts +14 -0
  102. package/dist/types/model/nodes/SubGraphNode.d.ts +21 -2
  103. package/dist/types/model/nodes/ToBase64Node.d.ts +12 -0
  104. package/dist/types/recording/ExecutionRecorder.d.ts +8 -2
  105. package/dist/types/utils/base64.d.ts +1 -1
  106. package/dist/types/utils/errors.d.ts +4 -0
  107. package/dist/types/utils/interpolation.d.ts +13 -2
  108. package/dist/types/utils/interpolationSyntax.d.ts +1 -1
  109. package/dist/types/utils/serialization/serialization.d.ts +3 -1
  110. package/dist/types/utils/serialization/serializationUtils.d.ts +1 -0
  111. package/package.json +1 -1
@@ -0,0 +1,270 @@
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
+ const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
14
+ const byteBuffer = Object.getOwnPropertyDescriptor(typedArrayPrototype, 'buffer').get;
15
+ const byteOffset = Object.getOwnPropertyDescriptor(typedArrayPrototype, 'byteOffset').get;
16
+ const byteLength = Object.getOwnPropertyDescriptor(typedArrayPrototype, 'byteLength').get;
17
+ /** A plain view uses real byte geometry and cannot execute authored byte accessors/methods. */
18
+ export function classifierByteView(value) {
19
+ return new Uint8Array(byteBuffer.call(value), byteOffset.call(value), byteLength.call(value));
20
+ }
21
+ export function classifierPreparationCheck(signal, deadline, timeoutMs) {
22
+ return () => {
23
+ signal.throwIfAborted();
24
+ if (Date.now() >= deadline)
25
+ throw new Error(`Classifier preparation/request timed out${timeoutMs === undefined ? '' : ` after ${timeoutMs} ms`}.`);
26
+ };
27
+ }
28
+ /** Bound expanded work before JSON serialization or image encoding, without reading getters. */
29
+ export function assertClassifierResourceLimits(value, check = () => { }, maxBytes = CLASSIFIER_LIMITS.requestBytes) {
30
+ return new ClassifierValueBudget(check, maxBytes).inspect(value).bytes;
31
+ }
32
+ /** One traversal can account, validate plain JSON, and detach it before IO. */
33
+ export class ClassifierValueBudget {
34
+ check;
35
+ bytes = 0;
36
+ values = 0;
37
+ maxBytes;
38
+ constructor(check = () => { }, maxBytes = CLASSIFIER_LIMITS.requestBytes) {
39
+ this.check = check;
40
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0)
41
+ throw new ClassifierResourceLimitError('Classifier byte limit must be a positive safe integer.');
42
+ this.maxBytes = Math.min(maxBytes, CLASSIFIER_LIMITS.requestBytes);
43
+ }
44
+ get remainingBytes() {
45
+ return this.maxBytes - this.bytes;
46
+ }
47
+ add(count) {
48
+ this.bytes += count;
49
+ if (this.bytes > this.maxBytes) {
50
+ const maxBytes = this.maxBytes;
51
+ const size = maxBytes >= 1_000_000
52
+ ? maxBytes % (1024 * 1024) === 0
53
+ ? `${maxBytes / (1024 * 1024)} MiB`
54
+ : `${maxBytes / 1_000_000} MB`
55
+ : `${maxBytes}-byte`;
56
+ throw new ClassifierResourceLimitError(`Classifier input exceeds the ${size} resource limit. Reduce input content or image size.`);
57
+ }
58
+ }
59
+ string(text) {
60
+ // Every UTF-16 unit occupies at least one JSON byte; reject before scanning huge strings.
61
+ this.add(text.length + 2);
62
+ for (let i = 0; i < text.length; i++) {
63
+ if ((i & 4095) === 0)
64
+ this.check();
65
+ const code = text.charCodeAt(i);
66
+ if (code === 34 || code === 92)
67
+ this.add(1);
68
+ else if (code < 32)
69
+ this.add([8, 9, 10, 12, 13].includes(code) ? 1 : 5);
70
+ else if (code < 128)
71
+ continue;
72
+ else if (code < 2048)
73
+ this.add(1);
74
+ else if (code >= 0xd800 && code <= 0xdfff) {
75
+ const next = text.charCodeAt(i + 1);
76
+ if (code <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) {
77
+ this.add(2);
78
+ i++;
79
+ }
80
+ else
81
+ this.add(5); // JSON.stringify escapes lone surrogates.
82
+ }
83
+ else
84
+ this.add(2);
85
+ }
86
+ }
87
+ value(depth) {
88
+ this.check();
89
+ if (++this.values > CLASSIFIER_LIMITS.values)
90
+ throw new ClassifierResourceLimitError('Classifier input has too many expanded values.');
91
+ if (depth > CLASSIFIER_LIMITS.depth)
92
+ throw new ClassifierResourceLimitError('Classifier input exceeds the maximum nesting depth of 64.');
93
+ }
94
+ inspect(value, json) {
95
+ const startBytes = this.bytes;
96
+ const path = new Set();
97
+ const invalid = () => new Error(`${json.label} is not JSON-compatible: use own data properties, not accessors or sparse arrays.`);
98
+ const visit = (item, depth) => {
99
+ this.value(depth);
100
+ if (typeof item === 'string') {
101
+ this.string(item);
102
+ return item;
103
+ }
104
+ if (!json && item instanceof Uint8Array) {
105
+ this.add(4 * Math.ceil(classifierByteView(item).byteLength / 3) + 40);
106
+ return item;
107
+ }
108
+ if (item === null || typeof item !== 'object') {
109
+ if (json && item !== null && typeof item !== 'boolean' && !(typeof item === 'number' && Number.isFinite(item)))
110
+ throw new Error(`${json.label} is not JSON-compatible.`);
111
+ this.add(typeof item === 'number' ? String(item).length : 5);
112
+ return item;
113
+ }
114
+ if (json) {
115
+ const prototype = Object.getPrototypeOf(item);
116
+ if (prototype !== (Array.isArray(item) ? Array.prototype : Object.prototype) && prototype !== null)
117
+ throw new Error(`${json.label} must contain plain JSON objects.`);
118
+ const hook = Object.getOwnPropertyDescriptor(item, 'toJSON') ??
119
+ (prototype && Object.getOwnPropertyDescriptor(prototype, 'toJSON'));
120
+ if (hook && (!('value' in hook) || typeof hook.value === 'function'))
121
+ throw new Error(`${json.label} must not contain JSON serialization hooks.`);
122
+ }
123
+ if (path.has(item))
124
+ throw new Error('Classifier input contains a circular reference.');
125
+ path.add(item);
126
+ this.add(2);
127
+ const copy = json?.copy ? (Array.isArray(item) ? [] : {}) : undefined;
128
+ if (Array.isArray(item)) {
129
+ if (item.length > CLASSIFIER_LIMITS.values)
130
+ throw new ClassifierResourceLimitError('Classifier input has too many expanded values.');
131
+ for (let i = 0; i < item.length; i++) {
132
+ if (i > 0)
133
+ this.add(1);
134
+ const descriptor = Object.getOwnPropertyDescriptor(item, String(i));
135
+ if (!descriptor || !('value' in descriptor)) {
136
+ if (json)
137
+ throw invalid();
138
+ visit(undefined, depth + 1);
139
+ continue;
140
+ }
141
+ const entry = visit(descriptor.value, depth + 1);
142
+ if (copy)
143
+ copy.push(entry);
144
+ }
145
+ }
146
+ else {
147
+ const keys = Object.keys(item);
148
+ if (keys.length > CLASSIFIER_LIMITS.values)
149
+ throw new ClassifierResourceLimitError('Classifier input has too many expanded values.');
150
+ let index = 0;
151
+ for (const key of keys) {
152
+ // Omitted wire fields still cost preparation work and snapshot memory.
153
+ this.string(key);
154
+ this.add(index++ === 0 ? 1 : 2);
155
+ const descriptor = Object.getOwnPropertyDescriptor(item, key);
156
+ if (!descriptor || !('value' in descriptor)) {
157
+ if (json)
158
+ throw invalid();
159
+ visit(undefined, depth + 1);
160
+ continue;
161
+ }
162
+ let entry;
163
+ if (descriptor.value === undefined && json) {
164
+ if (!(depth === 0 && json.allowUndefinedProperties))
165
+ throw invalid();
166
+ this.value(depth + 1);
167
+ this.add(5);
168
+ // Typed template values distinguish a missing value from an absent property.
169
+ // JSON.stringify will still omit optional undefined fields on the wire.
170
+ }
171
+ else {
172
+ entry = visit(descriptor.value, depth + 1);
173
+ }
174
+ if (copy)
175
+ Object.defineProperty(copy, key, { enumerable: true, writable: true, configurable: true, value: entry });
176
+ }
177
+ }
178
+ path.delete(item);
179
+ return copy ?? item;
180
+ };
181
+ const result = visit(value, 0);
182
+ this.check();
183
+ return { value: result, bytes: this.bytes - startBytes };
184
+ }
185
+ }
186
+ /** Bound parser allocation without interpreting brackets or separators inside strings. */
187
+ export function checkClassifierJsonWork(text, check, label = 'response') {
188
+ let quoted = false;
189
+ let escaped = false;
190
+ let depth = 0;
191
+ let separators = 0;
192
+ for (let i = 0; i < text.length; i++) {
193
+ if ((i & 4095) === 0)
194
+ check();
195
+ const character = text[i];
196
+ if (quoted) {
197
+ if (escaped)
198
+ escaped = false;
199
+ else if (character === '\\')
200
+ escaped = true;
201
+ else if (character === '"')
202
+ quoted = false;
203
+ }
204
+ else if (character === '"')
205
+ quoted = true;
206
+ else if (character === '{' || character === '[') {
207
+ if (++depth > CLASSIFIER_LIMITS.depth)
208
+ throw new ClassifierResourceLimitError(`Classifier ${label} exceeds the maximum nesting depth of 64.`);
209
+ separators++;
210
+ }
211
+ else if (character === '}' || character === ']')
212
+ depth--;
213
+ else if (character === ',' || character === ':')
214
+ separators++;
215
+ // A conservative token guard bounds JSON.parse allocation. The exact
216
+ // expanded-value guard runs on the parsed object afterward.
217
+ if (separators > CLASSIFIER_LIMITS.values * 2)
218
+ throw new ClassifierResourceLimitError(`Classifier ${label} has too many values.`);
219
+ }
220
+ }
221
+ /** Consume decoded response bytes incrementally; Content-Length is not trusted. */
222
+ export async function readClassifierResponse(response, signal, check = () => signal.throwIfAborted()) {
223
+ const length = response.headers.get('content-length');
224
+ if (length && Number(length) > CLASSIFIER_LIMITS.responseBytes)
225
+ throw new ClassifierResourceLimitError('Classifier response exceeds the 8 MiB response limit.');
226
+ if (!response.body)
227
+ return JSON.parse('');
228
+ const reader = response.body.getReader();
229
+ const cancel = () => {
230
+ void reader.cancel().catch(() => { });
231
+ };
232
+ signal.addEventListener('abort', cancel, { once: true });
233
+ const decoder = new TextDecoder('utf-8', { fatal: true });
234
+ const text = [];
235
+ let pending = '';
236
+ let bytes = 0;
237
+ try {
238
+ for (;;) {
239
+ check();
240
+ const { done, value } = await reader.read();
241
+ check();
242
+ if (done)
243
+ break;
244
+ const chunk = classifierByteView(value);
245
+ bytes += chunk.byteLength;
246
+ if (bytes > CLASSIFIER_LIMITS.responseBytes)
247
+ throw new ClassifierResourceLimitError('Classifier response exceeds the 8 MiB response limit.');
248
+ pending += decoder.decode(chunk, { stream: true });
249
+ if (pending.length >= 64 * 1024) {
250
+ text.push(pending);
251
+ pending = '';
252
+ }
253
+ }
254
+ text.push(pending + decoder.decode());
255
+ check();
256
+ const json = text.join('');
257
+ checkClassifierJsonWork(json, check);
258
+ const body = JSON.parse(json);
259
+ assertClassifierResourceLimits(body, check, CLASSIFIER_LIMITS.responseBytes);
260
+ return body;
261
+ }
262
+ catch (error) {
263
+ cancel();
264
+ throw error;
265
+ }
266
+ finally {
267
+ signal.removeEventListener('abort', cancel);
268
+ reader.releaseLock();
269
+ }
270
+ }
@@ -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
+ }
@@ -0,0 +1,74 @@
1
+ import { ClassifierValueBudget, classifierPreparationCheck, ClassifierResourceLimitError, CLASSIFIER_LIMITS, } from './limits.js';
2
+ /** One cumulative budget for authored templates, referenced values and resolved entries. */
3
+ export class ClassifierQuestionPreparation {
4
+ tokenLimit = CLASSIFIER_LIMITS.values;
5
+ budget;
6
+ operations = 0;
7
+ deadlineCheck;
8
+ constructor(context) {
9
+ this.deadlineCheck = classifierPreparationCheck(context.signal, Date.now() + 30_000, 30_000);
10
+ this.budget = new ClassifierValueBudget(this.check);
11
+ this.check();
12
+ }
13
+ check = () => {
14
+ this.deadlineCheck();
15
+ if (++this.operations > CLASSIFIER_LIMITS.values * 10)
16
+ throw new ClassifierResourceLimitError('Classifier question preparation has too much expanded work.');
17
+ };
18
+ capture(value) {
19
+ this.inspect(value, false);
20
+ }
21
+ prepareValue = (value) => this.inspect(value, true);
22
+ inspect(value, copy) {
23
+ if (value === undefined) {
24
+ this.check();
25
+ return value;
26
+ }
27
+ return this.budget.inspect(value, {
28
+ label: 'Question preparation',
29
+ allowUndefinedProperties: true,
30
+ copy,
31
+ }).value;
32
+ }
33
+ output = (fragment, previousLength) => {
34
+ this.check();
35
+ // Reject before concatenation. Exact UTF-8/JSON bytes are charged when
36
+ // the completed entry is captured; this bounds intermediate allocations.
37
+ if (fragment.length + previousLength > this.budget.remainingBytes)
38
+ throw new ClassifierResourceLimitError('Classifier question interpolation exceeds its remaining byte budget.');
39
+ };
40
+ processing = (input, name, parameter) => {
41
+ this.check();
42
+ if (['chain', 'sort', 'dedent', 'wrap', 'indent', 'quote', 'list'].includes(name)) {
43
+ let pieces = 1;
44
+ let whitespace = false;
45
+ for (let i = 0; i < input.length; i++) {
46
+ if ((i & 4095) === 0)
47
+ this.check();
48
+ const nextWhitespace = /\s/.test(input[i]);
49
+ if ((name === 'chain' && input[i] === '|') ||
50
+ ((name === 'chain' || name === 'wrap') && nextWhitespace && !whitespace) ||
51
+ (name !== 'chain' && name !== 'wrap' && input[i] === '\n')) {
52
+ if (++pieces > CLASSIFIER_LIMITS.values)
53
+ throw new ClassifierResourceLimitError('Classifier interpolation processor has too many expanded pieces.');
54
+ }
55
+ whitespace = nextWhitespace;
56
+ }
57
+ }
58
+ if (name !== 'indent' && name !== 'quote' && name !== 'list')
59
+ return;
60
+ const value = parameter ?? (name === 'indent' ? 0 : 1);
61
+ const prefix = name === 'indent' ? value : name === 'quote' ? value * 2 : (value - 1) * 2 + 2;
62
+ if (!Number.isSafeInteger(value) || value < (name === 'list' ? 1 : 0))
63
+ throw new Error(`Invalid classifier interpolation ${name} parameter.`);
64
+ let lines = 1;
65
+ for (let i = 0; i < input.length; i++) {
66
+ if ((i & 4095) === 0)
67
+ this.check();
68
+ if (input[i] === '\n')
69
+ lines++;
70
+ }
71
+ if (input.length + lines * prefix > this.budget.remainingBytes)
72
+ throw new ClassifierResourceLimitError('Classifier interpolation processor exceeds its remaining byte budget.');
73
+ };
74
+ }