/**
 * SmartPerfetto Base Agent
 *
 * Phase 2.1: Abstract base class for all AI domain agents
 *
 * This class provides the foundation for AI-driven domain agents that:
 * 1. Use Skills as tools through AI reasoning
 * 2. Can request information from other agents
 * 3. Build and verify hypotheses
 * 4. Generate evidence-backed findings
 *
 * The Think-Act-Reflect loop:
 * 1. Understand: Parse task and build understanding
 * 2. Plan: Decide which tools to use
 * 3. Execute: Run tools and collect results
 * 4. Reflect: Evaluate results and decide next steps
 * 5. Respond: Generate response with findings
 */
import { EventEmitter } from 'events';
import { AgentConfig, AgentTask, AgentTaskContext, AgentResponse, AgentTool, AgentToolContext, AgentToolResult, Hypothesis, HypothesisUpdate, Evidence, InterAgentQuestion, ReasoningStep, SharedAgentContext } from '../../types/agentProtocol';
import { Finding } from '../../types';
import { ModelRouter } from '../../core/modelRouter';
import { SkillExecutionResult } from '../../../services/skillEngine';
/**
 * Skill definition for lazy tool initialization in agents.
 * Agents declare which skills they use at construction time, but actual
 * tool creation is deferred to executeTask() when the async skill registry
 * is guaranteed to be initialized.
 */
export interface SkillDefinitionForAgent {
    skillId: string;
    toolName: string;
    description?: string;
    descriptionHint?: string;
    required?: boolean;
    category: AgentTool['category'];
}
/**
 * Configuration for the dynamic SQL upgrade path.
 * When predefined Skills return insufficient results, agents can
 * "upgrade" to dynamic SQL generation for more flexible analysis.
 */
export interface UpgradeConfig {
    /** Enable the upgrade path (default: true) */
    enabled: boolean;
    /** Minimum number of failed/empty steps before considering upgrade */
    minFailedSteps: number;
    /** Maximum retries for dynamic SQL (default: 2) */
    maxRetries: number;
    /** Required: explicit objective must be derivable from task */
    requireExplicitObjective: boolean;
}
/**
 * Result of checking if upgrade to dynamic SQL is eligible.
 */
export interface UpgradeEligibility {
    /** Whether upgrade should be attempted */
    eligible: boolean;
    /** Reason for the decision */
    reason: string;
    /** Suggested objective for SQL generation */
    suggestedObjective?: string;
    /** Failed step information for context */
    failedSteps?: string[];
}
/**
 * Understanding of a task
 */
export interface TaskUnderstanding {
    /** Main objective */
    objective: string;
    /** Key questions to answer */
    questions: string[];
    /** Relevant domain areas */
    relevantAreas: string[];
    /** Recommended tools to use */
    recommendedTools: string[];
    /** Constraints or requirements */
    constraints: string[];
    /** Confidence in understanding */
    confidence: number;
}
/**
 * Execution plan
 */
export interface ExecutionPlan {
    /** Sequence of tool calls */
    steps: ExecutionStep[];
    /** Expected outcomes */
    expectedOutcomes: string[];
    /** Estimated execution time */
    estimatedTimeMs: number;
    /** Plan confidence */
    confidence: number;
}
/**
 * Single execution step
 */
export interface ExecutionStep {
    stepNumber: number;
    toolName: string;
    params: Record<string, any>;
    purpose: string;
    dependsOn?: number[];
}
/**
 * Result of executing the plan
 */
export interface ExecutionResult {
    steps: ExecutionStepResult[];
    findings: Finding[];
    success: boolean;
    totalTimeMs: number;
}
/**
 * Result of a single execution step
 */
export interface ExecutionStepResult {
    stepNumber: number;
    toolName: string;
    result: AgentToolResult;
    observations: string[];
}
/**
 * Reflection on execution results
 */
export interface Reflection {
    /** What was learned */
    insights: string[];
    /** Whether objectives were met */
    objectivesMet: boolean;
    /** Confidence in findings */
    findingsConfidence: number;
    /** Gaps in analysis */
    gaps: string[];
    /** Suggested next steps */
    nextSteps: string[];
    /** Hypothesis updates */
    hypothesisUpdates: HypothesisUpdate[];
    /** Questions for other agents */
    questionsForOthers: InterAgentQuestion[];
}
/**
 * Abstract base class for domain-specific AI agents
 *
 * Each domain agent (Frame, CPU, Memory, Binder, etc.) extends this class
 * and provides:
 * 1. Domain-specific tools (wrapped Skills)
 * 2. Domain-specific reasoning prompts
 * 3. Domain-specific hypothesis generation
 */
