UNPKG

ai-sdk-guardrails

Version:

Input and output guardrails middleware for Vercel AI SDK.

2,115 lines 71.3 kB
import { d as InputGuardrailsMiddlewareConfig, c as OutputGuardrailsMiddlewareConfig, I as InputGuardrail, O as OutputGuardrail, R as RequestContext, e as GuardrailExecutionSummary, N as NormalizedGuardrailContext, b as OutputGuardrailContext, G as GuardrailResult } from '../types-C7t6e3EI.cjs';
import { D as DetectNormalizationOptions } from '../normalization-D6TVuWIv.cjs';
export { a as DEFAULT_DETECT_NORMALIZATION, R as ResolvedDetectNormalizationOptions, n as normalizeForDetection, r as resolveDetectNormalization } from '../normalization-D6TVuWIv.cjs';
import { G as GuardrailViolation } from '../stop-conditions-Dq-WLYV9.cjs';
export { o as SystemPromptLeakResult, r as ToolParameterGuardrailsOptions, q as ToolParameterValidationError, n as detectSystemPromptLeak, w as withToolParameterGuardrails } from '../stop-conditions-Dq-WLYV9.cjs';
import { LanguageModelV4Middleware, LanguageModelV4CallOptions, LanguageModelV4 } from '@ai-sdk/provider';
export { LanguageModelV4, LanguageModelV4CallOptions, LanguageModelV4GenerateResult, LanguageModelV4Middleware, LanguageModelV4StreamPart, LanguageModelV4StreamResult } from '@ai-sdk/provider';
import { ToolSet } from 'ai';

/**
 * AI SDK v7 (provider V4) middleware factories for guardrails.
 *
 * These adapt the `executeInput/OutputGuardrails` engine ({@link ./internal}) to
 * the `LanguageModelV4Middleware` lifecycle (`transformParams` / `wrapGenerate`
 * / `wrapStream`), including the buffer/progressive stream modes and the
 * auto-retry loop. They are the lower-level form behind {@link ../guardrails}'s
 * `withGuardrails`; prefer that for the common path.
 */

/**
 * Creates an input guardrails middleware that executes before AI calls
 * Follows AI SDK 5 middleware patterns
 *
 * @internal Advanced API - Use withGuardrails() for simpler usage
 * @param config - Input guardrails configuration
 * @returns AI SDK middleware that executes input guardrails
 */
declare function inputGuardrailsMiddleware<M extends Record<string, unknown> = Record<string, unknown>>(config: InputGuardrailsMiddlewareConfig<M>): LanguageModelV4Middleware;
/**
 * Creates an output guardrails middleware that executes after AI calls
 * Follows AI SDK 5 middleware patterns
 *
 * @internal Advanced API - Use withGuardrails() for simpler usage
 * @param config - Output guardrails configuration
 * @returns AI SDK middleware that executes output guardrails
 */
declare function outputGuardrailsMiddleware<M extends Record<string, unknown> = Record<string, unknown>>(config: OutputGuardrailsMiddlewareConfig<M>): LanguageModelV4Middleware;

/**
 * Enhanced Prompt Injection Detection
 *
 * Implements the roadmap features:
 * - Incremental Checking: Track conversation state
 * - Enhanced Confidence Scoring: Multi-factor analysis
 * - Tool Call Focus: Check function calls specifically
 * - User Intent Extraction: Better context understanding
 */

interface EnhancedConfidenceScore {
    patternMatch: number;
    contextCoherence: number;
    conversationFlow: number;
    semanticSimilarity: number;
    behavioralAnomaly: number;
    finalScore: number;
}
interface UserIntent {
    primaryIntent: string;
    confidence: number;
    suspiciousElements: string[];
    contextShifts: number;
    manipulationIndicators: string[];
}
interface EnhancedPromptInjectionOptions {
    enableIncremental?: boolean;
    enableToolCallFocus?: boolean;
    enableIntentExtraction?: boolean;
    confidenceThreshold?: number;
    conversationMemory?: number;
    contextShiftThreshold?: number;
    cumulativeThreshold?: number;
    weights?: {
        pattern?: number;
        context?: number;
        flow?: number;
        semantic?: number;
        behavior?: number;
    };
    /**
     * Normalize input before pattern scoring to defeat obfuscation (homoglyphs,
     * zero-width characters, leetspeak, spaced letters, typos). Enabled by
     * default; additive, so it never lowers the raw-text score.
     */
    normalize?: boolean | DetectNormalizationOptions;
}
interface IncrementalAnalysis {
    cumulativeScore: number;
    contextShifts: number;
    messageCount: number;
}
interface EnhancedInjectionMetadata extends Record<string, unknown> {
    enhancedScore: EnhancedConfidenceScore;
    incrementalAnalysis: IncrementalAnalysis | null;
    toolCallAnalysis: {
        suspiciousCalls: number;
        detectedCalls: Array<{
            tool: string;
            confidence: number;
            injectionType: string;
        }>;
    } | null;
    intentAnalysis: UserIntent | null;
    analysisType: string;
    features: {
        incremental: boolean;
        toolCallFocus: boolean;
        intentExtraction: boolean;
    };
}
declare const enhancedPromptInjectionDetector: (options?: EnhancedPromptInjectionOptions) => InputGuardrail<EnhancedInjectionMetadata>;
declare const incrementalPromptInjectionDetector: (options?: {
    conversationMemory?: number;
    cumulativeThreshold?: number;
}) => InputGuardrail;
declare const toolCallInjectionDetector: (options?: {
    confidenceThreshold?: number;
}) => InputGuardrail;
declare const intentBasedInjectionDetector: (options?: {
    confidenceThreshold?: number;
}) => InputGuardrail;

/**
 * Language Model Middleware Factory
 *
 * Creates guardrails as standard AI SDK middleware for use with wrapLanguageModel.
 * This enables composition with other middleware (logging, caching, etc.).
 */

/**
 * Configuration for guardrail middleware
 */
interface GuardrailMiddlewareConfig<MIn extends Record<string, unknown> = Record<string, unknown>, MOut extends Record<string, unknown> = Record<string, unknown>, TContext = Record<string, unknown>> {
    /** Input guardrails to execute before model call */
    inputGuardrails?: InputGuardrail<MIn>[];
    /** Output guardrails to execute after model call */
    outputGuardrails?: OutputGuardrail<MOut>[];
    /** Request-scoped context (user, session, permissions) */
    context?: RequestContext<TContext>;
    /** Whether to throw on blocked input/output */
    throwOnBlocked?: boolean;
    /** Whether to replace blocked output with placeholder */
    replaceOnBlocked?: boolean;
    /** Callback when input is blocked */
    onInputBlocked?: (summary: GuardrailExecutionSummary<MIn>, params: LanguageModelV4CallOptions) => void | Promise<void>;
    /** Callback when output is blocked */
    onOutputBlocked?: (summary: GuardrailExecutionSummary<MOut>, params: LanguageModelV4CallOptions, result: unknown) => void | Promise<void>;
    /** Execution options */
    executionOptions?: {
        parallel?: boolean;
        timeout?: number;
        continueOnFailure?: boolean;
        logLevel?: 'none' | 'error' | 'warn' | 'info' | 'debug';
    };
    /** Skip guardrails for this request (useful for testing) */
    skipGuardrails?: boolean | ((params: LanguageModelV4CallOptions) => boolean);
}
/**
 * Creates a guardrail middleware for use with AI SDK's wrapLanguageModel.
 *
 * This allows guardrails to be composed with other middleware like logging,
 * caching, rate limiting, etc.
 *
 * @example Basic usage
 * ```typescript
 * import { wrapLanguageModel } from 'ai';
 * import { anthropic } from '@ai-sdk/anthropic';
 * import { guardrailMiddleware } from 'ai-sdk-guardrails/guardrails/middleware';
 *
 * const model = wrapLanguageModel({
 *   model: anthropic('claude-3-opus'),
 *   middleware: [
 *     guardrailMiddleware({
 *       inputGuardrails: [promptInjectionDetector()],
 *       outputGuardrails: [piiRedactor()],
 *       throwOnBlocked: true,
 *     }),
 *   ],
 * });
 * ```
 *
 * @example Composing with other middleware
 * ```typescript
 * const model = wrapLanguageModel({
 *   model: openai('gpt-4'),
 *   middleware: [
 *     loggingMiddleware(),
 *     guardrailMiddleware({
 *       inputGuardrails: [rateLimiter(), piiDetector()],
 *       outputGuardrails: [contentFilter()],
 *     }),
 *     cachingMiddleware(),
 *   ],
 * });
 * ```
 *
 * @example With request context
 * ```typescript
 * // Create middleware with context getter
 * const createUserGuardrails = (user: User) =>
 *   guardrailMiddleware({
 *     inputGuardrails: [roleBasedAccess()],
 *     context: {
 *       userId: user.id,
 *       permissions: user.permissions,
 *       organizationId: user.orgId,
 *     },
 *   });
 *
 * // Use per-request
 * const userModel = wrapLanguageModel({
 *   model: baseModel,
 *   middleware: [createUserGuardrails(currentUser)],
 * });
 * ```
 */
