/**
 * @fileoverview Background Task Tracker for Claude Code sessions
 *
 * This module tracks background tasks (subagents) spawned by Claude Code
 * during session execution. It parses both JSON messages and terminal output
 * to detect when tasks are created, updated, and completed.
 *
 * ## Task Hierarchy
 *
 * Tasks can be nested (parent-child relationships) when Claude spawns
 * a subagent from within another subagent. The tracker maintains a stack
 * to track nesting and a tree structure for visualization.
 *
 * ## Detection Methods
 *
 * 1. **JSON Messages**: Parses `tool_use` blocks for Task tool invocations
 *    and `tool_result` blocks for completion
 * 2. **Terminal Output**: Fallback pattern matching for launch/complete messages
 *
 * @module task-tracker
 */
import { EventEmitter } from 'node:events';
/**
 * Content block for tool_use messages from Claude.
 * Emitted when Claude invokes a tool.
 */
interface ClaudeToolUseBlock {
    type: 'tool_use';
    /** Unique identifier for this tool invocation */
    id: string;
    /** Name of the tool being invoked */
    name: string;
    /** Parameters passed to the tool */
    input?: {
        description?: string;
        prompt?: string;
        subagent_type?: string;
        [key: string]: unknown;
    };
}
/**
 * Content block for tool_result messages from Claude.
 * Emitted when a tool completes execution.
 */
interface ClaudeToolResultBlock {
    type: 'tool_result';
    /** ID of the tool_use this result corresponds to */
    tool_use_id: string;
    /** Whether the tool execution resulted in an error */
    is_error?: boolean;
    /** Result content (string or structured data) */
    content?: string | unknown;
}
/**
 * Union type for content blocks we care about.
 */
type ClaudeContentBlock = ClaudeToolUseBlock | ClaudeToolResultBlock | {
    type: string;
};
/**
 * Claude JSON message structure.
 * This is the format Claude Code outputs for streaming events.
 */
interface ClaudeMessage {
    message?: {
        content?: ClaudeContentBlock[];
    };
}
/**
 * Represents a background task spawned by Claude Code.
 *
 * Tasks form a tree structure where a parent task can spawn child tasks.
 * This enables tracking of nested agent invocations.
 */
export interface BackgroundTask {
    /** Unique task identifier (usually the tool_use ID from Claude) */
    id: string;
    /** Parent task ID if this is a nested task, null for root tasks */
    parentId: string | null;
    /** Human-readable description of what the task is doing */
    description: string;
    /** Type of subagent (e.g., 'explore', 'bash', 'general-purpose') */
    subagentType: string;
    /** Current execution status */
    status: 'running' | 'completed' | 'failed';
    /** Timestamp when task was created (milliseconds since epoch) */
    startTime: number;
    /** Timestamp when task finished (milliseconds since epoch) */
    endTime?: number;
    /** Output/result from the task execution */
    output?: string;
    /** IDs of child tasks spawned by this task */
    children: string[];
}
/**
 * Events emitted by TaskTracker.
 *
 * @event taskCreated - New task detected and added
 * @event taskUpdated - Task state changed (rarely used)
 * @event taskCompleted - Task finished successfully
 * @event taskFailed - Task finished with error
 */
/**
 * TaskTracker - Detects and tracks background tasks in Claude Code sessions.
 *
 * ## How It Works
 *
 * Claude Code outputs JSON messages when executing. When it spawns a subagent
 * via the Task tool, we see:
 *
 * 1. `tool_use` block with `name: "Task"` and input parameters
 * 2. ... task execution output ...
 * 3. `tool_result` block with the result or error
 *
 * The tracker maintains:
 * - A map of all tasks by ID
 * - A stack of currently running tasks (for nesting)
 * - Parent-child relationships between tasks
 *
 * ## Usage
 *
 * ```typescript
 * const tracker = new TaskTracker();
 *
 * tracker.on('taskCreated', (task) => {
 *   console.log(`New task: ${task.description}`);
 * });
 *
 * tracker.on('taskCompleted', (task) => {
 *   console.log(`Task done: ${task.id}`);
 * });
 *
 * // Feed in Claude messages
 * tracker.processMessage(claudeJsonMessage);
 *
 * // Or terminal output as fallback
 * tracker.processTerminalOutput(ptyData);
 * ```
 *
 * @extends EventEmitter
 */
