@valerypopoff/rivet2-core 2.1.8 → 2.1.10

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 (168) hide show
  1. package/dist/cjs/bundle.cjs +4457 -1809
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/webAppRuntime.cjs +298 -21
  4. package/dist/cjs/webAppRuntime.cjs.map +4 -4
  5. package/dist/esm/exports.js +1 -0
  6. package/dist/esm/model/AgentResponseTrace.js +448 -0
  7. package/dist/esm/model/ConnectedToolContinuationHost.js +33 -0
  8. package/dist/esm/model/GraphProcessor.js +152 -74
  9. package/dist/esm/model/NodeImpl.js +6 -0
  10. package/dist/esm/model/ProcessContextBuilder.js +3 -1
  11. package/dist/esm/model/RecordingPlayer.js +164 -22
  12. package/dist/esm/model/SplitRunProcessor.js +68 -18
  13. package/dist/esm/model/SubprocessorBridge.js +2 -0
  14. package/dist/esm/model/ToolCallContinuationCoordinator.js +13 -4
  15. package/dist/esm/model/UiGraph.js +21 -0
  16. package/dist/esm/model/UiGraphActionProtocol.js +2 -0
  17. package/dist/esm/model/UiGraphBrowserRuntime.js +133 -4
  18. package/dist/esm/model/UiGraphRendererStyles.js +221 -0
  19. package/dist/esm/model/UiGraphRuntimeModel.js +9 -3
  20. package/dist/esm/model/UiGraphSchema.js +7 -1
  21. package/dist/esm/model/chat/aiSdkMessages.js +8 -0
  22. package/dist/esm/model/chat/aiSdkTools.js +3 -2
  23. package/dist/esm/model/chat-v2/chatV2CallObserver.js +11 -5
  24. package/dist/esm/model/chat-v2/chatV2EditorCache.js +58 -10
  25. package/dist/esm/model/chat-v2/chatV2Errors.js +7 -19
  26. package/dist/esm/model/chat-v2/chatV2FeatureCompatibility.js +1 -1
  27. package/dist/esm/model/chat-v2/chatV2Outputs.js +56 -106
  28. package/dist/esm/model/chat-v2/chatV2Pipeline.js +142 -149
  29. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +9 -2
  30. package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +9 -0
  31. package/dist/esm/model/chat-v2/chatV2RequestPlan.js +5 -5
  32. package/dist/esm/model/chat-v2/chatV2ResponseBodyCapture.js +55 -0
  33. package/dist/esm/model/chat-v2/chatV2ResponseFormat.js +8 -4
  34. package/dist/esm/model/chat-v2/chatV2Retry.js +4 -3
  35. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +6 -1
  36. package/dist/esm/model/chat-v2/chatV2Shared.js +1 -6
  37. package/dist/esm/model/chat-v2/chatV2Types.js +7 -1
  38. package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +78 -0
  39. package/dist/esm/model/chat-v2/customProviderApi.js +42 -0
  40. package/dist/esm/model/chat-v2/developerMessageRoles.js +45 -0
  41. package/dist/esm/model/chat-v2/index.js +12 -0
  42. package/dist/esm/model/chat-v2/llmChatV2Body.js +281 -0
  43. package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +32 -0
  44. package/dist/esm/model/chat-v2/llmChatV2CachePolicy.js +20 -0
  45. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +8 -54
  46. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +41 -20
  47. package/dist/esm/model/chat-v2/llmChatV2NodeMigration.js +24 -0
  48. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +178 -94
  49. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +60 -0
  50. package/dist/esm/model/chat-v2/llmInvocationDecision.js +11 -0
  51. package/dist/esm/model/chat-v2/llmInvocationJournal.js +43 -0
  52. package/dist/esm/model/chat-v2/llmInvocationPlan.js +68 -0
  53. package/dist/esm/model/chat-v2/llmInvocationProjections.js +5 -0
  54. package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +48 -0
  55. package/dist/esm/model/chat-v2/llmModelCandidate.js +75 -0
  56. package/dist/esm/model/chat-v2/llmProfile.js +31 -65
  57. package/dist/esm/model/chat-v2/llmProfileBody.js +183 -0
  58. package/dist/esm/model/chat-v2/llmProfileFallback.js +244 -0
  59. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +67 -0
  60. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +3 -0
  61. package/dist/esm/model/chat-v2/llmProfileTypes.js +1 -18
  62. package/dist/esm/model/chat-v2/llmResponseMaterializer.js +42 -0
  63. package/dist/esm/model/chat-v2/messageConverter.js +14 -0
  64. package/dist/esm/model/chat-v2/modelRegistry.js +54 -4
  65. package/dist/esm/model/chat-v2/parallelToolCalls.js +9 -2
  66. package/dist/esm/model/chat-v2/providerOptions.js +120 -21
  67. package/dist/esm/model/chat-v2/rivetToolRegistry.js +9 -0
  68. package/dist/esm/model/chat-v2/toolCallCodec.js +52 -0
  69. package/dist/esm/model/chat-v2/toolContinuation.js +72 -39
  70. package/dist/esm/model/chat-v2/toolHandlerResolver.js +23 -0
  71. package/dist/esm/model/chat-v2/toolRoundExecutor.js +12 -0
  72. package/dist/esm/model/nodes/AssembleMessageNode.js +6 -0
  73. package/dist/esm/model/nodes/ChatNode.js +6 -0
  74. package/dist/esm/model/nodes/ChatNodeBase.js +1 -0
  75. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +26 -1
  76. package/dist/esm/model/nodes/LLMChatV2Node.js +131 -144
  77. package/dist/esm/model/nodes/LLMProfileNode.js +27 -8
  78. package/dist/esm/model/nodes/PromptNode.js +16 -2
  79. package/dist/esm/model/nodes/ToolNode.js +7 -0
  80. package/dist/esm/model/nodes/toolCallDelegation.js +193 -110
  81. package/dist/esm/plugins/anthropic/anthropic.js +4 -4
  82. package/dist/esm/plugins/anthropic/nodes/ChatAnthropicNode.js +29 -28
  83. package/dist/esm/plugins/google/google.js +25 -18
  84. package/dist/esm/plugins/google/nodes/ChatGoogleNode.js +21 -7
  85. package/dist/esm/recording/ExecutionRecorder.js +13 -5
  86. package/dist/esm/utils/chatMessageToOpenAIChatCompletionMessage.js +4 -0
  87. package/dist/esm/utils/emitDetached.js +6 -3
  88. package/dist/esm/utils/openai.js +60 -16
  89. package/dist/esm/utils/serialization/serialization.js +2 -0
  90. package/dist/esm/webAppRuntime.js +3 -2
  91. package/dist/types/exports.d.ts +1 -0
  92. package/dist/types/model/AgentResponseTrace.d.ts +110 -0
  93. package/dist/types/model/ConnectedToolContinuationHost.d.ts +34 -0
  94. package/dist/types/model/DataValue.d.ts +7 -1
  95. package/dist/types/model/ExecutorProtocol.d.ts +25 -7
  96. package/dist/types/model/GraphProcessor.d.ts +27 -5
  97. package/dist/types/model/NodeBase.d.ts +6 -0
  98. package/dist/types/model/NodeImpl.d.ts +18 -1
  99. package/dist/types/model/Nodes.d.ts +2 -2
  100. package/dist/types/model/ProcessContext.d.ts +51 -0
  101. package/dist/types/model/ProcessContextBuilder.d.ts +3 -1
  102. package/dist/types/model/RecordingPlayer.d.ts +6 -0
  103. package/dist/types/model/SplitRunProcessor.d.ts +11 -3
  104. package/dist/types/model/UiGraph.d.ts +8 -0
  105. package/dist/types/model/UiGraphActionProtocol.d.ts +2 -0
  106. package/dist/types/model/UiGraphBrowserRuntime.d.ts +11 -2
  107. package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
  108. package/dist/types/model/UiGraphRuntimeModel.d.ts +2 -0
  109. package/dist/types/model/UiGraphSchema.d.ts +1 -0
  110. package/dist/types/model/chat-v2/chatV2CallObserver.d.ts +2 -0
  111. package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +3 -1
  112. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +7 -17
  113. package/dist/types/model/chat-v2/chatV2Pipeline.d.ts +29 -0
  114. package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +5 -0
  115. package/dist/types/model/chat-v2/chatV2ProviderRegistry.d.ts +8 -0
  116. package/dist/types/model/chat-v2/chatV2RequestPlan.d.ts +2 -2
  117. package/dist/types/model/chat-v2/chatV2ResponseBodyCapture.d.ts +19 -0
  118. package/dist/types/model/chat-v2/chatV2ResponseFormat.d.ts +3 -2
  119. package/dist/types/model/chat-v2/chatV2Retry.d.ts +2 -0
  120. package/dist/types/model/chat-v2/chatV2Shared.d.ts +0 -1
  121. package/dist/types/model/chat-v2/chatV2Types.d.ts +35 -1
  122. package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +14 -0
  123. package/dist/types/model/chat-v2/customProviderApi.d.ts +23 -0
  124. package/dist/types/model/chat-v2/developerMessageRoles.d.ts +10 -0
  125. package/dist/types/model/chat-v2/index.d.ts +12 -0
  126. package/dist/types/model/chat-v2/llmChatV2Body.d.ts +24 -0
  127. package/dist/types/model/chat-v2/llmChatV2CacheBoundary.d.ts +10 -0
  128. package/dist/types/model/chat-v2/llmChatV2CachePolicy.d.ts +13 -0
  129. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +13 -3
  130. package/dist/types/model/chat-v2/llmChatV2NodeMigration.d.ts +8 -0
  131. package/dist/types/model/chat-v2/llmChatV2NodeRuntime.d.ts +18 -4
  132. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +16 -0
  133. package/dist/types/model/chat-v2/llmInvocationDecision.d.ts +21 -0
  134. package/dist/types/model/chat-v2/llmInvocationJournal.d.ts +38 -0
  135. package/dist/types/model/chat-v2/llmInvocationPlan.d.ts +41 -0
  136. package/dist/types/model/chat-v2/llmInvocationProjections.d.ts +3 -0
  137. package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +26 -0
  138. package/dist/types/model/chat-v2/llmModelCandidate.d.ts +18 -0
  139. package/dist/types/model/chat-v2/llmProfile.d.ts +7 -0
  140. package/dist/types/model/chat-v2/llmProfileBody.d.ts +20 -0
  141. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +47 -0
  142. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +189 -0
  143. package/dist/types/model/chat-v2/llmProfileTypes.d.ts +1 -1
  144. package/dist/types/model/chat-v2/llmResponseMaterializer.d.ts +20 -0
  145. package/dist/types/model/chat-v2/modelRegistry.d.ts +17 -187
  146. package/dist/types/model/chat-v2/parallelToolCalls.d.ts +3 -1
  147. package/dist/types/model/chat-v2/providerOptions.d.ts +11 -0
  148. package/dist/types/model/chat-v2/rivetToolRegistry.d.ts +11 -0
  149. package/dist/types/model/chat-v2/toolCallCodec.d.ts +7 -0
  150. package/dist/types/model/chat-v2/toolContinuation.d.ts +3 -3
  151. package/dist/types/model/chat-v2/toolHandlerResolver.d.ts +25 -0
  152. package/dist/types/model/chat-v2/toolRoundExecutor.d.ts +18 -0
  153. package/dist/types/model/nodes/AssembleMessageNode.d.ts +2 -1
  154. package/dist/types/model/nodes/ChatNode.d.ts +2 -1
  155. package/dist/types/model/nodes/DelegateFunctionCallNode.d.ts +2 -1
  156. package/dist/types/model/nodes/LLMChatV2Node.d.ts +2 -1
  157. package/dist/types/model/nodes/LLMProfileNode.d.ts +2 -1
  158. package/dist/types/model/nodes/PromptNode.d.ts +6 -3
  159. package/dist/types/model/nodes/ToolNode.d.ts +2 -1
  160. package/dist/types/model/nodes/toolCallDelegation.d.ts +10 -3
  161. package/dist/types/plugins/anthropic/anthropic.d.ts +1 -0
  162. package/dist/types/plugins/google/google.d.ts +14 -9
  163. package/dist/types/plugins/google/nodes/ChatGoogleNode.d.ts +2 -1
  164. package/dist/types/recording/RecordedEvents.d.ts +6 -0
  165. package/dist/types/utils/emitDetached.d.ts +3 -2
  166. package/dist/types/utils/openai.d.ts +49 -0
  167. package/dist/types/webAppRuntime.d.ts +4 -2
  168. package/package.json +2 -2
