@valerypopoff/rivet2-core 2.6.0 → 2.7.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 (70) hide show
  1. package/dist/cjs/bundle.cjs +2735 -767
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/interpolationRuntime.cjs +7 -3
  4. package/dist/cjs/interpolationRuntime.cjs.map +2 -2
  5. package/dist/esm/api/createProcessor.js +3 -0
  6. package/dist/esm/exports.js +2 -1
  7. package/dist/esm/integrations/CodeRunner.js +6 -2
  8. package/dist/esm/integrations/mcp/MCPBase.js +2 -1
  9. package/dist/esm/model/ExecutionOutputClone.js +46 -0
  10. package/dist/esm/model/GlobalVariables.js +452 -0
  11. package/dist/esm/model/GraphBoundaryEffects.js +12 -4
  12. package/dist/esm/model/GraphProcessor.js +825 -41
  13. package/dist/esm/model/Nodes.js +6 -0
  14. package/dist/esm/model/ProcessContextBuilder.js +3 -1
  15. package/dist/esm/model/ProjectReferenceLoader.js +36 -1
  16. package/dist/esm/model/RecordingPlayer.js +21 -4
  17. package/dist/esm/model/StreamingOutputWatch.js +262 -0
  18. package/dist/esm/model/StreamingOutputWatchHistory.js +161 -0
  19. package/dist/esm/model/SubprocessorBridge.js +29 -19
  20. package/dist/esm/model/chat-v2/llmChatV2OutputClone.js +3 -42
  21. package/dist/esm/model/nodes/CodeNewNode.js +4 -1
  22. package/dist/esm/model/nodes/ExpressionNode.js +4 -1
  23. package/dist/esm/model/nodes/ExtractObjectPathNode.js +4 -4
  24. package/dist/esm/model/nodes/GraphOutputNode.js +13 -8
  25. package/dist/esm/model/nodes/MCPGetPromptNode.js +2 -1
  26. package/dist/esm/model/nodes/MCPToolCallNode.js +2 -1
  27. package/dist/esm/model/nodes/ObjectNode.js +5 -3
  28. package/dist/esm/model/nodes/PromptNode.js +5 -2
  29. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +9 -1
  30. package/dist/esm/model/nodes/StopWatchingStreamingOutputNode.js +48 -0
  31. package/dist/esm/model/nodes/SubGraphNode.js +11 -1
  32. package/dist/esm/model/nodes/TextNode.js +5 -2
  33. package/dist/esm/model/nodes/ToTreeNode.js +10 -3
  34. package/dist/esm/model/nodes/ToolNode.js +5 -2
  35. package/dist/esm/model/nodes/WatchStreamingOutputNode.js +126 -0
  36. package/dist/esm/model/nodes/jsListCallbackHelpers.js +7 -1
  37. package/dist/esm/model/nodes/jsValueInterpolation.js +21 -4
  38. package/dist/esm/plugins/openai/nodes/ThreadMessageNode.js +2 -1
  39. package/dist/esm/recording/ExecutionRecorder.js +16 -7
  40. package/dist/esm/utils/interpolation.js +35 -2
  41. package/dist/esm/utils/serialization/serializationUtils.js +9 -0
  42. package/dist/esm/utils/serialization/serialization_v4.js +7 -0
  43. package/dist/types/exports.d.ts +2 -1
  44. package/dist/types/integrations/CodeRunner.d.ts +3 -3
  45. package/dist/types/integrations/CodeRunnerOptions.d.ts +5 -0
  46. package/dist/types/integrations/mcp/MCPBase.d.ts +1 -1
  47. package/dist/types/model/ExecutionOutputClone.d.ts +11 -0
  48. package/dist/types/model/ExecutorProtocol.d.ts +8 -2
  49. package/dist/types/model/GlobalVariables.d.ts +29 -0
  50. package/dist/types/model/GraphBoundaryEffects.d.ts +7 -1
  51. package/dist/types/model/GraphProcessor.d.ts +47 -3
  52. package/dist/types/model/Nodes.d.ts +4 -2
  53. package/dist/types/model/ProcessContext.d.ts +14 -0
  54. package/dist/types/model/ProcessContextBuilder.d.ts +3 -1
  55. package/dist/types/model/Project.d.ts +7 -1
  56. package/dist/types/model/ProjectReferenceLoader.d.ts +15 -1
  57. package/dist/types/model/StreamingOutputWatch.d.ts +74 -0
  58. package/dist/types/model/StreamingOutputWatchHistory.d.ts +58 -0
  59. package/dist/types/model/SubprocessorBridge.d.ts +2 -0
  60. package/dist/types/model/chat-v2/llmChatV2OutputClone.d.ts +3 -3
  61. package/dist/types/model/nodes/ExtractObjectPathNode.d.ts +1 -1
  62. package/dist/types/model/nodes/GraphOutputNode.d.ts +8 -1
  63. package/dist/types/model/nodes/ObjectNode.d.ts +1 -1
  64. package/dist/types/model/nodes/StopWatchingStreamingOutputNode.d.ts +14 -0
  65. package/dist/types/model/nodes/ToTreeNode.d.ts +5 -1
  66. package/dist/types/model/nodes/WatchStreamingOutputNode.d.ts +17 -0
  67. package/dist/types/model/nodes/jsValueInterpolation.d.ts +10 -1
  68. package/dist/types/recording/RecordedEvents.d.ts +7 -0
  69. package/dist/types/utils/interpolation.d.ts +14 -5
  70. package/package.json +1 -1
