@valerypopoff/rivet2-core 2.1.9 → 2.3.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 (188) hide show
  1. package/README.md +1 -1
  2. package/dist/cjs/bundle.cjs +5618 -2533
  3. package/dist/cjs/bundle.cjs.map +4 -4
  4. package/dist/cjs/webAppRuntime.cjs +333 -22
  5. package/dist/cjs/webAppRuntime.cjs.map +4 -4
  6. package/dist/esm/api/createProcessor.js +2 -0
  7. package/dist/esm/exports.js +1 -0
  8. package/dist/esm/integrations/CodeRunner.js +2 -7
  9. package/dist/esm/integrations/CodeRunnerOptions.js +7 -0
  10. package/dist/esm/model/AgentResponseTrace.js +558 -0
  11. package/dist/esm/model/ConnectedToolContinuationHost.js +33 -0
  12. package/dist/esm/model/GraphProcessor.js +165 -74
  13. package/dist/esm/model/NodeImpl.js +6 -0
  14. package/dist/esm/model/ProcessContextBuilder.js +3 -1
  15. package/dist/esm/model/RecordingPlayer.js +212 -25
  16. package/dist/esm/model/SplitRunProcessor.js +49 -8
  17. package/dist/esm/model/SubprocessorBridge.js +3 -0
  18. package/dist/esm/model/ToolCallContinuationCoordinator.js +7 -3
  19. package/dist/esm/model/UiGraph.js +21 -0
  20. package/dist/esm/model/UiGraphActionProtocol.js +3 -0
  21. package/dist/esm/model/UiGraphBrowserRuntime.js +133 -4
  22. package/dist/esm/model/UiGraphRendererStyles.js +221 -0
  23. package/dist/esm/model/UiGraphRuntimeModel.js +9 -3
  24. package/dist/esm/model/UiGraphSchema.js +7 -1
  25. package/dist/esm/model/chat/aiSdkTools.js +3 -2
  26. package/dist/esm/model/chat-v2/aiSdkBridge.js +146 -14
  27. package/dist/esm/model/chat-v2/chatV2CallObserver.js +11 -5
  28. package/dist/esm/model/chat-v2/chatV2CredentialNames.js +93 -0
  29. package/dist/esm/model/chat-v2/chatV2EditorCache.js +47 -20
  30. package/dist/esm/model/chat-v2/chatV2Errors.js +7 -19
  31. package/dist/esm/model/chat-v2/chatV2FeatureCompatibility.js +1 -1
  32. package/dist/esm/model/chat-v2/chatV2Outputs.js +48 -108
  33. package/dist/esm/model/chat-v2/chatV2Pipeline.js +101 -149
  34. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +39 -4
  35. package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +9 -0
  36. package/dist/esm/model/chat-v2/chatV2RequestPlan.js +2 -3
  37. package/dist/esm/model/chat-v2/chatV2ResponseBodyCapture.js +63 -0
  38. package/dist/esm/model/chat-v2/chatV2ResponseFormat.js +8 -4
  39. package/dist/esm/model/chat-v2/chatV2Retry.js +4 -3
  40. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +7 -7
  41. package/dist/esm/model/chat-v2/chatV2Shared.js +1 -1
  42. package/dist/esm/model/chat-v2/chatV2Types.js +20 -8
  43. package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +78 -0
  44. package/dist/esm/model/chat-v2/customProviderApi.js +40 -0
  45. package/dist/esm/model/chat-v2/index.js +15 -0
  46. package/dist/esm/model/chat-v2/llmChatV2Body.js +289 -0
  47. package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +32 -0
  48. package/dist/esm/model/chat-v2/llmChatV2CachePolicy.js +25 -0
  49. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +13 -50
  50. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +117 -24
  51. package/dist/esm/model/chat-v2/llmChatV2NodeMigration.js +24 -0
  52. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +150 -199
  53. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +60 -0
  54. package/dist/esm/model/chat-v2/llmInvocationDecision.js +11 -0
  55. package/dist/esm/model/chat-v2/llmInvocationJournal.js +43 -0
  56. package/dist/esm/model/chat-v2/llmInvocationPlan.js +68 -0
  57. package/dist/esm/model/chat-v2/llmInvocationProjections.js +5 -0
  58. package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +48 -0
  59. package/dist/esm/model/chat-v2/llmModelCandidate.js +79 -0
  60. package/dist/esm/model/chat-v2/llmProfile.js +52 -65
  61. package/dist/esm/model/chat-v2/llmProfileBody.js +193 -0
  62. package/dist/esm/model/chat-v2/llmProfileFallback.js +442 -100
  63. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +74 -0
  64. package/dist/esm/model/chat-v2/llmProfileHealthStore.js +326 -0
  65. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +55 -33
  66. package/dist/esm/model/chat-v2/llmProfileTypes.js +1 -18
  67. package/dist/esm/model/chat-v2/llmResponseMaterializer.js +42 -0
  68. package/dist/esm/model/chat-v2/modelRegistry.js +54 -4
  69. package/dist/esm/model/chat-v2/parallelToolCalls.js +9 -2
  70. package/dist/esm/model/chat-v2/providerOptions.js +116 -24
  71. package/dist/esm/model/chat-v2/rivetToolRegistry.js +9 -0
  72. package/dist/esm/model/chat-v2/toolCallCodec.js +52 -0
  73. package/dist/esm/model/chat-v2/toolContinuation.js +72 -35
  74. package/dist/esm/model/chat-v2/toolHandlerResolver.js +23 -0
  75. package/dist/esm/model/chat-v2/toolRoundExecutor.js +12 -0
  76. package/dist/esm/model/nodes/ChatNode.js +6 -0
  77. package/dist/esm/model/nodes/ChatNodeBase.js +1 -0
  78. package/dist/esm/model/nodes/CodeNewNode.js +5 -47
  79. package/dist/esm/model/nodes/CodeNode.js +4 -46
  80. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +19 -6
  81. package/dist/esm/model/nodes/ExpressionNode.js +5 -8
  82. package/dist/esm/model/nodes/LLMChatV2Node.js +121 -229
  83. package/dist/esm/model/nodes/LLMProfileNode.js +27 -8
  84. package/dist/esm/model/nodes/MatchNode.js +86 -41
  85. package/dist/esm/model/nodes/PromptNode.js +7 -0
  86. package/dist/esm/model/nodes/ToolNode.js +7 -0
  87. package/dist/esm/model/nodes/toolCallDelegation.js +177 -110
  88. package/dist/esm/plugins/anthropic/anthropic.js +4 -4
  89. package/dist/esm/plugins/anthropic/nodes/ChatAnthropicNode.js +7 -0
  90. package/dist/esm/plugins/gentrace/gentraceSdk.js +0 -1
  91. package/dist/esm/plugins/gentrace/index.js +0 -1
  92. package/dist/esm/plugins/gentrace/plugin.js +61 -179
  93. package/dist/esm/plugins/google/google.js +5 -9
  94. package/dist/esm/plugins/google/nodes/ChatGoogleNode.js +4 -1
  95. package/dist/esm/plugins.js +1 -2
  96. package/dist/esm/recording/ExecutionRecorder.js +62 -13
  97. package/dist/esm/utils/emitDetached.js +6 -3
  98. package/dist/esm/utils/openai.js +60 -16
  99. package/dist/esm/utils/serialization/serialization.js +2 -19
  100. package/dist/esm/webAppRuntime.js +3 -2
  101. package/dist/types/api/createProcessor.d.ts +3 -0
  102. package/dist/types/exports.d.ts +1 -0
  103. package/dist/types/integrations/CodeRunner.d.ts +10 -7
  104. package/dist/types/integrations/CodeRunnerOptions.d.ts +15 -0
  105. package/dist/types/model/AgentResponseTrace.d.ts +123 -0
  106. package/dist/types/model/ConnectedToolContinuationHost.d.ts +34 -0
  107. package/dist/types/model/EditorDefinition.d.ts +16 -0
  108. package/dist/types/model/ExecutorProtocol.d.ts +32 -11
  109. package/dist/types/model/GraphProcessor.d.ts +41 -9
  110. package/dist/types/model/NodeBase.d.ts +0 -10
  111. package/dist/types/model/NodeImpl.d.ts +18 -1
  112. package/dist/types/model/Nodes.d.ts +2 -2
  113. package/dist/types/model/ProcessContext.d.ts +99 -0
  114. package/dist/types/model/ProcessContextBuilder.d.ts +3 -1
  115. package/dist/types/model/RecordingPlayer.d.ts +6 -0
  116. package/dist/types/model/SplitRunProcessor.d.ts +10 -3
  117. package/dist/types/model/UiGraph.d.ts +8 -0
  118. package/dist/types/model/UiGraphActionProtocol.d.ts +3 -0
  119. package/dist/types/model/UiGraphBrowserRuntime.d.ts +11 -2
  120. package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
  121. package/dist/types/model/UiGraphRuntimeModel.d.ts +2 -0
  122. package/dist/types/model/UiGraphSchema.d.ts +1 -0
  123. package/dist/types/model/chat-v2/chatV2CallObserver.d.ts +2 -0
  124. package/dist/types/model/chat-v2/chatV2CredentialNames.d.ts +30 -0
  125. package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +2 -3
  126. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +6 -16
  127. package/dist/types/model/chat-v2/chatV2Pipeline.d.ts +13 -17
  128. package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +7 -0
  129. package/dist/types/model/chat-v2/chatV2ProviderRegistry.d.ts +8 -0
  130. package/dist/types/model/chat-v2/chatV2RequestPlan.d.ts +2 -2
  131. package/dist/types/model/chat-v2/chatV2ResponseBodyCapture.d.ts +25 -0
  132. package/dist/types/model/chat-v2/chatV2ResponseFormat.d.ts +3 -2
  133. package/dist/types/model/chat-v2/chatV2Retry.d.ts +2 -0
  134. package/dist/types/model/chat-v2/chatV2RuntimeOptions.d.ts +3 -8
  135. package/dist/types/model/chat-v2/chatV2Types.d.ts +44 -10
  136. package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +14 -0
  137. package/dist/types/model/chat-v2/customProviderApi.d.ts +22 -0
  138. package/dist/types/model/chat-v2/index.d.ts +15 -0
  139. package/dist/types/model/chat-v2/llmChatV2Body.d.ts +24 -0
  140. package/dist/types/model/chat-v2/llmChatV2CacheBoundary.d.ts +10 -0
  141. package/dist/types/model/chat-v2/llmChatV2CachePolicy.d.ts +13 -0
  142. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +19 -3
  143. package/dist/types/model/chat-v2/llmChatV2NodeMigration.d.ts +8 -0
  144. package/dist/types/model/chat-v2/llmChatV2NodeRuntime.d.ts +14 -16
  145. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +16 -0
  146. package/dist/types/model/chat-v2/llmInvocationDecision.d.ts +21 -0
  147. package/dist/types/model/chat-v2/llmInvocationJournal.d.ts +38 -0
  148. package/dist/types/model/chat-v2/llmInvocationPlan.d.ts +41 -0
  149. package/dist/types/model/chat-v2/llmInvocationProjections.d.ts +3 -0
  150. package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +26 -0
  151. package/dist/types/model/chat-v2/llmModelCandidate.d.ts +20 -0
  152. package/dist/types/model/chat-v2/llmProfile.d.ts +14 -0
  153. package/dist/types/model/chat-v2/llmProfileBody.d.ts +20 -0
  154. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +36 -49
  155. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +209 -0
  156. package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +111 -0
  157. package/dist/types/model/chat-v2/llmProfileNodeRuntime.d.ts +1 -1
  158. package/dist/types/model/chat-v2/llmProfileTypes.d.ts +4 -1
  159. package/dist/types/model/chat-v2/llmResponseMaterializer.d.ts +20 -0
  160. package/dist/types/model/chat-v2/modelRegistry.d.ts +17 -187
  161. package/dist/types/model/chat-v2/parallelToolCalls.d.ts +3 -1
  162. package/dist/types/model/chat-v2/providerOptions.d.ts +12 -0
  163. package/dist/types/model/chat-v2/rivetToolRegistry.d.ts +11 -0
  164. package/dist/types/model/chat-v2/toolCallCodec.d.ts +7 -0
  165. package/dist/types/model/chat-v2/toolContinuation.d.ts +3 -3
  166. package/dist/types/model/chat-v2/toolHandlerResolver.d.ts +25 -0
  167. package/dist/types/model/chat-v2/toolRoundExecutor.d.ts +18 -0
  168. package/dist/types/model/nodes/ChatNode.d.ts +2 -1
  169. package/dist/types/model/nodes/CodeNewNode.d.ts +0 -5
  170. package/dist/types/model/nodes/CodeNode.d.ts +0 -5
  171. package/dist/types/model/nodes/DelegateFunctionCallNode.d.ts +2 -1
  172. package/dist/types/model/nodes/LLMChatV2Node.d.ts +2 -1
  173. package/dist/types/model/nodes/LLMProfileNode.d.ts +2 -1
  174. package/dist/types/model/nodes/MatchNode.d.ts +6 -0
  175. package/dist/types/model/nodes/PromptNode.d.ts +4 -1
  176. package/dist/types/model/nodes/ToolNode.d.ts +2 -1
  177. package/dist/types/model/nodes/toolCallDelegation.d.ts +10 -3
  178. package/dist/types/plugins/anthropic/anthropic.d.ts +1 -0
  179. package/dist/types/plugins/gentrace/gentraceSdk.d.ts +0 -1
  180. package/dist/types/plugins/gentrace/plugin.d.ts +55 -9
  181. package/dist/types/plugins/google/google.d.ts +2 -8
  182. package/dist/types/plugins.d.ts +1 -1
  183. package/dist/types/recording/ExecutionRecorder.d.ts +7 -1
  184. package/dist/types/recording/RecordedEvents.d.ts +6 -0
  185. package/dist/types/utils/emitDetached.d.ts +3 -2
  186. package/dist/types/utils/openai.d.ts +49 -0
  187. package/dist/types/webAppRuntime.d.ts +4 -2
  188. package/package.json +2 -2
