@limo-labs/deity 0.2.0 → 0.2.2
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.cjs +35 -10
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +16 -10
- package/dist/index.d.ts +16 -10
- package/dist/index.js +35 -11
- package/dist/index.js.map +1 -1
- package/dist/{jsx-dev-runtime-Dg782FK5.d.cts → jsx-dev-runtime-1R5Vpr7w.d.cts} +6 -8
- package/dist/{jsx-dev-runtime-Dg782FK5.d.ts → jsx-dev-runtime-1R5Vpr7w.d.ts} +6 -8
- package/dist/jsx-dev-runtime.d.cts +1 -1
- package/dist/jsx-dev-runtime.d.ts +1 -1
- package/dist/jsx-runtime.d.cts +1 -1
- package/dist/jsx-runtime.d.ts +1 -1
- package/package.json +1 -1
- package/README.md +0 -681
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/compiler/compile-observe.ts","../src/components/Agent.tsx","../src/components/Prompt.tsx","../src/components/System.tsx","../src/components/User.tsx","../src/components/Observe.tsx","../src/components/Result.tsx","../src/components/Validate.tsx","../src/components/Retry.tsx","../src/components/Tools.tsx","../src/components/ToolRef.tsx","../src/components/Sequence.tsx","../src/components/Parallel.tsx","../src/components/Conditional.tsx","../src/components/Loop.tsx","../src/components/ForEach.tsx","../src/components/Workflow.tsx","../src/utilities/resource-loader.ts","../src/compiler/compile-prompt.ts","../src/compiler/compile-agent.ts","../src/compiler/compile-result.ts","../src/compiler/compile-validate.ts","../src/compiler/compile-retry.ts","../src/compiler/index.ts","../src/compiler/compile-workflow-node.ts","../src/compiler/compile-workflow.ts","../src/ast/types.ts","../src/utilities/observe-utils.ts","../src/utilities/result-utils.ts","../src/utilities/validate-utils.ts","../src/utilities/retry-utils.ts","../src/utilities/jsx-helpers.ts","../src/utilities/preflight.ts","../src/testing/test-utils.ts","../src/dev/debug.ts","../src/engine/llm-loop.ts","../src/engine/retry.ts","../src/engine/parser.ts","../src/engine/executor.ts","../src/context/context.ts","../src/conversation/types.ts","../src/conversation/utils.ts","../src/conversation/manager.ts","../src/memory/types.ts","../src/memory/manager.ts","../src/session/types.ts","../src/session/serializer.ts","../src/session/store.ts","../src/engine/stores.ts","../src/engine/stats.ts","../src/context/factory.ts","../src/engine/workflow.ts"],"names":["path","z","compileObserve","fs"],"mappings":";;;;;;;;;;;;;;;;;AAAA,IAAA,uBAAA,GAAA,EAAA;AAAA,QAAA,CAAA,uBAAA,EAAA;AAAA,EAAA,cAAA,EAAA,MAAA;AAAA,CAAA,CAAA;AAwBO,SAAS,eACd,WAAA,EACiB;AACjB,EAAA,IAAI,CAAC,WAAA,IAAe,WAAA,CAAY,IAAA,KAAS,SAAA,EAAW;AAClD,IAAA,MAAM,IAAI,MAAM,uBAAuB,CAAA;AAAA,EACzC;AAEA,EAAA,MAAM,EAAE,OAAA,EAAQ,GAAI,WAAA,CAAY,KAAA;AAEhC,EAAA,IAAI,CAAC,OAAA,EAAS;AACZ,IAAA,MAAM,IAAI,MAAM,yCAAyC,CAAA;AAAA,EAC3D;AAEA,EAAA,OAAO,OAAO,SAAA,KAA+D;AAC3E,IAAA,MAAM,WAAW,MAAM,OAAA,CAAQ,OAAA,CAAQ,OAAA,CAAQ,SAAS,CAAC,CAAA;AAGzD,IAAA,IAAI,OAAO,aAAa,QAAA,IAAY,QAAA,KAAa,QAAQ,KAAA,CAAM,OAAA,CAAQ,QAAQ,CAAA,EAAG;AAChF,MAAA,MAAM,IAAI,MAAM,4CAA4C,CAAA;AAAA,IAC9D;AAEA,IAAA,OAAO,QAAA;AAAA,EACT,CAAA;AACF;AA/CA,IAAA,oBAAA,GAAA,KAAA,CAAA;AAAA,EAAA,iCAAA,GAAA;AAAA,EAAA;AAAA,CAAA,CAAA;;;ACmFO,SAAS,MACd,KAAA,EACiB;AACjB,EAAA,MAAM,EAAE,EAAA,EAAI,KAAA,EAAO,MAAA,EAAQ,WAAA,EAAa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Aa;AAAA,GAC1C;AACF;AASO,SAAS,eAAe,SAAA,EAA0C;AACvE,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,MAAA;AAAA,IACN;AAAA,GACF;AACF;AAKO,SAAS,mBAAmB,QAAA,EAA0C;AAC3E,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,UAAA;AAAA,IACN;AAAA,GACF;AACF;AAKO,SAAS,mBAAmB,QAAA,EAA0C;AAC3E,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,UAAA;AAAA,IACN;AAAA,GACF;AACF;AAKO,SAAS,qBAAA,CACd,SAAA,EACA,UAAA,EACA,WAAA,EACe;AACf,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,aAAA;AAAA,IACN,SAAA;AAAA,IACA,UAAU,WAAA,GAAc,CAAC,YAAY,WAAW,CAAA,GAAI,CAAC,UAAU;AAAA,GACjE;AACF;AAKO,SAAS,cAAA,CACd,OACA,aAAA,EACe;AACf,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,MAAA;AAAA,IACN,QAAA,EAAU,CAAC,KAAK,CAAA;AAAA,IAChB;AAAA,GACF;AACF","file":"index.js","sourcesContent":["/**\r\n * Deity TSX - Observe Compiler\r\n *\r\n * Compiles Observe AST nodes into observation function.\r\n */\r\n\r\nimport type { ObserveNode } from '../ast/types.js';\r\nimport type { LLMLoopResult } from '../engine/types.js';\r\n\r\n/**\r\n * Compiled Observe Function\r\n *\r\n * Extracts observations from LLM loop result.\r\n */\r\nexport type ObserveFunction = (\r\n llmResult: LLMLoopResult\r\n) => Promise<Record<string, unknown>>;\r\n\r\n/**\r\n * Compile Observe node to observation function\r\n *\r\n * @param observeNode - Observe AST node\r\n * @returns Observation function\r\n */\r\nexport function compileObserve(\r\n observeNode: ObserveNode\r\n): ObserveFunction {\r\n if (!observeNode || observeNode.type !== 'Observe') {\r\n throw new Error('Expected Observe node');\r\n }\r\n\r\n const { compute } = observeNode.props;\r\n\r\n if (!compute) {\r\n throw new Error('Observe node must have compute function');\r\n }\r\n\r\n return async (llmResult: LLMLoopResult): Promise<Record<string, unknown>> => {\r\n const observed = await Promise.resolve(compute(llmResult));\r\n\r\n // Validate observed data is a plain object\r\n if (typeof observed !== 'object' || observed === null || Array.isArray(observed)) {\r\n throw new Error('Observe compute must return a plain object');\r\n }\r\n\r\n return observed;\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Agent Component\r\n *\r\n * Root component for defining an AI agent.\r\n */\r\n\r\nimport type { ZodSchema } from 'zod';\r\nimport type { AgentNode, PromptNode, ObserveNode, ResultNode, ValidateNode, RetryNode, ToolsNode, ToolDefNode } from '../ast/types.js';\r\nimport type { Validator, ToolSpec } from '../engine/types.js';\r\n\r\n/**\r\n * LLM Loop Configuration\r\n */\r\nexport interface LLMLoopConfig {\r\n /** Maximum number of tool execution rounds */\r\n maxToolRounds?: number;\r\n /** Timeout in milliseconds */\r\n timeout?: number;\r\n}\r\n\r\n/**\r\n * Agent Component Props\r\n */\r\nexport interface AgentProps<I = unknown, O = unknown> {\r\n /** Unique agent identifier */\r\n id: string;\r\n\r\n /** Input schema (Zod) */\r\n input: ZodSchema<I>;\r\n\r\n /** Output schema (Zod) */\r\n output: ZodSchema<O>;\r\n\r\n /** Optional description */\r\n description?: string;\r\n\r\n /** Optional tags for categorization */\r\n tags?: string[];\r\n\r\n /** Optional loop-level validator (validates during LLM loop) */\r\n loopValidator?: Validator;\r\n\r\n /** Optional LLM loop configuration */\r\n loopConfig?: LLMLoopConfig;\r\n\r\n /** Optional tool definitions (backward compatible - can also use <Tools> child) */\r\n tools?: ToolSpec[];\r\n\r\n /** Child components (Tools, Prompt, Observe, Result, Validate, Retry) */\r\n children?: any[]; // Accept any JSX children, validate at runtime\r\n}\r\n\r\n/**\r\n * Agent Component\r\n *\r\n * Defines a complete AI agent with:\r\n * - Identity (id, description, tags)\r\n * - IO schemas (input/output)\r\n * - Behavior specification (Prompt, Observe, Result, Validate, Retry)\r\n * - Tool definitions (via props.tools or <Tools> child)\r\n *\r\n * @example\r\n * ```tsx\r\n * export const MyAgent = (\r\n * <Agent id=\"my-agent\" input={InputSchema} output={OutputSchema}>\r\n * <Tools>\r\n * <MemoryStore />\r\n * <MemoryRecall />\r\n * <Tool name=\"my_tool\" description=\"...\" input={Schema}>\r\n * {async (params) => ({ ... })}\r\n * </Tool>\r\n * </Tools>\r\n * <Prompt>\r\n * <System source=\"file:./prompt.md\" />\r\n * <User>{(ctx) => `Task: ${ctx.inputs.task}`}</User>\r\n * </Prompt>\r\n * <Result>\r\n * {(ctx, llmResult) => extractOutput(llmResult)}\r\n * </Result>\r\n * </Agent>\r\n * );\r\n * ```\r\n */\r\nexport function Agent<I = unknown, O = unknown>(\r\n props: AgentProps<I, O>\r\n): AgentNode<I, O> {\r\n const { id, input, output, description, tags, loopValidator, loopConfig, tools: propsTools, children } = props;\r\n\r\n // Validate required props\r\n if (!id) {\r\n throw new Error('Agent: id is required');\r\n }\r\n if (!input) {\r\n throw new Error('Agent: input schema is required');\r\n }\r\n if (!output) {\r\n throw new Error('Agent: output schema is required');\r\n }\r\n\r\n // Validate children structure\r\n if (!children || children.length === 0) {\r\n throw new Error('Agent: must have at least Prompt and Result children');\r\n }\r\n\r\n // Find and extract <Tools> node from children (if present)\r\n const toolsNode = children.find((child: any): child is ToolsNode => child?.type === 'Tools');\r\n\r\n // Non-Tools children for standard processing\r\n const nonToolsChildren = children.filter((child: any) => child?.type !== 'Tools');\r\n\r\n // Extract required and optional children from non-Tools children\r\n const [prompt, ...rest] = nonToolsChildren;\r\n\r\n if (!prompt || prompt.type !== 'Prompt') {\r\n throw new Error('Agent: first non-Tools child must be a Prompt component');\r\n }\r\n\r\n // Find Result node (required)\r\n const result = rest.find((child: any): child is ResultNode => child?.type === 'Result');\r\n if (!result) {\r\n throw new Error('Agent: must have a Result component');\r\n }\r\n\r\n // Find optional nodes\r\n const observe = rest.find((child: any): child is ObserveNode => child?.type === 'Observe');\r\n const validate = rest.find((child: any): child is ValidateNode => child?.type === 'Validate');\r\n const retry = rest.find((child: any): child is RetryNode => child?.type === 'Retry');\r\n\r\n // ========================================\r\n // Merge tools from props.tools and <Tools> child\r\n // ========================================\r\n const mergedTools = mergeTools(propsTools, toolsNode);\r\n\r\n // Build children array in canonical order\r\n const orderedChildren: (PromptNode | ObserveNode | ResultNode | ValidateNode | RetryNode | ToolsNode)[] = [\r\n prompt,\r\n ];\r\n\r\n if (observe) orderedChildren.push(observe);\r\n orderedChildren.push(result);\r\n if (validate) orderedChildren.push(validate);\r\n if (retry) orderedChildren.push(retry);\r\n // Preserve ToolsNode in children for AST introspection\r\n if (toolsNode) orderedChildren.push(toolsNode);\r\n\r\n return {\r\n type: 'Agent',\r\n props: {\r\n id,\r\n input,\r\n output,\r\n description,\r\n tags,\r\n loopValidator,\r\n loopConfig,\r\n tools: mergedTools,\r\n },\r\n children: orderedChildren,\r\n };\r\n}\r\n\r\n/**\r\n * Merge tools from props.tools and <Tools> child node.\r\n *\r\n * Both sources provide static ToolSpec arrays. The result is a\r\n * simple concatenation of all tools from both sources.\r\n */\r\nfunction mergeTools(\r\n propsTools: ToolSpec[] | undefined,\r\n toolsNode: ToolsNode | undefined\r\n): ToolSpec[] | undefined {\r\n // No tools from either source\r\n if (!propsTools && !toolsNode) {\r\n return undefined;\r\n }\r\n\r\n // Extract static tools from <ToolDef> / <Tool> children\r\n const staticToolsFromNode: ToolSpec[] = toolsNode\r\n ? (toolsNode.children || [])\r\n .filter((child: ToolDefNode) => child?.type === 'Tools:Def' && child.props?.tool)\r\n .map((child: ToolDefNode) => child.props.tool)\r\n : [];\r\n\r\n // Only props.tools, no <Tools> child\r\n if (!toolsNode) {\r\n return propsTools;\r\n }\r\n\r\n // Only <Tools> child, no props.tools\r\n if (!propsTools) {\r\n return staticToolsFromNode.length > 0 ? staticToolsFromNode : undefined;\r\n }\r\n\r\n // Both — concatenate\r\n return [...propsTools, ...staticToolsFromNode];\r\n}\r\n","/**\r\n * Deity TSX - Prompt Component\r\n *\r\n * Container for system and user prompts.\r\n */\r\n\r\nimport type { PromptNode, SystemNode, UserNode } from '../ast/types.js';\r\n\r\n/**\r\n * Prompt Component Props\r\n */\r\nexport interface PromptProps {\r\n /** Child components (System and User nodes) */\r\n children?: any[]; // Accept any JSX children, validate at runtime\r\n}\r\n\r\n/**\r\n * Prompt Component\r\n *\r\n * Container for system and user prompts.\r\n * Must contain at least one System or User node.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Prompt>\r\n * <System source=\"file:./system.md\" />\r\n * <User>{(ctx) => `Task: ${ctx.inputs.task}`}</User>\r\n * </Prompt>\r\n * ```\r\n */\r\nexport function Prompt(props: PromptProps): PromptNode {\r\n const children: (SystemNode | UserNode)[] = props.children ?? [];\r\n\r\n // Validate children\r\n if (children.length === 0) {\r\n throw new Error('Prompt: must have at least one System or User child');\r\n }\r\n\r\n // Validate child types\r\n for (const child of children) {\r\n if (!child || typeof child !== 'object' || !('type' in child)) {\r\n throw new Error('Prompt: invalid child node structure');\r\n }\r\n const childType = (child as SystemNode | UserNode).type;\r\n if (childType !== 'System' && childType !== 'User') {\r\n throw new Error(`Prompt: invalid child type \"${childType}\", expected System or User`);\r\n }\r\n }\r\n\r\n return {\r\n type: 'Prompt',\r\n children,\r\n };\r\n}\r\n","/**\r\n * Deity TSX - System Prompt Component\r\n *\r\n * System prompt node with support for file loading, inline content, or computed content.\r\n */\r\n\r\nimport type { SystemNode, TemplatePart } from '../ast/types.js';\r\nimport type { ExecutionContext } from '../engine/types.js';\r\n\r\n/**\r\n * System Component Props\r\n */\r\nexport interface SystemProps {\r\n /**\r\n * File source (e.g., 'file:./prompts/system.md')\r\n *\r\n * File paths are resolved relative to the agent definition file.\r\n */\r\n source?: string;\r\n\r\n /**\r\n * Is this prompt required? (fail-fast if missing)\r\n *\r\n * Default: false\r\n */\r\n required?: boolean;\r\n\r\n /**\r\n * Inline content (alternative to source)\r\n */\r\n content?: string;\r\n\r\n /**\r\n * Computed content (function)\r\n *\r\n * Alternative to source and content.\r\n * Receives ExecutionContext and returns prompt string.\r\n */\r\n compute?: (ctx: ExecutionContext) => string | Promise<string>;\r\n\r\n /**\r\n * Children (text or computed function)\r\n */\r\n children?: any; // Accept any JSX children, validate at runtime\r\n}\r\n\r\n/**\r\n * System Component\r\n *\r\n * Defines a system prompt with multiple loading strategies:\r\n * - File: `<System source=\"file:./prompt.md\" />`\r\n * - Inline: `<System content=\"You are a helpful assistant\" />`\r\n * - Computed: `<System compute={(ctx) => generatePrompt(ctx)} />`\r\n * - Children: `<System>{(ctx) => `Task: ${ctx.inputs.task}`}</System>`\r\n *\r\n * @example\r\n * ```tsx\r\n * // Load from file\r\n * <System source=\"file:./prompts/system.md\" required />\r\n *\r\n * // Inline content\r\n * <System content=\"You are a helpful assistant\" />\r\n *\r\n * // Computed content\r\n * <System compute={(ctx) => `Analyze: ${ctx.inputs.file}`} />\r\n *\r\n * // Children (text)\r\n * <System>You are a helpful assistant</System>\r\n *\r\n * // Children (function)\r\n * <System>{(ctx) => `Task: ${ctx.inputs.task}`}</System>\r\n * ```\r\n */\r\nexport function System(props: SystemProps): SystemNode {\r\n const { source, required, content, compute, children } = props;\r\n\r\n // Determine content strategy\r\n let finalContent: string | undefined;\r\n let finalCompute: ((ctx: ExecutionContext) => string | Promise<string>) | undefined;\r\n\r\n if (source) {\r\n // File source\r\n if (content || compute || children) {\r\n throw new Error('System: cannot use source with content, compute, or children');\r\n }\r\n } else if (content) {\r\n // Inline content\r\n if (compute || children) {\r\n throw new Error('System: cannot use content with compute or children');\r\n }\r\n finalContent = content;\r\n } else if (compute) {\r\n // Computed content\r\n if (children) {\r\n throw new Error('System: cannot use compute with children');\r\n }\r\n finalCompute = compute;\r\n } else if (children) {\r\n // Children can be: string, function, or array (from JSX)\r\n let actualChild = children;\r\n\r\n // Unwrap array children (JSX always passes array)\r\n if (Array.isArray(children)) {\r\n if (children.length === 0) {\r\n throw new Error('System: children array is empty');\r\n }\r\n\r\n // Check if we have mixed content with ToolRef nodes\r\n const hasToolRef = children.some(\r\n (child) =>\r\n typeof child === 'object' &&\r\n child !== null &&\r\n 'type' in child &&\r\n child.type === 'ToolRef'\r\n );\r\n\r\n if (hasToolRef) {\r\n // Template mode: collect all parts\r\n const parts: TemplatePart[] = [];\r\n\r\n for (const child of children) {\r\n if (typeof child === 'object' && child !== null && 'type' in child) {\r\n const node = child as any;\r\n if (node.type === 'Text' && node.props?.content) {\r\n parts.push({ kind: 'text', value: node.props.content });\r\n } else if (node.type === 'ComputedText' && node.props?.compute) {\r\n parts.push({ kind: 'computed', compute: node.props.compute });\r\n } else if (node.type === 'ToolRef' && node.props?.toolName) {\r\n parts.push({ kind: 'toolref', toolName: node.props.toolName });\r\n } else {\r\n throw new Error(`System: invalid child type in template mode: ${node.type}`);\r\n }\r\n } else if (typeof child === 'string') {\r\n parts.push({ kind: 'text', value: child });\r\n } else if (typeof child === 'function') {\r\n parts.push({ kind: 'computed', compute: child });\r\n } else {\r\n throw new Error('System: invalid child in template mode');\r\n }\r\n }\r\n\r\n return {\r\n type: 'System',\r\n props: {\r\n source,\r\n required,\r\n templateParts: parts,\r\n },\r\n };\r\n }\r\n\r\n // Single-child mode (existing behavior)\r\n if (children.length > 1) {\r\n throw new Error('System: can only have one child');\r\n }\r\n actualChild = children[0];\r\n }\r\n\r\n // Handle ComputedText node from jsx-runtime\r\n if (typeof actualChild === 'object' && actualChild !== null && 'type' in actualChild) {\r\n const node = actualChild as any;\r\n if (node.type === 'ComputedText' && node.props?.compute) {\r\n finalCompute = node.props.compute;\r\n } else if (node.type === 'Text' && node.props?.content) {\r\n finalContent = node.props.content;\r\n } else {\r\n throw new Error('System: invalid child node type');\r\n }\r\n } else if (typeof actualChild === 'string') {\r\n finalContent = actualChild;\r\n } else if (typeof actualChild === 'function') {\r\n finalCompute = actualChild;\r\n } else {\r\n throw new Error('System: children must be a string or function');\r\n }\r\n } else {\r\n throw new Error('System: must provide source, content, compute, or children');\r\n }\r\n\r\n return {\r\n type: 'System',\r\n props: {\r\n source,\r\n required,\r\n content: finalContent,\r\n compute: finalCompute,\r\n },\r\n };\r\n}\r\n","/**\r\n * Deity TSX - User Prompt Component\r\n *\r\n * User prompt node with support for inline or computed content.\r\n */\r\n\r\nimport type { UserNode, TemplatePart } from '../ast/types.js';\r\nimport type { ExecutionContext } from '../engine/types.js';\r\n\r\n/**\r\n * User Component Props\r\n */\r\nexport interface UserProps {\r\n /**\r\n * Inline content\r\n */\r\n content?: string;\r\n\r\n /**\r\n * Computed content (function)\r\n *\r\n * Receives ExecutionContext and returns prompt string.\r\n */\r\n compute?: (ctx: ExecutionContext) => string | Promise<string>;\r\n\r\n /**\r\n * Children (text or computed function)\r\n */\r\n children?: any; // Accept any JSX children, validate at runtime\r\n}\r\n\r\n/**\r\n * User Component\r\n *\r\n * Defines a user prompt with multiple strategies:\r\n * - Inline: `<User content=\"Analyze this file\" />`\r\n * - Computed: `<User compute={(ctx) => generatePrompt(ctx)} />`\r\n * - Children: `<User>{(ctx) => `Task: ${ctx.inputs.task}`}</User>`\r\n *\r\n * @example\r\n * ```tsx\r\n * // Inline content\r\n * <User content=\"Analyze this file\" />\r\n *\r\n * // Computed content\r\n * <User compute={(ctx) => `Analyze: ${ctx.inputs.file}`} />\r\n *\r\n * // Children (text)\r\n * <User>Analyze this file</User>\r\n *\r\n * // Children (function)\r\n * <User>{(ctx) => `Task: ${ctx.inputs.task}`}</User>\r\n * ```\r\n */\r\nexport function User(props: UserProps): UserNode {\r\n const { content, compute, children } = props;\r\n\r\n // Determine content strategy\r\n let finalContent: string | undefined;\r\n let finalCompute: ((ctx: ExecutionContext) => string | Promise<string>) | undefined;\r\n\r\n if (content) {\r\n // Inline content\r\n if (compute || children) {\r\n throw new Error('User: cannot use content with compute or children');\r\n }\r\n finalContent = content;\r\n } else if (compute) {\r\n // Computed content\r\n if (children) {\r\n throw new Error('User: cannot use compute with children');\r\n }\r\n finalCompute = compute;\r\n } else if (children) {\r\n // Children can be: string, function, or array (from JSX)\r\n let actualChild = children;\r\n\r\n // Unwrap array children (JSX always passes array)\r\n if (Array.isArray(children)) {\r\n if (children.length === 0) {\r\n throw new Error('User: children array is empty');\r\n }\r\n\r\n // Check if we have mixed content with ToolRef nodes\r\n const hasToolRef = children.some(\r\n (child) =>\r\n typeof child === 'object' &&\r\n child !== null &&\r\n 'type' in child &&\r\n child.type === 'ToolRef'\r\n );\r\n\r\n if (hasToolRef) {\r\n // Template mode: collect all parts\r\n const parts: TemplatePart[] = [];\r\n\r\n for (const child of children) {\r\n if (typeof child === 'object' && child !== null && 'type' in child) {\r\n const node = child as any;\r\n if (node.type === 'Text' && node.props?.content) {\r\n parts.push({ kind: 'text', value: node.props.content });\r\n } else if (node.type === 'ComputedText' && node.props?.compute) {\r\n parts.push({ kind: 'computed', compute: node.props.compute });\r\n } else if (node.type === 'ToolRef' && node.props?.toolName) {\r\n parts.push({ kind: 'toolref', toolName: node.props.toolName });\r\n } else {\r\n throw new Error(`User: invalid child type in template mode: ${node.type}`);\r\n }\r\n } else if (typeof child === 'string') {\r\n parts.push({ kind: 'text', value: child });\r\n } else if (typeof child === 'function') {\r\n parts.push({ kind: 'computed', compute: child });\r\n } else {\r\n throw new Error('User: invalid child in template mode');\r\n }\r\n }\r\n\r\n return {\r\n type: 'User',\r\n props: {\r\n templateParts: parts,\r\n },\r\n };\r\n }\r\n\r\n // Single-child mode (existing behavior)\r\n if (children.length > 1) {\r\n throw new Error('User: can only have one child');\r\n }\r\n actualChild = children[0];\r\n }\r\n\r\n // Handle ComputedText node from jsx-runtime\r\n if (typeof actualChild === 'object' && actualChild !== null && 'type' in actualChild) {\r\n const node = actualChild as any;\r\n if (node.type === 'ComputedText' && node.props?.compute) {\r\n finalCompute = node.props.compute;\r\n } else if (node.type === 'Text' && node.props?.content) {\r\n finalContent = node.props.content;\r\n } else {\r\n throw new Error('User: invalid child node type');\r\n }\r\n } else if (typeof actualChild === 'string') {\r\n finalContent = actualChild;\r\n } else if (typeof actualChild === 'function') {\r\n finalCompute = actualChild;\r\n } else {\r\n throw new Error('User: children must be a string or function');\r\n }\r\n } else {\r\n throw new Error('User: must provide content, compute, or children');\r\n }\r\n\r\n return {\r\n type: 'User',\r\n props: {\r\n content: finalContent,\r\n compute: finalCompute,\r\n },\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Observe Component\r\n *\r\n * Declarative observation of LLM execution.\r\n */\r\n\r\nimport type { ObserveNode } from '../ast/types.js';\r\nimport type { LLMLoopResult } from '../engine/types.js';\r\n\r\n/**\r\n * Observe Component Props\r\n */\r\nexport interface ObserveProps {\r\n /**\r\n * Compute function to extract observations\r\n *\r\n * Must return a plain object with observed values.\r\n * Do NOT mutate llmResult.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * toolCallCount: llmResult.toolCalls.length,\r\n * hasError: llmResult.toolCalls.some(tc => tc.error),\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\n children?: any; // Accept any JSX children, validate at runtime\r\n\r\n /**\r\n * Alternative to children (same as children)\r\n */\r\n compute?: (llmResult: LLMLoopResult) => Record<string, unknown> | Promise<Record<string, unknown>>;\r\n}\r\n\r\n/**\r\n * Observe Component\r\n *\r\n * Used to extract statistics and metadata from LLM loop results:\r\n * - Tool call counts\r\n * - Success/failure rates\r\n * - Custom metrics\r\n *\r\n * The observed data is passed to Result and Validate nodes.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * planningCalled: llmResult.toolCalls.filter(\r\n * tc => tc.name === 'planning_create'\r\n * ).length,\r\n * filesScanned: llmResult.toolCalls.filter(\r\n * tc => tc.name === 'file_list'\r\n * ).length,\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\nexport function Observe(props: ObserveProps): ObserveNode {\r\n const { children, compute } = props;\r\n\r\n // Determine compute function\r\n let finalCompute: (llmResult: LLMLoopResult) => Record<string, unknown> | Promise<Record<string, unknown>>;\r\n\r\n if (children) {\r\n if (compute) {\r\n throw new Error('Observe: cannot use both children and compute');\r\n }\r\n\r\n // Unwrap array children (JSX always passes array)\r\n let actualChild = children;\r\n if (Array.isArray(children)) {\r\n if (children.length === 0) {\r\n throw new Error('Observe: children array is empty');\r\n }\r\n if (children.length > 1) {\r\n throw new Error('Observe: can only have one child');\r\n }\r\n actualChild = children[0];\r\n }\r\n\r\n // Handle ComputedText node from jsx-runtime\r\n if (typeof actualChild === 'object' && actualChild !== null && 'type' in actualChild) {\r\n const node = actualChild as any;\r\n if (node.type === 'ComputedText' && node.props?.compute) {\r\n finalCompute = node.props.compute as any;\r\n } else {\r\n throw new Error('Observe: invalid child node type (expected ComputedText)');\r\n }\r\n } else if (typeof actualChild === 'function') {\r\n finalCompute = actualChild as any;\r\n } else {\r\n throw new Error('Observe: children must be a function');\r\n }\r\n } else if (compute) {\r\n finalCompute = compute as any;\r\n } else {\r\n throw new Error('Observe: must provide children or compute function');\r\n }\r\n\r\n return {\r\n type: 'Observe',\r\n props: {\r\n compute: finalCompute,\r\n },\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Result Component\r\n *\r\n * Extract structured output from LLM execution.\r\n */\r\n\r\nimport type { ResultNode } from '../ast/types.js';\r\nimport type { ExecutionContext, LLMLoopResult } from '../engine/types.js';\r\n\r\n/**\r\n * Result Component Props\r\n */\r\nexport interface ResultProps<O = unknown> {\r\n /**\r\n * Extract function to produce output\r\n *\r\n * @param ctx - Execution context with inputs\r\n * @param llmResult - Complete LLM loop result\r\n * @param observed - Data from Observe node (if present)\r\n * @returns Output data (must conform to output schema)\r\n *\r\n * @example\r\n * ```tsx\r\n * <Result>\r\n * {(ctx, llmResult, observed) => {\r\n * const planCall = llmResult.toolCalls.find(\r\n * tc => tc.name === 'planning_create'\r\n * );\r\n * return JSON.parse(planCall.arguments);\r\n * }}\r\n * </Result>\r\n * ```\r\n */\r\n children?: any; // Accept any JSX children, validate at runtime\r\n\r\n /**\r\n * Alternative to children (same as children)\r\n */\r\n extract?: (\r\n ctx: ExecutionContext,\r\n llmResult: LLMLoopResult,\r\n observed: Record<string, unknown>\r\n ) => O | Promise<O>;\r\n}\r\n\r\n/**\r\n * Result Component\r\n *\r\n * Responsible for:\r\n * - Extracting output from llmResult (e.g., tool call arguments)\r\n * - Using observed data from Observe node\r\n * - Returning data that conforms to output schema\r\n *\r\n * @example\r\n * ```tsx\r\n * <Result>\r\n * {(ctx, llmResult, observed) => {\r\n * const planCall = llmResult.toolCalls.find(\r\n * tc => tc.name === 'planning_create'\r\n * );\r\n *\r\n * if (!planCall) {\r\n * throw new Error('planning_create not called');\r\n * }\r\n *\r\n * return JSON.parse(planCall.arguments);\r\n * }}\r\n * </Result>\r\n * ```\r\n */\r\nexport function Result<O = unknown>(props: ResultProps<O>): ResultNode<O> {\r\n const { children, extract } = props;\r\n\r\n // Determine extract function\r\n let finalExtract: (\r\n ctx: ExecutionContext,\r\n llmResult: LLMLoopResult,\r\n observed: Record<string, unknown>\r\n ) => O | Promise<O>;\r\n\r\n if (children) {\r\n if (extract) {\r\n throw new Error('Result: cannot use both children and extract');\r\n }\r\n\r\n // Unwrap array children (JSX always passes array)\r\n let actualChild = children;\r\n if (Array.isArray(children)) {\r\n if (children.length === 0) {\r\n throw new Error('Result: children array is empty');\r\n }\r\n if (children.length > 1) {\r\n throw new Error('Result: can only have one child');\r\n }\r\n actualChild = children[0];\r\n }\r\n\r\n // Handle ComputedText node from jsx-runtime\r\n if (typeof actualChild === 'object' && actualChild !== null && 'type' in actualChild) {\r\n const node = actualChild as any;\r\n if (node.type === 'ComputedText' && node.props?.compute) {\r\n finalExtract = node.props.compute as any;\r\n } else {\r\n throw new Error('Result: invalid child node type (expected ComputedText)');\r\n }\r\n } else if (typeof actualChild === 'function') {\r\n finalExtract = actualChild as any;\r\n } else {\r\n throw new Error('Result: children must be a function');\r\n }\r\n } else if (extract) {\r\n finalExtract = extract as any;\r\n } else {\r\n throw new Error('Result: must provide children or extract function');\r\n }\r\n\r\n return {\r\n type: 'Result',\r\n props: {\r\n extract: finalExtract,\r\n },\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Validate Component\r\n *\r\n * Declarative validation rules for output.\r\n */\r\n\r\nimport type { ValidateNode, ValidationRules } from '../ast/types.js';\r\nimport type { ExecutionContext } from '../engine/types.js';\r\n\r\n/**\r\n * Validate Component Props\r\n */\r\nexport interface ValidateProps {\r\n /**\r\n * Rules function to generate validation rules\r\n *\r\n * @param output - Extracted output from Result node\r\n * @param ctx - Execution context\r\n * @param observed - Data from Observe node (if present)\r\n * @returns Validation rules\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output, ctx, observed) => ({\r\n * rules: [\r\n * {\r\n * check: output.total_tasks >= 5,\r\n * error: `Must have >= 5 tasks, got ${output.total_tasks}`,\r\n * },\r\n * {\r\n * check: observed.planningCalled > 0,\r\n * error: 'Must call planning_create tool',\r\n * },\r\n * ],\r\n * })}\r\n * </Validate>\r\n * ```\r\n */\r\n children?: any; // Accept any JSX children, validate at runtime\r\n\r\n /**\r\n * Alternative to children (same as children)\r\n */\r\n rules?: (\r\n output: unknown,\r\n ctx: ExecutionContext,\r\n observed: Record<string, unknown>\r\n ) => ValidationRules | Promise<ValidationRules>;\r\n}\r\n\r\n/**\r\n * Validate Component\r\n *\r\n * Used to validate output against business rules.\r\n * Returns structured errors for consistent handling.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output, ctx, observed) => ({\r\n * rules: [\r\n * {\r\n * check: output.total_tasks >= 5,\r\n * error: `Plan must have at least 5 tasks, got ${output.total_tasks}`,\r\n * },\r\n * {\r\n * check: output.tasks.length === output.total_tasks,\r\n * error: 'Task count mismatch',\r\n * },\r\n * {\r\n * check: observed.planningCalled > 0,\r\n * error: 'Must call planning_create tool',\r\n * },\r\n * ],\r\n * })}\r\n * </Validate>\r\n * ```\r\n */\r\nexport function Validate(props: ValidateProps): ValidateNode {\r\n const { children, rules } = props;\r\n\r\n // Determine rules function\r\n let finalRules: (\r\n output: unknown,\r\n ctx: ExecutionContext,\r\n observed: Record<string, unknown>\r\n ) => ValidationRules | Promise<ValidationRules>;\r\n\r\n if (children) {\r\n if (rules) {\r\n throw new Error('Validate: cannot use both children and rules');\r\n }\r\n\r\n // Unwrap array children (JSX always passes array)\r\n let actualChild = children;\r\n if (Array.isArray(children)) {\r\n if (children.length === 0) {\r\n throw new Error('Validate: children array is empty');\r\n }\r\n if (children.length > 1) {\r\n throw new Error('Validate: can only have one child');\r\n }\r\n actualChild = children[0];\r\n }\r\n\r\n // Handle ComputedText node from jsx-runtime\r\n if (typeof actualChild === 'object' && actualChild !== null && 'type' in actualChild) {\r\n const node = actualChild as any;\r\n if (node.type === 'ComputedText' && node.props?.compute) {\r\n finalRules = node.props.compute as any;\r\n } else {\r\n throw new Error('Validate: invalid child node type (expected ComputedText)');\r\n }\r\n } else if (typeof actualChild === 'function') {\r\n finalRules = actualChild as any;\r\n } else {\r\n throw new Error('Validate: children must be a function');\r\n }\r\n } else if (rules) {\r\n finalRules = rules as any;\r\n } else {\r\n throw new Error('Validate: must provide children or rules function');\r\n }\r\n\r\n return {\r\n type: 'Validate',\r\n props: {\r\n rules: finalRules,\r\n },\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Retry Component\r\n *\r\n * Retry policy configuration.\r\n */\r\n\r\nimport type { RetryNode } from '../ast/types.js';\r\n\r\n/**\r\n * Retry Component Props\r\n */\r\nexport interface RetryProps {\r\n /**\r\n * Maximum retry attempts (default: 3)\r\n */\r\n maxAttempts?: number;\r\n\r\n /**\r\n * Include validation errors in retry prompt (default: true)\r\n */\r\n feedbackOnError?: boolean;\r\n\r\n /**\r\n * Retry on tool execution errors (default: true)\r\n */\r\n retryOnToolError?: boolean;\r\n\r\n /**\r\n * Send tool errors to LLM for correction (default: true)\r\n */\r\n feedbackErrorToLLM?: boolean;\r\n}\r\n\r\n/**\r\n * Retry Component\r\n *\r\n * Specifies how the agent should retry on validation failures.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Retry\r\n * maxAttempts={3}\r\n * feedbackOnError={true}\r\n * />\r\n * ```\r\n */\r\nexport function Retry(props: RetryProps = {}): RetryNode {\r\n const {\r\n maxAttempts = 3,\r\n feedbackOnError = true,\r\n retryOnToolError = true,\r\n feedbackErrorToLLM = true,\r\n } = props;\r\n\r\n // Validate maxAttempts\r\n if (maxAttempts < 0) {\r\n throw new Error('Retry: maxAttempts must be >= 0');\r\n }\r\n\r\n return {\r\n type: 'Retry',\r\n props: {\r\n maxAttempts,\r\n feedbackOnError,\r\n retryOnToolError,\r\n feedbackErrorToLLM,\r\n },\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Tools Components\r\n *\r\n * Container and definition components for declaring tools in JSX.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Agent id=\"my-agent\" input={InputSchema} output={OutputSchema}>\r\n * <Tools>\r\n * <MemoryStore />\r\n * <MemoryRecall />\r\n * <Tool name=\"greet\" description=\"Greet user\" input={GreetSchema}>\r\n * {async (params) => ({ success: true, data: { message: `Hello ${params.name}` } })}\r\n * </Tool>\r\n * </Tools>\r\n * <Prompt>...</Prompt>\r\n * <Result>...</Result>\r\n * </Agent>\r\n * ```\r\n */\r\n\r\nimport type { ZodSchema } from 'zod';\r\nimport type { ToolsNode, ToolDefNode } from '../ast/types.js';\r\nimport type { ToolSpec, ExecutionContext } from '../engine/types.js';\r\n\r\n/**\r\n * Tools Component Props\r\n */\r\nexport interface ToolsProps {\r\n /** Child ToolDef/Tool components */\r\n children?: any[];\r\n}\r\n\r\n/**\r\n * Tools Component\r\n *\r\n * Container for tool definitions within an Agent.\r\n * All tools (including memory tools) are declared as children.\r\n */\r\nexport function Tools(props: ToolsProps): ToolsNode {\r\n const { children } = props;\r\n\r\n // Filter children to only include ToolDef nodes\r\n const toolDefs: ToolDefNode[] = (children || []).filter(\r\n (child: any) => child?.type === 'Tools:Def'\r\n );\r\n\r\n return {\r\n type: 'Tools',\r\n props: {},\r\n children: toolDefs,\r\n };\r\n}\r\n\r\n/**\r\n * ToolDef Component Props\r\n */\r\nexport interface ToolDefProps {\r\n /** The tool object to register */\r\n tool: ToolSpec;\r\n\r\n /** Children (not used, but accepted for JSX compatibility) */\r\n children?: any[];\r\n}\r\n\r\n/**\r\n * ToolDef Component\r\n *\r\n * Wraps a single Tool object as a JSX element.\r\n * Must be used inside a <Tools> container.\r\n *\r\n * Low-level escape hatch for pre-built ToolSpec objects.\r\n * Prefer using the declarative <Tool> component for new tools.\r\n */\r\nexport function ToolDef(props: ToolDefProps): ToolDefNode {\r\n return {\r\n type: 'Tools:Def',\r\n props: { tool: props.tool },\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// Declarative Tool Component\r\n// ============================================================================\r\n\r\n/**\r\n * Tool Component Props\r\n *\r\n * Declarative tool definition using TSX syntax.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Tool name=\"file_list\" description=\"List files\" input={FileListInputSchema}>\r\n * {async (params) => {\r\n * const files = await glob(params.pattern);\r\n * return { success: true, data: { files } };\r\n * }}\r\n * </Tool>\r\n *\r\n * // Or using the execute prop instead of children:\r\n * <Tool\r\n * name=\"file_list\"\r\n * description=\"List files\"\r\n * input={FileListInputSchema}\r\n * execute={async (params) => ({ success: true, data: { files: [] } })}\r\n * />\r\n * ```\r\n */\r\nexport interface ToolProps<TInput = unknown> {\r\n /** Tool name (unique identifier used by LLM) */\r\n name: string;\r\n\r\n /** Description (LLM uses this to decide when to invoke the tool) */\r\n description: string;\r\n\r\n /** Input validation schema (Zod) */\r\n input: ZodSchema<TInput>;\r\n\r\n /**\r\n * Execute function (alternative to children).\r\n * Use either `execute` prop or a function child, not both.\r\n */\r\n execute?: (input: TInput, ctx?: ExecutionContext) => any;\r\n\r\n /** Function child that implements tool execution */\r\n children?: any[];\r\n}\r\n\r\n/**\r\n * Tool Component\r\n *\r\n * Declarative tool definition as a first-class TSX component.\r\n * Produces a `ToolDefNode` (same as `<ToolDef>`), so the\r\n * compiler and executor require zero changes.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Tool name=\"file_list\" description=\"List files\" input={FileListInputSchema}>\r\n * {async (params: FileListInput) => {\r\n * const files = await glob(params.pattern, { cwd: rootPath });\r\n * return { success: true, data: { files, total: files.length } };\r\n * }}\r\n * </Tool>\r\n * ```\r\n */\r\nexport function Tool<TInput = unknown>(props: ToolProps<TInput>): ToolDefNode {\r\n const { name, description, input, execute, children } = props;\r\n\r\n // Validate required props\r\n if (!name) {\r\n throw new Error('Tool: name is required');\r\n }\r\n if (!description) {\r\n throw new Error('Tool: description is required');\r\n }\r\n if (!input) {\r\n throw new Error('Tool: input schema is required');\r\n }\r\n\r\n // Resolve the execute function from children or execute prop\r\n let executeFn: ((input: TInput, ctx?: ExecutionContext) => any) | undefined;\r\n\r\n if (children) {\r\n if (execute) {\r\n throw new Error('Tool: cannot use both children and execute prop');\r\n }\r\n\r\n // Unwrap array children (JSX always passes array)\r\n let actualChild = children;\r\n if (Array.isArray(children)) {\r\n if (children.length === 0) {\r\n throw new Error('Tool: children array is empty');\r\n }\r\n if (children.length > 1) {\r\n throw new Error('Tool: can only have one child (the execute function)');\r\n }\r\n actualChild = children[0];\r\n }\r\n\r\n // Handle ComputedText node from jsx-runtime\r\n // (JSX runtime wraps function children as { type: 'ComputedText', props: { compute: fn } })\r\n if (typeof actualChild === 'object' && actualChild !== null && 'type' in actualChild) {\r\n const node = actualChild as any;\r\n if (node.type === 'ComputedText' && node.props?.compute) {\r\n executeFn = node.props.compute as any;\r\n } else {\r\n throw new Error('Tool: invalid child node type (expected ComputedText with execute function)');\r\n }\r\n } else if (typeof actualChild === 'function') {\r\n // Direct function (non-JSX path)\r\n executeFn = actualChild as any;\r\n } else {\r\n throw new Error('Tool: children must be a function');\r\n }\r\n } else if (execute) {\r\n executeFn = execute;\r\n } else {\r\n throw new Error('Tool: must provide children (execute function) or execute prop');\r\n }\r\n\r\n // Assemble the ToolSpec object\r\n const toolSpec: ToolSpec<TInput> = {\r\n name,\r\n description,\r\n inputSchema: input,\r\n execute: executeFn as (input: TInput, ctx?: ExecutionContext) => Promise<any>,\r\n };\r\n\r\n // Return a ToolDefNode — same output as <ToolDef tool={...} />\r\n return {\r\n type: 'Tools:Def',\r\n props: { tool: toolSpec },\r\n };\r\n}\r\n","/**\r\n * Deity TSX - ToolRef Component\r\n *\r\n * Allows referencing tool names in prompt text in a type-safe, refactoring-friendly way.\r\n */\r\n\r\nimport type { ToolRefNode, ToolDefNode } from '../ast/types.js';\r\nimport type { ToolSpec } from '../engine/types.js';\r\n\r\n/**\r\n * ToolRef target type\r\n *\r\n * Can be:\r\n * - A tool component function with .toolName static property\r\n * - A ToolSpec object with .name property\r\n * - A plain string tool ID\r\n */\r\nexport type ToolRefTarget =\r\n | { toolName: string } // Tool component with static toolName\r\n | { (): ToolDefNode; toolName: string } // Tool component function + toolName\r\n | ToolSpec // ToolSpec object (has .name)\r\n | string; // Direct tool ID string\r\n\r\n/**\r\n * ToolRef Component Props\r\n */\r\nexport interface ToolRefProps {\r\n /**\r\n * Tool reference\r\n *\r\n * Can be:\r\n * - Tool component with .toolName: `<ToolRef tool={MemoryStore} />`\r\n * - ToolSpec object: `<ToolRef tool={myToolSpec} />`\r\n * - String ID: `<ToolRef tool=\"memory_store\" />`\r\n */\r\n tool: ToolRefTarget;\r\n}\r\n\r\n/**\r\n * ToolRef Component\r\n *\r\n * Inserts a tool name reference into prompt text. The reference is resolved\r\n * at compile time to the tool's runtime ID.\r\n *\r\n * This provides type-safe, refactor-friendly tool references that stay in sync\r\n * with the <Tools> tree, unlike hard-coded string IDs.\r\n *\r\n * @example\r\n * ```tsx\r\n * import { MemoryStore } from '@limo-labs/deity-tools';\r\n *\r\n * <User>\r\n * Use <ToolRef tool={MemoryStore} /> to save your findings.\r\n * </User>\r\n * // Compiles to: \"Use memory_store to save your findings.\"\r\n * ```\r\n *\r\n * @example\r\n * ```tsx\r\n * // With a custom tool\r\n * const myTool = createTool({ name: 'my_tool', ... });\r\n *\r\n * <User>\r\n * Call <ToolRef tool={myTool} /> when ready.\r\n * </User>\r\n * // Compiles to: \"Call my_tool when ready.\"\r\n * ```\r\n *\r\n * @example\r\n * ```tsx\r\n * // Direct string (for backwards compatibility)\r\n * <User>\r\n * Use <ToolRef tool=\"memory_store\" /> for persistence.\r\n * </User>\r\n * ```\r\n */\r\nexport function ToolRef(props: ToolRefProps): ToolRefNode {\r\n const { tool } = props;\r\n let toolName: string;\r\n\r\n // Handle null/undefined first\r\n if (tool === null || tool === undefined) {\r\n throw new Error(\r\n 'ToolRef: `tool` prop must be a tool component with .toolName, ' +\r\n 'a ToolSpec with .name, or a string tool ID'\r\n );\r\n }\r\n\r\n // Extract tool name from various formats\r\n if (typeof tool === 'string') {\r\n // Direct string\r\n toolName = tool;\r\n } else if (typeof tool === 'function' && 'toolName' in tool && typeof tool.toolName === 'string') {\r\n // Tool component function with .toolName static property\r\n toolName = tool.toolName;\r\n } else if (typeof tool === 'object' && 'toolName' in tool && typeof tool.toolName === 'string') {\r\n // Object with .toolName property\r\n toolName = tool.toolName;\r\n } else if (typeof tool === 'object' && 'name' in tool && typeof tool.name === 'string') {\r\n // ToolSpec object\r\n toolName = tool.name;\r\n } else {\r\n throw new Error(\r\n 'ToolRef: `tool` prop must be a tool component with .toolName, ' +\r\n 'a ToolSpec with .name, or a string tool ID'\r\n );\r\n }\r\n\r\n return {\r\n type: 'ToolRef',\r\n props: { toolName },\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Sequence Component\r\n *\r\n * Execute child nodes in sequential order.\r\n */\r\n\r\nimport type { WorkflowSequenceNode, WorkflowChildNode } from '../ast/types.js';\r\n\r\n/**\r\n * Sequence Component Props\r\n */\r\nexport interface SequenceProps {\r\n /** Child workflow nodes (Agents or other workflow structures) */\r\n children?: WorkflowChildNode[] | any[]; // Accept JSX children, validate at runtime\r\n}\r\n\r\n/**\r\n * Sequence Component\r\n *\r\n * Executes child nodes in sequential order.\r\n * Each child completes before the next one starts.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Sequence>\r\n * <Agent1 />\r\n * <Agent2 />\r\n * <Agent3 />\r\n * </Sequence>\r\n * ```\r\n */\r\nexport function Sequence(props: SequenceProps): WorkflowSequenceNode {\r\n const { children } = props;\r\n\r\n // Validate children\r\n if (!children || children.length === 0) {\r\n throw new Error('Sequence: must have at least one child');\r\n }\r\n\r\n return {\r\n type: 'WorkflowSequence',\r\n children,\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Parallel Component\r\n *\r\n * Execute child nodes concurrently.\r\n */\r\n\r\nimport type { WorkflowParallelNode, WorkflowChildNode } from '../ast/types.js';\r\n\r\n/**\r\n * Parallel Component Props\r\n */\r\nexport interface ParallelProps {\r\n /** Child workflow nodes (Agents or other workflow structures) */\r\n children?: WorkflowChildNode[] | any[]; // Accept JSX children, validate at runtime\r\n}\r\n\r\n/**\r\n * Parallel Component\r\n *\r\n * Executes child nodes concurrently (in parallel).\r\n * All children start simultaneously and the node completes when all children complete.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Parallel>\r\n * <SecurityScanAgent />\r\n * <PerformanceAnalysisAgent />\r\n * <CodeQualityAgent />\r\n * </Parallel>\r\n * ```\r\n */\r\nexport function Parallel(props: ParallelProps): WorkflowParallelNode {\r\n const { children } = props;\r\n\r\n // Validate children\r\n if (!children || children.length === 0) {\r\n throw new Error('Parallel: must have at least one child');\r\n }\r\n\r\n return {\r\n type: 'WorkflowParallel',\r\n children,\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Conditional Component\r\n *\r\n * Execute child nodes based on a condition.\r\n */\r\n\r\nimport type { WorkflowConditionalNode, WorkflowChildNode } from '../ast/types.js';\r\nimport type { ExecutionContext } from '../engine/types.js';\r\n\r\n/**\r\n * Conditional Component Props\r\n */\r\nexport interface ConditionalProps {\r\n /** Condition function (true = first child, false = second child) */\r\n condition: (ctx: ExecutionContext) => boolean | Promise<boolean>;\r\n\r\n /** Child workflow nodes (1-2 children: true branch required, false branch optional) */\r\n children?: [WorkflowChildNode] | [WorkflowChildNode, WorkflowChildNode] | any[]; // Accept JSX children, validate at runtime\r\n}\r\n\r\n/**\r\n * Conditional Component\r\n *\r\n * Executes child nodes based on a condition function.\r\n * - First child: executed when condition returns true\r\n * - Second child (optional): executed when condition returns false\r\n *\r\n * @example\r\n * ```tsx\r\n * <Conditional condition={(ctx) => ctx.getOutput('check').needsAnalysis}>\r\n * <DeepAnalysisAgent />\r\n * <QuickSummaryAgent />\r\n * </Conditional>\r\n * ```\r\n *\r\n * @example With only true branch\r\n * ```tsx\r\n * <Conditional condition={(ctx) => ctx.getOutput('check').isValid}>\r\n * <ProcessAgent />\r\n * </Conditional>\r\n * ```\r\n */\r\nexport function Conditional(props: ConditionalProps): WorkflowConditionalNode {\r\n const { condition, children } = props;\r\n\r\n // Validate props\r\n if (!condition) {\r\n throw new Error('Conditional: condition prop is required');\r\n }\r\n\r\n if (!children) {\r\n throw new Error('Conditional: must have at least one child (true branch)');\r\n }\r\n\r\n if (children.length < 1 || children.length > 2) {\r\n throw new Error('Conditional: must have 1-2 children (true branch required, false branch optional)');\r\n }\r\n\r\n return {\r\n type: 'WorkflowConditional',\r\n props: {\r\n condition,\r\n },\r\n children: children as [WorkflowChildNode] | [WorkflowChildNode, WorkflowChildNode],\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Loop Component\r\n *\r\n * Execute a child node N times.\r\n */\r\n\r\nimport type { WorkflowLoopNode, WorkflowChildNode } from '../ast/types.js';\r\n\r\n/**\r\n * Loop Component Props\r\n */\r\nexport interface LoopProps {\r\n /** Number of iterations */\r\n iterations: number;\r\n\r\n /** Single child workflow node (Agent or workflow structure) */\r\n children?: WorkflowChildNode | any; // Accept JSX children, validate at runtime\r\n}\r\n\r\n/**\r\n * Loop Component\r\n *\r\n * Executes a single child node N times.\r\n * The child has access to iteration context via ctx.iteration.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Loop iterations={3}>\r\n * <RefineAgent />\r\n * </Loop>\r\n * ```\r\n */\r\nexport function Loop(props: LoopProps): WorkflowLoopNode {\r\n const { iterations, children } = props;\r\n\r\n // Validate props\r\n if (!iterations || iterations < 1) {\r\n throw new Error('Loop: iterations must be >= 1');\r\n }\r\n\r\n if (!children) {\r\n throw new Error('Loop: must have exactly one child');\r\n }\r\n\r\n // Convert single child to array for consistent AST structure\r\n const childArray = Array.isArray(children) ? children : [children];\r\n\r\n if (childArray.length !== 1) {\r\n throw new Error('Loop: must have exactly one child');\r\n }\r\n\r\n return {\r\n type: 'WorkflowLoop',\r\n props: {\r\n iterations,\r\n },\r\n children: [childArray[0]],\r\n };\r\n}\r\n","/**\r\n * Deity TSX - ForEach Component\r\n *\r\n * Execute a child node for each item in a dynamic array.\r\n */\r\n\r\nimport type { WorkflowForEachNode, WorkflowChildNode } from '../ast/types.js';\r\nimport type { ExecutionContext } from '../engine/types.js';\r\n\r\n/**\r\n * Item injection modes for ForEach\r\n */\r\nexport type ItemMode = 'merge' | 'replace' | 'property';\r\n\r\n/**\r\n * Error handling modes for ForEach\r\n */\r\nexport type ErrorMode = 'stop' | 'continue' | 'skip';\r\n\r\n/**\r\n * ForEach Component Props\r\n */\r\nexport interface ForEachProps<TItem = unknown> {\r\n /**\r\n * Array of items to iterate over, or function to dynamically resolve items\r\n * Function can be sync or async\r\n */\r\n items: TItem[] | ((ctx: ExecutionContext) => TItem[] | Promise<TItem[]>);\r\n\r\n /**\r\n * How to inject the current item into context inputs\r\n * - 'property' (default): Inject as ctx.inputs[itemKey]\r\n * - 'merge': Spread item properties into ctx.inputs (for object items)\r\n * - 'replace': Replace entire ctx.inputs with item\r\n */\r\n itemMode?: ItemMode;\r\n\r\n /**\r\n * Key name for 'property' mode (default: 'currentItem')\r\n */\r\n itemKey?: string;\r\n\r\n /**\r\n * Error handling mode\r\n * - 'stop' (default): Fail-fast, throw on first error\r\n * - 'continue': Collect errors, don't stop loop\r\n * - 'skip': Silent failure, increment failure count only\r\n */\r\n errorMode?: ErrorMode;\r\n\r\n /**\r\n * Whether to collect results from each iteration (default: true)\r\n * Set to false for side-effect-only operations to optimize memory\r\n */\r\n collectResults?: boolean;\r\n\r\n /** Single child workflow node (Agent or workflow structure) */\r\n children?: WorkflowChildNode | any; // Accept JSX children, validate at runtime\r\n}\r\n\r\n/**\r\n * ForEach Component\r\n *\r\n * Executes a single child node for each item in an array.\r\n * The child has access to iteration context via ctx.iteration and the current item\r\n * via the injection mode specified.\r\n *\r\n * @example\r\n * ```tsx\r\n * // Static array with property injection\r\n * <ForEach items={['task1', 'task2', 'task3']} itemKey=\"task\">\r\n * <ProcessAgent />\r\n * </ForEach>\r\n *\r\n * // Dynamic array with merge injection\r\n * <ForEach\r\n * items={(ctx) => ctx.getOutput('planner').tasks}\r\n * itemMode=\"merge\"\r\n * errorMode=\"continue\"\r\n * collectResults={false}\r\n * >\r\n * <AnalystAgent />\r\n * </ForEach>\r\n * ```\r\n */\r\nexport function ForEach<TItem = unknown>(props: ForEachProps<TItem>): WorkflowForEachNode {\r\n const {\r\n items,\r\n itemMode = 'property',\r\n itemKey = 'currentItem',\r\n errorMode = 'stop',\r\n collectResults = true,\r\n children\r\n } = props;\r\n\r\n // Validate props\r\n if (!items) {\r\n throw new Error('ForEach: items prop is required');\r\n }\r\n\r\n if (!children) {\r\n throw new Error('ForEach: must have exactly one child');\r\n }\r\n\r\n // Convert single child to array for consistent AST structure\r\n const childArray = Array.isArray(children) ? children : [children];\r\n\r\n if (childArray.length !== 1) {\r\n throw new Error('ForEach: must have exactly one child');\r\n }\r\n\r\n // Validate itemMode\r\n const validModes: ItemMode[] = ['merge', 'replace', 'property'];\r\n if (!validModes.includes(itemMode)) {\r\n throw new Error(`ForEach: itemMode must be one of: ${validModes.join(', ')}`);\r\n }\r\n\r\n // Validate errorMode\r\n const validErrorModes: ErrorMode[] = ['stop', 'continue', 'skip'];\r\n if (!validErrorModes.includes(errorMode)) {\r\n throw new Error(`ForEach: errorMode must be one of: ${validErrorModes.join(', ')}`);\r\n }\r\n\r\n return {\r\n type: 'WorkflowForEach',\r\n props: {\r\n items,\r\n itemMode,\r\n itemKey,\r\n errorMode,\r\n collectResults,\r\n },\r\n children: [childArray[0]],\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Workflow Component\r\n *\r\n * Top-level container for defining a complete workflow.\r\n */\r\n\r\nimport type { WorkflowNode, WorkflowChildNode } from '../ast/types.js';\r\n\r\n/**\r\n * LLM Adapter interface (minimal definition for type safety)\r\n */\r\nexport interface LLMAdapter {\r\n generate(messages: any[], config?: any): Promise<any>;\r\n}\r\n\r\n/**\r\n * Generation Config (minimal definition)\r\n */\r\nexport interface GenerationConfig {\r\n temperature?: number;\r\n maxTokens?: number;\r\n topP?: number;\r\n stopSequences?: string[];\r\n}\r\n\r\n/**\r\n * State Store interface (minimal definition)\r\n */\r\nexport interface StateStore {\r\n get(key: string): Promise<unknown>;\r\n set(key: string, value: unknown): Promise<void>;\r\n}\r\n\r\n/**\r\n * Workflow Enhancement Options\r\n */\r\nexport interface WorkflowEnhancements {\r\n /** Conversation management */\r\n conversation?: {\r\n maxTokens: number;\r\n pruneThreshold: number;\r\n messageRetentionPolicy?: unknown;\r\n };\r\n\r\n /** Memory management */\r\n memory?: {\r\n coreBudget: {\r\n maxItems: number;\r\n maxTotalSize: number;\r\n };\r\n detailedBudget?: {\r\n maxItems: number;\r\n maxTotalSize: number;\r\n };\r\n };\r\n\r\n /** Session persistence */\r\n session?: {\r\n directory: string;\r\n autoSave?: boolean;\r\n };\r\n\r\n /** UI updates */\r\n ui?: any; // UIUpdateBridge\r\n\r\n /** Application state store (isolated from AI memory) */\r\n appState?: any; // StateStore\r\n}\r\n\r\n/**\r\n * Workflow Component Props\r\n */\r\nexport interface WorkflowProps {\r\n /** Workflow name (required) */\r\n name: string;\r\n\r\n /** Optional description */\r\n description?: string;\r\n\r\n /** Default LLM model configuration */\r\n defaultModel?: {\r\n adapter: LLMAdapter;\r\n config?: GenerationConfig;\r\n };\r\n\r\n /** Optional state storage */\r\n state?: {\r\n store: StateStore;\r\n };\r\n\r\n /** Optional enhancements (conversation, memory, session, UI) */\r\n enhancements?: WorkflowEnhancements;\r\n\r\n /** Single child representing the workflow graph */\r\n children?: WorkflowChildNode | any; // Accept JSX children, validate at runtime\r\n}\r\n\r\n/**\r\n * Workflow Component\r\n *\r\n * Top-level container for defining a complete workflow.\r\n * Must contain exactly one child representing the workflow execution graph.\r\n *\r\n * @example\r\n * ```tsx\r\n * const workflow = Workflow({\r\n * name: 'my-workflow',\r\n * defaultModel: { adapter: llmAdapter },\r\n * children: Sequence({\r\n * children: [Agent1, Agent2, Agent3]\r\n * })\r\n * });\r\n * ```\r\n *\r\n * @example With enhancements\r\n * ```tsx\r\n * const workflow = Workflow({\r\n * name: 'enhanced-workflow',\r\n * defaultModel: { adapter: llmAdapter },\r\n * enhancements: {\r\n * conversation: { maxTokens: 8000, pruneThreshold: 6000 },\r\n * memory: {\r\n * coreBudget: { maxItems: 10, maxTotalSize: 8192 }\r\n * }\r\n * },\r\n * children: MyAgent\r\n * });\r\n * ```\r\n */\r\nexport function Workflow(props: WorkflowProps): WorkflowNode {\r\n const { name, description, defaultModel, state, enhancements, children } = props;\r\n\r\n // Validate required props\r\n if (!name) {\r\n throw new Error('Workflow: name is required');\r\n }\r\n\r\n if (!children) {\r\n throw new Error('Workflow: must have exactly one child (workflow graph)');\r\n }\r\n\r\n // Convert single child to array for consistent AST structure\r\n const childArray = Array.isArray(children) ? children : [children];\r\n\r\n if (childArray.length !== 1) {\r\n throw new Error('Workflow: must have exactly one child (workflow graph)');\r\n }\r\n\r\n return {\r\n type: 'Workflow',\r\n props: {\r\n name,\r\n description,\r\n defaultModel,\r\n state,\r\n enhancements,\r\n },\r\n children: [childArray[0]],\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Prompt Resource Loader\r\n *\r\n * Handles loading and caching of prompt resources (files, URLs, etc.)\r\n *\r\n * Features:\r\n * - File loading with relative path resolution\r\n * - Caching mechanism\r\n * - Error handling with clear messages\r\n * - Support for different resource types\r\n */\r\n\r\nimport * as fs from 'fs/promises';\r\nimport * as path from 'path';\r\n\r\n/**\r\n * Resource Type\r\n */\r\nexport enum ResourceType {\r\n File = 'file',\r\n Inline = 'inline',\r\n Computed = 'computed',\r\n}\r\n\r\n/**\r\n * Loaded Resource\r\n */\r\nexport interface LoadedResource {\r\n /** Resource type */\r\n type: ResourceType;\r\n\r\n /** Resource content (for file and inline) */\r\n content?: string;\r\n\r\n /** Source path (for file) */\r\n source?: string;\r\n\r\n /** Whether this resource was loaded successfully */\r\n loaded: boolean;\r\n\r\n /** Error message if loading failed */\r\n error?: string;\r\n}\r\n\r\n/**\r\n * Resource Loader Options\r\n */\r\nexport interface ResourceLoaderOptions {\r\n /** Base path for resolving relative file paths */\r\n basePath?: string;\r\n\r\n /** Enable caching (default: true) */\r\n cache?: boolean;\r\n\r\n /** Cache TTL in milliseconds (default: no expiration) */\r\n cacheTTL?: number;\r\n}\r\n\r\n/**\r\n * Cache Entry\r\n */\r\ninterface CacheEntry {\r\n content: string;\r\n timestamp: number;\r\n}\r\n\r\n/**\r\n * Prompt Resource Loader\r\n *\r\n * Manages loading and caching of prompt resources.\r\n *\r\n * @example\r\n * ```typescript\r\n * const loader = new PromptResourceLoader({\r\n * basePath: '/path/to/agents',\r\n * cache: true,\r\n * });\r\n *\r\n * const resource = await loader.load('file:./prompts/system.md');\r\n * console.log(resource.content);\r\n * ```\r\n */\r\nexport class PromptResourceLoader {\r\n private cache: Map<string, CacheEntry> = new Map();\r\n private options: Required<ResourceLoaderOptions>;\r\n\r\n constructor(options: ResourceLoaderOptions = {}) {\r\n this.options = {\r\n basePath: options.basePath || process.cwd(),\r\n cache: options.cache ?? true,\r\n cacheTTL: options.cacheTTL ?? 0, // 0 = no expiration\r\n };\r\n }\r\n\r\n /**\r\n * Load a resource\r\n *\r\n * @param source - Resource source (e.g., 'file:./prompt.md')\r\n * @param required - Whether this resource is required\r\n * @returns Loaded resource\r\n */\r\n async load(source: string, required: boolean = false): Promise<LoadedResource> {\r\n try {\r\n // Parse resource type\r\n const type = this.parseResourceType(source);\r\n\r\n switch (type) {\r\n case ResourceType.File:\r\n return await this.loadFile(source, required);\r\n default:\r\n return {\r\n type,\r\n loaded: false,\r\n error: `Unsupported resource type: ${type}`,\r\n };\r\n }\r\n } catch (error) {\r\n const errorMessage = error instanceof Error ? error.message : String(error);\r\n\r\n if (required) {\r\n throw new Error(`Failed to load required resource '${source}': ${errorMessage}`);\r\n }\r\n\r\n return {\r\n type: ResourceType.File,\r\n source,\r\n loaded: false,\r\n error: errorMessage,\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Load a file resource\r\n */\r\n private async loadFile(source: string, required: boolean): Promise<LoadedResource> {\r\n // Extract file path (remove 'file:' prefix)\r\n const filePath = this.extractFilePath(source);\r\n\r\n // Resolve absolute path\r\n const absolutePath = this.resolvePath(filePath);\r\n\r\n // Check cache\r\n if (this.options.cache) {\r\n const cached = this.getFromCache(absolutePath);\r\n if (cached) {\r\n return {\r\n type: ResourceType.File,\r\n source: absolutePath,\r\n content: cached,\r\n loaded: true,\r\n };\r\n }\r\n }\r\n\r\n // Load file\r\n try {\r\n const content = await fs.readFile(absolutePath, 'utf-8');\r\n\r\n // Cache the content\r\n if (this.options.cache) {\r\n this.setCache(absolutePath, content);\r\n }\r\n\r\n return {\r\n type: ResourceType.File,\r\n source: absolutePath,\r\n content,\r\n loaded: true,\r\n };\r\n } catch (error) {\r\n const errorMessage = error instanceof Error ? error.message : String(error);\r\n\r\n if (required) {\r\n throw new Error(`Required file not found: ${absolutePath}`);\r\n }\r\n\r\n return {\r\n type: ResourceType.File,\r\n source: absolutePath,\r\n loaded: false,\r\n error: errorMessage,\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Parse resource type from source string\r\n */\r\n private parseResourceType(source: string): ResourceType {\r\n if (source.startsWith('file:')) {\r\n return ResourceType.File;\r\n }\r\n\r\n // Default to inline\r\n return ResourceType.Inline;\r\n }\r\n\r\n /**\r\n * Extract file path from source\r\n */\r\n private extractFilePath(source: string): string {\r\n if (source.startsWith('file:')) {\r\n return source.slice(5); // Remove 'file:' prefix\r\n }\r\n return source;\r\n }\r\n\r\n /**\r\n * Resolve relative path to absolute path\r\n */\r\n private resolvePath(filePath: string): string {\r\n if (path.isAbsolute(filePath)) {\r\n return filePath;\r\n }\r\n\r\n // Resolve relative to base path\r\n return path.resolve(this.options.basePath, filePath);\r\n }\r\n\r\n /**\r\n * Get content from cache\r\n */\r\n private getFromCache(key: string): string | null {\r\n const entry = this.cache.get(key);\r\n\r\n if (!entry) {\r\n return null;\r\n }\r\n\r\n // Check TTL\r\n if (this.options.cacheTTL > 0) {\r\n const age = Date.now() - entry.timestamp;\r\n if (age > this.options.cacheTTL) {\r\n this.cache.delete(key);\r\n return null;\r\n }\r\n }\r\n\r\n return entry.content;\r\n }\r\n\r\n /**\r\n * Set content in cache\r\n */\r\n private setCache(key: string, content: string): void {\r\n this.cache.set(key, {\r\n content,\r\n timestamp: Date.now(),\r\n });\r\n }\r\n\r\n /**\r\n * Clear cache\r\n */\r\n clearCache(): void {\r\n this.cache.clear();\r\n }\r\n\r\n /**\r\n * Get cache size\r\n */\r\n getCacheSize(): number {\r\n return this.cache.size;\r\n }\r\n\r\n /**\r\n * Preflight check - verify all resources exist\r\n *\r\n * @param sources - List of file sources to check\r\n * @returns List of missing resources\r\n */\r\n async preflight(sources: Array<{ source: string; required: boolean }>): Promise<string[]> {\r\n const missing: string[] = [];\r\n\r\n for (const { source, required } of sources) {\r\n if (!source.startsWith('file:')) {\r\n continue; // Skip non-file resources\r\n }\r\n\r\n const filePath = this.extractFilePath(source);\r\n const absolutePath = this.resolvePath(filePath);\r\n\r\n try {\r\n await fs.access(absolutePath);\r\n } catch (error) {\r\n if (required) {\r\n missing.push(absolutePath);\r\n }\r\n }\r\n }\r\n\r\n return missing;\r\n }\r\n}\r\n\r\n/**\r\n * Global resource loader instance\r\n */\r\nlet globalLoader: PromptResourceLoader | null = null;\r\n\r\n/**\r\n * Get or create global resource loader\r\n */\r\nexport function getResourceLoader(options?: ResourceLoaderOptions): PromptResourceLoader {\r\n if (!globalLoader) {\r\n globalLoader = new PromptResourceLoader(options);\r\n }\r\n return globalLoader;\r\n}\r\n\r\n/**\r\n * Set global resource loader\r\n */\r\nexport function setResourceLoader(loader: PromptResourceLoader): void {\r\n globalLoader = loader;\r\n}\r\n\r\n/**\r\n * Reset global resource loader\r\n */\r\nexport function resetResourceLoader(): void {\r\n globalLoader = null;\r\n}\r\n","/**\r\n * Deity TSX - Prompt Compiler\r\n *\r\n * Compiles Prompt AST nodes into buildPrompt function.\r\n */\r\n\r\nimport type { PromptNode, SystemNode, UserNode } from '../ast/types.js';\r\nimport type { ExecutionContext, Message } from '../engine/types.js';\r\nimport { getResourceLoader } from '../utilities/resource-loader.js';\r\n\r\n/**\r\n * Compile Prompt node to buildPrompt function\r\n *\r\n * @param promptNode - Prompt AST node\r\n * @returns buildPrompt function\r\n */\r\nexport function compilePrompt(promptNode: PromptNode) {\r\n if (!promptNode || promptNode.type !== 'Prompt') {\r\n throw new Error('Expected Prompt node');\r\n }\r\n\r\n const children: (SystemNode | UserNode)[] = promptNode.children ?? [];\r\n\r\n return async (ctx: ExecutionContext): Promise<Message[]> => {\r\n const messages: Message[] = [];\r\n\r\n for (const child of children) {\r\n if (child.type === 'System') {\r\n const content = await resolveSystemContent(child, ctx);\r\n messages.push({ role: 'system', content });\r\n } else if (child.type === 'User') {\r\n const content = await resolveUserContent(child, ctx);\r\n messages.push({ role: 'user', content });\r\n } else {\r\n // This should never happen due to type constraints, but check anyway\r\n const _exhaustiveCheck: never = child;\r\n void _exhaustiveCheck; // Suppress unused variable warning\r\n throw new Error(`Invalid Prompt child: ${(child as any).type}`);\r\n }\r\n }\r\n\r\n return messages;\r\n };\r\n}\r\n\r\n/**\r\n * Resolve System node content\r\n */\r\nasync function resolveSystemContent(\r\n node: SystemNode,\r\n ctx: ExecutionContext\r\n): Promise<string> {\r\n const { source, content, compute, required = false, templateParts } = node.props;\r\n\r\n // Template mode (mixed content with ToolRef)\r\n if (templateParts) {\r\n const resolved = await Promise.all(\r\n templateParts.map(async (part) => {\r\n switch (part.kind) {\r\n case 'text':\r\n return part.value;\r\n case 'computed':\r\n return await Promise.resolve(part.compute(ctx));\r\n case 'toolref':\r\n return part.toolName;\r\n default:\r\n // TypeScript exhaustiveness check\r\n const _exhaustive: never = part;\r\n throw new Error(`Unknown template part kind: ${(_exhaustive as any).kind}`);\r\n }\r\n })\r\n );\r\n return resolved.join('');\r\n }\r\n\r\n // File source - use resource loader\r\n if (source) {\r\n if (!source.startsWith('file:')) {\r\n throw new Error(`Invalid source format: ${source} (must start with \"file:\")`);\r\n }\r\n\r\n const loader = getResourceLoader();\r\n const resource = await loader.load(source, required);\r\n\r\n if (!resource.loaded) {\r\n if (required) {\r\n throw new Error(`Required system prompt file not found: ${source}`);\r\n }\r\n // If not required, return empty string\r\n return '';\r\n }\r\n\r\n return resource.content || '';\r\n }\r\n\r\n // Inline content\r\n if (content !== undefined) {\r\n return content;\r\n }\r\n\r\n // Computed content\r\n if (compute) {\r\n return await Promise.resolve(compute(ctx));\r\n }\r\n\r\n throw new Error('System node must have source, content, compute, or templateParts');\r\n}\r\n\r\n/**\r\n * Resolve User node content\r\n */\r\nasync function resolveUserContent(\r\n node: UserNode,\r\n ctx: ExecutionContext\r\n): Promise<string> {\r\n const { content, compute, templateParts } = node.props;\r\n\r\n // Template mode (mixed content with ToolRef)\r\n if (templateParts) {\r\n const resolved = await Promise.all(\r\n templateParts.map(async (part) => {\r\n switch (part.kind) {\r\n case 'text':\r\n return part.value;\r\n case 'computed':\r\n return await Promise.resolve(part.compute(ctx));\r\n case 'toolref':\r\n return part.toolName;\r\n default:\r\n // TypeScript exhaustiveness check\r\n const _exhaustive: never = part;\r\n throw new Error(`Unknown template part kind: ${(_exhaustive as any).kind}`);\r\n }\r\n })\r\n );\r\n return resolved.join('');\r\n }\r\n\r\n // Inline content\r\n if (content !== undefined) {\r\n return content;\r\n }\r\n\r\n // Computed content\r\n if (compute) {\r\n return await Promise.resolve(compute(ctx));\r\n }\r\n\r\n throw new Error('User node must have content, compute, or templateParts');\r\n}\r\n","/**\r\n * Deity TSX - AST Compiler\r\n *\r\n * Compiles AST nodes into executable AgentComponent instances.\r\n *\r\n * Design principles:\r\n * - Pure transformation (AST -> AgentComponent)\r\n * - Fail-fast validation\r\n * - Preserve all function references\r\n * - Type-safe compilation\r\n */\r\n\r\nimport type { AgentNode } from '../ast/types.js';\r\nimport type { AgentComponent } from '../engine/types.js';\r\nimport { compilePrompt } from './compile-prompt.js';\r\nimport { compileObserve } from './compile-observe.js';\r\nimport { compileResult } from './compile-result.js';\r\nimport { compileValidate } from './compile-validate.js';\r\nimport { compileRetry } from './compile-retry.js';\r\n\r\n/**\r\n * Compile Agent AST to AgentComponent\r\n *\r\n * This is the main entry point for compilation.\r\n *\r\n * @param ast - Agent AST node\r\n * @returns Executable AgentComponent\r\n *\r\n * @example\r\n * ```typescript\r\n * const MyAgent = (\r\n * <Agent id=\"test\" input={TestInput} output={TestOutput}>\r\n * <Prompt>...</Prompt>\r\n * <Result>...</Result>\r\n * </Agent>\r\n * );\r\n *\r\n * const component = compileAgent(MyAgent);\r\n * // component is now an executable AgentComponent\r\n * ```\r\n */\r\nexport function compileAgent<I = unknown, O = unknown>(\r\n ast: AgentNode<I, O>\r\n): AgentComponent<I, O> {\r\n // Validate AST\r\n if (ast.type !== 'Agent') {\r\n throw new Error(`Expected Agent node, got ${ast.type}`);\r\n }\r\n\r\n // Extract children\r\n const children = ast.children;\r\n if (!children || children.length === 0) {\r\n throw new Error('Agent must have children');\r\n }\r\n\r\n // Find nodes by type\r\n const promptNode = children.find(n => n?.type === 'Prompt');\r\n const observeNode = children.find(n => n?.type === 'Observe');\r\n const resultNode = children.find(n => n?.type === 'Result');\r\n const validateNode = children.find(n => n?.type === 'Validate');\r\n const retryNode = children.find(n => n?.type === 'Retry');\r\n\r\n if (!promptNode) {\r\n throw new Error('Agent must have a Prompt node');\r\n }\r\n if (!resultNode) {\r\n throw new Error('Agent must have a Result node');\r\n }\r\n\r\n // Compile each part (with type assertions since we validated above)\r\n const buildPrompt = compilePrompt(promptNode as any);\r\n const observe = observeNode ? compileObserve(observeNode as any) : undefined;\r\n const extractOutput = compileResult<O>(resultNode as any, observe);\r\n const validateOutput = validateNode ? compileValidate(validateNode as any) : undefined;\r\n const retry = retryNode ? compileRetry(retryNode as any) : undefined;\r\n\r\n // Build AgentComponent\r\n const component: AgentComponent<I, O> = {\r\n id: ast.props.id,\r\n inputSchema: ast.props.input,\r\n outputSchema: ast.props.output,\r\n buildPrompt,\r\n extractOutput,\r\n };\r\n\r\n // Add optional configurations\r\n if (validateOutput) {\r\n component.validateOutput = validateOutput;\r\n }\r\n\r\n if (retry) {\r\n component.retry = retry;\r\n }\r\n\r\n if (ast.props.loopValidator) {\r\n component.loopValidator = ast.props.loopValidator;\r\n }\r\n\r\n if (ast.props.loopConfig) {\r\n component.loopConfig = ast.props.loopConfig;\r\n }\r\n\r\n if (ast.props.tools) {\r\n component.tools = ast.props.tools;\r\n }\r\n\r\n return component;\r\n}\r\n","/**\r\n * Deity TSX - Result Compiler\r\n *\r\n * Compiles Result AST nodes into extractOutput function.\r\n */\r\n\r\nimport type { ResultNode } from '../ast/types.js';\r\nimport type { ExecutionContext, LLMLoopResult } from '../engine/types.js';\r\nimport type { ObserveFunction } from './compile-observe.js';\r\n\r\n/**\r\n * Compile Result node to extractOutput function\r\n *\r\n * @param resultNode - Result AST node\r\n * @param observeFunction - Optional observe function (if Observe node exists)\r\n * @returns extractOutput function\r\n */\r\nexport function compileResult<O = unknown>(\r\n resultNode: ResultNode<O>,\r\n observeFunction?: ObserveFunction\r\n) {\r\n if (!resultNode || resultNode.type !== 'Result') {\r\n throw new Error('Expected Result node');\r\n }\r\n\r\n const { extract } = resultNode.props;\r\n\r\n if (!extract) {\r\n throw new Error('Result node must have extract function');\r\n }\r\n\r\n return async (\r\n ctx: ExecutionContext,\r\n llmResult: LLMLoopResult\r\n ): Promise<O> => {\r\n // Run observation if present\r\n let observed: Record<string, unknown> = {};\r\n if (observeFunction) {\r\n observed = await observeFunction(llmResult);\r\n }\r\n\r\n // Extract output\r\n const output = await Promise.resolve(extract(ctx, llmResult, observed));\r\n\r\n return output;\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Validate Compiler\r\n *\r\n * Compiles Validate AST nodes into validateOutput function.\r\n */\r\n\r\nimport type { ValidateNode, ValidationRules } from '../ast/types.js';\r\nimport type { ExecutionContext, ValidationResult } from '../engine/types.js';\r\n\r\n/**\r\n * Compile Validate node to validateOutput function\r\n *\r\n * @param validateNode - Validate AST node\r\n * @returns validateOutput function\r\n */\r\nexport function compileValidate(validateNode: ValidateNode) {\r\n if (!validateNode || validateNode.type !== 'Validate') {\r\n throw new Error('Expected Validate node');\r\n }\r\n\r\n const { rules: rulesFunction } = validateNode.props;\r\n\r\n if (!rulesFunction) {\r\n throw new Error('Validate node must have rules function');\r\n }\r\n\r\n return async (\r\n output: unknown,\r\n ctx: ExecutionContext\r\n ): Promise<ValidationResult> => {\r\n // Note: We need access to observed data here\r\n // For now, we'll pass an empty object\r\n // In the full implementation, we'd need to refactor to pass observed data\r\n const observed: Record<string, unknown> = {};\r\n\r\n // Get validation rules\r\n const validationRules: ValidationRules = await Promise.resolve(\r\n rulesFunction(output, ctx, observed)\r\n );\r\n\r\n // Validate rules structure\r\n if (!validationRules.rules || !Array.isArray(validationRules.rules)) {\r\n throw new Error('Validate rules function must return {rules: [...]}');\r\n }\r\n\r\n // Execute rules\r\n const errors: string[] = [];\r\n\r\n for (const rule of validationRules.rules) {\r\n if (!rule.check) {\r\n errors.push(rule.error);\r\n }\r\n }\r\n\r\n // Return validation result\r\n if (errors.length > 0) {\r\n return {\r\n valid: false,\r\n errors,\r\n };\r\n }\r\n\r\n return { valid: true };\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Retry Compiler\r\n *\r\n * Compiles Retry AST nodes into retry configuration.\r\n */\r\n\r\nimport type { RetryNode } from '../ast/types.js';\r\nimport type { RetryConfig } from '../engine/types.js';\r\n\r\n/**\r\n * Compile Retry node to retry configuration\r\n *\r\n * @param retryNode - Retry AST node\r\n * @returns Retry configuration\r\n */\r\nexport function compileRetry(retryNode: RetryNode): RetryConfig {\r\n if (!retryNode || retryNode.type !== 'Retry') {\r\n throw new Error('Expected Retry node');\r\n }\r\n\r\n const {\r\n maxAttempts = 3,\r\n feedbackOnError = true,\r\n retryOnToolError = true,\r\n feedbackErrorToLLM = true,\r\n } = retryNode.props;\r\n\r\n return {\r\n maxAttempts,\r\n feedbackOnError,\r\n retryOnToolError,\r\n feedbackErrorToLLM,\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Compiler\r\n *\r\n * Export all compiler functions.\r\n */\r\n\r\nexport { compileAgent } from './compile-agent.js';\r\nexport { compilePrompt } from './compile-prompt.js';\r\nexport { compileObserve } from './compile-observe.js';\r\nexport { compileResult } from './compile-result.js';\r\nexport { compileValidate } from './compile-validate.js';\r\nexport { compileRetry } from './compile-retry.js';\r\n\r\n// Workflow compilers\r\nexport { compileWorkflow } from './compile-workflow.js';\r\nexport { compileWorkflowNode } from './compile-workflow-node.js';\r\n\r\nexport type { ObserveFunction } from './compile-observe.js';\r\n","/**\r\n * Deity TSX - Workflow Node Compiler\r\n *\r\n * Compiles workflow structure AST nodes into ExecutionNode instances.\r\n */\r\n\r\nimport type {\r\n WorkflowChildNode,\r\n WorkflowSequenceNode,\r\n WorkflowParallelNode,\r\n WorkflowConditionalNode,\r\n WorkflowLoopNode,\r\n WorkflowForEachNode,\r\n AgentNode,\r\n} from '../ast/types.js';\r\nimport type { ExecutionNode, AgentComponent } from '../engine/types.js';\r\nimport { compileAgent } from './compile-agent.js';\r\n\r\n/**\r\n * Compile a workflow child node (Agent or workflow structure) to ExecutionNode\r\n *\r\n * This is the main dispatcher that routes to the appropriate compiler.\r\n *\r\n * @param node - Workflow child node (Agent, Sequence, Parallel, Conditional, Loop, ForEach)\r\n * @returns ExecutionNode that can be executed by the runtime\r\n */\r\nexport function compileWorkflowNode(node: WorkflowChildNode): ExecutionNode {\r\n switch (node.type) {\r\n case 'Agent':\r\n return compileAgentNode(node as AgentNode);\r\n\r\n case 'WorkflowSequence':\r\n return compileSequenceNode(node as WorkflowSequenceNode);\r\n\r\n case 'WorkflowParallel':\r\n return compileParallelNode(node as WorkflowParallelNode);\r\n\r\n case 'WorkflowConditional':\r\n return compileConditionalNode(node as WorkflowConditionalNode);\r\n\r\n case 'WorkflowLoop':\r\n return compileLoopNode(node as WorkflowLoopNode);\r\n\r\n case 'WorkflowForEach':\r\n return compileForEachNode(node as WorkflowForEachNode);\r\n\r\n default:\r\n throw new Error(`Unknown workflow node type: ${(node as any).type}`);\r\n }\r\n}\r\n\r\n/**\r\n * Compile an Agent node to a step ExecutionNode\r\n *\r\n * Uses lazy compilation wrapper to defer agent compilation until first execution.\r\n */\r\nfunction compileAgentNode(node: AgentNode): ExecutionNode {\r\n // Create lazy agent component wrapper\r\n const lazyComponent = createLazyAgentComponent(node);\r\n\r\n return {\r\n type: 'step',\r\n component: lazyComponent,\r\n };\r\n}\r\n\r\n/**\r\n * Compile a Sequence node to a sequence ExecutionNode\r\n */\r\nfunction compileSequenceNode(node: WorkflowSequenceNode): ExecutionNode {\r\n if (!node.children || node.children.length === 0) {\r\n throw new Error('Sequence node must have children');\r\n }\r\n\r\n const children = node.children.map(child => compileWorkflowNode(child));\r\n\r\n return {\r\n type: 'sequence',\r\n children,\r\n };\r\n}\r\n\r\n/**\r\n * Compile a Parallel node to a parallel ExecutionNode\r\n */\r\nfunction compileParallelNode(node: WorkflowParallelNode): ExecutionNode {\r\n if (!node.children || node.children.length === 0) {\r\n throw new Error('Parallel node must have children');\r\n }\r\n\r\n const children = node.children.map(child => compileWorkflowNode(child));\r\n\r\n return {\r\n type: 'parallel',\r\n children,\r\n };\r\n}\r\n\r\n/**\r\n * Compile a Conditional node to a conditional ExecutionNode\r\n */\r\nfunction compileConditionalNode(node: WorkflowConditionalNode): ExecutionNode {\r\n if (!node.props?.condition) {\r\n throw new Error('Conditional node must have a condition function');\r\n }\r\n\r\n if (!node.children || node.children.length < 1 || node.children.length > 2) {\r\n throw new Error('Conditional node must have 1-2 children (true branch required, false branch optional)');\r\n }\r\n\r\n const children = node.children.map(child => compileWorkflowNode(child));\r\n\r\n return {\r\n type: 'conditional',\r\n condition: node.props.condition,\r\n children,\r\n };\r\n}\r\n\r\n/**\r\n * Compile a Loop node to a loop ExecutionNode\r\n */\r\nfunction compileLoopNode(node: WorkflowLoopNode): ExecutionNode {\r\n if (!node.props?.iterations || node.props.iterations < 1) {\r\n throw new Error('Loop node must have iterations >= 1');\r\n }\r\n\r\n if (!node.children || node.children.length !== 1) {\r\n throw new Error('Loop node must have exactly one child');\r\n }\r\n\r\n const child = compileWorkflowNode(node.children[0]);\r\n\r\n return {\r\n type: 'loop',\r\n maxIterations: node.props.iterations,\r\n children: [child],\r\n };\r\n}\r\n\r\n/**\r\n * Compile a ForEach node to a foreach ExecutionNode\r\n */\r\nfunction compileForEachNode(node: WorkflowForEachNode): ExecutionNode {\r\n if (!node.props?.items) {\r\n throw new Error('ForEach node must have items prop');\r\n }\r\n\r\n if (!node.children || node.children.length !== 1) {\r\n throw new Error('ForEach node must have exactly one child');\r\n }\r\n\r\n const child = compileWorkflowNode(node.children[0]);\r\n\r\n return {\r\n type: 'foreach',\r\n itemsAccessor: node.props.items,\r\n itemMode: node.props.itemMode as 'merge' | 'replace' | 'property',\r\n itemKey: node.props.itemKey,\r\n errorMode: node.props.errorMode as 'stop' | 'continue' | 'skip',\r\n collectResults: node.props.collectResults,\r\n children: [child],\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// Lazy Agent Component Wrapper\r\n// ============================================================================\r\n\r\n/**\r\n * Create a lazy agent component that defers compilation until first use\r\n *\r\n * This wrapper implements the AgentComponent interface but delays actual\r\n * compilation of the AgentNode until the first method call.\r\n *\r\n * Benefits:\r\n * - Faster workflow startup (no upfront compilation)\r\n * - Only compile agents that are actually executed\r\n * - Compilation result is cached for subsequent calls\r\n */\r\nfunction createLazyAgentComponent<I = unknown, O = unknown>(\r\n astNode: AgentNode<I, O>\r\n): AgentComponent<I, O> {\r\n let compiled: AgentComponent<I, O> | null = null;\r\n\r\n const ensureCompiled = (): AgentComponent<I, O> => {\r\n if (!compiled) {\r\n compiled = compileAgent(astNode);\r\n }\r\n return compiled;\r\n };\r\n\r\n // Return a proxy that implements AgentComponent interface\r\n const proxy: AgentComponent<I, O> = {\r\n get id() {\r\n return astNode.props.id;\r\n },\r\n get inputSchema() {\r\n return astNode.props.input;\r\n },\r\n get outputSchema() {\r\n return astNode.props.output;\r\n },\r\n get tools() {\r\n return astNode.props.tools;\r\n },\r\n get loopValidator() {\r\n return astNode.props.loopValidator;\r\n },\r\n get loopConfig() {\r\n return astNode.props.loopConfig;\r\n },\r\n\r\n // Lazy methods - compile on first call\r\n buildPrompt(ctx) {\r\n return ensureCompiled().buildPrompt(ctx);\r\n },\r\n get retry() {\r\n return ensureCompiled().retry;\r\n },\r\n get model() {\r\n return ensureCompiled().model;\r\n },\r\n };\r\n\r\n // Conditionally add extractOutput only if it will exist after compilation\r\n // This is determined by checking if the AST has a Result node\r\n const hasResultNode = astNode.children.some(child => child.type === 'Result');\r\n if (hasResultNode) {\r\n proxy.extractOutput = (ctx, llmResult) => {\r\n return ensureCompiled().extractOutput!(ctx, llmResult);\r\n };\r\n }\r\n\r\n // Conditionally add validateOutput only if it will exist after compilation\r\n // This is determined by checking if the AST has a Validate node\r\n const hasValidateNode = astNode.children.some(child => child.type === 'Validate');\r\n if (hasValidateNode) {\r\n proxy.validateOutput = (output, ctx) => {\r\n const comp = ensureCompiled();\r\n return comp.validateOutput!(output, ctx);\r\n };\r\n }\r\n\r\n return proxy;\r\n}\r\n","/**\r\n * Deity TSX - Workflow Compiler\r\n *\r\n * Compiles WorkflowNode AST into executable WorkflowConfig.\r\n */\r\n\r\nimport type { WorkflowNode } from '../ast/types.js';\r\nimport type { WorkflowConfig } from '../engine/types.js';\r\nimport { compileWorkflowNode } from './compile-workflow-node.js';\r\n\r\n/**\r\n * Compile Workflow AST to WorkflowConfig\r\n *\r\n * This is the main entry point for compiling a complete workflow.\r\n *\r\n * @param ast - Workflow AST node\r\n * @returns Executable WorkflowConfig that can be passed to runWorkflow()\r\n *\r\n * @example\r\n * ```typescript\r\n * const MyWorkflow = Workflow({\r\n * name: 'my-workflow',\r\n * defaultModel: { adapter: llmAdapter },\r\n * children: Sequence({\r\n * children: [Agent1, Agent2, Agent3]\r\n * })\r\n * });\r\n *\r\n * const config = compileWorkflow(MyWorkflow);\r\n * const result = await runWorkflow(config, inputs);\r\n * ```\r\n */\r\nexport function compileWorkflow(ast: WorkflowNode): WorkflowConfig {\r\n // Validate AST\r\n if (ast.type !== 'Workflow') {\r\n throw new Error(`Expected Workflow node, got ${ast.type}`);\r\n }\r\n\r\n if (!ast.children || ast.children.length !== 1) {\r\n throw new Error('Workflow must have exactly one child (workflow graph)');\r\n }\r\n\r\n // Extract props\r\n const { name, description, defaultModel, state, enhancements } = ast.props;\r\n\r\n if (!name) {\r\n throw new Error('Workflow must have a name');\r\n }\r\n\r\n // Compile the workflow graph\r\n const graph = compileWorkflowNode(ast.children[0]);\r\n\r\n // Build WorkflowConfig\r\n const config: WorkflowConfig = {\r\n name,\r\n graph,\r\n };\r\n\r\n // Add optional properties\r\n if (description) {\r\n config.description = description;\r\n }\r\n\r\n if (defaultModel) {\r\n config.defaultModel = defaultModel;\r\n }\r\n\r\n if (state) {\r\n config.state = state;\r\n }\r\n\r\n if (enhancements) {\r\n config.enhancements = enhancements as any; // Type assertion for WorkflowEnhancements\r\n }\r\n\r\n return config;\r\n}\r\n","/**\r\n * Deity TSX - AST Type Definitions\r\n *\r\n * This module defines the Abstract Syntax Tree (AST) node types for the TSX DSL.\r\n * All nodes are pure data structures (no runtime behavior).\r\n *\r\n * Design principles:\r\n * - Logic only as TS function values (never strings)\r\n * - Text only as text\r\n * - Structure only via TSX AST\r\n */\r\n\r\nimport type { ZodSchema } from 'zod';\r\nimport type { ExecutionContext, LLMLoopResult, Validator, ToolSpec } from '../engine/types.js';\r\n\r\n// ============================================================================\r\n// Base AST Node\r\n// ============================================================================\r\n\r\n/**\r\n * Base interface for all AST nodes\r\n */\r\nexport interface ASTNode {\r\n /** Node type identifier */\r\n type: string;\r\n\r\n /** Node properties (varies by node type) */\r\n props?: Record<string, unknown>;\r\n\r\n /** Child nodes */\r\n children?: ASTNode[];\r\n}\r\n\r\n// ============================================================================\r\n// Agent Node (Root)\r\n// ============================================================================\r\n\r\n/**\r\n * Agent Node - Root node of an agent definition\r\n *\r\n * Represents a complete AI agent with:\r\n * - Identity (id, description, tags)\r\n * - IO schemas (input/output)\r\n * - Behavior specification (Prompt, Observe, Result, Validate, Retry)\r\n */\r\nexport interface AgentNode<I = unknown, O = unknown> extends ASTNode {\r\n type: 'Agent';\r\n props: {\r\n /** Unique agent identifier */\r\n id: string;\r\n\r\n /** Input schema (Zod) */\r\n input: ZodSchema<I>;\r\n\r\n /** Output schema (Zod) */\r\n output: ZodSchema<O>;\r\n\r\n /** Optional description */\r\n description?: string;\r\n\r\n /** Optional tags for categorization */\r\n tags?: string[];\r\n\r\n /** Optional loop-level validator (validates during LLM loop) */\r\n loopValidator?: Validator;\r\n\r\n /** Optional LLM loop configuration */\r\n loopConfig?: {\r\n /** Maximum number of tool execution rounds */\r\n maxToolRounds?: number;\r\n /** Timeout in milliseconds */\r\n timeout?: number;\r\n };\r\n\r\n /** Optional tool definitions (static array) */\r\n tools?: ToolSpec[];\r\n };\r\n\r\n /** Child nodes (Prompt is required, others are optional) */\r\n children: (PromptNode | ObserveNode | ResultNode | ValidateNode | RetryNode | ToolsNode)[];\r\n}\r\n\r\n// ============================================================================\r\n// Prompt Nodes\r\n// ============================================================================\r\n\r\n/**\r\n * Prompt Node - Container for system and user prompts\r\n */\r\nexport interface PromptNode extends ASTNode {\r\n type: 'Prompt';\r\n children: (SystemNode | UserNode)[];\r\n}\r\n\r\n/**\r\n * System Prompt Node\r\n *\r\n * Can be loaded from:\r\n * - File (source: 'file:path/to/prompt.md')\r\n * - Inline (content: 'text')\r\n * - Computed (compute: (ctx) => string)\r\n * - Mixed template (templateParts: TemplatePart[]) - for ToolRef support\r\n */\r\nexport interface SystemNode extends ASTNode {\r\n type: 'System';\r\n props: {\r\n /** File source (e.g., 'file:./prompts/system.md') */\r\n source?: string;\r\n\r\n /** Is this prompt required? (fail-fast if missing) */\r\n required?: boolean;\r\n\r\n /** Inline content */\r\n content?: string;\r\n\r\n /** Computed content (function) */\r\n compute?: (ctx: ExecutionContext) => string | Promise<string>;\r\n\r\n /** Template parts (for mixed text/computed/toolref content) */\r\n templateParts?: TemplatePart[];\r\n };\r\n}\r\n\r\n/**\r\n * User Prompt Node\r\n *\r\n * Can be:\r\n * - Inline (content: 'text')\r\n * - Computed (compute: (ctx) => string)\r\n * - Mixed template (templateParts: TemplatePart[]) - for ToolRef support\r\n */\r\nexport interface UserNode extends ASTNode {\r\n type: 'User';\r\n props: {\r\n /** Inline content */\r\n content?: string;\r\n\r\n /** Computed content (function) */\r\n compute?: (ctx: ExecutionContext) => string | Promise<string>;\r\n\r\n /** Template parts (for mixed text/computed/toolref content) */\r\n templateParts?: TemplatePart[];\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// ToolRef Node\r\n// ============================================================================\r\n\r\n/**\r\n * Template Part - Single part of a mixed-content template\r\n *\r\n * Used by System and User nodes to support inline ToolRef nodes.\r\n */\r\nexport type TemplatePart =\r\n | { kind: 'text'; value: string }\r\n | { kind: 'computed'; compute: (ctx: ExecutionContext) => string | Promise<string> }\r\n | { kind: 'toolref'; toolName: string };\r\n\r\n/**\r\n * ToolRef Node - Reference to a tool name in prompt text\r\n *\r\n * This node acts as a placeholder that gets replaced with the tool's\r\n * runtime ID during prompt compilation.\r\n *\r\n * @example\r\n * ```tsx\r\n * <User>Use <ToolRef tool={MemoryStore} /> to save data.</User>\r\n * // Compiles to: \"Use memory_store to save data.\"\r\n * ```\r\n */\r\nexport interface ToolRefNode extends ASTNode {\r\n type: 'ToolRef';\r\n props: {\r\n /** The tool's runtime ID (e.g., 'memory_store') */\r\n toolName: string;\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// Observe Node\r\n// ============================================================================\r\n\r\n/**\r\n * Observe Node - Declarative observation of LLM execution\r\n *\r\n * Used to extract statistics and metadata from LLM loop results:\r\n * - Tool call counts\r\n * - Success/failure rates\r\n * - Custom metrics\r\n *\r\n * The observed data is passed to Result and Validate nodes.\r\n */\r\nexport interface ObserveNode extends ASTNode {\r\n type: 'Observe';\r\n props: {\r\n /**\r\n * Compute function to extract observations\r\n *\r\n * Must return a plain object with observed values.\r\n * Do NOT mutate llmResult.\r\n */\r\n compute: (llmResult: LLMLoopResult) => Record<string, unknown> | Promise<Record<string, unknown>>;\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// Result Node\r\n// ============================================================================\r\n\r\n/**\r\n * Result Node - Extract structured output from LLM execution\r\n *\r\n * This node is responsible for:\r\n * - Extracting output from llmResult (e.g., tool call arguments)\r\n * - Using observed data from Observe node\r\n * - Returning data that conforms to output schema\r\n */\r\nexport interface ResultNode<O = unknown> extends ASTNode {\r\n type: 'Result';\r\n props: {\r\n /**\r\n * Extract function to produce output\r\n *\r\n * @param ctx - Execution context with inputs\r\n * @param llmResult - Complete LLM loop result\r\n * @param observed - Data from Observe node (if present)\r\n * @returns Output data (must conform to output schema)\r\n */\r\n extract: (\r\n ctx: ExecutionContext,\r\n llmResult: LLMLoopResult,\r\n observed: Record<string, unknown>\r\n ) => O | Promise<O>;\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// Validate Node\r\n// ============================================================================\r\n\r\n/**\r\n * Validation Rule\r\n *\r\n * A single validation rule with:\r\n * - check: boolean condition\r\n * - error: error message if check fails\r\n * - level: severity (error or warning)\r\n */\r\nexport interface ValidationRule {\r\n /** Condition to check (true = pass, false = fail) */\r\n check: boolean;\r\n\r\n /** Error message (shown when check fails) */\r\n error: string;\r\n\r\n /** Severity level (default: 'error') */\r\n level?: 'error' | 'warning';\r\n}\r\n\r\n/**\r\n * Validation Rules - Collection of rules\r\n */\r\nexport interface ValidationRules {\r\n rules: ValidationRule[];\r\n}\r\n\r\n/**\r\n * Validate Node - Declarative validation rules\r\n *\r\n * Used to validate output against business rules.\r\n * Returns structured errors for consistent handling.\r\n */\r\nexport interface ValidateNode extends ASTNode {\r\n type: 'Validate';\r\n props: {\r\n /**\r\n * Rules function to generate validation rules\r\n *\r\n * @param output - Extracted output from Result node\r\n * @param ctx - Execution context\r\n * @param observed - Data from Observe node (if present)\r\n * @returns Validation rules\r\n */\r\n rules: (\r\n output: unknown,\r\n ctx: ExecutionContext,\r\n observed: Record<string, unknown>\r\n ) => ValidationRules | Promise<ValidationRules>;\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// Retry Node\r\n// ============================================================================\r\n\r\n/**\r\n * Retry Node - Retry policy configuration\r\n *\r\n * Specifies how the agent should retry on validation failures.\r\n */\r\nexport interface RetryNode extends ASTNode {\r\n type: 'Retry';\r\n props: {\r\n /** Maximum retry attempts (default: 3) */\r\n maxAttempts?: number;\r\n\r\n /** Include validation errors in retry prompt (default: true) */\r\n feedbackOnError?: boolean;\r\n\r\n /** Retry on tool execution errors (default: true) */\r\n retryOnToolError?: boolean;\r\n\r\n /** Send tool errors to LLM for correction (default: true) */\r\n feedbackErrorToLLM?: boolean;\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// Tools Nodes\r\n// ============================================================================\r\n\r\n/**\r\n * Tools Container Node - Groups tool definitions for an agent\r\n *\r\n * Contains static tool definitions via <ToolDef> or <Tool> children.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Tools>\r\n * <MemoryStore />\r\n * <MemoryRecall />\r\n * <Tool name=\"my_tool\" description=\"...\" input={Schema}>\r\n * {async (params) => ({ ... })}\r\n * </Tool>\r\n * </Tools>\r\n * ```\r\n */\r\nexport interface ToolsNode extends ASTNode {\r\n type: 'Tools';\r\n props: Record<string, never>;\r\n /** Child ToolDef nodes */\r\n children: ToolDefNode[];\r\n}\r\n\r\n/**\r\n * Tool Definition Node - Wraps a single Tool object\r\n *\r\n * @example\r\n * ```tsx\r\n * <ToolDef tool={createFileListTool(context)} />\r\n * ```\r\n */\r\nexport interface ToolDefNode extends ASTNode {\r\n type: 'Tools:Def';\r\n props: {\r\n /** The tool object */\r\n tool: ToolSpec;\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// Type Guards\r\n// ============================================================================\r\n\r\n/**\r\n * Check if a node is an AgentNode\r\n */\r\nexport function isAgentNode(node: ASTNode): node is AgentNode {\r\n return node.type === 'Agent';\r\n}\r\n\r\n/**\r\n * Check if a node is a PromptNode\r\n */\r\nexport function isPromptNode(node: ASTNode): node is PromptNode {\r\n return node.type === 'Prompt';\r\n}\r\n\r\n/**\r\n * Check if a node is a SystemNode\r\n */\r\nexport function isSystemNode(node: ASTNode): node is SystemNode {\r\n return node.type === 'System';\r\n}\r\n\r\n/**\r\n * Check if a node is a UserNode\r\n */\r\nexport function isUserNode(node: ASTNode): node is UserNode {\r\n return node.type === 'User';\r\n}\r\n\r\n/**\r\n * Check if a node is an ObserveNode\r\n */\r\nexport function isObserveNode(node: ASTNode): node is ObserveNode {\r\n return node.type === 'Observe';\r\n}\r\n\r\n/**\r\n * Check if a node is a ResultNode\r\n */\r\nexport function isResultNode(node: ASTNode): node is ResultNode {\r\n return node.type === 'Result';\r\n}\r\n\r\n/**\r\n * Check if a node is a ValidateNode\r\n */\r\nexport function isValidateNode(node: ASTNode): node is ValidateNode {\r\n return node.type === 'Validate';\r\n}\r\n\r\n/**\r\n * Check if a node is a RetryNode\r\n */\r\nexport function isRetryNode(node: ASTNode): node is RetryNode {\r\n return node.type === 'Retry';\r\n}\r\n\r\n/**\r\n * Check if a node is a ToolsNode\r\n */\r\nexport function isToolsNode(node: ASTNode): node is ToolsNode {\r\n return node.type === 'Tools';\r\n}\r\n\r\n/**\r\n * Check if a node is a ToolDefNode\r\n */\r\nexport function isToolDefNode(node: ASTNode): node is ToolDefNode {\r\n return node.type === 'Tools:Def';\r\n}\r\n\r\n/**\r\n * Check if a node is a ToolRefNode\r\n */\r\nexport function isToolRefNode(node: ASTNode): node is ToolRefNode {\r\n return node.type === 'ToolRef';\r\n}\r\n\r\n// ============================================================================\r\n// Helper Types\r\n// ============================================================================\r\n\r\n/**\r\n * Extract input type from AgentNode\r\n */\r\nexport type AgentInput<T extends AgentNode<any, any>> = T extends AgentNode<infer I, any> ? I : never;\r\n\r\n/**\r\n * Extract output type from AgentNode\r\n */\r\nexport type AgentOutput<T extends AgentNode<any, any>> = T extends AgentNode<any, infer O> ? O : never;\r\n\r\n// ============================================================================\r\n// Workflow Nodes\r\n// ============================================================================\r\n\r\n/**\r\n * Workflow Sequence Node - Execute children in order\r\n */\r\nexport interface WorkflowSequenceNode extends ASTNode {\r\n type: 'WorkflowSequence';\r\n children: WorkflowChildNode[];\r\n}\r\n\r\n/**\r\n * Workflow Parallel Node - Execute children concurrently\r\n */\r\nexport interface WorkflowParallelNode extends ASTNode {\r\n type: 'WorkflowParallel';\r\n children: WorkflowChildNode[];\r\n}\r\n\r\n/**\r\n * Workflow Conditional Node - Execute children based on condition\r\n */\r\nexport interface WorkflowConditionalNode extends ASTNode {\r\n type: 'WorkflowConditional';\r\n props: {\r\n /** Condition function (true = first child, false = second child) */\r\n condition: (ctx: ExecutionContext) => boolean | Promise<boolean>;\r\n };\r\n children: [WorkflowChildNode] | [WorkflowChildNode, WorkflowChildNode];\r\n}\r\n\r\n/**\r\n * Workflow Loop Node - Execute child N times\r\n */\r\nexport interface WorkflowLoopNode extends ASTNode {\r\n type: 'WorkflowLoop';\r\n props: {\r\n /** Number of iterations */\r\n iterations: number;\r\n };\r\n children: [WorkflowChildNode];\r\n}\r\n\r\n/**\r\n * Workflow ForEach Node - Execute child for each item in array\r\n */\r\nexport interface WorkflowForEachNode extends ASTNode {\r\n type: 'WorkflowForEach';\r\n props: {\r\n /** Array of items or function to resolve items */\r\n items: unknown[] | ((ctx: ExecutionContext) => unknown[] | Promise<unknown[]>);\r\n /** How to inject item into context ('property' | 'merge' | 'replace') */\r\n itemMode: string;\r\n /** Property key for 'property' mode */\r\n itemKey: string;\r\n /** Error handling mode ('stop' | 'continue' | 'skip') */\r\n errorMode: string;\r\n /** Whether to collect results */\r\n collectResults: boolean;\r\n };\r\n children: [WorkflowChildNode];\r\n}\r\n\r\n/**\r\n * Union type for workflow child nodes\r\n * Can be either an Agent or a workflow structure node\r\n */\r\nexport type WorkflowChildNode =\r\n | AgentNode\r\n | WorkflowSequenceNode\r\n | WorkflowParallelNode\r\n | WorkflowConditionalNode\r\n | WorkflowLoopNode\r\n | WorkflowForEachNode;\r\n\r\n// ============================================================================\r\n// Workflow Type Guards\r\n// ============================================================================\r\n\r\n/**\r\n * Check if a node is a WorkflowSequenceNode\r\n */\r\nexport function isWorkflowSequenceNode(node: ASTNode): node is WorkflowSequenceNode {\r\n return node.type === 'WorkflowSequence';\r\n}\r\n\r\n/**\r\n * Check if a node is a WorkflowParallelNode\r\n */\r\nexport function isWorkflowParallelNode(node: ASTNode): node is WorkflowParallelNode {\r\n return node.type === 'WorkflowParallel';\r\n}\r\n\r\n/**\r\n * Check if a node is a WorkflowConditionalNode\r\n */\r\nexport function isWorkflowConditionalNode(node: ASTNode): node is WorkflowConditionalNode {\r\n return node.type === 'WorkflowConditional';\r\n}\r\n\r\n/**\r\n * Check if a node is a WorkflowLoopNode\r\n */\r\nexport function isWorkflowLoopNode(node: ASTNode): node is WorkflowLoopNode {\r\n return node.type === 'WorkflowLoop';\r\n}\r\n\r\n/**\r\n * Check if a node is a WorkflowForEachNode\r\n */\r\nexport function isWorkflowForEachNode(node: ASTNode): node is WorkflowForEachNode {\r\n return node.type === 'WorkflowForEach';\r\n}\r\n\r\n// ============================================================================\r\n// Workflow Container Node\r\n// ============================================================================\r\n\r\n/**\r\n * Workflow Node - Top-level workflow container\r\n *\r\n * Contains the complete workflow configuration including:\r\n * - Name and description\r\n * - Default model configuration\r\n * - Workflow graph (Sequence, Parallel, Conditional, Loop, or Agent)\r\n * - Optional enhancements (conversation, memory, session, UI)\r\n */\r\nexport interface WorkflowNode extends ASTNode {\r\n type: 'Workflow';\r\n props: {\r\n /** Workflow name */\r\n name: string;\r\n\r\n /** Optional description */\r\n description?: string;\r\n\r\n /** Default LLM model configuration */\r\n defaultModel?: {\r\n adapter: any; // LLMAdapter type from engine/types.ts\r\n config?: any; // GenerationConfig type from engine/types.ts\r\n };\r\n\r\n /** Optional state storage */\r\n state?: {\r\n store: any; // StateStore type from engine/types.ts\r\n };\r\n\r\n /** Optional enhancements */\r\n enhancements?: {\r\n /** Conversation management */\r\n conversation?: {\r\n maxTokens: number;\r\n pruneThreshold: number;\r\n messageRetentionPolicy?: unknown;\r\n };\r\n\r\n /** Memory management */\r\n memory?: {\r\n coreBudget: {\r\n maxItems: number;\r\n maxTotalSize: number;\r\n };\r\n detailedBudget?: {\r\n maxItems: number;\r\n maxTotalSize: number;\r\n };\r\n };\r\n\r\n /** Session persistence */\r\n session?: {\r\n directory: string;\r\n autoSave?: boolean;\r\n };\r\n\r\n /** UI updates */\r\n ui?: any; // UIUpdateBridge type\r\n\r\n /** Application state store (isolated from AI memory) */\r\n appState?: any; // StateStore type\r\n };\r\n };\r\n\r\n /** Single child representing the workflow graph */\r\n children: [WorkflowChildNode];\r\n}\r\n\r\n/**\r\n * Check if a node is a WorkflowNode\r\n */\r\nexport function isWorkflowNode(node: ASTNode): node is WorkflowNode {\r\n return node.type === 'Workflow';\r\n}\r\n","/**\r\n * Deity TSX - Observe Utilities\r\n *\r\n * Helper functions for building Observe nodes.\r\n * Provides common patterns for extracting statistics from LLM results.\r\n *\r\n * Design principles:\r\n * - Pure functions (no side effects)\r\n * - Composable utilities\r\n * - Type-safe\r\n * - Reusable patterns\r\n */\r\n\r\nimport type { LLMLoopResult } from '../engine/types.js';\r\n\r\n/**\r\n * Tool Call Filter\r\n *\r\n * Function to filter tool calls\r\n */\r\nexport type ToolCallFilter = (toolCall: any) => boolean;\r\n\r\n/**\r\n * Observe Utilities\r\n *\r\n * Collection of helper functions for common observation patterns.\r\n */\r\nexport class ObserveUtils {\r\n /**\r\n * Count total tool calls\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * totalCalls: ObserveUtils.countToolCalls(llmResult),\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\n static countToolCalls(llmResult: LLMLoopResult): number {\r\n return llmResult.response.toolCalls?.length ?? 0;\r\n }\r\n\r\n /**\r\n * Count tool calls by name\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * planningCalls: ObserveUtils.countToolCallsByName(\r\n * llmResult,\r\n * 'planning_create'\r\n * ),\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\n static countToolCallsByName(llmResult: LLMLoopResult, name: string): number {\r\n return llmResult.response.toolCalls?.filter(tc => tc.name === name).length ?? 0;\r\n }\r\n\r\n /**\r\n * Count tool calls matching filter\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * successfulCalls: ObserveUtils.countToolCallsWhere(\r\n * llmResult,\r\n * tc => tc.result?.success === true\r\n * ),\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\n static countToolCallsWhere(\r\n llmResult: LLMLoopResult,\r\n filter: ToolCallFilter\r\n ): number {\r\n return llmResult.response.toolCalls?.filter(filter).length ?? 0;\r\n }\r\n\r\n /**\r\n * Get list of unique tool names called\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * toolsUsed: ObserveUtils.getToolNames(llmResult),\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\n static getToolNames(llmResult: LLMLoopResult): string[] {\r\n const names = llmResult.response.toolCalls?.map(tc => tc.name) ?? [];\r\n return Array.from(new Set(names));\r\n }\r\n\r\n /**\r\n * Count occurrences of each tool\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * toolFrequency: ObserveUtils.getToolFrequency(llmResult),\r\n * // Result: { file_read: 5, memory_store: 3, ... }\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\n static getToolFrequency(llmResult: LLMLoopResult): Record<string, number> {\r\n const frequency: Record<string, number> = {};\r\n\r\n for (const tc of llmResult.response.toolCalls ?? []) {\r\n frequency[tc.name] = (frequency[tc.name] || 0) + 1;\r\n }\r\n\r\n return frequency;\r\n }\r\n\r\n /**\r\n * Check if specific tool was called\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * usedPlanning: ObserveUtils.hasToolCall(llmResult, 'planning_create'),\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\n static hasToolCall(llmResult: LLMLoopResult, name: string): boolean {\r\n return llmResult.response.toolCalls?.some(tc => tc.name === name) ?? false;\r\n }\r\n\r\n /**\r\n * Check if any tool matching filter was called\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * hasErrors: ObserveUtils.hasToolCallWhere(\r\n * llmResult,\r\n * tc => tc.error !== undefined\r\n * ),\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\n static hasToolCallWhere(\r\n llmResult: LLMLoopResult,\r\n filter: ToolCallFilter\r\n ): boolean {\r\n return llmResult.response.toolCalls?.some(filter) ?? false;\r\n }\r\n\r\n /**\r\n * Get content length\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * responseLength: ObserveUtils.getContentLength(llmResult),\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\n static getContentLength(llmResult: LLMLoopResult): number {\r\n return llmResult.response.content?.length ?? 0;\r\n }\r\n\r\n /**\r\n * Count successful tool calls\r\n *\r\n * Note: Since ToolCall type only has id/name/arguments, we consider\r\n * a call \"successful\" if it has valid arguments (not an error indicator).\r\n * For more sophisticated success tracking, use custom observers.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * successCount: ObserveUtils.countSuccessfulCalls(llmResult),\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\n static countSuccessfulCalls(llmResult: LLMLoopResult): number {\r\n // Since we don't have result/error info in ToolCall type,\r\n // we count all tool calls that have arguments\r\n return llmResult.response.toolCalls?.filter(tc => tc.arguments).length ?? 0;\r\n }\r\n\r\n /**\r\n * Count failed tool calls\r\n *\r\n * Note: Since ToolCall type only has id/name/arguments, we cannot\r\n * determine failures. This returns 0 for compatibility.\r\n * For error tracking, use custom observers or check messages array.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * failureCount: ObserveUtils.countFailedCalls(llmResult),\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\n static countFailedCalls(_llmResult: LLMLoopResult): number {\r\n // ToolCall type doesn't include error information\r\n // Return 0 for compatibility\r\n return 0;\r\n }\r\n\r\n /**\r\n * Get tool call arguments\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => {\r\n * const args = ObserveUtils.getToolArguments(\r\n * llmResult,\r\n * 'planning_create'\r\n * );\r\n * return {\r\n * taskCount: args?.[0]?.tasks?.length ?? 0,\r\n * };\r\n * }}\r\n * </Observe>\r\n * ```\r\n */\r\n static getToolArguments(\r\n llmResult: LLMLoopResult,\r\n name: string\r\n ): any[] {\r\n return llmResult.response.toolCalls\r\n ?.filter((tc: any) => tc.name === name)\r\n .map((tc: any) => {\r\n if (typeof tc.arguments === 'string') {\r\n try {\r\n return JSON.parse(tc.arguments);\r\n } catch {\r\n return tc.arguments;\r\n }\r\n }\r\n return tc.arguments;\r\n }) ?? [];\r\n }\r\n\r\n /**\r\n * Get first tool call matching name\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => {\r\n * const planCall = ObserveUtils.findToolCall(\r\n * llmResult,\r\n * 'planning_create'\r\n * );\r\n * return {\r\n * hasPlan: planCall !== null,\r\n * };\r\n * }}\r\n * </Observe>\r\n * ```\r\n */\r\n static findToolCall(\r\n llmResult: LLMLoopResult,\r\n name: string\r\n ): any | null {\r\n return llmResult.response.toolCalls?.find((tc: any) => tc.name === name) ?? null;\r\n }\r\n\r\n /**\r\n * Get all tool calls matching filter\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => {\r\n * const readCalls = ObserveUtils.filterToolCalls(\r\n * llmResult,\r\n * tc => tc.name.startsWith('file_')\r\n * );\r\n * return {\r\n * fileOpsCount: readCalls.length,\r\n * };\r\n * }}\r\n * </Observe>\r\n * ```\r\n */\r\n static filterToolCalls(\r\n llmResult: LLMLoopResult,\r\n filter: ToolCallFilter\r\n ): any[] {\r\n return llmResult.response.toolCalls?.filter(filter) ?? [];\r\n }\r\n\r\n /**\r\n * Check if content contains text\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * mentionedError: ObserveUtils.contentContains(llmResult, 'error'),\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\n static contentContains(llmResult: LLMLoopResult, text: string): boolean {\r\n return llmResult.response.content?.includes(text) ?? false;\r\n }\r\n\r\n /**\r\n * Check if content matches regex\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * hasCodeBlock: ObserveUtils.contentMatches(llmResult, /```[\\s\\S]*```/),\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\n static contentMatches(llmResult: LLMLoopResult, regex: RegExp): boolean {\r\n return regex.test(llmResult.response.content ?? '');\r\n }\r\n\r\n /**\r\n * Calculate success rate\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * successRate: ObserveUtils.getSuccessRate(llmResult),\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\n static getSuccessRate(llmResult: LLMLoopResult): number {\r\n const total = this.countToolCalls(llmResult);\r\n if (total === 0) return 0;\r\n\r\n const successful = this.countSuccessfulCalls(llmResult);\r\n return successful / total;\r\n }\r\n}\r\n\r\n/**\r\n * Create common observation patterns\r\n */\r\nexport const observe = {\r\n /**\r\n * Basic statistics\r\n */\r\n basicStats: (llmResult: LLMLoopResult) => ({\r\n totalToolCalls: ObserveUtils.countToolCalls(llmResult),\r\n uniqueTools: ObserveUtils.getToolNames(llmResult).length,\r\n contentLength: ObserveUtils.getContentLength(llmResult),\r\n successRate: ObserveUtils.getSuccessRate(llmResult),\r\n }),\r\n\r\n /**\r\n * Tool call statistics\r\n */\r\n toolStats: (llmResult: LLMLoopResult) => ({\r\n toolCalls: ObserveUtils.countToolCalls(llmResult),\r\n toolFrequency: ObserveUtils.getToolFrequency(llmResult),\r\n toolNames: ObserveUtils.getToolNames(llmResult),\r\n successfulCalls: ObserveUtils.countSuccessfulCalls(llmResult),\r\n failedCalls: ObserveUtils.countFailedCalls(llmResult),\r\n }),\r\n\r\n /**\r\n * Success/failure tracking\r\n */\r\n successTracking: (llmResult: LLMLoopResult) => ({\r\n successful: ObserveUtils.countSuccessfulCalls(llmResult),\r\n failed: ObserveUtils.countFailedCalls(llmResult),\r\n successRate: ObserveUtils.getSuccessRate(llmResult),\r\n hasErrors: ObserveUtils.countFailedCalls(llmResult) > 0,\r\n }),\r\n};\r\n\r\n/**\r\n * Create tool-specific observer\r\n *\r\n * @example\r\n * ```tsx\r\n * const observePlanning = createToolObserver('planning_create');\r\n *\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * ...observePlanning(llmResult),\r\n * // Returns: { called: true, count: 2, arguments: [...] }\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\nexport function createToolObserver(toolName: string) {\r\n return (llmResult: LLMLoopResult) => ({\r\n called: ObserveUtils.hasToolCall(llmResult, toolName),\r\n count: ObserveUtils.countToolCallsByName(llmResult, toolName),\r\n arguments: ObserveUtils.getToolArguments(llmResult, toolName),\r\n firstCall: ObserveUtils.findToolCall(llmResult, toolName),\r\n });\r\n}\r\n\r\n/**\r\n * Create pattern observer\r\n *\r\n * @example\r\n * ```tsx\r\n * const observeFileOps = createPatternObserver(\r\n * tc => tc.name.startsWith('file_')\r\n * );\r\n *\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * fileOps: observeFileOps(llmResult),\r\n * // Returns: { count: 5, calls: [...] }\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\nexport function createPatternObserver(filter: ToolCallFilter) {\r\n return (llmResult: LLMLoopResult) => ({\r\n count: ObserveUtils.countToolCallsWhere(llmResult, filter),\r\n calls: ObserveUtils.filterToolCalls(llmResult, filter),\r\n hasMatches: ObserveUtils.hasToolCallWhere(llmResult, filter),\r\n });\r\n}\r\n","/**\r\n * Deity TSX - Result Utilities\r\n *\r\n * Helper functions for building Result nodes.\r\n * Provides common patterns for extracting and transforming LLM output.\r\n *\r\n * Design principles:\r\n * - Pure functions (no side effects)\r\n * - Type-safe transformations\r\n * - Composable utilities\r\n * - Schema-driven validation\r\n */\r\n\r\nimport type { LLMLoopResult } from '../engine/types.js';\r\nimport { z } from 'zod';\r\n\r\n/**\r\n * Result extraction error\r\n */\r\nexport class ResultExtractionError extends Error {\r\n constructor(\r\n message: string,\r\n public readonly context?: {\r\n content?: string;\r\n toolCalls?: any[];\r\n attemptedParsers?: string[];\r\n }\r\n ) {\r\n super(message);\r\n this.name = 'ResultExtractionError';\r\n }\r\n}\r\n\r\n/**\r\n * Result Utils\r\n *\r\n * Collection of helper functions for common result extraction patterns.\r\n */\r\nexport class ResultUtils {\r\n /**\r\n * Extract JSON from LLM content\r\n *\r\n * Looks for JSON in code blocks or raw JSON in the content.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Result>\r\n * {(ctx, llmResult) => {\r\n * const data = ResultUtils.extractJSON(llmResult);\r\n * return { result: data };\r\n * }}\r\n * </Result>\r\n * ```\r\n */\r\n static extractJSON<T = any>(llmResult: LLMLoopResult): T {\r\n const content = llmResult.response.content || '';\r\n\r\n // Try to find JSON in code blocks\r\n const codeBlockMatch = content.match(/```(?:json)?\\s*([\\s\\S]*?)\\s*```/);\r\n if (codeBlockMatch) {\r\n try {\r\n return JSON.parse(codeBlockMatch[1]);\r\n } catch (error) {\r\n throw new ResultExtractionError('Failed to parse JSON from code block', {\r\n content: codeBlockMatch[1],\r\n attemptedParsers: ['code-block'],\r\n });\r\n }\r\n }\r\n\r\n // Try to parse the entire content as JSON\r\n try {\r\n return JSON.parse(content);\r\n } catch (error) {\r\n throw new ResultExtractionError('Failed to parse content as JSON', {\r\n content,\r\n attemptedParsers: ['code-block', 'raw'],\r\n });\r\n }\r\n }\r\n\r\n /**\r\n * Extract JSON with Zod schema validation\r\n *\r\n * @example\r\n * ```tsx\r\n * const OutputSchema = z.object({\r\n * summary: z.string(),\r\n * items: z.array(z.string()),\r\n * });\r\n *\r\n * <Result>\r\n * {(ctx, llmResult) => {\r\n * const data = ResultUtils.extractWithSchema(llmResult, OutputSchema);\r\n * return data;\r\n * }}\r\n * </Result>\r\n * ```\r\n */\r\n static extractWithSchema<T extends z.ZodType>(\r\n llmResult: LLMLoopResult,\r\n schema: T\r\n ): z.infer<T> {\r\n const json = this.extractJSON(llmResult);\r\n\r\n try {\r\n return schema.parse(json);\r\n } catch (error) {\r\n if (error instanceof z.ZodError) {\r\n throw new ResultExtractionError('Schema validation failed', {\r\n content: JSON.stringify(json),\r\n attemptedParsers: ['schema-validation'],\r\n });\r\n }\r\n throw error;\r\n }\r\n }\r\n\r\n /**\r\n * Extract from specific tool call result\r\n *\r\n * @example\r\n * ```tsx\r\n * <Result>\r\n * {(ctx, llmResult) => {\r\n * const planData = ResultUtils.extractFromToolCall(\r\n * llmResult,\r\n * 'planning_create'\r\n * );\r\n * return { plan: planData };\r\n * }}\r\n * </Result>\r\n * ```\r\n */\r\n static extractFromToolCall(llmResult: LLMLoopResult, toolName: string): any {\r\n const toolCall = llmResult.response.toolCalls?.find(tc => tc.name === toolName);\r\n\r\n if (!toolCall) {\r\n throw new ResultExtractionError(`Tool call not found: ${toolName}`, {\r\n toolCalls: llmResult.response.toolCalls,\r\n });\r\n }\r\n\r\n // Return the arguments\r\n if (toolCall.arguments) {\r\n if (typeof toolCall.arguments === 'string') {\r\n try {\r\n return JSON.parse(toolCall.arguments);\r\n } catch {\r\n return toolCall.arguments;\r\n }\r\n }\r\n return toolCall.arguments;\r\n }\r\n\r\n throw new ResultExtractionError(`Tool call has no result or arguments: ${toolName}`, {\r\n toolCalls: [toolCall],\r\n });\r\n }\r\n\r\n /**\r\n * Extract text content (no JSON parsing)\r\n *\r\n * @example\r\n * ```tsx\r\n * <Result>\r\n * {(ctx, llmResult) => ({\r\n * summary: ResultUtils.extractText(llmResult),\r\n * })}\r\n * </Result>\r\n * ```\r\n */\r\n static extractText(llmResult: LLMLoopResult): string {\r\n return llmResult.response.content || '';\r\n }\r\n\r\n /**\r\n * Extract code block by language\r\n *\r\n * @example\r\n * ```tsx\r\n * <Result>\r\n * {(ctx, llmResult) => ({\r\n * code: ResultUtils.extractCodeBlock(llmResult, 'typescript'),\r\n * })}\r\n * </Result>\r\n * ```\r\n */\r\n static extractCodeBlock(llmResult: LLMLoopResult, language?: string): string {\r\n const content = llmResult.response.content || '';\r\n const pattern = language\r\n ? new RegExp(`\\`\\`\\`${language}\\\\s*([\\\\s\\\\S]*?)\\\\s*\\`\\`\\``)\r\n : /```(?:\\w+)?\\s*([\\s\\S]*?)\\s*```/;\r\n\r\n const match = content.match(pattern);\r\n if (!match) {\r\n throw new ResultExtractionError(\r\n language ? `No ${language} code block found` : 'No code block found',\r\n { content }\r\n );\r\n }\r\n\r\n return match[1];\r\n }\r\n\r\n /**\r\n * Extract all code blocks\r\n *\r\n * @example\r\n * ```tsx\r\n * <Result>\r\n * {(ctx, llmResult) => ({\r\n * codeBlocks: ResultUtils.extractAllCodeBlocks(llmResult),\r\n * })}\r\n * </Result>\r\n * ```\r\n */\r\n static extractAllCodeBlocks(llmResult: LLMLoopResult): Array<{\r\n language: string | null;\r\n code: string;\r\n }> {\r\n const content = llmResult.response.content || '';\r\n const pattern = /```(\\w+)?\\s*([\\s\\S]*?)\\s*```/g;\r\n const blocks: Array<{ language: string | null; code: string }> = [];\r\n\r\n let match;\r\n while ((match = pattern.exec(content)) !== null) {\r\n blocks.push({\r\n language: match[1] || null,\r\n code: match[2],\r\n });\r\n }\r\n\r\n return blocks;\r\n }\r\n\r\n /**\r\n * Try multiple extraction strategies\r\n *\r\n * @example\r\n * ```tsx\r\n * <Result>\r\n * {(ctx, llmResult) => {\r\n * const data = ResultUtils.tryExtract(llmResult, [\r\n * (result) => ResultUtils.extractJSON(result),\r\n * (result) => ({ fallback: ResultUtils.extractText(result) }),\r\n * ]);\r\n * return data;\r\n * }}\r\n * </Result>\r\n * ```\r\n */\r\n static tryExtract<T = any>(\r\n llmResult: LLMLoopResult,\r\n extractors: Array<(result: LLMLoopResult) => T>\r\n ): T {\r\n const errors: Error[] = [];\r\n\r\n for (const extractor of extractors) {\r\n try {\r\n return extractor(llmResult);\r\n } catch (error) {\r\n errors.push(error as Error);\r\n }\r\n }\r\n\r\n throw new ResultExtractionError('All extraction strategies failed', {\r\n content: llmResult.response.content,\r\n attemptedParsers: errors.map(e => e.message),\r\n });\r\n }\r\n\r\n /**\r\n * Normalize partial data with defaults\r\n *\r\n * Useful when LLM might return incomplete data.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Result>\r\n * {(ctx, llmResult) => {\r\n * const raw = ResultUtils.extractJSON(llmResult);\r\n * return ResultUtils.normalize(raw, {\r\n * status: 'unknown',\r\n * items: [],\r\n * metadata: {},\r\n * });\r\n * }}\r\n * </Result>\r\n * ```\r\n */\r\n static normalize<T extends Record<string, any>>(\r\n data: Partial<T>,\r\n defaults: T\r\n ): T {\r\n return { ...defaults, ...data };\r\n }\r\n\r\n /**\r\n * Transform data with mapper function\r\n *\r\n * @example\r\n * ```tsx\r\n * <Result>\r\n * {(ctx, llmResult) => {\r\n * const raw = ResultUtils.extractJSON(llmResult);\r\n * return ResultUtils.transform(raw, (data) => ({\r\n * id: data.id,\r\n * name: data.name.toUpperCase(),\r\n * createdAt: new Date(),\r\n * }));\r\n * }}\r\n * </Result>\r\n * ```\r\n */\r\n static transform<TInput, TOutput>(\r\n data: TInput,\r\n mapper: (input: TInput) => TOutput\r\n ): TOutput {\r\n return mapper(data);\r\n }\r\n\r\n /**\r\n * Extract and validate with custom validator\r\n *\r\n * @example\r\n * ```tsx\r\n * <Result>\r\n * {(ctx, llmResult) => {\r\n * return ResultUtils.extractAndValidate(\r\n * llmResult,\r\n * ResultUtils.extractJSON,\r\n * (data) => {\r\n * if (!data.id) throw new Error('Missing id');\r\n * return data;\r\n * }\r\n * );\r\n * }}\r\n * </Result>\r\n * ```\r\n */\r\n static extractAndValidate<T>(\r\n llmResult: LLMLoopResult,\r\n extractor: (result: LLMLoopResult) => T,\r\n validator: (data: T) => T\r\n ): T {\r\n const data = extractor(llmResult);\r\n return validator(data);\r\n }\r\n\r\n /**\r\n * Merge observed data with extracted output\r\n *\r\n * @example\r\n * ```tsx\r\n * <Result>\r\n * {(ctx, llmResult, observed) => {\r\n * const output = ResultUtils.extractJSON(llmResult);\r\n * return ResultUtils.mergeWithObserved(output, observed, {\r\n * toolCallCount: observed.totalToolCalls,\r\n * executionTime: observed.executionTime,\r\n * });\r\n * }}\r\n * </Result>\r\n * ```\r\n */\r\n static mergeWithObserved<TOutput extends Record<string, any>>(\r\n output: TOutput,\r\n _observed: Record<string, any>,\r\n mapping: Record<string, any>\r\n ): TOutput & Record<string, any> {\r\n const merged: any = { ...output };\r\n\r\n for (const [key, value] of Object.entries(mapping)) {\r\n merged[key] = value;\r\n }\r\n\r\n return merged;\r\n }\r\n}\r\n\r\n/**\r\n * Common result extraction patterns\r\n */\r\nexport const result = {\r\n /**\r\n * JSON extraction with fallback to text\r\n */\r\n jsonOrText: (llmResult: LLMLoopResult) => {\r\n try {\r\n return ResultUtils.extractJSON(llmResult);\r\n } catch {\r\n return { text: ResultUtils.extractText(llmResult) };\r\n }\r\n },\r\n\r\n /**\r\n * Extract first code block or empty string\r\n */\r\n codeOrEmpty: (llmResult: LLMLoopResult, language?: string) => {\r\n try {\r\n return ResultUtils.extractCodeBlock(llmResult, language);\r\n } catch {\r\n return '';\r\n }\r\n },\r\n\r\n /**\r\n * Extract all tool calls with arguments\r\n */\r\n allToolCalls: (llmResult: LLMLoopResult) => {\r\n return (llmResult.response.toolCalls || [])\r\n .map((tc: any) => ({\r\n tool: tc.name,\r\n arguments: typeof tc.arguments === 'string'\r\n ? ((() => { try { return JSON.parse(tc.arguments); } catch { return tc.arguments; } })())\r\n : tc.arguments,\r\n }));\r\n },\r\n\r\n /**\r\n * Simple text response\r\n */\r\n text: (llmResult: LLMLoopResult) => ({\r\n response: ResultUtils.extractText(llmResult),\r\n }),\r\n};\r\n\r\n/**\r\n * Create schema-based extractor\r\n *\r\n * @example\r\n * ```tsx\r\n * const extractOutput = createSchemaExtractor(z.object({\r\n * summary: z.string(),\r\n * items: z.array(z.string()),\r\n * }));\r\n *\r\n * <Result>\r\n * {(ctx, llmResult) => extractOutput(llmResult)}\r\n * </Result>\r\n * ```\r\n */\r\nexport function createSchemaExtractor<T extends z.ZodType>(schema: T) {\r\n return (llmResult: LLMLoopResult): z.infer<T> => {\r\n return ResultUtils.extractWithSchema(llmResult, schema);\r\n };\r\n}\r\n\r\n/**\r\n * Create tool-based extractor\r\n *\r\n * @example\r\n * ```tsx\r\n * const extractPlan = createToolExtractor('planning_create');\r\n *\r\n * <Result>\r\n * {(ctx, llmResult) => ({\r\n * plan: extractPlan(llmResult),\r\n * })}\r\n * </Result>\r\n * ```\r\n */\r\nexport function createToolExtractor(toolName: string) {\r\n return (llmResult: LLMLoopResult) => {\r\n return ResultUtils.extractFromToolCall(llmResult, toolName);\r\n };\r\n}\r\n\r\n/**\r\n * Create fallback extractor\r\n *\r\n * @example\r\n * ```tsx\r\n * const extract = createFallbackExtractor(\r\n * (result) => ResultUtils.extractJSON(result),\r\n * (result) => ({ text: ResultUtils.extractText(result) })\r\n * );\r\n *\r\n * <Result>{(ctx, llmResult) => extract(llmResult)}</Result>\r\n * ```\r\n */\r\nexport function createFallbackExtractor<T = any>(\r\n ...extractors: Array<(result: LLMLoopResult) => T>\r\n) {\r\n return (llmResult: LLMLoopResult): T => {\r\n return ResultUtils.tryExtract(llmResult, extractors);\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Validate Utilities\r\n *\r\n * Helper functions for building Validate nodes.\r\n * Provides common patterns for validating agent output.\r\n *\r\n * Design principles:\r\n * - Pure functions (no side effects)\r\n * - Composable validators\r\n * - Clear error messages\r\n * - Schema-driven validation\r\n */\r\n\r\nimport { z } from 'zod';\r\nimport type { ValidationRules } from '../ast/types.js';\r\n\r\n/**\r\n * Validation result\r\n */\r\nexport interface ValidationResult {\r\n /** Whether validation passed */\r\n valid: boolean;\r\n\r\n /** Feedback message for LLM when validation fails (used by validators) */\r\n feedback?: string;\r\n\r\n /** Optional message for logging/debugging */\r\n message?: string;\r\n\r\n /** Legacy error list (deprecated, use feedback instead) */\r\n errors?: string[];\r\n}\r\n\r\n/**\r\n * Validator function type\r\n */\r\nexport type ValidatorFunction<T = any> = (\r\n output: T,\r\n observed?: Record<string, any>\r\n) => ValidationResult;\r\n\r\n/**\r\n * Convert ValidationResult to ValidationRules format\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output) => toValidationRules(\r\n * ValidateUtils.validateSchema(output, schema)\r\n * )}\r\n * </Validate>\r\n * ```\r\n */\r\nexport function toValidationRules(result: ValidationResult): ValidationRules {\r\n if (result.valid) {\r\n return { rules: [] };\r\n }\r\n\r\n return {\r\n rules: (result.errors || []).map(error => ({\r\n check: false,\r\n error,\r\n })),\r\n };\r\n}\r\n\r\n/**\r\n * Validate Utils\r\n *\r\n * Collection of helper functions for common validation patterns.\r\n */\r\nexport class ValidateUtils {\r\n /**\r\n * Validate with Zod schema\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output) => ValidateUtils.validateSchema(output, OutputSchema)}\r\n * </Validate>\r\n * ```\r\n */\r\n static validateSchema<T extends z.ZodType>(\r\n output: any,\r\n schema: T\r\n ): ValidationResult {\r\n try {\r\n schema.parse(output);\r\n return { valid: true };\r\n } catch (error) {\r\n if (error instanceof z.ZodError) {\r\n return {\r\n valid: false,\r\n errors: error.issues.map(issue => `${issue.path.join('.')}: ${issue.message}`),\r\n };\r\n }\r\n return {\r\n valid: false,\r\n errors: ['Unknown validation error'],\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Validate required fields\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output) => ValidateUtils.requireFields(output, ['id', 'name', 'status'])}\r\n * </Validate>\r\n * ```\r\n */\r\n static requireFields<T extends Record<string, any>>(\r\n output: T,\r\n fields: Array<keyof T>\r\n ): ValidationResult {\r\n const missing = fields.filter(field => {\r\n const value = output[field];\r\n return value === undefined || value === null || value === '';\r\n });\r\n\r\n if (missing.length > 0) {\r\n return {\r\n valid: false,\r\n errors: missing.map(field => `Missing required field: ${String(field)}`),\r\n };\r\n }\r\n\r\n return { valid: true };\r\n }\r\n\r\n /**\r\n * Validate field values\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output) => ValidateUtils.validateFields(output, {\r\n * priority: (val) => ['low', 'medium', 'high'].includes(val),\r\n * count: (val) => val > 0,\r\n * })}\r\n * </Validate>\r\n * ```\r\n */\r\n static validateFields<T extends Record<string, any>>(\r\n output: T,\r\n validators: { [K in keyof T]?: (value: T[K]) => boolean }\r\n ): ValidationResult {\r\n const errors: string[] = [];\r\n\r\n for (const [field, validator] of Object.entries(validators)) {\r\n const value = output[field];\r\n if (validator && !validator(value)) {\r\n errors.push(`Invalid value for field: ${field}`);\r\n }\r\n }\r\n\r\n if (errors.length > 0) {\r\n return { valid: false, errors };\r\n }\r\n\r\n return { valid: true };\r\n }\r\n\r\n /**\r\n * Validate minimum length\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output) => ValidateUtils.minLength(output.items, 1, 'items')}\r\n * </Validate>\r\n * ```\r\n */\r\n static minLength(\r\n value: any[] | string | undefined,\r\n min: number,\r\n fieldName = 'value'\r\n ): ValidationResult {\r\n const length = value?.length ?? 0;\r\n\r\n if (length < min) {\r\n return {\r\n valid: false,\r\n errors: [`${fieldName} must have at least ${min} items (got ${length})`],\r\n };\r\n }\r\n\r\n return { valid: true };\r\n }\r\n\r\n /**\r\n * Validate maximum length\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output) => ValidateUtils.maxLength(output.description, 500, 'description')}\r\n * </Validate>\r\n * ```\r\n */\r\n static maxLength(\r\n value: any[] | string | undefined,\r\n max: number,\r\n fieldName = 'value'\r\n ): ValidationResult {\r\n const length = value?.length ?? 0;\r\n\r\n if (length > max) {\r\n return {\r\n valid: false,\r\n errors: [`${fieldName} must have at most ${max} items (got ${length})`],\r\n };\r\n }\r\n\r\n return { valid: true };\r\n }\r\n\r\n /**\r\n * Validate range\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output) => ValidateUtils.inRange(output.priority, 1, 5, 'priority')}\r\n * </Validate>\r\n * ```\r\n */\r\n static inRange(\r\n value: number | undefined,\r\n min: number,\r\n max: number,\r\n fieldName = 'value'\r\n ): ValidationResult {\r\n if (value === undefined || value === null) {\r\n return {\r\n valid: false,\r\n errors: [`${fieldName} is required`],\r\n };\r\n }\r\n\r\n if (value < min || value > max) {\r\n return {\r\n valid: false,\r\n errors: [`${fieldName} must be between ${min} and ${max} (got ${value})`],\r\n };\r\n }\r\n\r\n return { valid: true };\r\n }\r\n\r\n /**\r\n * Validate enum value\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output) => ValidateUtils.inEnum(output.status, ['pending', 'done'], 'status')}\r\n * </Validate>\r\n * ```\r\n */\r\n static inEnum<T>(\r\n value: T | undefined,\r\n allowedValues: readonly T[],\r\n fieldName = 'value'\r\n ): ValidationResult {\r\n if (!allowedValues.includes(value as T)) {\r\n return {\r\n valid: false,\r\n errors: [\r\n `${fieldName} must be one of: ${allowedValues.join(', ')} (got ${value})`,\r\n ],\r\n };\r\n }\r\n\r\n return { valid: true };\r\n }\r\n\r\n /**\r\n * Validate pattern (regex)\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output) => ValidateUtils.matchesPattern(output.email, /^.+@.+\\..+$/, 'email')}\r\n * </Validate>\r\n * ```\r\n */\r\n static matchesPattern(\r\n value: string | undefined,\r\n pattern: RegExp,\r\n fieldName = 'value'\r\n ): ValidationResult {\r\n if (!value) {\r\n return {\r\n valid: false,\r\n errors: [`${fieldName} is required`],\r\n };\r\n }\r\n\r\n if (!pattern.test(value)) {\r\n return {\r\n valid: false,\r\n errors: [`${fieldName} does not match required pattern`],\r\n };\r\n }\r\n\r\n return { valid: true };\r\n }\r\n\r\n /**\r\n * Validate uniqueness in array\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output) => ValidateUtils.uniqueItems(output.ids, 'ids')}\r\n * </Validate>\r\n * ```\r\n */\r\n static uniqueItems<T>(\r\n items: T[] | undefined,\r\n fieldName = 'items'\r\n ): ValidationResult {\r\n if (!items || items.length === 0) {\r\n return { valid: true };\r\n }\r\n\r\n const unique = new Set(items);\r\n if (unique.size !== items.length) {\r\n return {\r\n valid: false,\r\n errors: [`${fieldName} contains duplicate values`],\r\n };\r\n }\r\n\r\n return { valid: true };\r\n }\r\n\r\n /**\r\n * Validate using custom function\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output) => ValidateUtils.custom(\r\n * output,\r\n * (data) => data.startDate < data.endDate,\r\n * 'End date must be after start date'\r\n * )}\r\n * </Validate>\r\n * ```\r\n */\r\n static custom<T>(\r\n value: T,\r\n predicate: (value: T) => boolean,\r\n errorMessage: string\r\n ): ValidationResult {\r\n if (!predicate(value)) {\r\n return {\r\n valid: false,\r\n errors: [errorMessage],\r\n };\r\n }\r\n\r\n return { valid: true };\r\n }\r\n\r\n /**\r\n * Combine multiple validation results\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output) => ValidateUtils.all([\r\n * ValidateUtils.requireFields(output, ['id', 'name']),\r\n * ValidateUtils.minLength(output.items, 1, 'items'),\r\n * ])}\r\n * </Validate>\r\n * ```\r\n */\r\n static all(results: ValidationResult[]): ValidationResult {\r\n const errors: string[] = [];\r\n\r\n for (const result of results) {\r\n if (!result.valid && result.errors) {\r\n errors.push(...result.errors);\r\n }\r\n }\r\n\r\n return {\r\n valid: errors.length === 0,\r\n errors: errors.length > 0 ? errors : undefined,\r\n };\r\n }\r\n\r\n /**\r\n * At least one validation must pass\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output) => ValidateUtils.any([\r\n * ValidateUtils.requireFields(output, ['email']),\r\n * ValidateUtils.requireFields(output, ['phone']),\r\n * ])}\r\n * </Validate>\r\n * ```\r\n */\r\n static any(results: ValidationResult[]): ValidationResult {\r\n const hasValid = results.some(r => r.valid);\r\n\r\n if (hasValid) {\r\n return { valid: true };\r\n }\r\n\r\n // Combine all errors\r\n const errors: string[] = [];\r\n for (const result of results) {\r\n if (result.errors) {\r\n errors.push(...result.errors);\r\n }\r\n }\r\n\r\n return {\r\n valid: false,\r\n errors: errors.length > 0 ? ['None of the validation rules passed'] : undefined,\r\n };\r\n }\r\n\r\n /**\r\n * Validate with message (doesn't fail, just adds a message)\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output) => ValidateUtils.warn(\r\n * output.items.length < 5,\r\n * 'Consider adding more items for better results'\r\n * )}\r\n * </Validate>\r\n * ```\r\n */\r\n static warn(condition: boolean, message: string): ValidationResult {\r\n if (condition) {\r\n return {\r\n valid: true,\r\n message: message,\r\n };\r\n }\r\n\r\n return { valid: true };\r\n }\r\n\r\n /**\r\n * Validate observed data constraints\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output, observed) => ValidateUtils.requireObserved(\r\n * observed,\r\n * 'usedPlanning',\r\n * 'Agent must call planning_create tool'\r\n * )}\r\n * </Validate>\r\n * ```\r\n */\r\n static requireObserved(\r\n observed: Record<string, any> | undefined,\r\n key: string,\r\n errorMessage: string\r\n ): ValidationResult {\r\n if (!observed || !observed[key]) {\r\n return {\r\n valid: false,\r\n errors: [errorMessage],\r\n };\r\n }\r\n\r\n return { valid: true };\r\n }\r\n}\r\n\r\n/**\r\n * Common validation patterns\r\n */\r\nexport const validate = {\r\n /**\r\n * Pass all validations (useful for development)\r\n */\r\n pass: (): ValidationResult => ({ valid: true }),\r\n\r\n /**\r\n * Always fail (useful for testing)\r\n */\r\n fail: (message: string): ValidationResult => ({\r\n valid: false,\r\n errors: [message],\r\n }),\r\n\r\n /**\r\n * Validate non-empty string\r\n */\r\n nonEmptyString: (value: any, fieldName = 'value'): ValidationResult => {\r\n if (typeof value !== 'string' || value.trim() === '') {\r\n return {\r\n valid: false,\r\n errors: [`${fieldName} must be a non-empty string`],\r\n };\r\n }\r\n return { valid: true };\r\n },\r\n\r\n /**\r\n * Validate non-empty array\r\n */\r\n nonEmptyArray: (value: any, fieldName = 'value'): ValidationResult => {\r\n if (!Array.isArray(value) || value.length === 0) {\r\n return {\r\n valid: false,\r\n errors: [`${fieldName} must be a non-empty array`],\r\n };\r\n }\r\n return { valid: true };\r\n },\r\n\r\n /**\r\n * Validate positive number\r\n */\r\n positiveNumber: (value: any, fieldName = 'value'): ValidationResult => {\r\n if (typeof value !== 'number' || value <= 0) {\r\n return {\r\n valid: false,\r\n errors: [`${fieldName} must be a positive number`],\r\n };\r\n }\r\n return { valid: true };\r\n },\r\n};\r\n\r\n/**\r\n * Create schema-based validator\r\n *\r\n * @example\r\n * ```tsx\r\n * const validateOutput = createSchemaValidator(OutputSchema);\r\n *\r\n * <Validate>\r\n * {(output) => toValidationRules(validateOutput(output))}\r\n * </Validate>\r\n * ```\r\n */\r\nexport function createSchemaValidator<T extends z.ZodType>(schema: T) {\r\n return (output: any): ValidationResult => {\r\n return ValidateUtils.validateSchema(output, schema);\r\n };\r\n}\r\n\r\n/**\r\n * Create field validator\r\n *\r\n * @example\r\n * ```tsx\r\n * const validateFields = createFieldValidator({\r\n * priority: (val) => ['low', 'medium', 'high'].includes(val),\r\n * count: (val) => val > 0,\r\n * });\r\n *\r\n * <Validate>\r\n * {(output) => toValidationRules(validateFields(output))}\r\n * </Validate>\r\n * ```\r\n */\r\nexport function createFieldValidator<T extends Record<string, any>>(\r\n validators: { [K in keyof T]?: (value: T[K]) => boolean }\r\n) {\r\n return (output: T): ValidationResult => {\r\n return ValidateUtils.validateFields(output, validators);\r\n };\r\n}\r\n\r\n/**\r\n * Create composite validator\r\n *\r\n * @example\r\n * ```tsx\r\n * const validateOutput = createCompositeValidator(\r\n * (output) => ValidateUtils.requireFields(output, ['id', 'name']),\r\n * (output) => ValidateUtils.minLength(output.items, 1, 'items')\r\n * );\r\n *\r\n * <Validate>\r\n * {(output) => toValidationRules(validateOutput(output))}\r\n * </Validate>\r\n * ```\r\n */\r\nexport function createCompositeValidator<T = any>(\r\n ...validators: ValidatorFunction<T>[]\r\n) {\r\n return (output: T, observed?: Record<string, any>): ValidationResult => {\r\n const results = validators.map(v => v(output, observed));\r\n return ValidateUtils.all(results);\r\n };\r\n}\r\n\r\n/**\r\n * Wrap validator to return ValidationRules format\r\n *\r\n * @example\r\n * ```tsx\r\n * const validator = wrapValidator((output) =>\r\n * ValidateUtils.requireFields(output, ['id', 'name'])\r\n * );\r\n *\r\n * <Validate>{validator}</Validate>\r\n * ```\r\n */\r\nexport function wrapValidator<T = any>(\r\n validator: ValidatorFunction<T>\r\n): (output: T, ctx?: any, observed?: Record<string, any>) => ValidationRules {\r\n return (output: T, _ctx?: any, observed?: Record<string, any>) => {\r\n const result = validator(output, observed);\r\n return toValidationRules(result);\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Retry Utilities\r\n *\r\n * Helper functions for building Retry nodes.\r\n * Provides retry strategies, backoff algorithms, and error handling patterns.\r\n *\r\n * Design principles:\r\n * - Configurable retry strategies\r\n * - Exponential and linear backoff\r\n * - Error classification\r\n * - Resource-aware retries\r\n */\r\n\r\n/**\r\n * Backoff strategy type\r\n */\r\nexport type BackoffStrategy = 'none' | 'fixed' | 'linear' | 'exponential' | 'fibonacci';\r\n\r\n/**\r\n * Retry strategy options\r\n */\r\nexport interface RetryStrategyOptions {\r\n /** Maximum number of retry attempts */\r\n maxAttempts?: number;\r\n\r\n /** Initial delay in milliseconds */\r\n initialDelay?: number;\r\n\r\n /** Maximum delay in milliseconds */\r\n maxDelay?: number;\r\n\r\n /** Backoff multiplier for exponential/fibonacci strategies */\r\n backoffMultiplier?: number;\r\n\r\n /** Backoff strategy to use */\r\n backoffStrategy?: BackoffStrategy;\r\n\r\n /** Whether to add jitter to delays */\r\n jitter?: boolean;\r\n\r\n /** Maximum jitter percentage (0-1) */\r\n jitterFactor?: number;\r\n}\r\n\r\n/**\r\n * Retry context information\r\n */\r\nexport interface RetryContext {\r\n /** Current attempt number (1-indexed) */\r\n attempt: number;\r\n\r\n /** Total number of allowed attempts */\r\n maxAttempts: number;\r\n\r\n /** Error from previous attempt */\r\n lastError?: Error | string;\r\n\r\n /** Delay before this attempt (ms) */\r\n delay: number;\r\n}\r\n\r\n/**\r\n * Should retry function type\r\n */\r\nexport type ShouldRetryFunction = (\r\n error: Error | string,\r\n context: RetryContext\r\n) => boolean;\r\n\r\n/**\r\n * Retry Utils\r\n *\r\n * Collection of helper functions for retry strategies.\r\n */\r\nexport class RetryUtils {\r\n /**\r\n * Calculate delay for next retry attempt\r\n *\r\n * @example\r\n * ```tsx\r\n * const delay = RetryUtils.calculateDelay(2, {\r\n * backoffStrategy: 'exponential',\r\n * initialDelay: 1000,\r\n * backoffMultiplier: 2,\r\n * });\r\n * ```\r\n */\r\n static calculateDelay(\r\n attempt: number,\r\n options: RetryStrategyOptions = {}\r\n ): number {\r\n const {\r\n initialDelay = 1000,\r\n maxDelay = 60000,\r\n backoffMultiplier = 2,\r\n backoffStrategy = 'exponential',\r\n jitter = true,\r\n jitterFactor = 0.1,\r\n } = options;\r\n\r\n let delay: number;\r\n\r\n switch (backoffStrategy) {\r\n case 'none':\r\n delay = 0;\r\n break;\r\n\r\n case 'fixed':\r\n delay = initialDelay;\r\n break;\r\n\r\n case 'linear':\r\n delay = initialDelay * attempt;\r\n break;\r\n\r\n case 'exponential':\r\n delay = initialDelay * Math.pow(backoffMultiplier, attempt - 1);\r\n break;\r\n\r\n case 'fibonacci':\r\n delay = initialDelay * this.fibonacci(attempt);\r\n break;\r\n\r\n default:\r\n delay = initialDelay;\r\n }\r\n\r\n // Cap at max delay\r\n delay = Math.min(delay, maxDelay);\r\n\r\n // Add jitter if enabled\r\n if (jitter && delay > 0) {\r\n const jitterAmount = delay * jitterFactor;\r\n const randomJitter = (Math.random() * 2 - 1) * jitterAmount;\r\n delay = Math.max(0, delay + randomJitter);\r\n }\r\n\r\n return Math.round(delay);\r\n }\r\n\r\n /**\r\n * Calculate fibonacci number (for fibonacci backoff)\r\n */\r\n private static fibonacci(n: number): number {\r\n if (n <= 1) return 1;\r\n if (n === 2) return 2;\r\n\r\n let a = 1;\r\n let b = 2;\r\n for (let i = 3; i <= n; i++) {\r\n const temp = a + b;\r\n a = b;\r\n b = temp;\r\n }\r\n return b;\r\n }\r\n\r\n /**\r\n * Check if error is retryable\r\n *\r\n * @example\r\n * ```tsx\r\n * const shouldRetry = RetryUtils.isRetryableError(error, {\r\n * retryableErrors: ['TIMEOUT', 'RATE_LIMIT'],\r\n * nonRetryableErrors: ['AUTH_FAILED'],\r\n * });\r\n * ```\r\n */\r\n static isRetryableError(\r\n error: Error | string,\r\n options: {\r\n retryableErrors?: string[];\r\n nonRetryableErrors?: string[];\r\n } = {}\r\n ): boolean {\r\n const { retryableErrors = [], nonRetryableErrors = [] } = options;\r\n\r\n const errorMessage = typeof error === 'string' ? error : error.message;\r\n const errorName = typeof error === 'object' && error.name ? error.name : '';\r\n\r\n // Normalize to lowercase for case-insensitive matching\r\n const errorMessageLower = errorMessage.toLowerCase();\r\n const errorNameLower = errorName.toLowerCase();\r\n\r\n // Check non-retryable errors first\r\n for (const pattern of nonRetryableErrors) {\r\n const patternLower = pattern.toLowerCase();\r\n if (errorMessageLower.includes(patternLower) || errorNameLower.includes(patternLower)) {\r\n return false;\r\n }\r\n }\r\n\r\n // If retryable errors specified, check if error matches\r\n if (retryableErrors.length > 0) {\r\n return retryableErrors.some(\r\n pattern => {\r\n const patternLower = pattern.toLowerCase();\r\n return errorMessageLower.includes(patternLower) || errorNameLower.includes(patternLower);\r\n }\r\n );\r\n }\r\n\r\n // Default: retry unless explicitly non-retryable\r\n return true;\r\n }\r\n\r\n /**\r\n * Create retry predicate based on error type\r\n *\r\n * @example\r\n * ```tsx\r\n * const shouldRetry = RetryUtils.retryOnError([\r\n * 'timeout',\r\n * 'network error',\r\n * 'rate limit',\r\n * ]);\r\n * ```\r\n */\r\n static retryOnError(errorPatterns: string[]): ShouldRetryFunction {\r\n return (error: Error | string) => {\r\n const errorMessage = typeof error === 'string' ? error : error.message;\r\n return errorPatterns.some(pattern =>\r\n errorMessage.toLowerCase().includes(pattern.toLowerCase())\r\n );\r\n };\r\n }\r\n\r\n /**\r\n * Create retry predicate for validation errors\r\n *\r\n * @example\r\n * ```tsx\r\n * const shouldRetry = RetryUtils.retryOnValidationError();\r\n * ```\r\n */\r\n static retryOnValidationError(): ShouldRetryFunction {\r\n return (error: Error | string) => {\r\n const errorMessage = typeof error === 'string' ? error : error.message;\r\n const validationKeywords = [\r\n 'validation',\r\n 'invalid',\r\n 'missing',\r\n 'required',\r\n 'schema',\r\n ];\r\n return validationKeywords.some(keyword =>\r\n errorMessage.toLowerCase().includes(keyword)\r\n );\r\n };\r\n }\r\n\r\n /**\r\n * Never retry (for testing or specific cases)\r\n *\r\n * @example\r\n * ```tsx\r\n * const shouldRetry = RetryUtils.neverRetry();\r\n * ```\r\n */\r\n static neverRetry(): ShouldRetryFunction {\r\n return () => false;\r\n }\r\n\r\n /**\r\n * Always retry up to max attempts\r\n *\r\n * @example\r\n * ```tsx\r\n * const shouldRetry = RetryUtils.alwaysRetry();\r\n * ```\r\n */\r\n static alwaysRetry(): ShouldRetryFunction {\r\n return () => true;\r\n }\r\n\r\n /**\r\n * Retry based on attempt count\r\n *\r\n * @example\r\n * ```tsx\r\n * const shouldRetry = RetryUtils.retryUntilAttempt(3);\r\n * ```\r\n */\r\n static retryUntilAttempt(maxAttempts: number): ShouldRetryFunction {\r\n return (_error: Error | string, context: RetryContext) => {\r\n return context.attempt < maxAttempts;\r\n };\r\n }\r\n\r\n /**\r\n * Combine multiple retry predicates (AND logic)\r\n *\r\n * @example\r\n * ```tsx\r\n * const shouldRetry = RetryUtils.all([\r\n * RetryUtils.retryOnValidationError(),\r\n * RetryUtils.retryUntilAttempt(3),\r\n * ]);\r\n * ```\r\n */\r\n static all(predicates: ShouldRetryFunction[]): ShouldRetryFunction {\r\n return (error: Error | string, context: RetryContext) => {\r\n return predicates.every(predicate => predicate(error, context));\r\n };\r\n }\r\n\r\n /**\r\n * Combine multiple retry predicates (OR logic)\r\n *\r\n * @example\r\n * ```tsx\r\n * const shouldRetry = RetryUtils.any([\r\n * RetryUtils.retryOnError(['timeout']),\r\n * RetryUtils.retryOnValidationError(),\r\n * ]);\r\n * ```\r\n */\r\n static any(predicates: ShouldRetryFunction[]): ShouldRetryFunction {\r\n return (error: Error | string, context: RetryContext) => {\r\n return predicates.some(predicate => predicate(error, context));\r\n };\r\n }\r\n\r\n /**\r\n * Create retry context\r\n *\r\n * @example\r\n * ```tsx\r\n * const context = RetryUtils.createContext(2, 5, error, 2000);\r\n * ```\r\n */\r\n static createContext(\r\n attempt: number,\r\n maxAttempts: number,\r\n lastError?: Error | string,\r\n delay?: number\r\n ): RetryContext {\r\n return {\r\n attempt,\r\n maxAttempts,\r\n lastError,\r\n delay: delay ?? 0,\r\n };\r\n }\r\n\r\n /**\r\n * Format retry delay for human readability\r\n *\r\n * @example\r\n * ```tsx\r\n * const message = RetryUtils.formatDelay(5000);\r\n * // Returns: \"5.0s\"\r\n * ```\r\n */\r\n static formatDelay(delayMs: number): string {\r\n if (delayMs < 1000) {\r\n return `${delayMs}ms`;\r\n }\r\n return `${(delayMs / 1000).toFixed(1)}s`;\r\n }\r\n\r\n /**\r\n * Get retry statistics\r\n *\r\n * @example\r\n * ```tsx\r\n * const stats = RetryUtils.getStats(3, 5, {\r\n * backoffStrategy: 'exponential',\r\n * initialDelay: 1000,\r\n * });\r\n * ```\r\n */\r\n static getStats(\r\n currentAttempt: number,\r\n maxAttempts: number,\r\n options: RetryStrategyOptions = {}\r\n ): {\r\n attemptsRemaining: number;\r\n nextDelay: number;\r\n totalDelaysSoFar: number;\r\n } {\r\n const attemptsRemaining = maxAttempts - currentAttempt;\r\n const nextDelay =\r\n attemptsRemaining > 0\r\n ? this.calculateDelay(currentAttempt + 1, options)\r\n : 0;\r\n\r\n // Calculate total delays up to current attempt\r\n let totalDelaysSoFar = 0;\r\n for (let i = 1; i <= currentAttempt; i++) {\r\n totalDelaysSoFar += this.calculateDelay(i, { ...options, jitter: false });\r\n }\r\n\r\n return {\r\n attemptsRemaining,\r\n nextDelay,\r\n totalDelaysSoFar,\r\n };\r\n }\r\n}\r\n\r\n/**\r\n * Common retry strategies\r\n */\r\nexport const retry = {\r\n /**\r\n * No retry (fail immediately)\r\n */\r\n none: (): RetryStrategyOptions => ({\r\n maxAttempts: 1,\r\n backoffStrategy: 'none',\r\n initialDelay: 0,\r\n }),\r\n\r\n /**\r\n * Simple retry with fixed delay\r\n */\r\n fixed: (attempts = 3, delayMs = 1000): RetryStrategyOptions => ({\r\n maxAttempts: attempts,\r\n backoffStrategy: 'fixed',\r\n initialDelay: delayMs,\r\n }),\r\n\r\n /**\r\n * Linear backoff (delay increases linearly)\r\n */\r\n linear: (attempts = 3, initialDelayMs = 1000): RetryStrategyOptions => ({\r\n maxAttempts: attempts,\r\n backoffStrategy: 'linear',\r\n initialDelay: initialDelayMs,\r\n maxDelay: 30000,\r\n }),\r\n\r\n /**\r\n * Exponential backoff (common for API retries)\r\n */\r\n exponential: (\r\n attempts = 5,\r\n initialDelayMs = 1000,\r\n maxDelayMs = 60000\r\n ): RetryStrategyOptions => ({\r\n maxAttempts: attempts,\r\n backoffStrategy: 'exponential',\r\n initialDelay: initialDelayMs,\r\n maxDelay: maxDelayMs,\r\n backoffMultiplier: 2,\r\n jitter: true,\r\n }),\r\n\r\n /**\r\n * Fibonacci backoff (gentler than exponential)\r\n */\r\n fibonacci: (\r\n attempts = 5,\r\n initialDelayMs = 1000,\r\n maxDelayMs = 60000\r\n ): RetryStrategyOptions => ({\r\n maxAttempts: attempts,\r\n backoffStrategy: 'fibonacci',\r\n initialDelay: initialDelayMs,\r\n maxDelay: maxDelayMs,\r\n jitter: true,\r\n }),\r\n\r\n /**\r\n * Aggressive retry (many attempts, short delays)\r\n */\r\n aggressive: (): RetryStrategyOptions => ({\r\n maxAttempts: 10,\r\n backoffStrategy: 'linear',\r\n initialDelay: 500,\r\n maxDelay: 5000,\r\n }),\r\n\r\n /**\r\n * Conservative retry (few attempts, long delays)\r\n */\r\n conservative: (): RetryStrategyOptions => ({\r\n maxAttempts: 3,\r\n backoffStrategy: 'exponential',\r\n initialDelay: 2000,\r\n maxDelay: 30000,\r\n }),\r\n};\r\n\r\n/**\r\n * Create custom retry strategy\r\n *\r\n * @example\r\n * ```tsx\r\n * const strategy = createRetryStrategy({\r\n * maxAttempts: 5,\r\n * backoffStrategy: 'exponential',\r\n * initialDelay: 1000,\r\n * shouldRetry: RetryUtils.retryOnValidationError(),\r\n * });\r\n * ```\r\n */\r\nexport function createRetryStrategy(\r\n options: RetryStrategyOptions & {\r\n shouldRetry?: ShouldRetryFunction;\r\n }\r\n): {\r\n options: RetryStrategyOptions;\r\n shouldRetry?: ShouldRetryFunction;\r\n} {\r\n const { shouldRetry, ...strategyOptions } = options;\r\n return {\r\n options: strategyOptions,\r\n shouldRetry,\r\n };\r\n}\r\n\r\n/**\r\n * Simulate retry delays for testing\r\n *\r\n * @example\r\n * ```tsx\r\n * const delays = simulateRetries(5, retry.exponential());\r\n * // Returns array of delays for each retry\r\n * ```\r\n */\r\nexport function simulateRetries(\r\n attempts: number,\r\n options: RetryStrategyOptions\r\n): number[] {\r\n const delays: number[] = [];\r\n for (let i = 1; i <= attempts; i++) {\r\n delays.push(RetryUtils.calculateDelay(i, { ...options, jitter: false }));\r\n }\r\n return delays;\r\n}\r\n","/**\r\n * JSX Type Helpers\r\n *\r\n * Helper functions to convert JSX elements to their specific AST node types.\r\n * This avoids the need for manual type assertions in user code.\r\n */\r\n\r\nimport type { ASTNode, WorkflowNode, AgentNode } from '../ast/types.js';\r\n\r\n/**\r\n * Convert a JSX Workflow element to WorkflowNode type\r\n *\r\n * This is a type-safe helper that avoids manual type assertions.\r\n *\r\n * @example\r\n * ```tsx\r\n * const workflow = toWorkflow(\r\n * <Workflow name=\"my-workflow\">\r\n * <Sequence>\r\n * <Agent1 />\r\n * <Agent2 />\r\n * </Sequence>\r\n * </Workflow>\r\n * );\r\n *\r\n * // No need for: as unknown as WorkflowNode\r\n * await runTSXWorkflow(workflow, inputs);\r\n * ```\r\n */\r\nexport function toWorkflow(element: ASTNode): WorkflowNode {\r\n if (element.type !== 'Workflow') {\r\n throw new Error(`Expected Workflow element, got ${element.type}`);\r\n }\r\n return element as unknown as WorkflowNode;\r\n}\r\n\r\n/**\r\n * Convert a JSX Agent element to AgentNode type\r\n *\r\n * @example\r\n * ```tsx\r\n * const agent = toAgent(\r\n * <Agent id=\"test\" input={schema} output={schema}>\r\n * <Prompt>...</Prompt>\r\n * </Agent>\r\n * );\r\n * ```\r\n */\r\nexport function toAgent<I = unknown, O = unknown>(element: ASTNode): AgentNode<I, O> {\r\n if (element.type !== 'Agent') {\r\n throw new Error(`Expected Agent element, got ${element.type}`);\r\n }\r\n return element as unknown as AgentNode<I, O>;\r\n}\r\n","/**\r\n * Deity TSX - Preflight Checker\r\n *\r\n * Validates agent configuration before execution.\r\n * Performs checks at startup/compilation time to fail fast.\r\n *\r\n * Features:\r\n * - Resource existence validation\r\n * - Schema validation\r\n * - Agent structure validation\r\n * - Detailed error reporting\r\n */\r\n\r\nimport type { AgentNode } from '../ast/types.js';\r\nimport { getResourceLoader } from './resource-loader.js';\r\n\r\n/**\r\n * Preflight Check Result\r\n */\r\nexport interface PreflightResult {\r\n /** Whether preflight passed */\r\n passed: boolean;\r\n\r\n /** List of errors found */\r\n errors: PreflightError[];\r\n\r\n /** List of warnings */\r\n warnings: PreflightWarning[];\r\n}\r\n\r\n/**\r\n * Preflight Error\r\n */\r\nexport interface PreflightError {\r\n /** Error type */\r\n type: 'missing_resource' | 'invalid_structure' | 'schema_error' | 'other';\r\n\r\n /** Error message */\r\n message: string;\r\n\r\n /** Resource path (for missing_resource errors) */\r\n resource?: string;\r\n\r\n /** Node type (for structure errors) */\r\n nodeType?: string;\r\n}\r\n\r\n/**\r\n * Preflight Warning\r\n */\r\nexport interface PreflightWarning {\r\n /** Warning type */\r\n type: 'optional_resource' | 'performance' | 'best_practice';\r\n\r\n /** Warning message */\r\n message: string;\r\n\r\n /** Additional context */\r\n context?: string;\r\n}\r\n\r\n/**\r\n * Preflight Checker Options\r\n */\r\nexport interface PreflightOptions {\r\n /** Check resource existence (default: true) */\r\n checkResources?: boolean;\r\n\r\n /** Check agent structure (default: true) */\r\n checkStructure?: boolean;\r\n\r\n /** Check schemas (default: true) */\r\n checkSchemas?: boolean;\r\n\r\n /** Base path for resource resolution */\r\n basePath?: string;\r\n}\r\n\r\n/**\r\n * Preflight Checker\r\n *\r\n * Validates agent configuration before execution.\r\n *\r\n * @example\r\n * ```typescript\r\n * const checker = new PreflightChecker();\r\n * const result = await checker.check(MyAgent);\r\n *\r\n * if (!result.passed) {\r\n * console.error('Preflight failed:', result.errors);\r\n * }\r\n * ```\r\n */\r\nexport class PreflightChecker {\r\n private options: Required<PreflightOptions>;\r\n\r\n constructor(options: PreflightOptions = {}) {\r\n this.options = {\r\n checkResources: options.checkResources ?? true,\r\n checkStructure: options.checkStructure ?? true,\r\n checkSchemas: options.checkSchemas ?? true,\r\n basePath: options.basePath || process.cwd(),\r\n };\r\n }\r\n\r\n /**\r\n * Run preflight checks on an agent\r\n *\r\n * @param agent - Agent AST node\r\n * @returns Preflight result\r\n */\r\n async check(agent: AgentNode): Promise<PreflightResult> {\r\n const errors: PreflightError[] = [];\r\n const warnings: PreflightWarning[] = [];\r\n\r\n // Check agent structure\r\n if (this.options.checkStructure) {\r\n this.checkAgentStructure(agent, errors);\r\n }\r\n\r\n // Check schemas\r\n if (this.options.checkSchemas) {\r\n this.checkSchemas(agent, errors, warnings);\r\n }\r\n\r\n // Check resources\r\n if (this.options.checkResources) {\r\n await this.checkResources(agent, errors, warnings);\r\n }\r\n\r\n return {\r\n passed: errors.length === 0,\r\n errors,\r\n warnings,\r\n };\r\n }\r\n\r\n /**\r\n * Check agent structure\r\n */\r\n private checkAgentStructure(agent: AgentNode, errors: PreflightError[]): void {\r\n // Verify agent has required children\r\n const [promptNode, ...rest] = agent.children;\r\n\r\n if (!promptNode || promptNode.type !== 'Prompt') {\r\n errors.push({\r\n type: 'invalid_structure',\r\n message: 'Agent must have a Prompt node as first child',\r\n nodeType: 'Agent',\r\n });\r\n }\r\n\r\n // Verify Result node exists\r\n const resultNode = rest.find(n => n?.type === 'Result');\r\n if (!resultNode) {\r\n errors.push({\r\n type: 'invalid_structure',\r\n message: 'Agent must have a Result node',\r\n nodeType: 'Agent',\r\n });\r\n }\r\n\r\n // Check Prompt children\r\n if (promptNode && promptNode.children) {\r\n const hasSystemOrUser = promptNode.children.some(\r\n child => child.type === 'System' || child.type === 'User'\r\n );\r\n\r\n if (!hasSystemOrUser) {\r\n errors.push({\r\n type: 'invalid_structure',\r\n message: 'Prompt must have at least one System or User node',\r\n nodeType: 'Prompt',\r\n });\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Check schemas\r\n */\r\n private checkSchemas(\r\n agent: AgentNode,\r\n errors: PreflightError[],\r\n warnings: PreflightWarning[]\r\n ): void {\r\n // Verify input schema exists\r\n if (!agent.props.input) {\r\n errors.push({\r\n type: 'schema_error',\r\n message: 'Agent must have an input schema',\r\n nodeType: 'Agent',\r\n });\r\n }\r\n\r\n // Verify output schema exists\r\n if (!agent.props.output) {\r\n errors.push({\r\n type: 'schema_error',\r\n message: 'Agent must have an output schema',\r\n nodeType: 'Agent',\r\n });\r\n }\r\n\r\n // Warn if no description\r\n if (!agent.props.description) {\r\n warnings.push({\r\n type: 'best_practice',\r\n message: 'Agent should have a description',\r\n context: `Agent \"${agent.props.id}\" has no description`,\r\n });\r\n }\r\n }\r\n\r\n /**\r\n * Check resources (file existence)\r\n */\r\n private async checkResources(\r\n agent: AgentNode,\r\n errors: PreflightError[],\r\n warnings: PreflightWarning[]\r\n ): Promise<void> {\r\n const [promptNode] = agent.children;\r\n\r\n if (!promptNode || promptNode.type !== 'Prompt') {\r\n return;\r\n }\r\n\r\n // Collect file sources\r\n const sources: Array<{ source: string; required: boolean }> = [];\r\n\r\n for (const child of promptNode.children || []) {\r\n if (child.type === 'System' && child.props.source) {\r\n sources.push({\r\n source: child.props.source,\r\n required: child.props.required ?? false,\r\n });\r\n }\r\n }\r\n\r\n if (sources.length === 0) {\r\n return; // No file resources to check\r\n }\r\n\r\n // Check resources\r\n const loader = getResourceLoader({ basePath: this.options.basePath });\r\n const missing = await loader.preflight(sources);\r\n\r\n // Add errors for missing required files\r\n for (const missingPath of missing) {\r\n errors.push({\r\n type: 'missing_resource',\r\n message: `Required resource not found: ${missingPath}`,\r\n resource: missingPath,\r\n });\r\n }\r\n\r\n // Warn about caching\r\n if (sources.length > 3) {\r\n warnings.push({\r\n type: 'performance',\r\n message: `Agent has ${sources.length} file resources`,\r\n context: 'Consider enabling caching for better performance',\r\n });\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Run preflight check on an agent\r\n *\r\n * Convenience function for quick preflight checks.\r\n *\r\n * @param agent - Agent AST node\r\n * @param options - Preflight options\r\n * @returns Preflight result\r\n */\r\nexport async function preflight(\r\n agent: AgentNode,\r\n options?: PreflightOptions\r\n): Promise<PreflightResult> {\r\n const checker = new PreflightChecker(options);\r\n return await checker.check(agent);\r\n}\r\n\r\n/**\r\n * Assert preflight passed\r\n *\r\n * Throws error if preflight failed.\r\n *\r\n * @param agent - Agent AST node\r\n * @param options - Preflight options\r\n */\r\nexport async function assertPreflight(\r\n agent: AgentNode,\r\n options?: PreflightOptions\r\n): Promise<void> {\r\n const result = await preflight(agent, options);\r\n\r\n if (!result.passed) {\r\n const errorMessages = result.errors.map(e => ` - ${e.message}`).join('\\n');\r\n throw new Error(`Preflight check failed:\\n${errorMessages}`);\r\n }\r\n}\r\n","/**\r\n * Deity TSX - Test Utils\r\n *\r\n * Testing utilities for TSX agents:\r\n * - Prompt Preview: Preview prompts without executing LLM\r\n * - Validate Dry-run: Test validation rules without LLM execution\r\n * - Observe Testing: Test observation logic with mock data\r\n */\r\n\r\nimport type { AgentNode } from '../ast/types.js';\r\nimport type { ExecutionContext, Message, LLMLoopResult, ValidationResult } from '../engine/types.js';\r\nimport { compileAgent } from '../compiler/index.js';\r\n\r\n/**\r\n * Prompt Preview Options\r\n */\r\nexport interface PromptPreviewOptions<I = unknown> {\r\n /** Mock inputs for the agent */\r\n inputs: I;\r\n\r\n /** Optional execution context overrides */\r\n ctx?: Partial<ExecutionContext<I>>;\r\n}\r\n\r\n/**\r\n * Prompt Preview Result\r\n */\r\nexport interface PromptPreviewResult {\r\n /** Generated messages */\r\n messages: Message[];\r\n\r\n /** Serialized messages for snapshot testing */\r\n snapshot: string;\r\n}\r\n\r\n/**\r\n * Render Prompt Preview\r\n *\r\n * Generate prompts without executing LLM.\r\n * Useful for:\r\n * - Snapshot testing prompts\r\n * - Debugging prompt templates\r\n * - Validating prompt structure\r\n *\r\n * @example\r\n * ```typescript\r\n * const preview = await renderPromptPreview(MyAgent, {\r\n * inputs: { task: 'test' },\r\n * });\r\n *\r\n * expect(preview.messages).toHaveLength(2);\r\n * expect(preview.snapshot).toMatchSnapshot();\r\n * ```\r\n */\r\nexport async function renderPromptPreview<I = unknown, O = unknown>(\r\n agent: AgentNode<I, O>,\r\n options: PromptPreviewOptions<I>\r\n): Promise<PromptPreviewResult> {\r\n // Compile agent\r\n const component = compileAgent(agent);\r\n\r\n // Build execution context\r\n const ctx: ExecutionContext<I> = {\r\n inputs: options.inputs,\r\n ...options.ctx,\r\n } as ExecutionContext<I>;\r\n\r\n // Generate messages\r\n const messages = await component.buildPrompt(ctx);\r\n\r\n // Create snapshot\r\n const snapshot = messages\r\n .map((msg, i) => {\r\n return `[${i}] ${msg.role}:\\n${msg.content}\\n`;\r\n })\r\n .join('\\n---\\n\\n');\r\n\r\n return {\r\n messages,\r\n snapshot,\r\n };\r\n}\r\n\r\n/**\r\n * Validate Dry-run Options\r\n */\r\nexport interface ValidateDryRunOptions<I = unknown> {\r\n /** Mock output to validate */\r\n output: unknown;\r\n\r\n /** Mock inputs (optional) */\r\n inputs?: I;\r\n\r\n /** Mock observed data (optional) */\r\n observed?: Record<string, unknown>;\r\n}\r\n\r\n/**\r\n * Dry-run Validate\r\n *\r\n * Test validation rules without LLM execution.\r\n * Useful for:\r\n * - Testing validation logic\r\n * - Debugging validation rules\r\n * - Ensuring rules are correct\r\n *\r\n * @example\r\n * ```typescript\r\n * const result = await dryRunValidate(MyAgent, {\r\n * output: { count: 3 },\r\n * inputs: { test: 'test' },\r\n * });\r\n *\r\n * expect(result.valid).toBe(false);\r\n * expect(result.errors).toContain('Count must be >= 5');\r\n * ```\r\n */\r\nexport async function dryRunValidate<I = unknown, O = unknown>(\r\n agent: AgentNode<I, O>,\r\n options: ValidateDryRunOptions<I>\r\n): Promise<ValidationResult> {\r\n // Compile agent\r\n const component = compileAgent(agent);\r\n\r\n // Check if agent has validation\r\n if (!component.validateOutput) {\r\n return { valid: true };\r\n }\r\n\r\n // Build execution context\r\n const ctx: ExecutionContext<I> = {\r\n inputs: options.inputs ?? {} as I,\r\n } as ExecutionContext<I>;\r\n\r\n // Note: The compiled validateOutput doesn't have access to observed data\r\n // This is a limitation of the current implementation\r\n // For now, validation will work but won't have access to observed metrics\r\n // TODO: Refactor validateOutput to accept observed parameter\r\n\r\n // Run validation\r\n const result = await component.validateOutput(options.output as O, ctx);\r\n\r\n return result;\r\n}\r\n\r\n/**\r\n * Observe Testing Options\r\n */\r\nexport interface ObserveTestOptions {\r\n /** Mock LLM loop result */\r\n llmResult: Partial<LLMLoopResult>;\r\n}\r\n\r\n/**\r\n * Run Observe\r\n *\r\n * Test observation logic with mock LLM result.\r\n * Useful for:\r\n * - Testing observation extractors\r\n * - Debugging observation logic\r\n * - Ensuring correct metrics\r\n *\r\n * @example\r\n * ```typescript\r\n * const observed = await runObserve(MyAgent, {\r\n * llmResult: {\r\n * toolCalls: [\r\n * { name: 'tool1', arguments: '{}' },\r\n * { name: 'tool2', arguments: '{}' },\r\n * ],\r\n * },\r\n * });\r\n *\r\n * expect(observed.toolCount).toBe(2);\r\n * ```\r\n */\r\nexport async function runObserve<I = unknown, O = unknown>(\r\n agent: AgentNode<I, O>,\r\n options: ObserveTestOptions\r\n): Promise<Record<string, unknown>> {\r\n // Compile agent (skipped for testing, we use the node directly)\r\n // const _component = compileAgent(agent);\r\n\r\n // Find Observe node\r\n const observeNode = agent.children.find(n => n?.type === 'Observe');\r\n\r\n if (!observeNode) {\r\n return {};\r\n }\r\n\r\n // Compile observe function\r\n const { compileObserve } = await import('../compiler/compile-observe.js');\r\n const observeFunction = compileObserve(observeNode as any);\r\n\r\n // Mock LLM result - handle both old-style and new-style input\r\n const mockInput = options.llmResult as any;\r\n\r\n // Handle tool calls - convert 'result' to 'arguments' for backwards compatibility\r\n let toolCalls = mockInput.toolCalls || mockInput.response?.toolCalls || [];\r\n if (toolCalls.length > 0) {\r\n toolCalls = toolCalls.map((tc: any) => {\r\n // If test provides 'result', convert it to 'arguments'\r\n if (tc.result && !tc.arguments) {\r\n return {\r\n ...tc,\r\n arguments: typeof tc.result === 'string' ? tc.result : JSON.stringify(tc.result),\r\n };\r\n }\r\n return tc;\r\n });\r\n }\r\n\r\n const llmResult: LLMLoopResult = {\r\n response: {\r\n content: mockInput.content || mockInput.response?.content || '',\r\n toolCalls,\r\n },\r\n messages: mockInput.messages || [],\r\n rounds: mockInput.rounds || 1,\r\n toolCallsExecuted: mockInput.toolCallsExecuted || 0,\r\n errors: mockInput.errors || [],\r\n } as LLMLoopResult;\r\n\r\n // Run observation\r\n const observed = await observeFunction(llmResult);\r\n\r\n return observed;\r\n}\r\n\r\n/**\r\n * Extract Output Testing Options\r\n */\r\nexport interface ExtractOutputTestOptions<I = unknown> {\r\n /** Mock inputs */\r\n inputs: I;\r\n\r\n /** Mock LLM loop result */\r\n llmResult: Partial<LLMLoopResult>;\r\n}\r\n\r\n/**\r\n * Test Extract Output\r\n *\r\n * Test output extraction with mock data.\r\n * Useful for:\r\n * - Testing extraction logic\r\n * - Debugging output transformation\r\n * - Ensuring correct output structure\r\n *\r\n * @example\r\n * ```typescript\r\n * const output = await testExtractOutput(MyAgent, {\r\n * inputs: { test: 'test' },\r\n * llmResult: {\r\n * content: 'Hello',\r\n * toolCalls: [{ name: 'planning_create', arguments: '{\"tasks\":[]}' }],\r\n * },\r\n * });\r\n *\r\n * expect(output).toHaveProperty('tasks');\r\n * ```\r\n */\r\nexport async function testExtractOutput<I = unknown, O = unknown>(\r\n agent: AgentNode<I, O>,\r\n options: ExtractOutputTestOptions<I>\r\n): Promise<O | undefined> {\r\n // Compile agent\r\n const component = compileAgent(agent);\r\n\r\n // Build execution context\r\n const ctx: ExecutionContext<I> = {\r\n inputs: options.inputs,\r\n } as ExecutionContext<I>;\r\n\r\n // Mock LLM result - handle both old-style and new-style input\r\n const mockInput = options.llmResult as any;\r\n\r\n // Handle tool calls - convert 'result' to 'arguments' for backwards compatibility\r\n let toolCalls = mockInput.toolCalls || mockInput.response?.toolCalls || [];\r\n if (toolCalls.length > 0) {\r\n toolCalls = toolCalls.map((tc: any) => {\r\n // If test provides 'result', convert it to 'arguments'\r\n if (tc.result && !tc.arguments) {\r\n return {\r\n ...tc,\r\n arguments: typeof tc.result === 'string' ? tc.result : JSON.stringify(tc.result),\r\n };\r\n }\r\n return tc;\r\n });\r\n }\r\n\r\n const llmResult: LLMLoopResult = {\r\n response: {\r\n content: mockInput.content || mockInput.response?.content || '',\r\n toolCalls,\r\n },\r\n messages: mockInput.messages || [],\r\n rounds: mockInput.rounds || 1,\r\n toolCallsExecuted: mockInput.toolCallsExecuted || 0,\r\n errors: mockInput.errors || [],\r\n } as LLMLoopResult;\r\n\r\n // Extract output\r\n const output = await component.extractOutput?.(ctx, llmResult);\r\n\r\n return output;\r\n}\r\n\r\n/**\r\n * Full Agent Test Options\r\n */\r\nexport interface FullAgentTestOptions<I = unknown> {\r\n /** Inputs for the agent */\r\n inputs: I;\r\n\r\n /** Mock LLM loop result */\r\n llmResult: Partial<LLMLoopResult>;\r\n}\r\n\r\n/**\r\n * Full Agent Test Result\r\n */\r\nexport interface FullAgentTestResult<O = unknown> {\r\n /** Generated prompts */\r\n prompts: Message[];\r\n\r\n /** Observed data */\r\n observed: Record<string, unknown>;\r\n\r\n /** Extracted output */\r\n output: O | undefined;\r\n\r\n /** Validation result */\r\n validation: ValidationResult;\r\n}\r\n\r\n/**\r\n * Test Full Agent Pipeline\r\n *\r\n * Test the complete agent pipeline without LLM execution:\r\n * 1. Build prompts\r\n * 2. Run observation\r\n * 3. Extract output\r\n * 4. Validate output\r\n *\r\n * Useful for:\r\n * - Integration testing\r\n * - End-to-end agent testing\r\n * - Ensuring all parts work together\r\n *\r\n * @example\r\n * ```typescript\r\n * const result = await testFullAgent(MyAgent, {\r\n * inputs: { task: 'test' },\r\n * llmResult: {\r\n * content: 'Done',\r\n * toolCalls: [{ name: 'planning_create', arguments: '{\"tasks\":[]}' }],\r\n * },\r\n * });\r\n *\r\n * expect(result.output).toBeDefined();\r\n * expect(result.validation.valid).toBe(true);\r\n * ```\r\n */\r\nexport async function testFullAgent<I = unknown, O = unknown>(\r\n agent: AgentNode<I, O>,\r\n options: FullAgentTestOptions<I>\r\n): Promise<FullAgentTestResult<O>> {\r\n // Compile agent\r\n const component = compileAgent(agent);\r\n\r\n // Build execution context\r\n const ctx: ExecutionContext<I> = {\r\n inputs: options.inputs,\r\n } as ExecutionContext<I>;\r\n\r\n // Mock LLM result - handle both old-style and new-style input\r\n const mockInput = options.llmResult as any;\r\n\r\n // Handle tool calls - convert 'result' to 'arguments' for backwards compatibility\r\n let toolCalls = mockInput.toolCalls || mockInput.response?.toolCalls || [];\r\n if (toolCalls.length > 0) {\r\n toolCalls = toolCalls.map((tc: any) => {\r\n // If test provides 'result', convert it to 'arguments'\r\n if (tc.result && !tc.arguments) {\r\n return {\r\n ...tc,\r\n arguments: typeof tc.result === 'string' ? tc.result : JSON.stringify(tc.result),\r\n };\r\n }\r\n return tc;\r\n });\r\n }\r\n\r\n const llmResult: LLMLoopResult = {\r\n response: {\r\n content: mockInput.content || mockInput.response?.content || '',\r\n toolCalls,\r\n },\r\n messages: mockInput.messages || [],\r\n rounds: mockInput.rounds || 1,\r\n toolCallsExecuted: mockInput.toolCallsExecuted || 0,\r\n errors: mockInput.errors || [],\r\n } as LLMLoopResult;\r\n\r\n // 1. Build prompts\r\n const prompts = await component.buildPrompt(ctx);\r\n\r\n // 2. Run observation (if present)\r\n const observed = await runObserve(agent, { llmResult });\r\n\r\n // 3. Extract output\r\n const output = await component.extractOutput?.(ctx, llmResult);\r\n\r\n // 4. Validate output (if present)\r\n let validation: ValidationResult = { valid: true };\r\n if (component.validateOutput && output !== undefined) {\r\n validation = await component.validateOutput(output as O, ctx);\r\n }\r\n\r\n return {\r\n prompts,\r\n observed,\r\n output,\r\n validation,\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Debug Utilities\r\n *\r\n * Development utilities for debugging TSX agents.\r\n * Provides logging, inspection, and debugging helpers.\r\n */\r\n\r\nimport type { ASTNode } from '../ast/types.js';\r\nimport type { Message } from '../engine/types.js';\r\nimport type { ValidationResult } from '../utilities/validate-utils.js';\r\nimport type { RetryContext } from '../utilities/retry-utils.js';\r\n\r\n/**\r\n * Debug mode flag (set via environment variable)\r\n */\r\nexport const DEBUG_ENABLED = process.env.DEITY_DEBUG === 'true';\r\n\r\n/**\r\n * Debug log levels\r\n */\r\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\r\n\r\n/**\r\n * Debug logger configuration\r\n */\r\nexport interface DebugLoggerConfig {\r\n /** Enable/disable logging */\r\n enabled?: boolean;\r\n /** Minimum log level to display */\r\n level?: LogLevel;\r\n /** Custom log prefix */\r\n prefix?: string;\r\n /** Enable timestamps */\r\n timestamps?: boolean;\r\n /** Enable colors in output */\r\n colors?: boolean;\r\n}\r\n\r\n/**\r\n * Log levels in order of severity\r\n */\r\nconst LOG_LEVELS: Record<LogLevel, number> = {\r\n debug: 0,\r\n info: 1,\r\n warn: 2,\r\n error: 3,\r\n};\r\n\r\n/**\r\n * ANSI color codes\r\n */\r\nconst COLORS = {\r\n reset: '\\x1b[0m',\r\n bright: '\\x1b[1m',\r\n dim: '\\x1b[2m',\r\n red: '\\x1b[31m',\r\n green: '\\x1b[32m',\r\n yellow: '\\x1b[33m',\r\n blue: '\\x1b[34m',\r\n magenta: '\\x1b[35m',\r\n cyan: '\\x1b[36m',\r\n white: '\\x1b[37m',\r\n};\r\n\r\n/**\r\n * Debug Logger\r\n *\r\n * Provides structured logging for development and debugging.\r\n *\r\n * @example\r\n * ```tsx\r\n * const logger = new DebugLogger({ level: 'debug' });\r\n * logger.debug('Processing agent', { nodeType: 'Agent' });\r\n * logger.warn('Validation failed', { errors: ['missing field'] });\r\n * ```\r\n */\r\nexport class DebugLogger {\r\n private config: Required<DebugLoggerConfig>;\r\n\r\n constructor(config: DebugLoggerConfig = {}) {\r\n this.config = {\r\n enabled: config.enabled ?? DEBUG_ENABLED,\r\n level: config.level ?? 'info',\r\n prefix: config.prefix ?? '[Deity]',\r\n timestamps: config.timestamps ?? true,\r\n colors: config.colors ?? true,\r\n };\r\n }\r\n\r\n /**\r\n * Log debug message\r\n */\r\n debug(message: string, data?: unknown): void {\r\n this.log('debug', message, data);\r\n }\r\n\r\n /**\r\n * Log info message\r\n */\r\n info(message: string, data?: unknown): void {\r\n this.log('info', message, data);\r\n }\r\n\r\n /**\r\n * Log warning message\r\n */\r\n warn(message: string, data?: unknown): void {\r\n this.log('warn', message, data);\r\n }\r\n\r\n /**\r\n * Log error message\r\n */\r\n error(message: string, data?: unknown): void {\r\n this.log('error', message, data);\r\n }\r\n\r\n /**\r\n * Internal log method\r\n */\r\n private log(level: LogLevel, message: string, data?: unknown): void {\r\n if (!this.config.enabled) return;\r\n if (LOG_LEVELS[level] < LOG_LEVELS[this.config.level]) return;\r\n\r\n const timestamp = this.config.timestamps ? `[${new Date().toISOString()}]` : '';\r\n const levelStr = level.toUpperCase().padEnd(5);\r\n const prefix = this.config.prefix;\r\n\r\n let output = `${timestamp} ${prefix} ${levelStr} ${message}`;\r\n\r\n if (this.config.colors) {\r\n const color = this.getLevelColor(level);\r\n output = `${COLORS.dim}${timestamp}${COLORS.reset} ${color}${prefix} ${levelStr}${COLORS.reset} ${message}`;\r\n }\r\n\r\n console.log(output);\r\n\r\n if (data !== undefined) {\r\n console.log(this.formatData(data));\r\n }\r\n }\r\n\r\n /**\r\n * Get color for log level\r\n */\r\n private getLevelColor(level: LogLevel): string {\r\n switch (level) {\r\n case 'debug':\r\n return COLORS.cyan;\r\n case 'info':\r\n return COLORS.blue;\r\n case 'warn':\r\n return COLORS.yellow;\r\n case 'error':\r\n return COLORS.red;\r\n default:\r\n return COLORS.white;\r\n }\r\n }\r\n\r\n /**\r\n * Format data for output\r\n */\r\n private formatData(data: unknown): string {\r\n if (typeof data === 'string') return data;\r\n return JSON.stringify(data, null, 2);\r\n }\r\n}\r\n\r\n/**\r\n * Global debug logger instance\r\n */\r\nexport const logger = new DebugLogger();\r\n\r\n/**\r\n * AST Inspector\r\n *\r\n * Utilities for inspecting and debugging AST nodes.\r\n */\r\nexport class ASTInspector {\r\n /**\r\n * Print AST tree structure\r\n *\r\n * @example\r\n * ```tsx\r\n * const ast = <Agent>...</Agent>;\r\n * ASTInspector.printTree(ast);\r\n * ```\r\n */\r\n static printTree(node: ASTNode, indent = 0): void {\r\n const spaces = ' '.repeat(indent);\r\n const nodeType = node.type;\r\n\r\n console.log(`${spaces}${nodeType}`);\r\n\r\n if ('children' in node && node.children) {\r\n for (const child of node.children) {\r\n if (typeof child === 'object' && child !== null && 'type' in child) {\r\n this.printTree(child as ASTNode, indent + 1);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Get node count by type\r\n */\r\n static getNodeCounts(node: ASTNode): Record<string, number> {\r\n const counts: Record<string, number> = {};\r\n\r\n const traverse = (n: ASTNode): void => {\r\n counts[n.type] = (counts[n.type] || 0) + 1;\r\n\r\n if ('children' in n && n.children) {\r\n for (const child of n.children) {\r\n if (typeof child === 'object' && child !== null && 'type' in child) {\r\n traverse(child as ASTNode);\r\n }\r\n }\r\n }\r\n };\r\n\r\n traverse(node);\r\n return counts;\r\n }\r\n\r\n /**\r\n * Find nodes by type\r\n */\r\n static findNodesByType<T extends ASTNode>(\r\n node: ASTNode,\r\n type: string\r\n ): T[] {\r\n const results: T[] = [];\r\n\r\n const traverse = (n: ASTNode): void => {\r\n if (n.type === type) {\r\n results.push(n as T);\r\n }\r\n\r\n if ('children' in n && n.children) {\r\n for (const child of n.children) {\r\n if (typeof child === 'object' && child !== null && 'type' in child) {\r\n traverse(child as ASTNode);\r\n }\r\n }\r\n }\r\n };\r\n\r\n traverse(node);\r\n return results;\r\n }\r\n\r\n /**\r\n * Validate AST structure\r\n */\r\n static validateStructure(node: ASTNode): ValidationResult {\r\n const errors: string[] = [];\r\n\r\n const traverse = (n: ASTNode, path: string): void => {\r\n // Check required fields\r\n if (!n.type) {\r\n errors.push(`${path}: Missing 'type' field`);\r\n }\r\n\r\n // Type-specific validation\r\n if (n.type === 'Agent') {\r\n if (!('children' in n) || !n.children) {\r\n errors.push(`${path}: Agent node must have children`);\r\n }\r\n }\r\n\r\n // Recurse\r\n if ('children' in n && n.children) {\r\n for (let i = 0; i < n.children.length; i++) {\r\n const child = n.children[i];\r\n if (typeof child === 'object' && child !== null && 'type' in child) {\r\n traverse(child as ASTNode, `${path}.children[${i}]`);\r\n }\r\n }\r\n }\r\n };\r\n\r\n traverse(node, 'root');\r\n\r\n return {\r\n valid: errors.length === 0,\r\n errors: errors.length > 0 ? errors : undefined,\r\n };\r\n }\r\n}\r\n\r\n/**\r\n * Execution Tracer\r\n *\r\n * Traces agent execution for debugging.\r\n */\r\nexport class ExecutionTracer {\r\n private events: ExecutionEvent[] = [];\r\n private enabled: boolean;\r\n\r\n constructor(enabled = DEBUG_ENABLED) {\r\n this.enabled = enabled;\r\n }\r\n\r\n /**\r\n * Record LLM call\r\n */\r\n recordLLMCall(messages: Message[], responseContent: string): void {\r\n if (!this.enabled) return;\r\n\r\n this.events.push({\r\n type: 'llm_call',\r\n timestamp: Date.now(),\r\n data: {\r\n messageCount: messages.length,\r\n responseLength: responseContent.length,\r\n lastMessage: messages[messages.length - 1],\r\n },\r\n });\r\n }\r\n\r\n /**\r\n * Record validation\r\n */\r\n recordValidation(result: ValidationResult): void {\r\n if (!this.enabled) return;\r\n\r\n this.events.push({\r\n type: 'validation',\r\n timestamp: Date.now(),\r\n data: result,\r\n });\r\n }\r\n\r\n /**\r\n * Record retry attempt\r\n */\r\n recordRetry(context: RetryContext): void {\r\n if (!this.enabled) return;\r\n\r\n this.events.push({\r\n type: 'retry',\r\n timestamp: Date.now(),\r\n data: context,\r\n });\r\n }\r\n\r\n /**\r\n * Record tool call\r\n */\r\n recordToolCall(toolName: string, args: unknown): void {\r\n if (!this.enabled) return;\r\n\r\n this.events.push({\r\n type: 'tool_call',\r\n timestamp: Date.now(),\r\n data: { toolName, args },\r\n });\r\n }\r\n\r\n /**\r\n * Get all events\r\n */\r\n getEvents(): ExecutionEvent[] {\r\n return [...this.events];\r\n }\r\n\r\n /**\r\n * Get events by type\r\n */\r\n getEventsByType(type: string): ExecutionEvent[] {\r\n return this.events.filter((e) => e.type === type);\r\n }\r\n\r\n /**\r\n * Print execution timeline\r\n */\r\n printTimeline(): void {\r\n if (this.events.length === 0) {\r\n console.log('No events recorded');\r\n return;\r\n }\r\n\r\n const startTime = this.events[0].timestamp;\r\n\r\n console.log('\\n=== Execution Timeline ===\\n');\r\n\r\n for (const event of this.events) {\r\n const elapsed = ((event.timestamp - startTime) / 1000).toFixed(2);\r\n console.log(`[+${elapsed}s] ${event.type}`);\r\n\r\n if (event.type === 'llm_call') {\r\n console.log(` Messages: ${event.data.messageCount}`);\r\n } else if (event.type === 'validation') {\r\n console.log(` Valid: ${event.data.valid}`);\r\n if (!event.data.valid) {\r\n console.log(` Errors: ${event.data.errors?.length || 0}`);\r\n }\r\n } else if (event.type === 'retry') {\r\n console.log(` Attempt: ${event.data.attempt}/${event.data.maxAttempts}`);\r\n } else if (event.type === 'tool_call') {\r\n console.log(` Tool: ${event.data.toolName}`);\r\n }\r\n }\r\n\r\n console.log('\\n=========================\\n');\r\n }\r\n\r\n /**\r\n * Clear all events\r\n */\r\n clear(): void {\r\n this.events = [];\r\n }\r\n\r\n /**\r\n * Get execution summary\r\n */\r\n getSummary(): ExecutionSummary {\r\n const llmCalls = this.getEventsByType('llm_call').length;\r\n const validations = this.getEventsByType('validation').length;\r\n const retries = this.getEventsByType('retry').length;\r\n const toolCalls = this.getEventsByType('tool_call').length;\r\n\r\n const duration =\r\n this.events.length > 0\r\n ? this.events[this.events.length - 1].timestamp - this.events[0].timestamp\r\n : 0;\r\n\r\n return {\r\n totalEvents: this.events.length,\r\n llmCalls,\r\n validations,\r\n retries,\r\n toolCalls,\r\n durationMs: duration,\r\n };\r\n }\r\n}\r\n\r\n/**\r\n * Execution event type\r\n */\r\nexport interface ExecutionEvent {\r\n type: string;\r\n timestamp: number;\r\n data: any;\r\n}\r\n\r\n/**\r\n * Execution summary\r\n */\r\nexport interface ExecutionSummary {\r\n totalEvents: number;\r\n llmCalls: number;\r\n validations: number;\r\n retries: number;\r\n toolCalls: number;\r\n durationMs: number;\r\n}\r\n\r\n/**\r\n * Performance Monitor\r\n *\r\n * Monitor performance metrics during agent execution.\r\n */\r\nexport class PerformanceMonitor {\r\n private timings: Map<string, number[]> = new Map();\r\n private enabled: boolean;\r\n\r\n constructor(enabled = DEBUG_ENABLED) {\r\n this.enabled = enabled;\r\n }\r\n\r\n /**\r\n * Start timing\r\n */\r\n start(label: string): () => void {\r\n if (!this.enabled) return () => {};\r\n\r\n const startTime = performance.now();\r\n\r\n return () => {\r\n const duration = performance.now() - startTime;\r\n const timings = this.timings.get(label) || [];\r\n timings.push(duration);\r\n this.timings.set(label, timings);\r\n };\r\n }\r\n\r\n /**\r\n * Get statistics for a label\r\n */\r\n getStats(label: string): TimingStats | undefined {\r\n const timings = this.timings.get(label);\r\n if (!timings || timings.length === 0) return undefined;\r\n\r\n const sorted = [...timings].sort((a, b) => a - b);\r\n const sum = sorted.reduce((a, b) => a + b, 0);\r\n\r\n return {\r\n count: sorted.length,\r\n min: sorted[0],\r\n max: sorted[sorted.length - 1],\r\n mean: sum / sorted.length,\r\n median: sorted[Math.floor(sorted.length / 2)],\r\n p95: sorted[Math.floor(sorted.length * 0.95)],\r\n p99: sorted[Math.floor(sorted.length * 0.99)],\r\n };\r\n }\r\n\r\n /**\r\n * Print all statistics\r\n */\r\n printStats(): void {\r\n console.log('\\n=== Performance Stats ===\\n');\r\n\r\n for (const [label, _timings] of this.timings) {\r\n const stats = this.getStats(label);\r\n if (!stats) continue;\r\n\r\n console.log(`${label}:`);\r\n console.log(` Count: ${stats.count}`);\r\n console.log(` Mean: ${stats.mean.toFixed(2)}ms`);\r\n console.log(` Min: ${stats.min.toFixed(2)}ms`);\r\n console.log(` Max: ${stats.max.toFixed(2)}ms`);\r\n console.log(` P95: ${stats.p95.toFixed(2)}ms`);\r\n console.log('');\r\n }\r\n\r\n console.log('=========================\\n');\r\n }\r\n\r\n /**\r\n * Clear all timings\r\n */\r\n clear(): void {\r\n this.timings.clear();\r\n }\r\n}\r\n\r\n/**\r\n * Timing statistics\r\n */\r\nexport interface TimingStats {\r\n count: number;\r\n min: number;\r\n max: number;\r\n mean: number;\r\n median: number;\r\n p95: number;\r\n p99: number;\r\n}\r\n\r\n/**\r\n * Global performance monitor instance\r\n */\r\nexport const perfMonitor = new PerformanceMonitor();\r\n\r\n/**\r\n * Global execution tracer instance\r\n */\r\nexport const tracer = new ExecutionTracer();\r\n","/**\n * Deity 4.0 - LLM Execution Loop\n *\n * Handles LLM calls with tool execution loop.\n *\n * **Tool Handling Architecture**:\n * - Deity passes tools to adapter via generate(messages, tools, config)\n * - Adapter decides how to handle tools:\n * - Option A: Use SDK's native tool support (OpenAI, Anthropic, Copilot SDK)\n * - Option B: Use Deity's optional helpers (injectToolPrompts, parseToolCallsFromResponse)\n * - Deity executes tool calls returned by adapter\n */\n\nimport type {\n Message,\n ToolSpec,\n LLMAdapter,\n GenerationConfig,\n LLMResponse,\n ToolCall,\n ExecutionContext,\n LLMLoopResult,\n Validator,\n LLMLoopState\n} from './types.js';\n\n// ============================================================================\n// LLM Loop Configuration\n// ============================================================================\n\n/**\n * Memory injection configuration\n */\nexport interface MemoryInjectionConfig {\n /** Enable automatic memory injection (default: true if memory is available) */\n enabled?: boolean;\n\n /** Maximum number of memories to inject (default: 5) */\n maxMemories?: number;\n\n /** Filter by categories */\n categories?: string[];\n\n /** Minimum relevance score (0-100, default: 50) */\n minRelevanceScore?: number;\n\n /** Injection position */\n injectionPosition?: 'before-user' | 'after-system';\n}\n\n/**\n * LLM loop configuration\n */\nexport interface LLMLoopConfig {\n /** Maximum tool calling rounds */\n maxToolRounds?: number;\n\n /** Timeout for LLM calls (ms) */\n timeout?: number;\n\n /** Enable verbose logging */\n verbose?: boolean;\n\n /** Memory injection configuration */\n memoryInjection?: MemoryInjectionConfig;\n}\n\n/**\n * Default LLM loop configuration\n */\nexport const DEFAULT_LLM_LOOP_CONFIG: Required<Omit<LLMLoopConfig, 'memoryInjection'>> = {\n maxToolRounds: 10,\n timeout: 120000, // 2 minutes\n verbose: false\n};\n\n// ============================================================================\n// LLM Loop Result (now exported from core/types.ts)\n// ============================================================================\n// export interface LLMLoopResult - moved to core/types.ts for use in AgentComponent\n\n// ============================================================================\n// LLM Execution Loop\n// ============================================================================\n\n/**\n * Execute LLM with tool calling loop\n *\n * Architecture:\n * 1. Pass messages and tools to adapter\n * 2. Adapter handles tool calling (native or via helpers)\n * 3. Framework executes tool calls returned by adapter\n * 4. Repeat until no tool calls or max rounds\n *\n * @param adapter - LLM adapter (handles tool integration)\n * @param initialMessages - Initial conversation messages\n * @param tools - Available tools (adapter decides how to handle)\n * @param config - Generation configuration\n * @param ctx - Execution context\n * @param loopConfig - Loop configuration\n * @param validator - Optional validator for loop convergence\n */\nexport async function executeLLMLoop(\n adapter: LLMAdapter,\n initialMessages: Message[],\n tools: ToolSpec[] | undefined,\n config: GenerationConfig | undefined,\n ctx: ExecutionContext,\n loopConfig: LLMLoopConfig = {},\n validator?: Validator\n): Promise<LLMLoopResult> {\n const cfg = { ...DEFAULT_LLM_LOOP_CONFIG, ...loopConfig };\n\n // 🌟 Inject relevant memories before starting loop\n const messagesWithMemory = await injectRelevantMemories(\n initialMessages,\n ctx,\n loopConfig.memoryInjection\n );\n\n const messages = [...messagesWithMemory];\n const errors: string[] = [];\n let rounds = 0;\n let toolCallsExecuted = 0;\n let response: LLMResponse;\n let toolCallsThisRound: ToolCall[] = []; // Track tool calls for validator\n\n // Main loop\n while (rounds < cfg.maxToolRounds) {\n rounds++;\n toolCallsThisRound = []; // Reset for this round\n\n // Log LLM call\n await ctx.trace.log({\n type: 'llm_call',\n messages: [...messages],\n tools,\n timestamp: new Date()\n });\n\n // Call LLM (adapter handles tools)\n try {\n response = await adapter.generate(messages, tools, config, ctx);\n } catch (error) {\n throw new Error(\n `LLM call failed: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n\n // Log LLM response\n await ctx.trace.log({\n type: 'llm_response',\n content: response.content,\n toolCalls: response.toolCalls,\n timestamp: new Date()\n });\n\n // Add assistant message\n messages.push({\n role: 'assistant',\n content: response.content\n });\n\n // Check for tool calls\n if (!response.toolCalls || response.toolCalls.length === 0) {\n // No more tool calls - but check validator before exiting\n if (validator) {\n const loopState: LLMLoopState = {\n rounds,\n response,\n messages: [...messages],\n toolCallsThisRound,\n totalToolCalls: toolCallsExecuted,\n errors: [...errors]\n };\n\n const validationResult = await Promise.resolve(validator.validate(ctx, loopState));\n\n if (!validationResult.valid && validationResult.feedback) {\n // Validation failed, add feedback and continue\n messages.push({\n role: 'user',\n content: validationResult.feedback\n });\n continue; // Continue loop to get another response\n }\n }\n\n // No more tool calls and validation passed (or no validator) - exit loop\n break;\n }\n\n // Prevent infinite loops\n if (rounds >= cfg.maxToolRounds) {\n errors.push(`Maximum tool rounds (${cfg.maxToolRounds}) exceeded`);\n break;\n }\n\n // Execute tool calls\n for (const toolCall of response.toolCalls) {\n // Check if tool is already executed (by SDK)\n const alreadyExecuted = (toolCall as any)._alreadyExecuted;\n\n if (alreadyExecuted) {\n // Tool was already executed by SDK, just record it\n toolCallsThisRound.push(toolCall);\n toolCallsExecuted++;\n\n // Add tool result message\n const result = (toolCall as any)._executionResult || '{\"success\":true}';\n messages.push({\n role: 'tool',\n content: result,\n toolCallId: toolCall.id,\n name: toolCall.name\n });\n\n // Log tool call (executed by adapter)\n await ctx.trace.log({\n type: 'tool_call',\n toolName: toolCall.name,\n input: toolCall.arguments,\n timestamp: new Date()\n } as any);\n\n continue;\n }\n\n // Tool not executed yet, execute it now\n toolCallsThisRound.push(toolCall);\n toolCallsExecuted++;\n\n try {\n const result = await executeToolCall(toolCall, tools, ctx);\n\n // Add tool result message\n messages.push({\n role: 'tool',\n content: JSON.stringify(result),\n toolCallId: toolCall.id,\n name: toolCall.name\n });\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : String(error);\n errors.push(`Tool ${toolCall.name} failed: ${errorMsg}`);\n\n // Add error as tool result\n messages.push({\n role: 'tool',\n content: JSON.stringify({\n success: false,\n error: errorMsg\n }),\n toolCallId: toolCall.id,\n name: toolCall.name\n });\n }\n }\n\n // Check if all tools were pre-executed by adapter (e.g., Copilot SDK)\n // If so, the adapter already completed its internal tool loop — don't send to LLM again\n const allPreExecuted = response.toolCalls!.every(tc => (tc as any)._alreadyExecuted);\n\n // After executing tools, check validator\n if (validator) {\n const loopState: LLMLoopState = {\n rounds,\n response,\n messages: [...messages],\n toolCallsThisRound,\n totalToolCalls: toolCallsExecuted,\n errors: [...errors]\n };\n\n const validationResult = await Promise.resolve(validator.validate(ctx, loopState));\n\n if (validationResult.valid) {\n // Validation passed, exit loop\n break;\n } else if (validationResult.feedback) {\n // Validation failed, provide feedback and continue\n messages.push({\n role: 'user',\n content: validationResult.feedback\n });\n // Continue to next iteration\n }\n }\n\n // If all tools were pre-executed by SDK, don't loop again\n // The SDK already completed its tool calling internally\n if (allPreExecuted) {\n break;\n }\n }\n\n return {\n response: response!,\n messages,\n rounds,\n toolCallsExecuted,\n errors\n };\n}\n\n// ============================================================================\n// Tool Execution\n// ============================================================================\n\n/**\n * Execute a single tool call\n */\nasync function executeToolCall(\n toolCall: ToolCall,\n tools: ToolSpec[] | undefined,\n ctx: ExecutionContext\n): Promise<unknown> {\n // Find tool\n const tool = tools?.find(t => t.name === toolCall.name);\n if (!tool) {\n throw new Error(`Tool not found: ${toolCall.name}`);\n }\n\n // Parse arguments\n let args: unknown;\n try {\n args = JSON.parse(toolCall.arguments);\n } catch (error) {\n throw new Error(\n `Invalid tool arguments JSON: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n\n // Validate arguments\n const validation = tool.inputSchema.safeParse(args);\n if (!validation.success) {\n throw new Error(\n `Tool input validation failed: ${validation.error.issues.map((e: any) => e.message).join(', ')}`\n );\n }\n\n // Log tool call\n await ctx.trace.log({\n type: 'tool_call',\n toolName: toolCall.name,\n input: validation.data,\n timestamp: new Date()\n });\n\n // Execute tool\n let result: unknown;\n try {\n result = await tool.execute(validation.data, ctx);\n } catch (error) {\n // Tool threw error\n throw error;\n }\n\n // Log tool result\n await ctx.trace.log({\n type: 'tool_result',\n toolName: toolCall.name,\n result,\n timestamp: new Date()\n });\n\n // Check if result is ToolResult wrapper\n if (\n result &&\n typeof result === 'object' &&\n 'success' in result &&\n typeof (result as { success: boolean }).success === 'boolean'\n ) {\n const toolResult = result as { success: boolean; error?: string };\n if (!toolResult.success && toolResult.error) {\n throw new Error(toolResult.error);\n }\n }\n\n return result;\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Create simple LLM loop (no tools)\n */\nexport async function executeSimpleLLM(\n adapter: LLMAdapter,\n messages: Message[],\n config: GenerationConfig | undefined,\n ctx: ExecutionContext\n): Promise<LLMResponse> {\n const result = await executeLLMLoop(\n adapter,\n messages,\n undefined,\n config,\n ctx,\n { maxToolRounds: 1 }\n );\n\n return result.response;\n}\n\n/**\n * Check if LLM result has errors\n */\nexport function hasLLMErrors(result: LLMLoopResult): boolean {\n return result.errors.length > 0;\n}\n\n/**\n * Format LLM result summary\n */\nexport function formatLLMResult(result: LLMLoopResult): string {\n const lines = [\n `LLM Loop Summary:`,\n ` Rounds: ${result.rounds}`,\n ` Tool calls: ${result.toolCallsExecuted}`,\n ` Errors: ${result.errors.length}`\n ];\n\n if (result.errors.length > 0) {\n lines.push(` Error details:`);\n for (const error of result.errors) {\n lines.push(` - ${error}`);\n }\n }\n\n return lines.join('\\n');\n}\n\n// ============================================================================\n// Memory Injection\n// ============================================================================\n\n/**\n * Inject relevant memories into message list\n *\n * Automatically retrieves and injects relevant memories based on current task context.\n * This implements Deity's \"dynamic context reconstruction\" philosophy.\n *\n * @param messages Current message list\n * @param ctx Execution context\n * @param config Memory injection configuration\n * @returns Messages with injected memories\n */\nasync function injectRelevantMemories(\n messages: Message[],\n ctx: ExecutionContext,\n config?: MemoryInjectionConfig\n): Promise<Message[]> {\n // If memory not enabled, return original messages\n if (!ctx.memory) {\n return messages;\n }\n\n // If injection explicitly disabled, return original messages\n if (config?.enabled === false) {\n return messages;\n }\n\n // Find last user message to determine current task context\n const lastUserMessage = [...messages].reverse().find(m => m.role === 'user');\n if (!lastUserMessage) {\n return messages;\n }\n\n // Extract keywords from user message\n const keywords = extractKeywords(lastUserMessage.content);\n\n // Load relevant memories\n const relevantMemories = await ctx.memory.loadWorkingMemory({\n currentTask: lastUserMessage.content,\n keywords,\n categories: config?.categories\n });\n\n // If no relevant memories, return original messages\n if (relevantMemories.length === 0) {\n return messages;\n }\n\n // Apply minimum relevance threshold if specified\n // Note: loadWorkingMemory already returns sorted by relevance\n // We just need to limit the count\n const maxMemories = config?.maxMemories ?? 5;\n const topMemories = relevantMemories.slice(0, maxMemories);\n\n // Format memories for injection\n const memoryContent = formatMemoriesForInjection(topMemories);\n\n // Create memory injection message\n const memoryMessage: Message = {\n role: 'system',\n content: memoryContent\n };\n\n // Determine injection position\n const position = config?.injectionPosition ?? 'after-system';\n\n if (position === 'after-system') {\n // Insert after last system message, before user messages\n const systemMessages = messages.filter(m => m.role === 'system');\n const nonSystemMessages = messages.filter(m => m.role !== 'system');\n\n return [\n ...systemMessages,\n memoryMessage, // Inject here\n ...nonSystemMessages\n ];\n } else {\n // Insert before user messages\n const beforeUser = messages.filter(m => m.role !== 'user');\n const userMessages = messages.filter(m => m.role === 'user');\n\n return [\n ...beforeUser,\n memoryMessage, // Inject here\n ...userMessages\n ];\n }\n}\n\n/**\n * Format memories for injection into LLM context\n */\nfunction formatMemoriesForInjection(memories: import('../memory/types.js').Memory[]): string {\n let content = '## Relevant Context from Previous Analysis\\n\\n';\n content += 'The following information was stored from earlier work and may be relevant to your current task:\\n\\n';\n\n for (const memory of memories) {\n content += `### ${memory.id}\\n`;\n\n if (memory.category) {\n content += `**Category**: ${memory.category}\\n`;\n }\n\n content += `**Importance**: ${memory.importance}/10\\n`;\n\n if (memory.tags && memory.tags.length > 0) {\n content += `**Tags**: ${memory.tags.join(', ')}\\n`;\n }\n\n content += `\\n${memory.content}\\n\\n`;\n content += '---\\n\\n';\n }\n\n return content;\n}\n\n/**\n * Extract keywords from text\n */\nfunction extractKeywords(text: string): string[] {\n // Simple keyword extraction\n // Remove common words, split on whitespace, filter short words\n const commonWords = new Set([\n 'the', 'be', 'to', 'of', 'and', 'a', 'in', 'that', 'have', 'i',\n 'it', 'for', 'not', 'on', 'with', 'he', 'as', 'you', 'do', 'at',\n 'this', 'but', 'his', 'by', 'from', 'they', 'we', 'say', 'her', 'she',\n 'or', 'an', 'will', 'my', 'one', 'all', 'would', 'there', 'their',\n 'what', 'so', 'up', 'out', 'if', 'about', 'who', 'get', 'which', 'go', 'me'\n ]);\n\n const words = text\n .toLowerCase()\n .replace(/[^a-z0-9\\s]/g, ' ') // Remove punctuation\n .split(/\\s+/)\n .filter(word => word.length > 3) // At least 4 characters\n .filter(word => !commonWords.has(word)); // Not a common word\n\n // Return unique keywords\n return Array.from(new Set(words));\n}\n","/**\n * Deity 4.0 - Retry Mechanism\n *\n * Validation-based retry with dynamic stop conditions\n */\n\nimport type {\n AgentComponent,\n ExecutionContext,\n ValidationResult,\n Message,\n RetryConfig\n} from './types.js';\n// import { RetryManager } from './retry.js'; // TODO: RetryManager not implemented yet\n\n// ============================================================================\n// Retry Execution Result\n// ============================================================================\n\n/**\n * Result from retry execution\n */\nexport interface RetryExecutionResult<O> {\n /** Final output (if successful) */\n output?: O;\n\n /** Whether execution succeeded */\n success: boolean;\n\n /** Total attempts made */\n attempts: number;\n\n /** Validation errors from final attempt */\n errors: string[];\n\n /** All validation results */\n validationHistory: ValidationResult[];\n\n /** All outputs attempted */\n outputHistory: O[];\n}\n\n// ============================================================================\n// Retry Loop\n// ============================================================================\n\n/**\n * Execute component with retry logic\n *\n * Algorithm:\n * 1. Execute component (buildPrompt + LLM + parse)\n * 2. Validate output\n * 3. If valid → return output\n * 4. If invalid:\n * a. Check shouldRetry\n * b. If should retry → add feedback + retry\n * c. If should not retry → fail\n */\nexport async function executeWithRetry<I, O>(\n component: AgentComponent<I, O>,\n ctx: ExecutionContext<I>,\n executeFn: (feedbackMessages?: Message[]) => Promise<O>\n): Promise<RetryExecutionResult<O>> {\n const retryConfig = component.retry ?? { maxAttempts: 1 };\n // const retryManager = new RetryManager(retryConfig); // TODO: RetryManager not implemented yet\n\n const validationHistory: ValidationResult[] = [];\n const outputHistory: O[] = [];\n let attempts = 0;\n\n while (true) {\n attempts++;\n\n // Execute component\n let output: O;\n try {\n // Build feedback messages for retry attempts\n const feedbackMessages = attempts > 1\n ? buildFeedbackMessages(validationHistory, retryConfig)\n : undefined;\n\n output = await executeFn(feedbackMessages);\n } catch (error) {\n // Execution failed (e.g., LLM error, parse error)\n return {\n success: false,\n attempts,\n errors: [error instanceof Error ? error.message : String(error)],\n validationHistory,\n outputHistory\n };\n }\n\n outputHistory.push(output);\n\n // Validate output (if validateOutput method is provided)\n let validation: ValidationResult;\n if (component.validateOutput) {\n try {\n validation = await Promise.resolve(component.validateOutput(output, ctx));\n } catch (error) {\n // Validation threw error\n validation = {\n valid: false,\n errors: [error instanceof Error ? error.message : String(error)]\n };\n }\n } else {\n // No validation method, assume valid\n validation = { valid: true };\n }\n\n validationHistory.push(validation);\n\n // Log validation result\n if (!validation.valid) {\n await ctx.trace.log({\n type: 'validation_failed',\n errors: validation.errors ?? [],\n attempt: attempts,\n timestamp: new Date()\n });\n }\n\n // Check if valid\n if (validation.valid) {\n // Success!\n return {\n output,\n success: true,\n attempts,\n errors: [],\n validationHistory,\n outputHistory\n };\n }\n\n // Check if should retry\n const shouldRetry = retryConfig.shouldRetry\n ? retryConfig.shouldRetry(attempts, output, ctx)\n : attempts < retryConfig.maxAttempts;\n\n if (!shouldRetry) {\n // No more retries - fail\n return {\n success: false,\n attempts,\n errors: validation.errors ?? ['Validation failed'],\n validationHistory,\n outputHistory\n };\n }\n\n // Continue to next attempt\n }\n}\n\n// ============================================================================\n// Feedback Messages\n// ============================================================================\n\n/**\n * Build feedback messages for retry attempts\n */\nfunction buildFeedbackMessages(\n validationHistory: ValidationResult[],\n retryConfig: RetryConfig\n): Message[] | undefined {\n // Check if feedback is enabled\n if (retryConfig.feedbackOnError === false) {\n return undefined;\n }\n\n // Get last validation result\n const lastValidation = validationHistory[validationHistory.length - 1];\n if (!lastValidation || lastValidation.valid) {\n return undefined;\n }\n\n // Build feedback message\n const errors = lastValidation.errors ?? ['Validation failed'];\n const errorList = errors.map(e => `- ${e}`).join('\\n');\n\n const feedbackContent = [\n 'Previous attempt failed validation:',\n errorList,\n '',\n 'Please correct your output and try again.'\n ].join('\\n');\n\n return [\n {\n role: 'user',\n content: feedbackContent\n }\n ];\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Check if retry result succeeded\n */\nexport function retrySucceeded<O>(result: RetryExecutionResult<O>): boolean {\n return result.success && result.output !== undefined;\n}\n\n/**\n * Get retry result output (throws if failed)\n */\nexport function getRetryOutput<O>(result: RetryExecutionResult<O>): O {\n if (!result.success || !result.output) {\n throw new Error(\n `Retry execution failed after ${result.attempts} attempts: ${result.errors.join(', ')}`\n );\n }\n return result.output;\n}\n\n/**\n * Format retry result summary\n */\nexport function formatRetryResult<O>(result: RetryExecutionResult<O>): string {\n const lines = [\n `Retry Execution Summary:`,\n ` Status: ${result.success ? 'SUCCESS' : 'FAILED'}`,\n ` Attempts: ${result.attempts}`,\n ` Outputs tried: ${result.outputHistory.length}`\n ];\n\n if (!result.success) {\n lines.push(` Final errors:`);\n for (const error of result.errors) {\n lines.push(` - ${error}`);\n }\n }\n\n // Validation history\n if (result.validationHistory.length > 0) {\n lines.push(` Validation history:`);\n for (let i = 0; i < result.validationHistory.length; i++) {\n const validation = result.validationHistory[i];\n const status = validation.valid ? '✓' : '✗';\n lines.push(` Attempt ${i + 1}: ${status}`);\n if (!validation.valid && validation.errors) {\n for (const error of validation.errors) {\n lines.push(` - ${error}`);\n }\n }\n }\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Create retry config with defaults\n */\nexport function createRetryConfig(config?: Partial<RetryConfig>): RetryConfig {\n return {\n maxAttempts: config?.maxAttempts ?? 3,\n feedbackOnError: config?.feedbackOnError ?? true,\n retryOnToolError: config?.retryOnToolError ?? true,\n feedbackErrorToLLM: config?.feedbackErrorToLLM ?? true,\n toolCosts: config?.toolCosts,\n phases: config?.phases,\n shouldRetry: config?.shouldRetry\n };\n}\n","/**\n * Deity 4.0 - Output Parser\n *\n * Parse and validate LLM output\n */\n\nimport type { ZodSchema } from 'zod';\n\n// ============================================================================\n// JSON Extraction\n// ============================================================================\n\n/**\n * Extract JSON from LLM response\n *\n * Handles:\n * - Code fences (```json ... ```)\n * - Preamble text before JSON\n * - Multiple JSON blocks (returns first valid)\n */\nexport function extractJSON(content: string): unknown {\n // Try to find JSON in code fence\n const codeFenceMatch = content.match(/```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?```/);\n if (codeFenceMatch) {\n try {\n return JSON.parse(codeFenceMatch[1].trim());\n } catch {\n // Continue to other methods\n }\n }\n\n // Try to find JSON object/array\n const jsonPatterns = [\n /\\{[\\s\\S]*\\}/, // Object\n /\\[[\\s\\S]*\\]/ // Array\n ];\n\n for (const pattern of jsonPatterns) {\n const match = content.match(pattern);\n if (match) {\n try {\n return JSON.parse(match[0]);\n } catch {\n // Continue to next pattern\n }\n }\n }\n\n // Try to parse entire content as JSON\n try {\n return JSON.parse(content.trim());\n } catch {\n throw new Error(\n 'Failed to extract valid JSON from LLM response. ' +\n 'Response should contain valid JSON object or array.'\n );\n }\n}\n\n// ============================================================================\n// Output Parsing\n// ============================================================================\n\n/**\n * Parse and validate component output\n */\nexport function parseComponentOutput<O>(\n content: string,\n schema: ZodSchema<O>\n): O {\n // Extract JSON\n let json: unknown;\n try {\n json = extractJSON(content);\n } catch (error) {\n throw new Error(\n `Failed to parse output: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n\n // Validate with schema\n const validation = schema.safeParse(json);\n if (!validation.success) {\n const errors = validation.error.issues\n .map((e: any) => `${e.path.join('.')}: ${e.message}`)\n .join('; ');\n\n throw new Error(`Output validation failed: ${errors}`);\n }\n\n return validation.data;\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Check if string contains JSON\n */\nexport function containsJSON(content: string): boolean {\n try {\n extractJSON(content);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Format validation error\n */\nexport function formatValidationError(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n return String(error);\n}\n","/**\n * Deity 4.0 - Component Executor\n *\n * Orchestrates AgentComponent execution\n */\n\nimport type {\n AgentComponent,\n ExecutionContext,\n LLMAdapter,\n GenerationConfig,\n Message,\n LLMLoopResult\n} from './types.js';\nimport { executeLLMLoop } from './llm-loop.js';\nimport { executeWithRetry, type RetryExecutionResult } from './retry.js';\nimport { parseComponentOutput } from './parser.js';\n\n// ============================================================================\n// Component Execution Result\n// ============================================================================\n\n/**\n * Result from component execution\n */\nexport interface ComponentExecutionResult<O> {\n /** Component output */\n output: O;\n\n /** Whether execution succeeded */\n success: boolean;\n\n /** Total attempts made */\n attempts: number;\n\n /** LLM loop results from all attempts */\n llmResults: LLMLoopResult[];\n\n /** Retry execution result */\n retryResult: RetryExecutionResult<O>;\n\n /** Execution duration (ms) */\n duration: number;\n}\n\n// ============================================================================\n// Component Executor\n// ============================================================================\n\n/**\n * Execute an AgentComponent\n *\n * Orchestrates:\n * 1. Build prompt\n * 2. LLM execution loop (with tools)\n * 3. Parse output\n * 4. Validate output\n * 5. Retry if needed\n * 6. UI updates (if bridge available)\n */\nexport async function executeComponent<I, O>(\n component: AgentComponent<I, O>,\n ctx: ExecutionContext<I>,\n adapter: LLMAdapter,\n config?: GenerationConfig\n): Promise<ComponentExecutionResult<O>> {\n const startTime = Date.now();\n const llmResults: LLMLoopResult[] = [];\n\n // UI: Start step\n ctx.ui?.startStep(component.id, component.id);\n\n // Log stage start\n await ctx.trace.log({\n type: 'stage_start',\n stageId: component.id,\n timestamp: new Date()\n });\n\n // Execute with retry\n const retryResult = await executeWithRetry<I, O>(\n component,\n ctx,\n async (feedbackMessages?: Message[]) => {\n // UI: Update progress\n ctx.ui?.stepProgress(component.id, 50, 'Executing LLM...');\n\n // 1. Build prompt\n const promptMessages = await Promise.resolve(component.buildPrompt(ctx));\n\n // 2. Add feedback messages (for retry attempts)\n const messages = feedbackMessages\n ? [...promptMessages, ...feedbackMessages]\n : promptMessages;\n\n // 2.5. Resolve tools\n const resolvedTools = component.tools;\n\n // 3. Execute LLM loop (with tools)\n const llmResult = await executeLLMLoop(\n adapter,\n messages,\n resolvedTools,\n config,\n ctx,\n component.loopConfig, // Pass component-specific loop config\n component.loopValidator // Pass loop validator for convergence\n );\n\n llmResults.push(llmResult);\n\n // UI: Update progress\n ctx.ui?.stepProgress(component.id, 75, 'Parsing output...');\n\n // 4. Parse output (custom extraction or standard JSON parsing)\n let output: O;\n\n if (component.extractOutput) {\n // Custom output extraction\n await ctx.trace.log({\n type: 'output_extraction',\n method: 'custom',\n componentId: component.id,\n timestamp: new Date()\n });\n\n try {\n const extracted = await Promise.resolve(component.extractOutput(ctx, llmResult));\n\n // Validate extracted output with schema\n const validation = component.outputSchema.safeParse(extracted);\n if (!validation.success) {\n const errors = validation.error.issues\n .map((e: any) => `${e.path.join('.')}: ${e.message}`)\n .join('; ');\n throw new Error(`Output validation failed: ${errors}`);\n }\n\n output = validation.data;\n } catch (error) {\n throw new Error(\n `Failed to extract output: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n } else {\n // Standard JSON parsing\n await ctx.trace.log({\n type: 'output_extraction',\n method: 'json',\n componentId: component.id,\n timestamp: new Date()\n });\n\n output = parseComponentOutput<O>(\n llmResult.response.content,\n component.outputSchema\n );\n }\n\n return output;\n }\n );\n\n const duration = Date.now() - startTime;\n\n // Log completion or failure\n if (retryResult.success && retryResult.output) {\n await ctx.trace.log({\n type: 'stage_complete',\n output: retryResult.output,\n timestamp: new Date()\n });\n\n // UI: Complete step\n ctx.ui?.completeStep(\n component.id,\n `Completed in ${Math.round(duration / 1000)}s`\n );\n\n return {\n output: retryResult.output,\n success: true,\n attempts: retryResult.attempts,\n llmResults,\n retryResult,\n duration\n };\n } else {\n const errorMessage = retryResult.errors.join('; ');\n\n await ctx.trace.log({\n type: 'stage_failed',\n error: errorMessage,\n timestamp: new Date()\n });\n\n // UI: Fail step\n ctx.ui?.failStep(component.id, errorMessage);\n\n throw new Error(\n `Component ${component.id} failed after ${retryResult.attempts} attempts: ${errorMessage}`\n );\n }\n}\n\n// ============================================================================\n// Simplified Component Execution\n// ============================================================================\n\n/**\n * Execute component and return output only\n */\nexport async function executeComponentSimple<I, O>(\n component: AgentComponent<I, O>,\n ctx: ExecutionContext<I>,\n adapter: LLMAdapter,\n config?: GenerationConfig\n): Promise<O> {\n const result = await executeComponent(component, ctx, adapter, config);\n return result.output;\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Check if component execution succeeded\n */\nexport function componentSucceeded<O>(result: ComponentExecutionResult<O>): boolean {\n return result.success;\n}\n\n/**\n * Format component execution result\n */\nexport function formatComponentResult<O>(result: ComponentExecutionResult<O>): string {\n const lines = [\n `Component Execution Summary:`,\n ` Status: ${result.success ? 'SUCCESS' : 'FAILED'}`,\n ` Attempts: ${result.attempts}`,\n ` Duration: ${result.duration}ms`\n ];\n\n // LLM stats\n const totalRounds = result.llmResults.reduce((sum, r) => sum + r.rounds, 0);\n const totalToolCalls = result.llmResults.reduce((sum, r) => sum + r.toolCallsExecuted, 0);\n\n lines.push(` LLM rounds: ${totalRounds}`);\n lines.push(` Tool calls: ${totalToolCalls}`);\n\n // Errors\n const allErrors = result.llmResults.flatMap(r => r.errors);\n if (allErrors.length > 0) {\n lines.push(` LLM errors: ${allErrors.length}`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Get total tool calls from component result\n */\nexport function getTotalToolCalls<O>(result: ComponentExecutionResult<O>): number {\n return result.llmResults.reduce((sum, r) => sum + r.toolCallsExecuted, 0);\n}\n\n/**\n * Get total LLM rounds from component result\n */\nexport function getTotalLLMRounds<O>(result: ComponentExecutionResult<O>): number {\n return result.llmResults.reduce((sum, r) => sum + r.rounds, 0);\n}\n","/**\n * Deity 4.0 - Enhanced Execution Context\n *\n * Unified context with integrated managers:\n * - ConversationManager (Phase 2)\n * - LimoMemoryManager (Phase 3)\n * - SessionStore (Phase 4)\n * - StatsManager (Phase 1)\n */\n\nimport type {\n ExecutionContext as IExecutionContext,\n StateStore,\n TraceLogger,\n ExecutionStats\n} from '../engine/types.js';\nimport type { ConversationManager } from '../conversation/manager.js';\nimport type { LimoMemoryManager } from '../memory/manager.js';\nimport type { SessionStore } from '../session/types.js';\nimport type { UIUpdateBridge } from '../engine/types.js';\n\n// ============================================================================\n// Enhanced Execution Context Class\n// ============================================================================\n\n/**\n * Enhanced execution context implementation\n *\n * Provides unified access to:\n * - Component inputs and outputs\n * - Conversation history\n * - Tiered memory\n * - Session persistence\n * - Execution statistics\n * - UI updates\n */\nexport class ExecutionContext<I = unknown> implements IExecutionContext<I> {\n // ========== Core Fields ==========\n\n /** Component inputs */\n public readonly inputs: I;\n\n /** Outputs from previous stages */\n public readonly previousOutputs: Record<string, unknown>;\n\n /** State store for persistence */\n public readonly store: StateStore;\n\n /** Trace logger for observability */\n public readonly trace: TraceLogger;\n\n /** Execution statistics */\n public readonly stats: ExecutionStats;\n\n // ========== Loop Context ==========\n\n /** Current iteration (for Loop primitive) */\n public iteration?: number;\n\n /** Maximum iterations (for Loop primitive) */\n public maxIterations?: number;\n\n /** Is this the last iteration? */\n public isLastIteration?: boolean;\n\n /** History of previous iterations */\n public iterationHistory?: unknown[];\n\n // ========== Optional Enhancements ==========\n\n /** Conversation manager (optional) */\n public readonly conversation?: ConversationManager;\n\n /** Tiered memory manager (optional) */\n public readonly memory?: LimoMemoryManager;\n\n /** UI update bridge (optional) */\n public readonly ui?: UIUpdateBridge;\n\n /** Session store (optional) */\n public readonly session?: SessionStore;\n\n /** Application state store (optional, isolated from AI memory) */\n public readonly appState?: StateStore;\n\n /** Current stage ID (for UI updates) */\n public currentStageId?: string;\n\n // ========== Constructor ==========\n\n constructor(params: {\n inputs: I;\n previousOutputs?: Record<string, unknown>;\n store: StateStore;\n trace: TraceLogger;\n stats: ExecutionStats;\n conversation?: ConversationManager;\n memory?: LimoMemoryManager;\n session?: SessionStore;\n appState?: StateStore;\n ui?: UIUpdateBridge;\n currentStageId?: string;\n iteration?: number;\n maxIterations?: number;\n iterationHistory?: unknown[];\n }) {\n this.inputs = params.inputs;\n this.previousOutputs = params.previousOutputs ?? {};\n this.store = params.store;\n this.trace = params.trace;\n this.stats = params.stats;\n this.conversation = params.conversation;\n this.memory = params.memory;\n this.session = params.session;\n this.appState = params.appState;\n this.ui = params.ui;\n this.currentStageId = params.currentStageId;\n this.iteration = params.iteration;\n this.maxIterations = params.maxIterations;\n this.iterationHistory = params.iterationHistory;\n\n // Calculate isLastIteration\n if (params.iteration !== undefined && params.maxIterations !== undefined) {\n this.isLastIteration = params.iteration >= params.maxIterations - 1;\n }\n }\n\n // ========== Core Methods ==========\n\n /**\n * Get output from a specific stage\n * @throws Error if stage not completed\n */\n getOutput<T>(stageId: string): T {\n if (!(stageId in this.previousOutputs)) {\n throw new Error(\n `Stage \"${stageId}\" has not been completed yet. ` +\n `Available stages: ${Object.keys(this.previousOutputs).join(', ') || 'none'}`\n );\n }\n return this.previousOutputs[stageId] as T;\n }\n\n /**\n * Check if stage output exists\n */\n hasOutput(stageId: string): boolean {\n return stageId in this.previousOutputs;\n }\n\n /**\n * Get all completed stage IDs\n */\n getCompletedStages(): string[] {\n return Object.keys(this.previousOutputs);\n }\n\n // ========== Convenience Methods ==========\n\n /**\n * Clone context with updated fields\n */\n clone(updates: Partial<{\n inputs: I;\n previousOutputs: Record<string, unknown>;\n currentStageId: string;\n iteration: number;\n maxIterations: number;\n iterationHistory: unknown[];\n }>): ExecutionContext<I> {\n return new ExecutionContext({\n inputs: updates.inputs ?? this.inputs,\n previousOutputs: updates.previousOutputs ?? this.previousOutputs,\n store: this.store,\n trace: this.trace,\n stats: this.stats,\n conversation: this.conversation,\n memory: this.memory,\n session: this.session,\n appState: this.appState,\n ui: this.ui,\n currentStageId: updates.currentStageId ?? this.currentStageId,\n iteration: updates.iteration ?? this.iteration,\n maxIterations: updates.maxIterations ?? this.maxIterations,\n iterationHistory: updates.iterationHistory ?? this.iterationHistory\n });\n }\n\n /**\n * Add stage output to context\n */\n withOutput(stageId: string, output: unknown): ExecutionContext<I> {\n return this.clone({\n previousOutputs: {\n ...this.previousOutputs,\n [stageId]: output\n }\n });\n }\n\n /**\n * Update iteration info (for loops)\n */\n withIteration(iteration: number, maxIterations: number): ExecutionContext<I> {\n return this.clone({\n iteration,\n maxIterations,\n iterationHistory: this.iterationHistory\n });\n }\n\n /**\n * Update inputs (for ForEach iterations)\n */\n withInputs<NewI = I>(inputs: NewI): ExecutionContext<NewI> {\n return new ExecutionContext({\n inputs,\n previousOutputs: this.previousOutputs,\n store: this.store,\n trace: this.trace,\n stats: this.stats,\n conversation: this.conversation,\n memory: this.memory,\n session: this.session,\n appState: this.appState,\n ui: this.ui,\n currentStageId: this.currentStageId,\n iteration: this.iteration,\n maxIterations: this.maxIterations,\n iterationHistory: this.iterationHistory\n });\n }\n\n /**\n * Add to iteration history\n */\n withIterationResult(result: unknown): ExecutionContext<I> {\n return this.clone({\n iterationHistory: [...(this.iterationHistory ?? []), result]\n });\n }\n\n // ========== Manager Helpers ==========\n\n /**\n * Check if conversation is enabled\n */\n hasConversation(): boolean {\n return this.conversation !== undefined;\n }\n\n /**\n * Check if memory is enabled\n */\n hasMemory(): boolean {\n return this.memory !== undefined;\n }\n\n /**\n * Check if session is enabled\n */\n hasSession(): boolean {\n return this.session !== undefined;\n }\n\n /**\n * Check if UI is enabled\n */\n hasUI(): boolean {\n return this.ui !== undefined;\n }\n\n /**\n * Check if appState is enabled\n */\n hasAppState(): boolean {\n return this.appState !== undefined;\n }\n\n /**\n * Get conversation manager (throws if not available)\n */\n requireConversation(): ConversationManager {\n if (!this.conversation) {\n throw new Error('Conversation manager not available in this context');\n }\n return this.conversation;\n }\n\n /**\n * Get memory manager (throws if not available)\n */\n requireMemory(): LimoMemoryManager {\n if (!this.memory) {\n throw new Error('Memory manager not available in this context');\n }\n return this.memory;\n }\n\n /**\n * Get session store (throws if not available)\n */\n requireSession(): SessionStore {\n if (!this.session) {\n throw new Error('Session store not available in this context');\n }\n return this.session;\n }\n\n /**\n * Get UI bridge (throws if not available)\n */\n requireUI(): UIUpdateBridge {\n if (!this.ui) {\n throw new Error('UI bridge not available in this context');\n }\n return this.ui;\n }\n\n /**\n * Get application state store (throws if not available)\n */\n requireAppState(): StateStore {\n if (!this.appState) {\n throw new Error('Application state store not available in this context');\n }\n return this.appState;\n }\n\n // ========== Debugging ==========\n\n /**\n * Get context summary for debugging\n */\n getSummary(): {\n hasInputs: boolean;\n completedStages: string[];\n iteration?: number;\n maxIterations?: number;\n features: {\n conversation: boolean;\n memory: boolean;\n session: boolean;\n ui: boolean;\n appState: boolean;\n };\n stats: ExecutionStats;\n } {\n return {\n hasInputs: this.inputs !== undefined,\n completedStages: this.getCompletedStages(),\n iteration: this.iteration,\n maxIterations: this.maxIterations,\n features: {\n conversation: this.hasConversation(),\n memory: this.hasMemory(),\n session: this.hasSession(),\n ui: this.hasUI(),\n appState: this.hasAppState()\n },\n stats: this.stats\n };\n }\n\n /**\n * Format context as string\n */\n toString(): string {\n const summary = this.getSummary();\n const lines = [\n 'ExecutionContext {',\n ` Inputs: ${summary.hasInputs ? 'present' : 'none'}`,\n ` Completed stages: ${summary.completedStages.length}`,\n ];\n\n if (summary.iteration !== undefined) {\n lines.push(` Iteration: ${summary.iteration + 1}/${summary.maxIterations}`);\n }\n\n const enabledFeatures = Object.entries(summary.features)\n .filter(([_, enabled]) => enabled)\n .map(([feature]) => feature);\n\n if (enabledFeatures.length > 0) {\n lines.push(` Features: ${enabledFeatures.join(', ')}`);\n }\n\n lines.push('}');\n\n return lines.join('\\n');\n }\n}\n","/**\n * Deity 4.0 - Conversation Types\n *\n * Types for optimized conversation management\n */\n\nimport type { Message } from '../engine/types.js';\n\n// ============================================================================\n// Conversation Message\n// ============================================================================\n\n/**\n * Message metadata for conversation management\n */\nexport interface MessageMetadata {\n /** Message importance (0-10) */\n importance?: number;\n\n /** Is this message pinned (always retained)? */\n pinned?: boolean;\n\n /** Custom tags for filtering */\n tags?: string[];\n\n /** Source of the message (stage ID, user, etc.) */\n source?: string;\n\n /** Any custom metadata */\n [key: string]: unknown;\n}\n\n/**\n * Enhanced message with conversation metadata\n */\nexport interface ConversationMessage extends Message {\n /** Unique message ID */\n id: string;\n\n /** Timestamp */\n timestamp: Date;\n\n /** Message metadata */\n metadata?: MessageMetadata;\n}\n\n// ============================================================================\n// Conversation Filter\n// ============================================================================\n\n/**\n * Filter for querying messages\n */\nexport interface ConversationFilter {\n /** Filter by role */\n role?: string;\n\n /** Filter messages after this date */\n after?: Date;\n\n /** Filter messages before this date */\n before?: Date;\n\n /** Filter by tags */\n tags?: string[];\n\n /** Filter by source */\n source?: string;\n\n /** Limit number of results */\n limit?: number;\n}\n\n// ============================================================================\n// Conversation Configuration\n// ============================================================================\n\n/**\n * Message retention policy\n */\nexport interface MessageRetentionPolicy {\n /** Determine if a message is important (should always be retained) */\n isImportant(message: ConversationMessage): boolean;\n}\n\n/**\n * Conversation configuration\n */\nexport interface ConversationConfig {\n /** Maximum tokens allowed (estimated) */\n maxTokens?: number;\n\n /** Maximum number of messages */\n maxMessages?: number;\n\n /** Threshold for pruning (0-1, default 0.75) */\n pruneThreshold?: number;\n\n /** Message retention policy */\n messageRetentionPolicy?: MessageRetentionPolicy;\n\n /** Enable token caching */\n enableTokenCaching?: boolean;\n\n /** Pruning interval in milliseconds (default: 10000ms = 10s) */\n pruningInterval?: number;\n\n /** Minimum messages before pruning (default: 50) */\n minMessagesBeforePrune?: number;\n}\n\n// ============================================================================\n// Conversation Statistics\n// ============================================================================\n\n/**\n * Conversation statistics\n */\nexport interface ConversationStats {\n /** Total messages */\n totalMessages: number;\n\n /** Messages by role */\n messagesByRole: Record<string, number>;\n\n /** Estimated total tokens */\n estimatedTokens: number;\n\n /** Number of pruning operations */\n pruningCount: number;\n\n /** Last pruning time */\n lastPruneTime?: Date;\n\n /** Important messages count */\n importantMessagesCount: number;\n}\n\n// ============================================================================\n// Default Policies\n// ============================================================================\n\n/**\n * Default retention policy: system messages and pinned messages are important\n */\nexport const DEFAULT_RETENTION_POLICY: MessageRetentionPolicy = {\n isImportant(message: ConversationMessage): boolean {\n // System messages are important\n if (message.role === 'system') return true;\n\n // Pinned messages are important\n if (message.metadata?.pinned) return true;\n\n // High importance messages\n if (message.metadata?.importance !== undefined && message.metadata.importance >= 8) {\n return true;\n }\n\n return false;\n }\n};\n\n/**\n * Default conversation configuration\n */\nexport const DEFAULT_CONVERSATION_CONFIG: Required<ConversationConfig> = {\n maxTokens: 100000,\n maxMessages: 1000,\n pruneThreshold: 0.75,\n messageRetentionPolicy: DEFAULT_RETENTION_POLICY,\n enableTokenCaching: true,\n pruningInterval: 10000, // 10 seconds\n minMessagesBeforePrune: 50\n};\n","/**\n * Deity 4.0 - Conversation Utilities\n *\n * Utility functions for conversation management\n */\n\nimport type { ConversationMessage, ConversationStats } from './types.js';\n\n// ============================================================================\n// ID Generation\n// ============================================================================\n\nlet messageIdCounter = 0;\n\n/**\n * Generate unique message ID\n */\nexport function generateMessageId(): string {\n return `msg_${Date.now()}_${messageIdCounter++}`;\n}\n\n/**\n * Reset message ID counter (for testing)\n */\nexport function resetMessageIdCounter(): void {\n messageIdCounter = 0;\n}\n\n// ============================================================================\n// Token Estimation\n// ============================================================================\n\n/**\n * Estimate tokens for a message\n * Approximation: 1 token ≈ 3.5 characters\n */\nexport function estimateMessageTokens(message: ConversationMessage): number {\n const chars = message.content.length;\n return Math.ceil(chars / 3.5);\n}\n\n/**\n * Estimate tokens for multiple messages\n */\nexport function estimateMessagesTokens(messages: ConversationMessage[]): number {\n const totalChars = messages.reduce((sum, m) => sum + m.content.length, 0);\n return Math.ceil(totalChars / 3.5);\n}\n\n// ============================================================================\n// Message Formatting\n// ============================================================================\n\n/**\n * Format conversation stats as string\n */\nexport function formatConversationStats(stats: ConversationStats): string {\n const lines = [\n `Total Messages: ${stats.totalMessages}`,\n `Estimated Tokens: ${stats.estimatedTokens}`,\n `Important Messages: ${stats.importantMessagesCount}`,\n `Pruning Count: ${stats.pruningCount}`,\n ];\n\n if (stats.lastPruneTime) {\n lines.push(`Last Prune: ${stats.lastPruneTime.toISOString()}`);\n }\n\n lines.push('', 'Messages by Role:');\n for (const [role, count] of Object.entries(stats.messagesByRole)) {\n lines.push(` ${role}: ${count}`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Format message as compact string\n */\nexport function formatMessageCompact(message: ConversationMessage): string {\n const role = message.role.padEnd(10);\n const preview = message.content.slice(0, 50).replace(/\\n/g, ' ');\n const timestamp = message.timestamp.toISOString().split('T')[1].split('.')[0];\n return `[${timestamp}] ${role} ${preview}${message.content.length > 50 ? '...' : ''}`;\n}\n\n/**\n * Format messages as conversation log\n */\nexport function formatConversationLog(messages: ConversationMessage[]): string {\n return messages.map(formatMessageCompact).join('\\n');\n}\n\n// ============================================================================\n// Message Analysis\n// ============================================================================\n\n/**\n * Count messages by role\n */\nexport function countMessagesByRole(messages: ConversationMessage[]): Record<string, number> {\n const counts: Record<string, number> = {};\n for (const message of messages) {\n counts[message.role] = (counts[message.role] ?? 0) + 1;\n }\n return counts;\n}\n\n/**\n * Get unique roles in messages\n */\nexport function getUniqueRoles(messages: ConversationMessage[]): string[] {\n return Array.from(new Set(messages.map(m => m.role)));\n}\n\n/**\n * Filter messages by date range\n */\nexport function filterMessagesByDateRange(\n messages: ConversationMessage[],\n start: Date,\n end: Date\n): ConversationMessage[] {\n return messages.filter(m =>\n m.timestamp >= start && m.timestamp <= end\n );\n}\n\n/**\n * Get messages from last N minutes\n */\nexport function getRecentMessages(\n messages: ConversationMessage[],\n minutes: number\n): ConversationMessage[] {\n const cutoff = new Date(Date.now() - minutes * 60 * 1000);\n return messages.filter(m => m.timestamp >= cutoff);\n}\n\n// ============================================================================\n// Message Creation Helpers\n// ============================================================================\n\n/**\n * Create a system message\n */\nexport function createSystemMessage(content: string): ConversationMessage {\n return {\n id: generateMessageId(),\n role: 'system',\n content,\n timestamp: new Date()\n };\n}\n\n/**\n * Create a user message\n */\nexport function createUserMessage(content: string): ConversationMessage {\n return {\n id: generateMessageId(),\n role: 'user',\n content,\n timestamp: new Date()\n };\n}\n\n/**\n * Create an assistant message\n */\nexport function createAssistantMessage(content: string): ConversationMessage {\n return {\n id: generateMessageId(),\n role: 'assistant',\n content,\n timestamp: new Date()\n };\n}\n\n/**\n * Create a tool message\n */\nexport function createToolMessage(content: string, toolCallId: string): ConversationMessage {\n return {\n id: generateMessageId(),\n role: 'tool',\n content,\n toolCallId,\n timestamp: new Date()\n };\n}\n\n// ============================================================================\n// Conversation Validation\n// ============================================================================\n\n/**\n * Validate conversation alternates between user and assistant\n */\nexport function validateConversationFlow(messages: ConversationMessage[]): {\n valid: boolean;\n errors: string[];\n} {\n const errors: string[] = [];\n\n // Filter out system and tool messages\n const conversationMessages = messages.filter(\n m => m.role === 'user' || m.role === 'assistant'\n );\n\n // Check alternation\n for (let i = 1; i < conversationMessages.length; i++) {\n const prev = conversationMessages[i - 1];\n const curr = conversationMessages[i];\n\n if (prev.role === curr.role) {\n errors.push(\n `Consecutive ${curr.role} messages at positions ${i - 1} and ${i}`\n );\n }\n }\n\n // Check starts with user\n if (conversationMessages.length > 0 && conversationMessages[0].role !== 'user') {\n errors.push('Conversation should start with a user message');\n }\n\n return {\n valid: errors.length === 0,\n errors\n };\n}\n\n/**\n * Check if conversation has system message\n */\nexport function hasSystemMessage(messages: ConversationMessage[]): boolean {\n return messages.some(m => m.role === 'system');\n}\n\n/**\n * Get conversation length in tokens\n */\nexport function getConversationLength(messages: ConversationMessage[]): {\n messages: number;\n tokens: number;\n characters: number;\n} {\n const characters = messages.reduce((sum, m) => sum + m.content.length, 0);\n const tokens = Math.ceil(characters / 3.5);\n\n return {\n messages: messages.length,\n tokens,\n characters\n };\n}\n","/**\n * Deity 4.0 - Conversation Manager\n *\n * Optimized conversation management with O(1) operations\n *\n * Performance targets (from LIMO_DEITY_CONSENSUS.md):\n * - addMessage: < 1ms (99th percentile)\n * - getMessages(role): O(1) indexed lookup\n * - Pruning frequency: Every 50 messages or 10 seconds\n *\n * Optimizations:\n * - Role indexing for O(1) role-based queries\n * - Importance indexing for fast pruning\n * - Token estimate caching to avoid recalculation\n * - Incremental pruning (not every message)\n */\n\nimport type { Message } from '../engine/types.js';\nimport type {\n ConversationMessage,\n MessageMetadata,\n ConversationFilter,\n ConversationConfig,\n ConversationStats\n} from './types.js';\nimport { DEFAULT_CONVERSATION_CONFIG } from './types.js';\nimport { generateMessageId } from './utils.js';\n\n// ============================================================================\n// Conversation Manager\n// ============================================================================\n\n/**\n * Optimized conversation manager with indexed lookups\n */\nexport class ConversationManager {\n private messages: ConversationMessage[] = [];\n private config: Required<ConversationConfig>;\n\n // ========== Indexes (O(1) lookups) ==========\n\n /** Role index: role -> messages */\n private roleIndex: Map<string, ConversationMessage[]> = new Map();\n\n /** Important messages set: message ID -> message */\n private importantMessagesSet: Set<string> = new Set();\n\n // ========== Pruning state ==========\n\n /** Size at last pruning */\n private lastPruneSize: number = 0;\n\n /** Time of last pruning */\n private lastPruneTime: number = 0;\n\n /** Number of pruning operations */\n private pruningCount: number = 0;\n\n // ========== Token caching ==========\n\n /** Cached token estimate */\n private tokenEstimateCache: number = 0;\n\n /** Cache size (number of messages when cached) */\n private tokenEstimateCacheSize: number = 0;\n\n constructor(config?: ConversationConfig) {\n this.config = {\n ...DEFAULT_CONVERSATION_CONFIG,\n ...config,\n messageRetentionPolicy: config?.messageRetentionPolicy ?? DEFAULT_CONVERSATION_CONFIG.messageRetentionPolicy\n };\n }\n\n // ============================================================================\n // Core Operations\n // ============================================================================\n\n /**\n * Add a message to the conversation\n * Performance target: < 1ms (99th percentile)\n */\n addMessage(message: Message, metadata?: MessageMetadata): void {\n const conversationMessage: ConversationMessage = {\n ...message,\n id: generateMessageId(),\n timestamp: new Date(),\n metadata\n };\n\n // Add to messages array\n this.messages.push(conversationMessage);\n\n // Update indexes (O(1))\n this.updateIndexes(conversationMessage);\n\n // Invalidate token cache\n this.invalidateTokenCache();\n\n // Incremental pruning check (not every message!)\n this.incrementalPruneIfNeeded();\n }\n\n /**\n * Get conversation history\n */\n getHistory(): Message[] {\n return this.messages.map(msg => ({\n role: msg.role,\n content: msg.content,\n toolCallId: msg.toolCallId,\n name: msg.name\n }));\n }\n\n /**\n * Get messages with optional filtering\n * Performance: O(1) for role-only queries (indexed)\n */\n getMessages(filter?: ConversationFilter): ConversationMessage[] {\n // Fast path: role-only query (O(1) indexed)\n if (filter?.role && !filter.after && !filter.before && !filter.tags && !filter.source) {\n const roleMessages = this.roleIndex.get(filter.role) ?? [];\n return filter.limit ? roleMessages.slice(-filter.limit) : roleMessages;\n }\n\n // General filtering\n let filtered = [...this.messages];\n\n if (filter) {\n if (filter.role) {\n filtered = filtered.filter(m => m.role === filter.role);\n }\n if (filter.after) {\n filtered = filtered.filter(m => m.timestamp >= filter.after!);\n }\n if (filter.before) {\n filtered = filtered.filter(m => m.timestamp <= filter.before!);\n }\n if (filter.tags && filter.tags.length > 0) {\n filtered = filtered.filter(m =>\n filter.tags!.some(tag => m.metadata?.tags?.includes(tag))\n );\n }\n if (filter.source) {\n filtered = filtered.filter(m => m.metadata?.source === filter.source);\n }\n if (filter.limit) {\n filtered = filtered.slice(-filter.limit);\n }\n }\n\n return filtered;\n }\n\n /**\n * Clear all messages\n */\n clear(): void {\n this.messages = [];\n this.roleIndex.clear();\n this.importantMessagesSet.clear();\n this.lastPruneSize = 0;\n this.lastPruneTime = 0;\n this.pruningCount = 0;\n this.tokenEstimateCache = 0;\n this.tokenEstimateCacheSize = 0;\n }\n\n /**\n * Get conversation statistics\n */\n getStats(): ConversationStats {\n // Update token estimate if needed\n const estimatedTokens = this.estimateTokens();\n\n // Count messages by role\n const messagesByRole: Record<string, number> = {};\n for (const [role, messages] of this.roleIndex.entries()) {\n messagesByRole[role] = messages.length;\n }\n\n return {\n totalMessages: this.messages.length,\n messagesByRole,\n estimatedTokens,\n pruningCount: this.pruningCount,\n lastPruneTime: this.lastPruneTime > 0 ? new Date(this.lastPruneTime) : undefined,\n importantMessagesCount: this.importantMessagesSet.size\n };\n }\n\n // ============================================================================\n // Indexing (O(1) operations)\n // ============================================================================\n\n /**\n * Update indexes for a new message (O(1))\n */\n private updateIndexes(message: ConversationMessage): void {\n // Role index\n if (!this.roleIndex.has(message.role)) {\n this.roleIndex.set(message.role, []);\n }\n this.roleIndex.get(message.role)!.push(message);\n\n // Important messages set\n if (this.config.messageRetentionPolicy.isImportant(message)) {\n this.importantMessagesSet.add(message.id);\n }\n }\n\n /**\n * Rebuild all indexes (after pruning)\n */\n private rebuildIndexes(): void {\n this.roleIndex.clear();\n this.importantMessagesSet.clear();\n\n for (const message of this.messages) {\n this.updateIndexes(message);\n }\n }\n\n // ============================================================================\n // Incremental Pruning\n // ============================================================================\n\n /**\n * Incremental pruning check (not every message!)\n *\n * Strategy:\n * 1. Only prune if growth >= threshold (default: 50 messages)\n * 2. Only prune if time since last prune >= interval (default: 10s)\n * 3. Only prune if token/message count exceeds threshold\n */\n private incrementalPruneIfNeeded(): void {\n // Strategy 1: Check growth threshold\n const growth = this.messages.length - this.lastPruneSize;\n const growthThreshold = this.config.minMessagesBeforePrune;\n\n if (growth < growthThreshold) {\n return; // Not enough growth\n }\n\n // Strategy 2: Check time threshold\n const timeSinceLastPrune = Date.now() - this.lastPruneTime;\n if (timeSinceLastPrune < this.config.pruningInterval) {\n return; // Too soon\n }\n\n // Strategy 3: Check if pruning is needed\n if (!this.shouldPrune()) {\n return; // No need to prune yet\n }\n\n // Execute pruning\n this.performPruning();\n\n // Update pruning state\n this.lastPruneSize = this.messages.length;\n this.lastPruneTime = Date.now();\n this.pruningCount++;\n }\n\n /**\n * Check if pruning should be performed\n */\n private shouldPrune(): boolean {\n const estimatedTokens = this.estimateTokens();\n const tokenThreshold = this.config.maxTokens * this.config.pruneThreshold;\n const messageThreshold = this.config.maxMessages * this.config.pruneThreshold;\n\n return (\n estimatedTokens >= tokenThreshold ||\n this.messages.length >= messageThreshold\n );\n }\n\n /**\n * Perform pruning operation\n *\n * Algorithm:\n * 1. Separate messages into categories (using indexes!)\n * 2. Keep all important messages (includes system messages)\n * 3. Keep most recent 1/3 of regular messages\n * 4. Rebuild indexes\n */\n private performPruning(): void {\n // Categorize messages using importance index\n const importantMessages = this.messages.filter(m =>\n this.importantMessagesSet.has(m.id)\n );\n const regularMessages = this.messages.filter(m =>\n !this.importantMessagesSet.has(m.id)\n );\n\n // Keep most recent 1/3 of regular messages\n const keepCount = Math.floor(regularMessages.length / 3);\n const recentRegular = regularMessages.slice(-keepCount);\n\n // Reconstruct messages array (no duplicates)\n this.messages = [\n ...importantMessages,\n ...recentRegular\n ].sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());\n\n // Rebuild indexes\n this.rebuildIndexes();\n\n // Invalidate token cache\n this.invalidateTokenCache();\n }\n\n // ============================================================================\n // Token Estimation (with caching)\n // ============================================================================\n\n /**\n * Estimate total tokens (cached)\n *\n * Approximation: 1 token ≈ 3.5 characters\n */\n private estimateTokens(): number {\n // Return cached value if valid\n if (this.config.enableTokenCaching &&\n this.tokenEstimateCacheSize === this.messages.length) {\n return this.tokenEstimateCache;\n }\n\n // Calculate estimate\n const totalChars = this.messages.reduce((sum, m) => sum + m.content.length, 0);\n const estimate = Math.ceil(totalChars / 3.5);\n\n // Update cache\n if (this.config.enableTokenCaching) {\n this.tokenEstimateCache = estimate;\n this.tokenEstimateCacheSize = this.messages.length;\n }\n\n return estimate;\n }\n\n /**\n * Invalidate token cache\n */\n private invalidateTokenCache(): void {\n this.tokenEstimateCacheSize = 0;\n }\n\n // ============================================================================\n // Configuration\n // ============================================================================\n\n /**\n * Get current configuration\n */\n getConfig(): Required<ConversationConfig> {\n return { ...this.config };\n }\n\n /**\n * Update configuration\n */\n updateConfig(config: Partial<ConversationConfig>): void {\n this.config = {\n ...this.config,\n ...config,\n messageRetentionPolicy: config.messageRetentionPolicy ?? this.config.messageRetentionPolicy\n };\n\n // Invalidate cache\n this.invalidateTokenCache();\n }\n}\n","/**\n * Deity 4.0 - Memory Types\n *\n * Types for tiered memory management\n * Based on Deity POC with Limo enhancements\n */\n\n// ============================================================================\n// Memory Entry\n// ============================================================================\n\n/**\n * A single memory entry\n */\nexport interface Memory {\n /** Unique identifier */\n id: string;\n\n /** Memory content */\n content: string;\n\n /** Importance level (0-10) */\n importance: number;\n\n /** Category (optional) */\n category?: string;\n\n /** Tags for filtering */\n tags: string[];\n\n /** When this memory was stored */\n stored_at: Date;\n\n /** Last access time */\n last_accessed?: Date;\n\n /** Access count */\n access_count: number;\n\n /** Is this in core memory? */\n is_core: boolean;\n\n /** Source files (optional) */\n source_files?: string[];\n\n /** Conflicting memory IDs */\n conflicts_with?: string[];\n}\n\n// ============================================================================\n// Working Memory Context\n// ============================================================================\n\n/**\n * Context for loading working memory (Limo requirement)\n */\nexport interface WorkingMemoryContext {\n /** Current task description */\n currentTask: string;\n\n /** Keywords for relevance matching */\n keywords: string[];\n\n /** Relevant categories (optional) */\n categories?: string[];\n}\n\n// ============================================================================\n// Memory Configuration\n// ============================================================================\n\n/**\n * Core memory budget configuration\n */\nexport interface CoreMemoryBudget {\n /** Maximum number of items */\n maxItems: number;\n\n /** Maximum total size in bytes */\n maxTotalSize: number;\n}\n\n/**\n * Detailed memory configuration\n */\nexport interface DetailedMemoryConfig {\n /** Maximum size in bytes */\n maxSize: number;\n}\n\n/**\n * Memory configuration\n */\nexport interface MemoryConfig {\n /** Core memory budget */\n coreBudget: CoreMemoryBudget;\n\n /** Detailed memory configuration */\n detailed?: DetailedMemoryConfig;\n\n /** Enable AI compression */\n compressionEnabled?: boolean;\n}\n\n// ============================================================================\n// Memory Statistics\n// ============================================================================\n\n/**\n * Memory statistics\n */\nexport interface MemoryStats {\n /** Core memories count */\n coreCount: number;\n\n /** Detailed memories count */\n detailedCount: number;\n\n /** Total memories */\n totalCount: number;\n\n /** Core size in bytes */\n coreSize: number;\n\n /** Detailed size in bytes */\n detailedSize: number;\n\n /** Total size in bytes */\n totalSize: number;\n\n /** Core utilization (0-1) */\n coreUtilization: number;\n\n /** Detailed utilization (0-1) */\n detailedUtilization: number;\n}\n\n// ============================================================================\n// Relevance Score\n// ============================================================================\n\n/**\n * Relevance score breakdown\n */\nexport interface RelevanceScore {\n /** Total score (0-100) */\n total: number;\n\n /** Category match score */\n categoryScore: number;\n\n /** Tags match score */\n tagsScore: number;\n\n /** Importance score */\n importanceScore: number;\n\n /** Recency score */\n recencyScore: number;\n}\n\n// ============================================================================\n// Default Configuration\n// ============================================================================\n\n/**\n * Default memory configuration\n */\nexport const DEFAULT_MEMORY_CONFIG: Required<MemoryConfig> = {\n coreBudget: {\n maxItems: 10,\n maxTotalSize: 8192 // 8KB\n },\n detailed: {\n maxSize: 102400 // 100KB\n },\n compressionEnabled: true\n};\n","/**\n * Deity 4.0 - Limo Memory Manager\n *\n * Simplified tiered memory manager focused on Limo-specific requirements:\n * - loadWorkingMemory() - Context-based memory loading\n * - Relevance scoring - Category + tags + importance + recency\n * - Core/detailed dual-layer architecture\n *\n * Based on Deity POC, simplified for v4.0\n */\n\nimport type {\n Memory,\n WorkingMemoryContext,\n MemoryConfig,\n MemoryStats,\n RelevanceScore\n} from './types.js';\nimport { DEFAULT_MEMORY_CONFIG } from './types.js';\n\n// ============================================================================\n// Limo Memory Manager\n// ============================================================================\n\n/**\n * Simplified tiered memory manager\n *\n * Focus: Limo-specific features\n * - loadWorkingMemory() with relevance scoring\n * - Core/detailed layers\n * - Simple promotion/demotion\n */\nexport class LimoMemoryManager {\n private config: Required<MemoryConfig>;\n private coreMemories: Map<string, Memory> = new Map();\n private detailedMemories: Map<string, Memory> = new Map();\n\n constructor(config?: MemoryConfig) {\n this.config = {\n ...DEFAULT_MEMORY_CONFIG,\n ...config,\n coreBudget: {\n ...DEFAULT_MEMORY_CONFIG.coreBudget,\n ...config?.coreBudget\n },\n detailed: {\n ...DEFAULT_MEMORY_CONFIG.detailed,\n ...config?.detailed\n }\n };\n }\n\n // ============================================================================\n // Public API\n // ============================================================================\n\n /**\n * Store a memory\n */\n async set(key: string, value: unknown): Promise<void> {\n const content = typeof value === 'string' ? value : JSON.stringify(value);\n\n const memory: Memory = {\n id: key,\n content,\n importance: 5, // Default importance\n tags: [],\n stored_at: new Date(),\n access_count: 0,\n is_core: false\n };\n\n // Store in detailed by default\n this.detailedMemories.set(key, memory);\n\n // Enforce budget\n await this.enforceDetailedBudget();\n }\n\n /**\n * Get a memory\n */\n async get(key: string): Promise<unknown> {\n const memory = this.coreMemories.get(key) || this.detailedMemories.get(key);\n\n if (!memory) {\n return undefined;\n }\n\n // Update access metadata\n this.updateAccessMetadata(memory);\n\n // Try to parse as JSON, fallback to string\n try {\n return JSON.parse(memory.content);\n } catch {\n return memory.content;\n }\n }\n\n /**\n * Check if memory exists\n */\n async has(key: string): Promise<boolean> {\n return this.coreMemories.has(key) || this.detailedMemories.has(key);\n }\n\n /**\n * Delete a memory\n */\n async delete(key: string): Promise<void> {\n this.coreMemories.delete(key);\n this.detailedMemories.delete(key);\n }\n\n /**\n * Clear all memories\n */\n async clear(): Promise<void> {\n this.coreMemories.clear();\n this.detailedMemories.clear();\n }\n\n /**\n * Load working memory based on context (Limo requirement)\n *\n * Algorithm:\n * 1. Start with core memories (always relevant)\n * 2. Score detailed memories by relevance\n * 3. Select top N most relevant\n * 4. Update access counts\n */\n loadWorkingMemory(context: WorkingMemoryContext): Memory[] {\n // 1. Always include core memories\n const coreMemories = Array.from(this.coreMemories.values());\n\n // 2. Score detailed memories\n const scoredDetailed = Array.from(this.detailedMemories.values())\n .map(memory => ({\n memory,\n score: this.calculateRelevance(memory, context)\n }))\n .filter(item => item.score.total > 30) // Relevance threshold\n .sort((a, b) => b.score.total - a.score.total);\n\n // 3. Select top 20 most relevant\n const topRelevant = scoredDetailed\n .slice(0, 20)\n .map(item => item.memory);\n\n // 4. Update access counts\n for (const memory of [...coreMemories, ...topRelevant]) {\n this.updateAccessMetadata(memory);\n }\n\n return [...coreMemories, ...topRelevant];\n }\n\n /**\n * Get core memories\n */\n getCoreMemories(): Memory[] {\n return Array.from(this.coreMemories.values());\n }\n\n /**\n * Get detailed memories\n */\n getDetailedMemories(): Memory[] {\n return Array.from(this.detailedMemories.values());\n }\n\n /**\n * Get all memory keys (core + detailed)\n *\n * @returns Array of all memory keys\n */\n getAllKeys(): string[] {\n const keys = new Set<string>();\n for (const key of this.coreMemories.keys()) keys.add(key);\n for (const key of this.detailedMemories.keys()) keys.add(key);\n return Array.from(keys);\n }\n\n /**\n * Get all Memory objects (core + detailed)\n *\n * @returns Array of all Memory entries\n */\n getAllMemories(): Memory[] {\n return [\n ...Array.from(this.coreMemories.values()),\n ...Array.from(this.detailedMemories.values()),\n ];\n }\n\n /**\n * Get raw Memory object by key (without triggering access metadata update)\n *\n * @param key - Memory key\n * @returns Memory object or undefined\n */\n getMemory(key: string): Memory | undefined {\n return this.coreMemories.get(key) || this.detailedMemories.get(key);\n }\n\n /**\n * Update an existing memory entry\n *\n * @param key - Memory key to update\n * @param updates - Partial updates (content, importance, category, tags)\n * @returns true if updated, false if key not found\n */\n async update(\n key: string,\n updates: Partial<{ content: string; importance: number; category: string; tags: string[] }>\n ): Promise<boolean> {\n const memory = this.coreMemories.get(key) || this.detailedMemories.get(key);\n if (!memory) return false;\n\n if (updates.content !== undefined) memory.content = updates.content;\n if (updates.importance !== undefined) memory.importance = updates.importance;\n if (updates.category !== undefined) memory.category = updates.category;\n if (updates.tags !== undefined) memory.tags = updates.tags;\n\n return true;\n }\n\n /**\n * Promote a memory to core by key\n *\n * @param key - Memory key to promote\n * @returns true if promoted, false if key not found or already in core\n */\n promoteToCoreByKey(key: string): boolean {\n const memory = this.detailedMemories.get(key);\n if (!memory) {\n // Already in core or doesn't exist\n return this.coreMemories.has(key) ? false : false;\n }\n\n this.promoteToCore(memory);\n return true;\n }\n\n /**\n * Demote a memory from core to detailed by key\n *\n * @param key - Memory key to demote\n * @returns true if demoted, false if key not found in core\n */\n demoteFromCore(key: string): boolean {\n const memory = this.coreMemories.get(key);\n if (!memory) return false;\n\n memory.is_core = false;\n this.detailedMemories.set(memory.id, memory);\n this.coreMemories.delete(memory.id);\n return true;\n }\n\n /**\n * Get memory statistics\n */\n getStats(): MemoryStats {\n const coreMemories = Array.from(this.coreMemories.values());\n const detailedMemories = Array.from(this.detailedMemories.values());\n\n const coreSize = coreMemories.reduce((sum, m) => sum + m.content.length, 0);\n const detailedSize = detailedMemories.reduce((sum, m) => sum + m.content.length, 0);\n\n return {\n coreCount: coreMemories.length,\n detailedCount: detailedMemories.length,\n totalCount: coreMemories.length + detailedMemories.length,\n coreSize,\n detailedSize,\n totalSize: coreSize + detailedSize,\n coreUtilization: coreSize / this.config.coreBudget.maxTotalSize,\n detailedUtilization: detailedSize / this.config.detailed.maxSize\n };\n }\n\n // ============================================================================\n // Relevance Scoring (Limo-specific algorithm)\n // ============================================================================\n\n /**\n * Calculate relevance score for a memory\n *\n * Algorithm (from LIMO_DEITY_CONSENSUS.md):\n * - Category match: 40%\n * - Tags match (Jaccard): 30%\n * - Importance: 20%\n * - Recency: 10%\n */\n private calculateRelevance(\n memory: Memory,\n context: WorkingMemoryContext\n ): RelevanceScore {\n let categoryScore = 0;\n let tagsScore = 0;\n let importanceScore = 0;\n let recencyScore = 0;\n\n // 1. Category match (40%)\n if (context.categories && memory.category && context.categories.includes(memory.category)) {\n categoryScore = 40;\n }\n\n // 2. Tags match - Jaccard similarity (30%)\n if (context.keywords.length > 0 && memory.tags.length > 0) {\n const intersection = context.keywords.filter(k =>\n memory.tags.some(t => t.toLowerCase() === k.toLowerCase())\n ).length;\n const union = new Set([...context.keywords, ...memory.tags]).size;\n tagsScore = (intersection / union) * 30;\n }\n\n // 3. Importance (20%)\n importanceScore = (memory.importance / 10) * 20;\n\n // 4. Recency (10%)\n const ageInDays = this.calculateAgeInDays(memory.stored_at);\n const recency = Math.max(0, 1 - (ageInDays / 30)); // 30-day window\n recencyScore = recency * 10;\n\n return {\n total: categoryScore + tagsScore + importanceScore + recencyScore,\n categoryScore,\n tagsScore,\n importanceScore,\n recencyScore\n };\n }\n\n // ============================================================================\n // Internal Helpers\n // ============================================================================\n\n /**\n * Update access metadata\n */\n private updateAccessMetadata(memory: Memory): void {\n memory.access_count++;\n memory.last_accessed = new Date();\n\n // Promote to core if frequently accessed\n if (!memory.is_core && memory.access_count >= 5 && memory.importance >= 7) {\n this.promoteToCore(memory);\n }\n }\n\n /**\n * Promote memory to core\n */\n private promoteToCore(memory: Memory): void {\n // Check if already in core\n if (this.coreMemories.has(memory.id)) {\n return;\n }\n\n // Check core budget\n const coreSize = Array.from(this.coreMemories.values())\n .reduce((sum, m) => sum + m.content.length, 0);\n\n const requiredSpace = memory.content.length;\n\n // Enforce budget\n if (\n this.coreMemories.size >= this.config.coreBudget.maxItems ||\n coreSize + requiredSpace > this.config.coreBudget.maxTotalSize\n ) {\n this.demoteLowValueMemories();\n }\n\n // Move to core\n memory.is_core = true;\n this.coreMemories.set(memory.id, memory);\n this.detailedMemories.delete(memory.id);\n }\n\n /**\n * Demote low-value memories from core\n */\n private demoteLowValueMemories(): void {\n const coreMemories = Array.from(this.coreMemories.values());\n\n // Sort by access count (ascending - least accessed first)\n const sorted = coreMemories.sort((a, b) => a.access_count - b.access_count);\n\n // Demote lowest 1/3\n const demoteCount = Math.max(1, Math.floor(sorted.length / 3));\n for (let i = 0; i < demoteCount; i++) {\n const memory = sorted[i];\n memory.is_core = false;\n this.detailedMemories.set(memory.id, memory);\n this.coreMemories.delete(memory.id);\n }\n }\n\n /**\n * Enforce detailed memory budget\n */\n private async enforceDetailedBudget(): Promise<void> {\n const detailedMemories = Array.from(this.detailedMemories.values());\n const currentSize = detailedMemories.reduce((sum, m) => sum + m.content.length, 0);\n\n if (currentSize <= this.config.detailed.maxSize) {\n return;\n }\n\n // Sort by last accessed (oldest first)\n const sorted = detailedMemories.sort((a, b) => {\n const timeA = (a.last_accessed || a.stored_at).getTime();\n const timeB = (b.last_accessed || b.stored_at).getTime();\n return timeA - timeB;\n });\n\n // Remove oldest until within budget\n let totalSize = currentSize;\n for (const memory of sorted) {\n if (totalSize <= this.config.detailed.maxSize) break;\n\n this.detailedMemories.delete(memory.id);\n totalSize -= memory.content.length;\n }\n }\n\n /**\n * Calculate age in days\n */\n private calculateAgeInDays(date: Date): number {\n const now = new Date();\n const diffMs = now.getTime() - date.getTime();\n return diffMs / (1000 * 60 * 60 * 24);\n }\n}\n","/**\n * Deity 4.0 - Session Types\n *\n * Types for session persistence and recovery\n */\n\nimport { z } from 'zod';\nimport type { ConversationMessage } from '../conversation/types.js';\nimport type { Memory } from '../memory/types.js';\nimport type { ExecutionStats } from '../engine/types.js';\n\n// ============================================================================\n// Session Data\n// ============================================================================\n\n/**\n * Complete session state\n */\nexport interface SessionData {\n /** Session identifier */\n sessionId: string;\n\n /** Workflow name */\n workflowName: string;\n\n /** Conversation messages */\n messages: ConversationMessage[];\n\n /** Memory entries */\n memories: Memory[];\n\n /** Execution statistics */\n stats: ExecutionStats;\n\n /** Stage outputs (checkpoint data) */\n stageOutputs: Record<string, unknown>;\n\n /** Application state (isolated from AI memory) */\n appState?: Record<string, unknown>;\n\n /** Session metadata */\n metadata: SessionMetadata;\n}\n\n// ============================================================================\n// Session Metadata\n// ============================================================================\n\n/**\n * Session metadata\n */\nexport interface SessionMetadata {\n /** When session was created */\n createdAt: Date;\n\n /** When session was last updated */\n updatedAt: Date;\n\n /** Current stage being executed */\n currentStage?: string;\n\n /** Completed stages */\n completedStages: string[];\n\n /** Failed stages */\n failedStages: string[];\n\n /** Session status */\n status: SessionStatus;\n\n /** User-defined tags */\n tags?: string[];\n\n /** User-defined notes */\n notes?: string;\n}\n\n/**\n * Session status\n */\nexport type SessionStatus =\n | 'active' // Currently running\n | 'paused' // Paused mid-execution\n | 'completed' // Successfully completed\n | 'failed' // Failed permanently\n | 'archived'; // Archived (no longer active)\n\n// ============================================================================\n// Session Configuration\n// ============================================================================\n\n/**\n * Session store configuration\n */\nexport interface SessionConfig {\n /** Base directory for session files */\n directory: string;\n\n /** Auto-save interval in milliseconds (0 = disabled) */\n autoSaveInterval?: number;\n\n /** Keep backup files */\n keepBackups?: boolean;\n\n /** Max backup files to keep */\n maxBackups?: number;\n\n /** Compress session files */\n compress?: boolean;\n}\n\n/**\n * Default session configuration\n */\nexport const DEFAULT_SESSION_CONFIG: Required<SessionConfig> = {\n directory: '.deity/sessions',\n autoSaveInterval: 30000, // 30 seconds\n keepBackups: true,\n maxBackups: 5,\n compress: false\n};\n\n// ============================================================================\n// Session Store Interface\n// ============================================================================\n\n/**\n * Session store interface\n */\nexport interface SessionStore {\n /**\n * Save session data\n */\n save(data: SessionData): Promise<void>;\n\n /**\n * Load session data\n */\n load(sessionId: string): Promise<SessionData | null>;\n\n /**\n * Check if session exists\n */\n exists(sessionId: string): Promise<boolean>;\n\n /**\n * Delete session\n */\n delete(sessionId: string): Promise<void>;\n\n /**\n * List all sessions\n */\n list(): Promise<SessionMetadata[]>;\n\n /**\n * Create backup of session\n */\n backup(sessionId: string): Promise<void>;\n\n /**\n * Restore from backup\n */\n restore(sessionId: string, backupIndex?: number): Promise<SessionData>;\n\n /**\n * Clean up old backups\n */\n cleanupBackups(sessionId: string): Promise<void>;\n}\n\n// ============================================================================\n// Recovery Types\n// ============================================================================\n\n/**\n * Recovery result\n */\nexport interface RecoveryResult {\n /** Recovery succeeded */\n success: boolean;\n\n /** Recovered session data (if successful) */\n data?: SessionData;\n\n /** Recovery errors/warnings */\n errors: string[];\n\n /** Data that couldn't be recovered */\n lost?: Partial<SessionData>;\n}\n\n/**\n * Serialization metadata\n */\nexport interface SerializationMetadata {\n /** Serialization format version */\n version: string;\n\n /** Serialization timestamp */\n timestamp: Date;\n\n /** Fields with special serialization */\n specialFields?: {\n field: string;\n type: 'Date' | 'Set' | 'Map' | 'RegExp';\n }[];\n}\n\n// ============================================================================\n// Paused Session Types (ADR-001)\n// ============================================================================\n\n/**\n * Reason for pausing execution\n */\nexport type PauseReason = 'manual' | 'timeout' | 'error';\n\n/**\n * Paused session state - contains serialized execution context\n */\nexport interface PausedSessionState {\n /** Workflow inputs (arbitrary type) */\n inputs: unknown;\n\n /** Component outputs (componentId -> output) */\n outputs: Record<string, unknown>;\n\n /** Serialized conversation state (optional) */\n conversation?: string;\n\n /** Serialized memory state (optional) */\n memory?: string;\n\n /** Serialized application state (optional) */\n appState?: string;\n\n /** Execution statistics */\n stats: ExecutionStats;\n}\n\n/**\n * Paused session metadata\n */\nexport interface PausedSessionMetadata {\n /** Reason for pausing */\n pauseReason: PauseReason;\n\n /** Whether session can be resumed */\n resumable: boolean;\n\n /** Optional notes about the pause */\n notes?: string;\n}\n\n/**\n * Complete paused session structure\n */\nexport interface PausedSession {\n /** Session identifier */\n sessionId: string;\n\n /** Workflow name */\n workflowName: string;\n\n /** ISO 8601 timestamp when paused */\n pausedAt: string;\n\n /** Deity framework version (for compatibility checks) */\n version: string;\n\n /** Serialized execution state */\n state: PausedSessionState;\n\n /** Pause metadata */\n metadata: PausedSessionMetadata;\n}\n\n// ============================================================================\n// Zod Schemas for Validation (ADR-001)\n// ============================================================================\n\n/**\n * Zod schema for PauseReason\n */\nexport const PauseReasonSchema = z.enum(['manual', 'timeout', 'error']);\n\n/**\n * Zod schema for ExecutionStats (basic validation)\n * Note: Full schema should be imported from engine/types if available\n */\nconst ExecutionStatsSchema = z.object({\n totalToolCalls: z.number().int().min(0),\n totalRetries: z.number().int().min(0),\n}).passthrough(); // Allow additional fields\n\n/**\n * Zod schema for PausedSessionState\n */\nexport const PausedSessionStateSchema = z.object({\n inputs: z.unknown(),\n outputs: z.record(z.string(), z.unknown()),\n conversation: z.string().optional(),\n memory: z.string().optional(),\n appState: z.string().optional(),\n stats: ExecutionStatsSchema,\n});\n\n/**\n * Zod schema for PausedSessionMetadata\n */\nexport const PausedSessionMetadataSchema = z.object({\n pauseReason: PauseReasonSchema,\n resumable: z.boolean(),\n notes: z.string().optional(),\n});\n\n/**\n * Zod schema for PausedSession\n */\nexport const PausedSessionSchema = z.object({\n sessionId: z.string().min(1, 'Session ID cannot be empty'),\n workflowName: z.string().min(1, 'Workflow name cannot be empty'),\n pausedAt: z.string().datetime('Must be ISO 8601 datetime'),\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/, 'Must be semver format (e.g., 4.0.0)'),\n state: PausedSessionStateSchema,\n metadata: PausedSessionMetadataSchema,\n});\n\n/**\n * Infer TypeScript type from Zod schema (for validation)\n */\nexport type PausedSessionValidated = z.infer<typeof PausedSessionSchema>;\n\n","/**\n * Deity 4.0 - Session Serializer\n *\n * Handles serialization/deserialization of complex types (Date, Set, Map)\n */\n\nimport type { SessionData, SerializationMetadata } from './types.js';\n\n// ============================================================================\n// Type Markers\n// ============================================================================\n\nconst TYPE_MARKERS = {\n DATE: '__deity_date__',\n SET: '__deity_set__',\n MAP: '__deity_map__',\n REGEXP: '__deity_regexp__'\n} as const;\n\n/**\n * Serialized value wrapper\n */\ninterface SerializedValue {\n __type: string;\n value: unknown;\n}\n\n// ============================================================================\n// Serializer\n// ============================================================================\n\n/**\n * Session serializer\n */\nexport class SessionSerializer {\n private metadata: SerializationMetadata;\n\n constructor() {\n this.metadata = {\n version: '4.0.0',\n timestamp: new Date(),\n specialFields: []\n };\n }\n\n /**\n * Serialize session data to JSON-safe object\n */\n serialize(data: SessionData): { data: unknown; metadata: SerializationMetadata } {\n this.metadata.timestamp = new Date();\n this.metadata.specialFields = [];\n\n const serialized = this.serializeValue(data, '');\n\n return {\n data: serialized,\n metadata: this.metadata\n };\n }\n\n /**\n * Deserialize session data from JSON-safe object\n */\n deserialize(data: unknown, _metadata?: SerializationMetadata): SessionData {\n return this.deserializeValue(data) as SessionData;\n }\n\n /**\n * Serialize any value\n */\n private serializeValue(value: unknown, path: string): unknown {\n // Null/undefined\n if (value === null || value === undefined) {\n return value;\n }\n\n // Date\n if (value instanceof Date) {\n this.metadata.specialFields?.push({ field: path, type: 'Date' });\n return {\n __type: TYPE_MARKERS.DATE,\n value: value.toISOString()\n } as SerializedValue;\n }\n\n // Set\n if (value instanceof Set) {\n this.metadata.specialFields?.push({ field: path, type: 'Set' });\n return {\n __type: TYPE_MARKERS.SET,\n value: Array.from(value).map((item, i) =>\n this.serializeValue(item, `${path}[${i}]`)\n )\n } as SerializedValue;\n }\n\n // Map\n if (value instanceof Map) {\n this.metadata.specialFields?.push({ field: path, type: 'Map' });\n return {\n __type: TYPE_MARKERS.MAP,\n value: Array.from(value.entries()).map(([k, v], i) => [\n this.serializeValue(k, `${path}.key[${i}]`),\n this.serializeValue(v, `${path}.value[${i}]`)\n ])\n } as SerializedValue;\n }\n\n // RegExp\n if (value instanceof RegExp) {\n this.metadata.specialFields?.push({ field: path, type: 'RegExp' });\n return {\n __type: TYPE_MARKERS.REGEXP,\n value: {\n source: value.source,\n flags: value.flags\n }\n } as SerializedValue;\n }\n\n // Array\n if (Array.isArray(value)) {\n return value.map((item, i) =>\n this.serializeValue(item, `${path}[${i}]`)\n );\n }\n\n // Object\n if (typeof value === 'object') {\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n result[key] = this.serializeValue(val, path ? `${path}.${key}` : key);\n }\n return result;\n }\n\n // Primitive\n return value;\n }\n\n /**\n * Deserialize any value\n */\n private deserializeValue(value: unknown): unknown {\n // Null/undefined\n if (value === null || value === undefined) {\n return value;\n }\n\n // Array\n if (Array.isArray(value)) {\n return value.map(item => this.deserializeValue(item));\n }\n\n // Object\n if (typeof value === 'object') {\n const obj = value as Record<string, unknown>;\n\n // Check for type marker\n if ('__type' in obj && typeof obj.__type === 'string') {\n return this.deserializeSpecialType(obj as unknown as SerializedValue);\n }\n\n // Regular object\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(obj)) {\n result[key] = this.deserializeValue(val);\n }\n return result;\n }\n\n // Primitive\n return value;\n }\n\n /**\n * Deserialize special type\n */\n private deserializeSpecialType(value: SerializedValue): unknown {\n switch (value.__type) {\n case TYPE_MARKERS.DATE:\n return new Date(value.value as string);\n\n case TYPE_MARKERS.SET:\n return new Set(\n (value.value as unknown[]).map(item => this.deserializeValue(item))\n );\n\n case TYPE_MARKERS.MAP:\n return new Map(\n (value.value as [unknown, unknown][]).map(([k, v]) => [\n this.deserializeValue(k),\n this.deserializeValue(v)\n ])\n );\n\n case TYPE_MARKERS.REGEXP:\n const { source, flags } = value.value as { source: string; flags: string };\n return new RegExp(source, flags);\n\n default:\n // Unknown type - return as-is\n return value;\n }\n }\n}\n\n// ============================================================================\n// Utility Functions\n// ============================================================================\n\n/**\n * Create serializer instance\n */\nexport function createSerializer(): SessionSerializer {\n return new SessionSerializer();\n}\n\n/**\n * Quick serialize\n */\nexport function serialize(data: SessionData): string {\n const serializer = createSerializer();\n const { data: serialized, metadata } = serializer.serialize(data);\n return JSON.stringify({ data: serialized, metadata }, null, 2);\n}\n\n/**\n * Quick deserialize\n */\nexport function deserialize(json: string): SessionData {\n const parsed = JSON.parse(json);\n const serializer = createSerializer();\n return serializer.deserialize(parsed.data, parsed.metadata);\n}\n\n/**\n * Validate serialized data\n */\nexport function validateSerialized(json: string): { valid: boolean; errors: string[] } {\n const errors: string[] = [];\n\n try {\n const parsed = JSON.parse(json);\n\n // Check structure\n if (!parsed.data) {\n errors.push('Missing data field');\n }\n\n if (!parsed.metadata) {\n errors.push('Missing metadata field');\n }\n\n // Check metadata\n if (parsed.metadata) {\n if (!parsed.metadata.version) {\n errors.push('Missing metadata.version');\n }\n if (!parsed.metadata.timestamp) {\n errors.push('Missing metadata.timestamp');\n }\n }\n\n // Try to deserialize\n if (errors.length === 0) {\n deserialize(json);\n }\n } catch (error) {\n errors.push(`Parse error: ${error instanceof Error ? error.message : String(error)}`);\n }\n\n return {\n valid: errors.length === 0,\n errors\n };\n}\n","/**\n * Deity 4.0 - FileSystem Session Store\n *\n * Single-file JSON storage for session data\n */\n\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport type {\n SessionStore,\n SessionData,\n SessionConfig,\n SessionMetadata,\n RecoveryResult\n} from './types.js';\nimport { DEFAULT_SESSION_CONFIG } from './types.js';\nimport { SessionSerializer } from './serializer.js';\n\n// ============================================================================\n// FileSystem Session Store\n// ============================================================================\n\n/**\n * FileSystem-based session store\n */\nexport class FileSystemSessionStore implements SessionStore {\n private config: Required<SessionConfig>;\n private serializer: SessionSerializer;\n private autoSaveTimers: Map<string, NodeJS.Timeout> = new Map();\n\n constructor(config?: SessionConfig) {\n this.config = {\n ...DEFAULT_SESSION_CONFIG,\n ...config\n };\n this.serializer = new SessionSerializer();\n }\n\n /**\n * Initialize store (create directories)\n */\n async init(): Promise<void> {\n await fs.mkdir(this.config.directory, { recursive: true });\n\n // Create backups directory if enabled\n if (this.config.keepBackups) {\n const backupsDir = path.join(this.config.directory, 'backups');\n await fs.mkdir(backupsDir, { recursive: true });\n }\n }\n\n // ============================================================================\n // Core Operations\n // ============================================================================\n\n /**\n * Save session data\n */\n async save(data: SessionData): Promise<void> {\n // Update metadata\n data.metadata.updatedAt = new Date();\n\n // Serialize\n const { data: serialized, metadata } = this.serializer.serialize(data);\n\n // Write to file\n const filePath = this.getSessionPath(data.sessionId);\n const content = JSON.stringify({ data: serialized, metadata }, null, 2);\n\n await fs.writeFile(filePath, content, 'utf-8');\n\n // Create backup if enabled\n if (this.config.keepBackups) {\n await this.backup(data.sessionId);\n await this.cleanupBackups(data.sessionId);\n }\n\n // Schedule auto-save if enabled\n if (this.config.autoSaveInterval > 0) {\n this.scheduleAutoSave(data);\n }\n }\n\n /**\n * Load session data\n */\n async load(sessionId: string): Promise<SessionData | null> {\n try {\n const filePath = this.getSessionPath(sessionId);\n const content = await fs.readFile(filePath, 'utf-8');\n const parsed = JSON.parse(content);\n\n return this.serializer.deserialize(parsed.data, parsed.metadata);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return null;\n }\n throw error;\n }\n }\n\n /**\n * Check if session exists\n */\n async exists(sessionId: string): Promise<boolean> {\n try {\n const filePath = this.getSessionPath(sessionId);\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Delete session\n */\n async delete(sessionId: string): Promise<void> {\n // Cancel auto-save\n const timer = this.autoSaveTimers.get(sessionId);\n if (timer) {\n clearTimeout(timer);\n this.autoSaveTimers.delete(sessionId);\n }\n\n // Delete main file\n const filePath = this.getSessionPath(sessionId);\n try {\n await fs.unlink(filePath);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n\n // Delete backups\n if (this.config.keepBackups) {\n const backupsDir = this.getBackupsDir(sessionId);\n try {\n await fs.rm(backupsDir, { recursive: true, force: true });\n } catch {\n // Ignore errors\n }\n }\n }\n\n /**\n * List all sessions\n */\n async list(): Promise<SessionMetadata[]> {\n try {\n const files = await fs.readdir(this.config.directory);\n const sessions: SessionMetadata[] = [];\n\n for (const file of files) {\n if (file.endsWith('.json') && file !== 'backups') {\n const sessionId = file.replace('.json', '');\n const data = await this.load(sessionId);\n if (data) {\n sessions.push(data.metadata);\n }\n }\n }\n\n return sessions.sort((a, b) =>\n b.updatedAt.getTime() - a.updatedAt.getTime()\n );\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return [];\n }\n throw error;\n }\n }\n\n // ============================================================================\n // Backup Operations\n // ============================================================================\n\n /**\n * Create backup of session\n */\n async backup(sessionId: string): Promise<void> {\n if (!this.config.keepBackups) {\n return;\n }\n\n const sourcePath = this.getSessionPath(sessionId);\n const backupsDir = this.getBackupsDir(sessionId);\n\n // Create backups directory\n await fs.mkdir(backupsDir, { recursive: true });\n\n // Generate backup filename with timestamp\n const timestamp = new Date().toISOString().replace(/:/g, '-');\n const backupPath = path.join(backupsDir, `${timestamp}.json`);\n\n // Copy file\n try {\n await fs.copyFile(sourcePath, backupPath);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n }\n\n /**\n * Restore from backup\n */\n async restore(sessionId: string, backupIndex: number = 0): Promise<SessionData> {\n const backupsDir = this.getBackupsDir(sessionId);\n\n // List backups\n const backups = await fs.readdir(backupsDir);\n const sortedBackups = backups\n .filter(f => f.endsWith('.json'))\n .sort()\n .reverse(); // Most recent first\n\n if (backupIndex >= sortedBackups.length) {\n throw new Error(`Backup index ${backupIndex} out of range (max: ${sortedBackups.length - 1})`);\n }\n\n // Read backup\n const backupPath = path.join(backupsDir, sortedBackups[backupIndex]);\n const content = await fs.readFile(backupPath, 'utf-8');\n const parsed = JSON.parse(content);\n\n return this.serializer.deserialize(parsed.data, parsed.metadata);\n }\n\n /**\n * Clean up old backups\n */\n async cleanupBackups(sessionId: string): Promise<void> {\n if (!this.config.keepBackups) {\n return;\n }\n\n const backupsDir = this.getBackupsDir(sessionId);\n\n try {\n // List backups\n const backups = await fs.readdir(backupsDir);\n const sortedBackups = backups\n .filter(f => f.endsWith('.json'))\n .sort()\n .reverse(); // Most recent first\n\n // Delete old backups\n const toDelete = sortedBackups.slice(this.config.maxBackups);\n for (const backup of toDelete) {\n const backupPath = path.join(backupsDir, backup);\n await fs.unlink(backupPath);\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n }\n\n // ============================================================================\n // Recovery Operations\n // ============================================================================\n\n /**\n * Attempt to recover corrupted session\n */\n async recover(sessionId: string): Promise<RecoveryResult> {\n const errors: string[] = [];\n let data: SessionData | undefined;\n let lost: Partial<SessionData> | undefined;\n\n try {\n // Try to load normally\n const loaded = await this.load(sessionId);\n if (loaded) {\n return { success: true, data: loaded, errors: [] };\n }\n } catch (error) {\n errors.push(`Failed to load session: ${error instanceof Error ? error.message : String(error)}`);\n }\n\n // Try to recover from backup\n if (this.config.keepBackups) {\n try {\n data = await this.restore(sessionId, 0);\n errors.push('Recovered from most recent backup');\n return { success: true, data, errors };\n } catch (error) {\n errors.push(`Failed to restore from backup: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n // Try to parse corrupted file\n try {\n const filePath = this.getSessionPath(sessionId);\n const content = await fs.readFile(filePath, 'utf-8');\n const parsed = JSON.parse(content);\n\n // Partial recovery\n lost = {};\n const recovered: Partial<SessionData> = {};\n\n // Try to recover each field\n const fields: (keyof SessionData)[] = [\n 'sessionId',\n 'workflowName',\n 'messages',\n 'memories',\n 'stats',\n 'stageOutputs',\n 'metadata'\n ];\n\n for (const field of fields) {\n try {\n if (parsed.data?.[field]) {\n recovered[field] = this.serializer.deserialize(parsed.data[field]) as never;\n } else {\n lost[field] = undefined as never;\n }\n } catch {\n lost[field] = parsed.data?.[field] as never;\n }\n }\n\n if (Object.keys(recovered).length > 0) {\n data = recovered as SessionData;\n errors.push('Partial recovery successful');\n return { success: true, data, errors, lost };\n }\n } catch (error) {\n errors.push(`Failed to parse corrupted file: ${error instanceof Error ? error.message : String(error)}`);\n }\n\n return { success: false, errors };\n }\n\n // ============================================================================\n // Helper Methods\n // ============================================================================\n\n /**\n * Get session file path\n */\n private getSessionPath(sessionId: string): string {\n return path.join(this.config.directory, `${sessionId}.json`);\n }\n\n /**\n * Get backups directory for session\n */\n private getBackupsDir(sessionId: string): string {\n return path.join(this.config.directory, 'backups', sessionId);\n }\n\n /**\n * Schedule auto-save\n */\n private scheduleAutoSave(data: SessionData): void {\n // Cancel existing timer\n const existingTimer = this.autoSaveTimers.get(data.sessionId);\n if (existingTimer) {\n clearTimeout(existingTimer);\n }\n\n // Schedule new timer\n const timer = setTimeout(async () => {\n try {\n await this.save(data);\n } catch (error) {\n // Auto-save failed silently - session data remains at last successful save point\n }\n }, this.config.autoSaveInterval);\n\n this.autoSaveTimers.set(data.sessionId, timer);\n }\n\n /**\n * Cleanup (cancel all auto-save timers)\n */\n cleanup(): void {\n for (const timer of this.autoSaveTimers.values()) {\n clearTimeout(timer);\n }\n this.autoSaveTimers.clear();\n }\n}\n\n// ============================================================================\n// Factory Function\n// ============================================================================\n\n/**\n * Create FileSystem session store\n */\nexport function createSessionStore(config?: SessionConfig): FileSystemSessionStore {\n return new FileSystemSessionStore(config);\n}\n","/**\n * Deity 4.0 - In-Memory Stores\n *\n * Simple in-memory implementations for testing\n */\n\nimport type { StateStore, TraceLogger, TraceEntry } from './types.js';\n\n// ============================================================================\n// In-Memory State Store\n// ============================================================================\n\n/**\n * Simple in-memory state store\n */\nexport class InMemoryStore implements StateStore {\n private data = new Map<string, unknown>();\n\n async get(key: string): Promise<unknown> {\n return this.data.get(key);\n }\n\n async set(key: string, value: unknown): Promise<void> {\n this.data.set(key, value);\n }\n\n async has(key: string): Promise<boolean> {\n return this.data.has(key);\n }\n\n async delete(key: string): Promise<void> {\n this.data.delete(key);\n }\n\n async clear(): Promise<void> {\n this.data.clear();\n }\n\n // Extra methods beyond StateStore interface\n size(): number {\n return this.data.size;\n }\n\n keys(): string[] {\n return Array.from(this.data.keys());\n }\n\n entries(): [string, unknown][] {\n return Array.from(this.data.entries());\n }\n\n values(): unknown[] {\n return Array.from(this.data.values());\n }\n}\n\n// ============================================================================\n// In-Memory Trace Logger\n// ============================================================================\n\n/**\n * Simple in-memory trace logger\n */\nexport class InMemoryTrace implements TraceLogger {\n private entries: TraceEntry[] = [];\n\n async log(entry: TraceEntry): Promise<void> {\n this.entries.push(entry);\n }\n\n async getEntries(): Promise<TraceEntry[]> {\n return [...this.entries];\n }\n\n // Extra methods for testing\n clear(): void {\n this.entries = [];\n }\n\n count(): number {\n return this.entries.length;\n }\n\n getEntriesByType(type: TraceEntry['type']): TraceEntry[] {\n return this.entries.filter(e => e.type === type);\n }\n}\n","/**\n * Deity 4.0 - Execution Statistics\n *\n * Tracks execution statistics for dynamic stop conditions\n * - Tool call tracking by type\n * - Recent tool calls (sliding window)\n * - Retry attempts\n * - Validation errors\n * - Elapsed time\n */\n\nimport type { ExecutionStats, ToolCost } from './types.js';\n\n// ============================================================================\n// Stats Manager\n// ============================================================================\n\n/**\n * Manages execution statistics during workflow execution\n */\nexport class StatsManager {\n private stats: ExecutionStats;\n private startTime: number;\n private recentToolsWindow: number;\n\n constructor(options: { recentToolsWindow?: number } = {}) {\n this.recentToolsWindow = options.recentToolsWindow ?? 10;\n this.startTime = Date.now();\n\n this.stats = {\n totalToolCalls: 0,\n toolCallsByType: {\n expensive: 0,\n cheap: 0,\n delivery: 0\n },\n recentToolCalls: [],\n totalRetries: 0,\n validationErrors: 0,\n elapsedTimeMs: 0,\n currentPhase: undefined\n };\n }\n\n /**\n * Record a tool call\n */\n recordToolCall(toolName: string, cost: ToolCost): void {\n // Increment total\n this.stats.totalToolCalls++;\n\n // Increment by type\n this.stats.toolCallsByType[cost]++;\n\n // Add to recent tools (sliding window)\n this.stats.recentToolCalls.push(toolName);\n if (this.stats.recentToolCalls.length > this.recentToolsWindow) {\n this.stats.recentToolCalls.shift();\n }\n\n // Update elapsed time\n this.updateElapsedTime();\n }\n\n /**\n * Record a retry attempt\n */\n recordRetry(): void {\n this.stats.totalRetries++;\n this.updateElapsedTime();\n }\n\n /**\n * Record validation errors\n */\n recordValidationError(errorCount: number = 1): void {\n this.stats.validationErrors += errorCount;\n this.updateElapsedTime();\n }\n\n /**\n * Set current phase\n */\n setPhase(phase: 'main' | 'delivery'): void {\n this.stats.currentPhase = phase;\n }\n\n /**\n * Update elapsed time\n */\n private updateElapsedTime(): void {\n this.stats.elapsedTimeMs = Date.now() - this.startTime;\n }\n\n /**\n * Get current stats (immutable copy)\n */\n getStats(): ExecutionStats {\n this.updateElapsedTime();\n return {\n ...this.stats,\n toolCallsByType: { ...this.stats.toolCallsByType },\n recentToolCalls: [...this.stats.recentToolCalls]\n };\n }\n\n /**\n * Reset stats\n */\n reset(): void {\n this.startTime = Date.now();\n this.stats = {\n totalToolCalls: 0,\n toolCallsByType: {\n expensive: 0,\n cheap: 0,\n delivery: 0\n },\n recentToolCalls: [],\n totalRetries: 0,\n validationErrors: 0,\n elapsedTimeMs: 0,\n currentPhase: undefined\n };\n }\n\n /**\n * Get stats summary string\n */\n getSummary(): string {\n const stats = this.getStats();\n return [\n `Total Tool Calls: ${stats.totalToolCalls}`,\n ` Expensive: ${stats.toolCallsByType.expensive}`,\n ` Cheap: ${stats.toolCallsByType.cheap}`,\n ` Delivery: ${stats.toolCallsByType.delivery}`,\n `Recent Tools: ${stats.recentToolCalls.slice(-5).join(', ')}`,\n `Retries: ${stats.totalRetries}`,\n `Validation Errors: ${stats.validationErrors}`,\n `Elapsed: ${(stats.elapsedTimeMs / 1000).toFixed(2)}s`,\n `Phase: ${stats.currentPhase ?? 'N/A'}`\n ].join('\\n');\n }\n}\n\n// ============================================================================\n// Stats Analyzer\n// ============================================================================\n\n/**\n * Analyzes execution statistics for insights\n */\nexport class StatsAnalyzer {\n /**\n * Check if in delivery phase based on stats\n */\n static isInDeliveryPhase(stats: ExecutionStats, threshold: number = 100): boolean {\n return stats.toolCallsByType.expensive >= threshold;\n }\n\n /**\n * Check if using delivery tools recently\n */\n static isUsingDeliveryTools(\n stats: ExecutionStats,\n toolCosts: Record<string, ToolCost>,\n windowSize: number = 5\n ): boolean {\n const recentWindow = stats.recentToolCalls.slice(-windowSize);\n return recentWindow.some(toolName => toolCosts[toolName] === 'delivery');\n }\n\n /**\n * Calculate tool diversity (0-1)\n */\n static calculateToolDiversity(stats: ExecutionStats): number {\n const uniqueTools = new Set(stats.recentToolCalls);\n if (stats.recentToolCalls.length === 0) return 0;\n return uniqueTools.size / stats.recentToolCalls.length;\n }\n\n /**\n * Get tool usage distribution\n */\n static getToolDistribution(stats: ExecutionStats): Record<string, number> {\n const distribution: Record<string, number> = {};\n for (const tool of stats.recentToolCalls) {\n distribution[tool] = (distribution[tool] ?? 0) + 1;\n }\n return distribution;\n }\n\n /**\n * Calculate retry rate\n */\n static calculateRetryRate(stats: ExecutionStats): number {\n if (stats.totalRetries === 0) return 0;\n return stats.totalRetries / (stats.totalRetries + 1); // +1 for initial attempt\n }\n\n /**\n * Estimate remaining time based on current progress\n */\n static estimateRemainingTime(\n stats: ExecutionStats,\n targetToolCalls: number\n ): number {\n if (stats.totalToolCalls === 0) return 0;\n\n const avgTimePerTool = stats.elapsedTimeMs / stats.totalToolCalls;\n const remainingCalls = Math.max(0, targetToolCalls - stats.totalToolCalls);\n\n return avgTimePerTool * remainingCalls;\n }\n}\n\n// ============================================================================\n// Stats Formatter\n// ============================================================================\n\n/**\n * Format stats for display\n */\nexport class StatsFormatter {\n /**\n * Format stats as JSON\n */\n static toJSON(stats: ExecutionStats): string {\n return JSON.stringify(stats, null, 2);\n }\n\n /**\n * Format stats as table\n */\n static toTable(stats: ExecutionStats): string {\n const rows = [\n ['Metric', 'Value'],\n ['---', '---'],\n ['Total Tool Calls', stats.totalToolCalls.toString()],\n ['Expensive Tools', stats.toolCallsByType.expensive.toString()],\n ['Cheap Tools', stats.toolCallsByType.cheap.toString()],\n ['Delivery Tools', stats.toolCallsByType.delivery.toString()],\n ['Total Retries', stats.totalRetries.toString()],\n ['Validation Errors', stats.validationErrors.toString()],\n ['Elapsed Time', `${(stats.elapsedTimeMs / 1000).toFixed(2)}s`],\n ['Current Phase', stats.currentPhase ?? 'N/A']\n ];\n\n const colWidths = [\n Math.max(...rows.map(r => r[0].length)),\n Math.max(...rows.map(r => r[1].length))\n ];\n\n return rows.map(([col1, col2]) =>\n `| ${col1.padEnd(colWidths[0])} | ${col2.padEnd(colWidths[1])} |`\n ).join('\\n');\n }\n\n /**\n * Format stats as compact summary\n */\n static toCompact(stats: ExecutionStats): string {\n return [\n `Tools: ${stats.totalToolCalls} (E:${stats.toolCallsByType.expensive} C:${stats.toolCallsByType.cheap} D:${stats.toolCallsByType.delivery})`,\n `Retries: ${stats.totalRetries}`,\n `Errors: ${stats.validationErrors}`,\n `Time: ${(stats.elapsedTimeMs / 1000).toFixed(1)}s`,\n `Phase: ${stats.currentPhase ?? 'N/A'}`\n ].join(' | ');\n }\n\n /**\n * Format recent tools as list\n */\n static formatRecentTools(stats: ExecutionStats, limit: number = 10): string {\n const recent = stats.recentToolCalls.slice(-limit);\n if (recent.length === 0) return 'No recent tools';\n\n return recent.map((tool, i) => `${i + 1}. ${tool}`).join('\\n');\n }\n}\n\n// ============================================================================\n// Stats Snapshot\n// ============================================================================\n\n/**\n * Create immutable snapshot of stats\n */\nexport function createStatsSnapshot(stats: ExecutionStats): Readonly<ExecutionStats> {\n return Object.freeze({\n ...stats,\n toolCallsByType: Object.freeze({ ...stats.toolCallsByType }),\n recentToolCalls: Object.freeze([...stats.recentToolCalls])\n }) as Readonly<ExecutionStats>;\n}\n\n/**\n * Compare two stats snapshots\n */\nexport function compareStats(\n before: ExecutionStats,\n after: ExecutionStats\n): {\n toolCallsDelta: number;\n retriesDelta: number;\n errorsDelta: number;\n timeDelta: number;\n phaseChanged: boolean;\n} {\n return {\n toolCallsDelta: after.totalToolCalls - before.totalToolCalls,\n retriesDelta: after.totalRetries - before.totalRetries,\n errorsDelta: after.validationErrors - before.validationErrors,\n timeDelta: after.elapsedTimeMs - before.elapsedTimeMs,\n phaseChanged: before.currentPhase !== after.currentPhase\n };\n}\n\n// All exports are inline above - no need for re-export block\n","/**\n * Deity 4.0 - Context Factory\n *\n * Factory functions for creating ExecutionContext instances\n */\n\nimport { ExecutionContext } from './context.js';\nimport type { StateStore, TraceLogger, ExecutionStats, UIUpdateBridge } from '../engine/types.js';\nimport { ConversationManager } from '../conversation/manager.js';\nimport { LimoMemoryManager } from '../memory/manager.js';\nimport { FileSystemSessionStore } from '../session/store.js';\nimport { InMemoryStore } from '../engine/stores.js';\nimport type { ConversationConfig } from '../conversation/types.js';\nimport type { MemoryConfig } from '../memory/types.js';\nimport type { SessionConfig } from '../session/types.js';\nimport { StatsManager } from '../engine/stats.js';\n\n// ============================================================================\n// Context Configuration\n// ============================================================================\n\n/**\n * Configuration for creating ExecutionContext\n */\nexport interface ContextConfig<I = unknown> {\n /** Component inputs */\n inputs: I;\n\n /** Previous stage outputs */\n previousOutputs?: Record<string, unknown>;\n\n /** State store (required) */\n store: StateStore;\n\n /** Trace logger (required) */\n trace: TraceLogger;\n\n /** Execution stats (optional, will create if not provided) */\n stats?: ExecutionStats;\n\n /** Enable conversation manager */\n enableConversation?: boolean | ConversationConfig;\n\n /** Enable memory manager */\n enableMemory?: boolean | MemoryConfig;\n\n /** Enable session store */\n enableSession?: boolean | SessionConfig;\n\n /** Enable application state store (isolated from AI memory) */\n enableAppState?: boolean | StateStore;\n\n /** UI update bridge */\n ui?: UIUpdateBridge;\n\n /** Current stage ID */\n currentStageId?: string;\n\n /** Loop iteration info */\n loop?: {\n iteration: number;\n maxIterations: number;\n history?: unknown[];\n };\n}\n\n// ============================================================================\n// Factory Functions\n// ============================================================================\n\n/**\n * Create minimal ExecutionContext (no enhancements)\n */\nexport function createMinimalContext<I = unknown>(\n inputs: I,\n store: StateStore,\n trace: TraceLogger,\n previousOutputs: Record<string, unknown> = {}\n): ExecutionContext<I> {\n const statsManager = new StatsManager();\n\n return new ExecutionContext({\n inputs,\n previousOutputs,\n store,\n trace,\n stats: statsManager.getStats()\n });\n}\n\n/**\n * Create ExecutionContext with full enhancements\n */\nexport async function createEnhancedContext<I = unknown>(\n config: ContextConfig<I>\n): Promise<ExecutionContext<I>> {\n // Create stats manager if not provided\n const statsManager = config.stats\n ? undefined\n : new StatsManager();\n\n // Create conversation manager if enabled\n let conversation: ConversationManager | undefined;\n if (config.enableConversation) {\n const conversationConfig = typeof config.enableConversation === 'object'\n ? config.enableConversation\n : undefined;\n conversation = new ConversationManager(conversationConfig);\n }\n\n // Create memory manager if enabled\n let memory: LimoMemoryManager | undefined;\n if (config.enableMemory) {\n const memoryConfig = typeof config.enableMemory === 'object'\n ? config.enableMemory\n : undefined;\n memory = new LimoMemoryManager(memoryConfig);\n }\n\n // Create session store if enabled\n let session: FileSystemSessionStore | undefined;\n if (config.enableSession) {\n const sessionConfig = typeof config.enableSession === 'object'\n ? config.enableSession\n : undefined;\n session = new FileSystemSessionStore(sessionConfig);\n await session.init();\n }\n\n // Create application state store if enabled\n let appState: StateStore | undefined;\n if (config.enableAppState) {\n if (typeof config.enableAppState === 'boolean') {\n // Create default InMemoryStore\n appState = new InMemoryStore();\n } else {\n // Use provided StateStore instance\n appState = config.enableAppState;\n }\n }\n\n return new ExecutionContext({\n inputs: config.inputs,\n previousOutputs: config.previousOutputs ?? {},\n store: config.store,\n trace: config.trace,\n stats: config.stats ?? statsManager!.getStats(),\n conversation,\n memory,\n session,\n appState,\n ui: config.ui,\n currentStageId: config.currentStageId,\n iteration: config.loop?.iteration,\n maxIterations: config.loop?.maxIterations,\n iterationHistory: config.loop?.history\n });\n}\n\n/**\n * Create ExecutionContext with conversation only\n */\nexport function createContextWithConversation<I = unknown>(\n inputs: I,\n store: StateStore,\n trace: TraceLogger,\n conversationConfig?: ConversationConfig,\n previousOutputs: Record<string, unknown> = {}\n): ExecutionContext<I> {\n const statsManager = new StatsManager();\n const conversation = new ConversationManager(conversationConfig);\n\n return new ExecutionContext({\n inputs,\n previousOutputs,\n store,\n trace,\n stats: statsManager.getStats(),\n conversation\n });\n}\n\n/**\n * Create ExecutionContext with memory only\n */\nexport function createContextWithMemory<I = unknown>(\n inputs: I,\n store: StateStore,\n trace: TraceLogger,\n memoryConfig?: MemoryConfig,\n previousOutputs: Record<string, unknown> = {}\n): ExecutionContext<I> {\n const statsManager = new StatsManager();\n const memory = new LimoMemoryManager(memoryConfig);\n\n return new ExecutionContext({\n inputs,\n previousOutputs,\n store,\n trace,\n stats: statsManager.getStats(),\n memory\n });\n}\n\n/**\n * Create ExecutionContext with session only\n */\nexport async function createContextWithSession<I = unknown>(\n inputs: I,\n store: StateStore,\n trace: TraceLogger,\n sessionConfig?: SessionConfig,\n previousOutputs: Record<string, unknown> = {}\n): Promise<ExecutionContext<I>> {\n const statsManager = new StatsManager();\n const session = new FileSystemSessionStore(sessionConfig);\n await session.init();\n\n return new ExecutionContext({\n inputs,\n previousOutputs,\n store,\n trace,\n stats: statsManager.getStats(),\n session\n });\n}\n\n// ============================================================================\n// Builder Pattern\n// ============================================================================\n\n/**\n * Context builder for fluent API\n */\nexport class ContextBuilder<I = unknown> {\n private config: Partial<ContextConfig<I>> = {};\n\n /**\n * Set inputs\n */\n withInputs(inputs: I): this {\n this.config.inputs = inputs;\n return this;\n }\n\n /**\n * Set previous outputs\n */\n withPreviousOutputs(outputs: Record<string, unknown>): this {\n this.config.previousOutputs = outputs;\n return this;\n }\n\n /**\n * Set store\n */\n withStore(store: StateStore): this {\n this.config.store = store;\n return this;\n }\n\n /**\n * Set trace logger\n */\n withTrace(trace: TraceLogger): this {\n this.config.trace = trace;\n return this;\n }\n\n /**\n * Set stats\n */\n withStats(stats: ExecutionStats): this {\n this.config.stats = stats;\n return this;\n }\n\n /**\n * Enable conversation\n */\n withConversation(config?: ConversationConfig): this {\n this.config.enableConversation = config ?? true;\n return this;\n }\n\n /**\n * Enable memory\n */\n withMemory(config?: MemoryConfig): this {\n this.config.enableMemory = config ?? true;\n return this;\n }\n\n /**\n * Enable session\n */\n withSession(config?: SessionConfig): this {\n this.config.enableSession = config ?? true;\n return this;\n }\n\n /**\n * Set UI bridge\n */\n withUI(ui: UIUpdateBridge): this {\n this.config.ui = ui;\n return this;\n }\n\n /**\n * Enable application state store\n */\n withAppState(storeOrTrue?: StateStore | boolean): this {\n this.config.enableAppState = storeOrTrue ?? true;\n return this;\n }\n\n /**\n * Set current stage ID\n */\n withStageId(stageId: string): this {\n this.config.currentStageId = stageId;\n return this;\n }\n\n /**\n * Set loop info\n */\n withLoop(iteration: number, maxIterations: number, history?: unknown[]): this {\n this.config.loop = { iteration, maxIterations, history };\n return this;\n }\n\n /**\n * Build the context\n */\n async build(): Promise<ExecutionContext<I>> {\n if (!this.config.inputs) {\n throw new Error('Context inputs are required');\n }\n if (!this.config.store) {\n throw new Error('Context store is required');\n }\n if (!this.config.trace) {\n throw new Error('Context trace logger is required');\n }\n\n return createEnhancedContext(this.config as ContextConfig<I>);\n }\n}\n\n/**\n * Create a new context builder\n */\nexport function contextBuilder<I = unknown>(): ContextBuilder<I> {\n return new ContextBuilder<I>();\n}\n","/**\n * Deity 4.0 - Workflow Runner\n *\n * Orchestrates workflow execution with checkpoint/resume\n */\n\nimport type {\n WorkflowConfig,\n ExecutionNode,\n AgentComponent,\n ExecutionContext as IExecutionContext,\n LLMAdapter,\n GenerationConfig\n} from './types.js';\nimport type { WorkflowNode } from '../ast/types.js';\nimport { ExecutionContext } from '../context/context.js';\nimport { executeComponent, type ComponentExecutionResult } from './executor.js';\nimport { createEnhancedContext } from '../context/factory.js';\nimport { InMemoryStore } from './stores.js';\nimport { InMemoryTrace } from './traces.js';\nimport { compileWorkflow } from '../compiler/compile-workflow.js';\n\n// ============================================================================\n// Workflow Execution Result\n// ============================================================================\n\n/**\n * Result from workflow execution\n */\nexport interface WorkflowExecutionResult {\n /** Final output from workflow */\n output: unknown;\n\n /** All stage outputs */\n stageOutputs: Record<string, unknown>;\n\n /** Execution succeeded */\n success: boolean;\n\n /** Total execution time (ms) */\n duration: number;\n\n /** Component results */\n componentResults: Record<string, ComponentExecutionResult<unknown>>;\n}\n\n// ============================================================================\n// Workflow Runner\n// ============================================================================\n\n/**\n * Execute a workflow\n */\nexport async function runWorkflow<I, O>(\n config: WorkflowConfig,\n inputs: I\n): Promise<O> {\n // Create store and trace\n const store = config.state?.store ?? new InMemoryStore();\n const trace = new InMemoryTrace();\n\n // Create initial context\n const ctx = await createEnhancedContext({\n inputs,\n store,\n trace,\n enableConversation: config.enhancements?.conversation !== undefined,\n enableMemory: config.enhancements?.memory !== undefined,\n enableSession: config.enhancements?.session !== undefined,\n enableAppState: config.enhancements?.appState,\n ui: config.enhancements?.ui\n });\n\n // Execute graph\n const result = await executeNode(\n config.graph,\n ctx,\n config.defaultModel?.adapter,\n config.defaultModel?.config\n );\n\n return result as O;\n}\n\n/**\n * Execute a TSX workflow\n *\n * Convenience function that compiles a WorkflowNode AST and executes it.\n * This is the recommended way to run TSX-defined workflows.\n *\n * @param workflowAST - Workflow AST node (created by Workflow component)\n * @param inputs - Workflow inputs\n * @returns Workflow output\n *\n * @example\n * ```typescript\n * const workflow = Workflow({\n * name: 'my-workflow',\n * defaultModel: { adapter: llmAdapter },\n * children: Sequence({\n * children: [Agent1, Agent2, Agent3]\n * })\n * });\n *\n * const result = await runTSXWorkflow(workflow, { input: 'data' });\n * ```\n *\n * @example With enhancements\n * ```typescript\n * const workflow = Workflow({\n * name: 'enhanced-workflow',\n * defaultModel: { adapter: llmAdapter },\n * enhancements: {\n * conversation: { maxTokens: 8000, pruneThreshold: 6000 },\n * memory: { coreBudget: { maxItems: 10, maxTotalSize: 8192 } }\n * },\n * children: MyAgent\n * });\n *\n * const result = await runTSXWorkflow(workflow, inputs);\n * ```\n */\nexport async function runTSXWorkflow<I, O>(\n workflowAST: WorkflowNode,\n inputs: I\n): Promise<O> {\n // Compile the workflow AST to WorkflowConfig\n const config = compileWorkflow(workflowAST);\n\n // Execute using the standard workflow runner\n return runWorkflow<I, O>(config, inputs);\n}\n\n// ============================================================================\n// Node Execution\n// ============================================================================\n\n/**\n * Execute an execution node\n */\nasync function executeNode(\n node: ExecutionNode,\n ctx: IExecutionContext,\n adapter?: LLMAdapter,\n config?: GenerationConfig\n): Promise<unknown> {\n switch (node.type) {\n case 'step':\n return executeStepNode(node, ctx, adapter, config);\n\n case 'sequence':\n return executeSequenceNode(node, ctx, adapter, config);\n\n case 'parallel':\n return executeParallelNode(node, ctx, adapter, config);\n\n case 'conditional':\n return executeConditionalNode(node, ctx, adapter, config);\n\n case 'loop':\n return executeLoopNode(node, ctx, adapter, config);\n\n case 'foreach':\n return executeForEachNode(node, ctx, adapter, config);\n\n default:\n throw new Error(`Unknown node type: ${(node as ExecutionNode).type}`);\n }\n}\n\n// ============================================================================\n// Step Node\n// ============================================================================\n\n/**\n * Execute a step node (single component)\n */\nasync function executeStepNode(\n node: ExecutionNode,\n ctx: IExecutionContext,\n adapter?: LLMAdapter,\n config?: GenerationConfig\n): Promise<unknown> {\n if (!node.component) {\n throw new Error('Step node missing component');\n }\n\n if (!adapter) {\n // Check if component has its own adapter\n if (node.component.model?.adapter) {\n adapter = node.component.model.adapter;\n config = node.component.model.config;\n } else {\n throw new Error('No LLM adapter provided');\n }\n }\n\n // Execute component\n const result = await executeComponent(\n node.component,\n ctx,\n adapter,\n config\n );\n\n // Update context with output\n if (ctx instanceof ExecutionContext) {\n // Note: We would need to pass this updated context to subsequent nodes\n // For now, we modify previousOutputs directly\n (ctx.previousOutputs as Record<string, unknown>)[node.component.id] = result.output;\n }\n\n return result.output;\n}\n\n// ============================================================================\n// Sequence Node\n// ============================================================================\n\n/**\n * Execute a sequence node (children in order)\n */\nasync function executeSequenceNode(\n node: ExecutionNode,\n ctx: IExecutionContext,\n adapter?: LLMAdapter,\n config?: GenerationConfig\n): Promise<unknown> {\n if (!node.children || node.children.length === 0) {\n throw new Error('Sequence node has no children');\n }\n\n let lastOutput: unknown;\n\n for (const child of node.children) {\n lastOutput = await executeNode(child, ctx, adapter, config);\n }\n\n return lastOutput;\n}\n\n// ============================================================================\n// Parallel Node\n// ============================================================================\n\n/**\n * Execute a parallel node (children concurrently)\n */\nasync function executeParallelNode(\n node: ExecutionNode,\n ctx: IExecutionContext,\n adapter?: LLMAdapter,\n config?: GenerationConfig\n): Promise<unknown[]> {\n if (!node.children || node.children.length === 0) {\n throw new Error('Parallel node has no children');\n }\n\n const results = await Promise.all(\n node.children.map(child => executeNode(child, ctx, adapter, config))\n );\n\n return results;\n}\n\n// ============================================================================\n// Conditional Node\n// ============================================================================\n\n/**\n * Execute a conditional node\n */\nasync function executeConditionalNode(\n node: ExecutionNode,\n ctx: IExecutionContext,\n adapter?: LLMAdapter,\n config?: GenerationConfig\n): Promise<unknown> {\n if (!node.condition) {\n throw new Error('Conditional node missing condition');\n }\n\n if (!node.children || node.children.length === 0) {\n throw new Error('Conditional node has no children');\n }\n\n // Evaluate condition\n const conditionResult = await Promise.resolve(node.condition(ctx));\n\n if (conditionResult) {\n // Execute first child (true branch)\n return executeNode(node.children[0], ctx, adapter, config);\n } else if (node.children.length > 1) {\n // Execute second child (false branch)\n return executeNode(node.children[1], ctx, adapter, config);\n }\n\n return undefined;\n}\n\n// ============================================================================\n// Loop Node\n// ============================================================================\n\n/**\n * Execute a loop node\n */\nasync function executeLoopNode(\n node: ExecutionNode,\n ctx: IExecutionContext,\n adapter?: LLMAdapter,\n config?: GenerationConfig\n): Promise<unknown[]> {\n if (!node.children || node.children.length === 0) {\n throw new Error('Loop node has no children');\n }\n\n if (!node.maxIterations) {\n throw new Error('Loop node missing maxIterations');\n }\n\n const results: unknown[] = [];\n\n // Create loop context\n let loopCtx = ctx;\n if (loopCtx instanceof ExecutionContext) {\n loopCtx = loopCtx.withIteration(0, node.maxIterations);\n }\n\n for (let i = 0; i < node.maxIterations; i++) {\n // Update iteration\n if (loopCtx instanceof ExecutionContext) {\n loopCtx = loopCtx.withIteration(i, node.maxIterations);\n }\n\n // Execute child\n const result = await executeNode(node.children[0], loopCtx, adapter, config);\n results.push(result);\n\n // Add to history\n if (loopCtx instanceof ExecutionContext) {\n loopCtx = loopCtx.withIterationResult(result);\n }\n }\n\n return results;\n}\n\n// ============================================================================\n// ForEach Node\n// ============================================================================\n\n/**\n * Result from ForEach execution with error tracking\n */\nexport interface ForEachResult {\n /** Results from successful iterations */\n results: unknown[];\n\n /** Errors from failed iterations (when errorMode='continue' or 'skip') */\n errors: Array<{ index: number; item: unknown; error: Error }>;\n\n /** Total items processed */\n totalItems: number;\n\n /** Successfully processed count */\n successCount: number;\n\n /** Failed iterations count */\n failureCount: number;\n}\n\n/**\n * Execute a foreach node\n */\nasync function executeForEachNode(\n node: ExecutionNode,\n ctx: IExecutionContext,\n adapter?: LLMAdapter,\n config?: GenerationConfig\n): Promise<unknown[] | ForEachResult> {\n if (!node.children || node.children.length === 0) {\n throw new Error('ForEach node has no children');\n }\n\n if (!node.itemsAccessor) {\n throw new Error('ForEach node missing itemsAccessor');\n }\n\n // Resolve items array (may be static or function)\n let items: unknown[];\n if (typeof node.itemsAccessor === 'function') {\n items = await Promise.resolve(node.itemsAccessor(ctx));\n } else {\n items = node.itemsAccessor as unknown[];\n }\n\n // Validate items is an array\n if (!Array.isArray(items)) {\n throw new Error('ForEach items must be an array');\n }\n\n const itemMode = node.itemMode ?? 'property';\n const itemKey = node.itemKey ?? 'currentItem';\n const errorMode = node.errorMode ?? 'stop';\n const collectResults = node.collectResults ?? true;\n\n const results: unknown[] = [];\n const errors: Array<{ index: number; item: unknown; error: Error }> = [];\n let successCount = 0;\n let failureCount = 0;\n\n // Loop over items\n for (let i = 0; i < items.length; i++) {\n const item = items[i];\n\n try {\n // Create iteration-specific context\n const iterationCtx = createIterationContext(\n ctx,\n item,\n i,\n items.length,\n itemMode,\n itemKey\n );\n\n // Execute child node with iteration context\n const result = await executeNode(node.children[0], iterationCtx, adapter, config);\n\n if (collectResults) {\n results.push(result);\n }\n successCount++;\n } catch (error) {\n failureCount++;\n const err = error instanceof Error ? error : new Error(String(error));\n\n // Handle error based on errorMode\n if (errorMode === 'stop') {\n // Fail-fast: re-throw error\n throw err;\n } else if (errorMode === 'continue') {\n // Collect error and continue\n errors.push({ index: i, item, error: err });\n } else if (errorMode === 'skip') {\n // Silent failure, just increment failureCount\n // Error is not added to errors array\n }\n }\n }\n\n // Return format depends on errorMode and whether errors occurred\n if (errorMode === 'continue' && (errors.length > 0 || failureCount > 0)) {\n // Return detailed result with errors\n return {\n results,\n errors,\n totalItems: items.length,\n successCount,\n failureCount,\n };\n }\n\n // Return simple results array\n return results;\n}\n\n/**\n * Create an iteration-specific context with item injected\n */\nfunction createIterationContext(\n baseCtx: IExecutionContext,\n currentItem: unknown,\n index: number,\n totalItems: number,\n itemMode: 'merge' | 'replace' | 'property',\n itemKey: string\n): IExecutionContext {\n // Build new inputs based on itemMode\n let newInputs: unknown;\n\n if (itemMode === 'property') {\n // Inject as property\n newInputs = {\n ...(baseCtx.inputs as Record<string, unknown>),\n [itemKey]: currentItem,\n __forEachIndex: index,\n __forEachTotal: totalItems,\n __forEachIsLast: index === totalItems - 1,\n };\n } else if (itemMode === 'merge') {\n // Merge item properties into inputs\n if (typeof currentItem === 'object' && currentItem !== null) {\n newInputs = {\n ...(baseCtx.inputs as Record<string, unknown>),\n ...(currentItem as Record<string, unknown>),\n __forEachIndex: index,\n __forEachTotal: totalItems,\n __forEachIsLast: index === totalItems - 1,\n };\n } else {\n throw new Error(\n `ForEach itemMode='merge' requires object items, got ${typeof currentItem}`\n );\n }\n } else if (itemMode === 'replace') {\n // Replace entire inputs with item\n // If item is not an object, metadata is lost (by design)\n if (typeof currentItem === 'object' && currentItem !== null) {\n newInputs = {\n ...(currentItem as Record<string, unknown>),\n __forEachIndex: index,\n __forEachTotal: totalItems,\n __forEachIsLast: index === totalItems - 1,\n };\n } else {\n newInputs = currentItem;\n }\n } else {\n throw new Error(`Unknown itemMode: ${itemMode}`);\n }\n\n // If ExecutionContext class, use withInputs method\n if (baseCtx instanceof ExecutionContext) {\n return baseCtx\n .withInputs(newInputs)\n .withIteration(index, totalItems);\n }\n\n // Otherwise, create new context object\n return {\n ...baseCtx,\n inputs: newInputs,\n iteration: index,\n maxIterations: totalItems,\n isLastIteration: index === totalItems - 1,\n };\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Create a simple step node\n */\nexport function createStepNode(component: AgentComponent): ExecutionNode {\n return {\n type: 'step',\n component\n };\n}\n\n/**\n * Create a sequence node\n */\nexport function createSequenceNode(children: ExecutionNode[]): ExecutionNode {\n return {\n type: 'sequence',\n children\n };\n}\n\n/**\n * Create a parallel node\n */\nexport function createParallelNode(children: ExecutionNode[]): ExecutionNode {\n return {\n type: 'parallel',\n children\n };\n}\n\n/**\n * Create a conditional node\n */\nexport function createConditionalNode(\n condition: (ctx: IExecutionContext) => boolean | Promise<boolean>,\n trueBranch: ExecutionNode,\n falseBranch?: ExecutionNode\n): ExecutionNode {\n return {\n type: 'conditional',\n condition,\n children: falseBranch ? [trueBranch, falseBranch] : [trueBranch]\n };\n}\n\n/**\n * Create a loop node\n */\nexport function createLoopNode(\n child: ExecutionNode,\n maxIterations: number\n): ExecutionNode {\n return {\n type: 'loop',\n children: [child],\n maxIterations\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/compiler/compile-observe.ts","../src/components/Agent.tsx","../src/components/Prompt.tsx","../src/components/System.tsx","../src/components/User.tsx","../src/components/Observe.tsx","../src/components/Result.tsx","../src/components/Validate.tsx","../src/components/Retry.tsx","../src/components/Tools.tsx","../src/components/ToolRef.tsx","../src/components/Sequence.tsx","../src/components/Parallel.tsx","../src/components/Conditional.tsx","../src/components/Loop.tsx","../src/components/ForEach.tsx","../src/components/Workflow.tsx","../src/utilities/resource-loader.ts","../src/compiler/compile-prompt.ts","../src/compiler/compile-agent.ts","../src/compiler/compile-result.ts","../src/compiler/compile-validate.ts","../src/compiler/compile-retry.ts","../src/compiler/index.ts","../src/compiler/compile-workflow-node.ts","../src/compiler/compile-workflow.ts","../src/ast/types.ts","../src/utilities/observe-utils.ts","../src/utilities/result-utils.ts","../src/utilities/validate-utils.ts","../src/utilities/retry-utils.ts","../src/utilities/jsx-helpers.ts","../src/utilities/preflight.ts","../src/testing/test-utils.ts","../src/dev/debug.ts","../src/engine/llm-loop.ts","../src/engine/retry.ts","../src/engine/parser.ts","../src/engine/executor.ts","../src/context/context.ts","../src/conversation/types.ts","../src/conversation/utils.ts","../src/conversation/manager.ts","../src/memory/types.ts","../src/memory/manager.ts","../src/session/types.ts","../src/session/serializer.ts","../src/session/store.ts","../src/engine/stores.ts","../src/engine/stats.ts","../src/context/factory.ts","../src/engine/workflow.ts"],"names":["path","z","compileObserve","fs"],"mappings":";;;;;;;;;;;;;;;;;AAAA,IAAA,uBAAA,GAAA,EAAA;AAAA,QAAA,CAAA,uBAAA,EAAA;AAAA,EAAA,cAAA,EA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EAAA,OAAO;AAAA,IACL,IAAA,EAAM,MAAA;AAAA,IACN,QAAA,EAAU,CAAC,KAAK,CAAA;AAAA,IAChB;AAAA,GACF;AACF","file":"index.js","sourcesContent":["/**\r\n * Deity TSX - Observe Compiler\r\n *\r\n * Compiles Observe AST nodes into observation function.\r\n */\r\n\r\nimport type { ObserveNode } from '../ast/types.js';\r\nimport type { LLMLoopResult } from '../engine/types.js';\r\n\r\n/**\r\n * Compiled Observe Function\r\n *\r\n * Extracts observations from LLM loop result.\r\n */\r\nexport type ObserveFunction = (\r\n llmResult: LLMLoopResult\r\n) => Promise<Record<string, unknown>>;\r\n\r\n/**\r\n * Compile Observe node to observation function\r\n *\r\n * @param observeNode - Observe AST node\r\n * @returns Observation function\r\n */\r\nexport function compileObserve(\r\n observeNode: ObserveNode\r\n): ObserveFunction {\r\n if (!observeNode || observeNode.type !== 'Observe') {\r\n throw new Error('Expected Observe node');\r\n }\r\n\r\n const { compute } = observeNode.props;\r\n\r\n if (!compute) {\r\n throw new Error('Observe node must have compute function');\r\n }\r\n\r\n return async (llmResult: LLMLoopResult): Promise<Record<string, unknown>> => {\r\n const observed = await Promise.resolve(compute(llmResult));\r\n\r\n // Validate observed data is a plain object\r\n if (typeof observed !== 'object' || observed === null || Array.isArray(observed)) {\r\n throw new Error('Observe compute must return a plain object');\r\n }\r\n\r\n return observed;\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Agent Component\r\n *\r\n * Root component for defining an AI agent.\r\n */\r\n\r\nimport type { ZodSchema } from 'zod';\r\nimport type { AgentNode, PromptNode, ObserveNode, ResultNode, ValidateNode, RetryNode, ToolsNode, ToolDefNode } from '../ast/types.js';\r\nimport type { Validator, ToolSpec } from '../engine/types.js';\r\n\r\n/**\r\n * LLM Loop Configuration\r\n */\r\nexport interface LLMLoopConfig {\r\n /** Maximum number of tool execution rounds */\r\n maxToolRounds?: number;\r\n /** Timeout in milliseconds */\r\n timeout?: number;\r\n}\r\n\r\n/**\r\n * Agent Component Props\r\n */\r\nexport interface AgentProps<I = unknown, O = unknown> {\r\n /** Unique agent identifier */\r\n id: string;\r\n\r\n /** Input schema (Zod) */\r\n input: ZodSchema<I>;\r\n\r\n /** Output schema (Zod) */\r\n output: ZodSchema<O>;\r\n\r\n /** Optional description */\r\n description?: string;\r\n\r\n /** Optional tags for categorization */\r\n tags?: string[];\r\n\r\n /** Optional loop-level validator (validates during LLM loop) */\r\n loopValidator?: Validator;\r\n\r\n /** Optional LLM loop configuration */\r\n loopConfig?: LLMLoopConfig;\r\n\r\n /** Optional tool definitions (backward compatible - can also use <Tools> child) */\r\n tools?: ToolSpec[];\r\n\r\n /** Child components (Tools, Prompt, Observe, Result, Validate, Retry) */\r\n children?: any[]; // Accept any JSX children, validate at runtime\r\n}\r\n\r\n/**\r\n * Agent Component\r\n *\r\n * Defines a complete AI agent with:\r\n * - Identity (id, description, tags)\r\n * - IO schemas (input/output)\r\n * - Behavior specification (Prompt, Observe, Result, Validate, Retry)\r\n * - Tool definitions (via props.tools or <Tools> child)\r\n *\r\n * @example\r\n * ```tsx\r\n * export const MyAgent = (\r\n * <Agent id=\"my-agent\" input={InputSchema} output={OutputSchema}>\r\n * <Tools>\r\n * <MemoryStore />\r\n * <MemoryRecall />\r\n * <Tool name=\"my_tool\" description=\"...\" input={Schema}>\r\n * {async (params) => ({ ... })}\r\n * </Tool>\r\n * </Tools>\r\n * <Prompt>\r\n * <System source=\"file:./prompt.md\" />\r\n * <User>{(ctx) => `Task: ${ctx.inputs.task}`}</User>\r\n * </Prompt>\r\n * <Result>\r\n * {(ctx, llmResult) => extractOutput(llmResult)}\r\n * </Result>\r\n * </Agent>\r\n * );\r\n * ```\r\n */\r\nexport function Agent<I = unknown, O = unknown>(\r\n props: AgentProps<I, O>\r\n): AgentNode<I, O> {\r\n const { id, input, output, description, tags, loopValidator, loopConfig, tools: propsTools, children } = props;\r\n\r\n // Validate required props\r\n if (!id) {\r\n throw new Error('Agent: id is required');\r\n }\r\n if (!input) {\r\n throw new Error('Agent: input schema is required');\r\n }\r\n if (!output) {\r\n throw new Error('Agent: output schema is required');\r\n }\r\n\r\n // Validate children structure\r\n if (!children || children.length === 0) {\r\n throw new Error('Agent: must have at least Prompt and Result children');\r\n }\r\n\r\n // Find and extract <Tools> node from children (if present)\r\n const toolsNode = children.find((child: any): child is ToolsNode => child?.type === 'Tools');\r\n\r\n // Non-Tools children for standard processing\r\n const nonToolsChildren = children.filter((child: any) => child?.type !== 'Tools');\r\n\r\n // Extract required and optional children from non-Tools children\r\n const [prompt, ...rest] = nonToolsChildren;\r\n\r\n if (!prompt || prompt.type !== 'Prompt') {\r\n throw new Error('Agent: first non-Tools child must be a Prompt component');\r\n }\r\n\r\n // Find Result node (required)\r\n const result = rest.find((child: any): child is ResultNode => child?.type === 'Result');\r\n if (!result) {\r\n throw new Error('Agent: must have a Result component');\r\n }\r\n\r\n // Find optional nodes\r\n const observe = rest.find((child: any): child is ObserveNode => child?.type === 'Observe');\r\n const validate = rest.find((child: any): child is ValidateNode => child?.type === 'Validate');\r\n const retry = rest.find((child: any): child is RetryNode => child?.type === 'Retry');\r\n\r\n // ========================================\r\n // Merge tools from props.tools and <Tools> child\r\n // ========================================\r\n const mergedTools = mergeTools(propsTools, toolsNode);\r\n\r\n // Build children array in canonical order\r\n const orderedChildren: (PromptNode | ObserveNode | ResultNode | ValidateNode | RetryNode | ToolsNode)[] = [\r\n prompt,\r\n ];\r\n\r\n if (observe) orderedChildren.push(observe);\r\n orderedChildren.push(result);\r\n if (validate) orderedChildren.push(validate);\r\n if (retry) orderedChildren.push(retry);\r\n // Preserve ToolsNode in children for AST introspection\r\n if (toolsNode) orderedChildren.push(toolsNode);\r\n\r\n return {\r\n type: 'Agent',\r\n props: {\r\n id,\r\n input,\r\n output,\r\n description,\r\n tags,\r\n loopValidator,\r\n loopConfig,\r\n tools: mergedTools,\r\n },\r\n children: orderedChildren,\r\n };\r\n}\r\n\r\n/**\r\n * Merge tools from props.tools and <Tools> child node.\r\n *\r\n * Both sources provide static ToolSpec arrays. The result is a\r\n * simple concatenation of all tools from both sources.\r\n */\r\nfunction mergeTools(\r\n propsTools: ToolSpec[] | undefined,\r\n toolsNode: ToolsNode | undefined\r\n): ToolSpec[] | undefined {\r\n // No tools from either source\r\n if (!propsTools && !toolsNode) {\r\n return undefined;\r\n }\r\n\r\n // Extract static tools from <ToolDef> / <Tool> children\r\n const staticToolsFromNode: ToolSpec[] = toolsNode\r\n ? (toolsNode.children || [])\r\n .filter((child: ToolDefNode) => child?.type === 'Tools:Def' && child.props?.tool)\r\n .map((child: ToolDefNode) => child.props.tool)\r\n : [];\r\n\r\n // Only props.tools, no <Tools> child\r\n if (!toolsNode) {\r\n return propsTools;\r\n }\r\n\r\n // Only <Tools> child, no props.tools\r\n if (!propsTools) {\r\n return staticToolsFromNode.length > 0 ? staticToolsFromNode : undefined;\r\n }\r\n\r\n // Both — concatenate\r\n return [...propsTools, ...staticToolsFromNode];\r\n}\r\n","/**\r\n * Deity TSX - Prompt Component\r\n *\r\n * Container for system and user prompts.\r\n */\r\n\r\nimport type { PromptNode, SystemNode, UserNode } from '../ast/types.js';\r\n\r\n/**\r\n * Prompt Component Props\r\n */\r\nexport interface PromptProps {\r\n /** Child components (System and User nodes) */\r\n children?: any[]; // Accept any JSX children, validate at runtime\r\n}\r\n\r\n/**\r\n * Prompt Component\r\n *\r\n * Container for system and user prompts.\r\n * Must contain at least one System or User node.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Prompt>\r\n * <System source=\"file:./system.md\" />\r\n * <User>{(ctx) => `Task: ${ctx.inputs.task}`}</User>\r\n * </Prompt>\r\n * ```\r\n */\r\nexport function Prompt(props: PromptProps): PromptNode {\r\n const children: (SystemNode | UserNode)[] = props.children ?? [];\r\n\r\n // Validate children\r\n if (children.length === 0) {\r\n throw new Error('Prompt: must have at least one System or User child');\r\n }\r\n\r\n // Validate child types\r\n for (const child of children) {\r\n if (!child || typeof child !== 'object' || !('type' in child)) {\r\n throw new Error('Prompt: invalid child node structure');\r\n }\r\n const childType = (child as SystemNode | UserNode).type;\r\n if (childType !== 'System' && childType !== 'User') {\r\n throw new Error(`Prompt: invalid child type \"${childType}\", expected System or User`);\r\n }\r\n }\r\n\r\n return {\r\n type: 'Prompt',\r\n children,\r\n };\r\n}\r\n","/**\r\n * Deity TSX - System Prompt Component\r\n *\r\n * System prompt node with support for file loading, inline content, or computed content.\r\n */\r\n\r\nimport type { SystemNode, TemplatePart } from '../ast/types.js';\r\nimport type { ExecutionContext } from '../engine/types.js';\r\n\r\n/**\r\n * System Component Props\r\n */\r\nexport interface SystemProps {\r\n /**\r\n * File source (e.g., 'file:./prompts/system.md')\r\n *\r\n * File paths are resolved relative to the agent definition file.\r\n */\r\n source?: string;\r\n\r\n /**\r\n * Is this prompt required? (fail-fast if missing)\r\n *\r\n * Default: false\r\n */\r\n required?: boolean;\r\n\r\n /**\r\n * Inline content (alternative to source)\r\n */\r\n content?: string;\r\n\r\n /**\r\n * Computed content (function)\r\n *\r\n * Alternative to source and content.\r\n * Receives ExecutionContext and returns prompt string.\r\n */\r\n compute?: (ctx: ExecutionContext) => string | Promise<string>;\r\n\r\n /**\r\n * Children (text or computed function)\r\n */\r\n children?: any; // Accept any JSX children, validate at runtime\r\n}\r\n\r\n/**\r\n * System Component\r\n *\r\n * Defines a system prompt with multiple loading strategies:\r\n * - File: `<System source=\"file:./prompt.md\" />`\r\n * - Inline: `<System content=\"You are a helpful assistant\" />`\r\n * - Computed: `<System compute={(ctx) => generatePrompt(ctx)} />`\r\n * - Children: `<System>{(ctx) => `Task: ${ctx.inputs.task}`}</System>`\r\n *\r\n * @example\r\n * ```tsx\r\n * // Load from file\r\n * <System source=\"file:./prompts/system.md\" required />\r\n *\r\n * // Inline content\r\n * <System content=\"You are a helpful assistant\" />\r\n *\r\n * // Computed content\r\n * <System compute={(ctx) => `Analyze: ${ctx.inputs.file}`} />\r\n *\r\n * // Children (text)\r\n * <System>You are a helpful assistant</System>\r\n *\r\n * // Children (function)\r\n * <System>{(ctx) => `Task: ${ctx.inputs.task}`}</System>\r\n * ```\r\n */\r\nexport function System(props: SystemProps): SystemNode {\r\n const { source, required, content, compute, children } = props;\r\n\r\n // Determine content strategy\r\n let finalContent: string | undefined;\r\n let finalCompute: ((ctx: ExecutionContext) => string | Promise<string>) | undefined;\r\n\r\n if (source) {\r\n // File source\r\n if (content || compute || children) {\r\n throw new Error('System: cannot use source with content, compute, or children');\r\n }\r\n } else if (content) {\r\n // Inline content\r\n if (compute || children) {\r\n throw new Error('System: cannot use content with compute or children');\r\n }\r\n finalContent = content;\r\n } else if (compute) {\r\n // Computed content\r\n if (children) {\r\n throw new Error('System: cannot use compute with children');\r\n }\r\n finalCompute = compute;\r\n } else if (children) {\r\n // Children can be: string, function, or array (from JSX)\r\n let actualChild = children;\r\n\r\n // Unwrap array children (JSX always passes array)\r\n if (Array.isArray(children)) {\r\n if (children.length === 0) {\r\n throw new Error('System: children array is empty');\r\n }\r\n\r\n // Check if we have mixed content with ToolRef nodes\r\n const hasToolRef = children.some(\r\n (child) =>\r\n typeof child === 'object' &&\r\n child !== null &&\r\n 'type' in child &&\r\n child.type === 'ToolRef'\r\n );\r\n\r\n if (hasToolRef) {\r\n // Template mode: collect all parts\r\n const parts: TemplatePart[] = [];\r\n\r\n for (const child of children) {\r\n if (typeof child === 'object' && child !== null && 'type' in child) {\r\n const node = child as any;\r\n if (node.type === 'Text' && node.props?.content) {\r\n parts.push({ kind: 'text', value: node.props.content });\r\n } else if (node.type === 'ComputedText' && node.props?.compute) {\r\n parts.push({ kind: 'computed', compute: node.props.compute });\r\n } else if (node.type === 'ToolRef' && node.props?.toolName) {\r\n parts.push({ kind: 'toolref', toolName: node.props.toolName });\r\n } else {\r\n throw new Error(`System: invalid child type in template mode: ${node.type}`);\r\n }\r\n } else if (typeof child === 'string') {\r\n parts.push({ kind: 'text', value: child });\r\n } else if (typeof child === 'function') {\r\n parts.push({ kind: 'computed', compute: child });\r\n } else {\r\n throw new Error('System: invalid child in template mode');\r\n }\r\n }\r\n\r\n return {\r\n type: 'System',\r\n props: {\r\n source,\r\n required,\r\n templateParts: parts,\r\n },\r\n };\r\n }\r\n\r\n // Single-child mode (existing behavior)\r\n if (children.length > 1) {\r\n throw new Error('System: can only have one child');\r\n }\r\n actualChild = children[0];\r\n }\r\n\r\n // Handle ComputedText node from jsx-runtime\r\n if (typeof actualChild === 'object' && actualChild !== null && 'type' in actualChild) {\r\n const node = actualChild as any;\r\n if (node.type === 'ComputedText' && node.props?.compute) {\r\n finalCompute = node.props.compute;\r\n } else if (node.type === 'Text' && node.props?.content) {\r\n finalContent = node.props.content;\r\n } else {\r\n throw new Error('System: invalid child node type');\r\n }\r\n } else if (typeof actualChild === 'string') {\r\n finalContent = actualChild;\r\n } else if (typeof actualChild === 'function') {\r\n finalCompute = actualChild;\r\n } else {\r\n throw new Error('System: children must be a string or function');\r\n }\r\n } else {\r\n throw new Error('System: must provide source, content, compute, or children');\r\n }\r\n\r\n return {\r\n type: 'System',\r\n props: {\r\n source,\r\n required,\r\n content: finalContent,\r\n compute: finalCompute,\r\n },\r\n };\r\n}\r\n","/**\r\n * Deity TSX - User Prompt Component\r\n *\r\n * User prompt node with support for inline or computed content.\r\n */\r\n\r\nimport type { UserNode, TemplatePart } from '../ast/types.js';\r\nimport type { ExecutionContext } from '../engine/types.js';\r\n\r\n/**\r\n * User Component Props\r\n */\r\nexport interface UserProps {\r\n /**\r\n * Inline content\r\n */\r\n content?: string;\r\n\r\n /**\r\n * Computed content (function)\r\n *\r\n * Receives ExecutionContext and returns prompt string.\r\n */\r\n compute?: (ctx: ExecutionContext) => string | Promise<string>;\r\n\r\n /**\r\n * Children (text or computed function)\r\n */\r\n children?: any; // Accept any JSX children, validate at runtime\r\n}\r\n\r\n/**\r\n * User Component\r\n *\r\n * Defines a user prompt with multiple strategies:\r\n * - Inline: `<User content=\"Analyze this file\" />`\r\n * - Computed: `<User compute={(ctx) => generatePrompt(ctx)} />`\r\n * - Children: `<User>{(ctx) => `Task: ${ctx.inputs.task}`}</User>`\r\n *\r\n * @example\r\n * ```tsx\r\n * // Inline content\r\n * <User content=\"Analyze this file\" />\r\n *\r\n * // Computed content\r\n * <User compute={(ctx) => `Analyze: ${ctx.inputs.file}`} />\r\n *\r\n * // Children (text)\r\n * <User>Analyze this file</User>\r\n *\r\n * // Children (function)\r\n * <User>{(ctx) => `Task: ${ctx.inputs.task}`}</User>\r\n * ```\r\n */\r\nexport function User(props: UserProps): UserNode {\r\n const { content, compute, children } = props;\r\n\r\n // Determine content strategy\r\n let finalContent: string | undefined;\r\n let finalCompute: ((ctx: ExecutionContext) => string | Promise<string>) | undefined;\r\n\r\n if (content) {\r\n // Inline content\r\n if (compute || children) {\r\n throw new Error('User: cannot use content with compute or children');\r\n }\r\n finalContent = content;\r\n } else if (compute) {\r\n // Computed content\r\n if (children) {\r\n throw new Error('User: cannot use compute with children');\r\n }\r\n finalCompute = compute;\r\n } else if (children) {\r\n // Children can be: string, function, or array (from JSX)\r\n let actualChild = children;\r\n\r\n // Unwrap array children (JSX always passes array)\r\n if (Array.isArray(children)) {\r\n if (children.length === 0) {\r\n throw new Error('User: children array is empty');\r\n }\r\n\r\n // Check if we have mixed content with ToolRef nodes\r\n const hasToolRef = children.some(\r\n (child) =>\r\n typeof child === 'object' &&\r\n child !== null &&\r\n 'type' in child &&\r\n child.type === 'ToolRef'\r\n );\r\n\r\n if (hasToolRef) {\r\n // Template mode: collect all parts\r\n const parts: TemplatePart[] = [];\r\n\r\n for (const child of children) {\r\n if (typeof child === 'object' && child !== null && 'type' in child) {\r\n const node = child as any;\r\n if (node.type === 'Text' && node.props?.content) {\r\n parts.push({ kind: 'text', value: node.props.content });\r\n } else if (node.type === 'ComputedText' && node.props?.compute) {\r\n parts.push({ kind: 'computed', compute: node.props.compute });\r\n } else if (node.type === 'ToolRef' && node.props?.toolName) {\r\n parts.push({ kind: 'toolref', toolName: node.props.toolName });\r\n } else {\r\n throw new Error(`User: invalid child type in template mode: ${node.type}`);\r\n }\r\n } else if (typeof child === 'string') {\r\n parts.push({ kind: 'text', value: child });\r\n } else if (typeof child === 'function') {\r\n parts.push({ kind: 'computed', compute: child });\r\n } else {\r\n throw new Error('User: invalid child in template mode');\r\n }\r\n }\r\n\r\n return {\r\n type: 'User',\r\n props: {\r\n templateParts: parts,\r\n },\r\n };\r\n }\r\n\r\n // Single-child mode (existing behavior)\r\n if (children.length > 1) {\r\n throw new Error('User: can only have one child');\r\n }\r\n actualChild = children[0];\r\n }\r\n\r\n // Handle ComputedText node from jsx-runtime\r\n if (typeof actualChild === 'object' && actualChild !== null && 'type' in actualChild) {\r\n const node = actualChild as any;\r\n if (node.type === 'ComputedText' && node.props?.compute) {\r\n finalCompute = node.props.compute;\r\n } else if (node.type === 'Text' && node.props?.content) {\r\n finalContent = node.props.content;\r\n } else {\r\n throw new Error('User: invalid child node type');\r\n }\r\n } else if (typeof actualChild === 'string') {\r\n finalContent = actualChild;\r\n } else if (typeof actualChild === 'function') {\r\n finalCompute = actualChild;\r\n } else {\r\n throw new Error('User: children must be a string or function');\r\n }\r\n } else {\r\n throw new Error('User: must provide content, compute, or children');\r\n }\r\n\r\n return {\r\n type: 'User',\r\n props: {\r\n content: finalContent,\r\n compute: finalCompute,\r\n },\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Observe Component\r\n *\r\n * Declarative observation of LLM execution.\r\n */\r\n\r\nimport type { ObserveNode } from '../ast/types.js';\r\nimport type { LLMLoopResult } from '../engine/types.js';\r\n\r\n/**\r\n * Observe Component Props\r\n */\r\nexport interface ObserveProps {\r\n /**\r\n * Compute function to extract observations\r\n *\r\n * Must return a plain object with observed values.\r\n * Do NOT mutate llmResult.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * toolCallCount: llmResult.toolCalls.length,\r\n * hasError: llmResult.toolCalls.some(tc => tc.error),\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\n children?: any; // Accept any JSX children, validate at runtime\r\n\r\n /**\r\n * Alternative to children (same as children)\r\n */\r\n compute?: (llmResult: LLMLoopResult) => Record<string, unknown> | Promise<Record<string, unknown>>;\r\n}\r\n\r\n/**\r\n * Observe Component\r\n *\r\n * Used to extract statistics and metadata from LLM loop results:\r\n * - Tool call counts\r\n * - Success/failure rates\r\n * - Custom metrics\r\n *\r\n * The observed data is passed to Result and Validate nodes.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * planningCalled: llmResult.toolCalls.filter(\r\n * tc => tc.name === 'planning_create'\r\n * ).length,\r\n * filesScanned: llmResult.toolCalls.filter(\r\n * tc => tc.name === 'file_list'\r\n * ).length,\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\nexport function Observe(props: ObserveProps): ObserveNode {\r\n const { children, compute } = props;\r\n\r\n // Determine compute function\r\n let finalCompute: (llmResult: LLMLoopResult) => Record<string, unknown> | Promise<Record<string, unknown>>;\r\n\r\n if (children) {\r\n if (compute) {\r\n throw new Error('Observe: cannot use both children and compute');\r\n }\r\n\r\n // Unwrap array children (JSX always passes array)\r\n let actualChild = children;\r\n if (Array.isArray(children)) {\r\n if (children.length === 0) {\r\n throw new Error('Observe: children array is empty');\r\n }\r\n if (children.length > 1) {\r\n throw new Error('Observe: can only have one child');\r\n }\r\n actualChild = children[0];\r\n }\r\n\r\n // Handle ComputedText node from jsx-runtime\r\n if (typeof actualChild === 'object' && actualChild !== null && 'type' in actualChild) {\r\n const node = actualChild as any;\r\n if (node.type === 'ComputedText' && node.props?.compute) {\r\n finalCompute = node.props.compute as any;\r\n } else {\r\n throw new Error('Observe: invalid child node type (expected ComputedText)');\r\n }\r\n } else if (typeof actualChild === 'function') {\r\n finalCompute = actualChild as any;\r\n } else {\r\n throw new Error('Observe: children must be a function');\r\n }\r\n } else if (compute) {\r\n finalCompute = compute as any;\r\n } else {\r\n throw new Error('Observe: must provide children or compute function');\r\n }\r\n\r\n return {\r\n type: 'Observe',\r\n props: {\r\n compute: finalCompute,\r\n },\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Result Component\r\n *\r\n * Extract structured output from LLM execution.\r\n */\r\n\r\nimport type { ResultNode } from '../ast/types.js';\r\nimport type { ExecutionContext, LLMLoopResult } from '../engine/types.js';\r\n\r\n/**\r\n * Result Component Props\r\n */\r\nexport interface ResultProps<O = unknown> {\r\n /**\r\n * Extract function to produce output\r\n *\r\n * @param ctx - Execution context with inputs\r\n * @param llmResult - Complete LLM loop result\r\n * @param observed - Data from Observe node (if present)\r\n * @returns Output data (must conform to output schema)\r\n *\r\n * @example\r\n * ```tsx\r\n * <Result>\r\n * {(ctx, llmResult, observed) => {\r\n * const planCall = llmResult.toolCalls.find(\r\n * tc => tc.name === 'planning_create'\r\n * );\r\n * return JSON.parse(planCall.arguments);\r\n * }}\r\n * </Result>\r\n * ```\r\n */\r\n children?: any; // Accept any JSX children, validate at runtime\r\n\r\n /**\r\n * Alternative to children (same as children)\r\n */\r\n extract?: (\r\n ctx: ExecutionContext,\r\n llmResult: LLMLoopResult,\r\n observed: Record<string, unknown>\r\n ) => O | Promise<O>;\r\n}\r\n\r\n/**\r\n * Result Component\r\n *\r\n * Responsible for:\r\n * - Extracting output from llmResult (e.g., tool call arguments)\r\n * - Using observed data from Observe node\r\n * - Returning data that conforms to output schema\r\n *\r\n * @example\r\n * ```tsx\r\n * <Result>\r\n * {(ctx, llmResult, observed) => {\r\n * const planCall = llmResult.toolCalls.find(\r\n * tc => tc.name === 'planning_create'\r\n * );\r\n *\r\n * if (!planCall) {\r\n * throw new Error('planning_create not called');\r\n * }\r\n *\r\n * return JSON.parse(planCall.arguments);\r\n * }}\r\n * </Result>\r\n * ```\r\n */\r\nexport function Result<O = unknown>(props: ResultProps<O>): ResultNode<O> {\r\n const { children, extract } = props;\r\n\r\n // Determine extract function\r\n let finalExtract: (\r\n ctx: ExecutionContext,\r\n llmResult: LLMLoopResult,\r\n observed: Record<string, unknown>\r\n ) => O | Promise<O>;\r\n\r\n if (children) {\r\n if (extract) {\r\n throw new Error('Result: cannot use both children and extract');\r\n }\r\n\r\n // Unwrap array children (JSX always passes array)\r\n let actualChild = children;\r\n if (Array.isArray(children)) {\r\n if (children.length === 0) {\r\n throw new Error('Result: children array is empty');\r\n }\r\n if (children.length > 1) {\r\n throw new Error('Result: can only have one child');\r\n }\r\n actualChild = children[0];\r\n }\r\n\r\n // Handle ComputedText node from jsx-runtime\r\n if (typeof actualChild === 'object' && actualChild !== null && 'type' in actualChild) {\r\n const node = actualChild as any;\r\n if (node.type === 'ComputedText' && node.props?.compute) {\r\n finalExtract = node.props.compute as any;\r\n } else {\r\n throw new Error('Result: invalid child node type (expected ComputedText)');\r\n }\r\n } else if (typeof actualChild === 'function') {\r\n finalExtract = actualChild as any;\r\n } else {\r\n throw new Error('Result: children must be a function');\r\n }\r\n } else if (extract) {\r\n finalExtract = extract as any;\r\n } else {\r\n throw new Error('Result: must provide children or extract function');\r\n }\r\n\r\n return {\r\n type: 'Result',\r\n props: {\r\n extract: finalExtract,\r\n },\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Validate Component\r\n *\r\n * Declarative validation rules for output.\r\n */\r\n\r\nimport type { ValidateNode, ValidationRules } from '../ast/types.js';\r\nimport type { ExecutionContext } from '../engine/types.js';\r\n\r\n/**\r\n * Validate Component Props\r\n */\r\nexport interface ValidateProps {\r\n /**\r\n * Rules function to generate validation rules\r\n *\r\n * @param output - Extracted output from Result node\r\n * @param ctx - Execution context\r\n * @param observed - Data from Observe node (if present)\r\n * @returns Validation rules\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output, ctx, observed) => ({\r\n * rules: [\r\n * {\r\n * check: output.total_tasks >= 5,\r\n * error: `Must have >= 5 tasks, got ${output.total_tasks}`,\r\n * },\r\n * {\r\n * check: observed.planningCalled > 0,\r\n * error: 'Must call planning_create tool',\r\n * },\r\n * ],\r\n * })}\r\n * </Validate>\r\n * ```\r\n */\r\n children?: any; // Accept any JSX children, validate at runtime\r\n\r\n /**\r\n * Alternative to children (same as children)\r\n */\r\n rules?: (\r\n output: unknown,\r\n ctx: ExecutionContext,\r\n observed: Record<string, unknown>\r\n ) => ValidationRules | Promise<ValidationRules>;\r\n}\r\n\r\n/**\r\n * Validate Component\r\n *\r\n * Used to validate output against business rules.\r\n * Returns structured errors for consistent handling.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output, ctx, observed) => ({\r\n * rules: [\r\n * {\r\n * check: output.total_tasks >= 5,\r\n * error: `Plan must have at least 5 tasks, got ${output.total_tasks}`,\r\n * },\r\n * {\r\n * check: output.tasks.length === output.total_tasks,\r\n * error: 'Task count mismatch',\r\n * },\r\n * {\r\n * check: observed.planningCalled > 0,\r\n * error: 'Must call planning_create tool',\r\n * },\r\n * ],\r\n * })}\r\n * </Validate>\r\n * ```\r\n */\r\nexport function Validate(props: ValidateProps): ValidateNode {\r\n const { children, rules } = props;\r\n\r\n // Determine rules function\r\n let finalRules: (\r\n output: unknown,\r\n ctx: ExecutionContext,\r\n observed: Record<string, unknown>\r\n ) => ValidationRules | Promise<ValidationRules>;\r\n\r\n if (children) {\r\n if (rules) {\r\n throw new Error('Validate: cannot use both children and rules');\r\n }\r\n\r\n // Unwrap array children (JSX always passes array)\r\n let actualChild = children;\r\n if (Array.isArray(children)) {\r\n if (children.length === 0) {\r\n throw new Error('Validate: children array is empty');\r\n }\r\n if (children.length > 1) {\r\n throw new Error('Validate: can only have one child');\r\n }\r\n actualChild = children[0];\r\n }\r\n\r\n // Handle ComputedText node from jsx-runtime\r\n if (typeof actualChild === 'object' && actualChild !== null && 'type' in actualChild) {\r\n const node = actualChild as any;\r\n if (node.type === 'ComputedText' && node.props?.compute) {\r\n finalRules = node.props.compute as any;\r\n } else {\r\n throw new Error('Validate: invalid child node type (expected ComputedText)');\r\n }\r\n } else if (typeof actualChild === 'function') {\r\n finalRules = actualChild as any;\r\n } else {\r\n throw new Error('Validate: children must be a function');\r\n }\r\n } else if (rules) {\r\n finalRules = rules as any;\r\n } else {\r\n throw new Error('Validate: must provide children or rules function');\r\n }\r\n\r\n return {\r\n type: 'Validate',\r\n props: {\r\n rules: finalRules,\r\n },\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Retry Component\r\n *\r\n * Retry policy configuration.\r\n */\r\n\r\nimport type { RetryNode } from '../ast/types.js';\r\n\r\n/**\r\n * Retry Component Props\r\n */\r\nexport interface RetryProps {\r\n /**\r\n * Maximum retry attempts (default: 3)\r\n */\r\n maxAttempts?: number;\r\n\r\n /**\r\n * Include validation errors in retry prompt (default: true)\r\n */\r\n feedbackOnError?: boolean;\r\n\r\n /**\r\n * Retry on tool execution errors (default: true)\r\n */\r\n retryOnToolError?: boolean;\r\n\r\n /**\r\n * Send tool errors to LLM for correction (default: true)\r\n */\r\n feedbackErrorToLLM?: boolean;\r\n}\r\n\r\n/**\r\n * Retry Component\r\n *\r\n * Specifies how the agent should retry on validation failures.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Retry\r\n * maxAttempts={3}\r\n * feedbackOnError={true}\r\n * />\r\n * ```\r\n */\r\nexport function Retry(props: RetryProps = {}): RetryNode {\r\n const {\r\n maxAttempts = 3,\r\n feedbackOnError = true,\r\n retryOnToolError = true,\r\n feedbackErrorToLLM = true,\r\n } = props;\r\n\r\n // Validate maxAttempts\r\n if (maxAttempts < 0) {\r\n throw new Error('Retry: maxAttempts must be >= 0');\r\n }\r\n\r\n return {\r\n type: 'Retry',\r\n props: {\r\n maxAttempts,\r\n feedbackOnError,\r\n retryOnToolError,\r\n feedbackErrorToLLM,\r\n },\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Tools Components\r\n *\r\n * Container and definition components for declaring tools in JSX.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Agent id=\"my-agent\" input={InputSchema} output={OutputSchema}>\r\n * <Tools>\r\n * <MemoryStore />\r\n * <MemoryRecall />\r\n * <Tool name=\"greet\" description=\"Greet user\" input={GreetSchema}>\r\n * {async (params) => ({ success: true, data: { message: `Hello ${params.name}` } })}\r\n * </Tool>\r\n * </Tools>\r\n * <Prompt>...</Prompt>\r\n * <Result>...</Result>\r\n * </Agent>\r\n * ```\r\n */\r\n\r\nimport type { ZodSchema } from 'zod';\r\nimport type { ToolsNode, ToolDefNode } from '../ast/types.js';\r\nimport type { ToolSpec, ExecutionContext } from '../engine/types.js';\r\n\r\n/**\r\n * Tools Component Props\r\n */\r\nexport interface ToolsProps {\r\n /** Child ToolDef/Tool components */\r\n children?: any[];\r\n}\r\n\r\n/**\r\n * Tools Component\r\n *\r\n * Container for tool definitions within an Agent.\r\n * All tools (including memory tools) are declared as children.\r\n */\r\nexport function Tools(props: ToolsProps): ToolsNode {\r\n const { children } = props;\r\n\r\n // Filter children to only include ToolDef nodes\r\n const toolDefs: ToolDefNode[] = (children || []).filter(\r\n (child: any) => child?.type === 'Tools:Def'\r\n );\r\n\r\n return {\r\n type: 'Tools',\r\n props: {},\r\n children: toolDefs,\r\n };\r\n}\r\n\r\n/**\r\n * ToolDef Component Props\r\n */\r\nexport interface ToolDefProps {\r\n /** The tool object to register */\r\n tool: ToolSpec;\r\n\r\n /** Children (not used, but accepted for JSX compatibility) */\r\n children?: any[];\r\n}\r\n\r\n/**\r\n * ToolDef Component\r\n *\r\n * Wraps a single Tool object as a JSX element.\r\n * Must be used inside a <Tools> container.\r\n *\r\n * Low-level escape hatch for pre-built ToolSpec objects.\r\n * Prefer using the declarative <Tool> component for new tools.\r\n */\r\nexport function ToolDef(props: ToolDefProps): ToolDefNode {\r\n return {\r\n type: 'Tools:Def',\r\n props: { tool: props.tool },\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// Declarative Tool Component\r\n// ============================================================================\r\n\r\n/**\r\n * Tool Component Props\r\n *\r\n * Declarative tool definition using TSX syntax.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Tool name=\"file_list\" description=\"List files\" input={FileListInputSchema}>\r\n * {async (params) => {\r\n * const files = await glob(params.pattern);\r\n * return { success: true, data: { files } };\r\n * }}\r\n * </Tool>\r\n *\r\n * // Or using the execute prop instead of children:\r\n * <Tool\r\n * name=\"file_list\"\r\n * description=\"List files\"\r\n * input={FileListInputSchema}\r\n * execute={async (params) => ({ success: true, data: { files: [] } })}\r\n * />\r\n * ```\r\n */\r\nexport interface ToolProps<TInput = unknown> {\r\n /** Tool name (unique identifier used by LLM) */\r\n name: string;\r\n\r\n /** Description (LLM uses this to decide when to invoke the tool) */\r\n description: string;\r\n\r\n /** Input validation schema (Zod) */\r\n input: ZodSchema<TInput>;\r\n\r\n /**\r\n * Execute function (alternative to children).\r\n * Use either `execute` prop or a function child, not both.\r\n */\r\n execute?: (input: TInput, ctx?: ExecutionContext) => any;\r\n\r\n /** Function child that implements tool execution */\r\n children?: any[];\r\n}\r\n\r\n/**\r\n * Tool Component\r\n *\r\n * Declarative tool definition as a first-class TSX component.\r\n * Produces a `ToolDefNode` (same as `<ToolDef>`), so the\r\n * compiler and executor require zero changes.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Tool name=\"file_list\" description=\"List files\" input={FileListInputSchema}>\r\n * {async (params: FileListInput) => {\r\n * const files = await glob(params.pattern, { cwd: rootPath });\r\n * return { success: true, data: { files, total: files.length } };\r\n * }}\r\n * </Tool>\r\n * ```\r\n */\r\nexport function Tool<TInput = unknown>(props: ToolProps<TInput>): ToolDefNode {\r\n const { name, description, input, execute, children } = props;\r\n\r\n // Validate required props\r\n if (!name) {\r\n throw new Error('Tool: name is required');\r\n }\r\n if (!description) {\r\n throw new Error('Tool: description is required');\r\n }\r\n if (!input) {\r\n throw new Error('Tool: input schema is required');\r\n }\r\n\r\n // Resolve the execute function from children or execute prop\r\n let executeFn: ((input: TInput, ctx?: ExecutionContext) => any) | undefined;\r\n\r\n // Check if children is actually provided (not an empty array from JSX)\r\n const hasChildren = children && Array.isArray(children) && children.length > 0;\r\n\r\n if (hasChildren) {\r\n if (execute) {\r\n throw new Error('Tool: cannot use both children and execute prop');\r\n }\r\n\r\n // Unwrap array children (JSX always passes array)\r\n let actualChild = children;\r\n if (Array.isArray(children)) {\r\n if (children.length > 1) {\r\n throw new Error('Tool: can only have one child (the execute function)');\r\n }\r\n actualChild = children[0];\r\n }\r\n\r\n // Handle ComputedText node from jsx-runtime\r\n // (JSX runtime wraps function children as { type: 'ComputedText', props: { compute: fn } })\r\n if (typeof actualChild === 'object' && actualChild !== null && 'type' in actualChild) {\r\n const node = actualChild as any;\r\n if (node.type === 'ComputedText' && node.props?.compute) {\r\n executeFn = node.props.compute as any;\r\n } else {\r\n throw new Error('Tool: invalid child node type (expected ComputedText with execute function)');\r\n }\r\n } else if (typeof actualChild === 'function') {\r\n // Direct function (non-JSX path)\r\n executeFn = actualChild as any;\r\n } else {\r\n throw new Error('Tool: children must be a function');\r\n }\r\n } else if (execute) {\r\n executeFn = execute;\r\n } else {\r\n throw new Error('Tool: must provide children (execute function) or execute prop');\r\n }\r\n\r\n // Assemble the ToolSpec object\r\n const toolSpec: ToolSpec<TInput> = {\r\n name,\r\n description,\r\n inputSchema: input,\r\n execute: executeFn as (input: TInput, ctx?: ExecutionContext) => Promise<any>,\r\n };\r\n\r\n // Return a ToolDefNode — same output as <ToolDef tool={...} />\r\n return {\r\n type: 'Tools:Def',\r\n props: { tool: toolSpec },\r\n };\r\n}\r\n","/**\r\n * Deity TSX - ToolRef Component\r\n *\r\n * Allows referencing tool names in prompt text in a type-safe, refactoring-friendly way.\r\n */\r\n\r\nimport type { ToolRefNode, ToolDefNode } from '../ast/types.js';\r\nimport type { ToolSpec } from '../engine/types.js';\r\n\r\n/**\r\n * ToolRef target type\r\n *\r\n * Can be:\r\n * - A tool component function with .toolName static property\r\n * - A ToolSpec object with .name property\r\n * - A plain string tool ID\r\n */\r\nexport type ToolRefTarget =\r\n | { toolName: string } // Tool component with static toolName\r\n | { (): ToolDefNode; toolName: string } // Tool component function + toolName\r\n | ToolSpec // ToolSpec object (has .name)\r\n | string; // Direct tool ID string\r\n\r\n/**\r\n * ToolRef Component Props\r\n */\r\nexport interface ToolRefProps {\r\n /**\r\n * Tool reference\r\n *\r\n * Can be:\r\n * - Tool component with .toolName: `<ToolRef tool={MemoryStore} />`\r\n * - ToolSpec object: `<ToolRef tool={myToolSpec} />`\r\n * - String ID: `<ToolRef tool=\"memory_store\" />`\r\n */\r\n tool: ToolRefTarget;\r\n}\r\n\r\n/**\r\n * ToolRef Component\r\n *\r\n * Inserts a tool name reference into prompt text. The reference is resolved\r\n * at compile time to the tool's runtime ID.\r\n *\r\n * This provides type-safe, refactor-friendly tool references that stay in sync\r\n * with the <Tools> tree, unlike hard-coded string IDs.\r\n *\r\n * @example\r\n * ```tsx\r\n * import { MemoryStore } from '@limo-labs/deity-tools';\r\n *\r\n * <User>\r\n * Use <ToolRef tool={MemoryStore} /> to save your findings.\r\n * </User>\r\n * // Compiles to: \"Use memory_store to save your findings.\"\r\n * ```\r\n *\r\n * @example\r\n * ```tsx\r\n * // With a custom tool\r\n * const myTool = createTool({ name: 'my_tool', ... });\r\n *\r\n * <User>\r\n * Call <ToolRef tool={myTool} /> when ready.\r\n * </User>\r\n * // Compiles to: \"Call my_tool when ready.\"\r\n * ```\r\n *\r\n * @example\r\n * ```tsx\r\n * // Direct string (for backwards compatibility)\r\n * <User>\r\n * Use <ToolRef tool=\"memory_store\" /> for persistence.\r\n * </User>\r\n * ```\r\n */\r\nexport function ToolRef(props: ToolRefProps): ToolRefNode {\r\n const { tool } = props;\r\n let toolName: string;\r\n\r\n // Handle null/undefined first\r\n if (tool === null || tool === undefined) {\r\n throw new Error(\r\n 'ToolRef: `tool` prop must be a tool component with .toolName, ' +\r\n 'a ToolSpec with .name, or a string tool ID'\r\n );\r\n }\r\n\r\n // Extract tool name from various formats\r\n if (typeof tool === 'string') {\r\n // Direct string\r\n toolName = tool;\r\n } else if (typeof tool === 'function' && 'toolName' in tool && typeof tool.toolName === 'string') {\r\n // Tool component function with .toolName static property\r\n toolName = tool.toolName;\r\n } else if (typeof tool === 'object' && 'toolName' in tool && typeof tool.toolName === 'string') {\r\n // Object with .toolName property\r\n toolName = tool.toolName;\r\n } else if (typeof tool === 'object' && 'name' in tool && typeof tool.name === 'string') {\r\n // ToolSpec object\r\n toolName = tool.name;\r\n } else {\r\n throw new Error(\r\n 'ToolRef: `tool` prop must be a tool component with .toolName, ' +\r\n 'a ToolSpec with .name, or a string tool ID'\r\n );\r\n }\r\n\r\n return {\r\n type: 'ToolRef',\r\n props: { toolName },\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Sequence Component\r\n *\r\n * Execute child nodes in sequential order.\r\n */\r\n\r\nimport type { WorkflowSequenceNode, WorkflowChildNode } from '../ast/types.js';\r\n\r\n/**\r\n * Sequence Component Props\r\n */\r\nexport interface SequenceProps {\r\n /** Child workflow nodes (Agents or other workflow structures) */\r\n children?: WorkflowChildNode[] | any[]; // Accept JSX children, validate at runtime\r\n}\r\n\r\n/**\r\n * Sequence Component\r\n *\r\n * Executes child nodes in sequential order.\r\n * Each child completes before the next one starts.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Sequence>\r\n * <Agent1 />\r\n * <Agent2 />\r\n * <Agent3 />\r\n * </Sequence>\r\n * ```\r\n */\r\nexport function Sequence(props: SequenceProps): WorkflowSequenceNode {\r\n const { children } = props;\r\n\r\n // Validate children\r\n if (!children || children.length === 0) {\r\n throw new Error('Sequence: must have at least one child');\r\n }\r\n\r\n return {\r\n type: 'WorkflowSequence',\r\n children,\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Parallel Component\r\n *\r\n * Execute child nodes concurrently.\r\n */\r\n\r\nimport type { WorkflowParallelNode, WorkflowChildNode } from '../ast/types.js';\r\n\r\n/**\r\n * Parallel Component Props\r\n */\r\nexport interface ParallelProps {\r\n /** Child workflow nodes (Agents or other workflow structures) */\r\n children?: WorkflowChildNode[] | any[]; // Accept JSX children, validate at runtime\r\n}\r\n\r\n/**\r\n * Parallel Component\r\n *\r\n * Executes child nodes concurrently (in parallel).\r\n * All children start simultaneously and the node completes when all children complete.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Parallel>\r\n * <SecurityScanAgent />\r\n * <PerformanceAnalysisAgent />\r\n * <CodeQualityAgent />\r\n * </Parallel>\r\n * ```\r\n */\r\nexport function Parallel(props: ParallelProps): WorkflowParallelNode {\r\n const { children } = props;\r\n\r\n // Validate children\r\n if (!children || children.length === 0) {\r\n throw new Error('Parallel: must have at least one child');\r\n }\r\n\r\n return {\r\n type: 'WorkflowParallel',\r\n children,\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Conditional Component\r\n *\r\n * Execute child nodes based on a condition.\r\n */\r\n\r\nimport type { WorkflowConditionalNode, WorkflowChildNode } from '../ast/types.js';\r\nimport type { ExecutionContext } from '../engine/types.js';\r\n\r\n/**\r\n * Conditional Component Props\r\n */\r\nexport interface ConditionalProps {\r\n /** Condition function (true = first child, false = second child) */\r\n condition: (ctx: ExecutionContext) => boolean | Promise<boolean>;\r\n\r\n /** Child workflow nodes (1-2 children: true branch required, false branch optional) */\r\n children?: [WorkflowChildNode] | [WorkflowChildNode, WorkflowChildNode] | any[]; // Accept JSX children, validate at runtime\r\n}\r\n\r\n/**\r\n * Conditional Component\r\n *\r\n * Executes child nodes based on a condition function.\r\n * - First child: executed when condition returns true\r\n * - Second child (optional): executed when condition returns false\r\n *\r\n * @example\r\n * ```tsx\r\n * <Conditional condition={(ctx) => ctx.getOutput('check').needsAnalysis}>\r\n * <DeepAnalysisAgent />\r\n * <QuickSummaryAgent />\r\n * </Conditional>\r\n * ```\r\n *\r\n * @example With only true branch\r\n * ```tsx\r\n * <Conditional condition={(ctx) => ctx.getOutput('check').isValid}>\r\n * <ProcessAgent />\r\n * </Conditional>\r\n * ```\r\n */\r\nexport function Conditional(props: ConditionalProps): WorkflowConditionalNode {\r\n const { condition, children } = props;\r\n\r\n // Validate props\r\n if (!condition) {\r\n throw new Error('Conditional: condition prop is required');\r\n }\r\n\r\n if (!children) {\r\n throw new Error('Conditional: must have at least one child (true branch)');\r\n }\r\n\r\n if (children.length < 1 || children.length > 2) {\r\n throw new Error('Conditional: must have 1-2 children (true branch required, false branch optional)');\r\n }\r\n\r\n return {\r\n type: 'WorkflowConditional',\r\n props: {\r\n condition,\r\n },\r\n children: children as [WorkflowChildNode] | [WorkflowChildNode, WorkflowChildNode],\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Loop Component\r\n *\r\n * Execute a child node N times.\r\n */\r\n\r\nimport type { WorkflowLoopNode, WorkflowChildNode } from '../ast/types.js';\r\n\r\n/**\r\n * Loop Component Props\r\n */\r\nexport interface LoopProps {\r\n /** Number of iterations */\r\n iterations: number;\r\n\r\n /** Single child workflow node (Agent or workflow structure) */\r\n children?: WorkflowChildNode | any; // Accept JSX children, validate at runtime\r\n}\r\n\r\n/**\r\n * Loop Component\r\n *\r\n * Executes a single child node N times.\r\n * The child has access to iteration context via ctx.iteration.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Loop iterations={3}>\r\n * <RefineAgent />\r\n * </Loop>\r\n * ```\r\n */\r\nexport function Loop(props: LoopProps): WorkflowLoopNode {\r\n const { iterations, children } = props;\r\n\r\n // Validate props\r\n if (!iterations || iterations < 1) {\r\n throw new Error('Loop: iterations must be >= 1');\r\n }\r\n\r\n if (!children) {\r\n throw new Error('Loop: must have exactly one child');\r\n }\r\n\r\n // Convert single child to array for consistent AST structure\r\n const childArray = Array.isArray(children) ? children : [children];\r\n\r\n if (childArray.length !== 1) {\r\n throw new Error('Loop: must have exactly one child');\r\n }\r\n\r\n return {\r\n type: 'WorkflowLoop',\r\n props: {\r\n iterations,\r\n },\r\n children: [childArray[0]],\r\n };\r\n}\r\n","/**\r\n * Deity TSX - ForEach Component\r\n *\r\n * Execute a child node for each item in a dynamic array.\r\n */\r\n\r\nimport type { WorkflowForEachNode, WorkflowChildNode } from '../ast/types.js';\r\nimport type { ExecutionContext } from '../engine/types.js';\r\n\r\n/**\r\n * Item injection modes for ForEach\r\n */\r\nexport type ItemMode = 'merge' | 'replace' | 'property';\r\n\r\n/**\r\n * Error handling modes for ForEach\r\n */\r\nexport type ErrorMode = 'stop' | 'continue' | 'skip';\r\n\r\n/**\r\n * ForEach Component Props\r\n */\r\nexport interface ForEachProps<TItem = unknown> {\r\n /**\r\n * Array of items to iterate over, or function to dynamically resolve items\r\n * Function can be sync or async\r\n */\r\n items: TItem[] | ((ctx: ExecutionContext) => TItem[] | Promise<TItem[]>);\r\n\r\n /**\r\n * How to inject the current item into context inputs\r\n * - 'property' (default): Inject as ctx.inputs[itemKey]\r\n * - 'merge': Spread item properties into ctx.inputs (for object items)\r\n * - 'replace': Replace entire ctx.inputs with item\r\n */\r\n itemMode?: ItemMode;\r\n\r\n /**\r\n * Key name for 'property' mode (default: 'currentItem')\r\n */\r\n itemKey?: string;\r\n\r\n /**\r\n * Error handling mode\r\n * - 'stop' (default): Fail-fast, throw on first error\r\n * - 'continue': Collect errors, don't stop loop\r\n * - 'skip': Silent failure, increment failure count only\r\n */\r\n errorMode?: ErrorMode;\r\n\r\n /**\r\n * Whether to collect results from each iteration (default: true)\r\n * Set to false for side-effect-only operations to optimize memory\r\n */\r\n collectResults?: boolean;\r\n\r\n /** Single child workflow node (Agent or workflow structure) */\r\n children?: WorkflowChildNode | any; // Accept JSX children, validate at runtime\r\n}\r\n\r\n/**\r\n * ForEach Component\r\n *\r\n * Executes a single child node for each item in an array.\r\n * The child has access to iteration context via ctx.iteration and the current item\r\n * via the injection mode specified.\r\n *\r\n * @example\r\n * ```tsx\r\n * // Static array with property injection\r\n * <ForEach items={['task1', 'task2', 'task3']} itemKey=\"task\">\r\n * <ProcessAgent />\r\n * </ForEach>\r\n *\r\n * // Dynamic array with merge injection\r\n * <ForEach\r\n * items={(ctx) => ctx.getOutput('planner').tasks}\r\n * itemMode=\"merge\"\r\n * errorMode=\"continue\"\r\n * collectResults={false}\r\n * >\r\n * <AnalystAgent />\r\n * </ForEach>\r\n * ```\r\n */\r\nexport function ForEach<TItem = unknown>(props: ForEachProps<TItem>): WorkflowForEachNode {\r\n const {\r\n items,\r\n itemMode = 'property',\r\n itemKey = 'currentItem',\r\n errorMode = 'stop',\r\n collectResults = true,\r\n children\r\n } = props;\r\n\r\n // Validate props\r\n if (!items) {\r\n throw new Error('ForEach: items prop is required');\r\n }\r\n\r\n if (!children) {\r\n throw new Error('ForEach: must have exactly one child');\r\n }\r\n\r\n // Convert single child to array for consistent AST structure\r\n const childArray = Array.isArray(children) ? children : [children];\r\n\r\n if (childArray.length !== 1) {\r\n throw new Error('ForEach: must have exactly one child');\r\n }\r\n\r\n // Validate itemMode\r\n const validModes: ItemMode[] = ['merge', 'replace', 'property'];\r\n if (!validModes.includes(itemMode)) {\r\n throw new Error(`ForEach: itemMode must be one of: ${validModes.join(', ')}`);\r\n }\r\n\r\n // Validate errorMode\r\n const validErrorModes: ErrorMode[] = ['stop', 'continue', 'skip'];\r\n if (!validErrorModes.includes(errorMode)) {\r\n throw new Error(`ForEach: errorMode must be one of: ${validErrorModes.join(', ')}`);\r\n }\r\n\r\n return {\r\n type: 'WorkflowForEach',\r\n props: {\r\n items,\r\n itemMode,\r\n itemKey,\r\n errorMode,\r\n collectResults,\r\n },\r\n children: [childArray[0]],\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Workflow Component\r\n *\r\n * Top-level container for defining a complete workflow.\r\n */\r\n\r\nimport type { WorkflowNode, WorkflowChildNode } from '../ast/types.js';\r\n\r\n/**\r\n * LLM Adapter interface (minimal definition for type safety)\r\n */\r\nexport interface LLMAdapter {\r\n generate(messages: any[], config?: any): Promise<any>;\r\n}\r\n\r\n/**\r\n * Generation Config (minimal definition)\r\n */\r\nexport interface GenerationConfig {\r\n temperature?: number;\r\n maxTokens?: number;\r\n topP?: number;\r\n stopSequences?: string[];\r\n}\r\n\r\n/**\r\n * State Store interface (minimal definition)\r\n */\r\nexport interface StateStore {\r\n get(key: string): Promise<unknown>;\r\n set(key: string, value: unknown): Promise<void>;\r\n}\r\n\r\n/**\r\n * Workflow Enhancement Options\r\n */\r\nexport interface WorkflowEnhancements {\r\n /** Conversation management */\r\n conversation?: {\r\n maxTokens: number;\r\n pruneThreshold: number;\r\n messageRetentionPolicy?: unknown;\r\n };\r\n\r\n /** Memory management */\r\n memory?: {\r\n coreBudget: {\r\n maxItems: number;\r\n maxTotalSize: number;\r\n };\r\n detailedBudget?: {\r\n maxItems: number;\r\n maxTotalSize: number;\r\n };\r\n };\r\n\r\n /** Session persistence */\r\n session?: {\r\n directory: string;\r\n autoSave?: boolean;\r\n };\r\n\r\n /** UI updates */\r\n ui?: any; // UIUpdateBridge\r\n\r\n /** Application state store (isolated from AI memory) */\r\n appState?: any; // StateStore\r\n}\r\n\r\n/**\r\n * Workflow Component Props\r\n */\r\nexport interface WorkflowProps {\r\n /** Workflow name (required) */\r\n name: string;\r\n\r\n /** Optional description */\r\n description?: string;\r\n\r\n /** Default LLM model configuration */\r\n defaultModel?: {\r\n adapter: LLMAdapter;\r\n config?: GenerationConfig;\r\n };\r\n\r\n /** Optional state storage */\r\n state?: {\r\n store: StateStore;\r\n };\r\n\r\n /** Optional enhancements (conversation, memory, session, UI) */\r\n enhancements?: WorkflowEnhancements;\r\n\r\n /** Single child representing the workflow graph */\r\n children?: WorkflowChildNode | any; // Accept JSX children, validate at runtime\r\n}\r\n\r\n/**\r\n * Workflow Component\r\n *\r\n * Top-level container for defining a complete workflow.\r\n * Must contain exactly one child representing the workflow execution graph.\r\n *\r\n * @example\r\n * ```tsx\r\n * const workflow = Workflow({\r\n * name: 'my-workflow',\r\n * defaultModel: { adapter: llmAdapter },\r\n * children: Sequence({\r\n * children: [Agent1, Agent2, Agent3]\r\n * })\r\n * });\r\n * ```\r\n *\r\n * @example With enhancements\r\n * ```tsx\r\n * const workflow = Workflow({\r\n * name: 'enhanced-workflow',\r\n * defaultModel: { adapter: llmAdapter },\r\n * enhancements: {\r\n * conversation: { maxTokens: 8000, pruneThreshold: 6000 },\r\n * memory: {\r\n * coreBudget: { maxItems: 10, maxTotalSize: 8192 }\r\n * }\r\n * },\r\n * children: MyAgent\r\n * });\r\n * ```\r\n */\r\nexport function Workflow(props: WorkflowProps): WorkflowNode {\r\n const { name, description, defaultModel, state, enhancements, children } = props;\r\n\r\n // Validate required props\r\n if (!name) {\r\n throw new Error('Workflow: name is required');\r\n }\r\n\r\n if (!children) {\r\n throw new Error('Workflow: must have exactly one child (workflow graph)');\r\n }\r\n\r\n // Convert single child to array for consistent AST structure\r\n const childArray = Array.isArray(children) ? children : [children];\r\n\r\n if (childArray.length !== 1) {\r\n throw new Error('Workflow: must have exactly one child (workflow graph)');\r\n }\r\n\r\n return {\r\n type: 'Workflow',\r\n props: {\r\n name,\r\n description,\r\n defaultModel,\r\n state,\r\n enhancements,\r\n },\r\n children: [childArray[0]],\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Prompt Resource Loader\r\n *\r\n * Handles loading and caching of prompt resources (files, URLs, etc.)\r\n *\r\n * Features:\r\n * - File loading with relative path resolution\r\n * - Caching mechanism\r\n * - Error handling with clear messages\r\n * - Support for different resource types\r\n */\r\n\r\nimport * as fs from 'fs/promises';\r\nimport * as path from 'path';\r\n\r\n/**\r\n * Resource Type\r\n */\r\nexport enum ResourceType {\r\n File = 'file',\r\n Inline = 'inline',\r\n Computed = 'computed',\r\n}\r\n\r\n/**\r\n * Loaded Resource\r\n */\r\nexport interface LoadedResource {\r\n /** Resource type */\r\n type: ResourceType;\r\n\r\n /** Resource content (for file and inline) */\r\n content?: string;\r\n\r\n /** Source path (for file) */\r\n source?: string;\r\n\r\n /** Whether this resource was loaded successfully */\r\n loaded: boolean;\r\n\r\n /** Error message if loading failed */\r\n error?: string;\r\n}\r\n\r\n/**\r\n * Resource Loader Options\r\n */\r\nexport interface ResourceLoaderOptions {\r\n /** Base path for resolving relative file paths */\r\n basePath?: string;\r\n\r\n /** Enable caching (default: true) */\r\n cache?: boolean;\r\n\r\n /** Cache TTL in milliseconds (default: no expiration) */\r\n cacheTTL?: number;\r\n}\r\n\r\n/**\r\n * Cache Entry\r\n */\r\ninterface CacheEntry {\r\n content: string;\r\n timestamp: number;\r\n}\r\n\r\n/**\r\n * Prompt Resource Loader\r\n *\r\n * Manages loading and caching of prompt resources.\r\n *\r\n * @example\r\n * ```typescript\r\n * const loader = new PromptResourceLoader({\r\n * basePath: '/path/to/agents',\r\n * cache: true,\r\n * });\r\n *\r\n * const resource = await loader.load('file:./prompts/system.md');\r\n * console.log(resource.content);\r\n * ```\r\n */\r\nexport class PromptResourceLoader {\r\n private cache: Map<string, CacheEntry> = new Map();\r\n private options: Required<ResourceLoaderOptions>;\r\n\r\n constructor(options: ResourceLoaderOptions = {}) {\r\n this.options = {\r\n basePath: options.basePath || process.cwd(),\r\n cache: options.cache ?? true,\r\n cacheTTL: options.cacheTTL ?? 0, // 0 = no expiration\r\n };\r\n }\r\n\r\n /**\r\n * Load a resource\r\n *\r\n * @param source - Resource source (e.g., 'file:./prompt.md')\r\n * @param required - Whether this resource is required\r\n * @returns Loaded resource\r\n */\r\n async load(source: string, required: boolean = false): Promise<LoadedResource> {\r\n try {\r\n // Parse resource type\r\n const type = this.parseResourceType(source);\r\n\r\n switch (type) {\r\n case ResourceType.File:\r\n return await this.loadFile(source, required);\r\n default:\r\n return {\r\n type,\r\n loaded: false,\r\n error: `Unsupported resource type: ${type}`,\r\n };\r\n }\r\n } catch (error) {\r\n const errorMessage = error instanceof Error ? error.message : String(error);\r\n\r\n if (required) {\r\n throw new Error(`Failed to load required resource '${source}': ${errorMessage}`);\r\n }\r\n\r\n return {\r\n type: ResourceType.File,\r\n source,\r\n loaded: false,\r\n error: errorMessage,\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Load a file resource\r\n */\r\n private async loadFile(source: string, required: boolean): Promise<LoadedResource> {\r\n // Extract file path (remove 'file:' prefix)\r\n const filePath = this.extractFilePath(source);\r\n\r\n // Resolve absolute path\r\n const absolutePath = this.resolvePath(filePath);\r\n\r\n // Check cache\r\n if (this.options.cache) {\r\n const cached = this.getFromCache(absolutePath);\r\n if (cached) {\r\n return {\r\n type: ResourceType.File,\r\n source: absolutePath,\r\n content: cached,\r\n loaded: true,\r\n };\r\n }\r\n }\r\n\r\n // Load file\r\n try {\r\n const content = await fs.readFile(absolutePath, 'utf-8');\r\n\r\n // Cache the content\r\n if (this.options.cache) {\r\n this.setCache(absolutePath, content);\r\n }\r\n\r\n return {\r\n type: ResourceType.File,\r\n source: absolutePath,\r\n content,\r\n loaded: true,\r\n };\r\n } catch (error) {\r\n const errorMessage = error instanceof Error ? error.message : String(error);\r\n\r\n if (required) {\r\n throw new Error(`Required file not found: ${absolutePath}`);\r\n }\r\n\r\n return {\r\n type: ResourceType.File,\r\n source: absolutePath,\r\n loaded: false,\r\n error: errorMessage,\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Parse resource type from source string\r\n */\r\n private parseResourceType(source: string): ResourceType {\r\n if (source.startsWith('file:')) {\r\n return ResourceType.File;\r\n }\r\n\r\n // Default to inline\r\n return ResourceType.Inline;\r\n }\r\n\r\n /**\r\n * Extract file path from source\r\n */\r\n private extractFilePath(source: string): string {\r\n if (source.startsWith('file:')) {\r\n return source.slice(5); // Remove 'file:' prefix\r\n }\r\n return source;\r\n }\r\n\r\n /**\r\n * Resolve relative path to absolute path\r\n */\r\n private resolvePath(filePath: string): string {\r\n if (path.isAbsolute(filePath)) {\r\n return filePath;\r\n }\r\n\r\n // Resolve relative to base path\r\n return path.resolve(this.options.basePath, filePath);\r\n }\r\n\r\n /**\r\n * Get content from cache\r\n */\r\n private getFromCache(key: string): string | null {\r\n const entry = this.cache.get(key);\r\n\r\n if (!entry) {\r\n return null;\r\n }\r\n\r\n // Check TTL\r\n if (this.options.cacheTTL > 0) {\r\n const age = Date.now() - entry.timestamp;\r\n if (age > this.options.cacheTTL) {\r\n this.cache.delete(key);\r\n return null;\r\n }\r\n }\r\n\r\n return entry.content;\r\n }\r\n\r\n /**\r\n * Set content in cache\r\n */\r\n private setCache(key: string, content: string): void {\r\n this.cache.set(key, {\r\n content,\r\n timestamp: Date.now(),\r\n });\r\n }\r\n\r\n /**\r\n * Clear cache\r\n */\r\n clearCache(): void {\r\n this.cache.clear();\r\n }\r\n\r\n /**\r\n * Get cache size\r\n */\r\n getCacheSize(): number {\r\n return this.cache.size;\r\n }\r\n\r\n /**\r\n * Preflight check - verify all resources exist\r\n *\r\n * @param sources - List of file sources to check\r\n * @returns List of missing resources\r\n */\r\n async preflight(sources: Array<{ source: string; required: boolean }>): Promise<string[]> {\r\n const missing: string[] = [];\r\n\r\n for (const { source, required } of sources) {\r\n if (!source.startsWith('file:')) {\r\n continue; // Skip non-file resources\r\n }\r\n\r\n const filePath = this.extractFilePath(source);\r\n const absolutePath = this.resolvePath(filePath);\r\n\r\n try {\r\n await fs.access(absolutePath);\r\n } catch (error) {\r\n if (required) {\r\n missing.push(absolutePath);\r\n }\r\n }\r\n }\r\n\r\n return missing;\r\n }\r\n}\r\n\r\n/**\r\n * Global resource loader instance\r\n */\r\nlet globalLoader: PromptResourceLoader | null = null;\r\n\r\n/**\r\n * Get or create global resource loader\r\n */\r\nexport function getResourceLoader(options?: ResourceLoaderOptions): PromptResourceLoader {\r\n if (!globalLoader) {\r\n globalLoader = new PromptResourceLoader(options);\r\n }\r\n return globalLoader;\r\n}\r\n\r\n/**\r\n * Set global resource loader\r\n */\r\nexport function setResourceLoader(loader: PromptResourceLoader): void {\r\n globalLoader = loader;\r\n}\r\n\r\n/**\r\n * Reset global resource loader\r\n */\r\nexport function resetResourceLoader(): void {\r\n globalLoader = null;\r\n}\r\n","/**\r\n * Deity TSX - Prompt Compiler\r\n *\r\n * Compiles Prompt AST nodes into buildPrompt function.\r\n */\r\n\r\nimport type { PromptNode, SystemNode, UserNode } from '../ast/types.js';\r\nimport type { ExecutionContext, Message } from '../engine/types.js';\r\nimport { getResourceLoader } from '../utilities/resource-loader.js';\r\n\r\n/**\r\n * Compile Prompt node to buildPrompt function\r\n *\r\n * @param promptNode - Prompt AST node\r\n * @returns buildPrompt function\r\n */\r\nexport function compilePrompt(promptNode: PromptNode) {\r\n if (!promptNode || promptNode.type !== 'Prompt') {\r\n throw new Error('Expected Prompt node');\r\n }\r\n\r\n const children: (SystemNode | UserNode)[] = promptNode.children ?? [];\r\n\r\n return async (ctx: ExecutionContext): Promise<Message[]> => {\r\n const messages: Message[] = [];\r\n\r\n for (const child of children) {\r\n if (child.type === 'System') {\r\n const content = await resolveSystemContent(child, ctx);\r\n messages.push({ role: 'system', content });\r\n } else if (child.type === 'User') {\r\n const content = await resolveUserContent(child, ctx);\r\n messages.push({ role: 'user', content });\r\n } else {\r\n // This should never happen due to type constraints, but check anyway\r\n const _exhaustiveCheck: never = child;\r\n void _exhaustiveCheck; // Suppress unused variable warning\r\n throw new Error(`Invalid Prompt child: ${(child as any).type}`);\r\n }\r\n }\r\n\r\n return messages;\r\n };\r\n}\r\n\r\n/**\r\n * Resolve System node content\r\n */\r\nasync function resolveSystemContent(\r\n node: SystemNode,\r\n ctx: ExecutionContext\r\n): Promise<string> {\r\n const { source, content, compute, required = false, templateParts } = node.props;\r\n\r\n // Template mode (mixed content with ToolRef)\r\n if (templateParts) {\r\n const resolved = await Promise.all(\r\n templateParts.map(async (part) => {\r\n switch (part.kind) {\r\n case 'text':\r\n return part.value;\r\n case 'computed':\r\n return await Promise.resolve(part.compute(ctx));\r\n case 'toolref':\r\n return part.toolName;\r\n default:\r\n // TypeScript exhaustiveness check\r\n const _exhaustive: never = part;\r\n throw new Error(`Unknown template part kind: ${(_exhaustive as any).kind}`);\r\n }\r\n })\r\n );\r\n return resolved.join('');\r\n }\r\n\r\n // File source - use resource loader\r\n if (source) {\r\n if (!source.startsWith('file:')) {\r\n throw new Error(`Invalid source format: ${source} (must start with \"file:\")`);\r\n }\r\n\r\n const loader = getResourceLoader();\r\n const resource = await loader.load(source, required);\r\n\r\n if (!resource.loaded) {\r\n if (required) {\r\n throw new Error(`Required system prompt file not found: ${source}`);\r\n }\r\n // If not required, return empty string\r\n return '';\r\n }\r\n\r\n return resource.content || '';\r\n }\r\n\r\n // Inline content\r\n if (content !== undefined) {\r\n return content;\r\n }\r\n\r\n // Computed content\r\n if (compute) {\r\n return await Promise.resolve(compute(ctx));\r\n }\r\n\r\n throw new Error('System node must have source, content, compute, or templateParts');\r\n}\r\n\r\n/**\r\n * Resolve User node content\r\n */\r\nasync function resolveUserContent(\r\n node: UserNode,\r\n ctx: ExecutionContext\r\n): Promise<string> {\r\n const { content, compute, templateParts } = node.props;\r\n\r\n // Template mode (mixed content with ToolRef)\r\n if (templateParts) {\r\n const resolved = await Promise.all(\r\n templateParts.map(async (part) => {\r\n switch (part.kind) {\r\n case 'text':\r\n return part.value;\r\n case 'computed':\r\n return await Promise.resolve(part.compute(ctx));\r\n case 'toolref':\r\n return part.toolName;\r\n default:\r\n // TypeScript exhaustiveness check\r\n const _exhaustive: never = part;\r\n throw new Error(`Unknown template part kind: ${(_exhaustive as any).kind}`);\r\n }\r\n })\r\n );\r\n return resolved.join('');\r\n }\r\n\r\n // Inline content\r\n if (content !== undefined) {\r\n return content;\r\n }\r\n\r\n // Computed content\r\n if (compute) {\r\n return await Promise.resolve(compute(ctx));\r\n }\r\n\r\n throw new Error('User node must have content, compute, or templateParts');\r\n}\r\n","/**\r\n * Deity TSX - AST Compiler\r\n *\r\n * Compiles AST nodes into executable AgentComponent instances.\r\n *\r\n * Design principles:\r\n * - Pure transformation (AST -> AgentComponent)\r\n * - Fail-fast validation\r\n * - Preserve all function references\r\n * - Type-safe compilation\r\n */\r\n\r\nimport type { AgentNode } from '../ast/types.js';\r\nimport type { AgentComponent } from '../engine/types.js';\r\nimport { compilePrompt } from './compile-prompt.js';\r\nimport { compileObserve } from './compile-observe.js';\r\nimport { compileResult } from './compile-result.js';\r\nimport { compileValidate } from './compile-validate.js';\r\nimport { compileRetry } from './compile-retry.js';\r\n\r\n/**\r\n * Compile Agent AST to AgentComponent\r\n *\r\n * This is the main entry point for compilation.\r\n *\r\n * @param ast - Agent AST node\r\n * @returns Executable AgentComponent\r\n *\r\n * @example\r\n * ```typescript\r\n * const MyAgent = (\r\n * <Agent id=\"test\" input={TestInput} output={TestOutput}>\r\n * <Prompt>...</Prompt>\r\n * <Result>...</Result>\r\n * </Agent>\r\n * );\r\n *\r\n * const component = compileAgent(MyAgent);\r\n * // component is now an executable AgentComponent\r\n * ```\r\n */\r\nexport function compileAgent<I = unknown, O = unknown>(\r\n ast: AgentNode<I, O>\r\n): AgentComponent<I, O> {\r\n // Validate AST\r\n if (ast.type !== 'Agent') {\r\n throw new Error(`Expected Agent node, got ${ast.type}`);\r\n }\r\n\r\n // Extract children\r\n const children = ast.children;\r\n if (!children || children.length === 0) {\r\n throw new Error('Agent must have children');\r\n }\r\n\r\n // Find nodes by type\r\n const promptNode = children.find(n => n?.type === 'Prompt');\r\n const observeNode = children.find(n => n?.type === 'Observe');\r\n const resultNode = children.find(n => n?.type === 'Result');\r\n const validateNode = children.find(n => n?.type === 'Validate');\r\n const retryNode = children.find(n => n?.type === 'Retry');\r\n\r\n if (!promptNode) {\r\n throw new Error('Agent must have a Prompt node');\r\n }\r\n if (!resultNode) {\r\n throw new Error('Agent must have a Result node');\r\n }\r\n\r\n // Compile each part (with type assertions since we validated above)\r\n const buildPrompt = compilePrompt(promptNode as any);\r\n const observe = observeNode ? compileObserve(observeNode as any) : undefined;\r\n const extractOutput = compileResult<O>(resultNode as any, observe);\r\n const validateOutput = validateNode ? compileValidate(validateNode as any) : undefined;\r\n const retry = retryNode ? compileRetry(retryNode as any) : undefined;\r\n\r\n // Build AgentComponent\r\n const component: AgentComponent<I, O> = {\r\n id: ast.props.id,\r\n inputSchema: ast.props.input,\r\n outputSchema: ast.props.output,\r\n buildPrompt,\r\n extractOutput,\r\n };\r\n\r\n // Add optional configurations\r\n if (validateOutput) {\r\n component.validateOutput = validateOutput;\r\n }\r\n\r\n if (retry) {\r\n component.retry = retry;\r\n }\r\n\r\n if (ast.props.loopValidator) {\r\n component.loopValidator = ast.props.loopValidator;\r\n }\r\n\r\n if (ast.props.loopConfig) {\r\n component.loopConfig = ast.props.loopConfig;\r\n }\r\n\r\n if (ast.props.tools) {\r\n component.tools = ast.props.tools;\r\n }\r\n\r\n return component;\r\n}\r\n","/**\r\n * Deity TSX - Result Compiler\r\n *\r\n * Compiles Result AST nodes into extractOutput function.\r\n */\r\n\r\nimport type { ResultNode } from '../ast/types.js';\r\nimport type { ExecutionContext, LLMLoopResult } from '../engine/types.js';\r\nimport type { ObserveFunction } from './compile-observe.js';\r\n\r\n/**\r\n * Compile Result node to extractOutput function\r\n *\r\n * @param resultNode - Result AST node\r\n * @param observeFunction - Optional observe function (if Observe node exists)\r\n * @returns extractOutput function\r\n */\r\nexport function compileResult<O = unknown>(\r\n resultNode: ResultNode<O>,\r\n observeFunction?: ObserveFunction\r\n) {\r\n if (!resultNode || resultNode.type !== 'Result') {\r\n throw new Error('Expected Result node');\r\n }\r\n\r\n const { extract } = resultNode.props;\r\n\r\n if (!extract) {\r\n throw new Error('Result node must have extract function');\r\n }\r\n\r\n return async (\r\n ctx: ExecutionContext,\r\n llmResult: LLMLoopResult\r\n ): Promise<O> => {\r\n // Run observation if present\r\n let observed: Record<string, unknown> = {};\r\n if (observeFunction) {\r\n observed = await observeFunction(llmResult);\r\n }\r\n\r\n // Extract output\r\n const output = await Promise.resolve(extract(ctx, llmResult, observed));\r\n\r\n return output;\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Validate Compiler\r\n *\r\n * Compiles Validate AST nodes into validateOutput function.\r\n */\r\n\r\nimport type { ValidateNode, ValidationRules } from '../ast/types.js';\r\nimport type { ExecutionContext, ValidationResult } from '../engine/types.js';\r\n\r\n/**\r\n * Compile Validate node to validateOutput function\r\n *\r\n * @param validateNode - Validate AST node\r\n * @returns validateOutput function\r\n */\r\nexport function compileValidate(validateNode: ValidateNode) {\r\n if (!validateNode || validateNode.type !== 'Validate') {\r\n throw new Error('Expected Validate node');\r\n }\r\n\r\n const { rules: rulesFunction } = validateNode.props;\r\n\r\n if (!rulesFunction) {\r\n throw new Error('Validate node must have rules function');\r\n }\r\n\r\n return async (\r\n output: unknown,\r\n ctx: ExecutionContext\r\n ): Promise<ValidationResult> => {\r\n // Note: We need access to observed data here\r\n // For now, we'll pass an empty object\r\n // In the full implementation, we'd need to refactor to pass observed data\r\n const observed: Record<string, unknown> = {};\r\n\r\n // Get validation rules\r\n const validationRules: ValidationRules = await Promise.resolve(\r\n rulesFunction(output, ctx, observed)\r\n );\r\n\r\n // Validate rules structure\r\n if (!validationRules.rules || !Array.isArray(validationRules.rules)) {\r\n throw new Error('Validate rules function must return {rules: [...]}');\r\n }\r\n\r\n // Execute rules\r\n const errors: string[] = [];\r\n\r\n for (const rule of validationRules.rules) {\r\n if (!rule.check) {\r\n errors.push(rule.error);\r\n }\r\n }\r\n\r\n // Return validation result\r\n if (errors.length > 0) {\r\n return {\r\n valid: false,\r\n errors,\r\n };\r\n }\r\n\r\n return { valid: true };\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Retry Compiler\r\n *\r\n * Compiles Retry AST nodes into retry configuration.\r\n */\r\n\r\nimport type { RetryNode } from '../ast/types.js';\r\nimport type { RetryConfig } from '../engine/types.js';\r\n\r\n/**\r\n * Compile Retry node to retry configuration\r\n *\r\n * @param retryNode - Retry AST node\r\n * @returns Retry configuration\r\n */\r\nexport function compileRetry(retryNode: RetryNode): RetryConfig {\r\n if (!retryNode || retryNode.type !== 'Retry') {\r\n throw new Error('Expected Retry node');\r\n }\r\n\r\n const {\r\n maxAttempts = 3,\r\n feedbackOnError = true,\r\n retryOnToolError = true,\r\n feedbackErrorToLLM = true,\r\n } = retryNode.props;\r\n\r\n return {\r\n maxAttempts,\r\n feedbackOnError,\r\n retryOnToolError,\r\n feedbackErrorToLLM,\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Compiler\r\n *\r\n * Export all compiler functions.\r\n */\r\n\r\nexport { compileAgent } from './compile-agent.js';\r\nexport { compilePrompt } from './compile-prompt.js';\r\nexport { compileObserve } from './compile-observe.js';\r\nexport { compileResult } from './compile-result.js';\r\nexport { compileValidate } from './compile-validate.js';\r\nexport { compileRetry } from './compile-retry.js';\r\n\r\n// Workflow compilers\r\nexport { compileWorkflow } from './compile-workflow.js';\r\nexport { compileWorkflowNode } from './compile-workflow-node.js';\r\n\r\nexport type { ObserveFunction } from './compile-observe.js';\r\n","/**\r\n * Deity TSX - Workflow Node Compiler\r\n *\r\n * Compiles workflow structure AST nodes into ExecutionNode instances.\r\n */\r\n\r\nimport type {\r\n WorkflowChildNode,\r\n WorkflowSequenceNode,\r\n WorkflowParallelNode,\r\n WorkflowConditionalNode,\r\n WorkflowLoopNode,\r\n WorkflowForEachNode,\r\n AgentNode,\r\n} from '../ast/types.js';\r\nimport type { ExecutionNode, AgentComponent } from '../engine/types.js';\r\nimport { compileAgent } from './compile-agent.js';\r\n\r\n/**\r\n * Compile a workflow child node (Agent or workflow structure) to ExecutionNode\r\n *\r\n * This is the main dispatcher that routes to the appropriate compiler.\r\n *\r\n * @param node - Workflow child node (Agent, Sequence, Parallel, Conditional, Loop, ForEach)\r\n * @returns ExecutionNode that can be executed by the runtime\r\n */\r\nexport function compileWorkflowNode(node: WorkflowChildNode): ExecutionNode {\r\n switch (node.type) {\r\n case 'Agent':\r\n return compileAgentNode(node as AgentNode);\r\n\r\n case 'WorkflowSequence':\r\n return compileSequenceNode(node as WorkflowSequenceNode);\r\n\r\n case 'WorkflowParallel':\r\n return compileParallelNode(node as WorkflowParallelNode);\r\n\r\n case 'WorkflowConditional':\r\n return compileConditionalNode(node as WorkflowConditionalNode);\r\n\r\n case 'WorkflowLoop':\r\n return compileLoopNode(node as WorkflowLoopNode);\r\n\r\n case 'WorkflowForEach':\r\n return compileForEachNode(node as WorkflowForEachNode);\r\n\r\n default:\r\n throw new Error(`Unknown workflow node type: ${(node as any).type}`);\r\n }\r\n}\r\n\r\n/**\r\n * Compile an Agent node to a step ExecutionNode\r\n *\r\n * Uses lazy compilation wrapper to defer agent compilation until first execution.\r\n */\r\nfunction compileAgentNode(node: AgentNode): ExecutionNode {\r\n // Create lazy agent component wrapper\r\n const lazyComponent = createLazyAgentComponent(node);\r\n\r\n return {\r\n type: 'step',\r\n component: lazyComponent,\r\n };\r\n}\r\n\r\n/**\r\n * Compile a Sequence node to a sequence ExecutionNode\r\n */\r\nfunction compileSequenceNode(node: WorkflowSequenceNode): ExecutionNode {\r\n if (!node.children || node.children.length === 0) {\r\n throw new Error('Sequence node must have children');\r\n }\r\n\r\n const children = node.children.map(child => compileWorkflowNode(child));\r\n\r\n return {\r\n type: 'sequence',\r\n children,\r\n };\r\n}\r\n\r\n/**\r\n * Compile a Parallel node to a parallel ExecutionNode\r\n */\r\nfunction compileParallelNode(node: WorkflowParallelNode): ExecutionNode {\r\n if (!node.children || node.children.length === 0) {\r\n throw new Error('Parallel node must have children');\r\n }\r\n\r\n const children = node.children.map(child => compileWorkflowNode(child));\r\n\r\n return {\r\n type: 'parallel',\r\n children,\r\n };\r\n}\r\n\r\n/**\r\n * Compile a Conditional node to a conditional ExecutionNode\r\n */\r\nfunction compileConditionalNode(node: WorkflowConditionalNode): ExecutionNode {\r\n if (!node.props?.condition) {\r\n throw new Error('Conditional node must have a condition function');\r\n }\r\n\r\n if (!node.children || node.children.length < 1 || node.children.length > 2) {\r\n throw new Error('Conditional node must have 1-2 children (true branch required, false branch optional)');\r\n }\r\n\r\n const children = node.children.map(child => compileWorkflowNode(child));\r\n\r\n return {\r\n type: 'conditional',\r\n condition: node.props.condition,\r\n children,\r\n };\r\n}\r\n\r\n/**\r\n * Compile a Loop node to a loop ExecutionNode\r\n */\r\nfunction compileLoopNode(node: WorkflowLoopNode): ExecutionNode {\r\n if (!node.props?.iterations || node.props.iterations < 1) {\r\n throw new Error('Loop node must have iterations >= 1');\r\n }\r\n\r\n if (!node.children || node.children.length !== 1) {\r\n throw new Error('Loop node must have exactly one child');\r\n }\r\n\r\n const child = compileWorkflowNode(node.children[0]);\r\n\r\n return {\r\n type: 'loop',\r\n maxIterations: node.props.iterations,\r\n children: [child],\r\n };\r\n}\r\n\r\n/**\r\n * Compile a ForEach node to a foreach ExecutionNode\r\n */\r\nfunction compileForEachNode(node: WorkflowForEachNode): ExecutionNode {\r\n if (!node.props?.items) {\r\n throw new Error('ForEach node must have items prop');\r\n }\r\n\r\n if (!node.children || node.children.length !== 1) {\r\n throw new Error('ForEach node must have exactly one child');\r\n }\r\n\r\n const child = compileWorkflowNode(node.children[0]);\r\n\r\n return {\r\n type: 'foreach',\r\n itemsAccessor: node.props.items,\r\n itemMode: node.props.itemMode as 'merge' | 'replace' | 'property',\r\n itemKey: node.props.itemKey,\r\n errorMode: node.props.errorMode as 'stop' | 'continue' | 'skip',\r\n collectResults: node.props.collectResults,\r\n children: [child],\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// Lazy Agent Component Wrapper\r\n// ============================================================================\r\n\r\n/**\r\n * Create a lazy agent component that defers compilation until first use\r\n *\r\n * This wrapper implements the AgentComponent interface but delays actual\r\n * compilation of the AgentNode until the first method call.\r\n *\r\n * Benefits:\r\n * - Faster workflow startup (no upfront compilation)\r\n * - Only compile agents that are actually executed\r\n * - Compilation result is cached for subsequent calls\r\n */\r\nfunction createLazyAgentComponent<I = unknown, O = unknown>(\r\n astNode: AgentNode<I, O>\r\n): AgentComponent<I, O> {\r\n let compiled: AgentComponent<I, O> | null = null;\r\n\r\n const ensureCompiled = (): AgentComponent<I, O> => {\r\n if (!compiled) {\r\n compiled = compileAgent(astNode);\r\n }\r\n return compiled;\r\n };\r\n\r\n // Return a proxy that implements AgentComponent interface\r\n const proxy: AgentComponent<I, O> = {\r\n get id() {\r\n return astNode.props.id;\r\n },\r\n get inputSchema() {\r\n return astNode.props.input;\r\n },\r\n get outputSchema() {\r\n return astNode.props.output;\r\n },\r\n get tools() {\r\n return astNode.props.tools;\r\n },\r\n get loopValidator() {\r\n return astNode.props.loopValidator;\r\n },\r\n get loopConfig() {\r\n return astNode.props.loopConfig;\r\n },\r\n\r\n // Lazy methods - compile on first call\r\n buildPrompt(ctx) {\r\n return ensureCompiled().buildPrompt(ctx);\r\n },\r\n get retry() {\r\n return ensureCompiled().retry;\r\n },\r\n get model() {\r\n return ensureCompiled().model;\r\n },\r\n };\r\n\r\n // Conditionally add extractOutput only if it will exist after compilation\r\n // This is determined by checking if the AST has a Result node\r\n const hasResultNode = astNode.children.some(child => child.type === 'Result');\r\n if (hasResultNode) {\r\n proxy.extractOutput = (ctx, llmResult) => {\r\n return ensureCompiled().extractOutput!(ctx, llmResult);\r\n };\r\n }\r\n\r\n // Conditionally add validateOutput only if it will exist after compilation\r\n // This is determined by checking if the AST has a Validate node\r\n const hasValidateNode = astNode.children.some(child => child.type === 'Validate');\r\n if (hasValidateNode) {\r\n proxy.validateOutput = (output, ctx) => {\r\n const comp = ensureCompiled();\r\n return comp.validateOutput!(output, ctx);\r\n };\r\n }\r\n\r\n return proxy;\r\n}\r\n","/**\r\n * Deity TSX - Workflow Compiler\r\n *\r\n * Compiles WorkflowNode AST into executable WorkflowConfig.\r\n */\r\n\r\nimport type { WorkflowNode } from '../ast/types.js';\r\nimport type { WorkflowConfig } from '../engine/types.js';\r\nimport { compileWorkflowNode } from './compile-workflow-node.js';\r\n\r\n/**\r\n * Compile Workflow AST to WorkflowConfig\r\n *\r\n * This is the main entry point for compiling a complete workflow.\r\n *\r\n * @param ast - Workflow AST node\r\n * @returns Executable WorkflowConfig that can be passed to runWorkflow()\r\n *\r\n * @example\r\n * ```typescript\r\n * const MyWorkflow = Workflow({\r\n * name: 'my-workflow',\r\n * defaultModel: { adapter: llmAdapter },\r\n * children: Sequence({\r\n * children: [Agent1, Agent2, Agent3]\r\n * })\r\n * });\r\n *\r\n * const config = compileWorkflow(MyWorkflow);\r\n * const result = await runWorkflow(config, inputs);\r\n * ```\r\n */\r\nexport function compileWorkflow(ast: WorkflowNode): WorkflowConfig {\r\n // Validate AST\r\n if (ast.type !== 'Workflow') {\r\n throw new Error(`Expected Workflow node, got ${ast.type}`);\r\n }\r\n\r\n if (!ast.children || ast.children.length !== 1) {\r\n throw new Error('Workflow must have exactly one child (workflow graph)');\r\n }\r\n\r\n // Extract props\r\n const { name, description, defaultModel, state, enhancements } = ast.props;\r\n\r\n if (!name) {\r\n throw new Error('Workflow must have a name');\r\n }\r\n\r\n // Compile the workflow graph\r\n const graph = compileWorkflowNode(ast.children[0]);\r\n\r\n // Build WorkflowConfig\r\n const config: WorkflowConfig = {\r\n name,\r\n graph,\r\n };\r\n\r\n // Add optional properties\r\n if (description) {\r\n config.description = description;\r\n }\r\n\r\n if (defaultModel) {\r\n config.defaultModel = defaultModel;\r\n }\r\n\r\n if (state) {\r\n config.state = state;\r\n }\r\n\r\n if (enhancements) {\r\n config.enhancements = enhancements as any; // Type assertion for WorkflowEnhancements\r\n }\r\n\r\n return config;\r\n}\r\n","/**\r\n * Deity TSX - AST Type Definitions\r\n *\r\n * This module defines the Abstract Syntax Tree (AST) node types for the TSX DSL.\r\n * All nodes are pure data structures (no runtime behavior).\r\n *\r\n * Design principles:\r\n * - Logic only as TS function values (never strings)\r\n * - Text only as text\r\n * - Structure only via TSX AST\r\n */\r\n\r\nimport type { ZodSchema } from 'zod';\r\nimport type { ExecutionContext, LLMLoopResult, Validator, ToolSpec } from '../engine/types.js';\r\n\r\n// ============================================================================\r\n// Base AST Node\r\n// ============================================================================\r\n\r\n/**\r\n * Base interface for all AST nodes\r\n */\r\nexport interface ASTNode {\r\n /** Node type identifier */\r\n type: string;\r\n\r\n /** Node properties (varies by node type) */\r\n props?: Record<string, unknown>;\r\n\r\n /** Child nodes */\r\n children?: ASTNode[];\r\n}\r\n\r\n// ============================================================================\r\n// Agent Node (Root)\r\n// ============================================================================\r\n\r\n/**\r\n * Agent Node - Root node of an agent definition\r\n *\r\n * Represents a complete AI agent with:\r\n * - Identity (id, description, tags)\r\n * - IO schemas (input/output)\r\n * - Behavior specification (Prompt, Observe, Result, Validate, Retry)\r\n */\r\nexport interface AgentNode<I = unknown, O = unknown> extends ASTNode {\r\n type: 'Agent';\r\n props: {\r\n /** Unique agent identifier */\r\n id: string;\r\n\r\n /** Input schema (Zod) */\r\n input: ZodSchema<I>;\r\n\r\n /** Output schema (Zod) */\r\n output: ZodSchema<O>;\r\n\r\n /** Optional description */\r\n description?: string;\r\n\r\n /** Optional tags for categorization */\r\n tags?: string[];\r\n\r\n /** Optional loop-level validator (validates during LLM loop) */\r\n loopValidator?: Validator;\r\n\r\n /** Optional LLM loop configuration */\r\n loopConfig?: {\r\n /** Maximum number of tool execution rounds */\r\n maxToolRounds?: number;\r\n /** Timeout in milliseconds */\r\n timeout?: number;\r\n };\r\n\r\n /** Optional tool definitions (static array) */\r\n tools?: ToolSpec[];\r\n };\r\n\r\n /** Child nodes (Prompt is required, others are optional) */\r\n children: (PromptNode | ObserveNode | ResultNode | ValidateNode | RetryNode | ToolsNode)[];\r\n}\r\n\r\n// ============================================================================\r\n// Prompt Nodes\r\n// ============================================================================\r\n\r\n/**\r\n * Prompt Node - Container for system and user prompts\r\n */\r\nexport interface PromptNode extends ASTNode {\r\n type: 'Prompt';\r\n children: (SystemNode | UserNode)[];\r\n}\r\n\r\n/**\r\n * System Prompt Node\r\n *\r\n * Can be loaded from:\r\n * - File (source: 'file:path/to/prompt.md')\r\n * - Inline (content: 'text')\r\n * - Computed (compute: (ctx) => string)\r\n * - Mixed template (templateParts: TemplatePart[]) - for ToolRef support\r\n */\r\nexport interface SystemNode extends ASTNode {\r\n type: 'System';\r\n props: {\r\n /** File source (e.g., 'file:./prompts/system.md') */\r\n source?: string;\r\n\r\n /** Is this prompt required? (fail-fast if missing) */\r\n required?: boolean;\r\n\r\n /** Inline content */\r\n content?: string;\r\n\r\n /** Computed content (function) */\r\n compute?: (ctx: ExecutionContext) => string | Promise<string>;\r\n\r\n /** Template parts (for mixed text/computed/toolref content) */\r\n templateParts?: TemplatePart[];\r\n };\r\n}\r\n\r\n/**\r\n * User Prompt Node\r\n *\r\n * Can be:\r\n * - Inline (content: 'text')\r\n * - Computed (compute: (ctx) => string)\r\n * - Mixed template (templateParts: TemplatePart[]) - for ToolRef support\r\n */\r\nexport interface UserNode extends ASTNode {\r\n type: 'User';\r\n props: {\r\n /** Inline content */\r\n content?: string;\r\n\r\n /** Computed content (function) */\r\n compute?: (ctx: ExecutionContext) => string | Promise<string>;\r\n\r\n /** Template parts (for mixed text/computed/toolref content) */\r\n templateParts?: TemplatePart[];\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// ToolRef Node\r\n// ============================================================================\r\n\r\n/**\r\n * Template Part - Single part of a mixed-content template\r\n *\r\n * Used by System and User nodes to support inline ToolRef nodes.\r\n */\r\nexport type TemplatePart =\r\n | { kind: 'text'; value: string }\r\n | { kind: 'computed'; compute: (ctx: ExecutionContext) => string | Promise<string> }\r\n | { kind: 'toolref'; toolName: string };\r\n\r\n/**\r\n * ToolRef Node - Reference to a tool name in prompt text\r\n *\r\n * This node acts as a placeholder that gets replaced with the tool's\r\n * runtime ID during prompt compilation.\r\n *\r\n * @example\r\n * ```tsx\r\n * <User>Use <ToolRef tool={MemoryStore} /> to save data.</User>\r\n * // Compiles to: \"Use memory_store to save data.\"\r\n * ```\r\n */\r\nexport interface ToolRefNode extends ASTNode {\r\n type: 'ToolRef';\r\n props: {\r\n /** The tool's runtime ID (e.g., 'memory_store') */\r\n toolName: string;\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// Observe Node\r\n// ============================================================================\r\n\r\n/**\r\n * Observe Node - Declarative observation of LLM execution\r\n *\r\n * Used to extract statistics and metadata from LLM loop results:\r\n * - Tool call counts\r\n * - Success/failure rates\r\n * - Custom metrics\r\n *\r\n * The observed data is passed to Result and Validate nodes.\r\n */\r\nexport interface ObserveNode extends ASTNode {\r\n type: 'Observe';\r\n props: {\r\n /**\r\n * Compute function to extract observations\r\n *\r\n * Must return a plain object with observed values.\r\n * Do NOT mutate llmResult.\r\n */\r\n compute: (llmResult: LLMLoopResult) => Record<string, unknown> | Promise<Record<string, unknown>>;\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// Result Node\r\n// ============================================================================\r\n\r\n/**\r\n * Result Node - Extract structured output from LLM execution\r\n *\r\n * This node is responsible for:\r\n * - Extracting output from llmResult (e.g., tool call arguments)\r\n * - Using observed data from Observe node\r\n * - Returning data that conforms to output schema\r\n */\r\nexport interface ResultNode<O = unknown> extends ASTNode {\r\n type: 'Result';\r\n props: {\r\n /**\r\n * Extract function to produce output\r\n *\r\n * @param ctx - Execution context with inputs\r\n * @param llmResult - Complete LLM loop result\r\n * @param observed - Data from Observe node (if present)\r\n * @returns Output data (must conform to output schema)\r\n */\r\n extract: (\r\n ctx: ExecutionContext,\r\n llmResult: LLMLoopResult,\r\n observed: Record<string, unknown>\r\n ) => O | Promise<O>;\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// Validate Node\r\n// ============================================================================\r\n\r\n/**\r\n * Validation Rule\r\n *\r\n * A single validation rule with:\r\n * - check: boolean condition\r\n * - error: error message if check fails\r\n * - level: severity (error or warning)\r\n */\r\nexport interface ValidationRule {\r\n /** Condition to check (true = pass, false = fail) */\r\n check: boolean;\r\n\r\n /** Error message (shown when check fails) */\r\n error: string;\r\n\r\n /** Severity level (default: 'error') */\r\n level?: 'error' | 'warning';\r\n}\r\n\r\n/**\r\n * Validation Rules - Collection of rules\r\n */\r\nexport interface ValidationRules {\r\n rules: ValidationRule[];\r\n}\r\n\r\n/**\r\n * Validate Node - Declarative validation rules\r\n *\r\n * Used to validate output against business rules.\r\n * Returns structured errors for consistent handling.\r\n */\r\nexport interface ValidateNode extends ASTNode {\r\n type: 'Validate';\r\n props: {\r\n /**\r\n * Rules function to generate validation rules\r\n *\r\n * @param output - Extracted output from Result node\r\n * @param ctx - Execution context\r\n * @param observed - Data from Observe node (if present)\r\n * @returns Validation rules\r\n */\r\n rules: (\r\n output: unknown,\r\n ctx: ExecutionContext,\r\n observed: Record<string, unknown>\r\n ) => ValidationRules | Promise<ValidationRules>;\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// Retry Node\r\n// ============================================================================\r\n\r\n/**\r\n * Retry Node - Retry policy configuration\r\n *\r\n * Specifies how the agent should retry on validation failures.\r\n */\r\nexport interface RetryNode extends ASTNode {\r\n type: 'Retry';\r\n props: {\r\n /** Maximum retry attempts (default: 3) */\r\n maxAttempts?: number;\r\n\r\n /** Include validation errors in retry prompt (default: true) */\r\n feedbackOnError?: boolean;\r\n\r\n /** Retry on tool execution errors (default: true) */\r\n retryOnToolError?: boolean;\r\n\r\n /** Send tool errors to LLM for correction (default: true) */\r\n feedbackErrorToLLM?: boolean;\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// Tools Nodes\r\n// ============================================================================\r\n\r\n/**\r\n * Tools Container Node - Groups tool definitions for an agent\r\n *\r\n * Contains static tool definitions via <ToolDef> or <Tool> children.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Tools>\r\n * <MemoryStore />\r\n * <MemoryRecall />\r\n * <Tool name=\"my_tool\" description=\"...\" input={Schema}>\r\n * {async (params) => ({ ... })}\r\n * </Tool>\r\n * </Tools>\r\n * ```\r\n */\r\nexport interface ToolsNode extends ASTNode {\r\n type: 'Tools';\r\n props: Record<string, never>;\r\n /** Child ToolDef nodes */\r\n children: ToolDefNode[];\r\n}\r\n\r\n/**\r\n * Tool Definition Node - Wraps a single Tool object\r\n *\r\n * @example\r\n * ```tsx\r\n * <ToolDef tool={createFileListTool(context)} />\r\n * ```\r\n */\r\nexport interface ToolDefNode extends ASTNode {\r\n type: 'Tools:Def';\r\n props: {\r\n /** The tool object */\r\n tool: ToolSpec;\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// Type Guards\r\n// ============================================================================\r\n\r\n/**\r\n * Check if a node is an AgentNode\r\n */\r\nexport function isAgentNode(node: ASTNode): node is AgentNode {\r\n return node.type === 'Agent';\r\n}\r\n\r\n/**\r\n * Check if a node is a PromptNode\r\n */\r\nexport function isPromptNode(node: ASTNode): node is PromptNode {\r\n return node.type === 'Prompt';\r\n}\r\n\r\n/**\r\n * Check if a node is a SystemNode\r\n */\r\nexport function isSystemNode(node: ASTNode): node is SystemNode {\r\n return node.type === 'System';\r\n}\r\n\r\n/**\r\n * Check if a node is a UserNode\r\n */\r\nexport function isUserNode(node: ASTNode): node is UserNode {\r\n return node.type === 'User';\r\n}\r\n\r\n/**\r\n * Check if a node is an ObserveNode\r\n */\r\nexport function isObserveNode(node: ASTNode): node is ObserveNode {\r\n return node.type === 'Observe';\r\n}\r\n\r\n/**\r\n * Check if a node is a ResultNode\r\n */\r\nexport function isResultNode(node: ASTNode): node is ResultNode {\r\n return node.type === 'Result';\r\n}\r\n\r\n/**\r\n * Check if a node is a ValidateNode\r\n */\r\nexport function isValidateNode(node: ASTNode): node is ValidateNode {\r\n return node.type === 'Validate';\r\n}\r\n\r\n/**\r\n * Check if a node is a RetryNode\r\n */\r\nexport function isRetryNode(node: ASTNode): node is RetryNode {\r\n return node.type === 'Retry';\r\n}\r\n\r\n/**\r\n * Check if a node is a ToolsNode\r\n */\r\nexport function isToolsNode(node: ASTNode): node is ToolsNode {\r\n return node.type === 'Tools';\r\n}\r\n\r\n/**\r\n * Check if a node is a ToolDefNode\r\n */\r\nexport function isToolDefNode(node: ASTNode): node is ToolDefNode {\r\n return node.type === 'Tools:Def';\r\n}\r\n\r\n/**\r\n * Check if a node is a ToolRefNode\r\n */\r\nexport function isToolRefNode(node: ASTNode): node is ToolRefNode {\r\n return node.type === 'ToolRef';\r\n}\r\n\r\n// ============================================================================\r\n// Helper Types\r\n// ============================================================================\r\n\r\n/**\r\n * Extract input type from AgentNode\r\n */\r\nexport type AgentInput<T extends AgentNode<any, any>> = T extends AgentNode<infer I, any> ? I : never;\r\n\r\n/**\r\n * Extract output type from AgentNode\r\n */\r\nexport type AgentOutput<T extends AgentNode<any, any>> = T extends AgentNode<any, infer O> ? O : never;\r\n\r\n// ============================================================================\r\n// Workflow Nodes\r\n// ============================================================================\r\n\r\n/**\r\n * Workflow Sequence Node - Execute children in order\r\n */\r\nexport interface WorkflowSequenceNode extends ASTNode {\r\n type: 'WorkflowSequence';\r\n children: WorkflowChildNode[];\r\n}\r\n\r\n/**\r\n * Workflow Parallel Node - Execute children concurrently\r\n */\r\nexport interface WorkflowParallelNode extends ASTNode {\r\n type: 'WorkflowParallel';\r\n children: WorkflowChildNode[];\r\n}\r\n\r\n/**\r\n * Workflow Conditional Node - Execute children based on condition\r\n */\r\nexport interface WorkflowConditionalNode extends ASTNode {\r\n type: 'WorkflowConditional';\r\n props: {\r\n /** Condition function (true = first child, false = second child) */\r\n condition: (ctx: ExecutionContext) => boolean | Promise<boolean>;\r\n };\r\n children: [WorkflowChildNode] | [WorkflowChildNode, WorkflowChildNode];\r\n}\r\n\r\n/**\r\n * Workflow Loop Node - Execute child N times\r\n */\r\nexport interface WorkflowLoopNode extends ASTNode {\r\n type: 'WorkflowLoop';\r\n props: {\r\n /** Number of iterations */\r\n iterations: number;\r\n };\r\n children: [WorkflowChildNode];\r\n}\r\n\r\n/**\r\n * Workflow ForEach Node - Execute child for each item in array\r\n */\r\nexport interface WorkflowForEachNode extends ASTNode {\r\n type: 'WorkflowForEach';\r\n props: {\r\n /** Array of items or function to resolve items */\r\n items: unknown[] | ((ctx: ExecutionContext) => unknown[] | Promise<unknown[]>);\r\n /** How to inject item into context ('property' | 'merge' | 'replace') */\r\n itemMode: string;\r\n /** Property key for 'property' mode */\r\n itemKey: string;\r\n /** Error handling mode ('stop' | 'continue' | 'skip') */\r\n errorMode: string;\r\n /** Whether to collect results */\r\n collectResults: boolean;\r\n };\r\n children: [WorkflowChildNode];\r\n}\r\n\r\n/**\r\n * Union type for workflow child nodes\r\n * Can be either an Agent or a workflow structure node\r\n */\r\nexport type WorkflowChildNode =\r\n | AgentNode\r\n | WorkflowSequenceNode\r\n | WorkflowParallelNode\r\n | WorkflowConditionalNode\r\n | WorkflowLoopNode\r\n | WorkflowForEachNode;\r\n\r\n// ============================================================================\r\n// Workflow Type Guards\r\n// ============================================================================\r\n\r\n/**\r\n * Check if a node is a WorkflowSequenceNode\r\n */\r\nexport function isWorkflowSequenceNode(node: ASTNode): node is WorkflowSequenceNode {\r\n return node.type === 'WorkflowSequence';\r\n}\r\n\r\n/**\r\n * Check if a node is a WorkflowParallelNode\r\n */\r\nexport function isWorkflowParallelNode(node: ASTNode): node is WorkflowParallelNode {\r\n return node.type === 'WorkflowParallel';\r\n}\r\n\r\n/**\r\n * Check if a node is a WorkflowConditionalNode\r\n */\r\nexport function isWorkflowConditionalNode(node: ASTNode): node is WorkflowConditionalNode {\r\n return node.type === 'WorkflowConditional';\r\n}\r\n\r\n/**\r\n * Check if a node is a WorkflowLoopNode\r\n */\r\nexport function isWorkflowLoopNode(node: ASTNode): node is WorkflowLoopNode {\r\n return node.type === 'WorkflowLoop';\r\n}\r\n\r\n/**\r\n * Check if a node is a WorkflowForEachNode\r\n */\r\nexport function isWorkflowForEachNode(node: ASTNode): node is WorkflowForEachNode {\r\n return node.type === 'WorkflowForEach';\r\n}\r\n\r\n// ============================================================================\r\n// Workflow Container Node\r\n// ============================================================================\r\n\r\n/**\r\n * Workflow Node - Top-level workflow container\r\n *\r\n * Contains the complete workflow configuration including:\r\n * - Name and description\r\n * - Default model configuration\r\n * - Workflow graph (Sequence, Parallel, Conditional, Loop, or Agent)\r\n * - Optional enhancements (conversation, memory, session, UI)\r\n */\r\nexport interface WorkflowNode extends ASTNode {\r\n type: 'Workflow';\r\n props: {\r\n /** Workflow name */\r\n name: string;\r\n\r\n /** Optional description */\r\n description?: string;\r\n\r\n /** Default LLM model configuration */\r\n defaultModel?: {\r\n adapter: any; // LLMAdapter type from engine/types.ts\r\n config?: any; // GenerationConfig type from engine/types.ts\r\n };\r\n\r\n /** Optional state storage */\r\n state?: {\r\n store: any; // StateStore type from engine/types.ts\r\n };\r\n\r\n /** Optional enhancements */\r\n enhancements?: {\r\n /** Conversation management */\r\n conversation?: {\r\n maxTokens: number;\r\n pruneThreshold: number;\r\n messageRetentionPolicy?: unknown;\r\n };\r\n\r\n /** Memory management */\r\n memory?: {\r\n coreBudget: {\r\n maxItems: number;\r\n maxTotalSize: number;\r\n };\r\n detailedBudget?: {\r\n maxItems: number;\r\n maxTotalSize: number;\r\n };\r\n };\r\n\r\n /** Session persistence */\r\n session?: {\r\n directory: string;\r\n autoSave?: boolean;\r\n };\r\n\r\n /** UI updates */\r\n ui?: any; // UIUpdateBridge type\r\n\r\n /** Application state store (isolated from AI memory) */\r\n appState?: any; // StateStore type\r\n };\r\n };\r\n\r\n /** Single child representing the workflow graph */\r\n children: [WorkflowChildNode];\r\n}\r\n\r\n/**\r\n * Check if a node is a WorkflowNode\r\n */\r\nexport function isWorkflowNode(node: ASTNode): node is WorkflowNode {\r\n return node.type === 'Workflow';\r\n}\r\n","/**\r\n * Deity TSX - Observe Utilities\r\n *\r\n * Helper functions for building Observe nodes.\r\n * Provides common patterns for extracting statistics from LLM results.\r\n *\r\n * Design principles:\r\n * - Pure functions (no side effects)\r\n * - Composable utilities\r\n * - Type-safe\r\n * - Reusable patterns\r\n */\r\n\r\nimport type { LLMLoopResult } from '../engine/types.js';\r\n\r\n/**\r\n * Tool Call Filter\r\n *\r\n * Function to filter tool calls\r\n */\r\nexport type ToolCallFilter = (toolCall: any) => boolean;\r\n\r\n/**\r\n * Observe Utilities\r\n *\r\n * Collection of helper functions for common observation patterns.\r\n */\r\nexport class ObserveUtils {\r\n /**\r\n * Count total tool calls\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * totalCalls: ObserveUtils.countToolCalls(llmResult),\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\n static countToolCalls(llmResult: LLMLoopResult): number {\r\n return llmResult.response.toolCalls?.length ?? 0;\r\n }\r\n\r\n /**\r\n * Count tool calls by name\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * planningCalls: ObserveUtils.countToolCallsByName(\r\n * llmResult,\r\n * 'planning_create'\r\n * ),\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\n static countToolCallsByName(llmResult: LLMLoopResult, name: string): number {\r\n return llmResult.response.toolCalls?.filter(tc => tc.name === name).length ?? 0;\r\n }\r\n\r\n /**\r\n * Count tool calls matching filter\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * successfulCalls: ObserveUtils.countToolCallsWhere(\r\n * llmResult,\r\n * tc => tc.result?.success === true\r\n * ),\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\n static countToolCallsWhere(\r\n llmResult: LLMLoopResult,\r\n filter: ToolCallFilter\r\n ): number {\r\n return llmResult.response.toolCalls?.filter(filter).length ?? 0;\r\n }\r\n\r\n /**\r\n * Get list of unique tool names called\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * toolsUsed: ObserveUtils.getToolNames(llmResult),\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\n static getToolNames(llmResult: LLMLoopResult): string[] {\r\n const names = llmResult.response.toolCalls?.map(tc => tc.name) ?? [];\r\n return Array.from(new Set(names));\r\n }\r\n\r\n /**\r\n * Count occurrences of each tool\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * toolFrequency: ObserveUtils.getToolFrequency(llmResult),\r\n * // Result: { file_read: 5, memory_store: 3, ... }\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\n static getToolFrequency(llmResult: LLMLoopResult): Record<string, number> {\r\n const frequency: Record<string, number> = {};\r\n\r\n for (const tc of llmResult.response.toolCalls ?? []) {\r\n frequency[tc.name] = (frequency[tc.name] || 0) + 1;\r\n }\r\n\r\n return frequency;\r\n }\r\n\r\n /**\r\n * Check if specific tool was called\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * usedPlanning: ObserveUtils.hasToolCall(llmResult, 'planning_create'),\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\n static hasToolCall(llmResult: LLMLoopResult, name: string): boolean {\r\n return llmResult.response.toolCalls?.some(tc => tc.name === name) ?? false;\r\n }\r\n\r\n /**\r\n * Check if any tool matching filter was called\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * hasErrors: ObserveUtils.hasToolCallWhere(\r\n * llmResult,\r\n * tc => tc.error !== undefined\r\n * ),\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\n static hasToolCallWhere(\r\n llmResult: LLMLoopResult,\r\n filter: ToolCallFilter\r\n ): boolean {\r\n return llmResult.response.toolCalls?.some(filter) ?? false;\r\n }\r\n\r\n /**\r\n * Get content length\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * responseLength: ObserveUtils.getContentLength(llmResult),\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\n static getContentLength(llmResult: LLMLoopResult): number {\r\n return llmResult.response.content?.length ?? 0;\r\n }\r\n\r\n /**\r\n * Count successful tool calls\r\n *\r\n * Note: Since ToolCall type only has id/name/arguments, we consider\r\n * a call \"successful\" if it has valid arguments (not an error indicator).\r\n * For more sophisticated success tracking, use custom observers.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * successCount: ObserveUtils.countSuccessfulCalls(llmResult),\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\n static countSuccessfulCalls(llmResult: LLMLoopResult): number {\r\n // Since we don't have result/error info in ToolCall type,\r\n // we count all tool calls that have arguments\r\n return llmResult.response.toolCalls?.filter(tc => tc.arguments).length ?? 0;\r\n }\r\n\r\n /**\r\n * Count failed tool calls\r\n *\r\n * Note: Since ToolCall type only has id/name/arguments, we cannot\r\n * determine failures. This returns 0 for compatibility.\r\n * For error tracking, use custom observers or check messages array.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * failureCount: ObserveUtils.countFailedCalls(llmResult),\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\n static countFailedCalls(_llmResult: LLMLoopResult): number {\r\n // ToolCall type doesn't include error information\r\n // Return 0 for compatibility\r\n return 0;\r\n }\r\n\r\n /**\r\n * Get tool call arguments\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => {\r\n * const args = ObserveUtils.getToolArguments(\r\n * llmResult,\r\n * 'planning_create'\r\n * );\r\n * return {\r\n * taskCount: args?.[0]?.tasks?.length ?? 0,\r\n * };\r\n * }}\r\n * </Observe>\r\n * ```\r\n */\r\n static getToolArguments(\r\n llmResult: LLMLoopResult,\r\n name: string\r\n ): any[] {\r\n return llmResult.response.toolCalls\r\n ?.filter((tc: any) => tc.name === name)\r\n .map((tc: any) => {\r\n if (typeof tc.arguments === 'string') {\r\n try {\r\n return JSON.parse(tc.arguments);\r\n } catch {\r\n return tc.arguments;\r\n }\r\n }\r\n return tc.arguments;\r\n }) ?? [];\r\n }\r\n\r\n /**\r\n * Get first tool call matching name\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => {\r\n * const planCall = ObserveUtils.findToolCall(\r\n * llmResult,\r\n * 'planning_create'\r\n * );\r\n * return {\r\n * hasPlan: planCall !== null,\r\n * };\r\n * }}\r\n * </Observe>\r\n * ```\r\n */\r\n static findToolCall(\r\n llmResult: LLMLoopResult,\r\n name: string\r\n ): any | null {\r\n return llmResult.response.toolCalls?.find((tc: any) => tc.name === name) ?? null;\r\n }\r\n\r\n /**\r\n * Get all tool calls matching filter\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => {\r\n * const readCalls = ObserveUtils.filterToolCalls(\r\n * llmResult,\r\n * tc => tc.name.startsWith('file_')\r\n * );\r\n * return {\r\n * fileOpsCount: readCalls.length,\r\n * };\r\n * }}\r\n * </Observe>\r\n * ```\r\n */\r\n static filterToolCalls(\r\n llmResult: LLMLoopResult,\r\n filter: ToolCallFilter\r\n ): any[] {\r\n return llmResult.response.toolCalls?.filter(filter) ?? [];\r\n }\r\n\r\n /**\r\n * Check if content contains text\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * mentionedError: ObserveUtils.contentContains(llmResult, 'error'),\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\n static contentContains(llmResult: LLMLoopResult, text: string): boolean {\r\n return llmResult.response.content?.includes(text) ?? false;\r\n }\r\n\r\n /**\r\n * Check if content matches regex\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * hasCodeBlock: ObserveUtils.contentMatches(llmResult, /```[\\s\\S]*```/),\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\n static contentMatches(llmResult: LLMLoopResult, regex: RegExp): boolean {\r\n return regex.test(llmResult.response.content ?? '');\r\n }\r\n\r\n /**\r\n * Calculate success rate\r\n *\r\n * @example\r\n * ```tsx\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * successRate: ObserveUtils.getSuccessRate(llmResult),\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\n static getSuccessRate(llmResult: LLMLoopResult): number {\r\n const total = this.countToolCalls(llmResult);\r\n if (total === 0) return 0;\r\n\r\n const successful = this.countSuccessfulCalls(llmResult);\r\n return successful / total;\r\n }\r\n}\r\n\r\n/**\r\n * Create common observation patterns\r\n */\r\nexport const observe = {\r\n /**\r\n * Basic statistics\r\n */\r\n basicStats: (llmResult: LLMLoopResult) => ({\r\n totalToolCalls: ObserveUtils.countToolCalls(llmResult),\r\n uniqueTools: ObserveUtils.getToolNames(llmResult).length,\r\n contentLength: ObserveUtils.getContentLength(llmResult),\r\n successRate: ObserveUtils.getSuccessRate(llmResult),\r\n }),\r\n\r\n /**\r\n * Tool call statistics\r\n */\r\n toolStats: (llmResult: LLMLoopResult) => ({\r\n toolCalls: ObserveUtils.countToolCalls(llmResult),\r\n toolFrequency: ObserveUtils.getToolFrequency(llmResult),\r\n toolNames: ObserveUtils.getToolNames(llmResult),\r\n successfulCalls: ObserveUtils.countSuccessfulCalls(llmResult),\r\n failedCalls: ObserveUtils.countFailedCalls(llmResult),\r\n }),\r\n\r\n /**\r\n * Success/failure tracking\r\n */\r\n successTracking: (llmResult: LLMLoopResult) => ({\r\n successful: ObserveUtils.countSuccessfulCalls(llmResult),\r\n failed: ObserveUtils.countFailedCalls(llmResult),\r\n successRate: ObserveUtils.getSuccessRate(llmResult),\r\n hasErrors: ObserveUtils.countFailedCalls(llmResult) > 0,\r\n }),\r\n};\r\n\r\n/**\r\n * Create tool-specific observer\r\n *\r\n * @example\r\n * ```tsx\r\n * const observePlanning = createToolObserver('planning_create');\r\n *\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * ...observePlanning(llmResult),\r\n * // Returns: { called: true, count: 2, arguments: [...] }\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\nexport function createToolObserver(toolName: string) {\r\n return (llmResult: LLMLoopResult) => ({\r\n called: ObserveUtils.hasToolCall(llmResult, toolName),\r\n count: ObserveUtils.countToolCallsByName(llmResult, toolName),\r\n arguments: ObserveUtils.getToolArguments(llmResult, toolName),\r\n firstCall: ObserveUtils.findToolCall(llmResult, toolName),\r\n });\r\n}\r\n\r\n/**\r\n * Create pattern observer\r\n *\r\n * @example\r\n * ```tsx\r\n * const observeFileOps = createPatternObserver(\r\n * tc => tc.name.startsWith('file_')\r\n * );\r\n *\r\n * <Observe>\r\n * {(llmResult) => ({\r\n * fileOps: observeFileOps(llmResult),\r\n * // Returns: { count: 5, calls: [...] }\r\n * })}\r\n * </Observe>\r\n * ```\r\n */\r\nexport function createPatternObserver(filter: ToolCallFilter) {\r\n return (llmResult: LLMLoopResult) => ({\r\n count: ObserveUtils.countToolCallsWhere(llmResult, filter),\r\n calls: ObserveUtils.filterToolCalls(llmResult, filter),\r\n hasMatches: ObserveUtils.hasToolCallWhere(llmResult, filter),\r\n });\r\n}\r\n","/**\r\n * Deity TSX - Result Utilities\r\n *\r\n * Helper functions for building Result nodes.\r\n * Provides common patterns for extracting and transforming LLM output.\r\n *\r\n * Design principles:\r\n * - Pure functions (no side effects)\r\n * - Type-safe transformations\r\n * - Composable utilities\r\n * - Schema-driven validation\r\n */\r\n\r\nimport type { LLMLoopResult } from '../engine/types.js';\r\nimport { z } from 'zod';\r\n\r\n/**\r\n * Result extraction error\r\n */\r\nexport class ResultExtractionError extends Error {\r\n constructor(\r\n message: string,\r\n public readonly context?: {\r\n content?: string;\r\n toolCalls?: any[];\r\n attemptedParsers?: string[];\r\n }\r\n ) {\r\n super(message);\r\n this.name = 'ResultExtractionError';\r\n }\r\n}\r\n\r\n/**\r\n * Result Utils\r\n *\r\n * Collection of helper functions for common result extraction patterns.\r\n */\r\nexport class ResultUtils {\r\n /**\r\n * Extract JSON from LLM content\r\n *\r\n * Looks for JSON in code blocks or raw JSON in the content.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Result>\r\n * {(ctx, llmResult) => {\r\n * const data = ResultUtils.extractJSON(llmResult);\r\n * return { result: data };\r\n * }}\r\n * </Result>\r\n * ```\r\n */\r\n static extractJSON<T = any>(llmResult: LLMLoopResult): T {\r\n const content = llmResult.response.content || '';\r\n\r\n // Try to find JSON in code blocks\r\n const codeBlockMatch = content.match(/```(?:json)?\\s*([\\s\\S]*?)\\s*```/);\r\n if (codeBlockMatch) {\r\n try {\r\n return JSON.parse(codeBlockMatch[1]);\r\n } catch (error) {\r\n throw new ResultExtractionError('Failed to parse JSON from code block', {\r\n content: codeBlockMatch[1],\r\n attemptedParsers: ['code-block'],\r\n });\r\n }\r\n }\r\n\r\n // Try to parse the entire content as JSON\r\n try {\r\n return JSON.parse(content);\r\n } catch (error) {\r\n throw new ResultExtractionError('Failed to parse content as JSON', {\r\n content,\r\n attemptedParsers: ['code-block', 'raw'],\r\n });\r\n }\r\n }\r\n\r\n /**\r\n * Extract JSON with Zod schema validation\r\n *\r\n * @example\r\n * ```tsx\r\n * const OutputSchema = z.object({\r\n * summary: z.string(),\r\n * items: z.array(z.string()),\r\n * });\r\n *\r\n * <Result>\r\n * {(ctx, llmResult) => {\r\n * const data = ResultUtils.extractWithSchema(llmResult, OutputSchema);\r\n * return data;\r\n * }}\r\n * </Result>\r\n * ```\r\n */\r\n static extractWithSchema<T extends z.ZodType>(\r\n llmResult: LLMLoopResult,\r\n schema: T\r\n ): z.infer<T> {\r\n const json = this.extractJSON(llmResult);\r\n\r\n try {\r\n return schema.parse(json);\r\n } catch (error) {\r\n if (error instanceof z.ZodError) {\r\n throw new ResultExtractionError('Schema validation failed', {\r\n content: JSON.stringify(json),\r\n attemptedParsers: ['schema-validation'],\r\n });\r\n }\r\n throw error;\r\n }\r\n }\r\n\r\n /**\r\n * Extract from specific tool call result\r\n *\r\n * @example\r\n * ```tsx\r\n * <Result>\r\n * {(ctx, llmResult) => {\r\n * const planData = ResultUtils.extractFromToolCall(\r\n * llmResult,\r\n * 'planning_create'\r\n * );\r\n * return { plan: planData };\r\n * }}\r\n * </Result>\r\n * ```\r\n */\r\n static extractFromToolCall(llmResult: LLMLoopResult, toolName: string): any {\r\n const toolCall = llmResult.response.toolCalls?.find(tc => tc.name === toolName);\r\n\r\n if (!toolCall) {\r\n throw new ResultExtractionError(`Tool call not found: ${toolName}`, {\r\n toolCalls: llmResult.response.toolCalls,\r\n });\r\n }\r\n\r\n // Return the arguments\r\n if (toolCall.arguments) {\r\n if (typeof toolCall.arguments === 'string') {\r\n try {\r\n return JSON.parse(toolCall.arguments);\r\n } catch {\r\n return toolCall.arguments;\r\n }\r\n }\r\n return toolCall.arguments;\r\n }\r\n\r\n throw new ResultExtractionError(`Tool call has no result or arguments: ${toolName}`, {\r\n toolCalls: [toolCall],\r\n });\r\n }\r\n\r\n /**\r\n * Extract text content (no JSON parsing)\r\n *\r\n * @example\r\n * ```tsx\r\n * <Result>\r\n * {(ctx, llmResult) => ({\r\n * summary: ResultUtils.extractText(llmResult),\r\n * })}\r\n * </Result>\r\n * ```\r\n */\r\n static extractText(llmResult: LLMLoopResult): string {\r\n return llmResult.response.content || '';\r\n }\r\n\r\n /**\r\n * Extract code block by language\r\n *\r\n * @example\r\n * ```tsx\r\n * <Result>\r\n * {(ctx, llmResult) => ({\r\n * code: ResultUtils.extractCodeBlock(llmResult, 'typescript'),\r\n * })}\r\n * </Result>\r\n * ```\r\n */\r\n static extractCodeBlock(llmResult: LLMLoopResult, language?: string): string {\r\n const content = llmResult.response.content || '';\r\n const pattern = language\r\n ? new RegExp(`\\`\\`\\`${language}\\\\s*([\\\\s\\\\S]*?)\\\\s*\\`\\`\\``)\r\n : /```(?:\\w+)?\\s*([\\s\\S]*?)\\s*```/;\r\n\r\n const match = content.match(pattern);\r\n if (!match) {\r\n throw new ResultExtractionError(\r\n language ? `No ${language} code block found` : 'No code block found',\r\n { content }\r\n );\r\n }\r\n\r\n return match[1];\r\n }\r\n\r\n /**\r\n * Extract all code blocks\r\n *\r\n * @example\r\n * ```tsx\r\n * <Result>\r\n * {(ctx, llmResult) => ({\r\n * codeBlocks: ResultUtils.extractAllCodeBlocks(llmResult),\r\n * })}\r\n * </Result>\r\n * ```\r\n */\r\n static extractAllCodeBlocks(llmResult: LLMLoopResult): Array<{\r\n language: string | null;\r\n code: string;\r\n }> {\r\n const content = llmResult.response.content || '';\r\n const pattern = /```(\\w+)?\\s*([\\s\\S]*?)\\s*```/g;\r\n const blocks: Array<{ language: string | null; code: string }> = [];\r\n\r\n let match;\r\n while ((match = pattern.exec(content)) !== null) {\r\n blocks.push({\r\n language: match[1] || null,\r\n code: match[2],\r\n });\r\n }\r\n\r\n return blocks;\r\n }\r\n\r\n /**\r\n * Try multiple extraction strategies\r\n *\r\n * @example\r\n * ```tsx\r\n * <Result>\r\n * {(ctx, llmResult) => {\r\n * const data = ResultUtils.tryExtract(llmResult, [\r\n * (result) => ResultUtils.extractJSON(result),\r\n * (result) => ({ fallback: ResultUtils.extractText(result) }),\r\n * ]);\r\n * return data;\r\n * }}\r\n * </Result>\r\n * ```\r\n */\r\n static tryExtract<T = any>(\r\n llmResult: LLMLoopResult,\r\n extractors: Array<(result: LLMLoopResult) => T>\r\n ): T {\r\n const errors: Error[] = [];\r\n\r\n for (const extractor of extractors) {\r\n try {\r\n return extractor(llmResult);\r\n } catch (error) {\r\n errors.push(error as Error);\r\n }\r\n }\r\n\r\n throw new ResultExtractionError('All extraction strategies failed', {\r\n content: llmResult.response.content,\r\n attemptedParsers: errors.map(e => e.message),\r\n });\r\n }\r\n\r\n /**\r\n * Normalize partial data with defaults\r\n *\r\n * Useful when LLM might return incomplete data.\r\n *\r\n * @example\r\n * ```tsx\r\n * <Result>\r\n * {(ctx, llmResult) => {\r\n * const raw = ResultUtils.extractJSON(llmResult);\r\n * return ResultUtils.normalize(raw, {\r\n * status: 'unknown',\r\n * items: [],\r\n * metadata: {},\r\n * });\r\n * }}\r\n * </Result>\r\n * ```\r\n */\r\n static normalize<T extends Record<string, any>>(\r\n data: Partial<T>,\r\n defaults: T\r\n ): T {\r\n return { ...defaults, ...data };\r\n }\r\n\r\n /**\r\n * Transform data with mapper function\r\n *\r\n * @example\r\n * ```tsx\r\n * <Result>\r\n * {(ctx, llmResult) => {\r\n * const raw = ResultUtils.extractJSON(llmResult);\r\n * return ResultUtils.transform(raw, (data) => ({\r\n * id: data.id,\r\n * name: data.name.toUpperCase(),\r\n * createdAt: new Date(),\r\n * }));\r\n * }}\r\n * </Result>\r\n * ```\r\n */\r\n static transform<TInput, TOutput>(\r\n data: TInput,\r\n mapper: (input: TInput) => TOutput\r\n ): TOutput {\r\n return mapper(data);\r\n }\r\n\r\n /**\r\n * Extract and validate with custom validator\r\n *\r\n * @example\r\n * ```tsx\r\n * <Result>\r\n * {(ctx, llmResult) => {\r\n * return ResultUtils.extractAndValidate(\r\n * llmResult,\r\n * ResultUtils.extractJSON,\r\n * (data) => {\r\n * if (!data.id) throw new Error('Missing id');\r\n * return data;\r\n * }\r\n * );\r\n * }}\r\n * </Result>\r\n * ```\r\n */\r\n static extractAndValidate<T>(\r\n llmResult: LLMLoopResult,\r\n extractor: (result: LLMLoopResult) => T,\r\n validator: (data: T) => T\r\n ): T {\r\n const data = extractor(llmResult);\r\n return validator(data);\r\n }\r\n\r\n /**\r\n * Merge observed data with extracted output\r\n *\r\n * @example\r\n * ```tsx\r\n * <Result>\r\n * {(ctx, llmResult, observed) => {\r\n * const output = ResultUtils.extractJSON(llmResult);\r\n * return ResultUtils.mergeWithObserved(output, observed, {\r\n * toolCallCount: observed.totalToolCalls,\r\n * executionTime: observed.executionTime,\r\n * });\r\n * }}\r\n * </Result>\r\n * ```\r\n */\r\n static mergeWithObserved<TOutput extends Record<string, any>>(\r\n output: TOutput,\r\n _observed: Record<string, any>,\r\n mapping: Record<string, any>\r\n ): TOutput & Record<string, any> {\r\n const merged: any = { ...output };\r\n\r\n for (const [key, value] of Object.entries(mapping)) {\r\n merged[key] = value;\r\n }\r\n\r\n return merged;\r\n }\r\n}\r\n\r\n/**\r\n * Common result extraction patterns\r\n */\r\nexport const result = {\r\n /**\r\n * JSON extraction with fallback to text\r\n */\r\n jsonOrText: (llmResult: LLMLoopResult) => {\r\n try {\r\n return ResultUtils.extractJSON(llmResult);\r\n } catch {\r\n return { text: ResultUtils.extractText(llmResult) };\r\n }\r\n },\r\n\r\n /**\r\n * Extract first code block or empty string\r\n */\r\n codeOrEmpty: (llmResult: LLMLoopResult, language?: string) => {\r\n try {\r\n return ResultUtils.extractCodeBlock(llmResult, language);\r\n } catch {\r\n return '';\r\n }\r\n },\r\n\r\n /**\r\n * Extract all tool calls with arguments\r\n */\r\n allToolCalls: (llmResult: LLMLoopResult) => {\r\n return (llmResult.response.toolCalls || [])\r\n .map((tc: any) => ({\r\n tool: tc.name,\r\n arguments: typeof tc.arguments === 'string'\r\n ? ((() => { try { return JSON.parse(tc.arguments); } catch { return tc.arguments; } })())\r\n : tc.arguments,\r\n }));\r\n },\r\n\r\n /**\r\n * Simple text response\r\n */\r\n text: (llmResult: LLMLoopResult) => ({\r\n response: ResultUtils.extractText(llmResult),\r\n }),\r\n};\r\n\r\n/**\r\n * Create schema-based extractor\r\n *\r\n * @example\r\n * ```tsx\r\n * const extractOutput = createSchemaExtractor(z.object({\r\n * summary: z.string(),\r\n * items: z.array(z.string()),\r\n * }));\r\n *\r\n * <Result>\r\n * {(ctx, llmResult) => extractOutput(llmResult)}\r\n * </Result>\r\n * ```\r\n */\r\nexport function createSchemaExtractor<T extends z.ZodType>(schema: T) {\r\n return (llmResult: LLMLoopResult): z.infer<T> => {\r\n return ResultUtils.extractWithSchema(llmResult, schema);\r\n };\r\n}\r\n\r\n/**\r\n * Create tool-based extractor\r\n *\r\n * @example\r\n * ```tsx\r\n * const extractPlan = createToolExtractor('planning_create');\r\n *\r\n * <Result>\r\n * {(ctx, llmResult) => ({\r\n * plan: extractPlan(llmResult),\r\n * })}\r\n * </Result>\r\n * ```\r\n */\r\nexport function createToolExtractor(toolName: string) {\r\n return (llmResult: LLMLoopResult) => {\r\n return ResultUtils.extractFromToolCall(llmResult, toolName);\r\n };\r\n}\r\n\r\n/**\r\n * Create fallback extractor\r\n *\r\n * @example\r\n * ```tsx\r\n * const extract = createFallbackExtractor(\r\n * (result) => ResultUtils.extractJSON(result),\r\n * (result) => ({ text: ResultUtils.extractText(result) })\r\n * );\r\n *\r\n * <Result>{(ctx, llmResult) => extract(llmResult)}</Result>\r\n * ```\r\n */\r\nexport function createFallbackExtractor<T = any>(\r\n ...extractors: Array<(result: LLMLoopResult) => T>\r\n) {\r\n return (llmResult: LLMLoopResult): T => {\r\n return ResultUtils.tryExtract(llmResult, extractors);\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Validate Utilities\r\n *\r\n * Helper functions for building Validate nodes.\r\n * Provides common patterns for validating agent output.\r\n *\r\n * Design principles:\r\n * - Pure functions (no side effects)\r\n * - Composable validators\r\n * - Clear error messages\r\n * - Schema-driven validation\r\n */\r\n\r\nimport { z } from 'zod';\r\nimport type { ValidationRules } from '../ast/types.js';\r\n\r\n/**\r\n * Validation result\r\n */\r\nexport interface ValidationResult {\r\n /** Whether validation passed */\r\n valid: boolean;\r\n\r\n /** Feedback message for LLM when validation fails (used by validators) */\r\n feedback?: string;\r\n\r\n /** Optional message for logging/debugging */\r\n message?: string;\r\n\r\n /** Legacy error list (deprecated, use feedback instead) */\r\n errors?: string[];\r\n}\r\n\r\n/**\r\n * Validator function type\r\n */\r\nexport type ValidatorFunction<T = any> = (\r\n output: T,\r\n observed?: Record<string, any>\r\n) => ValidationResult;\r\n\r\n/**\r\n * Convert ValidationResult to ValidationRules format\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output) => toValidationRules(\r\n * ValidateUtils.validateSchema(output, schema)\r\n * )}\r\n * </Validate>\r\n * ```\r\n */\r\nexport function toValidationRules(result: ValidationResult): ValidationRules {\r\n if (result.valid) {\r\n return { rules: [] };\r\n }\r\n\r\n return {\r\n rules: (result.errors || []).map(error => ({\r\n check: false,\r\n error,\r\n })),\r\n };\r\n}\r\n\r\n/**\r\n * Validate Utils\r\n *\r\n * Collection of helper functions for common validation patterns.\r\n */\r\nexport class ValidateUtils {\r\n /**\r\n * Validate with Zod schema\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output) => ValidateUtils.validateSchema(output, OutputSchema)}\r\n * </Validate>\r\n * ```\r\n */\r\n static validateSchema<T extends z.ZodType>(\r\n output: any,\r\n schema: T\r\n ): ValidationResult {\r\n try {\r\n schema.parse(output);\r\n return { valid: true };\r\n } catch (error) {\r\n if (error instanceof z.ZodError) {\r\n return {\r\n valid: false,\r\n errors: error.issues.map(issue => `${issue.path.join('.')}: ${issue.message}`),\r\n };\r\n }\r\n return {\r\n valid: false,\r\n errors: ['Unknown validation error'],\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Validate required fields\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output) => ValidateUtils.requireFields(output, ['id', 'name', 'status'])}\r\n * </Validate>\r\n * ```\r\n */\r\n static requireFields<T extends Record<string, any>>(\r\n output: T,\r\n fields: Array<keyof T>\r\n ): ValidationResult {\r\n const missing = fields.filter(field => {\r\n const value = output[field];\r\n return value === undefined || value === null || value === '';\r\n });\r\n\r\n if (missing.length > 0) {\r\n return {\r\n valid: false,\r\n errors: missing.map(field => `Missing required field: ${String(field)}`),\r\n };\r\n }\r\n\r\n return { valid: true };\r\n }\r\n\r\n /**\r\n * Validate field values\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output) => ValidateUtils.validateFields(output, {\r\n * priority: (val) => ['low', 'medium', 'high'].includes(val),\r\n * count: (val) => val > 0,\r\n * })}\r\n * </Validate>\r\n * ```\r\n */\r\n static validateFields<T extends Record<string, any>>(\r\n output: T,\r\n validators: { [K in keyof T]?: (value: T[K]) => boolean }\r\n ): ValidationResult {\r\n const errors: string[] = [];\r\n\r\n for (const [field, validator] of Object.entries(validators)) {\r\n const value = output[field];\r\n if (validator && !validator(value)) {\r\n errors.push(`Invalid value for field: ${field}`);\r\n }\r\n }\r\n\r\n if (errors.length > 0) {\r\n return { valid: false, errors };\r\n }\r\n\r\n return { valid: true };\r\n }\r\n\r\n /**\r\n * Validate minimum length\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output) => ValidateUtils.minLength(output.items, 1, 'items')}\r\n * </Validate>\r\n * ```\r\n */\r\n static minLength(\r\n value: any[] | string | undefined,\r\n min: number,\r\n fieldName = 'value'\r\n ): ValidationResult {\r\n const length = value?.length ?? 0;\r\n\r\n if (length < min) {\r\n return {\r\n valid: false,\r\n errors: [`${fieldName} must have at least ${min} items (got ${length})`],\r\n };\r\n }\r\n\r\n return { valid: true };\r\n }\r\n\r\n /**\r\n * Validate maximum length\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output) => ValidateUtils.maxLength(output.description, 500, 'description')}\r\n * </Validate>\r\n * ```\r\n */\r\n static maxLength(\r\n value: any[] | string | undefined,\r\n max: number,\r\n fieldName = 'value'\r\n ): ValidationResult {\r\n const length = value?.length ?? 0;\r\n\r\n if (length > max) {\r\n return {\r\n valid: false,\r\n errors: [`${fieldName} must have at most ${max} items (got ${length})`],\r\n };\r\n }\r\n\r\n return { valid: true };\r\n }\r\n\r\n /**\r\n * Validate range\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output) => ValidateUtils.inRange(output.priority, 1, 5, 'priority')}\r\n * </Validate>\r\n * ```\r\n */\r\n static inRange(\r\n value: number | undefined,\r\n min: number,\r\n max: number,\r\n fieldName = 'value'\r\n ): ValidationResult {\r\n if (value === undefined || value === null) {\r\n return {\r\n valid: false,\r\n errors: [`${fieldName} is required`],\r\n };\r\n }\r\n\r\n if (value < min || value > max) {\r\n return {\r\n valid: false,\r\n errors: [`${fieldName} must be between ${min} and ${max} (got ${value})`],\r\n };\r\n }\r\n\r\n return { valid: true };\r\n }\r\n\r\n /**\r\n * Validate enum value\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output) => ValidateUtils.inEnum(output.status, ['pending', 'done'], 'status')}\r\n * </Validate>\r\n * ```\r\n */\r\n static inEnum<T>(\r\n value: T | undefined,\r\n allowedValues: readonly T[],\r\n fieldName = 'value'\r\n ): ValidationResult {\r\n if (!allowedValues.includes(value as T)) {\r\n return {\r\n valid: false,\r\n errors: [\r\n `${fieldName} must be one of: ${allowedValues.join(', ')} (got ${value})`,\r\n ],\r\n };\r\n }\r\n\r\n return { valid: true };\r\n }\r\n\r\n /**\r\n * Validate pattern (regex)\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output) => ValidateUtils.matchesPattern(output.email, /^.+@.+\\..+$/, 'email')}\r\n * </Validate>\r\n * ```\r\n */\r\n static matchesPattern(\r\n value: string | undefined,\r\n pattern: RegExp,\r\n fieldName = 'value'\r\n ): ValidationResult {\r\n if (!value) {\r\n return {\r\n valid: false,\r\n errors: [`${fieldName} is required`],\r\n };\r\n }\r\n\r\n if (!pattern.test(value)) {\r\n return {\r\n valid: false,\r\n errors: [`${fieldName} does not match required pattern`],\r\n };\r\n }\r\n\r\n return { valid: true };\r\n }\r\n\r\n /**\r\n * Validate uniqueness in array\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output) => ValidateUtils.uniqueItems(output.ids, 'ids')}\r\n * </Validate>\r\n * ```\r\n */\r\n static uniqueItems<T>(\r\n items: T[] | undefined,\r\n fieldName = 'items'\r\n ): ValidationResult {\r\n if (!items || items.length === 0) {\r\n return { valid: true };\r\n }\r\n\r\n const unique = new Set(items);\r\n if (unique.size !== items.length) {\r\n return {\r\n valid: false,\r\n errors: [`${fieldName} contains duplicate values`],\r\n };\r\n }\r\n\r\n return { valid: true };\r\n }\r\n\r\n /**\r\n * Validate using custom function\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output) => ValidateUtils.custom(\r\n * output,\r\n * (data) => data.startDate < data.endDate,\r\n * 'End date must be after start date'\r\n * )}\r\n * </Validate>\r\n * ```\r\n */\r\n static custom<T>(\r\n value: T,\r\n predicate: (value: T) => boolean,\r\n errorMessage: string\r\n ): ValidationResult {\r\n if (!predicate(value)) {\r\n return {\r\n valid: false,\r\n errors: [errorMessage],\r\n };\r\n }\r\n\r\n return { valid: true };\r\n }\r\n\r\n /**\r\n * Combine multiple validation results\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output) => ValidateUtils.all([\r\n * ValidateUtils.requireFields(output, ['id', 'name']),\r\n * ValidateUtils.minLength(output.items, 1, 'items'),\r\n * ])}\r\n * </Validate>\r\n * ```\r\n */\r\n static all(results: ValidationResult[]): ValidationResult {\r\n const errors: string[] = [];\r\n\r\n for (const result of results) {\r\n if (!result.valid && result.errors) {\r\n errors.push(...result.errors);\r\n }\r\n }\r\n\r\n return {\r\n valid: errors.length === 0,\r\n errors: errors.length > 0 ? errors : undefined,\r\n };\r\n }\r\n\r\n /**\r\n * At least one validation must pass\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output) => ValidateUtils.any([\r\n * ValidateUtils.requireFields(output, ['email']),\r\n * ValidateUtils.requireFields(output, ['phone']),\r\n * ])}\r\n * </Validate>\r\n * ```\r\n */\r\n static any(results: ValidationResult[]): ValidationResult {\r\n const hasValid = results.some(r => r.valid);\r\n\r\n if (hasValid) {\r\n return { valid: true };\r\n }\r\n\r\n // Combine all errors\r\n const errors: string[] = [];\r\n for (const result of results) {\r\n if (result.errors) {\r\n errors.push(...result.errors);\r\n }\r\n }\r\n\r\n return {\r\n valid: false,\r\n errors: errors.length > 0 ? ['None of the validation rules passed'] : undefined,\r\n };\r\n }\r\n\r\n /**\r\n * Validate with message (doesn't fail, just adds a message)\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output) => ValidateUtils.warn(\r\n * output.items.length < 5,\r\n * 'Consider adding more items for better results'\r\n * )}\r\n * </Validate>\r\n * ```\r\n */\r\n static warn(condition: boolean, message: string): ValidationResult {\r\n if (condition) {\r\n return {\r\n valid: true,\r\n message: message,\r\n };\r\n }\r\n\r\n return { valid: true };\r\n }\r\n\r\n /**\r\n * Validate observed data constraints\r\n *\r\n * @example\r\n * ```tsx\r\n * <Validate>\r\n * {(output, observed) => ValidateUtils.requireObserved(\r\n * observed,\r\n * 'usedPlanning',\r\n * 'Agent must call planning_create tool'\r\n * )}\r\n * </Validate>\r\n * ```\r\n */\r\n static requireObserved(\r\n observed: Record<string, any> | undefined,\r\n key: string,\r\n errorMessage: string\r\n ): ValidationResult {\r\n if (!observed || !observed[key]) {\r\n return {\r\n valid: false,\r\n errors: [errorMessage],\r\n };\r\n }\r\n\r\n return { valid: true };\r\n }\r\n}\r\n\r\n/**\r\n * Common validation patterns\r\n */\r\nexport const validate = {\r\n /**\r\n * Pass all validations (useful for development)\r\n */\r\n pass: (): ValidationResult => ({ valid: true }),\r\n\r\n /**\r\n * Always fail (useful for testing)\r\n */\r\n fail: (message: string): ValidationResult => ({\r\n valid: false,\r\n errors: [message],\r\n }),\r\n\r\n /**\r\n * Validate non-empty string\r\n */\r\n nonEmptyString: (value: any, fieldName = 'value'): ValidationResult => {\r\n if (typeof value !== 'string' || value.trim() === '') {\r\n return {\r\n valid: false,\r\n errors: [`${fieldName} must be a non-empty string`],\r\n };\r\n }\r\n return { valid: true };\r\n },\r\n\r\n /**\r\n * Validate non-empty array\r\n */\r\n nonEmptyArray: (value: any, fieldName = 'value'): ValidationResult => {\r\n if (!Array.isArray(value) || value.length === 0) {\r\n return {\r\n valid: false,\r\n errors: [`${fieldName} must be a non-empty array`],\r\n };\r\n }\r\n return { valid: true };\r\n },\r\n\r\n /**\r\n * Validate positive number\r\n */\r\n positiveNumber: (value: any, fieldName = 'value'): ValidationResult => {\r\n if (typeof value !== 'number' || value <= 0) {\r\n return {\r\n valid: false,\r\n errors: [`${fieldName} must be a positive number`],\r\n };\r\n }\r\n return { valid: true };\r\n },\r\n};\r\n\r\n/**\r\n * Create schema-based validator\r\n *\r\n * @example\r\n * ```tsx\r\n * const validateOutput = createSchemaValidator(OutputSchema);\r\n *\r\n * <Validate>\r\n * {(output) => toValidationRules(validateOutput(output))}\r\n * </Validate>\r\n * ```\r\n */\r\nexport function createSchemaValidator<T extends z.ZodType>(schema: T) {\r\n return (output: any): ValidationResult => {\r\n return ValidateUtils.validateSchema(output, schema);\r\n };\r\n}\r\n\r\n/**\r\n * Create field validator\r\n *\r\n * @example\r\n * ```tsx\r\n * const validateFields = createFieldValidator({\r\n * priority: (val) => ['low', 'medium', 'high'].includes(val),\r\n * count: (val) => val > 0,\r\n * });\r\n *\r\n * <Validate>\r\n * {(output) => toValidationRules(validateFields(output))}\r\n * </Validate>\r\n * ```\r\n */\r\nexport function createFieldValidator<T extends Record<string, any>>(\r\n validators: { [K in keyof T]?: (value: T[K]) => boolean }\r\n) {\r\n return (output: T): ValidationResult => {\r\n return ValidateUtils.validateFields(output, validators);\r\n };\r\n}\r\n\r\n/**\r\n * Create composite validator\r\n *\r\n * @example\r\n * ```tsx\r\n * const validateOutput = createCompositeValidator(\r\n * (output) => ValidateUtils.requireFields(output, ['id', 'name']),\r\n * (output) => ValidateUtils.minLength(output.items, 1, 'items')\r\n * );\r\n *\r\n * <Validate>\r\n * {(output) => toValidationRules(validateOutput(output))}\r\n * </Validate>\r\n * ```\r\n */\r\nexport function createCompositeValidator<T = any>(\r\n ...validators: ValidatorFunction<T>[]\r\n) {\r\n return (output: T, observed?: Record<string, any>): ValidationResult => {\r\n const results = validators.map(v => v(output, observed));\r\n return ValidateUtils.all(results);\r\n };\r\n}\r\n\r\n/**\r\n * Wrap validator to return ValidationRules format\r\n *\r\n * @example\r\n * ```tsx\r\n * const validator = wrapValidator((output) =>\r\n * ValidateUtils.requireFields(output, ['id', 'name'])\r\n * );\r\n *\r\n * <Validate>{validator}</Validate>\r\n * ```\r\n */\r\nexport function wrapValidator<T = any>(\r\n validator: ValidatorFunction<T>\r\n): (output: T, ctx?: any, observed?: Record<string, any>) => ValidationRules {\r\n return (output: T, _ctx?: any, observed?: Record<string, any>) => {\r\n const result = validator(output, observed);\r\n return toValidationRules(result);\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Retry Utilities\r\n *\r\n * Helper functions for building Retry nodes.\r\n * Provides retry strategies, backoff algorithms, and error handling patterns.\r\n *\r\n * Design principles:\r\n * - Configurable retry strategies\r\n * - Exponential and linear backoff\r\n * - Error classification\r\n * - Resource-aware retries\r\n */\r\n\r\n/**\r\n * Backoff strategy type\r\n */\r\nexport type BackoffStrategy = 'none' | 'fixed' | 'linear' | 'exponential' | 'fibonacci';\r\n\r\n/**\r\n * Retry strategy options\r\n */\r\nexport interface RetryStrategyOptions {\r\n /** Maximum number of retry attempts */\r\n maxAttempts?: number;\r\n\r\n /** Initial delay in milliseconds */\r\n initialDelay?: number;\r\n\r\n /** Maximum delay in milliseconds */\r\n maxDelay?: number;\r\n\r\n /** Backoff multiplier for exponential/fibonacci strategies */\r\n backoffMultiplier?: number;\r\n\r\n /** Backoff strategy to use */\r\n backoffStrategy?: BackoffStrategy;\r\n\r\n /** Whether to add jitter to delays */\r\n jitter?: boolean;\r\n\r\n /** Maximum jitter percentage (0-1) */\r\n jitterFactor?: number;\r\n}\r\n\r\n/**\r\n * Retry context information\r\n */\r\nexport interface RetryContext {\r\n /** Current attempt number (1-indexed) */\r\n attempt: number;\r\n\r\n /** Total number of allowed attempts */\r\n maxAttempts: number;\r\n\r\n /** Error from previous attempt */\r\n lastError?: Error | string;\r\n\r\n /** Delay before this attempt (ms) */\r\n delay: number;\r\n}\r\n\r\n/**\r\n * Should retry function type\r\n */\r\nexport type ShouldRetryFunction = (\r\n error: Error | string,\r\n context: RetryContext\r\n) => boolean;\r\n\r\n/**\r\n * Retry Utils\r\n *\r\n * Collection of helper functions for retry strategies.\r\n */\r\nexport class RetryUtils {\r\n /**\r\n * Calculate delay for next retry attempt\r\n *\r\n * @example\r\n * ```tsx\r\n * const delay = RetryUtils.calculateDelay(2, {\r\n * backoffStrategy: 'exponential',\r\n * initialDelay: 1000,\r\n * backoffMultiplier: 2,\r\n * });\r\n * ```\r\n */\r\n static calculateDelay(\r\n attempt: number,\r\n options: RetryStrategyOptions = {}\r\n ): number {\r\n const {\r\n initialDelay = 1000,\r\n maxDelay = 60000,\r\n backoffMultiplier = 2,\r\n backoffStrategy = 'exponential',\r\n jitter = true,\r\n jitterFactor = 0.1,\r\n } = options;\r\n\r\n let delay: number;\r\n\r\n switch (backoffStrategy) {\r\n case 'none':\r\n delay = 0;\r\n break;\r\n\r\n case 'fixed':\r\n delay = initialDelay;\r\n break;\r\n\r\n case 'linear':\r\n delay = initialDelay * attempt;\r\n break;\r\n\r\n case 'exponential':\r\n delay = initialDelay * Math.pow(backoffMultiplier, attempt - 1);\r\n break;\r\n\r\n case 'fibonacci':\r\n delay = initialDelay * this.fibonacci(attempt);\r\n break;\r\n\r\n default:\r\n delay = initialDelay;\r\n }\r\n\r\n // Cap at max delay\r\n delay = Math.min(delay, maxDelay);\r\n\r\n // Add jitter if enabled\r\n if (jitter && delay > 0) {\r\n const jitterAmount = delay * jitterFactor;\r\n const randomJitter = (Math.random() * 2 - 1) * jitterAmount;\r\n delay = Math.max(0, delay + randomJitter);\r\n }\r\n\r\n return Math.round(delay);\r\n }\r\n\r\n /**\r\n * Calculate fibonacci number (for fibonacci backoff)\r\n */\r\n private static fibonacci(n: number): number {\r\n if (n <= 1) return 1;\r\n if (n === 2) return 2;\r\n\r\n let a = 1;\r\n let b = 2;\r\n for (let i = 3; i <= n; i++) {\r\n const temp = a + b;\r\n a = b;\r\n b = temp;\r\n }\r\n return b;\r\n }\r\n\r\n /**\r\n * Check if error is retryable\r\n *\r\n * @example\r\n * ```tsx\r\n * const shouldRetry = RetryUtils.isRetryableError(error, {\r\n * retryableErrors: ['TIMEOUT', 'RATE_LIMIT'],\r\n * nonRetryableErrors: ['AUTH_FAILED'],\r\n * });\r\n * ```\r\n */\r\n static isRetryableError(\r\n error: Error | string,\r\n options: {\r\n retryableErrors?: string[];\r\n nonRetryableErrors?: string[];\r\n } = {}\r\n ): boolean {\r\n const { retryableErrors = [], nonRetryableErrors = [] } = options;\r\n\r\n const errorMessage = typeof error === 'string' ? error : error.message;\r\n const errorName = typeof error === 'object' && error.name ? error.name : '';\r\n\r\n // Normalize to lowercase for case-insensitive matching\r\n const errorMessageLower = errorMessage.toLowerCase();\r\n const errorNameLower = errorName.toLowerCase();\r\n\r\n // Check non-retryable errors first\r\n for (const pattern of nonRetryableErrors) {\r\n const patternLower = pattern.toLowerCase();\r\n if (errorMessageLower.includes(patternLower) || errorNameLower.includes(patternLower)) {\r\n return false;\r\n }\r\n }\r\n\r\n // If retryable errors specified, check if error matches\r\n if (retryableErrors.length > 0) {\r\n return retryableErrors.some(\r\n pattern => {\r\n const patternLower = pattern.toLowerCase();\r\n return errorMessageLower.includes(patternLower) || errorNameLower.includes(patternLower);\r\n }\r\n );\r\n }\r\n\r\n // Default: retry unless explicitly non-retryable\r\n return true;\r\n }\r\n\r\n /**\r\n * Create retry predicate based on error type\r\n *\r\n * @example\r\n * ```tsx\r\n * const shouldRetry = RetryUtils.retryOnError([\r\n * 'timeout',\r\n * 'network error',\r\n * 'rate limit',\r\n * ]);\r\n * ```\r\n */\r\n static retryOnError(errorPatterns: string[]): ShouldRetryFunction {\r\n return (error: Error | string) => {\r\n const errorMessage = typeof error === 'string' ? error : error.message;\r\n return errorPatterns.some(pattern =>\r\n errorMessage.toLowerCase().includes(pattern.toLowerCase())\r\n );\r\n };\r\n }\r\n\r\n /**\r\n * Create retry predicate for validation errors\r\n *\r\n * @example\r\n * ```tsx\r\n * const shouldRetry = RetryUtils.retryOnValidationError();\r\n * ```\r\n */\r\n static retryOnValidationError(): ShouldRetryFunction {\r\n return (error: Error | string) => {\r\n const errorMessage = typeof error === 'string' ? error : error.message;\r\n const validationKeywords = [\r\n 'validation',\r\n 'invalid',\r\n 'missing',\r\n 'required',\r\n 'schema',\r\n ];\r\n return validationKeywords.some(keyword =>\r\n errorMessage.toLowerCase().includes(keyword)\r\n );\r\n };\r\n }\r\n\r\n /**\r\n * Never retry (for testing or specific cases)\r\n *\r\n * @example\r\n * ```tsx\r\n * const shouldRetry = RetryUtils.neverRetry();\r\n * ```\r\n */\r\n static neverRetry(): ShouldRetryFunction {\r\n return () => false;\r\n }\r\n\r\n /**\r\n * Always retry up to max attempts\r\n *\r\n * @example\r\n * ```tsx\r\n * const shouldRetry = RetryUtils.alwaysRetry();\r\n * ```\r\n */\r\n static alwaysRetry(): ShouldRetryFunction {\r\n return () => true;\r\n }\r\n\r\n /**\r\n * Retry based on attempt count\r\n *\r\n * @example\r\n * ```tsx\r\n * const shouldRetry = RetryUtils.retryUntilAttempt(3);\r\n * ```\r\n */\r\n static retryUntilAttempt(maxAttempts: number): ShouldRetryFunction {\r\n return (_error: Error | string, context: RetryContext) => {\r\n return context.attempt < maxAttempts;\r\n };\r\n }\r\n\r\n /**\r\n * Combine multiple retry predicates (AND logic)\r\n *\r\n * @example\r\n * ```tsx\r\n * const shouldRetry = RetryUtils.all([\r\n * RetryUtils.retryOnValidationError(),\r\n * RetryUtils.retryUntilAttempt(3),\r\n * ]);\r\n * ```\r\n */\r\n static all(predicates: ShouldRetryFunction[]): ShouldRetryFunction {\r\n return (error: Error | string, context: RetryContext) => {\r\n return predicates.every(predicate => predicate(error, context));\r\n };\r\n }\r\n\r\n /**\r\n * Combine multiple retry predicates (OR logic)\r\n *\r\n * @example\r\n * ```tsx\r\n * const shouldRetry = RetryUtils.any([\r\n * RetryUtils.retryOnError(['timeout']),\r\n * RetryUtils.retryOnValidationError(),\r\n * ]);\r\n * ```\r\n */\r\n static any(predicates: ShouldRetryFunction[]): ShouldRetryFunction {\r\n return (error: Error | string, context: RetryContext) => {\r\n return predicates.some(predicate => predicate(error, context));\r\n };\r\n }\r\n\r\n /**\r\n * Create retry context\r\n *\r\n * @example\r\n * ```tsx\r\n * const context = RetryUtils.createContext(2, 5, error, 2000);\r\n * ```\r\n */\r\n static createContext(\r\n attempt: number,\r\n maxAttempts: number,\r\n lastError?: Error | string,\r\n delay?: number\r\n ): RetryContext {\r\n return {\r\n attempt,\r\n maxAttempts,\r\n lastError,\r\n delay: delay ?? 0,\r\n };\r\n }\r\n\r\n /**\r\n * Format retry delay for human readability\r\n *\r\n * @example\r\n * ```tsx\r\n * const message = RetryUtils.formatDelay(5000);\r\n * // Returns: \"5.0s\"\r\n * ```\r\n */\r\n static formatDelay(delayMs: number): string {\r\n if (delayMs < 1000) {\r\n return `${delayMs}ms`;\r\n }\r\n return `${(delayMs / 1000).toFixed(1)}s`;\r\n }\r\n\r\n /**\r\n * Get retry statistics\r\n *\r\n * @example\r\n * ```tsx\r\n * const stats = RetryUtils.getStats(3, 5, {\r\n * backoffStrategy: 'exponential',\r\n * initialDelay: 1000,\r\n * });\r\n * ```\r\n */\r\n static getStats(\r\n currentAttempt: number,\r\n maxAttempts: number,\r\n options: RetryStrategyOptions = {}\r\n ): {\r\n attemptsRemaining: number;\r\n nextDelay: number;\r\n totalDelaysSoFar: number;\r\n } {\r\n const attemptsRemaining = maxAttempts - currentAttempt;\r\n const nextDelay =\r\n attemptsRemaining > 0\r\n ? this.calculateDelay(currentAttempt + 1, options)\r\n : 0;\r\n\r\n // Calculate total delays up to current attempt\r\n let totalDelaysSoFar = 0;\r\n for (let i = 1; i <= currentAttempt; i++) {\r\n totalDelaysSoFar += this.calculateDelay(i, { ...options, jitter: false });\r\n }\r\n\r\n return {\r\n attemptsRemaining,\r\n nextDelay,\r\n totalDelaysSoFar,\r\n };\r\n }\r\n}\r\n\r\n/**\r\n * Common retry strategies\r\n */\r\nexport const retry = {\r\n /**\r\n * No retry (fail immediately)\r\n */\r\n none: (): RetryStrategyOptions => ({\r\n maxAttempts: 1,\r\n backoffStrategy: 'none',\r\n initialDelay: 0,\r\n }),\r\n\r\n /**\r\n * Simple retry with fixed delay\r\n */\r\n fixed: (attempts = 3, delayMs = 1000): RetryStrategyOptions => ({\r\n maxAttempts: attempts,\r\n backoffStrategy: 'fixed',\r\n initialDelay: delayMs,\r\n }),\r\n\r\n /**\r\n * Linear backoff (delay increases linearly)\r\n */\r\n linear: (attempts = 3, initialDelayMs = 1000): RetryStrategyOptions => ({\r\n maxAttempts: attempts,\r\n backoffStrategy: 'linear',\r\n initialDelay: initialDelayMs,\r\n maxDelay: 30000,\r\n }),\r\n\r\n /**\r\n * Exponential backoff (common for API retries)\r\n */\r\n exponential: (\r\n attempts = 5,\r\n initialDelayMs = 1000,\r\n maxDelayMs = 60000\r\n ): RetryStrategyOptions => ({\r\n maxAttempts: attempts,\r\n backoffStrategy: 'exponential',\r\n initialDelay: initialDelayMs,\r\n maxDelay: maxDelayMs,\r\n backoffMultiplier: 2,\r\n jitter: true,\r\n }),\r\n\r\n /**\r\n * Fibonacci backoff (gentler than exponential)\r\n */\r\n fibonacci: (\r\n attempts = 5,\r\n initialDelayMs = 1000,\r\n maxDelayMs = 60000\r\n ): RetryStrategyOptions => ({\r\n maxAttempts: attempts,\r\n backoffStrategy: 'fibonacci',\r\n initialDelay: initialDelayMs,\r\n maxDelay: maxDelayMs,\r\n jitter: true,\r\n }),\r\n\r\n /**\r\n * Aggressive retry (many attempts, short delays)\r\n */\r\n aggressive: (): RetryStrategyOptions => ({\r\n maxAttempts: 10,\r\n backoffStrategy: 'linear',\r\n initialDelay: 500,\r\n maxDelay: 5000,\r\n }),\r\n\r\n /**\r\n * Conservative retry (few attempts, long delays)\r\n */\r\n conservative: (): RetryStrategyOptions => ({\r\n maxAttempts: 3,\r\n backoffStrategy: 'exponential',\r\n initialDelay: 2000,\r\n maxDelay: 30000,\r\n }),\r\n};\r\n\r\n/**\r\n * Create custom retry strategy\r\n *\r\n * @example\r\n * ```tsx\r\n * const strategy = createRetryStrategy({\r\n * maxAttempts: 5,\r\n * backoffStrategy: 'exponential',\r\n * initialDelay: 1000,\r\n * shouldRetry: RetryUtils.retryOnValidationError(),\r\n * });\r\n * ```\r\n */\r\nexport function createRetryStrategy(\r\n options: RetryStrategyOptions & {\r\n shouldRetry?: ShouldRetryFunction;\r\n }\r\n): {\r\n options: RetryStrategyOptions;\r\n shouldRetry?: ShouldRetryFunction;\r\n} {\r\n const { shouldRetry, ...strategyOptions } = options;\r\n return {\r\n options: strategyOptions,\r\n shouldRetry,\r\n };\r\n}\r\n\r\n/**\r\n * Simulate retry delays for testing\r\n *\r\n * @example\r\n * ```tsx\r\n * const delays = simulateRetries(5, retry.exponential());\r\n * // Returns array of delays for each retry\r\n * ```\r\n */\r\nexport function simulateRetries(\r\n attempts: number,\r\n options: RetryStrategyOptions\r\n): number[] {\r\n const delays: number[] = [];\r\n for (let i = 1; i <= attempts; i++) {\r\n delays.push(RetryUtils.calculateDelay(i, { ...options, jitter: false }));\r\n }\r\n return delays;\r\n}\r\n","/**\r\n * JSX Type Helpers\r\n *\r\n * Helper functions to convert JSX elements to their specific AST node types.\r\n * This avoids the need for manual type assertions in user code.\r\n */\r\n\r\nimport type { ASTNode, WorkflowNode, AgentNode } from '../ast/types.js';\r\n\r\n/**\r\n * Convert a JSX Workflow element to WorkflowNode type\r\n *\r\n * This is a type-safe helper that avoids manual type assertions.\r\n *\r\n * @example\r\n * ```tsx\r\n * const workflow = toWorkflow(\r\n * <Workflow name=\"my-workflow\">\r\n * <Sequence>\r\n * <Agent1 />\r\n * <Agent2 />\r\n * </Sequence>\r\n * </Workflow>\r\n * );\r\n *\r\n * // No need for: as unknown as WorkflowNode\r\n * await runTSXWorkflow(workflow, inputs);\r\n * ```\r\n */\r\nexport function toWorkflow(element: ASTNode): WorkflowNode {\r\n if (element.type !== 'Workflow') {\r\n throw new Error(`Expected Workflow element, got ${element.type}`);\r\n }\r\n return element as unknown as WorkflowNode;\r\n}\r\n\r\n/**\r\n * Convert a JSX Agent element to AgentNode type\r\n *\r\n * @example\r\n * ```tsx\r\n * const agent = toAgent(\r\n * <Agent id=\"test\" input={schema} output={schema}>\r\n * <Prompt>...</Prompt>\r\n * </Agent>\r\n * );\r\n * ```\r\n */\r\nexport function toAgent<I = unknown, O = unknown>(element: ASTNode): AgentNode<I, O> {\r\n if (element.type !== 'Agent') {\r\n throw new Error(`Expected Agent element, got ${element.type}`);\r\n }\r\n return element as unknown as AgentNode<I, O>;\r\n}\r\n","/**\r\n * Deity TSX - Preflight Checker\r\n *\r\n * Validates agent configuration before execution.\r\n * Performs checks at startup/compilation time to fail fast.\r\n *\r\n * Features:\r\n * - Resource existence validation\r\n * - Schema validation\r\n * - Agent structure validation\r\n * - Detailed error reporting\r\n */\r\n\r\nimport type { AgentNode } from '../ast/types.js';\r\nimport { getResourceLoader } from './resource-loader.js';\r\n\r\n/**\r\n * Preflight Check Result\r\n */\r\nexport interface PreflightResult {\r\n /** Whether preflight passed */\r\n passed: boolean;\r\n\r\n /** List of errors found */\r\n errors: PreflightError[];\r\n\r\n /** List of warnings */\r\n warnings: PreflightWarning[];\r\n}\r\n\r\n/**\r\n * Preflight Error\r\n */\r\nexport interface PreflightError {\r\n /** Error type */\r\n type: 'missing_resource' | 'invalid_structure' | 'schema_error' | 'other';\r\n\r\n /** Error message */\r\n message: string;\r\n\r\n /** Resource path (for missing_resource errors) */\r\n resource?: string;\r\n\r\n /** Node type (for structure errors) */\r\n nodeType?: string;\r\n}\r\n\r\n/**\r\n * Preflight Warning\r\n */\r\nexport interface PreflightWarning {\r\n /** Warning type */\r\n type: 'optional_resource' | 'performance' | 'best_practice';\r\n\r\n /** Warning message */\r\n message: string;\r\n\r\n /** Additional context */\r\n context?: string;\r\n}\r\n\r\n/**\r\n * Preflight Checker Options\r\n */\r\nexport interface PreflightOptions {\r\n /** Check resource existence (default: true) */\r\n checkResources?: boolean;\r\n\r\n /** Check agent structure (default: true) */\r\n checkStructure?: boolean;\r\n\r\n /** Check schemas (default: true) */\r\n checkSchemas?: boolean;\r\n\r\n /** Base path for resource resolution */\r\n basePath?: string;\r\n}\r\n\r\n/**\r\n * Preflight Checker\r\n *\r\n * Validates agent configuration before execution.\r\n *\r\n * @example\r\n * ```typescript\r\n * const checker = new PreflightChecker();\r\n * const result = await checker.check(MyAgent);\r\n *\r\n * if (!result.passed) {\r\n * console.error('Preflight failed:', result.errors);\r\n * }\r\n * ```\r\n */\r\nexport class PreflightChecker {\r\n private options: Required<PreflightOptions>;\r\n\r\n constructor(options: PreflightOptions = {}) {\r\n this.options = {\r\n checkResources: options.checkResources ?? true,\r\n checkStructure: options.checkStructure ?? true,\r\n checkSchemas: options.checkSchemas ?? true,\r\n basePath: options.basePath || process.cwd(),\r\n };\r\n }\r\n\r\n /**\r\n * Run preflight checks on an agent\r\n *\r\n * @param agent - Agent AST node\r\n * @returns Preflight result\r\n */\r\n async check(agent: AgentNode): Promise<PreflightResult> {\r\n const errors: PreflightError[] = [];\r\n const warnings: PreflightWarning[] = [];\r\n\r\n // Check agent structure\r\n if (this.options.checkStructure) {\r\n this.checkAgentStructure(agent, errors);\r\n }\r\n\r\n // Check schemas\r\n if (this.options.checkSchemas) {\r\n this.checkSchemas(agent, errors, warnings);\r\n }\r\n\r\n // Check resources\r\n if (this.options.checkResources) {\r\n await this.checkResources(agent, errors, warnings);\r\n }\r\n\r\n return {\r\n passed: errors.length === 0,\r\n errors,\r\n warnings,\r\n };\r\n }\r\n\r\n /**\r\n * Check agent structure\r\n */\r\n private checkAgentStructure(agent: AgentNode, errors: PreflightError[]): void {\r\n // Verify agent has required children\r\n const [promptNode, ...rest] = agent.children;\r\n\r\n if (!promptNode || promptNode.type !== 'Prompt') {\r\n errors.push({\r\n type: 'invalid_structure',\r\n message: 'Agent must have a Prompt node as first child',\r\n nodeType: 'Agent',\r\n });\r\n }\r\n\r\n // Verify Result node exists\r\n const resultNode = rest.find(n => n?.type === 'Result');\r\n if (!resultNode) {\r\n errors.push({\r\n type: 'invalid_structure',\r\n message: 'Agent must have a Result node',\r\n nodeType: 'Agent',\r\n });\r\n }\r\n\r\n // Check Prompt children\r\n if (promptNode && promptNode.children) {\r\n const hasSystemOrUser = promptNode.children.some(\r\n child => child.type === 'System' || child.type === 'User'\r\n );\r\n\r\n if (!hasSystemOrUser) {\r\n errors.push({\r\n type: 'invalid_structure',\r\n message: 'Prompt must have at least one System or User node',\r\n nodeType: 'Prompt',\r\n });\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Check schemas\r\n */\r\n private checkSchemas(\r\n agent: AgentNode,\r\n errors: PreflightError[],\r\n warnings: PreflightWarning[]\r\n ): void {\r\n // Verify input schema exists\r\n if (!agent.props.input) {\r\n errors.push({\r\n type: 'schema_error',\r\n message: 'Agent must have an input schema',\r\n nodeType: 'Agent',\r\n });\r\n }\r\n\r\n // Verify output schema exists\r\n if (!agent.props.output) {\r\n errors.push({\r\n type: 'schema_error',\r\n message: 'Agent must have an output schema',\r\n nodeType: 'Agent',\r\n });\r\n }\r\n\r\n // Warn if no description\r\n if (!agent.props.description) {\r\n warnings.push({\r\n type: 'best_practice',\r\n message: 'Agent should have a description',\r\n context: `Agent \"${agent.props.id}\" has no description`,\r\n });\r\n }\r\n }\r\n\r\n /**\r\n * Check resources (file existence)\r\n */\r\n private async checkResources(\r\n agent: AgentNode,\r\n errors: PreflightError[],\r\n warnings: PreflightWarning[]\r\n ): Promise<void> {\r\n const [promptNode] = agent.children;\r\n\r\n if (!promptNode || promptNode.type !== 'Prompt') {\r\n return;\r\n }\r\n\r\n // Collect file sources\r\n const sources: Array<{ source: string; required: boolean }> = [];\r\n\r\n for (const child of promptNode.children || []) {\r\n if (child.type === 'System' && child.props.source) {\r\n sources.push({\r\n source: child.props.source,\r\n required: child.props.required ?? false,\r\n });\r\n }\r\n }\r\n\r\n if (sources.length === 0) {\r\n return; // No file resources to check\r\n }\r\n\r\n // Check resources\r\n const loader = getResourceLoader({ basePath: this.options.basePath });\r\n const missing = await loader.preflight(sources);\r\n\r\n // Add errors for missing required files\r\n for (const missingPath of missing) {\r\n errors.push({\r\n type: 'missing_resource',\r\n message: `Required resource not found: ${missingPath}`,\r\n resource: missingPath,\r\n });\r\n }\r\n\r\n // Warn about caching\r\n if (sources.length > 3) {\r\n warnings.push({\r\n type: 'performance',\r\n message: `Agent has ${sources.length} file resources`,\r\n context: 'Consider enabling caching for better performance',\r\n });\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Run preflight check on an agent\r\n *\r\n * Convenience function for quick preflight checks.\r\n *\r\n * @param agent - Agent AST node\r\n * @param options - Preflight options\r\n * @returns Preflight result\r\n */\r\nexport async function preflight(\r\n agent: AgentNode,\r\n options?: PreflightOptions\r\n): Promise<PreflightResult> {\r\n const checker = new PreflightChecker(options);\r\n return await checker.check(agent);\r\n}\r\n\r\n/**\r\n * Assert preflight passed\r\n *\r\n * Throws error if preflight failed.\r\n *\r\n * @param agent - Agent AST node\r\n * @param options - Preflight options\r\n */\r\nexport async function assertPreflight(\r\n agent: AgentNode,\r\n options?: PreflightOptions\r\n): Promise<void> {\r\n const result = await preflight(agent, options);\r\n\r\n if (!result.passed) {\r\n const errorMessages = result.errors.map(e => ` - ${e.message}`).join('\\n');\r\n throw new Error(`Preflight check failed:\\n${errorMessages}`);\r\n }\r\n}\r\n","/**\r\n * Deity TSX - Test Utils\r\n *\r\n * Testing utilities for TSX agents:\r\n * - Prompt Preview: Preview prompts without executing LLM\r\n * - Validate Dry-run: Test validation rules without LLM execution\r\n * - Observe Testing: Test observation logic with mock data\r\n */\r\n\r\nimport type { AgentNode } from '../ast/types.js';\r\nimport type { ExecutionContext, Message, LLMLoopResult, ValidationResult } from '../engine/types.js';\r\nimport { compileAgent } from '../compiler/index.js';\r\n\r\n/**\r\n * Prompt Preview Options\r\n */\r\nexport interface PromptPreviewOptions<I = unknown> {\r\n /** Mock inputs for the agent */\r\n inputs: I;\r\n\r\n /** Optional execution context overrides */\r\n ctx?: Partial<ExecutionContext<I>>;\r\n}\r\n\r\n/**\r\n * Prompt Preview Result\r\n */\r\nexport interface PromptPreviewResult {\r\n /** Generated messages */\r\n messages: Message[];\r\n\r\n /** Serialized messages for snapshot testing */\r\n snapshot: string;\r\n}\r\n\r\n/**\r\n * Render Prompt Preview\r\n *\r\n * Generate prompts without executing LLM.\r\n * Useful for:\r\n * - Snapshot testing prompts\r\n * - Debugging prompt templates\r\n * - Validating prompt structure\r\n *\r\n * @example\r\n * ```typescript\r\n * const preview = await renderPromptPreview(MyAgent, {\r\n * inputs: { task: 'test' },\r\n * });\r\n *\r\n * expect(preview.messages).toHaveLength(2);\r\n * expect(preview.snapshot).toMatchSnapshot();\r\n * ```\r\n */\r\nexport async function renderPromptPreview<I = unknown, O = unknown>(\r\n agent: AgentNode<I, O>,\r\n options: PromptPreviewOptions<I>\r\n): Promise<PromptPreviewResult> {\r\n // Compile agent\r\n const component = compileAgent(agent);\r\n\r\n // Build execution context\r\n const ctx: ExecutionContext<I> = {\r\n inputs: options.inputs,\r\n ...options.ctx,\r\n } as ExecutionContext<I>;\r\n\r\n // Generate messages\r\n const messages = await component.buildPrompt(ctx);\r\n\r\n // Create snapshot\r\n const snapshot = messages\r\n .map((msg, i) => {\r\n return `[${i}] ${msg.role}:\\n${msg.content}\\n`;\r\n })\r\n .join('\\n---\\n\\n');\r\n\r\n return {\r\n messages,\r\n snapshot,\r\n };\r\n}\r\n\r\n/**\r\n * Validate Dry-run Options\r\n */\r\nexport interface ValidateDryRunOptions<I = unknown> {\r\n /** Mock output to validate */\r\n output: unknown;\r\n\r\n /** Mock inputs (optional) */\r\n inputs?: I;\r\n\r\n /** Mock observed data (optional) */\r\n observed?: Record<string, unknown>;\r\n}\r\n\r\n/**\r\n * Dry-run Validate\r\n *\r\n * Test validation rules without LLM execution.\r\n * Useful for:\r\n * - Testing validation logic\r\n * - Debugging validation rules\r\n * - Ensuring rules are correct\r\n *\r\n * @example\r\n * ```typescript\r\n * const result = await dryRunValidate(MyAgent, {\r\n * output: { count: 3 },\r\n * inputs: { test: 'test' },\r\n * });\r\n *\r\n * expect(result.valid).toBe(false);\r\n * expect(result.errors).toContain('Count must be >= 5');\r\n * ```\r\n */\r\nexport async function dryRunValidate<I = unknown, O = unknown>(\r\n agent: AgentNode<I, O>,\r\n options: ValidateDryRunOptions<I>\r\n): Promise<ValidationResult> {\r\n // Compile agent\r\n const component = compileAgent(agent);\r\n\r\n // Check if agent has validation\r\n if (!component.validateOutput) {\r\n return { valid: true };\r\n }\r\n\r\n // Build execution context\r\n const ctx: ExecutionContext<I> = {\r\n inputs: options.inputs ?? {} as I,\r\n } as ExecutionContext<I>;\r\n\r\n // Note: The compiled validateOutput doesn't have access to observed data\r\n // This is a limitation of the current implementation\r\n // For now, validation will work but won't have access to observed metrics\r\n // TODO: Refactor validateOutput to accept observed parameter\r\n\r\n // Run validation\r\n const result = await component.validateOutput(options.output as O, ctx);\r\n\r\n return result;\r\n}\r\n\r\n/**\r\n * Observe Testing Options\r\n */\r\nexport interface ObserveTestOptions {\r\n /** Mock LLM loop result */\r\n llmResult: Partial<LLMLoopResult>;\r\n}\r\n\r\n/**\r\n * Run Observe\r\n *\r\n * Test observation logic with mock LLM result.\r\n * Useful for:\r\n * - Testing observation extractors\r\n * - Debugging observation logic\r\n * - Ensuring correct metrics\r\n *\r\n * @example\r\n * ```typescript\r\n * const observed = await runObserve(MyAgent, {\r\n * llmResult: {\r\n * toolCalls: [\r\n * { name: 'tool1', arguments: '{}' },\r\n * { name: 'tool2', arguments: '{}' },\r\n * ],\r\n * },\r\n * });\r\n *\r\n * expect(observed.toolCount).toBe(2);\r\n * ```\r\n */\r\nexport async function runObserve<I = unknown, O = unknown>(\r\n agent: AgentNode<I, O>,\r\n options: ObserveTestOptions\r\n): Promise<Record<string, unknown>> {\r\n // Compile agent (skipped for testing, we use the node directly)\r\n // const _component = compileAgent(agent);\r\n\r\n // Find Observe node\r\n const observeNode = agent.children.find(n => n?.type === 'Observe');\r\n\r\n if (!observeNode) {\r\n return {};\r\n }\r\n\r\n // Compile observe function\r\n const { compileObserve } = await import('../compiler/compile-observe.js');\r\n const observeFunction = compileObserve(observeNode as any);\r\n\r\n // Mock LLM result - handle both old-style and new-style input\r\n const mockInput = options.llmResult as any;\r\n\r\n // Handle tool calls - convert 'result' to 'arguments' for backwards compatibility\r\n let toolCalls = mockInput.toolCalls || mockInput.response?.toolCalls || [];\r\n if (toolCalls.length > 0) {\r\n toolCalls = toolCalls.map((tc: any) => {\r\n // If test provides 'result', convert it to 'arguments'\r\n if (tc.result && !tc.arguments) {\r\n return {\r\n ...tc,\r\n arguments: typeof tc.result === 'string' ? tc.result : JSON.stringify(tc.result),\r\n };\r\n }\r\n return tc;\r\n });\r\n }\r\n\r\n const llmResult: LLMLoopResult = {\r\n response: {\r\n content: mockInput.content || mockInput.response?.content || '',\r\n toolCalls,\r\n },\r\n messages: mockInput.messages || [],\r\n rounds: mockInput.rounds || 1,\r\n toolCallsExecuted: mockInput.toolCallsExecuted || 0,\r\n errors: mockInput.errors || [],\r\n } as LLMLoopResult;\r\n\r\n // Run observation\r\n const observed = await observeFunction(llmResult);\r\n\r\n return observed;\r\n}\r\n\r\n/**\r\n * Extract Output Testing Options\r\n */\r\nexport interface ExtractOutputTestOptions<I = unknown> {\r\n /** Mock inputs */\r\n inputs: I;\r\n\r\n /** Mock LLM loop result */\r\n llmResult: Partial<LLMLoopResult>;\r\n}\r\n\r\n/**\r\n * Test Extract Output\r\n *\r\n * Test output extraction with mock data.\r\n * Useful for:\r\n * - Testing extraction logic\r\n * - Debugging output transformation\r\n * - Ensuring correct output structure\r\n *\r\n * @example\r\n * ```typescript\r\n * const output = await testExtractOutput(MyAgent, {\r\n * inputs: { test: 'test' },\r\n * llmResult: {\r\n * content: 'Hello',\r\n * toolCalls: [{ name: 'planning_create', arguments: '{\"tasks\":[]}' }],\r\n * },\r\n * });\r\n *\r\n * expect(output).toHaveProperty('tasks');\r\n * ```\r\n */\r\nexport async function testExtractOutput<I = unknown, O = unknown>(\r\n agent: AgentNode<I, O>,\r\n options: ExtractOutputTestOptions<I>\r\n): Promise<O | undefined> {\r\n // Compile agent\r\n const component = compileAgent(agent);\r\n\r\n // Build execution context\r\n const ctx: ExecutionContext<I> = {\r\n inputs: options.inputs,\r\n } as ExecutionContext<I>;\r\n\r\n // Mock LLM result - handle both old-style and new-style input\r\n const mockInput = options.llmResult as any;\r\n\r\n // Handle tool calls - convert 'result' to 'arguments' for backwards compatibility\r\n let toolCalls = mockInput.toolCalls || mockInput.response?.toolCalls || [];\r\n if (toolCalls.length > 0) {\r\n toolCalls = toolCalls.map((tc: any) => {\r\n // If test provides 'result', convert it to 'arguments'\r\n if (tc.result && !tc.arguments) {\r\n return {\r\n ...tc,\r\n arguments: typeof tc.result === 'string' ? tc.result : JSON.stringify(tc.result),\r\n };\r\n }\r\n return tc;\r\n });\r\n }\r\n\r\n const llmResult: LLMLoopResult = {\r\n response: {\r\n content: mockInput.content || mockInput.response?.content || '',\r\n toolCalls,\r\n },\r\n messages: mockInput.messages || [],\r\n rounds: mockInput.rounds || 1,\r\n toolCallsExecuted: mockInput.toolCallsExecuted || 0,\r\n errors: mockInput.errors || [],\r\n } as LLMLoopResult;\r\n\r\n // Extract output\r\n const output = await component.extractOutput?.(ctx, llmResult);\r\n\r\n return output;\r\n}\r\n\r\n/**\r\n * Full Agent Test Options\r\n */\r\nexport interface FullAgentTestOptions<I = unknown> {\r\n /** Inputs for the agent */\r\n inputs: I;\r\n\r\n /** Mock LLM loop result */\r\n llmResult: Partial<LLMLoopResult>;\r\n}\r\n\r\n/**\r\n * Full Agent Test Result\r\n */\r\nexport interface FullAgentTestResult<O = unknown> {\r\n /** Generated prompts */\r\n prompts: Message[];\r\n\r\n /** Observed data */\r\n observed: Record<string, unknown>;\r\n\r\n /** Extracted output */\r\n output: O | undefined;\r\n\r\n /** Validation result */\r\n validation: ValidationResult;\r\n}\r\n\r\n/**\r\n * Test Full Agent Pipeline\r\n *\r\n * Test the complete agent pipeline without LLM execution:\r\n * 1. Build prompts\r\n * 2. Run observation\r\n * 3. Extract output\r\n * 4. Validate output\r\n *\r\n * Useful for:\r\n * - Integration testing\r\n * - End-to-end agent testing\r\n * - Ensuring all parts work together\r\n *\r\n * @example\r\n * ```typescript\r\n * const result = await testFullAgent(MyAgent, {\r\n * inputs: { task: 'test' },\r\n * llmResult: {\r\n * content: 'Done',\r\n * toolCalls: [{ name: 'planning_create', arguments: '{\"tasks\":[]}' }],\r\n * },\r\n * });\r\n *\r\n * expect(result.output).toBeDefined();\r\n * expect(result.validation.valid).toBe(true);\r\n * ```\r\n */\r\nexport async function testFullAgent<I = unknown, O = unknown>(\r\n agent: AgentNode<I, O>,\r\n options: FullAgentTestOptions<I>\r\n): Promise<FullAgentTestResult<O>> {\r\n // Compile agent\r\n const component = compileAgent(agent);\r\n\r\n // Build execution context\r\n const ctx: ExecutionContext<I> = {\r\n inputs: options.inputs,\r\n } as ExecutionContext<I>;\r\n\r\n // Mock LLM result - handle both old-style and new-style input\r\n const mockInput = options.llmResult as any;\r\n\r\n // Handle tool calls - convert 'result' to 'arguments' for backwards compatibility\r\n let toolCalls = mockInput.toolCalls || mockInput.response?.toolCalls || [];\r\n if (toolCalls.length > 0) {\r\n toolCalls = toolCalls.map((tc: any) => {\r\n // If test provides 'result', convert it to 'arguments'\r\n if (tc.result && !tc.arguments) {\r\n return {\r\n ...tc,\r\n arguments: typeof tc.result === 'string' ? tc.result : JSON.stringify(tc.result),\r\n };\r\n }\r\n return tc;\r\n });\r\n }\r\n\r\n const llmResult: LLMLoopResult = {\r\n response: {\r\n content: mockInput.content || mockInput.response?.content || '',\r\n toolCalls,\r\n },\r\n messages: mockInput.messages || [],\r\n rounds: mockInput.rounds || 1,\r\n toolCallsExecuted: mockInput.toolCallsExecuted || 0,\r\n errors: mockInput.errors || [],\r\n } as LLMLoopResult;\r\n\r\n // 1. Build prompts\r\n const prompts = await component.buildPrompt(ctx);\r\n\r\n // 2. Run observation (if present)\r\n const observed = await runObserve(agent, { llmResult });\r\n\r\n // 3. Extract output\r\n const output = await component.extractOutput?.(ctx, llmResult);\r\n\r\n // 4. Validate output (if present)\r\n let validation: ValidationResult = { valid: true };\r\n if (component.validateOutput && output !== undefined) {\r\n validation = await component.validateOutput(output as O, ctx);\r\n }\r\n\r\n return {\r\n prompts,\r\n observed,\r\n output,\r\n validation,\r\n };\r\n}\r\n","/**\r\n * Deity TSX - Debug Utilities\r\n *\r\n * Development utilities for debugging TSX agents.\r\n * Provides logging, inspection, and debugging helpers.\r\n */\r\n\r\nimport type { ASTNode } from '../ast/types.js';\r\nimport type { Message } from '../engine/types.js';\r\nimport type { ValidationResult } from '../utilities/validate-utils.js';\r\nimport type { RetryContext } from '../utilities/retry-utils.js';\r\n\r\n/**\r\n * Debug mode flag (set via environment variable)\r\n */\r\nexport const DEBUG_ENABLED = process.env.DEITY_DEBUG === 'true';\r\n\r\n/**\r\n * Debug log levels\r\n */\r\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\r\n\r\n/**\r\n * Debug logger configuration\r\n */\r\nexport interface DebugLoggerConfig {\r\n /** Enable/disable logging */\r\n enabled?: boolean;\r\n /** Minimum log level to display */\r\n level?: LogLevel;\r\n /** Custom log prefix */\r\n prefix?: string;\r\n /** Enable timestamps */\r\n timestamps?: boolean;\r\n /** Enable colors in output */\r\n colors?: boolean;\r\n}\r\n\r\n/**\r\n * Log levels in order of severity\r\n */\r\nconst LOG_LEVELS: Record<LogLevel, number> = {\r\n debug: 0,\r\n info: 1,\r\n warn: 2,\r\n error: 3,\r\n};\r\n\r\n/**\r\n * ANSI color codes\r\n */\r\nconst COLORS = {\r\n reset: '\\x1b[0m',\r\n bright: '\\x1b[1m',\r\n dim: '\\x1b[2m',\r\n red: '\\x1b[31m',\r\n green: '\\x1b[32m',\r\n yellow: '\\x1b[33m',\r\n blue: '\\x1b[34m',\r\n magenta: '\\x1b[35m',\r\n cyan: '\\x1b[36m',\r\n white: '\\x1b[37m',\r\n};\r\n\r\n/**\r\n * Debug Logger\r\n *\r\n * Provides structured logging for development and debugging.\r\n *\r\n * @example\r\n * ```tsx\r\n * const logger = new DebugLogger({ level: 'debug' });\r\n * logger.debug('Processing agent', { nodeType: 'Agent' });\r\n * logger.warn('Validation failed', { errors: ['missing field'] });\r\n * ```\r\n */\r\nexport class DebugLogger {\r\n private config: Required<DebugLoggerConfig>;\r\n\r\n constructor(config: DebugLoggerConfig = {}) {\r\n this.config = {\r\n enabled: config.enabled ?? DEBUG_ENABLED,\r\n level: config.level ?? 'info',\r\n prefix: config.prefix ?? '[Deity]',\r\n timestamps: config.timestamps ?? true,\r\n colors: config.colors ?? true,\r\n };\r\n }\r\n\r\n /**\r\n * Log debug message\r\n */\r\n debug(message: string, data?: unknown): void {\r\n this.log('debug', message, data);\r\n }\r\n\r\n /**\r\n * Log info message\r\n */\r\n info(message: string, data?: unknown): void {\r\n this.log('info', message, data);\r\n }\r\n\r\n /**\r\n * Log warning message\r\n */\r\n warn(message: string, data?: unknown): void {\r\n this.log('warn', message, data);\r\n }\r\n\r\n /**\r\n * Log error message\r\n */\r\n error(message: string, data?: unknown): void {\r\n this.log('error', message, data);\r\n }\r\n\r\n /**\r\n * Internal log method\r\n */\r\n private log(level: LogLevel, message: string, data?: unknown): void {\r\n if (!this.config.enabled) return;\r\n if (LOG_LEVELS[level] < LOG_LEVELS[this.config.level]) return;\r\n\r\n const timestamp = this.config.timestamps ? `[${new Date().toISOString()}]` : '';\r\n const levelStr = level.toUpperCase().padEnd(5);\r\n const prefix = this.config.prefix;\r\n\r\n let output = `${timestamp} ${prefix} ${levelStr} ${message}`;\r\n\r\n if (this.config.colors) {\r\n const color = this.getLevelColor(level);\r\n output = `${COLORS.dim}${timestamp}${COLORS.reset} ${color}${prefix} ${levelStr}${COLORS.reset} ${message}`;\r\n }\r\n\r\n console.log(output);\r\n\r\n if (data !== undefined) {\r\n console.log(this.formatData(data));\r\n }\r\n }\r\n\r\n /**\r\n * Get color for log level\r\n */\r\n private getLevelColor(level: LogLevel): string {\r\n switch (level) {\r\n case 'debug':\r\n return COLORS.cyan;\r\n case 'info':\r\n return COLORS.blue;\r\n case 'warn':\r\n return COLORS.yellow;\r\n case 'error':\r\n return COLORS.red;\r\n default:\r\n return COLORS.white;\r\n }\r\n }\r\n\r\n /**\r\n * Format data for output\r\n */\r\n private formatData(data: unknown): string {\r\n if (typeof data === 'string') return data;\r\n return JSON.stringify(data, null, 2);\r\n }\r\n}\r\n\r\n/**\r\n * Global debug logger instance\r\n */\r\nexport const logger = new DebugLogger();\r\n\r\n/**\r\n * AST Inspector\r\n *\r\n * Utilities for inspecting and debugging AST nodes.\r\n */\r\nexport class ASTInspector {\r\n /**\r\n * Print AST tree structure\r\n *\r\n * @example\r\n * ```tsx\r\n * const ast = <Agent>...</Agent>;\r\n * ASTInspector.printTree(ast);\r\n * ```\r\n */\r\n static printTree(node: ASTNode, indent = 0): void {\r\n const spaces = ' '.repeat(indent);\r\n const nodeType = node.type;\r\n\r\n console.log(`${spaces}${nodeType}`);\r\n\r\n if ('children' in node && node.children) {\r\n for (const child of node.children) {\r\n if (typeof child === 'object' && child !== null && 'type' in child) {\r\n this.printTree(child as ASTNode, indent + 1);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Get node count by type\r\n */\r\n static getNodeCounts(node: ASTNode): Record<string, number> {\r\n const counts: Record<string, number> = {};\r\n\r\n const traverse = (n: ASTNode): void => {\r\n counts[n.type] = (counts[n.type] || 0) + 1;\r\n\r\n if ('children' in n && n.children) {\r\n for (const child of n.children) {\r\n if (typeof child === 'object' && child !== null && 'type' in child) {\r\n traverse(child as ASTNode);\r\n }\r\n }\r\n }\r\n };\r\n\r\n traverse(node);\r\n return counts;\r\n }\r\n\r\n /**\r\n * Find nodes by type\r\n */\r\n static findNodesByType<T extends ASTNode>(\r\n node: ASTNode,\r\n type: string\r\n ): T[] {\r\n const results: T[] = [];\r\n\r\n const traverse = (n: ASTNode): void => {\r\n if (n.type === type) {\r\n results.push(n as T);\r\n }\r\n\r\n if ('children' in n && n.children) {\r\n for (const child of n.children) {\r\n if (typeof child === 'object' && child !== null && 'type' in child) {\r\n traverse(child as ASTNode);\r\n }\r\n }\r\n }\r\n };\r\n\r\n traverse(node);\r\n return results;\r\n }\r\n\r\n /**\r\n * Validate AST structure\r\n */\r\n static validateStructure(node: ASTNode): ValidationResult {\r\n const errors: string[] = [];\r\n\r\n const traverse = (n: ASTNode, path: string): void => {\r\n // Check required fields\r\n if (!n.type) {\r\n errors.push(`${path}: Missing 'type' field`);\r\n }\r\n\r\n // Type-specific validation\r\n if (n.type === 'Agent') {\r\n if (!('children' in n) || !n.children) {\r\n errors.push(`${path}: Agent node must have children`);\r\n }\r\n }\r\n\r\n // Recurse\r\n if ('children' in n && n.children) {\r\n for (let i = 0; i < n.children.length; i++) {\r\n const child = n.children[i];\r\n if (typeof child === 'object' && child !== null && 'type' in child) {\r\n traverse(child as ASTNode, `${path}.children[${i}]`);\r\n }\r\n }\r\n }\r\n };\r\n\r\n traverse(node, 'root');\r\n\r\n return {\r\n valid: errors.length === 0,\r\n errors: errors.length > 0 ? errors : undefined,\r\n };\r\n }\r\n}\r\n\r\n/**\r\n * Execution Tracer\r\n *\r\n * Traces agent execution for debugging.\r\n */\r\nexport class ExecutionTracer {\r\n private events: ExecutionEvent[] = [];\r\n private enabled: boolean;\r\n\r\n constructor(enabled = DEBUG_ENABLED) {\r\n this.enabled = enabled;\r\n }\r\n\r\n /**\r\n * Record LLM call\r\n */\r\n recordLLMCall(messages: Message[], responseContent: string): void {\r\n if (!this.enabled) return;\r\n\r\n this.events.push({\r\n type: 'llm_call',\r\n timestamp: Date.now(),\r\n data: {\r\n messageCount: messages.length,\r\n responseLength: responseContent.length,\r\n lastMessage: messages[messages.length - 1],\r\n },\r\n });\r\n }\r\n\r\n /**\r\n * Record validation\r\n */\r\n recordValidation(result: ValidationResult): void {\r\n if (!this.enabled) return;\r\n\r\n this.events.push({\r\n type: 'validation',\r\n timestamp: Date.now(),\r\n data: result,\r\n });\r\n }\r\n\r\n /**\r\n * Record retry attempt\r\n */\r\n recordRetry(context: RetryContext): void {\r\n if (!this.enabled) return;\r\n\r\n this.events.push({\r\n type: 'retry',\r\n timestamp: Date.now(),\r\n data: context,\r\n });\r\n }\r\n\r\n /**\r\n * Record tool call\r\n */\r\n recordToolCall(toolName: string, args: unknown): void {\r\n if (!this.enabled) return;\r\n\r\n this.events.push({\r\n type: 'tool_call',\r\n timestamp: Date.now(),\r\n data: { toolName, args },\r\n });\r\n }\r\n\r\n /**\r\n * Get all events\r\n */\r\n getEvents(): ExecutionEvent[] {\r\n return [...this.events];\r\n }\r\n\r\n /**\r\n * Get events by type\r\n */\r\n getEventsByType(type: string): ExecutionEvent[] {\r\n return this.events.filter((e) => e.type === type);\r\n }\r\n\r\n /**\r\n * Print execution timeline\r\n */\r\n printTimeline(): void {\r\n if (this.events.length === 0) {\r\n console.log('No events recorded');\r\n return;\r\n }\r\n\r\n const startTime = this.events[0].timestamp;\r\n\r\n console.log('\\n=== Execution Timeline ===\\n');\r\n\r\n for (const event of this.events) {\r\n const elapsed = ((event.timestamp - startTime) / 1000).toFixed(2);\r\n console.log(`[+${elapsed}s] ${event.type}`);\r\n\r\n if (event.type === 'llm_call') {\r\n console.log(` Messages: ${event.data.messageCount}`);\r\n } else if (event.type === 'validation') {\r\n console.log(` Valid: ${event.data.valid}`);\r\n if (!event.data.valid) {\r\n console.log(` Errors: ${event.data.errors?.length || 0}`);\r\n }\r\n } else if (event.type === 'retry') {\r\n console.log(` Attempt: ${event.data.attempt}/${event.data.maxAttempts}`);\r\n } else if (event.type === 'tool_call') {\r\n console.log(` Tool: ${event.data.toolName}`);\r\n }\r\n }\r\n\r\n console.log('\\n=========================\\n');\r\n }\r\n\r\n /**\r\n * Clear all events\r\n */\r\n clear(): void {\r\n this.events = [];\r\n }\r\n\r\n /**\r\n * Get execution summary\r\n */\r\n getSummary(): ExecutionSummary {\r\n const llmCalls = this.getEventsByType('llm_call').length;\r\n const validations = this.getEventsByType('validation').length;\r\n const retries = this.getEventsByType('retry').length;\r\n const toolCalls = this.getEventsByType('tool_call').length;\r\n\r\n const duration =\r\n this.events.length > 0\r\n ? this.events[this.events.length - 1].timestamp - this.events[0].timestamp\r\n : 0;\r\n\r\n return {\r\n totalEvents: this.events.length,\r\n llmCalls,\r\n validations,\r\n retries,\r\n toolCalls,\r\n durationMs: duration,\r\n };\r\n }\r\n}\r\n\r\n/**\r\n * Execution event type\r\n */\r\nexport interface ExecutionEvent {\r\n type: string;\r\n timestamp: number;\r\n data: any;\r\n}\r\n\r\n/**\r\n * Execution summary\r\n */\r\nexport interface ExecutionSummary {\r\n totalEvents: number;\r\n llmCalls: number;\r\n validations: number;\r\n retries: number;\r\n toolCalls: number;\r\n durationMs: number;\r\n}\r\n\r\n/**\r\n * Performance Monitor\r\n *\r\n * Monitor performance metrics during agent execution.\r\n */\r\nexport class PerformanceMonitor {\r\n private timings: Map<string, number[]> = new Map();\r\n private enabled: boolean;\r\n\r\n constructor(enabled = DEBUG_ENABLED) {\r\n this.enabled = enabled;\r\n }\r\n\r\n /**\r\n * Start timing\r\n */\r\n start(label: string): () => void {\r\n if (!this.enabled) return () => {};\r\n\r\n const startTime = performance.now();\r\n\r\n return () => {\r\n const duration = performance.now() - startTime;\r\n const timings = this.timings.get(label) || [];\r\n timings.push(duration);\r\n this.timings.set(label, timings);\r\n };\r\n }\r\n\r\n /**\r\n * Get statistics for a label\r\n */\r\n getStats(label: string): TimingStats | undefined {\r\n const timings = this.timings.get(label);\r\n if (!timings || timings.length === 0) return undefined;\r\n\r\n const sorted = [...timings].sort((a, b) => a - b);\r\n const sum = sorted.reduce((a, b) => a + b, 0);\r\n\r\n return {\r\n count: sorted.length,\r\n min: sorted[0],\r\n max: sorted[sorted.length - 1],\r\n mean: sum / sorted.length,\r\n median: sorted[Math.floor(sorted.length / 2)],\r\n p95: sorted[Math.floor(sorted.length * 0.95)],\r\n p99: sorted[Math.floor(sorted.length * 0.99)],\r\n };\r\n }\r\n\r\n /**\r\n * Print all statistics\r\n */\r\n printStats(): void {\r\n console.log('\\n=== Performance Stats ===\\n');\r\n\r\n for (const [label, _timings] of this.timings) {\r\n const stats = this.getStats(label);\r\n if (!stats) continue;\r\n\r\n console.log(`${label}:`);\r\n console.log(` Count: ${stats.count}`);\r\n console.log(` Mean: ${stats.mean.toFixed(2)}ms`);\r\n console.log(` Min: ${stats.min.toFixed(2)}ms`);\r\n console.log(` Max: ${stats.max.toFixed(2)}ms`);\r\n console.log(` P95: ${stats.p95.toFixed(2)}ms`);\r\n console.log('');\r\n }\r\n\r\n console.log('=========================\\n');\r\n }\r\n\r\n /**\r\n * Clear all timings\r\n */\r\n clear(): void {\r\n this.timings.clear();\r\n }\r\n}\r\n\r\n/**\r\n * Timing statistics\r\n */\r\nexport interface TimingStats {\r\n count: number;\r\n min: number;\r\n max: number;\r\n mean: number;\r\n median: number;\r\n p95: number;\r\n p99: number;\r\n}\r\n\r\n/**\r\n * Global performance monitor instance\r\n */\r\nexport const perfMonitor = new PerformanceMonitor();\r\n\r\n/**\r\n * Global execution tracer instance\r\n */\r\nexport const tracer = new ExecutionTracer();\r\n","/**\n * Deity - LLM Execution Loop\n *\n * Handles LLM calls with tool execution loop.\n *\n * **Tool Handling Architecture**:\n * - Deity passes tools to adapter via generate(messages, tools, config)\n * - Adapter decides how to handle tools:\n * - Option A: Use SDK's native tool support (OpenAI, Anthropic, Copilot SDK)\n * - Option B: Use Deity's optional helpers (injectToolPrompts, parseToolCallsFromResponse)\n * - Deity executes tool calls returned by adapter\n */\n\nimport type {\n Message,\n ToolSpec,\n LLMAdapter,\n GenerationConfig,\n LLMResponse,\n ToolCall,\n ExecutionContext,\n LLMLoopResult,\n Validator,\n LLMLoopState\n} from './types.js';\n\n// ============================================================================\n// LLM Loop Configuration\n// ============================================================================\n\n/**\n * Memory injection configuration\n */\nexport interface MemoryInjectionConfig {\n /** Enable automatic memory injection (default: true if memory is available) */\n enabled?: boolean;\n\n /** Maximum number of memories to inject (default: 5) */\n maxMemories?: number;\n\n /** Filter by categories */\n categories?: string[];\n\n /** Minimum relevance score (0-100, default: 50) */\n minRelevanceScore?: number;\n\n /** Injection position */\n injectionPosition?: 'before-user' | 'after-system';\n}\n\n/**\n * LLM loop configuration\n */\nexport interface LLMLoopConfig {\n /** Maximum tool calling rounds */\n maxToolRounds?: number;\n\n /** Timeout for LLM calls (ms) */\n timeout?: number;\n\n /** Enable verbose logging */\n verbose?: boolean;\n\n /** Memory injection configuration */\n memoryInjection?: MemoryInjectionConfig;\n}\n\n/**\n * Default LLM loop configuration\n */\nexport const DEFAULT_LLM_LOOP_CONFIG: Required<Omit<LLMLoopConfig, 'memoryInjection'>> = {\n maxToolRounds: 10,\n timeout: 120000, // 2 minutes\n verbose: false\n};\n\n/**\n * Deadline prompt injected when timeout or maxToolRounds is reached.\n * Instructs the LLM to immediately provide its final answer without further tool calls.\n * Exported for testing and external customization.\n */\nexport const DEADLINE_PROMPT = `⚠️ DEADLINE REACHED: You have reached the maximum allowed rounds or time limit. You MUST immediately provide your final answer based on the information gathered so far. Do NOT call any more tools. Respond with your best final output NOW.`;\n\n// ============================================================================\n// LLM Loop Result (now exported from core/types.ts)\n// ============================================================================\n// export interface LLMLoopResult - moved to core/types.ts for use in AgentComponent\n\n// ============================================================================\n// LLM Execution Loop\n// ============================================================================\n\n/**\n * Execute LLM with tool calling loop\n *\n * Architecture:\n * 1. Pass messages and tools to adapter\n * 2. Adapter handles tool calling (native or via helpers)\n * 3. Framework executes tool calls returned by adapter\n * 4. Repeat until no tool calls or max rounds\n *\n * @param adapter - LLM adapter (handles tool integration)\n * @param initialMessages - Initial conversation messages\n * @param tools - Available tools (adapter decides how to handle)\n * @param config - Generation configuration\n * @param ctx - Execution context\n * @param loopConfig - Loop configuration\n * @param validator - Optional validator for loop convergence\n */\nexport async function executeLLMLoop(\n adapter: LLMAdapter,\n initialMessages: Message[],\n tools: ToolSpec[] | undefined,\n config: GenerationConfig | undefined,\n ctx: ExecutionContext,\n loopConfig: LLMLoopConfig = {},\n validator?: Validator\n): Promise<LLMLoopResult> {\n const cfg = { ...DEFAULT_LLM_LOOP_CONFIG, ...loopConfig };\n\n // 🌟 Inject relevant memories before starting loop\n const messagesWithMemory = await injectRelevantMemories(\n initialMessages,\n ctx,\n loopConfig.memoryInjection\n );\n\n const messages = [...messagesWithMemory];\n const errors: string[] = [];\n let rounds = 0;\n let toolCallsExecuted = 0;\n let response: LLMResponse;\n let toolCallsThisRound: ToolCall[] = []; // Track tool calls for validator\n const startTime = Date.now();\n\n // Main loop\n while (rounds < cfg.maxToolRounds) {\n rounds++;\n toolCallsThisRound = []; // Reset for this round\n\n // Log LLM call\n await ctx.trace.log({\n type: 'llm_call',\n messages: [...messages],\n tools,\n timestamp: new Date()\n });\n\n // Call LLM (adapter handles tools)\n try {\n response = await adapter.generate(messages, tools, config, ctx);\n } catch (error) {\n throw new Error(\n `LLM call failed: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n\n // Log LLM response\n await ctx.trace.log({\n type: 'llm_response',\n content: response.content,\n toolCalls: response.toolCalls,\n timestamp: new Date()\n });\n\n // Add assistant message\n messages.push({\n role: 'assistant',\n content: response.content\n });\n\n // Check for tool calls\n if (!response.toolCalls || response.toolCalls.length === 0) {\n // No more tool calls - but check validator before exiting\n if (validator) {\n const loopState: LLMLoopState = {\n rounds,\n response,\n messages: [...messages],\n toolCallsThisRound,\n totalToolCalls: toolCallsExecuted,\n errors: [...errors]\n };\n\n const validationResult = await Promise.resolve(validator.validate(ctx, loopState));\n\n if (!validationResult.valid && validationResult.feedback) {\n // Validation failed, add feedback and continue\n messages.push({\n role: 'user',\n content: validationResult.feedback\n });\n continue; // Continue loop to get another response\n }\n }\n\n // No more tool calls and validation passed (or no validator) - exit loop\n break;\n }\n\n // Execute tool calls\n for (const toolCall of response.toolCalls) {\n // Check if tool is already executed (by SDK)\n const alreadyExecuted = (toolCall as any)._alreadyExecuted;\n\n if (alreadyExecuted) {\n // Tool was already executed by SDK, just record it\n toolCallsThisRound.push(toolCall);\n toolCallsExecuted++;\n\n // Add tool result message\n const result = (toolCall as any)._executionResult || '{\"success\":true}';\n messages.push({\n role: 'tool',\n content: result,\n toolCallId: toolCall.id,\n name: toolCall.name\n });\n\n // Log tool call (executed by adapter)\n await ctx.trace.log({\n type: 'tool_call',\n toolName: toolCall.name,\n input: toolCall.arguments,\n timestamp: new Date()\n } as any);\n\n continue;\n }\n\n // Tool not executed yet, execute it now\n toolCallsThisRound.push(toolCall);\n toolCallsExecuted++;\n\n try {\n const result = await executeToolCall(toolCall, tools, ctx);\n\n // Add tool result message\n messages.push({\n role: 'tool',\n content: JSON.stringify(result),\n toolCallId: toolCall.id,\n name: toolCall.name\n });\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : String(error);\n errors.push(`Tool ${toolCall.name} failed: ${errorMsg}`);\n\n // Add error as tool result\n messages.push({\n role: 'tool',\n content: JSON.stringify({\n success: false,\n error: errorMsg\n }),\n toolCallId: toolCall.id,\n name: toolCall.name\n });\n }\n }\n\n // Check if all tools were pre-executed by adapter (e.g., Copilot SDK)\n // If so, the adapter already completed its internal tool loop — don't send to LLM again\n const allPreExecuted = response.toolCalls!.every(tc => (tc as any)._alreadyExecuted);\n\n // After executing tools, check validator\n if (validator) {\n const loopState: LLMLoopState = {\n rounds,\n response,\n messages: [...messages],\n toolCallsThisRound,\n totalToolCalls: toolCallsExecuted,\n errors: [...errors]\n };\n\n const validationResult = await Promise.resolve(validator.validate(ctx, loopState));\n\n if (validationResult.valid) {\n // Validation passed, exit loop\n break;\n } else if (validationResult.feedback) {\n // Validation failed, provide feedback and continue\n messages.push({\n role: 'user',\n content: validationResult.feedback\n });\n // Continue to next iteration\n }\n }\n\n // If all tools were pre-executed by SDK, don't loop again\n // The SDK already completed its tool calling internally\n if (allPreExecuted) {\n break;\n }\n\n // ===== Graceful termination: check timeout and maxToolRounds after each complete round =====\n // Only check after a full round (LLM call + tool execution) has completed.\n // We never interrupt an in-progress LLM call — timeout is cooperative, not preemptive.\n const isTimeout = cfg.timeout > 0 && (Date.now() - startTime) >= cfg.timeout;\n const isLastRound = rounds >= cfg.maxToolRounds;\n\n if (isTimeout || isLastRound) {\n // Inject deadline prompt and make one final LLM call without tools\n messages.push({\n role: 'user',\n content: DEADLINE_PROMPT\n });\n\n // Final LLM call — no tools passed, forcing a text-only response\n try {\n response = await adapter.generate(messages, undefined, config, ctx);\n messages.push({ role: 'assistant', content: response.content });\n } catch (_error) {\n // Even if the final call fails, we don't throw — preserve whatever response we have\n }\n\n errors.push(\n isTimeout\n ? `Timeout reached (${cfg.timeout}ms)`\n : `Maximum tool rounds (${cfg.maxToolRounds}) reached`\n );\n break;\n }\n }\n\n return {\n response: response!,\n messages,\n rounds,\n toolCallsExecuted,\n errors\n };\n}\n\n// ============================================================================\n// Tool Execution\n// ============================================================================\n\n/**\n * Execute a single tool call\n */\nasync function executeToolCall(\n toolCall: ToolCall,\n tools: ToolSpec[] | undefined,\n ctx: ExecutionContext\n): Promise<unknown> {\n // Find tool\n const tool = tools?.find(t => t.name === toolCall.name);\n if (!tool) {\n throw new Error(`Tool not found: ${toolCall.name}`);\n }\n\n // Parse arguments\n let args: unknown;\n try {\n args = JSON.parse(toolCall.arguments);\n } catch (error) {\n throw new Error(\n `Invalid tool arguments JSON: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n\n // Validate arguments\n const validation = tool.inputSchema.safeParse(args);\n if (!validation.success) {\n throw new Error(\n `Tool input validation failed: ${validation.error.issues.map((e: any) => e.message).join(', ')}`\n );\n }\n\n // Log tool call\n await ctx.trace.log({\n type: 'tool_call',\n toolName: toolCall.name,\n input: validation.data,\n timestamp: new Date()\n });\n\n // Execute tool\n let result: unknown;\n try {\n result = await tool.execute(validation.data, ctx);\n } catch (error) {\n // Tool threw error\n throw error;\n }\n\n // Log tool result\n await ctx.trace.log({\n type: 'tool_result',\n toolName: toolCall.name,\n result,\n timestamp: new Date()\n });\n\n // Check if result is ToolResult wrapper\n if (\n result &&\n typeof result === 'object' &&\n 'success' in result &&\n typeof (result as { success: boolean }).success === 'boolean'\n ) {\n const toolResult = result as { success: boolean; error?: string };\n if (!toolResult.success && toolResult.error) {\n throw new Error(toolResult.error);\n }\n }\n\n return result;\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Create simple LLM loop (no tools)\n */\nexport async function executeSimpleLLM(\n adapter: LLMAdapter,\n messages: Message[],\n config: GenerationConfig | undefined,\n ctx: ExecutionContext\n): Promise<LLMResponse> {\n const result = await executeLLMLoop(\n adapter,\n messages,\n undefined,\n config,\n ctx,\n { maxToolRounds: 1 }\n );\n\n return result.response;\n}\n\n/**\n * Check if LLM result has errors\n */\nexport function hasLLMErrors(result: LLMLoopResult): boolean {\n return result.errors.length > 0;\n}\n\n/**\n * Format LLM result summary\n */\nexport function formatLLMResult(result: LLMLoopResult): string {\n const lines = [\n `LLM Loop Summary:`,\n ` Rounds: ${result.rounds}`,\n ` Tool calls: ${result.toolCallsExecuted}`,\n ` Errors: ${result.errors.length}`\n ];\n\n if (result.errors.length > 0) {\n lines.push(` Error details:`);\n for (const error of result.errors) {\n lines.push(` - ${error}`);\n }\n }\n\n return lines.join('\\n');\n}\n\n// ============================================================================\n// Memory Injection\n// ============================================================================\n\n/**\n * Inject relevant memories into message list\n *\n * Automatically retrieves and injects relevant memories based on current task context.\n * This implements Deity's \"dynamic context reconstruction\" philosophy.\n *\n * @param messages Current message list\n * @param ctx Execution context\n * @param config Memory injection configuration\n * @returns Messages with injected memories\n */\nasync function injectRelevantMemories(\n messages: Message[],\n ctx: ExecutionContext,\n config?: MemoryInjectionConfig\n): Promise<Message[]> {\n // If memory not enabled, return original messages\n if (!ctx.memory) {\n return messages;\n }\n\n // If injection explicitly disabled, return original messages\n if (config?.enabled === false) {\n return messages;\n }\n\n // Find last user message to determine current task context\n const lastUserMessage = [...messages].reverse().find(m => m.role === 'user');\n if (!lastUserMessage) {\n return messages;\n }\n\n // Extract keywords from user message\n const keywords = extractKeywords(lastUserMessage.content);\n\n // Load relevant memories\n const relevantMemories = await ctx.memory.loadWorkingMemory({\n currentTask: lastUserMessage.content,\n keywords,\n categories: config?.categories\n });\n\n // If no relevant memories, return original messages\n if (relevantMemories.length === 0) {\n return messages;\n }\n\n // Apply minimum relevance threshold if specified\n // Note: loadWorkingMemory already returns sorted by relevance\n // We just need to limit the count\n const maxMemories = config?.maxMemories ?? 5;\n const topMemories = relevantMemories.slice(0, maxMemories);\n\n // Format memories for injection\n const memoryContent = formatMemoriesForInjection(topMemories);\n\n // Create memory injection message\n const memoryMessage: Message = {\n role: 'system',\n content: memoryContent\n };\n\n // Determine injection position\n const position = config?.injectionPosition ?? 'after-system';\n\n if (position === 'after-system') {\n // Insert after last system message, before user messages\n const systemMessages = messages.filter(m => m.role === 'system');\n const nonSystemMessages = messages.filter(m => m.role !== 'system');\n\n return [\n ...systemMessages,\n memoryMessage, // Inject here\n ...nonSystemMessages\n ];\n } else {\n // Insert before user messages\n const beforeUser = messages.filter(m => m.role !== 'user');\n const userMessages = messages.filter(m => m.role === 'user');\n\n return [\n ...beforeUser,\n memoryMessage, // Inject here\n ...userMessages\n ];\n }\n}\n\n/**\n * Format memories for injection into LLM context\n */\nfunction formatMemoriesForInjection(memories: import('../memory/types.js').Memory[]): string {\n let content = '## Relevant Context from Previous Analysis\\n\\n';\n content += 'The following information was stored from earlier work and may be relevant to your current task:\\n\\n';\n\n for (const memory of memories) {\n content += `### ${memory.id}\\n`;\n\n if (memory.category) {\n content += `**Category**: ${memory.category}\\n`;\n }\n\n content += `**Importance**: ${memory.importance}/10\\n`;\n\n if (memory.tags && memory.tags.length > 0) {\n content += `**Tags**: ${memory.tags.join(', ')}\\n`;\n }\n\n content += `\\n${memory.content}\\n\\n`;\n content += '---\\n\\n';\n }\n\n return content;\n}\n\n/**\n * Extract keywords from text\n */\nfunction extractKeywords(text: string): string[] {\n // Simple keyword extraction\n // Remove common words, split on whitespace, filter short words\n const commonWords = new Set([\n 'the', 'be', 'to', 'of', 'and', 'a', 'in', 'that', 'have', 'i',\n 'it', 'for', 'not', 'on', 'with', 'he', 'as', 'you', 'do', 'at',\n 'this', 'but', 'his', 'by', 'from', 'they', 'we', 'say', 'her', 'she',\n 'or', 'an', 'will', 'my', 'one', 'all', 'would', 'there', 'their',\n 'what', 'so', 'up', 'out', 'if', 'about', 'who', 'get', 'which', 'go', 'me'\n ]);\n\n const words = text\n .toLowerCase()\n .replace(/[^a-z0-9\\s]/g, ' ') // Remove punctuation\n .split(/\\s+/)\n .filter(word => word.length > 3) // At least 4 characters\n .filter(word => !commonWords.has(word)); // Not a common word\n\n // Return unique keywords\n return Array.from(new Set(words));\n}\n","/**\n * Deity - Retry Mechanism\n *\n * Validation-based retry with dynamic stop conditions\n */\n\nimport type {\n AgentComponent,\n ExecutionContext,\n ValidationResult,\n Message,\n RetryConfig\n} from './types.js';\n// import { RetryManager } from './retry.js'; // TODO: RetryManager not implemented yet\n\n// ============================================================================\n// Retry Execution Result\n// ============================================================================\n\n/**\n * Result from retry execution\n */\nexport interface RetryExecutionResult<O> {\n /** Final output (if successful) */\n output?: O;\n\n /** Whether execution succeeded */\n success: boolean;\n\n /** Total attempts made */\n attempts: number;\n\n /** Validation errors from final attempt */\n errors: string[];\n\n /** All validation results */\n validationHistory: ValidationResult[];\n\n /** All outputs attempted */\n outputHistory: O[];\n}\n\n// ============================================================================\n// Retry Loop\n// ============================================================================\n\n/**\n * Execute component with retry logic\n *\n * Algorithm:\n * 1. Execute component (buildPrompt + LLM + parse)\n * 2. Validate output\n * 3. If valid → return output\n * 4. If invalid:\n * a. Check shouldRetry\n * b. If should retry → add feedback + retry\n * c. If should not retry → fail\n */\nexport async function executeWithRetry<I, O>(\n component: AgentComponent<I, O>,\n ctx: ExecutionContext<I>,\n executeFn: (feedbackMessages?: Message[]) => Promise<O>\n): Promise<RetryExecutionResult<O>> {\n const retryConfig = component.retry ?? { maxAttempts: 1 };\n // const retryManager = new RetryManager(retryConfig); // TODO: RetryManager not implemented yet\n\n const validationHistory: ValidationResult[] = [];\n const outputHistory: O[] = [];\n let attempts = 0;\n\n while (true) {\n attempts++;\n\n // Execute component\n let output: O;\n try {\n // Build feedback messages for retry attempts\n const feedbackMessages = attempts > 1\n ? buildFeedbackMessages(validationHistory, retryConfig)\n : undefined;\n\n output = await executeFn(feedbackMessages);\n } catch (error) {\n // Execution failed (e.g., LLM error, parse error)\n return {\n success: false,\n attempts,\n errors: [error instanceof Error ? error.message : String(error)],\n validationHistory,\n outputHistory\n };\n }\n\n outputHistory.push(output);\n\n // Validate output (if validateOutput method is provided)\n let validation: ValidationResult;\n if (component.validateOutput) {\n try {\n validation = await Promise.resolve(component.validateOutput(output, ctx));\n } catch (error) {\n // Validation threw error\n validation = {\n valid: false,\n errors: [error instanceof Error ? error.message : String(error)]\n };\n }\n } else {\n // No validation method, assume valid\n validation = { valid: true };\n }\n\n validationHistory.push(validation);\n\n // Log validation result\n if (!validation.valid) {\n await ctx.trace.log({\n type: 'validation_failed',\n errors: validation.errors ?? [],\n attempt: attempts,\n timestamp: new Date()\n });\n }\n\n // Check if valid\n if (validation.valid) {\n // Success!\n return {\n output,\n success: true,\n attempts,\n errors: [],\n validationHistory,\n outputHistory\n };\n }\n\n // Check if should retry\n const shouldRetry = retryConfig.shouldRetry\n ? retryConfig.shouldRetry(attempts, output, ctx)\n : attempts < retryConfig.maxAttempts;\n\n if (!shouldRetry) {\n // Graceful degradation: if we produced output at least once, return the\n // last output as a best-effort result instead of failing completely.\n // This allows the workflow to continue with the best available answer\n // rather than throwing an error and halting execution.\n const lastOutput = outputHistory[outputHistory.length - 1];\n if (lastOutput !== undefined) {\n return {\n output: lastOutput,\n success: true,\n attempts,\n errors: validation.errors ?? ['Validation failed (used best-effort output)'],\n validationHistory,\n outputHistory\n };\n }\n\n // No output was ever produced — genuine failure\n return {\n success: false,\n attempts,\n errors: validation.errors ?? ['Validation failed'],\n validationHistory,\n outputHistory\n };\n }\n\n // Continue to next attempt\n }\n}\n\n// ============================================================================\n// Feedback Messages\n// ============================================================================\n\n/**\n * Build feedback messages for retry attempts\n */\nfunction buildFeedbackMessages(\n validationHistory: ValidationResult[],\n retryConfig: RetryConfig\n): Message[] | undefined {\n // Check if feedback is enabled\n if (retryConfig.feedbackOnError === false) {\n return undefined;\n }\n\n // Get last validation result\n const lastValidation = validationHistory[validationHistory.length - 1];\n if (!lastValidation || lastValidation.valid) {\n return undefined;\n }\n\n // Build feedback message\n const errors = lastValidation.errors ?? ['Validation failed'];\n const errorList = errors.map(e => `- ${e}`).join('\\n');\n\n const feedbackContent = [\n 'Previous attempt failed validation:',\n errorList,\n '',\n 'Please correct your output and try again.'\n ].join('\\n');\n\n return [\n {\n role: 'user',\n content: feedbackContent\n }\n ];\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Check if retry result succeeded\n */\nexport function retrySucceeded<O>(result: RetryExecutionResult<O>): boolean {\n return result.success && result.output !== undefined;\n}\n\n/**\n * Get retry result output (throws if failed)\n */\nexport function getRetryOutput<O>(result: RetryExecutionResult<O>): O {\n if (!result.success || !result.output) {\n throw new Error(\n `Retry execution failed after ${result.attempts} attempts: ${result.errors.join(', ')}`\n );\n }\n return result.output;\n}\n\n/**\n * Format retry result summary\n */\nexport function formatRetryResult<O>(result: RetryExecutionResult<O>): string {\n const lines = [\n `Retry Execution Summary:`,\n ` Status: ${result.success ? 'SUCCESS' : 'FAILED'}`,\n ` Attempts: ${result.attempts}`,\n ` Outputs tried: ${result.outputHistory.length}`\n ];\n\n if (!result.success) {\n lines.push(` Final errors:`);\n for (const error of result.errors) {\n lines.push(` - ${error}`);\n }\n }\n\n // Validation history\n if (result.validationHistory.length > 0) {\n lines.push(` Validation history:`);\n for (let i = 0; i < result.validationHistory.length; i++) {\n const validation = result.validationHistory[i];\n const status = validation.valid ? '✓' : '✗';\n lines.push(` Attempt ${i + 1}: ${status}`);\n if (!validation.valid && validation.errors) {\n for (const error of validation.errors) {\n lines.push(` - ${error}`);\n }\n }\n }\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Create retry config with defaults\n */\nexport function createRetryConfig(config?: Partial<RetryConfig>): RetryConfig {\n return {\n maxAttempts: config?.maxAttempts ?? 3,\n feedbackOnError: config?.feedbackOnError ?? true,\n retryOnToolError: config?.retryOnToolError ?? true,\n feedbackErrorToLLM: config?.feedbackErrorToLLM ?? true,\n toolCosts: config?.toolCosts,\n phases: config?.phases,\n shouldRetry: config?.shouldRetry\n };\n}\n","/**\n * Deity - Output Parser\n *\n * Parse and validate LLM output\n */\n\nimport type { ZodSchema } from 'zod';\n\n// ============================================================================\n// JSON Extraction\n// ============================================================================\n\n/**\n * Extract JSON from LLM response\n *\n * Handles:\n * - Code fences (```json ... ```)\n * - Preamble text before JSON\n * - Multiple JSON blocks (returns first valid)\n */\nexport function extractJSON(content: string): unknown {\n // Try to find JSON in code fence\n const codeFenceMatch = content.match(/```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?```/);\n if (codeFenceMatch) {\n try {\n return JSON.parse(codeFenceMatch[1].trim());\n } catch {\n // Continue to other methods\n }\n }\n\n // Try to find JSON object/array\n const jsonPatterns = [\n /\\{[\\s\\S]*\\}/, // Object\n /\\[[\\s\\S]*\\]/ // Array\n ];\n\n for (const pattern of jsonPatterns) {\n const match = content.match(pattern);\n if (match) {\n try {\n return JSON.parse(match[0]);\n } catch {\n // Continue to next pattern\n }\n }\n }\n\n // Try to parse entire content as JSON\n try {\n return JSON.parse(content.trim());\n } catch {\n throw new Error(\n 'Failed to extract valid JSON from LLM response. ' +\n 'Response should contain valid JSON object or array.'\n );\n }\n}\n\n// ============================================================================\n// Output Parsing\n// ============================================================================\n\n/**\n * Parse and validate component output\n */\nexport function parseComponentOutput<O>(\n content: string,\n schema: ZodSchema<O>\n): O {\n // Extract JSON\n let json: unknown;\n try {\n json = extractJSON(content);\n } catch (error) {\n throw new Error(\n `Failed to parse output: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n\n // Validate with schema\n const validation = schema.safeParse(json);\n if (!validation.success) {\n const errors = validation.error.issues\n .map((e: any) => `${e.path.join('.')}: ${e.message}`)\n .join('; ');\n\n throw new Error(`Output validation failed: ${errors}`);\n }\n\n return validation.data;\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Check if string contains JSON\n */\nexport function containsJSON(content: string): boolean {\n try {\n extractJSON(content);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Format validation error\n */\nexport function formatValidationError(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n return String(error);\n}\n","/**\n * Deity -Component Executor\n *\n * Orchestrates AgentComponent execution\n */\n\nimport type {\n AgentComponent,\n ExecutionContext,\n LLMAdapter,\n GenerationConfig,\n Message,\n LLMLoopResult\n} from './types.js';\nimport { executeLLMLoop } from './llm-loop.js';\nimport { executeWithRetry, type RetryExecutionResult } from './retry.js';\nimport { parseComponentOutput } from './parser.js';\n\n// ============================================================================\n// Component Execution Result\n// ============================================================================\n\n/**\n * Result from component execution\n */\nexport interface ComponentExecutionResult<O> {\n /** Component output */\n output: O;\n\n /** Whether execution succeeded */\n success: boolean;\n\n /** Total attempts made */\n attempts: number;\n\n /** LLM loop results from all attempts */\n llmResults: LLMLoopResult[];\n\n /** Retry execution result */\n retryResult: RetryExecutionResult<O>;\n\n /** Execution duration (ms) */\n duration: number;\n}\n\n// ============================================================================\n// Component Executor\n// ============================================================================\n\n/**\n * Execute an AgentComponent\n *\n * Orchestrates:\n * 1. Build prompt\n * 2. LLM execution loop (with tools)\n * 3. Parse output\n * 4. Validate output\n * 5. Retry if needed\n * 6. UI updates (if bridge available)\n */\nexport async function executeComponent<I, O>(\n component: AgentComponent<I, O>,\n ctx: ExecutionContext<I>,\n adapter: LLMAdapter,\n config?: GenerationConfig\n): Promise<ComponentExecutionResult<O>> {\n const startTime = Date.now();\n const llmResults: LLMLoopResult[] = [];\n\n // UI: Start step\n ctx.ui?.startStep(component.id, component.id);\n\n // Log stage start\n await ctx.trace.log({\n type: 'stage_start',\n stageId: component.id,\n timestamp: new Date()\n });\n\n // Execute with retry\n const retryResult = await executeWithRetry<I, O>(\n component,\n ctx,\n async (feedbackMessages?: Message[]) => {\n // UI: Update progress\n ctx.ui?.stepProgress(component.id, 50, 'Executing LLM...');\n\n // 1. Build prompt\n const promptMessages = await Promise.resolve(component.buildPrompt(ctx));\n\n // 2. Add feedback messages (for retry attempts)\n const messages = feedbackMessages\n ? [...promptMessages, ...feedbackMessages]\n : promptMessages;\n\n // 2.5. Resolve tools\n const resolvedTools = component.tools;\n\n // 3. Execute LLM loop (with tools)\n const llmResult = await executeLLMLoop(\n adapter,\n messages,\n resolvedTools,\n config,\n ctx,\n component.loopConfig, // Pass component-specific loop config\n component.loopValidator // Pass loop validator for convergence\n );\n\n llmResults.push(llmResult);\n\n // UI: Update progress\n ctx.ui?.stepProgress(component.id, 75, 'Parsing output...');\n\n // 4. Parse output (custom extraction or standard JSON parsing)\n let output: O;\n\n if (component.extractOutput) {\n // Custom output extraction\n await ctx.trace.log({\n type: 'output_extraction',\n method: 'custom',\n componentId: component.id,\n timestamp: new Date()\n });\n\n try {\n const extracted = await Promise.resolve(component.extractOutput(ctx, llmResult));\n\n // Validate extracted output with schema\n const validation = component.outputSchema.safeParse(extracted);\n if (!validation.success) {\n const errors = validation.error.issues\n .map((e: any) => `${e.path.join('.')}: ${e.message}`)\n .join('; ');\n throw new Error(`Output validation failed: ${errors}`);\n }\n\n output = validation.data;\n } catch (error) {\n throw new Error(\n `Failed to extract output: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n } else {\n // Standard JSON parsing\n await ctx.trace.log({\n type: 'output_extraction',\n method: 'json',\n componentId: component.id,\n timestamp: new Date()\n });\n\n output = parseComponentOutput<O>(\n llmResult.response.content,\n component.outputSchema\n );\n }\n\n return output;\n }\n );\n\n const duration = Date.now() - startTime;\n\n // Log completion or failure\n if (retryResult.success && retryResult.output) {\n await ctx.trace.log({\n type: 'stage_complete',\n output: retryResult.output,\n timestamp: new Date()\n });\n\n // UI: Complete step\n ctx.ui?.completeStep(\n component.id,\n `Completed in ${Math.round(duration / 1000)}s`\n );\n\n return {\n output: retryResult.output,\n success: true,\n attempts: retryResult.attempts,\n llmResults,\n retryResult,\n duration\n };\n } else {\n const errorMessage = retryResult.errors.join('; ');\n\n await ctx.trace.log({\n type: 'stage_failed',\n error: errorMessage,\n timestamp: new Date()\n });\n\n // UI: Fail step\n ctx.ui?.failStep(component.id, errorMessage);\n\n throw new Error(\n `Component ${component.id} failed after ${retryResult.attempts} attempts: ${errorMessage}`\n );\n }\n}\n\n// ============================================================================\n// Simplified Component Execution\n// ============================================================================\n\n/**\n * Execute component and return output only\n */\nexport async function executeComponentSimple<I, O>(\n component: AgentComponent<I, O>,\n ctx: ExecutionContext<I>,\n adapter: LLMAdapter,\n config?: GenerationConfig\n): Promise<O> {\n const result = await executeComponent(component, ctx, adapter, config);\n return result.output;\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Check if component execution succeeded\n */\nexport function componentSucceeded<O>(result: ComponentExecutionResult<O>): boolean {\n return result.success;\n}\n\n/**\n * Format component execution result\n */\nexport function formatComponentResult<O>(result: ComponentExecutionResult<O>): string {\n const lines = [\n `Component Execution Summary:`,\n ` Status: ${result.success ? 'SUCCESS' : 'FAILED'}`,\n ` Attempts: ${result.attempts}`,\n ` Duration: ${result.duration}ms`\n ];\n\n // LLM stats\n const totalRounds = result.llmResults.reduce((sum, r) => sum + r.rounds, 0);\n const totalToolCalls = result.llmResults.reduce((sum, r) => sum + r.toolCallsExecuted, 0);\n\n lines.push(` LLM rounds: ${totalRounds}`);\n lines.push(` Tool calls: ${totalToolCalls}`);\n\n // Errors\n const allErrors = result.llmResults.flatMap(r => r.errors);\n if (allErrors.length > 0) {\n lines.push(` LLM errors: ${allErrors.length}`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Get total tool calls from component result\n */\nexport function getTotalToolCalls<O>(result: ComponentExecutionResult<O>): number {\n return result.llmResults.reduce((sum, r) => sum + r.toolCallsExecuted, 0);\n}\n\n/**\n * Get total LLM rounds from component result\n */\nexport function getTotalLLMRounds<O>(result: ComponentExecutionResult<O>): number {\n return result.llmResults.reduce((sum, r) => sum + r.rounds, 0);\n}\n","/**\n * Deity -Enhanced Execution Context\n *\n * Unified context with integrated managers:\n * - ConversationManager (Phase 2)\n * - LimoMemoryManager (Phase 3)\n * - SessionStore (Phase 4)\n * - StatsManager (Phase 1)\n */\n\nimport type {\n ExecutionContext as IExecutionContext,\n StateStore,\n TraceLogger,\n ExecutionStats\n} from '../engine/types.js';\nimport type { ConversationManager } from '../conversation/manager.js';\nimport type { LimoMemoryManager } from '../memory/manager.js';\nimport type { SessionStore } from '../session/types.js';\nimport type { UIUpdateBridge } from '../engine/types.js';\n\n// ============================================================================\n// Enhanced Execution Context Class\n// ============================================================================\n\n/**\n * Enhanced execution context implementation\n *\n * Provides unified access to:\n * - Component inputs and outputs\n * - Conversation history\n * - Tiered memory\n * - Session persistence\n * - Execution statistics\n * - UI updates\n */\nexport class ExecutionContext<I = unknown> implements IExecutionContext<I> {\n // ========== Core Fields ==========\n\n /** Component inputs */\n public readonly inputs: I;\n\n /** Outputs from previous stages */\n public readonly previousOutputs: Record<string, unknown>;\n\n /** State store for persistence */\n public readonly store: StateStore;\n\n /** Trace logger for observability */\n public readonly trace: TraceLogger;\n\n /** Execution statistics */\n public readonly stats: ExecutionStats;\n\n // ========== Loop Context ==========\n\n /** Current iteration (for Loop primitive) */\n public iteration?: number;\n\n /** Maximum iterations (for Loop primitive) */\n public maxIterations?: number;\n\n /** Is this the last iteration? */\n public isLastIteration?: boolean;\n\n /** History of previous iterations */\n public iterationHistory?: unknown[];\n\n // ========== Optional Enhancements ==========\n\n /** Conversation manager (optional) */\n public readonly conversation?: ConversationManager;\n\n /** Tiered memory manager (optional) */\n public readonly memory?: LimoMemoryManager;\n\n /** UI update bridge (optional) */\n public readonly ui?: UIUpdateBridge;\n\n /** Session store (optional) */\n public readonly session?: SessionStore;\n\n /** Application state store (optional, isolated from AI memory) */\n public readonly appState?: StateStore;\n\n /** Current stage ID (for UI updates) */\n public currentStageId?: string;\n\n // ========== Constructor ==========\n\n constructor(params: {\n inputs: I;\n previousOutputs?: Record<string, unknown>;\n store: StateStore;\n trace: TraceLogger;\n stats: ExecutionStats;\n conversation?: ConversationManager;\n memory?: LimoMemoryManager;\n session?: SessionStore;\n appState?: StateStore;\n ui?: UIUpdateBridge;\n currentStageId?: string;\n iteration?: number;\n maxIterations?: number;\n iterationHistory?: unknown[];\n }) {\n this.inputs = params.inputs;\n this.previousOutputs = params.previousOutputs ?? {};\n this.store = params.store;\n this.trace = params.trace;\n this.stats = params.stats;\n this.conversation = params.conversation;\n this.memory = params.memory;\n this.session = params.session;\n this.appState = params.appState;\n this.ui = params.ui;\n this.currentStageId = params.currentStageId;\n this.iteration = params.iteration;\n this.maxIterations = params.maxIterations;\n this.iterationHistory = params.iterationHistory;\n\n // Calculate isLastIteration\n if (params.iteration !== undefined && params.maxIterations !== undefined) {\n this.isLastIteration = params.iteration >= params.maxIterations - 1;\n }\n }\n\n // ========== Core Methods ==========\n\n /**\n * Get output from a specific stage\n * @throws Error if stage not completed\n */\n getOutput<T>(stageId: string): T {\n if (!(stageId in this.previousOutputs)) {\n throw new Error(\n `Stage \"${stageId}\" has not been completed yet. ` +\n `Available stages: ${Object.keys(this.previousOutputs).join(', ') || 'none'}`\n );\n }\n return this.previousOutputs[stageId] as T;\n }\n\n /**\n * Check if stage output exists\n */\n hasOutput(stageId: string): boolean {\n return stageId in this.previousOutputs;\n }\n\n /**\n * Get all completed stage IDs\n */\n getCompletedStages(): string[] {\n return Object.keys(this.previousOutputs);\n }\n\n // ========== Convenience Methods ==========\n\n /**\n * Clone context with updated fields\n */\n clone(updates: Partial<{\n inputs: I;\n previousOutputs: Record<string, unknown>;\n currentStageId: string;\n iteration: number;\n maxIterations: number;\n iterationHistory: unknown[];\n }>): ExecutionContext<I> {\n return new ExecutionContext({\n inputs: updates.inputs ?? this.inputs,\n previousOutputs: updates.previousOutputs ?? this.previousOutputs,\n store: this.store,\n trace: this.trace,\n stats: this.stats,\n conversation: this.conversation,\n memory: this.memory,\n session: this.session,\n appState: this.appState,\n ui: this.ui,\n currentStageId: updates.currentStageId ?? this.currentStageId,\n iteration: updates.iteration ?? this.iteration,\n maxIterations: updates.maxIterations ?? this.maxIterations,\n iterationHistory: updates.iterationHistory ?? this.iterationHistory\n });\n }\n\n /**\n * Add stage output to context\n */\n withOutput(stageId: string, output: unknown): ExecutionContext<I> {\n return this.clone({\n previousOutputs: {\n ...this.previousOutputs,\n [stageId]: output\n }\n });\n }\n\n /**\n * Update iteration info (for loops)\n */\n withIteration(iteration: number, maxIterations: number): ExecutionContext<I> {\n return this.clone({\n iteration,\n maxIterations,\n iterationHistory: this.iterationHistory\n });\n }\n\n /**\n * Update inputs (for ForEach iterations)\n */\n withInputs<NewI = I>(inputs: NewI): ExecutionContext<NewI> {\n return new ExecutionContext({\n inputs,\n previousOutputs: this.previousOutputs,\n store: this.store,\n trace: this.trace,\n stats: this.stats,\n conversation: this.conversation,\n memory: this.memory,\n session: this.session,\n appState: this.appState,\n ui: this.ui,\n currentStageId: this.currentStageId,\n iteration: this.iteration,\n maxIterations: this.maxIterations,\n iterationHistory: this.iterationHistory\n });\n }\n\n /**\n * Add to iteration history\n */\n withIterationResult(result: unknown): ExecutionContext<I> {\n return this.clone({\n iterationHistory: [...(this.iterationHistory ?? []), result]\n });\n }\n\n // ========== Manager Helpers ==========\n\n /**\n * Check if conversation is enabled\n */\n hasConversation(): boolean {\n return this.conversation !== undefined;\n }\n\n /**\n * Check if memory is enabled\n */\n hasMemory(): boolean {\n return this.memory !== undefined;\n }\n\n /**\n * Check if session is enabled\n */\n hasSession(): boolean {\n return this.session !== undefined;\n }\n\n /**\n * Check if UI is enabled\n */\n hasUI(): boolean {\n return this.ui !== undefined;\n }\n\n /**\n * Check if appState is enabled\n */\n hasAppState(): boolean {\n return this.appState !== undefined;\n }\n\n /**\n * Get conversation manager (throws if not available)\n */\n requireConversation(): ConversationManager {\n if (!this.conversation) {\n throw new Error('Conversation manager not available in this context');\n }\n return this.conversation;\n }\n\n /**\n * Get memory manager (throws if not available)\n */\n requireMemory(): LimoMemoryManager {\n if (!this.memory) {\n throw new Error('Memory manager not available in this context');\n }\n return this.memory;\n }\n\n /**\n * Get session store (throws if not available)\n */\n requireSession(): SessionStore {\n if (!this.session) {\n throw new Error('Session store not available in this context');\n }\n return this.session;\n }\n\n /**\n * Get UI bridge (throws if not available)\n */\n requireUI(): UIUpdateBridge {\n if (!this.ui) {\n throw new Error('UI bridge not available in this context');\n }\n return this.ui;\n }\n\n /**\n * Get application state store (throws if not available)\n */\n requireAppState(): StateStore {\n if (!this.appState) {\n throw new Error('Application state store not available in this context');\n }\n return this.appState;\n }\n\n // ========== Debugging ==========\n\n /**\n * Get context summary for debugging\n */\n getSummary(): {\n hasInputs: boolean;\n completedStages: string[];\n iteration?: number;\n maxIterations?: number;\n features: {\n conversation: boolean;\n memory: boolean;\n session: boolean;\n ui: boolean;\n appState: boolean;\n };\n stats: ExecutionStats;\n } {\n return {\n hasInputs: this.inputs !== undefined,\n completedStages: this.getCompletedStages(),\n iteration: this.iteration,\n maxIterations: this.maxIterations,\n features: {\n conversation: this.hasConversation(),\n memory: this.hasMemory(),\n session: this.hasSession(),\n ui: this.hasUI(),\n appState: this.hasAppState()\n },\n stats: this.stats\n };\n }\n\n /**\n * Format context as string\n */\n toString(): string {\n const summary = this.getSummary();\n const lines = [\n 'ExecutionContext {',\n ` Inputs: ${summary.hasInputs ? 'present' : 'none'}`,\n ` Completed stages: ${summary.completedStages.length}`,\n ];\n\n if (summary.iteration !== undefined) {\n lines.push(` Iteration: ${summary.iteration + 1}/${summary.maxIterations}`);\n }\n\n const enabledFeatures = Object.entries(summary.features)\n .filter(([_, enabled]) => enabled)\n .map(([feature]) => feature);\n\n if (enabledFeatures.length > 0) {\n lines.push(` Features: ${enabledFeatures.join(', ')}`);\n }\n\n lines.push('}');\n\n return lines.join('\\n');\n }\n}\n","/**\n * Deity - Conversation Types\n *\n * Types for optimized conversation management\n */\n\nimport type { Message } from '../engine/types.js';\n\n// ============================================================================\n// Conversation Message\n// ============================================================================\n\n/**\n * Message metadata for conversation management\n */\nexport interface MessageMetadata {\n /** Message importance (0-10) */\n importance?: number;\n\n /** Is this message pinned (always retained)? */\n pinned?: boolean;\n\n /** Custom tags for filtering */\n tags?: string[];\n\n /** Source of the message (stage ID, user, etc.) */\n source?: string;\n\n /** Any custom metadata */\n [key: string]: unknown;\n}\n\n/**\n * Enhanced message with conversation metadata\n */\nexport interface ConversationMessage extends Message {\n /** Unique message ID */\n id: string;\n\n /** Timestamp */\n timestamp: Date;\n\n /** Message metadata */\n metadata?: MessageMetadata;\n}\n\n// ============================================================================\n// Conversation Filter\n// ============================================================================\n\n/**\n * Filter for querying messages\n */\nexport interface ConversationFilter {\n /** Filter by role */\n role?: string;\n\n /** Filter messages after this date */\n after?: Date;\n\n /** Filter messages before this date */\n before?: Date;\n\n /** Filter by tags */\n tags?: string[];\n\n /** Filter by source */\n source?: string;\n\n /** Limit number of results */\n limit?: number;\n}\n\n// ============================================================================\n// Conversation Configuration\n// ============================================================================\n\n/**\n * Message retention policy\n */\nexport interface MessageRetentionPolicy {\n /** Determine if a message is important (should always be retained) */\n isImportant(message: ConversationMessage): boolean;\n}\n\n/**\n * Conversation configuration\n */\nexport interface ConversationConfig {\n /** Maximum tokens allowed (estimated) */\n maxTokens?: number;\n\n /** Maximum number of messages */\n maxMessages?: number;\n\n /** Threshold for pruning (0-1, default 0.75) */\n pruneThreshold?: number;\n\n /** Message retention policy */\n messageRetentionPolicy?: MessageRetentionPolicy;\n\n /** Enable token caching */\n enableTokenCaching?: boolean;\n\n /** Pruning interval in milliseconds (default: 10000ms = 10s) */\n pruningInterval?: number;\n\n /** Minimum messages before pruning (default: 50) */\n minMessagesBeforePrune?: number;\n}\n\n// ============================================================================\n// Conversation Statistics\n// ============================================================================\n\n/**\n * Conversation statistics\n */\nexport interface ConversationStats {\n /** Total messages */\n totalMessages: number;\n\n /** Messages by role */\n messagesByRole: Record<string, number>;\n\n /** Estimated total tokens */\n estimatedTokens: number;\n\n /** Number of pruning operations */\n pruningCount: number;\n\n /** Last pruning time */\n lastPruneTime?: Date;\n\n /** Important messages count */\n importantMessagesCount: number;\n}\n\n// ============================================================================\n// Default Policies\n// ============================================================================\n\n/**\n * Default retention policy: system messages and pinned messages are important\n */\nexport const DEFAULT_RETENTION_POLICY: MessageRetentionPolicy = {\n isImportant(message: ConversationMessage): boolean {\n // System messages are important\n if (message.role === 'system') return true;\n\n // Pinned messages are important\n if (message.metadata?.pinned) return true;\n\n // High importance messages\n if (message.metadata?.importance !== undefined && message.metadata.importance >= 8) {\n return true;\n }\n\n return false;\n }\n};\n\n/**\n * Default conversation configuration\n */\nexport const DEFAULT_CONVERSATION_CONFIG: Required<ConversationConfig> = {\n maxTokens: 100000,\n maxMessages: 1000,\n pruneThreshold: 0.75,\n messageRetentionPolicy: DEFAULT_RETENTION_POLICY,\n enableTokenCaching: true,\n pruningInterval: 10000, // 10 seconds\n minMessagesBeforePrune: 50\n};\n","/**\n * Deity - Conversation Utilities\n *\n * Utility functions for conversation management\n */\n\nimport type { ConversationMessage, ConversationStats } from './types.js';\n\n// ============================================================================\n// ID Generation\n// ============================================================================\n\nlet messageIdCounter = 0;\n\n/**\n * Generate unique message ID\n */\nexport function generateMessageId(): string {\n return `msg_${Date.now()}_${messageIdCounter++}`;\n}\n\n/**\n * Reset message ID counter (for testing)\n */\nexport function resetMessageIdCounter(): void {\n messageIdCounter = 0;\n}\n\n// ============================================================================\n// Token Estimation\n// ============================================================================\n\n/**\n * Estimate tokens for a message\n * Approximation: 1 token ≈ 3.5 characters\n */\nexport function estimateMessageTokens(message: ConversationMessage): number {\n const chars = message.content.length;\n return Math.ceil(chars / 3.5);\n}\n\n/**\n * Estimate tokens for multiple messages\n */\nexport function estimateMessagesTokens(messages: ConversationMessage[]): number {\n const totalChars = messages.reduce((sum, m) => sum + m.content.length, 0);\n return Math.ceil(totalChars / 3.5);\n}\n\n// ============================================================================\n// Message Formatting\n// ============================================================================\n\n/**\n * Format conversation stats as string\n */\nexport function formatConversationStats(stats: ConversationStats): string {\n const lines = [\n `Total Messages: ${stats.totalMessages}`,\n `Estimated Tokens: ${stats.estimatedTokens}`,\n `Important Messages: ${stats.importantMessagesCount}`,\n `Pruning Count: ${stats.pruningCount}`,\n ];\n\n if (stats.lastPruneTime) {\n lines.push(`Last Prune: ${stats.lastPruneTime.toISOString()}`);\n }\n\n lines.push('', 'Messages by Role:');\n for (const [role, count] of Object.entries(stats.messagesByRole)) {\n lines.push(` ${role}: ${count}`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Format message as compact string\n */\nexport function formatMessageCompact(message: ConversationMessage): string {\n const role = message.role.padEnd(10);\n const preview = message.content.slice(0, 50).replace(/\\n/g, ' ');\n const timestamp = message.timestamp.toISOString().split('T')[1].split('.')[0];\n return `[${timestamp}] ${role} ${preview}${message.content.length > 50 ? '...' : ''}`;\n}\n\n/**\n * Format messages as conversation log\n */\nexport function formatConversationLog(messages: ConversationMessage[]): string {\n return messages.map(formatMessageCompact).join('\\n');\n}\n\n// ============================================================================\n// Message Analysis\n// ============================================================================\n\n/**\n * Count messages by role\n */\nexport function countMessagesByRole(messages: ConversationMessage[]): Record<string, number> {\n const counts: Record<string, number> = {};\n for (const message of messages) {\n counts[message.role] = (counts[message.role] ?? 0) + 1;\n }\n return counts;\n}\n\n/**\n * Get unique roles in messages\n */\nexport function getUniqueRoles(messages: ConversationMessage[]): string[] {\n return Array.from(new Set(messages.map(m => m.role)));\n}\n\n/**\n * Filter messages by date range\n */\nexport function filterMessagesByDateRange(\n messages: ConversationMessage[],\n start: Date,\n end: Date\n): ConversationMessage[] {\n return messages.filter(m =>\n m.timestamp >= start && m.timestamp <= end\n );\n}\n\n/**\n * Get messages from last N minutes\n */\nexport function getRecentMessages(\n messages: ConversationMessage[],\n minutes: number\n): ConversationMessage[] {\n const cutoff = new Date(Date.now() - minutes * 60 * 1000);\n return messages.filter(m => m.timestamp >= cutoff);\n}\n\n// ============================================================================\n// Message Creation Helpers\n// ============================================================================\n\n/**\n * Create a system message\n */\nexport function createSystemMessage(content: string): ConversationMessage {\n return {\n id: generateMessageId(),\n role: 'system',\n content,\n timestamp: new Date()\n };\n}\n\n/**\n * Create a user message\n */\nexport function createUserMessage(content: string): ConversationMessage {\n return {\n id: generateMessageId(),\n role: 'user',\n content,\n timestamp: new Date()\n };\n}\n\n/**\n * Create an assistant message\n */\nexport function createAssistantMessage(content: string): ConversationMessage {\n return {\n id: generateMessageId(),\n role: 'assistant',\n content,\n timestamp: new Date()\n };\n}\n\n/**\n * Create a tool message\n */\nexport function createToolMessage(content: string, toolCallId: string): ConversationMessage {\n return {\n id: generateMessageId(),\n role: 'tool',\n content,\n toolCallId,\n timestamp: new Date()\n };\n}\n\n// ============================================================================\n// Conversation Validation\n// ============================================================================\n\n/**\n * Validate conversation alternates between user and assistant\n */\nexport function validateConversationFlow(messages: ConversationMessage[]): {\n valid: boolean;\n errors: string[];\n} {\n const errors: string[] = [];\n\n // Filter out system and tool messages\n const conversationMessages = messages.filter(\n m => m.role === 'user' || m.role === 'assistant'\n );\n\n // Check alternation\n for (let i = 1; i < conversationMessages.length; i++) {\n const prev = conversationMessages[i - 1];\n const curr = conversationMessages[i];\n\n if (prev.role === curr.role) {\n errors.push(\n `Consecutive ${curr.role} messages at positions ${i - 1} and ${i}`\n );\n }\n }\n\n // Check starts with user\n if (conversationMessages.length > 0 && conversationMessages[0].role !== 'user') {\n errors.push('Conversation should start with a user message');\n }\n\n return {\n valid: errors.length === 0,\n errors\n };\n}\n\n/**\n * Check if conversation has system message\n */\nexport function hasSystemMessage(messages: ConversationMessage[]): boolean {\n return messages.some(m => m.role === 'system');\n}\n\n/**\n * Get conversation length in tokens\n */\nexport function getConversationLength(messages: ConversationMessage[]): {\n messages: number;\n tokens: number;\n characters: number;\n} {\n const characters = messages.reduce((sum, m) => sum + m.content.length, 0);\n const tokens = Math.ceil(characters / 3.5);\n\n return {\n messages: messages.length,\n tokens,\n characters\n };\n}\n","/**\n * Deity - Conversation Manager\n *\n * Optimized conversation management with O(1) operations\n *\n * Performance targets (from LIMO_DEITY_CONSENSUS.md):\n * - addMessage: < 1ms (99th percentile)\n * - getMessages(role): O(1) indexed lookup\n * - Pruning frequency: Every 50 messages or 10 seconds\n *\n * Optimizations:\n * - Role indexing for O(1) role-based queries\n * - Importance indexing for fast pruning\n * - Token estimate caching to avoid recalculation\n * - Incremental pruning (not every message)\n */\n\nimport type { Message } from '../engine/types.js';\nimport type {\n ConversationMessage,\n MessageMetadata,\n ConversationFilter,\n ConversationConfig,\n ConversationStats\n} from './types.js';\nimport { DEFAULT_CONVERSATION_CONFIG } from './types.js';\nimport { generateMessageId } from './utils.js';\n\n// ============================================================================\n// Conversation Manager\n// ============================================================================\n\n/**\n * Optimized conversation manager with indexed lookups\n */\nexport class ConversationManager {\n private messages: ConversationMessage[] = [];\n private config: Required<ConversationConfig>;\n\n // ========== Indexes (O(1) lookups) ==========\n\n /** Role index: role -> messages */\n private roleIndex: Map<string, ConversationMessage[]> = new Map();\n\n /** Important messages set: message ID -> message */\n private importantMessagesSet: Set<string> = new Set();\n\n // ========== Pruning state ==========\n\n /** Size at last pruning */\n private lastPruneSize: number = 0;\n\n /** Time of last pruning */\n private lastPruneTime: number = 0;\n\n /** Number of pruning operations */\n private pruningCount: number = 0;\n\n // ========== Token caching ==========\n\n /** Cached token estimate */\n private tokenEstimateCache: number = 0;\n\n /** Cache size (number of messages when cached) */\n private tokenEstimateCacheSize: number = 0;\n\n constructor(config?: ConversationConfig) {\n this.config = {\n ...DEFAULT_CONVERSATION_CONFIG,\n ...config,\n messageRetentionPolicy: config?.messageRetentionPolicy ?? DEFAULT_CONVERSATION_CONFIG.messageRetentionPolicy\n };\n }\n\n // ============================================================================\n // Core Operations\n // ============================================================================\n\n /**\n * Add a message to the conversation\n * Performance target: < 1ms (99th percentile)\n */\n addMessage(message: Message, metadata?: MessageMetadata): void {\n const conversationMessage: ConversationMessage = {\n ...message,\n id: generateMessageId(),\n timestamp: new Date(),\n metadata\n };\n\n // Add to messages array\n this.messages.push(conversationMessage);\n\n // Update indexes (O(1))\n this.updateIndexes(conversationMessage);\n\n // Invalidate token cache\n this.invalidateTokenCache();\n\n // Incremental pruning check (not every message!)\n this.incrementalPruneIfNeeded();\n }\n\n /**\n * Get conversation history\n */\n getHistory(): Message[] {\n return this.messages.map(msg => ({\n role: msg.role,\n content: msg.content,\n toolCallId: msg.toolCallId,\n name: msg.name\n }));\n }\n\n /**\n * Get messages with optional filtering\n * Performance: O(1) for role-only queries (indexed)\n */\n getMessages(filter?: ConversationFilter): ConversationMessage[] {\n // Fast path: role-only query (O(1) indexed)\n if (filter?.role && !filter.after && !filter.before && !filter.tags && !filter.source) {\n const roleMessages = this.roleIndex.get(filter.role) ?? [];\n return filter.limit ? roleMessages.slice(-filter.limit) : roleMessages;\n }\n\n // General filtering\n let filtered = [...this.messages];\n\n if (filter) {\n if (filter.role) {\n filtered = filtered.filter(m => m.role === filter.role);\n }\n if (filter.after) {\n filtered = filtered.filter(m => m.timestamp >= filter.after!);\n }\n if (filter.before) {\n filtered = filtered.filter(m => m.timestamp <= filter.before!);\n }\n if (filter.tags && filter.tags.length > 0) {\n filtered = filtered.filter(m =>\n filter.tags!.some(tag => m.metadata?.tags?.includes(tag))\n );\n }\n if (filter.source) {\n filtered = filtered.filter(m => m.metadata?.source === filter.source);\n }\n if (filter.limit) {\n filtered = filtered.slice(-filter.limit);\n }\n }\n\n return filtered;\n }\n\n /**\n * Clear all messages\n */\n clear(): void {\n this.messages = [];\n this.roleIndex.clear();\n this.importantMessagesSet.clear();\n this.lastPruneSize = 0;\n this.lastPruneTime = 0;\n this.pruningCount = 0;\n this.tokenEstimateCache = 0;\n this.tokenEstimateCacheSize = 0;\n }\n\n /**\n * Get conversation statistics\n */\n getStats(): ConversationStats {\n // Update token estimate if needed\n const estimatedTokens = this.estimateTokens();\n\n // Count messages by role\n const messagesByRole: Record<string, number> = {};\n for (const [role, messages] of this.roleIndex.entries()) {\n messagesByRole[role] = messages.length;\n }\n\n return {\n totalMessages: this.messages.length,\n messagesByRole,\n estimatedTokens,\n pruningCount: this.pruningCount,\n lastPruneTime: this.lastPruneTime > 0 ? new Date(this.lastPruneTime) : undefined,\n importantMessagesCount: this.importantMessagesSet.size\n };\n }\n\n // ============================================================================\n // Indexing (O(1) operations)\n // ============================================================================\n\n /**\n * Update indexes for a new message (O(1))\n */\n private updateIndexes(message: ConversationMessage): void {\n // Role index\n if (!this.roleIndex.has(message.role)) {\n this.roleIndex.set(message.role, []);\n }\n this.roleIndex.get(message.role)!.push(message);\n\n // Important messages set\n if (this.config.messageRetentionPolicy.isImportant(message)) {\n this.importantMessagesSet.add(message.id);\n }\n }\n\n /**\n * Rebuild all indexes (after pruning)\n */\n private rebuildIndexes(): void {\n this.roleIndex.clear();\n this.importantMessagesSet.clear();\n\n for (const message of this.messages) {\n this.updateIndexes(message);\n }\n }\n\n // ============================================================================\n // Incremental Pruning\n // ============================================================================\n\n /**\n * Incremental pruning check (not every message!)\n *\n * Strategy:\n * 1. Only prune if growth >= threshold (default: 50 messages)\n * 2. Only prune if time since last prune >= interval (default: 10s)\n * 3. Only prune if token/message count exceeds threshold\n */\n private incrementalPruneIfNeeded(): void {\n // Strategy 1: Check growth threshold\n const growth = this.messages.length - this.lastPruneSize;\n const growthThreshold = this.config.minMessagesBeforePrune;\n\n if (growth < growthThreshold) {\n return; // Not enough growth\n }\n\n // Strategy 2: Check time threshold\n const timeSinceLastPrune = Date.now() - this.lastPruneTime;\n if (timeSinceLastPrune < this.config.pruningInterval) {\n return; // Too soon\n }\n\n // Strategy 3: Check if pruning is needed\n if (!this.shouldPrune()) {\n return; // No need to prune yet\n }\n\n // Execute pruning\n this.performPruning();\n\n // Update pruning state\n this.lastPruneSize = this.messages.length;\n this.lastPruneTime = Date.now();\n this.pruningCount++;\n }\n\n /**\n * Check if pruning should be performed\n */\n private shouldPrune(): boolean {\n const estimatedTokens = this.estimateTokens();\n const tokenThreshold = this.config.maxTokens * this.config.pruneThreshold;\n const messageThreshold = this.config.maxMessages * this.config.pruneThreshold;\n\n return (\n estimatedTokens >= tokenThreshold ||\n this.messages.length >= messageThreshold\n );\n }\n\n /**\n * Perform pruning operation\n *\n * Algorithm:\n * 1. Separate messages into categories (using indexes!)\n * 2. Keep all important messages (includes system messages)\n * 3. Keep most recent 1/3 of regular messages\n * 4. Rebuild indexes\n */\n private performPruning(): void {\n // Categorize messages using importance index\n const importantMessages = this.messages.filter(m =>\n this.importantMessagesSet.has(m.id)\n );\n const regularMessages = this.messages.filter(m =>\n !this.importantMessagesSet.has(m.id)\n );\n\n // Keep most recent 1/3 of regular messages\n const keepCount = Math.floor(regularMessages.length / 3);\n const recentRegular = regularMessages.slice(-keepCount);\n\n // Reconstruct messages array (no duplicates)\n this.messages = [\n ...importantMessages,\n ...recentRegular\n ].sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());\n\n // Rebuild indexes\n this.rebuildIndexes();\n\n // Invalidate token cache\n this.invalidateTokenCache();\n }\n\n // ============================================================================\n // Token Estimation (with caching)\n // ============================================================================\n\n /**\n * Estimate total tokens (cached)\n *\n * Approximation: 1 token ≈ 3.5 characters\n */\n private estimateTokens(): number {\n // Return cached value if valid\n if (this.config.enableTokenCaching &&\n this.tokenEstimateCacheSize === this.messages.length) {\n return this.tokenEstimateCache;\n }\n\n // Calculate estimate\n const totalChars = this.messages.reduce((sum, m) => sum + m.content.length, 0);\n const estimate = Math.ceil(totalChars / 3.5);\n\n // Update cache\n if (this.config.enableTokenCaching) {\n this.tokenEstimateCache = estimate;\n this.tokenEstimateCacheSize = this.messages.length;\n }\n\n return estimate;\n }\n\n /**\n * Invalidate token cache\n */\n private invalidateTokenCache(): void {\n this.tokenEstimateCacheSize = 0;\n }\n\n // ============================================================================\n // Configuration\n // ============================================================================\n\n /**\n * Get current configuration\n */\n getConfig(): Required<ConversationConfig> {\n return { ...this.config };\n }\n\n /**\n * Update configuration\n */\n updateConfig(config: Partial<ConversationConfig>): void {\n this.config = {\n ...this.config,\n ...config,\n messageRetentionPolicy: config.messageRetentionPolicy ?? this.config.messageRetentionPolicy\n };\n\n // Invalidate cache\n this.invalidateTokenCache();\n }\n}\n","/**\n * Deity - Memory Types\n *\n * Types for tiered memory management\n * Based on Deity POC with Limo enhancements\n */\n\n// ============================================================================\n// Memory Entry\n// ============================================================================\n\n/**\n * A single memory entry\n */\nexport interface Memory {\n /** Unique identifier */\n id: string;\n\n /** Memory content */\n content: string;\n\n /** Importance level (0-10) */\n importance: number;\n\n /** Category (optional) */\n category?: string;\n\n /** Tags for filtering */\n tags: string[];\n\n /** When this memory was stored */\n stored_at: Date;\n\n /** Last access time */\n last_accessed?: Date;\n\n /** Access count */\n access_count: number;\n\n /** Is this in core memory? */\n is_core: boolean;\n\n /** Source files (optional) */\n source_files?: string[];\n\n /** Conflicting memory IDs */\n conflicts_with?: string[];\n}\n\n// ============================================================================\n// Working Memory Context\n// ============================================================================\n\n/**\n * Context for loading working memory (Limo requirement)\n */\nexport interface WorkingMemoryContext {\n /** Current task description */\n currentTask: string;\n\n /** Keywords for relevance matching */\n keywords: string[];\n\n /** Relevant categories (optional) */\n categories?: string[];\n}\n\n// ============================================================================\n// Memory Configuration\n// ============================================================================\n\n/**\n * Core memory budget configuration\n */\nexport interface CoreMemoryBudget {\n /** Maximum number of items */\n maxItems: number;\n\n /** Maximum total size in bytes */\n maxTotalSize: number;\n}\n\n/**\n * Detailed memory configuration\n */\nexport interface DetailedMemoryConfig {\n /** Maximum size in bytes */\n maxSize: number;\n}\n\n/**\n * Memory configuration\n */\nexport interface MemoryConfig {\n /** Core memory budget */\n coreBudget: CoreMemoryBudget;\n\n /** Detailed memory configuration */\n detailed?: DetailedMemoryConfig;\n\n /** Enable AI compression */\n compressionEnabled?: boolean;\n}\n\n// ============================================================================\n// Memory Statistics\n// ============================================================================\n\n/**\n * Memory statistics\n */\nexport interface MemoryStats {\n /** Core memories count */\n coreCount: number;\n\n /** Detailed memories count */\n detailedCount: number;\n\n /** Total memories */\n totalCount: number;\n\n /** Core size in bytes */\n coreSize: number;\n\n /** Detailed size in bytes */\n detailedSize: number;\n\n /** Total size in bytes */\n totalSize: number;\n\n /** Core utilization (0-1) */\n coreUtilization: number;\n\n /** Detailed utilization (0-1) */\n detailedUtilization: number;\n}\n\n// ============================================================================\n// Relevance Score\n// ============================================================================\n\n/**\n * Relevance score breakdown\n */\nexport interface RelevanceScore {\n /** Total score (0-100) */\n total: number;\n\n /** Category match score */\n categoryScore: number;\n\n /** Tags match score */\n tagsScore: number;\n\n /** Importance score */\n importanceScore: number;\n\n /** Recency score */\n recencyScore: number;\n}\n\n// ============================================================================\n// Default Configuration\n// ============================================================================\n\n/**\n * Default memory configuration\n */\nexport const DEFAULT_MEMORY_CONFIG: Required<MemoryConfig> = {\n coreBudget: {\n maxItems: 10,\n maxTotalSize: 8192 // 8KB\n },\n detailed: {\n maxSize: 102400 // 100KB\n },\n compressionEnabled: true\n};\n","/**\n * Deity - Limo Memory Manager\n *\n * Simplified tiered memory manager focused on Limo-specific requirements:\n * - loadWorkingMemory() - Context-based memory loading\n * - Relevance scoring - Category + tags + importance + recency\n * - Core/detailed dual-layer architecture\n */\n\nimport type {\n Memory,\n WorkingMemoryContext,\n MemoryConfig,\n MemoryStats,\n RelevanceScore\n} from './types.js';\nimport { DEFAULT_MEMORY_CONFIG } from './types.js';\n\n// ============================================================================\n// Limo Memory Manager\n// ============================================================================\n\n/**\n * Simplified tiered memory manager\n *\n * Focus: Limo-specific features\n * - loadWorkingMemory() with relevance scoring\n * - Core/detailed layers\n * - Simple promotion/demotion\n */\nexport class LimoMemoryManager {\n private config: Required<MemoryConfig>;\n private coreMemories: Map<string, Memory> = new Map();\n private detailedMemories: Map<string, Memory> = new Map();\n\n constructor(config?: MemoryConfig) {\n this.config = {\n ...DEFAULT_MEMORY_CONFIG,\n ...config,\n coreBudget: {\n ...DEFAULT_MEMORY_CONFIG.coreBudget,\n ...config?.coreBudget\n },\n detailed: {\n ...DEFAULT_MEMORY_CONFIG.detailed,\n ...config?.detailed\n }\n };\n }\n\n // ============================================================================\n // Public API\n // ============================================================================\n\n /**\n * Store a memory\n */\n async set(key: string, value: unknown): Promise<void> {\n const content = typeof value === 'string' ? value : JSON.stringify(value);\n\n const memory: Memory = {\n id: key,\n content,\n importance: 5, // Default importance\n tags: [],\n stored_at: new Date(),\n access_count: 0,\n is_core: false\n };\n\n // Store in detailed by default\n this.detailedMemories.set(key, memory);\n\n // Enforce budget\n await this.enforceDetailedBudget();\n }\n\n /**\n * Get a memory\n */\n async get(key: string): Promise<unknown> {\n const memory = this.coreMemories.get(key) || this.detailedMemories.get(key);\n\n if (!memory) {\n return undefined;\n }\n\n // Update access metadata\n this.updateAccessMetadata(memory);\n\n // Try to parse as JSON, fallback to string\n try {\n return JSON.parse(memory.content);\n } catch {\n return memory.content;\n }\n }\n\n /**\n * Check if memory exists\n */\n async has(key: string): Promise<boolean> {\n return this.coreMemories.has(key) || this.detailedMemories.has(key);\n }\n\n /**\n * Delete a memory\n */\n async delete(key: string): Promise<void> {\n this.coreMemories.delete(key);\n this.detailedMemories.delete(key);\n }\n\n /**\n * Clear all memories\n */\n async clear(): Promise<void> {\n this.coreMemories.clear();\n this.detailedMemories.clear();\n }\n\n /**\n * Load working memory based on context (Limo requirement)\n *\n * Algorithm:\n * 1. Start with core memories (always relevant)\n * 2. Score detailed memories by relevance\n * 3. Select top N most relevant\n * 4. Update access counts\n */\n loadWorkingMemory(context: WorkingMemoryContext): Memory[] {\n // 1. Always include core memories\n const coreMemories = Array.from(this.coreMemories.values());\n\n // 2. Score detailed memories\n const scoredDetailed = Array.from(this.detailedMemories.values())\n .map(memory => ({\n memory,\n score: this.calculateRelevance(memory, context)\n }))\n .filter(item => item.score.total > 30) // Relevance threshold\n .sort((a, b) => b.score.total - a.score.total);\n\n // 3. Select top 20 most relevant\n const topRelevant = scoredDetailed\n .slice(0, 20)\n .map(item => item.memory);\n\n // 4. Update access counts\n for (const memory of [...coreMemories, ...topRelevant]) {\n this.updateAccessMetadata(memory);\n }\n\n return [...coreMemories, ...topRelevant];\n }\n\n /**\n * Get core memories\n */\n getCoreMemories(): Memory[] {\n return Array.from(this.coreMemories.values());\n }\n\n /**\n * Get detailed memories\n */\n getDetailedMemories(): Memory[] {\n return Array.from(this.detailedMemories.values());\n }\n\n /**\n * Get all memory keys (core + detailed)\n *\n * @returns Array of all memory keys\n */\n getAllKeys(): string[] {\n const keys = new Set<string>();\n for (const key of this.coreMemories.keys()) keys.add(key);\n for (const key of this.detailedMemories.keys()) keys.add(key);\n return Array.from(keys);\n }\n\n /**\n * Get all Memory objects (core + detailed)\n *\n * @returns Array of all Memory entries\n */\n getAllMemories(): Memory[] {\n return [\n ...Array.from(this.coreMemories.values()),\n ...Array.from(this.detailedMemories.values()),\n ];\n }\n\n /**\n * Get raw Memory object by key (without triggering access metadata update)\n *\n * @param key - Memory key\n * @returns Memory object or undefined\n */\n getMemory(key: string): Memory | undefined {\n return this.coreMemories.get(key) || this.detailedMemories.get(key);\n }\n\n /**\n * Update an existing memory entry\n *\n * @param key - Memory key to update\n * @param updates - Partial updates (content, importance, category, tags)\n * @returns true if updated, false if key not found\n */\n async update(\n key: string,\n updates: Partial<{ content: string; importance: number; category: string; tags: string[] }>\n ): Promise<boolean> {\n const memory = this.coreMemories.get(key) || this.detailedMemories.get(key);\n if (!memory) return false;\n\n if (updates.content !== undefined) memory.content = updates.content;\n if (updates.importance !== undefined) memory.importance = updates.importance;\n if (updates.category !== undefined) memory.category = updates.category;\n if (updates.tags !== undefined) memory.tags = updates.tags;\n\n return true;\n }\n\n /**\n * Promote a memory to core by key\n *\n * @param key - Memory key to promote\n * @returns true if promoted, false if key not found or already in core\n */\n promoteToCoreByKey(key: string): boolean {\n const memory = this.detailedMemories.get(key);\n if (!memory) {\n // Already in core or doesn't exist\n return this.coreMemories.has(key) ? false : false;\n }\n\n this.promoteToCore(memory);\n return true;\n }\n\n /**\n * Demote a memory from core to detailed by key\n *\n * @param key - Memory key to demote\n * @returns true if demoted, false if key not found in core\n */\n demoteFromCore(key: string): boolean {\n const memory = this.coreMemories.get(key);\n if (!memory) return false;\n\n memory.is_core = false;\n this.detailedMemories.set(memory.id, memory);\n this.coreMemories.delete(memory.id);\n return true;\n }\n\n /**\n * Get memory statistics\n */\n getStats(): MemoryStats {\n const coreMemories = Array.from(this.coreMemories.values());\n const detailedMemories = Array.from(this.detailedMemories.values());\n\n const coreSize = coreMemories.reduce((sum, m) => sum + m.content.length, 0);\n const detailedSize = detailedMemories.reduce((sum, m) => sum + m.content.length, 0);\n\n return {\n coreCount: coreMemories.length,\n detailedCount: detailedMemories.length,\n totalCount: coreMemories.length + detailedMemories.length,\n coreSize,\n detailedSize,\n totalSize: coreSize + detailedSize,\n coreUtilization: coreSize / this.config.coreBudget.maxTotalSize,\n detailedUtilization: detailedSize / this.config.detailed.maxSize\n };\n }\n\n // ============================================================================\n // Relevance Scoring (Limo-specific algorithm)\n // ============================================================================\n\n /**\n * Calculate relevance score for a memory\n *\n * Algorithm (from LIMO_DEITY_CONSENSUS.md):\n * - Category match: 40%\n * - Tags match (Jaccard): 30%\n * - Importance: 20%\n * - Recency: 10%\n */\n private calculateRelevance(\n memory: Memory,\n context: WorkingMemoryContext\n ): RelevanceScore {\n let categoryScore = 0;\n let tagsScore = 0;\n let importanceScore = 0;\n let recencyScore = 0;\n\n // 1. Category match (40%)\n if (context.categories && memory.category && context.categories.includes(memory.category)) {\n categoryScore = 40;\n }\n\n // 2. Tags match - Jaccard similarity (30%)\n if (context.keywords.length > 0 && memory.tags.length > 0) {\n const intersection = context.keywords.filter(k =>\n memory.tags.some(t => t.toLowerCase() === k.toLowerCase())\n ).length;\n const union = new Set([...context.keywords, ...memory.tags]).size;\n tagsScore = (intersection / union) * 30;\n }\n\n // 3. Importance (20%)\n importanceScore = (memory.importance / 10) * 20;\n\n // 4. Recency (10%)\n const ageInDays = this.calculateAgeInDays(memory.stored_at);\n const recency = Math.max(0, 1 - (ageInDays / 30)); // 30-day window\n recencyScore = recency * 10;\n\n return {\n total: categoryScore + tagsScore + importanceScore + recencyScore,\n categoryScore,\n tagsScore,\n importanceScore,\n recencyScore\n };\n }\n\n // ============================================================================\n // Internal Helpers\n // ============================================================================\n\n /**\n * Update access metadata\n */\n private updateAccessMetadata(memory: Memory): void {\n memory.access_count++;\n memory.last_accessed = new Date();\n\n // Promote to core if frequently accessed\n if (!memory.is_core && memory.access_count >= 5 && memory.importance >= 7) {\n this.promoteToCore(memory);\n }\n }\n\n /**\n * Promote memory to core\n */\n private promoteToCore(memory: Memory): void {\n // Check if already in core\n if (this.coreMemories.has(memory.id)) {\n return;\n }\n\n // Check core budget\n const coreSize = Array.from(this.coreMemories.values())\n .reduce((sum, m) => sum + m.content.length, 0);\n\n const requiredSpace = memory.content.length;\n\n // Enforce budget\n if (\n this.coreMemories.size >= this.config.coreBudget.maxItems ||\n coreSize + requiredSpace > this.config.coreBudget.maxTotalSize\n ) {\n this.demoteLowValueMemories();\n }\n\n // Move to core\n memory.is_core = true;\n this.coreMemories.set(memory.id, memory);\n this.detailedMemories.delete(memory.id);\n }\n\n /**\n * Demote low-value memories from core\n */\n private demoteLowValueMemories(): void {\n const coreMemories = Array.from(this.coreMemories.values());\n\n // Sort by access count (ascending - least accessed first)\n const sorted = coreMemories.sort((a, b) => a.access_count - b.access_count);\n\n // Demote lowest 1/3\n const demoteCount = Math.max(1, Math.floor(sorted.length / 3));\n for (let i = 0; i < demoteCount; i++) {\n const memory = sorted[i];\n memory.is_core = false;\n this.detailedMemories.set(memory.id, memory);\n this.coreMemories.delete(memory.id);\n }\n }\n\n /**\n * Enforce detailed memory budget\n */\n private async enforceDetailedBudget(): Promise<void> {\n const detailedMemories = Array.from(this.detailedMemories.values());\n const currentSize = detailedMemories.reduce((sum, m) => sum + m.content.length, 0);\n\n if (currentSize <= this.config.detailed.maxSize) {\n return;\n }\n\n // Sort by last accessed (oldest first)\n const sorted = detailedMemories.sort((a, b) => {\n const timeA = (a.last_accessed || a.stored_at).getTime();\n const timeB = (b.last_accessed || b.stored_at).getTime();\n return timeA - timeB;\n });\n\n // Remove oldest until within budget\n let totalSize = currentSize;\n for (const memory of sorted) {\n if (totalSize <= this.config.detailed.maxSize) break;\n\n this.detailedMemories.delete(memory.id);\n totalSize -= memory.content.length;\n }\n }\n\n /**\n * Calculate age in days\n */\n private calculateAgeInDays(date: Date): number {\n const now = new Date();\n const diffMs = now.getTime() - date.getTime();\n return diffMs / (1000 * 60 * 60 * 24);\n }\n}\n","/**\n * Deity - Session Types\n *\n * Types for session persistence and recovery\n */\n\nimport { z } from 'zod';\nimport type { ConversationMessage } from '../conversation/types.js';\nimport type { Memory } from '../memory/types.js';\nimport type { ExecutionStats } from '../engine/types.js';\n\n// ============================================================================\n// Session Data\n// ============================================================================\n\n/**\n * Complete session state\n */\nexport interface SessionData {\n /** Session identifier */\n sessionId: string;\n\n /** Workflow name */\n workflowName: string;\n\n /** Conversation messages */\n messages: ConversationMessage[];\n\n /** Memory entries */\n memories: Memory[];\n\n /** Execution statistics */\n stats: ExecutionStats;\n\n /** Stage outputs (checkpoint data) */\n stageOutputs: Record<string, unknown>;\n\n /** Application state (isolated from AI memory) */\n appState?: Record<string, unknown>;\n\n /** Session metadata */\n metadata: SessionMetadata;\n}\n\n// ============================================================================\n// Session Metadata\n// ============================================================================\n\n/**\n * Session metadata\n */\nexport interface SessionMetadata {\n /** When session was created */\n createdAt: Date;\n\n /** When session was last updated */\n updatedAt: Date;\n\n /** Current stage being executed */\n currentStage?: string;\n\n /** Completed stages */\n completedStages: string[];\n\n /** Failed stages */\n failedStages: string[];\n\n /** Session status */\n status: SessionStatus;\n\n /** User-defined tags */\n tags?: string[];\n\n /** User-defined notes */\n notes?: string;\n}\n\n/**\n * Session status\n */\nexport type SessionStatus =\n | 'active' // Currently running\n | 'paused' // Paused mid-execution\n | 'completed' // Successfully completed\n | 'failed' // Failed permanently\n | 'archived'; // Archived (no longer active)\n\n// ============================================================================\n// Session Configuration\n// ============================================================================\n\n/**\n * Session store configuration\n */\nexport interface SessionConfig {\n /** Base directory for session files */\n directory: string;\n\n /** Auto-save interval in milliseconds (0 = disabled) */\n autoSaveInterval?: number;\n\n /** Keep backup files */\n keepBackups?: boolean;\n\n /** Max backup files to keep */\n maxBackups?: number;\n\n /** Compress session files */\n compress?: boolean;\n}\n\n/**\n * Default session configuration\n */\nexport const DEFAULT_SESSION_CONFIG: Required<SessionConfig> = {\n directory: '.deity/sessions',\n autoSaveInterval: 30000, // 30 seconds\n keepBackups: true,\n maxBackups: 5,\n compress: false\n};\n\n// ============================================================================\n// Session Store Interface\n// ============================================================================\n\n/**\n * Session store interface\n */\nexport interface SessionStore {\n /**\n * Save session data\n */\n save(data: SessionData): Promise<void>;\n\n /**\n * Load session data\n */\n load(sessionId: string): Promise<SessionData | null>;\n\n /**\n * Check if session exists\n */\n exists(sessionId: string): Promise<boolean>;\n\n /**\n * Delete session\n */\n delete(sessionId: string): Promise<void>;\n\n /**\n * List all sessions\n */\n list(): Promise<SessionMetadata[]>;\n\n /**\n * Create backup of session\n */\n backup(sessionId: string): Promise<void>;\n\n /**\n * Restore from backup\n */\n restore(sessionId: string, backupIndex?: number): Promise<SessionData>;\n\n /**\n * Clean up old backups\n */\n cleanupBackups(sessionId: string): Promise<void>;\n}\n\n// ============================================================================\n// Recovery Types\n// ============================================================================\n\n/**\n * Recovery result\n */\nexport interface RecoveryResult {\n /** Recovery succeeded */\n success: boolean;\n\n /** Recovered session data (if successful) */\n data?: SessionData;\n\n /** Recovery errors/warnings */\n errors: string[];\n\n /** Data that couldn't be recovered */\n lost?: Partial<SessionData>;\n}\n\n/**\n * Serialization metadata\n */\nexport interface SerializationMetadata {\n /** Serialization format version */\n version: string;\n\n /** Serialization timestamp */\n timestamp: Date;\n\n /** Fields with special serialization */\n specialFields?: {\n field: string;\n type: 'Date' | 'Set' | 'Map' | 'RegExp';\n }[];\n}\n\n// ============================================================================\n// Paused Session Types (ADR-001)\n// ============================================================================\n\n/**\n * Reason for pausing execution\n */\nexport type PauseReason = 'manual' | 'timeout' | 'error';\n\n/**\n * Paused session state - contains serialized execution context\n */\nexport interface PausedSessionState {\n /** Workflow inputs (arbitrary type) */\n inputs: unknown;\n\n /** Component outputs (componentId -> output) */\n outputs: Record<string, unknown>;\n\n /** Serialized conversation state (optional) */\n conversation?: string;\n\n /** Serialized memory state (optional) */\n memory?: string;\n\n /** Serialized application state (optional) */\n appState?: string;\n\n /** Execution statistics */\n stats: ExecutionStats;\n}\n\n/**\n * Paused session metadata\n */\nexport interface PausedSessionMetadata {\n /** Reason for pausing */\n pauseReason: PauseReason;\n\n /** Whether session can be resumed */\n resumable: boolean;\n\n /** Optional notes about the pause */\n notes?: string;\n}\n\n/**\n * Complete paused session structure\n */\nexport interface PausedSession {\n /** Session identifier */\n sessionId: string;\n\n /** Workflow name */\n workflowName: string;\n\n /** ISO 8601 timestamp when paused */\n pausedAt: string;\n\n /** Deity framework version (for compatibility checks) */\n version: string;\n\n /** Serialized execution state */\n state: PausedSessionState;\n\n /** Pause metadata */\n metadata: PausedSessionMetadata;\n}\n\n// ============================================================================\n// Zod Schemas for Validation (ADR-001)\n// ============================================================================\n\n/**\n * Zod schema for PauseReason\n */\nexport const PauseReasonSchema = z.enum(['manual', 'timeout', 'error']);\n\n/**\n * Zod schema for ExecutionStats (basic validation)\n * Note: Full schema should be imported from engine/types if available\n */\nconst ExecutionStatsSchema = z.object({\n totalToolCalls: z.number().int().min(0),\n totalRetries: z.number().int().min(0),\n}).passthrough(); // Allow additional fields\n\n/**\n * Zod schema for PausedSessionState\n */\nexport const PausedSessionStateSchema = z.object({\n inputs: z.unknown(),\n outputs: z.record(z.string(), z.unknown()),\n conversation: z.string().optional(),\n memory: z.string().optional(),\n appState: z.string().optional(),\n stats: ExecutionStatsSchema,\n});\n\n/**\n * Zod schema for PausedSessionMetadata\n */\nexport const PausedSessionMetadataSchema = z.object({\n pauseReason: PauseReasonSchema,\n resumable: z.boolean(),\n notes: z.string().optional(),\n});\n\n/**\n * Zod schema for PausedSession\n */\nexport const PausedSessionSchema = z.object({\n sessionId: z.string().min(1, 'Session ID cannot be empty'),\n workflowName: z.string().min(1, 'Workflow name cannot be empty'),\n pausedAt: z.string().datetime('Must be ISO 8601 datetime'),\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/, 'Must be semver format (e.g., 1.0.0)'),\n state: PausedSessionStateSchema,\n metadata: PausedSessionMetadataSchema,\n});\n\n/**\n * Infer TypeScript type from Zod schema (for validation)\n */\nexport type PausedSessionValidated = z.infer<typeof PausedSessionSchema>;\n\n","/**\n * Deity - Session Serializer\n *\n * Handles serialization/deserialization of complex types (Date, Set, Map)\n */\n\nimport type { SessionData, SerializationMetadata } from './types.js';\n\n// ============================================================================\n// Type Markers\n// ============================================================================\n\nconst TYPE_MARKERS = {\n DATE: '__deity_date__',\n SET: '__deity_set__',\n MAP: '__deity_map__',\n REGEXP: '__deity_regexp__'\n} as const;\n\n/**\n * Serialized value wrapper\n */\ninterface SerializedValue {\n __type: string;\n value: unknown;\n}\n\n// ============================================================================\n// Serializer\n// ============================================================================\n\n/**\n * Session serializer\n */\nexport class SessionSerializer {\n private metadata: SerializationMetadata;\n\n constructor() {\n this.metadata = {\n version: '1.0.0',\n timestamp: new Date(),\n specialFields: []\n };\n }\n\n /**\n * Serialize session data to JSON-safe object\n */\n serialize(data: SessionData): { data: unknown; metadata: SerializationMetadata } {\n this.metadata.timestamp = new Date();\n this.metadata.specialFields = [];\n\n const serialized = this.serializeValue(data, '');\n\n return {\n data: serialized,\n metadata: this.metadata\n };\n }\n\n /**\n * Deserialize session data from JSON-safe object\n */\n deserialize(data: unknown, _metadata?: SerializationMetadata): SessionData {\n return this.deserializeValue(data) as SessionData;\n }\n\n /**\n * Serialize any value\n */\n private serializeValue(value: unknown, path: string): unknown {\n // Null/undefined\n if (value === null || value === undefined) {\n return value;\n }\n\n // Date\n if (value instanceof Date) {\n this.metadata.specialFields?.push({ field: path, type: 'Date' });\n return {\n __type: TYPE_MARKERS.DATE,\n value: value.toISOString()\n } as SerializedValue;\n }\n\n // Set\n if (value instanceof Set) {\n this.metadata.specialFields?.push({ field: path, type: 'Set' });\n return {\n __type: TYPE_MARKERS.SET,\n value: Array.from(value).map((item, i) =>\n this.serializeValue(item, `${path}[${i}]`)\n )\n } as SerializedValue;\n }\n\n // Map\n if (value instanceof Map) {\n this.metadata.specialFields?.push({ field: path, type: 'Map' });\n return {\n __type: TYPE_MARKERS.MAP,\n value: Array.from(value.entries()).map(([k, v], i) => [\n this.serializeValue(k, `${path}.key[${i}]`),\n this.serializeValue(v, `${path}.value[${i}]`)\n ])\n } as SerializedValue;\n }\n\n // RegExp\n if (value instanceof RegExp) {\n this.metadata.specialFields?.push({ field: path, type: 'RegExp' });\n return {\n __type: TYPE_MARKERS.REGEXP,\n value: {\n source: value.source,\n flags: value.flags\n }\n } as SerializedValue;\n }\n\n // Array\n if (Array.isArray(value)) {\n return value.map((item, i) =>\n this.serializeValue(item, `${path}[${i}]`)\n );\n }\n\n // Object\n if (typeof value === 'object') {\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n result[key] = this.serializeValue(val, path ? `${path}.${key}` : key);\n }\n return result;\n }\n\n // Primitive\n return value;\n }\n\n /**\n * Deserialize any value\n */\n private deserializeValue(value: unknown): unknown {\n // Null/undefined\n if (value === null || value === undefined) {\n return value;\n }\n\n // Array\n if (Array.isArray(value)) {\n return value.map(item => this.deserializeValue(item));\n }\n\n // Object\n if (typeof value === 'object') {\n const obj = value as Record<string, unknown>;\n\n // Check for type marker\n if ('__type' in obj && typeof obj.__type === 'string') {\n return this.deserializeSpecialType(obj as unknown as SerializedValue);\n }\n\n // Regular object\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(obj)) {\n result[key] = this.deserializeValue(val);\n }\n return result;\n }\n\n // Primitive\n return value;\n }\n\n /**\n * Deserialize special type\n */\n private deserializeSpecialType(value: SerializedValue): unknown {\n switch (value.__type) {\n case TYPE_MARKERS.DATE:\n return new Date(value.value as string);\n\n case TYPE_MARKERS.SET:\n return new Set(\n (value.value as unknown[]).map(item => this.deserializeValue(item))\n );\n\n case TYPE_MARKERS.MAP:\n return new Map(\n (value.value as [unknown, unknown][]).map(([k, v]) => [\n this.deserializeValue(k),\n this.deserializeValue(v)\n ])\n );\n\n case TYPE_MARKERS.REGEXP:\n const { source, flags } = value.value as { source: string; flags: string };\n return new RegExp(source, flags);\n\n default:\n // Unknown type - return as-is\n return value;\n }\n }\n}\n\n// ============================================================================\n// Utility Functions\n// ============================================================================\n\n/**\n * Create serializer instance\n */\nexport function createSerializer(): SessionSerializer {\n return new SessionSerializer();\n}\n\n/**\n * Quick serialize\n */\nexport function serialize(data: SessionData): string {\n const serializer = createSerializer();\n const { data: serialized, metadata } = serializer.serialize(data);\n return JSON.stringify({ data: serialized, metadata }, null, 2);\n}\n\n/**\n * Quick deserialize\n */\nexport function deserialize(json: string): SessionData {\n const parsed = JSON.parse(json);\n const serializer = createSerializer();\n return serializer.deserialize(parsed.data, parsed.metadata);\n}\n\n/**\n * Validate serialized data\n */\nexport function validateSerialized(json: string): { valid: boolean; errors: string[] } {\n const errors: string[] = [];\n\n try {\n const parsed = JSON.parse(json);\n\n // Check structure\n if (!parsed.data) {\n errors.push('Missing data field');\n }\n\n if (!parsed.metadata) {\n errors.push('Missing metadata field');\n }\n\n // Check metadata\n if (parsed.metadata) {\n if (!parsed.metadata.version) {\n errors.push('Missing metadata.version');\n }\n if (!parsed.metadata.timestamp) {\n errors.push('Missing metadata.timestamp');\n }\n }\n\n // Try to deserialize\n if (errors.length === 0) {\n deserialize(json);\n }\n } catch (error) {\n errors.push(`Parse error: ${error instanceof Error ? error.message : String(error)}`);\n }\n\n return {\n valid: errors.length === 0,\n errors\n };\n}\n","/**\n * Deity - FileSystem Session Store\n *\n * Single-file JSON storage for session data\n */\n\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport type {\n SessionStore,\n SessionData,\n SessionConfig,\n SessionMetadata,\n RecoveryResult\n} from './types.js';\nimport { DEFAULT_SESSION_CONFIG } from './types.js';\nimport { SessionSerializer } from './serializer.js';\n\n// ============================================================================\n// FileSystem Session Store\n// ============================================================================\n\n/**\n * FileSystem-based session store\n */\nexport class FileSystemSessionStore implements SessionStore {\n private config: Required<SessionConfig>;\n private serializer: SessionSerializer;\n private autoSaveTimers: Map<string, NodeJS.Timeout> = new Map();\n\n constructor(config?: SessionConfig) {\n this.config = {\n ...DEFAULT_SESSION_CONFIG,\n ...config\n };\n this.serializer = new SessionSerializer();\n }\n\n /**\n * Initialize store (create directories)\n */\n async init(): Promise<void> {\n await fs.mkdir(this.config.directory, { recursive: true });\n\n // Create backups directory if enabled\n if (this.config.keepBackups) {\n const backupsDir = path.join(this.config.directory, 'backups');\n await fs.mkdir(backupsDir, { recursive: true });\n }\n }\n\n // ============================================================================\n // Core Operations\n // ============================================================================\n\n /**\n * Save session data\n */\n async save(data: SessionData): Promise<void> {\n // Update metadata\n data.metadata.updatedAt = new Date();\n\n // Serialize\n const { data: serialized, metadata } = this.serializer.serialize(data);\n\n // Write to file\n const filePath = this.getSessionPath(data.sessionId);\n const content = JSON.stringify({ data: serialized, metadata }, null, 2);\n\n await fs.writeFile(filePath, content, 'utf-8');\n\n // Create backup if enabled\n if (this.config.keepBackups) {\n await this.backup(data.sessionId);\n await this.cleanupBackups(data.sessionId);\n }\n\n // Schedule auto-save if enabled\n if (this.config.autoSaveInterval > 0) {\n this.scheduleAutoSave(data);\n }\n }\n\n /**\n * Load session data\n */\n async load(sessionId: string): Promise<SessionData | null> {\n try {\n const filePath = this.getSessionPath(sessionId);\n const content = await fs.readFile(filePath, 'utf-8');\n const parsed = JSON.parse(content);\n\n return this.serializer.deserialize(parsed.data, parsed.metadata);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return null;\n }\n throw error;\n }\n }\n\n /**\n * Check if session exists\n */\n async exists(sessionId: string): Promise<boolean> {\n try {\n const filePath = this.getSessionPath(sessionId);\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Delete session\n */\n async delete(sessionId: string): Promise<void> {\n // Cancel auto-save\n const timer = this.autoSaveTimers.get(sessionId);\n if (timer) {\n clearTimeout(timer);\n this.autoSaveTimers.delete(sessionId);\n }\n\n // Delete main file\n const filePath = this.getSessionPath(sessionId);\n try {\n await fs.unlink(filePath);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n\n // Delete backups\n if (this.config.keepBackups) {\n const backupsDir = this.getBackupsDir(sessionId);\n try {\n await fs.rm(backupsDir, { recursive: true, force: true });\n } catch {\n // Ignore errors\n }\n }\n }\n\n /**\n * List all sessions\n */\n async list(): Promise<SessionMetadata[]> {\n try {\n const files = await fs.readdir(this.config.directory);\n const sessions: SessionMetadata[] = [];\n\n for (const file of files) {\n if (file.endsWith('.json') && file !== 'backups') {\n const sessionId = file.replace('.json', '');\n const data = await this.load(sessionId);\n if (data) {\n sessions.push(data.metadata);\n }\n }\n }\n\n return sessions.sort((a, b) =>\n b.updatedAt.getTime() - a.updatedAt.getTime()\n );\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return [];\n }\n throw error;\n }\n }\n\n // ============================================================================\n // Backup Operations\n // ============================================================================\n\n /**\n * Create backup of session\n */\n async backup(sessionId: string): Promise<void> {\n if (!this.config.keepBackups) {\n return;\n }\n\n const sourcePath = this.getSessionPath(sessionId);\n const backupsDir = this.getBackupsDir(sessionId);\n\n // Create backups directory\n await fs.mkdir(backupsDir, { recursive: true });\n\n // Generate backup filename with timestamp\n const timestamp = new Date().toISOString().replace(/:/g, '-');\n const backupPath = path.join(backupsDir, `${timestamp}.json`);\n\n // Copy file\n try {\n await fs.copyFile(sourcePath, backupPath);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n }\n\n /**\n * Restore from backup\n */\n async restore(sessionId: string, backupIndex: number = 0): Promise<SessionData> {\n const backupsDir = this.getBackupsDir(sessionId);\n\n // List backups\n const backups = await fs.readdir(backupsDir);\n const sortedBackups = backups\n .filter(f => f.endsWith('.json'))\n .sort()\n .reverse(); // Most recent first\n\n if (backupIndex >= sortedBackups.length) {\n throw new Error(`Backup index ${backupIndex} out of range (max: ${sortedBackups.length - 1})`);\n }\n\n // Read backup\n const backupPath = path.join(backupsDir, sortedBackups[backupIndex]);\n const content = await fs.readFile(backupPath, 'utf-8');\n const parsed = JSON.parse(content);\n\n return this.serializer.deserialize(parsed.data, parsed.metadata);\n }\n\n /**\n * Clean up old backups\n */\n async cleanupBackups(sessionId: string): Promise<void> {\n if (!this.config.keepBackups) {\n return;\n }\n\n const backupsDir = this.getBackupsDir(sessionId);\n\n try {\n // List backups\n const backups = await fs.readdir(backupsDir);\n const sortedBackups = backups\n .filter(f => f.endsWith('.json'))\n .sort()\n .reverse(); // Most recent first\n\n // Delete old backups\n const toDelete = sortedBackups.slice(this.config.maxBackups);\n for (const backup of toDelete) {\n const backupPath = path.join(backupsDir, backup);\n await fs.unlink(backupPath);\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n }\n\n // ============================================================================\n // Recovery Operations\n // ============================================================================\n\n /**\n * Attempt to recover corrupted session\n */\n async recover(sessionId: string): Promise<RecoveryResult> {\n const errors: string[] = [];\n let data: SessionData | undefined;\n let lost: Partial<SessionData> | undefined;\n\n try {\n // Try to load normally\n const loaded = await this.load(sessionId);\n if (loaded) {\n return { success: true, data: loaded, errors: [] };\n }\n } catch (error) {\n errors.push(`Failed to load session: ${error instanceof Error ? error.message : String(error)}`);\n }\n\n // Try to recover from backup\n if (this.config.keepBackups) {\n try {\n data = await this.restore(sessionId, 0);\n errors.push('Recovered from most recent backup');\n return { success: true, data, errors };\n } catch (error) {\n errors.push(`Failed to restore from backup: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n // Try to parse corrupted file\n try {\n const filePath = this.getSessionPath(sessionId);\n const content = await fs.readFile(filePath, 'utf-8');\n const parsed = JSON.parse(content);\n\n // Partial recovery\n lost = {};\n const recovered: Partial<SessionData> = {};\n\n // Try to recover each field\n const fields: (keyof SessionData)[] = [\n 'sessionId',\n 'workflowName',\n 'messages',\n 'memories',\n 'stats',\n 'stageOutputs',\n 'metadata'\n ];\n\n for (const field of fields) {\n try {\n if (parsed.data?.[field]) {\n recovered[field] = this.serializer.deserialize(parsed.data[field]) as never;\n } else {\n lost[field] = undefined as never;\n }\n } catch {\n lost[field] = parsed.data?.[field] as never;\n }\n }\n\n if (Object.keys(recovered).length > 0) {\n data = recovered as SessionData;\n errors.push('Partial recovery successful');\n return { success: true, data, errors, lost };\n }\n } catch (error) {\n errors.push(`Failed to parse corrupted file: ${error instanceof Error ? error.message : String(error)}`);\n }\n\n return { success: false, errors };\n }\n\n // ============================================================================\n // Helper Methods\n // ============================================================================\n\n /**\n * Get session file path\n */\n private getSessionPath(sessionId: string): string {\n return path.join(this.config.directory, `${sessionId}.json`);\n }\n\n /**\n * Get backups directory for session\n */\n private getBackupsDir(sessionId: string): string {\n return path.join(this.config.directory, 'backups', sessionId);\n }\n\n /**\n * Schedule auto-save\n */\n private scheduleAutoSave(data: SessionData): void {\n // Cancel existing timer\n const existingTimer = this.autoSaveTimers.get(data.sessionId);\n if (existingTimer) {\n clearTimeout(existingTimer);\n }\n\n // Schedule new timer\n const timer = setTimeout(async () => {\n try {\n await this.save(data);\n } catch (error) {\n // Auto-save failed silently - session data remains at last successful save point\n }\n }, this.config.autoSaveInterval);\n\n this.autoSaveTimers.set(data.sessionId, timer);\n }\n\n /**\n * Cleanup (cancel all auto-save timers)\n */\n cleanup(): void {\n for (const timer of this.autoSaveTimers.values()) {\n clearTimeout(timer);\n }\n this.autoSaveTimers.clear();\n }\n}\n\n// ============================================================================\n// Factory Function\n// ============================================================================\n\n/**\n * Create FileSystem session store\n */\nexport function createSessionStore(config?: SessionConfig): FileSystemSessionStore {\n return new FileSystemSessionStore(config);\n}\n","/**\n * Deity - In-Memory Stores\n *\n * Simple in-memory implementations for testing\n */\n\nimport type { StateStore, TraceLogger, TraceEntry } from './types.js';\n\n// ============================================================================\n// In-Memory State Store\n// ============================================================================\n\n/**\n * Simple in-memory state store\n */\nexport class InMemoryStore implements StateStore {\n private data = new Map<string, unknown>();\n\n async get(key: string): Promise<unknown> {\n return this.data.get(key);\n }\n\n async set(key: string, value: unknown): Promise<void> {\n this.data.set(key, value);\n }\n\n async has(key: string): Promise<boolean> {\n return this.data.has(key);\n }\n\n async delete(key: string): Promise<void> {\n this.data.delete(key);\n }\n\n async clear(): Promise<void> {\n this.data.clear();\n }\n\n // Extra methods beyond StateStore interface\n size(): number {\n return this.data.size;\n }\n\n keys(): string[] {\n return Array.from(this.data.keys());\n }\n\n entries(): [string, unknown][] {\n return Array.from(this.data.entries());\n }\n\n values(): unknown[] {\n return Array.from(this.data.values());\n }\n}\n\n// ============================================================================\n// In-Memory Trace Logger\n// ============================================================================\n\n/**\n * Simple in-memory trace logger\n */\nexport class InMemoryTrace implements TraceLogger {\n private entries: TraceEntry[] = [];\n\n async log(entry: TraceEntry): Promise<void> {\n this.entries.push(entry);\n }\n\n async getEntries(): Promise<TraceEntry[]> {\n return [...this.entries];\n }\n\n // Extra methods for testing\n clear(): void {\n this.entries = [];\n }\n\n count(): number {\n return this.entries.length;\n }\n\n getEntriesByType(type: TraceEntry['type']): TraceEntry[] {\n return this.entries.filter(e => e.type === type);\n }\n}\n","/**\n * Deity - Execution Statistics\n *\n * Tracks execution statistics for dynamic stop conditions\n * - Tool call tracking by type\n * - Recent tool calls (sliding window)\n * - Retry attempts\n * - Validation errors\n * - Elapsed time\n */\n\nimport type { ExecutionStats, ToolCost } from './types.js';\n\n// ============================================================================\n// Stats Manager\n// ============================================================================\n\n/**\n * Manages execution statistics during workflow execution\n */\nexport class StatsManager {\n private stats: ExecutionStats;\n private startTime: number;\n private recentToolsWindow: number;\n\n constructor(options: { recentToolsWindow?: number } = {}) {\n this.recentToolsWindow = options.recentToolsWindow ?? 10;\n this.startTime = Date.now();\n\n this.stats = {\n totalToolCalls: 0,\n toolCallsByType: {\n expensive: 0,\n cheap: 0,\n delivery: 0\n },\n recentToolCalls: [],\n totalRetries: 0,\n validationErrors: 0,\n elapsedTimeMs: 0,\n currentPhase: undefined\n };\n }\n\n /**\n * Record a tool call\n */\n recordToolCall(toolName: string, cost: ToolCost): void {\n // Increment total\n this.stats.totalToolCalls++;\n\n // Increment by type\n this.stats.toolCallsByType[cost]++;\n\n // Add to recent tools (sliding window)\n this.stats.recentToolCalls.push(toolName);\n if (this.stats.recentToolCalls.length > this.recentToolsWindow) {\n this.stats.recentToolCalls.shift();\n }\n\n // Update elapsed time\n this.updateElapsedTime();\n }\n\n /**\n * Record a retry attempt\n */\n recordRetry(): void {\n this.stats.totalRetries++;\n this.updateElapsedTime();\n }\n\n /**\n * Record validation errors\n */\n recordValidationError(errorCount: number = 1): void {\n this.stats.validationErrors += errorCount;\n this.updateElapsedTime();\n }\n\n /**\n * Set current phase\n */\n setPhase(phase: 'main' | 'delivery'): void {\n this.stats.currentPhase = phase;\n }\n\n /**\n * Update elapsed time\n */\n private updateElapsedTime(): void {\n this.stats.elapsedTimeMs = Date.now() - this.startTime;\n }\n\n /**\n * Get current stats (immutable copy)\n */\n getStats(): ExecutionStats {\n this.updateElapsedTime();\n return {\n ...this.stats,\n toolCallsByType: { ...this.stats.toolCallsByType },\n recentToolCalls: [...this.stats.recentToolCalls]\n };\n }\n\n /**\n * Reset stats\n */\n reset(): void {\n this.startTime = Date.now();\n this.stats = {\n totalToolCalls: 0,\n toolCallsByType: {\n expensive: 0,\n cheap: 0,\n delivery: 0\n },\n recentToolCalls: [],\n totalRetries: 0,\n validationErrors: 0,\n elapsedTimeMs: 0,\n currentPhase: undefined\n };\n }\n\n /**\n * Get stats summary string\n */\n getSummary(): string {\n const stats = this.getStats();\n return [\n `Total Tool Calls: ${stats.totalToolCalls}`,\n ` Expensive: ${stats.toolCallsByType.expensive}`,\n ` Cheap: ${stats.toolCallsByType.cheap}`,\n ` Delivery: ${stats.toolCallsByType.delivery}`,\n `Recent Tools: ${stats.recentToolCalls.slice(-5).join(', ')}`,\n `Retries: ${stats.totalRetries}`,\n `Validation Errors: ${stats.validationErrors}`,\n `Elapsed: ${(stats.elapsedTimeMs / 1000).toFixed(2)}s`,\n `Phase: ${stats.currentPhase ?? 'N/A'}`\n ].join('\\n');\n }\n}\n\n// ============================================================================\n// Stats Analyzer\n// ============================================================================\n\n/**\n * Analyzes execution statistics for insights\n */\nexport class StatsAnalyzer {\n /**\n * Check if in delivery phase based on stats\n */\n static isInDeliveryPhase(stats: ExecutionStats, threshold: number = 100): boolean {\n return stats.toolCallsByType.expensive >= threshold;\n }\n\n /**\n * Check if using delivery tools recently\n */\n static isUsingDeliveryTools(\n stats: ExecutionStats,\n toolCosts: Record<string, ToolCost>,\n windowSize: number = 5\n ): boolean {\n const recentWindow = stats.recentToolCalls.slice(-windowSize);\n return recentWindow.some(toolName => toolCosts[toolName] === 'delivery');\n }\n\n /**\n * Calculate tool diversity (0-1)\n */\n static calculateToolDiversity(stats: ExecutionStats): number {\n const uniqueTools = new Set(stats.recentToolCalls);\n if (stats.recentToolCalls.length === 0) return 0;\n return uniqueTools.size / stats.recentToolCalls.length;\n }\n\n /**\n * Get tool usage distribution\n */\n static getToolDistribution(stats: ExecutionStats): Record<string, number> {\n const distribution: Record<string, number> = {};\n for (const tool of stats.recentToolCalls) {\n distribution[tool] = (distribution[tool] ?? 0) + 1;\n }\n return distribution;\n }\n\n /**\n * Calculate retry rate\n */\n static calculateRetryRate(stats: ExecutionStats): number {\n if (stats.totalRetries === 0) return 0;\n return stats.totalRetries / (stats.totalRetries + 1); // +1 for initial attempt\n }\n\n /**\n * Estimate remaining time based on current progress\n */\n static estimateRemainingTime(\n stats: ExecutionStats,\n targetToolCalls: number\n ): number {\n if (stats.totalToolCalls === 0) return 0;\n\n const avgTimePerTool = stats.elapsedTimeMs / stats.totalToolCalls;\n const remainingCalls = Math.max(0, targetToolCalls - stats.totalToolCalls);\n\n return avgTimePerTool * remainingCalls;\n }\n}\n\n// ============================================================================\n// Stats Formatter\n// ============================================================================\n\n/**\n * Format stats for display\n */\nexport class StatsFormatter {\n /**\n * Format stats as JSON\n */\n static toJSON(stats: ExecutionStats): string {\n return JSON.stringify(stats, null, 2);\n }\n\n /**\n * Format stats as table\n */\n static toTable(stats: ExecutionStats): string {\n const rows = [\n ['Metric', 'Value'],\n ['---', '---'],\n ['Total Tool Calls', stats.totalToolCalls.toString()],\n ['Expensive Tools', stats.toolCallsByType.expensive.toString()],\n ['Cheap Tools', stats.toolCallsByType.cheap.toString()],\n ['Delivery Tools', stats.toolCallsByType.delivery.toString()],\n ['Total Retries', stats.totalRetries.toString()],\n ['Validation Errors', stats.validationErrors.toString()],\n ['Elapsed Time', `${(stats.elapsedTimeMs / 1000).toFixed(2)}s`],\n ['Current Phase', stats.currentPhase ?? 'N/A']\n ];\n\n const colWidths = [\n Math.max(...rows.map(r => r[0].length)),\n Math.max(...rows.map(r => r[1].length))\n ];\n\n return rows.map(([col1, col2]) =>\n `| ${col1.padEnd(colWidths[0])} | ${col2.padEnd(colWidths[1])} |`\n ).join('\\n');\n }\n\n /**\n * Format stats as compact summary\n */\n static toCompact(stats: ExecutionStats): string {\n return [\n `Tools: ${stats.totalToolCalls} (E:${stats.toolCallsByType.expensive} C:${stats.toolCallsByType.cheap} D:${stats.toolCallsByType.delivery})`,\n `Retries: ${stats.totalRetries}`,\n `Errors: ${stats.validationErrors}`,\n `Time: ${(stats.elapsedTimeMs / 1000).toFixed(1)}s`,\n `Phase: ${stats.currentPhase ?? 'N/A'}`\n ].join(' | ');\n }\n\n /**\n * Format recent tools as list\n */\n static formatRecentTools(stats: ExecutionStats, limit: number = 10): string {\n const recent = stats.recentToolCalls.slice(-limit);\n if (recent.length === 0) return 'No recent tools';\n\n return recent.map((tool, i) => `${i + 1}. ${tool}`).join('\\n');\n }\n}\n\n// ============================================================================\n// Stats Snapshot\n// ============================================================================\n\n/**\n * Create immutable snapshot of stats\n */\nexport function createStatsSnapshot(stats: ExecutionStats): Readonly<ExecutionStats> {\n return Object.freeze({\n ...stats,\n toolCallsByType: Object.freeze({ ...stats.toolCallsByType }),\n recentToolCalls: Object.freeze([...stats.recentToolCalls])\n }) as Readonly<ExecutionStats>;\n}\n\n/**\n * Compare two stats snapshots\n */\nexport function compareStats(\n before: ExecutionStats,\n after: ExecutionStats\n): {\n toolCallsDelta: number;\n retriesDelta: number;\n errorsDelta: number;\n timeDelta: number;\n phaseChanged: boolean;\n} {\n return {\n toolCallsDelta: after.totalToolCalls - before.totalToolCalls,\n retriesDelta: after.totalRetries - before.totalRetries,\n errorsDelta: after.validationErrors - before.validationErrors,\n timeDelta: after.elapsedTimeMs - before.elapsedTimeMs,\n phaseChanged: before.currentPhase !== after.currentPhase\n };\n}\n\n// All exports are inline above - no need for re-export block\n","/**\n * Deity - Context Factory\n *\n * Factory functions for creating ExecutionContext instances\n */\n\nimport { ExecutionContext } from './context.js';\nimport type { StateStore, TraceLogger, ExecutionStats, UIUpdateBridge } from '../engine/types.js';\nimport { ConversationManager } from '../conversation/manager.js';\nimport { LimoMemoryManager } from '../memory/manager.js';\nimport { FileSystemSessionStore } from '../session/store.js';\nimport { InMemoryStore } from '../engine/stores.js';\nimport type { ConversationConfig } from '../conversation/types.js';\nimport type { MemoryConfig } from '../memory/types.js';\nimport type { SessionConfig } from '../session/types.js';\nimport { StatsManager } from '../engine/stats.js';\n\n// ============================================================================\n// Context Configuration\n// ============================================================================\n\n/**\n * Configuration for creating ExecutionContext\n */\nexport interface ContextConfig<I = unknown> {\n /** Component inputs */\n inputs: I;\n\n /** Previous stage outputs */\n previousOutputs?: Record<string, unknown>;\n\n /** State store (required) */\n store: StateStore;\n\n /** Trace logger (required) */\n trace: TraceLogger;\n\n /** Execution stats (optional, will create if not provided) */\n stats?: ExecutionStats;\n\n /** Enable conversation manager */\n enableConversation?: boolean | ConversationConfig;\n\n /** Enable memory manager */\n enableMemory?: boolean | MemoryConfig;\n\n /** Enable session store */\n enableSession?: boolean | SessionConfig;\n\n /** Enable application state store (isolated from AI memory) */\n enableAppState?: boolean | StateStore;\n\n /** UI update bridge */\n ui?: UIUpdateBridge;\n\n /** Current stage ID */\n currentStageId?: string;\n\n /** Loop iteration info */\n loop?: {\n iteration: number;\n maxIterations: number;\n history?: unknown[];\n };\n}\n\n// ============================================================================\n// Factory Functions\n// ============================================================================\n\n/**\n * Create minimal ExecutionContext (no enhancements)\n */\nexport function createMinimalContext<I = unknown>(\n inputs: I,\n store: StateStore,\n trace: TraceLogger,\n previousOutputs: Record<string, unknown> = {}\n): ExecutionContext<I> {\n const statsManager = new StatsManager();\n\n return new ExecutionContext({\n inputs,\n previousOutputs,\n store,\n trace,\n stats: statsManager.getStats()\n });\n}\n\n/**\n * Create ExecutionContext with full enhancements\n */\nexport async function createEnhancedContext<I = unknown>(\n config: ContextConfig<I>\n): Promise<ExecutionContext<I>> {\n // Create stats manager if not provided\n const statsManager = config.stats\n ? undefined\n : new StatsManager();\n\n // Create conversation manager if enabled\n let conversation: ConversationManager | undefined;\n if (config.enableConversation) {\n const conversationConfig = typeof config.enableConversation === 'object'\n ? config.enableConversation\n : undefined;\n conversation = new ConversationManager(conversationConfig);\n }\n\n // Create memory manager if enabled\n let memory: LimoMemoryManager | undefined;\n if (config.enableMemory) {\n const memoryConfig = typeof config.enableMemory === 'object'\n ? config.enableMemory\n : undefined;\n memory = new LimoMemoryManager(memoryConfig);\n }\n\n // Create session store if enabled\n let session: FileSystemSessionStore | undefined;\n if (config.enableSession) {\n const sessionConfig = typeof config.enableSession === 'object'\n ? config.enableSession\n : undefined;\n session = new FileSystemSessionStore(sessionConfig);\n await session.init();\n }\n\n // Create application state store if enabled\n let appState: StateStore | undefined;\n if (config.enableAppState) {\n if (typeof config.enableAppState === 'boolean') {\n // Create default InMemoryStore\n appState = new InMemoryStore();\n } else {\n // Use provided StateStore instance\n appState = config.enableAppState;\n }\n }\n\n return new ExecutionContext({\n inputs: config.inputs,\n previousOutputs: config.previousOutputs ?? {},\n store: config.store,\n trace: config.trace,\n stats: config.stats ?? statsManager!.getStats(),\n conversation,\n memory,\n session,\n appState,\n ui: config.ui,\n currentStageId: config.currentStageId,\n iteration: config.loop?.iteration,\n maxIterations: config.loop?.maxIterations,\n iterationHistory: config.loop?.history\n });\n}\n\n/**\n * Create ExecutionContext with conversation only\n */\nexport function createContextWithConversation<I = unknown>(\n inputs: I,\n store: StateStore,\n trace: TraceLogger,\n conversationConfig?: ConversationConfig,\n previousOutputs: Record<string, unknown> = {}\n): ExecutionContext<I> {\n const statsManager = new StatsManager();\n const conversation = new ConversationManager(conversationConfig);\n\n return new ExecutionContext({\n inputs,\n previousOutputs,\n store,\n trace,\n stats: statsManager.getStats(),\n conversation\n });\n}\n\n/**\n * Create ExecutionContext with memory only\n */\nexport function createContextWithMemory<I = unknown>(\n inputs: I,\n store: StateStore,\n trace: TraceLogger,\n memoryConfig?: MemoryConfig,\n previousOutputs: Record<string, unknown> = {}\n): ExecutionContext<I> {\n const statsManager = new StatsManager();\n const memory = new LimoMemoryManager(memoryConfig);\n\n return new ExecutionContext({\n inputs,\n previousOutputs,\n store,\n trace,\n stats: statsManager.getStats(),\n memory\n });\n}\n\n/**\n * Create ExecutionContext with session only\n */\nexport async function createContextWithSession<I = unknown>(\n inputs: I,\n store: StateStore,\n trace: TraceLogger,\n sessionConfig?: SessionConfig,\n previousOutputs: Record<string, unknown> = {}\n): Promise<ExecutionContext<I>> {\n const statsManager = new StatsManager();\n const session = new FileSystemSessionStore(sessionConfig);\n await session.init();\n\n return new ExecutionContext({\n inputs,\n previousOutputs,\n store,\n trace,\n stats: statsManager.getStats(),\n session\n });\n}\n\n// ============================================================================\n// Builder Pattern\n// ============================================================================\n\n/**\n * Context builder for fluent API\n */\nexport class ContextBuilder<I = unknown> {\n private config: Partial<ContextConfig<I>> = {};\n\n /**\n * Set inputs\n */\n withInputs(inputs: I): this {\n this.config.inputs = inputs;\n return this;\n }\n\n /**\n * Set previous outputs\n */\n withPreviousOutputs(outputs: Record<string, unknown>): this {\n this.config.previousOutputs = outputs;\n return this;\n }\n\n /**\n * Set store\n */\n withStore(store: StateStore): this {\n this.config.store = store;\n return this;\n }\n\n /**\n * Set trace logger\n */\n withTrace(trace: TraceLogger): this {\n this.config.trace = trace;\n return this;\n }\n\n /**\n * Set stats\n */\n withStats(stats: ExecutionStats): this {\n this.config.stats = stats;\n return this;\n }\n\n /**\n * Enable conversation\n */\n withConversation(config?: ConversationConfig): this {\n this.config.enableConversation = config ?? true;\n return this;\n }\n\n /**\n * Enable memory\n */\n withMemory(config?: MemoryConfig): this {\n this.config.enableMemory = config ?? true;\n return this;\n }\n\n /**\n * Enable session\n */\n withSession(config?: SessionConfig): this {\n this.config.enableSession = config ?? true;\n return this;\n }\n\n /**\n * Set UI bridge\n */\n withUI(ui: UIUpdateBridge): this {\n this.config.ui = ui;\n return this;\n }\n\n /**\n * Enable application state store\n */\n withAppState(storeOrTrue?: StateStore | boolean): this {\n this.config.enableAppState = storeOrTrue ?? true;\n return this;\n }\n\n /**\n * Set current stage ID\n */\n withStageId(stageId: string): this {\n this.config.currentStageId = stageId;\n return this;\n }\n\n /**\n * Set loop info\n */\n withLoop(iteration: number, maxIterations: number, history?: unknown[]): this {\n this.config.loop = { iteration, maxIterations, history };\n return this;\n }\n\n /**\n * Build the context\n */\n async build(): Promise<ExecutionContext<I>> {\n if (!this.config.inputs) {\n throw new Error('Context inputs are required');\n }\n if (!this.config.store) {\n throw new Error('Context store is required');\n }\n if (!this.config.trace) {\n throw new Error('Context trace logger is required');\n }\n\n return createEnhancedContext(this.config as ContextConfig<I>);\n }\n}\n\n/**\n * Create a new context builder\n */\nexport function contextBuilder<I = unknown>(): ContextBuilder<I> {\n return new ContextBuilder<I>();\n}\n","/**\n * Deity - Workflow Runner\n *\n * Orchestrates workflow execution with checkpoint/resume\n */\n\nimport type {\n WorkflowConfig,\n ExecutionNode,\n AgentComponent,\n ExecutionContext as IExecutionContext,\n LLMAdapter,\n GenerationConfig\n} from './types.js';\nimport type { WorkflowNode } from '../ast/types.js';\nimport { ExecutionContext } from '../context/context.js';\nimport { executeComponent, type ComponentExecutionResult } from './executor.js';\nimport { createEnhancedContext } from '../context/factory.js';\nimport { InMemoryStore } from './stores.js';\nimport { InMemoryTrace } from './traces.js';\nimport { compileWorkflow } from '../compiler/compile-workflow.js';\n\n// ============================================================================\n// Workflow Execution Result\n// ============================================================================\n\n/**\n * Result from workflow execution\n */\nexport interface WorkflowExecutionResult {\n /** Final output from workflow */\n output: unknown;\n\n /** All stage outputs */\n stageOutputs: Record<string, unknown>;\n\n /** Execution succeeded */\n success: boolean;\n\n /** Total execution time (ms) */\n duration: number;\n\n /** Component results */\n componentResults: Record<string, ComponentExecutionResult<unknown>>;\n}\n\n// ============================================================================\n// Workflow Runner\n// ============================================================================\n\n/**\n * Execute a workflow\n */\nexport async function runWorkflow<I, O>(\n config: WorkflowConfig,\n inputs: I\n): Promise<O> {\n // Create store and trace\n const store = config.state?.store ?? new InMemoryStore();\n const trace = new InMemoryTrace();\n\n // Create initial context\n const ctx = await createEnhancedContext({\n inputs,\n store,\n trace,\n enableConversation: config.enhancements?.conversation !== undefined,\n enableMemory: config.enhancements?.memory !== undefined,\n enableSession: config.enhancements?.session !== undefined,\n enableAppState: config.enhancements?.appState,\n ui: config.enhancements?.ui\n });\n\n // Execute graph\n const result = await executeNode(\n config.graph,\n ctx,\n config.defaultModel?.adapter,\n config.defaultModel?.config\n );\n\n return result as O;\n}\n\n/**\n * Execute a TSX workflow\n *\n * Convenience function that compiles a WorkflowNode AST and executes it.\n * This is the recommended way to run TSX-defined workflows.\n *\n * @param workflowAST - Workflow AST node (created by Workflow component)\n * @param inputs - Workflow inputs\n * @returns Workflow output\n *\n * @example\n * ```typescript\n * const workflow = Workflow({\n * name: 'my-workflow',\n * defaultModel: { adapter: llmAdapter },\n * children: Sequence({\n * children: [Agent1, Agent2, Agent3]\n * })\n * });\n *\n * const result = await runTSXWorkflow(workflow, { input: 'data' });\n * ```\n *\n * @example With enhancements\n * ```typescript\n * const workflow = Workflow({\n * name: 'enhanced-workflow',\n * defaultModel: { adapter: llmAdapter },\n * enhancements: {\n * conversation: { maxTokens: 8000, pruneThreshold: 6000 },\n * memory: { coreBudget: { maxItems: 10, maxTotalSize: 8192 } }\n * },\n * children: MyAgent\n * });\n *\n * const result = await runTSXWorkflow(workflow, inputs);\n * ```\n */\nexport async function runTSXWorkflow<I, O>(\n workflowAST: WorkflowNode,\n inputs: I\n): Promise<O> {\n // Compile the workflow AST to WorkflowConfig\n const config = compileWorkflow(workflowAST);\n\n // Execute using the standard workflow runner\n return runWorkflow<I, O>(config, inputs);\n}\n\n// ============================================================================\n// Node Execution\n// ============================================================================\n\n/**\n * Execute an execution node\n */\nasync function executeNode(\n node: ExecutionNode,\n ctx: IExecutionContext,\n adapter?: LLMAdapter,\n config?: GenerationConfig\n): Promise<unknown> {\n switch (node.type) {\n case 'step':\n return executeStepNode(node, ctx, adapter, config);\n\n case 'sequence':\n return executeSequenceNode(node, ctx, adapter, config);\n\n case 'parallel':\n return executeParallelNode(node, ctx, adapter, config);\n\n case 'conditional':\n return executeConditionalNode(node, ctx, adapter, config);\n\n case 'loop':\n return executeLoopNode(node, ctx, adapter, config);\n\n case 'foreach':\n return executeForEachNode(node, ctx, adapter, config);\n\n default:\n throw new Error(`Unknown node type: ${(node as ExecutionNode).type}`);\n }\n}\n\n// ============================================================================\n// Step Node\n// ============================================================================\n\n/**\n * Execute a step node (single component)\n */\nasync function executeStepNode(\n node: ExecutionNode,\n ctx: IExecutionContext,\n adapter?: LLMAdapter,\n config?: GenerationConfig\n): Promise<unknown> {\n if (!node.component) {\n throw new Error('Step node missing component');\n }\n\n if (!adapter) {\n // Check if component has its own adapter\n if (node.component.model?.adapter) {\n adapter = node.component.model.adapter;\n config = node.component.model.config;\n } else {\n throw new Error('No LLM adapter provided');\n }\n }\n\n // Execute component\n const result = await executeComponent(\n node.component,\n ctx,\n adapter,\n config\n );\n\n // Update context with output\n if (ctx instanceof ExecutionContext) {\n // Note: We would need to pass this updated context to subsequent nodes\n // For now, we modify previousOutputs directly\n (ctx.previousOutputs as Record<string, unknown>)[node.component.id] = result.output;\n }\n\n return result.output;\n}\n\n// ============================================================================\n// Sequence Node\n// ============================================================================\n\n/**\n * Execute a sequence node (children in order)\n */\nasync function executeSequenceNode(\n node: ExecutionNode,\n ctx: IExecutionContext,\n adapter?: LLMAdapter,\n config?: GenerationConfig\n): Promise<unknown> {\n if (!node.children || node.children.length === 0) {\n throw new Error('Sequence node has no children');\n }\n\n let lastOutput: unknown;\n\n for (const child of node.children) {\n lastOutput = await executeNode(child, ctx, adapter, config);\n }\n\n return lastOutput;\n}\n\n// ============================================================================\n// Parallel Node\n// ============================================================================\n\n/**\n * Execute a parallel node (children concurrently)\n */\nasync function executeParallelNode(\n node: ExecutionNode,\n ctx: IExecutionContext,\n adapter?: LLMAdapter,\n config?: GenerationConfig\n): Promise<unknown[]> {\n if (!node.children || node.children.length === 0) {\n throw new Error('Parallel node has no children');\n }\n\n const results = await Promise.all(\n node.children.map(child => executeNode(child, ctx, adapter, config))\n );\n\n return results;\n}\n\n// ============================================================================\n// Conditional Node\n// ============================================================================\n\n/**\n * Execute a conditional node\n */\nasync function executeConditionalNode(\n node: ExecutionNode,\n ctx: IExecutionContext,\n adapter?: LLMAdapter,\n config?: GenerationConfig\n): Promise<unknown> {\n if (!node.condition) {\n throw new Error('Conditional node missing condition');\n }\n\n if (!node.children || node.children.length === 0) {\n throw new Error('Conditional node has no children');\n }\n\n // Evaluate condition\n const conditionResult = await Promise.resolve(node.condition(ctx));\n\n if (conditionResult) {\n // Execute first child (true branch)\n return executeNode(node.children[0], ctx, adapter, config);\n } else if (node.children.length > 1) {\n // Execute second child (false branch)\n return executeNode(node.children[1], ctx, adapter, config);\n }\n\n return undefined;\n}\n\n// ============================================================================\n// Loop Node\n// ============================================================================\n\n/**\n * Execute a loop node\n */\nasync function executeLoopNode(\n node: ExecutionNode,\n ctx: IExecutionContext,\n adapter?: LLMAdapter,\n config?: GenerationConfig\n): Promise<unknown[]> {\n if (!node.children || node.children.length === 0) {\n throw new Error('Loop node has no children');\n }\n\n if (!node.maxIterations) {\n throw new Error('Loop node missing maxIterations');\n }\n\n const results: unknown[] = [];\n\n // Create loop context\n let loopCtx = ctx;\n if (loopCtx instanceof ExecutionContext) {\n loopCtx = loopCtx.withIteration(0, node.maxIterations);\n }\n\n for (let i = 0; i < node.maxIterations; i++) {\n // Update iteration\n if (loopCtx instanceof ExecutionContext) {\n loopCtx = loopCtx.withIteration(i, node.maxIterations);\n }\n\n // Execute child\n const result = await executeNode(node.children[0], loopCtx, adapter, config);\n results.push(result);\n\n // Add to history\n if (loopCtx instanceof ExecutionContext) {\n loopCtx = loopCtx.withIterationResult(result);\n }\n }\n\n return results;\n}\n\n// ============================================================================\n// ForEach Node\n// ============================================================================\n\n/**\n * Result from ForEach execution with error tracking\n */\nexport interface ForEachResult {\n /** Results from successful iterations */\n results: unknown[];\n\n /** Errors from failed iterations (when errorMode='continue' or 'skip') */\n errors: Array<{ index: number; item: unknown; error: Error }>;\n\n /** Total items processed */\n totalItems: number;\n\n /** Successfully processed count */\n successCount: number;\n\n /** Failed iterations count */\n failureCount: number;\n}\n\n/**\n * Execute a foreach node\n */\nasync function executeForEachNode(\n node: ExecutionNode,\n ctx: IExecutionContext,\n adapter?: LLMAdapter,\n config?: GenerationConfig\n): Promise<unknown[] | ForEachResult> {\n if (!node.children || node.children.length === 0) {\n throw new Error('ForEach node has no children');\n }\n\n if (!node.itemsAccessor) {\n throw new Error('ForEach node missing itemsAccessor');\n }\n\n // Resolve items array (may be static or function)\n let items: unknown[];\n if (typeof node.itemsAccessor === 'function') {\n items = await Promise.resolve(node.itemsAccessor(ctx));\n } else {\n items = node.itemsAccessor as unknown[];\n }\n\n // Validate items is an array\n if (!Array.isArray(items)) {\n throw new Error('ForEach items must be an array');\n }\n\n const itemMode = node.itemMode ?? 'property';\n const itemKey = node.itemKey ?? 'currentItem';\n const errorMode = node.errorMode ?? 'stop';\n const collectResults = node.collectResults ?? true;\n\n const results: unknown[] = [];\n const errors: Array<{ index: number; item: unknown; error: Error }> = [];\n let successCount = 0;\n let failureCount = 0;\n\n // Loop over items\n for (let i = 0; i < items.length; i++) {\n const item = items[i];\n\n try {\n // Create iteration-specific context\n const iterationCtx = createIterationContext(\n ctx,\n item,\n i,\n items.length,\n itemMode,\n itemKey\n );\n\n // Execute child node with iteration context\n const result = await executeNode(node.children[0], iterationCtx, adapter, config);\n\n if (collectResults) {\n results.push(result);\n }\n successCount++;\n } catch (error) {\n failureCount++;\n const err = error instanceof Error ? error : new Error(String(error));\n\n // Handle error based on errorMode\n if (errorMode === 'stop') {\n // Fail-fast: re-throw error\n throw err;\n } else if (errorMode === 'continue') {\n // Collect error and continue\n errors.push({ index: i, item, error: err });\n } else if (errorMode === 'skip') {\n // Silent failure, just increment failureCount\n // Error is not added to errors array\n }\n }\n }\n\n // Return format depends on errorMode and whether errors occurred\n if (errorMode === 'continue' && (errors.length > 0 || failureCount > 0)) {\n // Return detailed result with errors\n return {\n results,\n errors,\n totalItems: items.length,\n successCount,\n failureCount,\n };\n }\n\n // Return simple results array\n return results;\n}\n\n/**\n * Create an iteration-specific context with item injected\n */\nfunction createIterationContext(\n baseCtx: IExecutionContext,\n currentItem: unknown,\n index: number,\n totalItems: number,\n itemMode: 'merge' | 'replace' | 'property',\n itemKey: string\n): IExecutionContext {\n // Build new inputs based on itemMode\n let newInputs: unknown;\n\n if (itemMode === 'property') {\n // Inject as property\n newInputs = {\n ...(baseCtx.inputs as Record<string, unknown>),\n [itemKey]: currentItem,\n __forEachIndex: index,\n __forEachTotal: totalItems,\n __forEachIsLast: index === totalItems - 1,\n };\n } else if (itemMode === 'merge') {\n // Merge item properties into inputs\n if (typeof currentItem === 'object' && currentItem !== null) {\n newInputs = {\n ...(baseCtx.inputs as Record<string, unknown>),\n ...(currentItem as Record<string, unknown>),\n __forEachIndex: index,\n __forEachTotal: totalItems,\n __forEachIsLast: index === totalItems - 1,\n };\n } else {\n throw new Error(\n `ForEach itemMode='merge' requires object items, got ${typeof currentItem}`\n );\n }\n } else if (itemMode === 'replace') {\n // Replace entire inputs with item\n // If item is not an object, metadata is lost (by design)\n if (typeof currentItem === 'object' && currentItem !== null) {\n newInputs = {\n ...(currentItem as Record<string, unknown>),\n __forEachIndex: index,\n __forEachTotal: totalItems,\n __forEachIsLast: index === totalItems - 1,\n };\n } else {\n newInputs = currentItem;\n }\n } else {\n throw new Error(`Unknown itemMode: ${itemMode}`);\n }\n\n // If ExecutionContext class, use withInputs method\n if (baseCtx instanceof ExecutionContext) {\n return baseCtx\n .withInputs(newInputs)\n .withIteration(index, totalItems);\n }\n\n // Otherwise, create new context object\n return {\n ...baseCtx,\n inputs: newInputs,\n iteration: index,\n maxIterations: totalItems,\n isLastIteration: index === totalItems - 1,\n };\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Create a simple step node\n */\nexport function createStepNode(component: AgentComponent): ExecutionNode {\n return {\n type: 'step',\n component\n };\n}\n\n/**\n * Create a sequence node\n */\nexport function createSequenceNode(children: ExecutionNode[]): ExecutionNode {\n return {\n type: 'sequence',\n children\n };\n}\n\n/**\n * Create a parallel node\n */\nexport function createParallelNode(children: ExecutionNode[]): ExecutionNode {\n return {\n type: 'parallel',\n children\n };\n}\n\n/**\n * Create a conditional node\n */\nexport function createConditionalNode(\n condition: (ctx: IExecutionContext) => boolean | Promise<boolean>,\n trueBranch: ExecutionNode,\n falseBranch?: ExecutionNode\n): ExecutionNode {\n return {\n type: 'conditional',\n condition,\n children: falseBranch ? [trueBranch, falseBranch] : [trueBranch]\n };\n}\n\n/**\n * Create a loop node\n */\nexport function createLoopNode(\n child: ExecutionNode,\n maxIterations: number\n): ExecutionNode {\n return {\n type: 'loop',\n children: [child],\n maxIterations\n };\n}\n"]}
|