@@ -77,6 +77,9 @@ export function coreCreateProcessor(project, options, internalOptions = {}) {
77
77
  if (options.onNodeOutputsCleared) {
78
78
  processor.on('nodeOutputsCleared', options.onNodeOutputsCleared);
79
79
  }
80
+ if (options.onStreamingOutputWatchSummary) {
81
+ processor.on('streamingOutputWatchSummary', options.onStreamingOutputWatchSummary);
82
+ }
80
83
  if (options.externalFunctions) {
81
84
  for (const [name, fn] of Object.entries(options.externalFunctions)) {
82
85
  processor.setExternalFunction(name, fn);
@@ -24,6 +24,7 @@ export * from './model/NodeImpl.js';
24
24
  export * from './model/NodeDefinition.js';
25
25
  export * from './model/Nodes.js';
26
26
  export * from './model/Project.js';
27
+ export * from './model/GlobalVariables.js';
27
28
  export * from './native/BaseDir.js';
28
29
  export * from './native/NativeApi.js';
29
30
  export * from './native/BrowserNativeApi.js';
@@ -66,7 +67,7 @@ export * from './integrations/Tokenizer.js';
66
67
  export * from './integrations/GptTokenizerTokenizer.js';
67
68
  export { JS_LIST_CALLBACK_LOCAL_NAMES, interpolateJSListCallbackBody } from './model/nodes/jsListCallbackHelpers.js';
68
69
  export { findAutoDelegateGraphCandidate } from './model/nodes/toolCallDelegation.js';
69
- export { extractInterpolationVariables, extractInterpolationVariableReferences, findInterpolationTokenSpans, getInterpolationTokenReference, getInterpolationTokenName, interpolate, parseInterpolationExpression, parseInterpolationTemplate, protectEscapedInterpolationTokens, resolveCodeInterpolationExpression, resolveInterpolationExpressionRawValue, resolveInterpolationTokenRawValue, restoreEscapedInterpolationTokens, stringifyInterpolationSourceValue, } from './utils/interpolation.js';
70
+ export { extractInterpolationVariables, extractInterpolationVariableReferences, findInterpolationTokenSpans, getInterpolationGlobalValues, getInterpolationTokenReference, getInterpolationTokenName, interpolate, parseInterpolationExpression, parseInterpolationTemplate, protectEscapedInterpolationTokens, resolveCodeInterpolationExpression, resolveInterpolationExpressionRawValue, resolveInterpolationTokenRawValue, restoreEscapedInterpolationTokens, stringifyInterpolationSourceValue, } from './utils/interpolation.js';
70
71
  export { scanInterpolationTokenSpans } from './utils/interpolationSyntax.js';
71
72
  export { WarningsPort } from './utils/symbols.js';
72
73
  import * as openai from './utils/openai.js';
@@ -3,7 +3,7 @@ import { resolveCodeInterpolationExpression } from '../utils/interpolation.js';
3
3
  import * as Rivet from '../exports.js';
4
4
  export { ALL_CODE_RUNNER_OPTIONS } from './CodeRunnerOptions.js';
5
5
  export class IsomorphicCodeRunner {
6
- async runCode(code, inputs, options, graphInputs, contextValues) {
6
+ async runCode(code, inputs, options, graphInputs, contextValues, globalValues) {
7
7
  const argNames = ['inputs'];
8
8
  const args = [inputs];
9
9
  if (options.includeConsole) {
@@ -30,6 +30,10 @@ export class IsomorphicCodeRunner {
30
30
  argNames.push(options.interpolationHelperIdentifier);
31
31
  args.push(resolveCodeInterpolationExpression);
32
32
  }
33
+ if (options.globalValuesIdentifier) {
34
+ argNames.push(options.globalValuesIdentifier);
35
+ args.push(globalValues ?? Object.create(null));
36
+ }
33
37
  argNames.push(code);
34
38
  const AsyncFunction = async function () { }.constructor;
35
39
  const codeFunction = new AsyncFunction(...argNames);
@@ -38,7 +42,7 @@ export class IsomorphicCodeRunner {
38
42
  }
39
43
  }
40
44
  export class NotAllowedCodeRunner {
41
- async runCode(_code, _inputs, _options, _graphInputs, _contextValues) {
45
+ async runCode(_code, _inputs, _options, _graphInputs, _contextValues, _globalValues) {
42
46
  throw new Error('Dynamic code execution is disabled.');
43
47
  }
44
48
  }
@@ -134,7 +134,7 @@ export async function resolveMCPServer(data, inputs, context) {
134
134
  }
135
135
  return undefined;
136
136
  }
137
- export function interpolateMCPArgumentTemplate(template, inputs, graphInputValues, contextValues) {
137
+ export function interpolateMCPArgumentTemplate(template, inputs, graphInputValues, contextValues, globalValues) {
138
138
  const values = {};
139
139
  for (const key of keys(inputs)) {
140
140
  if (key.startsWith('input-')) {
@@ -143,6 +143,7 @@ export function interpolateMCPArgumentTemplate(template, inputs, graphInputValue
143
143
  }
144
144
  return interpolate(template, values, graphInputValues, contextValues, {
145
145
  coerceBareVariableDataValues: true,
146
+ globalValues,
146
147
  });
147
148
  }
148
149
  export function getMCPArgumentTemplateInputs(template) {
@@ -0,0 +1,46 @@
1
+ function cloneOutputValue(value, seen = new WeakMap()) {
2
+ if (value == null || typeof value !== 'object') {
3
+ return value;
4
+ }
5
+ if (value instanceof Uint8Array) {
6
+ return new Uint8Array(value);
7
+ }
8
+ const existing = seen.get(value);
9
+ if (existing != null) {
10
+ return existing;
11
+ }
12
+ if (Array.isArray(value)) {
13
+ const clone = [];
14
+ seen.set(value, clone);
15
+ clone.push(...value.map((item) => cloneOutputValue(item, seen)));
16
+ return clone;
17
+ }
18
+ const clone = {};
19
+ seen.set(value, clone);
20
+ for (const [key, item] of Object.entries(value)) {
21
+ clone[key] = cloneOutputValue(item, seen);
22
+ }
23
+ return clone;
24
+ }
25
+ /**
26
+ * Creates a cycle-safe copy at an execution-data ownership boundary.
27
+ *
28
+ * Providers may continue mutating output objects after a partial event. A
29
+ * snapshot, recorder, or deferred branch must therefore never retain the
30
+ * producer-owned reference.
31
+ */
32
+ export function cloneExecutionValue(value) {
33
+ if (typeof structuredClone === 'function') {
34
+ try {
35
+ return structuredClone(value);
36
+ }
37
+ catch {
38
+ // Fall through for values structuredClone cannot copy.
39
+ }
40
+ }
41
+ return cloneOutputValue(value);
42
+ }
43
+ /** Creates a cycle-safe snapshot specifically for a node output map. */
44
+ export function cloneExecutionOutputs(outputs) {
45
+ return cloneExecutionValue(outputs);
46
+ }
@@ -0,0 +1,452 @@
1
+ import { scalarTypes } from './DataValue.js';
2
+ import { base64ToUint8Array, uint8ArrayToBase64Sync } from '../utils/base64.js';
3
+ const literalMarkerKey = '$rivetProjectGlobalLiteral';
4
+ const literalMarkerObject = 'object';
5
+ const projectGlobalVariableScalarTypes = new Set(scalarTypes.filter((type) => type !== 'control-flow-excluded'));
6
+ function isPlainRecord(value) {
7
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
8
+ return false;
9
+ const prototype = Object.getPrototypeOf(value);
10
+ return prototype === Object.prototype || prototype === null;
11
+ }
12
+ function isProjectGlobalVariableDataType(value) {
13
+ if (typeof value !== 'string')
14
+ return false;
15
+ const scalarType = value.endsWith('[]') ? value.slice(0, -2) : value;
16
+ return projectGlobalVariableScalarTypes.has(scalarType);
17
+ }
18
+ function isSparseArray(value) {
19
+ for (let index = 0; index < value.length; index++) {
20
+ if (!Object.hasOwn(value, index))
21
+ return true;
22
+ }
23
+ return false;
24
+ }
25
+ function marker(kind, value) {
26
+ return value === undefined ? { [literalMarkerKey]: kind } : { [literalMarkerKey]: kind, value };
27
+ }
28
+ function encodeLiteral(value, seen) {
29
+ if (value === undefined)
30
+ return marker('undefined');
31
+ if (value === null || typeof value === 'boolean' || typeof value === 'string')
32
+ return value;
33
+ if (typeof value === 'number') {
34
+ if (Number.isNaN(value))
35
+ return marker('number', 'nan');
36
+ if (value === Infinity)
37
+ return marker('number', 'infinity');
38
+ if (value === -Infinity)
39
+ return marker('number', '-infinity');
40
+ return value;
41
+ }
42
+ if (value instanceof Uint8Array) {
43
+ return marker('uint8array', uint8ArrayToBase64Sync(value));
44
+ }
45
+ if (typeof value !== 'object' || value === null) {
46
+ throw new Error(`cannot persist ${typeof value} values`);
47
+ }
48
+ if (seen.has(value))
49
+ throw new Error('cannot persist circular values');
50
+ seen.add(value);
51
+ try {
52
+ if (Array.isArray(value)) {
53
+ if (isSparseArray(value))
54
+ throw new Error('cannot persist sparse arrays');
55
+ return value.map((item) => encodeLiteral(item, seen));
56
+ }
57
+ if (!isPlainRecord(value))
58
+ throw new Error('can only persist plain objects and Uint8Array values');
59
+ const entries = Object.entries(value).map(([key, item]) => [key, encodeLiteral(item, seen)]);
60
+ if (Object.hasOwn(value, literalMarkerKey)) {
61
+ return marker(literalMarkerObject, entries.map(([key, item]) => [key, item]));
62
+ }
63
+ return Object.fromEntries(entries);
64
+ }
65
+ finally {
66
+ seen.delete(value);
67
+ }
68
+ }
69
+ function literalError(label, message) {
70
+ return new Error(`${label}: ${message}`);
71
+ }
72
+ function decodeLiteral(value, label, seen = new Set()) {
73
+ if (value === null || typeof value === 'boolean' || typeof value === 'string')
74
+ return value;
75
+ if (typeof value === 'number') {
76
+ if (!Number.isFinite(value))
77
+ throw literalError(label, 'must use a Rivet marker for a non-finite number');
78
+ return value;
79
+ }
80
+ if (typeof value !== 'object')
81
+ throw literalError(label, 'value must be JSON-compatible');
82
+ if (seen.has(value))
83
+ throw literalError(label, 'cannot be circular');
84
+ seen.add(value);
85
+ try {
86
+ if (Array.isArray(value)) {
87
+ if (isSparseArray(value))
88
+ throw literalError(label, 'cannot be a sparse array');
89
+ return value.map((item, index) => decodeLiteral(item, `${label}[${index}]`, seen));
90
+ }
91
+ if (!isPlainRecord(value))
92
+ throw literalError(label, 'value must be JSON-compatible');
93
+ if (Object.hasOwn(value, literalMarkerKey)) {
94
+ const kind = value[literalMarkerKey];
95
+ if (kind === 'undefined' && Object.keys(value).length === 1)
96
+ return undefined;
97
+ if (kind === 'number' && Object.keys(value).length === 2 && Object.hasOwn(value, 'value')) {
98
+ if (value.value === 'nan')
99
+ return Number.NaN;
100
+ if (value.value === 'infinity')
101
+ return Infinity;
102
+ if (value.value === '-infinity')
103
+ return -Infinity;
104
+ }
105
+ if (kind === 'uint8array' &&
106
+ Object.keys(value).length === 2 &&
107
+ Object.hasOwn(value, 'value') &&
108
+ typeof value.value === 'string') {
109
+ try {
110
+ return base64ToUint8Array(value.value);
111
+ }
112
+ catch {
113
+ throw literalError(label, 'has an invalid Uint8Array base64 value');
114
+ }
115
+ }
116
+ if (kind === literalMarkerObject &&
117
+ Object.keys(value).length === 2 &&
118
+ Object.hasOwn(value, 'value') &&
119
+ Array.isArray(value.value)) {
120
+ if (isSparseArray(value.value))
121
+ throw literalError(label, 'has a sparse escaped object value');
122
+ const result = {};
123
+ for (const [index, entry] of value.value.entries()) {
124
+ if (!Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== 'string') {
125
+ throw literalError(label, `has an invalid escaped object entry at index ${index}`);
126
+ }
127
+ Object.defineProperty(result, entry[0], {
128
+ configurable: true,
129
+ enumerable: true,
130
+ value: decodeLiteral(entry[1], `${label}.${entry[0]}`, seen),
131
+ writable: true,
132
+ });
133
+ }
134
+ return result;
135
+ }
136
+ throw literalError(label, 'has an invalid reserved literal marker');
137
+ }
138
+ const result = {};
139
+ for (const [key, item] of Object.entries(value)) {
140
+ Object.defineProperty(result, key, {
141
+ configurable: true,
142
+ enumerable: true,
143
+ value: decodeLiteral(item, `${label}.${key}`, seen),
144
+ writable: true,
145
+ });
146
+ }
147
+ return result;
148
+ }
149
+ finally {
150
+ seen.delete(value);
151
+ }
152
+ }
153
+ function validateMetadata(value, label) {
154
+ if (value === null || typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string')
155
+ return;
156
+ if (!Array.isArray(value) || isSparseArray(value))
157
+ throw literalError(label, 'must contain only JSON-compatible metadata values');
158
+ for (const [index, item] of value.entries()) {
159
+ if (item === null || typeof item === 'boolean' || typeof item === 'number' || typeof item === 'string')
160
+ continue;
161
+ throw literalError(`${label}[${index}]`, 'must be a scalar value');
162
+ }
163
+ }
164
+ function requirePlainRecord(value, label) {
165
+ if (!isPlainRecord(value))
166
+ throw literalError(label, 'must be an object');
167
+ return value;
168
+ }
169
+ function requireString(value, label) {
170
+ if (typeof value !== 'string')
171
+ throw literalError(label, 'must be a string');
172
+ }
173
+ function requireBoolean(value, label) {
174
+ if (typeof value !== 'boolean')
175
+ throw literalError(label, 'must be a boolean');
176
+ }
177
+ function requireUint8Array(value, label) {
178
+ if (!(value instanceof Uint8Array))
179
+ throw literalError(label, 'must be a Uint8Array');
180
+ }
181
+ function validateChatMessagePart(value, label) {
182
+ if (typeof value === 'string')
183
+ return;
184
+ const part = requirePlainRecord(value, label);
185
+ if (part.type === 'url') {
186
+ requireString(part.url, `${label}.url`);
187
+ return;
188
+ }
189
+ if (part.type === 'image') {
190
+ requireString(part.mediaType, `${label}.mediaType`);
191
+ requireUint8Array(part.data, `${label}.data`);
192
+ return;
193
+ }
194
+ if (part.type === 'document') {
195
+ requireString(part.mediaType, `${label}.mediaType`);
196
+ requireUint8Array(part.data, `${label}.data`);
197
+ if (part.title !== undefined)
198
+ requireString(part.title, `${label}.title`);
199
+ if (part.context !== undefined)
200
+ requireString(part.context, `${label}.context`);
201
+ requireBoolean(part.enableCitations, `${label}.enableCitations`);
202
+ return;
203
+ }
204
+ throw literalError(label, 'has an unsupported message part');
205
+ }
206
+ function validateStructuredScalar(type, value, label) {
207
+ switch (type) {
208
+ case 'any':
209
+ return;
210
+ case 'boolean':
211
+ return requireBoolean(value, label);
212
+ case 'number':
213
+ if (typeof value !== 'number')
214
+ throw literalError(label, 'must be a number');
215
+ return;
216
+ case 'string':
217
+ case 'date':
218
+ case 'time':
219
+ case 'datetime':
220
+ return requireString(value, label);
221
+ case 'object':
222
+ requirePlainRecord(value, label);
223
+ return;
224
+ case 'vector': {
225
+ if (!Array.isArray(value) || isSparseArray(value) || !value.every((item) => typeof item === 'number')) {
226
+ throw literalError(label, 'must be an array of numbers');
227
+ }
228
+ return;
229
+ }
230
+ case 'binary':
231
+ return requireUint8Array(value, label);
232
+ case 'image': {
233
+ const image = requirePlainRecord(value, label);
234
+ requireString(image.mediaType, `${label}.mediaType`);
235
+ requireUint8Array(image.data, `${label}.data`);
236
+ return;
237
+ }
238
+ case 'audio': {
239
+ const audio = requirePlainRecord(value, label);
240
+ if (audio.mediaType !== undefined)
241
+ requireString(audio.mediaType, `${label}.mediaType`);
242
+ requireUint8Array(audio.data, `${label}.data`);
243
+ return;
244
+ }
245
+ case 'document': {
246
+ const document = requirePlainRecord(value, label);
247
+ requireString(document.mediaType, `${label}.mediaType`);
248
+ requireUint8Array(document.data, `${label}.data`);
249
+ if (document.title !== undefined)
250
+ requireString(document.title, `${label}.title`);
251
+ if (document.context !== undefined)
252
+ requireString(document.context, `${label}.context`);
253
+ requireBoolean(document.enableCitations, `${label}.enableCitations`);
254
+ return;
255
+ }
256
+ case 'graph-reference': {
257
+ const graph = requirePlainRecord(value, label);
258
+ requireString(graph.graphId, `${label}.graphId`);
259
+ requireString(graph.graphName, `${label}.graphName`);
260
+ return;
261
+ }
262
+ case 'knowledge-source': {
263
+ const source = requirePlainRecord(value, label);
264
+ requireString(source.connectionId, `${label}.connectionId`);
265
+ requireString(source.sourceId, `${label}.sourceId`);
266
+ if (source.version !== undefined)
267
+ requireString(source.version, `${label}.version`);
268
+ return;
269
+ }
270
+ case 'knowledge-document': {
271
+ const document = requirePlainRecord(value, label);
272
+ requireString(document.text, `${label}.text`);
273
+ if (document.id !== undefined)
274
+ requireString(document.id, `${label}.id`);
275
+ if (document.title !== undefined)
276
+ requireString(document.title, `${label}.title`);
277
+ if (document.metadata !== undefined)
278
+ requirePlainRecord(document.metadata, `${label}.metadata`);
279
+ for (const [key, item] of Object.entries((document.metadata ?? {}))) {
280
+ validateMetadata(item, `${label}.metadata.${key}`);
281
+ }
282
+ return;
283
+ }
284
+ case 'knowledge-evidence': {
285
+ const evidence = requirePlainRecord(value, label);
286
+ requireString(evidence.id, `${label}.id`);
287
+ requireString(evidence.text, `${label}.text`);
288
+ requireString(evidence.documentId, `${label}.documentId`);
289
+ validateStructuredScalar('knowledge-source', evidence.source, `${label}.source`);
290
+ if (evidence.relevanceScore !== undefined && typeof evidence.relevanceScore !== 'number') {
291
+ throw literalError(`${label}.relevanceScore`, 'must be a number');
292
+ }
293
+ if (evidence.title !== undefined)
294
+ requireString(evidence.title, `${label}.title`);
295
+ if (evidence.chunkIndex !== undefined && typeof evidence.chunkIndex !== 'number') {
296
+ throw literalError(`${label}.chunkIndex`, 'must be a number');
297
+ }
298
+ if (evidence.metadata !== undefined)
299
+ requirePlainRecord(evidence.metadata, `${label}.metadata`);
300
+ for (const [key, item] of Object.entries((evidence.metadata ?? {}))) {
301
+ validateMetadata(item, `${label}.metadata.${key}`);
302
+ }
303
+ return;
304
+ }
305
+ case 'gpt-function': {
306
+ const fn = requirePlainRecord(value, label);
307
+ requireString(fn.name, `${label}.name`);
308
+ requireString(fn.description, `${label}.description`);
309
+ requirePlainRecord(fn.parameters, `${label}.parameters`);
310
+ requireBoolean(fn.strict, `${label}.strict`);
311
+ if (fn.namespace !== undefined)
312
+ requireString(fn.namespace, `${label}.namespace`);
313
+ if (fn.resultHandling !== undefined &&
314
+ fn.resultHandling !== 'continue' &&
315
+ fn.resultHandling !== 'return-direct') {
316
+ throw literalError(`${label}.resultHandling`, 'must be "continue" or "return-direct"');
317
+ }
318
+ return;
319
+ }
320
+ case 'chat-message': {
321
+ const message = requirePlainRecord(value, label);
322
+ if (message.type !== 'system' &&
323
+ message.type !== 'developer' &&
324
+ message.type !== 'user' &&
325
+ message.type !== 'assistant' &&
326
+ message.type !== 'function') {
327
+ throw literalError(`${label}.type`, 'must be a supported chat message type');
328
+ }
329
+ const parts = Array.isArray(message.message) ? message.message : [message.message];
330
+ if (Array.isArray(message.message) && isSparseArray(message.message)) {
331
+ throw literalError(`${label}.message`, 'cannot be a sparse array');
332
+ }
333
+ for (const [index, part] of parts.entries())
334
+ validateChatMessagePart(part, `${label}.message[${index}]`);
335
+ if (message.isCacheBreakpoint !== undefined)
336
+ requireBoolean(message.isCacheBreakpoint, `${label}.isCacheBreakpoint`);
337
+ if (message.type === 'assistant') {
338
+ if (message.function_call !== undefined && !isPlainRecord(message.function_call)) {
339
+ throw literalError(`${label}.function_call`, 'must be an object');
340
+ }
341
+ if (message.function_calls !== undefined && !Array.isArray(message.function_calls)) {
342
+ throw literalError(`${label}.function_calls`, 'must be an array');
343
+ }
344
+ }
345
+ if (message.type === 'function')
346
+ requireString(message.name, `${label}.name`);
347
+ return;
348
+ }
349
+ case 'llm-config': {
350
+ const profile = requirePlainRecord(value, label);
351
+ if (profile.version !== 1)
352
+ throw literalError(`${label}.version`, 'must be version 1');
353
+ requirePlainRecord(profile.configuration, `${label}.configuration`);
354
+ requirePlainRecord(profile.credential, `${label}.credential`);
355
+ return;
356
+ }
357
+ default:
358
+ throw literalError(label, `has unsupported data type "${type}"`);
359
+ }
360
+ }
361
+ function validateProjectGlobalVariableDataValue(type, value, label) {
362
+ const isArrayType = type.endsWith('[]');
363
+ const scalarType = isArrayType ? type.slice(0, -2) : type;
364
+ const values = isArrayType ? value : [value];
365
+ if (!Array.isArray(values) || (isArrayType && isSparseArray(values))) {
366
+ throw literalError(label, isArrayType ? 'must be an array' : 'has an invalid value');
367
+ }
368
+ for (const [index, item] of values.entries()) {
369
+ validateStructuredScalar(scalarType, item, isArrayType ? `${label}[${index}]` : label);
370
+ }
371
+ }
372
+ /** Encodes a normal global value into a portable project-file definition. */
373
+ export function encodeProjectGlobalVariable(value) {
374
+ if (!isProjectGlobalVariableDataType(value.type)) {
375
+ throw new Error(`Project global variables do not support data type "${value.type}".`);
376
+ }
377
+ validateProjectGlobalVariableDataValue(value.type, value.value, 'Project global variable');
378
+ return { type: value.type, value: encodeLiteral(value.value, new Set()) };
379
+ }
380
+ /** Decodes and validates a single portable project-file global definition. */
381
+ export function decodeProjectGlobalVariable(value, label = 'Project global variable') {
382
+ if (!isPlainRecord(value))
383
+ throw literalError(label, 'definition must be an object');
384
+ if (!isProjectGlobalVariableDataType(value.type)) {
385
+ throw literalError(label, 'type must be a supported non-function data type');
386
+ }
387
+ if (!Object.hasOwn(value, 'value'))
388
+ throw literalError(label, 'definition is missing value');
389
+ const decoded = {
390
+ type: value.type,
391
+ value: decodeLiteral(value.value, label),
392
+ };
393
+ validateProjectGlobalVariableDataValue(decoded.type, decoded.value, label);
394
+ return decoded;
395
+ }
396
+ function decodeProjectGlobalVariables(value, label) {
397
+ if (!isPlainRecord(value))
398
+ throw literalError(label, 'must be a plain object');
399
+ return Object.entries(value).map(([id, definition]) => {
400
+ if (!id.trim())
401
+ throw literalError(label, 'contains an empty variable ID');
402
+ return [id, decodeProjectGlobalVariable(definition, `${label}.${id}`)];
403
+ });
404
+ }
405
+ /** Validates definitions without retaining decoded runtime values. */
406
+ export function validateProjectGlobalVariables(value, label = 'Project metadata.globalVariables') {
407
+ decodeProjectGlobalVariables(value, label);
408
+ }
409
+ export function getProjectGlobalVariableIds(project) {
410
+ return Object.keys(project?.metadata.globalVariables ?? {}).filter((id) => id.trim().length > 0);
411
+ }
412
+ /**
413
+ * Resolves referenced projects depth-first in reference order, then the root
414
+ * project. Later definitions intentionally replace earlier ones; the root
415
+ * project therefore always wins a collision with one of its references.
416
+ */
417
+ export function resolveProjectGlobalVariables(rootProject, loadedProjects) {
418
+ const resolved = new Map();
419
+ const visited = new Set();
420
+ const visit = (project) => {
421
+ const projectId = project.metadata.id;
422
+ if (visited.has(projectId))
423
+ return;
424
+ // Existing project loading is cycle-tolerant: the first visit owns a
425
+ // project and later back-edges reuse it. Keep project-global resolution
426
+ // compatible with that behavior so adding defaults cannot reject a legacy
427
+ // reference graph that ran before this feature existed.
428
+ visited.add(projectId);
429
+ for (const reference of project.references ?? []) {
430
+ // The root is supplied separately from the referenced-project lookup.
431
+ // A legacy child -> root back-edge must therefore reuse that in-memory
432
+ // root, not require loaders to resolve the active project as if it were
433
+ // another reference.
434
+ if (reference.id === rootProject.metadata.id) {
435
+ visit(rootProject);
436
+ continue;
437
+ }
438
+ if (!Object.hasOwn(loadedProjects, reference.id)) {
439
+ throw new Error(`Referenced project "${reference.id}" was not loaded while resolving project global variables.`);
440
+ }
441
+ const referencedProject = loadedProjects[reference.id];
442
+ visit(referencedProject);
443
+ }
444
+ if (project.metadata.globalVariables !== undefined) {
445
+ for (const [id, definition] of decodeProjectGlobalVariables(project.metadata.globalVariables, `Global variables in project "${projectId}"`)) {
446
+ resolved.set(id, definition);
447
+ }
448
+ }
449
+ };
450
+ visit(rootProject);
451
+ return resolved;
452
+ }
@@ -1,3 +1,13 @@
1
+ /**
2
+ * Graph Outputs with the same public ID retain the first non-excluded value.
3
+ * Normal execution, frozen replay, and control-flow exclusion all use this
4
+ * single boundary rule.
5
+ */
6
+ export function commitGraphOutputValue(graphOutputs, outputId, value) {
7
+ if (graphOutputs[outputId] == null || graphOutputs[outputId]?.type === 'control-flow-excluded') {
8
+ graphOutputs[outputId] = value;
9
+ }
10
+ }
1
11
  export function ensureGraphCostOutput(graphOutputs, totalCost) {
2
12
  const costPort = 'cost';
3
13
  if (graphOutputs[costPort] == null) {
@@ -13,10 +23,8 @@ export function applyFrozenGraphBoundaryEffects(graphOutputs, node, outputValues
13
23
  const valueOutput = outputValues['valueOutput'];
14
24
  // Duplicate Graph Outputs share the ordinary first-non-excluded winner,
15
25
  // whether a producer is computed or replayed from frozen outputs.
16
- if (outputId &&
17
- valueOutput &&
18
- (graphOutputs[outputId] == null || graphOutputs[outputId]?.type === 'control-flow-excluded')) {
19
- graphOutputs[outputId] = valueOutput;
26
+ if (outputId && valueOutput) {
27
+ commitGraphOutputValue(graphOutputs, outputId, valueOutput);
20
28
  }
21
29
  return undefined;
22
30
  }