@valerypopoff/rivet2-core 2.17.0 → 2.21.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 (120) hide show
  1. package/dist/cjs/bundle.cjs +3197 -1461
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/interpolationRuntime.cjs +40 -4
  4. package/dist/cjs/interpolationRuntime.cjs.map +2 -2
  5. package/dist/cjs/serialization.cjs +1880 -0
  6. package/dist/cjs/serialization.cjs.map +7 -0
  7. package/dist/cjs/webAppRuntime.cjs +168 -6
  8. package/dist/cjs/webAppRuntime.cjs.map +3 -3
  9. package/dist/esm/api/processSettings.js +1 -0
  10. package/dist/esm/exports.js +3 -0
  11. package/dist/esm/model/AgentResponseTrace.js +99 -34
  12. package/dist/esm/model/AgentResponseTracePresentation.js +130 -0
  13. package/dist/esm/model/DataValue.js +11 -2
  14. package/dist/esm/model/GlobalVariables.js +2 -1
  15. package/dist/esm/model/GraphBoundaryEffects.js +38 -1
  16. package/dist/esm/model/GraphExecutionState.js +81 -0
  17. package/dist/esm/model/GraphProcessor.js +625 -943
  18. package/dist/esm/model/GraphSchedulerBoundaryState.js +64 -0
  19. package/dist/esm/model/Nodes.js +5 -0
  20. package/dist/esm/model/ProjectBundle.js +69 -11
  21. package/dist/esm/model/ProjectBundleRuntime.js +54 -0
  22. package/dist/esm/model/ProjectGraphCallSites.js +46 -0
  23. package/dist/esm/model/SchedulerBoundaryPlanner.js +233 -0
  24. package/dist/esm/model/SubprocessorBridge.js +125 -87
  25. package/dist/esm/model/ToolCallContinuationCoordinator.js +1 -1
  26. package/dist/esm/model/chat-v2/aiSdkBridge.js +15 -12
  27. package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -4
  28. package/dist/esm/model/chat-v2/chatV2CredentialNames.js +5 -1
  29. package/dist/esm/model/chat-v2/chatV2Outputs.js +2 -2
  30. package/dist/esm/model/chat-v2/chatV2Pipeline.js +11 -1
  31. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +3 -2
  32. package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +46 -6
  33. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +7 -0
  34. package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +10 -0
  35. package/dist/esm/model/chat-v2/llmChatV2Body.js +3 -3
  36. package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +5 -2
  37. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +1 -0
  38. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +25 -15
  39. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +10 -2
  40. package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +17 -0
  41. package/dist/esm/model/chat-v2/llmModelCandidate.js +2 -1
  42. package/dist/esm/model/chat-v2/llmProfile.js +2 -1
  43. package/dist/esm/model/chat-v2/llmProfileBody.js +9 -0
  44. package/dist/esm/model/chat-v2/llmProfileFallback.js +7 -4
  45. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +1 -0
  46. package/dist/esm/model/chat-v2/llmProfileHealthStore.js +16 -3
  47. package/dist/esm/model/chat-v2/messageConverter.js +18 -16
  48. package/dist/esm/model/chat-v2/modelRegistry.js +14 -4
  49. package/dist/esm/model/chat-v2/openRouterModel.js +73 -0
  50. package/dist/esm/model/chat-v2/parallelToolCalls.js +2 -0
  51. package/dist/esm/model/chat-v2/providerOptions.js +30 -25
  52. package/dist/esm/model/classifier/credentials.js +13 -3
  53. package/dist/esm/model/classifier/limits.js +33 -3
  54. package/dist/esm/model/classifier/perplexity.js +63 -0
  55. package/dist/esm/model/classifier/profile.js +151 -0
  56. package/dist/esm/model/classifier/profileExecution.js +294 -0
  57. package/dist/esm/model/classifier/providers.js +217 -30
  58. package/dist/esm/model/classifier/state.js +4 -1
  59. package/dist/esm/model/classifier/types.js +11 -1
  60. package/dist/esm/model/nodeRunFailure.js +8 -1
  61. package/dist/esm/model/nodes/CallGraphNode.js +6 -0
  62. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +257 -66
  63. package/dist/esm/model/nodes/ClassifierProfileNode.js +133 -0
  64. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +1 -1
  65. package/dist/esm/model/nodes/LLMChatV2Node.js +2 -1
  66. package/dist/esm/model/nodes/SubGraphNode.js +4 -0
  67. package/dist/esm/model/nodes/toolCallDelegation.js +5 -1
  68. package/dist/esm/model/profileSuspensionHints.js +8 -0
  69. package/dist/esm/serialization.js +2 -0
  70. package/dist/esm/utils/coerceType.js +11 -1
  71. package/dist/esm/webAppRuntime.js +1 -0
  72. package/dist/types/exports.d.ts +3 -0
  73. package/dist/types/model/AgentResponseTrace.d.ts +15 -4
  74. package/dist/types/model/AgentResponseTracePresentation.d.ts +15 -0
  75. package/dist/types/model/DataValue.d.ts +12 -8
  76. package/dist/types/model/ExecutorProtocol.d.ts +14 -2
  77. package/dist/types/model/GraphBoundaryEffects.d.ts +10 -1
  78. package/dist/types/model/GraphExecutionState.d.ts +68 -0
  79. package/dist/types/model/GraphProcessor.d.ts +1 -0
  80. package/dist/types/model/GraphSchedulerBoundaryState.d.ts +96 -0
  81. package/dist/types/model/Nodes.d.ts +7 -4
  82. package/dist/types/model/ProcessContext.d.ts +12 -3
  83. package/dist/types/model/ProjectBundle.d.ts +18 -4
  84. package/dist/types/model/ProjectBundleRuntime.d.ts +24 -0
  85. package/dist/types/model/ProjectGraphCallSites.d.ts +12 -0
  86. package/dist/types/model/RivetUIContext.d.ts +1 -1
  87. package/dist/types/model/SchedulerBoundaryPlanner.d.ts +42 -0
  88. package/dist/types/model/Settings.d.ts +1 -0
  89. package/dist/types/model/SubgraphProjectTarget.d.ts +6 -0
  90. package/dist/types/model/SubprocessorBridge.d.ts +2 -0
  91. package/dist/types/model/chat-v2/chatV2CredentialNames.d.ts +4 -0
  92. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +1 -1
  93. package/dist/types/model/chat-v2/chatV2ProviderRegistry.d.ts +79 -1
  94. package/dist/types/model/chat-v2/chatV2ProviderTypes.d.ts +1 -1
  95. package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +2 -0
  96. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +2 -1
  97. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +2 -0
  98. package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +2 -0
  99. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +51 -3
  100. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +9 -6
  101. package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +6 -2
  102. package/dist/types/model/chat-v2/modelRegistry.d.ts +5 -4
  103. package/dist/types/model/chat-v2/openRouterModel.d.ts +2 -0
  104. package/dist/types/model/chat-v2/providerOptions.d.ts +2 -13
  105. package/dist/types/model/classifier/credentials.d.ts +4 -0
  106. package/dist/types/model/classifier/limits.d.ts +4 -1
  107. package/dist/types/model/classifier/perplexity.d.ts +7 -0
  108. package/dist/types/model/classifier/profile.d.ts +46 -0
  109. package/dist/types/model/classifier/profileExecution.d.ts +32 -0
  110. package/dist/types/model/classifier/providers.d.ts +32 -1
  111. package/dist/types/model/classifier/types.d.ts +9 -0
  112. package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +14 -12
  113. package/dist/types/model/nodes/ClassifierProfileNode.d.ts +20 -0
  114. package/dist/types/model/nodes/SubGraphNode.d.ts +1 -1
  115. package/dist/types/model/nodes/toolCallDelegation.d.ts +3 -1
  116. package/dist/types/model/profileSuspensionHints.d.ts +8 -0
  117. package/dist/types/recording/ExecutionRecorder.d.ts +5 -1
  118. package/dist/types/serialization.d.ts +2 -0
  119. package/dist/types/webAppRuntime.d.ts +1 -0
  120. package/package.json +7 -1
