@valerypopoff/rivet2-core 2.15.0 → 2.19.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 (187) hide show
  1. package/dist/cjs/bundle.cjs +7906 -3980
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/interpolationRuntime.cjs +62 -7
  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/cjs/serialization.cjs +1880 -0
  8. package/dist/cjs/serialization.cjs.map +7 -0
  9. package/dist/cjs/webAppRuntime.cjs +168 -6
  10. package/dist/cjs/webAppRuntime.cjs.map +3 -3
  11. package/dist/esm/api/createProcessor.js +5 -2
  12. package/dist/esm/api/processSettings.js +1 -0
  13. package/dist/esm/exports.js +4 -0
  14. package/dist/esm/model/AgentResponseTrace.js +99 -34
  15. package/dist/esm/model/AgentResponseTracePresentation.js +130 -0
  16. package/dist/esm/model/DataValue.js +11 -2
  17. package/dist/esm/model/GlobalVariables.js +2 -1
  18. package/dist/esm/model/GraphBoundaryCache.js +2 -1
  19. package/dist/esm/model/GraphBoundaryEffects.js +38 -1
  20. package/dist/esm/model/GraphExecutionState.js +81 -0
  21. package/dist/esm/model/GraphProcessor.js +825 -884
  22. package/dist/esm/model/GraphSchedulerBoundaryState.js +64 -0
  23. package/dist/esm/model/Nodes.js +15 -0
  24. package/dist/esm/model/ProjectBundle.js +248 -0
  25. package/dist/esm/model/ProjectBundleRuntime.js +54 -0
  26. package/dist/esm/model/SchedulerBoundaryPlanner.js +233 -0
  27. package/dist/esm/model/SplitRunProcessor.js +28 -7
  28. package/dist/esm/model/StreamingWatchTopology.js +118 -8
  29. package/dist/esm/model/SubgraphProjectTarget.js +7 -0
  30. package/dist/esm/model/SubprocessorBridge.js +125 -87
  31. package/dist/esm/model/ToolCallContinuationCoordinator.js +1 -1
  32. package/dist/esm/model/chat-v2/aiSdkBridge.js +22 -17
  33. package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -4
  34. package/dist/esm/model/chat-v2/chatV2CredentialNames.js +5 -1
  35. package/dist/esm/model/chat-v2/chatV2Outputs.js +2 -2
  36. package/dist/esm/model/chat-v2/chatV2Pipeline.js +24 -9
  37. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +3 -2
  38. package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +46 -6
  39. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +26 -1
  40. package/dist/esm/model/chat-v2/chatV2Shared.js +2 -1
  41. package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +10 -0
  42. package/dist/esm/model/chat-v2/llmChatV2Body.js +13 -10
  43. package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +5 -2
  44. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +3 -0
  45. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +33 -9
  46. package/dist/esm/model/chat-v2/llmChatV2NodeMigration.js +22 -2
  47. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +10 -2
  48. package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +17 -0
  49. package/dist/esm/model/chat-v2/llmModelCandidate.js +2 -1
  50. package/dist/esm/model/chat-v2/llmProfile.js +5 -1
  51. package/dist/esm/model/chat-v2/llmProfileBody.js +11 -2
  52. package/dist/esm/model/chat-v2/llmProfileFallback.js +7 -4
  53. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +2 -1
  54. package/dist/esm/model/chat-v2/llmProfileHealthStore.js +16 -3
  55. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +1 -1
  56. package/dist/esm/model/chat-v2/messageConverter.js +18 -16
  57. package/dist/esm/model/chat-v2/modelRegistry.js +14 -4
  58. package/dist/esm/model/chat-v2/openRouterModel.js +73 -0
  59. package/dist/esm/model/chat-v2/parallelToolCalls.js +2 -0
  60. package/dist/esm/model/chat-v2/providerOptions.js +30 -25
  61. package/dist/esm/model/chat-v2/temperature.js +9 -0
  62. package/dist/esm/model/classifier/credentials.js +42 -6
  63. package/dist/esm/model/classifier/images.js +176 -0
  64. package/dist/esm/model/classifier/json.js +57 -0
  65. package/dist/esm/model/classifier/limits.js +300 -0
  66. package/dist/esm/model/classifier/openai.js +118 -0
  67. package/dist/esm/model/classifier/perplexity.js +63 -0
  68. package/dist/esm/model/classifier/preparation.js +74 -0
  69. package/dist/esm/model/classifier/profile.js +151 -0
  70. package/dist/esm/model/classifier/profileExecution.js +294 -0
  71. package/dist/esm/model/classifier/providers.js +454 -192
  72. package/dist/esm/model/classifier/questionHelpers.js +29 -45
  73. package/dist/esm/model/classifier/questions.js +53 -0
  74. package/dist/esm/model/classifier/response.js +75 -0
  75. package/dist/esm/model/classifier/state.js +207 -0
  76. package/dist/esm/model/classifier/types.js +11 -1
  77. package/dist/esm/model/nodeRunFailure.js +54 -0
  78. package/dist/esm/model/nodes/CallGraphNode.js +6 -0
  79. package/dist/esm/model/nodes/CatchStreamingChunksNode.js +42 -0
  80. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +385 -154
  81. package/dist/esm/model/nodes/ClassifierProfileNode.js +133 -0
  82. package/dist/esm/model/nodes/ClassifierQuestionNode.js +59 -15
  83. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +1 -1
  84. package/dist/esm/model/nodes/GetGlobalNode.js +2 -2
  85. package/dist/esm/model/nodes/HttpCallNode.js +44 -75
  86. package/dist/esm/model/nodes/ImageNode.js +44 -3
  87. package/dist/esm/model/nodes/LLMChatV2Node.js +26 -4
  88. package/dist/esm/model/nodes/ObjectNode.js +29 -18
  89. package/dist/esm/model/nodes/PromptNode.js +2 -1
  90. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +4 -1
  91. package/dist/esm/model/nodes/SetGlobalNode.js +5 -3
  92. package/dist/esm/model/nodes/StopWatchingStreamingOutputNode.js +8 -8
  93. package/dist/esm/model/nodes/StreamValueNode.js +38 -0
  94. package/dist/esm/model/nodes/SubGraphNode.js +199 -35
  95. package/dist/esm/model/nodes/ToBase64Node.js +106 -0
  96. package/dist/esm/model/nodes/WatchStreamingOutputNode.js +7 -7
  97. package/dist/esm/model/nodes/toolCallDelegation.js +5 -1
  98. package/dist/esm/model/profileSuspensionHints.js +8 -0
  99. package/dist/esm/recording/ExecutionRecorder.js +26 -0
  100. package/dist/esm/serialization.js +2 -0
  101. package/dist/esm/utils/base64.js +18 -15
  102. package/dist/esm/utils/coerceType.js +11 -1
  103. package/dist/esm/utils/errors.js +41 -0
  104. package/dist/esm/utils/interpolation.js +44 -22
  105. package/dist/esm/utils/interpolationSyntax.js +15 -6
  106. package/dist/esm/utils/serialization/serialization.js +3 -2
  107. package/dist/esm/utils/serialization/serializationUtils.js +6 -0
  108. package/dist/esm/utils/serialization/serialization_v4.js +15 -3
  109. package/dist/esm/webAppRuntime.js +1 -0
  110. package/dist/types/api/createProcessor.d.ts +7 -1
  111. package/dist/types/exports.d.ts +4 -0
  112. package/dist/types/model/AgentResponseTrace.d.ts +15 -4
  113. package/dist/types/model/AgentResponseTracePresentation.d.ts +15 -0
  114. package/dist/types/model/CycleDetector.d.ts +1 -2
  115. package/dist/types/model/DataValue.d.ts +12 -8
  116. package/dist/types/model/ExecutorProtocol.d.ts +9 -0
  117. package/dist/types/model/GraphBoundaryCache.d.ts +2 -0
  118. package/dist/types/model/GraphBoundaryEffects.d.ts +10 -1
  119. package/dist/types/model/GraphExecutionState.d.ts +68 -0
  120. package/dist/types/model/GraphProcessor.d.ts +2 -0
  121. package/dist/types/model/GraphSchedulerBoundaryState.d.ts +96 -0
  122. package/dist/types/model/Nodes.d.ts +11 -4
  123. package/dist/types/model/ProcessContext.d.ts +24 -3
  124. package/dist/types/model/ProjectBundle.d.ts +59 -0
  125. package/dist/types/model/ProjectBundleRuntime.d.ts +24 -0
  126. package/dist/types/model/ProjectReferenceLoader.d.ts +3 -0
  127. package/dist/types/model/RivetUIContext.d.ts +1 -1
  128. package/dist/types/model/SchedulerBoundaryPlanner.d.ts +42 -0
  129. package/dist/types/model/Settings.d.ts +1 -0
  130. package/dist/types/model/StreamingWatchTopology.d.ts +11 -1
  131. package/dist/types/model/SubgraphProjectTarget.d.ts +38 -0
  132. package/dist/types/model/SubprocessorBridge.d.ts +2 -0
  133. package/dist/types/model/chat-v2/chatV2CredentialNames.d.ts +4 -0
  134. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +1 -1
  135. package/dist/types/model/chat-v2/chatV2ProviderRegistry.d.ts +79 -1
  136. package/dist/types/model/chat-v2/chatV2ProviderTypes.d.ts +1 -1
  137. package/dist/types/model/chat-v2/chatV2Shared.d.ts +1 -1
  138. package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +2 -0
  139. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +4 -1
  140. package/dist/types/model/chat-v2/llmChatV2NodeMigration.d.ts +3 -1
  141. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +2 -0
  142. package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +2 -0
  143. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +51 -3
  144. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +10 -7
  145. package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +6 -2
  146. package/dist/types/model/chat-v2/modelRegistry.d.ts +5 -4
  147. package/dist/types/model/chat-v2/openRouterModel.d.ts +2 -0
  148. package/dist/types/model/chat-v2/providerOptions.d.ts +2 -13
  149. package/dist/types/model/chat-v2/temperature.d.ts +2 -0
  150. package/dist/types/model/classifier/credentials.d.ts +7 -1
  151. package/dist/types/model/classifier/images.d.ts +18 -0
  152. package/dist/types/model/classifier/json.d.ts +19 -0
  153. package/dist/types/model/classifier/limits.d.ts +45 -0
  154. package/dist/types/model/classifier/openai.d.ts +5 -0
  155. package/dist/types/model/classifier/perplexity.d.ts +7 -0
  156. package/dist/types/model/classifier/preparation.d.ts +16 -0
  157. package/dist/types/model/classifier/profile.d.ts +46 -0
  158. package/dist/types/model/classifier/profileExecution.d.ts +32 -0
  159. package/dist/types/model/classifier/providers.d.ts +98 -9
  160. package/dist/types/model/classifier/questionHelpers.d.ts +6 -4
  161. package/dist/types/model/classifier/questions.d.ts +4 -0
  162. package/dist/types/model/classifier/response.d.ts +4 -0
  163. package/dist/types/model/classifier/state.d.ts +37 -0
  164. package/dist/types/model/classifier/types.d.ts +11 -0
  165. package/dist/types/model/nodeRunFailure.d.ts +13 -0
  166. package/dist/types/model/nodes/CatchStreamingChunksNode.d.ts +20 -0
  167. package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +17 -12
  168. package/dist/types/model/nodes/ClassifierProfileNode.d.ts +20 -0
  169. package/dist/types/model/nodes/GetGlobalNode.d.ts +7 -0
  170. package/dist/types/model/nodes/ImageNode.d.ts +4 -0
  171. package/dist/types/model/nodes/LLMChatV2Node.d.ts +1 -0
  172. package/dist/types/model/nodes/ObjectNode.d.ts +2 -1
  173. package/dist/types/model/nodes/StreamValueNode.d.ts +14 -0
  174. package/dist/types/model/nodes/SubGraphNode.d.ts +21 -2
  175. package/dist/types/model/nodes/ToBase64Node.d.ts +12 -0
  176. package/dist/types/model/nodes/toolCallDelegation.d.ts +3 -1
  177. package/dist/types/model/profileSuspensionHints.d.ts +8 -0
  178. package/dist/types/recording/ExecutionRecorder.d.ts +8 -2
  179. package/dist/types/serialization.d.ts +2 -0
  180. package/dist/types/utils/base64.d.ts +1 -1
  181. package/dist/types/utils/errors.d.ts +4 -0
  182. package/dist/types/utils/interpolation.d.ts +13 -2
  183. package/dist/types/utils/interpolationSyntax.d.ts +1 -1
  184. package/dist/types/utils/serialization/serialization.d.ts +3 -1
  185. package/dist/types/utils/serialization/serializationUtils.d.ts +1 -0
  186. package/dist/types/webAppRuntime.d.ts +1 -0
  187. package/package.json +7 -1
