{
  "version": 3,
  "sources": ["../../src/index.ts", "../../src/exports.ts", "../../src/utils/coerceType.ts", "../../src/utils/genericUtilFunctions.ts", "../../src/model/DataValue.ts", "../../src/utils/expectType.ts", "../../src/utils/errors.ts", "../../src/utils/serialization/serialization.ts", "../../src/utils/serialization/serialization_v3.ts", "../../src/utils/serialization/serializationUtils.ts", "../../src/utils/serialization/serialization_v4.ts", "../../src/utils/typeSafety.ts", "../../src/model/NodeGraph.ts", "../../src/model/NodeBase.ts", "../../src/utils/serialization/serialization_v2.ts", "../../src/utils/serialization/serialization_v1.ts", "../../src/utils/symbols.ts", "../../src/utils/outputs.ts", "../../src/utils/base64.ts", "../../src/utils/inputs.ts", "../../src/utils/misc.ts", "../../src/utils/getPluginConfig.ts", "../../src/utils/newId.ts", "../../src/utils/handleEscapeCharacters.ts", "../../src/utils/compatibility.ts", "../../src/utils/defaults.ts", "../../src/model/GraphProcessor.ts", "../../src/model/NodeImpl.ts", "../../src/model/NodeRegistration.ts", "../../src/model/nodes/UserInputNode.ts", "../../src/model/NodeDefinition.ts", "../../src/model/nodes/TextNode.ts", "../../src/utils/interpolation.ts", "../../src/model/nodes/ChatNode.ts", "../../src/model/nodes/ChatNodeBase.ts", "../../src/utils/openai.ts", "../../src/utils/fetchEventSource.ts", "../../src/utils/chatMessageToOpenAIChatCompletionMessage.ts", "../../src/model/nodes/PromptNode.ts", "../../src/model/nodes/ExtractRegexNode.ts", "../../src/model/nodes/CodeNode.ts", "../../src/model/nodes/MatchNode.ts", "../../src/model/nodes/IfNode.ts", "../../src/model/nodes/ReadDirectoryNode.ts", "../../src/utils/paths.ts", "../../src/model/nodes/ReadFileNode.ts", "../../src/model/nodes/IfElseNode.ts", "../../src/model/nodes/ChunkNode.ts", "../../src/model/nodes/GraphInputNode.ts", "../../src/model/nodes/GraphOutputNode.ts", "../../src/model/nodes/SubGraphNode.ts", "../../src/model/nodes/ArrayNode.ts", "../../src/model/nodes/ExtractJsonNode.ts", "../../src/model/nodes/AssemblePromptNode.ts", "../../src/model/nodes/ExtractYamlNode.ts", "../../src/model/nodes/LoopControllerNode.ts", "../../src/model/nodes/TrimChatMessagesNode.ts", "../../src/model/nodes/ExternalCallNode.ts", "../../src/model/nodes/ExtractObjectPathNode.ts", "../../src/model/nodes/RaiseEventNode.ts", "../../src/model/nodes/ContextNode.ts", "../../src/model/nodes/CoalesceNode.ts", "../../src/model/nodes/PassthroughNode.ts", "../../src/model/nodes/PopNode.ts", "../../src/model/nodes/SetGlobalNode.ts", "../../src/model/nodes/GetGlobalNode.ts", "../../src/model/nodes/WaitForEventNode.ts", "../../src/model/nodes/ToolNode.ts", "../../src/model/nodes/ToYamlNode.ts", "../../src/model/nodes/GetEmbeddingNode.ts", "../../src/integrations/integrations.ts", "../../src/model/nodes/VectorStoreNode.ts", "../../src/model/nodes/VectorNearestNeighborsNode.ts", "../../src/model/nodes/HashNode.ts", "../../src/model/nodes/AbortGraphNode.ts", "../../src/model/nodes/RaceInputsNode.ts", "../../src/model/nodes/ToJsonNode.ts", "../../src/model/nodes/JoinNode.ts", "../../src/model/nodes/FilterNode.ts", "../../src/model/nodes/ObjectNode.ts", "../../src/model/nodes/BooleanNode.ts", "../../src/model/nodes/CompareNode.ts", "../../src/model/nodes/EvaluateNode.ts", "../../src/model/nodes/NumberNode.ts", "../../src/model/nodes/RandomNumberNode.ts", "../../src/model/nodes/ShuffleNode.ts", "../../src/model/nodes/CommentNode.ts", "../../src/model/nodes/ImageNode.ts", "../../src/model/nodes/AudioNode.ts", "../../src/model/nodes/HttpCallNode.ts", "../../src/model/nodes/DelayNode.ts", "../../src/model/nodes/AppendToDatasetNode.ts", "../../src/model/nodes/CreateDatasetNode.ts", "../../src/model/nodes/LoadDatasetNode.ts", "../../src/model/nodes/GetAllDatasetsNode.ts", "../../src/model/nodes/SplitNode.ts", "../../src/model/nodes/DatasetNearestNeigborsNode.ts", "../../src/model/nodes/GetDatasetRowNode.ts", "../../src/model/nodes/SliceNode.ts", "../../src/model/nodes/ExtractMarkdownCodeBlocksNode.ts", "../../src/model/nodes/AssembleMessageNode.ts", "../../src/model/nodes/URLReferenceNode.ts", "../../src/model/nodes/DestructureNode.ts", "../../src/model/nodes/ReplaceDatasetNode.ts", "../../src/model/nodes/ListGraphsNode.ts", "../../src/model/nodes/GraphReferenceNode.ts", "../../src/model/nodes/CallGraphNode.ts", "../../src/api/looseDataValue.ts", "../../src/model/nodes/DelegateFunctionCallNode.ts", "../../src/model/nodes/PlayAudioNode.ts", "../../src/model/nodes/DocumentNode.ts", "../../src/model/nodes/ChatLoopNode.ts", "../../src/model/nodes/ReadAllFilesNode.ts", "../../src/model/nodes/ToMarkdownTableNode.ts", "../../src/model/nodes/CronNode.ts", "../../src/model/nodes/ToTreeNode.ts", "../../src/model/nodes/LoopUntilNode.ts", "../../src/model/nodes/MCPDiscoveryNode.ts", "../../src/integrations/mcp/MCPProvider.ts", "../../src/integrations/mcp/MCPUtils.ts", "../../src/integrations/mcp/MCPBase.ts", "../../src/model/nodes/MCPToolCallNode.ts", "../../src/model/nodes/MCPGetPromptNode.ts", "../../src/model/nodes/ReferencedGraphAliasNode.ts", "../../src/model/Nodes.ts", "../../src/integrations/GptTokenizerTokenizer.ts", "../../src/integrations/CodeRunner.ts", "../../src/native/BaseDir.ts", "../../src/native/BrowserNativeApi.ts", "../../src/integrations/openai/OpenAIEmbeddingGenerator.ts", "../../src/integrations/enableIntegrations.ts", "../../src/recording/ExecutionRecorder.ts", "../../src/plugins/anthropic/fetchEventSource.ts", "../../src/plugins/anthropic/anthropic.ts", "../../src/plugins/anthropic/nodes/ChatAnthropicNode.ts", "../../src/utils/assertNever.ts", "../../src/plugins/anthropic/plugin.ts", "../../src/plugins/anthropic/index.ts", "../../src/plugins/autoevals/AutoEvalsNode.ts", "../../src/plugins/autoevals/plugin.ts", "../../src/plugins/autoevals/index.ts", "../../src/plugins/assemblyAi/LemurQaNode.ts", "../../src/plugins/assemblyAi/lemurHelpers.ts", "../../src/plugins/assemblyAi/TranscribeAudioNode.ts", "../../src/plugins/assemblyAi/LemurSummaryNode.ts", "../../src/plugins/assemblyAi/LemurTaskNode.ts", "../../src/plugins/assemblyAi/LemurActionItemsNode.ts", "../../src/plugins/assemblyAi/plugin.ts", "../../src/plugins/assemblyAi/index.ts", "../../src/plugins/huggingface/nodes/ChatHuggingFace.ts", "../../src/plugins/huggingface/nodes/TextToImageHuggingFace.ts", "../../src/plugins/huggingface/plugin.ts", "../../src/plugins/pinecone/PineconeVectorDatabase.ts", "../../src/plugins/pinecone/plugin.ts", "../../src/plugins/pinecone/index.ts", "../../src/plugins/gentrace/plugin.ts", "../../src/plugins/gentrace/index.ts", "../../src/plugins/openai/nodes/CreateThreadNode.ts", "../../src/plugins/openai/nodes/GetThreadNode.ts", "../../src/plugins/openai/nodes/DeleteThreadNode.ts", "../../src/plugins/openai/handleOpenaiError.ts", "../../src/plugins/openai/nodes/CreateAssistantNode.ts", "../../src/plugins/openai/nodes/GetAssistantNode.ts", "../../src/plugins/openai/nodes/ListAssistantsNode.ts", "../../src/plugins/openai/nodes/DeleteAssistantNode.ts", "../../src/plugins/openai/nodes/UploadFileNode.ts", "../../src/plugins/openai/nodes/ListOpenAIFilesNode.ts", "../../src/plugins/openai/nodes/GetOpenAIFileNode.ts", "../../src/plugins/openai/nodes/AttachAssistantFileNode.ts", "../../src/plugins/openai/nodes/CreateThreadMessageNode.ts", "../../src/plugins/openai/nodes/ListThreadMessagesNode.ts", "../../src/plugins/openai/nodes/RunThreadNode.ts", "../../src/plugins/openai/nodes/ThreadMessageNode.ts", "../../src/plugins/openai/plugin.ts", "../../src/plugins/google/google.ts", "../../src/plugins/google/nodes/ChatGoogleNode.ts", "../../src/plugins/google/plugin.ts", "../../src/plugins.ts", "../../src/integrations/DatasetProvider.ts", "../../src/api/streaming.ts", "../../src/api/createProcessor.ts"],
  "sourcesContent": ["import type * as RivetTypes from './exports.js';\nexport * from './exports.js';\n\nexport const Rivet: typeof RivetTypes = undefined!;\n\nexport type RivetPluginInitializer = (rivet: typeof Rivet) => RivetTypes.RivetPlugin;\n", "export * from './utils/index.js';\nexport * from './model/GraphProcessor.js';\nexport * from './model/DataValue.js';\nexport * from './model/NodeBase.js';\nexport * from './model/NodeGraph.js';\nexport * from './model/NodeImpl.js';\nexport * from './model/NodeDefinition.js';\nexport * from './model/Nodes.js';\nexport * from './model/Project.js';\nexport * from './native/BaseDir.js';\nexport * from './native/NativeApi.js';\nexport * from './native/BrowserNativeApi.js';\nexport * from './model/ProcessContext.js';\nexport * from './integrations/integrations.js';\nimport './integrations/enableIntegrations.js';\nexport * from './integrations/VectorDatabase.js';\nexport * from './integrations/mcp/MCPProvider.js';\nexport * from './integrations/EmbeddingGenerator.js';\nexport * from './integrations/LLMProvider.js';\nexport * from './recording/ExecutionRecorder.js';\nexport * from './recording/RecordedEvents.js';\nexport * from './model/RivetPlugin.js';\nexport * from './plugins.js';\nexport * from './model/NodeRegistration.js';\nexport type * from './model/Settings.js';\nexport * from './model/EditorDefinition.js';\nexport * from './model/NodeBodySpec.js';\nexport * from './integrations/DatasetProvider.js';\nexport * from './model/Dataset.js';\nexport * from './api/streaming.js';\nexport * from './api/createProcessor.js';\nexport * from './integrations/AudioProvider.js';\nexport * from './api/looseDataValue.js';\nexport * from './integrations/CodeRunner.js';\n\nimport * as openai from './utils/openai.js';\nexport { openai };\n", "import { match } from 'ts-pattern';\nimport {\n  type ChatMessage,\n  type DataType,\n  type DataValue,\n  type GetDataValue,\n  getScalarTypeOf,\n  isArrayDataType,\n  isArrayDataValue,\n  unwrapDataValue,\n} from '../model/DataValue.js';\nimport { expectTypeOptional } from './expectType.js';\nimport type { GraphId } from '../index.js';\n\nexport function coerceTypeOptional<T extends DataType>(\n  wrapped: DataValue | undefined,\n  type: T,\n): GetDataValue<T>['value'] | undefined {\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    return [coerced] as any;\n  }\n\n  // Coerce foo[] to bar[]\n  if (isArrayDataType(type) && isArrayDataValue(value) && getScalarTypeOf(type) !== getScalarTypeOf(value.type)) {\n    return value.value.map((v) =>\n      coerceTypeOptional({ type: getScalarTypeOf(value.type), value: v } as DataValue, getScalarTypeOf(type)),\n    ) as any;\n  }\n\n  const result = match(type as DataType)\n    .with('string', () => coerceToString(value))\n    .with('boolean', () => coerceToBoolean(value))\n    .with('chat-message', () => coerceToChatMessage(value))\n    .with('number', () => coerceToNumber(value))\n    .with('object', () => coerceToObject(value))\n    .with('binary', () => coerceToBinary(value))\n    .with('graph-reference', () => coerceToGraphReference(value))\n    .otherwise(() => {\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\n  return result as GetDataValue<T>['value'] | undefined;\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    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\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\n// TODO hard to keep in sync with coerceType\nexport function canBeCoerced(from: DataType, to: DataType) {\n  if (to === 'any' || 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 (to === 'gpt-function') {\n    return from === 'object';\n  }\n\n  if (to === 'audio' || to === 'binary' || to === 'image') {\n    return false;\n  }\n\n  return true;\n}\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 { GraphId } from '../index.js';\nimport { exhaustiveTuple } from '../utils/genericUtilFunctions.js';\nimport type { DataId } from './Project.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 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\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 = SystemChatMessage | UserChatMessage | AssistantChatMessage | 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 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\n/** GPT function definition */\nexport type GptFunction = {\n  name: string;\n  namespace?: string;\n  description: string;\n  parameters: object;\n  strict: boolean;\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  | 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 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  '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  '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  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 ArrayDataValues {\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(value: DataValue | undefined): value is FunctionDataValues {\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 !isFunctionDataValue(value);\n}\n\nexport function functionTypeToScalarType(functionType: FunctionDataType): ScalarDataType {\n  return functionType.slice(3, -1) as ScalarDataType;\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    return { type: functionTypeToScalarType(value.type), value: value.value() } 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  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): (DataValue & { type: T })['value'] {\n  if (isArrayDataType(type)) {\n    return [] as any;\n  }\n\n  if (isFunctionDataType(type)) {\n    return (() => scalarDefaults[getScalarTypeOf(type)]) as any;\n  }\n\n  return scalarDefaults[getScalarTypeOf(type)] as any;\n}\n", "import {\n  type DataType,\n  type DataValue,\n  type GetDataValue,\n  getScalarTypeOf,\n  isArrayDataType,\n  isFunctionDataType,\n  isScalarDataValue,\n  unwrapDataValue,\n} from '../model/DataValue.js';\n\nexport function expectType<T extends DataType>(value: DataValue | undefined, type: T): GetDataValue<T>['value'] {\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 (type === 'any' || type === 'any[]' || value?.type === 'any' || value?.type === 'any[]') {\n    return value?.value as GetDataValue<T>['value'];\n  }\n\n  if ((isFunctionDataType(type) && value?.type === `fn<${type}>`) || type === 'fn<any>') {\n    return (() => value!.value) as GetDataValue<T>['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'];\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  // 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  // 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", "/** Gets an Error from an unknown error object (strict unknown errors is enabled, helper util). */\nexport function getError(error: unknown): Error {\n  const errorInstance =\n    typeof error === 'object' && error instanceof Error\n      ? error\n      : new Error(error != null ? error.toString() : 'Unknown error');\n  return errorInstance;\n}\n", "// @ts-ignore\nimport * as yaml from 'yaml';\nimport { graphV3Deserializer, projectV3Deserializer } from './serialization_v3.js';\nimport type { Project, NodeGraph, Dataset, DatasetMetadata } from '../../index.js';\nimport { getError } from '../errors.js';\nimport { type AttachedData, yamlProblem } from './serializationUtils.js';\nimport {\n  datasetV4Deserializer,\n  datasetV4Serializer,\n  graphV4Deserializer,\n  graphV4Serializer,\n  projectV4Deserializer,\n  projectV4Serializer,\n} from './serialization_v4.js';\nimport { graphV2Deserializer, projectV2Deserializer } from './serialization_v2.js';\nimport { graphV1Deserializer, projectV1Deserializer } from './serialization_v1.js';\n\nexport function serializeProject(project: Project, attachedData?: AttachedData): unknown {\n  return projectV4Serializer(project, attachedData);\n}\n\nconst errMessage = (err: unknown) => `${getError(err).message}\\n${getError(err).stack}`;\n\nexport function deserializeProject(serializedProject: unknown, path: string | null = null): [Project, AttachedData] {\n  try {\n    const result = projectV4Deserializer(serializedProject);\n    if (path !== null) result[0].metadata.path = path;\n    return result;\n  } catch (err) {\n    if (err instanceof yaml.YAMLError) {\n      yamlProblem(err);\n    }\n    console.warn(`Failed to deserialize project v4: ${errMessage(err)}`);\n\n    try {\n      const project = projectV3Deserializer(serializedProject);\n      return [project, {}];\n    } catch (err) {\n      if (err instanceof yaml.YAMLError) {\n        yamlProblem(err);\n      }\n      console.warn(`Failed to deserialize project v3: ${errMessage(err)}`);\n\n      try {\n        const project = projectV2Deserializer(serializedProject);\n        return [project, {}];\n      } catch (err) {\n        if (err instanceof yaml.YAMLError) {\n          yamlProblem(err);\n        }\n        console.warn(`Failed to deserialize project v2: ${errMessage(err)}`);\n\n        try {\n          const project = projectV1Deserializer(serializedProject);\n          return [project, {}];\n        } catch (err) {\n          console.warn(`Failed to deserialize project v1: ${errMessage(err)}`);\n          throw new Error('Could not deserialize project');\n        }\n      }\n    }\n  }\n}\n\nexport function serializeGraph(graph: NodeGraph): unknown {\n  return graphV4Serializer(graph);\n}\n\nexport function deserializeGraph(serializedGraph: unknown): NodeGraph {\n  try {\n    return graphV4Deserializer(serializedGraph);\n  } catch (err) {\n    try {\n      return graphV3Deserializer(serializedGraph);\n    } catch (err) {\n      try {\n        return graphV2Deserializer(serializedGraph);\n      } catch (err) {\n        try {\n          return graphV1Deserializer(serializedGraph);\n        } catch (err) {\n          throw new Error('Could not deserialize graph');\n        }\n      }\n    }\n  }\n}\n\nexport type CombinedDataset = {\n  meta: DatasetMetadata;\n  data: Dataset;\n};\n\nexport function serializeDatasets(datasets: CombinedDataset[]): string {\n  return datasetV4Serializer(datasets);\n}\n\nexport function deserializeDatasets(serializedDatasets: string): CombinedDataset[] {\n  return datasetV4Deserializer(serializedDatasets);\n}\n", "import { mapValues } from 'lodash-es';\nimport type {\n  NodeGraph,\n  Project,\n  GraphId,\n  NodeId,\n  NodeConnection,\n  ChartNode,\n  PortId,\n  ChartNodeVariant,\n  ProjectId,\n} from '../../index.js';\nimport stableStringify from 'safe-stable-stringify';\n// @ts-ignore\nimport * as yaml from 'yaml';\nimport { doubleCheckProject } from './serializationUtils.js';\n\ntype SerializedProject = {\n  metadata: {\n    id: ProjectId;\n    title: string;\n    description: string;\n  };\n\n  graphs: Record<GraphId, SerializedGraph>;\n};\n\ntype SerializedGraph = {\n  metadata: {\n    id: GraphId;\n    name: string;\n    description: string;\n  };\n\n  nodes: Record<NodeId, SerializedNode>;\n};\n\nexport type SerializedNode = {\n  type: string;\n  id: string;\n  title: string;\n  description?: string;\n  isSplitRun?: boolean;\n  splitRunMax?: number;\n\n  // x/y/width/zIndex\n  visualData: `${string}/${string}/${string}/${string}`;\n  outgoingConnections: SerializedNodeConnection[];\n  data?: unknown;\n  variants?: ChartNodeVariant<unknown>[];\n};\n\n/** x/y/width/zIndex */\n// type SerializedVisualData = `${string}/${string}/${string}/${string}`;\n\n// portId->nodeId/portId\ntype SerializedNodeConnection = `${string}->\"${string}\" ${string}/${string}`;\n\nexport function projectV3Deserializer(data: unknown): Project {\n  if (typeof data !== 'string') {\n    throw new Error('Project v3 deserializer requires a string');\n  }\n\n  const serializedProject = yaml.parse(data) as { version: number; data: SerializedProject };\n\n  if (serializedProject.version !== 3) {\n    throw new Error('Project v3 deserializer requires a version 3 project');\n  }\n\n  const project = fromSerializedProject(serializedProject.data);\n\n  doubleCheckProject(project);\n\n  return project;\n}\n\nexport function graphV3Deserializer(data: unknown): NodeGraph {\n  if (typeof data !== 'string') {\n    throw new Error('Graph v3 deserializer requires a string');\n  }\n\n  const serializedGraph = yaml.parse(data) as { version: number; data: SerializedGraph };\n\n  if (serializedGraph.version !== 3) {\n    throw new Error('Graph v3 deserializer requires a version 3 graph');\n  }\n\n  return fromSerializedGraph(serializedGraph.data);\n}\n\nexport function projectV3Serializer(project: Project): unknown {\n  // Make sure all data is ordered deterministically first\n  const stabilized = JSON.parse(stableStringify(toSerializedProject(project)));\n\n  const serialized = yaml.stringify(\n    {\n      version: 3,\n      data: stabilized,\n    },\n    null,\n    {\n      indent: 2,\n    },\n  );\n\n  return serialized;\n}\n\nexport function graphV3Serializer(graph: NodeGraph): unknown {\n  // Make sure all data is ordered deterministically first\n  const stabilized = JSON.parse(stableStringify(toSerializedGraph(graph)));\n\n  const serialized = yaml.stringify(\n    {\n      version: 4,\n      data: stabilized,\n    },\n    null,\n    {\n      indent: 2,\n    },\n  );\n\n  return serialized;\n}\n\nfunction toSerializedProject(project: Project): SerializedProject {\n  return {\n    metadata: project.metadata,\n    graphs: mapValues(project.graphs, (graph) => toSerializedGraph(graph)),\n  };\n}\n\nfunction fromSerializedProject(serializedProject: SerializedProject): Project {\n  return {\n    metadata: serializedProject.metadata,\n    graphs: mapValues(serializedProject.graphs, (graph) => fromSerializedGraph(graph)) as Record<GraphId, NodeGraph>,\n    plugins: [],\n  };\n}\n\nfunction toSerializedGraph(graph: NodeGraph): SerializedGraph {\n  return {\n    metadata: {\n      id: graph.metadata!.id!,\n      name: graph.metadata!.name!,\n      description: graph.metadata!.description!,\n    },\n    nodes: graph.nodes.reduce(\n      (acc, node) => ({\n        ...acc,\n        [node.id]: toSerializedNode(node, graph.nodes, graph.connections),\n      }),\n      {} as Record<NodeId, SerializedNode>,\n    ),\n  };\n}\n\nfunction fromSerializedGraph(serializedGraph: SerializedGraph): NodeGraph {\n  const allConnections: NodeConnection[] = [];\n  const allNodes: ChartNode[] = [];\n\n  for (const node of Object.values(serializedGraph.nodes)) {\n    const [chartNode, connections] = fromSerializedNode(node);\n    allNodes.push(chartNode);\n    allConnections.push(...connections);\n  }\n\n  return {\n    metadata: {\n      id: serializedGraph.metadata.id,\n      name: serializedGraph.metadata.name,\n      description: serializedGraph.metadata.description,\n    },\n    nodes: allNodes,\n    connections: allConnections,\n  };\n}\n\nfunction toSerializedNode(node: ChartNode, allNodes: ChartNode[], allConnections: NodeConnection[]): SerializedNode {\n  return {\n    id: node.id,\n    title: node.title,\n    description: node.description,\n    type: node.type,\n    visualData: `${node.visualData.x}/${node.visualData.y}/${node.visualData.width ?? 'null'}/${\n      node.visualData.zIndex ?? 'null'\n    }`,\n    isSplitRun: node.isSplitRun,\n    splitRunMax: node.splitRunMax,\n    data: node.data,\n    outgoingConnections: allConnections\n      .filter((connection) => connection.outputNodeId === node.id)\n      .map((connection) => toSerializedConnection(connection, allNodes))\n      .sort(),\n    variants: (node.variants?.length ?? 0) > 0 ? node.variants : undefined,\n  };\n}\n\nfunction fromSerializedNode(serializedNode: SerializedNode): [ChartNode, NodeConnection[]] {\n  const [x, y, width, zIndex] = serializedNode.visualData.split('/');\n\n  const connections = serializedNode.outgoingConnections.map((serializedConnection) =>\n    fromSerializedConnection(serializedConnection, serializedNode),\n  );\n\n  return [\n    {\n      id: serializedNode.id as NodeId,\n      title: serializedNode.title,\n      description: serializedNode.description,\n      type: serializedNode.type,\n      isSplitRun: serializedNode.isSplitRun,\n      splitRunMax: serializedNode.splitRunMax,\n      visualData: {\n        x: parseFloat(x!),\n        y: parseFloat(y!),\n        width: width === 'null' ? undefined : parseFloat(width!),\n        zIndex: zIndex === 'null' ? undefined : parseFloat(zIndex!),\n      },\n      data: serializedNode.data,\n      variants: serializedNode.variants,\n    },\n    connections,\n  ];\n}\n\nfunction toSerializedConnection(connection: NodeConnection, allNodes: ChartNode[]): SerializedNodeConnection {\n  return `${connection.outputId}->\"${allNodes.find((node) => node.id === connection.inputNodeId)?.title}\" ${\n    connection.inputNodeId\n  }/${connection.inputId}`;\n}\n\nfunction fromSerializedConnection(connection: SerializedNodeConnection, outgoingNode: SerializedNode): NodeConnection {\n  const [, outputId, , inputNodeId, inputId] = connection.match(/(.+)->\"(.+)\" (.+)\\/(.+)/)!;\n\n  return {\n    outputId: outputId as PortId,\n    outputNodeId: outgoingNode.id as NodeId,\n    inputId: inputId as PortId,\n    inputNodeId: inputNodeId as NodeId,\n  };\n}\n", "import type { Project } from '../../index.js';\nimport type * as yaml from 'yaml';\n\n/** Additional data that has been attached to a project/graph, for use by plugins, etc. */\nexport type AttachedData = Record<string, unknown>;\n\nexport function doubleCheckProject(project: Project): void {\n  if (\n    !project.metadata ||\n    !project.metadata!.id ||\n    !project.metadata!.title ||\n    !project.graphs ||\n    typeof project.graphs !== 'object'\n  ) {\n    throw new Error('Invalid project file');\n  }\n}\n\nexport function yamlProblem(err: yaml.YAMLError): never {\n  const { code, message, pos, linePos } = err;\n  throw new Error(`YAML error: ${code} ${message} at ${pos} ${linePos}`);\n}\n", "import { mapValues } from 'lodash-es';\nimport type {\n  NodeGraph,\n  Project,\n  GraphId,\n  NodeId,\n  NodeConnection,\n  ChartNode,\n  PortId,\n  ProjectId,\n  ChartNodeVariant,\n} from '../../index.js';\nimport stableStringify from 'safe-stable-stringify';\nimport * as yaml from 'yaml';\nimport { type AttachedData, doubleCheckProject } from './serializationUtils.js';\nimport { entries } from '../typeSafety.js';\nimport type { PluginLoadSpec } from '../../model/PluginLoadSpec.js';\nimport type { CombinedDataset } from './serialization.js';\nimport { type ProjectMetadata } from '../../model/Project.js';\n\ntype SerializedProject = {\n  metadata: ProjectMetadata;\n\n  graphs: Record<GraphId, SerializedGraph>;\n\n  attachedData?: AttachedData;\n  plugins?: PluginLoadSpec[];\n  references?: SerializedProjectReference[];\n};\n\ntype SerializedProjectReference = {\n  id: ProjectId;\n  hintPaths?: string[];\n  title?: string;\n};\n\ntype SerializedGraphMetadata = {\n  id: GraphId;\n  name: string;\n  description: string;\n  attachedData?: AttachedData;\n};\n\ntype SerializedGraph = {\n  metadata: SerializedGraphMetadata;\n  nodes: Record<SerializedGraphNodeKey, SerializedNode>;\n};\n\ntype SerializedNode = {\n  description?: string;\n  isSplitRun?: boolean;\n  splitRunMax?: number;\n  isSplitSequential?: boolean;\n  visualData: SerializedVisualData;\n  outgoingConnections: SerializedNodeConnection[] | undefined;\n  data?: unknown;\n  variants?: ChartNodeVariant<unknown>[];\n  disabled?: boolean;\n  isConditional?: boolean;\n};\n\n/** x/y/width/zIndex */\ntype SerializedVisualData = `${string}/${string}/${string}/${string}`;\n\n// portId->nodeId/portId\ntype SerializedNodeConnection = `${string}->\"${string}\" ${string}/${string}`;\n\nexport function projectV4Deserializer(data: unknown): [Project, AttachedData] {\n  if (typeof data !== 'string') {\n    throw new Error('Project v4 deserializer requires a string');\n  }\n\n  const serializedProject = yaml.parse(data) as { version: number; data: SerializedProject };\n\n  if (serializedProject.version !== 4) {\n    throw new Error('Project v4 deserializer requires a version 4 project');\n  }\n\n  const [project, attachedData] = fromSerializedProject(serializedProject.data);\n\n  doubleCheckProject(project);\n\n  return [project, attachedData];\n}\n\nexport function graphV4Deserializer(data: unknown): NodeGraph {\n  if (typeof data !== 'string') {\n    throw new Error('Graph v4 deserializer requires a string');\n  }\n\n  const serializedGraph = yaml.parse(data) as { version: number; data: SerializedGraph };\n\n  if (serializedGraph.version !== 4) {\n    throw new Error('Graph v4 deserializer requires a version 4 graph');\n  }\n\n  return fromSerializedGraph(serializedGraph.data);\n}\n\nexport function projectV4Serializer(project: Project, attachedData?: AttachedData): unknown {\n  const filteredProject = {\n    ...project,\n    metadata: {\n      ...project.metadata,\n      path: undefined,\n    },\n  };\n\n  // Make sure all data is ordered deterministically first\n  const stabilized = JSON.parse(stableStringify(toSerializedProject(filteredProject, attachedData)));\n\n  const serialized = yaml.stringify(\n    {\n      version: 4,\n      data: stabilized,\n    },\n    null,\n    {\n      indent: 2,\n    },\n  );\n\n  return serialized;\n}\n\nexport function graphV4Serializer(graph: NodeGraph): unknown {\n  // Make sure all data is ordered deterministically first\n  const stabilized = JSON.parse(stableStringify(toSerializedGraph(graph)));\n\n  const serialized = yaml.stringify(\n    {\n      version: 4,\n      data: stabilized,\n    },\n    null,\n    {\n      indent: 2,\n    },\n  );\n\n  return serialized;\n}\n\nfunction toSerializedProject(project: Project, attachedData?: AttachedData): SerializedProject {\n  return {\n    metadata: project.metadata,\n    graphs: mapValues(project.graphs, (graph) => toSerializedGraph(graph)),\n    attachedData,\n    plugins: project.plugins ?? [],\n    references: project.references ?? [],\n  };\n}\n\nfunction fromSerializedProject(serializedProject: SerializedProject): [Project, AttachedData] {\n  return [\n    {\n      metadata: serializedProject.metadata,\n      graphs: mapValues(serializedProject.graphs, (graph) => fromSerializedGraph(graph)) as Record<GraphId, NodeGraph>,\n      plugins: serializedProject.plugins ?? [],\n      references: serializedProject.references ?? [],\n    },\n    serializedProject.attachedData ?? {},\n  ];\n}\n\nfunction toSerializedGraph(graph: NodeGraph): SerializedGraph {\n  const graphMetadata: SerializedGraphMetadata = {\n    id: graph.metadata!.id!,\n    name: graph.metadata!.name!,\n    description: graph.metadata!.description!,\n  };\n\n  if (graph.metadata!.attachedData) {\n    graphMetadata.attachedData = graph.metadata!.attachedData;\n  }\n\n  return {\n    metadata: graphMetadata,\n    nodes: graph.nodes.reduce(\n      (acc, node) => ({\n        ...acc,\n        [getGraphNodeKey(node)]: toSerializedNode(node, graph.nodes, graph.connections),\n      }),\n      {} as Record<NodeId, SerializedNode>,\n    ),\n  };\n}\n\n/** [nodeId]:type \"Title of Node\" */\ntype SerializedGraphNodeKey = `[${NodeId}]:${string} \"${string}\"`;\n\nfunction getGraphNodeKey(node: ChartNode): string {\n  return `[${node.id}]:${node.type} \"${node.title}\"`;\n}\n\nfunction deserializeGraphNodeKey(key: string): [NodeId, string, string] {\n  const { nodeId, type, title } = key.match(/^\\[(?<nodeId>[^\\]]+)\\]:(?<type>[^\\s]+) \"(?<title>.*)\"$/)?.groups ?? {};\n  if (!nodeId || !type || !title) {\n    throw new Error(`Invalid graph node key: ${key}`);\n  }\n  return [nodeId as NodeId, type, title];\n}\n\nfunction fromSerializedGraph(serializedGraph: SerializedGraph): NodeGraph {\n  const allConnections: NodeConnection[] = [];\n  const allNodes: ChartNode[] = [];\n\n  for (const [serializedNodeInfo, node] of entries(serializedGraph.nodes)) {\n    const [chartNode, connections] = fromSerializedNode(node, serializedNodeInfo);\n    allNodes.push(chartNode);\n    allConnections.push(...connections);\n  }\n\n  const metadata: SerializedGraphMetadata = {\n    id: serializedGraph.metadata.id,\n    name: serializedGraph.metadata.name,\n    description: serializedGraph.metadata.description,\n  };\n\n  if (serializedGraph.metadata.attachedData) {\n    metadata.attachedData = serializedGraph.metadata.attachedData;\n  }\n\n  return {\n    metadata,\n    nodes: allNodes,\n    connections: allConnections,\n  };\n}\n\nfunction toSerializedNode(node: ChartNode, allNodes: ChartNode[], allConnections: NodeConnection[]): SerializedNode {\n  const outgoingConnections = allConnections\n    .filter((connection) => connection.outputNodeId === node.id)\n    .map((connection) => toSerializedConnection(connection, allNodes))\n    .sort();\n  return {\n    description: node.description?.trim() ? node.description : undefined,\n    visualData: `${node.visualData.x}/${node.visualData.y}/${node.visualData.width ?? 'null'}/${\n      node.visualData.zIndex ?? 'null'\n    }/${node.visualData.color?.border ?? ''}/${node.visualData.color?.bg ?? ''}`,\n    isSplitRun: node.isSplitRun ? true : undefined,\n    splitRunMax: node.isSplitRun ? node.splitRunMax : undefined,\n    isSplitSequential: node.isSplitSequential ? true : undefined,\n    data: Object.keys(node.data ?? {}).length > 0 ? node.data : undefined,\n    outgoingConnections: outgoingConnections.length > 0 ? outgoingConnections : undefined,\n    variants: (node.variants?.length ?? 0) > 0 ? node.variants : undefined,\n    disabled: node.disabled ? true : undefined,\n    isConditional: node.isConditional,\n  };\n}\n\nfunction fromSerializedNode(\n  serializedNode: SerializedNode,\n  serializedNodeInfo: SerializedGraphNodeKey,\n): [ChartNode, NodeConnection[]] {\n  const [nodeId, type, title] = deserializeGraphNodeKey(serializedNodeInfo);\n\n  const [x, y, width, zIndex, borderColor, bgColor] = serializedNode.visualData.split('/');\n\n  const connections =\n    serializedNode.outgoingConnections?.map((serializedConnection) =>\n      fromSerializedConnection(serializedConnection, nodeId),\n    ) ?? [];\n\n  const color = borderColor || bgColor ? { border: borderColor!, bg: bgColor! } : undefined;\n\n  return [\n    {\n      id: nodeId,\n      type,\n      title,\n      description: serializedNode.description,\n      isSplitRun: serializedNode.isSplitRun ?? false,\n      splitRunMax: serializedNode.splitRunMax ?? 10,\n      isSplitSequential: serializedNode.isSplitSequential ?? false,\n      visualData: {\n        x: parseFloat(x!),\n        y: parseFloat(y!),\n        width: width === 'null' ? undefined : parseFloat(width!),\n        zIndex: zIndex === 'null' ? undefined : parseFloat(zIndex!),\n        color,\n      },\n      data: serializedNode.data ?? {},\n      variants: serializedNode.variants ?? [],\n      disabled: serializedNode.disabled,\n      isConditional: serializedNode.isConditional,\n    },\n    connections,\n  ];\n}\n\nfunction toSerializedConnection(connection: NodeConnection, allNodes: ChartNode[]): SerializedNodeConnection {\n  return `${connection.outputId}->\"${allNodes.find((node) => node.id === connection.inputNodeId)?.title}\" ${\n    connection.inputNodeId\n  }/${connection.inputId}`;\n}\n\nfunction fromSerializedConnection(connection: SerializedNodeConnection, nodeId: NodeId): NodeConnection {\n  try {\n    const [, outputId, , inputNodeId, inputId] = connection.match(/(.+)->\"(.+)\"\\s+(.+)\\/(.+)/)!;\n\n    return {\n      outputId: outputId as PortId,\n      outputNodeId: nodeId,\n      inputId: inputId as PortId,\n      inputNodeId: inputNodeId as NodeId,\n    };\n  } catch (err) {\n    throw new Error(`Invalid connection: ${connection}`);\n  }\n}\n\nexport function datasetV4Serializer(datasets: CombinedDataset[]): string {\n  const dataContainer = {\n    datasets,\n  };\n\n  const data = JSON.stringify(dataContainer);\n\n  return data;\n}\n\nexport function datasetV4Deserializer(serializedDatasets: string): CombinedDataset[] {\n  const stringData = serializedDatasets as string;\n\n  const dataContainer = JSON.parse(stringData) as { datasets: CombinedDataset[] };\n\n  if (!dataContainer.datasets) {\n    throw new Error('Invalid dataset data');\n  }\n\n  return dataContainer.datasets;\n}\n", "/**\n * Type-safe version of {@link Object.entries} which can infer the type for the keys in the\n * returned pairs when the input object has a branded type as its key.\n *\n * @example\n * type MyId = string & { __myIdBrand: unknown };\n * // Types check out!\n * const things: [MyId, Thing][] = Objects.entries({} as Record<MyId, Thing>);\n *\n * @see {@link fromEntries}\n */\nexport const entries = <K extends string, V>(\n  // In principle we should be able to use only Partial<> as the type is a superset of the non-\n  // Partial type, but in practice this causes the compiler to infer a too-restricted type for V\n  // in some cases involving unions.\n  object: Record<K, V> | Partial<Record<K, V>> | undefined | null,\n): [K, V][] => (object == null ? [] : (Object.entries(object) as [K, V][]));\n\n/**\n * Type-safe version of {@link Object.fromEntries} which can infer the type for the key in the\n * returned object when the input array has a branded type as its key.\n *\n * @example\n * type MyId = string & { __myIdBrand: unknown };\n * // Types check out!\n * const things: Partial<Record<MyId, Thing>> = Objects.fromEntries([] as [MyId, Thing][]);\n *\n * @see {@link entries}\n */\n// This returns a Partial<> because we can't guarantee that every key is present when K is a\n// string literal union (which is what Record<K, V> would be saying). As a side effect, this means\n// that using this with branded IDs will force null checks downstream, which is good practice.\nexport function fromEntries<K extends string, V>(entries_: Iterable<[K, V]>): Partial<Record<K, V>> {\n  return Object.fromEntries(entries_) as Partial<Record<K, V>>;\n}\n\n/**\n * Type safe version of Object.keys()\n */\nexport function keys<K extends string>(o: Record<K, unknown>): K[];\nexport function keys<T>(o: T): (keyof T)[];\nexport function keys(o: object) {\n  return Object.keys(o);\n}\n\n/**\n * Type safe version of Object.values()\n */\nexport function values<V extends string>(o: Record<keyof any, V>): V[];\nexport function values<T>(o: T): T[keyof T][];\nexport function values(o: object) {\n  return Object.values(o);\n}\n\nexport function mapValues<T extends object, U>(\n  o: T,\n  fn: (value: T[keyof T]) => U,\n): {\n  [K in keyof T]: U;\n} {\n  return Object.fromEntries(Object.entries(o).map(([key, value]) => [key, fn(value)])) as any;\n}\n", "import { nanoid } from 'nanoid/non-secure';\nimport { type ChartNode, type NodeConnection } from './NodeBase.js';\nimport type { Opaque } from 'type-fest';\nimport { type AttachedData } from '../utils/serialization/serializationUtils.js';\n\nexport type GraphId = Opaque<string, 'GraphId'>;\n\nexport interface NodeGraph {\n  metadata?: {\n    id?: GraphId;\n    name?: string;\n    description?: string;\n\n    attachedData?: AttachedData;\n  };\n\n  nodes: ChartNode[];\n  connections: NodeConnection[];\n}\n\nexport function emptyNodeGraph(): NodeGraph {\n  return {\n    nodes: [],\n    connections: [],\n    metadata: {\n      id: nanoid() as GraphId,\n      name: 'Untitled Graph',\n      description: '',\n    },\n  };\n}\n", "import type { Opaque } from 'type-fest';\nimport type { DataType } from './DataValue.js';\nimport type { GraphId } from '../index.js';\n\n/** Unique in a NodeGraph. */\nexport type NodeId = Opaque<string, 'NodeId'>;\n\n/** Unique within the inputs of a single node */\nexport type PortId = Opaque<string, 'PortId'>;\n\n/** Base interface for a node in a NodeGraph. All nodes will have this data.*/\nexport interface NodeBase {\n  /** The type of the node. See Nodes['type']. */\n  type: string;\n\n  /** The unique identifier of the node. Unique within a NodeGraph. */\n  id: NodeId;\n\n  /** The title of the node. Displayed in the graph. */\n  title: string;\n\n  /** A user description/notes for the node */\n  description?: string;\n\n  isSplitRun?: boolean;\n\n  /** When splitting, should the executions be ran sequentially instead of in parallel? */\n  isSplitSequential?: boolean;\n\n  splitRunMax?: number;\n\n  /** The visual data of the node, including its position. Visual data does not affect its processing. */\n  visualData: {\n    /** The x-coordinate of the node's position. */\n    x: number;\n\n    /** The y-coordinate of the node's position. */\n    y: number;\n\n    width?: number;\n\n    /** The accent color of the node in the UI. */\n    color?: {\n      border: string;\n      bg: string;\n    };\n\n    /** The z-index, the last grabbed node is on top of all others. */\n    zIndex?: number;\n  };\n\n  /** The data associated with the node. Typed when using `Nodes` or a subtype. */\n  data: unknown;\n\n  /** Alternative sets of data for the node. */\n  variants?: ChartNodeVariant<unknown>[];\n\n  tests?: NodeTestGroup[];\n\n  /** If true, the node is disabled and effectively \"not ran\" */\n  disabled?: boolean;\n\n  /** If true, the node exposes an `if` port that lets it run conditionally. */\n  isConditional?: boolean;\n}\n\n/** Base type for a typed node. */\nexport type ChartNode<Type extends string = string, Data = unknown> = NodeBase & {\n  /** The type of the node. */\n  type: Type;\n\n  /** The data associated with the node. */\n  data: Data;\n\n  /** Alternative sets of data for the node. */\n  variants?: ChartNodeVariant<Data>[];\n};\n\nexport type ChartNodeVariant<Data = unknown> = {\n  id: string;\n  data: Data;\n};\n\nexport type NodeTestGroup = {\n  id: string;\n  evaluatorGraphId: GraphId;\n  tests: NodeTest[];\n};\n\nexport type NodeTest = {\n  conditionText: string;\n};\n\n/** Represents an input definition of a node. */\nexport type NodeInputDefinition = {\n  /** The unique identifier of the input. Unique within a single node only. */\n  id: PortId;\n\n  /** The title of the input. Shows in the UI. */\n  title: string;\n\n  /** Whether the input is required. If it is required, there is no default value, and the node cannot process if this input is not connected. */\n  required?: boolean;\n\n  /** The data type of the input. */\n  dataType: DataType | Readonly<DataType[]>;\n\n  /** Other data associated with the input. Typed in subtypes. */\n  data?: unknown;\n\n  /** The default value of the input, if it is not connected to an output. */\n  defaultValue?: unknown;\n\n  /** User-facing description of the port. */\n  description?: string;\n\n  /** Will the input value attempt to be coerced into the desired type? */\n  coerced?: boolean;\n};\n\n/** Represents an output definition of a node. */\nexport type NodeOutputDefinition = {\n  /** The unique identifier of the output. Unique within a single node. */\n  id: PortId;\n\n  /** The title of the output. Shown in the UI. */\n  title: string;\n\n  /** The data type of the output. */\n  dataType: DataType | Readonly<DataType[]>;\n\n  /** The data associated with the output. */\n  data?: unknown;\n\n  /** The default value of the output. Some outputs just have a fixed value. */\n  defaultValue?: unknown;\n\n  /** User-facing description of the port. */\n  description?: string;\n};\n\n/** Represents a connection between two nodes. */\nexport type NodeConnection = {\n  /** The unique identifier of the output node. */\n  outputNodeId: NodeId;\n\n  /** The unique identifier of the input node. */\n  inputNodeId: NodeId;\n\n  /** The unique identifier of the output. */\n  outputId: PortId;\n\n  /** The unique identifier of the input. */\n  inputId: PortId;\n};\n\nexport const IF_PORT: NodeInputDefinition = {\n  id: `$if` as PortId,\n  title: 'if',\n  dataType: 'boolean',\n  coerced: true,\n  description: 'Only run the node if this condition is true',\n  defaultValue: 'false',\n};\n\nexport function isBuiltInInputDefinition(input: NodeInputDefinition): boolean {\n  return input.id === IF_PORT.id;\n}\n", "import type { Project, NodeGraph } from '../../index.js';\nimport { doubleCheckProject } from './serializationUtils.js';\n// @ts-ignore\nimport * as yaml from 'yaml';\n\nexport function projectV2Deserializer(data: unknown): Project {\n  if (typeof data !== 'string') {\n    throw new Error('Project v2 deserializer requires a string');\n  }\n\n  const project = yaml.parse(data) as { version: number; data: Project };\n\n  if (project.version !== 2) {\n    throw new Error('Project v2 deserializer requires a version 2 project');\n  }\n\n  doubleCheckProject(project.data);\n\n  return project.data;\n}\n\nexport function graphV2Deserializer(data: unknown): NodeGraph {\n  if (typeof data !== 'string') {\n    throw new Error('Graph v2 deserializer requires a string');\n  }\n\n  const graph = yaml.parse(data) as { version: number; data: NodeGraph };\n\n  if (graph.version !== 2) {\n    throw new Error('Graph v2 deserializer requires a version 2 graph');\n  }\n\n  return graph.data;\n}\n", "import type { Project, NodeGraph } from '../../index.js';\nimport { doubleCheckProject } from './serializationUtils.js';\n\nexport function projectV1Deserializer(data: unknown): Project {\n  if (typeof data !== 'string') {\n    throw new Error('Project v1 deserializer requires a string');\n  }\n\n  const project = JSON.parse(data);\n\n  doubleCheckProject(project);\n\n  return project;\n}\n\nexport function graphV1Deserializer(data: unknown): NodeGraph {\n  if (typeof data !== 'string') {\n    throw new Error('Graph v1 deserializer requires a string');\n  }\n\n  const graph = JSON.parse(data);\n\n  if (!graph.nodes || !graph.connections) {\n    throw new Error('Invalid graph file');\n  }\n\n  return graph;\n}\n", "import type { PortId } from '../model/NodeBase.js';\n\nexport const Warnings = '__internalPort_Warnings';\nexport const WarningsPort = Warnings as unknown as PortId;\n", "import type { Outputs } from '../index.js';\nimport type { ArrayDataValue, StringDataValue } from '../model/DataValue.js';\nimport { expectType } from './expectType.js';\nimport { WarningsPort } from './symbols.js';\n\nexport function addWarning(outputs: Outputs, warning: string): void {\n  if (!outputs[WarningsPort]) {\n    outputs[WarningsPort] = { type: 'string[]', value: [] };\n  }\n\n  (outputs[WarningsPort] as ArrayDataValue<StringDataValue>).value.push(warning);\n}\n\nexport function getWarnings(outputs: Outputs | undefined): string[] | undefined {\n  if (!outputs?.[WarningsPort]) {\n    return undefined;\n  }\n\n  return expectType(outputs[WarningsPort], 'string[]');\n}\n", "export async function uint8ArrayToBase64(uint8Array: Uint8Array) {\n  if (typeof window === 'undefined') {\n    // Node executor\n    return Buffer.from(uint8Array).toString('base64');\n  } else {\n    // Browser executor\n    const blob = new Blob([uint8Array], { type: 'application/octet-stream' });\n    const dataUrl = await new Promise<string>((resolve) => {\n      const reader = new FileReader();\n      reader.onload = () => resolve(reader.result as string);\n      reader.readAsDataURL(blob);\n    });\n    return dataUrl.split(',')[1];\n  }\n}\n\nexport function uint8ArrayToBase64Sync(uint8Array: Uint8Array) {\n  if (typeof window === 'undefined') {\n    // Node executor\n    return Buffer.from(uint8Array).toString('base64');\n  } else {\n    // Browser executor\n    const binary = Array.from(uint8Array)\n      .map((byte) => String.fromCharCode(byte))\n      .join('');\n    return btoa(binary);\n  }\n}\n\nexport function base64ToUint8Array(base64: string) {\n  const binaryString = atob(base64);\n  const len = binaryString.length;\n  const bytes = new Uint8Array(len);\n  for (let i = 0; i < len; i++) {\n    bytes[i] = binaryString.charCodeAt(i);\n  }\n  return bytes;\n}\n", "import type { DataType, GetDataValue, Inputs, PortId } from '../index.js';\nimport { coerceTypeOptional } from './coerceType.js';\nimport { entries } from './typeSafety.js';\n\nexport function getInputOrData<Data extends object, T extends DataType = 'string'>(\n  data: Data,\n  inputs: Inputs,\n  inputAndDataKey: keyof Data & string,\n  type?: T,\n  useInputToggleDataKey?: keyof Data & string,\n): GetDataValue<T>['value'] {\n  if (!useInputToggleDataKey) {\n    const capitalized = inputAndDataKey[0]!.toUpperCase() + inputAndDataKey.slice(1);\n    const key = `use${capitalized}Input` as keyof Data & string;\n    useInputToggleDataKey = key;\n  }\n  const value =\n    data[useInputToggleDataKey] && inputs[inputAndDataKey as PortId] != null\n      ? coerceTypeOptional(inputs[inputAndDataKey as PortId], type ?? 'string') ?? data[inputAndDataKey]\n      : data[inputAndDataKey];\n  return value as GetDataValue<T>['value'];\n}\n\nexport function cleanHeaders(headers: Record<string, string>): Record<string, string> {\n  return Object.fromEntries(entries(headers).filter(([key]) => key.trim()));\n}\n", "export { dedent } from 'ts-dedent';\n", "import type { RivetPlugin, Settings, StringPluginConfigurationSpec } from '../index.js';\n\nexport function getPluginConfig(plugin: RivetPlugin | undefined, settings: Settings, name: string) {\n  if (!plugin) {\n    return undefined;\n  }\n\n  const configSpec = plugin?.configSpec?.[name];\n\n  if (!configSpec) {\n    return undefined;\n  }\n\n  const pluginSettings = settings.pluginSettings?.[plugin.id];\n  if (pluginSettings) {\n    const value = pluginSettings[name];\n    if (!value || typeof value !== 'string') {\n      return undefined;\n    }\n\n    return value;\n  }\n\n  const envFallback = (configSpec as StringPluginConfigurationSpec).pullEnvironmentVariable;\n  const envFallbackName = envFallback === true ? name : envFallback;\n\n  if (envFallbackName && settings.pluginEnv?.[envFallbackName]) {\n    return settings.pluginEnv[envFallbackName];\n  }\n\n  return undefined;\n}\n", "import { nanoid } from 'nanoid/non-secure';\n\nexport function newId<T extends string>(): T {\n  return nanoid() as T;\n}\n", "/** Let the user type things like \\n and \\t in the editor, and they'll be replaced with the actual characters. */\nexport function handleEscapeCharacters(inputString: string): string {\n  // Would use negative lookbehind but not supported in some recent safari versions >.<\n  return inputString\n    .replace(/([^\\\\]|^)\\\\n/g, '$1\\n')\n    .replace(/([^\\\\]|^)\\\\t/g, '$1\\t')\n    .replace(/([^\\\\]|^)\\\\r/g, '$1\\r')\n    .replace(/([^\\\\]|^)\\\\f/g, '$1\\f')\n    .replace(/([^\\\\]|^)\\\\b/g, '$1\\b')\n    .replace(/([^\\\\]|^)\\\\v/g, '$1\\v');\n}\n", "import { isArrayDataType, type DataType } from '../model/DataValue.js';\n\nexport function isDataTypeAccepted(\n  inputType: DataType | Readonly<DataType[]>,\n  accepted: DataType | Readonly<DataType[]>,\n) {\n  inputType = Array.isArray(inputType) ? inputType : [inputType];\n  accepted = Array.isArray(accepted) ? accepted : [accepted];\n\n  for (const input of inputType) {\n    for (const accept of accepted) {\n      if (isDataTypeCompatible(input, accept)) {\n        return true;\n      }\n    }\n  }\n\n  return false;\n}\n\nexport function isDataTypeCompatible(inputType: DataType, accepted: DataType): boolean {\n  // Any is always compatible on either side\n  if (inputType === 'any' || accepted === 'any') {\n    return true;\n  }\n\n  // If they're both arrays, and either is 'any[]', it's compatible\n  if (isArrayDataType(inputType) && isArrayDataType(accepted) && (inputType === 'any[]' || accepted === 'any[]')) {\n    return true;\n  }\n\n  if (inputType === accepted) {\n    return true;\n  }\n\n  return false;\n}\n", "export const DEFAULT_CHAT_ENDPOINT = 'https://api.openai.com/v1/chat/completions';\n\nexport const DEFAULT_CHAT_NODE_TIMEOUT = 30_000;\n", "import { max, range, sum, uniqBy } from 'lodash-es';\nimport {\n  type DataValue,\n  type ArrayDataValue,\n  type AnyDataValue,\n  type StringArrayDataValue,\n  type ControlFlowExcludedDataValue,\n  isArrayDataValue,\n  arrayizeDataValue,\n  type ScalarOrArrayDataValue,\n  getScalarTypeOf,\n} from './DataValue.js';\nimport {\n  IF_PORT,\n  type ChartNode,\n  type NodeConnection,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from './NodeBase.js';\nimport type { GraphId, NodeGraph } from './NodeGraph.js';\nimport type { NodeImpl } from './NodeImpl.js';\nimport type { UserInputNode } from './nodes/UserInputNode.js';\nimport PQueueImport from 'p-queue';\nimport { getError } from '../utils/errors.js';\nimport Emittery from 'emittery';\nimport { entries, fromEntries, values } from '../utils/typeSafety.js';\nimport { isNotNull } from '../utils/genericUtilFunctions.js';\nimport { type ProjectId, type Project, type ProjectReference } from './Project.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport type { InternalProcessContext, ProcessContext, ProcessId } from './ProcessContext.js';\nimport type { ExecutionRecorder } from '../recording/ExecutionRecorder.js';\nimport { P, match } from 'ts-pattern';\nimport type { Tagged } from 'type-fest';\nimport { coerceTypeOptional } from '../utils/coerceType.js';\nimport { globalRivetNodeRegistry } from './Nodes.js';\nimport type { BuiltInNodeType, BuiltInNodes } from './Nodes.js';\nimport type { NodeRegistration } from './NodeRegistration.js';\nimport { getPluginConfig } from '../utils/index.js';\nimport { GptTokenizerTokenizer } from '../integrations/GptTokenizerTokenizer.js';\n\n// eslint-disable-next-line import/no-cycle -- There has to be a cycle because CodeRunner needs to import the entirety of Rivet\nimport { IsomorphicCodeRunner } from '../integrations/CodeRunner.js';\n\n// CJS compatibility, gets default.default for whatever reason\nlet PQueue = PQueueImport;\nif (typeof PQueue !== 'function') {\n  PQueue = (PQueueImport as any).default;\n}\n\nexport type ProcessEvents = {\n  /** Called when processing has started. */\n  start: { project: Project; startGraph: NodeGraph; inputs: GraphInputs; contextValues: Record<string, DataValue> };\n\n  /** Called when a graph or subgraph has started. */\n  graphStart: { graph: NodeGraph; inputs: GraphInputs };\n\n  /** Called when a graph or subgraph has errored. */\n  graphError: { graph: NodeGraph; error: Error | string };\n\n  /** Called when a graph or a subgraph has finished. */\n  graphFinish: { graph: NodeGraph; outputs: GraphOutputs };\n\n  /** Called when a graph has been aborted. */\n  graphAbort: { successful: boolean; graph: NodeGraph; error?: Error | string };\n\n  /** Called when a node has started processing, with the input values for the node. */\n  nodeStart: { node: ChartNode; inputs: Inputs; processId: ProcessId };\n\n  /** Called when a node has finished processing, with the output values for the node. */\n  nodeFinish: { node: ChartNode; outputs: Outputs; processId: ProcessId };\n\n  /** Called when a node has errored during processing. */\n  nodeError: { node: ChartNode; error: Error | string; processId: ProcessId };\n\n  /** Called when a node has been excluded from processing. */\n  nodeExcluded: { node: ChartNode; processId: ProcessId; inputs: Inputs; outputs: Outputs; reason: string };\n\n  /** Called when a user input node requires user input. Call the callback when finished, or call userInput() on the GraphProcessor with the results. */\n  userInput: {\n    node: ChartNode;\n    inputStrings: string[];\n\n    /** @deprecated use inputStrings instead */\n    inputs: Inputs;\n\n    callback: (values: StringArrayDataValue) => void;\n    processId: ProcessId;\n\n    renderingType: 'text' | 'markdown';\n  };\n\n  /** Called when a node has partially processed, with the current partial output values for the node. */\n  partialOutput: { node: ChartNode; outputs: Outputs; index: number; processId: ProcessId };\n\n  /** Called when the outputs of a node have been cleared entirely. If processId is present, only the one process() should be cleared. */\n  nodeOutputsCleared: { node: ChartNode; processId?: ProcessId };\n\n  /** Called when the root graph has errored. The root graph will also throw. */\n  error: { error: Error | string };\n\n  /** Called when processing has completed. */\n  done: { results: GraphOutputs };\n\n  /** Called when processing has been aborted. */\n  abort: { successful: boolean; error?: string | Error };\n\n  /** Called when processing has finished either successfully or unsuccessfully. */\n  finish: void;\n\n  /** Called for trace level logs. */\n  trace: string;\n\n  /** Called when the graph has been paused. */\n  pause: void;\n\n  /** Called when the graph has been resumed. */\n  resume: void;\n\n  /** Called when a global variable has been set in a graph. */\n  globalSet: { id: string; value: ScalarOrArrayDataValue; processId: ProcessId };\n\n  /** Called when an AbortController has been created. Used by node to increase the max event listeners. */\n  newAbortController: AbortController;\n} & {\n  /** Listen for any user event. */\n  [key: `userEvent:${string}`]: DataValue | undefined;\n} & {\n  [key: `globalSet:${string}`]: ScalarOrArrayDataValue | undefined;\n};\n\nexport type ProcessEvent = {\n  [P in keyof ProcessEvents]: { type: P } & ProcessEvents[P];\n}[keyof ProcessEvents];\n\nexport type GraphOutputs = Record<string, DataValue>;\nexport type GraphInputs = Record<string, DataValue>;\n\nexport type NodeResults = Map<NodeId, Outputs>;\nexport type Inputs = Record<PortId, DataValue | undefined>;\nexport type Outputs = Record<PortId, DataValue | undefined>;\n\nexport type ExternalFunctionProcessContext = Omit<InternalProcessContext, 'setGlobal'>;\n\nexport type ExternalFunction = (\n  context: ExternalFunctionProcessContext,\n  ...args: unknown[]\n) => Promise<DataValue & { cost?: number }>;\n\nexport type RaceId = Tagged<string, 'RaceId'>;\n\nexport type LoopInfo = AttachedNodeDataItem & {\n  /** ID of the controller of the loop */\n  loopControllerId: NodeId;\n\n  /** Nodes add themselves to this as the loop processes */\n  nodes: Set<NodeId>;\n\n  iterationCount: number;\n};\n\nexport type AttachedNodeDataItem = {\n  propagate: boolean | ((parent: ChartNode, connections: NodeConnection[]) => boolean);\n};\n\nexport type AttachedNodeData = {\n  loopInfo?: LoopInfo;\n  races?: {\n    propagate: boolean;\n    raceIds: RaceId[];\n\n    // The race is completed by some branch\n    completed: boolean;\n  };\n\n  [key: string]: AttachedNodeDataItem | undefined;\n};\n\nexport class GraphProcessor {\n  // Per-instance state\n  readonly #graph: NodeGraph;\n  readonly #project: Project;\n  readonly #nodesById: Record<NodeId, ChartNode>;\n  readonly #nodeInstances: Record<NodeId, NodeImpl<ChartNode>>;\n  readonly #connections: Record<NodeId, NodeConnection[]>;\n  readonly #emitter: Emittery<ProcessEvents> = new Emittery();\n  #running = false;\n  #isSubProcessor = false;\n  #externalFunctions: Record<string, ExternalFunction> = {};\n  slowMode = false;\n  #isPaused = false;\n  #parent: GraphProcessor | undefined;\n  readonly #registry: NodeRegistration<any, any>;\n  id = nanoid();\n\n  readonly #includeTrace?: boolean = true;\n\n  executor?: 'nodejs' | 'browser';\n\n  /** If set, specifies the node(s) that the graph will run TO, instead of the nodes without any dependents. */\n  runToNodeIds?: NodeId[];\n\n  /** If set, specifies the node that the graph will run FROM, instead of the start nodes. Requires preloading data. */\n  runFromNodeId?: NodeId;\n\n  /** The node that is executing this graph, almost always a subgraph node. Undefined for root. */\n  #executor:\n    | {\n        nodeId: NodeId;\n        index: number;\n        processId: ProcessId;\n      }\n    | undefined;\n\n  /** The interval between nodeFinish events when playing back a recording. I.e. how fast the playback is. */\n  recordingPlaybackChatLatency = 1000;\n\n  warnOnInvalidGraph = false;\n\n  // Per-process state\n  #erroredNodes: Map<NodeId, Error | string> = undefined!; // Values are strings in recordings\n  #remainingNodes: Set<NodeId> = undefined!;\n  #visitedNodes: Set<NodeId> = undefined!;\n  #currentlyProcessing: Set<NodeId> = undefined!;\n  #context: ProcessContext = undefined!;\n  #nodeResults: NodeResults = undefined!;\n  #abortController: AbortController = undefined!;\n  #processingQueue: PQueueImport = undefined!;\n  #graphInputs: GraphInputs = undefined!;\n  #graphOutputs: GraphOutputs = undefined!;\n  #executionCache: Map<string, unknown> = undefined!;\n  #queuedNodes: Set<NodeId> = undefined!;\n  #loopControllersSeen: Set<NodeId> = undefined!;\n  #subprocessors: Set<GraphProcessor> = undefined!;\n  #contextValues: Record<string, DataValue> = undefined!;\n  #globals: Map<string, ScalarOrArrayDataValue> = undefined!;\n  #attachedNodeData: Map<NodeId, AttachedNodeData> = undefined!;\n  #aborted = false;\n  #abortSuccessfully = false;\n  #abortError: Error | string | undefined = undefined;\n  #totalCost: number = 0;\n  #ignoreNodes: Set<NodeId> = undefined!;\n  #hasPreloadedData = false;\n  #loadedProjects: Record<ProjectId, Project> = undefined!;\n  #definitions: Record<NodeId, { inputs: NodeInputDefinition[]; outputs: NodeOutputDefinition[] }> = undefined!;\n  #scc: ChartNode[][] = undefined!;\n\n  // @ts-expect-error\n  #nodesNotInCycle: ChartNode[] = undefined!;\n\n  #nodeAbortControllers = new Map<`${NodeId}-${ProcessId}`, AbortController>();\n\n  #graphInputNodeValues: Record<string, DataValue> = {};\n\n  /** User input nodes that are pending user input. */\n  #pendingUserInputs: Record<\n    NodeId,\n    { resolve: (values: StringArrayDataValue) => void; reject: (error: unknown) => void }\n  > = undefined!;\n\n  get isRunning() {\n    return this.#running;\n  }\n\n  constructor(project: Project, graphId?: GraphId, registry?: NodeRegistration<any, any>, includeTrace?: boolean) {\n    this.#project = project;\n    const graph = graphId\n      ? project.graphs[graphId]\n      : project.metadata.mainGraphId\n        ? project.graphs[project.metadata.mainGraphId]\n        : undefined;\n\n    if (!graph) {\n      throw new Error(`Graph ${graphId} not found in project`);\n    }\n    this.#graph = graph;\n\n    this.#includeTrace = includeTrace;\n    this.#nodeInstances = {};\n    this.#connections = {};\n    this.#nodesById = {};\n    this.#registry = registry ?? (globalRivetNodeRegistry as unknown as NodeRegistration);\n\n    this.#emitter.bindMethods(this as any, ['on', 'off', 'once', 'onAny', 'offAny']);\n\n    this.setExternalFunction('echo', async (value) => ({ type: 'any', value }) satisfies DataValue);\n\n    this.#emitter.on('globalSet', ({ id, value }) => {\n      // eslint-disable-next-line @typescript-eslint/no-floating-promises\n      this.#emitter.emit(`globalSet:${id}`, value);\n    });\n  }\n\n  #preprocessGraph() {\n    // Create node instances and store them in a lookup table\n    for (const node of this.#graph.nodes) {\n      this.#nodeInstances[node.id] = this.#registry.createDynamicImpl(node);\n      this.#nodesById[node.id] = node;\n    }\n\n    // Store connections in a lookup table\n    for (const conn of this.#graph.connections) {\n      if (!this.#nodesById[conn.inputNodeId] || !this.#nodesById[conn.outputNodeId]) {\n        if (this.warnOnInvalidGraph) {\n          if (!this.#nodesById[conn.inputNodeId]) {\n            console.warn(\n              `Missing node ${conn.inputNodeId} in graph ${this.#graph} (connection from ${\n                this.#nodesById[conn.outputNodeId]?.title\n              })`,\n            );\n          } else {\n            console.warn(\n              `Missing node ${conn.outputNodeId} in graph ${this.#graph} (connection to ${\n                this.#nodesById[conn.inputNodeId]?.title\n              }) `,\n            );\n          }\n        }\n        continue;\n      }\n\n      this.#connections[conn.inputNodeId] ??= [];\n      this.#connections[conn.outputNodeId] ??= [];\n      this.#connections[conn.inputNodeId]!.push(conn);\n      this.#connections[conn.outputNodeId]!.push(conn);\n    }\n\n    this.#loadInputOutputDefinitions();\n\n    this.#scc = this.#tarjanSCC();\n    this.#nodesNotInCycle = this.#scc.filter((cycle) => cycle.length === 1).flat();\n  }\n\n  #loadInputOutputDefinitions() {\n    // Store input and output definitions in a lookup table\n    this.#definitions = {};\n    for (const node of this.#graph.nodes) {\n      const connectionsForNode = this.#connections[node.id] ?? [];\n\n      const inputDefs = this.#nodeInstances[node.id]!.getInputDefinitionsIncludingBuiltIn(\n        connectionsForNode,\n        this.#nodesById,\n        this.#project,\n        this.#loadedProjects,\n      );\n\n      const outputDefs = this.#nodeInstances[node.id]!.getOutputDefinitions(\n        connectionsForNode,\n        this.#nodesById,\n        this.#project,\n        this.#loadedProjects,\n      );\n\n      this.#definitions[node.id] = { inputs: inputDefs, outputs: outputDefs };\n\n      // Find all invalid connections to or from the node, then remove them from consideration\n      const invalidConnections = connectionsForNode.filter((connection) => {\n        if (connection.inputNodeId === node.id) {\n          const inputDef = inputDefs.find((def) => def.id === connection.inputId);\n\n          if (!inputDef) {\n            if (this.warnOnInvalidGraph) {\n              const nodeFrom = this.#nodesById[connection.outputNodeId];\n              console.warn(\n                `[Warn] Invalid connection going from \"${nodeFrom?.title}\".${connection.outputId} to \"${node.title}\".${connection.inputId}`,\n              );\n            }\n\n            return true;\n          }\n        } else {\n          const outputDef = outputDefs.find((def) => def.id === connection.outputId);\n\n          if (!outputDef) {\n            if (this.warnOnInvalidGraph) {\n              const nodeTo = this.#nodesById[connection.inputNodeId];\n              console.warn(\n                `[Warn] Invalid connection going from \"${node.title}\".${connection.outputId} to \"${nodeTo?.title}\".${connection.inputId}`,\n              );\n            }\n\n            return true;\n          }\n        }\n\n        return false;\n      });\n\n      for (const connections of values(this.#connections)) {\n        for (const invalidConnection of invalidConnections) {\n          const index = connections.indexOf(invalidConnection);\n          if (index !== -1) {\n            connections.splice(index, 1);\n          }\n        }\n      }\n    }\n  }\n\n  #emitTraceEvent(eventData: string) {\n    if (this.#includeTrace) {\n      // eslint-disable-next-line @typescript-eslint/no-floating-promises\n      this.#emitter.emit('trace', eventData);\n    }\n  }\n\n  on = undefined! as Emittery<ProcessEvents>['on'];\n  off = undefined! as Emittery<ProcessEvents>['off'];\n  once = undefined! as Emittery<ProcessEvents>['once'];\n  onAny = undefined! as Emittery<ProcessEvents>['onAny'];\n  offAny = undefined! as Emittery<ProcessEvents>['offAny'];\n\n  readonly #onUserEventHandlers: Map<(event: DataValue | undefined) => void, Function> = new Map();\n\n  onUserEvent(onEvent: string, listener: (event: DataValue | undefined) => void): void {\n    const handler = (event: string, value: unknown) => {\n      if (event === `userEvent:${onEvent}`) {\n        listener(value as DataValue | undefined);\n      }\n    };\n\n    this.#onUserEventHandlers.set(listener, handler);\n    this.#emitter.onAny(handler);\n  }\n\n  offUserEvent(listener: (data: DataValue | undefined) => void): void {\n    const internalHandler = this.#onUserEventHandlers.get(listener);\n    this.#emitter.offAny(internalHandler as any);\n  }\n\n  userInput(nodeId: NodeId, values: StringArrayDataValue): void {\n    const pending = this.#pendingUserInputs[nodeId];\n    if (pending) {\n      pending.resolve(values as StringArrayDataValue);\n      delete this.#pendingUserInputs[nodeId];\n    }\n\n    for (const processor of this.#subprocessors) {\n      processor.userInput(nodeId, values);\n    }\n  }\n\n  setExternalFunction(name: string, fn: ExternalFunction): void {\n    this.#externalFunctions[name] = fn;\n  }\n\n  async abort(successful: boolean = false, error?: Error | string): Promise<void> {\n    if (!this.#running || this.#aborted) {\n      return Promise.resolve();\n    }\n\n    this.#abortController.abort();\n    this.#abortSuccessfully = successful;\n    this.#abortError = error;\n\n    // eslint-disable-next-line @typescript-eslint/no-floating-promises\n    this.#emitter.emit('graphAbort', { successful, error, graph: this.#graph });\n\n    if (!this.#isSubProcessor) {\n      // eslint-disable-next-line @typescript-eslint/no-floating-promises\n      this.#emitter.emit('abort', { successful, error });\n    }\n\n    await this.#processingQueue.onIdle();\n  }\n\n  pause(): void {\n    if (this.#isPaused === false) {\n      this.#isPaused = true;\n      // eslint-disable-next-line @typescript-eslint/no-floating-promises\n      this.#emitter.emit('pause', void 0);\n    }\n  }\n\n  resume(): void {\n    if (this.#isPaused) {\n      this.#isPaused = false;\n      // eslint-disable-next-line @typescript-eslint/no-floating-promises\n      this.#emitter.emit('resume', void 0);\n    }\n  }\n\n  setSlowMode(slowMode: boolean): void {\n    this.slowMode = slowMode;\n  }\n\n  async #waitUntilUnpaused(): Promise<void> {\n    if (!this.#isPaused) {\n      return;\n    }\n\n    await this.#emitter.once('resume');\n  }\n\n  async *events(): AsyncGenerator<ProcessEvent> {\n    for await (const [event, data] of this.#emitter.anyEvent()) {\n      yield { type: event, ...(data as any) };\n\n      if (event === 'finish') {\n        break;\n      }\n    }\n  }\n\n  preloadNodeData(nodeId: NodeId, data: Outputs): void {\n    this.#nodeResults ??= new Map();\n    this.#visitedNodes ??= new Set();\n\n    for (const value of Object.values(data)) {\n      if (!value || !('type' in value) || !value.type) {\n        throw new Error(`Invalid data value for node ${nodeId}, must be a DataValue`);\n      }\n    }\n\n    this.#nodeResults.set(nodeId, data);\n    this.#visitedNodes.add(nodeId);\n    this.#hasPreloadedData = true;\n  }\n\n  /** Gets all node IDs that a given node ID depends on being complete before the given node ID can start. */\n  getDependencyNodesDeep(nodeId: NodeId): NodeId[] {\n    const node = this.#nodesById[nodeId];\n    if (!node) {\n      return [];\n    }\n\n    const connections = this.#connections[nodeId];\n    if (!connections) {\n      return [];\n    }\n\n    const dependencyNodes = connections\n      .map((conn) => {\n        if (conn.inputNodeId === nodeId) {\n          return this.getDependencyNodesDeep(conn.outputNodeId);\n        }\n        return [];\n      })\n      .flat();\n\n    return [...new Set([nodeId, ...dependencyNodes])];\n  }\n\n  async replayRecording(recorder: ExecutionRecorder): Promise<GraphOutputs> {\n    const { events } = recorder;\n\n    this.#initProcessState();\n\n    try {\n      const nodesByIdAllGraphs: Record<NodeId, ChartNode> = {};\n      for (const graph of Object.values(this.#project.graphs)) {\n        for (const node of graph.nodes) {\n          nodesByIdAllGraphs[node.id] = node;\n        }\n      }\n\n      const getGraph = (graphId: GraphId) => {\n        const graph = this.#project.graphs[graphId];\n        if (!graph) {\n          throw new Error(`Mismatch between project and recording: graph ${graphId} not found in project`);\n        }\n        return graph;\n      };\n\n      const getNode = (nodeId: NodeId) => {\n        const node = nodesByIdAllGraphs[nodeId];\n\n        if (!node) {\n          throw new Error(`Mismatch between project and recording: node ${nodeId} not found in any graph in project`);\n        }\n\n        return node;\n      };\n\n      for (const event of events) {\n        if (this.#aborted) {\n          break;\n        }\n\n        await this.#waitUntilUnpaused();\n\n        await match(event)\n          .with({ type: 'start' }, ({ data }) => {\n            // eslint-disable-next-line @typescript-eslint/no-floating-promises\n            this.#emitter.emit('start', {\n              project: this.#project,\n              contextValues: data.contextValues,\n              inputs: data.inputs,\n              startGraph: getGraph(data.startGraph),\n            });\n            this.#contextValues = data.contextValues;\n            this.#graphInputs = data.inputs;\n          })\n          .with({ type: 'abort' }, ({ data }) => {\n            // eslint-disable-next-line @typescript-eslint/no-floating-promises\n            this.#emitter.emit('abort', data);\n          })\n          .with({ type: 'pause' }, () => {})\n          .with({ type: 'resume' }, () => {})\n          .with({ type: 'done' }, ({ data }) => {\n            // eslint-disable-next-line @typescript-eslint/no-floating-promises\n            this.#emitter.emit('done', data);\n            this.#graphOutputs = data.results;\n            this.#running = false;\n          })\n          .with({ type: 'error' }, ({ data }) => {\n            // eslint-disable-next-line @typescript-eslint/no-floating-promises\n            this.#emitter.emit('error', data);\n          })\n          .with({ type: 'globalSet' }, ({ data }) => {\n            // eslint-disable-next-line @typescript-eslint/no-floating-promises\n            this.#emitter.emit('globalSet', data);\n          })\n          .with({ type: 'trace' }, ({ data }) => {\n            // eslint-disable-next-line @typescript-eslint/no-floating-promises\n            this.#emitter.emit('trace', data);\n          })\n          .with({ type: 'graphStart' }, ({ data }) => {\n            // eslint-disable-next-line @typescript-eslint/no-floating-promises\n            this.#emitter.emit('graphStart', {\n              graph: getGraph(data.graphId),\n              inputs: data.inputs,\n            });\n          })\n          .with({ type: 'graphFinish' }, ({ data }) => {\n            // eslint-disable-next-line @typescript-eslint/no-floating-promises\n            this.#emitter.emit('graphFinish', {\n              graph: getGraph(data.graphId),\n              outputs: data.outputs,\n            });\n          })\n          .with({ type: 'graphError' }, ({ data }) => {\n            // eslint-disable-next-line @typescript-eslint/no-floating-promises\n            this.#emitter.emit('graphError', {\n              graph: getGraph(data.graphId),\n              error: data.error,\n            });\n          })\n          .with({ type: 'graphAbort' }, ({ data }) => {\n            // eslint-disable-next-line @typescript-eslint/no-floating-promises\n            this.#emitter.emit('graphAbort', {\n              graph: getGraph(data.graphId),\n              error: data.error,\n              successful: data.successful,\n            });\n          })\n          .with({ type: 'nodeStart' }, async ({ data }) => {\n            const node = getNode(data.nodeId);\n            // eslint-disable-next-line @typescript-eslint/no-floating-promises\n            this.#emitter.emit('nodeStart', {\n              node: getNode(data.nodeId),\n              inputs: data.inputs,\n              processId: data.processId,\n            });\n\n            // Every time a chat node starts, we wait for the playback interval\n            if (node.type === 'chat') {\n              await new Promise((resolve) => setTimeout(resolve, this.recordingPlaybackChatLatency));\n            }\n          })\n          .with({ type: 'nodeFinish' }, ({ data }) => {\n            const node = getNode(data.nodeId);\n            // eslint-disable-next-line @typescript-eslint/no-floating-promises\n            this.#emitter.emit('nodeFinish', {\n              node,\n              outputs: data.outputs,\n              processId: data.processId,\n            });\n\n            this.#nodeResults.set(data.nodeId, data.outputs);\n            this.#visitedNodes.add(data.nodeId);\n          })\n          .with({ type: 'nodeError' }, ({ data }) => {\n            // eslint-disable-next-line @typescript-eslint/no-floating-promises\n            this.#emitter.emit('nodeError', {\n              node: getNode(data.nodeId),\n              error: data.error,\n              processId: data.processId,\n            });\n\n            this.#erroredNodes.set(data.nodeId, data.error);\n            this.#visitedNodes.add(data.nodeId);\n          })\n          .with({ type: 'nodeExcluded' }, ({ data }) => {\n            // eslint-disable-next-line @typescript-eslint/no-floating-promises\n            this.#emitter.emit('nodeExcluded', {\n              node: getNode(data.nodeId),\n              processId: data.processId,\n              inputs: data.inputs,\n              outputs: data.outputs,\n              reason: data.reason,\n            });\n\n            this.#visitedNodes.add(data.nodeId);\n          })\n          .with({ type: 'nodeOutputsCleared' }, () => {})\n          .with({ type: 'partialOutput' }, () => {})\n          .with({ type: 'userInput' }, ({ data }) => {\n            // eslint-disable-next-line @typescript-eslint/no-floating-promises\n            this.#emitter.emit('userInput', {\n              callback: undefined!,\n              inputStrings: data.inputStrings,\n              inputs: data.inputs,\n              node: getNode(data.nodeId) as UserInputNode,\n              processId: data.processId,\n              renderingType: data.renderingType,\n            });\n          })\n          .with({ type: P.string.startsWith('globalSet:') }, ({ type, data }) => {\n            // eslint-disable-next-line @typescript-eslint/no-floating-promises\n            this.#emitter.emit(type, data);\n          })\n          .with({ type: P.string.startsWith('userEvent:') }, ({ type, data }) => {\n            // eslint-disable-next-line @typescript-eslint/no-floating-promises\n            this.#emitter.emit(type, data);\n          })\n          .with({ type: 'newAbortController' }, () => {})\n          .with({ type: 'finish' }, () => {\n            // eslint-disable-next-line @typescript-eslint/no-floating-promises\n            this.#emitter.emit('finish', undefined);\n          })\n          .with(P.nullish, () => {})\n          .exhaustive();\n      }\n    } catch (err) {\n      // eslint-disable-next-line @typescript-eslint/no-floating-promises\n      this.#emitter.emit('error', { error: getError(err) });\n    } finally {\n      this.#running = false;\n    }\n\n    return this.#graphOutputs;\n  }\n\n  #initProcessState() {\n    this.#running = true;\n\n    if (!this.#hasPreloadedData) {\n      this.#nodeResults = new Map();\n      this.#visitedNodes = new Set();\n    }\n\n    this.#erroredNodes = new Map();\n    this.#currentlyProcessing = new Set();\n    this.#remainingNodes = new Set(this.#graph.nodes.map((n) => n.id));\n    this.#pendingUserInputs = {};\n    this.#processingQueue = new PQueue({ concurrency: Infinity });\n    this.#graphOutputs = {};\n    this.#executionCache ??= new Map();\n    this.#queuedNodes = new Set();\n    this.#loopControllersSeen = new Set();\n    this.#subprocessors = new Set();\n    this.#attachedNodeData = new Map();\n    this.#globals ??= new Map();\n    this.#ignoreNodes = new Set();\n\n    this.#abortController = this.#newAbortController();\n    this.#abortController.signal.addEventListener('abort', () => {\n      this.#aborted = true;\n    });\n    this.#aborted = false;\n    this.#abortError = undefined;\n    this.#abortSuccessfully = false;\n    this.#nodeAbortControllers = new Map();\n    this.#loadedProjects = {};\n    this.#graphInputNodeValues = {};\n  }\n\n  /** Main function for running a graph. Runs a graph and returns the outputs from the output nodes of the graph. */\n  async processGraph(\n    /** Required and optional context available to the nodes and all subgraphs. */\n    context: ProcessContext,\n\n    /** Inputs to the main graph. You should pass all inputs required by the GraphInputNodes of the graph. */\n    inputs: Record<string, DataValue> = {},\n\n    /** Contextual data available to all graphs and subgraphs. Kind of like react context, avoids drilling down data into subgraphs. Be careful when using it. */\n    contextValues: Record<string, DataValue> = {},\n  ): Promise<GraphOutputs> {\n    try {\n      if (this.#running) {\n        throw new Error('Cannot process graph while already processing');\n      }\n\n      this.#initProcessState();\n\n      this.#context = context;\n      this.#graphInputs = inputs;\n      this.#contextValues ??= contextValues;\n\n      if (this.#context.tokenizer) {\n        this.#context.tokenizer.on('error', (error) => {\n          // eslint-disable-next-line @typescript-eslint/no-floating-promises\n          this.#emitter.emit('error', { error });\n        });\n      }\n\n      await this.#loadProjectReferences();\n\n      this.#preprocessGraph();\n\n      if (!this.#isSubProcessor) {\n        await this.#emitter.emit('start', {\n          contextValues: this.#contextValues,\n          inputs: this.#graphInputs,\n          project: this.#project,\n          startGraph: this.#graph,\n        });\n      }\n\n      await this.#emitter.emit('graphStart', { graph: this.#graph, inputs: this.#graphInputs });\n\n      if (this.#hasPreloadedData) {\n        for (const node of this.#graph.nodes) {\n          if (this.#nodeResults.has(node.id)) {\n            this.#emitTraceEvent(`Node ${node.title} has preloaded data`);\n\n            await this.#emitter.emit('nodeStart', {\n              node,\n              inputs: {},\n              processId: 'preload' as ProcessId,\n            });\n\n            await this.#emitter.emit('nodeFinish', {\n              node,\n              outputs: this.#nodeResults.get(node.id)!,\n              processId: 'preload' as ProcessId,\n            });\n          }\n        }\n      }\n\n      const startNodes = this.runToNodeIds\n        ? this.#graph.nodes.filter((node) => this.runToNodeIds?.includes(node.id))\n        : this.#graph.nodes.filter((node) => this.#outputNodesFrom(node).nodes.length === 0);\n\n      await this.#waitUntilUnpaused();\n\n      for (const startNode of startNodes) {\n        // eslint-disable-next-line @typescript-eslint/no-floating-promises\n        this.#processingQueue.add(async () => {\n          await this.#fetchNodeDataAndProcessNode(startNode);\n        });\n      }\n\n      await this.#processingQueue.onIdle();\n\n      // Anything not queued at this phase here should be ignored\n      if (this.runToNodeIds) {\n        // For safety, we'll only activate this if runToNodeIds is set, in case there are bugs in the first pass\n        for (const node of this.#graph.nodes) {\n          if (this.#queuedNodes.has(node.id) === false) {\n            this.#ignoreNodes.add(node.id);\n          }\n        }\n      }\n\n      // If we've aborted successfully, we can treat the graph like it succeeded\n      const erroredNodes = [...this.#erroredNodes.entries()].filter(([nodeId]) => {\n        const erroredNodeAttachedData = this.#getAttachedDataTo(nodeId);\n        return erroredNodeAttachedData.races == null || erroredNodeAttachedData.races.completed === false;\n      });\n      if (erroredNodes.length && !this.#abortSuccessfully) {\n        let error = this.#abortError;\n        if (!error) {\n          const message = `Graph ${this.#graph.metadata!.name} (${\n            this.#graph.metadata!.id\n          }) failed to process due to errors in nodes:\\n${erroredNodes\n            .map(([nodeId]) => `- ${this.#nodesById[nodeId]!.title} (${nodeId})`)\n            .join('\\n')}`;\n          if (erroredNodes.length === 1) {\n            const [, nodeError] = erroredNodes[0]!;\n            error = new Error(message, { cause: nodeError });\n          } else {\n            error = new AggregateError(\n              erroredNodes.map(([, nodeError]) => nodeError),\n              message,\n            );\n          }\n        }\n\n        await this.#emitter.emit('graphError', { graph: this.#graph, error });\n\n        if (!this.#isSubProcessor) {\n          await this.#emitter.emit('error', { error });\n        }\n\n        throw error;\n      }\n\n      if (this.#graphOutputs['cost' as PortId] == null) {\n        this.#graphOutputs['cost' as PortId] = {\n          type: 'number',\n          value: this.#totalCost,\n        };\n      }\n\n      const outputValues = this.#graphOutputs;\n\n      this.#running = false;\n\n      await this.#emitter.emit('graphFinish', { graph: this.#graph, outputs: outputValues });\n\n      if (!this.#isSubProcessor) {\n        await this.#emitter.emit('done', { results: outputValues });\n        await this.#emitter.emit('finish', undefined);\n      }\n\n      return outputValues;\n    } finally {\n      this.#running = false;\n\n      if (!this.#isSubProcessor) {\n        await this.#emitter.emit('finish', undefined);\n      }\n    }\n  }\n\n  async #loadProjectReferences() {\n    if ((this.#project.references?.length ?? 0) > 0) {\n      if (!this.#context.projectReferenceLoader) {\n        throw new Error(\n          'Project references are set, but no projectReferenceLoader is set in the context. Since this project uses project references, you must provide a projectReferenceLoader in the context.',\n        );\n      }\n\n      const seenProjectIds = new Set<ProjectId>();\n\n      const loadProject = async (ref: ProjectReference) => {\n        if (seenProjectIds.has(ref.id)) {\n          return;\n        }\n\n        seenProjectIds.add(ref.id);\n\n        const project = await this.#context.projectReferenceLoader!.loadProject(this.#context.projectPath, ref);\n\n        this.#loadedProjects[project.metadata!.id!] = project;\n\n        for (const reference of project.references ?? []) {\n          await loadProject(reference);\n        }\n      };\n\n      for (const reference of this.#project.references!) {\n        await loadProject(reference);\n      }\n    }\n  }\n\n  async #fetchNodeDataAndProcessNode(node: ChartNode): Promise<void> {\n    if (this.#currentlyProcessing.has(node.id) || this.#queuedNodes.has(node.id)) {\n      return;\n    }\n\n    if (this.#nodeResults.has(node.id) || this.#erroredNodes.has(node.id)) {\n      return;\n    }\n\n    const inputNodes = this.#inputNodesTo(node);\n\n    // Check if all input nodes are free of errors\n    for (const inputNode of inputNodes) {\n      if (this.#erroredNodes.has(inputNode.id)) {\n        return;\n      }\n    }\n\n    // Check if all required inputs have connections and if the connected output nodes have been visited\n    const connections = this.#connections[node.id] ?? [];\n    const inputsReady = this.#definitions[node.id]!.inputs.every((input) => {\n      const connectionToInput = connections?.find((conn) => conn.inputId === input.id && conn.inputNodeId === node.id);\n      return connectionToInput || !input.required;\n    });\n\n    if (!inputsReady) {\n      return;\n    }\n\n    this.#emitTraceEvent(`Node ${node.title} has required inputs nodes: ${inputNodes.map((n) => n.title).join(', ')}`);\n\n    const attachedData = this.#getAttachedDataTo(node);\n\n    if (node.type === 'raceInputs' || attachedData.races) {\n      for (const inputNode of inputNodes) {\n        const inputNodeAttachedData = this.#getAttachedDataTo(inputNode);\n        const raceIds = new Set<RaceId>([...(attachedData.races?.raceIds ?? ([] as RaceId[]))]);\n\n        if (node.type === 'raceInputs') {\n          raceIds.add(`race-${node.id}` as RaceId);\n        }\n\n        inputNodeAttachedData.races = {\n          propagate: false,\n          raceIds: [...raceIds],\n          completed: false,\n        };\n      }\n    }\n\n    this.#queuedNodes.add(node.id);\n\n    // eslint-disable-next-line @typescript-eslint/no-floating-promises\n    this.#processingQueue.addAll(\n      inputNodes.map((inputNode) => {\n        return async () => {\n          this.#emitTraceEvent(`Fetching required data for node ${inputNode.title} (${inputNode.id})`);\n\n          await this.#fetchNodeDataAndProcessNode(inputNode);\n        };\n      }),\n    );\n\n    await this.#processNodeIfAllInputsAvailable(node);\n  }\n\n  /** If all inputs are present, all conditions met, processes the node. */\n  async #processNodeIfAllInputsAvailable(node: ChartNode): Promise<void> {\n    const builtInNode = node as BuiltInNodes;\n\n    if (this.#ignoreNodes.has(node.id)) {\n      this.#emitTraceEvent(`Node ${node.title} is ignored`);\n      return;\n    }\n\n    if (this.runToNodeIds) {\n      const dependencyNodes = this.getDependencyNodesDeep(node.id);\n\n      if (this.runToNodeIds.some((runTo) => runTo !== node.id && dependencyNodes.includes(runTo))) {\n        this.#emitTraceEvent(`Node ${node.title} is excluded due to runToNodeIds`);\n        return;\n      }\n    }\n\n    if (this.#currentlyProcessing.has(node.id)) {\n      this.#emitTraceEvent(`Node ${node.title} is already being processed`);\n      return;\n    }\n\n    // For a loop controller, it can run multiple times, otherwise we already processed this node so bail out\n    if (this.#visitedNodes.has(node.id) && node.type !== 'loopController') {\n      this.#emitTraceEvent(`Node ${node.title} has already been processed`);\n      return;\n    }\n\n    if (this.#erroredNodes.has(node.id)) {\n      this.#emitTraceEvent(`Node ${node.title} has already errored`);\n      return;\n    }\n\n    const inputNodes = this.#inputNodesTo(node);\n\n    // Check if all input nodes are free of errors\n    for (const inputNode of inputNodes) {\n      if (this.#erroredNodes.has(inputNode.id)) {\n        this.#emitTraceEvent(`Node ${node.title} has errored input node ${inputNode.title}`);\n        return;\n      }\n    }\n\n    // Check if all required inputs have connections and if the connected output nodes have been visited\n    const connections = this.#connections[node.id] ?? [];\n    const inputsReady = this.#definitions[node.id]!.inputs.every((input) => {\n      const connectionToInput = connections?.find((conn) => conn.inputId === input.id && conn.inputNodeId === node.id);\n      return connectionToInput || !input.required;\n    });\n\n    if (!inputsReady) {\n      this.#emitTraceEvent(\n        `Node ${node.title} has required inputs nodes: ${inputNodes.map((n) => n.title).join(', ')}`,\n      );\n      return;\n    }\n\n    // Excluded because control flow is still in a loop - difference between \"will not execute\" and \"has not executed yet\"\n    const inputValues = this.#getInputValuesForNode(node);\n\n    if (this.#excludedDueToControlFlow(node, inputValues, nanoid() as ProcessId, 'loop-not-broken')) {\n      this.#emitTraceEvent(`Node ${node.title} is excluded due to control flow`);\n      return;\n    }\n\n    let waitingForInputNode: false | string = false;\n    const anyInputIsValid = Object.values(inputValues).some(\n      (value) => value && value.type.includes('control-flow-excluded') === false,\n    );\n    for (const inputNode of inputNodes) {\n      // For loop controllers, allow nodes in the same cycle to be not processed yet,\n      // but if we're in a 2nd iteration, we do need to wait for them\n      if (\n        node.type === 'loopController' &&\n        !this.#loopControllersSeen.has(node.id) &&\n        this.#nodesAreInSameCycle(node.id, inputNode.id)\n      ) {\n        continue;\n      }\n\n      // Only one visited node required for a raceInputs node\n      if (node.type === 'raceInputs' && this.#visitedNodes.has(inputNode.id) && anyInputIsValid) {\n        waitingForInputNode = false;\n        break;\n      }\n\n      if (waitingForInputNode === false && this.#visitedNodes.has(inputNode.id) === false) {\n        waitingForInputNode = inputNode.title;\n      }\n    }\n\n    if (waitingForInputNode) {\n      this.#emitTraceEvent(`Node ${node.title} is waiting for input node ${waitingForInputNode}`);\n      return;\n    }\n\n    this.#currentlyProcessing.add(node.id);\n\n    if (node.type === 'loopController') {\n      this.#loopControllersSeen.add(node.id);\n    }\n\n    const attachedData = this.#getAttachedDataTo(node);\n\n    if (attachedData.loopInfo && attachedData.loopInfo.loopControllerId !== node.id) {\n      attachedData.loopInfo.nodes.add(node.id);\n    }\n\n    if (attachedData.races?.completed) {\n      this.#emitTraceEvent(`Node ${node.title} is part of a race that was completed`);\n      return;\n    }\n\n    const processId = await this.#processNode(node);\n\n    if (this.slowMode) {\n      await new Promise((resolve) => setTimeout(resolve, 250));\n    }\n    this.#emitTraceEvent(`Finished processing node ${node.title} (${node.id})`);\n    this.#visitedNodes.add(node.id);\n    this.#currentlyProcessing.delete(node.id);\n    this.#remainingNodes.delete(node.id);\n\n    const outputNodes = this.#outputNodesFrom(node);\n\n    // Aggressive - each iteration of the loop controller, we clear everything in the same cycle as the controller\n    if (node.type === 'loopController') {\n      const loopControllerResults = this.#nodeResults.get(node.id)!;\n\n      // If the loop controller is excluded, we have to \"break\" it or else it'll loop forever...\n      const breakValue = loopControllerResults['break' as PortId];\n\n      const didBreak =\n        // @ts-ignore\n        !(breakValue?.type === 'control-flow-excluded' && breakValue?.value === 'loop-not-broken') ??\n        this.#excludedDueToControlFlow(node, this.#getInputValuesForNode(node), nanoid() as ProcessId);\n\n      if (!didBreak) {\n        this.#emitTraceEvent(`Loop controller ${node.title} did not break, so we're looping again`);\n        for (const loopNodeId of attachedData.loopInfo?.nodes ?? []) {\n          const cycleNode = this.#nodesById[loopNodeId]!;\n          this.#emitTraceEvent(`Clearing cycle node ${cycleNode.title} (${cycleNode.id})`);\n          this.#visitedNodes.delete(cycleNode.id);\n          this.#currentlyProcessing.delete(cycleNode.id);\n          this.#remainingNodes.add(cycleNode.id);\n          this.#nodeResults.delete(cycleNode.id);\n        }\n      }\n    }\n\n    // Abort everything the race depends on - everything already executed won't\n    // be aborted, but everything that hasn't will be, effectively terminating all slower branches\n    if (node.type === 'raceInputs') {\n      const allNodesForRace = [...this.#attachedNodeData.entries()].filter(([, { races }]) =>\n        races?.raceIds.includes(`race-${node.id}` as RaceId),\n      );\n      for (const [nodeId] of allNodesForRace) {\n        for (const [key, abortController] of this.#nodeAbortControllers.entries()) {\n          if (key.startsWith(nodeId)) {\n            this.#emitTraceEvent(`Aborting node ${nodeId} because other race branch won`);\n            abortController.abort();\n          }\n        }\n\n        // Mark every attached data as completed for the race\n        for (const [, nodeAttachedData] of [...this.#attachedNodeData.entries()]) {\n          if (nodeAttachedData.races?.raceIds.includes(`race-${node.id}` as RaceId)) {\n            nodeAttachedData.races.completed = true;\n          }\n        }\n      }\n    }\n\n    let childLoopInfo = attachedData.loopInfo;\n    if (builtInNode.type === 'loopController') {\n      if (childLoopInfo != null && childLoopInfo.loopControllerId !== builtInNode.id) {\n        this.#nodeErrored(node, new Error('Nested loops are not supported'), processId);\n        return;\n      }\n\n      childLoopInfo = {\n        propagate: (parent, connectionsFromParent) => {\n          if (\n            parent.type === 'loopController' &&\n            connectionsFromParent.some((c) => c.outputId === ('break' as PortId))\n          ) {\n            return false;\n          }\n          return true;\n        },\n\n        loopControllerId: node.id,\n\n        // We want to be able to clear every node that _potentially_ could run in the loop\n        nodes: childLoopInfo?.nodes ?? new Set(),\n\n        iterationCount: (childLoopInfo?.iterationCount ?? 0) + 1,\n      };\n\n      attachedData.loopInfo = childLoopInfo; // Not 100% sure if this is right - sets the childLoopInfo on the loop controller itself, probably fine?\n    }\n\n    for (const { node: outputNode, connections: connectionsToOutputNode } of outputNodes.connectionsToNodes) {\n      const outputNodeAttachedData = this.#getAttachedDataTo(outputNode);\n\n      const propagatedAttachedData = Object.entries(attachedData).filter(([, value]): boolean => {\n        if (!value) {\n          return false;\n        }\n\n        if (typeof value.propagate === 'boolean') {\n          return value.propagate;\n        }\n\n        return value.propagate(node, connectionsToOutputNode);\n      });\n\n      for (const [key, value] of propagatedAttachedData) {\n        outputNodeAttachedData[key] = value;\n      }\n    }\n\n    // Node is finished, check if we can run any more nodes that depend on this one\n    // eslint-disable-next-line @typescript-eslint/no-floating-promises\n    this.#processingQueue.addAll(\n      outputNodes.nodes.map((outputNode) => async () => {\n        this.#emitTraceEvent(`Trying to run output node from ${node.title}: ${outputNode.title} (${outputNode.id})`);\n\n        await this.#processNodeIfAllInputsAvailable(outputNode);\n      }),\n    );\n  }\n\n  #getAttachedDataTo(node: ChartNode | NodeId): AttachedNodeData {\n    const nodeId = typeof node === 'string' ? node : node.id;\n    let nodeData = this.#attachedNodeData.get(nodeId);\n    if (nodeData == null) {\n      nodeData = {};\n      this.#attachedNodeData.set(nodeId, nodeData);\n    }\n    return nodeData;\n  }\n\n  async #processNode(node: ChartNode) {\n    const processId = nanoid() as ProcessId;\n\n    if (this.#abortController.signal.aborted) {\n      this.#nodeErrored(node, new Error('Processing aborted'), processId);\n      return processId;\n    }\n\n    const inputNodes = this.#inputNodesTo(node);\n    const erroredInputNodes = inputNodes.filter((inputNode) => this.#erroredNodes.has(inputNode.id));\n    if (erroredInputNodes.length > 0) {\n      const error = new Error(\n        `Cannot process node ${node.title} (${node.id}) because it depends on errored nodes: ${erroredInputNodes\n          .map((n) => `${n.title} (${n.id})`)\n          .join(', ')}`,\n      );\n      this.#nodeErrored(node, error, processId);\n      return processId;\n    }\n\n    if (node.isSplitRun) {\n      await this.#processSplitRunNode(node, processId);\n    } else {\n      await this.#processNormalNode(node, processId);\n    }\n\n    return processId;\n  }\n\n  async #processSplitRunNode(node: ChartNode, processId: ProcessId) {\n    const inputValues = this.#getInputValuesForNode(node);\n\n    if (this.#excludedDueToControlFlow(node, inputValues, processId)) {\n      return;\n    }\n\n    const splittingAmount = Math.min(\n      max(values(inputValues).map((value) => (Array.isArray(value?.value) ? value?.value.length : 1))) ?? 1,\n      node.splitRunMax ?? 10,\n    );\n\n    // eslint-disable-next-line @typescript-eslint/no-floating-promises\n    this.#emitter.emit('nodeStart', { node, inputs: inputValues, processId });\n\n    try {\n      let results: (\n        | {\n            type: string;\n            output: Outputs;\n            error?: Error;\n          }\n        | {\n            type: string;\n            error: Error;\n            output?: Outputs;\n          }\n      )[] = [];\n\n      if (node.isSplitSequential) {\n        for (let i = 0; i < splittingAmount; i++) {\n          if (this.#aborted) {\n            throw new Error('Processing aborted');\n          }\n\n          const inputs = fromEntries(\n            entries(inputValues).map(([port, value]) => [\n              port as PortId,\n              isArrayDataValue(value) ? arrayizeDataValue(value)[i] ?? undefined : value,\n            ]),\n          );\n\n          try {\n            const output = await this.#processNodeWithInputData(\n              node,\n              inputs as Inputs,\n              i,\n              processId,\n              (node, partialOutputs, index) => {\n                // eslint-disable-next-line @typescript-eslint/no-floating-promises\n                this.#emitter.emit('partialOutput', { node, outputs: partialOutputs, index, processId });\n              },\n            );\n\n            if (output['cost' as PortId]?.type === 'number') {\n              this.#totalCost += coerceTypeOptional(output['cost' as PortId], 'number') ?? 0;\n            }\n            results.push({ type: 'output', output });\n          } catch (error) {\n            results.push({ type: 'error', error: getError(error) });\n          }\n        }\n      } else {\n        results = await Promise.all(\n          range(0, splittingAmount).map(async (i) => {\n            const inputs = fromEntries(\n              entries(inputValues).map(([port, value]) => [\n                port as PortId,\n                isArrayDataValue(value) ? arrayizeDataValue(value)[i] ?? undefined : value,\n              ]),\n            );\n\n            try {\n              const output = await this.#processNodeWithInputData(\n                node,\n                inputs as Inputs,\n                i,\n                processId,\n                (node, partialOutputs, index) => {\n                  // eslint-disable-next-line @typescript-eslint/no-floating-promises\n                  this.#emitter.emit('partialOutput', { node, outputs: partialOutputs, index, processId });\n                },\n              );\n\n              if (output['cost' as PortId]?.type === 'number') {\n                this.#totalCost += coerceTypeOptional(output['cost' as PortId], 'number') ?? 0;\n              }\n              return { type: 'output', output };\n            } catch (error) {\n              return { type: 'error', error: getError(error) };\n            }\n          }),\n        );\n      }\n\n      const errors = results.filter((r) => r.type === 'error').map((r) => r.error!);\n      if (errors.length === 1) {\n        const e = errors[0]!;\n        throw e;\n      } else if (errors.length > 0) {\n        throw new AggregateError(errors);\n      }\n\n      // Combine the parallel results into the final output\n\n      // Turn a Record<PortId, DataValue[]> into a Record<PortId, AnyArrayDataValue>\n      const aggregateResults = results.reduce((acc, result) => {\n        for (const [portId, value] of entries(result.output!)) {\n          acc[portId as PortId] ??= { type: (value?.type + '[]') as DataValue['type'], value: [] } as DataValue;\n          (acc[portId as PortId] as ArrayDataValue<AnyDataValue>).value.push(value?.value);\n        }\n        return acc;\n      }, {} as Outputs);\n\n      this.#nodeResults.set(node.id, aggregateResults);\n      this.#visitedNodes.add(node.id);\n      this.#totalCost += sum(results.map((r) => coerceTypeOptional(r.output?.['cost' as PortId], 'number') ?? 0));\n      // eslint-disable-next-line @typescript-eslint/no-floating-promises\n      this.#emitter.emit('nodeFinish', { node, outputs: aggregateResults, processId });\n    } catch (error) {\n      this.#nodeErrored(node, error, processId);\n    }\n  }\n\n  async #processNormalNode(node: ChartNode, processId: ProcessId) {\n    const inputValues = this.#getInputValuesForNode(node);\n\n    if (this.#excludedDueToControlFlow(node, inputValues, processId)) {\n      return;\n    }\n\n    // eslint-disable-next-line @typescript-eslint/no-floating-promises\n    this.#emitter.emit('nodeStart', { node, inputs: inputValues, processId });\n\n    try {\n      const outputValues = await this.#processNodeWithInputData(\n        node,\n        inputValues,\n        0,\n        processId,\n        (node, partialOutputs, index) => {\n          // eslint-disable-next-line @typescript-eslint/no-floating-promises\n          this.#emitter.emit('partialOutput', { node, outputs: partialOutputs, index, processId });\n        },\n      );\n\n      this.#nodeResults.set(node.id, outputValues);\n      this.#visitedNodes.add(node.id);\n      if (outputValues['cost' as PortId]?.type === 'number') {\n        this.#totalCost += coerceTypeOptional(outputValues['cost' as PortId], 'number') ?? 0;\n      }\n      // eslint-disable-next-line @typescript-eslint/no-floating-promises\n      this.#emitter.emit('nodeFinish', { node, outputs: outputValues, processId });\n    } catch (error) {\n      this.#nodeErrored(node, error, processId);\n    }\n  }\n\n  #nodeErrored(node: ChartNode, e: unknown, processId: ProcessId) {\n    const error = getError(e);\n    // eslint-disable-next-line @typescript-eslint/no-floating-promises\n    this.#emitter.emit('nodeError', { node, error, processId });\n    this.#emitTraceEvent(`Node ${node.title} (${node.id}-${processId}) errored: ${error.stack}`);\n    this.#erroredNodes.set(node.id, error);\n  }\n\n  getRootProcessor(): GraphProcessor {\n    let processor: GraphProcessor = this;\n    while (processor.#parent) {\n      processor = processor.#parent;\n    }\n    return processor;\n  }\n\n  /** Raise a user event on the processor, all subprocessors, and their children. */\n  raiseEvent(event: string, data: DataValue) {\n    // eslint-disable-next-line @typescript-eslint/no-floating-promises\n    this.#emitter.emit(`userEvent:${event}`, data);\n\n    for (const subprocessor of this.#subprocessors) {\n      subprocessor.raiseEvent(event, data);\n    }\n  }\n\n  #newAbortController() {\n    const controller = new AbortController();\n    // eslint-disable-next-line @typescript-eslint/no-floating-promises\n    this.#emitter.emit('newAbortController', controller);\n    return controller;\n  }\n\n  async #processNodeWithInputData(\n    node: ChartNode,\n    inputValues: Inputs,\n    index: number,\n    processId: ProcessId,\n    partialOutput?: (node: ChartNode, partialOutputs: Outputs, index: number) => void,\n  ) {\n    const instance = this.#nodeInstances[node.id]!;\n    const nodeAbortController = this.#newAbortController();\n    const abortListener = () => {\n      nodeAbortController.abort();\n    };\n    this.#nodeAbortControllers.set(`${node.id}-${processId}`, nodeAbortController);\n    this.#abortController.signal.addEventListener('abort', abortListener);\n\n    const plugin = this.#registry.getPluginFor(node.type);\n\n    let tokenizer = this.#context.tokenizer;\n    if (!tokenizer) {\n      tokenizer = new GptTokenizerTokenizer();\n\n      tokenizer.on('error', (e) => {\n        // eslint-disable-next-line @typescript-eslint/no-floating-promises\n        this.#emitter.emit('error', { error: e });\n      });\n    }\n\n    const context: InternalProcessContext = {\n      ...this.#context,\n      node,\n      tokenizer,\n      executor: this.executor ?? 'nodejs',\n      project: this.#project,\n      executionCache: this.#executionCache,\n      graphInputs: this.#graphInputs,\n      graphOutputs: this.#graphOutputs,\n      attachedData: this.#getAttachedDataTo(node),\n      codeRunner: this.#context.codeRunner ?? new IsomorphicCodeRunner(),\n      referencedProjects: this.#loadedProjects,\n      waitEvent: async (event) => {\n        return new Promise((resolve, reject) => {\n          this.#emitter.once(`userEvent:${event}`).then(resolve).catch(reject);\n          nodeAbortController.signal.addEventListener('abort', () => {\n            reject(new Error('Process aborted'));\n          });\n        });\n      },\n      raiseEvent: (event, data) => {\n        this.getRootProcessor().raiseEvent(event, data as DataValue);\n      },\n      contextValues: this.#contextValues,\n      externalFunctions: { ...this.#externalFunctions },\n      onPartialOutputs: (partialOutputs) => {\n        partialOutput?.(node, partialOutputs, index);\n\n        const { useAsGraphPartialOutput } = (node.data as { useAsGraphPartialOutput?: boolean } | undefined) ?? {};\n\n        if (useAsGraphPartialOutput && this.#executor && this.#parent) {\n          const executorNode = this.#parent.#nodesById[this.#executor.nodeId];\n          if (executorNode) {\n            // eslint-disable-next-line @typescript-eslint/no-floating-promises\n            this.#emitter.emit('partialOutput', {\n              index: this.#executor.index,\n              node: executorNode,\n              outputs: partialOutputs,\n              processId: this.#executor.processId,\n            });\n          }\n        }\n      },\n      signal: nodeAbortController.signal,\n      processId,\n      getGlobal: (id) => this.#globals.get(id),\n      setGlobal: (id, value) => {\n        this.#globals.set(id, value);\n        // eslint-disable-next-line @typescript-eslint/no-floating-promises\n        this.#emitter.emit('globalSet', { id, value, processId });\n      },\n      waitForGlobal: async (id) => {\n        if (this.#globals.has(id)) {\n          return this.#globals.get(id)!;\n        }\n        await this.getRootProcessor().#emitter.once(`globalSet:${id}`);\n        return this.#globals.get(id)!;\n      },\n      createSubProcessor: (\n        subGraphId: GraphId | undefined,\n        { signal, project }: { signal?: AbortSignal; project?: Project } = {},\n      ) => {\n        const processor = new GraphProcessor(project ?? this.#project, subGraphId, this.#registry);\n        processor.executor = this.executor;\n        processor.#isSubProcessor = true;\n        processor.#executionCache = this.#executionCache;\n        processor.#externalFunctions = this.#externalFunctions;\n        processor.#contextValues = this.#contextValues;\n        processor.#parent = this;\n        processor.#globals = this.#globals;\n        processor.#executor = {\n          nodeId: node.id,\n          index,\n          processId,\n        };\n        processor.on('nodeError', (e) => this.#emitter.emit('nodeError', e));\n        processor.on('nodeFinish', (e) => this.#emitter.emit('nodeFinish', e));\n        processor.on('partialOutput', (e) => this.#emitter.emit('partialOutput', e));\n        processor.on('nodeExcluded', (e) => this.#emitter.emit('nodeExcluded', e));\n        processor.on('nodeStart', (e) => this.#emitter.emit('nodeStart', e));\n        processor.on('graphAbort', (e) => this.#emitter.emit('graphAbort', e));\n        processor.on('userInput', (e) => this.#emitter.emit('userInput', e)); // TODO!\n        processor.on('graphStart', (e) => this.#emitter.emit('graphStart', e));\n        processor.on('graphFinish', (e) => this.#emitter.emit('graphFinish', e));\n        processor.on('globalSet', (e) => this.#emitter.emit('globalSet', e));\n        processor.on('newAbortController', (e) => this.#emitter.emit('newAbortController', e));\n        processor.on('pause', () => {\n          if (!this.#isPaused) {\n            this.pause();\n          }\n        });\n        processor.on('resume', () => {\n          if (this.#isPaused) {\n            this.resume();\n          }\n        });\n\n        processor.onAny((event, data) => {\n          if (event.startsWith('globalSet:')) {\n            // eslint-disable-next-line @typescript-eslint/no-floating-promises\n            this.#emitter.emit(event, data);\n          }\n        });\n\n        this.#subprocessors.add(processor);\n\n        if (signal) {\n          signal.addEventListener('abort', () => {\n            // eslint-disable-next-line @typescript-eslint/no-floating-promises\n            processor.abort();\n          });\n        }\n\n        // If parent is aborted, abort subgraph with error (it's fine, success state is on the parent)\n        this.#abortController.signal.addEventListener('abort', () => {\n          // eslint-disable-next-line @typescript-eslint/no-floating-promises\n          processor.abort();\n        });\n\n        this.on('pause', () => processor.pause());\n        this.on('resume', () => processor.resume());\n\n        return processor;\n      },\n      trace: (message) => {\n        this.#emitTraceEvent(message);\n      },\n      abortGraph: (error) => {\n        // eslint-disable-next-line @typescript-eslint/no-floating-promises\n        this.abort(error === undefined, error);\n      },\n      getPluginConfig: (name) => getPluginConfig(plugin, this.#context.settings, name),\n      requestUserInput: async (inputStrings, renderingType) => {\n        const results = await new Promise<StringArrayDataValue>((resolve, reject) => {\n          this.#pendingUserInputs[node.id] = {\n            resolve,\n            reject,\n          };\n\n          this.#abortController.signal.addEventListener('abort', () => {\n            delete this.#pendingUserInputs[node.id];\n            reject(new Error('Processing aborted'));\n          });\n\n          // eslint-disable-next-line @typescript-eslint/no-floating-promises\n          this.#emitter.emit('userInput', {\n            node,\n            inputStrings,\n            inputs: inputValues,\n            renderingType,\n            callback: (results) => {\n              resolve(results);\n\n              delete this.#pendingUserInputs[node.id];\n            },\n            processId,\n          });\n        });\n\n        return results;\n      },\n      graphInputNodeValues: this.#graphInputNodeValues,\n    };\n\n    await this.#waitUntilUnpaused();\n    const results = await instance.process(inputValues, context);\n    this.#nodeAbortControllers.delete(`${node.id}-${processId}`);\n    this.#abortController.signal.removeEventListener('abort', abortListener);\n\n    if (nodeAbortController.signal.aborted) {\n      throw new Error('Aborted');\n    }\n\n    return results;\n  }\n\n  #excludedDueToControlFlow(\n    node: ChartNode,\n    inputValues: Inputs,\n    processId: ProcessId,\n    typeOfExclusion: ControlFlowExcludedDataValue['value'] = undefined,\n  ) {\n    if (node.disabled) {\n      this.#emitTraceEvent(`Excluding node ${node.title} because it's disabled`);\n\n      this.#visitedNodes.add(node.id);\n      this.#markAsExcluded(node, processId, inputValues, 'disabled');\n\n      return true;\n    }\n\n    if (node.isConditional && typeOfExclusion === undefined) {\n      const ifValue = coerceTypeOptional(inputValues[IF_PORT.id], 'boolean');\n      if (ifValue === false) {\n        this.#emitTraceEvent(`Excluding node ${node.title} because if port is false`);\n\n        this.#visitedNodes.add(node.id);\n        this.#markAsExcluded(node, processId, inputValues, 'if port is false');\n        return true;\n      }\n    }\n\n    const inputsWithValues = entries(inputValues);\n    const controlFlowExcludedValues = inputsWithValues.filter(\n      ([, value]) =>\n        value &&\n        getScalarTypeOf(value.type) === 'control-flow-excluded' &&\n        (!typeOfExclusion || value.value === typeOfExclusion),\n    );\n    const inputIsExcludedValue = inputsWithValues.length > 0 && controlFlowExcludedValues.length > 0;\n\n    const isWaitingForLoop = controlFlowExcludedValues.some((value) => value?.[1]?.value === 'loop-not-broken');\n\n    const nodesAllowedToConsumeExcludedValue: BuiltInNodeType[] = [\n      'if',\n      'ifElse',\n      'coalesce',\n      'graphOutput',\n      'raceInputs',\n      'loopController',\n    ];\n\n    const allowedToConsumedExcludedValue =\n      nodesAllowedToConsumeExcludedValue.includes(node.type as BuiltInNodeType) && !isWaitingForLoop;\n\n    if (inputIsExcludedValue && !allowedToConsumedExcludedValue) {\n      if (!isWaitingForLoop) {\n        if (inputIsExcludedValue) {\n          this.#emitTraceEvent(\n            `Excluding node ${node.title} because of control flow. Input is has excluded value: ${controlFlowExcludedValues[0]?.[0]}`,\n          );\n        }\n\n        this.#visitedNodes.add(node.id);\n        this.#markAsExcluded(node, processId, inputValues, 'input is excluded value');\n      }\n\n      return true;\n    }\n\n    return false;\n  }\n\n  #markAsExcluded(node: ChartNode, processId: ProcessId, inputValues: Inputs, reason: string) {\n    const outputs: Outputs = {};\n    for (const output of this.#definitions[node.id]!.outputs) {\n      outputs[output.id] = { type: 'control-flow-excluded', value: undefined };\n    }\n\n    // Prevent infinite loop, a control-flow-excluded to loop controller shouldn't set the break port, let the loop controller handle it\n    if (node.type === 'loopController') {\n      outputs['break' as PortId] = { type: 'control-flow-excluded', value: 'loop-not-broken' };\n    }\n\n    this.#nodeResults.set(node.id, outputs);\n\n    // eslint-disable-next-line @typescript-eslint/no-floating-promises\n    this.#emitter.emit('nodeExcluded', {\n      node,\n      processId,\n      inputs: inputValues,\n      outputs,\n      reason,\n    });\n  }\n\n  #getInputValuesForNode(node: ChartNode): Inputs {\n    const connections = this.#connections[node.id];\n    return this.#definitions[node.id]!.inputs.reduce(\n      (values, input) => {\n        if (!connections) {\n          return values;\n        }\n        const connection = connections.find((conn) => conn.inputId === input.id && conn.inputNodeId === node.id);\n        if (connection) {\n          const outputNode = this.#nodeInstances[connection.outputNodeId]!.chartNode;\n          const outputNodeOutputs = this.#nodeResults.get(outputNode.id);\n          const outputResult = outputNodeOutputs?.[connection.outputId];\n\n          values[input.id] = outputResult;\n        }\n        return values;\n      },\n      {} as Record<string, any>,\n    );\n  }\n\n  /** Gets the nodes that are inputting to the given node. */\n  #inputNodesTo(node: ChartNode): ChartNode[] {\n    const connections = this.#connections[node.id];\n    if (!connections) {\n      return [];\n    }\n\n    const connectionsToNode = connections.filter((conn) => conn.inputNodeId === node.id).filter(isNotNull);\n\n    // Filter out invalid connections\n    const inputDefinitions = this.#definitions[node.id]?.inputs ?? [];\n    return connectionsToNode\n      .filter((connection) => {\n        const connectionDefinition = inputDefinitions.find((def) => def.id === connection.inputId);\n        return connectionDefinition != null;\n      })\n      .map((conn) => this.#nodesById[conn.outputNodeId])\n      .filter(isNotNull);\n  }\n\n  /** Gets the nodes that the given node it outputting to. */\n  #outputNodesFrom(node: ChartNode): {\n    nodes: ChartNode[];\n    connections: NodeConnection[];\n    connectionsToNodes: { connections: NodeConnection[]; node: ChartNode }[];\n  } {\n    const connections = this.#connections[node.id];\n    if (!connections) {\n      return { nodes: [], connections: [], connectionsToNodes: [] };\n    }\n\n    const connectionsToNode = connections.filter((conn) => conn.outputNodeId === node.id);\n\n    // Filter out invalid connections\n    const outputDefinitions = this.#definitions[node.id]?.outputs ?? [];\n    const outputConnections = connectionsToNode.filter((connection) => {\n      const connectionDefinition = outputDefinitions.find((def) => def.id === connection.outputId);\n      return connectionDefinition != null;\n    });\n\n    const outputNodes = uniqBy(\n      outputConnections.map((conn) => this.#nodesById[conn.inputNodeId]).filter(isNotNull),\n      (x) => x.id,\n    );\n\n    const connectionsToNodes: { connections: NodeConnection[]; node: ChartNode }[] = [];\n\n    outputNodes.forEach((node) => {\n      const connections = outputConnections.filter((conn) => conn.inputNodeId === node.id);\n      connectionsToNodes.push({ connections, node });\n    });\n\n    return { nodes: outputNodes, connections: outputConnections, connectionsToNodes };\n  }\n\n  #tarjanSCC(): ChartNode[][] {\n    let index = 0;\n    const stack: ChartNode[] = [];\n    const indices: Map<string, number> = new Map();\n    const lowLinks: Map<string, number> = new Map();\n    const onStack: Map<string, boolean> = new Map();\n    const sccs: ChartNode[][] = [];\n\n    const strongConnect = (node: ChartNode) => {\n      indices.set(node.id, index);\n      lowLinks.set(node.id, index);\n      index++;\n      stack.push(node);\n      onStack.set(node.id, true);\n\n      const outgoingConnections = this.#connections[node.id]?.filter((conn) => conn.outputNodeId === node.id);\n      for (const connection of outgoingConnections ?? []) {\n        const successor = this.#nodesById[connection.inputNodeId]!;\n\n        if (!indices.has(successor.id)) {\n          strongConnect(successor);\n          lowLinks.set(node.id, Math.min(lowLinks.get(node.id)!, lowLinks.get(successor.id)!));\n        } else if (onStack.get(successor.id)) {\n          lowLinks.set(node.id, Math.min(lowLinks.get(node.id)!, indices.get(successor.id)!));\n        }\n      }\n\n      if (lowLinks.get(node.id) === indices.get(node.id)) {\n        const scc: Array<ChartNode> = [];\n        let connectedNode: ChartNode;\n\n        do {\n          connectedNode = stack.pop()!;\n          onStack.set(connectedNode.id, false);\n          scc.push(connectedNode);\n        } while (connectedNode.id !== node.id);\n\n        sccs.push(scc);\n      }\n    };\n\n    for (const node of this.#graph.nodes) {\n      if (!indices.has(node.id)) {\n        strongConnect(node);\n      }\n    }\n\n    return sccs;\n  }\n\n  #nodesAreInSameCycle(a: NodeId, b: NodeId) {\n    return this.#scc.find((cycle) => cycle.find((node) => node.id === a) && cycle.find((node) => node.id === b));\n  }\n}\n", "import type { Inputs, Outputs } from './GraphProcessor.js';\nimport {\n  IF_PORT,\n  type ChartNode,\n  type NodeConnection,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n} from './NodeBase.js';\nimport type { Project, ProjectId } from './Project.js';\nimport type { InternalProcessContext } from './ProcessContext.js';\nimport type { EditorDefinition } from './EditorDefinition.js';\nimport type { NodeBodySpec } from './NodeBodySpec.js';\nimport type { RivetUIContext } from './RivetUIContext.js';\n\nexport interface PluginNodeImpl<T extends ChartNode> {\n  getInputDefinitions(\n    data: T['data'],\n    connections: NodeConnection[],\n    nodes: Record<NodeId, ChartNode>,\n    project: Project,\n  ): NodeInputDefinition[];\n\n  getOutputDefinitions(\n    data: T['data'],\n    connections: NodeConnection[],\n    nodes: Record<NodeId, ChartNode>,\n    project: Project,\n  ): NodeOutputDefinition[];\n\n  process(data: T['data'], inputData: Inputs, context: InternalProcessContext): Promise<Outputs>;\n\n  getEditors(data: T['data'], context: RivetUIContext): EditorDefinition<T>[] | Promise<EditorDefinition<T>[]>;\n\n  getBody(data: T['data'], context: RivetUIContext): NodeBody | Promise<NodeBody>;\n\n  create(): T;\n\n  getUIData(context: RivetUIContext): NodeUIData | Promise<NodeUIData>;\n}\n\nexport abstract class NodeImpl<T extends ChartNode, Type extends T['type'] = T['type']> {\n  readonly chartNode: T;\n\n  constructor(chartNode: T) {\n    this.chartNode = chartNode;\n  }\n\n  get id(): string {\n    return this.chartNode.id;\n  }\n\n  get type(): Type {\n    return this.chartNode.type as Type;\n  }\n\n  get title(): string {\n    return this.chartNode.title;\n  }\n\n  get visualData(): { x: number; y: number } {\n    return this.chartNode.visualData;\n  }\n\n  get data(): T['data'] {\n    return this.chartNode.data;\n  }\n\n  abstract getInputDefinitions(\n    connections: NodeConnection[],\n    nodes: Record<NodeId, ChartNode>,\n    project: Project,\n    referencedProjects: Record<ProjectId, Project>,\n  ): NodeInputDefinition[];\n\n  getInputDefinitionsIncludingBuiltIn(\n    connections: NodeConnection[],\n    nodes: Record<NodeId, ChartNode>,\n    project: Project,\n    referencedProjects: Record<ProjectId, Project>,\n  ): NodeInputDefinition[] {\n    const ports = [...this.getInputDefinitions(connections, nodes, project, referencedProjects)];\n\n    if (this.chartNode.isConditional) {\n      ports.push(IF_PORT);\n    }\n\n    return ports;\n  }\n\n  abstract getOutputDefinitions(\n    connections: NodeConnection[],\n    nodes: Record<NodeId, ChartNode>,\n    project: Project,\n    referencedProjects: Record<ProjectId, Project>,\n  ): NodeOutputDefinition[];\n\n  abstract process(inputData: Inputs, context: InternalProcessContext): Promise<Outputs>;\n\n  getEditors(_context: RivetUIContext): EditorDefinition<T>[] | Promise<EditorDefinition<T>[]> {\n    return [];\n  }\n\n  getBody(_context: RivetUIContext): NodeBody | Promise<NodeBody> {\n    return undefined;\n  }\n}\n\nexport type NodeBody = string | NodeBodySpec | NodeBodySpec[] | undefined;\n\nexport class PluginNodeImplClass<T extends ChartNode, Type extends T['type'] = T['type']> extends NodeImpl<T, Type> {\n  readonly impl: PluginNodeImpl<T>;\n\n  constructor(chartNode: T, impl: PluginNodeImpl<T>) {\n    super(chartNode);\n    this.impl = impl;\n  }\n\n  getInputDefinitions(\n    connections: NodeConnection[],\n    nodes: Record<NodeId, ChartNode>,\n    project: Project,\n  ): NodeInputDefinition[] {\n    return this.impl.getInputDefinitions(this.data, connections, nodes, project);\n  }\n\n  getOutputDefinitions(\n    connections: NodeConnection[],\n    nodes: Record<NodeId, ChartNode>,\n    project: Project,\n  ): NodeOutputDefinition[] {\n    return this.impl.getOutputDefinitions(this.data, connections, nodes, project);\n  }\n\n  process(inputData: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    return this.impl.process(this.data, inputData, context);\n  }\n\n  getEditors(context: RivetUIContext): EditorDefinition<T>[] | Promise<EditorDefinition<T>[]> {\n    return this.impl.getEditors(this.data, context);\n  }\n\n  getBody(context: RivetUIContext): NodeBody | Promise<NodeBody> {\n    return this.impl.getBody(this.data, context);\n  }\n}\n\nexport type NodeUIData = {\n  contextMenuTitle?: string;\n  infoBoxTitle?: string;\n  infoBoxBody?: string;\n  infoBoxImageUri?: string;\n  group?: string | string[];\n};\n\nexport type NodeImplConstructor<T extends ChartNode> = {\n  new (chartNode: T, pluginImpl: PluginNodeImpl<T> | undefined): NodeImpl<T>;\n\n  create(pluginImpl?: PluginNodeImpl<T>): T;\n\n  getUIData(context: RivetUIContext): NodeUIData | Promise<NodeUIData>;\n};\n", "import { type ChartNode, type NodeImplConstructor, type NodeImpl, type PluginNodeImpl } from '../index.js';\nimport { mapValues, values } from '../utils/typeSafety.js';\nimport type { NodeDefinition, PluginNodeDefinition } from './NodeDefinition.js';\nimport { type RivetPlugin } from './RivetPlugin.js';\nimport { type RivetUIContext } from './RivetUIContext.js';\nimport { PluginNodeImplClass } from './NodeImpl.js';\n\nexport class NodeRegistration<NodeTypes extends string = never, Nodes extends ChartNode = never> {\n  NodesType: Nodes = undefined!;\n  NodeTypesType: NodeTypes = undefined!;\n\n  #infos = {} as {\n    [P in NodeTypes]: {\n      displayName: string;\n      impl: NodeImplConstructor<Extract<Nodes, { type: P }>>;\n      plugin?: RivetPlugin;\n      pluginImpl?: PluginNodeImpl<Extract<Nodes, { type: P }>>;\n    };\n  };\n\n  readonly #plugins = [] as RivetPlugin[];\n\n  #implsMap = {} as Record<string, { impl: NodeImplConstructor<ChartNode>; pluginImpl?: PluginNodeImpl<ChartNode> }>;\n  readonly #nodeTypes = [] as NodeTypes[];\n\n  register<T extends ChartNode>(\n    definition: NodeDefinition<T>,\n    plugin?: RivetPlugin,\n  ): NodeRegistration<NodeTypes | T['type'], Nodes | T> {\n    const newRegistration = this as NodeRegistration<NodeTypes | T['type'], Nodes | T>;\n\n    const typeStr = definition.impl.create(undefined).type as T['type'];\n\n    if (newRegistration.#infos[typeStr]) {\n      throw new Error(`Duplicate node type: ${typeStr}`);\n    }\n\n    newRegistration.#infos[typeStr] = {\n      displayName: definition.displayName,\n      impl: definition.impl as any,\n      plugin,\n    };\n\n    newRegistration.#implsMap[typeStr] = {\n      impl: definition.impl as any,\n      pluginImpl: undefined,\n    };\n\n    newRegistration.#nodeTypes.push(typeStr);\n\n    return newRegistration;\n  }\n\n  registerPluginNode<T extends ChartNode>(\n    definition: PluginNodeDefinition<T>,\n    plugin: RivetPlugin,\n  ): NodeRegistration<NodeTypes | T['type'], Nodes | T> {\n    const newRegistration = this as NodeRegistration<NodeTypes | T['type'], Nodes | T>;\n\n    const typeStr = definition.impl.create().type as T['type'];\n\n    if (newRegistration.#infos[typeStr]) {\n      throw new Error(`Duplicate node type: ${typeStr}`);\n    }\n\n    const pluginClass = class extends PluginNodeImplClass<T> {\n      static create() {\n        return definition.impl.create();\n      }\n\n      static getUIData(context: RivetUIContext) {\n        return definition.impl.getUIData(context);\n      }\n    };\n\n    newRegistration.#infos[typeStr] = {\n      displayName: definition.displayName,\n      impl: pluginClass as any,\n      plugin,\n      pluginImpl: definition.impl as any,\n    };\n\n    newRegistration.#implsMap[typeStr] = {\n      impl: pluginClass as any,\n      pluginImpl: definition.impl as any,\n    };\n\n    newRegistration.#nodeTypes.push(typeStr);\n\n    return newRegistration;\n  }\n\n  get #dynamicImpls(): Record<\n    string,\n    { impl: NodeImplConstructor<ChartNode>; pluginImpl?: PluginNodeImpl<ChartNode> }\n  > {\n    return this.#implsMap;\n  }\n\n  get #dynamicDisplayNames(): Record<string, string> {\n    const displayNameMap = mapValues(this.#infos, (info) => info.displayName);\n    return displayNameMap as Record<string, string>;\n  }\n\n  registerPlugin(plugin: RivetPlugin) {\n    if (plugin.register) {\n      plugin.register((definition) => this.registerPluginNode(definition, plugin));\n    }\n    this.#plugins.push(plugin);\n  }\n\n  create<T extends NodeTypes>(type: T): Extract<Nodes, { type: T }> {\n    const info = this.#infos[type];\n    if (!info) {\n      throw new Error(`Unknown node type: ${type}`);\n    }\n\n    return info.impl.create(info.pluginImpl) as unknown as Extract<Nodes, { type: T }>;\n  }\n\n  createDynamic(type: string): ChartNode {\n    const implClass = this.#dynamicImpls[type];\n    if (!implClass) {\n      throw new Error(`Unknown node type: ${type}`);\n    }\n    return implClass.impl.create(implClass.pluginImpl);\n  }\n\n  createImpl<T extends Nodes>(node: T): NodeImpl<T> {\n    const type = node.type as Extract<NodeTypes, T['type']>;\n\n    const info = this.#infos[type];\n\n    if (!info) {\n      throw new Error(`Unknown node type: ${type}`);\n    }\n\n    const { impl: ImplClass, pluginImpl } = info;\n\n    const impl = new ImplClass(node as any, pluginImpl) as unknown as NodeImpl<T>;\n    if (!impl) {\n      throw new Error(`Unknown node type: ${type}`);\n    }\n\n    return impl;\n  }\n\n  createDynamicImpl(node: ChartNode): NodeImpl<ChartNode> {\n    const { type } = node;\n    const ImplClass = this.#dynamicImpls[type];\n\n    if (!ImplClass) {\n      throw new Error(`Unknown node type: ${type}`);\n    }\n\n    const impl = new ImplClass.impl(node, ImplClass.pluginImpl) as unknown as NodeImpl<ChartNode>;\n    if (!impl) {\n      throw new Error(`Unknown node type: ${type}`);\n    }\n\n    return impl;\n  }\n\n  getDisplayName<T extends NodeTypes>(type: T): string {\n    const info = this.#infos[type];\n\n    if (!info) {\n      throw new Error(`Unknown node type: ${type}`);\n    }\n\n    return info.displayName;\n  }\n\n  getDynamicDisplayName(type: string) {\n    const displayName = this.#dynamicDisplayNames[type];\n    if (!displayName) {\n      throw new Error(`Unknown node type: ${type}`);\n    }\n\n    return displayName;\n  }\n\n  isRegistered(type: NodeTypes): boolean {\n    return this.#infos[type] !== undefined;\n  }\n\n  getNodeTypes(): NodeTypes[] {\n    return this.#nodeTypes;\n  }\n\n  getNodeConstructors(): NodeImplConstructor<ChartNode>[] {\n    return values(this.#dynamicImpls).map((info) => info.impl);\n  }\n\n  getPluginFor(type: string): RivetPlugin | undefined {\n    const info = this.#infos[type as NodeTypes];\n\n    if (!info) {\n      throw new Error(`Unknown node type: ${type}`);\n    }\n\n    return info.plugin;\n  }\n\n  getPlugins() {\n    return this.#plugins;\n  }\n}\n", "import { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport type { ChartNode, NodeId, NodeInputDefinition, NodeOutputDefinition, PortId } from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { zip } from 'lodash-es';\nimport { type Outputs, type Inputs, type EditorDefinition, type NodeBodySpec } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { coerceType } from '../../utils/coerceType.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\n\nexport type UserInputNode = ChartNode<'userInput', UserInputNodeData>;\n\nexport type UserInputNodeData = {\n  prompt: string;\n  useInput: boolean;\n\n  renderingFormat?: 'preformatted' | 'markdown';\n};\n\nexport class UserInputNodeImpl extends NodeImpl<UserInputNode> {\n  static create(): UserInputNode {\n    const chartNode: UserInputNode = {\n      type: 'userInput',\n      title: 'User Input',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 250,\n      },\n      data: {\n        prompt: 'This is an example question?',\n        useInput: false,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    if (this.chartNode.data.useInput) {\n      return [\n        {\n          dataType: 'string[]',\n          id: 'questions' as PortId,\n          title: 'Questions',\n        },\n      ];\n    }\n    return [];\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        dataType: 'string[]',\n        id: 'output' as PortId,\n        title: 'Answers Only',\n      },\n      {\n        dataType: 'string[]',\n        id: 'questionsAndAnswers' as PortId,\n        title: 'Q & A',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<UserInputNode>[] {\n    return [\n      {\n        type: 'code',\n        label: 'Prompt',\n        dataKey: 'prompt',\n        useInputToggleDataKey: 'useInput',\n        language: 'plain-text',\n      },\n      {\n        type: 'group',\n        label: 'Rendering',\n        editors: [\n          {\n            type: 'dropdown',\n            dataKey: 'renderingFormat',\n            label: 'Format',\n            options: [\n              { label: 'Preformatted', value: 'preformatted' },\n              { label: 'Markdown', value: 'markdown' },\n            ],\n            defaultValue: 'markdown',\n          },\n        ],\n      },\n    ];\n  }\n\n  getBody(): string | NodeBodySpec | undefined {\n    return this.data.useInput ? '(Using input)' : this.data.prompt;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Prompts the user for input during the execution of the graph. The user's response becomes the output of this node.\n      `,\n      infoBoxTitle: 'User Input Node',\n      contextMenuTitle: 'User Input',\n      group: ['Input/Output'],\n    };\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const questions = this.data.useInput ? coerceType(inputs['questions' as PortId], 'string[]') : [this.data.prompt];\n\n    const renderingFormat = this.data.renderingFormat === 'preformatted' ? 'text' : 'markdown';\n\n    const response = await context.requestUserInput(questions, renderingFormat);\n\n    return {\n      ['output' as PortId]: {\n        type: 'string[]',\n        value: response.value,\n      },\n      ['questionsAndAnswers' as PortId]: {\n        type: 'string[]',\n        value: zip(questions, response.value).map(([q, a]) => `${q}\\n${a}`),\n      },\n    };\n  }\n}\n\nexport const userInputNode = nodeDefinition(UserInputNodeImpl, 'User Input');\n", "import type { ChartNode } from './NodeBase.js';\nimport type { NodeImplConstructor, PluginNodeImpl } from './NodeImpl.js';\n\nexport type NodeDefinition<T extends ChartNode> = {\n  impl: NodeImplConstructor<T>;\n  displayName: string;\n};\n\nexport type PluginNodeDefinition<T extends ChartNode> = {\n  impl: PluginNodeImpl<T>;\n  displayName: string;\n};\n\nexport type UnknownNodeDefinition = NodeDefinition<ChartNode>;\n\nexport function nodeDefinition<T extends ChartNode>(\n  impl: NodeImplConstructor<T>,\n  displayName: string,\n): NodeDefinition<T> {\n  return {\n    impl,\n    displayName,\n  };\n}\n\nexport function pluginNodeDefinition<T extends ChartNode>(\n  impl: PluginNodeImpl<T>,\n  displayName: string,\n): PluginNodeDefinition<T> {\n  return {\n    impl,\n    displayName,\n  };\n}\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type DataValue } from '../DataValue.js';\nimport { type EditorDefinition, type NodeBodySpec } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { coerceTypeOptional } from '../../utils/coerceType.js';\nimport { extractInterpolationVariables, interpolate } from '../../utils/interpolation.js';\n\nexport type TextNode = ChartNode<'text', TextNodeData>;\n\nexport type TextNodeData = {\n  text: string;\n  normalizeLineEndings?: boolean;\n};\n\nexport class TextNodeImpl extends NodeImpl<TextNode> {\n  static create(): TextNode {\n    const chartNode: TextNode = {\n      type: 'text',\n      title: 'Text',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 300,\n      },\n      data: {\n        text: '{{input}}',\n        normalizeLineEndings: true, // Default to true for better compatibility\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    // Extract inputs from text, everything like {{input}}\n    const inputNames = extractInterpolationVariables(this.data.text);\n    return (\n      inputNames?.map((inputName) => {\n        return {\n          type: 'string',\n          // id and title should not have the {{ and }}\n          id: inputName as PortId,\n          title: inputName,\n          dataType: 'string',\n          required: false,\n        };\n      }) ?? []\n    );\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'output' as PortId,\n        title: 'Output',\n        dataType: 'string',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<TextNode>[] {\n    return [\n      {\n        type: 'custom',\n        label: 'AI Assist',\n        customEditorId: 'TextNodeAiAssist',\n      },\n      {\n        type: 'code',\n        label: 'Text',\n        dataKey: 'text',\n        language: 'prompt-interpolation-markdown',\n        theme: 'prompt-interpolation',\n      },\n      {\n        type: 'toggle',\n        label: 'Normalize Line Endings',\n        dataKey: 'normalizeLineEndings',\n        helperMessage: 'Normalize line endings to use only LF (\\\\n) instead of CRLF (\\\\r\\\\n).',\n      },\n    ];\n  }\n\n  getBody(): string | NodeBodySpec | undefined {\n    const truncated = this.data.text.split('\\n').slice(0, 15).join('\\n').trim();\n\n    return {\n      type: 'colorized',\n      language: 'prompt-interpolation-markdown',\n      theme: 'prompt-interpolation',\n      text: truncated,\n    };\n  }\n\n  async process(inputs: Record<string, DataValue>, context: any): Promise<Record<string, DataValue>> {\n    const inputMap = Object.keys(inputs).reduce(\n      (acc, key) => {\n        const stringValue = coerceTypeOptional(inputs[key], 'string') ?? '';\n\n        acc[key] = stringValue;\n        return acc;\n      },\n      {} as Record<string, string>,\n    );\n\n    let outputValue = interpolate(\n      this.chartNode.data.text,\n      inputMap,\n      context.graphInputNodeValues, // Pass graph inputs\n      context.contextValues, // Pass context values\n    );\n\n    if (this.chartNode.data.normalizeLineEndings) {\n      outputValue = outputValue.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\n    }\n\n    return {\n      output: {\n        type: 'string',\n        value: outputValue,\n      },\n    };\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Outputs a string of text. It can also interpolate values using <span style=\"color: var(--primary)\">{{tags}}</span>.\n\n        The inputs are dynamic based on the interpolation tags.\n      `,\n      contextMenuTitle: 'Text',\n      infoBoxTitle: 'Text Node',\n      group: ['Common', 'Text'],\n    };\n  }\n}\n\nexport const textNode = nodeDefinition(TextNodeImpl, 'Text');\n", "import { dedent } from './misc.js';\nimport type { DataValue } from '../model/DataValue.js';\nimport { get as lodashGet } from 'lodash-es';\n\n// Simpler regex allowing spaces, relies on trim() later\nexport const TOKEN_MATCH_REGEX = /\\{\\{([^}]+?)\\}\\}/g;\nexport const ESCAPED_TOKEN_REGEX = /\\{\\{\\{([^}]+?)\\}\\}\\}/g;\nexport const ESCAPED_ESCAPED_TOKEN_REGEX = /\\\\\\{\\\\\\{([^}]+?)\\\\\\}\\\\\\}/g;\n\n// Processing functions\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) => {\n    return input.toUpperCase();\n  },\n\n  lowercase: (input: string) => {\n    return input.toLowerCase();\n  },\n\n  trim: (input: string) => {\n    return input.trim();\n  },\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) => {\n    return input.split('\\n').sort().join('\\n');\n  },\n\n  dedent: (input: string) => {\n    return dedent(input);\n  },\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// Helper function to check and potentially unwrap a DataValue-like object\nexport function unwrapPotentialDataValue(value: any): any {\n  if (\n    typeof value === 'object' &&\n    value !== null &&\n    typeof value.type === 'string' &&\n    Object.prototype.hasOwnProperty.call(value, 'value') // More robust check for 'value' property\n  ) {\n    return value.value;\n  }\n  return value;\n}\n\n// Renamed from resolveExpression, now exported and returns raw value\nexport function resolveExpressionRawValue(\n  source: Record<string, any> | undefined,\n  expression: string,\n  sourceType: 'graphInputs' | 'context',\n): any | undefined {\n  if (!source) {\n    return undefined;\n  }\n\n  // Regex to capture the main key and the optional path starting with . or [\n  // Allows for spaces around the key, path, ., and []\n  // Key: Group 1; Path: Group 2\n  const match = expression.trim().match(/^([^[.\\s]+)\\s*(.*)$/);\n\n  let key: string | undefined;\n  let path: string | undefined;\n\n  // Check if match is successful AND group 1 (the key) was captured\n  if (match && typeof match[1] === 'string') {\n    key = match[1];\n    const rawPath = match[2]; // Group 2 (the path part, might start with . or [)\n\n    // Clean and assign path only if rawPath is not empty\n    if (rawPath) {\n      // Clean path: Trim whitespace, then remove spaces around separators '.', '[', ']'\n      // Preserve the leading '.' or '[' as lodashGet handles them.\n      path = rawPath.trim().replace(/\\s*(\\.|\\[|\\])\\s*/g, '$1');\n    } else {\n      path = undefined;\n    }\n  } else {\n    // If match failed or group 1 wasn't captured (fallback)\n    // Assume the entire expression is the key and there's no path\n    key = expression.trim();\n    path = undefined;\n  }\n\n  if (!key) {\n    // If key is empty after trimming, it's invalid.\n    return undefined;\n  }\n\n  const topLevelValue = source[key];\n\n  if (topLevelValue === undefined) {\n    return undefined; // Key not found in source\n  }\n\n  // Get the base value by potentially unwrapping the top-level value using the shared helper\n  const baseValue = unwrapPotentialDataValue(topLevelValue);\n\n  // If there's a path, try to resolve it using lodashGet on the baseValue\n  let finalValue: any;\n  if (path) {\n    try {\n      finalValue = lodashGet(baseValue, path);\n\n      // IMPORTANT: After getting a potentially nested value via path,\n      // we might *still* have a DataValue (if the context stores them nested).\n      // Unwrap again to be safe.\n      finalValue = unwrapPotentialDataValue(finalValue);\n    } catch (error) {\n      console.warn(`Error accessing path \"${path}\" in ${sourceType} value for key \"${key}\":`, error);\n      return undefined; // Error during path access\n    }\n  } else {\n    finalValue = baseValue; // No path, use the (potentially unwrapped) base value\n  }\n\n  // Return the raw final value\n  return finalValue;\n}\n\n// New function: Resolves and converts to string format suitable for TextNode\nexport function resolveExpressionToString(\n  source: Record<string, any> | undefined,\n  expression: string,\n  sourceType: 'graphInputs' | 'context',\n): string | undefined {\n  const finalValue = resolveExpressionRawValue(source, expression, sourceType);\n\n  if (finalValue === undefined) {\n    return undefined;\n  }\n\n  // Convert the final value to a string for TextNode context\n  if (typeof finalValue === 'object' && finalValue !== null) {\n    try {\n      return JSON.stringify(finalValue);\n    } catch (error) {\n      console.warn(`Error stringifying object/array in ${sourceType} for expression \"${expression}\":`, error);\n      return '[object Object]'; // Fallback\n    }\n  }\n\n  // For primitives\n  return String(finalValue);\n}\n\n// Helper function to parse processing instructions like \"indent 2\" or \"quote\" into function name and parameter\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] ? parseInt(parts[1], 10) : undefined,\n  };\n}\n\n// Apply a chain of processing functions to a string\nfunction applyProcessing(value: string, processingChain: string): string {\n  const instructions = processingChain.split('|').slice(1); // Remove the token part\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\nexport function interpolate(\n  template: string,\n  variables: Record<string, DataValue | string | undefined>,\n  graphInputValues?: Record<string, DataValue>,\n  contextValues?: Record<string, DataValue>,\n): string {\n  return template\n    .replace(ESCAPED_TOKEN_REGEX, (_match, expression) => {\n      // Replace with \\{\\{expression\\}\\} to escape\n      return `\\\\{\\\\{${expression}\\\\}\\\\}`; // Escaped token\n    })\n    .replace(/\\{\\{((?:@graphInputs|@context)\\..*?|[^}]+?)\\}\\}/g, (_match, expressionWithMaybeProcessing) => {\n      const parts = expressionWithMaybeProcessing.split('|').map((s: string) => s.trim());\n      const expression = parts[0]!; // The variable name or path, e.g., @context.foo.bar or myVar\n      const processingChain = parts.slice(1).join('|'); // e.g., indent 2 | quote\n\n      let resolvedValue: string | undefined;\n\n      if (expression.startsWith('@graphInputs.')) {\n        // Use the new string-converting function\n        resolvedValue = resolveExpressionToString(\n          graphInputValues,\n          expression.substring('@graphInputs.'.length),\n          'graphInputs',\n        );\n      } else if (expression.startsWith('@context.')) {\n        // Use the new string-converting function\n        resolvedValue = resolveExpressionToString(contextValues, expression.substring('@context.'.length), 'context');\n      } else {\n        const simpleVar = variables[expression];\n        if (simpleVar !== undefined) {\n          // Simple variables might be DataValue or raw strings\n          resolvedValue = String(unwrapPotentialDataValue(simpleVar) ?? '');\n        } else {\n          resolvedValue = undefined; // Variable not found\n        }\n      }\n\n      if (resolvedValue === undefined) {\n        // Return an empty string if the variable is not found or resolves to undefined\n        console.warn(`Interpolation variable or path \"${expression}\" not found or resolved to undefined.`);\n        return '';\n      }\n\n      // Apply processing if any instructions exist\n      if (processingChain) {\n        return applyProcessing(resolvedValue, processingChain);\n      }\n\n      return resolvedValue;\n    })\n    .replace(ESCAPED_ESCAPED_TOKEN_REGEX, (_match, expression) => {\n      // Replace with {{expression}} to unescape\n      return `{{${expression}}}`; // Unescaped token\n    });\n}\n\n// Extract all unique variable names from a template string\n// Ignores variables starting with @graphInputs. or @context., as they are treated as special references.\nexport function extractInterpolationVariables(template: string): string[] {\n  const matches = template\n    .replace(ESCAPED_TOKEN_REGEX, (_match, content) => {\n      // Replace escaped tokens with the escaped escaped version so they're not matched\n      return `\\\\{\\\\{${content}\\\\}\\\\}`;\n    })\n    .matchAll(TOKEN_MATCH_REGEX);\n  const variables = new Set<string>();\n\n  for (const match of matches) {\n    if (match[1]) {\n      const [tokenPart] = match[1].split('|');\n      if (tokenPart) {\n        const token = tokenPart.trim();\n\n        // Filter out special prefixes\n        if (!token.startsWith('@graphInputs.') && !token.startsWith('@context.')) {\n          variables.add(token);\n        }\n      }\n    }\n  }\n\n  return Array.from(variables);\n}\n", "import { type ChartNode, type NodeId, type NodeInputDefinition, type NodeOutputDefinition } from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport type { Inputs, Outputs } from '../GraphProcessor.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { type EditorDefinition } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { ChatNodeBase, type ChatNodeData } from './ChatNodeBase.js';\n\nexport type ChatNode = ChartNode<'chat', ChatNodeData>;\n\nexport class ChatNodeImpl extends NodeImpl<ChatNode> {\n  static create(): ChatNode {\n    const chartNode: ChatNode = {\n      type: 'chat',\n      title: 'Chat',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 200,\n      },\n      data: ChatNodeBase.defaultData(),\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    return ChatNodeBase.getInputDefinitions(this.data);\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return ChatNodeBase.getOutputDefinitions(this.data);\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Makes a call to an LLM chat model. Supports GPT and any OpenAI-compatible API. The settings contains many options for tweaking the model's behavior.\n\n        The \\`System Prompt\\` input specifies a system prompt as the first message to the model. This is useful for providing context to the model.\n\n        The \\`Prompt\\` input takes one or more strings or chat-messages (from a Prompt node) to send to the model.\n      `,\n      contextMenuTitle: 'Chat',\n      infoBoxTitle: 'Chat Node',\n      group: ['Common', 'AI'],\n    };\n  }\n\n  getEditors(): EditorDefinition<ChatNode>[] {\n    return ChatNodeBase.getEditors();\n  }\n\n  getBody() {\n    return ChatNodeBase.getBody(this.data);\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    return ChatNodeBase.process(this.data, this.chartNode, inputs, context);\n  }\n}\n\nexport const chatNode = nodeDefinition(ChatNodeImpl, 'Chat');\n", "import { match } from 'ts-pattern';\nimport { coerceType, coerceTypeOptional } from '../../utils/coerceType.js';\nimport { getError } from '../../utils/errors.js';\nimport { dedent } from '../../utils/misc.js';\nimport {\n  OpenAIError,\n  openAiModelOptions,\n  openaiModels,\n  type ChatCompletionOptions,\n  type ChatCompletionTool,\n  chatCompletions,\n  streamChatCompletions,\n  type ChatCompletionChunkUsage,\n  defaultOpenaiSupported,\n  type OpenAIModel,\n} from '../../utils/openai.js';\nimport { isArrayDataValue, type ChatMessage, getScalarTypeOf, type ScalarDataValue } from '../DataValue.js';\nimport type { EditorDefinition } from '../EditorDefinition.js';\nimport type { ChartNode, NodeInputDefinition, NodeOutputDefinition, PortId } from '../NodeBase.js';\nimport type { ChatNode } from './ChatNode.js';\nimport type { Inputs, Outputs } from '../GraphProcessor.js';\nimport { cleanHeaders, getInputOrData } from '../../utils/inputs.js';\nimport type { InternalProcessContext } from '../ProcessContext.js';\nimport { chatMessageToOpenAIChatCompletionMessage } from '../../utils/chatMessageToOpenAIChatCompletionMessage.js';\nimport { DEFAULT_CHAT_ENDPOINT } from '../../utils/defaults.js';\nimport type { TokenizerCallInfo } from '../../integrations/Tokenizer.js';\nimport { addWarning } from '../../utils/outputs.js';\nimport retry from 'p-retry';\nimport { base64ToUint8Array } from '../../utils/base64.js';\n\nexport type ChatNodeConfigData = {\n  model: string;\n  temperature: number;\n  useTopP: boolean;\n  top_p?: number;\n  maxTokens: number;\n  stop?: string;\n  presencePenalty?: number;\n  frequencyPenalty?: number;\n  enableFunctionUse?: boolean;\n  user?: string;\n  numberOfChoices?: number;\n  endpoint?: string;\n  overrideModel?: string;\n  overrideMaxTokens?: number;\n  headers?: { key: string; value: string }[];\n  seed?: number;\n  toolChoice?: 'none' | 'auto' | 'function';\n  toolChoiceFunction?: string;\n  responseFormat?: '' | 'text' | 'json' | 'json_schema';\n  parallelFunctionCalling?: boolean;\n  additionalParameters?: { key: string; value: string }[];\n  responseSchemaName?: string;\n  useServerTokenCalculation?: boolean;\n  outputUsage?: boolean;\n  usePredictedOutput?: boolean;\n  reasoningEffort?: '' | 'low' | 'medium' | 'high';\n\n  modalitiesIncludeText?: boolean;\n  modalitiesIncludeAudio?: boolean;\n\n  audioVoice?: string;\n  audioFormat?: 'wav' | 'mp3' | 'flac' | 'opus' | 'pcm16';\n};\n\nexport type ChatNodeData = ChatNodeConfigData & {\n  useModelInput: boolean;\n  useTemperatureInput: boolean;\n  useTopPInput: boolean;\n  useTopP: boolean;\n  useUseTopPInput: boolean;\n  useMaxTokensInput: boolean;\n  useStop: boolean;\n  useStopInput: boolean;\n  usePresencePenaltyInput: boolean;\n  useFrequencyPenaltyInput: boolean;\n  useUserInput?: boolean;\n  useNumberOfChoicesInput?: boolean;\n  useEndpointInput?: boolean;\n  useHeadersInput?: boolean;\n  useSeedInput?: boolean;\n  useToolChoiceInput?: boolean;\n  useToolChoiceFunctionInput?: boolean;\n  useResponseFormatInput?: boolean;\n  useAdditionalParametersInput?: boolean;\n  useResponseSchemaNameInput?: boolean;\n  useAudioVoiceInput?: boolean;\n  useAudioFormatInput?: boolean;\n  useReasoningEffortInput?: boolean;\n\n  /** Given the same set of inputs, return the same output without hitting GPT */\n  cache: boolean;\n\n  useAsGraphPartialOutput?: boolean;\n};\n\n// Temporary\nconst cache = new Map<string, Outputs>();\n\nexport const ChatNodeBase = {\n  defaultData: (): ChatNodeData => ({\n    model: 'gpt-4o-mini',\n    useModelInput: false,\n    temperature: 0.5,\n    useTemperatureInput: false,\n    top_p: 1,\n    useTopPInput: false,\n    useTopP: false,\n    useUseTopPInput: false,\n    maxTokens: 1024,\n    useMaxTokensInput: false,\n    useStop: false,\n    stop: '',\n    useStopInput: false,\n    presencePenalty: undefined,\n    usePresencePenaltyInput: false,\n    frequencyPenalty: undefined,\n    useFrequencyPenaltyInput: false,\n    user: undefined,\n    useUserInput: false,\n    enableFunctionUse: false,\n    cache: false,\n    useAsGraphPartialOutput: true,\n    parallelFunctionCalling: true,\n    additionalParameters: [],\n    useAdditionalParametersInput: false,\n    useServerTokenCalculation: true,\n    outputUsage: false,\n    usePredictedOutput: false,\n    modalitiesIncludeAudio: false,\n    modalitiesIncludeText: false,\n    reasoningEffort: '',\n    useReasoningEffortInput: false,\n  }),\n\n  getInputDefinitions: (data: ChatNodeData): NodeInputDefinition[] => {\n    const inputs: NodeInputDefinition[] = [];\n\n    if (data.useEndpointInput) {\n      inputs.push({\n        dataType: 'string',\n        id: 'endpoint' as PortId,\n        title: 'Endpoint',\n        description:\n          'The endpoint to use for the OpenAI API. You can use this to replace with any OpenAI-compatible API. Leave blank for the default: https://api.openai.com/api/v1/chat/completions',\n      });\n    }\n\n    inputs.push({\n      id: 'systemPrompt' as PortId,\n      title: 'System Prompt',\n      dataType: 'string',\n      required: false,\n      description: 'The system prompt to send to the model.',\n      coerced: true,\n    });\n\n    if (data.useModelInput) {\n      inputs.push({\n        id: 'model' as PortId,\n        title: 'Model',\n        dataType: 'string',\n        required: false,\n        description: 'The model to use for the chat.',\n      });\n    }\n\n    if (data.useTemperatureInput) {\n      inputs.push({\n        dataType: 'number',\n        id: 'temperature' as PortId,\n        title: 'Temperature',\n        description:\n          'What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.',\n      });\n    }\n\n    if (data.useTopPInput) {\n      inputs.push({\n        dataType: 'number',\n        id: 'top_p' as PortId,\n        title: 'Top P',\n        description:\n          'An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.',\n      });\n    }\n\n    if (data.useUseTopPInput) {\n      inputs.push({\n        dataType: 'boolean',\n        id: 'useTopP' as PortId,\n        title: 'Use Top P',\n        description: 'Whether to use top p sampling, or temperature sampling.',\n      });\n    }\n\n    if (data.useMaxTokensInput) {\n      inputs.push({\n        dataType: 'number',\n        id: 'maxTokens' as PortId,\n        title: 'Max Tokens',\n        description: 'The maximum number of tokens to generate in the chat completion.',\n      });\n    }\n\n    if (data.useStopInput) {\n      inputs.push({\n        dataType: 'string',\n        id: 'stop' as PortId,\n        title: 'Stop',\n        description: 'A sequence where the API will stop generating further tokens.',\n      });\n    }\n\n    if (data.usePresencePenaltyInput) {\n      inputs.push({\n        dataType: 'number',\n        id: 'presencePenalty' as PortId,\n        title: 'Presence Penalty',\n        description: `Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.`,\n      });\n    }\n\n    if (data.useFrequencyPenaltyInput) {\n      inputs.push({\n        dataType: 'number',\n        id: 'frequencyPenalty' as PortId,\n        title: 'Frequency Penalty',\n        description: `Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.`,\n      });\n    }\n\n    if (data.useUserInput) {\n      inputs.push({\n        dataType: 'string',\n        id: 'user' as PortId,\n        title: 'User',\n        description:\n          'A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse.',\n      });\n    }\n\n    if (data.useNumberOfChoicesInput) {\n      inputs.push({\n        dataType: 'number',\n        id: 'numberOfChoices' as PortId,\n        title: 'Number of Choices',\n        description: 'If greater than 1, the model will return multiple choices and the response will be an array.',\n      });\n    }\n\n    if (data.useHeadersInput) {\n      inputs.push({\n        dataType: 'object',\n        id: 'headers' as PortId,\n        title: 'Headers',\n        description: 'Additional headers to send to the API.',\n      });\n    }\n\n    inputs.push({\n      dataType: ['chat-message', 'chat-message[]'] as const,\n      id: 'prompt' as PortId,\n      title: 'Prompt',\n      description: 'The prompt message or messages to send to the model.',\n      coerced: true,\n    });\n\n    if (data.enableFunctionUse) {\n      inputs.push({\n        dataType: ['gpt-function', 'gpt-function[]'] as const,\n        id: 'functions' as PortId,\n        title: 'Functions',\n        description: 'Functions to use in the model. To connect multiple functions, use an Array node.',\n        coerced: false,\n      });\n    }\n\n    if (data.useSeedInput) {\n      inputs.push({\n        dataType: 'number',\n        id: 'seed' as PortId,\n        title: 'Seed',\n        coerced: true,\n        description:\n          'If specified, OpenAI will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result.',\n      });\n    }\n\n    if (data.useToolChoiceInput) {\n      inputs.push({\n        dataType: 'string',\n        id: 'toolChoice' as PortId,\n        title: 'Tool Choice',\n        coerced: true,\n        description:\n          'Controls which (if any) function is called by the model. `none` is the default when no functions are present. `auto` is the default if functions are present. `function` forces the model to call a function.',\n      });\n    }\n\n    if (data.useToolChoiceInput || data.useToolChoiceFunctionInput) {\n      inputs.push({\n        dataType: 'string',\n        id: 'toolChoiceFunction' as PortId,\n        title: 'Tool Choice Function',\n        coerced: true,\n        description: 'The name of the function to force the model to call.',\n      });\n    }\n\n    if (data.useResponseFormatInput) {\n      inputs.push({\n        dataType: 'string',\n        id: 'responseFormat' as PortId,\n        title: 'Response Format',\n        coerced: true,\n        description: 'The format to force the model to reply in.',\n      });\n    }\n\n    if (data.useAdditionalParametersInput) {\n      inputs.push({\n        dataType: 'object',\n        id: 'additionalParameters' as PortId,\n        title: 'Additional Parameters',\n        description: 'Additional chat completion parameters to send to the API.',\n      });\n    }\n\n    if (data.responseFormat === 'json_schema') {\n      inputs.push({\n        dataType: 'object',\n        id: 'responseSchema' as PortId,\n        title: 'Response Schema',\n        description: 'The JSON schema that the response will adhere to (Structured Outputs).',\n        required: true,\n      });\n\n      if (data.useResponseSchemaNameInput) {\n        inputs.push({\n          dataType: 'string',\n          id: 'responseSchemaName' as PortId,\n          title: 'Response Schema Name',\n          description: 'The name of the JSON schema that the response will adhere to (Structured Outputs).',\n          required: false,\n        });\n      }\n    }\n\n    if (data.usePredictedOutput) {\n      inputs.push({\n        dataType: 'string[]',\n        id: 'predictedOutput' as PortId,\n        title: 'Predicted Output',\n        description: 'The predicted output from the model.',\n        coerced: true,\n      });\n    }\n\n    if (data.useAudioVoiceInput) {\n      inputs.push({\n        dataType: 'string',\n        id: 'audioVoice' as PortId,\n        title: 'Audio Voice',\n        description: 'The voice to use for audio responses. See your model for supported voices.',\n      });\n    }\n\n    if (data.useAudioFormatInput) {\n      inputs.push({\n        dataType: 'string',\n        id: 'audioFormat' as PortId,\n        title: 'Audio Format',\n        description: 'The format to use for audio responses.',\n      });\n    }\n\n    return inputs;\n  },\n\n  getOutputDefinitions: (data: ChatNodeData): NodeInputDefinition[] => {\n    const outputs: NodeOutputDefinition[] = [];\n\n    if (data.useNumberOfChoicesInput || (data.numberOfChoices ?? 1) > 1) {\n      outputs.push({\n        dataType: 'string[]',\n        id: 'response' as PortId,\n        title: 'Responses',\n        description: 'All responses from the model.',\n      });\n    } else {\n      outputs.push({\n        dataType: 'string',\n        id: 'response' as PortId,\n        title: 'Response',\n        description: 'The textual response from the model.',\n      });\n    }\n\n    if (data.enableFunctionUse) {\n      if (data.parallelFunctionCalling) {\n        outputs.push({\n          dataType: 'object[]',\n          id: 'function-calls' as PortId,\n          title: 'Function Calls',\n          description: 'The function calls that were made, if any.',\n        });\n      } else {\n        outputs.push({\n          dataType: 'object',\n          id: 'function-call' as PortId,\n          title: 'Function Call',\n          description: 'The function call that was made, if any.',\n        });\n      }\n    }\n\n    outputs.push({\n      dataType: 'chat-message[]',\n      id: 'in-messages' as PortId,\n      title: 'Messages Sent',\n      description: 'All messages sent to the model.',\n    });\n\n    if (!(data.useNumberOfChoicesInput || (data.numberOfChoices ?? 1) > 1)) {\n      outputs.push({\n        dataType: 'chat-message[]',\n        id: 'all-messages' as PortId,\n        title: 'All Messages',\n        description: 'All messages, with the response appended.',\n      });\n    }\n\n    outputs.push({\n      dataType: 'number',\n      id: 'responseTokens' as PortId,\n      title: 'Response Tokens',\n      description: 'The number of tokens in the response from the LLM. For a multi-response, this is the sum.',\n    });\n\n    if (data.outputUsage) {\n      outputs.push({\n        dataType: 'object',\n        id: 'usage' as PortId,\n        title: 'Usage',\n        description: 'Usage statistics for the model.',\n      });\n    }\n\n    if (data.modalitiesIncludeAudio) {\n      outputs.push({\n        dataType: 'audio',\n        id: 'audio' as PortId,\n        title: 'Audio',\n        description: 'The audio response from the model.',\n      });\n\n      outputs.push({\n        dataType: 'string',\n        id: 'audioTranscript' as PortId,\n        title: 'Transcript',\n        description: 'The transcript of the audio response.',\n      });\n    }\n\n    return outputs;\n  },\n\n  getEditors: (): EditorDefinition<ChatNode>[] => {\n    return [\n      {\n        type: 'dropdown',\n        label: 'GPT Model',\n        dataKey: 'model',\n        useInputToggleDataKey: 'useModelInput',\n        options: openAiModelOptions,\n        disableIf: (data) => {\n          return !!data.overrideModel?.trim();\n        },\n        helperMessage: (data) => {\n          if (data.overrideModel?.trim()) {\n            return `Model overridden to: ${data.overrideModel}`;\n          }\n          if (data.model === 'local-model') {\n            return 'Local model is an indicator for your own convenience, it does not affect the local LLM used.';\n          }\n        },\n      },\n      {\n        type: 'group',\n        label: 'Parameters',\n        editors: [\n          {\n            type: 'number',\n            label: 'Temperature',\n            dataKey: 'temperature',\n            useInputToggleDataKey: 'useTemperatureInput',\n            min: 0,\n            max: 2,\n            step: 0.1,\n            helperMessage:\n              'What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.',\n          },\n          {\n            type: 'number',\n            label: 'Top P',\n            dataKey: 'top_p',\n            useInputToggleDataKey: 'useTopPInput',\n            min: 0,\n            max: 1,\n            step: 0.1,\n            helperMessage:\n              'An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.',\n          },\n          {\n            type: 'toggle',\n            label: 'Use Top P',\n            dataKey: 'useTopP',\n            useInputToggleDataKey: 'useUseTopPInput',\n            helperMessage: 'Whether to use top p sampling, or temperature sampling.',\n          },\n          {\n            type: 'number',\n            label: 'Max Tokens',\n            dataKey: 'maxTokens',\n            useInputToggleDataKey: 'useMaxTokensInput',\n            min: 0,\n            max: Number.MAX_SAFE_INTEGER,\n            step: 1,\n            helperMessage: 'The maximum number of tokens to generate in the chat completion.',\n          },\n          {\n            type: 'string',\n            label: 'Stop',\n            dataKey: 'stop',\n            useInputToggleDataKey: 'useStopInput',\n            helperMessage: 'A sequence where the API will stop generating further tokens.',\n          },\n          {\n            type: 'number',\n            label: 'Presence Penalty',\n            dataKey: 'presencePenalty',\n            useInputToggleDataKey: 'usePresencePenaltyInput',\n            min: 0,\n            max: 2,\n            step: 0.1,\n            allowEmpty: true,\n            helperMessage: `Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.`,\n          },\n          {\n            type: 'number',\n            label: 'Frequency Penalty',\n            dataKey: 'frequencyPenalty',\n            useInputToggleDataKey: 'useFrequencyPenaltyInput',\n            min: 0,\n            max: 2,\n            step: 0.1,\n            allowEmpty: true,\n            helperMessage: `Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.`,\n          },\n          {\n            type: 'dropdown',\n            label: 'Reasoning Effort',\n            dataKey: 'reasoningEffort',\n            useInputToggleDataKey: 'useReasoningEffortInput',\n            options: [\n              { value: '', label: 'Unset' },\n              { value: 'low', label: 'Low' },\n              { value: 'medium', label: 'Medium' },\n              { value: 'high', label: 'High' },\n            ],\n            defaultValue: '',\n            helperMessage:\n              'Adjust the level of reasoning depth the model should apply. Only applies to reasoning models such as o3-mini.',\n          },\n          {\n            type: 'dropdown',\n            label: 'Response Format',\n            dataKey: 'responseFormat',\n            useInputToggleDataKey: 'useResponseFormatInput',\n            options: [\n              { value: '', label: 'Default' },\n              { value: 'text', label: 'Text' },\n              { value: 'json', label: 'JSON Object' },\n              { value: 'json_schema', label: 'JSON Schema' },\n            ],\n            defaultValue: '',\n            helperMessage: 'The format to force the model to reply in.',\n          },\n          {\n            type: 'string',\n            label: 'Response Schema Name',\n            dataKey: 'responseSchemaName',\n            useInputToggleDataKey: 'useResponseSchemaNameInput',\n            helperMessage:\n              'The name of the JSON schema that the response will adhere to (Structured Outputs). Defaults to response_schema',\n            hideIf: (data) => data.responseFormat !== 'json_schema',\n          },\n          {\n            type: 'number',\n            label: 'Seed',\n            dataKey: 'seed',\n            useInputToggleDataKey: 'useSeedInput',\n            step: 1,\n            allowEmpty: true,\n            helperMessage:\n              'If specified, OpenAI will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result.',\n          },\n        ],\n      },\n      {\n        type: 'group',\n        label: 'GPT Tools',\n        editors: [\n          {\n            type: 'toggle',\n            label: 'Enable Function Use',\n            dataKey: 'enableFunctionUse',\n          },\n          {\n            type: 'toggle',\n            label: 'Enable Parallel Function Calling',\n            dataKey: 'parallelFunctionCalling',\n            hideIf: (data) => !data.enableFunctionUse,\n          },\n          {\n            type: 'dropdown',\n            label: 'Tool Choice',\n            dataKey: 'toolChoice',\n            useInputToggleDataKey: 'useToolChoiceInput',\n            options: [\n              { value: '', label: 'Default' },\n              { value: 'none', label: 'None' },\n              { value: 'auto', label: 'Auto' },\n              { value: 'function', label: 'Function' },\n              { value: 'required', label: 'Required' },\n            ],\n            defaultValue: '',\n            helperMessage:\n              'Controls which (if any) function is called by the model. None is the default when no functions are present. Auto is the default if functions are present.',\n            hideIf: (data) => !data.enableFunctionUse,\n          },\n          {\n            type: 'string',\n            label: 'Tool Choice Function',\n            dataKey: 'toolChoiceFunction',\n            useInputToggleDataKey: 'useToolChoiceFunctionInput',\n            helperMessage: 'The name of the function to force the model to call.',\n            hideIf: (data) => data.toolChoice !== 'function' || !data.enableFunctionUse,\n          },\n        ],\n      },\n      {\n        type: 'group',\n        label: 'Features',\n        editors: [\n          {\n            type: 'toggle',\n            label: 'Enable Predicted Output',\n            dataKey: 'usePredictedOutput',\n            helperMessage:\n              'If on, enables an input port for the predicted output from the model, when many of the output tokens are known ahead of time.',\n          },\n          {\n            type: 'toggle',\n            label: 'Modalities: Text',\n            dataKey: 'modalitiesIncludeText',\n            helperMessage: 'If on, the model will include text in its responses. Only relevant for multimodal models.',\n          },\n          {\n            type: 'toggle',\n            label: 'Modalities: Audio',\n            dataKey: 'modalitiesIncludeAudio',\n            helperMessage: 'If on, the model will include audio in its responses. Only relevant for multimodal models.',\n          },\n          {\n            type: 'string',\n            label: 'Audio Voice',\n            dataKey: 'audioVoice',\n            useInputToggleDataKey: 'useAudioVoiceInput',\n            helperMessage:\n              'The voice to use for audio responses. See your model for supported voices. OpenAI voices are: alloy, ash, coral, echo, fable, onyx, nova, sage, and shimmer.',\n            hideIf: (data) => !data.modalitiesIncludeAudio,\n          },\n          {\n            type: 'dropdown',\n            label: 'Audio Format',\n            dataKey: 'audioFormat',\n            useInputToggleDataKey: 'useAudioFormatInput',\n            options: [\n              { value: 'wav', label: 'WAV' },\n              { value: 'mp3', label: 'MP3' },\n              { value: 'flac', label: 'FLAC' },\n              { value: 'opus', label: 'OPUS' },\n              { value: 'pcm16', label: 'PCM16' },\n            ],\n            defaultValue: 'wav',\n            hideIf: (data) => !data.modalitiesIncludeAudio,\n          },\n        ],\n      },\n      {\n        type: 'group',\n        label: 'Advanced',\n        editors: [\n          {\n            type: 'toggle',\n            label: 'Use Server Token Calculation',\n            dataKey: 'useServerTokenCalculation',\n            helperMessage:\n              'If on, do not calculate token counts on the client side, and rely on the server providing the token count.',\n          },\n          {\n            type: 'toggle',\n            label: 'Output Usage Statistics',\n            dataKey: 'outputUsage',\n            helperMessage: 'If on, output usage statistics for the model, such as token counts and cost.',\n          },\n          {\n            type: 'string',\n            label: 'User',\n            dataKey: 'user',\n            useInputToggleDataKey: 'useUserInput',\n            helperMessage:\n              'A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse.',\n          },\n          {\n            type: 'number',\n            label: 'Number of Choices',\n            dataKey: 'numberOfChoices',\n            useInputToggleDataKey: 'useNumberOfChoicesInput',\n            min: 1,\n            max: 10,\n            step: 1,\n            defaultValue: 1,\n            helperMessage:\n              'If greater than 1, the model will return multiple choices and the response will be an array.',\n          },\n          {\n            type: 'string',\n            label: 'Endpoint',\n            dataKey: 'endpoint',\n            useInputToggleDataKey: 'useEndpointInput',\n            helperMessage:\n              'The endpoint to use for the OpenAI API. You can use this to replace with any OpenAI-compatible API. Leave blank for the default: https://api.openai.com/api/v1/chat/completions',\n          },\n          {\n            type: 'string',\n            label: 'Custom Model',\n            dataKey: 'overrideModel',\n            helperMessage: 'Overrides the model selected above with a custom string for the model.',\n          },\n          {\n            type: 'number',\n            label: 'Custom Max Tokens',\n            dataKey: 'overrideMaxTokens',\n            allowEmpty: true,\n            helperMessage:\n              'Overrides the max number of tokens a model can support. Leave blank for preconfigured token limits.',\n          },\n          {\n            type: 'keyValuePair',\n            label: 'Headers',\n            dataKey: 'headers',\n            useInputToggleDataKey: 'useHeadersInput',\n            keyPlaceholder: 'Header',\n            helperMessage: 'Additional headers to send to the API.',\n          },\n          {\n            type: 'toggle',\n            label: 'Cache In Rivet',\n            dataKey: 'cache',\n            helperMessage:\n              'If on, requests with the same parameters and messages will be cached in Rivet, for immediate responses without an API call.',\n          },\n          {\n            type: 'toggle',\n            label: 'Use for subgraph partial output',\n            dataKey: 'useAsGraphPartialOutput',\n            helperMessage:\n              'If on, streaming responses from this node will be shown in Subgraph nodes that call this graph.',\n          },\n          {\n            type: 'keyValuePair',\n            label: 'Additional Parameters',\n            dataKey: 'additionalParameters',\n            useInputToggleDataKey: 'useAdditionalParametersInput',\n            keyPlaceholder: 'Parameter',\n            valuePlaceholder: 'Value',\n            helperMessage:\n              'Additional chat completion parameters to send to the API. If the value appears to be a number, it will be sent as a number.',\n          },\n        ],\n      },\n    ];\n  },\n\n  getBody: (data: ChatNodeData): string | undefined => {\n    return dedent`\n      ${data.endpoint ? `${data.endpoint}` : ''}\n      ${data.useMaxTokensInput ? 'Max Tokens: (Using Input)' : `${data.maxTokens} tokens`}\n      Model: ${data.useModelInput ? '(Using Input)' : data.overrideModel || data.model}\n      ${data.useTopP ? 'Top P' : 'Temperature'}:\n      ${\n        data.useTopP\n          ? data.useTopPInput\n            ? '(Using Input)'\n            : data.top_p\n          : data.useTemperatureInput\n            ? '(Using Input)'\n            : data.temperature\n      }\n      ${data.useStop ? `Stop: ${data.useStopInput ? '(Using Input)' : data.stop}` : ''}\n      ${\n        (data.frequencyPenalty ?? 0) !== 0\n          ? `Frequency Penalty: ${data.useFrequencyPenaltyInput ? '(Using Input)' : data.frequencyPenalty}`\n          : ''\n      }\n      ${\n        (data.presencePenalty ?? 0) !== 0\n          ? `Presence Penalty: ${data.usePresencePenaltyInput ? '(Using Input)' : data.presencePenalty}`\n          : ''\n      }\n    `.trim();\n  },\n\n  process: async (\n    data: ChatNodeData,\n    node: ChartNode,\n    inputs: Inputs,\n    context: InternalProcessContext,\n  ): Promise<Outputs> => {\n    const output: Outputs = {};\n\n    const model = getInputOrData(data, inputs, 'model');\n    const temperature = getInputOrData(data, inputs, 'temperature', 'number');\n\n    const topP = data.useTopPInput ? coerceTypeOptional(inputs['top_p' as PortId], 'number') ?? data.top_p : data.top_p;\n\n    const useTopP = getInputOrData(data, inputs, 'useTopP', 'boolean');\n    const stop = data.useStopInput\n      ? data.useStop\n        ? coerceTypeOptional(inputs['stop' as PortId], 'string') ?? data.stop\n        : undefined\n      : data.stop;\n\n    const presencePenalty = getInputOrData(data, inputs, 'presencePenalty', 'number');\n    const frequencyPenalty = getInputOrData(data, inputs, 'frequencyPenalty', 'number');\n    const numberOfChoices = getInputOrData(data, inputs, 'numberOfChoices', 'number');\n    const endpoint = getInputOrData(data, inputs, 'endpoint');\n    const overrideModel = getInputOrData(data, inputs, 'overrideModel');\n    const seed = getInputOrData(data, inputs, 'seed', 'number');\n    const responseFormat = getInputOrData(data, inputs, 'responseFormat') as 'text' | 'json' | 'json_schema' | '';\n    const toolChoiceMode = getInputOrData(data, inputs, 'toolChoice', 'string') as 'none' | 'auto' | 'function';\n    const parallelFunctionCalling = getInputOrData(data, inputs, 'parallelFunctionCalling', 'boolean');\n\n    const predictedOutput = data.usePredictedOutput\n      ? coerceTypeOptional(inputs['predictedOutput' as PortId], 'string[]')\n      : undefined;\n\n    const toolChoice: ChatCompletionOptions['tool_choice'] =\n      !toolChoiceMode || !data.enableFunctionUse\n        ? undefined\n        : toolChoiceMode === 'function'\n          ? {\n              type: 'function',\n              function: {\n                name: getInputOrData(data, inputs, 'toolChoiceFunction', 'string'),\n              },\n            }\n          : toolChoiceMode;\n\n    let responseSchema: object | undefined;\n\n    const responseSchemaInput = inputs['responseSchema' as PortId];\n    if (responseSchemaInput?.type === 'gpt-function') {\n      responseSchema = responseSchemaInput.value.parameters;\n    } else if (responseSchemaInput != null) {\n      responseSchema = coerceType(responseSchemaInput, 'object');\n    }\n\n    const openaiResponseFormat = !responseFormat?.trim()\n      ? undefined\n      : responseFormat === 'json'\n        ? ({\n            type: 'json_object',\n          } as const)\n        : responseFormat === 'json_schema'\n          ? {\n              type: 'json_schema' as const,\n              json_schema: {\n                name: getInputOrData(data, inputs, 'responseSchemaName', 'string') || 'response_schema',\n                strict: true,\n                schema: responseSchema ?? {},\n              },\n            }\n          : ({\n              type: 'text',\n            } as const);\n\n    const headersFromData = (data.headers ?? []).reduce(\n      (acc, header) => {\n        acc[header.key] = header.value;\n        return acc;\n      },\n      {} as Record<string, string>,\n    );\n    const additionalHeaders = data.useHeadersInput\n      ? (coerceTypeOptional(inputs['headers' as PortId], 'object') as Record<string, string> | undefined) ??\n        headersFromData\n      : headersFromData;\n\n    const additionalParametersFromData = (data.additionalParameters ?? []).reduce(\n      (acc, param) => {\n        acc[param.key] = Number.isNaN(parseFloat(param.value)) ? param.value : parseFloat(param.value);\n        return acc;\n      },\n      {} as Record<string, string | number>,\n    );\n    const additionalParameters = data.useAdditionalParametersInput\n      ? (coerceTypeOptional(inputs['additionalParameters' as PortId], 'object') as\n          | Record<string, string>\n          | undefined) ?? additionalParametersFromData\n      : additionalParametersFromData;\n\n    // If using a model input, that's priority, otherwise override > main\n    const finalModel = data.useModelInput && inputs['model' as PortId] != null ? model : overrideModel || model;\n\n    const functions = coerceTypeOptional(inputs['functions' as PortId], 'gpt-function[]');\n\n    const tools = (functions ?? []).map(\n      (fn): ChatCompletionTool => ({\n        function: fn,\n        type: 'function',\n      }),\n    );\n\n    const { messages } = getChatNodeMessages(inputs);\n\n    const isReasoningModel = finalModel.startsWith('o1') || finalModel.startsWith('o3') || finalModel.startsWith('o4');\n\n    const completionMessages = await Promise.all(\n      messages.map((message) => chatMessageToOpenAIChatCompletionMessage(message, { isReasoningModel })),\n    );\n\n    let { maxTokens } = data;\n\n    const openaiModel = {\n      ...(openaiModels[model as keyof typeof openaiModels] ?? {\n        maxTokens: data.overrideMaxTokens ?? 8192,\n        cost: {\n          completion: 0,\n          prompt: 0,\n        },\n        displayName: 'Custom Model',\n      }),\n    };\n\n    if (data.overrideMaxTokens) {\n      openaiModel.maxTokens = data.overrideMaxTokens;\n    }\n\n    const isMultiResponse = data.useNumberOfChoicesInput || (data.numberOfChoices ?? 1) > 1;\n\n    // Resolve to final endpoint if configured in ProcessContext\n    const configuredEndpoint = endpoint || context.settings.openAiEndpoint || DEFAULT_CHAT_ENDPOINT;\n    const resolvedEndpointAndHeaders = context.getChatNodeEndpoint\n      ? await context.getChatNodeEndpoint(configuredEndpoint, finalModel)\n      : {\n          endpoint: configuredEndpoint,\n          headers: {},\n        };\n\n    const allAdditionalHeaders = cleanHeaders({\n      ...context.settings.chatNodeHeaders,\n      ...additionalHeaders,\n      ...resolvedEndpointAndHeaders.headers,\n    });\n\n    let inputTokenCount: number = 0;\n\n    const tokenizerInfo: TokenizerCallInfo = {\n      node,\n      model: finalModel,\n      endpoint: resolvedEndpointAndHeaders.endpoint,\n    };\n\n    if (!data.useServerTokenCalculation) {\n      inputTokenCount = await context.tokenizer.getTokenCountForMessages(messages, functions, tokenizerInfo);\n\n      if (inputTokenCount >= openaiModel.maxTokens) {\n        throw new Error(\n          `The model ${model} can only handle ${openaiModel.maxTokens} tokens, but ${inputTokenCount} were provided in the prompts alone.`,\n        );\n      }\n\n      if (inputTokenCount + maxTokens > openaiModel.maxTokens) {\n        const message = `The model can only handle a maximum of ${\n          openaiModel.maxTokens\n        } tokens, but the prompts and max tokens together exceed this limit. The max tokens has been reduced to ${\n          openaiModel.maxTokens - inputTokenCount\n        }.`;\n        addWarning(output, message);\n        maxTokens = Math.floor((openaiModel.maxTokens - inputTokenCount) * 0.95); // reduce max tokens by 5% to be safe, calculation is a little wrong.\n      }\n    }\n\n    const predictionObject = predictedOutput\n      ? predictedOutput.length === 1\n        ? { type: 'content' as const, content: predictedOutput[0]! }\n        : { type: 'content' as const, content: predictedOutput.map((part) => ({ type: 'text', text: part })) }\n      : undefined;\n\n    const voice = getInputOrData(data, inputs, 'audioVoice');\n\n    let modalities: ('text' | 'audio')[] | undefined = [];\n    if (data.modalitiesIncludeText) {\n      modalities.push('text');\n    }\n    if (data.modalitiesIncludeAudio) {\n      modalities.push('audio');\n\n      if (!voice) {\n        throw new Error('Audio voice must be specified if audio is enabled.');\n      }\n    }\n\n    // Errors happen if modalities isn't supported, so omit it if it's empty\n    if (modalities.length === 0) {\n      modalities = undefined;\n    }\n\n    const audio = modalities?.includes('audio')\n      ? {\n          voice,\n          format:\n            (getInputOrData(data, inputs, 'audioFormat') as 'wav' | 'mp3' | 'flac' | 'opus' | 'pcm16' | undefined) ??\n            'wav',\n        }\n      : undefined;\n\n    const reasoningEffort = getInputOrData(data, inputs, 'reasoningEffort') as '' | 'low' | 'medium' | 'high';\n\n    const supported =\n      (openaiModels[finalModel as keyof typeof openaiModels] as OpenAIModel | undefined)?.supported ??\n      defaultOpenaiSupported;\n\n    try {\n      return await retry(\n        async () => {\n          const options: Omit<ChatCompletionOptions, 'auth' | 'signal'> = {\n            messages: completionMessages,\n            model: finalModel,\n            top_p: useTopP ? topP : undefined,\n            n: numberOfChoices,\n            frequency_penalty: frequencyPenalty,\n            presence_penalty: presencePenalty,\n            stop: stop || undefined,\n            tools: tools.length > 0 ? tools : undefined,\n            endpoint: resolvedEndpointAndHeaders.endpoint,\n            seed,\n            response_format: openaiResponseFormat,\n            tool_choice: toolChoice,\n            parallel_tool_calls:\n              tools.length > 0 && supported.parallelFunctionCalls ? parallelFunctionCalling : undefined,\n            prediction: predictionObject,\n            modalities,\n            audio,\n            reasoning_effort: reasoningEffort || undefined,\n            ...additionalParameters,\n          };\n\n          const isO1Beta = finalModel.startsWith('o1-preview') || finalModel.startsWith('o1-mini');\n\n          if (isReasoningModel) {\n            options.max_completion_tokens = maxTokens;\n          } else {\n            options.temperature = useTopP ? undefined : temperature; // Not supported in o1-preview\n            options.max_tokens = maxTokens;\n          }\n\n          const cacheKey = JSON.stringify(options);\n\n          if (data.cache) {\n            const cached = cache.get(cacheKey);\n            if (cached) {\n              return cached;\n            }\n          }\n\n          const startTime = Date.now();\n\n          // Non-streaming APIs\n          if (isO1Beta || audio) {\n            const response = await chatCompletions({\n              auth: {\n                apiKey: context.settings.openAiKey ?? '',\n                organization: context.settings.openAiOrganization,\n              },\n              headers: allAdditionalHeaders,\n              signal: context.signal,\n              timeout: context.settings.chatNodeTimeout,\n              ...options,\n            });\n\n            if ('error' in response) {\n              throw new OpenAIError(400, response.error);\n            }\n\n            if (isMultiResponse) {\n              output['response' as PortId] = {\n                type: 'string[]',\n                value: response.choices.map((c) => c.message.content!),\n              };\n            } else {\n              output['response' as PortId] = {\n                type: 'string',\n                value: response.choices[0]!.message.content! ?? '',\n              };\n            }\n\n            if (!isMultiResponse) {\n              output['all-messages' as PortId] = {\n                type: 'chat-message[]',\n                value: [\n                  ...messages,\n                  {\n                    type: 'assistant',\n                    message: response.choices[0]!.message.content! ?? '',\n                    function_calls: undefined,\n                    isCacheBreakpoint: false,\n                    function_call: undefined,\n                  },\n                ],\n              };\n            }\n\n            if (modalities?.includes('audio')) {\n              const audioData = response.choices[0]!.message.audio;\n\n              output['audio' as PortId] = {\n                type: 'audio',\n                value: {\n                  data: base64ToUint8Array(audioData!.data),\n                  mediaType: audioFormatToMediaType(audio!.format),\n                },\n              };\n\n              output['audioTranscript' as PortId] = {\n                type: 'string',\n                value: response.choices[0]!.message.audio!.transcript,\n              };\n            }\n\n            output['duration' as PortId] = { type: 'number', value: Date.now() - startTime };\n\n            if (response.usage) {\n              output['usage' as PortId] = {\n                type: 'object',\n                value: response.usage,\n              };\n\n              const costs =\n                finalModel in openaiModels ? openaiModels[finalModel as keyof typeof openaiModels].cost : undefined;\n\n              const promptCostPerThousand = costs?.prompt ?? 0;\n              const completionCostPerThousand = costs?.completion ?? 0;\n              const audioPromptCostPerThousand = costs\n                ? 'audioPrompt' in costs\n                  ? (costs.audioPrompt as number)\n                  : 0\n                : 0;\n              const audioCompletionCostPerThousand = costs\n                ? 'audioCompletion' in costs\n                  ? (costs.audioCompletion as number)\n                  : 0\n                : 0;\n\n              const promptCost = getCostForTokens(\n                response.usage.prompt_tokens_details.text_tokens,\n                promptCostPerThousand,\n              );\n              const completionCost = getCostForTokens(\n                response.usage.completion_tokens_details.text_tokens,\n                completionCostPerThousand,\n              );\n              const audioPromptCost = getCostForTokens(\n                response.usage.prompt_tokens_details.audio_tokens,\n                audioPromptCostPerThousand,\n              );\n              const audioCompletionCost = getCostForTokens(\n                response.usage.completion_tokens_details.audio_tokens,\n                audioCompletionCostPerThousand,\n              );\n\n              output['cost' as PortId] = {\n                type: 'number',\n                value: promptCost + completionCost + audioPromptCost + audioCompletionCost,\n              };\n            }\n\n            Object.freeze(output);\n            cache.set(cacheKey, output);\n\n            return output;\n          }\n\n          const chunks = streamChatCompletions({\n            auth: {\n              apiKey: context.settings.openAiKey ?? '',\n              organization: context.settings.openAiOrganization,\n            },\n            headers: allAdditionalHeaders,\n            signal: context.signal,\n            timeout: context.settings.chatNodeTimeout,\n            ...options,\n          });\n\n          const responseChoicesParts: string[][] = [];\n\n          // First array is the function calls per choice, inner array is the functions calls inside the choice\n          const functionCalls: {\n            type: 'function';\n            id: string;\n            name: string;\n            arguments: string;\n            lastParsedArguments?: unknown;\n          }[][] = [];\n\n          let usage: ChatCompletionChunkUsage | undefined;\n\n          let throttleLastCalledTime = Date.now();\n          const onPartialOutput = (output: Outputs) => {\n            const now = Date.now();\n            if (now - throttleLastCalledTime > (context.settings.throttleChatNode ?? 100)) {\n              context.onPartialOutputs?.(output);\n              throttleLastCalledTime = now;\n            }\n          };\n\n          for await (const chunk of chunks) {\n            if (chunk.usage) {\n              usage = chunk.usage;\n            }\n\n            if (!chunk.choices) {\n              // Could be error for some reason \uD83E\uDD37\u200D\u2642\uFE0F but ignoring has worked for me so far.\n              continue;\n            }\n\n            for (const { delta, index } of chunk.choices) {\n              if (delta.content != null) {\n                responseChoicesParts[index] ??= [];\n                responseChoicesParts[index]!.push(delta.content);\n              }\n\n              if (delta.tool_calls) {\n                // Are we sure that tool_calls will always be full and not a bunch of deltas?\n                functionCalls[index] ??= [];\n\n                for (const toolCall of delta.tool_calls) {\n                  functionCalls[index]![toolCall.index] ??= {\n                    type: 'function',\n                    arguments: '',\n                    lastParsedArguments: undefined,\n                    name: '',\n                    id: '',\n                  };\n\n                  if (toolCall.id) {\n                    functionCalls[index]![toolCall.index]!.id = toolCall.id;\n                  }\n\n                  if (toolCall.function.name) {\n                    functionCalls[index]![toolCall.index]!.name += toolCall.function.name;\n                  }\n\n                  if (toolCall.function.arguments) {\n                    functionCalls[index]![toolCall.index]!.arguments += toolCall.function.arguments;\n\n                    try {\n                      functionCalls[index]![toolCall.index]!.lastParsedArguments = JSON.parse(\n                        functionCalls[index]![toolCall.index]!.arguments,\n                      );\n                    } catch (error) {\n                      // Ignore\n                    }\n                  }\n                }\n              }\n            }\n\n            if (isMultiResponse) {\n              output['response' as PortId] = {\n                type: 'string[]',\n                value: responseChoicesParts.map((parts) => parts.join('')),\n              };\n            } else {\n              output['response' as PortId] = {\n                type: 'string',\n                value: responseChoicesParts[0]?.join('') ?? '',\n              };\n            }\n\n            if (functionCalls.length > 0) {\n              if (isMultiResponse) {\n                output['function-call' as PortId] = {\n                  type: 'object[]',\n                  value: functionCalls.map((functionCalls) => ({\n                    name: functionCalls[0]?.name,\n                    arguments: functionCalls[0]?.lastParsedArguments,\n                    id: functionCalls[0]?.id,\n                  })),\n                };\n              } else {\n                if (data.parallelFunctionCalling) {\n                  output['function-calls' as PortId] = {\n                    type: 'object[]',\n                    value: functionCalls[0]!.map((functionCall) => ({\n                      name: functionCall.name,\n                      arguments: functionCall.lastParsedArguments,\n                      id: functionCall.id,\n                    })),\n                  };\n                } else {\n                  output['function-call' as PortId] = {\n                    type: 'object',\n                    value: {\n                      name: functionCalls[0]![0]?.name,\n                      arguments: functionCalls[0]![0]?.lastParsedArguments,\n                      id: functionCalls[0]![0]?.id,\n                    } as Record<string, unknown>,\n                  };\n                }\n              }\n            }\n\n            onPartialOutput(output);\n          }\n\n          // Call one last time manually to ensure the last output is sent\n          context.onPartialOutputs?.(output);\n\n          if (!isMultiResponse) {\n            output['all-messages' as PortId] = {\n              type: 'chat-message[]',\n              value: [\n                ...messages,\n                {\n                  type: 'assistant',\n                  message: responseChoicesParts[0]?.join('') ?? '',\n                  function_call: functionCalls[0]\n                    ? {\n                        name: functionCalls[0][0]!.name,\n                        arguments: functionCalls[0][0]!.arguments, // Needs the stringified one here in chat list\n                        id: functionCalls[0][0]!.id,\n                      }\n                    : undefined,\n                  function_calls: functionCalls[0]\n                    ? functionCalls[0].map((fc) => ({\n                        name: fc.name,\n                        arguments: fc.arguments,\n                        id: fc.id,\n                      }))\n                    : undefined,\n                },\n              ],\n            };\n          }\n\n          const endTime = Date.now();\n\n          if (responseChoicesParts.length === 0 && functionCalls.length === 0) {\n            throw new Error('No response from OpenAI');\n          }\n\n          let outputTokenCount = 0;\n\n          if (usage) {\n            inputTokenCount = usage.prompt_tokens;\n            outputTokenCount = usage.completion_tokens;\n          }\n\n          output['in-messages' as PortId] = { type: 'chat-message[]', value: messages };\n          output['requestTokens' as PortId] = { type: 'number', value: inputTokenCount * (numberOfChoices ?? 1) };\n\n          if (!data.useServerTokenCalculation) {\n            let responseTokenCount = 0;\n            for (const choiceParts of responseChoicesParts) {\n              responseTokenCount += await context.tokenizer.getTokenCountForString(choiceParts.join(), tokenizerInfo);\n            }\n            outputTokenCount = responseTokenCount;\n          }\n\n          output['responseTokens' as PortId] = { type: 'number', value: outputTokenCount };\n\n          const outputTokensForCostCalculation = usage?.completion_tokens_details\n            ? usage.completion_tokens_details.rejected_prediction_tokens > 0\n              ? usage.completion_tokens_details.rejected_prediction_tokens\n              : usage.completion_tokens\n            : outputTokenCount;\n\n          const promptCostPerThousand =\n            model in openaiModels ? openaiModels[model as keyof typeof openaiModels].cost.prompt : 0;\n          const completionCostPerThousand =\n            model in openaiModels ? openaiModels[model as keyof typeof openaiModels].cost.completion : 0;\n\n          const promptCost = getCostForTokens(inputTokenCount, promptCostPerThousand);\n          const completionCost = getCostForTokens(outputTokensForCostCalculation, completionCostPerThousand);\n\n          const cost = promptCost + completionCost;\n\n          if (usage) {\n            output['usage' as PortId] = {\n              type: 'object',\n              value: {\n                ...usage,\n                prompt_cost: promptCost,\n                completion_cost: completionCost,\n                total_cost: cost,\n              },\n            };\n          } else {\n            output['usage' as PortId] = {\n              type: 'object',\n              value: {\n                prompt_tokens: inputTokenCount,\n                completion_tokens: outputTokenCount,\n              },\n            };\n          }\n\n          output['cost' as PortId] = { type: 'number', value: cost };\n          output['__hidden_token_count' as PortId] = { type: 'number', value: inputTokenCount + outputTokenCount };\n\n          const duration = endTime - startTime;\n\n          output['duration' as PortId] = { type: 'number', value: duration };\n\n          Object.freeze(output);\n          cache.set(cacheKey, output);\n\n          return output;\n        },\n        {\n          forever: true,\n          retries: 10000,\n          maxRetryTime: 1000 * 60 * 5,\n          factor: 2.5,\n          minTimeout: 500,\n          maxTimeout: 5000,\n          randomize: true,\n          signal: context.signal,\n          onFailedAttempt(originalError) {\n            let err = originalError;\n            if (originalError.toString().includes('fetch failed') && originalError.cause) {\n              const cause =\n                getError(originalError.cause) instanceof AggregateError\n                  ? (originalError.cause as AggregateError).errors[0]\n                  : getError(originalError.cause);\n\n              err = cause;\n            }\n\n            if (context.signal.aborted) {\n              throw new Error('Aborted');\n            }\n\n            context.trace(`ChatNode failed, retrying: ${err.toString()}`);\n\n            const { retriesLeft } = err;\n\n            // Retry network errors\n            if (\n              err.toString().includes('terminated') ||\n              originalError.toString().includes('terminated') ||\n              err.toString().includes('fetch failed')\n            ) {\n              return;\n            }\n\n            if (!(err instanceof OpenAIError)) {\n              if ('code' in err) {\n                throw err;\n              }\n\n              return; // Just retry?\n            }\n\n            if (err.status === 429) {\n              if (retriesLeft) {\n                context.onPartialOutputs?.({\n                  ['response' as PortId]: {\n                    type: 'string',\n                    value: 'OpenAI API rate limit exceeded, retrying...',\n                  },\n                });\n                return;\n              }\n            }\n\n            if (err.status === 408) {\n              if (retriesLeft) {\n                context.onPartialOutputs?.({\n                  ['response' as PortId]: {\n                    type: 'string',\n                    value: 'OpenAI API timed out, retrying...',\n                  },\n                });\n                return;\n              }\n            }\n\n            // We did something wrong (besides rate limit)\n            if (err.status >= 400 && err.status < 500) {\n              throw new Error(err.message);\n            }\n          },\n        },\n      );\n    } catch (error) {\n      context.trace(getError(error).stack ?? 'Missing stack');\n      throw new Error(`Error processing ChatNode: ${(error as Error).message}`, { cause: error });\n    }\n  },\n};\n\nexport function getChatNodeMessages(inputs: Inputs) {\n  const prompt = inputs['prompt' as PortId];\n\n  let messages: ChatMessage[] = match(prompt)\n    .with({ type: 'chat-message' }, (p) => [p.value])\n    .with({ type: 'chat-message[]' }, (p) => p.value)\n    .with({ type: 'string' }, (p): ChatMessage[] => [{ type: 'user', message: p.value }])\n    .with({ type: 'string[]' }, (p): ChatMessage[] => p.value.map((v) => ({ type: 'user', message: v })))\n    .otherwise((p): ChatMessage[] => {\n      if (!p) {\n        return [];\n      }\n\n      if (isArrayDataValue(p)) {\n        const stringValues = (p.value as readonly unknown[]).map((v) =>\n          coerceType(\n            {\n              type: getScalarTypeOf(p.type),\n              value: v,\n            } as ScalarDataValue,\n            'string',\n          ),\n        );\n\n        return stringValues.filter((v) => v != null).map((v) => ({ type: 'user', message: v }));\n      }\n\n      const coercedMessage = coerceTypeOptional(p, 'chat-message');\n      if (coercedMessage != null) {\n        return [coercedMessage];\n      }\n\n      const coercedString = coerceTypeOptional(p, 'string');\n      return coercedString != null ? [{ type: 'user', message: coerceType(p, 'string') }] : [];\n    });\n\n  const systemPrompt = inputs['systemPrompt' as PortId];\n  if (systemPrompt) {\n    if (messages.length > 0 && messages.at(0)!.type === 'system') {\n      // Delete the first system message if it's already there\n      messages.splice(0, 1);\n    }\n\n    messages = [{ type: 'system', message: coerceType(systemPrompt, 'string') }, ...messages];\n  }\n\n  return { messages, systemPrompt };\n}\n\nexport function getCostForTokens(tokenCount: number, costPerThousand: number) {\n  return (tokenCount / 1000) * costPerThousand;\n}\n\nfunction audioFormatToMediaType(format: 'wav' | 'mp3' | 'flac' | 'opus' | 'pcm16') {\n  switch (format) {\n    case 'wav':\n      return 'audio/wav';\n    case 'mp3':\n      return 'audio/mpeg';\n    case 'flac':\n      return 'audio/flac';\n    case 'opus':\n      return 'audio/opus';\n    case 'pcm16':\n      return 'audio/wav';\n  }\n}\n", "import { orderBy } from 'lodash-es';\nimport { DEFAULT_CHAT_NODE_TIMEOUT } from './defaults.js';\nimport fetchEventSource from './fetchEventSource.js';\n\n// https://github.com/openai/openai-node/issues/18#issuecomment-1518715285\n\nexport type OpenAIModel = {\n  maxTokens: number;\n  cost: {\n    prompt: number;\n    completion: number;\n\n    audioPrompt?: number;\n    audioCompletion?: number;\n  };\n  displayName: string;\n\n  supported?: {\n    parallelFunctionCalls: boolean;\n  };\n};\n\nexport const defaultOpenaiSupported: NonNullable<OpenAIModel['supported']> = {\n  parallelFunctionCalls: true,\n};\n\nexport const openaiModels = {\n  'gpt-4': {\n    maxTokens: 8192,\n    cost: {\n      prompt: 0.03,\n      completion: 0.06,\n    },\n    displayName: 'GPT-4',\n  },\n  'gpt-4-32k': {\n    maxTokens: 32768,\n    cost: {\n      prompt: 0.06,\n      completion: 0.12,\n    },\n    displayName: 'GPT-4 32k',\n  },\n  'gpt-4-0613': {\n    maxTokens: 8192,\n    cost: {\n      prompt: 0.03,\n      completion: 0.06,\n    },\n    displayName: 'GPT-4 (v0613)',\n  },\n  'gpt-4-32k-0613': {\n    maxTokens: 32768,\n    cost: {\n      prompt: 0.06,\n      completion: 0.12,\n    },\n    displayName: 'GPT-4 32k (v0613)',\n  },\n  'gpt-4-0314': {\n    maxTokens: 8192,\n    cost: {\n      prompt: 0.03,\n      completion: 0.06,\n    },\n    displayName: 'GPT-4 (v0314)',\n  },\n  'gpt-4-32k-0314': {\n    maxTokens: 32768,\n    cost: {\n      prompt: 0.06,\n      completion: 0.12,\n    },\n    displayName: 'GPT-4 32k (v0314)',\n  },\n  'gpt-4-1106-preview': {\n    maxTokens: 128000,\n    cost: {\n      prompt: 0.01,\n      completion: 0.03,\n    },\n    displayName: 'GPT-4 Turbo 128K (1106 Preview)',\n  },\n  'gpt-4-turbo': {\n    maxTokens: 128000,\n    cost: {\n      prompt: 0.01,\n      completion: 0.03,\n    },\n    displayName: 'GPT-4 Turbo 128K with Vision',\n  },\n  'gpt-4-vision-preview': {\n    maxTokens: 128000,\n    cost: {\n      prompt: 0.01,\n      completion: 0.03,\n    },\n    displayName: 'GPT-4 Vision (Preview)',\n  },\n  'gpt-4o': {\n    maxTokens: 128000,\n    cost: {\n      prompt: 0.005,\n      completion: 0.015,\n    },\n    displayName: 'GPT-4o',\n  },\n  'gpt-4o-mini': {\n    maxTokens: 128000,\n    cost: {\n      prompt: 0.00015,\n      completion: 0.00075,\n    },\n    displayName: 'GPT-4o mini',\n  },\n  'gpt-4o-mini-2024-07-18': {\n    maxTokens: 128000,\n    cost: {\n      prompt: 0.00015,\n      completion: 0.00075,\n    },\n    displayName: 'GPT-4o mini (2024-07-18)',\n  },\n  o1: {\n    maxTokens: 128000,\n    cost: {\n      prompt: 0.015,\n      completion: 0.6,\n    },\n    displayName: 'o1',\n    supported: {\n      parallelFunctionCalls: false,\n    },\n  },\n  'o1-preview': {\n    maxTokens: 128000,\n    cost: {\n      prompt: 0.015,\n      completion: 0.06,\n    },\n    displayName: 'o1-preview',\n    supported: {\n      parallelFunctionCalls: false,\n    },\n  },\n  'o1-preview-2024-09-12': {\n    maxTokens: 128000,\n    cost: {\n      prompt: 0.015,\n      completion: 0.06,\n    },\n    displayName: 'o1-preview (2024-09-12)',\n    supported: {\n      parallelFunctionCalls: false,\n    },\n  },\n  'o1-mini': {\n    maxTokens: 128000,\n    cost: {\n      prompt: 0.0011,\n      completion: 0.0044,\n    },\n    displayName: 'o1-mini',\n    supported: {\n      parallelFunctionCalls: false,\n    },\n  },\n  'o1-mini-2024-09-12': {\n    maxTokens: 128000,\n    cost: {\n      prompt: 0.0011,\n      completion: 0.0044,\n    },\n    displayName: 'o1-mini (2024-09-12)',\n    supported: {\n      parallelFunctionCalls: false,\n    },\n  },\n  'o3-mini': {\n    maxTokens: 200000,\n    cost: {\n      prompt: 0.0011,\n      completion: 0.0044,\n    },\n    displayName: 'o3-mini',\n    supported: {\n      parallelFunctionCalls: false,\n    },\n  },\n  'o3-mini-2025-01-31': {\n    maxTokens: 200000,\n    cost: {\n      prompt: 0.0011,\n      completion: 0.0044,\n    },\n    displayName: 'o3-mini (2025-01-31)',\n    supported: {\n      parallelFunctionCalls: false,\n    },\n  },\n  'gpt-4o-audio-preview': {\n    maxTokens: 128000,\n    cost: {\n      prompt: 0.0025,\n      completion: 0.01,\n      audioPrompt: 0.04,\n      audioCompletion: 0.08,\n    },\n    displayName: 'GPT-4o Audio (Preview)',\n  },\n  'gpt-4.1': {\n    maxTokens: 1_047_576,\n    cost: {\n      prompt: 2e-6,\n      completion: 8e-6,\n    },\n    displayName: 'GPT-4.1',\n  },\n  o3: {\n    maxTokens: 200_000,\n    cost: {\n      prompt: 10e-6,\n      completion: 40e-6,\n    },\n    displayName: 'o3',\n  },\n  'o4-mini': {\n    maxTokens: 200_000,\n    cost: {\n      prompt: 1.1e-6,\n      completion: 4.4e-6,\n    },\n    displayName: 'o4-mini',\n  },\n  'local-model': {\n    maxTokens: Number.MAX_SAFE_INTEGER,\n    cost: {\n      prompt: 0,\n      completion: 0,\n    },\n    displayName: 'Local Model',\n  },\n} satisfies Record<string, OpenAIModel>;\n\nexport const openAiModelOptions = orderBy(\n  Object.entries(openaiModels).map(([id, { displayName }]) => ({\n    value: id,\n    label: displayName,\n  })),\n  'label',\n);\n\nexport class OpenAIError extends Error {\n  constructor(\n    readonly status: number,\n    readonly responseJson: any,\n  ) {\n    super(`OpenAIError: ${status} ${JSON.stringify(responseJson)}`);\n    this.name = 'OpenAIError';\n  }\n}\n\nexport type ChatCompletionRole = ChatCompletionRequestMessage['role'];\n\nexport type ChatCompletionRequestMessage =\n  | ChatCompletionRequestSystemMessage\n  | ChatCompletionRequestUserMessage\n  | ChatCompletionRequestAssistantMessage\n  | ChatCompletionRequestToolMessage\n  | ChatCompletionRequestDeveloperMessage;\n\nexport type ChatCompletionRequestSystemMessage = {\n  role: 'system';\n  content: string | null;\n};\n\nexport type ChatCompletionRequestDeveloperMessage = {\n  role: 'developer';\n  content: string | null;\n};\n\nexport type ChatCompletionRequestUserMessage = {\n  role: 'user';\n  content: string | ChatCompletionRequestUserMessageContent[];\n};\n\nexport type ChatCompletionRequestUserMessageContent =\n  | ChatCompletionRequestUserMessageTextContent\n  | ChatCompletionRequestUserMessageImageContent;\n\nexport type ChatCompletionRequestUserMessageTextContent = {\n  type: 'text';\n  text: string;\n};\n\nexport type ChatCompletionRequestUserMessageImageContent = {\n  type: 'image_url';\n  image_url: {\n    url: string;\n    /**\n     * low will disable the \u201Chigh res\u201D model. The model will receive a low-res 512 x 512 version of the image, and represent the image with a budget of 65 tokens. This allows the API to return faster responses and consume fewer input tokens for use cases that do not require high detail.\n     * high will enable \u201Chigh res\u201D mode, which first allows the model to see the low res image and then creates detailed crops of input images as 512px squares based on the input image size. Each of the detailed crops uses twice the token budget (65 tokens) for a total of 129 tokens.\n     */\n    detail?: 'low' | 'high';\n  };\n};\n\nexport type ChatCompletionRequestAssistantMessage = {\n  role: 'assistant';\n  content: string | null;\n  tool_calls?: ChatCompletionRequestAssistantMessageToolCall[];\n};\n\nexport type ChatCompletionRequestAssistantMessageToolCall = {\n  type: 'function';\n  id: string;\n  function: GptFunctionCall;\n};\n\nexport type ChatCompletionRequestToolMessage = {\n  role: 'tool';\n  content: string | null;\n  tool_call_id: string;\n};\n\n// https://platform.openai.com/docs/api-reference/chat/create\nexport type ChatCompletionOptions = {\n  endpoint: string;\n  auth: { apiKey: string; organization?: string };\n  headers?: Record<string, string>;\n  signal?: AbortSignal;\n\n  /** The timeout in milliseconds before an initial response, before retrying. */\n  timeout?: number;\n\n  model: string;\n  messages: ChatCompletionRequestMessage[];\n  temperature?: number;\n  top_p?: number;\n  max_tokens?: number;\n\n  /** Only for o1 series of models. Otherwise max_tokens. */\n  max_completion_tokens?: number;\n\n  n?: number;\n  stop?: string | string[];\n  presence_penalty?: number;\n  frequency_penalty?: number;\n  logit_bias?: {\n    [key: number]: number;\n  };\n\n  /** This feature is in Beta. If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same seed and parameters should return the same result. Determinism is not guaranteed, and you should refer to the system_fingerprint response parameter to monitor changes in the backend. */\n  seed?: number;\n\n  tools?: ChatCompletionTool[];\n  tool_choice?:\n    | 'none'\n    | 'auto'\n    | 'required'\n    | {\n        type: 'function';\n        function: {\n          name: string;\n        };\n      };\n  parallel_tool_calls?: boolean;\n\n  /** An object specifying the format that the model must output. Used to enable JSON mode. */\n  response_format?:\n    | {\n        type: 'text';\n      }\n    | {\n        /**\n         * Setting to json_object enables JSON mode. This guarantees that the message the model generates is valid JSON.\n         * Note that your system prompt must still instruct the model to produce JSON, and to help ensure you don't forget, the API will throw an error if the string JSON does not appear in your system message. Also note that the message content may be partial (i.e. cut off) if finish_reason=\"length\", which indicates the generation exceeded max_tokens or the conversation exceeded the max context length.\n         * Must be one of text or json_object.\n         */\n        type: 'json_object';\n      }\n    | {\n        type: 'json_schema';\n        json_schema: {\n          name: string;\n          strict: boolean;\n          schema: object;\n        };\n      };\n\n  prediction?: {\n    type: 'content';\n    content: string | { type: string; text: string }[];\n  };\n\n  modalities: ('text' | 'audio')[] | undefined;\n\n  audio?: {\n    voice: string;\n    format: 'wav' | 'mp3' | 'flac' | 'opus' | 'pcm16';\n  };\n\n  reasoning_effort?: 'low' | 'medium' | 'high';\n};\n\nexport type ChatCompletionResponse =\n  | {\n      /** A unique identifier for the chat completion. */\n      id: string;\n\n      /** The object type, which is always chat.completion. */\n      object: 'text_completion';\n\n      /** The Unix timestamp (in seconds) of when the chat completion was created. */\n      created: number;\n\n      /** The model used for the chat completion. */\n      model: string;\n\n      /**\n       * This fingerprint represents the backend configuration that the model runs with.\n       * Can be used in conjunction with the seed request parameter to understand when backend changes have been made that might impact determinism.\n       */\n      system_fingerprint: string;\n\n      /** Usage statistics for the completion request. */\n      usage: {\n        /** Number of tokens in the generated completion. */\n        completion_tokens: number;\n\n        /** Number of tokens in the prompt. */\n        prompt_tokens: number;\n\n        /** Total number of tokens used in the request (prompt + completion). */\n        total_tokens: number;\n\n        prompt_tokens_details: {\n          /** Number of tokens used from the cache. */\n          cached_tokens: number;\n\n          /** Number of tokens used for audio. */\n          audio_tokens: number;\n\n          text_tokens: number;\n\n          image_tokens: number;\n        };\n\n        completion_tokens_details: {\n          /** Number of tokens used for reasoning. */\n          reasoning_tokens: number;\n\n          /** Number of tokens used for audio. */\n          audio_tokens: number;\n\n          /** Number of tokens used for accepted predictions. */\n          accepted_prediction_tokens: number;\n\n          /** Number of tokens used for rejected predictions. */\n          rejected_prediction_tokens: number;\n\n          text_tokens: number;\n        };\n      };\n\n      /** A list of chat completion choices. Can be more than one if n is greater than 1. */\n      choices: ChatCompletionResponseChoice[];\n    }\n  | {\n      error: {\n        message: string;\n      };\n    };\n\nexport type ChatCompletionResponseChoice = {\n  /** The index of the choice in the list of choices. */\n  index: number;\n\n  /**\n   * The reason the model stopped generating tokens. This will be stop if the model hit a natural stop point or a provided stop sequence,\n   * length if the maximum number of tokens specified in the request was reached, content_filter if content was omitted due to a flag\n   * from our content filters, tool_calls if the model called a tool, or function_call (deprecated) if the model called a function.\n   */\n  finish_reason: 'stop' | 'length' | 'content_filter' | 'insufficient_tokens' | 'tool_calls';\n\n  /** A chat completion message generated by the model. */\n  message: ChatCompletionResponseMessage;\n};\n\nexport type ChatCompletionResponseMessage = {\n  /** The role of the author of this message. */\n  role: ChatCompletionRole;\n\n  /** The contents of the message. */\n  content: string | null;\n\n  /** The tool calls generated by the model, such as function calls. */\n  tool_calls: OpenAIFunctionToolCall[];\n\n  refusal: string | null;\n\n  audio?: {\n    id: string;\n    data: string;\n    expires_at: number;\n    transcript: string;\n  };\n};\n\nexport type ChatCompletionChunk = {\n  object: 'chat.completion.chunk';\n  created: number;\n  model: string;\n  choices?: ChatCompletionChunkChoice[];\n  usage?: ChatCompletionChunkUsage;\n};\n\nexport type ChatCompletionChunkUsage = {\n  prompt_tokens: number;\n  completion_tokens: number;\n  total_tokens: number;\n\n  prompt_tokens_details: {\n    cached_tokens: number;\n    audio_tokens: number;\n  };\n\n  completion_tokens_details: {\n    reasoning_tokens: number;\n    audio_tokens: number;\n    accepted_prediction_tokens: number;\n    rejected_prediction_tokens: number;\n  };\n};\n\nexport type GptFunctionCall = {\n  name: string;\n  arguments: string;\n};\n\nexport type GptFunctionCallDelta = {\n  name?: string;\n  arguments?: string;\n};\n\nexport type ChatCompletionChunkChoice = {\n  index: number;\n  message_index: number;\n  delta: {\n    role?: 'assistant';\n    content?: string;\n    tool_calls?: ChatCompletionChunkChoiceToolCall[];\n  };\n  finish_reason: null | 'stop' | 'length' | 'insufficient_tokens' | 'content_filter' | 'tool_calls';\n};\n\nexport type ChatCompletionChunkChoiceToolCall = {\n  index: number;\n  id: string;\n  type: 'function';\n  function: GptFunctionCall;\n};\n\nexport type ChatCompletionTool = ChatCompletionFunctionTool;\n\nexport type ChatCompletionFunctionTool = {\n  type: 'function';\n  function: ChatCompletionFunction;\n};\n\nexport type ChatCompletionFunction = {\n  name: string;\n  description: string;\n  parameters: object;\n  strict: boolean;\n};\n\nexport async function chatCompletions({\n  endpoint,\n  auth,\n  signal,\n  headers,\n  timeout,\n  ...rest\n}: ChatCompletionOptions): Promise<ChatCompletionResponse> {\n  const abortSignal = signal ?? new AbortController().signal;\n\n  const response = await fetch(endpoint, {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application/json',\n      Authorization: `Bearer ${auth.apiKey}`,\n      ...(auth.organization ? { 'OpenAI-Organization': auth.organization } : {}),\n      ...headers,\n    },\n    body: JSON.stringify(rest),\n    signal: abortSignal,\n  });\n\n  return response.json();\n}\n\nexport async function* streamChatCompletions({\n  endpoint,\n  auth,\n  signal,\n  headers,\n  timeout,\n  ...rest\n}: ChatCompletionOptions): AsyncGenerator<ChatCompletionChunk> {\n  const abortSignal = signal ?? new AbortController().signal;\n\n  const response = await fetchEventSource(\n    endpoint,\n    {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application/json',\n        Authorization: `Bearer ${auth.apiKey}`,\n        ...(auth.organization ? { 'OpenAI-Organization': auth.organization } : {}),\n        ...headers,\n      },\n      body: JSON.stringify({\n        ...rest,\n        stream: true,\n        stream_options: {\n          include_usage: true,\n        },\n      }),\n      signal: abortSignal,\n    },\n    timeout ?? DEFAULT_CHAT_NODE_TIMEOUT,\n  );\n\n  let hadChunks = false;\n\n  for await (const chunk of response.events()) {\n    hadChunks = true;\n\n    if (chunk === '[DONE]' || abortSignal?.aborted) {\n      return;\n    }\n    let data: ChatCompletionChunk;\n    try {\n      data = JSON.parse(chunk);\n    } catch (err) {\n      console.error('JSON parse failed on chunk: ', chunk);\n      throw err;\n    }\n\n    yield data;\n  }\n\n  if (!hadChunks) {\n    const responseJson = await response.json();\n    throw new OpenAIError(response.status, responseJson);\n  }\n}\n\nexport type OpenAIAssistant = {\n  /** The identifier, which can be referenced in API endpoints. */\n  id: string;\n\n  /** The object type, which is always assistant. */\n  object: 'assistant';\n\n  /** The Unix timestamp (in seconds) for when the assistant was created. */\n  created_at: number;\n\n  /** The name of the assistant. The maximum length is 256 characters. */\n  name: string | null;\n\n  /** The description of the assistant. The maximum length is 512 characters. */\n  description: string | null;\n\n  /** ID of the model to use. You can use the List models API to see all of your available models, or see our Model overview for descriptions of them. */\n  model: string;\n\n  /** The system instructions that the assistant uses. The maximum length is 32768 characters. */\n  instructions: string | null;\n\n  /** A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types code_interpreter, retrieval, or function. */\n  tools: OpenAIAssistantTool[];\n\n  /** A list of file IDs attached to this assistant. There can be a maximum of 20 files attached to the assistant. Files are ordered by their creation date in ascending order. */\n  file_ids: string[];\n\n  /** Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. */\n  metadata: Record<string, string>;\n};\n\nexport type OpenAIAssistantCodeInterpreterTool = {\n  /** The type of tool being defined: code_interpreter */\n  type: 'code_interpreter';\n};\n\nexport type OpenAIAssistantRetrievalTool = {\n  /** The type of tool being defined: retrieval */\n  type: 'retrieval';\n};\n\nexport type OpenAIAssistantFunctionTool = {\n  /** The type of tool being defined: function */\n  type: 'function';\n\n  /** The function definition. */\n  function: ChatCompletionFunction;\n};\n\nexport type OpenAIAssistantTool =\n  | OpenAIAssistantCodeInterpreterTool\n  | OpenAIAssistantRetrievalTool\n  | OpenAIAssistantFunctionTool;\n\n/**\n * POST https://api.openai.com/v1/assistants\n * Create an assistant with a model and instructions.\n */\nexport type CreateAssistantBody = {\n  /** ID of the model to use. You can use the List models API to see all of your available models, or see our Model overview for descriptions of them. */\n  model?: string;\n\n  /** The name of the assistant. The maximum length is 256 characters. */\n  name?: string | null;\n\n  /** The description of the assistant. The maximum length is 512 characters. */\n  description?: string | null;\n\n  /** The system instructions that the assistant uses. The maximum length is 32768 characters. */\n  instructions?: string | null;\n\n  /** A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types code_interpreter, retrieval, or function. */\n  tools?: OpenAIAssistantTool[];\n\n  /** A list of file IDs attached to this assistant. There can be a maximum of 20 files attached to the assistant. Files are ordered by their creation date in ascending order. */\n  file_ids?: string[];\n\n  /** Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. */\n  metadata?: Record<string, string>;\n};\n\nexport type CreateAssistantResponse = OpenAIAssistant;\n\nexport type OpenAIPaginationQuery = {\n  /** A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. */\n  limit?: string;\n\n  /** Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. */\n  order?: string;\n\n  /** A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. */\n  after?: string;\n\n  /** A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. */\n  before?: string;\n};\n\nexport type OpenAIAssistantFile = {\n  /** The identifier, which can be referenced in API endpoints. */\n  id: string;\n\n  /** The object type, which is always assistant.file. */\n  object: 'assistant.file';\n\n  /** The Unix timestamp (in seconds) for when the assistant file was created. */\n  created_at: number;\n\n  /** The assistant ID that the file is attached to. */\n  assistant_id: string;\n};\n\nexport type CreateAssistantFileBody = {\n  file_id: string;\n};\n\nexport type OpenAIFile = {\n  /** The file identifier, which can be referenced in the API endpoints. */\n  id: string;\n\n  /** The size of the file, in bytes. */\n  bytes: number;\n\n  /** The Unix timestamp (in seconds) for when the file was created. */\n  created_at: number;\n\n  /** The name of the file. */\n  filename: string;\n\n  /** The object type, which is always file. */\n  object: 'file';\n\n  /** The intended purpose of the file. Supported values are fine-tune, fine-tune-results, assistants, and assistants_output. */\n  purpose: OpenAIFilePurpose;\n};\n\nexport type OpenAIFilePurpose = 'fine-tune' | 'fine-tune-results' | 'assistants' | 'assistants_output';\n\nexport const openAIFilePurposeOptions = [\n  { value: 'fine-tune', label: 'Fine-tuning' },\n  { value: 'fine-tune-results', label: 'Fine-tuning Results' },\n  { value: 'assistants', label: 'Assistants' },\n  { value: 'assistants_output', label: 'Assistants Output' },\n];\n\nexport const openAIFileUploadPurposeOptions = [\n  { value: 'fine-tune', label: 'Fine-tuning' },\n  { value: 'assistants', label: 'Assistants' },\n  { value: 'assistants_output', label: 'Assistants Output' },\n];\n\nexport type OpenAIThread = {\n  /** The identifier, which can be referenced in API endpoints. */\n  id: string;\n\n  /** The object type, which is always thread. */\n  object: 'thread';\n\n  /** The Unix timestamp (in seconds) for when the thread was created. */\n  created_at: number;\n\n  /** Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. */\n  metadata: Record<string, string>;\n};\n\nexport type OpenAIThreadMessage = {\n  /** The identifier, which can be referenced in API endpoints. */\n  id: string;\n\n  /** The object type, which is always thread.message. */\n  object: 'thread.message';\n\n  /** The Unix timestamp (in seconds) for when the message was created. */\n  created_at: number;\n\n  /** The thread ID that this message belongs to. */\n  thread_id: string;\n\n  /** The entity that produced the message. One of user or assistant. */\n  role: 'user' | 'assistant';\n\n  /** The content of the message in array of text and/or images. */\n  content: OpenAIThreadMessageContent[];\n};\n\nexport type OpenAIThreadMessageContent = OpenAIThreadMessageImageFileContent | OpenAIThreadMessageTextContent;\n\n/** References an image File in the content of a message. */\nexport type OpenAIThreadMessageImageFileContent = {\n  /** Always image_file. */\n  type: 'image_file';\n  image_file: {\n    /** The File ID of the image in the message content. */\n    file_id: string;\n  };\n};\n\n/** The text content that is part of a message. */\nexport type OpenAIThreadMessageTextContent = {\n  /** Always text. */\n  type: 'text';\n  text: {\n    /** The data that makes up the text. */\n    value: string;\n    annotations: OpenAIThreadMessageContentAnnotation[];\n  };\n};\n\nexport type OpenAIThreadMessageContentAnnotation =\n  | OpenAIThreadMessageTextContentFileCitationAnnotation\n  | OpenAIThreadMessageTextContentFilePathAnnotation;\n\n/** A citation within the message that points to a specific quote from a specific File associated with the assistant or the message. Generated when the assistant uses the \"retrieval\" tool to search files. */\nexport type OpenAIThreadMessageTextContentFileCitationAnnotation = {\n  /** Always file_citation. */\n  type: 'file_citation';\n\n  /** The text in the message content that needs to be replaced. */\n  text: string;\n\n  file_citation: {\n    /** The ID of the specific File the citation is from. */\n    file_id: string;\n\n    /** The specific quote in the file. */\n    quote: string;\n  };\n\n  start_index: number;\n  end_index: number;\n};\n\n/** A URL for the file that's generated when the assistant used the code_interpreter tool to generate a file. */\nexport type OpenAIThreadMessageTextContentFilePathAnnotation = {\n  /** Always file_path. */\n  type: 'file_path';\n\n  /** The text in the message content that needs to be replaced. */\n  text: string;\n\n  file_path: {\n    /** The ID of the file that was generated. */\n    file_id: string;\n  };\n\n  start_index: number;\n  end_index: number;\n};\n\nexport type CreateMessageBody = {\n  /** The role of the entity that is creating the message. Currently only user is supported. */\n  role: 'user';\n\n  /** The content of the message. */\n  content: string;\n\n  /** A list of File IDs that the message should use. There can be a maximum of 10 files attached to a message. Useful for tools like retrieval and code_interpreter that can access and use files. */\n  file_ids?: string[];\n\n  /** Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. */\n  metadata?: Record<string, string>;\n};\n\nexport type CreateThreadBody = {\n  /** A list of messages to start the thread with. */\n  messages: CreateMessageBody[];\n\n  /** Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. */\n  metadata: Record<string, string>;\n};\n\nexport type OpenAIRun = {\n  /** The identifier, which can be referenced in API endpoints. */\n  id: string;\n\n  /** The object type, which is always assistant.run. */\n  object: 'assistant.run';\n\n  /** The Unix timestamp (in seconds) for when the run was created. */\n  created_at: number;\n\n  /** The ID of the thread that was executed on as a part of this run. */\n  thread_id: string;\n\n  /** The ID of the assistant used for execution of this run. */\n  assistant_id: string;\n\n  /** The status of the run, which can be either queued, in_progress, requires_action, cancelling, cancelled, failed, completed, or expired. */\n  status:\n    | 'queued'\n    | 'in_progress'\n    | 'requires_action'\n    | 'cancelling'\n    | 'cancelled'\n    | 'failed'\n    | 'completed'\n    | 'expired';\n\n  /** Details on the action required to continue the run. Will be null if no action is required. */\n  required_action: OpenAIRunRequiredAction | null;\n\n  /** The last error associated with this run. Will be null if there are no errors. */\n  last_error: {\n    /** One of server_error or rate_limit_exceeded. */\n    code: string;\n\n    /** A human-readable description of the error. */\n    message: string;\n  } | null;\n\n  /** The Unix timestamp (in seconds) for when the run will expire. */\n  expires_at: number;\n\n  /** The Unix timestamp (in seconds) for when the run was started. */\n  started_at: number;\n\n  /** The Unix timestamp (in seconds) for when the run was cancelled. */\n  cancelled_at: number;\n\n  /** The Unix timestamp (in seconds) for when the run failed. */\n  failed_at: number;\n\n  /** The Unix timestamp (in seconds) for when the run was completed. */\n  completed_at: number;\n\n  /** The model that the assistant used for this run. */\n  model: string;\n\n  /** The instructions that the assistant used for this run. */\n  instructions: string;\n\n  /** The list of tools that the assistant used for this run. */\n  tools: OpenAIAssistantTool[];\n\n  /** The list of File IDs the assistant used for this run. */\n  file_ids: string[];\n\n  /** Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. */\n  metadata: Record<string, string>;\n};\n\nexport type OpenAIRunRequiredAction = OpenAIRunRequiredActionSubmitToolOutputs;\n\nexport type OpenAIRunRequiredActionSubmitToolOutputs = {\n  /** For now, this is always submit_tool_outputs. */\n  type: 'submit_tool_outputs';\n\n  /** Details on the tool outputs needed for this run to continue. */\n  submit_tool_outputs: {\n    /** A list of the relevant tool calls. */\n    tool_calls: OpenAIFunctionToolCall[];\n  };\n};\n\nexport type OpenAIRunToolCall = OpenAIFunctionToolCall | OpenAIRunRetrievalToolCall | OpenAIRunCodeInterpreterToolCall;\n\nexport type OpenAIFunctionToolCall = {\n  /** The ID of the tool call. This ID must be referenced when you submit the tool outputs in using the Submit tool outputs to run endpoint. */\n  id: string;\n\n  /** The type of tool call the output is required for. For now, this is always function. */\n  type: 'function';\n\n  /** The function definition. */\n  function: OpenAIRunFunctionToolCallFunction;\n};\n\nexport type OpenAIRunFunctionToolCallFunction = {\n  /** The name of the function. */\n  name: string;\n\n  /** The arguments that the model expects you to pass to the function. */\n  arguments: string;\n\n  /** The output of the function. This will be null if the outputs have not been submitted yet. Ignore when submitting tool calls.  */\n  output?: string | null;\n};\n\nexport type OpenAIRunRetrievalToolCall = {\n  /** The ID of the tool call object. */\n  id: string;\n\n  /** The type of tool call. This is always going to be retrieval for this type of tool call. */\n  type: 'retrieval';\n\n  /** For now, this is always going to be an empty object. */\n  retrieval: {};\n};\n\n/** Details of the Code Interpreter tool call the run step was involved in. */\nexport type OpenAIRunCodeInterpreterToolCall = {\n  /** The ID of the tool call. */\n  id: string;\n\n  /** The type of tool call. This is always going to be code_interpreter for this type of tool call. */\n  type: 'code_interpreter';\n\n  /** The Code Interpreter tool call definition. */\n  code_interpreter: {\n    /**I The input to the Code Interpreter tool call. */\n    input: string;\n\n    /** The outputs from the Code Interpreter tool call. Code Interpreter can output one or more items, including text (logs) or images (image). Each of these are represented by a different object type. */\n    outputs: OpenAIRunCodeInterpreterToolCallOutput[];\n  };\n};\n\nexport type OpenAIRunCodeInterpreterToolCallOutput =\n  | OpenAIRunCodeInterpreterToolCallLogOutput\n  | OpenAIRunCodeInterpreterToolCallImageOutput;\n\n/** Text output from the Code Interpreter tool call as part of a run step. */\nexport type OpenAIRunCodeInterpreterToolCallLogOutput = {\n  /** Always logs. */\n  type: 'logs';\n\n  /** The text output from the Code Interpreter tool call. */\n  logs: string;\n};\n\n/** Code interpreter image output */\nexport type OpenAIRunCodeInterpreterToolCallImageOutput = {\n  /** Always image. */\n  type: 'image';\n  image: {\n    /** The file ID of the image. */\n    file_id: string;\n  };\n};\n\nexport type ListThreadMessagesQuery = {\n  /** A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. */\n  limit?: number;\n\n  /** Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. */\n  order?: string;\n\n  /** A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. */\n  after?: string;\n\n  /** A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. */\n  before?: string;\n};\n\nexport type CreateRunBody = {\n  assistant_id: string;\n  model?: string;\n  instructions?: string;\n  tools?: OpenAIAssistantTool[];\n  metadata?: Record<string, string>;\n};\n\nexport type SubmitToolOutputsBody = {\n  tool_outputs: SubmitToolOutputsBodyToolOutput[];\n};\n\nexport type SubmitToolOutputsBodyToolOutput = {\n  // Dunno why these are optional\n\n  /** The ID of the tool call in the required_action object within the run object the output is being submitted for. */\n  tool_call_id?: string;\n\n  /** The output of the tool call to be submitted to continue the run. */\n  output?: string;\n};\n\n/** Represents a step in execution of a run. */\nexport type OpenAIRunStep = {\n  /** The identifier of the run step, which can be referenced in API endpoints. */\n  id: string;\n\n  /** The object type, which is always `assistant.run.step``. */\n  object: 'thread.run.step';\n\n  /** The Unix timestamp (in seconds) for when the run step was created. */\n  created_at: number;\n\n  /** The ID of the assistant associated with the run step. */\n  assistant_id: string;\n\n  /** The ID of the thread that was run. */\n  thread_id: string;\n\n  /** The ID of the run that this run step is a part of. */\n  run_id: string;\n\n  /** The type of run step, which can be either message_creation or tool_calls. */\n  type: 'message_creation' | 'tool_calls';\n\n  /** The status of the run, which can be either in_progress, cancelled, failed, completed, or expired. */\n  status: 'in_progress' | 'cancelled' | 'failed' | 'completed' | 'expired';\n\n  /** The details of the run step. */\n  step_details: OpenAIRunStepDetails;\n\n  /** The last error associated with this run step. Will be null if there are no errors. */\n  last_error: OpenAIErrorInfo | null;\n\n  /** The Unix timestamp (in seconds) for when the run step expired. A step is considered expired if the parent run is expired. */\n  expired_at: number | null;\n\n  /** The Unix timestamp (in seconds) for when the run step was cancelled. */\n  cancelled_at: number | null;\n\n  /** The Unix timestamp (in seconds) for when the run step failed. */\n  failed_at: number | null;\n\n  /** The Unix timestamp (in seconds) for when the run step completed. */\n  completed_at: number | null;\n\n  /** Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. */\n  metadata: Record<string, string>;\n};\n\nexport type OpenAIRunStepDetails = OpenAIMessageCreationRunStepDetails | OpenAIToolCallRunStepDetails;\n\n/** Details of the message creation by the run step. */\nexport type OpenAIMessageCreationRunStepDetails = {\n  /** Always `message_creation``. */\n  type: 'message_creation';\n\n  message_creation: {\n    /** The ID of the message that was created by this run step. */\n    message_id: string;\n  };\n};\n\nexport type OpenAIErrorInfo = {\n  /** One of server_error or rate_limit_exceeded. */\n  code: 'server_error' | 'rate_limit_exceeded';\n\n  /** A human-readable description of the error. */\n  message: string;\n};\n\nexport type OpenAIToolCallRunStepDetails = {\n  type: 'tool_calls';\n\n  /** An array of tool calls the run step was involved in. These can be associated with one of three types of tools: code_interpreter, retrieval, or function. */\n  tool_calls: OpenAIRunToolCall[];\n};\n\nexport type OpenAIListResponse<T> = {\n  object: 'list';\n  data: T[];\n  first_id: string;\n  last_id: string;\n  has_more: boolean;\n};\n", "import { getError } from './errors.js';\nimport { DEFAULT_CHAT_NODE_TIMEOUT } from './defaults.js';\n\n// https://github.com/openai/openai-node/issues/18#issuecomment-1518715285\nexport class EventSourceResponse extends Response {\n  name: string;\n  timeout?: number;\n  readonly streams: {\n    eventStream: ReadableStream<string>;\n    textStream: ReadableStream<string>;\n  } | null;\n\n  constructor(body: ReadableStream<Uint8Array> | null, init?: ResponseInit, timeout?: number) {\n    if (body == null) {\n      super(null, init);\n      this.name = 'EventSourceResponse';\n      this.streams = null;\n      this.timeout = timeout;\n      return;\n    }\n\n    const [bodyForString, bodyForEvents] = body.tee();\n    const streams = createEventStream(bodyForEvents);\n    // By passing our transformed stream into the Response constructor, we prevent anyone\n    // from accidentally accessing the raw response.body stream.\n    super(bodyForString, init);\n    this.name = 'EventSourceResponse';\n    this.streams = streams;\n    this.timeout = timeout;\n  }\n\n  async *events(): AsyncGenerator<string> {\n    if (this.streams == null) {\n      return;\n    }\n    const reader = this.streams.eventStream.getReader();\n\n    try {\n      while (true) {\n        const { done, value } = await this.raceWithTimeout(reader.read(), this.timeout);\n        if (done) {\n          break;\n        }\n        yield value;\n      }\n    } finally {\n      try {\n        reader.releaseLock();\n      } catch (err) {\n        console.error(`Failed to release read lock on event source: ${getError(err).toString()}`);\n      }\n    }\n  }\n\n  private async raceWithTimeout<T>(promise: Promise<T>, timeout?: number): Promise<T> {\n    const raceTimeout = timeout ?? DEFAULT_CHAT_NODE_TIMEOUT;\n\n    // eslint-disable-next-line no-async-promise-executor,@typescript-eslint/no-misused-promises -- Error handled correctly\n    return new Promise(async (resolve, reject) => {\n      const timer = setTimeout(() => {\n        reject(new Error('Timeout: API response took too long.'));\n      }, raceTimeout);\n\n      try {\n        const result = await promise;\n        clearTimeout(timer);\n        resolve(result);\n      } catch (error) {\n        clearTimeout(timer);\n        reject(error);\n      }\n    });\n  }\n}\n\nexport default async function fetchEventSource(\n  url: string,\n  init?: RequestInit,\n  timeout?: number,\n): Promise<EventSourceResponse> {\n  const headers = {\n    ...init?.headers,\n    accept: 'text/event-stream',\n  };\n\n  const response = await fetch(url, {\n    ...init,\n    headers,\n  });\n\n  return new EventSourceResponse(response.body, response, timeout);\n}\n\nclass LineSplitter implements Transformer<string, string> {\n  private buffer = '';\n  constructor(readonly separator = /\\n+/) {}\n\n  transform(chunk: string, controller: TransformStreamDefaultController<string>): void {\n    this.buffer += chunk;\n    const lines = this.buffer.split(this.separator);\n    this.buffer = lines.pop() ?? '';\n\n    for (const line of lines) {\n      controller.enqueue(line);\n    }\n  }\n\n  flush(controller: TransformStreamDefaultController<string>): void {\n    if (this.buffer.length > 0) {\n      controller.enqueue(this.buffer);\n      this.buffer = '';\n    }\n  }\n}\n\nfunction createEventStream(body: ReadableStream<Uint8Array> | null) {\n  if (body == null) {\n    return null;\n  }\n\n  const textStream = body.pipeThrough(new TextDecoderStream());\n\n  const eventStream = textStream.pipeThrough(new TransformStream(new LineSplitter())).pipeThrough(\n    new TransformStream<string, string>({\n      transform(line, controller) {\n        if (line.trim().length === 0) {\n          return;\n        }\n\n        if (line.startsWith('data: ')) {\n          const data = line.slice(6).trim();\n          controller.enqueue(data);\n        } else if (line.startsWith('event: ')) {\n          const event = line.slice(7).trim();\n          controller.enqueue(`[${event}]`);\n        }\n      },\n    }),\n  );\n  return { eventStream, textStream };\n}\n", "import { match } from 'ts-pattern';\nimport type { ChatMessage } from '../index.js';\nimport { uint8ArrayToBase64 } from './index.js';\nimport type { ChatCompletionRequestMessage, ChatCompletionRequestUserMessageContent } from './openai.js';\n\nexport async function chatMessageToOpenAIChatCompletionMessage(\n  message: ChatMessage,\n  options: { isReasoningModel: boolean },\n): Promise<ChatCompletionRequestMessage> {\n  const onlyStringContent = (message: ChatMessage): string => {\n    const parts = Array.isArray(message.message) ? message.message : [message.message];\n    const stringContent = parts\n      .map((part) => {\n        if (typeof part !== 'string') {\n          throw new Error('System prompt must be a string');\n        }\n\n        return part;\n      })\n      .join('\\n\\n');\n    return stringContent;\n  };\n\n  return match(message)\n    .with({ type: 'system' }, (m): ChatCompletionRequestMessage => {\n      if (options.isReasoningModel) {\n        return {\n          role: 'developer',\n          content: onlyStringContent(m),\n        };\n      } else {\n        return {\n          role: m.type,\n          content: onlyStringContent(m),\n        };\n      }\n    })\n    .with({ type: 'user' }, async (m): Promise<ChatCompletionRequestMessage> => {\n      const parts = Array.isArray(m.message) ? m.message : [m.message];\n\n      if (parts.length === 1 && typeof parts[0] === 'string') {\n        return { role: m.type, content: parts[0] };\n      }\n\n      const chatMessageParts = await Promise.all(\n        parts.map(async (part): Promise<ChatCompletionRequestUserMessageContent> => {\n          if (typeof part === 'string') {\n            return { type: 'text', text: part };\n          }\n\n          const url =\n            part.type === 'url' ? part.url : `data:${part.mediaType};base64,${await uint8ArrayToBase64(part.data)}`;\n\n          return {\n            type: 'image_url',\n            image_url: { url },\n          };\n        }),\n      );\n\n      return { role: m.type, content: chatMessageParts };\n    })\n    .with(\n      { type: 'assistant' },\n      (m): ChatCompletionRequestMessage => ({\n        role: m.type,\n        content: onlyStringContent(m),\n\n        tool_calls: m.function_calls\n          ? m.function_calls.map((fc) => ({\n              id: fc.id ?? 'unknown_function_call',\n              type: 'function',\n              function: fc,\n            }))\n          : m.function_call\n            ? [\n                {\n                  id: m.function_call.id ?? 'unknown_function_call',\n                  type: 'function',\n                  function: m.function_call,\n                },\n              ]\n            : undefined,\n      }),\n    )\n    .with(\n      { type: 'function' },\n      (m): ChatCompletionRequestMessage => ({\n        role: 'tool',\n        content: onlyStringContent(m),\n        tool_call_id: m.name ?? 'unknown_function_call',\n      }),\n    )\n    .exhaustive();\n}\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport {\n  type AssistantChatMessageFunctionCall,\n  type ChatMessage,\n  type EditorDefinition,\n  type Inputs,\n  type InternalProcessContext,\n  type NodeBodySpec,\n  type Outputs,\n} from '../../index.js';\nimport { mapValues } from 'lodash-es';\nimport { dedent } from 'ts-dedent';\nimport { coerceType, coerceTypeOptional } from '../../utils/coerceType.js';\nimport { getInputOrData } from '../../utils/index.js';\nimport { interpolate, extractInterpolationVariables } from '../../utils/interpolation.js';\nimport { match } from 'ts-pattern';\n\nexport type PromptNode = ChartNode<'prompt', PromptNodeData>;\n\nexport type PromptNodeData = {\n  type: 'system' | 'user' | 'assistant' | 'function';\n  useTypeInput: boolean;\n\n  promptText: string;\n\n  name?: string;\n  useNameInput?: boolean;\n  enableFunctionCall?: boolean;\n  computeTokenCount?: boolean;\n\n  isCacheBreakpoint?: boolean;\n  useIsCacheBreakpointInput?: boolean;\n};\n\nexport class PromptNodeImpl extends NodeImpl<PromptNode> {\n  static create(): PromptNode {\n    const chartNode: PromptNode = {\n      type: 'prompt',\n      title: 'Prompt',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 250,\n      },\n      data: {\n        type: 'user',\n        useTypeInput: false,\n        promptText: '{{input}}',\n        enableFunctionCall: false,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    let inputs: NodeInputDefinition[] = [];\n\n    if (this.data.enableFunctionCall) {\n      inputs.push({\n        id: 'function-call' as PortId,\n        title: 'Function Call',\n        dataType: 'object',\n      });\n    }\n\n    if (this.data.useTypeInput) {\n      inputs.push({\n        id: 'type' as PortId,\n        title: 'Type',\n        dataType: 'string',\n      });\n    }\n\n    if (this.data.useNameInput) {\n      inputs.push({\n        id: 'name' as PortId,\n        title: 'Name/ID',\n        dataType: 'string',\n      });\n    }\n\n    if (this.data.useIsCacheBreakpointInput) {\n      inputs.push({\n        id: 'isCacheBreakpoint' as PortId,\n        title: 'Is Cache Breakpoint',\n        dataType: 'boolean',\n      });\n    }\n\n    // Extract inputs from promptText, everything like {{input}}\n    const inputNames = extractInterpolationVariables(this.data.promptText);\n    inputs = [\n      ...inputs,\n      ...(inputNames?.map((inputName): NodeInputDefinition => {\n        return {\n          id: inputName as PortId,\n          title: inputName,\n          dataType: 'string',\n          required: false,\n        };\n      }) ?? []),\n    ];\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    const outputs: NodeOutputDefinition[] = [\n      {\n        id: 'output' as PortId,\n        title: 'Output',\n        dataType: 'chat-message',\n      },\n    ];\n\n    if (this.chartNode.data.computeTokenCount) {\n      outputs.push({\n        id: 'tokenCount' as PortId,\n        title: 'Token Count',\n        dataType: 'number',\n      });\n    }\n\n    return outputs;\n  }\n\n  getEditors(): EditorDefinition<PromptNode>[] {\n    return [\n      {\n        type: 'custom',\n        customEditorId: 'PromptNodeAiAssist',\n        label: 'Generate Using AI',\n      },\n      {\n        type: 'dropdown',\n        label: 'Type',\n        options: [\n          { value: 'system', label: 'System' },\n          { value: 'user', label: 'User' },\n          { value: 'assistant', label: 'Assistant' },\n          { value: 'function', label: 'Function' },\n        ],\n        dataKey: 'type',\n        useInputToggleDataKey: 'useTypeInput',\n      },\n      {\n        type: 'string',\n        label: 'Name',\n        dataKey: 'name',\n        useInputToggleDataKey: 'useNameInput',\n        hideIf: (data) => data.type !== 'function',\n        helperMessage:\n          'For OpenAI, this is the tool call ID. Otherwise, it is the name of the function that is outputting the message.',\n      },\n      {\n        type: 'toggle',\n        label: 'Enable Function Call',\n        dataKey: 'enableFunctionCall',\n        hideIf: (data) => data.type !== 'assistant',\n      },\n      {\n        type: 'toggle',\n        label: 'Compute Token Count',\n        dataKey: 'computeTokenCount',\n      },\n      {\n        type: 'toggle',\n        label: 'Is Cache Breakpoint',\n        dataKey: 'isCacheBreakpoint',\n        helperMessage:\n          'For Anthropic, marks this message as a cache breakpoint - this message and every message before it will be cached using Prompt Caching.',\n        useInputToggleDataKey: 'useIsCacheBreakpointInput',\n      },\n      {\n        type: 'code',\n        label: 'Prompt Text',\n        dataKey: 'promptText',\n        language: 'prompt-interpolation-markdown',\n        theme: 'prompt-interpolation',\n      },\n    ];\n  }\n\n  getBody(): string | NodeBodySpec | NodeBodySpec[] | undefined {\n    return [\n      {\n        type: 'markdown',\n        text: dedent`\n          _${typeDisplay[this.data.type]}${this.data.name ? ` (${this.data.name})` : ''}_ ${this.data.isCacheBreakpoint ? ' (Cache Breakpoint)' : ''}\n      `,\n      },\n      {\n        type: 'colorized',\n        text: this.data.promptText.split('\\n').slice(0, 15).join('\\n').trim(),\n        language: 'prompt-interpolation-markdown',\n        theme: 'prompt-interpolation',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Outputs a chat message, which is a string of text with an attached \"type\" saying who sent the message (User, Assistant, System) and optionally an attached \"name\".\n\n        Also provides the same <span style=\"color: var(--primary)\">{{interpolation}}</span> capabilities as a Text node.\n\n        Can change one chat message type into another chat message type. For example, changing a User message into a System message.\n      `,\n      infoBoxTitle: 'Prompt Node',\n      contextMenuTitle: 'Prompt',\n      group: ['Text'],\n    };\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext<PromptNode>): Promise<Outputs> {\n    const inputMap = mapValues(inputs, (input) => coerceType(input, 'string')) as Record<PortId, string>;\n\n    const outputValue = interpolate(\n      this.chartNode.data.promptText,\n      inputMap,\n      context.graphInputNodeValues,\n      context.contextValues\n    );\n\n    const type = getInputOrData(this.data, inputs, 'type', 'string');\n    const isCacheBreakpoint = getInputOrData(this.data, inputs, 'isCacheBreakpoint', 'boolean');\n\n    if (['assistant', 'system', 'user', 'function'].includes(type) === false) {\n      throw new Error(`Invalid type: ${type}`);\n    }\n\n    const message = match(type)\n      .with(\n        'system',\n        (type): ChatMessage => ({\n          type,\n          message: outputValue,\n          isCacheBreakpoint,\n        }),\n      )\n      .with(\n        'user',\n        (type): ChatMessage => ({\n          type,\n          message: outputValue,\n          isCacheBreakpoint,\n        }),\n      )\n      .with('assistant', (type): ChatMessage => {\n        let functionCall = this.data.enableFunctionCall\n          ? coerceTypeOptional(inputs['function-call' as PortId], 'object')\n          : undefined;\n\n        // If no name is specified, ignore the function call\n        if (!functionCall?.name || !functionCall?.arguments) {\n          functionCall = undefined;\n        }\n\n        // GPT is weird - the arguments should be a stringified JSON object https://platform.openai.com/docs/api-reference/chat/create\n        if (functionCall?.arguments && typeof functionCall.arguments !== 'string') {\n          functionCall.arguments = JSON.stringify(functionCall.arguments);\n        }\n\n        return {\n          type,\n          message: outputValue,\n          function_call: functionCall as AssistantChatMessageFunctionCall,\n          function_calls: functionCall ? [functionCall as AssistantChatMessageFunctionCall] : undefined,\n          isCacheBreakpoint,\n        };\n      })\n      .with(\n        'function',\n        (type): ChatMessage => ({\n          type,\n          message: outputValue,\n          name: getInputOrData(this.data, inputs, 'name', 'string'),\n          isCacheBreakpoint,\n        }),\n      )\n      .otherwise(() => {\n        throw new Error(`Invalid chat-message type: ${type}`);\n      });\n\n    const outputs: Outputs = {\n      ['output' as PortId]: {\n        type: 'chat-message',\n        value: message,\n      },\n    };\n\n    if (this.chartNode.data.computeTokenCount) {\n      const tokenCount = await context.tokenizer.getTokenCountForMessages([message], undefined, {\n        node: this.chartNode,\n      });\n      outputs['tokenCount' as PortId] = {\n        type: 'number',\n        value: tokenCount,\n      };\n    }\n\n    return outputs;\n  }\n}\n\nexport const promptNode = nodeDefinition(PromptNodeImpl, 'Prompt');\n\nconst typeDisplay: Record<PromptNodeData['type'], string> = {\n  assistant: 'Assistant',\n  system: 'System',\n  user: 'User',\n  function: 'Function',\n};\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type DataValue } from '../DataValue.js';\nimport { expectType, expectTypeOptional } from '../../utils/expectType.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { type NodeBodySpec } from '../NodeBodySpec.js';\n\nexport type ExtractRegexNode = ChartNode<'extractRegex', ExtractRegexNodeData>;\n\nexport type ExtractRegexNodeData = {\n  regex: string;\n  useRegexInput: boolean;\n  errorOnFailed: boolean;\n  multilineMode?: boolean;\n};\n\nexport class ExtractRegexNodeImpl extends NodeImpl<ExtractRegexNode> {\n  static create(): ExtractRegexNode {\n    const chartNode: ExtractRegexNode = {\n      type: 'extractRegex',\n      title: 'Extract Regex',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 250,\n      },\n      data: {\n        regex: '([a-zA-Z]+)',\n        useRegexInput: false,\n        errorOnFailed: false,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [\n      {\n        id: 'input' as PortId,\n        title: 'Input',\n        dataType: 'string',\n        required: true,\n        coerced: false,\n      },\n    ];\n\n    if (this.chartNode.data.useRegexInput) {\n      inputs.push({\n        id: 'regex' as PortId,\n        title: 'Regex',\n        dataType: 'string',\n        required: false,\n        coerced: false,\n      });\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    const regex = this.chartNode.data.regex;\n    try {\n      const regExp = new RegExp(regex, 'g');\n      const captureGroupCount = countCaptureGroups(regExp);\n\n      const outputs: NodeOutputDefinition[] = [];\n\n      for (let i = 0; i < captureGroupCount; i++) {\n        outputs.push({\n          id: `output${i + 1}` as PortId,\n          title: `Output ${i + 1}`,\n          dataType: 'string',\n        });\n      }\n\n      outputs.push({\n        id: 'matches' as PortId,\n        title: 'Matches',\n        dataType: 'string[]',\n      });\n\n      outputs.push(\n        {\n          id: 'succeeded' as PortId,\n          title: 'Succeeded',\n          dataType: 'boolean',\n        },\n        {\n          id: 'failed' as PortId,\n          title: 'Failed',\n          dataType: 'boolean',\n        },\n      );\n\n      return outputs;\n    } catch (err) {\n      return [];\n    }\n  }\n\n  getEditors(): EditorDefinition<ExtractRegexNode>[] {\n    return [\n      {\n        type: 'custom',\n        customEditorId: 'ExtractRegexNodeAiAssist',\n        label: 'AI Assist',\n      },\n      {\n        type: 'toggle',\n        label: 'Error on failed',\n        dataKey: 'errorOnFailed',\n      },\n      {\n        type: 'toggle',\n        label: 'Multiline mode',\n        dataKey: 'multilineMode',\n      },\n      {\n        type: 'code',\n        label: 'Regex',\n        dataKey: 'regex',\n        useInputToggleDataKey: 'useRegexInput',\n        language: 'regex',\n      },\n    ];\n  }\n\n  getBody(): string | NodeBodySpec | undefined {\n    return this.data.useRegexInput ? '(Using regex input)' : this.data.regex;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Extracts data from the input text using the configured regular expression. The regular expression can contain capture groups to extract specific parts of the text.\n\n        Each capture group corresponds to an output port of the node.\n      `,\n      infoBoxTitle: 'Extract With Regex Node',\n      contextMenuTitle: 'Extract With Regex',\n      group: ['Text'],\n    };\n  }\n\n  async process(inputs: Record<PortId, DataValue>): Promise<Record<PortId, DataValue>> {\n    const inputString = expectType(inputs['input' as PortId], 'string');\n    const regex = expectTypeOptional(inputs['regex' as PortId], 'string') ?? this.chartNode.data.regex;\n\n    const regExp = new RegExp(regex, this.data.multilineMode ? 'gm' : 'g');\n\n    let matches = [];\n    let match;\n    let firstMatch;\n\n    while ((match = regExp.exec(inputString)) !== null) {\n      if (!firstMatch) {\n        firstMatch = match;\n      }\n      matches.push(match[1]!);\n    }\n\n    matches = matches.filter((m) => m);\n\n    if (matches.length === 0 && this.chartNode.data.errorOnFailed) {\n      throw new Error(`No match found for regex ${regex}`);\n    }\n\n    const outputArray: DataValue = {\n      type: 'string[]',\n      value: matches,\n    };\n\n    if (!firstMatch) {\n      if (this.chartNode.data.errorOnFailed) {\n        throw new Error(`No match found for regex ${regex}`);\n      }\n      return {\n        ['succeeded' as PortId]: {\n          type: 'boolean',\n          value: false,\n        },\n        ['failed' as PortId]: {\n          type: 'boolean',\n          value: true,\n        },\n      };\n    }\n\n    const output: Record<PortId, DataValue> = {};\n\n    for (let i = 1; i < firstMatch.length; i++) {\n      output[`output${i}` as PortId] = {\n        type: 'string',\n        value: firstMatch[i]!,\n      };\n    }\n\n    output['matches' as PortId] = outputArray;\n\n    output['succeeded' as PortId] = {\n      type: 'boolean',\n      value: true,\n    };\n    output['failed' as PortId] = {\n      type: 'boolean',\n      value: false,\n    };\n\n    return output;\n  }\n}\n\nfunction countCaptureGroups(regex: RegExp): number {\n  const regexSource = regex.source;\n  let count = 0;\n  let inCharacterClass = false;\n\n  for (let i = 0; i < regexSource.length; i++) {\n    const currentChar = regexSource[i];\n    const prevChar = i > 0 ? regexSource[i - 1] : null;\n\n    if (currentChar === '[' && prevChar !== '\\\\') {\n      inCharacterClass = true;\n    } else if (currentChar === ']' && prevChar !== '\\\\') {\n      inCharacterClass = false;\n    } else if (currentChar === '(' && prevChar !== '\\\\' && !inCharacterClass) {\n      if (regexSource[i + 1] !== '?' || regexSource[i + 2] === ':') {\n        count++;\n      }\n    }\n  }\n\n  return count;\n}\n\nexport const extractRegexNode = nodeDefinition(ExtractRegexNodeImpl, 'Extract Regex');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { type NodeBodySpec } from '../NodeBodySpec.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport type { InternalProcessContext } from '../ProcessContext.js';\nimport type { Inputs, Outputs } from '../GraphProcessor.js';\n\nexport type CodeNode = ChartNode<'code', CodeNodeData>;\n\nconst maskInput = (name: string) => name.trim().replace(/[^a-zA-Z0-9_]/g, '_');\nconst asValidNames = (names: string[]): string[] => Array(...new Set(names.map(maskInput))).filter(Boolean);\n\nexport type CodeNodeData = {\n  code: string;\n  inputNames: string | string[];\n  outputNames: string | string[];\n  allowFetch?: boolean;\n  allowRequire?: boolean;\n  allowRivet?: boolean;\n  allowProcess?: boolean;\n  allowConsole?: boolean;\n};\n\nexport class CodeNodeImpl extends NodeImpl<CodeNode> {\n  static create(): CodeNode {\n    const chartNode: CodeNode = {\n      type: 'code',\n      title: 'Code',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n      },\n      data: {\n        code: dedent`\n          // This is a code node, you can write and JS in here and it will be executed.\n          // Inputs are accessible via an object \\`inputs\\` and data is typed (i.e. inputs.foo.type, inputs.foo.value)\n          // Return an object with named outputs that match the output names specified in the node's config.\n          // Output values must by typed as well (e.g. { bar: { type: 'string', value: 'bar' } }\n          return {\n            output1: {\n              type: inputs.input1.type,\n              value: inputs.input1.value\n            }\n          };\n        `,\n        inputNames: 'input1',\n        outputNames: 'output1',\n        allowFetch: false,\n        allowRequire: false,\n        allowRivet: false,\n        allowProcess: false,\n        allowConsole: false,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputNames = this.data.inputNames\n      ? Array.isArray(this.data.inputNames)\n        ? this.data.inputNames\n        : [this.data.inputNames]\n      : [];\n\n    return asValidNames(inputNames).map((inputName) => {\n      return {\n        type: 'any',\n        id: inputName.trim() as PortId,\n        title: inputName.trim(),\n        dataType: 'string',\n        required: false,\n      };\n    });\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    const outputNames = this.data.outputNames\n      ? Array.isArray(this.data.outputNames)\n        ? this.data.outputNames\n        : [this.data.outputNames]\n      : [];\n\n    return asValidNames(outputNames).map((outputName) => {\n      return {\n        id: outputName.trim() as PortId,\n        title: outputName.trim(),\n        dataType: 'any',\n      };\n    });\n  }\n\n  getEditors(): EditorDefinition<CodeNode>[] {\n    return [\n      {\n        type: 'custom',\n        customEditorId: 'CodeNodeAIAssist',\n        label: 'AI Assist',\n      },\n      {\n        type: 'code',\n        label: 'Code',\n        dataKey: 'code',\n        language: 'javascript',\n      },\n      {\n        type: 'stringList',\n        label: 'Inputs',\n        dataKey: 'inputNames',\n      },\n      {\n        type: 'stringList',\n        label: 'Outputs',\n        dataKey: 'outputNames',\n      },\n      {\n        type: 'toggle',\n        label: 'Allow using `fetch`',\n        dataKey: 'allowFetch',\n      },\n      {\n        type: 'toggle',\n        label: 'Allow using `require`',\n        dataKey: 'allowRequire',\n        helperMessage: 'This is only available when using the Node executor.',\n      },\n      {\n        type: 'toggle',\n        label: 'Allow using `Rivet`',\n        dataKey: 'allowRivet',\n      },\n      {\n        type: 'toggle',\n        label: 'Allow using `process`',\n        dataKey: 'allowProcess',\n        helperMessage: 'This is only available when using the Node executor.',\n      },\n      {\n        type: 'toggle',\n        label: 'Allow using `console`',\n        dataKey: 'allowConsole',\n      },\n    ];\n  }\n\n  getBody(): string | NodeBodySpec | undefined {\n    const trimmed = this.data.code\n      .split('\\n')\n      .slice(0, 15)\n      .map((line) => (line.length > 50 ? line.slice(0, 50) + '...' : line))\n      .join('\\n')\n      .trim();\n\n    return {\n      type: 'colorized',\n      text: trimmed,\n      language: 'javascript',\n      fontSize: 12,\n      fontFamily: 'monospace',\n    };\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Executes a piece of JavaScript code. See the Rivet Documentation for more information on how to write code for the Code Node.\n      `,\n      infoBoxTitle: 'Code Node',\n      contextMenuTitle: 'Code',\n      group: ['Advanced'],\n    };\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const outputs = await context.codeRunner.runCode(\n      this.data.code,\n      inputs,\n      {\n        includeFetch: this.data.allowFetch ?? false,\n        includeRequire: this.data.allowRequire ?? false,\n        includeRivet: this.data.allowRivet ?? false,\n        includeProcess: this.data.allowProcess ?? false,\n        includeConsole: this.data.allowConsole ?? false,\n      },\n      context.graphInputNodeValues,\n      context.contextValues\n    );\n\n    if (outputs == null || typeof outputs !== 'object' || ('then' in outputs && typeof outputs.then === 'function')) {\n      throw new Error('Code node must return an object with output values.');\n    }\n\n    const missingOutputs = this.getOutputDefinitions().filter((output) => !(output.id in outputs));\n    if (missingOutputs.length > 0) {\n      throw new Error(\n        `Code node must return an object with output values for all outputs. To not run an output, return { \"type\": \"control-flow-excluded\", \"value\": undefiend }. To return undefined, return { \"type\": \"any\", \"value\": undefined }. Missing: ${missingOutputs\n          .map((output) => output.id)\n          .join(', ')}`,\n      );\n    }\n\n    return outputs;\n  }\n}\n\nexport const codeNode = nodeDefinition(CodeNodeImpl, 'Code');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type DataValue } from '../DataValue.js';\nimport { type EditorDefinition, type Inputs, type NodeBody, type Outputs } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { coerceType } from '../../utils/coerceType.js';\n\nexport type MatchNode = ChartNode<'match', MatchNodeData>;\n\nexport type MatchNodeData = {\n  cases: string[];\n\n  /** If true, only the first matching branch will be ran. */\n  exclusive?: boolean;\n};\n\nexport class MatchNodeImpl extends NodeImpl<MatchNode> {\n  static create(): MatchNode {\n    const chartNode: MatchNode = {\n      type: 'match',\n      title: 'Match',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 250,\n      },\n      data: {\n        cases: ['YES', 'NO'],\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [\n      {\n        id: 'input' as PortId,\n        title: 'Test',\n        dataType: 'string',\n        required: true,\n        description: 'The value that will be tested against each of the cases.',\n      },\n      {\n        id: 'value' as PortId,\n        title: 'Value',\n        dataType: 'any',\n        description:\n          'The value passed through to the output port that matches. If unconnected, the test value will be passed through.',\n      },\n    ];\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    const outputs: NodeOutputDefinition[] = [];\n\n    for (let i = 0; i < this.data.cases.length; i++) {\n      outputs.push({\n        id: `case${i + 1}` as PortId,\n        title: this.data.cases[i]?.trim() ? this.data.cases[i]! : `Case ${i + 1}`,\n        dataType: 'string',\n        description: `The 'value' (or 'test' if value is unconnected) passed through if the test value matches this regex: /${this\n          .data.cases[i]!}/`,\n      });\n    }\n\n    outputs.push({\n      id: 'unmatched' as PortId,\n      title: 'Unmatched',\n      dataType: 'string',\n      description: 'The value (or test if value is unconnected) passed through if no regexes match.',\n    });\n\n    return outputs;\n  }\n\n  getBody(): NodeBody {\n    return dedent`\n      ${this.data.exclusive ? 'First Matching Case' : 'All Matching Cases'}\n      ${this.data.cases.length} Cases\n    `;\n  }\n\n  getEditors(): EditorDefinition<MatchNode>[] {\n    return [\n      {\n        type: 'toggle',\n        dataKey: 'exclusive',\n        label: 'Exclusive',\n        helperMessage: 'If enabled, only the first matching branch will be ran.',\n      },\n      {\n        type: 'stringList',\n        dataKey: 'cases',\n        label: 'Cases',\n        placeholder: 'Case (regular expression)',\n        helperMessage: '(Regular expressions)',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Any number of regular expressions can be configured, each corresponding to an output of the node. The output port of the first matching regex will be ran, and all other output ports will not be ran.\n      `,\n      infoBoxTitle: 'Match Node',\n      contextMenuTitle: 'Match',\n      group: ['Logic'],\n    };\n  }\n\n  async process(inputs: Inputs): Promise<Outputs> {\n    const inputString = coerceType(inputs['input' as PortId], 'string');\n    const value = inputs['value' as PortId];\n\n    const outputType = value === undefined ? 'string' : value.type;\n    const outputValue = value === undefined ? inputString : value.value;\n\n    const cases = this.data.cases;\n    let matched = false;\n    const output: Outputs = {};\n\n    for (let i = 0; i < cases.length; i++) {\n      const regExp = new RegExp(cases[i]!);\n      const match = regExp.test(inputString);\n\n      const canMatch = !this.data.exclusive || !matched;\n      if (match && canMatch) {\n        matched = true;\n        output[`case${i + 1}` as PortId] = {\n          type: outputType,\n          value: outputValue,\n        } as DataValue;\n      } else {\n        output[`case${i + 1}` as PortId] = {\n          type: 'control-flow-excluded',\n          value: undefined,\n        };\n      }\n    }\n\n    if (!matched) {\n      output['unmatched' as PortId] = {\n        type: outputType,\n        value: outputValue,\n      } as DataValue;\n    } else {\n      output['unmatched' as PortId] = {\n        type: 'control-flow-excluded',\n        value: undefined,\n      };\n    }\n\n    return output;\n  }\n}\n\nexport const matchNode = nodeDefinition(MatchNodeImpl, 'Match');\n", "import { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport {\n  type ControlFlowExcludedDataValue,\n  type ScalarDataValue,\n  type ArrayDataValue,\n  type DataValue,\n} from '../DataValue.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport type { Inputs, Outputs } from '../GraphProcessor.js';\nimport { dedent } from 'ts-dedent';\nimport type { EditorDefinition } from '../EditorDefinition.js';\nimport { coerceType } from '../../utils/coerceType.js';\n\nexport type IfNode = ChartNode<'if', IfNodeData>;\n\nexport type IfNodeData = {\n  unconnectedControlFlowExcluded?: boolean;\n};\n\nexport class IfNodeImpl extends NodeImpl<IfNode> {\n  static create = (): IfNode => {\n    const chartNode: IfNode = {\n      type: 'if',\n      title: 'If',\n      id: nanoid() as NodeId,\n      data: {\n        // Legacy behavior is false\n        unconnectedControlFlowExcluded: true,\n      },\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 125,\n      },\n    };\n    return chartNode;\n  };\n  getInputDefinitions(): NodeInputDefinition[] {\n    return [\n      {\n        id: 'if' as PortId,\n        title: 'If',\n        dataType: 'any',\n        description:\n          'If this is truthy, the value will be passed through the True port. Otherwise, it will be passed through the False port. An unconnected port is considered false.',\n      },\n      {\n        id: 'value' as PortId,\n        title: 'Value',\n        dataType: 'any',\n        description: 'The value to pass through the True or False port. If unconnected, it will be undefined.',\n      },\n    ];\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'output' as PortId,\n        title: 'True',\n        dataType: 'any',\n        description: 'The `value` passed through if the condition is truthy.',\n      },\n      {\n        id: 'falseOutput' as PortId,\n        title: 'False',\n        dataType: 'any',\n        description: 'The `value` passed through if the condition is falsy.',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Takes in a condition and a value. If the condition is truthy, the value is passed through the True port, and the False port is not ran.\n        If the condition is falsy, the value is passed through the False port, and the True port is not ran.\n      `,\n      infoBoxTitle: 'If Node',\n      contextMenuTitle: 'If',\n      group: ['Logic'],\n    };\n  }\n\n  getEditors(): EditorDefinition<IfNode>[] {\n    return [\n      {\n        type: 'toggle',\n        label: \"Don't run unconnected value\",\n        dataKey: 'unconnectedControlFlowExcluded',\n      },\n    ];\n  }\n\n  async process(inputData: Inputs): Promise<Outputs> {\n    const unconnectedValue: DataValue = this.data.unconnectedControlFlowExcluded\n      ? { type: 'control-flow-excluded', value: undefined }\n      : { type: 'any', value: undefined };\n\n    const ifValue = inputData['if' as PortId];\n    const value = inputData['value' as PortId] ?? unconnectedValue;\n\n    const isFalse = {\n      output: {\n        type: 'control-flow-excluded',\n        value: undefined,\n      } as ControlFlowExcludedDataValue,\n      falseOutput: value,\n    };\n\n    if (!ifValue) {\n      return isFalse;\n    }\n\n    if (ifValue.type === 'control-flow-excluded') {\n      return isFalse;\n    }\n\n    if (ifValue.type === 'string' && !ifValue.value) {\n      return isFalse;\n    }\n\n    if (ifValue.type === 'boolean' && !ifValue.value) {\n      return isFalse;\n    }\n\n    if (ifValue.type === 'chat-message') {\n      const asString = coerceType(ifValue, 'string');\n\n      if (!asString) {\n        return isFalse;\n      }\n    }\n\n    if (ifValue.type === 'object' || ifValue.type === 'any') {\n      if (!ifValue.value) {\n        return isFalse;\n      }\n    }\n\n    if (ifValue.type.endsWith('[]')) {\n      const value = ifValue as ArrayDataValue<ScalarDataValue>;\n\n      if (!value.value || value.value.length === 0) {\n        return isFalse;\n      }\n    }\n\n    return {\n      ['output' as PortId]: value,\n      ['falseOutput' as PortId]: {\n        type: 'control-flow-excluded',\n        value: undefined,\n      } as ControlFlowExcludedDataValue,\n    };\n  }\n}\n\nexport const ifNode = nodeDefinition(IfNodeImpl, 'If');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type PortId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type NodeBodySpec } from '../../index.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { dedent } from 'ts-dedent';\nimport { createTreeFromPaths } from '../../utils/paths.js';\nimport { getInputOrData } from '../../utils/inputs.js';\n\nexport type ReadDirectoryNode = ChartNode<'readDirectory', ReadDirectoryNodeData>;\n\ntype ReadDirectoryNodeData = {\n  path: string;\n  usePathInput: boolean;\n\n  recursive: boolean;\n  useRecursiveInput: boolean;\n\n  includeDirectories: boolean;\n  useIncludeDirectoriesInput: boolean;\n\n  filterGlobs: string[];\n  useFilterGlobsInput: boolean;\n\n  relative: boolean;\n  useRelativeInput: boolean;\n\n  ignores?: string[];\n  useIgnoresInput: boolean;\n};\n\nexport class ReadDirectoryNodeImpl extends NodeImpl<ReadDirectoryNode> {\n  static create(): ReadDirectoryNode {\n    return {\n      id: nanoid() as NodeId,\n      type: 'readDirectory',\n      title: 'Read Directory',\n      visualData: { x: 0, y: 0 },\n      data: {\n        path: 'examples',\n        recursive: false,\n        usePathInput: false,\n        useRecursiveInput: false,\n        includeDirectories: false,\n        useIncludeDirectoriesInput: false,\n        filterGlobs: [],\n        useFilterGlobsInput: false,\n        relative: false,\n        useRelativeInput: false,\n        ignores: [],\n        useIgnoresInput: false,\n      },\n    };\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputDefinitions: NodeInputDefinition[] = [];\n\n    if (this.chartNode.data.usePathInput) {\n      inputDefinitions.push({\n        id: 'path' as PortId,\n        title: 'Path',\n        dataType: 'string',\n        required: true,\n        coerced: false,\n      });\n    }\n\n    if (this.chartNode.data.useRecursiveInput) {\n      inputDefinitions.push({\n        id: 'recursive' as PortId,\n        title: 'Recursive',\n        dataType: 'boolean',\n        required: true,\n        coerced: false,\n      });\n    }\n\n    if (this.chartNode.data.useIncludeDirectoriesInput) {\n      inputDefinitions.push({\n        id: 'includeDirectories' as PortId,\n        title: 'Include Directories',\n        dataType: 'boolean',\n        required: true,\n        coerced: false,\n      });\n    }\n\n    if (this.chartNode.data.useFilterGlobsInput) {\n      inputDefinitions.push({\n        id: 'filterGlobs' as PortId,\n        title: 'Filter Globs',\n        dataType: 'string[]',\n        required: true,\n        coerced: false,\n      });\n    }\n\n    if (this.chartNode.data.useRelativeInput) {\n      inputDefinitions.push({\n        id: 'relative' as PortId,\n        title: 'Relative',\n        dataType: 'boolean',\n        required: true,\n        coerced: false,\n      });\n    }\n\n    return inputDefinitions;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'rootPath' as PortId,\n        title: 'Root Path',\n        dataType: 'string',\n      },\n      {\n        id: 'paths' as PortId,\n        title: 'Paths',\n        dataType: 'string[]',\n      },\n      {\n        id: 'tree' as PortId,\n        title: 'Tree',\n        dataType: 'object',\n      },\n    ];\n  }\n\n  getBody(): string | NodeBodySpec | undefined {\n    return dedent`\n      Path: ${this.data.usePathInput ? '(Input)' : this.data.path}\n      Recursive: ${this.data.useRecursiveInput ? '(Input)' : this.data.recursive}\n      Include Directories: ${this.data.useIncludeDirectoriesInput ? '(Input)' : this.data.includeDirectories}\n      Relative: ${this.data.useRelativeInput ? '(Input)' : this.data.relative}\n      Filters: ${\n        this.data.useFilterGlobsInput\n          ? '(Input)'\n          : this.data.filterGlobs.length > 0\n            ? this.data.filterGlobs.join(', ')\n            : 'None'\n      }\n    `;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Reads the contents of the specified directory and outputs:\n        1. An array of filenames\n        2. The root path of the search\n        3. A tree structure representing the directory hierarchy\n      `,\n      infoBoxTitle: 'Read Directory Node',\n      contextMenuTitle: 'Read Directory',\n      group: ['Input/Output'],\n    };\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const { nativeApi } = context;\n\n    if (nativeApi == null) {\n      throw new Error('This node requires a native API to run.');\n    }\n\n    const path = getInputOrData(this.data, inputs, 'path');\n    const recursive = getInputOrData(this.data, inputs, 'recursive', 'boolean');\n    const includeDirectories = getInputOrData(this.data, inputs, 'includeDirectories', 'boolean');\n    const filterGlobs = getInputOrData(this.data, inputs, 'filterGlobs', 'string[]');\n    const relative = getInputOrData(this.data, inputs, 'relative', 'boolean');\n    const ignores = getInputOrData(this.data, inputs, 'ignores', 'string[]');\n\n    try {\n      const files = await nativeApi.readdir(path, undefined, {\n        recursive,\n        includeDirectories,\n        filterGlobs,\n        relative,\n        ignores,\n      });\n\n      const tree = createTreeFromPaths(files, path);\n\n      return {\n        ['paths' as PortId]: { type: 'string[]', value: files },\n        ['rootPath' as PortId]: { type: 'string', value: path },\n        ['tree' as PortId]: { type: 'object', value: tree as unknown as Record<string, unknown> },\n      };\n    } catch (err) {\n      return {\n        ['paths' as PortId]: { type: 'string[]', value: ['(no such path)'] },\n        ['rootPath' as PortId]: { type: 'string', value: path },\n        ['tree' as PortId]: {\n          type: 'object',\n          value: {\n            path,\n            name: path.split('/').pop() || path,\n            isDirectory: true,\n            children: [],\n          },\n        },\n      };\n    }\n  }\n}\n\nexport const readDirectoryNode = nodeDefinition(ReadDirectoryNodeImpl, 'Read Directory');\n", "interface TreeNode {\n  path: string;\n  name: string;\n  isDirectory: boolean;\n  children: TreeNode[];\n}\n\nexport function createTreeFromPaths(paths: string[], rootPath: string): TreeNode {\n  // Helper to get all parent paths of a given path\n  const getParentPaths = (path: string): string[] => {\n    const parts = path.split('/').filter((p) => p);\n    return parts.slice(0, -1).map((_, index) => parts.slice(0, index + 1).join('/'));\n  };\n\n  // First, create a unique set of all directories\n  const directories = new Set<string>();\n  paths.forEach((path) => {\n    // Add all parent directories of this path\n    const cleanPath = path.replace(/^\\/+|\\/+$/g, '');\n    getParentPaths(cleanPath).forEach((dir) => directories.add(dir));\n\n    // If the path itself ends with /, it's a directory\n    if (path.endsWith('/')) {\n      directories.add(cleanPath);\n    }\n  });\n\n  // Create the root node\n  const root: TreeNode = {\n    path: rootPath,\n    name: rootPath || 'root',\n    isDirectory: true,\n    children: [],\n  };\n\n  // Create a map for quick node lookups - use full paths as keys\n  const nodeMap = new Map<string, TreeNode>();\n  nodeMap.set(rootPath, root);\n\n  // Helper to get or create a node for a path\n  const getOrCreateNode = (fullPath: string): TreeNode => {\n    const cleanPath = fullPath.replace(/^\\/+|\\/+$/g, '');\n\n    if (nodeMap.has(cleanPath)) {\n      return nodeMap.get(cleanPath)!;\n    }\n\n    const parts = cleanPath.split('/').filter((p) => p);\n    const name = parts[parts.length - 1] || cleanPath;\n    const node: TreeNode = {\n      path: name, // Just use the name as the path\n      name,\n      isDirectory: directories.has(cleanPath),\n      children: [],\n    };\n    nodeMap.set(cleanPath, node); // Still use full path for lookup\n\n    // Important: Create parent-child relationship immediately\n    if (parts.length > 1) {\n      const parentPath = parts.slice(0, -1).join('/');\n      const parent = getOrCreateNode(parentPath);\n      if (!parent.children.some((child) => child.name === name)) {\n        parent.children.push(node);\n      }\n    } else if (cleanPath && rootPath !== cleanPath) {\n      // Top-level node\n      if (!root.children.some((child) => child.name === name)) {\n        root.children.push(node);\n      }\n    }\n\n    return node;\n  };\n\n  // Process all paths to build the tree\n  paths\n    .filter((path) => path.trim())\n    .forEach((path) => {\n      const cleanPath = path.replace(/^\\/+|\\/+$/g, '');\n      if (cleanPath) {\n        getOrCreateNode(cleanPath);\n      }\n    });\n\n  // Sort children of all nodes\n  const sortNode = (node: TreeNode) => {\n    node.children.sort((a, b) => {\n      if (a.isDirectory !== b.isDirectory) {\n        return a.isDirectory ? -1 : 1;\n      }\n      return a.name.localeCompare(b.name);\n    });\n    node.children.forEach(sortNode);\n  };\n  sortNode(root);\n\n  return root;\n}\n", "import {\n  type ChartNode,\n  type NodeId,\n  type PortId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { type DataValue } from '../DataValue.js';\nimport { NodeImpl, type NodeBody, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { getInputOrData } from '../../utils/index.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { dedent } from 'ts-dedent';\nimport type { EditorDefinition } from '../EditorDefinition.js';\n\nexport type ReadFileNode = ChartNode<'readFile', ReadFileNodeData>;\n\ntype ReadFileNodeData = {\n  path: string;\n  usePathInput: boolean;\n\n  asBinary?: boolean;\n\n  errorOnMissingFile?: boolean;\n};\n\nexport class ReadFileNodeImpl extends NodeImpl<ReadFileNode> {\n  static create(): ReadFileNode {\n    return {\n      id: nanoid() as NodeId,\n      type: 'readFile',\n      title: 'Read File',\n      visualData: { x: 0, y: 0, width: 250 },\n      data: {\n        path: '',\n        asBinary: false,\n        usePathInput: true,\n        errorOnMissingFile: false,\n      },\n    };\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputDefinitions: NodeInputDefinition[] = [];\n\n    if (this.chartNode.data.usePathInput) {\n      inputDefinitions.push({\n        id: 'path' as PortId,\n        title: 'Path',\n        dataType: 'string',\n        coerced: false,\n      });\n    }\n\n    return inputDefinitions;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'content' as PortId,\n        title: 'Content',\n        dataType: this.data.asBinary ? 'binary' : 'string',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Reads the contents of the specified file and outputs it as a string.\n      `,\n      infoBoxTitle: 'Read File Node',\n      contextMenuTitle: 'Read File',\n      group: ['Input/Output'],\n    };\n  }\n\n  getEditors(): EditorDefinition<ReadFileNode>[] {\n    return [\n      {\n        type: 'filePathBrowser',\n        label: 'Path',\n        dataKey: 'path',\n        useInputToggleDataKey: 'usePathInput',\n      },\n      {\n        type: 'toggle',\n        label: 'Error on Missing File',\n        dataKey: 'errorOnMissingFile',\n      },\n      {\n        type: 'toggle',\n        label: 'Read as Binary',\n        dataKey: 'asBinary',\n      },\n    ];\n  }\n\n  getBody(): NodeBody {\n    return dedent`\n      ${this.data.asBinary ? 'Read as Binary' : 'Read as Text'}\n      ${this.data.usePathInput ? '' : `Path: ${this.data.path}`}\n    `;\n  }\n\n  async process(\n    inputData: Record<PortId, DataValue>,\n    context: InternalProcessContext,\n  ): Promise<Record<PortId, DataValue>> {\n    const { nativeApi } = context;\n\n    if (nativeApi == null) {\n      throw new Error('This node requires a native API to run.');\n    }\n\n    const path = getInputOrData(this.chartNode.data, inputData, 'path');\n\n    try {\n      if (this.data.asBinary) {\n        const content = await nativeApi.readBinaryFile(path);\n        const buffer = await content.arrayBuffer();\n        return {\n          ['content' as PortId]: { type: 'binary', value: new Uint8Array(buffer) },\n        };\n      } else {\n        const content = await nativeApi.readTextFile(path, undefined);\n        return {\n          ['content' as PortId]: { type: 'string', value: content },\n        };\n      }\n    } catch (err) {\n      if (this.chartNode.data.errorOnMissingFile) {\n        throw err;\n      } else {\n        return {\n          ['content' as PortId]: { type: 'control-flow-excluded', value: undefined },\n        };\n      }\n    }\n  }\n}\n\nexport const readFileNode = nodeDefinition(ReadFileNodeImpl, 'Read File');\n", "import { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport { type ArrayDataValue, type DataValue, type ScalarDataValue } from '../DataValue.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { dedent } from 'ts-dedent';\nimport type { EditorDefinition } from '../EditorDefinition.js';\nimport { coerceType } from '../../utils/coerceType.js';\n\nexport type IfElseNode = ChartNode<'ifElse', IfElseNodeData>;\n\nexport type IfElseNodeData = {\n  /** If true, unconnected input ports are control-flow-excluded. */\n  unconnectedControlFlowExcluded?: boolean;\n};\n\nexport class IfElseNodeImpl extends NodeImpl<IfElseNode> {\n  static create = (): IfElseNode => {\n    const chartNode: IfElseNode = {\n      type: 'ifElse',\n      title: 'If/Else',\n      id: nanoid() as NodeId,\n      data: {\n        // Legacy behavior is false\n        unconnectedControlFlowExcluded: true,\n      },\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 175,\n      },\n    };\n    return chartNode;\n  };\n  getInputDefinitions(): NodeInputDefinition[] {\n    return [\n      {\n        id: 'if' as PortId,\n        title: 'If',\n        dataType: 'any',\n        description:\n          'If this is truthy, the `true` value will be passed through the output port. Otherwise, the `false` value will be passed through the output port. An unconnected port is considered false. A `Not Ran` value is considered false.',\n      },\n      {\n        id: 'true' as PortId,\n        title: 'True',\n        dataType: 'any',\n        description: 'The value to pass through the output port if the condition is truthy. ',\n      },\n      {\n        id: 'false' as PortId,\n        title: 'False',\n        dataType: 'any',\n        description: 'The value to pass through the output port if the condition is not truthy.',\n      },\n    ];\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'output' as PortId,\n        title: 'Output',\n        dataType: 'any',\n        description: 'The `true` or `false` value, depending on the `if` condition.',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Takes in three inputs: a condition, a true value, and a false value. If the condition is truthy, the true value is passed through the output port. If the condition is not truthy, the false value is passed through the output port.\n\n        This node can \"consume\" a \\`Not Ran\\` to continue a graph from that point.\n      `,\n      infoBoxTitle: 'If/Else Node',\n      contextMenuTitle: 'If/Else',\n      group: ['Logic'],\n    };\n  }\n\n  getEditors(): EditorDefinition<IfElseNode>[] {\n    return [\n      {\n        type: 'toggle',\n        label: \"Don't run unconnected ports\",\n        dataKey: 'unconnectedControlFlowExcluded',\n      },\n    ];\n  }\n\n  async process(inputData: Record<PortId, DataValue>): Promise<Record<PortId, DataValue>> {\n    const unconnectedValue: DataValue = this.data.unconnectedControlFlowExcluded\n      ? { type: 'control-flow-excluded', value: undefined }\n      : {\n          type: 'any',\n          value: undefined,\n        };\n\n    const ifValue = inputData['if' as PortId];\n    const trueValue = inputData['true' as PortId] ?? unconnectedValue;\n    const falseValue = inputData['false' as PortId] ?? unconnectedValue;\n\n    if (!(trueValue || falseValue)) {\n      return {\n        ['output' as PortId]: {\n          type: 'control-flow-excluded',\n          value: undefined,\n        },\n      };\n    }\n\n    if (ifValue?.type === 'control-flow-excluded') {\n      return {\n        ['output' as PortId]: falseValue,\n      };\n    }\n\n    if (ifValue?.value == null) {\n      return {\n        ['output' as PortId]: falseValue,\n      };\n    }\n\n    if (ifValue?.type && ifValue.type === 'boolean') {\n      return {\n        ['output' as PortId]: ifValue.value ? trueValue : falseValue,\n      };\n    }\n\n    if (ifValue?.type === 'string') {\n      return {\n        ['output' as PortId]: ifValue.value.length > 0 ? trueValue : falseValue,\n      };\n    }\n\n    if (ifValue?.type === 'chat-message') {\n      const asString = coerceType(ifValue, 'string');\n\n      return {\n        ['output' as PortId]: asString ? trueValue : falseValue,\n      };\n    }\n\n    if (ifValue?.type.endsWith('[]')) {\n      return {\n        ['output' as PortId]: (ifValue as ArrayDataValue<ScalarDataValue>).value.length > 0 ? trueValue : falseValue,\n      };\n    }\n\n    if (ifValue?.type === 'any' || ifValue?.type === 'object') {\n      return {\n        ['output' as PortId]: !!ifValue.value ? trueValue : falseValue,\n      };\n    }\n\n    return {\n      ['output' as PortId]: falseValue,\n    };\n  }\n}\n\nexport const ifElseNode = nodeDefinition(IfElseNodeImpl, 'If/Else');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../../model/NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../../model/NodeImpl.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { coerceType } from '../../utils/coerceType.js';\nimport { dedent } from 'ts-dedent';\nimport { openAiModelOptions } from '../../utils/openai.js';\nimport { type EditorDefinition, type Inputs, type InternalProcessContext, type Outputs } from '../../index.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport type { Tokenizer, TokenizerCallInfo } from '../../integrations/Tokenizer.js';\n\nexport type ChunkNodeData = {\n  numTokensPerChunk: number;\n\n  model: string;\n  useModelInput: boolean;\n\n  overlap: number;\n};\n\nexport type ChunkNode = ChartNode<'chunk', ChunkNodeData>;\n\nexport class ChunkNodeImpl extends NodeImpl<ChunkNode> {\n  static create() {\n    const chartNode: ChunkNode = {\n      type: 'chunk',\n      title: 'Chunk',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 200,\n      },\n      data: {\n        model: 'gpt-4o',\n        useModelInput: false,\n        numTokensPerChunk: 1024,\n        overlap: 0,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [\n      {\n        id: 'input' as PortId,\n        title: 'Input',\n        dataType: 'string',\n      },\n    ];\n\n    if (this.data.useModelInput) {\n      inputs.push({\n        id: 'model' as PortId,\n        title: 'Model',\n        dataType: 'string',\n      });\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'chunks' as PortId,\n        title: 'Chunks',\n        dataType: 'string[]',\n      },\n      {\n        id: 'first' as PortId,\n        title: 'First',\n        dataType: 'string',\n      },\n      {\n        id: 'last' as PortId,\n        title: 'Last',\n        dataType: 'string',\n      },\n      {\n        id: 'indexes' as PortId,\n        title: 'Indexes',\n        dataType: 'number[]',\n      },\n      {\n        id: 'count' as PortId,\n        title: 'Count',\n        dataType: 'number',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<ChunkNode>[] {\n    return [\n      {\n        type: 'dropdown',\n        label: 'Model',\n        dataKey: 'model',\n        options: openAiModelOptions,\n        useInputToggleDataKey: 'useModelInput',\n      },\n      {\n        type: 'number',\n        label: 'Number of tokens per chunk',\n        dataKey: 'numTokensPerChunk',\n        min: 1,\n        max: 32768,\n        step: 1,\n      },\n      {\n        type: 'number',\n        label: 'Overlap (in %)',\n        dataKey: 'overlap',\n        min: 0,\n        max: 100,\n        step: 1,\n      },\n    ];\n  }\n\n  getBody(): string | undefined {\n    return dedent`\n      Model: ${this.data.model}\n      Token Count: ${this.data.numTokensPerChunk.toLocaleString()}\n      ${this.data.overlap ? `Overlap: ${this.data.overlap}%` : ''}\n    `;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n          Splits the input text into an array of chunks based on an approximate GPT token count per chunk.\n\n          The \"overlap\" setting allows you to partially overlap the chunks for redundancy.\n\n          Can also be used for string length truncation by only using the \\`First\\` or \\`Last\\` outputs of the node.\n        `,\n      infoBoxTitle: 'Chunk Node',\n      contextMenuTitle: 'Chunk',\n      group: ['Text'],\n    };\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const input = coerceType(inputs['input' as PortId], 'string');\n\n    const overlapPercent = this.chartNode.data.overlap / 100;\n\n    const chunked = await chunkStringByTokenCount(\n      context.tokenizer,\n      {\n        node: this.chartNode,\n        endpoint: undefined,\n        model: this.data.model,\n      },\n      input,\n      this.chartNode.data.numTokensPerChunk,\n      overlapPercent,\n    );\n\n    return {\n      ['chunks' as PortId]: {\n        type: 'string[]',\n        value: chunked,\n      },\n      ['first' as PortId]: {\n        type: 'string',\n        value: chunked[0]!,\n      },\n      ['last' as PortId]: {\n        type: 'string',\n        value: chunked.at(-1)!,\n      },\n      ['indexes' as PortId]: {\n        type: 'number[]',\n        value: chunked.map((_, i) => i + 1),\n      },\n      ['count' as PortId]: {\n        type: 'number',\n        value: chunked.length,\n      },\n    };\n  }\n}\n\nexport const chunkNode = nodeDefinition(ChunkNodeImpl, 'Chunk');\n\nexport async function chunkStringByTokenCount(\n  tokenizer: Tokenizer,\n  tokenizerInfo: TokenizerCallInfo,\n  input: string,\n  targetTokenCount: number,\n  overlapPercent: number,\n) {\n  overlapPercent = Number.isNaN(overlapPercent) ? 0 : Math.max(0, Math.min(1, overlapPercent));\n\n  const chunks: string[] = [];\n  const guess = Math.floor(\n    targetTokenCount * (input.length / (await tokenizer.getTokenCountForString(input, tokenizerInfo))),\n  );\n  let remaining = input;\n\n  while (remaining.length > 0) {\n    chunks.push(remaining.slice(0, guess));\n    remaining = remaining.slice(guess - Math.floor(guess * overlapPercent));\n  }\n\n  return chunks;\n}\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type DataType, type DataValue, getDefaultValue, isArrayDataType } from '../DataValue.js';\nimport { type Inputs } from '../GraphProcessor.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { type DynamicEditorEditor, type EditorDefinition, type NodeBodySpec } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { coerceTypeOptional, inferType } from '../../utils/coerceType.js';\n\nexport type GraphInputNode = ChartNode<'graphInput', GraphInputNodeData>;\n\nexport type GraphInputNodeData = {\n  id: string;\n  dataType: DataType;\n  defaultValue?: unknown;\n  useDefaultValueInput?: boolean;\n  editor?: DynamicEditorEditor;\n};\n\nexport class GraphInputNodeImpl extends NodeImpl<GraphInputNode> {\n  static create(): GraphInputNode {\n    const chartNode: GraphInputNode = {\n      type: 'graphInput',\n      title: 'Graph Input',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 300,\n      },\n      data: {\n        id: 'input',\n        dataType: 'string',\n        defaultValue: undefined,\n        useDefaultValueInput: false,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    if (this.data.useDefaultValueInput) {\n      return [\n        {\n          id: 'default' as PortId,\n          title: 'Default Value',\n          dataType: this.chartNode.data.dataType as DataType,\n        },\n      ];\n    }\n\n    return [];\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'data' as PortId,\n        title: this.data.id,\n        dataType: this.chartNode.data.dataType as DataType,\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<GraphInputNode>[] {\n    return [\n      {\n        type: 'string',\n        label: 'ID',\n        dataKey: 'id',\n      },\n      {\n        type: 'dataTypeSelector',\n        label: 'Data Type',\n        dataKey: 'dataType',\n      },\n      {\n        type: 'anyData',\n        label: 'Default Value',\n        dataKey: 'defaultValue',\n        useInputToggleDataKey: 'useDefaultValueInput',\n      },\n      {\n        type: 'dropdown',\n        label: 'Editor',\n        dataKey: 'editor',\n        defaultValue: 'auto',\n        options: [\n          { label: 'None', value: 'none' },\n          { label: 'Auto', value: 'auto' },\n          { label: 'String', value: 'string' },\n          { label: 'Number', value: 'number' },\n          { label: 'Code', value: 'code' },\n          { label: 'Data Type', value: 'dataTypeSelector' },\n          { label: 'String List', value: 'stringList' },\n          { label: 'Key Value Pairs', value: 'keyValuePair' },\n          { label: 'Toggle', value: 'toggle' },\n        ] satisfies { label: string; value: DynamicEditorEditor }[],\n        helperMessage: 'The editor to use when editing this value in the UI. Make sure this matches the data type.',\n      },\n    ];\n  }\n\n  getBody(): string | NodeBodySpec | undefined {\n    return dedent`\n      ${this.data.id}\n      Type: ${this.data.dataType}\n      ${this.data.defaultValue == null ? '' : `Default: ${this.data.defaultValue}`}\n    `;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Defines an input for the graph which can be passed in when the graph is called, or defines one of the input ports when the graph is a subgraph.\n      `,\n      infoBoxTitle: 'Graph Input Node',\n      contextMenuTitle: 'Graph Input',\n      group: ['Input/Output'],\n    };\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Record<string, DataValue>> {\n    let inputValue =\n      context.graphInputs[this.data.id] == null\n        ? undefined\n        : coerceTypeOptional(context.graphInputs[this.data.id], this.data.dataType);\n\n    if (inputValue == null && this.data.useDefaultValueInput) {\n      inputValue = coerceTypeOptional(inputs['default' as PortId], this.data.dataType);\n    }\n\n    if (inputValue == null) {\n      inputValue =\n        coerceTypeOptional(inferType(this.data.defaultValue), this.data.dataType) ||\n        getDefaultValue(this.data.dataType);\n    }\n\n    // Resolve undefined for array inputs to empty array\n    if (inputValue == null && isArrayDataType(this.data.dataType)) {\n      inputValue = { type: this.data.dataType, value: [] } as DataValue;\n    }\n\n    const value = {\n      type: this.data.dataType,\n      value: inputValue,\n    } as DataValue;\n\n    // Store the resolved value in the context for access by other nodes\n    context.graphInputNodeValues[this.data.id] = value;\n\n    return { ['data' as PortId]: value };\n  }\n}\n\nexport const graphInputNode = nodeDefinition(GraphInputNodeImpl, 'Graph Input');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeOutputDefinition,\n  type PortId,\n  type NodeInputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type DataType } from '../DataValue.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { type NodeBodySpec } from '../NodeBodySpec.js';\n\nexport type GraphOutputNode = ChartNode<'graphOutput', GraphOutputNodeData>;\n\nexport type GraphOutputNodeData = {\n  id: string;\n  dataType: DataType;\n};\n\nexport class GraphOutputNodeImpl extends NodeImpl<GraphOutputNode> {\n  static create(): GraphOutputNode {\n    const chartNode: GraphOutputNode = {\n      type: 'graphOutput',\n      title: 'Graph Output',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 300,\n      },\n      data: {\n        id: 'output',\n        dataType: 'string',\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    return [\n      {\n        id: 'value' as PortId,\n        title: this.data.id,\n        dataType: this.chartNode.data.dataType as DataType,\n      },\n    ];\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'valueOutput' as PortId,\n        title: this.data.id,\n        dataType: this.chartNode.data.dataType as DataType,\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<GraphOutputNode>[] {\n    return [\n      {\n        type: 'string',\n        label: 'ID',\n        dataKey: 'id',\n      },\n      {\n        type: 'dataTypeSelector',\n        label: 'Data Type',\n        dataKey: 'dataType',\n      },\n    ];\n  }\n\n  getBody(): string | NodeBodySpec | undefined {\n    return dedent`\n      ${this.data.id}\n      Type: ${this.data.dataType}\n    `;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Each instance of this node represents an individual output of the graph. The value passed into this node becomes part of the overall output of the graph.\n      `,\n      infoBoxTitle: 'Graph Output Node',\n      contextMenuTitle: 'Graph Output',\n      group: ['Input/Output'],\n    };\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const value = inputs['value' as PortId] ?? { type: 'any', value: undefined };\n\n    const isExcluded = value.type === 'control-flow-excluded';\n\n    if (isExcluded && context.graphOutputs[this.data.id] == null) {\n      context.graphOutputs[this.data.id] = {\n        type: 'control-flow-excluded',\n        value: undefined,\n      };\n    } else if (\n      (context.graphOutputs[this.data.id] == null ||\n        context.graphOutputs[this.data.id]?.type === 'control-flow-excluded') &&\n      inputs['value' as PortId]\n    ) {\n      context.graphOutputs[this.data.id] = value;\n    }\n\n    if (isExcluded) {\n      return {\n        ['valueOutput' as PortId]: {\n          type: 'control-flow-excluded',\n          value: undefined,\n        },\n      };\n    }\n\n    return {\n      ['valueOutput' as PortId]: context.graphOutputs[this.data.id],\n    };\n  }\n}\n\nexport const graphOutputNode = nodeDefinition(GraphOutputNodeImpl, 'Graph Output');\n", "import {\n  type ChartNode,\n  type NodeConnection,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type GraphId } from '../NodeGraph.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { type Project } from '../Project.js';\nimport { type GraphInputNode } from './GraphInputNode.js';\nimport { type GraphOutputNode } from './GraphOutputNode.js';\nimport { type DataValue } from '../DataValue.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { type EditorDefinition } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { getError } from '../../utils/errors.js';\n\nimport type { RivetUIContext } from '../RivetUIContext.js';\n\nexport type SubGraphNode = ChartNode & {\n  type: 'subGraph';\n  data: {\n    graphId: GraphId;\n    useErrorOutput?: boolean;\n    useAsGraphPartialOutput?: boolean;\n\n    /** Data for each of the inputs of the subgraph */\n    inputData?: Record<string, DataValue>;\n  };\n};\n\nexport class SubGraphNodeImpl extends NodeImpl<SubGraphNode> {\n  static create(): SubGraphNode {\n    const chartNode: SubGraphNode = {\n      type: 'subGraph',\n      title: 'Subgraph',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 300,\n      },\n      data: {\n        graphId: '' as GraphId,\n        useErrorOutput: false,\n        useAsGraphPartialOutput: false,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(\n    _connections: NodeConnection[],\n    _nodes: Record<NodeId, ChartNode>,\n    project: Project,\n  ): NodeInputDefinition[] {\n    const graph = project.graphs[this.data.graphId];\n    if (!graph) {\n      return [];\n    }\n\n    const inputNodes = graph.nodes.filter((node) => node.type === 'graphInput') as GraphInputNode[];\n    const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();\n\n    return inputIds.map(\n      (id): NodeInputDefinition => ({\n        id: id as PortId,\n        title: id,\n        dataType: inputNodes.find((node) => node.data.id === id)!.data.dataType,\n      }),\n    );\n  }\n\n  getGraphOutputs(project: Project): NodeOutputDefinition[] {\n    const graph = project.graphs[this.data.graphId];\n    if (!graph) {\n      return [];\n    }\n\n    const outputNodes = graph.nodes.filter((node) => node.type === 'graphOutput') as GraphOutputNode[];\n    const outputIds = [...new Set(outputNodes.map((node) => node.data.id))].sort();\n\n    const outputs = outputIds.map(\n      (id): NodeOutputDefinition => ({\n        id: id as PortId,\n        title: id,\n        dataType: outputNodes.find((node) => node.data.id === id)!.data.dataType,\n      }),\n    );\n\n    return outputs;\n  }\n\n  getOutputDefinitions(\n    _connections: NodeConnection[],\n    _nodes: Record<NodeId, ChartNode>,\n    project: Project,\n  ): NodeOutputDefinition[] {\n    const outputs: NodeOutputDefinition[] = [];\n\n    outputs.push(...this.getGraphOutputs(project));\n\n    if (this.data.useErrorOutput) {\n      outputs.push({\n        id: 'error' as PortId,\n        title: 'Error',\n        dataType: 'string',\n      });\n    }\n\n    return outputs;\n  }\n\n  getEditors(context: RivetUIContext): EditorDefinition<SubGraphNode>[] {\n    const definitions: EditorDefinition<SubGraphNode>[] = [\n      {\n        type: 'graphSelector',\n        label: 'Graph',\n        dataKey: 'graphId',\n      },\n      {\n        type: 'toggle',\n        label: 'Use Error Output',\n        dataKey: 'useErrorOutput',\n      },\n    ];\n\n    if (this.data.graphId) {\n      const graph = context.project.graphs[this.data.graphId];\n      if (graph) {\n        const inputNodes = graph.nodes.filter((node) => node.type === 'graphInput') as GraphInputNode[];\n        const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();\n\n        for (const inputId of inputIds) {\n          const inputNode = inputNodes.find((node) => node.data.id === inputId)!;\n          definitions.push({\n            type: 'dynamic',\n            dataKey: 'inputData',\n            dynamicDataKey: inputNode.data.id,\n            dataType: inputNode.data.dataType,\n            label: inputNode.data.id,\n            editor: inputNode.data.editor ?? 'auto',\n          });\n        }\n      }\n    }\n\n    return definitions;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Executes another graph. Inputs and outputs are defined by Graph Input and Graph Output nodes within the subgraph.\n      `,\n      infoBoxTitle: 'Subgraph Node',\n      contextMenuTitle: 'Subgraph',\n      group: ['Advanced'],\n    };\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const { project } = context;\n\n    if (!project) {\n      throw new Error('SubGraphNode requires a project to be set in the context.');\n    }\n\n    const graph = project.graphs[this.data.graphId];\n    if (!graph) {\n      throw new Error(`SubGraphNode requires a graph with id ${this.data.graphId} to be present in the project.`);\n    }\n\n    const inputNodes = graph.nodes.filter((node) => node.type === 'graphInput') as GraphInputNode[];\n    const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();\n\n    const inputData = inputIds.reduce((obj, id): Inputs => {\n      if (inputs[id as PortId] != null) {\n        return {\n          ...obj,\n          [id]: inputs[id as PortId],\n        };\n      }\n\n      if (this.data.inputData?.[id] != null) {\n        return {\n          ...obj,\n          [id]: this.data.inputData[id],\n        };\n      }\n\n      return obj;\n    }, {} as Inputs);\n\n    const subGraphProcessor = context.createSubProcessor(this.data.graphId, { signal: context.signal });\n\n    try {\n      const startTime = Date.now();\n\n      const outputs = await subGraphProcessor.processGraph(\n        context,\n        inputData as Record<string, DataValue>,\n        context.contextValues,\n      );\n\n      const duration = Date.now() - startTime;\n\n      if (this.data.useErrorOutput) {\n        outputs['error' as PortId] = {\n          type: 'control-flow-excluded',\n          value: undefined,\n        };\n      }\n\n      if (outputs['duration' as PortId] == null) {\n        outputs['duration' as PortId] = {\n          type: 'number',\n          value: duration,\n        };\n      }\n\n      return outputs;\n    } catch (err) {\n      if (!this.data.useErrorOutput) {\n        throw err;\n      }\n\n      const outputs: Outputs = this.getGraphOutputs(context.project).reduce(\n        (obj, output): Outputs => ({\n          ...obj,\n          [output.id as PortId]: {\n            type: 'control-flow-excluded',\n            value: undefined,\n          },\n        }),\n        {} as Outputs,\n      );\n\n      outputs['error' as PortId] = {\n        type: 'string',\n        value: getError(err).message,\n      };\n\n      return outputs;\n    }\n  }\n}\n\nexport const subGraphNode = nodeDefinition(SubGraphNodeImpl, 'Subgraph');\n", "import {\n  type ChartNode,\n  type NodeConnection,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeBody, type NodeUIData } from '../NodeImpl.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { entries } from '../../utils/typeSafety.js';\nimport { flattenDeep } from 'lodash-es';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\n\nexport type ArrayNode = ChartNode<'array', ArrayNodeData>;\n\nexport type ArrayNodeData = {\n  flatten?: boolean;\n  flattenDeep?: boolean;\n};\n\nexport class ArrayNodeImpl extends NodeImpl<ArrayNode> {\n  static create(): ArrayNode {\n    const chartNode: ArrayNode = {\n      type: 'array',\n      title: 'Array',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 200,\n      },\n      data: {\n        flatten: true,\n        flattenDeep: false,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(connections: NodeConnection[]): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [];\n    const inputCount = this.#getInputPortCount(connections);\n\n    for (let i = 1; i <= inputCount; i++) {\n      inputs.push({\n        dataType: 'any',\n        id: `input${i}` as PortId,\n        title: `Input ${i}`,\n        description:\n          'An input to create the array from. If an array, will be flattened if the \"Flatten\" option is enabled.',\n      });\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        dataType: 'any[]',\n        id: 'output' as PortId,\n        title: 'Output',\n        description: 'The array created from the inputs.',\n      },\n      {\n        dataType: 'number[]',\n        id: 'indices' as PortId,\n        title: 'Indices',\n        description:\n          'The indices of the array. I.e. [0, 1, 2, 3, etc]. Useful for zipping with the output array to get the indexes.',\n      },\n      {\n        dataType: 'number',\n        id: 'length' as PortId,\n        title: 'Length',\n        description: 'The length of the output array.',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<ArrayNode>[] {\n    return [\n      { type: 'toggle', label: 'Flatten', dataKey: 'flatten' },\n      {\n        type: 'toggle',\n        label: 'Deep',\n        dataKey: 'flattenDeep',\n      },\n    ];\n  }\n\n  #getInputPortCount(connections: NodeConnection[]): number {\n    const inputNodeId = this.chartNode.id;\n    const inputConnections = connections.filter(\n      (connection) => connection.inputNodeId === inputNodeId && connection.inputId.startsWith('input'),\n    );\n\n    let maxInputNumber = 0;\n    for (const connection of inputConnections) {\n      const inputNumber = parseInt(connection.inputId.replace('input', ''));\n      if (inputNumber > maxInputNumber) {\n        maxInputNumber = inputNumber;\n      }\n    }\n\n    return maxInputNumber + 1;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Creates an array from the input values. By default, flattens any arrays which are inputs into a single array. Can be configured to keep the arrays separate, or deeply flatten arrays.\n\n        Useful for both creating and merging arrays.\n\n        The number of inputs is dynamic based on the number of connections.\n      `,\n      infoBoxTitle: 'Array Node',\n      contextMenuTitle: 'Array',\n      group: ['Lists'],\n    };\n  }\n\n  getBody(): NodeBody {\n    return dedent`\n      ${this.data.flatten ? (this.data.flattenDeep ? 'Flatten (Deep)' : 'Flatten') : 'No Flatten'}\n    `;\n  }\n\n  async process(inputs: Inputs): Promise<Outputs> {\n    const outputArray: any[] = [];\n\n    for (const [key, input] of entries(inputs)) {\n      if (key.startsWith('input')) {\n        if (this.data.flatten) {\n          if (Array.isArray(input?.value)) {\n            for (const value of input?.value ?? []) {\n              if (this.data.flattenDeep) {\n                outputArray.push(...(Array.isArray(value) ? flattenDeep(value) : [value]));\n              } else {\n                outputArray.push(value);\n              }\n            }\n          } else {\n            outputArray.push(input?.value);\n          }\n        } else {\n          outputArray.push(input?.value);\n        }\n      }\n    }\n\n    return {\n      ['output' as PortId]: {\n        type: 'any[]',\n        value: outputArray,\n      },\n      ['indices' as PortId]: {\n        type: 'number[]',\n        value: outputArray.map((_, index) => index),\n      },\n      ['length' as PortId]: {\n        type: 'number',\n        value: outputArray.length,\n      },\n    };\n  }\n}\n\nexport const arrayNode = nodeDefinition(ArrayNodeImpl, 'Array');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type DataValue } from '../DataValue.js';\nimport { expectType } from '../../utils/index.js';\nimport { dedent } from 'ts-dedent';\n\nexport type ExtractJsonNode = ChartNode<'extractJson', ExtractJsonNodeData>;\n\nexport type ExtractJsonNodeData = {};\n\nexport class ExtractJsonNodeImpl extends NodeImpl<ExtractJsonNode> {\n  static create(): ExtractJsonNode {\n    const chartNode: ExtractJsonNode = {\n      type: 'extractJson',\n      title: 'Extract JSON',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 250,\n      },\n      data: {},\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    return [\n      {\n        id: 'input' as PortId,\n        title: 'Input',\n        dataType: 'string',\n        required: true,\n        coerced: false,\n      },\n    ];\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'output' as PortId,\n        title: 'Output',\n        dataType: 'object',\n      },\n      {\n        id: 'noMatch' as PortId,\n        title: 'No Match',\n        dataType: 'string',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Finds and parses the first JSON object in the input text.\n\n        Outputs the parsed object.\n      `,\n      infoBoxTitle: 'Extract JSON Node',\n      contextMenuTitle: 'Extract JSON',\n      group: ['Objects'],\n    };\n  }\n\n  async process(inputs: Record<PortId, DataValue>): Promise<Record<PortId, DataValue>> {\n    const inputString = expectType(inputs['input' as PortId], 'string');\n\n    try {\n      const parsed = JSON.parse(inputString);\n      return {\n        ['output' as PortId]: {\n          type: 'object',\n          value: parsed,\n        },\n        ['noMatch' as PortId]: {\n          type: 'control-flow-excluded',\n          value: undefined,\n        },\n      };\n    } catch (_err: unknown) {\n      // Fall back to more manual parsing\n    }\n\n    // Find the first { or [ and the last } or ], and try parsing everything in between including them.\n\n    const firstBracket = inputString.indexOf('{');\n    const lastBracket = inputString.lastIndexOf('}');\n    const firstSquareBracket = inputString.indexOf('[');\n    const lastSquareBracket = inputString.lastIndexOf(']');\n\n    const firstIndex =\n      firstBracket >= 0 && firstSquareBracket >= 0\n        ? Math.min(firstBracket, firstSquareBracket)\n        : firstBracket >= 0\n          ? firstBracket\n          : firstSquareBracket;\n\n    const lastIndex =\n      lastBracket >= 0 && lastSquareBracket >= 0\n        ? Math.max(lastBracket, lastSquareBracket)\n        : lastBracket >= 0\n          ? lastBracket\n          : lastSquareBracket;\n\n    const substring = inputString.substring(firstIndex, lastIndex + 1);\n\n    let jsonObject: Record<string, unknown> | undefined = undefined;\n    try {\n      jsonObject = JSON.parse(substring);\n    } catch (err) {\n      return {\n        ['noMatch' as PortId]: {\n          type: 'string',\n          value: inputString,\n        },\n        ['output' as PortId]: {\n          type: 'control-flow-excluded',\n          value: undefined,\n        },\n      };\n    }\n\n    return {\n      ['output' as PortId]: {\n        type: 'object',\n        value: jsonObject!,\n      },\n      ['noMatch' as PortId]: {\n        type: 'control-flow-excluded',\n        value: undefined,\n      },\n    };\n  }\n}\n\nexport const extractJsonNode = nodeDefinition(ExtractJsonNodeImpl, 'Extract JSON');\n", "import {\n  type ChartNode,\n  type NodeConnection,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeBody, type NodeUIData } from '../NodeImpl.js';\nimport { type ChatMessage, arrayizeDataValue, unwrapDataValue } from '../DataValue.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { coerceType } from '../../utils/coerceType.js';\nimport { orderBy } from 'lodash-es';\nimport { dedent } from 'ts-dedent';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport type { EditorDefinition } from '../EditorDefinition.js';\nimport type { RivetUIContext } from '../RivetUIContext.js';\nimport type { InternalProcessContext } from '../ProcessContext.js';\nimport { getInputOrData } from '../../utils/inputs.js';\n\nexport type AssemblePromptNode = ChartNode<'assemblePrompt', AssemblePromptNodeData>;\n\nexport type AssemblePromptNodeData = {\n  computeTokenCount?: boolean;\n\n  isLastMessageCacheBreakpoint?: boolean;\n  useIsLastMessageCacheBreakpointInput?: boolean;\n};\n\nexport class AssemblePromptNodeImpl extends NodeImpl<AssemblePromptNode> {\n  static create(): AssemblePromptNode {\n    const chartNode: AssemblePromptNode = {\n      type: 'assemblePrompt',\n      title: 'Assemble Prompt',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 250,\n      },\n      data: {},\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(connections: NodeConnection[]): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [];\n    const messageCount = this.#getMessagePortCount(connections);\n\n    if (this.data.useIsLastMessageCacheBreakpointInput) {\n      inputs.push({\n        dataType: 'boolean',\n        id: 'isLastMessageCacheBreakpoint' as PortId,\n        title: 'Is Last Message Cache Breakpoint',\n        description: 'Whether the last message in the prompt should be a cache breakpoint.',\n      });\n    }\n\n    for (let i = 1; i <= messageCount; i++) {\n      inputs.push({\n        dataType: ['chat-message', 'chat-message[]'] as const,\n        id: `message${i}` as PortId,\n        title: `Message ${i}`,\n        description: 'A message, or messages, to include in the full prompt.',\n      });\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    const outputs: NodeOutputDefinition[] = [\n      {\n        dataType: 'chat-message[]',\n        id: 'prompt' as PortId,\n        title: 'Prompt',\n        description: 'The assembled prompt, a list of chat messages.',\n      },\n    ];\n\n    if (this.data.computeTokenCount) {\n      outputs.push({\n        dataType: 'number',\n        id: 'tokenCount' as PortId,\n        title: 'Token Count',\n        description: 'The number of tokens in the full output prompt.',\n      });\n    }\n\n    return outputs;\n  }\n\n  #getMessagePortCount(connections: NodeConnection[]): number {\n    const inputNodeId = this.chartNode.id;\n    const messageConnections = connections.filter(\n      (connection) => connection.inputNodeId === inputNodeId && connection.inputId.startsWith('message'),\n    );\n\n    let maxMessageNumber = 0;\n    for (const connection of messageConnections) {\n      const messageNumber = parseInt(connection.inputId.replace('message', ''));\n      if (messageNumber > maxMessageNumber) {\n        maxMessageNumber = messageNumber;\n      }\n    }\n\n    return maxMessageNumber + 1;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Assembles an array of chat messages for use with a Chat node. The inputs can be strings or chat messages.\n\n        The number of inputs is dynamic based on the number of connections.\n\n        Strings are converted to User type chat messages.\n      `,\n      infoBoxTitle: 'Assemble Prompt Node',\n      contextMenuTitle: 'Assemble Prompt',\n      group: ['AI'],\n    };\n  }\n\n  getEditors(_context: RivetUIContext): EditorDefinition<AssemblePromptNode>[] {\n    return [\n      {\n        type: 'toggle',\n        label: 'Compute Token Count',\n        dataKey: 'computeTokenCount',\n      },\n      {\n        type: 'toggle',\n        label: 'Is Last Message Cache Breakpoint',\n        dataKey: 'isLastMessageCacheBreakpoint',\n        helperMessage:\n          'For Anthropic, marks the last message as a cache breakpoint - this message and every message before it will be cached using Prompt Caching.',\n      },\n    ];\n  }\n\n  getBody(_context: RivetUIContext): NodeBody | Promise<NodeBody> {\n    return this.data.isLastMessageCacheBreakpoint ? 'Last message is cache breakpoint' : '';\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const output: Outputs = {};\n\n    const isLastMessageCacheBreakpoint = getInputOrData(this.data, inputs, 'isLastMessageCacheBreakpoint', 'boolean');\n\n    const outMessages: ChatMessage[] = [];\n\n    const inputMessages = orderBy(\n      Object.entries(inputs).filter(([key]) => key.startsWith('message')),\n      ([key]) => key,\n      'asc',\n    );\n\n    for (const [, inputMessage] of inputMessages) {\n      if (!inputMessage || inputMessage.type === 'control-flow-excluded' || !inputMessage.value) {\n        continue;\n      }\n\n      const inMessages = arrayizeDataValue(unwrapDataValue(inputMessage));\n      for (const message of inMessages) {\n        if (message.type === 'chat-message') {\n          outMessages.push(message.value);\n        } else {\n          const coerced = coerceType(message, 'chat-message');\n\n          if (coerced) {\n            outMessages.push(coerced);\n          }\n        }\n      }\n    }\n\n    if (isLastMessageCacheBreakpoint && outMessages.length > 1) {\n      outMessages.at(-1)!.isCacheBreakpoint = true;\n    }\n\n    output['prompt' as PortId] = {\n      type: 'chat-message[]',\n      value: outMessages,\n    };\n\n    if (this.data.computeTokenCount) {\n      const tokenCount = await context.tokenizer.getTokenCountForMessages(outMessages, undefined, {\n        node: this.chartNode,\n      });\n      output['tokenCount' as PortId] = {\n        type: 'number',\n        value: tokenCount,\n      };\n    }\n\n    return output;\n  }\n}\n\nexport const assemblePromptNode = nodeDefinition(AssemblePromptNodeImpl, 'Assemble Prompt');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type DataValue } from '../DataValue.js';\nimport yaml from 'yaml';\nimport { expectType } from '../../utils/expectType.js';\nimport { JSONPath } from 'jsonpath-plus';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition, type NodeBodySpec } from '../../index.js';\nimport { coerceType } from '../../utils/coerceType.js';\n\nexport type ExtractYamlNode = ChartNode<'extractYaml', ExtractYamlNodeData>;\n\nexport type ExtractYamlNodeData = {\n  rootPropertyName: string;\n  useRootPropertyNameInput?: boolean;\n  objectPath?: string;\n  useObjectPathInput?: boolean;\n};\n\nexport class ExtractYamlNodeImpl extends NodeImpl<ExtractYamlNode> {\n  static create(): ExtractYamlNode {\n    const chartNode: ExtractYamlNode = {\n      type: 'extractYaml',\n      title: 'Extract YAML',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 250,\n      },\n      data: {\n        rootPropertyName: 'yamlDocument',\n        useRootPropertyNameInput: false,\n        useObjectPathInput: false,\n        objectPath: undefined,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [\n      {\n        id: 'input' as PortId,\n        title: 'Input',\n        dataType: 'string',\n        required: true,\n        coerced: false,\n      },\n    ];\n\n    if (this.data.useRootPropertyNameInput) {\n      inputs.push({\n        id: 'rootPropertyName' as PortId,\n        title: 'Root Property Name',\n        dataType: 'string',\n        required: true,\n      });\n    }\n\n    if (this.data.useObjectPathInput) {\n      inputs.push({\n        id: 'objectPath' as PortId,\n        title: 'Object Path',\n        dataType: 'string',\n        required: true,\n      });\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'output' as PortId,\n        title: 'Output',\n        dataType: 'object',\n      },\n      {\n        id: 'matches' as PortId,\n        title: 'Matches',\n        dataType: 'any[]',\n      },\n      {\n        id: 'noMatch' as PortId,\n        title: 'No Match',\n        dataType: 'string',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<ExtractYamlNode>[] {\n    return [\n      {\n        type: 'string',\n        label: 'Root Property Name',\n        dataKey: 'rootPropertyName',\n        useInputToggleDataKey: 'useRootPropertyNameInput',\n      },\n      {\n        type: 'code',\n        label: 'Object Path',\n        dataKey: 'objectPath',\n        language: 'jsonpath',\n        useInputToggleDataKey: 'useObjectPathInput',\n      },\n    ];\n  }\n\n  getBody(): string | NodeBodySpec | undefined {\n    return dedent`\n      Root: ${this.data.useRootPropertyNameInput ? '(Using Input)' : this.data.rootPropertyName}\n      ${\n        this.data.useObjectPathInput\n          ? 'Path: (Using Input)'\n          : this.data.objectPath\n            ? `Path: ${this.data.objectPath}`\n            : ``\n      }\n    `;\n  }\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Finds and parses a YAML object in the input text with a predefined root property name (configurable).\n\n        Defaults to \\`yamlDocument\\`, which means the input text must have a \\`yamlDocument:\\` root node somewhere in it. All indented text after that is considered part of the YAML.\n\n        Outputs the parsed object.\n      `,\n      infoBoxTitle: 'Extract YAML Node',\n      contextMenuTitle: 'Extract YAML',\n      group: ['Objects'],\n    };\n  }\n\n  async process(inputs: Record<PortId, DataValue>): Promise<Record<PortId, DataValue>> {\n    const inputString = expectType(inputs['input' as PortId], 'string');\n\n    const rootPropertyName = this.data.useRootPropertyNameInput\n      ? coerceType(inputs['rootPropertyName' as PortId], 'string')\n      : this.data.rootPropertyName;\n\n    const objectPath = this.data.useObjectPathInput\n      ? coerceType(inputs['objectPath' as PortId], 'string')\n      : this.data.objectPath;\n\n    const match = new RegExp(`^${rootPropertyName}:`, 'm').exec(inputString);\n    const rootPropertyStart = match?.index ?? -1;\n\n    const nextLines = inputString.slice(rootPropertyStart).split('\\n');\n    const yamlLines = [nextLines.shift()]; // remove the first line, which is the root property name\n\n    while (nextLines[0]?.startsWith(' ') || nextLines[0]?.startsWith('\\t') || nextLines[0] === '') {\n      yamlLines.push(nextLines.shift());\n    }\n\n    const potentialYaml = yamlLines.join('\\n');\n\n    let yamlObject: Record<string, unknown> | undefined = undefined;\n    try {\n      yamlObject = yaml.parse(potentialYaml);\n    } catch (err) {\n      return {\n        ['noMatch' as PortId]: {\n          type: 'string',\n          value: potentialYaml,\n        },\n        ['output' as PortId]: {\n          type: 'control-flow-excluded',\n          value: undefined,\n        },\n      };\n    }\n\n    if (!yamlObject?.hasOwnProperty(rootPropertyName)) {\n      return {\n        ['noMatch' as PortId]: {\n          type: 'string',\n          value: potentialYaml,\n        },\n        ['output' as PortId]: {\n          type: 'control-flow-excluded',\n          value: undefined,\n        },\n      };\n    }\n\n    let matches: unknown[] = [];\n\n    if (objectPath) {\n      try {\n        const extractedValue = JSONPath({ json: yamlObject, path: objectPath.trim() });\n        matches = extractedValue;\n        yamlObject = extractedValue.length > 0 ? extractedValue[0] : undefined;\n      } catch (err) {\n        return {\n          ['noMatch' as PortId]: {\n            type: 'string',\n            value: potentialYaml,\n          },\n          ['output' as PortId]: {\n            type: 'control-flow-excluded',\n            value: undefined,\n          },\n          ['matches' as PortId]: {\n            type: 'control-flow-excluded',\n            value: undefined,\n          },\n        };\n      }\n    }\n\n    return {\n      ['output' as PortId]:\n        yamlObject === undefined\n          ? {\n              type: 'control-flow-excluded',\n              value: undefined,\n            }\n          : this.data.objectPath\n            ? {\n                type: 'any',\n                value: yamlObject,\n              }\n            : {\n                type: 'object',\n                value: yamlObject,\n              },\n      ['noMatch' as PortId]: {\n        type: 'control-flow-excluded',\n        value: undefined,\n      },\n      ['matches' as PortId]: {\n        type: 'any[]',\n        value: matches,\n      },\n    };\n  }\n}\n\nexport const extractYamlNode = nodeDefinition(ExtractYamlNodeImpl, 'Extract YAML');\n", "import {\n  type ChartNode,\n  type NodeConnection,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { coerceType } from '../../utils/coerceType.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../../index.js';\nimport { entries } from '../../utils/typeSafety.js';\n\nexport type LoopControllerNode = ChartNode<'loopController', LoopControllerNodeData>;\n\nexport type LoopControllerNodeData = {\n  maxIterations?: number;\n  atMaxIterationsAction?: 'break' | 'error';\n};\n\nexport class LoopControllerNodeImpl extends NodeImpl<LoopControllerNode> {\n  static create(): LoopControllerNode {\n    const chartNode: LoopControllerNode = {\n      type: 'loopController',\n      title: 'Loop Controller',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 250,\n      },\n      data: {\n        maxIterations: 100,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(connections: NodeConnection[], nodes: Record<NodeId, ChartNode>): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [];\n    const messageCount = this.#getInputPortCount(connections);\n\n    inputs.push({\n      dataType: 'any',\n      id: 'continue' as PortId,\n      title: 'Continue',\n    });\n\n    let i = 1;\n    for (; i <= messageCount + 1; i++) {\n      const input: NodeInputDefinition = {\n        dataType: 'any',\n        id: `input${i}` as PortId,\n        title: `Input ${i}`,\n      };\n\n      const inputConnection = connections.find(\n        (connection) => connection.inputId === input.id && connection.inputNodeId === this.id,\n      );\n      if (inputConnection && nodes[inputConnection.outputNodeId]) {\n        input.title = nodes[inputConnection.outputNodeId]!.title;\n      }\n\n      const inputDefault: NodeInputDefinition = {\n        dataType: 'any',\n        id: `input${i}Default` as PortId,\n        title: `Input ${i} Default`,\n      };\n      const inputDefaultConnection = connections.find(\n        (connection) => connection.inputId === inputDefault.id && connection.inputNodeId === this.id,\n      );\n      if (inputDefaultConnection && nodes[inputDefaultConnection.outputNodeId]) {\n        inputDefault.title = `${nodes[inputDefaultConnection.outputNodeId]!.title} (Default)`;\n      }\n\n      inputs.push(input);\n      inputs.push(inputDefault);\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(connections: NodeConnection[], nodes: Record<NodeId, ChartNode>): NodeOutputDefinition[] {\n    const messageCount = this.#getInputPortCount(connections);\n\n    const outputs: NodeOutputDefinition[] = [];\n\n    outputs.push({\n      dataType: 'any',\n      id: 'break' as PortId,\n      title: 'Break',\n    });\n\n    outputs.push({\n      dataType: 'number',\n      id: 'iteration' as PortId,\n      title: 'Iteration',\n    });\n\n    for (let i = 1; i <= messageCount; i++) {\n      const output: NodeOutputDefinition = {\n        dataType: 'any',\n        id: `output${i}` as PortId,\n        title: `Output ${i}`,\n      };\n\n      const inputConnection = connections.find(\n        (connection) => connection.inputId === `input${i}` && connection.inputNodeId === this.id,\n      );\n      if (inputConnection && nodes[inputConnection.outputNodeId]) {\n        output.title = `${nodes[inputConnection.outputNodeId]!.title}?`;\n      }\n\n      outputs.push(output);\n    }\n\n    return outputs;\n  }\n\n  getEditors(): EditorDefinition<LoopControllerNode>[] {\n    return [\n      {\n        type: 'number',\n        label: 'Max Iterations',\n        dataKey: 'maxIterations',\n      },\n      {\n        type: 'dropdown',\n        options: [\n          {\n            label: 'Break',\n            value: 'break',\n          },\n          {\n            label: 'Error',\n            value: 'error',\n          },\n        ],\n        label: 'At Max Iterations',\n        dataKey: 'atMaxIterationsAction',\n        defaultValue: 'error',\n        helperMessage: 'What should happen when the max iterations is reached?',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Defines the entry point for a loop. Values from inside the loop should be passed back through the \"Input\" ports, and their corresponding \"Default\" values can be specified on the input ports as well.\n\n        If the \"continue\" input is falsey, then the \"break\" output will run.\n      `,\n      infoBoxTitle: 'Loop Controller Node',\n      contextMenuTitle: 'Loop Controller',\n      group: ['Logic'],\n    };\n  }\n\n  #getInputPortCount(connections: NodeConnection[]): number {\n    const inputNodeId = this.chartNode.id;\n    const messageConnections = connections.filter(\n      (connection) => connection.inputNodeId === inputNodeId && connection.inputId.startsWith('input'),\n    );\n\n    let maxMessageNumber = 0;\n    for (const connection of messageConnections) {\n      const messageNumber = parseInt(connection.inputId.replace('input', ''));\n      if (messageNumber > maxMessageNumber) {\n        maxMessageNumber = messageNumber;\n      }\n    }\n\n    return maxMessageNumber;\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const output: Outputs = {};\n\n    let inputCount = 0;\n    while (inputs[`input${inputCount + 1}` as PortId] || inputs[`input${inputCount + 1}Default` as PortId]) {\n      inputCount++;\n    }\n\n    const defaultInputs = entries(inputs).filter(([key]) => key.endsWith('Default'));\n\n    // If any of the default inputs are control-flow-excluded, then exclude all outputs.\n    // Technically, it should be \"any node outside of the cycle\" but this should be good enough?\n    if (defaultInputs.some(([, value]) => value?.type === 'control-flow-excluded')) {\n      for (let i = 0; i <= inputCount; i++) {\n        output[`output${i}` as PortId] = { type: 'control-flow-excluded', value: undefined };\n      }\n      output['break' as PortId] = { type: 'control-flow-excluded', value: undefined };\n\n      return output;\n    }\n\n    const iterationCount = context.attachedData.loopInfo?.iterationCount ?? 0;\n\n    output['iteration' as PortId] = { type: 'number', value: iterationCount + 1 };\n\n    if (iterationCount >= (this.data.maxIterations ?? 100) && this.data.atMaxIterationsAction !== 'break') {\n      throw new Error(`Loop controller exceeded max iterations of ${this.data.maxIterations ?? 100}`);\n    }\n\n    // If the continue port is not connected (so undefined), or if it's undefined before it's\n    // inside the loop itself (connection has not ran yet), then we should continue by default.\n    let continueValue = false;\n\n    if (inputs['continue' as PortId] === undefined) {\n      continueValue = true;\n    } else {\n      const continueDataValue = inputs['continue' as PortId]!;\n      if (continueDataValue.type === 'control-flow-excluded') {\n        continueValue = false;\n      } else {\n        continueValue = coerceType(continueDataValue, 'boolean');\n      }\n    }\n\n    if (iterationCount >= (this.data.maxIterations ?? 100) && this.data.atMaxIterationsAction === 'break') {\n      continueValue = false;\n    }\n\n    if (continueValue) {\n      output['break' as PortId] = { type: 'control-flow-excluded', value: 'loop-not-broken' };\n    } else {\n      const inputValues: unknown[] = [];\n      for (let i = 1; i <= inputCount; i++) {\n        inputValues.push(inputs[`input${i}` as PortId]?.value);\n      }\n\n      // Break gets an array of all the input values\n      output['break' as PortId] = { type: 'any[]', value: inputValues };\n    }\n\n    for (let i = 1; i <= inputCount; i++) {\n      if (continueValue) {\n        const inputId = `input${i}` as PortId;\n        const outputId = `output${i}` as PortId;\n\n        if (inputs[inputId]) {\n          output[outputId] = inputs[inputId]!;\n        } else {\n          output[outputId] = inputs[`${inputId}Default` as PortId]!;\n        }\n      } else {\n        output[`output${i}` as PortId] = { type: 'control-flow-excluded', value: undefined };\n      }\n    }\n\n    return output;\n  }\n}\n\nexport const loopControllerNode = nodeDefinition(LoopControllerNodeImpl, 'Loop Controller');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type PortId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n} from '../../model/NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../../model/NodeImpl.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport {\n  type EditorDefinition,\n  type Inputs,\n  type InternalProcessContext,\n  type NodeBodySpec,\n  type Outputs,\n} from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport type { TokenizerCallInfo } from '../../integrations/Tokenizer.js';\nimport { coerceType } from '../../utils/coerceType.js';\nimport { getInputOrData } from '../../utils/index.js';\n\nexport type TrimChatMessagesNodeData = {\n  maxTokenCount: number;\n  useMaxTokenCountInput?: boolean;\n\n  removeFromBeginning: boolean;\n  useRemoveFromBeginningInput?: boolean;\n};\n\nexport type TrimChatMessagesNode = ChartNode<'trimChatMessages', TrimChatMessagesNodeData>;\n\nexport class TrimChatMessagesNodeImpl extends NodeImpl<TrimChatMessagesNode> {\n  static create() {\n    const chartNode: TrimChatMessagesNode = {\n      type: 'trimChatMessages',\n      title: 'Trim Chat Messages',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 200,\n      },\n      data: {\n        maxTokenCount: 4096,\n        removeFromBeginning: true,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [\n      {\n        id: 'input' as PortId,\n        title: 'Input',\n        dataType: 'chat-message[]',\n      },\n    ];\n\n    if (this.data.useMaxTokenCountInput) {\n      inputs.push({\n        id: 'maxTokenCount' as PortId,\n        title: 'Max Token Count',\n        dataType: 'number',\n      });\n    }\n\n    if (this.data.useRemoveFromBeginningInput) {\n      inputs.push({\n        id: 'removeFromBeginning' as PortId,\n        title: 'Remove From Beginning',\n        dataType: 'boolean',\n      });\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'trimmed' as PortId,\n        title: 'Trimmed',\n        dataType: 'chat-message[]',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<TrimChatMessagesNode>[] {\n    return [\n      {\n        type: 'number',\n        label: 'Max Token Count',\n        dataKey: 'maxTokenCount',\n        useInputToggleDataKey: 'useMaxTokenCountInput',\n      },\n      {\n        type: 'toggle',\n        label: 'Remove From Beginning',\n        dataKey: 'removeFromBeginning',\n        useInputToggleDataKey: 'useRemoveFromBeginningInput',\n      },\n    ];\n  }\n\n  getBody(): string | NodeBodySpec | undefined {\n    return dedent`\n      Max Token Count: ${this.data.useMaxTokenCountInput ? '(From Input)' : this.data.maxTokenCount}\n      Remove From Beginning: ${\n        this.data.useRemoveFromBeginningInput ? '(From Input)' : this.data.removeFromBeginning ? 'Yes' : 'No'\n      }\n    `;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Takes an array of chat messages, and slices messages from the beginning or the end of the list until the total length of the messages is under the configured token length.\n\n        Useful for setting up infinite message chains that stay under the LLM context limit.\n      `,\n      infoBoxTitle: 'Trim Chat Messages Node',\n      contextMenuTitle: 'Trim Chat Messages',\n      group: ['AI'],\n    };\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext<TrimChatMessagesNode>): Promise<Outputs> {\n    const input = coerceType(inputs['input' as PortId], 'chat-message[]');\n\n    const maxTokenCount = getInputOrData(this.data, inputs, 'maxTokenCount', 'number');\n    const removeFromBeginning = getInputOrData(this.data, inputs, 'removeFromBeginning', 'boolean');\n\n    const trimmedMessages = [...input];\n\n    const tokenizerInfo: TokenizerCallInfo = {\n      node: this.chartNode,\n    };\n\n    let tokenCount = await context.tokenizer.getTokenCountForMessages(trimmedMessages, undefined, tokenizerInfo);\n\n    while (tokenCount > maxTokenCount) {\n      if (removeFromBeginning) {\n        trimmedMessages.shift();\n      } else {\n        trimmedMessages.pop();\n      }\n      tokenCount = await context.tokenizer.getTokenCountForMessages(trimmedMessages, undefined, tokenizerInfo);\n    }\n\n    return {\n      ['trimmed' as PortId]: {\n        type: 'chat-message[]',\n        value: trimmedMessages,\n      },\n    };\n  }\n}\n\nexport const trimChatMessagesNode = nodeDefinition(TrimChatMessagesNodeImpl, 'Trim Chat Messages');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type AnyDataValue, type ArrayDataValue } from '../DataValue.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { coerceType } from '../../utils/coerceType.js';\nimport { getError } from '../../utils/errors.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { omit } from 'lodash-es';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { type NodeBodySpec } from '../NodeBodySpec.js';\n\nexport type ExternalCallNode = ChartNode<'externalCall', ExternalCallNodeData>;\n\nexport type ExternalCallNodeData = {\n  functionName: string;\n  useFunctionNameInput: boolean;\n  useErrorOutput: boolean;\n};\n\nexport class ExternalCallNodeImpl extends NodeImpl<ExternalCallNode> {\n  static create(): ExternalCallNode {\n    return {\n      id: nanoid() as NodeId,\n      type: 'externalCall',\n      title: 'External Call',\n      visualData: { x: 0, y: 0, width: 150 },\n      data: {\n        functionName: '',\n        useFunctionNameInput: false,\n        useErrorOutput: false,\n      },\n    };\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputDefinitions: NodeInputDefinition[] = [];\n\n    if (this.chartNode.data.useFunctionNameInput) {\n      inputDefinitions.push({\n        id: 'functionName' as PortId,\n        title: 'Function Name',\n        dataType: 'string',\n      });\n    }\n\n    inputDefinitions.push({\n      id: 'arguments' as PortId,\n      title: 'Arguments',\n      dataType: 'any[]',\n    });\n\n    return inputDefinitions;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    const outputs: NodeOutputDefinition[] = [\n      {\n        id: 'result' as PortId,\n        title: 'Result',\n        dataType: 'any',\n      },\n    ];\n\n    if (this.chartNode.data.useErrorOutput) {\n      outputs.push({\n        id: 'error' as PortId,\n        title: 'Error',\n        dataType: 'string',\n      });\n    }\n\n    return outputs;\n  }\n\n  getEditors(): EditorDefinition<ExternalCallNode>[] {\n    return [\n      {\n        type: 'string',\n        label: 'Function Name',\n        dataKey: 'functionName',\n        useInputToggleDataKey: 'useFunctionNameInput',\n      },\n      {\n        type: 'toggle',\n        label: 'Use Error Output',\n        dataKey: 'useErrorOutput',\n      },\n    ];\n  }\n\n  getBody(): string | NodeBodySpec | undefined {\n    return this.data.useFunctionNameInput ? '(Using Input)' : this.data.functionName;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Provides a way to call into the host project from inside a Rivet graph when Rivet graphs are integrated into another project.\n      `,\n      infoBoxTitle: 'External Call Node',\n      contextMenuTitle: 'External Call',\n      group: ['Advanced'],\n    };\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const functionName = this.chartNode.data.useFunctionNameInput\n      ? coerceType(inputs['functionName' as PortId], 'string')\n      : this.chartNode.data.functionName;\n\n    const args = inputs['arguments' as PortId];\n    let arrayArgs: ArrayDataValue<AnyDataValue> = {\n      type: 'any[]',\n      value: [],\n    };\n\n    if (args) {\n      if (args.type.endsWith('[]') === false) {\n        arrayArgs = {\n          type: 'any[]',\n          value: [args.value],\n        };\n      } else {\n        arrayArgs = args as ArrayDataValue<AnyDataValue>;\n      }\n    }\n\n    const fn = context.externalFunctions[functionName];\n    const externalContext = omit(context, ['setGlobal']);\n\n    if (!fn) {\n      if (this.data.useErrorOutput) {\n        return {\n          ['result' as PortId]: {\n            type: 'control-flow-excluded',\n            value: undefined,\n          },\n          ['error' as PortId]: {\n            type: 'string',\n            value: `Function ${functionName} not was not defined using setExternalCall`,\n          },\n        };\n      } else {\n        throw new Error(`Function ${functionName} not was not defined using setExternalCall`);\n      }\n    }\n\n    if (this.data.useErrorOutput) {\n      try {\n        const result = await fn(externalContext, ...arrayArgs.value);\n        return {\n          ['result' as PortId]: result,\n          ['cost' as PortId]: {\n            type: 'number',\n            value: result.cost ?? 0,\n          },\n          ['error' as PortId]: {\n            type: 'control-flow-excluded',\n            value: undefined,\n          },\n        };\n      } catch (error) {\n        return {\n          ['result' as PortId]: {\n            type: 'control-flow-excluded',\n            value: undefined,\n          },\n          ['error' as PortId]: {\n            type: 'string',\n            value: getError(error).message,\n          },\n        };\n      }\n    }\n    const result = await fn(externalContext, ...arrayArgs.value);\n    return {\n      ['result' as PortId]: result,\n    };\n  }\n}\n\nexport const externalCallNode = nodeDefinition(ExternalCallNodeImpl, 'External Call');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type DataValue } from '../DataValue.js';\nimport { JSONPath } from 'jsonpath-plus';\nimport { expectType } from '../../utils/expectType.js';\nimport { type EditorDefinition, type NodeBodySpec } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { coerceTypeOptional } from '../../utils/coerceType.js';\n\nexport type ExtractObjectPathNode = ChartNode<'extractObjectPath', ExtractObjectPathNodeData>;\n\nexport type ExtractObjectPathNodeData = {\n  path: string;\n  usePathInput: boolean;\n};\n\nexport class ExtractObjectPathNodeImpl extends NodeImpl<ExtractObjectPathNode> {\n  static create(): ExtractObjectPathNode {\n    const chartNode: ExtractObjectPathNode = {\n      type: 'extractObjectPath',\n      title: 'Extract Object Path',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 250,\n      },\n      data: {\n        path: '$',\n        usePathInput: false,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputDefinitions: NodeInputDefinition[] = [\n      {\n        id: 'object' as PortId,\n        title: 'Object',\n        dataType: 'object',\n        required: true,\n      },\n    ];\n\n    if (this.chartNode.data.usePathInput) {\n      inputDefinitions.push({\n        id: 'path' as PortId,\n        title: 'Path',\n        dataType: 'string',\n        required: true,\n        coerced: false,\n      });\n    }\n\n    return inputDefinitions;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'match' as PortId,\n        title: 'Match',\n        dataType: 'any',\n      },\n      {\n        id: 'all_matches' as PortId,\n        title: 'All Matches',\n        dataType: 'any[]',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<ExtractObjectPathNode>[] {\n    return [\n      {\n        type: 'code',\n        label: 'Path',\n        dataKey: 'path',\n        language: 'jsonpath',\n        useInputToggleDataKey: 'usePathInput',\n      },\n    ];\n  }\n\n  getBody(): string | NodeBodySpec | undefined {\n    return this.data.usePathInput ? '(Using Input)' : this.data.path;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Extracts the value at the specified path from the input value. The path uses JSONPath notation to navigate through the value.\n      `,\n      infoBoxTitle: 'Extract Object Path Node',\n      contextMenuTitle: 'Extract Object Path',\n      group: ['Objects'],\n    };\n  }\n\n  async process(inputs: Record<PortId, DataValue>): Promise<Record<PortId, DataValue>> {\n    const inputObject = coerceTypeOptional(inputs['object' as PortId], 'object');\n    const inputPath = this.chartNode.data.usePathInput\n      ? expectType(inputs['path' as PortId], 'string')\n      : this.chartNode.data.path;\n\n    if (!inputPath) {\n      throw new Error('Path input is not provided');\n    }\n\n    let matches: unknown[];\n    try {\n      // Wrap doesn't seem to wrap when the input is undefined or null...\n      const match = JSONPath<unknown>({ json: inputObject ?? null, path: inputPath.trim(), wrap: true });\n      matches = match == null ? [] : (match as unknown[]);\n    } catch (err) {\n      matches = [];\n    }\n\n    if (matches.length === 0) {\n      return {\n        ['match' as PortId]: {\n          type: 'control-flow-excluded',\n          value: undefined,\n        },\n        ['all_matches' as PortId]: {\n          type: 'any[]',\n          value: [],\n        },\n      };\n    }\n\n    return {\n      ['match' as PortId]: {\n        type: 'any',\n        value: matches[0],\n      },\n      ['all_matches' as PortId]: {\n        type: 'any[]',\n        value: matches,\n      },\n    };\n  }\n}\n\nexport const extractObjectPathNode = nodeDefinition(ExtractObjectPathNodeImpl, 'Extract Object Path');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type DataValue } from '../DataValue.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { type Inputs } from '../GraphProcessor.js';\nimport { coerceType } from '../../utils/coerceType.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { type NodeBodySpec } from '../NodeBodySpec.js';\n\nexport type RaiseEventNode = ChartNode<'raiseEvent', RaiseEventNodeData>;\n\nexport type RaiseEventNodeData = {\n  eventName: string;\n  useEventNameInput: boolean;\n};\n\nexport class RaiseEventNodeImpl extends NodeImpl<RaiseEventNode> {\n  static create(): RaiseEventNode {\n    return {\n      id: nanoid() as NodeId,\n      type: 'raiseEvent',\n      title: 'Raise Event',\n      visualData: { x: 0, y: 0, width: 150 },\n      data: {\n        eventName: 'toast',\n        useEventNameInput: false,\n      },\n    };\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputDefinitions: NodeInputDefinition[] = [];\n\n    if (this.chartNode.data.useEventNameInput) {\n      inputDefinitions.push({\n        id: 'eventName' as PortId,\n        title: 'Event Name',\n        dataType: 'string',\n      });\n    }\n\n    inputDefinitions.push({\n      id: 'data' as PortId,\n      title: 'Data',\n      dataType: 'any',\n    });\n\n    return inputDefinitions;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'result' as PortId,\n        title: 'Result',\n        dataType: 'any',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<RaiseEventNode>[] {\n    return [\n      {\n        type: 'string',\n        label: 'Event Name',\n        dataKey: 'eventName',\n        useInputToggleDataKey: 'useEventNameInput',\n      },\n    ];\n  }\n\n  getBody(): string | NodeBodySpec | undefined {\n    return this.data.useEventNameInput ? '(Using Input)' : this.data.eventName;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Raises an event that the host project or a 'Wait For Event' node can listen for.\n      `,\n      infoBoxTitle: 'Raise Event Node',\n      contextMenuTitle: 'Raise Event',\n      group: ['Advanced'],\n    };\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Record<string, DataValue>> {\n    const eventName = this.chartNode.data.useEventNameInput\n      ? coerceType(inputs['eventName' as PortId], 'string')\n      : this.chartNode.data.eventName;\n\n    const eventData = inputs['data' as PortId];\n\n    context.raiseEvent(eventName, eventData);\n\n    return {\n      result: eventData as DataValue,\n    };\n  }\n}\n\nexport const raiseEventNode = nodeDefinition(RaiseEventNodeImpl, 'Raise Event');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { type DataType, type DataValue } from '../DataValue.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { type NodeBodySpec } from '../NodeBodySpec.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\n\nexport type ContextNode = ChartNode<'context', ContextNodeData>;\n\nexport type ContextNodeData = {\n  id: string;\n  dataType: DataType;\n  defaultValue?: unknown;\n  useDefaultValueInput?: boolean;\n};\n\nexport class ContextNodeImpl extends NodeImpl<ContextNode> {\n  static create(): ContextNode {\n    const chartNode: ContextNode = {\n      type: 'context',\n      title: 'Context',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 300,\n      },\n      data: {\n        id: 'input',\n        dataType: 'string',\n        defaultValue: undefined,\n        useDefaultValueInput: false,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    if (this.data.useDefaultValueInput) {\n      return [\n        {\n          id: 'default' as PortId,\n          title: 'Default Value',\n          dataType: this.chartNode.data.dataType as DataType,\n        },\n      ];\n    }\n\n    return [];\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'data' as PortId,\n        title: this.data.id,\n        dataType: this.chartNode.data.dataType as DataType,\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<ContextNode>[] {\n    return [\n      { type: 'string', label: 'ID', dataKey: 'id' },\n      { type: 'dataTypeSelector', label: 'Data Type', dataKey: 'dataType' },\n      {\n        type: 'anyData',\n        label: 'Default Value',\n        dataKey: 'defaultValue',\n        useInputToggleDataKey: 'useDefaultValueInput',\n      },\n    ];\n  }\n\n  getBody(): string | NodeBodySpec | undefined {\n    return dedent`\n      ${this.data.id}\n      Type: ${this.data.dataType}\n    `;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Retrieves a value from the graph's context using a configured id. The context serves as a \"global graph input\", allowing the same values to be accessible from any graph or subgraph.\n      `,\n      infoBoxTitle: 'Context Node',\n      contextMenuTitle: 'Context',\n      group: ['Advanced'],\n    };\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const contextValue = context.contextValues[this.data.id];\n\n    if (contextValue !== undefined) {\n      return {\n        ['data' as PortId]: contextValue,\n      };\n    }\n\n    let defaultValue;\n    if (this.data.useDefaultValueInput) {\n      defaultValue = inputs['default' as PortId]!;\n    } else {\n      defaultValue = { type: this.data.dataType, value: this.data.defaultValue } as DataValue;\n    }\n\n    return {\n      ['data' as PortId]: defaultValue,\n    };\n  }\n}\n\nexport const contextNode = nodeDefinition(ContextNodeImpl, 'Context');\n", "import { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport {\n  type ChartNode,\n  type NodeConnection,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport { type DataValue, unwrapDataValue } from '../DataValue.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { dedent } from 'ts-dedent';\nimport { nodeDefinition } from '../NodeDefinition.js';\n\nexport type CoalesceNode = ChartNode<'coalesce', CoalesceNodeData>;\n\nexport type CoalesceNodeData = {};\n\nexport class CoalesceNodeImpl extends NodeImpl<CoalesceNode> {\n  static create = (): CoalesceNode => {\n    const chartNode: CoalesceNode = {\n      type: 'coalesce',\n      title: 'Coalesce',\n      id: nanoid() as NodeId,\n      data: {},\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 150,\n      },\n    };\n    return chartNode;\n  };\n\n  getInputDefinitions(connections: NodeConnection[]): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [];\n    const inputCount = this.#getInputPortCount(connections);\n\n    inputs.push({\n      dataType: 'boolean',\n      id: 'conditional' as PortId,\n      title: 'Conditional',\n    });\n\n    for (let i = 1; i <= inputCount; i++) {\n      inputs.push({\n        dataType: 'any',\n        id: `input${i}` as PortId,\n        title: `Input ${i}`,\n      });\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        dataType: 'any',\n        id: 'output' as PortId,\n        title: 'Output',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Takes in any number of inputs and outputs the first value that exists. Useful for consolidating branches after a Match node. This node can also \"consume\" the \"Not Ran\" value.\n      `,\n      infoBoxTitle: 'Coalesce Node',\n      contextMenuTitle: 'Coalesce',\n      group: ['Logic'],\n    };\n  }\n\n  #getInputPortCount(connections: NodeConnection[]): number {\n    const inputNodeId = this.chartNode.id;\n    const inputConnections = connections.filter(\n      (connection) => connection.inputNodeId === inputNodeId && connection.inputId.startsWith('input'),\n    );\n\n    let maxInputNumber = 0;\n    for (const connection of inputConnections) {\n      const messageNumber = parseInt(connection.inputId.replace('input', ''), 10);\n      if (messageNumber > maxInputNumber) {\n        maxInputNumber = messageNumber;\n      }\n    }\n\n    return maxInputNumber + 1;\n  }\n\n  async process(inputData: Inputs): Promise<Outputs> {\n    const conditional = inputData['conditional' as PortId];\n\n    // This lets the coalesce actually be control-flow-excluded itself, because otherwise\n    // the input control-flow-excluded are consumed.\n    if (conditional?.type === 'control-flow-excluded') {\n      return {\n        ['output' as PortId]: {\n          type: 'control-flow-excluded',\n          value: undefined,\n        },\n      };\n    }\n\n    const inputCount = Object.keys(inputData).filter((key) => key.startsWith('input')).length;\n    const okInputValues: DataValue[] = [];\n\n    for (let i = 1; i <= inputCount; i++) {\n      const inputValue = inputData[`input${i}` as PortId];\n      if (inputValue && inputValue.type !== 'control-flow-excluded' && unwrapDataValue(inputValue) != null) {\n        okInputValues.push(inputValue);\n      }\n    }\n\n    if (okInputValues.length === 0) {\n      return {\n        ['output' as PortId]: {\n          type: 'control-flow-excluded',\n          value: undefined,\n        },\n      };\n    }\n\n    return {\n      ['output' as PortId]: okInputValues[0]!,\n    };\n  }\n}\n\nexport const coalesceNode = nodeDefinition(CoalesceNodeImpl, 'Coalesce');\n", "import { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport {\n  type ChartNode,\n  type NodeConnection,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { dedent } from 'ts-dedent';\n\nexport type PassthroughNode = ChartNode<'passthrough', PassthroughNodeData>;\n\nexport type PassthroughNodeData = {};\n\nexport class PassthroughNodeImpl extends NodeImpl<PassthroughNode> {\n  static create = (): PassthroughNode => {\n    const chartNode: PassthroughNode = {\n      type: 'passthrough',\n      title: 'Passthrough',\n      id: nanoid() as NodeId,\n      data: {},\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 175,\n      },\n    };\n    return chartNode;\n  };\n\n  getInputDefinitions(connections: NodeConnection[]): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [];\n    const inputCount = this.#getInputPortCount(connections);\n\n    for (let i = 1; i <= inputCount; i++) {\n      inputs.push({\n        dataType: 'any',\n        id: `input${i}` as PortId,\n        title: `Input ${i}`,\n      });\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(connections: NodeConnection[]): NodeOutputDefinition[] {\n    const outputs: NodeOutputDefinition[] = [];\n    const inputCount = this.#getInputPortCount(connections);\n\n    for (let i = 1; i <= inputCount - 1; i++) {\n      outputs.push({\n        dataType: 'any',\n        id: `output${i}` as PortId,\n        title: `Output ${i}`,\n      });\n    }\n\n    return outputs;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Simply passes the input value to the output without any modifications.\n      `,\n      infoBoxTitle: 'Passthrough Node',\n      contextMenuTitle: 'Passthrough',\n      group: ['Logic'],\n    };\n  }\n\n  #getInputPortCount(connections: NodeConnection[]): number {\n    const inputNodeId = this.chartNode.id;\n    const inputConnections = connections.filter(\n      (connection) => connection.inputNodeId === inputNodeId && connection.inputId.startsWith('input'),\n    );\n\n    let maxInputNumber = 0;\n    for (const connection of inputConnections) {\n      const messageNumber = parseInt(connection.inputId.replace('input', ''), 10);\n      if (messageNumber > maxInputNumber) {\n        maxInputNumber = messageNumber;\n      }\n    }\n\n    return maxInputNumber + 1;\n  }\n\n  async process(inputData: Inputs): Promise<Outputs> {\n    const inputCount = Object.keys(inputData).filter((key) => key.startsWith('input')).length;\n\n    const outputs: Outputs = {};\n\n    for (let i = 1; i <= inputCount; i++) {\n      const input = inputData[`input${i}` as PortId]!;\n      outputs[`output${i}` as PortId] = input;\n    }\n\n    return outputs;\n  }\n}\n\nexport const passthroughNode = nodeDefinition(PassthroughNodeImpl, 'Passthrough');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeBody, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { dedent } from 'ts-dedent';\nimport type { EditorDefinition } from '../EditorDefinition.js';\nimport type { RivetUIContext } from '../RivetUIContext.js';\n\nexport type PopNode = ChartNode<'pop', PopNodeData>;\n\nexport type PopNodeData = {\n  fromFront?: boolean;\n};\n\nexport class PopNodeImpl extends NodeImpl<PopNode> {\n  static create(): PopNode {\n    const baseNode: PopNode = {\n      type: 'pop',\n      title: 'Pop',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 200,\n      },\n      data: {},\n    };\n\n    return baseNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    return [\n      {\n        dataType: 'any[]',\n        id: 'array' as PortId,\n        title: 'Array',\n        coerced: false,\n      },\n    ];\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        dataType: 'any',\n        id: 'lastItem' as PortId,\n        title: this.data.fromFront ? 'First' : 'Last',\n      },\n      {\n        dataType: 'any',\n        id: 'restOfArray' as PortId,\n        title: 'Rest',\n      },\n    ];\n  }\n\n  getEditors(_context: RivetUIContext): EditorDefinition<PopNode>[] | Promise<EditorDefinition<PopNode>[]> {\n    return [\n      {\n        label: 'Pop from front',\n        type: 'toggle',\n        dataKey: 'fromFront',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Pops the last value off the input array and outputs the new array and the popped value.\n\n        Can also be used to just extract the last value from an array.\n      `,\n      infoBoxTitle: 'Pop Node',\n      contextMenuTitle: 'Pop',\n      group: ['Lists'],\n    };\n  }\n\n  getBody(_context: RivetUIContext): NodeBody | Promise<NodeBody> {\n    return this.data.fromFront ? 'From front' : 'From back';\n  }\n\n  async process(inputs: Inputs): Promise<Outputs> {\n    const inputArray = inputs['array' as PortId]?.value;\n\n    if (!Array.isArray(inputArray) || inputArray.length === 0) {\n      throw new Error('Input array is empty or not an array');\n    }\n\n    const lastItem = this.data.fromFront ? inputArray[0] : inputArray[inputArray.length - 1];\n    const rest = this.data.fromFront ? inputArray.slice(1) : inputArray.slice(0, inputArray.length - 1);\n\n    return {\n      ['lastItem' as PortId]: {\n        type: 'any',\n        value: lastItem,\n      },\n      ['restOfArray' as PortId]: {\n        type: 'any[]',\n        value: rest,\n      },\n    };\n  }\n}\n\nexport const popNode = nodeDefinition(PopNodeImpl, 'Pop');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport {\n  type DataType,\n  type ScalarDataValue,\n  isArrayDataType,\n  isScalarDataType,\n  scalarDefaults,\n  unwrapDataValue,\n} from '../DataValue.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { coerceType } from '../../utils/coerceType.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { type NodeBodySpec } from '../NodeBodySpec.js';\n\nexport type SetGlobalNode = ChartNode<'setGlobal', SetGlobalNodeData>;\n\nexport type SetGlobalNodeData = {\n  id: string;\n  useIdInput: boolean;\n  dataType: DataType;\n};\n\nexport class SetGlobalNodeImpl extends NodeImpl<SetGlobalNode> {\n  static create(): SetGlobalNode {\n    const chartNode: SetGlobalNode = {\n      type: 'setGlobal',\n      title: 'Set Global',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 200,\n      },\n      data: {\n        id: 'variable-name',\n        dataType: 'string',\n        useIdInput: false,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputs = [\n      {\n        id: 'value' as PortId,\n        title: 'Value',\n        dataType: this.chartNode.data.dataType as DataType,\n      },\n    ];\n\n    if (this.data.useIdInput) {\n      inputs.push({\n        id: 'id' as PortId,\n        title: 'Variable ID',\n        dataType: 'string',\n      });\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'saved-value' as PortId,\n        title: 'Value',\n        dataType: this.data.dataType,\n      },\n      {\n        id: 'previous-value' as PortId,\n        title: 'Previous Value',\n        dataType: this.data.dataType,\n      },\n      {\n        id: 'variable_id_out' as PortId,\n        title: 'Variable ID',\n        dataType: 'string',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<SetGlobalNode>[] {\n    return [\n      {\n        type: 'string',\n        dataKey: 'id',\n        useInputToggleDataKey: 'useIdInput',\n        label: 'ID',\n      },\n      {\n        type: 'dataTypeSelector',\n        dataKey: 'dataType',\n        label: 'Data Type',\n        useInputToggleDataKey: 'useIdInput',\n      },\n    ];\n  }\n\n  getBody(): string | NodeBodySpec | undefined {\n    return dedent`\n      ${this.data.id}\n      Type: ${this.data.dataType}\n    `;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Sets a global value that is shared across all graphs and subgraphs. The id of the global value and the value itself are configured in this node.\n      `,\n      infoBoxTitle: 'Set Global Node',\n      contextMenuTitle: 'Set Global',\n      group: ['Advanced'],\n    };\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const rawValue = inputs['value' as PortId]!;\n    if (!rawValue) {\n      return {};\n    }\n\n    const id = this.data.useIdInput ? coerceType(inputs['id' as PortId], 'string') : this.data.id;\n\n    if (!id) {\n      throw new Error('Missing variable ID');\n    }\n\n    let previousValue = context.getGlobal(this.data.id);\n    if (!previousValue && isArrayDataType(this.data.dataType)) {\n      previousValue = { type: this.data.dataType, value: [] };\n    } else if (!previousValue && isScalarDataType(this.data.dataType)) {\n      previousValue = { type: this.data.dataType, value: scalarDefaults[this.data.dataType] } as ScalarDataValue;\n    }\n\n    const value = unwrapDataValue(rawValue);\n\n    context.setGlobal(id, value);\n\n    return {\n      ['saved-value' as PortId]: value,\n      ['previous-value' as PortId]: previousValue,\n      ['variable_id_out' as PortId]: { type: 'string', value: id },\n    };\n  }\n}\n\nexport const setGlobalNode = nodeDefinition(SetGlobalNodeImpl, 'Set Global');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport {\n  type FunctionDataValues,\n  type ScalarDataType,\n  type ScalarDataValue,\n  type ScalarOrArrayDataType,\n  isArrayDataType,\n  isScalarDataType,\n  scalarDefaults,\n} from '../DataValue.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { coerceType } from '../../utils/coerceType.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition, type NodeBodySpec } from '../../index.js';\n\nexport type GetGlobalNode = ChartNode<'getGlobal', GetGlobalNodeData>;\n\nexport type GetGlobalNodeData = {\n  id: string;\n  useIdInput: boolean;\n\n  dataType: ScalarOrArrayDataType;\n\n  /**\n   * Returns a fn<value> instead of a value, so that the variable is read when nodes need it, rather than when this node executes.\n   * The only time you wouldn't want this is to read a global at the start of a subgraph.\n   */\n  onDemand: boolean;\n\n  /** Wait until the variable is available */\n  wait: boolean;\n};\n\nexport class GetGlobalNodeImpl extends NodeImpl<GetGlobalNode> {\n  static create(): GetGlobalNode {\n    const chartNode: GetGlobalNode = {\n      type: 'getGlobal',\n      title: 'Get Global',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 200,\n      },\n      data: {\n        id: 'variable-name',\n        dataType: 'string',\n        onDemand: true,\n        useIdInput: false,\n        wait: false,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    if (this.data.useIdInput) {\n      return [\n        {\n          id: 'id' as PortId,\n          title: 'Variable ID',\n          dataType: this.data.dataType as ScalarDataType,\n        },\n      ];\n    }\n\n    return [];\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    const { onDemand, dataType } = this.chartNode.data;\n    return [\n      {\n        id: 'value' as PortId,\n        title: 'Value',\n        dataType: onDemand ? (`fn<${dataType}>` as const) : dataType,\n      },\n      {\n        id: 'variable_id_out' as PortId,\n        title: 'Variable ID',\n        dataType: 'string',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<GetGlobalNode>[] {\n    return [\n      {\n        type: 'string',\n        label: 'Variable ID',\n        dataKey: 'id',\n        useInputToggleDataKey: 'useIdInput',\n      },\n      {\n        type: 'dataTypeSelector',\n        label: 'Data Type',\n        dataKey: 'dataType',\n      },\n      {\n        type: 'toggle',\n        label: 'On Demand',\n        dataKey: 'onDemand',\n      },\n      {\n        type: 'toggle',\n        label: 'Wait',\n        dataKey: 'wait',\n      },\n    ];\n  }\n\n  getBody(): string | NodeBodySpec | undefined {\n    return dedent`\n      ${this.data.useIdInput ? '(ID from input)' : this.data.id}\n      Type: ${this.data.dataType}\n      ${this.data.wait ? 'Waits for available data' : ''}\n    `;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Retrieves a global value that is shared across all graphs and subgraphs. The id of the global value is configured in this node.\n      `,\n      infoBoxTitle: 'Get Global Node',\n      contextMenuTitle: 'Get Global',\n      group: ['Advanced'],\n    };\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    if (this.data.onDemand) {\n      if (this.data.wait) {\n        throw new Error('Cannot use onDemand and wait together');\n      }\n      return {\n        ['value' as PortId]: {\n          type: `fn<${this.data.dataType}>` as const,\n          value: () => {\n            const id = this.data.useIdInput ? coerceType(inputs['id' as PortId], 'string') : this.data.id;\n\n            const value = context.getGlobal(id);\n            if (value) {\n              return value.value;\n            }\n\n            // Have some useful defaults before the value is set\n            if (isArrayDataType(this.data.dataType)) {\n              return [];\n            }\n\n            return scalarDefaults[this.data.dataType];\n          },\n        } as FunctionDataValues,\n      };\n    }\n\n    const id = this.data.useIdInput ? coerceType(inputs['id' as PortId], 'string') : this.data.id;\n\n    let value = this.data.wait ? await context.waitForGlobal(id) : context.getGlobal(id);\n\n    // Have some useful defaults before the value is set\n    if (!value && isArrayDataType(this.data.dataType)) {\n      value = { type: this.data.dataType, value: [] };\n    }\n\n    if (!value && isScalarDataType(this.data.dataType)) {\n      value = { type: this.data.dataType, value: scalarDefaults[this.data.dataType] } as ScalarDataValue;\n    }\n\n    return {\n      ['value' as PortId]: value,\n      ['variable_id_out' as PortId]: { type: 'string', value: id },\n    };\n  }\n}\n\nexport const getGlobalNode = nodeDefinition(GetGlobalNodeImpl, 'Get Global');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { coerceType } from '../../utils/coerceType.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { type NodeBodySpec } from '../NodeBodySpec.js';\n\nexport type WaitForEventNode = ChartNode<'waitForEvent', WaitForEventNodeData>;\n\nexport type WaitForEventNodeData = {\n  eventName: string;\n  useEventNameInput: boolean;\n};\n\nexport class WaitForEventNodeImpl extends NodeImpl<WaitForEventNode> {\n  static create(): WaitForEventNode {\n    return {\n      id: nanoid() as NodeId,\n      type: 'waitForEvent',\n      title: 'Wait For Event',\n      visualData: { x: 0, y: 0, width: 150 },\n      data: {\n        eventName: 'continue',\n        useEventNameInput: false,\n      },\n    };\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputDefinitions: NodeInputDefinition[] = [];\n\n    if (this.chartNode.data.useEventNameInput) {\n      inputDefinitions.push({\n        id: 'eventName' as PortId,\n        title: 'Event Name',\n        dataType: 'string',\n      });\n    }\n\n    inputDefinitions.push({\n      id: 'inputData' as PortId,\n      title: 'Data',\n      dataType: 'any',\n    });\n\n    return inputDefinitions;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'outputData' as PortId,\n        title: 'Data',\n        dataType: 'any',\n      },\n      {\n        id: 'eventData' as PortId,\n        title: 'Event Data',\n        dataType: 'any',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<WaitForEventNode>[] {\n    return [\n      {\n        type: 'string',\n        label: 'Event Name',\n        dataKey: 'eventName',\n        useInputToggleDataKey: 'useEventNameInput',\n      },\n    ];\n  }\n\n  getBody(): string | NodeBodySpec | undefined {\n    return this.data.useEventNameInput ? '(Using Input)' : this.data.eventName;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Waits for a specific event to be raised by a 'Raise Event' node or the host project. The event name can be configured.\n      `,\n      infoBoxTitle: 'Wait For Event Node',\n      contextMenuTitle: 'Wait For Event',\n      group: ['Advanced'],\n    };\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const eventName = this.chartNode.data.useEventNameInput\n      ? coerceType(inputs['eventName' as PortId], 'string')\n      : this.chartNode.data.eventName;\n\n    const eventData = await context.waitEvent(eventName);\n\n    return {\n      ['outputData' as PortId]: inputs['inputData' as PortId],\n      ['eventData' as PortId]: eventData,\n    };\n  }\n}\n\nexport const waitForEventNode = nodeDefinition(WaitForEventNodeImpl, 'Wait For Event');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { type NodeBodySpec } from '../NodeBodySpec.js';\nimport { interpolate } from '../../utils/interpolation.js';\nimport type { Inputs, Outputs } from '../GraphProcessor.js';\nimport { keys } from '../../utils/typeSafety.js';\nimport { coerceTypeOptional, coerceType } from '../../utils/coerceType.js';\nimport { getInputOrData } from '../../utils/index.js';\n\nexport type GptFunctionNode = ChartNode<'gptFunction', GptFunctionNodeData>;\n\nexport type GptFunctionNodeData = {\n  name: string;\n  useNameInput?: boolean;\n\n  description: string;\n  useDescriptionInput?: boolean;\n\n  schema: string;\n  useSchemaInput?: boolean;\n\n  strict?: boolean;\n};\n\nexport class GptFunctionNodeImpl extends NodeImpl<GptFunctionNode> {\n  static create(): GptFunctionNode {\n    const chartNode: GptFunctionNode = {\n      type: 'gptFunction',\n      title: 'Tool',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 250,\n      },\n      data: {\n        name: 'newTool',\n        description: 'No description provided',\n        schema: dedent`\n          {\n            \"type\": \"object\",\n            \"properties\": {}\n          }`,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    let inputs: NodeInputDefinition[] = [];\n\n    if (this.data.useNameInput) {\n      inputs.push({\n        id: 'name' as PortId,\n        title: 'Name',\n        dataType: 'string',\n        description: 'The name of the tool that the LLM will see as available to call',\n      });\n    }\n\n    if (this.data.useDescriptionInput) {\n      inputs.push({\n        id: 'description' as PortId,\n        title: 'Description',\n        dataType: 'string',\n        description: 'The description of the tool that the LLM will see as available to call',\n      });\n    }\n\n    if (this.data.useSchemaInput) {\n      inputs.push({\n        id: 'schema' as PortId,\n        title: 'Schema',\n        dataType: 'object',\n        description: 'The schema of the tool that the LLM will see as available to call',\n      });\n    }\n\n    // Extract inputs from promptText, everything like {{input}}\n    const inputNames = this.data.useSchemaInput ? [] : [...new Set(this.data.schema.match(/\\{\\{([^}]+)\\}\\}/g))];\n    inputs = [\n      ...inputs,\n      ...(inputNames?.map((inputName): NodeInputDefinition => {\n        const name = inputName.slice(2, -2);\n        return {\n          // id and title should not have the {{ and }}\n          id: `input-${name}` as PortId,\n          title: name,\n          dataType: 'string',\n          description: `An interpolated value in the schema named '${name}'`,\n        };\n      }) ?? []),\n    ];\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'function' as PortId,\n        title: 'Function',\n        dataType: 'gpt-function',\n        description: 'The tool that can be called by the LLM.',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<GptFunctionNode>[] {\n    return [\n      {\n        type: 'string',\n        label: 'Name',\n        dataKey: 'name',\n        useInputToggleDataKey: 'useNameInput',\n      },\n      {\n        type: 'toggle',\n        label: 'Strict',\n        dataKey: 'strict',\n        helperMessage: 'Sets the strict parameter, which determines if OpenAI Structured Outputs are used.',\n      },\n      {\n        type: 'code',\n        label: 'Description',\n        dataKey: 'description',\n        useInputToggleDataKey: 'useDescriptionInput',\n        language: 'markdown',\n        height: 100,\n      },\n      {\n        type: 'custom',\n        customEditorId: 'GptFunctionNodeJsonSchemaAiAssist',\n        label: 'AI Assist',\n      },\n      {\n        type: 'code',\n        label: 'Schema',\n        dataKey: 'schema',\n        language: 'json',\n        useInputToggleDataKey: 'useSchemaInput',\n      },\n    ];\n  }\n\n  getBody(): string | NodeBodySpec | undefined {\n    return `!markdown_${this.data.name}_: ${this.data.description}`;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Defines a tool, which is a method that the LLM can call in its responses.\n      `,\n      infoBoxTitle: 'Tool Node',\n      contextMenuTitle: 'Tool',\n      group: ['AI'],\n    };\n  }\n\n  async process(inputs: Inputs): Promise<Outputs> {\n    const name = getInputOrData(this.data, inputs, 'name');\n    const description = getInputOrData(this.data, inputs, 'description');\n\n    let schema: unknown;\n    if (this.data.useSchemaInput) {\n      schema = coerceType(inputs['schema' as PortId], 'object');\n    } else {\n      const inputMap = keys(inputs)\n        .filter((key) => key.startsWith('input'))\n        .reduce(\n          (acc, key) => {\n            const stringValue = coerceTypeOptional(inputs[key], 'string') ?? '';\n\n            const interpolationKey = key.slice('input-'.length);\n            acc[interpolationKey] = stringValue;\n            return acc;\n          },\n          {} as Record<string, string>,\n        );\n\n      const interpolated = interpolate(this.data.schema, inputMap);\n\n      schema = JSON.parse(interpolated);\n    }\n\n    return {\n      ['function' as PortId]: {\n        type: 'gpt-function',\n        value: {\n          name,\n          description,\n          parameters: schema as object,\n          strict: this.data.strict ?? false,\n        },\n      },\n    };\n  }\n}\n\nexport const gptFunctionNode = nodeDefinition(GptFunctionNodeImpl, 'Tool');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\n// @ts-ignore\nimport yaml from 'yaml';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { coerceType } from '../../utils/index.js';\nimport { dedent } from 'ts-dedent';\nimport { nodeDefinition } from '../NodeDefinition.js';\n\nexport type ToYamlNode = ChartNode<'toYaml', ToYamlNodeData>;\n\nexport type ToYamlNodeData = {};\n\nexport class ToYamlNodeImpl extends NodeImpl<ToYamlNode> {\n  static create(): ToYamlNode {\n    const chartNode: ToYamlNode = {\n      type: 'toYaml',\n      title: 'To YAML',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 175,\n      },\n      data: {},\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    return [\n      {\n        id: 'object' as PortId,\n        title: 'Object',\n        dataType: 'object',\n        required: true,\n      },\n    ];\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'yaml' as PortId,\n        title: 'YAML',\n        dataType: 'string',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Turns the input object into YAML text.\n      `,\n      infoBoxTitle: 'To YAML Node',\n      contextMenuTitle: 'To YAML',\n      group: ['Text'],\n    };\n  }\n\n  async process(inputs: Inputs): Promise<Outputs> {\n    const object = coerceType(inputs['object' as PortId], 'object');\n\n    const toYaml = yaml.stringify(object, null, {\n      indent: 2,\n      aliasDuplicateObjects: false,\n    });\n\n    return {\n      ['yaml' as PortId]: {\n        type: 'string',\n        value: toYaml,\n      },\n    };\n  }\n}\n\nexport const toYamlNode = nodeDefinition(ToYamlNodeImpl, 'To YAML');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { type EditorDefinition } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { coerceType } from '../../utils/coerceType.js';\nimport { getIntegration } from '../../integrations/integrations.js';\n\nexport type GetEmbeddingNode = ChartNode<'getEmbedding', GetEmbeddingNodeData>;\n\nexport type GetEmbeddingNodeData = {\n  integration: string;\n  model?: string;\n  dimensions?: number;\n  useIntegrationInput?: boolean;\n  useModelInput?: boolean;\n  useDimensionsInput?: boolean;\n};\n\nexport class GetEmbeddingNodeImpl extends NodeImpl<GetEmbeddingNode> {\n  static create(): GetEmbeddingNode {\n    return {\n      id: nanoid() as NodeId,\n      type: 'getEmbedding',\n      title: 'Get Embedding',\n      visualData: { x: 0, y: 0, width: 250 },\n      data: {\n        integration: 'openai',\n        useIntegrationInput: false,\n        model: undefined,\n        dimensions: undefined,\n      },\n    };\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputDefinitions: NodeInputDefinition[] = [];\n\n    inputDefinitions.push({\n      id: 'input' as PortId,\n      title: 'Input',\n      dataType: 'string',\n      required: true,\n    });\n\n    if (this.data.useIntegrationInput) {\n      inputDefinitions.push({\n        id: 'integration' as PortId,\n        title: 'Integration',\n        dataType: 'string',\n        required: true,\n      });\n    }\n\n    if (this.data.useModelInput) {\n      inputDefinitions.push({\n        id: 'model' as PortId,\n        title: 'Model',\n        dataType: 'string',\n        required: false,\n      });\n    }\n\n    if (this.data.useDimensionsInput) {\n      inputDefinitions.push({\n        id: 'dimensions' as PortId,\n        title: 'Dimensions',\n        dataType: 'number',\n        required: false,\n      });\n    }\n\n    return inputDefinitions;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    const outputs: NodeOutputDefinition[] = [\n      {\n        id: 'embedding' as PortId,\n        title: 'Embedding',\n        dataType: 'vector',\n      },\n    ];\n\n    return outputs;\n  }\n\n  getEditors(): EditorDefinition<GetEmbeddingNode>[] {\n    return [\n      {\n        type: 'dropdown',\n        label: 'Integration',\n        dataKey: 'integration',\n        options: [{ label: 'OpenAI', value: 'openai' }],\n        useInputToggleDataKey: 'useIntegrationInput',\n      },\n      {\n        type: 'string',\n        label: 'Model',\n        dataKey: 'model',\n        useInputToggleDataKey: 'useModelInput',\n      },\n      {\n        type: 'number',\n        label: 'Dimensions',\n        dataKey: 'dimensions',\n        useInputToggleDataKey: 'useDimensionsInput',\n      },\n    ];\n  }\n\n  getBody(): string | undefined {\n    return `Using ${this.data.useIntegrationInput ? '(input)' : this.data.integration}`;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Gets a OpenAI vector embedding for the input text provided.\n\n        Can be used with the Vector Store and Vector KNN nodes.\n      `,\n      infoBoxTitle: 'Get Embedding Node',\n      contextMenuTitle: 'Get Embedding',\n      group: ['AI'],\n    };\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const input = coerceType(inputs['input' as PortId], 'string');\n\n    const integrationName = this.data.useIntegrationInput\n      ? coerceType(inputs['integration' as PortId], 'string')\n      : this.data.integration;\n\n    const model = this.data.useModelInput ? coerceType(inputs['model' as PortId], 'string') : this.data.model;\n\n    const dimensions = this.data.useDimensionsInput\n      ? coerceType(inputs['dimensions' as PortId], 'number')\n      : this.data.dimensions;\n\n    const embeddingGenerator = getIntegration('embeddingGenerator', integrationName, context);\n\n    const embedding = await embeddingGenerator.generateEmbedding(input, {\n      model,\n      dimensions,\n    });\n\n    return {\n      ['embedding' as PortId]: {\n        type: 'vector',\n        value: embedding,\n      },\n    };\n  }\n}\n\nexport const getEmbeddingNode = nodeDefinition(GetEmbeddingNodeImpl, 'Get Embedding');\n", "import { type InternalProcessContext } from '../model/ProcessContext.js';\nimport { type EmbeddingGenerator } from './EmbeddingGenerator.js';\nimport { type LLMProvider } from './LLMProvider.js';\nimport { type VectorDatabase } from './VectorDatabase.js';\n\nexport type IntegrationFactories = {\n  vectorDatabase: (context: InternalProcessContext) => VectorDatabase;\n  llmProvider: (context: InternalProcessContext) => LLMProvider;\n  embeddingGenerator: (context: InternalProcessContext) => EmbeddingGenerator;\n};\n\nexport type IntegrationType = keyof IntegrationFactories;\n\nconst registeredIntegrations: {\n  [P in IntegrationType]: Map<string, IntegrationFactories[P]>;\n} = {\n  vectorDatabase: new Map<string, (context: InternalProcessContext) => VectorDatabase>(),\n  llmProvider: new Map<string, (context: InternalProcessContext) => LLMProvider>(),\n  embeddingGenerator: new Map<string, (context: InternalProcessContext) => EmbeddingGenerator>(),\n};\n\nexport function registerIntegration<T extends IntegrationType>(\n  type: T,\n  integrationKey: string,\n  factory: IntegrationFactories[T],\n): void {\n  registeredIntegrations[type].set(integrationKey, factory);\n}\n\nexport function getIntegration<T extends IntegrationType>(\n  type: T,\n  integrationKey: string,\n  context: InternalProcessContext,\n): ReturnType<IntegrationFactories[T]> {\n  const factory = registeredIntegrations[type].get(integrationKey);\n  if (!factory) {\n    throw new Error(`Integration ${integrationKey} not found`);\n  }\n  return factory(context) as ReturnType<IntegrationFactories[T]>;\n}\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { type EditorDefinition, type VectorDataValue } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { getIntegration } from '../../integrations/integrations.js';\nimport { getInputOrData } from '../../utils/index.js';\nimport { coerceTypeOptional } from '../../utils/coerceType.js';\n\nexport type VectorStoreNode = ChartNode<'vectorStore', VectorStoreNodeData>;\n\nexport type VectorStoreNodeData = {\n  integration: string;\n  useIntegrationInput?: boolean;\n\n  collectionId: string;\n  useCollectionIdInput?: boolean;\n};\n\nexport class VectorStoreNodeImpl extends NodeImpl<VectorStoreNode> {\n  static create(): VectorStoreNode {\n    return {\n      id: nanoid() as NodeId,\n      type: 'vectorStore',\n      title: 'Vector Store',\n      visualData: { x: 0, y: 0, width: 200 },\n      data: {\n        integration: 'pinecone',\n        collectionId: '',\n      },\n    };\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputDefinitions: NodeInputDefinition[] = [];\n\n    inputDefinitions.push({\n      id: 'vector' as PortId,\n      title: 'Vector',\n      dataType: 'vector',\n      required: true,\n    });\n\n    if (this.data.useCollectionIdInput) {\n      inputDefinitions.push({\n        id: 'collectionId' as PortId,\n        title: 'Collection ID',\n        dataType: 'string',\n        required: true,\n      });\n    }\n\n    inputDefinitions.push({\n      id: 'data' as PortId,\n      title: 'Data',\n      dataType: 'any',\n      required: true,\n    });\n\n    if (this.data.useIntegrationInput) {\n      inputDefinitions.push({\n        id: 'integration' as PortId,\n        title: 'Integration',\n        dataType: 'string',\n        required: true,\n      });\n    }\n\n    inputDefinitions.push({\n      id: 'id' as PortId,\n      title: 'ID',\n      dataType: 'string',\n      required: false,\n    });\n\n    return inputDefinitions;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    const outputs: NodeOutputDefinition[] = [\n      {\n        id: 'complete' as PortId,\n        title: 'Complete',\n        dataType: 'boolean',\n      },\n    ];\n\n    return outputs;\n  }\n\n  getEditors(): EditorDefinition<VectorStoreNode>[] {\n    return [\n      {\n        type: 'dropdown',\n        label: 'Integration',\n        dataKey: 'integration',\n        options: [{ label: 'Pinecone', value: 'pinecone' }],\n        useInputToggleDataKey: 'useIntegrationInput',\n      },\n      {\n        type: 'string',\n        label: 'Collection ID',\n        dataKey: 'collectionId',\n        useInputToggleDataKey: 'useCollectionIdInput',\n      },\n    ];\n  }\n\n  getBody(): string | undefined {\n    return dedent`\n      Integration: ${this.data.useIntegrationInput ? '(using input)' : this.data.integration}\n      Collection Id: ${this.data.useCollectionIdInput ? '(using input)' : this.data.collectionId}\n    `;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Takes in a vector, as well as data to store with the vector. This data is stored in the configured vector DB integration for later retrieval.\n      `,\n      infoBoxTitle: 'Vector Store Node',\n      contextMenuTitle: 'Vector Store',\n      group: ['Input/Output'],\n    };\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const integration = getInputOrData(this.data, inputs, 'integration');\n    const vectorDb = getIntegration('vectorDatabase', integration, context);\n\n    const indexUrl = getInputOrData(this.data, inputs, 'collectionId');\n\n    if (inputs['vector' as PortId]?.type !== 'vector') {\n      throw new Error(`Expected vector input, got ${inputs['vector' as PortId]?.type}`);\n    }\n\n    await vectorDb.store(\n      { type: 'string', value: indexUrl },\n      inputs['vector' as PortId] as VectorDataValue,\n      inputs['data' as PortId]!,\n      {\n        id: coerceTypeOptional(inputs['id' as PortId], 'string'),\n      },\n    );\n\n    return {\n      ['complete' as PortId]: {\n        type: 'boolean',\n        value: true,\n      },\n    };\n  }\n}\n\nexport const vectorStoreNode = nodeDefinition(VectorStoreNodeImpl, 'Vector Store');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { type DataValue, type EditorDefinition, type VectorDataValue } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { getIntegration } from '../../integrations/integrations.js';\nimport { getInputOrData } from '../../utils/index.js';\n\nexport type VectorNearestNeighborsNode = ChartNode<'vectorNearestNeighbors', VectorNearestNeighborsNodeData>;\n\nexport type VectorNearestNeighborsNodeData = {\n  integration: string;\n  useIntegrationInput?: boolean;\n\n  k: number;\n  useKInput?: boolean;\n\n  collectionId: string;\n  useCollectionIdInput?: boolean;\n};\n\nexport class VectorNearestNeighborsNodeImpl extends NodeImpl<VectorNearestNeighborsNode> {\n  static create(): VectorNearestNeighborsNode {\n    return {\n      id: nanoid() as NodeId,\n      type: 'vectorNearestNeighbors',\n      title: 'Vector KNN',\n      visualData: { x: 0, y: 0, width: 200 },\n      data: {\n        k: 10,\n        integration: 'pinecone',\n        collectionId: '',\n      },\n    };\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputDefinitions: NodeInputDefinition[] = [];\n\n    inputDefinitions.push({\n      id: 'vector' as PortId,\n      title: 'Vector',\n      dataType: 'vector',\n      required: true,\n    });\n\n    if (this.data.useIntegrationInput) {\n      inputDefinitions.push({\n        id: 'integration' as PortId,\n        title: 'Integration',\n        dataType: 'string',\n        required: true,\n      });\n    }\n\n    if (this.data.useCollectionIdInput) {\n      inputDefinitions.push({\n        id: 'collectionId' as PortId,\n        title: 'Collection ID',\n        dataType: 'string',\n        required: true,\n      });\n    }\n\n    if (this.data.useKInput) {\n      inputDefinitions.push({\n        id: 'k' as PortId,\n        title: 'K',\n        dataType: 'number',\n        required: true,\n      });\n    }\n\n    return inputDefinitions;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    const outputs: NodeOutputDefinition[] = [\n      {\n        id: 'results' as PortId,\n        title: 'Results',\n        dataType: 'any[]',\n      },\n    ];\n\n    return outputs;\n  }\n\n  getEditors(): EditorDefinition<VectorNearestNeighborsNode>[] {\n    return [\n      {\n        type: 'dropdown',\n        label: 'Integration',\n        dataKey: 'integration',\n        options: [{ label: 'Pinecone', value: 'pinecone' }],\n        useInputToggleDataKey: 'useIntegrationInput',\n      },\n      {\n        type: 'number',\n        label: 'K',\n        dataKey: 'k',\n        min: 1,\n        max: 100,\n        step: 1,\n        defaultValue: 10,\n        useInputToggleDataKey: 'useKInput',\n      },\n      {\n        type: 'string',\n        label: 'Collection ID',\n        dataKey: 'collectionId',\n        useInputToggleDataKey: 'useCollectionIdInput',\n      },\n    ];\n  }\n\n  getBody(): string | undefined {\n    return dedent`\n      Integration: ${this.data.useIntegrationInput ? '(using input)' : this.data.integration}\n      K: ${this.data.useKInput ? '(using input)' : this.data.k}\n      Collection Id: ${this.data.useCollectionIdInput ? '(using input)' : this.data.collectionId}\n    `;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Performs a k-nearest neighbors search on the vectors stored in the configured vector DB integration. Takes in a vector and returns the k closest vectors and their corresponding data.\n      `,\n      infoBoxTitle: 'Vector KNN Node',\n      contextMenuTitle: 'Vector KNN',\n      group: ['Input/Output'],\n    };\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const integration = getInputOrData(this.data, inputs, 'integration');\n    const vectorDb = getIntegration('vectorDatabase', integration, context);\n\n    const indexUrl = getInputOrData(this.data, inputs, 'collectionId');\n    const k = getInputOrData(this.data, inputs, 'k', 'number');\n\n    if (inputs['vector' as PortId]?.type !== 'vector') {\n      throw new Error(`Expected vector input, got ${inputs['vector' as PortId]?.type}`);\n    }\n\n    const results = await vectorDb.nearestNeighbors(\n      { type: 'string', value: indexUrl },\n      inputs['vector' as PortId] as VectorDataValue,\n      k,\n    );\n\n    return {\n      ['results' as PortId]: results as DataValue,\n    };\n  }\n}\n\nexport const vectorNearestNeighborsNode = nodeDefinition(VectorNearestNeighborsNodeImpl, 'Vector KNN');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type EditorDefinition, type Inputs, type Outputs } from '../../index.js';\nimport * as crypto from 'crypto-js';\nimport { match } from 'ts-pattern';\nimport { dedent } from 'ts-dedent';\nimport { coerceType } from '../../utils/coerceType.js';\n\nconst { SHA256, SHA512, MD5, SHA1 } = crypto;\n\nexport type HashNode = ChartNode<'hash', HashNodeData>;\n\nexport type HashNodeData = {\n  algorithm: 'md5' | 'sha1' | 'sha256' | 'sha512';\n};\n\nexport class HashNodeImpl extends NodeImpl<HashNode> {\n  static create(): HashNode {\n    const chartNode: HashNode = {\n      type: 'hash',\n      title: 'Hash',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 250,\n      },\n      data: {\n        algorithm: 'sha256',\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    return [\n      {\n        id: 'input' as PortId,\n        title: 'Input',\n        dataType: 'string',\n        required: true,\n      },\n    ];\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'hash' as PortId,\n        title: 'Hash',\n        dataType: 'string',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<HashNode>[] {\n    return [\n      {\n        type: 'dropdown',\n        label: 'Algorithm',\n        dataKey: 'algorithm',\n        options: [\n          { value: 'md5', label: 'MD5' },\n          { value: 'sha1', label: 'SHA1' },\n          { value: 'sha256', label: 'SHA256' },\n          { value: 'sha512', label: 'SHA512' },\n        ],\n      },\n    ];\n  }\n\n  getBody(): string | undefined {\n    return algorithmDisplayName[this.data.algorithm];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Computes a hash of the input value using the configured hash function.\n      `,\n      infoBoxTitle: 'Hash Node',\n      contextMenuTitle: 'Hash',\n      group: ['Data'],\n    };\n  }\n\n  async process(inputs: Inputs): Promise<Outputs> {\n    const inputText = coerceType(inputs['input' as PortId], 'string');\n\n    const hash = match(this.data.algorithm)\n      .with('md5', () => MD5(inputText).toString())\n      .with('sha1', () => SHA1(inputText).toString())\n      .with('sha256', () => SHA256(inputText).toString())\n      .with('sha512', () => SHA512(inputText).toString())\n      .exhaustive();\n\n    return {\n      ['hash' as PortId]: {\n        type: 'string',\n        value: hash,\n      },\n    };\n  }\n}\n\nconst algorithmDisplayName: Record<HashNodeData['algorithm'], string> = {\n  md5: 'MD5',\n  sha1: 'SHA-1',\n  sha256: 'SHA-256',\n  sha512: 'SHA-512',\n};\n\nexport const hashNode = nodeDefinition(HashNodeImpl, 'Hash');\n", "import type { ChartNode, NodeId, NodeOutputDefinition, PortId, NodeInputDefinition } from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport type { Inputs, Outputs } from '../GraphProcessor.js';\nimport type { InternalProcessContext } from '../ProcessContext.js';\nimport type { EditorDefinition } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { coerceTypeOptional } from '../../utils/coerceType.js';\n\nexport type AbortGraphNode = ChartNode<'abortGraph', AbortGraphNodeData>;\n\nexport type AbortGraphNodeData = {\n  /** Did the graph abort, but it's a success? Use this for early-exit instead of \"error abort\". */\n  successfully: boolean;\n\n  useSuccessfullyInput?: boolean;\n\n  errorMessage?: string;\n};\n\nexport class AbortGraphNodeImpl extends NodeImpl<AbortGraphNode> {\n  static create(): AbortGraphNode {\n    const chartNode: AbortGraphNode = {\n      type: 'abortGraph',\n      title: 'Abort Graph',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 200,\n      },\n      data: {\n        successfully: true,\n        errorMessage: '',\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [\n      {\n        id: 'data' as PortId,\n        title: 'Data or Error',\n        dataType: 'any',\n        description: 'The message to abort the graph with.',\n      },\n    ];\n\n    if (this.data.useSuccessfullyInput) {\n      inputs.push({\n        id: 'successfully' as PortId,\n        title: 'Successfully',\n        dataType: 'boolean',\n        description: 'Whether to successfully abort the graph (early-exit), or error abort the graph.',\n      });\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [];\n  }\n\n  getEditors(): EditorDefinition<AbortGraphNode>[] {\n    return [\n      {\n        type: 'toggle',\n        label: 'Successfully Abort',\n        dataKey: 'successfully',\n        useInputToggleDataKey: 'useSuccessfullyInput',\n      },\n      {\n        type: 'string',\n        label: 'Error Message (if not successfully aborting)',\n        dataKey: 'errorMessage',\n      },\n    ];\n  }\n\n  getBody(): string | undefined {\n    return dedent`\n      ${\n        this.data.useSuccessfullyInput\n          ? 'Success depends on input'\n          : this.data.successfully\n            ? 'Successfully Abort'\n            : this.data.errorMessage\n              ? `Error Abort: ${this.data.errorMessage}`\n              : 'Error Abort'\n      }\n    `;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Aborts the execution of the entire graph immediately.\n\n        Can either \"successfully\" abort the graph (early-exit), or \"error\" abort the graph.\n      `,\n      infoBoxTitle: 'Abort Graph Node',\n      contextMenuTitle: 'Abort Graph',\n      group: ['Logic'],\n    };\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const successfully = this.data.useSuccessfullyInput\n      ? coerceTypeOptional(inputs['successfully' as PortId], 'boolean') ?? this.data.successfully\n      : this.data.successfully;\n\n    if (successfully) {\n      context.abortGraph();\n    } else {\n      const errorMessage =\n        coerceTypeOptional(inputs['data' as PortId], 'string')?.trim() ||\n        this.data.errorMessage ||\n        'Graph aborted with error';\n      context.abortGraph(errorMessage);\n    }\n\n    return {};\n  }\n}\n\nexport const abortGraphNode = nodeDefinition(AbortGraphNodeImpl, 'Abort Graph');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type NodeOutputDefinition,\n  type NodeConnection,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../../index.js';\n\nexport type RaceInputsNode = ChartNode<'raceInputs', RaceInputsNodeData>;\n\nexport type RaceInputsNodeData = {};\n\nexport class RaceInputsNodeImpl extends NodeImpl<RaceInputsNode> {\n  static create(): RaceInputsNode {\n    const chartNode: RaceInputsNode = {\n      type: 'raceInputs',\n      title: 'Race Inputs',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 300,\n      },\n      data: {},\n    };\n\n    return chartNode;\n  }\n\n  #getInputPortCount(connections: NodeConnection[]): number {\n    const inputNodeId = this.chartNode.id;\n    const inputConnections = connections.filter(\n      (connection) => connection.inputNodeId === inputNodeId && connection.inputId.startsWith('input'),\n    );\n\n    let maxInputNumber = 0;\n    for (const connection of inputConnections) {\n      const messageNumber = parseInt(connection.inputId.replace('input', ''), 10);\n      if (messageNumber > maxInputNumber) {\n        maxInputNumber = messageNumber;\n      }\n    }\n\n    return maxInputNumber + 1;\n  }\n\n  getInputDefinitions(connections: NodeConnection[]): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [];\n    const inputCount = this.#getInputPortCount(connections);\n\n    for (let i = 1; i <= inputCount; i++) {\n      inputs.push({\n        dataType: 'any',\n        id: `input${i}` as PortId,\n        title: `Input ${i}`,\n      });\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'result' as PortId,\n        title: 'Result',\n        dataType: 'any',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<RaceInputsNode>[] {\n    return [];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Takes in multiple inputs and outputs the value of the first one to finish. The other inputs are cancelled.\n      `,\n      infoBoxTitle: 'Race Inputs Node',\n      contextMenuTitle: 'Race Inputs',\n      group: ['Logic'],\n    };\n  }\n\n  async process(inputs: Inputs): Promise<Outputs> {\n    // GraphProcessor handles most of the racing/aborting logic for us.\n    const value = Object.entries(inputs).find(\n      ([key, value]) => key.startsWith('input') && value !== undefined && value.type !== 'control-flow-excluded',\n    );\n\n    if (!value) {\n      return {\n        ['result' as PortId]: {\n          type: 'control-flow-excluded',\n          value: undefined,\n        },\n      };\n    }\n\n    return {\n      ['result' as PortId]: value[1],\n    };\n  }\n}\n\nexport const raceInputsNode = nodeDefinition(RaceInputsNodeImpl, 'Race Inputs');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type EditorDefinition } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { coerceType } from '../../utils/coerceType.js';\n\nexport type ToJsonNode = ChartNode<'toJson', ToJsonNodeData>;\n\nexport type ToJsonNodeData = {\n  indented?: boolean;\n};\n\nexport class ToJsonNodeImpl extends NodeImpl<ToJsonNode> {\n  static create(): ToJsonNode {\n    const chartNode: ToJsonNode = {\n      type: 'toJson',\n      title: 'To JSON',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 175,\n      },\n      data: {\n        indented: true,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    return [\n      {\n        id: 'data' as PortId,\n        title: 'Data',\n        dataType: 'any',\n        required: true,\n      },\n    ];\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'json' as PortId,\n        title: 'JSON',\n        dataType: 'string',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<ToJsonNode>[] {\n    return [\n      {\n        type: 'toggle',\n        label: 'Indented',\n        dataKey: 'indented',\n      },\n    ];\n  }\n\n  getBody(): string | undefined {\n    return this.data.indented ? 'Indented' : 'Not indented';\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Turns the input value into its JSON equivalent (stringifies the value).\n      `,\n      infoBoxTitle: 'To JSON Node',\n      contextMenuTitle: 'To JSON',\n      group: ['Text'],\n    };\n  }\n\n  async process(inputs: Inputs): Promise<Outputs> {\n    const data = coerceType(inputs['data' as PortId], 'any');\n\n    const toJson = this.data.indented ? JSON.stringify(data, null, 2) : JSON.stringify(data);\n\n    return {\n      ['json' as PortId]: {\n        type: 'string',\n        value: toJson,\n      },\n    };\n  }\n}\n\nexport const toJsonNode = nodeDefinition(ToJsonNodeImpl, 'To JSON');\n", "import { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport {\n  type ChartNode,\n  type NodeConnection,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport { isArrayDataValue } from '../DataValue.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { coerceType, coerceTypeOptional, inferType } from '../../utils/coerceType.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { handleEscapeCharacters } from '../../utils/index.js';\n\nexport type JoinNode = ChartNode<'join', JoinNodeData>;\n\nexport type JoinNodeData = {\n  flatten?: boolean;\n  joinString: string;\n  useJoinStringInput?: boolean;\n};\n\nexport class JoinNodeImpl extends NodeImpl<JoinNode> {\n  static create = (): JoinNode => {\n    const chartNode: JoinNode = {\n      type: 'join',\n      title: 'Join',\n      id: nanoid() as NodeId,\n      data: {\n        flatten: true,\n        joinString: '\\n',\n      },\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 150,\n      },\n    };\n    return chartNode;\n  };\n\n  getInputDefinitions(connections: NodeConnection[]): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [];\n    const inputCount = this.#getInputPortCount(connections);\n\n    if (this.data.useJoinStringInput) {\n      inputs.push({\n        dataType: 'string',\n        id: 'joinString' as PortId,\n        title: 'Join String',\n      });\n    }\n\n    for (let i = 1; i <= inputCount; i++) {\n      inputs.push({\n        dataType: 'string',\n        id: `input${i}` as PortId,\n        title: `Input ${i}`,\n      });\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        dataType: 'string',\n        id: 'output' as PortId,\n        title: 'Joined',\n      },\n    ];\n  }\n\n  #getInputPortCount(connections: NodeConnection[]): number {\n    const inputNodeId = this.chartNode.id;\n    const inputConnections = connections.filter(\n      (connection) => connection.inputNodeId === inputNodeId && connection.inputId.startsWith('input'),\n    );\n\n    let maxInputNumber = 0;\n    for (const connection of inputConnections) {\n      const messageNumber = parseInt(connection.inputId.replace('input', ''), 10);\n      if (messageNumber > maxInputNumber) {\n        maxInputNumber = messageNumber;\n      }\n    }\n\n    return maxInputNumber + 1;\n  }\n\n  getEditors(): EditorDefinition<JoinNode>[] {\n    return [\n      {\n        type: 'toggle',\n        label: 'Flatten',\n        dataKey: 'flatten',\n      },\n      {\n        type: 'code',\n        label: 'Join String',\n        dataKey: 'joinString',\n        useInputToggleDataKey: 'useJoinStringInput',\n        language: 'plaintext',\n      },\n    ];\n  }\n\n  getBody(): string | undefined {\n    return this.data.useJoinStringInput\n      ? '(Join value is input)'\n      : this.data.joinString === '\\n'\n        ? '(New line)'\n        : this.data.joinString === '\\t'\n          ? '(Tab)'\n          : this.data.joinString === ' '\n            ? '(Space)'\n            : this.data.joinString;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Takes an array of strings, and joins them using the configured delimiter.\n\n        Defaults to a newline.\n      `,\n      infoBoxTitle: 'Join Node',\n      contextMenuTitle: 'Join',\n      group: ['Text'],\n    };\n  }\n\n  async process(inputs: Inputs): Promise<Outputs> {\n    const joinString = this.data.useJoinStringInput\n      ? coerceTypeOptional(inputs['joinString' as PortId], 'string') ?? this.data.joinString\n      : this.data.joinString;\n\n    const normalizedJoinString = handleEscapeCharacters(joinString);\n\n    const inputKeys = Object.keys(inputs).filter((key) => key.startsWith('input'));\n\n    const inputValueStrings: string[] = [];\n\n    for (let i = 1; i <= inputKeys.length; i++) {\n      const inputValue = inputs[`input${i}` as PortId];\n      if (isArrayDataValue(inputValue) && this.data.flatten) {\n        for (const value of inputValue.value) {\n          inputValueStrings.push(coerceType(inferType(value), 'string'));\n        }\n      } else if (inputValue) {\n        inputValueStrings.push(coerceType(inputValue, 'string'));\n      }\n    }\n\n    const outputValue = inputValueStrings.join(normalizedJoinString);\n\n    return {\n      ['output' as PortId]: {\n        type: 'string',\n        value: outputValue,\n      },\n    };\n  }\n}\n\nexport const joinNode = nodeDefinition(JoinNodeImpl, 'Coalesce');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type DataValue } from '../../index.js';\nimport { zip } from 'lodash-es';\nimport { dedent } from 'ts-dedent';\nimport { coerceType } from '../../utils/coerceType.js';\n\nexport type FilterNode = ChartNode<'filter', FilterNodeData>;\n\nexport type FilterNodeData = {};\n\nexport class FilterNodeImpl extends NodeImpl<FilterNode> {\n  static create(): FilterNode {\n    const chartNode: FilterNode = {\n      type: 'filter',\n      title: 'Filter',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 175,\n      },\n      data: {},\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    return [\n      {\n        id: 'array' as PortId,\n        title: 'Array',\n        dataType: 'any[]',\n        required: true,\n      },\n      {\n        id: 'include' as PortId,\n        title: 'Include',\n        dataType: 'boolean[]',\n        required: true,\n      },\n    ];\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'filtered' as PortId,\n        title: 'Filtered',\n        dataType: 'any[]',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Takes in both an array of values, and an array of booleans of the same length, and filters the array where the corresponding boolean is true.\n      `,\n      infoBoxTitle: 'Filter Node',\n      contextMenuTitle: 'Filter',\n      group: ['Lists'],\n    };\n  }\n\n  async process(inputs: Inputs): Promise<Outputs> {\n    const array = coerceType(inputs['array' as PortId], 'any[]');\n    const include = coerceType(inputs['include' as PortId], 'boolean[]');\n\n    const zipped = zip(array, include);\n\n    const filtered = zipped.filter(([_, include]) => include).map(([value, _]) => value);\n\n    return {\n      ['filtered' as PortId]: {\n        type: inputs['array' as PortId]?.type ?? 'any',\n        value: filtered,\n      } as DataValue,\n    };\n  }\n}\n\nexport const filterNode = nodeDefinition(FilterNodeImpl, 'Filter');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type DataValue } from '../DataValue.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport type { InternalProcessContext } from '../ProcessContext.js';\nimport { resolveExpressionRawValue, unwrapPotentialDataValue } from '../../utils/interpolation.js';\n\nexport type ObjectNode = ChartNode<'object', ObjectNodeData>;\n\nexport type ObjectNodeData = {\n  jsonTemplate: string;\n};\n\nconst DEFAULT_JSON_TEMPLATE = `{\n  \"key\": \"{{input}}\"\n}`;\n\nexport class ObjectNodeImpl extends NodeImpl<ObjectNode> {\n  static create(): ObjectNode {\n    const chartNode: ObjectNode = {\n      type: 'object',\n      title: 'Object',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 200,\n      },\n      data: {\n        jsonTemplate: DEFAULT_JSON_TEMPLATE,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    // Provide default empty string for jsonTemplate if undefined\n    const jsonTemplate = this.chartNode.data.jsonTemplate ?? '';\n    const matches = jsonTemplate.match(/\\{\\{([^}]+?)\\}\\}/g); // matches is string[] | null\n    const allTokens = matches ?? []; // allTokens is now explicitly string[]\n    const inputTokens = allTokens\n      // id and title should not have the {{ and }}\n      .map((token) => token.slice(2, -2).trim())\n      .filter((tokenContent) => !tokenContent.startsWith('@graphInputs.') && !tokenContent.startsWith('@context.'))\n      .filter((token) => token !== '');\n\n    return [...new Set(inputTokens)].map((inputName) => {\n      return {\n        id: inputName as PortId,\n        title: inputName,\n        dataType: 'any',\n        required: false,\n      };\n    });\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        dataType: ['object', 'object[]'],\n        id: 'output' as PortId,\n        title: 'Output',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<ObjectNode>[] {\n    return [\n      {\n        type: 'custom',\n        customEditorId: 'ObjectNodeAiAssist',\n        label: 'AI Assist',\n      },\n      {\n        type: 'code',\n        label: 'JSON Template',\n        dataKey: 'jsonTemplate',\n        language: 'json',\n        theme: 'prompt-interpolation',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Creates an object from input values and a JSON template, escaping the input values and inserting them into the template.\n\n        Use double-quotes around the input values to escape them. String values are automatically escaped.\n\n        Useful for creating objects from multiple inputs.\n      `,\n      infoBoxTitle: 'Object Node',\n      contextMenuTitle: 'Object',\n      group: ['Objects'],\n    };\n  }\n\n  interpolate(\n    baseString: string,\n    values: Record<string, any>,\n    graphInputNodeValues?: Record<string, DataValue>,\n    contextValues?: Record<string, DataValue>\n  ): string {\n    return baseString.replace(/(\"?)\\{\\{([^}]+?)\\}\\}(\"?)/g, (_m, openQuote, key, _closeQuote) => {\n      const isQuoted = Boolean(openQuote);\n      const trimmedKey = key.trim(); // Use trimmedKey for lookups\n\n      let value: any;\n\n      const graphInputPrefix = '@graphInputs.';\n      const contextPrefix = '@context.';\n\n      if (trimmedKey.startsWith(graphInputPrefix) && graphInputNodeValues) {\n        value = resolveExpressionRawValue(\n          graphInputNodeValues,\n          trimmedKey.substring(graphInputPrefix.length),\n          'graphInputs'\n        );\n      } else if (trimmedKey.startsWith(contextPrefix) && contextValues) {\n        value = resolveExpressionRawValue(\n          contextValues,\n          trimmedKey.substring(contextPrefix.length),\n          'context'\n        );\n      } else {\n        value = values[trimmedKey]; // Original logic for non-@ variables\n      }\n\n      if (value == null) {\n        return 'null';\n      }\n      if (isQuoted && typeof value === 'string') {\n        // Adds double-quotes back.\n        return JSON.stringify(value);\n      }\n      if (isQuoted) {\n        // Non-strings require a double-stringify, first to turn them into a string, then to escape that string and add quotes.\n        return JSON.stringify(JSON.stringify(value));\n      }\n      // Otherwise, it was not quoted, so no need to double-stringify\n      return JSON.stringify(value);\n    });\n  }\n\n  async process(inputs: Record<string, DataValue>, context: InternalProcessContext): Promise<Record<string, DataValue>> {\n    const inputMap = Object.keys(inputs).reduce(\n      (acc, key) => {\n        acc[key] = unwrapPotentialDataValue(inputs[key]);\n        return acc;\n      },\n      {} as Record<string, any>,\n    );\n\n    const interpolatedString = this.interpolate(\n      this.chartNode.data.jsonTemplate,\n      inputMap,\n      context.graphInputNodeValues, // Pass graph inputs\n      context.contextValues // Pass context values\n    );\n\n    let outputValue: Record<string, unknown> | unknown[];\n\n    try {\n      outputValue = JSON.parse(interpolatedString) as Record<string, unknown> | unknown[];\n    } catch (err) {\n      throw new Error(`Failed to parse JSON template: ${(err as Error).message}`);\n    }\n\n    const outputType = Array.isArray(outputValue) ? 'object[]' : 'object';\n\n    return {\n      output: {\n        type: outputType,\n        value: outputValue,\n      } as DataValue,\n    };\n  }\n}\n\nexport const objectNode = nodeDefinition(ObjectNodeImpl, 'Object');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type EditorDefinition } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { coerceTypeOptional } from '../../utils/coerceType.js';\n\nexport type BooleanNode = ChartNode<'boolean', BooleanNodeData>;\n\nexport type BooleanNodeData = {\n  value?: boolean;\n  useValueInput?: boolean;\n};\n\nexport class BooleanNodeImpl extends NodeImpl<BooleanNode> {\n  static create(): BooleanNode {\n    const chartNode: BooleanNode = {\n      type: 'boolean',\n      title: 'Bool',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 130,\n      },\n      data: {\n        value: false,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    return this.data.useValueInput\n      ? [\n          {\n            dataType: 'any',\n            id: 'input' as PortId,\n            title: 'Input',\n          },\n        ]\n      : [];\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        dataType: 'boolean',\n        id: 'value' as PortId,\n        title: 'Value',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<BooleanNode>[] {\n    return [{ type: 'toggle', label: 'Value', dataKey: 'value', useInputToggleDataKey: 'useValueInput' }];\n  }\n\n  getBody(): string | undefined {\n    return this.data.useValueInput ? `(Input to bool)` : (this.data.value ?? false).toString();\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Outputs a boolean constant, or converts an input value into a boolean.\n      `,\n      infoBoxTitle: 'Bool Node',\n      contextMenuTitle: 'Bool',\n      group: ['Data'],\n    };\n  }\n\n  async process(inputs: Inputs): Promise<Outputs> {\n    const value = this.data.useValueInput\n      ? coerceTypeOptional(inputs['input' as PortId], 'boolean') ?? this.data.value ?? false\n      : this.data.value ?? false;\n\n    return {\n      ['value' as PortId]: {\n        type: 'boolean',\n        value,\n      },\n    };\n  }\n}\n\nexport const booleanNode = nodeDefinition(BooleanNodeImpl, 'Boolean');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type EditorDefinition } from '../../index.js';\nimport { isEqual } from 'lodash-es';\nimport { match } from 'ts-pattern';\nimport { dedent } from 'ts-dedent';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { coerceType, coerceTypeOptional } from '../../utils/coerceType.js';\n\nexport type CompareNode = ChartNode<'compare', CompareNodeData>;\n\nexport type CompareNodeData = {\n  comparisonFunction: '==' | '<' | '>' | '<=' | '>=' | '!=' | 'and' | 'or' | 'xor' | 'nand' | 'nor' | 'xnor';\n  useComparisonFunctionInput?: boolean;\n};\n\nexport class CompareNodeImpl extends NodeImpl<CompareNode> {\n  static create(): CompareNode {\n    const chartNode: CompareNode = {\n      type: 'compare',\n      title: 'Compare',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 160,\n      },\n      data: {\n        comparisonFunction: '==',\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [\n      {\n        dataType: 'any',\n        id: 'a' as PortId,\n        title: 'A',\n      },\n      {\n        dataType: 'any',\n        id: 'b' as PortId,\n        title: 'B',\n      },\n    ];\n\n    if (this.data.useComparisonFunctionInput) {\n      inputs.push({\n        dataType: 'string',\n        id: 'comparisonFunction' as PortId,\n        title: 'Comparison Function',\n      });\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        dataType: 'boolean',\n        id: 'output' as PortId,\n        title: 'Output',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<CompareNode>[] {\n    return [\n      {\n        type: 'dropdown',\n        label: 'Comparison Function',\n        dataKey: 'comparisonFunction',\n        options: [\n          { label: '==', value: '==' },\n          { label: '!=', value: '!=' },\n          { label: '<', value: '<' },\n          { label: '<=', value: '<=' },\n          { label: '>', value: '>' },\n          { label: '>=', value: '>=' },\n          { label: 'and', value: 'and' },\n          { label: 'or', value: 'or' },\n          { label: 'xor', value: 'xor' },\n          { label: 'nand', value: 'nand' },\n          { label: 'nor', value: 'nor' },\n          { label: 'xnor', value: 'xnor' },\n        ],\n        useInputToggleDataKey: 'useComparisonFunctionInput',\n      },\n    ];\n  }\n\n  getBody(): string | undefined {\n    return this.data.useComparisonFunctionInput ? 'A (Comparison Function) B' : `A ${this.data.comparisonFunction} B`;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Compares two values using the configured operator and outputs the result.\n\n        If the data types of the values do not match, then the B value is converted to the type of the A value.\n      `,\n      infoBoxTitle: 'Compare Node',\n      contextMenuTitle: 'Compare',\n      group: ['Logic'],\n    };\n  }\n\n  async process(inputs: Inputs): Promise<Outputs> {\n    const comparisonFunction = (\n      this.data.useComparisonFunctionInput\n        ? coerceType(inputs['comparisonFunction' as PortId], 'string')\n        : this.data.comparisonFunction\n    ) as CompareNodeData['comparisonFunction'];\n\n    const inputA = inputs['a' as PortId];\n    const inputB = inputs['b' as PortId];\n\n    if (!inputA) {\n      return {\n        ['output' as PortId]: {\n          type: 'boolean',\n          value: match(comparisonFunction)\n            .with('==', () => !inputB)\n            .with('!=', () => !!inputB)\n            .otherwise(() => false),\n        },\n      };\n    }\n\n    const value1 = inputA.value;\n    const value2 = inputB?.type !== inputA.type ? coerceTypeOptional(inputB, inputA.type) : inputB.value;\n\n    return {\n      ['output' as PortId]: {\n        type: 'boolean',\n        value: match(comparisonFunction)\n          .with('==', () => isEqual(value1, value2))\n          .with('!=', () => !isEqual(value1, value2))\n          .with('<', () => (value1 as any) < (value2 as any))\n          .with('>', () => (value1 as any) > (value2 as any))\n          .with('<=', () => (value1 as any) <= (value2 as any))\n          .with('>=', () => (value1 as any) >= (value2 as any))\n          .with('and', () => !!(value1 && value2))\n          .with('or', () => !!(value1 || value2))\n          .with('xor', () => !!(value1 ? !value2 : value2))\n          .with('nand', () => !(value1 && value2))\n          .with('nor', () => !(value1 || value2))\n          .with('xnor', () => !(value1 ? !value2 : value2))\n          .exhaustive(),\n      },\n    };\n  }\n}\n\nexport const compareNode = nodeDefinition(CompareNodeImpl, 'Compare');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type EditorDefinition } from '../../index.js';\nimport { match } from 'ts-pattern';\nimport { dedent } from 'ts-dedent';\nimport { coerceType, coerceTypeOptional } from '../../utils/coerceType.js';\n\nexport type EvaluateNode = ChartNode<'evaluate', EvaluateNodeData>;\n\nexport type EvaluateNodeData = {\n  operation: '+' | '-' | '*' | '/' | '^' | '%' | 'abs' | 'negate';\n  useOperationInput?: boolean;\n};\n\nconst unaryOperation = ['abs', 'negate'] as const;\ntype Unary = (typeof unaryOperation)[number];\nconst isUnaryOp = (operation: string): operation is Unary => unaryOperation.includes(operation as Unary);\n\nexport class EvaluateNodeImpl extends NodeImpl<EvaluateNode> {\n  static create(): EvaluateNode {\n    const chartNode: EvaluateNode = {\n      type: 'evaluate',\n      title: 'Evaluate',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 175,\n      },\n      data: {\n        operation: '+',\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [\n      {\n        dataType: 'number',\n        id: 'a' as PortId,\n        title: 'A',\n      },\n    ];\n\n    const isUnary = !this.data.useOperationInput && isUnaryOp(this.data.operation);\n\n    if (!isUnary) {\n      inputs.push({\n        dataType: 'number',\n        id: 'b' as PortId,\n        title: 'B',\n      });\n    }\n\n    if (this.data.useOperationInput) {\n      inputs.push({\n        dataType: 'string',\n        id: 'operation' as PortId,\n        title: 'Operation',\n      });\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        dataType: 'number',\n        id: 'output' as PortId,\n        title: 'Output',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<EvaluateNode>[] {\n    return [\n      {\n        type: 'dropdown',\n        label: 'Operation',\n        dataKey: 'operation',\n        options: [\n          { label: '+', value: '+' },\n          { label: '-', value: '-' },\n          { label: '*', value: '*' },\n          { label: '/', value: '/' },\n          { label: '^', value: '^' },\n          { label: '%', value: '%' },\n          { label: 'abs', value: 'abs' },\n          { label: 'negate', value: 'negate' },\n        ],\n        useInputToggleDataKey: 'useOperationInput',\n      },\n    ];\n  }\n\n  getBody(): string | undefined {\n    const isUnary = !this.data.useOperationInput && isUnaryOp(this.data.operation);\n\n    if (isUnary) {\n      return match(this.data.operation as Unary)\n        .with('abs', () => 'abs(A)')\n        .with('negate', () => '-A')\n        .exhaustive();\n    }\n\n    if (this.data.operation === '^') {\n      return '!markdownA<sup>B</sup>';\n    }\n\n    return this.data.useOperationInput ? 'A (Operation) B' : `A ${this.data.operation} B`;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Evaluates the configured mathematical operation on the input values and outputs the result.\n\n        For more complex operations, you should use the \\`Code\\` node.\n      `,\n      infoBoxTitle: 'Evaluate Node',\n      contextMenuTitle: 'Evaluate',\n      group: ['Numbers'],\n    };\n  }\n\n  async process(inputs: Inputs): Promise<Outputs> {\n    const operation = (\n      this.data.useOperationInput ? coerceType(inputs['operation' as PortId], 'string') : this.data.operation\n    ) as EvaluateNodeData['operation'];\n\n    const inputA = coerceTypeOptional(inputs['a' as PortId], 'number');\n    const inputB = coerceTypeOptional(inputs['b' as PortId], 'number');\n\n    if (isUnaryOp(operation) && inputA) {\n      return {\n        ['output' as PortId]: {\n          type: 'number',\n          value: match(operation as Extract<EvaluateNodeData['operation'], Unary>)\n            .with('abs', () => Math.abs(inputA))\n            .with('negate', () => -inputA)\n            .exhaustive(),\n        },\n      };\n    }\n\n    if (inputA == null || inputB == null) {\n      throw new Error('Missing input');\n    }\n\n    return {\n      ['output' as PortId]: {\n        type: 'number',\n        value: match(operation as Exclude<EvaluateNodeData['operation'], Unary>)\n          .with('+', () => inputA + inputB)\n          .with('-', () => inputA - inputB)\n          .with('*', () => inputA * inputB)\n          .with('/', () => inputA / inputB)\n          .with('^', () => Math.pow(inputA, inputB))\n          .with('%', () => inputA % inputB)\n          .exhaustive(),\n      },\n    };\n  }\n}\n\nexport const evaluateNode = nodeDefinition(EvaluateNodeImpl, 'Evaluate');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type EditorDefinition } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { coerceTypeOptional } from '../../utils/coerceType.js';\n\nexport type NumberNode = ChartNode<'number', NumberNodeData>;\n\nexport type NumberNodeData = {\n  value?: number;\n  useValueInput?: boolean;\n  round?: boolean;\n  roundTo?: number;\n};\n\nexport class NumberNodeImpl extends NodeImpl<NumberNode> {\n  static create(): NumberNode {\n    const chartNode: NumberNode = {\n      type: 'number',\n      title: 'Number',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 200,\n      },\n      data: {\n        value: 0,\n        round: false,\n        roundTo: 0,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    return this.data.useValueInput\n      ? [\n          {\n            dataType: 'any',\n            id: 'input' as PortId,\n            title: 'Input',\n          },\n        ]\n      : [];\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        dataType: 'number',\n        id: 'value' as PortId,\n        title: 'Value',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<NumberNode>[] {\n    return [\n      { type: 'number', label: 'Value', dataKey: 'value', useInputToggleDataKey: 'useValueInput' },\n      { type: 'toggle', label: 'Round', dataKey: 'round' },\n      { type: 'number', label: 'Round To', dataKey: 'roundTo' },\n    ];\n  }\n\n  getBody(): string | undefined {\n    return this.data.useValueInput ? `(Input to number)` : (this.data.value ?? 0).toLocaleString();\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Outputs a number constant, or converts an input value into a number.\n\n        Can be configured to round the number to a certain number of decimal places.\n      `,\n      infoBoxTitle: 'Number Node',\n      contextMenuTitle: 'Number',\n      group: ['Numbers'],\n    };\n  }\n\n  async process(inputs: Inputs): Promise<Outputs> {\n    let value = this.data.useValueInput\n      ? coerceTypeOptional(inputs['input' as PortId], 'number') ?? this.data.value ?? 0\n      : this.data.value ?? 0;\n\n    const { roundTo = 0, round = false } = this.data;\n\n    if (round) {\n      value = Math.round(value * Math.pow(10, roundTo)) / Math.pow(10, roundTo);\n    }\n\n    return {\n      ['value' as PortId]: {\n        type: 'number',\n        value,\n      },\n    };\n  }\n}\n\nexport const numberNode = nodeDefinition(NumberNodeImpl, 'Number');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type EditorDefinition } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { coerceTypeOptional } from '../../utils/coerceType.js';\n\nexport type RandomNumberNode = ChartNode<'randomNumber', RandomNumberNodeData>;\n\nexport type RandomNumberNodeData = {\n  min?: number;\n  max?: number;\n  integers?: boolean;\n  maxInclusive?: boolean;\n  useMinInput?: boolean;\n  useMaxInput?: boolean;\n};\n\nexport class RandomNumberNodeImpl extends NodeImpl<RandomNumberNode> {\n  static create(): RandomNumberNode {\n    const chartNode: RandomNumberNode = {\n      type: 'randomNumber',\n      title: 'RNG',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 150,\n      },\n      data: {\n        min: 0,\n        max: 1,\n        integers: false,\n        maxInclusive: false,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [];\n    if (this.data.useMinInput) {\n      inputs.push({\n        dataType: 'number',\n        id: 'min' as PortId,\n        title: 'Min',\n      });\n    }\n    if (this.data.useMaxInput) {\n      inputs.push({\n        dataType: 'number',\n        id: 'max' as PortId,\n        title: 'Max',\n      });\n    }\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        dataType: 'number',\n        id: 'value' as PortId,\n        title: 'Value',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<RandomNumberNode>[] {\n    return [\n      { type: 'number', label: 'Min', dataKey: 'min', useInputToggleDataKey: 'useMinInput' },\n      { type: 'number', label: 'Max', dataKey: 'max', useInputToggleDataKey: 'useMaxInput' },\n      { type: 'toggle', label: 'Integers', dataKey: 'integers' },\n      { type: 'toggle', label: 'Max Inclusive', dataKey: 'maxInclusive' },\n    ];\n  }\n\n  getBody(): string | undefined {\n    return dedent`\n      Min: ${this.data.useMinInput ? '(Input)' : this.data.min ?? 0}\n      Max: ${this.data.useMaxInput ? '(Input)' : this.data.max ?? 1}\n      ${this.data.integers ? 'Integers' : 'Floats'}\n      ${this.data.maxInclusive ? 'Max Inclusive' : 'Max Exclusive'}\n    `;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Outputs a random number between the configured min and max values.\n\n        Can be configured to output only integers, and whether the max value is inclusive or exclusive.\n      `,\n      infoBoxTitle: 'RNG Node',\n      contextMenuTitle: 'RNG',\n      group: ['Numbers'],\n    };\n  }\n\n  async process(inputs: Inputs): Promise<Outputs> {\n    const min = this.data.useMinInput\n      ? coerceTypeOptional(inputs['min' as PortId], 'number') ?? this.data.min ?? 0\n      : this.data.min ?? 0;\n\n    let max = this.data.useMaxInput\n      ? coerceTypeOptional(inputs['max' as PortId], 'number') ?? this.data.max ?? 1\n      : this.data.max ?? 1;\n\n    if (this.data.integers && this.data.maxInclusive) {\n      max += 1;\n    }\n    let value = Math.random() * (max - min) + min;\n\n    if (this.data.integers) {\n      value = Math.floor(value);\n    }\n\n    return {\n      ['value' as PortId]: {\n        type: 'number',\n        value,\n      },\n    };\n  }\n}\n\nexport const randomNumberNode = nodeDefinition(RandomNumberNodeImpl, 'Random Number');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { shuffle } from 'lodash-es';\nimport { type DataValue, isArrayDataValue } from '../DataValue.js';\nimport { dedent } from 'ts-dedent';\n\nexport type ShuffleNode = ChartNode<'shuffle'>;\n\nexport class ShuffleNodeImpl extends NodeImpl<ShuffleNode> {\n  static create(): ShuffleNode {\n    const chartNode: ShuffleNode = {\n      type: 'shuffle',\n      title: 'Shuffle',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 175,\n      },\n      data: {},\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    return [\n      {\n        dataType: 'any[]',\n        id: 'array' as PortId,\n        title: 'Array',\n      },\n    ];\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        dataType: 'any[]',\n        id: 'shuffled' as PortId,\n        title: 'Shuffled',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Shuffles the input array. Outputs the shuffled array.\n      `,\n      infoBoxTitle: 'Shuffle Node',\n      contextMenuTitle: 'Shuffle',\n      group: ['Lists'],\n    };\n  }\n\n  async process(inputs: Inputs): Promise<Outputs> {\n    const input = inputs['array' as PortId];\n\n    const items = input ? (isArrayDataValue(input) ? input.value : [input.value]) : [];\n\n    const shuffled = shuffle(items);\n\n    return {\n      ['shuffled' as PortId]: {\n        type: inputs['array' as PortId]?.type ?? 'any[]',\n        value: shuffled,\n      } as DataValue,\n    };\n  }\n}\n\nexport const shuffleNode = nodeDefinition(ShuffleNodeImpl, 'Shuffle');\n", "import { type ChartNode, type NodeId, type NodeInputDefinition, type NodeOutputDefinition } from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { type DataValue } from '../DataValue.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\n\nexport type CommentNode = ChartNode<'comment', CommentNodeData>;\n\nexport type CommentNodeData = {\n  text: string;\n  color?: string;\n  backgroundColor?: string;\n  height: number;\n};\n\nexport class CommentNodeImpl extends NodeImpl<CommentNode> {\n  static create(): CommentNode {\n    const chartNode: CommentNode = {\n      type: 'comment',\n      title: 'Comment',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 600,\n      },\n      data: {\n        text: '',\n        height: 600,\n        color: 'rgba(255,255,255,1)',\n        backgroundColor: 'rgba(0,0,0,0.05)',\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    return [];\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [];\n  }\n\n  getEditors(): EditorDefinition<CommentNode>[] {\n    return [\n      {\n        type: 'color',\n        label: 'Color',\n        dataKey: 'color',\n      },\n      {\n        type: 'color',\n        label: 'Background Color',\n        dataKey: 'backgroundColor',\n      },\n      {\n        type: 'code',\n        label: 'Text',\n        dataKey: 'text',\n        language: 'markdown',\n        theme: 'vs-dark',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        A comment node is a node that does nothing. It is useful for adding notes to a graph.\n      `,\n      infoBoxTitle: 'Comment Node',\n      contextMenuTitle: 'Comment',\n      group: ['Advanced'],\n    };\n  }\n\n  async process(): Promise<Record<string, DataValue>> {\n    return {};\n  }\n}\n\nexport const commentNode = nodeDefinition(CommentNodeImpl, 'Comment');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type PortId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport {\n  type DataRef,\n  type EditorDefinition,\n  type Inputs,\n  type InternalProcessContext,\n  type Outputs,\n} from '../../index.js';\nimport { base64ToUint8Array } from '../../utils/base64.js';\nimport { expectType } from '../../utils/expectType.js';\n\nexport type ImageNode = ChartNode<'image', ImageNodeData>;\n\ntype ImageNodeData = {\n  data?: DataRef;\n  useDataInput: boolean;\n  mediaType: 'image/png' | 'image/jpeg' | 'image/gif';\n  useMediaTypeInput: boolean;\n};\n\nexport class ImageNodeImpl extends NodeImpl<ImageNode> {\n  static create(): ImageNode {\n    return {\n      id: nanoid() as NodeId,\n      type: 'image',\n      title: 'Image',\n      visualData: { x: 0, y: 0, width: 250 },\n      data: {\n        useDataInput: false,\n        mediaType: 'image/png',\n        useMediaTypeInput: false,\n      },\n    };\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputDefinitions: NodeInputDefinition[] = [];\n\n    if (this.chartNode.data.useDataInput) {\n      inputDefinitions.push({\n        id: 'data' as PortId,\n        title: 'Data',\n        dataType: 'binary',\n        coerced: false,\n      });\n    }\n\n    if (this.chartNode.data.useMediaTypeInput) {\n      inputDefinitions.push({\n        id: 'mediaType' as PortId,\n        title: 'Media Type',\n        dataType: 'string',\n      });\n    }\n\n    return inputDefinitions;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'image' as PortId,\n        title: 'Image',\n        dataType: 'image',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<ImageNode>[] {\n    return [\n      {\n        type: 'dropdown',\n        label: 'Media Type',\n        dataKey: 'mediaType',\n        options: [\n          { value: 'image/png', label: 'PNG' },\n          { value: 'image/jpeg', label: 'JPEG' },\n          { value: 'image/gif', label: 'GIF' },\n        ],\n        useInputToggleDataKey: 'useMediaTypeInput',\n      },\n      {\n        type: 'imageBrowser',\n        label: 'Image',\n        dataKey: 'data',\n        useInputToggleDataKey: 'useDataInput',\n        mediaTypeDataKey: 'mediaType',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      contextMenuTitle: 'Image',\n      group: 'Data',\n      infoBoxTitle: 'Image Node',\n      infoBoxBody: 'Defines a static image for use with other nodes. Can convert a binary type into an image type.',\n    };\n  }\n\n  async process(inputData: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    let data: Uint8Array;\n\n    if (this.chartNode.data.useDataInput) {\n      data = expectType(inputData['data' as PortId], 'binary');\n    } else {\n      const dataRef = this.data.data?.refId;\n      if (!dataRef) {\n        throw new Error('No data ref');\n      }\n\n      const encodedData = context.project.data?.[dataRef] as string;\n\n      if (!encodedData) {\n        throw new Error(`No data at ref ${dataRef}`);\n      }\n\n      data = base64ToUint8Array(encodedData);\n    }\n\n    const mediaType = this.chartNode.data.useMediaTypeInput\n      ? expectType(inputData['mediaType' as PortId], 'string')\n      : this.chartNode.data.mediaType;\n\n    return {\n      ['image' as PortId]: {\n        type: 'image',\n        value: { mediaType: mediaType as 'image/png' | 'image/jpeg' | 'image/gif', data },\n      },\n    };\n  }\n}\n\nexport const imageNode = nodeDefinition(ImageNodeImpl, 'Image');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type PortId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport {\n  type DataRef,\n  type EditorDefinition,\n  type Inputs,\n  type InternalProcessContext,\n  type Outputs,\n} from '../../index.js';\nimport { base64ToUint8Array, expectType } from '../../utils/index.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { getInputOrData } from '../../utils/inputs.js';\n\nexport type AudioNode = ChartNode<'audio', AudioNodeData>;\n\ntype AudioNodeData = {\n  data?: DataRef;\n  useDataInput: boolean;\n\n  mediaType?: 'audio/wav' | 'audio/mp3' | 'audio/ogg';\n  useMediaTypeInput: boolean;\n};\n\nexport class AudioNodeImpl extends NodeImpl<AudioNode> {\n  static create(): AudioNode {\n    return {\n      id: nanoid() as NodeId,\n      type: 'audio',\n      title: 'Audio',\n      visualData: { x: 0, y: 0, width: 300 },\n      data: {\n        useDataInput: false,\n        useMediaTypeInput: false,\n      },\n    };\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputDefinitions: NodeInputDefinition[] = [];\n\n    if (this.chartNode.data.useDataInput) {\n      inputDefinitions.push({\n        id: 'data' as PortId,\n        title: 'Data',\n        dataType: 'string',\n        coerced: false,\n      });\n    }\n\n    if (this.chartNode.data.useMediaTypeInput) {\n      inputDefinitions.push({\n        id: 'mediaType' as PortId,\n        title: 'Media Type',\n        dataType: 'string',\n        coerced: false,\n      });\n    }\n\n    return inputDefinitions;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'data' as PortId,\n        title: 'Audio Data',\n        dataType: 'audio',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<AudioNode>[] {\n    return [\n      {\n        type: 'fileBrowser',\n        label: 'Audio File',\n        dataKey: 'data',\n        mediaTypeDataKey: 'mediaType',\n        useInputToggleDataKey: 'useDataInput',\n        accept: 'audio/*',\n      },\n      {\n        type: 'string',\n        label: 'Media Type',\n        dataKey: 'mediaType',\n        useInputToggleDataKey: 'useMediaTypeInput',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      contextMenuTitle: 'Audio',\n      group: 'Data',\n      infoBoxTitle: 'Audio Node',\n      infoBoxBody: 'Defines an audio sample for use with other nodes. Can convert a binary type into an audio type.',\n    };\n  }\n\n  async process(inputData: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    let data: Uint8Array;\n\n    const mediaType = getInputOrData(this.data, inputData, 'mediaType', 'string') || 'audio/wav';\n\n    if (this.chartNode.data.useDataInput) {\n      data = expectType(inputData['data' as PortId], 'binary');\n    } else {\n      const dataRef = this.data.data?.refId;\n      if (!dataRef) {\n        throw new Error('No data ref');\n      }\n\n      const encodedData = context.project.data?.[dataRef] as string;\n\n      if (!encodedData) {\n        throw new Error(`No data at ref ${dataRef}`);\n      }\n\n      data = base64ToUint8Array(encodedData);\n    }\n\n    return {\n      ['data' as PortId]: {\n        type: 'audio',\n        value: { data, mediaType },\n      },\n    };\n  }\n}\n\nexport const audioNode = nodeDefinition(AudioNodeImpl, 'Audio');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type EditorDefinition, type InternalProcessContext } from '../../index.js';\nimport { coerceType, dedent, getInputOrData } from '../../utils/index.js';\nimport { getError } from '../../utils/errors.js';\n\nexport type HttpCallNode = ChartNode<'httpCall', HttpCallNodeData>;\n\nexport type HttpCallNodeData = {\n  method: 'GET' | 'POST' | 'PUT' | 'DELETE';\n  useMethodInput?: boolean;\n\n  url: string;\n  useUrlInput?: boolean;\n\n  headers: string;\n  useHeadersInput?: boolean;\n\n  body: string;\n  useBodyInput?: boolean;\n\n  isBinaryOutput?: boolean;\n\n  errorOnNon200?: boolean;\n};\n\nexport class HttpCallNodeImpl extends NodeImpl<HttpCallNode> {\n  static create(): HttpCallNode {\n    const chartNode: HttpCallNode = {\n      type: 'httpCall',\n      title: 'Http Call',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 250,\n      },\n      data: {\n        method: 'GET',\n        url: '',\n        headers: '',\n        body: '',\n        errorOnNon200: true,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [];\n\n    if (this.data.useMethodInput) {\n      inputs.push({\n        dataType: 'string',\n        id: 'method' as PortId,\n        title: 'Method',\n      });\n    }\n\n    if (this.data.useUrlInput) {\n      inputs.push({\n        dataType: 'string',\n        id: 'url' as PortId,\n        title: 'URL',\n      });\n    }\n\n    if (this.data.useHeadersInput) {\n      inputs.push({\n        dataType: 'object',\n        id: 'headers' as PortId,\n        title: 'Headers',\n      });\n    }\n\n    if (this.data.useBodyInput) {\n      inputs.push({\n        dataType: 'string',\n        id: 'req_body' as PortId,\n        title: 'Body',\n      });\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    const outputDefinitions: NodeOutputDefinition[] = [];\n    if (this.data.isBinaryOutput) {\n      outputDefinitions.push({\n        dataType: 'binary',\n        id: 'binary' as PortId,\n        title: 'Binary',\n      });\n    } else {\n      outputDefinitions.push(\n        {\n          dataType: 'string',\n          id: 'res_body' as PortId,\n          title: 'Body',\n        },\n        {\n          dataType: 'object',\n          id: 'json' as PortId,\n          title: 'JSON',\n        },\n      );\n    }\n\n    outputDefinitions.push(\n      {\n        dataType: 'number',\n        id: 'statusCode' as PortId,\n        title: 'Status Code',\n      },\n      {\n        dataType: 'object',\n        id: 'res_headers' as PortId,\n        title: 'Headers',\n      },\n    );\n\n    return outputDefinitions;\n  }\n\n  getEditors(): EditorDefinition<HttpCallNode>[] {\n    return [\n      {\n        type: 'dropdown',\n        label: 'Method',\n        dataKey: 'method',\n        useInputToggleDataKey: 'useMethodInput',\n        options: [\n          { label: 'GET', value: 'GET' },\n          { label: 'POST', value: 'POST' },\n          { label: 'PUT', value: 'PUT' },\n          { label: 'DELETE', value: 'DELETE' },\n        ],\n      },\n      {\n        type: 'string',\n        label: 'URL',\n        dataKey: 'url',\n        useInputToggleDataKey: 'useUrlInput',\n      },\n      {\n        type: 'code',\n        label: 'Headers',\n        dataKey: 'headers',\n        useInputToggleDataKey: 'useHeadersInput',\n        language: 'json',\n      },\n      {\n        type: 'code',\n        label: 'Body',\n        dataKey: 'body',\n        useInputToggleDataKey: 'useBodyInput',\n        language: 'json',\n      },\n      {\n        type: 'toggle',\n        label: 'Binary Output',\n        dataKey: 'isBinaryOutput',\n        helperMessage: 'Toggle on if the response is expected to be binary data',\n      },\n      {\n        type: 'toggle',\n        label: 'Error on non-200 status code',\n        dataKey: 'errorOnNon200',\n      },\n    ];\n  }\n\n  getBody(): string {\n    return dedent`\n      ${this.data.useMethodInput ? '(Method Using Input)' : this.data.method} ${\n        this.data.useUrlInput ? '(URL Using Input)' : this.data.url\n      } ${\n        this.data.useHeadersInput\n          ? '\\nHeaders: (Using Input)'\n          : this.data.headers.trim()\n            ? `\\nHeaders: ${this.data.headers}`\n            : ''\n      }${this.data.useBodyInput ? '\\nBody: (Using Input)' : this.data.body.trim() ? `\\nBody: ${this.data.body}` : ''}${\n        this.data.errorOnNon200 ? '\\nError on non-200' : ''\n      }\n    `;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Makes an HTTP call to the specified URL with the given method, headers, and body.\n      `,\n      infoBoxTitle: 'HTTP Call Node',\n      contextMenuTitle: 'HTTP Call',\n      group: ['Advanced'],\n    };\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const method = getInputOrData(this.data, inputs, 'method', 'string');\n    const url = getInputOrData(this.data, inputs, 'url', 'string');\n\n    // TODO: Use URL.canParse when we drop support for Node 18\n    try {\n      new URL(url);\n    } catch (err) {\n      throw new Error(`Invalid URL: ${url}`);\n    }\n\n    let headers: Record<string, string> | undefined;\n    if (this.data.useHeadersInput) {\n      const headersInput = inputs['headers' as PortId];\n      if (headersInput?.type === 'string') {\n        headers = JSON.parse(headersInput!.value);\n      } else if (headersInput?.type === 'object') {\n        headers = headersInput!.value as Record<string, string>;\n      } else {\n        headers = coerceType(headersInput, 'object') as Record<string, string>;\n      }\n    } else if (this.data.headers.trim()) {\n      headers = JSON.parse(this.data.headers);\n    }\n\n    let body: string | undefined;\n    if (this.data.useBodyInput) {\n      const bodyInput = inputs['req_body' as PortId];\n      if (bodyInput?.type === 'string') {\n        body = bodyInput!.value;\n      } else if (bodyInput?.type === 'object') {\n        body = JSON.stringify(bodyInput!.value);\n      } else {\n        body = coerceType(bodyInput, 'string');\n      }\n    } else {\n      body = this.data.body || undefined;\n    }\n\n    try {\n      const response = await fetch(url, {\n        method,\n        headers,\n        body,\n        signal: context.signal,\n        mode: 'cors',\n      });\n\n      const output: Outputs = {\n        ['statusCode' as PortId]: {\n          type: 'number',\n          value: response.status,\n        },\n        ['res_headers' as PortId]: {\n          type: 'object',\n          value: Object.fromEntries(response.headers.entries()),\n        },\n      };\n\n      if (this.data.isBinaryOutput) {\n        const responseBlob = await response.blob();\n        output['binary' as PortId] = {\n          type: 'binary',\n          value: new Uint8Array(await responseBlob.arrayBuffer()),\n        };\n      } else {\n        const responseText = await response.text();\n        output['res_body' as PortId] = {\n          type: 'string',\n          value: responseText,\n        };\n        if (response.headers.get('content-type')?.includes('application/json')) {\n          const jsonData = JSON.parse(responseText);\n          output['json' as PortId] = {\n            type: 'object',\n            value: jsonData,\n          };\n        } else {\n          output['json' as PortId] = {\n            type: 'control-flow-excluded',\n            value: undefined,\n          };\n        }\n      }\n\n      return output;\n    } catch (err) {\n      const { message } = getError(err);\n      if (message.includes('Load failed') || message.includes('Failed to fetch')) {\n        if (context.executor === 'browser') {\n          throw new Error(\n            'Failed to make HTTP call. You may be running into CORS problems. Try using the Node executor in the top-right menu.',\n          );\n        }\n      }\n\n      throw err;\n    }\n  }\n}\n\nexport const httpCallNode = nodeDefinition(HttpCallNodeImpl, 'Http Call');\n", "import {\n  type ChartNode,\n  type NodeConnection,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type EditorDefinition } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { getInputOrData } from '../../utils/inputs.js';\n\nexport type DelayNode = ChartNode<'delay', DelayNodeData>;\n\nexport type DelayNodeData = {\n  delay: number;\n  useDelayInput?: boolean;\n};\n\nexport class DelayNodeImpl extends NodeImpl<DelayNode> {\n  static create(): DelayNode {\n    const chartNode: DelayNode = {\n      type: 'delay',\n      title: 'Delay',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 175,\n      },\n      data: {\n        delay: 0,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(connections: NodeConnection[]): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [];\n    const inputCount = this.#getInputPortCount(connections);\n\n    if (this.data.useDelayInput) {\n      inputs.push({\n        dataType: 'number',\n        id: 'delay' as PortId,\n        title: 'Delay (ms)',\n      });\n    }\n\n    for (let i = 1; i <= inputCount; i++) {\n      inputs.push({\n        dataType: 'any',\n        id: `input${i}` as PortId,\n        title: `Input ${i}`,\n      });\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(connections: NodeConnection[]): NodeOutputDefinition[] {\n    const outputs: NodeOutputDefinition[] = [];\n    const inputCount = this.#getInputPortCount(connections);\n\n    for (let i = 1; i <= inputCount - 1; i++) {\n      outputs.push({\n        dataType: 'any',\n        id: `output${i}` as PortId,\n        title: `Output ${i}`,\n      });\n    }\n\n    return outputs;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Delays the execution and then passes the input value to the output without any modifications.\n      `,\n      infoBoxTitle: 'Delay Node',\n      contextMenuTitle: 'Delay',\n      group: ['Logic'],\n    };\n  }\n\n  #getInputPortCount(connections: NodeConnection[]): number {\n    const inputNodeId = this.chartNode.id;\n    const inputConnections = connections.filter(\n      (connection) => connection.inputNodeId === inputNodeId && connection.inputId.startsWith('input'),\n    );\n\n    let maxInputNumber = 0;\n    for (const connection of inputConnections) {\n      const messageNumber = parseInt(connection.inputId.replace('input', ''), 10);\n      if (messageNumber > maxInputNumber) {\n        maxInputNumber = messageNumber;\n      }\n    }\n\n    return maxInputNumber + 1;\n  }\n\n  getEditors(): EditorDefinition<DelayNode>[] {\n    return [\n      {\n        type: 'number',\n        label: 'Delay (ms)',\n        dataKey: 'delay',\n        useInputToggleDataKey: 'useDelayInput',\n        defaultValue: 0,\n      },\n    ];\n  }\n\n  getBody(): string | undefined {\n    return `Delay ${this.data.useDelayInput ? '(Input ms)' : `${this.chartNode.data.delay}ms`}`;\n  }\n\n  async process(inputData: Inputs): Promise<Outputs> {\n    const delayAmount = getInputOrData(this.data, inputData, 'delay', 'number');\n\n    await new Promise((resolve) => setTimeout(resolve, delayAmount));\n\n    const inputCount = Object.keys(inputData).filter((key) => key.startsWith('input')).length;\n\n    const outputs: Outputs = {};\n\n    for (let i = 1; i <= inputCount; i++) {\n      const input = inputData[`input${i}` as PortId]!;\n      outputs[`output${i}` as PortId] = input;\n    }\n\n    return outputs;\n  }\n}\n\nexport const delayNode = nodeDefinition(DelayNodeImpl, 'Delay');\n", "import type { ChartNode, NodeId, PortId, NodeInputDefinition, NodeOutputDefinition } from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nanoid } from 'nanoid/non-secure';\n\nimport type { InternalProcessContext } from '../ProcessContext.js';\nimport { dedent } from 'ts-dedent';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { getInputOrData, coerceTypeOptional, newId, coerceType } from '../../utils/index.js';\nimport { arrayizeDataValue, unwrapDataValue } from '../DataValue.js';\nimport type { DatasetId, DatasetRow } from '../Dataset.js';\nimport type { EditorDefinition } from '../EditorDefinition.js';\nimport type { Inputs, Outputs } from '../GraphProcessor.js';\n\nexport type AppendToDatasetNode = ChartNode<'appendToDataset', AppendToDatasetNodeData>;\n\ntype AppendToDatasetNodeData = {\n  datasetId: DatasetId;\n  useDatasetIdInput?: boolean;\n};\n\nexport class AppendToDatasetNodeImpl extends NodeImpl<AppendToDatasetNode> {\n  static create(): AppendToDatasetNode {\n    return {\n      id: nanoid() as NodeId,\n      type: 'appendToDataset',\n      title: 'Append to Dataset',\n      visualData: { x: 0, y: 0, width: 250 },\n      data: {\n        datasetId: '' as DatasetId,\n      },\n    };\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputDefinitions: NodeInputDefinition[] = [];\n\n    inputDefinitions.push({\n      id: 'data' as PortId,\n      dataType: 'string[]',\n      title: 'Data',\n      description:\n        'The data to append to the dataset. May be a string or array of strings. If an array, each element will be a column in the dataset.',\n    });\n\n    inputDefinitions.push({\n      id: 'id' as PortId,\n      dataType: 'string',\n      title: 'ID',\n      description:\n        'The ID of the row to append. If not provided, a random ID will be generated. If an existing ID is provided, the row will be overwritten.',\n    });\n\n    inputDefinitions.push({\n      id: 'embedding' as PortId,\n      dataType: 'vector',\n      title: 'Embedding',\n      description: 'The vector embedding to store with the row.',\n    });\n\n    if (this.data.useDatasetIdInput) {\n      inputDefinitions.push({\n        id: 'datasetId' as PortId,\n        title: 'Dataset ID',\n        dataType: 'string',\n        description: 'The ID of the dataset to append to.',\n      });\n    }\n\n    return inputDefinitions;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'dataset' as PortId,\n        title: 'Dataset',\n        dataType: 'object', // technically string[][]...\n      },\n      {\n        id: 'id_out' as PortId,\n        title: 'ID',\n        dataType: 'string',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Appends a row of data to the specified dataset.\n      `,\n      infoBoxTitle: 'Append to Dataset Node',\n      contextMenuTitle: 'Append to Dataset',\n      group: ['Input/Output'],\n    };\n  }\n\n  getEditors(): EditorDefinition<AppendToDatasetNode>[] | Promise<EditorDefinition<AppendToDatasetNode>[]> {\n    return [\n      {\n        type: 'datasetSelector',\n        label: 'Dataset',\n        dataKey: 'datasetId',\n        useInputToggleDataKey: 'useDatasetIdInput',\n      },\n    ];\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const { datasetProvider } = context;\n\n    if (datasetProvider == null) {\n      throw new Error('datasetProvider is required');\n    }\n\n    const datasetId = getInputOrData(this.data, inputs, 'datasetId', 'string') as DatasetId;\n    const dataId = coerceTypeOptional(inputs['id' as PortId], 'string') || newId<DatasetId>();\n    const embedding = coerceTypeOptional(inputs['embedding' as PortId], 'vector');\n\n    const dataInput = inputs['data' as PortId];\n\n    if (!dataInput) {\n      throw new Error('data input is required');\n    }\n\n    const data = arrayizeDataValue(unwrapDataValue(dataInput));\n    const stringData = data.map((d) => coerceType(d, 'string'));\n\n    const newData: DatasetRow = {\n      id: dataId,\n      data: stringData,\n      embedding,\n    };\n\n    await datasetProvider.putDatasetRow(datasetId, newData);\n\n    return {\n      ['dataset' as PortId]: {\n        type: 'object',\n        value: newData as any,\n      },\n      ['id_out' as PortId]: {\n        type: 'string',\n        value: datasetId,\n      },\n    };\n  }\n}\n\nexport const appendToDatasetNode = nodeDefinition(AppendToDatasetNodeImpl, 'Append To Dataset');\n", "import type {\n  ChartNode,\n  DatasetId,\n  Inputs,\n  InternalProcessContext,\n  NodeId,\n  NodeInputDefinition,\n  NodeOutputDefinition,\n  NodeUIData,\n  Outputs,\n  PortId,\n} from '../../index.js';\nimport { NodeImpl } from '../NodeImpl.js';\nimport { coerceTypeOptional, dedent, newId } from '../../utils/index.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\n\nexport type CreateDatasetNode = ChartNode<'createDataset', CreateDatasetNodeData>;\n\ntype CreateDatasetNodeData = {};\n\nexport class CreateDatasetNodeImpl extends NodeImpl<CreateDatasetNode> {\n  static create(): CreateDatasetNode {\n    return {\n      id: newId<NodeId>(),\n      type: 'createDataset',\n      title: 'Create Dataset',\n      visualData: { x: 0, y: 0, width: 250 },\n      data: {},\n    };\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    return [\n      {\n        id: 'datasetId' as PortId,\n        title: 'Dataset ID',\n        dataType: 'string',\n      },\n      {\n        id: 'datasetName' as PortId,\n        title: 'Dataset Name',\n        dataType: 'string',\n      },\n    ];\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'datasetId_out' as PortId,\n        title: 'Dataset ID',\n        dataType: 'string',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Creates a new dataset with the provided ID and name. If the dataset already exists, it does nothing.\n      `,\n      infoBoxTitle: 'Create Dataset Node',\n      contextMenuTitle: 'Create Dataset',\n      group: ['Input/Output'],\n    };\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const { datasetProvider } = context;\n\n    if (datasetProvider == null) {\n      throw new Error('datasetProvider is required');\n    }\n\n    const datasetId =\n      (coerceTypeOptional(inputs['datasetId' as PortId], 'string') as DatasetId | undefined) || newId<DatasetId>();\n    const datasetName = coerceTypeOptional(inputs['datasetName' as PortId], 'string') || datasetId;\n\n    const existingDataset = await datasetProvider.getDatasetMetadata(datasetId);\n\n    if (!existingDataset) {\n      await datasetProvider.putDatasetMetadata({\n        id: datasetId,\n        name: datasetName,\n        description: '',\n        projectId: context.project.metadata.id,\n      });\n    }\n\n    return {\n      ['datasetId_out' as PortId]: {\n        type: 'string',\n        value: datasetId || datasetName,\n      },\n    };\n  }\n}\n\nexport const createDatasetNode = nodeDefinition(CreateDatasetNodeImpl, 'Create Dataset');\n", "import type {\n  ChartNode,\n  DatasetId,\n  Inputs,\n  InternalProcessContext,\n  NodeId,\n  NodeInputDefinition,\n  NodeOutputDefinition,\n  NodeUIData,\n  Outputs,\n  PortId,\n  EditorDefinition,\n} from '../../index.js';\nimport { NodeImpl } from '../NodeImpl.js';\nimport { coerceTypeOptional, dedent, newId } from '../../utils/index.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\n\nexport type LoadDatasetNode = ChartNode<'loadDataset', LoadDatasetNodeData>;\n\ntype LoadDatasetNodeData = {\n  datasetId: DatasetId;\n  useDatasetIdInput?: boolean;\n};\n\nexport class LoadDatasetNodeImpl extends NodeImpl<LoadDatasetNode> {\n  static create(): LoadDatasetNode {\n    return {\n      id: newId<NodeId>(),\n      type: 'loadDataset',\n      title: 'Load Dataset',\n      visualData: { x: 0, y: 0, width: 250 },\n      data: {\n        datasetId: '' as DatasetId,\n      },\n    };\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [];\n\n    if (this.data.useDatasetIdInput) {\n      inputs.push({\n        id: 'datasetId' as PortId,\n        title: 'Dataset ID',\n        dataType: 'string',\n      });\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'dataset' as PortId,\n        title: 'Dataset',\n        dataType: 'object[]',\n      },\n      {\n        id: 'datasetId_out' as PortId,\n        title: 'Dataset ID',\n        dataType: 'string',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Loads a dataset with the provided ID. If the dataset does not exist, it throws an error.\n      `,\n      infoBoxTitle: 'Load Dataset Node',\n      contextMenuTitle: 'Load Dataset',\n      group: ['Input/Output'],\n    };\n  }\n\n  getEditors(): EditorDefinition<LoadDatasetNode>[] | Promise<EditorDefinition<LoadDatasetNode>[]> {\n    return [\n      {\n        type: 'datasetSelector',\n        label: 'Dataset',\n        dataKey: 'datasetId',\n        useInputToggleDataKey: 'useDatasetIdInput',\n      },\n    ];\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const { datasetProvider } = context;\n\n    if (datasetProvider == null) {\n      throw new Error('datasetProvider is required');\n    }\n\n    const datasetId = coerceTypeOptional(inputs['datasetId' as PortId], 'string') || this.data.datasetId;\n\n    const dataset = await datasetProvider.getDatasetData(datasetId as DatasetId);\n\n    if (!dataset) {\n      throw new Error(`Dataset with ID ${datasetId} does not exist`);\n    }\n\n    return {\n      ['dataset' as PortId]: {\n        type: 'object[]',\n        value: dataset.rows,\n      },\n      ['datasetId_out' as PortId]: {\n        type: 'string',\n        value: datasetId,\n      },\n    };\n  }\n}\n\nexport const loadDatasetNode = nodeDefinition(LoadDatasetNodeImpl, 'Load Dataset');\n", "import type {\n  ChartNode,\n  EditorDefinition,\n  InternalProcessContext,\n  NodeId,\n  NodeInputDefinition,\n  NodeOutputDefinition,\n  NodeUIData,\n  Outputs,\n  PortId,\n  Inputs,\n} from '../../index.js';\nimport { NodeImpl } from '../NodeImpl.js';\nimport { dedent, newId } from '../../utils/index.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\n\nexport type GetAllDatasetsNode = ChartNode<'getAllDatasets', GetAllDatasetsNodeData>;\n\ntype GetAllDatasetsNodeData = {};\n\nexport class GetAllDatasetsNodeImpl extends NodeImpl<GetAllDatasetsNode> {\n  static create(): GetAllDatasetsNode {\n    return {\n      id: newId<NodeId>(),\n      type: 'getAllDatasets',\n      title: 'Get All Datasets',\n      visualData: { x: 0, y: 0, width: 250 },\n      data: {},\n    };\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    return [];\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'datasets' as PortId,\n        title: 'Datasets',\n        dataType: 'object[]',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Retrieves all datasets. If no datasets exist, it returns an empty array.\n      `,\n      infoBoxTitle: 'Get All Datasets Node',\n      contextMenuTitle: 'Get All Datasets',\n      group: ['Input/Output'],\n    };\n  }\n\n  getEditors(): EditorDefinition<GetAllDatasetsNode>[] | Promise<EditorDefinition<GetAllDatasetsNode>[]> {\n    return [];\n  }\n\n  async process(_inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const { datasetProvider } = context;\n\n    if (datasetProvider == null) {\n      throw new Error('datasetProvider is required');\n    }\n\n    const datasets = await datasetProvider.getDatasetsForProject(context.project.metadata.id);\n\n    return {\n      ['datasets' as PortId]: {\n        type: 'object[]',\n        value: datasets,\n      },\n    };\n  }\n}\n\nexport const getAllDatasetsNode = nodeDefinition(GetAllDatasetsNodeImpl, 'Get All Datasets');\n", "import type {\n  ChartNode,\n  NodeId,\n  NodeInputDefinition,\n  NodeOutputDefinition,\n  NodeUIData,\n  EditorDefinition,\n  PortId,\n  Inputs,\n  Outputs,\n  NodeBodySpec,\n} from '../../index.js';\nimport { NodeImpl } from '../NodeImpl.js';\nimport { coerceType, dedent, getInputOrData, handleEscapeCharacters, newId } from '../../utils/index.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\n\nexport type SplitNode = ChartNode<'split', SplitNodeData>;\n\ntype SplitNodeData = {\n  delimiter: string;\n  useDelimiterInput?: boolean;\n  regex?: boolean;\n};\n\nexport class SplitNodeImpl extends NodeImpl<SplitNode> {\n  static create(): SplitNode {\n    return {\n      id: newId<NodeId>(),\n      type: 'split',\n      title: 'Split Text',\n      visualData: { x: 0, y: 0, width: 250 },\n      data: {\n        delimiter: ',',\n        regex: false,\n      },\n    };\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [\n      {\n        id: 'string' as PortId,\n        title: 'String',\n        dataType: 'string',\n      },\n    ];\n\n    if (this.data.useDelimiterInput) {\n      inputs.push({\n        id: 'delimiter' as PortId,\n        title: 'Delimiter',\n        dataType: 'string',\n      });\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'splitString' as PortId,\n        title: 'Split',\n        dataType: 'string[]',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Splits a string by the provided delimiter.\n      `,\n      infoBoxTitle: 'Split Text Node',\n      contextMenuTitle: 'Split Text',\n      group: ['Text'],\n    };\n  }\n\n  getEditors(): EditorDefinition<SplitNode>[] | Promise<EditorDefinition<SplitNode>[]> {\n    return [\n      {\n        type: 'toggle',\n        label: 'Regex',\n        dataKey: 'regex',\n      },\n      {\n        type: 'code',\n        label: 'Delimiter',\n        language: 'plaintext',\n        dataKey: 'delimiter',\n        useInputToggleDataKey: 'useDelimiterInput',\n      },\n    ];\n  }\n\n  getBody(): string | NodeBodySpec | NodeBodySpec[] | undefined {\n    if (this.data.useDelimiterInput) {\n      return '(Delimiter from input)';\n    }\n\n    const normalized = handleEscapeCharacters(this.data.delimiter);\n\n    if (normalized === '\\n') {\n      return '(New line)';\n    }\n\n    if (normalized === '\\r\\n') {\n      return '(New line (windows))';\n    }\n\n    if (normalized === '\\t') {\n      return '(Tab)';\n    }\n\n    if (normalized === ' ') {\n      return '(Space)';\n    }\n\n    return normalized;\n  }\n\n  async process(inputs: Inputs): Promise<Outputs> {\n    const delimiter = getInputOrData(this.data, inputs, 'delimiter');\n\n    const normalizedDelimiter = this.data.regex ? new RegExp(delimiter) : handleEscapeCharacters(delimiter);\n\n    const stringToSplit = coerceType(inputs['string' as PortId], 'string');\n\n    const splitString = stringToSplit.split(normalizedDelimiter);\n\n    return {\n      ['splitString' as PortId]: {\n        type: 'string[]',\n        value: splitString,\n      },\n    };\n  }\n}\n\nexport const splitNode = nodeDefinition(SplitNodeImpl, 'Split String');\n", "import type {\n  ChartNode,\n  DatasetId,\n  Inputs,\n  InternalProcessContext,\n  NodeId,\n  NodeInputDefinition,\n  NodeOutputDefinition,\n  NodeUIData,\n  Outputs,\n  PortId,\n  EditorDefinition,\n} from '../../index.js';\nimport { NodeImpl } from '../NodeImpl.js';\nimport { coerceType, dedent, getInputOrData, newId } from '../../utils/index.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\n\nexport type DatasetNearestNeighborsNode = ChartNode<'datasetNearestNeighbors', DatasetNearestNeighborsNodeData>;\n\ntype DatasetNearestNeighborsNodeData = {\n  datasetId: DatasetId;\n  useDatasetIdInput?: boolean;\n\n  k: number;\n  useKInput?: boolean;\n};\n\nexport class DatasetNearestNeighborsNodeImpl extends NodeImpl<DatasetNearestNeighborsNode> {\n  static create(): DatasetNearestNeighborsNode {\n    return {\n      id: newId<NodeId>(),\n      type: 'datasetNearestNeighbors',\n      title: 'KNN Dataset',\n      visualData: { x: 0, y: 0, width: 250 },\n      data: {\n        datasetId: '' as DatasetId,\n        k: 5,\n      },\n    };\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [\n      {\n        id: 'embedding' as PortId,\n        title: 'Embedding',\n        dataType: 'object',\n      },\n    ];\n\n    if (this.data.useDatasetIdInput) {\n      inputs.push({\n        id: 'datasetId' as PortId,\n        title: 'Dataset ID',\n        dataType: 'string',\n      });\n    }\n\n    if (this.data.useKInput) {\n      inputs.push({\n        id: 'k' as PortId,\n        title: 'K',\n        dataType: 'number',\n      });\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'nearestNeighbors' as PortId,\n        title: 'Nearest Neighbors',\n        dataType: 'object[]',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Finds the k nearest neighbors in the dataset with the provided ID, given an embedding.\n      `,\n      infoBoxTitle: 'KNN Dataset Node',\n      contextMenuTitle: 'KNN Dataset',\n      group: ['Input/Output'],\n    };\n  }\n\n  getEditors(): EditorDefinition<DatasetNearestNeighborsNode>[] {\n    return [\n      {\n        type: 'datasetSelector',\n        label: 'Dataset',\n        dataKey: 'datasetId',\n        useInputToggleDataKey: 'useDatasetIdInput',\n      },\n      {\n        type: 'number',\n        label: 'K',\n        dataKey: 'k',\n        useInputToggleDataKey: 'useKInput',\n      },\n    ];\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const { datasetProvider } = context;\n\n    if (datasetProvider == null) {\n      throw new Error('datasetProvider is required');\n    }\n\n    const datasetId = getInputOrData(this.data, inputs, 'datasetId');\n    const k = getInputOrData(this.data, inputs, 'k', 'number');\n    const embedding = coerceType(inputs['embedding' as PortId], 'vector');\n\n    const nearestNeighbors = await datasetProvider.knnDatasetRows(datasetId as DatasetId, k, embedding);\n\n    return {\n      ['nearestNeighbors' as PortId]: {\n        type: 'object[]',\n        value: nearestNeighbors.map((neighbor) => ({\n          id: neighbor.id,\n          distance: neighbor.distance,\n          data: neighbor.data,\n        })),\n      },\n    };\n  }\n}\n\nexport const datasetNearestNeighborsNode = nodeDefinition(DatasetNearestNeighborsNodeImpl, 'Dataset Nearest Neighbors');\n", "import type {\n  ChartNode,\n  DatasetId,\n  Inputs,\n  InternalProcessContext,\n  NodeId,\n  NodeInputDefinition,\n  NodeOutputDefinition,\n  NodeUIData,\n  Outputs,\n  PortId,\n  EditorDefinition,\n} from '../../index.js';\nimport { NodeImpl } from '../NodeImpl.js';\nimport { dedent, getInputOrData, newId } from '../../utils/index.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\n\nexport type GetDatasetRowNode = ChartNode<'getDatasetRow', GetDatasetRowNodeData>;\n\ntype GetDatasetRowNodeData = {\n  datasetId: DatasetId;\n  useDatasetIdInput?: boolean;\n\n  rowId: string;\n  useRowIdInput?: boolean;\n};\n\nexport class GetDatasetRowNodeImpl extends NodeImpl<GetDatasetRowNode> {\n  static create(): GetDatasetRowNode {\n    return {\n      id: newId<NodeId>(),\n      type: 'getDatasetRow',\n      title: 'Get Dataset Row',\n      visualData: { x: 0, y: 0, width: 250 },\n      data: {\n        datasetId: '' as DatasetId,\n        rowId: '',\n      },\n    };\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [];\n\n    if (this.data.useRowIdInput) {\n      inputs.push({\n        id: 'rowId' as PortId,\n        title: 'Row ID',\n        dataType: 'string',\n      });\n    }\n\n    if (this.data.useDatasetIdInput) {\n      inputs.push({\n        id: 'datasetId' as PortId,\n        title: 'Dataset ID',\n        dataType: 'string',\n      });\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'row' as PortId,\n        title: 'Row',\n        dataType: 'object',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Gets a row from a dataset with the provided ID. If the dataset or row does not exist, it throws an error.\n      `,\n      infoBoxTitle: 'Get Dataset Row Node',\n      contextMenuTitle: 'Get Dataset Row',\n      group: ['Input/Output'],\n    };\n  }\n\n  getEditors(): EditorDefinition<GetDatasetRowNode>[] | Promise<EditorDefinition<GetDatasetRowNode>[]> {\n    return [\n      {\n        type: 'datasetSelector',\n        label: 'Dataset',\n        dataKey: 'datasetId',\n        useInputToggleDataKey: 'useDatasetIdInput',\n      },\n      {\n        type: 'string',\n        label: 'Row ID',\n        dataKey: 'rowId',\n        useInputToggleDataKey: 'useRowIdInput',\n      },\n    ];\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const { datasetProvider } = context;\n\n    if (datasetProvider == null) {\n      throw new Error('datasetProvider is required');\n    }\n\n    const datasetId = getInputOrData(this.data, inputs, 'datasetId', 'string') as DatasetId;\n    const rowId = getInputOrData(this.data, inputs, 'rowId', 'string') as string;\n\n    const dataset = await datasetProvider.getDatasetData(datasetId as DatasetId);\n\n    if (!dataset) {\n      throw new Error(`Dataset with ID ${datasetId} does not exist`);\n    }\n\n    // TODO be more efficient\n    const row = dataset.rows.find((r) => r.id === rowId);\n\n    if (!row) {\n      return {\n        ['row' as PortId]: {\n          type: 'control-flow-excluded',\n          value: undefined,\n        },\n      };\n    }\n\n    return {\n      ['row' as PortId]: {\n        type: 'object',\n        value: row,\n      },\n    };\n  }\n}\n\nexport const getDatasetRowNode = nodeDefinition(GetDatasetRowNodeImpl, 'Get Dataset Row');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { type NodeBodySpec } from '../../index.js';\nimport { coerceType } from '../../utils/coerceType.js';\nimport { getInputOrData } from '../../utils/index.js';\n\nexport type SliceNode = ChartNode<'slice', SliceNodeData>;\n\nexport type SliceNodeData = {\n  start?: number;\n  useStartInput?: boolean;\n\n  count?: number;\n  useCountInput?: boolean;\n};\n\nexport class SliceNodeImpl extends NodeImpl<SliceNode> {\n  static create(): SliceNode {\n    const chartNode: SliceNode = {\n      type: 'slice',\n      title: 'Slice',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 200,\n      },\n      data: {\n        start: 0,\n        count: undefined,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [\n      {\n        dataType: 'any[]',\n        id: 'input' as PortId,\n        title: 'Input',\n      },\n    ];\n\n    if (this.data.useStartInput) {\n      inputs.push({\n        dataType: 'number',\n        id: 'start' as PortId,\n        title: 'Start',\n      });\n    }\n\n    if (this.data.useCountInput) {\n      inputs.push({\n        dataType: 'number',\n        id: 'count' as PortId,\n        title: 'Count',\n      });\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        dataType: 'any[]',\n        id: 'output' as PortId,\n        title: 'Output',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<SliceNode>[] {\n    return [\n      { type: 'number', label: 'Start', dataKey: 'start', useInputToggleDataKey: 'useStartInput', allowEmpty: true },\n      { type: 'number', label: 'Count', dataKey: 'count', useInputToggleDataKey: 'useCountInput', allowEmpty: true },\n    ];\n  }\n\n  getBody(): string | NodeBodySpec | NodeBodySpec[] | undefined {\n    return dedent`\n      Start: ${this.data.useStartInput ? '(Using Input)' : this.data.start == null ? '0' : this.data.start}\n      Count: ${this.data.useCountInput ? '(Using Input)' : this.data.count == null ? 'All' : this.data.count}\n    `;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Slices an array from the start index for the count number of elements.\n\n        Useful for extracting a portion of an array.\n      `,\n      infoBoxTitle: 'Slice Node',\n      contextMenuTitle: 'Slice',\n      group: ['Lists'],\n    };\n  }\n\n  async process(inputs: Inputs): Promise<Outputs> {\n    const inputArray = coerceType(inputs['input' as PortId], 'any[]');\n\n    const start = getInputOrData(this.data, inputs, 'start', 'number') ?? 0;\n    const count = getInputOrData(this.data, inputs, 'count', 'number') ?? inputArray.length;\n\n    const outputArray = inputArray.slice(start, start + count);\n\n    return {\n      ['output' as PortId]: {\n        type: 'any[]',\n        value: outputArray,\n      },\n    };\n  }\n}\n\nexport const sliceNode = nodeDefinition(SliceNodeImpl, 'Slice');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { expectType } from '../../utils/expectType.js';\nimport type { Inputs, Outputs } from '../GraphProcessor.js';\nimport { dedent } from 'ts-dedent';\n\nexport type ExtractMarkdownCodeBlocksNode = ChartNode<'extractMarkdownCodeBlocks', {}>;\n\nexport class ExtractMarkdownCodeBlocksNodeImpl extends NodeImpl<ExtractMarkdownCodeBlocksNode> {\n  static create(): ExtractMarkdownCodeBlocksNode {\n    const chartNode: ExtractMarkdownCodeBlocksNode = {\n      type: 'extractMarkdownCodeBlocks',\n      title: 'Extract Markdown Code Blocks',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 250,\n      },\n      data: {},\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    return [\n      {\n        id: 'input' as PortId,\n        title: 'Input',\n        dataType: 'string',\n        required: true,\n      },\n    ];\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'firstBlock' as PortId,\n        title: 'First Block',\n        dataType: 'string',\n      },\n      {\n        id: 'allBlocks' as PortId,\n        title: 'All Blocks',\n        dataType: 'string[]',\n      },\n      {\n        id: 'languages' as PortId,\n        title: 'Languages',\n        dataType: 'string[]',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Extracts the code blocks in the input Markdown text.\n\n        Outputs the first matched block, all matched blocks, and the languages specified for the blocks.\n      `,\n      infoBoxTitle: 'Extract Markdown Code Blocks Node',\n      contextMenuTitle: 'Extract Markdown Code Blocks',\n      group: ['Text'],\n    };\n  }\n\n  async process(inputs: Inputs): Promise<Outputs> {\n    const inputString = expectType(inputs['input' as PortId], 'string');\n\n    const regex = /```(\\w*)\\n([\\s\\S]*?)```/g;\n    let match;\n    let firstBlock: string | undefined;\n    const allBlocks = [];\n    const languages = [];\n\n    while ((match = regex.exec(inputString)) !== null) {\n      const language = match[1];\n      const block = match[2];\n\n      if (!firstBlock) {\n        firstBlock = block!;\n      }\n\n      allBlocks.push(block!);\n      languages.push(language!);\n    }\n\n    return {\n      ['firstBlock' as PortId]:\n        firstBlock == null\n          ? {\n              type: 'control-flow-excluded',\n              value: undefined,\n            }\n          : {\n              type: 'string',\n              value: firstBlock,\n            },\n      ['allBlocks' as PortId]: {\n        type: 'string[]',\n        value: allBlocks,\n      },\n      ['languages' as PortId]: {\n        type: 'string[]',\n        value: languages,\n      },\n    };\n  }\n}\n\nexport const extractMarkdownCodeBlocksNode = nodeDefinition(\n  ExtractMarkdownCodeBlocksNodeImpl,\n  'Extract Markdown Code Blocks',\n);\n", "import {\n  type ChartNode,\n  type NodeConnection,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeBody, type NodeUIData } from '../NodeImpl.js';\nimport { type ChatMessage, type ChatMessageMessagePart, arrayizeDataValue, unwrapDataValue } from '../DataValue.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { orderBy } from 'lodash-es';\nimport { coerceTypeOptional, dedent, getInputOrData } from '../../utils/index.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport type { EditorDefinition } from '../EditorDefinition.js';\nimport type { RivetUIContext } from '../RivetUIContext.js';\nimport { match } from 'ts-pattern';\n\nexport type AssembleMessageNode = ChartNode<'assembleMessage', AssembleMessageNodeData>;\n\nexport type AssembleMessageNodeData = {\n  type: 'system' | 'user' | 'assistant' | 'function';\n  useTypeInput: boolean;\n\n  toolCallId: string;\n  useToolCallIdInput?: boolean;\n};\n\nconst messageTypeToTitle: Record<ChatMessage['type'], string> = {\n  assistant: 'Assistant',\n  function: 'Function Tool Call',\n  system: 'System',\n  user: 'User',\n};\n\nexport class AssembleMessageNodeImpl extends NodeImpl<AssembleMessageNode> {\n  static create(): AssembleMessageNode {\n    const chartNode: AssembleMessageNode = {\n      type: 'assembleMessage',\n      title: 'Assemble Message',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 250,\n      },\n      data: {\n        type: 'user',\n        useTypeInput: false,\n        toolCallId: '',\n        useToolCallIdInput: false,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(connections: NodeConnection[]): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [];\n    const messageCount = this.#getInputPortCount(connections);\n\n    if (this.data.useTypeInput) {\n      inputs.push({\n        dataType: 'string',\n        id: 'type' as PortId,\n        title: 'Type',\n        description: 'The type of message to assemble.',\n      });\n    }\n\n    if (this.data.useToolCallIdInput) {\n      inputs.push({\n        dataType: 'string',\n        id: 'toolCallId' as PortId,\n        title: 'Tool Call ID',\n        description: 'The ID of the tool call to associate with the message.',\n      });\n    }\n\n    for (let i = 1; i <= messageCount; i++) {\n      inputs.push({\n        dataType: ['string', 'image', 'string[]', 'image[]', 'object', 'object[]', 'document', 'document[]'] as const,\n        id: `part${i}` as PortId,\n        title: `Part ${i}`,\n        description: 'A part of the message to assemble.',\n      });\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        dataType: 'chat-message',\n        id: 'message' as PortId,\n        title: 'Message',\n        description: 'The assembled message.',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<AssembleMessageNode>[] {\n    return [\n      {\n        type: 'dropdown',\n        label: 'Type',\n        dataKey: 'type',\n        options: [\n          { value: 'system', label: 'System' },\n          { value: 'user', label: 'User' },\n          { value: 'assistant', label: 'Assistant' },\n          { value: 'function', label: 'Function' },\n        ],\n        defaultValue: 'user',\n        useInputToggleDataKey: 'useTypeInput',\n      },\n      {\n        type: 'string',\n        label: 'Tool Call ID',\n        dataKey: 'toolCallId',\n        useInputToggleDataKey: 'useToolCallIdInput',\n        hideIf: (data) => data.type !== 'function',\n      },\n    ];\n  }\n\n  #getInputPortCount(connections: NodeConnection[]): number {\n    const inputNodeId = this.chartNode.id;\n    const messageConnections = connections.filter(\n      (connection) => connection.inputNodeId === inputNodeId && connection.inputId.startsWith('part'),\n    );\n\n    let maxMessageNumber = 0;\n    for (const connection of messageConnections) {\n      const messageNumber = parseInt(connection.inputId.replace('part', ''));\n      if (messageNumber > maxMessageNumber) {\n        maxMessageNumber = messageNumber;\n      }\n    }\n\n    return maxMessageNumber + 1;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Assembles a single chat message from multiple parts. This is similar to a Prompt node, but works with multimodal\n        models, as you can include text, images, and documents in the message.\n      `,\n      infoBoxTitle: 'Assemble Message Node',\n      contextMenuTitle: 'Assemble Message',\n      group: 'AI',\n    };\n  }\n\n  getBody(_context: RivetUIContext): NodeBody | Promise<NodeBody> {\n    return dedent`\n      ${this.data.useTypeInput ? '(Type From Input)' : messageTypeToTitle[this.data.type]}\n      ${\n        this.data.useTypeInput || this.data.type === 'function'\n          ? `Tool Call ID: ${this.data.useToolCallIdInput ? '(From Input)' : this.data.toolCallId}`\n          : ``\n      }\n    `;\n  }\n\n  async process(inputs: Inputs): Promise<Outputs> {\n    const output: Outputs = {};\n\n    const type = getInputOrData(this.data, inputs, 'type');\n\n    type MultiMessage = ChatMessage & { message: ChatMessageMessagePart[] };\n    const outMessage: MultiMessage = match(type)\n      .with(\n        'system',\n        (type): MultiMessage => ({\n          type,\n          message: [],\n        }),\n      )\n      .with(\n        'user',\n        (type): MultiMessage => ({\n          type,\n          message: [],\n        }),\n      )\n      .with(\n        'assistant',\n        (type): MultiMessage => ({\n          type,\n          message: [],\n          function_call: undefined, // Not supported yet in Assemble Message node\n          function_calls: undefined, // Not supported yet in Assemble Message node\n        }),\n      )\n      .with(\n        'function',\n        (type): MultiMessage => ({\n          type,\n          message: [],\n          name: getInputOrData(this.data, inputs, 'toolCallId'),\n        }),\n      )\n      .otherwise(() => {\n        throw new Error(`Invalid type: ${type}`);\n      });\n\n    const inputParts = orderBy(\n      Object.entries(inputs).filter(([key]) => key.startsWith('part')),\n      ([key]) => key,\n      'asc',\n    );\n\n    for (const [, inputPart] of inputParts) {\n      if (!inputPart || inputPart.type === 'control-flow-excluded' || !inputPart.value) {\n        continue;\n      }\n\n      const inPart = arrayizeDataValue(unwrapDataValue(inputPart));\n      for (const message of inPart) {\n        if (message.type === 'string') {\n          outMessage.message.push(message.value);\n        } else if (message.type === 'image') {\n          outMessage.message.push({\n            type: 'image',\n            data: message.value.data,\n            mediaType: message.value.mediaType,\n          });\n        } else if (message.type === 'object') {\n          if (\n            message.value &&\n            'type' in message.value &&\n            message.value.type === 'url_reference' &&\n            typeof message.value.url === 'string'\n          ) {\n            outMessage.message.push({\n              type: 'url',\n              url: message.value.url,\n            });\n          }\n        } else if (message.type === 'document') {\n          outMessage.message.push({\n            type: 'document',\n            data: message.value.data,\n            mediaType: message.value.mediaType,\n            context: message.value.context,\n            title: message.value.title,\n            enableCitations: message.value.enableCitations,\n          });\n        } else {\n          const coerced = coerceTypeOptional(message, 'string');\n\n          if (coerced) {\n            outMessage.message.push(coerced);\n          }\n        }\n      }\n    }\n\n    output['message' as PortId] = {\n      type: 'chat-message',\n      value: outMessage,\n    };\n\n    return output;\n  }\n}\n\nexport const assembleMessageNode = nodeDefinition(AssembleMessageNodeImpl, 'Assemble Prompt');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl } from '../NodeImpl.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type EditorDefinition, type NodeUIData } from '../../index.js';\nimport { nodeDefinition } from '../../model/NodeDefinition.js';\nimport { getInputOrData } from '../../utils/index.js';\n\nexport type UrlReferenceNode = ChartNode<'urlReference', UrlReferenceNodeData>;\n\nexport type UrlReferenceNodeData = {\n  url: string;\n  useUrlInput?: boolean;\n};\n\nexport class UrlReferenceNodeImpl extends NodeImpl<UrlReferenceNode> {\n  static create(): UrlReferenceNode {\n    const chartNode: UrlReferenceNode = {\n      type: 'urlReference',\n      title: 'URL Reference',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 225,\n      },\n      data: {\n        url: '',\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [];\n\n    if (this.data.useUrlInput) {\n      inputs.push({\n        dataType: 'string',\n        id: 'url' as PortId,\n        title: 'URL',\n        description: 'The value to convert into a URL reference.',\n        coerced: true,\n      });\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        dataType: 'object',\n        id: 'urlReference' as PortId,\n        title: 'URL Reference',\n        description: 'A reference to a URL.',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<UrlReferenceNode>[] {\n    return [\n      {\n        type: 'string',\n        label: 'URL',\n        dataKey: 'url',\n        useInputToggleDataKey: 'useUrlInput',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      contextMenuTitle: 'URL Reference',\n      group: 'Data',\n      infoBoxTitle: 'URL Reference Node',\n      infoBoxBody:\n        'Defines a reference to a URL, or converts a string into a URL reference. Used with the Assemble Message node to define URLs for attachments/images.',\n    };\n  }\n\n  getBody(): string {\n    return this.data.useUrlInput ? '(URL Using Input)' : this.data.url;\n  }\n\n  async process(inputs: Inputs): Promise<Outputs> {\n    const url = getInputOrData(this.data, inputs, 'url', 'string');\n\n    return {\n      ['urlReference' as PortId]: {\n        type: 'object',\n        value: { type: 'url_reference', url },\n      },\n    };\n  }\n}\n\nexport const urlReferenceNode = nodeDefinition(UrlReferenceNodeImpl, 'URL Reference');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type DataValue } from '../DataValue.js';\nimport { JSONPath } from 'jsonpath-plus';\nimport { type EditorDefinition, type NodeBodySpec } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { coerceTypeOptional } from '../../utils/coerceType.js';\n\nexport type DestructureNode = ChartNode<'destructure', DestructureNodeData>;\n\nexport type DestructureNodeData = {\n  paths: string[];\n};\n\nexport class DestructureNodeImpl extends NodeImpl<DestructureNode> {\n  static create(): DestructureNode {\n    const chartNode: DestructureNode = {\n      type: 'destructure',\n      title: 'Destructure',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 250,\n      },\n      data: {\n        paths: ['$.value'],\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    return [\n      {\n        id: 'object' as PortId,\n        title: 'Object',\n        dataType: 'object',\n        required: true,\n      },\n    ];\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return this.data.paths.map((path, index) => ({\n      id: `match_${index}` as PortId,\n      title: path,\n      dataType: 'any',\n    }));\n  }\n\n  getEditors(): EditorDefinition<DestructureNode>[] {\n    return [\n      {\n        type: 'stringList',\n        label: 'Paths',\n        dataKey: 'paths',\n        helperMessage:\n          'One or more JSONPath expressions. Each expression will correspond to an output port of the node.',\n      },\n    ];\n  }\n\n  getBody(): string | NodeBodySpec | undefined {\n    return '';\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Destructures the input value by extracting values at the specified paths. The paths use JSONPath notation to navigate through the value.\n      `,\n      infoBoxTitle: 'Destructure Node',\n      contextMenuTitle: 'Destructure',\n      group: ['Objects'],\n    };\n  }\n\n  async process(inputs: Record<PortId, DataValue>): Promise<Record<PortId, DataValue>> {\n    const inputObject = coerceTypeOptional(inputs['object' as PortId], 'object');\n\n    const output: Record<PortId, DataValue> = {};\n\n    this.data.paths.forEach((path, index) => {\n      let match: unknown;\n      try {\n        match = JSONPath<unknown>({ json: inputObject ?? null, path: path.trim(), wrap: false });\n      } catch (err) {\n        match = undefined;\n      }\n\n      output[`match_${index}` as PortId] = {\n        type: 'any',\n        value: match,\n      };\n    });\n\n    return output;\n  }\n}\n\nexport const destructureNode = nodeDefinition(DestructureNodeImpl, 'Destructure');\n", "import type { ChartNode, NodeId, PortId, NodeInputDefinition, NodeOutputDefinition } from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nanoid } from 'nanoid/non-secure';\n\nimport type { InternalProcessContext } from '../ProcessContext.js';\nimport { dedent } from 'ts-dedent';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { getInputOrData, coerceType, newId, inferType } from '../../utils/index.js';\nimport { unwrapDataValue } from '../DataValue.js';\nimport type { DatasetId, DatasetRow } from '../Dataset.js';\nimport type { EditorDefinition } from '../EditorDefinition.js';\nimport type { Inputs, Outputs } from '../GraphProcessor.js';\n\nexport type ReplaceDatasetNode = ChartNode<'replaceDataset', ReplaceDatasetNodeData>;\n\ntype ReplaceDatasetNodeData = {\n  datasetId: DatasetId;\n  useDatasetIdInput?: boolean;\n};\n\nexport class ReplaceDatasetNodeImpl extends NodeImpl<ReplaceDatasetNode> {\n  static create(): ReplaceDatasetNode {\n    return {\n      id: nanoid() as NodeId,\n      type: 'replaceDataset',\n      title: 'Replace Dataset',\n      visualData: { x: 0, y: 0, width: 250 },\n      data: {\n        datasetId: '' as DatasetId,\n      },\n    };\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputDefinitions: NodeInputDefinition[] = [];\n\n    inputDefinitions.push({\n      id: 'data' as PortId,\n      dataType: 'object[]',\n      title: 'Data',\n      description:\n        'The new data of the dataset. If empty, the dataset will be cleared. May be an array of array of strings, or an array of DatasetRow objects with { id, data } properties. If a string[][], IDs will be generated.',\n    });\n\n    if (this.data.useDatasetIdInput) {\n      inputDefinitions.push({\n        id: 'datasetId' as PortId,\n        title: 'Dataset ID',\n        dataType: 'string',\n        description: 'The ID of the dataset to replace.',\n      });\n    }\n\n    return inputDefinitions;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'dataset' as PortId,\n        title: 'Dataset',\n        dataType: 'object[]',\n        description: 'The new data of the dataset. An array of DatasetRow objects with { id, data } properties.',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Replaces the data in a dataset with the given data. If no data is given, the dataset will be cleared instead.\n      `,\n      infoBoxTitle: 'Replace Dataset Node',\n      contextMenuTitle: 'Replace Dataset',\n      group: ['Input/Output'],\n    };\n  }\n\n  getEditors(): EditorDefinition<ReplaceDatasetNode>[] | Promise<EditorDefinition<ReplaceDatasetNode>[]> {\n    return [\n      {\n        type: 'datasetSelector',\n        label: 'Dataset',\n        dataKey: 'datasetId',\n        useInputToggleDataKey: 'useDatasetIdInput',\n      },\n    ];\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const { datasetProvider } = context;\n\n    if (datasetProvider == null) {\n      throw new Error('datasetProvider is required');\n    }\n\n    const datasetId = getInputOrData(this.data, inputs, 'datasetId', 'string') as DatasetId;\n    const dataInput = inputs['data' as PortId];\n\n    if (!dataInput) {\n      await datasetProvider.putDatasetData(datasetId, { id: datasetId, rows: [] });\n      return {\n        ['dataset' as PortId]: {\n          type: 'object[]',\n          value: [],\n        },\n      };\n    }\n\n    let dataArrays = unwrapDataValue(dataInput).value as unknown[][] | unknown[] | DatasetRow[];\n    if (!Array.isArray(dataArrays)) {\n      throw new Error('Data input must be either an array of rows, or an array of columns for a single row.');\n    }\n\n    const isDatasetRow = (row: unknown): row is DatasetRow => {\n      return typeof row === 'object' && row != null && 'id' in row && 'data' in row;\n    };\n\n    const firstElem = dataArrays[0];\n    if (!Array.isArray(firstElem) && !isDatasetRow(firstElem)) {\n      dataArrays = [dataArrays as unknown[]];\n    }\n\n    const rows = (dataArrays as unknown[][] | DatasetRow[]).map((row): DatasetRow => {\n      if (Array.isArray(row)) {\n        return {\n          id: newId(),\n          data: row.map((value) => coerceType(inferType(value), 'string')),\n        };\n      }\n\n      if ('id' in row && 'data' in row) {\n        return row;\n      }\n\n      throw new Error('Data input must be an array of strings or DatasetRows');\n    });\n\n    await datasetProvider.putDatasetData(datasetId, {\n      id: datasetId,\n      rows,\n    });\n\n    return {\n      ['dataset' as PortId]: {\n        type: 'object[]',\n        value: rows,\n      },\n    };\n  }\n}\n\nexport const replaceDatasetNode = nodeDefinition(ReplaceDatasetNodeImpl, 'Replace Dataset');\n", "import type {\n  ChartNode,\n  EditorDefinition,\n  GraphId,\n  Inputs,\n  InternalProcessContext,\n  NodeId,\n  NodeInputDefinition,\n  NodeOutputDefinition,\n  NodeUIData,\n  Outputs,\n  PortId,\n} from '../../index.js';\nimport { NodeImpl } from '../NodeImpl.js';\nimport { dedent, newId } from '../../utils/index.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\n\nexport type ListGraphsNode = ChartNode<'listGraphs', ListSubgraphsData>;\n\ntype ListSubgraphsData = {};\n\nexport class ListGraphsNodeImpl extends NodeImpl<ListGraphsNode> {\n  static create(): ListGraphsNode {\n    return {\n      id: newId<NodeId>(),\n      type: 'listGraphs',\n      title: 'List Graphs',\n      visualData: { x: 0, y: 0, width: 250 },\n      data: {},\n    };\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    return [];\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'graphs' as PortId,\n        title: 'Graphs',\n        dataType: 'graph-reference[]',\n      },\n      {\n        id: 'graph-names' as PortId,\n        title: 'Graph Names',\n        dataType: 'string[]',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Lists all graphs in the project.\n      `,\n      infoBoxTitle: 'List Graphs Node',\n      contextMenuTitle: 'List Graphs',\n      group: ['Input/Output'],\n    };\n  }\n\n  getEditors(): EditorDefinition<ListGraphsNode>[] | Promise<EditorDefinition<ListGraphsNode>[]> {\n    return [];\n  }\n\n  async process(_inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const graphs = Object.values(context.project.graphs);\n\n    return {\n      ['graphs' as PortId]: {\n        type: 'graph-reference[]',\n        value: graphs.map((graph) => ({\n          graphId: graph.metadata!.id ?? ('' as GraphId),\n          graphName: graph.metadata!.name ?? '',\n        })),\n      },\n      ['graph-names' as PortId]: {\n        type: 'string[]',\n        value: graphs.map((graph) => graph.metadata!.name ?? ''),\n      },\n    };\n  }\n}\n\nexport const listGraphsNode = nodeDefinition(ListGraphsNodeImpl, 'List Graphs');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type GraphId } from '../NodeGraph.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { type EditorDefinition } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport type { RivetUIContext } from '../RivetUIContext.js';\nimport { coerceType } from '../../utils/index.js';\n\nexport type GraphReferenceNode = ChartNode<'graphReference', GraphReferenceNodeData>;\n\nexport type GraphReferenceNodeData = {\n  graphId: GraphId;\n  useGraphIdOrNameInput: boolean;\n};\n\nexport class GraphReferenceNodeImpl extends NodeImpl<GraphReferenceNode> {\n  static create(): GraphReferenceNode {\n    const chartNode: GraphReferenceNode = {\n      type: 'graphReference',\n      title: 'Graph Reference',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 275,\n      },\n      data: {\n        graphId: '' as GraphId,\n        useGraphIdOrNameInput: false,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [];\n\n    if (this.data.useGraphIdOrNameInput) {\n      inputs.push({\n        id: 'graph-name-or-id' as PortId,\n        dataType: 'string',\n        title: 'Graph Name Or ID',\n        description: 'The name or ID of the graph to get a reference to.',\n        required: true,\n      });\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'graph' as PortId,\n        dataType: 'graph-reference',\n        title: 'Graph',\n        description: 'A reference to the graph.',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<GraphReferenceNode>[] {\n    const definitions: EditorDefinition<GraphReferenceNode>[] = [\n      {\n        type: 'graphSelector',\n        label: 'Graph',\n        dataKey: 'graphId',\n        useInputToggleDataKey: 'useGraphIdOrNameInput',\n      },\n    ];\n\n    return definitions;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Gets a reference to another graph, that can be used to pass around graphs to call using a Call Graph node.\n      `,\n      infoBoxTitle: 'Graph Reference Node',\n      contextMenuTitle: 'Graph Reference',\n      group: ['Advanced'],\n    };\n  }\n\n  getBody(context: RivetUIContext): string {\n    if (this.data.useGraphIdOrNameInput) {\n      return '(Graph from input)';\n    }\n\n    const graph = context.project.graphs[this.data.graphId];\n\n    if (!graph) {\n      return '(Graph not found)';\n    }\n\n    return graph.metadata!.name ?? '(Unnamed Graph)';\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    if (this.data.useGraphIdOrNameInput) {\n      const graphIdOrName = coerceType(inputs['graph-name-or-id' as PortId], 'string');\n\n      let graph = context.project.graphs[graphIdOrName as GraphId];\n\n      if (!graph) {\n        graph = Object.values(context.project.graphs).find((graph) => graph.metadata!.name === graphIdOrName);\n      }\n\n      if (!graph) {\n        return {\n          ['graph' as PortId]: {\n            type: 'control-flow-excluded',\n            value: undefined,\n          },\n        };\n      }\n\n      return {\n        ['graph' as PortId]: {\n          type: 'graph-reference',\n          value: {\n            graphId: graph.metadata!.id ?? ('' as GraphId),\n            graphName: graph.metadata!.name ?? '',\n          },\n        },\n      };\n    }\n\n    const graph = context.project.graphs[this.data.graphId];\n\n    if (!graph) {\n      return {\n        ['graph' as PortId]: {\n          type: 'control-flow-excluded',\n          value: undefined,\n        },\n      };\n    }\n\n    return {\n      ['graph' as PortId]: {\n        type: 'graph-reference',\n        value: {\n          graphId: graph.metadata!.id ?? ('' as GraphId),\n          graphName: graph.metadata!.name ?? '',\n        },\n      },\n    };\n  }\n}\n\nexport const graphReferenceNode = nodeDefinition(GraphReferenceNodeImpl, 'Graph Reference');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { dedent } from 'ts-dedent';\nimport { coerceTypeOptional } from '../../utils/coerceType.js';\nimport { looseDataValuesToDataValues, type LooseDataValue } from '../../api/looseDataValue.js';\nimport { getError } from '../../utils/errors.js';\n\nexport type CallGraphNode = ChartNode<'callGraph', CallGraphNodeData>;\n\nexport type CallGraphNodeData = {\n  useErrorOutput?: boolean;\n};\n\nexport class CallGraphNodeImpl extends NodeImpl<CallGraphNode> {\n  static create(): CallGraphNode {\n    const chartNode: CallGraphNode = {\n      type: 'callGraph',\n      title: 'Call Graph',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 200,\n      },\n      data: {\n        useErrorOutput: false,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [];\n\n    inputs.push({\n      id: 'graph' as PortId,\n      dataType: 'graph-reference',\n      title: 'Graph',\n      description: 'The reference to the graph to call.',\n      required: true,\n    });\n\n    inputs.push({\n      id: 'inputs' as PortId,\n      dataType: 'object',\n      title: 'Inputs',\n      description:\n        'The inputs to pass to the graph. Should be an object where the keys are the input names and the values are the input values.',\n    });\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    const outputs: NodeOutputDefinition[] = [\n      {\n        id: 'outputs' as PortId,\n        dataType: 'object',\n        title: 'Outputs',\n        description: 'The outputs of the graph.',\n      },\n    ];\n\n    if (this.data.useErrorOutput) {\n      outputs.push({\n        id: 'error' as PortId,\n        dataType: 'string',\n        title: 'Error',\n        description: 'The error message if the graph call failed.',\n      });\n    }\n\n    return outputs;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Calls another graph and passes inputs to it. Use in combination with the Graph Reference node to call dynamic graphs.\n      `,\n      infoBoxTitle: 'Call Graph Node',\n      contextMenuTitle: 'Call Graph',\n      group: ['Advanced'],\n    };\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const graphRef = coerceTypeOptional(inputs['graph' as PortId], 'graph-reference');\n    const graphInputs = coerceTypeOptional(inputs['inputs' as PortId], 'object');\n\n    if (!graphRef) {\n      return {\n        ['outputs' as PortId]: {\n          type: 'control-flow-excluded',\n          value: undefined,\n        },\n      };\n    }\n\n    const graph = context.project.graphs[graphRef.graphId];\n\n    if (!graph) {\n      return {\n        ['outputs' as PortId]: {\n          type: 'control-flow-excluded',\n          value: undefined,\n        },\n      };\n    }\n\n    const subGraphProcessor = context.createSubProcessor(graphRef.graphId, { signal: context.signal });\n\n    const outputs: Outputs = {};\n\n    try {\n      const startTime = Date.now();\n\n      const inputData = looseDataValuesToDataValues(graphInputs as Record<string, LooseDataValue>);\n\n      const graphOutputs = await subGraphProcessor.processGraph(context, inputData, context.contextValues);\n\n      const duration = Date.now() - startTime;\n\n      outputs['outputs' as PortId] = {\n        type: 'object',\n        value: graphOutputs,\n      };\n\n      if (this.data.useErrorOutput) {\n        outputs['error' as PortId] = {\n          type: 'control-flow-excluded',\n          value: undefined,\n        };\n      }\n\n      if (outputs['duration' as PortId] == null) {\n        outputs['duration' as PortId] = {\n          type: 'number',\n          value: duration,\n        };\n      }\n\n      return outputs;\n    } catch (err) {\n      if (!this.data.useErrorOutput) {\n        throw err;\n      }\n\n      outputs['outputs' as PortId] = {\n        type: 'control-flow-excluded',\n        value: undefined,\n      };\n\n      outputs['error' as PortId] = {\n        type: 'string',\n        value: getError(err).message,\n      };\n\n      return outputs;\n    }\n  }\n}\n\nexport const callGraphNode = nodeDefinition(CallGraphNodeImpl, 'Call Graph');\n", "import { mapValues } from 'lodash-es';\nimport type { DataValue } from '../model/DataValue.js';\n\nexport type LooseDataValue = DataValue | string | number | boolean;\n\nexport function looseDataValuesToDataValues(values: Record<string, LooseDataValue>): Record<string, DataValue> {\n  return mapValues(values, (val) => looseDataValueToDataValue(val));\n}\n\nexport function looseDataValueToDataValue(value: LooseDataValue): DataValue {\n  if (typeof value === 'string') {\n    return { type: 'string', value };\n  }\n\n  if (typeof value === 'number') {\n    return { type: 'number', value };\n  }\n\n  if (typeof value === 'boolean') {\n    return { type: 'boolean', value };\n  }\n\n  return value;\n}\n", "import { nanoid } from 'nanoid';\nimport type { DataValue, ParsedAssistantChatMessageFunctionCall } from '../DataValue.js';\nimport type { ChartNode, NodeId, NodeInputDefinition, NodeOutputDefinition, PortId } from '../NodeBase.js';\nimport type { GraphId } from '../NodeGraph.js';\nimport { NodeImpl, type NodeBody, type NodeUIData } from '../NodeImpl.js';\nimport { dedent } from 'ts-dedent';\nimport type { EditorDefinition } from '../EditorDefinition.js';\nimport type { RivetUIContext } from '../RivetUIContext.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport type { InternalProcessContext } from '../ProcessContext.js';\nimport type { Inputs, Outputs } from '../GraphProcessor.js';\nimport { coerceType, coerceTypeOptional } from '../../utils/coerceType.js';\n\nexport type DelegateFunctionCallNode = ChartNode<'delegateFunctionCall', DelegateFunctionCallNodeData>;\n\nexport type DelegateFunctionCallNodeData = {\n  handlers: { key: string; value: GraphId }[];\n  unknownHandler: GraphId | undefined;\n  autoDelegate: boolean;\n};\n\nexport class DelegateFunctionCallNodeImpl extends NodeImpl<DelegateFunctionCallNode> {\n  static create(): DelegateFunctionCallNode {\n    const chartNode: DelegateFunctionCallNode = {\n      type: 'delegateFunctionCall',\n      title: 'Delegate Tool Call',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 325,\n      },\n      data: {\n        handlers: [],\n        unknownHandler: undefined,\n        autoDelegate: true,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [];\n\n    inputs.push({\n      id: 'function-call' as PortId,\n      dataType: 'object',\n      title: 'Tool Call',\n      coerced: true,\n      required: true,\n      description: 'The tool call to delegate to a subgraph.',\n    });\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    const outputs: NodeOutputDefinition[] = [];\n\n    outputs.push({\n      id: 'output' as PortId,\n      dataType: 'string',\n      title: 'Output',\n      description: 'The output of the tool call.',\n    });\n\n    outputs.push({\n      id: 'message' as PortId,\n      dataType: 'object',\n      title: 'Message Output',\n      description: 'Maps the output for use directly with an Assemble Prompt node and GPT.',\n    });\n\n    return outputs;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Handles a tool call by delegating it to a different subgraph depending on the tool call.\n      `,\n      infoBoxTitle: 'Delegate Tool Call Node',\n      contextMenuTitle: 'Delegate Tool Call',\n      group: ['Advanced'],\n    };\n  }\n\n  getEditors(): EditorDefinition<DelegateFunctionCallNode>[] {\n    return [\n      {\n        type: 'toggle',\n        label: 'Auto Delegate',\n        dataKey: 'autoDelegate',\n        helperMessage: 'Automatically delegates tool calls to the subgraph containing the same name as the tool.',\n      },\n      {\n        type: 'custom',\n        customEditorId: 'ToolCallHandlers',\n        label: 'Handlers',\n        dataKey: 'handlers',\n        hideIf: (data) => data.autoDelegate,\n      },\n      {\n        type: 'graphSelector',\n        dataKey: 'unknownHandler',\n        label: 'Unknown Handler',\n        helperMessage: 'The subgraph to delegate to if the tool call does not match any handlers.',\n      },\n    ];\n  }\n\n  getBody(context: RivetUIContext): NodeBody {\n    if (this.data.autoDelegate) {\n      return 'Auto Delegate To Subgraphs';\n    }\n\n    if (this.data.handlers.length === 0) {\n      return 'No handlers defined';\n    }\n\n    const lines = ['Handlers:'];\n\n    this.data.handlers.forEach(({ key, value }) => {\n      const subgraphName = context.project.graphs[value]?.metadata!.name! ?? 'Unknown Subgraph';\n      lines.push(`    ${key || '(MISSING!)'} -> ${subgraphName}`);\n    });\n\n    return lines.join('\\n');\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const functionCall = coerceType(\n      inputs['function-call' as PortId],\n      'object',\n    ) as ParsedAssistantChatMessageFunctionCall;\n\n    let handler: { key: string; value: GraphId } | undefined;\n\n    if (this.data.autoDelegate) {\n      const matchingGraph = Object.values(context.project.graphs).find((graph) =>\n        graph.metadata?.name?.includes(functionCall.name),\n      );\n      if (matchingGraph) {\n        handler = { key: undefined!, value: matchingGraph.metadata!.id! };\n      }\n    } else {\n      handler = this.data.handlers.find((handler) => handler.key === functionCall.name);\n    }\n\n    if (!handler) {\n      if (this.data.unknownHandler) {\n        handler = { key: undefined!, value: this.data.unknownHandler };\n      } else {\n        if (this.data.autoDelegate) {\n          throw new Error(\n            `No handler found for tool call: ${functionCall.name}, no graph containing the name \"${functionCall.name}\" was found.`,\n          );\n        } else {\n          throw new Error(`No handler found for tool call: ${functionCall.name}`);\n        }\n      }\n    }\n\n    const subgraphInputs: Record<string, DataValue> = {\n      _function_name: {\n        type: 'string',\n        value: functionCall.name,\n      },\n      _arguments: {\n        type: 'object',\n        value: functionCall.arguments,\n      },\n    };\n\n    for (const [argName, argument] of Object.entries(functionCall.arguments ?? {})) {\n      subgraphInputs[argName] = {\n        type: 'any',\n        value: argument,\n      };\n    }\n\n    const handlerGraphId = handler.value;\n    const subprocessor = context.createSubProcessor(handlerGraphId, { signal: context.signal });\n\n    const outputs = await subprocessor.processGraph(context, subgraphInputs, context.contextValues);\n\n    const outputString = coerceTypeOptional(outputs.output, 'string') ?? '';\n\n    return {\n      ['output' as PortId]: {\n        type: 'string',\n        value: outputString,\n      },\n      ['message' as PortId]: {\n        type: 'chat-message',\n        value: {\n          type: 'function',\n          message: outputString,\n          name: functionCall.id ?? '',\n        },\n      },\n    };\n  }\n}\n\nexport const delegateFunctionCallNode = nodeDefinition(DelegateFunctionCallNodeImpl, 'Delegate Tool Call');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type PortId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { type EditorDefinition, type Inputs, type InternalProcessContext, type Outputs } from '../../index.js';\nimport { expectType } from '../../utils/index.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\n\nexport type PlayAudioNode = ChartNode<'playAudio', PlayAudioNodeData>;\n\ntype PlayAudioNodeData = {};\n\nexport class PlayAudioNodeImpl extends NodeImpl<PlayAudioNode> {\n  static create(): PlayAudioNode {\n    return {\n      id: nanoid() as NodeId,\n      type: 'playAudio',\n      title: 'Play Audio',\n      visualData: { x: 0, y: 0, width: 200 },\n      data: {},\n    };\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputDefinitions: NodeInputDefinition[] = [];\n\n    inputDefinitions.push({\n      id: 'data' as PortId,\n      title: 'Data',\n      dataType: 'audio',\n      coerced: false,\n    });\n\n    return inputDefinitions;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'data' as PortId,\n        title: 'Audio Data',\n        dataType: 'audio',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<PlayAudioNode>[] {\n    return [];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      contextMenuTitle: 'Play Audio',\n      group: 'Input/Output',\n      infoBoxTitle: 'Play Audio Node',\n      infoBoxBody: 'Plays audio data to the speakers.',\n    };\n  }\n\n  async process(inputData: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    if (!context.audioProvider) {\n      throw new Error('Playing audio is not supported in this context');\n    }\n\n    const data = expectType(inputData['data' as PortId], 'audio');\n\n    await context.audioProvider.playAudio({ type: 'audio', value: data }, context.signal);\n\n    return {\n      ['data' as PortId]: {\n        type: 'audio',\n        value: data,\n      },\n    };\n  }\n}\n\nexport const playAudioNode = nodeDefinition(PlayAudioNodeImpl, 'Play Audio');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type PortId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport {\n  type DataRef,\n  type EditorDefinition,\n  type Inputs,\n  type InternalProcessContext,\n  type NodeBody,\n  type Outputs,\n  type SupportedDocumentMediaTypes,\n} from '../../index.js';\nimport { base64ToUint8Array, expectType } from '../../utils/index.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { getInputOrData } from '../../utils/inputs.js';\nimport type { RivetUIContext } from '../RivetUIContext.js';\nimport { dedent } from '../../utils/misc.js';\n\nexport type DocumentNode = ChartNode<'document', DocumentNodeData>;\n\ntype DocumentNodeData = {\n  data?: DataRef;\n  useDataInput: boolean;\n\n  mediaType?: SupportedDocumentMediaTypes;\n  useMediaTypeInput: boolean;\n\n  title: string;\n  useTitleInput: boolean;\n\n  context: string;\n  useContextInput: boolean;\n\n  enableCitations: boolean;\n  useEnableCitationsInput: boolean;\n};\n\nexport class DocumentNodeImpl extends NodeImpl<DocumentNode> {\n  static create(): DocumentNode {\n    return {\n      id: nanoid() as NodeId,\n      type: 'document',\n      title: 'Document',\n      visualData: { x: 0, y: 0, width: 300 },\n      data: {\n        useDataInput: false,\n        useMediaTypeInput: false,\n        title: '',\n        useTitleInput: false,\n        context: '',\n        useContextInput: false,\n        enableCitations: false,\n        useEnableCitationsInput: false,\n      },\n    };\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputDefinitions: NodeInputDefinition[] = [];\n\n    if (this.chartNode.data.useDataInput) {\n      inputDefinitions.push({\n        id: 'data' as PortId,\n        title: 'Data',\n        dataType: ['string', 'binary'],\n        coerced: false,\n        description: 'The document data. Either string or binary data loaded from a file.',\n      });\n    }\n\n    if (this.chartNode.data.useMediaTypeInput) {\n      inputDefinitions.push({\n        id: 'mediaType' as PortId,\n        title: 'Media Type',\n        dataType: 'string',\n        coerced: false,\n        description: 'The media type of the document, such as text/plain or application/pdf.',\n      });\n    }\n\n    if (this.data.useTitleInput) {\n      inputDefinitions.push({\n        id: 'title' as PortId,\n        title: 'Title',\n        dataType: 'string',\n        coerced: true,\n        description: 'The title of the document.',\n      });\n    }\n\n    if (this.data.useContextInput) {\n      inputDefinitions.push({\n        id: 'context' as PortId,\n        title: 'Context',\n        dataType: 'string',\n        coerced: true,\n        description: 'The context of the document.',\n      });\n    }\n\n    if (this.data.useEnableCitationsInput) {\n      inputDefinitions.push({\n        id: 'enableCitations' as PortId,\n        title: 'Enable Citations',\n        dataType: 'boolean',\n        coerced: true,\n        description: 'Whether to enable citations for the document.',\n      });\n    }\n\n    return inputDefinitions;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'data' as PortId,\n        title: 'Document Data',\n        dataType: 'document',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<DocumentNode>[] {\n    return [\n      {\n        type: 'fileBrowser',\n        label: 'Document File',\n        dataKey: 'data',\n        mediaTypeDataKey: 'mediaType',\n        useInputToggleDataKey: 'useDataInput',\n        accept: '*/*',\n      },\n      {\n        type: 'string',\n        label: 'Media Type',\n        dataKey: 'mediaType',\n        useInputToggleDataKey: 'useMediaTypeInput',\n      },\n      {\n        type: 'string',\n        label: 'Title',\n        dataKey: 'title',\n        useInputToggleDataKey: 'useTitleInput',\n      },\n      {\n        type: 'string',\n        label: 'Context',\n        dataKey: 'context',\n        useInputToggleDataKey: 'useContextInput',\n      },\n      {\n        type: 'toggle',\n        label: 'Enable Citations',\n        dataKey: 'enableCitations',\n        useInputToggleDataKey: 'useEnableCitationsInput',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      contextMenuTitle: 'Document',\n      group: 'Data',\n      infoBoxTitle: 'Document Node',\n      infoBoxBody:\n        'Defines a document for use with other nodes such as Assemble Message. Can accept text and PDF files.',\n    };\n  }\n\n  getBody(_context: RivetUIContext): NodeBody | Promise<NodeBody> {\n    const parts = [\n      this.data.useDataInput ? '(Data from input)' : '(Data stored in node)',\n      this.data.useMediaTypeInput\n        ? '(Media type from input)'\n        : this.data.mediaType\n          ? `(${this.data.mediaType.trim()})`\n          : undefined,\n      this.data.useTitleInput ? '(Title from input)' : this.data.title ? `Title: ${this.data.title}` : undefined,\n      this.data.useContextInput\n        ? '(Context from input)'\n        : this.data.context\n          ? `Context: ${this.data.context}`\n          : undefined,\n    ].filter((x) => x != null);\n\n    return dedent`\n      ${parts.join('\\n')}\n    `;\n  }\n\n  async process(inputData: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    let data: Uint8Array;\n\n    const mediaType = getInputOrData(this.data, inputData, 'mediaType', 'string') || 'text/plain';\n\n    const title = getInputOrData(this.data, inputData, 'title');\n    const contextInput = getInputOrData(this.data, inputData, 'context');\n    const enableCitations = getInputOrData(this.data, inputData, 'enableCitations', 'boolean');\n\n    if (this.chartNode.data.useDataInput) {\n      data = expectType(inputData['data' as PortId], 'binary');\n    } else {\n      const dataRef = this.data.data?.refId;\n      if (!dataRef) {\n        throw new Error('No data ref');\n      }\n\n      const encodedData = context.project.data?.[dataRef] as string;\n\n      if (!encodedData) {\n        throw new Error(`No data at ref ${dataRef}`);\n      }\n\n      data = base64ToUint8Array(encodedData);\n    }\n\n    return {\n      ['data' as PortId]: {\n        type: 'document',\n        value: {\n          data,\n          mediaType: mediaType as SupportedDocumentMediaTypes,\n          title,\n          context: contextInput,\n          enableCitations,\n        },\n      },\n    };\n  }\n}\n\nexport const documentNode = nodeDefinition(DocumentNodeImpl, 'Document');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport type { Inputs, Outputs } from '../GraphProcessor.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { type ChatMessage, type EditorDefinition } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { ChatNodeBase, type ChatNodeData } from './ChatNodeBase.js';\nimport { coerceType } from '../../utils/coerceType.js';\n\nexport type ChatLoopNode = ChartNode<'chatLoop', ChatLoopNodeData>;\n\nexport type ChatLoopNodeData = ChatNodeData & {\n  userPrompt: string;\n  renderingFormat?: 'text' | 'markdown';\n};\n\nexport class ChatLoopNodeImpl extends NodeImpl<ChatLoopNode> {\n  static create(): ChatLoopNode {\n    const chartNode: ChatLoopNode = {\n      type: 'chatLoop',\n      title: 'Chat Loop',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 250,\n      },\n      data: {\n        ...ChatNodeBase.defaultData(),\n        userPrompt: 'Your response:',\n        renderingFormat: 'markdown',\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    return ChatNodeBase.getInputDefinitions(this.data);\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        dataType: 'string[]',\n        id: 'conversation' as PortId,\n        title: 'Full Conversation',\n      },\n      {\n        dataType: 'string',\n        id: 'lastMessage' as PortId,\n        title: 'Last Message',\n      },\n    ];\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Creates an interactive chat loop with an AI model. The node will:\n        1. Send the initial prompt to the AI\n        2. Show the AI's response and prompt for user input\n        3. Send the user's input back to the AI\n        4. Repeat steps 2-3 until the user ends the conversation\n\n        The conversation history is maintained and sent with each new message.\n      `,\n      contextMenuTitle: 'Chat Loop',\n      infoBoxTitle: 'Chat Loop Node',\n      group: ['Convenience'],\n    };\n  }\n\n  getEditors(): EditorDefinition<ChatLoopNode>[] {\n    return [\n      ...ChatNodeBase.getEditors(),\n      {\n        type: 'code',\n        label: 'User Prompt',\n        dataKey: 'userPrompt',\n        language: 'plain-text',\n      },\n      {\n        type: 'group',\n        label: 'Rendering',\n        editors: [\n          {\n            type: 'dropdown',\n            dataKey: 'renderingFormat',\n            label: 'Format',\n            options: [\n              { label: 'Text', value: 'text' },\n              { label: 'Markdown', value: 'markdown' },\n            ],\n            defaultValue: 'markdown',\n          },\n        ],\n      },\n    ];\n  }\n\n  getBody() {\n    return ChatNodeBase.getBody(this.data);\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const conversation: ChatMessage[] = [];\n    let continueChat = true;\n\n    conversation.push(...coerceType(inputs['prompt' as PortId], 'chat-message[]'));\n\n    // Initial chat call\n    const initialResponse = await ChatNodeBase.process(this.data, this.chartNode, inputs, context);\n    const firstMessage = coerceType(initialResponse['response' as PortId], 'string');\n    conversation.push({\n      type: 'assistant',\n      message: firstMessage,\n      function_calls: undefined,\n      function_call: undefined,\n    });\n\n    let messageToUser = firstMessage;\n\n    while (continueChat) {\n      // Get user input\n      const userResponse = await context.requestUserInput([messageToUser], this.data.renderingFormat ?? 'text');\n\n      // Check if user wants to end conversation\n      if (!userResponse || userResponse.value.length === 0 || userResponse.value[0]?.length === 0) {\n        continueChat = false;\n        break;\n      }\n\n      // Add user message to conversation\n      conversation.push({\n        type: 'user',\n        message: userResponse.value[0]!,\n      });\n\n      // Prepare next AI message\n      const chatInputs = {\n        ...inputs,\n        prompt: {\n          type: 'chat-message[]',\n          value: conversation,\n        },\n      };\n\n      // Get AI response\n      const aiResponse = await ChatNodeBase.process(this.data, this.chartNode, chatInputs, context);\n      const aiMessage = coerceType(aiResponse['response' as PortId], 'string');\n      conversation.push({\n        type: 'assistant',\n        message: aiMessage,\n        function_calls: undefined,\n        function_call: undefined,\n      });\n\n      messageToUser = aiMessage;\n    }\n\n    return {\n      ['conversation' as PortId]: {\n        type: 'chat-message[]',\n        value: conversation,\n      },\n      ['lastMessage' as PortId]: {\n        type: 'chat-message',\n        value: conversation.at(-1)!,\n      },\n    };\n  }\n}\n\nexport const chatLoopNode = nodeDefinition(ChatLoopNodeImpl, 'Chat Loop');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type PortId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { type DataValue } from '../DataValue.js';\nimport { NodeImpl, type NodeBody, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { getInputOrData } from '../../utils/index.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { dedent } from 'ts-dedent';\nimport type { EditorDefinition } from '../EditorDefinition.js';\nimport type { Inputs } from '../GraphProcessor.js';\nimport { uint8ArrayToBase64 } from '../../utils/base64.js';\n\nexport type ReadAllFilesNode = ChartNode<'readAllFiles', ReadAllFilesNodeData>;\n\ntype ReadAllFilesNodeData = {\n  path: string;\n  usePathInput: boolean;\n\n  recursive: boolean;\n  useRecursiveInput: boolean;\n\n  filterGlobs: string[];\n  useFilterGlobsInput: boolean;\n\n  ignores?: string[];\n  useIgnoresInput: boolean;\n\n  asBinary?: boolean;\n  errorOnMissingFile?: boolean;\n};\n\ntype FileOutput = {\n  path: string;\n  content: string | Uint8Array;\n};\n\nexport class ReadAllFilesNodeImpl extends NodeImpl<ReadAllFilesNode> {\n  static create(): ReadAllFilesNode {\n    return {\n      id: nanoid() as NodeId,\n      type: 'readAllFiles',\n      title: 'Read All Files',\n      visualData: { x: 0, y: 0, width: 250 },\n      data: {\n        path: '',\n        usePathInput: false,\n        recursive: false,\n        useRecursiveInput: false,\n        filterGlobs: [],\n        useFilterGlobsInput: false,\n        ignores: [],\n        useIgnoresInput: false,\n        asBinary: false,\n        errorOnMissingFile: false,\n      },\n    };\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputDefinitions: NodeInputDefinition[] = [];\n\n    if (this.chartNode.data.usePathInput) {\n      inputDefinitions.push({\n        id: 'path' as PortId,\n        title: 'Path',\n        dataType: 'string',\n        required: true,\n        coerced: false,\n      });\n    }\n\n    if (this.chartNode.data.useRecursiveInput) {\n      inputDefinitions.push({\n        id: 'recursive' as PortId,\n        title: 'Recursive',\n        dataType: 'boolean',\n        required: true,\n        coerced: false,\n      });\n    }\n\n    if (this.chartNode.data.useFilterGlobsInput) {\n      inputDefinitions.push({\n        id: 'filterGlobs' as PortId,\n        title: 'Filter Globs',\n        dataType: 'string[]',\n        required: true,\n        coerced: false,\n      });\n    }\n\n    if (this.chartNode.data.useIgnoresInput) {\n      inputDefinitions.push({\n        id: 'ignores' as PortId,\n        title: 'Ignores',\n        dataType: 'string[]',\n        required: true,\n        coerced: false,\n      });\n    }\n\n    return inputDefinitions;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'files' as PortId,\n        title: 'Files',\n        dataType: 'object[]',\n      },\n      {\n        id: 'rootPath' as PortId,\n        title: 'Root Path',\n        dataType: 'string',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<ReadAllFilesNode>[] {\n    return [\n      {\n        type: 'directoryBrowser',\n        label: 'Path',\n        dataKey: 'path',\n        useInputToggleDataKey: 'usePathInput',\n      },\n      {\n        type: 'toggle',\n        label: 'Recursive',\n        dataKey: 'recursive',\n        useInputToggleDataKey: 'useRecursiveInput',\n      },\n      {\n        type: 'stringList',\n        label: 'Filter Globs',\n        dataKey: 'filterGlobs',\n        useInputToggleDataKey: 'useFilterGlobsInput',\n      },\n      {\n        type: 'stringList',\n        label: 'Ignores',\n        dataKey: 'ignores',\n        useInputToggleDataKey: 'useIgnoresInput',\n      },\n      {\n        type: 'toggle',\n        label: 'Read as Binary',\n        dataKey: 'asBinary',\n      },\n      {\n        type: 'toggle',\n        label: 'Error on Missing File',\n        dataKey: 'errorOnMissingFile',\n      },\n    ];\n  }\n\n  getBody(): NodeBody {\n    return dedent`\n      ${this.data.asBinary ? 'Read as Binary' : 'Read as Text'}\n      Path: ${this.data.usePathInput ? '(Input)' : this.data.path}\n      Recursive: ${this.data.useRecursiveInput ? '(Input)' : this.data.recursive}\n      Filters: ${\n        this.data.useFilterGlobsInput\n          ? '(Input)'\n          : this.data.filterGlobs.length > 0\n            ? this.data.filterGlobs.join(', ')\n            : 'None'\n      }\n    `;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Reads all files in the specified directory and outputs an array of objects containing each file's path and contents.\n        Each object has a 'path' (string) and 'content' (string or binary) property.\n      `,\n      infoBoxTitle: 'Read All Files Node',\n      contextMenuTitle: 'Read All Files',\n      group: ['Input/Output'],\n    };\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Record<PortId, DataValue>> {\n    const { nativeApi } = context;\n\n    if (nativeApi == null) {\n      throw new Error('This node requires a native API to run.');\n    }\n\n    const path = getInputOrData(this.chartNode.data, inputs, 'path');\n\n    const recursive = getInputOrData(this.data, inputs, 'recursive', 'boolean');\n    const filterGlobs = getInputOrData(this.data, inputs, 'filterGlobs', 'string[]');\n    const ignores = getInputOrData(this.data, inputs, 'ignores', 'string[]');\n\n    try {\n      // First read the directory\n      const filePaths = await nativeApi.readdir(path, undefined, {\n        recursive,\n        includeDirectories: false, // We only want files since we're reading contents\n        filterGlobs,\n        relative: true, // Always use relative paths in output\n        ignores,\n      });\n\n      // Then read each file\n      const filePromises = filePaths.map(async (filePath): Promise<FileOutput> => {\n        try {\n          if (this.data.asBinary) {\n            const content = await nativeApi.readBinaryFile(`${path}/${filePath}`);\n            const buffer = await content.arrayBuffer();\n            return {\n              path: filePath,\n              content: (await uint8ArrayToBase64(new Uint8Array(buffer))) ?? '',\n            };\n          } else {\n            const content = await nativeApi.readTextFile(`${path}/${filePath}`, undefined);\n            return {\n              path: filePath,\n              content,\n            };\n          }\n        } catch (err) {\n          if (this.chartNode.data.errorOnMissingFile) {\n            throw err;\n          }\n          return {\n            path: filePath,\n            content: this.data.asBinary ? new Uint8Array() : '',\n          };\n        }\n      });\n\n      const files = await Promise.all(filePromises);\n\n      return {\n        ['files' as PortId]: { type: 'object[]', value: files },\n        ['rootPath' as PortId]: { type: 'string', value: path },\n      };\n    } catch (err) {\n      if (this.chartNode.data.errorOnMissingFile) {\n        throw err;\n      }\n      return {\n        ['files' as PortId]: { type: 'object[]', value: [] },\n        ['rootPath' as PortId]: { type: 'string', value: path },\n      };\n    }\n  }\n}\n\nexport const readAllFilesNode = nodeDefinition(ReadAllFilesNodeImpl, 'Read All Files');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type EditorDefinition } from '../../index.js';\nimport { dedent } from 'ts-dedent';\nimport { coerceType } from '../../utils/coerceType.js';\n\nexport type ToMarkdownTableNode = ChartNode<'toMarkdownTable', ToMarkdownTableNodeData>;\n\nexport type ToMarkdownTableNodeData = {\n  includeHeaders?: boolean;\n  alignPipes?: boolean;\n};\n\nexport class ToMarkdownTableNodeImpl extends NodeImpl<ToMarkdownTableNode> {\n  static create(): ToMarkdownTableNode {\n    const chartNode: ToMarkdownTableNode = {\n      type: 'toMarkdownTable',\n      title: 'To Markdown Table',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 200,\n      },\n      data: {\n        includeHeaders: true,\n        alignPipes: false,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    return [\n      {\n        id: 'data' as PortId,\n        title: 'Data Array',\n        dataType: 'any',\n        required: true,\n      },\n    ];\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'markdown' as PortId,\n        title: 'Markdown Table',\n        dataType: 'string',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<ToMarkdownTableNode>[] {\n    return [\n      {\n        type: 'toggle',\n        label: 'Include Headers',\n        dataKey: 'includeHeaders',\n      },\n      {\n        type: 'toggle',\n        label: 'Align Pipes',\n        dataKey: 'alignPipes',\n      },\n    ];\n  }\n\n  getBody(): string | undefined {\n    const parts = [];\n    if (this.data.includeHeaders) parts.push('With Header Row');\n    if (this.data.alignPipes) parts.push('Pipes Aligned');\n    return parts.length > 0 ? parts.join(', ') : undefined;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Converts an array of objects into a markdown table format.\n        Input should be an array of objects with consistent keys.\n      `,\n      infoBoxTitle: 'To Markdown Table Node',\n      contextMenuTitle: 'To Markdown Table',\n      group: ['Text'],\n    };\n  }\n\n  async process(inputs: Inputs): Promise<Outputs> {\n    const data = coerceType(inputs['data' as PortId], 'object[]');\n\n    const keys = data.length === 0 ? [] : Object.keys(data[0]!);\n\n    // Dynamic import because these are ESM-only, and top level imports are converted to CommonJS for rivet-node.\n    // Dynamic import is able to load ESM-only modules.\n    const { toMarkdown } = await import('mdast-util-to-markdown');\n    const { gfmTableToMarkdown } = await import('mdast-util-gfm-table');\n\n    const markdownTable = toMarkdown(\n      {\n        type: 'table',\n        children: [\n          ...(this.data.includeHeaders\n            ? [\n                {\n                  type: 'tableRow' as const,\n                  children: keys.map((key) => ({\n                    type: 'tableCell' as const,\n                    children: [{ type: 'text' as const, value: key }],\n                  })),\n                },\n              ]\n            : []),\n          ...data.map((row) => ({\n            type: 'tableRow' as const,\n            children: keys.map((key) => ({\n              type: 'tableCell' as const,\n              children: [{ type: 'text' as const, value: `${row[key]}` }],\n            })),\n          })),\n        ],\n      },\n      {\n        extensions: [gfmTableToMarkdown({ tablePipeAlign: this.data.alignPipes })],\n      },\n    );\n\n    return {\n      ['markdown' as PortId]: {\n        type: 'string',\n        value: markdownTable,\n      },\n    };\n  }\n}\n\nexport const toMarkdownTableNode = nodeDefinition(ToMarkdownTableNodeImpl, 'To Markdown Table');\n", "import { nanoid } from 'nanoid';\nimport type { DataValue } from '../DataValue.js';\nimport type { ChartNode, NodeId, NodeInputDefinition, NodeOutputDefinition, PortId } from '../NodeBase.js';\nimport type { GraphId } from '../NodeGraph.js';\nimport { NodeImpl, type NodeBody } from '../NodeImpl.js';\nimport { dedent } from 'ts-dedent';\nimport type { EditorDefinition } from '../EditorDefinition.js';\nimport type { RivetUIContext } from '../RivetUIContext.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport type { InternalProcessContext } from '../ProcessContext.js';\nimport type { Inputs, Outputs } from '../GraphProcessor.js';\nimport { coerceTypeOptional } from '../../utils/coerceType.js';\nimport * as cronParser from 'cron-parser';\n\ntype TimeUnit = 'seconds' | 'minutes' | 'hours' | 'days' | 'weeks';\ntype ScheduleType = 'interval' | 'cron';\n\ninterface IntervalSchedule {\n  type: 'interval';\n  value: number;\n  unit: TimeUnit;\n}\n\ninterface CronSchedule {\n  type: 'cron';\n  expression: string;\n}\n\ntype Schedule = IntervalSchedule | CronSchedule;\n\nexport type CronNode = ChartNode<'cron', CronNodeData>;\n\nexport type CronNodeData = {\n  targetGraph: GraphId | undefined;\n  scheduleType: ScheduleType;\n  schedule: string;\n  executeImmediately?: boolean;\n\n  useTargetGraphInput?: boolean;\n};\n\nexport class CronNodeImpl extends NodeImpl<CronNode> {\n  static create(): CronNode {\n    const chartNode: CronNode = {\n      type: 'cron',\n      title: 'Cron',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 200,\n      },\n      data: {\n        targetGraph: undefined,\n        scheduleType: 'interval',\n        schedule: '5 minutes',\n        executeImmediately: true,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [];\n\n    inputs.push({\n      id: 'trigger' as PortId,\n      title: 'Trigger',\n      dataType: 'boolean',\n      description: 'Starts the scheduled job when true.',\n    });\n\n    if (this.data.useTargetGraphInput) {\n      inputs.push({\n        id: 'targetGraph' as PortId,\n        title: 'Target Graph',\n        dataType: 'string',\n        description: 'The subgraph to execute on schedule',\n      });\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'output' as PortId,\n        title: 'Last Output',\n        dataType: 'any',\n        description: 'The last output from the subgraph execution.',\n      },\n      {\n        id: 'iteration' as PortId,\n        title: 'Iteration',\n        dataType: 'number',\n        description: 'The current iteration number.',\n      },\n      {\n        id: 'completed' as PortId,\n        title: 'Completed',\n        dataType: 'boolean',\n        description: 'True when the job has completed.',\n      },\n      {\n        id: 'nextRun' as PortId,\n        title: 'Next Run',\n        dataType: 'string',\n        description: 'The scheduled time for the next execution.',\n      },\n    ];\n  }\n\n  static getUIData() {\n    return {\n      infoBoxBody: dedent`\n        Executes a subgraph on a schedule. Supports:\n        - Natural language (e.g., \"every 5 minutes\", \"daily at 3pm\")\n        - Cron expressions (e.g., \"0 * * * *\")\n        - Simple intervals (e.g., \"5 minutes\", \"1 hour\")\n      `,\n      infoBoxTitle: 'Cron Node',\n      contextMenuTitle: 'Cron',\n      group: ['Advanced'],\n    };\n  }\n\n  getEditors(): EditorDefinition<CronNode>[] {\n    return [\n      {\n        type: 'toggle',\n        dataKey: 'executeImmediately',\n        label: 'Execute Immediately',\n        helperMessage: 'Starts the job immediately when the node is run, in addition to the schedule',\n      },\n      {\n        type: 'graphSelector',\n        dataKey: 'targetGraph',\n        useInputToggleDataKey: 'useTargetGraphInput',\n        label: 'Target Graph',\n        helperMessage: 'The subgraph to execute on schedule',\n      },\n      {\n        type: 'dropdown',\n        dataKey: 'scheduleType',\n        label: 'Schedule Type',\n        options: [\n          { label: 'Cron Expression', value: 'cron' },\n          { label: 'Simple Interval', value: 'interval' },\n        ],\n        helperMessage: 'How to specify the schedule',\n      },\n      {\n        type: 'string',\n        dataKey: 'schedule',\n        label: 'Schedule',\n        helperMessage: dedent`\n          Examples:\n          Cron: \"*/5 * * * *\", \"0 15 * * *\"\n          Interval: \"5 minutes\", \"1 hour\", \"7 days\"\n        `,\n      },\n    ];\n  }\n\n  private parseSchedule(): Schedule {\n    const { scheduleType, schedule } = this.data;\n\n    if (scheduleType === 'cron') {\n      return { type: 'cron', expression: schedule };\n    }\n\n    // Parse interval\n    const match = schedule.match(/^(\\d+)\\s*(second|seconds|minute|minutes|hour|hours|day|days|week|weeks)$/i);\n    if (!match) {\n      throw new Error('Invalid interval format. Expected: \"number unit\" (e.g., \"5 minutes\")');\n    }\n\n    const value = parseInt(match[1]!, 10);\n    let unit = match[2]!.toLowerCase() as TimeUnit;\n\n    // Normalize unit to plural\n    if (unit.endsWith('s')) {\n      unit = unit as TimeUnit;\n    } else {\n      unit = `${unit}s` as TimeUnit;\n    }\n\n    return { type: 'interval', value, unit };\n  }\n\n  private getNextRunTime(schedule: Schedule): Date {\n    const now = new Date();\n\n    if (schedule.type === 'interval') {\n      const { value, unit } = schedule;\n      const next = new Date(now);\n\n      switch (unit) {\n        case 'seconds':\n          next.setSeconds(now.getSeconds() + value);\n          break;\n        case 'minutes':\n          next.setMinutes(now.getMinutes() + value);\n          break;\n        case 'hours':\n          next.setHours(now.getHours() + value);\n          break;\n        case 'days':\n          next.setDate(now.getDate() + value);\n          break;\n        case 'weeks':\n          next.setDate(now.getDate() + value * 7);\n          break;\n      }\n\n      return next;\n    }\n\n    if (schedule.type === 'cron') {\n      const cron = cronParser.parseExpression(schedule.expression, { currentDate: now });\n\n      const next = cron.next().toDate();\n      return next;\n    }\n\n    throw new Error('Invalid schedule type');\n  }\n\n  getBody(context: RivetUIContext): NodeBody {\n    if (!this.data.targetGraph && !this.data.useTargetGraphInput) {\n      return 'No target graph selected';\n    }\n\n    const graphName = this.data.useTargetGraphInput\n      ? 'graph from input'\n      : context.project.graphs[this.data.targetGraph!]?.metadata?.name ?? 'Unknown Graph';\n    return `Executes ${graphName}\\n${this.data.schedule}`;\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    if (inputs['trigger' as PortId] !== undefined) {\n      const trigger = coerceTypeOptional(inputs['trigger' as PortId], 'boolean');\n\n      if (!trigger) {\n        return {\n          ['completed' as PortId]: { type: 'boolean', value: false },\n          ['iteration' as PortId]: { type: 'number', value: 0 },\n        };\n      }\n    }\n\n    if (!this.data.targetGraph) {\n      throw new Error('No target graph selected');\n    }\n\n    let iteration = 0;\n    const schedule = this.parseSchedule();\n\n    let lastOutputs: Outputs = {};\n\n    let didExecuteFirstTime = !this.data.executeImmediately;\n\n    while (!context.signal.aborted) {\n      const nextRun = didExecuteFirstTime ? this.getNextRunTime(schedule) : new Date();\n      const delay = nextRun.getTime() - Date.now();\n\n      didExecuteFirstTime = true;\n\n      // Emit the next run time\n      const outputs: Outputs = {\n        ['output' as PortId]: lastOutputs\n          ? { type: 'object', value: lastOutputs as Record<string, unknown> }\n          : {\n              type: 'any',\n              value: null,\n            },\n        ['iteration' as PortId]: { type: 'number', value: iteration },\n        ['completed' as PortId]: { type: 'boolean', value: false },\n        ['nextRun' as PortId]: { type: 'string', value: nextRun.toISOString() },\n      };\n\n      if (delay > 0) {\n        await new Promise((resolve) => {\n          context.signal.addEventListener('abort', resolve, { once: true });\n\n          setTimeout(resolve, delay);\n        });\n      }\n\n      if (context.signal.aborted) {\n        throw new Error('Aborted');\n      }\n\n      iteration++;\n\n      const subprocessor = context.createSubProcessor(this.data.targetGraph, { signal: context.signal });\n      lastOutputs = await subprocessor.processGraph(\n        context,\n        lastOutputs as Record<string, DataValue>,\n        context.contextValues,\n      );\n\n      // Check for break signal\n      const breakSignal = coerceTypeOptional(lastOutputs['break' as PortId], 'boolean');\n      if (breakSignal === true) {\n        return {\n          ...outputs,\n          ['completed' as PortId]: { type: 'boolean', value: true },\n        };\n      }\n    }\n\n    return {\n      ['output' as PortId]: lastOutputs\n        ? { type: 'object', value: lastOutputs as Record<string, unknown> }\n        : { type: 'any', value: null },\n      ['iteration' as PortId]: { type: 'number', value: iteration },\n      ['completed' as PortId]: { type: 'boolean', value: true },\n      ['nextRun' as PortId]: { type: 'string', value: new Date().toISOString() },\n    };\n  }\n}\n\nexport const cronNode = nodeDefinition(CronNodeImpl, 'Cron');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type NodeOutputDefinition,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type DataValue } from '../DataValue.js';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { dedent } from 'ts-dedent';\nimport { coerceTypeOptional } from '../../utils/coerceType.js';\nimport { extractInterpolationVariables, interpolate } from '../../utils/interpolation.js';\nimport { get, sortBy } from 'lodash-es';\n\nexport type ToTreeNode = ChartNode<'toTree', ToTreeNodeData>;\n\nexport type ToTreeNodeData = {\n  format: string;\n  childrenProperty: string;\n  useSortAlphabetically: boolean;\n};\n\nexport class ToTreeNodeImpl extends NodeImpl<ToTreeNode> {\n  static create(): ToTreeNode {\n    const chartNode: ToTreeNode = {\n      type: 'toTree',\n      title: 'To Tree',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 300,\n      },\n      data: {\n        format: '{{path}}',\n        childrenProperty: 'children',\n        useSortAlphabetically: true,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    return [\n      {\n        id: 'objects' as PortId,\n        title: 'Objects',\n        dataType: ['object[]', 'object'],\n        required: true,\n      },\n    ];\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'tree' as PortId,\n        title: 'Tree',\n        dataType: 'string',\n      },\n    ];\n  }\n\n  getEditors(): EditorDefinition<ToTreeNode>[] {\n    return [\n      {\n        type: 'string',\n        label: 'Children Property',\n        dataKey: 'childrenProperty',\n      },\n      {\n        type: 'code',\n        label: 'Format',\n        dataKey: 'format',\n        language: 'prompt-interpolation-markdown',\n        theme: 'prompt-interpolation',\n      },\n      {\n        type: 'toggle',\n        label: 'Sort Alphabetically',\n        dataKey: 'useSortAlphabetically',\n      },\n    ];\n  }\n\n  getBody(): string {\n    return dedent`\n      Format: ${this.data.format}\n      Children: ${this.data.childrenProperty}\n      Sort: ${this.data.useSortAlphabetically ? 'Yes' : 'No'}\n    `;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Converts an array of objects into a tree structure and renders it as text.\n\n        The format field supports interpolation using {{property}} syntax to determine\n        how each node is displayed.\n\n        Use the children property to specify which field contains child nodes.\n      `,\n      infoBoxTitle: 'To Tree Node',\n      contextMenuTitle: 'To Tree',\n      group: ['Text'],\n    };\n  }\n\n  buildTree(objects: unknown[], parentPath: string = '', level: number = 0, isLast: boolean = true): string {\n    if (!Array.isArray(objects) || objects.length === 0) return '';\n\n    let result = '';\n    const sortedObjects = this.data.useSortAlphabetically\n      ? sortBy(objects, (obj) => String(get(obj, 'path', '')))\n      : objects;\n\n    sortedObjects.forEach((obj, index) => {\n      const isLastItem = index === sortedObjects.length - 1;\n      const prefix = level === 0 ? '' : isLast ? '\u2514\u2500\u2500 ' : '\u251C\u2500\u2500 ';\n      const indent = level === 0 ? '' : '    '.repeat(level - 1) + (isLast ? '    ' : '\u2502   ');\n\n      // Get all potential interpolation variables from the format string\n      const matches = extractInterpolationVariables(this.data.format);\n      const interpolationVars = matches.reduce(\n        (acc, match) => {\n          const key = match;\n          acc[key] = String(get(obj, key, ''));\n          return acc;\n        },\n        {} as Record<string, string>,\n      );\n\n      const formattedNode = interpolate(this.data.format, interpolationVars);\n\n      // Add this node to the result\n      result += indent + prefix + formattedNode + '\\n';\n\n      // Process children if they exist\n      const children = get(obj, this.data.childrenProperty);\n      if (Array.isArray(children) && children.length > 0) {\n        const newPath = parentPath ? `${parentPath}/${formattedNode}` : formattedNode;\n        result += this.buildTree(children, newPath, level + 1, isLastItem);\n      }\n    });\n\n    return result;\n  }\n\n  async process(inputs: Record<PortId, DataValue>): Promise<Record<PortId, DataValue>> {\n    const objects = coerceTypeOptional(inputs['objects' as PortId], 'object[]') ?? [];\n    const treeOutput = this.buildTree(objects);\n\n    return {\n      ['tree' as PortId]: {\n        type: 'string',\n        value: treeOutput,\n      },\n    };\n  }\n}\n\nexport const toTreeNode = nodeDefinition(ToTreeNodeImpl, 'To Tree');\n", "import {\n  type ChartNode,\n  type NodeConnection,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type GraphId } from '../NodeGraph.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { type Project } from '../Project.js';\nimport { type GraphInputNode } from './GraphInputNode.js';\nimport { type GraphOutputNode } from './GraphOutputNode.js';\nimport { type DataValue } from '../DataValue.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { dedent } from 'ts-dedent';\nimport type { RivetUIContext } from '../RivetUIContext.js';\n\ntype ConditionType = 'allOutputsSet' | 'inputEqual';\n\nexport type LoopUntilNode = ChartNode<'loopUntil', LoopUntilNodeData>;\n\nexport type LoopUntilNodeData = {\n  targetGraph: GraphId | undefined;\n  conditionType: ConditionType;\n  maxIterations?: number;\n\n  // For inputEqual condition\n  inputToCheck?: string;\n  targetValue?: string;\n\n  /** Data for each of the inputs of the subgraph */\n  inputData?: Record<string, DataValue>;\n};\n\nexport class LoopUntilNodeImpl extends NodeImpl<LoopUntilNode> {\n  static create(): LoopUntilNode {\n    const chartNode: LoopUntilNode = {\n      type: 'loopUntil',\n      title: 'Loop Until',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 200,\n      },\n      data: {\n        targetGraph: undefined,\n        conditionType: 'allOutputsSet',\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(\n    _connections: NodeConnection[],\n    _nodes: Record<NodeId, ChartNode>,\n    project: Project,\n  ): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [];\n\n    // Get inputs from the target graph\n    const graph = project.graphs[this.data.targetGraph ?? ('' as GraphId)];\n    if (graph) {\n      const inputNodes = graph.nodes.filter((node) => node.type === 'graphInput') as GraphInputNode[];\n      const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();\n\n      inputIds.forEach((id) => {\n        const inputNode = inputNodes.find((node) => node.data.id === id)!;\n        inputs.push({\n          id: id as PortId,\n          title: id,\n          dataType: inputNode.data.dataType,\n        });\n      });\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(\n    _connections: NodeConnection[],\n    _nodes: Record<NodeId, ChartNode>,\n    project: Project,\n  ): NodeOutputDefinition[] {\n    const outputs: NodeOutputDefinition[] = [];\n\n    // Get outputs from the target graph\n    const graph = project.graphs[this.data.targetGraph ?? ('' as GraphId)];\n    if (graph) {\n      const outputNodes = graph.nodes.filter((node) => node.type === 'graphOutput') as GraphOutputNode[];\n      const outputIds = [...new Set(outputNodes.map((node) => node.data.id))].sort();\n\n      outputIds.forEach((id) => {\n        const outputNode = outputNodes.find((node) => node.data.id === id)!;\n        outputs.push({\n          id: id as PortId,\n          title: id,\n          dataType: outputNode.data.dataType,\n        });\n      });\n    }\n\n    // Add standard loop outputs\n    outputs.push(\n      {\n        id: 'iteration' as PortId,\n        title: 'Iterations',\n        dataType: 'number',\n        description: 'The number of iterations completed.',\n      },\n      {\n        id: 'completed' as PortId,\n        title: 'Completed',\n        dataType: 'boolean',\n        description: 'True when the loop has completed.',\n      },\n    );\n\n    return outputs;\n  }\n\n  getEditors(context: RivetUIContext): EditorDefinition<LoopUntilNode>[] {\n    const definitions: EditorDefinition<LoopUntilNode>[] = [\n      {\n        type: 'graphSelector',\n        label: 'Target Graph',\n        dataKey: 'targetGraph',\n      },\n      {\n        type: 'dropdown',\n        dataKey: 'conditionType',\n        label: 'Stop Condition',\n        options: [\n          { label: 'All Outputs Set', value: 'allOutputsSet' },\n          { label: 'Input Equals Value', value: 'inputEqual' },\n        ],\n        helperMessage: 'The condition that will stop the loop',\n      },\n      {\n        type: 'number',\n        dataKey: 'maxIterations',\n        label: 'Max Iterations',\n        helperMessage: 'Maximum number of iterations (optional, leave empty for unlimited)',\n        allowEmpty: true,\n      },\n    ];\n\n    if (this.data.conditionType === 'inputEqual') {\n      definitions.push(\n        {\n          type: 'string',\n          dataKey: 'inputToCheck',\n          label: 'Input to Check',\n          helperMessage: 'The name of the input to compare',\n        },\n        {\n          type: 'string',\n          dataKey: 'targetValue',\n          label: 'Target Value',\n          helperMessage: 'The value to compare against',\n        },\n      );\n    }\n\n    // Add dynamic editors for graph inputs\n    if (this.data.targetGraph) {\n      const graph = context.project.graphs[this.data.targetGraph];\n      if (graph) {\n        const inputNodes = graph.nodes.filter((node) => node.type === 'graphInput') as GraphInputNode[];\n        const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();\n\n        for (const inputId of inputIds) {\n          const inputNode = inputNodes.find((node) => node.data.id === inputId)!;\n          definitions.push({\n            type: 'dynamic',\n            dataKey: 'inputData',\n            dynamicDataKey: inputNode.data.id,\n            dataType: inputNode.data.dataType,\n            label: inputNode.data.id,\n            editor: inputNode.data.editor ?? 'auto',\n          });\n        }\n      }\n    }\n\n    return definitions;\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Executes a subgraph in a loop until a condition is met. Each iteration's outputs become\n        the inputs for the next iteration. Supports different stopping conditions and optional\n        maximum iterations.\n      `,\n      infoBoxTitle: 'Loop Until Node',\n      contextMenuTitle: 'Loop Until',\n      group: ['Logic'],\n    };\n  }\n\n  getBody(context: RivetUIContext): string {\n    if (!this.data.targetGraph) {\n      return 'No target graph selected';\n    }\n\n    const graphName = context.project.graphs[this.data.targetGraph]?.metadata?.name ?? 'Unknown Graph';\n    const condition =\n      this.data.conditionType === 'allOutputsSet'\n        ? 'all outputs are set'\n        : `${this.data.inputToCheck} equals ${this.data.targetValue}`;\n\n    const maxIterations = this.data.maxIterations ? `\\nMax iterations: ${this.data.maxIterations}` : '';\n\n    return `Executes ${graphName}\\nuntil ${condition}${maxIterations}`;\n  }\n\n  private shouldBreak(outputs: Outputs): boolean {\n    if (this.data.conditionType === 'allOutputsSet') {\n      // Check if any output is control-flow-excluded\n      const anyInputIsExcluded = Object.values(outputs)\n        .filter((o) => o != null)\n        .some((output) => output.type === 'control-flow-excluded');\n      return !anyInputIsExcluded;\n    } else if (this.data.conditionType === 'inputEqual' && this.data.inputToCheck && this.data.targetValue) {\n      const inputValue = outputs[this.data.inputToCheck as PortId];\n      return inputValue?.value?.toString() === this.data.targetValue;\n    }\n\n    return false;\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    if (!this.data.targetGraph) {\n      throw new Error('No target graph selected');\n    }\n\n    let iteration = 0;\n    let currentInputs = { ...inputs };\n\n    // Add any default values from inputData\n    if (this.data.inputData) {\n      Object.entries(this.data.inputData).forEach(([key, value]) => {\n        if (currentInputs[key as PortId] === undefined) {\n          currentInputs[key as PortId] = value;\n        }\n      });\n    }\n\n    let lastOutputs: Outputs = {};\n\n    while (!context.signal.aborted) {\n      // Check max iterations if set\n      if (this.data.maxIterations && iteration >= this.data.maxIterations) {\n        break;\n      }\n\n      const subprocessor = context.createSubProcessor(this.data.targetGraph, { signal: context.signal });\n      lastOutputs = await subprocessor.processGraph(\n        context,\n        currentInputs as Record<string, DataValue>,\n        context.contextValues,\n      );\n\n      iteration++;\n\n      // Check if the condition is met\n      if (this.shouldBreak(lastOutputs)) {\n        break;\n      }\n\n      context.onPartialOutputs?.(lastOutputs);\n\n      // Use outputs as inputs for next iteration\n      currentInputs = lastOutputs;\n    }\n\n    return {\n      ...lastOutputs,\n      ['iteration' as PortId]: { type: 'number', value: iteration },\n      ['completed' as PortId]: { type: 'boolean', value: true },\n    };\n  }\n}\n\nexport const loopUntilNode = nodeDefinition(LoopUntilNodeImpl, 'Loop Until');\n", "import { nanoid } from 'nanoid';\nimport type { ChartNode, NodeId, NodeInputDefinition, NodeOutputDefinition, PortId } from '../NodeBase.js';\nimport { NodeImpl } from '../NodeImpl.js';\nimport type { EditorDefinition } from '../EditorDefinition.js';\nimport {\n  type GptFunction,\n  type Inputs,\n  type InternalProcessContext,\n  type NodeUIData,\n  type Outputs,\n} from '../../index.js';\n\nimport { MCPError, MCPErrorType, type MCP } from '../../integrations/mcp/MCPProvider.js';\n\nimport { dedent, getInputOrData } from '../../utils/index.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport type { RivetUIContext } from '../RivetUIContext.js';\nimport { getServerHelperMessage, getServerOptions, loadMCPConfiguration } from '../../integrations/mcp/MCPUtils.js';\nimport { getMCPBaseInputs, type MCPBaseNodeData } from '../../integrations/mcp/MCPBase.js';\n\ntype MCPDiscoveryNode = ChartNode<'mcpDiscovery', MCPDiscoveryNodeData>;\n\nexport type MCPDiscoveryNodeData = MCPBaseNodeData & { useToolsOutput?: boolean; usePromptsOutput?: boolean };\n\nclass MCPDiscoveryNodeImpl extends NodeImpl<MCPDiscoveryNode> {\n  static create(): MCPDiscoveryNode {\n    const chartNode: MCPDiscoveryNode = {\n      type: 'mcpDiscovery',\n      title: 'MCP Discovery',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 250,\n      },\n      data: {\n        name: 'mcp-client',\n        version: '1.0.0',\n        transportType: 'stdio',\n        serverUrl: 'http://localhost:8080/mcp',\n        serverId: '',\n        useNameInput: false,\n        useVersionInput: false,\n        useToolsOutput: true,\n        usePromptsOutput: true,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = getMCPBaseInputs(this.data);\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    const outputDefinitions: NodeOutputDefinition[] = [];\n\n    if (this.data.useToolsOutput) {\n      outputDefinitions.push({\n        id: 'tools' as PortId,\n        title: 'Tools',\n        dataType: 'object[]',\n        description: 'Tools returned from the MCP server',\n      });\n    }\n\n    if (this.data.usePromptsOutput) {\n      outputDefinitions.push({\n        id: 'prompts' as PortId,\n        title: 'Prompts',\n        dataType: 'object[]',\n        description: 'Prompts returned from the MCP server',\n      });\n    }\n    return outputDefinitions;\n  }\n\n  async getEditors(context: RivetUIContext): Promise<EditorDefinition<MCPDiscoveryNode>[]> {\n    const editors: EditorDefinition<MCPDiscoveryNode>[] = [\n      {\n        type: 'toggle',\n        label: 'Output Tools',\n        dataKey: 'useToolsOutput',\n        helperMessage: 'Toggle on if you want to get a Tools output',\n      },\n      {\n        type: 'toggle',\n        label: 'Output Prompts',\n        dataKey: 'usePromptsOutput',\n        helperMessage: 'Toggle on if you want to get a Prompts output',\n      },\n      {\n        type: 'string',\n        label: 'Name',\n        dataKey: 'name',\n        useInputToggleDataKey: 'useNameInput',\n        helperMessage: 'The name for the MCP Client',\n      },\n      {\n        type: 'string',\n        label: 'Version',\n        dataKey: 'version',\n        useInputToggleDataKey: 'useVersionInput',\n        helperMessage: 'A version for the MCP Client',\n      },\n\n      {\n        type: 'dropdown',\n        label: 'Transport Type',\n        dataKey: 'transportType',\n        options: [\n          { label: 'HTTP', value: 'http' },\n          { label: 'STDIO', value: 'stdio' },\n        ],\n      },\n    ];\n\n    if (this.data.transportType === 'http') {\n      editors.push({\n        type: 'string',\n        label: 'Server URL',\n        dataKey: 'serverUrl',\n        useInputToggleDataKey: 'useServerUrlInput',\n        helperMessage: 'The base URL endpoint for the MCP server with `/mcp`',\n      });\n    } else if (this.data.transportType === 'stdio') {\n      const serverOptions = await getServerOptions(context);\n\n      editors.push({\n        type: 'dropdown',\n        label: 'Server ID',\n        dataKey: 'serverId',\n        helperMessage: getServerHelperMessage(context, serverOptions.length),\n        options: serverOptions,\n      });\n    }\n    return editors;\n  }\n\n  getBody(context: RivetUIContext): string {\n    let base;\n    if (this.data.transportType === 'http') {\n      base = this.data.useServerUrlInput ? '(Using Server URL Input)' : this.data.serverUrl;\n    } else {\n      base = `Server ID: ${this.data.serverId || '(None)'}`;\n    }\n    const namePart = `Name: ${this.data.name}`;\n    const versionPart = `Version: ${this.data.version}`;\n    const parts = [namePart, versionPart, base];\n\n    if (context.executor !== 'nodejs') {\n      parts.push('(Requires Node Executor)');\n    }\n\n    return parts.join('\\n');\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Connects to an MCP (Model Context Protocol) server to discover capabilities like tools and prompts.\n      `,\n      infoBoxTitle: 'MCP Discovery Node',\n      contextMenuTitle: 'MCP Discovery',\n      group: ['MCP'],\n    };\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const name = getInputOrData(this.data, inputs, 'name', 'string');\n    const version = getInputOrData(this.data, inputs, 'version', 'string');\n\n    const transportType = getInputOrData(this.data, inputs, 'transportType', 'string') as 'http' | 'stdio';\n\n    let tools: MCP.Tool[] = [];\n    let prompts: MCP.Prompt[] = [];\n\n    try {\n      if (!context.mcpProvider) {\n        throw new Error('MCP Provider not found');\n      }\n\n      if (transportType === 'http') {\n        const serverUrl = getInputOrData(this.data, inputs, 'serverUrl', 'string');\n        if (!serverUrl || serverUrl === '') {\n          throw new MCPError(MCPErrorType.SERVER_NOT_FOUND, 'No server URL was provided');\n        }\n        if (!serverUrl.includes('/mcp')) {\n          throw new MCPError(\n            MCPErrorType.SERVER_COMMUNICATION_FAILED,\n            'Include /mcp in your server URL. For example: http://localhost:8080/mcp',\n          );\n        }\n\n        tools = await context.mcpProvider.getHTTPTools({ name, version }, serverUrl);\n        prompts = await context.mcpProvider.getHTTPrompts({ name, version }, serverUrl);\n      } else if (transportType === 'stdio') {\n        const serverId = this.data.serverId ?? '';\n\n        const mcpConfig = await loadMCPConfiguration(context);\n        if (!mcpConfig.mcpServers[serverId]) {\n          throw new MCPError(MCPErrorType.SERVER_NOT_FOUND, `Server ${serverId} not found in MCP config`);\n        }\n\n        const serverConfig = {\n          config: mcpConfig.mcpServers[serverId],\n          serverId,\n        };\n\n        tools = await context.mcpProvider.getStdioTools({ name, version }, serverConfig);\n        prompts = await context.mcpProvider.getStdioPrompts({ name, version }, serverConfig);\n      }\n\n      const output: Outputs = {};\n\n      const gptFunctions: GptFunction[] = tools.map((tool) => ({\n        name: tool.name,\n        description: tool.description ?? '',\n        parameters: tool.inputSchema,\n        strict: false,\n      }));\n\n      if (this.data.useToolsOutput) {\n        output['tools' as PortId] = {\n          type: 'gpt-function[]',\n          value: gptFunctions,\n        };\n      }\n\n      if (this.data.usePromptsOutput) {\n        output['prompts' as PortId] = {\n          type: 'object[]',\n          value: prompts.map((prompt) => ({\n            name: prompt.name,\n            description: prompt.description,\n            arguments: prompt.arugments,\n          })),\n        };\n      }\n\n      return output;\n    } catch (err) {\n      if (context.executor === 'browser') {\n        throw new Error('Failed to create Client without Node Executor');\n      }\n\n      throw err;\n    }\n  }\n}\n\nexport const mcpDiscoveryNode = nodeDefinition(MCPDiscoveryNodeImpl, 'MCP Discovery');\n", "/**\n * Derived from types here - https://github.com/modelcontextprotocol/typescript-sdk/blob/main/src/types.ts\n */\n\nexport namespace MCP {\n  export type TransportType = 'stdio' | 'http';\n\n  export interface ServerConfig {\n    command: string;\n    args?: string[];\n    env?: Record<string, string>;\n    disabled?: boolean;\n    alwaysAllow?: string[];\n  }\n\n  export type ServerConfigWithId = {\n    config: ServerConfig;\n    serverId: string;\n  };\n\n  export interface Config {\n    mcpServers: Record<string, ServerConfig>;\n  }\n\n  /**\n   * Tools\n   */\n  interface ToolAnnotations {\n    title?: string;\n    readOnlyHint?: boolean;\n    destructiveHint?: boolean;\n    idempotentHint?: boolean;\n    openWorldHint?: boolean;\n  }\n\n  export interface Tool {\n    name: string;\n    description?: string;\n    inputSchema: { [x: string]: unknown };\n    annotations?: ToolAnnotations;\n  }\n\n  export interface ToolCallRequest {\n    [key: string]: unknown;\n    name: string;\n    arguments?: { [x: string]: unknown };\n    id?: string;\n  }\n\n  export interface ToolCallResponse {\n    content: ResponseContent[];\n    isError?: boolean;\n  }\n\n  /**\n   * Prompts\n   */\n  interface PromptArgument {\n    name: string;\n    description?: string;\n    required?: boolean;\n  }\n  export interface Prompt {\n    name: string;\n    description?: string;\n    arugments?: PromptArgument[];\n  }\n\n  export interface GetPromptRequest {\n    [x: string]: unknown;\n    name: string;\n    arguments?: { [x: string]: string };\n  }\n\n  export interface PromptMessage {\n    role: 'user' | 'assistant';\n    content: ResponseContent;\n  }\n  export interface GetPromptResponse {\n    messages: PromptMessage[];\n    description?: string;\n  }\n\n  /**\n   * Content\n   */\n  interface BaseContent {\n    type: 'text' | 'image' | 'audio';\n  }\n  interface TextContent extends BaseContent {\n    type: 'text';\n    text: string;\n  }\n\n  interface ImageContent extends BaseContent {\n    type: 'image';\n    data: string;\n    mimeType: string;\n  }\n\n  interface AudioContent extends BaseContent {\n    type: 'audio';\n    data: string;\n    mimeType: string;\n  }\n\n  type ResponseContent = TextContent | ImageContent | AudioContent | { [key: string]: unknown };\n}\n\n/**\n * Errors\n */\nexport enum MCPErrorType {\n  CONFIG_NOT_FOUND = 'CONFIG_NOT_FOUND',\n  SERVER_NOT_FOUND = 'SERVER_NOT_FOUND',\n  SERVER_COMMUNICATION_FAILED = 'SERVER_COMMUNICATION_FAILED',\n  INVALID_SCHEMA = 'INVALID_SCHEMA',\n}\n\nexport class MCPError extends Error {\n  constructor(\n    public type: MCPErrorType,\n    message: string,\n    public details?: unknown,\n  ) {\n    super(message);\n    this.name = 'Error';\n  }\n}\n\n/**\n * MCP Provider for Node Implementation\n */\n\nexport interface MCPProvider {\n  getHTTPTools(clientConfig: { name: string; version: string }, serverUrl: string): Promise<MCP.Tool[]>;\n\n  getStdioTools(\n    clientConfig: { name: string; version: string },\n    serverConfig: MCP.ServerConfigWithId,\n  ): Promise<MCP.Tool[]>;\n\n  getHTTPrompts(clientConfig: { name: string; version: string }, serverUrl: string): Promise<MCP.Prompt[]>;\n\n  getStdioPrompts(\n    clientConfig: { name: string; version: string },\n    serverConfig: MCP.ServerConfigWithId,\n  ): Promise<MCP.Prompt[]>;\n\n  httpToolCall(\n    clientConfig: { name: string; version: string },\n    serverUrl: string,\n    toolCall: MCP.ToolCallRequest,\n  ): Promise<MCP.ToolCallResponse>;\n\n  stdioToolCall(\n    clientConfig: { name: string; version: string },\n    serverConfig: MCP.ServerConfigWithId,\n    toolCall: MCP.ToolCallRequest,\n  ): Promise<MCP.ToolCallResponse>;\n\n  getHTTPrompt(\n    clientConfig: { name: string; version: string },\n    serverUrl: string,\n    getPromptRequest: MCP.GetPromptRequest,\n  ): Promise<MCP.GetPromptResponse>;\n\n  getStdioPrompt(\n    clientConfig: { name: string; version: string },\n    serverConfig: MCP.ServerConfigWithId,\n    getPromptRequest: MCP.GetPromptRequest,\n  ): Promise<MCP.GetPromptResponse>;\n}\n", "import type { InternalProcessContext } from '../../model/ProcessContext.js';\nimport type { RivetUIContext } from '../../model/RivetUIContext.js';\nimport { MCPError, MCPErrorType, type MCP } from './MCPProvider.js';\n\nexport const loadMCPConfiguration = async (context: InternalProcessContext | RivetUIContext): Promise<MCP.Config> => {\n  if (context.executor !== 'nodejs') {\n    throw new MCPError(MCPErrorType.CONFIG_NOT_FOUND, 'MCP config is not supported in browser environment');\n  }\n\n  const mcpConfig = context.project.metadata.mcpServer;\n  if (!mcpConfig || mcpConfig.mcpServers == null) {\n    throw new MCPError(MCPErrorType.CONFIG_NOT_FOUND, 'MCP configuration not defined in Project tab');\n  }\n\n  return mcpConfig;\n};\n\nexport const getServerOptions = async (context: RivetUIContext): Promise<{ label: string; value: string }[]> => {\n  if (context.executor === 'nodejs' && context.nativeApi) {\n    try {\n      const config = await loadMCPConfiguration(context);\n\n      return Object.entries(config.mcpServers)\n        .filter(([, config]) => !config.disabled)\n        .map(([id]) => ({\n          label: id,\n          value: id,\n        }));\n    } catch {}\n  }\n  return [];\n};\n\nexport const getServerHelperMessage = (context: RivetUIContext, optionsLength: number): string => {\n  if (optionsLength > 0) return 'Select an MCP server from local configuration located in the Project tab';\n  if (context.executor !== 'nodejs') return 'MCP nodes require Node Executor';\n  return 'No MCP servers found in config';\n};\n", "import type { EditorDefinition } from '../../model/EditorDefinition.js';\nimport type { ChartNode, NodeInputDefinition, PortId } from '../../model/NodeBase.js';\nimport type { RivetUIContext } from '../../model/RivetUIContext.js';\nimport type { MCP } from './MCPProvider.js';\nimport { getServerHelperMessage, getServerOptions } from './MCPUtils.js';\n\nexport interface MCPBaseNodeData {\n  name: string;\n  version: string;\n  transportType: MCP.TransportType;\n  serverUrl?: string;\n  serverId?: string;\n\n  // Input toggles\n  useNameInput?: boolean;\n  useVersionInput?: boolean;\n  useServerUrlInput?: boolean;\n  useServerIdInput?: boolean;\n}\n\nexport type MCPBaseNode = ChartNode<'mcpBase', MCPBaseNodeData>;\n\nexport const getMCPBaseInputs = (data: MCPBaseNodeData) => {\n  const inputs: NodeInputDefinition[] = [];\n\n  if (data.useNameInput) {\n    inputs.push({\n      dataType: 'string',\n      id: 'name' as PortId,\n      title: 'Name',\n    });\n  }\n\n  if (data.useVersionInput) {\n    inputs.push({\n      dataType: 'string',\n      id: 'version' as PortId,\n      title: 'Version',\n    });\n  }\n\n  if (data.transportType === 'http' && data.useServerUrlInput) {\n    inputs.push({\n      dataType: 'string',\n      id: 'serverUrl' as PortId,\n      title: 'Server URL',\n      description: 'The endpoint URL for the MCP server',\n    });\n  }\n\n  return inputs;\n};\n\nexport const getMCPBaseEditors = async (\n  context: RivetUIContext,\n  data: MCPBaseNodeData,\n): Promise<EditorDefinition<MCPBaseNode>[]> => {\n  const editors = [];\n\n  editors.push([\n    {\n      type: 'toggle',\n      label: 'Output Tools',\n      dataKey: 'useToolsOutput',\n      helperMessage: 'Toggle on if you want to get a Tools output',\n    },\n    {\n      type: 'toggle',\n      label: 'Output Prompts',\n      dataKey: 'usePromptsOutput',\n      helperMessage: 'Toggle on if you want to get a Prompts output',\n    },\n    {\n      type: 'string',\n      label: 'Name',\n      dataKey: 'name',\n      useInputToggleDataKey: 'useNameInput',\n      helperMessage: 'The name for the MCP Client',\n    },\n    {\n      type: 'string',\n      label: 'Version',\n      dataKey: 'version',\n      useInputToggleDataKey: 'useVersionInput',\n      helperMessage: 'A version for the MCP Client',\n    },\n\n    {\n      type: 'dropdown',\n      label: 'Transport Type',\n      dataKey: 'transportType',\n      options: [\n        { label: 'HTTP', value: 'http' },\n        { label: 'STDIO', value: 'stdio' },\n      ],\n    },\n  ]);\n\n  if (data.transportType === 'http') {\n    editors.push({\n      type: 'string',\n      label: 'Server URL',\n      dataKey: 'serverUrl',\n      useInputToggleDataKey: 'useServerUrlInput',\n      helperMessage: 'The endpoint URL for the MCP server to connect',\n    });\n  } else if (data.transportType === 'stdio') {\n    const serverOptions = await getServerOptions(context);\n\n    editors.push({\n      type: 'dropdown',\n      label: 'Server ID',\n      dataKey: 'serverId',\n      helperMessage: getServerHelperMessage(context, serverOptions.length),\n      options: serverOptions,\n    });\n  }\n  return editors as EditorDefinition<MCPBaseNode>[];\n};\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\n\nimport { type InternalProcessContext } from '../../index.js';\n\nimport { MCPError, MCPErrorType, type MCP } from '../../integrations/mcp/MCPProvider.js';\nimport { coerceTypeOptional } from '../../utils/coerceType.js';\n\nimport { getInputOrData } from '../../utils/index.js';\nimport { getError } from '../../utils/errors.js';\nimport { getMCPBaseInputs, type MCPBaseNodeData } from '../../integrations/mcp/MCPBase.js';\nimport { getServerHelperMessage, getServerOptions, loadMCPConfiguration } from '../../integrations/mcp/MCPUtils.js';\nimport type { RivetUIContext } from '../RivetUIContext.js';\nimport { dedent } from 'ts-dedent';\nimport { type EditorDefinition } from '../EditorDefinition.js';\nimport { interpolate } from '../../utils/interpolation.js';\nimport { keys } from '../../utils/typeSafety.js';\n\nexport type MCPToolCallNode = ChartNode<'mcpToolCall', MCPToolCallNodeData>;\n\nexport type MCPToolCallNodeData = MCPBaseNodeData & {\n  toolName: string;\n  toolArguments?: string;\n  toolCallId?: string;\n\n  useToolNameInput?: boolean;\n  useToolArgumentsInput?: boolean;\n  useToolCallIdInput?: boolean;\n};\n\nexport class MCPToolCallNodeImpl extends NodeImpl<MCPToolCallNode> {\n  static create(): MCPToolCallNode {\n    const chartNode: MCPToolCallNode = {\n      type: 'mcpToolCall',\n      title: 'MCP Tool Call',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 250,\n      },\n      data: {\n        name: 'mcp-tool-call-client',\n        version: '1.0.0',\n        transportType: 'stdio',\n        serverUrl: 'http://localhost:8080/mcp',\n        serverId: '',\n        toolName: '',\n        toolArguments: dedent`\n        {\n          \"key\": \"value\"\n        }`,\n        toolCallId: '',\n        useNameInput: false,\n        useVersionInput: false,\n        useToolNameInput: true,\n        useToolArgumentsInput: true,\n        useToolCallIdInput: true,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = getMCPBaseInputs(this.data);\n\n    if (this.data.useToolNameInput) {\n      inputs.push({\n        dataType: 'string',\n        id: 'toolName' as PortId,\n        title: 'Tool Name',\n      });\n    }\n\n    if (this.data.useToolArgumentsInput) {\n      inputs.push({\n        dataType: 'object',\n        id: 'toolArguments' as PortId,\n        title: 'Tool Arguments',\n      });\n    }\n\n    if (this.data.useToolCallIdInput) {\n      inputs.push({\n        dataType: 'object',\n        id: 'toolCallId' as PortId,\n        title: 'Tool ID',\n      });\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    const outputDefinitions: NodeOutputDefinition[] = [];\n\n    outputDefinitions.push({\n      id: 'response' as PortId,\n      title: 'Response',\n      dataType: 'object',\n      description: 'Response from the Tool Call',\n    });\n\n    outputDefinitions.push({\n      id: 'toolCallId' as PortId,\n      title: 'Tool ID',\n      dataType: 'string',\n      description: 'ID associated with the Tool Call',\n    });\n\n    return outputDefinitions;\n  }\n\n  async getEditors(context: RivetUIContext): Promise<EditorDefinition<MCPToolCallNode>[]> {\n    const editors: EditorDefinition<MCPToolCallNode>[] = [\n      {\n        type: 'string',\n        label: 'Name',\n        dataKey: 'name',\n        useInputToggleDataKey: 'useNameInput',\n        helperMessage: 'The name for the MCP Client',\n      },\n      {\n        type: 'string',\n        label: 'Version',\n        dataKey: 'version',\n        useInputToggleDataKey: 'useVersionInput',\n        helperMessage: 'A version for the MCP Client',\n      },\n      {\n        type: 'dropdown',\n        label: 'Transport Type',\n        dataKey: 'transportType',\n        options: [\n          { label: 'HTTP', value: 'http' },\n          { label: 'STDIO', value: 'stdio' },\n        ],\n      },\n      {\n        type: 'string',\n        label: 'Tool Name',\n        dataKey: 'toolName',\n        useInputToggleDataKey: 'useToolNameInput',\n        helperMessage: 'The name for the MCP Tool Call',\n      },\n      {\n        type: 'code',\n        label: 'Tool Arguments',\n        dataKey: 'toolArguments',\n        language: 'json',\n        useInputToggleDataKey: 'useToolArgumentsInput',\n      },\n      {\n        type: 'string',\n        label: 'Tool ID',\n        dataKey: 'toolCallId',\n        useInputToggleDataKey: 'useToolCallIdInput',\n        helperMessage: 'The name for the MCP Tool Call',\n      },\n    ];\n\n    if (this.data.transportType === 'http') {\n      editors.push({\n        type: 'string',\n        label: 'Server URL',\n        dataKey: 'serverUrl',\n        useInputToggleDataKey: 'useServerUrlInput',\n        helperMessage: 'The endpoint URL for the MCP server to connect',\n      });\n    } else if (this.data.transportType === 'stdio') {\n      const serverOptions = await getServerOptions(context);\n\n      editors.push({\n        type: 'dropdown',\n        label: 'Server ID',\n        dataKey: 'serverId',\n        helperMessage: getServerHelperMessage(context, serverOptions.length),\n        options: serverOptions,\n      });\n    }\n\n    return editors;\n  }\n\n  getBody(context: RivetUIContext): string {\n    let base;\n    if (this.data.transportType === 'http') {\n      base = this.data.useServerUrlInput ? '(Using Server URL Input)' : this.data.serverUrl;\n    } else {\n      base = `Server ID: ${this.data.serverId || '(None)'}`;\n    }\n    const namePart = `Name: ${this.data.name}`;\n    const versionPart = `Version: ${this.data.version}`;\n    const parts = [namePart, versionPart, base];\n\n    if (context.executor !== 'nodejs') {\n      parts.push('(Requires Node Executor)');\n    }\n\n    return parts.join('\\n');\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Connects to an MCP (Model Context Protocol) server and gets a tool call response.\n      `,\n      infoBoxTitle: 'MCP Tool Call Node',\n      contextMenuTitle: 'MCP Tool Call',\n      group: ['MCP'],\n    };\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const name = getInputOrData(this.data, inputs, 'name', 'string');\n    const version = getInputOrData(this.data, inputs, 'version', 'string');\n\n    const toolName = getInputOrData(this.data, inputs, 'toolName', 'string');\n\n    const toolCallId = getInputOrData(this.data, inputs, 'toolCallId', 'string');\n\n    let toolArguments;\n\n    if (this.data.useToolArgumentsInput) {\n      toolArguments = getInputOrData(this.data, inputs, 'toolArguments', 'object');\n      if (toolArguments == null) {\n        throw new MCPError(MCPErrorType.INVALID_SCHEMA, 'Cannot parse tool argument with input toggle on');\n      }\n    } else {\n      const inputMap = keys(inputs)\n        .filter((key) => key.startsWith('input'))\n        .reduce(\n          (acc, key) => {\n            const stringValue = coerceTypeOptional(inputs[key], 'string') ?? '';\n\n            const interpolationKey = key.slice('input-'.length);\n            acc[interpolationKey] = stringValue;\n            return acc;\n          },\n          {} as Record<string, string>,\n        );\n\n      const interpolated = interpolate(this.data.toolArguments ?? '', inputMap);\n\n      toolArguments = JSON.parse(interpolated);\n    }\n\n    const toolCall: MCP.ToolCallRequest = {\n      name: toolName,\n      arguments: toolArguments,\n    };\n\n    const transportType = getInputOrData(this.data, inputs, 'transportType', 'string') as 'http' | 'stdio';\n\n    let toolResponse: MCP.ToolCallResponse | undefined = undefined;\n\n    try {\n      if (!context.mcpProvider) {\n        throw new Error('MCP Provider not found');\n      }\n\n      if (transportType === 'http') {\n        const serverUrl = getInputOrData(this.data, inputs, 'serverUrl', 'string');\n        if (!serverUrl || serverUrl === '') {\n          throw new MCPError(MCPErrorType.SERVER_NOT_FOUND, 'No server URL was provided');\n        }\n        if (!serverUrl.includes('/mcp')) {\n          throw new MCPError(\n            MCPErrorType.SERVER_COMMUNICATION_FAILED,\n            'Include /mcp in your server URL. For example: http://localhost:8080/mcp',\n          );\n        }\n\n        toolResponse = await context.mcpProvider.httpToolCall({ name, version }, serverUrl, toolCall);\n      } else if (transportType === 'stdio') {\n        const serverId = this.data.serverId ?? '';\n\n        const mcpConfig = await loadMCPConfiguration(context);\n        if (!mcpConfig.mcpServers[serverId]) {\n          throw new MCPError(MCPErrorType.SERVER_NOT_FOUND, `Server ${serverId} not found in MCP config`);\n        }\n\n        const serverConfig = {\n          config: mcpConfig.mcpServers[serverId],\n          serverId,\n        };\n\n        toolResponse = await context.mcpProvider.stdioToolCall({ name, version }, serverConfig, toolCall);\n      }\n\n      const output: Outputs = {};\n\n      output['response' as PortId] = {\n        type: 'object[]',\n        value: toolResponse?.content as unknown as Record<string, unknown>[],\n      };\n\n      output['toolCallId' as PortId] = {\n        type: 'string',\n        value: toolCallId,\n      };\n\n      return output;\n    } catch (err) {\n      const { message } = getError(err);\n      if (context.executor === 'browser') {\n        throw new Error('Failed to create Client without a node executor');\n      }\n      console.log(message);\n      throw err;\n    }\n  }\n}\n\nexport const mcpToolCallNode = nodeDefinition(MCPToolCallNodeImpl, 'MCP Tool Call');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { NodeImpl, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\n\nimport { type EditorDefinition, type InternalProcessContext } from '../../index.js';\n\nimport { MCPError, MCPErrorType, type MCP } from '../../integrations/mcp/MCPProvider.js';\n\nimport { coerceTypeOptional } from '../../utils/coerceType.js';\n\nimport { dedent, getInputOrData } from '../../utils/index.js';\nimport { getError } from '../../utils/errors.js';\nimport { getMCPBaseInputs, type MCPBaseNodeData } from '../../integrations/mcp/MCPBase.js';\nimport { getServerHelperMessage, getServerOptions, loadMCPConfiguration } from '../../integrations/mcp/MCPUtils.js';\nimport type { RivetUIContext } from '../RivetUIContext.js';\nimport { keys } from '../../utils/typeSafety.js';\nimport { interpolate } from '../../utils/interpolation.js';\n\nexport type MCPGetPromptNode = ChartNode<'mcpGetPrompt', MCPGetPromptNodeData>;\n\nexport type MCPGetPromptNodeData = MCPBaseNodeData & {\n  promptName: string;\n  promptArguments?: string;\n\n  usePromptNameInput?: boolean;\n  usePromptArgumentsInput?: boolean;\n};\n\nexport class MCPGetPromptNodeImpl extends NodeImpl<MCPGetPromptNode> {\n  static create(): MCPGetPromptNode {\n    const chartNode: MCPGetPromptNode = {\n      type: 'mcpGetPrompt',\n      title: 'MCP Get Prompt',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 250,\n      },\n      data: {\n        name: 'mcp-get-prompt-client',\n        version: '1.0.0',\n        transportType: 'stdio',\n        serverUrl: 'http://localhost:8080/mcp',\n        serverId: '',\n        promptName: '',\n        promptArguments: dedent`\n        {\n          \"key\": \"value\"\n        }`,\n        useNameInput: false,\n        useVersionInput: false,\n        usePromptNameInput: false,\n        usePromptArgumentsInput: false,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = getMCPBaseInputs(this.data);\n\n    if (this.data.usePromptNameInput) {\n      inputs.push({\n        dataType: 'string',\n        id: 'promptName' as PortId,\n        title: 'Prompt Name',\n      });\n    }\n\n    if (this.data.usePromptArgumentsInput) {\n      inputs.push({\n        dataType: 'object',\n        id: 'promptArguments' as PortId,\n        title: 'Prompt Arguments',\n      });\n    }\n\n    return inputs;\n  }\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    const outputDefinitions: NodeOutputDefinition[] = [];\n\n    outputDefinitions.push({\n      id: 'prompt' as PortId,\n      title: 'Prompt',\n      dataType: 'object',\n      description: 'Prompt response result',\n    });\n\n    return outputDefinitions;\n  }\n\n  async getEditors(context: RivetUIContext): Promise<EditorDefinition<MCPGetPromptNode>[]> {\n    const editors: EditorDefinition<MCPGetPromptNode>[] = [\n      {\n        type: 'string',\n        label: 'Name',\n        dataKey: 'name',\n        useInputToggleDataKey: 'useNameInput',\n        helperMessage: 'The name for the MCP Client',\n      },\n      {\n        type: 'string',\n        label: 'Version',\n        dataKey: 'version',\n        useInputToggleDataKey: 'useVersionInput',\n        helperMessage: 'A version for the MCP Client',\n      },\n      {\n        type: 'dropdown',\n        label: 'Transport Type',\n        dataKey: 'transportType',\n        options: [\n          { label: 'HTTP', value: 'http' },\n          { label: 'STDIO', value: 'stdio' },\n        ],\n      },\n      {\n        type: 'string',\n        label: 'Prompt Name',\n        dataKey: 'promptName',\n        useInputToggleDataKey: 'usePromptNameInput',\n        helperMessage: 'The name for the MCP prompt',\n      },\n      {\n        type: 'code',\n        label: 'Prompt Arguments',\n        dataKey: 'promptArguments',\n        useInputToggleDataKey: 'usePromptArgumentsInput',\n        language: 'json',\n        helperMessage: 'Arguments to provide the prompt',\n      },\n    ];\n\n    if (this.data.transportType === 'http') {\n      editors.push({\n        type: 'string',\n        label: 'Server URL',\n        dataKey: 'serverUrl',\n        useInputToggleDataKey: 'useServerUrlInput',\n        helperMessage: 'The endpoint URL for the MCP server to connect',\n      });\n    } else if (this.data.transportType === 'stdio') {\n      const serverOptions = await getServerOptions(context);\n\n      editors.push({\n        type: 'dropdown',\n        label: 'Server ID',\n        dataKey: 'serverId',\n        helperMessage: getServerHelperMessage(context, serverOptions.length),\n        options: serverOptions,\n      });\n    }\n\n    return editors;\n  }\n\n  getBody(context: RivetUIContext): string {\n    let base;\n    if (this.data.transportType === 'http') {\n      base = this.data.useServerUrlInput ? '(Using Server URL Input)' : this.data.serverUrl;\n    } else {\n      base = `Server ID: ${this.data.serverId || '(None)'}`;\n    }\n    const namePart = `Name: ${this.data.name}`;\n    const versionPart = `Version: ${this.data.version}`;\n    const parts = [namePart, versionPart, base];\n\n    if (context.executor !== 'nodejs') {\n      parts.push('(Requires Node Executor)');\n    }\n\n    return parts.join('\\n');\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Connects to an MCP (Model Context Protocol) server and gets a prompt response.\n      `,\n      infoBoxTitle: 'MCP Get Prompt Node',\n      contextMenuTitle: 'MCP Get Prompt',\n      group: ['MCP'],\n    };\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const name = getInputOrData(this.data, inputs, 'name', 'string');\n    const version = getInputOrData(this.data, inputs, 'version', 'string');\n\n    const promptName = getInputOrData(this.data, inputs, 'promptName', 'string');\n\n    let promptArguments;\n\n    if (this.data.usePromptArgumentsInput) {\n      promptArguments = getInputOrData(this.data, inputs, 'promptArguments', 'object');\n\n      if (promptArguments == null) {\n        throw new MCPError(MCPErrorType.INVALID_SCHEMA, 'Cannot parse tool argument with input toggle on');\n      }\n    } else {\n      const inputMap = keys(inputs)\n        .filter((key) => key.startsWith('input'))\n        .reduce(\n          (acc, key) => {\n            const stringValue = coerceTypeOptional(inputs[key], 'string') ?? '';\n\n            const interpolationKey = key.slice('input-'.length);\n            acc[interpolationKey] = stringValue;\n            return acc;\n          },\n          {} as Record<string, string>,\n        );\n\n      const interpolated = interpolate(this.data.promptArguments ?? '', inputMap);\n\n      promptArguments = JSON.parse(interpolated);\n    }\n\n    const getPromptRequest: MCP.GetPromptRequest = {\n      name: promptName,\n      arguments: promptArguments,\n    };\n\n    const transportType = getInputOrData(this.data, inputs, 'transportType', 'string') as 'http' | 'stdio';\n\n    let getPromptResponse: MCP.GetPromptResponse | undefined = undefined;\n\n    try {\n      if (!context.mcpProvider) {\n        throw new Error('MCP Provider not found');\n      }\n\n      if (transportType === 'http') {\n        const serverUrl = getInputOrData(this.data, inputs, 'serverUrl', 'string');\n        if (!serverUrl || serverUrl === '') {\n          throw new MCPError(MCPErrorType.SERVER_NOT_FOUND, 'No server URL was provided');\n        }\n        if (!serverUrl.includes('/mcp')) {\n          throw new MCPError(\n            MCPErrorType.SERVER_COMMUNICATION_FAILED,\n            'Include /mcp in your server URL. For example: http://localhost:8080/mcp',\n          );\n        }\n\n        getPromptResponse = await context.mcpProvider.getHTTPrompt({ name, version }, serverUrl, getPromptRequest);\n      } else if (transportType === 'stdio') {\n        const serverId = this.data.serverId ?? '';\n\n        const mcpConfig = await loadMCPConfiguration(context);\n        if (!mcpConfig.mcpServers[serverId]) {\n          throw new MCPError(MCPErrorType.SERVER_NOT_FOUND, `Server ${serverId} not found in MCP config`);\n        }\n\n        const serverConfig = {\n          config: mcpConfig.mcpServers[serverId],\n          serverId,\n        };\n\n        getPromptResponse = await context.mcpProvider.getStdioPrompt({ name, version }, serverConfig, getPromptRequest);\n      }\n\n      const output: Outputs = {};\n\n      output['response' as PortId] = {\n        type: 'object',\n        value: getPromptResponse as unknown as Record<string, unknown>,\n      };\n\n      return output;\n    } catch (err) {\n      const { message } = getError(err);\n      if (context.executor === 'browser') {\n        throw new Error('Failed to create Client without a node executor');\n      }\n      console.log(message);\n      throw err;\n    }\n  }\n}\n\nexport const mcpGetPromptNode = nodeDefinition(MCPGetPromptNodeImpl, 'MCP Get Prompt');\n", "import {\n  type ChartNode,\n  type NodeConnection,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type PortId,\n} from '../NodeBase.js';\nimport { NodeImpl, type NodeBody, type NodeUIData } from '../NodeImpl.js';\nimport { nodeDefinition } from '../NodeDefinition.js';\nimport { type Inputs, type Outputs } from '../GraphProcessor.js';\nimport { type GraphId } from '../NodeGraph.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { type Project, type ProjectId } from '../Project.js';\nimport { type GraphInputNode } from './GraphInputNode.js';\nimport { type GraphOutputNode } from './GraphOutputNode.js';\nimport { type DataValue } from '../DataValue.js';\nimport { type InternalProcessContext } from '../ProcessContext.js';\nimport { dedent } from 'ts-dedent';\nimport { getError } from '../../utils/errors.js';\nimport type { RivetUIContext } from '../RivetUIContext.js';\nimport type { EditorDefinition } from '../EditorDefinition.js';\n\nexport type ReferencedGraphAliasNode = ChartNode & {\n  type: 'referencedGraphAlias';\n  data: {\n    projectId: ProjectId;\n    graphId: GraphId;\n    useErrorOutput?: boolean;\n    outputCostDuration?: boolean;\n\n    /** Data for each of the inputs of the referenced graph */\n    inputData?: Record<string, DataValue>;\n  };\n};\n\nexport class ReferencedGraphAliasNodeImpl extends NodeImpl<ReferencedGraphAliasNode> {\n  static create(): ReferencedGraphAliasNode {\n    const chartNode: ReferencedGraphAliasNode = {\n      type: 'referencedGraphAlias',\n      title: '', // Always set initially by the editor\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 300,\n      },\n      data: {\n        projectId: undefined!, // Always set initially by the editor\n        graphId: undefined!, // Always set initially by the editor\n        useErrorOutput: false,\n      },\n    };\n\n    return chartNode;\n  }\n\n  getInputDefinitions(\n    _connections: NodeConnection[],\n    _nodes: Record<NodeId, ChartNode>,\n    _project: Project,\n    referencedProjects: Record<ProjectId, Project>,\n  ): NodeInputDefinition[] {\n    const referencedProject = referencedProjects[this.data.projectId];\n    if (!referencedProject) {\n      return [];\n    }\n\n    const graph = referencedProject.graphs[this.data.graphId];\n    if (!graph) {\n      return [];\n    }\n\n    const inputNodes = graph.nodes.filter((node) => node.type === 'graphInput') as GraphInputNode[];\n    const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();\n\n    return inputIds.map(\n      (id): NodeInputDefinition => ({\n        id: id as PortId,\n        title: id,\n        dataType: inputNodes.find((node) => node.data.id === id)!.data.dataType,\n      }),\n    );\n  }\n\n  getGraphOutputs(referencedProject: Project): NodeOutputDefinition[] {\n    const graph = referencedProject.graphs[this.data.graphId];\n    if (!graph) {\n      return [];\n    }\n\n    const outputNodes = graph.nodes.filter((node) => node.type === 'graphOutput') as GraphOutputNode[];\n    const outputIds = [...new Set(outputNodes.map((node) => node.data.id))].sort();\n\n    const outputs = outputIds.map(\n      (id): NodeOutputDefinition => ({\n        id: id as PortId,\n        title: id,\n        dataType: outputNodes.find((node) => node.data.id === id)!.data.dataType,\n      }),\n    );\n\n    return outputs;\n  }\n\n  getOutputDefinitions(\n    _connections: NodeConnection[],\n    _nodes: Record<NodeId, ChartNode>,\n    _project: Project,\n    referencedProjects: Record<ProjectId, Project>,\n  ): NodeOutputDefinition[] {\n    const outputs: NodeOutputDefinition[] = [];\n\n    const referencedProject = referencedProjects[this.data.projectId];\n    if (!referencedProject) {\n      return outputs;\n    }\n\n    outputs.push(...this.getGraphOutputs(referencedProject));\n\n    if (this.data.useErrorOutput) {\n      outputs.push({\n        id: 'error' as PortId,\n        title: 'Error',\n        dataType: 'string',\n      });\n    }\n\n    return outputs;\n  }\n\n  getEditors(context: RivetUIContext): EditorDefinition<ReferencedGraphAliasNode>[] {\n    const definitions: EditorDefinition<ReferencedGraphAliasNode>[] = [\n      {\n        type: 'toggle',\n        label: 'Use Error Output',\n        dataKey: 'useErrorOutput',\n      },\n      {\n        type: 'toggle',\n        label: 'Output Cost & Duration',\n        dataKey: 'outputCostDuration',\n      },\n    ];\n\n    const referencedProject = context.referencedProjects[this.data.projectId];\n    if (referencedProject) {\n      const graph = referencedProject.graphs[this.data.graphId];\n      if (graph) {\n        const inputNodes = graph.nodes.filter((node) => node.type === 'graphInput') as GraphInputNode[];\n        const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();\n\n        for (const inputId of inputIds) {\n          const inputNode = inputNodes.find((node) => node.data.id === inputId)!;\n          definitions.push({\n            type: 'dynamic',\n            dataKey: 'inputData',\n            dynamicDataKey: inputNode.data.id,\n            dataType: inputNode.data.dataType,\n            label: inputNode.data.id,\n            editor: inputNode.data.editor ?? 'auto',\n          });\n        }\n      }\n    }\n\n    return definitions;\n  }\n\n  getBody(context: RivetUIContext): NodeBody | Promise<NodeBody> {\n    return context.referencedProjects[this.data.projectId]?.graphs[this.data.graphId]?.metadata?.description ?? '';\n  }\n\n  static getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        References a graph from another project. Inputs and outputs are defined by Graph Input and Graph Output nodes within the referenced graph.\n      `,\n      infoBoxTitle: 'Referenced Graph Alias Node',\n      contextMenuTitle: 'Referenced Graph Alias',\n      group: ['Advanced'],\n    };\n  }\n\n  async process(inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const referencedProject = context.referencedProjects[this.data.projectId];\n    if (!referencedProject) {\n      throw new Error(\n        `ReferencedGraphAliasNode requires a project with id ${this.data.projectId} to be available in the context.referencedProjects.`,\n      );\n    }\n\n    const graph = referencedProject.graphs[this.data.graphId];\n    if (!graph) {\n      throw new Error(\n        `ReferencedGraphAliasNode requires a graph with id ${this.data.graphId} to be present in the referenced project.`,\n      );\n    }\n\n    const inputNodes = graph.nodes.filter((node) => node.type === 'graphInput') as GraphInputNode[];\n    const inputIds = [...new Set(inputNodes.map((node) => node.data.id))].sort();\n\n    const inputData = inputIds.reduce((obj, id): Inputs => {\n      if (inputs[id as PortId] != null) {\n        return {\n          ...obj,\n          [id]: inputs[id as PortId],\n        };\n      }\n\n      if (this.data.inputData?.[id] != null) {\n        return {\n          ...obj,\n          [id]: this.data.inputData[id],\n        };\n      }\n\n      return obj;\n    }, {} as Inputs);\n\n    // Create a subprocessor using the referenced project's graph\n    const subGraphProcessor = context.createSubProcessor(this.data.graphId, {\n      signal: context.signal,\n      project: referencedProject!,\n    });\n\n    try {\n      const startTime = Date.now();\n\n      const outputs = await subGraphProcessor.processGraph(\n        context,\n        inputData as Record<string, DataValue>,\n        context.contextValues,\n      );\n\n      const duration = Date.now() - startTime;\n\n      if (this.data.useErrorOutput) {\n        outputs['error' as PortId] = {\n          type: 'control-flow-excluded',\n          value: undefined,\n        };\n      }\n\n      if (outputs['duration' as PortId] == null) {\n        outputs['duration' as PortId] = {\n          type: 'number',\n          value: duration,\n        };\n      }\n\n      if (!this.data.outputCostDuration) {\n        delete outputs['cost' as PortId];\n        delete outputs['duration' as PortId];\n      }\n\n      return outputs;\n    } catch (err) {\n      if (!this.data.useErrorOutput) {\n        throw err;\n      }\n\n      const outputs: Outputs = this.getGraphOutputs(referencedProject).reduce(\n        (obj, output): Outputs => ({\n          ...obj,\n          [output.id as PortId]: {\n            type: 'control-flow-excluded',\n            value: undefined,\n          },\n        }),\n        {} as Outputs,\n      );\n\n      outputs['error' as PortId] = {\n        type: 'string',\n        value: getError(err).message,\n      };\n\n      return outputs;\n    }\n  }\n}\n\nexport const referencedGraphAliasNode = nodeDefinition(ReferencedGraphAliasNodeImpl, 'Referenced Graph Alias');\n", "import { NodeRegistration } from './NodeRegistration.js';\n\nimport { userInputNode } from './nodes/UserInputNode.js';\nexport * from './nodes/UserInputNode.js';\n\nimport { textNode } from './nodes/TextNode.js';\nexport * from './nodes/TextNode.js';\n\nimport { chatNode } from './nodes/ChatNode.js';\nexport * from './nodes/ChatNode.js';\nexport * from './nodes/ChatNodeBase.js';\n\nimport { promptNode } from './nodes/PromptNode.js';\nexport * from './nodes/PromptNode.js';\n\nimport { extractRegexNode } from './nodes/ExtractRegexNode.js';\nexport * from './nodes/ExtractRegexNode.js';\n\nimport { codeNode } from './nodes/CodeNode.js';\nexport * from './nodes/CodeNode.js';\n\nimport { matchNode } from './nodes/MatchNode.js';\nexport * from './nodes/MatchNode.js';\n\nimport { ifNode } from './nodes/IfNode.js';\nexport * from './nodes/IfNode.js';\n\nimport { readDirectoryNode } from './nodes/ReadDirectoryNode.js';\nexport * from './nodes/ReadDirectoryNode.js';\n\nimport { readFileNode } from './nodes/ReadFileNode.js';\nexport * from './nodes/ReadFileNode.js';\n\nimport { ifElseNode } from './nodes/IfElseNode.js';\nexport * from './nodes/IfElseNode.js';\n\nimport { chunkNode } from './nodes/ChunkNode.js';\nexport * from './nodes/ChunkNode.js';\n\nimport { graphInputNode } from './nodes/GraphInputNode.js';\nexport * from './nodes/GraphInputNode.js';\n\nimport { graphOutputNode } from './nodes/GraphOutputNode.js';\nexport * from './nodes/GraphOutputNode.js';\n\nimport { subGraphNode } from './nodes/SubGraphNode.js';\nexport * from './nodes/SubGraphNode.js';\n\nimport { arrayNode } from './nodes/ArrayNode.js';\nexport * from './nodes/ArrayNode.js';\n\nimport { extractJsonNode } from './nodes/ExtractJsonNode.js';\nexport * from './nodes/ExtractJsonNode.js';\n\nimport { assemblePromptNode } from './nodes/AssemblePromptNode.js';\nexport * from './nodes/ExtractYamlNode.js';\n\nimport { loopControllerNode } from './nodes/LoopControllerNode.js';\nexport * from './nodes/AssemblePromptNode.js';\n\nimport { trimChatMessagesNode } from './nodes/TrimChatMessagesNode.js';\nexport * from './nodes/LoopControllerNode.js';\n\nimport { extractYamlNode } from './nodes/ExtractYamlNode.js';\nexport * from './nodes/TrimChatMessagesNode.js';\n\nimport { externalCallNode } from './nodes/ExternalCallNode.js';\nexport * from './nodes/ExternalCallNode.js';\n\nimport { extractObjectPathNode } from './nodes/ExtractObjectPathNode.js';\nexport * from './nodes/ExtractObjectPathNode.js';\n\nimport { raiseEventNode } from './nodes/RaiseEventNode.js';\nexport * from './nodes/RaiseEventNode.js';\n\nimport { contextNode } from './nodes/ContextNode.js';\nexport * from './nodes/ContextNode.js';\n\nimport { coalesceNode } from './nodes/CoalesceNode.js';\nexport * from './nodes/CoalesceNode.js';\n\nimport { passthroughNode } from './nodes/PassthroughNode.js';\nexport * from './nodes/PassthroughNode.js';\n\nimport { popNode } from './nodes/PopNode.js';\nexport * from './nodes/PopNode.js';\n\nimport { setGlobalNode } from './nodes/SetGlobalNode.js';\nexport * from './nodes/SetGlobalNode.js';\n\nimport { getGlobalNode } from './nodes/GetGlobalNode.js';\nexport * from './nodes/GetGlobalNode.js';\n\nimport { waitForEventNode } from './nodes/WaitForEventNode.js';\nexport * from './nodes/WaitForEventNode.js';\n\nimport { gptFunctionNode } from './nodes/ToolNode.js';\nexport * from './nodes/ToolNode.js';\n\nimport { toYamlNode } from './nodes/ToYamlNode.js';\nexport * from './nodes/ToYamlNode.js';\n\nimport { getEmbeddingNode } from './nodes/GetEmbeddingNode.js';\nexport * from './nodes/GetEmbeddingNode.js';\n\nimport { vectorStoreNode } from './nodes/VectorStoreNode.js';\nexport * from './nodes/VectorStoreNode.js';\n\nimport { vectorNearestNeighborsNode } from './nodes/VectorNearestNeighborsNode.js';\nexport * from './nodes/VectorNearestNeighborsNode.js';\n\nimport { hashNode } from './nodes/HashNode.js';\nexport * from './nodes/HashNode.js';\n\nimport { abortGraphNode } from './nodes/AbortGraphNode.js';\nexport * from './nodes/AbortGraphNode.js';\n\nimport { raceInputsNode } from './nodes/RaceInputsNode.js';\nexport * from './nodes/RaceInputsNode.js';\n\nimport { toJsonNode } from './nodes/ToJsonNode.js';\nexport * from './nodes/ToJsonNode.js';\n\nimport { joinNode } from './nodes/JoinNode.js';\nexport * from './nodes/JoinNode.js';\n\nimport { filterNode } from './nodes/FilterNode.js';\nexport * from './nodes/FilterNode.js';\n\nimport { objectNode } from './nodes/ObjectNode.js';\nexport * from './nodes/ObjectNode.js';\n\nimport { booleanNode } from './nodes/BooleanNode.js';\nexport * from './nodes/BooleanNode.js';\n\nimport { compareNode } from './nodes/CompareNode.js';\nexport * from './nodes/CompareNode.js';\n\nimport { evaluateNode } from './nodes/EvaluateNode.js';\nexport * from './nodes/EvaluateNode.js';\n\nimport { numberNode } from './nodes/NumberNode.js';\nexport * from './nodes/NumberNode.js';\n\nimport { randomNumberNode } from './nodes/RandomNumberNode.js';\nexport * from './nodes/RandomNumberNode.js';\n\nimport { shuffleNode } from './nodes/ShuffleNode.js';\nexport * from './nodes/ShuffleNode.js';\n\nimport { commentNode } from './nodes/CommentNode.js';\nexport * from './nodes/CommentNode.js';\n\nimport { imageNode } from './nodes/ImageNode.js';\nexport * from './nodes/ImageNode.js';\n\nimport { audioNode } from './nodes/AudioNode.js';\nexport * from './nodes/AudioNode.js';\n\nimport { httpCallNode } from './nodes/HttpCallNode.js';\nexport * from './nodes/HttpCallNode.js';\n\nimport { delayNode } from './nodes/DelayNode.js';\nexport * from './nodes/DelayNode.js';\n\nimport { appendToDatasetNode } from './nodes/AppendToDatasetNode.js';\nexport * from './nodes/AppendToDatasetNode.js';\n\nimport { createDatasetNode } from './nodes/CreateDatasetNode.js';\nexport * from './nodes/CreateDatasetNode.js';\n\nimport { loadDatasetNode } from './nodes/LoadDatasetNode.js';\nexport * from './nodes/LoadDatasetNode.js';\n\nimport { getAllDatasetsNode } from './nodes/GetAllDatasetsNode.js';\nexport * from './nodes/GetAllDatasetsNode.js';\n\nimport { splitNode } from './nodes/SplitNode.js';\nexport * from './nodes/SplitNode.js';\n\nimport { datasetNearestNeighborsNode } from './nodes/DatasetNearestNeigborsNode.js';\nexport * from './nodes/DatasetNearestNeigborsNode.js';\n\nimport { getDatasetRowNode } from './nodes/GetDatasetRowNode.js';\nexport * from './nodes/GetDatasetRowNode.js';\n\nimport { sliceNode } from './nodes/SliceNode.js';\nexport * from './nodes/SliceNode.js';\n\nimport { extractMarkdownCodeBlocksNode } from './nodes/ExtractMarkdownCodeBlocksNode.js';\nexport * from './nodes/ExtractMarkdownCodeBlocksNode.js';\n\nimport { assembleMessageNode } from './nodes/AssembleMessageNode.js';\nexport * from './nodes/AssembleMessageNode.js';\n\nimport { urlReferenceNode } from './nodes/URLReferenceNode.js';\nexport * from './nodes/URLReferenceNode.js';\n\nimport { destructureNode } from './nodes/DestructureNode.js';\nexport * from './nodes/DestructureNode.js';\n\nimport { replaceDatasetNode } from './nodes/ReplaceDatasetNode.js';\nexport * from './nodes/ReplaceDatasetNode.js';\n\nimport { listGraphsNode } from './nodes/ListGraphsNode.js';\nexport * from './nodes/ListGraphsNode.js';\n\nimport { graphReferenceNode } from './nodes/GraphReferenceNode.js';\nexport * from './nodes/GraphReferenceNode.js';\n\nimport { callGraphNode } from './nodes/CallGraphNode.js';\nexport * from './nodes/CallGraphNode.js';\n\nimport { delegateFunctionCallNode } from './nodes/DelegateFunctionCallNode.js';\nexport * from './nodes/DelegateFunctionCallNode.js';\n\nimport { playAudioNode } from './nodes/PlayAudioNode.js';\nexport * from './nodes/PlayAudioNode.js';\n\nimport { documentNode } from './nodes/DocumentNode.js';\nexport * from './nodes/DocumentNode.js';\n\nimport { chatLoopNode } from './nodes/ChatLoopNode.js';\nexport * from './nodes/ChatLoopNode.js';\n\nimport { readAllFilesNode } from './nodes/ReadAllFilesNode.js';\nexport * from './nodes/ReadAllFilesNode.js';\n\nimport { toMarkdownTableNode } from './nodes/ToMarkdownTableNode.js';\nexport * from './nodes/ToMarkdownTableNode.js';\n\nimport { cronNode } from './nodes/CronNode.js';\nexport * from './nodes/CronNode.js';\n\nimport { toTreeNode } from './nodes/ToTreeNode.js';\nexport * from './nodes/ToTreeNode.js';\n\nimport { loopUntilNode } from './nodes/LoopUntilNode.js';\nexport * from './nodes/LoopUntilNode.js';\n\nimport { mcpDiscoveryNode } from './nodes/MCPDiscoveryNode.js';\nexport * from './nodes/MCPDiscoveryNode.js';\n\nimport { mcpToolCallNode } from './nodes/MCPToolCallNode.js';\nexport * from './nodes/MCPToolCallNode.js';\n\nimport { mcpGetPromptNode } from './nodes/MCPGetPromptNode.js';\nexport * from './nodes/MCPGetPromptNode.js';\n\nimport { referencedGraphAliasNode } from './nodes/ReferencedGraphAliasNode.js';\nexport * from './nodes/ReferencedGraphAliasNode.js';\n\nexport const registerBuiltInNodes = (registry: NodeRegistration) => {\n  return registry\n    .register(toYamlNode)\n    .register(userInputNode)\n    .register(textNode)\n    .register(chatNode)\n    .register(promptNode)\n    .register(extractRegexNode)\n    .register(codeNode)\n    .register(matchNode)\n    .register(ifNode)\n    .register(readDirectoryNode)\n    .register(readFileNode)\n    .register(ifElseNode)\n    .register(chunkNode)\n    .register(graphInputNode)\n    .register(graphOutputNode)\n    .register(subGraphNode)\n    .register(arrayNode)\n    .register(extractJsonNode)\n    .register(assemblePromptNode)\n    .register(loopControllerNode)\n    .register(trimChatMessagesNode)\n    .register(extractYamlNode)\n    .register(externalCallNode)\n    .register(extractObjectPathNode)\n    .register(raiseEventNode)\n    .register(contextNode)\n    .register(coalesceNode)\n    .register(passthroughNode)\n    .register(popNode)\n    .register(setGlobalNode)\n    .register(getGlobalNode)\n    .register(waitForEventNode)\n    .register(gptFunctionNode)\n    .register(getEmbeddingNode)\n    .register(vectorStoreNode)\n    .register(vectorNearestNeighborsNode)\n    .register(hashNode)\n    .register(abortGraphNode)\n    .register(raceInputsNode)\n    .register(toJsonNode)\n    .register(joinNode)\n    .register(filterNode)\n    .register(objectNode)\n    .register(booleanNode)\n    .register(compareNode)\n    .register(evaluateNode)\n    .register(numberNode)\n    .register(randomNumberNode)\n    .register(shuffleNode)\n    .register(commentNode)\n    .register(imageNode)\n    .register(audioNode)\n    .register(httpCallNode)\n    .register(delayNode)\n    .register(appendToDatasetNode)\n    .register(createDatasetNode)\n    .register(loadDatasetNode)\n    .register(getAllDatasetsNode)\n    .register(splitNode)\n    .register(datasetNearestNeighborsNode)\n    .register(getDatasetRowNode)\n    .register(sliceNode)\n    .register(extractMarkdownCodeBlocksNode)\n    .register(assembleMessageNode)\n    .register(urlReferenceNode)\n    .register(destructureNode)\n    .register(replaceDatasetNode)\n    .register(listGraphsNode)\n    .register(graphReferenceNode)\n    .register(callGraphNode)\n    .register(delegateFunctionCallNode)\n    .register(playAudioNode)\n    .register(documentNode)\n    .register(chatLoopNode)\n    .register(readAllFilesNode)\n    .register(toMarkdownTableNode)\n    .register(cronNode)\n    .register(toTreeNode)\n    .register(loopUntilNode)\n    .register(mcpDiscoveryNode)\n    .register(mcpToolCallNode)\n    .register(mcpGetPromptNode)\n    .register(referencedGraphAliasNode);\n};\n\nlet globalRivetNodeRegistry = registerBuiltInNodes(new NodeRegistration());\n\nexport { globalRivetNodeRegistry };\n\nexport type BuiltInNodes = typeof globalRivetNodeRegistry.NodesType;\n\nexport type BuiltInNodeType = typeof globalRivetNodeRegistry.NodeTypesType;\n\nexport type NodeOfType<T extends BuiltInNodeType> = Extract<BuiltInNodes, { type: T }>;\n\n/** Resets the global node registry to a fresh one with only built-in nodes registered. */\nexport function resetGlobalRivetNodeRegistry() {\n  globalRivetNodeRegistry = registerBuiltInNodes(new NodeRegistration());\n}\n", "import { type ChatMessage, type GptFunction } from '../index.js';\nimport type { Tokenizer, TokenizerCallInfo } from './Tokenizer.js';\nimport Emittery from 'emittery';\nimport { getError } from '../utils/errors.js';\nimport { chatMessageToOpenAIChatCompletionMessage } from '../utils/chatMessageToOpenAIChatCompletionMessage.js';\nimport type { ChatCompletionRequestUserMessageTextContent } from '../utils/openai.js';\n\nexport class GptTokenizerTokenizer implements Tokenizer {\n  emitter = new Emittery<{\n    error: Error;\n  }>();\n\n  on(event: 'error', listener: (err: Error) => void): void {\n    this.emitter.on(event, listener);\n  }\n\n  async getTokenCountForString(input: string, _info: TokenizerCallInfo): Promise<number> {\n    const { encode } = await import('gpt-tokenizer');\n    return encode(input).length;\n  }\n\n  async getTokenCountForMessages(\n    messages: ChatMessage[],\n    functions: GptFunction[] | undefined,\n    _info: TokenizerCallInfo,\n  ): Promise<number> {\n    try {\n      const openaiMessages = await Promise.all(\n        messages.map((message) => chatMessageToOpenAIChatCompletionMessage(message, { isReasoningModel: false })),\n      );\n\n      const validMessages = openaiMessages.map((message) => {\n        // Tools not supported to calculate token count so we convert them to user messages\n        if (message.role === 'tool') {\n          return { role: 'user', content: message.content };\n        }\n\n        if (Array.isArray(message.content)) {\n          const textContent = message.content\n            .filter((c): c is ChatCompletionRequestUserMessageTextContent => c.type === 'text')\n            .map((c) => c.text)\n            .join('');\n          return { ...message, content: textContent };\n        }\n\n        return message;\n      });\n\n      const { encode, encodeChat } = await import('gpt-tokenizer');\n\n      const encodedChat = encodeChat(validMessages as any, 'gpt-3.5-turbo');\n      const encodedFunctions =\n        functions && functions.length > 0 ? encode(this.convertGptFunctionsToPromptString(functions)) : [];\n\n      return encodedChat.length + encodedFunctions.length;\n    } catch (err) {\n      // eslint-disable-next-line @typescript-eslint/no-floating-promises\n      this.emitter.emit('error', getError(err));\n      return 0;\n    }\n  }\n\n  /**\n   * Converts GPT Functions to approximate TypeScript-style string.\n   * Per thread: https://community.openai.com/t/how-to-calculate-the-tokens-when-using-function-call/266573/24\n   * We should consider using a different library, eg. https://github.com/hmarr/openai-chat-tokens\n   * @param functions\n   */\n  private convertGptFunctionsToPromptString(functions: GptFunction[]): string {\n    return `\n# Tools\n\n## functions\n\nnamespace functions {\n${functions\n  .map(\n    (fn) => `\n// ${fn.description}\ntype ${fn.name} = (_: {\n${Object.entries((fn.parameters as any)?.properties ?? {})\n  .map(([parameterName, value]: [string, any]) => `// ${value?.description}\\n${parameterName}?: ${value?.type}`)\n  .join('\\n')}\n})\n`,\n  )\n  .join('')}\n} // namespace functions\n`;\n  }\n}\n", "import type { Inputs, Outputs } from '../index.js';\nimport type { DataValue } from '../model/DataValue.js';\n\n// eslint-disable-next-line import/no-cycle -- There has to be a cycle if we're to import the entirety of Rivet here.\nimport * as Rivet from '../exports.js';\n\nexport interface CodeRunnerOptions {\n  includeRequire: boolean;\n  includeFetch: boolean;\n  includeRivet: boolean;\n  includeProcess: boolean;\n  includeConsole: boolean;\n}\n\n/** An object that can run arbitrary code (evals it). */\nexport interface CodeRunner {\n  runCode: (\n    code: string,\n    inputs: Inputs,\n    options: CodeRunnerOptions,\n    graphInputs?: Record<string, DataValue>,\n    contextValues?: Record<string, DataValue>\n  ) => Promise<Outputs>;\n}\n\nexport class IsomorphicCodeRunner implements CodeRunner {\n  async runCode(\n    code: string,\n    inputs: Inputs,\n    options: CodeRunnerOptions,\n    graphInputs?: Record<string, DataValue>,\n    contextValues?: Record<string, DataValue>\n  ): Promise<Outputs> {\n    const argNames = ['inputs'];\n    const args: any[] = [inputs];\n\n    if (options.includeRequire) {\n      throw new Error('require() requires the Node executor.');\n    }\n\n    if (options.includeProcess) {\n      throw new Error('process requires the Node executor.');\n    }\n\n    if (options.includeConsole) {\n      argNames.push('console');\n      args.push(console);\n    }\n\n    if (options.includeFetch) {\n      argNames.push('fetch');\n      args.push(fetch);\n    }\n\n    if (options.includeRivet) {\n      argNames.push('Rivet');\n      args.push(Rivet);\n    }\n\n    if (graphInputs) {\n      argNames.push('graphInputs');\n      args.push(graphInputs);\n    }\n\n    if (contextValues) {\n      argNames.push('context');\n      args.push(contextValues);\n    }\n\n    argNames.push(code);\n\n    const AsyncFunction = async function () {}.constructor as new (...args: string[]) => Function;\n    const codeFunction = new AsyncFunction(...argNames);\n    const outputs = await codeFunction(...args);\n\n    return outputs;\n  }\n}\n\nexport class NotAllowedCodeRunner implements CodeRunner {\n  async runCode(\n    _code: string,\n    _inputs: Inputs,\n    _options: CodeRunnerOptions,\n    _graphInputs?: Record<string, DataValue>,\n    _contextValues?: Record<string, DataValue>\n  ): Promise<Outputs> {\n    throw new Error('Dynamic code execution is disabled.');\n  }\n}\n", "export const baseDirs = {\n  app: 'app',\n  appCache: 'appCache',\n  appConfig: 'appConfig',\n  appData: 'appData',\n  appLocalData: 'appLocalData',\n  appLog: 'appLog',\n  audio: 'audio',\n  cache: 'cache',\n  config: 'config',\n  data: 'data',\n  desktop: 'desktop',\n  document: 'document',\n  download: 'download',\n  executable: 'executable',\n  font: 'font',\n  home: 'home',\n  localData: 'localData',\n  log: 'log',\n  picture: 'picture',\n  public: 'public',\n  resource: 'resource',\n  runtime: 'runtime',\n  temp: 'temp',\n  template: 'template',\n  video: 'video',\n} as const;\n\nexport type BaseDir = (typeof baseDirs)[keyof typeof baseDirs];\n\nexport function assertBaseDir(baseDir: string): asserts baseDir is BaseDir {\n  if (!(baseDir in baseDirs)) {\n    throw new Error(`Invalid base directory: ${baseDir}`);\n  }\n}\n", "import { type BaseDir } from './BaseDir.js';\nimport { type NativeApi } from './NativeApi.js';\n\nexport class BrowserNativeApi implements NativeApi {\n  readdir(_path: string, _baseDir: BaseDir): Promise<string[]> {\n    throw new Error('Method not implemented.');\n  }\n\n  readTextFile(_path: string, _baseDir: BaseDir): Promise<string> {\n    throw new Error('Method not implemented.');\n  }\n\n  readBinaryFile(_path: string, _baseDir: BaseDir): Promise<Blob> {\n    throw new Error('Method not implemented.');\n  }\n\n  writeTextFile(_path: string, _data: string, _baseDir?: BaseDir): Promise<void> {\n    throw new Error('Method not implemented.');\n  }\n\n  exec(): Promise<void> {\n    throw new Error('Method not supported.');\n  }\n}\n", "import { type Settings } from '../../index.js';\nimport { type EmbeddingGenerator } from '../EmbeddingGenerator.js';\nimport { OpenAI } from 'openai';\n\ntype OpenAIOptions = Pick<OpenAI.EmbeddingCreateParams, 'model' | 'dimensions'>;\n\nexport class OpenAIEmbeddingGenerator implements EmbeddingGenerator {\n  readonly #settings;\n\n  constructor(settings: Settings) {\n    this.#settings = settings;\n  }\n\n  async generateEmbedding(text: string, options?: OpenAIOptions): Promise<number[]> {\n    const api = new OpenAI({\n      apiKey: this.#settings.openAiKey,\n      organization: this.#settings.openAiOrganization,\n      dangerouslyAllowBrowser: true, // It's fine in Rivet\n    });\n\n    const response = await api.embeddings.create({\n      input: text,\n      model: options?.model ?? 'text-embedding-ada-002',\n      dimensions: options?.dimensions,\n    });\n\n    const embeddings = response.data;\n\n    return embeddings[0]!.embedding;\n  }\n}\n", "import { registerIntegration } from './integrations.js';\nimport { OpenAIEmbeddingGenerator } from './openai/OpenAIEmbeddingGenerator.js';\n\nregisterIntegration('embeddingGenerator', 'openai', (context) => new OpenAIEmbeddingGenerator(context.settings));\n", "import { nanoid } from 'nanoid/non-secure';\nimport fnv1a from '@sindresorhus/fnv1a';\nimport {\n  type GraphProcessor,\n  type ProcessEvents,\n  type RecordedEvent,\n  type RecordedEvents,\n  type Recording,\n  type RecordingId,\n  type SerializedRecording,\n} from '../index.js';\nimport Emittery from 'emittery';\nimport { uint8ArrayToBase64Sync, base64ToUint8Array } from '../utils/base64.js';\nimport { isPlainObject } from 'lodash-es';\nimport { stringifyJsonStream, type SerializableJsonValue, parseJsonStream, streamToIterable } from 'json-stream-es';\n\nexport type ExecutionRecorderEvents = {\n  finish: { recording: Recording };\n};\n\nconst toRecordedEventMap: {\n  [P in keyof ProcessEvents]: (data: ProcessEvents[P]) => RecordedEvent<P>['data'];\n} = {\n  graphStart: ({ graph, inputs }) => ({ graphId: graph.metadata!.id!, inputs }),\n  graphFinish: ({ graph, outputs }) => ({ graphId: graph.metadata!.id!, outputs }),\n  graphError: ({ graph, error }) => ({\n    graphId: graph.metadata!.id!,\n    error: typeof error === 'string' ? error : error.stack!,\n  }),\n  nodeStart: ({ node, inputs, processId }) => ({\n    nodeId: node.id,\n    inputs,\n    processId,\n  }),\n  nodeFinish: ({ node, outputs, processId }) => ({\n    nodeId: node.id,\n    outputs,\n    processId,\n  }),\n  nodeError: ({ node, error, processId }) => ({\n    nodeId: node.id,\n    error: typeof error === 'string' ? error : error.stack!,\n    processId,\n  }),\n  abort: ({ successful, error }) => ({ successful, error: typeof error === 'string' ? error : error?.stack }),\n  graphAbort: ({ successful, error, graph }) => ({\n    successful,\n    error: typeof error === 'string' ? error : error?.stack,\n    graphId: graph.metadata!.id!,\n  }),\n  nodeExcluded: ({ node, processId, inputs, outputs, reason }) => ({\n    nodeId: node.id,\n    processId,\n    inputs,\n    outputs,\n    reason,\n  }),\n  userInput: ({ node, inputs, callback, processId, inputStrings, renderingType }) => ({\n    nodeId: node.id,\n    inputs,\n    callback,\n    processId,\n    inputStrings,\n    renderingType,\n  }),\n  partialOutput: ({ node, outputs, index, processId }) => ({\n    nodeId: node.id,\n    outputs,\n    index,\n    processId,\n  }),\n  nodeOutputsCleared: ({ node, processId }) => ({\n    nodeId: node.id,\n    processId,\n  }),\n  error: ({ error }) => ({\n    error: typeof error === 'string' ? error : error.stack!,\n  }),\n  done: ({ results }) => ({ results }),\n  globalSet: ({ id, processId, value }) => ({ id, processId, value }),\n  pause: () => void 0,\n  resume: () => void 0,\n  start: ({ contextValues, inputs, project, startGraph }) => ({\n    contextValues,\n    inputs,\n    projectId: project.metadata!.id!,\n    startGraph: startGraph.metadata!.id!,\n  }),\n  trace: (message) => message,\n  newAbortController: () => {},\n  finish: () => void 0,\n};\n\nconst isPrefix = <const T extends string>(s: string, prefix: T): s is `${T}${string}` => s.startsWith(prefix);\n\nfunction toRecordedEvent<T extends keyof ProcessEvents>(event: T, data: ProcessEvents[T]): RecordedEvents {\n  if (isPrefix(event, 'globalSet:')) {\n    return {\n      type: event,\n      data: data as ProcessEvents[`globalSet:${string}`],\n      ts: Date.now(),\n    };\n  }\n\n  if (isPrefix(event, 'userEvent:')) {\n    return {\n      type: event,\n      data: data as ProcessEvents[`userEvent:${string}`],\n      ts: Date.now(),\n    };\n  }\n\n  return {\n    type: event,\n    data: (toRecordedEventMap[event] as any)(data),\n    ts: Date.now(),\n  };\n}\n\nexport type ExecutionRecorderOptions = {\n  includePartialOutputs?: boolean;\n  includeTrace?: boolean;\n};\n\nfunction mapValuesDeep(obj: any, fn: (value: any) => any): any {\n  if (Array.isArray(obj)) {\n    return obj.map((value) => {\n      if (isPlainObject(value) || Array.isArray(value)) {\n        return mapValuesDeep(value, fn);\n      }\n      return fn(value);\n    });\n  }\n\n  if (isPlainObject(obj)) {\n    return Object.fromEntries(\n      Object.entries(obj).map(([key, value]) => {\n        if (isPlainObject(value) || Array.isArray(value)) {\n          return [key, mapValuesDeep(value, fn)];\n        }\n        return [key, fn(value)];\n      }),\n    );\n  }\n\n  return fn(obj);\n}\n\nfunction serializeToObject(recording: Recording) {\n  const serialized: SerializedRecording = {\n    version: 1,\n    recording,\n    assets: {},\n    strings: {},\n  };\n\n  serialized.recording = mapValuesDeep(serialized.recording, (val) => {\n    if (val instanceof Uint8Array) {\n      const asString = uint8ArrayToBase64Sync(val);\n      const existingAsset = Object.entries(serialized.assets).find(([, asset]) => asset === asString);\n\n      if (!existingAsset) {\n        const id = nanoid();\n        serialized.assets[id] = asString;\n        return `$ASSET:${id}`;\n      } else {\n        const [id] = existingAsset;\n        return `$ASSET:${id}`;\n      }\n    }\n\n    if (typeof val === 'string' && !val.startsWith('$ASSET:') && val.length > 30) {\n      const hash = fnv1a(val, { size: 32 });\n      serialized.strings[`${hash}`] = val;\n      return `$STRING:${hash}`;\n    }\n\n    return val;\n  }) as SerializedRecording['recording'];\n\n  return serialized as SerializableJsonValue;\n}\n\nfunction deserializeFromObject(serializedRecording: SerializedRecording) {\n  if (serializedRecording.version !== 1) {\n    throw new Error('Unsupported serialized events version');\n  }\n\n  return mapValuesDeep(serializedRecording.recording, (val) => {\n    if (typeof val === 'string' && val.startsWith('$ASSET:')) {\n      const id = val.slice('$ASSET:'.length);\n      const asset = serializedRecording.assets?.[id];\n      if (asset) {\n        return new Uint8Array(base64ToUint8Array(asset));\n      } else {\n        return val;\n      }\n    }\n\n    if (typeof val === 'string' && val.startsWith('$STRING:')) {\n      const hash = val.slice('$STRING:'.length);\n      const string = serializedRecording.strings?.[hash];\n      if (string) {\n        return string;\n      }\n    }\n\n    return val;\n  }) as Recording;\n}\n\nexport class ExecutionRecorder {\n  #events: RecordedEvents[] = [];\n  recordingId: RecordingId | undefined;\n  readonly #emitter: Emittery<ExecutionRecorderEvents>;\n\n  readonly #includePartialOutputs: boolean;\n  readonly #includeTrace: boolean;\n\n  constructor(options: ExecutionRecorderOptions = {}) {\n    this.#emitter = new Emittery();\n    this.#emitter.bindMethods(this as any, ['on', 'off', 'once']);\n    this.#includePartialOutputs = options.includePartialOutputs ?? false;\n    this.#includeTrace = options.includeTrace ?? false;\n  }\n\n  on: Emittery<ExecutionRecorderEvents>['on'] = undefined!;\n  off: Emittery<ExecutionRecorderEvents>['off'] = undefined!;\n  once: Emittery<ExecutionRecorderEvents>['once'] = undefined!;\n\n  recordSocket(channel: WebSocket) {\n    return new Promise<void>((resolve) => {\n      this.recordingId = nanoid() as RecordingId;\n\n      const listener = (event: MessageEvent) => {\n        const { message, data } = JSON.parse(event.data);\n\n        if (this.#includePartialOutputs === false && message === 'partialOutput') {\n          return;\n        }\n\n        if (this.#includeTrace === false && message === 'trace') {\n          return;\n        }\n\n        this.#events.push(toRecordedEvent(message, data) as RecordedEvents);\n\n        if (message === 'done' || message === 'abort' || message === 'error') {\n          // eslint-disable-next-line @typescript-eslint/no-floating-promises\n          this.#emitter.emit('finish', {\n            recording: this.getRecording(),\n          });\n\n          channel.removeEventListener('message', listener);\n\n          resolve();\n        }\n      };\n\n      channel.addEventListener('message', listener);\n    });\n  }\n\n  record(processor: GraphProcessor) {\n    this.recordingId = nanoid() as RecordingId;\n    processor.onAny((event, data) => {\n      if (this.#includePartialOutputs === false && event === 'partialOutput') {\n        return;\n      }\n\n      if (this.#includeTrace === false && event === 'trace') {\n        return;\n      }\n\n      this.#events.push(toRecordedEvent(event, data) as RecordedEvents);\n\n      if (event === 'done' || event === 'abort' || event === 'error') {\n        // eslint-disable-next-line @typescript-eslint/no-floating-promises\n        this.#emitter.emit('finish', {\n          recording: this.getRecording(),\n        });\n      }\n    });\n  }\n\n  getRecording(): Recording {\n    return {\n      recordingId: this.recordingId!,\n      events: this.#events,\n      startTs: this.#events[0]?.ts ?? 0,\n      finishTs: this.#events[this.#events.length - 1]?.ts ?? 0,\n    };\n  }\n\n  get events() {\n    return this.#events;\n  }\n\n  static deserializeFromString(serialized: string) {\n    const recorder = new ExecutionRecorder();\n    const recording = deserializeFromObject(JSON.parse(serialized) as SerializedRecording);\n\n    recorder.recordingId = recording.recordingId;\n    recorder.#events = recording.events;\n    return recorder;\n  }\n\n  static async deserializeFromStream(serialized: ReadableStream) {\n    const recorder = new ExecutionRecorder();\n\n    let serializedRecording!: SerializedRecording;\n    for await (const value of streamToIterable(serialized.pipeThrough(parseJsonStream(undefined)))) {\n      serializedRecording = value as SerializedRecording;\n      break;\n    }\n\n    const recording = deserializeFromObject(serializedRecording);\n\n    recorder.recordingId = recording.recordingId;\n    recorder.#events = recording.events;\n    return recorder;\n  }\n\n  serialize() {\n    return JSON.stringify(serializeToObject(this.getRecording()));\n  }\n\n  serializeStream() {\n    return stringifyJsonStream(serializeToObject(this.getRecording()));\n  }\n}\n", "import { DEFAULT_CHAT_NODE_TIMEOUT } from '../../utils/defaults.js';\n\n// https://github.com/openai/openai-node/issues/18#issuecomment-1518715285\nexport class EventSourceResponse extends Response {\n  name: string;\n  readonly streams: {\n    eventStream: ReadableStream<string>;\n    textStream: ReadableStream<string>;\n  } | null;\n\n  constructor(body: ReadableStream<Uint8Array> | null, init?: ResponseInit) {\n    if (body == null) {\n      super(null, init);\n      this.name = 'EventSourceResponse';\n      this.streams = null;\n      return;\n    }\n\n    const [bodyForString, bodyForEvents] = body.tee();\n    const streams = createEventStream(bodyForEvents);\n    // By passing our transformed stream into the Response constructor, we prevent anyone\n    // from accidentally accessing the raw response.body stream.\n    super(bodyForString, init);\n    this.name = 'EventSourceResponse';\n    this.streams = streams;\n  }\n\n  async *events(): AsyncGenerator<string> {\n    if (this.streams == null) {\n      return;\n    }\n    const reader = this.streams.eventStream.getReader();\n\n    try {\n      while (true) {\n        const { done, value } = await this.raceWithTimeout(reader.read(), DEFAULT_CHAT_NODE_TIMEOUT);\n        if (done) {\n          break;\n        }\n        yield value;\n      }\n    } finally {\n      reader.releaseLock();\n    }\n  }\n\n  private async raceWithTimeout<T>(promise: Promise<T>, timeout = 5000): Promise<T> {\n    // eslint-disable-next-line no-async-promise-executor,@typescript-eslint/no-misused-promises -- Error handled correctly\n    return new Promise(async (resolve, reject) => {\n      const timer = setTimeout(() => {\n        reject(new Error('Timeout: API response took too long.'));\n      }, timeout);\n\n      try {\n        const result = await promise;\n        clearTimeout(timer);\n        resolve(result);\n      } catch (error) {\n        clearTimeout(timer);\n        reject(error);\n      }\n    });\n  }\n}\n\nexport default async function fetchEventSource(url: string, init?: RequestInit): Promise<EventSourceResponse> {\n  const headers = {\n    ...init?.headers,\n    accept: 'text/event-stream',\n  };\n\n  const response = await fetch(url, {\n    ...init,\n    headers,\n  });\n\n  return new EventSourceResponse(response.body, response);\n}\n\nclass LineSplitter implements Transformer<string, string> {\n  private buffer = '';\n  constructor(readonly separator = /\\n+/) {}\n\n  transform(chunk: string, controller: TransformStreamDefaultController<string>): void {\n    this.buffer += chunk;\n    const lines = this.buffer.split(this.separator);\n    this.buffer = lines.pop() ?? '';\n\n    for (const line of lines) {\n      controller.enqueue(line);\n    }\n  }\n\n  flush(controller: TransformStreamDefaultController<string>): void {\n    if (this.buffer.length > 0) {\n      controller.enqueue(this.buffer);\n      this.buffer = '';\n    }\n  }\n}\n\nfunction createEventStream(body: ReadableStream<Uint8Array> | null) {\n  if (body == null) {\n    return null;\n  }\n\n  const textStream = body.pipeThrough(new TextDecoderStream());\n\n  const eventStream = textStream.pipeThrough(new TransformStream(new LineSplitter())).pipeThrough(\n    new TransformStream<string, string>({\n      transform(line, controller) {\n        if (line.startsWith('data: ')) {\n          const data = line.slice(6).trim();\n          controller.enqueue(data);\n        } else if (line.startsWith('event: ')) {\n          const event = line.slice(7).trim();\n          controller.enqueue(`[${event}]`);\n        }\n      },\n    }),\n  );\n  return { eventStream, textStream };\n}\n", "import fetchEventSource from './fetchEventSource.js';\n\nexport type AnthropicModel = {\n  maxTokens: number;\n  cost: {\n    prompt: number;\n    completion: number;\n  };\n  displayName: string;\n};\n\nexport const anthropicModels = {\n  'claude-instant-1': {\n    maxTokens: 100_000,\n    cost: {\n      prompt: 0.00163,\n      completion: 0.00551,\n    },\n    displayName: 'Claude Instant',\n  },\n  'claude-instant-1.2': {\n    maxTokens: 100_000,\n    cost: {\n      prompt: 0.8e-6,\n      completion: 2.4e-6,\n    },\n    displayName: 'Claude Instant 1.2',\n  },\n  'claude-2': {\n    maxTokens: 100_000,\n    cost: {\n      prompt: 8e-6,\n      completion: 24e-6,\n    },\n    displayName: 'Claude 2',\n  },\n  'claude-2.1': {\n    maxTokens: 200_000,\n    cost: {\n      prompt: 8e-6,\n      completion: 24e-6,\n    },\n    displayName: 'Claude 2.1',\n  },\n  'claude-3-haiku-20240307': {\n    maxTokens: 200_000,\n    cost: {\n      prompt: 0.25e-6,\n      completion: 1.25e-6,\n    },\n    displayName: 'Claude 3 Haiku',\n  },\n  'claude-3-sonnet-20240229': {\n    maxTokens: 200_000,\n    cost: {\n      prompt: 3e-6,\n      completion: 15e-6,\n    },\n    displayName: 'Claude 3 Sonnet',\n  },\n  'claude-3-opus-20240229': {\n    maxTokens: 200_000,\n    cost: {\n      prompt: 15e-6,\n      completion: 75e-6,\n    },\n    displayName: 'Claude 3 Opus',\n  },\n  'claude-3-5-sonnet-latest': {\n    maxTokens: 200_000,\n    cost: {\n      prompt: 3e-6,\n      completion: 15e-6,\n    },\n    displayName: 'Claude 3.5 Sonnet',\n  },\n  'claude-3-5-haiku-latest': {\n    maxTokens: 200_000,\n    cost: {\n      prompt: 0.8e-6,\n      completion: 4e-6,\n    },\n    displayName: 'Claude 3.5 Haiku',\n  },\n  'claude-3-7-sonnet-latest': {\n    maxTokens: 200_000,\n    cost: {\n      prompt: 3e-6,\n      completion: 15e-6,\n    },\n    displayName: 'Claude 3.7 Sonnet',\n  },\n  'claude-sonnet-4-20250514': {\n    maxTokens: 200_000,\n    cost: {\n      prompt: 3e-6,\n      completion: 3.75e-6,\n    },\n    displayName: 'Claude Sonnet 4',\n  },\n  'claude-opus-4-20250514': {\n    maxTokens: 200_000,\n    cost: {\n      prompt: 15e-6,\n      completion: 18.75e-6,\n    },\n    displayName: 'Claude Opus 4',\n  },\n} satisfies Record<string, AnthropicModel>;\n\nexport type AnthropicModels = keyof typeof anthropicModels;\n\nexport const anthropicModelOptions = Object.entries(anthropicModels).map(([id, { displayName }]) => ({\n  value: id,\n  label: displayName,\n}));\n\nexport type Claude3ChatMessage = {\n  role: 'user' | 'assistant';\n  content: string | Claude3ChatMessageContentPart[];\n};\n\nexport type Claude3ChatMessageTextContentPart = {\n  type: 'text';\n  text: string;\n  cache_control: CacheControl;\n};\n\nexport type Claude3ChatMessageImageContentPart = {\n  type: 'image';\n  source: {\n    type: 'base64';\n    media_type: string;\n    data: string;\n  };\n  cache_control: CacheControl;\n};\n\nexport type Claude3ChatMessageDocumentContentPart = {\n  type: 'document';\n  source: {\n    type: 'base64';\n    media_type: string;\n    data: string;\n  };\n  title: string | undefined;\n  context: string | undefined;\n  citations:\n    | undefined\n    | {\n        enabled: true;\n      };\n  cache_control: CacheControl;\n};\n\nexport type Claude3ChatMessageToolResultContentPart = {\n  type: 'tool_result';\n  tool_use_id: string;\n  content: string | { type: 'text'; text: string }[];\n  cache_control: CacheControl;\n};\n\nexport type Claude3ChatMessageToolUseContentPart = {\n  type: 'tool_use';\n  id: string;\n  name: string;\n  input: object;\n  cache_control: CacheControl;\n};\n\nexport type Claude3ChatMessageContentPart =\n  | Claude3ChatMessageTextContentPart\n  | Claude3ChatMessageImageContentPart\n  | Claude3ChatMessageToolResultContentPart\n  | Claude3ChatMessageToolUseContentPart\n  | Claude3ChatMessageDocumentContentPart;\n\nexport type ChatMessageOptions = {\n  apiEndpoint: string;\n  apiKey: string;\n  model: AnthropicModels;\n  messages: Claude3ChatMessage[];\n  system?: SystemPrompt;\n  max_tokens: number;\n  stop_sequences?: string[];\n  temperature?: number;\n  top_p?: number;\n  top_k?: number;\n  signal?: AbortSignal;\n  stream?: boolean;\n  tools?: {\n    name: string;\n    description: string;\n    input_schema: object;\n  }[];\n  beta?: string;\n  additionalHeaders?: Record<string, string>;\n};\n\nexport type ChatCompletionOptions = {\n  apiEndpoint: string;\n  apiKey: string;\n  model: AnthropicModels;\n  prompt: string;\n  max_tokens_to_sample: number;\n  stop_sequences?: string[];\n  temperature?: number;\n  top_p?: number;\n  top_k?: number;\n  signal?: AbortSignal;\n  stream?: boolean;\n  additionalHeaders?: Record<string, string>;\n};\n\nexport type ChatCompletionChunk = {\n  completion: string;\n  stop_reason: 'stop_sequence' | null;\n  model: string;\n};\n\nexport type CacheControl = null | {\n  type: 'ephemeral';\n};\n\nexport type SystemPrompt = string | SystemPromptMessage[];\n\nexport type SystemPromptMessage = {\n  cache_control: CacheControl;\n  type: 'text';\n  text: string;\n};\n\nexport type ChatMessageChunk =\n  | {\n      type: 'message_start';\n      message: {\n        id: string;\n        type: string;\n        role: string;\n        content: {\n          type: 'text';\n          text: string;\n        }[];\n        model: AnthropicModels;\n        stop_reason: string | null;\n        stop_sequence: string | null;\n        usage: {\n          input_tokens: number;\n          output_tokens: number;\n        };\n      };\n    }\n  | {\n      type: 'content_block_start';\n      index: number;\n      content_block:\n        | {\n            type: 'text';\n            text: string;\n          }\n        | {\n            type: 'tool_use';\n            id: string;\n            name: string;\n            input?: object;\n          };\n    }\n  | {\n      type: 'ping';\n    }\n  | {\n      type: 'content_block_delta';\n      index: number;\n      delta:\n        | {\n            type: 'text_delta';\n            text: string;\n          }\n        | {\n            type: 'citations_delta';\n            citation: ChatMessageCitation;\n          }\n        | {\n            type: 'input_json_delta';\n            partial_json: string;\n          };\n    }\n  | {\n      type: 'message_delta';\n      delta: {\n        stop_reason: string | null;\n        stop_sequence: string | null;\n        usage: {\n          output_tokens: number;\n        };\n      };\n    }\n  | {\n      type: 'message_stop';\n    }\n  | {\n      type: 'content_block_stop';\n      index: number;\n    };\n\nexport type ChatMessageResponse = {\n  id: string;\n  content: ChatMessageContentItem[];\n  model: string;\n  stop_reason: 'end_turn';\n  stop_sequence: string;\n  usage: {\n    input_tokens: number;\n    output_tokens: number;\n  };\n};\n\nexport type ChatMessageTextContentItem = {\n  type: 'text';\n  text: string;\n  citations?: ChatMessageCitation[];\n};\n\nexport type ChatMessageToolUseContentItem = {\n  type: 'tool_use';\n  id: string;\n  name: string;\n  input: object;\n};\n\nexport type ChatMessageContentItem = ChatMessageTextContentItem | ChatMessageToolUseContentItem;\n\nexport type ChatMessageCitation =\n  | {\n      type: 'char_location';\n      cited_text: string;\n      document_index: number;\n      document_title: string | null;\n      start_char_index: number;\n      end_chat_index: number;\n    }\n  | {\n      type: 'page_location';\n      cited_text: string;\n      document_index: number;\n      document_title: string | null;\n      page_number: number;\n      end_page_number: number;\n    };\n\nexport async function* streamChatCompletions({\n  apiEndpoint,\n  apiKey,\n  signal,\n  additionalHeaders,\n  ...rest\n}: ChatCompletionOptions): AsyncGenerator<ChatCompletionChunk> {\n  const defaultSignal = new AbortController().signal;\n  const response = await fetchEventSource(`${apiEndpoint}/completions`, {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application/json',\n      'x-api-key': apiKey,\n      'anthropic-version': '2023-06-01',\n      'anthropic-dangerous-direct-browser-access': 'true',\n      ...additionalHeaders,\n    },\n    body: JSON.stringify({\n      ...rest,\n      stream: true,\n    }),\n    signal: signal ?? defaultSignal,\n  });\n\n  let hadChunks = false;\n\n  for await (const chunk of response.events()) {\n    hadChunks = true;\n\n    if (chunk === '[DONE]') {\n      return;\n    } else if (/\\[\\w+\\]/.test(chunk)) {\n      continue;\n    }\n\n    let data: ChatCompletionChunk;\n    try {\n      data = JSON.parse(chunk);\n    } catch (err) {\n      console.error('JSON parse failed on chunk: ', chunk);\n      throw err;\n    }\n\n    yield data;\n  }\n\n  if (!hadChunks) {\n    const responseJson = await response.json();\n    throw new AnthropicError(`No chunks received. Response: ${JSON.stringify(responseJson)}`, response, responseJson);\n  }\n}\n\nexport async function callMessageApi({\n  apiEndpoint,\n  apiKey,\n  signal,\n  tools,\n  beta,\n  additionalHeaders,\n  ...rest\n}: ChatMessageOptions): Promise<ChatMessageResponse> {\n  const defaultSignal = new AbortController().signal;\n  const response = await fetch(`${apiEndpoint}/messages`, {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application/json',\n      'x-api-key': apiKey,\n      'anthropic-version': '2023-06-01',\n      'anthropic-dangerous-direct-browser-access': 'true',\n      ...(beta ? { 'anthropic-beta': beta } : {}),\n      ...additionalHeaders,\n    },\n    body: JSON.stringify({\n      ...rest,\n      tools,\n      stream: false,\n    }),\n    signal: signal ?? defaultSignal,\n  });\n  const responseJson = await response.json();\n  if (response.status !== 200) {\n    throw new AnthropicError(responseJson?.error?.message ?? 'Request failed', response, responseJson);\n  }\n  return responseJson;\n}\n\nexport async function* streamMessageApi({\n  apiEndpoint,\n  apiKey,\n  signal,\n  beta,\n  additionalHeaders,\n  ...rest\n}: ChatMessageOptions): AsyncGenerator<ChatMessageChunk> {\n  // Use the Messages API for Claude 3 models\n  const defaultSignal = new AbortController().signal;\n  const response = await fetchEventSource(`${apiEndpoint}/messages`, {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application/json',\n      'x-api-key': apiKey,\n      'anthropic-version': '2023-06-01',\n      'anthropic-dangerous-direct-browser-access': 'true',\n      ...(beta ? { 'anthropic-beta': beta } : {}),\n      ...additionalHeaders,\n    },\n    body: JSON.stringify({\n      ...rest,\n      stream: true,\n    }),\n    signal: signal ?? defaultSignal,\n  });\n\n  let hadChunks = false;\n\n  for await (const chunk of response.events()) {\n    hadChunks = true;\n\n    if (chunk === '[message_stop]') {\n      return;\n    } else if (/^\\[\\w+\\]$/.test(chunk)) {\n      continue;\n    }\n\n    let data: ChatMessageChunk;\n    try {\n      data = JSON.parse(chunk);\n    } catch (err) {\n      console.error('JSON parse failed on chunk: ', chunk);\n      throw err;\n    }\n\n    yield data;\n  }\n\n  if (!hadChunks) {\n    const responseJson = await response.json();\n    throw new AnthropicError(`No chunks received. Response: ${JSON.stringify(responseJson)}`, response, responseJson);\n  }\n}\n\nexport class AnthropicError extends Error {\n  constructor(\n    message: string,\n    public readonly response: Response,\n    public readonly responseJson: unknown,\n  ) {\n    super(message);\n  }\n}\n", "import {\n  type ChartNode,\n  type ChatMessage,\n  type EditorDefinition,\n  type Inputs,\n  type InternalProcessContext,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type NodeUIData,\n  type Outputs,\n  type PluginNodeImpl,\n  type PortId,\n  type ScalarDataValue,\n  type ChatMessageMessagePart,\n} from '../../../index.js';\nimport {\n  type AnthropicModels,\n  type ChatCompletionOptions,\n  anthropicModelOptions,\n  anthropicModels,\n  streamChatCompletions,\n  AnthropicError,\n  type Claude3ChatMessage,\n  type Claude3ChatMessageContentPart,\n  streamMessageApi,\n  type ChatMessageOptions,\n  type Claude3ChatMessageTextContentPart,\n  type SystemPrompt,\n  type ChatMessageCitation,\n  type Claude3ChatMessageToolResultContentPart,\n} from '../anthropic.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { dedent } from 'ts-dedent';\nimport retry from 'p-retry';\nimport { match } from 'ts-pattern';\nimport { coerceType, coerceTypeOptional } from '../../../utils/coerceType.js';\nimport { addWarning } from '../../../utils/outputs.js';\nimport { getError } from '../../../utils/errors.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport { getScalarTypeOf, isArrayDataValue } from '../../../model/DataValue.js';\nimport type { TokenizerCallInfo } from '../../../integrations/Tokenizer.js';\nimport { assertNever } from '../../../utils/assertNever.js';\nimport { isNotNull } from '../../../utils/genericUtilFunctions.js';\nimport { uint8ArrayToBase64 } from '../../../utils/base64.js';\nimport { getInputOrData, cleanHeaders } from '../../../utils/inputs.js';\n\nexport type ChatAnthropicNode = ChartNode<'chatAnthropic', ChatAnthropicNodeData>;\n\nexport type ChatAnthropicNodeConfigData = {\n  model: AnthropicModels;\n  temperature: number;\n  useTopP: boolean;\n  top_p?: number;\n  top_k?: number;\n  maxTokens: number;\n  stop?: string;\n  enableToolUse?: boolean;\n  endpoint?: string;\n  overrideModel?: string;\n  enableCitations?: boolean;\n  headers?: { key: string; value: string }[];\n};\n\nexport type ChatAnthropicNodeData = ChatAnthropicNodeConfigData & {\n  useModelInput: boolean;\n  useTemperatureInput: boolean;\n  useTopPInput: boolean;\n  useTopKInput: boolean;\n  useUseTopPInput: boolean;\n  useMaxTokensInput: boolean;\n  useStop: boolean;\n  useStopInput: boolean;\n  useEndpointInput: boolean;\n  useOverrideModelInput: boolean;\n  useHeadersInput?: boolean;\n\n  /** Given the same set of inputs, return the same output without hitting GPT */\n  cache: boolean;\n\n  useAsGraphPartialOutput?: boolean;\n};\n\n// Temporary\nconst cache = new Map<string, Outputs>();\n\nexport const ChatAnthropicNodeImpl: PluginNodeImpl<ChatAnthropicNode> = {\n  create(): ChatAnthropicNode {\n    const chartNode: ChatAnthropicNode = {\n      type: 'chatAnthropic',\n      title: 'Chat (Anthropic)',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 275,\n      },\n      data: {\n        model: 'claude-sonnet-4-20250514',\n        useModelInput: false,\n\n        temperature: 0.5,\n        useTemperatureInput: false,\n\n        top_p: 1,\n        useTopPInput: false,\n\n        top_k: undefined,\n        useTopKInput: false,\n\n        useTopP: false,\n        useUseTopPInput: false,\n\n        maxTokens: 1024,\n        useMaxTokensInput: false,\n\n        useStop: false,\n        stop: '',\n        useStopInput: false,\n\n        cache: false,\n        useAsGraphPartialOutput: true,\n\n        enableToolUse: false,\n\n        endpoint: '',\n        useEndpointInput: false,\n\n        overrideModel: undefined,\n        useOverrideModelInput: false,\n\n        enableCitations: false,\n      },\n    };\n\n    return chartNode;\n  },\n\n  getInputDefinitions(data): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [];\n\n    if (data.model.startsWith('claude-3')) {\n      inputs.push({\n        dataType: 'string',\n        id: 'system' as PortId,\n        title: 'System Prompt',\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        dataType: 'number',\n        id: 'temperature' as PortId,\n        title: 'Temperature',\n      });\n    }\n\n    if (data.useTopPInput) {\n      inputs.push({\n        dataType: 'number',\n        id: 'top_p' as PortId,\n        title: 'Top P',\n      });\n    }\n\n    if (data.useUseTopPInput) {\n      inputs.push({\n        dataType: 'boolean',\n        id: 'useTopP' as PortId,\n        title: 'Use Top P',\n      });\n    }\n\n    if (data.useMaxTokensInput) {\n      inputs.push({\n        dataType: 'number',\n        id: 'maxTokens' as PortId,\n        title: 'Max Tokens',\n      });\n    }\n\n    if (data.useStopInput) {\n      inputs.push({\n        dataType: 'string',\n        id: 'stop' as PortId,\n        title: 'Stop',\n      });\n    }\n\n    inputs.push({\n      dataType: ['chat-message', 'chat-message[]'] as const,\n      id: 'prompt' as PortId,\n      title: 'Prompt',\n    });\n\n    if (data.enableToolUse) {\n      inputs.push({\n        dataType: ['gpt-function', 'gpt-function[]'] as const,\n        id: 'tools' as PortId,\n        title: 'Tools',\n        description: 'Tools to use in the model. To connect multiple tools, use an Array node.',\n        coerced: false,\n      });\n    }\n\n    if (data.useHeadersInput) {\n      inputs.push({\n        dataType: 'object',\n        id: 'headers' as PortId,\n        title: 'Headers',\n        description: 'Additional headers to send to the API.',\n      });\n    }\n\n    return inputs;\n  },\n\n  getOutputDefinitions(data): NodeOutputDefinition[] {\n    const outputs: NodeOutputDefinition[] = [];\n\n    outputs.push({\n      dataType: 'string',\n      id: 'response' as PortId,\n      title: 'Response',\n    });\n\n    if (data.enableCitations) {\n      outputs.push({\n        dataType: 'object[]',\n        id: 'citations' as PortId,\n        title: 'Citations',\n        description: 'Citations from the response, if any.',\n      });\n    }\n\n    if (data.enableToolUse) {\n      outputs.push({\n        dataType: 'object[]',\n        id: 'function-calls' as PortId,\n        title: 'Tool Calls',\n        description: 'The tool calls that were made, if any.',\n      });\n    }\n\n    outputs.push({\n      dataType: 'chat-message[]',\n      id: 'all-messages' as PortId,\n      title: 'All Messages',\n      description: 'All messages, with the response appended.',\n    });\n\n    return outputs;\n  },\n\n  getBody(data): string {\n    const modelName = data.overrideModel\n      ? data.overrideModel\n      : anthropicModels[data.model]?.displayName ?? 'Unknown Model';\n\n    return dedent`\n      ${modelName}\n      ${\n        data.useTopP\n          ? `Top P: ${data.useTopPInput ? '(Using Input)' : data.top_p}`\n          : `Temperature: ${data.useTemperatureInput ? '(Using Input)' : data.temperature}`\n      }\n      Max Tokens: ${data.maxTokens}\n      ${data.useStop ? `Stop: ${data.useStopInput ? '(Using Input)' : data.stop}` : ''}\n    `;\n  },\n\n  getEditors(): EditorDefinition<ChatAnthropicNode>[] {\n    return [\n      {\n        type: 'group',\n        label: 'Parameters',\n        defaultOpen: true,\n        editors: [\n          {\n            type: 'dropdown',\n            label: 'Model',\n            dataKey: 'model',\n            useInputToggleDataKey: 'useModelInput',\n            options: anthropicModelOptions,\n            disableIf: (d) => !!d.overrideModel?.trim(),\n            helperMessage: (d) => (!!d.overrideModel ? `Model is overridden to: ${d.overrideModel}` : ''),\n          },\n          {\n            type: 'number',\n            label: 'Temperature',\n            dataKey: 'temperature',\n            useInputToggleDataKey: 'useTemperatureInput',\n            min: 0,\n            max: 2,\n            step: 0.1,\n          },\n          {\n            type: 'number',\n            label: 'Top P',\n            dataKey: 'top_p',\n            useInputToggleDataKey: 'useTopPInput',\n            min: 0,\n            max: 1,\n            step: 0.1,\n          },\n          {\n            type: 'toggle',\n            label: 'Use Top P',\n            dataKey: 'useTopP',\n            useInputToggleDataKey: 'useUseTopPInput',\n          },\n          {\n            type: 'number',\n            label: 'Max Tokens',\n            dataKey: 'maxTokens',\n            useInputToggleDataKey: 'useMaxTokensInput',\n            min: 0,\n            max: Number.MAX_SAFE_INTEGER,\n            step: 1,\n          },\n          {\n            type: 'string',\n            label: 'Stop',\n            dataKey: 'stop',\n            useInputToggleDataKey: 'useStopInput',\n          },\n        ],\n      },\n      {\n        type: 'group',\n        label: 'Tools',\n        editors: [\n          {\n            type: 'toggle',\n            label: 'Enable Tool Use (disables streaming)',\n            dataKey: 'enableToolUse',\n          },\n          {\n            type: 'toggle',\n            label: 'Enable Citations',\n            dataKey: 'enableCitations',\n          },\n        ],\n      },\n      {\n        type: 'group',\n        label: 'Advanced',\n        editors: [\n          {\n            type: 'toggle',\n            label: 'Cache (same inputs, same outputs)',\n            dataKey: 'cache',\n          },\n          {\n            type: 'toggle',\n            label: 'Use for subgraph partial output',\n            dataKey: 'useAsGraphPartialOutput',\n          },\n          {\n            type: 'string',\n            label: 'Endpoint',\n            dataKey: 'endpoint',\n            useInputToggleDataKey: 'useEndpointInput',\n            helperMessage:\n              'Overrides the Anthropic API endpoint. Leave blank to use the default configured endpoint in settings, or https://api.anthropic.com/v1 if none is configured.',\n          },\n          {\n            type: 'string',\n            label: 'Override Model',\n            dataKey: 'overrideModel',\n            useInputToggleDataKey: 'useOverrideModelInput',\n            helperMessage: 'Overrides the AI model used for the chat node to this value.',\n          },\n          {\n            type: 'keyValuePair',\n            label: 'Headers',\n            dataKey: 'headers',\n            useInputToggleDataKey: 'useHeadersInput',\n            keyPlaceholder: 'Header',\n            helperMessage: 'Additional headers to send to the API.',\n          },\n        ],\n      },\n    ];\n  },\n\n  getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Makes a call to an Anthropic chat model. The settings contains many options for tweaking the model's behavior.\n      `,\n      infoBoxTitle: 'Chat (Anthropic) Node',\n      contextMenuTitle: 'Chat (Anthropic)',\n      group: ['AI'],\n    };\n  },\n\n  async process(data, inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const output: Outputs = {};\n    const rawModel = getInputOrData(data, inputs, 'model');\n    const overrideModel = getInputOrData(data, inputs, 'overrideModel');\n\n    const model = (overrideModel || rawModel) as AnthropicModels;\n\n    const temperature = data.useTemperatureInput\n      ? coerceTypeOptional(inputs['temperature' as PortId], 'number') ?? data.temperature\n      : data.temperature;\n    const topP = data.useTopPInput ? coerceTypeOptional(inputs['top_p' as PortId], 'number') ?? data.top_p : data.top_p;\n    const useTopP = data.useUseTopPInput\n      ? coerceTypeOptional(inputs['useTopP' as PortId], 'boolean') ?? data.useTopP\n      : data.useTopP;\n    const stop = data.useStopInput\n      ? data.useStop\n        ? coerceTypeOptional(inputs['stop' as PortId], 'string') ?? data.stop\n        : undefined\n      : data.stop;\n    const tools = data.enableToolUse\n      ? coerceTypeOptional(inputs['tools' as PortId], 'gpt-function[]') ?? []\n      : undefined;\n\n    const rivetChatMessages = getChatMessages(inputs);\n    const messages = await chatMessagesToClaude3ChatMessages(rivetChatMessages);\n\n    let prompt = messages.reduce((acc, message) => {\n      const content =\n        typeof message.content === 'string'\n          ? message.content\n          : message.content\n              .filter((c): c is Claude3ChatMessageTextContentPart => c.type === 'text')\n              .map((c) => c.text ?? '')\n              .join('');\n      if (message.role === 'user') {\n        return `${acc}\\n\\nHuman: ${content}`;\n      } else if (message.role === 'assistant') {\n        return `${acc}\\n\\nAssistant: ${content}`;\n      }\n      return acc;\n    }, '');\n    prompt += '\\n\\nAssistant:';\n\n    // Get the \"System\" prompt input for Claude 3 models\n    const system = data.model.startsWith('claude-3') ? getSystemPrompt(inputs) : undefined;\n\n    let { maxTokens } = data;\n    const tokenizerInfo: TokenizerCallInfo = {\n      node: context.node,\n      model,\n      endpoint: undefined,\n    };\n\n    const tokenCountEstimate = await context.tokenizer.getTokenCountForString(prompt, tokenizerInfo);\n    const modelInfo = anthropicModels[model] ?? {\n      maxTokens: Number.MAX_SAFE_INTEGER,\n      cost: {\n        prompt: 0,\n        completion: 0,\n      },\n    };\n\n    if (tokenCountEstimate >= modelInfo.maxTokens) {\n      throw new Error(\n        `The model ${model} can only handle ${modelInfo.maxTokens} tokens, but ${tokenCountEstimate} were provided in the prompts alone.`,\n      );\n    }\n\n    if (tokenCountEstimate + maxTokens > modelInfo.maxTokens) {\n      const message = `The model can only handle a maximum of ${\n        modelInfo.maxTokens\n      } tokens, but the prompts and max tokens together exceed this limit. The max tokens has been reduced to ${\n        modelInfo.maxTokens - tokenCountEstimate\n      }.`;\n      addWarning(output, message);\n      maxTokens = Math.floor((modelInfo.maxTokens - tokenCountEstimate) * 0.95); // reduce max tokens by 5% to be safe, calculation is a little wrong.\n    }\n\n    const headersFromData = (data.headers ?? []).reduce(\n      (acc, header) => {\n        acc[header.key] = header.value;\n        return acc;\n      },\n      {} as Record<string, string>,\n    );\n    const additionalHeaders = data.useHeadersInput\n      ? (coerceTypeOptional(inputs['headers' as PortId], 'object') as Record<string, string> | undefined) ??\n        headersFromData\n      : headersFromData;\n\n    const allAdditionalHeaders = cleanHeaders({\n      ...context.settings.chatNodeHeaders,\n      ...additionalHeaders,\n    });\n\n    try {\n      return await retry(\n        async () => {\n          const completionOptions: Omit<ChatCompletionOptions, 'apiKey' | 'apiEndpoint' | 'signal'> = {\n            model,\n            temperature: useTopP ? undefined : temperature,\n            top_p: useTopP ? topP : undefined,\n            max_tokens_to_sample: maxTokens ?? modelInfo.maxTokens,\n            stop_sequences: stop ? [stop] : undefined,\n            prompt,\n          };\n          const messageOptions: Omit<ChatMessageOptions, 'apiKey' | 'apiEndpoint' | 'signal'> = {\n            model,\n            temperature: useTopP ? undefined : temperature,\n            top_p: useTopP ? topP : undefined,\n            max_tokens: maxTokens ?? modelInfo.maxTokens,\n            stop_sequences: stop ? [stop] : undefined,\n            system,\n            messages,\n            tools: tools\n              ? tools.map((tool) => ({ name: tool.name, description: tool.description, input_schema: tool.parameters }))\n              : undefined,\n          };\n          const useMessageApi =\n            model.startsWith('claude-3') || model.startsWith('claude-sonnet') || model.startsWith('claude-opus');\n          const cacheKey = JSON.stringify(useMessageApi ? messageOptions : completionOptions);\n          if (data.cache) {\n            const cached = cache.get(cacheKey);\n            if (cached) {\n              return cached;\n            }\n          }\n\n          const startTime = Date.now();\n          const apiKey = context.getPluginConfig('anthropicApiKey');\n          const defaultApiEndpoint = context.getPluginConfig('anthropicApiEndpoint') || 'https://api.anthropic.com/v1';\n\n          const configuredEndpoint = getInputOrData(data, inputs, 'endpoint');\n\n          const apiEndpoint = configuredEndpoint?.trim() ? configuredEndpoint : defaultApiEndpoint;\n\n          if (useMessageApi) {\n            // Use the messages API for Claude 3 models\n            const chunks = streamMessageApi({\n              apiEndpoint,\n              apiKey: apiKey ?? '',\n              signal: context.signal,\n              beta: 'prompt-caching-2024-07-31',\n              additionalHeaders: allAdditionalHeaders,\n              ...messageOptions,\n            });\n\n            // Process the response chunks and update the output\n            const responseParts: string[] = [];\n            let requestTokens: number | undefined = undefined;\n            let responseTokens: number | undefined = undefined;\n            const citations: ChatMessageCitation[] = [];\n\n            type ToolCall = {\n              id: string;\n              name: string;\n              input: object;\n            };\n\n            // Track tool calls\n            const toolCalls: ToolCall[] = [];\n            let currentToolCall: ToolCall | null = null;\n            let accumulatedJsonString = '';\n\n            for await (const chunk of chunks) {\n              let completion: string = '';\n\n              if (chunk.type === 'content_block_start') {\n                if (chunk.content_block.type === 'text') {\n                  completion = chunk.content_block.text || '';\n                } else if (chunk.content_block.type === 'tool_use') {\n                  currentToolCall = {\n                    id: chunk.content_block.id,\n                    name: chunk.content_block.name,\n                    input: chunk.content_block.input || {},\n                  };\n                  accumulatedJsonString = '';\n                }\n              } else if (chunk.type === 'content_block_delta') {\n                if (chunk.delta.type === 'text_delta') {\n                  completion = chunk.delta.text;\n                } else if (chunk.delta.type === 'input_json_delta') {\n                  if (currentToolCall) {\n                    accumulatedJsonString += chunk.delta.partial_json || '';\n\n                    try {\n                      // Try to parse the accumulated JSON\n                      const parsedJson = JSON.parse(accumulatedJsonString);\n                      currentToolCall.input = parsedJson;\n                      accumulatedJsonString = '';\n                    } catch (e) {\n                      // Not valid JSON yet, keep accumulating\n                    }\n                  }\n                } else if (chunk.delta.type === 'citations_delta') {\n                  citations.push(chunk.delta.citation);\n                }\n              } else if (chunk.type === 'content_block_stop') {\n                if (currentToolCall) {\n                  if (accumulatedJsonString) {\n                    try {\n                      const parsedJson = JSON.parse(accumulatedJsonString);\n                      currentToolCall.input = parsedJson;\n                    } catch (e) {\n                      console.warn('Failed to parse tool call JSON input:', accumulatedJsonString);\n                    }\n                  }\n\n                  toolCalls.push({ ...currentToolCall });\n                  currentToolCall = null;\n                  accumulatedJsonString = '';\n                }\n              } else if (chunk.type === 'message_start' && chunk.message?.usage?.input_tokens) {\n                requestTokens = chunk.message.usage.input_tokens;\n              } else if (chunk.type === 'message_delta' && chunk.delta?.usage?.output_tokens) {\n                responseTokens = chunk.delta.usage.output_tokens;\n              }\n\n              if (completion) {\n                responseParts.push(completion);\n              }\n\n              output['response' as PortId] = {\n                type: 'string',\n                value: responseParts.join('').trim(),\n              };\n\n              if (toolCalls.length > 0) {\n                output['function-calls' as PortId] = {\n                  type: 'object[]',\n                  value: toolCalls.map((tool) => ({\n                    id: tool.id,\n                    name: tool.name,\n                    arguments: tool.input,\n                  })),\n                };\n              } else {\n                output['function-calls' as PortId] = {\n                  type: 'control-flow-excluded',\n                  value: undefined,\n                };\n              }\n\n              output['citations' as PortId] = {\n                type: 'object[]',\n                value: citations,\n              };\n\n              // Format function calls for the ChatMessage interface\n              const functionCalls = toolCalls.map((tool) => ({\n                name: tool.name,\n                arguments: typeof tool.input === 'object' ? JSON.stringify(tool.input) : tool.input,\n                id: tool.id,\n              }));\n\n              output['all-messages' as PortId] = {\n                type: 'chat-message[]',\n                value: [\n                  ...rivetChatMessages,\n                  {\n                    type: 'assistant',\n                    message: responseParts.join('').trim(),\n                    function_call: functionCalls.length === 1 ? functionCalls[0] : undefined,\n                    function_calls: functionCalls.length > 0 ? functionCalls : undefined,\n                  } satisfies ChatMessage,\n                ],\n              };\n\n              context.onPartialOutputs?.(output);\n            }\n\n            // Final validation\n            if (responseParts.length === 0 && toolCalls.length === 0) {\n              throw new Error('No response or tool calls received from Anthropic');\n            }\n\n            output['requestTokens' as PortId] = { type: 'number', value: requestTokens ?? tokenCountEstimate };\n            const responseTokenCount =\n              responseTokens ?? (await context.tokenizer.getTokenCountForString(responseParts.join(''), tokenizerInfo));\n            output['responseTokens' as PortId] = { type: 'number', value: responseTokenCount };\n          } else {\n            // Use the normal chat completion method for non-Claude 3 models\n            const chunks = streamChatCompletions({\n              apiEndpoint,\n              apiKey: apiKey ?? '',\n              signal: context.signal,\n              additionalHeaders: allAdditionalHeaders,\n              ...completionOptions,\n            });\n\n            // Process the response chunks and update the output\n            const responseParts: string[] = [];\n            for await (const chunk of chunks) {\n              if (!chunk.completion) {\n                continue;\n              }\n              responseParts.push(chunk.completion);\n              output['response' as PortId] = {\n                type: 'string',\n                value: responseParts.join('').trim(),\n              };\n              context.onPartialOutputs?.(output);\n            }\n\n            if (responseParts.length === 0) {\n              throw new Error('No response from Anthropic');\n            }\n\n            output['all-messages' as PortId] = {\n              type: 'chat-message[]',\n              value: [\n                ...rivetChatMessages,\n                {\n                  type: 'assistant',\n                  message: responseParts.join('').trim(),\n                  function_call: undefined,\n                  function_calls: undefined,\n                } satisfies ChatMessage,\n              ],\n            };\n            output['requestTokens' as PortId] = { type: 'number', value: tokenCountEstimate };\n            const responseTokenCount = await context.tokenizer.getTokenCountForString(\n              responseParts.join(''),\n              tokenizerInfo,\n            );\n            output['responseTokens' as PortId] = { type: 'number', value: responseTokenCount };\n          }\n\n          const cost = getCostForTokens(\n            {\n              requestTokens: output['requestTokens' as PortId]?.value as number,\n              responseTokens: output['responseTokens' as PortId]?.value as number,\n            },\n            model,\n          );\n          if (cost != null) {\n            output['cost' as PortId] = { type: 'number', value: cost };\n          }\n\n          const endTime = Date.now();\n\n          const duration = endTime - startTime;\n          output['duration' as PortId] = { type: 'number', value: duration };\n\n          Object.freeze(output);\n          cache.set(cacheKey, output);\n\n          return output;\n        },\n        {\n          forever: true,\n          retries: 10000,\n          maxRetryTime: 1000 * 60 * 5,\n          factor: 2.5,\n          minTimeout: 500,\n          maxTimeout: 5000,\n          randomize: true,\n          signal: context.signal,\n          onFailedAttempt(err) {\n            context.trace(`ChatAnthropicNode failed, retrying: ${err.toString()}`);\n\n            if (context.signal.aborted) {\n              throw new Error('Aborted');\n            }\n\n            if (err instanceof AnthropicError) {\n              if (err.response.status >= 400 && err.response.status < 500) {\n                if ((err.responseJson as any).error?.message) {\n                  throw new Error((err.responseJson as any).error.message);\n                }\n              }\n            }\n          },\n        },\n      );\n    } catch (error) {\n      context.trace(getError(error).stack ?? 'Missing stack');\n      throw new Error(`Error processing ChatAnthropicNode: ${(error as Error).message}`);\n    }\n  },\n};\n\nexport const chatAnthropicNode = pluginNodeDefinition(ChatAnthropicNodeImpl, 'Chat');\n\nexport function getSystemPrompt(inputs: Inputs): SystemPrompt | undefined {\n  const systemInput = inputs['system' as PortId];\n\n  const system = coerceTypeOptional(systemInput, 'string');\n\n  if (system) {\n    return [\n      {\n        type: 'text',\n        text: system,\n        cache_control:\n          systemInput?.type === 'chat-message'\n            ? systemInput.value.isCacheBreakpoint\n              ? { type: 'ephemeral' }\n              : null\n            : null,\n      },\n    ];\n  }\n\n  const prompt = inputs['prompt' as PortId];\n  if (prompt && prompt.type === 'chat-message[]') {\n    const systemMessages = prompt.value.filter((message) => message.type === 'system');\n    if (systemMessages.length) {\n      const converted = systemMessages.map((message) => {\n        return {\n          type: 'text' as const,\n          text: coerceType({ type: 'chat-message', value: message }, 'string'),\n          cache_control: message.isCacheBreakpoint ? { type: 'ephemeral' as const } : null,\n        };\n      });\n\n      return converted;\n    }\n  }\n\n  return undefined;\n}\n\nfunction getChatMessages(inputs: Inputs) {\n  const prompt = inputs['prompt' as PortId];\n  if (!prompt) {\n    throw new Error('Prompt is required');\n  }\n\n  const chatMessages = match(prompt)\n    .with({ type: 'chat-message' }, (p) => [p.value])\n    .with({ type: 'chat-message[]' }, (p) => p.value)\n    .with({ type: 'string' }, (p): ChatMessage[] => [{ type: 'user', message: p.value }])\n    .with({ type: 'string[]' }, (p): ChatMessage[] => p.value.map((v) => ({ type: 'user', message: v })))\n    .otherwise((p): ChatMessage[] => {\n      if (isArrayDataValue(p)) {\n        const stringValues = (p.value as readonly unknown[]).map((v) =>\n          coerceType(\n            {\n              type: getScalarTypeOf(p.type),\n              value: v,\n            } as ScalarDataValue,\n            'string',\n          ),\n        );\n\n        return stringValues.filter((v) => v != null).map((v) => ({ type: 'user', message: v }));\n      }\n\n      const coercedMessage = coerceType(p, 'chat-message');\n      if (coercedMessage != null) {\n        return [coercedMessage];\n      }\n\n      const coercedString = coerceType(p, 'string');\n      return coercedString != null ? [{ type: 'user', message: coerceType(p, 'string') }] : [];\n    });\n\n  return chatMessages;\n}\n\nexport async function chatMessagesToClaude3ChatMessages(chatMessages: ChatMessage[]): Promise<Claude3ChatMessage[]> {\n  const messages: Claude3ChatMessage[] = (await Promise.all(chatMessages.map(chatMessageToClaude3ChatMessage))).filter(\n    isNotNull,\n  );\n\n  // Combine sequential tool_result messages into a single user message with multiple content items\n  const combinedMessages = messages.reduce<Claude3ChatMessage[]>((acc, message) => {\n    if (\n      message.role === 'user' &&\n      Array.isArray(message.content) &&\n      message.content.length === 1 &&\n      message.content[0]!.type === 'tool_result'\n    ) {\n      const last = acc.at(-1);\n      if (last?.role === 'user' && Array.isArray(last.content) && last.content.every((c) => c.type === 'tool_result')) {\n        const content = last.content.concat(message.content as Claude3ChatMessageToolResultContentPart[]);\n        return [...acc.slice(0, -1), { ...last, content }];\n      }\n    }\n\n    return [...acc, message];\n  }, []);\n\n  return combinedMessages;\n}\n\nasync function chatMessageToClaude3ChatMessage(message: ChatMessage): Promise<Claude3ChatMessage | undefined> {\n  if (message.type === 'system') {\n    return undefined;\n  }\n\n  if (message.type === 'function') {\n    // Interpret function messages as user messages with tool_result content items (making Claude API more similar to OpenAI's)\n    const content = (Array.isArray(message.message) ? message.message : [message.message])\n      .map((m) => (typeof m === 'string' ? { type: 'text' as const, text: m } : undefined))\n      .filter(isNotNull);\n    return {\n      role: 'user',\n      content: [\n        {\n          type: 'tool_result',\n          tool_use_id: message.name,\n          content: content.length === 1 ? content[0]!.text : content,\n          cache_control: message.isCacheBreakpoint ? { type: 'ephemeral' } : null,\n        },\n      ],\n    };\n  }\n\n  const content = Array.isArray(message.message)\n    ? await Promise.all(message.message.map((part) => chatMessageContentToClaude3ChatMessage(part)))\n    : [await chatMessageContentToClaude3ChatMessage(message.message)];\n\n  if (message.type === 'assistant' && message.function_calls) {\n    content.push(\n      ...message.function_calls.map((fc) => ({\n        type: 'tool_use' as const,\n        id: fc.id!,\n        name: fc.name,\n        input: JSON.parse(fc.arguments),\n        cache_control: message.isCacheBreakpoint ? { type: 'ephemeral' as const } : null,\n      })),\n    );\n  } else if (message.type === 'assistant' && message.function_call) {\n    content.push({\n      type: 'tool_use',\n      id: message.function_call.id!,\n      name: message.function_call.name,\n      input: JSON.parse(message.function_call.arguments),\n      cache_control: message.isCacheBreakpoint ? { type: 'ephemeral' } : null,\n    });\n  }\n\n  // If the message is a cache breakpoint, cache using the last content item of the message\n  if (message.isCacheBreakpoint) {\n    content.at(-1)!.cache_control = { type: 'ephemeral' };\n  }\n\n  return {\n    role: message.type,\n    content,\n  };\n}\n\nasync function chatMessageContentToClaude3ChatMessage(\n  content: ChatMessageMessagePart,\n): Promise<Claude3ChatMessageContentPart> {\n  if (typeof content === 'string') {\n    return {\n      type: 'text',\n      text: content,\n      cache_control: null, // set later\n    };\n  }\n  switch (content.type) {\n    case 'image':\n      return {\n        type: 'image',\n        source: {\n          type: 'base64' as const,\n          media_type: content.mediaType as string,\n          data: (await uint8ArrayToBase64(content.data)) ?? '',\n        },\n        cache_control: null, // set later\n      };\n    case 'url':\n      throw new Error('unable to convert urls for Claude');\n    case 'document':\n      return {\n        type: 'document',\n        source: {\n          type: 'base64' as const,\n          data: (await uint8ArrayToBase64(content.data)) ?? '',\n          media_type: content.mediaType as string,\n        },\n        title: content.title?.trim() ? content.title.trim() : undefined,\n        context: content.context?.trim() ? content.context.trim() : undefined,\n        citations: content.enableCitations ? { enabled: true } : undefined,\n        cache_control: null, // set later\n      };\n    default:\n      assertNever(content);\n  }\n}\n\nfunction getCostForTokens(\n  tokenCounts: { requestTokens: number; responseTokens: number },\n  model: AnthropicModels,\n): number | undefined {\n  const modelInfo = anthropicModels[model];\n  if (modelInfo == null) {\n    return undefined;\n  }\n  return modelInfo.cost.prompt * tokenCounts.requestTokens + modelInfo.cost.completion * tokenCounts.responseTokens;\n}\n", "export function assertNever(x: never): never {\n  throw new Error(`Unexpected object: ${x}`);\n}\n", "import { type RivetPlugin } from '../../index.js';\nimport { chatAnthropicNode } from './nodes/ChatAnthropicNode.js';\n\nexport const anthropicPlugin: RivetPlugin = {\n  id: 'anthropic',\n  name: 'Anthropic',\n\n  register: (register) => {\n    register(chatAnthropicNode);\n  },\n\n  configSpec: {\n    anthropicApiKey: {\n      type: 'secret',\n      label: 'Anthropic API Key',\n      description: 'The API key for the Anthropic service.',\n      pullEnvironmentVariable: 'ANTHROPIC_API_KEY',\n      helperText: 'You may also set the ANTHROPIC_API_KEY environment variable.',\n    },\n    anthropicApiEndpoint: {\n      type: 'string',\n      label: 'Anthropic API Endpoint',\n      description: 'The API endpoint for the Anthropic service.',\n      pullEnvironmentVariable: 'ANTHROPIC_API_ENDPOINT',\n      helperText:\n        'Defaults to https://api.anthropic.com/v1. You may also set the ANTHROPIC_API_ENDPOINT environment variable.',\n      default: 'https://api.anthropic.com/v1',\n    },\n  },\n};\n", "import { anthropicPlugin } from './plugin.js';\n\nexport default anthropicPlugin;\n", "import { nanoid } from 'nanoid/non-secure';\nimport { dedent } from 'ts-dedent';\nimport {\n  Battle,\n  ClosedQA,\n  Factuality,\n  Humor,\n  Possible,\n  Security,\n  Summary,\n  Translation,\n  Sql,\n  type templates,\n} from 'autoevals';\nimport type {\n  ChartNode,\n  EditorDefinition,\n  Inputs,\n  InternalProcessContext,\n  NodeId,\n  NodeInputDefinition,\n  NodeOutputDefinition,\n  NodeUIData,\n  Outputs,\n  PluginNodeImpl,\n  PortId,\n} from '../../index.js';\nimport { match } from 'ts-pattern';\nimport { coerceType } from '../../utils/coerceType.js';\nimport { pluginNodeDefinition } from '../../model/NodeDefinition.js';\n\nexport type AutoEvalsNode = ChartNode<'autoevals', AutoEvalsNodeData>;\n\nexport type AutoEvalsNodeData = {\n  evaluatorName?: keyof typeof templates;\n};\n\nconst options = [\n  { label: 'Factuality', value: 'factuality' },\n  { label: 'Humor', value: 'humor' },\n  { label: 'Security', value: 'security' },\n  { label: 'Possible', value: 'possible' },\n  { label: 'Summary', value: 'summary' },\n  { label: 'Translation', value: 'translation' },\n  { label: 'Battle', value: 'battle' },\n  { label: 'Closed Q&A', value: 'closed_q_a' },\n  { label: 'SQL', value: 'sql' },\n];\n\nexport const AutoEvalsNodeImpl: PluginNodeImpl<AutoEvalsNode> = {\n  create(): AutoEvalsNode {\n    const chartNode: AutoEvalsNode = {\n      type: 'autoevals',\n      title: 'Autoevals',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 250,\n      },\n      data: {\n        evaluatorName: 'factuality',\n      },\n    };\n\n    return chartNode;\n  },\n\n  getInputDefinitions(data): NodeInputDefinition[] {\n    const base: NodeInputDefinition[] = [\n      {\n        id: 'output' as PortId,\n        dataType: 'string',\n        title: 'Output',\n      },\n      {\n        id: 'expected' as PortId,\n        dataType: 'string',\n        title: 'Expected',\n      },\n    ];\n\n    const forEvaluator: NodeInputDefinition[] = match(data.evaluatorName)\n      .with('factuality', (): NodeInputDefinition[] => [\n        {\n          id: 'input' as PortId,\n          dataType: 'string',\n          title: 'Input',\n        },\n      ])\n      .with('battle', (): NodeInputDefinition[] => [\n        {\n          id: 'instructions' as PortId,\n          dataType: 'string',\n          title: 'Instructions',\n        },\n      ])\n      .with('closed_q_a', (): NodeInputDefinition[] => [\n        {\n          id: 'input' as PortId,\n          dataType: 'string',\n          title: 'Input',\n        },\n        {\n          id: 'criteria' as PortId,\n          dataType: 'string',\n          title: 'Criteria',\n        },\n      ])\n      .with('humor', (): NodeInputDefinition[] => [])\n      .with('possible', (): NodeInputDefinition[] => [\n        {\n          id: 'input' as PortId,\n          dataType: 'string',\n          title: 'Input',\n        },\n      ])\n      .with('security', (): NodeInputDefinition[] => [])\n      .with('summary', (): NodeInputDefinition[] => [\n        {\n          id: 'input' as PortId,\n          dataType: 'string',\n          title: 'Input',\n        },\n      ])\n      .with('translation', (): NodeInputDefinition[] => [\n        {\n          id: 'input' as PortId,\n          dataType: 'string',\n          title: 'Input',\n        },\n        {\n          id: 'language' as PortId,\n          dataType: 'string',\n          title: 'Language',\n        },\n      ])\n      .with('sql', (): NodeInputDefinition[] => [\n        {\n          id: 'input' as PortId,\n          dataType: 'string',\n          title: 'Input',\n        },\n      ])\n      .with(undefined, (): NodeInputDefinition[] => [])\n      .exhaustive();\n\n    return [...forEvaluator, ...base];\n  },\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        dataType: 'number',\n        id: 'score' as PortId,\n        title: 'Score',\n      },\n      {\n        dataType: 'string',\n        id: 'rationale' as PortId,\n        title: 'Rationale',\n      },\n      {\n        dataType: 'object',\n        id: 'metadata' as PortId,\n        title: 'Metadata',\n      },\n    ];\n  },\n\n  getEditors(): EditorDefinition<AutoEvalsNode>[] {\n    return [\n      {\n        type: 'dropdown',\n        dataKey: 'evaluatorName',\n        label: 'Evaluator',\n        options,\n      },\n    ];\n  },\n\n  getBody(data): string | undefined {\n    return options.find((option) => option.value === data.evaluatorName)?.label ?? 'None';\n  },\n\n  getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Evaluates the validity of a response using the autoevals library.\n      `,\n      infoBoxTitle: 'Autoevals Node',\n      contextMenuTitle: 'Autoevals',\n      group: 'Custom',\n    };\n  },\n\n  async process(data, inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const evaluatorName = data.evaluatorName;\n\n    const output = coerceType(inputs['output' as PortId], 'string');\n    const expected = coerceType(inputs['expected' as PortId], 'string');\n\n    const baseArgs = {\n      output,\n      expected,\n      openAiApiKey: context.settings.openAiKey,\n      openAiOrganizationId: context.settings.openAiOrganization,\n    };\n\n    const result = await match(evaluatorName)\n      .with('factuality', () => {\n        const input = coerceType(inputs['input' as PortId], 'string');\n        return Factuality({ ...baseArgs, input });\n      })\n      .with('battle', () => {\n        const instructions = coerceType(inputs['instructions' as PortId], 'string');\n        return Battle({ ...baseArgs, instructions });\n      })\n      .with('closed_q_a', () => {\n        const input = coerceType(inputs['input' as PortId], 'string');\n        const criteria = coerceType(inputs['criteria' as PortId], 'string');\n        return ClosedQA({ ...baseArgs, input, criteria });\n      })\n      .with('humor', () => {\n        return Humor({ ...baseArgs });\n      })\n      .with('possible', () => {\n        const input = coerceType(inputs['input' as PortId], 'string');\n        return Possible({ ...baseArgs, input });\n      })\n      .with('security', () => {\n        return Security({ ...baseArgs });\n      })\n      .with('summary', () => {\n        const input = coerceType(inputs['input' as PortId], 'string');\n        return Summary({ ...baseArgs, input });\n      })\n      .with('translation', () => {\n        const input = coerceType(inputs['input' as PortId], 'string');\n        const language = coerceType(inputs['language' as PortId], 'string');\n        return Translation({ ...baseArgs, input, language });\n      })\n      .with('sql', () => {\n        const input = coerceType(inputs['input' as PortId], 'string');\n        return Sql({ ...baseArgs, input });\n      })\n      .with(undefined, () => {\n        throw new Error('Evaluator name is undefined');\n      })\n      .exhaustive();\n\n    return {\n      ['score' as PortId]: {\n        type: 'number',\n        value: result.score,\n      },\n      ['rationale' as PortId]: {\n        type: 'string',\n        value: (result.metadata?.rationale as string | undefined) ?? '',\n      },\n      ['metadata' as PortId]: {\n        type: 'object',\n        value: result.metadata as Record<string, unknown>,\n      },\n    };\n  },\n};\n\nexport const autoEvalsNode = pluginNodeDefinition(AutoEvalsNodeImpl, 'Autoevals');\n", "import type { RivetPlugin } from '../../index.js';\nimport { autoEvalsNode } from './AutoEvalsNode.js';\n\nexport const autoevalsPlugin: RivetPlugin = {\n  id: 'autoevals',\n  name: 'Autoevals',\n  register: (register) => {\n    register(autoEvalsNode);\n  },\n};\n", "import { autoevalsPlugin } from './plugin.js';\n\nexport default autoevalsPlugin;\n", "import { nanoid } from 'nanoid/non-secure';\nimport { dedent } from 'ts-dedent';\nimport {\n  type AnyDataValue,\n  type ChartNode,\n  type EditorDefinition,\n  type Inputs,\n  type InternalProcessContext,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type NodeUIData,\n  type Outputs,\n  type PortId,\n  type StringArrayDataValue,\n  type StringDataValue,\n  type ObjectDataValue,\n  type ArrayDataValue,\n  type PluginNodeImpl,\n} from '../../index.js';\nimport {\n  type LemurNodeData,\n  getClient,\n  getLemurParams,\n  lemurEditorDefinitions,\n  lemurInputDefinitions,\n} from './lemurHelpers.js';\nimport { coerceType } from '../../utils/coerceType.js';\nimport { pluginNodeDefinition } from '../../model/NodeDefinition.js';\nimport { type LemurQuestion, type LemurQuestionAnswerParams } from 'assemblyai';\n\nexport type LemurQaNode = ChartNode<'assemblyAiLemurQa', LemurQaNodeData>;\n\nexport type LemurQaNodeData = LemurNodeData & {\n  questions_answer_format?: string;\n  questions_context?: string;\n  questions_answer_options?: string;\n};\n\nexport const LemurQaNodeImpl = {\n  create(): LemurQaNode {\n    const chartNode: LemurQaNode = {\n      type: 'assemblyAiLemurQa',\n      title: 'LeMUR Question & Answers',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 250,\n      },\n      data: {\n        final_model: 'default',\n      },\n    };\n\n    return chartNode;\n  },\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    return [\n      ...lemurInputDefinitions,\n      {\n        id: 'questions' as PortId,\n        dataType: ['string', 'string[]', 'object', 'object[]', 'any', 'any[]'],\n        title: 'Questions',\n      },\n      {\n        id: 'context' as PortId,\n        dataType: 'string',\n        title: 'Context',\n      },\n    ];\n  },\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        dataType: 'object[]',\n        id: 'response' as PortId,\n        title: 'Response',\n      },\n    ];\n  },\n\n  getEditors(): EditorDefinition<LemurQaNode>[] {\n    return [\n      {\n        type: 'string',\n        label: 'Context',\n        dataKey: 'context',\n      },\n      ...(lemurEditorDefinitions as unknown as EditorDefinition<LemurQaNode>[]),\n      {\n        type: 'string',\n        label: 'Questions Answer Format',\n        dataKey: 'questions_answer_format',\n      },\n      {\n        type: 'string',\n        label: 'Questions Context',\n        dataKey: 'questions_context',\n      },\n      {\n        type: 'string',\n        label: 'Questions Answer Options',\n        dataKey: 'questions_answer_options',\n      },\n    ];\n  },\n\n  getBody(): string | undefined {\n    return '';\n  },\n\n  getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`Use AssemblyAI LeMUR to ask questions about transcripts`,\n      infoBoxTitle: 'Use AssemblyAI LeMUR Question & Answer',\n      contextMenuTitle: 'LeMUR Q&A',\n      group: ['AI', 'AssemblyAI'],\n    };\n  },\n\n  async process(data, inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const client = getClient(context);\n\n    const questions = getQuestions(inputs).map((question) => applyQuestionEditors(data, question));\n\n    const params: LemurQuestionAnswerParams = {\n      questions,\n      ...getLemurParams(inputs, data),\n    };\n\n    const { response } = await client.lemur.questionAnswer(params);\n    return {\n      ['response' as PortId]: {\n        type: 'object[]',\n        value: response,\n      },\n    };\n  },\n} satisfies PluginNodeImpl<LemurQaNode>;\n\nfunction getQuestions(inputs: Inputs): LemurQuestion[] {\n  const input = inputs['questions' as PortId] as\n    | StringDataValue\n    | StringArrayDataValue\n    | AnyDataValue\n    | ObjectDataValue\n    | ArrayDataValue<ObjectDataValue>\n    | ArrayDataValue<AnyDataValue>;\n\n  if (!input) throw new Error('Questions are required.');\n\n  if (input.type === 'string') {\n    return [\n      {\n        question: coerceType(input, 'string'),\n      },\n    ];\n  } else if (input.type === 'string[]') {\n    return coerceType(input, 'string[]').map((question) => ({ question }));\n  } else if (input.type === 'object') {\n    return [coerceType(input, 'object')] as LemurQuestion[];\n  } else if (input.type === 'object[]') {\n    return coerceType(input, 'object[]') as unknown as LemurQuestion[];\n  } else if (input.type === 'any' && typeof input.value === 'string') {\n    return [\n      {\n        question: coerceType(input, 'string'),\n      },\n    ];\n  } else if ((input.type === 'any' && Array.isArray(input.value)) || input.type === 'any[]') {\n    return (input.value as any[]).map<LemurQuestion>((question: any) => {\n      if (typeof question === 'string') {\n        return { question };\n      } else if (typeof question === 'object') {\n        return question as LemurQuestion;\n      } else {\n        throw new Error('Question must be a string or object.');\n      }\n    });\n  }\n  throw new Error('Questions must be a string, string[], a question object, or an array of question objects.');\n}\n\nfunction applyQuestionEditors(data: LemurQaNodeData, question: LemurQuestion): LemurQuestion {\n  if (!('answer_format' in question) && data.questions_answer_format) {\n    question.answer_format = data.questions_answer_format;\n  }\n  if (!('answer_options' in question) && data.questions_answer_options) {\n    question.answer_options = data.questions_answer_options.split(';');\n  }\n  if (!('context' in question) && data.questions_context) {\n    question.context = data.questions_context;\n  }\n\n  return question;\n}\n\nexport const lemurQaNode = pluginNodeDefinition(LemurQaNodeImpl, 'LeMUR Q&A');\n", "import { AssemblyAI } from 'assemblyai';\nimport type { LemurBaseParams } from 'assemblyai';\nimport {\n  type AnyDataValue,\n  type ArrayDataValue,\n  type Inputs,\n  type InternalProcessContext,\n  type PortId,\n  type StringArrayDataValue,\n  type StringDataValue,\n} from '../../index.js';\nimport { coerceType, coerceTypeOptional } from '../../utils/coerceType.js';\n\nfunction getTranscriptIds(inputs: Inputs): string[] | undefined {\n  const input = inputs['transcript_ids' as PortId] as\n    | StringDataValue\n    | StringArrayDataValue\n    | AnyDataValue\n    | ArrayDataValue<AnyDataValue>;\n  if (!input) return undefined;\n\n  if (input.type === 'string' || (input.type === 'any' && typeof input.value === 'string')) {\n    return [coerceType(input, 'string')];\n  } else if (\n    input.type === 'string[]' ||\n    input.type === 'any[]' ||\n    (input.type === 'any' && Array.isArray(input.value))\n  ) {\n    return coerceType(input, 'string[]');\n  }\n  throw new Error('Transcript IDs must be a string or string[] of transcript IDs.');\n}\n\nconst userAgent = {\n  integration: {\n    name: 'Rivet',\n    version: '1.0.1',\n  },\n};\nexport function getClient(context: InternalProcessContext): AssemblyAI {\n  const apiKey = context.getPluginConfig('assemblyAiApiKey');\n  if (!apiKey) {\n    throw new Error('AssemblyAI API key not set.');\n  }\n  return new AssemblyAI({ apiKey, userAgent });\n}\n\nexport function getLemurParams(inputs: Inputs, editorData: LemurNodeData): LemurBaseParams {\n  const params: LemurBaseParams = {\n    transcript_ids: getTranscriptIds(inputs),\n    input_text: coerceTypeOptional(inputs['input_text' as PortId], 'string'),\n    context: coerceTypeOptional(inputs['context' as PortId], 'string') || editorData.context || undefined,\n    final_model: editorData.final_model && editorData.final_model !== 'default' ? editorData.final_model : undefined,\n    max_output_size: editorData.max_output_size,\n    temperature: editorData.temperature,\n  };\n\n  return params;\n}\n\nexport const lemurInputDefinitions = [\n  {\n    id: 'transcript_ids' as PortId,\n    dataType: ['string', 'string[]', 'any', 'any[]'],\n    title: 'Transcript IDs',\n  },\n  {\n    id: 'input_text' as PortId,\n    dataType: ['string'],\n    title: 'Input Text',\n  },\n] as const;\n\nexport const lemurEditorDefinitions = [\n  {\n    type: 'dropdown',\n    label: 'Final Model',\n    dataKey: 'final_model',\n    options: [\n      {\n        value: 'anthropic/claude-3-5-sonnet',\n        label: 'Claude 3.5 Sonnet (on Anthropic)',\n      },\n      {\n        value: 'anthropic/claude-3-opus',\n        label: 'Claude 3 Opus (on Anthropic)',\n      },\n      {\n        value: 'anthropic/claude-3-haiku',\n        label: 'Claude 3 Haiku (on Anthropic)',\n      },\n      {\n        value: 'anthropic/claude-3-sonnet',\n        label: 'Claude 3 Sonnet (on Anthropic)',\n      },\n      {\n        value: 'anthropic/claude-2-1',\n        label: 'Claude 2.1 (on Anthropic)',\n      },\n      {\n        value: 'anthropic/claude-2',\n        label: 'Claude 2.1 (on Anthropic)',\n      },\n      {\n        value: 'default',\n        label: 'Default',\n      },\n      {\n        value: 'anthropic/claude-instant-1-2',\n        label: 'Claude Instant 1.2 (on Anthropic)',\n      },\n      {\n        value: 'basic',\n        label: 'Basic',\n      },\n      {\n        value: 'assemblyai/mistral-7b',\n        label: 'Mistral 7B (hosted by AssemblyAI)',\n      },\n    ],\n  },\n  {\n    type: 'number',\n    label: 'Maximum Output Size',\n    dataKey: 'max_output_size',\n  },\n  {\n    type: 'number',\n    label: 'Temperature',\n    dataKey: 'temperature',\n    min: 0,\n    max: 1,\n  },\n] as const;\n\nexport type FinalModel =\n  | 'anthropic/claude-3-5-sonnet'\n  | 'anthropic/claude-3-opus'\n  | 'anthropic/claude-3-haiku'\n  | 'anthropic/claude-3-sonnet'\n  | 'anthropic/claude-2-1'\n  | 'anthropic/claude-2'\n  | 'default'\n  | 'anthropic/claude-instant-1-2'\n  | 'basic'\n  | 'assemblyai/mistral-7b';\n\nexport type LemurNodeData = {\n  context?: string;\n  final_model?: FinalModel;\n  max_output_size?: number;\n  temperature?: number;\n};\n", "import { nanoid } from 'nanoid/non-secure';\nimport { dedent } from 'ts-dedent';\nimport type { TranscribeParams, TranscriptParams } from 'assemblyai';\nimport {\n  type AnyDataValue,\n  type AudioDataValue,\n  type ChartNode,\n  type EditorDefinition,\n  type Inputs,\n  type InternalProcessContext,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type NodeUIData,\n  type Outputs,\n  type PluginNodeImpl,\n  type PortId,\n  type StringDataValue,\n} from '../../index.js';\nimport { getClient } from './lemurHelpers.js';\nimport { pluginNodeDefinition } from '../../model/NodeDefinition.js';\nimport { coerceType } from '../../utils/coerceType.js';\n\nexport type TranscribeAudioNode = ChartNode<'assemblyAiTranscribeAudio', TranscribeAudioNodeData>;\n\nexport type TranscribeAudioNodeData = {\n  transcriptParameters?: string;\n};\n\nexport const TranscribeAudioNodeImpl: PluginNodeImpl<TranscribeAudioNode> = {\n  create(): TranscribeAudioNode {\n    const chartNode: TranscribeAudioNode = {\n      type: 'assemblyAiTranscribeAudio',\n      title: 'Transcribe Audio',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 250,\n      },\n      data: {},\n    };\n\n    return chartNode;\n  },\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    return [\n      {\n        id: 'audio' as PortId,\n        dataType: ['audio', 'string'],\n        title: 'Audio',\n      },\n    ];\n  },\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        dataType: 'string',\n        id: 'text' as PortId,\n        title: 'Transcript text',\n      },\n      {\n        dataType: 'string',\n        id: 'id' as PortId,\n        title: 'Transcript ID',\n      },\n      {\n        dataType: 'object',\n        id: 'transcript' as PortId,\n        title: 'Transcript object',\n      },\n    ];\n  },\n\n  getEditors(): EditorDefinition<TranscribeAudioNode>[] {\n    return [\n      {\n        type: 'code',\n        label: 'Transcript Parameters (JSON)',\n        language: 'json',\n        dataKey: 'transcriptParameters',\n        helperMessage: `Configure additional parameters using a JSON object. This will override any other fields you have set.\n        For a detailed list of parameters, see [the AssemblyAI API documentation](https://www.assemblyai.com/docs/api-reference/transcripts/submit?utm_source=rivet).`,\n      },\n    ];\n  },\n\n  getBody(): string | undefined {\n    return '';\n  },\n\n  getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`Use AssemblyAI to transcribe audio`,\n      infoBoxTitle: 'Transcribe Audio Node',\n      contextMenuTitle: 'Transcribe Audio',\n      group: ['AI', 'AssemblyAI'],\n    };\n  },\n\n  async process(data, inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const input = inputs['audio' as PortId] as AudioDataValue | StringDataValue | AnyDataValue;\n    if (!input) throw new Error('Audio input is required.');\n\n    const client = getClient(context);\n\n    let audioUrl: string;\n    if (input.type === 'audio') {\n      const audio = coerceType(inputs['audio' as PortId], 'audio');\n      audioUrl = await client.files.upload(audio.data);\n    } else if (input.type === 'string' || input.type === 'any') {\n      audioUrl = coerceType(inputs['audio' as PortId], 'string');\n    } else {\n      throw new Error('Audio input must be audio or string containing the audio URL.');\n    }\n\n    let transcriptParams: TranscribeParams = { audio: audioUrl };\n    transcriptParams = { ...transcriptParams, ...getAdditionalParameters(data) };\n    const transcript = await client.transcripts.transcribe(transcriptParams);\n\n    return {\n      ['text' as PortId]: {\n        type: 'string',\n        value: transcript.text as string,\n      },\n      ['id' as PortId]: {\n        type: 'string',\n        value: transcript.id,\n      },\n      ['transcript' as PortId]: {\n        type: 'object',\n        value: transcript,\n      },\n    };\n  },\n};\n\nexport const transcribeAudioNode = pluginNodeDefinition(TranscribeAudioNodeImpl, 'Transcribe Audio');\n\nfunction getAdditionalParameters(data: TranscribeAudioNodeData): Partial<TranscriptParams> {\n  const transcriptParams: string | null | undefined = data.transcriptParameters?.trim();\n  if (!transcriptParams) {\n    return {};\n  }\n\n  let transcriptParamsObj: Array<unknown> | Partial<TranscriptParams>;\n  try {\n    transcriptParamsObj = JSON.parse(transcriptParams);\n  } catch (e) {\n    throw new Error('The transcript parameters field has to be a valid JSON object, or empty.'); // This message is surfaced to the user\n  }\n\n  if (Array.isArray(transcriptParamsObj)) {\n    throw new Error('The transcript parameters field should be a JSON object, but is a JSON array'); // This message is surfaced to the user\n  }\n\n  return transcriptParamsObj;\n}\n", "import { nanoid } from 'nanoid/non-secure';\nimport { dedent } from 'ts-dedent';\nimport { type LemurSummaryParams } from 'assemblyai';\nimport {\n  type ChartNode,\n  type EditorDefinition,\n  type Inputs,\n  type InternalProcessContext,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type NodeUIData,\n  type Outputs,\n  type PluginNodeImpl,\n  type PortId,\n} from '../../index.js';\nimport {\n  type LemurNodeData,\n  getClient,\n  getLemurParams,\n  lemurEditorDefinitions,\n  lemurInputDefinitions,\n} from './lemurHelpers.js';\nimport { pluginNodeDefinition } from '../../model/NodeDefinition.js';\n\nexport type LemurSummaryNode = ChartNode<'assemblyAiLemurSummary', LemurSummaryNodeData>;\n\nexport type LemurSummaryNodeData = LemurNodeData & {\n  answer_format?: string;\n};\n\nexport const LemurSummaryNodeImpl: PluginNodeImpl<LemurSummaryNode> = {\n  create(): LemurSummaryNode {\n    const chartNode: LemurSummaryNode = {\n      type: 'assemblyAiLemurSummary',\n      title: 'LeMUR Summary',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 250,\n      },\n      data: {\n        final_model: 'default',\n      },\n    };\n\n    return chartNode;\n  },\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    return [\n      ...lemurInputDefinitions,\n      {\n        id: 'context' as PortId,\n        dataType: 'string',\n        title: 'Context',\n      },\n    ];\n  },\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        dataType: 'string',\n        id: 'response' as PortId,\n        title: 'Response',\n      },\n    ];\n  },\n\n  getEditors(): EditorDefinition<LemurSummaryNode>[] {\n    return [\n      {\n        type: 'string',\n        label: 'Context',\n        dataKey: 'context',\n      },\n      ...(lemurEditorDefinitions as unknown as EditorDefinition<LemurSummaryNode>[]),\n    ];\n  },\n\n  getBody(): string | undefined {\n    return '';\n  },\n\n  getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`Use AssemblyAI LeMUR Summary to summarize transcripts`,\n      infoBoxTitle: 'Use AssemblyAI LeMUR Summary',\n      contextMenuTitle: 'LeMUR Summary',\n      group: ['AI', 'AssemblyAI'],\n    };\n  },\n\n  async process(data, inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const client = getClient(context);\n    const params: LemurSummaryParams = getLemurParams(inputs, data);\n\n    if (data.answer_format) {\n      params.answer_format = data.answer_format;\n    }\n\n    const { response } = await client.lemur.summary(params);\n\n    return {\n      ['response' as PortId]: {\n        type: 'string',\n        value: response,\n      },\n    };\n  },\n};\n\nexport const lemurSummaryNode = pluginNodeDefinition(LemurSummaryNodeImpl, 'LeMUR Summary');\n", "import { nanoid } from 'nanoid/non-secure';\nimport { dedent } from 'ts-dedent';\nimport { type LemurTaskParams } from 'assemblyai';\nimport {\n  type ChartNode,\n  type EditorDefinition,\n  type Inputs,\n  type InternalProcessContext,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type NodeUIData,\n  type Outputs,\n  type PluginNodeImpl,\n  type PortId,\n} from '../../index.js';\nimport {\n  type LemurNodeData,\n  getClient,\n  getLemurParams,\n  lemurEditorDefinitions,\n  lemurInputDefinitions,\n} from './lemurHelpers.js';\nimport { pluginNodeDefinition } from '../../model/NodeDefinition.js';\nimport { coerceTypeOptional } from '../../utils/coerceType.js';\n\nexport type LemurTaskNode = ChartNode<'assemblyAiLemurTask', LemurTaskNodeData>;\n\nexport type LemurTaskNodeData = LemurNodeData & {\n  prompt?: string;\n};\n\nexport const LemurTaskNodeImpl: PluginNodeImpl<LemurTaskNode> = {\n  create(): LemurTaskNode {\n    const chartNode: LemurTaskNode = {\n      type: 'assemblyAiLemurTask',\n      title: 'LeMUR Task',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 250,\n      },\n      data: {\n        final_model: 'default',\n      },\n    };\n\n    return chartNode;\n  },\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    return [\n      ...lemurInputDefinitions,\n      {\n        id: 'prompt' as PortId,\n        dataType: 'string',\n        title: 'Prompt',\n      },\n    ];\n  },\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        dataType: 'string',\n        id: 'response' as PortId,\n        title: 'Response',\n      },\n    ];\n  },\n\n  getEditors(): EditorDefinition<LemurTaskNode>[] {\n    return [\n      {\n        type: 'string',\n        label: 'Prompt',\n        dataKey: 'prompt',\n      },\n      ...(lemurEditorDefinitions as unknown as EditorDefinition<LemurTaskNode>[]),\n    ];\n  },\n\n  getBody(): string | undefined {\n    return '';\n  },\n\n  getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`Use AssemblyAI LeMUR Custom Task to ask anything.`,\n      infoBoxTitle: 'Use AssemblyAI LeMUR Custom Task',\n      contextMenuTitle: 'LeMUR Custom Task',\n      group: ['AI', 'AssemblyAI'],\n    };\n  },\n\n  async process(data, inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const client = getClient(context);\n    const params: LemurTaskParams = {\n      prompt: coerceTypeOptional(inputs['prompt' as PortId], 'string') || data.prompt || '',\n      ...getLemurParams(inputs, data),\n    };\n    if (!params.prompt) throw new Error('Prompt must be provided.');\n\n    const { response } = await client.lemur.task(params);\n\n    return {\n      ['response' as PortId]: {\n        type: 'string',\n        value: response,\n      },\n    };\n  },\n};\n\nexport const lemurTaskNode = pluginNodeDefinition(LemurTaskNodeImpl, 'LeMUR Task');\n", "import { nanoid } from 'nanoid/non-secure';\nimport { dedent } from 'ts-dedent';\nimport type { LemurActionItemsParams } from 'assemblyai';\nimport {\n  type ChartNode,\n  type EditorDefinition,\n  type Inputs,\n  type InternalProcessContext,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type NodeUIData,\n  type Outputs,\n  type PluginNodeImpl,\n  type PortId,\n} from '../../index.js';\nimport { pluginNodeDefinition } from '../../model/NodeDefinition.js';\nimport {\n  type LemurNodeData,\n  getClient,\n  getLemurParams,\n  lemurEditorDefinitions,\n  lemurInputDefinitions,\n} from './lemurHelpers.js';\n\nexport type LemurActionItemsNode = ChartNode<'assemblyAiLemurActionItems', LemurActionItemsNodeData>;\n\nexport type LemurActionItemsNodeData = LemurNodeData;\n\nexport const LemurActionItemsNodeImpl: PluginNodeImpl<LemurActionItemsNode> = {\n  create(): LemurActionItemsNode {\n    const chartNode: LemurActionItemsNode = {\n      type: 'assemblyAiLemurActionItems',\n      title: 'LeMUR Action Items',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 250,\n      },\n      data: {\n        final_model: 'default',\n      },\n    };\n\n    return chartNode;\n  },\n\n  getInputDefinitions(): NodeInputDefinition[] {\n    return [\n      ...lemurInputDefinitions,\n      {\n        id: 'context' as PortId,\n        dataType: 'string',\n        title: 'Context',\n      },\n    ];\n  },\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        dataType: 'string',\n        id: 'response' as PortId,\n        title: 'Response',\n      },\n    ];\n  },\n\n  getEditors(): EditorDefinition<LemurActionItemsNode>[] {\n    return [\n      {\n        type: 'string',\n        label: 'Context',\n        dataKey: 'context',\n      },\n      ...(lemurEditorDefinitions as unknown as EditorDefinition<LemurActionItemsNode>[]),\n    ];\n  },\n\n  getBody(): string | undefined {\n    return '';\n  },\n\n  getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`Use AssemblyAI LeMUR Action Items to extract action items`,\n      infoBoxTitle: 'Use AssemblyAI LeMUR Action Items',\n      contextMenuTitle: 'LeMUR Action Items',\n      group: ['AI', 'AssemblyAI'],\n    };\n  },\n\n  async process(data, inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const client = getClient(context);\n\n    const params: LemurActionItemsParams = getLemurParams(inputs, data);\n\n    const { response } = await client.lemur.actionItems(params);\n\n    return {\n      ['response' as PortId]: {\n        type: 'string',\n        value: response,\n      },\n    };\n  },\n};\n\nexport const lemurActionItemsNode = pluginNodeDefinition(LemurActionItemsNodeImpl, 'LeMUR Action Items');\n", "import { type RivetPlugin } from '../../index.js';\nimport { lemurQaNode } from './LemurQaNode.js';\nimport { transcribeAudioNode } from './TranscribeAudioNode.js';\nimport { lemurSummaryNode } from './LemurSummaryNode.js';\nimport { lemurTaskNode } from './LemurTaskNode.js';\nimport { lemurActionItemsNode } from './LemurActionItemsNode.js';\n\nexport const assemblyAiPlugin: RivetPlugin = {\n  id: 'assemblyAi',\n  name: 'AssemblyAI',\n\n  register: (register) => {\n    register(transcribeAudioNode);\n    register(lemurSummaryNode);\n    register(lemurQaNode);\n    register(lemurTaskNode);\n    register(lemurActionItemsNode);\n  },\n\n  configSpec: {\n    assemblyAiApiKey: {\n      type: 'secret',\n      label: 'AssemblyAI API Key',\n      description: 'The API key for the AssemblyAI service.',\n      pullEnvironmentVariable: 'ASSEMBLYAI_API_KEY',\n      helperText: 'You may also set the ASSEMBLYAI_API_KEY environment variable.',\n    },\n  },\n\n  contextMenuGroups: [\n    {\n      id: 'add-node-group:assemblyai',\n      label: 'AssemblyAI',\n    },\n  ],\n};\n", "import { assemblyAiPlugin } from './plugin.js';\n\nexport default assemblyAiPlugin;\n", "import { nanoid } from 'nanoid/non-secure';\nimport {\n  type ChartNode,\n  type EditorDefinition,\n  type NodeBodySpec,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type NodeUIData,\n  type Outputs,\n  type PluginNodeImpl,\n  type PortId,\n} from '../../../index.js';\nimport { HfInference, HfInferenceEndpoint } from '@huggingface/inference';\nimport { getInputOrData } from '../../../utils/inputs.js';\nimport { coerceType } from '../../../utils/coerceType.js';\nimport { dedent } from '../../../utils/misc.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\n\nexport type ChatHuggingFaceNode = ChartNode<'chatHuggingFace', ChatHuggingFaceNodeData>;\n\nexport type ChatHuggingFaceNodeData = {\n  model: string;\n  useModelInput?: boolean;\n\n  endpoint?: string;\n  useEndpointInput?: boolean;\n\n  temperature?: number;\n  useTemperatureInput?: boolean;\n\n  maxNewTokens: number;\n  useMaxNewTokensInput?: boolean;\n\n  doSample: boolean;\n  useDoSampleInput?: boolean;\n\n  maxTime?: number;\n  useMaxTimeInput?: boolean;\n\n  repetitionPenalty?: number;\n  useRepetitionPenaltyInput?: boolean;\n\n  topP?: number;\n  useTopPInput?: boolean;\n\n  topK?: number;\n  useTopKInput?: boolean;\n};\n\nexport const ChatHuggingFaceNodeImpl: PluginNodeImpl<ChatHuggingFaceNode> = {\n  create(): ChatHuggingFaceNode {\n    return {\n      id: nanoid() as NodeId,\n      type: 'chatHuggingFace',\n      data: {\n        model: '',\n        temperature: 0.5,\n        maxNewTokens: 1024,\n        doSample: false,\n      },\n      title: 'Chat (Hugging Face)',\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 300,\n      },\n    };\n  },\n\n  getUIData(): NodeUIData {\n    return {\n      group: ['AI', 'Hugging Face'],\n      contextMenuTitle: 'Chat (Hugging Face)',\n      infoBoxTitle: 'Chat (Hugging Face) Node',\n      infoBoxBody: 'Chat, using the hugging face inference API',\n    };\n  },\n\n  getInputDefinitions(data): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [];\n\n    inputs.push({\n      id: 'prompt' as PortId,\n      dataType: 'string',\n      title: 'Prompt',\n      required: true,\n    });\n\n    if (data.useModelInput) {\n      inputs.push({\n        id: 'model' as PortId,\n        dataType: 'string',\n        title: 'Model',\n      });\n    }\n\n    if (data.useEndpointInput) {\n      inputs.push({\n        id: 'endpoint' as PortId,\n        dataType: 'string',\n        title: 'Endpoint',\n      });\n    }\n\n    if (data.useTemperatureInput) {\n      inputs.push({\n        id: 'temperature' as PortId,\n        dataType: 'number',\n        title: 'Temperature',\n      });\n    }\n\n    if (data.useMaxNewTokensInput) {\n      inputs.push({\n        id: 'maxNewTokens' as PortId,\n        dataType: 'number',\n        title: 'Max New Tokens',\n      });\n    }\n\n    if (data.useDoSampleInput) {\n      inputs.push({\n        id: 'doSample' as PortId,\n        dataType: 'boolean',\n        title: 'Do Sample',\n      });\n    }\n\n    if (data.useMaxTimeInput) {\n      inputs.push({\n        id: 'maxTime' as PortId,\n        dataType: 'number',\n        title: 'Max Time (s)',\n      });\n    }\n\n    if (data.useRepetitionPenaltyInput) {\n      inputs.push({\n        id: 'repetitionPenalty' as PortId,\n        dataType: 'number',\n        title: 'Repetition Penalty',\n      });\n    }\n\n    if (data.useTopPInput) {\n      inputs.push({\n        id: 'topP' as PortId,\n        dataType: 'number',\n        title: 'Top P',\n      });\n    }\n\n    if (data.useTopKInput) {\n      inputs.push({\n        id: 'topK' as PortId,\n        dataType: 'number',\n        title: 'Top K',\n      });\n    }\n\n    return inputs;\n  },\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'output' as PortId,\n        dataType: 'string',\n        title: 'Output',\n      },\n    ];\n  },\n\n  getEditors(): EditorDefinition<ChatHuggingFaceNode>[] {\n    return [\n      {\n        type: 'string',\n        label: 'Model',\n        dataKey: 'model',\n        useInputToggleDataKey: 'useModelInput',\n      },\n      {\n        type: 'string',\n        label: 'Endpoint',\n        dataKey: 'endpoint',\n        useInputToggleDataKey: 'useEndpointInput',\n      },\n      {\n        type: 'number',\n        label: 'Temperature (0-100)',\n        dataKey: 'temperature',\n        useInputToggleDataKey: 'useTemperatureInput',\n        min: 0,\n        step: 50,\n        allowEmpty: true,\n      },\n      {\n        type: 'number',\n        label: 'Max New Tokens',\n        dataKey: 'maxNewTokens',\n        useInputToggleDataKey: 'useMaxNewTokensInput',\n        min: 0,\n        step: 1,\n      },\n      {\n        type: 'toggle',\n        label: 'Do Sample',\n        dataKey: 'doSample',\n        useInputToggleDataKey: 'useDoSampleInput',\n      },\n      {\n        type: 'number',\n        label: 'Max Time (s)',\n        dataKey: 'maxTime',\n        useInputToggleDataKey: 'useMaxTimeInput',\n        allowEmpty: true,\n      },\n      {\n        type: 'number',\n        label: 'Repetition Penalty (0-100)',\n        dataKey: 'repetitionPenalty',\n        useInputToggleDataKey: 'useRepetitionPenaltyInput',\n        allowEmpty: true,\n      },\n      {\n        type: 'number',\n        label: 'Top P (0-100)',\n        dataKey: 'topP',\n        useInputToggleDataKey: 'useTopPInput',\n        allowEmpty: true,\n      },\n      {\n        type: 'number',\n        label: 'Top K (0-100)',\n        dataKey: 'topK',\n        useInputToggleDataKey: 'useTopKInput',\n        allowEmpty: true,\n      },\n    ];\n  },\n\n  getBody(data): string | NodeBodySpec | NodeBodySpec[] | undefined {\n    return dedent`\n      ${\n        data.endpoint || data.useEndpointInput\n          ? `Endpoint: ${data.useEndpointInput ? '(Using Input)' : 'Yes'}`\n          : `Model: ${data.useModelInput ? '(Using Input)' : data.model}`\n      }\n      ${\n        data.useTemperatureInput\n          ? 'Temperature: (Using Input)'\n          : data.temperature != null\n            ? `Temperature: ${data.temperature}`\n            : ''\n      }\n      Max New Tokens: ${data.useMaxNewTokensInput ? '(Using Input)' : data.maxNewTokens}\n    `;\n  },\n\n  async process(data, inputData, context): Promise<Outputs> {\n    const accessToken = context.getPluginConfig('huggingFaceAccessToken');\n\n    const prompt = coerceType(inputData['prompt' as PortId], 'string');\n    const endpoint = getInputOrData(data, inputData, 'endpoint');\n\n    const model = getInputOrData(data, inputData, 'model');\n    const temperature = getInputOrData(data, inputData, 'temperature', 'number');\n    const maxNewTokens = getInputOrData(data, inputData, 'maxNewTokens', 'number');\n    const doSample = getInputOrData(data, inputData, 'doSample', 'boolean');\n    const maxTime = getInputOrData(data, inputData, 'maxTime', 'number');\n    const repetitionPenalty = getInputOrData(data, inputData, 'repetitionPenalty', 'number');\n    const topP = getInputOrData(data, inputData, 'topP', 'number');\n    const topK = getInputOrData(data, inputData, 'topK', 'number');\n\n    const hf = endpoint ? new HfInferenceEndpoint(endpoint, accessToken) : new HfInference(accessToken);\n\n    const generationStream = hf.textGenerationStream({\n      inputs: prompt,\n      model,\n      parameters: {\n        temperature,\n        max_new_tokens: maxNewTokens,\n        do_sample: doSample,\n        max_time: maxTime,\n        repetition_penalty: repetitionPenalty,\n        top_p: topP,\n        top_k: topK,\n      },\n    });\n\n    const parts = [];\n\n    for await (const { token } of generationStream) {\n      if (!token.special) {\n        parts.push(token.text);\n      }\n\n      context.onPartialOutputs?.({\n        ['output' as PortId]: {\n          type: 'string',\n          value: parts.join(''),\n        },\n      });\n    }\n\n    return {\n      ['output' as PortId]: {\n        type: 'string',\n        value: parts.join(''),\n      },\n    };\n  },\n};\n\nexport const chatHuggingFaceNode = pluginNodeDefinition(ChatHuggingFaceNodeImpl, 'Chat (Hugging Face)');\n", "import { nanoid } from 'nanoid/non-secure';\nimport {\n  type ChartNode,\n  type EditorDefinition,\n  type NodeBodySpec,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type NodeUIData,\n  type Outputs,\n  type PluginNodeImpl,\n  type PortId,\n} from '../../../index.js';\nimport { HfInference, HfInferenceEndpoint } from '@huggingface/inference';\nimport { dedent } from 'ts-dedent';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport { getInputOrData } from '../../../utils/inputs.js';\nimport { coerceType } from '../../../utils/coerceType.js';\n\nexport type TextToImageHuggingFaceNode = ChartNode<'textToImageHuggingFace', TextToImageHuggingFaceNodeData>;\n\nexport type TextToImageHuggingFaceNodeData = {\n  model: string;\n  useModelInput?: boolean;\n\n  endpoint?: string;\n  useEndpointInput?: boolean;\n\n  width: number;\n  useWidthInput?: boolean;\n\n  height: number;\n  useHeightInput?: boolean;\n\n  negativePrompt?: string;\n  useNegativePromptInput?: boolean;\n\n  guidanceScale: number;\n  useGuidanceScaleInput?: boolean;\n\n  numInferenceSteps: number;\n  useNumInferenceStepsInput?: boolean;\n};\n\nexport const TextToImageHuggingFaceNodeImpl: PluginNodeImpl<TextToImageHuggingFaceNode> = {\n  create(): TextToImageHuggingFaceNode {\n    return {\n      id: nanoid() as NodeId,\n      type: 'textToImageHuggingFace',\n      data: {\n        model: '',\n        width: 256,\n        height: 256,\n        negativePrompt: '',\n        guidanceScale: 7,\n        numInferenceSteps: 3,\n      },\n      title: 'Text-to-Image (Hugging Face)',\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 300,\n      },\n    };\n  },\n\n  getUIData(): NodeUIData {\n    return {\n      group: ['AI', 'Hugging Face'],\n      contextMenuTitle: 'Text-to-Image (Hugging Face)',\n      infoBoxTitle: 'Text-to-Image (Hugging Face) Node',\n      infoBoxBody: 'Use the Hugging Face API to generate an image from text.',\n    };\n  },\n\n  getInputDefinitions(data): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [];\n\n    inputs.push({\n      id: 'prompt' as PortId,\n      dataType: 'string',\n      title: 'Prompt',\n      required: true,\n    });\n\n    if (data.useModelInput) {\n      inputs.push({\n        id: 'model' as PortId,\n        dataType: 'string',\n        title: 'Model',\n      });\n    }\n\n    if (data.useEndpointInput) {\n      inputs.push({\n        id: 'endpoint' as PortId,\n        dataType: 'string',\n        title: 'Endpoint',\n      });\n    }\n\n    if (data.useWidthInput) {\n      inputs.push({\n        id: 'width' as PortId,\n        dataType: 'number',\n        title: 'Width',\n      });\n    }\n\n    if (data.useHeightInput) {\n      inputs.push({\n        id: 'height' as PortId,\n        dataType: 'number',\n        title: 'Height',\n      });\n    }\n\n    if (data.useNegativePromptInput) {\n      inputs.push({\n        id: 'negativePrompt' as PortId,\n        dataType: 'string',\n        title: 'Negative Prompt',\n      });\n    }\n\n    if (data.useGuidanceScaleInput) {\n      inputs.push({\n        id: 'guidanceScale' as PortId,\n        dataType: 'number',\n        title: 'Guidance Scale',\n      });\n    }\n\n    if (data.useNumInferenceStepsInput) {\n      inputs.push({\n        id: 'numInferenceSteps' as PortId,\n        dataType: 'number',\n        title: 'Num Inference Steps',\n      });\n    }\n\n    return inputs;\n  },\n\n  getOutputDefinitions(): NodeOutputDefinition[] {\n    return [\n      {\n        id: 'output' as PortId,\n        dataType: 'string',\n        title: 'Output',\n      },\n    ];\n  },\n\n  getEditors(): EditorDefinition<TextToImageHuggingFaceNode>[] {\n    return [\n      {\n        type: 'string',\n        label: 'Model',\n        dataKey: 'model',\n        useInputToggleDataKey: 'useModelInput',\n      },\n      {\n        type: 'number',\n        label: 'Width',\n        dataKey: 'width',\n        useInputToggleDataKey: 'useWidthInput',\n      },\n      {\n        type: 'number',\n        label: 'Height',\n        dataKey: 'height',\n        useInputToggleDataKey: 'useHeightInput',\n      },\n      {\n        type: 'string',\n        label: 'Negative Prompt',\n        dataKey: 'negativePrompt',\n        useInputToggleDataKey: 'useNegativePromptInput',\n      },\n      {\n        type: 'number',\n        label: 'Guidance Scale',\n        dataKey: 'guidanceScale',\n        useInputToggleDataKey: 'useGuidanceScaleInput',\n        min: 0,\n        max: 20,\n        step: 1,\n      },\n      {\n        type: 'number',\n        label: 'Num Inference Steps',\n        dataKey: 'numInferenceSteps',\n        useInputToggleDataKey: 'useNumInferenceStepsInput',\n        min: 0,\n        max: 20,\n        step: 1,\n      },\n    ];\n  },\n\n  getBody(data): string | NodeBodySpec | NodeBodySpec[] | undefined {\n    return dedent`\n      Model: ${data.useModelInput ? '(Using Input)' : data.model}\n    `;\n  },\n\n  async process(data, inputData, context): Promise<Outputs> {\n    const accessToken = context.getPluginConfig('huggingFaceAccessToken');\n\n    const prompt = coerceType(inputData['prompt' as PortId], 'string');\n    const endpoint = getInputOrData(data, inputData, 'endpoint');\n\n    const model = getInputOrData(data, inputData, 'model');\n    const width = getInputOrData(data, inputData, 'width', 'number');\n    const height = getInputOrData(data, inputData, 'height', 'number');\n    const negativePrompt = getInputOrData(data, inputData, 'negativePrompt') || undefined;\n    const guidanceScale = getInputOrData(data, inputData, 'guidanceScale', 'number');\n    const numInferenceSteps = getInputOrData(data, inputData, 'numInferenceSteps', 'number');\n\n    const hf = endpoint ? new HfInferenceEndpoint(endpoint, accessToken) : new HfInference(accessToken);\n\n    const image = await hf.textToImage({\n      inputs: prompt,\n      model,\n      parameters: {\n        width,\n        height,\n        negative_prompt: negativePrompt,\n        guidance_scale: guidanceScale,\n        num_inference_steps: numInferenceSteps,\n      },\n    });\n\n    return {\n      ['output' as PortId]: {\n        type: 'image',\n        value: {\n          mediaType: 'image/png',\n          data: new Uint8Array(await image.arrayBuffer()),\n        },\n      },\n    };\n  },\n};\n\nexport const textToImageHuggingFaceNode = pluginNodeDefinition(\n  TextToImageHuggingFaceNodeImpl,\n  'Text-to-Image (Hugging Face)',\n);\n", "import { type RivetPlugin } from '../../index.js';\nimport { chatHuggingFaceNode } from './nodes/ChatHuggingFace.js';\nimport { textToImageHuggingFaceNode } from './nodes/TextToImageHuggingFace.js';\n\nexport const huggingFacePlugin: RivetPlugin = {\n  id: 'huggingface',\n  name: 'Hugging Face',\n\n  configSpec: {\n    huggingFaceAccessToken: {\n      type: 'secret',\n      label: 'Hugging Face Access Token',\n      description: 'Your access token for the Hugging Face API.',\n      pullEnvironmentVariable: 'HUGGING_FACE_ACCESS_TOKEN',\n      helperText: 'Create at https://huggingface.co/settings/tokens',\n    },\n  },\n\n  contextMenuGroups: [\n    {\n      id: 'huggingFace',\n      label: 'Hugging Face',\n    },\n  ],\n\n  register(register) {\n    register(chatHuggingFaceNode);\n    register(textToImageHuggingFaceNode);\n  },\n};\n", "import {\n  type ArrayDataValue,\n  type DataValue,\n  type ScalarDataValue,\n  type Settings,\n  type VectorDataValue,\n  type VectorDatabase,\n} from '../../index.js';\nimport * as CryptoJS from 'crypto-js';\nimport { coerceType } from '../../utils/coerceType.js';\n\nexport class PineconeVectorDatabase implements VectorDatabase {\n  readonly #apiKey;\n\n  constructor(settings: Settings) {\n    this.#apiKey = settings.pluginSettings?.pinecone?.pineconeApiKey as string | undefined;\n  }\n\n  async store(collection: DataValue, vector: VectorDataValue, data: DataValue, { id }: { id?: string }): Promise<void> {\n    const collectionDetails = getCollection(coerceType(collection, 'string'));\n\n    if (!id) {\n      id = CryptoJS.SHA256(vector.value.join(',')).toString(CryptoJS.enc.Hex);\n    }\n\n    let metadata: Record<string, unknown> = {};\n    if (data.type === 'object') {\n      metadata = data.value;\n    } else {\n      metadata = { data: data.value };\n    }\n\n    const response = await fetch(`${collectionDetails.host}/vectors/upsert`, {\n      method: 'POST',\n      body: JSON.stringify({\n        vectors: [\n          {\n            id,\n            values: vector.value,\n            metadata,\n          },\n        ],\n        ...collectionDetails.options,\n      }),\n      headers: {\n        'Content-Type': 'application/json',\n        Accept: 'application/json',\n        'api-key': this.#apiKey!,\n      },\n    });\n\n    if (response.status !== 200) {\n      throw new Error(`Pinecone error: ${await response.text()}`);\n    }\n  }\n\n  async nearestNeighbors(\n    collection: DataValue,\n    vector: VectorDataValue,\n    k: number,\n  ): Promise<ArrayDataValue<ScalarDataValue>> {\n    const collectionDetails = getCollection(coerceType(collection, 'string'));\n\n    const response = await fetch(`${collectionDetails.host}/query`, {\n      method: 'POST',\n      body: JSON.stringify({\n        vector: vector.value,\n        topK: k,\n        includeMetadata: true,\n        ...collectionDetails.options,\n      }),\n      headers: {\n        'Content-Type': 'application/json',\n        Accept: 'application/json',\n        'api-key': this.#apiKey!,\n      },\n    });\n\n    if (response.status !== 200) {\n      throw new Error(`Pinecone error: ${await response.text()}`);\n    }\n\n    const responseData = await response.json();\n\n    const { matches } = responseData as {\n      matches: {\n        id: string;\n        score: number;\n        metadata: { data: unknown };\n      }[];\n    };\n\n    return {\n      type: 'object[]',\n      value: matches.map(({ id, metadata }) => ({ id, data: metadata.data, metadata })),\n    };\n  }\n}\n\ninterface CollectionDetails {\n  host: string;\n  options: { [option: string]: any };\n}\n\nfunction getCollection(collectionString: string): CollectionDetails {\n  let collectionURL: URL;\n\n  if (!collectionString.startsWith('http://') && !collectionString.startsWith('https://')) {\n    collectionString = `https://${collectionString}`;\n  }\n\n  try {\n    collectionURL = new URL(collectionString);\n  } catch (error) {\n    throw new Error(`Incorrectly formatted Pinecone collection: ${error}`);\n  }\n\n  const host = `${collectionURL.protocol}//${collectionURL.host}`;\n  const options: { [option: string]: any } = {};\n\n  if (collectionURL.pathname !== '/') {\n    // Chop off the leading slash.\n    options.namespace = collectionURL.pathname.slice(1);\n  }\n\n  return { host, options };\n}\n", "import { type RivetPlugin } from '../../index.js';\nimport { PineconeVectorDatabase } from './PineconeVectorDatabase.js';\nimport { registerIntegration } from '../../integrations/integrations.js';\n\nexport const pineconePlugin: RivetPlugin = {\n  id: 'pinecone',\n  name: 'Pinecone',\n\n  register: () => {\n    registerIntegration('vectorDatabase', 'pinecone', (context) => new PineconeVectorDatabase(context.settings));\n  },\n\n  configSpec: {\n    pineconeApiKey: {\n      type: 'secret',\n      label: 'Pinecone API Key',\n      description: 'The API key for the Pinecone service.',\n      pullEnvironmentVariable: 'PINECONE_API_KEY',\n      helperText: 'You may also set the PINECONE_API_KEY environment variable.',\n    },\n  },\n};\n", "import { pineconePlugin } from './plugin.js';\n\nexport default pineconePlugin;\n", "import { Pipeline, StepRun, init, runTest, getPipelines } from '@gentrace/core';\n\nimport {\n  type GraphId,\n  type NativeApi,\n  type NodeGraph,\n  type Project,\n  type Recording,\n  type RivetPlugin,\n  type SecretPluginConfigurationSpec,\n  type Settings,\n} from '../../index.js';\nimport { mapValues } from 'lodash-es';\nimport { ExecutionRecorder } from '../../recording/ExecutionRecorder.js';\nimport { inferType } from '../../utils/coerceType.js';\nimport { GraphProcessor } from '../../model/GraphProcessor.js';\n\nconst apiKeyConfigSpec: SecretPluginConfigurationSpec = {\n  type: 'secret',\n  label: 'Gentrace API Key',\n  description: 'The API key for the Gentrace service.',\n  pullEnvironmentVariable: 'GENTRACE_API_KEY',\n  helperText: 'Create at https://gentrace.ai/settings/api-keys',\n};\n\nfunction initializeGentrace(gentraceApiKey: string) {\n  init({\n    apiKey: gentraceApiKey,\n  });\n}\n\nexport const runGentraceTests = async (\n  gentracePipelineSlug: string,\n  settings: Settings,\n  project: Omit<Project, 'data'>,\n  graph: NodeGraph,\n  nativeApi: NativeApi,\n) => {\n  const gentraceApiKey = settings.pluginSettings?.gentrace?.gentraceApiKey as string | undefined;\n\n  if (!gentraceApiKey) {\n    throw new Error('Gentrace API key not set.');\n  }\n\n  const graphId = graph.metadata?.id;\n\n  if (!graphId) {\n    throw new Error('Graph ID not set.');\n  }\n\n  initializeGentrace(gentraceApiKey);\n\n  const response = await runTest(gentracePipelineSlug, async (testCase) => {\n    const pipeline = new Pipeline({\n      slug: gentracePipelineSlug,\n    });\n\n    const runner = pipeline.start();\n\n    const rivetFormattedInputs = mapValues(testCase.inputs, inferType);\n\n    const tempProject = {\n      ...project,\n      graphs: {\n        ...project.graphs,\n        [graph.metadata!.id!]: graph,\n      },\n    };\n\n    const recorder = new ExecutionRecorder();\n    const processor = new GraphProcessor(tempProject, graphId);\n    processor.executor = 'browser';\n\n    recorder.record(processor);\n    await processor.processGraph(\n      {\n        settings,\n        nativeApi,\n      },\n      rivetFormattedInputs,\n    );\n\n    const fullRecording = recorder.getRecording();\n\n    const stepRuns = convertRecordingToStepRuns(fullRecording, project, graphId);\n\n    for (const stepRun of stepRuns) {\n      await runner.addStepRunNode(stepRun);\n    }\n\n    if (stepRuns.length === 0) {\n      throw new Error('No Rivet steps found. You need operations which are not Graph Input or Graph Output nodes.');\n    }\n\n    return ['', runner];\n  });\n\n  return response;\n};\n\nexport const runRemoteGentraceTests = async (\n  gentracePipelineSlug: string,\n  settings: Settings,\n  project: Omit<Project, 'data'>,\n  graph: NodeGraph,\n  runAndRecord: (testCase: Record<string, any>) => Promise<Recording>,\n) => {\n  const gentraceApiKey = settings.pluginSettings?.gentrace?.gentraceApiKey as string | undefined;\n\n  if (!gentraceApiKey) {\n    throw new Error('Gentrace API key not set.');\n  }\n\n  const graphId = graph.metadata?.id;\n\n  if (!graphId) {\n    throw new Error('Graph ID not set.');\n  }\n\n  initializeGentrace(gentraceApiKey);\n\n  const response = await runTest(gentracePipelineSlug, async (testCase) => {\n    const pipeline = new Pipeline({\n      slug: gentracePipelineSlug,\n    });\n\n    const runner = pipeline.start();\n\n    const rivetFormattedInputs = mapValues(testCase.inputs, inferType);\n\n    const fullRecording = await runAndRecord(rivetFormattedInputs);\n    const stepRuns = convertRecordingToStepRuns(fullRecording, project, graphId);\n\n    for (const stepRun of stepRuns) {\n      await runner.addStepRunNode(stepRun);\n    }\n\n    if (stepRuns.length === 0) {\n      throw new Error('No Rivet steps found. You need operations which are not Graph Input or Graph Output nodes.');\n    }\n\n    return ['', runner];\n  });\n\n  return response;\n};\n\ntype SimplifiedNode = {\n  nodeId: string;\n  start: number;\n  end: number;\n  modelParams: Record<string, any>;\n  inputs: Record<string, any>;\n  outputs: Record<string, any>;\n};\n\nfunction convertRecordingToStepRuns(recording: Recording, project: Omit<Project, 'data'>, graphId: GraphId): StepRun[] {\n  const partialProcessStartEndPairs: {\n    [processId: string]: Partial<SimplifiedNode>;\n  } = {};\n\n  recording.events.forEach((event) => {\n    const eventType = event?.type;\n\n    if (!eventType) {\n      return;\n    }\n\n    if (eventType === 'nodeStart' || eventType === 'nodeFinish') {\n      const processId = event?.data?.processId;\n      const nodeId = event?.data?.nodeId;\n\n      if (!processId) {\n        return;\n      }\n\n      let existingPair = partialProcessStartEndPairs[processId];\n\n      if (!existingPair) {\n        existingPair = {};\n        partialProcessStartEndPairs[processId] = existingPair;\n      }\n\n      existingPair.nodeId = nodeId;\n\n      if (eventType === 'nodeStart') {\n        existingPair.start = event.ts;\n        existingPair.inputs = event.data.inputs;\n      } else {\n        existingPair.end = event.ts;\n        existingPair.outputs = event.data.outputs;\n      }\n    }\n  });\n\n  const processStartEndPairs = partialProcessStartEndPairs as {\n    [processId: string]: SimplifiedNode;\n  };\n\n  const selectedGraph = project.graphs[graphId];\n\n  if (!selectedGraph) {\n    return [];\n  }\n\n  // Convert to step runs\n  const stepRuns: StepRun[] = [];\n\n  for (const [, pair] of Object.entries(processStartEndPairs)) {\n    const { nodeId } = pair;\n\n    const relatedNode = selectedGraph.nodes.find((node) => node.id === nodeId);\n\n    const nodeType = relatedNode?.type;\n\n    if (!nodeType || !relatedNode.data || nodeType === 'graphInput' || nodeType === 'graphOutput') {\n      continue;\n    }\n\n    const nodeData = relatedNode.data as Record<string, any>;\n\n    if (relatedNode) {\n      pair.modelParams = { ...nodeData, ...{ type: nodeType } };\n    }\n\n    if (nodeType === 'chat') {\n      const modelName = nodeData.model ? nodeData.model : '';\n\n      if (modelName.startsWith('gpt')) {\n        // Convert to OpenAI Gentrace node\n        const gentraceOpenAIInputs: Record<string, any> = { ...pair.inputs };\n\n        gentraceOpenAIInputs.messages = [\n          {\n            content: pair.inputs.prompt.value,\n            role: 'user',\n          },\n        ];\n\n        const gentraceOpenAIModelParams: Record<string, any> = { ...pair.modelParams };\n\n        gentraceOpenAIModelParams.model = modelName;\n\n        gentraceOpenAIModelParams.frequency_penalty = pair.modelParams.frequencyPenalty || null;\n\n        gentraceOpenAIModelParams.max_tokens = pair.modelParams.maxTokens || undefined;\n\n        gentraceOpenAIModelParams.presence_penalty = pair.modelParams.presencePenalty || null;\n\n        gentraceOpenAIModelParams.stop = pair.modelParams.stop || null;\n\n        gentraceOpenAIModelParams.temperature = pair.modelParams.temperature || null;\n\n        gentraceOpenAIModelParams.top_p = pair.modelParams.top_p || null;\n\n        const gentraceOpenAIOutputs: Record<string, any> = { ...pair.outputs };\n\n        const outputValues: string[] = Array.isArray(pair.outputs.response.value)\n          ? pair.outputs.response.value\n          : [pair.outputs.response.value];\n\n        gentraceOpenAIOutputs.choices = outputValues.map((outputValue, index) => {\n          return {\n            index,\n            message: {\n              content: outputValue,\n              role: 'assistant',\n            },\n            usage: {\n              completion_tokens: pair.outputs.responseTokens.value,\n              prompt_tokens: pair.outputs.requestTokens.value,\n              total_tokens: pair.outputs.responseTokens.value + pair.outputs.requestTokens.value,\n            },\n          };\n        });\n\n        stepRuns.push(\n          new StepRun(\n            'openai',\n            'openai_createChatCompletion',\n            pair.end - pair.start,\n            new Date(pair.start).toISOString(),\n            new Date(pair.end).toISOString(),\n            gentraceOpenAIInputs,\n            gentraceOpenAIModelParams,\n            gentraceOpenAIOutputs,\n            {},\n          ),\n        );\n\n        continue;\n      }\n    }\n\n    stepRuns.push(\n      new StepRun(\n        'rivet',\n        nodeType ? `rivet_operation_${nodeType}` : 'rivet_operation',\n        pair.end - pair.start,\n        new Date(pair.start).toISOString(),\n        new Date(pair.end).toISOString(),\n        pair.inputs,\n        pair.modelParams,\n        pair.outputs,\n        {},\n      ),\n    );\n  }\n\n  return stepRuns;\n}\n\nexport const getGentracePipelines = async (gentraceApiKey: string) => {\n  initializeGentrace(gentraceApiKey);\n  return await getPipelines();\n};\n\nexport const gentracePlugin: RivetPlugin = {\n  id: 'gentrace',\n  name: 'Gentrace',\n\n  configSpec: {\n    gentraceApiKey: apiKeyConfigSpec,\n  },\n};\n", "import { gentracePlugin } from './plugin.js';\n\nexport default gentracePlugin;\n", "import {\n  type ChartNode,\n  type PluginNodeImpl,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type EditorDefinition,\n} from '../../../index.js';\nimport type { CreateMessageBody, CreateThreadBody, OpenAIThread } from '../../../utils/openai.js';\nimport { dedent, newId, coerceTypeOptional, getInputOrData } from '../../../utils/index.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\n\nexport type CreateThreadNode = ChartNode<'openaiCreateThread', CreateThreadNodeData>;\n\nexport type CreateThreadNodeData = {\n  threadId?: string;\n  useThreadIdInput?: boolean;\n\n  metadata: { key: string; value: string }[];\n  useMetadataInput?: boolean;\n};\n\nexport const CreateThreadNodeImpl: PluginNodeImpl<CreateThreadNode> = {\n  create() {\n    return {\n      id: newId<NodeId>(),\n      type: 'openaiCreateThread',\n      data: {\n        metadata: [],\n        useMetadataInput: false,\n      },\n      title: 'Create Thread',\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 225,\n      },\n    };\n  },\n\n  getUIData() {\n    return {\n      group: 'OpenAI',\n      contextMenuTitle: 'Create Thread',\n      infoBoxTitle: 'Create Thread Node',\n      infoBoxBody: 'Create a new thread for OpenAI assistants.',\n    };\n  },\n\n  getInputDefinitions(data) {\n    const inputs: NodeInputDefinition[] = [];\n\n    if (data.useThreadIdInput) {\n      inputs.push({\n        id: 'threadId' as PortId,\n        dataType: 'string',\n        title: 'Thread ID',\n        coerced: true,\n        defaultValue: '',\n        description: 'The ID of the thread to modify. If not provided, a new thread will be created.',\n        required: true,\n      });\n    }\n\n    inputs.push({\n      id: 'messages' as PortId,\n      dataType: 'object[]',\n      title: 'Messages',\n      coerced: true,\n      defaultValue: [],\n      description: 'A list of user messages to start the thread with.',\n      required: false,\n    });\n\n    if (data.useMetadataInput) {\n      inputs.push({\n        id: 'metadata' as PortId,\n        dataType: 'object',\n        title: 'Metadata',\n        coerced: true,\n        defaultValue: {},\n        description: 'Metadata to attach to the thread.',\n        required: false,\n      });\n    }\n\n    return inputs;\n  },\n\n  getOutputDefinitions() {\n    return [\n      {\n        id: 'threadId' as PortId,\n        dataType: 'string',\n        title: 'Thread ID',\n        description: 'The ID of the created thread.',\n      },\n      {\n        id: 'thread' as PortId,\n        dataType: 'object',\n        title: 'Thread',\n        description: 'The full created thread object.',\n      },\n    ];\n  },\n\n  getEditors(): EditorDefinition<CreateThreadNode>[] {\n    return [\n      {\n        type: 'keyValuePair',\n        dataKey: 'metadata',\n        useInputToggleDataKey: 'useMetadataInput',\n        label: 'Metadata',\n        keyPlaceholder: 'Key',\n        valuePlaceholder: 'Value',\n      },\n    ];\n  },\n\n  getBody(data) {\n    return dedent`\n      ${data.threadId ? `Thread ID: ${data.threadId}` : 'Create New Thread'}\n      ${\n        data.useMetadataInput\n          ? '(Metadata From Input)'\n          : data.metadata.map(({ key, value }) => `${key}=${value}`).join(', ')\n      }\n    `;\n  },\n\n  async process(data, inputData, context) {\n    const threadId = getInputOrData(data, inputData, 'threadId') ?? '';\n\n    const messages = coerceTypeOptional(inputData['messages' as PortId], 'object[]') ?? [];\n\n    let metadata: Record<string, string> = data.metadata.reduce(\n      (acc, { key, value }) => {\n        acc[key] = value;\n        return acc;\n      },\n      {} as Record<string, string>,\n    );\n\n    if (data.useMetadataInput && inputData['metadata' as PortId]) {\n      metadata = coerceTypeOptional(inputData['metadata' as PortId], 'object') as Record<string, string>;\n    }\n\n    if (!context.settings.openAiKey) {\n      throw new Error('OpenAI key is not set.');\n    }\n\n    const messagesFormatted = messages.map((message): CreateMessageBody => {\n      if (!('role' in message)) {\n        throw new Error('Invalid message format.');\n      }\n\n      if (message.role !== 'user') {\n        throw new Error('Only user messages are supported.');\n      }\n\n      return message as CreateMessageBody;\n    });\n\n    const url = threadId.trim() ? `https://api.openai.com/v1/threads/${threadId}` : 'https://api.openai.com/v1/threads';\n\n    if (threadId && messages.length > 0) {\n      throw new Error('Cannot provide messages when modifying an existing thread.');\n    }\n\n    const response = await fetch(url, {\n      method: 'POST',\n      headers: {\n        'OpenAI-Beta': 'assistants=v1',\n        'Content-Type': 'application/json',\n        Authorization: `Bearer ${context.settings.openAiKey}`,\n        'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n      },\n      body: JSON.stringify(\n        threadId.trim()\n          ? { metadata }\n          : ({\n              messages: messagesFormatted,\n              metadata,\n            } satisfies CreateThreadBody),\n      ),\n    });\n\n    if (!response.ok) {\n      throw new Error('Failed to create thread.');\n    }\n\n    const body = (await response.json()) as OpenAIThread;\n\n    return {\n      ['threadId' as PortId]: {\n        type: 'string',\n        value: body.id,\n      },\n      ['thread' as PortId]: {\n        type: 'object',\n        value: body,\n      },\n    };\n  },\n};\n\nexport const createThreadNode = pluginNodeDefinition(CreateThreadNodeImpl, 'Create Thread');\n", "import {\n  type ChartNode,\n  type PluginNodeImpl,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type EditorDefinition,\n} from '../../../index.js';\nimport type { OpenAIThread } from '../../../utils/openai.js';\nimport { newId, dedent } from '../../../utils/index.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\n\nexport type GetThreadNode = ChartNode<'openaiGetThread', GetThreadNodeData>;\n\nexport type GetThreadNodeData = {\n  threadId: string;\n  useThreadIdInput?: boolean;\n};\n\nexport const GetThreadNodeImpl: PluginNodeImpl<GetThreadNode> = {\n  create() {\n    return {\n      id: newId<NodeId>(),\n      type: 'openaiGetThread',\n      data: {\n        threadId: '',\n        useThreadIdInput: true,\n      },\n      title: 'Get Thread',\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 225,\n      },\n    };\n  },\n\n  getUIData() {\n    return {\n      group: 'OpenAI',\n      contextMenuTitle: 'Get Thread',\n      infoBoxTitle: 'Get Thread Node',\n      infoBoxBody: 'Retrieve an existing thread from OpenAI assistants.',\n    };\n  },\n\n  getInputDefinitions(data) {\n    const inputs: NodeInputDefinition[] = [];\n\n    if (data.useThreadIdInput) {\n      inputs.push({\n        id: 'threadId' as PortId,\n        dataType: 'string',\n        title: 'Thread ID',\n        description: 'The ID of the thread to retrieve.',\n        required: true,\n      });\n    }\n\n    return inputs;\n  },\n\n  getOutputDefinitions() {\n    return [\n      {\n        id: 'thread' as PortId,\n        dataType: 'object',\n        title: 'Thread',\n        description:\n          'The retrieved thread object. If the thread does not exist, this port will not be ran. You can use an If node to test whether the thread exists.',\n      },\n    ];\n  },\n\n  getEditors(): EditorDefinition<GetThreadNode>[] {\n    return [\n      {\n        type: 'string',\n        dataKey: 'threadId',\n        useInputToggleDataKey: 'useThreadIdInput',\n        label: 'Thread ID',\n        autoFocus: true,\n      },\n    ];\n  },\n\n  getBody(data) {\n    return dedent`\n      ${data.useThreadIdInput ? '(Thread ID from input)' : `Thread ID: ${data.threadId}`}\n    `;\n  },\n\n  async process(data, inputData, context) {\n    let threadId = data.threadId;\n\n    if (data.useThreadIdInput) {\n      threadId = inputData['threadId' as PortId]?.value as string;\n      if (!threadId) {\n        throw new Error('Thread ID is required.');\n      }\n    }\n\n    if (!context.settings.openAiKey) {\n      throw new Error('OpenAI key is not set.');\n    }\n\n    const response = await fetch(`https://api.openai.com/v1/threads/${threadId}`, {\n      method: 'GET',\n      headers: {\n        'OpenAI-Beta': 'assistants=v1',\n        'Content-Type': 'application/json',\n        Authorization: `Bearer ${context.settings.openAiKey}`,\n        'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n      },\n    });\n\n    if (response.status === 404) {\n      return {\n        ['thread' as PortId]: {\n          type: 'control-flow-excluded',\n          value: undefined,\n        },\n      };\n    }\n\n    if (!response.ok) {\n      throw new Error('Failed to get thread.');\n    }\n\n    const body = (await response.json()) as OpenAIThread;\n\n    return {\n      ['thread' as PortId]: {\n        type: 'object',\n        value: body,\n      },\n    };\n  },\n};\n\nexport const getThreadNode = pluginNodeDefinition(GetThreadNodeImpl, 'Get Thread');\n", "import {\n  type ChartNode,\n  type PluginNodeImpl,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n} from '../../../index.js';\nimport { newId, dedent, getInputOrData } from '../../../utils/index.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\n\nexport type DeleteThreadNode = ChartNode<'openaiDeleteThread', DeleteThreadNodeData>;\n\nexport type DeleteThreadNodeData = {\n  threadId: string;\n  useThreadIdInput?: boolean;\n};\n\nexport const DeleteThreadNodeImpl: PluginNodeImpl<DeleteThreadNode> = {\n  create() {\n    return {\n      id: newId<NodeId>(),\n      type: 'openaiDeleteThread',\n      data: {\n        threadId: '',\n        useThreadIdInput: true,\n      },\n      title: 'Delete Thread',\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 225,\n      },\n    };\n  },\n\n  getUIData() {\n    return {\n      group: 'OpenAI',\n      contextMenuTitle: 'Delete Thread',\n      infoBoxTitle: 'Delete Thread Node',\n      infoBoxBody: 'Delete an existing thread from OpenAI assistants.',\n    };\n  },\n\n  getInputDefinitions(data) {\n    const inputs: NodeInputDefinition[] = [];\n\n    if (data.useThreadIdInput) {\n      inputs.push({\n        id: 'threadId' as PortId,\n        dataType: 'string',\n        title: 'Thread ID',\n        description: 'The ID of the thread to delete.',\n        required: true,\n      });\n    }\n\n    return inputs;\n  },\n\n  getOutputDefinitions() {\n    return [\n      {\n        id: 'threadId' as PortId,\n        dataType: 'string',\n        title: 'Thread ID',\n        description: 'The ID of the deleted thread.',\n      },\n    ];\n  },\n\n  getBody(data) {\n    return dedent`\n      ${data.useThreadIdInput ? '' : `Thread ID: ${data.threadId}`}\n    `;\n  },\n\n  getEditors() {\n    return [];\n  },\n\n  async process(data, inputData, context) {\n    const threadId = getInputOrData(data, inputData, 'threadId');\n\n    if (!threadId) {\n      throw new Error('Thread ID is required.');\n    }\n\n    if (!context.settings.openAiKey) {\n      throw new Error('OpenAI key is not set.');\n    }\n\n    const response = await fetch(`https://api.openai.com/v1/threads/${threadId}`, {\n      method: 'DELETE',\n      headers: {\n        'OpenAI-Beta': 'assistants=v1',\n        'Content-Type': 'application/json',\n        Authorization: `Bearer ${context.settings.openAiKey}`,\n        'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n      },\n    });\n\n    if (response.status === 404) {\n      return {\n        ['threadId' as PortId]: {\n          type: 'control-flow-excluded',\n          value: undefined,\n        },\n      };\n    }\n\n    if (!response.ok) {\n      throw new Error('Failed to delete thread.');\n    }\n\n    // Return the threadId as output so that subsequent nodes can use it\n    return {\n      ['threadId' as PortId]: {\n        type: 'string',\n        value: threadId,\n      },\n    };\n  },\n};\n\nexport const deleteThreadNode = pluginNodeDefinition(DeleteThreadNodeImpl, 'Delete Thread');\n", "export async function handleOpenAIError(response: Response) {\n  if (!response.ok) {\n    let errorBody: any;\n    try {\n      errorBody = await response.json();\n    } catch (err) {\n      throw new Error(`OpenAI request failed, no JSON body. Status code: ${response.status}`);\n    }\n\n    if (errorBody?.error?.message) {\n      throw new Error(errorBody.error.message);\n    } else {\n      throw new Error(`OpenAI request failed with body. Status code: ${response.status}: ${JSON.stringify(errorBody)}`);\n    }\n  }\n}\n", "import {\n  type ChartNode,\n  type PluginNodeImpl,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type EditorDefinition,\n  type GptFunction,\n} from '../../../index.js';\nimport { openAiModelOptions, type CreateAssistantBody, type OpenAIAssistantTool } from '../../../utils/openai.js';\nimport { dedent, newId, coerceTypeOptional, getInputOrData } from '../../../utils/index.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport { handleOpenAIError } from '../handleOpenaiError.js';\n\nexport type CreateAssistantNode = ChartNode<'openaiCreateAssistant', CreateAssistantNodeData>;\n\nexport type CreateAssistantNodeData = {\n  assistantId: string;\n  useAssistantIdInput?: boolean;\n\n  model?: string;\n  useModelInput?: boolean;\n\n  name?: string;\n  useNameInput?: boolean;\n\n  description?: string;\n  useDescriptionInput?: boolean;\n\n  instructions?: string;\n  useInstructionsInput?: boolean;\n\n  useCodeInterpreterTool?: boolean;\n  useRetrievalTool?: boolean;\n  functions?: GptFunction[];\n\n  file_ids?: string[];\n  useFileIdsInput?: boolean;\n\n  metadata: { key: string; value: string }[];\n  useMetadataInput?: boolean;\n};\n\nexport const CreateAssistantNodeImpl: PluginNodeImpl<CreateAssistantNode> = {\n  create() {\n    return {\n      id: newId<NodeId>(),\n      type: 'openaiCreateAssistant',\n      data: {\n        assistantId: '',\n        useAssistantIdInput: false,\n        model: '',\n        useModelInput: false,\n        name: '',\n        useNameInput: false,\n        description: '',\n        useDescriptionInput: false,\n        instructions: '',\n        useInstructionsInput: false,\n        tools: [],\n        file_ids: [],\n        useFileIdsInput: false,\n        metadata: [],\n        useMetadataInput: false,\n      },\n      title: 'Create Assistant',\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 300,\n      },\n    };\n  },\n\n  getUIData() {\n    return {\n      group: 'OpenAI',\n      contextMenuTitle: 'Create Assistant',\n      infoBoxTitle: 'Create Assistant Node',\n      infoBoxBody: 'Create a new assistant for OpenAI.',\n    };\n  },\n\n  getInputDefinitions(data) {\n    const inputs: NodeInputDefinition[] = [];\n\n    if (data.useAssistantIdInput) {\n      inputs.push({\n        id: 'assistantId' as PortId,\n        dataType: 'string',\n        title: 'Assistant ID',\n        coerced: true,\n        defaultValue: '',\n        description: 'The ID of the assistant to modify. Leave empty to create a new assistant.',\n      });\n    }\n\n    if (data.useModelInput) {\n      inputs.push({\n        id: 'model' as PortId,\n        dataType: 'string',\n        title: 'Model',\n        coerced: true,\n        defaultValue: '',\n        description: 'ID of the model to use.',\n        required: false,\n      });\n    }\n\n    if (data.useNameInput) {\n      inputs.push({\n        id: 'name' as PortId,\n        dataType: 'string',\n        title: 'Name',\n        coerced: true,\n        defaultValue: '',\n        description: 'The name of the assistant.',\n        required: false,\n      });\n    }\n\n    if (data.useDescriptionInput) {\n      inputs.push({\n        id: 'description' as PortId,\n        dataType: 'string',\n        title: 'Description',\n        coerced: true,\n        defaultValue: '',\n        description: 'The description of the assistant.',\n        required: false,\n      });\n    }\n\n    if (data.useInstructionsInput) {\n      inputs.push({\n        id: 'instructions' as PortId,\n        dataType: 'string',\n        title: 'Instructions',\n        coerced: true,\n        defaultValue: '',\n        description: 'The system instructions that the assistant uses.',\n        required: false,\n      });\n    }\n\n    inputs.push({\n      id: 'functions' as PortId,\n      dataType: 'object[]',\n      title: 'Functions',\n      coerced: true,\n      defaultValue: [],\n      description: 'A list of GPT functions enabled on the assistant.',\n      required: false,\n    });\n\n    if (data.useFileIdsInput) {\n      inputs.push({\n        id: 'file_ids' as PortId,\n        dataType: 'string[]',\n        title: 'File IDs',\n        coerced: true,\n        defaultValue: [],\n        description: 'A list of file IDs attached to this assistant.',\n        required: false,\n      });\n    }\n\n    if (data.useMetadataInput) {\n      inputs.push({\n        id: 'metadata' as PortId,\n        dataType: 'object',\n        title: 'Metadata',\n        coerced: true,\n        defaultValue: {},\n        description: 'Metadata to attach to the assistant.',\n        required: false,\n      });\n    }\n\n    return inputs;\n  },\n\n  getOutputDefinitions() {\n    return [\n      {\n        id: 'assistantId' as PortId,\n        dataType: 'string',\n        title: 'Assistant ID',\n        description: 'The ID of the created assistant.',\n      },\n      {\n        id: 'assistant' as PortId,\n        dataType: 'object',\n        title: 'Assistant',\n        description: 'The full created assistant object.',\n      },\n    ];\n  },\n\n  getEditors(): EditorDefinition<CreateAssistantNode>[] {\n    return [\n      {\n        type: 'string',\n        dataKey: 'assistantId',\n        useInputToggleDataKey: 'useAssistantIdInput',\n        label: 'Existing Assistant ID',\n        placeholder: 'Existing assistant ID',\n        helperMessage: 'Leave empty to create a new assistant.',\n      },\n      {\n        type: 'dropdown',\n        dataKey: 'model',\n        useInputToggleDataKey: 'useModelInput',\n        label: 'Model',\n        options: openAiModelOptions,\n        defaultValue: 'gpt-4-turbo',\n      },\n      {\n        type: 'string',\n        dataKey: 'name',\n        useInputToggleDataKey: 'useNameInput',\n        label: 'Name',\n        placeholder: 'Enter assistant name',\n        maxLength: 256,\n        autoFocus: true,\n      },\n      {\n        type: 'string',\n        dataKey: 'description',\n        useInputToggleDataKey: 'useDescriptionInput',\n        label: 'Description',\n        placeholder: 'Enter assistant description',\n        maxLength: 512,\n      },\n      {\n        type: 'code',\n        dataKey: 'instructions',\n        useInputToggleDataKey: 'useInstructionsInput',\n        label: 'Instructions',\n        language: 'markdown',\n      },\n      {\n        type: 'toggle',\n        dataKey: 'useCodeInterpreterTool',\n        label: 'Code Interpreter Tool Enabled',\n      },\n      {\n        type: 'toggle',\n        dataKey: 'useRetrievalTool',\n        label: 'Retrieval Tool Enabled',\n      },\n      {\n        type: 'stringList',\n        dataKey: 'file_ids',\n        useInputToggleDataKey: 'useFileIdsInput',\n        label: 'File IDs',\n      },\n      {\n        type: 'keyValuePair',\n        dataKey: 'metadata',\n        useInputToggleDataKey: 'useMetadataInput',\n        label: 'Metadata',\n        keyPlaceholder: 'Key',\n        valuePlaceholder: 'Value',\n      },\n    ];\n  },\n\n  getBody(data) {\n    return dedent`\n      Model: ${data.useModelInput ? '(Model From Input)' : data.model}\n      Name: ${data.useNameInput ? '(Name From Input)' : data.name}\n      Description: ${data.useDescriptionInput ? '(Description From Input)' : data.description}\n      File IDs: ${data.useFileIdsInput ? '(File IDs From Input)' : JSON.stringify(data.file_ids)}\n      Metadata: ${\n        data.useMetadataInput\n          ? '(Metadata From Input)'\n          : data.metadata.map(({ key, value }) => `${key}=${value}`).join(', ')\n      }\n\n      ${data.useInstructionsInput ? '(Instructions From Input)' : data.instructions}\n    `;\n  },\n\n  async process(data, inputData, context) {\n    const assistantId = getInputOrData(data, inputData, 'assistantId');\n\n    let metadata = data.metadata.reduce(\n      (acc, { key, value }) => {\n        acc[key] = value;\n        return acc;\n      },\n      {} as Record<string, string>,\n    );\n    if (data.useMetadataInput && inputData['metadata' as PortId]) {\n      metadata = coerceTypeOptional(inputData['metadata' as PortId], 'object') as Record<string, string>;\n    }\n\n    const functionTools = coerceTypeOptional(inputData['functions' as PortId], 'gpt-function[]');\n    const tools = [...(functionTools?.map((f): OpenAIAssistantTool => ({ type: 'function', function: f })) ?? [])];\n    if (data.useCodeInterpreterTool) {\n      tools.push({ type: 'code_interpreter' });\n    }\n    if (data.useRetrievalTool) {\n      tools.push({ type: 'retrieval' });\n    }\n\n    const requestBody: CreateAssistantBody = {\n      model: getInputOrData(data, inputData, 'model'),\n      name: getInputOrData(data, inputData, 'name'),\n      description: getInputOrData(data, inputData, 'description'),\n      instructions: getInputOrData(data, inputData, 'instructions'),\n      tools,\n      file_ids: getInputOrData(data, inputData, 'file_ids', 'string[]'),\n      metadata,\n    };\n\n    if (!requestBody.model?.trim() || !requestBody.name?.trim()) {\n      throw new Error('Model and name are required.');\n    }\n\n    if (!context.settings.openAiKey) {\n      throw new Error('OpenAI key is not set.');\n    }\n\n    const url = assistantId.trim()\n      ? `https://api.openai.com/v1/assistants/${assistantId}`\n      : 'https://api.openai.com/v1/assistants';\n\n    const response = await fetch(url, {\n      method: 'POST',\n      headers: {\n        'OpenAI-Beta': 'assistants=v1',\n        'Content-Type': 'application/json',\n        Authorization: `Bearer ${context.settings.openAiKey}`,\n        'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n      },\n      body: JSON.stringify(requestBody),\n    });\n\n    await handleOpenAIError(response);\n\n    const body = await response.json();\n\n    return {\n      ['assistantId' as PortId]: {\n        type: 'string',\n        value: body.id,\n      },\n      ['assistant' as PortId]: {\n        type: 'object',\n        value: body,\n      },\n    };\n  },\n};\n\nexport const createAssistantNode = pluginNodeDefinition(CreateAssistantNodeImpl, 'Create Assistant');\n", "import {\n  type ChartNode,\n  type PluginNodeImpl,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type EditorDefinition,\n} from '../../../index.js';\nimport { newId, getInputOrData } from '../../../utils/index.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport { handleOpenAIError } from '../handleOpenaiError.js';\n\nexport type GetAssistantNode = ChartNode<'openaiGetAssistant', GetAssistantNodeData>;\n\nexport type GetAssistantNodeData = {\n  assistantId?: string;\n  useAssistantIdInput?: boolean;\n};\n\nexport const GetAssistantNodeImpl: PluginNodeImpl<GetAssistantNode> = {\n  create() {\n    return {\n      id: newId<NodeId>(),\n      type: 'openaiGetAssistant',\n      data: {\n        assistantId: '',\n        useAssistantIdInput: true,\n      },\n      title: 'Get Assistant',\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 300,\n      },\n    };\n  },\n\n  getUIData() {\n    return {\n      group: 'OpenAI',\n      contextMenuTitle: 'Get Assistant',\n      infoBoxTitle: 'Get Assistant Node',\n      infoBoxBody: 'Retrieve an assistant by its ID from OpenAI.',\n    };\n  },\n\n  getInputDefinitions(data) {\n    const inputs: NodeInputDefinition[] = [];\n\n    if (data.useAssistantIdInput) {\n      inputs.push({\n        id: 'assistantId' as PortId,\n        dataType: 'string',\n        title: 'Assistant ID',\n        coerced: true,\n        defaultValue: '',\n        description: 'The ID of the assistant to retrieve.',\n        required: true,\n      });\n    }\n\n    return inputs;\n  },\n\n  getOutputDefinitions() {\n    return [\n      {\n        id: 'assistantId' as PortId,\n        dataType: 'string',\n        title: 'Assistant ID',\n        description: 'The ID of the retrieved assistant.',\n      },\n      {\n        id: 'assistant' as PortId,\n        dataType: 'object',\n        title: 'Assistant',\n        description: 'The full retrieved assistant object.',\n      },\n    ];\n  },\n\n  getEditors(): EditorDefinition<GetAssistantNode>[] {\n    return [\n      {\n        type: 'string',\n        dataKey: 'assistantId',\n        useInputToggleDataKey: 'useAssistantIdInput',\n        label: 'Assistant ID',\n        placeholder: 'Enter assistant ID',\n      },\n    ];\n  },\n\n  getBody(data) {\n    return `Assistant ID: ${data.useAssistantIdInput ? '(Assistant ID From Input)' : data.assistantId}`;\n  },\n\n  async process(data, inputData, context) {\n    const assistantId = getInputOrData(data, inputData, 'assistantId');\n\n    if (!assistantId?.trim()) {\n      throw new Error('Assistant ID is required.');\n    }\n\n    if (!context.settings.openAiKey) {\n      throw new Error('OpenAI key is not set.');\n    }\n\n    const response = await fetch(`https://api.openai.com/v1/assistants/${assistantId}`, {\n      method: 'GET',\n      headers: {\n        'OpenAI-Beta': 'assistants=v1',\n        'Content-Type': 'application/json',\n        Authorization: `Bearer ${context.settings.openAiKey}`,\n        'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n      },\n    });\n\n    if (response.status === 404) {\n      return {\n        ['assistantId' as PortId]: {\n          type: 'control-flow-excluded',\n          value: undefined,\n        },\n        ['assistant' as PortId]: {\n          type: 'control-flow-excluded',\n          value: undefined,\n        },\n      };\n    }\n\n    await handleOpenAIError(response);\n\n    const body = await response.json();\n\n    return {\n      ['assistantId' as PortId]: {\n        type: 'string',\n        value: body.id,\n      },\n      ['assistant' as PortId]: {\n        type: 'object',\n        value: body,\n      },\n    };\n  },\n};\n\nexport const getAssistantNode = pluginNodeDefinition(GetAssistantNodeImpl, 'Get Assistant');\n", "import {\n  type ChartNode,\n  type PluginNodeImpl,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type EditorDefinition,\n} from '../../../index.js';\nimport { newId, getInputOrData, dedent } from '../../../utils/index.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport { handleOpenAIError } from '../handleOpenaiError.js';\nimport type { OpenAIAssistant, OpenAIListResponse, OpenAIPaginationQuery } from '../../../utils/openai.js';\n\nexport type ListAssistantsNode = ChartNode<'openaiListAssistants', ListAssistantsNodeData>;\n\nexport type ListAssistantsNodeData = {\n  limit?: number;\n  useLimitInput?: boolean;\n\n  order?: string;\n  useOrderInput?: boolean;\n\n  after?: string;\n  useAfterInput?: boolean;\n\n  before?: string;\n  useBeforeInput?: boolean;\n};\n\nexport const ListAssistantsNodeImpl: PluginNodeImpl<ListAssistantsNode> = {\n  create() {\n    return {\n      id: newId<NodeId>(),\n      type: 'openaiListAssistants',\n      data: {\n        limit: 20,\n        useLimitInput: false,\n        order: 'asc',\n        useOrderInput: false,\n        after: '',\n        useAfterInput: false,\n        before: '',\n        useBeforeInput: false,\n      },\n      title: 'List Assistants',\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 300,\n      },\n    };\n  },\n\n  getUIData() {\n    return {\n      group: 'OpenAI',\n      contextMenuTitle: 'List Assistants',\n      infoBoxTitle: 'List Assistants Node',\n      infoBoxBody: 'List assistants from OpenAI.',\n    };\n  },\n\n  getInputDefinitions(data) {\n    const inputs: NodeInputDefinition[] = [];\n\n    if (data.useLimitInput) {\n      inputs.push({\n        id: 'limit' as PortId,\n        dataType: 'number',\n        title: 'Limit',\n        coerced: true,\n        defaultValue: 20,\n        description: 'A limit on the number of objects to be returned.',\n        required: false,\n      });\n    }\n\n    if (data.useOrderInput) {\n      inputs.push({\n        id: 'order' as PortId,\n        dataType: 'string',\n        title: 'Order',\n        coerced: true,\n        defaultValue: 'asc',\n        description: 'Sort order by the created_at timestamp of the objects.',\n        required: false,\n      });\n    }\n\n    if (data.useAfterInput) {\n      inputs.push({\n        id: 'after' as PortId,\n        dataType: 'string',\n        title: 'After',\n        coerced: true,\n        defaultValue: '',\n        description: 'A cursor for use in pagination.',\n        required: false,\n      });\n    }\n\n    if (data.useBeforeInput) {\n      inputs.push({\n        id: 'before' as PortId,\n        dataType: 'string',\n        title: 'Before',\n        coerced: true,\n        defaultValue: '',\n        description: 'A cursor for use in pagination.',\n        required: false,\n      });\n    }\n\n    return inputs;\n  },\n\n  getOutputDefinitions() {\n    return [\n      {\n        id: 'assistants' as PortId,\n        dataType: 'object[]',\n        title: 'Assistants',\n        description: 'The list of assistants.',\n      },\n      {\n        id: 'first_id' as PortId,\n        dataType: 'string',\n        title: 'First ID',\n        description: 'The ID of the first assistant in the list.',\n      },\n      {\n        id: 'last_id' as PortId,\n        dataType: 'string',\n        title: 'Last ID',\n        description: 'The ID of the last assistant in the list.',\n      },\n      {\n        id: 'has_more' as PortId,\n        dataType: 'boolean',\n        title: 'Has More',\n        description: 'Whether there are more assistants to be retrieved.',\n      },\n    ];\n  },\n\n  getEditors(): EditorDefinition<ListAssistantsNode>[] {\n    return [\n      {\n        type: 'number',\n        dataKey: 'limit',\n        useInputToggleDataKey: 'useLimitInput',\n        label: 'Limit',\n        defaultValue: 20,\n        min: 1,\n        max: 100,\n      },\n      {\n        type: 'dropdown',\n        dataKey: 'order',\n        useInputToggleDataKey: 'useOrderInput',\n        label: 'Order',\n        options: [\n          { value: 'asc', label: 'Ascending' },\n          { value: 'desc', label: 'Descending' },\n        ],\n        defaultValue: 'asc',\n      },\n      {\n        type: 'string',\n        dataKey: 'after',\n        useInputToggleDataKey: 'useAfterInput',\n        label: 'After',\n        placeholder: 'Enter after cursor',\n      },\n      {\n        type: 'string',\n        dataKey: 'before',\n        useInputToggleDataKey: 'useBeforeInput',\n        label: 'Before',\n        placeholder: 'Enter before cursor',\n      },\n    ];\n  },\n\n  getBody(data) {\n    return dedent`\n      Limit: ${data.useLimitInput ? '(Limit From Input)' : data.limit}, ${\n        data.useOrderInput ? '(Order From Input)' : data.order === 'asc' ? 'Ascending' : 'Descending'\n      }\n${\n  data.useAfterInput || data.after?.trim() ? `After: ${data.useAfterInput ? '(After From Input)' : data.after}\\n` : ''\n}${\n      data.useBeforeInput || data.before?.trim()\n        ? `Before: ${data.useBeforeInput ? '(Before From Input)' : data.before}\\n`\n        : ''\n    }\n    `;\n  },\n\n  async process(data, inputData, context) {\n    const requestQuery: OpenAIPaginationQuery = {\n      limit: getInputOrData(data, inputData, 'limit', 'number').toString(),\n      order: getInputOrData(data, inputData, 'order'),\n      after: getInputOrData(data, inputData, 'after') || undefined, // Mutually exclusive with before, so set to undefined if empty string\n      before: getInputOrData(data, inputData, 'before') || undefined,\n    };\n\n    const queryParams = Object.entries(requestQuery).filter(([, value]) => value !== undefined) as string[][];\n\n    if (!context.settings.openAiKey) {\n      throw new Error('OpenAI key is not set.');\n    }\n\n    const query = new URLSearchParams(queryParams);\n    const url = `https://api.openai.com/v1/assistants?${query.toString()}`;\n\n    const response = await fetch(url, {\n      method: 'GET',\n      headers: {\n        'OpenAI-Beta': 'assistants=v1',\n        'Content-Type': 'application/json',\n        Authorization: `Bearer ${context.settings.openAiKey}`,\n        'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n      },\n    });\n\n    await handleOpenAIError(response);\n\n    const body = (await response.json()) as OpenAIListResponse<OpenAIAssistant>;\n\n    return {\n      ['assistants' as PortId]: {\n        type: 'object[]',\n        value: body.data,\n      },\n      ['first_id' as PortId]: {\n        type: 'string',\n        value: body.first_id,\n      },\n      ['last_id' as PortId]: {\n        type: 'string',\n        value: body.last_id,\n      },\n      ['has_more' as PortId]: {\n        type: 'boolean',\n        value: body.has_more,\n      },\n    };\n  },\n};\n\nexport const listAssistantsNode = pluginNodeDefinition(ListAssistantsNodeImpl, 'List Assistants');\n", "import {\n  type ChartNode,\n  type PluginNodeImpl,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n} from '../../../index.js';\nimport { newId, dedent, getInputOrData } from '../../../utils/index.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport { handleOpenAIError } from '../handleOpenaiError.js';\n\nexport type DeleteAssistantNode = ChartNode<'openaiDeleteAssistant', DeleteAssistantNodeData>;\n\nexport type DeleteAssistantNodeData = {\n  assistantId: string;\n  useAssistantIdInput?: boolean;\n};\n\nexport const DeleteAssistantNodeImpl: PluginNodeImpl<DeleteAssistantNode> = {\n  create() {\n    return {\n      id: newId<NodeId>(),\n      type: 'openaiDeleteAssistant',\n      data: {\n        assistantId: '',\n        useAssistantIdInput: true,\n      },\n      title: 'Delete Assistant',\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 275,\n      },\n    };\n  },\n\n  getUIData() {\n    return {\n      group: 'OpenAI',\n      contextMenuTitle: 'Delete Assistant',\n      infoBoxTitle: 'Delete Assistant Node',\n      infoBoxBody: 'Delete an existing assistant from OpenAI.',\n    };\n  },\n\n  getInputDefinitions(data) {\n    const inputs: NodeInputDefinition[] = [];\n\n    if (data.useAssistantIdInput) {\n      inputs.push({\n        id: 'assistantId' as PortId,\n        dataType: 'string',\n        title: 'Assistant ID',\n        description: 'The ID of the assistant to delete.',\n        required: true,\n      });\n    }\n\n    return inputs;\n  },\n\n  getOutputDefinitions() {\n    return [\n      {\n        id: 'assistantId' as PortId,\n        dataType: 'string',\n        title: 'Assistant ID',\n        description: 'The ID of the deleted assistant.',\n      },\n    ];\n  },\n\n  getBody(data) {\n    return dedent`\n      ${data.useAssistantIdInput ? '' : `Assistant ID: ${data.assistantId}`}\n    `;\n  },\n\n  getEditors() {\n    return [\n      {\n        type: 'string',\n        dataKey: 'assistantId',\n        useInputToggleDataKey: 'useAssistantIdInput',\n        label: 'Assistant ID',\n        placeholder: 'Enter assistant ID',\n      },\n    ];\n  },\n\n  async process(data, inputData, context) {\n    const assistantId = getInputOrData(data, inputData, 'assistantId');\n\n    if (!assistantId) {\n      throw new Error('Assistant ID is required.');\n    }\n\n    if (!context.settings.openAiKey) {\n      throw new Error('OpenAI key is not set.');\n    }\n\n    const response = await fetch(`https://api.openai.com/v1/assistants/${assistantId}`, {\n      method: 'DELETE',\n      headers: {\n        'OpenAI-Beta': 'assistants=v1',\n        'Content-Type': 'application/json',\n        Authorization: `Bearer ${context.settings.openAiKey}`,\n        'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n      },\n    });\n\n    if (response.status === 404) {\n      return {\n        ['assistantId' as PortId]: {\n          type: 'control-flow-excluded',\n          value: undefined,\n        },\n      };\n    }\n\n    await handleOpenAIError(response);\n\n    // Return the assistantId as output so that subsequent nodes can use it\n    return {\n      ['assistantId' as PortId]: {\n        type: 'string',\n        value: assistantId,\n      },\n    };\n  },\n};\n\nexport const deleteAssistantNode = pluginNodeDefinition(DeleteAssistantNodeImpl, 'Delete Assistant');\n", "import {\n  type ChartNode,\n  type PluginNodeImpl,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type EditorDefinition,\n} from '../../../index.js';\nimport { newId, dedent, getInputOrData, coerceType, coerceTypeOptional } from '../../../utils/index.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport { handleOpenAIError } from '../handleOpenaiError.js';\nimport { openAIFileUploadPurposeOptions } from '../../../utils/openai.js';\n\nexport type UploadFileNode = ChartNode<'openaiUploadFile', UploadFileNodeData>;\n\nexport type UploadFileNodeData = {\n  purpose: 'fine-tune' | 'assistants' | 'assistants_output';\n};\n\nexport const UploadFileNodeImpl: PluginNodeImpl<UploadFileNode> = {\n  create() {\n    return {\n      id: newId<NodeId>(),\n      type: 'openaiUploadFile',\n      data: {\n        purpose: 'assistants',\n      },\n      title: 'Upload File to OpenAI',\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 300,\n      },\n    };\n  },\n\n  getUIData() {\n    return {\n      group: 'OpenAI',\n      contextMenuTitle: 'Upload File to OpenAI',\n      infoBoxTitle: 'Upload File to OpenAI Node',\n      infoBoxBody: 'Upload a file to OpenAI.',\n    };\n  },\n\n  getInputDefinitions() {\n    const inputs: NodeInputDefinition[] = [];\n\n    inputs.push({\n      id: 'data' as PortId,\n      dataType: 'binary',\n      title: 'Data',\n      coerced: true,\n      defaultValue: '',\n      description: 'The binary data of the file to upload.',\n      required: true,\n    });\n\n    inputs.push({\n      id: 'file-name' as PortId,\n      dataType: 'string',\n      title: 'File Name',\n      coerced: true,\n      description: 'An optional file name to use for the uploaded file.',\n      required: false,\n    });\n\n    return inputs;\n  },\n\n  getOutputDefinitions() {\n    return [\n      {\n        id: 'fileId' as PortId,\n        dataType: 'string',\n        title: 'File ID',\n        description: 'The ID of the uploaded file.',\n      },\n      {\n        id: 'file' as PortId,\n        dataType: 'object',\n        title: 'File',\n        description: 'The full uploaded file object.',\n      },\n    ];\n  },\n\n  getEditors(): EditorDefinition<UploadFileNode>[] {\n    return [\n      {\n        type: 'dropdown',\n        dataKey: 'purpose',\n        label: 'Purpose',\n        options: openAIFileUploadPurposeOptions,\n        defaultValue: 'assistants',\n      },\n    ];\n  },\n\n  getBody(data) {\n    return dedent`\n      Purpose: ${openAIFileUploadPurposeOptions.find(({ value }) => value === data.purpose)?.label ?? 'Unknown'}\n    `;\n  },\n\n  async process(data, inputData, context) {\n    const purpose = getInputOrData(data, inputData, 'purpose');\n    const fileData = coerceType(inputData['data' as PortId], 'binary');\n    const fileName = coerceTypeOptional(inputData['file-name' as PortId], 'string');\n\n    if (!fileData) {\n      throw new Error('File data is required.');\n    }\n\n    if (!context.settings.openAiKey) {\n      throw new Error('OpenAI key is not set.');\n    }\n\n    const file = fileName\n      ? new File([fileData], fileName, { type: 'application/octet-stream' })\n      : new Blob([fileData], { type: 'application/octet-stream' });\n\n    const formData = new FormData();\n    formData.append('purpose', purpose);\n    formData.append('file', file);\n\n    const response = await fetch('https://api.openai.com/v1/files', {\n      method: 'POST',\n      headers: {\n        Authorization: `Bearer ${context.settings.openAiKey}`,\n        'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n      },\n      body: formData,\n    });\n\n    await handleOpenAIError(response);\n\n    const body = await response.json();\n\n    return {\n      ['fileId' as PortId]: {\n        type: 'string',\n        value: body.id,\n      },\n      ['file' as PortId]: {\n        type: 'object',\n        value: body,\n      },\n    };\n  },\n};\n\nexport const uploadFileNode = pluginNodeDefinition(UploadFileNodeImpl, 'Upload File to OpenAI');\n", "import {\n  type ChartNode,\n  type PluginNodeImpl,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type EditorDefinition,\n} from '../../../index.js';\nimport { newId, getInputOrData, dedent } from '../../../utils/index.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport { handleOpenAIError } from '../handleOpenaiError.js';\nimport { openAIFilePurposeOptions, type OpenAIFile } from '../../../utils/openai.js';\n\nexport type ListOpenAIFilesNode = ChartNode<'openaiListFiles', ListOpenAIFilesNodeData>;\n\nexport type ListOpenAIFilesNodeData = {\n  purpose?: 'fine-tune' | 'fine-tune-results' | 'assistants' | 'assistants_output';\n  usePurposeInput?: boolean;\n};\n\nexport const ListOpenAIFilesNodeImpl: PluginNodeImpl<ListOpenAIFilesNode> = {\n  create() {\n    return {\n      id: newId<NodeId>(),\n      type: 'openaiListFiles',\n      data: {\n        purpose: 'assistants',\n      },\n      title: 'List OpenAI Files',\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 300,\n      },\n    };\n  },\n\n  getUIData() {\n    return {\n      group: 'OpenAI',\n      contextMenuTitle: 'List OpenAI Files',\n      infoBoxTitle: 'List OpenAI Files Node',\n      infoBoxBody: 'List files from OpenAI.',\n    };\n  },\n\n  getInputDefinitions(data) {\n    const inputs: NodeInputDefinition[] = [];\n\n    if (data.usePurposeInput) {\n      inputs.push({\n        id: 'purpose' as PortId,\n        dataType: 'string',\n        title: 'Purpose',\n        coerced: true,\n        defaultValue: '',\n        description: 'Retrieve only files with the specified purpose.',\n      });\n    }\n\n    return inputs;\n  },\n\n  getOutputDefinitions() {\n    return [\n      {\n        id: 'files' as PortId,\n        dataType: 'object[]',\n        title: 'Files',\n        description: 'The list of files.',\n      },\n    ];\n  },\n\n  getEditors(): EditorDefinition<ListOpenAIFilesNode>[] {\n    return [\n      {\n        type: 'dropdown',\n        dataKey: 'purpose',\n        useInputToggleDataKey: 'usePurposeInput',\n        label: 'Purpose',\n        options: openAIFilePurposeOptions,\n        defaultValue: 'assistants',\n      },\n    ];\n  },\n\n  getBody(data) {\n    return dedent`\n      Purpose: ${openAIFilePurposeOptions.find(({ value }) => value === data.purpose)?.label ?? 'Unknown'}\n    `;\n  },\n\n  async process(data, inputData, context) {\n    const purpose = getInputOrData(data, inputData, 'purpose');\n\n    if (!context.settings.openAiKey) {\n      throw new Error('OpenAI key is not set.');\n    }\n\n    const url = `https://api.openai.com/v1/files?purpose=${purpose}`;\n\n    const response = await fetch(url, {\n      method: 'GET',\n      headers: {\n        Authorization: `Bearer ${context.settings.openAiKey}`,\n        'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n      },\n    });\n\n    await handleOpenAIError(response);\n\n    const body = (await response.json()) as {\n      object: 'list';\n      data: OpenAIFile[];\n    };\n\n    return {\n      ['files' as PortId]: {\n        type: 'object[]',\n        value: body.data,\n      },\n    };\n  },\n};\n\nexport const listOpenAIFilesNode = pluginNodeDefinition(ListOpenAIFilesNodeImpl, 'List OpenAI Files');\n", "import {\n  type ChartNode,\n  type PluginNodeImpl,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type EditorDefinition,\n} from '../../../index.js';\nimport { newId, getInputOrData, dedent } from '../../../utils/index.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport { handleOpenAIError } from '../handleOpenaiError.js';\n\nexport type GetOpenAIFileNode = ChartNode<'openaiGetFile', GetOpenAIFileNodeData>;\n\nexport type GetOpenAIFileNodeData = {\n  fileId?: string;\n  useFileIdInput?: boolean;\n};\n\nexport const GetOpenAIFileNodeImpl: PluginNodeImpl<GetOpenAIFileNode> = {\n  create() {\n    return {\n      id: newId<NodeId>(),\n      type: 'openaiGetFile',\n      data: {\n        useFileIdInput: true,\n      },\n      title: 'Get OpenAI File',\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 300,\n      },\n    };\n  },\n\n  getUIData() {\n    return {\n      group: 'OpenAI',\n      contextMenuTitle: 'Get OpenAI File',\n      infoBoxTitle: 'Get OpenAI File Node',\n      infoBoxBody: 'Get a specific file from OpenAI.',\n    };\n  },\n\n  getInputDefinitions(data) {\n    const inputs: NodeInputDefinition[] = [];\n\n    if (data.useFileIdInput) {\n      inputs.push({\n        id: 'fileId' as PortId,\n        dataType: 'string',\n        title: 'File ID',\n        coerced: true,\n        defaultValue: '',\n        description: 'The ID of the file to retrieve.',\n        required: true,\n      });\n    }\n\n    return inputs;\n  },\n\n  getOutputDefinitions() {\n    return [\n      {\n        id: 'file' as PortId,\n        dataType: 'object',\n        title: 'File',\n        description: 'The retrieved file object.',\n      },\n    ];\n  },\n\n  getEditors(): EditorDefinition<GetOpenAIFileNode>[] {\n    return [\n      {\n        type: 'string',\n        dataKey: 'fileId',\n        useInputToggleDataKey: 'useFileIdInput',\n        label: 'File ID',\n      },\n    ];\n  },\n\n  getBody(data) {\n    return dedent`\n      File ID: ${data.fileId ?? 'Unknown'}\n    `;\n  },\n\n  async process(data, inputData, context) {\n    const fileId = getInputOrData(data, inputData, 'fileId');\n\n    if (!context.settings.openAiKey) {\n      throw new Error('OpenAI key is not set.');\n    }\n\n    const url = `https://api.openai.com/v1/files/${fileId}`;\n\n    const response = await fetch(url, {\n      method: 'GET',\n      headers: {\n        Authorization: `Bearer ${context.settings.openAiKey}`,\n        'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n      },\n    });\n\n    if (response.status === 404) {\n      return {\n        ['file' as PortId]: {\n          type: 'control-flow-excluded',\n          value: undefined,\n        },\n      };\n    }\n\n    await handleOpenAIError(response);\n\n    const body = await response.json();\n\n    return {\n      ['file' as PortId]: {\n        type: 'object',\n        value: body,\n      },\n    };\n  },\n};\n\nexport const getOpenAIFileNode = pluginNodeDefinition(GetOpenAIFileNodeImpl, 'Get OpenAI File');\n", "import {\n  type ChartNode,\n  type PluginNodeImpl,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type EditorDefinition,\n} from '../../../index.js';\nimport type { OpenAIAssistantFile } from '../../../utils/openai.js';\nimport { dedent, newId, getInputOrData } from '../../../utils/index.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport { handleOpenAIError } from '../handleOpenaiError.js';\n\nexport type AttachAssistantFileNode = ChartNode<'openaiAttachAssistantFile', AttachAssistantFileNodeData>;\n\nexport type AttachAssistantFileNodeData = {\n  assistantId?: string;\n  useAssistantIdInput?: boolean;\n  fileId?: string;\n  useFileIdInput?: boolean;\n};\n\nexport const AttachAssistantFileNodeImpl: PluginNodeImpl<AttachAssistantFileNode> = {\n  create() {\n    return {\n      id: newId<NodeId>(),\n      type: 'openaiAttachAssistantFile',\n      data: {\n        useAssistantIdInput: true,\n        useFileIdInput: true,\n      },\n      title: 'Attach Assistant File',\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 225,\n      },\n    };\n  },\n\n  getUIData() {\n    return {\n      group: 'OpenAI',\n      contextMenuTitle: 'Attach Assistant File',\n      infoBoxTitle: 'Attach Assistant File Node',\n      infoBoxBody: 'Attach a file to an OpenAI assistant.',\n    };\n  },\n\n  getInputDefinitions(data) {\n    const inputs: NodeInputDefinition[] = [];\n\n    if (data.useAssistantIdInput) {\n      inputs.push({\n        id: 'assistantId' as PortId,\n        dataType: 'string',\n        title: 'Assistant ID',\n        coerced: true,\n        defaultValue: '',\n        description: 'The ID of the assistant to attach the file to.',\n        required: true,\n      });\n    }\n\n    if (data.useFileIdInput) {\n      inputs.push({\n        id: 'fileId' as PortId,\n        dataType: 'string',\n        title: 'File ID',\n        coerced: true,\n        defaultValue: '',\n        description: 'The ID of the file to attach.',\n        required: true,\n      });\n    }\n\n    return inputs;\n  },\n\n  getOutputDefinitions() {\n    return [\n      {\n        id: 'fileId' as PortId,\n        dataType: 'string',\n        title: 'File ID',\n        description: 'The ID of the attached file.',\n      },\n    ];\n  },\n\n  getEditors(): EditorDefinition<AttachAssistantFileNode>[] {\n    return [\n      {\n        type: 'string',\n        dataKey: 'assistantId',\n        useInputToggleDataKey: 'useAssistantIdInput',\n        label: 'Assistant ID',\n      },\n      {\n        type: 'string',\n        dataKey: 'fileId',\n        useInputToggleDataKey: 'useFileIdInput',\n        label: 'File ID',\n      },\n    ];\n  },\n\n  getBody(data) {\n    return dedent`\n      Assistant ID: ${data.useAssistantIdInput ? '(From Input)' : data.assistantId}\n      File ID: ${data.useFileIdInput ? '(From Input)' : data.fileId}\n    `;\n  },\n\n  async process(data, inputData, context) {\n    const assistantId = getInputOrData(data, inputData, 'assistantId');\n    const fileId = getInputOrData(data, inputData, 'fileId');\n\n    if (!context.settings.openAiKey) {\n      throw new Error('OpenAI key is not set.');\n    }\n\n    const url = `https://api.openai.com/v1/assistants/${assistantId}/files`;\n\n    const response = await fetch(url, {\n      method: 'POST',\n      headers: {\n        'OpenAI-Beta': 'assistants=v1',\n        'Content-Type': 'application/json',\n        Authorization: `Bearer ${context.settings.openAiKey}`,\n        'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n      },\n      body: JSON.stringify({ file_id: fileId }),\n    });\n\n    if (response.status === 404) {\n      return {\n        ['fileId' as PortId]: {\n          type: 'control-flow-excluded',\n          value: undefined,\n        },\n      };\n    }\n\n    await handleOpenAIError(response);\n\n    const body = (await response.json()) as OpenAIAssistantFile;\n\n    return {\n      ['fileId' as PortId]: {\n        type: 'string',\n        value: body.id,\n      },\n    };\n  },\n};\n\nexport const attachAssistantFileNode = pluginNodeDefinition(AttachAssistantFileNodeImpl, 'Attach Assistant File');\n", "import {\n  type ChartNode,\n  type PluginNodeImpl,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type EditorDefinition,\n} from '../../../index.js';\nimport type { CreateMessageBody, OpenAIThreadMessage } from '../../../utils/openai.js';\nimport { dedent, newId, coerceTypeOptional, getInputOrData } from '../../../utils/index.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport { handleOpenAIError } from '../handleOpenaiError.js';\n\nexport type CreateThreadMessageNode = ChartNode<'openaiCreateThreadMessage', CreateThreadMessageNodeData>;\n\nexport type CreateThreadMessageNodeData = {\n  threadId: string;\n  useThreadIdInput?: boolean;\n\n  file_ids: string[];\n  useFileIdsInput?: boolean;\n\n  metadata: { key: string; value: string }[];\n  useMetadataInput?: boolean;\n};\n\nexport const CreateThreadMessageNodeImpl: PluginNodeImpl<CreateThreadMessageNode> = {\n  create() {\n    return {\n      id: newId<NodeId>(),\n      type: 'openaiCreateThreadMessage',\n      data: {\n        threadId: '',\n        useThreadIdInput: true,\n        file_ids: [],\n        useFileIdsInput: false,\n        metadata: [],\n        useMetadataInput: false,\n      },\n      title: 'Create Thread Message',\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 300,\n      },\n    };\n  },\n\n  getUIData() {\n    return {\n      group: 'OpenAI',\n      contextMenuTitle: 'Create Thread Message',\n      infoBoxTitle: 'Create Thread Message Node',\n      infoBoxBody: 'Create a new message for an OpenAI thread.',\n    };\n  },\n\n  getInputDefinitions(data) {\n    const inputs: NodeInputDefinition[] = [];\n\n    inputs.push({\n      id: 'content' as PortId,\n      dataType: 'string',\n      title: 'Content',\n      coerced: true,\n      defaultValue: '',\n      description: 'The content of the message.',\n    });\n\n    if (data.useThreadIdInput) {\n      inputs.push({\n        id: 'threadId' as PortId,\n        dataType: 'string',\n        title: 'Thread ID',\n        coerced: true,\n        defaultValue: '',\n        description: 'The ID of the thread to post the message to.',\n        required: true,\n      });\n    }\n\n    if (data.useFileIdsInput) {\n      inputs.push({\n        id: 'file_ids' as PortId,\n        dataType: 'string[]',\n        title: 'File IDs',\n        coerced: true,\n        defaultValue: [],\n        description: 'A list of file IDs attached to this message.',\n        required: false,\n      });\n    }\n\n    if (data.useMetadataInput) {\n      inputs.push({\n        id: 'metadata' as PortId,\n        dataType: 'object',\n        title: 'Metadata',\n        coerced: true,\n        defaultValue: {},\n        description: 'Metadata to attach to the message.',\n        required: false,\n      });\n    }\n\n    return inputs;\n  },\n\n  getOutputDefinitions() {\n    return [\n      {\n        id: 'messageId' as PortId,\n        dataType: 'string',\n        title: 'Message ID',\n        description: 'The ID of the created message.',\n      },\n      {\n        id: 'message' as PortId,\n        dataType: 'object',\n        title: 'Message',\n        description: 'The full created message object.',\n      },\n    ];\n  },\n\n  getEditors(): EditorDefinition<CreateThreadMessageNode>[] {\n    return [\n      {\n        type: 'string',\n        dataKey: 'threadId',\n        useInputToggleDataKey: 'useThreadIdInput',\n        label: 'Thread ID',\n        placeholder: 'Enter thread ID',\n        helperMessage: 'The ID of the thread to post the message to.',\n      },\n      {\n        type: 'stringList',\n        dataKey: 'file_ids',\n        useInputToggleDataKey: 'useFileIdsInput',\n        label: 'File IDs',\n      },\n      {\n        type: 'keyValuePair',\n        dataKey: 'metadata',\n        useInputToggleDataKey: 'useMetadataInput',\n        label: 'Metadata',\n        keyPlaceholder: 'Key',\n        valuePlaceholder: 'Value',\n      },\n    ];\n  },\n\n  getBody(data) {\n    return dedent`\n      Thread ID: ${data.useThreadIdInput ? '(Thread ID From Input)' : data.threadId}${\n        data.useFileIdsInput || data.file_ids.length > 0\n          ? `File IDs: ${data.useFileIdsInput ? '(File IDs From Input)' : JSON.stringify(data.file_ids)}\\n`\n          : ''\n      }${\n        data.useMetadataInput || data.metadata.length > 0\n          ? `Metadata: ${\n              data.useMetadataInput\n                ? '(Metadata From Input)'\n                : data.metadata.map(({ key, value }) => `${key}=${value}`).join(', ')\n            }\\n`\n          : ''\n      }\n    `;\n  },\n\n  async process(data, inputData, context) {\n    const threadId = getInputOrData(data, inputData, 'threadId');\n    const content = coerceTypeOptional(inputData['content' as PortId], 'string') ?? '';\n\n    let metadata = data.metadata.reduce(\n      (acc, { key, value }) => {\n        acc[key] = value;\n        return acc;\n      },\n      {} as Record<string, string>,\n    );\n    if (data.useMetadataInput && inputData['metadata' as PortId]) {\n      metadata = coerceTypeOptional(inputData['metadata' as PortId], 'object') as Record<string, string>;\n    }\n\n    const requestBody: CreateMessageBody = {\n      role: 'user',\n      content,\n      file_ids: getInputOrData(data, inputData, 'file_ids', 'string[]'),\n      metadata,\n    };\n\n    if (!context.settings.openAiKey) {\n      throw new Error('OpenAI key is not set.');\n    }\n\n    const url = `https://api.openai.com/v1/threads/${threadId}/messages`;\n\n    const response = await fetch(url, {\n      method: 'POST',\n      headers: {\n        'OpenAI-Beta': 'assistants=v1',\n        'Content-Type': 'application/json',\n        Authorization: `Bearer ${context.settings.openAiKey}`,\n        'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n      },\n      body: JSON.stringify(requestBody),\n    });\n\n    await handleOpenAIError(response);\n\n    const body = (await response.json()) as OpenAIThreadMessage;\n\n    return {\n      ['messageId' as PortId]: {\n        type: 'string',\n        value: body.id,\n      },\n      ['message' as PortId]: {\n        type: 'object',\n        value: body,\n      },\n    };\n  },\n};\n\nexport const createThreadMessageNode = pluginNodeDefinition(CreateThreadMessageNodeImpl, 'Create Thread Message');\n", "import {\n  type ChartNode,\n  type PluginNodeImpl,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type EditorDefinition,\n} from '../../../index.js';\nimport { newId, getInputOrData, dedent } from '../../../utils/index.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport { handleOpenAIError } from '../handleOpenaiError.js';\nimport type { ListThreadMessagesQuery, OpenAIListResponse, OpenAIThreadMessage } from '../../../utils/openai.js';\n\nexport type ListThreadMessagesNode = ChartNode<'openaiListThreadMessages', ListThreadMessagesNodeData>;\n\nexport type ListThreadMessagesNodeData = {\n  threadId: string;\n  useThreadIdInput?: boolean;\n\n  limit?: number;\n  useLimitInput?: boolean;\n\n  order?: string;\n  useOrderInput?: boolean;\n\n  after?: string;\n  useAfterInput?: boolean;\n\n  before?: string;\n  useBeforeInput?: boolean;\n};\n\nexport const ListThreadMessagesNodeImpl: PluginNodeImpl<ListThreadMessagesNode> = {\n  create() {\n    return {\n      id: newId<NodeId>(),\n      type: 'openaiListThreadMessages',\n      data: {\n        threadId: '',\n        useThreadIdInput: true,\n        limit: 20,\n        useLimitInput: false,\n        order: 'asc',\n        useOrderInput: false,\n        after: '',\n        useAfterInput: false,\n        before: '',\n        useBeforeInput: false,\n      },\n      title: 'List Thread Messages',\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 300,\n      },\n    };\n  },\n\n  getUIData() {\n    return {\n      group: 'OpenAI',\n      contextMenuTitle: 'List Thread Messages',\n      infoBoxTitle: 'List Thread Messages Node',\n      infoBoxBody: 'List messages from a thread in OpenAI.',\n    };\n  },\n\n  getInputDefinitions(data) {\n    const inputs: NodeInputDefinition[] = [];\n\n    if (data.useThreadIdInput) {\n      inputs.push({\n        id: 'threadId' as PortId,\n        dataType: 'string',\n        title: 'Thread ID',\n        coerced: true,\n        defaultValue: '',\n        description: 'The ID of the thread to retrieve messages from.',\n        required: true,\n      });\n    }\n\n    if (data.useLimitInput) {\n      inputs.push({\n        id: 'limit' as PortId,\n        dataType: 'number',\n        title: 'Limit',\n        coerced: true,\n        defaultValue: 20,\n        description: 'A limit on the number of objects to be returned.',\n        required: false,\n      });\n    }\n\n    if (data.useOrderInput) {\n      inputs.push({\n        id: 'order' as PortId,\n        dataType: 'string',\n        title: 'Order',\n        coerced: true,\n        defaultValue: 'asc',\n        description: 'Sort order by the created_at timestamp of the objects.',\n        required: false,\n      });\n    }\n\n    if (data.useAfterInput) {\n      inputs.push({\n        id: 'after' as PortId,\n        dataType: 'string',\n        title: 'After',\n        coerced: true,\n        defaultValue: '',\n        description: 'A cursor for use in pagination.',\n        required: false,\n      });\n    }\n\n    if (data.useBeforeInput) {\n      inputs.push({\n        id: 'before' as PortId,\n        dataType: 'string',\n        title: 'Before',\n        coerced: true,\n        defaultValue: '',\n        description: 'A cursor for use in pagination.',\n        required: false,\n      });\n    }\n\n    return inputs;\n  },\n\n  getOutputDefinitions() {\n    return [\n      {\n        id: 'messages' as PortId,\n        dataType: 'object[]',\n        title: 'Messages',\n        description: 'The list of messages.',\n      },\n      {\n        id: 'first_id' as PortId,\n        dataType: 'string',\n        title: 'First ID',\n        description: 'The ID of the first message in the list.',\n      },\n      {\n        id: 'last_id' as PortId,\n        dataType: 'string',\n        title: 'Last ID',\n        description: 'The ID of the last message in the list.',\n      },\n      {\n        id: 'has_more' as PortId,\n        dataType: 'boolean',\n        title: 'Has More',\n        description: 'Whether there are more messages to be retrieved.',\n      },\n    ];\n  },\n\n  getEditors(): EditorDefinition<ListThreadMessagesNode>[] {\n    return [\n      {\n        type: 'string',\n        dataKey: 'threadId',\n        useInputToggleDataKey: 'useThreadIdInput',\n        label: 'Thread ID',\n        placeholder: 'Enter thread ID',\n      },\n      {\n        type: 'number',\n        dataKey: 'limit',\n        useInputToggleDataKey: 'useLimitInput',\n        label: 'Limit',\n        defaultValue: 20,\n        min: 1,\n        max: 100,\n      },\n      {\n        type: 'dropdown',\n        dataKey: 'order',\n        useInputToggleDataKey: 'useOrderInput',\n        label: 'Order',\n        options: [\n          { value: 'asc', label: 'Ascending' },\n          { value: 'desc', label: 'Descending' },\n        ],\n        defaultValue: 'asc',\n      },\n      {\n        type: 'string',\n        dataKey: 'after',\n        useInputToggleDataKey: 'useAfterInput',\n        label: 'After',\n        placeholder: 'Enter after cursor',\n      },\n      {\n        type: 'string',\n        dataKey: 'before',\n        useInputToggleDataKey: 'useBeforeInput',\n        label: 'Before',\n        placeholder: 'Enter before cursor',\n      },\n    ];\n  },\n\n  getBody(data) {\n    return dedent`\n      Thread ID: ${data.useThreadIdInput ? '(Thread ID From Input)' : data.threadId}\n      Limit: ${data.useLimitInput ? '(Limit From Input)' : data.limit}, ${\n        data.useOrderInput ? '(Order From Input)' : data.order === 'asc' ? 'Ascending' : 'Descending'\n      }\n${\n  data.useAfterInput || data.after?.trim() ? `After: ${data.useAfterInput ? '(After From Input)' : data.after}\\n` : ''\n}${\n      data.useBeforeInput || data.before?.trim()\n        ? `Before: ${data.useBeforeInput ? '(Before From Input)' : data.before}\\n`\n        : ''\n    }\n    `;\n  },\n\n  async process(data, inputData, context) {\n    const threadId = getInputOrData(data, inputData, 'threadId');\n    const requestQuery: ListThreadMessagesQuery = {\n      limit: getInputOrData(data, inputData, 'limit', 'number'),\n      order: getInputOrData(data, inputData, 'order'),\n      after: getInputOrData(data, inputData, 'after') || undefined, // Mutually exclusive with before, so set to undefined if empty string\n      before: getInputOrData(data, inputData, 'before') || undefined,\n    };\n\n    const queryParams = Object.entries(requestQuery).filter(([, value]) => value !== undefined) as string[][];\n\n    if (!context.settings.openAiKey) {\n      throw new Error('OpenAI key is not set.');\n    }\n\n    const query = new URLSearchParams(queryParams);\n    const url = `https://api.openai.com/v1/threads/${threadId}/messages?${query.toString()}`;\n\n    const response = await fetch(url, {\n      method: 'GET',\n      headers: {\n        'OpenAI-Beta': 'assistants=v1',\n        'Content-Type': 'application/json',\n        Authorization: `Bearer ${context.settings.openAiKey}`,\n        'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n      },\n    });\n\n    await handleOpenAIError(response);\n\n    const body = (await response.json()) as OpenAIListResponse<OpenAIThreadMessage>;\n\n    return {\n      ['messages' as PortId]: {\n        type: 'object[]',\n        value: body.data,\n      },\n      ['first_id' as PortId]: {\n        type: 'string',\n        value: body.first_id,\n      },\n      ['last_id' as PortId]: {\n        type: 'string',\n        value: body.last_id,\n      },\n      ['has_more' as PortId]: {\n        type: 'boolean',\n        value: body.has_more,\n      },\n    };\n  },\n};\n\nexport const listThreadMessagesNode = pluginNodeDefinition(ListThreadMessagesNodeImpl, 'List Thread Messages');\n", "import {\n  type ChartNode,\n  type PluginNodeImpl,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type EditorDefinition,\n  type GptFunction,\n  type GraphId,\n  type GraphInputs,\n} from '../../../index.js';\nimport {\n  openAiModelOptions,\n  type CreateRunBody,\n  type OpenAIAssistantTool,\n  type OpenAIRun,\n  type CreateMessageBody,\n  type OpenAIRunStep,\n  type OpenAIListResponse,\n  type OpenAIPaginationQuery,\n  type OpenAIThreadMessage,\n} from '../../../utils/openai.js';\nimport { dedent, newId, coerceTypeOptional, getInputOrData } from '../../../utils/index.js';\nimport { arrayizeDataValue, unwrapDataValue } from '../../../model/DataValue.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport { handleOpenAIError } from '../handleOpenaiError.js';\nimport { type DataValue } from '../../../model/DataValue.js';\n\nexport type RunThreadNode = ChartNode<'openaiRunThread', RunThreadNodeData>;\n\nexport type RunThreadNodeData = {\n  createThread: boolean;\n\n  threadId: string;\n  useThreadIdInput?: boolean;\n\n  assistantId: string;\n  useAssistantIdInput?: boolean;\n\n  model?: string;\n  useModelInput?: boolean;\n\n  instructions?: string;\n  useInstructionsInput?: boolean;\n\n  useCodeInterpreterTool?: boolean;\n  useRetrievalTool?: boolean;\n  functions?: GptFunction[];\n\n  metadata: { key: string; value: string }[];\n  useMetadataInput?: boolean;\n\n  toolCallHandlers: { key: string; value: GraphId }[];\n\n  onMessageCreationSubgraphId?: GraphId;\n};\n\nconst POLL_FREQUENCY = 500;\n\nexport const RunThreadNodeImpl: PluginNodeImpl<RunThreadNode> = {\n  create() {\n    return {\n      id: newId<NodeId>(),\n      type: 'openaiRunThread',\n      data: {\n        createThread: true,\n        threadId: '',\n        useThreadIdInput: false,\n        assistantId: '',\n        useAssistantIdInput: false,\n        model: '',\n        useModelInput: false,\n        instructions: '',\n        useInstructionsInput: false,\n        tools: [],\n        metadata: [],\n        useMetadataInput: false,\n        toolCallHandlers: [],\n      },\n      title: 'Run Thread',\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 400,\n      },\n    };\n  },\n\n  getUIData() {\n    return {\n      group: 'OpenAI',\n      contextMenuTitle: 'Run Thread',\n      infoBoxTitle: 'Run Thread Node',\n      infoBoxBody: 'Run a thread for OpenAI.',\n    };\n  },\n\n  getInputDefinitions(data) {\n    const inputs: NodeInputDefinition[] = [];\n\n    if (!data.createThread && data.useThreadIdInput) {\n      inputs.push({\n        id: 'threadId' as PortId,\n        dataType: 'string',\n        title: 'Thread ID',\n        coerced: true,\n        defaultValue: '',\n        description: 'The ID of the thread to run.',\n        required: true,\n      });\n    }\n\n    if (data.createThread) {\n      inputs.push({\n        id: 'messages' as PortId,\n        dataType: 'object[]',\n        title: 'Messages',\n        coerced: true,\n        defaultValue: [],\n        description: 'A list of user messages to start the thread with.',\n        required: false,\n      });\n    }\n\n    if (data.useAssistantIdInput) {\n      inputs.push({\n        id: 'assistantId' as PortId,\n        dataType: 'string',\n        title: 'Assistant ID',\n        coerced: true,\n        defaultValue: '',\n        description: 'The ID of the assistant to use.',\n        required: true,\n      });\n    }\n\n    if (data.useModelInput) {\n      inputs.push({\n        id: 'model' as PortId,\n        dataType: 'string',\n        title: 'Model',\n        coerced: true,\n        defaultValue: '',\n        description: 'ID of the model to use.',\n        required: false,\n      });\n    }\n\n    if (data.useInstructionsInput) {\n      inputs.push({\n        id: 'instructions' as PortId,\n        dataType: 'string',\n        title: 'Instructions',\n        coerced: true,\n        defaultValue: '',\n        description: 'The system instructions that the assistant uses.',\n        required: false,\n      });\n    }\n\n    inputs.push({\n      id: 'functions' as PortId,\n      dataType: ['gpt-function[]', 'gpt-function'],\n      title: 'Functions',\n      coerced: true,\n      defaultValue: [],\n      description: 'A list of GPT functions enabled on the assistant.',\n      required: false,\n    });\n\n    if (data.useMetadataInput) {\n      inputs.push({\n        id: 'metadata' as PortId,\n        dataType: 'object',\n        title: 'Metadata',\n        coerced: true,\n        defaultValue: {},\n        description: 'Metadata to attach to the run.',\n        required: false,\n      });\n    }\n\n    return inputs;\n  },\n\n  getOutputDefinitions() {\n    return [\n      {\n        id: 'runId' as PortId,\n        dataType: 'string',\n        title: 'Run ID',\n        description: 'The ID of the run.',\n      },\n      {\n        id: 'run' as PortId,\n        dataType: 'object',\n        title: 'Run',\n        description: 'The full run object.',\n      },\n      {\n        id: 'steps' as PortId,\n        dataType: 'object[]',\n        title: 'Steps',\n        description: 'The list of steps for the run.',\n      },\n      {\n        id: 'last_step' as PortId,\n        dataType: 'object',\n        title: 'Last Step',\n        description: 'The last step for the run.',\n      },\n      {\n        id: 'messages' as PortId,\n        dataType: 'object[]',\n        title: 'Messages',\n        description: 'The list of messages for the thread.',\n      },\n      {\n        id: 'last_message' as PortId,\n        dataType: 'object',\n        title: 'Last Message',\n        description: 'The last message on the thread.',\n      },\n      {\n        id: 'last_assistant_messages' as PortId,\n        dataType: 'object[]',\n        title: 'Last Assistant Messages',\n        description: 'The last messages of type `assistant` for the thread.',\n      },\n    ];\n  },\n\n  getEditors(): EditorDefinition<RunThreadNode>[] {\n    return [\n      {\n        type: 'toggle',\n        dataKey: 'createThread',\n        label: 'Create New Thread',\n      },\n      {\n        type: 'string',\n        dataKey: 'threadId',\n        useInputToggleDataKey: 'useThreadIdInput',\n        label: 'Thread ID',\n        placeholder: 'Enter thread ID',\n        helperMessage: 'The ID of the thread to run.',\n        hideIf: (data) => data.createThread,\n      },\n      {\n        type: 'string',\n        dataKey: 'assistantId',\n        useInputToggleDataKey: 'useAssistantIdInput',\n        label: 'Assistant ID',\n        placeholder: 'Enter assistant ID',\n        helperMessage: 'The ID of the assistant to use. Required.',\n      },\n      {\n        type: 'dropdown',\n        dataKey: 'model',\n        useInputToggleDataKey: 'useModelInput',\n        label: 'Model',\n        options: [\n          {\n            label: 'Default',\n            value: '',\n          },\n          ...openAiModelOptions,\n        ],\n        defaultValue: '',\n        helperMessage: 'The GPT model to use for the run. If default, the model of the assistant will be used.',\n      },\n      {\n        type: 'code',\n        dataKey: 'instructions',\n        useInputToggleDataKey: 'useInstructionsInput',\n        label: 'Instructions',\n        language: 'markdown',\n        helperMessage:\n          'The instructions for the assistant to use for the run. If empty, the instructions of the assistant will be used.',\n      },\n      {\n        type: 'toggle',\n        dataKey: 'useCodeInterpreterTool',\n        label: 'Code Interpreter Tool Enabled',\n        helperMessage:\n          \"Note: Only enabled if functions are provided. Otherwise, the assistant's settings will be used.\",\n      },\n      {\n        type: 'toggle',\n        dataKey: 'useRetrievalTool',\n        label: 'Retrieval Tool Enabled',\n        helperMessage:\n          \"Note: Only enabled if functions are provided. Otherwise, the assistant's settings will be used.\",\n      },\n      {\n        type: 'custom',\n        customEditorId: 'ToolCallHandlers',\n        label: 'Tool Call Handlers',\n        dataKey: 'toolCallHandlers',\n        helperMessage:\n          'Handles for each function tool call that the assistant has access to. Make sure you provide a subgraph handler for every possible tool call that can be performed. A special `unknown` handler can be used as a fallback for unconfigured tool calls.',\n      },\n      {\n        type: 'keyValuePair',\n        dataKey: 'metadata',\n        useInputToggleDataKey: 'useMetadataInput',\n        label: 'Metadata',\n        keyPlaceholder: 'Key',\n        valuePlaceholder: 'Value',\n      },\n      {\n        type: 'graphSelector',\n        dataKey: 'onMessageCreationSubgraphId',\n        label: 'On Message Creation Subgraph',\n        helperMessage:\n          'A subgraph to run when a message is created. The message will be available as `input` or `message` in the subgraph.',\n      },\n    ];\n  },\n\n  getBody(data, context) {\n    let body = dedent`\n      Assistant ID: ${data.useAssistantIdInput ? '(Assistant ID From Input)' : data.assistantId}\n    `;\n\n    const additional: string[] = [];\n\n    if (data.createThread) {\n      additional.push('Create New Thread');\n    } else {\n      additional.push(`Thread ID: ${data.useThreadIdInput ? '(Thread ID From Input)' : data.threadId}`);\n    }\n\n    if (data.useModelInput || data.model) {\n      additional.push(`Model: ${data.useModelInput ? '(Model From Input)' : data.model}`);\n    }\n\n    if (data.useInstructionsInput || data.instructions?.trim()) {\n      additional.push(`Instructions: ${data.useInstructionsInput ? '(Instructions From Input)' : data.instructions}`);\n    }\n\n    if (data.useMetadataInput || data.metadata.length > 0) {\n      additional.push(\n        `Metadata: ${\n          data.useMetadataInput\n            ? '(Metadata From Input)'\n            : data.metadata.map(({ key, value }) => `${key}=${value}`).join(', ')\n        }`,\n      );\n    }\n\n    if (data.useCodeInterpreterTool) {\n      additional.push('Code Interpreter Tool Enabled');\n    }\n\n    if (data.useRetrievalTool) {\n      additional.push('Retrieval Tool Enabled');\n    }\n\n    if (data.toolCallHandlers.length > 0) {\n      additional.push('Tool Call Handlers:');\n\n      data.toolCallHandlers.forEach(({ key, value }) => {\n        const subgraphName = context.project.graphs[value]?.metadata!.name! ?? 'Unknown Subgraph';\n        additional.push(`    ${key || '(MISSING!)'} -> ${subgraphName}`);\n      });\n    }\n\n    if (data.onMessageCreationSubgraphId) {\n      const subgraphName =\n        context.project.graphs[data.onMessageCreationSubgraphId]?.metadata!.name! ?? 'Unknown Subgraph';\n      additional.push(`On Message Creation Subgraph: ${subgraphName}`);\n    }\n\n    body = `${body}\\n${additional.join('\\n')}`;\n\n    return body;\n  },\n\n  async process(data, inputData, context) {\n    const threadId = getInputOrData(data, inputData, 'threadId');\n    const assistantId = getInputOrData(data, inputData, 'assistantId');\n\n    let metadata = data.metadata.reduce(\n      (acc, { key, value }) => {\n        acc[key] = value;\n        return acc;\n      },\n      {} as Record<string, string>,\n    );\n    if (data.useMetadataInput && inputData['metadata' as PortId]) {\n      metadata = coerceTypeOptional(inputData['metadata' as PortId], 'object') as Record<string, string>;\n    }\n\n    const functionTools = coerceTypeOptional(inputData['functions' as PortId], 'gpt-function[]');\n    const tools = [...(functionTools?.map((f): OpenAIAssistantTool => ({ type: 'function', function: f })) ?? [])];\n\n    if (tools.length) {\n      if (data.useCodeInterpreterTool) {\n        tools.push({ type: 'code_interpreter' });\n      }\n      if (data.useRetrievalTool) {\n        tools.push({ type: 'retrieval' });\n      }\n    }\n\n    const requestBody: CreateRunBody = {\n      assistant_id: assistantId,\n      model: getInputOrData(data, inputData, 'model'),\n      instructions: getInputOrData(data, inputData, 'instructions'),\n      tools: tools.length > 0 ? tools : undefined,\n      metadata,\n    };\n\n    if (!context.settings.openAiKey) {\n      throw new Error('OpenAI key is not set.');\n    }\n\n    let response: Response;\n\n    const coerceToThreadMessage = (value: DataValue | undefined): CreateMessageBody | undefined => {\n      if (!value?.value) {\n        return undefined;\n      }\n\n      if (value.type === 'string' || typeof value.value === 'string') {\n        return { role: 'user', content: value.value as string };\n      }\n\n      if (typeof value.value === 'object') {\n        if (!('role' in value.value)) {\n          throw new Error('Invalid message format - missing role.');\n        }\n\n        if (value.value.role !== 'user') {\n          throw new Error('Only user messages are supported.');\n        }\n\n        return value.value as CreateMessageBody;\n      }\n\n      return { role: 'user', content: coerceTypeOptional(value, 'string') ?? '' };\n    };\n\n    if (data.createThread) {\n      const messagesInput = inputData['messages' as PortId];\n      const messages = messagesInput\n        ? arrayizeDataValue(unwrapDataValue(messagesInput)).map((message) => coerceToThreadMessage(message))\n        : [];\n\n      response = await fetch('https://api.openai.com/v1/threads/runs', {\n        method: 'POST',\n        headers: {\n          'OpenAI-Beta': 'assistants=v1',\n          'Content-Type': 'application/json',\n          Authorization: `Bearer ${context.settings.openAiKey}`,\n          'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n        },\n        body: JSON.stringify({\n          ...requestBody,\n          thread: {\n            messages,\n            // Thread metadata?\n          },\n        }),\n      });\n    } else {\n      response = await fetch(`https://api.openai.com/v1/threads/${threadId}/runs`, {\n        method: 'POST',\n        headers: {\n          'OpenAI-Beta': 'assistants=v1',\n          'Content-Type': 'application/json',\n          Authorization: `Bearer ${context.settings.openAiKey}`,\n          'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n        },\n        body: JSON.stringify(requestBody),\n      });\n    }\n\n    await handleOpenAIError(response);\n\n    const body = (await response.json()) as OpenAIRun;\n\n    const pollController = new AbortController();\n    const pollRunSteps = async (onNewStepCompleted: (step: OpenAIRunStep) => Promise<void>) => {\n      let lastCompletedAt = 0;\n\n      // On poll controller abort, continue so we get the final poll\n      const pollControllerAborted = new Promise((resolve) =>\n        pollController.signal.addEventListener('abort', () => resolve(undefined)),\n      );\n\n      // On main controller abort, reject\n      const mainGraphAborted = new Promise((_, reject) =>\n        context.signal.addEventListener('abort', () => reject(new Error('aborted'))),\n      );\n\n      while (!pollController.signal.aborted) {\n        // Delay at beginning because there won't be anything to start, and also this helps last poll get final data\n        await Promise.race([\n          // Poll frequency\n          new Promise((resolve) => setTimeout(resolve, POLL_FREQUENCY)),\n          pollControllerAborted,\n          mainGraphAborted,\n        ]);\n\n        const query = new URLSearchParams({\n          limit: '3',\n          order: 'desc',\n        } satisfies OpenAIPaginationQuery);\n\n        const url = `https://api.openai.com/v1/threads/${body.thread_id}/runs/${body.id}/steps?${query.toString()}`;\n        const response = await fetch(url, {\n          method: 'GET',\n          headers: {\n            'OpenAI-Beta': 'assistants=v1',\n            'Content-Type': 'application/json',\n            Authorization: `Bearer ${context.settings.openAiKey}`,\n            'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n          },\n        });\n\n        await handleOpenAIError(response);\n\n        const stepListBody = (await response.json()) as OpenAIListResponse<OpenAIRunStep>;\n\n        const newSteps = stepListBody.data.filter(\n          (step) => step.completed_at != null && step.completed_at > lastCompletedAt,\n        );\n\n        if (newSteps.length > 0) {\n          lastCompletedAt = newSteps[0]!.completed_at!;\n        }\n\n        for (const newStep of newSteps) {\n          await onNewStepCompleted(newStep);\n        }\n      }\n    };\n\n    const pollRunStepsPromise = data.onMessageCreationSubgraphId\n      ? pollRunSteps(async (step) => {\n          if (step.step_details.type !== 'message_creation') {\n            return;\n          }\n\n          const messageId = step.step_details.message_creation.message_id;\n\n          const messageResponse = await fetch(\n            `https://api.openai.com/v1/threads/${body.thread_id}/messages/${messageId}`,\n            {\n              method: 'GET',\n              headers: {\n                'OpenAI-Beta': 'assistants=v1',\n                'Content-Type': 'application/json',\n                Authorization: `Bearer ${context.settings.openAiKey}`,\n                'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n              },\n            },\n          );\n\n          await handleOpenAIError(messageResponse);\n\n          const messageBody = (await messageResponse.json()) as OpenAIThreadMessage;\n\n          const inputs: GraphInputs = {\n            input: {\n              type: 'object[]',\n              value: messageBody.content,\n            },\n            message: {\n              type: 'object',\n              value: messageBody,\n            },\n            message_id: {\n              type: 'string',\n              value: messageBody.id,\n            },\n            thread_id: {\n              type: 'string',\n              value: messageBody.thread_id,\n            },\n          };\n\n          const subprocessor = context.createSubProcessor(data.onMessageCreationSubgraphId!, {\n            signal: context.signal,\n          });\n\n          await subprocessor.processGraph(context, inputs, context.contextValues);\n        })\n      : Promise.resolve();\n\n    let latestBody = body;\n\n    try {\n      while (\n        latestBody.status === 'in_progress' ||\n        latestBody.status === 'queued' ||\n        latestBody.status === 'requires_action'\n      ) {\n        const runResponse = await fetch(`https://api.openai.com/v1/threads/${body.thread_id}/runs/${body.id}`, {\n          method: 'GET',\n          headers: {\n            'OpenAI-Beta': 'assistants=v1',\n            'Content-Type': 'application/json',\n            Authorization: `Bearer ${context.settings.openAiKey}`,\n            'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n          },\n        });\n\n        await handleOpenAIError(runResponse);\n\n        latestBody = (await runResponse.json()) as OpenAIRun;\n\n        // Requires action, start calling subgraphs\n        if (latestBody.status === 'requires_action') {\n          const toolCalls = latestBody.required_action!.submit_tool_outputs.tool_calls;\n\n          /** Run one subgraph per tool call requested */\n          const toolCallOutputs = await Promise.all(\n            toolCalls.map(async (toolCall) => {\n              let inputArguments: Record<string, any> = {};\n              try {\n                inputArguments = JSON.parse(toolCall.function.arguments);\n              } catch (err) {\n                // Ignore\n              }\n\n              const inputs: Record<string, DataValue> = {\n                run_id: {\n                  type: 'string',\n                  value: latestBody.id,\n                },\n                run: {\n                  type: 'object',\n                  value: latestBody,\n                },\n                tool_call_id: {\n                  type: 'string',\n                  value: toolCall.id,\n                },\n                name: {\n                  type: 'string',\n                  value: toolCall.function.name,\n                },\n                arguments: {\n                  type: 'object',\n                  value: inputArguments,\n                },\n                input: {\n                  type: 'object',\n                  value: inputArguments,\n                },\n              };\n\n              let handlerSubgraphId = data.toolCallHandlers.find(({ key }) => key === toolCall.function.name)?.value;\n\n              // Fall back to \"unknown\" if it's present\n              if (!handlerSubgraphId) {\n                handlerSubgraphId = data.toolCallHandlers.find(({ key }) => key === 'unknown')?.value;\n              }\n\n              if (!handlerSubgraphId) {\n                throw new Error(`No handler found for tool call: ${toolCall.function.name}`);\n              }\n\n              const subprocessor = context.createSubProcessor(handlerSubgraphId, { signal: context.signal });\n\n              const outputs = await subprocessor.processGraph(context, inputs, context.contextValues);\n\n              const outputString = coerceTypeOptional(outputs.output, 'string');\n\n              return outputString ?? '';\n            }),\n          );\n\n          /** Collect all the subgraph outputs, then submit them. All outputs must be submitted in a single request, per documentation. */\n          const mappedToolCallOuptuts = toolCalls.map((toolCall, i) => ({\n            tool_call_id: toolCall.id,\n            output: toolCallOutputs[i],\n          }));\n\n          const submitResponse = await fetch(\n            `https://api.openai.com/v1/threads/${body.thread_id}/runs/${body.id}/submit_tool_outputs`,\n            {\n              method: 'POST',\n              headers: {\n                'OpenAI-Beta': 'assistants=v1',\n                'Content-Type': 'application/json',\n                Authorization: `Bearer ${context.settings.openAiKey}`,\n                'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n              },\n              body: JSON.stringify({\n                tool_outputs: mappedToolCallOuptuts,\n              }),\n            },\n          );\n\n          await handleOpenAIError(submitResponse);\n        }\n\n        await Promise.race([\n          new Promise((resolve) => setTimeout(resolve, POLL_FREQUENCY)),\n          new Promise((_, reject) => context.signal.addEventListener('abort', () => reject(new Error('aborted')))),\n        ]);\n      }\n\n      if (\n        latestBody.status === 'cancelled' ||\n        latestBody.status === 'cancelling' ||\n        latestBody.status === 'expired' ||\n        latestBody.status === 'failed'\n      ) {\n        throw new Error(`Run failed with status: ${latestBody.status}`);\n      }\n\n      const listStepsQuery = new URLSearchParams({\n        limit: '20',\n        order: 'desc',\n      });\n\n      const listStepsResponsePromise = await fetch(\n        `https://api.openai.com/v1/threads/${body.thread_id}/runs/${body.id}/steps?${listStepsQuery.toString()}`,\n        {\n          method: 'GET',\n          headers: {\n            'OpenAI-Beta': 'assistants=v1',\n            'Content-Type': 'application/json',\n            Authorization: `Bearer ${context.settings.openAiKey}`,\n            'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n          },\n        },\n      );\n\n      const getMessagesQuery = new URLSearchParams({\n        limit: '20',\n        order: 'desc',\n      } satisfies OpenAIPaginationQuery);\n\n      const messagesResponsePromise = await fetch(\n        `https://api.openai.com/v1/threads/${body.thread_id}/messages?${getMessagesQuery.toString()}`,\n        {\n          method: 'GET',\n          headers: {\n            'OpenAI-Beta': 'assistants=v1',\n            'Content-Type': 'application/json',\n            Authorization: `Bearer ${context.settings.openAiKey}`,\n            'OpenAI-Organization': context.settings.openAiOrganization ?? '',\n          },\n        },\n      );\n\n      const [listStepsResponse, messagesResponse] = await Promise.all([\n        listStepsResponsePromise,\n        messagesResponsePromise,\n      ]);\n\n      await handleOpenAIError(listStepsResponse);\n      await handleOpenAIError(messagesResponse);\n\n      const listStepsBody = (await listStepsResponse.json()) as OpenAIListResponse<OpenAIRunStep>;\n      const messagesForThread = (await messagesResponse.json()) as OpenAIListResponse<OpenAIThreadMessage>;\n\n      const lastUserMessageIndex = messagesForThread.data.findIndex((message) => message.role === 'user');\n      const lastAssistantMessages = messagesForThread.data.slice(0, lastUserMessageIndex);\n\n      return {\n        ['runId' as PortId]: {\n          type: 'string',\n          value: latestBody.id,\n        },\n        ['run' as PortId]: {\n          type: 'object',\n          value: latestBody,\n        },\n        ['steps' as PortId]: {\n          type: 'object[]',\n          value: listStepsBody.data,\n        },\n        ['last_step' as PortId]: {\n          type: 'object',\n          value: listStepsBody.data[0]!,\n        },\n        ['messages' as PortId]: {\n          type: 'object[]',\n          value: messagesForThread.data,\n        },\n        ['last_message' as PortId]: {\n          type: 'object',\n          value: messagesForThread.data[0]!,\n        },\n        ['last_assistant_messages' as PortId]: {\n          type: 'object[]',\n          value: lastAssistantMessages,\n        },\n      };\n    } finally {\n      pollController.abort();\n      await pollRunStepsPromise;\n    }\n  },\n};\n\nexport const runThreadNode = pluginNodeDefinition(RunThreadNodeImpl, 'Run Thread');\n", "import {\n  type ChartNode,\n  type NodeId,\n  type NodeInputDefinition,\n  type PortId,\n  type EditorDefinition,\n  type PluginNodeImpl,\n} from '../../../index.js';\nimport { newId, coerceTypeOptional, getInputOrData, coerceType } from '../../../utils/index.js';\nimport { interpolate } from '../../../utils/interpolation.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport type { CreateMessageBody } from '../../../utils/openai.js';\nimport { mapValues } from 'lodash-es';\n\nexport type ThreadMessageNode = ChartNode<'threadMessage', ThreadMessageNodeData>;\n\nexport type ThreadMessageNodeData = {\n  text: string;\n\n  fileIds?: string[];\n  useFileIdsInput?: boolean;\n\n  metadata: { key: string; value: string }[];\n  useMetadataInput?: boolean;\n};\n\nexport const ThreadMessageNodeImpl: PluginNodeImpl<ThreadMessageNode> = {\n  create() {\n    return {\n      id: newId<NodeId>(),\n      type: 'threadMessage',\n      data: {\n        text: '{{input}}',\n        fileIds: [],\n        useFileIdsInput: false,\n        metadata: [],\n        useMetadataInput: false,\n      },\n      title: 'Thread Message',\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 225,\n      },\n    };\n  },\n\n  getUIData() {\n    return {\n      group: 'OpenAI',\n      contextMenuTitle: 'Thread Message',\n      infoBoxTitle: 'Thread Message Node',\n      infoBoxBody: 'Create a new message for a thread.',\n    };\n  },\n\n  getInputDefinitions(data) {\n    let inputs: NodeInputDefinition[] = [];\n\n    if (data.useFileIdsInput) {\n      inputs.push({\n        id: 'fileIds' as PortId,\n        dataType: 'string[]',\n        title: 'File IDs',\n        coerced: true,\n        defaultValue: [],\n        description: 'The IDs of the files to attach to the message.',\n        required: false,\n      });\n    }\n\n    if (data.useMetadataInput) {\n      inputs.push({\n        id: 'metadata' as PortId,\n        dataType: 'object',\n        title: 'Metadata',\n        coerced: true,\n        defaultValue: {},\n        description: 'Metadata to attach to the message.',\n        required: false,\n      });\n    }\n\n    // Extract inputs from promptText, everything like {{input}}\n    const inputNames = [...new Set(data.text.match(/\\{\\{([^}]+)\\}\\}/g))];\n    inputs = [\n      ...inputs,\n      ...(inputNames?.map((inputName): NodeInputDefinition => {\n        return {\n          // id and title should not have the {{ and }}\n          id: inputName.slice(2, -2) as PortId,\n          title: inputName.slice(2, -2),\n          dataType: 'string',\n          required: false,\n        };\n      }) ?? []),\n    ];\n\n    return inputs;\n  },\n\n  getOutputDefinitions() {\n    return [\n      {\n        id: 'message' as PortId,\n        dataType: 'object',\n        title: 'Message',\n        description: 'The created message.',\n      },\n    ];\n  },\n\n  getEditors(): EditorDefinition<ThreadMessageNode>[] {\n    return [\n      {\n        type: 'code',\n        label: 'Text',\n        dataKey: 'text',\n        language: 'prompt-interpolation-markdown',\n        theme: 'prompt-interpolation',\n      },\n      {\n        type: 'keyValuePair',\n        dataKey: 'metadata',\n        useInputToggleDataKey: 'useMetadataInput',\n        label: 'Metadata',\n        keyPlaceholder: 'Key',\n        valuePlaceholder: 'Value',\n      },\n      {\n        type: 'stringList',\n        dataKey: 'fileIds',\n        useInputToggleDataKey: 'useFileIdsInput',\n        label: 'File IDs',\n        placeholder: 'File ID',\n      },\n    ];\n  },\n\n  getBody(data) {\n    return {\n      type: 'colorized',\n      text: data.text.split('\\n').slice(0, 15).join('\\n').trim(),\n      language: 'prompt-interpolation-markdown',\n      theme: 'prompt-interpolation',\n    };\n  },\n\n  async process(data, inputData) {\n    const text = getInputOrData(data, inputData, 'text', 'string');\n    const fileIds = getInputOrData(data, inputData, 'fileIds', 'string[]') ?? [];\n\n    let metadata: Record<string, string> = data.metadata.reduce(\n      (acc, { key, value }) => {\n        acc[key] = value;\n        return acc;\n      },\n      {} as Record<string, string>,\n    );\n\n    if (data.useMetadataInput && inputData['metadata' as PortId]) {\n      metadata = coerceTypeOptional(inputData['metadata' as PortId], 'object') as Record<string, string>;\n    }\n\n    const inputMap = mapValues(inputData, (input) => coerceType(input, 'string')) as Record<PortId, string>;\n    const interpolated = interpolate(text, inputMap);\n\n    // Here you would typically make a call to an API to create the message\n    // For the sake of this example, we'll just return the data as is\n\n    return {\n      ['message' as PortId]: {\n        type: 'object',\n        value: {\n          role: 'user',\n          content: interpolated,\n          file_ids: fileIds,\n          metadata,\n        } satisfies CreateMessageBody,\n      },\n    };\n  },\n};\n\nexport const threadMessageNode = pluginNodeDefinition(ThreadMessageNodeImpl, 'Thread Message');\n", "import { type RivetPlugin } from '../../index.js';\nimport { createThreadNode } from './nodes/CreateThreadNode.js';\nimport { getThreadNode } from './nodes/GetThreadNode.js';\nimport { deleteThreadNode } from './nodes/DeleteThreadNode.js';\nimport { createAssistantNode } from './nodes/CreateAssistantNode.js';\nimport { getAssistantNode } from './nodes/GetAssistantNode.js';\nimport { listAssistantsNode } from './nodes/ListAssistantsNode.js';\nimport { deleteAssistantNode } from './nodes/DeleteAssistantNode.js';\nimport { uploadFileNode } from './nodes/UploadFileNode.js';\nimport { listOpenAIFilesNode } from './nodes/ListOpenAIFilesNode.js';\nimport { getOpenAIFileNode } from './nodes/GetOpenAIFileNode.js';\nimport { attachAssistantFileNode } from './nodes/AttachAssistantFileNode.js';\nimport { createThreadMessageNode } from './nodes/CreateThreadMessageNode.js';\nimport { listThreadMessagesNode } from './nodes/ListThreadMessagesNode.js';\nimport { runThreadNode } from './nodes/RunThreadNode.js';\nimport { threadMessageNode } from './nodes/ThreadMessageNode.js';\n\nexport const openAIPlugin: RivetPlugin = {\n  id: 'openai',\n  name: 'OpenAI',\n\n  configSpec: {},\n\n  contextMenuGroups: [\n    {\n      id: 'openai',\n      label: 'OpenAI',\n    },\n  ],\n\n  register(register) {\n    register(createThreadNode);\n    register(getThreadNode);\n    register(deleteThreadNode);\n    register(createAssistantNode);\n    register(getAssistantNode);\n    register(listAssistantsNode);\n    register(deleteAssistantNode);\n    register(uploadFileNode);\n    register(listOpenAIFilesNode);\n    register(getOpenAIFileNode);\n    register(attachAssistantFileNode);\n    register(createThreadMessageNode);\n    register(listThreadMessagesNode);\n    register(runThreadNode);\n    register(threadMessageNode);\n  },\n};\n", "import { type Content, type FunctionCall, type Tool } from '@google/genai';\n\nexport type GoogleModelDeprecated = {\n  maxTokens: number;\n  cost: {\n    prompt: number;\n    completion: number;\n  };\n  displayName: string;\n};\n\nexport const googleModelsDeprecated = {\n  'gemini-pro': {\n    maxTokens: 32760,\n    cost: {\n      prompt: NaN,\n      completion: NaN,\n    },\n    displayName: 'Gemini Pro',\n  },\n  'gemini-pro-vision': {\n    maxTokens: 16384,\n    cost: {\n      prompt: NaN,\n      completion: NaN,\n    },\n    displayName: 'Gemini Pro Vision',\n  },\n} satisfies Record<string, GoogleModelDeprecated>;\n\nexport type GoogleModelsDeprecated = keyof typeof googleModelsDeprecated;\n\nexport const generativeAiGoogleModels = {\n  'gemini-2.5-flash-preview-04-17': {\n    maxTokens: 1048576,\n    cost: {\n      prompt: 0.15 / 1000,\n      completion: 0.6 / 1000,\n    },\n    displayName: 'Gemini 2.5 Flash Preview',\n  },\n  'gemini-2.0-flash-001': {\n    maxTokens: 1048576,\n    cost: {\n      prompt: 0.1 / 1000,\n      completion: 0.4 / 1000,\n    },\n    displayName: 'Gemini 2.0 Flash',\n  },\n  'gemini-2.0-pro-exp-02-05': {\n    maxTokens: 2097152,\n    cost: {\n      prompt: 0, // Unknown\n      completion: 0, // Unknown\n    },\n    displayName: 'Gemini 2.0 Pro',\n  },\n  'gemini-2.5-pro-exp-03-25': {\n    maxTokens: 1000000,\n    cost: {\n      prompt: 0, // Unknown\n      completion: 0, // Unknown\n    },\n    displayName: 'Gemini 2.5 Pro Experimental',\n  },\n  'gemini-2.0-flash-lite-preview-02-05': {\n    maxTokens: 1048576,\n    cost: {\n      prompt: 0.075 / 1000,\n      completion: 0.3 / 1000,\n    },\n    displayName: 'Gemini 2.0 Flash Lite',\n  },\n  'gemini-2.0-flash-thinking-exp-01-21': {\n    maxTokens: 1048576,\n    cost: {\n      prompt: 0, // Unknown\n      completion: 0, // Unknown\n    },\n    displayName: 'Gemini 2.0 Flash Thinking',\n  },\n  'gemini-1.5-flash': {\n    maxTokens: 1048576,\n    cost: {\n      prompt: 0, // It's per-character wtf\n      completion: 0, // It's per-character\n    },\n    displayName: 'Gemini 1.5 Flash',\n  },\n  'gemini-1.5-pro': {\n    maxTokens: 2097152,\n    cost: {\n      prompt: 0, // It's per-character wtf\n      completion: 0, // It's per-character\n    },\n    displayName: 'Gemini 1.5 Pro',\n  },\n  'gemini-1.0-pro': {\n    maxTokens: 32760,\n    cost: {\n      prompt: 0, // It's per-character wtf\n      completion: 0, // 1It's per-character\n    },\n    displayName: 'Gemini 1.0 Pro',\n  },\n  'gemini-1.0-pro-vision': {\n    maxTokens: 16384,\n    cost: {\n      prompt: 0, // It's per-character wtf\n      completion: 0, // It's per-character\n    },\n    displayName: 'Gemini 1.0 Pro Vision',\n  },\n};\n\nexport type GenerativeAiGoogleModel = keyof typeof generativeAiGoogleModels;\n\nexport const googleModelOptionsDeprecated = Object.entries(googleModelsDeprecated).map(([id, { displayName }]) => ({\n  value: id,\n  label: displayName,\n}));\n\nexport const generativeAiOptions = Object.entries(generativeAiGoogleModels).map(([id, { displayName }]) => ({\n  value: id,\n  label: displayName,\n}));\n\nexport type ChatCompletionOptions = {\n  project: string;\n  location: string;\n  applicationCredentials: string;\n  model: GoogleModelsDeprecated;\n  prompt: Content[];\n  max_output_tokens: number;\n  temperature?: number;\n  top_p?: number;\n  top_k?: number;\n  signal?: AbortSignal;\n};\n\nexport type ChatCompletionChunk = {\n  completion?: string;\n  function_calls?: FunctionCall[];\n  finish_reason:\n    | 'FINISH_REASON_UNSPECIFIED'\n    | 'FINISH_REASON_STOP'\n    | 'FINISH_REASON_MAX_TOKENS'\n    | 'FINISH_REASON_SAFETY'\n    | 'FINISH_REASON_RECITATION'\n    | 'FINISH_REASON_OTHER'\n    | undefined;\n  model: string;\n};\n\nexport type StreamGenerativeAiOptions = {\n  apiKey: string;\n  model: GenerativeAiGoogleModel;\n  systemPrompt: string | undefined;\n  prompt: Content[];\n  maxOutputTokens: number;\n  temperature: number | undefined;\n  topP: number | undefined;\n  topK: number | undefined;\n  signal?: AbortSignal;\n  tools: Tool[] | undefined;\n  thinkingBudget?: number;\n  additionalHeaders?: Record<string, string>;\n};\n\nexport async function* streamGenerativeAi({\n  apiKey,\n  model,\n  systemPrompt,\n  prompt,\n  maxOutputTokens,\n  temperature,\n  topP,\n  topK,\n  signal,\n  tools,\n  thinkingBudget,\n  additionalHeaders,\n}: StreamGenerativeAiOptions): AsyncGenerator<ChatCompletionChunk> {\n  const { GoogleGenAI } = await import('@google/genai');\n  const genAi = new GoogleGenAI({ apiKey });\n\n  const result = await genAi.models.generateContentStream({\n    model,\n    contents: prompt,\n    config: {\n      systemInstruction: systemPrompt,\n      maxOutputTokens,\n      temperature,\n      topP,\n      topK,\n      tools,\n      abortSignal: signal,\n      thinkingConfig: {\n        thinkingBudget,\n      },\n      httpOptions: {\n        headers: {\n          ...additionalHeaders,\n        },\n      },\n    },\n  });\n\n  for await (const chunk of result) {\n    const outChunk: ChatCompletionChunk = {\n      completion: undefined,\n      finish_reason: undefined,\n      function_calls: undefined,\n      model,\n    };\n\n    const functionCalls = chunk.functionCalls;\n    if (functionCalls) {\n      outChunk.function_calls = functionCalls;\n    }\n\n    if (chunk.candidates) {\n      outChunk.completion = chunk.candidates[0]?.content?.parts?.[0]?.text;\n      outChunk.finish_reason = chunk.candidates[0]?.finishReason as any;\n    }\n\n    if (outChunk.completion || outChunk.function_calls) {\n      yield outChunk;\n    }\n  }\n}\n\nexport async function* streamChatCompletions({\n  project,\n  location,\n  applicationCredentials,\n  model,\n  signal,\n  max_output_tokens,\n  temperature,\n  top_p,\n  top_k,\n  prompt,\n}: ChatCompletionOptions): AsyncGenerator<ChatCompletionChunk> {\n  // If you import normally, the Google auth library throws a fit.\n  const { VertexAI } = await import('@google-cloud/vertexai');\n\n  // Can't find a way to pass the credentials path in\n  process.env.GOOGLE_APPLICATION_CREDENTIALS = applicationCredentials;\n  const vertexAi = new VertexAI({ project, location });\n  const generativeModel = vertexAi.preview.getGenerativeModel({\n    model,\n    generation_config: {\n      max_output_tokens,\n      temperature,\n      top_p,\n      top_k,\n    },\n  });\n  const response = await generativeModel.generateContentStream({\n    contents: prompt as any, // crazy type stuff but... this is good enough, this is legacy\n  });\n\n  let hadChunks = false;\n\n  for await (const chunk of response.stream) {\n    hadChunks = true;\n\n    if (!signal?.aborted && chunk.candidates[0]?.content.parts[0]?.text) {\n      yield {\n        completion: chunk.candidates[0]?.content.parts[0]?.text,\n        finish_reason: chunk.candidates[0]?.finishReason as any,\n        model,\n      };\n    } else {\n      return;\n    }\n  }\n\n  if (!hadChunks) {\n    throw new Error(`No chunks received.`);\n  }\n}\n", "import {\n  type ChartNode,\n  type ChatMessage,\n  type EditorDefinition,\n  type Inputs,\n  type InternalProcessContext,\n  type NodeId,\n  type NodeInputDefinition,\n  type NodeOutputDefinition,\n  type NodeUIData,\n  type Outputs,\n  type PluginNodeImpl,\n  type PortId,\n  type ScalarDataValue,\n} from '../../../index.js';\nimport {\n  streamChatCompletions,\n  streamGenerativeAi,\n  type GenerativeAiGoogleModel,\n  generativeAiGoogleModels,\n  type StreamGenerativeAiOptions,\n  type ChatCompletionChunk,\n  type GoogleModelsDeprecated,\n  generativeAiOptions,\n} from '../google.js';\nimport { nanoid } from 'nanoid/non-secure';\nimport { dedent } from 'ts-dedent';\nimport retry from 'p-retry';\nimport { match } from 'ts-pattern';\nimport { coerceType, coerceTypeOptional } from '../../../utils/coerceType.js';\nimport { addWarning } from '../../../utils/outputs.js';\nimport { getError } from '../../../utils/errors.js';\nimport { uint8ArrayToBase64 } from '../../../utils/base64.js';\nimport { pluginNodeDefinition } from '../../../model/NodeDefinition.js';\nimport { getScalarTypeOf, isArrayDataValue } from '../../../model/DataValue.js';\nimport type { TokenizerCallInfo } from '../../../integrations/Tokenizer.js';\nimport { getInputOrData, cleanHeaders } from '../../../utils/inputs.js';\nimport { type Content, type FunctionDeclaration, type Part, type Tool, type FunctionCall, Type } from '@google/genai';\nimport { mapValues } from 'lodash-es';\n\nexport type ChatGoogleNode = ChartNode<'chatGoogle', ChatGoogleNodeData>;\n\nexport type ChatGoogleNodeConfigData = {\n  model: GenerativeAiGoogleModel;\n  temperature: number;\n  useTopP: boolean;\n  top_p?: number;\n  top_k?: number;\n  maxTokens: number;\n  thinkingBudget: number | undefined;\n  headers?: { key: string; value: string }[];\n};\n\nexport type ChatGoogleNodeData = ChatGoogleNodeConfigData & {\n  useModelInput: boolean;\n  useTemperatureInput: boolean;\n  useTopPInput: boolean;\n  useTopKInput: boolean;\n  useUseTopPInput: boolean;\n  useMaxTokensInput: boolean;\n  useToolCalling: boolean;\n  useThinkingBudgetInput: boolean;\n  useHeadersInput?: boolean;\n\n  /** Given the same set of inputs, return the same output without hitting GPT */\n  cache: boolean;\n\n  useAsGraphPartialOutput?: boolean;\n};\n\n// Temporary\nconst cache = new Map<string, Outputs>();\n\nexport const ChatGoogleNodeImpl: PluginNodeImpl<ChatGoogleNode> = {\n  create(): ChatGoogleNode {\n    const chartNode: ChatGoogleNode = {\n      type: 'chatGoogle',\n      title: 'Chat (Google)',\n      id: nanoid() as NodeId,\n      visualData: {\n        x: 0,\n        y: 0,\n        width: 275,\n      },\n      data: {\n        model: 'gemini-2.5-flash-preview-04-17',\n        useModelInput: false,\n\n        temperature: 0.5,\n        useTemperatureInput: false,\n\n        top_p: 1,\n        useTopPInput: false,\n\n        top_k: undefined,\n        useTopKInput: false,\n\n        useTopP: false,\n        useUseTopPInput: false,\n\n        maxTokens: 1024,\n        useMaxTokensInput: false,\n\n        cache: false,\n        useAsGraphPartialOutput: true,\n\n        useToolCalling: false,\n\n        thinkingBudget: undefined,\n        useThinkingBudgetInput: false,\n      },\n    };\n\n    return chartNode;\n  },\n\n  getInputDefinitions(data): NodeInputDefinition[] {\n    const inputs: NodeInputDefinition[] = [];\n\n    inputs.push({\n      id: 'systemPrompt' as PortId,\n      title: 'System Prompt',\n      dataType: 'string',\n      required: false,\n      description: 'An optional system prompt for the model to use.',\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        dataType: 'number',\n        id: 'temperature' as PortId,\n        title: 'Temperature',\n      });\n    }\n\n    if (data.useTopPInput) {\n      inputs.push({\n        dataType: 'number',\n        id: 'top_p' as PortId,\n        title: 'Top P',\n      });\n    }\n\n    if (data.useUseTopPInput) {\n      inputs.push({\n        dataType: 'boolean',\n        id: 'useTopP' as PortId,\n        title: 'Use Top P',\n      });\n    }\n\n    if (data.useMaxTokensInput) {\n      inputs.push({\n        dataType: 'number',\n        id: 'maxTokens' as PortId,\n        title: 'Max Tokens',\n      });\n    }\n\n    if (data.useToolCalling) {\n      inputs.push({\n        dataType: 'gpt-function[]',\n        id: 'functions' as PortId,\n        title: 'Tools',\n        description: 'Tools available for the model to call.',\n      });\n    }\n\n    if (data.useThinkingBudgetInput) {\n      inputs.push({\n        dataType: 'number',\n        id: 'thinkingBudget' as PortId,\n        title: 'Thinking Budget',\n        description: 'The token budget for the model to think before responding.',\n      });\n    }\n\n    inputs.push({\n      dataType: ['chat-message', 'chat-message[]'] as const,\n      id: 'prompt' as PortId,\n      title: 'Prompt',\n    });\n\n    if (data.useHeadersInput) {\n      inputs.push({\n        dataType: 'object',\n        id: 'headers' as PortId,\n        title: 'Headers',\n        description: 'Additional headers to send to the API.',\n      });\n    }\n\n    return inputs;\n  },\n\n  getOutputDefinitions(data): NodeOutputDefinition[] {\n    const outputs: NodeOutputDefinition[] = [];\n\n    outputs.push({\n      dataType: 'string',\n      id: 'response' as PortId,\n      title: 'Response',\n    });\n\n    outputs.push({\n      dataType: 'chat-message[]',\n      id: 'in-messages' as PortId,\n      title: 'Messages Sent',\n      description: 'All messages sent to the model.',\n    });\n\n    outputs.push({\n      dataType: 'chat-message[]',\n      id: 'all-messages' as PortId,\n      title: 'All Messages',\n      description: 'All messages, with the response appended.',\n    });\n\n    if (data.useToolCalling) {\n      outputs.push({\n        dataType: 'object[]',\n        id: 'function-calls' as PortId,\n        title: 'Tool Calls',\n        description: 'Tool calls made by the model.',\n      });\n    }\n\n    return outputs;\n  },\n\n  getBody(data): string {\n    return dedent`\n      ${generativeAiGoogleModels[data.model]?.displayName ?? `Google (${data.model})`}\n      ${\n        data.useTopP\n          ? `Top P: ${data.useTopPInput ? '(Using Input)' : data.top_p}`\n          : `Temperature: ${data.useTemperatureInput ? '(Using Input)' : data.temperature}`\n      }\n      Max Tokens: ${data.maxTokens}\n      Thinking Budget: ${data.thinkingBudget ?? 'Automatic'}\n    `;\n  },\n\n  getEditors(): EditorDefinition<ChatGoogleNode>[] {\n    return [\n      {\n        type: 'dropdown',\n        label: 'Model',\n        dataKey: 'model',\n        useInputToggleDataKey: 'useModelInput',\n        options: generativeAiOptions,\n      },\n      {\n        type: 'number',\n        label: 'Temperature',\n        dataKey: 'temperature',\n        useInputToggleDataKey: 'useTemperatureInput',\n        min: 0,\n        max: 2,\n        step: 0.1,\n      },\n      {\n        type: 'number',\n        label: 'Top P',\n        dataKey: 'top_p',\n        useInputToggleDataKey: 'useTopPInput',\n        min: 0,\n        max: 1,\n        step: 0.1,\n      },\n      {\n        type: 'toggle',\n        label: 'Use Top P',\n        dataKey: 'useTopP',\n        useInputToggleDataKey: 'useUseTopPInput',\n      },\n      {\n        type: 'number',\n        label: 'Max Tokens',\n        dataKey: 'maxTokens',\n        useInputToggleDataKey: 'useMaxTokensInput',\n        min: 0,\n        max: Number.MAX_SAFE_INTEGER,\n        step: 1,\n      },\n      {\n        type: 'number',\n        label: 'Thinking Budget',\n        dataKey: 'thinkingBudget',\n        allowEmpty: true,\n        step: 1,\n        min: 0,\n        max: Number.MAX_SAFE_INTEGER,\n        useInputToggleDataKey: 'useThinkingBudgetInput',\n        helperMessage: 'The token budget for the model to think before responding. Leave blank for automatic budget.',\n      },\n      {\n        type: 'toggle',\n        label: 'Enable Tool Calling',\n        dataKey: 'useToolCalling',\n      },\n      {\n        type: 'toggle',\n        label: 'Cache (same inputs, same outputs)',\n        dataKey: 'cache',\n      },\n      {\n        type: 'toggle',\n        label: 'Use for subgraph partial output',\n        dataKey: 'useAsGraphPartialOutput',\n      },\n      {\n        type: 'keyValuePair',\n        label: 'Headers',\n        dataKey: 'headers',\n        useInputToggleDataKey: 'useHeadersInput',\n        keyPlaceholder: 'Header',\n        helperMessage: 'Additional headers to send to the API.',\n      },\n    ];\n  },\n\n  getUIData(): NodeUIData {\n    return {\n      infoBoxBody: dedent`\n        Makes a call to an Google chat model. The settings contains many options for tweaking the model's behavior.\n      `,\n      infoBoxTitle: 'Chat (Google) Node',\n      contextMenuTitle: 'Chat (Google)',\n      group: ['AI'],\n    };\n  },\n\n  async process(data, inputs: Inputs, context: InternalProcessContext): Promise<Outputs> {\n    const output: Outputs = {};\n\n    const systemPrompt = coerceTypeOptional(inputs['systemPrompt' as PortId], 'string');\n\n    const rawModel = getInputOrData(data, inputs, 'model');\n    const model = rawModel as GenerativeAiGoogleModel;\n\n    const temperature = getInputOrData(data, inputs, 'temperature', 'number');\n    const topP = getInputOrData(data, inputs, 'top_p', 'number');\n    const useTopP = getInputOrData(data, inputs, 'useTopP', 'boolean');\n    const thinkingBudget = getInputOrData(data, inputs, 'thinkingBudget', 'number');\n\n    const { messages } = getChatGoogleNodeMessages(inputs);\n\n    let prompt = await Promise.all(\n      messages.map(async (message): Promise<Content> => {\n        if (message.type === 'user' || message.type === 'assistant') {\n          const parts = await Promise.all(\n            [message.message].flat().map(async (part): Promise<Part> => {\n              if (typeof part === 'string') {\n                return { text: part };\n              } else if (part.type === 'image') {\n                return {\n                  inlineData: {\n                    mimeType: part.mediaType,\n                    data: (await uint8ArrayToBase64(part.data))!,\n                  },\n                };\n              } else {\n                throw new Error(`Google Vertex AI does not support message parts of type ${part.type}`);\n              }\n            }),\n          );\n\n          if (message.type === 'assistant' && (message.function_calls?.length ?? 0) > 0) {\n            if (parts[0]!.text === '') {\n              parts.shift(); // remove empty text part\n            }\n\n            for (const call of message.function_calls ?? []) {\n              parts.push({\n                functionCall: {\n                  name: call.name,\n                  args: JSON.parse(call.arguments),\n                },\n              });\n            }\n          }\n\n          return {\n            role: match(message.type)\n              .with('user', () => 'user')\n              .with('assistant', () => 'model')\n              .exhaustive(),\n            parts,\n          };\n        }\n\n        if (message.type === 'function') {\n          return {\n            role: 'function',\n            parts: [\n              {\n                functionResponse: {\n                  name: message.name,\n                  response: {\n                    result: typeof message.message === 'string' ? message.message : '',\n                  },\n                },\n              },\n            ],\n          };\n        }\n\n        throw new Error(`Google Vertex AI does not support message type ${message.type}`);\n      }),\n    );\n\n    // Collapse sequential function responses into a single function response with mutliple parts\n    prompt = prompt.reduce((acc: Content[], message) => {\n      const lastMessage = acc.at(-1);\n\n      // Shouldn't be undefined but not sure if this is where the crash is happening...\n      if (\n        lastMessage &&\n        message.role === 'function' &&\n        lastMessage.role === 'function' &&\n        lastMessage?.parts &&\n        message.parts\n      ) {\n        lastMessage.parts.push(...message.parts);\n      } else {\n        acc.push(message);\n      }\n\n      return acc;\n    }, [] as Content[]);\n\n    let { maxTokens } = data;\n\n    const tokenizerInfo: TokenizerCallInfo = {\n      node: context.node,\n      model,\n      endpoint: undefined,\n    };\n\n    // TODO Better token counting for Google models.\n    const tokenCount = await context.tokenizer.getTokenCountForMessages(messages, undefined, tokenizerInfo);\n\n    if (generativeAiGoogleModels[model] && tokenCount >= generativeAiGoogleModels[model].maxTokens) {\n      throw new Error(\n        `The model ${model} can only handle ${generativeAiGoogleModels[model].maxTokens} tokens, but ${tokenCount} were provided in the prompts alone.`,\n      );\n    }\n\n    if (generativeAiGoogleModels[model] && tokenCount + maxTokens > generativeAiGoogleModels[model].maxTokens) {\n      const message = `The model can only handle a maximum of ${\n        generativeAiGoogleModels[model].maxTokens\n      } tokens, but the prompts and max tokens together exceed this limit. The max tokens has been reduced to ${\n        generativeAiGoogleModels[model].maxTokens - tokenCount\n      }.`;\n      addWarning(output, message);\n      maxTokens = Math.floor((generativeAiGoogleModels[model].maxTokens - tokenCount) * 0.95); // reduce max tokens by 5% to be safe, calculation is a little wrong.\n    }\n\n    const project = context.getPluginConfig('googleProjectId');\n    const location = context.getPluginConfig('googleRegion');\n    const applicationCredentials = context.getPluginConfig('googleApplicationCredentials');\n    const apiKey = context.getPluginConfig('googleApiKey');\n\n    let tools: Tool[] = [];\n\n    if (data.useToolCalling) {\n      const gptTools = coerceTypeOptional(inputs['functions' as PortId], 'gpt-function[]') ?? [];\n\n      if (gptTools) {\n        tools = [\n          {\n            functionDeclarations: gptTools.map(\n              (tool): FunctionDeclaration => ({\n                name: tool.name,\n                description: tool.description,\n                parameters:\n                  Object.keys((tool.parameters as any).properties).length === 0\n                    ? undefined\n                    : {\n                        type: Type.OBJECT,\n                        properties: mapValues((tool.parameters as any).properties, (p: any) => ({\n                          // gemini doesn't support union property types, it uses openapi style not jsonschema, what a mess\n                          type: Array.isArray(p.type) ? p.type.filter((t: any) => t !== 'null')[0] : p.type,\n                          description: p.description,\n                        })),\n                        required: (tool.parameters as any).required || [],\n                      },\n              }),\n            ),\n          },\n        ];\n      }\n    }\n\n    if (!apiKey) {\n      if (project == null) {\n        throw new Error('Google Project ID or Google API Key is not defined.');\n      }\n      if (location == null) {\n        throw new Error('Google Region or Google API Key is not defined.');\n      }\n      if (applicationCredentials == null) {\n        throw new Error('Google Application Credentials or Google API Key is not defined.');\n      }\n    }\n\n    const headersFromData = (data.headers ?? []).reduce(\n      (acc, header) => {\n        acc[header.key] = header.value;\n        return acc;\n      },\n      {} as Record<string, string>,\n    );\n    const additionalHeaders = data.useHeadersInput\n      ? (coerceTypeOptional(inputs['headers' as PortId], 'object') as Record<string, string> | undefined) ??\n        headersFromData\n      : headersFromData;\n\n    const allAdditionalHeaders = cleanHeaders({\n      ...context.settings.chatNodeHeaders,\n      ...additionalHeaders,\n    });\n\n    try {\n      return await retry(\n        async () => {\n          const options: Omit<StreamGenerativeAiOptions, 'apiKey' | 'signal'> = {\n            prompt,\n            model,\n            temperature: useTopP ? undefined : temperature,\n            topP: useTopP ? topP : undefined,\n            maxOutputTokens: maxTokens,\n            systemPrompt,\n            topK: undefined,\n            tools,\n            thinkingBudget,\n            additionalHeaders: allAdditionalHeaders,\n          };\n          const cacheKey = JSON.stringify(options);\n\n          if (data.cache) {\n            const cached = cache.get(cacheKey);\n            if (cached) {\n              return cached;\n            }\n          }\n\n          const startTime = Date.now();\n\n          let chunks: AsyncGenerator<ChatCompletionChunk>;\n\n          if (data.useToolCalling && !apiKey) {\n            throw new Error('Tool calling is only supported when using a generative API key.');\n          }\n\n          if (apiKey) {\n            chunks = streamGenerativeAi({\n              signal: context.signal,\n              model,\n              prompt,\n              maxOutputTokens: maxTokens,\n              temperature: useTopP ? undefined : temperature,\n              topP: useTopP ? topP : undefined,\n              topK: undefined,\n              apiKey,\n              systemPrompt,\n              tools,\n              thinkingBudget,\n              additionalHeaders: allAdditionalHeaders,\n            });\n          } else {\n            chunks = streamChatCompletions({\n              signal: context.signal,\n              model: model as GoogleModelsDeprecated,\n              prompt,\n              max_output_tokens: maxTokens,\n              temperature: useTopP ? undefined : temperature,\n              top_p: useTopP ? topP : undefined,\n              top_k: undefined,\n              project: project!,\n              location: location!,\n              applicationCredentials: applicationCredentials!,\n            });\n          }\n\n          const responseParts: string[] = [];\n          const functionCalls: FunctionCall[] = [];\n\n          let throttleLastCalledTime = Date.now();\n          const onPartialOutput = (output: Outputs) => {\n            const now = Date.now();\n            if (now - throttleLastCalledTime > (context.settings.throttleChatNode ?? 100)) {\n              context.onPartialOutputs?.(output);\n              throttleLastCalledTime = now;\n            }\n          };\n\n          for await (const chunk of chunks) {\n            if (chunk.completion) {\n              responseParts.push(chunk.completion);\n\n              output['response' as PortId] = {\n                type: 'string',\n                value: responseParts.join('').trim(),\n              };\n            }\n\n            if (chunk.function_calls) {\n              functionCalls.push(...chunk.function_calls);\n\n              output['function-calls' as PortId] = {\n                type: 'object[]',\n                value: functionCalls.map((fc) => ({\n                  id: fc.name,\n                  name: fc.name,\n                  arguments: fc.args,\n                })),\n              };\n            }\n\n            onPartialOutput?.(output);\n          }\n\n          // Call one last time manually to ensure the last output is sent\n          context.onPartialOutputs?.(output);\n\n          const endTime = Date.now();\n\n          output['all-messages' as PortId] = {\n            type: 'chat-message[]',\n            value: [\n              ...messages,\n              {\n                type: 'assistant',\n                message: responseParts.join('').trim() ?? '',\n                function_call: undefined,\n                function_calls:\n                  functionCalls.length === 0\n                    ? undefined\n                    : functionCalls.map((fc) => ({\n                        id: fc.name!,\n                        name: fc.name!,\n                        arguments: JSON.stringify(fc.args),\n                      })),\n              },\n            ],\n          };\n\n          output['in-messages' as PortId] = {\n            type: 'chat-message[]',\n            value: messages,\n          };\n\n          if (responseParts.length === 0 && functionCalls.length === 0) {\n            throw new Error('No response from Google');\n          }\n\n          output['requestTokens' as PortId] = { type: 'number', value: tokenCount };\n\n          const responseTokenCount = await context.tokenizer.getTokenCountForString(\n            responseParts.join(''),\n            tokenizerInfo,\n          );\n          output['responseTokens' as PortId] = { type: 'number', value: responseTokenCount };\n\n          // TODO\n          // const cost =\n          //   getCostForPrompt(completionMessages, model) + getCostForTokens(responseTokenCount, 'completion', model);\n\n          // output['cost' as PortId] = { type: 'number', value: cost };\n\n          const duration = endTime - startTime;\n\n          output['duration' as PortId] = { type: 'number', value: duration };\n\n          Object.freeze(output);\n          cache.set(cacheKey, output);\n\n          return output;\n        },\n        {\n          retries: 10,\n          maxRetryTime: 1000 * 60 * 5,\n          factor: 2.5,\n          minTimeout: 500,\n          maxTimeout: 5000,\n          randomize: true,\n          signal: context.signal,\n          onFailedAttempt(err) {\n            context.trace(`ChatGoogleNode failed, retrying: ${err.toString()}`);\n\n            const googleError = err as { status?: number; message?: string };\n\n            if (googleError.status && googleError.status >= 400 && googleError.status < 500) {\n              if (googleError.status === 429) {\n                context.trace('Google API rate limit exceeded, retrying...');\n              } else {\n                throw new Error(`Google API error: ${googleError.status} ${googleError.message}`);\n              }\n            }\n\n            if (context.signal.aborted) {\n              throw new Error('Aborted');\n            }\n          },\n        },\n      );\n    } catch (error) {\n      const raisedError = getError(error);\n      context.trace(raisedError.stack ?? 'Missing stack');\n      const err = new Error(`Error processing ChatGoogleNode: ${raisedError.message}`);\n      err.cause = raisedError;\n      throw err;\n    }\n  },\n};\n\nexport const chatGoogleNode = pluginNodeDefinition(ChatGoogleNodeImpl, 'Chat');\n\nexport function getChatGoogleNodeMessages(inputs: Inputs) {\n  const prompt = inputs['prompt' as PortId];\n  if (!prompt) {\n    throw new Error('Prompt is required');\n  }\n\n  const messages: ChatMessage[] = match(prompt)\n    .with({ type: 'chat-message' }, (p) => [p.value])\n    .with({ type: 'chat-message[]' }, (p) => p.value)\n    .with({ type: 'string' }, (p): ChatMessage[] => [{ type: 'user', message: p.value }])\n    .with({ type: 'string[]' }, (p): ChatMessage[] => p.value.map((v) => ({ type: 'user', message: v })))\n    .otherwise((p): ChatMessage[] => {\n      if (isArrayDataValue(p)) {\n        const stringValues = (p.value as readonly unknown[]).map((v) =>\n          coerceType(\n            {\n              type: getScalarTypeOf(p.type),\n              value: v,\n            } as ScalarDataValue,\n            'string',\n          ),\n        );\n\n        return stringValues.filter((v) => v != null).map((v) => ({ type: 'user', message: v }));\n      }\n\n      const coercedMessage = coerceType(p, 'chat-message');\n      if (coercedMessage != null) {\n        return [coercedMessage];\n      }\n\n      const coercedString = coerceType(p, 'string');\n      return coercedString != null ? [{ type: 'user', message: coerceType(p, 'string') }] : [];\n    });\n  return { messages };\n}\n", "import { type RivetPlugin } from '../../index.js';\nimport { chatGoogleNode } from './nodes/ChatGoogleNode.js';\n\nexport const googlePlugin: RivetPlugin = {\n  id: 'google',\n  name: 'Google',\n\n  register: (register) => {\n    register(chatGoogleNode);\n  },\n\n  configSpec: {\n    googleApiKey: {\n      type: 'secret',\n      label: 'Google API Key',\n      description: 'The API key for accessing Google generative AI.',\n      pullEnvironmentVariable: 'GOOGLE_GENERATIVE_AI_API_KEY',\n      helperText: 'You may also set the GOOGLE_GENERATIVE_AI_API_KEY environment variable.',\n    },\n    googleProjectId: {\n      type: 'string',\n      label: 'Google Project ID (Deprecated)',\n      description: 'The Google project ID.',\n      pullEnvironmentVariable: 'GCP_PROJECT',\n      helperText: 'Deprecated, use Google API Key instead. You may also set the GCP_PROJECT environment variable.',\n    },\n    googleRegion: {\n      type: 'string',\n      label: 'Google Region (Deprecated)',\n      description: 'The Google region.',\n      pullEnvironmentVariable: 'GCP_REGION',\n      helperText: 'Deprecated, use Google API Key instead. You may also set the GCP_REGION environment variable.',\n    },\n    googleApplicationCredentials: {\n      type: 'string',\n      label: 'Google Application Credentials (Deprecated)',\n      description: 'The path with the JSON file that contains your credentials.',\n      pullEnvironmentVariable: 'GOOGLE_APPLICATION_CREDENTIALS',\n      helperText:\n        'Deprecated, use Google API Key instead. You may also set the GOOGLE_APPLICATION_CREDENTIALS environment variable. See https://cloud.google.com/vertex-ai/docs/start/client-libraries for more info.',\n    },\n  },\n};\n", "import anthropicPlugin from './plugins/anthropic/index.js';\nimport autoevalsPlugin from './plugins/autoevals/index.js';\nimport assemblyAiPlugin from './plugins/assemblyAi/index.js';\nimport { huggingFacePlugin } from './plugins/huggingface/plugin.js';\nimport pineconePlugin from './plugins/pinecone/index.js';\nimport gentracePlugin from './plugins/gentrace/index.js';\nimport { openAIPlugin } from './plugins/openai/plugin.js';\nimport { googlePlugin } from './plugins/google/plugin.js';\n\nexport {\n  anthropicPlugin,\n  autoevalsPlugin,\n  assemblyAiPlugin,\n  pineconePlugin,\n  huggingFacePlugin,\n  gentracePlugin,\n  googlePlugin,\n};\n\nexport const plugins = {\n  anthropic: anthropicPlugin,\n  autoevals: autoevalsPlugin,\n  assemblyAi: assemblyAiPlugin,\n  pinecone: pineconePlugin,\n  huggingFace: huggingFacePlugin,\n  gentrace: gentracePlugin,\n  openai: openAIPlugin,\n  google: googlePlugin,\n};\n", "import { type Dataset, type DatasetId, type DatasetMetadata, type DatasetRow, type ProjectId } from '../index.js';\nimport { cloneDeep } from 'lodash-es';\nimport type { CombinedDataset } from '../utils/index.js';\n\nexport interface DatasetProvider {\n  getDatasetMetadata(id: DatasetId): Promise<DatasetMetadata | undefined>;\n\n  getDatasetsForProject(projectId: ProjectId): Promise<DatasetMetadata[]>;\n\n  getDatasetData(id: DatasetId): Promise<Dataset>;\n\n  putDatasetData(id: DatasetId, data: Dataset): Promise<void>;\n\n  putDatasetRow(id: DatasetId, row: DatasetRow): Promise<void>;\n\n  putDatasetMetadata(metadata: DatasetMetadata): Promise<void>;\n\n  clearDatasetData(id: DatasetId): Promise<void>;\n\n  deleteDataset(id: DatasetId): Promise<void>;\n\n  /** Gets the K nearest neighbor rows to the given vector. */\n  knnDatasetRows(datasetId: DatasetId, k: number, vector: number[]): Promise<(DatasetRow & { distance?: number })[]>;\n\n  exportDatasetsForProject(projectId: ProjectId): Promise<CombinedDataset[]>;\n}\n\nexport class InMemoryDatasetProvider implements DatasetProvider {\n  readonly #datasets;\n\n  constructor(datasets: CombinedDataset[]) {\n    this.#datasets = datasets;\n  }\n\n  async getDatasetMetadata(id: DatasetId): Promise<DatasetMetadata | undefined> {\n    const dataset = this.#datasets.find((d) => d.meta.id === id);\n    return dataset?.meta;\n  }\n\n  async getDatasetsForProject(): Promise<DatasetMetadata[]> {\n    return this.#datasets.map((d) => d.meta);\n  }\n\n  async getDatasetData(id: DatasetId): Promise<Dataset> {\n    const dataset = this.#datasets.find((d) => d.meta.id === id);\n    if (!dataset) {\n      return { id, rows: [] };\n    }\n    return dataset.data;\n  }\n\n  async putDatasetRow(id: DatasetId, row: DatasetRow): Promise<void> {\n    const dataset = this.#datasets.find((d) => d.meta.id === id);\n    if (!dataset) {\n      throw new Error(`Dataset ${id} not found`);\n    }\n\n    const existingRow = dataset.data.rows.find((r) => r.id === row.id);\n    if (existingRow) {\n      existingRow.data = row.data;\n      existingRow.embedding = row.embedding;\n      return;\n    }\n\n    dataset.data.rows.push(row);\n  }\n\n  async putDatasetData(id: DatasetId, data: Dataset): Promise<void> {\n    const dataset = this.#datasets.find((d) => d.meta.id === id);\n    if (!dataset) {\n      throw new Error(`Dataset ${id} not found`);\n    }\n\n    dataset.data = data;\n  }\n\n  async putDatasetMetadata(metadata: DatasetMetadata): Promise<void> {\n    const matchingDataset = this.#datasets.find((d) => d.meta.id === metadata.id);\n\n    if (matchingDataset) {\n      matchingDataset.meta = metadata;\n      return;\n    }\n\n    this.#datasets.push({\n      meta: metadata,\n      data: {\n        id: metadata.id,\n        rows: [],\n      },\n    });\n  }\n\n  async clearDatasetData(id: DatasetId): Promise<void> {\n    const dataset = this.#datasets.find((d) => d.meta.id === id);\n    if (!dataset) {\n      return;\n    }\n\n    dataset.data = {\n      id,\n      rows: [],\n    };\n  }\n\n  async deleteDataset(id: DatasetId): Promise<void> {\n    const index = this.#datasets.findIndex((d) => d.meta.id === id);\n    if (index === -1) {\n      return;\n    }\n\n    this.#datasets.splice(index, 1);\n  }\n\n  async knnDatasetRows(\n    datasetId: DatasetId,\n    k: number,\n    vector: number[],\n  ): Promise<(DatasetRow & { distance?: number | undefined })[]> {\n    const allRows = await this.getDatasetData(datasetId);\n\n    const sorted = allRows.rows\n      .filter((row) => row.embedding != null)\n      .map((row) => ({\n        row,\n        similarity: dotProductSimilarity(vector, row.embedding!),\n      }))\n      .sort((a, b) => b.similarity - a.similarity);\n\n    return sorted.slice(0, k).map((r) => ({ ...r.row, distance: r.similarity }));\n  }\n\n  async exportDatasetsForProject(_projectId: ProjectId): Promise<CombinedDataset[]> {\n    // Cloning is safest... but slow\n    return cloneDeep(this.#datasets);\n  }\n}\n\n/** OpenAI embeddings are already normalized, so this is equivalent to cosine similarity */\nconst dotProductSimilarity = (a: number[], b: number[]): number => {\n  return a.reduce((acc, val, i) => acc + val * b[i]!, 0);\n};\n", "import {\n  type NodeId,\n  type Inputs,\n  type Outputs,\n  type GraphOutputs,\n  type GraphProcessor,\n  type PortId,\n} from '../index.js';\nimport { coerceType } from '../utils/coerceType.js';\n\nexport type RivetEventStreamFilterSpec = {\n  /** Stream partial output deltas for the specified node IDs or node titles. */\n  partialOutputs?: string[] | true;\n\n  /** Send the graph output when done? */\n  done?: boolean;\n\n  /** If the graph errors, send an error event? */\n  error?: boolean;\n\n  /** Stream node start events for the specified node IDs or node titles. */\n  nodeStart?: string[] | true;\n\n  /** Stream node finish events for the specified nodeIDs or node titles. */\n  nodeFinish?: string[] | true;\n};\n\n/** Map of all possible event names to their data for streaming events. */\nexport type RivetEventStreamEvent = {\n  /** Deltas for partial outputs. */\n  partialOutput: {\n    nodeId: NodeId;\n    nodeTitle: string;\n    delta: string;\n  };\n\n  nodeStart: {\n    nodeId: NodeId;\n    nodeTitle: string;\n    inputs: Inputs;\n  };\n\n  nodeFinish: {\n    nodeId: NodeId;\n    nodeTitle: string;\n    outputs: Outputs;\n  };\n\n  done: {\n    graphOutput: GraphOutputs;\n  };\n\n  error: {\n    error: string;\n  };\n};\n\nexport type RivetEventStreamEventInfo = {\n  [P in keyof RivetEventStreamEvent]: {\n    type: P;\n  } & RivetEventStreamEvent[P];\n}[keyof RivetEventStreamEvent];\n\n/** A simplified way to listen and stream processor events, including filtering. */\nexport async function* getProcessorEvents(\n  processor: GraphProcessor,\n  spec: RivetEventStreamFilterSpec,\n): AsyncGenerator<RivetEventStreamEventInfo, void> {\n  const previousIndexes = new Map<NodeId, number>();\n\n  for await (const event of processor.events()) {\n    if (event.type === 'partialOutput') {\n      if (\n        spec.partialOutputs === true ||\n        spec.partialOutputs?.includes(event.node.id) ||\n        spec.partialOutputs?.includes(event.node.title)\n      ) {\n        const currentOutput = coerceType(event.outputs['response' as PortId], 'string');\n\n        const delta = currentOutput.slice(previousIndexes.get(event.node.id) ?? 0);\n\n        yield {\n          type: 'partialOutput',\n          nodeId: event.node.id,\n          nodeTitle: event.node.title,\n          delta,\n        };\n\n        previousIndexes.set(event.node.id, currentOutput.length);\n      }\n    } else if (event.type === 'done') {\n      if (spec.done) {\n        yield {\n          type: 'done',\n          graphOutput: event.results,\n        };\n      }\n    } else if (event.type === 'error') {\n      if (spec.error) {\n        yield {\n          type: 'error',\n          error: typeof event.error === 'string' ? event.error : event.error.toString(),\n        };\n      }\n    } else if (event.type === 'nodeStart') {\n      if (\n        spec.nodeStart === true ||\n        spec.nodeStart?.includes(event.node.id) ||\n        spec.nodeStart?.includes(event.node.title)\n      ) {\n        yield {\n          type: 'nodeStart',\n          inputs: event.inputs,\n          nodeId: event.node.id,\n          nodeTitle: event.node.title,\n        };\n      }\n    } else if (event.type === 'nodeFinish') {\n      if (\n        spec.nodeFinish === true ||\n        spec.nodeFinish?.includes(event.node.id) ||\n        spec.nodeFinish?.includes(event.node.title)\n      ) {\n        yield {\n          type: 'nodeFinish',\n          outputs: event.outputs,\n          nodeId: event.node.id,\n          nodeTitle: event.node.title,\n        };\n      }\n    }\n  }\n}\n\n/**\n * Creates a ReadableStream for processor events, following the Server-Sent Events protocol.\n * https://developer.mozilla.org/en-US/docs/Web/API/EventSource\n *\n * Includes configuration for what events to send to the client, for example you can stream the partial output deltas\n * for specific nodes, and/or the graph output when done.\n */\nexport function getProcessorSSEStream(\n  processor: GraphProcessor,\n\n  /** The spec for what you're streaming to the client */\n  spec: RivetEventStreamFilterSpec,\n) {\n  const encoder = new TextEncoder();\n\n  function sendEvent<T extends keyof RivetEventStreamEvent>(\n    controller: ReadableStreamDefaultController,\n    type: T,\n    data: RivetEventStreamEvent[T],\n  ) {\n    const event = `event: ${type}\\ndata: ${JSON.stringify(data)}\\n\\n`;\n    controller.enqueue(encoder.encode(event));\n  }\n\n  return new ReadableStream<Uint8Array>({\n    async start(controller) {\n      try {\n        for await (const event of getProcessorEvents(processor, spec)) {\n          sendEvent(controller, event.type, event);\n        }\n        controller.close();\n      } catch (err) {\n        controller.error(err);\n      }\n    },\n  });\n}\n\nexport function getSingleNodeStream(processor: GraphProcessor, nodeIdOrTitle: string) {\n  return new ReadableStream<string>({\n    async start(controller) {\n      try {\n        for await (const event of getProcessorEvents(processor, {\n          partialOutputs: [nodeIdOrTitle],\n          nodeFinish: [nodeIdOrTitle],\n        })) {\n          if (event.type === 'partialOutput' && (event.nodeId === nodeIdOrTitle || event.nodeTitle === nodeIdOrTitle)) {\n            controller.enqueue(`data: ${JSON.stringify(event.delta)}\\n\\n`);\n          } else if (\n            event.type === 'nodeFinish' &&\n            (event.nodeId === nodeIdOrTitle || event.nodeTitle === nodeIdOrTitle)\n          ) {\n            controller.close();\n          }\n        }\n\n        controller.close();\n      } catch (err) {\n        controller.error(err);\n      }\n    },\n  });\n}\n", "import type { PascalCase } from 'type-fest';\nimport {\n  type AttachedData,\n  type AudioProvider,\n  type DataValue,\n  type DatasetProvider,\n  type ExternalFunction,\n  type GraphId,\n  type MCPProvider,\n  type NativeApi,\n  type NodeRegistration,\n  type ProcessContext,\n  type ProcessEvents,\n  type Project,\n  type RivetEventStreamFilterSpec,\n  type Settings,\n} from '../index.js';\nimport { getProcessorEvents, getProcessorSSEStream, getSingleNodeStream } from './streaming.js';\n// eslint-disable-next-line import/no-cycle -- Necessary cycle\nimport { GraphProcessor } from '../model/GraphProcessor.js';\nimport { deserializeProject } from '../utils/serialization/serialization.js';\nimport { DEFAULT_CHAT_NODE_TIMEOUT } from '../utils/defaults.js';\nimport type { Tokenizer } from '../integrations/Tokenizer.js';\nimport { looseDataValuesToDataValues, type LooseDataValue } from './looseDataValue.js';\nimport type { CodeRunner } from '../integrations/CodeRunner.js';\nimport type { ProjectReferenceLoader } from '../model/ProjectReferenceLoader.js';\n\nexport type RunGraphOptions = {\n  graph?: string;\n  inputs?: Record<string, LooseDataValue>;\n  context?: Record<string, LooseDataValue>;\n  nativeApi?: NativeApi;\n  datasetProvider?: DatasetProvider;\n  audioProvider?: AudioProvider;\n  mcpProvider?: MCPProvider;\n  externalFunctions?: {\n    [key: string]: ExternalFunction;\n  };\n  onUserEvent?: {\n    [key: string]: (data: DataValue | undefined) => void;\n  };\n  abortSignal?: AbortSignal;\n  registry?: NodeRegistration<any, any>;\n  includeTrace?: boolean;\n  getChatNodeEndpoint?: ProcessContext['getChatNodeEndpoint'];\n  tokenizer?: Tokenizer;\n  codeRunner?: CodeRunner;\n  projectPath?: string;\n  projectReferenceLoader?: ProjectReferenceLoader;\n} & {\n  [P in keyof ProcessEvents as `on${PascalCase<P>}`]?: (params: ProcessEvents[P]) => void;\n} & Settings;\n\nexport function coreCreateProcessor(project: Project, options: RunGraphOptions) {\n  const { graph, inputs = {}, context = {} } = options;\n\n  const graphId = graph\n    ? graph in project.graphs\n      ? graph\n      : Object.values(project.graphs).find((g) => g.metadata?.name === graph)?.metadata?.id\n    : project.metadata.mainGraphId;\n\n  if (!graphId) {\n    throw new Error(`Graph not found, and no main graph specified.`);\n  }\n\n  // TODO: Consolidate options into one object\n  const processor = new GraphProcessor(project, graphId as GraphId, options.registry, options.includeTrace);\n\n  if (options.onStart) {\n    processor.on('start', options.onStart);\n  }\n\n  if (options.onNodeStart) {\n    processor.on('nodeStart', options.onNodeStart);\n  }\n\n  if (options.onNodeFinish) {\n    processor.on('nodeFinish', options.onNodeFinish);\n  }\n\n  if (options.onNodeError) {\n    processor.on('nodeError', options.onNodeError);\n  }\n\n  if (options.onNodeExcluded) {\n    processor.on('nodeExcluded', options.onNodeExcluded);\n  }\n\n  if (options.onGraphStart) {\n    processor.on('graphStart', options.onGraphStart);\n  }\n\n  if (options.onGraphError) {\n    processor.on('graphError', options.onGraphError);\n  }\n\n  if (options.onGraphFinish) {\n    processor.on('graphFinish', options.onGraphFinish);\n  }\n\n  if (options.onPartialOutput) {\n    processor.on('partialOutput', options.onPartialOutput);\n  }\n\n  if (options.onUserInput) {\n    processor.on('userInput', options.onUserInput);\n  }\n\n  if (options.onDone) {\n    processor.on('done', options.onDone);\n  }\n\n  if (options.onAbort) {\n    processor.on('abort', options.onAbort);\n  }\n\n  if (options.onGraphAbort) {\n    processor.on('graphAbort', options.onGraphAbort);\n  }\n\n  if (options.onTrace) {\n    processor.on('trace', options.onTrace);\n  }\n\n  if (options.onNodeOutputsCleared) {\n    processor.on('nodeOutputsCleared', options.onNodeOutputsCleared);\n  }\n\n  if (options.externalFunctions) {\n    for (const [name, fn] of Object.entries(options.externalFunctions)) {\n      processor.setExternalFunction(name, fn);\n    }\n  }\n\n  if (options.onUserEvent) {\n    for (const [name, fn] of Object.entries(options.onUserEvent)) {\n      processor.onUserEvent(name, fn);\n    }\n  }\n\n  options.abortSignal?.addEventListener('abort', () => {\n    // eslint-disable-next-line @typescript-eslint/no-floating-promises\n    processor.abort();\n  });\n\n  const resolvedInputs = looseDataValuesToDataValues(inputs);\n  const resolvedContextValues = looseDataValuesToDataValues(context);\n\n  return {\n    processor,\n    inputs: resolvedInputs,\n    contextValues: resolvedContextValues,\n    getEvents: (spec: RivetEventStreamFilterSpec) => getProcessorEvents(processor, spec),\n    getSSEStream: (spec: RivetEventStreamFilterSpec) => getProcessorSSEStream(processor, spec),\n    streamNode: (nodeIdOrTitle: string) => getSingleNodeStream(processor, nodeIdOrTitle),\n    async run() {\n      const outputs = await processor.processGraph(\n        {\n          nativeApi: options.nativeApi,\n          datasetProvider: options.datasetProvider,\n          audioProvider: options.audioProvider,\n          mcpProvider: options.mcpProvider,\n          codeRunner: options.codeRunner,\n          projectPath: options.projectPath,\n          projectReferenceLoader: options.projectReferenceLoader,\n          settings: {\n            openAiKey: options.openAiKey ?? '',\n            openAiOrganization: options.openAiOrganization ?? '',\n            openAiEndpoint: options.openAiEndpoint ?? '',\n            pluginEnv: options.pluginEnv ?? {},\n            pluginSettings: options.pluginSettings ?? {},\n            recordingPlaybackLatency: 1000,\n            chatNodeHeaders: options.chatNodeHeaders ?? {},\n            chatNodeTimeout: options.chatNodeTimeout ?? DEFAULT_CHAT_NODE_TIMEOUT,\n            throttleChatNode: options.throttleChatNode ?? 100,\n          } satisfies Required<Settings>,\n          getChatNodeEndpoint: options.getChatNodeEndpoint,\n        },\n        resolvedInputs,\n        resolvedContextValues,\n      );\n\n      return outputs;\n    },\n  };\n}\n\nexport async function coreRunGraph(project: Project, options: RunGraphOptions): Promise<Record<string, DataValue>> {\n  const processorInfo = coreCreateProcessor(project, options);\n  return processorInfo.run();\n}\n\nexport function loadProjectFromString(content: string): Project {\n  const [project] = deserializeProject(content);\n  return project;\n}\n\nexport function loadProjectAndAttachedDataFromString(content: string): [Project, AttachedData] {\n  return deserializeProject(content);\n}\n"],
  "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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AAO;AAC5C,SAAO;AACT;AAEO,SAAS,qCAAqC,SAA0C;AAC7F,SAAO,mBAAmB,OAAO;AACnC;;;ApLrMO,IAAM,QAA2B;",
  "names": ["yaml", "import_lodash_es", "import_safe_stable_stringify", "yaml", "mapValues", "fromSerializedProject", "fromSerializedGraph", "stableStringify", "fromSerializedNode", "fromSerializedConnection", "yaml", "err", "import_non_secure", "import_lodash_es", "import_emittery", "import_non_secure", "import_ts_pattern", "mapValues", "import_non_secure", "import_lodash_es", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_lodash_es", "match", "lodashGet", "import_non_secure", "import_ts_dedent", "import_ts_pattern", "import_lodash_es", "init", "import_ts_pattern", "options", "message", "retry", "_a", "options", "promptCostPerThousand", "completionCostPerThousand", "promptCost", "completionCost", "output", "functionCalls", "_b", "_c", "import_non_secure", "import_lodash_es", "import_ts_dedent", "import_ts_pattern", "type", "import_non_secure", "import_ts_dedent", "match", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "match", "import_non_secure", "import_ts_dedent", "value", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_lodash_es", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_lodash_es", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "match", "yaml", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_lodash_es", "import_ts_dedent", "result", "import_non_secure", "import_jsonpath_plus", "import_ts_dedent", "match", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "id", "value", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_yaml", "import_ts_dedent", "yaml", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_pattern", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "value", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_lodash_es", "import_ts_dedent", "include", "import_non_secure", "import_ts_dedent", "values", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_lodash_es", "import_ts_pattern", "import_ts_dedent", "import_non_secure", "import_ts_pattern", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "max", "import_non_secure", "import_lodash_es", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_non_secure", "import_non_secure", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "match", "import_non_secure", "import_lodash_es", "import_ts_pattern", "type", "import_non_secure", "import_non_secure", "import_jsonpath_plus", "import_ts_dedent", "match", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "graph", "import_non_secure", "import_ts_dedent", "import_lodash_es", "values", "import_ts_dedent", "handler", "import_non_secure", "import_non_secure", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "keys", "import_nanoid", "import_ts_dedent", "match", "import_non_secure", "import_ts_dedent", "import_lodash_es", "match", "import_non_secure", "import_ts_dedent", "import_nanoid", "MCPErrorType", "config", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_non_secure", "import_ts_dedent", "Emittery", "options", "PQueueImport", "Emittery", "values", "node", "_a", "results", "connections", "import_openai", "options", "import_non_secure", "import_emittery", "import_lodash_es", "fnv1a", "options", "Emittery", "EventSourceResponse", "init", "createEventStream", "fetchEventSource", "LineSplitter", "streamChatCompletions", "fetchEventSource", "fetchEventSource", "import_non_secure", "import_ts_dedent", "import_p_retry", "import_ts_pattern", "cache", "retry", "streamChatCompletions", "getCostForTokens", "content", "import_non_secure", "import_ts_dedent", "import_ts_pattern", "import_non_secure", "import_ts_dedent", "import_assemblyai", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_ts_dedent", "import_assemblyai", "import_non_secure", "import_ts_dedent", "import_assemblyai", "import_non_secure", "import_ts_dedent", "import_non_secure", "import_non_secure", "import_inference", "import_ts_dedent", "options", "import_lodash_es", "_a", "response", "import_lodash_es", "streamChatCompletions", "import_non_secure", "import_ts_dedent", "import_p_retry", "import_ts_pattern", "import_genai", "import_lodash_es", "cache", "retry", "options", "streamChatCompletions", "output", "_a", "import_lodash_es", "options", "_a"]
}
