import type { AIProviderRegistry, ChatAttachment, ChatDriverResult, ChatMessage, ChatToolChoice, InteractionRequestOptions, SubAgentFailureReason } from '@genesislcap/foundation-ai';
import { type ActivityBus } from '../../channel/ai-activity-bus';
import type { AgentConfig, SystemPromptInput, ToolDefinitionsInput, ToolHandlersInput } from '../../config/config';
import type { DiagnosticEntry } from '../../state/persistence/diagnostics';
import type { InteractionContext } from '../../types/interaction-context';
import type { AiDriver, AllAgentSummary } from '../ai-driver/ai-driver';
/** Name reserved for the cross-agent handoff tool — injected by OrchestratingDriver. */
export declare const REQUEST_CONTINUATION_TOOL = "request_continuation";
/**
 * Event emitted when the chat history is updated (new message appended).
 *
 * @beta
 */
export type ChatHistoryUpdatedEvent = CustomEvent<ReadonlyArray<ChatMessage>>;
/**
 * One captured frame of what the LLM saw on a single tool-loop iteration.
 * The driver records these as a ring buffer (cap: configurable via
 * `chatConfig.agent.maxTurnSnapshots`, default 400) so the export log can show,
 * per turn: which agent was active, the resolved system prompt, the tool names
 * visible to the LLM, and any agent-supplied debug snapshot (e.g. machine
 * state for stateful agents).
 *
 * @beta
 */
export interface TurnSnapshot {
    /**
     * Turn identifier, always a string. A driver's own turns are the bare counter
     * (`"0"`, `"1"`, … — monotonic, does not reset on agent swap). Turns forwarded
     * up from a sub-agent are re-labelled under the parent turn that activated them
     * — a sub-agent invoked on parent turn 5 contributes `"5-1"`, `"5-2"`, …, and a
     * nested sub-agent on `"5-2"` contributes `"5-2-1"`, …. See
     * `forwardSubAgentSnapshots`.
     */
    turnIndex: string;
    /** ISO timestamp captured just before the LLM call. */
    timestamp: string;
    /** Name of the agent active when this LLM call ran. */
    agentName?: string;
    /**
     * The agent's resolved system prompt sent to the LLM, verbatim. NOTE: this is
     * now the *bare* prompt — the fold-surface suffix and the malformed/empty retry
     * nudge no longer mutate it (they kept it byte-unstable and busted prompt
     * caching), so they moved to {@link TurnSnapshot.tailContext}. To reconstruct
     * exactly what the model saw, read both fields.
     */
    systemPrompt?: string;
    /**
     * The framed `<system-reminder>` tail appended to the final user turn for this
     * call, verbatim — never part of stored history, so this snapshot is the only
     * record of it. Carries the framework's volatile additions (fold suffix, retry
     * nudge) and the agent's per-turn `tailContext` (e.g. current file spec, live
     * diagnostics). Undefined when the tail was empty (the normal case).
     */
    tailContext?: string;
    /** Tool names sent to the LLM, in order — definitions are static per name so names alone suffice. */
    toolNames: string[];
    /**
     * Normalized `0`–`1` sampling temperature in effect for this call, if the
     * agent (or its current state) configured one. Undefined → provider/model
     * default. Mirrors the value resolved from `BaseAgentConfig.temperature`.
     */
    temperature?: number;
    /**
     * Tool-call mode actually sent to the provider this call — the effective
     * value, including the sub-agent `'required'` default. Undefined → `'auto'`.
     * Mirrors the value resolved from `BaseAgentConfig.toolChoice`.
     */
    toolChoice?: ChatToolChoice;
    /**
     * Per-turn display label resolved from the agent's `displayName`, e.g.
     * "Guided Booking (Counterparties)". `agentName` stays as the canonical
     * identity used for routing/filtering.
     */
    agentLabel?: string;
    /** Agent-supplied snapshot — machine state/context for stateful agents, undefined otherwise. */
    agentSnapshot?: unknown;
}
/**
 * Construction-time configuration for {@link ChatDriver}. Everything except the provider
 * registry is optional — most fields are also settable per-agent via `applyAgent`, so a
 * bare `new ChatDriver(registry)` is valid. Mirrors the `(registry, options)` shape of
 * `OrchestratingDriver`.
 *
 * @beta
 */
