import { M as Message$1, n as RunResult, A as AgentLike, G as GuardrailFn, O as OutputGuardrailData, aX as StreamingCallbackRunner, q as DebugEvent, a8 as DebugEventType, b as AgentRunner, az as OrchestratorState, au as NamedGuardrail, I as InputGuardrailData, W as Checkpoint, L as BreakpointModifications, N as BreakpointRequest, o as OrchestratorConstraint, ax as OrchestratorResolver, aj as GuardrailsConfig, z as ApprovalRequest, av as OrchestratorDebugConfig, w as AgentRetryConfig, aw as OrchestratorLifecycleHooks, aU as SelfHealingConfig, e as CheckpointStore, H as BreakpointConfig, am as HealthMonitorConfig, p as RunOptions, T as ToolCallGuardrailData, l as PatternCheckpointConfig, i as DagPattern, m as GoalPattern, j as GoalNode, g as AgentSelectionStrategy, R as RelaxationTier, r as GoalResult, ab as GoalCheckpointState, aV as SequentialCheckpointState, aY as SupervisorCheckpointState, aG as ReflectCheckpointState, a5 as DebateCheckpointState, a2 as DagCheckpointState, aS as Scratchpad, as as MultiAgentLifecycleHooks, at as MultiAgentSelfHealingConfig, aq as MultiAgentBreakpointType, a0 as CrossAgentDerivationFn } from './types-CRmwFnVk.js';
import { Plugin, System, Requirement } from '@directive-run/core';
import { CircuitBreaker } from '@directive-run/core/plugins';

/**
 * Agent Memory System
 *
 * Provides sliding window message management and automatic summarization
 * for long-running agent conversations.
 *
 * @example
 * ```typescript
 * import { createAgentMemory, createSlidingWindowStrategy } from '@directive-run/ai';
 *
 * const memory = createAgentMemory({
 *   strategy: createSlidingWindowStrategy({ maxMessages: 50 }),
 *   summarizer: async (messages) => {
 *     // Call LLM to summarize older messages
 *     return await summarizeWithLLM(messages);
 *   },
 * });
 *
 * // Use with orchestrator
 * const orchestrator = createAgentOrchestrator({
 *   memory,
 *   runner: run,
 * });
 * ```
 */
/**
 * Memory-compatible message type.
 * Extends the standard Message type to include system messages for summaries.
 */
interface MemoryMessage {
    role: "user" | "assistant" | "tool" | "system";
    content: string;
    toolCallId?: string;
}
type Message = MemoryMessage;
/** Configuration for memory management strategies */
interface MemoryStrategyConfig {
    /** Maximum number of messages to keep in active memory */
    maxMessages?: number;
    /** Maximum total tokens to keep in active memory */
    maxTokens?: number;
    /** Number of recent messages to always keep (protected from summarization) */
    preserveRecentCount?: number;
    /** Whether to include system messages in token count */
    countSystemMessages?: boolean;
}
/** Result of a memory strategy evaluation */
interface MemoryStrategyResult {
    /** Messages to keep in active memory */
    keep: Message[];
    /** Messages to summarize or discard */
    toSummarize: Message[];
    /** Estimated token count of kept messages */
    estimatedTokens: number;
}
/** Memory management strategy function */
type MemoryStrategy = (messages: Message[], config: MemoryStrategyConfig) => MemoryStrategyResult;
/** Summarizer function to compress older messages */
type MessageSummarizer = (messages: Message[]) => Promise<string>;
/** Agent memory configuration */
interface AgentMemoryConfig {
    /** Memory management strategy */
    strategy: MemoryStrategy;
    /** Optional summarizer for compressing old messages */
    summarizer?: MessageSummarizer;
    /** Strategy configuration */
    strategyConfig?: MemoryStrategyConfig;
    /** Whether to auto-manage memory after each interaction */
    autoManage?: boolean;
    /** Callback when memory is managed */
    onMemoryManaged?: (result: MemoryManageResult) => void;
    /** Callback when auto-manage encounters an error */
    onManageError?: (error: Error) => void;
    /** Maximum context window tokens (triggers additional summarization if exceeded) */
    maxContextTokens?: number;
}
/** Result of memory management */
interface MemoryManageResult {
    /** Number of messages before management */
    messagesBefore: number;
    /** Number of messages after management */
    messagesAfter: number;
    /** Number of messages summarized */
    messagesSummarized: number;
    /** The summary that was generated (if any) */
    summary?: string;
    /** Estimated tokens before */
    estimatedTokensBefore: number;
    /** Estimated tokens after */
    estimatedTokensAfter: number;
}
/** Memory state for a conversation */
interface MemoryState {
    /** Active messages in memory */
    messages: Message[];
    /** Summaries of older messages */
    summaries: Array<{
        content: string;
        messagesCount: number;
        createdAt: number;
    }>;
    /** Total messages ever processed */
    totalMessagesProcessed: number;
    /** Estimated current token count */
    estimatedTokens: number;
}
/** Agent memory instance */
interface AgentMemory {
    /** Get current memory state */
    getState(): MemoryState;
    /** Add a message to memory */
    addMessage(message: Message): void;
    /** Check if memory management is currently in progress */
    isManaging(): boolean;
    /** Add multiple messages to memory */
    addMessages(messages: Message[]): void;
    /** Get messages for context (includes summaries as system messages) */
    getContextMessages(): Message[];
    /** Manually trigger memory management */
    manage(): Promise<MemoryManageResult>;
    /** Clear all memory */
    clear(): void;
    /** Export memory state for persistence */
    export(): MemoryState;
    /** Import memory state from persistence */
    import(state: MemoryState): void;
}
/**
 * Create a sliding window memory strategy that keeps the most recent N messages.
 *
 * Messages beyond `maxMessages` are moved to the summarization queue.
 * The most recent `preserveRecentCount` messages are always kept.
 *
 * @param defaultConfig - Default strategy configuration (can be overridden per-call).
 * @returns A {@link MemoryStrategy} function.
 *
 * @example
 * ```typescript
 * const strategy = createSlidingWindowStrategy({
 *   maxMessages: 50,
 *   preserveRecentCount: 10,
 * });
 * ```
 * @public
 */
declare function createSlidingWindowStrategy(defaultConfig?: MemoryStrategyConfig): MemoryStrategy;
/**
 * Create a token-based memory strategy that keeps messages until a token limit is reached.
 *
 * Adds messages from newest to oldest until `maxTokens` would be exceeded,
 * then moves the remaining older messages to the summarization queue.
 *
 * @param defaultConfig - Default strategy configuration (can be overridden per-call).
 * @returns A {@link MemoryStrategy} function.
 *
 * @example
 * ```typescript
 * const strategy = createTokenBasedStrategy({
 *   maxTokens: 4000,
 *   preserveRecentCount: 5,
 * });
 * ```
 * @public
 */
declare function createTokenBasedStrategy(defaultConfig?: MemoryStrategyConfig): MemoryStrategy;
/**
 * Create a hybrid strategy that combines message count and token limits.
 *
 * Applies both {@link createSlidingWindowStrategy} and {@link createTokenBasedStrategy},
 * then uses whichever result keeps fewer messages (the more restrictive outcome).
 *
 * @param defaultConfig - Default strategy configuration (can be overridden per-call).
 * @returns A {@link MemoryStrategy} function.
 *
 * @example
 * ```typescript
 * const strategy = createHybridStrategy({
 *   maxMessages: 50,
 *   maxTokens: 4000,
 *   preserveRecentCount: 5,
 * });
 * ```
 * @public
 */
declare function createHybridStrategy(defaultConfig?: MemoryStrategyConfig): MemoryStrategy;
/**
 * Create an agent memory instance for managing conversation history.
 *
 * Provides sliding window management, automatic summarization of older messages,
 * and import/export for persistence. Pass the returned instance to an orchestrator's
 * `memory` option to auto-inject context and auto-store results.
 *
 * @param config - Memory configuration including strategy, optional summarizer, and auto-manage settings.
 * @returns An {@link AgentMemory} instance with `addMessage`, `getContextMessages`, `manage`, and `export`/`import` APIs.
 *
 * @example
 * ```typescript
 * const memory = createAgentMemory({
 *   strategy: createSlidingWindowStrategy({ maxMessages: 50 }),
 *   summarizer: async (messages) => {
 *     const response = await openai.chat.completions.create({
 *       model: 'gpt-4o-mini',
 *       messages: [
 *         { role: 'system', content: 'Summarize the following conversation concisely.' },
 *         ...messages.map(m => ({ role: m.role, content: m.content })),
 *       ],
 *     });
 *     return response.choices[0].message.content;
 *   },
 *   autoManage: true,
 * });
 * ```
 * @public
 */