@@ -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';
@@ -0,0 +1,448 @@
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_TOOL_CALLS = 500;
4
+ export function buildAgentResponseTrace(options) {
5
+ const matchingEvents = deduplicateAgentTraceEvents(options.events.filter((event) => {
6
+ if (event.execution.rootRunId !== options.execution.rootRunId)
7
+ return false;
8
+ if (options.scope === 'response')
9
+ return true;
10
+ if (event.execution.graphRunId !== options.execution.graphRunId)
11
+ return false;
12
+ if (event.type === 'llm-call-finished') {
13
+ return event.nodeId === options.nodeId && event.processId === options.processId;
14
+ }
15
+ return event.sourceNodeId === options.nodeId && event.sourceProcessId === options.processId;
16
+ }));
17
+ const allModelCalls = matchingEvents
18
+ .filter((event) => event.type === 'llm-call-finished')
19
+ .map(toModelCallTrace);
20
+ const allToolCalls = matchingEvents
21
+ .filter((event) => event.type === 'tool-call-finished')
22
+ .map(toToolCallTrace);
23
+ const summary = summarizeAgentCalls(allModelCalls, allToolCalls);
24
+ const terminalAt = options.responseReadyAt ?? options.finishedAt;
25
+ return {
26
+ schemaVersion: AGENT_RESPONSE_TRACE_SCHEMA_VERSION,
27
+ traceId: options.execution.rootRunId,
28
+ scope: options.scope,
29
+ rootRunId: options.execution.rootRunId,
30
+ graphRunId: options.execution.graphRunId,
31
+ graphId: options.execution.graphId,
32
+ ...(options.nodeId == null ? {} : { nodeId: options.nodeId }),
33
+ ...(options.processId == null ? {} : { processId: options.processId }),
34
+ ...(options.startedAt == null ? {} : { startedAt: options.startedAt }),
35
+ ...(options.responseReadyAt == null ? {} : { responseReadyAt: options.responseReadyAt }),
36
+ ...(options.finishedAt == null ? {} : { finishedAt: options.finishedAt }),
37
+ ...(options.startedAt == null || terminalAt == null
38
+ ? {}
39
+ : { durationMs: Math.max(0, terminalAt - options.startedAt) }),
40
+ status: options.status,
41
+ ...(options.backgroundWorkPending == null ? {} : { backgroundWorkPending: options.backgroundWorkPending }),
42
+ summary,
43
+ modelCalls: allModelCalls.slice(0, AGENT_RESPONSE_TRACE_MAX_MODEL_CALLS),
44
+ toolCalls: allToolCalls.slice(0, AGENT_RESPONSE_TRACE_MAX_TOOL_CALLS),
45
+ omittedModelCallCount: Math.max(0, allModelCalls.length - AGENT_RESPONSE_TRACE_MAX_MODEL_CALLS),
46
+ omittedToolCallCount: Math.max(0, allToolCalls.length - AGENT_RESPONSE_TRACE_MAX_TOOL_CALLS),
47
+ };
48
+ }
49
+ /**
50
+ * Trace transport is observational and may redeliver an event. Keep the
51
+ * projection idempotent so repeated delivery cannot inflate call counts,
52
+ * tokens, or cost. Physical model calls and identified tool calls carry stable
53
+ * IDs; anonymous tool events remain distinct because they cannot be matched
54
+ * safely.
55
+ */
56
+ function deduplicateAgentTraceEvents(events) {
57
+ const deduplicated = [];
58
+ const indexByIdentity = new Map();
59
+ for (const event of events) {
60
+ const identity = getAgentTraceEventIdentity(event);
61
+ if (identity == null) {
62
+ deduplicated.push(event);
63
+ continue;
64
+ }
65
+ const existingIndex = indexByIdentity.get(identity);
66
+ if (existingIndex == null) {
67
+ indexByIdentity.set(identity, deduplicated.length);
68
+ deduplicated.push(event);
69
+ }
70
+ else {
71
+ // Preserve first-seen order while retaining the latest terminal metadata.
72
+ deduplicated[existingIndex] = mergeAgentTraceEvent(deduplicated[existingIndex], event);
73
+ }
74
+ }
75
+ return deduplicated;
76
+ }
77
+ export function getAgentTraceEventIdentity(event) {
78
+ if (event.type === 'llm-call-finished') {
79
+ return `model\u0000${event.execution.rootRunId}\u0000${event.execution.graphRunId}\u0000${event.nodeId}\u0000${event.processId}\u0000${event.callId}`;
80
+ }
81
+ return event.toolCallId == null
82
+ ? undefined
83
+ : `tool\u0000${event.execution.rootRunId}\u0000${event.execution.graphRunId}\u0000${event.sourceNodeId}\u0000${event.sourceProcessId}\u0000${event.toolCallId}`;
84
+ }
85
+ /**
86
+ * Redelivery is allowed to omit newly added optional observability fields. Keep
87
+ * an exact Delegate result pointer once it was observed instead of making a
88
+ * later legacy-shaped copy erase result navigation.
89
+ */
90
+ export function mergeAgentTraceEvent(existing, incoming) {
91
+ if (existing.type === 'tool-call-finished' &&
92
+ incoming.type === 'tool-call-finished' &&
93
+ existing.resultOwner != null &&
94
+ incoming.resultOwner == null &&
95
+ isAgentToolResultOutcome(incoming.outcome)) {
96
+ return { ...incoming, resultOwner: existing.resultOwner };
97
+ }
98
+ return incoming;
99
+ }
100
+ function toModelCallTrace(event) {
101
+ return {
102
+ callId: event.callId,
103
+ nodeId: event.nodeId,
104
+ processId: event.processId,
105
+ provider: event.provider,
106
+ model: event.model,
107
+ ...(event.customProviderApi == null ? {} : { customProviderApi: event.customProviderApi }),
108
+ outcome: event.outcome,
109
+ attemptIndex: event.attemptIndex,
110
+ ...(event.profileIndex == null ? {} : { profileIndex: event.profileIndex }),
111
+ ...(event.roundIndex == null ? {} : { roundIndex: event.roundIndex }),
112
+ ...(event.startedAt == null ? {} : { startedAt: event.startedAt }),
113
+ ...(event.durationMs == null ? {} : { durationMs: event.durationMs }),
114
+ ...(event.finishReason == null ? {} : { finishReason: event.finishReason }),
115
+ ...(event.normalizedUsage == null ? {} : { usage: event.normalizedUsage }),
116
+ pricing: event.pricing,
117
+ };
118
+ }
119
+ function toToolCallTrace(event) {
120
+ return {
121
+ ...(event.toolCallId == null ? {} : { toolCallId: event.toolCallId }),
122
+ toolName: event.toolName,
123
+ sourceNodeId: event.sourceNodeId,
124
+ sourceProcessId: event.sourceProcessId,
125
+ ...(event.resultOwner == null ? {} : { resultOwner: event.resultOwner }),
126
+ handlerKind: event.handlerKind,
127
+ ...(event.handlerGraphId == null ? {} : { handlerGraphId: event.handlerGraphId }),
128
+ ...(event.handlerName == null ? {} : { handlerName: event.handlerName }),
129
+ outcome: event.outcome,
130
+ ...(event.startedAt == null ? {} : { startedAt: event.startedAt }),
131
+ ...(event.durationMs == null ? {} : { durationMs: event.durationMs }),
132
+ };
133
+ }
134
+ function summarizeAgentCalls(modelCalls, toolCalls) {
135
+ const usageKeys = ['promptTokens', 'completionTokens', 'totalTokens', 'cachedTokens', 'reasoningTokens'];
136
+ const usage = Object.fromEntries(usageKeys.flatMap((key) => {
137
+ const values = modelCalls.map((call) => call.usage?.[key]).filter((value) => value != null);
138
+ return values.length === 0 ? [] : [[key, values.reduce((sum, value) => sum + value, 0)]];
139
+ }));
140
+ const knownCosts = modelCalls
141
+ .map((call) => call.pricing.costUsd)
142
+ .filter((value) => value != null && Number.isFinite(value));
143
+ const unknownCostCount = modelCalls.filter((call) => call.pricing.status === 'unknown' || !Number.isFinite(call.pricing.costUsd)).length;
144
+ const profileTransitions = countProfileFallbacks(modelCalls);
145
+ return {
146
+ modelCallCount: modelCalls.length,
147
+ toolCallCount: toolCalls.length,
148
+ retryCount: modelCalls.filter((call) => call.attemptIndex > 0).length,
149
+ fallbackCount: profileTransitions,
150
+ ...usage,
151
+ knownCostUsd: knownCosts.reduce((sum, value) => sum + value, 0),
152
+ costStatus: modelCalls.length === 0 || unknownCostCount === modelCalls.length
153
+ ? 'unknown'
154
+ : unknownCostCount > 0
155
+ ? 'partial'
156
+ : 'known',
157
+ };
158
+ }
159
+ /**
160
+ * Counts forward profile advances per physical node invocation. The fallback
161
+ * runner starts at profile zero and stays on or advances from its selected
162
+ * profile across continuation rounds. Using that invariant also accounts for
163
+ * configuration-failed profiles that never produced a physical-call event.
164
+ */
165
+ function countProfileFallbacks(modelCalls) {
166
+ const highestProfileByInvocation = new Map();
167
+ let count = 0;
168
+ for (const call of modelCalls) {
169
+ if (call.profileIndex == null)
170
+ continue;
171
+ const key = `${call.nodeId}\u0000${call.processId}`;
172
+ const highestProfile = highestProfileByInvocation.get(key) ?? 0;
173
+ if (call.profileIndex <= highestProfile)
174
+ continue;
175
+ count += call.profileIndex - highestProfile;
176
+ highestProfileByInvocation.set(key, call.profileIndex);
177
+ }
178
+ return count;
179
+ }
180
+ export function isAgentResponseTrace(value) {
181
+ if (!isRecord(value) || value.schemaVersion !== AGENT_RESPONSE_TRACE_SCHEMA_VERSION)
182
+ return false;
183
+ if (!hasOnlyKeys(value, [
184
+ 'schemaVersion',
185
+ 'traceId',
186
+ 'scope',
187
+ 'rootRunId',
188
+ 'graphRunId',
189
+ 'graphId',
190
+ 'nodeId',
191
+ 'processId',
192
+ 'startedAt',
193
+ 'responseReadyAt',
194
+ 'finishedAt',
195
+ 'durationMs',
196
+ 'status',
197
+ 'backgroundWorkPending',
198
+ 'summary',
199
+ 'modelCalls',
200
+ 'toolCalls',
201
+ 'omittedModelCallCount',
202
+ 'omittedToolCallCount',
203
+ ]))
204
+ return false;
205
+ if (typeof value.traceId !== 'string' || typeof value.rootRunId !== 'string')
206
+ return false;
207
+ if (typeof value.graphRunId !== 'string' || typeof value.graphId !== 'string')
208
+ return false;
209
+ if (value.scope !== 'response' && value.scope !== 'llm-invocation')
210
+ return false;
211
+ if (!isRecord(value.summary) || !Array.isArray(value.modelCalls) || !Array.isArray(value.toolCalls))
212
+ return false;
213
+ if (value.modelCalls.length > AGENT_RESPONSE_TRACE_MAX_MODEL_CALLS)
214
+ return false;
215
+ if (value.toolCalls.length > AGENT_RESPONSE_TRACE_MAX_TOOL_CALLS)
216
+ return false;
217
+ return (isOptionalString(value.nodeId) &&
218
+ isOptionalString(value.processId) &&
219
+ isOptionalNonNegativeFiniteNumber(value.startedAt) &&
220
+ isOptionalNonNegativeFiniteNumber(value.responseReadyAt) &&
221
+ isOptionalNonNegativeFiniteNumber(value.finishedAt) &&
222
+ isOptionalNonNegativeFiniteNumber(value.durationMs) &&
223
+ isOptionalBoolean(value.backgroundWorkPending) &&
224
+ ['running', 'response-ready', 'completed', 'error', 'aborted', 'unavailable'].includes(String(value.status)) &&
225
+ isNonNegativeInteger(value.omittedModelCallCount) &&
226
+ isNonNegativeInteger(value.omittedToolCallCount) &&
227
+ isAgentTraceSummary(value.summary) &&
228
+ value.modelCalls.every(isAgentModelCallTrace) &&
229
+ value.toolCalls.every(isAgentToolCallTrace));
230
+ }
231
+ /**
232
+ * Collects privacy-bounded response metadata for one root processor run.
233
+ * Listener failures are isolated by GraphProcessor; callers should dispose the
234
+ * collector after the processor and any asynchronous branches settle.
235
+ */
236
+ export class AgentResponseTraceCollector {
237
+ #events = [];
238
+ #cleanups = [];
239
+ #startedAt = Date.now();
240
+ #execution;
241
+ #responseReadyAt;
242
+ #finishedAt;
243
+ #status = 'running';
244
+ #backgroundWorkPending = false;
245
+ constructor(processor) {
246
+ this.#cleanups.push(processor.on('start', ({ execution }) => {
247
+ this.#execution = execution;
248
+ }), processor.on('llmCallFinished', (event) => {
249
+ this.#execution ??= event.execution;
250
+ this.#events.push({ type: 'llm-call-finished', ...event });
251
+ }), processor.on('toolCallFinished', (event) => {
252
+ this.#execution ??= event.execution;
253
+ this.#events.push({ type: 'tool-call-finished', ...event });
254
+ }), processor.on('graphOutputsReady', ({ execution }) => {
255
+ if (execution.parentGraphRunId != null)
256
+ return;
257
+ this.#execution ??= execution;
258
+ this.#responseReadyAt ??= Date.now();
259
+ this.#status = 'response-ready';
260
+ this.#backgroundWorkPending = processor.isRunning;
261
+ }), processor.on('graphFinish', ({ execution }) => {
262
+ if (execution.parentGraphRunId != null)
263
+ return;
264
+ this.#execution ??= execution;
265
+ this.#finishedAt = Date.now();
266
+ this.#responseReadyAt ??= this.#finishedAt;
267
+ this.#status = 'completed';
268
+ this.#backgroundWorkPending = false;
269
+ }), processor.on('graphError', ({ execution }) => {
270
+ if (execution.parentGraphRunId != null)
271
+ return;
272
+ this.#execution ??= execution;
273
+ this.#finishedAt = Date.now();
274
+ this.#status = 'error';
275
+ this.#backgroundWorkPending = false;
276
+ }), processor.on('graphAbort', ({ execution }) => {
277
+ if (execution.parentGraphRunId != null)
278
+ return;
279
+ this.#execution ??= execution;
280
+ this.#finishedAt = Date.now();
281
+ this.#status = 'aborted';
282
+ this.#backgroundWorkPending = false;
283
+ }));
284
+ }
285
+ build() {
286
+ if (this.#execution == null)
287
+ return undefined;
288
+ return buildAgentResponseTrace({
289
+ scope: 'response',
290
+ execution: this.#execution,
291
+ events: this.#events,
292
+ startedAt: this.#startedAt,
293
+ ...(this.#responseReadyAt == null ? {} : { responseReadyAt: this.#responseReadyAt }),
294
+ ...(this.#finishedAt == null ? {} : { finishedAt: this.#finishedAt }),
295
+ status: this.#status,
296
+ backgroundWorkPending: this.#backgroundWorkPending,
297
+ });
298
+ }
299
+ dispose() {
300
+ for (const cleanup of this.#cleanups.splice(0))
301
+ cleanup();
302
+ }
303
+ }
304
+ function isAgentModelCallTrace(value) {
305
+ return (isRecord(value) &&
306
+ hasOnlyKeys(value, [
307
+ 'callId',
308
+ 'nodeId',
309
+ 'processId',
310
+ 'provider',
311
+ 'model',
312
+ 'customProviderApi',
313
+ 'outcome',
314
+ 'attemptIndex',
315
+ 'profileIndex',
316
+ 'roundIndex',
317
+ 'startedAt',
318
+ 'durationMs',
319
+ 'finishReason',
320
+ 'usage',
321
+ 'pricing',
322
+ ]) &&
323
+ typeof value.callId === 'string' &&
324
+ typeof value.nodeId === 'string' &&
325
+ typeof value.processId === 'string' &&
326
+ typeof value.provider === 'string' &&
327
+ typeof value.model === 'string' &&
328
+ (value.customProviderApi === undefined ||
329
+ value.customProviderApi === 'completions' ||
330
+ value.customProviderApi === 'responses') &&
331
+ (value.outcome === 'success' || value.outcome === 'provider-failure' || value.outcome === 'aborted') &&
332
+ isNonNegativeInteger(value.attemptIndex) &&
333
+ isOptionalNonNegativeInteger(value.profileIndex) &&
334
+ isOptionalNonNegativeInteger(value.roundIndex) &&
335
+ isOptionalNonNegativeFiniteNumber(value.startedAt) &&
336
+ isOptionalNonNegativeFiniteNumber(value.durationMs) &&
337
+ isOptionalString(value.finishReason) &&
338
+ (value.usage === undefined || isAgentTraceUsage(value.usage)) &&
339
+ isAgentTracePricing(value.pricing));
340
+ }
341
+ function isAgentToolCallTrace(value) {
342
+ const hasKnownOutcome = isRecord(value) &&
343
+ (value.outcome === 'success' ||
344
+ value.outcome === 'passthrough-error' ||
345
+ value.outcome === 'failure' ||
346
+ value.outcome === 'aborted');
347
+ return (isRecord(value) &&
348
+ hasOnlyKeys(value, [
349
+ 'toolCallId',
350
+ 'toolName',
351
+ 'sourceNodeId',
352
+ 'sourceProcessId',
353
+ 'resultOwner',
354
+ 'handlerKind',
355
+ 'handlerGraphId',
356
+ 'handlerName',
357
+ 'outcome',
358
+ 'startedAt',
359
+ 'durationMs',
360
+ ]) &&
361
+ isOptionalString(value.toolCallId) &&
362
+ typeof value.toolName === 'string' &&
363
+ typeof value.sourceNodeId === 'string' &&
364
+ typeof value.sourceProcessId === 'string' &&
365
+ (value.resultOwner === undefined ||
366
+ (isAgentToolResultOutcome(value.outcome) && isAgentToolResultOwner(value.resultOwner))) &&
367
+ (value.handlerKind === 'graph' || value.handlerKind === 'external' || value.handlerKind === 'unknown') &&
368
+ isOptionalString(value.handlerGraphId) &&
369
+ isOptionalString(value.handlerName) &&
370
+ hasKnownOutcome &&
371
+ isOptionalNonNegativeFiniteNumber(value.startedAt) &&
372
+ isOptionalNonNegativeFiniteNumber(value.durationMs));
373
+ }
374
+ function isAgentToolResultOutcome(value) {
375
+ return value === 'success' || value === 'passthrough-error';
376
+ }
377
+ function isAgentToolResultOwner(value) {
378
+ return (isRecord(value) &&
379
+ hasOnlyKeys(value, ['nodeId', 'processId', 'outputPortId']) &&
380
+ typeof value.nodeId === 'string' &&
381
+ typeof value.processId === 'string' &&
382
+ typeof value.outputPortId === 'string');
383
+ }
384
+ function isAgentTraceSummary(value) {
385
+ return (hasOnlyKeys(value, [
386
+ 'modelCallCount',
387
+ 'toolCallCount',
388
+ 'retryCount',
389
+ 'fallbackCount',
390
+ 'promptTokens',
391
+ 'completionTokens',
392
+ 'totalTokens',
393
+ 'cachedTokens',
394
+ 'reasoningTokens',
395
+ 'knownCostUsd',
396
+ 'costStatus',
397
+ ]) &&
398
+ isNonNegativeInteger(value.modelCallCount) &&
399
+ isNonNegativeInteger(value.toolCallCount) &&
400
+ isNonNegativeInteger(value.retryCount) &&
401
+ isNonNegativeInteger(value.fallbackCount) &&
402
+ isOptionalNonNegativeFiniteNumber(value.promptTokens) &&
403
+ isOptionalNonNegativeFiniteNumber(value.completionTokens) &&
404
+ isOptionalNonNegativeFiniteNumber(value.totalTokens) &&
405
+ isOptionalNonNegativeFiniteNumber(value.cachedTokens) &&
406
+ isOptionalNonNegativeFiniteNumber(value.reasoningTokens) &&
407
+ isNonNegativeFiniteNumber(value.knownCostUsd) &&
408
+ (value.costStatus === 'known' || value.costStatus === 'partial' || value.costStatus === 'unknown'));
409
+ }
410
+ function isAgentTraceUsage(value) {
411
+ return (isRecord(value) &&
412
+ hasOnlyKeys(value, ['promptTokens', 'completionTokens', 'totalTokens', 'cachedTokens', 'reasoningTokens']) &&
413
+ Object.values(value).every(isNonNegativeFiniteNumber));
414
+ }
415
+ function isAgentTracePricing(value) {
416
+ return (isRecord(value) &&
417
+ hasOnlyKeys(value, ['status', 'costUsd']) &&
418
+ (value.status === 'known' || value.status === 'unknown') &&
419
+ isOptionalNonNegativeFiniteNumber(value.costUsd));
420
+ }
421
+ function hasOnlyKeys(value, allowed) {
422
+ const allowedKeys = new Set(allowed);
423
+ return Object.keys(value).every((key) => allowedKeys.has(key));
424
+ }
425
+ function isFiniteNumber(value) {
426
+ return typeof value === 'number' && Number.isFinite(value);
427
+ }
428
+ function isNonNegativeFiniteNumber(value) {
429
+ return isFiniteNumber(value) && value >= 0;
430
+ }
431
+ function isOptionalNonNegativeFiniteNumber(value) {
432
+ return value === undefined || isNonNegativeFiniteNumber(value);
433
+ }
434
+ function isNonNegativeInteger(value) {
435
+ return Number.isInteger(value) && value >= 0;
436
+ }
437
+ function isOptionalNonNegativeInteger(value) {
438
+ return value === undefined || isNonNegativeInteger(value);
439
+ }
440
+ function isOptionalString(value) {
441
+ return value === undefined || typeof value === 'string';
442
+ }
443
+ function isOptionalBoolean(value) {
444
+ return value === undefined || typeof value === 'boolean';
445
+ }
446
+ function isRecord(value) {
447
+ return typeof value === 'object' && value != null && !Array.isArray(value);
448
+ }
@@ -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
+ }