@valerypopoff/rivet2-core 2.22.1 → 2.25.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 (80) hide show
  1. package/dist/cjs/bundle.cjs +1438 -824
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/interpolationRuntime.cjs +23 -0
  4. package/dist/cjs/interpolationRuntime.cjs.map +3 -3
  5. package/dist/cjs/serialization.cjs +1 -0
  6. package/dist/cjs/serialization.cjs.map +2 -2
  7. package/dist/cjs/webAppRuntime.cjs +4 -1
  8. package/dist/cjs/webAppRuntime.cjs.map +2 -2
  9. package/dist/esm/exports.js +3 -1
  10. package/dist/esm/index.js +3 -0
  11. package/dist/esm/integrations/CodeRunner.js +6 -3
  12. package/dist/esm/integrations/CodeRunnerNamespace.js +10 -0
  13. package/dist/esm/model/AgentResponseTracePresentation.js +5 -1
  14. package/dist/esm/model/ChildInvocationOwnership.js +51 -0
  15. package/dist/esm/model/DatasetOwnership.js +9 -0
  16. package/dist/esm/model/GraphExecutionState.js +3 -0
  17. package/dist/esm/model/GraphProcessor.js +94 -55
  18. package/dist/esm/model/NodeRegistration.js +2 -6
  19. package/dist/esm/model/RunCostLedger.js +58 -0
  20. package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -2
  21. package/dist/esm/model/chat-v2/chatV2Outputs.js +1 -1
  22. package/dist/esm/model/chat-v2/chatV2Pipeline.js +5 -0
  23. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +3 -0
  24. package/dist/esm/model/chat-v2/llmModelCandidate.js +3 -0
  25. package/dist/esm/model/chat-v2/llmProfile.js +2 -0
  26. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +1 -0
  27. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +2 -1
  28. package/dist/esm/model/chat-v2/modelRegistry.js +12 -3
  29. package/dist/esm/model/classifier/baseten.js +78 -0
  30. package/dist/esm/model/classifier/credentials.js +17 -9
  31. package/dist/esm/model/classifier/images.js +4 -4
  32. package/dist/esm/model/classifier/jev.js +45 -0
  33. package/dist/esm/model/classifier/json.js +1 -1
  34. package/dist/esm/model/classifier/limits.js +13 -13
  35. package/dist/esm/model/classifier/openai.js +20 -2
  36. package/dist/esm/model/classifier/preparation.js +5 -5
  37. package/dist/esm/model/classifier/profile.js +24 -15
  38. package/dist/esm/model/classifier/profileExecution.js +28 -24
  39. package/dist/esm/model/classifier/providers.js +194 -87
  40. package/dist/esm/model/classifier/questionHelpers.js +21 -2
  41. package/dist/esm/model/classifier/questions.js +37 -7
  42. package/dist/esm/model/classifier/response.js +8 -2
  43. package/dist/esm/model/classifier/state.js +2 -2
  44. package/dist/esm/model/classifier/subq.js +51 -0
  45. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +48 -66
  46. package/dist/esm/model/nodes/ClassifierProfileNode.js +11 -9
  47. package/dist/esm/model/nodes/ClassifierQuestionNode.js +53 -34
  48. package/dist/esm/model/tokenPricing.js +52 -0
  49. package/dist/esm/model/tokenPricingEditor.js +9 -0
  50. package/dist/types/exports.d.ts +3 -0
  51. package/dist/types/index.d.ts +1 -1
  52. package/dist/types/integrations/CodeRunner.d.ts +4 -1
  53. package/dist/types/integrations/CodeRunnerNamespace.d.ts +5 -0
  54. package/dist/types/model/AgentResponseTracePresentation.d.ts +2 -0
  55. package/dist/types/model/ChildInvocationOwnership.d.ts +36 -0
  56. package/dist/types/model/DatasetOwnership.d.ts +5 -0
  57. package/dist/types/model/GraphExecutionState.d.ts +2 -0
  58. package/dist/types/model/GraphProcessor.d.ts +3 -0
  59. package/dist/types/model/RunCostLedger.d.ts +19 -0
  60. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +1 -1
  61. package/dist/types/model/chat-v2/chatV2Types.d.ts +2 -0
  62. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +3 -1
  63. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +7 -5
  64. package/dist/types/model/chat-v2/modelRegistry.d.ts +7 -1
  65. package/dist/types/model/classifier/baseten.d.ts +8 -0
  66. package/dist/types/model/classifier/credentials.d.ts +2 -0
  67. package/dist/types/model/classifier/jev.d.ts +9 -0
  68. package/dist/types/model/classifier/profile.d.ts +3 -1
  69. package/dist/types/model/classifier/profileExecution.d.ts +2 -1
  70. package/dist/types/model/classifier/providers.d.ts +30 -6
  71. package/dist/types/model/classifier/questionHelpers.d.ts +3 -1
  72. package/dist/types/model/classifier/questions.d.ts +2 -1
  73. package/dist/types/model/classifier/state.d.ts +1 -0
  74. package/dist/types/model/classifier/subq.d.ts +8 -0
  75. package/dist/types/model/classifier/types.d.ts +9 -2
  76. package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +2 -4
  77. package/dist/types/model/nodes/ClassifierQuestionNode.d.ts +2 -2
  78. package/dist/types/model/tokenPricing.d.ts +18 -0
  79. package/dist/types/model/tokenPricingEditor.d.ts +4 -0
  80. package/package.json +2 -2
