import type { Message, Thread } from 'chat';
import type { Agent } from '../agent/agent.js';
import type { MastraProviderMetadata } from '../agent/message-list/state/types.js';
import type { AgentSignalContents, AgentSignalInput } from '../agent/signals.js';
import type { AgentController } from '../agent-controller/agent-controller.js';
import type { Session } from '../agent-controller/session.js';
import type { Mastra } from '../mastra/index.js';
import type { StorageThreadType } from '../memory/types.js';
import type { RequestContext } from '../request-context/index.js';
import { AgentChannels } from './agent-channels.js';
import type { ThreadHistoryLogContext } from './thread-history.js';
import type { ChannelConfig } from './types.js';
/** Context passed to {@link AgentControllerChannelsConfig.onSessionStart}. */
export interface ChannelSessionStartContext {
    /**
     * The controller session, already bound to `thread`. Bound before the hook
     * runs on purpose: session settings persist to the bound thread's metadata,
     * so a hook that writes settings must not race the thread switch.
     */
    session: Session<any>;
    /** The mapped Mastra thread the session is bound to. */
    thread: Pick<StorageThreadType, 'id' | 'resourceId'>;
    /** Request context of the message that started the session, when there is one. */
    requestContext?: RequestContext;
}
/**
 * Configure a session the first time a channel thread reaches it, before the
 * inbound message is dispatched.
 *
 * The seam exists because a host can name a session (`resolveResourceId`) but
 * never receives the `Session` object — it is created here, inside the channel
 * machinery. Without this hook a host that resolves its own resourceIds can
 * only ever configure sessions the web UI created, and channel-created sessions
 * silently run on the SDK's built-in defaults.
 *
 * Errors are logged and swallowed: configuration is best-effort and must not
 * drop the message that triggered it.
 */
export type ChannelSessionStart = (ctx: ChannelSessionStartContext) => void | Promise<void>;
/** Context passed to {@link AgentControllerChannelsConfig.resolveSession}. */
export interface ChannelSessionResolveContext {
    /**
     * The bound controller. The resolver must create its session through this
     * controller so the channels instance stays the single owner of outbound
     * delivery for that session.
     */
    controller: AgentController<any>;
    /** The mapped Mastra thread the returned session will be bound to. */
    thread: Pick<StorageThreadType, 'id' | 'resourceId'>;
    /** Request context of the inbound message or approval action, when there is one. */
    requestContext?: RequestContext;
}
/**
 * Create the controller session for a mapped channel thread, replacing the
 * default `controller.createSession({ resourceId: thread.resourceId, ... })`.
 *
 * `onSessionStart` cannot serve this purpose: it runs after the session already
 * exists and its errors are swallowed, so a host cannot use it to authorize or
 * route. This hook runs *before* any session is created and its errors
 * propagate, which is what makes fail-closed authorization possible — a host
 * that rejects the request ends up with no session, no model call, and no
 * output.
 *
 * It also runs on approval continuations, so a shared install can revalidate
 * the execution principal on every approve/decline rather than only on the
 * message that opened the session.
 *
 * The returned session must own the mapped thread, i.e. be created under
 * `thread.resourceId` — a session can only bind threads it owns. Hosts that
 * want a different session identity choose it on both ends, by pairing this
 * with the channels `resolveResourceId` option.
 *
 * Create the session with `threadId: thread.id` so it binds the mapped thread
 * directly. Without it, a session scoped by tags or `projectPath` auto-selects
 * or creates a different thread and is only switched onto the mapped one
 * afterwards, leaving an extra empty thread behind.
 */
export type ChannelSessionResolve = (ctx: ChannelSessionResolveContext) => Session<any> | Promise<Session<any>>;
/** Context passed to {@link AgentControllerChannelsConfig.onStaleToolApproval}. */
export interface ChannelStaleToolApprovalContext {
    /** Which button the user pressed on the approval card. */
    decision: 'approve' | 'decline';
    /** The tool call the action referred to. */
    toolCallId: string;
    /**
     * The run the approval card was rendered for — the run the user actually
     * answered. This is the id to settle against: after a restart it is the only
     * one that still identifies that attempt.
     */
    runId: string;
    /**
     * The run currently on the session, when there is one. Usually `null` for a
     * restart-recovered action, and a *different* run when the session has since
     * moved on — never assume it matches {@link runId}.
     */
    currentRunId: string | null;
    /** Request context of the approval action. */
    requestContext: RequestContext;
    /** The mapped thread/resource the approval card belongs to. */
    memory: {
        thread: string;
        resource: string;
    };
    /** The session the action resolved to. */
    session: Session<any>;
}
/**
 * Called when an approval action arrives with no matching parked approval gate
 * — the usual cause being a process restart, which drops the in-memory gate and
 * makes every recovered approval stale.
 *
 * Core still never executes the tool action; the hook exists so a durable host
 * can settle that exact attempt (mark it interrupted, retryable, expired)
 * instead of silently dropping the user's click. Errors propagate.
 */