declare function createAgentMemory(config: AgentMemoryConfig): AgentMemory;
/**
 * Create a simple truncation summarizer that clips messages to a maximum length.
 *
 * Useful for testing or when LLM-based summarization is not needed.
 * Concatenates non-system messages with role prefixes and truncates to `maxLength`.
 *
 * @param maxLength - Maximum character length of the summary (default: 500).
 * @returns A {@link MessageSummarizer} function.
 * @public
 */
declare function createTruncationSummarizer(maxLength?: number): MessageSummarizer;
/**
 * Create a summarizer that extracts user questions from messages.
 *
 * Scans for sentences ending with `?` in user messages and lists them as key topics.
 *
 * @returns A {@link MessageSummarizer} function.
 * @public
 */
declare function createKeyPointsSummarizer(): MessageSummarizer;
/**
 * Create a summarizer that delegates to an LLM for conversation compression.
 *
 * You provide the LLM call function; this handles prompt construction
 * including length limits and key-fact preservation instructions.
 *
 * @param llmCall - Async function that sends a prompt to an LLM and returns the response text.
 * @param options - Optional `maxSummaryLength` and `preserveKeyFacts` settings.
 * @returns A {@link MessageSummarizer} function.
 *
 * @example
 * ```typescript
 * const summarizer = createLLMSummarizer(async (prompt) => {
 *   const response = await openai.chat.completions.create({
 *     model: 'gpt-4o-mini',
 *     messages: [{ role: 'user', content: prompt }],
 *   });
 *   return response.choices[0].message.content ?? '';
 * });
 * ```
 * @public
 */
declare function createLLMSummarizer(llmCall: (prompt: string) => Promise<string>, options?: {
    maxSummaryLength?: number;
    preserveKeyFacts?: boolean;
}): MessageSummarizer;

/**
 * Agent Streaming - Token-by-token streaming with backpressure support
 *
 * Provides async iterators for streaming agent responses with guardrail evaluation
 * on partial output and configurable backpressure handling.
 *
 * @example
 * ```typescript
 * import { createAgentOrchestrator } from '@directive-run/ai';
 * import { createStreamingRunner } from '@directive-run/ai';
 *
 * const { stream, result } = orchestrator.runStream(agent, input);
 *
 * for await (const chunk of stream) {
 *   if (chunk.type === 'token') process.stdout.write(chunk.data);
 *   if (chunk.type === 'guardrail_triggered') handleGuardrail(chunk);
 * }
 *
 * const finalResult = await result;
 * ```
 */

/** Token chunk from streaming response */
interface TokenChunk {
    type: "token";
    data: string;
    /** Running total of tokens received */
    tokenCount: number;
}
/** Tool execution started */
interface ToolStartChunk {
    type: "tool_start";
    tool: string;
    toolCallId: string;
    arguments: string;
}
/** Tool execution completed */
interface ToolEndChunk {
    type: "tool_end";
    tool: string;
    toolCallId: string;
    result: string;
}
/** Message added to conversation */
interface MessageChunk {
    type: "message";
    message: Message$1;
}
/** Guardrail was triggered during streaming */
interface GuardrailTriggeredChunk {
    type: "guardrail_triggered";
    guardrailName: string;
    reason: string;
    /** Partial output at the time of trigger */
    partialOutput: string;
    /** Whether the stream was stopped */
    stopped: boolean;
}
/** Progress update for UI feedback */
interface ProgressChunk {
    type: "progress";
    phase: "starting" | "generating" | "tool_calling" | "finishing";
    /** Percentage complete (0-100), if known */
    percent?: number;
    /** Human-readable status message */
    message?: string;
}
/** Stream completed */
interface DoneChunk {
    type: "done";
    totalTokens: number;
    duration: number;
    /** Number of tokens dropped due to backpressure (only with 'drop' strategy) */
    droppedTokens: number;
}
/** Error during streaming */
interface ErrorChunk {
    type: "error";
    error: Error;
    /** Partial output before error */
    partialOutput?: string;
}
/** Union of all stream chunk types */
type StreamChunk = TokenChunk | ToolStartChunk | ToolEndChunk | MessageChunk | GuardrailTriggeredChunk | ProgressChunk | DoneChunk | ErrorChunk;
/** Backpressure strategy when consumer is slow */
type BackpressureStrategy = 
/** Drop tokens when buffer is full (lossy, fast) */
"drop"
/** Block producer when buffer is full (lossless, may slow response) */
 | "block"
/** Buffer all tokens (lossless, uses memory) */
 | "buffer";
/** Streaming run options */
interface StreamRunOptions {
    /** Maximum turns before stopping */
    maxTurns?: number;
    /** Abort signal for cancellation */
    signal?: AbortSignal;
    /** Backpressure strategy. @default "buffer" */
    backpressure?: BackpressureStrategy;
    /** Buffer size for 'drop' and 'block' strategies. @default 1000 */
    bufferSize?: number;
    /** Evaluate guardrails every N tokens. @default 50 */
    guardrailCheckInterval?: number;
    /** Stop stream on guardrail trigger. @default true */
    stopOnGuardrail?: boolean | ((chunk: GuardrailTriggeredChunk) => boolean);
}
/** Stream run function type (mirrors OpenAI Agents streaming API) */
type StreamRunner = <T = unknown>(agent: AgentLike, input: string, options?: StreamRunOptions) => StreamingRunResult<T>;
/** Result from a streaming run */
interface StreamingRunResult<T = unknown> {
    /** Async iterator for streaming chunks */
    stream: AsyncIterable<StreamChunk>;
    /** Promise that resolves to the final result */
    result: Promise<RunResult<T>>;
    /** Abort the stream */
    abort: () => void;
}
/** Streaming guardrail that evaluates partial output */
interface StreamingGuardrail {
    /** Unique name for this guardrail */
    name: string;
    /** Check partial output (called every guardrailCheckInterval tokens) */
    check: (partialOutput: string, tokenCount: number) => StreamingGuardrailResult | Promise<StreamingGuardrailResult>;
    /** Whether to stop the stream on failure. @default true */
    stopOnFail?: boolean;
}
/** Result from a streaming guardrail check */
interface StreamingGuardrailResult {
    passed: boolean;
    reason?: string;
    /** Severity level for UI display */
    severity?: "warning" | "error" | "critical";
    /** Warning message (guardrail passed but wants to emit a warning) */
    warning?: string;
}
/**
 * Create a streaming runner that wraps a base run function.
 * This is used internally by the orchestrator but can be used standalone.
 *
 * @param baseRunner - The underlying non-streaming runner
 * @param options - Configuration options
 */
declare function createStreamingRunner(baseRunner: StreamingCallbackRunner, options?: {
    streamingGuardrails?: StreamingGuardrail[];
}): StreamRunner;
/**
 * Create a streaming guardrail that detects toxic content.
 *
 * @example
 * ```typescript
 * const toxicityGuardrail = createToxicityStreamingGuardrail({
 *   threshold: 0.9,
 *   checkFn: async (text) => myToxicityModel.score(text),
 * });
 * ```
 */
declare function createToxicityStreamingGuardrail(options: {
    /** Toxicity scoring function (returns 0-1) */
    checkFn: (text: string) => number | Promise<number>;
    /** Threshold above which content is flagged. @default 0.8 */
    threshold?: number;
    /** Stop the stream on detection. @default true */
    stopOnFail?: boolean;
}): StreamingGuardrail;
/**
 * Create a streaming guardrail that limits output length.
 *
 * @example
 * ```typescript
 * const lengthGuardrail = createLengthStreamingGuardrail({
 *   maxTokens: 4000,
 *   warnAt: 3500,
 * });
 * ```
 */
declare function createLengthStreamingGuardrail(options: {
    /** Maximum tokens before stopping */
    maxTokens: number;
    /** Warn at this token count (optional) */
    warnAt?: number;
    /** Stop the stream on max. @default true */
    stopOnFail?: boolean;
}): StreamingGuardrail;
/**
 * Create a streaming guardrail that detects patterns (regex-based).
 *
 * @example
 * ```typescript
 * const piiGuardrail = createPatternStreamingGuardrail({
 *   patterns: [
 *     { regex: /\b\d{3}-\d{2}-\d{4}\b/, name: 'SSN' },
 *     { regex: /\b\d{16}\b/, name: 'Credit Card' },
 *   ],
 *   stopOnFail: true,
 * });
 * ```
 */
declare function createPatternStreamingGuardrail(options: {
    patterns: Array<{
        regex: RegExp;
        name: string;
    }>;
    stopOnFail?: boolean;
}): StreamingGuardrail;
/**
 * Combine multiple streaming guardrails into one.
 *
 * @example
 * ```typescript
 * const combined = combineStreamingGuardrails([
 *   createToxicityStreamingGuardrail({ ... }),
 *   createLengthStreamingGuardrail({ ... }),
 * ]);
 * ```
 */
