@valerypopoff/rivet2-core 2.15.0 → 2.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/dist/cjs/bundle.cjs +4350 -2077
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/interpolationRuntime.cjs +22 -3
  4. package/dist/cjs/interpolationRuntime.cjs.map +3 -3
  5. package/dist/cjs/interpolationSyntax.cjs +9 -5
  6. package/dist/cjs/interpolationSyntax.cjs.map +2 -2
  7. package/dist/esm/api/createProcessor.js +5 -2
  8. package/dist/esm/exports.js +2 -0
  9. package/dist/esm/model/GraphBoundaryCache.js +2 -1
  10. package/dist/esm/model/GraphProcessor.js +268 -6
  11. package/dist/esm/model/Nodes.js +10 -0
  12. package/dist/esm/model/ProjectBundle.js +235 -0
  13. package/dist/esm/model/SplitRunProcessor.js +28 -7
  14. package/dist/esm/model/StreamingWatchTopology.js +118 -8
  15. package/dist/esm/model/SubgraphProjectTarget.js +7 -0
  16. package/dist/esm/model/chat-v2/aiSdkBridge.js +7 -5
  17. package/dist/esm/model/chat-v2/chatV2Pipeline.js +13 -8
  18. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +19 -1
  19. package/dist/esm/model/chat-v2/chatV2Shared.js +2 -1
  20. package/dist/esm/model/chat-v2/llmChatV2Body.js +11 -8
  21. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +2 -0
  22. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +15 -1
  23. package/dist/esm/model/chat-v2/llmChatV2NodeMigration.js +22 -2
  24. package/dist/esm/model/chat-v2/llmProfile.js +3 -0
  25. package/dist/esm/model/chat-v2/llmProfileBody.js +2 -2
  26. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +1 -1
  27. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +1 -1
  28. package/dist/esm/model/chat-v2/temperature.js +9 -0
  29. package/dist/esm/model/classifier/credentials.js +30 -4
  30. package/dist/esm/model/classifier/images.js +176 -0
  31. package/dist/esm/model/classifier/json.js +57 -0
  32. package/dist/esm/model/classifier/limits.js +270 -0
  33. package/dist/esm/model/classifier/openai.js +118 -0
  34. package/dist/esm/model/classifier/preparation.js +74 -0
  35. package/dist/esm/model/classifier/providers.js +260 -185
  36. package/dist/esm/model/classifier/questionHelpers.js +29 -45
  37. package/dist/esm/model/classifier/questions.js +53 -0
  38. package/dist/esm/model/classifier/response.js +75 -0
  39. package/dist/esm/model/classifier/state.js +204 -0
  40. package/dist/esm/model/nodeRunFailure.js +47 -0
  41. package/dist/esm/model/nodes/CatchStreamingChunksNode.js +42 -0
  42. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +178 -138
  43. package/dist/esm/model/nodes/ClassifierQuestionNode.js +59 -15
  44. package/dist/esm/model/nodes/GetGlobalNode.js +2 -2
  45. package/dist/esm/model/nodes/HttpCallNode.js +44 -75
  46. package/dist/esm/model/nodes/ImageNode.js +44 -3
  47. package/dist/esm/model/nodes/LLMChatV2Node.js +24 -3
  48. package/dist/esm/model/nodes/ObjectNode.js +29 -18
  49. package/dist/esm/model/nodes/PromptNode.js +2 -1
  50. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +4 -1
  51. package/dist/esm/model/nodes/SetGlobalNode.js +5 -3
  52. package/dist/esm/model/nodes/StopWatchingStreamingOutputNode.js +8 -8
  53. package/dist/esm/model/nodes/StreamValueNode.js +38 -0
  54. package/dist/esm/model/nodes/SubGraphNode.js +196 -35
  55. package/dist/esm/model/nodes/ToBase64Node.js +106 -0
  56. package/dist/esm/model/nodes/WatchStreamingOutputNode.js +7 -7
  57. package/dist/esm/recording/ExecutionRecorder.js +26 -0
  58. package/dist/esm/utils/base64.js +18 -15
  59. package/dist/esm/utils/errors.js +41 -0
  60. package/dist/esm/utils/interpolation.js +44 -22
  61. package/dist/esm/utils/interpolationSyntax.js +15 -6
  62. package/dist/esm/utils/serialization/serialization.js +3 -2
  63. package/dist/esm/utils/serialization/serializationUtils.js +6 -0
  64. package/dist/esm/utils/serialization/serialization_v4.js +15 -3
  65. package/dist/types/api/createProcessor.d.ts +7 -1
  66. package/dist/types/exports.d.ts +2 -0
  67. package/dist/types/model/CycleDetector.d.ts +1 -2
  68. package/dist/types/model/ExecutorProtocol.d.ts +2 -0
  69. package/dist/types/model/GraphBoundaryCache.d.ts +2 -0
  70. package/dist/types/model/GraphProcessor.d.ts +1 -0
  71. package/dist/types/model/Nodes.d.ts +6 -2
  72. package/dist/types/model/ProcessContext.d.ts +12 -0
  73. package/dist/types/model/ProjectBundle.d.ts +54 -0
  74. package/dist/types/model/ProjectReferenceLoader.d.ts +3 -0
  75. package/dist/types/model/StreamingWatchTopology.d.ts +11 -1
  76. package/dist/types/model/SubgraphProjectTarget.d.ts +38 -0
  77. package/dist/types/model/chat-v2/chatV2Shared.d.ts +1 -1
  78. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +3 -1
  79. package/dist/types/model/chat-v2/llmChatV2NodeMigration.d.ts +3 -1
  80. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +6 -6
  81. package/dist/types/model/chat-v2/temperature.d.ts +2 -0
  82. package/dist/types/model/classifier/credentials.d.ts +3 -1
  83. package/dist/types/model/classifier/images.d.ts +18 -0
  84. package/dist/types/model/classifier/json.d.ts +19 -0
  85. package/dist/types/model/classifier/limits.d.ts +42 -0
  86. package/dist/types/model/classifier/openai.d.ts +5 -0
  87. package/dist/types/model/classifier/preparation.d.ts +16 -0
  88. package/dist/types/model/classifier/providers.d.ts +67 -9
  89. package/dist/types/model/classifier/questionHelpers.d.ts +6 -4
  90. package/dist/types/model/classifier/questions.d.ts +4 -0
  91. package/dist/types/model/classifier/response.d.ts +4 -0
  92. package/dist/types/model/classifier/state.d.ts +37 -0
  93. package/dist/types/model/classifier/types.d.ts +2 -0
  94. package/dist/types/model/nodeRunFailure.d.ts +13 -0
  95. package/dist/types/model/nodes/CatchStreamingChunksNode.d.ts +20 -0
  96. package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +3 -0
  97. package/dist/types/model/nodes/GetGlobalNode.d.ts +7 -0
  98. package/dist/types/model/nodes/ImageNode.d.ts +4 -0
  99. package/dist/types/model/nodes/LLMChatV2Node.d.ts +1 -0
  100. package/dist/types/model/nodes/ObjectNode.d.ts +2 -1
  101. package/dist/types/model/nodes/StreamValueNode.d.ts +14 -0
  102. package/dist/types/model/nodes/SubGraphNode.d.ts +21 -2
  103. package/dist/types/model/nodes/ToBase64Node.d.ts +12 -0
  104. package/dist/types/recording/ExecutionRecorder.d.ts +8 -2
  105. package/dist/types/utils/base64.d.ts +1 -1
  106. package/dist/types/utils/errors.d.ts +4 -0
  107. package/dist/types/utils/interpolation.d.ts +13 -2
  108. package/dist/types/utils/interpolationSyntax.d.ts +1 -1
  109. package/dist/types/utils/serialization/serialization.d.ts +3 -1
  110. package/dist/types/utils/serialization/serializationUtils.d.ts +1 -0
  111. package/package.json +1 -1
