@valerypopoff/rivet2-core 2.13.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 (134) hide show
  1. package/dist/cjs/bundle.cjs +28167 -23834
  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 +10 -2
  8. package/dist/esm/api/processSettings.js +1 -0
  9. package/dist/esm/exports.js +6 -0
  10. package/dist/esm/model/GraphBoundaryCache.js +2 -1
  11. package/dist/esm/model/GraphProcessor.js +278 -22
  12. package/dist/esm/model/MarkdownSanitizationPolicy.js +2 -0
  13. package/dist/esm/model/NodeImpl.js +1 -1
  14. package/dist/esm/model/Nodes.js +16 -0
  15. package/dist/esm/model/ProjectBundle.js +235 -0
  16. package/dist/esm/model/SplitRunProcessor.js +28 -7
  17. package/dist/esm/model/StreamingWatchTopology.js +211 -64
  18. package/dist/esm/model/SubgraphProjectTarget.js +7 -0
  19. package/dist/esm/model/chat-v2/aiSdkBridge.js +7 -5
  20. package/dist/esm/model/chat-v2/chatV2Pipeline.js +13 -8
  21. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +19 -1
  22. package/dist/esm/model/chat-v2/chatV2Shared.js +2 -1
  23. package/dist/esm/model/chat-v2/llmChatV2Body.js +11 -8
  24. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +2 -0
  25. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +15 -1
  26. package/dist/esm/model/chat-v2/llmChatV2NodeMigration.js +22 -2
  27. package/dist/esm/model/chat-v2/llmProfile.js +3 -0
  28. package/dist/esm/model/chat-v2/llmProfileBody.js +2 -2
  29. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +1 -1
  30. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +1 -1
  31. package/dist/esm/model/chat-v2/temperature.js +9 -0
  32. package/dist/esm/model/classifier/credentials.js +107 -0
  33. package/dist/esm/model/classifier/images.js +176 -0
  34. package/dist/esm/model/classifier/json.js +57 -0
  35. package/dist/esm/model/classifier/limits.js +270 -0
  36. package/dist/esm/model/classifier/migration.js +97 -0
  37. package/dist/esm/model/classifier/openai.js +118 -0
  38. package/dist/esm/model/classifier/preparation.js +74 -0
  39. package/dist/esm/model/classifier/providers.js +422 -0
  40. package/dist/esm/model/classifier/questionHelpers.js +109 -0
  41. package/dist/esm/model/classifier/questions.js +53 -0
  42. package/dist/esm/model/classifier/response.js +75 -0
  43. package/dist/esm/model/classifier/state.js +204 -0
  44. package/dist/esm/model/classifier/types.js +1 -0
  45. package/dist/esm/model/nodeBodyMarkdown.js +37 -0
  46. package/dist/esm/model/nodeRunFailure.js +47 -0
  47. package/dist/esm/model/nodes/CatchStreamingChunksNode.js +42 -0
  48. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +432 -0
  49. package/dist/esm/model/nodes/ClassifierQuestionNode.js +613 -0
  50. package/dist/esm/model/nodes/CodeNewNode.js +33 -9
  51. package/dist/esm/model/nodes/GetGlobalNode.js +2 -2
  52. package/dist/esm/model/nodes/HttpCallNode.js +44 -75
  53. package/dist/esm/model/nodes/ImageNode.js +44 -3
  54. package/dist/esm/model/nodes/LLMChatV2Node.js +27 -15
  55. package/dist/esm/model/nodes/LLMProfileNode.js +6 -12
  56. package/dist/esm/model/nodes/MatchCaseNode.js +76 -1
  57. package/dist/esm/model/nodes/MatchCaseNodeBase.js +24 -2
  58. package/dist/esm/model/nodes/ObjectNode.js +68 -50
  59. package/dist/esm/model/nodes/PassthroughNode.js +1 -1
  60. package/dist/esm/model/nodes/PromptNode.js +2 -1
  61. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +4 -1
  62. package/dist/esm/model/nodes/SetGlobalNode.js +5 -3
  63. package/dist/esm/model/nodes/StopWatchingStreamingOutputNode.js +8 -8
  64. package/dist/esm/model/nodes/StreamValueNode.js +38 -0
  65. package/dist/esm/model/nodes/SubGraphNode.js +196 -35
  66. package/dist/esm/model/nodes/ToBase64Node.js +106 -0
  67. package/dist/esm/model/nodes/WatchStreamingOutputNode.js +7 -7
  68. package/dist/esm/model/nodes/codeOutputInference.js +292 -0
  69. package/dist/esm/recording/ExecutionRecorder.js +26 -0
  70. package/dist/esm/utils/base64.js +18 -15
  71. package/dist/esm/utils/errors.js +41 -0
  72. package/dist/esm/utils/interpolation.js +44 -22
  73. package/dist/esm/utils/interpolationSyntax.js +15 -6
  74. package/dist/esm/utils/serialization/serialization.js +7 -2
  75. package/dist/esm/utils/serialization/serializationUtils.js +6 -0
  76. package/dist/esm/utils/serialization/serialization_v4.js +15 -3
  77. package/dist/types/api/createProcessor.d.ts +7 -1
  78. package/dist/types/exports.d.ts +6 -0
  79. package/dist/types/model/CycleDetector.d.ts +1 -2
  80. package/dist/types/model/EditorDefinition.d.ts +24 -0
  81. package/dist/types/model/ExecutorProtocol.d.ts +2 -0
  82. package/dist/types/model/GraphBoundaryCache.d.ts +2 -0
  83. package/dist/types/model/GraphProcessor.d.ts +1 -0
  84. package/dist/types/model/MarkdownSanitizationPolicy.d.ts +1 -1
  85. package/dist/types/model/NodeImpl.d.ts +3 -1
  86. package/dist/types/model/Nodes.d.ts +10 -4
  87. package/dist/types/model/ProcessContext.d.ts +12 -0
  88. package/dist/types/model/ProjectBundle.d.ts +54 -0
  89. package/dist/types/model/ProjectReferenceLoader.d.ts +3 -0
  90. package/dist/types/model/Settings.d.ts +4 -0
  91. package/dist/types/model/StreamingWatchTopology.d.ts +17 -1
  92. package/dist/types/model/SubgraphProjectTarget.d.ts +38 -0
  93. package/dist/types/model/chat-v2/chatV2Shared.d.ts +1 -1
  94. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +3 -1
  95. package/dist/types/model/chat-v2/llmChatV2NodeMigration.d.ts +3 -1
  96. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +6 -6
  97. package/dist/types/model/chat-v2/temperature.d.ts +2 -0
  98. package/dist/types/model/classifier/credentials.d.ts +26 -0
  99. package/dist/types/model/classifier/images.d.ts +18 -0
  100. package/dist/types/model/classifier/json.d.ts +19 -0
  101. package/dist/types/model/classifier/limits.d.ts +42 -0
  102. package/dist/types/model/classifier/migration.d.ts +18 -0
  103. package/dist/types/model/classifier/openai.d.ts +5 -0
  104. package/dist/types/model/classifier/preparation.d.ts +16 -0
  105. package/dist/types/model/classifier/providers.d.ts +136 -0
  106. package/dist/types/model/classifier/questionHelpers.d.ts +33 -0
  107. package/dist/types/model/classifier/questions.d.ts +4 -0
  108. package/dist/types/model/classifier/response.d.ts +4 -0
  109. package/dist/types/model/classifier/state.d.ts +37 -0
  110. package/dist/types/model/classifier/types.d.ts +60 -0
  111. package/dist/types/model/nodeBodyMarkdown.d.ts +19 -0
  112. package/dist/types/model/nodeRunFailure.d.ts +13 -0
  113. package/dist/types/model/nodes/CatchStreamingChunksNode.d.ts +20 -0
  114. package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +50 -0
  115. package/dist/types/model/nodes/ClassifierQuestionNode.d.ts +60 -0
  116. package/dist/types/model/nodes/CodeNewNode.d.ts +6 -0
  117. package/dist/types/model/nodes/GetGlobalNode.d.ts +7 -0
  118. package/dist/types/model/nodes/ImageNode.d.ts +4 -0
  119. package/dist/types/model/nodes/LLMChatV2Node.d.ts +1 -0
  120. package/dist/types/model/nodes/MatchCaseNode.d.ts +8 -1
  121. package/dist/types/model/nodes/MatchCaseNodeBase.d.ts +13 -1
  122. package/dist/types/model/nodes/ObjectNode.d.ts +6 -0
  123. package/dist/types/model/nodes/StreamValueNode.d.ts +14 -0
  124. package/dist/types/model/nodes/SubGraphNode.d.ts +21 -2
  125. package/dist/types/model/nodes/ToBase64Node.d.ts +12 -0
  126. package/dist/types/model/nodes/codeOutputInference.d.ts +31 -0
  127. package/dist/types/recording/ExecutionRecorder.d.ts +8 -2
  128. package/dist/types/utils/base64.d.ts +1 -1
  129. package/dist/types/utils/errors.d.ts +4 -0
  130. package/dist/types/utils/interpolation.d.ts +13 -2
  131. package/dist/types/utils/interpolationSyntax.d.ts +1 -1
  132. package/dist/types/utils/serialization/serialization.d.ts +3 -1
  133. package/dist/types/utils/serialization/serializationUtils.d.ts +1 -0
  134. package/package.json +1 -1