@@ -138,6 +138,8 @@ export function coreCreateProcessor(project, options, internalOptions = {}) {
138
138
  settings: resolveProcessSettings(options),
139
139
  getChatNodeEndpoint: options.getChatNodeEndpoint,
140
140
  onChatV2CallFinished: options.onChatV2CallFinished,
141
+ llmProfileHealthStore: options.llmProfileHealthStore,
142
+ evaluation: options.evaluation,
141
143
  }, resolvedInputs, resolvedContextValues, { returnWhenGraphOutputsReady: options.returnWhenGraphOutputsReady });
142
144
  if (abortSignal?.aborted) {
143
145
  void processor.abort();
@@ -26,6 +26,7 @@ export * from './native/BaseDir.js';
26
26
  export * from './native/NativeApi.js';
27
27
  export * from './native/BrowserNativeApi.js';
28
28
  export * from './model/ProcessContext.js';
29
+ export * from './model/AgentResponseTrace.js';
29
30
  export * from './model/DebuggerTransportSentinel.js';
30
31
  export * from './model/ProjectReferenceLoader.js';
31
32
  export * from './model/RivetUIContext.js';
@@ -1,15 +1,10 @@
1
- // eslint-disable-next-line import/no-cycle -- There has to be a cycle if we're to import the entirety of Rivet here.
1
+ // eslint-disable-next-line import/no-cycle -- Authored code receives the complete public Rivet namespace at execution time.
2
2
  import * as Rivet from '../exports.js';
3
+ export { ALL_CODE_RUNNER_OPTIONS } from './CodeRunnerOptions.js';
3
4
  export class IsomorphicCodeRunner {
4
5
  async runCode(code, inputs, options, graphInputs, contextValues) {
5
6
  const argNames = ['inputs'];
6
7
  const args = [inputs];
7
- if (options.includeRequire) {
8
- throw new Error('require() requires the Node executor.');
9
- }
10
- if (options.includeProcess) {
11
- throw new Error('process requires the Node executor.');
12
- }
13
8
  if (options.includeConsole) {
14
9
  argNames.push('console');
15
10
  args.push(console);
@@ -0,0 +1,7 @@
1
+ export const ALL_CODE_RUNNER_OPTIONS = Object.freeze({
2
+ includeRequire: true,
3
+ includeFetch: true,
4
+ includeRivet: true,
5
+ includeProcess: true,
6
+ includeConsole: true,
7
+ });
@@ -0,0 +1,558 @@
1
+ export const AGENT_RESPONSE_TRACE_SCHEMA_VERSION = 1;
2
+ export const AGENT_RESPONSE_TRACE_MAX_MODEL_CALLS = 250;
3
+ export const AGENT_RESPONSE_TRACE_MAX_PROFILE_ATTEMPTS = 1_000;
4
+ export const AGENT_RESPONSE_TRACE_MAX_TOOL_CALLS = 500;
5
+ export function buildAgentResponseTrace(options) {
6
+ const matchingEvents = deduplicateAgentTraceEvents(options.events.filter((event) => {
7
+ if (event.execution.rootRunId !== options.execution.rootRunId)
8
+ return false;
9
+ if (options.scope === 'response')
10
+ return true;
11
+ if (event.execution.graphRunId !== options.execution.graphRunId)
12
+ return false;
13
+ if (event.type === 'llm-call-finished') {
14
+ return event.nodeId === options.nodeId && event.processId === options.processId;
15
+ }
16
+ if (event.type === 'llm-profile-attempt') {
17
+ return event.nodeId === options.nodeId && event.processId === options.processId;
18
+ }
19
+ return event.sourceNodeId === options.nodeId && event.sourceProcessId === options.processId;
20
+ }));
21
+ const allModelCalls = matchingEvents
22
+ .filter((event) => event.type === 'llm-call-finished')
23
+ .map(toModelCallTrace);
24
+ const allProfileAttempts = matchingEvents
25
+ .filter((event) => event.type === 'llm-profile-attempt')
26
+ .map(toProfileAttemptTrace);
27
+ const allToolCalls = matchingEvents
28
+ .filter((event) => event.type === 'tool-call-finished')
29
+ .map(toToolCallTrace);
30
+ const summary = summarizeAgentCalls(allModelCalls, allProfileAttempts, allToolCalls);
31
+ const terminalAt = options.responseReadyAt ?? options.finishedAt;
32
+ return {
33
+ schemaVersion: AGENT_RESPONSE_TRACE_SCHEMA_VERSION,
34
+ traceId: options.execution.rootRunId,
35
+ scope: options.scope,
36
+ rootRunId: options.execution.rootRunId,
37
+ graphRunId: options.execution.graphRunId,
38
+ graphId: options.execution.graphId,
39
+ ...(options.nodeId == null ? {} : { nodeId: options.nodeId }),
40
+ ...(options.processId == null ? {} : { processId: options.processId }),
41
+ ...(options.startedAt == null ? {} : { startedAt: options.startedAt }),
42
+ ...(options.responseReadyAt == null ? {} : { responseReadyAt: options.responseReadyAt }),
43
+ ...(options.finishedAt == null ? {} : { finishedAt: options.finishedAt }),
44
+ ...(options.startedAt == null || terminalAt == null
45
+ ? {}
46
+ : { durationMs: Math.max(0, terminalAt - options.startedAt) }),
47
+ status: options.status,
48
+ ...(options.backgroundWorkPending == null ? {} : { backgroundWorkPending: options.backgroundWorkPending }),
49
+ summary,
50
+ modelCalls: allModelCalls.slice(0, AGENT_RESPONSE_TRACE_MAX_MODEL_CALLS),
51
+ profileAttempts: allProfileAttempts.slice(0, AGENT_RESPONSE_TRACE_MAX_PROFILE_ATTEMPTS),
52
+ toolCalls: allToolCalls.slice(0, AGENT_RESPONSE_TRACE_MAX_TOOL_CALLS),
53
+ omittedModelCallCount: Math.max(0, allModelCalls.length - AGENT_RESPONSE_TRACE_MAX_MODEL_CALLS),
54
+ omittedProfileAttemptCount: Math.max(0, allProfileAttempts.length - AGENT_RESPONSE_TRACE_MAX_PROFILE_ATTEMPTS),
55
+ omittedToolCallCount: Math.max(0, allToolCalls.length - AGENT_RESPONSE_TRACE_MAX_TOOL_CALLS),
56
+ };
57
+ }
58
+ /**
59
+ * Trace transport is observational and may redeliver an event. Keep the
60
+ * projection idempotent so repeated delivery cannot inflate call counts,
61
+ * tokens, or cost. Physical model calls and identified tool calls carry stable
62
+ * IDs; anonymous tool events remain distinct because they cannot be matched
63
+ * safely.
64
+ */
65
+ function deduplicateAgentTraceEvents(events) {
66
+ const deduplicated = [];
67
+ const indexByIdentity = new Map();
68
+ for (const event of events) {
69
+ const identity = getAgentTraceEventIdentity(event);
70
+ if (identity == null) {
71
+ deduplicated.push(event);
72
+ continue;
73
+ }
74
+ const existingIndex = indexByIdentity.get(identity);
75
+ if (existingIndex == null) {
76
+ indexByIdentity.set(identity, deduplicated.length);
77
+ deduplicated.push(event);
78
+ }
79
+ else {
80
+ // Preserve first-seen order while retaining the latest terminal metadata.
81
+ deduplicated[existingIndex] = mergeAgentTraceEvent(deduplicated[existingIndex], event);
82
+ }
83
+ }
84
+ return deduplicated;
85
+ }
86
+ export function getAgentTraceEventIdentity(event) {
87
+ if (event.type === 'llm-call-finished') {
88
+ return `model\u0000${event.execution.rootRunId}\u0000${event.execution.graphRunId}\u0000${event.nodeId}\u0000${event.processId}\u0000${event.callId}`;
89
+ }
90
+ if (event.type === 'llm-profile-attempt') {
91
+ return `profile-attempt\u0000${event.execution.rootRunId}\u0000${event.execution.graphRunId}\u0000${event.nodeId}\u0000${event.processId}\u0000${event.eventId}`;
92
+ }
93
+ return event.toolCallId == null
94
+ ? undefined
95
+ : `tool\u0000${event.execution.rootRunId}\u0000${event.execution.graphRunId}\u0000${event.sourceNodeId}\u0000${event.sourceProcessId}\u0000${event.toolCallId}`;
96
+ }
97
+ /**
98
+ * Redelivery is allowed to omit newly added optional observability fields. Keep
99
+ * an exact Delegate result pointer once it was observed instead of making a
100
+ * later legacy-shaped copy erase result navigation.
101
+ */
102
+ export function mergeAgentTraceEvent(existing, incoming) {
103
+ if (existing.type === 'llm-call-finished' && incoming.type === 'llm-call-finished') {
104
+ return {
105
+ ...incoming,
106
+ ...(incoming.profileHealthKey == null && existing.profileHealthKey != null
107
+ ? { profileHealthKey: existing.profileHealthKey }
108
+ : {}),
109
+ ...(incoming.profileHealthState == null && existing.profileHealthState != null
110
+ ? { profileHealthState: existing.profileHealthState }
111
+ : {}),
112
+ };
113
+ }
114
+ if (existing.type === 'tool-call-finished' &&
115
+ incoming.type === 'tool-call-finished' &&
116
+ existing.resultOwner != null &&
117
+ incoming.resultOwner == null &&
118
+ isAgentToolResultOutcome(incoming.outcome)) {
119
+ return { ...incoming, resultOwner: existing.resultOwner };
120
+ }
121
+ return incoming;
122
+ }
123
+ function toModelCallTrace(event) {
124
+ return {
125
+ callId: event.callId,
126
+ nodeId: event.nodeId,
127
+ processId: event.processId,
128
+ provider: event.provider,
129
+ model: event.model,
130
+ ...(event.customProviderApi == null ? {} : { customProviderApi: event.customProviderApi }),
131
+ outcome: event.outcome,
132
+ attemptIndex: event.attemptIndex,
133
+ ...(event.profileIndex == null ? {} : { profileIndex: event.profileIndex }),
134
+ ...(event.profileHealthKey == null ? {} : { profileHealthKey: event.profileHealthKey }),
135
+ ...(event.profileHealthState == null ? {} : { profileHealthState: event.profileHealthState }),
136
+ ...(event.roundIndex == null ? {} : { roundIndex: event.roundIndex }),
137
+ ...(event.startedAt == null ? {} : { startedAt: event.startedAt }),
138
+ ...(event.durationMs == null ? {} : { durationMs: event.durationMs }),
139
+ ...(event.finishReason == null ? {} : { finishReason: event.finishReason }),
140
+ ...(event.normalizedUsage == null ? {} : { usage: event.normalizedUsage }),
141
+ pricing: event.pricing,
142
+ };
143
+ }
144
+ function toToolCallTrace(event) {
145
+ return {
146
+ ...(event.toolCallId == null ? {} : { toolCallId: event.toolCallId }),
147
+ toolName: event.toolName,
148
+ sourceNodeId: event.sourceNodeId,
149
+ sourceProcessId: event.sourceProcessId,
150
+ ...(event.resultOwner == null ? {} : { resultOwner: event.resultOwner }),
151
+ handlerKind: event.handlerKind,
152
+ ...(event.handlerGraphId == null ? {} : { handlerGraphId: event.handlerGraphId }),
153
+ ...(event.handlerName == null ? {} : { handlerName: event.handlerName }),
154
+ outcome: event.outcome,
155
+ ...(event.startedAt == null ? {} : { startedAt: event.startedAt }),
156
+ ...(event.durationMs == null ? {} : { durationMs: event.durationMs }),
157
+ };
158
+ }
159
+ function toProfileAttemptTrace(event) {
160
+ const { type: _type, execution: _execution, ...trace } = event;
161
+ return trace;
162
+ }
163
+ function summarizeAgentCalls(modelCalls, profileAttempts, toolCalls) {
164
+ const usageKeys = ['promptTokens', 'completionTokens', 'totalTokens', 'cachedTokens', 'reasoningTokens'];
165
+ const usage = Object.fromEntries(usageKeys.flatMap((key) => {
166
+ const values = modelCalls.map((call) => call.usage?.[key]).filter((value) => value != null);
167
+ return values.length === 0 ? [] : [[key, values.reduce((sum, value) => sum + value, 0)]];
168
+ }));
169
+ const knownCosts = modelCalls
170
+ .map((call) => call.pricing.costUsd)
171
+ .filter((value) => value != null && Number.isFinite(value));
172
+ const unknownCostCount = modelCalls.filter((call) => call.pricing.status === 'unknown' || !Number.isFinite(call.pricing.costUsd)).length;
173
+ const profileTransitions = countProfileFallbacks(modelCalls, profileAttempts);
174
+ return {
175
+ modelCallCount: modelCalls.length,
176
+ toolCallCount: toolCalls.length,
177
+ retryCount: modelCalls.filter((call) => call.attemptIndex > 0).length,
178
+ fallbackCount: profileTransitions,
179
+ ...usage,
180
+ knownCostUsd: knownCosts.reduce((sum, value) => sum + value, 0),
181
+ costStatus: modelCalls.length === 0 || unknownCostCount === modelCalls.length
182
+ ? 'unknown'
183
+ : unknownCostCount > 0
184
+ ? 'partial'
185
+ : 'known',
186
+ };
187
+ }
188
+ /**
189
+ * Counts forward profile advances per physical node invocation. The fallback
190
+ * runner starts at profile zero and stays on or advances from its selected
191
+ * profile across continuation rounds. Using that invariant also accounts for
192
+ * configuration-failed profiles that never produced a physical-call event.
193
+ */
194
+ function countProfileFallbacks(modelCalls, profileAttempts) {
195
+ const highestProfileByInvocation = new Map();
196
+ let count = 0;
197
+ const candidates = [
198
+ ...modelCalls.flatMap((call) => call.profileIndex == null
199
+ ? []
200
+ : [{ nodeId: call.nodeId, processId: call.processId, profileIndex: call.profileIndex }]),
201
+ ...profileAttempts.flatMap((attempt) => attempt.profileIndex == null
202
+ ? []
203
+ : [{ nodeId: attempt.nodeId, processId: attempt.processId, profileIndex: attempt.profileIndex }]),
204
+ ];
205
+ for (const candidate of candidates) {
206
+ const key = `${candidate.nodeId}\u0000${candidate.processId}`;
207
+ const highestProfile = highestProfileByInvocation.get(key) ?? 0;
208
+ if (candidate.profileIndex <= highestProfile)
209
+ continue;
210
+ count += candidate.profileIndex - highestProfile;
211
+ highestProfileByInvocation.set(key, candidate.profileIndex);
212
+ }
213
+ return count;
214
+ }
215
+ export function isAgentResponseTrace(value) {
216
+ if (!isRecord(value) || value.schemaVersion !== AGENT_RESPONSE_TRACE_SCHEMA_VERSION)
217
+ return false;
218
+ if (!hasOnlyKeys(value, [
219
+ 'schemaVersion',
220
+ 'traceId',
221
+ 'scope',
222
+ 'rootRunId',
223
+ 'graphRunId',
224
+ 'graphId',
225
+ 'nodeId',
226
+ 'processId',
227
+ 'startedAt',
228
+ 'responseReadyAt',
229
+ 'finishedAt',
230
+ 'durationMs',
231
+ 'status',
232
+ 'backgroundWorkPending',
233
+ 'summary',
234
+ 'modelCalls',
235
+ 'profileAttempts',
236
+ 'toolCalls',
237
+ 'omittedModelCallCount',
238
+ 'omittedProfileAttemptCount',
239
+ 'omittedToolCallCount',
240
+ ]))
241
+ return false;
242
+ if (typeof value.traceId !== 'string' || typeof value.rootRunId !== 'string')
243
+ return false;
244
+ if (typeof value.graphRunId !== 'string' || typeof value.graphId !== 'string')
245
+ return false;
246
+ if (value.scope !== 'response' && value.scope !== 'llm-invocation')
247
+ return false;
248
+ if (!isRecord(value.summary) || !Array.isArray(value.modelCalls) || !Array.isArray(value.toolCalls))
249
+ return false;
250
+ if (value.profileAttempts !== undefined && !Array.isArray(value.profileAttempts))
251
+ return false;
252
+ if (value.modelCalls.length > AGENT_RESPONSE_TRACE_MAX_MODEL_CALLS)
253
+ return false;
254
+ if (Array.isArray(value.profileAttempts) &&
255
+ value.profileAttempts.length > AGENT_RESPONSE_TRACE_MAX_PROFILE_ATTEMPTS)
256
+ return false;
257
+ if (value.toolCalls.length > AGENT_RESPONSE_TRACE_MAX_TOOL_CALLS)
258
+ return false;
259
+ return (isOptionalString(value.nodeId) &&
260
+ isOptionalString(value.processId) &&
261
+ isOptionalNonNegativeFiniteNumber(value.startedAt) &&
262
+ isOptionalNonNegativeFiniteNumber(value.responseReadyAt) &&
263
+ isOptionalNonNegativeFiniteNumber(value.finishedAt) &&
264
+ isOptionalNonNegativeFiniteNumber(value.durationMs) &&
265
+ isOptionalBoolean(value.backgroundWorkPending) &&
266
+ ['running', 'response-ready', 'completed', 'error', 'aborted', 'unavailable'].includes(String(value.status)) &&
267
+ isNonNegativeInteger(value.omittedModelCallCount) &&
268
+ (value.omittedProfileAttemptCount === undefined || isNonNegativeInteger(value.omittedProfileAttemptCount)) &&
269
+ isNonNegativeInteger(value.omittedToolCallCount) &&
270
+ isAgentTraceSummary(value.summary) &&
271
+ value.modelCalls.every(isAgentModelCallTrace) &&
272
+ (value.profileAttempts === undefined || value.profileAttempts.every(isAgentLLMProfileAttemptTrace)) &&
273
+ value.toolCalls.every(isAgentToolCallTrace));
274
+ }
275
+ /**
276
+ * Collects privacy-bounded response metadata for one root processor run.
277
+ * Listener failures are isolated by GraphProcessor; callers should dispose the
278
+ * collector after the processor and any asynchronous branches settle.
279
+ */
280
+ export class AgentResponseTraceCollector {
281
+ #events = [];
282
+ #cleanups = [];
283
+ #startedAt = Date.now();
284
+ #execution;
285
+ #responseReadyAt;
286
+ #finishedAt;
287
+ #status = 'running';
288
+ #backgroundWorkPending = false;
289
+ constructor(processor) {
290
+ this.#cleanups.push(processor.on('start', ({ execution }) => {
291
+ this.#execution = execution;
292
+ }), processor.on('llmCallFinished', (event) => {
293
+ this.#execution ??= event.execution;
294
+ this.#events.push({ type: 'llm-call-finished', ...event });
295
+ }), processor.on('llmProfileAttempt', (event) => {
296
+ this.#execution ??= event.execution;
297
+ this.#events.push({ type: 'llm-profile-attempt', ...event });
298
+ }), processor.on('toolCallFinished', (event) => {
299
+ this.#execution ??= event.execution;
300
+ this.#events.push({ type: 'tool-call-finished', ...event });
301
+ }), processor.on('graphOutputsReady', ({ execution }) => {
302
+ if (execution.parentGraphRunId != null)
303
+ return;
304
+ this.#execution ??= execution;
305
+ this.#responseReadyAt ??= Date.now();
306
+ this.#status = 'response-ready';
307
+ this.#backgroundWorkPending = processor.isRunning;
308
+ }), processor.on('graphFinish', ({ execution }) => {
309
+ if (execution.parentGraphRunId != null)
310
+ return;
311
+ this.#execution ??= execution;
312
+ this.#finishedAt = Date.now();
313
+ this.#responseReadyAt ??= this.#finishedAt;
314
+ this.#status = 'completed';
315
+ this.#backgroundWorkPending = false;
316
+ }), processor.on('graphError', ({ execution }) => {
317
+ if (execution.parentGraphRunId != null)
318
+ return;
319
+ this.#execution ??= execution;
320
+ this.#finishedAt = Date.now();
321
+ this.#status = 'error';
322
+ this.#backgroundWorkPending = false;
323
+ }), processor.on('graphAbort', ({ execution }) => {
324
+ if (execution.parentGraphRunId != null)
325
+ return;
326
+ this.#execution ??= execution;
327
+ this.#finishedAt = Date.now();
328
+ this.#status = 'aborted';
329
+ this.#backgroundWorkPending = false;
330
+ }));
331
+ }
332
+ build() {
333
+ if (this.#execution == null)
334
+ return undefined;
335
+ return buildAgentResponseTrace({
336
+ scope: 'response',
337
+ execution: this.#execution,
338
+ events: this.#events,
339
+ startedAt: this.#startedAt,
340
+ ...(this.#responseReadyAt == null ? {} : { responseReadyAt: this.#responseReadyAt }),
341
+ ...(this.#finishedAt == null ? {} : { finishedAt: this.#finishedAt }),
342
+ status: this.#status,
343
+ backgroundWorkPending: this.#backgroundWorkPending,
344
+ });
345
+ }
346
+ dispose() {
347
+ for (const cleanup of this.#cleanups.splice(0))
348
+ cleanup();
349
+ }
350
+ }
351
+ function isAgentModelCallTrace(value) {
352
+ return (isRecord(value) &&
353
+ hasOnlyKeys(value, [
354
+ 'callId',
355
+ 'nodeId',
356
+ 'processId',
357
+ 'provider',
358
+ 'model',
359
+ 'customProviderApi',
360
+ 'outcome',
361
+ 'attemptIndex',
362
+ 'profileIndex',
363
+ 'profileHealthKey',
364
+ 'profileHealthState',
365
+ 'roundIndex',
366
+ 'startedAt',
367
+ 'durationMs',
368
+ 'finishReason',
369
+ 'usage',
370
+ 'pricing',
371
+ ]) &&
372
+ typeof value.callId === 'string' &&
373
+ typeof value.nodeId === 'string' &&
374
+ typeof value.processId === 'string' &&
375
+ typeof value.provider === 'string' &&
376
+ typeof value.model === 'string' &&
377
+ (value.customProviderApi === undefined ||
378
+ value.customProviderApi === 'completions' ||
379
+ value.customProviderApi === 'responses') &&
380
+ (value.outcome === 'success' || value.outcome === 'provider-failure' || value.outcome === 'aborted') &&
381
+ isNonNegativeInteger(value.attemptIndex) &&
382
+ isOptionalNonNegativeInteger(value.profileIndex) &&
383
+ isOptionalString(value.profileHealthKey) &&
384
+ (value.profileHealthState === undefined ||
385
+ value.profileHealthState === 'closed' ||
386
+ value.profileHealthState === 'open' ||
387
+ value.profileHealthState === 'half-open') &&
388
+ isOptionalNonNegativeInteger(value.roundIndex) &&
389
+ isOptionalNonNegativeFiniteNumber(value.startedAt) &&
390
+ isOptionalNonNegativeFiniteNumber(value.durationMs) &&
391
+ isOptionalString(value.finishReason) &&
392
+ (value.usage === undefined || isAgentTraceUsage(value.usage)) &&
393
+ isAgentTracePricing(value.pricing));
394
+ }
395
+ function isAgentLLMProfileAttemptTrace(value) {
396
+ return (isRecord(value) &&
397
+ hasOnlyKeys(value, [
398
+ 'eventId',
399
+ 'roundIndex',
400
+ 'profileIndex',
401
+ 'nodeId',
402
+ 'processId',
403
+ 'provider',
404
+ 'model',
405
+ 'customProviderApi',
406
+ 'stage',
407
+ 'outcome',
408
+ 'attemptIndex',
409
+ 'status',
410
+ 'error',
411
+ 'profileHealthKey',
412
+ 'healthState',
413
+ 'healthDisposition',
414
+ 'healthOutcome',
415
+ 'retryAt',
416
+ 'timeoutKind',
417
+ ]) &&
418
+ typeof value.eventId === 'string' &&
419
+ isNonNegativeInteger(value.roundIndex) &&
420
+ isOptionalNonNegativeInteger(value.profileIndex) &&
421
+ typeof value.nodeId === 'string' &&
422
+ typeof value.processId === 'string' &&
423
+ typeof value.provider === 'string' &&
424
+ typeof value.model === 'string' &&
425
+ (value.customProviderApi === undefined ||
426
+ value.customProviderApi === 'completions' ||
427
+ value.customProviderApi === 'responses') &&
428
+ ['configuration', 'request', 'response-validation', 'health-gate', 'health-update'].includes(String(value.stage)) &&
429
+ ['success', 'failure', 'aborted', 'skipped'].includes(String(value.outcome)) &&
430
+ isOptionalNonNegativeInteger(value.attemptIndex) &&
431
+ isOptionalNonNegativeFiniteNumber(value.status) &&
432
+ isOptionalString(value.error) &&
433
+ isOptionalString(value.profileHealthKey) &&
434
+ (value.healthState === undefined ||
435
+ value.healthState === 'closed' ||
436
+ value.healthState === 'open' ||
437
+ value.healthState === 'half-open') &&
438
+ (value.healthDisposition === undefined ||
439
+ value.healthDisposition === 'allow' ||
440
+ value.healthDisposition === 'deny' ||
441
+ value.healthDisposition === 'fail-open') &&
442
+ (value.healthOutcome === undefined ||
443
+ value.healthOutcome === 'healthy' ||
444
+ value.healthOutcome === 'unhealthy' ||
445
+ value.healthOutcome === 'ignored') &&
446
+ isOptionalNonNegativeFiniteNumber(value.retryAt) &&
447
+ (value.timeoutKind === undefined ||
448
+ value.timeoutKind === 'first-output' ||
449
+ value.timeoutKind === 'stream-inactivity'));
450
+ }
451
+ function isAgentToolCallTrace(value) {
452
+ const hasKnownOutcome = isRecord(value) &&
453
+ (value.outcome === 'success' ||
454
+ value.outcome === 'passthrough-error' ||
455
+ value.outcome === 'failure' ||
456
+ value.outcome === 'aborted');
457
+ return (isRecord(value) &&
458
+ hasOnlyKeys(value, [
459
+ 'toolCallId',
460
+ 'toolName',
461
+ 'sourceNodeId',
462
+ 'sourceProcessId',
463
+ 'resultOwner',
464
+ 'handlerKind',
465
+ 'handlerGraphId',
466
+ 'handlerName',
467
+ 'outcome',
468
+ 'startedAt',
469
+ 'durationMs',
470
+ ]) &&
471
+ isOptionalString(value.toolCallId) &&
472
+ typeof value.toolName === 'string' &&
473
+ typeof value.sourceNodeId === 'string' &&
474
+ typeof value.sourceProcessId === 'string' &&
475
+ (value.resultOwner === undefined ||
476
+ (isAgentToolResultOutcome(value.outcome) && isAgentToolResultOwner(value.resultOwner))) &&
477
+ (value.handlerKind === 'graph' || value.handlerKind === 'external' || value.handlerKind === 'unknown') &&
478
+ isOptionalString(value.handlerGraphId) &&
479
+ isOptionalString(value.handlerName) &&
480
+ hasKnownOutcome &&
481
+ isOptionalNonNegativeFiniteNumber(value.startedAt) &&
482
+ isOptionalNonNegativeFiniteNumber(value.durationMs));
483
+ }
484
+ function isAgentToolResultOutcome(value) {
485
+ return value === 'success' || value === 'passthrough-error';
486
+ }
487
+ function isAgentToolResultOwner(value) {
488
+ return (isRecord(value) &&
489
+ hasOnlyKeys(value, ['nodeId', 'processId', 'outputPortId']) &&
490
+ typeof value.nodeId === 'string' &&
491
+ typeof value.processId === 'string' &&
492
+ typeof value.outputPortId === 'string');
493
+ }
494
+ function isAgentTraceSummary(value) {
495
+ return (hasOnlyKeys(value, [
496
+ 'modelCallCount',
497
+ 'toolCallCount',
498
+ 'retryCount',
499
+ 'fallbackCount',
500
+ 'promptTokens',
501
+ 'completionTokens',
502
+ 'totalTokens',
503
+ 'cachedTokens',
504
+ 'reasoningTokens',
505
+ 'knownCostUsd',
506
+ 'costStatus',
507
+ ]) &&
508
+ isNonNegativeInteger(value.modelCallCount) &&
509
+ isNonNegativeInteger(value.toolCallCount) &&
510
+ isNonNegativeInteger(value.retryCount) &&
511
+ isNonNegativeInteger(value.fallbackCount) &&
512
+ isOptionalNonNegativeFiniteNumber(value.promptTokens) &&
513
+ isOptionalNonNegativeFiniteNumber(value.completionTokens) &&
514
+ isOptionalNonNegativeFiniteNumber(value.totalTokens) &&
515
+ isOptionalNonNegativeFiniteNumber(value.cachedTokens) &&
516
+ isOptionalNonNegativeFiniteNumber(value.reasoningTokens) &&
517
+ isNonNegativeFiniteNumber(value.knownCostUsd) &&
518
+ (value.costStatus === 'known' || value.costStatus === 'partial' || value.costStatus === 'unknown'));
519
+ }
520
+ function isAgentTraceUsage(value) {
521
+ return (isRecord(value) &&
522
+ hasOnlyKeys(value, ['promptTokens', 'completionTokens', 'totalTokens', 'cachedTokens', 'reasoningTokens']) &&
523
+ Object.values(value).every(isNonNegativeFiniteNumber));
524
+ }
525
+ function isAgentTracePricing(value) {
526
+ return (isRecord(value) &&
527
+ hasOnlyKeys(value, ['status', 'costUsd']) &&
528
+ (value.status === 'known' || value.status === 'unknown') &&
529
+ isOptionalNonNegativeFiniteNumber(value.costUsd));
530
+ }
531
+ function hasOnlyKeys(value, allowed) {
532
+ const allowedKeys = new Set(allowed);
533
+ return Object.keys(value).every((key) => allowedKeys.has(key));
534
+ }
535
+ function isFiniteNumber(value) {
536
+ return typeof value === 'number' && Number.isFinite(value);
537
+ }
538
+ function isNonNegativeFiniteNumber(value) {
539
+ return isFiniteNumber(value) && value >= 0;
540
+ }
541
+ function isOptionalNonNegativeFiniteNumber(value) {
542
+ return value === undefined || isNonNegativeFiniteNumber(value);
543
+ }
544
+ function isNonNegativeInteger(value) {
545
+ return Number.isInteger(value) && value >= 0;
546
+ }
547
+ function isOptionalNonNegativeInteger(value) {
548
+ return value === undefined || isNonNegativeInteger(value);
549
+ }
550
+ function isOptionalString(value) {
551
+ return value === undefined || typeof value === 'string';
552
+ }
553
+ function isOptionalBoolean(value) {
554
+ return value === undefined || typeof value === 'boolean';
555
+ }
556
+ function isRecord(value) {
557
+ return typeof value === 'object' && value != null && !Array.isArray(value);
558
+ }
@@ -0,0 +1,33 @@
1
+ export class ConnectedToolContinuationHost {
2
+ #invocations = new Map();
3
+ begin(params) {
4
+ const invocation = {
5
+ delegateNode: params.delegateNode,
6
+ latestOutputs: new Map(),
7
+ llmNodeId: params.llmNodeId,
8
+ llmProcessId: params.llmProcessId,
9
+ released: false,
10
+ };
11
+ this.#invocations.set(params.key, invocation);
12
+ return {
13
+ run: (toolCalls, assistantMessage) => params.run(invocation, toolCalls, assistantMessage),
14
+ release: () => {
15
+ invocation.released = true;
16
+ },
17
+ };
18
+ }
19
+ finalize(params) {
20
+ const invocation = this.#invocations.get(params.key);
21
+ this.#invocations.delete(params.key);
22
+ if (!invocation || invocation.released)
23
+ return;
24
+ params.replay(invocation, params.nodeOutputs);
25
+ params.commit(invocation);
26
+ }
27
+ discard(key) {
28
+ this.#invocations.delete(key);
29
+ }
30
+ reset() {
31
+ this.#invocations.clear();
32
+ }
33
+ }