/** @module services/pty-service */
import { type IAgentRuntime } from "@elizaos/core";
import { type AdapterType, type AgentFileDescriptor, type ApprovalConfig, type ApprovalPreset, type PreflightResult, type WriteMemoryOptions } from "coding-agent-adapters";
import { PTYConsoleBridge } from "pty-console";
import type { SessionFilter, SessionMessage } from "pty-manager";
import type { AgentSelectionStrategy } from "./agent-selection.ts";
import { type CoordinatorNormalizedEvent } from "./coordinator-event-normalizer.ts";
import type { CodingAgentType, PTYServiceConfig, SessionEventCallback, SessionInfo, SpawnSessionOptions } from "./pty-types.ts";
import { SwarmCoordinator } from "./swarm-coordinator.ts";
import { type TaskAgentAuthLaunchResult, type TaskAgentAuthStatus } from "./task-agent-auth.ts";
import { type SupportedTaskAgentAdapter, type TaskAgentFrameworkState, type TaskAgentTaskProfileInput } from "./task-agent-frameworks.ts";
export type { CodingAgentType, PTYServiceConfig, SessionEventName, SessionInfo, SpawnSessionOptions, } from "./pty-types.ts";
export { normalizeAgentType } from "./pty-types.ts";
/**
 * Retrieve the SwarmCoordinator from the PTYService registered on the runtime.
 * Returns undefined if PTYService or coordinator is not available.
 */