declare function combineStreamingGuardrails(guardrails: StreamingGuardrail[], options?: {
    name?: string;
    stopOnFirstFail?: boolean;
}): StreamingGuardrail;
/**
 * Convert a regular output guardrail to a streaming guardrail.
 * Useful for reusing existing guardrails in streaming context.
 *
 * @example
 * ```typescript
 * const streamingPII = adaptOutputGuardrail(
 *   "pii-streaming",
 *   createPIIGuardrail({ redact: false }),
 *   { checkInterval: 100 }
 * );
 * ```
 */
declare function adaptOutputGuardrail(name: string, guardrail: GuardrailFn<OutputGuardrailData>, options?: {
    /** Only run after this many tokens (optimization) */
    minTokens?: number;
    stopOnFail?: boolean;
}): StreamingGuardrail;
/**
 * Collect all tokens from a stream into a string.
 *
 * @example
 * ```typescript
 * const { stream, result } = orchestrator.runStream(agent, input);
 * const fullOutput = await collectTokens(stream);
 * ```
 */
declare function collectTokens(stream: AsyncIterable<StreamChunk>): Promise<string>;
/**
 * Tap into a stream without consuming it.
 * Useful for logging or side effects.
 *
 * @example
 * ```typescript
 * const { stream } = orchestrator.runStream(agent, input);
 * const tapped = tapStream(stream, (chunk) => console.log(chunk));
 * for await (const chunk of tapped) { ... }
 * ```
 */
declare function tapStream(stream: AsyncIterable<StreamChunk>, fn: (chunk: StreamChunk) => void | Promise<void>): AsyncIterable<StreamChunk>;
/**
 * Filter stream chunks by type.
 *
 * @example
 * ```typescript
 * const tokensOnly = filterStream(stream, ['token']);
 * ```
 */
declare function filterStream<T extends StreamChunk["type"]>(stream: AsyncIterable<StreamChunk>, types: T[]): AsyncIterable<Extract<StreamChunk, {
    type: T;
}>>;
/**
 * Transform stream chunks.
 *
 * @example
 * ```typescript
 * const upperTokens = mapStream(stream, (chunk) => {
 *   if (chunk.type === 'token') return { ...chunk, data: chunk.data.toUpperCase() };
 *   return chunk;
 * });
 * ```
 */
declare function mapStream<R>(stream: AsyncIterable<StreamChunk>, fn: (chunk: StreamChunk) => R | Promise<R>): AsyncIterable<R>;
/** A multiplexed stream chunk tagged with the agent that produced it */
interface MultiplexedStreamChunk {
    chunk: OrchestratorStreamChunk;
    agentId: string;
}
/** Result from a parallel streaming operation */
interface MultiplexedStreamResult<T = unknown> {
    stream: AsyncIterable<MultiplexedStreamChunk>;
    results: Promise<RunResult<unknown>[]>;
    merge: Promise<T>;
    abort: () => void;
    /** Number of chunks dropped due to buffer overflow */
    getDroppedCount: () => number;
}
/** A source stream with its agent ID */
interface TaggedSource {
    agentId: string;
    stream: AsyncIterable<OrchestratorStreamChunk>;
}
/**
 * Merge multiple async iterables into a single multiplexed stream,
 * tagging each chunk with its source agent ID.
 *
 * Race-based merge: pulls from all sources concurrently, emitting
 * chunks in arrival order. Error chunks from individual agents are
 * tagged and emitted (other agents continue).
 *
 * @example
 * ```typescript
 * const merged = mergeTaggedStreams([
 *   { agentId: "researcher", stream: researchStream },
 *   { agentId: "writer", stream: writerStream },
 * ]);
 *
 * for await (const { chunk, agentId } of merged) {
 *   console.log(`[${agentId}]`, chunk);
 * }
 * ```
 */
/** Result from mergeTaggedStreams */
interface MergedTaggedStreamResult {
    stream: AsyncIterable<MultiplexedStreamChunk>;
    /** Number of chunks dropped due to buffer overflow */
    getDroppedCount: () => number;
}
/**
 * Merge multiple tagged async iterables into a single multiplexed stream.
 *
 * @param sources - Array of tagged source streams to merge.
 * @returns A merged stream result with a `getDroppedCount` accessor.
 */
declare function mergeTaggedStreams(sources: TaggedSource[]): MergedTaggedStreamResult;

/**
 * Debug Timeline — AI-specific event log with snapshot correlation.
 *
 * Records agent lifecycle events (start, complete, error, guardrail checks,
 * approvals, handoffs, patterns) and correlates them with core time-travel
 * snapshots for visual timeline UIs and fork-and-replay debugging.
 *
 * Zero-cost when debug=false — the timeline is simply `null`.
 *
 * @module
 */

/** Callback fired when a new event is recorded */
type DebugTimelineListener = (event: DebugEvent) => void;
/** Debug timeline instance */
interface DebugTimeline {
    /** Record a new event (id is auto-assigned) */
    record(event: Omit<DebugEvent, "id"> & Record<string, unknown>): DebugEvent;
    /** Get all events in order */
    getEvents(): DebugEvent[];
    /** Get events for a specific agent */
    getEventsForAgent(agentId: string): DebugEvent[];
    /** Get events by type with type narrowing */
    getEventsByType<T extends DebugEventType>(type: T): Extract<DebugEvent, {
        type: T;
    }>[];
    /** Get events at a specific snapshot */
    getEventsAtSnapshot(snapshotId: number): DebugEvent[];
    /** Get events in a time range */
    getEventsInRange(startMs: number, endMs: number): DebugEvent[];
    /** Fork from a snapshot — truncates events after it and calls goTo */
    forkFrom(snapshotId: number): void;
    /** Export timeline as JSON */
    export(): string;
    /** Import timeline from JSON */
    import(json: string): void;
    /** Clear all events */
    clear(): void;
    /** Subscribe to new events. Returns unsubscribe function. */
    subscribe(listener: DebugTimelineListener): () => void;
    /** Current number of events */
    readonly length: number;
}
/** Options for creating a debug timeline */
interface DebugTimelineOptions {
    /** Maximum events before eviction. @default 2000 */
    maxEvents?: number;
    /** Callback to get current snapshot ID from the system */
    getSnapshotId?: () => number | null;
    /** Callback to navigate to a snapshot (for forkFrom) */
    goToSnapshot?: (snapshotId: number) => void;
}
/**
 * Create a debug timeline for recording and correlating AI events.
 *
 * @example
 * ```typescript
 * const timeline = createDebugTimeline({ maxEvents: 1000 });
 *
 * timeline.record({
 *   type: "agent_start",
 *   timestamp: Date.now(),
 *   agentId: "researcher",
 *   snapshotId: null,
 *   inputLength: 42,
 * });
 *
 * const agentEvents = timeline.getEventsForAgent("researcher");
 * ```
 */
declare function createDebugTimeline(options?: DebugTimelineOptions): DebugTimeline;
/**
 * Create a Directive plugin that bridges core constraint/resolver events
 * to the debug timeline.
 *
 * @example
 * ```typescript
 * const timeline = createDebugTimeline();
 * const plugin = createDebugTimelinePlugin(timeline, () => system.history?.currentIndex ?? null);
 * ```
 */
declare function createDebugTimelinePlugin(timeline: DebugTimeline, getSnapshotId: () => number | null): Plugin;

/**
 * P6: Structured Outputs — Schema validation with auto-retry for LLM responses.
 *
 * Turns unreliable text output into typed, validated data. Appends JSON schema
 * instructions to the system prompt and retries with error feedback on parse failure.
 *
 * Works with any Zod-compatible schema (any object with a `safeParse` method).
 *
 * @module
 *
 * @example
 * ```typescript
 * import { z } from "zod";
 * import { withStructuredOutput, StructuredOutputError } from '@directive-run/ai';
 *
 * const SentimentSchema = z.object({
 *   sentiment: z.enum(["positive", "negative", "neutral"]),
 *   confidence: z.number().min(0).max(1),
 * });
 *
 * const runner = withStructuredOutput(baseRunner, {
 *   schema: SentimentSchema,
 *   maxRetries: 2,
 * });
 *
 * const result = await runner(agent, "Analyze: I love this product!");
 * // result.output is typed as { sentiment: string; confidence: number }
 * ```
 */

/**
 * Zod-compatible schema duck type — any object with a `safeParse` method.
 *
 * This interface allows structured outputs to work with Zod, Valibot,
 * or any validation library that implements this pattern.
 *
 * @example
 * ```typescript
 * import { z } from "zod";
 *
 * // Zod schemas implement SafeParseable automatically
 * const schema = z.object({ name: z.string() });
 *
 * // Custom schema
 * const custom: SafeParseable<{ name: string }> = {
 *   safeParse(value) {
 *     if (typeof value === "object" && value && "name" in value) {
 *       return { success: true, data: value as { name: string } };
 *     }
 *     return { success: false, error: { message: "Missing name field" } };
 *   },
 * };
 * ```
 */
