@valerypopoff/rivet2-core 2.17.0 → 2.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/dist/cjs/bundle.cjs +3093 -1440
  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 +2 -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 +621 -942
  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 +23 -10
  21. package/dist/esm/model/ProjectBundleRuntime.js +54 -0
  22. package/dist/esm/model/SchedulerBoundaryPlanner.js +233 -0
  23. package/dist/esm/model/SubprocessorBridge.js +125 -87
  24. package/dist/esm/model/ToolCallContinuationCoordinator.js +1 -1
  25. package/dist/esm/model/chat-v2/aiSdkBridge.js +15 -12
  26. package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -4
  27. package/dist/esm/model/chat-v2/chatV2CredentialNames.js +5 -1
  28. package/dist/esm/model/chat-v2/chatV2Outputs.js +2 -2
  29. package/dist/esm/model/chat-v2/chatV2Pipeline.js +11 -1
  30. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +3 -2
  31. package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +46 -6
  32. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +7 -0
  33. package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +10 -0
  34. package/dist/esm/model/chat-v2/llmChatV2Body.js +2 -2
  35. package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +5 -2
  36. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +1 -0
  37. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +18 -8
  38. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +10 -2
  39. package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +17 -0
  40. package/dist/esm/model/chat-v2/llmModelCandidate.js +2 -1
  41. package/dist/esm/model/chat-v2/llmProfile.js +2 -1
  42. package/dist/esm/model/chat-v2/llmProfileBody.js +9 -0
  43. package/dist/esm/model/chat-v2/llmProfileFallback.js +7 -4
  44. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +1 -0
  45. package/dist/esm/model/chat-v2/llmProfileHealthStore.js +16 -3
  46. package/dist/esm/model/chat-v2/messageConverter.js +18 -16
  47. package/dist/esm/model/chat-v2/modelRegistry.js +14 -4
  48. package/dist/esm/model/chat-v2/openRouterModel.js +73 -0
  49. package/dist/esm/model/chat-v2/parallelToolCalls.js +2 -0
  50. package/dist/esm/model/chat-v2/providerOptions.js +30 -25
  51. package/dist/esm/model/classifier/credentials.js +13 -3
  52. package/dist/esm/model/classifier/limits.js +33 -3
  53. package/dist/esm/model/classifier/perplexity.js +63 -0
  54. package/dist/esm/model/classifier/profile.js +151 -0
  55. package/dist/esm/model/classifier/profileExecution.js +294 -0
  56. package/dist/esm/model/classifier/providers.js +217 -30
  57. package/dist/esm/model/classifier/state.js +4 -1
  58. package/dist/esm/model/classifier/types.js +11 -1
  59. package/dist/esm/model/nodeRunFailure.js +8 -1
  60. package/dist/esm/model/nodes/CallGraphNode.js +6 -0
  61. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +250 -59
  62. package/dist/esm/model/nodes/ClassifierProfileNode.js +133 -0
  63. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +1 -1
  64. package/dist/esm/model/nodes/LLMChatV2Node.js +2 -1
  65. package/dist/esm/model/nodes/SubGraphNode.js +3 -0
  66. package/dist/esm/model/nodes/toolCallDelegation.js +5 -1
  67. package/dist/esm/model/profileSuspensionHints.js +8 -0
  68. package/dist/esm/serialization.js +2 -0
  69. package/dist/esm/utils/coerceType.js +11 -1
  70. package/dist/esm/webAppRuntime.js +1 -0
  71. package/dist/types/exports.d.ts +2 -0
  72. package/dist/types/model/AgentResponseTrace.d.ts +15 -4
  73. package/dist/types/model/AgentResponseTracePresentation.d.ts +15 -0
  74. package/dist/types/model/DataValue.d.ts +12 -8
  75. package/dist/types/model/ExecutorProtocol.d.ts +7 -0
  76. package/dist/types/model/GraphBoundaryEffects.d.ts +10 -1
  77. package/dist/types/model/GraphExecutionState.d.ts +68 -0
  78. package/dist/types/model/GraphProcessor.d.ts +1 -0
  79. package/dist/types/model/GraphSchedulerBoundaryState.d.ts +96 -0
  80. package/dist/types/model/Nodes.d.ts +7 -4
  81. package/dist/types/model/ProcessContext.d.ts +12 -3
  82. package/dist/types/model/ProjectBundle.d.ts +9 -4
  83. package/dist/types/model/ProjectBundleRuntime.d.ts +24 -0
  84. package/dist/types/model/RivetUIContext.d.ts +1 -1
  85. package/dist/types/model/SchedulerBoundaryPlanner.d.ts +42 -0
  86. package/dist/types/model/Settings.d.ts +1 -0
  87. package/dist/types/model/SubprocessorBridge.d.ts +2 -0
  88. package/dist/types/model/chat-v2/chatV2CredentialNames.d.ts +4 -0
  89. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +1 -1
  90. package/dist/types/model/chat-v2/chatV2ProviderRegistry.d.ts +79 -1
  91. package/dist/types/model/chat-v2/chatV2ProviderTypes.d.ts +1 -1
  92. package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +2 -0
  93. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +2 -1
  94. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +2 -0
  95. package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +2 -0
  96. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +51 -3
  97. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +9 -6
  98. package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +6 -2
  99. package/dist/types/model/chat-v2/modelRegistry.d.ts +5 -4
  100. package/dist/types/model/chat-v2/openRouterModel.d.ts +2 -0
  101. package/dist/types/model/chat-v2/providerOptions.d.ts +2 -13
  102. package/dist/types/model/classifier/credentials.d.ts +4 -0
  103. package/dist/types/model/classifier/limits.d.ts +4 -1
  104. package/dist/types/model/classifier/perplexity.d.ts +7 -0
  105. package/dist/types/model/classifier/profile.d.ts +46 -0
  106. package/dist/types/model/classifier/profileExecution.d.ts +32 -0
  107. package/dist/types/model/classifier/providers.d.ts +32 -1
  108. package/dist/types/model/classifier/types.d.ts +9 -0
  109. package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +14 -12
  110. package/dist/types/model/nodes/ClassifierProfileNode.d.ts +20 -0
  111. package/dist/types/model/nodes/toolCallDelegation.d.ts +3 -1
  112. package/dist/types/model/profileSuspensionHints.d.ts +8 -0
  113. package/dist/types/serialization.d.ts +2 -0
  114. package/dist/types/webAppRuntime.d.ts +1 -0
  115. package/package.json +7 -1