declare function guardrailMiddleware<MIn extends Record<string, unknown> = Record<string, unknown>, MOut extends Record<string, unknown> = Record<string, unknown>, TContext = Record<string, unknown>>(config: GuardrailMiddlewareConfig<MIn, MOut, TContext>): LanguageModelV4Middleware;
/**
 * Creates a no-op middleware that skips all guardrails (for testing)
 */
declare function noopGuardrailMiddleware(): LanguageModelV4Middleware;

/**
 * Guardrail Composition DSL
 *
 * Provides utilities for composing guardrails with conditional logic,
 * parallel execution, fallbacks, and pipeline patterns.
 */

/**
 * A composable guardrail unit that can be used in pipelines
 */
type ComposableGuardrail<T extends 'input' | 'output'> = T extends 'input' ? InputGuardrail : OutputGuardrail;
/**
 * Condition function for conditional guardrails
 */
type GuardrailCondition<T extends 'input' | 'output'> = T extends 'input' ? (context: NormalizedGuardrailContext) => boolean | Promise<boolean> : (context: OutputGuardrailContext) => boolean | Promise<boolean>;
/**
 * Pipeline execution result
 */
interface PipelineResult<M = Record<string, unknown>> {
    /** Final result from the pipeline */
    result: GuardrailResult<M>;
    /** All intermediate results */
    intermediateResults: GuardrailResult<M>[];
    /** Whether the pipeline short-circuited */
    shortCircuited: boolean;
    /** Execution time in ms */
    executionTimeMs: number;
}
/**
 * Creates a conditional guardrail that only executes when a condition is met.
 *
 * @example
 * ```typescript
 * // Only run expensive check on long prompts
 * const conditionalGuardrail = when(
 *   (ctx) => ctx.prompt.length > 1000,
 *   promptInjectionDetector()
 * );
 * ```
 */
declare function when<M extends Record<string, unknown> = Record<string, unknown>>(condition: (context: NormalizedGuardrailContext) => boolean | Promise<boolean>, guardrail: InputGuardrail<M>): InputGuardrail<M>;
declare function when<M extends Record<string, unknown> = Record<string, unknown>>(condition: (context: OutputGuardrailContext) => boolean | Promise<boolean>, guardrail: OutputGuardrail<M>): OutputGuardrail<M>;
/**
 * Creates a guardrail that runs only when the previous guardrail passed.
 *
 * @example
 * ```typescript
 * // Run toxicity check only if length check passes
 * const chainedGuardrail = after(lengthCheck, toxicityFilter);
 * ```
 */
declare function after<M extends Record<string, unknown> = Record<string, unknown>>(prerequisite: InputGuardrail<M>, guardrail: InputGuardrail<M>): InputGuardrail<M>;
declare function after<M extends Record<string, unknown> = Record<string, unknown>>(prerequisite: OutputGuardrail<M>, guardrail: OutputGuardrail<M>): OutputGuardrail<M>;
/**
 * Creates a guardrail with a fallback that runs if the primary fails or times out.
 *
 * @example
 * ```typescript
 * // Use AI moderation, fall back to keyword filter if it fails
 * const robustGuardrail = withFallback(
 *   aiContentModerator(),
 *   keywordFilter(),
 *   { timeoutMs: 5000 }
 * );
 * ```
 */
declare function withFallback<M extends Record<string, unknown> = Record<string, unknown>>(primary: InputGuardrail<M>, fallback: InputGuardrail<M>, options?: {
    timeoutMs?: number;
}): InputGuardrail<M>;
declare function withFallback<M extends Record<string, unknown> = Record<string, unknown>>(primary: OutputGuardrail<M>, fallback: OutputGuardrail<M>, options?: {
    timeoutMs?: number;
}): OutputGuardrail<M>;
/**
 * Creates a guardrail that runs multiple guardrails in parallel and combines results.
 *
 * @example
 * ```typescript
 * // Run PII and toxicity checks in parallel
 * const parallelGuardrail = parallel([
 *   piiDetector(),
 *   toxicityFilter(),
 * ], { mode: 'any' });  // Block if any fails
 * ```
 */
declare function parallel<M extends Record<string, unknown> = Record<string, unknown>>(guardrails: InputGuardrail<M>[], options?: {
    /** 'any' blocks if any guardrail triggers, 'all' blocks only if all trigger */
    mode?: 'any' | 'all';
    /** Timeout for all guardrails */
    timeoutMs?: number;
}): InputGuardrail<M>;
declare function parallel<M extends Record<string, unknown> = Record<string, unknown>>(guardrails: OutputGuardrail<M>[], options?: {
    mode?: 'any' | 'all';
    timeoutMs?: number;
}): OutputGuardrail<M>;
/**
 * Creates a guardrail pipeline that executes guardrails in sequence.
 *
 * @example
 * ```typescript
 * const pipeline = createPipeline([
 *   lengthLimit({ max: 10000 }),
 *   when((ctx) => ctx.prompt.length > 100, promptInjectionDetector()),
 *   parallel([piiDetector(), toxicityFilter()]),
 * ], {
 *   shortCircuitOnBlock: true,
 *   name: 'input-validation-pipeline'
 * });
 * ```
 */
declare function createPipeline<M extends Record<string, unknown> = Record<string, unknown>>(guardrails: InputGuardrail<M>[], options?: {
    name?: string;
    shortCircuitOnBlock?: boolean;
}): InputGuardrail<M>;
declare function createPipeline<M extends Record<string, unknown> = Record<string, unknown>>(guardrails: OutputGuardrail<M>[], options?: {
    name?: string;
    shortCircuitOnBlock?: boolean;
}): OutputGuardrail<M>;
/**
 * Creates a guardrail that negates the result of another guardrail.
 * Useful for allowlist patterns.
 *
 * @example
 * ```typescript
 * // Only allow if NOT on blocklist
 * const allowlist = not(blockedUsersGuardrail());
 * ```
 */
declare function not<M extends Record<string, unknown> = Record<string, unknown>>(guardrail: InputGuardrail<M>): InputGuardrail<M>;
declare function not<M extends Record<string, unknown> = Record<string, unknown>>(guardrail: OutputGuardrail<M>): OutputGuardrail<M>;
/**
 * Creates a guardrail that retries on failure with configurable backoff.
 *
 * @example
 * ```typescript
 * const resilientGuardrail = withRetry(aiModerator(), {
 *   maxRetries: 3,
 *   backoffMs: (attempt) => attempt * 1000,
 * });
 * ```
 */
declare function withRetry<M extends Record<string, unknown> = Record<string, unknown>>(guardrail: InputGuardrail<M>, options: {
    maxRetries?: number;
    backoffMs?: number | ((attempt: number) => number);
    retryOn?: (result: GuardrailResult<M>) => boolean;
}): InputGuardrail<M>;
declare function withRetry<M extends Record<string, unknown> = Record<string, unknown>>(guardrail: OutputGuardrail<M>, options: {
    maxRetries?: number;
    backoffMs?: number | ((attempt: number) => number);
    retryOn?: (result: GuardrailResult<M>) => boolean;
}): OutputGuardrail<M>;
/**
 * Creates an input guardrail pipeline
 */
declare const inputPipeline: <M extends Record<string, unknown> = Record<string, unknown>>(guardrails: InputGuardrail<M>[], options?: {
    name?: string;
    shortCircuitOnBlock?: boolean;
}) => InputGuardrail<M>;
/**
 * Creates an output guardrail pipeline
 */
declare const outputPipeline: <M extends Record<string, unknown> = Record<string, unknown>>(guardrails: OutputGuardrail<M>[], options?: {
    name?: string;
    shortCircuitOnBlock?: boolean;
}) => OutputGuardrail<M>;

/**
 * Gradual Enforcement Mode
 *
 * Provides soft-fail patterns, warning escalation, and grace periods
 * for introducing new guardrails without immediately blocking users.
 */

/**
 * Enforcement mode for gradual rollout
 */
type EnforcementMode = 'warn' | 'escalate' | 'enforce';
/**
 * Escalation configuration for gradual enforcement
 */
interface EscalationConfig {
    /** Number of violations to warn about before blocking */
    warnCount: number;
    /** Number of violations after which to start blocking */
    blockAfter: number;
    /** Time window in ms to reset the counter */
    windowMs: number;
    /** Optional: only escalate for specific severities */
    severities?: Array<'low' | 'medium' | 'high' | 'critical'>;
}
/**
 * Grace period configuration
 */
interface GracePeriodConfig {
    /** Don't block until this date */
    until: Date;
    /** Log level for grace period violations */
    logLevel?: 'debug' | 'info' | 'warn';
    /** Custom message to include in logs */
    message?: string;
}
/**
 * Options for gradual enforcement wrapper
 */
interface GradualEnforcementOptions {
    /** Enforcement mode */
    mode: EnforcementMode;
    /** Escalation configuration (for 'escalate' mode) */
    escalation?: EscalationConfig;
    /** Grace period configuration */
    gracePeriod?: GracePeriodConfig;
    /** Callback when a violation is detected but not blocked */
    onWarn?: (result: GuardrailResult, stats: ViolationStats) => void;
    /** Callback when enforcement transitions from warn to block */
    onEscalation?: (stats: ViolationStats) => void;
    /** Storage key for persisting violation counts (optional) */
    storageKey?: string;
}
/**
 * Violation statistics
 */