export interface ChatDriverConfig {
    /** Initial tool handlers (static map or per-turn factory). Default `{}`. */
    toolHandlers?: ToolHandlersInput;
    /** Initial tool definitions (static array or per-turn factory). Default `[]`. */
    toolDefinitions?: ToolDefinitionsInput;
    /** Initial system prompt (string or per-turn resolver). */
    systemPrompt?: SystemPromptInput;
    /** Primer history prepended to the conversation. */
    primerHistory?: ChatMessage[];
    /** Hard cap on tool-loop iterations. Default `50`. */
    maxToolIterations?: number;
    /** Hard cap on fold operations. Default `5`. */
    maxFoldOperations?: number;
    /** Ring-buffer size for per-turn snapshots. Default `400`. */
    maxTurnSnapshots?: number;
    /** Session identity used to file meta events onto the shared debug-log timeline. */
    sessionKey?: string;
    /**
     * Activity bus for lifecycle/halo/tool-loop events. Injected by the browser host
     * (the shared cross-tab singleton); omitted off-browser (Node, tests, headless), where
     * it defaults to {@link NOOP_ACTIVITY_BUS} so no `BroadcastChannel` is ever opened.
     */
    activityBus?: ActivityBus;
}
/**
 * Plain TS class that drives a multi-turn chat conversation, including the tool-call loop.
 * Owned by `FoundationAiAssistant` — created in `connectedCallback`, torn down in `disconnectedCallback`.
 *
 * Dispatches `'history-updated'` events on itself so the owning element can observe changes.
 *
 * @fires history-updated - Fired whenever the in-memory chat history changes (append, tool loop, interaction resolution) with the full history snapshot. detail: `ReadonlyArray<ChatMessage>`
 *
 * @beta
 */
