@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
@@ -13,8 +13,11 @@ export function prepareClassifierState(input, budget) {
13
13
  throw new Error('Rivet State input and provider State cannot be supplied together.');
14
14
  return prepareRivetState(input.stateInput, budget);
15
15
  }
16
- if (input.stateMessages === undefined)
16
+ if (input.stateMessages === undefined) {
17
+ if (typeof input.state !== 'string' && !record(input.state) && !Array.isArray(input.state))
18
+ throw new Error('State must be text, a JSON object or an array.');
17
19
  return { kind: 'json', value: snapshotClassifierJson(input.state, 'State', budget) };
20
+ }
18
21
  if (input.state !== '')
19
22
  throw new Error('Structured State and multimodal State messages cannot be supplied together.');
20
23
  const messages = snapshotClassifierJson(input.stateMessages, 'State', budget);
@@ -1 +1,11 @@
1
- export {};
1
+ /** Secret-free classification used by fallback diagnostics and recording traces. */
2
+ export const classifierFailureKinds = [
3
+ 'configuration',
4
+ 'capability',
5
+ 'authentication',
6
+ 'transport',
7
+ 'http',
8
+ 'timeout',
9
+ 'response-parsing',
10
+ 'response-validation',
11
+ ];
@@ -36,7 +36,14 @@ export function createCaughtRunFailureOutputs(definitions, error, evidence) {
36
36
  for (const definition of definitions) {
37
37
  outputs[definition.id] = { type: 'control-flow-excluded', value: undefined };
38
38
  }
39
- for (const id of ['requestBody', 'responseBody', 'llmAttempts', 'llmProfileSummary']) {
39
+ for (const id of [
40
+ 'requestBody',
41
+ 'responseBody',
42
+ 'llmAttempts',
43
+ 'llmProfileSummary',
44
+ 'classifierAttempts',
45
+ 'classifierProfileSummary',
46
+ ]) {
40
47
  const port = id;
41
48
  if (port in outputs && evidence?.[port] != null)
42
49
  outputs[port] = evidence[port];
@@ -102,6 +102,12 @@ export class CallGraphNodeImpl extends NodeImpl {
102
102
  type: 'object',
103
103
  value: graphOutputs,
104
104
  };
105
+ // Carry implicit graph metrics outside the wrapped user outputs so the
106
+ // containing processor accounts this invocation just like a Subgraph.
107
+ for (const metric of ['cost', 'costBreakdown']) {
108
+ if (graphOutputs[metric])
109
+ outputs[metric] = graphOutputs[metric];
110
+ }
105
111
  if (this.data.useErrorOutput) {
106
112
  outputs['error'] = {
107
113
  type: 'control-flow-excluded',
@@ -5,13 +5,19 @@ import { createExcludedNodeOutputs } from '../NodeExclusionPolicy.js';
5
5
  import { formatNodeBodyMarkdownField, formatNodeBodyMarkdownSeparator } from '../nodeBodyMarkdown.js';
6
6
  import { createCaughtRunFailureOutputs, getRunFailureOutputDefinitions, shouldCatchRunFailure, withRunSuccessOutputs, } from '../nodeRunFailure.js';
7
7
  import { getNextVariadicPortIndex } from './variadicPortIndex.js';
8
- import { resolveClassifierApiKey, } from '../classifier/credentials.js';
8
+ import { resolveClassifierApiKey } from '../classifier/credentials.js';
9
9
  import { classifierArrayValues, classifierInputDataValue } from '../classifier/json.js';
10
10
  import { normalizeClassifierState } from '../classifier/state.js';
11
11
  import { CLASSIFIER_LIMITS, classifierPreparationCheck, ClassifierValueBudget } from '../classifier/limits.js';
12
- import { calculateClassifierUsageCost, classifierProviders, DEFAULT_CLASSIFIER_RETRY_ON_NON_200_COOLDOWN_MS, DEFAULT_CLASSIFIER_RETRY_ON_NON_200_REPEAT_TIMES, getClassifierProvider, normalizeClassifierNon200RetryCooldownMs, normalizeClassifierNon200RetryCount, } from '../classifier/providers.js';
12
+ import { calculateClassifierUsageCost, classifierFailureKind, classifierProviders, DEFAULT_CLASSIFIER_RETRY_ON_NON_200_COOLDOWN_MS, DEFAULT_CLASSIFIER_RETRY_ON_NON_200_REPEAT_TIMES, getClassifierProvider, normalizeClassifierNon200RetryCooldownMs, normalizeClassifierNon200RetryCount, } from '../classifier/providers.js';
13
+ import { normalizeClassifierProfiles } from '../classifier/profile.js';
14
+ import { classifierProfileSummary, ClassifierProfileExhaustedError, runClassifierProfiles, } from '../classifier/profileExecution.js';
15
+ import { prepareClassifierQuestion } from '../classifier/questions.js';
13
16
  const QUESTION_TYPES = ['object', 'object[]', 'any', 'any[]'];
14
17
  export class ClassifierEvaluateNodeImpl extends NodeImpl {
18
+ getRunActivityDescriptor() {
19
+ return { category: 'model', primaryOutputPortId: 'answers' };
20
+ }
15
21
  static create() {
16
22
  return {
17
23
  type: 'classifierEvaluate',
@@ -46,10 +52,21 @@ export class ClassifierEvaluateNodeImpl extends NodeImpl {
46
52
  splitRunBehavior: 'preserve-array',
47
53
  },
48
54
  ];
49
- if (this.data.useModelInput) {
55
+ if (this.data.configurationMode === 'profile') {
56
+ inputs.unshift({
57
+ id: 'classifierProfile',
58
+ title: 'Classifier Profiles',
59
+ dataType: ['classifier-config', 'classifier-config[]'],
60
+ required: true,
61
+ coerced: true,
62
+ splitRunBehavior: 'preserve-array',
63
+ description: 'One Classifier Profile or an ordered fallback chain.',
64
+ });
65
+ }
66
+ if (this.data.configurationMode !== 'profile' && this.data.useModelInput) {
50
67
  inputs.push({ id: 'model', title: 'Model', dataType: 'string', required: true });
51
68
  }
52
- if (this.data.apiKeySource === 'input') {
69
+ if (this.data.configurationMode !== 'profile' && this.data.apiKeySource === 'input') {
53
70
  inputs.push({ id: 'apiKey', title: 'API Key', dataType: 'string', required: true });
54
71
  }
55
72
  const count = getNextVariadicPortIndex(connections, this.chartNode.id, 'question', 'strict-positive');
@@ -81,71 +98,48 @@ export class ClassifierEvaluateNodeImpl extends NodeImpl {
81
98
  if (this.data.outputResponseBody === true) {
82
99
  outputs.push({ id: 'responseBody', title: 'Response body', dataType: 'object' });
83
100
  }
101
+ if (this.data.outputClassifierAttempts)
102
+ outputs.push({ id: 'classifierAttempts', title: 'Classifier Attempts', dataType: 'object[]' });
103
+ if (this.data.configurationMode === 'profile' && this.data.outputClassifierProfileSummary)
104
+ outputs.push({
105
+ id: 'classifierProfileSummary',
106
+ title: 'Classifier Profile Summary',
107
+ dataType: 'string',
108
+ });
84
109
  return [...outputs, ...getRunFailureOutputDefinitions({ catchRequestFailed: this.data.catchRequestFailed })];
85
110
  }
86
111
  getEditors() {
87
112
  return [
88
- {
89
- type: 'group',
90
- label: 'Model',
91
- defaultOpen: true,
92
- editors: [
93
- {
94
- type: 'dropdown',
95
- label: 'Provider',
96
- dataKey: 'provider',
97
- defaultValue: 'jev',
98
- options: classifierProviders.map((provider) => ({ value: provider.id, label: provider.label })),
99
- },
100
- {
101
- type: 'string',
102
- label: 'Model',
103
- dataKey: 'model',
104
- useInputToggleDataKey: 'useModelInput',
105
- placeholder: getProviderForDisplay(this.data.provider).defaultModel,
106
- },
107
- {
108
- type: 'segmented',
109
- label: 'API key source',
110
- ariaLabel: 'API key source',
111
- dataKey: 'apiKeySource',
112
- defaultValue: 'configured',
113
- options: [
114
- { value: 'configured', label: 'Automatic' },
115
- { value: 'classifier-settings', label: 'Classifier settings' },
116
- { value: 'input', label: 'Input port' },
117
- ],
118
- helperMessage: getApiKeySourceHelperMessage,
119
- },
120
- {
121
- type: 'custom',
122
- label: 'Configured API key names',
123
- customEditorId: 'ClassifierCredentialNames',
124
- hideIf: (data) => data.apiKeySource === 'input' || data.apiKeySource === 'classifier-settings',
125
- },
126
- ],
127
- },
113
+ { type: 'custom', label: 'Configuration', customEditorId: 'ClassifierConfiguration' },
114
+ { ...getClassifierModelEditor(this.data), hideIf: (data) => data.configurationMode === 'profile' },
128
115
  {
129
116
  type: 'group',
130
117
  label: 'Outputs',
131
118
  editors: [
132
119
  {
133
120
  type: 'toggle',
134
- label: 'Output usage details',
121
+ label: 'Usage details',
135
122
  dataKey: 'outputUsage',
136
123
  helperMessage: 'Adds estimated totalCost to Usage only for recognized requested/returned models. Unknown pricing is omitted. Provider-specific premiums are not included.',
137
124
  },
138
125
  {
139
126
  type: 'toggle',
140
- label: 'Output request body',
127
+ label: 'Request body',
141
128
  dataKey: 'outputRequestBody',
142
129
  helperMessage: 'Adds the exact classifier request JSON body sent to the provider. It excludes authorization headers and Rivet-managed API keys.',
143
130
  },
144
131
  {
145
132
  type: 'toggle',
146
- label: 'Output response body',
133
+ label: 'Response body',
147
134
  dataKey: 'outputResponseBody',
148
- helperMessage: 'Adds the complete classifier JSON response returned by the provider after validation. Rivet does not redact or truncate captured content.',
135
+ helperMessage: 'Shows the provider response, including rejected or invalid responses. Non-JSON responses appear as raw text. Captured content may contain sensitive input.',
136
+ },
137
+ { type: 'toggle', label: 'Classifier attempts', dataKey: 'outputClassifierAttempts' },
138
+ {
139
+ type: 'toggle',
140
+ label: 'Classifier profile summary',
141
+ dataKey: 'outputClassifierProfileSummary',
142
+ hideIf: (data) => data.configurationMode !== 'profile',
149
143
  },
150
144
  ],
151
145
  },
@@ -156,12 +150,12 @@ export class ClassifierEvaluateNodeImpl extends NodeImpl {
156
150
  {
157
151
  type: 'number',
158
152
  label: 'Overall timeout (seconds)',
159
- dataKey: 'timeoutMs',
160
- defaultValue: 30,
153
+ dataKey: this.data.configurationMode === 'profile' ? 'profileChainTimeoutMs' : 'timeoutMs',
154
+ defaultValue: this.data.configurationMode === 'profile' ? 180_000 : 30_000,
161
155
  storageMultiplier: 1000,
162
- min: 1,
163
- max: 600,
164
- step: 1,
156
+ min: 1_000,
157
+ max: 600_000,
158
+ step: 1_000,
165
159
  },
166
160
  ],
167
161
  },
@@ -171,14 +165,14 @@ export class ClassifierEvaluateNodeImpl extends NodeImpl {
171
165
  editors: [
172
166
  {
173
167
  type: 'toggle',
174
- label: 'Fail on non-2XX status code',
168
+ label: 'Throw exception on non-2XX status code',
175
169
  dataKey: 'errorOnNon200',
176
170
  defaultValue: true,
177
- helperMessage: 'After retries, throw on a rejected HTTP request. When disabled, unavailable outputs are excluded. Run failed and Run error are available only when Catch all failures is enabled.',
171
+ helperMessage: 'After retries, throw on a rejected HTTP request. When disabled, unavailable outputs are excluded. Run failed and Run error are available only when Catch all exceptions is enabled.',
178
172
  },
179
173
  {
180
174
  type: 'toggle',
181
- label: 'Catch all failures',
175
+ label: 'Catch all exceptions',
182
176
  dataKey: 'catchRequestFailed',
183
177
  helperMessage: 'Return any node execution failure through Run failed and Run error instead of stopping the graph. Explicit graph cancellation is never caught.',
184
178
  },
@@ -236,25 +230,84 @@ export class ClassifierEvaluateNodeImpl extends NodeImpl {
236
230
  };
237
231
  }
238
232
  async process(inputs, context) {
233
+ const attempts = [];
234
+ const bodies = {};
235
+ let getRequestBody;
236
+ const diagnostics = {
237
+ ...(this.data.outputRequestBody || this.data.outputResponseBody
238
+ ? {
239
+ onRequestBody: (getBody) => {
240
+ // Pair the last prepared request with its response, never bodies from different candidates.
241
+ delete bodies['responseBody'];
242
+ if (this.data.outputRequestBody)
243
+ getRequestBody = getBody;
244
+ },
245
+ }
246
+ : {}),
247
+ ...(this.data.outputResponseBody
248
+ ? {
249
+ onResponseBody: (body) => {
250
+ bodies['responseBody'] = {
251
+ type: 'object',
252
+ value: body !== null && typeof body === 'object' && !Array.isArray(body)
253
+ ? body
254
+ : { raw: body },
255
+ };
256
+ },
257
+ }
258
+ : {}),
259
+ };
239
260
  try {
240
261
  context.signal.throwIfAborted();
241
- const outputs = await this.processRun(inputs, context);
262
+ const outputs = await this.processRun(inputs, context, attempts, diagnostics);
242
263
  context.signal.throwIfAborted();
243
264
  return withRunSuccessOutputs({ catchRequestFailed: this.data.catchRequestFailed }, outputs);
244
265
  }
245
266
  catch (error) {
246
- if (!shouldCatchRunFailure(this.data, error, context.signal))
267
+ try {
268
+ if (getRequestBody)
269
+ bodies['requestBody'] = { type: 'object', value: getRequestBody() };
270
+ }
271
+ catch {
272
+ /* Request diagnostics cannot replace the execution failure. */
273
+ }
274
+ const evidence = {
275
+ ...bodies,
276
+ ...this.profileEvidence(attempts, error instanceof ClassifierProfileExhaustedError ? error.summary : undefined),
277
+ };
278
+ const failure = error instanceof ClassifierProfileExhaustedError ? { statusCode: error.statusCode } : error;
279
+ if (!shouldCatchRunFailure(this.data, failure, context.signal)) {
280
+ try {
281
+ if (Object.keys(evidence).length) {
282
+ if (context.setFailureOutputs)
283
+ context.setFailureOutputs(evidence);
284
+ else
285
+ context.onPartialOutputs?.(evidence);
286
+ }
287
+ }
288
+ catch {
289
+ /* Diagnostics must not replace the original failure. */
290
+ }
247
291
  throw error;
292
+ }
248
293
  return this.data.catchRequestFailed === true
249
- ? createCaughtRunFailureOutputs(this.getOutputDefinitions(), error)
250
- : createExcludedNodeOutputs(this.chartNode, this.getOutputDefinitions());
294
+ ? createCaughtRunFailureOutputs(this.getOutputDefinitions(), error, evidence)
295
+ : { ...createExcludedNodeOutputs(this.chartNode, this.getOutputDefinitions()), ...evidence };
251
296
  }
252
297
  }
253
- async processRun(inputs, context) {
254
- const timeoutMs = normalizeTimeout(this.data.timeoutMs);
298
+ async processRun(inputs, context, attempts, diagnostics) {
299
+ if (this.data.configurationMode !== undefined &&
300
+ this.data.configurationMode !== 'inline' &&
301
+ this.data.configurationMode !== 'profile')
302
+ throw new Error('Unknown classifier configuration mode.');
303
+ const timeoutMs = this.data.configurationMode === 'profile'
304
+ ? normalizeTimeout(this.data.profileChainTimeoutMs ?? 180_000)
305
+ : normalizeTimeout(this.data.timeoutMs);
255
306
  const deadline = Date.now() + timeoutMs;
256
307
  const checkPreparation = classifierPreparationCheck(context.signal, deadline, timeoutMs);
257
308
  checkPreparation();
309
+ if (this.data.configurationMode === 'profile')
310
+ return this.processProfiles(inputs, context, deadline, checkPreparation, attempts, diagnostics);
258
311
  const provider = getClassifierProvider(this.data.provider);
259
312
  if (!provider.browserExecutionSupported && context.executor === 'browser') {
260
313
  throw new Error(`${provider.label} cannot run in the Browser executor. Select the Node executor, or run through Studio Server or remote debugging.`);
@@ -313,10 +366,33 @@ export class ClassifierEvaluateNodeImpl extends NodeImpl {
313
366
  ...state,
314
367
  timeoutMs,
315
368
  deadline,
369
+ ...diagnostics,
370
+ onAttempt: ({ kind, ...attempt }) => {
371
+ const event = {
372
+ ...attempt,
373
+ family: 'classifier',
374
+ roundIndex: 0,
375
+ provider: provider.id,
376
+ model: modelValue,
377
+ stage: kind === 'response-validation' || kind === 'response-parsing' ? 'response-validation' : 'request',
378
+ failureKind: kind ? classifierFailureKind(kind, attempt.status) : undefined,
379
+ timeoutKind: kind === 'timeout' ? 'response' : undefined,
380
+ };
381
+ attempts.push(event);
382
+ context.onLLMProfileAttempt?.({
383
+ ...structuredClone(event),
384
+ eventId: nanoid(),
385
+ nodeId: this.chartNode.id,
386
+ processId: context.processId,
387
+ });
388
+ },
316
389
  });
317
390
  // Custom providers still own their asynchronous transport, but no late
318
391
  // result may become a successful node output after the original deadline.
319
392
  checkPreparation();
393
+ return { ...this.projectResult(provider, modelValue, result, checkPreparation), ...this.profileEvidence(attempts) };
394
+ }
395
+ projectResult(provider, modelValue, result, checkPreparation) {
320
396
  const totalCost = calculateClassifierUsageCost(provider, result.response.usage, {
321
397
  requestedModel: modelValue,
322
398
  responseModel: result.response.model,
@@ -344,6 +420,114 @@ export class ClassifierEvaluateNodeImpl extends NodeImpl {
344
420
  }
345
421
  return outputs;
346
422
  }
423
+ profileEvidence(attempts, summary) {
424
+ return {
425
+ ...(this.data.outputClassifierAttempts
426
+ ? { ['classifierAttempts']: { type: 'object[]', value: attempts } }
427
+ : {}),
428
+ ...(this.data.configurationMode === 'profile' && this.data.outputClassifierProfileSummary && summary !== undefined
429
+ ? { ['classifierProfileSummary']: { type: 'string', value: summary } }
430
+ : {}),
431
+ };
432
+ }
433
+ async processProfiles(inputs, context, deadline, check, attempts, diagnostics) {
434
+ const profiles = normalizeClassifierProfiles(classifierInputDataValue(inputs, 'classifierProfile')?.value, check);
435
+ const graph = context.project?.graphs[context.execution?.graphId];
436
+ if (classifierInputDataValue(inputs, 'images') !== undefined ||
437
+ graph?.connections.some((connection) => connection.inputNodeId === this.id && connection.inputId === 'images'))
438
+ throw new Error('The separate Images input has been removed. Connect images or an assembled user message to State.');
439
+ const state = normalizeClassifierState(classifierInputDataValue(inputs, 'state'), check);
440
+ const budget = new ClassifierValueBudget(check);
441
+ budget.inspect(state);
442
+ const values = [];
443
+ const work = { values: 0 };
444
+ for (const port of Object.keys(inputs)
445
+ .filter((id) => /^question\d+$/.test(id))
446
+ .sort(compareQuestionPorts)) {
447
+ const input = classifierInputDataValue(inputs, port);
448
+ if (input)
449
+ flattenQuestions(input.value, values, check, new Set(), 0, work);
450
+ }
451
+ if (!values.length)
452
+ throw new Error('Classifier Evaluate requires at least one question.');
453
+ const ids = new Set();
454
+ const questions = values.map((value) => {
455
+ const question = prepareClassifierQuestion(value, budget);
456
+ if (ids.has(question.questionId))
457
+ throw new Error(`Question ID '${question.questionId}' is duplicated in this evaluation.`);
458
+ ids.add(question.questionId);
459
+ return question;
460
+ });
461
+ const selected = await runClassifierProfiles({
462
+ profiles,
463
+ state,
464
+ questions,
465
+ context,
466
+ nodeId: this.chartNode.id,
467
+ deadline,
468
+ retryOnNon200: this.data.retryOnNon200,
469
+ retryOnNon200RepeatTimes: this.data.retryOnNon200RepeatTimes,
470
+ retryOnNon200CooldownMs: this.data.retryOnNon200CooldownMs,
471
+ ...diagnostics,
472
+ onAttempt: (attempt) => {
473
+ attempts.push(attempt);
474
+ context.onLLMProfileAttempt?.({
475
+ ...structuredClone(attempt),
476
+ eventId: nanoid(),
477
+ nodeId: this.chartNode.id,
478
+ processId: context.processId,
479
+ });
480
+ },
481
+ });
482
+ check();
483
+ return {
484
+ ...this.projectResult(selected.provider, selected.model, selected.result, check),
485
+ ...this.profileEvidence(attempts, classifierProfileSummary(profiles, attempts)),
486
+ };
487
+ }
488
+ }
489
+ /** Shared settings definition; constructing an unrelated node is unnecessary. */
490
+ export function getClassifierModelEditor(data) {
491
+ return {
492
+ type: 'group',
493
+ label: 'Model',
494
+ defaultOpen: true,
495
+ editors: [
496
+ {
497
+ type: 'dropdown',
498
+ label: 'Provider',
499
+ dataKey: 'provider',
500
+ defaultValue: 'jev',
501
+ options: classifierProviders.map((provider) => ({ value: provider.id, label: provider.label })),
502
+ },
503
+ {
504
+ type: 'string',
505
+ label: 'Model',
506
+ dataKey: 'model',
507
+ useInputToggleDataKey: 'useModelInput',
508
+ placeholder: getProviderForDisplay(data.provider).defaultModel,
509
+ },
510
+ {
511
+ type: 'segmented',
512
+ label: 'API key source',
513
+ ariaLabel: 'API key source',
514
+ dataKey: 'apiKeySource',
515
+ defaultValue: 'configured',
516
+ options: [
517
+ { value: 'configured', label: 'Automatic' },
518
+ { value: 'classifier-settings', label: 'Classifier settings' },
519
+ { value: 'input', label: 'Input port' },
520
+ ],
521
+ helperMessage: getApiKeySourceHelperMessage,
522
+ },
523
+ {
524
+ type: 'custom',
525
+ label: 'Configured API key names',
526
+ customEditorId: 'ClassifierCredentialNames',
527
+ hideIf: (data) => data.apiKeySource === 'input' || data.apiKeySource === 'classifier-settings',
528
+ },
529
+ ],
530
+ };
347
531
  }
348
532
  function getProviderForDisplay(id) {
349
533
  try {
@@ -363,8 +547,15 @@ export function getClassifierEvaluateBodySections(data) {
363
547
  {
364
548
  id: 'configuration',
365
549
  fields: [
366
- { label: 'Provider', value: provider.label },
367
- { label: 'Model', value: data.useModelInput ? 'input' : getStaticModel(data.model, provider.defaultModel) },
550
+ ...(data.configurationMode === 'profile'
551
+ ? [{ label: 'Configuration', value: 'From profile' }]
552
+ : [
553
+ { label: 'Provider', value: provider.label },
554
+ {
555
+ label: 'Model',
556
+ value: data.useModelInput ? 'input' : getStaticModel(data.model, provider.defaultModel),
557
+ },
558
+ ]),
368
559
  ],
369
560
  },
370
561
  ];
@@ -373,7 +564,7 @@ export function getClassifierEvaluateBodySections(data) {
373
564
  id: 'error-behavior',
374
565
  fields: [
375
566
  ...(data.errorOnNon200 !== false ? [{ label: 'Throw on non-2XX', value: 'Enabled' }] : []),
376
- ...(data.catchRequestFailed ? [{ label: 'Catch all failures', value: 'Enabled' }] : []),
567
+ ...(data.catchRequestFailed ? [{ label: 'Catch all exceptions', value: 'Enabled' }] : []),
377
568
  ...(data.retryOnNon200
378
569
  ? [
379
570
  { label: 'Retry on non-200', value: 'Enabled' },
@@ -397,7 +588,7 @@ function getApiKeySourceHelperMessage(data) {
397
588
  return 'Uses the API Key input port instead of a configured provider key.';
398
589
  const provider = getProviderForDisplay(data.provider);
399
590
  if (data.apiKeySource === 'classifier-settings')
400
- return `Uses only Settings > Classifier > ${provider.label} API Key on the executor. A missing key fails without fallback.`;
591
+ return `Uses only Settings > Classifier > ${provider.label} API Key on the executor. Does not fall back to named or environment credentials.`;
401
592
  return 'Automatic checks the named programmatic setting, then the named environment variable, then the saved Classifier key (default names only). OpenAI also accepts its legacy general key; Jev accepts its legacy plugin key last. Resolution happens on the executor, not in this editor.';
402
593
  }
403
594
  function flattenQuestions(value, target, check, seen = new Set(), depth = 0, work = { values: 0 }) {
@@ -0,0 +1,133 @@
1
+ import { nanoid } from 'nanoid/non-secure';
2
+ import { NodeImpl } from '../NodeImpl.js';
3
+ import { nodeDefinition } from '../NodeDefinition.js';
4
+ import { resolveClassifierProfile, DEFAULT_CLASSIFIER_PROFILE_RESPONSE_TIMEOUT_MS, DEFAULT_CLASSIFIER_PROFILE_FAILURE_THRESHOLD, DEFAULT_CLASSIFIER_PROFILE_FAILURE_WINDOW_MS, DEFAULT_CLASSIFIER_PROFILE_OPEN_DURATION_MS, } from '../classifier/profile.js';
5
+ import { getClassifierModelEditor, getClassifierEvaluateBodySections } from './ClassifierEvaluateNode.js';
6
+ import { formatNodeBodyMarkdownField } from '../nodeBodyMarkdown.js';
7
+ import { profileSuspensionHints } from '../profileSuspensionHints.js';
8
+ export class ClassifierProfileNodeImpl extends NodeImpl {
9
+ static create() {
10
+ return {
11
+ type: 'classifierProfile',
12
+ title: 'Classifier Profile',
13
+ id: nanoid(),
14
+ visualData: { x: 0, y: 0, width: 260 },
15
+ data: { provider: 'jev', responseTimeoutMs: DEFAULT_CLASSIFIER_PROFILE_RESPONSE_TIMEOUT_MS },
16
+ };
17
+ }
18
+ getInputDefinitions() {
19
+ return [
20
+ ...(this.data.useModelInput
21
+ ? [{ id: 'model', title: 'Model', dataType: 'string', required: true }]
22
+ : []),
23
+ ...(this.data.apiKeySource === 'input'
24
+ ? [{ id: 'apiKey', title: 'API Key', dataType: 'string', required: false }]
25
+ : []),
26
+ ];
27
+ }
28
+ getOutputDefinitions() {
29
+ return [
30
+ {
31
+ id: 'profile',
32
+ title: 'Profile',
33
+ dataType: 'classifier-config',
34
+ description: 'Sensitive resolved classifier configuration. Combine profiles with Array for ordered fallback.',
35
+ },
36
+ ];
37
+ }
38
+ getEditors() {
39
+ return [
40
+ getClassifierModelEditor(this.data),
41
+ {
42
+ type: 'group',
43
+ label: 'Classifier profile suspension',
44
+ editors: [
45
+ {
46
+ type: 'info',
47
+ label: "It's a hosted runtime capability",
48
+ helperMessage: profileSuspensionHints.host,
49
+ },
50
+ {
51
+ type: 'toggle',
52
+ label: 'Enable automatic suspension',
53
+ dataKey: 'enableCircuitBreaker',
54
+ helperMessage: profileSuspensionHints.enable,
55
+ },
56
+ {
57
+ type: 'number',
58
+ label: 'Response timeout, seconds',
59
+ dataKey: 'responseTimeoutMs',
60
+ defaultValue: DEFAULT_CLASSIFIER_PROFILE_RESPONSE_TIMEOUT_MS,
61
+ storageMultiplier: 1_000,
62
+ min: 1,
63
+ max: 600_000,
64
+ step: 1,
65
+ helperMessage: 'Batch time limit, including retries and retry waits. Minimum 0.001 s.',
66
+ hideIf: (data) => data.enableCircuitBreaker !== true,
67
+ },
68
+ {
69
+ type: 'number',
70
+ label: 'Failures before suspension',
71
+ dataKey: 'circuitBreakerFailureThreshold',
72
+ defaultValue: DEFAULT_CLASSIFIER_PROFILE_FAILURE_THRESHOLD,
73
+ min: 1,
74
+ max: 1000,
75
+ step: 1,
76
+ helperMessage: profileSuspensionHints.threshold,
77
+ hideIf: (data) => data.enableCircuitBreaker !== true,
78
+ },
79
+ {
80
+ type: 'number',
81
+ label: 'Failure window, seconds',
82
+ dataKey: 'circuitBreakerFailureWindowMs',
83
+ defaultValue: DEFAULT_CLASSIFIER_PROFILE_FAILURE_WINDOW_MS,
84
+ storageMultiplier: 1_000,
85
+ min: 1_000,
86
+ max: 86_400_000,
87
+ step: 1_000,
88
+ helperMessage: profileSuspensionHints.window,
89
+ hideIf: (data) => data.enableCircuitBreaker !== true,
90
+ },
91
+ {
92
+ type: 'number',
93
+ label: 'Suspension duration, seconds',
94
+ dataKey: 'circuitBreakerOpenDurationMs',
95
+ defaultValue: DEFAULT_CLASSIFIER_PROFILE_OPEN_DURATION_MS,
96
+ storageMultiplier: 1_000,
97
+ min: 1_000,
98
+ max: 86_400_000,
99
+ step: 1_000,
100
+ helperMessage: profileSuspensionHints.duration,
101
+ hideIf: (data) => data.enableCircuitBreaker !== true,
102
+ },
103
+ ],
104
+ },
105
+ ];
106
+ }
107
+ getBody() {
108
+ return {
109
+ type: 'markdown',
110
+ text: getClassifierEvaluateBodySections(this.data)
111
+ .filter((section) => section.id === 'configuration')
112
+ .flatMap((section) => section.fields)
113
+ .map((field) => formatNodeBodyMarkdownField(field.label, field.value))
114
+ .join('') +
115
+ formatNodeBodyMarkdownField('Automatic suspension', this.data.enableCircuitBreaker ? 'Enabled' : 'Disabled'),
116
+ };
117
+ }
118
+ static getUIData() {
119
+ return {
120
+ contextMenuTitle: 'Classifier Profile',
121
+ infoBoxTitle: 'Classifier Profile',
122
+ infoBoxBody: 'Reusable classifier provider/model/credential configuration. Combine profiles with Array for ordered fallback.',
123
+ group: ['Classifier'],
124
+ };
125
+ }
126
+ async process(inputs, context) {
127
+ context.signal.throwIfAborted();
128
+ return {
129
+ ['profile']: { type: 'classifier-config', value: resolveClassifierProfile(this.data, inputs, context) },
130
+ };
131
+ }
132
+ }
133
+ export const classifierProfileNode = nodeDefinition(ClassifierProfileNodeImpl, 'Classifier Profile');
@@ -160,7 +160,7 @@ export class DelegateFunctionCallNodeImpl extends NodeImpl {
160
160
  return buildDelegatedToolCallOutputs(delegatedRecords);
161
161
  }
162
162
  const result = await delegateToolCall(functionCallInput, context, this.data);
163
- return buildDelegatedToolCallOutputs([result.record], undefined, result.cost);
163
+ return buildDelegatedToolCallOutputs([result.record], undefined, result.cost, result.costBreakdown);
164
164
  }
165
165
  }
166
166
  function getDelegatedToolCallRecords(input) {