interface ViolationStats {
    /** Total violations in current window */
    count: number;
    /** Window start time */
    windowStart: Date;
    /** Whether currently in blocking mode */
    isBlocking: boolean;
    /** Violations by severity */
    bySeverity: Record<string, number>;
}
/**
 * Wraps a guardrail with gradual enforcement behavior.
 *
 * This enables soft-fail patterns for rolling out new guardrails:
 * - 'warn': Log violations but never block
 * - 'escalate': Warn for first N violations, then start blocking
 * - 'enforce': Always block (with optional grace period)
 *
 * @example Warn-only mode (for testing new rules)
 * ```typescript
 * const warnOnlyGuardrail = withGradualEnforcement(toxicityFilter(), {
 *   mode: 'warn',
 *   onWarn: (result, stats) => {
 *     analytics.track('guardrail_would_block', {
 *       guardrail: 'toxicity',
 *       message: result.message,
 *       count: stats.count
 *     });
 *   }
 * });
 * ```
 *
 * @example Escalation mode (gradual tightening)
 * ```typescript
 * const escalatingGuardrail = withGradualEnforcement(toxicityFilter(), {
 *   mode: 'escalate',
 *   escalation: {
 *     warnCount: 3,      // Warn for first 3 violations
 *     blockAfter: 5,     // Block after 5 violations
 *     windowMs: 60000,   // Reset counter every minute
 *   },
 *   onEscalation: (stats) => {
 *     notifyModerator(`User escalated to blocking after ${stats.count} violations`);
 *   }
 * });
 * ```
 *
 * @example Grace period (for new rules)
 * ```typescript
 * const newRuleGuardrail = withGradualEnforcement(newComplianceRule(), {
 *   mode: 'enforce',
 *   gracePeriod: {
 *     until: new Date('2024-02-01'),
 *     logLevel: 'warn',
 *     message: 'New compliance rule will be enforced starting Feb 1'
 *   }
 * });
 * ```
 */
declare function withGradualEnforcement<M extends Record<string, unknown> = Record<string, unknown>>(guardrail: InputGuardrail<M>, options: GradualEnforcementOptions): InputGuardrail<M>;
declare function withGradualEnforcement<M extends Record<string, unknown> = Record<string, unknown>>(guardrail: OutputGuardrail<M>, options: GradualEnforcementOptions): OutputGuardrail<M>;
/**
 * Clears violation history for a guardrail or all guardrails.
 * Useful for testing or manual resets.
 */
declare function clearViolationHistory(guardrailName?: string): void;
/**
 * Gets current violation stats for a guardrail
 */
declare function getViolationStats(guardrailName: string, windowMs?: number): ViolationStats | null;
/**
 * Creates a warn-only enforcement (for A/B testing new rules)
 */
declare function warnOnly<M extends Record<string, unknown> = Record<string, unknown>>(guardrail: InputGuardrail<M> | OutputGuardrail<M>, options?: {
    onWarn?: (result: GuardrailResult, stats: ViolationStats) => void;
}): InputGuardrail<M> | OutputGuardrail<M>;
/**
 * Creates a lenient escalation (3 warnings, block after 5)
 */
declare function lenientEscalation<M extends Record<string, unknown> = Record<string, unknown>>(guardrail: InputGuardrail<M> | OutputGuardrail<M>, options?: {
    onWarn?: (result: GuardrailResult, stats: ViolationStats) => void;
    onEscalation?: (stats: ViolationStats) => void;
}): InputGuardrail<M> | OutputGuardrail<M>;
/**
 * Creates a strict escalation (1 warning, block after 2)
 */
declare function strictEscalation<M extends Record<string, unknown> = Record<string, unknown>>(guardrail: InputGuardrail<M> | OutputGuardrail<M>, options?: {
    onWarn?: (result: GuardrailResult, stats: ViolationStats) => void;
    onEscalation?: (stats: ViolationStats) => void;
}): InputGuardrail<M> | OutputGuardrail<M>;
/**
 * Creates enforcement with a grace period
 */
declare function withGracePeriod<M extends Record<string, unknown> = Record<string, unknown>>(guardrail: InputGuardrail<M> | OutputGuardrail<M>, until: Date, options?: {
    logLevel?: 'debug' | 'info' | 'warn';
    message?: string;
}): InputGuardrail<M> | OutputGuardrail<M>;

/**
 * Observability & Metrics
 *
 * Provides metrics collection, violation analytics, and performance tracking
 * for guardrail execution.
 */

/**
 * Metrics for a single guardrail
 */
interface GuardrailMetrics {
    /** Guardrail name */
    guardrailName: string;
    /** Total number of executions */
    executionCount: number;
    /** Number of times the guardrail blocked */
    blockCount: number;
    /** Number of execution errors */
    errorCount: number;
    /** Average execution time in ms */
    avgExecutionMs: number;
    /** 95th percentile execution time */
    p95ExecutionMs: number;
    /** 99th percentile execution time */
    p99ExecutionMs: number;
    /** Min execution time */
    minExecutionMs: number;
    /** Max execution time */
    maxExecutionMs: number;
    /** Block rate (0-1) */
    blockRate: number;
    /** Last violation timestamp */
    lastViolation?: Date;
    /** Violations by severity */
    violationsBySeverity: Record<string, number>;
    /** First seen timestamp */
    firstSeen: Date;
    /** Last seen timestamp */
    lastSeen: Date;
}
/**
 * Aggregated metrics across all guardrails
 */
interface AggregatedMetrics {
    /** Total executions across all guardrails */
    totalExecutions: number;
    /** Total blocks across all guardrails */
    totalBlocks: number;
    /** Total errors across all guardrails */
    totalErrors: number;
    /** Overall block rate */
    overallBlockRate: number;
    /** Average execution time across all guardrails */
    avgExecutionMs: number;
    /** Per-guardrail metrics */
    byGuardrail: Map<string, GuardrailMetrics>;
    /** Metrics collection period start */
    periodStart: Date;
    /** Metrics collection period end */
    periodEnd: Date;
}
/**
 * Options for the metrics collector
 */
interface MetricsCollectorOptions {
    /** Callback when metrics are flushed */
    onFlush?: (metrics: AggregatedMetrics) => void | Promise<void>;
    /** Flush interval in ms (default: 60000 - 1 minute) */
    flushIntervalMs?: number;
    /** Sampling rate 0-1 (default: 1.0 - collect all) */
    sampling?: number;
    /** Maximum number of execution times to track per guardrail (for percentiles) */
    maxExecutionTimeSamples?: number;
    /** Whether to auto-start flushing */
    autoStart?: boolean;
    /** Custom logger */
    logger?: {
        info: (msg: string, ...args: any[]) => void;
        warn: (msg: string, ...args: any[]) => void;
        error: (msg: string, ...args: any[]) => void;
    };
}
/**
 * Creates a metrics collector for guardrail execution tracking.
 *
 * @example Basic usage
 * ```typescript
 * const collector = createMetricsCollector({
 *   onFlush: (metrics) => {
 *     console.log('Metrics:', {
 *       totalExecutions: metrics.totalExecutions,
 *       blockRate: metrics.overallBlockRate,
 *     });
 *   },
 *   flushIntervalMs: 60000, // Every minute
 * });
 *
 * // Wrap guardrails with metrics
 * const trackedGuardrail = collector.track(myGuardrail);
 *
 * // Use in config
 * const model = withGuardrails({ model: baseModel,
 *   inputGuardrails: [trackedGuardrail],
 * });
 *
 * // Get current metrics
 * const currentMetrics = collector.getMetrics();
 *
 * // Clean up
 * collector.stop();
 * ```
 *
 * @example With sampling and external metrics system
 * ```typescript
 * const collector = createMetricsCollector({
 *   sampling: 0.1, // Sample 10% of requests
 *   onFlush: async (metrics) => {
 *     await datadog.gauge('guardrails.block_rate', metrics.overallBlockRate);
 *     await datadog.histogram('guardrails.execution_time', metrics.avgExecutionMs);
 *
 *     for (const [name, guardrailMetrics] of metrics.byGuardrail) {
 *       await datadog.gauge(`guardrails.${name}.block_rate`, guardrailMetrics.blockRate);
 *     }
 *   },
 * });
 * ```
 */
declare function createMetricsCollector(options?: MetricsCollectorOptions): {
    /** Track a single guardrail */
    track: {
        <M extends Record<string, unknown>>(guardrail: InputGuardrail<M>): InputGuardrail<M>;
        <M extends Record<string, unknown>>(guardrail: OutputGuardrail<M>): OutputGuardrail<M>;
    };
    /** Track multiple guardrails */
    trackAll: {
        <M extends Record<string, unknown>>(guardrails: InputGuardrail<M>[]): InputGuardrail<M>[];
        <M extends Record<string, unknown>>(guardrails: OutputGuardrail<M>[]): OutputGuardrail<M>[];
    };
    /** Get current metrics without flushing */
    getMetrics: () => AggregatedMetrics;
    /** Manually flush metrics */
    flush: () => Promise<AggregatedMetrics>;
    /** Reset all metrics */
    reset: () => void;
    /** Start automatic flushing */
    start: () => void;
    /** Stop automatic flushing */
    stop: () => void;
    /** Record an execution manually */
    recordExecution: (guardrailName: string, result: GuardrailResult, executionTimeMs: number) => void;
};
/**
 * Logs an execution summary in a structured format
 */