interface SafeParseable<T = unknown> {
    safeParse(value: unknown): SafeParseResult<T>;
    /** Optional: schema description injected into the system prompt. */
    description?: string;
}
interface SafeParseResult<T> {
    success: boolean;
    data?: T;
    error?: {
        message?: string;
        issues?: Array<{
            message: string;
        }>;
    };
}
interface StructuredOutputConfig<T = unknown> {
    /** Zod-compatible schema with safeParse. */
    schema: SafeParseable<T>;
    /** Max retries on parse/validation failure. @default 2 */
    maxRetries?: number;
    /** Custom JSON extractor. Default: finds first `{...}` or `[...]` in output. */
    extractJson?: (output: string) => unknown;
    /** Schema description to inject into system prompt. Auto-derived from schema.description if available. */
    schemaDescription?: string;
}
/** Default JSON extractor — finds the first `{...}` or `[...]` in output. */
declare function extractJsonFromOutput(output: string): unknown;
/**
 * Wrap an AgentRunner with structured output parsing and validation.
 *
 * @example
 * ```typescript
 * import { z } from "zod";
 *
 * const SentimentSchema = z.object({
 *   sentiment: z.enum(["positive", "negative", "neutral"]),
 *   confidence: z.number().min(0).max(1),
 * });
 *
 * const runner = withStructuredOutput(baseRunner, {
 *   schema: SentimentSchema,
 *   maxRetries: 2,
 * });
 *
 * const result = await runner(agent, "Analyze: I love this product!");
 * // result.output is typed as { sentiment: string; confidence: number }
 * ```
 */
declare function withStructuredOutput<T = unknown>(runner: AgentRunner, config: StructuredOutputConfig<T>): AgentRunner;
/** Error thrown when structured output parsing fails after all retries. */
declare class StructuredOutputError extends Error {
    readonly lastResult: RunResult<unknown> | undefined;
    constructor(message: string, lastResult?: RunResult<unknown>);
}

/** Orchestrator options */
interface OrchestratorOptions<F extends Record<string, unknown>> {
    /** Function to run an agent */
    runner: AgentRunner;
    /**
     * Schema for custom facts tracked in the orchestrator's Directive System.
     * @example
     * ```typescript
     * import { t } from '@directive-run/core';
     * const orchestrator = createOrchestrator({
     *   factsSchema: { confidence: t.number(), category: t.string() },
     *   // ...
     * });
     * ```
     */
    factsSchema?: Record<string, {
        _type: unknown;
        _validators: [];
    }>;
    /** Initialize additional facts */
    init?: (facts: F & OrchestratorState) => void;
    /** Constraints for orchestration */
    constraints?: Record<string, OrchestratorConstraint<F>>;
    /** Resolvers for orchestration */
    resolvers?: Record<string, OrchestratorResolver<F, Requirement>>;
    /** Guardrails */
    guardrails?: GuardrailsConfig;
    /** Callback for approval requests */
    onApprovalRequest?: (request: ApprovalRequest) => void;
    /**
     * Auto-approve tool calls
     * @default true
     */
    autoApproveToolCalls?: boolean;
    /**
     * Maximum token budget across all agent runs.
     *
     * When exceeded, agents are automatically paused with status "paused".
     * Check `facts.agent.tokenUsage` to see current usage.
     *
     * For more sophisticated cost management (per-user budgets, tiered pricing,
     * cost alerts), see the Cost Management section in the documentation.
     *
     * @example
     * ```typescript
     * const orchestrator = createAgentOrchestrator({
     *   maxTokenBudget: 10000, // Pause after 10K tokens
     * });
     *
     * // Check if paused due to budget
     * if (orchestrator.facts.agent.status === 'paused') {
     *   console.log('Budget exceeded:', orchestrator.facts.agent.tokenUsage);
     * }
     * ```
     */
    maxTokenBudget?: number;
    /** Fires when token usage reaches this percentage of maxTokenBudget (0-1). @default 0.8 */
    budgetWarningThreshold?: number;
    /** Callback when budget warning threshold is reached */
    onBudgetWarning?: (event: {
        currentTokens: number;
        maxBudget: number;
        percentage: number;
    }) => void;
    /** Plugins */
    plugins?: Plugin[];
    /**
     * Enable debugging — `true` for default debug, or config object for advanced options
     * @default false
     */
    debug?: boolean | OrchestratorDebugConfig;
    /**
     * Approval timeout in milliseconds
     * @default 300000 (5 minutes)
     */
    approvalTimeoutMs?: number;
    /** Retry configuration for agent runs (no retries if not specified) */
    agentRetry?: AgentRetryConfig;
    /** Lifecycle hooks for observability */
    hooks?: OrchestratorLifecycleHooks;
    /**
     * Optional memory instance. When provided, context messages are auto-injected
     * into agent instructions before each run, and result messages are auto-stored.
     */
    memory?: AgentMemory;
    /**
     * Optional circuit breaker. Wraps every run() call.
     * When OPEN, throws CircuitBreakerOpenError instead of calling the agent.
     */
    circuitBreaker?: CircuitBreaker;
    /** Self-healing configuration for automatic fallback */
    selfHealing?: SelfHealingConfig;
    /**
     * Default schema for structured output. When set, agent output is parsed and
     * validated against this schema with automatic retry on failure.
     * Any Zod-compatible schema (anything with `safeParse`) works.
     */
    outputSchema?: SafeParseable<unknown>;
    /**
     * Max retries for structured output parsing.
     * @default 2
     */
    maxSchemaRetries?: number;
    /** Optional checkpoint store for save/restore workflow state. */
    checkpointStore?: CheckpointStore;
    /**
     * Breakpoint configurations for human-in-the-loop pause points.
     * Zero overhead when empty — guard checks at each insertion point.
     */
    breakpoints?: BreakpointConfig[];
    /** Callback fired when a breakpoint is hit and waiting for resolution. */
    onBreakpoint?: (request: BreakpointRequest) => void;
    /**
     * Timeout for breakpoint resolution in milliseconds.
     * @default 300000 (5 minutes)
     */
    breakpointTimeoutMs?: number;
    /**
     * Include system meta in agent instructions for structured LLM reasoning.
     * When true, constraint labels, resolver descriptions, fact annotations,
     * and module metadata are injected into the agent's system prompt.
     * @default false
     */
    metaContext?: boolean;
}
/** Streaming run result from orchestrator */
interface OrchestratorStreamResult<T = unknown> {
    /** Async iterator for streaming chunks */
    stream: AsyncIterable<OrchestratorStreamChunk>;
    /** Promise that resolves to the final result */
    result: Promise<RunResult<T>>;
    /** Abort the stream */
    abort: () => void;
}
/** Stream chunk types for orchestrator — extends StreamChunk with approval events */
type OrchestratorStreamChunk = StreamChunk | {
    type: "approval_required";
    requestId: string;
    toolName: string;
} | {
    type: "approval_resolved";
    requestId: string;
    approved: boolean;
};
/** Per-call options for run() */
interface RunCallOptions {
    /** Override output guardrails for this call only. Set to [] to skip. */
    outputGuardrails?: Array<GuardrailFn<OutputGuardrailData> | NamedGuardrail<OutputGuardrailData>>;
    /** Override input guardrails for this call only. Set to [] to skip. */
    inputGuardrails?: Array<GuardrailFn<InputGuardrailData> | NamedGuardrail<InputGuardrailData>>;
    /** Signal for abort */
    signal?: AbortSignal;
    /** Override structured output schema for this call. Set to `null` to opt out. */
    outputSchema?: SafeParseable<unknown> | null;
    /** Override max schema retries for this call. */
    maxSchemaRetries?: number;
}
/** Orchestrator instance */
interface AgentOrchestrator<F extends Record<string, unknown>> {
    system: System<any>;
    facts: F & OrchestratorState;
    /** Run an agent with guardrails. Pass options to override guardrails per-call. */
    run<T>(agent: AgentLike, input: string, options?: RunCallOptions): Promise<RunResult<T>>;
    /**
     * Run an agent with streaming support.
     * Returns an async iterator for chunks and a promise for the final result.
     *
     * @example
     * ```typescript
     * const { stream, result, abort } = orchestrator.runStream(agent, input);
     *
     * for await (const chunk of stream) {
     *   if (chunk.type === 'token') process.stdout.write(chunk.data);
     *   if (chunk.type === 'approval_required') showApprovalDialog(chunk);
     *   if (chunk.type === 'guardrail_triggered') handleGuardrail(chunk);
     * }
     *
     * const finalResult = await result;
     * ```
     */
    runStream<T>(agent: AgentLike, input: string, options?: {
        signal?: AbortSignal;
    }): OrchestratorStreamResult<T>;
    /** Approve a pending request */
    approve(requestId: string): void;
    /** Reject a pending request */
    reject(requestId: string, reason?: string): void;
    /** Pause all agents */
    pause(): void;
    /** Resume agents */
    resume(): void;
    /** Reset conversation state */
    reset(): void;
    /** Total tokens consumed across all agent runs */
    readonly totalTokens: number;
    /** Debug timeline (null when debug is false) */
    readonly timeline: DebugTimeline | null;
    /** Wait until agent is idle. Resolves immediately if already idle. */
    waitForIdle(timeoutMs?: number): Promise<void>;
    /** Create a checkpoint of the current orchestrator state. Only valid when agent is not running. */
    checkpoint(options?: {
        label?: string;
    }): Promise<Checkpoint>;
    /** Restore orchestrator state from a checkpoint. */
    restore(checkpoint: Checkpoint, options?: {
        restoreTimeline?: boolean;
    }): void;
    /** Resume a pending breakpoint, optionally with input modifications. */
    resumeBreakpoint(id: string, modifications?: BreakpointModifications): void;
    /** Cancel a pending breakpoint with optional reason. */
    cancelBreakpoint(id: string, reason?: string): void;
    /** Get all currently pending breakpoint requests. */
    getPendingBreakpoints(): BreakpointRequest[];
    /** Destroy the orchestrator, releasing all resources. */
    destroy(): void;
}
/**
 * Create a constraint-driven agent orchestrator backed by a Directive System.
 *
 * Wraps a single agent runner with reactive state, guardrails, streaming,
 * approval workflows, breakpoints, structured output, and lifecycle hooks.
 * Constraints and resolvers let you declaratively control agent behavior
 * based on runtime facts.
 *
 * @param options - Orchestrator configuration including runner, guardrails, constraints, and plugins.
 * @returns An {@link AgentOrchestrator} instance with `run`, `runStream`, `approve`/`reject`, and checkpoint APIs.
 *
 * @example
 * ```typescript
 * import { run as runner } from '@openai/agents';
 *
 * const orchestrator = createAgentOrchestrator({
 *   runner,
 *   constraints: {
 *     escalateToExpert: {
 *       when: (facts) => facts.agent.output?.confidence < 0.7,
 *       require: (facts) => ({
 *         type: 'RUN_EXPERT_AGENT',
 *         query: facts.agent.input,
 *       }),
 *     },
 *     budgetExceeded: {
 *       when: (facts) => facts.agent.tokenUsage > 10000,
 *       require: { type: 'PAUSE_AGENTS' },
 *     },
 *   },
 *   guardrails: {
 *     input: [
 *       async (data) => {
 *         const hasPII = await detectPII(data.input);
 *         return { passed: !hasPII, reason: hasPII ? 'Contains PII' : undefined };
 *       },
 *     ],
 *     output: [
 *       async (data) => {
 *         const isToxic = await checkToxicity(data.output);
 *         return { passed: !isToxic, reason: isToxic ? 'Toxic content' : undefined };
 *       },
 *     ],
 *   },
 * });
 *
 * // Run with guardrails and constraint-driven orchestration
 * const result = await orchestrator.run(myAgent, 'Hello, can you help me?');
 * ```
 *
 * @throws If autoApproveToolCalls is false but no onApprovalRequest callback is provided
 * @public
 */