export declare class ChatDriver extends EventTarget implements AiDriver {
    private readonly providerRegistry;
    private history;
    private busy;
    /** Epoch ms when the current turn loop began — drives the `turn.end` duration. */
    private turnStartedAt;
    private pendingInteractions;
    /**
     * Live per-interaction contexts (GENC-1390), keyed by interactionId. Created in
     * `requestInteraction` alongside the pending entry, disposed + removed in
     * `resolveInteraction`. Non-serialisable (sockets, timers, subscriber sets), so
     * they live here on the driver — not on the DOM, not in the persisted store — and
     * therefore survive the element remounts (layout reflow/drag, transcript
     * re-render) that this feature exists to make harmless. At most one is live at a
     * time (see the one-interaction-at-a-time guard in `requestInteraction`).
     */
    private interactionContexts;
    private systemPrompt?;
    /**
     * Resolved tool definitions visible to the LLM. Folds mutate this in place
     * (push/pop on open/close). When `toolDefinitionsFactory` is set, this is
     * overwritten each tool-loop iteration with the factory's output.
     */
    private toolDefinitions;
    /**
     * Optional dynamic-tools source. When set, called each tool-loop iteration
     * to recompute `toolDefinitions` before the LLM call. `defineStatefulAgent`
     * forbids folds when this is set, so the fold-mutation path is unreachable
     * in that case.
     */
    private toolDefinitionsFactory?;
    /**
     * Resolved tool handler map used for dispatch. When `toolHandlersFactory` is
     * set, this is overwritten each tool-loop iteration with the factory's output
     * — keeping it in lockstep with `toolDefinitions` so handlers don't have to
     * defend themselves against being dispatched in states where their tool
     * isn't advertised. Folds mutate this in place; `defineStatefulAgent`
     * forbids folds when a factory is set, so the fold-mutation path is
     * unreachable in that case.
     */
    private toolHandlers;
    /**
     * Optional per-turn handler-map source. Mirrors `toolDefinitionsFactory` so
     * the LLM-visible tools and the dispatchable handlers can be narrowed in
     * lockstep. Resolved each tool-loop iteration before the LLM call.
     */
    private toolHandlersFactory?;
    private primerHistory?;
    private activeAgentName?;
    /**
     * Per-turn display label resolved from the agent's `displayName`. Stamped
     * onto outgoing messages and turn snapshots for UX; `activeAgentName` stays
     * stable for routing/history-transform identity matching.
     */
    private activeAgentLabel?;
    private displayName?;
    /**
     * When set, `requestInteraction` delegates to this callback instead of using
     * this driver's own pending map. Wired by `invokeSubAgent` so a sub-agent's
     * widget renders in — and resolves through — the parent (ultimately the
     * root) driver, where the main UI is listening.
     */
    private hostInteractionRequester?;
    /**
     * When set (e.g. by OrchestratingDriver), applied only to the conversation slice
     * sent to the model — stored `history` stays unchanged for UI and logging.
     */
    private providerHistoryTransform?;
    /**
     * Tool-declared condensation policies, keyed by tool-call id. Populated by
     * `condenseWhen` (first-wins per call); read by `applyCondensation` before each
     * provider call to collapse stale payloads from the model-bound history only.
     * Accumulates across agents on a shared driver (a superseded read collapses no
     * matter which agent made it) and is never cleared — it dies with the driver.
     */
    private readonly condensePolicies;
    /**
     * Monotonic model-call counter for the driver's whole lifetime — the age clock
     * for `condenseWhen({ on: { kind: 'age' } })`. The per-`sendMessage` `iterations`
     * loop counter resets to 0 every turn, so it can only measure age WITHIN a
     * single turn; this never resets, so `age` counts model-calls since the result
     * appeared across turn boundaries (each short turn still advances it ≥ 1).
     * Bumped once per tool-loop iteration (provider call).
     */
    private modelCallSeq;
    /**
     * Monotonic turn counter — the `turnEnd` clock. Bumped once per `sendMessage`
     * (a user turn; NOT per handoff continuation, which is the same request), never
     * reset. `turnEnd` collapses a payload once `turnSeq` exceeds the turn it was
     * created in.
     */
    private turnSeq;
    /**
     * Monotonic agent-activation counter — the `agentEnd` clock. Advances when the
     * active flow ends: a swap to a different-named agent (`applyAgent`) OR an
     * explicit `releaseAgent` / `completeSubAgent`. A stateful agent re-resolving
     * the same name across turns keeps one activation. `agentEnd` fires for a
     * payload once a LATER activation is current (`callActivation < currentActivation`)
     * — so a re-run of a released agent gets a fresh activation and is NOT
     * collapsed until IT ends.
     */
    private currentActivation;
    /**
     * Monotonic phase-epoch counter — the `phaseEnd` clock. Advanced by the
     * handler-context `endPhase()` (an app-declared phase boundary within one
     * activation), never reset. Unlike `currentActivation` it is NOT tied to agent
     * swaps or releases — it ticks only when the agent itself declares a phase
     * done. `phaseEnd` fires for a payload once a LATER epoch is current
     * (`callPhaseEpoch < currentPhaseEpoch`), with an `agentEnd` backstop.
     */
    private currentPhaseEpoch;
    /** Stack of fold frames — grows when a fold opens, shrinks when it closes. */
    private foldStack;
    /** Consecutive fold open/close ops without a real tool call. Reset on real tool execution. */
    private consecutiveFoldOps;
    /** Consecutive unknown-tool calls without a real tool call. Reset on real tool execution. */
    private consecutiveUnknownToolCalls;
    /**
     * Distinct unknown-tool names seen in the current consecutive streak — stamped
     * onto the `unknown-tool-limit` turn.error so a triager knows which tools were
     * hallucinated. Reset alongside `consecutiveUnknownToolCalls`.
     */
    private readonly recentUnknownToolNames;
    /**
     * Union of every tool name advertised at any point during the current agent
     * activation. Lets the unknown-tool path tell a *stale* call (a real tool from
     * an earlier state, now retired — or one an open exclusive fold is hiding)
     * apart from a *hallucinated* one. Reset on agent swap in `applyAgent`.
     */
    private readonly everSeenToolNames;
    /**
     * Subset of the current unknown-tool streak that was stale (previously
     * available) rather than hallucinated — surfaced separately on the
     * `unknown-tool-limit` turn.error so triage can tell a state/prompt-design
     * problem from a model that's inventing tools. Reset alongside
     * `recentUnknownToolNames`.
     */
    private readonly recentStaleToolNames;
    private readonly maxFoldOperations;
    /** Sub-agents declared on the active agent config, keyed by name. */
    private subAgentsMap;
    /**
     * Set by `completeSubAgent` inside a sub-agent tool handler. Checked at the
     * same point in the loop as `REQUEST_CONTINUATION_TOOL` — after tool results
     * are appended — so the exit path mirrors the system-call pattern.
     * `undefined` means the loop has not been stopped early.
     */
    private subAgentCompletion;
    /**
     * True when this driver runs as a child sub-agent (created by a parent
     * driver's `invokeSubAgent`). Sub-agents force tool use every turn so a turn
     * can only end via their completion tool, and on any non-completion exit they
     * record a typed `SubAgentFailureReason` instead of appending a
     * user-facing message — the parent decides how to surface the failure.
     */
    private isSubAgent;
    /**
     * Set when a sub-agent's tool loop ends without `completeSubAgent` being
     * called. Read by the parent's `invokeSubAgent` to build the `{ ok: false }`
     * branch of `requestSubAgent`. Only ever set when `isSubAgent` is true.
     */
    private subAgentFailure;
    /**
     * Set by `releaseAgent` inside a top-level tool handler — typically a stateful
     * agent's terminal-state handler signalling that its flow is complete and the
     * auto-pin lock can release. Checked by the orchestrator after `sendMessage`
     * returns; the orchestrator fires `onDeactivate` and clears the pin.
     *
     * Reset at the start of each `sendMessage` so a release from a previous turn
     * doesn't leak forward.
     */
    private agentReleaseRequested;
    /**
     * Ring buffer of per-LLM-call snapshots. Cap is configurable via
     * `chatConfig.agent.maxTurnSnapshots`; older entries drop off as new ones
     * arrive. See {@link TurnSnapshot} for the captured shape.
     */
    private turnSnapshots;
    /**
     * `turn` + `message` diagnostic-log entries harvested from an out-of-band source (a resolved
     * interaction whose widget returned `InteractionResult.diagnostics` — e.g. a server-side
     * ChatDriver's debug log). `event` entries are NOT kept here — they're folded into the session's
     * meta-event registry via `mergeMetaEvents` (see `resolveInteraction`) so they inherit fresh host
     * indices, and reach the log through `getMetaEvents`. Append-only; the host folds these into its
     * debug log alongside this driver's own timeline. Not cleared here — it lives with the driver
     * instance, like `turnSnapshots`, so a new chat (fresh driver) starts empty while a compaction
     * (same instance) keeps it. (GENC-1461.)
     */
    private readonly externalDiagnostics;
    /**
     * Monotonic count of external-diagnostics batches harvested this driver-lifetime. Namespaces each
     * batch's re-keyed `turn` entries so distinct server generations in one chat session can't collide
     * on `turnIndex` in the forward-capture persister (which dedups turns by that key). (GENC-1461.)
     */
    private externalDiagnosticsBatches;
    /** Monotonic counter that survives agent swaps — useful for cross-referencing with history. */
    private globalTurnIndex;
    /** Captured from `applyAgent` so we don't store the whole `AgentConfig`. */
    private debugSnapshotter?;
    private readonly maxTurnSnapshots;
    /**
     * Aborted by `dispose()` on driver teardown (e.g. an agent-config swap).
     * Threaded into every provider call as `ChatRequestOptions.signal`, so a
     * disposed driver's in-flight LLM request is cancelled instead of running on
     * to completion or the transport timeout. Also passed to prompt/tool
     * factories via `SystemPromptContext.signal`.
     */
    private readonly lifecycleController;
    /**
     * Per-turn abort controller, reset at the start of every turn by `beginTurn`.
     * Aborted by `cancel()` (user stop) and chained to `lifecycleController` so a
     * driver dispose also ends the current turn. Its signal — not the lifecycle
     * one — is what reaches the provider call, so a turn can be cancelled without
     * bricking the driver for the next message.
     */
    private turnController;
    /** True when the current turn was stopped via `cancel()` (vs a dispose). Drives the "Stopped." marker. */
    private turnCancelled;
    /** Detaches the lifecycle→turn abort link at turn end; set by `beginTurn`. */
    private unlinkLifecycleFromTurn?;
    /**
     * Active agent's provider selector (static name or per-turn resolver).
     * `undefined` means "use the registry default".
     */
    private activeProviderInput?;
    /**
     * Active agent's temperature selector (static number or per-turn resolver),
     * normalized to `0`–`1`. `undefined` means "use the provider/model default".
     */
    private activeTemperatureInput?;
    /**
     * Active agent's tool-call mode selector (static value or per-turn resolver).
     * `undefined` falls back to the per-turn default (sub-agents force a tool
     * call; top-level turns are `'auto'`).
     */
    private activeToolChoiceInput?;
    /**
     * Active agent's prompt-cache policy selector (static value or per-turn resolver).
     * `undefined` requests no caching (equivalent to `{ scope: 'default' }`).
     */
    private activeCachePolicyInput?;
    /**
     * Active agent's tail-context selector (static value or per-turn resolver). The driver frames
     * the resolved string in a `<system-reminder>` marker and injects it at the message tail.
     */
    private activeTailContextInput?;
    /**
     * Active agent's structured-output schema selector (static value or per-turn resolver).
     * When it resolves to a schema, the model's final answer is constrained to it this turn.
     */
    private activeResponseSchemaInput?;
    /**
     * Active agent's refusal-fallback chain (static). Passed through to the provider so a refused
     * turn (e.g. Fable 5) is re-run on the next model server-side.
     */
    private activeFallbacks?;
    /**
     * Active agent's unresolved-tool hook, captured from `applyAgent`. Consulted
     * only when a tool call cannot be dispatched (a stale or hallucinated name);
     * `undefined` keeps the framework's default messages. See
     * `resolveUnresolvedToolContent`.
     */
    private activeOnUnresolvedTool?;
    /**
     * Caches validated provider lookups per name within the current agent. Cleared
     * by `applyAgent` so each new agent's static/function-resolved names are
     * validated fresh.
     */
    private resolvedProviderCache;
    /** Last successfully resolved provider name — drives `getActiveProviderName`. */
    private lastResolvedProviderName?;
    /** Last dispatched `provider-changed` name; avoids duplicate events on stable turns. */
    private lastDispatchedProviderName?;
    /**
     * Concrete model id of the provider resolved for the current turn, read from
     * its `getStatus()` and stamped onto the resulting assistant message so the
     * debug log carries per-message model lineage. Re-resolved each turn in
     * `resolveProviderForTurn`.
     */
    private lastResolvedModel?;
    /**
     * Vendor id from the provider's `getStatus()` for the current turn (e.g.
     * `'anthropic'`, `'gemini'`). Stamped onto assistant messages alongside
     * `lastResolvedModel`.
     */
    private lastResolvedProvider?;
    /**
     * Memoised `name → getStatus()` lookups, so per-turn resolution doesn't
     * re-await `getStatus()` every turn. Cleared (with `resolvedProviderCache`) on
     * an observable-registry change, so a model swapped behind a stable name is
     * picked up on the next turn.
     */
    private resolvedStatusCache;
    /**
     * Unsubscribe handle for the provider-registry change listener (only set when
     * the injected registry is observable). Called in `dispose` so the long-lived
     * registry doesn't retain this driver — see the constructor and the sub-agent
     * teardown in `runSubAgent`.
     */
    private unsubscribeRegistry?;
    /** Hard cap on tool-loop iterations. */
    private readonly maxToolIterations;
    /** Session identity used to file meta events onto the shared debug-log timeline. */
    private readonly sessionKey;
    /** Injected activity bus; defaults to a no-op off-browser (Node/tests/headless). */
    private readonly activityBus;
    constructor(providerRegistry: AIProviderRegistry, config?: ChatDriverConfig);
    /**
     * Tear down the driver: aborts the lifecycle signal so any in-flight provider
     * request (and prompt/tool factories awaiting it) cancels instead of running
     * on to completion or the transport timeout. Called by the host on driver
     * swap and by `OrchestratingDriver.dispose()`. Idempotent.
     *
     * Deliberately does NOT settle `pendingInteractions` here: dispose is never
     * reached while one is pending. The only host-level dispose is the agent-swap
     * rebuild, which is guarded by `isBusy()` — a pending interaction keeps the
     * tool loop suspended (`busy === true`), so the swap is deferred until the
     * widget resolves. Sub-agent child disposes always have an empty pending map
     * (widgets park on the parent via `setHostInteractionRequester`). A pending
     * interaction is instead settled by `resolveInteraction` (user response or
     * timeout), which also stamps history and reverts the chat-input override.
     */
    dispose(): void;
    /**
     * Stop the current turn (user "stop" button). Aborts the in-flight provider
     * request immediately; if a tool is mid-execution it runs to completion and
     * the loop bails at the next boundary (tools are atomic). No-op when idle.
     * The driver stays usable for the next message.
     */
    cancel(): void;
    /**
     * Start a fresh per-turn abort scope. Chains `lifecycleController` into the
     * new `turnController` so a dispose mid-turn also aborts the request.
     */
    private beginTurn;
    /** Detach the lifecycle→turn link so a long-lived lifecycle signal doesn't accumulate listeners. */
    private endTurn;
    /**
     * Finish a turn whose signal aborted. A user cancel adds a subtle "Stopped."
     * marker; a dispose-driven abort stops quietly (the widget is gone and the
     * cached history would otherwise gain a stray marker on remount).
     */
    private completeAbortedTurn;
    /**
     * Build the `done` loop result, carrying the typed failure reason when the turn
     * bailed (PTC-0). The discriminant stays `'done'` either way — the same value a
     * clean turn returns — so consumers matching on `reason === 'done'` are unchanged;
     * `failureReason` is simply present on a failure and absent on success. Omitted
     * (rather than set to `undefined`) so a happy-path result stays byte-identical to
     * the historical `{ reason: 'done' }`.
     */
    private turnDone;
    /** The typed failure reason on a loop result, or `undefined` for a clean turn / handoff. */
    private static failureReasonOf;
    /**
     * Build the `tool-loop-end` event detail for a turn's result. A failure carries a
     * `{ failureReason }` detail; a clean turn emits `undefined` — the historical shape,
     * kept byte-identical so subscribers see exactly what they always have.
     */
    private static loopEndDetail;
    /**
     * Swap in a new agent's configuration. Called by OrchestratingDriver before
     * each specialist turn so the shared driver runs with the right tools and prompt.
     */
    applyAgent(config: AgentConfig): void;
    /**
     * Resolve the tool-result content for an unresolved tool call. Consults the
     * active agent's `onUnresolvedTool` hook (if any) with the attempted tool
     * name, the failure `kind`, and the currently dispatchable tools, and returns
     * the hook's non-empty string. Falls back to `fallback` when no hook is set,
     * the hook returns nothing/empty, or the hook throws — so a misbehaving hook
     * can never break tool dispatch.
     */
    private resolveUnresolvedToolContent;
    /**
     * Returns the most recently resolved provider name. Falls back to the
     * registry's default when no per-turn resolution has happened yet.
     */
    getActiveProviderName(): string;
    /**
     * Resolve a named provider against the registry. Cached per-agent so
     * repeated lookups during one agent's lifetime don't re-validate.
     * Validation lives in `resolveChatProvider`; this wrapper just adds the
     * cache.
     */
    private resolveProviderByName;
    /**
     * Resolve the provider to use for the current turn. Walks the agent's
     * `provider` selector (static or function form) or falls back to the
     * registry default. Dispatches `provider-changed` when the resolved name
     * differs from the last dispatched value.
     */
    private resolveProviderForTurn;
    /**
     * Resolve model id and vendor from a provider via its optional `getStatus()`,
     * memoised by registry name. Used to stamp `model` and `provider` onto outgoing
     * messages. Best-effort: a provider without `getStatus`, a null status, or a
     * throw all yield empty fields — attribution is diagnostic, never load-bearing.
     */
    private resolveStatusForProvider;
    /**
     * Resolve a per-turn config input that is either a static value or a function
     * of the turn context — the value-or-resolver shape shared by `provider`,
     * `temperature`, and `toolChoice`. Returns undefined when the input is unset.
     */
    private resolveTurnInput;
    /**
     * Returns the early-stop result set by `completeSubAgent`, if any.
     * Called by a parent `ChatDriver` after running this instance as a sub-agent.
     */
    getSubAgentCompletion(): {
        result: unknown;
    } | undefined;
    /**
     * Mark this driver as running as a sub-agent. Called by a parent driver's
     * `invokeSubAgent` immediately after construction, before the first turn.
     * Enables forced tool use and typed failure reporting (see `isSubAgent`).
     */
    markAsSubAgent(): void;
    /**
     * Returns the typed failure recorded when a sub-agent run ended without
     * `completeSubAgent`, if any. Called by a parent `ChatDriver` after running
     * this instance as a sub-agent.
     */
    getSubAgentFailure(): {
        reason: SubAgentFailureReason;
    } | undefined;
    /**
     * Record a sub-agent failure reason (first one wins). No-op for top-level
     * agents, so loop-exit sites can call it unconditionally. The parent reads
     * this via `getSubAgentFailure()` and emits the `subagent.failed` meta event
     * under its *own* session — see `invokeSubAgent`. (A child sub-agent runs
     * under a separate session key, so recording here would orphan the event off
     * the user-visible debug-log timeline.)
     */
    private failSubAgent;
    /**
     * Returns true if `releaseAgent` was called during the most recent turn.
     * Consumed by the orchestrator to trigger the auto-pin release path.
     */
    getAgentReleaseRequested(): boolean;
    /**
     * Return the per-turn snapshots captured so far. Used by the host's debug
     * log exporter to show what the LLM saw on each turn — system prompt, tool
     * surface, and agent-supplied state (e.g. a machine snapshot).
     *
     * Ring-buffered at `MAX_TURN_SNAPSHOTS`; older entries are dropped.
     */
    getTurnSnapshots(): ReadonlyArray<TurnSnapshot>;
    /**
     * The `turn` + `message` diagnostic-log entries harvested from resolved interactions'
     * `InteractionResult.diagnostics` (e.g. a server-side ChatDriver's collated debug log). The host
     * concatenates these into its own debug log so `downloadDebugLog`/the persisted diagnostics stream
     * include external-engine logs; `event` entries are excluded here because they're merged into the
     * session's meta-event registry instead (see `resolveInteraction`) and reach the log via
     * `getMetaEvents`. Opaque, chronologically sorted by the host at assemble time. (GENC-1461.)
     */
    getExternalDiagnostics(): ReadonlyArray<DiagnosticEntry>;
    /**
     * Merge a sub-agent's turn snapshots into this driver's buffer so they surface
     * as `kind:'turn'` entries in the exported debug log. The child runs as a
     * separate, discarded driver, so its snapshots would otherwise be lost. Each is
     * re-labelled under the parent turn that activated the sub-agent: the child's
     * own (numeric) turns become `"<parentTurn>-1"`, `"-2"`, … (1-based, in order);
     * any already-forwarded grand-child labels (strings) have their leading segment
     * remapped the same way, so nesting composes (`"5-2"` → `"5-2-1"`).
     *
     * Note: two sub-agents invoked in the *same* parent turn share the prefix, so
     * their labels can repeat — `agentName` on each snapshot disambiguates them.
     */
    private forwardSubAgentSnapshots;
    /**
     * Push one snapshot to the ring buffer. Called inside `runToolLoop` just
     * before each LLM call — that's the latest point where the prompt, tool
     * surface, and agent state line up with what the model is about to see.
     */
    private recordTurnSnapshot;
    /**
     * Optional transform applied to conversation history immediately before each LLM request.
     * Cleared when `undefined`. Does not alter stored history.
     */
    setProviderHistoryTransform(transform?: (history: ChatMessage[]) => ChatMessage[]): void;
    getHistory(): ReadonlyArray<ChatMessage>;
    getRawHistory(): readonly ChatMessage[];
    /** Returns the current fold stack names for debugging. */
    getActiveFoldNames(): string[];
    getSuggestions(history: ChatMessage[], prompt: string, count: number, allAgentInfo?: AllAgentSummary[]): Promise<string[]>;
    /**
     * Whether `compact()` would do anything right now — a summarizable run of older
     * turns exists behind a clean boundary. Uses the same `history` `compact()`
     * acts on, so the UI's gate can't disagree with the action (GENC-1351 follow-up).
     */
    canCompact(): boolean;
    /**
     * Destructively compact older turns into a single `compacted-summary` message
     * (GENC-1351 §5.7). Summarizes everything before a clean recent-tail boundary
     * via the registry-default provider's one-shot `prompt()`, then **atomically**
     * replaces the covered turns with one summary message at the head — history is
     * mutated only on success. Rolling: any existing head summary is folded into
     * the new one. Returns the created summary message, or `null` when there is
     * nothing worth compacting or the default provider cannot summarize.
     */
    compact(): Promise<ChatMessage | null>;
    isBusy(): boolean;
    /**
     * Wire a parent driver as the host for this driver's interactions. When set,
     * `requestInteraction` delegates upward so the widget renders in (and
     * resolves through) the parent's history and pending map. Calls chain
     * naturally: a grandchild → child → root.
     */
    setHostInteractionRequester(fn: <T>(componentName: string, data: any, options?: InteractionRequestOptions) => Promise<T>): void;
    /**
     * Request a custom UI interaction. Emits a new message with the interaction.
     * Tool handlers can call this to pause execution until the user completes the UI interaction.
     *
     * If a host requester is wired (sub-agent case), the call delegates upward
     * so the interaction lives on the parent — the main UI is only listening to
     * the root driver. Only one interaction may be in flight at any time on a
     * given root: concurrent calls (e.g. two parallel sub-agents both spawning a
     * widget) throw. Parallel sub-agents are for parallel work, not for user
     * interaction, which is inherently sequential.
     *
     * @param componentName - The custom element name to render.
     * @param data - Data to pass to the component.
     * @param options - Optional per-call overrides, including
     *   `chatInputDuringExecution` to hide or disable the main chat input while
     *   the widget is awaiting user input (reverts when the interaction resolves),
     *   and `presentation` to control whether the host wraps the widget in a chat
     *   bubble and/or shows the "Assistant" label.
     */
    requestInteraction<T>(componentName: string, data: any, options?: InteractionRequestOptions): Promise<T>;
    /**
     * Resolve a pending interaction. The wrapper component calls this on completion.
     * Marks the interaction message as resolved so it renders read-only on re-render.
     */
    resolveInteraction(interactionId: string, result: any): void;
    /**
     * The live {@link InteractionContext} for a pending interaction (GENC-1390), or
     * `undefined` once resolved/evicted. Read by `AiChatInteractionWrapper` (via the
     * host) to build the widget's pending `interaction` descriptor.
     */
    getInteractionContext(interactionId: string): InteractionContext | undefined;
    /**
     * Resolve every in-flight interaction with a `'timeout'` result, closing its
     * widget read-only. Used when a sub-agent that owns the open widget times out:
     * the widget is parked in *this* driver's map (interactions resolve on the
     * host, not the child), so cancelling it here unblocks the sub-agent handler
     * awaiting it. The "one interaction at a time" invariant means there is at
     * most one.
     */
    private cancelPendingInteractions;
    /**
     * Seeds the driver with a prior conversation history so a new component instance
     * can continue an existing conversation. Call this before the first user message.
     */
    loadHistory(messages: ChatMessage[]): void;
    sendMessage(userInput: string, attachments?: ChatAttachment[]): Promise<ChatDriverResult>;
    /**
     * Builds the context object passed to every tool handler call.
     * Centralised here so fold shortcut dispatch and the main tool loop use the
     * same context without duplication.
     *
     * @param activeToolCallId - The id of the tool call this context belongs to, so
     *   `condenseWhen` can register against the right call (it stamps the clocks
     *   straight off the driver). Absent for dispatch paths with no addressable tool
     *   call (e.g. the fold-close handler), where `condenseWhen` is a no-op.
     * @param traceCapture - Optional per-invocation slot. When provided, the trace
     *   from any sub-agent call is written here rather than to shared instance state,
     *   so parallel tool calls each capture their own trace independently.
     */
    private buildHandlerContext;
    /**
     * Creates a child `ChatDriver` for the named sub-agent, runs it to completion,
     * and returns its structured result (or final text fallback) together with the
     * full child conversation trace. Callers receive both values so each parallel
     * invocation can capture its own trace without touching shared instance state.
     */
    private invokeSubAgent;
    /**
     * Continue the tool loop from current history without appending a new user message.
     * Used by OrchestratingDriver after an agent handoff.
     */
    continueFromHistory(transientPrimer?: ChatMessage[]): Promise<ChatDriverResult>;
    /** Extract ToolFold metadata from a handler, or undefined if it isn't a fold facade. */
    private getFold;
    /**
     * Search all currently registered fold facades (and their nested folds recursively)
     * to find which fold contains a given tool name. Returns the immediate parent fold name.
     */
    private findFoldContaining;
    /**
     * If an open fold is hiding a previously-available tool, return the name of
     * the fold to close to start getting it back. Only exclusive folds hide tools
     * (they replace the tool set on open rather than extending it), so a base tool
     * that was visible before the fold opened now sits in a fold-stack frame's
     * `previousHandlers` but not in the live handler map. Only the top fold's
     * `close_` tool is active, so that's always the actionable next step — even
     * when the tool lives further down the stack, closing repeatedly walks back to
     * it. Returns null when no open fold accounts for the tool.
     */
    private foldHidingTool;
    /**
     * Install the fold's inner tool set, replacing (exclusive) or extending (non-exclusive)
     * the current tool set. Also injects the close tool. Does NOT touch the fold stack.
     */
    private applyFoldToolSet;
    /** Open a fold: push a stack frame, swap the tool set, return the response message. */
    private openFold;
    private pushFoldFrame;
    /** Close the top fold: pop the stack frame, restore the previous tool set. */
    private closeFold;
    /** Build the fold-awareness suffix appended to the system prompt each LLM call. */
    private buildFoldSystemPromptSuffix;
    private runToolLoop;
    private appendToHistory;
}
//# sourceMappingURL=chat-driver.d.ts.map