import type { LanguageModelV2Prompt, LanguageModelV2CallWarning } from '../_types/@ai-sdk_provider@2.0.5/dist/index.js';
import type { StepResult } from '../_types/@internal_ai-sdk-v5@0.0.98/dist/index.js';
import type { Agent } from '../agent/index.js';
import type { MastraDBMessage } from '../agent/message-list/index.js';
import { MessageList } from '../agent/message-list/index.js';
import type { TripWireOptions } from '../agent/trip-wire.js';
import type { IMastraLogger } from '../logger/index.js';
import type { AnySpan, ObservabilityContext, ProcessorSpanType, Span } from '../observability/index.js';
import type { TracingContext } from '../observability/types/index.js';
import { RequestContext } from '../request-context/index.js';
import type { ChunkType } from '../stream/index.js';
import type { MastraModelOutput } from '../stream/base/output.js';
import type { LanguageModelUsage, ProviderMetadata } from '../stream/types.js';
import type { AnyWorkspace } from '../workspace/workspace.js';
import type { ProcessorLateSignalSink } from './send-signal.js';
import type { CachedLLMStepChunk, CachedLLMStepResponse, ErrorProcessorOrWorkflow, OutputResult, ProcessInputStepResult, Processor, ProcessorMessageResult, ProcessorStreamWriter, ProcessorWorkflow, RunProcessInputStepArgs, RunProcessInputStepResult, ToolCallInfo } from './index.js';
/**
 * Implementation of processor state management
 */
/**
 * Tracks state for stream processing across chunks.
 * Used by both legacy processors and workflow processors.
 */
export declare class ProcessorState<OUTPUT = undefined> {
    private inputAccumulatedText;
    private outputAccumulatedText;
    private outputChunkCount;
    customState: Record<string, unknown>;
    streamParts: ChunkType<OUTPUT>[];
    span?: Span<ProcessorSpanType>;
    /**
     * Milliseconds spent inside `processOutputStream`, summed across every
     * chunk. The span itself lasts for the whole stream, so its duration is
     * dominated by the model's inter-chunk latency; this is the processor's own
     * share of that window.
     */
    hookDurationMs: number;
    constructor(options?: {
        processorName?: string;
        processorIndex?: number;
        createSpan?: boolean;
        /**
         * The processor this state belongs to, so a span created here honours
         * its span declaration. `processOutputStream` is the one processor
         * method whose span is created from this constructor rather than from
         * one of the runner's own call sites, so without this a processor that
         * declares a span type would keep it everywhere except its streaming
         * phase.
         */
        processor?: Pick<Processor, 'id' | 'spanType' | 'spanName' | 'spanAttributes'>;
    } & Partial<ObservabilityContext>);
    /** Track incoming chunk (before processor transformation) */
    addInputPart(part: ChunkType<OUTPUT>): void;
    /** Track outgoing chunk (after processor transformation) */
    addOutputPart(part: ChunkType<OUTPUT> | null | undefined): void;
    /** Get final output for span */
    getFinalOutput(): {
        totalChunks: number;
        accumulatedText: string;
    };
    /** Attributes attached on every end path of the span. */
    getFinalAttributes(): {
        hookDurationMs: number;
    };
}
/**
 * Key under which the workflow-processor stream path keeps its accumulated
 * hook time on the shared processor state, next to `__outputStreamSpan_<id>`.
 */
export declare const OUTPUT_STREAM_HOOK_DURATION_KEY_PREFIX = "__outputStreamHookDurationMs_";
/**
 * The MODEL_STEP an output stream processor span belongs under: `span` itself
 * (a step's stream passes its step span) or its nearest step ancestor. Stops at
 * the first agent run, so a nested agent's stream never attaches to its
 * caller's step.
 */
export declare function findOwnModelStepSpan(span: AnySpan | undefined): AnySpan | undefined;
/**
 * When a step's stream starts, ends the stored output stream processor span if
 * it was opened outside that step (e.g. by a tool result replayed on resume,
 * before any step started), so it does not carry into the step.
 */
export declare function endOutputStreamSpanOutsideStep(state: Record<string, unknown>, processorId: string, part: ChunkType, stepSpan: AnySpan | undefined, totalChunks: number): void;
/**
 * Ends the stored output stream processor span when the model step it sits
 * under ends. The span outlives the step's model stream so the step's tool
 * results land in it too.
 */