declare function createAgentOrchestrator<F extends Record<string, unknown> = Record<string, never>>(options: OrchestratorOptions<F>): AgentOrchestrator<F>;

/**
 * Health Monitor — tracks per-agent health metrics for self-healing networks.
 *
 * Pure computation module with zero Directive dependency.
 * Maintains a rolling window of success/failure events and computes a health
 * score from 0-100 based on configurable weights.
 *
 * @module
 */

/** Circuit state values */
type HealthCircuitState = "CLOSED" | "OPEN" | "HALF_OPEN";
/** Per-agent health metrics */
interface AgentHealthMetrics {
    agentId: string;
    circuitState: HealthCircuitState;
    successRate: number;
    avgLatencyMs: number;
    recentFailures: number;
    recentSuccesses: number;
    healthScore: number;
    /** Last N error messages (most recent last) */
    lastErrors: string[];
}
/** Health monitor instance */
interface HealthMonitor {
    recordSuccess(agentId: string, latencyMs: number): void;
    recordFailure(agentId: string, latencyMs: number, error?: Error): void;
    getMetrics(agentId: string): AgentHealthMetrics;
    getAllMetrics(): Record<string, AgentHealthMetrics>;
    /** Returns a 0-100 health score. Returns 50 (neutral) when no data is available for the agent. */
    getHealthScore(agentId: string): number;
    updateCircuitState(agentId: string, state: HealthCircuitState): void;
    /** Reset all metrics. Useful for testing. */
    reset(): void;
}
/**
 * Create a health monitor that tracks per-agent metrics.
 *
 * @example
 * ```typescript
 * const monitor = createHealthMonitor({ windowMs: 30000 });
 *
 * monitor.recordSuccess("agent-a", 120);
 * monitor.recordFailure("agent-a", 5000, new Error("timeout"));
 *
 * const score = monitor.getHealthScore("agent-a");
 * console.log(score); // 0-100
 * ```
 */
declare function createHealthMonitor(config?: HealthMonitorConfig): HealthMonitor;

/**
 * Agent Reflection / Self-Improvement
 *
 * Quality-based iteration: agent produces output → evaluator checks it → retry
 * with feedback until pass. Works with any AgentRunner.
 *
 * Shipped with aggressive safeguards to prevent silent budget burn:
 * - maxIterations default: 2 (conservative)
 * - Dev-mode warning for maxIterations > 3
 * - onIteration fires on every iteration (observable by default)
 * - Token usage accumulated across iterations
 *
 * @example
 * ```typescript
 * import { withReflection } from '@directive-run/ai';
 *
 * const reflective = withReflection(runner, {
 *   evaluate: (output) => ({
 *     passed: output.includes('conclusion'),
 *     feedback: 'Missing conclusion section',
 *   }),
 *   maxIterations: 2,
 * });
 *
 * const result = await reflective(agent, 'Write a report');
 * ```
 */

/** Context passed to the reflection evaluator */
interface ReflectionContext {
    input: string;
    /** 0-based iteration number */
    iteration: number;
    result: RunResult<unknown>;
    history: ReflectionEvaluation[];
}
/** Result of a reflection evaluation */
interface ReflectionEvaluation {
    passed: boolean;
    feedback?: string;
    /** Quality score from 0 to 1, optional */
    score?: number;
}
/** Evaluator function for reflection */
type ReflectionEvaluator<T = unknown> = (output: T, context: ReflectionContext) => ReflectionEvaluation | Promise<ReflectionEvaluation>;
/** Configuration for the reflection wrapper */
interface ReflectionConfig<T = unknown> {
    /** Evaluator function — decides if the output is acceptable */
    evaluate: ReflectionEvaluator<T>;
    /** Maximum iterations (including the first). Default: 2 (conservative) */
    maxIterations?: number;
    /** Build the retry input from original input + feedback */
    buildRetryInput?: (input: string, feedback: string, iteration: number) => string;
    /** Callback on each iteration */
    onIteration?: (event: {
        iteration: number;
        passed: boolean;
        feedback?: string;
        score?: number;
        durationMs: number;
    }) => void;
    /** Behavior when maxIterations exhausted. Default: "accept-last" */
    onExhausted?: "accept-last" | "throw";
    /** Stop early if budget remaining < threshold (tokens). Works with withBudget. */
    budgetThreshold?: number;
}
/** Error thrown when reflection iterations are exhausted and onExhausted is "throw" */
declare class ReflectionExhaustedError extends Error {
    readonly iterations: number;
    readonly history: ReflectionEvaluation[];
    readonly lastResult: RunResult<unknown>;
    readonly totalTokens: number;
    constructor(options: {
        iterations: number;
        history: ReflectionEvaluation[];
        lastResult: RunResult<unknown>;
        totalTokens: number;
    });
}
/**
 * Wrap an AgentRunner with reflection (self-improvement) logic.
 *
 * The returned runner runs the agent, evaluates the output, and retries with
 * feedback if the evaluation fails — up to `maxIterations` times.
 *
 * @example
 * ```typescript
 * const reflective = withReflection(runner, {
 *   evaluate: (output) => ({
 *     passed: typeof output === 'string' && output.length > 100,
 *     feedback: 'Response too short, please elaborate',
 *     score: Math.min(1, (output as string).length / 200),
 *   }),
 *   maxIterations: 3,
 *   onExhausted: 'accept-last',
 * });
 * ```
 */
declare function withReflection<T = unknown>(runner: AgentRunner, config: ReflectionConfig<T>): AgentRunner;