export type ChannelStaleToolApproval = (ctx: ChannelStaleToolApprovalContext) => void | Promise<void>;
/** Configuration for {@link AgentControllerChannels}. */
export interface AgentControllerChannelsConfig extends ChannelConfig {
    /**
     * Called once per session per process, after the session is bound to its
     * thread and before the first message dispatches. Concurrent messages on a
     * new session wait for the hook to settle rather than dispatching on an
     * unconfigured session. See {@link ChannelSessionStart}.
     */
    onSessionStart?: ChannelSessionStart;
    /**
     * Creates the session instead of the built-in `createSession` call, before
     * any session exists. Use this — not `onSessionStart` — for authorization and
     * routing: it can fail closed. See {@link ChannelSessionResolve}.
     */
    resolveSession?: ChannelSessionResolve;
    /**
     * Called when an approval action has no matching parked gate, typically after
     * a restart. See {@link ChannelStaleToolApproval}.
     */
    onStaleToolApproval?: ChannelStaleToolApproval;
}
/**
 * Runs an AgentController inside chat channels (Slack, Discord, ...).
 *
 * Extends {@link AgentChannels} so all inbound machinery (thread mapping,
 * history, attachments, event context) and all outbound rendering
 * (`ChatChannelOutputProcessor` with native streaming, tool cards, typing
 * status) are reused unchanged. Only the dispatch seams differ: instead of
 * routing into a bare agent, inbound messages route into a controller
 * `Session` — one durable session per chat thread, keyed by the mapped
 * Mastra thread's `resourceId`.
 *
 * V1 targets long-lived servers: controller sessions are in-memory objects
 * and do not survive process restarts.
 */
