import { AGENT_LIFECYCLE_STATUSES, type AgentLifecycleStatus } from "@kong-link/protocol/agent-lifecycle";
import type { Logger } from "pino";
import type { TerminalManager } from "../../terminal/terminal-manager.js";
import { type AgentCapabilityFlags, type AgentClient, type AgentFeature, type AgentSlashCommand, type AgentMode, type AgentPermissionRequest, type AgentPermissionResponse, type AgentPermissionResult, type AgentPersistenceHandle, type AgentPromptInput, type AgentProvider, type AgentRunOptions, type AgentRunResult, type AgentSession, type AgentSessionConfig, type AgentStreamEvent, type AgentTimelineItem, type AgentUsage, type AgentRuntimeInfo, type ListPersistedAgentsOptions, type PersistedAgentDescriptor } from "./agent-sdk-types.js";
import type { StoredAgentRecord, AgentStorage } from "./agent-storage.js";
import type { AgentTimelineFetchOptions, AgentTimelineFetchResult, AgentTimelineRow, AgentTimelineStore } from "./agent-timeline-store-types.js";
import { type ForegroundTurnWaiter } from "./foreground-run-state.js";
import { type RewindMode } from "./rewind/rewind.js";
export { AGENT_LIFECYCLE_STATUSES, type AgentLifecycleStatus };
export type { AgentTimelineCursor, AgentTimelineFetchDirection, AgentTimelineFetchOptions, AgentTimelineFetchResult, AgentTimelineRow, AgentTimelineWindow, } from "./agent-timeline-store-types.js";
export type AgentManagerEvent = {
    type: "agent_state";
    agent: ManagedAgent;
} | {
    type: "agent_stream";
    agentId: string;
    event: AgentStreamEvent;
    seq?: number;
    epoch?: string;
    timestamp?: string;
};
export type AgentSubscriber = (event: AgentManagerEvent) => void;
export interface SubscribeOptions {
    agentId?: string;
    replayState?: boolean;
}
interface HydrateTimelineOptions {
    force?: boolean;
    broadcast?: boolean;
}
export type ImportablePersistedAgentQueryOptions = ListPersistedAgentsOptions & {
    /**
     * When set, only providers in this set are scanned, in addition to the
     * built-in importable allowlist + enabled + non-derived rules.
     */
    providerFilter?: Set<string>;
};
export type AgentAttentionCallback = (params: {
    agentId: string;
    provider: AgentProvider;
    reason: "finished" | "error" | "permission";
}) => void;
export type AgentArchivedCallback = (agentId: string) => Promise<void> | void;
export interface ProviderAvailability {
    provider: AgentProvider;
    available: boolean;
    error: string | null;
}
interface AgentManagerRescueTimeouts {
    reloadSessionCloseMs?: number;
    interruptSessionMs?: number;
}
interface ProviderEnabledFlag {
    enabled: boolean;
    derivedFromProviderId?: string | null;
}
type ProviderEnabledMap = Partial<Record<AgentProvider, ProviderEnabledFlag>>;
type ProviderClientMap = Partial<Record<AgentProvider, AgentClient>>;
export interface AgentManagerOptions {
    clients?: ProviderClientMap;
    providerDefinitions?: ProviderEnabledMap;
    idFactory?: () => string;
    registry?: AgentStorage;
    onAgentAttention?: AgentAttentionCallback;
    durableTimelineStore?: AgentTimelineStore;
    terminalManager?: TerminalManager | null;
    mcpBaseUrl?: string;
    appendSystemPrompt?: string;
    agentStreamCoalesceWindowMs?: number;
    rescueTimeouts?: AgentManagerRescueTimeouts;
    logger: Logger;
}
export interface WaitForAgentOptions {
    signal?: AbortSignal;
    waitForActive?: boolean;
}
export interface WaitForAgentResult {
    status: AgentLifecycleStatus;
    permission: AgentPermissionRequest | null;
    lastMessage: string | null;
}
export interface WaitForAgentStartOptions {
    signal?: AbortSignal;
}
type AttentionState = {
    requiresAttention: false;
} | {
    requiresAttention: true;
    attentionReason: "finished" | "error" | "permission";
    attentionTimestamp: Date;
};
interface ManagedAgentBase {
    id: string;
    provider: AgentProvider;
    cwd: string;
    capabilities: AgentCapabilityFlags;
    config: AgentSessionConfig;
    runtimeInfo?: AgentRuntimeInfo;
    createdAt: Date;
    updatedAt: Date;
    availableModes: AgentMode[];
    features?: AgentFeature[];
    currentModeId: string | null;
    pendingPermissions: Map<string, AgentPermissionRequest>;
    bufferedPermissionResolutions: Map<string, Extract<AgentStreamEvent, {
        type: "permission_resolved";
    }>>;
    inFlightPermissionResponses: Set<string>;
    pendingReplacement: boolean;
    persistence: AgentPersistenceHandle | null;
    historyPrimed: boolean;
    lastUserMessageAt: Date | null;
    lastUsage?: AgentUsage;
    lastError?: string;
    attention: AttentionState;
    foregroundTurnWaiters: Set<ForegroundTurnWaiter>;
    finalizedForegroundTurnIds: Set<string>;
    unsubscribeSession: (() => void) | null;
    /**
     * Internal agents are hidden from listings and don't trigger notifications.
     */
    internal?: boolean;
    /**
     * User-defined labels for categorizing agents (e.g., { surface: "workspace" }).
     */
    labels: Record<string, string>;
}
type ManagedAgentWithSession = ManagedAgentBase & {
    session: AgentSession;
};
type ManagedAgentInitializing = ManagedAgentWithSession & {
    lifecycle: "initializing";
    activeForegroundTurnId: null;
};
type ManagedAgentIdle = ManagedAgentWithSession & {
    lifecycle: "idle";
    activeForegroundTurnId: null;
};
type ManagedAgentRunning = ManagedAgentWithSession & {
    lifecycle: "running";
    activeForegroundTurnId: string | null;
};
type ManagedAgentError = ManagedAgentWithSession & {
    lifecycle: "error";
    activeForegroundTurnId: null;
    lastError: string;
};
type ManagedAgentClosed = ManagedAgentBase & {
    lifecycle: "closed";
    session: null;
    activeForegroundTurnId: null;
};
export type ManagedAgent = ManagedAgentInitializing | ManagedAgentIdle | ManagedAgentRunning | ManagedAgentError | ManagedAgentClosed;
export interface AgentMetricsSnapshot {
    total: number;
    byLifecycle: Record<string, number>;
    withActiveForegroundTurn: number;
    timelineStats: {
        totalItems: number;
        maxItemsPerAgent: number;
    };
}
export declare class AgentManager {
    private readonly clients;
    private readonly providerEnabled;
    private readonly providerDerivedFromId;
    private readonly agents;
    private readonly timelineStore;
    private readonly agentsAwaitingInitialSnapshotPersist;
    private readonly sessionEventTails;
    private readonly foregroundRuns;
    private readonly subscribers;
    private readonly idFactory;
    private readonly registry?;
    private readonly durableTimelineStore?;
    private readonly previousStatuses;
    private readonly backgroundTasks;
    private readonly agentStreamCoalescer;
    private mcpBaseUrl;
    private appendSystemPrompt;
    private onAgentAttention?;
    private onAgentArchived?;
    private logger;
    private readonly rescueTimeouts;
    constructor(options: AgentManagerOptions);
    registerClient(provider: AgentProvider, client: AgentClient): void;
    updateProviderRegistry(input: {
        providerDefinitions: ProviderEnabledMap;
        clients: ProviderClientMap;
    }): void;
    getRegisteredProviderIds(): AgentProvider[];
    setAgentAttentionCallback(callback: AgentAttentionCallback): void;
    setAgentArchivedCallback(callback: AgentArchivedCallback): void;
    setMcpBaseUrl(url: string | null): void;
    setAppendSystemPrompt(prompt: string | null | undefined): void;
    getMetricsSnapshot(): AgentMetricsSnapshot;
    private touchUpdatedAt;
    private nextStoredUpdatedAt;
    hasInFlightRun(agentId: string): boolean;
    subscribe(callback: AgentSubscriber, options?: SubscribeOptions): () => void;
    listAgents(): ManagedAgent[];
    listImportablePersistedAgents(options?: ImportablePersistedAgentQueryOptions): Promise<PersistedAgentDescriptor[]>;
    private isProviderImportable;
    findPersistedAgent(provider: AgentProvider, sessionId: string, options?: Pick<ListPersistedAgentsOptions, "cwd">): Promise<PersistedAgentDescriptor | null>;
    listProviderAvailability(): Promise<ProviderAvailability[]>;
    listDraftCommands(config: AgentSessionConfig): Promise<AgentSlashCommand[]>;
    listDraftFeatures(config: AgentSessionConfig): Promise<AgentFeature[]>;
    getAgent(id: string): ManagedAgent | null;
    getTimeline(id: string): AgentTimelineItem[];
    getTimelineRows(id: string): Promise<AgentTimelineRow[]>;
    fetchTimeline(id: string, options?: AgentTimelineFetchOptions): AgentTimelineFetchResult;
    createAgent(config: AgentSessionConfig, agentId?: string, options?: {
        labels?: Record<string, string>;
        workspaceId?: string;
        initialPrompt?: string;
        env?: Record<string, string>;
        persistSession?: boolean;
        initialTitle?: string | null;
    }): Promise<ManagedAgent>;
    private buildCreateSessionOptions;
    resumeAgentFromPersistence(handle: AgentPersistenceHandle, overrides?: Partial<AgentSessionConfig>, agentId?: string, options?: {
        createdAt?: Date;
        updatedAt?: Date;
        lastUserMessageAt?: Date | null;
        labels?: Record<string, string>;
    }): Promise<ManagedAgent>;
    reloadAgentSession(agentId: string, overrides?: Partial<AgentSessionConfig>, options?: {
        rehydrateFromDisk?: boolean;
    }): Promise<ManagedAgent>;
    private closeReloadedSession;
    private waitWithTimeout;
    closeAgent(agentId: string): Promise<void>;
    archiveAgent(agentId: string): Promise<{
        archivedAt: string;
    }>;
    private cascadeArchiveChildren;
    private markRecordArchived;
    private fireAgentArchived;
    private dispatchArchivedStoredAgent;
    setAgentMode(agentId: string, modeId: string): Promise<void>;
    setAgentModel(agentId: string, modelId: string | null): Promise<void>;
    setAgentThinkingOption(agentId: string, thinkingOptionId: string | null): Promise<void>;
    setAgentFeature(agentId: string, featureId: string, value: unknown): Promise<void>;
    setTitle(agentId: string, title: string): Promise<void>;
    setGeneratedTitle(agentId: string, title: string): Promise<void>;
    setLabels(agentId: string, labels: Record<string, string>): Promise<void>;
    notifyAgentState(agentId: string): void;
    clearAgentAttention(agentId: string): Promise<void>;
    archiveSnapshot(agentId: string, archivedAt: string): Promise<StoredAgentRecord>;
    unarchiveSnapshot(agentId: string): Promise<boolean>;
    unarchiveSnapshotByHandle(handle: AgentPersistenceHandle): Promise<void>;
    updateAgentMetadata(agentId: string, updates: {
        title?: string;
        labels?: Record<string, string>;
    }): Promise<void>;
    runAgent(agentId: string, prompt: AgentPromptInput, options?: AgentRunOptions): Promise<AgentRunResult>;
    /**
     * Try to run a prompt out-of-band — i.e. without allocating a foreground turn
     * and without canceling any active turn. Returns true when the session
     * accepted the prompt as a side-effect command (e.g. /goal pause). Events
     * emitted by the handler flow through dispatchStream so they persist and
     * broadcast like normal timeline events.
     */
    tryRunOutOfBand(agentId: string, prompt: AgentPromptInput): boolean;
    appendTimelineItem(agentId: string, item: AgentTimelineItem): Promise<void>;
    emitLiveTimelineItem(agentId: string, item: AgentTimelineItem): Promise<void>;
    streamAgent(agentId: string, prompt: AgentPromptInput, options?: AgentRunOptions): AsyncGenerator<AgentStreamEvent>;
    private finalizeForegroundTurn;
    replaceAgentRun(agentId: string, prompt: AgentPromptInput, options?: AgentRunOptions): AsyncGenerator<AgentStreamEvent>;
    waitForAgentRunStart(agentId: string, options?: WaitForAgentStartOptions): Promise<void>;
    respondToPermission(agentId: string, requestId: string, response: AgentPermissionResponse): Promise<AgentPermissionResult | void>;
    cancelAgentRun(agentId: string): Promise<boolean>;
    private interruptSession;
    getPendingPermissions(agentId: string): AgentPermissionRequest[];
    private peekPendingPermission;
    /**
     * Hydrates the timeline from provider history if the agent's durable
     * timeline is empty (e.g., imported agents that have provider history
     * on disk but no persisted timeline rows). No-ops if already hydrated.
     */
    hydrateTimelineFromProvider(agentId: string, options?: HydrateTimelineOptions): Promise<void>;
    rewind(agentId: string, messageId: string, mode: RewindMode): Promise<void>;
    deleteCommittedTimeline(agentId: string): Promise<void>;
    getLastAssistantMessage(agentId: string): Promise<string | null>;
    private getLastAssistantMessageFromTimeline;
    private getLastAssistantMessageSegmentFromTimeline;
    private getLastAssistantMessageFromStores;
    private getLastItemFromStores;
    waitForAgentEvent(agentId: string, options?: WaitForAgentOptions): Promise<WaitForAgentResult>;
    private registerSession;
    private initializeAgentTimelineForRegister;
    private buildManagedAgentForRegister;
    private loadCommittedTimelineSeed;
    private prepareAgentForClosure;
    private emitClosedAgent;
    private subscribeToSession;
    private enqueueSessionEvent;
    private dispatchSessionEvent;
    private resolveInitialPersistedTitle;
    private persistSnapshot;
    private requireRegistry;
    private refreshSessionState;
    private refreshRuntimeInfo;
    private hydrateTimelineFromLegacyProviderHistory;
    private notifyForegroundTurnWaiters;
    private handleStreamEvent;
    private traceHandleStreamEventStart;
    private traceCoalescerBuffered;
    private traceHandleStreamEventEnd;
    private dispatchStreamEventByType;
    private onStreamThreadStarted;
    private onStreamTimelineEvent;
    private onStreamTurnCompleted;
    private onStreamTurnFailed;
    private onStreamTurnCanceled;
    private onStreamTurnStarted;
    private onStreamPermissionRequested;
    private onStreamPermissionResolved;
    private resolvePendingPermissionsForAgent;
    private recordAndDispatchTimelineItem;
    private appendSystemErrorTimelineMessage;
    private formatTurnFailedMessage;
    private recordTimeline;
    private emitState;
    private syncFeaturesFromSession;
    private checkAndSetAttention;
    private enqueueBackgroundPersist;
    private enqueueDurableTimelineAppend;
    private enqueueDurableTimelineBulkInsert;
    private trackBackgroundTask;
    /**
     * Flush any background persistence work (best-effort).
     * Used by daemon shutdown paths to avoid unhandled rejections after cleanup.
     */
    flush(): Promise<void>;
    private broadcastAgentAttention;
    private dispatchStream;
    private dispatch;
    private normalizeConfig;
    private applyDaemonAppendSystemPrompt;
    private buildLaunchContext;
    private requireAvailableClient;
    private requireEnabledProvider;
    private getConfiguredProviderIds;
    private requireClient;
    archiveNativeSessionBestEffort(provider: AgentProvider, persistence: AgentPersistenceHandle | null | undefined): Promise<void>;
    private requireAgent;
    private requireSessionAgent;
}
//# sourceMappingURL=agent-manager.d.ts.map