@@ -42,6 +42,8 @@ __export(src_exports, {
42
42
  AssembleMessageNodeImpl: () => AssembleMessageNodeImpl,
43
43
  AssemblePromptNodeImpl: () => AssemblePromptNodeImpl,
44
44
  AudioNodeImpl: () => AudioNodeImpl,
45
+ BASETEN_DECISIONS_ENDPOINT: () => BASETEN_DECISIONS_ENDPOINT,
46
+ BASETEN_DEFAULT_CREDENTIAL_NAMES: () => BASETEN_DEFAULT_CREDENTIAL_NAMES,
45
47
  BooleanNodeImpl: () => BooleanNodeImpl,
46
48
  BrowserNativeApi: () => BrowserNativeApi,
47
49
  BuildKnowledgeContextNodeImpl: () => BuildKnowledgeContextNodeImpl,
@@ -211,6 +213,8 @@ __export(src_exports, {
211
213
  RivetLLMProfileHealthPolicyError: () => RivetLLMProfileHealthPolicyError,
212
214
  RivetStoredValueController: () => RivetStoredValueController,
213
215
  STREAM_RESPONSE_HELPER_MESSAGE: () => STREAM_RESPONSE_HELPER_MESSAGE,
216
+ SUBQ_DECISIONS_ENDPOINT: () => SUBQ_DECISIONS_ENDPOINT,
217
+ SUBQ_DEFAULT_CREDENTIAL_NAMES: () => SUBQ_DEFAULT_CREDENTIAL_NAMES,
214
218
  SearchKnowledgeNodeImpl: () => SearchKnowledgeNodeImpl,
215
219
  SetGlobalNodeImpl: () => SetGlobalNodeImpl,
216
220
  SetStoredValueNodeImpl: () => SetStoredValueNodeImpl,
@@ -262,6 +266,7 @@ __export(src_exports, {
262
266
  autoevalsPlugin: () => autoevals_default,
263
267
  base64ToUint8Array: () => base64ToUint8Array,
264
268
  baseDirs: () => baseDirs,
269
+ basetenClassifierProvider: () => basetenClassifierProvider,
265
270
  booleanNode: () => booleanNode,
266
271
  buildAgentProfileAttemptInspectorRows: () => buildAgentProfileAttemptInspectorRows,
267
272
  buildAgentResponseTrace: () => buildAgentResponseTrace,
@@ -273,6 +278,7 @@ __export(src_exports, {
273
278
  calculateChatV2Cost: () => calculateChatV2Cost,
274
279
  calculateChatV2UsageCost: () => calculateChatV2UsageCost,
275
280
  calculateClassifierUsageCost: () => calculateClassifierUsageCost,
281
+ calculateTokenUsageCost: () => calculateTokenUsageCost,
276
282
  callGraphNode: () => callGraphNode,
277
283
  canBeCoerced: () => canBeCoerced,
278
284
  canBeCoercedAny: () => canBeCoercedAny,
@@ -423,6 +429,7 @@ __export(src_exports, {
423
429
  getChatV2ModelRegistry: () => getChatV2ModelRegistry,
424
430
  getChatV2ProviderCapabilities: () => getChatV2ProviderCapabilities,
425
431
  getChatV2ProviderLabel: () => getChatV2ProviderLabel,
432
+ getChatV2SystemTokenPricing: () => getChatV2SystemTokenPricing,
426
433
  getClassifierCredentialNamesForDisplay: () => getClassifierCredentialNamesForDisplay,
427
434
  getClassifierEvaluateBodySections: () => getClassifierEvaluateBodySections,
428
435
  getClassifierModelEditor: () => getClassifierModelEditor,
@@ -430,6 +437,7 @@ __export(src_exports, {
430
437
  getClassifierProviderEnvironmentVariableNames: () => getClassifierProviderEnvironmentVariableNames,
431
438
  getClassifierQuestionBodySections: () => getClassifierQuestionBodySections,
432
439
  getClassifierRequestCount: () => getClassifierRequestCount,
440
+ getClassifierSystemTokenPricing: () => getClassifierSystemTokenPricing,
433
441
  getCodeOutputFields: () => getCodeOutputFields,
434
442
  getCodeOutputKeys: () => getCodeOutputKeys,
435
443
  getCommonChatV2Editors: () => getCommonChatV2Editors,
@@ -469,6 +477,7 @@ __export(src_exports, {
469
477
  getProcessorEvents: () => getProcessorEvents,
470
478
  getProcessorSSEStream: () => getProcessorSSEStream,
471
479
  getProfileAttemptOmissionNotice: () => getProfileAttemptOmissionNotice,
480
+ getProfileDisplayName: () => getProfileDisplayName,
472
481
  getProjectConnectionComparisonKey: () => getProjectConnectionComparisonKey,
473
482
  getProjectGlobalVariableIds: () => getProjectGlobalVariableIds,
474
483
  getProjectNodeFieldComparisons: () => getProjectNodeFieldComparisons,
@@ -564,6 +573,7 @@ __export(src_exports, {
564
573
  isLLMChatV2StructuredResponseFormat: () => isLLMChatV2StructuredResponseFormat,
565
574
  isNodePrefabInstanceNode: () => isNodePrefabInstanceNode,
566
575
  isNotFunctionDataValue: () => isNotFunctionDataValue,
576
+ isReportedTokenCount: () => isReportedTokenCount,
567
577
  isReservedKnowledgeObjectKey: () => isReservedKnowledgeObjectKey,
568
578
  isRivetWebAppRunTerminalEvent: () => isRivetWebAppRunTerminalEvent,
569
579
  isRuntimeDebugLoggingEnabled: () => isRuntimeDebugLoggingEnabled,
@@ -707,6 +717,7 @@ __export(src_exports, {
707
717
  registerIntegration: () => registerIntegration,
708
718
  registerKnowledgeStoreProvider: () => registerKnowledgeStoreProvider,
709
719
  registerPluginsIntoRegistry: () => registerPluginsIntoRegistry,
720
+ remapOwnedDatasets: () => remapOwnedDatasets,
710
721
  removeKnowledgeStoreConnectionCredentials: () => removeKnowledgeStoreConnectionCredentials,
711
722
  renderUiGraphOutputValue: () => renderUiGraphOutputValue,
712
723
  replaceDatasetNode: () => replaceDatasetNode,
@@ -770,6 +781,7 @@ __export(src_exports, {
770
781
  stringifyToolResult: () => stringifyToolResult,
771
782
  stringifyUiGraphValue: () => stringifyUiGraphValue,
772
783
  subGraphNode: () => subGraphNode,
784
+ subqClassifierProvider: () => subqClassifierProvider,
773
785
  summarizeAgentResponseCalls: () => summarizeAgentResponseCalls,
774
786
  summarizeChatV2RequestPlan: () => summarizeChatV2RequestPlan,
775
787
  summarizeDataValueForLog: () => summarizeDataValueForLog,
@@ -797,6 +809,7 @@ __export(src_exports, {
797
809
  validateProjectGlobalVariables: () => validateProjectGlobalVariables,
798
810
  validateProjectUiGraphActionBindings: () => validateProjectUiGraphActionBindings,
799
811
  validateProjectUiGraphButtonBindings: () => validateProjectUiGraphButtonBindings,
812
+ validateTokenPricing: () => validateTokenPricing,
800
813
  validateUiGraphActionBindings: () => validateUiGraphActionBindings,
801
814
  validateUiGraphButtonBindings: () => validateUiGraphButtonBindings,
802
815
  vectorNearestNeighborsNode: () => vectorNearestNeighborsNode,
@@ -824,6 +837,8 @@ __export(exports_exports, {
824
837
  AssembleMessageNodeImpl: () => AssembleMessageNodeImpl,
825
838
  AssemblePromptNodeImpl: () => AssemblePromptNodeImpl,
826
839
  AudioNodeImpl: () => AudioNodeImpl,
840
+ BASETEN_DECISIONS_ENDPOINT: () => BASETEN_DECISIONS_ENDPOINT,
841
+ BASETEN_DEFAULT_CREDENTIAL_NAMES: () => BASETEN_DEFAULT_CREDENTIAL_NAMES,
827
842
  BooleanNodeImpl: () => BooleanNodeImpl,
828
843
  BrowserNativeApi: () => BrowserNativeApi,
829
844
  BuildKnowledgeContextNodeImpl: () => BuildKnowledgeContextNodeImpl,
@@ -992,6 +1007,8 @@ __export(exports_exports, {
992
1007
  RivetLLMProfileHealthPolicyError: () => RivetLLMProfileHealthPolicyError,
993
1008
  RivetStoredValueController: () => RivetStoredValueController,
994
1009
  STREAM_RESPONSE_HELPER_MESSAGE: () => STREAM_RESPONSE_HELPER_MESSAGE,
1010
+ SUBQ_DECISIONS_ENDPOINT: () => SUBQ_DECISIONS_ENDPOINT,
1011
+ SUBQ_DEFAULT_CREDENTIAL_NAMES: () => SUBQ_DEFAULT_CREDENTIAL_NAMES,
995
1012
  SearchKnowledgeNodeImpl: () => SearchKnowledgeNodeImpl,
996
1013
  SetGlobalNodeImpl: () => SetGlobalNodeImpl,
997
1014
  SetStoredValueNodeImpl: () => SetStoredValueNodeImpl,
@@ -1043,6 +1060,7 @@ __export(exports_exports, {
1043
1060
  autoevalsPlugin: () => autoevals_default,
1044
1061
  base64ToUint8Array: () => base64ToUint8Array,
1045
1062
  baseDirs: () => baseDirs,
1063
+ basetenClassifierProvider: () => basetenClassifierProvider,
1046
1064
  booleanNode: () => booleanNode,
1047
1065
  buildAgentProfileAttemptInspectorRows: () => buildAgentProfileAttemptInspectorRows,
1048
1066
  buildAgentResponseTrace: () => buildAgentResponseTrace,
@@ -1054,6 +1072,7 @@ __export(exports_exports, {
1054
1072
  calculateChatV2Cost: () => calculateChatV2Cost,
1055
1073
  calculateChatV2UsageCost: () => calculateChatV2UsageCost,
1056
1074
  calculateClassifierUsageCost: () => calculateClassifierUsageCost,
1075
+ calculateTokenUsageCost: () => calculateTokenUsageCost,
1057
1076
  callGraphNode: () => callGraphNode,
1058
1077
  canBeCoerced: () => canBeCoerced,
1059
1078
  canBeCoercedAny: () => canBeCoercedAny,
@@ -1204,6 +1223,7 @@ __export(exports_exports, {
1204
1223
  getChatV2ModelRegistry: () => getChatV2ModelRegistry,
1205
1224
  getChatV2ProviderCapabilities: () => getChatV2ProviderCapabilities,
1206
1225
  getChatV2ProviderLabel: () => getChatV2ProviderLabel,
1226
+ getChatV2SystemTokenPricing: () => getChatV2SystemTokenPricing,
1207
1227
  getClassifierCredentialNamesForDisplay: () => getClassifierCredentialNamesForDisplay,
1208
1228
  getClassifierEvaluateBodySections: () => getClassifierEvaluateBodySections,
1209
1229
  getClassifierModelEditor: () => getClassifierModelEditor,
@@ -1211,6 +1231,7 @@ __export(exports_exports, {
1211
1231
  getClassifierProviderEnvironmentVariableNames: () => getClassifierProviderEnvironmentVariableNames,
1212
1232
  getClassifierQuestionBodySections: () => getClassifierQuestionBodySections,
1213
1233
  getClassifierRequestCount: () => getClassifierRequestCount,
1234
+ getClassifierSystemTokenPricing: () => getClassifierSystemTokenPricing,
1214
1235
  getCodeOutputFields: () => getCodeOutputFields,
1215
1236
  getCodeOutputKeys: () => getCodeOutputKeys,
1216
1237
  getCommonChatV2Editors: () => getCommonChatV2Editors,
@@ -1250,6 +1271,7 @@ __export(exports_exports, {
1250
1271
  getProcessorEvents: () => getProcessorEvents,
1251
1272
  getProcessorSSEStream: () => getProcessorSSEStream,
1252
1273
  getProfileAttemptOmissionNotice: () => getProfileAttemptOmissionNotice,
1274
+ getProfileDisplayName: () => getProfileDisplayName,
1253
1275
  getProjectConnectionComparisonKey: () => getProjectConnectionComparisonKey,
1254
1276
  getProjectGlobalVariableIds: () => getProjectGlobalVariableIds,
1255
1277
  getProjectNodeFieldComparisons: () => getProjectNodeFieldComparisons,
@@ -1345,6 +1367,7 @@ __export(exports_exports, {
1345
1367
  isLLMChatV2StructuredResponseFormat: () => isLLMChatV2StructuredResponseFormat,
1346
1368
  isNodePrefabInstanceNode: () => isNodePrefabInstanceNode,
1347
1369
  isNotFunctionDataValue: () => isNotFunctionDataValue,
1370
+ isReportedTokenCount: () => isReportedTokenCount,
1348
1371
  isReservedKnowledgeObjectKey: () => isReservedKnowledgeObjectKey,
1349
1372
  isRivetWebAppRunTerminalEvent: () => isRivetWebAppRunTerminalEvent,
1350
1373
  isRuntimeDebugLoggingEnabled: () => isRuntimeDebugLoggingEnabled,
@@ -1488,6 +1511,7 @@ __export(exports_exports, {
1488
1511
  registerIntegration: () => registerIntegration,
1489
1512
  registerKnowledgeStoreProvider: () => registerKnowledgeStoreProvider,
1490
1513
  registerPluginsIntoRegistry: () => registerPluginsIntoRegistry,
1514
+ remapOwnedDatasets: () => remapOwnedDatasets,
1491
1515
  removeKnowledgeStoreConnectionCredentials: () => removeKnowledgeStoreConnectionCredentials,
1492
1516
  renderUiGraphOutputValue: () => renderUiGraphOutputValue,
1493
1517
  replaceDatasetNode: () => replaceDatasetNode,
@@ -1551,6 +1575,7 @@ __export(exports_exports, {
1551
1575
  stringifyToolResult: () => stringifyToolResult,
1552
1576
  stringifyUiGraphValue: () => stringifyUiGraphValue,
1553
1577
  subGraphNode: () => subGraphNode,
1578
+ subqClassifierProvider: () => subqClassifierProvider,
1554
1579
  summarizeAgentResponseCalls: () => summarizeAgentResponseCalls,
1555
1580
  summarizeChatV2RequestPlan: () => summarizeChatV2RequestPlan,
1556
1581
  summarizeDataValueForLog: () => summarizeDataValueForLog,
@@ -1578,6 +1603,7 @@ __export(exports_exports, {
1578
1603
  validateProjectGlobalVariables: () => validateProjectGlobalVariables,
1579
1604
  validateProjectUiGraphActionBindings: () => validateProjectUiGraphActionBindings,
1580
1605
  validateProjectUiGraphButtonBindings: () => validateProjectUiGraphButtonBindings,
1606
+ validateTokenPricing: () => validateTokenPricing,
1581
1607
  validateUiGraphActionBindings: () => validateUiGraphActionBindings,
1582
1608
  validateUiGraphButtonBindings: () => validateUiGraphButtonBindings,
1583
1609
  vectorNearestNeighborsNode: () => vectorNearestNeighborsNode,
@@ -1944,6 +1970,7 @@ async function waitForLLMChatV2RetryCooldown(cooldownMs, signal) {
1944
1970
 
1945
1971
  // src/model/chat-v2/llmProfileFieldRegistry.ts
1946
1972
  var llmProfileFieldSpecs = [
1973
+ { key: "tokenPricing" },
1947
1974
  { key: "model", inputId: "model", valueKind: "string" },
1948
1975
  { key: "useModelInput", valueKind: "boolean", resolvedInputToggle: true },
1949
1976
  { key: "temperature", inputId: "temperature", valueKind: "optional-number" },
@@ -3352,6 +3379,47 @@ function normalizeTemperature(value, label = "Temperature") {
3352
3379
  return value;
3353
3380
  }
3354
3381
 
3382
+ // src/model/tokenPricing.ts
3383
+ function isReportedTokenCount(value) {
3384
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
3385
+ }
3386
+ function validateTokenPricing(value) {
3387
+ if (value === void 0) return void 0;
3388
+ if (value === null || typeof value !== "object" || Array.isArray(value))
3389
+ throw new Error("Token pricing override must be an object.");
3390
+ const result = {};
3391
+ for (const key of [
3392
+ "inputPerMillionTokens",
3393
+ "outputPerMillionTokens",
3394
+ "cacheReadPerMillionTokens",
3395
+ "cacheWritePerMillionTokens"
3396
+ ]) {
3397
+ const rate = value[key];
3398
+ if (rate === void 0 && key.startsWith("cache")) continue;
3399
+ if (typeof rate !== "number" || !Number.isFinite(rate) || rate < 0)
3400
+ throw new Error(`Token pricing ${key} must be a finite, non-negative USD rate.`);
3401
+ result[key] = rate;
3402
+ }
3403
+ return result;
3404
+ }
3405
+ function calculateTokenUsageCost(pricing, usage) {
3406
+ try {
3407
+ const validated = validateTokenPricing(pricing);
3408
+ if (!validated) return void 0;
3409
+ pricing = validated;
3410
+ } catch {
3411
+ return void 0;
3412
+ }
3413
+ const { inputTokens, outputTokens, inputTokenDetails } = usage ?? {};
3414
+ const read = (inputTokenDetails == null ? void 0 : inputTokenDetails.cacheReadTokens) === void 0 ? 0 : inputTokenDetails.cacheReadTokens;
3415
+ const write = (inputTokenDetails == null ? void 0 : inputTokenDetails.cacheWriteTokens) === void 0 ? 0 : inputTokenDetails.cacheWriteTokens;
3416
+ if (!isReportedTokenCount(inputTokens) || !isReportedTokenCount(outputTokens) || !isReportedTokenCount(read) || !isReportedTokenCount(write))
3417
+ return void 0;
3418
+ if (read + write > inputTokens) return void 0;
3419
+ const total = ((inputTokens - read - write) * pricing.inputPerMillionTokens + read * (pricing.cacheReadPerMillionTokens ?? pricing.inputPerMillionTokens) + write * (pricing.cacheWritePerMillionTokens ?? pricing.inputPerMillionTokens) + outputTokens * pricing.outputPerMillionTokens) / 1e6;
3420
+ return Number.isFinite(total) && total >= 0 ? total : void 0;
3421
+ }
3422
+
3355
3423
  // src/model/chat-v2/llmProfile.ts
3356
3424
  var credentialSources = /* @__PURE__ */ new Set([
3357
3425
  "input",
@@ -3439,6 +3507,7 @@ function scopeLLMProfileHealthIdentity(profile, fallback) {
3439
3507
  }
3440
3508
  function normalizeConfiguration(data) {
3441
3509
  var _a, _b;
3510
+ data = { ...data, tokenPricing: validateTokenPricing(data.tokenPricing) };
3442
3511
  for (const field2 of llmProfileStringDataKeys) {
3443
3512
  if (typeof data[field2] !== "string") {
3444
3513
  throw new Error(`LLM Profile ${field2} must be a string.`);
@@ -5330,11 +5399,11 @@ var import_lodash_es2 = require("lodash");
5330
5399
  // src/model/chat-v2/llmChatV2NodeMigration.ts
5331
5400
  function normalizeSerializedLLMTemperatureData(nodeType, data) {
5332
5401
  if (!["llmChatV2", "llmProfile"].includes(nodeType) || data == null || typeof data !== "object") return data;
5333
- const record3 = data;
5334
- if (!Object.hasOwn(record3, "temperature")) return data;
5335
- if (record3.temperature != null && !(typeof record3.temperature === "number" && Number.isNaN(record3.temperature)))
5402
+ const record4 = data;
5403
+ if (!Object.hasOwn(record4, "temperature")) return data;
5404
+ if (record4.temperature != null && !(typeof record4.temperature === "number" && Number.isNaN(record4.temperature)))
5336
5405
  return data;
5337
- const copy = { ...record3 };
5406
+ const copy = { ...record4 };
5338
5407
  delete copy.temperature;
5339
5408
  return copy;
5340
5409
  }
@@ -5369,9 +5438,6 @@ function keys(o) {
5369
5438
  function values(o) {
5370
5439
  return Object.values(o);
5371
5440
  }
5372
- function mapValues2(o, fn) {
5373
- return Object.fromEntries(Object.entries(o).map(([key, value]) => [key, fn(value)]));
5374
- }
5375
5441
 
5376
5442
  // src/model/NodeGraph.ts
5377
5443
  var import_non_secure3 = require("nanoid/non-secure");
@@ -6772,6 +6838,56 @@ function evaluateJsonPath(value, path, wrap = false) {
6772
6838
  });
6773
6839
  }
6774
6840
 
6841
+ // src/model/RunCostLedger.ts
6842
+ var RunCostLedger = class {
6843
+ #calls = /* @__PURE__ */ new Map();
6844
+ #hasUnobservedWork = false;
6845
+ observeChat(event) {
6846
+ if (typeof event.callId !== "string" || !event.callId) {
6847
+ this.markUnobserved();
6848
+ return;
6849
+ }
6850
+ this.#record(`llm:${event.callId}`, event.pricing.status === "known" ? event.pricing.costUsd : void 0);
6851
+ }
6852
+ observeClassifier(event) {
6853
+ var _a;
6854
+ if (event.family !== "classifier" || event.attemptIndex === void 0) return;
6855
+ if (typeof event.eventId !== "string" || !event.eventId || !Number.isSafeInteger(event.attemptIndex) || event.attemptIndex < 0) {
6856
+ this.markUnobserved();
6857
+ return;
6858
+ }
6859
+ this.#record(`decision:${event.eventId}`, (_a = event.classifierUsage) == null ? void 0 : _a.estimatedCostUsd);
6860
+ }
6861
+ /** Legacy Chat does not expose complete per-attempt accounting. */
6862
+ observeLegacy(key, value) {
6863
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) this.#record(`legacy:${key}`, value);
6864
+ this.markUnobserved();
6865
+ }
6866
+ markUnobserved() {
6867
+ this.#hasUnobservedWork = true;
6868
+ }
6869
+ snapshot(executionPending = false) {
6870
+ let known = 0;
6871
+ let knownCount = 0;
6872
+ let hasUnknownCost = this.#hasUnobservedWork || executionPending;
6873
+ for (const cost of this.#calls.values()) {
6874
+ if (cost === null) hasUnknownCost = true;
6875
+ else {
6876
+ known += cost;
6877
+ knownCount++;
6878
+ }
6879
+ }
6880
+ if (!Number.isFinite(known)) return { status: "unknown", knownCostUsd: null };
6881
+ if (!hasUnknownCost) return { status: "complete", knownCostUsd: known };
6882
+ if (knownCount === 0) return { status: "unknown", knownCostUsd: null };
6883
+ return { status: "partial", knownCostUsd: known };
6884
+ }
6885
+ #record(id, value) {
6886
+ if (this.#calls.has(id)) return;
6887
+ this.#calls.set(id, typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null);
6888
+ }
6889
+ };
6890
+
6775
6891
  // src/model/GraphExecutionState.ts
6776
6892
  var GraphInvocationState = class {
6777
6893
  rootRunId = void 0;
@@ -6798,6 +6914,7 @@ var GraphInvocationState = class {
6798
6914
  successfulAbortTerminalProcessIds = void 0;
6799
6915
  totalCost = 0;
6800
6916
  costBreakdown;
6917
+ costLedger = new RunCostLedger();
6801
6918
  ignoreNodes = void 0;
6802
6919
  hasPreloadedData = false;
6803
6920
  loadedProjects = void 0;
@@ -6834,6 +6951,7 @@ var GraphInvocationState = class {
6834
6951
  this.successfulAbortTerminalProcessIds = /* @__PURE__ */ new Set();
6835
6952
  this.totalCost = 0;
6836
6953
  this.costBreakdown = void 0;
6954
+ this.costLedger = new RunCostLedger();
6837
6955
  this.nodeAbortControllers = /* @__PURE__ */ new Map();
6838
6956
  this.loadedProjects = options2.loadedProjects;
6839
6957
  this.graphInputNodeValues = ((_c = options2.sharedOverride) == null ? void 0 : _c.graphInputNodeValues) ?? {};
@@ -6853,6 +6971,57 @@ var GraphSharedExecutionState = class _GraphSharedExecutionState {
6853
6971
  }
6854
6972
  };
6855
6973
 
6974
+ // src/model/ChildInvocationOwnership.ts
6975
+ function resolveChildInvocationOwnership(mode, context) {
6976
+ const { run } = context;
6977
+ switch (mode.kind) {
6978
+ case "continuation":
6979
+ return {
6980
+ parent: context.parent,
6981
+ abortOwner: context.abortOwner,
6982
+ sameGraphOwner: context.sameGraphOwner,
6983
+ suppressPartialOutputs: false,
6984
+ suppressLifecycle: true,
6985
+ state: {
6986
+ attachedNodeData: run.attachedNodeData,
6987
+ graphInputNodeValues: run.graphInputNodeValues,
6988
+ graphOutputs: mode.graphOutputs
6989
+ },
6990
+ identity: { rootRunId: run.rootRunId, graphRunId: run.graphRunId, parentGraphRunId: run.parentGraphRunId }
6991
+ };
6992
+ case "async":
6993
+ return {
6994
+ parent: context.sameGraphOwner,
6995
+ abortOwner: context.root,
6996
+ suppressPartialOutputs: true,
6997
+ suppressLifecycle: context.rootGraphOrigin,
6998
+ state: {
6999
+ attachedNodeData: run.attachedNodeData,
7000
+ graphInputNodeValues: run.graphInputNodeValues,
7001
+ graphOutputs: {}
7002
+ },
7003
+ identity: context.rootGraphOrigin ? { rootRunId: run.rootRunId, graphRunId: run.graphRunId, parentGraphRunId: run.parentGraphRunId } : {
7004
+ rootRunId: context.rootIdentity.rootRunId,
7005
+ graphRunId: context.newGraphRunId(),
7006
+ parentGraphRunId: context.sameGraphIdentity.graphRunId
7007
+ }
7008
+ };
7009
+ case "watch":
7010
+ return {
7011
+ parent: context.parent,
7012
+ abortOwner: context.root,
7013
+ suppressPartialOutputs: true,
7014
+ suppressLifecycle: true,
7015
+ state: { attachedNodeData: /* @__PURE__ */ new Map(), graphInputNodeValues: { ...run.graphInputNodeValues }, graphOutputs: {} },
7016
+ identity: {
7017
+ rootRunId: context.rootIdentity.rootRunId,
7018
+ graphRunId: mode.graphRunId,
7019
+ parentGraphRunId: run.graphRunId
7020
+ }
7021
+ };
7022
+ }
7023
+ }
7024
+
6856
7025
  // src/model/SchedulerBoundaryPlanner.ts
6857
7026
  function indexConnections(connections) {
6858
7027
  const outgoingByNodeId = /* @__PURE__ */ new Map();
@@ -9851,8 +10020,8 @@ function normalizeRivetStoredValueKey(value) {
9851
10020
  }
9852
10021
  return value;
9853
10022
  }
9854
- function setStoredValueRecordEntry(record3, key, value) {
9855
- Object.defineProperty(record3, key, { configurable: true, enumerable: true, value, writable: true });
10023
+ function setStoredValueRecordEntry(record4, key, value) {
10024
+ Object.defineProperty(record4, key, { configurable: true, enumerable: true, value, writable: true });
9856
10025
  }
9857
10026
  function cloneRivetStoredValue(value, label = "Stored value") {
9858
10027
  return clonePortableValue(value, label, /* @__PURE__ */ new Set());
@@ -10078,8 +10247,8 @@ function buildDelegatedToolCallOutputs(records, preToolMessage, cost, costBreakd
10078
10247
  type: "string",
10079
10248
  value: preToolMessage
10080
10249
  };
10081
- const executionTimesSeconds = records.map((record3) => {
10082
- const executionTimeMs = getExecutionTimeMs(record3);
10250
+ const executionTimesSeconds = records.map((record4) => {
10251
+ const executionTimeMs = getExecutionTimeMs(record4);
10083
10252
  return executionTimeMs == null ? void 0 : executionTimeMs / 1e3;
10084
10253
  });
10085
10254
  const executionTimeOutput = executionTimesSeconds.every((executionTimeSeconds) => executionTimeSeconds != null) ? records.length === 1 ? {
@@ -10114,21 +10283,21 @@ function buildDelegatedToolCallOutputs(records, preToolMessage, cost, costBreakd
10114
10283
  } : {
10115
10284
  ["tool-name"]: {
10116
10285
  type: "string[]",
10117
- value: records.map((record3) => record3.name)
10286
+ value: records.map((record4) => record4.name)
10118
10287
  },
10119
10288
  ["tool-arguments"]: {
10120
10289
  type: "object[]",
10121
- value: records.map((record3) => record3.arguments)
10290
+ value: records.map((record4) => record4.arguments)
10122
10291
  },
10123
10292
  ["assistant-message"]: preToolMessageOutput,
10124
10293
  ["output"]: {
10125
10294
  type: "string[]",
10126
- value: records.map((record3) => record3.output)
10295
+ value: records.map((record4) => record4.output)
10127
10296
  },
10128
10297
  ["execution-time"]: executionTimeOutput,
10129
10298
  ["message"]: {
10130
10299
  type: "chat-message[]",
10131
- value: records.map((record3) => record3.message)
10300
+ value: records.map((record4) => record4.message)
10132
10301
  }
10133
10302
  };
10134
10303
  if (cost != null) {
@@ -10307,8 +10476,8 @@ function getCurrentTimeMs() {
10307
10476
  var _a, _b;
10308
10477
  return ((_b = (_a = globalThis.performance) == null ? void 0 : _a.now) == null ? void 0 : _b.call(_a)) ?? Date.now();
10309
10478
  }
10310
- function getExecutionTimeMs(record3) {
10311
- const { executionTimeMs } = record3;
10479
+ function getExecutionTimeMs(record4) {
10480
+ const { executionTimeMs } = record4;
10312
10481
  return typeof executionTimeMs === "number" && Number.isFinite(executionTimeMs) && executionTimeMs >= 0 ? executionTimeMs : void 0;
10313
10482
  }
10314
10483
 
@@ -13512,6 +13681,20 @@ function resolveCodeInterpolationExpression(inputs, expression, graphInputValues
13512
13681
  });
13513
13682
  }
13514
13683
 
13684
+ // src/integrations/CodeRunnerNamespace.ts
13685
+ var namespace;
13686
+ function installCodeRunnerNamespace(value) {
13687
+ namespace = value;
13688
+ }
13689
+ function getCodeRunnerNamespace() {
13690
+ if (!namespace) {
13691
+ throw new Error(
13692
+ "The Rivet code namespace is unavailable. Import the public core entrypoint or supply a code runner."
13693
+ );
13694
+ }
13695
+ return namespace;
13696
+ }
13697
+
13515
13698
  // src/integrations/CodeRunnerOptions.ts
13516
13699
  var ALL_CODE_RUNNER_OPTIONS = Object.freeze({
13517
13700
  includeRequire: true,
@@ -13523,6 +13706,9 @@ var ALL_CODE_RUNNER_OPTIONS = Object.freeze({
13523
13706
 
13524
13707
  // src/integrations/CodeRunner.ts
13525
13708
  var IsomorphicCodeRunner = class {
13709
+ constructor(resolveNamespace = getCodeRunnerNamespace) {
13710
+ this.resolveNamespace = resolveNamespace;
13711
+ }
13526
13712
  async runCode(code, inputs, options2, graphInputs, contextValues, globalValues) {
13527
13713
  const argNames = ["inputs"];
13528
13714
  const args = [inputs];
@@ -13536,7 +13722,7 @@ var IsomorphicCodeRunner = class {
13536
13722
  }
13537
13723
  if (options2.includeRivet) {
13538
13724
  argNames.push("Rivet");
13539
- args.push(exports_exports);
13725
+ args.push(this.resolveNamespace());
13540
13726
  }
13541
13727
  if (graphInputs) {
13542
13728
  argNames.push("graphInputs");
@@ -14376,6 +14562,7 @@ var GraphProcessor = class _GraphProcessor {
14376
14562
  const hostChatV2Observer = this.getRootProcessor().#run.context.onChatV2CallFinished;
14377
14563
  const hostLLMChatOutputSnapshotObserver = this.getRootProcessor().#run.context.onLLMChatOutputSnapshot;
14378
14564
  const hostLLMProfileAttemptObserver = this.getRootProcessor().#run.context.onLLMProfileAttempt;
14565
+ const costLedger = this.getRootProcessor().#run.costLedger;
14379
14566
  this.#run.nodeProcessContextBase = {
14380
14567
  ...this.#run.context,
14381
14568
  abortGraph: (error) => {
@@ -14395,6 +14582,11 @@ var GraphProcessor = class _GraphProcessor {
14395
14582
  graphOutputs: this.#run.graphOutputs,
14396
14583
  graphCallPath: this.#graphCallPath,
14397
14584
  onChatV2CallFinished: (event) => {
14585
+ try {
14586
+ costLedger.observeChat(event);
14587
+ } catch {
14588
+ costLedger.markUnobserved();
14589
+ }
14398
14590
  try {
14399
14591
  const observerResult = hostChatV2Observer == null ? void 0 : hostChatV2Observer(event);
14400
14592
  if (observerResult != null && typeof observerResult.then === "function") {
@@ -14416,6 +14608,11 @@ var GraphProcessor = class _GraphProcessor {
14416
14608
  emitDetached(this.#emitter, "llmChatOutputSnapshot", this.#withExecution(event));
14417
14609
  },
14418
14610
  onLLMProfileAttempt: (event) => {
14611
+ try {
14612
+ costLedger.observeClassifier(event);
14613
+ } catch {
14614
+ costLedger.markUnobserved();
14615
+ }
14419
14616
  try {
14420
14617
  const observerResult = hostLLMProfileAttemptObserver == null ? void 0 : hostLLMProfileAttemptObserver(event);
14421
14618
  if (observerResult != null && typeof observerResult.then === "function") {
@@ -15291,7 +15488,6 @@ ${errors.map(({ node }) => `- ${node.title} (${node.id})`).join("\n")}`;
15291
15488
  var _a, _b;
15292
15489
  const root = this.getRootProcessor();
15293
15490
  const sameGraphOwner = this.#sameGraphRunOwnerOverride ?? this;
15294
- const isRootGraphOrigin = !sameGraphOwner.#isSubProcessor;
15295
15491
  if (root.#run.abortController.signal.aborted) {
15296
15492
  throw createGraphAbortErrorFromSignal(root.#run.abortController.signal, "Async branch aborted before it started");
15297
15493
  }
@@ -15308,29 +15504,8 @@ ${errors.map(({ node }) => `- ${node.title} (${node.id})`).join("\n")}`;
15308
15504
  ),
15309
15505
  onCreated: onProcessorCreated
15310
15506
  });
15311
- processor.#parent = sameGraphOwner;
15312
- processor.#abortOwnerOverride = root;
15313
- processor.#suppressGraphPartialOutputs = true;
15314
- processor.#suppressGraphLifecycleEvents = isRootGraphOrigin;
15315
- processor.#sharedRunStateOverride = {
15316
- attachedNodeData: this.#run.attachedNodeData,
15317
- graphInputNodeValues: this.#run.graphInputNodeValues,
15318
- // Async branches cannot contain Graph Output nodes. Keep their synthetic
15319
- // boundary outputs private so branch finalization cannot seed the root's
15320
- // derived cost output before the root has accumulated every path.
15321
- graphOutputs: {}
15322
- };
15323
15507
  const branchRunToNodeIds = (_b = this.runToNodeIds) == null ? void 0 : _b.filter((nodeId) => plan.nodeIds.has(nodeId));
15324
15508
  processor.runToNodeIds = (branchRunToNodeIds == null ? void 0 : branchRunToNodeIds.length) ? branchRunToNodeIds : void 0;
15325
- processor.#executionIdentityOverride = isRootGraphOrigin ? {
15326
- rootRunId: this.#run.rootRunId,
15327
- graphRunId: this.#run.graphRunId,
15328
- parentGraphRunId: this.#run.parentGraphRunId
15329
- } : {
15330
- rootRunId: root.#run.rootRunId,
15331
- graphRunId: (0, import_non_secure12.nanoid)(),
15332
- parentGraphRunId: sameGraphOwner.#run.graphRunId
15333
- };
15334
15509
  processor.preloadNodeData(triggerNode.id, triggerOutputs);
15335
15510
  processor.#suppressedPreloadedNodeIds.add(triggerNode.id);
15336
15511
  const unwireEvents = this.#wireChildEvents(processor, root, {
@@ -15662,6 +15837,11 @@ ${errors.map(({ node }) => `- ${node.title} (${node.id})`).join("\n")}`;
15662
15837
  }
15663
15838
  return processor;
15664
15839
  }
15840
+ /** Snapshot the root execution's observed provider estimates after completion. */
15841
+ getRunCostSnapshot() {
15842
+ const root = this.getRootProcessor();
15843
+ return root.#run.costLedger.snapshot(root.isRunning);
15844
+ }
15665
15845
  #getEnclosingStreamingWatchInvocation() {
15666
15846
  let processor = this;
15667
15847
  while (processor) {
@@ -15757,6 +15937,12 @@ ${errors.map(({ node }) => `- ${node.title} (${node.id})`).join("\n")}`;
15757
15937
  nodeAbortController.abort(getAbortSignalReason(this.#run.abortController.signal));
15758
15938
  }
15759
15939
  let continuationFinalized = false;
15940
+ const costLedger = this.getRootProcessor().#run.costLedger;
15941
+ const accountingKey = `${this.#run.graphRunId}:${processId}:${index}`;
15942
+ let accountingEntered = false;
15943
+ let observedPhysicalCall = false;
15944
+ let cacheHit = false;
15945
+ let accountingOutputs;
15760
15946
  try {
15761
15947
  const createContextProfileStart = this.#startRuntimeProfile();
15762
15948
  let context;
@@ -15769,7 +15955,10 @@ ${errors.map(({ node }) => `- ${node.title} (${node.id})`).join("\n")}`;
15769
15955
  nodeAbortController,
15770
15956
  partialOutput,
15771
15957
  void 0,
15772
- markResultAsEditorCacheHit
15958
+ markResultAsEditorCacheHit ? () => {
15959
+ cacheHit = true;
15960
+ markResultAsEditorCacheHit();
15961
+ } : void 0
15773
15962
  );
15774
15963
  } finally {
15775
15964
  this.#finishRuntimeProfile("createNodeProcessContext", createContextProfileStart);
@@ -15778,10 +15967,25 @@ ${errors.map(({ node }) => `- ${node.title} (${node.id})`).join("\n")}`;
15778
15967
  if (nodeAbortController.signal.aborted) {
15779
15968
  throw createGraphAbortErrorFromSignal(nodeAbortController.signal);
15780
15969
  }
15970
+ if (node.type === "llmChatV2") {
15971
+ const observer = context.onChatV2CallFinished;
15972
+ context.onChatV2CallFinished = (event) => {
15973
+ observedPhysicalCall = true;
15974
+ observer == null ? void 0 : observer(event);
15975
+ };
15976
+ } else if (node.type === "classifierEvaluate") {
15977
+ const observer = context.onLLMProfileAttempt;
15978
+ context.onLLMProfileAttempt = (event) => {
15979
+ if (event.family === "classifier" && event.attemptIndex !== void 0) observedPhysicalCall = true;
15980
+ observer == null ? void 0 : observer(event);
15981
+ };
15982
+ }
15781
15983
  const implementationProfileStart = this.#startRuntimeProfile();
15782
15984
  let results;
15783
15985
  try {
15986
+ accountingEntered = true;
15784
15987
  results = await instance.process(inputValues, context);
15988
+ accountingOutputs = results;
15785
15989
  } finally {
15786
15990
  this.#finishRuntimeProfile("nodeImplementation", implementationProfileStart);
15787
15991
  }
@@ -15800,6 +16004,18 @@ ${errors.map(({ node }) => `- ${node.title} (${node.id})`).join("\n")}`;
15800
16004
  this.#discardFailureOutputs(processId, index);
15801
16005
  return results;
15802
16006
  } finally {
16007
+ if (accountingEntered && !cacheHit) {
16008
+ try {
16009
+ if (["chat", "chatLoop", "chatGoogle", "chatAnthropic", "chatHuggingFace", "getEmbedding"].includes(node.type)) {
16010
+ const cost = accountingOutputs == null ? void 0 : accountingOutputs["cost"];
16011
+ costLedger.observeLegacy(accountingKey, (cost == null ? void 0 : cost.type) === "number" ? cost.value : void 0);
16012
+ } else if ((node.type === "llmChatV2" || node.type === "classifierEvaluate") && !observedPhysicalCall) {
16013
+ costLedger.markUnobserved();
16014
+ }
16015
+ } catch {
16016
+ costLedger.markUnobserved();
16017
+ }
16018
+ }
15803
16019
  if (!continuationFinalized) {
15804
16020
  this.#discardToolCallContinuation(processId, index);
15805
16021
  }
@@ -16086,23 +16302,14 @@ ${errors.map(({ node }) => `- ${node.title} (${node.id})`).join("\n")}`;
16086
16302
  throw new Error("Cannot execute a tool continuation branch because the current graph has no ID.");
16087
16303
  }
16088
16304
  const branchGraphOutputs = createGraphOutputsOverlay(this.#run.graphOutputs);
16089
- const processor = this.#constructChildInvocation({ kind: "continuation", graph: branchPlan.graph });
16090
- processor.#abortOwnerOverride = this.#abortOwnerOverride ?? this;
16091
- processor.#sameGraphRunOwnerOverride = this.#sameGraphRunOwnerOverride ?? this;
16092
- processor.#suppressGraphLifecycleEvents = true;
16093
- processor.#sharedRunStateOverride = {
16094
- attachedNodeData: this.#run.attachedNodeData,
16095
- graphInputNodeValues: this.#run.graphInputNodeValues,
16305
+ const processor = this.#constructChildInvocation({
16306
+ kind: "continuation",
16307
+ graph: branchPlan.graph,
16096
16308
  graphOutputs: branchGraphOutputs.view
16097
- };
16309
+ });
16098
16310
  const branchNodeIds = new Set(branchPlan.graph.nodes.map((node) => node.id));
16099
16311
  const branchRunToNodeIds = (_b = this.runToNodeIds) == null ? void 0 : _b.filter((nodeId) => branchNodeIds.has(nodeId));
16100
16312
  processor.runToNodeIds = (branchRunToNodeIds == null ? void 0 : branchRunToNodeIds.length) ? branchRunToNodeIds : void 0;
16101
- processor.#executionIdentityOverride = {
16102
- rootRunId: this.#run.rootRunId,
16103
- graphRunId: this.#run.graphRunId,
16104
- parentGraphRunId: this.#run.parentGraphRunId
16105
- };
16106
16313
  for (const [nodeId, outputs] of branchPlan.preloadedOutputs) {
16107
16314
  processor.preloadNodeData(nodeId, outputs);
16108
16315
  processor.#suppressedPreloadedNodeIds.add(nodeId);
@@ -16749,22 +16956,9 @@ ${errors.map(({ node }) => `- ${node.title} (${node.id})`).join("\n")}`;
16749
16956
  processor = this.#constructChildInvocation({
16750
16957
  kind: "watch",
16751
16958
  graph: plan.graph,
16752
- watchNodeId: plan.watchNode.id
16753
- });
16754
- processor.#abortOwnerOverride = root;
16755
- processor.#suppressGraphPartialOutputs = true;
16756
- processor.#suppressGraphLifecycleEvents = true;
16757
- processor.#sharedRunStateOverride = {
16758
- // Repeated node IDs do not imply shared race/loop state between snapshots.
16759
- attachedNodeData: /* @__PURE__ */ new Map(),
16760
- graphInputNodeValues: { ...this.#run.graphInputNodeValues },
16761
- graphOutputs: {}
16762
- };
16763
- processor.#executionIdentityOverride = {
16764
- rootRunId: root.#run.rootRunId,
16765
- graphRunId: historyIteration.graphRunId,
16766
- parentGraphRunId: this.#run.graphRunId
16767
- };
16959
+ watchNodeId: plan.watchNode.id,
16960
+ graphRunId: historyIteration.graphRunId
16961
+ });
16768
16962
  processor.#streamingWatchInvocation = {
16769
16963
  plan,
16770
16964
  historyIteration,
@@ -17108,8 +17302,8 @@ ${errors.map(({ node }) => `- ${node.title} (${node.id})`).join("\n")}`;
17108
17302
  execution: parentExecution
17109
17303
  });
17110
17304
  }
17111
- /** Common construction only. Aliases, execution identity and terminal commits
17112
- * remain explicit in each invocation path rather than a matrix of flags. */
17305
+ /** One construction boundary applies the discriminated ownership contract;
17306
+ * scheduling and terminal commits remain with their respective branch owner. */
17113
17307
  #constructChildInvocation(invocation) {
17114
17308
  const ordinary = invocation.kind === "subgraph";
17115
17309
  const processor = new _GraphProcessor(
@@ -17148,6 +17342,27 @@ ${errors.map(({ node }) => `- ${node.title} (${node.id})`).join("\n")}`;
17148
17342
  processor.#graphCallPath = this.#graphCallPath;
17149
17343
  processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
17150
17344
  processor.#executor = this.#executor;
17345
+ if (!ordinary) {
17346
+ const sameGraphOwner = this.#sameGraphRunOwnerOverride ?? this;
17347
+ const ownership = resolveChildInvocationOwnership(invocation, {
17348
+ parent: this,
17349
+ root: this.getRootProcessor(),
17350
+ abortOwner: this.#abortOwnerOverride ?? this,
17351
+ sameGraphOwner,
17352
+ rootGraphOrigin: !sameGraphOwner.#isSubProcessor,
17353
+ run: this.#run,
17354
+ rootIdentity: this.getRootProcessor().#run,
17355
+ sameGraphIdentity: sameGraphOwner.#run,
17356
+ newGraphRunId: () => (0, import_non_secure12.nanoid)()
17357
+ });
17358
+ processor.#parent = ownership.parent;
17359
+ processor.#abortOwnerOverride = ownership.abortOwner;
17360
+ processor.#sameGraphRunOwnerOverride = ownership.sameGraphOwner;
17361
+ processor.#suppressGraphPartialOutputs = ownership.suppressPartialOutputs;
17362
+ processor.#suppressGraphLifecycleEvents = ownership.suppressLifecycle;
17363
+ processor.#sharedRunStateOverride = ownership.state;
17364
+ processor.#executionIdentityOverride = ownership.identity;
17365
+ }
17151
17366
  return processor;
17152
17367
  }
17153
17368
  #wireChildEvents(processor, owner, options2 = {}) {
@@ -21238,10 +21453,6 @@ var NodeRegistration = class {
21238
21453
  get #dynamicImpls() {
21239
21454
  return this.#implsMap;
21240
21455
  }
21241
- get #dynamicDisplayNames() {
21242
- const displayNameMap = mapValues2(this.#infos, (info) => info.displayName);
21243
- return displayNameMap;
21244
- }
21245
21456
  registerPlugin(plugin) {
21246
21457
  if (plugin.register) {
21247
21458
  plugin.register((definition) => this.registerPluginNode(definition, plugin));
@@ -21279,7 +21490,7 @@ var NodeRegistration = class {
21279
21490
  return this.#getInfo(type).displayName;
21280
21491
  }
21281
21492
  getDynamicDisplayName(type) {
21282
- const displayName = this.#dynamicDisplayNames[type];
21493
+ const displayName = Object.hasOwn(this.#infos, type) ? this.#infos[type].displayName : void 0;
21283
21494
  if (!displayName) {
21284
21495
  throw new Error(`Unknown node type: ${type}`);
21285
21496
  }
@@ -23636,6 +23847,16 @@ var profileSuspensionHints = {
23636
23847
  duration: "Time to suspend this profile before one recovery attempt."
23637
23848
  };
23638
23849
 
23850
+ // src/model/tokenPricingEditor.ts
23851
+ function getTokenPricingEditor() {
23852
+ return {
23853
+ type: "group",
23854
+ label: "Token pricing",
23855
+ defaultOpen: false,
23856
+ editors: [{ type: "custom", label: "Token pricing", customEditorId: "AIProfilePricing" }]
23857
+ };
23858
+ }
23859
+
23639
23860
  // src/model/chat-v2/providerOptions.ts
23640
23861
  var import_anthropic2 = require("@ai-sdk/anthropic");
23641
23862
  var import_google2 = require("@ai-sdk/google");
@@ -23647,10 +23868,10 @@ var import_ai_sdk_provider = require("@openrouter/ai-sdk-provider");
23647
23868
  var import_ai = require("ai");
23648
23869
  function normalizeEmbeddedError(error) {
23649
23870
  if (error instanceof Error || error == null || typeof error !== "object" || Array.isArray(error)) return error;
23650
- const record3 = error;
23651
- if (typeof record3.message !== "string") return error;
23652
- const normalized = new Error(record3.message, { cause: error });
23653
- const code = typeof record3.code === "string" && /^\d{3}$/.test(record3.code) ? Number(record3.code) : record3.code;
23871
+ const record4 = error;
23872
+ if (typeof record4.message !== "string") return error;
23873
+ const normalized = new Error(record4.message, { cause: error });
23874
+ const code = typeof record4.code === "string" && /^\d{3}$/.test(record4.code) ? Number(record4.code) : record4.code;
23654
23875
  if (typeof code === "number" && Number.isInteger(code) && code >= 400 && code <= 599) {
23655
23876
  return Object.assign(normalized, { name: "AI_APICallError", statusCode: code });
23656
23877
  }
@@ -24142,22 +24363,28 @@ function getChatV2ModelInfo(provider, modelId) {
24142
24363
  const providerModels = chatV2ModelRegistry[provider];
24143
24364
  return providerModels[modelId];
24144
24365
  }
24366
+ function getChatV2SystemTokenPricing(provider, modelId) {
24367
+ var _a;
24368
+ const cost = (_a = getChatV2ModelInfo(provider, modelId.trim())) == null ? void 0 : _a.cost;
24369
+ return cost == null ? void 0 : { inputPerMillionTokens: cost.prompt * 1e6, outputPerMillionTokens: cost.completion * 1e6 };
24370
+ }
24145
24371
  function calculateChatV2Cost(provider, modelId, promptTokens, completionTokens) {
24146
24372
  const model = getChatV2ModelInfo(provider, modelId);
24147
- if ((model == null ? void 0 : model.cost) == null || !isFiniteNonNegative(promptTokens) || !isFiniteNonNegative(completionTokens)) {
24373
+ if ((model == null ? void 0 : model.cost) == null || !isReportedTokenCount(promptTokens) || !isReportedTokenCount(completionTokens)) {
24148
24374
  return void 0;
24149
24375
  }
24150
24376
  const cost = model.cost.prompt * promptTokens + model.cost.completion * completionTokens;
24151
24377
  return isFiniteNonNegative(cost) ? cost : void 0;
24152
24378
  }
24153
- function calculateChatV2UsageCost(provider, modelId, usage, providerMetadata) {
24379
+ function calculateChatV2UsageCost(provider, modelId, usage, providerMetadata, tokenPricing) {
24154
24380
  var _a;
24381
+ if (tokenPricing !== void 0) return calculateTokenUsageCost(tokenPricing, usage);
24155
24382
  if (provider === "openrouter") {
24156
24383
  const reportedUsage = (_a = providerMetadata == null ? void 0 : providerMetadata.openrouter) == null ? void 0 : _a.usage;
24157
24384
  const cost = reportedUsage != null && typeof reportedUsage === "object" ? reportedUsage.cost : void 0;
24158
24385
  return isFiniteNonNegative(cost) ? cost : void 0;
24159
24386
  }
24160
- if (!isFiniteNonNegative(usage == null ? void 0 : usage.inputTokens) || !isFiniteNonNegative(usage.outputTokens)) {
24387
+ if ((usage == null ? void 0 : usage.inputTokens) == null || usage.outputTokens == null) {
24161
24388
  return void 0;
24162
24389
  }
24163
24390
  return calculateChatV2Cost(provider, modelId, usage.inputTokens, usage.outputTokens);
@@ -25214,6 +25441,7 @@ async function getLLMChatV2Editors(data, context) {
25214
25441
  },
25215
25442
  ...!usesProfile ? [
25216
25443
  getModelEditors(await getResolvedModelOptions(data, context)),
25444
+ getTokenPricingEditor(),
25217
25445
  ...getProviderEditors(),
25218
25446
  getParameterEditors(),
25219
25447
  ...data.provider === "custom" ? [] : [getReasoningEditors()]
@@ -25229,6 +25457,7 @@ async function getLLMProfileEditors(data, context) {
25229
25457
  const profileData = data;
25230
25458
  return [
25231
25459
  getModelEditors(await getResolvedModelOptions(profileData, context)),
25460
+ getTokenPricingEditor(),
25232
25461
  ...getProviderEditors(),
25233
25462
  getParameterEditors(),
25234
25463
  ...profileData.provider === "custom" ? [] : [getReasoningEditors()],
@@ -26345,11 +26574,17 @@ function notifyChatV2CallFinished(options2, params) {
26345
26574
  const calculatedCost = safelyRead(
26346
26575
  () => {
26347
26576
  var _a2;
26348
- return calculateChatV2UsageCost(options2.provider, options2.modelId, rawUsage, (_a2 = params.result) == null ? void 0 : _a2.providerMetadata);
26577
+ return calculateChatV2UsageCost(
26578
+ options2.provider,
26579
+ options2.modelId,
26580
+ resultUsage ?? errorUsage,
26581
+ (_a2 = params.result) == null ? void 0 : _a2.providerMetadata,
26582
+ options2.tokenPricing
26583
+ );
26349
26584
  }
26350
26585
  );
26351
26586
  const costUsd = toUsageNumber(calculatedCost);
26352
- const hasKnownPricing = (modelInfo == null ? void 0 : modelInfo.cost) != null || options2.provider === "openrouter" && costUsd != null;
26587
+ const hasKnownPricing = options2.tokenPricing != null || (modelInfo == null ? void 0 : modelInfo.cost) != null || options2.provider === "openrouter" && costUsd != null;
26353
26588
  const finishReason = safelyRead(() => {
26354
26589
  var _a2;
26355
26590
  return (_a2 = params.result) == null ? void 0 : _a2.finishReason;
@@ -26665,9 +26900,9 @@ function isRecord8(value) {
26665
26900
  return false;
26666
26901
  }
26667
26902
  }
26668
- function getRecordProperty(record3, key) {
26903
+ function getRecordProperty(record4, key) {
26669
26904
  try {
26670
- return record3[key];
26905
+ return record4[key];
26671
26906
  } catch {
26672
26907
  return void 0;
26673
26908
  }
@@ -26793,8 +27028,8 @@ function coerceHttpStatusCode(value) {
26793
27028
  }
26794
27029
  return void 0;
26795
27030
  }
26796
- function getRecordStatusCode(record3) {
26797
- return coerceHttpStatusCode(getRecordProperty(record3, "statusCode")) ?? coerceHttpStatusCode(getRecordProperty(record3, "status"));
27031
+ function getRecordStatusCode(record4) {
27032
+ return coerceHttpStatusCode(getRecordProperty(record4, "statusCode")) ?? coerceHttpStatusCode(getRecordProperty(record4, "status"));
26798
27033
  }
26799
27034
  function getChatV2ProviderErrorStatusCode(error, seen = /* @__PURE__ */ new Set()) {
26800
27035
  if (!isRecord8(error)) {
@@ -27018,7 +27253,13 @@ function normalizeChatV2Usage(usage, options2, providerMetadata) {
27018
27253
  totalTokens,
27019
27254
  cachedTokens,
27020
27255
  reasoningTokens,
27021
- totalCost: calculateChatV2UsageCost(options2.provider, options2.modelId, usage, providerMetadata)
27256
+ totalCost: calculateChatV2UsageCost(
27257
+ options2.provider,
27258
+ options2.modelId,
27259
+ usage,
27260
+ providerMetadata,
27261
+ options2.tokenPricing
27262
+ )
27022
27263
  };
27023
27264
  }
27024
27265
  function createChatV2ResponseOutput2(response, structuredOutput, responseFormat) {
@@ -27172,6 +27413,7 @@ async function runChatV2WithRetry(options2, chatOptions, retryPlan, signal, tran
27172
27413
  const callId = createObservedChatV2CallId(options2);
27173
27414
  const callStartedAt = Date.now();
27174
27415
  let callWasObserved = false;
27416
+ let completedResponse;
27175
27417
  let acceptsResponseEvidence = true;
27176
27418
  const retireResponseEvidence = () => {
27177
27419
  acceptsResponseEvidence = false;
@@ -27212,6 +27454,7 @@ async function runChatV2WithRetry(options2, chatOptions, retryPlan, signal, tran
27212
27454
  onResponseReceived: reportResponseEvidence
27213
27455
  };
27214
27456
  const result = transportMode === "generate" ? await generateChatV2(attemptChatOptions) : await streamChatV2(attemptChatOptions);
27457
+ completedResponse = result;
27215
27458
  signal.throwIfAborted();
27216
27459
  await ((_a = options2.responseBodyCapture) == null ? void 0 : _a.flush());
27217
27460
  signal.throwIfAborted();
@@ -27253,6 +27496,7 @@ async function runChatV2WithRetry(options2, chatOptions, retryPlan, signal, tran
27253
27496
  callId,
27254
27497
  attemptIndex: attempt,
27255
27498
  outcome: signal.aborted ? "aborted" : "provider-failure",
27499
+ result: completedResponse,
27256
27500
  error,
27257
27501
  startedAt: callStartedAt,
27258
27502
  durationMs: Math.max(0, Date.now() - callStartedAt)
@@ -27602,7 +27846,7 @@ async function runChatV2PipelineWithToolContinuation(options2) {
27602
27846
  assistantMessage: result.response
27603
27847
  });
27604
27848
  delegatedToolCalls.push(
27605
- ...toolResultMessages.map((message2) => message2.delegatedToolCall).filter((record3) => record3 != null)
27849
+ ...toolResultMessages.map((message2) => message2.delegatedToolCall).filter((record4) => record4 != null)
27606
27850
  );
27607
27851
  if (decision.kind === "direct-tool-response") {
27608
27852
  const directResultMessage = (_a = toolResultMessages[0]) == null ? void 0 : _a.value;
@@ -28425,12 +28669,12 @@ function restoreOpenAICompatibleInstructionRoles(body, roles) {
28425
28669
  if (body == null || typeof body !== "object" || Array.isArray(body)) {
28426
28670
  throw new Error("Could not preserve developer messages: provider request body is not a JSON object.");
28427
28671
  }
28428
- const record3 = body;
28429
- const listKey = Array.isArray(record3.messages) ? "messages" : Array.isArray(record3.input) ? "input" : void 0;
28672
+ const record4 = body;
28673
+ const listKey = Array.isArray(record4.messages) ? "messages" : Array.isArray(record4.input) ? "input" : void 0;
28430
28674
  if (listKey == null) {
28431
28675
  throw new Error("Could not preserve developer messages: provider request body has no messages or input array.");
28432
28676
  }
28433
- const items = record3[listKey];
28677
+ const items = record4[listKey];
28434
28678
  const instructionIndexes = items.flatMap(
28435
28679
  (item, index) => item != null && typeof item === "object" && !Array.isArray(item) && (item.role === "system" || item.role === "developer") ? [index] : []
28436
28680
  );
@@ -28447,7 +28691,7 @@ function restoreOpenAICompatibleInstructionRoles(body, roles) {
28447
28691
  };
28448
28692
  });
28449
28693
  return {
28450
- ...record3,
28694
+ ...record4,
28451
28695
  [listKey]: rewrittenItems
28452
28696
  };
28453
28697
  }
@@ -28901,6 +29145,7 @@ async function resolveLLMModelCandidate(params) {
28901
29145
  var _a;
28902
29146
  const { plan, profile } = params;
28903
29147
  const effectiveData = profile ? applyLLMProfileToNodeData(plan.data, profile) : plan.data;
29148
+ const tokenPricing = validateTokenPricing(effectiveData.tokenPricing);
28904
29149
  if (hasLLMChatV2ToolResponseFormatConflict(effectiveData)) {
28905
29150
  throw new Error(LLM_CHAT_V2_TOOL_RESPONSE_FORMAT_CONFLICT_COPY.paragraphs[0]);
28906
29151
  }
@@ -28952,6 +29197,7 @@ async function resolveLLMModelCandidate(params) {
28952
29197
  requestBodyOverlay,
28953
29198
  runOptions: {
28954
29199
  ...baseRunOptions,
29200
+ tokenPricing,
28955
29201
  provider,
28956
29202
  model: resolvedProvider.model,
28957
29203
  modelId,
@@ -29964,7 +30210,7 @@ function resolveLLMProfileNodeValue(params) {
29964
30210
  return {
29965
30211
  version: LLM_PROFILE_VALUE_VERSION,
29966
30212
  credential,
29967
- configuration,
30213
+ configuration: { ...configuration, tokenPricing: validateTokenPricing(configuration.tokenPricing) },
29968
30214
  ...profileName === "" ? {} : { profileName },
29969
30215
  ...projectId == null ? {} : {
29970
30216
  healthIdentity: createRivetLLMProfileHealthIdentity({
@@ -43870,7 +44116,7 @@ function classifierPreparationCheck(signal, deadline, timeoutMs) {
43870
44116
  signal.throwIfAborted();
43871
44117
  if (Date.now() >= deadline)
43872
44118
  throw new Error(
43873
- `Classifier preparation/request timed out${timeoutMs === void 0 ? "" : ` after ${timeoutMs} ms`}.`
44119
+ `Decision AI preparation/request timed out${timeoutMs === void 0 ? "" : ` after ${timeoutMs} ms`}.`
43874
44120
  );
43875
44121
  };
43876
44122
  }
@@ -43883,7 +44129,7 @@ var ClassifierValueBudget = class {
43883
44129
  }, maxBytes = CLASSIFIER_LIMITS.requestBytes) {
43884
44130
  this.check = check;
43885
44131
  if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0)
43886
- throw new ClassifierResourceLimitError("Classifier byte limit must be a positive safe integer.");
44132
+ throw new ClassifierResourceLimitError("Decision AI byte limit must be a positive safe integer.");
43887
44133
  this.maxBytes = Math.min(maxBytes, CLASSIFIER_LIMITS.requestBytes);
43888
44134
  }
43889
44135
  bytes = 0;
@@ -43898,7 +44144,7 @@ var ClassifierValueBudget = class {
43898
44144
  const maxBytes = this.maxBytes;
43899
44145
  const size = maxBytes >= 1e6 ? maxBytes % (1024 * 1024) === 0 ? `${maxBytes / (1024 * 1024)} MiB` : `${maxBytes / 1e6} MB` : `${maxBytes}-byte`;
43900
44146
  throw new ClassifierResourceLimitError(
43901
- `Classifier input exceeds the ${size} resource limit. Reduce input content or image size.`
44147
+ `Decision AI input exceeds the ${size} resource limit. Reduce input content or image size.`
43902
44148
  );
43903
44149
  }
43904
44150
  }
@@ -43923,9 +44169,9 @@ var ClassifierValueBudget = class {
43923
44169
  value(depth) {
43924
44170
  this.check();
43925
44171
  if (++this.values > CLASSIFIER_LIMITS.values)
43926
- throw new ClassifierResourceLimitError("Classifier input has too many expanded values.");
44172
+ throw new ClassifierResourceLimitError("Decision AI input has too many expanded values.");
43927
44173
  if (depth > CLASSIFIER_LIMITS.depth)
43928
- throw new ClassifierResourceLimitError("Classifier input exceeds the maximum nesting depth of 64.");
44174
+ throw new ClassifierResourceLimitError("Decision AI input exceeds the maximum nesting depth of 64.");
43929
44175
  }
43930
44176
  inspect(value, json) {
43931
44177
  const startBytes = this.bytes;
@@ -43955,13 +44201,13 @@ var ClassifierValueBudget = class {
43955
44201
  if (hook && (!("value" in hook) || typeof hook.value === "function"))
43956
44202
  throw new Error(`${json.label} must not contain JSON serialization hooks.`);
43957
44203
  }
43958
- if (path.has(item)) throw new Error("Classifier input contains a circular reference.");
44204
+ if (path.has(item)) throw new Error("Decision AI input contains a circular reference.");
43959
44205
  path.add(item);
43960
44206
  this.add(2);
43961
44207
  const copy = (json == null ? void 0 : json.copy) ? Array.isArray(item) ? [] : {} : void 0;
43962
44208
  if (Array.isArray(item)) {
43963
44209
  if (item.length > CLASSIFIER_LIMITS.values)
43964
- throw new ClassifierResourceLimitError("Classifier input has too many expanded values.");
44210
+ throw new ClassifierResourceLimitError("Decision AI input has too many expanded values.");
43965
44211
  for (let i = 0; i < item.length; i++) {
43966
44212
  if (i > 0) this.add(1);
43967
44213
  const descriptor = Object.getOwnPropertyDescriptor(item, String(i));
@@ -43976,7 +44222,7 @@ var ClassifierValueBudget = class {
43976
44222
  } else {
43977
44223
  const keys2 = Object.keys(item);
43978
44224
  if (keys2.length > CLASSIFIER_LIMITS.values)
43979
- throw new ClassifierResourceLimitError("Classifier input has too many expanded values.");
44225
+ throw new ClassifierResourceLimitError("Decision AI input has too many expanded values.");
43980
44226
  let index = 0;
43981
44227
  for (const key of keys2) {
43982
44228
  this.string(key);
@@ -44022,18 +44268,18 @@ function checkClassifierJsonWork(text2, check, label = "response") {
44022
44268
  } else if (character === '"') quoted = true;
44023
44269
  else if (character === "{" || character === "[") {
44024
44270
  if (++depth > CLASSIFIER_LIMITS.depth)
44025
- throw new ClassifierResourceLimitError(`Classifier ${label} exceeds the maximum nesting depth of 64.`);
44271
+ throw new ClassifierResourceLimitError(`Decision AI ${label} exceeds the maximum nesting depth of 64.`);
44026
44272
  separators++;
44027
44273
  } else if (character === "}" || character === "]") depth--;
44028
44274
  else if (character === "," || character === ":") separators++;
44029
44275
  if (separators > CLASSIFIER_LIMITS.values * 2)
44030
- throw new ClassifierResourceLimitError(`Classifier ${label} has too many values.`);
44276
+ throw new ClassifierResourceLimitError(`Decision AI ${label} has too many values.`);
44031
44277
  }
44032
44278
  }
44033
44279
  async function readClassifierResponse(response, signal, check = () => signal.throwIfAborted(), onBody) {
44034
44280
  const length = response.headers.get("content-length");
44035
44281
  if (length && Number(length) > CLASSIFIER_LIMITS.responseBytes)
44036
- throw new ClassifierResourceLimitError("Classifier response exceeds the 8 MiB response limit.");
44282
+ throw new ClassifierResourceLimitError("Decision AI response exceeds the 8 MiB response limit.");
44037
44283
  if (!response.body) return JSON.parse("");
44038
44284
  const reader = response.body.getReader();
44039
44285
  const cancel = () => {
@@ -44049,14 +44295,14 @@ async function readClassifierResponse(response, signal, check = () => signal.thr
44049
44295
  for (; ; ) {
44050
44296
  check();
44051
44297
  const { done, value } = await reader.read().catch((cause) => {
44052
- throw new ClassifierResponseReadError("Classifier response body could not be read.", { cause });
44298
+ throw new ClassifierResponseReadError("Decision AI response body could not be read.", { cause });
44053
44299
  });
44054
44300
  check();
44055
44301
  if (done) break;
44056
44302
  const chunk = classifierByteView(value);
44057
44303
  bytes += chunk.byteLength;
44058
44304
  if (bytes > CLASSIFIER_LIMITS.responseBytes)
44059
- throw new ClassifierResourceLimitError("Classifier response exceeds the 8 MiB response limit.");
44305
+ throw new ClassifierResourceLimitError("Decision AI response exceeds the 8 MiB response limit.");
44060
44306
  pending += decoder.decode(chunk, { stream: true });
44061
44307
  if (pending.length >= 64 * 1024) {
44062
44308
  text2.push(pending);
@@ -44110,7 +44356,7 @@ var ClassifierQuestionPreparation = class {
44110
44356
  check = () => {
44111
44357
  this.deadlineCheck();
44112
44358
  if (++this.operations > CLASSIFIER_LIMITS.values * 10)
44113
- throw new ClassifierResourceLimitError("Classifier question preparation has too much expanded work.");
44359
+ throw new ClassifierResourceLimitError("Decision AI question preparation has too much expanded work.");
44114
44360
  };
44115
44361
  capture(value) {
44116
44362
  this.inspect(value, false);
@@ -44130,7 +44376,7 @@ var ClassifierQuestionPreparation = class {
44130
44376
  output = (fragment, previousLength) => {
44131
44377
  this.check();
44132
44378
  if (fragment.length + previousLength > this.budget.remainingBytes)
44133
- throw new ClassifierResourceLimitError("Classifier question interpolation exceeds its remaining byte budget.");
44379
+ throw new ClassifierResourceLimitError("Decision AI question interpolation exceeds its remaining byte budget.");
44134
44380
  };
44135
44381
  processing = (input, name, parameter) => {
44136
44382
  this.check();
@@ -44142,7 +44388,7 @@ var ClassifierQuestionPreparation = class {
44142
44388
  const nextWhitespace = /\s/.test(input[i]);
44143
44389
  if (name === "chain" && input[i] === "|" || (name === "chain" || name === "wrap") && nextWhitespace && !whitespace || name !== "chain" && name !== "wrap" && input[i] === "\n") {
44144
44390
  if (++pieces > CLASSIFIER_LIMITS.values)
44145
- throw new ClassifierResourceLimitError("Classifier interpolation processor has too many expanded pieces.");
44391
+ throw new ClassifierResourceLimitError("Decision AI interpolation processor has too many expanded pieces.");
44146
44392
  }
44147
44393
  whitespace = nextWhitespace;
44148
44394
  }
@@ -44151,14 +44397,14 @@ var ClassifierQuestionPreparation = class {
44151
44397
  const value = parameter ?? (name === "indent" ? 0 : 1);
44152
44398
  const prefix = name === "indent" ? value : name === "quote" ? value * 2 : (value - 1) * 2 + 2;
44153
44399
  if (!Number.isSafeInteger(value) || value < (name === "list" ? 1 : 0))
44154
- throw new Error(`Invalid classifier interpolation ${name} parameter.`);
44400
+ throw new Error(`Invalid Decision AI interpolation ${name} parameter.`);
44155
44401
  let lines = 1;
44156
44402
  for (let i = 0; i < input.length; i++) {
44157
44403
  if ((i & 4095) === 0) this.check();
44158
44404
  if (input[i] === "\n") lines++;
44159
44405
  }
44160
44406
  if (input.length + lines * prefix > this.budget.remainingBytes)
44161
- throw new ClassifierResourceLimitError("Classifier interpolation processor exceeds its remaining byte budget.");
44407
+ throw new ClassifierResourceLimitError("Decision AI interpolation processor exceeds its remaining byte budget.");
44162
44408
  };
44163
44409
  };
44164
44410
 
@@ -44170,7 +44416,7 @@ function classifierDataProperty(value, key, label = "State") {
44170
44416
  return property == null ? void 0 : property.value;
44171
44417
  }
44172
44418
  function classifierInputDataValue(inputs, port) {
44173
- const label = `Classifier ${port} input`;
44419
+ const label = `Decision AI ${port} input`;
44174
44420
  const input = classifierDataProperty(inputs, port, label);
44175
44421
  if (input === void 0) return void 0;
44176
44422
  if (input === null || typeof input !== "object" || Array.isArray(input))
@@ -44211,18 +44457,333 @@ function assertClassifierInstructions(value, label = "Instructions") {
44211
44457
  assertClassifierInstructionsKind(value, label);
44212
44458
  }
44213
44459
 
44460
+ // src/model/classifier/images.ts
44461
+ var InvalidClassifierImageError = class extends Error {
44462
+ };
44463
+ var invalidImage = () => new InvalidClassifierImageError(
44464
+ "State images must contain inline base64 PNG, JPEG, GIF or WebP image data with valid headers and matching media type."
44465
+ );
44466
+ function isBase64(value) {
44467
+ return value.length > 0 && value.length % 4 === 0 && /^[A-Za-z0-9+/]+={0,2}$/.test(value);
44468
+ }
44469
+ function jpegInfo(size, read, check) {
44470
+ const byte = (offset2) => read(offset2, 1)[0];
44471
+ const uint16 = (offset2) => {
44472
+ const bytes = read(offset2, 2);
44473
+ return (bytes[0] << 8) + bytes[1];
44474
+ };
44475
+ let offset = 2;
44476
+ while (offset + 4 <= size) {
44477
+ check == null ? void 0 : check();
44478
+ if (byte(offset++) !== 255) break;
44479
+ while (byte(offset) === 255) {
44480
+ if ((offset & 4095) === 0) check == null ? void 0 : check();
44481
+ offset++;
44482
+ }
44483
+ const marker2 = byte(offset++);
44484
+ if (marker2 === void 0 || marker2 === 218 || marker2 === 217) break;
44485
+ if (marker2 === 1 || marker2 >= 208 && marker2 <= 215) continue;
44486
+ if (offset + 2 > size) break;
44487
+ const length = uint16(offset);
44488
+ if (length < 2 || offset + length > size) break;
44489
+ if ([192, 193, 194, 195, 197, 198, 199, 201, 202, 203, 205, 206, 207].includes(marker2) && length >= 8)
44490
+ return { mediaType: "image/jpeg", width: uint16(offset + 5), height: uint16(offset + 3) };
44491
+ offset += length;
44492
+ }
44493
+ return void 0;
44494
+ }
44495
+ function imageInfo(bytes, check) {
44496
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
44497
+ const ascii = (offset, length) => String.fromCharCode(...bytes.subarray(offset, offset + length));
44498
+ let info;
44499
+ if (bytes.length >= 33 && ascii(0, 8) === "\x89PNG\r\n\n" && view.getUint32(8) === 13 && ascii(12, 4) === "IHDR") {
44500
+ info = { mediaType: "image/png", width: view.getUint32(16), height: view.getUint32(20) };
44501
+ } else if (bytes.length >= 13 && ["GIF87a", "GIF89a"].includes(ascii(0, 6))) {
44502
+ info = { mediaType: "image/gif", width: view.getUint16(6, true), height: view.getUint16(8, true) };
44503
+ } else if (bytes.length >= 25 && ascii(0, 4) === "RIFF" && ascii(8, 4) === "WEBP") {
44504
+ const chunk = ascii(12, 4);
44505
+ const uint24 = (offset) => bytes[offset] + (bytes[offset + 1] << 8) + (bytes[offset + 2] << 16);
44506
+ if (chunk === "VP8X" && bytes.length >= 30)
44507
+ info = { mediaType: "image/webp", width: uint24(24) + 1, height: uint24(27) + 1 };
44508
+ else if (chunk === "VP8 " && bytes.length >= 30 && ascii(23, 3) === "\x9D*")
44509
+ info = {
44510
+ mediaType: "image/webp",
44511
+ width: view.getUint16(26, true) & 16383,
44512
+ height: view.getUint16(28, true) & 16383
44513
+ };
44514
+ else if (chunk === "VP8L" && bytes[20] === 47) {
44515
+ const bits = view.getUint32(21, true);
44516
+ info = { mediaType: "image/webp", width: (bits & 16383) + 1, height: (bits >>> 14 & 16383) + 1 };
44517
+ }
44518
+ } else if (bytes.length >= 4 && bytes[0] === 255 && bytes[1] === 216) {
44519
+ info = jpegInfo(bytes.length, (offset, length) => bytes.subarray(offset, offset + length), check);
44520
+ }
44521
+ if (!info || info.width === 0 || info.height === 0) throw invalidImage();
44522
+ return info;
44523
+ }
44524
+ function base64ImageInfo(payload, check) {
44525
+ if (payload.startsWith("/9j/")) {
44526
+ const size = payload.length / 4 * 3 - (payload.endsWith("==") ? 2 : payload.endsWith("=") ? 1 : 0);
44527
+ let start = -1;
44528
+ let window = new Uint8Array();
44529
+ const info = jpegInfo(
44530
+ size,
44531
+ (offset, length) => {
44532
+ if (offset < start || offset + length > start + window.length) {
44533
+ start = Math.floor(offset / 3) * 3;
44534
+ window = base64ToUint8Array(payload.slice(start / 3 * 4, start / 3 * 4 + 4096));
44535
+ }
44536
+ return window.subarray(offset - start, offset - start + length);
44537
+ },
44538
+ check
44539
+ );
44540
+ if (!info || info.width === 0 || info.height === 0) throw invalidImage();
44541
+ return info;
44542
+ }
44543
+ return imageInfo(base64ToUint8Array(payload.slice(0, 48)));
44544
+ }
44545
+ function prepareNativeClassifierImage(value, check) {
44546
+ if (!value || typeof value !== "object") throw invalidImage();
44547
+ const data = classifierDataProperty(value, "data");
44548
+ const mediaType = classifierDataProperty(value, "mediaType");
44549
+ if (!(data instanceof Uint8Array)) throw invalidImage();
44550
+ const bytes = classifierByteView(data);
44551
+ assertClassifierResourceLimits(bytes, check);
44552
+ const info = imageInfo(bytes, check);
44553
+ if (info.mediaType !== mediaType) throw invalidImage();
44554
+ check == null ? void 0 : check();
44555
+ return { ...info, dataUrl: `data:${info.mediaType};base64,${uint8ArrayToBase64Sync(bytes)}` };
44556
+ }
44557
+ function inspectClassifierImage(value, check) {
44558
+ check == null ? void 0 : check();
44559
+ if (typeof value !== "string") throw invalidImage();
44560
+ const prefix = /^data:(image\/(?:png|jpeg|gif|webp));base64,/.exec(value);
44561
+ if (!prefix) throw invalidImage();
44562
+ const payload = value.slice(prefix[0].length);
44563
+ if (!isBase64(payload)) throw invalidImage();
44564
+ const info = base64ImageInfo(payload, check);
44565
+ if (info.mediaType !== prefix[1]) throw invalidImage();
44566
+ return info;
44567
+ }
44568
+ function prepareClassifierImageText(value, check) {
44569
+ check == null ? void 0 : check();
44570
+ if (value.length > CLASSIFIER_LIMITS.requestBytes)
44571
+ throw new Error("Decision AI image/text exceeds the 32 MiB input limit.");
44572
+ if (value.startsWith("data:image/")) {
44573
+ return { ...inspectClassifierImage(value, check), dataUrl: value };
44574
+ }
44575
+ if (!/^(?:iVBOR|\/9j\/|R0lGOD|UklGR)/.test(value) || !isBase64(value)) return void 0;
44576
+ try {
44577
+ const info = base64ImageInfo(value, check);
44578
+ return { ...info, dataUrl: `data:${info.mediaType};base64,${value}` };
44579
+ } catch (error) {
44580
+ if (error instanceof InvalidClassifierImageError) return void 0;
44581
+ throw error;
44582
+ }
44583
+ }
44584
+ function assertLiquidImageLimits(images, check) {
44585
+ if (images.length > 8) throw new Error("Liquid Decision AI State must contain at most 8 images.");
44586
+ let patches = 0;
44587
+ for (const { width, height } of images) {
44588
+ check == null ? void 0 : check();
44589
+ if (Math.max(width, height) / Math.min(width, height) > 100)
44590
+ throw new Error("Liquid Decision AI images must have an aspect ratio at most 100:1.");
44591
+ patches += Math.ceil(width / 32) * Math.ceil(height / 32);
44592
+ }
44593
+ if (patches > 1e4)
44594
+ throw new Error("Liquid Decision AI images must contain at most 10,000 patches of 32 by 32 pixels in total.");
44595
+ }
44596
+
44597
+ // src/model/classifier/state.ts
44598
+ var record = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
44599
+ var nativeImage = (value) => record(value) && (classifierDataProperty(value, "type") === "image" || "mediaType" in value && classifierDataProperty(value, "data") instanceof Uint8Array);
44600
+ var message = (value) => record(value) && "type" in value && "message" in value;
44601
+ function prepareClassifierState(input, budget) {
44602
+ if (input.stateInput !== void 0) {
44603
+ if (input.state !== "" || input.stateMessages !== void 0)
44604
+ throw new Error("Rivet State input and provider State cannot be supplied together.");
44605
+ return prepareRivetState(input.stateInput, budget);
44606
+ }
44607
+ if (input.stateMessages === void 0) {
44608
+ if (typeof input.state !== "string" && !record(input.state) && !Array.isArray(input.state))
44609
+ throw new Error("State must be text, a JSON object or an array.");
44610
+ return { kind: "json", value: snapshotClassifierJson(input.state, "State", budget) };
44611
+ }
44612
+ if (input.state !== "")
44613
+ throw new Error("Structured State and multimodal State messages cannot be supplied together.");
44614
+ const messages = snapshotClassifierJson(input.stateMessages, "State", budget);
44615
+ const images = inspectStateMessages(messages, budget.check);
44616
+ return { kind: "messages", messages, images };
44617
+ }
44618
+ function normalizeClassifierState(input, check, maxBytes) {
44619
+ const state = input === void 0 ? { kind: "json", value: "" } : prepareRivetState(input, new ClassifierValueBudget(check, maxBytes));
44620
+ return state.kind === "json" ? { state: state.value } : { state: "", stateMessages: state.messages };
44621
+ }
44622
+ function prepareRivetState(input, budget) {
44623
+ const check = budget.check;
44624
+ if (input === null || typeof input !== "object" || Array.isArray(input))
44625
+ throw new Error("State input must contain a Rivet data value.");
44626
+ const type = classifierDataProperty(input, "type");
44627
+ const value = classifierDataProperty(input, "value");
44628
+ if (typeof type !== "string") throw new Error("State input type must be a string.");
44629
+ if (![
44630
+ "string",
44631
+ "string[]",
44632
+ "image",
44633
+ "image[]",
44634
+ "chat-message",
44635
+ "chat-message[]",
44636
+ "object",
44637
+ "object[]",
44638
+ "any",
44639
+ "any[]"
44640
+ ].includes(type))
44641
+ throw new Error(`Unsupported State input type '${type}'.`);
44642
+ if (type.endsWith("[]") && !Array.isArray(value)) throw new Error("State array input must contain an array.");
44643
+ if (type === "string" && typeof value !== "string") throw new Error("State string input must contain a string.");
44644
+ if (type === "object" && !record(value) && !Array.isArray(value))
44645
+ throw new Error("State object input must contain a JSON object or array.");
44646
+ if ((type === "image" || type === "chat-message") && Array.isArray(value))
44647
+ throw new Error("State scalar input must not contain an array.");
44648
+ if (type === "object" || type === "object[]")
44649
+ return { kind: "json", value: snapshotClassifierJson(value, "State", budget) };
44650
+ budget.inspect(value);
44651
+ const imageTexts = /* @__PURE__ */ new Map();
44652
+ const textImage = (text2) => {
44653
+ const image = imageTexts.get(text2) ?? prepareClassifierImageText(text2, check);
44654
+ if (image) imageTexts.set(text2, image);
44655
+ return image;
44656
+ };
44657
+ const hasContent = (item) => nativeImage(item) || message(item) || typeof item === "string" && textImage(item) !== void 0;
44658
+ const arrayHasContent = () => {
44659
+ for (const item of classifierArrayValues(value, "State")) {
44660
+ check();
44661
+ if (hasContent(item)) return true;
44662
+ }
44663
+ return false;
44664
+ };
44665
+ const contentType = ["image", "image[]", "string[]", "chat-message", "chat-message[]"].includes(type);
44666
+ const inferredContent = (type === "any" || type === "any[]") && (hasContent(value) || Array.isArray(value) && arrayHasContent());
44667
+ if (!(contentType || inferredContent || type === "string" && textImage(value))) {
44668
+ if (typeof value !== "string" && !record(value) && !Array.isArray(value))
44669
+ throw new Error("State must be text, a JSON object/array, images, or user messages.");
44670
+ return {
44671
+ kind: "json",
44672
+ value: typeof value === "string" ? value : snapshotClassifierJson(value, "State", new ClassifierValueBudget(check))
44673
+ };
44674
+ }
44675
+ const values2 = Array.isArray(value) ? value : [value];
44676
+ if (type === "image[]" && values2.length > 128) throw new Error("State must contain at most 128 images.");
44677
+ const messages = [];
44678
+ const images = [];
44679
+ let partCount = 0;
44680
+ const imagePart = (prepare) => {
44681
+ if (images.length >= 128) throw new Error("State must contain at most 128 images.");
44682
+ const image = prepare();
44683
+ images.push(image);
44684
+ return { type: "image", dataUrl: image.dataUrl };
44685
+ };
44686
+ let parts = [];
44687
+ const flush = () => {
44688
+ if (parts.length) {
44689
+ if (messages.length >= CLASSIFIER_LIMITS.messages) throw new Error("State has too many messages.");
44690
+ messages.push({ parts });
44691
+ parts = [];
44692
+ }
44693
+ };
44694
+ const part = (item) => {
44695
+ check();
44696
+ if (++partCount > CLASSIFIER_LIMITS.parts) throw new Error("State has too many content parts.");
44697
+ if (typeof item === "string") {
44698
+ const image = textImage(item);
44699
+ return image ? imagePart(() => image) : { type: "text", text: item };
44700
+ }
44701
+ if (nativeImage(item)) return imagePart(() => prepareNativeClassifierImage(item, check));
44702
+ throw new Error("Multimodal State accepts only text, native images, image data URLs, and user messages.");
44703
+ };
44704
+ for (const item of classifierArrayValues(values2, "State")) {
44705
+ check();
44706
+ if (type === "image" || type === "image[]") {
44707
+ if (++partCount > CLASSIFIER_LIMITS.parts) throw new Error("State has too many content parts.");
44708
+ parts.push(imagePart(() => prepareNativeClassifierImage(item, check)));
44709
+ } else if (type === "string[]" && typeof item !== "string") {
44710
+ throw new Error("State string array must contain only strings.");
44711
+ } else if (message(item)) {
44712
+ if (classifierDataProperty(item, "type") !== "user" || "function_call" in item || "function_calls" in item)
44713
+ throw new Error(
44714
+ "Decision AI State supports only user messages, not system, developer, assistant, or tool messages."
44715
+ );
44716
+ flush();
44717
+ if (messages.length >= CLASSIFIER_LIMITS.messages) throw new Error("State has too many messages.");
44718
+ const contentValue = classifierDataProperty(item, "message");
44719
+ const content = Array.isArray(contentValue) ? contentValue : [contentValue];
44720
+ messages.push({
44721
+ parts: content.length ? Array.from(classifierArrayValues(content, "State"), part) : [{ type: "text", text: "" }]
44722
+ });
44723
+ } else {
44724
+ if (type === "chat-message" || type === "chat-message[]")
44725
+ throw new Error("State must contain valid user messages.");
44726
+ parts.push(part(item));
44727
+ }
44728
+ }
44729
+ flush();
44730
+ return messages.length ? { kind: "messages", messages, images } : { kind: "json", value: "" };
44731
+ }
44732
+ function inspectStateMessages(messages, check) {
44733
+ if (!Array.isArray(messages)) throw new Error("State messages must be an array.");
44734
+ if (messages.length > CLASSIFIER_LIMITS.messages) throw new Error("State has too many messages.");
44735
+ const images = [];
44736
+ let parts = 0;
44737
+ for (const message2 of messages) {
44738
+ if (!record(message2) || !Array.isArray(message2.parts)) throw new Error("State message parts must be an array.");
44739
+ for (const part of message2.parts) {
44740
+ check();
44741
+ if (++parts > CLASSIFIER_LIMITS.parts) throw new Error("State has too many content parts.");
44742
+ if (!record(part)) throw new Error("Invalid State content part.");
44743
+ if (part.type === "image" && typeof part.dataUrl === "string") {
44744
+ if (images.length >= 128) throw new Error("State must contain at most 128 images.");
44745
+ images.push({ ...inspectClassifierImage(part.dataUrl, check), dataUrl: part.dataUrl });
44746
+ } else if (part.type !== "text" || typeof part.text !== "string") throw new Error("Invalid State content part.");
44747
+ }
44748
+ }
44749
+ return images;
44750
+ }
44751
+ function systemOneState(input) {
44752
+ if (!input.stateMessages) return { state: input.state };
44753
+ const images = [];
44754
+ const state = input.stateMessages.map(
44755
+ ({ parts }) => parts.map((part) => {
44756
+ if (part.type === "text") return part.text;
44757
+ images.push(part.dataUrl);
44758
+ return `[Image ${images.length}]`;
44759
+ }).join("\n")
44760
+ ).join("\n\n");
44761
+ return { state, ...images.length ? { images } : {} };
44762
+ }
44763
+
44214
44764
  // src/model/classifier/questionHelpers.ts
44215
44765
  var STRUCTURED_ENTRY_TYPES = ["string", "object", "object[]", "any", "any[]"];
44216
44766
  function getInstructionsInputDefinition() {
44217
44767
  return {
44218
44768
  id: "instructions",
44219
44769
  title: "Instructions",
44220
- dataType: STRUCTURED_ENTRY_TYPES,
44770
+ dataType: [...STRUCTURED_ENTRY_TYPES, "string[]", "image", "image[]", "chat-message", "chat-message[]"],
44221
44771
  required: true,
44222
44772
  splitRunBehavior: "preserve-array",
44223
- description: "String or JSON structure describing the independent question."
44773
+ description: "Text/JSON, an image, or assembled User messages. Question images require Jev or OpenAI."
44224
44774
  };
44225
44775
  }
44776
+ function getQuestionInstructionsInput(inputs, preparation) {
44777
+ const input = classifierDataProperty(inputs, "instructions", "Instructions");
44778
+ if (!input) throw new Error("Instructions input is required.");
44779
+ const normalized = normalizeClassifierState(input, preparation.check);
44780
+ if (normalized.stateMessages && (input.type !== "string[]" || normalized.stateMessages.some(({ parts }) => parts.some((part) => part.type === "image"))))
44781
+ return { instructions: "", instructionsMessages: normalized.stateMessages };
44782
+ if (input.type === "image[]" || input.type === "chat-message[]")
44783
+ throw new Error("Instructions must not contain empty image or User-message arrays.");
44784
+ if (!normalized.stateMessages) return { instructions: normalized.state };
44785
+ return { instructions: getStructuredInput(inputs, "instructions", "Instructions") };
44786
+ }
44226
44787
  function getCriteriaInputDefinition(dataTypes2) {
44227
44788
  return {
44228
44789
  id: "criteria",
@@ -44335,6 +44896,81 @@ function abbreviate(value, maximum = 72) {
44335
44896
  return compact.length <= maximum ? compact : `${compact.slice(0, maximum - 3)}...`;
44336
44897
  }
44337
44898
 
44899
+ // src/model/classifier/questions.ts
44900
+ function createQuestionMap(questions, instructionsFor = (question) => question.instructionsMessages ? systemOneState({ state: "", stateMessages: question.instructionsMessages }).state : question.instructions) {
44901
+ const result = /* @__PURE__ */ Object.create(null);
44902
+ for (const question of questions) {
44903
+ const instructions = instructionsFor(question);
44904
+ const providerQuestion = (question.type === "noul" || question.type === "box") && question.criteria === void 0 ? { type: question.type, instructions } : { type: question.type, instructions, criteria: question.criteria };
44905
+ Object.defineProperty(result, question.questionId, { enumerable: true, value: providerQuestion });
44906
+ }
44907
+ return result;
44908
+ }
44909
+ function prepareClassifierQuestion(value, budget) {
44910
+ if (value === null || typeof value !== "object" || Array.isArray(value))
44911
+ throw new Error("Question inputs must contain question definition objects.");
44912
+ if ("images" in value)
44913
+ throw new Error(
44914
+ "Question-level images fields are not supported. Connect images to Question Instructions (Jev/OpenAI), or to Decision AI run's State input for shared evidence."
44915
+ );
44916
+ if ("instructionsMessages" in value) {
44917
+ const descriptor = Object.getOwnPropertyDescriptor(value, "instructionsMessages");
44918
+ if (!(descriptor == null ? void 0 : descriptor.enumerable) || !("value" in descriptor))
44919
+ throw new Error("Question instructionsMessages must be an own, enumerable data field.");
44920
+ }
44921
+ for (const key of ["questionId", "type", "instructions"]) {
44922
+ if (!Object.prototype.propertyIsEnumerable.call(value, key))
44923
+ throw new Error(`Every Decision AI question must have an own, enumerable '${key}' field.`);
44924
+ }
44925
+ const criteriaProperty = Object.getOwnPropertyDescriptor(value, "criteria");
44926
+ if (criteriaProperty && (!criteriaProperty.enumerable || !("value" in criteriaProperty)))
44927
+ throw new Error("Decision AI question criteria must be an own, enumerable field.");
44928
+ const question = snapshotClassifierJson(value, "Question", budget, true);
44929
+ if (typeof question.questionId !== "string" || question.questionId.trim() === "")
44930
+ throw new Error("Every Decision AI question must have a non-empty Question ID.");
44931
+ if (!["choice", "score", "noul", "box"].includes(question.type))
44932
+ throw new Error(`Question '${question.questionId}' has an unsupported type.`);
44933
+ if (question.instructionsMessages !== void 0) {
44934
+ if (question.instructions !== "")
44935
+ throw new Error("Question instructions and instructionsMessages cannot be supplied together.");
44936
+ inspectStateMessages(question.instructionsMessages, budget.check);
44937
+ if (!question.instructionsMessages.some(
44938
+ ({ parts }) => parts.some((part) => part.type === "image" || part.text.trim() !== "")
44939
+ ))
44940
+ throw new Error(`Question '${question.questionId}' instructions must not be empty.`);
44941
+ } else {
44942
+ assertClassifierInstructionsKind(question.instructions, `Question '${question.questionId}' instructions`);
44943
+ }
44944
+ const criteria = question.criteria;
44945
+ if (question.type === "box" && criteria !== void 0)
44946
+ throw new Error(`Bounding Box question '${question.questionId}' does not accept criteria.`);
44947
+ if (question.type === "choice") {
44948
+ if (typeof criteria !== "object" || criteria === null || Array.isArray(criteria))
44949
+ throw new Error(`Choice question '${question.questionId}' requires object criteria.`);
44950
+ const keys2 = Object.keys(criteria);
44951
+ if (keys2.length < 2 || keys2.length > 255)
44952
+ throw new Error(`Choice question '${question.questionId}' requires 2 to 255 options.`);
44953
+ for (const key of keys2)
44954
+ assertClassifierEntryKind(
44955
+ criteria[key],
44956
+ `Question '${question.questionId}' criteria.${key}`
44957
+ );
44958
+ } else if (question.type === "score") {
44959
+ if (!Array.isArray(criteria) || criteria.length < 2 || criteria.length > 10)
44960
+ throw new Error(`Score question '${question.questionId}' requires 2 to 10 levels.`);
44961
+ let index = 0;
44962
+ for (const entry of classifierArrayValues(criteria, "Criteria"))
44963
+ assertClassifierEntryKind(entry, `Question '${question.questionId}' criteria[${index++}]`);
44964
+ } else if (question.type === "noul" && criteria !== void 0) {
44965
+ if (typeof criteria !== "object" || criteria === null || Array.isArray(criteria) || !Object.prototype.propertyIsEnumerable.call(criteria, "true") || !Object.prototype.propertyIsEnumerable.call(criteria, "false"))
44966
+ throw new Error(`Noul question '${question.questionId}' criteria must contain true and false entries.`);
44967
+ const entries2 = criteria;
44968
+ assertClassifierEntryKind(entries2.true, `Question '${question.questionId}' criteria.true`);
44969
+ assertClassifierEntryKind(entries2.false, `Question '${question.questionId}' criteria.false`);
44970
+ }
44971
+ return question;
44972
+ }
44973
+
44338
44974
  // src/model/nodes/ClassifierQuestionNode.ts
44339
44975
  var defaultOptions = () => [
44340
44976
  { key: "", value: "" },
@@ -44357,7 +44993,7 @@ var ClassifierQuestionNodeImpl = class extends NodeImpl {
44357
44993
  static create() {
44358
44994
  return {
44359
44995
  type: "classifierQuestion",
44360
- title: "Classifier Question",
44996
+ title: "Decision AI Question",
44361
44997
  id: (0, import_non_secure109.nanoid)(),
44362
44998
  visualData: { x: 0, y: 0, width: 280 },
44363
44999
  data: {
@@ -44384,7 +45020,7 @@ var ClassifierQuestionNodeImpl = class extends NodeImpl {
44384
45020
  const data = this.data;
44385
45021
  const inputs = [];
44386
45022
  if (data.useInstructionsInput) inputs.push(getInstructionsInputDefinition());
44387
- if (data.useCriteriaInput) {
45023
+ if (data.questionType !== "box" && data.useCriteriaInput) {
44388
45024
  inputs.push(getCriteriaInputDefinition(getCriteriaInputTypes(data.questionType)));
44389
45025
  } else if (data.questionType === "noul") {
44390
45026
  const criteriaType = getCriteriaType(data);
@@ -44399,7 +45035,7 @@ var ClassifierQuestionNodeImpl = class extends NodeImpl {
44399
45035
  data.instructionsLines,
44400
45036
  data.instructionsObjectTemplate
44401
45037
  );
44402
- if (!data.useCriteriaInput) {
45038
+ if (data.questionType !== "box" && !data.useCriteriaInput) {
44403
45039
  if (data.questionType === "choice") {
44404
45040
  if (getCriteriaType(data) === "text") templates.push(...(data.options ?? []).map((option) => option.value));
44405
45041
  else {
@@ -44441,7 +45077,8 @@ var ClassifierQuestionNodeImpl = class extends NodeImpl {
44441
45077
  options: [
44442
45078
  { value: "noul", label: "Noul" },
44443
45079
  { value: "choice", label: "Choice" },
44444
- { value: "score", label: "Score" }
45080
+ { value: "score", label: "Score" },
45081
+ { value: "box", label: "Bounding Box" }
44445
45082
  ],
44446
45083
  defaultValue: "choice",
44447
45084
  allowOptionWrap: false
@@ -44501,7 +45138,7 @@ var ClassifierQuestionNodeImpl = class extends NodeImpl {
44501
45138
  type: "group",
44502
45139
  label: "Criteria",
44503
45140
  presentation: "section",
44504
- hideIf: (data) => data.questionType === "noul" && Boolean(data.useCriteriaInput),
45141
+ hideIf: (data) => data.questionType === "box" || data.questionType === "noul" && Boolean(data.useCriteriaInput),
44505
45142
  editors: [
44506
45143
  {
44507
45144
  type: "dropdown",
@@ -44632,17 +45269,17 @@ var ClassifierQuestionNodeImpl = class extends NodeImpl {
44632
45269
  }
44633
45270
  static getUIData() {
44634
45271
  return {
44635
- contextMenuTitle: "Classifier Question",
44636
- infoBoxTitle: "Classifier Question",
44637
- infoBoxBody: "Builds one typed classifier question without making a network request.",
44638
- group: ["Classifier"]
45272
+ contextMenuTitle: "Decision AI Question",
45273
+ infoBoxTitle: "Decision AI Question",
45274
+ infoBoxBody: "Builds one typed Decision AI question without making a network request.",
45275
+ group: ["Decision AI"]
44639
45276
  };
44640
45277
  }
44641
45278
  async process(inputs, context) {
44642
45279
  const preparation = new ClassifierQuestionPreparation(context);
44643
45280
  const data = this.data;
44644
45281
  preparation.capture(data.questionId);
44645
- const criteria = data.useCriteriaInput ? getQuestionInputValue(inputs, "criteria", "Criteria") : void 0;
45282
+ const criteria = data.questionType !== "box" && data.useCriteriaInput ? getQuestionInputValue(inputs, "criteria", "Criteria") : void 0;
44646
45283
  if (data.questionType === "score") {
44647
45284
  const count = data.useCriteriaInput ? Array.isArray(criteria) ? criteria.length : 0 : (data.scoreCriteria ?? data.levels ?? defaultLevels()).length;
44648
45285
  if (count < 2 || count > 10) throw new Error("Score questions require 2 to 10 levels.");
@@ -44650,23 +45287,27 @@ var ClassifierQuestionNodeImpl = class extends NodeImpl {
44650
45287
  const count = data.useCriteriaInput ? criteria && typeof criteria === "object" && !Array.isArray(criteria) ? Object.keys(criteria).length : 0 : (getCriteriaType(data) === "text" ? data.options ?? defaultOptions() : data.choiceCriteria ?? data.options ?? defaultOptions()).length;
44651
45288
  if (count < 2 || count > 255) throw new Error("Choice questions require 2 to 255 options.");
44652
45289
  }
44653
- if (data.useInstructionsInput) preparation.capture(getQuestionInputValue(inputs, "instructions", "Instructions"));
44654
45290
  const questionId = requireQuestionId(data.questionId);
44655
- const instructions = data.useInstructionsInput ? getStructuredInput(inputs, "instructions", "Instructions") : resolveAuthoredClassifierEntry({
44656
- type: data.instructionsType,
44657
- text: data.instructions,
44658
- lines: data.instructionsLines,
44659
- objectTemplate: data.instructionsObjectTemplate,
44660
- inputs,
44661
- context,
44662
- label: "Instructions",
44663
- preparation
44664
- });
44665
- assertClassifierInstructions(instructions);
45291
+ const instructionInput = data.useInstructionsInput ? getQuestionInstructionsInput(inputs, preparation) : {
45292
+ instructions: resolveAuthoredClassifierEntry({
45293
+ type: data.instructionsType,
45294
+ text: data.instructions,
45295
+ lines: data.instructionsLines,
45296
+ objectTemplate: data.instructionsObjectTemplate,
45297
+ inputs,
45298
+ context,
45299
+ label: "Instructions",
45300
+ preparation
45301
+ })
45302
+ };
45303
+ const { instructions } = instructionInput;
45304
+ if (data.useInstructionsInput) preparation.capture(instructionInput);
45305
+ if (!instructionInput.instructionsMessages) assertClassifierInstructions(instructions);
44666
45306
  const question = createQuestionDefinition(data, inputs, context, questionId, instructions, preparation);
44667
- assertClassifierJson(question, "Question", false, preparation.check);
45307
+ if (instructionInput.instructionsMessages) question.instructionsMessages = instructionInput.instructionsMessages;
45308
+ const prepared = prepareClassifierQuestion(question, new ClassifierValueBudget(preparation.check));
44668
45309
  preparation.check();
44669
- return { ["question"]: { type: "object", value: question } };
45310
+ return { ["question"]: { type: "object", value: prepared } };
44670
45311
  }
44671
45312
  };
44672
45313
  function getCriteriaInputTypes(questionType) {
@@ -44683,6 +45324,7 @@ function getNoulCriteriaInputDefinition(id, title, criteriaType) {
44683
45324
  };
44684
45325
  }
44685
45326
  function getQuestionTypeLabel(questionType) {
45327
+ if (questionType === "box") return "Bounding Box";
44686
45328
  return questionType === "noul" ? "Noul" : questionType[0].toUpperCase() + questionType.slice(1);
44687
45329
  }
44688
45330
  function getClassifierQuestionBodySections(data) {
@@ -44696,7 +45338,10 @@ function getClassifierQuestionBodySections(data) {
44696
45338
  ]
44697
45339
  },
44698
45340
  instructions,
44699
- {
45341
+ data.questionType === "box" ? {
45342
+ id: "capability",
45343
+ fields: [{ label: "Requires", value: "Jev 1.14 and an image (experimental)" }]
45344
+ } : {
44700
45345
  id: "criteria",
44701
45346
  fields: [{ label: "Criteria", value: data.useCriteriaInput ? "input" : getCriteriaSummary(data) }]
44702
45347
  }
@@ -44724,6 +45369,7 @@ function getInstructionsBodySection(data) {
44724
45369
  return { id: "instructions", fields: [], summary: abbreviate(data.instructions) || "(required)" };
44725
45370
  }
44726
45371
  function createQuestionDefinition(data, inputs, context, questionId, instructions, preparation) {
45372
+ if (data.questionType === "box") return { questionId, type: "box", instructions };
44727
45373
  if (data.questionType === "choice") {
44728
45374
  return createChoiceQuestion(data, inputs, context, questionId, instructions, preparation);
44729
45375
  }
@@ -44902,7 +45548,7 @@ function hasClassifierCriteriaValue(value) {
44902
45548
  if (typeof value !== "object") return true;
44903
45549
  return Object.keys(value).length > 0;
44904
45550
  }
44905
- var classifierQuestionNode = nodeDefinition(ClassifierQuestionNodeImpl, "Classifier Question");
45551
+ var classifierQuestionNode = nodeDefinition(ClassifierQuestionNodeImpl, "Decision AI Question");
44906
45552
 
44907
45553
  // src/model/nodes/ClassifierEvaluateNode.ts
44908
45554
  var import_non_secure110 = require("nanoid/non-secure");
@@ -44930,6 +45576,14 @@ var PERPLEXITY_DEFAULT_CREDENTIAL_NAMES = {
44930
45576
  programmaticName: "perplexityApiKey",
44931
45577
  environmentVariableName: "PERPLEXITY_API_KEY"
44932
45578
  };
45579
+ var SUBQ_DEFAULT_CREDENTIAL_NAMES = {
45580
+ programmaticName: "subqApiKey",
45581
+ environmentVariableName: "SUBQ_API_KEY"
45582
+ };
45583
+ var BASETEN_DEFAULT_CREDENTIAL_NAMES = {
45584
+ programmaticName: "basetenApiKey",
45585
+ environmentVariableName: "BASETEN_API_KEY"
45586
+ };
44933
45587
  var programmaticNamePattern2 = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
44934
45588
  var environmentVariableNamePattern2 = /^[A-Za-z_][A-Za-z0-9_]*$/;
44935
45589
  function isValidClassifierProgrammaticCredentialName(name) {
@@ -44941,25 +45595,25 @@ function isValidClassifierEnvironmentCredentialName(name) {
44941
45595
  function normalizeClassifierCredentialNames(value, defaults = JEV_DEFAULT_CREDENTIAL_NAMES) {
44942
45596
  var _a, _b;
44943
45597
  if (value != null && (typeof value !== "object" || Array.isArray(value))) {
44944
- throw new Error("Classifier API key names must be an object.");
45598
+ throw new Error("Decision AI API key names must be an object.");
44945
45599
  }
44946
45600
  const raw = value;
44947
45601
  if ((raw == null ? void 0 : raw.programmaticName) != null && typeof raw.programmaticName !== "string") {
44948
- throw new Error("Classifier programmatic API key name must be a string.");
45602
+ throw new Error("Decision AI programmatic API key name must be a string.");
44949
45603
  }
44950
45604
  if ((raw == null ? void 0 : raw.environmentVariableName) != null && typeof raw.environmentVariableName !== "string") {
44951
- throw new Error("Classifier API key environment variable must be a string.");
45605
+ throw new Error("Decision AI API key environment variable must be a string.");
44952
45606
  }
44953
45607
  const programmaticName = ((_a = raw == null ? void 0 : raw.programmaticName) == null ? void 0 : _a.trim()) || defaults.programmaticName;
44954
45608
  const environmentVariableName = ((_b = raw == null ? void 0 : raw.environmentVariableName) == null ? void 0 : _b.trim()) || defaults.environmentVariableName;
44955
45609
  if (!isValidClassifierProgrammaticCredentialName(programmaticName)) {
44956
45610
  throw new Error(
44957
- "Classifier programmatic API key name must be a JavaScript-style identifier without a leading digit."
45611
+ "Decision AI programmatic API key name must be a JavaScript-style identifier without a leading digit."
44958
45612
  );
44959
45613
  }
44960
45614
  if (!isValidClassifierEnvironmentCredentialName(environmentVariableName)) {
44961
45615
  throw new Error(
44962
- "Classifier API key environment variable must contain letters, digits, and _ without a leading digit."
45616
+ "Decision AI API key environment variable must contain letters, digits, and _ without a leading digit."
44963
45617
  );
44964
45618
  }
44965
45619
  return { programmaticName, environmentVariableName };
@@ -44984,11 +45638,11 @@ function resolveClassifierApiKey({
44984
45638
  }) {
44985
45639
  var _a, _b, _c, _d, _e;
44986
45640
  if (apiKeySource === "classifier-settings") {
44987
- const read = (value, key) => value !== null && typeof value === "object" ? classifierDataProperty(value, key, "Classifier settings credentials") : void 0;
45641
+ const read = (value, key) => value !== null && typeof value === "object" ? classifierDataProperty(value, key, "Decision AI settings credentials") : void 0;
44988
45642
  const saved = getNonEmptyString2(read(read(read(context.settings, "classifierProviders"), providerId), "apiKey"));
44989
45643
  if (!saved)
44990
45644
  throw new ClassifierCredentialMissingError(
44991
- `Classifier settings API key for ${providerId} is not set. No automatic fallback is used.`
45645
+ `Decision AI settings API key for ${providerId} is not set. No automatic fallback is used.`
44992
45646
  );
44993
45647
  return saved;
44994
45648
  }
@@ -44999,7 +45653,7 @@ function resolveClassifierApiKey({
44999
45653
  return value;
45000
45654
  }
45001
45655
  if (apiKeySource !== void 0 && apiKeySource !== "configured")
45002
- throw new Error("Unknown classifier API key source.");
45656
+ throw new Error("Unknown Decision AI API key source.");
45003
45657
  const names = normalizeClassifierCredentialNames(apiKeyNames, defaults);
45004
45658
  const namedValue = resolveNamedClassifierApiKey(
45005
45659
  context,
@@ -45016,7 +45670,7 @@ function resolveClassifierApiKey({
45016
45670
  }
45017
45671
  }
45018
45672
  throw new ClassifierCredentialMissingError(
45019
- `${providerId === "jev" ? "Jev" : "Classifier"} API key is not set. Pass ${names.programmaticName}, configure ${names.environmentVariableName}, or set the configured key in Settings > Classifier.`
45673
+ `${providerId === "jev" ? "Jev" : "Decision AI"} API key is not set. Pass ${names.programmaticName}, configure ${names.environmentVariableName}, or set the configured key in Settings > Decision AI.`
45020
45674
  );
45021
45675
  }
45022
45676
  function resolveNamedClassifierApiKey(context, names, useLegacyOpenAIKey = false) {
@@ -45037,316 +45691,12 @@ function getNonEmptyString2(value) {
45037
45691
  return typeof value === "string" && value.trim() ? value.trim() : void 0;
45038
45692
  }
45039
45693
 
45040
- // src/model/classifier/images.ts
45041
- var InvalidClassifierImageError = class extends Error {
45042
- };
45043
- var invalidImage = () => new InvalidClassifierImageError(
45044
- "State images must contain inline base64 PNG, JPEG, GIF or WebP image data with valid headers and matching media type."
45045
- );
45046
- function isBase64(value) {
45047
- return value.length > 0 && value.length % 4 === 0 && /^[A-Za-z0-9+/]+={0,2}$/.test(value);
45048
- }
45049
- function jpegInfo(size, read, check) {
45050
- const byte = (offset2) => read(offset2, 1)[0];
45051
- const uint16 = (offset2) => {
45052
- const bytes = read(offset2, 2);
45053
- return (bytes[0] << 8) + bytes[1];
45054
- };
45055
- let offset = 2;
45056
- while (offset + 4 <= size) {
45057
- check == null ? void 0 : check();
45058
- if (byte(offset++) !== 255) break;
45059
- while (byte(offset) === 255) {
45060
- if ((offset & 4095) === 0) check == null ? void 0 : check();
45061
- offset++;
45062
- }
45063
- const marker2 = byte(offset++);
45064
- if (marker2 === void 0 || marker2 === 218 || marker2 === 217) break;
45065
- if (marker2 === 1 || marker2 >= 208 && marker2 <= 215) continue;
45066
- if (offset + 2 > size) break;
45067
- const length = uint16(offset);
45068
- if (length < 2 || offset + length > size) break;
45069
- if ([192, 193, 194, 195, 197, 198, 199, 201, 202, 203, 205, 206, 207].includes(marker2) && length >= 8)
45070
- return { mediaType: "image/jpeg", width: uint16(offset + 5), height: uint16(offset + 3) };
45071
- offset += length;
45072
- }
45073
- return void 0;
45074
- }
45075
- function imageInfo(bytes, check) {
45076
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
45077
- const ascii = (offset, length) => String.fromCharCode(...bytes.subarray(offset, offset + length));
45078
- let info;
45079
- if (bytes.length >= 33 && ascii(0, 8) === "\x89PNG\r\n\n" && view.getUint32(8) === 13 && ascii(12, 4) === "IHDR") {
45080
- info = { mediaType: "image/png", width: view.getUint32(16), height: view.getUint32(20) };
45081
- } else if (bytes.length >= 13 && ["GIF87a", "GIF89a"].includes(ascii(0, 6))) {
45082
- info = { mediaType: "image/gif", width: view.getUint16(6, true), height: view.getUint16(8, true) };
45083
- } else if (bytes.length >= 25 && ascii(0, 4) === "RIFF" && ascii(8, 4) === "WEBP") {
45084
- const chunk = ascii(12, 4);
45085
- const uint24 = (offset) => bytes[offset] + (bytes[offset + 1] << 8) + (bytes[offset + 2] << 16);
45086
- if (chunk === "VP8X" && bytes.length >= 30)
45087
- info = { mediaType: "image/webp", width: uint24(24) + 1, height: uint24(27) + 1 };
45088
- else if (chunk === "VP8 " && bytes.length >= 30 && ascii(23, 3) === "\x9D*")
45089
- info = {
45090
- mediaType: "image/webp",
45091
- width: view.getUint16(26, true) & 16383,
45092
- height: view.getUint16(28, true) & 16383
45093
- };
45094
- else if (chunk === "VP8L" && bytes[20] === 47) {
45095
- const bits = view.getUint32(21, true);
45096
- info = { mediaType: "image/webp", width: (bits & 16383) + 1, height: (bits >>> 14 & 16383) + 1 };
45097
- }
45098
- } else if (bytes.length >= 4 && bytes[0] === 255 && bytes[1] === 216) {
45099
- info = jpegInfo(bytes.length, (offset, length) => bytes.subarray(offset, offset + length), check);
45100
- }
45101
- if (!info || info.width === 0 || info.height === 0) throw invalidImage();
45102
- return info;
45103
- }
45104
- function base64ImageInfo(payload, check) {
45105
- if (payload.startsWith("/9j/")) {
45106
- const size = payload.length / 4 * 3 - (payload.endsWith("==") ? 2 : payload.endsWith("=") ? 1 : 0);
45107
- let start = -1;
45108
- let window = new Uint8Array();
45109
- const info = jpegInfo(
45110
- size,
45111
- (offset, length) => {
45112
- if (offset < start || offset + length > start + window.length) {
45113
- start = Math.floor(offset / 3) * 3;
45114
- window = base64ToUint8Array(payload.slice(start / 3 * 4, start / 3 * 4 + 4096));
45115
- }
45116
- return window.subarray(offset - start, offset - start + length);
45117
- },
45118
- check
45119
- );
45120
- if (!info || info.width === 0 || info.height === 0) throw invalidImage();
45121
- return info;
45122
- }
45123
- return imageInfo(base64ToUint8Array(payload.slice(0, 48)));
45124
- }
45125
- function prepareNativeClassifierImage(value, check) {
45126
- if (!value || typeof value !== "object") throw invalidImage();
45127
- const data = classifierDataProperty(value, "data");
45128
- const mediaType = classifierDataProperty(value, "mediaType");
45129
- if (!(data instanceof Uint8Array)) throw invalidImage();
45130
- const bytes = classifierByteView(data);
45131
- assertClassifierResourceLimits(bytes, check);
45132
- const info = imageInfo(bytes, check);
45133
- if (info.mediaType !== mediaType) throw invalidImage();
45134
- check == null ? void 0 : check();
45135
- return { ...info, dataUrl: `data:${info.mediaType};base64,${uint8ArrayToBase64Sync(bytes)}` };
45136
- }
45137
- function inspectClassifierImage(value, check) {
45138
- check == null ? void 0 : check();
45139
- if (typeof value !== "string") throw invalidImage();
45140
- const prefix = /^data:(image\/(?:png|jpeg|gif|webp));base64,/.exec(value);
45141
- if (!prefix) throw invalidImage();
45142
- const payload = value.slice(prefix[0].length);
45143
- if (!isBase64(payload)) throw invalidImage();
45144
- const info = base64ImageInfo(payload, check);
45145
- if (info.mediaType !== prefix[1]) throw invalidImage();
45146
- return info;
45147
- }
45148
- function prepareClassifierImageText(value, check) {
45149
- check == null ? void 0 : check();
45150
- if (value.length > CLASSIFIER_LIMITS.requestBytes)
45151
- throw new Error("Classifier image/text exceeds the 32 MiB input limit.");
45152
- if (value.startsWith("data:image/")) {
45153
- return { ...inspectClassifierImage(value, check), dataUrl: value };
45154
- }
45155
- if (!/^(?:iVBOR|\/9j\/|R0lGOD|UklGR)/.test(value) || !isBase64(value)) return void 0;
45156
- try {
45157
- const info = base64ImageInfo(value, check);
45158
- return { ...info, dataUrl: `data:${info.mediaType};base64,${value}` };
45159
- } catch (error) {
45160
- if (error instanceof InvalidClassifierImageError) return void 0;
45161
- throw error;
45162
- }
45163
- }
45164
- function assertLiquidImageLimits(images, check) {
45165
- if (images.length > 8) throw new Error("Liquid d1 State must contain at most 8 images.");
45166
- let patches = 0;
45167
- for (const { width, height } of images) {
45168
- check == null ? void 0 : check();
45169
- if (Math.max(width, height) / Math.min(width, height) > 100)
45170
- throw new Error("Liquid d1 images must have an aspect ratio at most 100:1.");
45171
- patches += Math.ceil(width / 32) * Math.ceil(height / 32);
45172
- }
45173
- if (patches > 1e4)
45174
- throw new Error("Liquid d1 images must contain at most 10,000 patches of 32 by 32 pixels in total.");
45175
- }
45176
-
45177
- // src/model/classifier/state.ts
45178
- var record = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
45179
- var nativeImage = (value) => record(value) && (classifierDataProperty(value, "type") === "image" || "mediaType" in value && classifierDataProperty(value, "data") instanceof Uint8Array);
45180
- var message = (value) => record(value) && "type" in value && "message" in value;
45181
- function prepareClassifierState(input, budget) {
45182
- if (input.stateInput !== void 0) {
45183
- if (input.state !== "" || input.stateMessages !== void 0)
45184
- throw new Error("Rivet State input and provider State cannot be supplied together.");
45185
- return prepareRivetState(input.stateInput, budget);
45186
- }
45187
- if (input.stateMessages === void 0) {
45188
- if (typeof input.state !== "string" && !record(input.state) && !Array.isArray(input.state))
45189
- throw new Error("State must be text, a JSON object or an array.");
45190
- return { kind: "json", value: snapshotClassifierJson(input.state, "State", budget) };
45191
- }
45192
- if (input.state !== "")
45193
- throw new Error("Structured State and multimodal State messages cannot be supplied together.");
45194
- const messages = snapshotClassifierJson(input.stateMessages, "State", budget);
45195
- const images = inspectStateMessages(messages, budget.check);
45196
- return { kind: "messages", messages, images };
45197
- }
45198
- function normalizeClassifierState(input, check, maxBytes) {
45199
- const state = input === void 0 ? { kind: "json", value: "" } : prepareRivetState(input, new ClassifierValueBudget(check, maxBytes));
45200
- return state.kind === "json" ? { state: state.value } : { state: "", stateMessages: state.messages };
45201
- }
45202
- function prepareRivetState(input, budget) {
45203
- const check = budget.check;
45204
- if (input === null || typeof input !== "object" || Array.isArray(input))
45205
- throw new Error("State input must contain a Rivet data value.");
45206
- const type = classifierDataProperty(input, "type");
45207
- const value = classifierDataProperty(input, "value");
45208
- if (typeof type !== "string") throw new Error("State input type must be a string.");
45209
- if (![
45210
- "string",
45211
- "string[]",
45212
- "image",
45213
- "image[]",
45214
- "chat-message",
45215
- "chat-message[]",
45216
- "object",
45217
- "object[]",
45218
- "any",
45219
- "any[]"
45220
- ].includes(type))
45221
- throw new Error(`Unsupported State input type '${type}'.`);
45222
- if (type.endsWith("[]") && !Array.isArray(value)) throw new Error("State array input must contain an array.");
45223
- if (type === "string" && typeof value !== "string") throw new Error("State string input must contain a string.");
45224
- if (type === "object" && !record(value) && !Array.isArray(value))
45225
- throw new Error("State object input must contain a JSON object or array.");
45226
- if ((type === "image" || type === "chat-message") && Array.isArray(value))
45227
- throw new Error("State scalar input must not contain an array.");
45228
- if (type === "object" || type === "object[]")
45229
- return { kind: "json", value: snapshotClassifierJson(value, "State", budget) };
45230
- budget.inspect(value);
45231
- const imageTexts = /* @__PURE__ */ new Map();
45232
- const textImage = (text2) => {
45233
- const image = imageTexts.get(text2) ?? prepareClassifierImageText(text2, check);
45234
- if (image) imageTexts.set(text2, image);
45235
- return image;
45236
- };
45237
- const hasContent = (item) => nativeImage(item) || message(item) || typeof item === "string" && textImage(item) !== void 0;
45238
- const arrayHasContent = () => {
45239
- for (const item of classifierArrayValues(value, "State")) {
45240
- check();
45241
- if (hasContent(item)) return true;
45242
- }
45243
- return false;
45244
- };
45245
- const contentType = ["image", "image[]", "string[]", "chat-message", "chat-message[]"].includes(type);
45246
- const inferredContent = (type === "any" || type === "any[]") && (hasContent(value) || Array.isArray(value) && arrayHasContent());
45247
- if (!(contentType || inferredContent || type === "string" && textImage(value))) {
45248
- if (typeof value !== "string" && !record(value) && !Array.isArray(value))
45249
- throw new Error("State must be text, a JSON object/array, images, or user messages.");
45250
- return {
45251
- kind: "json",
45252
- value: typeof value === "string" ? value : snapshotClassifierJson(value, "State", new ClassifierValueBudget(check))
45253
- };
45254
- }
45255
- const values2 = Array.isArray(value) ? value : [value];
45256
- if (type === "image[]" && values2.length > 128) throw new Error("State must contain at most 128 images.");
45257
- const messages = [];
45258
- const images = [];
45259
- let partCount = 0;
45260
- const imagePart = (prepare) => {
45261
- if (images.length >= 128) throw new Error("State must contain at most 128 images.");
45262
- const image = prepare();
45263
- images.push(image);
45264
- return { type: "image", dataUrl: image.dataUrl };
45265
- };
45266
- let parts = [];
45267
- const flush = () => {
45268
- if (parts.length) {
45269
- if (messages.length >= CLASSIFIER_LIMITS.messages) throw new Error("State has too many messages.");
45270
- messages.push({ parts });
45271
- parts = [];
45272
- }
45273
- };
45274
- const part = (item) => {
45275
- check();
45276
- if (++partCount > CLASSIFIER_LIMITS.parts) throw new Error("State has too many content parts.");
45277
- if (typeof item === "string") {
45278
- const image = textImage(item);
45279
- return image ? imagePart(() => image) : { type: "text", text: item };
45280
- }
45281
- if (nativeImage(item)) return imagePart(() => prepareNativeClassifierImage(item, check));
45282
- throw new Error("Multimodal State accepts only text, native images, image data URLs, and user messages.");
45283
- };
45284
- for (const item of classifierArrayValues(values2, "State")) {
45285
- check();
45286
- if (type === "image" || type === "image[]") {
45287
- if (++partCount > CLASSIFIER_LIMITS.parts) throw new Error("State has too many content parts.");
45288
- parts.push(imagePart(() => prepareNativeClassifierImage(item, check)));
45289
- } else if (type === "string[]" && typeof item !== "string") {
45290
- throw new Error("State string array must contain only strings.");
45291
- } else if (message(item)) {
45292
- if (classifierDataProperty(item, "type") !== "user" || "function_call" in item || "function_calls" in item)
45293
- throw new Error(
45294
- "Classifier State supports only user messages, not system, developer, assistant, or tool messages."
45295
- );
45296
- flush();
45297
- if (messages.length >= CLASSIFIER_LIMITS.messages) throw new Error("State has too many messages.");
45298
- const contentValue = classifierDataProperty(item, "message");
45299
- const content = Array.isArray(contentValue) ? contentValue : [contentValue];
45300
- messages.push({
45301
- parts: content.length ? Array.from(classifierArrayValues(content, "State"), part) : [{ type: "text", text: "" }]
45302
- });
45303
- } else {
45304
- if (type === "chat-message" || type === "chat-message[]")
45305
- throw new Error("State must contain valid user messages.");
45306
- parts.push(part(item));
45307
- }
45308
- }
45309
- flush();
45310
- return messages.length ? { kind: "messages", messages, images } : { kind: "json", value: "" };
45311
- }
45312
- function inspectStateMessages(messages, check) {
45313
- if (!Array.isArray(messages)) throw new Error("State messages must be an array.");
45314
- if (messages.length > CLASSIFIER_LIMITS.messages) throw new Error("State has too many messages.");
45315
- const images = [];
45316
- let parts = 0;
45317
- for (const message2 of messages) {
45318
- if (!record(message2) || !Array.isArray(message2.parts)) throw new Error("State message parts must be an array.");
45319
- for (const part of message2.parts) {
45320
- check();
45321
- if (++parts > CLASSIFIER_LIMITS.parts) throw new Error("State has too many content parts.");
45322
- if (!record(part)) throw new Error("Invalid State content part.");
45323
- if (part.type === "image" && typeof part.dataUrl === "string") {
45324
- if (images.length >= 128) throw new Error("State must contain at most 128 images.");
45325
- images.push({ ...inspectClassifierImage(part.dataUrl, check), dataUrl: part.dataUrl });
45326
- } else if (part.type !== "text" || typeof part.text !== "string") throw new Error("Invalid State content part.");
45327
- }
45328
- }
45329
- return images;
45330
- }
45331
- function systemOneState(input) {
45332
- if (!input.stateMessages) return { state: input.state };
45333
- const images = [];
45334
- const state = input.stateMessages.map(
45335
- ({ parts }) => parts.map((part) => {
45336
- if (part.type === "text") return part.text;
45337
- images.push(part.dataUrl);
45338
- return `[Image ${images.length}]`;
45339
- }).join("\n")
45340
- ).join("\n\n");
45341
- return { state, ...images.length ? { images } : {} };
45342
- }
45343
-
45344
45694
  // src/model/classifier/response.ts
45345
45695
  function isRecord9(value) {
45346
45696
  return typeof value === "object" && value !== null && !Array.isArray(value);
45347
45697
  }
45348
- function responseField(record3, key) {
45349
- return Object.prototype.hasOwnProperty.call(record3, key) ? record3[key] : void 0;
45698
+ function responseField(record4, key) {
45699
+ return Object.prototype.hasOwnProperty.call(record4, key) ? record4[key] : void 0;
45350
45700
  }
45351
45701
  function requireResponseNumber(value, label, providerLabel) {
45352
45702
  if (typeof value !== "number" || !Number.isFinite(value)) {
@@ -45365,10 +45715,10 @@ function requireProbabilityMap(value, keys2, label, providerLabel) {
45365
45715
  const probabilities = requireResponseMap(value, keys2, label, providerLabel);
45366
45716
  for (const key of keys2) requireResponseNumber(probabilities[key], `${label}.${key}`, providerLabel);
45367
45717
  }
45368
- function validateApiCompatibleClassifierResponse(body, questions, providerLabel = "Classifier provider") {
45718
+ function validateApiCompatibleClassifierResponse(body, questions, providerLabel = "Decision AI provider") {
45369
45719
  return validateClassifierEvaluationResponse(body, questions, providerLabel);
45370
45720
  }
45371
- function validateClassifierEvaluationResponse(body, questions, providerLabel = "Classifier provider") {
45721
+ function validateClassifierEvaluationResponse(body, questions, providerLabel = "Decision AI provider") {
45372
45722
  const model = isRecord9(body) ? responseField(body, "model") : void 0;
45373
45723
  const answers = isRecord9(body) ? responseField(body, "answers") : void 0;
45374
45724
  const usage = isRecord9(body) ? responseField(body, "usage") : void 0;
@@ -45409,6 +45759,16 @@ function validateClassifierEvaluationResponse(body, questions, providerLabel = "
45409
45759
  providerLabel
45410
45760
  );
45411
45761
  requireResponseMap(responseField(answer, "legend"), keys2, `${question.questionId}.legend`, providerLabel);
45762
+ } else if (question.type === "box") {
45763
+ const box = requireResponseMap(
45764
+ responseField(answer, "box"),
45765
+ ["top", "bottom", "left", "right"],
45766
+ `${question.questionId}.box`,
45767
+ providerLabel
45768
+ );
45769
+ for (const edge of ["top", "bottom", "left", "right"])
45770
+ requireResponseNumber(box[edge], `${question.questionId}.box.${edge}`, providerLabel);
45771
+ requireResponseNumber(responseField(answer, "confidence"), `${question.questionId}.confidence`, providerLabel);
45412
45772
  } else {
45413
45773
  requireResponseNumber(responseField(answer, "noul"), `${question.questionId}.noul`, providerLabel);
45414
45774
  }
@@ -45433,7 +45793,14 @@ function createOpenAIDecisionRequest(args) {
45433
45793
  )
45434
45794
  })) : typeof state.value === "string" ? state.value : JSON.stringify(state.value),
45435
45795
  questions: args.questions.map((question) => {
45436
- const common = { name: question.questionId, instructions: text(question.instructions) };
45796
+ if (question.type === "box") throw new Error("OpenAI Decisions does not support Bounding Box questions.");
45797
+ const instructions = question.instructionsMessages ? question.instructionsMessages.flatMap(({ parts }, index) => [
45798
+ ...index ? [{ type: "input_text", text: "\n\n" }] : [],
45799
+ ...parts.map(
45800
+ (part) => part.type === "text" ? { type: "input_text", text: part.text } : { type: "input_image", image_url: part.dataUrl }
45801
+ )
45802
+ ]) : text(question.instructions);
45803
+ const common = { name: question.questionId, instructions };
45437
45804
  if (question.type === "choice")
45438
45805
  return {
45439
45806
  ...common,
@@ -45453,10 +45820,19 @@ function createOpenAIDecisionRequest(args) {
45453
45820
  return {
45454
45821
  ...common,
45455
45822
  type: "predicate",
45456
- instructions: criteria ? `${common.instructions}
45823
+ instructions: criteria ? typeof instructions === "string" ? `${instructions}
45824
+
45825
+ True criterion: ${text(criteria.true)}
45826
+ False criterion: ${text(criteria.false)}` : [
45827
+ ...instructions,
45828
+ {
45829
+ type: "input_text",
45830
+ text: `
45457
45831
 
45458
45832
  True criterion: ${text(criteria.true)}
45459
- False criterion: ${text(criteria.false)}` : common.instructions
45833
+ False criterion: ${text(criteria.false)}`
45834
+ }
45835
+ ] : common.instructions
45460
45836
  };
45461
45837
  })
45462
45838
  };
@@ -45569,60 +45945,165 @@ function assertPerplexityDecisionLimits({ model, state, questions }, check) {
45569
45945
  for (const part of Array.isArray(state.value) ? state.value : [state.value]) {
45570
45946
  check();
45571
45947
  if (!part || typeof part !== "object" || Array.isArray(part)) continue;
45572
- const record3 = part;
45573
- if (record3.type !== "image_url") continue;
45948
+ const record4 = part;
45949
+ if (record4.type !== "image_url") continue;
45574
45950
  if (++imageCount > 128) throw new Error("State must contain at most 128 images.");
45575
- const image = record3.image_url;
45951
+ const image = record4.image_url;
45576
45952
  const url = image && typeof image === "object" && !Array.isArray(image) ? image.url : void 0;
45577
45953
  inspect(inspectClassifierImage(url, check));
45578
45954
  }
45579
45955
  }
45580
45956
 
45581
- // src/model/classifier/questions.ts
45582
- function prepareClassifierQuestion(value, budget) {
45583
- if (value === null || typeof value !== "object" || Array.isArray(value))
45584
- throw new Error("Question inputs must contain question definition objects.");
45585
- if ("images" in value)
45586
- throw new Error("Question-level images are not supported. Connect images to Classifier Evaluate's State input.");
45587
- for (const key of ["questionId", "type", "instructions"]) {
45588
- if (!Object.prototype.propertyIsEnumerable.call(value, key))
45589
- throw new Error(`Every classifier question must have an own, enumerable '${key}' field.`);
45957
+ // src/model/classifier/jev.ts
45958
+ var JEV_IMAGE_MODELS = ["jev-latest", "jev-preview", "jev-1.13.0", "jev-1.14.0"];
45959
+ var JEV_BOX_MODELS = ["jev-latest", "jev-preview", "jev-1.14.0"];
45960
+ function assertJevImageLimits(images, check) {
45961
+ for (const { dataUrl, mediaType, width, height } of images) {
45962
+ check();
45963
+ if (mediaType !== "image/png" && mediaType !== "image/jpeg")
45964
+ throw new Error("Jev images must be still PNG or JPEG. Convert other formats upstream.");
45965
+ if (Math.min(width, height) < 280 || Math.max(width, height) > 1568)
45966
+ throw new Error("Jev image width and height must each be between 280 and 1568 pixels. Resize upstream.");
45967
+ const payload = dataUrl.slice(dataUrl.indexOf(",") + 1);
45968
+ const bytes = payload.length / 4 * 3 - (payload.endsWith("==") ? 2 : payload.endsWith("=") ? 1 : 0);
45969
+ if (bytes > 16 * 1024 * 1024) throw new Error("Jev image files must not exceed 16 MiB decoded.");
45590
45970
  }
45591
- const criteriaProperty = Object.getOwnPropertyDescriptor(value, "criteria");
45592
- if (criteriaProperty && (!criteriaProperty.enumerable || !("value" in criteriaProperty)))
45593
- throw new Error("Classifier question criteria must be an own, enumerable field.");
45594
- const question = snapshotClassifierJson(value, "Question", budget, true);
45595
- if (typeof question.questionId !== "string" || question.questionId.trim() === "")
45596
- throw new Error("Every classifier question must have a non-empty Question ID.");
45597
- if (!["choice", "score", "noul"].includes(question.type))
45598
- throw new Error(`Question '${question.questionId}' has an unsupported type.`);
45599
- assertClassifierInstructionsKind(question.instructions, `Question '${question.questionId}' instructions`);
45600
- const criteria = question.criteria;
45601
- if (question.type === "choice") {
45602
- if (typeof criteria !== "object" || criteria === null || Array.isArray(criteria))
45603
- throw new Error(`Choice question '${question.questionId}' requires object criteria.`);
45604
- const keys2 = Object.keys(criteria);
45605
- if (keys2.length < 2 || keys2.length > 255)
45606
- throw new Error(`Choice question '${question.questionId}' requires 2 to 255 options.`);
45607
- for (const key of keys2)
45608
- assertClassifierEntryKind(
45609
- criteria[key],
45610
- `Question '${question.questionId}' criteria.${key}`
45611
- );
45612
- } else if (question.type === "score") {
45613
- if (!Array.isArray(criteria) || criteria.length < 2 || criteria.length > 10)
45614
- throw new Error(`Score question '${question.questionId}' requires 2 to 10 levels.`);
45615
- let index = 0;
45616
- for (const entry of classifierArrayValues(criteria, "Criteria"))
45617
- assertClassifierEntryKind(entry, `Question '${question.questionId}' criteria[${index++}]`);
45618
- } else if (criteria !== void 0) {
45619
- if (typeof criteria !== "object" || criteria === null || Array.isArray(criteria) || !Object.prototype.propertyIsEnumerable.call(criteria, "true") || !Object.prototype.propertyIsEnumerable.call(criteria, "false"))
45620
- throw new Error(`Noul question '${question.questionId}' criteria must contain true and false entries.`);
45621
- const entries2 = criteria;
45622
- assertClassifierEntryKind(entries2.true, `Question '${question.questionId}' criteria.true`);
45623
- assertClassifierEntryKind(entries2.false, `Question '${question.questionId}' criteria.false`);
45971
+ }
45972
+ function createJevDecisionRequest({
45973
+ model,
45974
+ state,
45975
+ questions
45976
+ }) {
45977
+ const references = /* @__PURE__ */ new Map();
45978
+ const assets = {};
45979
+ const messagesText = (messages) => messages.map(
45980
+ ({ parts }) => parts.map((part) => {
45981
+ if (part.type === "text") return part.text;
45982
+ let reference = references.get(part.dataUrl);
45983
+ if (!reference) {
45984
+ reference = globalThis.crypto.randomUUID();
45985
+ references.set(part.dataUrl, reference);
45986
+ assets[reference] = {
45987
+ type: "image",
45988
+ format: part.dataUrl.startsWith("data:image/png;") ? "png" : "jpg",
45989
+ data_base64: part.dataUrl.slice(part.dataUrl.indexOf(",") + 1)
45990
+ };
45991
+ }
45992
+ return reference;
45993
+ }).join("\n")
45994
+ ).join("\n\n");
45995
+ const value = state.kind === "json" ? state.value : messagesText(state.messages);
45996
+ const questionMap = createQuestionMap(
45997
+ questions,
45998
+ (question) => question.instructionsMessages ? messagesText(question.instructionsMessages) : question.instructions
45999
+ );
46000
+ return { model, state: value, questions: questionMap, ...references.size ? { assets } : {} };
46001
+ }
46002
+
46003
+ // src/model/classifier/subq.ts
46004
+ var SUBQ_DECISION_MODELS = ["subq-snap-1.1"];
46005
+ function subqDecisionState(state) {
46006
+ if (state.kind === "json") return { state: state.value };
46007
+ const wire = systemOneState({ state: "", stateMessages: state.messages });
46008
+ return {
46009
+ state: wire.state,
46010
+ ...state.images.length ? {
46011
+ images: state.images.map(({ mediaType, dataUrl }) => ({
46012
+ mediaType,
46013
+ base64: dataUrl.slice(dataUrl.indexOf(",") + 1)
46014
+ }))
46015
+ } : {}
46016
+ };
46017
+ }
46018
+ function assertSubQDecisionLimits({ state, questions }, check) {
46019
+ if (questions.length > 128) throw new Error("SubQ Snap supports at most 128 questions per request.");
46020
+ for (const question of questions) {
46021
+ let characters = 0;
46022
+ for (const _character of question.questionId) {
46023
+ check();
46024
+ if (++characters > 100) throw new Error("SubQ Snap question IDs must contain at most 100 characters.");
46025
+ }
46026
+ }
46027
+ if (state.kind !== "messages") return;
46028
+ if (state.images.length > 4) throw new Error("SubQ Snap supports at most 4 images per request.");
46029
+ let total = 0;
46030
+ for (const { mediaType, dataUrl } of state.images) {
46031
+ check();
46032
+ if (!["image/png", "image/jpeg", "image/webp"].includes(mediaType))
46033
+ throw new Error("SubQ Snap accepts PNG, JPEG and WebP images, not GIF.");
46034
+ const payload = dataUrl.slice(dataUrl.indexOf(",") + 1);
46035
+ const bytes = payload.length / 4 * 3 - (payload.endsWith("==") ? 2 : payload.endsWith("=") ? 1 : 0);
46036
+ if (bytes > 4 * 1024 * 1024) throw new Error("SubQ Snap images must not exceed 4 MiB decoded each.");
46037
+ total += bytes;
46038
+ }
46039
+ if (total > 8 * 1024 * 1024) throw new Error("SubQ Snap images must not exceed 8 MiB decoded in total.");
46040
+ }
46041
+
46042
+ // src/model/classifier/baseten.ts
46043
+ var BASETEN_DECISION_MODELS = [
46044
+ "decision-models/baseten-elephant-9b-latest",
46045
+ "decision-models/baseten-mammoth-27b-latest"
46046
+ ];
46047
+ function basetenDecisionState(state) {
46048
+ if (state.kind === "json") return state.value;
46049
+ return {
46050
+ messages: state.messages.map(({ parts }) => ({
46051
+ role: "user",
46052
+ content: parts.map(
46053
+ (part) => part.type === "text" ? { type: "text", text: part.text } : { type: "image_url", image_url: { url: part.dataUrl } }
46054
+ )
46055
+ }))
46056
+ };
46057
+ }
46058
+ var record3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
46059
+ function assertBasetenDecisionLimits({ model, state, questions }, check) {
46060
+ let options2 = 0;
46061
+ for (const question of questions) {
46062
+ check();
46063
+ options2 += question.type === "noul" ? 2 : Object.keys(question.criteria ?? {}).length;
46064
+ }
46065
+ if (options2 > 512) throw new Error("Baseten supports at most 512 options across all questions; Noul counts as two.");
46066
+ const wire = basetenDecisionState(state);
46067
+ let characters = 0, images = 0;
46068
+ const text2 = (value) => {
46069
+ for (const _character of value) {
46070
+ check();
46071
+ if (++characters > 5e4) throw new Error("Baseten rendered State must fit within 50,000 characters.");
46072
+ }
46073
+ };
46074
+ if (!record3(wire) || !Array.isArray(wire.messages)) {
46075
+ text2(typeof wire === "string" ? wire : JSON.stringify(wire));
46076
+ return;
46077
+ }
46078
+ for (const message2 of wire.messages) {
46079
+ check();
46080
+ if (!record3(message2) || message2.role !== "user" && message2.role !== "assistant")
46081
+ throw new Error("Baseten State messages must have user or assistant roles.");
46082
+ if (typeof message2.content === "string") {
46083
+ text2(message2.content);
46084
+ continue;
46085
+ }
46086
+ if (!Array.isArray(message2.content)) throw new Error("Baseten message content must be text or content parts.");
46087
+ for (const part of message2.content) {
46088
+ check();
46089
+ if (!record3(part)) throw new Error("Invalid Baseten State content part.");
46090
+ if (part.type === "text" && typeof part.text === "string") {
46091
+ text2(part.text);
46092
+ continue;
46093
+ }
46094
+ if (part.type !== "image_url" || !record3(part.image_url))
46095
+ throw new Error("Baseten State supports text and image_url parts only.");
46096
+ if (message2.role !== "user") throw new Error("Baseten accepts images in user messages only.");
46097
+ if (!BASETEN_DECISION_MODELS.some((id) => id === model))
46098
+ throw new Error("Image support is not known for this Baseten model.");
46099
+ if (++images > 4) throw new Error("Baseten supports at most four images per request.");
46100
+ if (part.image_url.detail !== void 0 && part.image_url.detail !== "auto")
46101
+ throw new Error("Baseten image detail must be auto or omitted.");
46102
+ const image = inspectClassifierImage(part.image_url.url, check);
46103
+ if (!["image/png", "image/jpeg", "image/webp"].includes(image.mediaType))
46104
+ throw new Error("Baseten accepts PNG, JPEG and WebP images, not GIF.");
46105
+ }
45624
46106
  }
45625
- return question;
45626
46107
  }
45627
46108
 
45628
46109
  // src/model/classifier/providers.ts
@@ -45631,12 +46112,14 @@ var LIQUID_SYSTEM_ONE_ENDPOINT = "https://api.liquid.ai/decisions/v1/systemone";
45631
46112
  var OPENAI_DECISIONS_ENDPOINT = "https://api.openai.com/v1/decisions";
45632
46113
  var OPENROUTER_DECISIONS_ENDPOINT = "https://openrouter.ai/api/alpha/decisions";
45633
46114
  var PERPLEXITY_DECISIONS_ENDPOINT = "https://api.perplexity.ai/v1/decisions";
46115
+ var SUBQ_DECISIONS_ENDPOINT = "https://api.subq.ai/v1/systemone";
46116
+ var BASETEN_DECISIONS_ENDPOINT = "https://inference.baseten.co/v1/systemone";
45634
46117
  var JEV_TOKEN_PRICING = {
45635
46118
  inputPerMillionTokens: 0.042,
45636
46119
  outputPerMillionTokens: 0
45637
46120
  };
45638
46121
  var LIQUID_TOKEN_PRICING = {
45639
- inputPerMillionTokens: 0.04,
46122
+ inputPerMillionTokens: 0.02,
45640
46123
  outputPerMillionTokens: 0
45641
46124
  };
45642
46125
  var TOKENS_PER_MILLION = 1e6;
@@ -45657,22 +46140,46 @@ function createApiCompatibleClassifierProvider(config) {
45657
46140
  validateResponse: validateClassifierEvaluationResponse
45658
46141
  });
45659
46142
  }
45660
- var jevClassifierProvider = createApiCompatibleClassifierProvider({
46143
+ var jevClassifierProvider = createClassifierProvider({
45661
46144
  id: "jev",
45662
46145
  label: "Jev",
45663
46146
  defaultModel: "jev-latest",
46147
+ modelOptions: ["jev-latest", "jev-preview", "jev-1.14.0", "jev-1.13.0"].map((value) => ({ value, label: value })),
46148
+ modelHelp: "Jev images are experimental: use still PNG/JPEG, 280\u20131568 pixels per side. Image requests enable TypeSafe\u2019s experimental image API.",
45664
46149
  credentialNames: JEV_DEFAULT_CREDENTIAL_NAMES,
45665
46150
  endpoint: JEV_SYSTEM_ONE_ENDPOINT,
45666
- modelPricing: [{ models: ["jev-latest", "jev-preview", "jev-1.13.0"], pricing: JEV_TOKEN_PRICING }]
46151
+ browserExecutionSupported: false,
46152
+ modelPricing: [{ models: ["jev-latest", "jev-preview", "jev-1.13.0", "jev-1.14.0"], pricing: JEV_TOKEN_PRICING }],
46153
+ supportsImages: (model) => JEV_IMAGE_MODELS.includes(model),
46154
+ supportsQuestionImages: (model) => JEV_IMAGE_MODELS.includes(model),
46155
+ supportsBoxQuestions: (model) => JEV_BOX_MODELS.includes(model),
46156
+ checkState: (state, check) => {
46157
+ if (state.kind === "messages") assertJevImageLimits(state.images, check);
46158
+ },
46159
+ checkRequest: ({ questions }, check) => {
46160
+ for (const question of questions)
46161
+ if (question.instructionsMessages)
46162
+ assertJevImageLimits(inspectStateMessages(question.instructionsMessages, check), check);
46163
+ },
46164
+ buildRequest: createJevDecisionRequest,
46165
+ requestHeaders: ({ state, questions }) => state.kind === "messages" && state.images.length || questions.some(
46166
+ (question) => {
46167
+ var _a;
46168
+ return question.type === "box" || ((_a = question.instructionsMessages) == null ? void 0 : _a.some(({ parts }) => parts.some((part) => part.type === "image")));
46169
+ }
46170
+ ) ? { "TypeSafe-Danger-Zone-Images": "true" } : {},
46171
+ validateResponse: validateClassifierEvaluationResponse
45667
46172
  });
45668
46173
  var liquidClassifierProvider = createApiCompatibleClassifierProvider({
45669
46174
  id: "liquid",
45670
46175
  label: "Liquid AI",
45671
46176
  defaultModel: "d1",
46177
+ modelOptions: ["d1", "d1.1"].map((value) => ({ value, label: value })),
46178
+ modelHelp: "Images belong in shared State, not Question Instructions.",
45672
46179
  credentialNames: LIQUID_DEFAULT_CREDENTIAL_NAMES,
45673
46180
  endpoint: LIQUID_SYSTEM_ONE_ENDPOINT,
45674
46181
  modelPricing: [{ models: ["d1"], pricing: LIQUID_TOKEN_PRICING }],
45675
- supportsImages: (model) => model === "d1",
46182
+ supportsImages: (model) => model === "d1" || model === "d1.1",
45676
46183
  maxRequestBytes: 45e5,
45677
46184
  checkState: (state, check) => {
45678
46185
  if (state.kind === "messages") assertLiquidImageLimits(state.images, check);
@@ -45682,6 +46189,7 @@ var openrouterClassifierProvider = createApiCompatibleClassifierProvider({
45682
46189
  id: "openrouter",
45683
46190
  label: "OpenRouter",
45684
46191
  defaultModel: "microsoft/microsoft-decision-1",
46192
+ modelOptions: [{ value: "microsoft/microsoft-decision-1", label: "Microsoft Decision-1" }],
45685
46193
  credentialNames: OPENROUTER_DEFAULT_CREDENTIAL_NAMES,
45686
46194
  endpoint: OPENROUTER_DECISIONS_ENDPOINT,
45687
46195
  modelPricing: [
@@ -45695,10 +46203,12 @@ var openaiClassifierProvider = createClassifierProvider({
45695
46203
  id: "openai",
45696
46204
  label: "OpenAI",
45697
46205
  defaultModel: "gpt-6-luna",
46206
+ modelOptions: [{ value: "gpt-6-luna", label: "gpt-6-luna" }],
45698
46207
  credentialNames: OPENAI_DEFAULT_CREDENTIAL_NAMES,
45699
46208
  browserExecutionSupported: false,
45700
46209
  endpoint: OPENAI_DECISIONS_ENDPOINT,
45701
46210
  supportsImages: (model) => model === "gpt-6-luna",
46211
+ supportsQuestionImages: (model) => model === "gpt-6-luna",
45702
46212
  modelPricing: [
45703
46213
  {
45704
46214
  models: ["gpt-6-luna"],
@@ -45716,6 +46226,7 @@ var perplexityClassifierProvider = createClassifierProvider({
45716
46226
  id: "perplexity",
45717
46227
  label: "Perplexity",
45718
46228
  defaultModel: "pplx-decider-v1.1-27b",
46229
+ modelOptions: PERPLEXITY_DECISION_MODELS.map((value) => ({ value, label: value })),
45719
46230
  credentialNames: PERPLEXITY_DEFAULT_CREDENTIAL_NAMES,
45720
46231
  browserExecutionSupported: false,
45721
46232
  endpoint: PERPLEXITY_DECISIONS_ENDPOINT,
@@ -45734,19 +46245,62 @@ var perplexityClassifierProvider = createClassifierProvider({
45734
46245
  }),
45735
46246
  validateResponse: validateClassifierEvaluationResponse
45736
46247
  });
46248
+ var subqClassifierProvider = createClassifierProvider({
46249
+ id: "subq",
46250
+ label: "SubQ",
46251
+ defaultModel: "subq-snap-1.1",
46252
+ modelOptions: SUBQ_DECISION_MODELS.map((value) => ({ value, label: value })),
46253
+ credentialNames: SUBQ_DEFAULT_CREDENTIAL_NAMES,
46254
+ browserExecutionSupported: false,
46255
+ endpoint: SUBQ_DECISIONS_ENDPOINT,
46256
+ supportsImages: (model) => SUBQ_DECISION_MODELS.includes(model),
46257
+ modelPricing: [{ models: SUBQ_DECISION_MODELS, pricing: { inputPerMillionTokens: 0.04, outputPerMillionTokens: 0 } }],
46258
+ maxRequestBytes: 13 * 1024 * 1024,
46259
+ checkRequest: assertSubQDecisionLimits,
46260
+ buildRequest: ({ model, state, questions }) => ({
46261
+ model,
46262
+ ...subqDecisionState(state),
46263
+ questions: createQuestionMap(questions)
46264
+ }),
46265
+ validateResponse: validateClassifierEvaluationResponse
46266
+ });
46267
+ var basetenClassifierProvider = createClassifierProvider({
46268
+ id: "baseten",
46269
+ label: "Baseten",
46270
+ defaultModel: BASETEN_DECISION_MODELS[0],
46271
+ modelOptions: [
46272
+ { value: BASETEN_DECISION_MODELS[0], label: "Elephant-1" },
46273
+ { value: BASETEN_DECISION_MODELS[1], label: "Mammoth-1" }
46274
+ ],
46275
+ modelHelp: "Images belong in shared State, not Question Instructions.",
46276
+ credentialNames: BASETEN_DEFAULT_CREDENTIAL_NAMES,
46277
+ browserExecutionSupported: false,
46278
+ endpoint: BASETEN_DECISIONS_ENDPOINT,
46279
+ supportsImages: (model) => BASETEN_DECISION_MODELS.some((id) => id === model),
46280
+ checkRequest: assertBasetenDecisionLimits,
46281
+ buildRequest: ({ model, state, questions }) => ({
46282
+ model,
46283
+ state: basetenDecisionState(state),
46284
+ questions: createQuestionMap(questions)
46285
+ }),
46286
+ validateResponse: validateClassifierEvaluationResponse
46287
+ // A temporary free promotion is not permanent pricing. Unknown cost stays unknown.
46288
+ });
45737
46289
  var classifierProviders = [
45738
46290
  jevClassifierProvider,
45739
46291
  liquidClassifierProvider,
45740
46292
  openaiClassifierProvider,
45741
46293
  openrouterClassifierProvider,
45742
- perplexityClassifierProvider
46294
+ perplexityClassifierProvider,
46295
+ subqClassifierProvider,
46296
+ basetenClassifierProvider
45743
46297
  ];
45744
46298
  var ClassifierProviderError = class extends Error {
45745
46299
  constructor(message2, kind, statusCode, options2) {
45746
46300
  super(message2, options2);
45747
46301
  this.kind = kind;
45748
46302
  this.statusCode = statusCode;
45749
- this.name = "ClassifierProviderError";
46303
+ this.name = "DecisionAIProviderError";
45750
46304
  }
45751
46305
  };
45752
46306
  function classifierFailureKind(kind, status) {
@@ -45754,47 +46308,53 @@ function classifierFailureKind(kind, status) {
45754
46308
  }
45755
46309
  function classifierErrorMessage(error, apiKey) {
45756
46310
  try {
45757
- const text2 = error instanceof Error ? error.message : typeof error === "string" ? error : "Classifier request failed.";
46311
+ const text2 = error instanceof Error ? error.message : typeof error === "string" ? error : "Decision AI request failed.";
45758
46312
  return (apiKey ? text2.split(apiKey).join("[redacted]") : text2).slice(0, 2e3);
45759
46313
  } catch {
45760
- return "Classifier request failed with unreadable error metadata.";
46314
+ return "Decision AI request failed with unreadable error metadata.";
45761
46315
  }
45762
46316
  }
45763
46317
  function createOperation(args, label) {
45764
- if (!Number.isFinite(args.timeoutMs) || args.timeoutMs <= 0 || args.deadline !== void 0 && !Number.isFinite(args.deadline))
45765
- throw new Error("Classifier timeout and deadline must be finite, with a positive timeout.");
46318
+ if (args.timeoutMs !== void 0 && (!Number.isFinite(args.timeoutMs) || args.timeoutMs <= 0) || args.deadline !== void 0 && !Number.isFinite(args.deadline))
46319
+ throw new Error("Decision AI timeout and deadline must be finite, with a positive timeout.");
45766
46320
  const now = Date.now();
45767
- const deadline = Math.min(now + args.timeoutMs, args.deadline ?? Infinity);
45768
- if (deadline - now > MAX_TIMER_DELAY_MS)
45769
- throw new Error(`Classifier effective timeout must not exceed ${MAX_TIMER_DELAY_MS} ms.`);
45770
- const timeoutError = () => new ClassifierProviderError(`${label} request timed out after ${args.timeoutMs} ms.`, "timeout");
46321
+ const deadline = Math.min(args.timeoutMs === void 0 ? Infinity : now + args.timeoutMs, args.deadline ?? Infinity);
46322
+ if (Number.isFinite(deadline) && deadline - now > MAX_TIMER_DELAY_MS)
46323
+ throw new Error(`Decision AI effective timeout must not exceed ${MAX_TIMER_DELAY_MS} ms.`);
46324
+ const timeoutMessage = `${label} request timed out${args.timeoutMs === void 0 ? "" : ` after ${args.timeoutMs} ms`}.`;
45771
46325
  return {
45772
46326
  signal: args.signal,
45773
46327
  deadline,
46328
+ timeoutMessage,
45774
46329
  check(attemptSignal) {
45775
46330
  throwIfAborted2(args.signal, label);
45776
- if (Date.now() >= deadline || (attemptSignal == null ? void 0 : attemptSignal.aborted)) throw timeoutError();
46331
+ if (Date.now() >= deadline || (attemptSignal == null ? void 0 : attemptSignal.aborted))
46332
+ throw new ClassifierProviderError(timeoutMessage, "timeout");
45777
46333
  }
45778
46334
  };
45779
46335
  }
45780
46336
  function createClassifierProvider(spec) {
45781
- const { endpoint, buildRequest, validateResponse, checkState, checkRequest, ...provider } = spec;
46337
+ const { endpoint, buildRequest, requestHeaders, validateResponse, checkState, checkRequest, ...provider } = spec;
45782
46338
  const evaluate = async (input) => {
45783
- var _a;
46339
+ var _a, _b, _c;
45784
46340
  if ("images" in input) throw new Error("Pass image evidence through State, not a separate images field.");
45785
- const args = { ...input, fetchImplementation: input.fetchImplementation ?? fetch };
46341
+ const args = {
46342
+ ...input,
46343
+ tokenPricing: validateTokenPricing(input.tokenPricing),
46344
+ fetchImplementation: input.fetchImplementation ?? fetch
46345
+ };
45786
46346
  const operation = createOperation(args, provider.label);
45787
46347
  operation.check();
45788
- if (typeof args.model !== "string") throw new Error("Classifier model must be a nonblank string.");
46348
+ if (typeof args.model !== "string") throw new Error("Decision AI model must be a nonblank string.");
45789
46349
  const budget = new ClassifierValueBudget(operation.check, provider.maxRequestBytes);
45790
46350
  budget.inspect(args.model);
45791
- if (args.model.trim() === "") throw new Error("Classifier model must be a nonblank string.");
46351
+ if (args.model.trim() === "") throw new Error("Decision AI model must be a nonblank string.");
45792
46352
  if (typeof args.apiKey !== "string" || args.apiKey.trim() === "" || /[\r\n]/.test(args.apiKey))
45793
- throw new Error("Classifier API key must be a nonblank string without line breaks.");
46353
+ throw new Error("Decision AI API key must be a nonblank string without line breaks.");
45794
46354
  if (!Array.isArray(args.questions) || args.questions.length === 0)
45795
- throw new Error("Classifier Evaluate requires at least one question.");
46355
+ throw new Error("Decision AI run requires at least one question.");
45796
46356
  if (args.questions.length > CLASSIFIER_LIMITS.questions)
45797
- throw new Error("Classifier Evaluate supports at most 1000 questions.");
46357
+ throw new Error("Decision AI run supports at most 1000 questions.");
45798
46358
  const state = prepareClassifierState(args, budget);
45799
46359
  const questions = [];
45800
46360
  const ids = /* @__PURE__ */ new Set();
@@ -45805,9 +46365,32 @@ function createClassifierProvider(spec) {
45805
46365
  ids.add(question.questionId);
45806
46366
  questions.push(question);
45807
46367
  }
45808
- if (state.kind === "messages" && state.images.length && !((_a = provider.supportsImages) == null ? void 0 : _a.call(provider, args.model)))
46368
+ let imageCount = state.kind === "messages" ? state.images.length : 0;
46369
+ for (const question of questions) {
46370
+ const images = question.instructionsMessages ? inspectStateMessages(question.instructionsMessages, operation.check) : [];
46371
+ imageCount += images.length;
46372
+ if (question.type === "box") {
46373
+ if (!((_a = provider.supportsBoxQuestions) == null ? void 0 : _a.call(provider, args.model)))
46374
+ throw new ClassifierProviderError(
46375
+ `${provider.label} model '${args.model}' does not support Bounding Box questions.`,
46376
+ "capability"
46377
+ );
46378
+ if (!(state.kind === "messages" && state.images.length) && !images.length)
46379
+ throw new ClassifierProviderError(
46380
+ `Bounding Box question '${question.questionId}' requires an image in shared State or its own Instructions.`,
46381
+ "capability"
46382
+ );
46383
+ }
46384
+ if (images.length && !((_b = provider.supportsQuestionImages) == null ? void 0 : _b.call(provider, args.model)))
46385
+ throw new ClassifierProviderError(
46386
+ `${provider.label} model '${args.model}' does not support images in question instructions. Use a compatible Jev or OpenAI profile.`,
46387
+ "capability"
46388
+ );
46389
+ }
46390
+ if (imageCount > 128) throw new Error("State and questions together must contain at most 128 images.");
46391
+ if (state.kind === "messages" && state.images.length && !((_c = provider.supportsImages) == null ? void 0 : _c.call(provider, args.model)))
45809
46392
  throw new ClassifierProviderError(
45810
- `${provider.label} model '${args.model}' does not support classifier images.`,
46393
+ `${provider.label} model '${args.model}' does not support Decision AI images.`,
45811
46394
  "capability"
45812
46395
  );
45813
46396
  try {
@@ -45816,7 +46399,7 @@ function createClassifierProvider(spec) {
45816
46399
  } catch (error) {
45817
46400
  operation.check();
45818
46401
  throw new ClassifierProviderError(
45819
- error instanceof Error ? error.message : `${provider.label} does not support this classifier evidence.`,
46402
+ error instanceof Error ? error.message : `${provider.label} does not support this Decision AI evidence.`,
45820
46403
  "capability",
45821
46404
  void 0,
45822
46405
  { cause: error }
@@ -45825,7 +46408,7 @@ function createClassifierProvider(spec) {
45825
46408
  operation.check();
45826
46409
  const result = await callClassifierHttp(
45827
46410
  args,
45828
- { ...provider, endpoint, validateResponse },
46411
+ { ...provider, endpoint, requestHeaders, validateResponse },
45829
46412
  { model: args.model, state, questions },
45830
46413
  buildRequest,
45831
46414
  operation
@@ -45838,15 +46421,25 @@ function createClassifierProvider(spec) {
45838
46421
  function normalizeModelPricing(provider) {
45839
46422
  return provider.modelPricing ?? (provider.pricing && provider.defaultModel ? [{ models: [provider.defaultModel], pricing: provider.pricing }] : []);
45840
46423
  }
46424
+ function getClassifierSystemTokenPricing(providerId, model) {
46425
+ var _a;
46426
+ const provider = getClassifierProvider(providerId);
46427
+ return (_a = normalizeModelPricing(provider).find((entry) => entry.models.includes((model == null ? void 0 : model.trim()) || provider.defaultModel))) == null ? void 0 : _a.pricing;
46428
+ }
45841
46429
  function getClassifierProvider(id) {
45842
46430
  const provider = classifierProviders.find((candidate) => candidate.id === (id || jevClassifierProvider.id));
45843
- if (!provider) throw new Error(`Unknown classifier provider '${id}'.`);
46431
+ if (!provider) throw new Error(`Unknown Decision AI provider '${id}'.`);
45844
46432
  return provider;
45845
46433
  }
45846
46434
  function getClassifierProviderEnvironmentVariableNames() {
45847
46435
  return [...new Set(classifierProviders.map((provider) => provider.credentialNames.environmentVariableName))];
45848
46436
  }
45849
- function calculateClassifierUsageCost(provider, usage, models) {
46437
+ function calculateClassifierUsageCost(provider, usage, models, tokenPricing) {
46438
+ if (tokenPricing !== void 0)
46439
+ return calculateTokenUsageCost(tokenPricing, {
46440
+ inputTokens: usage.input_tokens,
46441
+ outputTokens: usage.output_tokens
46442
+ });
45850
46443
  if (!models) return void 0;
45851
46444
  const entries2 = normalizeModelPricing(provider);
45852
46445
  const entry = entries2.find(
@@ -45855,26 +46448,20 @@ function calculateClassifierUsageCost(provider, usage, models) {
45855
46448
  const base = entry == null ? void 0 : entry.pricing;
45856
46449
  const tier = base == null ? void 0 : base.longContext;
45857
46450
  const validRates = (rates) => Number.isFinite(rates.inputPerMillionTokens) && rates.inputPerMillionTokens >= 0 && Number.isFinite(rates.outputPerMillionTokens) && rates.outputPerMillionTokens >= 0;
45858
- if (base == null || !validRates(base) || tier != null && (!Number.isSafeInteger(tier.aboveInputTokens) || tier.aboveInputTokens < 0 || !validRates(tier)) || !Number.isSafeInteger(usage.input_tokens) || usage.input_tokens < 0 || !Number.isSafeInteger(usage.output_tokens) || usage.output_tokens < 0) {
46451
+ if (base == null || !validRates(base) || tier != null && (!Number.isSafeInteger(tier.aboveInputTokens) || tier.aboveInputTokens < 0 || !validRates(tier)) || !isReportedTokenCount(usage.input_tokens) || !isReportedTokenCount(usage.output_tokens)) {
45859
46452
  return void 0;
45860
46453
  }
45861
46454
  const pricing = tier && usage.input_tokens > tier.aboveInputTokens ? tier : base;
45862
46455
  const totalCost = (usage.input_tokens * pricing.inputPerMillionTokens + usage.output_tokens * pricing.outputPerMillionTokens) / TOKENS_PER_MILLION;
45863
46456
  return Number.isFinite(totalCost) && totalCost >= 0 ? totalCost : void 0;
45864
46457
  }
45865
- function createQuestionMap(questions) {
45866
- const result = /* @__PURE__ */ Object.create(null);
45867
- for (const question of questions) {
45868
- const providerQuestion = question.type === "noul" && question.criteria === void 0 ? { type: question.type, instructions: question.instructions } : { type: question.type, instructions: question.instructions, criteria: question.criteria };
45869
- Object.defineProperty(result, question.questionId, { enumerable: true, value: providerQuestion });
45870
- }
45871
- return result;
45872
- }
45873
46458
  async function callClassifierHttp(args, spec, prepared, buildRequest, operation) {
46459
+ var _a;
45874
46460
  const { apiKey, fetchImplementation, retryOnNon200, retryOnNon200CooldownMs, retryOnNon200RepeatTimes } = args;
45875
46461
  const { endpoint, label: providerLabel, validateResponse, maxRequestBytes } = spec;
45876
- const { signal, deadline } = operation;
46462
+ const { signal, deadline, timeoutMessage } = operation;
45877
46463
  const request = buildRequest(prepared);
46464
+ const requestHeaders = (_a = spec.requestHeaders) == null ? void 0 : _a.call(spec, prepared);
45878
46465
  const configuredRetryCount = retryOnNon200 ? normalizeClassifierNon200RetryCount(retryOnNon200RepeatTimes) : 0;
45879
46466
  const configuredCooldownMs = normalizeClassifierNon200RetryCooldownMs(retryOnNon200CooldownMs);
45880
46467
  let automaticRetryCount = 0;
@@ -45891,9 +46478,9 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
45891
46478
  let attemptIndex = -1;
45892
46479
  let attemptStartedAt = 0;
45893
46480
  const report = (outcome, status, kind, classifierUsage, error) => {
45894
- var _a;
46481
+ var _a2;
45895
46482
  try {
45896
- (_a = args.onAttempt) == null ? void 0 : _a.call(args, {
46483
+ (_a2 = args.onAttempt) == null ? void 0 : _a2.call(args, {
45897
46484
  attemptIndex,
45898
46485
  durationMs: Math.max(0, Date.now() - attemptStartedAt),
45899
46486
  outcome,
@@ -45921,7 +46508,7 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
45921
46508
  const controller = new AbortController();
45922
46509
  const onAbort = () => controller.abort(signal.reason);
45923
46510
  signal.addEventListener("abort", onAbort, { once: true });
45924
- const timer = setTimeout(() => controller.abort(new Error(`${providerLabel} request timeout`)), remainingMs);
46511
+ const timer = Number.isFinite(remainingMs) ? setTimeout(() => controller.abort(new Error(`${providerLabel} request timeout`)), remainingMs) : void 0;
45925
46512
  const cleanupAttempt = () => {
45926
46513
  clearTimeout(timer);
45927
46514
  signal.removeEventListener("abort", onAbort);
@@ -45933,7 +46520,7 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
45933
46520
  fetchImplementation(endpoint, {
45934
46521
  method: "POST",
45935
46522
  redirect: "error",
45936
- headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
46523
+ headers: { ...requestHeaders, Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
45937
46524
  body: requestJson,
45938
46525
  signal: controller.signal
45939
46526
  }),
@@ -45952,7 +46539,7 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
45952
46539
  void 0,
45953
46540
  kind,
45954
46541
  void 0,
45955
- kind === "timeout" ? `${providerLabel} request timed out after ${args.timeoutMs} ms.` : `${providerLabel} transport request failed.`
46542
+ kind === "timeout" ? timeoutMessage : `${providerLabel} transport request failed.`
45956
46543
  );
45957
46544
  operation.check(controller.signal);
45958
46545
  if (automaticRetryCount >= MAX_AUTOMATIC_ATTEMPTS - 1) {
@@ -45977,17 +46564,18 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
45977
46564
  response.status,
45978
46565
  signal.aborted ? void 0 : "timeout",
45979
46566
  void 0,
45980
- signal.aborted ? `${providerLabel} request was canceled.` : `${providerLabel} request timed out after ${args.timeoutMs} ms.`
46567
+ signal.aborted ? `${providerLabel} request was canceled.` : timeoutMessage
45981
46568
  );
45982
46569
  throw error;
45983
46570
  }
45984
46571
  if (!response.ok) {
46572
+ const accessDeniedMessage = response.status === 403 ? `${providerLabel} access denied (HTTP 403). Check API key permissions and requested model access.` : void 0;
45985
46573
  report(
45986
46574
  "failure",
45987
46575
  response.status,
45988
46576
  "http",
45989
46577
  void 0,
45990
- response.status === 401 || response.status === 403 ? `${providerLabel} authentication failed (HTTP ${response.status}). Check the ${providerLabel} API key.` : `${providerLabel} rejected the request (HTTP ${response.status}).`
46578
+ accessDeniedMessage ?? (response.status === 401 ? `${providerLabel} authentication failed (HTTP ${response.status}). Check the ${providerLabel} API key.` : `${providerLabel} rejected the request (HTTP ${response.status}).`)
45991
46579
  );
45992
46580
  const retryable = RETRYABLE_STATUSES.has(response.status);
45993
46581
  const permanent = [400, 401, 402, 403, 413, 422].includes(response.status);
@@ -46021,7 +46609,7 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
46021
46609
  }
46022
46610
  if (response.status === 401 || response.status === 403) {
46023
46611
  throw new ClassifierProviderError(
46024
- `${providerLabel} authentication failed. Check the ${providerLabel} API key.`,
46612
+ accessDeniedMessage ?? `${providerLabel} authentication failed. Check the ${providerLabel} API key.`,
46025
46613
  "http",
46026
46614
  response.status
46027
46615
  );
@@ -46058,7 +46646,7 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
46058
46646
  response.status,
46059
46647
  kind,
46060
46648
  void 0,
46061
- kind === "timeout" ? `${providerLabel} request timed out after ${args.timeoutMs} ms.` : error instanceof ClassifierResourceLimitError ? error.message : kind === "transport" ? `${providerLabel} response body could not be read.` : `${providerLabel} returned an invalid JSON response.`
46649
+ kind === "timeout" ? timeoutMessage : error instanceof ClassifierResourceLimitError ? error.message : kind === "transport" ? `${providerLabel} response body could not be read.` : `${providerLabel} returned an invalid JSON response.`
46062
46650
  );
46063
46651
  discardResponseBody(response);
46064
46652
  operation.check(controller.signal);
@@ -46080,17 +46668,17 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
46080
46668
  "failure",
46081
46669
  response.status,
46082
46670
  "response-validation",
46083
- classifierAttemptUsage(body, spec, args.model),
46084
- error instanceof Error ? error.message : `${providerLabel} returned an invalid classifier response.`
46671
+ classifierAttemptUsage(body, spec, args.model, args.tokenPricing),
46672
+ error instanceof Error ? error.message : `${providerLabel} returned an invalid Decision AI response.`
46085
46673
  );
46086
46674
  throw new ClassifierProviderError(
46087
- error instanceof Error ? error.message : `${providerLabel} returned an invalid classifier response.`,
46675
+ error instanceof Error ? error.message : `${providerLabel} returned an invalid Decision AI response.`,
46088
46676
  "response-validation",
46089
46677
  void 0,
46090
46678
  { cause: error }
46091
46679
  );
46092
46680
  }
46093
- report("success", response.status, void 0, classifierAttemptUsage(body, spec, args.model));
46681
+ report("success", response.status, void 0, classifierAttemptUsage(body, spec, args.model, args.tokenPricing));
46094
46682
  return {
46095
46683
  // Preserve the direct-provider result contract, but graph runs with the
46096
46684
  // diagnostic disabled never allocate this second representation.
@@ -46107,12 +46695,12 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
46107
46695
  };
46108
46696
  }
46109
46697
  }
46110
- function classifierAttemptUsage(body, provider, requestedModel) {
46698
+ function classifierAttemptUsage(body, provider, requestedModel, tokenPricing) {
46111
46699
  if (!body || typeof body !== "object" || Array.isArray(body) || !Object.hasOwn(body, "usage")) return;
46112
46700
  const { usage, model } = body;
46113
- if (!usage || typeof usage !== "object" || Array.isArray(usage) || !Object.hasOwn(usage, "input_tokens") || !Object.hasOwn(usage, "output_tokens") || !Number.isSafeInteger(usage.input_tokens) || usage.input_tokens < 0 || !Number.isSafeInteger(usage.output_tokens) || usage.output_tokens < 0)
46701
+ if (!usage || typeof usage !== "object" || Array.isArray(usage) || !Object.hasOwn(usage, "input_tokens") || !Object.hasOwn(usage, "output_tokens") || !isReportedTokenCount(usage.input_tokens) || !isReportedTokenCount(usage.output_tokens))
46114
46702
  return;
46115
- const estimatedCostUsd = typeof model === "string" && Object.hasOwn(body, "model") ? calculateClassifierUsageCost(provider, usage, { requestedModel, responseModel: model }) : void 0;
46703
+ const estimatedCostUsd = typeof model === "string" && Object.hasOwn(body, "model") ? calculateClassifierUsageCost(provider, usage, { requestedModel, responseModel: model }, tokenPricing) : void 0;
46116
46704
  return {
46117
46705
  inputTokens: usage.input_tokens,
46118
46706
  outputTokens: usage.output_tokens,
@@ -46164,22 +46752,26 @@ function throwIfAborted2(signal, providerLabel) {
46164
46752
  function throwAbort(signal, providerLabel) {
46165
46753
  throw signal.reason instanceof Error ? signal.reason : new Error(`${providerLabel} request aborted.`);
46166
46754
  }
46167
- function waitForRetry(delayMs, signal, providerLabel) {
46755
+ async function waitForRetry(delayMs, signal, providerLabel) {
46168
46756
  throwIfAborted2(signal, providerLabel);
46169
- if (delayMs <= 0) return Promise.resolve();
46170
- return new Promise((resolve, reject) => {
46171
- const onAbort = () => {
46172
- clearTimeout(timer);
46173
- signal.removeEventListener("abort", onAbort);
46174
- reject(signal.reason instanceof Error ? signal.reason : new Error(`${providerLabel} request aborted.`));
46175
- };
46176
- const timer = setTimeout(() => {
46177
- signal.removeEventListener("abort", onAbort);
46178
- resolve();
46179
- }, delayMs);
46180
- signal.addEventListener("abort", onAbort, { once: true });
46181
- if (signal.aborted) onAbort();
46182
- });
46757
+ while (delayMs > 0) {
46758
+ const chunkMs = Math.min(delayMs, MAX_TIMER_DELAY_MS);
46759
+ await new Promise((resolve, reject) => {
46760
+ const onAbort = () => {
46761
+ clearTimeout(timer);
46762
+ signal.removeEventListener("abort", onAbort);
46763
+ reject(signal.reason instanceof Error ? signal.reason : new Error(`${providerLabel} request aborted.`));
46764
+ };
46765
+ const timer = setTimeout(() => {
46766
+ signal.removeEventListener("abort", onAbort);
46767
+ resolve();
46768
+ }, chunkMs);
46769
+ signal.addEventListener("abort", onAbort, { once: true });
46770
+ if (signal.aborted) onAbort();
46771
+ });
46772
+ throwIfAborted2(signal, providerLabel);
46773
+ delayMs -= chunkMs;
46774
+ }
46183
46775
  }
46184
46776
  function getRetryDelayMs(retryAfter, attempt, deadline) {
46185
46777
  let requestedMs;
@@ -46203,6 +46795,7 @@ var DEFAULT_CLASSIFIER_PROFILE_FAILURE_WINDOW_MS = 3e5;
46203
46795
  var DEFAULT_CLASSIFIER_PROFILE_OPEN_DURATION_MS = 3e5;
46204
46796
  var classifierProfileInputIds = ["model", "apiKey"];
46205
46797
  var classifierProfileDataKeys = [
46798
+ "tokenPricing",
46206
46799
  "provider",
46207
46800
  "model",
46208
46801
  "useModelInput",
@@ -46223,7 +46816,7 @@ function pickClassifierProfileData(data) {
46223
46816
  function positive(value, fallback, label, maximum = 6e5) {
46224
46817
  const result = value ?? fallback;
46225
46818
  if (!Number.isSafeInteger(result) || result < 1 || result > maximum)
46226
- throw new Error(`Classifier Profile ${label} must be an integer between 1 and ${maximum}.`);
46819
+ throw new Error(`Decision AI Profile ${label} must be an integer between 1 and ${maximum}.`);
46227
46820
  return result;
46228
46821
  }
46229
46822
  function classifierProfileResponseTimeout(configuration) {
@@ -46255,34 +46848,36 @@ function classifierProfileHealthPolicy(configuration) {
46255
46848
  }
46256
46849
  function normalizeClassifierProfileValue(value) {
46257
46850
  return normalizeDetachedProfile(
46258
- snapshotClassifierJson(value, "Classifier Profile", new ClassifierValueBudget(), true)
46851
+ snapshotClassifierJson(value, "Decision AI Profile", new ClassifierValueBudget(), true)
46259
46852
  );
46260
46853
  }
46261
46854
  function normalizeDetachedProfile(value) {
46262
46855
  var _a;
46263
46856
  const profile = value;
46264
46857
  if (!profile || profile.version !== 1 || !profile.configuration || typeof profile.configuration !== "object" || Array.isArray(profile.configuration) || !profile.credential || typeof profile.credential !== "object" || Array.isArray(profile.credential))
46265
- throw new Error("Classifier Profiles input requires a version 1 Classifier Profile.");
46858
+ throw new Error("Decision AI Profiles input requires a version 1 Decision AI Profile.");
46266
46859
  const { configuration, credential } = profile;
46267
46860
  if (typeof configuration.provider !== "string" || typeof configuration.model !== "string" || !configuration.model.trim())
46268
- throw new Error("Classifier Profile requires a provider and a nonblank model.");
46861
+ throw new Error("Decision AI Profile requires a provider and a nonblank model.");
46269
46862
  getClassifierProvider(configuration.provider);
46270
46863
  if (credential.value !== void 0 && (typeof credential.value !== "string" || /[\r\n]/.test(credential.value)))
46271
- throw new Error("Classifier Profile credential must be a string without line breaks.");
46864
+ throw new Error("Decision AI Profile credential must be a string without line breaks.");
46272
46865
  if (profile.profileName !== void 0 && typeof profile.profileName !== "string")
46273
- throw new Error("Invalid Classifier Profile name.");
46866
+ throw new Error("Invalid Decision AI Profile name.");
46274
46867
  if (profile.sourceNodeId !== void 0 && (typeof profile.sourceNodeId !== "string" || !profile.sourceNodeId.trim()))
46275
- throw new Error("Invalid Classifier Profile source node.");
46868
+ throw new Error("Invalid Decision AI Profile source node.");
46276
46869
  if (configuration.enableCircuitBreaker !== void 0 && typeof configuration.enableCircuitBreaker !== "boolean")
46277
- throw new Error("Classifier Profile automatic suspension must be a boolean.");
46870
+ throw new Error("Decision AI Profile automatic suspension must be a boolean.");
46278
46871
  if (configuration.apiKeySource !== void 0 && !["configured", "classifier-settings", "input"].includes(configuration.apiKeySource))
46279
- throw new Error("Unknown classifier API key source.");
46872
+ throw new Error("Unknown Decision AI API key source.");
46280
46873
  classifierProfileResponseTimeout(configuration);
46281
46874
  classifierProfileHealthPolicy(configuration);
46875
+ configuration.tokenPricing = validateTokenPricing(configuration.tokenPricing);
46282
46876
  return {
46283
46877
  version: 1,
46284
- sourceNodeId: profile.sourceNodeId,
46285
- profileName: ((_a = profile.profileName) == null ? void 0 : _a.trim()) || void 0,
46878
+ ...profile.sourceNodeId === void 0 ? {} : { sourceNodeId: profile.sourceNodeId },
46879
+ // Blank names are absent, but authored whitespace must survive exact-default display aliases.
46880
+ ...((_a = profile.profileName) == null ? void 0 : _a.trim()) ? { profileName: profile.profileName } : {},
46286
46881
  credential: credential.value === void 0 ? {} : { value: credential.value.trim() },
46287
46882
  configuration: {
46288
46883
  ...pickClassifierProfileData(configuration),
@@ -46294,15 +46889,15 @@ function normalizeDetachedProfile(value) {
46294
46889
  }
46295
46890
  function normalizeClassifierProfiles(value, check) {
46296
46891
  if (Array.isArray(value) && (value.length === 0 || value.length > 128))
46297
- throw new Error("Classifier Profiles requires between 1 and 128 profiles.");
46298
- const detached = snapshotClassifierJson(value, "Classifier Profiles", new ClassifierValueBudget(check), true);
46892
+ throw new Error("Decision AI Profiles requires between 1 and 128 profiles.");
46893
+ const detached = snapshotClassifierJson(value, "Decision AI Profiles", new ClassifierValueBudget(check), true);
46299
46894
  return (Array.isArray(detached) ? detached : [detached]).map(normalizeDetachedProfile);
46300
46895
  }
46301
46896
  function resolveClassifierProfile(data, inputs, context) {
46302
46897
  var _a, _b, _c;
46303
46898
  const provider = getClassifierProvider(data.provider);
46304
46899
  const model = data.useModelInput ? (_a = classifierInputDataValue(inputs, "model")) == null ? void 0 : _a.value : ((_b = data.model) == null ? void 0 : _b.trim()) || provider.defaultModel;
46305
- if (typeof model !== "string" || !model.trim()) throw new Error("Classifier Profile model is required.");
46900
+ if (typeof model !== "string" || !model.trim()) throw new Error("Decision AI Profile model is required.");
46306
46901
  let value;
46307
46902
  try {
46308
46903
  value = resolveClassifierApiKey({
@@ -46318,7 +46913,12 @@ function resolveClassifierProfile(data, inputs, context) {
46318
46913
  }
46319
46914
  return normalizeClassifierProfileValue({
46320
46915
  version: 1,
46321
- configuration: { ...pickClassifierProfileData(data), provider: provider.id, model, useModelInput: false },
46916
+ configuration: {
46917
+ ...pickClassifierProfileData({ ...data, tokenPricing: validateTokenPricing(data.tokenPricing) }),
46918
+ provider: provider.id,
46919
+ model,
46920
+ useModelInput: false
46921
+ },
46322
46922
  credential: value === void 0 ? {} : { value },
46323
46923
  profileName: context.node.title,
46324
46924
  sourceNodeId: context.node.id
@@ -46344,6 +46944,107 @@ function classifierProfileHealthIdentity(profile, projectId, fallbackNodeId) {
46344
46944
  };
46345
46945
  }
46346
46946
 
46947
+ // src/model/AgentResponseTracePresentation.ts
46948
+ function getProfileDisplayName(name, family) {
46949
+ return family === "classifier" && name === "Classifier Profile" ? "Decision AI Profile" : name;
46950
+ }
46951
+ function buildAgentProfileAttemptInspectorRows(attempts) {
46952
+ return attempts.map((attempt) => {
46953
+ var _a;
46954
+ return {
46955
+ eventId: attempt.eventId,
46956
+ providerAndModel: [
46957
+ ...attempt.profileName == null || attempt.profileName.trim() === "" ? [] : [`Profile: ${getProfileDisplayName(attempt.profileName, attempt.family).trim()}`],
46958
+ `${formatProvider(attempt)} / ${attempt.model}`
46959
+ ].join(" \xB7 "),
46960
+ context: [
46961
+ ((_a = attempt.failureKind) == null ? void 0 : _a.replaceAll("-", " ")) ?? describeStage(attempt.stage),
46962
+ describeOutcome(attempt),
46963
+ attempt.profileIndex == null ? void 0 : `profile ${attempt.profileIndex + 1}`,
46964
+ attempt.family === "classifier" ? void 0 : `round ${attempt.roundIndex + 1}`,
46965
+ attempt.attemptIndex == null ? void 0 : `attempt ${attempt.attemptIndex + 1}`,
46966
+ attempt.status == null ? void 0 : `HTTP ${attempt.status}`,
46967
+ attempt.durationMs == null ? isClassifierRequest(attempt) ? "duration unavailable" : void 0 : `${(attempt.durationMs / 1e3).toFixed(2)} sec`,
46968
+ attempt.classifierUsage == null ? isClassifierRequest(attempt) ? "usage not reported" : void 0 : `${attempt.classifierUsage.inputTokens} input / ${attempt.classifierUsage.outputTokens} output tokens`,
46969
+ attempt.classifierUsage == null ? isClassifierRequest(attempt) ? "cost unknown" : void 0 : attempt.classifierUsage.estimatedCostUsd == null ? "cost unknown" : `estimated $${attempt.classifierUsage.estimatedCostUsd.toPrecision(4)}`
46970
+ ].filter((value) => value != null).join(" / "),
46971
+ ...attempt.error == null ? {} : { error: attempt.error }
46972
+ };
46973
+ });
46974
+ }
46975
+ function isClassifierRequest(attempt) {
46976
+ return attempt.family === "classifier" && attempt.attemptIndex != null;
46977
+ }
46978
+ function getClassifierRequestCount(trace) {
46979
+ var _a;
46980
+ if (trace.summary.classifierRequestCount != null) return trace.summary.classifierRequestCount;
46981
+ const attempts = (_a = trace.profileAttempts) == null ? void 0 : _a.filter((attempt) => attempt.family === "classifier");
46982
+ if (trace.scope !== "classifier-invocation" && !(attempts == null ? void 0 : attempts.length)) return void 0;
46983
+ return (attempts == null ? void 0 : attempts.filter(isClassifierRequest).length) ?? 0;
46984
+ }
46985
+ function formatClassifierRequestCount(trace) {
46986
+ const count = getClassifierRequestCount(trace);
46987
+ if (count == null) return void 0;
46988
+ return trace.summary.classifierRequestCount == null && (trace.omittedProfileAttemptCount ?? 0) > 0 ? `${count} (retained evidence only)` : String(count);
46989
+ }
46990
+ function getProfileAttemptOmissionNotice(trace) {
46991
+ const omitted = trace.omittedProfileAttemptCount ?? 0;
46992
+ return omitted > 0 ? `${omitted} additional profile-attempt rows (requests or decisions) omitted by the trace limit.` : void 0;
46993
+ }
46994
+ function formatProvider(attempt) {
46995
+ return attempt.provider === "custom" ? getCustomProviderApiContract(attempt.customProviderApi).label : attempt.provider;
46996
+ }
46997
+ function describeStage(stage) {
46998
+ switch (stage) {
46999
+ case "health-gate":
47000
+ return "reliability check";
47001
+ case "health-update":
47002
+ return "reliability update";
47003
+ case "response-validation":
47004
+ return "response validation";
47005
+ default:
47006
+ return stage;
47007
+ }
47008
+ }
47009
+ function describeOutcome(attempt) {
47010
+ if (attempt.skipReason === "unreached") return "not reached";
47011
+ if (attempt.healthDisposition === "deny") {
47012
+ return attempt.retryAt == null ? "profile suspended; skipped" : `profile suspended until ${new Date(attempt.retryAt).toLocaleString()}`;
47013
+ }
47014
+ if (attempt.healthDisposition === "fail-open") {
47015
+ return "reliability service unavailable; profile request continued";
47016
+ }
47017
+ if (attempt.timeoutKind === "first-output") return "first output timed out";
47018
+ if (attempt.timeoutKind === "stream-inactivity") return "stream became inactive";
47019
+ if (attempt.timeoutKind === "response") return "response timed out";
47020
+ if (attempt.stage === "health-update" && attempt.healthOutcome) {
47021
+ return `recorded ${describeReliabilityOutcome(attempt.healthOutcome)}${describeReliabilityState(attempt.healthState)}`;
47022
+ }
47023
+ return `${attempt.outcome}${describeReliabilityState(attempt.healthState)}`;
47024
+ }
47025
+ function describeReliabilityOutcome(outcome) {
47026
+ switch (outcome) {
47027
+ case "healthy":
47028
+ return "success";
47029
+ case "unhealthy":
47030
+ return "failure";
47031
+ default:
47032
+ return "ignored result";
47033
+ }
47034
+ }
47035
+ function describeReliabilityState(state) {
47036
+ switch (state) {
47037
+ case "open":
47038
+ return "; profile suspended";
47039
+ case "half-open":
47040
+ return "; recovery attempt in progress";
47041
+ case "closed":
47042
+ return "; profile available";
47043
+ default:
47044
+ return "";
47045
+ }
47046
+ }
47047
+
46347
47048
  // src/model/classifier/profileExecution.ts
46348
47049
  function classifierProfileSummary(profiles, attempts) {
46349
47050
  return profiles.map((profile, index) => {
@@ -46369,20 +47070,20 @@ function classifierProfileSummary(profiles, attempts) {
46369
47070
  outcome !== "suspended" && healthState === "open" ? "; profile is suspended" : "",
46370
47071
  healthState === "half-open" ? "; recovery attempt in progress" : ""
46371
47072
  ].join("");
46372
- return `${index + 1}. ${profile.profileName || "Classifier Profile"} (${profile.configuration.provider}/${profile.configuration.model}): ${outcome}${details}`;
47073
+ return `${index + 1}. ${getProfileDisplayName(profile.profileName, "classifier") || "Decision AI Profile"} (${profile.configuration.provider}/${profile.configuration.model}): ${outcome}${details}`;
46373
47074
  }).join("\n");
46374
47075
  }
46375
47076
  var ClassifierProfileExhaustedError = class extends Error {
46376
47077
  constructor(attempts, summary, options2, statusCode) {
46377
47078
  const details = attempts.filter((attempt) => attempt.outcome === "failure" || attempt.outcome === "aborted").map((attempt) => {
46378
- const profile = `Profile ${(attempt.profileIndex ?? 0) + 1}${attempt.profileName ? ` (${attempt.profileName})` : ""}`;
47079
+ const profile = `Profile ${(attempt.profileIndex ?? 0) + 1}${attempt.profileName ? ` (${getProfileDisplayName(attempt.profileName, "classifier")})` : ""}`;
46379
47080
  const request = attempt.attemptIndex === void 0 ? "" : ` attempt ${attempt.attemptIndex + 1}`;
46380
47081
  const status = attempt.status === void 0 ? "" : ` (HTTP ${attempt.status})`;
46381
47082
  const reason = attempt.error ? `: ${attempt.error.replace(/\r\n|\r|\n/g, "\n ")}` : "";
46382
47083
  return `${profile}, ${attempt.failureKind ?? attempt.stage}${request} ${attempt.outcome}${status}${reason}`;
46383
47084
  }).join("\n");
46384
47085
  super(
46385
- `Classifier profile chain exhausted.
47086
+ `Decision AI profile chain exhausted.
46386
47087
  ${summary}${details ? `
46387
47088
 
46388
47089
  Attempt details:
@@ -46392,21 +47093,22 @@ ${details}` : ""}`,
46392
47093
  this.attempts = attempts;
46393
47094
  this.summary = summary;
46394
47095
  this.statusCode = statusCode;
46395
- this.name = "ClassifierProfileExhaustedError";
47096
+ this.name = "DecisionAIProfileExhaustedError";
46396
47097
  }
46397
47098
  };
46398
47099
  async function runClassifierProfiles(input) {
46399
47100
  var _a, _b;
46400
47101
  const attempts = [];
46401
47102
  const { context } = input;
47103
+ const deadline = input.deadline ?? Infinity;
46402
47104
  let lastError;
46403
47105
  let httpFailuresOnly = true;
46404
47106
  let lastHttpStatus;
46405
- const record3 = (attempt) => {
47107
+ const record4 = (attempt) => {
46406
47108
  var _a2;
46407
47109
  const event = {
46408
47110
  ...attempt,
46409
- ...attempt.stage === "health-update" && attempt.outcome === "failure" ? { error: "Classifier profile health service unavailable." } : {},
47111
+ ...attempt.stage === "health-update" && attempt.outcome === "failure" ? { error: "Decision AI profile health service unavailable." } : {},
46410
47112
  family: "classifier",
46411
47113
  profileName: (_a2 = input.profiles[attempt.profileIndex ?? 0]) == null ? void 0 : _a2.profileName
46412
47114
  };
@@ -46418,10 +47120,10 @@ async function runClassifierProfiles(input) {
46418
47120
  };
46419
47121
  for (let profileIndex = 0; profileIndex < input.profiles.length; profileIndex++) {
46420
47122
  context.signal.throwIfAborted();
46421
- if (Date.now() >= input.deadline) {
46422
- lastError = new ClassifierProviderError("Classifier overall deadline expired.", "timeout");
47123
+ if (Date.now() >= deadline) {
47124
+ lastError = new ClassifierProviderError("Decision AI overall deadline expired.", "timeout");
46423
47125
  const profile2 = input.profiles[profileIndex];
46424
- record3({
47126
+ record4({
46425
47127
  roundIndex: 0,
46426
47128
  profileIndex,
46427
47129
  provider: profile2.configuration.provider,
@@ -46429,7 +47131,7 @@ async function runClassifierProfiles(input) {
46429
47131
  stage: "request",
46430
47132
  outcome: "failure",
46431
47133
  failureKind: "timeout",
46432
- error: "Classifier overall deadline expired."
47134
+ error: "Decision AI overall deadline expired."
46433
47135
  });
46434
47136
  httpFailuresOnly = false;
46435
47137
  break;
@@ -46449,7 +47151,7 @@ async function runClassifierProfiles(input) {
46449
47151
  try {
46450
47152
  const begin = await runBoundedHealthOperation({
46451
47153
  operation: "begin",
46452
- timeoutMs: Math.max(1, Math.min(2e3, input.deadline - Date.now())),
47154
+ timeoutMs: Math.max(1, Math.min(2e3, deadline - Date.now())),
46453
47155
  signal: context.signal,
46454
47156
  run: () => store.begin(health),
46455
47157
  onLateResolve: async (late) => {
@@ -46458,19 +47160,19 @@ async function runClassifierProfiles(input) {
46458
47160
  }
46459
47161
  });
46460
47162
  if (begin.disposition === "deny") {
46461
- record3({
47163
+ record4({
46462
47164
  ...base,
46463
47165
  stage: "health-gate",
46464
47166
  outcome: "skipped",
46465
47167
  healthDisposition: "deny",
46466
47168
  healthState: begin.state,
46467
47169
  retryAt: begin.retryAt,
46468
- error: "Classifier profile is suspended."
47170
+ error: "Decision AI profile is suspended."
46469
47171
  });
46470
47172
  continue;
46471
47173
  }
46472
47174
  if (!begin.permitId) throw new Error("Profile health service did not return a permit.");
46473
- record3({
47175
+ record4({
46474
47176
  ...base,
46475
47177
  stage: "health-gate",
46476
47178
  outcome: "success",
@@ -46487,34 +47189,35 @@ async function runClassifierProfiles(input) {
46487
47189
  operationTimeoutMs: 2e3,
46488
47190
  executionCorrelationId: context.llmProfileHealthExecutionCorrelationId,
46489
47191
  signal: context.signal,
46490
- recordAttempt: record3
47192
+ recordAttempt: record4
46491
47193
  });
46492
47194
  } catch {
46493
47195
  context.signal.throwIfAborted();
46494
- record3({
47196
+ record4({
46495
47197
  ...base,
46496
47198
  stage: "health-gate",
46497
47199
  outcome: "failure",
46498
47200
  healthDisposition: "fail-open",
46499
- error: "Classifier profile health service unavailable."
47201
+ error: "Decision AI profile health service unavailable."
46500
47202
  });
46501
47203
  }
46502
47204
  }
46503
47205
  try {
46504
47206
  context.signal.throwIfAborted();
46505
47207
  if (!provider.browserExecutionSupported && context.executor === "browser")
46506
- throw new ClassifierProviderError("Classifier provider requires the Node executor.", "capability");
47208
+ throw new ClassifierProviderError("Decision AI provider requires the Node executor.", "capability");
46507
47209
  if (!((_b = profile.credential.value) == null ? void 0 : _b.trim()))
46508
- throw new ClassifierProviderError("Classifier Profile API key is not set.", "configuration");
46509
- const remainingMs = input.deadline - Date.now();
47210
+ throw new ClassifierProviderError("Decision AI Profile API key is not set.", "configuration");
47211
+ const remainingMs = deadline - Date.now();
46510
47212
  const timeoutMs = health ? Math.min(classifierProfileResponseTimeout(profile.configuration), remainingMs) : remainingMs;
46511
- if (timeoutMs <= 0) throw new ClassifierProviderError("Classifier overall deadline expired.", "timeout");
47213
+ if (timeoutMs <= 0) throw new ClassifierProviderError("Decision AI overall deadline expired.", "timeout");
46512
47214
  const result = await provider.evaluate({
46513
47215
  ...input.state,
46514
47216
  questions: input.questions,
46515
47217
  apiKey: profile.credential.value,
47218
+ tokenPricing: profile.configuration.tokenPricing,
46516
47219
  model,
46517
- timeoutMs,
47220
+ ...Number.isFinite(timeoutMs) ? { timeoutMs } : {},
46518
47221
  deadline: input.deadline,
46519
47222
  signal: context.signal,
46520
47223
  retryOnNon200: input.retryOnNon200,
@@ -46526,7 +47229,7 @@ async function runClassifierProfiles(input) {
46526
47229
  observedRequest = true;
46527
47230
  observedAbort = attempt.outcome === "aborted";
46528
47231
  lastPhysicalFailure = attempt.outcome === "failure" ? { kind, status: attempt.status } : void 0;
46529
- record3({
47232
+ record4({
46530
47233
  ...base,
46531
47234
  ...attempt,
46532
47235
  stage: kind === "response-validation" || kind === "response-parsing" ? "response-validation" : "request",
@@ -46536,15 +47239,13 @@ async function runClassifierProfiles(input) {
46536
47239
  }
46537
47240
  });
46538
47241
  context.signal.throwIfAborted();
46539
- if (Date.now() >= input.deadline)
46540
- throw new ClassifierProviderError("Classifier overall deadline expired.", "timeout");
47242
+ if (Date.now() >= deadline) throw new ClassifierProviderError("Decision AI overall deadline expired.", "timeout");
46541
47243
  await (permit == null ? void 0 : permit.finish("healthy"));
46542
47244
  context.signal.throwIfAborted();
46543
- if (Date.now() >= input.deadline)
46544
- throw new ClassifierProviderError("Classifier overall deadline expired.", "timeout");
47245
+ if (Date.now() >= deadline) throw new ClassifierProviderError("Decision AI overall deadline expired.", "timeout");
46545
47246
  for (let unreached = profileIndex + 1; unreached < input.profiles.length; unreached++) {
46546
47247
  const candidate = input.profiles[unreached];
46547
- record3({
47248
+ record4({
46548
47249
  roundIndex: 0,
46549
47250
  profileIndex: unreached,
46550
47251
  provider: candidate.configuration.provider,
@@ -46554,7 +47255,7 @@ async function runClassifierProfiles(input) {
46554
47255
  skipReason: "unreached"
46555
47256
  });
46556
47257
  }
46557
- return { result, provider, model };
47258
+ return { result, provider, model, tokenPricing: profile.configuration.tokenPricing };
46558
47259
  } catch (error) {
46559
47260
  lastError = error;
46560
47261
  const providerError = error instanceof ClassifierProviderError ? error : void 0;
@@ -46563,7 +47264,7 @@ async function runClassifierProfiles(input) {
46563
47264
  if (httpFailure) lastHttpStatus = providerError.statusCode;
46564
47265
  const alreadyReported = context.signal.aborted && observedAbort || providerError && (lastPhysicalFailure == null ? void 0 : lastPhysicalFailure.kind) === providerError.kind && (providerError.kind !== "http" || lastPhysicalFailure.status === providerError.statusCode);
46565
47266
  if (!alreadyReported)
46566
- record3({
47267
+ record4({
46567
47268
  ...base,
46568
47269
  stage: providerError ? providerError.kind === "configuration" || providerError.kind === "capability" ? "configuration" : providerError.kind === "response-validation" || providerError.kind === "response-parsing" ? "response-validation" : "request" : "configuration",
46569
47270
  failureKind: context.signal.aborted ? void 0 : providerError ? classifierFailureKind(providerError.kind, providerError.statusCode) : "configuration",
@@ -46575,17 +47276,17 @@ async function runClassifierProfiles(input) {
46575
47276
  const unhealthy = (providerError == null ? void 0 : providerError.kind) === "timeout" || (providerError == null ? void 0 : providerError.kind) === "transport" || (providerError == null ? void 0 : providerError.kind) === "http" && (providerError.statusCode === 408 || providerError.statusCode === 429 || (providerError.statusCode ?? 0) >= 500);
46576
47277
  await (permit == null ? void 0 : permit.finish(!context.signal.aborted && observedRequest && unhealthy ? "unhealthy" : "ignored"));
46577
47278
  context.signal.throwIfAborted();
46578
- if (Date.now() >= input.deadline) {
47279
+ if (Date.now() >= deadline) {
46579
47280
  httpFailuresOnly = false;
46580
- lastError = new ClassifierProviderError("Classifier overall deadline expired.", "timeout", void 0, {
47281
+ lastError = new ClassifierProviderError("Decision AI overall deadline expired.", "timeout", void 0, {
46581
47282
  cause: error
46582
47283
  });
46583
47284
  if ((providerError == null ? void 0 : providerError.kind) !== "timeout")
46584
- record3({
47285
+ record4({
46585
47286
  ...base,
46586
47287
  stage: "request",
46587
47288
  outcome: "failure",
46588
- error: "Classifier overall deadline expired.",
47289
+ error: "Decision AI overall deadline expired.",
46589
47290
  failureKind: "timeout"
46590
47291
  });
46591
47292
  break;
@@ -46609,13 +47310,13 @@ var ClassifierEvaluateNodeImpl = class extends NodeImpl {
46609
47310
  static create() {
46610
47311
  return {
46611
47312
  type: "classifierEvaluate",
46612
- title: "Classifier Evaluate",
47313
+ title: "Decision AI run",
46613
47314
  id: (0, import_non_secure110.nanoid)(),
46614
47315
  visualData: { x: 0, y: 0, width: 260 },
46615
47316
  // Keep the default model in the provider descriptor rather than
46616
47317
  // serializing Jev's model into every new node. A future provider then
46617
47318
  // receives its own default when an author changes the Provider field.
46618
- data: { provider: "jev", timeoutMs: 3e4, errorOnNon200: true, catchRequestFailed: false }
47319
+ data: { provider: "jev", errorOnNon200: true, catchRequestFailed: false }
46619
47320
  };
46620
47321
  }
46621
47322
  getInputDefinitions(connections) {
@@ -46643,12 +47344,12 @@ var ClassifierEvaluateNodeImpl = class extends NodeImpl {
46643
47344
  if (this.data.configurationMode === "profile") {
46644
47345
  inputs.unshift({
46645
47346
  id: "classifierProfile",
46646
- title: "Classifier Profiles",
47347
+ title: "Decision AI Profiles",
46647
47348
  dataType: ["classifier-config", "classifier-config[]"],
46648
47349
  required: true,
46649
47350
  coerced: true,
46650
47351
  splitRunBehavior: "preserve-array",
46651
- description: "One Classifier Profile or an ordered fallback chain."
47352
+ description: "One Decision AI Profile or an ordered fallback chain."
46652
47353
  });
46653
47354
  }
46654
47355
  if (this.data.configurationMode !== "profile" && this.data.useModelInput) {
@@ -46687,11 +47388,11 @@ var ClassifierEvaluateNodeImpl = class extends NodeImpl {
46687
47388
  outputs.push({ id: "responseBody", title: "Response body", dataType: "object" });
46688
47389
  }
46689
47390
  if (this.data.outputClassifierAttempts)
46690
- outputs.push({ id: "classifierAttempts", title: "Classifier Attempts", dataType: "object[]" });
47391
+ outputs.push({ id: "classifierAttempts", title: "Decision AI Attempts", dataType: "object[]" });
46691
47392
  if (this.data.configurationMode === "profile" && this.data.outputClassifierProfileSummary)
46692
47393
  outputs.push({
46693
47394
  id: "classifierProfileSummary",
46694
- title: "Classifier Profile Summary",
47395
+ title: "Decision AI Profile Summary",
46695
47396
  dataType: "string"
46696
47397
  });
46697
47398
  return [...outputs, ...getRunFailureOutputDefinitions({ catchRequestFailed: this.data.catchRequestFailed })];
@@ -46699,7 +47400,11 @@ var ClassifierEvaluateNodeImpl = class extends NodeImpl {
46699
47400
  getEditors() {
46700
47401
  return [
46701
47402
  { type: "custom", label: "Configuration", customEditorId: "ClassifierConfiguration" },
46702
- { ...getClassifierModelEditor(this.data), hideIf: (data) => data.configurationMode === "profile" },
47403
+ { ...getClassifierModelEditor(), hideIf: (data) => data.configurationMode === "profile" },
47404
+ {
47405
+ ...getTokenPricingEditor(),
47406
+ hideIf: (data) => data.configurationMode === "profile"
47407
+ },
46703
47408
  {
46704
47409
  type: "group",
46705
47410
  label: "Outputs",
@@ -46708,13 +47413,13 @@ var ClassifierEvaluateNodeImpl = class extends NodeImpl {
46708
47413
  type: "toggle",
46709
47414
  label: "Usage details",
46710
47415
  dataKey: "outputUsage",
46711
- helperMessage: "Adds estimated totalCost to Usage only for recognized requested/returned models. Unknown pricing is omitted. Provider-specific premiums are not included."
47416
+ helperMessage: "Adds estimated totalCost to Usage using explicit token prices or known model rates. Unknown pricing is omitted. Provider-specific premiums are not included."
46712
47417
  },
46713
47418
  {
46714
47419
  type: "toggle",
46715
47420
  label: "Request body",
46716
47421
  dataKey: "outputRequestBody",
46717
- helperMessage: "Adds the exact classifier request JSON body sent to the provider. It excludes authorization headers and Rivet-managed API keys."
47422
+ helperMessage: "Adds the exact Decision AI request JSON body sent to the provider. It excludes authorization headers and Rivet-managed API keys."
46718
47423
  },
46719
47424
  {
46720
47425
  type: "toggle",
@@ -46722,31 +47427,15 @@ var ClassifierEvaluateNodeImpl = class extends NodeImpl {
46722
47427
  dataKey: "outputResponseBody",
46723
47428
  helperMessage: "Shows the provider response, including rejected or invalid responses. Non-JSON responses appear as raw text. Captured content may contain sensitive input."
46724
47429
  },
46725
- { type: "toggle", label: "Classifier attempts", dataKey: "outputClassifierAttempts" },
47430
+ { type: "toggle", label: "Decision AI attempts", dataKey: "outputClassifierAttempts" },
46726
47431
  {
46727
47432
  type: "toggle",
46728
- label: "Classifier profile summary",
47433
+ label: "Decision AI profile summary",
46729
47434
  dataKey: "outputClassifierProfileSummary",
46730
47435
  hideIf: (data) => data.configurationMode !== "profile"
46731
47436
  }
46732
47437
  ]
46733
47438
  },
46734
- {
46735
- type: "group",
46736
- label: "Advanced",
46737
- editors: [
46738
- {
46739
- type: "number",
46740
- label: "Overall timeout (seconds)",
46741
- dataKey: this.data.configurationMode === "profile" ? "profileChainTimeoutMs" : "timeoutMs",
46742
- defaultValue: this.data.configurationMode === "profile" ? 18e4 : 3e4,
46743
- storageMultiplier: 1e3,
46744
- min: 1e3,
46745
- max: 6e5,
46746
- step: 1e3
46747
- }
46748
- ]
46749
- },
46750
47439
  {
46751
47440
  type: "group",
46752
47441
  label: "Error behavior",
@@ -46809,10 +47498,10 @@ var ClassifierEvaluateNodeImpl = class extends NodeImpl {
46809
47498
  }
46810
47499
  static getUIData() {
46811
47500
  return {
46812
- contextMenuTitle: "Classifier Evaluate",
46813
- infoBoxTitle: "Classifier Evaluate",
46814
- infoBoxBody: "Evaluates shared state and optional images against typed classifier questions. Images are shared evidence for every question.",
46815
- group: ["Classifier"]
47501
+ contextMenuTitle: "Decision AI run",
47502
+ infoBoxTitle: "Decision AI run",
47503
+ infoBoxBody: "Evaluates shared state and optional images against typed Decision AI questions. Images are shared evidence for every question.",
47504
+ group: ["Decision AI"]
46816
47505
  };
46817
47506
  }
46818
47507
  async process(inputs, context) {
@@ -46867,13 +47556,12 @@ var ClassifierEvaluateNodeImpl = class extends NodeImpl {
46867
47556
  async processRun(inputs, context, attempts, diagnostics) {
46868
47557
  var _a, _b, _c, _d;
46869
47558
  if (this.data.configurationMode !== void 0 && this.data.configurationMode !== "inline" && this.data.configurationMode !== "profile")
46870
- throw new Error("Unknown classifier configuration mode.");
46871
- const timeoutMs = this.data.configurationMode === "profile" ? normalizeTimeout(this.data.profileChainTimeoutMs ?? 18e4) : normalizeTimeout(this.data.timeoutMs);
46872
- const deadline = Date.now() + timeoutMs;
46873
- const checkPreparation = classifierPreparationCheck(context.signal, deadline, timeoutMs);
47559
+ throw new Error("Unknown Decision AI configuration mode.");
47560
+ const checkPreparation = () => context.signal.throwIfAborted();
46874
47561
  checkPreparation();
46875
47562
  if (this.data.configurationMode === "profile")
46876
- return this.processProfiles(inputs, context, deadline, checkPreparation, attempts, diagnostics);
47563
+ return this.processProfiles(inputs, context, checkPreparation, attempts, diagnostics);
47564
+ const tokenPricing = validateTokenPricing(this.data.tokenPricing);
46877
47565
  const provider = getClassifierProvider(this.data.provider);
46878
47566
  if (!provider.browserExecutionSupported && context.executor === "browser") {
46879
47567
  throw new Error(
@@ -46913,9 +47601,10 @@ var ClassifierEvaluateNodeImpl = class extends NodeImpl {
46913
47601
  flattenQuestions(input.value, questions, checkPreparation, /* @__PURE__ */ new Set(), 0, flattenWork);
46914
47602
  }
46915
47603
  }
46916
- if (questions.length === 0) throw new Error("Classifier Evaluate requires at least one question.");
47604
+ if (questions.length === 0) throw new Error("Decision AI run requires at least one question.");
46917
47605
  const result = await (provider.evaluateInput ?? provider.evaluate).call(provider, {
46918
47606
  apiKey,
47607
+ tokenPricing,
46919
47608
  model: modelValue,
46920
47609
  questions,
46921
47610
  retryOnNon200: this.data.retryOnNon200,
@@ -46923,8 +47612,6 @@ var ClassifierEvaluateNodeImpl = class extends NodeImpl {
46923
47612
  retryOnNon200RepeatTimes: this.data.retryOnNon200RepeatTimes,
46924
47613
  signal: context.signal,
46925
47614
  ...state,
46926
- timeoutMs,
46927
- deadline,
46928
47615
  ...diagnostics,
46929
47616
  onAttempt: ({ kind, ...attempt }) => {
46930
47617
  var _a2;
@@ -46948,13 +47635,21 @@ var ClassifierEvaluateNodeImpl = class extends NodeImpl {
46948
47635
  }
46949
47636
  });
46950
47637
  checkPreparation();
46951
- return { ...this.projectResult(provider, modelValue, result, checkPreparation), ...this.profileEvidence(attempts) };
47638
+ return {
47639
+ ...this.projectResult(provider, modelValue, result, checkPreparation, tokenPricing),
47640
+ ...this.profileEvidence(attempts)
47641
+ };
46952
47642
  }
46953
- projectResult(provider, modelValue, result, checkPreparation) {
46954
- const totalCost = calculateClassifierUsageCost(provider, result.response.usage, {
46955
- requestedModel: modelValue,
46956
- responseModel: result.response.model
46957
- });
47643
+ projectResult(provider, modelValue, result, checkPreparation, tokenPricing) {
47644
+ const totalCost = calculateClassifierUsageCost(
47645
+ provider,
47646
+ result.response.usage,
47647
+ {
47648
+ requestedModel: modelValue,
47649
+ responseModel: result.response.model
47650
+ },
47651
+ tokenPricing
47652
+ );
46958
47653
  const usage = !this.data.outputUsage || totalCost === void 0 ? result.response.usage : { ...result.response.usage, totalCost };
46959
47654
  const outputs = {
46960
47655
  ["answers"]: { type: "object", value: result.response.answers },
@@ -46977,7 +47672,7 @@ var ClassifierEvaluateNodeImpl = class extends NodeImpl {
46977
47672
  ...this.data.configurationMode === "profile" && this.data.outputClassifierProfileSummary && summary !== void 0 ? { ["classifierProfileSummary"]: { type: "string", value: summary } } : {}
46978
47673
  };
46979
47674
  }
46980
- async processProfiles(inputs, context, deadline, check, attempts, diagnostics) {
47675
+ async processProfiles(inputs, context, check, attempts, diagnostics) {
46981
47676
  var _a, _b, _c;
46982
47677
  const profiles = normalizeClassifierProfiles((_a = classifierInputDataValue(inputs, "classifierProfile")) == null ? void 0 : _a.value, check);
46983
47678
  const graph = (_c = context.project) == null ? void 0 : _c.graphs[(_b = context.execution) == null ? void 0 : _b.graphId];
@@ -46994,7 +47689,7 @@ var ClassifierEvaluateNodeImpl = class extends NodeImpl {
46994
47689
  const input = classifierInputDataValue(inputs, port);
46995
47690
  if (input) flattenQuestions(input.value, values2, check, /* @__PURE__ */ new Set(), 0, work);
46996
47691
  }
46997
- if (!values2.length) throw new Error("Classifier Evaluate requires at least one question.");
47692
+ if (!values2.length) throw new Error("Decision AI run requires at least one question.");
46998
47693
  const ids = /* @__PURE__ */ new Set();
46999
47694
  const questions = values2.map((value) => {
47000
47695
  const question = prepareClassifierQuestion(value, budget);
@@ -47009,7 +47704,6 @@ var ClassifierEvaluateNodeImpl = class extends NodeImpl {
47009
47704
  questions,
47010
47705
  context,
47011
47706
  nodeId: this.chartNode.id,
47012
- deadline,
47013
47707
  retryOnNon200: this.data.retryOnNon200,
47014
47708
  retryOnNon200RepeatTimes: this.data.retryOnNon200RepeatTimes,
47015
47709
  retryOnNon200CooldownMs: this.data.retryOnNon200CooldownMs,
@@ -47027,12 +47721,12 @@ var ClassifierEvaluateNodeImpl = class extends NodeImpl {
47027
47721
  });
47028
47722
  check();
47029
47723
  return {
47030
- ...this.projectResult(selected.provider, selected.model, selected.result, check),
47724
+ ...this.projectResult(selected.provider, selected.model, selected.result, check, selected.tokenPricing),
47031
47725
  ...this.profileEvidence(attempts, classifierProfileSummary(profiles, attempts))
47032
47726
  };
47033
47727
  }
47034
47728
  };
47035
- function getClassifierModelEditor(data) {
47729
+ function getClassifierModelEditor() {
47036
47730
  return {
47037
47731
  type: "group",
47038
47732
  label: "Model",
@@ -47046,11 +47740,11 @@ function getClassifierModelEditor(data) {
47046
47740
  options: classifierProviders.map((provider) => ({ value: provider.id, label: provider.label }))
47047
47741
  },
47048
47742
  {
47049
- type: "string",
47743
+ type: "custom",
47050
47744
  label: "Model",
47051
47745
  dataKey: "model",
47052
47746
  useInputToggleDataKey: "useModelInput",
47053
- placeholder: getProviderForDisplay(data.provider).defaultModel
47747
+ customEditorId: "ClassifierModel"
47054
47748
  },
47055
47749
  {
47056
47750
  type: "segmented",
@@ -47060,7 +47754,7 @@ function getClassifierModelEditor(data) {
47060
47754
  defaultValue: "configured",
47061
47755
  options: [
47062
47756
  { value: "configured", label: "Automatic" },
47063
- { value: "classifier-settings", label: "Classifier settings" },
47757
+ { value: "classifier-settings", label: "Decision AI settings" },
47064
47758
  { value: "input", label: "Input port" }
47065
47759
  ],
47066
47760
  helperMessage: getApiKeySourceHelperMessage2
@@ -47069,7 +47763,7 @@ function getClassifierModelEditor(data) {
47069
47763
  type: "custom",
47070
47764
  label: "Configured API key names",
47071
47765
  customEditorId: "ClassifierCredentialNames",
47072
- hideIf: (data2) => data2.apiKeySource === "input" || data2.apiKeySource === "classifier-settings"
47766
+ hideIf: (data) => data.apiKeySource === "input" || data.apiKeySource === "classifier-settings"
47073
47767
  }
47074
47768
  ]
47075
47769
  };
@@ -47126,8 +47820,8 @@ function getApiKeySourceHelperMessage2(data) {
47126
47820
  if (data.apiKeySource === "input") return "Uses the API Key input port instead of a configured provider key.";
47127
47821
  const provider = getProviderForDisplay(data.provider);
47128
47822
  if (data.apiKeySource === "classifier-settings")
47129
- return `Uses only Settings > Classifier > ${provider.label} API Key on the executor. Does not fall back to named or environment credentials.`;
47130
- 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.";
47823
+ return `Uses only Settings > Decision AI > ${provider.label} API Key on the executor. Does not fall back to named or environment credentials.`;
47824
+ return "Automatic checks the named programmatic setting, then the named environment variable, then the saved Decision AI 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.";
47131
47825
  }
47132
47826
  function flattenQuestions(value, target, check, seen = /* @__PURE__ */ new Set(), depth = 0, work = { values: 0 }) {
47133
47827
  check();
@@ -47136,8 +47830,7 @@ function flattenQuestions(value, target, check, seen = /* @__PURE__ */ new Set()
47136
47830
  if (Array.isArray(value)) {
47137
47831
  if (seen.has(value)) throw new Error("Question inputs must not contain circular arrays.");
47138
47832
  seen.add(value);
47139
- if (value.length > CLASSIFIER_LIMITS.questions)
47140
- throw new Error("Classifier Evaluate supports at most 1000 questions.");
47833
+ if (value.length > CLASSIFIER_LIMITS.questions) throw new Error("Decision AI run supports at most 1000 questions.");
47141
47834
  for (const item of classifierArrayValues(value, "Questions"))
47142
47835
  flattenQuestions(item, target, check, seen, depth + 1, work);
47143
47836
  seen.delete(value);
@@ -47146,14 +47839,10 @@ function flattenQuestions(value, target, check, seen = /* @__PURE__ */ new Set()
47146
47839
  if (typeof value !== "object" || value === null) {
47147
47840
  throw new Error("Question inputs must contain question definition objects or nested arrays of definitions.");
47148
47841
  }
47149
- if (target.length >= CLASSIFIER_LIMITS.questions)
47150
- throw new Error("Classifier Evaluate supports at most 1000 questions.");
47842
+ if (target.length >= CLASSIFIER_LIMITS.questions) throw new Error("Decision AI run supports at most 1000 questions.");
47151
47843
  target.push(value);
47152
47844
  }
47153
- function normalizeTimeout(timeoutMs) {
47154
- return typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.min(timeoutMs, 6e5) : 3e4;
47155
- }
47156
- var classifierEvaluateNode = nodeDefinition(ClassifierEvaluateNodeImpl, "Classifier Evaluate");
47845
+ var classifierEvaluateNode = nodeDefinition(ClassifierEvaluateNodeImpl, "Decision AI run");
47157
47846
 
47158
47847
  // src/model/nodes/ClassifierProfileNode.ts
47159
47848
  var import_non_secure111 = require("nanoid/non-secure");
@@ -47161,7 +47850,7 @@ var ClassifierProfileNodeImpl = class extends NodeImpl {
47161
47850
  static create() {
47162
47851
  return {
47163
47852
  type: "classifierProfile",
47164
- title: "Classifier Profile",
47853
+ title: "Decision AI Profile",
47165
47854
  id: (0, import_non_secure111.nanoid)(),
47166
47855
  visualData: { x: 0, y: 0, width: 260 },
47167
47856
  data: { provider: "jev", responseTimeoutMs: DEFAULT_CLASSIFIER_PROFILE_RESPONSE_TIMEOUT_MS }
@@ -47179,16 +47868,17 @@ var ClassifierProfileNodeImpl = class extends NodeImpl {
47179
47868
  id: "profile",
47180
47869
  title: "Profile",
47181
47870
  dataType: "classifier-config",
47182
- description: "Sensitive resolved classifier configuration. Combine profiles with Array for ordered fallback."
47871
+ description: "Sensitive resolved Decision AI configuration. Combine profiles with Array for ordered fallback."
47183
47872
  }
47184
47873
  ];
47185
47874
  }
47186
47875
  getEditors() {
47187
47876
  return [
47188
- getClassifierModelEditor(this.data),
47877
+ getClassifierModelEditor(),
47878
+ getTokenPricingEditor(),
47189
47879
  {
47190
47880
  type: "group",
47191
- label: "Classifier profile suspension",
47881
+ label: "Decision AI profile suspension",
47192
47882
  editors: [
47193
47883
  {
47194
47884
  type: "info",
@@ -47260,10 +47950,10 @@ var ClassifierProfileNodeImpl = class extends NodeImpl {
47260
47950
  }
47261
47951
  static getUIData() {
47262
47952
  return {
47263
- contextMenuTitle: "Classifier Profile",
47264
- infoBoxTitle: "Classifier Profile",
47265
- infoBoxBody: "Reusable classifier provider/model/credential configuration. Combine profiles with Array for ordered fallback.",
47266
- group: ["Classifier"]
47953
+ contextMenuTitle: "Decision AI Profile",
47954
+ infoBoxTitle: "Decision AI Profile",
47955
+ infoBoxBody: "Reusable Decision AI provider/model/credential configuration. Combine profiles with Array for ordered fallback.",
47956
+ group: ["Decision AI"]
47267
47957
  };
47268
47958
  }
47269
47959
  async process(inputs, context) {
@@ -47273,7 +47963,7 @@ var ClassifierProfileNodeImpl = class extends NodeImpl {
47273
47963
  };
47274
47964
  }
47275
47965
  };
47276
- var classifierProfileNode = nodeDefinition(ClassifierProfileNodeImpl, "Classifier Profile");
47966
+ var classifierProfileNode = nodeDefinition(ClassifierProfileNodeImpl, "Decision AI Profile");
47277
47967
 
47278
47968
  // src/model/Nodes.ts
47279
47969
  var registerBuiltInNodes = (registry) => {
@@ -47340,104 +48030,6 @@ var BrowserNativeApi = class {
47340
48030
  }
47341
48031
  };
47342
48032
 
47343
- // src/model/AgentResponseTracePresentation.ts
47344
- function buildAgentProfileAttemptInspectorRows(attempts) {
47345
- return attempts.map((attempt) => {
47346
- var _a;
47347
- return {
47348
- eventId: attempt.eventId,
47349
- providerAndModel: [
47350
- ...attempt.profileName == null || attempt.profileName.trim() === "" ? [] : [`Profile: ${attempt.profileName.trim()}`],
47351
- `${formatProvider(attempt)} / ${attempt.model}`
47352
- ].join(" \xB7 "),
47353
- context: [
47354
- ((_a = attempt.failureKind) == null ? void 0 : _a.replaceAll("-", " ")) ?? describeStage(attempt.stage),
47355
- describeOutcome(attempt),
47356
- attempt.profileIndex == null ? void 0 : `profile ${attempt.profileIndex + 1}`,
47357
- attempt.family === "classifier" ? void 0 : `round ${attempt.roundIndex + 1}`,
47358
- attempt.attemptIndex == null ? void 0 : `attempt ${attempt.attemptIndex + 1}`,
47359
- attempt.status == null ? void 0 : `HTTP ${attempt.status}`,
47360
- attempt.durationMs == null ? isClassifierRequest(attempt) ? "duration unavailable" : void 0 : `${(attempt.durationMs / 1e3).toFixed(2)} sec`,
47361
- attempt.classifierUsage == null ? isClassifierRequest(attempt) ? "usage not reported" : void 0 : `${attempt.classifierUsage.inputTokens} input / ${attempt.classifierUsage.outputTokens} output tokens`,
47362
- attempt.classifierUsage == null ? isClassifierRequest(attempt) ? "cost unknown" : void 0 : attempt.classifierUsage.estimatedCostUsd == null ? "cost unknown" : `estimated $${attempt.classifierUsage.estimatedCostUsd.toPrecision(4)}`
47363
- ].filter((value) => value != null).join(" / "),
47364
- ...attempt.error == null ? {} : { error: attempt.error }
47365
- };
47366
- });
47367
- }
47368
- function isClassifierRequest(attempt) {
47369
- return attempt.family === "classifier" && attempt.attemptIndex != null;
47370
- }
47371
- function getClassifierRequestCount(trace) {
47372
- var _a;
47373
- if (trace.summary.classifierRequestCount != null) return trace.summary.classifierRequestCount;
47374
- const attempts = (_a = trace.profileAttempts) == null ? void 0 : _a.filter((attempt) => attempt.family === "classifier");
47375
- if (trace.scope !== "classifier-invocation" && !(attempts == null ? void 0 : attempts.length)) return void 0;
47376
- return (attempts == null ? void 0 : attempts.filter(isClassifierRequest).length) ?? 0;
47377
- }
47378
- function formatClassifierRequestCount(trace) {
47379
- const count = getClassifierRequestCount(trace);
47380
- if (count == null) return void 0;
47381
- return trace.summary.classifierRequestCount == null && (trace.omittedProfileAttemptCount ?? 0) > 0 ? `${count} (retained evidence only)` : String(count);
47382
- }
47383
- function getProfileAttemptOmissionNotice(trace) {
47384
- const omitted = trace.omittedProfileAttemptCount ?? 0;
47385
- return omitted > 0 ? `${omitted} additional profile-attempt rows (requests or decisions) omitted by the trace limit.` : void 0;
47386
- }
47387
- function formatProvider(attempt) {
47388
- return attempt.provider === "custom" ? getCustomProviderApiContract(attempt.customProviderApi).label : attempt.provider;
47389
- }
47390
- function describeStage(stage) {
47391
- switch (stage) {
47392
- case "health-gate":
47393
- return "reliability check";
47394
- case "health-update":
47395
- return "reliability update";
47396
- case "response-validation":
47397
- return "response validation";
47398
- default:
47399
- return stage;
47400
- }
47401
- }
47402
- function describeOutcome(attempt) {
47403
- if (attempt.skipReason === "unreached") return "not reached";
47404
- if (attempt.healthDisposition === "deny") {
47405
- return attempt.retryAt == null ? "profile suspended; skipped" : `profile suspended until ${new Date(attempt.retryAt).toLocaleString()}`;
47406
- }
47407
- if (attempt.healthDisposition === "fail-open") {
47408
- return "reliability service unavailable; profile request continued";
47409
- }
47410
- if (attempt.timeoutKind === "first-output") return "first output timed out";
47411
- if (attempt.timeoutKind === "stream-inactivity") return "stream became inactive";
47412
- if (attempt.timeoutKind === "response") return "response timed out";
47413
- if (attempt.stage === "health-update" && attempt.healthOutcome) {
47414
- return `recorded ${describeReliabilityOutcome(attempt.healthOutcome)}${describeReliabilityState(attempt.healthState)}`;
47415
- }
47416
- return `${attempt.outcome}${describeReliabilityState(attempt.healthState)}`;
47417
- }
47418
- function describeReliabilityOutcome(outcome) {
47419
- switch (outcome) {
47420
- case "healthy":
47421
- return "success";
47422
- case "unhealthy":
47423
- return "failure";
47424
- default:
47425
- return "ignored result";
47426
- }
47427
- }
47428
- function describeReliabilityState(state) {
47429
- switch (state) {
47430
- case "open":
47431
- return "; profile suspended";
47432
- case "half-open":
47433
- return "; recovery attempt in progress";
47434
- case "closed":
47435
- return "; profile available";
47436
- default:
47437
- return "";
47438
- }
47439
- }
47440
-
47441
48033
  // src/model/DebuggerTransportSentinel.ts
47442
48034
  var DEBUGGER_TRANSPORT_SENTINEL_KEY = "__rivetDebuggerTransportSentinel";
47443
48035
  var DEBUGGER_TRANSPORT_SENTINEL_VERSION = 1;
@@ -50712,8 +51304,8 @@ var PineconeKnowledgeStoreDriver = class {
50712
51304
  return (await this.#readManifest(sourceId, context)).manifest;
50713
51305
  }
50714
51306
  async #readManifest(sourceId, context) {
50715
- const namespace = this.#namespace(sourceId);
50716
- const url = `${this.config.indexHost}/vectors/fetch?ids=${encodeURIComponent(MANIFEST_RECORD_ID)}&namespace=${encodeURIComponent(namespace)}`;
51307
+ const namespace2 = this.#namespace(sourceId);
51308
+ const url = `${this.config.indexHost}/vectors/fetch?ids=${encodeURIComponent(MANIFEST_RECORD_ID)}&namespace=${encodeURIComponent(namespace2)}`;
50717
51309
  const response = await this.#request(url, { method: "GET" }, context);
50718
51310
  const indexedLsn = readPineconeLsn(response.headers, "x-pinecone-max-indexed-lsn");
50719
51311
  const payload = await parseJsonResponse(response, "fetching the knowledge-source manifest");
@@ -50746,12 +51338,12 @@ var PineconeKnowledgeStoreDriver = class {
50746
51338
  };
50747
51339
  }
50748
51340
  async upsertChunks(sourceId, version, chunks, context) {
50749
- const namespace = this.#namespace(sourceId);
51341
+ const namespace2 = this.#namespace(sourceId);
50750
51342
  const records = chunks.map((chunk) => this.#chunkRecord(sourceId, version, chunk));
50751
51343
  const batches = batchNdjson(records, 32, 15e5);
50752
51344
  for (let index = 0; index < batches.length; index += 1) {
50753
51345
  const response = await this.#request(
50754
- `${this.config.indexHost}/records/namespaces/${encodeURIComponent(namespace)}/upsert`,
51346
+ `${this.config.indexHost}/records/namespaces/${encodeURIComponent(namespace2)}/upsert`,
50755
51347
  { method: "POST", body: batches[index], headers: { "Content-Type": "application/x-ndjson" } },
50756
51348
  context
50757
51349
  );
@@ -50759,8 +51351,8 @@ var PineconeKnowledgeStoreDriver = class {
50759
51351
  }
50760
51352
  }
50761
51353
  async commitManifest(manifest, context) {
50762
- const namespace = this.#namespace(manifest.sourceId);
50763
- const record3 = {
51354
+ const namespace2 = this.#namespace(manifest.sourceId);
51355
+ const record4 = {
50764
51356
  _id: MANIFEST_RECORD_ID,
50765
51357
  [this.config.textField]: `Rivet knowledge-source manifest for ${manifest.sourceId}, version ${manifest.activeVersion}.`,
50766
51358
  rivet_record_type: "manifest",
@@ -50768,10 +51360,10 @@ var PineconeKnowledgeStoreDriver = class {
50768
51360
  rivet_source_version: manifest.activeVersion,
50769
51361
  rivet_manifest_json: JSON.stringify(manifest)
50770
51362
  };
50771
- validatePineconeRecordMetadataSize(record3, this.config.textField, `manifest for source "${manifest.sourceId}"`);
51363
+ validatePineconeRecordMetadataSize(record4, this.config.textField, `manifest for source "${manifest.sourceId}"`);
50772
51364
  const response = await this.#request(
50773
- `${this.config.indexHost}/records/namespaces/${encodeURIComponent(namespace)}/upsert`,
50774
- { method: "POST", body: JSON.stringify(record3), headers: { "Content-Type": "application/x-ndjson" } },
51365
+ `${this.config.indexHost}/records/namespaces/${encodeURIComponent(namespace2)}/upsert`,
51366
+ { method: "POST", body: JSON.stringify(record4), headers: { "Content-Type": "application/x-ndjson" } },
50775
51367
  context
50776
51368
  );
50777
51369
  const writeLsn = readPineconeLsn(response.headers, "x-pinecone-request-lsn") ?? readPineconeLsn(response.headers, "x-pinecone-max-indexed-lsn");
@@ -50789,7 +51381,7 @@ var PineconeKnowledgeStoreDriver = class {
50789
51381
  );
50790
51382
  }
50791
51383
  async search(request, context) {
50792
- const namespace = this.#namespace(request.sourceId);
51384
+ const namespace2 = this.#namespace(request.sourceId);
50793
51385
  const filter = combinePineconeFilters(
50794
51386
  {
50795
51387
  $and: [{ rivet_record_type: { $eq: "chunk" } }, { rivet_source_version: { $eq: request.version } }]
@@ -50814,7 +51406,7 @@ var PineconeKnowledgeStoreDriver = class {
50814
51406
  }
50815
51407
  }
50816
51408
  const response = await this.#request(
50817
- `${this.config.indexHost}/records/namespaces/${encodeURIComponent(namespace)}/search`,
51409
+ `${this.config.indexHost}/records/namespaces/${encodeURIComponent(namespace2)}/search`,
50818
51410
  { method: "POST", body: JSON.stringify(body), headers: { "Content-Type": "application/json" } },
50819
51411
  context
50820
51412
  );
@@ -50859,14 +51451,14 @@ var PineconeKnowledgeStoreDriver = class {
50859
51451
  });
50860
51452
  }
50861
51453
  async deleteVersion(sourceId, version, context) {
50862
- const namespace = this.#namespace(sourceId);
51454
+ const namespace2 = this.#namespace(sourceId);
50863
51455
  const response = await this.#request(
50864
51456
  `${this.config.indexHost}/vectors/delete`,
50865
51457
  {
50866
51458
  method: "POST",
50867
51459
  headers: { "Content-Type": "application/json" },
50868
51460
  body: JSON.stringify({
50869
- namespace,
51461
+ namespace: namespace2,
50870
51462
  filter: {
50871
51463
  $and: [{ rivet_record_type: { $eq: "chunk" } }, { rivet_source_version: { $eq: version } }]
50872
51464
  }
@@ -50894,7 +51486,7 @@ var PineconeKnowledgeStoreDriver = class {
50894
51486
  );
50895
51487
  }
50896
51488
  }
50897
- const record3 = {
51489
+ const record4 = {
50898
51490
  _id: chunk.id,
50899
51491
  [this.config.textField]: chunk.text,
50900
51492
  rivet_record_type: "chunk",
@@ -50906,18 +51498,18 @@ var PineconeKnowledgeStoreDriver = class {
50906
51498
  rivet_chunks_in_document: chunk.chunksInDocument,
50907
51499
  ...metadata
50908
51500
  };
50909
- validatePineconeRecordMetadataSize(record3, this.config.textField, `knowledge chunk "${chunk.id}"`);
50910
- return record3;
51501
+ validatePineconeRecordMetadataSize(record4, this.config.textField, `knowledge chunk "${chunk.id}"`);
51502
+ return record4;
50911
51503
  }
50912
51504
  #namespace(sourceId) {
50913
51505
  const readableSourceId = sourceId.replace(/[^a-zA-Z0-9._-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").slice(0, 120) || "source";
50914
51506
  const sourceHash = import_crypto_js6.default.SHA256(sourceId).toString(import_crypto_js6.default.enc.Hex).slice(0, 24);
50915
51507
  const safeSourceId = `${readableSourceId}--${sourceHash}`;
50916
- const namespace = this.config.namespaceTemplate.replaceAll("{sourceId}", safeSourceId).trim();
50917
- if (!namespace) throw new Error("Pinecone Namespace Template produced an empty namespace.");
50918
- if (namespace.length > 512)
51508
+ const namespace2 = this.config.namespaceTemplate.replaceAll("{sourceId}", safeSourceId).trim();
51509
+ if (!namespace2) throw new Error("Pinecone Namespace Template produced an empty namespace.");
51510
+ if (namespace2.length > 512)
50919
51511
  throw new Error("Pinecone Namespace Template produced a namespace longer than 512 characters.");
50920
- return namespace;
51512
+ return namespace2;
50921
51513
  }
50922
51514
  async #request(url, init2, context) {
50923
51515
  const headers = new Headers(init2.headers);
@@ -51029,8 +51621,8 @@ function batchNdjson(records, maxRecords, maxBytes) {
51029
51621
  const batches = [];
51030
51622
  let lines = [];
51031
51623
  let bytes = 0;
51032
- for (const record3 of records) {
51033
- const line = JSON.stringify(record3);
51624
+ for (const record4 of records) {
51625
+ const line = JSON.stringify(record4);
51034
51626
  const lineBytes = encoder.encode(line).byteLength + (lines.length ? 1 : 0);
51035
51627
  if (lineBytes > maxBytes) throw new Error(`A single Pinecone knowledge record exceeds ${maxBytes} bytes.`);
51036
51628
  if (lines.length && (lines.length >= maxRecords || bytes + lineBytes > maxBytes)) {
@@ -51044,9 +51636,9 @@ function batchNdjson(records, maxRecords, maxBytes) {
51044
51636
  if (lines.length) batches.push(lines.join("\n"));
51045
51637
  return batches;
51046
51638
  }
51047
- function validatePineconeRecordMetadataSize(record3, textField, label) {
51639
+ function validatePineconeRecordMetadataSize(record4, textField, label) {
51048
51640
  const storedMetadata = Object.fromEntries(
51049
- Object.entries(record3).filter(([key]) => key !== "_id" && key !== textField)
51641
+ Object.entries(record4).filter(([key]) => key !== "_id" && key !== textField)
51050
51642
  );
51051
51643
  if (new TextEncoder().encode(JSON.stringify(storedMetadata)).byteLength > 40 * 1024) {
51052
51644
  throw new Error(`Pinecone metadata for ${label} exceeds 40 KB.`);
@@ -54714,6 +55306,14 @@ async function assembleRegistry(specs, loadPlugin) {
54714
55306
  return { registry, results: { loaded, failed } };
54715
55307
  }
54716
55308
 
55309
+ // src/model/DatasetOwnership.ts
55310
+ function remapOwnedDatasets(datasets, sourceId, targetId) {
55311
+ return datasets.map((dataset) => {
55312
+ if (dataset.meta.projectId !== sourceId) throw new Error("Dataset ownership does not match the source project.");
55313
+ return { ...dataset, meta: { ...dataset.meta, projectId: targetId } };
55314
+ });
55315
+ }
55316
+
54717
55317
  // src/api/streaming.ts
54718
55318
  async function* getProcessorEvents(processor, spec) {
54719
55319
  var _a, _b, _c, _d, _e, _f;
@@ -55099,6 +55699,7 @@ function loadProjectAndAttachedDataFromString(content) {
55099
55699
  }
55100
55700
 
55101
55701
  // src/index.ts
55702
+ installCodeRunnerNamespace(exports_exports);
55102
55703
  var Rivet = void 0;
55103
55704
  // Annotate the CommonJS export names for ESM import in node:
55104
55705
  0 && (module.exports = {
@@ -55114,6 +55715,8 @@ var Rivet = void 0;
55114
55715
  AssembleMessageNodeImpl,
55115
55716
  AssemblePromptNodeImpl,
55116
55717
  AudioNodeImpl,
55718
+ BASETEN_DECISIONS_ENDPOINT,
55719
+ BASETEN_DEFAULT_CREDENTIAL_NAMES,
55117
55720
  BooleanNodeImpl,
55118
55721
  BrowserNativeApi,
55119
55722
  BuildKnowledgeContextNodeImpl,
@@ -55283,6 +55886,8 @@ var Rivet = void 0;
55283
55886
  RivetLLMProfileHealthPolicyError,
55284
55887
  RivetStoredValueController,
55285
55888
  STREAM_RESPONSE_HELPER_MESSAGE,
55889
+ SUBQ_DECISIONS_ENDPOINT,
55890
+ SUBQ_DEFAULT_CREDENTIAL_NAMES,
55286
55891
  SearchKnowledgeNodeImpl,
55287
55892
  SetGlobalNodeImpl,
55288
55893
  SetStoredValueNodeImpl,
@@ -55334,6 +55939,7 @@ var Rivet = void 0;
55334
55939
  autoevalsPlugin,
55335
55940
  base64ToUint8Array,
55336
55941
  baseDirs,
55942
+ basetenClassifierProvider,
55337
55943
  booleanNode,
55338
55944
  buildAgentProfileAttemptInspectorRows,
55339
55945
  buildAgentResponseTrace,
@@ -55345,6 +55951,7 @@ var Rivet = void 0;
55345
55951
  calculateChatV2Cost,
55346
55952
  calculateChatV2UsageCost,
55347
55953
  calculateClassifierUsageCost,
55954
+ calculateTokenUsageCost,
55348
55955
  callGraphNode,
55349
55956
  canBeCoerced,
55350
55957
  canBeCoercedAny,
@@ -55495,6 +56102,7 @@ var Rivet = void 0;
55495
56102
  getChatV2ModelRegistry,
55496
56103
  getChatV2ProviderCapabilities,
55497
56104
  getChatV2ProviderLabel,
56105
+ getChatV2SystemTokenPricing,
55498
56106
  getClassifierCredentialNamesForDisplay,
55499
56107
  getClassifierEvaluateBodySections,
55500
56108
  getClassifierModelEditor,
@@ -55502,6 +56110,7 @@ var Rivet = void 0;
55502
56110
  getClassifierProviderEnvironmentVariableNames,
55503
56111
  getClassifierQuestionBodySections,
55504
56112
  getClassifierRequestCount,
56113
+ getClassifierSystemTokenPricing,
55505
56114
  getCodeOutputFields,
55506
56115
  getCodeOutputKeys,
55507
56116
  getCommonChatV2Editors,
@@ -55541,6 +56150,7 @@ var Rivet = void 0;
55541
56150
  getProcessorEvents,
55542
56151
  getProcessorSSEStream,
55543
56152
  getProfileAttemptOmissionNotice,
56153
+ getProfileDisplayName,
55544
56154
  getProjectConnectionComparisonKey,
55545
56155
  getProjectGlobalVariableIds,
55546
56156
  getProjectNodeFieldComparisons,
@@ -55636,6 +56246,7 @@ var Rivet = void 0;
55636
56246
  isLLMChatV2StructuredResponseFormat,
55637
56247
  isNodePrefabInstanceNode,
55638
56248
  isNotFunctionDataValue,
56249
+ isReportedTokenCount,
55639
56250
  isReservedKnowledgeObjectKey,
55640
56251
  isRivetWebAppRunTerminalEvent,
55641
56252
  isRuntimeDebugLoggingEnabled,
@@ -55779,6 +56390,7 @@ var Rivet = void 0;
55779
56390
  registerIntegration,
55780
56391
  registerKnowledgeStoreProvider,
55781
56392
  registerPluginsIntoRegistry,
56393
+ remapOwnedDatasets,
55782
56394
  removeKnowledgeStoreConnectionCredentials,
55783
56395
  renderUiGraphOutputValue,
55784
56396
  replaceDatasetNode,
@@ -55842,6 +56454,7 @@ var Rivet = void 0;
55842
56454
  stringifyToolResult,
55843
56455
  stringifyUiGraphValue,
55844
56456
  subGraphNode,
56457
+ subqClassifierProvider,
55845
56458
  summarizeAgentResponseCalls,
55846
56459
  summarizeChatV2RequestPlan,
55847
56460
  summarizeDataValueForLog,
@@ -55869,6 +56482,7 @@ var Rivet = void 0;
55869
56482
  validateProjectGlobalVariables,
55870
56483
  validateProjectUiGraphActionBindings,
55871
56484
  validateProjectUiGraphButtonBindings,
56485
+ validateTokenPricing,
55872
56486
  validateUiGraphActionBindings,
55873
56487
  validateUiGraphButtonBindings,
55874
56488
  vectorNearestNeighborsNode,