/** Configuration for a registered agent */
interface AgentRegistration {
    /** The agent instance */
    agent: AgentLike;
    /** Maximum concurrent runs for this agent. @default 1 */
    maxConcurrent?: number;
    /** Timeout for agent runs (ms) */
    timeout?: number;
    /** Custom run options */
    runOptions?: Omit<RunOptions, "signal">;
    /** Description for constraint-based selection */
    description?: string;
    /** Capabilities this agent has */
    capabilities?: string[];
    /** Per-agent guardrails (applied in addition to orchestrator-level guardrails) */
    guardrails?: {
        input?: Array<GuardrailFn<InputGuardrailData> | NamedGuardrail<InputGuardrailData>>;
        output?: Array<GuardrailFn<OutputGuardrailData> | NamedGuardrail<OutputGuardrailData>>;
        toolCall?: Array<GuardrailFn<ToolCallGuardrailData> | NamedGuardrail<ToolCallGuardrailData>>;
    };
    /** Per-agent retry config (overrides orchestrator-level agentRetry) */
    retry?: AgentRetryConfig;
    /** Per-agent constraints */
    constraints?: Record<string, OrchestratorConstraint<Record<string, unknown>>>;
    /** Per-agent resolvers */
    resolvers?: Record<string, OrchestratorResolver<Record<string, unknown>, Requirement>>;
    /** Per-agent memory (overrides orchestrator-level memory) */
    memory?: AgentMemory;
    /** Per-agent circuit breaker (overrides orchestrator-level circuitBreaker) */
    circuitBreaker?: CircuitBreaker;
    /** Per-agent output schema for structured output */
    outputSchema?: SafeParseable<unknown>;
    /** Max retries for structured output validation. @default 2 */
    maxSchemaRetries?: number;
    /** Custom JSON extractor for structured output */
    extractJson?: (output: string) => unknown;
    /** Description of the schema for structured output prompting */
    schemaDescription?: string;
}
/** Agent registry configuration */
interface AgentRegistry {
    [agentId: string]: AgentRegistration;
}
/** Parallel execution pattern - run handlers concurrently and merge results */
interface ParallelPattern<T = unknown> {
    type: "parallel";
    /** Handler IDs (agents or tasks) to run in parallel (can repeat for multiple instances) */
    handlers: string[];
    /** Function to merge results from all handlers */
    merge: (results: RunResult<unknown>[]) => T | Promise<T>;
    /** Minimum successful results required. @default handlers.length */
    minSuccess?: number;
    /** Overall timeout (ms) */
    timeout?: number;
}
/** Sequential execution pattern - pipeline of handlers */
interface SequentialPattern<T = unknown> {
    type: "sequential";
    /** Handler IDs (agents or tasks) in execution order */
    handlers: string[];
    /** Transform output to next input. @default JSON.stringify */
    transform?: (output: unknown, handlerId: string, index: number) => string;
    /** Final result extractor */
    extract?: (output: unknown) => T;
    /** Continue on error. @default false */
    continueOnError?: boolean;
    /** Checkpoint configuration for mid-execution fault tolerance */
    checkpoint?: PatternCheckpointConfig;
}
/** Supervisor pattern - one agent directs others */
interface SupervisorPattern<T = unknown> {
    type: "supervisor";
    /** Supervisor agent ID */
    supervisor: string;
    /** Worker agent IDs */
    workers: string[];
    /** Maximum delegation rounds. @default 5 */
    maxRounds?: number;
    /** Extract final result */
    extract?: (supervisorOutput: unknown, workerResults: RunResult<unknown>[]) => T;
    /** Checkpoint configuration for mid-execution fault tolerance */
    checkpoint?: PatternCheckpointConfig;
}
/** Record of a single reflection iteration (for score history) */
interface ReflectIterationRecord {
    iteration: number;
    passed: boolean;
    score?: number;
    feedback?: string;
    durationMs: number;
    producerTokens: number;
    evaluatorTokens: number;
}
/**
 * Reflect pattern - produce, evaluate, retry with feedback.
 * @see reflect — factory helper
 * @see ReflectIterationRecord — per-iteration history entries
 */
interface ReflectPattern<T = unknown> {
    type: "reflect";
    /** Producer handler ID (agent or task) */
    handler: string;
    /** Evaluator agent ID (receives output as input) */
    evaluator: string;
    /** Maximum iterations. @default 2 */
    maxIterations?: number;
    /** Parse evaluator output into ReflectionEvaluation. @default JSON.parse */
    parseEvaluation?: (output: unknown) => ReflectionEvaluation;
    /** Build retry input from original input + feedback */
    buildRetryInput?: (input: string, feedback: string, iteration: number) => string;
    /** Extract result from raw producer output. Unlike race's extract (which receives RunResult), this receives the output directly since the producer is already selected. */
    extract?: (output: unknown) => T;
    /** Behavior when maxIterations exhausted. @default "accept-last" */
    onExhausted?: "accept-last" | "accept-best" | "throw";
    /** Callback fired after each iteration with score/feedback data. @see ReflectIterationRecord */
    onIteration?: (record: ReflectIterationRecord) => void;
    /** AbortSignal for external cancellation of the reflection loop */
    signal?: AbortSignal;
    /** Overall timeout (ms). Creates an internal AbortSignal. */
    timeout?: number;
    /** Score threshold for acceptance. Number or function of iteration. When set, evaluator score >= threshold is treated as passed. */
    threshold?: number | ((iteration: number) => number);
    /** Checkpoint configuration for mid-execution fault tolerance */
    checkpoint?: PatternCheckpointConfig;
}
/**
 * Race pattern - first successful agent wins, rest cancelled.
 * @see race — factory helper
 * @see RaceResult — return type
 */
interface RacePattern<T = unknown> {
    type: "race";
    /** Handler IDs (agents or tasks) to race */
    handlers: string[];
    /** Extract result from winning RunResult (receives full RunResult for access to tokens/metadata). @default output field */
    extract?: (result: RunResult<unknown>) => T;
    /** Overall timeout (ms) */
    timeout?: number;
    /** Require N successful results before resolving. @default 1 */
    minSuccess?: number;
    /** AbortSignal for external cancellation */
    signal?: AbortSignal;
}
/** Return type from debate pattern execution */
interface DebateResult<T = unknown> {
    winnerId: string;
    result: T;
    rounds: Array<{
        proposals: Array<{
            agentId: string;
            output: unknown;
        }>;
        judgement: {
            winnerId: string;
            feedback?: string;
            score?: number;
        };
    }>;
}
/** Individual result entry returned when minSuccess > 1 */
interface RaceSuccessEntry<T = unknown> {
    agentId: string;
    result: T;
}
/** Return type from race pattern execution */
interface RaceResult<T = unknown> {
    winnerId: string;
    result: T;
    allResults?: Array<RaceSuccessEntry<T>>;
}
/**
 * Debate pattern - agents compete, evaluator judges across rounds.
 * @see debate — factory helper
 * @see runDebate — imperative API
 * @see DebateResult — return type
 */
interface DebatePattern<T = unknown> {
    type: "debate";
    /** Handler IDs (agents or tasks) that will generate competing proposals */
    handlers: string[];
    /** Evaluator agent ID that judges proposals */
    evaluator: string;
    /** Maximum rounds of debate. @default 2 */
    maxRounds?: number;
    /** Extract final result from the winning proposal */
    extract?: (output: unknown) => T;
    /** Parse evaluator output. @default JSON.parse expecting `{ winnerId, feedback }` */
    parseJudgement?: (output: unknown) => {
        winnerId: string;
        feedback?: string;
        score?: number;
    };
    /** AbortSignal for external cancellation */
    signal?: AbortSignal;
    /** Overall timeout (ms). Creates an internal AbortSignal. */
    timeout?: number;
    /** Checkpoint configuration for mid-execution fault tolerance */
    checkpoint?: PatternCheckpointConfig;
}