@@ -10,7 +10,53 @@ import {} from '../ProcessContext.js';
10
10
  import {} from '../../index.js';
11
11
  import { dedent } from 'ts-dedent';
12
12
  import { getError } from '../../utils/errors.js';
13
+ import { getSubgraphProjectKey } from '../SubgraphProjectTarget.js';
14
+ import { ExecutionRecorder } from '../../recording/ExecutionRecorder.js';
13
15
  import { applyGraphBoundaryPortOrder, buildExcludedGraphBoundaryOutputs, buildGraphBoundaryInputData, getGraphBoundary, getGraphBoundaryInputDefinitions, getGraphBoundaryOutputDefinitions, } from '../GraphBoundaryCache.js';
16
+ /** A saved cross-project boundary is the wire contract until the user explicitly selects a new target. */
17
+ export function getSubgraphTargetBoundaryChange(expected, actual) {
18
+ if (!expected)
19
+ return null;
20
+ for (const side of ['inputs', 'outputs']) {
21
+ for (const port of expected[side]) {
22
+ const match = actual[side].find((candidate) => port.nodeId ? candidate.nodeId === port.nodeId : candidate.portId === port.portId);
23
+ if (match?.dataType !== port.dataType) {
24
+ return { side: side === 'inputs' ? 'input' : 'output', id: port.id };
25
+ }
26
+ }
27
+ const callerIds = new Set();
28
+ for (const port of actual[side]) {
29
+ const saved = expected[side].find((candidate) => candidate.nodeId ? candidate.nodeId === port.nodeId : candidate.portId === port.portId);
30
+ const callerId = saved?.portId ?? port.portId;
31
+ if (callerIds.has(callerId)) {
32
+ return { side: side === 'inputs' ? 'input' : 'output', id: port.id };
33
+ }
34
+ callerIds.add(callerId);
35
+ }
36
+ }
37
+ return null;
38
+ }
39
+ /** Keep the caller's saved wire IDs while adopting current target names and metadata. */
40
+ export function reconcileSubgraphTargetBoundary(expected, actual) {
41
+ if (!expected)
42
+ return actual;
43
+ return {
44
+ inputs: actual.inputs.map((port) => {
45
+ const saved = expected.inputs.find((candidate) => candidate.nodeId ? candidate.nodeId === port.nodeId : candidate.portId === port.portId);
46
+ return saved && saved.dataType === port.dataType ? { ...port, portId: saved.portId } : port;
47
+ }),
48
+ outputs: actual.outputs.map((port) => {
49
+ const saved = expected.outputs.find((candidate) => candidate.nodeId ? candidate.nodeId === port.nodeId : candidate.portId === port.portId);
50
+ return saved && saved.dataType === port.dataType ? { ...port, portId: saved.portId } : port;
51
+ }),
52
+ };
53
+ }
54
+ export function getSubgraphTargetBoundaryIssue(expected, actual) {
55
+ const change = getSubgraphTargetBoundaryChange(expected, actual);
56
+ return change
57
+ ? `The selected project's graph changed its ${change.side} "${change.id}". Re-select the graph and review its connections.`
58
+ : null;
59
+ }
14
60
  export class SubGraphNodeImpl extends NodeImpl {
15
61
  static create() {
16
62
  const chartNode = {
@@ -31,17 +77,19 @@ export class SubGraphNodeImpl extends NodeImpl {
31
77
  };
32
78
  return chartNode;
33
79
  }
34
- getInputDefinitions(_connections, _nodes, project, _referencedProjects, definitionContext) {
35
- const boundary = this.getBoundary(project, definitionContext);
80
+ getInputDefinitions(_connections, _nodes, project, referencedProjects, definitionContext) {
81
+ const boundary = this.getTargetBoundary(project, referencedProjects, definitionContext);
36
82
  return boundary ? getGraphBoundaryInputDefinitions(boundary, this.data.inputPortOrder) : [];
37
83
  }
38
84
  getGraphOutputs(project, definitionContext) {
39
85
  const boundary = this.getBoundary(project, definitionContext);
40
86
  return boundary ? getGraphBoundaryOutputDefinitions(boundary, this.data.outputPortOrder) : [];
41
87
  }
42
- getOutputDefinitions(_connections, _nodes, project, _referencedProjects, definitionContext) {
88
+ getOutputDefinitions(_connections, _nodes, project, referencedProjects, definitionContext) {
43
89
  const outputs = [];
44
- outputs.push(...this.getGraphOutputs(project, definitionContext));
90
+ const boundary = this.getTargetBoundary(project, referencedProjects, definitionContext);
91
+ if (boundary)
92
+ outputs.push(...getGraphBoundaryOutputDefinitions(boundary, this.data.outputPortOrder));
45
93
  if (this.data.useErrorOutput) {
46
94
  outputs.push({
47
95
  id: 'error',
@@ -54,34 +102,63 @@ export class SubGraphNodeImpl extends NodeImpl {
54
102
  getBoundary(project, definitionContext) {
55
103
  return (definitionContext?.getGraphBoundary(project, this.data.graphId) ?? getGraphBoundary(project, this.data.graphId));
56
104
  }
105
+ getTargetProject(project, referencedProjects) {
106
+ if (!this.data.targetProjectId)
107
+ return project;
108
+ return referencedProjects[getSubgraphProjectKey({
109
+ projectId: this.data.targetProjectId,
110
+ version: this.data.targetVersion ?? 'latest',
111
+ })];
112
+ }
113
+ getTargetBoundary(project, referencedProjects, definitionContext) {
114
+ // Keep the authored port contract visible even after a referenced project
115
+ // changes. Execution checks it against the resolved graph and fails with a
116
+ // reviewable error; replacing it here would hide existing wires in the UI.
117
+ if (this.data.targetProjectId && this.data.targetBoundary) {
118
+ const target = this.getTargetProject(project, referencedProjects);
119
+ const actual = target && this.getBoundary(target, definitionContext);
120
+ return actual && !getSubgraphTargetBoundaryChange(this.data.targetBoundary, actual)
121
+ ? reconcileSubgraphTargetBoundary(this.data.targetBoundary, actual)
122
+ : this.data.targetBoundary;
123
+ }
124
+ const target = this.getTargetProject(project, referencedProjects);
125
+ return ((target && this.getBoundary(target, definitionContext)) ??
126
+ (this.data.targetProjectId ? this.data.targetBoundary : undefined));
127
+ }
57
128
  getEditors(context) {
58
129
  const definitions = [
59
130
  {
60
- type: 'graphSelector',
131
+ type: 'custom',
61
132
  label: 'Graph',
62
- dataKey: 'graphId',
63
- },
64
- {
65
- type: 'toggle',
66
- label: 'Use Error Output',
67
- dataKey: 'useErrorOutput',
133
+ customEditorId: 'SubgraphTarget',
68
134
  },
69
135
  {
70
- type: 'toggle',
71
- label: 'Skip unused outputs',
72
- dataKey: 'skipUnusedOutputs',
73
- helperMessage: 'Only run branches needed by connected outputs. Skipped branches also skip their side effects and errors. ' +
74
- 'Runs the full subgraph for Run to here, partial-output forwarding, or a connected Error output.',
136
+ type: 'group',
137
+ label: 'Outputs',
138
+ editors: [
139
+ {
140
+ type: 'toggle',
141
+ label: 'Use Error Output',
142
+ dataKey: 'useErrorOutput',
143
+ },
144
+ {
145
+ type: 'toggle',
146
+ label: 'Skip unused outputs',
147
+ dataKey: 'skipUnusedOutputs',
148
+ helperMessage: 'Only run branches needed by connected outputs. Skipped branches also skip their side effects and errors. ' +
149
+ 'Runs the full subgraph for Run to here, partial-output forwarding, or a connected Error output.',
150
+ },
151
+ ],
75
152
  },
76
153
  ];
77
154
  if (this.data.graphId) {
78
- const boundary = getGraphBoundary(context.project, this.data.graphId);
155
+ const boundary = this.getTargetBoundary(context.project, context.referencedProjects);
79
156
  if (boundary) {
80
157
  for (const input of applyGraphBoundaryPortOrder(boundary.inputs, this.data.inputPortOrder)) {
81
158
  definitions.push({
82
159
  type: 'dynamic',
83
160
  dataKey: 'inputData',
84
- dynamicDataKey: input.id,
161
+ dynamicDataKey: input.portId,
85
162
  dataType: input.dataType,
86
163
  label: input.id,
87
164
  editor: input.editor ?? 'auto',
@@ -106,42 +183,92 @@ export class SubGraphNodeImpl extends NodeImpl {
106
183
  if (!project) {
107
184
  throw new Error('SubGraphNode requires a project to be set in the context.');
108
185
  }
109
- const graph = project.graphs[this.data.graphId];
186
+ const target = this.data.targetProjectId
187
+ ? context.referencedProjects[getSubgraphProjectKey({
188
+ projectId: this.data.targetProjectId,
189
+ version: this.data.targetVersion ?? 'latest',
190
+ })]
191
+ : project;
192
+ if (!target) {
193
+ throw new Error('The selected Studio Server project is unavailable. Refresh the target and try again.');
194
+ }
195
+ const graph = target.graphs[this.data.graphId];
110
196
  if (!graph) {
111
197
  throw new Error(`SubGraphNode requires a graph with id ${this.data.graphId} to be present in the project.`);
112
198
  }
113
- const boundary = context.getGraphBoundary?.(project, this.data.graphId) ?? getGraphBoundary(project, this.data.graphId);
114
- const inputData = buildGraphBoundaryInputData(boundary, inputs, this.data.inputData);
199
+ const boundary = context.getGraphBoundary?.(target, this.data.graphId) ?? getGraphBoundary(target, this.data.graphId);
200
+ if (this.data.targetProjectId) {
201
+ const boundaryIssue = getSubgraphTargetBoundaryIssue(this.data.targetBoundary, boundary);
202
+ if (boundaryIssue)
203
+ throw new Error(boundaryIssue);
204
+ }
205
+ const callerBoundary = this.data.targetProjectId
206
+ ? reconcileSubgraphTargetBoundary(this.data.targetBoundary, boundary)
207
+ : boundary;
208
+ const callerInputData = buildGraphBoundaryInputData(callerBoundary, inputs, this.data.inputData);
209
+ const inputData = this.data.targetProjectId ? {} : callerInputData;
210
+ if (this.data.targetProjectId) {
211
+ for (const input of callerBoundary.inputs) {
212
+ if (Object.hasOwn(callerInputData, input.portId))
213
+ inputData[input.id] = callerInputData[input.portId];
214
+ }
215
+ }
216
+ const graphInputStreams = this.data.targetProjectId
217
+ ? Object.fromEntries(callerBoundary.inputs.flatMap((input) => {
218
+ const stream = context.graphInputStreams?.[input.portId];
219
+ return stream ? [[input.id, stream]] : [];
220
+ }))
221
+ : context.graphInputStreams;
115
222
  const shouldRunWholeGraph = this.data.skipUnusedOutputs !== true ||
116
223
  context.isDirectRunTarget ||
117
224
  this.data.useAsGraphPartialOutput === true ||
118
225
  (this.data.useErrorOutput === true && context.activeOutputPortIds.has('error'));
119
226
  const requestedGraphOutputIds = shouldRunWholeGraph
120
227
  ? undefined
121
- : boundary.outputs.filter((output) => context.activeOutputPortIds.has(output.portId)).map((output) => output.id);
228
+ : callerBoundary.outputs
229
+ .filter((output) => context.activeOutputPortIds.has(output.portId))
230
+ .map((output) => output.id);
122
231
  if (requestedGraphOutputIds?.length === 0) {
123
- return buildOptimizedSubgraphOutputs(boundary, [], {}, 0, this.data.useErrorOutput);
232
+ return buildOptimizedSubgraphOutputs(callerBoundary, [], {}, 0, this.data.useErrorOutput);
124
233
  }
125
- const subGraphProcessor = context.createSubProcessor(this.data.graphId, { signal: context.signal });
234
+ const subGraphProcessor = context.createSubProcessor(this.data.graphId, {
235
+ signal: context.signal,
236
+ project: target,
237
+ });
238
+ const recordingTarget = this.data.targetProjectId && context.subgraphTarget;
239
+ const childRecorder = recordingTarget && context.onSubgraphProjectRun
240
+ ? new ExecutionRecorder(context.subgraphRecordingOptions)
241
+ : undefined;
242
+ const finishChildRecording = childRecorder?.record(subGraphProcessor);
243
+ const startedAt = Date.now();
244
+ let runError;
126
245
  try {
127
- const startTime = Date.now();
128
- const graphOutputs = await subGraphProcessor.processGraph(context, inputData, context.contextValues, {
246
+ const graphOutputs = await subGraphProcessor.processGraph(context.subgraphTarget
247
+ ? {
248
+ ...context,
249
+ datasetProvider: context.subgraphTarget.datasetProvider ?? context.datasetProvider,
250
+ projectPath: context.subgraphTarget.sourceProjectPath ?? context.projectPath,
251
+ }
252
+ : context, inputData, context.contextValues, {
129
253
  ...(requestedGraphOutputIds ? { requestedGraphOutputIds } : {}),
130
- graphInputStreams: context.graphInputStreams,
254
+ graphInputStreams,
131
255
  // A child Graph Output can relay a direct producer's partial value
132
256
  // under the public boundary port ID. An Error-output Subgraph may
133
257
  // later replace that same normal output with an exclusion, so it is
134
258
  // final-only even if a caller supplies this internal callback.
135
259
  // The parent owns all Watch scheduling.
136
260
  ...(context.onGraphOutputPartial && this.data.useErrorOutput !== true
137
- ? { onGraphOutputPartial: context.onGraphOutputPartial }
261
+ ? {
262
+ onGraphOutputPartial: (partial) => context.onGraphOutputPartial?.(this.data.targetProjectId ? mapSubgraphTargetOutputs(callerBoundary, partial) : partial),
263
+ }
138
264
  : {}),
139
265
  });
140
- const duration = Date.now() - startTime;
266
+ const duration = Date.now() - startedAt;
267
+ finishChildRecording?.({ type: 'done', results: graphOutputs });
141
268
  if (requestedGraphOutputIds) {
142
- return buildOptimizedSubgraphOutputs(boundary, requestedGraphOutputIds, graphOutputs, duration, this.data.useErrorOutput);
269
+ return buildOptimizedSubgraphOutputs(callerBoundary, requestedGraphOutputIds, graphOutputs, duration, this.data.useErrorOutput);
143
270
  }
144
- const outputs = graphOutputs;
271
+ const outputs = this.data.targetProjectId ? mapSubgraphTargetOutputs(callerBoundary, graphOutputs) : graphOutputs;
145
272
  if (this.data.useErrorOutput) {
146
273
  outputs['error'] = {
147
274
  type: 'control-flow-excluded',
@@ -157,29 +284,63 @@ export class SubGraphNodeImpl extends NodeImpl {
157
284
  return outputs;
158
285
  }
159
286
  catch (err) {
287
+ runError = getError(err);
288
+ finishChildRecording?.({ type: 'error', error: runError });
160
289
  if (!this.data.useErrorOutput) {
161
290
  throw err;
162
291
  }
163
- const outputs = buildExcludedGraphBoundaryOutputs(boundary);
292
+ const outputs = buildExcludedGraphBoundaryOutputs(callerBoundary);
164
293
  outputs['error'] = {
165
294
  type: 'string',
166
- value: getError(err).message,
295
+ value: runError.message,
167
296
  };
168
297
  return outputs;
169
298
  }
299
+ finally {
300
+ if (childRecorder && recordingTarget && this.data.targetProjectId) {
301
+ try {
302
+ // Hosted editor persistence uploads the replay over HTTP. Finish that
303
+ // upload before reporting the caller run complete, so closing its tab
304
+ // immediately after completion cannot discard the called-project run.
305
+ await context.onSubgraphProjectRun?.({
306
+ target: { projectId: this.data.targetProjectId, version: this.data.targetVersion ?? 'latest' },
307
+ resolved: recordingTarget,
308
+ graphId: this.data.graphId,
309
+ recorder: childRecorder,
310
+ status: runError ? 'failed' : 'succeeded',
311
+ durationMs: Math.max(0, Date.now() - startedAt),
312
+ ...(runError ? { errorMessage: runError.message } : {}),
313
+ correlationId: context.llmProfileHealthExecutionCorrelationId,
314
+ });
315
+ }
316
+ catch (error) {
317
+ console.error('Failed to retain Subgraph project run:', error);
318
+ }
319
+ }
320
+ }
170
321
  }
171
322
  }
172
323
  export const subGraphNode = nodeDefinition(SubGraphNodeImpl, 'Subgraph');
324
+ function mapSubgraphTargetOutputs(boundary, graphOutputs) {
325
+ const targetNames = new Set(boundary.outputs.map((output) => output.id));
326
+ const outputs = Object.fromEntries(Object.entries(graphOutputs).filter(([name]) => !targetNames.has(name)));
327
+ for (const output of boundary.outputs) {
328
+ if (Object.hasOwn(graphOutputs, output.id))
329
+ outputs[output.portId] = graphOutputs[output.id];
330
+ }
331
+ return outputs;
332
+ }
173
333
  function buildOptimizedSubgraphOutputs(boundary, requestedOutputIds, graphOutputs, duration, useErrorOutput) {
174
334
  const outputs = buildExcludedGraphBoundaryOutputs(boundary);
175
335
  for (const outputId of requestedOutputIds) {
336
+ const callerPortId = boundary.outputs.find((output) => output.id === outputId)?.portId ?? outputId;
176
337
  if (Object.hasOwn(graphOutputs, outputId)) {
177
- outputs[outputId] = graphOutputs[outputId];
338
+ outputs[callerPortId] = graphOutputs[outputId];
178
339
  }
179
340
  else {
180
341
  // Missing requested values must remain missing: downstream optional inputs
181
342
  // may use defaults, whereas an excluded value would skip their node.
182
- delete outputs[outputId];
343
+ delete outputs[callerPortId];
183
344
  }
184
345
  }
185
346
  if (useErrorOutput) {
@@ -0,0 +1,106 @@
1
+ import { nanoid } from 'nanoid/non-secure';
2
+ import { NodeImpl } from '../NodeImpl.js';
3
+ import { nodeDefinition } from '../NodeDefinition.js';
4
+ import { uint8ArrayToBase64 } from '../../utils/base64.js';
5
+ async function getBytesToEncode(input) {
6
+ if (!input) {
7
+ throw new Error('No data to encode as base64');
8
+ }
9
+ if (input.type.startsWith('fn<') || input.type === 'control-flow-excluded') {
10
+ throw new Error(`Cannot encode ${input.type} as base64`);
11
+ }
12
+ const value = input.value;
13
+ if (input.type === 'binary') {
14
+ if (!(value instanceof Uint8Array))
15
+ throw new Error('Binary input must contain bytes');
16
+ return value;
17
+ }
18
+ if (input.type === 'image' || input.type === 'audio' || input.type === 'document') {
19
+ const bytes = value && typeof value === 'object' && 'data' in value ? value.data : undefined;
20
+ if (!(bytes instanceof Uint8Array))
21
+ throw new Error(`${input.type} input must contain bytes`);
22
+ return bytes;
23
+ }
24
+ if (value instanceof Uint8Array) {
25
+ return value;
26
+ }
27
+ if (value instanceof ArrayBuffer) {
28
+ return new Uint8Array(value);
29
+ }
30
+ if (ArrayBuffer.isView(value)) {
31
+ return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
32
+ }
33
+ if (typeof Blob !== 'undefined' && value instanceof Blob) {
34
+ return new Uint8Array(await value.arrayBuffer());
35
+ }
36
+ if (typeof value === 'string') {
37
+ return new TextEncoder().encode(value);
38
+ }
39
+ let json;
40
+ try {
41
+ json = JSON.stringify(value, (_key, item) => {
42
+ if (typeof item === 'number' && !Number.isFinite(item)) {
43
+ throw new Error('Non-finite numbers cannot be encoded as JSON');
44
+ }
45
+ if (item && typeof item === 'object' && !Array.isArray(item)) {
46
+ const prototype = Object.getPrototypeOf(item);
47
+ if (prototype !== null && Object.getPrototypeOf(prototype) !== null) {
48
+ throw new Error('Non-JSON objects must be converted before base64 encoding');
49
+ }
50
+ }
51
+ return item;
52
+ });
53
+ }
54
+ catch (error) {
55
+ const detail = error instanceof Error ? `: ${error.message}` : '';
56
+ throw new Error(`Cannot serialize input as JSON for base64 encoding${detail}`, { cause: error });
57
+ }
58
+ if (json === undefined) {
59
+ throw new Error(`Cannot encode ${input.type} as base64`);
60
+ }
61
+ return new TextEncoder().encode(json);
62
+ }
63
+ export class ToBase64NodeImpl extends NodeImpl {
64
+ static create() {
65
+ return {
66
+ id: nanoid(),
67
+ type: 'toBase64',
68
+ title: 'To Base64',
69
+ visualData: { x: 0, y: 0, width: 175 },
70
+ data: {},
71
+ };
72
+ }
73
+ getInputDefinitions() {
74
+ return [
75
+ {
76
+ id: 'data',
77
+ title: 'Data',
78
+ dataType: 'any',
79
+ required: true,
80
+ coerced: false,
81
+ splitRunBehavior: 'preserve-array',
82
+ },
83
+ ];
84
+ }
85
+ getOutputDefinitions() {
86
+ return [{ id: 'base64', title: 'Base64', dataType: 'string' }];
87
+ }
88
+ static getUIData() {
89
+ return {
90
+ contextMenuTitle: 'To Base64',
91
+ group: ['Text', 'Data'],
92
+ infoBoxTitle: 'To Base64 Node',
93
+ infoBoxBody: 'Encodes bytes directly, text as UTF-8, and other JSON-serializable values as UTF-8 JSON. Outputs raw base64.',
94
+ };
95
+ }
96
+ async process(inputs) {
97
+ const bytes = await getBytesToEncode(inputs['data']);
98
+ return {
99
+ ['base64']: {
100
+ type: 'string',
101
+ value: await uint8ArrayToBase64(bytes),
102
+ },
103
+ };
104
+ }
105
+ }
106
+ export const toBase64Node = nodeDefinition(ToBase64NodeImpl, 'To Base64');
@@ -15,7 +15,7 @@ export class WatchStreamingOutputNodeImpl extends NodeImpl {
15
15
  queueOverflowBehavior: streamingOutputWatchDefaults.queueOverflowBehavior,
16
16
  },
17
17
  id: nanoid(),
18
- title: 'Watch Streaming Output',
18
+ title: 'Watch streaming',
19
19
  type: 'watchStreamingOutput',
20
20
  visualData: { x: 0, y: 0, width: 230 },
21
21
  };
@@ -38,12 +38,12 @@ export class WatchStreamingOutputNodeImpl extends NodeImpl {
38
38
  }
39
39
  static getUIData() {
40
40
  return {
41
- contextMenuTitle: 'Watch Streaming Output',
42
- group: ['Logic'],
43
- infoBoxTitle: 'Watch Streaming Output Node',
41
+ contextMenuTitle: 'Watch streaming',
42
+ group: ['Streaming'],
43
+ infoBoxTitle: 'Watch streaming node',
44
44
  infoBoxBody: dedent `
45
- Runs its downstream branch for streaming output snapshots. Without Stop Watching
46
- Streaming Output, every snapshot runs the branch and the watch finishes with its
45
+ Runs its downstream branch for streaming output snapshots. Without Stop watching
46
+ streaming, every snapshot runs the branch and the watch finishes with its
47
47
  producer. Add one Stop node only when a chosen value must continue through the
48
48
  ordinary graph. Non-watched connections still wait for their upstream node's final result.
49
49
  `,
@@ -123,4 +123,4 @@ export class WatchStreamingOutputNodeImpl extends NodeImpl {
123
123
  };
124
124
  }
125
125
  }
126
- export const watchStreamingOutputNode = nodeDefinition(WatchStreamingOutputNodeImpl, 'Watch Streaming Output');
126
+ export const watchStreamingOutputNode = nodeDefinition(WatchStreamingOutputNodeImpl, 'Watch streaming');
@@ -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
+ }