@@ -1,5 +1,5 @@
1
1
  import { max, range } from 'lodash-es';
2
- import { isArrayDataValue, arrayizeDataValue, } from './DataValue.js';
2
+ import { isArrayDataValue, arrayizeDataValue } from './DataValue.js';
3
3
  import {} from './NodeBase.js';
4
4
  import { getGraphAbortReasonFromError, isAbortLikeError } from './GraphAbortReasons.js';
5
5
  import { getError } from '../utils/errors.js';
@@ -84,7 +84,13 @@ async function runSequential(node, inputValues, inputDefinitionsById, splittingA
84
84
  resultOrigin = 'editor-cache';
85
85
  });
86
86
  deps.accumulateCost(output);
87
- results.push({ type: 'output', index: i, output, resultOrigin, durationMs: deps.finishNodeTiming?.(splitTimingStart) });
87
+ results.push({
88
+ type: 'output',
89
+ index: i,
90
+ output,
91
+ resultOrigin,
92
+ durationMs: deps.finishNodeTiming?.(splitTimingStart),
93
+ });
88
94
  }
89
95
  catch (error) {
90
96
  results.push({
@@ -183,13 +189,28 @@ function splitInputsAtIndex(inputValues, inputDefinitionsById, index) {
183
189
  ]));
184
190
  }