/** Union of all patterns */
type ExecutionPattern<T = unknown> = ParallelPattern<T> | SequentialPattern<T> | SupervisorPattern<T> | DagPattern<T> | ReflectPattern<T> | RacePattern<T> | DebatePattern<T> | GoalPattern<T>;
/** Handoff request between agents */
interface HandoffRequest {
    id: string;
    fromAgent: string;
    toAgent: string;
    input: string;
    context?: Record<string, unknown>;
    requestedAt: number;
}
/** Handoff result */
interface HandoffResult {
    request: HandoffRequest;
    result: RunResult<unknown>;
    completedAt: number;
}
/** Run agent requirement */
interface RunAgentRequirement extends Requirement {
    type: "RUN_AGENT";
    agent: string;
    input: string;
    context?: Record<string, unknown>;
}
/** Read-only context passed to task functions */
interface TaskContext {
    /** The ID of this task */
    taskId: string;
    /** Conversation history from orchestrator memory (read-only deep copy) */
    memory: ReadonlyArray<{
        role: string;
        content: string;
    }>;
    /** Current scratchpad state (read-only deep copy) */
    scratchpad: Readonly<Record<string, unknown>>;
    /** Read the state of any registered agent or task (status, lastOutput, lastError, totalTokens) */
    readAgentState: (nodeId: string) => Readonly<{
        status: string;
        lastOutput?: string;
        lastError?: string;
        totalTokens: number;
    }> | undefined;
    /** Report intermediate progress (0-100) for DevTools timeline */
    reportProgress: (percent: number, message?: string) => void;
}
/** Configuration for a registered task (imperative code) */
interface TaskRegistration {
    /** The function to execute. Receives input, abort signal, and context. */
    run: (input: string, signal: AbortSignal, context: TaskContext) => unknown | Promise<unknown>;
    /** Display label for DevTools graph. Defaults to task ID. */
    label?: string;
    /** Description for DevTools tooltip/detail panel. */
    description?: string;
    /** Timeout (ms) */
    timeout?: number;
    /** Max concurrent executions of this task. @default 1 */
    maxConcurrent?: number;
    /** Optional retry configuration for transient failures */
    retry?: {
        /** Max number of attempts (including the first try) */
        attempts: number;
        /** Backoff strategy between retries. @default 'fixed' */
        backoff?: "fixed" | "exponential";
        /** Base delay between retries (ms). @default 1000 */
        delayMs?: number;
    };
}
/** Multi-agent orchestrator options */
interface MultiAgentOrchestratorOptions {
    /** Base run function */
    runner: AgentRunner;
    /** Registered agents */
    agents: AgentRegistry;
    /** Imperative code tasks, referenced by ID in patterns (same namespace as agents) */
    tasks?: Record<string, TaskRegistration>;
    /** Execution patterns */
    patterns?: Record<string, ExecutionPattern>;
    /** Handoff callbacks */
    onHandoff?: (request: HandoffRequest) => void;
    /** Handoff completion callbacks */
    onHandoffComplete?: (result: HandoffResult) => void;
    /** Maximum number of handoff results to retain. @default 1000 */
    maxHandoffHistory?: number;
    /** Debug mode — `true` for default debug, or config object for advanced options */
    debug?: boolean | OrchestratorDebugConfig;
    /** Orchestrator-level guardrails (applied to all agents) */
    guardrails?: GuardrailsConfig;
    /** Lifecycle hooks */
    hooks?: MultiAgentLifecycleHooks;
    /** Shared memory across all agents */
    memory?: AgentMemory;
    /** Default retry config for all agents (per-agent overrides this) */
    agentRetry?: AgentRetryConfig;
    /** Maximum token budget across all agent runs */
    maxTokenBudget?: number;
    /** Fires when token usage reaches this percentage of maxTokenBudget (0-1). @default 0.8 */
    budgetWarningThreshold?: number;
    /** Callback when budget warning threshold is reached */
    onBudgetWarning?: (event: {
        currentTokens: number;
        maxBudget: number;
        percentage: number;
    }) => void;
    /** Plugins to attach to the underlying Directive System */
    plugins?: Plugin[];
    /** Callback for approval requests */
    onApprovalRequest?: (request: ApprovalRequest) => void;
    /** Auto-approve tool calls. @default true */
    autoApproveToolCalls?: boolean;
    /** Approval timeout in milliseconds. @default 300000 */
    approvalTimeoutMs?: number;
    /** Orchestrator-level constraints */
    constraints?: Record<string, OrchestratorConstraint<Record<string, unknown>>>;
    /** Orchestrator-level resolvers */
    resolvers?: Record<string, OrchestratorResolver<Record<string, unknown>, Requirement>>;
    /** Orchestrator-level circuit breaker */
    circuitBreaker?: CircuitBreaker;
    /** Self-healing configuration for automatic agent rerouting */
    selfHealing?: MultiAgentSelfHealingConfig;
    /** Checkpoint store for persistent state */
    checkpointStore?: CheckpointStore;
    /** Breakpoints for human-in-the-loop pause/inspect/modify */
    breakpoints?: BreakpointConfig<MultiAgentBreakpointType>[];
    /** Callback when a breakpoint fires */
    onBreakpoint?: (request: BreakpointRequest) => void;
    /** Timeout for breakpoint resolution (ms). @default 300000 */
    breakpointTimeoutMs?: number;
    /** Cross-agent derivation functions — compute values from combined agent states */
    derive?: Record<string, CrossAgentDerivationFn>;
    /** Shared scratchpad configuration */
    scratchpad?: {
        init: Record<string, unknown>;
    };
    /**
     * Include system meta in agent instructions for structured LLM reasoning.
     * When true, constraint labels, resolver descriptions, fact annotations,
     * and module metadata are injected into each agent's system prompt.
     * @default false
     */
    metaContext?: boolean;
}
/** Multi-agent state in facts */
interface MultiAgentState {
    /** Namespace for each agent's state */
    __agents: Record<string, {
        status: "idle" | "running" | "completed" | "error";
        lastInput?: string;
        lastOutput?: unknown;
        lastError?: string;
        runCount: number;
        totalTokens: number;
    }>;
    /** Pending handoffs */
    __handoffs: HandoffRequest[];
    /** Completed handoffs */
    __handoffResults: HandoffResult[];
}
/** Per-call options for multi-agent runAgent/run */
interface MultiAgentRunCallOptions extends RunOptions {
    /** Override structured output schema for this call. Set to `null` to opt out of per-agent schema. */
    outputSchema?: SafeParseable<unknown> | null;
    /** Override max schema retries for this call. */
    maxSchemaRetries?: number;
    /** Pattern ID that initiated this run (for lifecycle hooks). Set internally by pattern executors. */
    patternId?: string;
}
/** Multi-agent orchestrator instance */
interface MultiAgentOrchestrator {
    /** The underlying Directive System */
    system: System<any>;
    /** Combined facts from all agent modules + coordinator */
    facts: Record<string, unknown>;
    /** Run a single agent */
    runAgent<T>(agentId: string, input: string, options?: MultiAgentRunCallOptions): Promise<RunResult<T>>;
    /** Run an agent with streaming support */
    runAgentStream<T>(agentId: string, input: string, options?: {
        signal?: AbortSignal;
    }): OrchestratorStreamResult<T>;
    /**
     * Run an execution pattern by its registered pattern ID.
     *
     * Note: For race and debate patterns, `runPattern` returns only the extracted result value.
     * Use `runRace()` or `runDebate()` to access full results including `winnerId` and `allResults`.
     */
    runPattern<T>(patternId: string, input: string): Promise<T>;
    /** Run agents in parallel. Note: parallel does not support checkpoint/resume (single-step pattern). */
    runParallel<T>(agentIds: string[], inputs: string | string[], merge: (results: RunResult<unknown>[]) => T | Promise<T>, options?: {
        minSuccess?: number;
        timeout?: number;
    }): Promise<T>;
    /** Run agents sequentially */
    runSequential<T>(agentIds: string[], initialInput: string, options?: {
        transform?: (output: unknown, agentId: string, index: number) => string;
    }): Promise<RunResult<T>[]>;
    /** Request a handoff between agents */
    handoff(fromAgent: string, toAgent: string, input: string, context?: Record<string, unknown>): Promise<RunResult<unknown>>;
    /** Approve a pending request */
    approve(requestId: string): void;
    /** Reject a pending request */
    reject(requestId: string, reason?: string): void;
    /** Pause all agents */
    pause(): void;
    /** Resume agents */
    resume(): void;
    /** Total tokens consumed across all agents */
    readonly totalTokens: number;
    /** Wait until all agents are idle */
    waitForIdle(timeoutMs?: number): Promise<void>;
    /** Alias for runAgent */
    run<T>(agentId: string, input: string, options?: MultiAgentRunCallOptions): Promise<RunResult<T>>;
    /** Alias for runAgentStream */
    runStream<T>(agentId: string, input: string, options?: {
        signal?: AbortSignal;
    }): OrchestratorStreamResult<T>;
    /** Register a new agent dynamically */
    registerAgent(agentId: string, registration: AgentRegistration): void;
    /** Unregister an agent (must be idle) */
    unregisterAgent(agentId: string): void;
    /** Get registered agent IDs */
    getAgentIds(): string[];
    /** Register a new task dynamically */
    registerTask(taskId: string, registration: TaskRegistration): void;
    /** Unregister a task */
    unregisterTask(taskId: string): void;
    /** Get registered task IDs */
    getTaskIds(): string[];
    /** Get task registry info (labels + descriptions) */
    getTaskRegistry(): Record<string, {
        label?: string;
        description?: string;
    }>;
    /** Get task state */
    getTaskState(taskId: string): {
        status: string;
        lastOutput?: unknown;
        lastError?: string;
        startTime?: number;
        durationMs?: number;
    } | undefined;
    /** Get all task states */
    getAllTaskStates(): Record<string, {
        status: string;
        lastOutput?: unknown;
        lastError?: string;
        startTime?: number;
        durationMs?: number;
    }>;
    /** Get all handler IDs (agents + tasks combined) */
    getNodeIds(): string[];
    /** Get agent state */
    getAgentState(agentId: string): MultiAgentState["__agents"][string] | undefined;
    /** Get all agent states */
    getAllAgentStates(): Record<string, MultiAgentState["__agents"][string]>;
    /** Get pending handoffs */
    getPendingHandoffs(): HandoffRequest[];
    /** Reset all agent states */
    reset(): void;
    /** Debug timeline (null when debug is false) */
    readonly timeline: DebugTimeline | null;
    /** Health monitor (null when selfHealing is not configured) */
    readonly healthMonitor: HealthMonitor | null;
    /** Create a checkpoint of the current state */
    checkpoint(options?: {
        label?: string;
    }): Promise<Checkpoint>;
    /** Restore from a checkpoint */
    restore(checkpoint: Checkpoint, options?: {
        restoreTimeline?: boolean;
    }): void;
    /** Run multiple agents with multiplexed streaming */
    runParallelStream<T>(agentIds: string[], inputs: string | string[], merge: (results: RunResult<unknown>[]) => T | Promise<T>, options?: {
        minSuccess?: number;
        timeout?: number;
        signal?: AbortSignal;
    }): MultiplexedStreamResult<T>;
    /** Resume a paused breakpoint */
    resumeBreakpoint(id: string, modifications?: BreakpointModifications): void;
    /** Cancel a paused breakpoint */
    cancelBreakpoint(id: string, reason?: string): void;
    /** Get pending breakpoints */
    getPendingBreakpoints(): BreakpointRequest[];
    /** Race multiple agents — first successful result wins, rest cancelled. Note: race does not support checkpoint/resume (single-step pattern). */
    runRace<T>(agentIds: string[], input: string, options?: {
        extract?: (result: RunResult<unknown>) => T;
        timeout?: number;
        minSuccess?: number;
        signal?: AbortSignal;
    }): Promise<RaceResult<T>>;
    /** Run a reflect pattern imperatively (no pre-registration needed) */
    runReflect<T>(producerId: string, evaluatorId: string, input: string, options?: {
        maxIterations?: number;
        parseEvaluation?: (output: unknown) => ReflectionEvaluation;
        buildRetryInput?: (input: string, feedback: string, iteration: number) => string;
        extract?: (output: unknown) => T;
        onExhausted?: "accept-last" | "accept-best" | "throw";
        onIteration?: (record: ReflectIterationRecord) => void;
        signal?: AbortSignal;
        timeout?: number;
        threshold?: number | ((iteration: number) => number);
    }): Promise<{
        result: T;
        iterations: number;
        history: ReflectIterationRecord[];
        exhausted: boolean;
    }>;
    /** Run a debate imperatively (no pre-registration needed) */
    runDebate<T>(agentIds: string[], evaluatorId: string, input: string, options?: {
        maxRounds?: number;
        extract?: (output: unknown) => T;
        parseJudgement?: (output: unknown) => {
            winnerId: string;
            feedback?: string;
            score?: number;
        };
        signal?: AbortSignal;
        timeout?: number;
    }): Promise<DebateResult<T>>;
    /** Run a goal pattern imperatively — declare desired state, let the runtime resolve */
    runGoal<T>(nodes: Record<string, GoalNode>, initialInput: string | Record<string, unknown>, when: (facts: Record<string, unknown>) => boolean, options?: {
        satisfaction?: (facts: Record<string, unknown>) => number;
        maxSteps?: number;
        extract?: (facts: Record<string, unknown>) => T;
        timeout?: number;
        signal?: AbortSignal;
        selectionStrategy?: AgentSelectionStrategy;
        relaxation?: RelaxationTier[];
        onStep?: GoalPattern["onStep"];
        onStall?: GoalPattern["onStall"];
        checkpoint?: PatternCheckpointConfig;
    }): Promise<GoalResult<T>>;
    /** Resume a goal pattern from a saved checkpoint */
    resumeGoal<T>(checkpointState: GoalCheckpointState, pattern: GoalPattern<T>): Promise<GoalResult<T>>;
    /** Resume a sequential pattern from a saved checkpoint */
    resumeSequential<T>(checkpointState: SequentialCheckpointState, pattern: SequentialPattern<T>): Promise<T>;
    /** Resume a supervisor pattern from a saved checkpoint */
    resumeSupervisor<T>(checkpointState: SupervisorCheckpointState, pattern: SupervisorPattern<T>, options?: {
        input?: string;
    }): Promise<T>;
    /** Resume a reflect pattern from a saved checkpoint */
    resumeReflect<T>(checkpointState: ReflectCheckpointState, pattern: ReflectPattern<T>, options?: {
        input?: string;
    }): Promise<T>;
    /** Resume a debate pattern from a saved checkpoint */
    resumeDebate<T>(checkpointState: DebateCheckpointState, pattern: DebatePattern<T>): Promise<DebateResult<T>>;
    /** Resume a DAG pattern from a saved checkpoint */
    resumeDag<T>(checkpointState: DagCheckpointState, pattern: DagPattern<T>, options?: {
        input?: string;
    }): Promise<T>;
    /** Replay from a saved checkpoint (auto-detects pattern type) */
    replay<T>(checkpointId: string, pattern: ExecutionPattern, options?: {
        input?: string;
    }): Promise<T>;
    /**
     * Get reflection iteration history from last runReflectPattern call.
     */
    getLastReflectionHistory(): ReflectIterationRecord[] | null;
    /** Cross-agent derived values (frozen snapshot). Empty when derive not configured. */
    readonly derived: Record<string, unknown>;
    /** Subscribe to cross-agent derivation changes */
    onDerivedChange(callback: (id: string, value: unknown) => void): () => void;
    /** Shared scratchpad (null when not configured) */
    readonly scratchpad: Scratchpad | null;
    /** Destroy the orchestrator, resetting all state and releasing resources. */
    destroy(): void;
}

