/**
 * Utility module types - extracted from utils module files
 */
import { ErrorCategory, ErrorSeverity } from "../constants/enums.js";
import type { UnifiedGenerationOptions } from "./generate.js";
import type { ExecutionContext } from "./tools.js";
/**
 * Represents the available logging severity levels.
 * - debug: Detailed information for debugging purposes
 * - info: General information about system operation
 * - warn: Potential issues that don't prevent operation
 * - error: Critical issues that may cause failures
 */
export type LogLevel = "debug" | "info" | "warn" | "error";
export type TimeoutConfig = {
    operation: string;
    timeout?: number | string;
    gracefulShutdown?: boolean;
    retryOnTimeout?: boolean;
    maxRetries?: number;
    abortSignal?: AbortSignal;
};
export type TimeoutResult<T> = {
    success: boolean;
    data?: T;
    error?: Error;
    timedOut: boolean;
    executionTime: number;
    retriesUsed: number;
};
/**
 * Enhanced validation result with format checking
 */
export type APIValidationResult = {
    isValid: boolean;
    apiKey: string;
    formatValid?: boolean;
    errorType?: "missing" | "format" | "config";
    error?: string;
};
/**
 * Parsed proxy configuration
 */
export type ParsedProxyConfig = {
    protocol: string;
    hostname: string;
    port: number;
    auth?: {
        username: string;
        password: string;
    };
    cleanUrl: string;
};
/**
 * Represents a single log entry in the logging system.
 * Each entry contains metadata about the log event along with the actual message.
 */
export type LogEntry = {
    /** The severity level of the log entry */
    level: LogLevel;
    /** The text message to be logged */
    message: string;
    /** When the log entry was created */
    timestamp: Date;
    /** Optional additional data associated with the log entry (objects, arrays, etc.) */
    data?: unknown;
};
/**
 * Minimal emitter shape the logger forwards `"log-event"` payloads to.
 *
 * Structurally satisfied by `node:events`' `EventEmitter` and by NeuroLink's
 * own typed emitter, so a sink can be either.
 */
export type LogEventEmitter = {
    emit: (event: string, ...args: unknown[]) => boolean;
};
/**
 * Logger interface matching the logger object shape
 * Used for SDK tool contexts and other components that need a logger
 *
 * Deliberately a subset of the real logger: the per-instance routing methods
 * (`runInInstanceScope`, `addScopedEventEmitter`, …) are internal plumbing
 * between the SDK entry points and the logger, and this type is a structural
 * contract a caller can satisfy — `SDKToolContext.logger`. Adding required
 * members here would break anyone constructing that context themselves.
 */
export type Logger = {
    debug: (...args: unknown[]) => void;
    info: (...args: unknown[]) => void;
    warn: (...args: unknown[]) => void;
    error: (...args: unknown[]) => void;
    always: (...args: unknown[]) => void;
    table: (data: unknown) => void;
    setLogLevel: (level: LogLevel) => void;
    getLogs: (level?: LogLevel) => LogEntry[];
    clearLogs: () => void;
    setEventEmitter: (emitter: LogEventEmitter) => void;
    clearEventEmitter: () => void;
};
export type StructuredError = {
    code: string;
    message: string;
    category: ErrorCategory;
    severity: ErrorSeverity;
    retriable: boolean;
    context?: Record<string, unknown>;
    originalError?: Error;
    timestamp: Date;
    toolName?: string;
    serverId?: string;
};
/**
 * Enhancement types for different optimization strategies
 */
export type EnhancementType = "streaming-optimization" | "mcp-integration" | "legacy-migration" | "context-conversion" | "domain-configuration" | "batch-parallel-enhancement" | "batch-hybrid-enhancement" | "batch-dependency-enhancement";
/**
 * Enhancement options for modifying GenerateOptions
 */
export type EnhancementOptions = {
    enhancementType: EnhancementType;
    streamingOptions?: {
        enabled?: boolean;
        chunkSize?: number;
        bufferSize?: number;
        enableProgress?: boolean;
        preferStreaming?: boolean;
    };
    mcpOptions?: {
        enableToolRegistry?: boolean;
        contextAware?: boolean;
        executionContext?: ExecutionContext;
    };
    legacyMigration?: {
        legacyContext?: Record<string, unknown>;
        domainType?: string;
        preserveFields?: boolean;
    };
    domainConfiguration?: {
        domainType: string;
        keyTerms?: string[];
        failurePatterns?: string[];
        successPatterns?: string[];
        evaluationCriteria?: Record<string, unknown>;
    };
    performance?: {
        enableAnalytics?: boolean;
        enableEvaluation?: boolean;
        timeout?: number;
    };
};
/**
 * Enhancement result with metadata
 */
export type EnhancementResult = {
    options: UnifiedGenerationOptions;
    metadata: {
        enhancementApplied: boolean;
        enhancementType: EnhancementType;
        processingTime: number;
        configurationUsed: Record<string, unknown>;
        warnings: string[];
        recommendations: string[];
    };
};
/**
 * Plugin-based conflict detection system
 * Extensible and configurable enhancement conflict resolution
 */
