import { default as default_2 } from 'react'; import { JSX } from 'react/jsx-runtime'; import { ReactNode } from 'react'; import { ZodSchema } from 'zod'; export declare interface AIProvider { name: string; inference(prompt: string, options?: InferenceOptions): Promise; streamInference?(prompt: string, options?: InferenceOptions): AsyncIterable; } export declare interface AnthropicConfig extends CloudProviderConfig { /** Anthropic API version */ apiVersion?: string; } declare interface AttemptRecord { response: string; errors: ValidationError[]; prompt: string; } export declare interface AuditEntry { id: string; timestamp: number; from: MachineState; to: MachineState; event: string; payload?: unknown; } /** * Build a prompt with automatic context management */ export declare function buildManagedPrompt(systemPrompt: string, context: ContextMessage[], userMessage: string, maxTokens: number): string; /** * Builds a complete prompt for semantic state mutation */ export declare function buildPrompt({ schema, currentState, intent, context, }: PromptConfig): string; export declare interface CachedModelInfo { modelId: string; version: string; sha256: string; cachedAt: number; lastUsed: number; sizeBytes: number; } /** * Capability Check - Verify hardware before trusting local AI * * Addresses: Silent WebGPU Failure pre-mortem risk */ export declare interface CapabilityResult { /** WebGPU is available and working */ webgpu: boolean; /** WebGL2 fallback available */ webgl2: boolean; /** SharedArrayBuffer available (needed for some WASM) */ sharedArrayBuffer: boolean; /** Estimated VRAM in MB (0 if unknown) */ estimatedVRAM: number; /** Browser supports Web Workers */ webWorkers: boolean; /** Browser supports SharedWorker */ sharedWorkers: boolean; /** IndexedDB available for model caching */ indexedDB: boolean; /** Sanity inference test passed */ sanityTestPassed: boolean; /** Recommended inference mode */ recommendedMode: "local" | "cloud" | "hybrid"; /** Detailed capability scores */ scores: { gpu: number; memory: number; browser: number; overall: number; }; /** Any issues detected */ issues: string[]; } export declare interface CerebrasConfig { /** Cerebras API key (defaults to CEREBRAS_API_KEY env var) */ apiKey?: string; /** Model to use */ model?: string; /** Default inference options */ defaultOptions?: { temperature?: number; maxTokens?: number; }; } /** * Checks all capabilities needed for local AI inference */ export declare function checkCapabilities(): Promise; /** * Clears all Synapse data from the browser */ export declare function clearAllMemory(sources?: Partial): Promise<{ success: boolean; errors: string[]; }>; /** * Clear the Infer component cache */ export declare function clearInferCache(): void; /** * Clear all cached inference results */ export declare function clearInferenceCache(): void; /** * Clear the pipeline cache */ export declare function clearPipelineCache(): void; /** * Common configuration shared by all cloud providers */ export declare interface CloudProviderConfig { /** API key for authentication */ apiKey: string; /** Custom base URL (optional) */ baseUrl?: string; /** Model to use */ model?: string; /** Default inference options */ defaultOptions?: { temperature?: number; maxTokens?: number; }; } /** * Confidence-based gate component * * @example * ```tsx * * * * ``` */ export declare function ConfidenceGate({ confidence, threshold, pendingValue, onConfirm, onReject, children, renderConfirmation, showConfidenceIndicator, }: ConfidenceGateProps): ReactNode; export declare interface ConfidenceGateProps { /** Confidence score (0-1) */ confidence: number; /** Threshold for automatic acceptance */ threshold?: number; /** The pending change to confirm */ pendingValue: unknown; /** Called when user confirms */ onConfirm: () => void; /** Called when user rejects */ onReject: () => void; /** Render content for high confidence (auto-accepted) */ children: ReactNode; /** Render confirmation UI for low confidence */ renderConfirmation?: (props: ConfirmationRenderProps) => ReactNode; /** Show confidence indicator */ showConfidenceIndicator?: boolean; } export declare interface ConfirmationRenderProps { confidence: number; pendingValue: unknown; onConfirm: () => void; onReject: () => void; isDestructive: boolean; } export declare interface ContextConfig { /** Maximum context length in tokens */ maxTokens: number; /** Threshold to trigger compression (percentage of max) */ compressionThreshold?: number; /** Provider to use for summarization */ summarizationProvider?: AIProvider; /** Number of recent messages to preserve */ preserveRecent?: number; /** Called when compression occurs */ onCompress?: (original: number, compressed: number) => void; } export declare interface ContextMessage { role: "system" | "user" | "assistant"; content: string; timestamp?: number; tokens?: number; } export declare interface ContextState { messages: ContextMessage[]; totalTokens: number; compressedCount: number; systemPrompt?: string; } declare interface CorrectionConfig { maxRetries: number; onRetry?: (attempt: number, errors: ValidationError[]) => void; } export declare interface CorrectionResult { success: boolean; data: T | null; attempts: number; history: AttemptRecord[]; } /** * More accurate token counting using word/punctuation boundaries */ export declare function countTokensDetailed(text: string): { estimated: number; words: number; characters: number; }; export declare function createAnthropicProvider(config: AnthropicConfig): AIProvider; /** * Creates a Cerebras provider using the official SDK * * @example * ```ts * import { createCerebrasProvider } from '@mzhub/react'; * * const cerebras = createCerebrasProvider({ * apiKey: process.env.CEREBRAS_API_KEY, * model: 'llama3.1-70b' * }); * * const response = await cerebras.inference('Why is fast inference important?'); * ``` */ export declare function createCerebrasProvider(config?: CerebrasConfig): AIProvider; /** * Create a context manager for conversation history */ export declare function createContextManager(config: ContextConfig): { addMessage: (message: Omit) => void; setSystemPrompt: (prompt: string) => void; getMessages: () => ContextMessage[]; getContext: () => string; getState: () => ContextState; compress: () => Promise; clear: () => void; needsCompression: () => boolean; getTokenCount: () => number; getRemainingTokens: () => number; }; /** * Creates a download manager instance */ export declare function createDownloadManager(): DownloadManager; export declare function createGeminiProvider(config: GeminiConfig): AIProvider; /** * Creates a Groq provider using the official SDK * * @example * ```ts * import { createGroqProvider } from '@mzhub/react'; * * const groq = createGroqProvider({ * apiKey: process.env.GROQ_API_KEY, * model: 'llama-3.1-70b-versatile' * }); * * const response = await groq.inference('Explain quantum computing'); * ``` */ export declare function createGroqProvider(config?: GroqConfig): AIProvider; /** * Creates a hybrid provider that intelligently routes between cloud and local */ export declare function createHybridProvider(config: HybridProviderConfig): AIProvider & { getStatus: () => HybridProviderStatus; setLocalProvider: (provider: AIProvider) => void; setMode: (mode: InferenceMode) => void; }; /** * Mock provider for testing */ export declare function createMockProvider(responses: Record): AIProvider; export declare function createOpenAIProvider(config: OpenAIConfig): AIProvider; /** * Creates a prompt guard with default settings */ export declare function createPromptGuard(config?: PromptGuardConfig): PromptGuard; /** * Create a provider from a configuration object * * @example * ```ts * const provider = createProvider({ * type: 'anthropic', * apiKey: 'sk-ant-...', * model: 'claude-3-haiku-20240307' * }); * ``` */ export declare function createProvider(config: ProviderConfig): AIProvider; /** * Creates a rollback manager with default settings */ export declare function createRollbackManager(config?: RollbackManagerConfig): RollbackManager; /** * Creates a safe text renderer that prevents XSS */ export declare function createSafeRenderer(config?: SanitizerConfig): (content: string) => string; /** * Creates a secure inference function from proxy config */ export declare function createSecureInference(config: SecureProviderConfig): (prompt: string) => Promise; /** * Creates a local inference provider using Transformers.js */ export declare function createTransformersProvider(config: TransformersConfig): AIProvider & { isLoaded: () => boolean; preload: () => Promise; unload: () => void; }; /** * Creates a worker bridge with default settings */ export declare function createWorkerBridge(config: WorkerBridgeConfig): WorkerBridge; export declare type DispatchFn = (intent: string) => Promise; /** * Download manager for background model downloads */ export declare class DownloadManager { private activeDownloads; /** * Starts or resumes a model download */ download(modelId: string, url: string, expectedHash: string, options?: DownloadOptions): Promise; /** * Cancels an active download */ cancel(modelId: string): void; /** * Gets progress of active download */ getProgress(modelId: string): RuntimeDownloadProgress | null; /** * Loads model from cache */ loadFromCache(modelId: string): Promise; private combineChunks; private savePartialDownload; private loadPartialDownload; private clearPartialDownload; private saveToCache; } declare interface DownloadOptions { /** Called with download progress */ onProgress?: (progress: RuntimeDownloadProgress) => void; /** Called when download completes */ onComplete?: (modelId: string) => void; /** Called on error */ onError?: (error: Error) => void; /** Abort signal for cancellation */ signal?: AbortSignal; } declare interface DownloadProgress { modelId: string; bytesDownloaded: number; totalBytes: number; percent: number; estimatedTimeRemaining: number | null; } /** * Error factory functions for common scenarios */ export declare const Errors: { validationFailed: (response: string, errors: unknown[]) => SynapseError; inferenceTimeout: (modelId: string, timeoutMs: number) => SynapseError; modelError: (modelId: string, cause: Error) => SynapseError; networkError: (cause: Error) => SynapseError; capabilityUnsupported: (missing: string[]) => SynapseError; memoryPressure: (usedMB: number, limitMB: number) => SynapseError; securityViolation: (reason: string, intent: string) => SynapseError; }; /** * Escapes HTML entities to prevent injection */ export declare function escapeHtml(text: string): string; /** * Estimates available memory for model loading */ export declare function estimateAvailableMemory(): Promise<{ available: number; total: number; usageRatio: number; }>; /** * Estimates token count for a string * Uses the 4-char approximation (good enough for most use cases) * For accuracy, use tiktoken library separately */ export declare function estimateTokens(text: string): number; /** * Attempts to get valid output from an LLM, with automatic self-correction on failure */ export declare function executeWithCorrection({ prompt, schema, inference, config, }: ExecuteWithCorrectionParams): Promise>; declare interface ExecuteWithCorrectionParams { prompt: string; schema: ZodSchema; inference: (prompt: string) => Promise; config?: Partial; } /** * Extracts JSON from an LLM response that may be wrapped in markdown code blocks */ export declare function extractJson(response: string): string; /** * Fetches the latest model manifest from CDN */ export declare function fetchManifest(manifestUrl: string): Promise; export declare interface GeminiConfig extends CloudProviderConfig { /** Use v1beta for newer features */ useBeta?: boolean; } /** * Get list of available provider types */ export declare function getAvailableProviders(): ProviderType[]; /** * Gets storage usage for Synapse data */ export declare function getMemoryUsage(): Promise<{ total: number; breakdown: Record; }>; export declare interface GroqConfig { /** Groq API key (defaults to GROQ_API_KEY env var) */ apiKey?: string; /** Model to use */ model?: string; /** Default inference options */ defaultOptions?: { temperature?: number; maxTokens?: number; }; } export declare interface HybridProviderConfig { /** Cloud provider (required - this is always available) */ cloudProvider: AIProvider; /** Local provider (optional - created when model is ready) */ localProvider?: AIProvider; /** Threshold for simple vs complex tasks (token estimate) */ complexityThreshold?: number; /** Force a specific mode (overrides auto-detection) */ forceMode?: InferenceMode; /** Called when local model becomes ready */ onLocalReady?: () => void; /** Called with download progress */ onDownloadProgress?: (progress: DownloadProgress) => void; /** Called when mode changes */ onModeChange?: (mode: InferenceMode) => void; } export declare interface HybridProviderStatus { currentMode: InferenceMode; localAvailable: boolean; localDownloading: boolean; downloadProgress: DownloadProgress | null; capabilities: CapabilityResult | null; lastInferenceMode: "cloud" | "local" | null; stats: { cloudCalls: number; localCalls: number; localSavings: number; }; } /** * Declarative inference component * * @example * ```tsx * * {({ data, loading }) => ( * loading ? :

{data}

* )} *
* ``` */ export declare function Infer({ task, input, schema, children, fallback, errorFallback, dangerouslyDisableSanitization, cacheKey, refetchOnInputChange, immediate, stream, }: InferProps): ReactNode; export declare type InferenceMode = "cloud" | "local" | "hybrid"; /** * AI Provider Interface - Abstraction for different LLM backends */ export declare interface InferenceOptions { temperature?: number; maxTokens?: number; stream?: boolean; } export declare interface InferenceResponse { content: string; usage?: { promptTokens: number; completionTokens: number; totalTokens: number; }; finishReason?: string; } export declare interface InferProps { /** The task/prompt to run */ task: string; /** Input data to process */ input: string; /** Optional Zod schema for structured output */ schema?: ZodSchema; /** Render function for the result */ children: (result: InferRenderProps) => ReactNode; /** Fallback content while loading (SSR-safe) */ fallback?: ReactNode; /** Error fallback */ errorFallback?: (error: Error) => ReactNode; /** Disable automatic sanitization (DANGEROUS - only for trusted output) */ dangerouslyDisableSanitization?: boolean; /** Cache key for result caching */ cacheKey?: string; /** Refetch when input changes */ refetchOnInputChange?: boolean; /** Run on mount (default: true) */ immediate?: boolean; /** Enable streaming output */ stream?: boolean; } export declare interface InferRenderProps { /** The inference result */ data: T | null; /** Loading state */ loading: boolean; /** Error if inference failed */ error: Error | null; /** Whether result is from streaming */ isStreaming: boolean; /** Manually trigger inference */ refetch: () => Promise; } /** * Deletes cached model data */ export declare function invalidateCache(modelId: string): Promise; /** * Check if a provider type is registered */ export declare function isProviderAvailable(type: string): boolean; /** * Lists all cached models */ export declare function listCachedModels(): Promise; /** * State Machine - The 7-state lifecycle for semantic state mutations */ export declare type MachineState = "IDLE" | "OPTIMISTIC" | "GENERATING" | "VALIDATING" | "CORRECTING" | "GATING" | "SETTLED" | "REJECTED"; export declare interface ManifestValidation { valid: boolean; reason?: "version_mismatch" | "hash_mismatch" | "library_outdated" | "not_cached"; cachedVersion?: string; requiredVersion?: string; action?: "update" | "redownload" | "upgrade_library"; } export declare interface MemorySources { /** IndexedDB database names */ indexedDB: string[]; /** Cache API cache names */ caches: string[]; /** LocalStorage keys */ localStorage: string[]; /** SessionStorage keys */ sessionStorage: string[]; } /** * Model Manifest - Version management for cached models * * Addresses: Version Rot of Cached Models pre-mortem risk * * Features: * - Model versioning with SHA-256 hashes * - Automatic cache invalidation on version mismatch * - Migration support for prompt syntax changes */ export declare interface ModelManifest { /** Unique model identifier */ modelId: string; /** Semantic version */ version: string; /** SHA-256 hash of model weights */ sha256: string; /** Minimum library version required */ minLibraryVersion: string; /** Prompt syntax version */ promptSyntax: "v1" | "v2"; /** URL to download model from */ downloadUrl: string; /** Total size in bytes */ sizeBytes: number; /** Model capabilities */ capabilities: { maxTokens: number; supportsStreaming: boolean; supportsJson: boolean; }; /** When this manifest was published */ publishedAt: string; } /** * OpenAI-compatible provider */ export declare interface OpenAIConfig { apiKey: string; baseUrl?: string; model?: string; defaultOptions?: InferenceOptions; } /** * Preload a model in the background */ export declare function preloadModel(modelId: string, task?: TransformersTask, onProgress?: (progress: number) => void): Promise; /** * Pre-populate the Infer cache (useful for SSR) */ export declare function primeInferCache(key: string, value: T): void; export declare interface PromptConfig { schema: ZodSchema; currentState: T; intent: string; context?: string; } export declare class PromptGuard { private config; private violations; private allPatterns; constructor(config?: PromptGuardConfig); /** * Validates an intent before sending to AI * Throws SynapseError if blocked */ validateIntent(intent: string): void; /** * Validates that AI output doesn't modify sensitive fields */ validateStateChange(oldState: T, newState: T): void; /** * Sanitizes AI output by removing sensitive fields that shouldn't have changed */ sanitizeOutput(oldState: T, newState: T): T; /** * Gets the violation history */ getViolations(): SecurityViolation[]; /** * Clears violation history */ clearViolations(): void; /** * Adds sensitive fields to protect */ addSensitiveFields(fields: string[]): void; private recordViolation; private getNestedValue; private setNestedValue; } /** * Prompt Guard - Security layer for AI inputs * * Addresses: System Prompt Leak pre-mortem risk * * Rules: * 1. Client-side AI is for augmentation, not validation * 2. Detect and block prompt injection attempts * 3. Protect sensitive fields from AI modification * 4. Audit all AI-generated state changes */ export declare interface PromptGuardConfig { /** Fields that AI cannot modify directly */ sensitiveFields?: string[]; /** Custom injection patterns to detect */ customPatterns?: RegExp[]; /** Enable strict mode (block more aggressively) */ strictMode?: boolean; /** Called when a security violation is detected */ onViolation?: (violation: SecurityViolation) => void; } export declare interface ProviderConfig { type: ProviderType; apiKey?: string; baseUrl?: string; model?: string; [key: string]: unknown; } declare type ProviderFactory = (config: unknown) => AIProvider; /** * Provider registry for dynamic provider creation */ export declare type ProviderType = "openai" | "anthropic" | "gemini" | "groq" | "cerebras" | "transformers" | "mock"; /** * API Key Protection - Prevents client-side key exposure * * Addresses: API Key Exposure risk * * Rules: * 1. Never allow raw API keys in client-side config * 2. Require a proxy callback function instead * 3. Validate that keys aren't accidentally exposed */ export declare interface ProxyConfig { /** URL of your backend proxy endpoint */ proxyUrl: string; /** Optional custom headers */ headers?: Record; /** Optional request transformer */ transformRequest?: (prompt: string) => unknown; /** Optional response transformer */ transformResponse?: (response: unknown) => string; } /** * Quick check for obvious injection attempts * Returns true if the intent appears safe */ export declare function quickSafetyCheck(intent: string): boolean; /** * Registers handlers for browser clear-data events * Note: This is best-effort as browsers don't provide a reliable event */ declare function registerClearDataHandler(onClear: () => void): () => void; /** * Register a custom provider factory * * @example * ```ts * registerProvider('my-custom', (config) => ({ * name: 'my-custom', * inference: async (prompt) => ({ content: '...' }) * })); * ``` */ export declare function registerProvider(type: string, factory: ProviderFactory): void; export declare class RollbackManager { private snapshots; private maxSnapshots; private onRollback?; constructor(config?: RollbackManagerConfig); /** * Takes a snapshot of the current state before a dispatch */ snapshot(data: T, intent: string): string; /** * Gets the last known good state (most recent snapshot) */ getLastGoodState(): T | null; /** * Rolls back to a specific snapshot by ID */ rollbackTo(snapshotId: string): T | null; /** * Rolls back by N steps */ rollbackSteps(steps: number): T | null; /** * Performs automatic rollback and notifies */ autoRollback(currentState: T, reason: string): T | null; /** * Gets the full snapshot history */ getHistory(): StateSnapshot[]; /** * Clears all snapshots */ clear(): void; /** * Gets the number of snapshots available for rollback */ get availableRollbacks(): number; private deepClone; } declare interface RollbackManagerConfig { /** Maximum number of snapshots to keep */ maxSnapshots?: number; /** Called when a rollback occurs */ onRollback?: (from: unknown, to: unknown, reason: string) => void; } /** * Runs a simple sanity test to verify the AI model produces valid output * This catches driver bugs that cause garbage/NaN output */ export declare function runSanityTest(inference: (prompt: string) => Promise): Promise<{ passed: boolean; details: string; }>; /** * Download Manager - Background model downloading with resume support * * Addresses: 2GB Bounce Rate Wall pre-mortem risk * * Features: * - Resumable downloads with Range headers * - Progress callbacks * - Integrity verification (SHA-256) * - IndexedDB + Cache API storage */ export declare interface RuntimeDownloadProgress { modelId: string; bytesDownloaded: number; totalBytes: number; percent: number; speed: number; estimatedTimeRemaining: number | null; } /** * Sanitizes AI output by removing dangerous patterns */ export declare function sanitizeOutput(content: string, config?: SanitizerConfig): { sanitized: string; threats: string[]; }; /** * Output Sanitizer - Strips dangerous content from AI output * * Addresses: * - Indirect Prompt Injection (webpage trap) * - Data Exfiltration via image/script tags * * Rules: * 1. Never trust AI output to not contain HTML/scripts * 2. Block all external resource loading from AI content * 3. Whitelist only safe content patterns */ export declare interface SanitizerConfig { /** Allow safe inline formatting (bold, italic, etc) */ allowBasicFormatting?: boolean; /** Allow code blocks */ allowCodeBlocks?: boolean; /** Allow internal links (same origin) */ allowInternalLinks?: boolean; /** Custom patterns to strip */ customPatterns?: RegExp[]; /** Called when dangerous content is detected */ onDangerousContent?: (type: string, content: string) => void; } export declare interface SecureProviderConfig { /** Use a proxy endpoint (recommended) */ proxy?: ProxyConfig; /** Or provide a custom inference function */ customInference?: (prompt: string) => Promise; } /** * Security disclaimer for documentation */ export declare const SECURITY_DISCLAIMER = "\n\u26A0\uFE0F SYNAPSE SECURITY NOTICE \u26A0\uFE0F\n\n1. NEVER expose API keys in client-side code\n2. Always use a proxy endpoint for paid AI APIs\n3. AI-generated content is NOT sanitized by default\n4. Use sanitizeOutput() before rendering AI content as HTML\n5. Do NOT use useSemanticState for financial, medical, or safety-critical logic\n\nThe Synapse authors are NOT liable for:\n- Data breaches from exposed API keys\n- XSS attacks from unsanitized AI output\n- Incorrect AI-generated advice or decisions\n- Any financial, legal, or personal damages\n\nSee: https://synapse.dev/docs/security\n"; export declare interface SecurityViolation { type: "injection" | "sensitive_access" | "blocked_pattern"; intent: string; pattern?: string; field?: string; timestamp: number; } export declare interface SemanticStateConfig { /** Zod schema defining the state structure */ schema: ZodSchema; /** Initial state value */ initialState: T; /** Context/persona for the AI (e.g., "You are a task manager...") */ context?: string; /** Override confidence threshold for this state */ confidenceThreshold?: number; /** Callback when state changes */ onChange?: (newState: T, oldState: T) => void; /** Callback when gating is triggered (return true to accept, false to reject) */ onGate?: (newState: T, oldState: T, confidence: number) => Promise; } export declare interface SemanticStateMetadata { /** Current state machine state */ status: MachineState; /** Error if in REJECTED state */ error: Error | null; /** Current intent being processed */ currentIntent: string | null; /** Number of correction retries */ retryCount: number; /** Confidence score of last change */ confidence: number; /** Whether a change is pending user confirmation */ pendingConfirmation: boolean; /** Pending state awaiting confirmation */ pendingState: unknown | null; /** Confirm pending change */ confirmChange: () => void; /** Reject pending change */ rejectChange: () => void; /** Full audit history */ history: AuditEntry[]; /** Reset error state to IDLE */ reset: () => void; } export declare interface SSRInferenceConfig { /** The task/prompt to run */ task: string; /** Input data to process */ input: string; /** Optional Zod schema for structured output */ schema?: ZodSchema; /** Fallback value for SSR */ fallback?: unknown; /** Sanitize output (default: true) */ sanitize?: boolean; } export declare interface SSRInferenceReturn { /** Inference result */ data: T | null; /** Loading state */ loading: boolean; /** Error if any */ error: Error | null; /** Whether hydration is complete */ hydrated: boolean; /** Trigger inference manually */ run: () => Promise; } export declare interface SSRSemanticStateConfig { /** Zod schema defining the state structure */ schema: ZodSchema; /** Initial state value (used for SSR) */ initialState: T; /** Context/persona for the AI */ context?: string; /** Confidence threshold */ confidenceThreshold?: number; /** Initial intent to run on mount (client-only) */ initialIntent?: string; } export declare interface SSRSemanticStateReturn { /** Current state */ state: T; /** Dispatch an intent */ dispatch: (intent: string) => Promise; /** Whether currently loading */ loading: boolean; /** Error if any */ error: Error | null; /** Whether hydration is complete */ hydrated: boolean; /** Whether running on server */ isServer: boolean; } export declare interface StateContext { data: T; optimisticData: T | null; currentIntent: string | null; error: Error | null; retryCount: number; confidence: number; history: AuditEntry[]; } /** * Rollback Manager - Automatic state recovery on failure * * Addresses: Enhanced Firewall pre-mortem risk * * Guarantees: * - State is snapshotted before each dispatch * - Automatic rollback on validation failure * - Configurable history depth */ export declare interface StateSnapshot { id: string; timestamp: number; data: T; intent: string; } /** * Animated streaming text component * * @example * ```tsx * * ``` */ export declare function StreamingText({ text, isStreaming, typingSpeed, cursor, onComplete, className, as: Component, dangerouslyDisableSanitization, }: StreamingTextProps): ReactNode; export declare interface StreamingTextProps { /** The text to display (can be partial during streaming) */ text: string; /** Whether currently streaming */ isStreaming?: boolean; /** Typing speed in ms per character (0 = instant) */ typingSpeed?: number; /** Custom cursor element */ cursor?: ReactNode; /** Called when animation completes */ onComplete?: () => void; className?: string; as?: default_2.ElementType; /** Disable sanitization (DANGEROUS) */ dangerouslyDisableSanitization?: boolean; } export declare interface SynapseConfig { /** OpenAI API key or compatible provider key */ apiKey?: string; /** Base URL for the API (default: OpenAI) */ baseUrl?: string; /** Model to use (default: gpt-4o-mini) */ model?: string; /** Default temperature for inference */ temperature?: number; /** Maximum tokens for responses */ maxTokens?: number; /** Confidence threshold for automatic acceptance (0-1) */ confidenceThreshold?: number; /** Maximum retry attempts for self-correction */ maxRetries?: number; /** Enable debug logging */ debug?: boolean; /** Custom AI provider (overrides apiKey/baseUrl/model) */ provider?: AIProvider; } declare interface SynapseContextValue { config: Required> & { apiKey?: string; baseUrl?: string; model?: string; }; provider: AIProvider; log: (...args: unknown[]) => void; } export declare class SynapseError extends Error { readonly code: SynapseErrorCode; readonly suggestion: string; readonly debugInfo: SynapseErrorDebugInfo; readonly recoverable: boolean; readonly originalCause?: Error; constructor(code: SynapseErrorCode, message: string, options?: { suggestion?: string; debugInfo?: Partial; recoverable?: boolean; cause?: Error; }); private getDefaultSuggestion; private isRecoverableByDefault; toJSON(): { name: string; code: SynapseErrorCode; message: string; suggestion: string; recoverable: boolean; debugInfo: SynapseErrorDebugInfo; }; } /** * Synapse Error - Structured errors with actionable suggestions */ export declare type SynapseErrorCode = "VALIDATION_FAILED" | "INFERENCE_TIMEOUT" | "MODEL_ERROR" | "NETWORK_ERROR" | "CAPABILITY_UNSUPPORTED" | "MEMORY_PRESSURE" | "SECURITY_VIOLATION"; export declare interface SynapseErrorDebugInfo { prompt?: string; response?: string; validationErrors?: unknown[]; modelId?: string; timestamp: number; } /** * Synapse memory API - convenience wrapper */ export declare const SynapseMemory: { clear: typeof clearAllMemory; getUsage: typeof getMemoryUsage; onClear: typeof registerClearDataHandler; }; export declare function SynapseProvider({ config, children }: SynapseProviderProps): JSX.Element; export declare interface SynapseProviderProps { config: SynapseConfig; children: ReactNode; } export declare interface TransformersConfig { /** Model ID from Hugging Face (e.g., 'Xenova/gpt2', 'Xenova/distilgpt2') */ modelId: string; /** Task type */ task?: TransformersTask; /** Use WebGPU acceleration if available */ useWebGPU?: boolean; /** Cache models locally */ cacheModels?: boolean; /** Called when model loading starts */ onLoadStart?: () => void; /** Called with loading progress */ onLoadProgress?: (progress: number) => void; /** Called when model is ready */ onLoadComplete?: () => void; /** Custom quantization (e.g., 'q4', 'q8') */ quantization?: string; } export declare type TransformersTask = "text-generation" | "text2text-generation" | "summarization" | "translation"; /** * Truncate context to fit within token limit (simple fallback) */ export declare function truncateContext(messages: ContextMessage[], maxTokens: number, preserveRecent?: number): ContextMessage[]; /** * Hook for manual confidence gating */ export declare function useConfidenceGate(threshold?: number): { gate: (value: T, confidence: number) => Promise<{ accepted: boolean; value: T; }>; pending: { value: unknown; confidence: number; confirm: () => void; reject: () => void; } | null; }; /** * Check if component has hydrated (client-side) */ export declare function useHydrated(): boolean; export declare function useInference(options: UseInferenceOptions): UseInferenceResult; export declare interface UseInferenceOptions { /** The task/prompt to run */ task: string; /** Input data to process */ input: string; /** Optional Zod schema for structured output */ schema?: ZodSchema; /** Run immediately on mount */ immediate?: boolean; /** Cache key (same key = cached result) */ cacheKey?: string; /** Refetch when input changes */ refetchOnInputChange?: boolean; } export declare interface UseInferenceResult { /** The inference result */ data: T | null; /** Loading state */ loading: boolean; /** Error if inference failed */ error: Error | null; /** Manually trigger inference */ refetch: () => Promise; /** Clear the result */ clear: () => void; } /** * Check if we're on the server (SSR) */ export declare function useIsServer(): boolean; /** * The main semantic state hook */ export declare function useSemanticState(config: SemanticStateConfig): UseSemanticStateReturn; export declare type UseSemanticStateReturn = [T, DispatchFn, SemanticStateMetadata]; /** * SSR-safe inference hook */ export declare function useSSRInference(config: SSRInferenceConfig): SSRInferenceReturn; /** * SSR-safe semantic state hook * * - On server: Returns initialState, never runs AI * - On client: Hydrates with initialState first, then runs AI * * @example * ```tsx * function TaskList() { * const { state, dispatch, loading, hydrated } = useSSRSemanticState({ * schema: TodoSchema, * initialState: { items: [] }, * initialIntent: 'Load default tasks' // Runs after hydration * }); * * if (!hydrated) return ; * // ... * } * ``` */ export declare function useSSRSemanticState(config: SSRSemanticStateConfig): SSRSemanticStateReturn; /** * Hook for streaming text with sanitization */ export declare function useStreamingText(text: string, isStreaming: boolean, options?: { sanitize?: boolean; }): { displayedText: string; isComplete: boolean; }; /** * Hook to check if Synapse is configured */ export declare function useSynapseConfig(): { isConfigured: boolean; config: (Required> & { apiKey?: string; baseUrl?: string; model?: string; }) | undefined; }; export declare function useSynapseContext(): SynapseContextValue; /** * Validates cached model against manifest */ export declare function validateCachedModel(manifest: ModelManifest): Promise; /** * Validates that a value doesn't look like an API key * Throws if it appears to be an exposed key */ export declare function validateNotApiKey(value: string, fieldName: string): void; /** * Full validation pipeline: extract JSON, parse, validate against schema */ export declare function validateResponse(response: string, schema: ZodSchema): ValidationResult; /** * Validates that content is safe for rendering * Returns true if safe, throws if dangerous */ export declare function validateSafeContent(content: string): boolean; export declare interface ValidationError { path: string; message: string; expected: string; received: unknown; } export declare interface ValidationResult { success: boolean; data: T | null; errors: ValidationError[]; rawJson: string; } export declare class WorkerBridge { private worker; private port; private pendingRequests; private config; private broadcast; private healthy; private lastHealthCheck; constructor(config: WorkerBridgeConfig); /** * Initializes the worker connection */ connect(): Promise; /** * Sends a request to the worker */ send(type: WorkerMessage["type"], payload: unknown): Promise; /** * Performs inference through the worker */ inference(prompt: string): Promise; /** * Checks worker health */ healthCheck(): Promise; /** * Disconnects from the worker */ disconnect(): void; /** * Gets current health status */ isHealthy(): boolean; private handleMessage; private handleBroadcast; private setHealthy; private startMemoryMonitoring; } declare interface WorkerBridgeConfig { /** Path to the worker script */ workerUrl: string; /** Use SharedWorker if available */ useSharedWorker?: boolean; /** Memory pressure threshold (0-1) */ memoryPressureThreshold?: number; /** Timeout for inference requests (ms) */ inferenceTimeout?: number; /** Called when memory pressure is detected */ onMemoryPressure?: (usageRatio: number) => void; /** Called when worker health changes */ onHealthChange?: (healthy: boolean) => void; } /** * Worker Bridge - Main thread communication with SharedWorker * * Addresses: Tab Death (OOM) and JSON.parse Bottleneck pre-mortem risks * * Features: * - SharedWorker for single model instance across tabs * - Zero-copy transfer for large payloads * - Memory pressure detection * - BroadcastChannel for multi-tab sync */ declare interface WorkerMessage { id: string; type: "inference" | "status" | "load_model" | "unload_model"; payload: unknown; } /** * Converts a Zod schema to a human-readable TypeScript-like description */ export declare function zodToDescription(schema: ZodSchema): string; export { }