@codemation/core-nodes 0.0.19 → 0.0.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["OpenAIChatModelFactory","name: string","model: string","credentialSlotKey: string","options?: Readonly<{\n temperature?: number;\n maxTokens?: number;\n }>","AIAgentExecutionHelpersFactory","NodeBackedToolRuntime","nodeResolver: NodeResolver","AIAgentNode","nodeResolver: NodeResolver","credentialSessions: CredentialSessionService","nodeBackedToolRuntime: NodeBackedToolRuntime","executionHelpers: AIAgentExecutionHelpersFactory","out: Item[]","conversation: BaseMessage[]","finalResponse: AIMessage | undefined","CallbackNode","name: string","callback: CallbackHandler<TInputJson, TOutputJson>","id?: string","HttpRequestNode","output: Item[]","outputItem: Item","values: Record<string, string>","name: string","args: Readonly<{\n method?: string;\n urlField?: string;\n binaryName?: string;\n downloadMode?: HttpRequestDownloadMode;\n id?: string;\n }>","retryPolicy: RetryPolicySpec","IfNode","t: Item[]","f: Item[]","tagged: Item","name: string","predicate: (\n item: Item<TInputJson>,\n index: number,\n items: Items<TInputJson>,\n ctx: NodeExecutionContext<If<TInputJson>>,\n ) => boolean","id?: string","ManualTriggerNode","name: string","MapDataNode","out: Item[]","name: string","map: (\n item: Item<TInputJson>,\n ctx: NodeExecutionContext<MapData<TInputJson, TOutputJson>>,\n ) => TOutputJson","id?: string","MergeNode","out: Item[]","out","json: Record<string, unknown>","paired: any[]","meta: Record<string, unknown> | undefined","merged: any","fallback: Item[]","name: string","cfg: Readonly<{\n mode: MergeMode;\n /**\n * Deterministic input precedence order (only used for passThrough/append).\n * Any inputs not listed are appended in lexicographic order.\n */\n prefer?: ReadonlyArray<InputPortKey>;\n }>","id?: string","NoOpNode","name: string","id?: string","SubWorkflowNode","workflows: WorkflowRunnerService","out: Item[]","name: string","workflowId: string","upstreamRefs?: Array<{ nodeId: NodeId } | UpstreamRefPlaceholder>","startAt?: NodeId","id?: string","WaitNode","name: string","milliseconds: number","id?: string","responseItems: Items","continueItems: Items","responseItems: Items","WebhookTriggerNode","name: string","args: Readonly<{\n endpointKey: string;\n methods: ReadonlyArray<HttpMethod>;\n inputSchema?: TSchema;\n }>","handler: WebhookTriggerHandler<\n WebhookTrigger<TSchema>\n >","id?: string","ConnectionCredentialNode","steps: ReadonlyArray<AnyRunnableNodeConfig>","chain: ChainCursor<TCurrentJson>","id: string","workflowName: string","connectionCredentialNodeConfigFactory: ConnectionCredentialNodeConfigFactory","workflow","extraNodes: NodeDefinition[]","extraConnections: WorkflowNodeConnection[]","node","toolIds: string[]","name: string","credentialSource: { getCredentialRequirements?: () => ReadonlyArray<CredentialRequirement> }"],"sources":["../src/chatModels/OpenAIChatModelFactory.ts","../src/chatModels/openAiChatModelConfig.ts","../src/chatModels/OpenAiChatModelPresetsFactory.ts","../src/nodes/AgentMessageFactory.ts","../src/nodes/AgentOutputFactory.ts","../src/nodes/AgentToolCallPortMapFactory.ts","../src/nodes/ConnectionCredentialExecutionContextFactory.ts","../src/nodes/AIAgentExecutionHelpersFactory.ts","../src/nodes/NodeBackedToolRuntime.ts","../src/nodes/aiAgentSupport.types.ts","../src/nodes/AIAgentNode.ts","../src/nodes/AIAgentConfig.ts","../src/nodes/CallbackResultNormalizerFactory.ts","../src/nodes/CallbackNode.ts","../src/nodes/CallbackNodeFactory.ts","../src/nodes/HttpRequestNodeFactory.ts","../src/nodes/httpRequest.ts","../src/nodes/IfNode.ts","../src/nodes/if.ts","../src/nodes/ManualTriggerNode.ts","../src/nodes/ManualTriggerFactory.ts","../src/nodes/MapDataNode.ts","../src/nodes/mapData.ts","../src/nodes/mergeExecutionUtils.types.ts","../src/nodes/MergeNode.ts","../src/nodes/merge.ts","../src/nodes/NoOpNode.ts","../src/nodes/noOp.ts","../src/nodes/SubWorkflowNode.ts","../src/nodes/subWorkflow.ts","../src/nodes/WaitDurationFactory.ts","../src/nodes/WaitNode.ts","../src/nodes/wait.ts","../src/nodes/webhookRespondNowAndContinueError.ts","../src/nodes/webhookRespondNowError.ts","../src/nodes/webhookTriggerNode.ts","../src/nodes/WebhookTriggerFactory.ts","../src/nodes/ConnectionCredentialNode.ts","../src/register.types.ts","../src/workflowBuilder.types.ts","../src/workflowAuthoring/WorkflowChatModelFactory.types.ts","../src/workflowAuthoring/WorkflowAgentNodeFactory.types.ts","../src/workflowAuthoring/WorkflowDefinedNodeResolver.types.ts","../src/workflowAuthoring/WorkflowDurationParser.types.ts","../src/workflowAuthoring/WorkflowBranchBuilder.types.ts","../src/workflowAuthoring/WorkflowChain.types.ts","../src/workflowAuthoring/WorkflowAuthoringBuilder.types.ts","../src/workflowAuthoring.types.ts","../src/workflows/AIAgentConnectionWorkflowExpander.ts","../src/nodes/ConnectionCredentialNodeConfig.ts","../src/nodes/ConnectionCredentialNodeConfigFactory.ts"],"sourcesContent":["import type { ChatModelFactory, LangChainChatModelLike, NodeExecutionContext } from \"@codemation/core\";\nimport { chatModel } from \"@codemation/core\";\nimport { ChatOpenAI } from \"@langchain/openai\";\nimport type { OpenAiCredentialSession } from \"./OpenAiCredentialSession\";\nimport type { OpenAIChatModelConfig } from \"./openAiChatModelConfig\";\n\n@chatModel({ packageName: \"@codemation/core-nodes\" })\nexport class OpenAIChatModelFactory implements ChatModelFactory<OpenAIChatModelConfig> {\n async create(\n args: Readonly<{ config: OpenAIChatModelConfig; ctx: NodeExecutionContext<any> }>,\n ): Promise<LangChainChatModelLike> {\n const session = await args.ctx.getCredential<OpenAiCredentialSession>(args.config.credentialSlotKey);\n return new ChatOpenAI({\n apiKey: session.apiKey,\n model: args.config.model,\n temperature: args.config.options?.temperature,\n maxTokens: args.config.options?.maxTokens,\n configuration: session.baseUrl ? { baseURL: session.baseUrl } : undefined,\n });\n }\n}\n","import type { AgentCanvasPresentation, ChatModelConfig, CredentialRequirement } from \"@codemation/core\";\n\nimport type { CanvasIconName } from \"../canvasIconName\";\nimport { OpenAIChatModelFactory } from \"./OpenAIChatModelFactory\";\n\nexport class OpenAIChatModelConfig implements ChatModelConfig {\n readonly type = OpenAIChatModelFactory;\n readonly presentation: AgentCanvasPresentation<CanvasIconName>;\n\n constructor(\n public readonly name: string,\n public readonly model: string,\n public readonly credentialSlotKey: string = \"openai\",\n presentationIn?: AgentCanvasPresentation<CanvasIconName>,\n public readonly options?: Readonly<{\n temperature?: number;\n maxTokens?: number;\n }>,\n ) {\n this.presentation = presentationIn ?? { icon: \"builtin:openai\", label: name };\n }\n\n getCredentialRequirements(): ReadonlyArray<CredentialRequirement> {\n return [\n {\n slotKey: this.credentialSlotKey,\n label: \"OpenAI API key\",\n acceptedTypes: [\"openai.apiKey\"],\n },\n ];\n }\n}\n","import { OpenAIChatModelConfig } from \"./openAiChatModelConfig\";\n\n/**\n * Default OpenAI chat model configs for scaffolds and demos (icon + label match {@link OpenAIChatModelConfig} defaults).\n * Prefer importing {@link openAiChatModelPresets} from here or from the consumer template re-export\n * instead of repeating {@link OpenAIChatModelConfig} construction in app workflows.\n */\nexport class OpenAiChatModelPresets {\n readonly demoGpt4oMini = new OpenAIChatModelConfig(\"OpenAI\", \"gpt-4o-mini\");\n\n readonly demoGpt41 = new OpenAIChatModelConfig(\"OpenAI\", \"gpt-4.1\");\n}\n\nexport const openAiChatModelPresets = new OpenAiChatModelPresets();\n","import type { AgentMessageDto, AgentToolCall } from \"@codemation/core\";\n\nimport { AIMessage, HumanMessage, SystemMessage, ToolMessage, type BaseMessage } from \"@langchain/core/messages\";\n\nexport class AgentMessageFactory {\n static createPromptMessages(messages: ReadonlyArray<AgentMessageDto>): ReadonlyArray<BaseMessage> {\n return messages.map((message) => this.createPromptMessage(message));\n }\n\n static createSystemPrompt(systemMessage: string): SystemMessage {\n return new SystemMessage(systemMessage);\n }\n\n static createUserPrompt(prompt: string): HumanMessage {\n return new HumanMessage(prompt);\n }\n\n static createAssistantPrompt(prompt: string): AIMessage {\n return new AIMessage(prompt);\n }\n\n static createToolMessage(toolCallId: string, content: string): ToolMessage {\n return new ToolMessage({ tool_call_id: toolCallId, content });\n }\n\n static extractContent(message: unknown): string {\n if (typeof message === \"string\") return message;\n if (!this.isRecord(message)) return String(message);\n const content = message.content;\n if (typeof content === \"string\") return content;\n if (Array.isArray(content)) {\n return content\n .map((part) => {\n if (typeof part === \"string\") return part;\n if (this.isRecord(part) && typeof part.text === \"string\") return part.text;\n return JSON.stringify(part);\n })\n .join(\"\\n\");\n }\n return JSON.stringify(content);\n }\n\n static extractToolCalls(message: unknown): ReadonlyArray<AgentToolCall> {\n if (!this.isRecord(message)) return [];\n const toolCalls = message.tool_calls;\n if (!Array.isArray(toolCalls)) return [];\n return toolCalls\n .filter((toolCall) => this.isRecord(toolCall) && typeof toolCall.name === \"string\")\n .map((toolCall) => ({\n id: typeof toolCall.id === \"string\" ? toolCall.id : undefined,\n name: toolCall.name as string,\n input: this.isRecord(toolCall) && \"args\" in toolCall ? toolCall.args : undefined,\n }));\n }\n\n private static isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n }\n\n private static createPromptMessage(message: AgentMessageDto): BaseMessage {\n if (message.role === \"system\") {\n return this.createSystemPrompt(message.content);\n }\n if (message.role === \"assistant\") {\n return this.createAssistantPrompt(message.content);\n }\n return this.createUserPrompt(message.content);\n }\n}\n","import type { Item, NodeOutputs } from \"@codemation/core\";\n\nexport class AgentOutputFactory {\n static fromUnknown(value: unknown): NodeOutputs {\n return { main: [{ json: value }] };\n }\n\n static replaceJson(item: Item, value: unknown): Item {\n return {\n ...item,\n json: value,\n };\n }\n\n static fromAgentContent(content: string): unknown {\n try {\n return JSON.parse(content) as unknown;\n } catch {\n return { output: content };\n }\n }\n}\n","import type { NodeInputsByPort } from \"@codemation/core\";\n\nexport class AgentToolCallPortMap {\n static fromInput(input: unknown): NodeInputsByPort {\n return {\n in: [\n {\n json: input,\n },\n ],\n };\n }\n}\n","import type {\n CredentialRequirement,\n CredentialSessionService,\n NodeConfigBase,\n NodeExecutionContext,\n NodeId,\n} from \"@codemation/core\";\n\nimport { CredentialResolverFactory } from \"@codemation/core/bootstrap\";\n\n/**\n * Builds a {@link NodeExecutionContext} whose identity for credential binding and `getCredential`\n * is a **connection-owned** workflow node id (`ConnectionNodeIdFactory` in `@codemation/core`),\n * not the executing parent node. Use for LLM slots, tool slots, or any connection-scoped owner.\n */\nexport class ConnectionCredentialExecutionContextFactory {\n private readonly credentialResolverFactory: CredentialResolverFactory;\n\n constructor(credentialSessions: CredentialSessionService) {\n this.credentialResolverFactory = new CredentialResolverFactory(credentialSessions);\n }\n\n forConnectionNode<TConfig extends NodeConfigBase>(\n ctx: NodeExecutionContext<TConfig>,\n args: Readonly<{\n connectionNodeId: NodeId;\n getCredentialRequirements: () => ReadonlyArray<CredentialRequirement>;\n }>,\n ): NodeExecutionContext<TConfig> {\n const stubConfig = { getCredentialRequirements: args.getCredentialRequirements } as NodeConfigBase;\n const getCredential = this.credentialResolverFactory.create(ctx.workflowId, args.connectionNodeId, stubConfig);\n return {\n ...ctx,\n nodeId: args.connectionNodeId,\n getCredential,\n };\n }\n}\n","import type { CredentialSessionService, Item, Items, NodeExecutionContext } from \"@codemation/core\";\nimport { injectable } from \"@codemation/core\";\n\nimport { DynamicStructuredTool } from \"@langchain/core/tools\";\n\nimport { ConnectionCredentialExecutionContextFactory } from \"./ConnectionCredentialExecutionContextFactory\";\nimport type { ResolvedTool } from \"./aiAgentSupport.types\";\n\n/**\n * LangChain adapters and credential context wiring for {@link AIAgentNode}.\n * Lives in a `*Factory.ts` composition-root module so construction stays explicit and testable.\n */\n@injectable()\nexport class AIAgentExecutionHelpersFactory {\n createConnectionCredentialExecutionContextFactory(\n credentialSessions: CredentialSessionService,\n ): ConnectionCredentialExecutionContextFactory {\n return new ConnectionCredentialExecutionContextFactory(credentialSessions);\n }\n\n createDynamicStructuredTool(\n entry: ResolvedTool,\n toolCredentialContext: NodeExecutionContext<any>,\n item: Item,\n itemIndex: number,\n items: Items,\n ): DynamicStructuredTool {\n return new DynamicStructuredTool({\n name: entry.config.name,\n description: entry.config.description ?? entry.runtime.defaultDescription,\n schema: entry.runtime.inputSchema,\n func: async (input) => {\n const result = await entry.runtime.execute({\n config: entry.config,\n input,\n ctx: toolCredentialContext,\n item,\n itemIndex,\n items,\n });\n return JSON.stringify(result);\n },\n });\n }\n}\n","import type {\n MultiInputNode,\n Node,\n NodeExecutionContext,\n NodeOutputs,\n NodeResolver,\n NodeBackedToolConfig,\n ToolExecuteArgs,\n ZodSchemaAny,\n} from \"@codemation/core\";\nimport { CoreTokens, inject, injectable } from \"@codemation/core\";\n\n@injectable()\nexport class NodeBackedToolRuntime {\n constructor(\n @inject(CoreTokens.NodeResolver)\n private readonly nodeResolver: NodeResolver,\n ) {}\n\n async execute(\n config: NodeBackedToolConfig<any, ZodSchemaAny, ZodSchemaAny>,\n args: ToolExecuteArgs,\n ): Promise<unknown> {\n const nodeInput = config.toNodeItem({\n input: args.input,\n item: args.item,\n itemIndex: args.itemIndex,\n items: args.items,\n ctx: args.ctx,\n node: config.node,\n });\n const nodeCtx = {\n ...args.ctx,\n config: config.node,\n } as NodeExecutionContext<any>;\n const resolvedNode = this.nodeResolver.resolve(config.node.type);\n const outputs = await this.executeResolvedNode(resolvedNode, nodeInput, nodeCtx);\n return config.toToolOutput({\n input: args.input,\n item: args.item,\n itemIndex: args.itemIndex,\n items: args.items,\n ctx: args.ctx,\n node: config.node,\n outputs,\n });\n }\n\n private async executeResolvedNode(\n resolvedNode: unknown,\n nodeInput: ToolExecuteArgs[\"item\"],\n ctx: NodeExecutionContext<any>,\n ): Promise<NodeOutputs> {\n if (this.isMultiInputNode(resolvedNode)) {\n return await resolvedNode.executeMulti({ in: [nodeInput] }, ctx);\n }\n if (this.isNode(resolvedNode)) {\n return await resolvedNode.execute([nodeInput], ctx);\n }\n throw new Error(`Node-backed tool expected a runnable node instance for \"${ctx.config.name ?? ctx.nodeId}\".`);\n }\n\n private isNode(value: unknown): value is Node<any> {\n return typeof value === \"object\" && value !== null && \"execute\" in value;\n }\n\n private isMultiInputNode(value: unknown): value is MultiInputNode<any> {\n return typeof value === \"object\" && value !== null && \"executeMulti\" in value;\n }\n}\n","import type {\n AgentToolCall,\n Item,\n NodeInputsByPort,\n ToolConfig,\n ToolExecuteArgs,\n ZodSchemaAny,\n} from \"@codemation/core\";\nimport type { DynamicStructuredTool } from \"@langchain/core/tools\";\n\nexport class AgentItemPortMap {\n static fromItem(item: Item): NodeInputsByPort {\n return { in: [item] };\n }\n}\n\nexport type ResolvedTool = Readonly<{\n config: ToolConfig;\n runtime: Readonly<{\n defaultDescription: string;\n inputSchema: ZodSchemaAny;\n execute(args: ToolExecuteArgs<ToolConfig, unknown>): Promise<unknown>;\n }>;\n}>;\n\nexport type ItemScopedToolBinding = Readonly<{\n config: ToolConfig;\n langChainTool: DynamicStructuredTool;\n}>;\n\nexport type PlannedToolCall = Readonly<{\n binding: ItemScopedToolBinding;\n toolCall: AgentToolCall;\n invocationIndex: number;\n nodeId: string;\n}>;\n\nexport type ExecutedToolCall = Readonly<{\n toolName: string;\n toolCallId: string;\n result: unknown;\n serialized: string;\n}>;\n","import type {\n AgentGuardrailConfig,\n AgentToolCall,\n ChatModelConfig,\n ChatModelFactory,\n Item,\n Items,\n JsonValue,\n LangChainChatModelLike,\n Node,\n NodeExecutionContext,\n NodeInputsByPort,\n NodeOutputs,\n Tool,\n ToolConfig,\n ZodSchemaAny,\n} from \"@codemation/core\";\n\nimport type { CredentialSessionService } from \"@codemation/core\";\nimport {\n AgentGuardrailDefaults,\n AgentMessageConfigNormalizer,\n ConnectionInvocationIdFactory,\n ConnectionNodeIdFactory,\n CoreTokens,\n NodeBackedToolConfig,\n inject,\n node,\n type NodeResolver,\n} from \"@codemation/core\";\n\nimport { AIMessage, type BaseMessage } from \"@langchain/core/messages\";\n\nimport type { AIAgent } from \"./AIAgentConfig\";\nimport { AIAgentExecutionHelpersFactory } from \"./AIAgentExecutionHelpersFactory\";\nimport { ConnectionCredentialExecutionContextFactory } from \"./ConnectionCredentialExecutionContextFactory\";\nimport { AgentMessageFactory } from \"./AgentMessageFactory\";\nimport { AgentOutputFactory } from \"./AgentOutputFactory\";\nimport { AgentToolCallPortMap } from \"./AgentToolCallPortMapFactory\";\nimport { NodeBackedToolRuntime } from \"./NodeBackedToolRuntime\";\nimport {\n AgentItemPortMap,\n type ExecutedToolCall,\n type ItemScopedToolBinding,\n type PlannedToolCall,\n type ResolvedTool,\n} from \"./aiAgentSupport.types\";\n\ntype ResolvedGuardrails = Required<Pick<AgentGuardrailConfig, \"maxTurns\" | \"onTurnLimitReached\">> &\n Pick<AgentGuardrailConfig, \"modelInvocationOptions\">;\n\n/** Everything needed to run the agent loop for a workflow execution (one `execute` call). */\ninterface PreparedAgentExecution {\n readonly ctx: NodeExecutionContext<AIAgent<any, any>>;\n readonly model: LangChainChatModelLike;\n readonly resolvedTools: ReadonlyArray<ResolvedTool>;\n readonly guardrails: ResolvedGuardrails;\n readonly languageModelConnectionNodeId: string;\n}\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class AIAgentNode implements Node<AIAgent<any, any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n private readonly connectionCredentialExecutionContextFactory: ConnectionCredentialExecutionContextFactory;\n\n constructor(\n @inject(CoreTokens.NodeResolver)\n private readonly nodeResolver: NodeResolver,\n @inject(CoreTokens.CredentialSessionService)\n credentialSessions: CredentialSessionService,\n @inject(NodeBackedToolRuntime)\n private readonly nodeBackedToolRuntime: NodeBackedToolRuntime,\n @inject(AIAgentExecutionHelpersFactory)\n private readonly executionHelpers: AIAgentExecutionHelpersFactory,\n ) {\n this.connectionCredentialExecutionContextFactory =\n this.executionHelpers.createConnectionCredentialExecutionContextFactory(credentialSessions);\n }\n\n async execute(items: Items, ctx: NodeExecutionContext<AIAgent<any, any>>): Promise<NodeOutputs> {\n const prepared = await this.prepareExecution(ctx);\n const out: Item[] = [];\n for (let i = 0; i < items.length; i++) {\n out.push(await this.runAgentForItem(prepared, items[i]!, i, items));\n }\n return { main: out };\n }\n\n /**\n * Resolves the chat model and tools once, then returns shared state for every item in the batch.\n */\n private async prepareExecution(ctx: NodeExecutionContext<AIAgent<any, any>>): Promise<PreparedAgentExecution> {\n const chatModelFactory = this.nodeResolver.resolve(ctx.config.chatModel.type) as ChatModelFactory<ChatModelConfig>;\n const languageModelCredentialContext = this.connectionCredentialExecutionContextFactory.forConnectionNode(ctx, {\n connectionNodeId: ConnectionNodeIdFactory.languageModelConnectionNodeId(ctx.nodeId),\n getCredentialRequirements: () => ctx.config.chatModel.getCredentialRequirements?.() ?? [],\n });\n const model = await Promise.resolve(\n chatModelFactory.create({ config: ctx.config.chatModel, ctx: languageModelCredentialContext }),\n );\n return {\n ctx,\n model,\n resolvedTools: this.resolveTools(ctx.config.tools ?? []),\n guardrails: this.resolveGuardrails(ctx.config.guardrails),\n languageModelConnectionNodeId: ConnectionNodeIdFactory.languageModelConnectionNodeId(ctx.nodeId),\n };\n }\n\n /**\n * One item: build prompts, optionally bind tools, run the multi-turn loop, map the final model message to workflow JSON.\n */\n private async runAgentForItem(\n prepared: PreparedAgentExecution,\n item: Item,\n itemIndex: number,\n items: Items,\n ): Promise<Item> {\n const { ctx } = prepared;\n const itemInputsByPort = AgentItemPortMap.fromItem(item);\n const itemScopedTools = this.createItemScopedTools(prepared.resolvedTools, ctx, item, itemIndex, items);\n const conversation: BaseMessage[] = [...this.createPromptMessages(item, itemIndex, items, ctx)];\n const modelWithTools = this.bindToolsToModel(prepared.model, itemScopedTools);\n const finalResponse = await this.runTurnLoopUntilFinalAnswer({\n prepared,\n itemInputsByPort,\n itemScopedTools,\n conversation,\n modelWithTools,\n });\n return this.buildOutputItem(item, finalResponse);\n }\n\n /**\n * Repeatedly invokes the model until it returns without tool calls, or guardrails end the loop.\n */\n private async runTurnLoopUntilFinalAnswer(args: {\n prepared: PreparedAgentExecution;\n itemInputsByPort: NodeInputsByPort;\n itemScopedTools: ReadonlyArray<ItemScopedToolBinding>;\n conversation: BaseMessage[];\n modelWithTools: LangChainChatModelLike;\n }): Promise<AIMessage> {\n const { prepared, itemInputsByPort, itemScopedTools, conversation, modelWithTools } = args;\n const { ctx, guardrails, languageModelConnectionNodeId } = prepared;\n\n let finalResponse: AIMessage | undefined;\n\n for (let turn = 1; turn <= guardrails.maxTurns; turn++) {\n const response = await this.invokeModel(\n modelWithTools,\n languageModelConnectionNodeId,\n conversation,\n ctx,\n itemInputsByPort,\n guardrails.modelInvocationOptions,\n );\n finalResponse = response;\n\n const toolCalls = AgentMessageFactory.extractToolCalls(response);\n if (toolCalls.length === 0) {\n break;\n }\n\n if (this.cannotExecuteAnotherToolRound(turn, guardrails)) {\n this.finishOrThrowWhenTurnCapHitWithToolCalls(ctx, guardrails);\n break;\n }\n\n const plannedToolCalls = this.planToolCalls(itemScopedTools, toolCalls, ctx.nodeId);\n await this.markQueuedTools(plannedToolCalls, ctx);\n const executedToolCalls = await this.executeToolCalls(plannedToolCalls, ctx);\n this.appendAssistantAndToolMessages(conversation, response, executedToolCalls);\n }\n\n if (!finalResponse) {\n throw new Error(`AIAgent \"${ctx.config.name ?? ctx.nodeId}\" did not produce a model response.`);\n }\n return finalResponse;\n }\n\n private cannotExecuteAnotherToolRound(turn: number, guardrails: ResolvedGuardrails): boolean {\n return turn >= guardrails.maxTurns;\n }\n\n private finishOrThrowWhenTurnCapHitWithToolCalls(\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n guardrails: ResolvedGuardrails,\n ): void {\n if (guardrails.onTurnLimitReached === \"respondWithLastMessage\") {\n return;\n }\n throw new Error(\n `AIAgent \"${ctx.config.name ?? ctx.nodeId}\" reached maxTurns=${guardrails.maxTurns} before producing a final response.`,\n );\n }\n\n private appendAssistantAndToolMessages(\n conversation: BaseMessage[],\n assistantMessage: AIMessage,\n executedToolCalls: ReadonlyArray<ExecutedToolCall>,\n ): void {\n conversation.push(\n assistantMessage,\n ...executedToolCalls.map((toolCall) =>\n AgentMessageFactory.createToolMessage(toolCall.toolCallId, toolCall.serialized),\n ),\n );\n }\n\n private buildOutputItem(item: Item, finalResponse: AIMessage): Item {\n return AgentOutputFactory.replaceJson(\n item,\n AgentOutputFactory.fromAgentContent(AgentMessageFactory.extractContent(finalResponse)),\n );\n }\n\n private bindToolsToModel(\n model: LangChainChatModelLike,\n itemScopedTools: ReadonlyArray<ItemScopedToolBinding>,\n ): LangChainChatModelLike {\n if (itemScopedTools.length === 0 || !model.bindTools) {\n return model;\n }\n return model.bindTools(itemScopedTools.map((entry) => entry.langChainTool));\n }\n\n private resolveTools(toolConfigs: ReadonlyArray<ToolConfig>): ReadonlyArray<ResolvedTool> {\n const resolvedTools = toolConfigs.map((config) => ({\n config,\n runtime: this.resolveToolRuntime(config),\n }));\n\n const names = new Set<string>();\n for (const entry of resolvedTools) {\n if (names.has(entry.config.name)) throw new Error(`Duplicate tool name on AIAgent: ${entry.config.name}`);\n names.add(entry.config.name);\n }\n return resolvedTools;\n }\n\n private createItemScopedTools(\n tools: ReadonlyArray<ResolvedTool>,\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n item: Item,\n itemIndex: number,\n items: Items,\n ): ReadonlyArray<ItemScopedToolBinding> {\n return tools.map((entry) => {\n const toolCredentialContext = this.connectionCredentialExecutionContextFactory.forConnectionNode(ctx, {\n connectionNodeId: ConnectionNodeIdFactory.toolConnectionNodeId(ctx.nodeId, entry.config.name),\n getCredentialRequirements: () => entry.config.getCredentialRequirements?.() ?? [],\n });\n const langChainTool = this.executionHelpers.createDynamicStructuredTool(\n entry,\n toolCredentialContext,\n item,\n itemIndex,\n items,\n );\n\n return { config: entry.config, langChainTool };\n });\n }\n\n private async invokeModel(\n model: LangChainChatModelLike,\n nodeId: string,\n messages: ReadonlyArray<BaseMessage>,\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n inputsByPort: NodeInputsByPort,\n options?: AgentGuardrailConfig[\"modelInvocationOptions\"],\n ): Promise<AIMessage> {\n await ctx.nodeState?.markQueued({ nodeId, activationId: ctx.activationId, inputsByPort });\n await ctx.nodeState?.markRunning({ nodeId, activationId: ctx.activationId, inputsByPort });\n try {\n const response = (await model.invoke(messages, options)) as AIMessage;\n await ctx.nodeState?.markCompleted({\n nodeId,\n activationId: ctx.activationId,\n inputsByPort,\n outputs: AgentOutputFactory.fromUnknown({\n content: AgentMessageFactory.extractContent(response),\n }),\n });\n const content = AgentMessageFactory.extractContent(response);\n await ctx.nodeState?.appendConnectionInvocation({\n invocationId: ConnectionInvocationIdFactory.create(),\n connectionNodeId: nodeId,\n parentAgentNodeId: ctx.nodeId,\n parentAgentActivationId: ctx.activationId,\n status: \"completed\",\n managedInput: this.summarizeLlmMessages(messages),\n managedOutput: content,\n finishedAt: new Date().toISOString(),\n });\n return response;\n } catch (error) {\n throw await this.failTrackedNodeInvocation(error, nodeId, ctx, inputsByPort, this.summarizeLlmMessages(messages));\n }\n }\n\n private async markQueuedTools(\n plannedToolCalls: ReadonlyArray<PlannedToolCall>,\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n ): Promise<void> {\n for (const plannedToolCall of plannedToolCalls) {\n await ctx.nodeState?.markQueued({\n nodeId: plannedToolCall.nodeId,\n activationId: ctx.activationId,\n inputsByPort: AgentToolCallPortMap.fromInput(plannedToolCall.toolCall.input ?? {}),\n });\n }\n }\n\n private async executeToolCalls(\n plannedToolCalls: ReadonlyArray<PlannedToolCall>,\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n ): Promise<ReadonlyArray<ExecutedToolCall>> {\n const results = await Promise.allSettled(\n plannedToolCalls.map(async (plannedToolCall) => {\n const toolCallInputsByPort = AgentToolCallPortMap.fromInput(plannedToolCall.toolCall.input ?? {});\n await ctx.nodeState?.markRunning({\n nodeId: plannedToolCall.nodeId,\n activationId: ctx.activationId,\n inputsByPort: toolCallInputsByPort,\n });\n try {\n const serialized = await plannedToolCall.binding.langChainTool.invoke(plannedToolCall.toolCall.input ?? {});\n const result = this.parseToolOutput(serialized);\n await ctx.nodeState?.markCompleted({\n nodeId: plannedToolCall.nodeId,\n activationId: ctx.activationId,\n inputsByPort: toolCallInputsByPort,\n outputs: AgentOutputFactory.fromUnknown(result),\n });\n await ctx.nodeState?.appendConnectionInvocation({\n invocationId: ConnectionInvocationIdFactory.create(),\n connectionNodeId: plannedToolCall.nodeId,\n parentAgentNodeId: ctx.nodeId,\n parentAgentActivationId: ctx.activationId,\n status: \"completed\",\n managedInput: this.toolCallInputToJson(plannedToolCall.toolCall.input),\n managedOutput: this.resultToJsonValue(result),\n finishedAt: new Date().toISOString(),\n });\n return {\n toolName: plannedToolCall.binding.config.name,\n toolCallId: plannedToolCall.toolCall.id ?? plannedToolCall.binding.config.name,\n serialized,\n result,\n } satisfies ExecutedToolCall;\n } catch (error) {\n throw await this.failTrackedNodeInvocation(\n error,\n plannedToolCall.nodeId,\n ctx,\n toolCallInputsByPort,\n this.toolCallInputToJson(plannedToolCall.toolCall.input),\n );\n }\n }),\n );\n\n const rejected = results.find((result) => result.status === \"rejected\");\n if (rejected?.status === \"rejected\") {\n throw rejected.reason instanceof Error ? rejected.reason : new Error(String(rejected.reason));\n }\n\n return results\n .filter((result): result is PromiseFulfilledResult<ExecutedToolCall> => result.status === \"fulfilled\")\n .map((result) => result.value);\n }\n\n private planToolCalls(\n bindings: ReadonlyArray<ItemScopedToolBinding>,\n toolCalls: ReadonlyArray<AgentToolCall>,\n parentNodeId: string,\n ): ReadonlyArray<PlannedToolCall> {\n const invocationCountByToolName = new Map<string, number>();\n return toolCalls.map((toolCall) => {\n const binding = bindings.find((entry) => entry.config.name === toolCall.name);\n if (!binding) throw new Error(`Unknown tool requested by model: ${toolCall.name}`);\n const invocationIndex = (invocationCountByToolName.get(binding.config.name) ?? 0) + 1;\n invocationCountByToolName.set(binding.config.name, invocationIndex);\n return {\n binding,\n toolCall,\n invocationIndex,\n nodeId: ConnectionNodeIdFactory.toolConnectionNodeId(parentNodeId, binding.config.name),\n } satisfies PlannedToolCall;\n });\n }\n\n private parseToolOutput(serialized: unknown): unknown {\n if (typeof serialized !== \"string\") return serialized;\n try {\n return JSON.parse(serialized);\n } catch {\n return serialized;\n }\n }\n\n private async failTrackedNodeInvocation(\n error: unknown,\n nodeId: string,\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n inputsByPort: NodeInputsByPort,\n managedInput?: JsonValue,\n ): Promise<Error> {\n const effectiveError = error instanceof Error ? error : new Error(String(error));\n await ctx.nodeState?.markFailed({\n nodeId,\n activationId: ctx.activationId,\n inputsByPort,\n error: effectiveError,\n });\n await ctx.nodeState?.appendConnectionInvocation({\n invocationId: ConnectionInvocationIdFactory.create(),\n connectionNodeId: nodeId,\n parentAgentNodeId: ctx.nodeId,\n parentAgentActivationId: ctx.activationId,\n status: \"failed\",\n managedInput,\n error: {\n message: effectiveError.message,\n name: effectiveError.name,\n stack: effectiveError.stack,\n },\n finishedAt: new Date().toISOString(),\n });\n return effectiveError;\n }\n\n private summarizeLlmMessages(messages: ReadonlyArray<BaseMessage>): JsonValue {\n const last = messages[messages.length - 1];\n const preview =\n typeof last?.content === \"string\"\n ? last.content\n : last?.content !== undefined\n ? JSON.stringify(last.content)\n : \"\";\n return {\n messageCount: messages.length,\n lastMessagePreview: preview.slice(0, 4000),\n };\n }\n\n private toolCallInputToJson(input: unknown): JsonValue | undefined {\n return this.resultToJsonValue(input);\n }\n\n private resultToJsonValue(value: unknown): JsonValue | undefined {\n if (value === undefined) {\n return undefined;\n }\n const json = JSON.stringify(value);\n return JSON.parse(json) as JsonValue;\n }\n\n private createPromptMessages(\n item: Item,\n itemIndex: number,\n items: Items,\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n ): ReadonlyArray<BaseMessage> {\n return AgentMessageFactory.createPromptMessages(\n AgentMessageConfigNormalizer.normalize(ctx.config, {\n item,\n itemIndex,\n items,\n ctx,\n }),\n );\n }\n\n private resolveToolRuntime(config: ToolConfig): ResolvedTool[\"runtime\"] {\n if (config instanceof NodeBackedToolConfig) {\n return {\n defaultDescription: `Run workflow node \"${config.node.name ?? config.name}\" as an AI tool.`,\n inputSchema: config.getInputSchema(),\n execute: async (args) => await this.nodeBackedToolRuntime.execute(config, args),\n };\n }\n const tool = this.nodeResolver.resolve(config.type) as Tool<ToolConfig, ZodSchemaAny, ZodSchemaAny>;\n return {\n defaultDescription: tool.defaultDescription,\n inputSchema: tool.inputSchema,\n execute: async (args) => await Promise.resolve(tool.execute(args)),\n };\n }\n\n private resolveGuardrails(guardrails: AgentGuardrailConfig | undefined): ResolvedGuardrails {\n const maxTurns = guardrails?.maxTurns ?? AgentGuardrailDefaults.maxTurns;\n if (!Number.isInteger(maxTurns) || maxTurns < 1) {\n throw new Error(`AIAgent maxTurns must be a positive integer. Received: ${String(maxTurns)}`);\n }\n return {\n maxTurns,\n onTurnLimitReached: guardrails?.onTurnLimitReached ?? AgentGuardrailDefaults.onTurnLimitReached,\n modelInvocationOptions: guardrails?.modelInvocationOptions,\n };\n }\n}\n","import {\n RetryPolicy,\n type AgentGuardrailConfig,\n type AgentMessageConfig,\n type AgentNodeConfig,\n type ChatModelConfig,\n type RetryPolicySpec,\n type RunnableNodeConfig,\n type ToolConfig,\n type TypeToken,\n} from \"@codemation/core\";\n\nimport { AIAgentNode } from \"./AIAgentNode\";\n\nexport interface AIAgentOptions<TInputJson = unknown, _TOutputJson = unknown> {\n readonly name: string;\n readonly messages: AgentMessageConfig<TInputJson>;\n readonly chatModel: ChatModelConfig;\n readonly tools?: ReadonlyArray<ToolConfig>;\n readonly id?: string;\n readonly retryPolicy?: RetryPolicySpec;\n readonly guardrails?: AgentGuardrailConfig;\n}\n\n/**\n * AI agent: credential bindings are keyed to connection-owned LLM/tool node ids (ConnectionNodeIdFactory),\n * not to the agent workflow node id.\n */\nexport class AIAgent<TInputJson = unknown, TOutputJson = unknown>\n implements RunnableNodeConfig<TInputJson, TOutputJson>, AgentNodeConfig<TInputJson, TOutputJson>\n{\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = AIAgentNode;\n readonly execution = { hint: \"local\" } as const;\n readonly icon = \"lucide:bot\" as const;\n readonly name: string;\n readonly messages: AgentMessageConfig<TInputJson>;\n readonly chatModel: ChatModelConfig;\n readonly tools: ReadonlyArray<ToolConfig>;\n readonly id?: string;\n readonly retryPolicy: RetryPolicySpec;\n readonly guardrails?: AgentGuardrailConfig;\n\n constructor(options: AIAgentOptions<TInputJson, TOutputJson>) {\n this.name = options.name;\n this.messages = options.messages;\n this.chatModel = options.chatModel;\n this.tools = options.tools ?? [];\n this.id = options.id;\n this.retryPolicy = options.retryPolicy ?? RetryPolicy.defaultForAiAgent;\n this.guardrails = options.guardrails;\n }\n}\n","import type { Items, NodeOutputs } from \"@codemation/core\";\n\nexport class CallbackResultNormalizer {\n static toNodeOutputs(result: Items | void, items: Items): NodeOutputs {\n return { main: result ?? items };\n }\n}\n","import type { Items, Node, NodeExecutionContext, NodeOutputs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport { Callback } from \"./CallbackNodeFactory\";\nimport { CallbackResultNormalizer } from \"./CallbackResultNormalizerFactory\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class CallbackNode implements Node<Callback<any, any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n async execute(items: Items, ctx: NodeExecutionContext<Callback<any, any>>): Promise<NodeOutputs> {\n const result = await ctx.config.callback(items, ctx);\n return CallbackResultNormalizer.toNodeOutputs(result, items);\n }\n}\n","import type { Items, NodeExecutionContext, RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { CallbackNode } from \"./CallbackNode\";\n\nexport type CallbackHandler<\n TInputJson = unknown,\n TOutputJson = TInputJson,\n TConfig extends Callback<TInputJson, TOutputJson> = Callback<TInputJson, TOutputJson>,\n> = (\n items: Items<TInputJson>,\n ctx: NodeExecutionContext<TConfig>,\n) => Promise<Items<TOutputJson> | void> | Items<TOutputJson> | void;\n\nexport class Callback<TInputJson = unknown, TOutputJson = TInputJson> implements RunnableNodeConfig<\n TInputJson,\n TOutputJson\n> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = CallbackNode;\n readonly execution = { hint: \"local\" } as const;\n readonly icon = \"lucide:braces\" as const;\n\n constructor(\n public readonly name: string = \"Callback\",\n public readonly callback: CallbackHandler<TInputJson, TOutputJson> = Callback.defaultCallback as CallbackHandler<\n TInputJson,\n TOutputJson\n >,\n public readonly id?: string,\n ) {}\n\n private static defaultCallback<TItemJson>(items: Items<TItemJson>): Items<TItemJson> {\n return items;\n }\n}\n\nexport { CallbackNode } from \"./CallbackNode\";\nexport { CallbackResultNormalizer } from \"./CallbackResultNormalizerFactory\";\n","import type { Item, Items, Node, NodeExecutionContext, NodeOutputs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport type { HttpRequestDownloadMode } from \"./httpRequest\";\nimport { HttpRequest } from \"./httpRequest\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class HttpRequestNode implements Node<HttpRequest<any, any>> {\n readonly kind = \"node\" as const;\n readonly outputPorts = [\"main\"] as const;\n\n async execute(items: Items, ctx: NodeExecutionContext<HttpRequest<any, any>>): Promise<NodeOutputs> {\n const output: Item[] = [];\n for (const item of items) {\n output.push(await this.executeItem(item, ctx));\n }\n return { main: output };\n }\n\n private async executeItem(item: Item, ctx: NodeExecutionContext<HttpRequest<any, any>>): Promise<Item> {\n const url = this.resolveUrl(item, ctx);\n const response = await fetch(url, {\n method: ctx.config.method,\n });\n const headers = this.readHeaders(response.headers);\n const mimeType = this.resolveMimeType(headers);\n const bodyBinaryName = ctx.config.binaryName;\n const shouldAttachBody = this.shouldAttachBody(ctx.config.downloadMode, mimeType);\n const outputJson: Readonly<Record<string, unknown>> = {\n url,\n method: ctx.config.method,\n ok: response.ok,\n status: response.status,\n statusText: response.statusText,\n mimeType,\n headers,\n ...(shouldAttachBody ? { bodyBinaryName } : {}),\n };\n\n let outputItem: Item = {\n json: outputJson,\n };\n if (!shouldAttachBody) {\n return outputItem;\n }\n\n const attachment = await ctx.binary.attach({\n name: bodyBinaryName,\n body: response.body\n ? (response.body as unknown as Parameters<typeof ctx.binary.attach>[0][\"body\"])\n : new Uint8Array(await response.arrayBuffer()),\n mimeType,\n filename: this.resolveFilename(url, headers),\n });\n outputItem = ctx.binary.withAttachment(outputItem, bodyBinaryName, attachment);\n return outputItem;\n }\n\n private resolveUrl(item: Item, ctx: NodeExecutionContext<HttpRequest<any, any>>): string {\n const json = this.asRecord(item.json);\n const candidate = json[ctx.config.urlField];\n if (typeof candidate !== \"string\" || candidate.trim() === \"\") {\n throw new Error(`HttpRequest node expected item.json.${ctx.config.urlField} to contain a URL string.`);\n }\n return candidate;\n }\n\n private asRecord(value: unknown): Readonly<Record<string, unknown>> {\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n return value as Readonly<Record<string, unknown>>;\n }\n return { input: value };\n }\n\n private readHeaders(headers: Headers): Readonly<Record<string, string>> {\n const values: Record<string, string> = {};\n headers.forEach((value, key) => {\n values[key] = value;\n });\n return values;\n }\n\n private resolveMimeType(headers: Readonly<Record<string, string>>): string {\n const contentType = headers[\"content-type\"];\n if (!contentType) {\n return \"application/octet-stream\";\n }\n return contentType.split(\";\")[0]?.trim() || \"application/octet-stream\";\n }\n\n private shouldAttachBody(mode: HttpRequestDownloadMode, mimeType: string): boolean {\n if (mode === \"always\") {\n return true;\n }\n if (mode === \"never\") {\n return false;\n }\n return mimeType.startsWith(\"image/\") || mimeType.startsWith(\"audio/\") || mimeType.startsWith(\"video/\");\n }\n\n private resolveFilename(url: string, headers: Readonly<Record<string, string>>): string | undefined {\n const contentDisposition = headers[\"content-disposition\"];\n const fromDisposition = this.readFilenameFromContentDisposition(contentDisposition);\n if (fromDisposition) {\n return fromDisposition;\n }\n const pathname = new URL(url).pathname;\n const value = pathname.split(\"/\").at(-1);\n return value && value.trim() ? value : undefined;\n }\n\n private readFilenameFromContentDisposition(value: string | undefined): string | undefined {\n if (!value) {\n return undefined;\n }\n const parts = value.split(\";\");\n for (const part of parts) {\n const trimmed = part.trim();\n if (!trimmed.startsWith(\"filename=\")) {\n continue;\n }\n return trimmed.slice(\"filename=\".length).replace(/^\"|\"$/g, \"\");\n }\n return undefined;\n }\n}\n","import { RetryPolicy, type RetryPolicySpec, type RunnableNodeConfig, type TypeToken } from \"@codemation/core\";\n\nimport { HttpRequestNode } from \"./HttpRequestNodeFactory\";\n\nexport type HttpRequestDownloadMode = \"auto\" | \"always\" | \"never\";\n\n/** JSON emitted by {@link HttpRequest} — response metadata only (input item fields are not passed through). */\nexport type HttpRequestOutputJson = Readonly<{\n url: string;\n method: string;\n ok: boolean;\n status: number;\n statusText: string;\n mimeType: string;\n headers: Readonly<Record<string, string>>;\n bodyBinaryName?: string;\n}>;\n\nexport class HttpRequest<\n TInputJson = Readonly<{ url?: string }>,\n TOutputJson = HttpRequestOutputJson,\n> implements RunnableNodeConfig<TInputJson, TOutputJson> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = HttpRequestNode;\n readonly execution = { hint: \"local\" } as const;\n\n constructor(\n public readonly name: string,\n public readonly args: Readonly<{\n method?: string;\n urlField?: string;\n binaryName?: string;\n downloadMode?: HttpRequestDownloadMode;\n id?: string;\n }> = {},\n public readonly retryPolicy: RetryPolicySpec = RetryPolicy.defaultForHttp,\n ) {}\n\n get id(): string | undefined {\n return this.args.id;\n }\n\n get method(): string {\n return (this.args.method ?? \"GET\").toUpperCase();\n }\n\n get urlField(): string {\n return this.args.urlField ?? \"url\";\n }\n\n get binaryName(): string {\n return this.args.binaryName ?? \"body\";\n }\n\n get downloadMode(): HttpRequestDownloadMode {\n return this.args.downloadMode ?? \"auto\";\n }\n}\n\nexport { HttpRequestNode } from \"./HttpRequestNodeFactory\";\n","import type { Item, Items, Node, NodeExecutionContext, NodeOutputs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport { If } from \"./if\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class IfNode implements Node<If<any>> {\n kind = \"node\" as const;\n outputPorts = [\"true\", \"false\"] as const;\n\n async execute(items: Items, ctx: NodeExecutionContext<If<any>>): Promise<NodeOutputs> {\n const t: Item[] = [];\n const f: Item[] = [];\n for (let i = 0; i < items.length; i++) {\n const item = items[i] as Item<unknown>;\n const metaBase = (\n item.meta && typeof item.meta === \"object\" ? (item.meta as Record<string, unknown>) : {}\n ) as Record<string, unknown>;\n const cmBase =\n metaBase._cm && typeof metaBase._cm === \"object\"\n ? (metaBase._cm as Record<string, unknown>)\n : ({} as Record<string, unknown>);\n const originIndex = typeof cmBase.originIndex === \"number\" ? (cmBase.originIndex as number) : i;\n const tagged: Item = {\n ...item,\n meta: { ...metaBase, _cm: { ...cmBase, originIndex } },\n paired: [{ nodeId: ctx.nodeId, output: \"$in\", itemIndex: originIndex }, ...(item.paired ?? [])],\n };\n const ok = ctx.config.predicate(item, i, items, ctx);\n (ok ? t : f).push(tagged);\n }\n return { true: t, false: f };\n }\n}\n","import type { Item, Items, NodeExecutionContext, RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { IfNode } from \"./IfNode\";\n\nexport class If<TInputJson = unknown> implements RunnableNodeConfig<TInputJson, TInputJson> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = IfNode;\n readonly execution = { hint: \"local\" } as const;\n readonly icon = \"lucide:split\" as const;\n constructor(\n public readonly name: string,\n public readonly predicate: (\n item: Item<TInputJson>,\n index: number,\n items: Items<TInputJson>,\n ctx: NodeExecutionContext<If<TInputJson>>,\n ) => boolean,\n public readonly id?: string,\n ) {}\n}\n\nexport { IfNode } from \"./IfNode\";\n","import type {\n Items,\n NodeExecutionContext,\n NodeOutputs,\n TestableTriggerNode,\n TriggerSetupContext,\n TriggerTestItemsContext,\n} from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport { ManualTrigger } from \"./ManualTriggerFactory\";\n\n/**\n * Setup is intentionally a no-op: the engine host can run workflows manually\n * by calling `engine.runWorkflow(workflow, triggerNodeId, items)`.\n */\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class ManualTriggerNode implements TestableTriggerNode<ManualTrigger<any>> {\n kind = \"trigger\" as const;\n outputPorts = [\"main\"] as const;\n async setup(_ctx: TriggerSetupContext<ManualTrigger<any>>): Promise<undefined> {\n return undefined;\n }\n\n async getTestItems(ctx: TriggerTestItemsContext<ManualTrigger<any>>): Promise<Items> {\n return this.resolveManualItems([], ctx.config);\n }\n\n async execute(items: Items, ctx: NodeExecutionContext<ManualTrigger<any>>): Promise<NodeOutputs> {\n return { main: this.resolveManualItems(items, ctx.config) };\n }\n\n private resolveManualItems(items: Items, config: ManualTrigger<any>): Items {\n return items.length > 0 ? items : (config.defaultItems ?? []);\n }\n}\n","import type { Items, TriggerNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { ItemsInputNormalizer } from \"@codemation/core\";\n\nimport { ManualTriggerNode } from \"./ManualTriggerNode\";\n\ntype ManualTriggerDefaultValue<TOutputJson> = Items<TOutputJson> | ReadonlyArray<TOutputJson> | TOutputJson;\n\nexport class ManualTrigger<TOutputJson = unknown> implements TriggerNodeConfig<TOutputJson> {\n private static readonly itemsInputNormalizer = new ItemsInputNormalizer();\n readonly kind = \"trigger\" as const;\n readonly type: TypeToken<unknown> = ManualTriggerNode;\n readonly icon = \"lucide:play\" as const;\n readonly defaultItems?: Items<TOutputJson>;\n readonly id?: string;\n /** Manual runs often emit an empty batch; still schedule downstream by default. */\n readonly continueWhenEmptyOutput = true as const;\n\n constructor(name?: string, id?: string);\n constructor(name: string, defaultItems: ManualTriggerDefaultValue<TOutputJson>, id?: string);\n constructor(\n public readonly name: string = \"Manual trigger\",\n defaultItemsOrId?: ManualTriggerDefaultValue<TOutputJson> | string,\n id?: string,\n ) {\n this.defaultItems = ManualTrigger.resolveDefaultItems(defaultItemsOrId);\n this.id = ManualTrigger.resolveId(defaultItemsOrId, id);\n }\n\n private static resolveDefaultItems<TOutputJson>(\n value: ManualTriggerDefaultValue<TOutputJson> | string | undefined,\n ): Items<TOutputJson> | undefined {\n if (typeof value === \"string\" || value === undefined) {\n return undefined;\n }\n return this.itemsInputNormalizer.normalize(value) as Items<TOutputJson>;\n }\n\n private static resolveId<TOutputJson>(\n value: ManualTriggerDefaultValue<TOutputJson> | string | undefined,\n id: string | undefined,\n ): string | undefined {\n return typeof value === \"string\" ? value : id;\n }\n}\n\nexport { ManualTriggerNode } from \"./ManualTriggerNode\";\n","import type { Item, Items, Node, NodeExecutionContext, NodeOutputs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport { MapData } from \"./mapData\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class MapDataNode implements Node<MapData<any, any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n async execute(items: Items, ctx: NodeExecutionContext<MapData<any, any>>): Promise<NodeOutputs> {\n const out: Item[] = [];\n for (let i = 0; i < items.length; i++) {\n const item = items[i] as Item<unknown>;\n out.push({ ...item, json: ctx.config.map(item, ctx) });\n }\n return { main: out };\n }\n}\n","import type { Item, NodeExecutionContext, RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { MapDataNode } from \"./MapDataNode\";\n\nexport class MapData<TInputJson = unknown, TOutputJson = unknown> implements RunnableNodeConfig<\n TInputJson,\n TOutputJson\n> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = MapDataNode;\n readonly execution = { hint: \"local\" } as const;\n /** Zero mapped items should still allow downstream nodes to run. */\n readonly continueWhenEmptyOutput = true as const;\n constructor(\n public readonly name: string,\n public readonly map: (\n item: Item<TInputJson>,\n ctx: NodeExecutionContext<MapData<TInputJson, TOutputJson>>,\n ) => TOutputJson,\n public readonly id?: string,\n ) {}\n}\n\nexport { MapDataNode } from \"./MapDataNode\";\n","import type { InputPortKey, Item, Items } from \"@codemation/core\";\n\nexport function getOriginIndex(item: Item): number | undefined {\n const meta = item.meta as Record<string, unknown> | undefined;\n const cm = meta?._cm as Record<string, unknown> | undefined;\n const v = cm?.originIndex;\n return typeof v === \"number\" && Number.isFinite(v) ? v : undefined;\n}\n\nexport function orderedInputs(\n inputsByPort: Readonly<Record<InputPortKey, Items>>,\n prefer?: ReadonlyArray<InputPortKey>,\n): InputPortKey[] {\n const keys = Object.keys(inputsByPort);\n const preferred = (prefer ?? []).filter((k) => keys.includes(k));\n const rest = keys.filter((k) => !preferred.includes(k)).sort();\n return [...preferred, ...rest];\n}\n","import type { InputPortKey, Item, Items, MultiInputNode, NodeExecutionContext, NodeOutputs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport type { Merge } from \"./merge\";\nimport { getOriginIndex, orderedInputs } from \"./mergeExecutionUtils.types\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class MergeNode implements MultiInputNode<Merge<any, any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n async executeMulti(\n inputsByPort: Readonly<Record<InputPortKey, Items>>,\n ctx: NodeExecutionContext<Merge<any, any>>,\n ): Promise<NodeOutputs> {\n const order = orderedInputs(inputsByPort, ctx.config.cfg.prefer);\n\n if (ctx.config.cfg.mode === \"append\") {\n const out: Item[] = [];\n for (const k of order) out.push(...(inputsByPort[k] ?? []));\n return { main: out };\n }\n\n if (ctx.config.cfg.mode === \"mergeByPosition\") {\n let maxLen = 0;\n for (const k of order) maxLen = Math.max(maxLen, (inputsByPort[k] ?? []).length);\n\n const out: Item[] = [];\n for (let i = 0; i < maxLen; i++) {\n const json: Record<string, unknown> = {};\n const paired: any[] = [];\n let meta: Record<string, unknown> | undefined;\n\n for (const k of order) {\n const item = (inputsByPort[k] ?? [])[i];\n json[k] = item?.json;\n if (item?.paired) paired.push(...item.paired);\n if (!meta && item?.meta) meta = { ...(item.meta as any) };\n }\n\n const merged: any = { json };\n if (paired.length > 0) merged.paired = paired;\n if (meta) merged.meta = meta;\n out.push(merged as Item);\n }\n\n return { main: out };\n }\n\n // passThrough (default): for each origin index, take first available input (deterministic input precedence).\n const chosenByOrigin = new Map<number, Item>();\n const fallback: Item[] = [];\n\n for (const k of order) {\n for (const item of inputsByPort[k] ?? []) {\n const origin = getOriginIndex(item);\n if (origin === undefined) {\n fallback.push(item);\n continue;\n }\n if (!chosenByOrigin.has(origin)) chosenByOrigin.set(origin, item);\n }\n }\n\n const out: Item[] = [];\n const origins = Array.from(chosenByOrigin.keys()).sort((a, b) => a - b);\n for (const o of origins) out.push(chosenByOrigin.get(o)!);\n out.push(...fallback);\n\n return { main: out };\n }\n}\n","import type { InputPortKey, RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { MergeNode } from \"./MergeNode\";\n\nexport type MergeMode = \"passThrough\" | \"append\" | \"mergeByPosition\";\n\nexport class Merge<TInputJson = unknown, TOutputJson = TInputJson> implements RunnableNodeConfig<\n TInputJson,\n TOutputJson\n> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = MergeNode;\n readonly icon = \"lucide:git-merge\" as const;\n\n constructor(\n public readonly name: string,\n public readonly cfg: Readonly<{\n mode: MergeMode;\n /**\n * Deterministic input precedence order (only used for passThrough/append).\n * Any inputs not listed are appended in lexicographic order.\n */\n prefer?: ReadonlyArray<InputPortKey>;\n }> = { mode: \"passThrough\" },\n public readonly id?: string,\n ) {}\n}\n\nexport { MergeNode } from \"./MergeNode\";\n","import type { Items, Node, NodeExecutionContext, NodeOutputs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport { NoOp } from \"./noOp\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class NoOpNode implements Node<NoOp<any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n async execute(items: Items, _ctx: NodeExecutionContext<NoOp<any>>): Promise<NodeOutputs> {\n return { main: items };\n }\n}\n","import type { RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { NoOpNode } from \"./NoOpNode\";\n\nexport class NoOp<TItemJson = unknown> implements RunnableNodeConfig<TItemJson, TItemJson> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = NoOpNode;\n readonly execution = { hint: \"local\" } as const;\n\n constructor(\n public readonly name: string = \"NoOp\",\n public readonly id?: string,\n ) {}\n}\n\nexport { NoOpNode } from \"./NoOpNode\";\n","import type { Item, Items, Node, NodeExecutionContext, NodeOutputs, WorkflowRunnerService } from \"@codemation/core\";\n\nimport { CoreTokens, inject, node } from \"@codemation/core\";\n\nimport { SubWorkflow } from \"./subWorkflow\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class SubWorkflowNode implements Node<SubWorkflow<any, any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n constructor(\n @inject(CoreTokens.WorkflowRunnerService)\n private readonly workflows: WorkflowRunnerService,\n ) {}\n\n async execute(items: Items, ctx: NodeExecutionContext<SubWorkflow<any, any>>): Promise<NodeOutputs> {\n const out: Item[] = [];\n for (let i = 0; i < items.length; i++) {\n const current = items[i]!;\n const metaBase = (\n current.meta && typeof current.meta === \"object\" ? (current.meta as Record<string, unknown>) : {}\n ) as Record<string, unknown>;\n const cmBase =\n metaBase._cm && typeof metaBase._cm === \"object\"\n ? (metaBase._cm as Record<string, unknown>)\n : ({} as Record<string, unknown>);\n const originIndex = typeof cmBase.originIndex === \"number\" ? (cmBase.originIndex as number) : undefined;\n\n const result = await this.workflows.runById({\n workflowId: ctx.config.workflowId,\n startAt: ctx.config.startAt,\n items: [current],\n parent: {\n runId: ctx.runId,\n workflowId: ctx.workflowId,\n nodeId: ctx.nodeId,\n subworkflowDepth: ctx.subworkflowDepth,\n engineMaxNodeActivations: ctx.engineMaxNodeActivations,\n engineMaxSubworkflowDepth: ctx.engineMaxSubworkflowDepth,\n },\n });\n if (result.status !== \"completed\")\n throw new Error(`Subworkflow ${ctx.config.workflowId} did not complete (status=${result.status})`);\n for (const produced of result.outputs) {\n const childMetaBase =\n produced.meta && typeof produced.meta === \"object\"\n ? (produced.meta as Record<string, unknown>)\n : ({} as Record<string, unknown>);\n const childCmBase =\n childMetaBase._cm && typeof childMetaBase._cm === \"object\"\n ? (childMetaBase._cm as Record<string, unknown>)\n : ({} as Record<string, unknown>);\n\n out.push({\n ...produced,\n meta: originIndex === undefined ? childMetaBase : { ...childMetaBase, _cm: { ...childCmBase, originIndex } },\n paired: current.paired ?? produced.paired,\n });\n }\n }\n\n return { main: out };\n }\n}\n","import type { NodeId, RunnableNodeConfig, TypeToken, UpstreamRefPlaceholder } from \"@codemation/core\";\n\nimport { SubWorkflowNode } from \"./SubWorkflowNode\";\n\nexport class SubWorkflow<TInputJson = unknown, TOutputJson = unknown> implements RunnableNodeConfig<\n TInputJson,\n TOutputJson\n> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = SubWorkflowNode;\n constructor(\n public readonly name: string,\n public readonly workflowId: string,\n public upstreamRefs?: Array<{ nodeId: NodeId } | UpstreamRefPlaceholder>,\n public readonly startAt?: NodeId,\n public readonly id?: string,\n ) {}\n}\n\nexport { SubWorkflowNode } from \"./SubWorkflowNode\";\n","export class WaitDuration {\n static normalize(milliseconds: number): number {\n return Number.isFinite(milliseconds) && milliseconds > 0 ? Math.floor(milliseconds) : 0;\n }\n}\n","import type { Items, Node, NodeExecutionContext, NodeOutputs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport { Wait } from \"./wait\";\nimport { WaitDuration } from \"./WaitDurationFactory\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class WaitNode implements Node<Wait<any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n async execute(items: Items, ctx: NodeExecutionContext<Wait<any>>): Promise<NodeOutputs> {\n const milliseconds = WaitDuration.normalize(ctx.config.milliseconds);\n if (milliseconds > 0) {\n await new Promise<void>((resolve) => {\n setTimeout(resolve, milliseconds);\n });\n }\n return { main: items };\n }\n}\n","import type { RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { WaitNode } from \"./WaitNode\";\n\nexport class Wait<TItemJson = unknown> implements RunnableNodeConfig<TItemJson, TItemJson> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = WaitNode;\n readonly execution = { hint: \"local\" } as const;\n /** Pass-through empty batches should still advance to downstream nodes. */\n readonly continueWhenEmptyOutput = true as const;\n\n constructor(\n public readonly name: string,\n public readonly milliseconds: number,\n public readonly id?: string,\n ) {}\n}\n\nexport { WaitDuration } from \"./WaitDurationFactory\";\nexport { WaitNode } from \"./WaitNode\";\n","import type { Items, WebhookControlSignal } from \"@codemation/core\";\n\nexport class WebhookRespondNowAndContinueError extends Error implements WebhookControlSignal {\n readonly __webhookControl = true as const;\n readonly kind = \"respondNowAndContinue\" as const;\n\n constructor(\n public readonly responseItems: Items,\n public readonly continueItems: Items,\n message: string = \"Webhook responded immediately and continued the run.\",\n ) {\n super(message);\n this.name = \"WebhookRespondNowAndContinueError\";\n }\n}\n","import type { Items, WebhookControlSignal } from \"@codemation/core\";\n\nexport class WebhookRespondNowError extends Error implements WebhookControlSignal {\n readonly __webhookControl = true as const;\n readonly kind = \"respondNow\" as const;\n\n constructor(\n public readonly responseItems: Items,\n message: string = \"Webhook responded immediately.\",\n ) {\n super(message);\n this.name = \"WebhookRespondNowError\";\n }\n}\n","import type {\n ExecutableTriggerNode,\n Items,\n NodeExecutionContext,\n NodeOutputs,\n TriggerSetupContext,\n} from \"@codemation/core\";\nimport { node } from \"@codemation/core\";\nimport { WebhookTrigger } from \"./WebhookTriggerFactory\";\n\n/**\n * HTTP webhooks are not registered in trigger setup. The host exposes a single catch-all route\n * (e.g. `/api/webhooks/:endpointPath`); the engine's catalog-backed webhook matcher resolves the\n * user-defined endpoint path to this workflow + node, then runs the workflow from this trigger.\n */\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class WebhookTriggerNode implements ExecutableTriggerNode<WebhookTrigger<any>> {\n readonly kind = \"trigger\" as const;\n readonly outputPorts = [\"main\"] as const;\n\n async setup(_ctx: TriggerSetupContext<WebhookTrigger<any>>): Promise<undefined> {\n return undefined;\n }\n\n async execute(items: Items, _ctx: NodeExecutionContext<WebhookTrigger<any>>): Promise<NodeOutputs> {\n if (items.length === 0) {\n throw new Error(\n `Webhook trigger \"${_ctx.config.name}\" requires a webhook request. Invoke this workflow through its webhook endpoint until manual request simulation is supported.`,\n );\n }\n const result = await _ctx.config.handler(items, _ctx);\n return { main: result ?? items };\n }\n}\n","import type { HttpMethod, Items, NodeExecutionContext, TriggerNodeConfig, TypeToken } from \"@codemation/core\";\nimport type { ZodType } from \"zod\";\nimport { WebhookTriggerNode } from \"./webhookTriggerNode\";\n\ntype WebhookInputSchema = ZodType<any, any, any>;\ntype WebhookTriggerHandler<TConfig extends WebhookTrigger<any> = WebhookTrigger<any>> = (\n items: Items,\n ctx: NodeExecutionContext<TConfig>,\n) => Promise<Items | void> | Items | void;\n\nexport class WebhookTrigger<\n TSchema extends WebhookInputSchema | undefined = undefined,\n> implements TriggerNodeConfig<unknown> {\n readonly kind = \"trigger\" as const;\n readonly type: TypeToken<unknown> = WebhookTriggerNode;\n readonly icon = \"lucide:globe\";\n\n constructor(\n public readonly name: string,\n private readonly args: Readonly<{\n endpointKey: string;\n methods: ReadonlyArray<HttpMethod>;\n inputSchema?: TSchema;\n }>,\n public readonly handler: WebhookTriggerHandler<\n WebhookTrigger<TSchema>\n > = WebhookTrigger.defaultHandler as WebhookTriggerHandler<WebhookTrigger<TSchema>>,\n public readonly id?: string,\n ) {}\n\n get endpointKey(): string {\n return this.args.endpointKey;\n }\n\n get methods(): ReadonlyArray<HttpMethod> {\n return this.args.methods;\n }\n\n get inputSchema(): TSchema | undefined {\n return this.args.inputSchema;\n }\n\n parseJsonBody(body: unknown): unknown {\n if (!this.args.inputSchema) return body;\n return this.args.inputSchema.parse(body);\n }\n\n private static defaultHandler(items: Items): Items {\n return items;\n }\n}\n","import type { Items, Node, NodeExecutionContext, NodeOutputs } from \"@codemation/core\";\nimport { node } from \"@codemation/core\";\n\nimport type { ConnectionCredentialNodeConfig } from \"./ConnectionCredentialNodeConfig\";\n\n/**\n * Placeholder runnable node for connection-owned workflow nodes (LLM/tool slots).\n * The engine does not schedule these; they exist for credentials, tokens, and UI identity.\n */\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class ConnectionCredentialNode implements Node<ConnectionCredentialNodeConfig> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n async execute(_items: Items, _ctx: NodeExecutionContext<ConnectionCredentialNodeConfig>): Promise<NodeOutputs> {\n return { main: [] };\n }\n}\n","import type { Container } from \"@codemation/core\";\nimport { AIAgentExecutionHelpersFactory, AIAgentNode } from \"./nodes/aiAgent\";\nimport { CallbackNode } from \"./nodes/CallbackNodeFactory\";\nimport { HttpRequestNode } from \"./nodes/httpRequest\";\nimport { IfNode } from \"./nodes/if\";\nimport { ManualTriggerNode } from \"./nodes/ManualTriggerFactory\";\nimport { MapDataNode } from \"./nodes/mapData\";\nimport { NoOpNode } from \"./nodes/noOp\";\nimport { SubWorkflowNode } from \"./nodes/subWorkflow\";\nimport { WaitNode } from \"./nodes/wait\";\nimport { ConnectionCredentialNode } from \"./nodes/ConnectionCredentialNode\";\n\n/**\n * Registrar for built-in nodes. In a real project, this would use tsyringe's\n * container.registerSingleton(...). For the skeleton we keep it token-based:\n * the engine resolves node implementations by class token.\n */\nexport function registerCoreNodes(container: Container): void {\n // With class tokens, resolving registers happen via the DI container setup.\n // This function exists as the standardized extension point.\n void container;\n\n // Example: if using tsyringe, you'd do:\n // tsyringeContainer.registerSingleton(IfNode, IfNode);\n // ...\n void IfNode;\n void HttpRequestNode;\n void CallbackNode;\n void MapDataNode;\n void NoOpNode;\n void SubWorkflowNode;\n void ManualTriggerNode;\n void AIAgentNode;\n void AIAgentExecutionHelpersFactory;\n void WaitNode;\n void ConnectionCredentialNode;\n}\n","import type { WorkflowId } from \"@codemation/core\";\nimport { WorkflowBuilder } from \"@codemation/core\";\nimport { Merge } from \"./nodes/merge\";\n\nexport function createWorkflowBuilder(meta: Readonly<{ id: WorkflowId; name: string }>): WorkflowBuilder {\n return new WorkflowBuilder(meta, {\n makeMergeNode: (name) => new Merge(name, { mode: \"passThrough\", prefer: [\"true\", \"false\"] }),\n });\n}\n","import type { ChatModelConfig } from \"@codemation/core\";\nimport { OpenAIChatModelConfig } from \"../chatModels/openAiChatModelConfig\";\n\nexport class WorkflowChatModelFactory {\n static create(model: string | ChatModelConfig): ChatModelConfig {\n if (typeof model !== \"string\") {\n return model;\n }\n const [provider, resolvedModel] = model.includes(\":\") ? model.split(\":\", 2) : [\"openai\", model];\n if (provider !== \"openai\") {\n throw new Error(`Unsupported workflow().agent() model provider \"${provider}\".`);\n }\n return new OpenAIChatModelConfig(\"OpenAI\", resolvedModel);\n }\n}\n","import { z } from \"zod\";\nimport { AIAgent } from \"../nodes/AIAgentConfig\";\nimport type { WorkflowAgentOptions } from \"./WorkflowAuthoringOptions.types\";\nimport { WorkflowChatModelFactory } from \"./WorkflowChatModelFactory.types\";\n\nexport class WorkflowAgentNodeFactory {\n static create<TCurrentJson, TOutputSchema extends z.ZodTypeAny | undefined>(\n nameOrOptions: string | WorkflowAgentOptions<TCurrentJson, TOutputSchema>,\n optionsOrUndefined?: WorkflowAgentOptions<TCurrentJson, TOutputSchema>,\n ): AIAgent<TCurrentJson, TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>> {\n const options = typeof nameOrOptions === \"string\" ? optionsOrUndefined! : nameOrOptions;\n const name = typeof nameOrOptions === \"string\" ? nameOrOptions : \"AI agent\";\n const prompt = options.prompt;\n const messages = [\n {\n role: \"user\" as const,\n content:\n typeof prompt === \"function\" ? ({ item }: { item: { json: TCurrentJson } }) => prompt(item.json) : prompt,\n },\n ] as const;\n return new AIAgent<\n TCurrentJson,\n TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>\n >({\n name,\n messages,\n chatModel: WorkflowChatModelFactory.create(options.model),\n tools: options.tools,\n id: options.id,\n retryPolicy: options.retryPolicy,\n guardrails: options.guardrails,\n });\n }\n}\n","import { DefinedNodeRegistry, type DefinedNode } from \"@codemation/core\";\n\nexport class WorkflowDefinedNodeResolver {\n static resolve(\n definitionOrKey: DefinedNode<string, Record<string, unknown>, unknown, unknown> | string,\n ): DefinedNode<string, Record<string, unknown>, unknown, unknown> {\n if (typeof definitionOrKey !== \"string\") {\n return definitionOrKey;\n }\n const definition = DefinedNodeRegistry.resolve(definitionOrKey);\n if (!definition) {\n throw new Error(`No helper-defined node with key \"${definitionOrKey}\" is registered in this module graph.`);\n }\n return definition;\n }\n}\n","export class WorkflowDurationParser {\n static parse(duration: number | string): number {\n if (typeof duration === \"number\") {\n return Number.isFinite(duration) && duration > 0 ? Math.floor(duration) : 0;\n }\n const normalized = duration.trim().toLowerCase();\n const match = normalized.match(/^(\\d+)(ms|s|m|h)$/);\n if (!match) {\n throw new Error(\n `Unsupported wait duration \"${duration}\". Use a number of milliseconds or values like \"500ms\", \"2s\", \"5m\".`,\n );\n }\n const value = Number(match[1]);\n const unit = match[2];\n if (unit === \"ms\") {\n return value;\n }\n if (unit === \"s\") {\n return value * 1000;\n }\n if (unit === \"m\") {\n return value * 60_000;\n }\n return value * 3_600_000;\n }\n}\n","import type { AnyRunnableNodeConfig, DefinedNode, RunnableNodeConfig, RunnableNodeOutputJson } from \"@codemation/core\";\nimport { z } from \"zod\";\nimport { MapData } from \"../nodes/mapData\";\nimport { Wait } from \"../nodes/wait\";\nimport type { WorkflowAgentOptions } from \"./WorkflowAuthoringOptions.types\";\nimport { WorkflowAgentNodeFactory } from \"./WorkflowAgentNodeFactory.types\";\nimport { WorkflowDefinedNodeResolver } from \"./WorkflowDefinedNodeResolver.types\";\nimport { WorkflowDurationParser } from \"./WorkflowDurationParser.types\";\n\nexport class WorkflowBranchBuilder<TCurrentJson> {\n constructor(private readonly steps: ReadonlyArray<AnyRunnableNodeConfig> = []) {}\n\n then<TConfig extends RunnableNodeConfig<TCurrentJson, any>>(\n config: TConfig,\n ): WorkflowBranchBuilder<RunnableNodeOutputJson<TConfig>> {\n return new WorkflowBranchBuilder<RunnableNodeOutputJson<TConfig>>([...this.steps, config]);\n }\n\n map<TNextJson>(mapper: (item: TCurrentJson) => TNextJson): WorkflowBranchBuilder<TNextJson>;\n map<TNextJson>(\n name: string,\n mapper: (item: TCurrentJson) => TNextJson,\n id?: string,\n ): WorkflowBranchBuilder<TNextJson>;\n map<TNextJson>(\n nameOrMapper: string | ((item: TCurrentJson) => TNextJson),\n mapperOrUndefined?: (item: TCurrentJson) => TNextJson,\n id?: string,\n ): WorkflowBranchBuilder<TNextJson> {\n const name = typeof nameOrMapper === \"string\" ? nameOrMapper : \"Map data\";\n const mapper = typeof nameOrMapper === \"string\" ? mapperOrUndefined! : nameOrMapper;\n return this.then(\n new MapData<TCurrentJson, TNextJson>(name, (item) => mapper(item.json as TCurrentJson), id),\n ) as WorkflowBranchBuilder<TNextJson>;\n }\n\n wait(duration: number | string): WorkflowBranchBuilder<TCurrentJson>;\n wait(name: string, duration: number | string, id?: string): WorkflowBranchBuilder<TCurrentJson>;\n wait(\n nameOrDuration: string | number,\n durationOrUndefined?: string | number,\n id?: string,\n ): WorkflowBranchBuilder<TCurrentJson> {\n const name = typeof nameOrDuration === \"string\" && durationOrUndefined !== undefined ? nameOrDuration : \"Wait\";\n const duration = durationOrUndefined ?? nameOrDuration;\n return this.then(\n new Wait<TCurrentJson>(name, WorkflowDurationParser.parse(duration), id),\n ) as WorkflowBranchBuilder<TCurrentJson>;\n }\n\n agent<TOutputSchema extends z.ZodTypeAny>(\n options: WorkflowAgentOptions<TCurrentJson, TOutputSchema>,\n ): WorkflowBranchBuilder<z.output<TOutputSchema>>;\n agent(options: WorkflowAgentOptions<TCurrentJson, undefined>): WorkflowBranchBuilder<Record<string, unknown>>;\n agent<TOutputSchema extends z.ZodTypeAny>(\n name: string,\n options: WorkflowAgentOptions<TCurrentJson, TOutputSchema | undefined>,\n ): WorkflowBranchBuilder<TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>>;\n agent<TOutputSchema extends z.ZodTypeAny>(\n nameOrOptions: string | WorkflowAgentOptions<TCurrentJson, TOutputSchema | undefined>,\n optionsOrUndefined?: WorkflowAgentOptions<TCurrentJson, TOutputSchema | undefined>,\n ): WorkflowBranchBuilder<TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>> {\n return this.then(WorkflowAgentNodeFactory.create(nameOrOptions, optionsOrUndefined)) as WorkflowBranchBuilder<\n TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>\n >;\n }\n\n node<TConfig extends Record<string, unknown>, TOutputJson>(\n definitionOrKey: DefinedNode<string, TConfig, TCurrentJson, TOutputJson> | string,\n config: TConfig,\n name?: string,\n id?: string,\n ): WorkflowBranchBuilder<TOutputJson> {\n const definition = WorkflowDefinedNodeResolver.resolve(\n definitionOrKey as DefinedNode<string, Record<string, unknown>, unknown, unknown> | string,\n ) as DefinedNode<string, TConfig, TCurrentJson, TOutputJson>;\n return this.then(\n definition.create(config, name, id) as RunnableNodeConfig<TCurrentJson, TOutputJson>,\n ) as WorkflowBranchBuilder<TOutputJson>;\n }\n\n getSteps(): ReadonlyArray<AnyRunnableNodeConfig> {\n return this.steps;\n }\n}\n","import type { DefinedNode, RunnableNodeConfig, RunnableNodeOutputJson, WorkflowDefinition } from \"@codemation/core\";\nimport { ChainCursor } from \"@codemation/core\";\nimport { z } from \"zod\";\nimport { If } from \"../nodes/if\";\nimport { MapData } from \"../nodes/mapData\";\nimport { Wait } from \"../nodes/wait\";\nimport type { WorkflowAgentOptions } from \"./WorkflowAuthoringOptions.types\";\nimport { WorkflowAgentNodeFactory } from \"./WorkflowAgentNodeFactory.types\";\nimport { WorkflowBranchBuilder } from \"./WorkflowBranchBuilder.types\";\nimport { WorkflowDefinedNodeResolver } from \"./WorkflowDefinedNodeResolver.types\";\nimport { WorkflowDurationParser } from \"./WorkflowDurationParser.types\";\n\ntype BranchCallback<TCurrentJson, TNextJson> = (\n branch: WorkflowBranchBuilder<TCurrentJson>,\n) => WorkflowBranchBuilder<TNextJson>;\ntype BranchOutputMatch<TLeft, TRight> = [TLeft] extends [TRight] ? ([TRight] extends [TLeft] ? true : false) : false;\n\nexport class WorkflowChain<TCurrentJson> {\n constructor(private readonly chain: ChainCursor<TCurrentJson>) {}\n\n then<TConfig extends RunnableNodeConfig<TCurrentJson, any>>(\n config: TConfig,\n ): WorkflowChain<RunnableNodeOutputJson<TConfig>> {\n return new WorkflowChain(this.chain.then(config));\n }\n\n map<TNextJson>(mapper: (item: TCurrentJson) => TNextJson): WorkflowChain<TNextJson>;\n map<TNextJson>(name: string, mapper: (item: TCurrentJson) => TNextJson, id?: string): WorkflowChain<TNextJson>;\n map<TNextJson>(\n nameOrMapper: string | ((item: TCurrentJson) => TNextJson),\n mapperOrUndefined?: (item: TCurrentJson) => TNextJson,\n id?: string,\n ): WorkflowChain<TNextJson> {\n const name = typeof nameOrMapper === \"string\" ? nameOrMapper : \"Map data\";\n const mapper = typeof nameOrMapper === \"string\" ? mapperOrUndefined! : nameOrMapper;\n return this.then(\n new MapData<TCurrentJson, TNextJson>(name, (item) => mapper(item.json as TCurrentJson), id),\n ) as WorkflowChain<TNextJson>;\n }\n\n wait(duration: number | string): WorkflowChain<TCurrentJson>;\n wait(name: string, duration: number | string, id?: string): WorkflowChain<TCurrentJson>;\n wait(\n nameOrDuration: string | number,\n durationOrUndefined?: string | number,\n id?: string,\n ): WorkflowChain<TCurrentJson> {\n const name = typeof nameOrDuration === \"string\" && durationOrUndefined !== undefined ? nameOrDuration : \"Wait\";\n const duration = durationOrUndefined ?? nameOrDuration;\n return this.then(\n new Wait<TCurrentJson>(name, WorkflowDurationParser.parse(duration), id),\n ) as WorkflowChain<TCurrentJson>;\n }\n\n if<TBranchJson>(\n predicate: (item: TCurrentJson) => boolean,\n branches: Readonly<{\n true?: BranchCallback<TCurrentJson, TBranchJson>;\n false?: BranchCallback<TCurrentJson, TBranchJson>;\n }>,\n ): WorkflowChain<TBranchJson>;\n if<TBranchJson>(\n name: string,\n predicate: (item: TCurrentJson) => boolean,\n branches: Readonly<{\n true?: BranchCallback<TCurrentJson, TBranchJson>;\n false?: BranchCallback<TCurrentJson, TBranchJson>;\n }>,\n ): WorkflowChain<TBranchJson>;\n if<TTrueJson, TFalseJson>(\n nameOrPredicate: string | ((item: TCurrentJson) => boolean),\n predicateOrBranches:\n | ((item: TCurrentJson) => boolean)\n | Readonly<{ true?: BranchCallback<TCurrentJson, TTrueJson>; false?: BranchCallback<TCurrentJson, TFalseJson> }>,\n branchesOrUndefined?: Readonly<{\n true?: BranchCallback<TCurrentJson, TTrueJson>;\n false?: BranchCallback<TCurrentJson, TFalseJson>;\n }>,\n ): WorkflowChain<BranchOutputMatch<TTrueJson, TFalseJson> extends true ? TTrueJson : never> {\n const name = typeof nameOrPredicate === \"string\" ? nameOrPredicate : \"If\";\n const predicate =\n typeof nameOrPredicate === \"string\" ? (predicateOrBranches as (item: TCurrentJson) => boolean) : nameOrPredicate;\n const branches = (typeof nameOrPredicate === \"string\" ? branchesOrUndefined : predicateOrBranches) as Readonly<{\n true?: BranchCallback<TCurrentJson, TTrueJson>;\n false?: BranchCallback<TCurrentJson, TFalseJson>;\n }>;\n const cursor = this.chain.then(new If<TCurrentJson>(name, (item) => predicate(item.json as TCurrentJson)));\n const trueSteps = branches.true?.(new WorkflowBranchBuilder<TCurrentJson>()).getSteps();\n const falseSteps = branches.false?.(new WorkflowBranchBuilder<TCurrentJson>()).getSteps();\n return new WorkflowChain(\n cursor.when({\n true: trueSteps,\n false: falseSteps,\n }),\n ) as WorkflowChain<BranchOutputMatch<TTrueJson, TFalseJson> extends true ? TTrueJson : never>;\n }\n\n agent<TOutputSchema extends z.ZodTypeAny>(\n options: WorkflowAgentOptions<TCurrentJson, TOutputSchema>,\n ): WorkflowChain<z.output<TOutputSchema>>;\n agent(options: WorkflowAgentOptions<TCurrentJson, undefined>): WorkflowChain<Record<string, unknown>>;\n agent<TOutputSchema extends z.ZodTypeAny>(\n name: string,\n options: WorkflowAgentOptions<TCurrentJson, TOutputSchema | undefined>,\n ): WorkflowChain<TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>>;\n agent<TOutputSchema extends z.ZodTypeAny>(\n nameOrOptions: string | WorkflowAgentOptions<TCurrentJson, TOutputSchema | undefined>,\n optionsOrUndefined?: WorkflowAgentOptions<TCurrentJson, TOutputSchema | undefined>,\n ): WorkflowChain<TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>> {\n return this.then(WorkflowAgentNodeFactory.create(nameOrOptions, optionsOrUndefined)) as WorkflowChain<\n TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>\n >;\n }\n\n node<TConfig extends Record<string, unknown>, TOutputJson>(\n definitionOrKey: DefinedNode<string, TConfig, TCurrentJson, TOutputJson> | string,\n config: TConfig,\n name?: string,\n id?: string,\n ): WorkflowChain<TOutputJson> {\n const definition = WorkflowDefinedNodeResolver.resolve(\n definitionOrKey as DefinedNode<string, Record<string, unknown>, unknown, unknown> | string,\n ) as DefinedNode<string, TConfig, TCurrentJson, TOutputJson>;\n return this.then(\n definition.create(config, name, id) as RunnableNodeConfig<TCurrentJson, TOutputJson>,\n ) as WorkflowChain<TOutputJson>;\n }\n\n build(): WorkflowDefinition {\n return this.chain.build();\n }\n}\n","import { ChainCursor } from \"@codemation/core\";\nimport { ManualTrigger } from \"../nodes/ManualTriggerFactory\";\nimport { createWorkflowBuilder } from \"../workflowBuilder.types\";\nimport { WorkflowChain } from \"./WorkflowChain.types\";\n\nexport class WorkflowAuthoringBuilder {\n constructor(\n private readonly id: string,\n private readonly workflowName: string = id,\n ) {}\n\n name(name: string): WorkflowAuthoringBuilder {\n return new WorkflowAuthoringBuilder(this.id, name);\n }\n\n manualTrigger<TOutputJson>(defaultItems: TOutputJson | ReadonlyArray<TOutputJson>): WorkflowChain<TOutputJson>;\n manualTrigger<TOutputJson>(\n name: string,\n defaultItems?: TOutputJson | ReadonlyArray<TOutputJson>,\n id?: string,\n ): WorkflowChain<TOutputJson>;\n manualTrigger<TOutputJson>(\n nameOrDefaultItems: string | TOutputJson | ReadonlyArray<TOutputJson>,\n defaultItemsOrUndefined?: TOutputJson | ReadonlyArray<TOutputJson>,\n id?: string,\n ): WorkflowChain<TOutputJson> {\n const builder = createWorkflowBuilder({ id: this.id, name: this.workflowName });\n if (typeof nameOrDefaultItems === \"string\") {\n return new WorkflowChain(\n builder.trigger(\n new ManualTrigger<TOutputJson>(\n nameOrDefaultItems,\n defaultItemsOrUndefined as TOutputJson | ReadonlyArray<TOutputJson>,\n id,\n ),\n ) as ChainCursor<TOutputJson>,\n );\n }\n return new WorkflowChain(\n builder.trigger(new ManualTrigger<TOutputJson>(\"Manual trigger\", nameOrDefaultItems)) as ChainCursor<TOutputJson>,\n );\n }\n}\n","export type { WorkflowAgentOptions } from \"./workflowAuthoring/WorkflowAuthoringOptions.types\";\nexport { WorkflowAuthoringBuilder } from \"./workflowAuthoring/WorkflowAuthoringBuilder.types\";\nexport { WorkflowBranchBuilder } from \"./workflowAuthoring/WorkflowBranchBuilder.types\";\nexport { WorkflowChain } from \"./workflowAuthoring/WorkflowChain.types\";\n\nimport { WorkflowAuthoringBuilder } from \"./workflowAuthoring/WorkflowAuthoringBuilder.types\";\n\nexport function workflow(id: string): WorkflowAuthoringBuilder {\n return new WorkflowAuthoringBuilder(id);\n}\n","import type { NodeDefinition, WorkflowDefinition, WorkflowNodeConnection } from \"@codemation/core\";\nimport { AgentConfigInspector, ConnectionNodeIdFactory } from \"@codemation/core\";\n\nimport { AIAgentNode } from \"../nodes/AIAgentNode\";\nimport { ConnectionCredentialNode } from \"../nodes/ConnectionCredentialNode\";\nimport { ConnectionCredentialNodeConfigFactory } from \"../nodes/ConnectionCredentialNodeConfigFactory\";\n\n/**\n * Materializes connection-owned child nodes and {@link WorkflowDefinition.connections} for AI agent nodes.\n */\nexport class AIAgentConnectionWorkflowExpander {\n constructor(private readonly connectionCredentialNodeConfigFactory: ConnectionCredentialNodeConfigFactory) {}\n\n expand(workflow: WorkflowDefinition): WorkflowDefinition {\n const existingByParentAndName = new Map<string, WorkflowNodeConnection>();\n for (const c of workflow.connections ?? []) {\n existingByParentAndName.set(`${c.parentNodeId}\\0${c.connectionName}`, c);\n }\n\n const extraNodes: NodeDefinition[] = [];\n const extraConnections: WorkflowNodeConnection[] = [];\n\n for (const node of workflow.nodes) {\n if (node.type !== AIAgentNode || !AgentConfigInspector.isAgentNodeConfig(node.config)) {\n continue;\n }\n const agentId = node.id;\n const agentConfig = node.config;\n\n if (!existingByParentAndName.has(`${agentId}\\0llm`)) {\n const llmId = ConnectionNodeIdFactory.languageModelConnectionNodeId(agentId);\n this.assertNoIdCollision(workflow, extraNodes, llmId);\n extraNodes.push({\n id: llmId,\n kind: \"node\",\n type: ConnectionCredentialNode,\n name: agentConfig.chatModel.presentation?.label ?? agentConfig.chatModel.name,\n config: this.connectionCredentialNodeConfigFactory.create(agentConfig.chatModel.name, agentConfig.chatModel),\n });\n extraConnections.push({ parentNodeId: agentId, connectionName: \"llm\", childNodeIds: [llmId] });\n }\n\n if (!existingByParentAndName.has(`${agentId}\\0tools`) && (agentConfig.tools?.length ?? 0) > 0) {\n const toolIds: string[] = [];\n for (const tool of agentConfig.tools ?? []) {\n const toolId = ConnectionNodeIdFactory.toolConnectionNodeId(agentId, tool.name);\n this.assertNoIdCollision(workflow, extraNodes, toolId);\n toolIds.push(toolId);\n extraNodes.push({\n id: toolId,\n kind: \"node\",\n type: ConnectionCredentialNode,\n name: tool.presentation?.label ?? tool.name,\n config: this.connectionCredentialNodeConfigFactory.create(tool.name, tool),\n });\n }\n extraConnections.push({ parentNodeId: agentId, connectionName: \"tools\", childNodeIds: toolIds });\n }\n }\n\n if (extraNodes.length === 0) {\n return workflow;\n }\n\n return {\n ...workflow,\n nodes: [...workflow.nodes, ...extraNodes],\n connections: [...(workflow.connections ?? []), ...extraConnections],\n };\n }\n\n private assertNoIdCollision(workflow: WorkflowDefinition, pending: ReadonlyArray<NodeDefinition>, id: string): void {\n if (workflow.nodes.some((n) => n.id === id) || pending.some((n) => n.id === id)) {\n throw new Error(\n `AIAgent connection expansion: node id \"${id}\" already exists. Rename the conflicting node or adjust the workflow.`,\n );\n }\n }\n}\n","import type { CredentialRequirement, RunnableNodeConfig } from \"@codemation/core\";\n\nimport { ConnectionCredentialNode } from \"./ConnectionCredentialNode\";\n\nexport class ConnectionCredentialNodeConfig implements RunnableNodeConfig {\n readonly kind = \"node\" as const;\n readonly type = ConnectionCredentialNode;\n\n constructor(\n public readonly name: string,\n private readonly credentialSource: { getCredentialRequirements?: () => ReadonlyArray<CredentialRequirement> },\n ) {}\n\n getCredentialRequirements(): ReadonlyArray<CredentialRequirement> {\n return this.credentialSource.getCredentialRequirements?.() ?? [];\n }\n}\n","import type { CredentialRequirement } from \"@codemation/core\";\n\nimport { ConnectionCredentialNodeConfig } from \"./ConnectionCredentialNodeConfig\";\n\nexport class ConnectionCredentialNodeConfigFactory {\n create(\n name: string,\n credentialSource: { getCredentialRequirements?: () => ReadonlyArray<CredentialRequirement> },\n ): ConnectionCredentialNodeConfig {\n return new ConnectionCredentialNodeConfig(name, credentialSource);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAOO,mCAAMA,yBAA0E;CACrF,MAAM,OACJ,MACiC;EACjC,MAAM,UAAU,MAAM,KAAK,IAAI,cAAuC,KAAK,OAAO,kBAAkB;AACpG,SAAO,IAAI,WAAW;GACpB,QAAQ,QAAQ;GAChB,OAAO,KAAK,OAAO;GACnB,aAAa,KAAK,OAAO,SAAS;GAClC,WAAW,KAAK,OAAO,SAAS;GAChC,eAAe,QAAQ,UAAU,EAAE,SAAS,QAAQ,SAAS,GAAG;GACjE,CAAC;;;qCAZL,UAAU,EAAE,aAAa,0BAA0B,CAAC;;;;ACDrD,IAAa,wBAAb,MAA8D;CAC5D,AAAS,OAAO;CAChB,AAAS;CAET,YACE,AAAgBC,MAChB,AAAgBC,OAChB,AAAgBC,oBAA4B,UAC5C,gBACA,AAA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Ab,MAAmD;CACjD,OACE,MACA,kBACgC;AAChC,SAAO,IAAI,+BAA+B,MAAM,iBAAiB"}
1
+ {"version":3,"file":"index.js","names":["OpenAIChatModelFactory","name: string","model: string","credentialSlotKey: string","options?: Readonly<{\n temperature?: number;\n maxTokens?: number;\n }>","_a","id","schema","registry","ctx","AIAgentExecutionHelpersFactory","converted: unknown","node","NodeBackedToolRuntime","nodeResolver: NodeResolver","AIAgentNode","nodeResolver: NodeResolver","credentialSessions: CredentialSessionService","nodeBackedToolRuntime: NodeBackedToolRuntime","executionHelpers: AIAgentExecutionHelpersFactory","out: Item[]","conversation: BaseMessage[]","finalResponse: AIMessage | undefined","CallbackNode","name: string","callback: CallbackHandler<TInputJson, TOutputJson>","id?: string","HttpRequestNode","output: Item[]","outputItem: Item","values: Record<string, string>","name: string","args: Readonly<{\n method?: string;\n urlField?: string;\n binaryName?: string;\n downloadMode?: HttpRequestDownloadMode;\n id?: string;\n }>","retryPolicy: RetryPolicySpec","IfNode","t: Item[]","f: Item[]","tagged: Item","name: string","predicate: (\n item: Item<TInputJson>,\n index: number,\n items: Items<TInputJson>,\n ctx: NodeExecutionContext<If<TInputJson>>,\n ) => boolean","id?: string","ManualTriggerNode","name: string","MapDataNode","out: Item[]","name: string","map: (\n item: Item<TInputJson>,\n ctx: NodeExecutionContext<MapData<TInputJson, TOutputJson>>,\n ) => TOutputJson","id?: string","MergeNode","out: Item[]","out","json: Record<string, unknown>","paired: any[]","meta: Record<string, unknown> | undefined","merged: any","fallback: Item[]","name: string","cfg: Readonly<{\n mode: MergeMode;\n /**\n * Deterministic input precedence order (only used for passThrough/append).\n * Any inputs not listed are appended in lexicographic order.\n */\n prefer?: ReadonlyArray<InputPortKey>;\n }>","id?: string","NoOpNode","name: string","id?: string","SubWorkflowNode","workflows: WorkflowRunnerService","out: Item[]","name: string","workflowId: string","upstreamRefs?: Array<{ nodeId: NodeId } | UpstreamRefPlaceholder>","startAt?: NodeId","id?: string","WaitNode","name: string","milliseconds: number","id?: string","responseItems: Items","continueItems: Items","responseItems: Items","WebhookTriggerNode","name: string","args: Readonly<{\n endpointKey: string;\n methods: ReadonlyArray<HttpMethod>;\n inputSchema?: TSchema;\n }>","handler: WebhookTriggerHandler<\n WebhookTrigger<TSchema>\n >","id?: string","ConnectionCredentialNode","steps: ReadonlyArray<AnyRunnableNodeConfig>","chain: ChainCursor<TCurrentJson>","id: string","workflowName: string","connectionCredentialNodeConfigFactory: ConnectionCredentialNodeConfigFactory","workflow","extraNodes: NodeDefinition[]","node","name: string","credentialSource: { getCredentialRequirements?: () => ReadonlyArray<CredentialRequirement> }"],"sources":["../src/chatModels/OpenAIChatModelFactory.ts","../src/chatModels/openAiChatModelConfig.ts","../src/chatModels/OpenAiChatModelPresetsFactory.ts","../src/nodes/AgentMessageFactory.ts","../src/nodes/AgentOutputFactory.ts","../src/nodes/AgentToolCallPortMapFactory.ts","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/registries.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/to-json-schema.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-processors.js","../src/nodes/ConnectionCredentialExecutionContextFactory.ts","../src/nodes/AIAgentExecutionHelpersFactory.ts","../src/nodes/NodeBackedToolRuntime.ts","../src/nodes/aiAgentSupport.types.ts","../src/nodes/AIAgentNode.ts","../src/nodes/AIAgentConfig.ts","../src/nodes/CallbackResultNormalizerFactory.ts","../src/nodes/CallbackNode.ts","../src/nodes/CallbackNodeFactory.ts","../src/nodes/HttpRequestNodeFactory.ts","../src/nodes/httpRequest.ts","../src/nodes/IfNode.ts","../src/nodes/if.ts","../src/nodes/ManualTriggerNode.ts","../src/nodes/ManualTriggerFactory.ts","../src/nodes/MapDataNode.ts","../src/nodes/mapData.ts","../src/nodes/mergeExecutionUtils.types.ts","../src/nodes/MergeNode.ts","../src/nodes/merge.ts","../src/nodes/NoOpNode.ts","../src/nodes/noOp.ts","../src/nodes/SubWorkflowNode.ts","../src/nodes/subWorkflow.ts","../src/nodes/WaitDurationFactory.ts","../src/nodes/WaitNode.ts","../src/nodes/wait.ts","../src/nodes/webhookRespondNowAndContinueError.ts","../src/nodes/webhookRespondNowError.ts","../src/nodes/webhookTriggerNode.ts","../src/nodes/WebhookTriggerFactory.ts","../src/nodes/ConnectionCredentialNode.ts","../src/register.types.ts","../src/workflowBuilder.types.ts","../src/workflowAuthoring/WorkflowChatModelFactory.types.ts","../src/workflowAuthoring/WorkflowAgentNodeFactory.types.ts","../src/workflowAuthoring/WorkflowDefinedNodeResolver.types.ts","../src/workflowAuthoring/WorkflowDurationParser.types.ts","../src/workflowAuthoring/WorkflowBranchBuilder.types.ts","../src/workflowAuthoring/WorkflowChain.types.ts","../src/workflowAuthoring/WorkflowAuthoringBuilder.types.ts","../src/workflowAuthoring.types.ts","../src/workflows/AIAgentConnectionWorkflowExpander.ts","../src/nodes/ConnectionCredentialNodeConfig.ts","../src/nodes/ConnectionCredentialNodeConfigFactory.ts"],"sourcesContent":["import type { ChatModelFactory, LangChainChatModelLike, NodeExecutionContext } from \"@codemation/core\";\nimport { chatModel } from \"@codemation/core\";\nimport { ChatOpenAI } from \"@langchain/openai\";\nimport type { OpenAiCredentialSession } from \"./OpenAiCredentialSession\";\nimport type { OpenAIChatModelConfig } from \"./openAiChatModelConfig\";\n\n@chatModel({ packageName: \"@codemation/core-nodes\" })\nexport class OpenAIChatModelFactory implements ChatModelFactory<OpenAIChatModelConfig> {\n async create(\n args: Readonly<{ config: OpenAIChatModelConfig; ctx: NodeExecutionContext<any> }>,\n ): Promise<LangChainChatModelLike> {\n const session = await args.ctx.getCredential<OpenAiCredentialSession>(args.config.credentialSlotKey);\n return new ChatOpenAI({\n apiKey: session.apiKey,\n model: args.config.model,\n temperature: args.config.options?.temperature,\n maxTokens: args.config.options?.maxTokens,\n configuration: session.baseUrl ? { baseURL: session.baseUrl } : undefined,\n });\n }\n}\n","import type { AgentCanvasPresentation, ChatModelConfig, CredentialRequirement } from \"@codemation/core\";\n\nimport type { CanvasIconName } from \"../canvasIconName\";\nimport { OpenAIChatModelFactory } from \"./OpenAIChatModelFactory\";\n\nexport class OpenAIChatModelConfig implements ChatModelConfig {\n readonly type = OpenAIChatModelFactory;\n readonly presentation: AgentCanvasPresentation<CanvasIconName>;\n\n constructor(\n public readonly name: string,\n public readonly model: string,\n public readonly credentialSlotKey: string = \"openai\",\n presentationIn?: AgentCanvasPresentation<CanvasIconName>,\n public readonly options?: Readonly<{\n temperature?: number;\n maxTokens?: number;\n }>,\n ) {\n this.presentation = presentationIn ?? { icon: \"builtin:openai\", label: name };\n }\n\n getCredentialRequirements(): ReadonlyArray<CredentialRequirement> {\n return [\n {\n slotKey: this.credentialSlotKey,\n label: \"OpenAI API key\",\n acceptedTypes: [\"openai.apiKey\"],\n },\n ];\n }\n}\n","import { OpenAIChatModelConfig } from \"./openAiChatModelConfig\";\n\n/**\n * Default OpenAI chat model configs for scaffolds and demos (icon + label match {@link OpenAIChatModelConfig} defaults).\n * Prefer importing {@link openAiChatModelPresets} from here or from the consumer template re-export\n * instead of repeating {@link OpenAIChatModelConfig} construction in app workflows.\n */\nexport class OpenAiChatModelPresets {\n readonly demoGpt4oMini = new OpenAIChatModelConfig(\"OpenAI\", \"gpt-4o-mini\");\n\n readonly demoGpt41 = new OpenAIChatModelConfig(\"OpenAI\", \"gpt-4.1\");\n}\n\nexport const openAiChatModelPresets = new OpenAiChatModelPresets();\n","import type { AgentMessageDto, AgentToolCall } from \"@codemation/core\";\n\nimport { AIMessage, HumanMessage, SystemMessage, ToolMessage, type BaseMessage } from \"@langchain/core/messages\";\n\nexport class AgentMessageFactory {\n static createPromptMessages(messages: ReadonlyArray<AgentMessageDto>): ReadonlyArray<BaseMessage> {\n return messages.map((message) => this.createPromptMessage(message));\n }\n\n static createSystemPrompt(systemMessage: string): SystemMessage {\n return new SystemMessage(systemMessage);\n }\n\n static createUserPrompt(prompt: string): HumanMessage {\n return new HumanMessage(prompt);\n }\n\n static createAssistantPrompt(prompt: string): AIMessage {\n return new AIMessage(prompt);\n }\n\n static createToolMessage(toolCallId: string, content: string): ToolMessage {\n return new ToolMessage({ tool_call_id: toolCallId, content });\n }\n\n static extractContent(message: unknown): string {\n if (typeof message === \"string\") return message;\n if (!this.isRecord(message)) return String(message);\n const content = message.content;\n if (typeof content === \"string\") return content;\n if (Array.isArray(content)) {\n return content\n .map((part) => {\n if (typeof part === \"string\") return part;\n if (this.isRecord(part) && typeof part.text === \"string\") return part.text;\n return JSON.stringify(part);\n })\n .join(\"\\n\");\n }\n return JSON.stringify(content);\n }\n\n static extractToolCalls(message: unknown): ReadonlyArray<AgentToolCall> {\n if (!this.isRecord(message)) return [];\n const toolCalls = message.tool_calls;\n if (!Array.isArray(toolCalls)) return [];\n return toolCalls\n .filter((toolCall) => this.isRecord(toolCall) && typeof toolCall.name === \"string\")\n .map((toolCall) => ({\n id: typeof toolCall.id === \"string\" ? toolCall.id : undefined,\n name: toolCall.name as string,\n input: this.isRecord(toolCall) && \"args\" in toolCall ? toolCall.args : undefined,\n }));\n }\n\n private static isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n }\n\n private static createPromptMessage(message: AgentMessageDto): BaseMessage {\n if (message.role === \"system\") {\n return this.createSystemPrompt(message.content);\n }\n if (message.role === \"assistant\") {\n return this.createAssistantPrompt(message.content);\n }\n return this.createUserPrompt(message.content);\n }\n}\n","import type { Item, NodeOutputs } from \"@codemation/core\";\n\nexport class AgentOutputFactory {\n static fromUnknown(value: unknown): NodeOutputs {\n return { main: [{ json: value }] };\n }\n\n static replaceJson(item: Item, value: unknown): Item {\n return {\n ...item,\n json: value,\n };\n }\n\n static fromAgentContent(content: string): unknown {\n try {\n return JSON.parse(content) as unknown;\n } catch {\n return { output: content };\n }\n }\n}\n","import type { NodeInputsByPort } from \"@codemation/core\";\n\nexport class AgentToolCallPortMap {\n static fromInput(input: unknown): NodeInputsByPort {\n return {\n in: [\n {\n json: input,\n },\n ],\n };\n }\n}\n","// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\nexport function cached(getter) {\n const set = false;\n return {\n get value() {\n if (!set) {\n const value = getter();\n Object.defineProperty(this, \"value\", { value });\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n };\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepString = step.toString();\n let stepDecCount = (stepString.split(\".\")[1] || \"\").length;\n if (stepDecCount === 0 && /\\d?e-\\d?/.test(stepString)) {\n const match = stepString.match(/\\d?e-(\\d?)/);\n if (match?.[1]) {\n stepDecCount = Number.parseInt(match[1]);\n }\n }\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nconst EVALUATING = Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = cached(() => {\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = new Set([\"string\", \"number\", \"bigint\", \"boolean\", \"symbol\", \"undefined\"]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin === \"optional\" && shape[k]._zod.optout === \"optional\";\n });\n}\nexport const NUMBER_FORMAT_RANGES = {\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n};\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = {};\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n newShape[key] = currDef.shape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = { ...schema._zod.def.shape };\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n delete newShape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape\n // Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = schema._zod.def.shape;\n for (const key in shape) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function merge(a, b) {\n const def = mergeDefs(a._zod.def, {\n get shape() {\n const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: [], // delete existing checks\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".partial() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in oldShape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n else {\n for (const key in oldShape) {\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function required(Class, schema, mask) {\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n else {\n for (const key in oldShape) {\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n });\n return clone(schema, def);\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\nexport function finalizeIssue(iss, ctx, config) {\n const full = { ...iss, path: iss.path ?? [] };\n // for backwards compatibility\n if (!iss.message) {\n const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\";\n full.message = message;\n }\n // delete (full as any).def;\n delete full.inst;\n delete full.continue;\n if (!ctx?.reportInput) {\n delete full.input;\n }\n return full;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n","var _a;\nexport const $output = Symbol(\"ZodOutput\");\nexport const $input = Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n constructor() {\n this._map = new WeakMap();\n this._idmap = new Map();\n }\n add(schema, ..._meta) {\n const meta = _meta[0];\n this._map.set(schema, meta);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.set(meta.id, schema);\n }\n return this;\n }\n clear() {\n this._map = new WeakMap();\n this._idmap = new Map();\n return this;\n }\n remove(schema) {\n const meta = this._map.get(schema);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.delete(meta.id);\n }\n this._map.delete(schema);\n return this;\n }\n get(schema) {\n // return this._map.get(schema) as any;\n // inherit metadata\n const p = schema._zod.parent;\n if (p) {\n const pm = { ...(this.get(p) ?? {}) };\n delete pm.id; // do not inherit id\n const f = { ...pm, ...this._map.get(schema) };\n return Object.keys(f).length ? f : undefined;\n }\n return this._map.get(schema);\n }\n has(schema) {\n return this._map.has(schema);\n }\n}\n// registries\nexport function registry() {\n return new $ZodRegistry();\n}\n(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());\nexport const globalRegistry = globalThis.__zod_globalRegistry;\n","import { globalRegistry } from \"./registries.js\";\n// function initializeContext<T extends schemas.$ZodType>(inputs: JSONSchemaGeneratorParams<T>): ToJSONSchemaContext<T> {\n// return {\n// processor: inputs.processor,\n// metadataRegistry: inputs.metadata ?? globalRegistry,\n// target: inputs.target ?? \"draft-2020-12\",\n// unrepresentable: inputs.unrepresentable ?? \"throw\",\n// };\n// }\nexport function initializeContext(params) {\n // Normalize target: convert old non-hyphenated versions to hyphenated versions\n let target = params?.target ?? \"draft-2020-12\";\n if (target === \"draft-4\")\n target = \"draft-04\";\n if (target === \"draft-7\")\n target = \"draft-07\";\n return {\n processors: params.processors ?? {},\n metadataRegistry: params?.metadata ?? globalRegistry,\n target,\n unrepresentable: params?.unrepresentable ?? \"throw\",\n override: params?.override ?? (() => { }),\n io: params?.io ?? \"output\",\n counter: 0,\n seen: new Map(),\n cycles: params?.cycles ?? \"ref\",\n reused: params?.reused ?? \"inline\",\n external: params?.external ?? undefined,\n };\n}\nexport function process(schema, ctx, _params = { path: [], schemaPath: [] }) {\n var _a;\n const def = schema._zod.def;\n // check for schema in seens\n const seen = ctx.seen.get(schema);\n if (seen) {\n seen.count++;\n // check if cycle\n const isCycle = _params.schemaPath.includes(schema);\n if (isCycle) {\n seen.cycle = _params.path;\n }\n return seen.schema;\n }\n // initialize\n const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };\n ctx.seen.set(schema, result);\n // custom method overrides default behavior\n const overrideSchema = schema._zod.toJSONSchema?.();\n if (overrideSchema) {\n result.schema = overrideSchema;\n }\n else {\n const params = {\n ..._params,\n schemaPath: [..._params.schemaPath, schema],\n path: _params.path,\n };\n if (schema._zod.processJSONSchema) {\n schema._zod.processJSONSchema(ctx, result.schema, params);\n }\n else {\n const _json = result.schema;\n const processor = ctx.processors[def.type];\n if (!processor) {\n throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);\n }\n processor(schema, ctx, _json, params);\n }\n const parent = schema._zod.parent;\n if (parent) {\n // Also set ref if processor didn't (for inheritance)\n if (!result.ref)\n result.ref = parent;\n process(parent, ctx, params);\n ctx.seen.get(parent).isParent = true;\n }\n }\n // metadata\n const meta = ctx.metadataRegistry.get(schema);\n if (meta)\n Object.assign(result.schema, meta);\n if (ctx.io === \"input\" && isTransforming(schema)) {\n // examples/defaults only apply to output type of pipe\n delete result.schema.examples;\n delete result.schema.default;\n }\n // set prefault as default\n if (ctx.io === \"input\" && result.schema._prefault)\n (_a = result.schema).default ?? (_a.default = result.schema._prefault);\n delete result.schema._prefault;\n // pulling fresh from ctx.seen in case it was overwritten\n const _result = ctx.seen.get(schema);\n return _result.schema;\n}\nexport function extractDefs(ctx, schema\n// params: EmitParams\n) {\n // iterate over seen map;\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // Track ids to detect duplicates across different schemas\n const idToSchema = new Map();\n for (const entry of ctx.seen.entries()) {\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n const existing = idToSchema.get(id);\n if (existing && existing !== entry[0]) {\n throw new Error(`Duplicate schema id \"${id}\" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);\n }\n idToSchema.set(id, entry[0]);\n }\n }\n // returns a ref to the schema\n // defId will be empty if the ref points to an external schema (or #)\n const makeURI = (entry) => {\n // comparing the seen objects because sometimes\n // multiple schemas map to the same seen object.\n // e.g. lazy\n // external is configured\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n if (ctx.external) {\n const externalId = ctx.external.registry.get(entry[0])?.id; // ?? \"__shared\";// `__schema${ctx.counter++}`;\n // check if schema is in the external registry\n const uriGenerator = ctx.external.uri ?? ((id) => id);\n if (externalId) {\n return { ref: uriGenerator(externalId) };\n }\n // otherwise, add to __shared\n const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;\n entry[1].defId = id; // set defId so it will be reused if needed\n return { defId: id, ref: `${uriGenerator(\"__shared\")}#/${defsSegment}/${id}` };\n }\n if (entry[1] === root) {\n return { ref: \"#\" };\n }\n // self-contained schema\n const uriPrefix = `#`;\n const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;\n return { defId, ref: defUriPrefix + defId };\n };\n // stored cached version in `def` property\n // remove all properties, set $ref\n const extractToDef = (entry) => {\n // if the schema is already a reference, do not extract it\n if (entry[1].schema.$ref) {\n return;\n }\n const seen = entry[1];\n const { ref, defId } = makeURI(entry);\n seen.def = { ...seen.schema };\n // defId won't be set if the schema is a reference to an external schema\n // or if the schema is the root schema\n if (defId)\n seen.defId = defId;\n // wipe away all properties except $ref\n const schema = seen.schema;\n for (const key in schema) {\n delete schema[key];\n }\n schema.$ref = ref;\n };\n // throw on cycles\n // break cycles\n if (ctx.cycles === \"throw\") {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.cycle) {\n throw new Error(\"Cycle detected: \" +\n `#/${seen.cycle?.join(\"/\")}/<root>` +\n '\\n\\nSet the `cycles` parameter to `\"ref\"` to resolve cyclical schemas with defs.');\n }\n }\n }\n // extract schemas into $defs\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n // convert root schema to # $ref\n if (schema === entry[0]) {\n extractToDef(entry); // this has special handling for the root schema\n continue;\n }\n // extract schemas that are in the external registry\n if (ctx.external) {\n const ext = ctx.external.registry.get(entry[0])?.id;\n if (schema !== entry[0] && ext) {\n extractToDef(entry);\n continue;\n }\n }\n // extract schemas with `id` meta\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n extractToDef(entry);\n continue;\n }\n // break cycles\n if (seen.cycle) {\n // any\n extractToDef(entry);\n continue;\n }\n // extract reused schemas\n if (seen.count > 1) {\n if (ctx.reused === \"ref\") {\n extractToDef(entry);\n // biome-ignore lint:\n continue;\n }\n }\n }\n}\nexport function finalize(ctx, schema) {\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // flatten refs - inherit properties from parent schemas\n const flattenRef = (zodSchema) => {\n const seen = ctx.seen.get(zodSchema);\n // already processed\n if (seen.ref === null)\n return;\n const schema = seen.def ?? seen.schema;\n const _cached = { ...schema };\n const ref = seen.ref;\n seen.ref = null; // prevent infinite recursion\n if (ref) {\n flattenRef(ref);\n const refSeen = ctx.seen.get(ref);\n const refSchema = refSeen.schema;\n // merge referenced schema into current\n if (refSchema.$ref && (ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\")) {\n // older drafts can't combine $ref with other properties\n schema.allOf = schema.allOf ?? [];\n schema.allOf.push(refSchema);\n }\n else {\n Object.assign(schema, refSchema);\n }\n // restore child's own properties (child wins)\n Object.assign(schema, _cached);\n const isParentRef = zodSchema._zod.parent === ref;\n // For parent chain, child is a refinement - remove parent-only properties\n if (isParentRef) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (!(key in _cached)) {\n delete schema[key];\n }\n }\n }\n // When ref was extracted to $defs, remove properties that match the definition\n if (refSchema.$ref && refSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n // If parent was extracted (has $ref), propagate $ref to this schema\n // This handles cases like: readonly().meta({id}).describe()\n // where processor sets ref to innerType but parent should be referenced\n const parent = zodSchema._zod.parent;\n if (parent && parent !== ref) {\n // Ensure parent is processed first so its def has inherited properties\n flattenRef(parent);\n const parentSeen = ctx.seen.get(parent);\n if (parentSeen?.schema.$ref) {\n schema.$ref = parentSeen.schema.$ref;\n // De-duplicate with parent's definition\n if (parentSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n }\n // execute overrides\n ctx.override({\n zodSchema: zodSchema,\n jsonSchema: schema,\n path: seen.path ?? [],\n });\n };\n for (const entry of [...ctx.seen.entries()].reverse()) {\n flattenRef(entry[0]);\n }\n const result = {};\n if (ctx.target === \"draft-2020-12\") {\n result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n }\n else if (ctx.target === \"draft-07\") {\n result.$schema = \"http://json-schema.org/draft-07/schema#\";\n }\n else if (ctx.target === \"draft-04\") {\n result.$schema = \"http://json-schema.org/draft-04/schema#\";\n }\n else if (ctx.target === \"openapi-3.0\") {\n // OpenAPI 3.0 schema objects should not include a $schema property\n }\n else {\n // Arbitrary string values are allowed but won't have a $schema property set\n }\n if (ctx.external?.uri) {\n const id = ctx.external.registry.get(schema)?.id;\n if (!id)\n throw new Error(\"Schema is missing an `id` property\");\n result.$id = ctx.external.uri(id);\n }\n Object.assign(result, root.def ?? root.schema);\n // build defs object\n const defs = ctx.external?.defs ?? {};\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.def && seen.defId) {\n defs[seen.defId] = seen.def;\n }\n }\n // set definitions in result\n if (ctx.external) {\n }\n else {\n if (Object.keys(defs).length > 0) {\n if (ctx.target === \"draft-2020-12\") {\n result.$defs = defs;\n }\n else {\n result.definitions = defs;\n }\n }\n }\n try {\n // this \"finalizes\" this schema and ensures all cycles are removed\n // each call to finalize() is functionally independent\n // though the seen map is shared\n const finalized = JSON.parse(JSON.stringify(result));\n Object.defineProperty(finalized, \"~standard\", {\n value: {\n ...schema[\"~standard\"],\n jsonSchema: {\n input: createStandardJSONSchemaMethod(schema, \"input\", ctx.processors),\n output: createStandardJSONSchemaMethod(schema, \"output\", ctx.processors),\n },\n },\n enumerable: false,\n writable: false,\n });\n return finalized;\n }\n catch (_err) {\n throw new Error(\"Error converting schema to JSON.\");\n }\n}\nfunction isTransforming(_schema, _ctx) {\n const ctx = _ctx ?? { seen: new Set() };\n if (ctx.seen.has(_schema))\n return false;\n ctx.seen.add(_schema);\n const def = _schema._zod.def;\n if (def.type === \"transform\")\n return true;\n if (def.type === \"array\")\n return isTransforming(def.element, ctx);\n if (def.type === \"set\")\n return isTransforming(def.valueType, ctx);\n if (def.type === \"lazy\")\n return isTransforming(def.getter(), ctx);\n if (def.type === \"promise\" ||\n def.type === \"optional\" ||\n def.type === \"nonoptional\" ||\n def.type === \"nullable\" ||\n def.type === \"readonly\" ||\n def.type === \"default\" ||\n def.type === \"prefault\") {\n return isTransforming(def.innerType, ctx);\n }\n if (def.type === \"intersection\") {\n return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);\n }\n if (def.type === \"record\" || def.type === \"map\") {\n return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);\n }\n if (def.type === \"pipe\") {\n return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);\n }\n if (def.type === \"object\") {\n for (const key in def.shape) {\n if (isTransforming(def.shape[key], ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"union\") {\n for (const option of def.options) {\n if (isTransforming(option, ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"tuple\") {\n for (const item of def.items) {\n if (isTransforming(item, ctx))\n return true;\n }\n if (def.rest && isTransforming(def.rest, ctx))\n return true;\n return false;\n }\n return false;\n}\n/**\n * Creates a toJSONSchema method for a schema instance.\n * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.\n */\nexport const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {\n const ctx = initializeContext({ ...params, processors });\n process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\nexport const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {\n const { libraryOptions, target } = params ?? {};\n const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });\n process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\n","import { extractDefs, finalize, initializeContext, process, } from \"./to-json-schema.js\";\nimport { getEnumValues } from \"./util.js\";\nconst formatMap = {\n guid: \"uuid\",\n url: \"uri\",\n datetime: \"date-time\",\n json_string: \"json-string\",\n regex: \"\", // do not set\n};\n// ==================== SIMPLE TYPE PROCESSORS ====================\nexport const stringProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n json.type = \"string\";\n const { minimum, maximum, format, patterns, contentEncoding } = schema._zod\n .bag;\n if (typeof minimum === \"number\")\n json.minLength = minimum;\n if (typeof maximum === \"number\")\n json.maxLength = maximum;\n // custom pattern overrides format\n if (format) {\n json.format = formatMap[format] ?? format;\n if (json.format === \"\")\n delete json.format; // empty format is not valid\n // JSON Schema format: \"time\" requires a full time with offset or Z\n // z.iso.time() does not include timezone information, so format: \"time\" should never be used\n if (format === \"time\") {\n delete json.format;\n }\n }\n if (contentEncoding)\n json.contentEncoding = contentEncoding;\n if (patterns && patterns.size > 0) {\n const regexes = [...patterns];\n if (regexes.length === 1)\n json.pattern = regexes[0].source;\n else if (regexes.length > 1) {\n json.allOf = [\n ...regexes.map((regex) => ({\n ...(ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\"\n ? { type: \"string\" }\n : {}),\n pattern: regex.source,\n })),\n ];\n }\n }\n};\nexport const numberProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;\n if (typeof format === \"string\" && format.includes(\"int\"))\n json.type = \"integer\";\n else\n json.type = \"number\";\n if (typeof exclusiveMinimum === \"number\") {\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.minimum = exclusiveMinimum;\n json.exclusiveMinimum = true;\n }\n else {\n json.exclusiveMinimum = exclusiveMinimum;\n }\n }\n if (typeof minimum === \"number\") {\n json.minimum = minimum;\n if (typeof exclusiveMinimum === \"number\" && ctx.target !== \"draft-04\") {\n if (exclusiveMinimum >= minimum)\n delete json.minimum;\n else\n delete json.exclusiveMinimum;\n }\n }\n if (typeof exclusiveMaximum === \"number\") {\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.maximum = exclusiveMaximum;\n json.exclusiveMaximum = true;\n }\n else {\n json.exclusiveMaximum = exclusiveMaximum;\n }\n }\n if (typeof maximum === \"number\") {\n json.maximum = maximum;\n if (typeof exclusiveMaximum === \"number\" && ctx.target !== \"draft-04\") {\n if (exclusiveMaximum <= maximum)\n delete json.maximum;\n else\n delete json.exclusiveMaximum;\n }\n }\n if (typeof multipleOf === \"number\")\n json.multipleOf = multipleOf;\n};\nexport const booleanProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const bigintProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt cannot be represented in JSON Schema\");\n }\n};\nexport const symbolProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Symbols cannot be represented in JSON Schema\");\n }\n};\nexport const nullProcessor = (_schema, ctx, json, _params) => {\n if (ctx.target === \"openapi-3.0\") {\n json.type = \"string\";\n json.nullable = true;\n json.enum = [null];\n }\n else {\n json.type = \"null\";\n }\n};\nexport const undefinedProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Undefined cannot be represented in JSON Schema\");\n }\n};\nexport const voidProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Void cannot be represented in JSON Schema\");\n }\n};\nexport const neverProcessor = (_schema, _ctx, json, _params) => {\n json.not = {};\n};\nexport const anyProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const unknownProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const dateProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Date cannot be represented in JSON Schema\");\n }\n};\nexport const enumProcessor = (schema, _ctx, json, _params) => {\n const def = schema._zod.def;\n const values = getEnumValues(def.entries);\n // Number enums can have both string and number values\n if (values.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (values.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n json.enum = values;\n};\nexport const literalProcessor = (schema, ctx, json, _params) => {\n const def = schema._zod.def;\n const vals = [];\n for (const val of def.values) {\n if (val === undefined) {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Literal `undefined` cannot be represented in JSON Schema\");\n }\n else {\n // do not add to vals\n }\n }\n else if (typeof val === \"bigint\") {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt literals cannot be represented in JSON Schema\");\n }\n else {\n vals.push(Number(val));\n }\n }\n else {\n vals.push(val);\n }\n }\n if (vals.length === 0) {\n // do nothing (an undefined literal was stripped)\n }\n else if (vals.length === 1) {\n const val = vals[0];\n json.type = val === null ? \"null\" : typeof val;\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.enum = [val];\n }\n else {\n json.const = val;\n }\n }\n else {\n if (vals.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (vals.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n if (vals.every((v) => typeof v === \"boolean\"))\n json.type = \"boolean\";\n if (vals.every((v) => v === null))\n json.type = \"null\";\n json.enum = vals;\n }\n};\nexport const nanProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"NaN cannot be represented in JSON Schema\");\n }\n};\nexport const templateLiteralProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const pattern = schema._zod.pattern;\n if (!pattern)\n throw new Error(\"Pattern not found in template literal\");\n _json.type = \"string\";\n _json.pattern = pattern.source;\n};\nexport const fileProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const file = {\n type: \"string\",\n format: \"binary\",\n contentEncoding: \"binary\",\n };\n const { minimum, maximum, mime } = schema._zod.bag;\n if (minimum !== undefined)\n file.minLength = minimum;\n if (maximum !== undefined)\n file.maxLength = maximum;\n if (mime) {\n if (mime.length === 1) {\n file.contentMediaType = mime[0];\n Object.assign(_json, file);\n }\n else {\n Object.assign(_json, file); // shared props at root\n _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs\n }\n }\n else {\n Object.assign(_json, file);\n }\n};\nexport const successProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const customProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Custom types cannot be represented in JSON Schema\");\n }\n};\nexport const functionProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Function types cannot be represented in JSON Schema\");\n }\n};\nexport const transformProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Transforms cannot be represented in JSON Schema\");\n }\n};\nexport const mapProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Map cannot be represented in JSON Schema\");\n }\n};\nexport const setProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Set cannot be represented in JSON Schema\");\n }\n};\n// ==================== COMPOSITE TYPE PROCESSORS ====================\nexport const arrayProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n json.type = \"array\";\n json.items = process(def.element, ctx, { ...params, path: [...params.path, \"items\"] });\n};\nexport const objectProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n json.properties = {};\n const shape = def.shape;\n for (const key in shape) {\n json.properties[key] = process(shape[key], ctx, {\n ...params,\n path: [...params.path, \"properties\", key],\n });\n }\n // required keys\n const allKeys = new Set(Object.keys(shape));\n const requiredKeys = new Set([...allKeys].filter((key) => {\n const v = def.shape[key]._zod;\n if (ctx.io === \"input\") {\n return v.optin === undefined;\n }\n else {\n return v.optout === undefined;\n }\n }));\n if (requiredKeys.size > 0) {\n json.required = Array.from(requiredKeys);\n }\n // catchall\n if (def.catchall?._zod.def.type === \"never\") {\n // strict\n json.additionalProperties = false;\n }\n else if (!def.catchall) {\n // regular\n if (ctx.io === \"output\")\n json.additionalProperties = false;\n }\n else if (def.catchall) {\n json.additionalProperties = process(def.catchall, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n};\nexport const unionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches)\n // This includes both z.xor() and discriminated unions\n const isExclusive = def.inclusive === false;\n const options = def.options.map((x, i) => process(x, ctx, {\n ...params,\n path: [...params.path, isExclusive ? \"oneOf\" : \"anyOf\", i],\n }));\n if (isExclusive) {\n json.oneOf = options;\n }\n else {\n json.anyOf = options;\n }\n};\nexport const intersectionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const a = process(def.left, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 0],\n });\n const b = process(def.right, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 1],\n });\n const isSimpleIntersection = (val) => \"allOf\" in val && Object.keys(val).length === 1;\n const allOf = [\n ...(isSimpleIntersection(a) ? a.allOf : [a]),\n ...(isSimpleIntersection(b) ? b.allOf : [b]),\n ];\n json.allOf = allOf;\n};\nexport const tupleProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"array\";\n const prefixPath = ctx.target === \"draft-2020-12\" ? \"prefixItems\" : \"items\";\n const restPath = ctx.target === \"draft-2020-12\" ? \"items\" : ctx.target === \"openapi-3.0\" ? \"items\" : \"additionalItems\";\n const prefixItems = def.items.map((x, i) => process(x, ctx, {\n ...params,\n path: [...params.path, prefixPath, i],\n }));\n const rest = def.rest\n ? process(def.rest, ctx, {\n ...params,\n path: [...params.path, restPath, ...(ctx.target === \"openapi-3.0\" ? [def.items.length] : [])],\n })\n : null;\n if (ctx.target === \"draft-2020-12\") {\n json.prefixItems = prefixItems;\n if (rest) {\n json.items = rest;\n }\n }\n else if (ctx.target === \"openapi-3.0\") {\n json.items = {\n anyOf: prefixItems,\n };\n if (rest) {\n json.items.anyOf.push(rest);\n }\n json.minItems = prefixItems.length;\n if (!rest) {\n json.maxItems = prefixItems.length;\n }\n }\n else {\n json.items = prefixItems;\n if (rest) {\n json.additionalItems = rest;\n }\n }\n // length\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n};\nexport const recordProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n // For looseRecord with regex patterns, use patternProperties\n // This correctly represents \"only validate keys matching the pattern\" semantics\n // and composes well with allOf (intersections)\n const keyType = def.keyType;\n const keyBag = keyType._zod.bag;\n const patterns = keyBag?.patterns;\n if (def.mode === \"loose\" && patterns && patterns.size > 0) {\n // Use patternProperties for looseRecord with regex patterns\n const valueSchema = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"patternProperties\", \"*\"],\n });\n json.patternProperties = {};\n for (const pattern of patterns) {\n json.patternProperties[pattern.source] = valueSchema;\n }\n }\n else {\n // Default behavior: use propertyNames + additionalProperties\n if (ctx.target === \"draft-07\" || ctx.target === \"draft-2020-12\") {\n json.propertyNames = process(def.keyType, ctx, {\n ...params,\n path: [...params.path, \"propertyNames\"],\n });\n }\n json.additionalProperties = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n // Add required for keys with discrete values (enum, literal, etc.)\n const keyValues = keyType._zod.values;\n if (keyValues) {\n const validKeyValues = [...keyValues].filter((v) => typeof v === \"string\" || typeof v === \"number\");\n if (validKeyValues.length > 0) {\n json.required = validKeyValues;\n }\n }\n};\nexport const nullableProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const inner = process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n if (ctx.target === \"openapi-3.0\") {\n seen.ref = def.innerType;\n json.nullable = true;\n }\n else {\n json.anyOf = [inner, { type: \"null\" }];\n }\n};\nexport const nonoptionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const defaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.default = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const prefaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n if (ctx.io === \"input\")\n json._prefault = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const catchProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n let catchValue;\n try {\n catchValue = def.catchValue(undefined);\n }\n catch {\n throw new Error(\"Dynamic catch values are not supported in JSON Schema\");\n }\n json.default = catchValue;\n};\nexport const pipeProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n const innerType = ctx.io === \"input\" ? (def.in._zod.def.type === \"transform\" ? def.out : def.in) : def.out;\n process(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\nexport const readonlyProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.readOnly = true;\n};\nexport const promiseProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const optionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const lazyProcessor = (schema, ctx, _json, params) => {\n const innerType = schema._zod.innerType;\n process(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\n// ==================== ALL PROCESSORS ====================\nexport const allProcessors = {\n string: stringProcessor,\n number: numberProcessor,\n boolean: booleanProcessor,\n bigint: bigintProcessor,\n symbol: symbolProcessor,\n null: nullProcessor,\n undefined: undefinedProcessor,\n void: voidProcessor,\n never: neverProcessor,\n any: anyProcessor,\n unknown: unknownProcessor,\n date: dateProcessor,\n enum: enumProcessor,\n literal: literalProcessor,\n nan: nanProcessor,\n template_literal: templateLiteralProcessor,\n file: fileProcessor,\n success: successProcessor,\n custom: customProcessor,\n function: functionProcessor,\n transform: transformProcessor,\n map: mapProcessor,\n set: setProcessor,\n array: arrayProcessor,\n object: objectProcessor,\n union: unionProcessor,\n intersection: intersectionProcessor,\n tuple: tupleProcessor,\n record: recordProcessor,\n nullable: nullableProcessor,\n nonoptional: nonoptionalProcessor,\n default: defaultProcessor,\n prefault: prefaultProcessor,\n catch: catchProcessor,\n pipe: pipeProcessor,\n readonly: readonlyProcessor,\n promise: promiseProcessor,\n optional: optionalProcessor,\n lazy: lazyProcessor,\n};\nexport function toJSONSchema(input, params) {\n if (\"_idmap\" in input) {\n // Registry case\n const registry = input;\n const ctx = initializeContext({ ...params, processors: allProcessors });\n const defs = {};\n // First pass: process all schemas to build the seen map\n for (const entry of registry._idmap.entries()) {\n const [_, schema] = entry;\n process(schema, ctx);\n }\n const schemas = {};\n const external = {\n registry,\n uri: params?.uri,\n defs,\n };\n // Update the context with external configuration\n ctx.external = external;\n // Second pass: emit each schema\n for (const entry of registry._idmap.entries()) {\n const [key, schema] = entry;\n extractDefs(ctx, schema);\n schemas[key] = finalize(ctx, schema);\n }\n if (Object.keys(defs).length > 0) {\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n schemas.__shared = {\n [defsSegment]: defs,\n };\n }\n return { schemas };\n }\n // Single schema case\n const ctx = initializeContext({ ...params, processors: allProcessors });\n process(input, ctx);\n extractDefs(ctx, input);\n return finalize(ctx, input);\n}\n","import type {\n CredentialRequirement,\n CredentialSessionService,\n NodeConfigBase,\n NodeExecutionContext,\n NodeId,\n} from \"@codemation/core\";\n\nimport { CredentialResolverFactory } from \"@codemation/core/bootstrap\";\n\n/**\n * Builds a {@link NodeExecutionContext} whose identity for credential binding and `getCredential`\n * is a **connection-owned** workflow node id (`ConnectionNodeIdFactory` in `@codemation/core`),\n * not the executing parent node. Use for LLM slots, tool slots, or any connection-scoped owner.\n */\nexport class ConnectionCredentialExecutionContextFactory {\n private readonly credentialResolverFactory: CredentialResolverFactory;\n\n constructor(credentialSessions: CredentialSessionService) {\n this.credentialResolverFactory = new CredentialResolverFactory(credentialSessions);\n }\n\n forConnectionNode<TConfig extends NodeConfigBase>(\n ctx: NodeExecutionContext<TConfig>,\n args: Readonly<{\n connectionNodeId: NodeId;\n getCredentialRequirements: () => ReadonlyArray<CredentialRequirement>;\n }>,\n ): NodeExecutionContext<TConfig> {\n const stubConfig = { getCredentialRequirements: args.getCredentialRequirements } as NodeConfigBase;\n const getCredential = this.credentialResolverFactory.create(ctx.workflowId, args.connectionNodeId, stubConfig);\n return {\n ...ctx,\n nodeId: args.connectionNodeId,\n getCredential,\n };\n }\n}\n","import type { CredentialSessionService, Item, Items, NodeExecutionContext, ZodSchemaAny } from \"@codemation/core\";\nimport { injectable } from \"@codemation/core\";\n\nimport { isInteropZodSchema } from \"@langchain/core/utils/types\";\nimport { toJsonSchema } from \"@langchain/core/utils/json_schema\";\nimport { DynamicStructuredTool } from \"@langchain/core/tools\";\nimport { toJSONSchema } from \"zod/v4/core\";\n\nimport { ConnectionCredentialExecutionContextFactory } from \"./ConnectionCredentialExecutionContextFactory\";\nimport type { ResolvedTool } from \"./aiAgentSupport.types\";\n\n/**\n * LangChain adapters and credential context wiring for {@link AIAgentNode}.\n * Lives in a `*Factory.ts` composition-root module so construction stays explicit and testable.\n */\n@injectable()\nexport class AIAgentExecutionHelpersFactory {\n createConnectionCredentialExecutionContextFactory(\n credentialSessions: CredentialSessionService,\n ): ConnectionCredentialExecutionContextFactory {\n return new ConnectionCredentialExecutionContextFactory(credentialSessions);\n }\n\n createDynamicStructuredTool(\n entry: ResolvedTool,\n toolCredentialContext: NodeExecutionContext<any>,\n item: Item,\n itemIndex: number,\n items: Items,\n ): DynamicStructuredTool {\n if (entry.runtime.inputSchema == null) {\n throw new Error(\n `Cannot create LangChain tool \"${entry.config.name}\": missing inputSchema (broken tool runtime resolution).`,\n );\n }\n const schemaForOpenAi = this.normalizeToolInputSchemaForOpenAiDynamicStructuredTool(\n entry.config.name,\n entry.runtime.inputSchema,\n );\n return new DynamicStructuredTool({\n name: entry.config.name,\n description: entry.config.description ?? entry.runtime.defaultDescription,\n schema: schemaForOpenAi as unknown as ZodSchemaAny,\n func: async (input) => {\n const result = await entry.runtime.execute({\n config: entry.config,\n input,\n ctx: toolCredentialContext,\n item,\n itemIndex,\n items,\n });\n return JSON.stringify(result);\n },\n });\n }\n\n /**\n * Produces a plain JSON Schema object for OpenAI tool parameters and LangChain tool invocation:\n * - **Zod** → `toJSONSchema(..., { target: \"draft-07\" })` so shapes match what `@cfworker/json-schema`\n * expects (`required` must be an array; draft 2020-12 output can break validation).\n * - Otherwise LangChain `toJsonSchema` (Standard Schema + JSON passthrough); if the result is still Zod\n * (duplicate `zod` copies), fall back to Zod `toJSONSchema` with draft-07.\n * - Strip root `$schema` for OpenAI; normalize invalid `required` keywords for cfworker; ensure `properties`.\n */\n private normalizeToolInputSchemaForOpenAiDynamicStructuredTool(\n toolName: string,\n inputSchema: ZodSchemaAny,\n ): Record<string, unknown> {\n const draft07Params = { target: \"draft-07\" as const };\n let converted: unknown;\n if (isInteropZodSchema(inputSchema)) {\n converted = toJSONSchema(inputSchema as unknown as Parameters<typeof toJSONSchema>[0], draft07Params);\n } else {\n converted = toJsonSchema(inputSchema);\n if (isInteropZodSchema(converted)) {\n converted = toJSONSchema(inputSchema as unknown as Parameters<typeof toJSONSchema>[0], draft07Params);\n }\n }\n const record = converted as Record<string, unknown>;\n const { $schema: _draftSchemaOmitted, ...rest } = record;\n if (rest.type !== \"object\") {\n throw new Error(\n `Cannot create LangChain tool \"${toolName}\": tool input schema must be a JSON Schema object type (got type=${String(rest.type)}).`,\n );\n }\n if (rest.properties !== undefined && (typeof rest.properties !== \"object\" || Array.isArray(rest.properties))) {\n throw new Error(\n `Cannot create LangChain tool \"${toolName}\": tool input schema \"properties\" must be an object (got ${JSON.stringify(rest.properties)}).`,\n );\n }\n if (rest.properties === undefined) {\n rest.properties = {};\n }\n this.sanitizeJsonSchemaRequiredKeywordsForCfworker(rest);\n return rest;\n }\n\n /**\n * `@cfworker/json-schema` iterates `schema.required` with `for...of`; it must be a string array or absent.\n */\n private sanitizeJsonSchemaRequiredKeywordsForCfworker(node: unknown): void {\n if (!node || typeof node !== \"object\" || Array.isArray(node)) {\n return;\n }\n const o = node as Record<string, unknown>;\n const req = o.required;\n if (req !== undefined && !Array.isArray(req)) {\n delete o.required;\n } else if (Array.isArray(req)) {\n const strings = req.filter((x): x is string => typeof x === \"string\");\n if (strings.length === 0) {\n delete o.required;\n } else if (strings.length !== req.length) {\n o.required = strings;\n }\n }\n const props = o.properties;\n if (props && typeof props === \"object\" && !Array.isArray(props)) {\n for (const v of Object.values(props)) {\n this.sanitizeJsonSchemaRequiredKeywordsForCfworker(v);\n }\n }\n for (const key of [\"allOf\", \"anyOf\", \"oneOf\"] as const) {\n const branch = o[key];\n if (Array.isArray(branch)) {\n for (const sub of branch) {\n this.sanitizeJsonSchemaRequiredKeywordsForCfworker(sub);\n }\n }\n }\n if (o.if) this.sanitizeJsonSchemaRequiredKeywordsForCfworker(o.if);\n if (o.then) this.sanitizeJsonSchemaRequiredKeywordsForCfworker(o.then);\n if (o.else) this.sanitizeJsonSchemaRequiredKeywordsForCfworker(o.else);\n if (o.not) this.sanitizeJsonSchemaRequiredKeywordsForCfworker(o.not);\n if (o.items) this.sanitizeJsonSchemaRequiredKeywordsForCfworker(o.items);\n if (Array.isArray(o.prefixItems)) {\n for (const sub of o.prefixItems) {\n this.sanitizeJsonSchemaRequiredKeywordsForCfworker(sub);\n }\n }\n }\n}\n","import type {\n MultiInputNode,\n Node,\n NodeExecutionContext,\n NodeOutputs,\n NodeResolver,\n NodeBackedToolConfig,\n ToolExecuteArgs,\n ZodSchemaAny,\n} from \"@codemation/core\";\nimport { CoreTokens, inject, injectable } from \"@codemation/core\";\n\n@injectable()\nexport class NodeBackedToolRuntime {\n constructor(\n @inject(CoreTokens.NodeResolver)\n private readonly nodeResolver: NodeResolver,\n ) {}\n\n async execute(\n config: NodeBackedToolConfig<any, ZodSchemaAny, ZodSchemaAny>,\n args: ToolExecuteArgs,\n ): Promise<unknown> {\n const nodeInput = config.toNodeItem({\n input: args.input,\n item: args.item,\n itemIndex: args.itemIndex,\n items: args.items,\n ctx: args.ctx,\n node: config.node,\n });\n const nodeCtx = {\n ...args.ctx,\n config: config.node,\n } as NodeExecutionContext<any>;\n const resolvedNode = this.nodeResolver.resolve(config.node.type);\n const outputs = await this.executeResolvedNode(resolvedNode, nodeInput, nodeCtx);\n return config.toToolOutput({\n input: args.input,\n item: args.item,\n itemIndex: args.itemIndex,\n items: args.items,\n ctx: args.ctx,\n node: config.node,\n outputs,\n });\n }\n\n private async executeResolvedNode(\n resolvedNode: unknown,\n nodeInput: ToolExecuteArgs[\"item\"],\n ctx: NodeExecutionContext<any>,\n ): Promise<NodeOutputs> {\n if (this.isMultiInputNode(resolvedNode)) {\n return await resolvedNode.executeMulti({ in: [nodeInput] }, ctx);\n }\n if (this.isNode(resolvedNode)) {\n return await resolvedNode.execute([nodeInput], ctx);\n }\n throw new Error(`Node-backed tool expected a runnable node instance for \"${ctx.config.name ?? ctx.nodeId}\".`);\n }\n\n private isNode(value: unknown): value is Node<any> {\n return typeof value === \"object\" && value !== null && \"execute\" in value;\n }\n\n private isMultiInputNode(value: unknown): value is MultiInputNode<any> {\n return typeof value === \"object\" && value !== null && \"executeMulti\" in value;\n }\n}\n","import type {\n AgentToolCall,\n Item,\n NodeInputsByPort,\n ToolConfig,\n ToolExecuteArgs,\n ZodSchemaAny,\n} from \"@codemation/core\";\nimport type { DynamicStructuredTool } from \"@langchain/core/tools\";\n\nexport class AgentItemPortMap {\n static fromItem(item: Item): NodeInputsByPort {\n return { in: [item] };\n }\n}\n\nexport type ResolvedTool = Readonly<{\n config: ToolConfig;\n runtime: Readonly<{\n defaultDescription: string;\n inputSchema: ZodSchemaAny;\n execute(args: ToolExecuteArgs<ToolConfig, unknown>): Promise<unknown>;\n }>;\n}>;\n\nexport type ItemScopedToolBinding = Readonly<{\n config: ToolConfig;\n langChainTool: DynamicStructuredTool;\n}>;\n\nexport type PlannedToolCall = Readonly<{\n binding: ItemScopedToolBinding;\n toolCall: AgentToolCall;\n invocationIndex: number;\n nodeId: string;\n}>;\n\nexport type ExecutedToolCall = Readonly<{\n toolName: string;\n toolCallId: string;\n result: unknown;\n serialized: string;\n}>;\n","import type {\n AgentGuardrailConfig,\n AgentToolCall,\n ChatModelConfig,\n ChatModelFactory,\n Item,\n Items,\n JsonValue,\n LangChainChatModelLike,\n Node,\n NodeExecutionContext,\n NodeInputsByPort,\n NodeOutputs,\n Tool,\n ToolConfig,\n ZodSchemaAny,\n} from \"@codemation/core\";\n\nimport type { CredentialSessionService } from \"@codemation/core\";\nimport {\n AgentGuardrailDefaults,\n AgentMessageConfigNormalizer,\n ConnectionInvocationIdFactory,\n ConnectionNodeIdFactory,\n CoreTokens,\n NodeBackedToolConfig,\n inject,\n node,\n type NodeResolver,\n} from \"@codemation/core\";\n\nimport { AIMessage, type BaseMessage } from \"@langchain/core/messages\";\n\nimport type { AIAgent } from \"./AIAgentConfig\";\nimport { AIAgentExecutionHelpersFactory } from \"./AIAgentExecutionHelpersFactory\";\nimport { ConnectionCredentialExecutionContextFactory } from \"./ConnectionCredentialExecutionContextFactory\";\nimport { AgentMessageFactory } from \"./AgentMessageFactory\";\nimport { AgentOutputFactory } from \"./AgentOutputFactory\";\nimport { AgentToolCallPortMap } from \"./AgentToolCallPortMapFactory\";\nimport { NodeBackedToolRuntime } from \"./NodeBackedToolRuntime\";\nimport {\n AgentItemPortMap,\n type ExecutedToolCall,\n type ItemScopedToolBinding,\n type PlannedToolCall,\n type ResolvedTool,\n} from \"./aiAgentSupport.types\";\n\ntype ResolvedGuardrails = Required<Pick<AgentGuardrailConfig, \"maxTurns\" | \"onTurnLimitReached\">> &\n Pick<AgentGuardrailConfig, \"modelInvocationOptions\">;\n\n/** Everything needed to run the agent loop for a workflow execution (one `execute` call). */\ninterface PreparedAgentExecution {\n readonly ctx: NodeExecutionContext<AIAgent<any, any>>;\n readonly model: LangChainChatModelLike;\n readonly resolvedTools: ReadonlyArray<ResolvedTool>;\n readonly guardrails: ResolvedGuardrails;\n readonly languageModelConnectionNodeId: string;\n}\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class AIAgentNode implements Node<AIAgent<any, any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n private readonly connectionCredentialExecutionContextFactory: ConnectionCredentialExecutionContextFactory;\n\n constructor(\n @inject(CoreTokens.NodeResolver)\n private readonly nodeResolver: NodeResolver,\n @inject(CoreTokens.CredentialSessionService)\n credentialSessions: CredentialSessionService,\n @inject(NodeBackedToolRuntime)\n private readonly nodeBackedToolRuntime: NodeBackedToolRuntime,\n @inject(AIAgentExecutionHelpersFactory)\n private readonly executionHelpers: AIAgentExecutionHelpersFactory,\n ) {\n this.connectionCredentialExecutionContextFactory =\n this.executionHelpers.createConnectionCredentialExecutionContextFactory(credentialSessions);\n }\n\n async execute(items: Items, ctx: NodeExecutionContext<AIAgent<any, any>>): Promise<NodeOutputs> {\n const prepared = await this.prepareExecution(ctx);\n const out: Item[] = [];\n for (let i = 0; i < items.length; i++) {\n out.push(await this.runAgentForItem(prepared, items[i]!, i, items));\n }\n return { main: out };\n }\n\n /**\n * Resolves the chat model and tools once, then returns shared state for every item in the batch.\n */\n private async prepareExecution(ctx: NodeExecutionContext<AIAgent<any, any>>): Promise<PreparedAgentExecution> {\n const chatModelFactory = this.nodeResolver.resolve(ctx.config.chatModel.type) as ChatModelFactory<ChatModelConfig>;\n const languageModelCredentialContext = this.connectionCredentialExecutionContextFactory.forConnectionNode(ctx, {\n connectionNodeId: ConnectionNodeIdFactory.languageModelConnectionNodeId(ctx.nodeId),\n getCredentialRequirements: () => ctx.config.chatModel.getCredentialRequirements?.() ?? [],\n });\n const model = await Promise.resolve(\n chatModelFactory.create({ config: ctx.config.chatModel, ctx: languageModelCredentialContext }),\n );\n return {\n ctx,\n model,\n resolvedTools: this.resolveTools(ctx.config.tools ?? []),\n guardrails: this.resolveGuardrails(ctx.config.guardrails),\n languageModelConnectionNodeId: ConnectionNodeIdFactory.languageModelConnectionNodeId(ctx.nodeId),\n };\n }\n\n /**\n * One item: build prompts, optionally bind tools, run the multi-turn loop, map the final model message to workflow JSON.\n */\n private async runAgentForItem(\n prepared: PreparedAgentExecution,\n item: Item,\n itemIndex: number,\n items: Items,\n ): Promise<Item> {\n const { ctx } = prepared;\n const itemInputsByPort = AgentItemPortMap.fromItem(item);\n const itemScopedTools = this.createItemScopedTools(prepared.resolvedTools, ctx, item, itemIndex, items);\n const conversation: BaseMessage[] = [...this.createPromptMessages(item, itemIndex, items, ctx)];\n const modelWithTools = this.bindToolsToModel(prepared.model, itemScopedTools);\n const finalResponse = await this.runTurnLoopUntilFinalAnswer({\n prepared,\n itemInputsByPort,\n itemScopedTools,\n conversation,\n modelWithTools,\n });\n return this.buildOutputItem(item, finalResponse);\n }\n\n /**\n * Repeatedly invokes the model until it returns without tool calls, or guardrails end the loop.\n */\n private async runTurnLoopUntilFinalAnswer(args: {\n prepared: PreparedAgentExecution;\n itemInputsByPort: NodeInputsByPort;\n itemScopedTools: ReadonlyArray<ItemScopedToolBinding>;\n conversation: BaseMessage[];\n modelWithTools: LangChainChatModelLike;\n }): Promise<AIMessage> {\n const { prepared, itemInputsByPort, itemScopedTools, conversation, modelWithTools } = args;\n const { ctx, guardrails, languageModelConnectionNodeId } = prepared;\n\n let finalResponse: AIMessage | undefined;\n\n for (let turn = 1; turn <= guardrails.maxTurns; turn++) {\n const response = await this.invokeModel(\n modelWithTools,\n languageModelConnectionNodeId,\n conversation,\n ctx,\n itemInputsByPort,\n guardrails.modelInvocationOptions,\n );\n finalResponse = response;\n\n const toolCalls = AgentMessageFactory.extractToolCalls(response);\n if (toolCalls.length === 0) {\n break;\n }\n\n if (this.cannotExecuteAnotherToolRound(turn, guardrails)) {\n this.finishOrThrowWhenTurnCapHitWithToolCalls(ctx, guardrails);\n break;\n }\n\n const plannedToolCalls = this.planToolCalls(itemScopedTools, toolCalls, ctx.nodeId);\n await this.markQueuedTools(plannedToolCalls, ctx);\n const executedToolCalls = await this.executeToolCalls(plannedToolCalls, ctx);\n this.appendAssistantAndToolMessages(conversation, response, executedToolCalls);\n }\n\n if (!finalResponse) {\n throw new Error(`AIAgent \"${ctx.config.name ?? ctx.nodeId}\" did not produce a model response.`);\n }\n return finalResponse;\n }\n\n private cannotExecuteAnotherToolRound(turn: number, guardrails: ResolvedGuardrails): boolean {\n return turn >= guardrails.maxTurns;\n }\n\n private finishOrThrowWhenTurnCapHitWithToolCalls(\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n guardrails: ResolvedGuardrails,\n ): void {\n if (guardrails.onTurnLimitReached === \"respondWithLastMessage\") {\n return;\n }\n throw new Error(\n `AIAgent \"${ctx.config.name ?? ctx.nodeId}\" reached maxTurns=${guardrails.maxTurns} before producing a final response.`,\n );\n }\n\n private appendAssistantAndToolMessages(\n conversation: BaseMessage[],\n assistantMessage: AIMessage,\n executedToolCalls: ReadonlyArray<ExecutedToolCall>,\n ): void {\n conversation.push(\n assistantMessage,\n ...executedToolCalls.map((toolCall) =>\n AgentMessageFactory.createToolMessage(toolCall.toolCallId, toolCall.serialized),\n ),\n );\n }\n\n private buildOutputItem(item: Item, finalResponse: AIMessage): Item {\n return AgentOutputFactory.replaceJson(\n item,\n AgentOutputFactory.fromAgentContent(AgentMessageFactory.extractContent(finalResponse)),\n );\n }\n\n private bindToolsToModel(\n model: LangChainChatModelLike,\n itemScopedTools: ReadonlyArray<ItemScopedToolBinding>,\n ): LangChainChatModelLike {\n if (itemScopedTools.length === 0 || !model.bindTools) {\n return model;\n }\n return model.bindTools(itemScopedTools.map((entry) => entry.langChainTool));\n }\n\n private resolveTools(toolConfigs: ReadonlyArray<ToolConfig>): ReadonlyArray<ResolvedTool> {\n const resolvedTools = toolConfigs.map((config) => ({\n config,\n runtime: this.resolveToolRuntime(config),\n }));\n\n const names = new Set<string>();\n for (const entry of resolvedTools) {\n if (names.has(entry.config.name)) throw new Error(`Duplicate tool name on AIAgent: ${entry.config.name}`);\n names.add(entry.config.name);\n }\n return resolvedTools;\n }\n\n private createItemScopedTools(\n tools: ReadonlyArray<ResolvedTool>,\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n item: Item,\n itemIndex: number,\n items: Items,\n ): ReadonlyArray<ItemScopedToolBinding> {\n return tools.map((entry) => {\n const toolCredentialContext = this.connectionCredentialExecutionContextFactory.forConnectionNode(ctx, {\n connectionNodeId: ConnectionNodeIdFactory.toolConnectionNodeId(ctx.nodeId, entry.config.name),\n getCredentialRequirements: () => entry.config.getCredentialRequirements?.() ?? [],\n });\n const langChainTool = this.executionHelpers.createDynamicStructuredTool(\n entry,\n toolCredentialContext,\n item,\n itemIndex,\n items,\n );\n\n return { config: entry.config, langChainTool };\n });\n }\n\n private async invokeModel(\n model: LangChainChatModelLike,\n nodeId: string,\n messages: ReadonlyArray<BaseMessage>,\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n inputsByPort: NodeInputsByPort,\n options?: AgentGuardrailConfig[\"modelInvocationOptions\"],\n ): Promise<AIMessage> {\n await ctx.nodeState?.markQueued({ nodeId, activationId: ctx.activationId, inputsByPort });\n await ctx.nodeState?.markRunning({ nodeId, activationId: ctx.activationId, inputsByPort });\n try {\n const response = (await model.invoke(messages, options)) as AIMessage;\n await ctx.nodeState?.markCompleted({\n nodeId,\n activationId: ctx.activationId,\n inputsByPort,\n outputs: AgentOutputFactory.fromUnknown({\n content: AgentMessageFactory.extractContent(response),\n }),\n });\n const content = AgentMessageFactory.extractContent(response);\n await ctx.nodeState?.appendConnectionInvocation({\n invocationId: ConnectionInvocationIdFactory.create(),\n connectionNodeId: nodeId,\n parentAgentNodeId: ctx.nodeId,\n parentAgentActivationId: ctx.activationId,\n status: \"completed\",\n managedInput: this.summarizeLlmMessages(messages),\n managedOutput: content,\n finishedAt: new Date().toISOString(),\n });\n return response;\n } catch (error) {\n throw await this.failTrackedNodeInvocation(error, nodeId, ctx, inputsByPort, this.summarizeLlmMessages(messages));\n }\n }\n\n private async markQueuedTools(\n plannedToolCalls: ReadonlyArray<PlannedToolCall>,\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n ): Promise<void> {\n for (const plannedToolCall of plannedToolCalls) {\n await ctx.nodeState?.markQueued({\n nodeId: plannedToolCall.nodeId,\n activationId: ctx.activationId,\n inputsByPort: AgentToolCallPortMap.fromInput(plannedToolCall.toolCall.input ?? {}),\n });\n }\n }\n\n private async executeToolCalls(\n plannedToolCalls: ReadonlyArray<PlannedToolCall>,\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n ): Promise<ReadonlyArray<ExecutedToolCall>> {\n const results = await Promise.allSettled(\n plannedToolCalls.map(async (plannedToolCall) => {\n const toolCallInputsByPort = AgentToolCallPortMap.fromInput(plannedToolCall.toolCall.input ?? {});\n await ctx.nodeState?.markRunning({\n nodeId: plannedToolCall.nodeId,\n activationId: ctx.activationId,\n inputsByPort: toolCallInputsByPort,\n });\n try {\n const serialized = await plannedToolCall.binding.langChainTool.invoke(plannedToolCall.toolCall.input ?? {});\n const result = this.parseToolOutput(serialized);\n await ctx.nodeState?.markCompleted({\n nodeId: plannedToolCall.nodeId,\n activationId: ctx.activationId,\n inputsByPort: toolCallInputsByPort,\n outputs: AgentOutputFactory.fromUnknown(result),\n });\n await ctx.nodeState?.appendConnectionInvocation({\n invocationId: ConnectionInvocationIdFactory.create(),\n connectionNodeId: plannedToolCall.nodeId,\n parentAgentNodeId: ctx.nodeId,\n parentAgentActivationId: ctx.activationId,\n status: \"completed\",\n managedInput: this.toolCallInputToJson(plannedToolCall.toolCall.input),\n managedOutput: this.resultToJsonValue(result),\n finishedAt: new Date().toISOString(),\n });\n return {\n toolName: plannedToolCall.binding.config.name,\n toolCallId: plannedToolCall.toolCall.id ?? plannedToolCall.binding.config.name,\n serialized,\n result,\n } satisfies ExecutedToolCall;\n } catch (error) {\n throw await this.failTrackedNodeInvocation(\n error,\n plannedToolCall.nodeId,\n ctx,\n toolCallInputsByPort,\n this.toolCallInputToJson(plannedToolCall.toolCall.input),\n );\n }\n }),\n );\n\n const rejected = results.find((result) => result.status === \"rejected\");\n if (rejected?.status === \"rejected\") {\n throw rejected.reason instanceof Error ? rejected.reason : new Error(String(rejected.reason));\n }\n\n return results\n .filter((result): result is PromiseFulfilledResult<ExecutedToolCall> => result.status === \"fulfilled\")\n .map((result) => result.value);\n }\n\n private planToolCalls(\n bindings: ReadonlyArray<ItemScopedToolBinding>,\n toolCalls: ReadonlyArray<AgentToolCall>,\n parentNodeId: string,\n ): ReadonlyArray<PlannedToolCall> {\n const invocationCountByToolName = new Map<string, number>();\n return toolCalls.map((toolCall) => {\n const binding = bindings.find((entry) => entry.config.name === toolCall.name);\n if (!binding) throw new Error(`Unknown tool requested by model: ${toolCall.name}`);\n const invocationIndex = (invocationCountByToolName.get(binding.config.name) ?? 0) + 1;\n invocationCountByToolName.set(binding.config.name, invocationIndex);\n return {\n binding,\n toolCall,\n invocationIndex,\n nodeId: ConnectionNodeIdFactory.toolConnectionNodeId(parentNodeId, binding.config.name),\n } satisfies PlannedToolCall;\n });\n }\n\n private parseToolOutput(serialized: unknown): unknown {\n if (typeof serialized !== \"string\") return serialized;\n try {\n return JSON.parse(serialized);\n } catch {\n return serialized;\n }\n }\n\n private async failTrackedNodeInvocation(\n error: unknown,\n nodeId: string,\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n inputsByPort: NodeInputsByPort,\n managedInput?: JsonValue,\n ): Promise<Error> {\n const effectiveError = error instanceof Error ? error : new Error(String(error));\n await ctx.nodeState?.markFailed({\n nodeId,\n activationId: ctx.activationId,\n inputsByPort,\n error: effectiveError,\n });\n await ctx.nodeState?.appendConnectionInvocation({\n invocationId: ConnectionInvocationIdFactory.create(),\n connectionNodeId: nodeId,\n parentAgentNodeId: ctx.nodeId,\n parentAgentActivationId: ctx.activationId,\n status: \"failed\",\n managedInput,\n error: {\n message: effectiveError.message,\n name: effectiveError.name,\n stack: effectiveError.stack,\n },\n finishedAt: new Date().toISOString(),\n });\n return effectiveError;\n }\n\n private summarizeLlmMessages(messages: ReadonlyArray<BaseMessage>): JsonValue {\n const last = messages[messages.length - 1];\n const preview =\n typeof last?.content === \"string\"\n ? last.content\n : last?.content !== undefined\n ? JSON.stringify(last.content)\n : \"\";\n return {\n messageCount: messages.length,\n lastMessagePreview: preview.slice(0, 4000),\n };\n }\n\n private toolCallInputToJson(input: unknown): JsonValue | undefined {\n return this.resultToJsonValue(input);\n }\n\n private resultToJsonValue(value: unknown): JsonValue | undefined {\n if (value === undefined) {\n return undefined;\n }\n const json = JSON.stringify(value);\n return JSON.parse(json) as JsonValue;\n }\n\n private createPromptMessages(\n item: Item,\n itemIndex: number,\n items: Items,\n ctx: NodeExecutionContext<AIAgent<any, any>>,\n ): ReadonlyArray<BaseMessage> {\n return AgentMessageFactory.createPromptMessages(\n AgentMessageConfigNormalizer.normalize(ctx.config, {\n item,\n itemIndex,\n items,\n ctx,\n }),\n );\n }\n\n private resolveToolRuntime(config: ToolConfig): ResolvedTool[\"runtime\"] {\n if (this.isNodeBackedToolConfig(config)) {\n const inputSchema = config.getInputSchema();\n if (inputSchema == null) {\n throw new Error(\n `AIAgent tool \"${config.name}\": node-backed tool is missing inputSchema (cannot build LangChain tool).`,\n );\n }\n return {\n defaultDescription: `Run workflow node \"${config.node.name ?? config.name}\" as an AI tool.`,\n inputSchema,\n execute: async (args) => await this.nodeBackedToolRuntime.execute(config, args),\n };\n }\n const tool = this.nodeResolver.resolve(config.type) as Tool<ToolConfig, ZodSchemaAny, ZodSchemaAny>;\n if (tool.inputSchema == null) {\n throw new Error(`AIAgent tool \"${config.name}\": plugin tool \"${String(config.type)}\" is missing inputSchema.`);\n }\n return {\n defaultDescription: tool.defaultDescription,\n inputSchema: tool.inputSchema,\n execute: async (args) => await Promise.resolve(tool.execute(args)),\n };\n }\n\n /**\n * Consumer apps can resolve two copies of `@codemation/core`, breaking `instanceof NodeBackedToolConfig` and\n * sending node-backed tools down the plugin-tool branch with `inputSchema: undefined` (LangChain then crashes in\n * json-schema validation). {@link NodeBackedToolConfig#toolKind} is stable across copies.\n */\n private isNodeBackedToolConfig(config: ToolConfig): config is NodeBackedToolConfig<any, any, any> {\n return (\n config instanceof NodeBackedToolConfig ||\n (typeof config === \"object\" && config !== null && (config as { toolKind?: unknown }).toolKind === \"nodeBacked\")\n );\n }\n\n private resolveGuardrails(guardrails: AgentGuardrailConfig | undefined): ResolvedGuardrails {\n const maxTurns = guardrails?.maxTurns ?? AgentGuardrailDefaults.maxTurns;\n if (!Number.isInteger(maxTurns) || maxTurns < 1) {\n throw new Error(`AIAgent maxTurns must be a positive integer. Received: ${String(maxTurns)}`);\n }\n return {\n maxTurns,\n onTurnLimitReached: guardrails?.onTurnLimitReached ?? AgentGuardrailDefaults.onTurnLimitReached,\n modelInvocationOptions: guardrails?.modelInvocationOptions,\n };\n }\n}\n","import {\n RetryPolicy,\n type AgentGuardrailConfig,\n type AgentMessageConfig,\n type AgentNodeConfig,\n type ChatModelConfig,\n type RetryPolicySpec,\n type RunnableNodeConfig,\n type ToolConfig,\n type TypeToken,\n} from \"@codemation/core\";\n\nimport { AIAgentNode } from \"./AIAgentNode\";\n\nexport interface AIAgentOptions<TInputJson = unknown, _TOutputJson = unknown> {\n readonly name: string;\n readonly messages: AgentMessageConfig<TInputJson>;\n readonly chatModel: ChatModelConfig;\n readonly tools?: ReadonlyArray<ToolConfig>;\n readonly id?: string;\n readonly retryPolicy?: RetryPolicySpec;\n readonly guardrails?: AgentGuardrailConfig;\n}\n\n/**\n * AI agent: credential bindings are keyed to connection-owned LLM/tool node ids (ConnectionNodeIdFactory),\n * not to the agent workflow node id.\n */\nexport class AIAgent<TInputJson = unknown, TOutputJson = unknown>\n implements RunnableNodeConfig<TInputJson, TOutputJson>, AgentNodeConfig<TInputJson, TOutputJson>\n{\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = AIAgentNode;\n readonly execution = { hint: \"local\" } as const;\n readonly icon = \"lucide:bot\" as const;\n readonly name: string;\n readonly messages: AgentMessageConfig<TInputJson>;\n readonly chatModel: ChatModelConfig;\n readonly tools: ReadonlyArray<ToolConfig>;\n readonly id?: string;\n readonly retryPolicy: RetryPolicySpec;\n readonly guardrails?: AgentGuardrailConfig;\n\n constructor(options: AIAgentOptions<TInputJson, TOutputJson>) {\n this.name = options.name;\n this.messages = options.messages;\n this.chatModel = options.chatModel;\n this.tools = options.tools ?? [];\n this.id = options.id;\n this.retryPolicy = options.retryPolicy ?? RetryPolicy.defaultForAiAgent;\n this.guardrails = options.guardrails;\n }\n}\n","import type { Items, NodeOutputs } from \"@codemation/core\";\n\nexport class CallbackResultNormalizer {\n static toNodeOutputs(result: Items | void, items: Items): NodeOutputs {\n return { main: result ?? items };\n }\n}\n","import type { Items, Node, NodeExecutionContext, NodeOutputs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport { Callback } from \"./CallbackNodeFactory\";\nimport { CallbackResultNormalizer } from \"./CallbackResultNormalizerFactory\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class CallbackNode implements Node<Callback<any, any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n async execute(items: Items, ctx: NodeExecutionContext<Callback<any, any>>): Promise<NodeOutputs> {\n const result = await ctx.config.callback(items, ctx);\n return CallbackResultNormalizer.toNodeOutputs(result, items);\n }\n}\n","import type { Items, NodeExecutionContext, RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { CallbackNode } from \"./CallbackNode\";\n\nexport type CallbackHandler<\n TInputJson = unknown,\n TOutputJson = TInputJson,\n TConfig extends Callback<TInputJson, TOutputJson> = Callback<TInputJson, TOutputJson>,\n> = (\n items: Items<TInputJson>,\n ctx: NodeExecutionContext<TConfig>,\n) => Promise<Items<TOutputJson> | void> | Items<TOutputJson> | void;\n\nexport class Callback<TInputJson = unknown, TOutputJson = TInputJson> implements RunnableNodeConfig<\n TInputJson,\n TOutputJson\n> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = CallbackNode;\n readonly execution = { hint: \"local\" } as const;\n readonly icon = \"lucide:braces\" as const;\n\n constructor(\n public readonly name: string = \"Callback\",\n public readonly callback: CallbackHandler<TInputJson, TOutputJson> = Callback.defaultCallback as CallbackHandler<\n TInputJson,\n TOutputJson\n >,\n public readonly id?: string,\n ) {}\n\n private static defaultCallback<TItemJson>(items: Items<TItemJson>): Items<TItemJson> {\n return items;\n }\n}\n\nexport { CallbackNode } from \"./CallbackNode\";\nexport { CallbackResultNormalizer } from \"./CallbackResultNormalizerFactory\";\n","import type { Item, Items, Node, NodeExecutionContext, NodeOutputs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport type { HttpRequestDownloadMode } from \"./httpRequest\";\nimport { HttpRequest } from \"./httpRequest\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class HttpRequestNode implements Node<HttpRequest<any, any>> {\n readonly kind = \"node\" as const;\n readonly outputPorts = [\"main\"] as const;\n\n async execute(items: Items, ctx: NodeExecutionContext<HttpRequest<any, any>>): Promise<NodeOutputs> {\n const output: Item[] = [];\n for (const item of items) {\n output.push(await this.executeItem(item, ctx));\n }\n return { main: output };\n }\n\n private async executeItem(item: Item, ctx: NodeExecutionContext<HttpRequest<any, any>>): Promise<Item> {\n const url = this.resolveUrl(item, ctx);\n const response = await fetch(url, {\n method: ctx.config.method,\n });\n const headers = this.readHeaders(response.headers);\n const mimeType = this.resolveMimeType(headers);\n const bodyBinaryName = ctx.config.binaryName;\n const shouldAttachBody = this.shouldAttachBody(ctx.config.downloadMode, mimeType);\n const outputJson: Readonly<Record<string, unknown>> = {\n url,\n method: ctx.config.method,\n ok: response.ok,\n status: response.status,\n statusText: response.statusText,\n mimeType,\n headers,\n ...(shouldAttachBody ? { bodyBinaryName } : {}),\n };\n\n let outputItem: Item = {\n json: outputJson,\n };\n if (!shouldAttachBody) {\n return outputItem;\n }\n\n const attachment = await ctx.binary.attach({\n name: bodyBinaryName,\n body: response.body\n ? (response.body as unknown as Parameters<typeof ctx.binary.attach>[0][\"body\"])\n : new Uint8Array(await response.arrayBuffer()),\n mimeType,\n filename: this.resolveFilename(url, headers),\n });\n outputItem = ctx.binary.withAttachment(outputItem, bodyBinaryName, attachment);\n return outputItem;\n }\n\n private resolveUrl(item: Item, ctx: NodeExecutionContext<HttpRequest<any, any>>): string {\n const json = this.asRecord(item.json);\n const candidate = json[ctx.config.urlField];\n if (typeof candidate !== \"string\" || candidate.trim() === \"\") {\n throw new Error(`HttpRequest node expected item.json.${ctx.config.urlField} to contain a URL string.`);\n }\n return candidate;\n }\n\n private asRecord(value: unknown): Readonly<Record<string, unknown>> {\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n return value as Readonly<Record<string, unknown>>;\n }\n return { input: value };\n }\n\n private readHeaders(headers: Headers): Readonly<Record<string, string>> {\n const values: Record<string, string> = {};\n headers.forEach((value, key) => {\n values[key] = value;\n });\n return values;\n }\n\n private resolveMimeType(headers: Readonly<Record<string, string>>): string {\n const contentType = headers[\"content-type\"];\n if (!contentType) {\n return \"application/octet-stream\";\n }\n return contentType.split(\";\")[0]?.trim() || \"application/octet-stream\";\n }\n\n private shouldAttachBody(mode: HttpRequestDownloadMode, mimeType: string): boolean {\n if (mode === \"always\") {\n return true;\n }\n if (mode === \"never\") {\n return false;\n }\n return mimeType.startsWith(\"image/\") || mimeType.startsWith(\"audio/\") || mimeType.startsWith(\"video/\");\n }\n\n private resolveFilename(url: string, headers: Readonly<Record<string, string>>): string | undefined {\n const contentDisposition = headers[\"content-disposition\"];\n const fromDisposition = this.readFilenameFromContentDisposition(contentDisposition);\n if (fromDisposition) {\n return fromDisposition;\n }\n const pathname = new URL(url).pathname;\n const value = pathname.split(\"/\").at(-1);\n return value && value.trim() ? value : undefined;\n }\n\n private readFilenameFromContentDisposition(value: string | undefined): string | undefined {\n if (!value) {\n return undefined;\n }\n const parts = value.split(\";\");\n for (const part of parts) {\n const trimmed = part.trim();\n if (!trimmed.startsWith(\"filename=\")) {\n continue;\n }\n return trimmed.slice(\"filename=\".length).replace(/^\"|\"$/g, \"\");\n }\n return undefined;\n }\n}\n","import { RetryPolicy, type RetryPolicySpec, type RunnableNodeConfig, type TypeToken } from \"@codemation/core\";\n\nimport { HttpRequestNode } from \"./HttpRequestNodeFactory\";\n\nexport type HttpRequestDownloadMode = \"auto\" | \"always\" | \"never\";\n\n/** JSON emitted by {@link HttpRequest} — response metadata only (input item fields are not passed through). */\nexport type HttpRequestOutputJson = Readonly<{\n url: string;\n method: string;\n ok: boolean;\n status: number;\n statusText: string;\n mimeType: string;\n headers: Readonly<Record<string, string>>;\n bodyBinaryName?: string;\n}>;\n\nexport class HttpRequest<\n TInputJson = Readonly<{ url?: string }>,\n TOutputJson = HttpRequestOutputJson,\n> implements RunnableNodeConfig<TInputJson, TOutputJson> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = HttpRequestNode;\n readonly execution = { hint: \"local\" } as const;\n\n constructor(\n public readonly name: string,\n public readonly args: Readonly<{\n method?: string;\n urlField?: string;\n binaryName?: string;\n downloadMode?: HttpRequestDownloadMode;\n id?: string;\n }> = {},\n public readonly retryPolicy: RetryPolicySpec = RetryPolicy.defaultForHttp,\n ) {}\n\n get id(): string | undefined {\n return this.args.id;\n }\n\n get method(): string {\n return (this.args.method ?? \"GET\").toUpperCase();\n }\n\n get urlField(): string {\n return this.args.urlField ?? \"url\";\n }\n\n get binaryName(): string {\n return this.args.binaryName ?? \"body\";\n }\n\n get downloadMode(): HttpRequestDownloadMode {\n return this.args.downloadMode ?? \"auto\";\n }\n}\n\nexport { HttpRequestNode } from \"./HttpRequestNodeFactory\";\n","import type { Item, Items, Node, NodeExecutionContext, NodeOutputs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport { If } from \"./if\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class IfNode implements Node<If<any>> {\n kind = \"node\" as const;\n outputPorts = [\"true\", \"false\"] as const;\n\n async execute(items: Items, ctx: NodeExecutionContext<If<any>>): Promise<NodeOutputs> {\n const t: Item[] = [];\n const f: Item[] = [];\n for (let i = 0; i < items.length; i++) {\n const item = items[i] as Item<unknown>;\n const metaBase = (\n item.meta && typeof item.meta === \"object\" ? (item.meta as Record<string, unknown>) : {}\n ) as Record<string, unknown>;\n const cmBase =\n metaBase._cm && typeof metaBase._cm === \"object\"\n ? (metaBase._cm as Record<string, unknown>)\n : ({} as Record<string, unknown>);\n const originIndex = typeof cmBase.originIndex === \"number\" ? (cmBase.originIndex as number) : i;\n const tagged: Item = {\n ...item,\n meta: { ...metaBase, _cm: { ...cmBase, originIndex } },\n paired: [{ nodeId: ctx.nodeId, output: \"$in\", itemIndex: originIndex }, ...(item.paired ?? [])],\n };\n const ok = ctx.config.predicate(item, i, items, ctx);\n (ok ? t : f).push(tagged);\n }\n return { true: t, false: f };\n }\n}\n","import type { Item, Items, NodeExecutionContext, RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { IfNode } from \"./IfNode\";\n\nexport class If<TInputJson = unknown> implements RunnableNodeConfig<TInputJson, TInputJson> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = IfNode;\n readonly execution = { hint: \"local\" } as const;\n readonly icon = \"lucide:split\" as const;\n constructor(\n public readonly name: string,\n public readonly predicate: (\n item: Item<TInputJson>,\n index: number,\n items: Items<TInputJson>,\n ctx: NodeExecutionContext<If<TInputJson>>,\n ) => boolean,\n public readonly id?: string,\n ) {}\n}\n\nexport { IfNode } from \"./IfNode\";\n","import type {\n Items,\n NodeExecutionContext,\n NodeOutputs,\n TestableTriggerNode,\n TriggerSetupContext,\n TriggerTestItemsContext,\n} from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport { ManualTrigger } from \"./ManualTriggerFactory\";\n\n/**\n * Setup is intentionally a no-op: the engine host can run workflows manually\n * by calling `engine.runWorkflow(workflow, triggerNodeId, items)`.\n */\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class ManualTriggerNode implements TestableTriggerNode<ManualTrigger<any>> {\n kind = \"trigger\" as const;\n outputPorts = [\"main\"] as const;\n async setup(_ctx: TriggerSetupContext<ManualTrigger<any>>): Promise<undefined> {\n return undefined;\n }\n\n async getTestItems(ctx: TriggerTestItemsContext<ManualTrigger<any>>): Promise<Items> {\n return this.resolveManualItems([], ctx.config);\n }\n\n async execute(items: Items, ctx: NodeExecutionContext<ManualTrigger<any>>): Promise<NodeOutputs> {\n return { main: this.resolveManualItems(items, ctx.config) };\n }\n\n private resolveManualItems(items: Items, config: ManualTrigger<any>): Items {\n return items.length > 0 ? items : (config.defaultItems ?? []);\n }\n}\n","import type { Items, TriggerNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { ItemsInputNormalizer } from \"@codemation/core\";\n\nimport { ManualTriggerNode } from \"./ManualTriggerNode\";\n\ntype ManualTriggerDefaultValue<TOutputJson> = Items<TOutputJson> | ReadonlyArray<TOutputJson> | TOutputJson;\n\nexport class ManualTrigger<TOutputJson = unknown> implements TriggerNodeConfig<TOutputJson> {\n private static readonly itemsInputNormalizer = new ItemsInputNormalizer();\n readonly kind = \"trigger\" as const;\n readonly type: TypeToken<unknown> = ManualTriggerNode;\n readonly icon = \"lucide:play\" as const;\n readonly defaultItems?: Items<TOutputJson>;\n readonly id?: string;\n /** Manual runs often emit an empty batch; still schedule downstream by default. */\n readonly continueWhenEmptyOutput = true as const;\n\n constructor(name?: string, id?: string);\n constructor(name: string, defaultItems: ManualTriggerDefaultValue<TOutputJson>, id?: string);\n constructor(\n public readonly name: string = \"Manual trigger\",\n defaultItemsOrId?: ManualTriggerDefaultValue<TOutputJson> | string,\n id?: string,\n ) {\n this.defaultItems = ManualTrigger.resolveDefaultItems(defaultItemsOrId);\n this.id = ManualTrigger.resolveId(defaultItemsOrId, id);\n }\n\n private static resolveDefaultItems<TOutputJson>(\n value: ManualTriggerDefaultValue<TOutputJson> | string | undefined,\n ): Items<TOutputJson> | undefined {\n if (typeof value === \"string\" || value === undefined) {\n return undefined;\n }\n return this.itemsInputNormalizer.normalize(value) as Items<TOutputJson>;\n }\n\n private static resolveId<TOutputJson>(\n value: ManualTriggerDefaultValue<TOutputJson> | string | undefined,\n id: string | undefined,\n ): string | undefined {\n return typeof value === \"string\" ? value : id;\n }\n}\n\nexport { ManualTriggerNode } from \"./ManualTriggerNode\";\n","import type { Item, Items, Node, NodeExecutionContext, NodeOutputs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport { MapData } from \"./mapData\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class MapDataNode implements Node<MapData<any, any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n async execute(items: Items, ctx: NodeExecutionContext<MapData<any, any>>): Promise<NodeOutputs> {\n const out: Item[] = [];\n for (let i = 0; i < items.length; i++) {\n const item = items[i] as Item<unknown>;\n out.push({ ...item, json: ctx.config.map(item, ctx) });\n }\n return { main: out };\n }\n}\n","import type { Item, NodeExecutionContext, RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { MapDataNode } from \"./MapDataNode\";\n\nexport class MapData<TInputJson = unknown, TOutputJson = unknown> implements RunnableNodeConfig<\n TInputJson,\n TOutputJson\n> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = MapDataNode;\n readonly execution = { hint: \"local\" } as const;\n /** Zero mapped items should still allow downstream nodes to run. */\n readonly continueWhenEmptyOutput = true as const;\n constructor(\n public readonly name: string,\n public readonly map: (\n item: Item<TInputJson>,\n ctx: NodeExecutionContext<MapData<TInputJson, TOutputJson>>,\n ) => TOutputJson,\n public readonly id?: string,\n ) {}\n}\n\nexport { MapDataNode } from \"./MapDataNode\";\n","import type { InputPortKey, Item, Items } from \"@codemation/core\";\n\nexport function getOriginIndex(item: Item): number | undefined {\n const meta = item.meta as Record<string, unknown> | undefined;\n const cm = meta?._cm as Record<string, unknown> | undefined;\n const v = cm?.originIndex;\n return typeof v === \"number\" && Number.isFinite(v) ? v : undefined;\n}\n\nexport function orderedInputs(\n inputsByPort: Readonly<Record<InputPortKey, Items>>,\n prefer?: ReadonlyArray<InputPortKey>,\n): InputPortKey[] {\n const keys = Object.keys(inputsByPort);\n const preferred = (prefer ?? []).filter((k) => keys.includes(k));\n const rest = keys.filter((k) => !preferred.includes(k)).sort();\n return [...preferred, ...rest];\n}\n","import type { InputPortKey, Item, Items, MultiInputNode, NodeExecutionContext, NodeOutputs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport type { Merge } from \"./merge\";\nimport { getOriginIndex, orderedInputs } from \"./mergeExecutionUtils.types\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class MergeNode implements MultiInputNode<Merge<any, any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n async executeMulti(\n inputsByPort: Readonly<Record<InputPortKey, Items>>,\n ctx: NodeExecutionContext<Merge<any, any>>,\n ): Promise<NodeOutputs> {\n const order = orderedInputs(inputsByPort, ctx.config.cfg.prefer);\n\n if (ctx.config.cfg.mode === \"append\") {\n const out: Item[] = [];\n for (const k of order) out.push(...(inputsByPort[k] ?? []));\n return { main: out };\n }\n\n if (ctx.config.cfg.mode === \"mergeByPosition\") {\n let maxLen = 0;\n for (const k of order) maxLen = Math.max(maxLen, (inputsByPort[k] ?? []).length);\n\n const out: Item[] = [];\n for (let i = 0; i < maxLen; i++) {\n const json: Record<string, unknown> = {};\n const paired: any[] = [];\n let meta: Record<string, unknown> | undefined;\n\n for (const k of order) {\n const item = (inputsByPort[k] ?? [])[i];\n json[k] = item?.json;\n if (item?.paired) paired.push(...item.paired);\n if (!meta && item?.meta) meta = { ...(item.meta as any) };\n }\n\n const merged: any = { json };\n if (paired.length > 0) merged.paired = paired;\n if (meta) merged.meta = meta;\n out.push(merged as Item);\n }\n\n return { main: out };\n }\n\n // passThrough (default): for each origin index, take first available input (deterministic input precedence).\n const chosenByOrigin = new Map<number, Item>();\n const fallback: Item[] = [];\n\n for (const k of order) {\n for (const item of inputsByPort[k] ?? []) {\n const origin = getOriginIndex(item);\n if (origin === undefined) {\n fallback.push(item);\n continue;\n }\n if (!chosenByOrigin.has(origin)) chosenByOrigin.set(origin, item);\n }\n }\n\n const out: Item[] = [];\n const origins = Array.from(chosenByOrigin.keys()).sort((a, b) => a - b);\n for (const o of origins) out.push(chosenByOrigin.get(o)!);\n out.push(...fallback);\n\n return { main: out };\n }\n}\n","import type { InputPortKey, RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { MergeNode } from \"./MergeNode\";\n\nexport type MergeMode = \"passThrough\" | \"append\" | \"mergeByPosition\";\n\nexport class Merge<TInputJson = unknown, TOutputJson = TInputJson> implements RunnableNodeConfig<\n TInputJson,\n TOutputJson\n> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = MergeNode;\n readonly icon = \"lucide:git-merge\" as const;\n\n constructor(\n public readonly name: string,\n public readonly cfg: Readonly<{\n mode: MergeMode;\n /**\n * Deterministic input precedence order (only used for passThrough/append).\n * Any inputs not listed are appended in lexicographic order.\n */\n prefer?: ReadonlyArray<InputPortKey>;\n }> = { mode: \"passThrough\" },\n public readonly id?: string,\n ) {}\n}\n\nexport { MergeNode } from \"./MergeNode\";\n","import type { Items, Node, NodeExecutionContext, NodeOutputs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport { NoOp } from \"./noOp\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class NoOpNode implements Node<NoOp<any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n async execute(items: Items, _ctx: NodeExecutionContext<NoOp<any>>): Promise<NodeOutputs> {\n return { main: items };\n }\n}\n","import type { RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { NoOpNode } from \"./NoOpNode\";\n\nexport class NoOp<TItemJson = unknown> implements RunnableNodeConfig<TItemJson, TItemJson> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = NoOpNode;\n readonly execution = { hint: \"local\" } as const;\n\n constructor(\n public readonly name: string = \"NoOp\",\n public readonly id?: string,\n ) {}\n}\n\nexport { NoOpNode } from \"./NoOpNode\";\n","import type { Item, Items, Node, NodeExecutionContext, NodeOutputs, WorkflowRunnerService } from \"@codemation/core\";\n\nimport { CoreTokens, inject, node } from \"@codemation/core\";\n\nimport { SubWorkflow } from \"./subWorkflow\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class SubWorkflowNode implements Node<SubWorkflow<any, any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n constructor(\n @inject(CoreTokens.WorkflowRunnerService)\n private readonly workflows: WorkflowRunnerService,\n ) {}\n\n async execute(items: Items, ctx: NodeExecutionContext<SubWorkflow<any, any>>): Promise<NodeOutputs> {\n const out: Item[] = [];\n for (let i = 0; i < items.length; i++) {\n const current = items[i]!;\n const metaBase = (\n current.meta && typeof current.meta === \"object\" ? (current.meta as Record<string, unknown>) : {}\n ) as Record<string, unknown>;\n const cmBase =\n metaBase._cm && typeof metaBase._cm === \"object\"\n ? (metaBase._cm as Record<string, unknown>)\n : ({} as Record<string, unknown>);\n const originIndex = typeof cmBase.originIndex === \"number\" ? (cmBase.originIndex as number) : undefined;\n\n const result = await this.workflows.runById({\n workflowId: ctx.config.workflowId,\n startAt: ctx.config.startAt,\n items: [current],\n parent: {\n runId: ctx.runId,\n workflowId: ctx.workflowId,\n nodeId: ctx.nodeId,\n subworkflowDepth: ctx.subworkflowDepth,\n engineMaxNodeActivations: ctx.engineMaxNodeActivations,\n engineMaxSubworkflowDepth: ctx.engineMaxSubworkflowDepth,\n },\n });\n if (result.status !== \"completed\")\n throw new Error(`Subworkflow ${ctx.config.workflowId} did not complete (status=${result.status})`);\n for (const produced of result.outputs) {\n const childMetaBase =\n produced.meta && typeof produced.meta === \"object\"\n ? (produced.meta as Record<string, unknown>)\n : ({} as Record<string, unknown>);\n const childCmBase =\n childMetaBase._cm && typeof childMetaBase._cm === \"object\"\n ? (childMetaBase._cm as Record<string, unknown>)\n : ({} as Record<string, unknown>);\n\n out.push({\n ...produced,\n meta: originIndex === undefined ? childMetaBase : { ...childMetaBase, _cm: { ...childCmBase, originIndex } },\n paired: current.paired ?? produced.paired,\n });\n }\n }\n\n return { main: out };\n }\n}\n","import type { NodeId, RunnableNodeConfig, TypeToken, UpstreamRefPlaceholder } from \"@codemation/core\";\n\nimport { SubWorkflowNode } from \"./SubWorkflowNode\";\n\nexport class SubWorkflow<TInputJson = unknown, TOutputJson = unknown> implements RunnableNodeConfig<\n TInputJson,\n TOutputJson\n> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = SubWorkflowNode;\n constructor(\n public readonly name: string,\n public readonly workflowId: string,\n public upstreamRefs?: Array<{ nodeId: NodeId } | UpstreamRefPlaceholder>,\n public readonly startAt?: NodeId,\n public readonly id?: string,\n ) {}\n}\n\nexport { SubWorkflowNode } from \"./SubWorkflowNode\";\n","export class WaitDuration {\n static normalize(milliseconds: number): number {\n return Number.isFinite(milliseconds) && milliseconds > 0 ? Math.floor(milliseconds) : 0;\n }\n}\n","import type { Items, Node, NodeExecutionContext, NodeOutputs } from \"@codemation/core\";\n\nimport { node } from \"@codemation/core\";\n\nimport { Wait } from \"./wait\";\nimport { WaitDuration } from \"./WaitDurationFactory\";\n\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class WaitNode implements Node<Wait<any>> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n async execute(items: Items, ctx: NodeExecutionContext<Wait<any>>): Promise<NodeOutputs> {\n const milliseconds = WaitDuration.normalize(ctx.config.milliseconds);\n if (milliseconds > 0) {\n await new Promise<void>((resolve) => {\n setTimeout(resolve, milliseconds);\n });\n }\n return { main: items };\n }\n}\n","import type { RunnableNodeConfig, TypeToken } from \"@codemation/core\";\n\nimport { WaitNode } from \"./WaitNode\";\n\nexport class Wait<TItemJson = unknown> implements RunnableNodeConfig<TItemJson, TItemJson> {\n readonly kind = \"node\" as const;\n readonly type: TypeToken<unknown> = WaitNode;\n readonly execution = { hint: \"local\" } as const;\n /** Pass-through empty batches should still advance to downstream nodes. */\n readonly continueWhenEmptyOutput = true as const;\n\n constructor(\n public readonly name: string,\n public readonly milliseconds: number,\n public readonly id?: string,\n ) {}\n}\n\nexport { WaitDuration } from \"./WaitDurationFactory\";\nexport { WaitNode } from \"./WaitNode\";\n","import type { Items, WebhookControlSignal } from \"@codemation/core\";\n\nexport class WebhookRespondNowAndContinueError extends Error implements WebhookControlSignal {\n readonly __webhookControl = true as const;\n readonly kind = \"respondNowAndContinue\" as const;\n\n constructor(\n public readonly responseItems: Items,\n public readonly continueItems: Items,\n message: string = \"Webhook responded immediately and continued the run.\",\n ) {\n super(message);\n this.name = \"WebhookRespondNowAndContinueError\";\n }\n}\n","import type { Items, WebhookControlSignal } from \"@codemation/core\";\n\nexport class WebhookRespondNowError extends Error implements WebhookControlSignal {\n readonly __webhookControl = true as const;\n readonly kind = \"respondNow\" as const;\n\n constructor(\n public readonly responseItems: Items,\n message: string = \"Webhook responded immediately.\",\n ) {\n super(message);\n this.name = \"WebhookRespondNowError\";\n }\n}\n","import type {\n ExecutableTriggerNode,\n Items,\n NodeExecutionContext,\n NodeOutputs,\n TriggerSetupContext,\n} from \"@codemation/core\";\nimport { node } from \"@codemation/core\";\nimport { WebhookTrigger } from \"./WebhookTriggerFactory\";\n\n/**\n * HTTP webhooks are not registered in trigger setup. The host exposes a single catch-all route\n * (e.g. `/api/webhooks/:endpointPath`); the engine's catalog-backed webhook matcher resolves the\n * user-defined endpoint path to this workflow + node, then runs the workflow from this trigger.\n */\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class WebhookTriggerNode implements ExecutableTriggerNode<WebhookTrigger<any>> {\n readonly kind = \"trigger\" as const;\n readonly outputPorts = [\"main\"] as const;\n\n async setup(_ctx: TriggerSetupContext<WebhookTrigger<any>>): Promise<undefined> {\n return undefined;\n }\n\n async execute(items: Items, _ctx: NodeExecutionContext<WebhookTrigger<any>>): Promise<NodeOutputs> {\n if (items.length === 0) {\n throw new Error(\n `Webhook trigger \"${_ctx.config.name}\" requires a webhook request. Invoke this workflow through its webhook endpoint until manual request simulation is supported.`,\n );\n }\n const result = await _ctx.config.handler(items, _ctx);\n return { main: result ?? items };\n }\n}\n","import type { HttpMethod, Items, NodeExecutionContext, TriggerNodeConfig, TypeToken } from \"@codemation/core\";\nimport type { ZodType } from \"zod\";\nimport { WebhookTriggerNode } from \"./webhookTriggerNode\";\n\ntype WebhookInputSchema = ZodType<any, any, any>;\ntype WebhookTriggerHandler<TConfig extends WebhookTrigger<any> = WebhookTrigger<any>> = (\n items: Items,\n ctx: NodeExecutionContext<TConfig>,\n) => Promise<Items | void> | Items | void;\n\nexport class WebhookTrigger<\n TSchema extends WebhookInputSchema | undefined = undefined,\n> implements TriggerNodeConfig<unknown> {\n readonly kind = \"trigger\" as const;\n readonly type: TypeToken<unknown> = WebhookTriggerNode;\n readonly icon = \"lucide:globe\";\n\n constructor(\n public readonly name: string,\n private readonly args: Readonly<{\n endpointKey: string;\n methods: ReadonlyArray<HttpMethod>;\n inputSchema?: TSchema;\n }>,\n public readonly handler: WebhookTriggerHandler<\n WebhookTrigger<TSchema>\n > = WebhookTrigger.defaultHandler as WebhookTriggerHandler<WebhookTrigger<TSchema>>,\n public readonly id?: string,\n ) {}\n\n get endpointKey(): string {\n return this.args.endpointKey;\n }\n\n get methods(): ReadonlyArray<HttpMethod> {\n return this.args.methods;\n }\n\n get inputSchema(): TSchema | undefined {\n return this.args.inputSchema;\n }\n\n parseJsonBody(body: unknown): unknown {\n if (!this.args.inputSchema) return body;\n return this.args.inputSchema.parse(body);\n }\n\n private static defaultHandler(items: Items): Items {\n return items;\n }\n}\n","import type { Items, Node, NodeExecutionContext, NodeOutputs } from \"@codemation/core\";\nimport { node } from \"@codemation/core\";\n\nimport type { ConnectionCredentialNodeConfig } from \"./ConnectionCredentialNodeConfig\";\n\n/**\n * Placeholder runnable node for connection-owned workflow nodes (LLM/tool slots).\n * The engine does not schedule these; they exist for credentials, tokens, and UI identity.\n */\n@node({ packageName: \"@codemation/core-nodes\" })\nexport class ConnectionCredentialNode implements Node<ConnectionCredentialNodeConfig> {\n kind = \"node\" as const;\n outputPorts = [\"main\"] as const;\n\n async execute(_items: Items, _ctx: NodeExecutionContext<ConnectionCredentialNodeConfig>): Promise<NodeOutputs> {\n return { main: [] };\n }\n}\n","import type { Container } from \"@codemation/core\";\nimport { AIAgentExecutionHelpersFactory, AIAgentNode } from \"./nodes/aiAgent\";\nimport { CallbackNode } from \"./nodes/CallbackNodeFactory\";\nimport { HttpRequestNode } from \"./nodes/httpRequest\";\nimport { IfNode } from \"./nodes/if\";\nimport { ManualTriggerNode } from \"./nodes/ManualTriggerFactory\";\nimport { MapDataNode } from \"./nodes/mapData\";\nimport { NoOpNode } from \"./nodes/noOp\";\nimport { SubWorkflowNode } from \"./nodes/subWorkflow\";\nimport { WaitNode } from \"./nodes/wait\";\nimport { ConnectionCredentialNode } from \"./nodes/ConnectionCredentialNode\";\n\n/**\n * Registrar for built-in nodes. In a real project, this would use tsyringe's\n * container.registerSingleton(...). For the skeleton we keep it token-based:\n * the engine resolves node implementations by class token.\n */\nexport function registerCoreNodes(container: Container): void {\n // With class tokens, resolving registers happen via the DI container setup.\n // This function exists as the standardized extension point.\n void container;\n\n // Example: if using tsyringe, you'd do:\n // tsyringeContainer.registerSingleton(IfNode, IfNode);\n // ...\n void IfNode;\n void HttpRequestNode;\n void CallbackNode;\n void MapDataNode;\n void NoOpNode;\n void SubWorkflowNode;\n void ManualTriggerNode;\n void AIAgentNode;\n void AIAgentExecutionHelpersFactory;\n void WaitNode;\n void ConnectionCredentialNode;\n}\n","import type { WorkflowId } from \"@codemation/core\";\nimport { WorkflowBuilder } from \"@codemation/core\";\nimport { Merge } from \"./nodes/merge\";\n\nexport function createWorkflowBuilder(meta: Readonly<{ id: WorkflowId; name: string }>): WorkflowBuilder {\n return new WorkflowBuilder(meta, {\n makeMergeNode: (name) => new Merge(name, { mode: \"passThrough\", prefer: [\"true\", \"false\"] }),\n });\n}\n","import type { ChatModelConfig } from \"@codemation/core\";\nimport { OpenAIChatModelConfig } from \"../chatModels/openAiChatModelConfig\";\n\nexport class WorkflowChatModelFactory {\n static create(model: string | ChatModelConfig): ChatModelConfig {\n if (typeof model !== \"string\") {\n return model;\n }\n const [provider, resolvedModel] = model.includes(\":\") ? model.split(\":\", 2) : [\"openai\", model];\n if (provider !== \"openai\") {\n throw new Error(`Unsupported workflow().agent() model provider \"${provider}\".`);\n }\n return new OpenAIChatModelConfig(\"OpenAI\", resolvedModel);\n }\n}\n","import { z } from \"zod\";\nimport { AIAgent } from \"../nodes/AIAgentConfig\";\nimport type { WorkflowAgentOptions } from \"./WorkflowAuthoringOptions.types\";\nimport { WorkflowChatModelFactory } from \"./WorkflowChatModelFactory.types\";\n\nexport class WorkflowAgentNodeFactory {\n static create<TCurrentJson, TOutputSchema extends z.ZodTypeAny | undefined>(\n nameOrOptions: string | WorkflowAgentOptions<TCurrentJson, TOutputSchema>,\n optionsOrUndefined?: WorkflowAgentOptions<TCurrentJson, TOutputSchema>,\n ): AIAgent<TCurrentJson, TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>> {\n const options = typeof nameOrOptions === \"string\" ? optionsOrUndefined! : nameOrOptions;\n const name = typeof nameOrOptions === \"string\" ? nameOrOptions : \"AI agent\";\n const prompt = options.prompt;\n const messages = [\n {\n role: \"user\" as const,\n content:\n typeof prompt === \"function\" ? ({ item }: { item: { json: TCurrentJson } }) => prompt(item.json) : prompt,\n },\n ] as const;\n return new AIAgent<\n TCurrentJson,\n TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>\n >({\n name,\n messages,\n chatModel: WorkflowChatModelFactory.create(options.model),\n tools: options.tools,\n id: options.id,\n retryPolicy: options.retryPolicy,\n guardrails: options.guardrails,\n });\n }\n}\n","import { DefinedNodeRegistry, type DefinedNode } from \"@codemation/core\";\n\nexport class WorkflowDefinedNodeResolver {\n static resolve(\n definitionOrKey: DefinedNode<string, Record<string, unknown>, unknown, unknown> | string,\n ): DefinedNode<string, Record<string, unknown>, unknown, unknown> {\n if (typeof definitionOrKey !== \"string\") {\n return definitionOrKey;\n }\n const definition = DefinedNodeRegistry.resolve(definitionOrKey);\n if (!definition) {\n throw new Error(`No helper-defined node with key \"${definitionOrKey}\" is registered in this module graph.`);\n }\n return definition;\n }\n}\n","export class WorkflowDurationParser {\n static parse(duration: number | string): number {\n if (typeof duration === \"number\") {\n return Number.isFinite(duration) && duration > 0 ? Math.floor(duration) : 0;\n }\n const normalized = duration.trim().toLowerCase();\n const match = normalized.match(/^(\\d+)(ms|s|m|h)$/);\n if (!match) {\n throw new Error(\n `Unsupported wait duration \"${duration}\". Use a number of milliseconds or values like \"500ms\", \"2s\", \"5m\".`,\n );\n }\n const value = Number(match[1]);\n const unit = match[2];\n if (unit === \"ms\") {\n return value;\n }\n if (unit === \"s\") {\n return value * 1000;\n }\n if (unit === \"m\") {\n return value * 60_000;\n }\n return value * 3_600_000;\n }\n}\n","import type { AnyRunnableNodeConfig, DefinedNode, RunnableNodeConfig, RunnableNodeOutputJson } from \"@codemation/core\";\nimport { z } from \"zod\";\nimport { MapData } from \"../nodes/mapData\";\nimport { Wait } from \"../nodes/wait\";\nimport type { WorkflowAgentOptions } from \"./WorkflowAuthoringOptions.types\";\nimport { WorkflowAgentNodeFactory } from \"./WorkflowAgentNodeFactory.types\";\nimport { WorkflowDefinedNodeResolver } from \"./WorkflowDefinedNodeResolver.types\";\nimport { WorkflowDurationParser } from \"./WorkflowDurationParser.types\";\n\nexport class WorkflowBranchBuilder<TCurrentJson> {\n constructor(private readonly steps: ReadonlyArray<AnyRunnableNodeConfig> = []) {}\n\n then<TConfig extends RunnableNodeConfig<TCurrentJson, any>>(\n config: TConfig,\n ): WorkflowBranchBuilder<RunnableNodeOutputJson<TConfig>> {\n return new WorkflowBranchBuilder<RunnableNodeOutputJson<TConfig>>([...this.steps, config]);\n }\n\n map<TNextJson>(mapper: (item: TCurrentJson) => TNextJson): WorkflowBranchBuilder<TNextJson>;\n map<TNextJson>(\n name: string,\n mapper: (item: TCurrentJson) => TNextJson,\n id?: string,\n ): WorkflowBranchBuilder<TNextJson>;\n map<TNextJson>(\n nameOrMapper: string | ((item: TCurrentJson) => TNextJson),\n mapperOrUndefined?: (item: TCurrentJson) => TNextJson,\n id?: string,\n ): WorkflowBranchBuilder<TNextJson> {\n const name = typeof nameOrMapper === \"string\" ? nameOrMapper : \"Map data\";\n const mapper = typeof nameOrMapper === \"string\" ? mapperOrUndefined! : nameOrMapper;\n return this.then(\n new MapData<TCurrentJson, TNextJson>(name, (item) => mapper(item.json as TCurrentJson), id),\n ) as WorkflowBranchBuilder<TNextJson>;\n }\n\n wait(duration: number | string): WorkflowBranchBuilder<TCurrentJson>;\n wait(name: string, duration: number | string, id?: string): WorkflowBranchBuilder<TCurrentJson>;\n wait(\n nameOrDuration: string | number,\n durationOrUndefined?: string | number,\n id?: string,\n ): WorkflowBranchBuilder<TCurrentJson> {\n const name = typeof nameOrDuration === \"string\" && durationOrUndefined !== undefined ? nameOrDuration : \"Wait\";\n const duration = durationOrUndefined ?? nameOrDuration;\n return this.then(\n new Wait<TCurrentJson>(name, WorkflowDurationParser.parse(duration), id),\n ) as WorkflowBranchBuilder<TCurrentJson>;\n }\n\n agent<TOutputSchema extends z.ZodTypeAny>(\n options: WorkflowAgentOptions<TCurrentJson, TOutputSchema>,\n ): WorkflowBranchBuilder<z.output<TOutputSchema>>;\n agent(options: WorkflowAgentOptions<TCurrentJson, undefined>): WorkflowBranchBuilder<Record<string, unknown>>;\n agent<TOutputSchema extends z.ZodTypeAny>(\n name: string,\n options: WorkflowAgentOptions<TCurrentJson, TOutputSchema | undefined>,\n ): WorkflowBranchBuilder<TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>>;\n agent<TOutputSchema extends z.ZodTypeAny>(\n nameOrOptions: string | WorkflowAgentOptions<TCurrentJson, TOutputSchema | undefined>,\n optionsOrUndefined?: WorkflowAgentOptions<TCurrentJson, TOutputSchema | undefined>,\n ): WorkflowBranchBuilder<TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>> {\n return this.then(WorkflowAgentNodeFactory.create(nameOrOptions, optionsOrUndefined)) as WorkflowBranchBuilder<\n TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>\n >;\n }\n\n node<TConfig extends Record<string, unknown>, TOutputJson>(\n definitionOrKey: DefinedNode<string, TConfig, TCurrentJson, TOutputJson> | string,\n config: TConfig,\n name?: string,\n id?: string,\n ): WorkflowBranchBuilder<TOutputJson> {\n const definition = WorkflowDefinedNodeResolver.resolve(\n definitionOrKey as DefinedNode<string, Record<string, unknown>, unknown, unknown> | string,\n ) as DefinedNode<string, TConfig, TCurrentJson, TOutputJson>;\n return this.then(\n definition.create(config, name, id) as RunnableNodeConfig<TCurrentJson, TOutputJson>,\n ) as WorkflowBranchBuilder<TOutputJson>;\n }\n\n getSteps(): ReadonlyArray<AnyRunnableNodeConfig> {\n return this.steps;\n }\n}\n","import type { DefinedNode, RunnableNodeConfig, RunnableNodeOutputJson, WorkflowDefinition } from \"@codemation/core\";\nimport { ChainCursor } from \"@codemation/core\";\nimport { z } from \"zod\";\nimport { If } from \"../nodes/if\";\nimport { MapData } from \"../nodes/mapData\";\nimport { Wait } from \"../nodes/wait\";\nimport type { WorkflowAgentOptions } from \"./WorkflowAuthoringOptions.types\";\nimport { WorkflowAgentNodeFactory } from \"./WorkflowAgentNodeFactory.types\";\nimport { WorkflowBranchBuilder } from \"./WorkflowBranchBuilder.types\";\nimport { WorkflowDefinedNodeResolver } from \"./WorkflowDefinedNodeResolver.types\";\nimport { WorkflowDurationParser } from \"./WorkflowDurationParser.types\";\n\ntype BranchCallback<TCurrentJson, TNextJson> = (\n branch: WorkflowBranchBuilder<TCurrentJson>,\n) => WorkflowBranchBuilder<TNextJson>;\ntype BranchOutputMatch<TLeft, TRight> = [TLeft] extends [TRight] ? ([TRight] extends [TLeft] ? true : false) : false;\n\nexport class WorkflowChain<TCurrentJson> {\n constructor(private readonly chain: ChainCursor<TCurrentJson>) {}\n\n then<TConfig extends RunnableNodeConfig<TCurrentJson, any>>(\n config: TConfig,\n ): WorkflowChain<RunnableNodeOutputJson<TConfig>> {\n return new WorkflowChain(this.chain.then(config));\n }\n\n map<TNextJson>(mapper: (item: TCurrentJson) => TNextJson): WorkflowChain<TNextJson>;\n map<TNextJson>(name: string, mapper: (item: TCurrentJson) => TNextJson, id?: string): WorkflowChain<TNextJson>;\n map<TNextJson>(\n nameOrMapper: string | ((item: TCurrentJson) => TNextJson),\n mapperOrUndefined?: (item: TCurrentJson) => TNextJson,\n id?: string,\n ): WorkflowChain<TNextJson> {\n const name = typeof nameOrMapper === \"string\" ? nameOrMapper : \"Map data\";\n const mapper = typeof nameOrMapper === \"string\" ? mapperOrUndefined! : nameOrMapper;\n return this.then(\n new MapData<TCurrentJson, TNextJson>(name, (item) => mapper(item.json as TCurrentJson), id),\n ) as WorkflowChain<TNextJson>;\n }\n\n wait(duration: number | string): WorkflowChain<TCurrentJson>;\n wait(name: string, duration: number | string, id?: string): WorkflowChain<TCurrentJson>;\n wait(\n nameOrDuration: string | number,\n durationOrUndefined?: string | number,\n id?: string,\n ): WorkflowChain<TCurrentJson> {\n const name = typeof nameOrDuration === \"string\" && durationOrUndefined !== undefined ? nameOrDuration : \"Wait\";\n const duration = durationOrUndefined ?? nameOrDuration;\n return this.then(\n new Wait<TCurrentJson>(name, WorkflowDurationParser.parse(duration), id),\n ) as WorkflowChain<TCurrentJson>;\n }\n\n if<TBranchJson>(\n predicate: (item: TCurrentJson) => boolean,\n branches: Readonly<{\n true?: BranchCallback<TCurrentJson, TBranchJson>;\n false?: BranchCallback<TCurrentJson, TBranchJson>;\n }>,\n ): WorkflowChain<TBranchJson>;\n if<TBranchJson>(\n name: string,\n predicate: (item: TCurrentJson) => boolean,\n branches: Readonly<{\n true?: BranchCallback<TCurrentJson, TBranchJson>;\n false?: BranchCallback<TCurrentJson, TBranchJson>;\n }>,\n ): WorkflowChain<TBranchJson>;\n if<TTrueJson, TFalseJson>(\n nameOrPredicate: string | ((item: TCurrentJson) => boolean),\n predicateOrBranches:\n | ((item: TCurrentJson) => boolean)\n | Readonly<{ true?: BranchCallback<TCurrentJson, TTrueJson>; false?: BranchCallback<TCurrentJson, TFalseJson> }>,\n branchesOrUndefined?: Readonly<{\n true?: BranchCallback<TCurrentJson, TTrueJson>;\n false?: BranchCallback<TCurrentJson, TFalseJson>;\n }>,\n ): WorkflowChain<BranchOutputMatch<TTrueJson, TFalseJson> extends true ? TTrueJson : never> {\n const name = typeof nameOrPredicate === \"string\" ? nameOrPredicate : \"If\";\n const predicate =\n typeof nameOrPredicate === \"string\" ? (predicateOrBranches as (item: TCurrentJson) => boolean) : nameOrPredicate;\n const branches = (typeof nameOrPredicate === \"string\" ? branchesOrUndefined : predicateOrBranches) as Readonly<{\n true?: BranchCallback<TCurrentJson, TTrueJson>;\n false?: BranchCallback<TCurrentJson, TFalseJson>;\n }>;\n const cursor = this.chain.then(new If<TCurrentJson>(name, (item) => predicate(item.json as TCurrentJson)));\n const trueSteps = branches.true?.(new WorkflowBranchBuilder<TCurrentJson>()).getSteps();\n const falseSteps = branches.false?.(new WorkflowBranchBuilder<TCurrentJson>()).getSteps();\n return new WorkflowChain(\n cursor.when({\n true: trueSteps,\n false: falseSteps,\n }),\n ) as WorkflowChain<BranchOutputMatch<TTrueJson, TFalseJson> extends true ? TTrueJson : never>;\n }\n\n agent<TOutputSchema extends z.ZodTypeAny>(\n options: WorkflowAgentOptions<TCurrentJson, TOutputSchema>,\n ): WorkflowChain<z.output<TOutputSchema>>;\n agent(options: WorkflowAgentOptions<TCurrentJson, undefined>): WorkflowChain<Record<string, unknown>>;\n agent<TOutputSchema extends z.ZodTypeAny>(\n name: string,\n options: WorkflowAgentOptions<TCurrentJson, TOutputSchema | undefined>,\n ): WorkflowChain<TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>>;\n agent<TOutputSchema extends z.ZodTypeAny>(\n nameOrOptions: string | WorkflowAgentOptions<TCurrentJson, TOutputSchema | undefined>,\n optionsOrUndefined?: WorkflowAgentOptions<TCurrentJson, TOutputSchema | undefined>,\n ): WorkflowChain<TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>> {\n return this.then(WorkflowAgentNodeFactory.create(nameOrOptions, optionsOrUndefined)) as WorkflowChain<\n TOutputSchema extends z.ZodTypeAny ? z.output<TOutputSchema> : Record<string, unknown>\n >;\n }\n\n node<TConfig extends Record<string, unknown>, TOutputJson>(\n definitionOrKey: DefinedNode<string, TConfig, TCurrentJson, TOutputJson> | string,\n config: TConfig,\n name?: string,\n id?: string,\n ): WorkflowChain<TOutputJson> {\n const definition = WorkflowDefinedNodeResolver.resolve(\n definitionOrKey as DefinedNode<string, Record<string, unknown>, unknown, unknown> | string,\n ) as DefinedNode<string, TConfig, TCurrentJson, TOutputJson>;\n return this.then(\n definition.create(config, name, id) as RunnableNodeConfig<TCurrentJson, TOutputJson>,\n ) as WorkflowChain<TOutputJson>;\n }\n\n build(): WorkflowDefinition {\n return this.chain.build();\n }\n}\n","import { ChainCursor } from \"@codemation/core\";\nimport { ManualTrigger } from \"../nodes/ManualTriggerFactory\";\nimport { createWorkflowBuilder } from \"../workflowBuilder.types\";\nimport { WorkflowChain } from \"./WorkflowChain.types\";\n\nexport class WorkflowAuthoringBuilder {\n constructor(\n private readonly id: string,\n private readonly workflowName: string = id,\n ) {}\n\n name(name: string): WorkflowAuthoringBuilder {\n return new WorkflowAuthoringBuilder(this.id, name);\n }\n\n manualTrigger<TOutputJson>(defaultItems: TOutputJson | ReadonlyArray<TOutputJson>): WorkflowChain<TOutputJson>;\n manualTrigger<TOutputJson>(\n name: string,\n defaultItems?: TOutputJson | ReadonlyArray<TOutputJson>,\n id?: string,\n ): WorkflowChain<TOutputJson>;\n manualTrigger<TOutputJson>(\n nameOrDefaultItems: string | TOutputJson | ReadonlyArray<TOutputJson>,\n defaultItemsOrUndefined?: TOutputJson | ReadonlyArray<TOutputJson>,\n id?: string,\n ): WorkflowChain<TOutputJson> {\n const builder = createWorkflowBuilder({ id: this.id, name: this.workflowName });\n if (typeof nameOrDefaultItems === \"string\") {\n return new WorkflowChain(\n builder.trigger(\n new ManualTrigger<TOutputJson>(\n nameOrDefaultItems,\n defaultItemsOrUndefined as TOutputJson | ReadonlyArray<TOutputJson>,\n id,\n ),\n ) as ChainCursor<TOutputJson>,\n );\n }\n return new WorkflowChain(\n builder.trigger(new ManualTrigger<TOutputJson>(\"Manual trigger\", nameOrDefaultItems)) as ChainCursor<TOutputJson>,\n );\n }\n}\n","export type { WorkflowAgentOptions } from \"./workflowAuthoring/WorkflowAuthoringOptions.types\";\nexport { WorkflowAuthoringBuilder } from \"./workflowAuthoring/WorkflowAuthoringBuilder.types\";\nexport { WorkflowBranchBuilder } from \"./workflowAuthoring/WorkflowBranchBuilder.types\";\nexport { WorkflowChain } from \"./workflowAuthoring/WorkflowChain.types\";\n\nimport { WorkflowAuthoringBuilder } from \"./workflowAuthoring/WorkflowAuthoringBuilder.types\";\n\nexport function workflow(id: string): WorkflowAuthoringBuilder {\n return new WorkflowAuthoringBuilder(id);\n}\n","import type { NodeDefinition, WorkflowDefinition, WorkflowNodeConnection } from \"@codemation/core\";\nimport { AgentConfigInspector, AgentConnectionNodeCollector } from \"@codemation/core\";\n\nimport { AIAgentNode } from \"../nodes/AIAgentNode\";\nimport { ConnectionCredentialNode } from \"../nodes/ConnectionCredentialNode\";\nimport { ConnectionCredentialNodeConfigFactory } from \"../nodes/ConnectionCredentialNodeConfigFactory\";\n\n/**\n * Materializes connection-owned child nodes and {@link WorkflowDefinition.connections} for AI agent nodes.\n */\nexport class AIAgentConnectionWorkflowExpander {\n constructor(private readonly connectionCredentialNodeConfigFactory: ConnectionCredentialNodeConfigFactory) {}\n\n expand(workflow: WorkflowDefinition): WorkflowDefinition {\n const existingChildIds = this.collectExistingChildIds(workflow);\n const connectionsByParentAndName = this.createConnectionsByParentAndName(workflow);\n const extraNodes: NodeDefinition[] = [];\n let connectionsChanged = false;\n\n for (const node of workflow.nodes) {\n if (node.type !== AIAgentNode || !AgentConfigInspector.isAgentNodeConfig(node.config)) {\n continue;\n }\n for (const connectionNode of AgentConnectionNodeCollector.collect(node.id, node.config)) {\n if (!existingChildIds.has(connectionNode.nodeId)) {\n this.assertNoIdCollision(workflow, extraNodes, existingChildIds, connectionNode.nodeId);\n extraNodes.push({\n id: connectionNode.nodeId,\n kind: \"node\",\n type: ConnectionCredentialNode,\n name: connectionNode.name,\n config: this.connectionCredentialNodeConfigFactory.create(\n connectionNode.typeName,\n connectionNode.credentialSource,\n ),\n });\n }\n const connectionKey = this.connectionKey(connectionNode.parentNodeId, connectionNode.connectionName);\n const existingConnection = connectionsByParentAndName.get(connectionKey);\n if (!existingConnection) {\n connectionsByParentAndName.set(connectionKey, {\n parentNodeId: connectionNode.parentNodeId,\n connectionName: connectionNode.connectionName,\n childNodeIds: [connectionNode.nodeId],\n });\n connectionsChanged = true;\n continue;\n }\n if (!existingConnection.childNodeIds.includes(connectionNode.nodeId)) {\n connectionsByParentAndName.set(connectionKey, {\n ...existingConnection,\n childNodeIds: [...existingConnection.childNodeIds, connectionNode.nodeId],\n });\n connectionsChanged = true;\n }\n }\n }\n\n if (extraNodes.length === 0 && !connectionsChanged) {\n return workflow;\n }\n\n return {\n ...workflow,\n nodes: [...workflow.nodes, ...extraNodes],\n connections: [...connectionsByParentAndName.values()],\n };\n }\n\n private createConnectionsByParentAndName(workflow: WorkflowDefinition): Map<string, WorkflowNodeConnection> {\n const existingByParentAndName = new Map<string, WorkflowNodeConnection>();\n for (const connection of workflow.connections ?? []) {\n existingByParentAndName.set(this.connectionKey(connection.parentNodeId, connection.connectionName), connection);\n }\n return existingByParentAndName;\n }\n\n private collectExistingChildIds(workflow: WorkflowDefinition): ReadonlySet<string> {\n const ids = new Set<string>();\n for (const connection of workflow.connections ?? []) {\n for (const childId of connection.childNodeIds) {\n ids.add(childId);\n }\n }\n return ids;\n }\n\n private connectionKey(parentNodeId: string, connectionName: string): string {\n return `${parentNodeId}\\0${connectionName}`;\n }\n\n private assertNoIdCollision(\n workflow: WorkflowDefinition,\n pending: ReadonlyArray<NodeDefinition>,\n existingChildIds: ReadonlySet<string>,\n id: string,\n ): void {\n if (pending.some((n) => n.id === id)) {\n throw new Error(\n `AIAgent connection expansion: node id \"${id}\" already exists. Rename the conflicting node or adjust the workflow.`,\n );\n }\n if (workflow.nodes.some((n) => n.id === id) && !existingChildIds.has(id)) {\n throw new Error(\n `AIAgent connection expansion: node id \"${id}\" already exists. Rename the conflicting node or adjust the workflow.`,\n );\n }\n }\n}\n","import type { CredentialRequirement, RunnableNodeConfig } from \"@codemation/core\";\n\nimport { ConnectionCredentialNode } from \"./ConnectionCredentialNode\";\n\nexport class ConnectionCredentialNodeConfig implements RunnableNodeConfig {\n readonly kind = \"node\" as const;\n readonly type = ConnectionCredentialNode;\n\n constructor(\n public readonly name: string,\n private readonly credentialSource: { getCredentialRequirements?: () => ReadonlyArray<CredentialRequirement> },\n ) {}\n\n getCredentialRequirements(): ReadonlyArray<CredentialRequirement> {\n return this.credentialSource.getCredentialRequirements?.() ?? [];\n }\n}\n","import type { CredentialRequirement } from \"@codemation/core\";\n\nimport { ConnectionCredentialNodeConfig } from \"./ConnectionCredentialNodeConfig\";\n\nexport class ConnectionCredentialNodeConfigFactory {\n create(\n name: string,\n credentialSource: { getCredentialRequirements?: () => ReadonlyArray<CredentialRequirement> },\n ): ConnectionCredentialNodeConfig {\n return new ConnectionCredentialNodeConfig(name, credentialSource);\n }\n}\n"],"x_google_ignoreList":[6,7,8,9],"mappings":";;;;;;;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