@@ -11,6 +11,7 @@ export function resolveProcessSettings(settings = {}, fallbacks = {}) {
11
11
  openAiKey: openAiApiKey,
12
12
  anthropicApiKey: settings.anthropicApiKey || fallbacks.anthropicApiKey || '',
13
13
  googleApiKey: settings.googleApiKey || fallbacks.googleApiKey || '',
14
+ openRouterApiKey: settings.openRouterApiKey || fallbacks.openRouterApiKey || '',
14
15
  customAiApiKey: settings.customAiApiKey || fallbacks.customAiApiKey || '',
15
16
  openAiOrganization: settings.openAiOrganization ?? fallbacks.openAiOrganization ?? '',
16
17
  openAiEndpoint: settings.openAiEndpoint ?? fallbacks.openAiEndpoint ?? '',
@@ -31,10 +31,13 @@ export * from './native/NativeApi.js';
31
31
  export * from './native/BrowserNativeApi.js';
32
32
  export * from './model/ProcessContext.js';
33
33
  export * from './model/AgentResponseTrace.js';
34
+ export * from './model/AgentResponseTracePresentation.js';
34
35
  export * from './model/DebuggerTransportSentinel.js';
35
36
  export * from './model/ProjectReferenceLoader.js';
36
37
  export * from './model/SubgraphProjectTarget.js';
38
+ export * from './model/ProjectGraphCallSites.js';
37
39
  export * from './model/ProjectBundle.js';
40
+ export * from './model/ProjectBundleRuntime.js';
38
41
  export * from './model/RivetUIContext.js';
39
42
  export * from './model/chat-v2/index.js';
40
43
  export * from './integrations/integrations.js';
@@ -1,3 +1,4 @@
1
+ import { classifierFailureKinds } from './classifier/types.js';
1
2
  export const AGENT_RESPONSE_TRACE_SCHEMA_VERSION = 1;
2
3
  export const AGENT_RESPONSE_TRACE_MAX_MODEL_CALLS = 250;
3
4
  export const AGENT_RESPONSE_TRACE_MAX_PROFILE_ATTEMPTS = 1_000;
@@ -27,9 +28,9 @@ export function buildAgentResponseTrace(options) {
27
28
  const allToolCalls = matchingEvents
28
29
  .filter((event) => event.type === 'tool-call-finished')
29
30
  .map(toToolCallTrace);
30
- const summary = summarizeAgentCalls(allModelCalls, allProfileAttempts, allToolCalls);
31
+ const summary = summarizeAgentResponseCalls(allModelCalls, allProfileAttempts, allToolCalls);
31
32
  const terminalAt = options.responseReadyAt ?? options.finishedAt;
32
- const durationMs = options.scope === 'llm-invocation' && isNonNegativeFiniteNumber(options.invocationDurationMs)
33
+ const durationMs = options.scope !== 'response' && isNonNegativeFiniteNumber(options.invocationDurationMs)
33
34
  ? options.invocationDurationMs
34
35
  : isNonNegativeFiniteNumber(options.startedAt) &&
35
36
  isNonNegativeFiniteNumber(terminalAt) &&
@@ -101,31 +102,15 @@ export function getAgentTraceEventIdentity(event) {
101
102
  }
102
103
  /**
103
104
  * Redelivery is allowed to omit newly added optional observability fields. Keep
104
- * an exact Delegate result pointer once it was observed instead of making a
105
- * later legacy-shaped copy erase result navigation.
105
+ * observed profile metadata and exact Delegate result pointers instead of
106
+ * making a later legacy-shaped copy erase diagnostics or result navigation.
106
107
  */
107
108
  export function mergeAgentTraceEvent(existing, incoming) {
108
109
  if (existing.type === 'llm-call-finished' && incoming.type === 'llm-call-finished') {
109
- return {
110
- ...incoming,
111
- ...(incoming.profileName == null && existing.profileName != null
112
- ? { profileName: existing.profileName }
113
- : {}),
114
- ...(incoming.profileHealthKey == null && existing.profileHealthKey != null
115
- ? { profileHealthKey: existing.profileHealthKey }
116
- : {}),
117
- ...(incoming.profileHealthState == null && existing.profileHealthState != null
118
- ? { profileHealthState: existing.profileHealthState }
119
- : {}),
120
- };
110
+ return mergeAgentModelCall(existing, incoming);
121
111
  }
122
112
  if (existing.type === 'llm-profile-attempt' && incoming.type === 'llm-profile-attempt') {
123
- return {
124
- ...incoming,
125
- ...(incoming.profileName == null && existing.profileName != null
126
- ? { profileName: existing.profileName }
127
- : {}),
128
- };
113
+ return mergeAgentProfileAttempt(existing, incoming);
129
114
  }
130
115
  if (existing.type === 'tool-call-finished' &&
131
116
  incoming.type === 'tool-call-finished' &&
@@ -136,6 +121,42 @@ export function mergeAgentTraceEvent(existing, incoming) {
136
121
  }
137
122
  return incoming;
138
123
  }
124
+ /** Redelivery may omit optional receipts, but supplied pricing remains authoritative. */
125
+ export function mergeAgentModelCall(existing, incoming) {
126
+ return {
127
+ ...existing,
128
+ ...incoming,
129
+ ...(existing.outcome !== incoming.outcome && incoming.finishReason == null ? { finishReason: undefined } : {}),
130
+ ...(incoming.profileName == null && existing.profileName != null ? { profileName: existing.profileName } : {}),
131
+ ...(incoming.profileHealthKey == null && existing.profileHealthKey != null
132
+ ? { profileHealthKey: existing.profileHealthKey }
133
+ : {}),
134
+ ...(incoming.profileHealthState == null && existing.profileHealthState != null
135
+ ? { profileHealthState: existing.profileHealthState }
136
+ : {}),
137
+ ...(incoming.durationMs == null && existing.durationMs != null ? { durationMs: existing.durationMs } : {}),
138
+ ...(incoming.normalizedUsage == null && existing.normalizedUsage != null
139
+ ? { normalizedUsage: existing.normalizedUsage }
140
+ : {}),
141
+ };
142
+ }
143
+ /** Merge one identified attempt, retaining additive metadata omitted by older transports. */
144
+ export function mergeAgentProfileAttempt(existing, incoming) {
145
+ return {
146
+ // Failure/health details only belong to the same outcome. A corrected
147
+ // outcome must not inherit stale failure metadata.
148
+ ...(existing.outcome === incoming.outcome ? existing : {}),
149
+ ...incoming,
150
+ ...(incoming.family == null && existing.family != null ? { family: existing.family } : {}),
151
+ ...(incoming.profileName == null && existing.profileName != null ? { profileName: existing.profileName } : {}),
152
+ ...(incoming.profileIndex == null && existing.profileIndex != null ? { profileIndex: existing.profileIndex } : {}),
153
+ ...(incoming.attemptIndex == null && existing.attemptIndex != null ? { attemptIndex: existing.attemptIndex } : {}),
154
+ ...(incoming.durationMs == null && existing.durationMs != null ? { durationMs: existing.durationMs } : {}),
155
+ ...(incoming.classifierUsage == null && existing.classifierUsage != null
156
+ ? { classifierUsage: existing.classifierUsage }
157
+ : {}),
158
+ };
159
+ }
139
160
  function toModelCallTrace(event) {
140
161
  return {
141
162
  callId: event.callId,
@@ -177,25 +198,47 @@ function toProfileAttemptTrace(event) {
177
198
  const { type: _type, execution: _execution, ...trace } = event;
178
199
  return trace;
179
200
  }
180
- function summarizeAgentCalls(modelCalls, profileAttempts, toolCalls) {
201
+ /** Shared metadata accounting for response inspectors and the bounded activity journal. */
202
+ export function summarizeAgentResponseCalls(modelCalls, profileAttempts, toolCalls) {
203
+ const classifierCalls = profileAttempts.filter((attempt) => attempt.family === 'classifier' && attempt.attemptIndex != null);
204
+ const accountedCallCount = modelCalls.length + classifierCalls.length;
181
205
  const usageKeys = ['promptTokens', 'completionTokens', 'totalTokens', 'cachedTokens', 'reasoningTokens'];
182
206
  const usage = Object.fromEntries(usageKeys.flatMap((key) => {
183
207
  const values = modelCalls.map((call) => call.usage?.[key]).filter((value) => value != null);
208
+ for (const attempt of classifierCalls) {
209
+ const receipt = attempt.classifierUsage;
210
+ if (!receipt)
211
+ continue;
212
+ if (key === 'promptTokens')
213
+ values.push(receipt.inputTokens);
214
+ if (key === 'completionTokens')
215
+ values.push(receipt.outputTokens);
216
+ if (key === 'totalTokens')
217
+ values.push(receipt.inputTokens + receipt.outputTokens);
218
+ }
184
219
  return values.length === 0 ? [] : [[key, values.reduce((sum, value) => sum + value, 0)]];
185
220
  }));
186
- const knownCosts = modelCalls
187
- .map((call) => call.pricing.costUsd)
188
- .filter((value) => value != null && Number.isFinite(value));
189
- const unknownCostCount = modelCalls.filter((call) => call.pricing.status === 'unknown' || !Number.isFinite(call.pricing.costUsd)).length;
221
+ const knownCosts = [
222
+ ...modelCalls
223
+ .map((call) => call.pricing.costUsd)
224
+ .filter((value) => value != null && Number.isFinite(value)),
225
+ ...classifierCalls.flatMap((attempt) => attempt.classifierUsage?.estimatedCostUsd == null ? [] : [attempt.classifierUsage.estimatedCostUsd]),
226
+ ];
227
+ const unknownCostCount = modelCalls.filter((call) => call.pricing.status === 'unknown' || !Number.isFinite(call.pricing.costUsd)).length +
228
+ classifierCalls.filter((attempt) => attempt.classifierUsage?.estimatedCostUsd == null).length;
190
229
  const profileTransitions = countProfileFallbacks(modelCalls, profileAttempts);
191
230
  return {
192
231
  modelCallCount: modelCalls.length,
232
+ ...(profileAttempts.some((attempt) => attempt.family === 'classifier')
233
+ ? { classifierRequestCount: classifierCalls.length }
234
+ : {}),
193
235
  toolCallCount: toolCalls.length,
194
- retryCount: modelCalls.filter((call) => call.attemptIndex > 0).length,
236
+ retryCount: modelCalls.filter((call) => call.attemptIndex > 0).length +
237
+ classifierCalls.filter((attempt) => attempt.attemptIndex > 0).length,
195
238
  fallbackCount: profileTransitions,
196
239
  ...usage,
197
240
  knownCostUsd: knownCosts.reduce((sum, value) => sum + value, 0),
198
- costStatus: modelCalls.length === 0 || unknownCostCount === modelCalls.length
241
+ costStatus: accountedCallCount === 0 || unknownCostCount === accountedCallCount
199
242
  ? 'unknown'
200
243
  : unknownCostCount > 0
201
244
  ? 'partial'
@@ -215,7 +258,7 @@ function countProfileFallbacks(modelCalls, profileAttempts) {
215
258
  ...modelCalls.flatMap((call) => call.profileIndex == null
216
259
  ? []
217
260
  : [{ nodeId: call.nodeId, processId: call.processId, profileIndex: call.profileIndex }]),
218
- ...profileAttempts.flatMap((attempt) => attempt.profileIndex == null
261
+ ...profileAttempts.flatMap((attempt) => attempt.profileIndex == null || attempt.skipReason === 'unreached'
219
262
  ? []
220
263
  : [{ nodeId: attempt.nodeId, processId: attempt.processId, profileIndex: attempt.profileIndex }]),
221
264
  ];
@@ -260,7 +303,7 @@ export function isAgentResponseTrace(value) {
260
303
  return false;
261
304
  if (typeof value.graphRunId !== 'string' || typeof value.graphId !== 'string')
262
305
  return false;
263
- if (value.scope !== 'response' && value.scope !== 'llm-invocation')
306
+ if (value.scope !== 'response' && value.scope !== 'llm-invocation' && value.scope !== 'classifier-invocation')
264
307
  return false;
265
308
  if (!isRecord(value.summary) || !Array.isArray(value.modelCalls) || !Array.isArray(value.toolCalls))
266
309
  return false;
@@ -268,8 +311,7 @@ export function isAgentResponseTrace(value) {
268
311
  return false;
269
312
  if (value.modelCalls.length > AGENT_RESPONSE_TRACE_MAX_MODEL_CALLS)
270
313
  return false;
271
- if (Array.isArray(value.profileAttempts) &&
272
- value.profileAttempts.length > AGENT_RESPONSE_TRACE_MAX_PROFILE_ATTEMPTS)
314
+ if (Array.isArray(value.profileAttempts) && value.profileAttempts.length > AGENT_RESPONSE_TRACE_MAX_PROFILE_ATTEMPTS)
273
315
  return false;
274
316
  if (value.toolCalls.length > AGENT_RESPONSE_TRACE_MAX_TOOL_CALLS)
275
317
  return false;
@@ -434,11 +476,22 @@ function isAgentLLMProfileAttemptTrace(value) {
434
476
  'healthOutcome',
435
477
  'retryAt',
436
478
  'timeoutKind',
479
+ 'family',
480
+ 'failureKind',
481
+ 'skipReason',
482
+ 'classifierUsage',
483
+ 'durationMs',
437
484
  ]) &&
438
485
  typeof value.eventId === 'string' &&
439
486
  isNonNegativeInteger(value.roundIndex) &&
440
487
  isOptionalNonNegativeInteger(value.profileIndex) &&
441
488
  isOptionalString(value.profileName) &&
489
+ isOptionalNonNegativeFiniteNumber(value.durationMs) &&
490
+ (value.family === undefined || value.family === 'llm' || value.family === 'classifier') &&
491
+ (value.skipReason === undefined || (value.skipReason === 'unreached' && value.outcome === 'skipped')) &&
492
+ (value.classifierUsage === undefined ||
493
+ (value.family === 'classifier' && isClassifierAttemptUsage(value.classifierUsage))) &&
494
+ (value.failureKind === undefined || classifierFailureKinds.includes(value.failureKind)) &&
442
495
  typeof value.nodeId === 'string' &&
443
496
  typeof value.processId === 'string' &&
444
497
  typeof value.provider === 'string' &&
@@ -467,7 +520,17 @@ function isAgentLLMProfileAttemptTrace(value) {
467
520
  isOptionalNonNegativeFiniteNumber(value.retryAt) &&
468
521
  (value.timeoutKind === undefined ||
469
522
  value.timeoutKind === 'first-output' ||
470
- value.timeoutKind === 'stream-inactivity'));
523
+ value.timeoutKind === 'stream-inactivity' ||
524
+ value.timeoutKind === 'response'));
525
+ }
526
+ function isClassifierAttemptUsage(value) {
527
+ return (isRecord(value) &&
528
+ hasOnlyKeys(value, ['inputTokens', 'outputTokens', 'estimatedCostUsd']) &&
529
+ Number.isSafeInteger(value.inputTokens) &&
530
+ value.inputTokens >= 0 &&
531
+ Number.isSafeInteger(value.outputTokens) &&
532
+ value.outputTokens >= 0 &&
533
+ isOptionalNonNegativeFiniteNumber(value.estimatedCostUsd));
471
534
  }
472
535
  function isAgentToolCallTrace(value) {
473
536
  const hasKnownOutcome = isRecord(value) &&
@@ -515,6 +578,7 @@ function isAgentToolResultOwner(value) {
515
578
  function isAgentTraceSummary(value) {
516
579
  return (hasOnlyKeys(value, [
517
580
  'modelCallCount',
581
+ 'classifierRequestCount',
518
582
  'toolCallCount',
519
583
  'retryCount',
520
584
  'fallbackCount',
@@ -527,6 +591,7 @@ function isAgentTraceSummary(value) {
527
591
  'costStatus',
528
592
  ]) &&
529
593
  isNonNegativeInteger(value.modelCallCount) &&
594
+ isOptionalNonNegativeInteger(value.classifierRequestCount) &&
530
595
  isNonNegativeInteger(value.toolCallCount) &&
531
596
  isNonNegativeInteger(value.retryCount) &&
532
597
  isNonNegativeInteger(value.fallbackCount) &&
@@ -0,0 +1,130 @@
1
+ import { getCustomProviderApiContract } from './chat-v2/customProviderApi.js';
2
+ export function buildAgentProfileAttemptInspectorRows(attempts) {
3
+ return attempts.map((attempt) => ({
4
+ eventId: attempt.eventId,
5
+ providerAndModel: [
6
+ ...(attempt.profileName == null || attempt.profileName.trim() === ''
7
+ ? []
8
+ : [`Profile: ${attempt.profileName.trim()}`]),
9
+ `${formatProvider(attempt)} / ${attempt.model}`,
10
+ ].join(' · '),
11
+ context: [
12
+ attempt.failureKind?.replaceAll('-', ' ') ?? describeStage(attempt.stage),
13
+ describeOutcome(attempt),
14
+ attempt.profileIndex == null ? undefined : `profile ${attempt.profileIndex + 1}`,
15
+ attempt.family === 'classifier' ? undefined : `round ${attempt.roundIndex + 1}`,
16
+ attempt.attemptIndex == null ? undefined : `attempt ${attempt.attemptIndex + 1}`,
17
+ attempt.status == null ? undefined : `HTTP ${attempt.status}`,
18
+ attempt.durationMs == null
19
+ ? isClassifierRequest(attempt)
20
+ ? 'duration unavailable'
21
+ : undefined
22
+ : `${(attempt.durationMs / 1000).toFixed(2)} sec`,
23
+ attempt.classifierUsage == null
24
+ ? isClassifierRequest(attempt)
25
+ ? 'usage not reported'
26
+ : undefined
27
+ : `${attempt.classifierUsage.inputTokens} input / ${attempt.classifierUsage.outputTokens} output tokens`,
28
+ attempt.classifierUsage == null
29
+ ? isClassifierRequest(attempt)
30
+ ? 'cost unknown'
31
+ : undefined
32
+ : attempt.classifierUsage.estimatedCostUsd == null
33
+ ? 'cost unknown'
34
+ : `estimated $${attempt.classifierUsage.estimatedCostUsd.toPrecision(4)}`,
35
+ ]
36
+ .filter((value) => value != null)
37
+ .join(' / '),
38
+ ...(attempt.error == null ? {} : { error: attempt.error }),
39
+ }));
40
+ }
41
+ /** Physical classifier requests share profile evidence, not LLM chat-round semantics. */
42
+ export function isClassifierRequest(attempt) {
43
+ return attempt.family === 'classifier' && attempt.attemptIndex != null;
44
+ }
45
+ export function getClassifierRequestCount(trace) {
46
+ if (trace.summary.classifierRequestCount != null)
47
+ return trace.summary.classifierRequestCount;
48
+ const attempts = trace.profileAttempts?.filter((attempt) => attempt.family === 'classifier');
49
+ if (trace.scope !== 'classifier-invocation' && !attempts?.length)
50
+ return undefined;
51
+ // Older schema-v1 hosts recorded attempts before adding a dedicated counter.
52
+ return attempts?.filter(isClassifierRequest).length ?? 0;
53
+ }
54
+ /** Older trace counters inferred from capped rows are lower bounds, not exact totals. */
55
+ export function formatClassifierRequestCount(trace) {
56
+ const count = getClassifierRequestCount(trace);
57
+ if (count == null)
58
+ return undefined;
59
+ return trace.summary.classifierRequestCount == null && (trace.omittedProfileAttemptCount ?? 0) > 0
60
+ ? `${count} (retained evidence only)`
61
+ : String(count);
62
+ }
63
+ /** One shared cap covers both physical classifier requests and profile decisions. */
64
+ export function getProfileAttemptOmissionNotice(trace) {
65
+ const omitted = trace.omittedProfileAttemptCount ?? 0;
66
+ return omitted > 0
67
+ ? `${omitted} additional profile-attempt rows (requests or decisions) omitted by the trace limit.`
68
+ : undefined;
69
+ }
70
+ function formatProvider(attempt) {
71
+ return attempt.provider === 'custom'
72
+ ? getCustomProviderApiContract(attempt.customProviderApi).label
73
+ : attempt.provider;
74
+ }
75
+ function describeStage(stage) {
76
+ switch (stage) {
77
+ case 'health-gate':
78
+ return 'reliability check';
79
+ case 'health-update':
80
+ return 'reliability update';
81
+ case 'response-validation':
82
+ return 'response validation';
83
+ default:
84
+ return stage;
85
+ }
86
+ }
87
+ function describeOutcome(attempt) {
88
+ if (attempt.skipReason === 'unreached')
89
+ return 'not reached';
90
+ if (attempt.healthDisposition === 'deny') {
91
+ return attempt.retryAt == null
92
+ ? 'profile suspended; skipped'
93
+ : `profile suspended until ${new Date(attempt.retryAt).toLocaleString()}`;
94
+ }
95
+ if (attempt.healthDisposition === 'fail-open') {
96
+ return 'reliability service unavailable; profile request continued';
97
+ }
98
+ if (attempt.timeoutKind === 'first-output')
99
+ return 'first output timed out';
100
+ if (attempt.timeoutKind === 'stream-inactivity')
101
+ return 'stream became inactive';
102
+ if (attempt.timeoutKind === 'response')
103
+ return 'response timed out';
104
+ if (attempt.stage === 'health-update' && attempt.healthOutcome) {
105
+ return `recorded ${describeReliabilityOutcome(attempt.healthOutcome)}${describeReliabilityState(attempt.healthState)}`;
106
+ }
107
+ return `${attempt.outcome}${describeReliabilityState(attempt.healthState)}`;
108
+ }
109
+ function describeReliabilityOutcome(outcome) {
110
+ switch (outcome) {
111
+ case 'healthy':
112
+ return 'success';
113
+ case 'unhealthy':
114
+ return 'failure';
115
+ default:
116
+ return 'ignored result';
117
+ }
118
+ }
119
+ function describeReliabilityState(state) {
120
+ switch (state) {
121
+ case 'open':
122
+ return '; profile suspended';
123
+ case 'half-open':
124
+ return '; recovery attempt in progress';
125
+ case 'closed':
126
+ return '; profile available';
127
+ default:
128
+ return '';
129
+ }
130
+ }
@@ -1,7 +1,7 @@
1
1
  import { exhaustiveTuple } from '../utils/genericUtilFunctions.js';
2
2
  import { createDefaultLLMProfileValue } from './chat-v2/llmProfileTypes.js';
3
- export const dataTypes = exhaustiveTuple()('any', 'any[]', 'boolean', 'boolean[]', 'string', 'string[]', 'number', 'number[]', 'date', 'date[]', 'time', 'time[]', 'datetime', 'datetime[]', 'chat-message', 'chat-message[]', 'control-flow-excluded', 'control-flow-excluded[]', 'object', 'object[]', 'fn<string>', 'fn<number>', 'fn<boolean>', 'fn<date>', 'fn<time>', 'fn<datetime>', 'fn<any>', 'fn<object>', 'fn<chat-message>', 'fn<control-flow-excluded>', 'fn<string[]>', 'fn<number[]>', 'fn<boolean[]>', 'fn<date[]>', 'fn<time[]>', 'fn<datetime[]>', 'fn<any[]>', 'fn<object[]>', 'fn<chat-message[]>', 'fn<control-flow-excluded[]>', 'gpt-function', 'gpt-function[]', 'fn<gpt-function[]>', 'fn<gpt-function>', 'vector', 'vector[]', 'fn<vector>', 'fn<vector[]>', 'image', 'image[]', 'fn<image>', 'fn<image[]>', 'binary', 'binary[]', 'fn<binary>', 'fn<binary[]>', 'audio', 'audio[]', 'fn<audio>', 'fn<audio[]>', 'graph-reference', 'graph-reference[]', 'fn<graph-reference>', 'fn<graph-reference[]>', 'knowledge-source', 'knowledge-source[]', 'fn<knowledge-source>', 'fn<knowledge-source[]>', 'knowledge-document', 'knowledge-document[]', 'fn<knowledge-document>', 'fn<knowledge-document[]>', 'knowledge-evidence', 'knowledge-evidence[]', 'fn<knowledge-evidence>', 'fn<knowledge-evidence[]>', 'llm-config', 'llm-config[]', 'fn<llm-config>', 'fn<llm-config[]>', 'document', 'document[]', 'fn<document>', 'fn<document[]>');
4
- export const scalarTypes = exhaustiveTuple()('any', 'boolean', 'string', 'number', 'date', 'time', 'datetime', 'chat-message', 'control-flow-excluded', 'object', 'gpt-function', 'vector', 'image', 'binary', 'audio', 'graph-reference', 'knowledge-source', 'knowledge-document', 'knowledge-evidence', 'llm-config', 'document');
3
+ export const dataTypes = exhaustiveTuple()('any', 'any[]', 'boolean', 'boolean[]', 'string', 'string[]', 'number', 'number[]', 'date', 'date[]', 'time', 'time[]', 'datetime', 'datetime[]', 'chat-message', 'chat-message[]', 'control-flow-excluded', 'control-flow-excluded[]', 'object', 'object[]', 'fn<string>', 'fn<number>', 'fn<boolean>', 'fn<date>', 'fn<time>', 'fn<datetime>', 'fn<any>', 'fn<object>', 'fn<chat-message>', 'fn<control-flow-excluded>', 'fn<string[]>', 'fn<number[]>', 'fn<boolean[]>', 'fn<date[]>', 'fn<time[]>', 'fn<datetime[]>', 'fn<any[]>', 'fn<object[]>', 'fn<chat-message[]>', 'fn<control-flow-excluded[]>', 'gpt-function', 'gpt-function[]', 'fn<gpt-function[]>', 'fn<gpt-function>', 'vector', 'vector[]', 'fn<vector>', 'fn<vector[]>', 'image', 'image[]', 'fn<image>', 'fn<image[]>', 'binary', 'binary[]', 'fn<binary>', 'fn<binary[]>', 'audio', 'audio[]', 'fn<audio>', 'fn<audio[]>', 'graph-reference', 'graph-reference[]', 'fn<graph-reference>', 'fn<graph-reference[]>', 'knowledge-source', 'knowledge-source[]', 'fn<knowledge-source>', 'fn<knowledge-source[]>', 'knowledge-document', 'knowledge-document[]', 'fn<knowledge-document>', 'fn<knowledge-document[]>', 'knowledge-evidence', 'knowledge-evidence[]', 'fn<knowledge-evidence>', 'fn<knowledge-evidence[]>', 'llm-config', 'llm-config[]', 'fn<llm-config>', 'fn<llm-config[]>', 'classifier-config', 'classifier-config[]', 'fn<classifier-config>', 'fn<classifier-config[]>', 'document', 'document[]', 'fn<document>', 'fn<document[]>');
4
+ export const scalarTypes = exhaustiveTuple()('any', 'boolean', 'string', 'number', 'date', 'time', 'datetime', 'chat-message', 'control-flow-excluded', 'object', 'gpt-function', 'vector', 'image', 'binary', 'audio', 'graph-reference', 'knowledge-source', 'knowledge-document', 'knowledge-evidence', 'llm-config', 'classifier-config', 'document');
5
5
  export const dataTypeDisplayNames = {
6
6
  any: 'Any',
7
7
  'any[]': 'Any Array',
@@ -80,6 +80,10 @@ export const dataTypeDisplayNames = {
80
80
  'fn<knowledge-evidence>': 'Function<Knowledge Evidence>',
81
81
  'fn<knowledge-evidence[]>': 'Function<Knowledge Evidence Array>',
82
82
  'llm-config': 'LLM Profile',
83
+ 'classifier-config': 'Classifier Profile',
84
+ 'classifier-config[]': 'Classifier Profile Array',
85
+ 'fn<classifier-config>': 'Function<Classifier Profile>',
86
+ 'fn<classifier-config[]>': 'Function<Classifier Profile Array>',
83
87
  'llm-config[]': 'LLM Profile Array',
84
88
  'fn<llm-config>': 'Function<LLM Profile>',
85
89
  'fn<llm-config[]>': 'Function<LLM Profile Array>',
@@ -203,6 +207,11 @@ export const scalarDefaults = {
203
207
  documentId: '',
204
208
  },
205
209
  'llm-config': createDefaultLLMProfileValue(),
210
+ 'classifier-config': {
211
+ version: 1,
212
+ configuration: { provider: 'jev', model: 'jev-latest' },
213
+ credential: {},
214
+ },
206
215
  document: {
207
216
  mediaType: 'text/plain',
208
217
  data: new Uint8Array(),
@@ -346,7 +346,8 @@ function validateStructuredScalar(type, value, label) {
346
346
  requireString(message.name, `${label}.name`);
347
347
  return;
348
348
  }
349
- case 'llm-config': {
349
+ case 'llm-config':
350
+ case 'classifier-config': {
350
351
  const profile = requirePlainRecord(value, label);
351
352
  if (profile.version !== 1)
352
353
  throw literalError(`${label}.version`, 'must be version 1');
@@ -8,7 +8,40 @@ export function commitGraphOutputValue(graphOutputs, outputId, value) {
8
8
  graphOutputs[outputId] = value;
9
9
  }
10
10
  }
11
- export function ensureGraphCostOutput(graphOutputs, totalCost) {
11
+ /** Safe family totals carried across graph and tool boundaries, separate from node diagnostics. */
12
+ export function readGraphCostBreakdown(outputs) {
13
+ const output = outputs['costBreakdown'];
14
+ if (output?.type !== 'object' ||
15
+ output.value == null ||
16
+ typeof output.value !== 'object' ||
17
+ Array.isArray(output.value))
18
+ return undefined;
19
+ // Metadata is data, not executable plugin/authored accessors. Read each own
20
+ // field exactly once and never invoke a getter while accounting a node.
21
+ const fields = ['llm', 'classifier', 'other'].map((key) => Object.getOwnPropertyDescriptor(output.value, key));
22
+ if (!fields.every((field) => field &&
23
+ 'value' in field &&
24
+ typeof field.value === 'number' &&
25
+ Number.isFinite(field.value) &&
26
+ field.value >= 0))
27
+ return undefined;
28
+ return { llm: fields[0].value, classifier: fields[1].value, other: fields[2].value };
29
+ }
30
+ export function graphCostBreakdownMatchesCost(breakdown, cost) {
31
+ const sum = breakdown.llm + breakdown.classifier + breakdown.other;
32
+ return (Number.isFinite(cost) &&
33
+ cost >= 0 &&
34
+ Number.isFinite(sum) &&
35
+ Math.abs(sum - cost) <= Number.EPSILON * Math.max(1, Math.abs(cost)) * 8);
36
+ }
37
+ export function addGraphCostBreakdown(current, addition) {
38
+ return {
39
+ llm: (current?.llm ?? 0) + addition.llm,
40
+ classifier: (current?.classifier ?? 0) + addition.classifier,
41
+ other: (current?.other ?? 0) + addition.other,
42
+ };
43
+ }
44
+ export function ensureGraphCostOutput(graphOutputs, totalCost, breakdown) {
12
45
  const costPort = 'cost';
13
46
  if (graphOutputs[costPort] == null) {
14
47
  graphOutputs[costPort] = {
@@ -16,6 +49,10 @@ export function ensureGraphCostOutput(graphOutputs, totalCost) {
16
49
  value: totalCost,
17
50
  };
18
51
  }
52
+ if (breakdown && graphOutputs['costBreakdown'] == null) {
53
+ // Snapshot: early outputs must not change when background work settles.
54
+ graphOutputs['costBreakdown'] = { type: 'object', value: { ...breakdown } };
55
+ }
19
56
  }
20
57
  export function applyFrozenGraphBoundaryEffects(graphOutputs, node, outputValues) {
21
58
  if (node.type === 'graphOutput') {
@@ -0,0 +1,81 @@
1
+ /** Invocation-owned fields; GraphProcessor resets them at the established initialization boundaries. */
2
+ export class GraphInvocationState {
3
+ rootRunId = undefined;
4
+ graphRunId = undefined;
5
+ parentGraphRunId = undefined;
6
+ erroredNodes = undefined; // Values are strings in recordings
7
+ failureOutputsByProcessId = undefined;
8
+ remainingNodes = undefined;
9
+ visitedNodes = undefined;
10
+ currentlyProcessing = undefined;
11
+ context = undefined;
12
+ nodeResults = undefined;
13
+ abortController = undefined;
14
+ processingQueue = undefined;
15
+ graphInputs = undefined;
16
+ graphOutputs = undefined;
17
+ queuedNodes = undefined;
18
+ /** Run To quiescence may defer nodes that a later streaming Stop resumes. */
19
+ deferredRunToIgnoredNodes = undefined;
20
+ loopControllersSeen = undefined;
21
+ subprocessors = undefined;
22
+ attachedNodeData = undefined;
23
+ successfulAbortTerminalProcessIds = undefined;
24
+ totalCost = 0;
25
+ costBreakdown;
26
+ ignoreNodes = undefined;
27
+ hasPreloadedData = false;
28
+ loadedProjects = undefined;
29
+ nodeProcessContextBase = undefined;
30
+ runToRelevantNodeIds;
31
+ graphOutputSelection;
32
+ nodeAbortControllers = new Map();
33
+ graphInputNodeValues = {};
34
+ /** User input nodes awaiting interactive input for this invocation. */
35
+ pendingUserInputs = undefined;
36
+ /** Mutate the owner in place: late child cost/events still address this invocation. */
37
+ initialize(options) {
38
+ this.nodeResults = new Map(options.preloadedNodeResults);
39
+ this.visitedNodes = new Set(options.preloadedNodeResults.keys());
40
+ this.hasPreloadedData = options.preloadedNodeResults.size > 0;
41
+ this.erroredNodes = new Map();
42
+ this.failureOutputsByProcessId = new Map();
43
+ this.currentlyProcessing = new Set();
44
+ this.remainingNodes = new Set(options.remainingNodeIds);
45
+ this.pendingUserInputs = {};
46
+ this.processingQueue = options.processingQueue;
47
+ this.graphOutputs = options.sharedOverride?.graphOutputs ?? {};
48
+ this.queuedNodes = new Set();
49
+ this.deferredRunToIgnoredNodes = new Set();
50
+ this.loopControllersSeen = new Set();
51
+ this.subprocessors = new Set();
52
+ this.attachedNodeData = options.sharedOverride?.attachedNodeData ?? new Map();
53
+ this.ignoreNodes = new Set();
54
+ this.nodeProcessContextBase = undefined;
55
+ this.runToRelevantNodeIds = undefined;
56
+ this.graphOutputSelection = undefined;
57
+ this.abortController = options.createAbortController();
58
+ this.successfulAbortTerminalProcessIds = new Set();
59
+ this.totalCost = 0;
60
+ this.costBreakdown = undefined;
61
+ this.nodeAbortControllers = new Map();
62
+ this.loadedProjects = options.loadedProjects;
63
+ this.graphInputNodeValues = options.sharedOverride?.graphInputNodeValues ?? {};
64
+ // Execution identity, context and inputs are rebound by initializeGraphRun.
65
+ }
66
+ }
67
+ /** Shared by every child kind; retained caches/globals deliberately keep existing reuse semantics. */
68
+ export class GraphSharedExecutionState {
69
+ globals = undefined;
70
+ executionCache = undefined;
71
+ storedValueController = undefined;
72
+ knowledgeStoreController = undefined;
73
+ subgraphTargetCache = new Map();
74
+ nextRootRun() {
75
+ const next = new GraphSharedExecutionState();
76
+ // Latest/Published targets are resolved afresh; old children keep their scope.
77
+ next.globals = this.globals;
78
+ next.executionCache = this.executionCache;
79
+ return next;
80
+ }
81
+ }