import type { ConversationManager } from './conversation.js';
import type { ToolRegistry } from '../tools/registry.js';
import type { HookEvent, HookResult } from '../hooks/types.js';
import type { ContentPart } from '../providers/interface.js';
import type { PermissionManager } from '../permissions/manager.js';
import type { AcpManager } from '../acp/manager.js';
import { type ConversationFollowUpItem } from './conversation-follow-ups.js';
import { AgentManager } from '../tools/agent/index.js';
import { WrfcController } from '../agents/wrfc-controller.js';
import type { FeatureFlagManager } from '../runtime/feature-flags/manager.js';
import type { RuntimeEventBus, TurnInputOrigin } from '../runtime/events/index.js';
import { type OrchestratorCoreServices } from './orchestrator-runtime.js';
/** Minimal interface for hook dispatch — allows any hook dispatcher implementation */
interface HookDispatcherLike {
    fire(event: HookEvent): Promise<HookResult>;
}
interface LowPrioritySystemMessageSink {
    low(message: string): void;
}
export interface OrchestratorUserInputOptions {
    readonly origin?: TurnInputOrigin | undefined;
}
/**
 * Options for constructing an {@link Orchestrator}.
 *
 * @example
 * ```ts
 * const orchestrator = new Orchestrator({
 *   conversation,
 *   getViewportHeight: () => window.innerHeight,
 *   scrollToEnd: (vHeight) => scrollContainer.scrollTo({ top: vHeight }),
 *   toolRegistry,
 *   permissionManager,
 *   getSystemPrompt: () => mySystemPrompt,
 *   hookDispatcher,
 *   flagManager,
 *   requestRender: () => renderFn(),
 *   runtimeBus,
 *   services: { agentManager, wrfcController },
 * });
 * ```
 */
export interface OrchestratorOptions {
    /** Manages the conversation message history. */
    conversation: ConversationManager;
    /** Returns the current viewport height in rows/px for scrolling calculations. */
    getViewportHeight: () => number;
    /** Scrolls the UI to the given viewport height after a turn. */
    scrollToEnd: (vHeight: number) => void;
    /** Registry of all available tools. */
    toolRegistry: ToolRegistry;
    /** Manages tool-use permission grants and denials. */
    permissionManager: PermissionManager;
    /** Returns the current system prompt text. Defaults to `() => ''`. */
    getSystemPrompt?: (() => string) | undefined;
    /** Optional hook dispatcher for lifecycle events. */
    hookDispatcher?: HookDispatcherLike | null | undefined;
    /** Optional feature flag manager. */
    flagManager?: FeatureFlagManager | null | undefined;
    /** Optional render request callback, called after state changes requiring a redraw. */
    requestRender?: (() => void) | null | undefined;
    /** Optional runtime event bus for cross-system event propagation. */
    runtimeBus?: RuntimeEventBus | null | undefined;
    /**
     * Stable session id used in runtime events, hook events, idempotency keys,
     * plans, and reply correlation. Defaults to a generated private id.
     */
    sessionId?: string | undefined;
    /** Required runtime service dependencies. */
    services: {
        readonly agentManager: Pick<AgentManager, 'list' | 'spawn'>;
        readonly wrfcController: Pick<WrfcController, 'listChains'>;
    };
}
/**
 * Orchestrator - Manages LLM turn lifecycle with full tool-use loop.
 * Supports multi-turn agent loops: call LLM -> execute tools -> send results -> repeat.
 */