export declare class AgentControllerChannels extends AgentChannels {
    private controller;
    /**
     * Session resourceIds whose adapter can't render approval buttons, so their
     * runs must auto-approve tools (`requireToolApproval: false`) instead of
     * parking forever on an approval nobody can answer. Kept outside session
     * state on purpose: state is validated against the controller's
     * `stateSchema`, which would strip (or reject) an injected flag. Refreshed
     * on every inbound message; in-memory only, matching the v1 long-lived
     * server scope.
     */
    private autoApproveResourceIds;
    /** See {@link AgentControllerChannelsConfig.onSessionStart}. */
    private readonly onSessionStart;
    /** See {@link AgentControllerChannelsConfig.resolveSession}. */
    private readonly resolveSession;
    /** See {@link AgentControllerChannelsConfig.onStaleToolApproval}. */
    private readonly onStaleToolApproval;
    /**
     * One start-hook invocation per session resourceId. A map of promises rather
     * than a set of ids: concurrent messages on a new thread must all WAIT for
     * the hook, not just skip it, or the losers dispatch on an unconfigured
     * session. In-memory, matching the v1 scope where sessions themselves don't
     * survive a restart: a session rebuilt after a restart is a new session and
     * gets configured again. Keyed by session rather than by thread because a
     * `resolveSession` host can hand back a different session for the same thread
     * (per-principal routing), and each of those is a session that has never been
     * configured.
     */
    private sessionStartRuns;
    constructor(config: AgentControllerChannelsConfig);
    /** @internal Called by AgentController's constructor to bind itself. */
    __setController(controller: AgentController<any>): void;
    /**
     * @internal Consulted by the controller's run-option builder: `true` when
     * the session's channel adapter can't render approval buttons and tool
     * calls must auto-approve (the session-side equivalent of the base agent
     * path's `autoResumeSuspendedTools`).
     */
    __isAutoApproveResource(resourceId: string): boolean;
    /**
     * @internal No-op override. The controller attaches this instance to its
     * mode agents via `Agent.setChannels`, which calls `__setAgent(agent)` —
     * with multiple mode agents the last one would win. Every `this.agent` use
     * is overridden in this subclass, so keep the base field unset rather than
     * holding a misleading ref.
     */
    __setAgent(_agent: Agent<any, any, any, any>): void;
    protected getOwnerId(): string | null;
    protected getWebhookBasePath(): string;
    protected getMastra(): Mastra | undefined;
    /**
     * One session per chat thread: unless the user supplied a custom
     * `resolveResourceId`, key new Mastra threads (and therefore controller
     * sessions) off the platform + external thread id.
     */
    protected resolveChannelResourceId(args: {
        platform: string;
        chatThread: Thread;
        message: Message;
        defaultResourceId: string;
        requestContext: RequestContext;
    }): string | (() => string | Promise<string>);
    /**
     * Route an inbound chat message into the controller session bound to this
     * chat thread. Output renders back to the platform through the channels
     * output processor: the `requestContext` built by the base class (carrying
     * the channel context and render context) flows through the session into
     * the run.
     */
    protected dispatchInboundMessage(args: {
        signalContents: AgentSignalContents;
        attributes: Record<string, string | undefined>;
        signalMetadata: Record<string, unknown>;
        providerOptions: MastraProviderMetadata;
        requestContext: RequestContext;
        thread: StorageThreadType;
        memory: {
            thread: string;
            resource: string;
        };
        autoResumeSuspendedTools: true | undefined;
    }): Promise<void>;
    /**
     * Persist first-mention thread history into the controller session's own
     * thread. The session is resolved once, before the rows are built, and is
     * not guarded: a `resolveSession` refusal or resource mismatch propagates
     * out of the hook to the handler's error boundary exactly as it would from
     * the trigger dispatch a moment later. `onSessionStart` therefore runs
     * before the history rows rather than at trigger dispatch.
     *
     * Rows are written straight to the session agent's memory (see the base
     * class for why `session.sendSignal` cannot be used). Like the base class,
     * a session agent without memory or a failed write returns `false` so the
     * history still reaches the agent as the legacy text block.
     */
    protected persistThreadHistorySignals(args: {
        buildSignals: () => Promise<AgentSignalInput[]>;
        requestContext: RequestContext;
        thread: StorageThreadType;
        memory: {
            thread: string;
            resource: string;
        };
        logContext: ThreadHistoryLogContext;
    }): Promise<boolean>;
    /**
     * Resolve an approval-card "approve" action against the controller session's
     * parked tool-approval gate. The run engine — awaiting the gate inside its
     * stream-consumer loop — performs the actual resume itself and keeps
     * consuming, so the continuation renders through the output processor.
     */
    protected dispatchApproval(args: {
        runId: string;
        toolCallId: string;
        requestContext: RequestContext;
        memory: {
            thread: string;
            resource: string;
        };
    }): Promise<void>;
    /**
     * Resolve an approval-card "deny" action against the controller session's
     * parked tool-approval gate (see {@link dispatchApproval}).
     */
    protected dispatchDecline(args: {
        runId: string;
        toolCallId: string;
        requestContext: RequestContext;
        memory: {
            thread: string;
            resource: string;
        };
    }): Promise<void>;
    /**
     * Shared approve/decline path. Never calls the session's internal
     * `approveToolCall`/`declineToolCall` executors directly — the engine parked
     * at the gate owns the resume. `respondToToolApproval` is a silent no-op
     * when nothing is armed or the toolCallId mismatches, so staleness is
     * pre-checked explicitly (an armed gate does not survive process restarts,
     * so restart-recovered approvals are always stale — consistent with the
     * v1 long-lived-server scope).
     */
    private respondToSessionApproval;
    /**
     * Get-or-create the durable controller session for a mapped channel thread
     * and bind it to that thread. Keyed off the thread's own `resourceId` so
     * pre-existing threads (custom resolveResourceId, or created before this
     * feature) always pass the session's thread-ownership check.
     */
    protected getSessionForThread(thread: Pick<StorageThreadType, 'id' | 'resourceId'>, requestContext?: RequestContext, { bindThread }?: {
        bindThread?: boolean;
    }): Promise<Session<any>>;
    /**
     * Only render Approve/Deny controls when the session actually arms a human
     * gate. `allow` tools auto-approve and `deny` tools auto-decline inside the
     * session run, so a card for them would offer a decision nobody is waiting
     * on. The session is looked up in the controller's live registry by the
     * run's session id; when it isn't live, controls are rendered as a fallback.
     *
     * @internal
     */
    shouldRenderToolApproval(requestContext: RequestContext | undefined, toolName: string): Promise<boolean>;
    /**
     * Call the host's resolver and tag anything it throws as a refusal. Covers
     * synchronous throws too — the hook may return a `Session` directly, so a
     * plain `.catch()` on the return value would miss them.
     */
    private resolveChannelSession;
    /**
     * Run the configured session-start hook at most once per session. Fires after
     * the thread binding above, so a hook that persists session settings writes
     * them to the thread the session actually ends up on.
     */
    private runSessionStartHook;
    private requireController;
}
//# sourceMappingURL=agent-controller-channels.d.ts.map