declare function logExecutionSummary(summary: GuardrailExecutionSummary, options?: {
    logger?: {
        info: (msg: string, ...args: any[]) => void;
        warn: (msg: string, ...args: any[]) => void;
    };
    level?: 'info' | 'warn';
    includeDetails?: boolean;
}): void;
/**
 * Guardrail health status
 */
interface GuardrailHealthStatus {
    /** Overall health status */
    status: 'healthy' | 'degraded' | 'unhealthy';
    /** Per-guardrail health */
    guardrails: Array<{
        name: string;
        status: 'healthy' | 'degraded' | 'unhealthy';
        reason?: string;
    }>;
    /** Timestamp of health check */
    timestamp: Date;
}
/**
 * Creates a health check function for guardrails
 */
declare function createHealthCheck(guardrails: Array<InputGuardrail | OutputGuardrail>, options?: {
    /** Error rate threshold for unhealthy (default: 0.1 = 10%) */
    errorRateThreshold?: number;
    /** Block rate threshold for degraded (default: 0.5 = 50%) */
    blockRateThreshold?: number;
    /** Metrics collector to get stats from */
    metricsCollector?: ReturnType<typeof createMetricsCollector>;
}): () => GuardrailHealthStatus;

/**
 * Debug/Tracing Mode
 *
 * Provides detailed execution traces for debugging guardrail behavior,
 * including timing, decisions, patterns matched, and full context.
 */

/**
 * Trace entry for a single guardrail execution
 */
interface GuardrailTraceEntry {
    /** Guardrail name */
    guardrailName: string;
    /** Guardrail version if available */
    guardrailVersion?: string;
    /** Start time relative to trace start (ms) */
    startMs: number;
    /** End time relative to trace start (ms) */
    endMs: number;
    /** Duration in ms */
    durationMs: number;
    /** Result of execution */
    result: 'pass' | 'block' | 'error';
    /** Whether the guardrail triggered */
    triggered: boolean;
    /** Severity if triggered */
    severity?: 'low' | 'medium' | 'high' | 'critical';
    /** Message from the guardrail */
    message?: string;
    /** Patterns or keywords that matched (if any) */
    matchedPatterns?: string[];
    /** Confidence score if available */
    confidence?: number;
    /** Full decision details */
    decision: GuardrailResult;
    /** Additional debug info */
    debugInfo?: Record<string, unknown>;
}
/**
 * Complete execution trace
 */
interface ExecutionTrace {
    /** Unique trace ID */
    traceId: string;
    /** Timestamp when trace started */
    timestamp: Date;
    /** Type of guardrails executed */
    type: 'input' | 'output';
    /** All guardrail execution entries */
    guardrails: GuardrailTraceEntry[];
    /** Total execution time in ms */
    totalMs: number;
    /** Final decision */
    finalDecision: 'allowed' | 'blocked';
    /** Guardrails that blocked (if any) */
    blockedBy?: string[];
    /** Input context (optionally included) */
    inputContext?: {
        promptLength: number;
        messageCount: number;
        hasSystemMessage: boolean;
        promptPreview?: string;
    };
    /** Output context (optionally included for output guardrails) */
    outputContext?: {
        responseLength: number;
        responsePreview?: string;
    };
    /** Metadata */
    metadata?: Record<string, unknown>;
}
/**
 * Debug configuration options
 */
interface DebugOptions {
    /** Enable debug mode */
    enabled: boolean;
    /** Include verbose details (full input/output previews) */
    verbose?: boolean;
    /** Maximum length for text previews */
    previewLength?: number;
    /** Callback for each trace */
    onTrace?: (trace: ExecutionTrace) => void | Promise<void>;
    /** Custom trace ID generator */
    generateTraceId?: () => string;
    /** Include full input context in trace */
    includeInputContext?: boolean;
    /** Include full output context in trace */
    includeOutputContext?: boolean;
    /** Custom logger */
    logger?: {
        debug: (msg: string, ...args: any[]) => void;
        info: (msg: string, ...args: any[]) => void;
        warn: (msg: string, ...args: any[]) => void;
    };
}
/**
 * Creates a debug wrapper for guardrails that captures detailed execution traces.
 *
 * @example Basic debugging
 * ```typescript
 * const debug = createDebugWrapper({
 *   enabled: true,
 *   verbose: true,
 *   onTrace: (trace) => console.log(JSON.stringify(trace, null, 2))
 * });
 *
 * const debuggedGuardrails = myGuardrails.map(g => debug.wrap(g));
 *
 * const model = withGuardrails({ model: baseModel,
 *   inputGuardrails: debuggedGuardrails,
 * });
 * ```
 *
 * @example With external logging
 * ```typescript
 * const debug = createDebugWrapper({
 *   enabled: process.env.DEBUG_GUARDRAILS === 'true',
 *   onTrace: async (trace) => {
 *     if (trace.finalDecision === 'blocked') {
 *       await logger.warn('Request blocked by guardrails', {
 *         traceId: trace.traceId,
 *         blockedBy: trace.blockedBy,
 *         duration: trace.totalMs
 *       });
 *     }
 *   }
 * });
 * ```
 */
declare function createDebugWrapper(options: DebugOptions): {
    /** Wrap a single guardrail with debugging */
    wrap: {
        <M extends Record<string, unknown>>(guardrail: InputGuardrail<M>): InputGuardrail<M>;
        <M extends Record<string, unknown>>(guardrail: OutputGuardrail<M>): OutputGuardrail<M>;
    };
    /** Wrap multiple guardrails */
    wrapAll: {
        <M extends Record<string, unknown>>(guardrails: InputGuardrail<M>[]): InputGuardrail<M>[];
        <M extends Record<string, unknown>>(guardrails: OutputGuardrail<M>[]): OutputGuardrail<M>[];
    };
    /** Start a new trace (call before executing guardrails) */
    startTrace: (type: "input" | "output") => string;
    /** Complete and emit the current trace */
    completeTrace: (inputContext?: NormalizedGuardrailContext, outputContext?: {
        text?: string;
    }) => Promise<ExecutionTrace | null>;
    /** Get the current trace ID */
    getCurrentTraceId: () => string | undefined;
    /** Check if debugging is enabled */
    isEnabled: () => boolean;
};
/**
 * Formats a trace for console output
 */
declare function formatTraceForConsole(trace: ExecutionTrace): string;
/**
 * Formats a trace as JSON (for structured logging)
 */
declare function formatTraceAsJSON(trace: ExecutionTrace): string;
/**
 * Creates a compact trace summary for logging
 */
declare function formatTraceSummary(trace: ExecutionTrace): string;
/**
 * Creates a simple console logger for debugging
 */
declare function createConsoleDebugger(options?: {
    verbose?: boolean;
    format?: 'console' | 'json' | 'summary';
}): DebugOptions;
/**
 * Environment-based debug mode (checks GUARDRAILS_DEBUG env var)
 */
declare function envDebugMode(): DebugOptions;

/**
 * Options for guardrail stream transform
 */
interface GuardrailStreamTransformOptions {
    /**
     * Stop stream when violations of this severity or higher are detected
     * @default 'critical'
     */
    stopOnSeverity?: 'low' | 'medium' | 'high' | 'critical';
    /**
     * Custom condition to determine when to stop the stream
     * If provided, overrides stopOnSeverity
     */
    stopCondition?: (summary: GuardrailExecutionSummary) => boolean;
    /**
     * Callback invoked when a violation is detected
     */
    onViolation?: (summary: GuardrailExecutionSummary) => void;
    /**
     * How often to check guardrails (in number of chunks)
     * @default 1 (check every chunk)
     * Set higher to reduce overhead for high-throughput streams
     */
    checkInterval?: number;
    /**
     * Timeout for guardrail execution in milliseconds
     * @default 5000
     */
    timeout?: number;
    /**
     * Whether to execute guardrails in parallel
     * @default true
     */
    parallel?: boolean;
}
/**
 * Creates a stream transform that checks guardrails and stops the stream on violations
 *
 * This integrates with AI SDK's `experimental_transform` to provide efficient,
 * source-level stream stopping when guardrails detect violations. Unlike middleware
 * approaches that only stop consumption, this stops the provider stream itself.
 *
 * @param guardrails - Output guardrails to check during streaming
 * @param options - Configuration options
 * @returns Transform function compatible with streamText experimental_transform
 *
 * @example
 * ```typescript
 * import { streamText } from 'ai';
 * import { createGuardrailStreamTransform } from 'ai-sdk-guardrails';
 * import { toxicityFilter, piiDetector } from 'ai-sdk-guardrails/guardrails/output';
 *
 * const result = streamText({
 *   model,
 *   prompt: 'Tell me a story',
 *   experimental_transform: createGuardrailStreamTransform(
 *     [toxicityFilter(), piiDetector()],
 *     {
 *       stopOnSeverity: 'high',
 *       onViolation: (summary) => {
 *         console.log('Violation detected:', summary);
 *       },
 *     }
 *   ),
 * });
 * ```
 *
 * @example Multiple transforms can be composed
 * ```typescript
 * experimental_transform: [
 *   createGuardrailStreamTransform([toxicityFilter()]),
 *   customTransform(),
 * ]
 * ```
 */