export declare class Orchestrator {
    isThinking: boolean;
    thinkingFrame: number;
    usage: {
        input: number;
        output: number;
        cacheRead: number;
        cacheWrite: number;
    };
    /**
     * Input tokens from the most recent LLM response — represents current context window usage.
     * Includes cache read/write tokens for accurate context window occupancy.
     * Value is 0 before the first LLM response (context bar shows empty, which is correct).
     */
    lastInputTokens: number;
    /** Fresh input tokens from the most recent turn (excluding cache-read reuse where applicable). */
    lastRequestInputTokens: number;
    /** Approximate input tokens for the current streaming turn (from prior turn's response). */
    streamingInputTokens: number;
    /** Output tokens received so far in the current streaming turn (one per delta chunk). */
    streamingOutputTokens: number;
    messageQueue: {
        text: string;
        content?: ContentPart[] | undefined;
        options?: OrchestratorUserInputOptions | undefined;
    }[];
    private animInterval;
    private abortController;
    private autoSpawnTimeout;
    private acpManager;
    /** Message count at the start of a turn, used to rollback on cancel. */
    private turnStartMessageCount;
    /** Whether a streaming block is currently active (for cleanup on abort). */
    private isStreaming;
    /** Last token warning bracket (multiples of 10%) to avoid repeat warnings at same level. */
    private lastWarningBracket;
    /** Whether auto-compaction is currently in progress (prevents re-entry). */
    private isCompacting;
    /** Session ID for runtime and hook events. */
    private readonly sessionId;
    /**
     * Submission key for the currently active turn.
     *
     * Generated at the start of each `runTurn` call and used as the idempotency
     * key for the turn-level deduplication fence. A duplicate `runTurn` call with
     * the same text that arrives while a turn is still in-flight will be detected
     * via the shared `idempotencyStore` and rejected before re-executing.
     *
     * The key is reset to `null` when the turn completes.
     */
    currentSubmissionKey: string | null;
    /**
     * Tracks whether the current turn ended in failure.
     * Set to `true` in the catch block; read in `finally` to decide markComplete vs markFailed.
     */
    private _turnFailed;
    /** Event replay queue — ensures model acknowledges significant events */
    private readonly replayQueue;
    /** Cleanup function returned by the active replay queue attachment. */
    private detachReplay;
    private readonly runtimeBus;
    private readonly agentManager;
    private readonly wrfcController;
    private coreServices;
    private readonly ownedSessionLineageTracker;
    private readonly ownedIdempotencyStore;
    private readonly ownedCacheHitTracker;
    /**
     * Optional feature flag manager.
     *
     * When provided, the `tool-result-reconciliation` flag is
     * consulted at each turn end to decide whether to use full reconciliation
     * (`enabled`) or skip reconciliation (`disabled`).
     * When `null`, reconciliation defaults to enabled (matching the flag's
     * declared `defaultState`).
     */
    private flagManager;
    /**
     * Tracks the last provider response's tool calls within the current turn
     * iteration so the reconciliation pass can detect unresolved calls when
     * the loop exits early.
     */
    private _pendingToolCalls;
    private readonly requestRender;
    private systemMessageRouter;
    private readonly followUpRuntime;
    private conversation;
    private getViewportHeight;
    private scrollToEnd;
    private toolRegistry;
    private permissionManager;
    private getSystemPrompt;
    private hookDispatcher;
    /**
     * Construct an Orchestrator using a named-options object.
     *
     * @example
     * ```ts
     * const orchestrator = new Orchestrator({
     *   conversation,
     *   getViewportHeight: () => terminalRows,
     *   scrollToEnd: (vHeight) => ui.scrollToEnd(vHeight),
     *   toolRegistry,
     *   permissionManager,
     *   getSystemPrompt: () => systemPrompt,
     *   hookDispatcher,
     *   flagManager,
     *   requestRender: () => render(),
     *   runtimeBus,
     *   services: { agentManager, wrfcController },
     * });
     * ```
     */
    constructor(options: OrchestratorOptions);
    setCoreServices(services: OrchestratorCoreServices): void;
    /**
     * Attach an AcpManager and register the 'delegate' tool into the ToolRegistry.
     * Call this after construction, before the first turn.
     */
    registerDelegateTool(manager: AcpManager): void;
    getSpinner(): string;
    setSystemMessageRouter(router: LowPrioritySystemMessageSink | null): void;
    enqueueConversationFollowUp(item: ConversationFollowUpItem): void;
    /** Abort the current in-flight LLM request, if any. */
    abort(): void;
    /**
     * Dispose long-lived runtime attachments owned by this orchestrator.
     *
     * Safe to call multiple times. Intended for process shutdown and tests that
     * construct transient orchestrators against a shared RuntimeEventBus.
     */
    dispose(): void;
    /**
     * handleUserInput - Entry point for a user-submitted message.
     * Queues if already thinking, otherwise kicks off the LLM turn.
     * @param text - Plain text representation (for display and queuing).
     * @param content - Optional ContentPart[] for multimodal messages.
     * @param options - Optional origin metadata for external surfaces.
     */
    handleUserInput(text: string, content?: ContentPart[], options?: OrchestratorUserInputOptions | undefined): Promise<void>;
    private startThinking;
    private stopThinking;
    private runTurn;
    /** Phase 1: Idempotency fence, event emission, adaptive planner, plan injection, thinking start.
     *  Returns null when the turn is a duplicate in-flight submission that should not execute. */
    private runTurnPreflight;
    /** Phase 2: Execute the LLM streaming loop and tool dispatch. */
    private runTurnStream;
    /** Phase 3: Post-turn context maintenance (compaction, memory, plan updates). */
    private runTurnReconcile;
    /** Catch handler: route to abort path or error path. */
    private handleTurnError;
    /** Finally handler: tool-call reconciliation, submission key finalization, notifications, replay queue. */
    private finalizeTurn;
    /**
     * Pre-flight context window check.
     *
     * Estimates the token count of the pending request and compares it against
     * the model's context window from the catalog. If the request exceeds the
     * context window:
     *   1. If auto-compact is enabled (threshold configured), compact first.
     *   2. If still exceeds after compact, emit a clear error message with
     *      specific token counts and suggest alternatives.
     *
     * @returns 'ok' (within context), 'compacted' (compacted and now OK), or
     *          'error' (still exceeds even after compact, or compact disabled).
     */
    private checkContextWindowPreflight;
    /**
     * Auto-spawn agents for a list of ready plan items under bounded orchestration policy.
     */
    private autoSpawnPendingItems;
    /**
     * Returns `true` when the GC-ORCH-015 reconciliation feature is active.
     *
     * Defaults to `true` (flag `defaultState: 'enabled'`) when no flag manager
     * has been wired in — safe for tests that omit the optional constructor arg.
     */
    private isReconciliationEnabled;
    /**
     * Reconcile unresolved tool calls at turn end.
     *
     * Called when the turn loop exits while `_pendingToolCalls` is non-empty,
     * or when a malformed provider response is detected. Injects synthetic error
     * results for every unresolved call, adds a system message, and emits a
     * typed `TOOL_RECONCILED` runtime event.
     *
     * When the feature flag is disabled this method logs a warning and returns
     * without taking action.
     *
     * @param resolvedResults - Tool results already collected this iteration.
     * @param reason          - Why reconciliation was triggered.
     */
    private reconcileUnresolvedToolCalls;
    private executeToolCalls;
}
export {};
//# sourceMappingURL=orchestrator.d.ts.map