@@ -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,50 +98,20 @@ 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',
@@ -145,7 +132,14 @@ export class ClassifierEvaluateNodeImpl extends NodeImpl {
145
132
  type: 'toggle',
146
133
  label: 'Output 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: 'Output classifier attempts', dataKey: 'outputClassifierAttempts' },
138
+ {
139
+ type: 'toggle',
140
+ label: 'Output 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
  },
@@ -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
  ];
@@ -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) {
@@ -364,7 +364,7 @@ export class LLMChatV2NodeImpl extends NodeImpl {
364
364
  throw error;
365
365
  }
366
366
  context.signal.throwIfAborted();
367
- const { result, terminalSnapshot } = invocation;
367
+ const { result, terminalSnapshot, toolCost } = invocation;
368
368
  projectLLMInvocationResult({
369
369
  result,
370
370
  modelCalls: invocationJournal.modelCalls,
@@ -372,6 +372,7 @@ export class LLMChatV2NodeImpl extends NodeImpl {
372
372
  outputLLMAttempts: this.data.outputLLMAttempts,
373
373
  llmAttempts: invocationJournal.llmAttempts,
374
374
  profileSummary: runtime.getProfileSummary?.(),
375
+ toolCost,
375
376
  });
376
377
  result.commonOutputs = withRunSuccessOutputs(this.data, result.commonOutputs);
377
378
  // The final display page is taken after result projection, so it exactly
@@ -355,6 +355,9 @@ function buildOptimizedSubgraphOutputs(boundary, requestedOutputIds, graphOutput
355
355
  if (!boundary.outputs.some((output) => output.id === 'cost')) {
356
356
  outputs['cost'] = graphOutputs['cost'] ?? { type: 'number', value: 0 };
357
357
  }
358
+ if (!boundary.outputs.some((output) => output.id === 'costBreakdown') && graphOutputs['costBreakdown']) {
359
+ outputs['costBreakdown'] = graphOutputs['costBreakdown'];
360
+ }
358
361
  if (!boundary.outputs.some((output) => output.id === 'duration')) {
359
362
  outputs['duration'] = { type: 'number', value: duration };
360
363
  }
@@ -1,4 +1,5 @@
1
1
  import { omit } from 'lodash-es';
2
+ import { readGraphCostBreakdown } from '../GraphBoundaryEffects.js';
2
3
  import { coerceTypeOptional } from '../../utils/coerceType.js';
3
4
  import { getError } from '../../utils/errors.js';
4
5
  import { createDelegatedToolCallRecord, createToolResultMessage, normalizeToolCall, stringifyToolResult, } from '../chat-v2/toolCallCodec.js';
@@ -36,7 +37,7 @@ export function isDelegatedToolCallRecord(input) {
36
37
  typeof maybeMessage.name === 'string' &&
37
38
  (maybeMessage.toolName == null || typeof maybeMessage.toolName === 'string'));
38
39
  }
39
- export function buildDelegatedToolCallOutputs(records, preToolMessage, cost) {
40
+ export function buildDelegatedToolCallOutputs(records, preToolMessage, cost, costBreakdown) {
40
41
  const preToolMessageOutput = preToolMessage == null
41
42
  ? {
42
43
  type: 'control-flow-excluded',
@@ -107,6 +108,8 @@ export function buildDelegatedToolCallOutputs(records, preToolMessage, cost) {
107
108
  };
108
109
  if (cost != null) {
109
110
  outputs['cost'] = { type: 'number', value: cost };
111
+ if (costBreakdown)
112
+ outputs['costBreakdown'] = { type: 'object', value: { ...costBreakdown } };
110
113
  }
111
114
  return outputs;
112
115
  }
@@ -275,6 +278,7 @@ async function delegateResolvedToolCall(functionCall, context, config, trace) {
275
278
  message: createToolResultMessage(functionCall, outputString),
276
279
  record: createDelegatedToolCallRecord(functionCall, outputString, executionTimeMs),
277
280
  cost,
281
+ costBreakdown: readGraphCostBreakdown(outputs),
278
282
  };
279
283
  }
280
284
  function notifyToolCallFinished(context, event) {
@@ -0,0 +1,8 @@
1
+ /** Shared inspector wording for LLM and Classifier profile suspension. */
2
+ export const profileSuspensionHints = {
3
+ host: 'Requires Studio Server or a host with shared profile health. Not available in standalone Rivet.',
4
+ enable: 'Suspend this profile after provider failures or timeouts. After suspension, allow one recovery attempt.',
5
+ threshold: 'Failures or timeouts within the failure window needed to suspend this profile.',
6
+ window: 'Rolling period for counting failures and timeouts.',
7
+ duration: 'Time to suspend this profile before one recovery attempt.',
8
+ };
@@ -0,0 +1,2 @@
1
+ /** Lightweight entry point for file preparation without model/provider runtime initialization. */
2
+ export { deserializeProject, deserializeGraph, deserializeDatasets, serializeProject, serializeGraph, serializeDatasets, } from './utils/serialization/serialization.js';
@@ -6,7 +6,8 @@ function isValidatedObjectValueType(type) {
6
6
  return (type === 'knowledge-source' ||
7
7
  type === 'knowledge-document' ||
8
8
  type === 'knowledge-evidence' ||
9
- type === 'llm-config');
9
+ type === 'llm-config' ||
10
+ type === 'classifier-config');
10
11
  }
11
12
  function canAttemptGeneralCoercion(from, to) {
12
13
  return !isValidatedObjectValueType(from) || to === 'object' || to === 'string';
@@ -53,6 +54,8 @@ const scalarCoercionRules = {
53
54
  'knowledge-document': sameTypeOrObjectScalarRule('knowledge-document', (value) => coerceValidatedObjectValue(value, normalizeKnowledgeDocument)),
54
55
  'knowledge-evidence': sameTypeOrObjectScalarRule('knowledge-evidence', (value) => coerceValidatedObjectValue(value, normalizeKnowledgeEvidence)),
55
56
  'llm-config': sameTypeOrObjectScalarRule('llm-config', (value) => coerceValidatedObjectValue(value, normalizeLLMProfileValue)),
57
+ // Provider-specific validation belongs to Evaluate's bounded snapshot boundary.
58
+ 'classifier-config': sameTypeOrObjectScalarRule('classifier-config', (value) => value?.value != null && typeof value.value === 'object' && !Array.isArray(value.value) ? value.value : undefined),
56
59
  document: generalScalarRule('document'),
57
60
  };
58
61
  export function coerceTypeOptional(wrapped, type) {
@@ -60,6 +63,13 @@ export function coerceTypeOptional(wrapped, type) {
60
63
  return expectTypeOptional(wrapped, type);
61
64
  }
62
65
  const value = wrapped ? unwrapDataValue(wrapped) : undefined;
66
+ // These profiles share a versioned object envelope but configure different
67
+ // APIs. Do not reinterpret a typed chat profile as a classifier (or vice versa),
68
+ // including after unwrapping a deferred value. Object/any imports remain valid.
69
+ if ((type === 'classifier-config' && value?.type === 'llm-config') ||
70
+ (type === 'llm-config' && value?.type === 'classifier-config')) {
71
+ return undefined;
72
+ }
63
73
  // Coerce 'true' to [true] for example
64
74
  if (isArrayDataType(type) && !isArrayDataValue(value)) {
65
75
  const coerced = coerceTypeOptional(value, getScalarTypeOf(type));