export declare class TaskTracker extends EventEmitter {
    /** Map of task ID to task object */
    private tasks;
    /** Stack of active task IDs for tracking nesting depth */
    private taskStack;
    /** Pending tool_use blocks waiting for results (with timestamp for cleanup) */
    private pendingToolUses;
    /**
     * Creates a new TaskTracker instance.
     */
    constructor();
    /**
     * Process a Claude JSON message to detect task events.
     *
     * Looks for `tool_use` blocks with `name: "Task"` and `tool_result` blocks
     * to track task lifecycle.
     *
     * @param msg - Parsed Claude JSON message object
     * @fires taskCreated - When a new task is detected
     * @fires taskCompleted - When a task finishes successfully
     * @fires taskFailed - When a task finishes with error
     */
    processMessage(msg: ClaudeMessage | null | undefined): void;
    /**
     * Process raw terminal output to detect task patterns.
     *
     * This is a fallback for when JSON parsing doesn't capture everything.
     * Uses pre-compiled patterns to detect launch and completion messages.
     *
     * Note: May create duplicate tasks in some cases; deduplication is
     * handled by checking for existing running tasks of the same type.
     *
     * @param data - Raw terminal output string
     * @fires taskCreated - When a launch pattern is matched
     * @fires taskCompleted - When a complete pattern is matched
     */
    processTerminalOutput(data: string): void;
    /**
     * Handle a tool_use block for the Task tool.
     * Creates a new task and pushes it onto the stack.
     *
     * @param block - The tool_use content block
     * @fires taskCreated
     */
    private handleTaskToolUse;
    /**
     * Handle a tool_result block.
     * Marks the corresponding task as completed or failed.
     *
     * @param block - The tool_result content block
     * @fires taskCompleted - If result is success
     * @fires taskFailed - If result is error
     */
    private handleToolResult;
    /**
     * Remove old pending tool uses that never received results.
     * Prevents unbounded growth if tool_results never arrive.
     */
    private cleanupOldPendingToolUses;
    /**
     * Remove old completed/failed tasks when exceeding the limit
     * Keeps running tasks and the most recent completed tasks
     */
    private cleanupCompletedTasks;
    /**
     * Create a task from terminal pattern detection.
     * Used as fallback when JSON messages aren't available.
     *
     * @param agentType - Type of agent detected
     * @param context - Terminal context for debugging
     * @fires taskCreated
     */
    private createTaskFromTerminal;
    /**
     * Mark a task as completed.
     *
     * @param taskId - ID of task to complete
     * @fires taskCompleted - If task was running
     */
    private completeTask;
    /**
     * Get the most recently started running task.
     * Returns the task at the top of the stack (most nested).
     *
     * @returns Most recent running task, or undefined if none
     */
    private getMostRecentRunningTask;
    /**
     * Get root-level tasks as a list.
     *
     * Child tasks can be accessed via the `children` array on each task.
     * Use this for displaying a task tree in the UI.
     *
     * @returns Array of tasks without parents (root level)
     */
    getTaskTree(): BackgroundTask[];
    /**
     * Lightweight task tree for SSE broadcasts — strips large `output` strings
     * to avoid serializing 5-10MB of task results every 500ms.
     * Full task details available via getTaskTree().
     *
     * @returns Array of root tasks with output truncated to 200 chars
     */
    getTaskTreeLight(): Omit<BackgroundTask, 'output'>[];
    /**
     * Get all tasks as a flat Map.
     *
     * @returns Copy of the internal tasks map (safe to modify)
     */
    getAllTasks(): Map<string, BackgroundTask>;
    /**
     * Get a specific task by its ID.
     *
     * @param taskId - The task ID to look up
     * @returns The task if found, undefined otherwise
     */
    getTask(taskId: string): BackgroundTask | undefined;
    /**
     * Get the count of currently running tasks.
     *
     * @returns Number of tasks with status 'running'
     */
    getRunningCount(): number;
    /**
     * Get aggregated statistics about all tracked tasks.
     *
     * @returns Object with counts:
     *   - total: Total number of tracked tasks
     *   - running: Tasks currently executing
     *   - completed: Successfully finished tasks
     *   - failed: Tasks that ended with errors
     */
    getStats(): {
        total: number;
        running: number;
        completed: number;
        failed: number;
    };
    /**
     * Clear all tracked tasks.
     *
     * Use when the session is cleared or closed.
     * Resets the task map, stack, and pending tool uses.
     */
    clear(): void;
    /**
     * Clean up resources and release memory.
     *
     * Call this when the session is being destroyed to prevent memory leaks.
     * Clears all data and removes all event listeners.
     */
    destroy(): void;
}
export {};
//# sourceMappingURL=task-tracker.d.ts.map