export type ConflictDetectionPlugin = {
    /** Plugin name for identification */
    name: string;
    /** Plugin version for compatibility checks */
    version: string;
    /** Check if two enhancement types conflict */
    detectConflict(enhancementA: EnhancementType, enhancementB: EnhancementType, optionsA?: EnhancementOptions, optionsB?: EnhancementOptions): boolean;
    /** Get conflict severity (low, medium, high) */
    getConflictSeverity?(enhancementA: EnhancementType, enhancementB: EnhancementType): "low" | "medium" | "high";
    /** Suggest resolution strategies */
    suggestResolution?(enhancementA: EnhancementType, enhancementB: EnhancementType): string[];
};
export type RetryOptions = {
    maxAttempts?: number;
    initialDelay?: number;
    maxDelay?: number;
    backoffMultiplier?: number;
    retryCondition?: (error: unknown) => boolean;
    onRetry?: (attempt: number, error: unknown) => void;
};
export type PromptRedactionOptions = {
    /** Maximum length of redacted prompt */
    maxLength?: number;
    /** Whether to show word count */
    showWordCount?: boolean;
    /** Mask character to use for redaction */
    maskChar?: string;
};
/**
 * Validation results for environment variables
 */
export type EnvVarValidationResult = {
    isValid: boolean;
    missingVars: string[];
    invalidVars: string[];
    warnings: string[];
};
/**
 * Cached image entry structure for image cache
 */
export type CachedImage = {
    /** The image data as a base64 data URI */
    dataUri: string;
    /** Content type of the image (e.g., "image/jpeg") */
    contentType: string;
    /** Size of the image in bytes */
    size: number;
    /** SHA-256 hash of the image content for deduplication */
    contentHash: string;
    /** Timestamp when the entry was created */
    createdAt: number;
    /** Timestamp of last access */
    lastAccessedAt: number;
    /** Number of times this entry was accessed */
    accessCount: number;
};
/**
 * Configuration options for the image cache
 */
export type ImageCacheConfig = {
    /** Maximum number of entries in the cache (default: 100) */
    maxSize?: number;
    /** Time-to-live in milliseconds (default: 30 minutes) */
    ttlMs?: number;
    /** Maximum size per image in bytes (default: 10MB) */
    maxImageSize?: number;
};
/**
 * Cache statistics for monitoring
 */
export type ImageCacheStats = {
    /** Number of cache hits */
    hits: number;
    /** Number of cache misses */
    misses: number;
    /** Number of entries evicted due to size limits */
    evictions: number;
    /** Number of entries expired due to TTL */
    expirations: number;
    /** Total number of requests */
    totalRequests: number;
    /** Current number of entries in cache */
    size: number;
    /** Total size of cached images in bytes */
    totalBytes: number;
    /** Cache hit rate as percentage */
    hitRate: number;
};
/**
 * Pending request held by TokenBucketRateLimiter's queue.
 * Named RateLimiterPendingRequest to disambiguate from the MCP
 * PendingRequest in mcp.ts (Rule 9).
 */
export type RateLimiterPendingRequest = {
    resolve: () => void;
    reject: (error: Error) => void;
    timestamp: number;
    timeoutTimer?: ReturnType<typeof setTimeout>;
};
/**
 * Shape of a completed tool result as returned by the AI SDK in
 * `onStepFinish`. Both `output` (AI SDK v4) and `result` (older shape)
 * are supported so the helper works across SDK versions.
 */
export type StepToolResult = {
    toolName: string;
    output?: unknown;
    result?: unknown;
    error?: string;
};
/**
 * Result of coercing arbitrary model text into canonical, valid JSON.
 * `content` is a JSON.stringify of the recovered object; `structuredData` is
 * the parsed object itself.
 */
export type JsonCoercionResult = {
    content: string;
    structuredData: unknown;
    /** True when jsonrepair altered the model text to make it parse. */
    repaired: boolean;
    /**
     * True when the recovered object came from a truncated (unclosed) span —
     * the response likely hit the output-token cap and data may be incomplete.
     */
    truncated: boolean;
};
/**
 * Decision returned by `recoverScalarRoot`. Each caller applies it to its own
 * result shape and logger prefix, preserving its existing warning behaviour:
 *
 *   - `empty`     — the text is a JSON-encoded empty string (an EMPTY
 *                   completion, not a recovered scalar). Callers normalize to a
 *                   true empty.
 *   - `accepted`  — a scalar root the caller's schema accepts; safe to publish
 *                   as `structuredData`.
 *   - `rejected`  — a scalar root the caller's schema rejects (e.g. a raw
 *                   string under an object schema — the shape a truncated
 *                   response degrades to). Do NOT publish it.
 *   - `nullish`   — the text is the JSON literals `null`/`undefined`; there is
 *                   no structured value to publish.
 *   - `not-json`  — the text is not JSON at all.
 */
export type ScalarRecoveryDecision = {
    kind: "empty";
} | {
    kind: "accepted";
    value: unknown;
} | {
    kind: "rejected";
    value: unknown;
} | {
    kind: "nullish";
} | {
    kind: "not-json";
};
/**
 * An element in the parsed HTML tree used for Markdown conversion.
 */
export type MarkdownHtmlElementNode = {
    kind: "element";
    /** Lower-cased tag name. */
    tag: string;
    /** Lower-cased attribute names mapped to their decoded values. */
    attrs: Record<string, string>;
    children: MarkdownHtmlNode[];
};
/**
 * A node in the parsed HTML tree used for Markdown conversion: either a text
 * run or an element.
 */
export type MarkdownHtmlNode = {
    kind: "text";
    value: string;
} | MarkdownHtmlElementNode;