185
191
  function aggregateOutputs(results) {
186
- return results.reduce((acc, result) => {
192
+ const ports = new Map();
193
+ results.forEach((result, index) => {
187
194
  for (const [portId, value] of entries(result.output)) {
188
- acc[portId] ??= { type: (value?.type + '[]'), value: [] };
189
- acc[portId].value.push(value?.value);
195
+ const id = portId;
196
+ const aggregate = ports.get(id) ?? { values: [] };
197
+ // Exclusion is not a value type. Infer from a real item regardless of
198
+ // whether the first split item succeeded or returned a caught failure.
199
+ if (value?.type !== 'control-flow-excluded')
200
+ aggregate.type ??= value?.type;
201
+ aggregate.values[index] = value?.value;
202
+ ports.set(id, aggregate);
190
203
  }
191
- return acc;
192
- }, {});
204
+ });
205
+ return fromEntries([...ports].map(([id, aggregate]) => [
206
+ id,
207
+ aggregate.type == null
208
+ ? { type: 'control-flow-excluded', value: undefined }
209
+ : {
210
+ type: `${aggregate.type}[]`,
211
+ value: Array.from({ length: results.length }, (_, index) => aggregate.values[index]),
212
+ },
213
+ ]));
193
214
  }
194
215
  function isSplitOutputResult(result) {
195
216
  return result.type === 'output';
@@ -1,6 +1,49 @@
1
1
  import { canRenderDataBusNode, getDataBusInputChannelIndex, getDataBusOutputChannelIndex } from './DataBusTopology.js';
2
2
  import { resolveNodePrefabInstance } from './NodePrefabResolver.js';
3
+ import { getSubgraphTargetBoundaryChange, reconcileSubgraphTargetBoundary } from './nodes/SubGraphNode.js';
4
+ import { getGraphBoundary } from './GraphBoundaryCache.js';
3
5
  import { createGraphOutputSelection } from './GraphOutputSelection.js';
6
+ import { getSubgraphProjectKey } from './SubgraphProjectTarget.js';
7
+ import { nanoid } from 'nanoid/non-secure';
8
+ /** Only ports that can publish live partials receive streaming wire markers. */
9
+ function canEmitStreamingOutput(node, outputId) {
10
+ const data = node.data;
11
+ switch (node.type) {
12
+ case 'streamValue':
13
+ return outputId === 'value';
14
+ case 'llmChatV2':
15
+ return data.useAsGraphPartialOutput === true &&
16
+ ['response', 'in-messages', 'all-messages', 'function-calls', 'reasoning'].includes(outputId);
17
+ case 'chatAnthropic':
18
+ return ['response', 'all-messages', 'function-calls', 'citations'].includes(outputId);
19
+ case 'chatGoogle':
20
+ return ['response', 'function-calls'].includes(outputId);
21
+ case 'chatHuggingFace':
22
+ return outputId === 'output';
23
+ case 'loopUntil':
24
+ return outputId !== 'iteration' && outputId !== 'completed';
25
+ default:
26
+ return false;
27
+ }
28
+ }
29
+ function getCallerProject(owner, caller, projects) {
30
+ if (caller.type === 'referencedGraphAlias')
31
+ return projects[caller.data.projectId];
32
+ if (!caller.data.targetProjectId)
33
+ return owner;
34
+ return projects[getSubgraphProjectKey({
35
+ projectId: caller.data.targetProjectId,
36
+ version: caller.data.targetVersion ?? 'latest',
37
+ })];
38
+ }
39
+ function getCallerBoundary(caller, target) {
40
+ if (caller.type !== 'subGraph')
41
+ return undefined;
42
+ const actual = getGraphBoundary(target, caller.data.graphId);
43
+ if (!actual || getSubgraphTargetBoundaryChange(caller.data.targetBoundary, actual))
44
+ return undefined;
45
+ return reconcileSubgraphTargetBoundary(caller.data.targetBoundary, actual);
46
+ }
4
47
  /** An executing caller may forward outputs after its condition has passed. */
5
48
  export function canForwardGraphCallerOutputPartials(node) {
6
49
  return ((node.type === 'subGraph' || node.type === 'referencedGraphAlias') &&
@@ -29,7 +72,7 @@ export function canForwardGraphOutputPartials(graphOutput, sourceNode, graphOutp
29
72
  !graphOutputIsFrozen);
30
73
  }
31
74
  /** Trace Watch demand through named boundaries without making ordinary nodes repeatable. */
32
- export function getProjectStreamingOutputWatchConnections({ project, graph, referencedProjects, registry, frozenNodeOutputs = {}, isNodeFrozen, fullGraphCallers, }) {
75
+ export function getProjectStreamingOutputWatchConnections({ project, graph, referencedProjects, registry, frozenNodeOutputs = {}, isNodeFrozen, fullGraphCallers, getPreviewGraphOutputStreamingCapability, onlyStreamCapableSources = false, }) {
33
76
  // Unsaved active graph edits must take precedence over the stored project graph.
34
77
  const currentProject = {
35
78
  ...project,
@@ -96,7 +139,7 @@ export function getProjectStreamingOutputWatchConnections({ project, graph, refe
96
139
  if (node.disabled || isFrozen(context.project, parent, node) || !canStreamThroughGraphCaller(node))
97
140
  continue;
98
141
  const caller = node;
99
- const owner = caller.type === 'subGraph' ? context.project : projects[caller.data.projectId];
142
+ const owner = getCallerProject(context.project, caller, projects);
100
143
  const child = owner?.graphs[caller.data.graphId];
101
144
  if (!child)
102
145
  continue;
@@ -106,12 +149,13 @@ export function getProjectStreamingOutputWatchConnections({ project, graph, refe
106
149
  !caller.data.useAsGraphPartialOutput &&
107
150
  !(parent === graph && fullGraphCallers?.has(caller.id))) {
108
151
  const childContext = contexts.get(child);
152
+ const callerBoundary = getCallerBoundary(caller, owner);
109
153
  const outputNames = new Set(Object.values(childContext.nodes)
110
154
  .filter((node) => node.type === 'graphOutput')
111
155
  .map((node) => node.data.id));
112
156
  const outputs = parent.connections
113
157
  .filter((edge) => edge.outputNodeId === caller.id)
114
- .map((edge) => edge.outputId)
158
+ .map((edge) => callerBoundary?.outputs.find((output) => output.portId === edge.outputId)?.id ?? edge.outputId)
115
159
  .filter((id) => outputNames.has(id));
116
160
  try {
117
161
  selected = createGraphOutputSelection({ ...child, nodes: Object.values(childContext.nodes) }, outputs, (node) => childContext.incoming(node.id).map((edge) => childContext.nodes[edge.outputNodeId])).nodeIds;
@@ -128,7 +172,9 @@ export function getProjectStreamingOutputWatchConnections({ project, graph, refe
128
172
  const watchInputs = [];
129
173
  for (const [candidate, context] of contexts) {
130
174
  for (const node of Object.values(context.nodes)) {
131
- if (node.type !== 'watchStreamingOutput' || node.disabled || isFrozen(context.project, candidate, node))
175
+ if ((node.type !== 'watchStreamingOutput' && node.type !== 'catchStreamingChunks') ||
176
+ node.disabled ||
177
+ isFrozen(context.project, candidate, node))
132
178
  continue;
133
179
  const inputs = context.incoming(node.id).filter((edge) => edge.inputId === 'stream');
134
180
  // Multiple providers are rejected by the Watch scheduler, not multiple streams.
@@ -170,10 +216,11 @@ export function getProjectStreamingOutputWatchConnections({ project, graph, refe
170
216
  for (const parent of callers.get(candidate) ?? []) {
171
217
  if (parent.selected && !parent.selected.has(edge.inputNodeId))
172
218
  continue;
219
+ const callerPortId = getCallerBoundary(parent.node, context.project)?.inputs.find((input) => input.nodeId === source.id)?.portId ?? inputName;
173
220
  const inputs = contexts
174
221
  .get(parent.graph)
175
222
  .incoming(parent.node.id)
176
- .filter((input) => input.inputId === inputName);
223
+ .filter((input) => input.inputId === callerPortId);
177
224
  // Ambiguous authored inputs stay final-only even though ordinary
178
225
  // execution retains its established first-provider projection.
179
226
  if (inputs.length === 1 && trace(parent.graph, inputs[0]))
@@ -185,23 +232,35 @@ export function getProjectStreamingOutputWatchConnections({ project, graph, refe
185
232
  return true;
186
233
  }
187
234
  if (source.type !== 'subGraph' && source.type !== 'referencedGraphAlias') {
235
+ if (onlyStreamCapableSources && !canEmitStreamingOutput(source, edge.outputId))
236
+ return false;
188
237
  context.marked.add(edge);
189
238
  return true;
190
239
  }
191
240
  if (!canForwardGraphCallerOutputPartials(source))
192
241
  return false;
193
242
  const caller = source;
194
- const childProject = caller.type === 'subGraph' ? context.project : projects[caller.data.projectId];
243
+ const childProject = getCallerProject(context.project, caller, projects);
195
244
  const child = childProject?.graphs[caller.data.graphId];
196
245
  const childContext = child && contexts.get(child);
197
- if (!child || !childContext)
246
+ if (!childProject || !child || !childContext)
198
247
  return false;
199
- const outputs = Object.values(childContext.nodes).filter((node) => node.type === 'graphOutput' && !node.disabled && node.data.id === edge.outputId);
248
+ const targetOutputId = getCallerBoundary(caller, childProject)?.outputs.find((output) => output.portId === edge.outputId)?.id ??
249
+ edge.outputId;
250
+ const outputs = Object.values(childContext.nodes).filter((node) => node.type === 'graphOutput' && !node.disabled && node.data.id === targetOutputId);
200
251
  // Duplicate names have first-final-winner semantics, so cannot relay partials.
201
252
  if (outputs.length !== 1)
202
253
  return false;
203
254
  const output = outputs[0];
204
255
  const outputIsFrozen = isFrozen(childProject, child, output);
256
+ const previewCapability = getPreviewGraphOutputStreamingCapability?.(childProject, child, output.id);
257
+ if (previewCapability !== undefined) {
258
+ if (previewCapability && !outputIsFrozen && !output.isConditional && !output.isSplitRun) {
259
+ context.marked.add(edge);
260
+ return true;
261
+ }
262
+ return false;
263
+ }
205
264
  const providers = childContext.incoming(output.id).filter((input) => input.inputId === 'value');
206
265
  // As in GraphProcessor's effective connection projection, the first
207
266
  // valid provider owns a single-input Graph Output in a malformed graph.
@@ -226,3 +285,54 @@ export function getProjectStreamingOutputWatchConnections({ project, graph, refe
226
285
  trace(candidate, edge);
227
286
  return contexts.get(graph)?.marked ?? new Set();
228
287
  }
288
+ /** Derive safe boundary capability hints for every graph in one topology pass. */
289
+ export function getProjectStreamableGraphOutputNodeIdsByGraph({ project, referencedProjects, registry, }) {
290
+ // Graph IDs come from project files; keep unusual keys such as __proto__
291
+ // as data rather than assigning through Object.prototype.
292
+ const result = Object.create(null);
293
+ const nodes = [];
294
+ const probes = [];
295
+ for (const [graphId] of Object.entries(project.graphs)) {
296
+ result[graphId] = [];
297
+ const boundary = getGraphBoundary(project, graphId);
298
+ if (!boundary?.outputs.length)
299
+ continue;
300
+ const callerId = nanoid();
301
+ nodes.push({ id: callerId, type: 'subGraph', title: 'Probe', data: { graphId }, visualData: { x: 0, y: 0 } });
302
+ for (const output of boundary.outputs) {
303
+ const watchId = nanoid();
304
+ nodes.push({ id: watchId, type: 'watchStreamingOutput', title: 'Probe watch', data: {}, visualData: { x: 0, y: 0 } });
305
+ probes.push({
306
+ graphId,
307
+ outputNodeId: output.nodeId,
308
+ connection: {
309
+ outputNodeId: callerId,
310
+ outputId: output.portId,
311
+ inputNodeId: watchId,
312
+ inputId: 'stream',
313
+ },
314
+ });
315
+ }
316
+ }
317
+ if (probes.length === 0)
318
+ return result;
319
+ const probeGraphId = nanoid();
320
+ const probeGraph = {
321
+ metadata: { id: probeGraphId, name: 'Streaming preview probe' },
322
+ nodes,
323
+ connections: probes.map(({ connection }) => connection),
324
+ };
325
+ const probeProject = { ...project, graphs: { ...project.graphs, [probeGraphId]: probeGraph } };
326
+ const marked = getProjectStreamingOutputWatchConnections({
327
+ project: probeProject,
328
+ graph: probeGraph,
329
+ referencedProjects,
330
+ registry,
331
+ onlyStreamCapableSources: true,
332
+ });
333
+ for (const { graphId, outputNodeId, connection } of probes) {
334
+ if (marked.has(connection))
335
+ result[graphId].push(outputNodeId);
336
+ }
337
+ return result;
338
+ }
@@ -0,0 +1,7 @@
1
+ /** Internal definition key; not a project metadata ID or a persisted reference. */
2
+ export function getSubgraphProjectKey(target) {
3
+ return `\u0000rivet-subgraph:${target.version}:${encodeURIComponent(target.projectId)}`;
4
+ }
5
+ export function isSubgraphProjectKey(key) {
6
+ return key.startsWith('\u0000rivet-subgraph:');
7
+ }
@@ -1,23 +1,72 @@
1
1
  import { getGraphAbortReasonFromSignal } from './GraphAbortReasons.js';
2
+ import { logRuntimeWarn } from '../utils/runtimeLogging.js';
3
+ /** Drain before invoking disposers so cleanup is exhaustive and reentrant/idempotent. */
4
+ function releaseSubscriptions(...groups) {
5
+ const errors = [];
6
+ const subscriptions = groups.flatMap((group) => group.splice(0));
7
+ for (const unsubscribe of subscriptions) {
8
+ try {
9
+ unsubscribe();
10
+ }
11
+ catch (error) {
12
+ errors.push(error);
13
+ }
14
+ }
15
+ if (errors.length)
16
+ throw new AggregateError(errors, 'Failed to release child execution subscriptions');
17
+ }
18
+ function rollbackSubscriptions(error, ...groups) {
19
+ try {
20
+ releaseSubscriptions(...groups);
21
+ }
22
+ catch {
23
+ // Setup failure remains authoritative; every acquired disposer was attempted.
24
+ }
25
+ throw error;
26
+ }
27
+ /** Cleanup must not replace an execution/setup failure already being propagated. */
28
+ export function cleanupSubprocessorBindings(lifecycle, events, executionFailed) {
29
+ try {
30
+ releaseSubscriptions(lifecycle ? [lifecycle] : [], events ? [events] : []);
31
+ }
32
+ catch (error) {
33
+ if (!executionFailed)
34
+ throw error;
35
+ // Disposer errors may contain authored data. Keep secondary failure visible
36
+ // without logging messages or changing the primary Error identity.
37
+ try {
38
+ logRuntimeWarn('Child execution cleanup failed after an execution or setup failure.', {
39
+ failedBindings: error instanceof AggregateError ? error.errors.length : 1,
40
+ });
41
+ }
42
+ catch {
43
+ // A host-provided logger must not replace the primary failure either.
44
+ }
45
+ }
46
+ }
2
47
  function subscribeOwnGraphRunLifecycle(processor, onLifecycleEvent) {
3
48
  let ownGraphRunId;
4
- const unsubscribeGraphStart = processor.on('graphStart', (event) => {
5
- ownGraphRunId ??= event.execution.graphRunId;
6
- });
7
- const onPossibleLifecycleEvent = (event) => {
49
+ const onPossibleLifecycleEvent = (event, executionFailed) => {
8
50
  if (ownGraphRunId != null && event.execution.graphRunId === ownGraphRunId) {
9
- onLifecycleEvent();
51
+ if (executionFailed)
52
+ cleanupSubprocessorBindings(onLifecycleEvent, undefined, true);
53
+ else
54
+ onLifecycleEvent();
10
55
  }
11
56
  };
12
- const unsubscribeGraphFinish = processor.on('graphFinish', onPossibleLifecycleEvent);
13
- const unsubscribeGraphAbort = processor.on('graphAbort', onPossibleLifecycleEvent);
14
- const unsubscribeGraphError = processor.on('graphError', onPossibleLifecycleEvent);
15
- return () => {
16
- unsubscribeGraphStart();
17
- unsubscribeGraphFinish();
18
- unsubscribeGraphAbort();
19
- unsubscribeGraphError();
20
- };
57
+ const subscriptions = [];
58
+ try {
59
+ subscriptions.push(processor.on('graphStart', (event) => {
60
+ ownGraphRunId ??= event.execution.graphRunId;
61
+ }));
62
+ subscriptions.push(processor.on('graphFinish', (event) => onPossibleLifecycleEvent(event, false)));
63
+ subscriptions.push(processor.on('graphAbort', (event) => onPossibleLifecycleEvent(event, !event.successful)));
64
+ subscriptions.push(processor.on('graphError', (event) => onPossibleLifecycleEvent(event, true)));
65
+ }
66
+ catch (error) {
67
+ rollbackSubscriptions(error, subscriptions);
68
+ }
69
+ return () => releaseSubscriptions(subscriptions);
21
70
  }
22
71
  export function wireSubprocessorEvents(processor, parentEmitter, parentState) {
23
72
  const forward = (event, data) => {
@@ -33,60 +82,54 @@ export function wireSubprocessorEvents(processor, parentEmitter, parentState) {
33
82
  // graph-level terminal event. Keep passive forwarding alive for the
34
83
  // subprocessor object lifetime so remote-debugger/recorder consumers do not
35
84
  // miss those node terminals.
36
- const passiveUnsubscribers = [
37
- processor.on('nodeError', (event) => forward('nodeError', event)),
38
- processor.on('nodeFinish', (event) => forward('nodeFinish', event)),
39
- processor.on('partialOutput', (event) => forward('partialOutput', event)),
40
- processor.on('progress', (event) => forward('progress', event)),
41
- processor.on('llmCallFinished', (event) => forward('llmCallFinished', event)),
42
- processor.on('llmChatOutputSnapshot', (event) => forward('llmChatOutputSnapshot', event)),
43
- processor.on('llmProfileAttempt', (event) => forward('llmProfileAttempt', event)),
44
- processor.on('toolCallFinished', (event) => forward('toolCallFinished', event)),
45
- processor.on('nodeExcluded', (event) => forward('nodeExcluded', event)),
46
- processor.on('nodeStart', (event) => forward('nodeStart', event)),
47
- processor.on('graphAbort', (event) => forward('graphAbort', event)),
48
- processor.on('graphError', (event) => forward('graphError', event)),
49
- processor.on('userInput', (event) => forward('userInput', event)),
50
- processor.on('graphStart', (event) => forward('graphStart', event)),
51
- processor.on('graphFinish', (event) => forward('graphFinish', event)),
52
- processor.on('nodeOutputsCleared', (event) => forward('nodeOutputsCleared', event)),
53
- processor.on('streamingOutputWatchSummary', (event) => forward('streamingOutputWatchSummary', event)),
54
- processor.on('globalSet', (event) => forward('globalSet', event)),
55
- processor.on('newAbortController', (event) => forward('newAbortController', event)),
56
- ];
57
- const controlUnsubscribers = [
58
- processor.on('pause', () => {
59
- if (!parentState.isPaused()) {
85
+ const passiveUnsubscribers = [];
86
+ const controlUnsubscribers = [];
87
+ const cleanupControls = () => releaseSubscriptions(controlUnsubscribers);
88
+ try {
89
+ const passiveEvents = [
90
+ 'nodeError',
91
+ 'nodeFinish',
92
+ 'partialOutput',
93
+ 'progress',
94
+ 'llmCallFinished',
95
+ 'llmChatOutputSnapshot',
96
+ 'llmProfileAttempt',
97
+ 'toolCallFinished',
98
+ 'nodeExcluded',
99
+ 'nodeStart',
100
+ 'graphAbort',
101
+ 'graphError',
102
+ 'userInput',
103
+ 'graphStart',
104
+ 'graphFinish',
105
+ 'nodeOutputsCleared',
106
+ 'streamingOutputWatchSummary',
107
+ 'globalSet',
108
+ 'newAbortController',
109
+ ];
110
+ for (const event of passiveEvents) {
111
+ passiveUnsubscribers.push(processor.on(event, (data) => forward(event, data)));
112
+ }
113
+ controlUnsubscribers.push(processor.on('pause', () => {
114
+ if (!parentState.isPaused())
60
115
  parentState.pause();
61
- }
62
- }),
63
- processor.on('resume', () => {
64
- if (parentState.isPaused()) {
116
+ }));
117
+ controlUnsubscribers.push(processor.on('resume', () => {
118
+ if (parentState.isPaused())
65
119
  parentState.resume();
66
- }
67
- }),
68
- ];
69
- const unsubscribeAny = processor.onAny((event, data) => {
70
- if (event.startsWith('globalSet:')) {
71
- void forward(event, data);
72
- }
73
- });
74
- let controlsCleanedUp = false;
75
- const cleanupControls = () => {
76
- if (controlsCleanedUp) {
77
- return;
120
+ }));
121
+ passiveUnsubscribers.push(processor.onAny((event, data) => {
122
+ if (event.startsWith('globalSet:'))
123
+ void forward(event, data);
124
+ }));
125
+ if (parentState.autoCleanup !== false) {
126
+ controlUnsubscribers.push(subscribeOwnGraphRunLifecycle(processor, cleanupControls));
78
127
  }
79
- controlsCleanedUp = true;
80
- controlUnsubscribers.forEach((unsubscribe) => unsubscribe());
81
- };
82
- if (parentState.autoCleanup !== false) {
83
- controlUnsubscribers.push(subscribeOwnGraphRunLifecycle(processor, cleanupControls));
84
128
  }
85
- return () => {
86
- cleanupControls();
87
- passiveUnsubscribers.forEach((unsubscribe) => unsubscribe());
88
- unsubscribeAny();
89
- };
129
+ catch (error) {
130
+ rollbackSubscriptions(error, controlUnsubscribers, passiveUnsubscribers);
131
+ }
132
+ return () => releaseSubscriptions(controlUnsubscribers, passiveUnsubscribers);
90
133
  }
91
134
  export function wireSubprocessorLifecycle(processor, options) {
92
135
  let unsubscribePendingAbort;
@@ -115,31 +158,26 @@ export function wireSubprocessorLifecycle(processor, options) {
115
158
  const resumeProcessor = () => {
116
159
  void processor.resume();
117
160
  };
118
- options.signal?.addEventListener('abort', abortFromSignal, { once: true });
119
- options.parentAbortSignal.addEventListener('abort', abortFromParent, { once: true });
120
- const unsubscribers = [
121
- () => options.signal?.removeEventListener('abort', abortFromSignal),
122
- () => options.parentAbortSignal.removeEventListener('abort', abortFromParent),
123
- () => unsubscribePendingAbort?.(),
124
- options.onParentPause(pauseProcessor),
125
- options.onParentResume(resumeProcessor),
126
- ];
127
- let cleanedUp = false;
128
- const cleanup = () => {
129
- if (cleanedUp) {
130
- return;
161
+ const unsubscribers = [];
162
+ const cleanup = () => releaseSubscriptions(unsubscribers);
163
+ try {
164
+ options.signal?.addEventListener('abort', abortFromSignal, { once: true });
165
+ unsubscribers.push(() => options.signal?.removeEventListener('abort', abortFromSignal));
166
+ options.parentAbortSignal.addEventListener('abort', abortFromParent, { once: true });
167
+ unsubscribers.push(() => options.parentAbortSignal.removeEventListener('abort', abortFromParent));
168
+ unsubscribers.push(() => unsubscribePendingAbort?.());
169
+ unsubscribers.push(options.onParentPause(pauseProcessor));
170
+ unsubscribers.push(options.onParentResume(resumeProcessor));
171
+ if (options.autoCleanup !== false) {
172
+ unsubscribers.push(subscribeOwnGraphRunLifecycle(processor, cleanup));
131
173
  }
132
- cleanedUp = true;
133
- unsubscribers.forEach((unsubscribe) => unsubscribe());
134
- };
135
- if (options.autoCleanup !== false) {
136
- unsubscribers.push(subscribeOwnGraphRunLifecycle(processor, cleanup));
137
- }
138
- if (options.signal?.aborted) {
139
- abortFromSignal();
174
+ if (options.signal?.aborted)
175
+ abortFromSignal();
176
+ else if (options.parentAbortSignal.aborted)
177
+ abortFromParent();
140
178
  }
141
- else if (options.parentAbortSignal.aborted) {
142
- abortFromParent();
179
+ catch (error) {
180
+ rollbackSubscriptions(error, unsubscribers);
143
181
  }
144
182
  return cleanup;
145
183
  }
@@ -150,7 +150,7 @@ export class ToolCallContinuationCoordinator {
150
150
  if (nodeAbortController.signal.aborted) {
151
151
  throw createGraphAbortErrorFromSignal(nodeAbortController.signal, 'Delegate Tool Call aborted');
152
152
  }
153
- const outputs = buildDelegatedToolCallOutputs([toolResult.record], hasAssistantMessage ? assistantMessage : undefined, toolResult.cost);
153
+ const outputs = buildDelegatedToolCallOutputs([toolResult.record], hasAssistantMessage ? assistantMessage : undefined, toolResult.cost, toolResult.costBreakdown);
154
154
  this.#adapter.accumulateCost(outputs);
155
155
  await this.#adapter.emitDelegateFinish(delegateNode, outputs, processId, timingStart);
156
156
  delegateFinished = true;
@@ -2,6 +2,7 @@ import { generateText, NoObjectGeneratedError, streamText } from 'ai';
2
2
  import { consumeAiSdkStream } from '../chat/aiSdkStreaming.js';
3
3
  import { ChatV2ProviderTimeoutError } from './chatV2Types.js';
4
4
  import { isChatV2StructuredResponseFormat } from './chatV2ResponseFormat.js';
5
+ import { normalizeTemperature } from './temperature.js';
5
6
  function keepPromiseHandled(value) {
6
7
  const promise = Promise.resolve(value);
7
8
  void promise.catch(() => undefined);
@@ -64,7 +65,7 @@ async function resolveGenerateStructuredOutput(result, responseOutput, finishRea
64
65
  return undefined;
65
66
  }
66
67
  }
67
- function recoverGenerateStructuredOutputError(error, options, toolCalls) {
68
+ function recoverGenerateStructuredOutputError(error, options, evidence) {
68
69
  if (options.responseOutput == null || !isChatV2StructuredResponseFormat(options.responseFormat)) {
69
70
  return undefined;
70
71
  }
@@ -79,25 +80,28 @@ function recoverGenerateStructuredOutputError(error, options, toolCalls) {
79
80
  return {
80
81
  responseText,
81
82
  structuredOutput: undefined,
82
- functionCalls: toStreamedFunctionCalls(toolCalls),
83
+ functionCalls: toStreamedFunctionCalls(evidence.toolCalls),
83
84
  usage: error.usage,
84
85
  reasoning: '',
85
86
  finishReason: error.finishReason == null ? undefined : String(error.finishReason),
86
- providerMetadata: undefined,
87
+ // Output parsing runs after onStepFinish. Keep the actual provider billing
88
+ // metadata even when the SDK rejects the generated structured value.
89
+ providerMetadata: evidence.providerMetadata,
87
90
  requestStatus: undefined,
88
91
  };
89
92
  }
90
- function attachGenerateStepToolCallCollector(args) {
91
- const toolCalls = [];
93
+ function attachGenerateStepCollector(args) {
94
+ const evidence = { toolCalls: [] };
92
95
  const previousOnStepFinish = args.onStepFinish;
93
96
  args.onStepFinish = async (event) => {
94
- const stepToolCalls = event.toolCalls;
95
- if (stepToolCalls != null) {
96
- toolCalls.push(...stepToolCalls);
97
+ const step = event;
98
+ if (step.toolCalls != null) {
99
+ evidence.toolCalls.push(...step.toolCalls);
97
100
  }
101
+ evidence.providerMetadata = step.providerMetadata;
98
102
  await previousOnStepFinish?.(event);
99
103
  };
100
- return toolCalls;
104
+ return evidence;
101
105
  }
102
106
  function collapseRepeatedStructuredJsonText(responseText) {
103
107
  if (responseText.length === 0 || responseText.length % 2 !== 0) {
@@ -130,8 +134,9 @@ function buildTextArgs(options) {
130
134
  args.tools = options.tools;
131
135
  if (options.maxTokens !== undefined)
132
136
  args.maxOutputTokens = options.maxTokens;
133
- if (options.temperature !== undefined)
134
- args.temperature = options.temperature;
137
+ const temperature = normalizeTemperature(options.temperature);
138
+ if (temperature !== undefined)
139
+ args.temperature = temperature;
135
140
  if (options.topP !== undefined)
136
141
  args.topP = options.topP;
137
142
  if (options.topK !== undefined)
@@ -196,10 +201,10 @@ async function* streamWithDeadlines(stream, options, firstOutputStartedAt) {
196
201
  for (;;) {
197
202
  const kind = hasUsefulOutput ? 'stream-inactivity' : 'first-output';
198
203
  const configuredTimeout = hasUsefulOutput ? options.streamInactivityTimeoutMs : options.firstOutputTimeoutMs;
199
- const timeoutMs = configuredTimeout == null
204
+ const timeoutMs = configuredTimeout == null ? undefined : Math.max(1, configuredTimeout - (Date.now() - lastUsefulOutputAt));
205
+ const timeout = timeoutMs == null
200
206
  ? undefined
201
- : Math.max(1, configuredTimeout - (Date.now() - lastUsefulOutputAt));
202
- const timeout = timeoutMs == null ? undefined : timeoutPromise(timeoutMs, kind, options.onTimeout);
207
+ : timeoutPromise(timeoutMs, kind, options.onTimeout);
203
208
  let next;
204
209
  try {
205
210
  next = await (timeout == null ? iterator.next() : Promise.race([iterator.next(), timeout.promise]));
@@ -361,7 +366,7 @@ export async function streamChatV2(options) {
361
366
  }
362
367
  export async function generateChatV2(options) {
363
368
  const args = buildTextArgs(options);
364
- const stepToolCalls = attachGenerateStepToolCallCollector(args);
369
+ const stepEvidence = attachGenerateStepCollector(args);
365
370
  try {
366
371
  options.onRequestStarted?.();
367
372
  }
@@ -373,7 +378,7 @@ export async function generateChatV2(options) {
373
378
  result = await waitForGeneratedResponse(Promise.resolve((options.executeGenerate ?? defaultGenerateExecutor)(args)), options);
374
379
  }
375
380
  catch (error) {
376
- const recovered = recoverGenerateStructuredOutputError(error, options, stepToolCalls);
381
+ const recovered = recoverGenerateStructuredOutputError(error, options, stepEvidence);
377
382
  if (recovered != null) {
378
383
  return recovered;
379
384
  }
@@ -381,7 +386,7 @@ export async function generateChatV2(options) {
381
386
  }
382
387
  const isStructuredOutput = isChatV2StructuredResponseFormat(options.responseFormat);
383
388
  const responseText = isStructuredOutput ? collapseRepeatedStructuredJsonText(result.text) : result.text;
384
- const functionCalls = toStreamedFunctionCalls(result.toolCalls != null && result.toolCalls.length > 0 ? result.toolCalls : stepToolCalls);
389
+ const functionCalls = toStreamedFunctionCalls(result.toolCalls != null && result.toolCalls.length > 0 ? result.toolCalls : stepEvidence.toolCalls);
385
390
  const reasoningPromise = resolveGenerateReasoning(result);
386
391
  const usagePromise = resolveGenerateUsage(result);
387
392
  let evidence = { text: responseText, functionCalls, reasoning: '' };
@@ -109,11 +109,9 @@ export function notifyChatV2CallFinished(options, params) {
109
109
  const rawUsage = safelyRead(() => copyRawUsage(resultUsage ?? errorUsage));
110
110
  const normalizedUsage = safelyRead(() => normalizeObservedUsage(rawUsage));
111
111
  const modelInfo = safelyRead(() => getChatV2ModelInfo(options.provider, options.modelId));
112
- const hasKnownPricing = modelInfo?.cost != null;
113
- const calculatedCost = hasKnownPricing
114
- ? safelyRead(() => calculateChatV2UsageCost(options.provider, options.modelId, rawUsage))
115
- : undefined;
112
+ const calculatedCost = safelyRead(() => calculateChatV2UsageCost(options.provider, options.modelId, rawUsage, params.result?.providerMetadata));
116
113
  const costUsd = toUsageNumber(calculatedCost);
114
+ const hasKnownPricing = modelInfo?.cost != null || (options.provider === 'openrouter' && costUsd != null);
117
115
  const finishReason = safelyRead(() => params.result?.finishReason) ??
118
116
  getErrorProperty(params.error, 'finishReason', (value) => typeof value === 'string');
119
117
  const event = {