import { EventEmitter } from 'events'; import { z } from 'zod'; /** * AIKIT Agent Orchestration System - Type Definitions * * This module defines the core types for the AI agent execution framework. * Provides type-safe interfaces for agents, tools, and execution traces. */ /** * Schema definition for tool parameters using Zod */ type ToolParameterSchema = z.ZodObject | z.ZodType; /** * Tool metadata and configuration */ interface ToolDefinition { /** * Unique identifier for the tool */ name: string; /** * Human-readable description of what the tool does * This is used by the LLM to understand when to use the tool */ description: string; /** * Zod schema for validating tool parameters */ parameters: ToolParameterSchema; /** * The actual function that executes the tool * @param params - Validated parameters matching the schema * @returns Promise resolving to the tool result */ execute: (params: TParams) => Promise; /** * Optional retry configuration */ retry?: { maxAttempts: number; backoffMs: number; }; /** * Optional timeout in milliseconds */ timeoutMs?: number; /** * Optional metadata for categorization and filtering */ metadata?: Record; } /** * Runtime tool call request from the LLM */ interface ToolCall { /** * Unique ID for this specific tool call invocation */ id: string; /** * Name of the tool to execute */ name: string; /** * Parameters to pass to the tool (validated against schema) */ parameters: Record; } /** * Result of a tool execution */ interface ToolResult { /** * ID of the tool call this result corresponds to */ toolCallId: string; /** * Name of the tool that was executed */ toolName: string; /** * The result data from the tool execution */ result: unknown; /** * Error information if the tool execution failed */ error?: { message: string; code?: string; stack?: string; }; /** * Execution metadata */ metadata: { durationMs: number; timestamp: string; retryCount?: number; }; } /** * Agent configuration */ interface AgentConfig { /** * Unique identifier for the agent */ id: string; /** * Human-readable name */ name: string; /** * Description of the agent's purpose and capabilities */ description?: string; /** * System prompt that defines the agent's behavior */ systemPrompt: string; /** * LLM provider configuration */ llm: { provider: 'openai' | 'anthropic' | 'google' | 'custom'; model: string; temperature?: number; maxTokens?: number; topP?: number; apiKey?: string; baseUrl?: string; }; /** * Tools available to this agent */ tools: ToolDefinition[]; /** * Maximum number of execution steps before stopping */ maxSteps?: number; /** * Whether to enable streaming responses */ streaming?: boolean; /** * Custom metadata */ metadata?: Record; } /** * Message in the agent conversation */ interface Message { role: 'system' | 'user' | 'assistant' | 'tool'; content: string; name?: string; toolCalls?: ToolCall[]; toolCallId?: string; timestamp?: string; } /** * Agent state during execution */ interface AgentState { /** * Current step number in the execution */ step: number; /** * Conversation history */ messages: Message[]; /** * Pending tool calls waiting to be executed */ pendingToolCalls: ToolCall[]; /** * Results from completed tool calls */ toolResults: ToolResult[]; /** * Whether the agent has finished execution */ isComplete: boolean; /** * Final response if execution is complete */ finalResponse?: string; /** * Error information if execution failed */ error?: { message: string; step: number; cause?: unknown; }; } /** * Types of events in the execution trace */ type TraceEventType = 'agent_start' | 'agent_end' | 'llm_request' | 'llm_response' | 'llm_stream_start' | 'llm_stream_chunk' | 'llm_stream_end' | 'tool_call_request' | 'tool_call_start' | 'tool_call_end' | 'tool_call_error' | 'step_start' | 'step_end' | 'error'; /** * Individual trace event */ interface TraceEvent { /** * Event type */ type: TraceEventType; /** * Timestamp when the event occurred */ timestamp: string; /** * Step number during which this event occurred */ step?: number; /** * Event-specific data */ data: Record; /** * Duration in milliseconds (for start/end pairs) */ durationMs?: number; } /** * Complete execution trace */ interface ExecutionTrace { /** * Unique execution ID */ executionId: string; /** * Agent ID */ agentId: string; /** * Start timestamp */ startTime: string; /** * End timestamp */ endTime?: string; /** * Total duration in milliseconds */ durationMs?: number; /** * All trace events in chronological order */ events: TraceEvent[]; /** * Final agent state */ finalState?: AgentState; /** * Execution statistics */ stats: { totalSteps: number; totalToolCalls: number; totalLLMCalls: number; totalTokensUsed?: number; successfulToolCalls: number; failedToolCalls: number; }; } /** * Streaming event types */ type StreamEventType = 'start' | 'step' | 'thought' | 'tool_call' | 'tool_result' | 'text_chunk' | 'final_answer' | 'complete' | 'error'; /** * Base streaming event */ interface StreamEvent { type: StreamEventType; timestamp: string; data: unknown; } /** * Streaming callback handler */ type StreamCallback = (event: StreamEvent) => void | Promise; /** * Agent step event for streaming */ interface AgentStepEvent { /** * Event type identifier */ type: 'step'; /** * Current step number */ step: number; /** * Step timestamp */ timestamp: string; /** * Step metadata */ metadata?: { messagesCount?: number; pendingToolCalls?: number; }; } /** * Thought event - agent's reasoning/thinking */ interface ThoughtEvent { /** * Event type identifier */ type: 'thought'; /** * The thought/reasoning content */ content: string; /** * Step number during which this thought occurred */ step: number; /** * Event timestamp */ timestamp: string; } /** * Tool call event */ interface ToolCallEvent { /** * Event type identifier */ type: 'tool_call'; /** * The tool call details */ toolCall: ToolCall; /** * Step number */ step: number; /** * Event timestamp */ timestamp: string; } /** * Tool result event */ interface ToolResultEvent { /** * Event type identifier */ type: 'tool_result'; /** * The tool execution result */ result: ToolResult; /** * Step number */ step: number; /** * Event timestamp */ timestamp: string; } /** * Final answer event */ interface FinalAnswerEvent { /** * Event type identifier */ type: 'final_answer'; /** * The final answer/response */ answer: string; /** * Step number */ step: number; /** * Event timestamp */ timestamp: string; } /** * Error event */ interface ErrorEvent { /** * Event type identifier */ type: 'error'; /** * Error message */ error: string; /** * Error code */ code?: string; /** * Step number where error occurred */ step?: number; /** * Event timestamp */ timestamp: string; } /** * Union type of all agent execution streaming events */ type AgentExecutionEvent = AgentStepEvent | ThoughtEvent | ToolCallEvent | ToolResultEvent | FinalAnswerEvent | ErrorEvent; /** * Base error for agent system */ declare class AgentError extends Error { code: string; context?: Record | undefined; constructor(message: string, code: string, context?: Record | undefined); } /** * Tool execution error */ declare class ToolExecutionError extends AgentError { toolName: string; toolCallId: string; constructor(message: string, toolName: string, toolCallId: string, context?: Record); } /** * Tool validation error */ declare class ToolValidationError extends AgentError { toolName: string; validationErrors: z.ZodError; constructor(message: string, toolName: string, validationErrors: z.ZodError, context?: Record); } /** * LLM error */ declare class LLMError extends AgentError { provider: string; constructor(message: string, provider: string, context?: Record); } /** * Max steps exceeded error */ declare class MaxStepsExceededError extends AgentError { constructor(maxSteps: number, context?: Record); } /** * Extract parameter type from tool definition */ type ToolParams = T extends ToolDefinition ? P : never; /** * Extract result type from tool definition */ type ToolResultType = T extends ToolDefinition ? R : never; /** * Type-safe tool registry */ type ToolRegistry = Map; /** * Role of an agent in the swarm */ type AgentRole = 'supervisor' | 'specialist'; /** * Specialist agent configuration for swarm */ interface SpecialistAgent { /** * Unique identifier for the specialist */ id: string; /** * Agent instance */ agent: any; /** * Specialization area/domain */ specialization: string; /** * Keywords/tags that trigger this specialist */ keywords?: string[]; /** * Priority when multiple specialists match (higher = preferred) */ priority?: number; /** * Whether this specialist can handle multiple tasks concurrently */ concurrent?: boolean; } /** * Task routing decision */ interface TaskRoutingDecision { /** * ID of the specialist agent to handle the task */ specialistId: string; /** * Reason for routing to this specialist */ reason: string; /** * Confidence score (0-1) */ confidence: number; } /** * Specialist execution result */ interface SpecialistResult { /** * ID of the specialist that executed the task */ specialistId: string; /** * Specialization area */ specialization: string; /** * Response from the specialist */ response: string; /** * Execution trace from the specialist */ trace: ExecutionTrace; /** * Whether execution was successful */ success: boolean; /** * Error if execution failed */ error?: Error; /** * Execution metadata */ metadata: { startTime: string; endTime: string; durationMs: number; }; } /** * Configuration for AgentSwarm */ interface SwarmConfig { /** * Unique identifier for the swarm */ id: string; /** * Human-readable name */ name: string; /** * Description of the swarm's purpose */ description?: string; /** * Supervisor agent that coordinates specialists */ supervisor: any; /** * Specialist agents in the swarm */ specialists: SpecialistAgent[]; /** * Maximum number of concurrent specialist executions */ maxConcurrent?: number; /** * Whether to enable parallel execution of independent tasks */ parallelExecution?: boolean; /** * Timeout for specialist executions (milliseconds) */ specialistTimeoutMs?: number; /** * Custom routing strategy */ customRouter?: (task: string, specialists: SpecialistAgent[]) => Promise; /** * Custom result synthesizer */ customSynthesizer?: (results: SpecialistResult[]) => Promise; /** * Custom metadata */ metadata?: Record; } /** * Swarm execution result */ interface SwarmResult { /** * Final synthesized response */ response: string; /** * Results from individual specialists */ specialistResults: SpecialistResult[]; /** * Combined execution trace from all agents */ combinedTrace: ExecutionTrace; /** * Supervisor's decision-making trace */ supervisorTrace: ExecutionTrace; /** * Whether execution was successful */ success: boolean; /** * Error if execution failed */ error?: Error; /** * Execution statistics */ stats: { totalSpecialistsInvoked: number; successfulSpecialists: number; failedSpecialists: number; totalDurationMs: number; parallelExecutions: number; }; } /** * AIKIT Agent - Base Agent Class * * This module provides the base Agent class with tool registration, * validation, and management capabilities. */ /** * Base Agent class that manages tools and provides execution context */ declare class Agent { /** * Agent configuration */ readonly config: AgentConfig; /** * Tool registry (name -> definition) */ private toolRegistry; constructor(config: AgentConfig); /** * Register a tool with the agent */ registerTool(tool: ToolDefinition): void; /** * Register multiple tools at once */ registerTools(tools: ToolDefinition[]): void; /** * Unregister a tool by name */ unregisterTool(toolName: string): boolean; /** * Get a tool by name */ getTool(toolName: string): ToolDefinition | undefined; /** * Get all registered tools */ getTools(): ToolDefinition[]; /** * Check if a tool is registered */ hasTool(toolName: string): boolean; /** * Get tool names for LLM function calling */ getToolSchemas(): Array<{ name: string; description: string; parameters: Record; }>; /** * Validate tool call parameters against the tool's schema */ validateToolCall(toolCall: ToolCall): { valid: boolean; error?: ToolValidationError; validatedParams?: unknown; }; /** * Execute a single tool call */ executeToolCall(toolCall: ToolCall): Promise; /** * Execute multiple tool calls in parallel */ executeToolCalls(toolCalls: ToolCall[]): Promise; /** * Build initial messages for the agent */ buildInitialMessages(userMessage: string): Message[]; /** * Get agent metadata for logging/tracing */ getMetadata(): Record; /** * Validate tool definition structure */ private validateToolDefinition; /** * Convert Zod schema to JSON schema for LLM function calling */ private zodSchemaToJsonSchema; /** * Execute a function with timeout */ private executeWithTimeout; /** * Sleep for specified milliseconds */ private sleep; } /** * Factory function to create an agent */ declare function createAgent(config: AgentConfig): Agent; /** * LLM Provider Interface * * Defines the contract for LLM providers to integrate with the agent system */ /** * Chat request parameters */ interface ChatRequest { messages: Message[]; tools?: Array<{ name: string; description: string; parameters: Record; }>; temperature?: number; maxTokens?: number; topP?: number; streaming?: boolean; onStream?: (chunk: string) => void | Promise; } /** * Chat response */ interface ChatResponse { content: string; toolCalls?: ToolCall[]; finishReason?: 'stop' | 'tool_calls' | 'length' | 'content_filter'; usage?: { promptTokens: number; completionTokens: number; totalTokens: number; }; } /** * Base LLM provider interface */ declare abstract class LLMProvider { protected config: any; constructor(config: any); /** * Send a chat request to the LLM */ abstract chat(request: ChatRequest): Promise; /** * Get provider name */ abstract getProviderName(): string; } /** * AIKIT AgentExecutor - Multi-Step Agent Execution Engine * * This module implements the core agent execution loop with tool calling, * streaming support, error handling, and detailed execution tracing. */ /** * Configuration for agent execution */ interface ExecutionConfig { /** * Maximum number of steps before stopping */ maxSteps?: number; /** * Whether to enable streaming */ streaming?: boolean; /** * Stream callback for real-time updates */ onStream?: StreamCallback; /** * Whether to include detailed traces */ verbose?: boolean; /** * Custom LLM provider instance */ llmProvider?: LLMProvider; /** * Additional context to include in execution */ context?: Record; } /** * Result of agent execution */ interface ExecutionResult { /** * Final response from the agent */ response: string; /** * Final agent state */ state: AgentState; /** * Complete execution trace */ trace: ExecutionTrace; /** * Whether execution was successful */ success: boolean; /** * Error if execution failed */ error?: Error; } /** * AgentExecutor - Orchestrates multi-step agent execution with tool calling */ declare class AgentExecutor { private agent; private llmProvider; private executionId; private trace; private state; private defaultConfig; constructor(agent: Agent, config?: ExecutionConfig); /** * Execute the agent with the given input */ execute(input: string, config?: ExecutionConfig): Promise; /** * Main execution loop */ private executionLoop; /** * Execute LLM step to get next response */ private llmStep; /** * Execute pending tool calls */ private executeToolCallsStep; /** * Add an event to the execution trace */ private addTraceEvent; /** * Emit a stream event */ private emitStreamEvent; /** * Create LLM provider based on config */ private createLLMProvider; /** * Get current execution trace */ getTrace(): ExecutionTrace; /** * Get current agent state */ getState(): AgentState; } /** * Factory function to create and execute an agent in one call */ declare function executeAgent(agent: Agent, input: string, config?: ExecutionConfig): Promise; /** * AIKIT StreamingAgentExecutor - Streaming Agent Execution with Async Iterators * * This module provides streaming execution capabilities for agents, * allowing real-time updates as the agent thinks, calls tools, and generates responses. */ /** * Configuration for streaming execution */ interface StreamingExecutionConfig { /** * Maximum number of steps before stopping */ maxSteps?: number; /** * Custom LLM provider instance */ llmProvider?: LLMProvider; /** * Whether to include detailed traces */ verbose?: boolean; /** * Additional context to include in execution */ context?: Record; } /** * Complete streaming execution result */ interface StreamingExecutionResult { /** * Final response from the agent */ response: string; /** * Final agent state */ state: AgentState; /** * Complete execution trace */ trace: ExecutionTrace; /** * Whether execution was successful */ success: boolean; /** * Error if execution failed */ error?: Error; } /** * StreamingAgentExecutor - Provides async iterator-based streaming execution * * Usage: * ```typescript * const executor = new StreamingAgentExecutor(agent); * for await (const event of executor.stream(input)) { * if (event.type === 'thought') { * console.log('Agent thinking:', event.content); * } else if (event.type === 'tool_call') { * console.log('Calling tool:', event.toolCall.name); * } else if (event.type === 'final_answer') { * console.log('Final answer:', event.answer); * } * } * ``` */ declare class StreamingAgentExecutor { private agent; private llmProvider; private executionId; private trace; private state; constructor(agent: Agent, config?: StreamingExecutionConfig); /** * Stream agent execution as an async iterator * Yields events as the agent progresses through execution */ stream(input: string, config?: StreamingExecutionConfig): AsyncGenerator; /** * Main streaming execution loop */ private executionStreamLoop; /** * Execute LLM step and stream thoughts */ private llmStreamStep; /** * Execute pending tool calls and stream results */ private executeToolCallsStreamStep; /** * Add an event to the execution trace */ private addTraceEvent; /** * Create LLM provider based on config */ private createLLMProvider; /** * Get current execution trace */ getTrace(): ExecutionTrace; /** * Get current agent state */ getState(): AgentState; } /** * Factory function to create a streaming executor and iterate over events */ declare function streamAgentExecution(agent: Agent, input: string, config?: StreamingExecutionConfig): AsyncGenerator; /** * AIKIT AgentSwarm - Multi-Agent Coordination System * * This module implements a swarm architecture where a supervisor agent * coordinates multiple specialist agents to handle complex tasks. */ /** * Events emitted by the AgentSwarm */ interface SwarmEvents { 'swarm:start': { input: string; timestamp: string; }; 'swarm:routing': { task: string; decision: TaskRoutingDecision; }; 'specialist:start': { specialistId: string; task: string; }; 'specialist:complete': { specialistId: string; result: SpecialistResult; }; 'specialist:error': { specialistId: string; error: Error; }; 'swarm:synthesis': { results: SpecialistResult[]; }; 'swarm:complete': { result: SwarmResult; }; 'swarm:error': { error: Error; }; } /** * AgentSwarm - Coordinates multiple specialist agents under a supervisor */ declare class AgentSwarm extends EventEmitter { /** * Swarm configuration */ readonly config: SwarmConfig; /** * Supervisor agent */ private supervisor; /** * Map of specialist agents */ private specialists; /** * Execution ID for the current swarm execution */ private executionId?; constructor(config: SwarmConfig); /** * Register a new specialist agent */ registerSpecialist(specialist: SpecialistAgent): void; /** * Unregister a specialist agent */ unregisterSpecialist(specialistId: string): boolean; /** * Get a specialist by ID */ getSpecialist(specialistId: string): SpecialistAgent | undefined; /** * Get all registered specialists */ getSpecialists(): SpecialistAgent[]; /** * Execute the swarm with the given task */ execute(task: string, config?: ExecutionConfig): Promise; /** * Route the task to appropriate specialists */ private routeTask; /** * Match specialists based on keywords in the task */ private matchSpecialistsByKeywords; /** * Use supervisor agent to route the task */ private supervisorRouting; /** * Parse supervisor's routing response */ private parseSupervisorResponse; /** * Execute specialist agents based on routing decisions */ private executeSpecialists; /** * Execute specialists in parallel */ private executeSpecialistsParallel; /** * Execute specialists sequentially */ private executeSpecialistsSequential; /** * Execute a single specialist */ private executeSpecialist; /** * Synthesize results from multiple specialists */ private synthesizeResults; /** * Build combined execution trace from all specialists */ private buildCombinedTrace; /** * Get supervisor trace (routing decisions) */ private getSupervisorTrace; /** * Build an empty trace for error cases */ private buildEmptyTrace; /** * Build error result for a specialist */ private buildErrorResult; /** * Execute with timeout */ private executeWithTimeout; /** * Validate swarm configuration */ private validateConfig; /** * Get swarm metadata */ getMetadata(): Record; } /** * Factory function to create an AgentSwarm */ declare function createAgentSwarm(config: SwarmConfig): AgentSwarm; export { Agent as A, type ErrorEvent as B, type ChatRequest as C, type AgentExecutionEvent as D, type ExecutionConfig as E, type FinalAnswerEvent as F, AgentError as G, ToolExecutionError as H, ToolValidationError as I, LLMError as J, MaxStepsExceededError as K, LLMProvider as L, type Message as M, type ToolParams as N, type ToolResultType as O, type ToolRegistry as P, type AgentRole as Q, type SpecialistAgent as R, StreamingAgentExecutor as S, type ToolDefinition as T, type TaskRoutingDecision as U, type SpecialistResult as V, type SwarmConfig as W, type SwarmResult as X, AgentExecutor as a, AgentSwarm as b, createAgent as c, createAgentSwarm as d, executeAgent as e, type AgentConfig as f, type ToolCall as g, type ToolResult as h, type ExecutionResult as i, type StreamingExecutionConfig as j, type StreamingExecutionResult as k, type SwarmEvents as l, type ChatResponse as m, type ToolParameterSchema as n, type AgentState as o, type TraceEventType as p, type TraceEvent as q, type ExecutionTrace as r, streamAgentExecution as s, type StreamEventType as t, type StreamEvent as u, type StreamCallback as v, type AgentStepEvent as w, type ThoughtEvent as x, type ToolCallEvent as y, type ToolResultEvent as z };