UNPKG

@neuroequality/neuroadapt-ai

Version:

AI-powered accessibility personalization for neurodivergent users

1,566 lines 91.1 kB
import { EventEmitter as y } from "eventemitter3"; import { P as I } from "./engine-BGE0wXCL.js"; import { B as O } from "./behavior-analytics-Dfx-HuYy.js"; import { C as H } from "./content-adapter-CwBp76TE.js"; import { B, C as F, a as V, O as W } from "./ollama-provider-AUKt-Rtf.js"; class v { constructor(e) { this.config = e, this.currentModel = e.model || this.getDefaultModel(); } getModel() { return this.currentModel; } setModel(e) { if (!this.models.includes(e)) throw new Error(`Model ${e} is not supported by ${this.name}`); this.currentModel = e; } async retry(e, t = this.config.retryAttempts || 3, i = this.config.retryDelay || 1e3) { let s; for (let a = 1; a <= t; a++) try { return await e(); } catch (n) { if (s = n, a === t) throw s; if (this.isRetryableError(n)) await this.sleep(i * Math.pow(2, a - 1)); else throw s; } throw s; } isRetryableError(e) { if (e instanceof Error) { const t = e.message.toLowerCase(); return t.includes("timeout") || t.includes("rate limit") || t.includes("503") || t.includes("502") || t.includes("500"); } return !1; } sleep(e) { return new Promise((t) => setTimeout(t, e)); } formatMessages(e) { return e.map((t) => ({ role: t.role, content: t.content })); } createAbortController(e, t) { const i = new AbortController(); return e && e.addEventListener("abort", () => i.abort()), t && setTimeout(() => i.abort(), t), i; } } class b extends v { // Will be dynamically imported constructor(e) { super(e), this.initializeOpenAI(); } get name() { return "OpenAI"; } get models() { return [ "gpt-4", "gpt-4-turbo", "gpt-4-turbo-preview", "gpt-3.5-turbo", "gpt-3.5-turbo-16k" ]; } getDefaultModel() { return "gpt-4-turbo-preview"; } async complete(e, t = {}) { if (!this.openai) throw new Error("OpenAI client not initialized. Make sure to install the openai package."); return this.retry(async () => { const i = this.createAbortController(t.abortSignal, this.config.timeout), s = await this.openai.chat.completions.create({ model: this.currentModel, messages: this.formatMessages(e), max_tokens: t.maxTokens, temperature: t.temperature, top_p: t.topP, stop: t.stop, stream: !1 }, { signal: i.signal }); return { content: s.choices[0]?.message?.content || "", usage: { promptTokens: s.usage?.prompt_tokens || 0, completionTokens: s.usage?.completion_tokens || 0, totalTokens: s.usage?.total_tokens || 0 }, finishReason: s.choices[0]?.finish_reason, metadata: { model: s.model, created: s.created } }; }); } async *stream(e, t = {}) { if (!this.openai) throw new Error("OpenAI client not initialized. Make sure to install the openai package."); const i = this.createAbortController(t.abortSignal, this.config.timeout), s = await this.openai.chat.completions.create({ model: this.currentModel, messages: this.formatMessages(e), max_tokens: t.maxTokens, temperature: t.temperature, top_p: t.topP, stop: t.stop, stream: !0 }, { signal: i.signal }); for await (const a of s) { const n = a.choices[0]?.delta?.content || "", r = a.choices[0]?.finish_reason !== null; if (yield { delta: n, done: r, usage: a.usage ? { promptTokens: a.usage.prompt_tokens || 0, completionTokens: a.usage.completion_tokens || 0, totalTokens: a.usage.total_tokens || 0 } : void 0 }, r) break; } } async isAvailable() { try { return this.openai ? (await this.openai.models.list(), !0) : !1; } catch { return !1; } } async initializeOpenAI() { try { const { default: e } = await import("openai"); this.openai = new e({ apiKey: this.config.apiKey, baseURL: this.config.baseURL, organization: this.config.organization }); } catch { console.warn("OpenAI package not found. Install it to use OpenAI adapter."); } } } class M extends v { // Will be dynamically imported constructor(e) { super(e), this.initializeAnthropic(); } get name() { return "Claude"; } get models() { return [ "claude-3-5-sonnet-20241022", "claude-3-5-haiku-20241022", "claude-3-opus-20240229", "claude-3-sonnet-20240229", "claude-3-haiku-20240307" ]; } getDefaultModel() { return "claude-3-5-sonnet-20241022"; } async complete(e, t = {}) { if (!this.anthropic) throw new Error("Anthropic SDK not initialized. Make sure to install @anthropic-ai/sdk package."); return this.retry(async () => { const { system: i, messages: s } = this.formatClaudeMessages(e), a = await this.anthropic.messages.create({ model: this.currentModel, max_tokens: t.maxTokens || 4096, temperature: t.temperature, top_p: t.topP, stop_sequences: t.stop, system: i, messages: s, stream: !1 }); return { content: a.content[0]?.text || "", usage: { promptTokens: a.usage?.input_tokens || 0, completionTokens: a.usage?.output_tokens || 0, totalTokens: (a.usage?.input_tokens || 0) + (a.usage?.output_tokens || 0) }, finishReason: a.stop_reason, metadata: { model: a.model, role: a.role } }; }); } async *stream(e, t = {}) { if (!this.anthropic) throw new Error("Anthropic SDK not initialized. Make sure to install @anthropic-ai/sdk package."); const { system: i, messages: s } = this.formatClaudeMessages(e), a = await this.anthropic.messages.create({ model: this.currentModel, max_tokens: t.maxTokens || 4096, temperature: t.temperature, top_p: t.topP, stop_sequences: t.stop, system: i, messages: s, stream: !0 }); for await (const n of a) if (n.type === "content_block_delta") yield { delta: n.delta?.text || "", done: !1 }; else if (n.type === "message_stop") { yield { delta: "", done: !0, usage: n.message?.usage ? { promptTokens: n.message.usage.input_tokens || 0, completionTokens: n.message.usage.output_tokens || 0, totalTokens: (n.message.usage.input_tokens || 0) + (n.message.usage.output_tokens || 0) } : void 0 }; break; } } async isAvailable() { try { return this.anthropic ? (await this.anthropic.messages.create({ model: this.currentModel, max_tokens: 1, messages: [{ role: "user", content: "test" }] }), !0) : !1; } catch { return !1; } } formatClaudeMessages(e) { let t; const i = []; for (const s of e) s.role === "system" ? t = s.content : i.push({ role: s.role, content: s.content }); return { system: t, messages: i }; } async initializeAnthropic() { try { const { default: e } = await import("./index-DzuMHatY.js"); this.anthropic = new e({ apiKey: this.config.apiKey, baseURL: this.config.baseURL }); } catch { console.warn("Anthropic SDK not found. Install @anthropic-ai/sdk to use Claude adapter."); } } } class S extends v { constructor(e) { super(e), this.baseURL = e.baseURL || "http://localhost:11434"; } get name() { return "Ollama"; } get models() { return [ "deepseek-r1:32b", "llama3.2:3b", "llama3.2:1b", "phi3:mini", "mistral:7b", "codellama:7b", "gemma2:2b" ]; } getDefaultModel() { return "deepseek-r1:32b"; } async complete(e, t = {}) { return this.retry(async () => { const i = this.createAbortController(t.abortSignal, this.config.timeout), s = await fetch(`${this.baseURL}/api/chat`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ model: this.currentModel, messages: this.formatMessages(e), stream: !1, options: { temperature: t.temperature, top_p: t.topP, stop: t.stop, num_predict: t.maxTokens } }), signal: i.signal }); if (!s.ok) throw new Error(`Ollama API error: ${s.status} ${s.statusText}`); const a = await s.json(); return { content: a.message?.content || "", usage: { promptTokens: a.prompt_eval_count || 0, completionTokens: a.eval_count || 0, totalTokens: (a.prompt_eval_count || 0) + (a.eval_count || 0) }, finishReason: a.done ? "stop" : "length", metadata: { model: a.model, created_at: a.created_at, total_duration: a.total_duration, load_duration: a.load_duration, prompt_eval_duration: a.prompt_eval_duration, eval_duration: a.eval_duration } }; }); } async *stream(e, t = {}) { const i = this.createAbortController(t.abortSignal, this.config.timeout), s = await fetch(`${this.baseURL}/api/chat`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ model: this.currentModel, messages: this.formatMessages(e), stream: !0, options: { temperature: t.temperature, top_p: t.topP, stop: t.stop, num_predict: t.maxTokens } }), signal: i.signal }); if (!s.ok) throw new Error(`Ollama API error: ${s.status} ${s.statusText}`); const a = s.body?.getReader(); if (!a) throw new Error("No response body"); const n = new TextDecoder(); let r = ""; try { for (; ; ) { const { done: c, value: o } = await a.read(); if (c) break; r += n.decode(o, { stream: !0 }); const h = r.split(` `); r = h.pop() || ""; for (const m of h) if (m.trim()) try { const l = JSON.parse(m), u = l.message?.content || "", d = l.done || !1; if (yield { delta: u, done: d, usage: d ? { promptTokens: l.prompt_eval_count || 0, completionTokens: l.eval_count || 0, totalTokens: (l.prompt_eval_count || 0) + (l.eval_count || 0) } : void 0 }, d) return; } catch { console.warn("Failed to parse Ollama chunk:", m); } } } finally { a.releaseLock(); } } async isAvailable() { try { return (await fetch(`${this.baseURL}/api/tags`, { method: "GET", signal: AbortSignal.timeout(5e3) })).ok; } catch { return !1; } } async getAvailableModels() { try { const e = await fetch(`${this.baseURL}/api/tags`); if (!e.ok) throw new Error("Failed to fetch models"); return (await e.json()).models?.map((i) => i.name) || []; } catch (e) { return console.warn("Failed to fetch available models from Ollama:", e), this.models; } } async pullModel(e) { const t = await fetch(`${this.baseURL}/api/pull`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: e }) }); if (!t.ok) throw new Error(`Failed to pull model ${e}: ${t.statusText}`); const i = t.body?.getReader(); if (!i) return; const s = new TextDecoder(); try { for (; ; ) { const { done: a, value: n } = await i.read(); if (a) break; const r = s.decode(n); console.log("Pull progress:", r); } } finally { i.releaseLock(); } } } class k extends y { constructor(e, t = {}) { super(), this.undoHistory = [], this.currentStep = 0, this.cache = /* @__PURE__ */ new Map(), this.adapter = e, this.config = this.mergeDefaultConfig(t); } async complete(e, t = {}) { this.emit("response:start", { prompt: e }); try { const i = this.prepareMessages(e), s = this.getCacheKey(i); if (this.config.consistencyLevel === "high" && this.cache.has(s)) { const r = this.cache.get(s); return this.emit("response:complete", { response: r }), r; } const a = this.enhanceOptions(t), n = await this.adapter.complete(i, a); return this.config.consistencyLevel !== "low" && this.cache.set(s, n), this.config.allowUndo && this.addToUndoHistory(e, n), await this.applyPacing(), this.emit("response:complete", { response: n }), n; } catch (i) { throw this.emit("response:error", { error: i }), i; } } async *stream(e, t = {}) { if (!this.adapter.stream) throw new Error(`${this.adapter.name} adapter does not support streaming`); this.emit("response:start", { prompt: e }); try { const i = this.prepareMessages(e), s = this.enhanceOptions(t); let a = ""; const n = Date.now(); for await (const r of this.adapter.stream(i, s)) if (a += r.delta, this.emit("response:chunk", { chunk: r }), yield r, r.done) { const c = { content: a, usage: r.usage, finishReason: "stop", metadata: { streamDuration: Date.now() - n } }; this.config.allowUndo && this.addToUndoHistory(e, c), this.emit("response:complete", { response: c }); break; } } catch (i) { throw this.emit("response:error", { error: i }), i; } } updateConfig(e) { const t = { ...this.config }; this.config = { ...this.config, ...e }, e.consistencyLevel && e.consistencyLevel !== t.consistencyLevel && this.cache.clear(), this.emit("config:changed", { config: e }); } updateFromCognitivePreferences(e) { const t = {}; if (e.readingSpeed !== void 0) { const i = { slow: "slow", medium: "normal", fast: "quick" }; t.pacing = i[e.readingSpeed]; } if (e.explanationLevel !== void 0) { const i = { simple: "simple", moderate: "moderate", detailed: "detailed" }; t.explanationLevel = i[e.explanationLevel]; } if (e.processingPace !== void 0) { const i = { relaxed: "high", standard: "moderate", quick: "low" }; t.consistencyLevel = i[e.processingPace]; } this.updateConfig(t); } undo() { if (!this.config.allowUndo || this.undoHistory.length === 0) return null; if (this.currentStep > 0) { this.currentStep--; const e = this.undoHistory[this.currentStep]; return this.emit("undo:performed", { step: this.currentStep, state: e }), e; } return null; } redo() { if (!this.config.allowUndo || this.currentStep >= this.undoHistory.length - 1) return null; this.currentStep++; const e = this.undoHistory[this.currentStep]; return this.emit("undo:performed", { step: this.currentStep, state: e }), e; } canUndo() { return this.config.allowUndo && this.currentStep > 0; } canRedo() { return this.config.allowUndo && this.currentStep < this.undoHistory.length - 1; } getUndoHistory() { return [...this.undoHistory]; } clearUndoHistory() { this.undoHistory = [], this.currentStep = 0; } clearCache() { this.cache.clear(); } getConfig() { return { ...this.config }; } prepareMessages(e) { const t = this.createSystemPrompt(), i = []; return t && i.push({ role: "system", content: t, timestamp: Date.now() }), i.push({ role: "user", content: e, timestamp: Date.now() }), i; } createSystemPrompt() { const e = [], t = { "calm-supportive": "Respond in a calm, supportive manner. Use gentle language and provide reassurance.", encouraging: "Be encouraging and positive. Focus on possibilities and strengths.", neutral: "Maintain a neutral, professional tone. Be clear and objective.", clinical: "Use precise, clinical language. Be factual and methodical.", friendly: "Be warm and friendly. Use conversational language while remaining helpful." }; e.push(t[this.config.tone]); const i = { simple: "Use simple language and basic concepts. Avoid jargon and complex terms.", moderate: "Provide balanced explanations with some detail. Use accessible language.", detailed: "Give comprehensive explanations with examples and context.", technical: "Use precise technical language and detailed explanations." }; e.push(i[this.config.explanationLevel]), this.config.useAnalogies && e.push("When helpful, use analogies and real-world examples to clarify concepts."); const s = { slow: "Take time to explain each step. Break down complex ideas into smaller parts.", normal: "Provide clear explanations at a steady pace.", quick: "Be concise and direct. Focus on key points." }; return e.push(s[this.config.pacing]), e.join(" "); } enhanceOptions(e) { const t = { ...e }; if (t.temperature === void 0) { const i = { low: 0.8, moderate: 0.5, high: 0.2 }; t.temperature = i[this.config.consistencyLevel]; } return t; } addToUndoHistory(e, t) { const i = { step: this.currentStep + 1, prompt: e, response: t, timestamp: Date.now() }; this.currentStep < this.undoHistory.length - 1 && (this.undoHistory = this.undoHistory.slice(0, this.currentStep + 1)), this.undoHistory.push(i), this.currentStep = this.undoHistory.length - 1, this.undoHistory.length > this.config.maxUndoSteps && (this.undoHistory.shift(), this.currentStep--); } getCacheKey(e) { const t = e.map((s) => `${s.role}:${s.content}`).join("|"), i = `${this.config.tone}:${this.config.explanationLevel}:${this.config.pacing}`; return `${this.adapter.name}:${this.adapter.getModel()}:${i}:${t}`; } async applyPacing() { this.config.pacing === "slow" ? await new Promise((e) => setTimeout(e, 500)) : this.config.pacing === "normal" && await new Promise((e) => setTimeout(e, 200)); } mergeDefaultConfig(e) { return { tone: "neutral", explanationLevel: "moderate", pacing: "normal", consistencyLevel: "moderate", useAnalogies: !0, allowUndo: !0, maxUndoSteps: 10, ...e }; } } class A extends y { constructor(e = { learningRate: 0.1, confidenceThreshold: 0.8, maxPatternAge: 30 * 24 * 60 * 60 * 1e3, // 30 days realTimeAdaptation: !0 }) { super(), this.config = e, this.patterns = /* @__PURE__ */ new Map(), this.mlModels = /* @__PURE__ */ new Map(), this.realTimeMetrics = /* @__PURE__ */ new Map(), this.adaptationHistory = [], this.isLearning = !0, this.initializeModels(); } /** * Initialize machine learning models for different adaptation types */ initializeModels() { this.mlModels.set("visual", { modelType: "neural_network", parameters: { layers: [64, 32, 16], activation: "relu", learningRate: 1e-3, epochs: 100 }, trainingDataSize: 0, accuracy: 0, lastTrained: /* @__PURE__ */ new Date() }), this.mlModels.set("cognitive", { modelType: "random_forest", parameters: { n_estimators: 100, max_depth: 10, min_samples_split: 5 }, trainingDataSize: 0, accuracy: 0, lastTrained: /* @__PURE__ */ new Date() }), this.mlModels.set("motor", { modelType: "svm", parameters: { kernel: "rbf", C: 1, gamma: "scale" }, trainingDataSize: 0, accuracy: 0, lastTrained: /* @__PURE__ */ new Date() }), this.mlModels.set("sensory", { modelType: "decision_tree", parameters: { max_depth: 15, min_samples_leaf: 3, criterion: "gini" }, trainingDataSize: 0, accuracy: 0, lastTrained: /* @__PURE__ */ new Date() }); } /** * Analyze user behavior and generate adaptation patterns */ async analyzeUserBehavior(e, t, i, s, a) { this.patterns.get(e); const n = await this.analyzeVisualPatterns(t, i), r = await this.analyzeCognitivePatterns(s, t), c = await this.analyzeMotorPatterns(t), o = await this.analyzeSensoryPatterns(a, i), h = this.calculatePatternConfidence( n, r, c, o, t.length ), m = await this.calculateEffectivenessScore( e, { visual: n, cognitive: r, motor: c, sensory: o } ), l = { id: `pattern_${e}_${Date.now()}`, userId: e, patterns: { visual: n, cognitive: r, motor: c, sensory: o }, confidence: h, lastUpdated: /* @__PURE__ */ new Date(), effectivenessScore: m }; return this.patterns.set(e, l), this.config.realTimeAdaptation && h > this.config.confidenceThreshold && await this.applyRealTimeAdaptations(l), this.emit("pattern_updated", l), l; } /** * Analyze visual interaction patterns */ async analyzeVisualPatterns(e, t) { const i = e.filter((o) => o.type === "visual"), s = this.analyzeContrastPreferences(i), a = this.analyzeColorSensitivity(i, t), n = this.analyzeMotionTolerance(i), r = this.analyzeFontPreferences(i), c = this.analyzeBrightnessAdaptation(i); return { preferredContrast: s.optimal, colorSensitivity: a.sensitivities, motionTolerance: n.tolerance, fontSizePreference: r.optimalSize, brightnessAdaptation: c.adaptation }; } /** * Analyze cognitive load patterns using ML */ async analyzeCognitivePatterns(e, t) { this.mlModels.get("cognitive"); const i = this.predictProcessingSpeed(e, t), s = this.assessWorkingMemoryCapacity(e, t), a = this.calculateAttentionSpan(t), n = this.optimizeInformationDensity(e, t), r = this.assessDistractionSensitivity(e, t); return { processingSpeed: i, workingMemoryCapacity: s, attentionSpan: a, preferredInformationDensity: n, distractionSensitivity: r }; } /** * Analyze motor interaction patterns */ async analyzeMotorPatterns(e) { const t = e.filter((i) => i.type === "motor"); return { clickAccuracy: this.calculateClickAccuracy(t), hoverDuration: this.calculateOptimalHoverDuration(t), keyboardSpeed: this.calculateKeyboardSpeed(t), preferredTargetSize: this.calculateOptimalTargetSize(t), gestureComplexity: this.assessGestureComplexity(t) }; } /** * Analyze sensory adaptation patterns */ async analyzeSensoryPatterns(e, t) { return { soundSensitivity: e.audioSensitivity || 0.5, vibrationTolerance: e.vibrationTolerance || 0.5, lightSensitivity: e.lightSensitivity || 0.5, temperaturePreference: e.temperaturePreference || 22, texturePreference: t.sensory?.texturePreferences || [] }; } /** * Apply real-time adaptations based on patterns */ async applyRealTimeAdaptations(e) { const t = []; e.patterns.visual.motionTolerance < 0.3 && t.push({ type: "visual_adjustment", data: { reduceMotion: !0, animationDuration: 0 }, confidence: e.confidence, timestamp: /* @__PURE__ */ new Date() }), e.patterns.cognitive.processingSpeed < 0.5 && t.push({ type: "cognitive_load_change", data: { simplifyInterface: !0, reduceInformationDensity: 0.3, increasePausesBetweenActions: 500 }, confidence: e.confidence, timestamp: /* @__PURE__ */ new Date() }), e.patterns.motor.clickAccuracy < 0.7 && t.push({ type: "motor_assistance", data: { increaseTargetSize: 1.5, enableClickAssistance: !0, reduceFineMotorRequirements: !0 }, confidence: e.confidence, timestamp: /* @__PURE__ */ new Date() }), e.patterns.sensory.soundSensitivity > 0.8 && t.push({ type: "sensory_calibration", data: { muteNonEssentialSounds: !0, reduceAudioVolume: 0.3, enableVisualAlternatives: !0 }, confidence: e.confidence, timestamp: /* @__PURE__ */ new Date() }); for (const i of t) this.adaptationHistory.push(i), this.emit("adaptation_applied", i); } /** * Train ML models with new data */ async trainModels(e) { for (const [t, i] of this.mlModels.entries()) { const s = e.filter((a) => a.type === t); if (s.length > 10) { const a = await this.simulateModelTraining(i, s); i.accuracy = a, i.trainingDataSize = s.length, i.lastTrained = /* @__PURE__ */ new Date(), this.emit("model_trained", { modelName: t, accuracy: a, dataSize: s.length }); } } } /** * Predict optimal adaptations for new user interactions */ async predictAdaptations(e, t) { const i = this.patterns.get(e); if (!i || i.confidence < this.config.confidenceThreshold) return []; const s = []; for (const [a, n] of this.mlModels.entries()) if (n.accuracy > 0.7) { const r = await this.runModelPrediction(n, t, i); r.confidence > this.config.confidenceThreshold && s.push(r); } return s; } /** * Get adaptation effectiveness metrics */ getAdaptationMetrics(e) { const t = this.adaptationHistory.filter( (s) => this.patterns.get(e)?.id === s.data?.patternId ), i = this.patterns.get(e); return { totalAdaptations: t.length, averageConfidence: t.reduce((s, a) => s + a.confidence, 0) / t.length || 0, effectivenessScore: i?.effectivenessScore || 0, lastAdaptation: t.length > 0 ? t[t.length - 1].timestamp : null }; } // Private utility methods for ML analysis analyzeContrastPreferences(e) { const t = e.map((i) => i.contrastLevel || 1); return { optimal: t.reduce((i, s) => i + s, 0) / t.length || 1 }; } analyzeColorSensitivity(e, t) { return { sensitivities: t.visual?.colorBlindnessType ? [t.visual.colorBlindnessType] : [] }; } analyzeMotionTolerance(e) { const t = e.filter((i) => i.type === "motion_response"); return { tolerance: t.length > 0 && t[0].tolerance || 0.5 }; } analyzeFontPreferences(e) { return { optimalSize: 16 }; } analyzeBrightnessAdaptation(e) { return { adaptation: 0.8 }; } predictProcessingSpeed(e, t) { return e.taskComplexity ? 1 - e.taskComplexity : 0.7; } assessWorkingMemoryCapacity(e, t) { return e.memoryLoad ? 1 - e.memoryLoad : 0.7; } calculateAttentionSpan(e) { return 30; } optimizeInformationDensity(e, t) { return e.cognitiveLoad ? Math.max(0.1, 1 - e.cognitiveLoad) : 0.7; } assessDistractionSensitivity(e, t) { return e.distractorImpact || 0.5; } calculateClickAccuracy(e) { const t = e.filter((s) => s.action === "click"), i = t.filter((s) => s.successful); return t.length > 0 ? i.length / t.length : 1; } calculateOptimalHoverDuration(e) { const i = e.filter((s) => s.action === "hover").map((s) => s.duration || 500); return i.reduce((s, a) => s + a, 0) / i.length || 500; } calculateKeyboardSpeed(e) { return 0.8; } calculateOptimalTargetSize(e) { return 44; } assessGestureComplexity(e) { return 0.5; } calculatePatternConfidence(e, t, i, s, a) { return (Math.min(1, a / 100) + 0.8) / 2; } async calculateEffectivenessScore(e, t) { return 0.85; } async simulateModelTraining(e, t) { return await new Promise((i) => setTimeout(i, 100)), Math.random() * 0.3 + 0.7; } async runModelPrediction(e, t, i) { return { type: "visual_adjustment", data: { prediction: "optimize_contrast" }, confidence: e.accuracy, timestamp: /* @__PURE__ */ new Date() }; } } class T extends y { constructor(e = { layers: [24, 64, 32, 16, 8], // Input -> Hidden layers -> Output activations: ["relu", "relu", "relu", "relu", "sigmoid"], learningRate: 1e-3, momentum: 0.9, regularization: 0.01, batchSize: 32, maxEpochs: 1e3, convergenceThreshold: 1e-3 }) { super(), this.config = e, this.network = [], this.trainingHistory = [], this.realtimeBuffer = [], this.isTraining = !1, this.currentEpoch = 0, this.initializeNetwork(); } /** * Initialize neural network with random weights */ initializeNetwork() { this.network = []; for (let e = 0; e < this.config.layers.length - 1; e++) { const t = this.config.layers[e], i = this.config.layers[e + 1], s = Math.sqrt(6 / (t + i)), a = { weights: Array(i).fill(0).map( () => Array(t).fill(0).map( () => (Math.random() * 2 - 1) * s ) ), biases: Array(i).fill(0).map( () => (Math.random() * 2 - 1) * 0.1 ), activation: this.config.activations[e], dropout: e < this.config.layers.length - 2 ? 0.2 : void 0 }; this.network.push(a); } this.emit("network_initialized", { layers: this.config.layers, totalParameters: this.getTotalParameters() }); } /** * Forward propagation through the network */ forward(e, t = !1) { const i = [e]; for (let s = 0; s < this.network.length; s++) { const a = this.network[s], n = i[s], r = this.computeLayerOutput(a, n, t); i.push(r); } return i; } /** * Compute output for a single layer */ computeLayerOutput(e, t, i) { return e.weights.map((a, n) => { const r = a.reduce( (o, h, m) => o + h * t[m], 0 ) + e.biases[n], c = this.applyActivation(r, e.activation); return i && e.dropout && Math.random() < e.dropout ? 0 : c; }); } /** * Apply activation function */ applyActivation(e, t) { switch (t) { case "relu": return Math.max(0, e); case "sigmoid": return 1 / (1 + Math.exp(-e)); case "tanh": return Math.tanh(e); case "leaky_relu": return e > 0 ? e : 0.01 * e; case "softmax": return e; default: return e; } } /** * Backpropagation algorithm */ backward(e, t, i) { const s = [], a = [], n = e[e.length - 1]; let r = n.map( (o, h) => 2 * (o - t[h]) // MSE derivative ); for (let o = this.network.length - 1; o >= 0; o--) { const h = this.network[o], m = e[o], l = h.weights.map( (d, p) => d.map( (f, w) => r[p] * m[w] ) ), u = r.slice(); if (s.unshift(l), a.unshift(u), o > 0) { const d = Array(m.length).fill(0); for (let p = 0; p < h.weights.length; p++) for (let f = 0; f < h.weights[p].length; f++) d[f] += r[p] * h.weights[p][f]; r = d.map( (p, f) => p * this.getActivationDerivative(m[f], h.activation) ); } } for (let o = 0; o < this.network.length; o++) { const h = this.network[o]; for (let m = 0; m < h.weights.length; m++) for (let l = 0; l < h.weights[m].length; l++) { const u = s[o][m][l], d = this.config.regularization * h.weights[m][l]; h.weights[m][l] -= i * (u + d); } for (let m = 0; m < h.biases.length; m++) h.biases[m] -= i * a[o][m]; } return n.reduce( (o, h, m) => o + Math.pow(h - t[m], 2), 0 ) / n.length; } /** * Get activation function derivative */ getActivationDerivative(e, t) { switch (t) { case "relu": return e > 0 ? 1 : 0; case "sigmoid": const i = 1 / (1 + Math.exp(-e)); return i * (1 - i); case "tanh": return 1 - Math.pow(Math.tanh(e), 2); case "leaky_relu": return e > 0 ? 1 : 0.01; default: return 1; } } /** * Train the network with batch data */ async trainBatch(e) { if (this.isTraining) throw new Error("Network is already training"); this.isTraining = !0, this.currentEpoch = 0; try { let t = 1 / 0, i = 0; const s = 50; for (; this.currentEpoch < this.config.maxEpochs; ) { const n = await this.trainEpoch(e), r = e.slice(-Math.floor(e.length * 0.2)), c = this.evaluateNetwork(r), o = { epoch: this.currentEpoch, loss: n, accuracy: this.calculateAccuracy(e), validationLoss: c, validationAccuracy: this.calculateAccuracy(r), learningRate: this.config.learningRate, convergenceRate: Math.abs(t - n) / t }; if (this.trainingHistory.push(o), this.emit("training_progress", o), n < t - this.config.convergenceThreshold ? (t = n, i = 0) : i++, i >= s) { this.emit("training_converged", o); break; } this.currentEpoch++; } const a = this.trainingHistory[this.trainingHistory.length - 1]; return this.emit("training_completed", a), a; } finally { this.isTraining = !1; } } /** * Train for one epoch */ async trainEpoch(e) { const t = [...e].sort(() => Math.random() - 0.5); let i = 0, s = 0; for (let a = 0; a < t.length; a += this.config.batchSize) { const n = t.slice(a, a + this.config.batchSize), r = await this.trainBatchData(n); i += r, s++, s % 10 === 0 && await new Promise((c) => setTimeout(c, 0)); } return i / s; } /** * Train with a single batch of data */ async trainBatchData(e) { let t = 0; for (const i of e) { const s = this.preprocessInputs(i), a = this.preprocessTargets(i), n = this.forward(s, !0), r = this.backward(n, a, this.config.learningRate); t += r; } return t / e.length; } /** * Make prediction for user adaptations */ async predict(e, t, i) { const s = this.createPredictionInputs(e, t, i), a = this.forward(s, !1), n = a[a.length - 1], r = this.parseOutputToAdaptations(n), c = this.calculatePredictionConfidence(n), o = this.generateReasoning(s, n, r), h = await this.generateAlternatives(s, r), m = { adaptations: r, confidence: c, reasoning: o, alternatives: h }; return this.emit("prediction_made", m), m; } /** * Add real-time training data */ addRealtimeData(e) { this.realtimeBuffer.push(e), this.realtimeBuffer.length >= this.config.batchSize && this.performIncrementalLearning(); } /** * Perform incremental learning with real-time data */ async performIncrementalLearning() { if (this.isTraining || this.realtimeBuffer.length === 0) return; const e = this.realtimeBuffer.splice(0, this.config.batchSize); try { const t = this.config.learningRate; this.config.learningRate *= 0.1, await this.trainBatchData(e), this.config.learningRate = t, this.emit("incremental_learning_completed", { batchSize: e.length, totalParameters: this.getTotalParameters() }); } catch (t) { this.emit("incremental_learning_error", t); } } /** * Evaluate network performance */ evaluateNetwork(e) { let t = 0; for (const i of e) { const s = this.preprocessInputs(i), a = this.preprocessTargets(i), n = this.forward(s, !1), r = n[n.length - 1], c = r.reduce( (o, h, m) => o + Math.pow(h - a[m], 2), 0 ) / r.length; t += c; } return t / e.length; } /** * Calculate prediction accuracy */ calculateAccuracy(e) { let t = 0; for (const i of e) { const s = this.preprocessInputs(i), a = this.preprocessTargets(i), n = this.forward(s, !1); n[n.length - 1].every( (o, h) => Math.abs(o - a[h]) < 0.1 ) && t++; } return t / e.length; } /** * Get total number of parameters in the network */ getTotalParameters() { return this.network.reduce((e, t) => { const i = t.weights.reduce( (a, n) => a + n.length, 0 ), s = t.biases.length; return e + i + s; }, 0); } // Utility methods for data preprocessing and parsing preprocessInputs(e) { return [ ...e.inputs, e.context.timeOfDay / 24, e.context.cognitiveState, e.context.deviceType === "mobile" ? 1 : 0, e.context.environment === "quiet" ? 1 : 0 ]; } preprocessTargets(e) { return e.targets.map((t) => Math.max(0, Math.min(1, t))); } createPredictionInputs(e, t, i) { return [ t.timeOfDay / 24 || 0.5, t.cognitiveLoad || 0.5, t.environmentNoise || 0.5, t.lightLevel || 0.5, i.length / 100 || 0.1 // Add more context features... ].concat(Array(19).fill(0.5)); } parseOutputToAdaptations(e) { return { visual: e.slice(0, 2), // Contrast, brightness cognitive: e.slice(2, 4), // Processing speed, complexity motor: e.slice(4, 6), // Target size, timing sensory: e.slice(6, 8) // Sound, vibration }; } calculatePredictionConfidence(e) { const t = e.reduce((i, s) => { const a = e.reduce((n, r) => n + r, 0) / e.length; return i + Math.pow(s - a, 2); }, 0) / e.length; return Math.max(0, 1 - t); } generateReasoning(e, t, i) { const s = []; return e[1] > 0.7 && s.push("High cognitive load detected, simplifying interface"), i.visual[0] < 0.3 && s.push("Reducing visual complexity due to sensory sensitivity"), i.motor[0] > 0.7 && s.push("Increasing target sizes for better motor accessibility"), s; } async generateAlternatives(e, t) { return [ { adaptations: { ...t, visual: t.visual.map((i) => i * 0.8) }, confidence: 0.7 }, { adaptations: { ...t, cognitive: t.cognitive.map((i) => i * 1.2) }, confidence: 0.6 } ]; } /** * Export network for persistence */ exportNetwork() { return { config: this.config, network: this.network, trainingHistory: this.trainingHistory, currentEpoch: this.currentEpoch }; } /** * Import network from saved state */ importNetwork(e) { this.config = e.config, this.network = e.network, this.trainingHistory = e.trainingHistory || [], this.currentEpoch = e.currentEpoch || 0, this.emit("network_imported", { totalParameters: this.getTotalParameters(), trainingEpochs: this.currentEpoch }); } } class P extends y { constructor(e = { optimizationInterval: 5e3, // 5 seconds convergenceThreshold: 1e-3, maxIterations: 100, adaptationRate: 0.1, stabilityWindow: 10 }) { super(), this.config = e, this.optimizationTargets = /* @__PURE__ */ new Map(), this.metricsHistory = [], this.currentStrategies = /* @__PURE__ */ new Map(), this.optimizationLoop = null, this.isOptimizing = !1, this.initializeOptimizationStrategies(); } /** * Initialize optimization strategies */ initializeOptimizationStrategies() { this.currentStrategies.set("gradient_descent", { name: "Gradient Descent", algorithm: "gradient_descent", parameters: { learningRate: 0.01, momentum: 0.9, decay: 0.99 }, converged: !1, performance: 0 }), this.currentStrategies.set("genetic_algorithm", { name: "Genetic Algorithm", algorithm: "genetic_algorithm", parameters: { populationSize: 50, mutationRate: 0.1, crossoverRate: 0.8, elitismRatio: 0.2 }, converged: !1, performance: 0 }), this.currentStrategies.set("simulated_annealing", { name: "Simulated Annealing", algorithm: "simulated_annealing", parameters: { initialTemperature: 100, coolingRate: 0.95, minTemperature: 0.01 }, converged: !1, performance: 0 }), this.currentStrategies.set("particle_swarm", { name: "Particle Swarm", algorithm: "particle_swarm", parameters: { swarmSize: 30, inertiaWeight: 0.7, cognitiveWeight: 1.5, socialWeight: 1.5 }, converged: !1, performance: 0 }), this.currentStrategies.set("bayesian", { name: "Bayesian Optimization", algorithm: "bayesian", parameters: { acquisitionFunction: "expected_improvement", kernelType: "rbf", explorationWeight: 0.01 }, converged: !1, performance: 0 }); } /** * Start real-time optimization */ startOptimization() { this.isOptimizing || (this.isOptimizing = !0, this.optimizationLoop = setInterval(() => { this.runOptimizationCycle(); }, this.config.optimizationInterval), this.emit("optimization_started")); } /** * Stop real-time optimization */ stopOptimization() { this.isOptimizing && (this.isOptimizing = !1, this.optimizationLoop && (clearInterval(this.optimizationLoop), this.optimizationLoop = null), this.emit("optimization_stopped")); } /** * Add optimization target */ addOptimizationTarget(e) { this.optimizationTargets.set(e.metric, e), this.emit("target_added", e); } /** * Remove optimization target */ removeOptimizationTarget(e) { this.optimizationTargets.delete(e), this.emit("target_removed", e); } /** * Add real-time metrics */ addMetrics(e) { this.metricsHistory.push(e); const t = 1e3; this.metricsHistory.length > t && (this.metricsHistory = this.metricsHistory.slice(-t)), this.emit("metrics_added", e); } /** * Run single optimization cycle */ async runOptimizationCycle() { try { const e = []; for (const [i, s] of this.optimizationTargets.entries()) { const a = await this.optimizeTarget(s); e.push(a); } const t = this.evaluateOptimizationPerformance(e); await this.adaptOptimizationStrategies(t), this.emit("optimization_cycle_completed", { results: e, overallPerformance: t, timestamp: /* @__PURE__ */ new Date() }); } catch (e) { this.emit("optimization_error", e); } } /** * Optimize single target using best available strategy */ async optimizeTarget(e) { const t = this.selectBestStrategy(e), i = this.getCurrentMetrics(e.metric); if (!i || i.length === 0) return { parametersAdjusted: {}, improvementScore: 0, convergenceTime: 0, iterationsRequired: 0, stabilityMetric: 0 }; switch (t.algorithm) { case "gradient_descent": return await this.gradientDescentOptimization(e, i); case "genetic_algorithm": return await this.geneticAlgorithmOptimization(e, i); case "simulated_annealing": return await this.simulatedAnnealingOptimization(e, i); case "particle_swarm": return await this.particleSwarmOptimization(e, i); case "bayesian": return await this.bayesianOptimization(e, i); default: throw new Error(`Unknown optimization algorithm: ${t.algorithm}`); } } /** * Gradient Descent optimization implementation */ async gradientDescentOptimization(e, t) { const i = this.currentStrategies.get("gradient_descent"), s = Date.now(); let a = 0, n = e.currentValue; const r = {}; for (; a < this.config.maxIterations; ) { const m = this.calculateGradient(e, t, n), l = i.parameters.learningRate * m; if (n -= l, n = this.applyConstraints(n, e.constraints), r[e.metric] = n, Math.abs(l) < this.config.convergenceThreshold) break; a++, await new Promise((u) => setTimeout(u, 1)); } const c = Date.now() - s, o = this.calculateImprovementScore(e.currentValue, n, e.targetValue), h = this.calculateStabilityMetric(e.metric); return { parametersAdjusted: r, improvementScore: o, convergenceTime: c, iterationsRequired: a, stabilityMetric: h }; } /** * Genetic Algorithm optimization implementation */ async geneticAlgorithmOptimization(e, t) { const i = this.currentStrategies.get("genetic_algorithm"), s = Date.now(); let a = 0, n = this.initializePopulation(i.parameters.populationSize, e); const r = {}; for (; a < this.config.maxIterations; ) { const l = await this.evaluatePopulationFitness(n, e, t), u = l.indexOf(Math.max(...l)), d = n[u]; if (this.isConverged(l)) { r[e.metric] = d; break; } n = await this.createNewGeneration(n, l, i.parameters), a++, await new Promise((p) => setTimeout(p, 1)); } const c = Date.now() - s, o = r[e.metric] || e.currentValue, h = this.calculateImprovementScore(e.currentValue, o, e.targetValue), m = this.calculateStabilityMetric(e.metric); return { parametersAdjusted: r, improvementScore: h, convergenceTime: c, iterationsRequired: a, stabilityMetric: m }; } /** * Simulated Annealing optimization implementation */ async simulatedAnnealingOptimization(e, t) { const i = this.currentStrategies.get("simulated_annealing"), s = Date.now(); let a = 0, n = e.currentValue, r = i.parameters.initialTemperature; const c = {}; for (; a < this.config.maxIterations && r > i.parameters.minTemperature; ) { const l = this.generateNeighborSolution(n, e.constraints), u = this.calculateEnergy(n, e), p = this.calculateEnergy(l, e) - u; (p < 0 || Math.random() < Math.exp(-p / r)) && (n = l), r *= i.parameters.coolingRate, a++, await new Promise((f) => setTimeout(f, 1)); } c[e.metric] = n; const o = Date.now() - s, h = this.calculateImprovementScore(e.currentValue, n, e.targetValue), m = this.calculateStabilityMetric(e.metric); return { parametersAdjusted: c, improvementScore: h, convergenceTime: o, iterationsRequired: a, stabilityMetric: m }; } /** * Particle Swarm optimization implementation */ async particleSwarmOptimization(e, t) { const i = this.currentStrategies.get("particle_swarm"), s = Date.now(); let a = 0; const n = i.parameters.swarmSize, r = this.initializeParticleSwarm(n, e); let c = this.findGlobalBest(r, e); const o = {}; for (; a < this.config.maxIterations; ) { for (const d of r) this.updateParticleVelocity(d, c, i.parameters), this.updateParticlePosition(d, e.constraints), this.updateParticleBest(d, e); const u = this.findGlobalBest(r, e); if (this.isBetterSolution(u, c, e) && (c = u), this.isSwarmConverged(r)) break; a++, await new Promise((d) => setTimeout(d, 1)); } o[e.metric] = c.position; const h = Date.now() - s, m = this.calculateImprovementScore(e.currentValue, c.position, e.targetValue), l = this.calculateStabilityMetric(e.metric); return { parametersAdjusted: o, improvementScore: m, convergenceTime: h, iterationsRequired: a, stabilityMetric: l }; } /** * Bayesian optimization implementation */ async bayesianOptimization(e, t) { const i = this.currentStrategies.get("bayesian"), s = Date.now(); let a = 0; const n = [], r = {}; for (let l = 0; l < 5; l++) { const u = this.sampleFromConstraints(e.constraints), d = this.evaluateObjective(u, e, t); n.push({ x: u, y: d }); } for (; a < this.config.maxIterations; ) { const l = this.fitGaussianProcess(n), u = this.optimizeAcquisitionFunction(l, e, i.parameters), d = this.evaluateObjective(u, e, t); if (n.push({ x: u, y: d }), this.isBayesianConverged(n)) break; a++, await new Promise((p) => setTimeout(p, 1)); } const c = n.reduce( (l, u) => u.y > l.y ? u : l ); r[e.metric] = c.x; const o = Date.now() - s, h = this.calculateImprovementScore(e.currentValue, c.x, e.targetValue), m = this.calculateStabilityMetric(e.metric); return { parametersAdjusted: r, improvementScore: h, convergenceTime: o, iterationsRequired: a, stabilityMetric: m }; } // Utility methods for optimization algorithms selectBestStrategy(e) { return Array.from(this.currentStrategies.values()).reduce( (i, s) => s.performance > i.performance ? s : i ); } getCurrentMetrics(e) { return this.metricsHistory.slice(-this.config.stabilityWindow); } calculateGradient(e, t, i) { const a = this.evaluateObjective(i + 1e-3, e, t), n = this.evaluateObjective(i - 1e-3, e, t); return (a - n) / (2 * 1e-3); } evaluateObjective(e, t, i) { return 1 - Math.abs(e - t.targetValue) / Math.abs(t.targetValue); } applyConstraints(e, t) { for (const i of t) e = Math.max(i.minValue, Math.min(i.maxValue, e)); return e; } calculateImprovementScore(e, t, i) { const s = Math.abs(e - i), a = Math.abs(t - i); return s > 0 ? (s - a) / s : 0; } calculateStabilityMetric(e) { const t = this.getCurrentMetrics(e); if (t.length < 2) return 1; const i = t.map((n) => n.metrics[e]).filter((n) => n !== void 0), s = i.reduce((n, r) => n + r, 0) / i.length, a = i.reduce((n, r) => n + Math.pow(r - s, 2), 0) / i.length; return Math.max(0, 1 - Math.sqrt(a) / s); } evaluateOptimizationPerformance(e) { return e.reduce((t, i) => t + i.improvementScore, 0) / e.length; } async adaptOptimizationStrategies(e) { for (const [t, i] of this.currentStrategies.entries()) e > 0.8 ? i.parameters = this.finetuneParameters(i.