export declare function getCoordinator(runtime: IAgentRuntime): SwarmCoordinator | undefined;
export declare class PTYService {
    static serviceType: string;
    capabilityDescription: string;
    private runtime;
    private manager;
    private usingBunWorker;
    private serviceConfig;
    private sessionNames;
    private sessionMetadata;
    private sessionWorkdirs;
    private eventCallbacks;
    private normalizedEventCallbacks;
    private outputUnsubscribers;
    private transcriptUnsubscribers;
    private sessionOutputBuffers;
    private completionReconcileTimers;
    private completionSignalSince;
    private terminalSessionStates;
    private adapterCache;
    /** Tracks the buffer index when a task was sent, so we can capture the response on completion */
    private taskResponseMarkers;
    /** Captures "Task completion trace" log entries from worker stderr (rolling, capped at 200) */
    private traceEntries;
    private static readonly MAX_TRACE_ENTRIES;
    /** Lightweight per-agent-type metrics for observability */
    private metricsTracker;
    /** Active provider auth helper processes keyed by agent type. */
    private activeAuthFlows;
    /** Background auth-recovery watchers keyed by blocked session id. */
    private authRecoveryTimers;
    /** Console bridge for terminal output streaming and buffered hydration */
    consoleBridge: PTYConsoleBridge | null;
    /** Swarm coordinator instance (if active). Accessed via getCoordinator(runtime). */
    coordinator: SwarmCoordinator | null;
    constructor(runtime: IAgentRuntime, config?: PTYServiceConfig);
    static start(runtime: IAgentRuntime): Promise<PTYService>;
    static stopRuntime(runtime: IAgentRuntime): Promise<void>;
    private initialize;
    stop(): Promise<void>;
    private generateSessionId;
    /** Build a SessionIOContext from current instance state. */
    private ioContext;
    /**
     * Spawn a new PTY session for a coding agent
     */
    spawnSession(options: SpawnSessionOptions): Promise<SessionInfo>;
    private autoResponseContext;
    private pushDefaultRules;
    private handleGeminiAuth;
    sendToSession(sessionId: string, input: string): Promise<SessionMessage | undefined>;
    sendKeysToSession(sessionId: string, keys: string | string[]): Promise<void>;
    stopSession(sessionId: string, force?: boolean): Promise<void>;
    /** Default approval preset — runtime env var takes precedence over config. */
    get defaultApprovalPreset(): ApprovalPreset;
    /** Agent selection strategy — env var takes precedence. */
    get agentSelectionStrategy(): AgentSelectionStrategy;
    /**
     * Default agent type when strategy is "fixed".
     * Precedence: config file (`eliza.json` env section, written by the UI)
     * > runtime/env setting > "claude" fallback.
     */
    get defaultAgentType(): AdapterType;
    private get explicitDefaultAgentType();
    /**
     * Resolve which agent type to use when the caller didn't specify one.
     *
     * When the caller explicitly configured a fixed default agent type, fixed
     * mode returns that pinned framework. Otherwise the resolver scores the
     * available frameworks from task shape, auth/install state, and recent
     * metrics so dynamic routing still works on unconfigured installs.
     */
    resolveAgentType(selection?: TaskAgentTaskProfileInput): Promise<string>;
    getFrameworkState(selection?: TaskAgentTaskProfileInput): Promise<TaskAgentFrameworkState>;
    getSession(sessionId: string): SessionInfo | undefined;
    listSessions(filter?: SessionFilter): Promise<SessionInfo[]>;
    subscribeToOutput(sessionId: string, callback: (data: string) => void): () => void;
    getSessionOutput(sessionId: string, lines?: number): Promise<string>;
    /**
     * Whether the adapter currently classifies the session as actively
     * processing work (e.g. Codex's "esc to interrupt" status row).
     *
     * The swarm idle watchdog consults this before assuming a session is
     * idle based on output byte diffs, which are fooled by TUIs that
     * redraw the same status row in place via cursor positioning.
     *
     * Returns `false` for unknown sessions or adapters that don't
     * implement `detectLoading`. For Bun-compat mode this round-trips to
     * the worker; for in-process mode it reads the session directly.
     */
    isSessionLoading(sessionId: string): Promise<boolean>;
    private clearTranscriptCapture;
    private resolveTaskThreadId;
    private persistTranscript;
    private wireTranscriptCapture;
    isSessionBlocked(sessionId: string): boolean;
    /**
     * Find a PTY session ID by its working directory.
     * Used by the HTTP hooks endpoint to correlate Claude's cwd with our session.
     */
    findSessionIdByCwd(cwd: string): string | undefined;
    /**
     * Handle an incoming hook event from Claude Code's HTTP hooks.
     * Translates hook events into PTY service events.
     */
    handleHookEvent(sessionId: string, event: string, data: Record<string, unknown>): void;
    checkAvailableAgents(types?: AdapterType[]): Promise<PreflightResult[]>;
    getAgentAuthStatus(agentType: SupportedTaskAgentAdapter): Promise<TaskAgentAuthStatus>;
    triggerAgentAuth(agentType: SupportedTaskAgentAdapter): Promise<TaskAgentAuthLaunchResult>;
    startSessionAuthRecovery(sessionId: string, agentType: SupportedTaskAgentAdapter, login: {
        instructions?: string;
        url?: string;
        deviceCode?: string;
        method?: string;
        promptSnippet?: string;
    }): Promise<TaskAgentAuthLaunchResult & {
        recoveryStarted: boolean;
        status: "recovered" | "recovering" | "failed";
    }>;
    private monitorSessionAuthRecovery;
    private resumeSessionAfterRecoveredAuth;
    getSupportedAgentTypes(): CodingAgentType[];
    private classifyStall;
    private getAdapter;
    getWorkspaceFiles(agentType: AdapterType): AgentFileDescriptor[];
    getMemoryFilePath(agentType: AdapterType): string;
    getApprovalConfig(agentType: AdapterType, preset: ApprovalPreset): ApprovalConfig;
    writeMemoryFile(agentType: AdapterType, workspacePath: string, content: string, options?: WriteMemoryOptions): Promise<string>;
    /** Marker comment used to detect orchestrator-managed gitignore entries. */
    private static readonly GITIGNORE_MARKER;
    /** Per-path lock to serialize concurrent gitignore updates for the same workdir. */
    private static gitignoreLocks;
    /**
     * Ensure that orchestrator-injected files (CLAUDE.md, .claude/, GEMINI.md, etc.)
     * are listed in the workspace .gitignore so agents don't commit them.
     * Appends to an existing .gitignore or creates one. Idempotent — skips if
     * the marker comment is already present. Serialized per-path to prevent
     * duplicate entries from concurrent spawns.
     */
    private ensureOrchestratorGitignore;
    private doEnsureGitignore;
    onSessionEvent(callback: SessionEventCallback): () => void;
    onNormalizedSessionEvent(callback: (event: CoordinatorNormalizedEvent) => void): () => void;
    registerAdapter(adapter: unknown): void;
    private toSessionInfo;
    private toTerminalSessionInfo;
    private emitEvent;
    getAgentMetrics(): Record<string, Omit<import("./agent-metrics.ts").AgentMetrics, "totalCompletionMs">>;
    private log;
    private handleWorkerExit;
    private clearCompletionReconcile;
    private scheduleCompletionReconcile;
    private isAdapterBackedAgentType;
    private shouldSuppressBlockedEvent;
    private responseLooksMeaningful;
    private reconcileBusySessionFromOutput;
}
//# sourceMappingURL=pty-service.d.ts.map