@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,292 @@
1
+ import { nanoid } from 'nanoid/non-secure';
2
+ import { parse } from 'acorn';
3
+ import { buildJsValueInterpolatedSource, getJsValueInterpolationRuntimeContext } from './jsValueInterpolation.js';
4
+ const cache = new Map();
5
+ const MAX_CACHED_SOURCES = 128;
6
+ const WRAPPER_PREFIX = 'async function __codeOutputs() {\n';
7
+ const TRAVERSAL_BOUNDARIES = new Set([
8
+ 'FunctionDeclaration',
9
+ 'FunctionExpression',
10
+ 'ArrowFunctionExpression',
11
+ 'ClassDeclaration',
12
+ 'ClassExpression',
13
+ ]);
14
+ function isAstNode(value) {
15
+ return value !== null && typeof value === 'object' && 'type' in value && typeof value.type === 'string';
16
+ }
17
+ function getPropertyKey(property) {
18
+ if (property.type !== 'Property') {
19
+ return undefined;
20
+ }
21
+ const objectProperty = property;
22
+ if (objectProperty.computed || objectProperty.method || objectProperty.kind !== 'init')
23
+ return undefined;
24
+ const key = objectProperty.key;
25
+ if (key.type === 'Identifier') {
26
+ return { key: key.name, start: key.start, end: key.end };
27
+ }
28
+ return key.type === 'Literal' && ['string', 'number'].includes(typeof key.value)
29
+ ? { key: String(key.value), start: key.start, end: key.end }
30
+ : undefined;
31
+ }
32
+ function analyzeCodeOutputSyntax(code) {
33
+ const cached = cache.get(code);
34
+ if (cached) {
35
+ return cached;
36
+ }
37
+ let result;
38
+ try {
39
+ const source = buildJsValueInterpolatedSource(code, getJsValueInterpolationRuntimeContext(code, '__codeOutputInputs'), { trim: false });
40
+ const tree = parse(`${WRAPPER_PREFIX}${source}\n}`, { ecmaVersion: 'latest' });
41
+ const keys = new Set();
42
+ const occurrences = [];
43
+ const visit = (node) => {
44
+ if (TRAVERSAL_BOUNDARIES.has(node.type))
45
+ return;
46
+ if (node.type === 'ReturnStatement') {
47
+ const argument = node.argument;
48
+ if (argument?.type === 'ObjectExpression') {
49
+ for (const property of argument.properties) {
50
+ const key = getPropertyKey(property);
51
+ if (key === undefined)
52
+ continue;
53
+ keys.add(key.key);
54
+ occurrences.push({
55
+ key: key.key,
56
+ start: key.start - WRAPPER_PREFIX.length,
57
+ end: key.end - WRAPPER_PREFIX.length,
58
+ });
59
+ }
60
+ }
61
+ return;
62
+ }
63
+ for (const value of Object.values(node)) {
64
+ if (Array.isArray(value)) {
65
+ for (const child of value)
66
+ if (isAstNode(child))
67
+ visit(child);
68
+ }
69
+ else if (isAstNode(value)) {
70
+ visit(value);
71
+ }
72
+ }
73
+ };
74
+ // Enter only the wrapper body; nested functions remain traversal boundaries.
75
+ visit(tree.body[0].body);
76
+ result = Object.freeze({
77
+ valid: true,
78
+ keys: Object.freeze([...keys]),
79
+ occurrences: Object.freeze(occurrences.map((occurrence) => Object.freeze(occurrence))),
80
+ source,
81
+ });
82
+ }
83
+ catch {
84
+ result = Object.freeze({ valid: false });
85
+ }
86
+ if (cache.size >= MAX_CACHED_SOURCES) {
87
+ cache.delete(cache.keys().next().value);
88
+ }
89
+ cache.set(code, result);
90
+ return result;
91
+ }
92
+ /** Syntax-only analysis of explicit object returns in the authored function. */
93
+ export function analyzeCodeOutputs(code) {
94
+ const analysis = analyzeCodeOutputSyntax(code);
95
+ return analysis.valid ? Object.freeze({ valid: true, keys: analysis.keys }) : Object.freeze({ valid: false });
96
+ }
97
+ function sanitizeOutputFields(fieldsToSanitize) {
98
+ const seenIds = new Set();
99
+ const seenKeys = new Set();
100
+ const fields = [];
101
+ for (const field of fieldsToSanitize ?? []) {
102
+ if (typeof field?.id !== 'string' ||
103
+ !field.id.startsWith('field:') ||
104
+ typeof field.key !== 'string' ||
105
+ seenIds.has(field.id) ||
106
+ seenKeys.has(field.key)) {
107
+ continue;
108
+ }
109
+ seenIds.add(field.id);
110
+ seenKeys.add(field.key);
111
+ fields.push({ id: field.id, key: field.key });
112
+ }
113
+ return fields;
114
+ }
115
+ function getStoredOutputFields(data) {
116
+ return sanitizeOutputFields(data.inferredOutputFields);
117
+ }
118
+ function getLegacyOutputFields(keys) {
119
+ return [...new Set(keys.filter((key) => typeof key === 'string'))].map((key) => ({
120
+ id: `field:${key}`,
121
+ key,
122
+ }));
123
+ }
124
+ /** Resolves the displayed fields and their stable port identities without mutating node data. */
125
+ export function getCodeOutputFields(data) {
126
+ const analysis = analyzeCodeOutputSyntax(data.code);
127
+ const storedFields = getStoredOutputFields(data);
128
+ if (!analysis.valid) {
129
+ return storedFields.length > 0 ? storedFields : getLegacyOutputFields(data.inferredOutputKeys ?? []);
130
+ }
131
+ const storedFieldByKey = new Map(storedFields.map((field) => [field.key, field]));
132
+ return analysis.keys.map((key) => storedFieldByKey.get(key) ?? { id: `field:${key}`, key });
133
+ }
134
+ export function getCodeOutputKeys(data) {
135
+ return getCodeOutputFields(data).map((field) => field.key);
136
+ }
137
+ function getSingleTextChange(previous, next) {
138
+ let prefixLength = 0;
139
+ const sharedLength = Math.min(previous.length, next.length);
140
+ while (prefixLength < sharedLength && previous[prefixLength] === next[prefixLength]) {
141
+ prefixLength += 1;
142
+ }
143
+ let previousEnd = previous.length;
144
+ let nextEnd = next.length;
145
+ while (previousEnd > prefixLength && nextEnd > prefixLength && previous[previousEnd - 1] === next[nextEnd - 1]) {
146
+ previousEnd -= 1;
147
+ nextEnd -= 1;
148
+ }
149
+ if (prefixLength === previousEnd && prefixLength === nextEnd) {
150
+ return undefined;
151
+ }
152
+ return {
153
+ previousStart: prefixLength,
154
+ previousEnd,
155
+ nextStart: prefixLength,
156
+ nextEnd,
157
+ };
158
+ }
159
+ function isChangeWithinOccurrence(start, end, occurrence) {
160
+ return start >= occurrence.start && end <= occurrence.end;
161
+ }
162
+ /**
163
+ * A rename is safe only when the complete source change is confined to one
164
+ * explicit property key on each side. This deliberately rejects broad edits.
165
+ */
166
+ function getProvenOutputRename(previous, next) {
167
+ if (!previous.valid || !next.valid) {
168
+ return undefined;
169
+ }
170
+ const previousKeys = new Set(previous.keys);
171
+ const nextKeys = new Set(next.keys);
172
+ const removedKeys = previous.keys.filter((key) => !nextKeys.has(key));
173
+ const addedKeys = next.keys.filter((key) => !previousKeys.has(key));
174
+ if (removedKeys.length !== 1 || addedKeys.length !== 1) {
175
+ return undefined;
176
+ }
177
+ const oldKey = removedKeys[0];
178
+ const newKey = addedKeys[0];
179
+ const previousOccurrences = previous.occurrences.filter((occurrence) => occurrence.key === oldKey);
180
+ const nextOccurrences = next.occurrences.filter((occurrence) => occurrence.key === newKey);
181
+ if (previousOccurrences.length !== 1 || nextOccurrences.length !== 1) {
182
+ return undefined;
183
+ }
184
+ const change = getSingleTextChange(previous.source, next.source);
185
+ if (!change) {
186
+ return undefined;
187
+ }
188
+ return isChangeWithinOccurrence(change.previousStart, change.previousEnd, previousOccurrences[0]) &&
189
+ isChangeWithinOccurrence(change.nextStart, change.nextEnd, nextOccurrences[0])
190
+ ? { oldKey, newKey }
191
+ : undefined;
192
+ }
193
+ function createOutputFieldId(usedIds) {
194
+ let id;
195
+ do {
196
+ id = `field:${nanoid()}`;
197
+ } while (usedIds.has(id));
198
+ return id;
199
+ }
200
+ function getPreviousOutputFields(data) {
201
+ const storedFields = getStoredOutputFields(data);
202
+ return storedFields.length > 0 ? storedFields : [...getCodeOutputFields(data)];
203
+ }
204
+ function getRetiredOutputFields(data, activeFields) {
205
+ const activeIds = new Set(activeFields.map((field) => field.id));
206
+ const activeKeys = new Set(activeFields.map((field) => field.key));
207
+ return sanitizeOutputFields(data.inferredOutputRetiredFields).filter((field) => !activeIds.has(field.id) && !activeKeys.has(field.key));
208
+ }
209
+ const MAX_RETIRED_OUTPUT_FIELDS = 32;
210
+ function reconcileOutputFields(previous, nextAnalysis) {
211
+ const previousFields = getPreviousOutputFields(previous);
212
+ const previousFieldByKey = new Map(previousFields.map((field) => [field.key, field]));
213
+ const retiredFields = getRetiredOutputFields(previous, previousFields);
214
+ const retiredFieldByKey = new Map(retiredFields.map((field) => [field.key, field]));
215
+ const sourceForRename = previous.inferredOutputLastValidCode ?? previous.code;
216
+ const rename = getProvenOutputRename(analyzeCodeOutputSyntax(sourceForRename), nextAnalysis);
217
+ const usedIds = new Set([...previousFields, ...retiredFields].map((field) => field.id));
218
+ const fields = [];
219
+ const reusedRetiredKeys = new Set();
220
+ const renamedKeys = new Set();
221
+ for (const key of nextAnalysis.keys) {
222
+ const exactField = previousFieldByKey.get(key);
223
+ if (exactField) {
224
+ fields.push({ ...exactField });
225
+ continue;
226
+ }
227
+ const retiredField = retiredFieldByKey.get(key);
228
+ if (retiredField) {
229
+ fields.push({ ...retiredField });
230
+ reusedRetiredKeys.add(key);
231
+ continue;
232
+ }
233
+ const renamedField = rename?.newKey === key ? previousFieldByKey.get(rename.oldKey) : undefined;
234
+ if (renamedField && rename && !previousFieldByKey.has(key)) {
235
+ fields.push({ id: renamedField.id, key });
236
+ renamedKeys.add(rename.oldKey);
237
+ continue;
238
+ }
239
+ const id = createOutputFieldId(usedIds);
240
+ usedIds.add(id);
241
+ fields.push({ id, key });
242
+ }
243
+ const fieldKeys = new Set(fields.map((field) => field.key));
244
+ const fieldIds = new Set(fields.map((field) => field.id));
245
+ const newlyRetiredFields = previousFields.filter((field) => !fieldKeys.has(field.key) && !renamedKeys.has(field.key));
246
+ const nextRetiredFields = [
247
+ ...retiredFields.filter((field) => !reusedRetiredKeys.has(field.key)),
248
+ ...newlyRetiredFields,
249
+ ]
250
+ .filter((field, index, all) => !fieldIds.has(field.id) && all.findIndex((candidate) => candidate.id === field.id) === index)
251
+ .slice(-MAX_RETIRED_OUTPUT_FIELDS);
252
+ return {
253
+ inferredOutputFields: fields,
254
+ inferredOutputRetiredFields: nextRetiredFields,
255
+ };
256
+ }
257
+ function getLastValidCode(data) {
258
+ return analyzeCodeOutputSyntax(data.code).valid ? data.code : data.inferredOutputLastValidCode;
259
+ }
260
+ function withoutOutputMetadata(data) {
261
+ const { inferredOutputFields: _discardedFields, inferredOutputKeys: _discardedKeys, inferredOutputRetiredFields: _discardedRetiredFields, inferredOutputLastValidCode: _discardedLastValidCode, ...dataWithoutOutputMetadata } = data;
262
+ return dataWithoutOutputMetadata;
263
+ }
264
+ /**
265
+ * Prepares persisted output identities as part of an editor transaction.
266
+ * Valid source owns the visible fields. Invalid source retains the last valid
267
+ * identities and source so a completed key-only rename can still be proved.
268
+ */
269
+ export function prepareCodeOutputEdit(previous, patch) {
270
+ const next = { ...previous, ...patch };
271
+ const analysis = analyzeCodeOutputSyntax(next.code);
272
+ const nextWithoutOutputMetadata = withoutOutputMetadata(next);
273
+ if (analysis.valid) {
274
+ const { inferredOutputFields, inferredOutputRetiredFields } = reconcileOutputFields(previous, analysis);
275
+ return {
276
+ ...nextWithoutOutputMetadata,
277
+ inferredOutputFields,
278
+ inferredOutputKeys: inferredOutputFields.map((field) => field.key),
279
+ ...(inferredOutputRetiredFields.length > 0 ? { inferredOutputRetiredFields } : {}),
280
+ };
281
+ }
282
+ const inferredOutputFields = getPreviousOutputFields(previous);
283
+ const inferredOutputRetiredFields = getRetiredOutputFields(previous, inferredOutputFields);
284
+ const lastValidCode = getLastValidCode(previous);
285
+ return {
286
+ ...nextWithoutOutputMetadata,
287
+ inferredOutputFields,
288
+ inferredOutputKeys: inferredOutputFields.map((field) => field.key),
289
+ ...(inferredOutputRetiredFields.length > 0 ? { inferredOutputRetiredFields } : {}),
290
+ ...(lastValidCode ? { inferredOutputLastValidCode: lastValidCode } : {}),
291
+ };
292
+ }
@@ -295,6 +295,9 @@ export class ExecutionRecorder {
295
295
  if (this.#includeTrace === false && message === 'trace') {
296
296
  return;
297
297
  }
298
+ if (getEventProjectScope(data) !== undefined) {
299
+ return;
300
+ }
298
301
  this.#events.push(toRecordedEvent(message, data));
299
302
  if (isSocketRecordingTerminalEvent(message)) {
300
303
  finish(true);
@@ -314,6 +317,7 @@ export class ExecutionRecorder {
314
317
  }
315
318
  record(processor) {
316
319
  this.recordingId = nanoid();
320
+ const recordingProjectScope = processor.recordingProjectScope;
317
321
  let settled = false;
318
322
  const finish = () => {
319
323
  if (settled)
@@ -335,9 +339,25 @@ export class ExecutionRecorder {
335
339
  if (this.#includeTrace === false && event === 'trace') {
336
340
  return;
337
341
  }
342
+ const eventScope = getEventProjectScope(data);
343
+ if (eventScope !== undefined && eventScope !== recordingProjectScope) {
344
+ return;
345
+ }
338
346
  this.#events.push(toRecordedEvent(event, data));
339
347
  });
340
348
  const unsubscribeFinish = processor.on('finish', finish);
349
+ // Child processors have graph terminals but no root-level done/finish.
350
+ // Their owner calls this after processGraph settles to make a standalone,
351
+ // replayable recording without changing the live event stream.
352
+ return (terminal) => {
353
+ if (settled)
354
+ return;
355
+ if (terminal?.type === 'done')
356
+ this.#events.push(toRecordedEvent('done', { results: terminal.results }));
357
+ if (terminal?.type === 'error')
358
+ this.#events.push(toRecordedEvent('error', { error: terminal.error }));
359
+ finish();
360
+ };
341
361
  }
342
362
  getRecording() {
343
363
  return {
@@ -382,3 +402,9 @@ export class ExecutionRecorder {
382
402
  function isSocketRecordingTerminalEvent(event) {
383
403
  return event === 'done' || event === 'error';
384
404
  }
405
+ function getEventProjectScope(data) {
406
+ if (!data || typeof data !== 'object' || !('execution' in data))
407
+ return undefined;
408
+ const execution = data.execution;
409
+ return execution?.projectScope;
410
+ }
@@ -1,31 +1,34 @@
1
+ function encodeWithBtoa(bytes) {
2
+ const chunks = [];
3
+ // Every non-final chunk must contain a multiple of three bytes so its padding
4
+ // cannot interrupt the combined base64 stream.
5
+ for (let offset = 0; offset < bytes.length; offset += 0x6000) {
6
+ chunks.push(btoa(String.fromCharCode(...bytes.subarray(offset, offset + 0x6000))));
7
+ }
8
+ return chunks.join('');
9
+ }
1
10
  export async function uint8ArrayToBase64(uint8Array) {
2
- if (typeof window === 'undefined') {
3
- // Node executor
11
+ if (typeof Buffer !== 'undefined') {
4
12
  return Buffer.from(uint8Array).toString('base64');
5
13
  }
6
- else {
7
- // Browser executor
14
+ if (typeof FileReader !== 'undefined') {
8
15
  const blob = new Blob([uint8Array], { type: 'application/octet-stream' });
9
- const dataUrl = await new Promise((resolve) => {
16
+ const dataUrl = await new Promise((resolve, reject) => {
10
17
  const reader = new FileReader();
11
18
  reader.onload = () => resolve(reader.result);
19
+ reader.onerror = () => reject(reader.error ?? new Error('Failed to encode bytes as base64'));
12
20
  reader.readAsDataURL(blob);
13
21
  });
14
- return dataUrl.split(',')[1];
22
+ return dataUrl.slice(dataUrl.indexOf(',') + 1);
15
23
  }
24
+ // Browser workers have btoa but neither window nor FileReader.
25
+ return encodeWithBtoa(uint8Array);
16
26
  }
17
27
  export function uint8ArrayToBase64Sync(uint8Array) {
18
- if (typeof window === 'undefined') {
19
- // Node executor
28
+ if (typeof Buffer !== 'undefined') {
20
29
  return Buffer.from(uint8Array).toString('base64');
21
30
  }
22
- else {
23
- // Browser executor
24
- const binary = Array.from(uint8Array)
25
- .map((byte) => String.fromCharCode(byte))
26
- .join('');
27
- return btoa(binary);
28
- }
31
+ return encodeWithBtoa(uint8Array);
29
32
  }
30
33
  export function base64ToUint8Array(base64) {
31
34
  const binaryString = atob(base64);
@@ -5,3 +5,44 @@ export function getError(error) {
5
5
  : new Error(error != null ? error.toString() : 'Unknown error');
6
6
  return errorInstance;
7
7
  }
8
+ /** Full failure text for graph error outputs, including nested causes. */
9
+ export function formatCaughtRunError(error, seen = new Set()) {
10
+ try {
11
+ if (error && typeof error === 'object') {
12
+ if (seen.has(error))
13
+ return '[Circular error reference]';
14
+ seen.add(error);
15
+ }
16
+ const errorLike = error != null && typeof error === 'object' ? error : undefined;
17
+ // Error identity is realm-local; iframe/provider errors still have the
18
+ // standard name/message/stack shape, usually with non-enumerable fields.
19
+ if (errorLike &&
20
+ (error instanceof Error || (typeof errorLike.name === 'string' && typeof errorLike.message === 'string'))) {
21
+ const text = (typeof errorLike.stack === 'string' && errorLike.stack.trim()) ||
22
+ `${errorLike.name}: ${errorLike.message}`.trim();
23
+ return errorLike.cause == null ? text : `${text}\n\nCaused by: ${formatCaughtRunError(errorLike.cause, seen)}`;
24
+ }
25
+ return typeof error === 'object' && error != null ? JSON.stringify(error, null, 2) ?? String(error) : String(error);
26
+ }
27
+ catch {
28
+ // Arbitrary thrown values can have no prototype, cycles or throwing getters.
29
+ // Formatting their error output must never become a second graph failure.
30
+ try {
31
+ return String(error);
32
+ }
33
+ catch {
34
+ return '[Unprintable thrown value]';
35
+ }
36
+ }
37
+ }
38
+ /** Caller cancellation wins over provider failure, including cross-realm errors. */
39
+ export function isAbortError(error, signal) {
40
+ if (signal.aborted)
41
+ return true;
42
+ try {
43
+ return error != null && typeof error === 'object' && error.name === 'AbortError';
44
+ }
45
+ catch {
46
+ return false;
47
+ }
48
+ }
@@ -327,8 +327,9 @@ export function parseInterpolationToken(rawInner) {
327
327
  function freezeReference(reference) {
328
328
  return reference ? Object.freeze({ ...reference }) : undefined;
329
329
  }
330
- function parseInterpolationTemplateUncached(template) {
331
- const tokens = scanInterpolationTokenSpans(template).map((span) => {
330
+ function parseInterpolationTemplateUncached(template, check, tokenLimit = Infinity) {
331
+ const tokens = scanInterpolationTokenSpans(template, check, tokenLimit).map((span) => {
332
+ check?.();
332
333
  const parsedToken = parseInterpolationToken(span.rawInner);
333
334
  return Object.freeze({
334
335
  ...parsedToken,
@@ -373,12 +374,15 @@ function cacheInterpolationTemplate(template, parsed) {
373
374
  cachedInterpolationTemplateStorageChars += storageChars;
374
375
  }
375
376
  /** Returns an immutable, cached syntax representation. It never evaluates values. */
376
- export function parseInterpolationTemplate(template) {
377
+ export function parseInterpolationTemplate(template, check, tokenLimit = Infinity) {
378
+ check?.();
377
379
  const cached = interpolationTemplateCache.get(template);
378
380
  if (cached) {
381
+ if (cached.parsed.tokens.length > tokenLimit)
382
+ throw new Error('Interpolation template has too many tokens.');
379
383
  return cached.parsed;
380
384
  }
381
- const parsed = parseInterpolationTemplateUncached(template);
385
+ const parsed = parseInterpolationTemplateUncached(template, check, tokenLimit);
382
386
  if (template.includes('{{')) {
383
387
  cacheInterpolationTemplate(template, parsed);
384
388
  }
@@ -403,28 +407,33 @@ export function getInterpolationTokenReference(rawInner) {
403
407
  return parseInterpolationToken(rawInner).reference;
404
408
  }
405
409
  export function replaceInterpolationTokens(template, getReplacement, options = {}) {
406
- const parsedTemplate = parseInterpolationTemplate(template);
410
+ const parsedTemplate = parseInterpolationTemplate(template, options.guard?.check, options.guard?.tokenLimit);
407
411
  if (parsedTemplate.tokens.length === 0) {
408
412
  const restoredTemplate = restoreEscapedInterpolationTokens(template);
409
413
  return options.trim ? restoredTemplate.trim() : restoredTemplate;
410
414
  }
411
415
  let result = '';
412
416
  let cursor = 0;
417
+ const append = (fragment) => {
418
+ options.guard?.output(fragment, result.length);
419
+ result += fragment;
420
+ };
413
421
  for (const token of parsedTemplate.tokens) {
414
422
  // Restore escaped delimiters only from authored template text. A
415
423
  // replacement may deliberately contain `{{{...}}}` or `\\{\\{...\\}\\}` and
416
424
  // must be returned unchanged rather than interpreted as template syntax.
417
- result += restoreEscapedInterpolationTokens(template.slice(cursor, token.span.start));
418
- result += getReplacement({
425
+ options.guard?.check();
426
+ append(restoreEscapedInterpolationTokens(template.slice(cursor, token.span.start)));
427
+ append(getReplacement({
419
428
  rawInner: token.rawInner,
420
429
  span: { ...token.span },
421
430
  tokenName: token.tokenName,
422
431
  processingChain: token.processingChain,
423
432
  reference: token.reference ? { ...token.reference } : undefined,
424
- });
433
+ }));
425
434
  cursor = token.span.end;
426
435
  }
427
- result += restoreEscapedInterpolationTokens(template.slice(cursor));
436
+ append(restoreEscapedInterpolationTokens(template.slice(cursor)));
428
437
  return options.trim ? result.trim() : result;
429
438
  }
430
439
  /**
@@ -458,14 +467,17 @@ export function extractInterpolationVariableReferences(template) {
458
467
  * are intentionally snapshotted at node execution: interpolation neither
459
468
  * waits for a writer nor creates an execution dependency.
460
469
  */
461
- export function getInterpolationGlobalValues(template, getGlobal) {
470
+ export function getInterpolationGlobalValues(template, getGlobal, check, tokenLimit = Infinity) {
462
471
  const values = Object.create(null);
463
472
  if (!getGlobal || !template.includes('{{')) {
464
473
  return values;
465
474
  }
466
- for (const token of parseInterpolationTemplate(template).tokens) {
475
+ for (const token of parseInterpolationTemplate(template, check, tokenLimit).tokens) {
476
+ check?.();
467
477
  const reference = token.reference;
468
- if (!reference || reference.source !== 'globals' || Object.prototype.hasOwnProperty.call(values, reference.baseName)) {
478
+ if (!reference ||
479
+ reference.source !== 'globals' ||
480
+ Object.prototype.hasOwnProperty.call(values, reference.baseName)) {
469
481
  continue;
470
482
  }
471
483
  const value = getGlobal(reference.baseName);
@@ -511,18 +523,22 @@ export function resolveInterpolationExpressionRawValue(expression, sources) {
511
523
  return undefined;
512
524
  }
513
525
  const shouldUnwrapDataValue = reference.source !== 'variable' || sources.unwrapVariableDataValues !== false;
514
- const baseValue = shouldUnwrapDataValue
515
- ? unwrapPotentialDataValue(source[reference.baseName])
516
- : source[reference.baseName];
526
+ const property = sources.guard ? Object.getOwnPropertyDescriptor(source, reference.baseName) : undefined;
527
+ if (sources.guard && (!property || !('value' in property)))
528
+ throw new Error('Interpolation sources must use own data properties, not accessors.');
529
+ const sourceValue = sources.guard ? sources.guard.prepareValue(property.value) : source[reference.baseName];
530
+ const baseValue = shouldUnwrapDataValue ? unwrapPotentialDataValue(sourceValue) : sourceValue;
517
531
  if (reference.jsonPath === undefined) {
518
532
  return baseValue;
519
533
  }
534
+ let selected;
520
535
  try {
521
- return evaluateJsonPath(baseValue, reference.jsonPath, false);
536
+ selected = evaluateJsonPath(baseValue, reference.jsonPath, false);
522
537
  }
523
538
  catch {
524
539
  return undefined;
525
540
  }
541
+ return sources.guard ? sources.guard.prepareValue(selected) : selected;
526
542
  }
527
543
  export function resolveInterpolationTokenRawValue(rawInner, sources) {
528
544
  const reference = parseInterpolationToken(rawInner).reference;
@@ -559,19 +575,23 @@ function parseProcessing(instruction) {
559
575
  param: parts[1] ? Number.parseInt(parts[1], 10) : undefined,
560
576
  };
561
577
  }
562
- function applyProcessing(value, processingChain) {
578
+ function applyProcessing(value, processingChain, guard) {
579
+ guard?.processing(processingChain, 'chain', undefined);
563
580
  const instructions = processingChain
564
581
  .split('|')
565
582
  .map((instruction) => instruction.trim())
566
583
  .filter((instruction) => instruction !== '');
567
584
  return instructions.reduce((result, instruction) => {
568
585
  const { func, param } = parseProcessing(instruction);
586
+ guard?.processing(result, func, param);
569
587
  const processingFunc = processingFunctions[func];
570
588
  if (!processingFunc) {
571
589
  console.warn(`Unknown processing function: ${func}`);
572
590
  return result;
573
591
  }
574
- return processingFunc(result, param);
592
+ const processed = processingFunc(result, param);
593
+ guard?.output(processed, 0);
594
+ return processed;
575
595
  }, value);
576
596
  }
577
597
  /**
@@ -590,6 +610,7 @@ export function interpolate(template, variables, graphInputValues, contextValues
590
610
  contextValues,
591
611
  globalValues: options.globalValues,
592
612
  unwrapVariableDataValues: options.unwrapVariableDataValues,
613
+ guard: options.guard,
593
614
  });
594
615
  if (resolvedValue === undefined) {
595
616
  console.warn(`Interpolation variable or path "${token.tokenName}" not found or resolved to undefined.`);
@@ -597,13 +618,14 @@ export function interpolate(template, variables, graphInputValues, contextValues
597
618
  }
598
619
  const isBareOrdinaryVariable = token.reference.source === 'variable' && token.reference.jsonPath === undefined;
599
620
  const stringValue = isBareOrdinaryVariable
600
- ? stringifyInterpolationSourceValue(variables[token.reference.baseName], {
621
+ ? stringifyInterpolationSourceValue(options.guard ? resolvedValue : variables[token.reference.baseName], {
601
622
  coerceDataValueToString: options.coerceBareVariableDataValues,
602
- unwrapDataValue: options.unwrapVariableDataValues !== false,
623
+ unwrapDataValue: !options.guard && options.unwrapVariableDataValues !== false,
603
624
  })
604
625
  : stringifyInterpolationValue(resolvedValue);
605
- return token.processingChain ? applyProcessing(stringValue, token.processingChain) : stringValue;
606
- });
626
+ options.guard?.output(stringValue, 0);
627
+ return token.processingChain ? applyProcessing(stringValue, token.processingChain, options.guard) : stringValue;
628
+ }, { guard: options.guard });
607
629
  }
608
630
  /** Runtime helper injected into JavaScript runners without exposing the whole Rivet API. */
609
631
  export function resolveCodeInterpolationExpression(inputs, expression, graphInputValues, contextValues, globalValues) {