import { b as RateLimitConfig, d as ToolExecutionErrorDetails, V as ValidationFailure, A as AuthenticationConfig, e as ToolErrorCode, R as RetryConfig, L as LoadBalancingConfig, C as CollaborationConfig, f as LearningConfig, M as MemoryConfig, a as TimeoutConfig } from './common.d-iR60eBef.js'; export { h as AuthProviderConfig, j as CollaborationMode, i as LearningMode, P as PerformanceMetrics, g as RateLimitRule, T as TokenCount, c as ToolCall } from './common.d-iR60eBef.js'; import { J as JsonValue, f as ToolId, A as AgentId, a as MessageId, R as Result, g as ModelId, U as UsageStats, B as Brand } from './streaming.d-Cj-pZLSI.js'; export { V as AllUndefined, aO as Annotation, I as AsyncFn, w as Awaited, aT as BaseStreamEvent, be as BatchStreamConfig, b3 as CacheConfig, aW as ContentEvent, C as ConversationId, aQ as Cost, aR as CostBreakdown, D as DeepPartial, k as DeepReadonly, l as DeepRequired, aq as DiscriminatedUnion, as as DiscriminatorValues, ak as Email, ar as ExtractVariant, au as Failure, X as FlatPick, H as Fn, aP as FunctionCall, aX as FunctionCallEvent, O as FunctionParams, Q as FunctionReturn, am as ISODateString, aM as ImageContent, z as JsonArray, y as JsonObject, x as JsonPrimitive, E as Jsonable, K as KeysOfType, L as LastOf, v as Maybe, M as Message, aK as MessageContent, aJ as MessageContentType, aN as MessageMetadata, aI as MessageRole, bd as MultimodalStreamConfig, p as Mutable, aj as Nominal, ap as NonNegativeInt, N as NonNullable, aA as None, u as Nullable, G as NumberLiteral, aB as Option, P as PartialBy, r as PathValue, q as Paths, ao as PositiveInt, m as RequireAtLeastOne, n as RequireExactlyOne, o as RequiredBy, b8 as SSEConfig, b7 as SSEMessage, S as SessionId, az as Some, b1 as StreamAbortEvent, c as StreamCallbacks, b as StreamConfig, b6 as StreamController, aZ as StreamDoneEvent, a_ as StreamErrorEvent, b2 as StreamEvent, aS as StreamEventType, bb as StreamFunction, a$ as StreamMetadataEvent, bf as StreamMiddleware, e as StreamOptions, h as StreamResult, aU as StreamStartEvent, b5 as StreamState, bc as StreamTool, b4 as StreamTransport, b0 as StreamUsageEvent, bg as StreamWithMiddleware, Y as StrictOmit, Z as StrictPick, F as StringLiteral, at as Success, aL as TextContent, T as Timestamp, aV as TokenEvent, aY as ToolCallEvent, an as UUID, s as UnionToIntersection, t as UnionToTuple, al as Url, d as Usage, i as UserId, ba as WebSocketConfig, b9 as WebSocketMessage, W as Writable, ad as assert, ae as assertDefined, ai as assertNever, ag as assertNumber, ah as assertObject, af as assertString, j as createBrandedId, aw as failure, aG as fromNullable, a8 as hasProperty, a4 as isArray, a2 as isBoolean, _ as isDefined, a7 as isError, ay as isFailure, a5 as isFunction, ab as isJsonValue, aa as isNonEmptyArray, a9 as isNonEmptyString, aF as isNone, $ as isNullish, a1 as isNumber, a3 as isObject, a6 as isPromise, aE as isSome, a0 as isString, ax as isSuccess, aD as none, ac as notNullish, aC as some, av as success, aH as toNullable } from './streaming.d-Cj-pZLSI.js'; export { z as Agent, f as AgentAction, g as AgentActionType, x as AgentCallbacks, c as AgentCapability, d as AgentConfig, A as AgentContext, w as AgentExecutionOptions, y as AgentExecutionResult, B as AgentFactory, m as AgentMessage, n as AgentMessageType, o as AgentProtocol, a as AgentRole, e as AgentState, b as AgentStatus, p as AgentTeam, l as Artifact, D as Decision, r as DecisionOption, s as DecisionStrategy, E as Experience, G as Goal, I as Improvement, v as MemoryEntry, M as MemoryType, O as OrchestrationPlan, q as OrchestrationStep, t as Plan, u as PlanStep, P as PlanningStrategy, R as Reflection, i as Task, k as TaskMetrics, T as TaskPriority, j as TaskResult, h as TaskStatus } from './agents.d-Dhf5taAS.js'; export { A as AIStream } from './AIStream-BwgeGI-N.js'; export { MODEL_PRICING, ModelName, calculateCost, countMessageTokens, countMessagesTokens, countTokens, estimateRequestTokens } from './streaming/index.js'; export { A as AppendOptions, B as BaseStoreConfig, a as Conversation, b as ConversationMetadata, C as ConversationStore, L as LoadOptions, M as MemoryStoreConfig, R as RedisStoreConfig, d as SaveOptions, c as StoreBackend, S as StoreConfig, e as StoreStats, Z as ZeroDBStoreConfig } from './ConversationStore-C33N9v7n.js'; export { MemoryStore, RedisStore, ZeroDBStore, createStore, isMemoryStore, isRedisStore, isZeroDBStore } from './store/index.js'; export { ContextConfig, ContextManager, ContextMessage, MODEL_ENCODING_MAP, MODEL_TOKEN_LIMITS, MessageImportance, ModelType, TokenCounter, TokenUsage, TruncationStrategy, TruncationStrategyType, tokenCounter } from './context/index.js'; export { CompressionLevel, ConversationSummarizer, ExtractedSentence, IncrementalSummaryOptions, SummarizationResult, SummarizationStats, SummarizeOptions, Summary, SummaryCacheEntry, SummaryConfig, SummaryProvider, SummaryStrategy, calculateDiversity, createExtractiveSummary, extractKeyPoints, extractKeySentences, extractKeywords } from './summarization/index.js'; export { C as CreateSessionOptions, E as ExpirationStrategy, I as InMemorySessionStore, L as ListSessionsOptions, j as RefreshSessionOptions, a as Session, c as SessionConfig, b as SessionData, f as SessionEvent, k as SessionEventPayload, S as SessionManager, i as SessionStats, h as SessionStore, g as StorageBackend, U as UpdateSessionOptions, Z as ZeroDBSessionStore } from './ZeroDBSessionStore-BQisM5nM.js'; export { RedisSessionStore } from './session/index.js'; export { AINativeAuthProvider, APIKeyCredentials, AuthConfig, AuthCredentials, AuthError, AuthErrorType, AuthEvent, AuthEventListener, AuthEventType, AuthMethod, AuthResponse, AuthSession, AuthStatus, BaseCredentials, JWTCredentials, OAuthCredentials, RefreshResponse, StorageAdapter, StorageStrategy, TokenRefreshOptions, TokenValidationResult, UserInfo, ValidationResponse } from './auth/index.js'; export { A as AnalyticsResult, B as BatchOperation, E as ExportOptions, c as Feedback, F as FeedbackData, g as FeedbackFilter, d as FeedbackSession, e as FeedbackStats, f as IStorageBackend, i as InstrumentationConfig, I as InteractionLog, b as RLHFConfig, a as RLHFInstrumentation, R as RLHFLogger, M as RLHFMemoryStorage, Z as RLHFZeroDBStorage } from './ZeroDBStorage-BrocsToA.js'; export { L as RLHFLocalStorage } from './index-CFgNB7s4.js'; export { A as AccessibilityConstraint, B as BaseConstraint, e as ColorConstraint, b as ColorFormat, d as ColorPalette, h as ComponentConstraint, g as ComponentSizes, o as ConditionalConstraint, q as ConflictStrategy, k as Constraint, r as ConstraintParseResult, a as ConstraintPriority, p as ConstraintSetConfig, n as ConstraintTemplate, C as ConstraintType, j as CustomConstraint, D as DesignConstraints, s as DesignOutput, c as LayoutConstraint, L as LayoutSystem, M as MergeOptions, N as NaturalLanguageConstraint, t as PromptGenerationOptions, P as PromptInstruction, i as SpacingConstraint, S as SpacingSystem, f as TypographyConstraint, T as TypographyScale, l as ValidationIssue, m as ValidationResult, V as ValidationSeverity, W as WCAGLevel } from './DesignConstraints-C19svfal.js'; export { TEMPLATE_REGISTRY, createBootstrapTemplate, createFromTemplate, createMaterialDesignTemplate, createMinimalTemplate, createTailwindTemplate, createiOSTemplate, getAvailableTemplates, getTemplateMetadata } from './design/index.js'; import 'events'; /** * Tool type definitions for AI Kit * Comprehensive types for AI tools and function calling */ // Local type aliases for backwards compatibility within tools.d.ts type ToolError$1 = ToolExecutionErrorDetails; type ValidationError$1 = ValidationFailure; /** * Tool category */ type ToolCategory = | 'data' | 'computation' | 'communication' | 'search' | 'filesystem' | 'api' | 'database' | 'visualization' | 'analysis' | 'automation' | 'custom'; /** * Tool status */ type ToolStatus = | 'available' | 'unavailable' | 'deprecated' | 'experimental' | 'beta'; /** * Parameter type */ type ParameterType = | 'string' | 'number' | 'integer' | 'boolean' | 'array' | 'object' | 'null'; /** * Parameter schema (JSON Schema subset) */ interface ParameterSchema { readonly type: ParameterType | readonly ParameterType[]; readonly description?: string; readonly enum?: readonly JsonValue[]; readonly default?: JsonValue; readonly minimum?: number; readonly maximum?: number; readonly minLength?: number; readonly maxLength?: number; readonly pattern?: string; readonly format?: string; readonly items?: ParameterSchema; readonly properties?: Record; readonly required?: readonly string[]; readonly additionalProperties?: boolean | ParameterSchema; readonly oneOf?: readonly ParameterSchema[]; readonly anyOf?: readonly ParameterSchema[]; readonly allOf?: readonly ParameterSchema[]; readonly not?: ParameterSchema; readonly [key: string]: JsonValue | undefined; } /** * Tool parameter definition */ interface ToolParameter { readonly name: string; readonly description: string; readonly schema: ParameterSchema; readonly required: boolean; readonly defaultValue?: JsonValue; readonly examples?: readonly JsonValue[]; } /** * Tool return type schema */ interface ToolReturnSchema { readonly type: ParameterType | readonly ParameterType[]; readonly description?: string; readonly schema?: ParameterSchema; readonly examples?: readonly JsonValue[]; } // ============================================================================ // Tool Configuration // ============================================================================ /** * Tool configuration */ interface ToolConfig { readonly id: ToolId; readonly name: string; readonly description: string; readonly category: ToolCategory; readonly version?: string; readonly status?: ToolStatus; readonly parameters: readonly ToolParameter[]; readonly returns: ToolReturnSchema; readonly examples?: readonly ToolExample[]; readonly tags?: readonly string[]; readonly permissions?: readonly ToolPermission[]; readonly rateLimit?: RateLimitConfig; readonly timeout?: number; // milliseconds readonly caching?: ToolCacheConfig; readonly retryable?: boolean; readonly metadata?: Record; } /** * Tool example */ interface ToolExample { readonly description: string; readonly input: Record; readonly output: JsonValue; readonly explanation?: string; } /** * Tool permission */ type ToolPermission = | 'read' | 'write' | 'execute' | 'network' | 'filesystem' | 'database' | 'admin'; /** * Tool cache configuration */ interface ToolCacheConfig { readonly enabled: boolean; readonly ttl?: number; // seconds readonly keyGenerator?: (input: Record) => string; readonly strategy?: 'lru' | 'lfu' | 'ttl' | 'custom'; } // ============================================================================ // Tool Execution // ============================================================================ /** * Tool execution context */ interface ToolExecutionContext { readonly agentId?: AgentId; readonly messageId?: MessageId; readonly sessionId?: string; readonly userId?: string; readonly timestamp: number; readonly parentCallId?: string; // For nested tool calls readonly metadata?: Record; } /** * Tool execution options */ interface ToolExecutionOptions { readonly timeout?: number; // milliseconds readonly retry?: ToolRetryConfig; readonly cache?: boolean; readonly validate?: boolean; readonly context?: ToolExecutionContext; readonly signal?: AbortSignal; readonly metadata?: Record; } /** * Tool retry configuration */ interface ToolRetryConfig { readonly maxAttempts: number; readonly backoff: 'linear' | 'exponential' | 'constant'; readonly initialDelay: number; // milliseconds readonly maxDelay: number; // milliseconds readonly retryableErrors?: readonly string[]; } /** * Tool call result */ interface ToolCallResult { readonly callId: string; readonly success: boolean; readonly output?: JsonValue; readonly error?: ToolError$1; readonly duration: number; // milliseconds readonly cached?: boolean; readonly retries?: number; readonly timestamp: number; readonly metadata?: Record; } // ============================================================================ // Tool Handler // ============================================================================ /** * Tool handler function */ type ToolHandler, TOutput = JsonValue> = ( input: TInput, context: ToolExecutionContext, options?: ToolExecutionOptions ) => Promise | TOutput; /** * Tool validator function */ type ToolValidator = ( input: Record, schema: readonly ToolParameter[] ) => Result, ValidationError$1>; // ============================================================================ // Tool Interface // ============================================================================ /** * Core tool interface */ interface Tool, TOutput = JsonValue> { readonly config: ToolConfig; readonly handler: ToolHandler; // Execution execute( input: TInput, context?: ToolExecutionContext, options?: ToolExecutionOptions ): Promise; // Validation validateInput(input: Record): Result; // Schema getSchema(): ToolConfig; getParameterSchema(): readonly ToolParameter[]; getReturnSchema(): ToolReturnSchema; // Status isAvailable(): boolean; getStatus(): ToolStatus; } // ============================================================================ // Tool Registry // ============================================================================ /** * Tool registry interface */ interface ToolRegistry { // Registration register(tool: Tool): void; unregister(toolId: ToolId): void; registerMultiple(tools: readonly Tool[]): void; // Retrieval get(toolId: ToolId): Tool | undefined; getByName(name: string): Tool | undefined; getAll(): readonly Tool[]; getByCategory(category: ToolCategory): readonly Tool[]; getByTags(tags: readonly string[]): readonly Tool[]; // Search search(query: string): readonly Tool[]; filter(predicate: (tool: Tool) => boolean): readonly Tool[]; // Status has(toolId: ToolId): boolean; count(): number; getAvailable(): readonly Tool[]; } // ============================================================================ // Tool Builder // ============================================================================ /** * Fluent tool builder */ interface ToolBuilder, TOutput = JsonValue> { // Basic info name(name: string): this; description(description: string): this; category(category: ToolCategory): this; version(version: string): this; status(status: ToolStatus): this; // Parameters parameter(param: ToolParameter): this; requiredParameter(name: string, description: string, schema: ParameterSchema): this; optionalParameter( name: string, description: string, schema: ParameterSchema, defaultValue?: JsonValue ): this; // Return type returns(schema: ToolReturnSchema): this; // Configuration timeout(ms: number): this; rateLimit(config: RateLimitConfig): this; permissions(perms: readonly ToolPermission[]): this; caching(config: ToolCacheConfig): this; retryable(enabled: boolean): this; tags(tags: readonly string[]): this; // Examples example(example: ToolExample): this; // Handler handler(handler: ToolHandler): this; // Build build(): Tool; } // ============================================================================ // Specialized Tool Types // ============================================================================ /** * API tool configuration */ interface APIToolConfig extends ToolConfig { readonly endpoint: string; readonly method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'; readonly headers?: Record; readonly authentication?: AuthenticationConfig; readonly requestTransform?: (input: Record) => JsonValue; readonly responseTransform?: (response: JsonValue) => JsonValue; } /** * Database tool configuration */ interface DatabaseToolConfig extends ToolConfig { readonly connectionString: string; readonly database: string; readonly query: string; readonly parameterMapping?: Record; readonly resultTransform?: (results: JsonValue) => JsonValue; } /** * File system tool configuration */ interface FileSystemToolConfig extends ToolConfig { readonly basePath?: string; readonly allowedPaths?: readonly string[]; readonly maxFileSize?: number; // bytes readonly allowedExtensions?: readonly string[]; } /** * Search tool configuration */ interface SearchToolConfig extends ToolConfig { readonly searchEngine: 'google' | 'bing' | 'duckduckgo' | 'custom'; readonly maxResults?: number; readonly filters?: Record; readonly resultFormat?: 'full' | 'snippet' | 'links'; } /** * Code execution tool configuration */ interface CodeExecutionToolConfig extends ToolConfig { readonly language: string; readonly runtime: string; readonly memoryLimit?: number; // MB readonly cpuLimit?: number; // milliseconds readonly networkAccess?: boolean; readonly fileSystemAccess?: 'none' | 'read-only' | 'read-write'; readonly allowedPackages?: readonly string[]; } // ============================================================================ // Tool Composition // ============================================================================ /** * Composite tool - combines multiple tools */ interface CompositeTool extends Tool { readonly tools: readonly ToolId[]; readonly composition: CompositionStrategy; } /** * Composition strategy */ type CompositionStrategy = | 'sequential' // Execute tools in sequence, passing output to next | 'parallel' // Execute tools in parallel, aggregate results | 'conditional' // Execute tools based on conditions | 'fallback'; // Try tools in order until one succeeds /** * Tool pipeline configuration */ interface ToolPipeline { readonly id: string; readonly name: string; readonly steps: readonly ToolPipelineStep[]; readonly errorHandling?: 'abort' | 'continue' | 'fallback'; } /** * Tool pipeline step */ interface ToolPipelineStep { readonly toolId: ToolId; readonly inputMapping?: Record; // Map from previous outputs readonly outputMapping?: Record; // Map to next inputs readonly condition?: (context: Record) => boolean; readonly fallback?: ToolId; } // ============================================================================ // Tool Monitoring // ============================================================================ /** * Tool usage statistics */ interface ToolUsageStats { readonly toolId: ToolId; readonly totalCalls: number; readonly successfulCalls: number; readonly failedCalls: number; readonly averageDuration: number; // milliseconds readonly cacheHitRate?: number; // 0-1 readonly lastUsed?: number; // timestamp readonly errorBreakdown: Record; } /** * Tool performance metrics */ interface ToolPerformanceMetrics { readonly p50: number; // 50th percentile duration readonly p95: number; // 95th percentile duration readonly p99: number; // 99th percentile duration readonly min: number; readonly max: number; readonly mean: number; readonly stdDev: number; } /** * Tool event */ interface ToolEvent { readonly type: ToolEventType; readonly toolId: ToolId; readonly callId: string; readonly timestamp: number; readonly data?: JsonValue; } /** * Tool event types */ type ToolEventType = | 'call_start' | 'call_end' | 'call_error' | 'cache_hit' | 'cache_miss' | 'rate_limit' | 'timeout' | 'retry'; /** * Tool observer interface */ interface ToolObserver { onEvent(event: ToolEvent): void | Promise; } /** * LLM Model type definitions for AI Kit * Comprehensive types for language models and model management */ // ============================================================================ // Model Identifiers and Categories // ============================================================================ /** * Model provider */ type ModelProvider = | 'openai' | 'anthropic' | 'google' | 'cohere' | 'mistral' | 'huggingface' | 'azure' | 'aws' | 'local' | 'custom'; /** * Model category */ type ModelCategory = | 'chat' | 'completion' | 'embedding' | 'image' | 'audio' | 'video' | 'multimodal' | 'code' | 'reasoning'; /** * Model size category */ type ModelSize = 'tiny' | 'small' | 'medium' | 'large' | 'xlarge'; /** * Model capability */ type ModelCapability = | 'chat' | 'streaming' | 'function-calling' | 'vision' | 'audio' | 'code' | 'reasoning' | 'embeddings' | 'fine-tuning'; // ============================================================================ // Model Configuration // ============================================================================ /** * Model configuration */ interface ModelConfig { readonly id: ModelId; readonly name: string; readonly provider: ModelProvider; readonly category: ModelCategory; readonly version?: string; readonly capabilities: readonly ModelCapability[]; readonly contextWindow: number; // max tokens readonly maxOutputTokens: number; readonly inputCostPer1kTokens?: number; // in USD readonly outputCostPer1kTokens?: number; // in USD readonly supportedLanguages?: readonly string[]; readonly defaultParameters?: ModelParameters; readonly metadata?: Record; } /** * Model parameters */ interface ModelParameters { readonly temperature?: number; // 0-2 readonly topP?: number; // 0-1 readonly topK?: number; readonly frequencyPenalty?: number; // -2 to 2 readonly presencePenalty?: number; // -2 to 2 readonly maxTokens?: number; readonly stop?: readonly string[]; readonly seed?: number; readonly responseFormat?: ResponseFormat; readonly logitBias?: Record; readonly n?: number; // number of completions readonly [key: string]: JsonValue | undefined; } /** * Response format */ interface ResponseFormat { readonly type: 'text' | 'json_object' | 'json_schema'; readonly schema?: JsonValue; // JSON Schema } // ============================================================================ // Model Endpoints and Authentication // ============================================================================ /** * Model endpoint configuration */ interface ModelEndpoint { readonly url: string; readonly method?: 'GET' | 'POST'; readonly headers?: Record; readonly authentication: ModelAuthentication; readonly timeout?: number; // milliseconds readonly retryConfig?: RetryConfig; } /** * Model authentication */ interface ModelAuthentication { readonly type: 'none' | 'bearer' | 'api-key' | 'oauth2' | 'custom'; readonly credentials?: ModelCredentials; readonly headerName?: string; // For API key authentication } /** * Model credentials */ interface ModelCredentials { readonly apiKey?: string; readonly token?: string; readonly clientId?: string; readonly clientSecret?: string; readonly [key: string]: string | undefined; } // ============================================================================ // Model Selection and Routing // ============================================================================ /** * Model selection criteria */ interface ModelSelectionCriteria { readonly provider?: ModelProvider; readonly category?: ModelCategory; readonly capabilities?: readonly ModelCapability[]; readonly minContextWindow?: number; readonly maxCost?: number; // cost per 1k tokens readonly preferredModels?: readonly ModelId[]; readonly excludedModels?: readonly ModelId[]; readonly size?: ModelSize; } /** * Model selector interface */ interface ModelSelector { select(criteria: ModelSelectionCriteria): ModelId | null; selectMultiple(criteria: ModelSelectionCriteria, count: number): readonly ModelId[]; rank(criteria: ModelSelectionCriteria): readonly ModelRanking[]; } /** * Model ranking result */ interface ModelRanking { readonly modelId: ModelId; readonly score: number; // 0-1 readonly reasons: readonly string[]; readonly matchedCriteria: readonly string[]; } /** * Model router configuration */ interface ModelRouterConfig { readonly strategy: RoutingStrategy; readonly fallbackModel?: ModelId; readonly loadBalancing?: LoadBalancingConfig; readonly costOptimization?: boolean; readonly qualityThreshold?: number; // 0-1 } /** * Routing strategy */ type RoutingStrategy = | 'cheapest' // Select cheapest model | 'fastest' // Select fastest model | 'best-quality' // Select highest quality model | 'balanced' // Balance cost/speed/quality | 'round-robin' // Rotate through models | 'least-loaded' // Select least busy model | 'custom'; // ============================================================================ // Model Performance and Monitoring // ============================================================================ /** * Model performance metrics */ interface ModelPerformanceMetrics { readonly modelId: ModelId; readonly totalRequests: number; readonly successfulRequests: number; readonly failedRequests: number; readonly averageLatency: number; // milliseconds readonly p50Latency: number; readonly p95Latency: number; readonly p99Latency: number; readonly averageTokensPerSecond: number; readonly totalTokensUsed: number; readonly totalCost: number; readonly errorRate: number; // 0-1 readonly availability: number; // 0-1 readonly lastUpdated: number; // timestamp } /** * Model health status */ interface ModelHealthStatus { readonly modelId: ModelId; readonly status: 'healthy' | 'degraded' | 'unhealthy' | 'unknown'; readonly responseTime?: number; // milliseconds readonly errorRate?: number; // 0-1 readonly lastCheck: number; // timestamp readonly issues?: readonly string[]; } /** * Model usage statistics */ interface ModelUsageStatistics { readonly modelId: ModelId; readonly period: TimePeriod; readonly requestCount: number; readonly tokenCount: number; readonly cost: number; readonly breakdown: UsageBreakdown; } /** * Time period for statistics */ interface TimePeriod { readonly start: number; // timestamp readonly end: number; // timestamp readonly duration: number; // milliseconds } /** * Usage breakdown */ interface UsageBreakdown { readonly byDay?: Record; readonly byUser?: Record; readonly byAgent?: Record; readonly byOperation?: Record; } // ============================================================================ // Model Comparison and Benchmarking // ============================================================================ /** * Model comparison request */ interface ModelComparisonRequest { readonly models: readonly ModelId[]; readonly prompt: string; readonly parameters?: ModelParameters; readonly criteria: readonly ComparisonCriterion[]; } /** * Comparison criterion */ type ComparisonCriterion = | 'accuracy' | 'speed' | 'cost' | 'quality' | 'consistency' | 'creativity'; /** * Model comparison result */ interface ModelComparisonResult { readonly models: readonly ModelId[]; readonly results: readonly ModelResult[]; readonly rankings: Record; readonly winner?: ModelId; readonly analysis: string; } /** * Individual model result in comparison */ interface ModelResult { readonly modelId: ModelId; readonly output: string; readonly duration: number; // milliseconds readonly cost: number; readonly tokenCount: number; readonly scores: Record; // 0-1 readonly metadata?: Record; } /** * Benchmark configuration */ interface BenchmarkConfig { readonly name: string; readonly description?: string; readonly prompts: readonly string[]; readonly models: readonly ModelId[]; readonly parameters?: ModelParameters; readonly metrics: readonly ComparisonCriterion[]; readonly iterations?: number; } /** * Benchmark result */ interface BenchmarkResult { readonly config: BenchmarkConfig; readonly results: readonly ModelComparisonResult[]; readonly summary: BenchmarkSummary; readonly timestamp: number; } /** * Benchmark summary */ interface BenchmarkSummary { readonly overall: Record; // Average score 0-1 readonly byMetric: Record>; readonly winner: ModelId; readonly recommendations: readonly string[]; } // ============================================================================ // Model Versioning and Deprecation // ============================================================================ /** * Model version */ interface ModelVersion { readonly version: string; readonly releaseDate: number; // timestamp readonly deprecationDate?: number; // timestamp readonly endOfLifeDate?: number; // timestamp readonly changes?: readonly string[]; readonly breaking?: boolean; readonly stable: boolean; } /** * Model lifecycle stage */ type ModelLifecycleStage = | 'preview' | 'beta' | 'stable' | 'deprecated' | 'end-of-life'; /** * Model deprecation notice */ interface DeprecationNotice { readonly modelId: ModelId; readonly stage: ModelLifecycleStage; readonly deprecationDate: number; // timestamp readonly endOfLifeDate: number; // timestamp readonly migrationGuide?: string; readonly replacementModels?: readonly ModelId[]; readonly reason?: string; } // ============================================================================ // Model Registry // ============================================================================ /** * Model registry interface */ interface ModelRegistry { // Registration register(config: ModelConfig): void; unregister(modelId: ModelId): void; update(modelId: ModelId, updates: Partial): void; // Retrieval get(modelId: ModelId): ModelConfig | undefined; getAll(): readonly ModelConfig[]; getByProvider(provider: ModelProvider): readonly ModelConfig[]; getByCategory(category: ModelCategory): readonly ModelConfig[]; getByCapability(capability: ModelCapability): readonly ModelConfig[]; // Search search(query: string): readonly ModelConfig[]; filter(predicate: (config: ModelConfig) => boolean): readonly ModelConfig[]; // Status has(modelId: ModelId): boolean; count(): number; getAvailable(): readonly ModelConfig[]; getDeprecated(): readonly DeprecationNotice[]; } // ============================================================================ // Model Provider Interfaces // ============================================================================ /** * Model provider interface */ interface ModelProviderInterface { readonly provider: ModelProvider; readonly models: readonly ModelConfig[]; // Execution complete( modelId: ModelId, prompt: string, parameters?: ModelParameters ): Promise; stream( modelId: ModelId, prompt: string, parameters?: ModelParameters ): AsyncIterableIterator; embed(modelId: ModelId, input: string | readonly string[]): Promise; // Management listModels(): Promise; getModel(modelId: ModelId): Promise; validateApiKey(): Promise; } /** * Completion response */ interface CompletionResponse { readonly id: string; readonly model: ModelId; readonly choices: readonly CompletionChoice[]; readonly usage: UsageStats; readonly created: number; // timestamp readonly metadata?: Record; } /** * Completion choice */ interface CompletionChoice { readonly index: number; readonly text: string; readonly finishReason: FinishReason; readonly logprobs?: LogProbs; } /** * Finish reason */ type FinishReason = 'stop' | 'length' | 'content_filter' | 'function_call' | 'tool_calls'; /** * Log probabilities */ interface LogProbs { readonly tokens: readonly string[]; readonly tokenLogprobs: readonly number[]; readonly topLogprobs?: readonly Record[]; readonly textOffset: readonly number[]; } /** * Completion chunk (for streaming) */ interface CompletionChunk { readonly id: string; readonly model: ModelId; readonly delta: string; readonly finishReason?: FinishReason; readonly index: number; } /** * Embedding response */ interface EmbeddingResponse { readonly model: ModelId; readonly embeddings: readonly Embedding[]; readonly usage: UsageStats; } /** * Single embedding */ interface Embedding { readonly index: number; readonly embedding: readonly number[]; readonly object: 'embedding'; } // ============================================================================ // Model Caching // ============================================================================ /** * Model cache configuration */ interface ModelCacheConfig { readonly enabled: boolean; readonly ttl: number; // seconds readonly maxSize?: number; // max items readonly strategy: 'lru' | 'lfu' | 'ttl'; readonly keyGenerator?: (prompt: string, params: ModelParameters) => string; } /** * Cached response metadata */ interface CachedResponseMetadata { readonly cached: true; readonly cachedAt: number; // timestamp readonly expiresAt: number; // timestamp readonly hits: number; } // ============================================================================ // Fine-tuning Support // ============================================================================ /** * Fine-tuning job configuration */ interface FineTuningConfig { readonly baseModel: ModelId; readonly trainingData: string; // File path or URL readonly validationData?: string; readonly hyperparameters?: FineTuningHyperparameters; readonly suffix?: string; } /** * Fine-tuning hyperparameters */ interface FineTuningHyperparameters { readonly nEpochs?: number; readonly batchSize?: number; readonly learningRateMultiplier?: number; readonly promptLossWeight?: number; } /** * Fine-tuning job status */ interface FineTuningJob { readonly id: string; readonly status: 'pending' | 'running' | 'succeeded' | 'failed' | 'cancelled'; readonly createdAt: number; readonly finishedAt?: number; readonly fineTunedModel?: ModelId; readonly error?: string; readonly metrics?: FineTuningMetrics; } /** * Fine-tuning metrics */ interface FineTuningMetrics { readonly trainLoss?: number; readonly validLoss?: number; readonly trainAccuracy?: number; readonly validAccuracy?: number; readonly steps: number; } /** * Error type definitions for AI Kit * Comprehensive error types and error handling utilities */ // ============================================================================ // Error Categories // ============================================================================ /** * Error category for classification */ type ErrorCategory = | 'validation' | 'authentication' | 'authorization' | 'rate-limit' | 'timeout' | 'network' | 'model' | 'tool' | 'agent' | 'stream' | 'configuration' | 'internal' | 'unknown'; /** * Error severity level */ type ErrorSeverity = 'low' | 'medium' | 'high' | 'critical'; /** * Error code - branded string for type safety */ type ErrorCode = Brand; // ============================================================================ // Base Error Types // ============================================================================ /** * Base AI Kit error interface */ interface AIKitError extends Error { readonly name: string; readonly message: string; readonly code: ErrorCode; readonly category: ErrorCategory; readonly severity: ErrorSeverity; readonly recoverable: boolean; readonly timestamp: number; readonly details?: JsonValue; readonly cause?: Error; readonly stack?: string; readonly metadata?: Record; } /** * Error context for additional information */ interface ErrorContext { readonly operation?: string; readonly component?: string; readonly userId?: string; readonly sessionId?: string; readonly requestId?: string; readonly modelId?: ModelId; readonly toolId?: ToolId; readonly agentId?: AgentId; readonly timestamp: number; readonly [key: string]: JsonValue | undefined; } // ============================================================================ // Validation Errors // ============================================================================ /** * Validation error */ interface ValidationError extends AIKitError { readonly category: 'validation'; readonly field?: string; readonly expected?: string; readonly received?: string; readonly constraint?: string; readonly validationErrors?: readonly FieldValidationError[]; } /** * Field validation error */ interface FieldValidationError { readonly field: string; readonly message: string; readonly constraint: string; readonly value?: JsonValue; } /** * Schema validation error */ interface SchemaValidationError extends ValidationError { readonly schema?: JsonValue; readonly path?: string; } /** * Parameter validation error */ interface ParameterValidationError extends ValidationError { readonly parameter: string; readonly required: boolean; } // ============================================================================ // Authentication and Authorization Errors // ============================================================================ /** * Authentication error */ interface AuthenticationError extends AIKitError { readonly category: 'authentication'; readonly authMethod?: string; readonly provider?: string; } /** * Authorization error */ interface AuthorizationError extends AIKitError { readonly category: 'authorization'; readonly resource?: string; readonly action?: string; readonly requiredPermissions?: readonly string[]; readonly userPermissions?: readonly string[]; } /** * API key error */ interface APIKeyError extends AuthenticationError { readonly keyId?: string; readonly expired: boolean; readonly invalid: boolean; } /** * Token error */ interface TokenError extends AuthenticationError { readonly tokenType: 'access' | 'refresh' | 'api'; readonly expired: boolean; readonly invalid: boolean; readonly expiresAt?: number; } // ============================================================================ // Rate Limit Errors // ============================================================================ /** * Rate limit error */ interface RateLimitError extends AIKitError { readonly category: 'rate-limit'; readonly limit: number; readonly remaining: number; readonly resetAt: number; // timestamp readonly retryAfter: number; // milliseconds readonly scope: 'user' | 'api-key' | 'ip' | 'global'; } /** * Quota exceeded error */ interface QuotaExceededError extends RateLimitError { readonly quotaType: 'requests' | 'tokens' | 'cost' | 'storage'; readonly used: number; readonly quota: number; readonly period: 'minute' | 'hour' | 'day' | 'month'; } // ============================================================================ // Timeout and Network Errors // ============================================================================ /** * Timeout error */ interface TimeoutError extends AIKitError { readonly category: 'timeout'; readonly timeoutMs: number; readonly elapsedMs: number; readonly operation: string; } /** * Network error */ interface NetworkError extends AIKitError { readonly category: 'network'; readonly statusCode?: number; readonly endpoint?: string; readonly method?: string; readonly retryable: boolean; } /** * Connection error */ interface ConnectionError extends NetworkError { readonly host?: string; readonly port?: number; readonly protocol?: string; } /** * HTTP error */ interface HTTPError extends NetworkError { readonly statusCode: number; readonly statusText?: string; readonly requestId?: string; readonly headers?: Record; readonly body?: JsonValue; } // ============================================================================ // Model Errors // ============================================================================ /** * Model error */ interface ModelError extends AIKitError { readonly category: 'model'; readonly modelId?: ModelId; readonly provider?: string; } /** * Model not found error */ interface ModelNotFoundError extends ModelError { readonly modelId: ModelId; readonly availableModels?: readonly ModelId[]; } /** * Model unavailable error */ interface ModelUnavailableError extends ModelError { readonly modelId: ModelId; readonly reason?: string; readonly retryAfter?: number; // milliseconds } /** * Model response error */ interface ModelResponseError extends ModelError { readonly modelId: ModelId; readonly prompt?: string; readonly response?: string; readonly finishReason?: string; } /** * Context length exceeded error */ interface ContextLengthError extends ModelError { readonly modelId: ModelId; readonly maxTokens: number; readonly requestedTokens: number; readonly promptTokens: number; readonly completionTokens?: number; } /** * Content filter error */ interface ContentFilterError extends ModelError { readonly modelId: ModelId; readonly filterType: 'hate' | 'violence' | 'sexual' | 'self-harm' | 'profanity'; readonly severity: 'low' | 'medium' | 'high'; readonly prompt?: string; readonly response?: string; } // ============================================================================ // Tool Errors // ============================================================================ /** * Tool error */ interface ToolError extends AIKitError { readonly category: 'tool'; readonly toolId?: ToolId; readonly toolName?: string; } /** * Tool not found error */ interface ToolNotFoundError extends ToolError { readonly toolId: ToolId; readonly availableTools?: readonly ToolId[]; } /** * Tool execution error */ interface ToolExecutionError extends ToolError { readonly toolId: ToolId; readonly input?: JsonValue; readonly output?: JsonValue; readonly exitCode?: number; } /** * Tool timeout error */ interface ToolTimeoutError extends ToolError { readonly toolId: ToolId; readonly timeoutMs: number; readonly elapsedMs: number; } /** * Tool permission error */ interface ToolPermissionError extends ToolError { readonly toolId: ToolId; readonly requiredPermissions: readonly string[]; readonly grantedPermissions: readonly string[]; } // ============================================================================ // Agent Errors // ============================================================================ /** * Agent error */ interface AgentError extends AIKitError { readonly category: 'agent'; readonly agentId?: AgentId; readonly agentName?: string; } /** * Agent not found error */ interface AgentNotFoundError extends AgentError { readonly agentId: AgentId; } /** * Agent execution error */ interface AgentExecutionError extends AgentError { readonly agentId: AgentId; readonly task?: string; readonly iteration?: number; } /** * Agent communication error */ interface AgentCommunicationError extends AgentError { readonly fromAgent: AgentId; readonly toAgent: AgentId; readonly messageType?: string; } /** * Agent state error */ interface AgentStateError extends AgentError { readonly agentId: AgentId; readonly currentState?: string; readonly expectedState?: string; } // ============================================================================ // Stream Errors // ============================================================================ /** * Stream error */ interface StreamError extends AIKitError { readonly category: 'stream'; readonly streamId?: string; } /** * Stream connection error */ interface StreamConnectionError extends StreamError { readonly endpoint?: string; readonly transport?: 'sse' | 'websocket'; } /** * Stream abort error */ interface StreamAbortError extends StreamError { readonly reason?: string; readonly abortedBy?: 'user' | 'timeout' | 'error' | 'server'; } /** * Stream parse error */ interface StreamParseError extends StreamError { readonly chunk?: string; readonly position?: number; } // ============================================================================ // Configuration Errors // ============================================================================ /** * Configuration error */ interface ConfigurationError extends AIKitError { readonly category: 'configuration'; readonly configKey?: string; readonly configValue?: JsonValue; } /** * Missing configuration error */ interface MissingConfigError extends ConfigurationError { readonly requiredKeys: readonly string[]; readonly providedKeys: readonly string[]; } /** * Invalid configuration error */ interface InvalidConfigError extends ConfigurationError { readonly configKey: string; readonly expectedType?: string; readonly receivedType?: string; readonly constraint?: string; } // ============================================================================ // Internal Errors // ============================================================================ /** * Internal error */ interface InternalError extends AIKitError { readonly category: 'internal'; readonly component?: string; } /** * Not implemented error */ interface NotImplementedError extends InternalError { readonly feature: string; readonly plannedVersion?: string; } /** * Assertion error */ interface AssertionError extends InternalError { readonly assertion: string; readonly expected?: JsonValue; readonly actual?: JsonValue; } // ============================================================================ // Error Aggregation // ============================================================================ /** * Aggregate error - contains multiple errors */ interface AggregateError extends AIKitError { readonly errors: readonly AIKitError[]; readonly successCount?: number; readonly failureCount: number; } /** * Validation aggregate error */ interface ValidationAggregateError extends AggregateError { readonly category: 'validation'; readonly errors: readonly ValidationError[]; } // ============================================================================ // Error Factory // ============================================================================ /** * Error factory options */ interface ErrorFactoryOptions { readonly message: string; readonly code?: ErrorCode; readonly severity?: ErrorSeverity; readonly recoverable?: boolean; readonly details?: JsonValue; readonly cause?: Error; readonly context?: ErrorContext; readonly metadata?: Record; } /** * Error factory interface */ interface ErrorFactory { // Validation errors validation(options: ErrorFactoryOptions): ValidationError; schemaValidation(schema: JsonValue, options: ErrorFactoryOptions): SchemaValidationError; parameterValidation(parameter: string, options: ErrorFactoryOptions): ParameterValidationError; // Auth errors authentication(options: ErrorFactoryOptions): AuthenticationError; authorization(resource: string, action: string, options: ErrorFactoryOptions): AuthorizationError; apiKey(keyId: string, options: ErrorFactoryOptions): APIKeyError; // Rate limit errors rateLimit(limit: number, resetAt: number, options: ErrorFactoryOptions): RateLimitError; quotaExceeded( quotaType: QuotaExceededError['quotaType'], used: number, quota: number, options: ErrorFactoryOptions ): QuotaExceededError; // Network errors timeout(timeoutMs: number, elapsedMs: number, options: ErrorFactoryOptions): TimeoutError; network(statusCode: number, options: ErrorFactoryOptions): NetworkError; http(statusCode: number, statusText: string, options: ErrorFactoryOptions): HTTPError; // Model errors model(modelId: ModelId, options: ErrorFactoryOptions): ModelError; modelNotFound(modelId: ModelId, options: ErrorFactoryOptions): ModelNotFoundError; contextLength( modelId: ModelId, maxTokens: number, requestedTokens: number, options: ErrorFactoryOptions ): ContextLengthError; // Tool errors tool(toolId: ToolId, options: ErrorFactoryOptions): ToolError; toolNotFound(toolId: ToolId, options: ErrorFactoryOptions): ToolNotFoundError; toolExecution(toolId: ToolId, options: ErrorFactoryOptions): ToolExecutionError; // Agent errors agent(agentId: AgentId, options: ErrorFactoryOptions): AgentError; agentNotFound(agentId: AgentId, options: ErrorFactoryOptions): AgentNotFoundError; // Stream errors stream(options: ErrorFactoryOptions): StreamError; streamAbort(reason: string, options: ErrorFactoryOptions): StreamAbortError; // Configuration errors configuration(configKey: string, options: ErrorFactoryOptions): ConfigurationError; missingConfig(requiredKeys: readonly string[], options: ErrorFactoryOptions): MissingConfigError; // Internal errors internal(component: string, options: ErrorFactoryOptions): InternalError; notImplemented(feature: string, options: ErrorFactoryOptions): NotImplementedError; // Aggregate errors aggregate(errors: readonly AIKitError[], options: ErrorFactoryOptions): AggregateError; } // ============================================================================ // Error Handler // ============================================================================ /** * Error handler function */ type ErrorHandler = (error: AIKitError, context?: ErrorContext) => void | Promise; /** * Error recovery strategy */ type ErrorRecoveryStrategy = | 'retry' | 'fallback' | 'ignore' | 'propagate' | 'circuit-break' | 'custom'; /** * Error recovery options */ interface ErrorRecoveryOptions { readonly strategy: ErrorRecoveryStrategy; readonly maxRetries?: number; readonly retryDelay?: number; // milliseconds readonly fallbackValue?: JsonValue; readonly circuitBreakerThreshold?: number; readonly customHandler?: ErrorHandler; } /** * Error handling middleware */ type ErrorMiddleware = ( error: AIKitError, next: (error: AIKitError) => void | Promise ) => void | Promise; // ============================================================================ // Error Reporter // ============================================================================ /** * Error report */ interface ErrorReport { readonly error: AIKitError; readonly context: ErrorContext; readonly timestamp: number; readonly stackTrace?: string; readonly userAgent?: string; readonly environment?: string; readonly version?: string; } /** * Error reporter interface */ interface ErrorReporter { report(error: AIKitError, context?: ErrorContext): void | Promise; reportMany(errors: readonly AIKitError[], context?: ErrorContext): void | Promise; } // ============================================================================ // Error Statistics // ============================================================================ /** * Error statistics */ interface ErrorStatistics { readonly totalErrors: number; readonly errorsByCategory: Record; readonly errorsBySeverity: Record; readonly errorRate: number; // errors per minute readonly mostCommonErrors: readonly ErrorSummary[]; readonly period: { readonly start: number; readonly end: number; }; } /** * Error summary */ interface ErrorSummary { readonly code: ErrorCode; readonly message: string; readonly count: number; readonly category: ErrorCategory; readonly severity: ErrorSeverity; readonly firstOccurrence: number; readonly lastOccurrence: number; } /** * Configuration type definitions for AI Kit * Comprehensive types for framework configuration */ // ============================================================================ // Core Configuration // ============================================================================ /** * Environment type */ type Environment = 'development' | 'staging' | 'production' | 'test'; /** * Log level */ type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'fatal' | 'silent'; /** * AI Kit configuration */ interface AIKitConfig { readonly environment: Environment; readonly version?: string; readonly models?: ModelsConfig; readonly tools?: ToolsConfig; readonly agents?: AgentsConfig; readonly streaming?: StreamingConfig; readonly caching?: CachingConfig; readonly logging?: LoggingConfig; readonly monitoring?: MonitoringConfig; readonly security?: SecurityConfig; readonly performance?: PerformanceConfig; readonly storage?: StorageConfig; readonly providers?: ProvidersConfig; readonly features?: FeaturesConfig; readonly experimental?: ExperimentalConfig; readonly metadata?: Record; } // ============================================================================ // Models Configuration // ============================================================================ /** * Models configuration */ interface ModelsConfig { readonly defaultProvider?: ModelProvider; readonly defaultModel?: ModelId; readonly providers: Record; readonly routing?: ModelRoutingConfig; readonly fallback?: ModelFallbackConfig; readonly optimization?: ModelOptimizationConfig; } /** * Provider configuration */ interface ProviderConfig { readonly enabled: boolean; readonly apiKey?: string; readonly endpoint?: string; readonly organization?: string; readonly timeout?: number; // milliseconds readonly maxRetries?: number; readonly rateLimit?: RateLimitConfig; readonly models?: readonly ModelId[]; readonly defaultParameters?: Record; readonly headers?: Record; readonly metadata?: Record; } /** * Model routing configuration */ interface ModelRoutingConfig { readonly enabled: boolean; readonly strategy: 'cheapest' | 'fastest' | 'best-quality' | 'balanced' | 'custom'; readonly rules?: readonly RoutingRule[]; readonly loadBalancing?: LoadBalancingConfig; } /** * Routing rule */ interface RoutingRule { readonly condition: RoutingCondition; readonly target: ModelId; readonly priority?: number; } /** * Routing condition */ interface RoutingCondition { readonly maxTokens?: number; readonly capabilities?: readonly string[]; readonly tags?: readonly string[]; readonly costLimit?: number; readonly custom?: (context: Record) => boolean; } /** * Model fallback configuration */ interface ModelFallbackConfig { readonly enabled: boolean; readonly fallbackChain?: readonly ModelId[]; readonly maxAttempts?: number; readonly conditions?: readonly FallbackCondition[]; } /** * Fallback condition */ interface FallbackCondition { readonly errorCodes?: readonly string[]; readonly statusCodes?: readonly number[]; readonly timeout?: number; // milliseconds } /** * Model optimization configuration */ interface ModelOptimizationConfig { readonly promptCompression?: boolean; readonly responseOptimization?: boolean; readonly batchingEnabled?: boolean; readonly batchSize?: number; readonly batchWindowMs?: number; } // ============================================================================ // Tools Configuration // ============================================================================ /** * Tools configuration */ interface ToolsConfig { readonly enabled: boolean; readonly registry?: ToolRegistryConfig; readonly execution?: ToolExecutionConfig; readonly security?: ToolSecurityConfig; readonly defaults?: ToolDefaultsConfig; } /** * Tool registry configuration */ interface ToolRegistryConfig { readonly autoDiscover?: boolean; readonly paths?: readonly string[]; readonly whitelist?: readonly ToolId[]; readonly blacklist?: readonly ToolId[]; } /** * Tool execution configuration */ interface ToolExecutionConfig { readonly timeout?: number; // milliseconds readonly maxConcurrent?: number; readonly retry?: RetryConfig; readonly sandboxed?: boolean; readonly resourceLimits?: ResourceLimits; } /** * Resource limits for tool execution */ interface ResourceLimits { readonly memory?: number; // bytes readonly cpu?: number; // percentage readonly diskIO?: number; // bytes per second readonly networkIO?: number; // bytes per second } /** * Tool security configuration */ interface ToolSecurityConfig { readonly permissions?: Record; readonly requireApproval?: boolean; readonly dangerousToolsBlocked?: boolean; readonly auditLogging?: boolean; } /** * Tool defaults configuration */ interface ToolDefaultsConfig { readonly timeout?: number; readonly retryable?: boolean; readonly caching?: boolean; readonly validation?: boolean; } // ============================================================================ // Agents Configuration // ============================================================================ /** * Agents configuration */ interface AgentsConfig { readonly enabled: boolean; readonly defaults?: AgentDefaultsConfig; readonly collaboration?: CollaborationConfig; readonly planning?: PlanningConfig; readonly learning?: LearningConfig; readonly memory?: MemoryConfig; } /** * Agent defaults configuration */ interface AgentDefaultsConfig { readonly model?: ModelId; readonly temperature?: number; readonly maxIterations?: number; readonly timeout?: number; // milliseconds readonly tools?: readonly ToolId[]; } /** * Planning configuration */ interface PlanningConfig { readonly enabled: boolean; readonly strategy?: 'forward' | 'backward' | 'hierarchical' | 'reactive' | 'deliberative'; readonly maxDepth?: number; readonly timeLimit?: number; // milliseconds } // ============================================================================ // Streaming Configuration // ============================================================================ /** * Streaming configuration */ interface StreamingConfig { readonly enabled: boolean; readonly transport?: 'sse' | 'websocket' | 'http'; readonly reconnect?: boolean; readonly maxReconnectAttempts?: number; readonly reconnectDelay?: number; // milliseconds readonly heartbeatInterval?: number; // milliseconds readonly bufferSize?: number; readonly compression?: boolean; } // ============================================================================ // Caching Configuration // ============================================================================ /** * Caching configuration */ interface CachingConfig { readonly enabled: boolean; readonly storage?: CacheStorageConfig; readonly policies?: CachePoliciesConfig; readonly invalidation?: CacheInvalidationConfig; readonly compression?: boolean; } /** * Cache storage configuration */ interface CacheStorageConfig { readonly type: 'memory' | 'redis' | 'memcached' | 'custom'; readonly url?: string; readonly options?: Record; readonly maxSize?: number; // max items readonly maxSizeBytes?: number; // max bytes } /** * Cache policies configuration */ interface CachePoliciesConfig { readonly default?: CachePolicy; readonly models?: Record; readonly tools?: Record; readonly custom?: Record; } /** * Cache policy */ interface CachePolicy { readonly ttl?: number; // seconds readonly strategy?: 'lru' | 'lfu' | 'ttl' | 'adaptive'; readonly keyGenerator?: string; // function name or reference readonly conditions?: readonly CacheCondition[]; } /** * Cache condition */ interface CacheCondition { readonly parameter?: string; readonly operator: '==' | '!=' | '>' | '<' | '>=' | '<=' | 'contains' | 'matches'; readonly value: JsonValue; } /** * Cache invalidation configuration */ interface CacheInvalidationConfig { readonly enabled: boolean; readonly strategies?: readonly CacheInvalidationStrategy[]; readonly webhook?: string; } /** * Cache invalidation strategy */ type CacheInvalidationStrategy = | 'time-based' | 'event-based' | 'pattern-based' | 'manual' | 'custom'; // ============================================================================ // Logging Configuration // ============================================================================ /** * Logging configuration */ interface LoggingConfig { readonly level: LogLevel; readonly format?: 'json' | 'text' | 'pretty'; readonly outputs?: readonly LogOutput[]; readonly filters?: readonly LogFilter[]; readonly sampling?: LogSamplingConfig; readonly redaction?: LogRedactionConfig; } /** * Log output */ interface LogOutput { readonly type: 'console' | 'file' | 'syslog' | 'http' | 'custom'; readonly enabled: boolean; readonly level?: LogLevel; readonly format?: 'json' | 'text'; readonly path?: string; // for file output readonly url?: string; // for http output readonly options?: Record; } /** * Log filter */ interface LogFilter { readonly type: 'include' | 'exclude'; readonly categories?: readonly string[]; readonly patterns?: readonly string[]; readonly minLevel?: LogLevel; } /** * Log sampling configuration */ interface LogSamplingConfig { readonly enabled: boolean; readonly rate?: number; // 0-1 readonly rules?: readonly SamplingRule[]; } /** * Sampling rule */ interface SamplingRule { readonly pattern?: string; readonly category?: string; readonly rate: number; // 0-1 } /** * Log redaction configuration */ interface LogRedactionConfig { readonly enabled: boolean; readonly patterns?: readonly string[]; // regex patterns readonly fields?: readonly string[]; // field names to redact readonly replacement?: string; } // ============================================================================ // Monitoring Configuration // ============================================================================ /** * Monitoring configuration */ interface MonitoringConfig { readonly enabled: boolean; readonly metrics?: MetricsConfig; readonly tracing?: TracingConfig; readonly alerts?: AlertsConfig; readonly health?: HealthCheckConfig; } /** * Metrics configuration */ interface MetricsConfig { readonly enabled: boolean; readonly provider?: 'prometheus' | 'statsd' | 'cloudwatch' | 'datadog' | 'custom'; readonly endpoint?: string; readonly interval?: number; // milliseconds readonly prefix?: string; readonly labels?: Record; } /** * Tracing configuration */ interface TracingConfig { readonly enabled: boolean; readonly provider?: 'jaeger' | 'zipkin' | 'datadog' | 'honeycomb' | 'custom'; readonly endpoint?: string; readonly serviceName?: string; readonly sampleRate?: number; // 0-1 } /** * Alerts configuration */ interface AlertsConfig { readonly enabled: boolean; readonly rules?: readonly AlertRule[]; readonly channels?: readonly AlertChannel[]; } /** * Alert rule */ interface AlertRule { readonly id: string; readonly name: string; readonly condition: AlertCondition; readonly severity: ErrorSeverity; readonly cooldown?: number; // milliseconds readonly channels?: readonly string[]; // channel IDs } /** * Alert condition */ interface AlertCondition { readonly metric: string; readonly operator: '>' | '<' | '>=' | '<=' | '==' | '!='; readonly threshold: number; readonly window?: number; // milliseconds } /** * Alert channel */ interface AlertChannel { readonly id: string; readonly type: 'email' | 'slack' | 'webhook' | 'pagerduty' | 'custom'; readonly enabled: boolean; readonly config: Record; } /** * Health check configuration */ interface HealthCheckConfig { readonly enabled: boolean; readonly endpoint?: string; readonly interval?: number; // milliseconds readonly checks?: readonly HealthCheck[]; } /** * Health check */ interface HealthCheck { readonly name: string; readonly type: 'http' | 'tcp' | 'custom'; readonly target: string; readonly timeout?: number; // milliseconds readonly critical?: boolean; } // ============================================================================ // Security Configuration // ============================================================================ /** * Security configuration */ interface SecurityConfig { readonly authentication?: AuthenticationConfig; readonly authorization?: AuthorizationConfig; readonly encryption?: EncryptionConfig; readonly rateLimit?: RateLimitConfig; readonly cors?: CORSConfig; readonly contentSecurity?: ContentSecurityConfig; } /** * Authorization configuration */ interface AuthorizationConfig { readonly enabled: boolean; readonly model?: 'rbac' | 'abac' | 'custom'; readonly policies?: readonly AuthorizationPolicy[]; readonly defaultDeny?: boolean; } /** * Authorization policy */ interface AuthorizationPolicy { readonly id: string; readonly resource: string; readonly actions: readonly string[]; readonly effect: 'allow' | 'deny'; readonly conditions?: readonly PolicyCondition[]; } /** * Policy condition */ interface PolicyCondition { readonly attribute: string; readonly operator: string; readonly value: JsonValue; } /** * Encryption configuration */ interface EncryptionConfig { readonly enabled: boolean; readonly algorithm?: 'aes-256-gcm' | 'chacha20-poly1305'; readonly keyManagement?: 'kms' | 'vault' | 'env' | 'custom'; readonly atRest?: boolean; readonly inTransit?: boolean; } /** * CORS configuration */ interface CORSConfig { readonly enabled: boolean; readonly origins?: readonly string[]; readonly methods?: readonly string[]; readonly headers?: readonly string[]; readonly credentials?: boolean; readonly maxAge?: number; // seconds } /** * Content security configuration */ interface ContentSecurityConfig { readonly piiDetection?: boolean; readonly jailbreakDetection?: boolean; readonly toxicityFiltering?: boolean; readonly contentFiltering?: ContentFilterConfig; } /** * Content filter configuration */ interface ContentFilterConfig { readonly enabled: boolean; readonly categories?: readonly ContentFilterCategory[]; readonly threshold?: 'low' | 'medium' | 'high'; readonly action?: 'block' | 'warn' | 'log'; } /** * Content filter category */ type ContentFilterCategory = 'hate' | 'violence' | 'sexual' | 'self-harm' | 'profanity'; // ============================================================================ // Performance Configuration // ============================================================================ /** * Performance configuration */ interface PerformanceConfig { readonly optimization?: OptimizationConfig; readonly concurrency?: ConcurrencyConfig; readonly timeout?: TimeoutConfig; readonly retry?: RetryConfig; } /** * Optimization configuration */ interface OptimizationConfig { readonly enabled: boolean; readonly caching?: boolean; readonly compression?: boolean; readonly minification?: boolean; readonly lazyLoading?: boolean; } /** * Concurrency configuration */ interface ConcurrencyConfig { readonly maxConcurrentRequests?: number; readonly queueSize?: number; readonly queueTimeout?: number; // milliseconds } // ============================================================================ // Storage Configuration // ============================================================================ /** * Storage configuration */ interface StorageConfig { readonly type: 'memory' | 'file' | 'database' | 's3' | 'custom'; readonly path?: string; readonly connectionString?: string; readonly options?: Record; } // ============================================================================ // Providers Configuration // ============================================================================ /** * Providers configuration */ interface ProvidersConfig { readonly openai?: ProviderConfig; readonly anthropic?: ProviderConfig; readonly google?: ProviderConfig; readonly cohere?: ProviderConfig; readonly custom?: Record; } // ============================================================================ // Features Configuration // ============================================================================ /** * Features configuration (feature flags) */ interface FeaturesConfig { readonly streaming?: boolean; readonly tools?: boolean; readonly agents?: boolean; readonly multimodal?: boolean; readonly vision?: boolean; readonly audio?: boolean; readonly codeExecution?: boolean; readonly reasoning?: boolean; readonly rlhf?: boolean; readonly [key: string]: boolean | undefined; } // ============================================================================ // Experimental Configuration // ============================================================================ /** * Experimental configuration */ interface ExperimentalConfig { readonly enabled: boolean; readonly features?: Record; readonly betaAccess?: boolean; readonly telemetry?: boolean; } export { type AIKitConfig, type AIKitError, type APIKeyError, type APIToolConfig, type AgentCommunicationError, type AgentDefaultsConfig, type AgentError, type AgentExecutionError, AgentId, type AgentNotFoundError, type AgentStateError, type AgentsConfig, type AggregateError, type AlertChannel, type AlertCondition, type AlertRule, type AlertsConfig, type AssertionError, AuthenticationConfig, type AuthenticationError, type AuthorizationConfig, type AuthorizationError, type AuthorizationPolicy, type BenchmarkConfig, type BenchmarkResult, type BenchmarkSummary, Brand, type CORSConfig, type CacheCondition, type CacheInvalidationConfig, type CacheInvalidationStrategy, type CachePoliciesConfig, type CachePolicy, type CacheStorageConfig, type CachedResponseMetadata, type CachingConfig, type CodeExecutionToolConfig, CollaborationConfig, type ComparisonCriterion, type CompletionChoice, type CompletionChunk, type CompletionResponse, type CompositeTool, type CompositionStrategy, type ConcurrencyConfig, type ConfigurationError, type ConnectionError, type ContentFilterCategory, type ContentFilterConfig, type ContentFilterError, type ContentSecurityConfig, type ContextLengthError, type DatabaseToolConfig, type DeprecationNotice, type Embedding, type EmbeddingResponse, type EncryptionConfig, type Environment, type ErrorCategory, type ErrorCode, type ErrorContext, type ErrorFactory, type ErrorFactoryOptions, type ErrorHandler, type ErrorMiddleware, type ErrorRecoveryOptions, type ErrorRecoveryStrategy, type ErrorReport, type ErrorReporter, type ErrorSeverity, type ErrorStatistics, type ErrorSummary, type ExperimentalConfig, type FallbackCondition, type FeaturesConfig, type FieldValidationError, type FileSystemToolConfig, type FineTuningConfig, type FineTuningHyperparameters, type FineTuningJob, type FineTuningMetrics, type FinishReason, type HTTPError, type HealthCheck, type HealthCheckConfig, type InternalError, type InvalidConfigError, JsonValue, LearningConfig, LoadBalancingConfig, type LogFilter, type LogLevel, type LogOutput, type LogProbs, type LogRedactionConfig, type LogSamplingConfig, type LoggingConfig, MemoryConfig, MessageId, type MetricsConfig, type MissingConfigError, type ModelAuthentication, type ModelCacheConfig, type ModelCapability, type ModelCategory, type ModelComparisonRequest, type ModelComparisonResult, type ModelConfig, type ModelCredentials, type ModelEndpoint, type ModelError, type ModelFallbackConfig, type ModelHealthStatus, ModelId, type ModelLifecycleStage, type ModelNotFoundError, type ModelOptimizationConfig, type ModelParameters, type ModelPerformanceMetrics, type ModelProvider, type ModelProviderInterface, type ModelRanking, type ModelRegistry, type ModelResponseError, type ModelResult, type ModelRouterConfig, type ModelRoutingConfig, type ModelSelectionCriteria, type ModelSelector, type ModelSize, type ModelUnavailableError, type ModelUsageStatistics, type ModelVersion, type ModelsConfig, type MonitoringConfig, type NetworkError, type NotImplementedError, type OptimizationConfig, type ParameterSchema, type ParameterType, type ParameterValidationError, type PerformanceConfig, type PlanningConfig, type PolicyCondition, type ProviderConfig, type ProvidersConfig, type QuotaExceededError, RateLimitConfig, type RateLimitError, type ResourceLimits, type ResponseFormat, Result, RetryConfig, type RoutingCondition, type RoutingRule, type RoutingStrategy, type SamplingRule, type SchemaValidationError, type SearchToolConfig, type SecurityConfig, type StorageConfig, type StreamAbortError, type StreamConnectionError, type StreamError, type StreamParseError, type StreamingConfig, type TimePeriod, TimeoutConfig, type TimeoutError, type TokenError, type Tool, type ToolBuilder, type ToolCacheConfig, type ToolCallResult, type ToolCategory, type ToolConfig, type ToolDefaultsConfig, type ToolError, ToolErrorCode, type ToolEvent, type ToolEventType, type ToolExample, type ToolExecutionConfig, type ToolExecutionContext, type ToolExecutionError, ToolExecutionErrorDetails, type ToolExecutionOptions, type ToolHandler, ToolId, type ToolNotFoundError, type ToolObserver, type ToolParameter, type ToolPerformanceMetrics, type ToolPermission, type ToolPermissionError, type ToolPipeline, type ToolPipelineStep, type ToolRegistry, type ToolRegistryConfig, type ToolRetryConfig, type ToolReturnSchema, type ToolSecurityConfig, type ToolStatus, type ToolTimeoutError, type ToolUsageStats, type ToolValidator, type ToolsConfig, type TracingConfig, type UsageBreakdown, UsageStats, type ValidationAggregateError, type ValidationError, ValidationFailure };