declare function createGuardrailStreamTransform<TOOLS extends Record<string, unknown>>(guardrails: OutputGuardrail[], options?: GuardrailStreamTransformOptions): (transformOptions: {
    tools: TOOLS;
    stopStream: () => void;
}) => TransformStream<{
    type: string;
    id?: string;
    text?: string;
    delta?: string;
}, {
    type: string;
    id?: string;
    text?: string;
    delta?: string;
    error?: unknown;
}>;
/**
 * Creates a simple transform that accumulates text and checks on flush
 * More efficient but less responsive than chunk-by-chunk checking
 *
 * @param guardrails - Output guardrails to check
 * @param options - Configuration options
 * @returns Transform function
 *
 * @example
 * ```typescript
 * experimental_transform: createGuardrailStreamTransformBuffered(
 *   [minLengthRequirement(100)],
 *   { onViolation: (summary) => console.log(summary) }
 * )
 * ```
 */
declare function createGuardrailStreamTransformBuffered<TOOLS extends Record<string, unknown>>(guardrails: OutputGuardrail[], options?: Omit<GuardrailStreamTransformOptions, 'checkInterval'>): (transformOptions: {
    tools: TOOLS;
    stopStream: () => void;
}) => TransformStream<{
    type: string;
    id?: string;
    text?: string;
    delta?: string;
}, {
    type: string;
    id?: string;
    text?: string;
    delta?: string;
    error?: unknown;
}>;

/**
 * Simple token estimation function
 * Uses a rough heuristic: ~4 characters per token for English text
 *
 * For production use, consider using a proper tokenizer like:
 * - @anthropic-ai/tokenizer for Claude models
 * - gpt-tokenizer for OpenAI models
 * - Or pass a custom tokenizer function
 */
declare function estimateTokenCount(text: string): number;
/**
 * Options for token budget transform
 */
interface TokenBudgetOptions {
    /**
     * Maximum tokens allowed before stopping the stream
     */
    maxTokens: number;
    /**
     * Custom tokenizer function
     * If not provided, uses estimateTokenCount
     */
    tokenizer?: (text: string) => number;
    /**
     * Callback invoked when token budget is exceeded
     */
    onBudgetExceeded?: (info: {
        consumed: number;
        budget: number;
    }) => void;
}
/**
 * Creates a transform that stops streaming after a token budget is exceeded
 *
 * Useful for controlling costs and preventing runaway generation, especially
 * when combined with guardrails that might detect issues late in generation.
 *
 * @param options - Token budget configuration
 * @returns Transform function compatible with streamText experimental_transform
 *
 * @example
 * ```typescript
 * import { streamText } from 'ai';
 * import { createTokenBudgetTransform } from 'ai-sdk-guardrails';
 *
 * const result = streamText({
 *   model,
 *   prompt: 'Write a long story',
 *   experimental_transform: createTokenBudgetTransform({
 *     maxTokens: 1000,
 *     onBudgetExceeded: ({ consumed, budget }) => {
 *       console.log(`Stopped at ${consumed} tokens (budget: ${budget})`);
 *     },
 *   }),
 * });
 * ```
 */
declare function createTokenBudgetTransform<TOOLS extends Record<string, unknown>>(options: TokenBudgetOptions): (transformOptions: {
    tools: TOOLS;
    stopStream: () => void;
}) => TransformStream<{
    type: string;
    id?: string;
    text?: string;
    delta?: string;
}, {
    type: string;
    id?: string;
    text?: string;
    delta?: string;
    error?: unknown;
}>;
/**
 * Options for token-aware guardrail transform
 */
interface TokenAwareGuardrailOptions {
    /**
     * Check guardrails every N tokens (reduces overhead)
     * @default 10
     */
    checkEveryTokens?: number;
    /**
     * Maximum tokens before stopping (optional)
     * If not set, stream continues until completion
     */
    maxTokens?: number;
    /**
     * Stop on violations of this severity or higher
     * @default 'critical'
     */
    stopOnSeverity?: 'low' | 'medium' | 'high' | 'critical';
    /**
     * Custom stop condition
     */
    stopCondition?: (summary: GuardrailExecutionSummary) => boolean;
    /**
     * Callback invoked when violation detected
     */
    onViolation?: (summary: GuardrailExecutionSummary) => void;
    /**
     * Custom tokenizer function
     */
    tokenizer?: (text: string) => number;
    /**
     * Timeout for guardrail execution
     * @default 5000
     */
    timeout?: number;
    /**
     * Execute guardrails in parallel
     * @default true
     */
    parallel?: boolean;
}
/**
 * Creates a transform that checks guardrails at token intervals
 *
 * More efficient than checking every chunk - reduces guardrail overhead
 * while maintaining safety. Particularly useful for high-throughput streams.
 *
 * @param guardrails - Output guardrails to check
 * @param options - Configuration options
 * @returns Transform function compatible with streamText experimental_transform
 *
 * @example
 * ```typescript
 * import { streamText } from 'ai';
 * import { createTokenAwareGuardrailTransform } from 'ai-sdk-guardrails';
 * import { toxicityFilter } from 'ai-sdk-guardrails/guardrails/output';
 *
 * const result = streamText({
 *   model,
 *   prompt: 'Write a story',
 *   experimental_transform: createTokenAwareGuardrailTransform(
 *     [toxicityFilter()],
 *     {
 *       checkEveryTokens: 50, // Check every 50 tokens
 *       maxTokens: 1000,      // Stop at 1000 tokens
 *       stopOnSeverity: 'high',
 *     }
 *   ),
 * });
 * ```
 *
 * @example Combine with token budget for cost control
 * ```typescript
 * experimental_transform: [
 *   createTokenBudgetTransform({ maxTokens: 2000 }),
 *   createTokenAwareGuardrailTransform([piiDetector()], {
 *     checkEveryTokens: 100,
 *   }),
 * ]
 * ```
 */
declare function createTokenAwareGuardrailTransform<TOOLS extends Record<string, unknown>>(guardrails: OutputGuardrail[], options?: TokenAwareGuardrailOptions): (transformOptions: {
    tools: TOOLS;
    stopStream: () => void;
}) => TransformStream<{
    type: string;
    id?: string;
    text?: string;
    delta?: string;
}, {
    type: string;
    id?: string;
    text?: string;
    delta?: string;
    error?: unknown;
}>;

/**
 * Stream Transform Integration
 *
 * Creates stream transforms for use with AI SDK's experimental_transform.
 * Enables real-time content filtering, redaction, and modification during streaming.
 */

/**
 * Stream part type (simplified for transform context)
 */
interface StreamPart {
    type: string;
    id?: string;
    text?: string;
    delta?: string;
    textDelta?: string;
    [key: string]: unknown;
}
/**
 * Violation handler result
 */
interface ViolationHandlerResult {
    /** Action to take */
    action: 'pass' | 'drop' | 'replace' | 'stop';
    /** Replacement text if action is 'replace' */
    replacement?: string;
    /** Reason for the action */
    reason?: string;
}
/**
 * Violation handler function type
 */
type ViolationHandler = (chunk: StreamPart, violation: GuardrailResult, context: StreamTransformContext) => ViolationHandlerResult | Promise<ViolationHandlerResult>;
/**
 * Context provided to stream transforms
 */
interface StreamTransformContext {
    /** Accumulated text so far */
    accumulatedText: string;
    /** Number of chunks processed */
    chunkCount: number;
    /** Violations encountered so far */
    violations: GuardrailResult[];
    /** Request context */
    requestContext?: RequestContext;
}
/**
 * Options for creating guardrail stream transforms
 */
interface GuardrailTransformOptions {
    /**
     * What to do when a violation is detected:
     * - 'stop': Stop the stream immediately
     * - 'drop': Drop the violating chunk silently
     * - 'redact': Replace matched patterns with redaction text
     * - 'replace': Replace entire chunk with replacement text
     * - function: Custom handler for full control
     */
    onViolation?: 'stop' | 'drop' | 'redact' | 'replace' | ViolationHandler;
    /** Patterns to redact when onViolation is 'redact' */
    redactPatterns?: Array<RegExp | string>;
    /** Text to use for redaction (default: '[REDACTED]') */
    redactionText?: string;
    /** Text to use for replacement when onViolation is 'replace' */
    replacementText?: string;
    /** Minimum characters to accumulate before checking guardrails */
    minCharsBeforeCheck?: number;
    /** Check frequency (every N chunks) to reduce overhead */
    checkEveryNChunks?: number;
    /** Request context to pass to guardrails */
    requestContext?: RequestContext;
    /** Callback when stream is stopped due to violation */
    onStreamStopped?: (violations: GuardrailResult[], accumulatedText: string) => void;
    /** Callback for each violation (even if not stopping) */
    onViolationDetected?: (violation: GuardrailResult, chunk: StreamPart) => void;
}
/**
 * AI SDK StreamTextTransform type
 */