export { type SafeParseResult as $, type AgentRegistry as A, type BackpressureStrategy as B, type MessageChunk as C, type DebatePattern as D, type ExecutionPattern as E, type MessageSummarizer as F, type GuardrailTriggeredChunk as G, type HealthMonitor as H, type MultiAgentRunCallOptions as I, type MultiAgentState as J, type MultiplexedStreamChunk as K, type MultiplexedStreamResult as L, type MultiAgentOrchestratorOptions as M, type OrchestratorStreamChunk as N, type OrchestratorOptions as O, type ParallelPattern as P, type OrchestratorStreamResult as Q, type RacePattern as R, type SequentialPattern as S, type ProgressChunk as T, type RaceResult as U, type RaceSuccessEntry as V, type ReflectionConfig as W, type ReflectionContext as X, type ReflectionEvaluator as Y, ReflectionExhaustedError as Z, type RunCallOptions as _, type MultiAgentOrchestrator as a, type SafeParseable as a0, type StreamChunk as a1, type StreamRunOptions as a2, type StreamRunner as a3, type StreamingGuardrail as a4, type StreamingGuardrailResult as a5, type StreamingRunResult as a6, type StructuredOutputConfig as a7, StructuredOutputError as a8, type TaskContext as a9, tapStream as aA, withReflection as aB, withStructuredOutput as aC, type TaskRegistration as aa, type TokenChunk as ab, type ToolEndChunk as ac, type ToolStartChunk as ad, adaptOutputGuardrail as ae, collectTokens as af, combineStreamingGuardrails as ag, createAgentMemory as ah, createAgentOrchestrator as ai, createDebugTimeline as aj, createDebugTimelinePlugin as ak, createHealthMonitor as al, createHybridStrategy as am, createKeyPointsSummarizer as an, createLLMSummarizer as ao, createLengthStreamingGuardrail as ap, createPatternStreamingGuardrail as aq, createSlidingWindowStrategy as ar, createStreamingRunner as as, createTokenBasedStrategy as at, createToxicityStreamingGuardrail as au, createTruncationSummarizer as av, extractJsonFromOutput as aw, filterStream as ax, mapStream as ay, mergeTaggedStreams as az, type ReflectionEvaluation as b, type ReflectIterationRecord as c, type ReflectPattern as d, type SupervisorPattern as e, type RunAgentRequirement as f, type DebateResult as g, type AgentHealthMetrics as h, type DebugTimeline as i, type AgentMemory as j, type AgentMemoryConfig as k, type AgentOrchestrator as l, type AgentRegistration as m, type DebugTimelineListener as n, type DebugTimelineOptions as o, type DoneChunk as p, type ErrorChunk as q, type HandoffRequest as r, type HandoffResult as s, type HealthCircuitState as t, type MemoryManageResult as u, type MemoryState as v, type MemoryStrategy as w, type MemoryStrategyConfig as x, type MemoryStrategyResult as y, type MergedTaggedStreamResult as z };