export declare function endOutputStreamSpanAtStepEnd(state: Record<string, unknown>, processorId: string, part: ChunkType, totalChunks: number): void;
/**
 * Union type for processor or workflow that can be used as a processor
 */
type ProcessorOrWorkflow = Processor | ProcessorWorkflow;
export declare class ProcessorRunner {
    readonly inputProcessors: ProcessorOrWorkflow[];
    readonly outputProcessors: ProcessorOrWorkflow[];
    readonly errorProcessors: ErrorProcessorOrWorkflow[];
    private readonly logger;
    private readonly agentName;
    private readonly agent?;
    /**
     * Shared processor state that persists across loop iterations.
     * Used by all processor methods (input and output) to share state.
     * Keyed by processor ID.
     */
    private readonly processorStates;
    private readonly lateSignalSink?;
    constructor({ inputProcessors, outputProcessors, errorProcessors, logger, agentName, agent, processorStates, lateSignalSink, }: {
        inputProcessors?: ProcessorOrWorkflow[];
        outputProcessors?: ProcessorOrWorkflow[];
        errorProcessors?: ErrorProcessorOrWorkflow[];
        logger: IMastraLogger;
        agentName: string;
        agent?: Agent<any, any, any, any>;
        processorStates?: Map<string, ProcessorState>;
        /** Receives `sendSignal` calls made after the creating step returned (durable engines). */
        lateSignalSink?: ProcessorLateSignalSink;
    });
    /**
     * Get or create ProcessorState for the given processor ID.
     * This state persists across loop iterations and is shared between
     * all processor methods (input and output).
     */
    private getProcessorState;
    private runComputeStateSignal;
    private runWorkflowComputeStateSignals;
    /**
     * Execute a workflow as a processor and handle the result.
     * Returns the processed messages and any tripwire information.
     */
    private executeWorkflowAsProcessor;
    runOutputProcessors(messageList: MessageList, observabilityContext?: ObservabilityContext, requestContext?: RequestContext, retryCount?: number, writer?: ProcessorStreamWriter, result?: OutputResult): Promise<MessageList>;
    /**
     * Process a stream part through all output processors with state management
     */
    processPart<OUTPUT>(part: ChunkType<OUTPUT>, processorStates: Map<string, ProcessorState<OUTPUT>>, observabilityContext?: ObservabilityContext, requestContext?: RequestContext, messageList?: MessageList, retryCount?: number, writer?: ProcessorStreamWriter, abortSignal?: AbortSignal, 
    /** Skip output processors before this index (the part was released by the one before it). */
    startIndex?: number): Promise<{
        part: ChunkType<OUTPUT> | null | undefined;
        blocked: boolean;
        reason?: string;
        tripwireOptions?: TripWireOptions<unknown>;
        processorId?: string;
    }>;
    endStreamProcessorSpans<OUTPUT>(processorStates: Map<string, ProcessorState<OUTPUT>>, options?: {
        /**
         * Leave workflow-path spans parented to a model step open. Set when only
         * the step's model stream closed: the step's tool results still flow
         * through the processors, and the span ends with the step's
         * `step-finish` chunk.
         */
        keepStepScopedSpans?: boolean;
    }): void;
    /**
     * Re-drive any parts that stream processors stashed for reprocessing through
     * the full output processor chain.
     *
     * A stream processor can only return one part from `processOutputStream`, but
     * some processors (e.g. `BatchPartsProcessor`) need to emit a second part for
     * one input — it returns the first part and stashes the second under
     * `REPROCESS_PART_KEY` on its state. After the primary part has been emitted,
     * callers invoke this to push each stashed part back through the whole chain
     * (so it receives downstream processing) and emit the results in order.
     *
     * Returns the processed results in emission order. Reprocessing can itself
     * stash more parts, so this drains until none remain.
     */
    drainReprocessParts<OUTPUT>(processorStates: Map<string, ProcessorState<OUTPUT>>, observabilityContext?: ObservabilityContext, requestContext?: RequestContext, messageList?: MessageList, retryCount?: number, writer?: ProcessorStreamWriter, abortSignal?: AbortSignal, minIndex?: number): Promise<Array<{
        part: ChunkType<OUTPUT> | null | undefined;
        blocked: boolean;
        reason?: string;
        tripwireOptions?: TripWireOptions<unknown>;
        processorId?: string;
    }>>;
    /**
     * Call when a stream ends. Processors that hold parts until a later part
     * arrives (`BatchPartsProcessor`, LLM-buffered checks) would otherwise drop
     * what they hold when nothing follows it. Each held part is released and
     * pushed through the processors after its holder, then any stashed parts are
     * drained. Returns the results in emission order, stopping at the first block.
     */
    flushHeldParts<OUTPUT>(processorStates: Map<string, ProcessorState<OUTPUT>>, observabilityContext?: ObservabilityContext, requestContext?: RequestContext, messageList?: MessageList, retryCount?: number, writer?: ProcessorStreamWriter, abortSignal?: AbortSignal): Promise<Array<{
        part: ChunkType<OUTPUT> | null | undefined;
        blocked: boolean;
        reason?: string;
        tripwireOptions?: TripWireOptions<unknown>;
        processorId?: string;
    }>>;
    /**
     * Call instead of {@link flushHeldParts} when a stream errored or was aborted:
     * clears what processors hold without emitting or checking it, so a retry
     * doesn't repeat it and nothing is emitted after cancellation.
     */
    /**
     * Drops what output processors hold after a failed or aborted model stream, without running
     * any checks. Returns the held control parts (start, error, finish, ...), oldest first.
     */
    discardHeldParts<OUTPUT>(processorStates: Map<string, ProcessorState<OUTPUT>>): Promise<ChunkType<OUTPUT>[]>;
    runOutputProcessorsForStream<OUTPUT = undefined>(streamResult: MastraModelOutput<OUTPUT>, observabilityContext?: ObservabilityContext, writer?: ProcessorStreamWriter): Promise<ReadableStream<any>>;
    runInputProcessors(messageList: MessageList, observabilityContext?: ObservabilityContext, requestContext?: RequestContext, retryCount?: number): Promise<MessageList>;
    /**
     * Run processInputStep for all processors that implement it.
     * Called at each step of the agentic loop, before the LLM is invoked.
     *
     * Unlike processInput which runs once at the start, this runs at every step
     * (including tool call continuations). This is useful for:
     * - Transforming message types between steps (e.g., AI SDK 'reasoning' -> Anthropic 'thinking')
     * - Modifying messages based on step context
     * - Implementing per-step message transformations
     *
     * @param args.messages - The current messages to be sent to the LLM (MastraDBMessage format)
     * @param args.messageList - MessageList instance for managing message sources
     * @param args.stepNumber - The current step number (0-indexed)
     * @param args.tracingContext - Optional tracing context for observability
     * @param args.requestContext - Optional runtime context with execution metadata
     *
     * @returns The processed MessageList
     */
    runProcessInputStep(args: RunProcessInputStepArgs): Promise<RunProcessInputStepResult>;
    /**
     * IDs of the processors that `runProcessLLMRequest` will call for these input processors.
     * Pass the result to `runProcessInputStep` as `llmRequestProcessorIds`.
     */
    static getLLMRequestProcessorIds(processors: readonly ProcessorOrWorkflow[]): Set<string>;
    /**
     * Run processLLMRequest for all processors that implement it.
     *
     * Called *after* `MessageList` has been converted to `LanguageModelV2Prompt`
     * and immediately *before* the prompt is forwarded to the provider.
     * Mutations are scoped to this single call — they do not affect the
     * persisted message list, memory, UI, or future model swaps.
     */
    runProcessLLMRequest(args: {
        prompt: LanguageModelV2Prompt;
        model: unknown;
        apiProviderId?: string;
        messageList?: MessageList;
        workspace?: AnyWorkspace;
        stepNumber: number;
        steps: Array<StepResult<any>>;
        requestContext?: RequestContext;
        retryCount?: number;
        abortSignal?: AbortSignal;
        tracingContext?: TracingContext;
        writer?: ProcessorStreamWriter;
    }): Promise<{
        prompt: LanguageModelV2Prompt;
        response?: CachedLLMStepResponse;
    }>;
    /**
     * Run processLLMResponse for all processors that implement it.
     *
     * Called *after* the LLM step completes (or after a cached response is
     * replayed) and *after* output processors have collected the response
     * chunks. The shared `state` object is the same instance passed to
     * `processLLMRequest` for the same step, allowing processors to correlate
     * pre- and post-call work (e.g. cache key stash, then cache write).
     */
    runProcessLLMResponse(args: {
        chunks: CachedLLMStepChunk[];
        model: unknown;
        stepNumber: number;
        steps: Array<StepResult<any>>;
        warnings?: LanguageModelV2CallWarning[];
        request?: unknown;
        rawResponse?: unknown;
        fromCache: boolean;
        requestContext?: RequestContext;
        retryCount?: number;
        abortSignal?: AbortSignal;
        tracingContext?: TracingContext;
        writer?: ProcessorStreamWriter;
    }): Promise<void>;
    /**
     * Type guard to check if result is { messages, systemMessages }
     */
    private isProcessInputResultWithSystemMessages;
    /**
     * Run processOutputStep for all processors that implement it.
     * Called after each LLM response in the agentic loop, before tool execution.
     *
     * Unlike processOutputResult which runs once at the end, this runs at every step.
     * This is the ideal place to implement guardrails that can trigger retries.
     *
     * @param args.messages - The current messages including the LLM response
     * @param args.messageList - MessageList instance for managing message sources
     * @param args.stepNumber - The current step number (0-indexed)
     * @param args.finishReason - The finish reason from the LLM
     * @param args.toolCalls - Tool calls made in this step (if any)
     * @param args.text - Generated text from this step
     * @param args.tracingContext - Optional tracing context for observability
     * @param args.requestContext - Optional runtime context with execution metadata
     * @param args.retryCount - Number of times processors have triggered retry
     *
     * @returns The processed MessageList
     */
    runProcessOutputStep(args: {
        steps: Array<StepResult<any>>;
        messages: MastraDBMessage[];
        messageList: MessageList;
        stepNumber: number;
        finishReason?: string;
        providerMetadata?: ProviderMetadata;
        toolCalls?: ToolCallInfo[];
        text?: string;
        usage?: LanguageModelUsage;
        requestContext?: RequestContext;
        retryCount?: number;
        writer?: ProcessorStreamWriter;
    } & Partial<ObservabilityContext>): Promise<MessageList>;
    /**
     * Run processToolResult on all output processors that implement it.
     * Called after tool.execute() returns and before the result is appended to
     * the message list / fed to the next LLM call.
     *
     * Symmetric with runProcessOutputStep — same TripWire/abort/state plumbing.
     * Processors mutate via messageList.updateToolInvocation. The caller is
     * responsible for re-reading the post-mutation result and syncing it into
     * the downstream stream chunk so streaming clients see the processed value.
     */
    runProcessToolResult(args: {
        steps: Array<StepResult<any>>;
        messages: MastraDBMessage[];
        messageList: MessageList;
        stepNumber: number;
        toolName: string;
        toolCallId: string;
        toolArgs: unknown;
        result: unknown;
        modelOutput?: unknown;
        providerExecuted?: boolean;
        requestContext?: RequestContext;
        retryCount?: number;
        writer?: ProcessorStreamWriter;
        abortSignal?: AbortSignal;
    } & Partial<ObservabilityContext>): Promise<MessageList>;
    /**
     * Run processAPIError on all processors that implement it.
     * Called when an LLM API call fails with a non-retryable error.
     * Iterates through both input and output processors.
     *
     * @returns { retry: boolean } indicating whether to retry the LLM call
     */
    runProcessAPIError(args: {
        error: unknown;
        messages: MastraDBMessage[];
        messageList: MessageList;
        stepNumber: number;
        steps: Array<StepResult<any>>;
        messageId?: string;
        requestContext?: RequestContext;
        retryCount?: number;
        writer?: ProcessorStreamWriter;
        abortSignal?: AbortSignal;
        rotateResponseMessageId?: () => string;
    } & Partial<ObservabilityContext>): Promise<{
        retry: boolean;
    }>;
    static applyMessagesToMessageList(messages: MastraDBMessage[], messageList: MessageList, idsBeforeProcessing: string[], check: ReturnType<MessageList['makeMessageSourceChecker']>, defaultSource?: 'input' | 'response'): void;
    static validateAndFormatProcessInputStepResult(result: ProcessInputStepResult | Awaited<ProcessorMessageResult> | undefined | void, { messageList, processor, stepNumber, }: {
        messageList: MessageList;
        processor: Processor;
        stepNumber: number;
    }): Promise<RunProcessInputStepResult>;
}
export {};
//# sourceMappingURL=runner.d.ts.map