type StreamTextTransform<TOOLS extends ToolSet> = (options: {
    tools: TOOLS;
    stopStream: () => void;
}) => TransformStream<StreamPart, StreamPart>;
/**
 * Creates a guardrail-based stream transform for use with AI SDK's experimental_transform.
 *
 * This enables real-time content filtering, redaction, and modification during streaming
 * without buffering the entire response.
 *
 * @example Basic usage - stop on violation
 * ```typescript
 * const result = streamText({
 *   model,
 *   prompt,
 *   experimental_transform: createGuardrailTransform(
 *     [toxicityFilter(), piiDetector()],
 *     { onViolation: 'stop' }
 *   )
 * });
 * ```
 *
 * @example Redaction - replace sensitive patterns
 * ```typescript
 * const result = streamText({
 *   model,
 *   prompt,
 *   experimental_transform: createGuardrailTransform(
 *     [piiDetector()],
 *     {
 *       onViolation: 'redact',
 *       redactPatterns: [
 *         /\b\d{3}-\d{2}-\d{4}\b/g,  // SSN
 *         /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g,  // Email
 *       ],
 *       redactionText: '[REDACTED]'
 *     }
 *   )
 * });
 * ```
 *
 * @example Custom handler
 * ```typescript
 * const result = streamText({
 *   model,
 *   prompt,
 *   experimental_transform: createGuardrailTransform(
 *     [toxicityFilter()],
 *     {
 *       onViolation: (chunk, violation, ctx) => {
 *         if (violation.severity === 'critical') {
 *           return { action: 'stop', reason: 'Critical violation' };
 *         }
 *         if (ctx.violations.length > 3) {
 *           return { action: 'stop', reason: 'Too many violations' };
 *         }
 *         return { action: 'pass' };  // Allow through with warning
 *       }
 *     }
 *   )
 * });
 * ```
 */
declare function createGuardrailTransform<TOOLS extends ToolSet = ToolSet>(guardrails: OutputGuardrail[], options?: GuardrailTransformOptions): StreamTextTransform<TOOLS>;
/**
 * Common PII patterns for redaction
 */
declare const PII_PATTERNS: {
    /** US Social Security Number */
    SSN: RegExp;
    /** Email addresses */
    EMAIL: RegExp;
    /** Phone numbers (various formats) */
    PHONE: RegExp;
    /** Credit card numbers */
    CREDIT_CARD: RegExp;
    /** IP addresses */
    IP_ADDRESS: RegExp;
    /** API keys (generic pattern) */
    API_KEY: RegExp;
};
/**
 * Creates a PII redaction transform
 */
declare function createPIIRedactionTransform<TOOLS extends ToolSet = ToolSet>(options?: {
    patterns?: Array<RegExp | string>;
    redactionText?: string;
    requestContext?: RequestContext;
}): StreamTextTransform<TOOLS>;
/**
 * Creates a simple content filter transform that stops on specific keywords
 */
declare function createContentFilterTransform<TOOLS extends ToolSet = ToolSet>(options: {
    blockedKeywords: string[];
    caseSensitive?: boolean;
    onBlocked?: (keyword: string, text: string) => void;
    requestContext?: RequestContext;
}): StreamTextTransform<TOOLS>;

/**
 * Options for guardrail-aware prepareStep
 */
interface GuardrailPrepareStepOptions {
    /**
     * How many recent steps to consider for violations
     * @default 2
     */
    lookback?: number;
    /**
     * Temperature to set when violations detected
     * @default 0.3
     */
    temperatureReduction?: number;
    /**
     * Whether to stop execution on critical violations
     * @default false
     */
    stopOnCritical?: boolean;
    /**
     * Custom system message to add on violations
     */
    warningMessage?: string;
}
/**
 * Creates a prepareStep function that adjusts generation based on guardrail violations
 *
 * This enables adaptive behavior in multi-step agent execution:
 * - Reduces temperature after violations (more conservative)
 * - Adds warning messages to system prompt
 * - Can stop execution entirely on critical violations
 *
 * @param violations - Array of guardrail violations from agent execution
 * @param options - Configuration options
 * @returns prepareStep function for use with streamText/Agent
 *
 * @example
 * ```typescript
 * import { streamText } from 'ai';
 * import { createGuardrailPrepareStep } from 'ai-sdk-guardrails';
 *
 * const violations: GuardrailViolation[] = [];
 *
 * const result = streamText({
 *   model,
 *   prompt: 'Multi-step task',
 *   tools: { search: searchTool },
 *   prepareStep: createGuardrailPrepareStep(violations, {
 *     temperatureReduction: 0.2,
 *     stopOnCritical: true,
 *   }),
 * });
 * ```
 *
 * @example With agent guardrails
 * ```typescript
 * const violations: GuardrailViolation[] = [];
 *
 * const agent = new ToolLoopAgent({
 *   ...agentGuardrails({ model,
 *     outputGuardrails: [toxicityFilter()],
 *     onOutputBlocked: (summary) => {
 *       violations.push({ step: violations.length, summary });
 *     },
 *   }),
 *   tools: { search: searchTool },
 *   prepareStep: createGuardrailPrepareStep(violations),
 * });
 * ```
 */
declare function createGuardrailPrepareStep(violations: GuardrailViolation[], options?: GuardrailPrepareStepOptions): (args: {
    steps: Array<{
        content: unknown;
    }>;
    stepNumber: number;
    messages: unknown[];
    model: LanguageModelV4;
}) => {
    temperature?: number;
    system?: string;
    stopWhen?: () => boolean;
} | undefined;
/**
 * Options for adaptive prepareStep
 */
interface AdaptivePrepareStepOptions {
    /**
     * Violation history to track
     */
    violations: GuardrailViolation[];
    /**
     * Custom strategy function to apply on violations
     * If not provided, uses default temperature reduction
     */
    strategy?: (violations: GuardrailViolation[]) => {
        temperature?: number;
        topP?: number;
        topK?: number;
        system?: string;
        stopWhen?: () => boolean;
    };
    /**
     * Callback when violations are detected
     */
    onViolationDetected?: (violations: GuardrailViolation[]) => void;
    /**
     * Number of violations before escalating to stop
     * @default 5
     */
    escalateAfter?: number;
    /**
     * Lookback window for recent violations
     * @default 3
     */
    lookback?: number;
}
/**
 * Creates an adaptive prepareStep that escalates restrictions based on violation patterns
 *
 * More sophisticated than createGuardrailPrepareStep - tracks violation trends
 * and escalates restrictions progressively.
 *
 * @param options - Configuration options
 * @returns prepareStep function for use with streamText/Agent
 *
 * @example
 * ```typescript
 * import { Experimental_Agent as Agent } from 'ai';
 * import { createAdaptivePrepareStep } from 'ai-sdk-guardrails';
 *
 * const violations: GuardrailViolation[] = [];
 *
 * const agent = new Agent({
 *   model,
 *   tools: { search: searchTool },
 *   prepareStep: createAdaptivePrepareStep({
 *     violations,
 *     escalateAfter: 3,
 *     strategy: (violations) => {
 *       const count = violations.length;
 *       return {
 *         temperature: Math.max(0.1, 0.7 - count * 0.1),
 *         system: `You have ${count} violations. Be extremely careful.`,
 *       };
 *     },
 *   }),
 * });
 * ```
 */
declare function createAdaptivePrepareStep(options: AdaptivePrepareStepOptions): (args: {
    steps: Array<{
        content: unknown;
    }>;
    stepNumber: number;
    messages: unknown[];
    model: LanguageModelV4;
}) => {
    temperature?: number;
    topP?: number;
    topK?: number;
    system?: string;
    stopWhen?: () => boolean;
} | undefined;

/**
 * Options for tool abortion controller
 */
interface ToolAbortionControllerOptions {
    /**
     * Minimum severity to trigger abortion
     * @default 'critical'
     */
    minSeverity?: 'low' | 'medium' | 'high' | 'critical';
    /**
     * Timeout for guardrail execution
     * @default 3000
     */
    timeout?: number;
}
/**
 * Controller for aborting tool execution based on guardrail violations
 */
declare class ToolAbortionController {
    private controller;
    private minSeverity;
    private timeout;
    constructor(options?: ToolAbortionControllerOptions);
    get signal(): AbortSignal;
    /**
     * Check guardrails and abort if violations detected
     */
    checkAndAbort(guardrails: OutputGuardrail[], context: OutputGuardrailContext): Promise<boolean>;
    /**
     * Manually abort
     */
    abort(reason?: string): void;
}
/**
 * Creates a tool abortion controller
 *
 * @param options - Configuration options
 * @returns Tool abortion controller
 *
 * @example
 * ```typescript
 * const controller = createToolAbortionController({
 *   minSeverity: 'high',
 * });
 *
 * // Use in tool wrapper
 * const wrappedTool = wrapToolWithAbortion(tool, guardrails, {
 *   abortSignal: controller.signal,
 * });
 * ```
 */
declare function createToolAbortionController(options?: ToolAbortionControllerOptions): ToolAbortionController;
/**
 * Options for wrapping tools with abortion capability
 */
