@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
@@ -2,16 +2,14 @@ import { createAnthropic } from '@ai-sdk/anthropic';
2
2
  import { createGoogleGenerativeAI } from '@ai-sdk/google';
3
3
  import { createOpenAI } from '@ai-sdk/openai';
4
4
  import { createOpenAICompatible } from '@ai-sdk/openai-compatible';
5
+ import { createOpenRouter } from '@openrouter/ai-sdk-provider';
6
+ import { withOpenRouterResponseValidation } from './openRouterModel.js';
5
7
  import { cleanHeaders } from '../../utils/inputs.js';
6
8
  import { getCustomProviderApiContract } from './customProviderApi.js';
7
9
  import { getChatV2ModelRegistry } from './modelRegistry.js';
10
+ import { chatV2ProviderDescriptors, chatV2ProviderOptions, isChatV2Provider } from './chatV2ProviderRegistry.js';
8
11
  export { customProviderApiOptions, getCustomProviderApiContract, parseCustomProviderApi, } from './customProviderApi.js';
9
- export const chatV2ProviderOptions = [
10
- { value: 'openai', label: 'OpenAI' },
11
- { value: 'anthropic', label: 'Anthropic' },
12
- { value: 'google', label: 'Google' },
13
- { value: 'custom', label: 'Custom provider' },
14
- ];
12
+ export { chatV2ProviderOptions };
15
13
  export const openAIReasoningEffortOptions = [
16
14
  { value: '', label: 'Default' },
17
15
  { value: 'none', label: 'None' },
@@ -55,6 +53,9 @@ export function getChatV2ProviderLabel(provider) {
55
53
  return chatV2ProviderOptions.find((option) => option.value === provider)?.label ?? provider;
56
54
  }
57
55
  export function getChatV2ModelOptions(provider) {
56
+ const catalog = chatV2ProviderDescriptors[provider].catalog;
57
+ if (catalog !== 'registry')
58
+ return catalog.map((option) => ({ ...option }));
58
59
  const registry = getChatV2ModelRegistry()[provider];
59
60
  return Object.entries(registry)
60
61
  .map(([value, model]) => ({
@@ -64,27 +65,12 @@ export function getChatV2ModelOptions(provider) {
64
65
  .sort((a, b) => a.label.localeCompare(b.label));
65
66
  }
66
67
  export function getDefaultChatV2Model(provider) {
67
- switch (provider) {
68
- case 'openai':
69
- return 'gpt-5';
70
- case 'anthropic':
71
- return 'claude-sonnet-4-20250514';
72
- case 'google':
73
- return 'gemini-2.5-flash';
74
- case 'custom':
75
- return 'model-id';
76
- }
68
+ return chatV2ProviderDescriptors[provider].defaultModel;
77
69
  }
78
70
  export function parseChatV2Provider(value) {
79
- switch (value) {
80
- case 'openai':
81
- case 'anthropic':
82
- case 'google':
83
- case 'custom':
84
- return value;
85
- default:
86
- throw new Error(`Unsupported LLM Chat provider: ${value}`);
87
- }
71
+ if (isChatV2Provider(value))
72
+ return value;
73
+ throw new Error(`Unsupported LLM Chat provider: ${value}`);
88
74
  }
89
75
  export function normalizeOpenAICompatibleEndpoint(endpoint) {
90
76
  let url;
@@ -267,6 +253,11 @@ export async function resolveChatV2ProviderConfig(provider, _modelId, context, o
267
253
  ...options.headers,
268
254
  });
269
255
  switch (provider) {
256
+ case 'openrouter':
257
+ return {
258
+ baseURL: 'https://openrouter.ai/api/v1',
259
+ headers: Object.keys(headers).length > 0 ? headers : undefined,
260
+ };
270
261
  case 'openai':
271
262
  return {
272
263
  baseURL: undefined,
@@ -297,6 +288,20 @@ export async function resolveChatV2ProviderConfig(provider, _modelId, context, o
297
288
  }
298
289
  export function createChatV2Model(provider, modelId, context, options = {}) {
299
290
  switch (provider) {
291
+ case 'openrouter': {
292
+ const providerInstance = createOpenRouter({
293
+ // Never fall back to the OpenAI/Custom key or an SDK ambient secret.
294
+ apiKey: options.apiKey ?? context.settings.openRouterApiKey ?? '',
295
+ baseURL: 'https://openrouter.ai/api/v1',
296
+ headers: options.headers,
297
+ fetch: maybeCreateProviderProcessingFetch(options),
298
+ });
299
+ return withOpenRouterResponseValidation(providerInstance.chat(modelId, {
300
+ usage: { include: true },
301
+ // Unsupported configured parameters must fail, not be ignored upstream.
302
+ provider: { require_parameters: true },
303
+ }));
304
+ }
300
305
  case 'openai': {
301
306
  const providerInstance = createOpenAI({
302
307
  apiKey: options.apiKey || context.settings.openAiApiKey || context.settings.openAiKey || undefined,
@@ -1,5 +1,7 @@
1
1
  import { coerceTypeOptional } from '../../utils/coerceType.js';
2
2
  import { classifierDataProperty, classifierInputDataValue } from './json.js';
3
+ export class ClassifierCredentialMissingError extends Error {
4
+ }
3
5
  export const JEV_DEFAULT_CREDENTIAL_NAMES = {
4
6
  programmaticName: 'typesafeApiKey',
5
7
  environmentVariableName: 'TYPESAFE_API_KEY',
@@ -12,6 +14,14 @@ export const OPENAI_DEFAULT_CREDENTIAL_NAMES = {
12
14
  programmaticName: 'openAiApiKey',
13
15
  environmentVariableName: 'OPENAI_API_KEY',
14
16
  };
17
+ export const OPENROUTER_DEFAULT_CREDENTIAL_NAMES = {
18
+ programmaticName: 'openRouterApiKey',
19
+ environmentVariableName: 'OPENROUTER_API_KEY',
20
+ };
21
+ export const PERPLEXITY_DEFAULT_CREDENTIAL_NAMES = {
22
+ programmaticName: 'perplexityApiKey',
23
+ environmentVariableName: 'PERPLEXITY_API_KEY',
24
+ };
15
25
  const programmaticNamePattern = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
16
26
  const environmentVariableNamePattern = /^[A-Za-z_][A-Za-z0-9_]*$/;
17
27
  export function isValidClassifierProgrammaticCredentialName(name) {
@@ -60,13 +70,13 @@ export function resolveClassifierApiKey({ apiKeyNames, apiKeySource, context, de
60
70
  : undefined;
61
71
  const saved = getNonEmptyString(read(read(read(context.settings, 'classifierProviders'), providerId), 'apiKey'));
62
72
  if (!saved)
63
- throw new Error(`Classifier settings API key for ${providerId} is not set. No automatic fallback is used.`);
73
+ throw new ClassifierCredentialMissingError(`Classifier settings API key for ${providerId} is not set. No automatic fallback is used.`);
64
74
  return saved;
65
75
  }
66
76
  if (apiKeySource === 'input') {
67
77
  const value = coerceTypeOptional(classifierInputDataValue(inputs, 'apiKey'), 'string')?.trim();
68
78
  if (!value)
69
- throw new Error('API Key input is required when API key source is Input port.');
79
+ throw new ClassifierCredentialMissingError('API Key input is required when API key source is Input port.');
70
80
  return value;
71
81
  }
72
82
  if (apiKeySource !== undefined && apiKeySource !== 'configured')
@@ -86,7 +96,7 @@ export function resolveClassifierApiKey({ apiKeyNames, apiKeySource, context, de
86
96
  return legacyValue;
87
97
  }
88
98
  }
89
- throw new Error(`${providerId === 'jev' ? 'Jev' : 'Classifier'} API key is not set. Pass ${names.programmaticName}, configure ${names.environmentVariableName}, or set the configured key in Settings > Classifier.`);
99
+ throw new ClassifierCredentialMissingError(`${providerId === 'jev' ? 'Jev' : 'Classifier'} API key is not set. Pass ${names.programmaticName}, configure ${names.environmentVariableName}, or set the configured key in Settings > Classifier.`);
90
100
  }
91
101
  function resolveNamedClassifierApiKey(context, names, useLegacyOpenAIKey = false) {
92
102
  const programmaticValue = getNonEmptyString(context.settings?.[names.programmaticName]);
@@ -10,6 +10,9 @@ export const CLASSIFIER_LIMITS = {
10
10
  };
11
11
  export class ClassifierResourceLimitError extends Error {
12
12
  }
13
+ /** Receipt failed before JSON decoding/validation, rather than malformed evidence. */
14
+ export class ClassifierResponseReadError extends Error {
15
+ }
13
16
  const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
14
17
  const byteBuffer = Object.getOwnPropertyDescriptor(typedArrayPrototype, 'buffer').get;
15
18
  const byteOffset = Object.getOwnPropertyDescriptor(typedArrayPrototype, 'byteOffset').get;
@@ -219,7 +222,7 @@ export function checkClassifierJsonWork(text, check, label = 'response') {
219
222
  }
220
223
  }
221
224
  /** Consume decoded response bytes incrementally; Content-Length is not trusted. */
222
- export async function readClassifierResponse(response, signal, check = () => signal.throwIfAborted()) {
225
+ export async function readClassifierResponse(response, signal, check = () => signal.throwIfAborted(), onBody) {
223
226
  const length = response.headers.get('content-length');
224
227
  if (length && Number(length) > CLASSIFIER_LIMITS.responseBytes)
225
228
  throw new ClassifierResourceLimitError('Classifier response exceeds the 8 MiB response limit.');
@@ -237,7 +240,9 @@ export async function readClassifierResponse(response, signal, check = () => sig
237
240
  try {
238
241
  for (;;) {
239
242
  check();
240
- const { done, value } = await reader.read();
243
+ const { done, value } = await reader.read().catch((cause) => {
244
+ throw new ClassifierResponseReadError('Classifier response body could not be read.', { cause });
245
+ });
241
246
  check();
242
247
  if (done)
243
248
  break;
@@ -255,8 +260,33 @@ export async function readClassifierResponse(response, signal, check = () => sig
255
260
  check();
256
261
  const json = text.join('');
257
262
  checkClassifierJsonWork(json, check);
258
- const body = JSON.parse(json);
263
+ let body;
264
+ try {
265
+ body = JSON.parse(json);
266
+ }
267
+ catch (error) {
268
+ check();
269
+ try {
270
+ onBody?.(json);
271
+ }
272
+ catch {
273
+ /* Observation only. */
274
+ }
275
+ check();
276
+ throw error;
277
+ }
259
278
  assertClassifierResourceLimits(body, check, CLASSIFIER_LIMITS.responseBytes);
279
+ check();
280
+ try {
281
+ // Diagnostics must not modify the private response before validation or pricing.
282
+ // Only opt-in observers allocate a detached copy of this bounded, plain JSON.
283
+ if (onBody)
284
+ onBody(structuredClone(body));
285
+ }
286
+ catch {
287
+ /* Observation only. */
288
+ }
289
+ check();
260
290
  return body;
261
291
  }
262
292
  catch (error) {
@@ -0,0 +1,63 @@
1
+ import { systemOneState } from './state.js';
2
+ import { inspectClassifierImage } from './images.js';
3
+ export const PERPLEXITY_DECISION_MODELS = ['pplx-decider-v1.1-27b', 'pplx-decider-v1-27b'];
4
+ /** Native inline image parts; a top-level images field is not accepted. */
5
+ export function perplexityDecisionState(state) {
6
+ if (state.kind === 'json')
7
+ return state.value;
8
+ if (!state.images.length)
9
+ return systemOneState({ state: '', stateMessages: state.messages }).state;
10
+ const parts = [];
11
+ for (const [messageIndex, message] of state.messages.entries()) {
12
+ if (messageIndex)
13
+ parts.push('\n\n');
14
+ for (const [partIndex, part] of message.parts.entries()) {
15
+ if (partIndex)
16
+ parts.push('\n');
17
+ parts.push(part.type === 'text' ? part.text : { type: 'image_url', image_url: { url: part.dataUrl } });
18
+ }
19
+ }
20
+ return parts;
21
+ }
22
+ /** Provider capability limits, not shared input errors or provider outages. */
23
+ export function assertPerplexityDecisionLimits({ model, state, questions }, check) {
24
+ if (questions.length > 128)
25
+ throw new Error('Perplexity Decisions supports at most 128 questions per request.');
26
+ for (const question of questions) {
27
+ check();
28
+ if (question.type === 'score' && question.criteria.includes(null))
29
+ throw new Error('Perplexity Decisions Score levels cannot be null.');
30
+ }
31
+ const inspect = ({ width, height, mediaType }) => {
32
+ check();
33
+ if (!PERPLEXITY_DECISION_MODELS.includes(model))
34
+ throw new Error('Image support is not known for this Perplexity Decisions model.');
35
+ if (!['image/png', 'image/jpeg', 'image/webp'].includes(mediaType))
36
+ throw new Error('Perplexity Decisions accepts PNG, JPEG and WebP images, not GIF.');
37
+ // Round up conservatively: oversized images can hang until a provider 504.
38
+ if (Math.ceil(width / 32) * Math.ceil(height / 32) > 2048)
39
+ throw new Error('Perplexity Decisions images must contain at most 2,048 tiles of 32 by 32 pixels each. Resize upstream.');
40
+ };
41
+ if (state.kind === 'messages') {
42
+ for (const image of state.images)
43
+ inspect(image);
44
+ return;
45
+ }
46
+ // The native API also interprets top-level image_url parts in JSON State.
47
+ // Validate that wire shape without traversing arbitrary nested evidence or
48
+ // letting raw parts bypass the ordinary image capability checks.
49
+ let imageCount = 0;
50
+ for (const part of Array.isArray(state.value) ? state.value : [state.value]) {
51
+ check();
52
+ if (!part || typeof part !== 'object' || Array.isArray(part))
53
+ continue;
54
+ const record = part;
55
+ if (record.type !== 'image_url')
56
+ continue;
57
+ if (++imageCount > 128)
58
+ throw new Error('State must contain at most 128 images.');
59
+ const image = record.image_url;
60
+ const url = image && typeof image === 'object' && !Array.isArray(image) ? image.url : undefined;
61
+ inspect(inspectClassifierImage(url, check));
62
+ }
63
+ }
@@ -0,0 +1,151 @@
1
+ import CryptoJS from 'crypto-js';
2
+ import stableStringify from 'safe-stable-stringify';
3
+ import { classifierInputDataValue, snapshotClassifierJson } from './json.js';
4
+ import { ClassifierValueBudget } from './limits.js';
5
+ import { getClassifierProvider } from './providers.js';
6
+ import { ClassifierCredentialMissingError, resolveClassifierApiKey, } from './credentials.js';
7
+ export const DEFAULT_CLASSIFIER_PROFILE_RESPONSE_TIMEOUT_MS = 500;
8
+ export const DEFAULT_CLASSIFIER_PROFILE_FAILURE_THRESHOLD = 3;
9
+ export const DEFAULT_CLASSIFIER_PROFILE_FAILURE_WINDOW_MS = 300_000;
10
+ export const DEFAULT_CLASSIFIER_PROFILE_OPEN_DURATION_MS = 300_000;
11
+ export const classifierProfileInputIds = ['model', 'apiKey'];
12
+ export const classifierProfileDataKeys = [
13
+ 'provider',
14
+ 'model',
15
+ 'useModelInput',
16
+ 'apiKeySource',
17
+ 'apiKeyNamesByProvider',
18
+ 'apiKeyNames',
19
+ 'responseTimeoutMs',
20
+ 'enableCircuitBreaker',
21
+ 'circuitBreakerFailureThreshold',
22
+ 'circuitBreakerFailureWindowMs',
23
+ 'circuitBreakerOpenDurationMs',
24
+ ];
25
+ export function pickClassifierProfileData(data) {
26
+ return Object.fromEntries(classifierProfileDataKeys.filter((key) => data[key] !== undefined).map((key) => [key, data[key]]));
27
+ }
28
+ function positive(value, fallback, label, maximum = 600_000) {
29
+ const result = value ?? fallback;
30
+ if (!Number.isSafeInteger(result) || result < 1 || result > maximum)
31
+ throw new Error(`Classifier Profile ${label} must be an integer between 1 and ${maximum}.`);
32
+ return result;
33
+ }
34
+ export function classifierProfileResponseTimeout(configuration) {
35
+ return positive(configuration.responseTimeoutMs, DEFAULT_CLASSIFIER_PROFILE_RESPONSE_TIMEOUT_MS, 'response timeout');
36
+ }
37
+ export function classifierProfileHealthPolicy(configuration) {
38
+ if (configuration.enableCircuitBreaker !== true)
39
+ return undefined;
40
+ return {
41
+ failureThreshold: positive(configuration.circuitBreakerFailureThreshold, DEFAULT_CLASSIFIER_PROFILE_FAILURE_THRESHOLD, 'failure threshold', 1000),
42
+ failureWindowMs: positive(configuration.circuitBreakerFailureWindowMs, DEFAULT_CLASSIFIER_PROFILE_FAILURE_WINDOW_MS, 'failure window', 86_400_000),
43
+ openDurationMs: positive(configuration.circuitBreakerOpenDurationMs, DEFAULT_CLASSIFIER_PROFILE_OPEN_DURATION_MS, 'suspension duration', 86_400_000),
44
+ halfOpenLeaseMs: classifierProfileResponseTimeout(configuration) + 5000,
45
+ };
46
+ }
47
+ export function normalizeClassifierProfileValue(value) {
48
+ return normalizeDetachedProfile(snapshotClassifierJson(value, 'Classifier Profile', new ClassifierValueBudget(), true));
49
+ }
50
+ function normalizeDetachedProfile(value) {
51
+ const profile = value;
52
+ if (!profile ||
53
+ profile.version !== 1 ||
54
+ !profile.configuration ||
55
+ typeof profile.configuration !== 'object' ||
56
+ Array.isArray(profile.configuration) ||
57
+ !profile.credential ||
58
+ typeof profile.credential !== 'object' ||
59
+ Array.isArray(profile.credential))
60
+ throw new Error('Classifier Profiles input requires a version 1 Classifier Profile.');
61
+ const { configuration, credential } = profile;
62
+ if (typeof configuration.provider !== 'string' ||
63
+ typeof configuration.model !== 'string' ||
64
+ !configuration.model.trim())
65
+ throw new Error('Classifier Profile requires a provider and a nonblank model.');
66
+ getClassifierProvider(configuration.provider);
67
+ if (credential.value !== undefined && (typeof credential.value !== 'string' || /[\r\n]/.test(credential.value)))
68
+ throw new Error('Classifier Profile credential must be a string without line breaks.');
69
+ if (profile.profileName !== undefined && typeof profile.profileName !== 'string')
70
+ throw new Error('Invalid Classifier Profile name.');
71
+ if (profile.sourceNodeId !== undefined && (typeof profile.sourceNodeId !== 'string' || !profile.sourceNodeId.trim()))
72
+ throw new Error('Invalid Classifier Profile source node.');
73
+ if (configuration.enableCircuitBreaker !== undefined && typeof configuration.enableCircuitBreaker !== 'boolean')
74
+ throw new Error('Classifier Profile automatic suspension must be a boolean.');
75
+ if (configuration.apiKeySource !== undefined &&
76
+ !['configured', 'classifier-settings', 'input'].includes(configuration.apiKeySource))
77
+ throw new Error('Unknown classifier API key source.');
78
+ classifierProfileResponseTimeout(configuration);
79
+ classifierProfileHealthPolicy(configuration);
80
+ return {
81
+ version: 1,
82
+ sourceNodeId: profile.sourceNodeId,
83
+ profileName: profile.profileName?.trim() || undefined,
84
+ credential: credential.value === undefined ? {} : { value: credential.value.trim() },
85
+ configuration: {
86
+ ...pickClassifierProfileData(configuration),
87
+ provider: configuration.provider,
88
+ model: configuration.model.trim(),
89
+ useModelInput: false,
90
+ },
91
+ };
92
+ }
93
+ export function normalizeClassifierProfiles(value, check) {
94
+ if (Array.isArray(value) && (value.length === 0 || value.length > 128))
95
+ throw new Error('Classifier Profiles requires between 1 and 128 profiles.');
96
+ // One deadline-aware traversal bounds, validates and detaches the whole
97
+ // chain. Do not rescan each candidate with a fresh resource budget.
98
+ const detached = snapshotClassifierJson(value, 'Classifier Profiles', new ClassifierValueBudget(check), true);
99
+ return (Array.isArray(detached) ? detached : [detached]).map(normalizeDetachedProfile);
100
+ }
101
+ export function resolveClassifierProfile(data, inputs, context) {
102
+ const provider = getClassifierProvider(data.provider);
103
+ const model = data.useModelInput
104
+ ? classifierInputDataValue(inputs, 'model')?.value
105
+ : data.model?.trim() || provider.defaultModel;
106
+ if (typeof model !== 'string' || !model.trim())
107
+ throw new Error('Classifier Profile model is required.');
108
+ let value;
109
+ // Missing credentials are a candidate failure, not an upstream graph failure.
110
+ // Invalid credential-name configuration still fails while authoring the profile.
111
+ try {
112
+ value = resolveClassifierApiKey({
113
+ apiKeyNames: data.apiKeyNamesByProvider?.[provider.id] ?? data.apiKeyNames,
114
+ apiKeySource: data.apiKeySource,
115
+ context,
116
+ defaults: provider.credentialNames,
117
+ inputs,
118
+ providerId: provider.id,
119
+ });
120
+ }
121
+ catch (error) {
122
+ if (!(error instanceof ClassifierCredentialMissingError))
123
+ throw error;
124
+ }
125
+ return normalizeClassifierProfileValue({
126
+ version: 1,
127
+ configuration: { ...pickClassifierProfileData(data), provider: provider.id, model, useModelInput: false },
128
+ credential: value === undefined ? {} : { value },
129
+ profileName: context.node.title,
130
+ sourceNodeId: context.node.id,
131
+ });
132
+ }
133
+ export function classifierProfileHealthIdentity(profile, projectId, fallbackNodeId) {
134
+ const hash = (value) => `sha256:${CryptoJS.SHA256(stableStringify(value) ?? '').toString(CryptoJS.enc.Hex)}`;
135
+ const configurationFingerprint = hash({
136
+ provider: profile.configuration.provider,
137
+ model: profile.configuration.model,
138
+ credential: profile.credential,
139
+ });
140
+ const profileNodeId = profile.sourceNodeId ?? fallbackNodeId;
141
+ return {
142
+ key: `classifier-profile:${hash({ projectId, profileNodeId, configurationFingerprint })}`,
143
+ family: 'classifier',
144
+ projectId,
145
+ profileNodeId,
146
+ profileName: profile.profileName,
147
+ provider: profile.configuration.provider,
148
+ model: profile.configuration.model,
149
+ configurationFingerprint,
150
+ };
151
+ }