@@ -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,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,97 @@
1
+ const legacyTypesafePluginId = 'typesafe';
2
+ function isLegacyTypesafePlugin(spec) {
3
+ return spec.type === 'built-in' && spec.id === legacyTypesafePluginId;
4
+ }
5
+ /**
6
+ * Converts the former TypeSafe plugin node family into the first-party
7
+ * classifier contract. It is intentionally idempotent because project data
8
+ * reaches Core through imports, hosted snapshots, recordings, and copies.
9
+ */
10
+ export function normalizeClassifierProject(project) {
11
+ for (const graph of Object.values(project.graphs))
12
+ normalizeClassifierGraph(graph);
13
+ for (const prefab of Object.values(project.nodePrefabs ?? {}))
14
+ normalizeClassifierNode(prefab.sourceNode);
15
+ if (project.plugins?.some(isLegacyTypesafePlugin)) {
16
+ project.plugins = project.plugins.filter((plugin) => !isLegacyTypesafePlugin(plugin));
17
+ }
18
+ }
19
+ /**
20
+ * Checks whether a project still needs the in-place legacy migration. Hosts
21
+ * which receive a caller-owned project object use this before cloning, so a
22
+ * compatibility repair never mutates the caller's snapshot.
23
+ */
24
+ export function hasLegacyClassifierProjectData(project) {
25
+ return (project.plugins?.some(isLegacyTypesafePlugin) === true ||
26
+ Object.values(project.graphs).some(hasLegacyClassifierGraphData) ||
27
+ Object.values(project.nodePrefabs ?? {}).some((prefab) => hasLegacyClassifierNodeData(prefab.sourceNode)));
28
+ }
29
+ export function normalizeClassifierGraph(graph) {
30
+ for (const node of graph.nodes)
31
+ normalizeClassifierNode(node);
32
+ }
33
+ export function hasLegacyClassifierGraphData(graph) {
34
+ return graph.nodes.some(hasLegacyClassifierNodeData);
35
+ }
36
+ export function normalizeClassifierNode(node) {
37
+ const legacyNode = node;
38
+ switch (legacyNode.type) {
39
+ case 'jevChoiceQuestion':
40
+ normalizeQuestionNode(legacyNode, 'choice', 'Jev Choice Question');
41
+ return;
42
+ case 'jevScoreQuestion':
43
+ normalizeQuestionNode(legacyNode, 'score', 'Jev Score Question');
44
+ return;
45
+ case 'jevNoulQuestion':
46
+ normalizeQuestionNode(legacyNode, 'noul', 'Jev Noul Question');
47
+ return;
48
+ case 'jevEvaluate':
49
+ normalizeEvaluateNode(legacyNode);
50
+ return;
51
+ case 'classifierEvaluate':
52
+ if (hasDeprecatedGlobalCredentialNames(legacyNode))
53
+ normalizeEvaluateNode(legacyNode);
54
+ return;
55
+ default:
56
+ return;
57
+ }
58
+ }
59
+ function hasLegacyClassifierNodeData(node) {
60
+ return (node.type === 'jevChoiceQuestion' ||
61
+ node.type === 'jevScoreQuestion' ||
62
+ node.type === 'jevNoulQuestion' ||
63
+ node.type === 'jevEvaluate' ||
64
+ (node.type === 'classifierEvaluate' && hasDeprecatedGlobalCredentialNames(node)));
65
+ }
66
+ function hasDeprecatedGlobalCredentialNames(node) {
67
+ return Object.prototype.hasOwnProperty.call(asRecord(node.data), 'apiKeyNames');
68
+ }
69
+ function normalizeQuestionNode(node, questionType, legacyTitle) {
70
+ node.type = 'classifierQuestion';
71
+ node.data = {
72
+ ...asRecord(node.data),
73
+ questionType,
74
+ };
75
+ if (node.title === legacyTitle)
76
+ node.title = 'Classifier Question';
77
+ }
78
+ function normalizeEvaluateNode(node) {
79
+ const legacyData = asRecord(node.data);
80
+ const legacyApiKeyNames = legacyData.apiKeyNames;
81
+ const existingNames = asRecord(legacyData.apiKeyNamesByProvider);
82
+ const apiKeyNamesByProvider = legacyApiKeyNames === undefined || Object.prototype.hasOwnProperty.call(existingNames, 'jev')
83
+ ? existingNames
84
+ : { ...existingNames, jev: legacyApiKeyNames };
85
+ const { apiKeyNames: _legacyApiKeyNames, ...dataWithoutLegacyNames } = legacyData;
86
+ node.type = 'classifierEvaluate';
87
+ node.data = {
88
+ ...dataWithoutLegacyNames,
89
+ provider: typeof legacyData.provider === 'string' && legacyData.provider ? legacyData.provider : 'jev',
90
+ ...(Object.keys(apiKeyNamesByProvider).length > 0 ? { apiKeyNamesByProvider } : {}),
91
+ };
92
+ if (node.title === 'Jev Evaluate')
93
+ node.title = 'Classifier Evaluate';
94
+ }
95
+ function asRecord(value) {
96
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
97
+ }
@@ -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
+ }