interface WrapToolWithAbortionOptions {
    /**
     * Check guardrails before executing tool
     * @default false
     */
    checkBefore?: boolean;
    /**
     * Monitor execution with periodic guardrail checks
     * @default false
     */
    monitorDuring?: boolean;
    /**
     * Interval for monitoring checks in milliseconds
     * @default 100
     */
    monitorInterval?: number;
    /**
     * Check input deltas in streaming tool inputs
     * @default false
     */
    checkInputDelta?: boolean;
    /**
     * Minimum severity to abort on
     * @default 'critical'
     */
    abortOnSeverity?: 'low' | 'medium' | 'high' | 'critical';
    /**
     * Timeout for guardrail execution
     * @default 3000
     */
    timeout?: number;
}
/**
 * Wraps a tool with guardrail-based abortion capability
 *
 * Enables stopping dangerous tool execution before or during execution based
 * on guardrail violations. Particularly useful for tools that:
 * - Make external API calls
 * - Modify system state
 * - Access sensitive data
 * - Execute long-running operations
 *
 * @param tool - The tool to wrap
 * @param guardrails - Output guardrails to check
 * @param options - Configuration options
 * @returns Wrapped tool with abortion capability
 *
 * @example
 * ```typescript
 * import { wrapToolWithAbortion } from 'ai-sdk-guardrails';
 *
 * const dangerousApiTool = {
 *   description: 'Call external API',
 *   parameters: z.object({ endpoint: z.string() }),
 *   execute: async ({ endpoint }) => {
 *     // ... API call
 *   },
 * };
 *
 * const safeTool = wrapToolWithAbortion(
 *   dangerousApiTool,
 *   [
 *     {
 *       name: 'url-validator',
 *       execute: async ({ result }) => {
 *         // Check if endpoint is safe
 *         const input = JSON.parse(result.text);
 *         if (input.endpoint.includes('internal')) {
 *           return {
 *             tripwireTriggered: true,
 *             message: 'Internal endpoint not allowed',
 *             severity: 'critical',
 *           };
 *         }
 *         return { tripwireTriggered: false, message: '' };
 *       },
 *     },
 *   ],
 *   {
 *     checkBefore: true,
 *     abortOnSeverity: 'critical',
 *   }
 * );
 * ```
 *
 * @example Monitor long-running tool execution
 * ```typescript
 * const longRunningTool = wrapToolWithAbortion(
 *   dataProcessingTool,
 *   [timeoutGuardrail],
 *   {
 *     monitorDuring: true,
 *     monitorInterval: 1000, // Check every second
 *   }
 * );
 * ```
 */
declare function wrapToolWithAbortion<T extends Record<string, unknown>>(tool: T & {
    execute: (input: unknown, options?: {
        abortSignal?: AbortSignal;
    }) => Promise<unknown>;
    onInputDelta?: (options: {
        inputTextDelta: string;
        toolCallId: string;
        messages: unknown[];
        abortSignal?: AbortSignal;
    }) => Promise<void> | void;
}, guardrails: OutputGuardrail[], options?: WrapToolWithAbortionOptions): T & {
    execute: (input: unknown, options?: {
        abortSignal?: AbortSignal;
    }) => Promise<unknown>;
    onInputDelta?: (options: {
        inputTextDelta: string;
        toolCallId: string;
        messages: unknown[];
        abortSignal?: AbortSignal;
    }) => Promise<void> | void;
};

/**
 * Custom error class for guardrail-triggered aborts
 * Extends Error to provide violation context when aborting
 */
declare class GuardrailViolationAbort extends Error {
    readonly summary: GuardrailExecutionSummary;
    constructor(summary: GuardrailExecutionSummary);
}
/**
 * Creates an AbortController that can be triggered by guardrail violations
 *
 * This provides a clean, standard way to cancel AI SDK operations when
 * guardrails detect violations. The AbortSignal can be passed to any
 * AI SDK function that supports cancellation.
 *
 * @example
 * ```typescript
 * const { signal, abortOnViolation } = createGuardrailAbortController();
 *
 * const guardedModel = withGuardrails({ model,
 *   outputGuardrails: [piiDetector()],
 *   onOutputBlocked: abortOnViolation('critical'),
 * });
 *
 * const result = await streamText({
 *   model: guardedModel,
 *   prompt: '...',
 *   abortSignal: signal, // Cancels on critical violations
 * });
 * ```
 *
 * @returns Object with AbortController signal and helper functions
 */
declare function createGuardrailAbortController(): {
    /**
     * The AbortSignal that can be passed to AI SDK functions
     */
    signal: AbortSignal;
    /**
     * Creates a callback that aborts on violations of specified severity or higher
     *
     * @param minSeverity - Minimum severity to trigger abort (default: 'critical')
     * @returns Callback function for use with onInputBlocked/onOutputBlocked
     *
     * @example
     * ```typescript
     * const { signal, abortOnViolation } = createGuardrailAbortController();
     *
     * withGuardrails({ model,
     *   outputGuardrails: [toxicityFilter()],
     *   onOutputBlocked: abortOnViolation('high'), // Abort on high or critical
     * });
     * ```
     */
    abortOnViolation: (minSeverity?: "low" | "medium" | "high" | "critical") => (summary: GuardrailExecutionSummary) => void;
    /**
     * Creates a callback that aborts based on custom condition
     *
     * @param condition - Function that returns true to trigger abort
     * @returns Callback function for use with onInputBlocked/onOutputBlocked
     *
     * @example
     * ```typescript
     * const { signal, abortOnCondition } = createGuardrailAbortController();
     *
     * withGuardrails({ model,
     *   outputGuardrails: [qualityCheck()],
     *   onOutputBlocked: abortOnCondition(
     *     (summary) => summary.blockedResults.length > 2
     *   ),
     * });
     * ```
     */
    abortOnCondition: (condition: (summary: GuardrailExecutionSummary) => boolean) => (summary: GuardrailExecutionSummary) => void;
    /**
     * Manually abort with custom reason
     *
     * @param reason - Custom abort reason
     *
     * @example
     * ```typescript
     * const { abort } = createGuardrailAbortController();
     * abort('User requested cancellation');
     * ```
     */
    abort: (reason?: string) => void;
};

/**
 * Options for finish reason mapping
 */
interface FinishReasonOptions {
    /**
     * Custom finish reason for blocked content
     * @default 'content_filter'
     */
    blocked?: 'content_filter' | 'stop' | 'length' | 'tool_calls' | 'error' | 'other' | 'unknown';
    /**
     * Custom finish reason for successful completion
     * @default 'stop'
     */
    success?: 'content_filter' | 'stop' | 'length' | 'tool_calls' | 'error' | 'other' | 'unknown';
}
/**
 * Determines the appropriate finish reason based on guardrail execution
 *
 * Maps guardrail violations to standard AI SDK finish reasons:
 * - blocked content → 'content_filter' (standard for safety filtering)
 * - successful completion → 'stop'
 *
 * @param summary - Guardrail execution summary
 * @param options - Custom finish reason mapping
 * @returns AI SDK finish reason
 *
 * @example
 * ```typescript
 * const finishReason = getGuardrailFinishReason(summary);
 * // Returns 'content_filter' if blocked, 'stop' otherwise
 * ```
 */
declare function getGuardrailFinishReason(summary: GuardrailExecutionSummary, options?: FinishReasonOptions): 'content_filter' | 'stop' | 'length' | 'tool_calls' | 'error' | 'other' | 'unknown';
/**
 * Options for provider metadata creation
 */
interface ProviderMetadataOptions {
    /**
     * Include full metadata from guardrail results
     * @default false
     */
    includeMetadata?: boolean;
    /**
     * Include execution statistics
     * @default true
     */
    includeStats?: boolean;
}
/**
 * Creates provider metadata object with guardrail information
 *
 * Provider metadata is a standard AI SDK feature that allows attaching
 * custom information to generation results. This function formats
 * guardrail execution details in a structured way for observability.
 *
 * @param summary - Guardrail execution summary
 * @param options - Metadata configuration
 * @returns Provider metadata object
 *
 * @example
 * ```typescript
 * const metadata = createGuardrailProviderMetadata(summary);
 * // Returns:
 * // {
 * //   guardrails: {
 * //     blocked: true,
 * //     violations: [...],
 * //     executionTime: 50,
 * //     guardrailsExecuted: 3,
 * //     stats: { passed: 2, blocked: 1, failed: 0 }
 * //   }
 * // }
 * ```
 */
declare function createGuardrailProviderMetadata(summary: GuardrailExecutionSummary, options?: ProviderMetadataOptions): {
    guardrails: {
        blocked: boolean;
        violations: Array<{
            message?: string;
            severity?: 'low' | 'medium' | 'high' | 'critical';
            guardrailName?: string;
            metadata?: unknown;
        }>;
        executionTime: number;
        guardrailsExecuted: number;
        stats?: {
            passed: number;
            blocked: number;
            failed: number;
        };
    };
};
/**
 * Enhances a generation result with guardrail finish reason and metadata
 *
 * This function modifies the AI SDK result to include:
 * - Appropriate finish reason (content_filter for blocks)
 * - Provider metadata with guardrail execution details
 *
 * @param summary - Guardrail execution summary
 * @param result - Original AI SDK result
 * @param options - Configuration options
 * @returns Enhanced result with guardrail information
 *
 * @example
 * ```typescript
 * const enhanced = createFinishReasonEnhancement(summary, result);
 * console.log(enhanced.finishReason); // 'content_filter'
 * console.log(enhanced.providerMetadata.guardrails.blocked); // true
 * ```
 *
 * @example Use in middleware
 * ```typescript
 * export function outputGuardrailsMiddleware(config) {
 *   return {
 *     wrapGenerate: async ({ doGenerate }) => {
 *       const result = await doGenerate();
 *       const summary = await executeOutputGuardrails(...);
 *
 *       if (summary.blockedResults.length > 0) {
 *         return createFinishReasonEnhancement(summary, result);
 *       }
 *
 *       return result;
 *     },
 *   };
 * }
 * ```
 */
