@valerypopoff/rivet2-core 2.15.0 → 2.17.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 (111) hide show
  1. package/dist/cjs/bundle.cjs +4350 -2077
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/interpolationRuntime.cjs +22 -3
  4. package/dist/cjs/interpolationRuntime.cjs.map +3 -3
  5. package/dist/cjs/interpolationSyntax.cjs +9 -5
  6. package/dist/cjs/interpolationSyntax.cjs.map +2 -2
  7. package/dist/esm/api/createProcessor.js +5 -2
  8. package/dist/esm/exports.js +2 -0
  9. package/dist/esm/model/GraphBoundaryCache.js +2 -1
  10. package/dist/esm/model/GraphProcessor.js +268 -6
  11. package/dist/esm/model/Nodes.js +10 -0
  12. package/dist/esm/model/ProjectBundle.js +235 -0
  13. package/dist/esm/model/SplitRunProcessor.js +28 -7
  14. package/dist/esm/model/StreamingWatchTopology.js +118 -8
  15. package/dist/esm/model/SubgraphProjectTarget.js +7 -0
  16. package/dist/esm/model/chat-v2/aiSdkBridge.js +7 -5
  17. package/dist/esm/model/chat-v2/chatV2Pipeline.js +13 -8
  18. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +19 -1
  19. package/dist/esm/model/chat-v2/chatV2Shared.js +2 -1
  20. package/dist/esm/model/chat-v2/llmChatV2Body.js +11 -8
  21. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +2 -0
  22. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +15 -1
  23. package/dist/esm/model/chat-v2/llmChatV2NodeMigration.js +22 -2
  24. package/dist/esm/model/chat-v2/llmProfile.js +3 -0
  25. package/dist/esm/model/chat-v2/llmProfileBody.js +2 -2
  26. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +1 -1
  27. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +1 -1
  28. package/dist/esm/model/chat-v2/temperature.js +9 -0
  29. package/dist/esm/model/classifier/credentials.js +30 -4
  30. package/dist/esm/model/classifier/images.js +176 -0
  31. package/dist/esm/model/classifier/json.js +57 -0
  32. package/dist/esm/model/classifier/limits.js +270 -0
  33. package/dist/esm/model/classifier/openai.js +118 -0
  34. package/dist/esm/model/classifier/preparation.js +74 -0
  35. package/dist/esm/model/classifier/providers.js +260 -185
  36. package/dist/esm/model/classifier/questionHelpers.js +29 -45
  37. package/dist/esm/model/classifier/questions.js +53 -0
  38. package/dist/esm/model/classifier/response.js +75 -0
  39. package/dist/esm/model/classifier/state.js +204 -0
  40. package/dist/esm/model/nodeRunFailure.js +47 -0
  41. package/dist/esm/model/nodes/CatchStreamingChunksNode.js +42 -0
  42. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +178 -138
  43. package/dist/esm/model/nodes/ClassifierQuestionNode.js +59 -15
  44. package/dist/esm/model/nodes/GetGlobalNode.js +2 -2
  45. package/dist/esm/model/nodes/HttpCallNode.js +44 -75
  46. package/dist/esm/model/nodes/ImageNode.js +44 -3
  47. package/dist/esm/model/nodes/LLMChatV2Node.js +24 -3
  48. package/dist/esm/model/nodes/ObjectNode.js +29 -18
  49. package/dist/esm/model/nodes/PromptNode.js +2 -1
  50. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +4 -1
  51. package/dist/esm/model/nodes/SetGlobalNode.js +5 -3
  52. package/dist/esm/model/nodes/StopWatchingStreamingOutputNode.js +8 -8
  53. package/dist/esm/model/nodes/StreamValueNode.js +38 -0
  54. package/dist/esm/model/nodes/SubGraphNode.js +196 -35
  55. package/dist/esm/model/nodes/ToBase64Node.js +106 -0
  56. package/dist/esm/model/nodes/WatchStreamingOutputNode.js +7 -7
  57. package/dist/esm/recording/ExecutionRecorder.js +26 -0
  58. package/dist/esm/utils/base64.js +18 -15
  59. package/dist/esm/utils/errors.js +41 -0
  60. package/dist/esm/utils/interpolation.js +44 -22
  61. package/dist/esm/utils/interpolationSyntax.js +15 -6
  62. package/dist/esm/utils/serialization/serialization.js +3 -2
  63. package/dist/esm/utils/serialization/serializationUtils.js +6 -0
  64. package/dist/esm/utils/serialization/serialization_v4.js +15 -3
  65. package/dist/types/api/createProcessor.d.ts +7 -1
  66. package/dist/types/exports.d.ts +2 -0
  67. package/dist/types/model/CycleDetector.d.ts +1 -2
  68. package/dist/types/model/ExecutorProtocol.d.ts +2 -0
  69. package/dist/types/model/GraphBoundaryCache.d.ts +2 -0
  70. package/dist/types/model/GraphProcessor.d.ts +1 -0
  71. package/dist/types/model/Nodes.d.ts +6 -2
  72. package/dist/types/model/ProcessContext.d.ts +12 -0
  73. package/dist/types/model/ProjectBundle.d.ts +54 -0
  74. package/dist/types/model/ProjectReferenceLoader.d.ts +3 -0
  75. package/dist/types/model/StreamingWatchTopology.d.ts +11 -1
  76. package/dist/types/model/SubgraphProjectTarget.d.ts +38 -0
  77. package/dist/types/model/chat-v2/chatV2Shared.d.ts +1 -1
  78. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +3 -1
  79. package/dist/types/model/chat-v2/llmChatV2NodeMigration.d.ts +3 -1
  80. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +6 -6
  81. package/dist/types/model/chat-v2/temperature.d.ts +2 -0
  82. package/dist/types/model/classifier/credentials.d.ts +3 -1
  83. package/dist/types/model/classifier/images.d.ts +18 -0
  84. package/dist/types/model/classifier/json.d.ts +19 -0
  85. package/dist/types/model/classifier/limits.d.ts +42 -0
  86. package/dist/types/model/classifier/openai.d.ts +5 -0
  87. package/dist/types/model/classifier/preparation.d.ts +16 -0
  88. package/dist/types/model/classifier/providers.d.ts +67 -9
  89. package/dist/types/model/classifier/questionHelpers.d.ts +6 -4
  90. package/dist/types/model/classifier/questions.d.ts +4 -0
  91. package/dist/types/model/classifier/response.d.ts +4 -0
  92. package/dist/types/model/classifier/state.d.ts +37 -0
  93. package/dist/types/model/classifier/types.d.ts +2 -0
  94. package/dist/types/model/nodeRunFailure.d.ts +13 -0
  95. package/dist/types/model/nodes/CatchStreamingChunksNode.d.ts +20 -0
  96. package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +3 -0
  97. package/dist/types/model/nodes/GetGlobalNode.d.ts +7 -0
  98. package/dist/types/model/nodes/ImageNode.d.ts +4 -0
  99. package/dist/types/model/nodes/LLMChatV2Node.d.ts +1 -0
  100. package/dist/types/model/nodes/ObjectNode.d.ts +2 -1
  101. package/dist/types/model/nodes/StreamValueNode.d.ts +14 -0
  102. package/dist/types/model/nodes/SubGraphNode.d.ts +21 -2
  103. package/dist/types/model/nodes/ToBase64Node.d.ts +12 -0
  104. package/dist/types/recording/ExecutionRecorder.d.ts +8 -2
  105. package/dist/types/utils/base64.d.ts +1 -1
  106. package/dist/types/utils/errors.d.ts +4 -0
  107. package/dist/types/utils/interpolation.d.ts +13 -2
  108. package/dist/types/utils/interpolationSyntax.d.ts +1 -1
  109. package/dist/types/utils/serialization/serialization.d.ts +3 -1
  110. package/dist/types/utils/serialization/serializationUtils.d.ts +1 -0
  111. package/package.json +1 -1
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../src/interpolationRuntime.ts", "../../src/utils/genericUtilFunctions.ts", "../../src/model/chat-v2/chatV2Shared.ts", "../../src/model/chat-v2/chatV2Retry.ts", "../../src/model/chat-v2/llmProfileFieldRegistry.ts", "../../src/model/chat-v2/llmProfileHealthStore.ts", "../../src/model/chat-v2/llmChatV2NodeData.ts", "../../src/model/chat-v2/llmProfileTypes.ts", "../../src/model/DataValue.ts", "../../src/utils/expectType.ts", "../../src/integrations/KnowledgeStoreValidation.ts", "../../src/model/chat-v2/customProviderApi.ts", "../../src/model/chat-v2/chatV2CredentialNames.ts", "../../src/model/chat-v2/llmProfile.ts", "../../src/utils/coerceType.ts", "../../src/utils/jsonPath.ts", "../../src/utils/interpolationSyntax.ts", "../../src/utils/misc.ts", "../../src/utils/interpolation.ts"],
4
- "sourcesContent": ["/**\n * Narrow runtime entrypoint for JavaScript executors. Build tooling can bundle\n * this module into isolated workers without exposing the complete Core API.\n */\nexport { resolveCodeInterpolationExpression } from './utils/interpolation.js';\n", "export function isNotNull<T>(value: T | undefined | null): value is T {\n return value != null;\n}\n\n/**\n * Checks that the given tuple is exhaustive, ie. it represents all possible values in the union T.\n * Note that this function returns a function, so the function needs to be called like\n * `SpecificStrings.exhaustiveTuple<Furniture>()('v1', 'v2', ...)`.\n * If you miss a value, the type error will tell you which value you missed.\n *\n * Taken from https://stackoverflow.com/a/55266531/\n *\n * @example\n * type Furniture = 'chair' | 'table' | 'lamp' | 'ottoman';\n * const furniture = SpecificStrings.exhaustiveTuple<Furniture>()('chair', 'table', 'lamp', 'ottoman');\n *\n * // error, argument of type '\"chair\"' is not assignable to parameter of type '\"You are missing ottoman\"'.\n * const missingFurniture = SpecificStrings.exhaustiveTuple<Furniture>()('chair', 'table', 'lamp');\n */\nexport const exhaustiveTuple =\n <T extends string>() =>\n // impressive inference from TS: it knows when the condition and the true branch can't both be satisfied\n <L extends T[]>(...x: [T] extends [L[number]] ? L : `You are missing ${Exclude<T, L[number]>}`[]) =>\n x;\n\n/**\n * See exhaustiveTuple above. Does the same thing except returns a Set, not an array.\n */\nexport const exhaustiveSet =\n <T extends string>() =>\n <L extends T[]>(...x: [T] extends [L[number]] ? L : `You are missing ${Exclude<T, L[number]>}`[]) =>\n new Set<(typeof x)[number]>(x);\n", "import type { EditorDefinition } from '../EditorDefinition.js';\nimport type { ChartNode, NodeInputDefinition, NodeOutputDefinition, PortId } from '../NodeBase.js';\n\nexport type ChatV2CommonNodeData = {\n model: string;\n useModelInput: boolean;\n temperature: number;\n useTemperatureInput: boolean;\n topP?: number;\n useTopPInput: boolean;\n topK?: number;\n useTopKInput: boolean;\n presencePenalty?: number;\n usePresencePenaltyInput: boolean;\n frequencyPenalty?: number;\n useFrequencyPenaltyInput: boolean;\n stopSequences?: string[];\n useStopSequencesInput: boolean;\n seed?: number;\n useSeedInput: boolean;\n maxTokens: number;\n useMaxTokensInput: boolean;\n useToolCalling: boolean;\n outputUsage: boolean;\n outputReasoning: boolean;\n cache: boolean;\n useAsGraphPartialOutput?: boolean;\n};\n\ntype ChatV2SharedNode = ChartNode<string, ChatV2CommonNodeData>;\n\nexport const STREAM_RESPONSE_HELPER_MESSAGE =\n 'Shows streamed response updates in the editor, including direct consumer previews. Ordinary consumers run after the final response; Watch Streaming Output branches can run during streaming.';\n\nexport type CommonChatV2InputOptions = {\n systemPromptPortId?: PortId;\n promptPortId?: PortId;\n functionsPortId?: PortId;\n includeTopP?: boolean;\n includeTopK?: boolean;\n includeFunctions?: boolean;\n};\n\nexport type CommonChatV2OutputOptions = {\n responsePortId?: PortId;\n inMessagesPortId?: PortId;\n allMessagesPortId?: PortId;\n functionCallsPortId?: PortId;\n usagePortId?: PortId;\n reasoningPortId?: PortId;\n includeFunctionCalls?: boolean;\n includeUsage?: boolean;\n includeReasoning?: boolean;\n};\n\nexport function createChatV2CommonNodeData(overrides: Partial<ChatV2CommonNodeData> = {}): ChatV2CommonNodeData {\n return {\n model: 'gpt-4o',\n useModelInput: false,\n temperature: 0.5,\n useTemperatureInput: false,\n topP: undefined,\n useTopPInput: false,\n topK: undefined,\n useTopKInput: false,\n presencePenalty: undefined,\n usePresencePenaltyInput: false,\n frequencyPenalty: undefined,\n useFrequencyPenaltyInput: false,\n stopSequences: [],\n useStopSequencesInput: false,\n seed: undefined,\n useSeedInput: false,\n maxTokens: 1024,\n useMaxTokensInput: false,\n useToolCalling: false,\n outputUsage: false,\n outputReasoning: false,\n cache: false,\n useAsGraphPartialOutput: false,\n ...overrides,\n };\n}\n\nexport function getCommonChatV2Inputs(\n data: ChatV2CommonNodeData,\n options: CommonChatV2InputOptions = {},\n): NodeInputDefinition[] {\n const {\n systemPromptPortId = 'systemPrompt' as PortId,\n promptPortId = 'prompt' as PortId,\n functionsPortId = 'functions' as PortId,\n includeTopP = true,\n includeTopK = true,\n includeFunctions = data.useToolCalling,\n } = options;\n\n const inputs: NodeInputDefinition[] = [\n {\n id: systemPromptPortId,\n title: 'System Prompt',\n dataType: 'string',\n required: false,\n coerced: true,\n },\n ];\n\n if (data.useModelInput) {\n inputs.push({\n id: 'model' as PortId,\n title: 'Model',\n dataType: 'string',\n required: false,\n });\n }\n\n if (data.useTemperatureInput) {\n inputs.push({\n id: 'temperature' as PortId,\n title: 'Temperature',\n dataType: 'number',\n });\n }\n\n if (includeTopP && data.useTopPInput) {\n inputs.push({\n id: 'topP' as PortId,\n title: 'Top P',\n dataType: 'number',\n });\n }\n\n if (includeTopK && data.useTopKInput) {\n inputs.push({\n id: 'topK' as PortId,\n title: 'Top K',\n dataType: 'number',\n });\n }\n\n if (data.usePresencePenaltyInput) {\n inputs.push({\n id: 'presencePenalty' as PortId,\n title: 'Presence Penalty',\n dataType: 'number',\n });\n }\n\n if (data.useFrequencyPenaltyInput) {\n inputs.push({\n id: 'frequencyPenalty' as PortId,\n title: 'Frequency Penalty',\n dataType: 'number',\n });\n }\n\n if (data.useStopSequencesInput) {\n inputs.push({\n id: 'stopSequences' as PortId,\n title: 'Stop Sequences',\n dataType: ['string', 'string[]'] as const,\n required: false,\n coerced: true,\n });\n }\n\n if (data.useSeedInput) {\n inputs.push({\n id: 'seed' as PortId,\n title: 'Seed',\n dataType: 'number',\n });\n }\n\n if (data.useMaxTokensInput) {\n inputs.push({\n id: 'maxTokens' as PortId,\n title: 'Max output tokens',\n dataType: 'number',\n });\n }\n\n if (includeFunctions) {\n inputs.push({\n id: functionsPortId,\n title: 'Tools',\n dataType: ['gpt-function', 'gpt-function[]'] as const,\n required: false,\n coerced: false,\n });\n }\n\n inputs.push({\n id: promptPortId,\n title: 'Prompt',\n dataType: ['chat-message', 'chat-message[]', 'string', 'string[]'] as const,\n coerced: true,\n });\n\n return inputs;\n}\n\nexport function getCommonChatV2Outputs(\n data: ChatV2CommonNodeData,\n options: CommonChatV2OutputOptions = {},\n): NodeOutputDefinition[] {\n const {\n responsePortId = 'response' as PortId,\n inMessagesPortId = 'in-messages' as PortId,\n allMessagesPortId = 'all-messages' as PortId,\n functionCallsPortId = 'function-calls' as PortId,\n usagePortId = 'usage' as PortId,\n reasoningPortId = 'reasoning' as PortId,\n includeFunctionCalls = data.useToolCalling,\n includeUsage = data.outputUsage,\n includeReasoning = data.outputReasoning,\n } = options;\n\n const outputs: NodeOutputDefinition[] = [\n {\n id: responsePortId,\n title: 'Response',\n dataType: 'string',\n },\n {\n id: inMessagesPortId,\n title: 'Messages Sent',\n dataType: 'chat-message[]',\n },\n {\n id: allMessagesPortId,\n title: 'All Messages',\n dataType: 'chat-message[]',\n },\n ];\n\n if (includeFunctionCalls) {\n outputs.push({\n id: functionCallsPortId,\n title: 'Tool Calls',\n dataType: 'object[]',\n });\n }\n\n if (includeUsage) {\n outputs.push({\n id: usagePortId,\n title: 'Usage',\n dataType: 'object',\n });\n }\n\n if (includeReasoning) {\n outputs.push({\n id: reasoningPortId,\n title: 'Reasoning',\n dataType: ['string', 'string[]'] as const,\n });\n }\n\n return outputs;\n}\n\nexport function getCommonChatV2Editors<T extends ChatV2SharedNode>(\n modelOptions: { value: string; label: string }[],\n): EditorDefinition<T>[] {\n const editors = [\n {\n type: 'dropdown',\n label: 'Model',\n dataKey: 'model',\n useInputToggleDataKey: 'useModelInput',\n options: modelOptions,\n },\n {\n type: 'group',\n label: 'Parameters',\n editors: [\n {\n type: 'number',\n label: 'Temperature',\n helperMessage: 'Provider-dependent; some reasoning models may ignore this setting.',\n dataKey: 'temperature',\n useInputToggleDataKey: 'useTemperatureInput',\n min: 0,\n max: 2,\n step: 0.1,\n },\n {\n type: 'number',\n label: 'Max output tokens',\n dataKey: 'maxTokens',\n useInputToggleDataKey: 'useMaxTokensInput',\n min: 1,\n step: 1,\n },\n {\n type: 'number',\n label: 'Top P',\n dataKey: 'topP',\n useInputToggleDataKey: 'useTopPInput',\n allowEmpty: true,\n min: 0,\n max: 1,\n step: 0.1,\n },\n {\n type: 'number',\n label: 'Top K',\n helperMessage: 'Provider-dependent; some providers or models may ignore this setting.',\n dataKey: 'topK',\n useInputToggleDataKey: 'useTopKInput',\n allowEmpty: true,\n min: 1,\n step: 1,\n },\n {\n type: 'number',\n label: 'Presence penalty',\n dataKey: 'presencePenalty',\n useInputToggleDataKey: 'usePresencePenaltyInput',\n allowEmpty: true,\n min: -1,\n max: 1,\n step: 0.1,\n },\n {\n type: 'number',\n label: 'Frequency penalty',\n dataKey: 'frequencyPenalty',\n useInputToggleDataKey: 'useFrequencyPenaltyInput',\n allowEmpty: true,\n min: -1,\n max: 1,\n step: 0.1,\n },\n {\n type: 'stringList',\n label: 'Stop sequences',\n dataKey: 'stopSequences',\n useInputToggleDataKey: 'useStopSequencesInput',\n placeholder: 'Stop sequence',\n newItemDefault: '',\n },\n {\n type: 'number',\n label: 'Seed',\n dataKey: 'seed',\n useInputToggleDataKey: 'useSeedInput',\n allowEmpty: true,\n min: 0,\n step: 1,\n },\n ],\n },\n {\n type: 'group',\n label: 'Outputs',\n editors: [\n {\n type: 'toggle',\n label: 'Enable Tool Calling',\n dataKey: 'useToolCalling',\n },\n {\n type: 'toggle',\n label: 'Output usage details',\n dataKey: 'outputUsage',\n helperMessage:\n 'Adds a Usage output built from Vercel AI SDK usage metadata: prompt, completion, total, cached, reasoning tokens, and estimated cost when available.',\n },\n {\n type: 'toggle',\n label: 'Stream response',\n dataKey: 'useAsGraphPartialOutput',\n helperMessage: STREAM_RESPONSE_HELPER_MESSAGE,\n },\n ],\n },\n ] satisfies EditorDefinition<ChatV2SharedNode>[];\n\n return editors as unknown as EditorDefinition<T>[];\n}\n", "export const DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_REPEAT_TIMES = 1;\nexport const DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_COOLDOWN_MS = 0;\n\nexport function normalizeLLMChatV2RetryCount(value: number | undefined): number {\n const retryCount =\n typeof value === 'number' && Number.isFinite(value) ? value : DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_REPEAT_TIMES;\n\n return Math.max(1, Math.floor(retryCount));\n}\n\nexport function normalizeLLMChatV2RetryCooldownMs(value: number | undefined): number {\n const cooldownMs =\n typeof value === 'number' && Number.isFinite(value) ? value : DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_COOLDOWN_MS;\n\n return Math.max(0, Math.floor(cooldownMs));\n}\n\n/** Keeps cancellation identity consistent before and during a retry cooldown. */\nexport function createLLMChatV2RetryAbortError(): Error {\n const error = new Error('Aborted');\n error.name = 'AbortError';\n return error;\n}\n\nexport async function waitForLLMChatV2RetryCooldown(cooldownMs: number, signal: AbortSignal): Promise<void> {\n if (signal.aborted) {\n throw createLLMChatV2RetryAbortError();\n }\n\n if (cooldownMs <= 0) {\n return;\n }\n\n await new Promise<void>((resolve, reject) => {\n const cleanup = () => {\n clearTimeout(timeout);\n signal.removeEventListener('abort', onAbort);\n };\n const onAbort = () => {\n cleanup();\n reject(createLLMChatV2RetryAbortError());\n };\n\n const timeout = setTimeout(() => {\n cleanup();\n resolve();\n }, cooldownMs);\n\n signal.addEventListener('abort', onAbort, { once: true });\n if (signal.aborted) {\n onAbort();\n }\n });\n}\n", "import type { LLMChatV2NodeData } from './llmChatV2NodeData.js';\n\n/**\n * Static ownership metadata for fields supplied by an LLM Profile.\n *\n * This deliberately does not attempt to describe editor layout or provider\n * request construction. It provides the one fact those surfaces must share:\n * which persisted LLM Chat fields are profile-owned, and which dynamic input\n * ports a resolved profile consumes before it is passed to LLM Chat.\n */\nexport type LLMProfileFieldSpec = {\n key: keyof LLMChatV2NodeData;\n inputId?: string;\n /** Runtime validation for scalar fields; enum and collection fields keep named validators. */\n valueKind?: 'string' | 'boolean' | 'required-number' | 'optional-number';\n /** A resolved profile must never retain an active dynamic-input toggle. */\n resolvedInputToggle?: boolean;\n};\n\nexport const llmProfileFieldSpecs = [\n { key: 'model', inputId: 'model', valueKind: 'string' },\n { key: 'useModelInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'temperature', inputId: 'temperature', valueKind: 'required-number' },\n { key: 'useTemperatureInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'topP', inputId: 'topP', valueKind: 'optional-number' },\n { key: 'useTopPInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'topK', inputId: 'topK', valueKind: 'optional-number' },\n { key: 'useTopKInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'presencePenalty', inputId: 'presencePenalty', valueKind: 'optional-number' },\n { key: 'usePresencePenaltyInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'frequencyPenalty', inputId: 'frequencyPenalty', valueKind: 'optional-number' },\n { key: 'useFrequencyPenaltyInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'stopSequences', inputId: 'stopSequences' },\n { key: 'useStopSequencesInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'seed', inputId: 'seed', valueKind: 'optional-number' },\n { key: 'useSeedInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'maxTokens', inputId: 'maxTokens', valueKind: 'required-number' },\n { key: 'useMaxTokensInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'provider' },\n { key: 'apiKeySource', inputId: 'apiKey' },\n { key: 'providerApiKeyNames' },\n { key: 'customProviderApiKeyProgrammaticName', valueKind: 'string' },\n { key: 'customProviderApiKeyEnvVarName', valueKind: 'string' },\n { key: 'customProviderBaseURL', inputId: 'customProviderBaseURL', valueKind: 'string' },\n { key: 'useCustomProviderBaseURLInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'customProviderApi' },\n { key: 'headers', inputId: 'headers' },\n { key: 'useHeadersInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'extraProviderOptions', inputId: 'extraProviderOptions', valueKind: 'string' },\n { key: 'useExtraProviderOptionsInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'openAIReasoningEffort', valueKind: 'string' },\n { key: 'openAIReasoningSummary', valueKind: 'string' },\n { key: 'openAIPreviousResponseId', inputId: 'previousResponseId', valueKind: 'string' },\n { key: 'useOpenAIPreviousResponseIdInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'enableOpenAIWebSearch', valueKind: 'boolean' },\n { key: 'openAIWebSearchContextSize' },\n { key: 'enableOpenAICodeInterpreter', valueKind: 'boolean' },\n { key: 'anthropicThinkingMode' },\n { key: 'anthropicThinkingBudget', inputId: 'anthropicThinkingBudget', valueKind: 'optional-number' },\n { key: 'useAnthropicThinkingBudgetInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'anthropicEffort' },\n { key: 'anthropicCacheControlTtl' },\n { key: 'googleThinkingBudget', inputId: 'googleThinkingBudget', valueKind: 'optional-number' },\n { key: 'useGoogleThinkingBudgetInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'googleThinkingLevel' },\n { key: 'googleIncludeThoughts', valueKind: 'boolean' },\n { key: 'enableGoogleSearchGrounding', valueKind: 'boolean' },\n { key: 'enableGoogleUrlContext', valueKind: 'boolean' },\n { key: 'enableCircuitBreaker', valueKind: 'boolean' },\n { key: 'firstOutputTimeoutMs', valueKind: 'required-number' },\n { key: 'streamInactivityTimeoutMs', valueKind: 'required-number' },\n { key: 'circuitBreakerFailureThreshold', valueKind: 'required-number' },\n { key: 'circuitBreakerFailureWindowMs', valueKind: 'required-number' },\n { key: 'circuitBreakerOpenDurationMs', valueKind: 'required-number' },\n] as const satisfies readonly LLMProfileFieldSpec[];\n\nexport const llmProfileDataKeys = llmProfileFieldSpecs.map((field) => field.key);\n\nexport const llmProfileInputIds = llmProfileFieldSpecs\n .flatMap((field) => ('inputId' in field ? [field.inputId] : []))\n .filter((inputId, index, inputIds) => inputIds.indexOf(inputId) === index);\n\nfunction keysForValueKind(valueKind: NonNullable<LLMProfileFieldSpec['valueKind']>) {\n return llmProfileFieldSpecs\n .filter((field) => 'valueKind' in field && field.valueKind === valueKind)\n .map((field) => field.key) as Array<keyof LLMChatV2NodeData>;\n}\n\n/** Runtime validation categories for resolved LLM Profile values. */\nexport const llmProfileStringDataKeys = keysForValueKind('string');\nexport const llmProfileBooleanDataKeys = keysForValueKind('boolean');\nexport const llmProfileRequiredNumberDataKeys = keysForValueKind('required-number');\nexport const llmProfileOptionalNumberDataKeys = keysForValueKind('optional-number');\n\n/** A serialized profile must be self-contained, not driven by hidden ports. */\nexport const llmProfileResolvedInputToggleDataKeys = llmProfileFieldSpecs\n .filter((field) => 'resolvedInputToggle' in field && field.resolvedInputToggle)\n .map((field) => field.key) as Array<keyof LLMChatV2NodeData>;\n", "import { nanoid } from 'nanoid/non-secure';\nimport CryptoJS from 'crypto-js';\nimport stableStringify from 'safe-stable-stringify';\nimport type { NodeId } from '../NodeBase.js';\nimport type { ProjectId } from '../Project.js';\nimport type { ChatV2CredentialResult } from './chatV2ProviderProfile.js';\nimport type { LLMChatV2ProfileData } from './llmChatV2NodeData.js';\nimport type { ChatV2Provider } from './chatV2ProviderTypes.js';\nimport type { CustomProviderApi } from './customProviderApi.js';\n\nexport const DEFAULT_LLM_PROFILE_FIRST_OUTPUT_TIMEOUT_MS = 30_000;\nexport const DEFAULT_LLM_PROFILE_STREAM_INACTIVITY_TIMEOUT_MS = 30_000;\nexport const DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_THRESHOLD = 3;\nexport const DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_WINDOW_MS = 300_000;\nexport const DEFAULT_LLM_PROFILE_CIRCUIT_OPEN_DURATION_MS = 300_000;\nconst LLM_PROFILE_HALF_OPEN_LEASE_SAFETY_MARGIN_MS = 5_000;\nconst LLM_PROFILE_CLOSED_PERMIT_MIN_RETENTION_MS = 24 * 60 * 60 * 1_000;\n\nexport class RivetLLMProfileHealthPolicyError extends Error {\n constructor(message: string) {\n super(`LLM profile suspension policy is invalid: ${message}`);\n this.name = 'RivetLLMProfileHealthPolicyError';\n }\n}\n\nexport type RivetLLMProfileCircuitBreakerPolicy = {\n failureThreshold: number;\n failureWindowMs: number;\n openDurationMs: number;\n halfOpenLeaseMs: number;\n};\n\nfunction requirePositiveInteger(value: unknown, label: string): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) {\n throw new RivetLLMProfileHealthPolicyError(`${label} must be a positive integer.`);\n }\n return value;\n}\n\nexport function resolveRivetLLMProfileCircuitBreakerPolicy(\n configuration: LLMChatV2ProfileData,\n): RivetLLMProfileCircuitBreakerPolicy | undefined {\n if (configuration.enableCircuitBreaker !== true) {\n return undefined;\n }\n\n const firstOutputTimeoutMs = requirePositiveInteger(\n configuration.firstOutputTimeoutMs ?? DEFAULT_LLM_PROFILE_FIRST_OUTPUT_TIMEOUT_MS,\n 'Useful output wait time',\n );\n const streamInactivityTimeoutMs = requirePositiveInteger(\n configuration.streamInactivityTimeoutMs ?? DEFAULT_LLM_PROFILE_STREAM_INACTIVITY_TIMEOUT_MS,\n 'Stream inactivity timeout',\n );\n const failureThreshold = requirePositiveInteger(\n configuration.circuitBreakerFailureThreshold ?? DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_THRESHOLD,\n 'Failures before suspension',\n );\n const failureWindowMs = requirePositiveInteger(\n configuration.circuitBreakerFailureWindowMs ?? DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_WINDOW_MS,\n 'Failure window',\n );\n const openDurationMs = requirePositiveInteger(\n configuration.circuitBreakerOpenDurationMs ?? DEFAULT_LLM_PROFILE_CIRCUIT_OPEN_DURATION_MS,\n 'Suspension duration',\n );\n\n return {\n failureThreshold,\n failureWindowMs,\n openDurationMs,\n // A live streaming probe renews this lease on useful output. The bounded\n // safety margin lets a dead owner recover promptly without coupling the\n // probe lease to the (usually much longer) circuit cooldown.\n halfOpenLeaseMs:\n Math.max(firstOutputTimeoutMs, streamInactivityTimeoutMs) + LLM_PROFILE_HALF_OPEN_LEASE_SAFETY_MARGIN_MS,\n };\n}\n\n/**\n * Stable, privacy-bounded identity for one resolved LLM Profile configuration.\n * `key` and `configurationFingerprint` are SHA-256 routing/auth digests;\n * credentials and provider configuration are never exposed through this\n * contract.\n */\nexport type RivetLLMProfileHealthIdentity = {\n key: string;\n projectId?: ProjectId;\n profileNodeId?: NodeId;\n /** Current source-node title used only for operator-facing identification. */\n profileName?: string;\n provider: ChatV2Provider;\n model: string;\n customProviderApi?: CustomProviderApi;\n configurationFingerprint: string;\n};\n\nfunction sha256(value: string): string {\n return `sha256:${CryptoJS.SHA256(value).toString(CryptoJS.enc.Hex)}`;\n}\n\nexport function createRivetLLMProfileHealthIdentity(params: {\n configuration: LLMChatV2ProfileData;\n credential: ChatV2CredentialResult;\n /** Project-wide Chat headers merged into every physical provider request. */\n chatNodeHeaders?: Record<string, string> | undefined;\n projectId?: ProjectId;\n profileNodeId?: NodeId;\n /** Current source-node title. It is intentionally excluded from the key. */\n profileName?: string;\n}): RivetLLMProfileHealthIdentity {\n const profileName = params.profileName?.trim();\n // Circuit health belongs to the physical provider route and credentials,\n // not to generation policy. A temperature/cooldown edit must not silently\n // create a fresh circuit, while changing the model, endpoint, auth, or\n // routing headers must never inherit another route's outage history.\n const routingConfiguration = {\n provider: params.configuration.provider,\n model: params.configuration.model,\n ...(params.configuration.provider !== 'custom'\n ? {}\n : {\n customProviderApi: params.configuration.customProviderApi ?? 'completions',\n customProviderBaseURL: params.configuration.customProviderBaseURL,\n }),\n headers: canonicalizeEffectiveRoutingHeaders(params.chatNodeHeaders, params.configuration.headers),\n };\n const serialized =\n stableStringify({\n routingConfiguration,\n credential: params.credential,\n }) ?? '';\n const configurationFingerprint = sha256(serialized);\n const projectId = params.projectId == null ? undefined : String(params.projectId);\n const profileNodeId = params.profileNodeId == null ? undefined : String(params.profileNodeId);\n const key = sha256(\n stableStringify({\n kind: 'rivet-llm-profile-health',\n projectId,\n profileNodeId,\n configurationFingerprint,\n }) ?? '',\n );\n\n return {\n key: `llm-profile:${key}`,\n ...(params.projectId == null ? {} : { projectId: params.projectId }),\n ...(params.profileNodeId == null ? {} : { profileNodeId: params.profileNodeId }),\n ...(profileName === '' || profileName == null ? {} : { profileName }),\n provider: params.configuration.provider,\n model: params.configuration.model,\n ...(params.configuration.provider !== 'custom'\n ? {}\n : { customProviderApi: params.configuration.customProviderApi ?? 'completions' }),\n configurationFingerprint,\n };\n}\n\nfunction canonicalizeEffectiveRoutingHeaders(\n chatNodeHeaders: Record<string, string> | undefined,\n profileHeaders: LLMChatV2ProfileData['headers'],\n): Array<[string, string]> {\n // Provider resolution spreads project-wide headers first and profile\n // headers second. Normalize names here because HTTP field names are\n // case-insensitive, while preserving that same profile-wins precedence.\n // Values remain confined to the SHA-256 input and never enter the public\n // identity or store key in plaintext.\n const headers = new Map<string, string>();\n for (const [key, value] of Object.entries(chatNodeHeaders ?? {})) {\n const normalizedKey = key.trim().toLowerCase();\n if (normalizedKey) headers.set(normalizedKey, value);\n }\n for (const { key, value } of profileHeaders) {\n const normalizedKey = key.trim().toLowerCase();\n if (normalizedKey) headers.set(normalizedKey, value);\n }\n return [...headers.entries()].sort(([left], [right]) => left.localeCompare(right));\n}\n\nexport type RivetLLMProfileHealthState = 'closed' | 'open' | 'half-open';\n\nexport type RivetLLMProfileHealthSnapshot = {\n identity: RivetLLMProfileHealthIdentity;\n state: RivetLLMProfileHealthState;\n failureCount: number;\n openUntil?: number;\n halfOpenLeaseUntil?: number;\n updatedAt: number;\n};\n\nexport type RivetLLMProfileHealthBeginRequest = {\n identity: RivetLLMProfileHealthIdentity;\n policy: RivetLLMProfileCircuitBreakerPolicy;\n};\n\nexport type RivetLLMProfileHealthBeginResult = {\n disposition: 'allow' | 'deny';\n state: RivetLLMProfileHealthState;\n /** Opaque permit returned to `finish`; present only when execution is allowed. */\n permitId?: string;\n retryAt?: number;\n snapshot: RivetLLMProfileHealthSnapshot;\n};\n\nexport type RivetLLMProfileHealthOutcome = 'healthy' | 'unhealthy' | 'ignored';\n\nexport type RivetLLMProfileHealthFinishRequest = {\n identity: RivetLLMProfileHealthIdentity;\n policy: RivetLLMProfileCircuitBreakerPolicy;\n permitId: string;\n outcome: RivetLLMProfileHealthOutcome;\n /**\n * Host-owned, privacy-bounded execution correlation. Studio Server uses this\n * only to join an unhealthy profile result to its normal run recording after\n * that recording has finished persisting.\n */\n executionCorrelationId?: string;\n};\n\nexport type RivetLLMProfileHealthRenewRequest = {\n identity: RivetLLMProfileHealthIdentity;\n permitId: string;\n leaseDurationMs: number;\n};\n\nexport type RivetLLMProfileHealthResetRequest =\n | { key: string; projectId?: never }\n | { key?: never; projectId: ProjectId };\n\nexport type RivetLLMProfileHealthListRequest = {\n projectId?: ProjectId;\n};\n\n/**\n * Host persistence seam for LLM Profile health. Implementations must make\n * each method atomic. In particular, `begin` must allow at most one probe\n * while an open circuit is half-open across all processes using the store.\n */\nexport interface RivetLLMProfileHealthStore {\n begin(\n request: RivetLLMProfileHealthBeginRequest,\n ): RivetLLMProfileHealthBeginResult | Promise<RivetLLMProfileHealthBeginResult>;\n finish(\n request: RivetLLMProfileHealthFinishRequest,\n ): RivetLLMProfileHealthSnapshot | Promise<RivetLLMProfileHealthSnapshot>;\n renew(\n request: RivetLLMProfileHealthRenewRequest,\n ): RivetLLMProfileHealthSnapshot | Promise<RivetLLMProfileHealthSnapshot>;\n reset(request: RivetLLMProfileHealthResetRequest): void | Promise<void>;\n list(\n request?: RivetLLMProfileHealthListRequest,\n ): RivetLLMProfileHealthSnapshot[] | Promise<RivetLLMProfileHealthSnapshot[]>;\n}\n\ntype MutableHealthEntry = {\n identity: RivetLLMProfileHealthIdentity;\n failureTimestamps: number[];\n openUntil?: number;\n halfOpenPermitId?: string;\n halfOpenLeaseUntil?: number;\n updatedAt: number;\n policy: RivetLLMProfileCircuitBreakerPolicy;\n closedPermits: Map<string, number>;\n};\n\nfunction requireMatchingProjectScope(existing: MutableHealthEntry, identity: RivetLLMProfileHealthIdentity): void {\n const storedProjectId = existing.identity.projectId == null ? undefined : String(existing.identity.projectId);\n const requestProjectId = identity.projectId == null ? undefined : String(identity.projectId);\n if (storedProjectId !== requestProjectId) {\n throw new Error(`LLM profile reliability key ${identity.key} belongs to a different project scope.`);\n }\n}\n\nfunction closedPermitRetentionMs(policy: RivetLLMProfileCircuitBreakerPolicy): number {\n return Math.max(\n LLM_PROFILE_CLOSED_PERMIT_MIN_RETENTION_MS,\n policy.failureWindowMs,\n policy.openDurationMs,\n policy.halfOpenLeaseMs,\n );\n}\n\nfunction pruneClosedPermits(entry: MutableHealthEntry, now: number): void {\n for (const [permitId, expiresAt] of entry.closedPermits) {\n if (expiresAt <= now) entry.closedPermits.delete(permitId);\n }\n}\n\nfunction pruneFailures(entry: MutableHealthEntry, policy: RivetLLMProfileCircuitBreakerPolicy, now: number): void {\n const windowStart = now - policy.failureWindowMs;\n entry.failureTimestamps = entry.failureTimestamps.filter((timestamp) => timestamp >= windowStart);\n}\n\nfunction getState(entry: MutableHealthEntry, now: number): RivetLLMProfileHealthState {\n if (entry.openUntil == null) return 'closed';\n if (entry.openUntil > now) return 'open';\n return 'half-open';\n}\n\nfunction toSnapshot(\n entry: MutableHealthEntry,\n policy: RivetLLMProfileCircuitBreakerPolicy,\n now: number,\n): RivetLLMProfileHealthSnapshot {\n pruneFailures(entry, policy, now);\n const state = getState(entry, now);\n return {\n identity: entry.identity,\n state,\n failureCount: entry.failureTimestamps.length,\n ...(entry.openUntil == null ? {} : { openUntil: entry.openUntil }),\n ...(state !== 'half-open' || entry.halfOpenLeaseUntil == null\n ? {}\n : { halfOpenLeaseUntil: entry.halfOpenLeaseUntil }),\n updatedAt: entry.updatedAt,\n };\n}\n\n/** Process-local reference implementation used when a host does not supply durable shared storage. */\nexport class InMemoryRivetLLMProfileHealthStore implements RivetLLMProfileHealthStore {\n readonly #entries = new Map<string, MutableHealthEntry>();\n readonly #now: () => number;\n\n constructor(options: { now?: () => number } = {}) {\n this.#now = options.now ?? Date.now;\n }\n\n #pruneStaleEntries(now: number): void {\n for (const [key, entry] of this.#entries) {\n pruneFailures(entry, entry.policy, now);\n pruneClosedPermits(entry, now);\n const isEmptyClosedEntry =\n entry.failureTimestamps.length === 0 &&\n entry.openUntil == null &&\n entry.halfOpenPermitId == null &&\n entry.closedPermits.size === 0;\n if (isEmptyClosedEntry && entry.updatedAt + closedPermitRetentionMs(entry.policy) <= now) {\n this.#entries.delete(key);\n }\n }\n }\n\n begin(request: RivetLLMProfileHealthBeginRequest): RivetLLMProfileHealthBeginResult {\n const { identity, policy } = request;\n const now = this.#now();\n this.#pruneStaleEntries(now);\n let entry = this.#entries.get(identity.key);\n if (entry == null) {\n entry = { identity, failureTimestamps: [], updatedAt: now, policy, closedPermits: new Map() };\n this.#entries.set(identity.key, entry);\n } else {\n requireMatchingProjectScope(entry, identity);\n entry.identity = identity;\n entry.policy = policy;\n }\n pruneFailures(entry, policy, now);\n pruneClosedPermits(entry, now);\n\n if (entry.openUntil != null && entry.openUntil > now) {\n return {\n disposition: 'deny',\n state: 'open',\n retryAt: entry.openUntil,\n snapshot: toSnapshot(entry, policy, now),\n };\n }\n\n if (entry.openUntil != null) {\n if (entry.halfOpenPermitId != null && (entry.halfOpenLeaseUntil ?? 0) > now) {\n return {\n disposition: 'deny',\n state: 'half-open',\n retryAt: entry.halfOpenLeaseUntil,\n snapshot: toSnapshot(entry, policy, now),\n };\n }\n\n const permitId = nanoid();\n entry.halfOpenPermitId = permitId;\n entry.halfOpenLeaseUntil = now + policy.halfOpenLeaseMs;\n entry.updatedAt = now;\n return {\n disposition: 'allow',\n state: 'half-open',\n permitId,\n snapshot: toSnapshot(entry, policy, now),\n };\n }\n\n const permitId = nanoid();\n entry.closedPermits.set(permitId, now + closedPermitRetentionMs(policy));\n entry.updatedAt = now;\n return {\n disposition: 'allow',\n state: 'closed',\n permitId,\n snapshot: toSnapshot(entry, policy, now),\n };\n }\n\n finish(request: RivetLLMProfileHealthFinishRequest): RivetLLMProfileHealthSnapshot {\n const { identity, policy, permitId, outcome } = request;\n const now = this.#now();\n this.#pruneStaleEntries(now);\n const entry = this.#entries.get(identity.key);\n if (entry == null) {\n return {\n identity,\n state: 'closed',\n failureCount: 0,\n updatedAt: now,\n };\n }\n requireMatchingProjectScope(entry, identity);\n entry.identity = identity;\n entry.policy = policy;\n pruneFailures(entry, policy, now);\n pruneClosedPermits(entry, now);\n\n const ownsHalfOpenLease = entry.halfOpenPermitId === permitId;\n const ownsClosedPermit = entry.closedPermits.delete(permitId);\n if (!ownsHalfOpenLease && !ownsClosedPermit) {\n return toSnapshot(entry, policy, now);\n }\n\n if (outcome === 'healthy' && ownsHalfOpenLease) {\n entry.failureTimestamps = [];\n entry.openUntil = undefined;\n entry.halfOpenPermitId = undefined;\n entry.halfOpenLeaseUntil = undefined;\n // Requests admitted before the circuit opened belong to the previous\n // health generation. Once the single recovery probe succeeds, their\n // eventual results must not immediately poison the recovered circuit.\n entry.closedPermits.clear();\n } else if (outcome === 'unhealthy') {\n const wasOpen = entry.openUntil != null;\n entry.failureTimestamps.push(now);\n if (ownsHalfOpenLease || (!wasOpen && entry.failureTimestamps.length >= policy.failureThreshold)) {\n entry.openUntil = now + policy.openDurationMs;\n }\n if (ownsHalfOpenLease) {\n entry.halfOpenPermitId = undefined;\n entry.halfOpenLeaseUntil = undefined;\n }\n } else if (outcome === 'ignored' && ownsHalfOpenLease) {\n entry.halfOpenPermitId = undefined;\n entry.halfOpenLeaseUntil = undefined;\n }\n\n entry.updatedAt = now;\n return toSnapshot(entry, policy, now);\n }\n\n renew(request: RivetLLMProfileHealthRenewRequest): RivetLLMProfileHealthSnapshot {\n const now = this.#now();\n this.#pruneStaleEntries(now);\n const entry = this.#entries.get(request.identity.key);\n if (entry == null) {\n return {\n identity: request.identity,\n state: 'closed',\n failureCount: 0,\n updatedAt: now,\n };\n }\n\n requireMatchingProjectScope(entry, request.identity);\n\n if (entry.halfOpenPermitId === request.permitId) {\n entry.halfOpenLeaseUntil = Math.max(entry.halfOpenLeaseUntil ?? 0, now + request.leaseDurationMs);\n entry.updatedAt = now;\n } else if (entry.closedPermits.has(request.permitId)) {\n entry.closedPermits.set(\n request.permitId,\n Math.max(entry.closedPermits.get(request.permitId) ?? 0, now + closedPermitRetentionMs(entry.policy)),\n );\n entry.updatedAt = now;\n }\n return toSnapshot(entry, entry.policy, now);\n }\n\n reset(request: RivetLLMProfileHealthResetRequest): void {\n if (request.key != null) {\n this.#entries.delete(request.key);\n return;\n }\n\n for (const [key, entry] of this.#entries) {\n if (entry.identity.projectId === request.projectId) {\n this.#entries.delete(key);\n }\n }\n }\n\n list(request: RivetLLMProfileHealthListRequest = {}): RivetLLMProfileHealthSnapshot[] {\n const now = this.#now();\n this.#pruneStaleEntries(now);\n return [...this.#entries.entries()]\n .filter(([, entry]) => request.projectId == null || entry.identity.projectId === request.projectId)\n .map(([, entry]) => {\n pruneFailures(entry, entry.policy, now);\n pruneClosedPermits(entry, now);\n const state = getState(entry, now);\n return {\n identity: entry.identity,\n state,\n failureCount: entry.failureTimestamps.length,\n ...(entry.openUntil == null ? {} : { openUntil: entry.openUntil }),\n ...(state !== 'half-open' || entry.halfOpenLeaseUntil == null\n ? {}\n : { halfOpenLeaseUntil: entry.halfOpenLeaseUntil }),\n updatedAt: entry.updatedAt,\n };\n });\n }\n}\n", "import type { ChatV2ResponseFormat } from './chatV2ResponseFormat.js';\nimport { createChatV2CommonNodeData, type ChatV2CommonNodeData } from './chatV2Shared.js';\nimport {\n DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_COOLDOWN_MS,\n DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_REPEAT_TIMES,\n} from './chatV2Retry.js';\nimport type { ChatV2Provider } from './chatV2Types.js';\nimport type { ChartNode, NodeId } from '../NodeBase.js';\nimport { llmProfileDataKeys } from './llmProfileFieldRegistry.js';\nimport type { CustomProviderApi } from './customProviderApi.js';\nimport type { ChatV2CredentialNamesByProvider } from './chatV2CredentialNames.js';\nimport {\n DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_THRESHOLD,\n DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_WINDOW_MS,\n DEFAULT_LLM_PROFILE_CIRCUIT_OPEN_DURATION_MS,\n DEFAULT_LLM_PROFILE_FIRST_OUTPUT_TIMEOUT_MS,\n DEFAULT_LLM_PROFILE_STREAM_INACTIVITY_TIMEOUT_MS,\n} from './llmProfileHealthStore.js';\n\nexport type { CustomProviderApi } from './customProviderApi.js';\n\nexport type LLMChatV2ToolChoiceMode = '' | 'auto' | 'function' | 'required';\nexport type LLMChatV2ApiKeySource = 'environment' | 'input';\nexport type LLMChatV2ConfigurationMode = 'inline' | 'profile';\nexport type LLMChatV2NodeConfigData = ChatV2CommonNodeData & {\n configurationMode?: LLMChatV2ConfigurationMode;\n provider: ChatV2Provider;\n apiKeySource?: LLMChatV2ApiKeySource;\n providerApiKeyNames?: ChatV2CredentialNamesByProvider;\n customProviderApiKeyProgrammaticName?: string;\n customProviderApiKeyEnvVarName?: string;\n customProviderBaseURL: string;\n useCustomProviderBaseURLInput: boolean;\n /** Missing on legacy/programmatically-created nodes means Chat Completions. */\n customProviderApi?: CustomProviderApi;\n baseURL: string;\n useBaseURLInput: boolean;\n headers: { key: string; value: string }[];\n useHeadersInput: boolean;\n extraProviderOptions: string;\n useExtraProviderOptionsInput: boolean;\n openAIReasoningEffort: string;\n openAIReasoningSummary: string;\n openAIPreviousResponseId: string;\n useOpenAIPreviousResponseIdInput: boolean;\n enableOpenAIWebSearch: boolean;\n openAIWebSearchContextSize: 'low' | 'medium' | 'high';\n enableOpenAICodeInterpreter: boolean;\n anthropicThinkingMode: '' | 'adaptive' | 'enabled' | 'disabled';\n anthropicThinkingBudget?: number;\n useAnthropicThinkingBudgetInput: boolean;\n anthropicEffort?: '' | 'low' | 'medium' | 'high' | 'max';\n anthropicCacheControlTtl: '' | '5m' | '1h';\n googleThinkingBudget?: number;\n useGoogleThinkingBudgetInput: boolean;\n googleThinkingLevel?: '' | 'minimal' | 'low' | 'medium' | 'high';\n googleIncludeThoughts?: boolean;\n enableGoogleSearchGrounding: boolean;\n enableGoogleUrlContext: boolean;\n enableCircuitBreaker?: boolean;\n firstOutputTimeoutMs?: number;\n streamInactivityTimeoutMs?: number;\n circuitBreakerFailureThreshold?: number;\n circuitBreakerFailureWindowMs?: number;\n circuitBreakerOpenDurationMs?: number;\n responseFormat?: ChatV2ResponseFormat;\n responseSchemaName?: string;\n useResponseSchemaNameInput?: boolean;\n responseSchemaDescription?: string;\n useResponseSchemaDescriptionInput?: boolean;\n toolChoice?: LLMChatV2ToolChoiceMode;\n toolChoiceFunction?: string;\n parallelToolCalls?: boolean;\n autoContinueToolCalls?: boolean;\n maxToolRounds?: number;\n retryOnNon200?: boolean;\n retryOnNon200RepeatTimes?: number;\n retryOnNon200CooldownMs?: number;\n outputLLMAttempts?: boolean;\n outputRequestBody?: boolean;\n outputResponseBody?: boolean;\n};\n\nexport type LLMChatV2NodeData = LLMChatV2NodeConfigData;\nexport type LLMChatV2Node = ChartNode<'llmChatV2', LLMChatV2NodeData>;\n\n/** @deprecated Use llmProfileDataKeys from llmProfileFieldRegistry instead. */\nexport const llmChatV2ProfileDataKeys = llmProfileDataKeys;\n\nexport type LLMChatV2ProfileDataKey = (typeof llmChatV2ProfileDataKeys)[number];\nexport type LLMChatV2ProfileData = Pick<LLMChatV2NodeData, LLMChatV2ProfileDataKey>;\n\nexport type LLMChatV2EditorCacheKeyParts = {\n /** Bump when cache identity semantics change; entries are editor-memory only. */\n cacheVersion?: number;\n nodeId: NodeId;\n nodeData: LLMChatV2NodeData;\n provider: ChatV2Provider;\n modelId: string;\n providerConfig: unknown;\n apiKeyFingerprint?: string;\n prompt: unknown;\n systemPrompt: unknown;\n functions: unknown;\n generationParameters: unknown;\n responseFormatParameters: unknown;\n providerOptions: unknown;\n requestBodyOverlay?: unknown;\n toolChoice: unknown;\n /** Ordered, credential-fingerprinted fallback profile configuration. */\n profileChain?: unknown;\n};\n\nexport function createLLMChatV2NodeData(): LLMChatV2NodeData {\n return {\n ...createChatV2CommonNodeData({\n model: 'gpt-5',\n }),\n configurationMode: 'inline',\n provider: 'openai',\n apiKeySource: 'environment',\n customProviderApiKeyProgrammaticName: '',\n customProviderApiKeyEnvVarName: 'CUSTOM_PROVIDER_API_KEY',\n customProviderBaseURL: '',\n useCustomProviderBaseURLInput: false,\n customProviderApi: 'completions',\n baseURL: '',\n useBaseURLInput: false,\n headers: [],\n useHeadersInput: false,\n extraProviderOptions: '',\n useExtraProviderOptionsInput: false,\n openAIReasoningEffort: '',\n openAIReasoningSummary: '',\n openAIPreviousResponseId: '',\n useOpenAIPreviousResponseIdInput: false,\n enableOpenAIWebSearch: false,\n openAIWebSearchContextSize: 'medium',\n enableOpenAICodeInterpreter: false,\n anthropicThinkingMode: '',\n anthropicThinkingBudget: undefined,\n useAnthropicThinkingBudgetInput: false,\n anthropicEffort: '',\n anthropicCacheControlTtl: '',\n googleThinkingBudget: undefined,\n useGoogleThinkingBudgetInput: false,\n googleThinkingLevel: '',\n googleIncludeThoughts: false,\n enableGoogleSearchGrounding: false,\n enableGoogleUrlContext: false,\n enableCircuitBreaker: false,\n firstOutputTimeoutMs: DEFAULT_LLM_PROFILE_FIRST_OUTPUT_TIMEOUT_MS,\n streamInactivityTimeoutMs: DEFAULT_LLM_PROFILE_STREAM_INACTIVITY_TIMEOUT_MS,\n circuitBreakerFailureThreshold: DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_THRESHOLD,\n circuitBreakerFailureWindowMs: DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_WINDOW_MS,\n circuitBreakerOpenDurationMs: DEFAULT_LLM_PROFILE_CIRCUIT_OPEN_DURATION_MS,\n responseFormat: '',\n responseSchemaName: '',\n useResponseSchemaNameInput: false,\n responseSchemaDescription: '',\n useResponseSchemaDescriptionInput: false,\n toolChoice: '',\n toolChoiceFunction: '',\n parallelToolCalls: false,\n autoContinueToolCalls: false,\n maxToolRounds: 3,\n retryOnNon200: false,\n retryOnNon200RepeatTimes: DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_REPEAT_TIMES,\n retryOnNon200CooldownMs: DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_COOLDOWN_MS,\n outputLLMAttempts: false,\n outputRequestBody: false,\n outputResponseBody: false,\n };\n}\n\nexport function shouldIncludeLLMChatV2ToolCalls(data: LLMChatV2NodeData): boolean {\n return data.useToolCalling;\n}\n", "import type { ChatV2CredentialResult } from './chatV2ProviderProfile.js';\nimport {\n createLLMChatV2NodeData,\n llmChatV2ProfileDataKeys,\n type LLMChatV2NodeData,\n type LLMChatV2ProfileData,\n} from './llmChatV2NodeData.js';\nimport type { RivetLLMProfileHealthIdentity } from './llmProfileHealthStore.js';\n\nexport const LLM_PROFILE_VALUE_VERSION = 1 as const;\n\n/**\n * Every input port owned by an LLM Profile, including ports that are hidden\n * until their matching provider or input toggle is enabled. This lets editor\n * operations preserve recoverable connections across configuration changes.\n */\nexport { llmProfileInputIds } from './llmProfileFieldRegistry.js';\n\nexport type LLMProfileValue = {\n version: typeof LLM_PROFILE_VALUE_VERSION;\n configuration: LLMChatV2ProfileData;\n credential: ChatV2CredentialResult;\n /**\n * User-facing title captured from the source LLM Profile node. It is\n * diagnostic metadata only: changing a node title must not change provider\n * resolution, caching, or circuit-breaker identity.\n */\n profileName?: string;\n /** Stable privacy-bounded identity used by optional cross-run health policy. */\n healthIdentity?: RivetLLMProfileHealthIdentity;\n};\n\nexport function createLLMProfileNodeData(): LLMChatV2ProfileData {\n return pickLLMChatV2ProfileData(createLLMChatV2NodeData());\n}\n\nexport function createDefaultLLMProfileValue(): LLMProfileValue {\n return {\n version: LLM_PROFILE_VALUE_VERSION,\n configuration: createLLMProfileNodeData(),\n credential: { reference: { source: 'none' } },\n };\n}\n\nexport function pickLLMChatV2ProfileData(data: LLMChatV2NodeData): LLMChatV2ProfileData {\n return Object.fromEntries(llmChatV2ProfileDataKeys.map((key) => [key, data[key]])) as LLMChatV2ProfileData;\n}\n\nexport function applyLLMProfileToNodeData(data: LLMChatV2NodeData, profile: LLMProfileValue): LLMChatV2NodeData {\n return {\n ...data,\n ...profile.configuration,\n configurationMode: 'profile',\n };\n}\n", "import type { GraphId } from '../index.js';\nimport { exhaustiveTuple } from '../utils/genericUtilFunctions.js';\nimport type { DataId } from './Project.js';\nimport type {\n RivetKnowledgeDocument,\n RivetKnowledgeEvidence,\n RivetKnowledgeSourceReference,\n} from '../integrations/KnowledgeStore.js';\nimport { createDefaultLLMProfileValue, type LLMProfileValue } from './chat-v2/llmProfileTypes.js';\n\nexport type DataValueDef<Type extends string, RuntimeType> = {\n type: Type;\n value: RuntimeType;\n};\n\nexport type StringDataValue = DataValueDef<'string', string>;\nexport type NumberDataValue = DataValueDef<'number', number>;\nexport type BoolDataValue = DataValueDef<'boolean', boolean>;\n\nexport type SystemChatMessage = {\n type: 'system';\n message: ChatMessageMessagePart | ChatMessageMessagePart[];\n\n /** If true, this message marks a breakpoint when used with prompt caching (as of right now, Anthropic-only). */\n isCacheBreakpoint?: boolean;\n};\n\nexport type DeveloperChatMessage = {\n type: 'developer';\n message: ChatMessageMessagePart | ChatMessageMessagePart[];\n\n /** If true, this message marks a breakpoint when used with prompt caching (as of right now, Anthropic-only). */\n isCacheBreakpoint?: boolean;\n};\n\nexport type UserChatMessage = {\n type: 'user';\n message: ChatMessageMessagePart | ChatMessageMessagePart[];\n\n /** If true, this message marks a breakpoint when used with prompt caching (as of right now, Anthropic-only). */\n isCacheBreakpoint?: boolean;\n};\n\nexport type AssistantChatMessageFunctionCall = {\n id: string | undefined;\n name: string;\n arguments: string; // JSON string\n};\n\nexport type ParsedAssistantChatMessageFunctionCall = {\n id: string | undefined;\n name: string;\n arguments: Record<string, unknown>;\n};\n\nexport type AssistantChatMessage = {\n type: 'assistant';\n message: ChatMessageMessagePart | ChatMessageMessagePart[];\n\n /** @deprecated use function_calls instead */\n function_call: AssistantChatMessageFunctionCall | undefined;\n\n function_calls: AssistantChatMessageFunctionCall[] | undefined;\n\n /** If true, this message marks a breakpoint when used with prompt caching (as of right now, Anthropic-only). */\n isCacheBreakpoint?: boolean;\n};\n\nexport type FunctionResponseChatMessage = {\n type: 'function';\n message: ChatMessageMessagePart | ChatMessageMessagePart[];\n name: string;\n toolName?: string;\n\n /** If true, this message marks a breakpoint when used with prompt caching (as of right now, Anthropic-only). */\n isCacheBreakpoint?: boolean;\n};\n\nexport type ChatMessage =\n | SystemChatMessage\n | DeveloperChatMessage\n | UserChatMessage\n | AssistantChatMessage\n | FunctionResponseChatMessage;\n\nexport type ChatMessageMessagePart =\n | string\n | { type: 'image'; mediaType: SupportedImageMediaTypes; data: Uint8Array }\n | { type: 'url'; url: string }\n | {\n type: 'document';\n title: string | undefined;\n context: string | undefined;\n mediaType: SupportedDocumentMediaTypes;\n data: Uint8Array;\n enableCitations: boolean;\n };\n\nexport type SupportedImageMediaTypes = 'image/jpeg' | 'image/png' | 'image/gif';\nexport type SupportedDocumentMediaTypes = 'application/pdf' | 'text/plain';\n\nexport type ChatMessageDataValue = DataValueDef<'chat-message', ChatMessage>;\n\nexport type DateDataValue = DataValueDef<'date', string>;\nexport type TimeDataValue = DataValueDef<'time', string>;\nexport type DateTimeDataValue = DataValueDef<'datetime', string>;\nexport type AnyDataValue = DataValueDef<'any', unknown>;\nexport type ObjectDataValue = DataValueDef<'object', Record<string, unknown>>;\nexport type VectorDataValue = DataValueDef<'vector', number[]>;\nexport type BinaryDataValue = DataValueDef<'binary', Uint8Array>;\nexport type ImageDataValue = DataValueDef<'image', { mediaType: SupportedImageMediaTypes; data: Uint8Array }>;\nexport type AudioDataValue = DataValueDef<'audio', { mediaType?: string; data: Uint8Array }>;\nexport type GraphReferenceValue = DataValueDef<'graph-reference', { graphId: GraphId; graphName: string }>;\nexport type KnowledgeSourceDataValue = DataValueDef<'knowledge-source', RivetKnowledgeSourceReference>;\nexport type KnowledgeDocumentDataValue = DataValueDef<'knowledge-document', RivetKnowledgeDocument>;\nexport type KnowledgeEvidenceDataValue = DataValueDef<'knowledge-evidence', RivetKnowledgeEvidence>;\nexport type LLMProfileDataValue = DataValueDef<'llm-config', LLMProfileValue>;\nexport type DocumentDataValue = DataValueDef<\n 'document',\n {\n mediaType: SupportedDocumentMediaTypes;\n data: Uint8Array;\n title: string | undefined;\n context: string | undefined;\n enableCitations: boolean;\n }\n>;\n\nexport type GptFunctionResultHandling = 'continue' | 'return-direct';\n\n/** GPT function definition */\nexport type GptFunction = {\n name: string;\n namespace?: string;\n description: string;\n parameters: object;\n strict: boolean;\n /** Rivet-only handling for the function result. This is not sent to the model provider. */\n resultHandling?: GptFunctionResultHandling;\n};\n\nexport type GptFunctionDataValue = DataValueDef<'gpt-function', GptFunction>;\n\nexport type ControlFlowExcludedDataValue = DataValueDef<'control-flow-excluded', undefined | 'loop-not-broken'>;\n\nexport type ScalarDataValue =\n | StringDataValue\n | NumberDataValue\n | DateDataValue\n | TimeDataValue\n | DateTimeDataValue\n | BoolDataValue\n | ChatMessageDataValue\n | ControlFlowExcludedDataValue\n | AnyDataValue\n | ObjectDataValue\n | GptFunctionDataValue\n | VectorDataValue\n | ImageDataValue\n | BinaryDataValue\n | AudioDataValue\n | GraphReferenceValue\n | KnowledgeSourceDataValue\n | KnowledgeDocumentDataValue\n | KnowledgeEvidenceDataValue\n | LLMProfileDataValue\n | DocumentDataValue;\n\nexport type ScalarType = ScalarDataValue['type'];\n\nexport type ArrayDataValue<T extends ScalarDataValue> = DataValueDef<`${T['type']}[]`, T['value'][]>;\n\nexport type FunctionDataValue<T extends ScalarOrArrayDataValue> = DataValueDef<`fn<${T['type']}>`, () => T['value']>;\n\nexport type StringArrayDataValue = ArrayDataValue<StringDataValue>;\n\nexport type ArrayDataValues = {\n [P in ScalarDataValue['type']]: ArrayDataValue<Extract<ScalarDataValue, { type: P }>>;\n}[ScalarDataValue['type']];\n\nexport type ArrayLikeDataValue =\n | ArrayDataValues\n | (AnyDataValue & { value: unknown[] })\n | (ObjectDataValue & { value: unknown[] });\n\nexport type ScalarOrArrayDataValue = ScalarDataValue | ArrayDataValues;\n\nexport type FunctionDataValues = {\n [P in ScalarOrArrayDataValue['type']]: FunctionDataValue<Extract<ScalarOrArrayDataValue, { type: P }>>;\n}[ScalarOrArrayDataValue['type']];\n\nexport type DataValue = ScalarDataValue | ArrayDataValues | FunctionDataValues;\n\nexport type DataType = DataValue['type'];\nexport type ScalarDataType = ScalarDataValue['type'];\nexport type ArrayDataType = ArrayDataValues['type'];\nexport type FunctionDataType = FunctionDataValues['type'];\nexport type ScalarOrArrayDataType = ScalarOrArrayDataValue['type'];\n\nexport type GetDataValue<Type extends DataType> = Extract<DataValue, { type: Type }>;\n\n/** A reference to large data stored outside the graphs themselves. */\nexport type DataRef = {\n refId: DataId;\n};\n\nexport const dataTypes = exhaustiveTuple<DataType>()(\n 'any',\n 'any[]',\n 'boolean',\n 'boolean[]',\n 'string',\n 'string[]',\n 'number',\n 'number[]',\n 'date',\n 'date[]',\n 'time',\n 'time[]',\n 'datetime',\n 'datetime[]',\n 'chat-message',\n 'chat-message[]',\n 'control-flow-excluded',\n 'control-flow-excluded[]',\n 'object',\n 'object[]',\n 'fn<string>',\n 'fn<number>',\n 'fn<boolean>',\n 'fn<date>',\n 'fn<time>',\n 'fn<datetime>',\n 'fn<any>',\n 'fn<object>',\n 'fn<chat-message>',\n 'fn<control-flow-excluded>',\n 'fn<string[]>',\n 'fn<number[]>',\n 'fn<boolean[]>',\n 'fn<date[]>',\n 'fn<time[]>',\n 'fn<datetime[]>',\n 'fn<any[]>',\n 'fn<object[]>',\n 'fn<chat-message[]>',\n 'fn<control-flow-excluded[]>',\n 'gpt-function',\n 'gpt-function[]',\n 'fn<gpt-function[]>',\n 'fn<gpt-function>',\n 'vector',\n 'vector[]',\n 'fn<vector>',\n 'fn<vector[]>',\n 'image',\n 'image[]',\n 'fn<image>',\n 'fn<image[]>',\n 'binary',\n 'binary[]',\n 'fn<binary>',\n 'fn<binary[]>',\n 'audio',\n 'audio[]',\n 'fn<audio>',\n 'fn<audio[]>',\n 'graph-reference',\n 'graph-reference[]',\n 'fn<graph-reference>',\n 'fn<graph-reference[]>',\n 'knowledge-source',\n 'knowledge-source[]',\n 'fn<knowledge-source>',\n 'fn<knowledge-source[]>',\n 'knowledge-document',\n 'knowledge-document[]',\n 'fn<knowledge-document>',\n 'fn<knowledge-document[]>',\n 'knowledge-evidence',\n 'knowledge-evidence[]',\n 'fn<knowledge-evidence>',\n 'fn<knowledge-evidence[]>',\n 'llm-config',\n 'llm-config[]',\n 'fn<llm-config>',\n 'fn<llm-config[]>',\n 'document',\n 'document[]',\n 'fn<document>',\n 'fn<document[]>',\n);\n\nexport const scalarTypes = exhaustiveTuple<ScalarType>()(\n 'any',\n 'boolean',\n 'string',\n 'number',\n 'date',\n 'time',\n 'datetime',\n 'chat-message',\n 'control-flow-excluded',\n 'object',\n 'gpt-function',\n 'vector',\n 'image',\n 'binary',\n 'audio',\n 'graph-reference',\n 'knowledge-source',\n 'knowledge-document',\n 'knowledge-evidence',\n 'llm-config',\n 'document',\n);\n\nexport const dataTypeDisplayNames: Record<DataType, string> = {\n any: 'Any',\n 'any[]': 'Any Array',\n boolean: 'Boolean',\n 'boolean[]': 'Boolean Array',\n string: 'String',\n 'string[]': 'String Array',\n number: 'Number',\n 'number[]': 'Number Array',\n date: 'Date',\n 'date[]': 'Date Array',\n time: 'Time',\n 'time[]': 'Time Array',\n datetime: 'DateTime',\n 'datetime[]': 'DateTime Array',\n 'chat-message': 'ChatMessage',\n 'chat-message[]': 'ChatMessage Array',\n 'control-flow-excluded': 'ControlFlowExcluded',\n 'control-flow-excluded[]': 'ControlFlowExcluded Array',\n object: 'Object',\n 'object[]': 'Object Array',\n 'gpt-function': 'GPT Function',\n 'gpt-function[]': 'GPT Function Array',\n 'fn<string>': 'Function<String>',\n 'fn<number>': 'Function<Number>',\n 'fn<boolean>': 'Function<Boolean>',\n 'fn<date>': 'Function<Date>',\n 'fn<time>': 'Function<Time>',\n 'fn<datetime>': 'Function<DateTime>',\n 'fn<any>': 'Function<Any>',\n 'fn<object>': 'Function<Object>',\n 'fn<chat-message>': 'Function<ChatMessage>',\n 'fn<control-flow-excluded>': 'Function<ControlFlowExcluded>',\n 'fn<gpt-function>': 'Function<GPT Function>',\n 'fn<string[]>': 'Function<String Array>',\n 'fn<number[]>': 'Function<Number Array>',\n 'fn<boolean[]>': 'Function<Boolean Array>',\n 'fn<date[]>': 'Function<Date Array>',\n 'fn<time[]>': 'Function<Time Array>',\n 'fn<datetime[]>': 'Function<DateTime Array>',\n 'fn<any[]>': 'Function<Any Array>',\n 'fn<object[]>': 'Function<Object Array>',\n 'fn<chat-message[]>': 'Function<ChatMessage Array>',\n 'fn<control-flow-excluded[]>': 'Function<ControlFlowExcluded Array>',\n 'fn<gpt-function[]>': 'Function<GPT Function Array>',\n vector: 'Vector',\n 'vector[]': 'Vector Array',\n 'fn<vector>': 'Function<Vector>',\n 'fn<vector[]>': 'Function<Vector Array>',\n image: 'Image',\n 'image[]': 'Image Array',\n 'fn<image>': 'Function<Image>',\n 'fn<image[]>': 'Function<Image Array>',\n binary: 'Binary',\n 'binary[]': 'Binary Array',\n 'fn<binary>': 'Function<Binary>',\n 'fn<binary[]>': 'Function<Binary Array>',\n audio: 'Audio',\n 'audio[]': 'Audio Array',\n 'fn<audio>': 'Function<Audio>',\n 'fn<audio[]>': 'Function<Audio Array>',\n 'graph-reference': 'Graph Reference',\n 'graph-reference[]': 'Graph Reference Array',\n 'fn<graph-reference>': 'Function<Graph Reference>',\n 'fn<graph-reference[]>': 'Function<Graph Reference Array>',\n 'knowledge-source': 'Knowledge Source',\n 'knowledge-source[]': 'Knowledge Source Array',\n 'fn<knowledge-source>': 'Function<Knowledge Source>',\n 'fn<knowledge-source[]>': 'Function<Knowledge Source Array>',\n 'knowledge-document': 'Knowledge Document',\n 'knowledge-document[]': 'Knowledge Document Array',\n 'fn<knowledge-document>': 'Function<Knowledge Document>',\n 'fn<knowledge-document[]>': 'Function<Knowledge Document Array>',\n 'knowledge-evidence': 'Knowledge Evidence',\n 'knowledge-evidence[]': 'Knowledge Evidence Array',\n 'fn<knowledge-evidence>': 'Function<Knowledge Evidence>',\n 'fn<knowledge-evidence[]>': 'Function<Knowledge Evidence Array>',\n 'llm-config': 'LLM Profile',\n 'llm-config[]': 'LLM Profile Array',\n 'fn<llm-config>': 'Function<LLM Profile>',\n 'fn<llm-config[]>': 'Function<LLM Profile Array>',\n document: 'Document',\n 'document[]': 'Document Array',\n 'fn<document>': 'Function<Document>',\n 'fn<document[]>': 'Function<Document Array>',\n};\n\nexport function isScalarDataValue(value: DataValue | undefined): value is ScalarDataValue {\n if (!value) {\n return false;\n }\n\n return !isArrayDataType(value.type) && !isFunctionDataType(value.type);\n}\n\nexport function isScalarDataType(type: DataType): type is ScalarDataType {\n return !isArrayDataType(type) && !isFunctionDataType(type);\n}\n\nexport function isArrayDataValue(value: DataValue | undefined): value is ArrayLikeDataValue {\n if (!value) {\n return false;\n }\n\n return (\n isArrayDataType(value.type) || ((value.type === 'any' || value.type === 'object') && Array.isArray(value.value))\n );\n}\n\nexport function isArrayDataType(type: DataType): type is ArrayDataType {\n return type.endsWith('[]');\n}\n\nexport function isFunctionDataType(type: DataType): type is FunctionDataType {\n return type.startsWith('fn<');\n}\n\nexport function isFunctionDataValue(\n value: DataValue | undefined,\n): value is FunctionDataValues | (AnyDataValue & { value: () => unknown }) {\n if (!value) {\n return false;\n }\n return isFunctionDataType(value.type) || (value.type === 'any' && typeof value.value === 'function');\n}\n\nexport function isNotFunctionDataValue(value: DataValue | undefined): value is ScalarOrArrayDataValue {\n return value !== undefined && !isFunctionDataValue(value);\n}\n\nexport function functionTypeToReturnType(functionType: FunctionDataType): ScalarOrArrayDataType {\n return functionType.slice(3, -1) as ScalarOrArrayDataType;\n}\n\nexport function functionTypeToScalarType(functionType: FunctionDataType): ScalarDataType {\n const returnType = functionTypeToReturnType(functionType);\n return isArrayDataType(returnType) ? arrayTypeToScalarType(returnType) : returnType;\n}\n\nexport function arrayTypeToScalarType(arrayType: ArrayDataType): ScalarDataType {\n return arrayType.slice(0, -2) as ScalarDataType;\n}\n\nexport function getScalarTypeOf(type: DataType): ScalarDataType {\n if (isArrayDataType(type)) {\n return arrayTypeToScalarType(type);\n }\n\n if (isFunctionDataType(type)) {\n return functionTypeToScalarType(type);\n }\n\n return type;\n}\n\n/** Unwraps a potentially function data value to a concrete value. I.e., evaluates on-demand values. */\nexport function unwrapDataValue(value: DataValue): ScalarOrArrayDataValue;\nexport function unwrapDataValue(value: DataValue | undefined): ScalarOrArrayDataValue | undefined {\n if (!value) {\n return undefined;\n }\n\n if (isFunctionDataValue(value)) {\n const evaluated = value.value();\n if (value.type === 'any') {\n return { type: 'any', value: evaluated };\n }\n return { type: functionTypeToReturnType(value.type), value: evaluated } as ScalarOrArrayDataValue;\n }\n\n return value;\n}\n\n/**\n * Turns a { type: 'string[]', value: string[] } into { type: 'string', value: string }[]\n * or a { type: 'object', value: something[] } into { type: 'object', value: something }[]\n * or a { type: 'any', value: something[] } into { type: 'any', value: something }[]\n * or a { type: 'string', value: string } into [{ type: 'string', value: string }]\n */\nexport const arrayizeDataValue = (value: ScalarOrArrayDataValue): ScalarDataValue[] => {\n const isArray =\n value.type.endsWith('[]') || ((value.type === 'any' || value.type === 'object') && Array.isArray(value.value));\n if (!isArray) {\n return [value as ScalarDataValue];\n }\n\n const unwrappedType = value.type.endsWith('[]') ? value.type.slice(0, -2) : value.type;\n\n return (value.value as unknown[]).map((v) => ({ type: unwrappedType as ScalarType, value: v })) as ScalarDataValue[];\n};\n\nexport const scalarDefaults: { [P in ScalarDataType]: Extract<ScalarDataValue, { type: P }>['value'] } = {\n string: '',\n number: 0,\n boolean: false,\n any: undefined,\n 'chat-message': {\n type: 'user',\n message: '',\n isCacheBreakpoint: undefined,\n },\n 'control-flow-excluded': undefined,\n date: new Date().toISOString(),\n time: new Date().toISOString(),\n datetime: new Date().toISOString(),\n object: {},\n 'gpt-function': {\n name: 'unknown',\n description: '',\n parameters: {},\n namespace: undefined,\n strict: false,\n },\n vector: [],\n image: {\n mediaType: 'image/jpeg',\n data: new Uint8Array(),\n },\n binary: new Uint8Array(),\n audio: { data: new Uint8Array() },\n 'graph-reference': { graphId: '' as GraphId, graphName: '' },\n 'knowledge-source': { connectionId: '', sourceId: '' },\n 'knowledge-document': { text: '' },\n 'knowledge-evidence': {\n id: '',\n text: '',\n source: { connectionId: '', sourceId: '' },\n documentId: '',\n },\n 'llm-config': createDefaultLLMProfileValue(),\n document: {\n mediaType: 'text/plain',\n data: new Uint8Array(),\n title: undefined,\n context: undefined,\n enableCitations: false,\n },\n};\n\nexport function getDefaultValue<T extends DataType>(type: T): GetDataValue<T>['value'] {\n if (isArrayDataType(type)) {\n return [] as unknown as GetDataValue<T>['value'];\n }\n\n if (isFunctionDataType(type)) {\n const returnType = functionTypeToReturnType(type);\n return (() => getDefaultValue(returnType)) as unknown as GetDataValue<T>['value'];\n }\n\n return structuredClone(scalarDefaults[getScalarTypeOf(type)]) as unknown as GetDataValue<T>['value'];\n}\n", "import {\n type DataType,\n type DataValue,\n type FunctionDataType,\n type GetDataValue,\n functionTypeToReturnType,\n getScalarTypeOf,\n isArrayDataType,\n isArrayDataValue,\n isFunctionDataType,\n isScalarDataValue,\n unwrapDataValue,\n} from '../model/DataValue.js';\n\nfunction getDeferredValue(value: DataValue, type: FunctionDataType): (() => unknown) | undefined {\n const targetReturnType = functionTypeToReturnType(type);\n\n if (isFunctionDataType(value.type)) {\n const sourceReturnType = functionTypeToReturnType(value.type);\n return targetReturnType === 'any' || sourceReturnType === 'any' || sourceReturnType === targetReturnType\n ? (value.value as () => unknown)\n : undefined;\n }\n\n if (value.type === 'any' && typeof value.value === 'function') {\n return value.value as () => unknown;\n }\n\n if (targetReturnType === 'any' || value.type === 'any' || value.type === targetReturnType) {\n return () => value.value;\n }\n\n return undefined;\n}\n\nexport function expectType<T extends DataType>(value: DataValue | undefined, type: T): GetDataValue<T>['value'] {\n if (isArrayDataType(type) && isArrayDataValue(value) && getScalarTypeOf(type) === getScalarTypeOf(value.type)) {\n return value.value as unknown as GetDataValue<T>['value'];\n }\n\n // Allow a string to be expected for a string[], just return an array of one element\n if (isArrayDataType(type) && isScalarDataValue(value) && getScalarTypeOf(type) === value.type) {\n return [value.value] as GetDataValue<T>['value'];\n }\n\n if (value?.type === type) {\n return value.value as GetDataValue<T>['value'];\n }\n\n if (value && isFunctionDataType(type)) {\n const deferredValue = getDeferredValue(value, type);\n if (deferredValue) {\n return deferredValue as GetDataValue<T>['value'];\n }\n }\n\n if (type === 'any' || type === 'any[]' || value?.type === 'any' || value?.type === 'any[]') {\n return value?.value as GetDataValue<T>['value'];\n }\n\n throw new Error(`Expected value of type ${type} but got ${value?.type}`);\n}\n\nexport function expectTypeOptional<T extends DataType>(\n value: DataValue | undefined,\n type: T,\n): GetDataValue<T>['value'] | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (isArrayDataType(type) && isArrayDataValue(value) && getScalarTypeOf(type) === getScalarTypeOf(value.type)) {\n // @ts-expect-error Generic T is not narrowed to its array subtype within this runtime-guarded branch.\n return value.value as unknown as GetDataValue<T>['value'];\n }\n\n // Allow a string to be expected for a string[], just return an array of one element\n if (isArrayDataType(type) && isScalarDataValue(value) && getScalarTypeOf(type) === value.type) {\n return [value.value] as GetDataValue<T>['value'] | undefined;\n }\n\n if (value.type === type) {\n // @ts-expect-error Generic T is not narrowed by comparing a DataValue's discriminant to T.\n return value.value as GetDataValue<T>['value'];\n }\n\n if (isFunctionDataType(type)) {\n const deferredValue = getDeferredValue(value, type);\n if (deferredValue) {\n // @ts-expect-error Generic T is not narrowed to its function subtype within this runtime-guarded branch.\n return deferredValue as GetDataValue<T>['value'];\n }\n }\n\n // We allow a fn<string> to be expected for a string, so unwrap it on demand\n if (isFunctionDataType(value.type) && value.type === `fn<${type}>`) {\n value = unwrapDataValue(value);\n }\n\n if (value.type !== type) {\n throw new Error(`Expected value of type ${type} but got ${value?.type}`);\n }\n return value.value as GetDataValue<T>['value'] | undefined;\n}\n", "import type {\n GetKnowledgeSourceStatusResult,\n KnowledgeFilter,\n KnowledgeFilterComparisonOperator,\n KnowledgeMetadata,\n KnowledgeMetadataValue,\n RivetKnowledgeDocument,\n RivetKnowledgeEvidence,\n RivetKnowledgeSourceReference,\n SearchKnowledgeSourceResult,\n SyncKnowledgeSourceResult,\n} from './KnowledgeStore.js';\n\nexport function normalizeKnowledgeConnectionId(value: unknown): string {\n const id = typeof value === 'string' ? value.trim() : '';\n if (!id) throw new Error('Knowledge store connection ID cannot be empty.');\n if (id.length > 256) throw new Error('Knowledge store connection ID cannot exceed 256 characters.');\n if (isReservedKnowledgeObjectKey(id)) {\n throw new Error(`Knowledge store connection ID \"${id}\" is reserved.`);\n }\n return id;\n}\n\nexport function isReservedKnowledgeObjectKey(key: string): boolean {\n return key === '__proto__' || key === 'prototype' || key === 'constructor';\n}\n\nexport function normalizeKnowledgeSourceId(value: unknown): string {\n const id = typeof value === 'string' ? value.trim() : '';\n if (!id) throw new Error('Knowledge source ID cannot be empty.');\n if (id.length > 512) throw new Error('Knowledge source ID cannot exceed 512 characters.');\n return id;\n}\n\nexport function normalizeKnowledgeSourceReference(value: unknown): RivetKnowledgeSourceReference {\n if (!isRecord(value)) throw new Error('Knowledge Source must be an object.');\n const connectionId = normalizeKnowledgeConnectionId(value.connectionId);\n const sourceId = normalizeKnowledgeSourceId(value.sourceId);\n const version = normalizeKnowledgeVersion(value.version, 'Knowledge source version');\n return { connectionId, sourceId, ...(version ? { version } : {}) };\n}\n\nexport function normalizeKnowledgeQueries(value: unknown): string[] {\n if (!Array.isArray(value)) throw new Error('Knowledge queries must be an array.');\n const queries: string[] = [];\n const seen = new Set<string>();\n for (const rawQuery of value) {\n if (typeof rawQuery !== 'string') throw new Error('Knowledge queries must contain only strings.');\n const query = rawQuery.trim();\n if (!query || seen.has(query)) continue;\n seen.add(query);\n queries.push(query);\n }\n if (queries.length === 0) throw new Error('Search Knowledge requires at least one non-empty query.');\n return queries;\n}\n\nexport function normalizeKnowledgeMetadata(value: unknown, label = 'Knowledge metadata'): KnowledgeMetadata {\n if (value == null) return {};\n if (!isRecord(value)) throw new Error(`${label} must be a plain object.`);\n\n const normalized: KnowledgeMetadata = {};\n for (const [rawKey, rawValue] of Object.entries(value)) {\n const key = rawKey.trim();\n if (!key) throw new Error(`${label} contains an empty field name.`);\n rejectUnsafeObjectKey(key, label);\n if (Object.prototype.hasOwnProperty.call(normalized, key)) {\n throw new Error(`${label} contains duplicate field \"${key}\" after trimming.`);\n }\n normalized[key] = normalizeKnowledgeMetadataValue(rawValue, `${label}.${key}`);\n }\n return normalized;\n}\n\nexport function normalizeKnowledgeDocument(value: unknown, index?: number): RivetKnowledgeDocument {\n const label = index == null ? 'Knowledge document' : `Knowledge document ${index + 1}`;\n if (typeof value === 'string') {\n const text = normalizeDocumentText(value);\n if (!text) throw new Error(`${label} text cannot be empty.`);\n return { text };\n }\n if (!isRecord(value)) throw new Error(`${label} must be a string or object.`);\n\n const text = normalizeDocumentText(value.text);\n if (!text) throw new Error(`${label} text cannot be empty.`);\n const id = optionalTrimmedString(value.id, `${label} ID`) ?? '';\n const title = optionalTrimmedString(value.title, `${label} title`) ?? '';\n const metadata = value.metadata == null ? undefined : normalizeKnowledgeMetadata(value.metadata, `${label} metadata`);\n return {\n ...(id ? { id } : {}),\n text,\n ...(title ? { title } : {}),\n ...(metadata && Object.keys(metadata).length > 0 ? { metadata } : {}),\n };\n}\n\nexport function normalizeKnowledgeEvidence(value: unknown): RivetKnowledgeEvidence {\n if (!isRecord(value)) throw new Error('Knowledge Evidence must be an object.');\n const id = typeof value.id === 'string' ? value.id.trim() : '';\n const text = normalizeDocumentText(value.text);\n const documentId = typeof value.documentId === 'string' ? value.documentId.trim() : '';\n if (!id || !text || !documentId) {\n throw new Error('Knowledge Evidence requires non-empty id, text, and documentId fields.');\n }\n const score = optionalFiniteNumber(value.relevanceScore, 'Knowledge Evidence relevance score');\n const title = optionalTrimmedString(value.title, 'Knowledge Evidence title') ?? '';\n const chunkIndex = optionalNonNegativeInteger(value.chunkIndex, 'Knowledge Evidence chunk index');\n return {\n id,\n text,\n source: normalizeKnowledgeSourceReference(value.source),\n documentId,\n ...(score == null ? {} : { relevanceScore: score }),\n ...(title ? { title } : {}),\n ...(chunkIndex == null ? {} : { chunkIndex }),\n ...(value.metadata == null ? {} : { metadata: normalizeKnowledgeMetadata(value.metadata) }),\n };\n}\n\nexport function normalizeKnowledgeSourceStatusResult(\n value: unknown,\n expectedSource?: RivetKnowledgeSourceReference,\n expectedVersion?: string,\n): GetKnowledgeSourceStatusResult {\n if (!isRecord(value)) throw new Error('Knowledge source status result must be an object.');\n if (typeof value.exists !== 'boolean') throw new Error('Knowledge source status result requires an Exists boolean.');\n const source = normalizeKnowledgeSourceReference(value.source);\n validateExpectedSourceIdentity(source, expectedSource);\n const activeVersion = normalizeKnowledgeVersion(value.activeVersion, 'Knowledge source active version');\n if (activeVersion && source.version && activeVersion !== source.version) {\n throw new Error('Knowledge source status returned conflicting active versions.');\n }\n const resolvedActiveVersion = value.exists ? activeVersion || source.version : activeVersion;\n if (!value.exists && activeVersion) {\n throw new Error('A missing knowledge source status cannot have an active version.');\n }\n const message = requiredString(value.message, 'Knowledge source status message');\n const documentCount = optionalNonNegativeInteger(value.documentCount, 'Knowledge source document count');\n const chunkCount = optionalNonNegativeInteger(value.chunkCount, 'Knowledge source chunk count');\n const updatedAt = optionalTrimmedString(value.updatedAt, 'Knowledge source update time');\n if (updatedAt && !Number.isFinite(Date.parse(updatedAt))) {\n throw new Error('Knowledge source status returned an invalid update time.');\n }\n if (value.matchesExpectedVersion != null && typeof value.matchesExpectedVersion !== 'boolean') {\n throw new Error('Knowledge source status returned an invalid expected-version match value.');\n }\n const requestedVersion =\n normalizeKnowledgeVersion(expectedVersion, 'Expected knowledge source version') ??\n normalizeKnowledgeVersion(expectedSource?.version, 'Expected knowledge source version');\n const matchesExpectedVersion = requestedVersion\n ? value.exists && resolvedActiveVersion === requestedVersion\n : undefined;\n if (\n matchesExpectedVersion != null &&\n typeof value.matchesExpectedVersion === 'boolean' &&\n value.matchesExpectedVersion !== matchesExpectedVersion\n ) {\n throw new Error('Knowledge source status returned an incorrect expected-version match value.');\n }\n const metadata = value.metadata == null ? undefined : normalizeKnowledgeMetadata(value.metadata, 'Source metadata');\n const normalizedFields = {\n message,\n ...(documentCount == null ? {} : { documentCount }),\n ...(chunkCount == null ? {} : { chunkCount }),\n ...(updatedAt ? { updatedAt } : {}),\n ...(metadata && Object.keys(metadata).length ? { metadata } : {}),\n ...(matchesExpectedVersion != null\n ? { matchesExpectedVersion }\n : typeof value.matchesExpectedVersion === 'boolean'\n ? { matchesExpectedVersion: value.matchesExpectedVersion }\n : {}),\n };\n if (!value.exists) return { ...normalizedFields, exists: false, source };\n if (!resolvedActiveVersion) {\n throw new Error('An existing knowledge source status requires an active version.');\n }\n return {\n ...normalizedFields,\n exists: true,\n source: { ...source, version: resolvedActiveVersion },\n activeVersion: resolvedActiveVersion,\n };\n}\n\nexport function normalizeSyncKnowledgeSourceResult(\n value: unknown,\n expectedSource?: RivetKnowledgeSourceReference,\n): SyncKnowledgeSourceResult {\n if (!isRecord(value)) throw new Error('Knowledge source sync result must be an object.');\n const source = normalizeKnowledgeSourceReference(value.source);\n validateExpectedSourceIdentity(source, expectedSource);\n if (!source.version) throw new Error('Knowledge source sync result requires a committed version.');\n if (value.result !== 'created' && value.result !== 'updated' && value.result !== 'unchanged') {\n throw new Error('Knowledge source sync result has an unsupported result value.');\n }\n const documentCount = requiredPositiveInteger(value.documentCount, 'Knowledge source document count');\n const chunkCount = requiredPositiveInteger(value.chunkCount, 'Knowledge source chunk count');\n const previousVersion = normalizeKnowledgeVersion(value.previousVersion, 'Previous knowledge source version');\n if (!Array.isArray(value.warnings) || !value.warnings.every((warning) => typeof warning === 'string')) {\n throw new Error('Knowledge source sync warnings must be a string array.');\n }\n return {\n source: { ...source, version: source.version },\n result: value.result,\n documentCount,\n chunkCount,\n ...(previousVersion ? { previousVersion } : {}),\n warnings: [...value.warnings],\n };\n}\n\nexport function normalizeSearchKnowledgeSourceResult(\n value: unknown,\n expectedSource?: RivetKnowledgeSourceReference,\n expectedQueries?: readonly string[],\n): SearchKnowledgeSourceResult {\n if (!isRecord(value)) throw new Error('Knowledge search result must be an object.');\n if (typeof value.sourceFound !== 'boolean')\n throw new Error('Knowledge search result requires a Source Found boolean.');\n const source = normalizeKnowledgeSourceReference(value.source);\n validateExpectedSourceIdentity(source, expectedSource);\n if (value.sourceFound && !source.version) {\n throw new Error('A found knowledge source search result requires an active version.');\n }\n if (value.sourceFound && expectedSource?.version && source.version !== expectedSource.version) {\n throw new Error('Knowledge search returned a different version than the exact version requested.');\n }\n if (!Array.isArray(value.evidence)) throw new Error('Knowledge search evidence must be an array.');\n if (!Array.isArray(value.queryResults)) throw new Error('Knowledge query results must be an array.');\n const evidence = value.evidence.map(normalizeKnowledgeEvidence);\n const queryResults = value.queryResults.map((queryResult, index) => {\n if (!isRecord(queryResult)) throw new Error(`Knowledge query result ${index + 1} must be an object.`);\n const query = requiredNonEmptyString(queryResult.query, `Knowledge query result ${index + 1} query`);\n if (!Array.isArray(queryResult.evidence)) {\n throw new Error(`Knowledge query result ${index + 1} evidence must be an array.`);\n }\n return { query, evidence: queryResult.evidence.map(normalizeKnowledgeEvidence) };\n });\n validateUniqueEvidence(evidence, 'Knowledge search evidence');\n for (const [index, queryResult] of queryResults.entries()) {\n validateUniqueEvidence(queryResult.evidence, `Knowledge query result ${index + 1} evidence`);\n }\n const queryEvidenceIds = new Set(queryResults.flatMap((queryResult) => queryResult.evidence.map((item) => item.id)));\n for (const item of evidence) {\n if (!queryEvidenceIds.has(item.id)) {\n throw new Error(`Final knowledge evidence \"${item.id}\" does not occur in any query result.`);\n }\n }\n for (const item of [...evidence, ...queryResults.flatMap((queryResult) => queryResult.evidence)]) {\n if (!sameKnowledgeSource(item.source, source)) {\n throw new Error(`Knowledge evidence \"${item.id}\" does not belong to the returned source.`);\n }\n }\n if (!value.sourceFound && (evidence.length > 0 || queryResults.some((result) => result.evidence.length > 0))) {\n throw new Error('A missing knowledge source search result cannot contain evidence.');\n }\n if (expectedQueries) {\n const normalizedExpectedQueries = normalizeKnowledgeQueries([...expectedQueries]);\n const actualQueries = queryResults.map((result) => result.query);\n const expectedResultQueries = value.sourceFound ? normalizedExpectedQueries : [];\n if (\n actualQueries.length !== expectedResultQueries.length ||\n actualQueries.some((query, index) => query !== expectedResultQueries[index])\n ) {\n throw new Error('Knowledge search returned query groups that do not match the requested queries.');\n }\n }\n return {\n sourceFound: value.sourceFound,\n source,\n evidence,\n queryResults,\n message: requiredString(value.message, 'Knowledge search status message'),\n };\n}\n\nexport function normalizeKnowledgeFilter(value: unknown): KnowledgeFilter {\n if (!isRecord(value)) throw new Error('Knowledge filter must be an object.');\n const branches = [\n Array.isArray(value.and),\n Array.isArray(value.or),\n value.not != null,\n value.field != null || value.operator != null,\n ].filter(Boolean).length;\n if (branches !== 1)\n throw new Error('Knowledge filter objects must contain exactly one comparison, and, or, or not expression.');\n if (Array.isArray(value.and)) {\n if (value.and.length === 0) throw new Error('Knowledge filter \"and\" groups cannot be empty.');\n return { and: value.and.map(normalizeKnowledgeFilter) };\n }\n if (Array.isArray(value.or)) {\n if (value.or.length === 0) throw new Error('Knowledge filter \"or\" groups cannot be empty.');\n return { or: value.or.map(normalizeKnowledgeFilter) };\n }\n if (value.not != null) return { not: normalizeKnowledgeFilter(value.not) };\n\n const field = typeof value.field === 'string' ? value.field.trim() : '';\n const operator = typeof value.operator === 'string' ? value.operator : '';\n const validOperators = ['eq', 'neq', 'in', 'nin', 'gt', 'gte', 'lt', 'lte', 'exists'] as const;\n if (!field || !validOperators.includes(operator as (typeof validOperators)[number])) {\n throw new Error('Knowledge filter comparisons require a field and supported operator.');\n }\n rejectUnsafeObjectKey(field, 'Knowledge filter');\n if (operator === 'exists') {\n return { field, operator };\n }\n const normalizedValue = normalizeKnowledgeMetadataValue(value.value, `Filter ${field}`);\n if ((operator === 'in' || operator === 'nin') && !Array.isArray(normalizedValue)) {\n throw new Error(`Knowledge filter operator \"${operator}\" requires an array value.`);\n }\n if (\n (operator === 'gt' || operator === 'gte' || operator === 'lt' || operator === 'lte') &&\n Array.isArray(normalizedValue)\n ) {\n throw new Error(`Knowledge filter operator \"${operator}\" requires a scalar value.`);\n }\n return {\n field,\n operator: operator as KnowledgeFilterComparisonOperator,\n value: normalizedValue,\n };\n}\n\nexport function isKnowledgeSourceReference(value: unknown): value is RivetKnowledgeSourceReference {\n try {\n normalizeKnowledgeSourceReference(value);\n return true;\n } catch {\n return false;\n }\n}\n\nexport function isKnowledgeDocument(value: unknown): value is RivetKnowledgeDocument {\n try {\n normalizeKnowledgeDocument(value);\n return true;\n } catch {\n return false;\n }\n}\n\nexport function isKnowledgeEvidence(value: unknown): value is RivetKnowledgeEvidence {\n try {\n normalizeKnowledgeEvidence(value);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction normalizeKnowledgeMetadataValue(value: unknown, label: string): KnowledgeMetadataValue {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) throw new Error(`${label} must be a finite number.`);\n return value;\n }\n if (Array.isArray(value)) {\n if (value.every((item) => typeof item === 'string')) return value;\n if (value.every((item) => typeof item === 'boolean')) return value;\n if (value.every((item) => typeof item === 'number' && Number.isFinite(item))) return value as number[];\n throw new Error(`${label} arrays must contain only strings, booleans, or finite numbers of one type.`);\n }\n throw new Error(`${label} must be a portable scalar or a homogeneous scalar array.`);\n}\n\nfunction normalizeDocumentText(value: unknown): string {\n return typeof value === 'string' ? value.replace(/\\r\\n?/g, '\\n').trim() : '';\n}\n\nfunction optionalTrimmedString(value: unknown, label: string): string | undefined {\n if (value == null || value === '') return undefined;\n if (typeof value !== 'string') throw new Error(`${label} must be a string.`);\n const normalized = value.trim();\n return normalized || undefined;\n}\n\nfunction normalizeKnowledgeVersion(value: unknown, label: string): string | undefined {\n const version = optionalTrimmedString(value, label);\n if (version && version.length > 512) throw new Error(`${label} cannot exceed 512 characters.`);\n return version;\n}\n\nfunction optionalFiniteNumber(value: unknown, label: string): number | undefined {\n if (value == null) return undefined;\n if (typeof value !== 'number' || !Number.isFinite(value)) throw new Error(`${label} must be a finite number.`);\n return value;\n}\n\nfunction requiredString(value: unknown, label: string): string {\n if (typeof value !== 'string') throw new Error(`${label} must be a string.`);\n return value;\n}\n\nfunction requiredNonEmptyString(value: unknown, label: string): string {\n const normalized = requiredString(value, label).trim();\n if (!normalized) throw new Error(`${label} cannot be empty.`);\n return normalized;\n}\n\nfunction optionalNonNegativeInteger(value: unknown, label: string): number | undefined {\n if (value == null) return undefined;\n if (!Number.isInteger(value) || (value as number) < 0) throw new Error(`${label} must be a non-negative integer.`);\n return value as number;\n}\n\nfunction requiredPositiveInteger(value: unknown, label: string): number {\n if (!Number.isInteger(value) || (value as number) < 1) throw new Error(`${label} must be a positive integer.`);\n return value as number;\n}\n\nfunction validateUniqueEvidence(evidence: RivetKnowledgeEvidence[], label: string): void {\n const seen = new Set<string>();\n for (const item of evidence) {\n if (seen.has(item.id)) throw new Error(`${label} contains duplicate evidence ID \"${item.id}\".`);\n seen.add(item.id);\n }\n}\n\nfunction sameKnowledgeSource(left: RivetKnowledgeSourceReference, right: RivetKnowledgeSourceReference): boolean {\n return (\n left.connectionId === right.connectionId &&\n left.sourceId === right.sourceId &&\n (left.version ?? '') === (right.version ?? '')\n );\n}\n\nfunction validateExpectedSourceIdentity(\n actual: RivetKnowledgeSourceReference,\n expected: RivetKnowledgeSourceReference | undefined,\n): void {\n if (expected && (actual.connectionId !== expected.connectionId || actual.sourceId !== expected.sourceId)) {\n throw new Error('Knowledge store returned a result for a different source.');\n }\n}\n\nfunction rejectUnsafeObjectKey(key: string, label: string): void {\n if (isReservedKnowledgeObjectKey(key)) {\n throw new Error(`${label} field \"${key}\" is reserved.`);\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n", "export type CustomProviderApi = 'completions' | 'responses';\n\nexport type CustomProviderApiContract = Readonly<{\n api: CustomProviderApi;\n adapter: 'openai-compatible' | 'openai-responses';\n endpointPath: '/chat/completions' | '/responses';\n label: 'Custom Completions' | 'Custom Responses';\n structuredOutput: 'raw-response-format' | 'sdk-output';\n parallelToolCalls: 'enabled-only-raw-field' | 'openai-option';\n}>;\n\nexport const customProviderApiOptions = [\n { value: 'completions', label: 'Completions' },\n { value: 'responses', label: 'Responses' },\n] as const;\n\nconst customProviderApiContracts: Record<CustomProviderApi, CustomProviderApiContract> = {\n completions: {\n api: 'completions',\n adapter: 'openai-compatible',\n endpointPath: '/chat/completions',\n label: 'Custom Completions',\n structuredOutput: 'raw-response-format',\n parallelToolCalls: 'enabled-only-raw-field',\n },\n responses: {\n api: 'responses',\n adapter: 'openai-responses',\n endpointPath: '/responses',\n label: 'Custom Responses',\n structuredOutput: 'sdk-output',\n parallelToolCalls: 'openai-option',\n },\n};\n\n/**\n * Keep legacy nodes on Chat Completions while rejecting corrupt/API-authored\n * values before a provider request is created.\n */\nexport function parseCustomProviderApi(value: unknown): CustomProviderApi {\n switch (value) {\n case undefined:\n case 'completions':\n return 'completions';\n case 'responses':\n return 'responses';\n default:\n throw new Error(`Unsupported Custom provider API: ${String(value)}.`);\n }\n}\n\nexport function getCustomProviderApiContract(value: unknown): CustomProviderApiContract {\n return customProviderApiContracts[parseCustomProviderApi(value)];\n}\n", "import type { ChatV2Provider } from './chatV2Types.js';\n\nexport type ChatV2BuiltInProvider = Exclude<ChatV2Provider, 'custom'>;\n\nexport type ChatV2CredentialNames = {\n programmaticName: string;\n environmentVariableName: string;\n};\n\nexport type ChatV2CredentialNamesByProvider = Partial<Record<ChatV2BuiltInProvider, ChatV2CredentialNames>>;\n\nexport const CHAT_V2_DEFAULT_CREDENTIAL_NAMES = {\n openai: {\n programmaticName: 'openAiApiKey',\n environmentVariableName: 'OPENAI_API_KEY',\n },\n anthropic: {\n programmaticName: 'anthropicApiKey',\n environmentVariableName: 'ANTHROPIC_API_KEY',\n },\n google: {\n programmaticName: 'googleApiKey',\n environmentVariableName: 'GOOGLE_GENERATIVE_AI_API_KEY',\n },\n} as const satisfies Record<ChatV2BuiltInProvider, ChatV2CredentialNames>;\n\nconst programmaticNamePattern = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\nconst environmentVariableNamePattern = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\nexport function isChatV2BuiltInProvider(provider: ChatV2Provider): provider is ChatV2BuiltInProvider {\n return Object.hasOwn(CHAT_V2_DEFAULT_CREDENTIAL_NAMES, provider);\n}\n\nexport function isValidChatV2ProgrammaticCredentialName(name: string): boolean {\n return programmaticNamePattern.test(name);\n}\n\nexport function isValidChatV2EnvironmentCredentialName(name: string): boolean {\n return environmentVariableNamePattern.test(name);\n}\n\nexport function getChatV2DefaultCredentialNames(provider: ChatV2BuiltInProvider): ChatV2CredentialNames {\n return { ...CHAT_V2_DEFAULT_CREDENTIAL_NAMES[provider] };\n}\n\nexport function getChatV2CredentialNamesForDisplay(\n provider: ChatV2BuiltInProvider,\n value: unknown,\n): ChatV2CredentialNames {\n try {\n return normalizeChatV2CredentialNames(provider, value);\n } catch {\n return getChatV2DefaultCredentialNames(provider);\n }\n}\n\nexport function normalizeChatV2CredentialNames(provider: ChatV2BuiltInProvider, value: unknown): ChatV2CredentialNames {\n if (value != null && (typeof value !== 'object' || Array.isArray(value))) {\n throw new Error(`${provider} API key names must be an object.`);\n }\n\n const raw = value as Partial<ChatV2CredentialNames> | undefined;\n if (raw?.programmaticName != null && typeof raw.programmaticName !== 'string') {\n throw new Error(`${provider} programmatic API key name must be a string.`);\n }\n if (raw?.environmentVariableName != null && typeof raw.environmentVariableName !== 'string') {\n throw new Error(`${provider} API key environment variable must be a string.`);\n }\n\n const defaults = CHAT_V2_DEFAULT_CREDENTIAL_NAMES[provider];\n const programmaticName = raw?.programmaticName?.trim() || defaults.programmaticName;\n const environmentVariableName = raw?.environmentVariableName?.trim() || defaults.environmentVariableName;\n\n if (!isValidChatV2ProgrammaticCredentialName(programmaticName)) {\n throw new Error(\n `${provider} programmatic API key name must be a JavaScript-style identifier (letters, digits, _, or $, and not starting with a digit).`,\n );\n }\n if (!isValidChatV2EnvironmentCredentialName(environmentVariableName)) {\n throw new Error(\n `${provider} API key environment variable must contain only letters, digits, and _, and must not start with a digit.`,\n );\n }\n\n return { programmaticName, environmentVariableName };\n}\n\nexport function normalizeChatV2CredentialNamesByProvider(value: unknown): ChatV2CredentialNamesByProvider | undefined {\n if (value == null) return undefined;\n if (typeof value !== 'object' || Array.isArray(value)) {\n throw new Error('Built-in provider API key names must be an object.');\n }\n\n const raw = value as Record<string, unknown>;\n const unsupportedProvider = Object.keys(raw).find(\n (provider) => !Object.hasOwn(CHAT_V2_DEFAULT_CREDENTIAL_NAMES, provider),\n );\n if (unsupportedProvider) {\n throw new Error(`Unsupported provider API key names entry: ${unsupportedProvider}.`);\n }\n\n const normalized: ChatV2CredentialNamesByProvider = {};\n for (const provider of ['openai', 'anthropic', 'google'] as const) {\n if (raw[provider] != null) {\n normalized[provider] = normalizeChatV2CredentialNames(provider, raw[provider]);\n }\n }\n\n return Object.keys(normalized).length === 0 ? undefined : normalized;\n}\n\nexport function isDefaultChatV2CredentialNames(provider: ChatV2BuiltInProvider, names: ChatV2CredentialNames): boolean {\n const defaults = CHAT_V2_DEFAULT_CREDENTIAL_NAMES[provider];\n return (\n names.programmaticName === defaults.programmaticName &&\n names.environmentVariableName === defaults.environmentVariableName\n );\n}\n\nexport function getNonDefaultChatV2CredentialNames(\n provider: ChatV2Provider,\n namesByProvider: ChatV2CredentialNamesByProvider | undefined,\n): ChatV2CredentialNames | undefined {\n if (!isChatV2BuiltInProvider(provider) || namesByProvider?.[provider] == null) return undefined;\n\n try {\n const names = normalizeChatV2CredentialNames(provider, namesByProvider[provider]);\n return isDefaultChatV2CredentialNames(provider, names) ? undefined : names;\n } catch {\n return undefined;\n }\n}\n", "import type { ChatV2CredentialReference, ChatV2CredentialResult } from './chatV2ProviderProfile.js';\nimport { createLLMChatV2NodeData, type LLMChatV2NodeData, type LLMChatV2ProfileData } from './llmChatV2NodeData.js';\nimport type { ChatV2Provider } from './chatV2Types.js';\nimport { parseCustomProviderApi } from './customProviderApi.js';\nimport {\n llmProfileBooleanDataKeys,\n llmProfileOptionalNumberDataKeys,\n llmProfileRequiredNumberDataKeys,\n llmProfileResolvedInputToggleDataKeys,\n llmProfileStringDataKeys,\n} from './llmProfileFieldRegistry.js';\nimport { LLM_PROFILE_VALUE_VERSION, pickLLMChatV2ProfileData, type LLMProfileValue } from './llmProfileTypes.js';\nimport { createRivetLLMProfileHealthIdentity } from './llmProfileHealthStore.js';\nimport type { NodeId } from '../NodeBase.js';\nimport type { ProjectId } from '../Project.js';\nimport { normalizeChatV2CredentialNamesByProvider } from './chatV2CredentialNames.js';\n\nexport {\n applyLLMProfileToNodeData,\n createDefaultLLMProfileValue,\n createLLMProfileNodeData,\n LLM_PROFILE_VALUE_VERSION,\n pickLLMChatV2ProfileData,\n type LLMProfileValue,\n} from './llmProfileTypes.js';\n\nconst credentialSources = new Set<ChatV2CredentialReference['source']>([\n 'input',\n 'settings',\n 'plugin',\n 'programmatic',\n 'environment',\n 'none',\n]);\nconst profileProviders = new Set<ChatV2Provider>(['openai', 'anthropic', 'google', 'custom']);\n\nexport function normalizeLLMProfileValue(value: unknown): LLMProfileValue {\n if (!isRecord(value)) {\n throw new Error('LLM Profile input must contain an LLM profile value.');\n }\n\n if (value.version !== LLM_PROFILE_VALUE_VERSION) {\n throw new Error(`Unsupported LLM Profile version: ${String(value.version)}.`);\n }\n\n if (!isRecord(value.configuration)) {\n throw new Error('LLM Profile configuration is missing.');\n }\n\n const defaults = createLLMChatV2NodeData();\n const provider = normalizeProvider(value.configuration.provider ?? defaults.provider);\n const model = value.configuration.model;\n if (typeof model !== 'string' || !model.trim()) {\n throw new Error('LLM Profile model must be a non-empty string.');\n }\n\n const credential = normalizeCredential(value.credential);\n const configuration = normalizeConfiguration({\n ...defaults,\n ...value.configuration,\n provider,\n model: model.trim(),\n } as LLMChatV2NodeData);\n\n const sourceIdentity = normalizeSourceIdentity(value.healthIdentity);\n const profileName = normalizeProfileName(value.profileName) ?? sourceIdentity.profileName;\n return {\n version: LLM_PROFILE_VALUE_VERSION,\n configuration,\n credential,\n ...(profileName == null ? {} : { profileName }),\n healthIdentity: createRivetLLMProfileHealthIdentity({\n configuration,\n credential,\n ...sourceIdentity,\n ...(profileName == null ? {} : { profileName }),\n }),\n };\n}\n\n/**\n * Normalizes the single LLM Profile or ordered fallback chain accepted by\n * LLM Chat's From profile input. We validate every member here rather than\n * trusting a same-type `llm-config[]` wrapper: arrays can otherwise carry\n * malformed values without re-entering scalar coercion.\n */\nexport function normalizeLLMProfileChainInput(value: unknown): LLMProfileValue[] {\n const rawProfiles = Array.isArray(value) ? value : [value];\n\n if (rawProfiles.length === 0) {\n throw new Error('LLM Profiles input must contain at least one LLM Profile.');\n }\n\n return rawProfiles.map((profile, index) => {\n try {\n return normalizeLLMProfileValue(profile);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`LLM Profiles input item ${index} is invalid: ${message}`);\n }\n });\n}\n\n/**\n * Programmatic or serialized llm-config values may originate outside the\n * currently executing project. Always bind health to that project before\n * shared storage is consulted so copied values cannot share a circuit across\n * projects. Preserve an originating profile-node identity when one exists;\n * otherwise the consuming Chat node owns the identity.\n */\nexport function scopeLLMProfileHealthIdentity(\n profile: LLMProfileValue,\n fallback: {\n projectId: ProjectId;\n profileNodeId: NodeId;\n chatNodeHeaders?: Record<string, string> | undefined;\n },\n): LLMProfileValue {\n const profileNodeId = profile.healthIdentity?.profileNodeId ?? fallback.profileNodeId;\n const profileName =\n normalizeProfileName(profile.profileName) ?? normalizeProfileName(profile.healthIdentity?.profileName);\n const healthIdentity = createRivetLLMProfileHealthIdentity({\n configuration: profile.configuration,\n credential: profile.credential,\n chatNodeHeaders: fallback.chatNodeHeaders,\n projectId: fallback.projectId,\n profileNodeId,\n ...(profileName == null ? {} : { profileName }),\n });\n\n if (\n profile.healthIdentity?.key === healthIdentity.key &&\n profile.profileName === profileName &&\n profile.healthIdentity?.profileName === profileName\n ) {\n return profile;\n }\n\n return {\n ...profile,\n ...(profileName == null ? {} : { profileName }),\n healthIdentity,\n };\n}\n\nfunction normalizeConfiguration(data: LLMChatV2NodeData): LLMChatV2ProfileData {\n for (const field of llmProfileStringDataKeys) {\n if (typeof data[field] !== 'string') {\n throw new Error(`LLM Profile ${field} must be a string.`);\n }\n }\n for (const field of llmProfileBooleanDataKeys) {\n if (typeof data[field] !== 'boolean') {\n throw new Error(`LLM Profile ${field} must be a boolean.`);\n }\n }\n for (const field of llmProfileRequiredNumberDataKeys) {\n if (typeof data[field] !== 'number' || !Number.isFinite(data[field])) {\n throw new Error(`LLM Profile ${field} must be a finite number.`);\n }\n }\n for (const field of llmProfileOptionalNumberDataKeys) {\n const fieldValue = data[field];\n if (fieldValue != null && (typeof fieldValue !== 'number' || !Number.isFinite(fieldValue))) {\n throw new Error(`LLM Profile ${field} must be a finite number when provided.`);\n }\n }\n\n if (!Array.isArray(data.stopSequences) || data.stopSequences.some((sequence) => typeof sequence !== 'string')) {\n throw new Error('LLM Profile stopSequences must be an array of strings.');\n }\n if (\n !Array.isArray(data.headers) ||\n data.headers.some(\n (header) => !isRecord(header) || typeof header.key !== 'string' || typeof header.value !== 'string',\n )\n ) {\n throw new Error('LLM Profile headers must contain string key/value pairs.');\n }\n if (data.apiKeySource !== 'environment' && data.apiKeySource !== 'input') {\n throw new Error(`Unsupported LLM Profile API key source: ${String(data.apiKeySource)}.`);\n }\n assertEnumValue(data.openAIWebSearchContextSize, ['low', 'medium', 'high'], 'OpenAI web search context');\n const customProviderApi = parseCustomProviderApi(data.customProviderApi);\n assertEnumValue(data.anthropicThinkingMode, ['', 'adaptive', 'enabled', 'disabled'], 'Anthropic thinking mode');\n assertEnumValue(data.anthropicEffort, ['', 'low', 'medium', 'high', 'max'], 'Anthropic effort');\n assertEnumValue(data.anthropicCacheControlTtl, ['', '5m', '1h'], 'Anthropic cache TTL');\n assertEnumValue(data.googleThinkingLevel, ['', 'minimal', 'low', 'medium', 'high'], 'Google thinking level');\n\n const resolvedData = {\n ...data,\n customProviderApi,\n providerApiKeyNames: normalizeChatV2CredentialNamesByProvider(data.providerApiKeyNames),\n model: data.model.trim(),\n customProviderBaseURL: data.customProviderBaseURL.trim(),\n customProviderApiKeyProgrammaticName: data.customProviderApiKeyProgrammaticName?.trim(),\n customProviderApiKeyEnvVarName: data.customProviderApiKeyEnvVarName?.trim(),\n stopSequences: [...data.stopSequences],\n headers: data.headers.map(({ key, value }) => ({ key, value })),\n };\n\n // A profile is a resolved configuration value. LLM Chat intentionally does not\n // expose the profile-owned inputs, so accepting a dynamic flag here would let\n // stale hidden connections influence a supposedly self-contained profile.\n for (const field of llmProfileResolvedInputToggleDataKeys) {\n (resolvedData as Record<string, unknown>)[field] = false;\n }\n\n return pickLLMChatV2ProfileData(resolvedData);\n}\n\nfunction assertEnumValue(value: unknown, allowed: readonly string[], label: string): asserts value is string {\n if (typeof value !== 'string' || !allowed.includes(value)) {\n throw new Error(`Unsupported LLM Profile ${label}: ${String(value)}.`);\n }\n}\n\nfunction normalizeProvider(value: unknown): ChatV2Provider {\n if (typeof value !== 'string' || !profileProviders.has(value as ChatV2Provider)) {\n throw new Error(`Unsupported LLM Profile provider: ${String(value)}.`);\n }\n\n return value as ChatV2Provider;\n}\n\nfunction normalizeCredential(value: unknown): ChatV2CredentialResult {\n if (\n !isRecord(value) ||\n !isRecord(value.reference) ||\n typeof value.reference.source !== 'string' ||\n !credentialSources.has(value.reference.source as ChatV2CredentialReference['source'])\n ) {\n throw new Error('LLM Profile credential metadata is invalid.');\n }\n\n const credentialValue = value.value;\n if (credentialValue != null && typeof credentialValue !== 'string') {\n throw new Error('LLM Profile API key must be a string when provided.');\n }\n\n const name = value.reference.name;\n if (name != null && typeof name !== 'string') {\n throw new Error('LLM Profile credential name must be a string when provided.');\n }\n\n return {\n ...(credentialValue == null ? {} : { value: credentialValue }),\n reference: {\n source: value.reference.source as ChatV2CredentialReference['source'],\n ...(name == null ? {} : { name }),\n },\n };\n}\n\nfunction normalizeSourceIdentity(value: unknown): { projectId?: ProjectId; profileNodeId?: NodeId; profileName?: string } {\n if (!isRecord(value)) {\n return {};\n }\n\n const profileName = normalizeProfileName(value.profileName);\n return {\n ...(typeof value.projectId === 'string' ? { projectId: value.projectId as ProjectId } : {}),\n ...(typeof value.profileNodeId === 'string' ? { profileNodeId: value.profileNodeId as NodeId } : {}),\n ...(profileName == null ? {} : { profileName }),\n };\n}\n\nfunction normalizeProfileName(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined;\n const normalized = value.trim();\n return normalized === '' ? undefined : normalized;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value != null && !Array.isArray(value);\n}\n", "import {\n type ChatMessage,\n type DataType,\n type DataValue,\n type GetDataValue,\n type ScalarDataType,\n type ScalarOrArrayDataValue,\n getScalarTypeOf,\n isArrayDataType,\n isArrayDataValue,\n isFunctionDataType,\n isScalarDataType,\n unwrapDataValue,\n} from '../model/DataValue.js';\nimport { expectTypeOptional } from './expectType.js';\nimport type { GraphId } from '../index.js';\nimport {\n normalizeKnowledgeDocument,\n normalizeKnowledgeEvidence,\n normalizeKnowledgeSourceReference,\n} from '../integrations/KnowledgeStoreValidation.js';\nimport { normalizeLLMProfileValue } from '../model/chat-v2/llmProfile.js';\n\ntype ScalarCoercer = (value: ScalarOrArrayDataValue | undefined) => unknown;\n\ntype ScalarCoercionRule = {\n readonly coerce?: ScalarCoercer;\n readonly canAttempt: (from: DataType) => boolean;\n};\n\ntype ScalarCoercionRuleRegistry = {\n readonly [T in ScalarDataType]: ScalarCoercionRule;\n};\n\nfunction isValidatedObjectValueType(type: DataType): boolean {\n return (\n type === 'knowledge-source' ||\n type === 'knowledge-document' ||\n type === 'knowledge-evidence' ||\n type === 'llm-config'\n );\n}\n\nfunction canAttemptGeneralCoercion(from: DataType, to: DataType): boolean {\n return !isValidatedObjectValueType(from) || to === 'object' || to === 'string';\n}\n\nfunction generalScalarRule(target: ScalarDataType, coerce?: ScalarCoercer): ScalarCoercionRule {\n return {\n ...(coerce ? { coerce } : {}),\n canAttempt: (from) => canAttemptGeneralCoercion(from, target),\n };\n}\n\nfunction sameTypeOrObjectScalarRule(target: ScalarDataType, coerce?: ScalarCoercer): ScalarCoercionRule {\n return {\n ...(coerce ? { coerce } : {}),\n canAttempt: (from) => from === target || from === 'object',\n };\n}\n\n/**\n * The single scalar coercion policy used by both runtime conversion and\n * type-level port compatibility. Array, function, and `any` wrappers are\n * handled once around this registry because their behavior is structural.\n */\nconst scalarCoercionRules: ScalarCoercionRuleRegistry = {\n any: {\n canAttempt: () => true,\n },\n boolean: generalScalarRule('boolean', coerceToBoolean),\n string: generalScalarRule('string', coerceToString),\n number: generalScalarRule('number', coerceToNumber),\n date: generalScalarRule('date'),\n time: generalScalarRule('time'),\n datetime: generalScalarRule('datetime'),\n 'chat-message': generalScalarRule('chat-message', coerceToChatMessage),\n 'control-flow-excluded': generalScalarRule('control-flow-excluded'),\n object: generalScalarRule('object', coerceToObject),\n 'gpt-function': {\n canAttempt: (from) => from === 'object',\n },\n vector: generalScalarRule('vector'),\n image: sameTypeOrObjectScalarRule('image'),\n binary: sameTypeOrObjectScalarRule('binary', coerceToBinary),\n audio: sameTypeOrObjectScalarRule('audio'),\n 'graph-reference': generalScalarRule('graph-reference', coerceToGraphReference),\n 'knowledge-source': sameTypeOrObjectScalarRule('knowledge-source', (value) =>\n coerceValidatedObjectValue(value, normalizeKnowledgeSourceReference),\n ),\n 'knowledge-document': sameTypeOrObjectScalarRule('knowledge-document', (value) =>\n coerceValidatedObjectValue(value, normalizeKnowledgeDocument),\n ),\n 'knowledge-evidence': sameTypeOrObjectScalarRule('knowledge-evidence', (value) =>\n coerceValidatedObjectValue(value, normalizeKnowledgeEvidence),\n ),\n 'llm-config': sameTypeOrObjectScalarRule('llm-config', (value) =>\n coerceValidatedObjectValue(value, normalizeLLMProfileValue),\n ),\n document: generalScalarRule('document'),\n};\n\nexport function coerceTypeOptional<T extends DataType>(\n wrapped: DataValue | undefined,\n type: T,\n): GetDataValue<T>['value'] | undefined {\n if (wrapped && isFunctionDataType(type)) {\n return expectTypeOptional(wrapped, type) as GetDataValue<T>['value'] | undefined;\n }\n\n const value = wrapped ? unwrapDataValue(wrapped) : undefined;\n\n // Coerce 'true' to [true] for example\n if (isArrayDataType(type) && !isArrayDataValue(value)) {\n const coerced = coerceTypeOptional(value, getScalarTypeOf(type));\n if (coerced === undefined) {\n return undefined;\n }\n\n const coercedArray = [coerced] as unknown;\n // @ts-expect-error Generic T is not narrowed to its array subtype within this runtime-guarded branch.\n return coercedArray as GetDataValue<T>['value'];\n }\n\n // Preserve arrays whose runtime shape is carried by an any/object wrapper,\n // or coerce each item when the scalar families differ.\n if (isArrayDataType(type) && isArrayDataValue(value)) {\n if (getScalarTypeOf(type) === getScalarTypeOf(value.type)) {\n // @ts-expect-error Generic T is not narrowed to its array subtype within this runtime-guarded branch.\n return value.value as unknown as GetDataValue<T>['value'];\n }\n\n const coercedArray = value.value.map((v) =>\n coerceTypeOptional({ type: getScalarTypeOf(value.type), value: v } as DataValue, getScalarTypeOf(type)),\n ) as unknown;\n\n // @ts-expect-error Generic T is not narrowed to its array subtype within this runtime-guarded branch.\n return coercedArray as GetDataValue<T>['value'];\n }\n\n const scalarRule = isScalarDataType(type) ? scalarCoercionRules[type] : undefined;\n const result = scalarRule?.coerce ? scalarRule.coerce(value) : coerceWithoutSpecializedRule(value, type);\n\n return result as GetDataValue<T>['value'] | undefined;\n}\n\nfunction coerceWithoutSpecializedRule(value: ScalarOrArrayDataValue | undefined, type: DataType): unknown {\n if (!value) {\n return value;\n }\n\n if (getScalarTypeOf(value.type) === 'any' || getScalarTypeOf(type) === 'any') {\n return value.value;\n }\n\n return expectTypeOptional(value, type);\n}\n\nexport function coerceType<T extends DataType>(value: DataValue | undefined, type: T): GetDataValue<T>['value'] {\n const result = coerceTypeOptional(value, type);\n if (result === undefined) {\n throw new Error(`Expected value of type ${type} but got undefined`);\n }\n return result as GetDataValue<T>['value'];\n}\n\nexport function inferType(value: unknown): DataValue {\n if (value === undefined) {\n return { type: 'any', value: undefined };\n }\n\n if (value === null) {\n return { type: 'any', value: null };\n }\n\n if (typeof value === 'function') {\n return { type: 'fn<any>', value: value as () => unknown };\n }\n\n if (typeof value === 'string') {\n return { type: 'string', value };\n }\n\n if (typeof value === 'boolean') {\n return { type: 'boolean', value };\n }\n\n if (typeof value === 'number') {\n return { type: 'number', value };\n }\n\n if (value instanceof Date) {\n return { type: 'datetime', value: value.toISOString() };\n }\n\n if (Array.isArray(value)) {\n if (value.length === 0) {\n return { type: 'any[]', value: [] };\n }\n\n const inferredType = inferType(value[0]);\n\n return { type: inferredType.type + '[]', value } as DataValue;\n }\n\n if (typeof value === 'object') {\n return { type: 'object', value: value as Record<string, unknown> };\n }\n\n throw new Error(`Cannot infer type of value: ${value}`);\n}\n\nfunction coerceToString(value: DataValue | undefined): string | undefined {\n if (!value) {\n return '';\n }\n\n if (isArrayDataValue(value)) {\n return value.value\n .map((v) => coerceTypeOptional({ type: getScalarTypeOf(value.type), value: v } as DataValue, 'string'))\n .join('\\n');\n }\n\n if (value.type === 'string') {\n return value.value;\n }\n\n if (value.type === 'boolean') {\n return value.value.toString();\n }\n\n if (value.type === 'number') {\n return value.value.toString();\n }\n\n if (value.type === 'date') {\n return value.value;\n }\n\n if (value.type === 'time') {\n return value.value;\n }\n\n if (value.type === 'datetime') {\n return value.value;\n }\n\n if (value.type === 'chat-message') {\n const messageParts = Array.isArray(value.value.message) ? value.value.message : [value.value.message];\n const singleString = messageParts\n .map((part) => {\n if (typeof part === 'string') {\n return part;\n }\n\n return part.type === 'url' ? `(Image: ${part.url})` : '(Image)';\n })\n .join('\\n\\n');\n return singleString;\n }\n\n if (value.value === undefined) {\n return undefined;\n }\n\n if (value.value === null) {\n return undefined;\n }\n\n if (typeof value.value === 'object' && !Array.isArray(value.value)) {\n return JSON.stringify(value.value);\n }\n\n // Don't know, so try to infer it from the type of the value\n // Any and object are basically the same...\n if (value.type === 'any' || value.type === 'object') {\n const inferred = inferType(value.value);\n return coerceTypeOptional(inferred, 'string');\n }\n\n return JSON.stringify(value.value);\n}\n\nfunction coerceToChatMessage(value: DataValue | undefined): ChatMessage | undefined {\n const chatMessage = coerceToChatMessageRaw(value);\n\n if (chatMessage?.type === 'assistant') {\n // Double check that arguments is a string, stringify if needed\n if (chatMessage.function_call?.arguments && typeof chatMessage.function_call.arguments !== 'string') {\n chatMessage.function_call.arguments = JSON.stringify(chatMessage.function_call.arguments);\n }\n }\n\n return chatMessage;\n}\n\nfunction coerceToChatMessageRaw(value: DataValue | undefined): ChatMessage | undefined {\n if (!value || value.value == null) {\n return undefined;\n }\n\n if (value.type === 'chat-message') {\n return value.value;\n }\n\n if (value.type === 'string') {\n return { type: 'user', message: value.value };\n }\n\n if (\n value.type === 'object' &&\n 'type' in value.value &&\n 'message' in value.value &&\n typeof value.value.type === 'string' &&\n typeof value.value.message === 'string'\n ) {\n return value.value as ChatMessage;\n }\n\n if (value.type === 'any') {\n const inferred = inferType(value.value);\n return coerceTypeOptional(inferred, 'chat-message');\n }\n}\n\nfunction coerceToBoolean(value: DataValue | undefined) {\n if (!value || !value.value) {\n return false;\n }\n\n if (isArrayDataValue(value)) {\n return value.value\n .map((v) => coerceTypeOptional({ type: value.type.replace('[]', ''), value: v } as DataValue, 'boolean'))\n .every((v) => v);\n }\n\n if (value.type === 'string') {\n return value.value.length > 0 && value.value !== 'false';\n }\n\n if (value.type === 'boolean') {\n return value.value;\n }\n\n if (value.type === 'number') {\n return value.value !== 0;\n }\n\n if (value.type === 'date') {\n return true;\n }\n\n if (value.type === 'time') {\n return true;\n }\n\n if (value.type === 'datetime') {\n return true;\n }\n\n if (value.type === 'chat-message') {\n const hasValue =\n (Array.isArray(value.value.message) && value.value.message.length > 0) ||\n (typeof value.value.message === 'string' && value.value.message.length > 0) ||\n (typeof value.value.message === 'object' &&\n 'type' in value.value.message &&\n value.value.message.type === 'url' &&\n value.value.message.url.length > 0);\n\n return hasValue;\n }\n\n return !!value.value;\n}\n\nfunction coerceToNumber(value: DataValue | undefined): number | undefined {\n if (!value || value.value == null) {\n return undefined;\n }\n\n if (isArrayDataValue(value)) {\n return undefined;\n }\n\n if (value.type === 'string') {\n return parseFloat(value.value);\n }\n\n if (value.type === 'boolean') {\n return value.value ? 1 : 0;\n }\n\n if (value.type === 'number') {\n return value.value;\n }\n\n if (value.type === 'date') {\n return new Date(value.value).valueOf();\n }\n\n if (value.type === 'time') {\n return new Date(value.value).valueOf();\n }\n\n if (value.type === 'datetime') {\n return new Date(value.value).valueOf();\n }\n\n if (value.type === 'chat-message') {\n if (typeof value.value.message === 'string') {\n return parseFloat(value.value.message);\n }\n\n if (\n Array.isArray(value.value.message) &&\n value.value.message.length === 1 &&\n typeof value.value.message[0] === 'string'\n ) {\n return parseFloat(value.value.message[0]);\n }\n\n return undefined;\n }\n\n if (value.type === 'any' || value.type === 'object') {\n const inferred = inferType(value.value);\n if (inferred.type === 'any' || inferred.type === 'object') {\n return undefined;\n }\n return coerceTypeOptional(inferred, 'number');\n }\n\n return undefined;\n}\n\nfunction coerceToObject(value: DataValue | undefined): object | undefined {\n if (!value || value.value == null) {\n return undefined;\n }\n\n return value.value; // Whatever, consider anything an object\n}\n\nfunction coerceToBinary(value: DataValue | undefined): Uint8Array | undefined {\n if (!value || value.value == null) {\n return undefined;\n }\n\n if (value.type === 'binary') {\n return value.value;\n }\n\n if (value.type === 'string') {\n return new TextEncoder().encode(value.value);\n }\n\n if (value.type === 'boolean') {\n return new TextEncoder().encode(value.value.toString());\n }\n\n if (value.type === 'vector' || value.type === 'number[]') {\n return new Uint8Array(value.value);\n }\n\n if (value.type === 'number') {\n return new Uint8Array([value.value]);\n }\n\n if (value.type === 'audio' || value.type === 'image' || value.type === 'document') {\n return value.value.data;\n }\n\n return new TextEncoder().encode(JSON.stringify(value.value));\n}\n\nfunction coerceToGraphReference(value: DataValue | undefined): { graphName: string; graphId: GraphId } | undefined {\n if (!value || value.value == null) {\n return undefined;\n }\n\n if (value.type === 'graph-reference') {\n return value.value;\n }\n\n if (value.type === 'string') {\n return { graphName: value.value, graphId: '' as GraphId };\n }\n\n if (value.type === 'object' && 'graphName' in value.value && 'graphId' in value.value) {\n return value.value as { graphName: string; graphId: GraphId };\n }\n\n return undefined;\n}\n\nfunction coerceValidatedObjectValue<T>(value: DataValue | undefined, normalize: (value: unknown) => T): T | undefined {\n if (!value || value.value == null || isArrayDataValue(value)) return undefined;\n try {\n return normalize(value.value);\n } catch {\n return undefined;\n }\n}\n\nexport function canBeCoercedAny(from: DataType | Readonly<DataType[]>, to: DataType | Readonly<DataType[]>) {\n for (const fromType of Array.isArray(from) ? from : [from]) {\n for (const toType of Array.isArray(to) ? to : [to]) {\n if (canBeCoerced(fromType, toType)) {\n return true;\n }\n }\n }\n return false;\n}\n\nexport function canBeCoerced(from: DataType, to: DataType) {\n if (to === 'any') {\n return scalarCoercionRules.any.canAttempt(from);\n }\n\n if (from === 'any') {\n return true;\n }\n\n if (isArrayDataType(to) && isArrayDataType(from)) {\n return canBeCoerced(getScalarTypeOf(from), getScalarTypeOf(to));\n }\n\n if (isArrayDataType(to) && !isArrayDataType(from)) {\n return canBeCoerced(from, getScalarTypeOf(to));\n }\n\n if (isArrayDataType(from) && !isArrayDataType(to)) {\n return to === 'string' || to === 'object';\n }\n\n if (isScalarDataType(to)) {\n return scalarCoercionRules[to].canAttempt(from);\n }\n\n return canAttemptGeneralCoercion(from, to);\n}\n", "import { JSONPath } from 'jsonpath-plus';\nimport { isInterpolationRegexLiteralStart, isInterpolationSyntaxCharacterEscaped } from './interpolationSyntax.js';\n\nfunction getNextNonWhitespaceCharacter(value: string, index: number): string | undefined {\n for (let cursor = index; cursor < value.length; cursor++) {\n if (!/\\s/.test(value[cursor]!)) {\n return value[cursor];\n }\n }\n\n return undefined;\n}\n\nfunction getWhitespaceRunEnd(value: string, index: number): number {\n let cursor = index;\n while (cursor < value.length && /\\s/.test(value[cursor]!)) {\n cursor += 1;\n }\n return cursor;\n}\n\n/**\n * Normalizes Rivet's historically accepted convenience whitespace around\n * JSONPath structural separators. Quoted values, regular expressions, filter\n * expressions, and object literals keep their authored contents unchanged.\n *\n * All runtime JSONPath consumers must pass through this helper so stored node\n * paths and interpolation suffixes accept the same path language.\n */\nexport function normalizeJsonPathExpression(path: string): string {\n const trimmedPath = path.trim();\n if (!/\\s/.test(trimmedPath)) {\n return trimmedPath;\n }\n\n const result: string[] = [];\n let lastResultCharacter: string | undefined;\n let quote: '\"' | \"'\" | '`' | undefined;\n let regex = false;\n let regexCharacterClass = false;\n const filterBrackets: boolean[] = [];\n let filterDepth = 0;\n\n const append = (value: string): void => {\n if (value === '') {\n return;\n }\n\n result.push(value);\n lastResultCharacter = value.at(-1);\n };\n\n for (let cursor = 0; cursor < trimmedPath.length; cursor++) {\n const character = trimmedPath[cursor]!;\n\n if (regex) {\n if (character === '[' && !isInterpolationSyntaxCharacterEscaped(trimmedPath, cursor)) {\n regexCharacterClass = true;\n } else if (character === ']' && !isInterpolationSyntaxCharacterEscaped(trimmedPath, cursor)) {\n regexCharacterClass = false;\n } else if (\n character === '/' &&\n !regexCharacterClass &&\n !isInterpolationSyntaxCharacterEscaped(trimmedPath, cursor)\n ) {\n regex = false;\n }\n append(character);\n continue;\n }\n\n if (quote) {\n if (character === quote && !isInterpolationSyntaxCharacterEscaped(trimmedPath, cursor)) {\n quote = undefined;\n }\n append(character);\n continue;\n }\n\n if (character === '\"' || character === \"'\" || character === '`') {\n quote = character;\n append(character);\n continue;\n }\n\n if (character === '/' && isInterpolationRegexLiteralStart(trimmedPath, cursor)) {\n regex = true;\n regexCharacterClass = false;\n append(character);\n continue;\n }\n\n const insideFilter = filterDepth > 0;\n\n if (/\\s/.test(character)) {\n const whitespaceEnd = getWhitespaceRunEnd(trimmedPath, cursor);\n const previousCharacter = lastResultCharacter;\n const nextCharacter = trimmedPath[whitespaceEnd];\n // jsonpath-plus rejects whitespace immediately inside either bracket.\n // Preserve other filter whitespace because it may separate JavaScript\n // tokens or be meaningful inside filter expressions.\n const shouldRemoveWhitespace =\n previousCharacter === '[' ||\n nextCharacter === ']' ||\n nextCharacter === '[' ||\n (!insideFilter && (previousCharacter === '.' || previousCharacter === ']' || nextCharacter === '.'));\n\n if (!shouldRemoveWhitespace) {\n append(trimmedPath.slice(cursor, whitespaceEnd));\n }\n cursor = whitespaceEnd - 1;\n continue;\n }\n\n if (character === '[') {\n const opensFilter = getNextNonWhitespaceCharacter(trimmedPath, cursor + 1) === '?';\n filterBrackets.push(opensFilter);\n if (opensFilter) {\n filterDepth += 1;\n }\n append(character);\n continue;\n }\n\n if (character === ']') {\n if (filterBrackets.pop()) {\n filterDepth -= 1;\n }\n append(character);\n continue;\n }\n\n append(character);\n }\n\n return result.join('').trim();\n}\n\n/**\n * Evaluates a JSONPath expression with the same engine and options used by the\n * object-path nodes. Callers retain ownership of their no-match and error\n * policy; this helper deliberately lets JSONPath errors propagate.\n */\nexport function evaluateJsonPath<T = unknown>(value: unknown, path: string, wrap = false): T | T[] | undefined {\n return JSONPath<T>({\n json: value ?? null,\n path: normalizeJsonPathExpression(path),\n wrap,\n });\n}\n", "export type InterpolationTokenSpan = {\n start: number;\n end: number;\n rawInner: string;\n};\n\nconst REGEX_LITERAL_PREFIX_CHARACTERS = new Set([\n '(',\n '[',\n '{',\n ':',\n ';',\n ',',\n '=',\n '!',\n '~',\n '?',\n '&',\n '|',\n '+',\n '-',\n '*',\n '%',\n '^',\n '<',\n '>',\n]);\n\nexport function isInterpolationSyntaxCharacterEscaped(value: string, index: number): boolean {\n let backslashCount = 0;\n\n for (let cursor = index - 1; cursor >= 0 && value[cursor] === '\\\\'; cursor -= 1) {\n backslashCount += 1;\n }\n\n return backslashCount % 2 === 1;\n}\n\n/**\n * JSONPath filters can contain JavaScript regex literals. Treat their contents\n * as opaque while looking for an interpolation terminator or processor pipe;\n * otherwise a `]` or `|` inside the regex can be mistaken for JSONPath syntax.\n */\nexport function isInterpolationRegexLiteralStart(value: string, index: number): boolean {\n if (value[index] !== '/') {\n return false;\n }\n\n let previousIndex = index - 1;\n while (previousIndex >= 0 && /\\s/.test(value[previousIndex]!)) {\n previousIndex -= 1;\n }\n\n return previousIndex < 0 || REGEX_LITERAL_PREFIX_CHARACTERS.has(value[previousIndex]!);\n}\n\nfunction getEscapedTripleTokenEnd(template: string, start: number): number | undefined {\n for (let cursor = start + 3; cursor < template.length - 2; cursor += 1) {\n if (template[cursor] === '}' && template[cursor + 1] === '}' && template[cursor + 2] === '}') {\n return cursor + 3;\n }\n }\n\n return undefined;\n}\n\ntype TokenScanResult = { kind: 'closed'; end: number } | { kind: 'nested'; start: number } | { kind: 'unclosed' };\n\n/** Finds a matching `}}` while allowing JSONPath filters, quotes, and braces. */\nfunction scanInterpolationToken(template: string, start: number): TokenScanResult {\n let quote: '\"' | \"'\" | '`' | undefined;\n let regex = false;\n let regexCharacterClass = false;\n let bracketDepth = 0;\n let parenthesisDepth = 0;\n let braceDepth = 0;\n\n for (let cursor = start + 2; cursor < template.length; cursor += 1) {\n const character = template[cursor]!;\n\n if (regex) {\n if (character === '[' && !isInterpolationSyntaxCharacterEscaped(template, cursor)) {\n regexCharacterClass = true;\n } else if (character === ']' && !isInterpolationSyntaxCharacterEscaped(template, cursor)) {\n regexCharacterClass = false;\n } else if (character === '/' && !regexCharacterClass && !isInterpolationSyntaxCharacterEscaped(template, cursor)) {\n regex = false;\n }\n continue;\n }\n\n if (quote) {\n if (character === quote && !isInterpolationSyntaxCharacterEscaped(template, cursor)) {\n quote = undefined;\n }\n continue;\n }\n\n if (character === '/' && isInterpolationRegexLiteralStart(template, cursor)) {\n regex = true;\n regexCharacterClass = false;\n continue;\n }\n\n if (character === '\"' || character === \"'\" || character === '`') {\n quote = character;\n continue;\n }\n\n // A second opener always starts recovery outside quoted or regex syntax.\n // JSONPath object literals use single `{` characters; a literal `{{` is\n // not valid JSONPath syntax and should not swallow a later valid token.\n if (character === '{' && template[cursor + 1] === '{') {\n return { kind: 'nested', start: cursor };\n }\n\n if (character === '[') {\n bracketDepth += 1;\n continue;\n }\n\n if (character === ']' && bracketDepth > 0) {\n bracketDepth -= 1;\n continue;\n }\n\n if (character === '(') {\n parenthesisDepth += 1;\n continue;\n }\n\n if (character === ')' && parenthesisDepth > 0) {\n parenthesisDepth -= 1;\n continue;\n }\n\n if (character === '{') {\n braceDepth += 1;\n continue;\n }\n\n if (character === '}') {\n if (braceDepth > 0) {\n braceDepth -= 1;\n continue;\n }\n\n if (template[cursor + 1] === '}' && bracketDepth === 0 && parenthesisDepth === 0) {\n return { kind: 'closed', end: cursor + 2 };\n }\n }\n }\n\n return { kind: 'unclosed' };\n}\n\n/**\n * Scans token boundaries without parsing expressions or resolving values.\n *\n * This deliberately has no evaluator dependencies, so editor-only surfaces\n * can share Core's malformed-token recovery rules without loading JSONPath or\n * the rest of the execution runtime. The returned spans are fresh data and\n * exclude escaped triple-brace tokens.\n */\nexport function scanInterpolationTokenSpans(template: string): InterpolationTokenSpan[] {\n const spans: InterpolationTokenSpan[] = [];\n let searchIndex = 0;\n\n while (searchIndex < template.length) {\n const start = template.indexOf('{{', searchIndex);\n\n if (start === -1) {\n break;\n }\n\n if (template[start + 2] === '{') {\n const escapedEnd = getEscapedTripleTokenEnd(template, start);\n if (escapedEnd !== undefined) {\n searchIndex = escapedEnd;\n continue;\n }\n }\n\n const scanResult = scanInterpolationToken(template, start);\n\n if (scanResult.kind === 'nested') {\n searchIndex = scanResult.start;\n continue;\n }\n\n if (scanResult.kind === 'unclosed') {\n // A malformed outer token can leave the scanner inside an unterminated\n // quote or filter. Resume at a later opener so a valid following token\n // is still discovered. Properly closed outer tokens return above, so\n // valid quoted `{{` content remains part of that outer token.\n const nextStart = template.indexOf('{{', start + 2);\n if (nextStart === -1) {\n break;\n }\n searchIndex = nextStart;\n continue;\n }\n\n spans.push({\n start,\n end: scanResult.end,\n rawInner: template.slice(start + 2, scanResult.end - 2),\n });\n searchIndex = scanResult.end;\n }\n\n return spans;\n}\n", "export { dedent } from 'ts-dedent';\n", "import { dataTypes, type DataValue } from '../model/DataValue.js';\nimport { coerceTypeOptional } from './coerceType.js';\nimport { evaluateJsonPath, normalizeJsonPathExpression } from './jsonPath.js';\nimport { dedent } from './misc.js';\nimport {\n isInterpolationRegexLiteralStart,\n isInterpolationSyntaxCharacterEscaped,\n scanInterpolationTokenSpans,\n type InterpolationTokenSpan,\n} from './interpolationSyntax.js';\n\nexport const ESCAPED_TOKEN_REGEX = /\\{\\{\\{([^}]+?)\\}\\}\\}/g;\nexport const ESCAPED_ESCAPED_TOKEN_REGEX = /\\\\\\{\\\\\\{([^}]+?)\\\\\\}\\\\\\}/g;\n\nconst INTERPOLATION_TEMPLATE_CACHE_MAX_ENTRIES = 2048;\nconst INTERPOLATION_TEMPLATE_CACHE_MAX_TEMPLATE_LENGTH = 64 * 1024;\nconst INTERPOLATION_TEMPLATE_CACHE_MAX_TEMPLATE_CHARS = 1024 * 1024;\nconst INTERPOLATION_TEMPLATE_CACHE_MAX_STORAGE_CHARS = 2 * 1024 * 1024;\n// JavaScript list callbacks can resolve the same expression for every item.\n// Keep this syntax-only cache deliberately smaller than the template cache:\n// values, contexts, and DataValues must never be retained here.\nconst INTERPOLATION_EXPRESSION_CACHE_MAX_ENTRIES = 512;\nconst INTERPOLATION_EXPRESSION_CACHE_MAX_EXPRESSION_LENGTH = 4 * 1024;\nconst INTERPOLATION_EXPRESSION_CACHE_MAX_CHARS = 128 * 1024;\nexport type { InterpolationTokenSpan } from './interpolationSyntax.js';\n\nexport type InterpolationReferenceSource = 'variable' | 'graphInputs' | 'context' | 'globals';\n\n/** A base value and, optionally, a JSONPath evaluated against that value. */\nexport type ParsedInterpolationExpression = {\n source: InterpolationReferenceSource;\n baseName: string;\n /** A JSONPath beginning with `$`, evaluated with `wrap: false`. */\n jsonPath: string | undefined;\n};\n\nexport type ParsedInterpolationToken = {\n span: InterpolationTokenSpan;\n rawInner: string;\n /** The interpolation expression before its optional processor chain. */\n tokenName: string | undefined;\n processingChain: string | undefined;\n reference: ParsedInterpolationExpression | undefined;\n};\n\nexport type ParsedInterpolationTemplate = {\n template: string;\n tokens: readonly ParsedInterpolationToken[];\n};\n\nexport type InterpolationVariableReference = {\n baseName: string;\n /** True when any occurrence of this input navigates into its value with JSONPath. */\n hasPath: boolean;\n};\n\nexport type InterpolationTokenReplacementInfo = {\n rawInner: string;\n span: InterpolationTokenSpan;\n tokenName: string | undefined;\n processingChain: string | undefined;\n reference: ParsedInterpolationExpression | undefined;\n};\n\nexport type ReplaceInterpolationTokensOptions = {\n trim?: boolean;\n};\n\nexport type InterpolateOptions = {\n /** A snapshot of the globals referenced by this template. */\n globalValues?: Record<string, unknown>;\n /** Set false when ordinary interpolation variables are raw JSON. */\n unwrapVariableDataValues?: boolean;\n /**\n * Use the historical text-template DataValue coercion for bare ordinary\n * variables. Paths still select raw JSON and use JSON serialization.\n */\n coerceBareVariableDataValues?: boolean;\n};\n\nexport type InterpolationValueSources = {\n variables?: Record<string, unknown>;\n graphInputValues?: Record<string, unknown>;\n contextValues?: Record<string, unknown>;\n globalValues?: Record<string, unknown>;\n /** Set false when `variables` are already raw JSON rather than DataValues. */\n unwrapVariableDataValues?: boolean;\n};\n\ntype CachedInterpolationTemplate = {\n templateChars: number;\n storageChars: number;\n parsed: ParsedInterpolationTemplate;\n};\n\nconst interpolationTemplateCache = new Map<string, CachedInterpolationTemplate>();\nlet cachedInterpolationTemplateChars = 0;\nlet cachedInterpolationTemplateStorageChars = 0;\nlet lastUncachedInterpolationTemplate: string | undefined;\nconst interpolationExpressionCache = new Map<string, ParsedInterpolationExpression | undefined>();\nlet cachedInterpolationExpressionChars = 0;\nconst dataValueTypeSet = new Set<string>(dataTypes);\n\ntype ProcessingFunction = (input: string, param?: number) => string;\n\nconst processingFunctions: Record<string, ProcessingFunction> = {\n indent: (input: string, spaces: number = 0) => {\n const indent = ' '.repeat(spaces);\n return input\n .split('\\n')\n .map((line) => `${indent}${line}`)\n .join('\\n');\n },\n\n quote: (input: string, level: number = 1) => {\n const quotePrefix = '> '.repeat(level);\n return input\n .split('\\n')\n .map((line) => `${quotePrefix}${line}`)\n .join('\\n');\n },\n\n uppercase: (input: string) => input.toUpperCase(),\n lowercase: (input: string) => input.toLowerCase(),\n trim: (input: string) => input.trim(),\n\n truncate: (input: string, length: number = 50) => {\n if (input.length <= length) return input;\n return input.slice(0, length) + '...';\n },\n\n list: (input: string, level: number = 1) => {\n const indent = ' '.repeat(level - 1);\n return input\n .split('\\n')\n .map((line) => `${indent}- ${line}`)\n .join('\\n');\n },\n\n sort: (input: string) => input.split('\\n').sort().join('\\n'),\n dedent: (input: string) => dedent(input),\n\n wrap: (input: string, width: number = 80) => {\n const words = input.split(/\\s+/);\n const lines: string[] = [];\n let currentLine = '';\n\n for (const word of words) {\n if (currentLine.length + word.length + 1 <= width) {\n currentLine += (currentLine ? ' ' : '') + word;\n } else {\n lines.push(currentLine);\n currentLine = word;\n }\n }\n\n if (currentLine) {\n lines.push(currentLine);\n }\n\n return lines.join('\\n');\n },\n};\n\n/**\n * Unwrap a Rivet DataValue at an interpolation source boundary. Callers must\n * not recursively apply this to selected JSON properties: an ordinary object\n * inside the value may legitimately have `type` and `value` properties.\n */\nexport function unwrapPotentialDataValue(value: unknown): unknown {\n if (isRivetDataValue(value)) {\n return (value as { value: unknown }).value;\n }\n\n return value;\n}\n\nfunction isRivetDataValue(value: unknown): value is DataValue {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { type?: unknown }).type === 'string' &&\n dataValueTypeSet.has((value as { type: string }).type) &&\n Object.prototype.hasOwnProperty.call(value, 'value')\n );\n}\n\n/**\n * Renders a whole interpolation input with the legacy generic interpolation\n * behavior. Text-oriented callers can opt into DataValue string coercion.\n */\nexport function stringifyInterpolationSourceValue(\n value: unknown,\n {\n coerceDataValueToString = false,\n unwrapDataValue = true,\n }: { coerceDataValueToString?: boolean; unwrapDataValue?: boolean } = {},\n): string {\n try {\n if (coerceDataValueToString && unwrapDataValue && isRivetDataValue(value)) {\n return coerceTypeOptional(value, 'string') ?? '';\n }\n\n return String((unwrapDataValue ? unwrapPotentialDataValue(value) : value) ?? '');\n } catch {\n // Keep interpolation usable for cyclic values and custom objects whose\n // string conversion throws, matching the prior object fallback.\n return '[object Object]';\n }\n}\n\nfunction findTopLevelProcessorSeparator(rawInner: string): number | undefined {\n let quote: '\"' | \"'\" | '`' | undefined;\n let regex = false;\n let regexCharacterClass = false;\n let bracketDepth = 0;\n let parenthesisDepth = 0;\n let braceDepth = 0;\n\n for (let cursor = 0; cursor < rawInner.length; cursor++) {\n const character = rawInner[cursor]!;\n\n if (regex) {\n if (character === '[' && !isInterpolationSyntaxCharacterEscaped(rawInner, cursor)) {\n regexCharacterClass = true;\n } else if (character === ']' && !isInterpolationSyntaxCharacterEscaped(rawInner, cursor)) {\n regexCharacterClass = false;\n } else if (\n character === '/' &&\n !regexCharacterClass &&\n !isInterpolationSyntaxCharacterEscaped(rawInner, cursor)\n ) {\n regex = false;\n }\n continue;\n }\n\n if (quote) {\n if (character === quote && !isInterpolationSyntaxCharacterEscaped(rawInner, cursor)) {\n quote = undefined;\n }\n continue;\n }\n\n if (character === '/' && isInterpolationRegexLiteralStart(rawInner, cursor)) {\n regex = true;\n regexCharacterClass = false;\n continue;\n }\n\n if (character === '\"' || character === \"'\" || character === '`') {\n quote = character;\n continue;\n }\n\n if (character === '[') {\n bracketDepth += 1;\n continue;\n }\n\n if (character === ']' && bracketDepth > 0) {\n bracketDepth -= 1;\n continue;\n }\n\n if (character === '(') {\n parenthesisDepth += 1;\n continue;\n }\n\n if (character === ')' && parenthesisDepth > 0) {\n parenthesisDepth -= 1;\n continue;\n }\n\n if (character === '{') {\n braceDepth += 1;\n continue;\n }\n\n if (character === '}' && braceDepth > 0) {\n braceDepth -= 1;\n continue;\n }\n\n if (character === '|' && bracketDepth === 0 && parenthesisDepth === 0 && braceDepth === 0) {\n return cursor;\n }\n }\n\n return undefined;\n}\n\nfunction findQuotedStringEnd(value: string, start: number): number | undefined {\n const quote = value[start];\n\n for (let cursor = start + 1; cursor < value.length; cursor++) {\n if (value[cursor] === quote && !isInterpolationSyntaxCharacterEscaped(value, cursor)) {\n return cursor;\n }\n }\n\n return undefined;\n}\n\nfunction parseQuotedBaseReference(expression: string): { baseName: string; suffix: string | undefined } | undefined {\n if (expression[0] !== '[') {\n return undefined;\n }\n\n let cursor = 1;\n while (expression[cursor] === ' ') {\n cursor += 1;\n }\n\n const quote = expression[cursor];\n if (quote !== '\"' && quote !== \"'\") {\n return undefined;\n }\n\n const quoteEnd = findQuotedStringEnd(expression, cursor);\n if (quoteEnd === undefined) {\n return undefined;\n }\n\n // JSONPath-plus retains the raw content of a bracket-property literal. Use\n // escaping only to find its closing quote, then keep its key untouched so\n // a `\\\\u` sequence names the same input it would name in JSONPath-plus.\n const baseName = expression.slice(cursor + 1, quoteEnd);\n if (!baseName) {\n return undefined;\n }\n\n cursor = quoteEnd + 1;\n while (expression[cursor] === ' ') {\n cursor += 1;\n }\n\n if (expression[cursor] !== ']') {\n return undefined;\n }\n\n const suffix = expression.slice(cursor + 1).trimStart();\n if (suffix !== '' && !suffix.startsWith('.') && !suffix.startsWith('[')) {\n return undefined;\n }\n\n return { baseName, suffix: suffix || undefined };\n}\n\nfunction parseBaseReference(\n expression: string,\n source: InterpolationReferenceSource,\n): ParsedInterpolationExpression | undefined {\n const trimmedExpression = expression.trim();\n if (!trimmedExpression) {\n return undefined;\n }\n\n const quotedReference = parseQuotedBaseReference(trimmedExpression);\n if (quotedReference) {\n return {\n source,\n baseName: quotedReference.baseName,\n jsonPath: quotedReference.suffix ? normalizeJsonPathExpression(`$${quotedReference.suffix}`) : undefined,\n };\n }\n\n let suffixStart = -1;\n for (let cursor = 0; cursor < trimmedExpression.length; cursor++) {\n const character = trimmedExpression[cursor];\n if (character === '.' || character === '[') {\n suffixStart = cursor;\n break;\n }\n }\n\n if (suffixStart === -1) {\n return {\n source,\n baseName: trimmedExpression,\n jsonPath: undefined,\n };\n }\n\n const baseName = trimmedExpression.slice(0, suffixStart).trim();\n const suffix = normalizeJsonPathExpression(trimmedExpression.slice(suffixStart));\n\n if (!baseName || (!suffix.startsWith('.') && !suffix.startsWith('['))) {\n return undefined;\n }\n\n return {\n source,\n baseName,\n jsonPath: `$${suffix}`,\n };\n}\n\n/**\n * Parses the authored portion of an interpolation token. Paths are always\n * rooted at the selected base value, so `foo.items[0]` becomes input `foo`\n * plus JSONPath `$.items[0]`.\n */\nfunction parseInterpolationExpressionUncached(trimmedExpression: string): ParsedInterpolationExpression | undefined {\n for (const [prefix, source] of [\n ['@graphInputs', 'graphInputs'],\n ['@context', 'context'],\n ['@globals', 'globals'],\n ] as const) {\n if (trimmedExpression.startsWith(`${prefix}.`)) {\n return parseBaseReference(trimmedExpression.slice(prefix.length + 1), source);\n }\n\n if (trimmedExpression.startsWith(`${prefix}[`)) {\n return parseBaseReference(trimmedExpression.slice(prefix.length), source);\n }\n }\n\n return parseBaseReference(trimmedExpression, 'variable');\n}\n\n/**\n * Returns an immutable syntax record for internal resolution. This cache is\n * intentionally keyed only by expression text; resolved values are always\n * read from the current invocation's sources.\n */\nfunction getCachedInterpolationExpression(expression: string): ParsedInterpolationExpression | undefined {\n const trimmedExpression = expression.trim();\n if (interpolationExpressionCache.has(trimmedExpression)) {\n return interpolationExpressionCache.get(trimmedExpression);\n }\n\n const parsed = parseInterpolationExpressionUncached(trimmedExpression);\n if (trimmedExpression.length > INTERPOLATION_EXPRESSION_CACHE_MAX_EXPRESSION_LENGTH) {\n return parsed;\n }\n\n if (\n interpolationExpressionCache.size >= INTERPOLATION_EXPRESSION_CACHE_MAX_ENTRIES ||\n cachedInterpolationExpressionChars + trimmedExpression.length > INTERPOLATION_EXPRESSION_CACHE_MAX_CHARS\n ) {\n interpolationExpressionCache.clear();\n cachedInterpolationExpressionChars = 0;\n }\n\n const immutableParsed = parsed ? (Object.freeze({ ...parsed }) as ParsedInterpolationExpression) : undefined;\n interpolationExpressionCache.set(trimmedExpression, immutableParsed);\n cachedInterpolationExpressionChars += trimmedExpression.length;\n return immutableParsed;\n}\n\n/**\n * Parses a public interpolation expression. Return a fresh record so callers\n * can safely mutate it without corrupting the internal syntax cache.\n */\nexport function parseInterpolationExpression(expression: string): ParsedInterpolationExpression | undefined {\n const parsed = getCachedInterpolationExpression(expression);\n return parsed ? { ...parsed } : undefined;\n}\n\n/** Splits an interpolation token into its expression, processor chain, and parsed reference. */\nexport function parseInterpolationToken(rawInner: string): Omit<ParsedInterpolationToken, 'span'> {\n const processorSeparator = findTopLevelProcessorSeparator(rawInner);\n const tokenName =\n (processorSeparator === undefined ? rawInner : rawInner.slice(0, processorSeparator)).trim() || undefined;\n const processingChain =\n processorSeparator === undefined ? undefined : rawInner.slice(processorSeparator + 1).trim() || undefined;\n\n return {\n rawInner,\n tokenName,\n processingChain,\n reference: tokenName ? parseInterpolationExpression(tokenName) : undefined,\n };\n}\n\nfunction freezeReference(\n reference: ParsedInterpolationExpression | undefined,\n): ParsedInterpolationExpression | undefined {\n return reference ? Object.freeze({ ...reference }) : undefined;\n}\n\nfunction parseInterpolationTemplateUncached(template: string): ParsedInterpolationTemplate {\n const tokens = scanInterpolationTokenSpans(template).map((span) => {\n const parsedToken = parseInterpolationToken(span.rawInner);\n return Object.freeze({\n ...parsedToken,\n span: Object.freeze({ ...span }),\n reference: freezeReference(parsedToken.reference),\n });\n });\n\n return Object.freeze({\n template,\n tokens: Object.freeze(tokens),\n });\n}\n\nfunction getTemplateStorageChars(template: string, parsed: ParsedInterpolationTemplate): number {\n return (\n template.length +\n parsed.tokens.reduce(\n (total, token) => total + token.rawInner.length + (token.tokenName?.length ?? 0),\n parsed.tokens.length * 48,\n )\n );\n}\n\nfunction cacheInterpolationTemplate(template: string, parsed: ParsedInterpolationTemplate): void {\n if (template.length > INTERPOLATION_TEMPLATE_CACHE_MAX_TEMPLATE_LENGTH) {\n return;\n }\n\n const storageChars = getTemplateStorageChars(template, parsed);\n const reachesCapacity =\n interpolationTemplateCache.size >= INTERPOLATION_TEMPLATE_CACHE_MAX_ENTRIES ||\n cachedInterpolationTemplateChars + template.length > INTERPOLATION_TEMPLATE_CACHE_MAX_TEMPLATE_CHARS ||\n cachedInterpolationTemplateStorageChars + storageChars > INTERPOLATION_TEMPLATE_CACHE_MAX_STORAGE_CHARS;\n\n if (reachesCapacity) {\n // Avoid miss-by-miss eviction churn. A repeated miss proves this template is hot.\n if (lastUncachedInterpolationTemplate !== template) {\n lastUncachedInterpolationTemplate = template;\n return;\n }\n\n interpolationTemplateCache.clear();\n cachedInterpolationTemplateChars = 0;\n cachedInterpolationTemplateStorageChars = 0;\n }\n\n lastUncachedInterpolationTemplate = undefined;\n interpolationTemplateCache.set(template, {\n templateChars: template.length,\n storageChars,\n parsed,\n });\n cachedInterpolationTemplateChars += template.length;\n cachedInterpolationTemplateStorageChars += storageChars;\n}\n\n/** Returns an immutable, cached syntax representation. It never evaluates values. */\nexport function parseInterpolationTemplate(template: string): ParsedInterpolationTemplate {\n const cached = interpolationTemplateCache.get(template);\n if (cached) {\n return cached.parsed;\n }\n\n const parsed = parseInterpolationTemplateUncached(template);\n if (template.includes('{{')) {\n cacheInterpolationTemplate(template, parsed);\n }\n return parsed;\n}\n\nexport function protectEscapedInterpolationTokens(template: string): string {\n return template.replace(ESCAPED_TOKEN_REGEX, (_match, expression) => `\\\\{\\\\{${expression}\\\\}\\\\}`);\n}\n\nexport function restoreEscapedInterpolationTokens(template: string): string {\n return template\n .replace(ESCAPED_ESCAPED_TOKEN_REGEX, (_match, expression) => `{{${expression}}}`)\n .replace(ESCAPED_TOKEN_REGEX, (_match, expression) => `{{${expression}}}`);\n}\n\nexport function findInterpolationTokenSpans(template: string): InterpolationTokenSpan[] {\n return parseInterpolationTemplate(template).tokens.map((token) => ({ ...token.span }));\n}\n\n/** Returns the pre-processor expression, retaining its authored path syntax. */\nexport function getInterpolationTokenName(rawInner: string): string | undefined {\n return parseInterpolationToken(rawInner).tokenName;\n}\n\nexport function getInterpolationTokenReference(rawInner: string): ParsedInterpolationExpression | undefined {\n return parseInterpolationToken(rawInner).reference;\n}\n\nexport function replaceInterpolationTokens(\n template: string,\n getReplacement: (token: InterpolationTokenReplacementInfo) => string,\n options: ReplaceInterpolationTokensOptions = {},\n): string {\n const parsedTemplate = parseInterpolationTemplate(template);\n\n if (parsedTemplate.tokens.length === 0) {\n const restoredTemplate = restoreEscapedInterpolationTokens(template);\n return options.trim ? restoredTemplate.trim() : restoredTemplate;\n }\n\n let result = '';\n let cursor = 0;\n\n for (const token of parsedTemplate.tokens) {\n // Restore escaped delimiters only from authored template text. A\n // replacement may deliberately contain `{{{...}}}` or `\\\\{\\\\{...\\\\}\\\\}` and\n // must be returned unchanged rather than interpreted as template syntax.\n result += restoreEscapedInterpolationTokens(template.slice(cursor, token.span.start));\n result += getReplacement({\n rawInner: token.rawInner,\n span: { ...token.span },\n tokenName: token.tokenName,\n processingChain: token.processingChain,\n reference: token.reference ? { ...token.reference } : undefined,\n });\n cursor = token.span.end;\n }\n\n result += restoreEscapedInterpolationTokens(template.slice(cursor));\n return options.trim ? result.trim() : result;\n}\n\n/**\n * Discovers connectable interpolation bases in first-occurrence order. Special\n * graph/context/global references are intentionally omitted because they do not make ports.\n */\nexport function extractInterpolationVariableReferences(template: string): InterpolationVariableReference[] {\n if (!template.includes('{{')) {\n return [];\n }\n\n const discovered = new Map<string, InterpolationVariableReference>();\n\n for (const token of parseInterpolationTemplate(template).tokens) {\n const reference = token.reference;\n if (!reference || reference.source !== 'variable') {\n continue;\n }\n\n const existing = discovered.get(reference.baseName);\n if (existing) {\n existing.hasPath ||= reference.jsonPath !== undefined;\n continue;\n }\n\n discovered.set(reference.baseName, {\n baseName: reference.baseName,\n hasPath: reference.jsonPath !== undefined,\n });\n }\n\n return Array.from(discovered.values(), (reference) => ({ ...reference }));\n}\n\n/**\n * Captures only globals referenced by a template into a safe record. Globals\n * are intentionally snapshotted at node execution: interpolation neither\n * waits for a writer nor creates an execution dependency.\n */\nexport function getInterpolationGlobalValues<T>(\n template: string,\n getGlobal: ((id: string) => T | undefined) | undefined,\n): Record<string, T> {\n const values = Object.create(null) as Record<string, T>;\n if (!getGlobal || !template.includes('{{')) {\n return values;\n }\n\n for (const token of parseInterpolationTemplate(template).tokens) {\n const reference = token.reference;\n if (!reference || reference.source !== 'globals' || Object.prototype.hasOwnProperty.call(values, reference.baseName)) {\n continue;\n }\n\n const value = getGlobal(reference.baseName);\n if (value !== undefined) {\n Object.defineProperty(values, reference.baseName, {\n configurable: true,\n enumerable: true,\n value,\n writable: true,\n });\n }\n }\n\n return values;\n}\n\n/** Extracts base port names only. Prefer `extractInterpolationVariableReferences` when type selection matters. */\nexport function extractInterpolationVariables(template: string): string[] {\n return extractInterpolationVariableReferences(template).map((reference) => reference.baseName);\n}\n\nfunction getInterpolationSource(\n reference: ParsedInterpolationExpression,\n sources: InterpolationValueSources,\n): Record<string, unknown> | undefined {\n switch (reference.source) {\n case 'variable':\n return sources.variables;\n case 'graphInputs':\n return sources.graphInputValues;\n case 'context':\n return sources.contextValues;\n case 'globals':\n return sources.globalValues;\n }\n}\n\n/**\n * Resolves one parsed interpolation expression from raw values. JSONPath uses\n * `wrap: false`, matching Destructure exactly; callers decide how to render a\n * missing value or a selected object.\n */\nexport function resolveInterpolationExpressionRawValue(\n expression: string | ParsedInterpolationExpression,\n sources: InterpolationValueSources,\n): unknown | undefined {\n const reference = typeof expression === 'string' ? getCachedInterpolationExpression(expression) : expression;\n if (!reference) {\n return undefined;\n }\n\n const source = getInterpolationSource(reference, sources);\n if (!source || !Object.prototype.hasOwnProperty.call(source, reference.baseName)) {\n return undefined;\n }\n\n const shouldUnwrapDataValue = reference.source !== 'variable' || sources.unwrapVariableDataValues !== false;\n const baseValue = shouldUnwrapDataValue\n ? unwrapPotentialDataValue(source[reference.baseName])\n : source[reference.baseName];\n if (reference.jsonPath === undefined) {\n return baseValue;\n }\n\n try {\n return evaluateJsonPath(baseValue, reference.jsonPath, false);\n } catch {\n return undefined;\n }\n}\n\nexport function resolveInterpolationTokenRawValue(\n rawInner: string,\n sources: InterpolationValueSources,\n): unknown | undefined {\n const reference = parseInterpolationToken(rawInner).reference;\n return reference ? resolveInterpolationExpressionRawValue(reference, sources) : undefined;\n}\n\n/** Backward-compatible special-reference resolver used by existing nodes. */\nexport function resolveExpressionRawValue(\n source: Record<string, unknown> | undefined,\n expression: string,\n sourceType: 'graphInputs' | 'context' | 'globals',\n): unknown | undefined {\n return resolveInterpolationExpressionRawValue(`@${sourceType}.${expression}`, {\n graphInputValues: sourceType === 'graphInputs' ? source : undefined,\n contextValues: sourceType === 'context' ? source : undefined,\n globalValues: sourceType === 'globals' ? source : undefined,\n });\n}\n\nfunction stringifyInterpolationValue(value: unknown): string {\n if (typeof value === 'object' && value !== null) {\n try {\n return JSON.stringify(value);\n } catch (error) {\n console.warn('Error stringifying an interpolation value:', error);\n return '[object Object]';\n }\n }\n\n return String(value);\n}\n\nexport function resolveExpressionToString(\n source: Record<string, unknown> | undefined,\n expression: string,\n sourceType: 'graphInputs' | 'context' | 'globals',\n): string | undefined {\n const finalValue = resolveExpressionRawValue(source, expression, sourceType);\n return finalValue === undefined ? undefined : stringifyInterpolationValue(finalValue);\n}\n\nfunction parseProcessing(instruction: string): { func: string; param?: number } {\n const parts = instruction.trim().split(/\\s+/);\n return {\n func: parts[0]!,\n param: parts[1] ? Number.parseInt(parts[1], 10) : undefined,\n };\n}\n\nfunction applyProcessing(value: string, processingChain: string): string {\n const instructions = processingChain\n .split('|')\n .map((instruction) => instruction.trim())\n .filter((instruction) => instruction !== '');\n\n return instructions.reduce((result, instruction) => {\n const { func, param } = parseProcessing(instruction);\n const processingFunc = processingFunctions[func];\n\n if (!processingFunc) {\n console.warn(`Unknown processing function: ${func}`);\n return result;\n }\n\n return processingFunc(result, param);\n }, value);\n}\n\n/**\n * Resolves text interpolation. Bare ordinary variables keep the historical\n * string coercion; path-bearing references select raw data first and serialize\n * selected objects/arrays as JSON.\n */\nexport function interpolate(\n template: string,\n variables: Record<string, unknown>,\n graphInputValues?: Record<string, DataValue>,\n contextValues?: Record<string, DataValue>,\n options: InterpolateOptions = {},\n): string {\n return replaceInterpolationTokens(template, (token) => {\n if (!token.reference) {\n return '';\n }\n\n const resolvedValue = resolveInterpolationExpressionRawValue(token.reference, {\n variables,\n graphInputValues,\n contextValues,\n globalValues: options.globalValues,\n unwrapVariableDataValues: options.unwrapVariableDataValues,\n });\n\n if (resolvedValue === undefined) {\n console.warn(`Interpolation variable or path \"${token.tokenName}\" not found or resolved to undefined.`);\n return '';\n }\n\n const isBareOrdinaryVariable = token.reference.source === 'variable' && token.reference.jsonPath === undefined;\n const stringValue = isBareOrdinaryVariable\n ? stringifyInterpolationSourceValue(variables[token.reference.baseName], {\n coerceDataValueToString: options.coerceBareVariableDataValues,\n unwrapDataValue: options.unwrapVariableDataValues !== false,\n })\n : stringifyInterpolationValue(resolvedValue);\n return token.processingChain ? applyProcessing(stringValue, token.processingChain) : stringValue;\n });\n}\n\n/** Runtime helper injected into JavaScript runners without exposing the whole Rivet API. */\nexport function resolveCodeInterpolationExpression(\n inputs: Record<string, DataValue | undefined>,\n expression: string,\n graphInputValues?: Record<string, DataValue>,\n contextValues?: Record<string, DataValue>,\n globalValues?: Record<string, DataValue>,\n): unknown | undefined {\n return resolveInterpolationExpressionRawValue(expression, {\n variables: inputs,\n graphInputValues,\n contextValues,\n globalValues,\n });\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACmBO,IAAM,kBACX;AAAA;AAAA,EAEA,IAAmB,MACjB;AAAA;;;ACgCG,SAAS,2BAA2B,YAA2C,CAAC,GAAyB;AAC9G,SAAO;AAAA,IACL,OAAO;AAAA,IACP,eAAe;AAAA,IACf,aAAa;AAAA,IACb,qBAAqB;AAAA,IACrB,MAAM;AAAA,IACN,cAAc;AAAA,IACd,MAAM;AAAA,IACN,cAAc;AAAA,IACd,iBA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,IAAM,YAAY,gBAA0B;AAAA,EACjD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,IAAM,cAAc,gBAA4B;AAAA,EACrD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAyFO,SAAS,kBAAkB,OAAwD;AACxF,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Y,OAAO,eAAe,WAAW,iCAAiC,UAAU,IAAI;AAClG,MAAI,CAAC,WAAW;AACd,WAAO;AAAA,EACT;AAEA,QAAM,SAAS,uBAAuB,WAAW,OAAO;AACxD,MAAI,CAAC,UAAU,CAAC,OAAO,UAAU,eAAe,KAAK,QAAQ,UAAU,QAAQ,GAAG;AAChF,WAAO;AAAA,EACT;AAEA,QAAM,wBAAwB,UAAU,WAAW,cAAc,QAAQ,6BAA6B;AACtG,QAAM,YAAY,wBACd,yBAAyB,OAAO,UAAU,QAAQ,CAAC,IACnD,OAAO,UAAU,QAAQ;AAC7B,MAAI,UAAU,aAAa,QAAW;AACpC,WAAO;AAAA,EACT;AAEA,MAAI;AACF,WAAO,iBAAiB,WAAW,UAAU,UAAU,KAAK;AAAA,EAC9D,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAkHO,SAAS,mCACd,QACA,YACA,kBACA,eACA,cACqB;AACrB,SAAO,uCAAuC,YAAY;AAAA,IACxD,WAAW;AAAA,IACX;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AACH;",
3
+ "sources": ["../../src/interpolationRuntime.ts", "../../src/utils/genericUtilFunctions.ts", "../../src/model/chat-v2/chatV2Shared.ts", "../../src/model/chat-v2/chatV2Retry.ts", "../../src/model/chat-v2/llmProfileFieldRegistry.ts", "../../src/model/chat-v2/llmProfileHealthStore.ts", "../../src/model/chat-v2/llmChatV2NodeData.ts", "../../src/model/chat-v2/llmProfileTypes.ts", "../../src/model/DataValue.ts", "../../src/utils/expectType.ts", "../../src/integrations/KnowledgeStoreValidation.ts", "../../src/model/chat-v2/customProviderApi.ts", "../../src/model/chat-v2/chatV2CredentialNames.ts", "../../src/model/chat-v2/temperature.ts", "../../src/model/chat-v2/llmProfile.ts", "../../src/utils/coerceType.ts", "../../src/utils/jsonPath.ts", "../../src/utils/interpolationSyntax.ts", "../../src/utils/misc.ts", "../../src/utils/interpolation.ts"],
4
+ "sourcesContent": ["/**\n * Narrow runtime entrypoint for JavaScript executors. Build tooling can bundle\n * this module into isolated workers without exposing the complete Core API.\n */\nexport { resolveCodeInterpolationExpression } from './utils/interpolation.js';\n", "export function isNotNull<T>(value: T | undefined | null): value is T {\n return value != null;\n}\n\n/**\n * Checks that the given tuple is exhaustive, ie. it represents all possible values in the union T.\n * Note that this function returns a function, so the function needs to be called like\n * `SpecificStrings.exhaustiveTuple<Furniture>()('v1', 'v2', ...)`.\n * If you miss a value, the type error will tell you which value you missed.\n *\n * Taken from https://stackoverflow.com/a/55266531/\n *\n * @example\n * type Furniture = 'chair' | 'table' | 'lamp' | 'ottoman';\n * const furniture = SpecificStrings.exhaustiveTuple<Furniture>()('chair', 'table', 'lamp', 'ottoman');\n *\n * // error, argument of type '\"chair\"' is not assignable to parameter of type '\"You are missing ottoman\"'.\n * const missingFurniture = SpecificStrings.exhaustiveTuple<Furniture>()('chair', 'table', 'lamp');\n */\nexport const exhaustiveTuple =\n <T extends string>() =>\n // impressive inference from TS: it knows when the condition and the true branch can't both be satisfied\n <L extends T[]>(...x: [T] extends [L[number]] ? L : `You are missing ${Exclude<T, L[number]>}`[]) =>\n x;\n\n/**\n * See exhaustiveTuple above. Does the same thing except returns a Set, not an array.\n */\nexport const exhaustiveSet =\n <T extends string>() =>\n <L extends T[]>(...x: [T] extends [L[number]] ? L : `You are missing ${Exclude<T, L[number]>}`[]) =>\n new Set<(typeof x)[number]>(x);\n", "import type { EditorDefinition } from '../EditorDefinition.js';\nimport type { ChartNode, NodeInputDefinition, NodeOutputDefinition, PortId } from '../NodeBase.js';\n\nexport type ChatV2CommonNodeData = {\n model: string;\n useModelInput: boolean;\n temperature?: number;\n useTemperatureInput: boolean;\n topP?: number;\n useTopPInput: boolean;\n topK?: number;\n useTopKInput: boolean;\n presencePenalty?: number;\n usePresencePenaltyInput: boolean;\n frequencyPenalty?: number;\n useFrequencyPenaltyInput: boolean;\n stopSequences?: string[];\n useStopSequencesInput: boolean;\n seed?: number;\n useSeedInput: boolean;\n maxTokens: number;\n useMaxTokensInput: boolean;\n useToolCalling: boolean;\n outputUsage: boolean;\n outputReasoning: boolean;\n cache: boolean;\n useAsGraphPartialOutput?: boolean;\n};\n\ntype ChatV2SharedNode = ChartNode<string, ChatV2CommonNodeData>;\n\nexport const STREAM_RESPONSE_HELPER_MESSAGE =\n 'Shows streamed response updates in the editor, including direct consumer previews. Ordinary consumers run after the final response; Watch Streaming Output branches can run during streaming.';\n\nexport type CommonChatV2InputOptions = {\n systemPromptPortId?: PortId;\n promptPortId?: PortId;\n functionsPortId?: PortId;\n includeTopP?: boolean;\n includeTopK?: boolean;\n includeFunctions?: boolean;\n};\n\nexport type CommonChatV2OutputOptions = {\n responsePortId?: PortId;\n inMessagesPortId?: PortId;\n allMessagesPortId?: PortId;\n functionCallsPortId?: PortId;\n usagePortId?: PortId;\n reasoningPortId?: PortId;\n includeFunctionCalls?: boolean;\n includeUsage?: boolean;\n includeReasoning?: boolean;\n};\n\nexport function createChatV2CommonNodeData(overrides: Partial<ChatV2CommonNodeData> = {}): ChatV2CommonNodeData {\n return {\n model: 'gpt-4o',\n useModelInput: false,\n temperature: 0.5,\n useTemperatureInput: false,\n topP: undefined,\n useTopPInput: false,\n topK: undefined,\n useTopKInput: false,\n presencePenalty: undefined,\n usePresencePenaltyInput: false,\n frequencyPenalty: undefined,\n useFrequencyPenaltyInput: false,\n stopSequences: [],\n useStopSequencesInput: false,\n seed: undefined,\n useSeedInput: false,\n maxTokens: 1024,\n useMaxTokensInput: false,\n useToolCalling: false,\n outputUsage: false,\n outputReasoning: false,\n cache: false,\n useAsGraphPartialOutput: false,\n ...overrides,\n };\n}\n\nexport function getCommonChatV2Inputs(\n data: ChatV2CommonNodeData,\n options: CommonChatV2InputOptions = {},\n): NodeInputDefinition[] {\n const {\n systemPromptPortId = 'systemPrompt' as PortId,\n promptPortId = 'prompt' as PortId,\n functionsPortId = 'functions' as PortId,\n includeTopP = true,\n includeTopK = true,\n includeFunctions = data.useToolCalling,\n } = options;\n\n const inputs: NodeInputDefinition[] = [\n {\n id: systemPromptPortId,\n title: 'System Prompt',\n dataType: 'string',\n required: false,\n coerced: true,\n },\n ];\n\n if (data.useModelInput) {\n inputs.push({\n id: 'model' as PortId,\n title: 'Model',\n dataType: 'string',\n required: false,\n });\n }\n\n if (data.useTemperatureInput) {\n inputs.push({\n id: 'temperature' as PortId,\n title: 'Temperature',\n dataType: 'number',\n });\n }\n\n if (includeTopP && data.useTopPInput) {\n inputs.push({\n id: 'topP' as PortId,\n title: 'Top P',\n dataType: 'number',\n });\n }\n\n if (includeTopK && data.useTopKInput) {\n inputs.push({\n id: 'topK' as PortId,\n title: 'Top K',\n dataType: 'number',\n });\n }\n\n if (data.usePresencePenaltyInput) {\n inputs.push({\n id: 'presencePenalty' as PortId,\n title: 'Presence Penalty',\n dataType: 'number',\n });\n }\n\n if (data.useFrequencyPenaltyInput) {\n inputs.push({\n id: 'frequencyPenalty' as PortId,\n title: 'Frequency Penalty',\n dataType: 'number',\n });\n }\n\n if (data.useStopSequencesInput) {\n inputs.push({\n id: 'stopSequences' as PortId,\n title: 'Stop Sequences',\n dataType: ['string', 'string[]'] as const,\n required: false,\n coerced: true,\n });\n }\n\n if (data.useSeedInput) {\n inputs.push({\n id: 'seed' as PortId,\n title: 'Seed',\n dataType: 'number',\n });\n }\n\n if (data.useMaxTokensInput) {\n inputs.push({\n id: 'maxTokens' as PortId,\n title: 'Max output tokens',\n dataType: 'number',\n });\n }\n\n if (includeFunctions) {\n inputs.push({\n id: functionsPortId,\n title: 'Tools',\n dataType: ['gpt-function', 'gpt-function[]'] as const,\n required: false,\n coerced: false,\n });\n }\n\n inputs.push({\n id: promptPortId,\n title: 'Prompt',\n dataType: ['chat-message', 'chat-message[]', 'string', 'string[]'] as const,\n coerced: true,\n });\n\n return inputs;\n}\n\nexport function getCommonChatV2Outputs(\n data: ChatV2CommonNodeData,\n options: CommonChatV2OutputOptions = {},\n): NodeOutputDefinition[] {\n const {\n responsePortId = 'response' as PortId,\n inMessagesPortId = 'in-messages' as PortId,\n allMessagesPortId = 'all-messages' as PortId,\n functionCallsPortId = 'function-calls' as PortId,\n usagePortId = 'usage' as PortId,\n reasoningPortId = 'reasoning' as PortId,\n includeFunctionCalls = data.useToolCalling,\n includeUsage = data.outputUsage,\n includeReasoning = data.outputReasoning,\n } = options;\n\n const outputs: NodeOutputDefinition[] = [\n {\n id: responsePortId,\n title: 'Response',\n dataType: 'string',\n },\n {\n id: inMessagesPortId,\n title: 'Messages Sent',\n dataType: 'chat-message[]',\n },\n {\n id: allMessagesPortId,\n title: 'All Messages',\n dataType: 'chat-message[]',\n },\n ];\n\n if (includeFunctionCalls) {\n outputs.push({\n id: functionCallsPortId,\n title: 'Tool Calls',\n dataType: 'object[]',\n });\n }\n\n if (includeUsage) {\n outputs.push({\n id: usagePortId,\n title: 'Usage',\n dataType: 'object',\n });\n }\n\n if (includeReasoning) {\n outputs.push({\n id: reasoningPortId,\n title: 'Reasoning',\n dataType: ['string', 'string[]'] as const,\n });\n }\n\n return outputs;\n}\n\nexport function getCommonChatV2Editors<T extends ChatV2SharedNode>(\n modelOptions: { value: string; label: string }[],\n): EditorDefinition<T>[] {\n const editors = [\n {\n type: 'dropdown',\n label: 'Model',\n dataKey: 'model',\n useInputToggleDataKey: 'useModelInput',\n options: modelOptions,\n },\n {\n type: 'group',\n label: 'Parameters',\n editors: [\n {\n type: 'number',\n label: 'Temperature',\n helperMessage: 'Leave blank to use the provider default. Some reasoning models may ignore this setting.',\n dataKey: 'temperature',\n useInputToggleDataKey: 'useTemperatureInput',\n allowEmpty: true,\n min: 0,\n max: 2,\n step: 0.1,\n },\n {\n type: 'number',\n label: 'Max output tokens',\n dataKey: 'maxTokens',\n useInputToggleDataKey: 'useMaxTokensInput',\n min: 1,\n step: 1,\n },\n {\n type: 'number',\n label: 'Top P',\n dataKey: 'topP',\n useInputToggleDataKey: 'useTopPInput',\n allowEmpty: true,\n min: 0,\n max: 1,\n step: 0.1,\n },\n {\n type: 'number',\n label: 'Top K',\n helperMessage: 'Provider-dependent; some providers or models may ignore this setting.',\n dataKey: 'topK',\n useInputToggleDataKey: 'useTopKInput',\n allowEmpty: true,\n min: 1,\n step: 1,\n },\n {\n type: 'number',\n label: 'Presence penalty',\n dataKey: 'presencePenalty',\n useInputToggleDataKey: 'usePresencePenaltyInput',\n allowEmpty: true,\n min: -1,\n max: 1,\n step: 0.1,\n },\n {\n type: 'number',\n label: 'Frequency penalty',\n dataKey: 'frequencyPenalty',\n useInputToggleDataKey: 'useFrequencyPenaltyInput',\n allowEmpty: true,\n min: -1,\n max: 1,\n step: 0.1,\n },\n {\n type: 'stringList',\n label: 'Stop sequences',\n dataKey: 'stopSequences',\n useInputToggleDataKey: 'useStopSequencesInput',\n placeholder: 'Stop sequence',\n newItemDefault: '',\n },\n {\n type: 'number',\n label: 'Seed',\n dataKey: 'seed',\n useInputToggleDataKey: 'useSeedInput',\n allowEmpty: true,\n min: 0,\n step: 1,\n },\n ],\n },\n {\n type: 'group',\n label: 'Outputs',\n editors: [\n {\n type: 'toggle',\n label: 'Enable Tool Calling',\n dataKey: 'useToolCalling',\n },\n {\n type: 'toggle',\n label: 'Output usage details',\n dataKey: 'outputUsage',\n helperMessage:\n 'Adds a Usage output built from Vercel AI SDK usage metadata: prompt, completion, total, cached, reasoning tokens, and estimated cost when available.',\n },\n {\n type: 'toggle',\n label: 'Stream response',\n dataKey: 'useAsGraphPartialOutput',\n helperMessage: STREAM_RESPONSE_HELPER_MESSAGE,\n },\n ],\n },\n ] satisfies EditorDefinition<ChatV2SharedNode>[];\n\n return editors as unknown as EditorDefinition<T>[];\n}\n", "export const DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_REPEAT_TIMES = 1;\nexport const DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_COOLDOWN_MS = 0;\n\nexport function normalizeLLMChatV2RetryCount(value: number | undefined): number {\n const retryCount =\n typeof value === 'number' && Number.isFinite(value) ? value : DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_REPEAT_TIMES;\n\n return Math.max(1, Math.floor(retryCount));\n}\n\nexport function normalizeLLMChatV2RetryCooldownMs(value: number | undefined): number {\n const cooldownMs =\n typeof value === 'number' && Number.isFinite(value) ? value : DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_COOLDOWN_MS;\n\n return Math.max(0, Math.floor(cooldownMs));\n}\n\n/** Keeps cancellation identity consistent before and during a retry cooldown. */\nexport function createLLMChatV2RetryAbortError(): Error {\n const error = new Error('Aborted');\n error.name = 'AbortError';\n return error;\n}\n\nexport async function waitForLLMChatV2RetryCooldown(cooldownMs: number, signal: AbortSignal): Promise<void> {\n if (signal.aborted) {\n throw createLLMChatV2RetryAbortError();\n }\n\n if (cooldownMs <= 0) {\n return;\n }\n\n await new Promise<void>((resolve, reject) => {\n const cleanup = () => {\n clearTimeout(timeout);\n signal.removeEventListener('abort', onAbort);\n };\n const onAbort = () => {\n cleanup();\n reject(createLLMChatV2RetryAbortError());\n };\n\n const timeout = setTimeout(() => {\n cleanup();\n resolve();\n }, cooldownMs);\n\n signal.addEventListener('abort', onAbort, { once: true });\n if (signal.aborted) {\n onAbort();\n }\n });\n}\n", "import type { LLMChatV2NodeData } from './llmChatV2NodeData.js';\n\n/**\n * Static ownership metadata for fields supplied by an LLM Profile.\n *\n * This deliberately does not attempt to describe editor layout or provider\n * request construction. It provides the one fact those surfaces must share:\n * which persisted LLM Chat fields are profile-owned, and which dynamic input\n * ports a resolved profile consumes before it is passed to LLM Chat.\n */\nexport type LLMProfileFieldSpec = {\n key: keyof LLMChatV2NodeData;\n inputId?: string;\n /** Runtime validation for scalar fields; enum and collection fields keep named validators. */\n valueKind?: 'string' | 'boolean' | 'required-number' | 'optional-number';\n /** A resolved profile must never retain an active dynamic-input toggle. */\n resolvedInputToggle?: boolean;\n};\n\nexport const llmProfileFieldSpecs = [\n { key: 'model', inputId: 'model', valueKind: 'string' },\n { key: 'useModelInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'temperature', inputId: 'temperature', valueKind: 'optional-number' },\n { key: 'useTemperatureInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'topP', inputId: 'topP', valueKind: 'optional-number' },\n { key: 'useTopPInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'topK', inputId: 'topK', valueKind: 'optional-number' },\n { key: 'useTopKInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'presencePenalty', inputId: 'presencePenalty', valueKind: 'optional-number' },\n { key: 'usePresencePenaltyInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'frequencyPenalty', inputId: 'frequencyPenalty', valueKind: 'optional-number' },\n { key: 'useFrequencyPenaltyInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'stopSequences', inputId: 'stopSequences' },\n { key: 'useStopSequencesInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'seed', inputId: 'seed', valueKind: 'optional-number' },\n { key: 'useSeedInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'maxTokens', inputId: 'maxTokens', valueKind: 'required-number' },\n { key: 'useMaxTokensInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'provider' },\n { key: 'apiKeySource', inputId: 'apiKey' },\n { key: 'providerApiKeyNames' },\n { key: 'customProviderApiKeyProgrammaticName', valueKind: 'string' },\n { key: 'customProviderApiKeyEnvVarName', valueKind: 'string' },\n { key: 'customProviderBaseURL', inputId: 'customProviderBaseURL', valueKind: 'string' },\n { key: 'useCustomProviderBaseURLInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'customProviderApi' },\n { key: 'headers', inputId: 'headers' },\n { key: 'useHeadersInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'extraProviderOptions', inputId: 'extraProviderOptions', valueKind: 'string' },\n { key: 'useExtraProviderOptionsInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'openAIReasoningEffort', valueKind: 'string' },\n { key: 'openAIReasoningSummary', valueKind: 'string' },\n { key: 'openAIPreviousResponseId', inputId: 'previousResponseId', valueKind: 'string' },\n { key: 'useOpenAIPreviousResponseIdInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'enableOpenAIWebSearch', valueKind: 'boolean' },\n { key: 'openAIWebSearchContextSize' },\n { key: 'enableOpenAICodeInterpreter', valueKind: 'boolean' },\n { key: 'anthropicThinkingMode' },\n { key: 'anthropicThinkingBudget', inputId: 'anthropicThinkingBudget', valueKind: 'optional-number' },\n { key: 'useAnthropicThinkingBudgetInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'anthropicEffort' },\n { key: 'anthropicCacheControlTtl' },\n { key: 'googleThinkingBudget', inputId: 'googleThinkingBudget', valueKind: 'optional-number' },\n { key: 'useGoogleThinkingBudgetInput', valueKind: 'boolean', resolvedInputToggle: true },\n { key: 'googleThinkingLevel' },\n { key: 'googleIncludeThoughts', valueKind: 'boolean' },\n { key: 'enableGoogleSearchGrounding', valueKind: 'boolean' },\n { key: 'enableGoogleUrlContext', valueKind: 'boolean' },\n { key: 'enableCircuitBreaker', valueKind: 'boolean' },\n { key: 'firstOutputTimeoutMs', valueKind: 'required-number' },\n { key: 'streamInactivityTimeoutMs', valueKind: 'required-number' },\n { key: 'circuitBreakerFailureThreshold', valueKind: 'required-number' },\n { key: 'circuitBreakerFailureWindowMs', valueKind: 'required-number' },\n { key: 'circuitBreakerOpenDurationMs', valueKind: 'required-number' },\n] as const satisfies readonly LLMProfileFieldSpec[];\n\nexport const llmProfileDataKeys = llmProfileFieldSpecs.map((field) => field.key);\n\nexport const llmProfileInputIds = llmProfileFieldSpecs\n .flatMap((field) => ('inputId' in field ? [field.inputId] : []))\n .filter((inputId, index, inputIds) => inputIds.indexOf(inputId) === index);\n\nfunction keysForValueKind(valueKind: NonNullable<LLMProfileFieldSpec['valueKind']>) {\n return llmProfileFieldSpecs\n .filter((field) => 'valueKind' in field && field.valueKind === valueKind)\n .map((field) => field.key) as Array<keyof LLMChatV2NodeData>;\n}\n\n/** Runtime validation categories for resolved LLM Profile values. */\nexport const llmProfileStringDataKeys = keysForValueKind('string');\nexport const llmProfileBooleanDataKeys = keysForValueKind('boolean');\nexport const llmProfileRequiredNumberDataKeys = keysForValueKind('required-number');\nexport const llmProfileOptionalNumberDataKeys = keysForValueKind('optional-number');\n\n/** A serialized profile must be self-contained, not driven by hidden ports. */\nexport const llmProfileResolvedInputToggleDataKeys = llmProfileFieldSpecs\n .filter((field) => 'resolvedInputToggle' in field && field.resolvedInputToggle)\n .map((field) => field.key) as Array<keyof LLMChatV2NodeData>;\n", "import { nanoid } from 'nanoid/non-secure';\nimport CryptoJS from 'crypto-js';\nimport stableStringify from 'safe-stable-stringify';\nimport type { NodeId } from '../NodeBase.js';\nimport type { ProjectId } from '../Project.js';\nimport type { ChatV2CredentialResult } from './chatV2ProviderProfile.js';\nimport type { LLMChatV2ProfileData } from './llmChatV2NodeData.js';\nimport type { ChatV2Provider } from './chatV2ProviderTypes.js';\nimport type { CustomProviderApi } from './customProviderApi.js';\n\nexport const DEFAULT_LLM_PROFILE_FIRST_OUTPUT_TIMEOUT_MS = 30_000;\nexport const DEFAULT_LLM_PROFILE_STREAM_INACTIVITY_TIMEOUT_MS = 30_000;\nexport const DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_THRESHOLD = 3;\nexport const DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_WINDOW_MS = 300_000;\nexport const DEFAULT_LLM_PROFILE_CIRCUIT_OPEN_DURATION_MS = 300_000;\nconst LLM_PROFILE_HALF_OPEN_LEASE_SAFETY_MARGIN_MS = 5_000;\nconst LLM_PROFILE_CLOSED_PERMIT_MIN_RETENTION_MS = 24 * 60 * 60 * 1_000;\n\nexport class RivetLLMProfileHealthPolicyError extends Error {\n constructor(message: string) {\n super(`LLM profile suspension policy is invalid: ${message}`);\n this.name = 'RivetLLMProfileHealthPolicyError';\n }\n}\n\nexport type RivetLLMProfileCircuitBreakerPolicy = {\n failureThreshold: number;\n failureWindowMs: number;\n openDurationMs: number;\n halfOpenLeaseMs: number;\n};\n\nfunction requirePositiveInteger(value: unknown, label: string): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) {\n throw new RivetLLMProfileHealthPolicyError(`${label} must be a positive integer.`);\n }\n return value;\n}\n\nexport function resolveRivetLLMProfileCircuitBreakerPolicy(\n configuration: LLMChatV2ProfileData,\n): RivetLLMProfileCircuitBreakerPolicy | undefined {\n if (configuration.enableCircuitBreaker !== true) {\n return undefined;\n }\n\n const firstOutputTimeoutMs = requirePositiveInteger(\n configuration.firstOutputTimeoutMs ?? DEFAULT_LLM_PROFILE_FIRST_OUTPUT_TIMEOUT_MS,\n 'Useful output wait time',\n );\n const streamInactivityTimeoutMs = requirePositiveInteger(\n configuration.streamInactivityTimeoutMs ?? DEFAULT_LLM_PROFILE_STREAM_INACTIVITY_TIMEOUT_MS,\n 'Stream inactivity timeout',\n );\n const failureThreshold = requirePositiveInteger(\n configuration.circuitBreakerFailureThreshold ?? DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_THRESHOLD,\n 'Failures before suspension',\n );\n const failureWindowMs = requirePositiveInteger(\n configuration.circuitBreakerFailureWindowMs ?? DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_WINDOW_MS,\n 'Failure window',\n );\n const openDurationMs = requirePositiveInteger(\n configuration.circuitBreakerOpenDurationMs ?? DEFAULT_LLM_PROFILE_CIRCUIT_OPEN_DURATION_MS,\n 'Suspension duration',\n );\n\n return {\n failureThreshold,\n failureWindowMs,\n openDurationMs,\n // A live streaming probe renews this lease on useful output. The bounded\n // safety margin lets a dead owner recover promptly without coupling the\n // probe lease to the (usually much longer) circuit cooldown.\n halfOpenLeaseMs:\n Math.max(firstOutputTimeoutMs, streamInactivityTimeoutMs) + LLM_PROFILE_HALF_OPEN_LEASE_SAFETY_MARGIN_MS,\n };\n}\n\n/**\n * Stable, privacy-bounded identity for one resolved LLM Profile configuration.\n * `key` and `configurationFingerprint` are SHA-256 routing/auth digests;\n * credentials and provider configuration are never exposed through this\n * contract.\n */\nexport type RivetLLMProfileHealthIdentity = {\n key: string;\n projectId?: ProjectId;\n profileNodeId?: NodeId;\n /** Current source-node title used only for operator-facing identification. */\n profileName?: string;\n provider: ChatV2Provider;\n model: string;\n customProviderApi?: CustomProviderApi;\n configurationFingerprint: string;\n};\n\nfunction sha256(value: string): string {\n return `sha256:${CryptoJS.SHA256(value).toString(CryptoJS.enc.Hex)}`;\n}\n\nexport function createRivetLLMProfileHealthIdentity(params: {\n configuration: LLMChatV2ProfileData;\n credential: ChatV2CredentialResult;\n /** Project-wide Chat headers merged into every physical provider request. */\n chatNodeHeaders?: Record<string, string> | undefined;\n projectId?: ProjectId;\n profileNodeId?: NodeId;\n /** Current source-node title. It is intentionally excluded from the key. */\n profileName?: string;\n}): RivetLLMProfileHealthIdentity {\n const profileName = params.profileName?.trim();\n // Circuit health belongs to the physical provider route and credentials,\n // not to generation policy. A temperature/cooldown edit must not silently\n // create a fresh circuit, while changing the model, endpoint, auth, or\n // routing headers must never inherit another route's outage history.\n const routingConfiguration = {\n provider: params.configuration.provider,\n model: params.configuration.model,\n ...(params.configuration.provider !== 'custom'\n ? {}\n : {\n customProviderApi: params.configuration.customProviderApi ?? 'completions',\n customProviderBaseURL: params.configuration.customProviderBaseURL,\n }),\n headers: canonicalizeEffectiveRoutingHeaders(params.chatNodeHeaders, params.configuration.headers),\n };\n const serialized =\n stableStringify({\n routingConfiguration,\n credential: params.credential,\n }) ?? '';\n const configurationFingerprint = sha256(serialized);\n const projectId = params.projectId == null ? undefined : String(params.projectId);\n const profileNodeId = params.profileNodeId == null ? undefined : String(params.profileNodeId);\n const key = sha256(\n stableStringify({\n kind: 'rivet-llm-profile-health',\n projectId,\n profileNodeId,\n configurationFingerprint,\n }) ?? '',\n );\n\n return {\n key: `llm-profile:${key}`,\n ...(params.projectId == null ? {} : { projectId: params.projectId }),\n ...(params.profileNodeId == null ? {} : { profileNodeId: params.profileNodeId }),\n ...(profileName === '' || profileName == null ? {} : { profileName }),\n provider: params.configuration.provider,\n model: params.configuration.model,\n ...(params.configuration.provider !== 'custom'\n ? {}\n : { customProviderApi: params.configuration.customProviderApi ?? 'completions' }),\n configurationFingerprint,\n };\n}\n\nfunction canonicalizeEffectiveRoutingHeaders(\n chatNodeHeaders: Record<string, string> | undefined,\n profileHeaders: LLMChatV2ProfileData['headers'],\n): Array<[string, string]> {\n // Provider resolution spreads project-wide headers first and profile\n // headers second. Normalize names here because HTTP field names are\n // case-insensitive, while preserving that same profile-wins precedence.\n // Values remain confined to the SHA-256 input and never enter the public\n // identity or store key in plaintext.\n const headers = new Map<string, string>();\n for (const [key, value] of Object.entries(chatNodeHeaders ?? {})) {\n const normalizedKey = key.trim().toLowerCase();\n if (normalizedKey) headers.set(normalizedKey, value);\n }\n for (const { key, value } of profileHeaders) {\n const normalizedKey = key.trim().toLowerCase();\n if (normalizedKey) headers.set(normalizedKey, value);\n }\n return [...headers.entries()].sort(([left], [right]) => left.localeCompare(right));\n}\n\nexport type RivetLLMProfileHealthState = 'closed' | 'open' | 'half-open';\n\nexport type RivetLLMProfileHealthSnapshot = {\n identity: RivetLLMProfileHealthIdentity;\n state: RivetLLMProfileHealthState;\n failureCount: number;\n openUntil?: number;\n halfOpenLeaseUntil?: number;\n updatedAt: number;\n};\n\nexport type RivetLLMProfileHealthBeginRequest = {\n identity: RivetLLMProfileHealthIdentity;\n policy: RivetLLMProfileCircuitBreakerPolicy;\n};\n\nexport type RivetLLMProfileHealthBeginResult = {\n disposition: 'allow' | 'deny';\n state: RivetLLMProfileHealthState;\n /** Opaque permit returned to `finish`; present only when execution is allowed. */\n permitId?: string;\n retryAt?: number;\n snapshot: RivetLLMProfileHealthSnapshot;\n};\n\nexport type RivetLLMProfileHealthOutcome = 'healthy' | 'unhealthy' | 'ignored';\n\nexport type RivetLLMProfileHealthFinishRequest = {\n identity: RivetLLMProfileHealthIdentity;\n policy: RivetLLMProfileCircuitBreakerPolicy;\n permitId: string;\n outcome: RivetLLMProfileHealthOutcome;\n /**\n * Host-owned, privacy-bounded execution correlation. Studio Server uses this\n * only to join an unhealthy profile result to its normal run recording after\n * that recording has finished persisting.\n */\n executionCorrelationId?: string;\n};\n\nexport type RivetLLMProfileHealthRenewRequest = {\n identity: RivetLLMProfileHealthIdentity;\n permitId: string;\n leaseDurationMs: number;\n};\n\nexport type RivetLLMProfileHealthResetRequest =\n | { key: string; projectId?: never }\n | { key?: never; projectId: ProjectId };\n\nexport type RivetLLMProfileHealthListRequest = {\n projectId?: ProjectId;\n};\n\n/**\n * Host persistence seam for LLM Profile health. Implementations must make\n * each method atomic. In particular, `begin` must allow at most one probe\n * while an open circuit is half-open across all processes using the store.\n */\nexport interface RivetLLMProfileHealthStore {\n begin(\n request: RivetLLMProfileHealthBeginRequest,\n ): RivetLLMProfileHealthBeginResult | Promise<RivetLLMProfileHealthBeginResult>;\n finish(\n request: RivetLLMProfileHealthFinishRequest,\n ): RivetLLMProfileHealthSnapshot | Promise<RivetLLMProfileHealthSnapshot>;\n renew(\n request: RivetLLMProfileHealthRenewRequest,\n ): RivetLLMProfileHealthSnapshot | Promise<RivetLLMProfileHealthSnapshot>;\n reset(request: RivetLLMProfileHealthResetRequest): void | Promise<void>;\n list(\n request?: RivetLLMProfileHealthListRequest,\n ): RivetLLMProfileHealthSnapshot[] | Promise<RivetLLMProfileHealthSnapshot[]>;\n}\n\ntype MutableHealthEntry = {\n identity: RivetLLMProfileHealthIdentity;\n failureTimestamps: number[];\n openUntil?: number;\n halfOpenPermitId?: string;\n halfOpenLeaseUntil?: number;\n updatedAt: number;\n policy: RivetLLMProfileCircuitBreakerPolicy;\n closedPermits: Map<string, number>;\n};\n\nfunction requireMatchingProjectScope(existing: MutableHealthEntry, identity: RivetLLMProfileHealthIdentity): void {\n const storedProjectId = existing.identity.projectId == null ? undefined : String(existing.identity.projectId);\n const requestProjectId = identity.projectId == null ? undefined : String(identity.projectId);\n if (storedProjectId !== requestProjectId) {\n throw new Error(`LLM profile reliability key ${identity.key} belongs to a different project scope.`);\n }\n}\n\nfunction closedPermitRetentionMs(policy: RivetLLMProfileCircuitBreakerPolicy): number {\n return Math.max(\n LLM_PROFILE_CLOSED_PERMIT_MIN_RETENTION_MS,\n policy.failureWindowMs,\n policy.openDurationMs,\n policy.halfOpenLeaseMs,\n );\n}\n\nfunction pruneClosedPermits(entry: MutableHealthEntry, now: number): void {\n for (const [permitId, expiresAt] of entry.closedPermits) {\n if (expiresAt <= now) entry.closedPermits.delete(permitId);\n }\n}\n\nfunction pruneFailures(entry: MutableHealthEntry, policy: RivetLLMProfileCircuitBreakerPolicy, now: number): void {\n const windowStart = now - policy.failureWindowMs;\n entry.failureTimestamps = entry.failureTimestamps.filter((timestamp) => timestamp >= windowStart);\n}\n\nfunction getState(entry: MutableHealthEntry, now: number): RivetLLMProfileHealthState {\n if (entry.openUntil == null) return 'closed';\n if (entry.openUntil > now) return 'open';\n return 'half-open';\n}\n\nfunction toSnapshot(\n entry: MutableHealthEntry,\n policy: RivetLLMProfileCircuitBreakerPolicy,\n now: number,\n): RivetLLMProfileHealthSnapshot {\n pruneFailures(entry, policy, now);\n const state = getState(entry, now);\n return {\n identity: entry.identity,\n state,\n failureCount: entry.failureTimestamps.length,\n ...(entry.openUntil == null ? {} : { openUntil: entry.openUntil }),\n ...(state !== 'half-open' || entry.halfOpenLeaseUntil == null\n ? {}\n : { halfOpenLeaseUntil: entry.halfOpenLeaseUntil }),\n updatedAt: entry.updatedAt,\n };\n}\n\n/** Process-local reference implementation used when a host does not supply durable shared storage. */\nexport class InMemoryRivetLLMProfileHealthStore implements RivetLLMProfileHealthStore {\n readonly #entries = new Map<string, MutableHealthEntry>();\n readonly #now: () => number;\n\n constructor(options: { now?: () => number } = {}) {\n this.#now = options.now ?? Date.now;\n }\n\n #pruneStaleEntries(now: number): void {\n for (const [key, entry] of this.#entries) {\n pruneFailures(entry, entry.policy, now);\n pruneClosedPermits(entry, now);\n const isEmptyClosedEntry =\n entry.failureTimestamps.length === 0 &&\n entry.openUntil == null &&\n entry.halfOpenPermitId == null &&\n entry.closedPermits.size === 0;\n if (isEmptyClosedEntry && entry.updatedAt + closedPermitRetentionMs(entry.policy) <= now) {\n this.#entries.delete(key);\n }\n }\n }\n\n begin(request: RivetLLMProfileHealthBeginRequest): RivetLLMProfileHealthBeginResult {\n const { identity, policy } = request;\n const now = this.#now();\n this.#pruneStaleEntries(now);\n let entry = this.#entries.get(identity.key);\n if (entry == null) {\n entry = { identity, failureTimestamps: [], updatedAt: now, policy, closedPermits: new Map() };\n this.#entries.set(identity.key, entry);\n } else {\n requireMatchingProjectScope(entry, identity);\n entry.identity = identity;\n entry.policy = policy;\n }\n pruneFailures(entry, policy, now);\n pruneClosedPermits(entry, now);\n\n if (entry.openUntil != null && entry.openUntil > now) {\n return {\n disposition: 'deny',\n state: 'open',\n retryAt: entry.openUntil,\n snapshot: toSnapshot(entry, policy, now),\n };\n }\n\n if (entry.openUntil != null) {\n if (entry.halfOpenPermitId != null && (entry.halfOpenLeaseUntil ?? 0) > now) {\n return {\n disposition: 'deny',\n state: 'half-open',\n retryAt: entry.halfOpenLeaseUntil,\n snapshot: toSnapshot(entry, policy, now),\n };\n }\n\n const permitId = nanoid();\n entry.halfOpenPermitId = permitId;\n entry.halfOpenLeaseUntil = now + policy.halfOpenLeaseMs;\n entry.updatedAt = now;\n return {\n disposition: 'allow',\n state: 'half-open',\n permitId,\n snapshot: toSnapshot(entry, policy, now),\n };\n }\n\n const permitId = nanoid();\n entry.closedPermits.set(permitId, now + closedPermitRetentionMs(policy));\n entry.updatedAt = now;\n return {\n disposition: 'allow',\n state: 'closed',\n permitId,\n snapshot: toSnapshot(entry, policy, now),\n };\n }\n\n finish(request: RivetLLMProfileHealthFinishRequest): RivetLLMProfileHealthSnapshot {\n const { identity, policy, permitId, outcome } = request;\n const now = this.#now();\n this.#pruneStaleEntries(now);\n const entry = this.#entries.get(identity.key);\n if (entry == null) {\n return {\n identity,\n state: 'closed',\n failureCount: 0,\n updatedAt: now,\n };\n }\n requireMatchingProjectScope(entry, identity);\n entry.identity = identity;\n entry.policy = policy;\n pruneFailures(entry, policy, now);\n pruneClosedPermits(entry, now);\n\n const ownsHalfOpenLease = entry.halfOpenPermitId === permitId;\n const ownsClosedPermit = entry.closedPermits.delete(permitId);\n if (!ownsHalfOpenLease && !ownsClosedPermit) {\n return toSnapshot(entry, policy, now);\n }\n\n if (outcome === 'healthy' && ownsHalfOpenLease) {\n entry.failureTimestamps = [];\n entry.openUntil = undefined;\n entry.halfOpenPermitId = undefined;\n entry.halfOpenLeaseUntil = undefined;\n // Requests admitted before the circuit opened belong to the previous\n // health generation. Once the single recovery probe succeeds, their\n // eventual results must not immediately poison the recovered circuit.\n entry.closedPermits.clear();\n } else if (outcome === 'unhealthy') {\n const wasOpen = entry.openUntil != null;\n entry.failureTimestamps.push(now);\n if (ownsHalfOpenLease || (!wasOpen && entry.failureTimestamps.length >= policy.failureThreshold)) {\n entry.openUntil = now + policy.openDurationMs;\n }\n if (ownsHalfOpenLease) {\n entry.halfOpenPermitId = undefined;\n entry.halfOpenLeaseUntil = undefined;\n }\n } else if (outcome === 'ignored' && ownsHalfOpenLease) {\n entry.halfOpenPermitId = undefined;\n entry.halfOpenLeaseUntil = undefined;\n }\n\n entry.updatedAt = now;\n return toSnapshot(entry, policy, now);\n }\n\n renew(request: RivetLLMProfileHealthRenewRequest): RivetLLMProfileHealthSnapshot {\n const now = this.#now();\n this.#pruneStaleEntries(now);\n const entry = this.#entries.get(request.identity.key);\n if (entry == null) {\n return {\n identity: request.identity,\n state: 'closed',\n failureCount: 0,\n updatedAt: now,\n };\n }\n\n requireMatchingProjectScope(entry, request.identity);\n\n if (entry.halfOpenPermitId === request.permitId) {\n entry.halfOpenLeaseUntil = Math.max(entry.halfOpenLeaseUntil ?? 0, now + request.leaseDurationMs);\n entry.updatedAt = now;\n } else if (entry.closedPermits.has(request.permitId)) {\n entry.closedPermits.set(\n request.permitId,\n Math.max(entry.closedPermits.get(request.permitId) ?? 0, now + closedPermitRetentionMs(entry.policy)),\n );\n entry.updatedAt = now;\n }\n return toSnapshot(entry, entry.policy, now);\n }\n\n reset(request: RivetLLMProfileHealthResetRequest): void {\n if (request.key != null) {\n this.#entries.delete(request.key);\n return;\n }\n\n for (const [key, entry] of this.#entries) {\n if (entry.identity.projectId === request.projectId) {\n this.#entries.delete(key);\n }\n }\n }\n\n list(request: RivetLLMProfileHealthListRequest = {}): RivetLLMProfileHealthSnapshot[] {\n const now = this.#now();\n this.#pruneStaleEntries(now);\n return [...this.#entries.entries()]\n .filter(([, entry]) => request.projectId == null || entry.identity.projectId === request.projectId)\n .map(([, entry]) => {\n pruneFailures(entry, entry.policy, now);\n pruneClosedPermits(entry, now);\n const state = getState(entry, now);\n return {\n identity: entry.identity,\n state,\n failureCount: entry.failureTimestamps.length,\n ...(entry.openUntil == null ? {} : { openUntil: entry.openUntil }),\n ...(state !== 'half-open' || entry.halfOpenLeaseUntil == null\n ? {}\n : { halfOpenLeaseUntil: entry.halfOpenLeaseUntil }),\n updatedAt: entry.updatedAt,\n };\n });\n }\n}\n", "import type { ChatV2ResponseFormat } from './chatV2ResponseFormat.js';\nimport { createChatV2CommonNodeData, type ChatV2CommonNodeData } from './chatV2Shared.js';\nimport {\n DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_COOLDOWN_MS,\n DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_REPEAT_TIMES,\n} from './chatV2Retry.js';\nimport type { ChatV2Provider } from './chatV2Types.js';\nimport type { ChartNode, NodeId } from '../NodeBase.js';\nimport { llmProfileDataKeys } from './llmProfileFieldRegistry.js';\nimport type { CustomProviderApi } from './customProviderApi.js';\nimport type { ChatV2CredentialNamesByProvider } from './chatV2CredentialNames.js';\nimport {\n DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_THRESHOLD,\n DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_WINDOW_MS,\n DEFAULT_LLM_PROFILE_CIRCUIT_OPEN_DURATION_MS,\n DEFAULT_LLM_PROFILE_FIRST_OUTPUT_TIMEOUT_MS,\n DEFAULT_LLM_PROFILE_STREAM_INACTIVITY_TIMEOUT_MS,\n} from './llmProfileHealthStore.js';\n\nexport type { CustomProviderApi } from './customProviderApi.js';\n\nexport type LLMChatV2ToolChoiceMode = '' | 'auto' | 'function' | 'required';\nexport type LLMChatV2ApiKeySource = 'environment' | 'input';\nexport type LLMChatV2ConfigurationMode = 'inline' | 'profile';\nexport type LLMChatV2NodeConfigData = ChatV2CommonNodeData & {\n configurationMode?: LLMChatV2ConfigurationMode;\n provider: ChatV2Provider;\n apiKeySource?: LLMChatV2ApiKeySource;\n providerApiKeyNames?: ChatV2CredentialNamesByProvider;\n customProviderApiKeyProgrammaticName?: string;\n customProviderApiKeyEnvVarName?: string;\n customProviderBaseURL: string;\n useCustomProviderBaseURLInput: boolean;\n /** Missing on legacy/programmatically-created nodes means Chat Completions. */\n customProviderApi?: CustomProviderApi;\n baseURL: string;\n useBaseURLInput: boolean;\n headers: { key: string; value: string }[];\n useHeadersInput: boolean;\n extraProviderOptions: string;\n useExtraProviderOptionsInput: boolean;\n openAIReasoningEffort: string;\n openAIReasoningSummary: string;\n openAIPreviousResponseId: string;\n useOpenAIPreviousResponseIdInput: boolean;\n enableOpenAIWebSearch: boolean;\n openAIWebSearchContextSize: 'low' | 'medium' | 'high';\n enableOpenAICodeInterpreter: boolean;\n anthropicThinkingMode: '' | 'adaptive' | 'enabled' | 'disabled';\n anthropicThinkingBudget?: number;\n useAnthropicThinkingBudgetInput: boolean;\n anthropicEffort?: '' | 'low' | 'medium' | 'high' | 'max';\n anthropicCacheControlTtl: '' | '5m' | '1h';\n googleThinkingBudget?: number;\n useGoogleThinkingBudgetInput: boolean;\n googleThinkingLevel?: '' | 'minimal' | 'low' | 'medium' | 'high';\n googleIncludeThoughts?: boolean;\n enableGoogleSearchGrounding: boolean;\n enableGoogleUrlContext: boolean;\n enableCircuitBreaker?: boolean;\n firstOutputTimeoutMs?: number;\n streamInactivityTimeoutMs?: number;\n circuitBreakerFailureThreshold?: number;\n circuitBreakerFailureWindowMs?: number;\n circuitBreakerOpenDurationMs?: number;\n responseFormat?: ChatV2ResponseFormat;\n responseSchemaName?: string;\n useResponseSchemaNameInput?: boolean;\n responseSchemaDescription?: string;\n useResponseSchemaDescriptionInput?: boolean;\n toolChoice?: LLMChatV2ToolChoiceMode;\n toolChoiceFunction?: string;\n parallelToolCalls?: boolean;\n autoContinueToolCalls?: boolean;\n maxToolRounds?: number;\n retryOnNon200?: boolean;\n errorOnNon200?: boolean;\n catchRequestFailed?: boolean;\n retryOnNon200RepeatTimes?: number;\n retryOnNon200CooldownMs?: number;\n outputLLMAttempts?: boolean;\n outputRequestBody?: boolean;\n outputResponseBody?: boolean;\n};\n\nexport type LLMChatV2NodeData = LLMChatV2NodeConfigData;\nexport type LLMChatV2Node = ChartNode<'llmChatV2', LLMChatV2NodeData>;\n\n/** @deprecated Use llmProfileDataKeys from llmProfileFieldRegistry instead. */\nexport const llmChatV2ProfileDataKeys = llmProfileDataKeys;\n\nexport type LLMChatV2ProfileDataKey = (typeof llmChatV2ProfileDataKeys)[number];\nexport type LLMChatV2ProfileData = Pick<LLMChatV2NodeData, LLMChatV2ProfileDataKey>;\n\nexport type LLMChatV2EditorCacheKeyParts = {\n /** Bump when cache identity semantics change; entries are editor-memory only. */\n cacheVersion?: number;\n nodeId: NodeId;\n nodeData: LLMChatV2NodeData;\n provider: ChatV2Provider;\n modelId: string;\n providerConfig: unknown;\n apiKeyFingerprint?: string;\n prompt: unknown;\n systemPrompt: unknown;\n functions: unknown;\n generationParameters: unknown;\n responseFormatParameters: unknown;\n providerOptions: unknown;\n requestBodyOverlay?: unknown;\n toolChoice: unknown;\n /** Ordered, credential-fingerprinted fallback profile configuration. */\n profileChain?: unknown;\n};\n\nexport function createLLMChatV2NodeData(): LLMChatV2NodeData {\n return {\n ...createChatV2CommonNodeData({\n model: 'gpt-5',\n }),\n configurationMode: 'inline',\n provider: 'openai',\n apiKeySource: 'environment',\n customProviderApiKeyProgrammaticName: '',\n customProviderApiKeyEnvVarName: 'CUSTOM_PROVIDER_API_KEY',\n customProviderBaseURL: '',\n useCustomProviderBaseURLInput: false,\n customProviderApi: 'completions',\n baseURL: '',\n useBaseURLInput: false,\n headers: [],\n useHeadersInput: false,\n extraProviderOptions: '',\n useExtraProviderOptionsInput: false,\n openAIReasoningEffort: '',\n openAIReasoningSummary: '',\n openAIPreviousResponseId: '',\n useOpenAIPreviousResponseIdInput: false,\n enableOpenAIWebSearch: false,\n openAIWebSearchContextSize: 'medium',\n enableOpenAICodeInterpreter: false,\n anthropicThinkingMode: '',\n anthropicThinkingBudget: undefined,\n useAnthropicThinkingBudgetInput: false,\n anthropicEffort: '',\n anthropicCacheControlTtl: '',\n googleThinkingBudget: undefined,\n useGoogleThinkingBudgetInput: false,\n googleThinkingLevel: '',\n googleIncludeThoughts: false,\n enableGoogleSearchGrounding: false,\n enableGoogleUrlContext: false,\n enableCircuitBreaker: false,\n firstOutputTimeoutMs: DEFAULT_LLM_PROFILE_FIRST_OUTPUT_TIMEOUT_MS,\n streamInactivityTimeoutMs: DEFAULT_LLM_PROFILE_STREAM_INACTIVITY_TIMEOUT_MS,\n circuitBreakerFailureThreshold: DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_THRESHOLD,\n circuitBreakerFailureWindowMs: DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_WINDOW_MS,\n circuitBreakerOpenDurationMs: DEFAULT_LLM_PROFILE_CIRCUIT_OPEN_DURATION_MS,\n responseFormat: '',\n responseSchemaName: '',\n useResponseSchemaNameInput: false,\n responseSchemaDescription: '',\n useResponseSchemaDescriptionInput: false,\n toolChoice: '',\n toolChoiceFunction: '',\n parallelToolCalls: false,\n autoContinueToolCalls: false,\n maxToolRounds: 3,\n retryOnNon200: false,\n errorOnNon200: true,\n catchRequestFailed: false,\n retryOnNon200RepeatTimes: DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_REPEAT_TIMES,\n retryOnNon200CooldownMs: DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_COOLDOWN_MS,\n outputLLMAttempts: false,\n outputRequestBody: false,\n outputResponseBody: false,\n };\n}\n\nexport function shouldIncludeLLMChatV2ToolCalls(data: LLMChatV2NodeData): boolean {\n return data.useToolCalling;\n}\n", "import type { ChatV2CredentialResult } from './chatV2ProviderProfile.js';\nimport {\n createLLMChatV2NodeData,\n llmChatV2ProfileDataKeys,\n type LLMChatV2NodeData,\n type LLMChatV2ProfileData,\n} from './llmChatV2NodeData.js';\nimport type { RivetLLMProfileHealthIdentity } from './llmProfileHealthStore.js';\n\nexport const LLM_PROFILE_VALUE_VERSION = 1 as const;\n\n/**\n * Every input port owned by an LLM Profile, including ports that are hidden\n * until their matching provider or input toggle is enabled. This lets editor\n * operations preserve recoverable connections across configuration changes.\n */\nexport { llmProfileInputIds } from './llmProfileFieldRegistry.js';\n\nexport type LLMProfileValue = {\n version: typeof LLM_PROFILE_VALUE_VERSION;\n configuration: LLMChatV2ProfileData;\n credential: ChatV2CredentialResult;\n /**\n * User-facing title captured from the source LLM Profile node. It is\n * diagnostic metadata only: changing a node title must not change provider\n * resolution, caching, or circuit-breaker identity.\n */\n profileName?: string;\n /** Stable privacy-bounded identity used by optional cross-run health policy. */\n healthIdentity?: RivetLLMProfileHealthIdentity;\n};\n\nexport function createLLMProfileNodeData(): LLMChatV2ProfileData {\n return pickLLMChatV2ProfileData(createLLMChatV2NodeData());\n}\n\nexport function createDefaultLLMProfileValue(): LLMProfileValue {\n return {\n version: LLM_PROFILE_VALUE_VERSION,\n configuration: createLLMProfileNodeData(),\n credential: { reference: { source: 'none' } },\n };\n}\n\nexport function pickLLMChatV2ProfileData(data: LLMChatV2NodeData): LLMChatV2ProfileData {\n return Object.fromEntries(llmChatV2ProfileDataKeys.map((key) => [key, data[key]])) as LLMChatV2ProfileData;\n}\n\nexport function applyLLMProfileToNodeData(data: LLMChatV2NodeData, profile: LLMProfileValue): LLMChatV2NodeData {\n return {\n ...data,\n ...profile.configuration,\n configurationMode: 'profile',\n };\n}\n", "import type { GraphId } from '../index.js';\nimport { exhaustiveTuple } from '../utils/genericUtilFunctions.js';\nimport type { DataId } from './Project.js';\nimport type {\n RivetKnowledgeDocument,\n RivetKnowledgeEvidence,\n RivetKnowledgeSourceReference,\n} from '../integrations/KnowledgeStore.js';\nimport { createDefaultLLMProfileValue, type LLMProfileValue } from './chat-v2/llmProfileTypes.js';\n\nexport type DataValueDef<Type extends string, RuntimeType> = {\n type: Type;\n value: RuntimeType;\n};\n\nexport type StringDataValue = DataValueDef<'string', string>;\nexport type NumberDataValue = DataValueDef<'number', number>;\nexport type BoolDataValue = DataValueDef<'boolean', boolean>;\n\nexport type SystemChatMessage = {\n type: 'system';\n message: ChatMessageMessagePart | ChatMessageMessagePart[];\n\n /** If true, this message marks a breakpoint when used with prompt caching (as of right now, Anthropic-only). */\n isCacheBreakpoint?: boolean;\n};\n\nexport type DeveloperChatMessage = {\n type: 'developer';\n message: ChatMessageMessagePart | ChatMessageMessagePart[];\n\n /** If true, this message marks a breakpoint when used with prompt caching (as of right now, Anthropic-only). */\n isCacheBreakpoint?: boolean;\n};\n\nexport type UserChatMessage = {\n type: 'user';\n message: ChatMessageMessagePart | ChatMessageMessagePart[];\n\n /** If true, this message marks a breakpoint when used with prompt caching (as of right now, Anthropic-only). */\n isCacheBreakpoint?: boolean;\n};\n\nexport type AssistantChatMessageFunctionCall = {\n id: string | undefined;\n name: string;\n arguments: string; // JSON string\n};\n\nexport type ParsedAssistantChatMessageFunctionCall = {\n id: string | undefined;\n name: string;\n arguments: Record<string, unknown>;\n};\n\nexport type AssistantChatMessage = {\n type: 'assistant';\n message: ChatMessageMessagePart | ChatMessageMessagePart[];\n\n /** @deprecated use function_calls instead */\n function_call: AssistantChatMessageFunctionCall | undefined;\n\n function_calls: AssistantChatMessageFunctionCall[] | undefined;\n\n /** If true, this message marks a breakpoint when used with prompt caching (as of right now, Anthropic-only). */\n isCacheBreakpoint?: boolean;\n};\n\nexport type FunctionResponseChatMessage = {\n type: 'function';\n message: ChatMessageMessagePart | ChatMessageMessagePart[];\n name: string;\n toolName?: string;\n\n /** If true, this message marks a breakpoint when used with prompt caching (as of right now, Anthropic-only). */\n isCacheBreakpoint?: boolean;\n};\n\nexport type ChatMessage =\n | SystemChatMessage\n | DeveloperChatMessage\n | UserChatMessage\n | AssistantChatMessage\n | FunctionResponseChatMessage;\n\nexport type ChatMessageMessagePart =\n | string\n | { type: 'image'; mediaType: SupportedImageMediaTypes; data: Uint8Array }\n | { type: 'url'; url: string }\n | {\n type: 'document';\n title: string | undefined;\n context: string | undefined;\n mediaType: SupportedDocumentMediaTypes;\n data: Uint8Array;\n enableCitations: boolean;\n };\n\nexport type SupportedImageMediaTypes = 'image/jpeg' | 'image/png' | 'image/gif';\nexport type SupportedDocumentMediaTypes = 'application/pdf' | 'text/plain';\n\nexport type ChatMessageDataValue = DataValueDef<'chat-message', ChatMessage>;\n\nexport type DateDataValue = DataValueDef<'date', string>;\nexport type TimeDataValue = DataValueDef<'time', string>;\nexport type DateTimeDataValue = DataValueDef<'datetime', string>;\nexport type AnyDataValue = DataValueDef<'any', unknown>;\nexport type ObjectDataValue = DataValueDef<'object', Record<string, unknown>>;\nexport type VectorDataValue = DataValueDef<'vector', number[]>;\nexport type BinaryDataValue = DataValueDef<'binary', Uint8Array>;\nexport type ImageDataValue = DataValueDef<'image', { mediaType: SupportedImageMediaTypes; data: Uint8Array }>;\nexport type AudioDataValue = DataValueDef<'audio', { mediaType?: string; data: Uint8Array }>;\nexport type GraphReferenceValue = DataValueDef<'graph-reference', { graphId: GraphId; graphName: string }>;\nexport type KnowledgeSourceDataValue = DataValueDef<'knowledge-source', RivetKnowledgeSourceReference>;\nexport type KnowledgeDocumentDataValue = DataValueDef<'knowledge-document', RivetKnowledgeDocument>;\nexport type KnowledgeEvidenceDataValue = DataValueDef<'knowledge-evidence', RivetKnowledgeEvidence>;\nexport type LLMProfileDataValue = DataValueDef<'llm-config', LLMProfileValue>;\nexport type DocumentDataValue = DataValueDef<\n 'document',\n {\n mediaType: SupportedDocumentMediaTypes;\n data: Uint8Array;\n title: string | undefined;\n context: string | undefined;\n enableCitations: boolean;\n }\n>;\n\nexport type GptFunctionResultHandling = 'continue' | 'return-direct';\n\n/** GPT function definition */\nexport type GptFunction = {\n name: string;\n namespace?: string;\n description: string;\n parameters: object;\n strict: boolean;\n /** Rivet-only handling for the function result. This is not sent to the model provider. */\n resultHandling?: GptFunctionResultHandling;\n};\n\nexport type GptFunctionDataValue = DataValueDef<'gpt-function', GptFunction>;\n\nexport type ControlFlowExcludedDataValue = DataValueDef<'control-flow-excluded', undefined | 'loop-not-broken'>;\n\nexport type ScalarDataValue =\n | StringDataValue\n | NumberDataValue\n | DateDataValue\n | TimeDataValue\n | DateTimeDataValue\n | BoolDataValue\n | ChatMessageDataValue\n | ControlFlowExcludedDataValue\n | AnyDataValue\n | ObjectDataValue\n | GptFunctionDataValue\n | VectorDataValue\n | ImageDataValue\n | BinaryDataValue\n | AudioDataValue\n | GraphReferenceValue\n | KnowledgeSourceDataValue\n | KnowledgeDocumentDataValue\n | KnowledgeEvidenceDataValue\n | LLMProfileDataValue\n | DocumentDataValue;\n\nexport type ScalarType = ScalarDataValue['type'];\n\nexport type ArrayDataValue<T extends ScalarDataValue> = DataValueDef<`${T['type']}[]`, T['value'][]>;\n\nexport type FunctionDataValue<T extends ScalarOrArrayDataValue> = DataValueDef<`fn<${T['type']}>`, () => T['value']>;\n\nexport type StringArrayDataValue = ArrayDataValue<StringDataValue>;\n\nexport type ArrayDataValues = {\n [P in ScalarDataValue['type']]: ArrayDataValue<Extract<ScalarDataValue, { type: P }>>;\n}[ScalarDataValue['type']];\n\nexport type ArrayLikeDataValue =\n | ArrayDataValues\n | (AnyDataValue & { value: unknown[] })\n | (ObjectDataValue & { value: unknown[] });\n\nexport type ScalarOrArrayDataValue = ScalarDataValue | ArrayDataValues;\n\nexport type FunctionDataValues = {\n [P in ScalarOrArrayDataValue['type']]: FunctionDataValue<Extract<ScalarOrArrayDataValue, { type: P }>>;\n}[ScalarOrArrayDataValue['type']];\n\nexport type DataValue = ScalarDataValue | ArrayDataValues | FunctionDataValues;\n\nexport type DataType = DataValue['type'];\nexport type ScalarDataType = ScalarDataValue['type'];\nexport type ArrayDataType = ArrayDataValues['type'];\nexport type FunctionDataType = FunctionDataValues['type'];\nexport type ScalarOrArrayDataType = ScalarOrArrayDataValue['type'];\n\nexport type GetDataValue<Type extends DataType> = Extract<DataValue, { type: Type }>;\n\n/** A reference to large data stored outside the graphs themselves. */\nexport type DataRef = {\n refId: DataId;\n};\n\nexport const dataTypes = exhaustiveTuple<DataType>()(\n 'any',\n 'any[]',\n 'boolean',\n 'boolean[]',\n 'string',\n 'string[]',\n 'number',\n 'number[]',\n 'date',\n 'date[]',\n 'time',\n 'time[]',\n 'datetime',\n 'datetime[]',\n 'chat-message',\n 'chat-message[]',\n 'control-flow-excluded',\n 'control-flow-excluded[]',\n 'object',\n 'object[]',\n 'fn<string>',\n 'fn<number>',\n 'fn<boolean>',\n 'fn<date>',\n 'fn<time>',\n 'fn<datetime>',\n 'fn<any>',\n 'fn<object>',\n 'fn<chat-message>',\n 'fn<control-flow-excluded>',\n 'fn<string[]>',\n 'fn<number[]>',\n 'fn<boolean[]>',\n 'fn<date[]>',\n 'fn<time[]>',\n 'fn<datetime[]>',\n 'fn<any[]>',\n 'fn<object[]>',\n 'fn<chat-message[]>',\n 'fn<control-flow-excluded[]>',\n 'gpt-function',\n 'gpt-function[]',\n 'fn<gpt-function[]>',\n 'fn<gpt-function>',\n 'vector',\n 'vector[]',\n 'fn<vector>',\n 'fn<vector[]>',\n 'image',\n 'image[]',\n 'fn<image>',\n 'fn<image[]>',\n 'binary',\n 'binary[]',\n 'fn<binary>',\n 'fn<binary[]>',\n 'audio',\n 'audio[]',\n 'fn<audio>',\n 'fn<audio[]>',\n 'graph-reference',\n 'graph-reference[]',\n 'fn<graph-reference>',\n 'fn<graph-reference[]>',\n 'knowledge-source',\n 'knowledge-source[]',\n 'fn<knowledge-source>',\n 'fn<knowledge-source[]>',\n 'knowledge-document',\n 'knowledge-document[]',\n 'fn<knowledge-document>',\n 'fn<knowledge-document[]>',\n 'knowledge-evidence',\n 'knowledge-evidence[]',\n 'fn<knowledge-evidence>',\n 'fn<knowledge-evidence[]>',\n 'llm-config',\n 'llm-config[]',\n 'fn<llm-config>',\n 'fn<llm-config[]>',\n 'document',\n 'document[]',\n 'fn<document>',\n 'fn<document[]>',\n);\n\nexport const scalarTypes = exhaustiveTuple<ScalarType>()(\n 'any',\n 'boolean',\n 'string',\n 'number',\n 'date',\n 'time',\n 'datetime',\n 'chat-message',\n 'control-flow-excluded',\n 'object',\n 'gpt-function',\n 'vector',\n 'image',\n 'binary',\n 'audio',\n 'graph-reference',\n 'knowledge-source',\n 'knowledge-document',\n 'knowledge-evidence',\n 'llm-config',\n 'document',\n);\n\nexport const dataTypeDisplayNames: Record<DataType, string> = {\n any: 'Any',\n 'any[]': 'Any Array',\n boolean: 'Boolean',\n 'boolean[]': 'Boolean Array',\n string: 'String',\n 'string[]': 'String Array',\n number: 'Number',\n 'number[]': 'Number Array',\n date: 'Date',\n 'date[]': 'Date Array',\n time: 'Time',\n 'time[]': 'Time Array',\n datetime: 'DateTime',\n 'datetime[]': 'DateTime Array',\n 'chat-message': 'ChatMessage',\n 'chat-message[]': 'ChatMessage Array',\n 'control-flow-excluded': 'ControlFlowExcluded',\n 'control-flow-excluded[]': 'ControlFlowExcluded Array',\n object: 'Object',\n 'object[]': 'Object Array',\n 'gpt-function': 'GPT Function',\n 'gpt-function[]': 'GPT Function Array',\n 'fn<string>': 'Function<String>',\n 'fn<number>': 'Function<Number>',\n 'fn<boolean>': 'Function<Boolean>',\n 'fn<date>': 'Function<Date>',\n 'fn<time>': 'Function<Time>',\n 'fn<datetime>': 'Function<DateTime>',\n 'fn<any>': 'Function<Any>',\n 'fn<object>': 'Function<Object>',\n 'fn<chat-message>': 'Function<ChatMessage>',\n 'fn<control-flow-excluded>': 'Function<ControlFlowExcluded>',\n 'fn<gpt-function>': 'Function<GPT Function>',\n 'fn<string[]>': 'Function<String Array>',\n 'fn<number[]>': 'Function<Number Array>',\n 'fn<boolean[]>': 'Function<Boolean Array>',\n 'fn<date[]>': 'Function<Date Array>',\n 'fn<time[]>': 'Function<Time Array>',\n 'fn<datetime[]>': 'Function<DateTime Array>',\n 'fn<any[]>': 'Function<Any Array>',\n 'fn<object[]>': 'Function<Object Array>',\n 'fn<chat-message[]>': 'Function<ChatMessage Array>',\n 'fn<control-flow-excluded[]>': 'Function<ControlFlowExcluded Array>',\n 'fn<gpt-function[]>': 'Function<GPT Function Array>',\n vector: 'Vector',\n 'vector[]': 'Vector Array',\n 'fn<vector>': 'Function<Vector>',\n 'fn<vector[]>': 'Function<Vector Array>',\n image: 'Image',\n 'image[]': 'Image Array',\n 'fn<image>': 'Function<Image>',\n 'fn<image[]>': 'Function<Image Array>',\n binary: 'Binary',\n 'binary[]': 'Binary Array',\n 'fn<binary>': 'Function<Binary>',\n 'fn<binary[]>': 'Function<Binary Array>',\n audio: 'Audio',\n 'audio[]': 'Audio Array',\n 'fn<audio>': 'Function<Audio>',\n 'fn<audio[]>': 'Function<Audio Array>',\n 'graph-reference': 'Graph Reference',\n 'graph-reference[]': 'Graph Reference Array',\n 'fn<graph-reference>': 'Function<Graph Reference>',\n 'fn<graph-reference[]>': 'Function<Graph Reference Array>',\n 'knowledge-source': 'Knowledge Source',\n 'knowledge-source[]': 'Knowledge Source Array',\n 'fn<knowledge-source>': 'Function<Knowledge Source>',\n 'fn<knowledge-source[]>': 'Function<Knowledge Source Array>',\n 'knowledge-document': 'Knowledge Document',\n 'knowledge-document[]': 'Knowledge Document Array',\n 'fn<knowledge-document>': 'Function<Knowledge Document>',\n 'fn<knowledge-document[]>': 'Function<Knowledge Document Array>',\n 'knowledge-evidence': 'Knowledge Evidence',\n 'knowledge-evidence[]': 'Knowledge Evidence Array',\n 'fn<knowledge-evidence>': 'Function<Knowledge Evidence>',\n 'fn<knowledge-evidence[]>': 'Function<Knowledge Evidence Array>',\n 'llm-config': 'LLM Profile',\n 'llm-config[]': 'LLM Profile Array',\n 'fn<llm-config>': 'Function<LLM Profile>',\n 'fn<llm-config[]>': 'Function<LLM Profile Array>',\n document: 'Document',\n 'document[]': 'Document Array',\n 'fn<document>': 'Function<Document>',\n 'fn<document[]>': 'Function<Document Array>',\n};\n\nexport function isScalarDataValue(value: DataValue | undefined): value is ScalarDataValue {\n if (!value) {\n return false;\n }\n\n return !isArrayDataType(value.type) && !isFunctionDataType(value.type);\n}\n\nexport function isScalarDataType(type: DataType): type is ScalarDataType {\n return !isArrayDataType(type) && !isFunctionDataType(type);\n}\n\nexport function isArrayDataValue(value: DataValue | undefined): value is ArrayLikeDataValue {\n if (!value) {\n return false;\n }\n\n return (\n isArrayDataType(value.type) || ((value.type === 'any' || value.type === 'object') && Array.isArray(value.value))\n );\n}\n\nexport function isArrayDataType(type: DataType): type is ArrayDataType {\n return type.endsWith('[]');\n}\n\nexport function isFunctionDataType(type: DataType): type is FunctionDataType {\n return type.startsWith('fn<');\n}\n\nexport function isFunctionDataValue(\n value: DataValue | undefined,\n): value is FunctionDataValues | (AnyDataValue & { value: () => unknown }) {\n if (!value) {\n return false;\n }\n return isFunctionDataType(value.type) || (value.type === 'any' && typeof value.value === 'function');\n}\n\nexport function isNotFunctionDataValue(value: DataValue | undefined): value is ScalarOrArrayDataValue {\n return value !== undefined && !isFunctionDataValue(value);\n}\n\nexport function functionTypeToReturnType(functionType: FunctionDataType): ScalarOrArrayDataType {\n return functionType.slice(3, -1) as ScalarOrArrayDataType;\n}\n\nexport function functionTypeToScalarType(functionType: FunctionDataType): ScalarDataType {\n const returnType = functionTypeToReturnType(functionType);\n return isArrayDataType(returnType) ? arrayTypeToScalarType(returnType) : returnType;\n}\n\nexport function arrayTypeToScalarType(arrayType: ArrayDataType): ScalarDataType {\n return arrayType.slice(0, -2) as ScalarDataType;\n}\n\nexport function getScalarTypeOf(type: DataType): ScalarDataType {\n if (isArrayDataType(type)) {\n return arrayTypeToScalarType(type);\n }\n\n if (isFunctionDataType(type)) {\n return functionTypeToScalarType(type);\n }\n\n return type;\n}\n\n/** Unwraps a potentially function data value to a concrete value. I.e., evaluates on-demand values. */\nexport function unwrapDataValue(value: DataValue): ScalarOrArrayDataValue;\nexport function unwrapDataValue(value: DataValue | undefined): ScalarOrArrayDataValue | undefined {\n if (!value) {\n return undefined;\n }\n\n if (isFunctionDataValue(value)) {\n const evaluated = value.value();\n if (value.type === 'any') {\n return { type: 'any', value: evaluated };\n }\n return { type: functionTypeToReturnType(value.type), value: evaluated } as ScalarOrArrayDataValue;\n }\n\n return value;\n}\n\n/**\n * Turns a { type: 'string[]', value: string[] } into { type: 'string', value: string }[]\n * or a { type: 'object', value: something[] } into { type: 'object', value: something }[]\n * or a { type: 'any', value: something[] } into { type: 'any', value: something }[]\n * or a { type: 'string', value: string } into [{ type: 'string', value: string }]\n */\nexport const arrayizeDataValue = (value: ScalarOrArrayDataValue): ScalarDataValue[] => {\n const isArray =\n value.type.endsWith('[]') || ((value.type === 'any' || value.type === 'object') && Array.isArray(value.value));\n if (!isArray) {\n return [value as ScalarDataValue];\n }\n\n const unwrappedType = value.type.endsWith('[]') ? value.type.slice(0, -2) : value.type;\n\n return (value.value as unknown[]).map((v) => ({ type: unwrappedType as ScalarType, value: v })) as ScalarDataValue[];\n};\n\nexport const scalarDefaults: { [P in ScalarDataType]: Extract<ScalarDataValue, { type: P }>['value'] } = {\n string: '',\n number: 0,\n boolean: false,\n any: undefined,\n 'chat-message': {\n type: 'user',\n message: '',\n isCacheBreakpoint: undefined,\n },\n 'control-flow-excluded': undefined,\n date: new Date().toISOString(),\n time: new Date().toISOString(),\n datetime: new Date().toISOString(),\n object: {},\n 'gpt-function': {\n name: 'unknown',\n description: '',\n parameters: {},\n namespace: undefined,\n strict: false,\n },\n vector: [],\n image: {\n mediaType: 'image/jpeg',\n data: new Uint8Array(),\n },\n binary: new Uint8Array(),\n audio: { data: new Uint8Array() },\n 'graph-reference': { graphId: '' as GraphId, graphName: '' },\n 'knowledge-source': { connectionId: '', sourceId: '' },\n 'knowledge-document': { text: '' },\n 'knowledge-evidence': {\n id: '',\n text: '',\n source: { connectionId: '', sourceId: '' },\n documentId: '',\n },\n 'llm-config': createDefaultLLMProfileValue(),\n document: {\n mediaType: 'text/plain',\n data: new Uint8Array(),\n title: undefined,\n context: undefined,\n enableCitations: false,\n },\n};\n\nexport function getDefaultValue<T extends DataType>(type: T): GetDataValue<T>['value'] {\n if (isArrayDataType(type)) {\n return [] as unknown as GetDataValue<T>['value'];\n }\n\n if (isFunctionDataType(type)) {\n const returnType = functionTypeToReturnType(type);\n return (() => getDefaultValue(returnType)) as unknown as GetDataValue<T>['value'];\n }\n\n return structuredClone(scalarDefaults[getScalarTypeOf(type)]) as unknown as GetDataValue<T>['value'];\n}\n", "import {\n type DataType,\n type DataValue,\n type FunctionDataType,\n type GetDataValue,\n functionTypeToReturnType,\n getScalarTypeOf,\n isArrayDataType,\n isArrayDataValue,\n isFunctionDataType,\n isScalarDataValue,\n unwrapDataValue,\n} from '../model/DataValue.js';\n\nfunction getDeferredValue(value: DataValue, type: FunctionDataType): (() => unknown) | undefined {\n const targetReturnType = functionTypeToReturnType(type);\n\n if (isFunctionDataType(value.type)) {\n const sourceReturnType = functionTypeToReturnType(value.type);\n return targetReturnType === 'any' || sourceReturnType === 'any' || sourceReturnType === targetReturnType\n ? (value.value as () => unknown)\n : undefined;\n }\n\n if (value.type === 'any' && typeof value.value === 'function') {\n return value.value as () => unknown;\n }\n\n if (targetReturnType === 'any' || value.type === 'any' || value.type === targetReturnType) {\n return () => value.value;\n }\n\n return undefined;\n}\n\nexport function expectType<T extends DataType>(value: DataValue | undefined, type: T): GetDataValue<T>['value'] {\n if (isArrayDataType(type) && isArrayDataValue(value) && getScalarTypeOf(type) === getScalarTypeOf(value.type)) {\n return value.value as unknown as GetDataValue<T>['value'];\n }\n\n // Allow a string to be expected for a string[], just return an array of one element\n if (isArrayDataType(type) && isScalarDataValue(value) && getScalarTypeOf(type) === value.type) {\n return [value.value] as GetDataValue<T>['value'];\n }\n\n if (value?.type === type) {\n return value.value as GetDataValue<T>['value'];\n }\n\n if (value && isFunctionDataType(type)) {\n const deferredValue = getDeferredValue(value, type);\n if (deferredValue) {\n return deferredValue as GetDataValue<T>['value'];\n }\n }\n\n if (type === 'any' || type === 'any[]' || value?.type === 'any' || value?.type === 'any[]') {\n return value?.value as GetDataValue<T>['value'];\n }\n\n throw new Error(`Expected value of type ${type} but got ${value?.type}`);\n}\n\nexport function expectTypeOptional<T extends DataType>(\n value: DataValue | undefined,\n type: T,\n): GetDataValue<T>['value'] | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (isArrayDataType(type) && isArrayDataValue(value) && getScalarTypeOf(type) === getScalarTypeOf(value.type)) {\n // @ts-expect-error Generic T is not narrowed to its array subtype within this runtime-guarded branch.\n return value.value as unknown as GetDataValue<T>['value'];\n }\n\n // Allow a string to be expected for a string[], just return an array of one element\n if (isArrayDataType(type) && isScalarDataValue(value) && getScalarTypeOf(type) === value.type) {\n return [value.value] as GetDataValue<T>['value'] | undefined;\n }\n\n if (value.type === type) {\n // @ts-expect-error Generic T is not narrowed by comparing a DataValue's discriminant to T.\n return value.value as GetDataValue<T>['value'];\n }\n\n if (isFunctionDataType(type)) {\n const deferredValue = getDeferredValue(value, type);\n if (deferredValue) {\n // @ts-expect-error Generic T is not narrowed to its function subtype within this runtime-guarded branch.\n return deferredValue as GetDataValue<T>['value'];\n }\n }\n\n // We allow a fn<string> to be expected for a string, so unwrap it on demand\n if (isFunctionDataType(value.type) && value.type === `fn<${type}>`) {\n value = unwrapDataValue(value);\n }\n\n if (value.type !== type) {\n throw new Error(`Expected value of type ${type} but got ${value?.type}`);\n }\n return value.value as GetDataValue<T>['value'] | undefined;\n}\n", "import type {\n GetKnowledgeSourceStatusResult,\n KnowledgeFilter,\n KnowledgeFilterComparisonOperator,\n KnowledgeMetadata,\n KnowledgeMetadataValue,\n RivetKnowledgeDocument,\n RivetKnowledgeEvidence,\n RivetKnowledgeSourceReference,\n SearchKnowledgeSourceResult,\n SyncKnowledgeSourceResult,\n} from './KnowledgeStore.js';\n\nexport function normalizeKnowledgeConnectionId(value: unknown): string {\n const id = typeof value === 'string' ? value.trim() : '';\n if (!id) throw new Error('Knowledge store connection ID cannot be empty.');\n if (id.length > 256) throw new Error('Knowledge store connection ID cannot exceed 256 characters.');\n if (isReservedKnowledgeObjectKey(id)) {\n throw new Error(`Knowledge store connection ID \"${id}\" is reserved.`);\n }\n return id;\n}\n\nexport function isReservedKnowledgeObjectKey(key: string): boolean {\n return key === '__proto__' || key === 'prototype' || key === 'constructor';\n}\n\nexport function normalizeKnowledgeSourceId(value: unknown): string {\n const id = typeof value === 'string' ? value.trim() : '';\n if (!id) throw new Error('Knowledge source ID cannot be empty.');\n if (id.length > 512) throw new Error('Knowledge source ID cannot exceed 512 characters.');\n return id;\n}\n\nexport function normalizeKnowledgeSourceReference(value: unknown): RivetKnowledgeSourceReference {\n if (!isRecord(value)) throw new Error('Knowledge Source must be an object.');\n const connectionId = normalizeKnowledgeConnectionId(value.connectionId);\n const sourceId = normalizeKnowledgeSourceId(value.sourceId);\n const version = normalizeKnowledgeVersion(value.version, 'Knowledge source version');\n return { connectionId, sourceId, ...(version ? { version } : {}) };\n}\n\nexport function normalizeKnowledgeQueries(value: unknown): string[] {\n if (!Array.isArray(value)) throw new Error('Knowledge queries must be an array.');\n const queries: string[] = [];\n const seen = new Set<string>();\n for (const rawQuery of value) {\n if (typeof rawQuery !== 'string') throw new Error('Knowledge queries must contain only strings.');\n const query = rawQuery.trim();\n if (!query || seen.has(query)) continue;\n seen.add(query);\n queries.push(query);\n }\n if (queries.length === 0) throw new Error('Search Knowledge requires at least one non-empty query.');\n return queries;\n}\n\nexport function normalizeKnowledgeMetadata(value: unknown, label = 'Knowledge metadata'): KnowledgeMetadata {\n if (value == null) return {};\n if (!isRecord(value)) throw new Error(`${label} must be a plain object.`);\n\n const normalized: KnowledgeMetadata = {};\n for (const [rawKey, rawValue] of Object.entries(value)) {\n const key = rawKey.trim();\n if (!key) throw new Error(`${label} contains an empty field name.`);\n rejectUnsafeObjectKey(key, label);\n if (Object.prototype.hasOwnProperty.call(normalized, key)) {\n throw new Error(`${label} contains duplicate field \"${key}\" after trimming.`);\n }\n normalized[key] = normalizeKnowledgeMetadataValue(rawValue, `${label}.${key}`);\n }\n return normalized;\n}\n\nexport function normalizeKnowledgeDocument(value: unknown, index?: number): RivetKnowledgeDocument {\n const label = index == null ? 'Knowledge document' : `Knowledge document ${index + 1}`;\n if (typeof value === 'string') {\n const text = normalizeDocumentText(value);\n if (!text) throw new Error(`${label} text cannot be empty.`);\n return { text };\n }\n if (!isRecord(value)) throw new Error(`${label} must be a string or object.`);\n\n const text = normalizeDocumentText(value.text);\n if (!text) throw new Error(`${label} text cannot be empty.`);\n const id = optionalTrimmedString(value.id, `${label} ID`) ?? '';\n const title = optionalTrimmedString(value.title, `${label} title`) ?? '';\n const metadata = value.metadata == null ? undefined : normalizeKnowledgeMetadata(value.metadata, `${label} metadata`);\n return {\n ...(id ? { id } : {}),\n text,\n ...(title ? { title } : {}),\n ...(metadata && Object.keys(metadata).length > 0 ? { metadata } : {}),\n };\n}\n\nexport function normalizeKnowledgeEvidence(value: unknown): RivetKnowledgeEvidence {\n if (!isRecord(value)) throw new Error('Knowledge Evidence must be an object.');\n const id = typeof value.id === 'string' ? value.id.trim() : '';\n const text = normalizeDocumentText(value.text);\n const documentId = typeof value.documentId === 'string' ? value.documentId.trim() : '';\n if (!id || !text || !documentId) {\n throw new Error('Knowledge Evidence requires non-empty id, text, and documentId fields.');\n }\n const score = optionalFiniteNumber(value.relevanceScore, 'Knowledge Evidence relevance score');\n const title = optionalTrimmedString(value.title, 'Knowledge Evidence title') ?? '';\n const chunkIndex = optionalNonNegativeInteger(value.chunkIndex, 'Knowledge Evidence chunk index');\n return {\n id,\n text,\n source: normalizeKnowledgeSourceReference(value.source),\n documentId,\n ...(score == null ? {} : { relevanceScore: score }),\n ...(title ? { title } : {}),\n ...(chunkIndex == null ? {} : { chunkIndex }),\n ...(value.metadata == null ? {} : { metadata: normalizeKnowledgeMetadata(value.metadata) }),\n };\n}\n\nexport function normalizeKnowledgeSourceStatusResult(\n value: unknown,\n expectedSource?: RivetKnowledgeSourceReference,\n expectedVersion?: string,\n): GetKnowledgeSourceStatusResult {\n if (!isRecord(value)) throw new Error('Knowledge source status result must be an object.');\n if (typeof value.exists !== 'boolean') throw new Error('Knowledge source status result requires an Exists boolean.');\n const source = normalizeKnowledgeSourceReference(value.source);\n validateExpectedSourceIdentity(source, expectedSource);\n const activeVersion = normalizeKnowledgeVersion(value.activeVersion, 'Knowledge source active version');\n if (activeVersion && source.version && activeVersion !== source.version) {\n throw new Error('Knowledge source status returned conflicting active versions.');\n }\n const resolvedActiveVersion = value.exists ? activeVersion || source.version : activeVersion;\n if (!value.exists && activeVersion) {\n throw new Error('A missing knowledge source status cannot have an active version.');\n }\n const message = requiredString(value.message, 'Knowledge source status message');\n const documentCount = optionalNonNegativeInteger(value.documentCount, 'Knowledge source document count');\n const chunkCount = optionalNonNegativeInteger(value.chunkCount, 'Knowledge source chunk count');\n const updatedAt = optionalTrimmedString(value.updatedAt, 'Knowledge source update time');\n if (updatedAt && !Number.isFinite(Date.parse(updatedAt))) {\n throw new Error('Knowledge source status returned an invalid update time.');\n }\n if (value.matchesExpectedVersion != null && typeof value.matchesExpectedVersion !== 'boolean') {\n throw new Error('Knowledge source status returned an invalid expected-version match value.');\n }\n const requestedVersion =\n normalizeKnowledgeVersion(expectedVersion, 'Expected knowledge source version') ??\n normalizeKnowledgeVersion(expectedSource?.version, 'Expected knowledge source version');\n const matchesExpectedVersion = requestedVersion\n ? value.exists && resolvedActiveVersion === requestedVersion\n : undefined;\n if (\n matchesExpectedVersion != null &&\n typeof value.matchesExpectedVersion === 'boolean' &&\n value.matchesExpectedVersion !== matchesExpectedVersion\n ) {\n throw new Error('Knowledge source status returned an incorrect expected-version match value.');\n }\n const metadata = value.metadata == null ? undefined : normalizeKnowledgeMetadata(value.metadata, 'Source metadata');\n const normalizedFields = {\n message,\n ...(documentCount == null ? {} : { documentCount }),\n ...(chunkCount == null ? {} : { chunkCount }),\n ...(updatedAt ? { updatedAt } : {}),\n ...(metadata && Object.keys(metadata).length ? { metadata } : {}),\n ...(matchesExpectedVersion != null\n ? { matchesExpectedVersion }\n : typeof value.matchesExpectedVersion === 'boolean'\n ? { matchesExpectedVersion: value.matchesExpectedVersion }\n : {}),\n };\n if (!value.exists) return { ...normalizedFields, exists: false, source };\n if (!resolvedActiveVersion) {\n throw new Error('An existing knowledge source status requires an active version.');\n }\n return {\n ...normalizedFields,\n exists: true,\n source: { ...source, version: resolvedActiveVersion },\n activeVersion: resolvedActiveVersion,\n };\n}\n\nexport function normalizeSyncKnowledgeSourceResult(\n value: unknown,\n expectedSource?: RivetKnowledgeSourceReference,\n): SyncKnowledgeSourceResult {\n if (!isRecord(value)) throw new Error('Knowledge source sync result must be an object.');\n const source = normalizeKnowledgeSourceReference(value.source);\n validateExpectedSourceIdentity(source, expectedSource);\n if (!source.version) throw new Error('Knowledge source sync result requires a committed version.');\n if (value.result !== 'created' && value.result !== 'updated' && value.result !== 'unchanged') {\n throw new Error('Knowledge source sync result has an unsupported result value.');\n }\n const documentCount = requiredPositiveInteger(value.documentCount, 'Knowledge source document count');\n const chunkCount = requiredPositiveInteger(value.chunkCount, 'Knowledge source chunk count');\n const previousVersion = normalizeKnowledgeVersion(value.previousVersion, 'Previous knowledge source version');\n if (!Array.isArray(value.warnings) || !value.warnings.every((warning) => typeof warning === 'string')) {\n throw new Error('Knowledge source sync warnings must be a string array.');\n }\n return {\n source: { ...source, version: source.version },\n result: value.result,\n documentCount,\n chunkCount,\n ...(previousVersion ? { previousVersion } : {}),\n warnings: [...value.warnings],\n };\n}\n\nexport function normalizeSearchKnowledgeSourceResult(\n value: unknown,\n expectedSource?: RivetKnowledgeSourceReference,\n expectedQueries?: readonly string[],\n): SearchKnowledgeSourceResult {\n if (!isRecord(value)) throw new Error('Knowledge search result must be an object.');\n if (typeof value.sourceFound !== 'boolean')\n throw new Error('Knowledge search result requires a Source Found boolean.');\n const source = normalizeKnowledgeSourceReference(value.source);\n validateExpectedSourceIdentity(source, expectedSource);\n if (value.sourceFound && !source.version) {\n throw new Error('A found knowledge source search result requires an active version.');\n }\n if (value.sourceFound && expectedSource?.version && source.version !== expectedSource.version) {\n throw new Error('Knowledge search returned a different version than the exact version requested.');\n }\n if (!Array.isArray(value.evidence)) throw new Error('Knowledge search evidence must be an array.');\n if (!Array.isArray(value.queryResults)) throw new Error('Knowledge query results must be an array.');\n const evidence = value.evidence.map(normalizeKnowledgeEvidence);\n const queryResults = value.queryResults.map((queryResult, index) => {\n if (!isRecord(queryResult)) throw new Error(`Knowledge query result ${index + 1} must be an object.`);\n const query = requiredNonEmptyString(queryResult.query, `Knowledge query result ${index + 1} query`);\n if (!Array.isArray(queryResult.evidence)) {\n throw new Error(`Knowledge query result ${index + 1} evidence must be an array.`);\n }\n return { query, evidence: queryResult.evidence.map(normalizeKnowledgeEvidence) };\n });\n validateUniqueEvidence(evidence, 'Knowledge search evidence');\n for (const [index, queryResult] of queryResults.entries()) {\n validateUniqueEvidence(queryResult.evidence, `Knowledge query result ${index + 1} evidence`);\n }\n const queryEvidenceIds = new Set(queryResults.flatMap((queryResult) => queryResult.evidence.map((item) => item.id)));\n for (const item of evidence) {\n if (!queryEvidenceIds.has(item.id)) {\n throw new Error(`Final knowledge evidence \"${item.id}\" does not occur in any query result.`);\n }\n }\n for (const item of [...evidence, ...queryResults.flatMap((queryResult) => queryResult.evidence)]) {\n if (!sameKnowledgeSource(item.source, source)) {\n throw new Error(`Knowledge evidence \"${item.id}\" does not belong to the returned source.`);\n }\n }\n if (!value.sourceFound && (evidence.length > 0 || queryResults.some((result) => result.evidence.length > 0))) {\n throw new Error('A missing knowledge source search result cannot contain evidence.');\n }\n if (expectedQueries) {\n const normalizedExpectedQueries = normalizeKnowledgeQueries([...expectedQueries]);\n const actualQueries = queryResults.map((result) => result.query);\n const expectedResultQueries = value.sourceFound ? normalizedExpectedQueries : [];\n if (\n actualQueries.length !== expectedResultQueries.length ||\n actualQueries.some((query, index) => query !== expectedResultQueries[index])\n ) {\n throw new Error('Knowledge search returned query groups that do not match the requested queries.');\n }\n }\n return {\n sourceFound: value.sourceFound,\n source,\n evidence,\n queryResults,\n message: requiredString(value.message, 'Knowledge search status message'),\n };\n}\n\nexport function normalizeKnowledgeFilter(value: unknown): KnowledgeFilter {\n if (!isRecord(value)) throw new Error('Knowledge filter must be an object.');\n const branches = [\n Array.isArray(value.and),\n Array.isArray(value.or),\n value.not != null,\n value.field != null || value.operator != null,\n ].filter(Boolean).length;\n if (branches !== 1)\n throw new Error('Knowledge filter objects must contain exactly one comparison, and, or, or not expression.');\n if (Array.isArray(value.and)) {\n if (value.and.length === 0) throw new Error('Knowledge filter \"and\" groups cannot be empty.');\n return { and: value.and.map(normalizeKnowledgeFilter) };\n }\n if (Array.isArray(value.or)) {\n if (value.or.length === 0) throw new Error('Knowledge filter \"or\" groups cannot be empty.');\n return { or: value.or.map(normalizeKnowledgeFilter) };\n }\n if (value.not != null) return { not: normalizeKnowledgeFilter(value.not) };\n\n const field = typeof value.field === 'string' ? value.field.trim() : '';\n const operator = typeof value.operator === 'string' ? value.operator : '';\n const validOperators = ['eq', 'neq', 'in', 'nin', 'gt', 'gte', 'lt', 'lte', 'exists'] as const;\n if (!field || !validOperators.includes(operator as (typeof validOperators)[number])) {\n throw new Error('Knowledge filter comparisons require a field and supported operator.');\n }\n rejectUnsafeObjectKey(field, 'Knowledge filter');\n if (operator === 'exists') {\n return { field, operator };\n }\n const normalizedValue = normalizeKnowledgeMetadataValue(value.value, `Filter ${field}`);\n if ((operator === 'in' || operator === 'nin') && !Array.isArray(normalizedValue)) {\n throw new Error(`Knowledge filter operator \"${operator}\" requires an array value.`);\n }\n if (\n (operator === 'gt' || operator === 'gte' || operator === 'lt' || operator === 'lte') &&\n Array.isArray(normalizedValue)\n ) {\n throw new Error(`Knowledge filter operator \"${operator}\" requires a scalar value.`);\n }\n return {\n field,\n operator: operator as KnowledgeFilterComparisonOperator,\n value: normalizedValue,\n };\n}\n\nexport function isKnowledgeSourceReference(value: unknown): value is RivetKnowledgeSourceReference {\n try {\n normalizeKnowledgeSourceReference(value);\n return true;\n } catch {\n return false;\n }\n}\n\nexport function isKnowledgeDocument(value: unknown): value is RivetKnowledgeDocument {\n try {\n normalizeKnowledgeDocument(value);\n return true;\n } catch {\n return false;\n }\n}\n\nexport function isKnowledgeEvidence(value: unknown): value is RivetKnowledgeEvidence {\n try {\n normalizeKnowledgeEvidence(value);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction normalizeKnowledgeMetadataValue(value: unknown, label: string): KnowledgeMetadataValue {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) throw new Error(`${label} must be a finite number.`);\n return value;\n }\n if (Array.isArray(value)) {\n if (value.every((item) => typeof item === 'string')) return value;\n if (value.every((item) => typeof item === 'boolean')) return value;\n if (value.every((item) => typeof item === 'number' && Number.isFinite(item))) return value as number[];\n throw new Error(`${label} arrays must contain only strings, booleans, or finite numbers of one type.`);\n }\n throw new Error(`${label} must be a portable scalar or a homogeneous scalar array.`);\n}\n\nfunction normalizeDocumentText(value: unknown): string {\n return typeof value === 'string' ? value.replace(/\\r\\n?/g, '\\n').trim() : '';\n}\n\nfunction optionalTrimmedString(value: unknown, label: string): string | undefined {\n if (value == null || value === '') return undefined;\n if (typeof value !== 'string') throw new Error(`${label} must be a string.`);\n const normalized = value.trim();\n return normalized || undefined;\n}\n\nfunction normalizeKnowledgeVersion(value: unknown, label: string): string | undefined {\n const version = optionalTrimmedString(value, label);\n if (version && version.length > 512) throw new Error(`${label} cannot exceed 512 characters.`);\n return version;\n}\n\nfunction optionalFiniteNumber(value: unknown, label: string): number | undefined {\n if (value == null) return undefined;\n if (typeof value !== 'number' || !Number.isFinite(value)) throw new Error(`${label} must be a finite number.`);\n return value;\n}\n\nfunction requiredString(value: unknown, label: string): string {\n if (typeof value !== 'string') throw new Error(`${label} must be a string.`);\n return value;\n}\n\nfunction requiredNonEmptyString(value: unknown, label: string): string {\n const normalized = requiredString(value, label).trim();\n if (!normalized) throw new Error(`${label} cannot be empty.`);\n return normalized;\n}\n\nfunction optionalNonNegativeInteger(value: unknown, label: string): number | undefined {\n if (value == null) return undefined;\n if (!Number.isInteger(value) || (value as number) < 0) throw new Error(`${label} must be a non-negative integer.`);\n return value as number;\n}\n\nfunction requiredPositiveInteger(value: unknown, label: string): number {\n if (!Number.isInteger(value) || (value as number) < 1) throw new Error(`${label} must be a positive integer.`);\n return value as number;\n}\n\nfunction validateUniqueEvidence(evidence: RivetKnowledgeEvidence[], label: string): void {\n const seen = new Set<string>();\n for (const item of evidence) {\n if (seen.has(item.id)) throw new Error(`${label} contains duplicate evidence ID \"${item.id}\".`);\n seen.add(item.id);\n }\n}\n\nfunction sameKnowledgeSource(left: RivetKnowledgeSourceReference, right: RivetKnowledgeSourceReference): boolean {\n return (\n left.connectionId === right.connectionId &&\n left.sourceId === right.sourceId &&\n (left.version ?? '') === (right.version ?? '')\n );\n}\n\nfunction validateExpectedSourceIdentity(\n actual: RivetKnowledgeSourceReference,\n expected: RivetKnowledgeSourceReference | undefined,\n): void {\n if (expected && (actual.connectionId !== expected.connectionId || actual.sourceId !== expected.sourceId)) {\n throw new Error('Knowledge store returned a result for a different source.');\n }\n}\n\nfunction rejectUnsafeObjectKey(key: string, label: string): void {\n if (isReservedKnowledgeObjectKey(key)) {\n throw new Error(`${label} field \"${key}\" is reserved.`);\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n", "export type CustomProviderApi = 'completions' | 'responses';\n\nexport type CustomProviderApiContract = Readonly<{\n api: CustomProviderApi;\n adapter: 'openai-compatible' | 'openai-responses';\n endpointPath: '/chat/completions' | '/responses';\n label: 'Custom Completions' | 'Custom Responses';\n structuredOutput: 'raw-response-format' | 'sdk-output';\n parallelToolCalls: 'enabled-only-raw-field' | 'openai-option';\n}>;\n\nexport const customProviderApiOptions = [\n { value: 'completions', label: 'Completions' },\n { value: 'responses', label: 'Responses' },\n] as const;\n\nconst customProviderApiContracts: Record<CustomProviderApi, CustomProviderApiContract> = {\n completions: {\n api: 'completions',\n adapter: 'openai-compatible',\n endpointPath: '/chat/completions',\n label: 'Custom Completions',\n structuredOutput: 'raw-response-format',\n parallelToolCalls: 'enabled-only-raw-field',\n },\n responses: {\n api: 'responses',\n adapter: 'openai-responses',\n endpointPath: '/responses',\n label: 'Custom Responses',\n structuredOutput: 'sdk-output',\n parallelToolCalls: 'openai-option',\n },\n};\n\n/**\n * Keep legacy nodes on Chat Completions while rejecting corrupt/API-authored\n * values before a provider request is created.\n */\nexport function parseCustomProviderApi(value: unknown): CustomProviderApi {\n switch (value) {\n case undefined:\n case 'completions':\n return 'completions';\n case 'responses':\n return 'responses';\n default:\n throw new Error(`Unsupported Custom provider API: ${String(value)}.`);\n }\n}\n\nexport function getCustomProviderApiContract(value: unknown): CustomProviderApiContract {\n return customProviderApiContracts[parseCustomProviderApi(value)];\n}\n", "import type { ChatV2Provider } from './chatV2Types.js';\n\nexport type ChatV2BuiltInProvider = Exclude<ChatV2Provider, 'custom'>;\n\nexport type ChatV2CredentialNames = {\n programmaticName: string;\n environmentVariableName: string;\n};\n\nexport type ChatV2CredentialNamesByProvider = Partial<Record<ChatV2BuiltInProvider, ChatV2CredentialNames>>;\n\nexport const CHAT_V2_DEFAULT_CREDENTIAL_NAMES = {\n openai: {\n programmaticName: 'openAiApiKey',\n environmentVariableName: 'OPENAI_API_KEY',\n },\n anthropic: {\n programmaticName: 'anthropicApiKey',\n environmentVariableName: 'ANTHROPIC_API_KEY',\n },\n google: {\n programmaticName: 'googleApiKey',\n environmentVariableName: 'GOOGLE_GENERATIVE_AI_API_KEY',\n },\n} as const satisfies Record<ChatV2BuiltInProvider, ChatV2CredentialNames>;\n\nconst programmaticNamePattern = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\nconst environmentVariableNamePattern = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\nexport function isChatV2BuiltInProvider(provider: ChatV2Provider): provider is ChatV2BuiltInProvider {\n return Object.hasOwn(CHAT_V2_DEFAULT_CREDENTIAL_NAMES, provider);\n}\n\nexport function isValidChatV2ProgrammaticCredentialName(name: string): boolean {\n return programmaticNamePattern.test(name);\n}\n\nexport function isValidChatV2EnvironmentCredentialName(name: string): boolean {\n return environmentVariableNamePattern.test(name);\n}\n\nexport function getChatV2DefaultCredentialNames(provider: ChatV2BuiltInProvider): ChatV2CredentialNames {\n return { ...CHAT_V2_DEFAULT_CREDENTIAL_NAMES[provider] };\n}\n\nexport function getChatV2CredentialNamesForDisplay(\n provider: ChatV2BuiltInProvider,\n value: unknown,\n): ChatV2CredentialNames {\n try {\n return normalizeChatV2CredentialNames(provider, value);\n } catch {\n return getChatV2DefaultCredentialNames(provider);\n }\n}\n\nexport function normalizeChatV2CredentialNames(provider: ChatV2BuiltInProvider, value: unknown): ChatV2CredentialNames {\n if (value != null && (typeof value !== 'object' || Array.isArray(value))) {\n throw new Error(`${provider} API key names must be an object.`);\n }\n\n const raw = value as Partial<ChatV2CredentialNames> | undefined;\n if (raw?.programmaticName != null && typeof raw.programmaticName !== 'string') {\n throw new Error(`${provider} programmatic API key name must be a string.`);\n }\n if (raw?.environmentVariableName != null && typeof raw.environmentVariableName !== 'string') {\n throw new Error(`${provider} API key environment variable must be a string.`);\n }\n\n const defaults = CHAT_V2_DEFAULT_CREDENTIAL_NAMES[provider];\n const programmaticName = raw?.programmaticName?.trim() || defaults.programmaticName;\n const environmentVariableName = raw?.environmentVariableName?.trim() || defaults.environmentVariableName;\n\n if (!isValidChatV2ProgrammaticCredentialName(programmaticName)) {\n throw new Error(\n `${provider} programmatic API key name must be a JavaScript-style identifier (letters, digits, _, or $, and not starting with a digit).`,\n );\n }\n if (!isValidChatV2EnvironmentCredentialName(environmentVariableName)) {\n throw new Error(\n `${provider} API key environment variable must contain only letters, digits, and _, and must not start with a digit.`,\n );\n }\n\n return { programmaticName, environmentVariableName };\n}\n\nexport function normalizeChatV2CredentialNamesByProvider(value: unknown): ChatV2CredentialNamesByProvider | undefined {\n if (value == null) return undefined;\n if (typeof value !== 'object' || Array.isArray(value)) {\n throw new Error('Built-in provider API key names must be an object.');\n }\n\n const raw = value as Record<string, unknown>;\n const unsupportedProvider = Object.keys(raw).find(\n (provider) => !Object.hasOwn(CHAT_V2_DEFAULT_CREDENTIAL_NAMES, provider),\n );\n if (unsupportedProvider) {\n throw new Error(`Unsupported provider API key names entry: ${unsupportedProvider}.`);\n }\n\n const normalized: ChatV2CredentialNamesByProvider = {};\n for (const provider of ['openai', 'anthropic', 'google'] as const) {\n if (raw[provider] != null) {\n normalized[provider] = normalizeChatV2CredentialNames(provider, raw[provider]);\n }\n }\n\n return Object.keys(normalized).length === 0 ? undefined : normalized;\n}\n\nexport function isDefaultChatV2CredentialNames(provider: ChatV2BuiltInProvider, names: ChatV2CredentialNames): boolean {\n const defaults = CHAT_V2_DEFAULT_CREDENTIAL_NAMES[provider];\n return (\n names.programmaticName === defaults.programmaticName &&\n names.environmentVariableName === defaults.environmentVariableName\n );\n}\n\nexport function getNonDefaultChatV2CredentialNames(\n provider: ChatV2Provider,\n namesByProvider: ChatV2CredentialNamesByProvider | undefined,\n): ChatV2CredentialNames | undefined {\n if (!isChatV2BuiltInProvider(provider) || namesByProvider?.[provider] == null) return undefined;\n\n try {\n const names = normalizeChatV2CredentialNames(provider, namesByProvider[provider]);\n return isDefaultChatV2CredentialNames(provider, names) ? undefined : names;\n } catch {\n return undefined;\n }\n}\n", "/** Empty historical editor values are unset, never the provider's explicit zero. */\nexport function normalizeTemperature(value: unknown, label = 'Temperature'): number | undefined {\n if (value == null || (typeof value === 'number' && Number.isNaN(value))) return undefined;\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new Error(`${label} must be a finite number when provided.`);\n }\n return value;\n}\n", "import type { ChatV2CredentialReference, ChatV2CredentialResult } from './chatV2ProviderProfile.js';\nimport { createLLMChatV2NodeData, type LLMChatV2NodeData, type LLMChatV2ProfileData } from './llmChatV2NodeData.js';\nimport type { ChatV2Provider } from './chatV2Types.js';\nimport { parseCustomProviderApi } from './customProviderApi.js';\nimport {\n llmProfileBooleanDataKeys,\n llmProfileOptionalNumberDataKeys,\n llmProfileRequiredNumberDataKeys,\n llmProfileResolvedInputToggleDataKeys,\n llmProfileStringDataKeys,\n} from './llmProfileFieldRegistry.js';\nimport { LLM_PROFILE_VALUE_VERSION, pickLLMChatV2ProfileData, type LLMProfileValue } from './llmProfileTypes.js';\nimport { createRivetLLMProfileHealthIdentity } from './llmProfileHealthStore.js';\nimport type { NodeId } from '../NodeBase.js';\nimport type { ProjectId } from '../Project.js';\nimport { normalizeChatV2CredentialNamesByProvider } from './chatV2CredentialNames.js';\nimport { normalizeTemperature } from './temperature.js';\n\nexport {\n applyLLMProfileToNodeData,\n createDefaultLLMProfileValue,\n createLLMProfileNodeData,\n LLM_PROFILE_VALUE_VERSION,\n pickLLMChatV2ProfileData,\n type LLMProfileValue,\n} from './llmProfileTypes.js';\n\nconst credentialSources = new Set<ChatV2CredentialReference['source']>([\n 'input',\n 'settings',\n 'plugin',\n 'programmatic',\n 'environment',\n 'none',\n]);\nconst profileProviders = new Set<ChatV2Provider>(['openai', 'anthropic', 'google', 'custom']);\n\nexport function normalizeLLMProfileValue(value: unknown): LLMProfileValue {\n if (!isRecord(value)) {\n throw new Error('LLM Profile input must contain an LLM profile value.');\n }\n\n if (value.version !== LLM_PROFILE_VALUE_VERSION) {\n throw new Error(`Unsupported LLM Profile version: ${String(value.version)}.`);\n }\n\n if (!isRecord(value.configuration)) {\n throw new Error('LLM Profile configuration is missing.');\n }\n\n const defaults = createLLMChatV2NodeData();\n const provider = normalizeProvider(value.configuration.provider ?? defaults.provider);\n const model = value.configuration.model;\n if (typeof model !== 'string' || !model.trim()) {\n throw new Error('LLM Profile model must be a non-empty string.');\n }\n\n const credential = normalizeCredential(value.credential);\n const configuration = normalizeConfiguration({\n ...defaults,\n ...value.configuration,\n // Defaults seed new nodes, not missing values in an existing profile.\n temperature: normalizeTemperature(value.configuration.temperature, 'LLM Profile temperature'),\n provider,\n model: model.trim(),\n } as LLMChatV2NodeData);\n\n const sourceIdentity = normalizeSourceIdentity(value.healthIdentity);\n const profileName = normalizeProfileName(value.profileName) ?? sourceIdentity.profileName;\n return {\n version: LLM_PROFILE_VALUE_VERSION,\n configuration,\n credential,\n ...(profileName == null ? {} : { profileName }),\n healthIdentity: createRivetLLMProfileHealthIdentity({\n configuration,\n credential,\n ...sourceIdentity,\n ...(profileName == null ? {} : { profileName }),\n }),\n };\n}\n\n/**\n * Normalizes the single LLM Profile or ordered fallback chain accepted by\n * LLM Chat's From profile input. We validate every member here rather than\n * trusting a same-type `llm-config[]` wrapper: arrays can otherwise carry\n * malformed values without re-entering scalar coercion.\n */\nexport function normalizeLLMProfileChainInput(value: unknown): LLMProfileValue[] {\n const rawProfiles = Array.isArray(value) ? value : [value];\n\n if (rawProfiles.length === 0) {\n throw new Error('LLM Profiles input must contain at least one LLM Profile.');\n }\n\n return rawProfiles.map((profile, index) => {\n try {\n return normalizeLLMProfileValue(profile);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`LLM Profiles input item ${index} is invalid: ${message}`);\n }\n });\n}\n\n/**\n * Programmatic or serialized llm-config values may originate outside the\n * currently executing project. Always bind health to that project before\n * shared storage is consulted so copied values cannot share a circuit across\n * projects. Preserve an originating profile-node identity when one exists;\n * otherwise the consuming Chat node owns the identity.\n */\nexport function scopeLLMProfileHealthIdentity(\n profile: LLMProfileValue,\n fallback: {\n projectId: ProjectId;\n profileNodeId: NodeId;\n chatNodeHeaders?: Record<string, string> | undefined;\n },\n): LLMProfileValue {\n const profileNodeId = profile.healthIdentity?.profileNodeId ?? fallback.profileNodeId;\n const profileName =\n normalizeProfileName(profile.profileName) ?? normalizeProfileName(profile.healthIdentity?.profileName);\n const healthIdentity = createRivetLLMProfileHealthIdentity({\n configuration: profile.configuration,\n credential: profile.credential,\n chatNodeHeaders: fallback.chatNodeHeaders,\n projectId: fallback.projectId,\n profileNodeId,\n ...(profileName == null ? {} : { profileName }),\n });\n\n if (\n profile.healthIdentity?.key === healthIdentity.key &&\n profile.profileName === profileName &&\n profile.healthIdentity?.profileName === profileName\n ) {\n return profile;\n }\n\n return {\n ...profile,\n ...(profileName == null ? {} : { profileName }),\n healthIdentity,\n };\n}\n\nfunction normalizeConfiguration(data: LLMChatV2NodeData): LLMChatV2ProfileData {\n for (const field of llmProfileStringDataKeys) {\n if (typeof data[field] !== 'string') {\n throw new Error(`LLM Profile ${field} must be a string.`);\n }\n }\n for (const field of llmProfileBooleanDataKeys) {\n if (typeof data[field] !== 'boolean') {\n throw new Error(`LLM Profile ${field} must be a boolean.`);\n }\n }\n for (const field of llmProfileRequiredNumberDataKeys) {\n if (typeof data[field] !== 'number' || !Number.isFinite(data[field])) {\n throw new Error(`LLM Profile ${field} must be a finite number.`);\n }\n }\n for (const field of llmProfileOptionalNumberDataKeys) {\n const fieldValue = data[field];\n if (fieldValue != null && (typeof fieldValue !== 'number' || !Number.isFinite(fieldValue))) {\n throw new Error(`LLM Profile ${field} must be a finite number when provided.`);\n }\n }\n\n if (!Array.isArray(data.stopSequences) || data.stopSequences.some((sequence) => typeof sequence !== 'string')) {\n throw new Error('LLM Profile stopSequences must be an array of strings.');\n }\n if (\n !Array.isArray(data.headers) ||\n data.headers.some(\n (header) => !isRecord(header) || typeof header.key !== 'string' || typeof header.value !== 'string',\n )\n ) {\n throw new Error('LLM Profile headers must contain string key/value pairs.');\n }\n if (data.apiKeySource !== 'environment' && data.apiKeySource !== 'input') {\n throw new Error(`Unsupported LLM Profile API key source: ${String(data.apiKeySource)}.`);\n }\n assertEnumValue(data.openAIWebSearchContextSize, ['low', 'medium', 'high'], 'OpenAI web search context');\n const customProviderApi = parseCustomProviderApi(data.customProviderApi);\n assertEnumValue(data.anthropicThinkingMode, ['', 'adaptive', 'enabled', 'disabled'], 'Anthropic thinking mode');\n assertEnumValue(data.anthropicEffort, ['', 'low', 'medium', 'high', 'max'], 'Anthropic effort');\n assertEnumValue(data.anthropicCacheControlTtl, ['', '5m', '1h'], 'Anthropic cache TTL');\n assertEnumValue(data.googleThinkingLevel, ['', 'minimal', 'low', 'medium', 'high'], 'Google thinking level');\n\n const resolvedData = {\n ...data,\n customProviderApi,\n providerApiKeyNames: normalizeChatV2CredentialNamesByProvider(data.providerApiKeyNames),\n model: data.model.trim(),\n customProviderBaseURL: data.customProviderBaseURL.trim(),\n customProviderApiKeyProgrammaticName: data.customProviderApiKeyProgrammaticName?.trim(),\n customProviderApiKeyEnvVarName: data.customProviderApiKeyEnvVarName?.trim(),\n stopSequences: [...data.stopSequences],\n headers: data.headers.map(({ key, value }) => ({ key, value })),\n };\n\n // A profile is a resolved configuration value. LLM Chat intentionally does not\n // expose the profile-owned inputs, so accepting a dynamic flag here would let\n // stale hidden connections influence a supposedly self-contained profile.\n for (const field of llmProfileResolvedInputToggleDataKeys) {\n (resolvedData as Record<string, unknown>)[field] = false;\n }\n\n return pickLLMChatV2ProfileData(resolvedData);\n}\n\nfunction assertEnumValue(value: unknown, allowed: readonly string[], label: string): asserts value is string {\n if (typeof value !== 'string' || !allowed.includes(value)) {\n throw new Error(`Unsupported LLM Profile ${label}: ${String(value)}.`);\n }\n}\n\nfunction normalizeProvider(value: unknown): ChatV2Provider {\n if (typeof value !== 'string' || !profileProviders.has(value as ChatV2Provider)) {\n throw new Error(`Unsupported LLM Profile provider: ${String(value)}.`);\n }\n\n return value as ChatV2Provider;\n}\n\nfunction normalizeCredential(value: unknown): ChatV2CredentialResult {\n if (\n !isRecord(value) ||\n !isRecord(value.reference) ||\n typeof value.reference.source !== 'string' ||\n !credentialSources.has(value.reference.source as ChatV2CredentialReference['source'])\n ) {\n throw new Error('LLM Profile credential metadata is invalid.');\n }\n\n const credentialValue = value.value;\n if (credentialValue != null && typeof credentialValue !== 'string') {\n throw new Error('LLM Profile API key must be a string when provided.');\n }\n\n const name = value.reference.name;\n if (name != null && typeof name !== 'string') {\n throw new Error('LLM Profile credential name must be a string when provided.');\n }\n\n return {\n ...(credentialValue == null ? {} : { value: credentialValue }),\n reference: {\n source: value.reference.source as ChatV2CredentialReference['source'],\n ...(name == null ? {} : { name }),\n },\n };\n}\n\nfunction normalizeSourceIdentity(value: unknown): {\n projectId?: ProjectId;\n profileNodeId?: NodeId;\n profileName?: string;\n} {\n if (!isRecord(value)) {\n return {};\n }\n\n const profileName = normalizeProfileName(value.profileName);\n return {\n ...(typeof value.projectId === 'string' ? { projectId: value.projectId as ProjectId } : {}),\n ...(typeof value.profileNodeId === 'string' ? { profileNodeId: value.profileNodeId as NodeId } : {}),\n ...(profileName == null ? {} : { profileName }),\n };\n}\n\nfunction normalizeProfileName(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined;\n const normalized = value.trim();\n return normalized === '' ? undefined : normalized;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value != null && !Array.isArray(value);\n}\n", "import {\n type ChatMessage,\n type DataType,\n type DataValue,\n type GetDataValue,\n type ScalarDataType,\n type ScalarOrArrayDataValue,\n getScalarTypeOf,\n isArrayDataType,\n isArrayDataValue,\n isFunctionDataType,\n isScalarDataType,\n unwrapDataValue,\n} from '../model/DataValue.js';\nimport { expectTypeOptional } from './expectType.js';\nimport type { GraphId } from '../index.js';\nimport {\n normalizeKnowledgeDocument,\n normalizeKnowledgeEvidence,\n normalizeKnowledgeSourceReference,\n} from '../integrations/KnowledgeStoreValidation.js';\nimport { normalizeLLMProfileValue } from '../model/chat-v2/llmProfile.js';\n\ntype ScalarCoercer = (value: ScalarOrArrayDataValue | undefined) => unknown;\n\ntype ScalarCoercionRule = {\n readonly coerce?: ScalarCoercer;\n readonly canAttempt: (from: DataType) => boolean;\n};\n\ntype ScalarCoercionRuleRegistry = {\n readonly [T in ScalarDataType]: ScalarCoercionRule;\n};\n\nfunction isValidatedObjectValueType(type: DataType): boolean {\n return (\n type === 'knowledge-source' ||\n type === 'knowledge-document' ||\n type === 'knowledge-evidence' ||\n type === 'llm-config'\n );\n}\n\nfunction canAttemptGeneralCoercion(from: DataType, to: DataType): boolean {\n return !isValidatedObjectValueType(from) || to === 'object' || to === 'string';\n}\n\nfunction generalScalarRule(target: ScalarDataType, coerce?: ScalarCoercer): ScalarCoercionRule {\n return {\n ...(coerce ? { coerce } : {}),\n canAttempt: (from) => canAttemptGeneralCoercion(from, target),\n };\n}\n\nfunction sameTypeOrObjectScalarRule(target: ScalarDataType, coerce?: ScalarCoercer): ScalarCoercionRule {\n return {\n ...(coerce ? { coerce } : {}),\n canAttempt: (from) => from === target || from === 'object',\n };\n}\n\n/**\n * The single scalar coercion policy used by both runtime conversion and\n * type-level port compatibility. Array, function, and `any` wrappers are\n * handled once around this registry because their behavior is structural.\n */\nconst scalarCoercionRules: ScalarCoercionRuleRegistry = {\n any: {\n canAttempt: () => true,\n },\n boolean: generalScalarRule('boolean', coerceToBoolean),\n string: generalScalarRule('string', coerceToString),\n number: generalScalarRule('number', coerceToNumber),\n date: generalScalarRule('date'),\n time: generalScalarRule('time'),\n datetime: generalScalarRule('datetime'),\n 'chat-message': generalScalarRule('chat-message', coerceToChatMessage),\n 'control-flow-excluded': generalScalarRule('control-flow-excluded'),\n object: generalScalarRule('object', coerceToObject),\n 'gpt-function': {\n canAttempt: (from) => from === 'object',\n },\n vector: generalScalarRule('vector'),\n image: sameTypeOrObjectScalarRule('image'),\n binary: sameTypeOrObjectScalarRule('binary', coerceToBinary),\n audio: sameTypeOrObjectScalarRule('audio'),\n 'graph-reference': generalScalarRule('graph-reference', coerceToGraphReference),\n 'knowledge-source': sameTypeOrObjectScalarRule('knowledge-source', (value) =>\n coerceValidatedObjectValue(value, normalizeKnowledgeSourceReference),\n ),\n 'knowledge-document': sameTypeOrObjectScalarRule('knowledge-document', (value) =>\n coerceValidatedObjectValue(value, normalizeKnowledgeDocument),\n ),\n 'knowledge-evidence': sameTypeOrObjectScalarRule('knowledge-evidence', (value) =>\n coerceValidatedObjectValue(value, normalizeKnowledgeEvidence),\n ),\n 'llm-config': sameTypeOrObjectScalarRule('llm-config', (value) =>\n coerceValidatedObjectValue(value, normalizeLLMProfileValue),\n ),\n document: generalScalarRule('document'),\n};\n\nexport function coerceTypeOptional<T extends DataType>(\n wrapped: DataValue | undefined,\n type: T,\n): GetDataValue<T>['value'] | undefined {\n if (wrapped && isFunctionDataType(type)) {\n return expectTypeOptional(wrapped, type) as GetDataValue<T>['value'] | undefined;\n }\n\n const value = wrapped ? unwrapDataValue(wrapped) : undefined;\n\n // Coerce 'true' to [true] for example\n if (isArrayDataType(type) && !isArrayDataValue(value)) {\n const coerced = coerceTypeOptional(value, getScalarTypeOf(type));\n if (coerced === undefined) {\n return undefined;\n }\n\n const coercedArray = [coerced] as unknown;\n // @ts-expect-error Generic T is not narrowed to its array subtype within this runtime-guarded branch.\n return coercedArray as GetDataValue<T>['value'];\n }\n\n // Preserve arrays whose runtime shape is carried by an any/object wrapper,\n // or coerce each item when the scalar families differ.\n if (isArrayDataType(type) && isArrayDataValue(value)) {\n if (getScalarTypeOf(type) === getScalarTypeOf(value.type)) {\n // @ts-expect-error Generic T is not narrowed to its array subtype within this runtime-guarded branch.\n return value.value as unknown as GetDataValue<T>['value'];\n }\n\n const coercedArray = value.value.map((v) =>\n coerceTypeOptional({ type: getScalarTypeOf(value.type), value: v } as DataValue, getScalarTypeOf(type)),\n ) as unknown;\n\n // @ts-expect-error Generic T is not narrowed to its array subtype within this runtime-guarded branch.\n return coercedArray as GetDataValue<T>['value'];\n }\n\n const scalarRule = isScalarDataType(type) ? scalarCoercionRules[type] : undefined;\n const result = scalarRule?.coerce ? scalarRule.coerce(value) : coerceWithoutSpecializedRule(value, type);\n\n return result as GetDataValue<T>['value'] | undefined;\n}\n\nfunction coerceWithoutSpecializedRule(value: ScalarOrArrayDataValue | undefined, type: DataType): unknown {\n if (!value) {\n return value;\n }\n\n if (getScalarTypeOf(value.type) === 'any' || getScalarTypeOf(type) === 'any') {\n return value.value;\n }\n\n return expectTypeOptional(value, type);\n}\n\nexport function coerceType<T extends DataType>(value: DataValue | undefined, type: T): GetDataValue<T>['value'] {\n const result = coerceTypeOptional(value, type);\n if (result === undefined) {\n throw new Error(`Expected value of type ${type} but got undefined`);\n }\n return result as GetDataValue<T>['value'];\n}\n\nexport function inferType(value: unknown): DataValue {\n if (value === undefined) {\n return { type: 'any', value: undefined };\n }\n\n if (value === null) {\n return { type: 'any', value: null };\n }\n\n if (typeof value === 'function') {\n return { type: 'fn<any>', value: value as () => unknown };\n }\n\n if (typeof value === 'string') {\n return { type: 'string', value };\n }\n\n if (typeof value === 'boolean') {\n return { type: 'boolean', value };\n }\n\n if (typeof value === 'number') {\n return { type: 'number', value };\n }\n\n if (value instanceof Date) {\n return { type: 'datetime', value: value.toISOString() };\n }\n\n if (Array.isArray(value)) {\n if (value.length === 0) {\n return { type: 'any[]', value: [] };\n }\n\n const inferredType = inferType(value[0]);\n\n return { type: inferredType.type + '[]', value } as DataValue;\n }\n\n if (typeof value === 'object') {\n return { type: 'object', value: value as Record<string, unknown> };\n }\n\n throw new Error(`Cannot infer type of value: ${value}`);\n}\n\nfunction coerceToString(value: DataValue | undefined): string | undefined {\n if (!value) {\n return '';\n }\n\n if (isArrayDataValue(value)) {\n return value.value\n .map((v) => coerceTypeOptional({ type: getScalarTypeOf(value.type), value: v } as DataValue, 'string'))\n .join('\\n');\n }\n\n if (value.type === 'string') {\n return value.value;\n }\n\n if (value.type === 'boolean') {\n return value.value.toString();\n }\n\n if (value.type === 'number') {\n return value.value.toString();\n }\n\n if (value.type === 'date') {\n return value.value;\n }\n\n if (value.type === 'time') {\n return value.value;\n }\n\n if (value.type === 'datetime') {\n return value.value;\n }\n\n if (value.type === 'chat-message') {\n const messageParts = Array.isArray(value.value.message) ? value.value.message : [value.value.message];\n const singleString = messageParts\n .map((part) => {\n if (typeof part === 'string') {\n return part;\n }\n\n return part.type === 'url' ? `(Image: ${part.url})` : '(Image)';\n })\n .join('\\n\\n');\n return singleString;\n }\n\n if (value.value === undefined) {\n return undefined;\n }\n\n if (value.value === null) {\n return undefined;\n }\n\n if (typeof value.value === 'object' && !Array.isArray(value.value)) {\n return JSON.stringify(value.value);\n }\n\n // Don't know, so try to infer it from the type of the value\n // Any and object are basically the same...\n if (value.type === 'any' || value.type === 'object') {\n const inferred = inferType(value.value);\n return coerceTypeOptional(inferred, 'string');\n }\n\n return JSON.stringify(value.value);\n}\n\nfunction coerceToChatMessage(value: DataValue | undefined): ChatMessage | undefined {\n const chatMessage = coerceToChatMessageRaw(value);\n\n if (chatMessage?.type === 'assistant') {\n // Double check that arguments is a string, stringify if needed\n if (chatMessage.function_call?.arguments && typeof chatMessage.function_call.arguments !== 'string') {\n chatMessage.function_call.arguments = JSON.stringify(chatMessage.function_call.arguments);\n }\n }\n\n return chatMessage;\n}\n\nfunction coerceToChatMessageRaw(value: DataValue | undefined): ChatMessage | undefined {\n if (!value || value.value == null) {\n return undefined;\n }\n\n if (value.type === 'chat-message') {\n return value.value;\n }\n\n if (value.type === 'string') {\n return { type: 'user', message: value.value };\n }\n\n if (\n value.type === 'object' &&\n 'type' in value.value &&\n 'message' in value.value &&\n typeof value.value.type === 'string' &&\n typeof value.value.message === 'string'\n ) {\n return value.value as ChatMessage;\n }\n\n if (value.type === 'any') {\n const inferred = inferType(value.value);\n return coerceTypeOptional(inferred, 'chat-message');\n }\n}\n\nfunction coerceToBoolean(value: DataValue | undefined) {\n if (!value || !value.value) {\n return false;\n }\n\n if (isArrayDataValue(value)) {\n return value.value\n .map((v) => coerceTypeOptional({ type: value.type.replace('[]', ''), value: v } as DataValue, 'boolean'))\n .every((v) => v);\n }\n\n if (value.type === 'string') {\n return value.value.length > 0 && value.value !== 'false';\n }\n\n if (value.type === 'boolean') {\n return value.value;\n }\n\n if (value.type === 'number') {\n return value.value !== 0;\n }\n\n if (value.type === 'date') {\n return true;\n }\n\n if (value.type === 'time') {\n return true;\n }\n\n if (value.type === 'datetime') {\n return true;\n }\n\n if (value.type === 'chat-message') {\n const hasValue =\n (Array.isArray(value.value.message) && value.value.message.length > 0) ||\n (typeof value.value.message === 'string' && value.value.message.length > 0) ||\n (typeof value.value.message === 'object' &&\n 'type' in value.value.message &&\n value.value.message.type === 'url' &&\n value.value.message.url.length > 0);\n\n return hasValue;\n }\n\n return !!value.value;\n}\n\nfunction coerceToNumber(value: DataValue | undefined): number | undefined {\n if (!value || value.value == null) {\n return undefined;\n }\n\n if (isArrayDataValue(value)) {\n return undefined;\n }\n\n if (value.type === 'string') {\n return parseFloat(value.value);\n }\n\n if (value.type === 'boolean') {\n return value.value ? 1 : 0;\n }\n\n if (value.type === 'number') {\n return value.value;\n }\n\n if (value.type === 'date') {\n return new Date(value.value).valueOf();\n }\n\n if (value.type === 'time') {\n return new Date(value.value).valueOf();\n }\n\n if (value.type === 'datetime') {\n return new Date(value.value).valueOf();\n }\n\n if (value.type === 'chat-message') {\n if (typeof value.value.message === 'string') {\n return parseFloat(value.value.message);\n }\n\n if (\n Array.isArray(value.value.message) &&\n value.value.message.length === 1 &&\n typeof value.value.message[0] === 'string'\n ) {\n return parseFloat(value.value.message[0]);\n }\n\n return undefined;\n }\n\n if (value.type === 'any' || value.type === 'object') {\n const inferred = inferType(value.value);\n if (inferred.type === 'any' || inferred.type === 'object') {\n return undefined;\n }\n return coerceTypeOptional(inferred, 'number');\n }\n\n return undefined;\n}\n\nfunction coerceToObject(value: DataValue | undefined): object | undefined {\n if (!value || value.value == null) {\n return undefined;\n }\n\n return value.value; // Whatever, consider anything an object\n}\n\nfunction coerceToBinary(value: DataValue | undefined): Uint8Array | undefined {\n if (!value || value.value == null) {\n return undefined;\n }\n\n if (value.type === 'binary') {\n return value.value;\n }\n\n if (value.type === 'string') {\n return new TextEncoder().encode(value.value);\n }\n\n if (value.type === 'boolean') {\n return new TextEncoder().encode(value.value.toString());\n }\n\n if (value.type === 'vector' || value.type === 'number[]') {\n return new Uint8Array(value.value);\n }\n\n if (value.type === 'number') {\n return new Uint8Array([value.value]);\n }\n\n if (value.type === 'audio' || value.type === 'image' || value.type === 'document') {\n return value.value.data;\n }\n\n return new TextEncoder().encode(JSON.stringify(value.value));\n}\n\nfunction coerceToGraphReference(value: DataValue | undefined): { graphName: string; graphId: GraphId } | undefined {\n if (!value || value.value == null) {\n return undefined;\n }\n\n if (value.type === 'graph-reference') {\n return value.value;\n }\n\n if (value.type === 'string') {\n return { graphName: value.value, graphId: '' as GraphId };\n }\n\n if (value.type === 'object' && 'graphName' in value.value && 'graphId' in value.value) {\n return value.value as { graphName: string; graphId: GraphId };\n }\n\n return undefined;\n}\n\nfunction coerceValidatedObjectValue<T>(value: DataValue | undefined, normalize: (value: unknown) => T): T | undefined {\n if (!value || value.value == null || isArrayDataValue(value)) return undefined;\n try {\n return normalize(value.value);\n } catch {\n return undefined;\n }\n}\n\nexport function canBeCoercedAny(from: DataType | Readonly<DataType[]>, to: DataType | Readonly<DataType[]>) {\n for (const fromType of Array.isArray(from) ? from : [from]) {\n for (const toType of Array.isArray(to) ? to : [to]) {\n if (canBeCoerced(fromType, toType)) {\n return true;\n }\n }\n }\n return false;\n}\n\nexport function canBeCoerced(from: DataType, to: DataType) {\n if (to === 'any') {\n return scalarCoercionRules.any.canAttempt(from);\n }\n\n if (from === 'any') {\n return true;\n }\n\n if (isArrayDataType(to) && isArrayDataType(from)) {\n return canBeCoerced(getScalarTypeOf(from), getScalarTypeOf(to));\n }\n\n if (isArrayDataType(to) && !isArrayDataType(from)) {\n return canBeCoerced(from, getScalarTypeOf(to));\n }\n\n if (isArrayDataType(from) && !isArrayDataType(to)) {\n return to === 'string' || to === 'object';\n }\n\n if (isScalarDataType(to)) {\n return scalarCoercionRules[to].canAttempt(from);\n }\n\n return canAttemptGeneralCoercion(from, to);\n}\n", "import { JSONPath } from 'jsonpath-plus';\nimport { isInterpolationRegexLiteralStart, isInterpolationSyntaxCharacterEscaped } from './interpolationSyntax.js';\n\nfunction getNextNonWhitespaceCharacter(value: string, index: number): string | undefined {\n for (let cursor = index; cursor < value.length; cursor++) {\n if (!/\\s/.test(value[cursor]!)) {\n return value[cursor];\n }\n }\n\n return undefined;\n}\n\nfunction getWhitespaceRunEnd(value: string, index: number): number {\n let cursor = index;\n while (cursor < value.length && /\\s/.test(value[cursor]!)) {\n cursor += 1;\n }\n return cursor;\n}\n\n/**\n * Normalizes Rivet's historically accepted convenience whitespace around\n * JSONPath structural separators. Quoted values, regular expressions, filter\n * expressions, and object literals keep their authored contents unchanged.\n *\n * All runtime JSONPath consumers must pass through this helper so stored node\n * paths and interpolation suffixes accept the same path language.\n */\nexport function normalizeJsonPathExpression(path: string): string {\n const trimmedPath = path.trim();\n if (!/\\s/.test(trimmedPath)) {\n return trimmedPath;\n }\n\n const result: string[] = [];\n let lastResultCharacter: string | undefined;\n let quote: '\"' | \"'\" | '`' | undefined;\n let regex = false;\n let regexCharacterClass = false;\n const filterBrackets: boolean[] = [];\n let filterDepth = 0;\n\n const append = (value: string): void => {\n if (value === '') {\n return;\n }\n\n result.push(value);\n lastResultCharacter = value.at(-1);\n };\n\n for (let cursor = 0; cursor < trimmedPath.length; cursor++) {\n const character = trimmedPath[cursor]!;\n\n if (regex) {\n if (character === '[' && !isInterpolationSyntaxCharacterEscaped(trimmedPath, cursor)) {\n regexCharacterClass = true;\n } else if (character === ']' && !isInterpolationSyntaxCharacterEscaped(trimmedPath, cursor)) {\n regexCharacterClass = false;\n } else if (\n character === '/' &&\n !regexCharacterClass &&\n !isInterpolationSyntaxCharacterEscaped(trimmedPath, cursor)\n ) {\n regex = false;\n }\n append(character);\n continue;\n }\n\n if (quote) {\n if (character === quote && !isInterpolationSyntaxCharacterEscaped(trimmedPath, cursor)) {\n quote = undefined;\n }\n append(character);\n continue;\n }\n\n if (character === '\"' || character === \"'\" || character === '`') {\n quote = character;\n append(character);\n continue;\n }\n\n if (character === '/' && isInterpolationRegexLiteralStart(trimmedPath, cursor)) {\n regex = true;\n regexCharacterClass = false;\n append(character);\n continue;\n }\n\n const insideFilter = filterDepth > 0;\n\n if (/\\s/.test(character)) {\n const whitespaceEnd = getWhitespaceRunEnd(trimmedPath, cursor);\n const previousCharacter = lastResultCharacter;\n const nextCharacter = trimmedPath[whitespaceEnd];\n // jsonpath-plus rejects whitespace immediately inside either bracket.\n // Preserve other filter whitespace because it may separate JavaScript\n // tokens or be meaningful inside filter expressions.\n const shouldRemoveWhitespace =\n previousCharacter === '[' ||\n nextCharacter === ']' ||\n nextCharacter === '[' ||\n (!insideFilter && (previousCharacter === '.' || previousCharacter === ']' || nextCharacter === '.'));\n\n if (!shouldRemoveWhitespace) {\n append(trimmedPath.slice(cursor, whitespaceEnd));\n }\n cursor = whitespaceEnd - 1;\n continue;\n }\n\n if (character === '[') {\n const opensFilter = getNextNonWhitespaceCharacter(trimmedPath, cursor + 1) === '?';\n filterBrackets.push(opensFilter);\n if (opensFilter) {\n filterDepth += 1;\n }\n append(character);\n continue;\n }\n\n if (character === ']') {\n if (filterBrackets.pop()) {\n filterDepth -= 1;\n }\n append(character);\n continue;\n }\n\n append(character);\n }\n\n return result.join('').trim();\n}\n\n/**\n * Evaluates a JSONPath expression with the same engine and options used by the\n * object-path nodes. Callers retain ownership of their no-match and error\n * policy; this helper deliberately lets JSONPath errors propagate.\n */\nexport function evaluateJsonPath<T = unknown>(value: unknown, path: string, wrap = false): T | T[] | undefined {\n return JSONPath<T>({\n json: value ?? null,\n path: normalizeJsonPathExpression(path),\n wrap,\n });\n}\n", "export type InterpolationTokenSpan = {\n start: number;\n end: number;\n rawInner: string;\n};\n\nconst REGEX_LITERAL_PREFIX_CHARACTERS = new Set([\n '(',\n '[',\n '{',\n ':',\n ';',\n ',',\n '=',\n '!',\n '~',\n '?',\n '&',\n '|',\n '+',\n '-',\n '*',\n '%',\n '^',\n '<',\n '>',\n]);\n\nexport function isInterpolationSyntaxCharacterEscaped(value: string, index: number): boolean {\n let backslashCount = 0;\n\n for (let cursor = index - 1; cursor >= 0 && value[cursor] === '\\\\'; cursor -= 1) {\n backslashCount += 1;\n }\n\n return backslashCount % 2 === 1;\n}\n\n/**\n * JSONPath filters can contain JavaScript regex literals. Treat their contents\n * as opaque while looking for an interpolation terminator or processor pipe;\n * otherwise a `]` or `|` inside the regex can be mistaken for JSONPath syntax.\n */\nexport function isInterpolationRegexLiteralStart(value: string, index: number): boolean {\n if (value[index] !== '/') {\n return false;\n }\n\n let previousIndex = index - 1;\n while (previousIndex >= 0 && /\\s/.test(value[previousIndex]!)) {\n previousIndex -= 1;\n }\n\n return previousIndex < 0 || REGEX_LITERAL_PREFIX_CHARACTERS.has(value[previousIndex]!);\n}\n\nfunction getEscapedTripleTokenEnd(template: string, start: number, check?: () => void): number | undefined {\n for (let cursor = start + 3; cursor < template.length - 2; cursor += 1) {\n if ((cursor & 4095) === 0) check?.();\n if (template[cursor] === '}' && template[cursor + 1] === '}' && template[cursor + 2] === '}') {\n return cursor + 3;\n }\n }\n\n return undefined;\n}\n\ntype TokenScanResult = { kind: 'closed'; end: number } | { kind: 'nested'; start: number } | { kind: 'unclosed' };\n\n/** Finds a matching `}}` while allowing JSONPath filters, quotes, and braces. */\nfunction scanInterpolationToken(template: string, start: number, check?: () => void): TokenScanResult {\n let quote: '\"' | \"'\" | '`' | undefined;\n let regex = false;\n let regexCharacterClass = false;\n let bracketDepth = 0;\n let parenthesisDepth = 0;\n let braceDepth = 0;\n\n for (let cursor = start + 2; cursor < template.length; cursor += 1) {\n if ((cursor & 4095) === 0) check?.();\n const character = template[cursor]!;\n\n if (regex) {\n if (character === '[' && !isInterpolationSyntaxCharacterEscaped(template, cursor)) {\n regexCharacterClass = true;\n } else if (character === ']' && !isInterpolationSyntaxCharacterEscaped(template, cursor)) {\n regexCharacterClass = false;\n } else if (\n character === '/' &&\n !regexCharacterClass &&\n !isInterpolationSyntaxCharacterEscaped(template, cursor)\n ) {\n regex = false;\n }\n continue;\n }\n\n if (quote) {\n if (character === quote && !isInterpolationSyntaxCharacterEscaped(template, cursor)) {\n quote = undefined;\n }\n continue;\n }\n\n if (character === '/' && isInterpolationRegexLiteralStart(template, cursor)) {\n regex = true;\n regexCharacterClass = false;\n continue;\n }\n\n if (character === '\"' || character === \"'\" || character === '`') {\n quote = character;\n continue;\n }\n\n // A second opener always starts recovery outside quoted or regex syntax.\n // JSONPath object literals use single `{` characters; a literal `{{` is\n // not valid JSONPath syntax and should not swallow a later valid token.\n if (character === '{' && template[cursor + 1] === '{') {\n return { kind: 'nested', start: cursor };\n }\n\n if (character === '[') {\n bracketDepth += 1;\n continue;\n }\n\n if (character === ']' && bracketDepth > 0) {\n bracketDepth -= 1;\n continue;\n }\n\n if (character === '(') {\n parenthesisDepth += 1;\n continue;\n }\n\n if (character === ')' && parenthesisDepth > 0) {\n parenthesisDepth -= 1;\n continue;\n }\n\n if (character === '{') {\n braceDepth += 1;\n continue;\n }\n\n if (character === '}') {\n if (braceDepth > 0) {\n braceDepth -= 1;\n continue;\n }\n\n if (template[cursor + 1] === '}' && bracketDepth === 0 && parenthesisDepth === 0) {\n return { kind: 'closed', end: cursor + 2 };\n }\n }\n }\n\n return { kind: 'unclosed' };\n}\n\n/**\n * Scans token boundaries without parsing expressions or resolving values.\n *\n * This deliberately has no evaluator dependencies, so editor-only surfaces\n * can share Core's malformed-token recovery rules without loading JSONPath or\n * the rest of the execution runtime. The returned spans are fresh data and\n * exclude escaped triple-brace tokens.\n */\nexport function scanInterpolationTokenSpans(\n template: string,\n check?: () => void,\n tokenLimit = Infinity,\n): InterpolationTokenSpan[] {\n const spans: InterpolationTokenSpan[] = [];\n let searchIndex = 0;\n\n while (searchIndex < template.length) {\n check?.();\n const start = template.indexOf('{{', searchIndex);\n\n if (start === -1) {\n break;\n }\n\n if (template[start + 2] === '{') {\n const escapedEnd = getEscapedTripleTokenEnd(template, start, check);\n if (escapedEnd !== undefined) {\n searchIndex = escapedEnd;\n continue;\n }\n }\n\n const scanResult = scanInterpolationToken(template, start, check);\n\n if (scanResult.kind === 'nested') {\n searchIndex = scanResult.start;\n continue;\n }\n\n if (scanResult.kind === 'unclosed') {\n // A malformed outer token can leave the scanner inside an unterminated\n // quote or filter. Resume at a later opener so a valid following token\n // is still discovered. Properly closed outer tokens return above, so\n // valid quoted `{{` content remains part of that outer token.\n const nextStart = template.indexOf('{{', start + 2);\n if (nextStart === -1) {\n break;\n }\n searchIndex = nextStart;\n continue;\n }\n\n if (spans.length >= tokenLimit) throw new Error('Interpolation template has too many tokens.');\n spans.push({\n start,\n end: scanResult.end,\n rawInner: template.slice(start + 2, scanResult.end - 2),\n });\n searchIndex = scanResult.end;\n }\n\n return spans;\n}\n", "export { dedent } from 'ts-dedent';\n", "import { dataTypes, type DataValue } from '../model/DataValue.js';\nimport { coerceTypeOptional } from './coerceType.js';\nimport { evaluateJsonPath, normalizeJsonPathExpression } from './jsonPath.js';\nimport { dedent } from './misc.js';\nimport {\n isInterpolationRegexLiteralStart,\n isInterpolationSyntaxCharacterEscaped,\n scanInterpolationTokenSpans,\n type InterpolationTokenSpan,\n} from './interpolationSyntax.js';\n\nexport const ESCAPED_TOKEN_REGEX = /\\{\\{\\{([^}]+?)\\}\\}\\}/g;\nexport const ESCAPED_ESCAPED_TOKEN_REGEX = /\\\\\\{\\\\\\{([^}]+?)\\\\\\}\\\\\\}/g;\n\nconst INTERPOLATION_TEMPLATE_CACHE_MAX_ENTRIES = 2048;\nconst INTERPOLATION_TEMPLATE_CACHE_MAX_TEMPLATE_LENGTH = 64 * 1024;\nconst INTERPOLATION_TEMPLATE_CACHE_MAX_TEMPLATE_CHARS = 1024 * 1024;\nconst INTERPOLATION_TEMPLATE_CACHE_MAX_STORAGE_CHARS = 2 * 1024 * 1024;\n// JavaScript list callbacks can resolve the same expression for every item.\n// Keep this syntax-only cache deliberately smaller than the template cache:\n// values, contexts, and DataValues must never be retained here.\nconst INTERPOLATION_EXPRESSION_CACHE_MAX_ENTRIES = 512;\nconst INTERPOLATION_EXPRESSION_CACHE_MAX_EXPRESSION_LENGTH = 4 * 1024;\nconst INTERPOLATION_EXPRESSION_CACHE_MAX_CHARS = 128 * 1024;\nexport type { InterpolationTokenSpan } from './interpolationSyntax.js';\n\nexport type InterpolationReferenceSource = 'variable' | 'graphInputs' | 'context' | 'globals';\n\n/** A base value and, optionally, a JSONPath evaluated against that value. */\nexport type ParsedInterpolationExpression = {\n source: InterpolationReferenceSource;\n baseName: string;\n /** A JSONPath beginning with `$`, evaluated with `wrap: false`. */\n jsonPath: string | undefined;\n};\n\nexport type ParsedInterpolationToken = {\n span: InterpolationTokenSpan;\n rawInner: string;\n /** The interpolation expression before its optional processor chain. */\n tokenName: string | undefined;\n processingChain: string | undefined;\n reference: ParsedInterpolationExpression | undefined;\n};\n\nexport type ParsedInterpolationTemplate = {\n template: string;\n tokens: readonly ParsedInterpolationToken[];\n};\n\nexport type InterpolationVariableReference = {\n baseName: string;\n /** True when any occurrence of this input navigates into its value with JSONPath. */\n hasPath: boolean;\n};\n\nexport type InterpolationTokenReplacementInfo = {\n rawInner: string;\n span: InterpolationTokenSpan;\n tokenName: string | undefined;\n processingChain: string | undefined;\n reference: ParsedInterpolationExpression | undefined;\n};\n\nexport type ReplaceInterpolationTokensOptions = {\n trim?: boolean;\n guard?: InterpolationGuard;\n};\n\n/** Optional caller-owned preparation limits; ordinary interpolation is unchanged. */\nexport type InterpolationGuard = {\n tokenLimit: number;\n check: () => void;\n prepareValue: (value: unknown) => unknown;\n output: (fragment: string, previousLength: number) => void;\n processing: (input: string, name: string, parameter: number | undefined) => void;\n};\n\nexport type InterpolateOptions = {\n guard?: InterpolationGuard;\n /** A snapshot of the globals referenced by this template. */\n globalValues?: Record<string, unknown>;\n /** Set false when ordinary interpolation variables are raw JSON. */\n unwrapVariableDataValues?: boolean;\n /**\n * Use the historical text-template DataValue coercion for bare ordinary\n * variables. Paths still select raw JSON and use JSON serialization.\n */\n coerceBareVariableDataValues?: boolean;\n};\n\nexport type InterpolationValueSources = {\n guard?: InterpolationGuard;\n variables?: Record<string, unknown>;\n graphInputValues?: Record<string, unknown>;\n contextValues?: Record<string, unknown>;\n globalValues?: Record<string, unknown>;\n /** Set false when `variables` are already raw JSON rather than DataValues. */\n unwrapVariableDataValues?: boolean;\n};\n\ntype CachedInterpolationTemplate = {\n templateChars: number;\n storageChars: number;\n parsed: ParsedInterpolationTemplate;\n};\n\nconst interpolationTemplateCache = new Map<string, CachedInterpolationTemplate>();\nlet cachedInterpolationTemplateChars = 0;\nlet cachedInterpolationTemplateStorageChars = 0;\nlet lastUncachedInterpolationTemplate: string | undefined;\nconst interpolationExpressionCache = new Map<string, ParsedInterpolationExpression | undefined>();\nlet cachedInterpolationExpressionChars = 0;\nconst dataValueTypeSet = new Set<string>(dataTypes);\n\ntype ProcessingFunction = (input: string, param?: number) => string;\n\nconst processingFunctions: Record<string, ProcessingFunction> = {\n indent: (input: string, spaces: number = 0) => {\n const indent = ' '.repeat(spaces);\n return input\n .split('\\n')\n .map((line) => `${indent}${line}`)\n .join('\\n');\n },\n\n quote: (input: string, level: number = 1) => {\n const quotePrefix = '> '.repeat(level);\n return input\n .split('\\n')\n .map((line) => `${quotePrefix}${line}`)\n .join('\\n');\n },\n\n uppercase: (input: string) => input.toUpperCase(),\n lowercase: (input: string) => input.toLowerCase(),\n trim: (input: string) => input.trim(),\n\n truncate: (input: string, length: number = 50) => {\n if (input.length <= length) return input;\n return input.slice(0, length) + '...';\n },\n\n list: (input: string, level: number = 1) => {\n const indent = ' '.repeat(level - 1);\n return input\n .split('\\n')\n .map((line) => `${indent}- ${line}`)\n .join('\\n');\n },\n\n sort: (input: string) => input.split('\\n').sort().join('\\n'),\n dedent: (input: string) => dedent(input),\n\n wrap: (input: string, width: number = 80) => {\n const words = input.split(/\\s+/);\n const lines: string[] = [];\n let currentLine = '';\n\n for (const word of words) {\n if (currentLine.length + word.length + 1 <= width) {\n currentLine += (currentLine ? ' ' : '') + word;\n } else {\n lines.push(currentLine);\n currentLine = word;\n }\n }\n\n if (currentLine) {\n lines.push(currentLine);\n }\n\n return lines.join('\\n');\n },\n};\n\n/**\n * Unwrap a Rivet DataValue at an interpolation source boundary. Callers must\n * not recursively apply this to selected JSON properties: an ordinary object\n * inside the value may legitimately have `type` and `value` properties.\n */\nexport function unwrapPotentialDataValue(value: unknown): unknown {\n if (isRivetDataValue(value)) {\n return (value as { value: unknown }).value;\n }\n\n return value;\n}\n\nfunction isRivetDataValue(value: unknown): value is DataValue {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { type?: unknown }).type === 'string' &&\n dataValueTypeSet.has((value as { type: string }).type) &&\n Object.prototype.hasOwnProperty.call(value, 'value')\n );\n}\n\n/**\n * Renders a whole interpolation input with the legacy generic interpolation\n * behavior. Text-oriented callers can opt into DataValue string coercion.\n */\nexport function stringifyInterpolationSourceValue(\n value: unknown,\n {\n coerceDataValueToString = false,\n unwrapDataValue = true,\n }: { coerceDataValueToString?: boolean; unwrapDataValue?: boolean } = {},\n): string {\n try {\n if (coerceDataValueToString && unwrapDataValue && isRivetDataValue(value)) {\n return coerceTypeOptional(value, 'string') ?? '';\n }\n\n return String((unwrapDataValue ? unwrapPotentialDataValue(value) : value) ?? '');\n } catch {\n // Keep interpolation usable for cyclic values and custom objects whose\n // string conversion throws, matching the prior object fallback.\n return '[object Object]';\n }\n}\n\nfunction findTopLevelProcessorSeparator(rawInner: string): number | undefined {\n let quote: '\"' | \"'\" | '`' | undefined;\n let regex = false;\n let regexCharacterClass = false;\n let bracketDepth = 0;\n let parenthesisDepth = 0;\n let braceDepth = 0;\n\n for (let cursor = 0; cursor < rawInner.length; cursor++) {\n const character = rawInner[cursor]!;\n\n if (regex) {\n if (character === '[' && !isInterpolationSyntaxCharacterEscaped(rawInner, cursor)) {\n regexCharacterClass = true;\n } else if (character === ']' && !isInterpolationSyntaxCharacterEscaped(rawInner, cursor)) {\n regexCharacterClass = false;\n } else if (\n character === '/' &&\n !regexCharacterClass &&\n !isInterpolationSyntaxCharacterEscaped(rawInner, cursor)\n ) {\n regex = false;\n }\n continue;\n }\n\n if (quote) {\n if (character === quote && !isInterpolationSyntaxCharacterEscaped(rawInner, cursor)) {\n quote = undefined;\n }\n continue;\n }\n\n if (character === '/' && isInterpolationRegexLiteralStart(rawInner, cursor)) {\n regex = true;\n regexCharacterClass = false;\n continue;\n }\n\n if (character === '\"' || character === \"'\" || character === '`') {\n quote = character;\n continue;\n }\n\n if (character === '[') {\n bracketDepth += 1;\n continue;\n }\n\n if (character === ']' && bracketDepth > 0) {\n bracketDepth -= 1;\n continue;\n }\n\n if (character === '(') {\n parenthesisDepth += 1;\n continue;\n }\n\n if (character === ')' && parenthesisDepth > 0) {\n parenthesisDepth -= 1;\n continue;\n }\n\n if (character === '{') {\n braceDepth += 1;\n continue;\n }\n\n if (character === '}' && braceDepth > 0) {\n braceDepth -= 1;\n continue;\n }\n\n if (character === '|' && bracketDepth === 0 && parenthesisDepth === 0 && braceDepth === 0) {\n return cursor;\n }\n }\n\n return undefined;\n}\n\nfunction findQuotedStringEnd(value: string, start: number): number | undefined {\n const quote = value[start];\n\n for (let cursor = start + 1; cursor < value.length; cursor++) {\n if (value[cursor] === quote && !isInterpolationSyntaxCharacterEscaped(value, cursor)) {\n return cursor;\n }\n }\n\n return undefined;\n}\n\nfunction parseQuotedBaseReference(expression: string): { baseName: string; suffix: string | undefined } | undefined {\n if (expression[0] !== '[') {\n return undefined;\n }\n\n let cursor = 1;\n while (expression[cursor] === ' ') {\n cursor += 1;\n }\n\n const quote = expression[cursor];\n if (quote !== '\"' && quote !== \"'\") {\n return undefined;\n }\n\n const quoteEnd = findQuotedStringEnd(expression, cursor);\n if (quoteEnd === undefined) {\n return undefined;\n }\n\n // JSONPath-plus retains the raw content of a bracket-property literal. Use\n // escaping only to find its closing quote, then keep its key untouched so\n // a `\\\\u` sequence names the same input it would name in JSONPath-plus.\n const baseName = expression.slice(cursor + 1, quoteEnd);\n if (!baseName) {\n return undefined;\n }\n\n cursor = quoteEnd + 1;\n while (expression[cursor] === ' ') {\n cursor += 1;\n }\n\n if (expression[cursor] !== ']') {\n return undefined;\n }\n\n const suffix = expression.slice(cursor + 1).trimStart();\n if (suffix !== '' && !suffix.startsWith('.') && !suffix.startsWith('[')) {\n return undefined;\n }\n\n return { baseName, suffix: suffix || undefined };\n}\n\nfunction parseBaseReference(\n expression: string,\n source: InterpolationReferenceSource,\n): ParsedInterpolationExpression | undefined {\n const trimmedExpression = expression.trim();\n if (!trimmedExpression) {\n return undefined;\n }\n\n const quotedReference = parseQuotedBaseReference(trimmedExpression);\n if (quotedReference) {\n return {\n source,\n baseName: quotedReference.baseName,\n jsonPath: quotedReference.suffix ? normalizeJsonPathExpression(`$${quotedReference.suffix}`) : undefined,\n };\n }\n\n let suffixStart = -1;\n for (let cursor = 0; cursor < trimmedExpression.length; cursor++) {\n const character = trimmedExpression[cursor];\n if (character === '.' || character === '[') {\n suffixStart = cursor;\n break;\n }\n }\n\n if (suffixStart === -1) {\n return {\n source,\n baseName: trimmedExpression,\n jsonPath: undefined,\n };\n }\n\n const baseName = trimmedExpression.slice(0, suffixStart).trim();\n const suffix = normalizeJsonPathExpression(trimmedExpression.slice(suffixStart));\n\n if (!baseName || (!suffix.startsWith('.') && !suffix.startsWith('['))) {\n return undefined;\n }\n\n return {\n source,\n baseName,\n jsonPath: `$${suffix}`,\n };\n}\n\n/**\n * Parses the authored portion of an interpolation token. Paths are always\n * rooted at the selected base value, so `foo.items[0]` becomes input `foo`\n * plus JSONPath `$.items[0]`.\n */\nfunction parseInterpolationExpressionUncached(trimmedExpression: string): ParsedInterpolationExpression | undefined {\n for (const [prefix, source] of [\n ['@graphInputs', 'graphInputs'],\n ['@context', 'context'],\n ['@globals', 'globals'],\n ] as const) {\n if (trimmedExpression.startsWith(`${prefix}.`)) {\n return parseBaseReference(trimmedExpression.slice(prefix.length + 1), source);\n }\n\n if (trimmedExpression.startsWith(`${prefix}[`)) {\n return parseBaseReference(trimmedExpression.slice(prefix.length), source);\n }\n }\n\n return parseBaseReference(trimmedExpression, 'variable');\n}\n\n/**\n * Returns an immutable syntax record for internal resolution. This cache is\n * intentionally keyed only by expression text; resolved values are always\n * read from the current invocation's sources.\n */\nfunction getCachedInterpolationExpression(expression: string): ParsedInterpolationExpression | undefined {\n const trimmedExpression = expression.trim();\n if (interpolationExpressionCache.has(trimmedExpression)) {\n return interpolationExpressionCache.get(trimmedExpression);\n }\n\n const parsed = parseInterpolationExpressionUncached(trimmedExpression);\n if (trimmedExpression.length > INTERPOLATION_EXPRESSION_CACHE_MAX_EXPRESSION_LENGTH) {\n return parsed;\n }\n\n if (\n interpolationExpressionCache.size >= INTERPOLATION_EXPRESSION_CACHE_MAX_ENTRIES ||\n cachedInterpolationExpressionChars + trimmedExpression.length > INTERPOLATION_EXPRESSION_CACHE_MAX_CHARS\n ) {\n interpolationExpressionCache.clear();\n cachedInterpolationExpressionChars = 0;\n }\n\n const immutableParsed = parsed ? (Object.freeze({ ...parsed }) as ParsedInterpolationExpression) : undefined;\n interpolationExpressionCache.set(trimmedExpression, immutableParsed);\n cachedInterpolationExpressionChars += trimmedExpression.length;\n return immutableParsed;\n}\n\n/**\n * Parses a public interpolation expression. Return a fresh record so callers\n * can safely mutate it without corrupting the internal syntax cache.\n */\nexport function parseInterpolationExpression(expression: string): ParsedInterpolationExpression | undefined {\n const parsed = getCachedInterpolationExpression(expression);\n return parsed ? { ...parsed } : undefined;\n}\n\n/** Splits an interpolation token into its expression, processor chain, and parsed reference. */\nexport function parseInterpolationToken(rawInner: string): Omit<ParsedInterpolationToken, 'span'> {\n const processorSeparator = findTopLevelProcessorSeparator(rawInner);\n const tokenName =\n (processorSeparator === undefined ? rawInner : rawInner.slice(0, processorSeparator)).trim() || undefined;\n const processingChain =\n processorSeparator === undefined ? undefined : rawInner.slice(processorSeparator + 1).trim() || undefined;\n\n return {\n rawInner,\n tokenName,\n processingChain,\n reference: tokenName ? parseInterpolationExpression(tokenName) : undefined,\n };\n}\n\nfunction freezeReference(\n reference: ParsedInterpolationExpression | undefined,\n): ParsedInterpolationExpression | undefined {\n return reference ? Object.freeze({ ...reference }) : undefined;\n}\n\nfunction parseInterpolationTemplateUncached(\n template: string,\n check?: () => void,\n tokenLimit = Infinity,\n): ParsedInterpolationTemplate {\n const tokens = scanInterpolationTokenSpans(template, check, tokenLimit).map((span) => {\n check?.();\n const parsedToken = parseInterpolationToken(span.rawInner);\n return Object.freeze({\n ...parsedToken,\n span: Object.freeze({ ...span }),\n reference: freezeReference(parsedToken.reference),\n });\n });\n\n return Object.freeze({\n template,\n tokens: Object.freeze(tokens),\n });\n}\n\nfunction getTemplateStorageChars(template: string, parsed: ParsedInterpolationTemplate): number {\n return (\n template.length +\n parsed.tokens.reduce(\n (total, token) => total + token.rawInner.length + (token.tokenName?.length ?? 0),\n parsed.tokens.length * 48,\n )\n );\n}\n\nfunction cacheInterpolationTemplate(template: string, parsed: ParsedInterpolationTemplate): void {\n if (template.length > INTERPOLATION_TEMPLATE_CACHE_MAX_TEMPLATE_LENGTH) {\n return;\n }\n\n const storageChars = getTemplateStorageChars(template, parsed);\n const reachesCapacity =\n interpolationTemplateCache.size >= INTERPOLATION_TEMPLATE_CACHE_MAX_ENTRIES ||\n cachedInterpolationTemplateChars + template.length > INTERPOLATION_TEMPLATE_CACHE_MAX_TEMPLATE_CHARS ||\n cachedInterpolationTemplateStorageChars + storageChars > INTERPOLATION_TEMPLATE_CACHE_MAX_STORAGE_CHARS;\n\n if (reachesCapacity) {\n // Avoid miss-by-miss eviction churn. A repeated miss proves this template is hot.\n if (lastUncachedInterpolationTemplate !== template) {\n lastUncachedInterpolationTemplate = template;\n return;\n }\n\n interpolationTemplateCache.clear();\n cachedInterpolationTemplateChars = 0;\n cachedInterpolationTemplateStorageChars = 0;\n }\n\n lastUncachedInterpolationTemplate = undefined;\n interpolationTemplateCache.set(template, {\n templateChars: template.length,\n storageChars,\n parsed,\n });\n cachedInterpolationTemplateChars += template.length;\n cachedInterpolationTemplateStorageChars += storageChars;\n}\n\n/** Returns an immutable, cached syntax representation. It never evaluates values. */\nexport function parseInterpolationTemplate(\n template: string,\n check?: () => void,\n tokenLimit = Infinity,\n): ParsedInterpolationTemplate {\n check?.();\n const cached = interpolationTemplateCache.get(template);\n if (cached) {\n if (cached.parsed.tokens.length > tokenLimit) throw new Error('Interpolation template has too many tokens.');\n return cached.parsed;\n }\n\n const parsed = parseInterpolationTemplateUncached(template, check, tokenLimit);\n if (template.includes('{{')) {\n cacheInterpolationTemplate(template, parsed);\n }\n return parsed;\n}\n\nexport function protectEscapedInterpolationTokens(template: string): string {\n return template.replace(ESCAPED_TOKEN_REGEX, (_match, expression) => `\\\\{\\\\{${expression}\\\\}\\\\}`);\n}\n\nexport function restoreEscapedInterpolationTokens(template: string): string {\n return template\n .replace(ESCAPED_ESCAPED_TOKEN_REGEX, (_match, expression) => `{{${expression}}}`)\n .replace(ESCAPED_TOKEN_REGEX, (_match, expression) => `{{${expression}}}`);\n}\n\nexport function findInterpolationTokenSpans(template: string): InterpolationTokenSpan[] {\n return parseInterpolationTemplate(template).tokens.map((token) => ({ ...token.span }));\n}\n\n/** Returns the pre-processor expression, retaining its authored path syntax. */\nexport function getInterpolationTokenName(rawInner: string): string | undefined {\n return parseInterpolationToken(rawInner).tokenName;\n}\n\nexport function getInterpolationTokenReference(rawInner: string): ParsedInterpolationExpression | undefined {\n return parseInterpolationToken(rawInner).reference;\n}\n\nexport function replaceInterpolationTokens(\n template: string,\n getReplacement: (token: InterpolationTokenReplacementInfo) => string,\n options: ReplaceInterpolationTokensOptions = {},\n): string {\n const parsedTemplate = parseInterpolationTemplate(template, options.guard?.check, options.guard?.tokenLimit);\n\n if (parsedTemplate.tokens.length === 0) {\n const restoredTemplate = restoreEscapedInterpolationTokens(template);\n return options.trim ? restoredTemplate.trim() : restoredTemplate;\n }\n\n let result = '';\n let cursor = 0;\n const append = (fragment: string) => {\n options.guard?.output(fragment, result.length);\n result += fragment;\n };\n\n for (const token of parsedTemplate.tokens) {\n // Restore escaped delimiters only from authored template text. A\n // replacement may deliberately contain `{{{...}}}` or `\\\\{\\\\{...\\\\}\\\\}` and\n // must be returned unchanged rather than interpreted as template syntax.\n options.guard?.check();\n append(restoreEscapedInterpolationTokens(template.slice(cursor, token.span.start)));\n append(\n getReplacement({\n rawInner: token.rawInner,\n span: { ...token.span },\n tokenName: token.tokenName,\n processingChain: token.processingChain,\n reference: token.reference ? { ...token.reference } : undefined,\n }),\n );\n cursor = token.span.end;\n }\n\n append(restoreEscapedInterpolationTokens(template.slice(cursor)));\n return options.trim ? result.trim() : result;\n}\n\n/**\n * Discovers connectable interpolation bases in first-occurrence order. Special\n * graph/context/global references are intentionally omitted because they do not make ports.\n */\nexport function extractInterpolationVariableReferences(template: string): InterpolationVariableReference[] {\n if (!template.includes('{{')) {\n return [];\n }\n\n const discovered = new Map<string, InterpolationVariableReference>();\n\n for (const token of parseInterpolationTemplate(template).tokens) {\n const reference = token.reference;\n if (!reference || reference.source !== 'variable') {\n continue;\n }\n\n const existing = discovered.get(reference.baseName);\n if (existing) {\n existing.hasPath ||= reference.jsonPath !== undefined;\n continue;\n }\n\n discovered.set(reference.baseName, {\n baseName: reference.baseName,\n hasPath: reference.jsonPath !== undefined,\n });\n }\n\n return Array.from(discovered.values(), (reference) => ({ ...reference }));\n}\n\n/**\n * Captures only globals referenced by a template into a safe record. Globals\n * are intentionally snapshotted at node execution: interpolation neither\n * waits for a writer nor creates an execution dependency.\n */\nexport function getInterpolationGlobalValues<T>(\n template: string,\n getGlobal: ((id: string) => T | undefined) | undefined,\n check?: () => void,\n tokenLimit = Infinity,\n): Record<string, T> {\n const values = Object.create(null) as Record<string, T>;\n if (!getGlobal || !template.includes('{{')) {\n return values;\n }\n\n for (const token of parseInterpolationTemplate(template, check, tokenLimit).tokens) {\n check?.();\n const reference = token.reference;\n if (\n !reference ||\n reference.source !== 'globals' ||\n Object.prototype.hasOwnProperty.call(values, reference.baseName)\n ) {\n continue;\n }\n\n const value = getGlobal(reference.baseName);\n if (value !== undefined) {\n Object.defineProperty(values, reference.baseName, {\n configurable: true,\n enumerable: true,\n value,\n writable: true,\n });\n }\n }\n\n return values;\n}\n\n/** Extracts base port names only. Prefer `extractInterpolationVariableReferences` when type selection matters. */\nexport function extractInterpolationVariables(template: string): string[] {\n return extractInterpolationVariableReferences(template).map((reference) => reference.baseName);\n}\n\nfunction getInterpolationSource(\n reference: ParsedInterpolationExpression,\n sources: InterpolationValueSources,\n): Record<string, unknown> | undefined {\n switch (reference.source) {\n case 'variable':\n return sources.variables;\n case 'graphInputs':\n return sources.graphInputValues;\n case 'context':\n return sources.contextValues;\n case 'globals':\n return sources.globalValues;\n }\n}\n\n/**\n * Resolves one parsed interpolation expression from raw values. JSONPath uses\n * `wrap: false`, matching Destructure exactly; callers decide how to render a\n * missing value or a selected object.\n */\nexport function resolveInterpolationExpressionRawValue(\n expression: string | ParsedInterpolationExpression,\n sources: InterpolationValueSources,\n): unknown | undefined {\n const reference = typeof expression === 'string' ? getCachedInterpolationExpression(expression) : expression;\n if (!reference) {\n return undefined;\n }\n\n const source = getInterpolationSource(reference, sources);\n if (!source || !Object.prototype.hasOwnProperty.call(source, reference.baseName)) {\n return undefined;\n }\n\n const shouldUnwrapDataValue = reference.source !== 'variable' || sources.unwrapVariableDataValues !== false;\n const property = sources.guard ? Object.getOwnPropertyDescriptor(source, reference.baseName) : undefined;\n if (sources.guard && (!property || !('value' in property)))\n throw new Error('Interpolation sources must use own data properties, not accessors.');\n const sourceValue = sources.guard ? sources.guard.prepareValue(property!.value) : source[reference.baseName];\n const baseValue = shouldUnwrapDataValue ? unwrapPotentialDataValue(sourceValue) : sourceValue;\n if (reference.jsonPath === undefined) {\n return baseValue;\n }\n\n let selected: unknown;\n try {\n selected = evaluateJsonPath(baseValue, reference.jsonPath, false);\n } catch {\n return undefined;\n }\n return sources.guard ? sources.guard.prepareValue(selected) : selected;\n}\n\nexport function resolveInterpolationTokenRawValue(\n rawInner: string,\n sources: InterpolationValueSources,\n): unknown | undefined {\n const reference = parseInterpolationToken(rawInner).reference;\n return reference ? resolveInterpolationExpressionRawValue(reference, sources) : undefined;\n}\n\n/** Backward-compatible special-reference resolver used by existing nodes. */\nexport function resolveExpressionRawValue(\n source: Record<string, unknown> | undefined,\n expression: string,\n sourceType: 'graphInputs' | 'context' | 'globals',\n): unknown | undefined {\n return resolveInterpolationExpressionRawValue(`@${sourceType}.${expression}`, {\n graphInputValues: sourceType === 'graphInputs' ? source : undefined,\n contextValues: sourceType === 'context' ? source : undefined,\n globalValues: sourceType === 'globals' ? source : undefined,\n });\n}\n\nfunction stringifyInterpolationValue(value: unknown): string {\n if (typeof value === 'object' && value !== null) {\n try {\n return JSON.stringify(value);\n } catch (error) {\n console.warn('Error stringifying an interpolation value:', error);\n return '[object Object]';\n }\n }\n\n return String(value);\n}\n\nexport function resolveExpressionToString(\n source: Record<string, unknown> | undefined,\n expression: string,\n sourceType: 'graphInputs' | 'context' | 'globals',\n): string | undefined {\n const finalValue = resolveExpressionRawValue(source, expression, sourceType);\n return finalValue === undefined ? undefined : stringifyInterpolationValue(finalValue);\n}\n\nfunction parseProcessing(instruction: string): { func: string; param?: number } {\n const parts = instruction.trim().split(/\\s+/);\n return {\n func: parts[0]!,\n param: parts[1] ? Number.parseInt(parts[1], 10) : undefined,\n };\n}\n\nfunction applyProcessing(value: string, processingChain: string, guard?: InterpolationGuard): string {\n guard?.processing(processingChain, 'chain', undefined);\n const instructions = processingChain\n .split('|')\n .map((instruction) => instruction.trim())\n .filter((instruction) => instruction !== '');\n\n return instructions.reduce((result, instruction) => {\n const { func, param } = parseProcessing(instruction);\n guard?.processing(result, func, param);\n const processingFunc = processingFunctions[func];\n\n if (!processingFunc) {\n console.warn(`Unknown processing function: ${func}`);\n return result;\n }\n\n const processed = processingFunc(result, param);\n guard?.output(processed, 0);\n return processed;\n }, value);\n}\n\n/**\n * Resolves text interpolation. Bare ordinary variables keep the historical\n * string coercion; path-bearing references select raw data first and serialize\n * selected objects/arrays as JSON.\n */\nexport function interpolate(\n template: string,\n variables: Record<string, unknown>,\n graphInputValues?: Record<string, DataValue>,\n contextValues?: Record<string, DataValue>,\n options: InterpolateOptions = {},\n): string {\n return replaceInterpolationTokens(\n template,\n (token) => {\n if (!token.reference) {\n return '';\n }\n\n const resolvedValue = resolveInterpolationExpressionRawValue(token.reference, {\n variables,\n graphInputValues,\n contextValues,\n globalValues: options.globalValues,\n unwrapVariableDataValues: options.unwrapVariableDataValues,\n guard: options.guard,\n });\n\n if (resolvedValue === undefined) {\n console.warn(`Interpolation variable or path \"${token.tokenName}\" not found or resolved to undefined.`);\n return '';\n }\n\n const isBareOrdinaryVariable = token.reference.source === 'variable' && token.reference.jsonPath === undefined;\n const stringValue = isBareOrdinaryVariable\n ? stringifyInterpolationSourceValue(options.guard ? resolvedValue : variables[token.reference.baseName], {\n coerceDataValueToString: options.coerceBareVariableDataValues,\n unwrapDataValue: !options.guard && options.unwrapVariableDataValues !== false,\n })\n : stringifyInterpolationValue(resolvedValue);\n options.guard?.output(stringValue, 0);\n return token.processingChain ? applyProcessing(stringValue, token.processingChain, options.guard) : stringValue;\n },\n { guard: options.guard },\n );\n}\n\n/** Runtime helper injected into JavaScript runners without exposing the whole Rivet API. */\nexport function resolveCodeInterpolationExpression(\n inputs: Record<string, DataValue | undefined>,\n expression: string,\n graphInputValues?: Record<string, DataValue>,\n contextValues?: Record<string, DataValue>,\n globalValues?: Record<string, DataValue>,\n): unknown | undefined {\n return resolveInterpolationExpressionRawValue(expression, {\n variables: inputs,\n graphInputValues,\n contextValues,\n globalValues,\n });\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA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