export declare abstract class BaseAgent extends EventEmitter {
    /** Agent configuration */
    readonly config: AgentConfig;
    /** Model router for LLM calls */
    protected modelRouter: ModelRouter;
    /** Available tools */
    protected tools: Map<string, AgentTool>;
    /** Skill definitions for lazy tool initialization */
    protected skillDefinitions: SkillDefinitionForAgent[];
    /** Whether tools have been lazily loaded from skill definitions */
    private toolsLoaded;
    /** Cached SkillExecutor with registered skills */
    private skillExecutorCache;
    /** Current shared context */
    protected sharedContext: SharedAgentContext | null;
    /** Reasoning trace */
    protected reasoningTrace: ReasoningStep[];
    /** Current iteration */
    protected currentIteration: number;
    /** Upgrade path configuration */
    protected upgradeConfig: UpgradeConfig;
    /** Track upgrade attempts per task */
    private upgradeAttempts;
    constructor(config: AgentConfig, modelRouter: ModelRouter, skillDefs?: SkillDefinitionForAgent[]);
    /**
     * Build domain-specific system prompt for understanding
     */
    protected abstract buildUnderstandingPrompt(task: AgentTask): string;
    /**
     * Build domain-specific system prompt for planning
     */
    protected abstract buildPlanningPrompt(understanding: TaskUnderstanding, task: AgentTask): string;
    /**
     * Build domain-specific system prompt for reflection
     */
    protected abstract buildReflectionPrompt(result: ExecutionResult, task: AgentTask): string;
    /**
     * Generate domain-specific hypotheses based on findings
     */
    protected abstract generateHypotheses(findings: Finding[], task: AgentTask): Promise<Hypothesis[]>;
    /**
     * Get domain-specific tool recommendations (subclass override)
     */
    protected abstract getRecommendedTools(context: AgentTaskContext): string[];
    /**
     * Resolve tools for a task context.
     * Generic: if orchestrator specifies `additionalData.focusTools`, restricts to those tools.
     * Otherwise falls back to subclass's getRecommendedTools().
     * This allows any orchestrator to control agent tool selection without scenario-specific flags.
     */
    private resolveToolsForTask;
    /**
     * Execute a task through the Think-Act-Reflect loop
     */
    executeTask(task: AgentTask, sharedContext: SharedAgentContext): Promise<AgentResponse>;
    /**
     * Step 1: Understand the task
     */
    protected understand(task: AgentTask): Promise<TaskUnderstanding>;
    /**
     * Step 2: Plan execution
     */
    protected plan(understanding: TaskUnderstanding, task: AgentTask): Promise<ExecutionPlan>;
    /**
     * Step 3: Execute the plan
     */
    protected execute(plan: ExecutionPlan, task: AgentTask): Promise<ExecutionResult>;
    /**
     * Check if the agent should attempt a dynamic SQL upgrade.
     *
     * Upgrade is eligible when:
     * 1. Upgrade path is enabled
     * 2. Predefined skills returned no useful results
     * 3. We haven't exceeded retry limits
     * 4. Task has a clear objective we can convert to SQL
     */
    protected checkUpgradeEligibility(task: AgentTask, stepResults: ExecutionStepResult[], toolContext: AgentToolContext): UpgradeEligibility;
    /**
     * Build an objective for dynamic SQL based on the failed task.
     * Subclasses can override for domain-specific objective building.
     */
    protected buildUpgradeObjective(task: AgentTask, failedTools: string[]): string | undefined;
    /**
     * Attempt to execute dynamic SQL for the given objective.
     *
     * This is the "escape hatch" when predefined Skills can't satisfy the analysis need.
     */
    protected tryDynamicSQLUpgrade(objective: string, toolContext: AgentToolContext, task: AgentTask): Promise<AgentToolResult>;
    /**
     * Reset upgrade attempts counter. Called at the start of each task.
     */
    protected resetUpgradeState(): void;
    /**
     * Configure the upgrade path behavior.
     * Subclasses can call this to customize upgrade behavior.
     */
    protected configureUpgrade(config: Partial<UpgradeConfig>): void;
    /**
     * Step 4: Reflect on results
     */
    protected reflect(result: ExecutionResult, task: AgentTask): Promise<Reflection>;
    /**
     * Step 5: Generate final response
     */
    protected respond(reflection: Reflection, result: ExecutionResult, task: AgentTask, startTime: number): Promise<AgentResponse>;
    /**
     * Ensure skill-based tools are loaded.
     * Called at the start of executeTask() — by this time the skill registry
     * is guaranteed to be initialized (the orchestrator awaits it before dispatching).
     */
    protected ensureToolsLoaded(): Promise<void>;
    private resolveSkillToolDescription;
    /**
     * Create a tool executor function for a given skill ID.
     * Shared across all domain agents — eliminates code duplication.
     */
    protected createSkillToolExecutor(toolName: string, skillId: string, category: string): (params: Record<string, any>, context: AgentToolContext) => Promise<AgentToolResult>;
    private getOrCreateSkillExecutor;
    /**
     * Extract findings from skill execution result.
     * Subclasses can override for domain-specific extraction logic.
     */
    protected extractFindingsFromResult(result: SkillExecutionResult, skillId: string, category: string): Finding[];
    private extractSynthesizeSummaryFinding;
    /**
     * Extract data from skill execution result
     */
    protected extractDataFromResult(result: SkillExecutionResult): any;
    /**
     * Add a step to the reasoning trace
     */
    protected addReasoningStep(type: ReasoningStep['type'], content: string, confidence?: number): void;
    /**
     * Generate observations from a tool result
     */
    protected generateObservations(result: AgentToolResult): string[];
    /**
     * Create a hypothesis
     */
    protected createHypothesis(description: string, confidence: number, supportingEvidence?: Evidence[]): Hypothesis;
    /**
     * Get tool by name
     */
    getTool(name: string): AgentTool | undefined;
    /**
     * Get all tools
     */
    getAllTools(): AgentTool[];
    /**
     * Get tool descriptions for LLM, including parameter info.
     * This helps the LLM understand that tools are self-contained (with built-in SQL)
     * and only need simple parameters to execute.
     */
    getToolDescriptionsForLLM(): string;
    /**
     * Get the full "available tools" section for LLM prompts.
     * Includes tool list, parameter info, usage clarification, and negative examples.
     * Use this in buildUnderstandingPrompt / buildPlanningPrompt instead of raw getToolDescriptionsForLLM().
     */
    protected getToolSectionForPrompt(): string;
    /**
     * Format common task context fields for prompts
     */
    protected formatTaskContext(task: AgentTask): string;
    /**
     * Set shared context
     */
    setSharedContext(context: SharedAgentContext): void;
    /**
     * SQL generator instance (lazy initialized).
     * Provides agents with the ability to generate dynamic SQL queries.
     */
    private sqlGenerator;
    private sqlValidator;
    /**
     * Get or create SQL generator instance.
     */
    protected getSQLGenerator(): Promise<import('../../tools/sqlGenerator').SQLGenerator>;
    /**
     * Get or create SQL validator instance.
     */
    protected getSQLValidator(): Promise<import('../../tools/sqlValidator').SQLValidator>;
    /**
     * Generate and execute a dynamic SQL query.
     *
     * This gives agents true autonomy to explore data beyond predefined Skills.
     * The method:
     * 1. Generates SQL using LLM based on the objective
     * 2. Validates the SQL for safety
     * 3. Executes the query
     * 4. Returns results with metadata
     *
     * @param objective - What the agent wants to analyze
     * @param context - Tool context with trace processor service
     * @param schemaContext - Optional schema context (auto-detected if not provided)
     * @returns Query result with data and metadata
     */
    protected generateAndExecuteSQL(objective: string, context: import('../../types/agentProtocol').AgentToolContext, schemaContext?: import('../../tools/sqlGenerator').SchemaContext): Promise<DynamicSQLResult>;
    /**
     * Process raw SQL query result into structured data.
     */
    private processSQLResult;
    /**
     * Check if dynamic SQL generation is enabled for this agent.
     * Subclasses can override to control when SQL generation is allowed.
     */
    protected isDynamicSQLEnabled(): boolean;
}
/**
 * Result of dynamic SQL generation and execution.
 */
export interface DynamicSQLResult {
    success: boolean;
    data?: any;
    error?: string;
    validationErrors?: string[];
    generatedSQL?: import('../../tools/sqlGenerator').GeneratedSQL;
    queryResult?: any;
    validation?: import('../../tools/sqlValidator').ValidationResult;
    /** Number of repair attempts performed (0 means no repair) */
    repairAttempts?: number;
    /** Error trail from validation/execution/repair attempts (best-effort) */
    repairErrors?: string[];
    executionTimeMs: number;
}
export default BaseAgent;
//# sourceMappingURL=baseAgent.d.ts.map