declare function createFinishReasonEnhancement<T extends {
    finishReason: 'content_filter' | 'stop' | 'length' | 'tool_calls' | 'error' | 'other' | 'unknown';
    providerMetadata?: Record<string, unknown>;
}>(summary: GuardrailExecutionSummary, result: T, options?: FinishReasonOptions & ProviderMetadataOptions): T;

/**
 * Default retry helpers for guardrails.
 *
 * This module provides the default `buildRetryParams` implementation that is used
 * when users don't provide their own. It works by calling `getRetryInstruction()`
 * on blocked guardrails and appending the instructions as user messages.
 */

/**
 * Options for creating the default buildRetryParams function.
 */
interface DefaultBuildRetryParamsOptions<M = Record<string, unknown>> {
    /** The output guardrails to search for getRetryInstruction */
    outputGuardrails: OutputGuardrail<M>[];
    /** Strategy for handling multiple blocked guardrails */
    multipleBlockedStrategy?: 'first' | 'all' | 'highest-severity';
    /** Current retry attempt (1-based) */
    attempt: number;
    /** Maximum retry attempts configured */
    maxRetries: number;
}
/**
 * Creates the default buildRetryParams function.
 *
 * This function is used when users don't provide their own `buildRetryParams`.
 * It works by:
 * 1. Finding which guardrail(s) blocked based on the configured strategy
 * 2. Calling their `getRetryInstruction()` method if available
 * 3. Appending the instruction as a user message to the prompt
 * 4. Optionally adjusting temperature based on guardrail suggestions
 *
 * @example
 * ```typescript
 * const buildRetryParams = createDefaultBuildRetryParams({
 *   outputGuardrails: [expectedToolUse({ tools: 'calculator' })],
 *   multipleBlockedStrategy: 'highest-severity',
 *   attempt: 1,
 *   maxRetries: 2,
 * });
 *
 * const nextParams = buildRetryParams({
 *   summary: executionSummary,
 *   originalParams: params,
 *   lastParams: params,
 *   lastResult: result,
 * });
 * ```
 */
declare function createDefaultBuildRetryParams<M = Record<string, unknown>>(options: DefaultBuildRetryParamsOptions<M>): (args: {
    summary: GuardrailExecutionSummary<M>;
    originalParams: LanguageModelV4CallOptions;
    lastParams: LanguageModelV4CallOptions;
    lastResult: unknown;
}) => LanguageModelV4CallOptions;
/**
 * Resolves the effective retry configuration by merging guardrail-level
 * and withGuardrails-level configs. withGuardrails-level takes precedence.
 */
declare function resolveRetryConfig<M>(globalRetry: {
    maxRetries?: number;
    backoffMs?: number | ((attempt: number) => number);
} | undefined, blockedGuardrails: OutputGuardrail<M>[]): {
    maxRetries: number;
    backoffMs: number | ((attempt: number) => number);
};

/**
 * Backoff Helpers for Retry Utilities
 *
 * Composable backoff functions to reduce boilerplate in retry configurations.
 * These are pure functions that return backoff calculators.
 */
interface BackoffOptions {
    /** Base delay in milliseconds */
    base?: number;
    /** Maximum delay in milliseconds */
    max?: number;
    /** Jitter factor (0-1) to add randomness */
    jitter?: number;
    /** Multiplier for exponential backoff */
    multiplier?: number;
}
/**
 * Exponential backoff with optional jitter and maximum cap
 *
 * @example
 * ```typescript
 * import { retry, exponentialBackoff } from 'ai-sdk-guardrails';
 *
 * await retry({
 *   // ... other options
 *   backoffMs: exponentialBackoff({ base: 1000, max: 10000, jitter: 0.1 })
 * });
 * ```
 */
declare function exponentialBackoff(options?: BackoffOptions): (attempt: number) => number;
/**
 * Linear backoff with optional jitter
 *
 * @example
 * ```typescript
 * import { retry, linearBackoff } from 'ai-sdk-guardrails';
 *
 * await retry({
 *   // ... other options
 *   backoffMs: linearBackoff({ base: 1000, max: 5000 })
 * });
 * ```
 */
declare function linearBackoff(options?: BackoffOptions): (attempt: number) => number;
/**
 * Fixed delay with optional jitter
 *
 * @example
 * ```typescript
 * import { retry, fixedBackoff } from 'ai-sdk-guardrails';
 *
 * await retry({
 *   // ... other options
 *   backoffMs: fixedBackoff({ base: 2000, jitter: 0.2 })
 * });
 * ```
 */
declare function fixedBackoff(options?: BackoffOptions): (attempt: number) => number;
/**
 * No delay backoff (immediate retry)
 *
 * @example
 * ```typescript
 * import { retry, noBackoff } from 'ai-sdk-guardrails';
 *
 * await retry({
 *   // ... other options
 *   backoffMs: noBackoff()
 * });
 * ```
 */
declare function noBackoff(): (attempt: number) => number;
/**
 * Composite backoff that switches strategies based on attempt number
 *
 * @example
 * ```typescript
 * import { retry, compositeBackoff, fixedBackoff, exponentialBackoff } from 'ai-sdk-guardrails';
 *
 * await retry({
 *   // ... other options
 *   backoffMs: compositeBackoff([
 *     { maxAttempts: 2, backoff: fixedBackoff({ base: 1000 }) },
 *     { maxAttempts: Infinity, backoff: exponentialBackoff({ base: 2000, max: 10000 }) }
 *   ])
 * });
 * ```
 */
declare function compositeBackoff(strategies: Array<{
    maxAttempts: number;
    backoff: (attempt: number) => number;
}>): (attempt: number) => number;
/**
 * Jittered exponential backoff (common pattern)
 * Equivalent to exponentialBackoff with 10% jitter
 */
declare const jitteredExponentialBackoff: (options?: Omit<BackoffOptions, "jitter">) => (attempt: number) => number;
/**
 * Common presets for quick setup
 */
declare const presets: {
    /** Fast retry: 500ms, 1s, 2s, 4s (max 4s) */
    readonly fast: () => (attempt: number) => number;
    /** Standard retry: 1s, 2s, 4s, 8s, 16s (max 16s) */
    readonly standard: () => (attempt: number) => number;
    /** Slow retry: 2s, 4s, 8s, 16s, 32s (max 32s) */
    readonly slow: () => (attempt: number) => number;
    /** Network resilient: jittered exponential with longer delays */
    readonly networkResilient: () => (attempt: number) => number;
    /** Aggressive: very fast with short max delay for quick failures */
    readonly aggressive: () => (attempt: number) => number;
};

export { type AdaptivePrepareStepOptions, type AggregatedMetrics, type BackoffOptions, type ComposableGuardrail, type DebugOptions, type DefaultBuildRetryParamsOptions, type EnforcementMode, type EscalationConfig, type ExecutionTrace, type FinishReasonOptions, type GracePeriodConfig, type GradualEnforcementOptions, type GuardrailCondition, type GuardrailHealthStatus, type GuardrailMetrics, type GuardrailMiddlewareConfig, type GuardrailPrepareStepOptions, type GuardrailStreamTransformOptions, type GuardrailTraceEntry, type GuardrailTransformOptions, GuardrailViolationAbort, type MetricsCollectorOptions, PII_PATTERNS, type PipelineResult, type ProviderMetadataOptions, type StreamTextTransform, type StreamTransformContext, type TokenAwareGuardrailOptions, type TokenBudgetOptions, type ToolAbortionControllerOptions, type ViolationHandler, type ViolationHandlerResult, type ViolationStats, type WrapToolWithAbortionOptions, after, presets as backoffPresets, clearViolationHistory, compositeBackoff, createAdaptivePrepareStep, createConsoleDebugger, createContentFilterTransform, createDebugWrapper, createDefaultBuildRetryParams, createFinishReasonEnhancement, createGuardrailAbortController, createGuardrailPrepareStep, createGuardrailProviderMetadata, createGuardrailStreamTransform, createGuardrailStreamTransformBuffered, createGuardrailTransform, createHealthCheck, createMetricsCollector, createPIIRedactionTransform, createPipeline, createTokenAwareGuardrailTransform, createTokenBudgetTransform, createToolAbortionController, enhancedPromptInjectionDetector, envDebugMode, estimateTokenCount, exponentialBackoff, fixedBackoff, formatTraceAsJSON, formatTraceForConsole, formatTraceSummary, getGuardrailFinishReason, getViolationStats, guardrailMiddleware, incrementalPromptInjectionDetector, inputGuardrailsMiddleware, inputPipeline, intentBasedInjectionDetector, jitteredExponentialBackoff, lenientEscalation, linearBackoff, logExecutionSummary, noBackoff, noopGuardrailMiddleware, not, outputGuardrailsMiddleware, outputPipeline, parallel, resolveRetryConfig, strictEscalation, toolCallInjectionDetector, warnOnly, when, withFallback, withGracePeriod, withGradualEnforcement, withRetry, wrapToolWithAbortion };