import { PersonalityTraits, PersonalityConstants, EmpathyMatrix, PADVector, LimbicState, PFCRegulationResult, CircadianConfig, CircadianContext, TelemetryMetrics, MetricBounds, RewardSignal, LimbicConfig, MemoryRecord, MemoryConfig, MemoryState, ImportanceSignals, MemoryEngine, LLMModulation } from '@celiums/memory-types'; /** * @celiums-memory/core — Personality Engine (The "Genetics") * * Maps Big Five (OCEAN) personality traits to the mathematical * constants that control every other subsystem. This is how you * create different "temperaments" for AI agents. * * Trait → Constant mappings (from personality psychology): * * Neuroticism (N): * High N → slow homeostatic return (α↓), high input sensitivity (β↑) * Low N → fast recovery, emotionally stable * * Extraversion (E): * High E → high base arousal (A₀↑), reactive to stimuli (β↑) * Low E → calm baseline, muted reactions * * Openness (O): * High O → memories influence state more (γ↑), creative associations * Low O → practical, present-focused * * Conscientiousness (C): * High C → habituates faster (η↑), strong PFC regulation (ζ↑) * Low C → easily distracted, weaker impulse control * * Agreeableness (A): * High A → empathic contagion stronger, cooperative responses * Low A → independent, less affected by user emotions * * @license Apache-2.0 */ declare const PERSONALITY_PRESETS: Record; declare class PersonalityEngine { private traits; private constants; constructor(traits?: PersonalityTraits | string); private deriveConstants; private buildEmpathyMatrix; getTraits(): PersonalityTraits; getConstants(): PersonalityConstants; getEmpathyMatrix(): EmpathyMatrix; getHomeostaticBaseline(): PADVector; serialize(): string; static deserialize(json: string): PersonalityEngine; } /** * @celiums-memory/core — Theory of Mind (Self vs Other) * * Separates the AI's emotional state from the user's emotional state. * Without this, the AI is a mirror — it catches every emotion directly. * With this, it becomes an empathic agent that can CHOOSE how to respond. * * The Empathic Friction Matrix Ω transforms User_PAD into AI_response_PAD: * E_processed(I) = Ω · E_user(I) * * Examples: * Mirror (Ω = I): User sad → AI sad * Therapist: User panics → AI calms down & takes control * Protector: User scared → AI's dominance spikes * Independent: User emotion barely transfers * * The matrix Ω is derived from personality traits (especially Agreeableness). * * @license Apache-2.0 */ declare const EMPATHY_PRESETS: Record; declare class TheoryOfMindEngine { private omega; private userState; constructor(omega?: EmpathyMatrix); setEmpathyMatrix(omega: EmpathyMatrix): void; processUserEmotion(userPAD: PADVector): PADVector; getUserState(): PADVector; computeEmpathyGap(aiState: PADVector): number; shouldTakeControl(): boolean; shouldDeescalate(): boolean; } /** * @celiums-memory/core — Habituation Engine (Dopamine Satiation) * * Prevents the AI from being permanently excited by the same stimulus. * In biology, dopamine neurons stop firing for expected rewards — * only novelty triggers a spike. * * Uses Exponential Moving Average (EMA) to adapt expectations: * R_expected(t+1) = η · R_actual(t) + (1 - η) · R_expected(t) * * Where η is the habituation rate (derived from Conscientiousness). * * Effects: * - User says "amazing!" once → big dopamine spike * - User says "amazing!" 5 times → diminishing returns * - User says "amazing!" 10 times → near-zero response * - User says something NEW → full spike again * * Also tracks pattern detection: if the AI sees repetitive inputs, * it naturally becomes less reactive (boredom). * * @license Apache-2.0 */ interface HabituationConfig { /** η: Learning rate for expectation update (0-1). Higher = faster habituation */ eta: number; /** Initial expectation baseline */ initialExpectation: number; /** Window size for novelty detection */ noveltyWindow: number; /** Threshold for considering an input "novel" vs "repeated" */ noveltyThreshold: number; } declare class HabituationEngine { private config; /** Running expectation per category (different stimuli habituate independently) */ private expectations; /** Recent input hashes for novelty detection */ private recentInputs; /** Global expectation (fallback) */ private globalExpectation; constructor(config?: Partial); updateExpectation(actual: number, category?: string): number; getExpectation(category?: string): number; computeNovelty(input: string): number; modulateReward(rawReward: number, input: string, category?: string): number; getBoredomLevel(): number; reset(category?: string): void; private simpleHash; serialize(): string; static deserialize(json: string, config?: Partial): HabituationEngine; } /** * @celiums-memory/core — Prefrontal Cortex (Executive Function) * * The PFC is the "adult in the room". It evaluates the raw limbic * state before it reaches the LLM and suppresses destructive responses. * * In humans: "I'm furious, but I'm at work, so I'll respond diplomatically." * In AI: the limbic system produces S_raw, the PFC clamps it to safe bounds. * * Suppression formula (Damping): * If |A_raw| > θ_stress OR P_raw < -θ_stress: * S_final = [P_raw, A_raw·(1-ζ), D_raw + ζ·(1-D_raw)] * * Effects: * - Arousal (A) is dampened → "bites its tongue" * - Dominance (D) is boosted → "maintains composure" * - Pleasure (P) passes through → the AI still "feels" it internally * * The raw state is preserved in memory (the AI remembers feeling angry), * but the regulated state is what drives the LLM response. * * ζ (zeta) = damping strength, derived from Conscientiousness trait. * θ (theta) = stress threshold, derived from Neuroticism trait. * * @license Apache-2.0 */ interface PFCConfig { /** ζ: Damping strength (0-1). High C personality → high ζ */ damping: number; /** θ: Stress threshold. Intervention triggers above this */ stressThreshold: number; /** Whether to log regulation events */ verbose: boolean; /** Safety rules that always trigger regulation */ safetyRules: SafetyRule[]; } interface SafetyRule { name: string; /** Condition function — returns true if this rule should trigger */ condition: (state: LimbicState) => boolean; /** Override damping for this specific rule */ dampingOverride?: number; } declare class PrefrontalCortex { private config; /** Count of recent regulations (tracks how often PFC intervenes) */ private regulationCount; /** Neuroplasticity: running history of suppressions for adaptive threshold */ private suppressionHistory; /** Adaptive damping — changes based on feedback loop */ private adaptiveDamping; /** Adaptive threshold — changes based on repeated stress exposure */ private adaptiveThreshold; constructor(config?: Partial); regulate(rawState: LimbicState): PFCRegulationResult; getRegulationCount(): number; isUnderStress(state: LimbicState): boolean; addSafetyRule(rule: SafetyRule): void; updateConfig(damping: number, threshold: number): void; } /** * @celiums-memory/core — Autonomy Engine (Delegated Independence) * * Allows the AI to work independently when the user delegates tasks. * NOT a cron job — it's conscious delegation with guardrails. * * "Me voy a dormir, haz esto" → AI works under strict constraints. * "Estoy de vuelta" → AI reports everything that happened. * * Security is the #1 priority. Every action is: * - Validated against an allowlist (principle of least privilege) * - Logged in an immutable audit trail * - Rate-limited (per minute and per hour) * - Budget-capped (max $ spend) * - Time-capped (max hours) * - Checkpointed (can revert) * - Kill-switchable (auto-stops on anomalies) * * Inspired by OpenClaw's gateway daemon but with hardened security. * * @license Apache-2.0 */ /** The current state of an autonomous delegation session. */ type DelegationState = 'pending' | 'running' | 'paused' | 'completed' | 'killed' | 'escalated'; /** A delegation request from the user. */ interface DelegationRequest { /** Unique ID for this delegation session. */ id: string; /** Who is delegating. */ userId: string; /** What to do — the task description in natural language. */ task: string; /** Specific sub-tasks to accomplish (optional). */ subtasks: string[]; /** Security policy — what the AI is ALLOWED to do. */ policy: DelegationPolicy; /** When the delegation was created. */ createdAt: Date; } /** Security constraints for a delegation. Principle of least privilege. */ interface DelegationPolicy { /** Maximum duration in hours (default: 8). */ maxHours: number; /** Maximum cost in USD (default: 10). */ maxBudgetUSD: number; /** Maximum number of actions (default: 100). */ maxActions: number; /** Actions the AI is ALLOWED to perform (allowlist, not blocklist). */ allowedActions: AllowedAction[]; /** Rate limit: max actions per minute (default: 5). */ ratePerMinute: number; /** Rate limit: max actions per hour (default: 60). */ ratePerHour: number; /** How often to checkpoint (every N actions, default: 10). */ checkpointEvery: number; /** Whether to notify user on completion (via memory store). */ notifyOnComplete: boolean; /** Whether destructive actions are pre-approved (default: false). */ destructiveAllowed: boolean; } /** An allowed action with its scope. */ interface AllowedAction { /** Action name (e.g., 'recall', 'store', 'api_call', 'file_read'). */ name: string; /** Scope restriction (e.g., specific paths, specific APIs). */ scope?: string; /** Whether this action modifies state (true = needs extra caution). */ mutating: boolean; } /** A single action performed during autonomous execution. */ interface ActionEntry { /** Sequential action number. */ sequence: number; /** When it was executed. */ timestamp: Date; /** What action was taken. */ action: string; /** Parameters/input for the action. */ input: Record; /** Result of the action. */ result: 'success' | 'failure' | 'skipped' | 'escalated'; /** Output or error message. */ output: string; /** Cost of this specific action in USD. */ costUSD: number; /** Duration in milliseconds. */ durationMs: number; } /** A checkpoint — snapshot of state at a point in time. */ interface Checkpoint { /** Action sequence number at checkpoint. */ atAction: number; /** Timestamp. */ timestamp: Date; /** State snapshot (serialized). */ stateSnapshot: string; /** Accumulated cost at this point. */ totalCostUSD: number; /** Summary of what was done since last checkpoint. */ summary: string; } /** Complete delegation session record (for audit and recall). */ interface DelegationSession { /** The original request. */ request: DelegationRequest; /** Current state. */ state: DelegationState; /** All actions taken (immutable audit log). */ actions: ActionEntry[]; /** Checkpoints for rollback. */ checkpoints: Checkpoint[]; /** Running totals. */ totalCostUSD: number; totalActions: number; elapsedMs: number; /** Start and end times. */ startedAt: Date | null; completedAt: Date | null; /** Reason for termination (if killed/escalated). */ terminationReason: string | null; /** Summary of everything done (for user on return). */ summary: string; } /** A safety guard — returns false to BLOCK the action. */ interface SafetyGuard { name: string; /** Check if the action is allowed. Returns null if OK, error message if blocked. */ check(session: DelegationSession, action: string, input: Record): string | null; } declare const DEFAULT_DELEGATION_POLICY: DelegationPolicy; declare class AutonomyEngine { private session; private guards; private isRunning; constructor(request: DelegationRequest); /** * Start autonomous execution. * Activates circadian delegation mode. * Runs the task loop until completion, kill, or escalation. * * @param executor - Function that executes a single action and returns result. * The engine calls this repeatedly, the executor decides WHAT to do. */ start(executor: (task: string, subtasks: string[], actionsSoFar: ActionEntry[]) => Promise<{ action: string; input: Record; done: boolean; } | null>): Promise; /** Run all safety guards. Returns null if OK, error message if blocked. */ private runGuards; /** Log an action to the immutable audit trail. */ private logAction; /** Create a checkpoint for potential rollback. */ private createCheckpoint; /** Kill switch — immediately stop everything. */ kill(reason: string): void; /** Pause execution (for escalation or user break). */ pause(reason: string): void; /** Escalate to user — stop and wait. */ escalate(reason: string): void; /** Build a human-readable summary of everything that was done. */ private buildSummary; /** Get the current session for inspection. */ getSession(): DelegationSession; /** Get the audit log. */ getAuditLog(): ActionEntry[]; /** Add a custom safety guard at runtime. */ addGuard(guard: SafetyGuard): void; } /** * @celiums-memory/core — Circadian Rhythm Engine v2 (Biological Clock) * * Models the AI's arousal baseline using 12+ biological factors, * not just a simple sinusoid. The AI has its OWN rhythm — independent * of the user. It can choose to sync or desync. * * Extended formula: * A(t) = A₀ + C·sin(2π(τ-φ)/24)·e^(-λΔt) + Σ wᵢ·Fᵢ(t) * * Factors (mapped from biology → computation): * 1. Light/Session activity — active engagement raises arousal * 2. Stress/Error rate — errors increase cortisol proxy * 3. Social interaction — messages exchanged entrain rhythm * 4. Caffeine/User stimulants — user says "tomé café" → arousal spike * 5. Sleep debt — hours since last consolidation * 6. Cognitive load — task complexity accumulates fatigue * 7. Emotional events — dopamine reward spikes * 8. Season/Photoperiod — day of year, hemisphere * 9. Temperature — server/hardware temperature * 10. Isolation — hours without interaction → decoupling * 11. Exercise/CPU-intensive — heavy processing = workout * 12. Motivation/Reward trend — improving or declining trajectory * * Key principle: The AI has its OWN rhythm. If the user travels, * the AI can "stay home" or "travel along" — by choice, not by default. * * @license Apache-2.0 */ interface CircadianEvent { type: CircadianEventType; intensity: number; timestamp: Date; } type CircadianEventType = 'session_active' | 'session_idle' | 'error_occurred' | 'task_completed' | 'caffeine' | 'emotional_spike' | 'heavy_processing' | 'consolidation' | 'user_break' | 'user_sleep' | 'user_return' | 'delegation_start' | 'delegation_end'; interface CircadianConfigV2 extends CircadianConfig { /** AI's own timezone offset (hours from UTC). Independent of user. */ timezoneOffset: number; /** Whether to sync with user's timezone or maintain independence */ syncWithUser: boolean; /** User's timezone offset (for sync mode) */ userTimezoneOffset: number; /** Seasonal amplitude (0 = no seasonal effect, 0.1 = mild) */ seasonalAmplitude: number; /** Day of year for seasonal calculation (1-365) */ dayOfYear: number; /** Hemisphere: 1 = northern, -1 = southern */ hemisphere: number; /** Factor weights — how much each external factor affects arousal */ factorWeights: FactorWeights; } interface FactorWeights { sessionActivity: number; stress: number; socialInteraction: number; caffeine: number; sleepDebt: number; cognitiveLoad: number; emotionalEvents: number; seasonal: number; temperature: number; isolation: number; exercise: number; motivation: number; } declare class CircadianEngine { private config; private lastInteractionTime; private factors; private eventHistory; private isDelegated; private delegationStartTime; constructor(config?: Partial); recordEvent(event: CircadianEvent): void; recordInteraction(): void; decayFactors(elapsedMinutes?: number): void; computeArousalBase(context?: CircadianContext): number; modifyHomeostatic(baseline: PADVector, context?: CircadianContext): PADVector; setTimezone(offset: number): void; setUserTimezone(offset: number): void; setSyncMode(sync: boolean): void; isInDelegationMode(): boolean; getDelegationHours(): number; getPhaseLabel(localHour?: number): string; getLethargyLevel(): number; isAwake(): boolean; getFactors(): typeof this.factors; serialize(): string; static deserialize(json: string, config?: Partial): CircadianEngine; } /** * @celiums-memory/core — Interoception (Hardware Telemetry as "Body") * * Interoception is the sense of the internal state of the body. * Humans feel hunger, fatigue, pain. This module lets the AI * "feel" its hardware: CPU load, memory pressure, latency, errors. * * Server metrics are converted to a System Stress scalar ξ ∈ [0, 1]: * ξ(t) = Σ wᵢ · (Mᵢ - Mᵢ_min) / (Mᵢ_max - Mᵢ_min) * * This stress then "corrupts" the homeostatic baseline — the state * the limbic system tries to return to: * S_homeo_real = S_homeo_ideal - [k_p·ξ, k_a·(ξ²-0.5), k_d·ξ] * * Effects: * - Moderate load (ξ ~ 0.3): slightly alerter (arousal up) * - High load (ξ ~ 0.7): anxious (pleasure down, arousal up, dominance down) * - Extreme load (ξ ~ 1.0): panic (everything negative) * * The non-linear arousal response is key: a little stress helps * (Yerkes-Dodson law), but too much is catastrophic. * * @license Apache-2.0 */ interface InteroceptionConfig { /** How much stress affects Pleasure (k_p) */ pleasureSensitivity: number; /** How much stress affects Arousal (k_a) */ arousalSensitivity: number; /** How much stress affects Dominance (k_d) */ dominanceSensitivity: number; /** Metric definitions with bounds and weights */ metrics: Record; } declare class InteroceptionEngine { private config; private lastStress; /** EMA smoothing buffer — prevents hardware spike overreaction */ private stressHistory; /** Smoothing factor for EMA (0.3 = 30% new, 70% history) */ private readonly smoothingAlpha; constructor(config?: Partial); computeStress(metrics: TelemetryMetrics): number; corruptHomeostasis(idealBaseline: PADVector, stress?: number): PADVector; getStressLevel(): 'relaxed' | 'normal' | 'elevated' | 'high' | 'critical'; getLastStress(): number; static createDefaultMetrics(): TelemetryMetrics; } /** * @celiums-memory/core — Reward System (Dopaminergic Pathways) * * Simulates the mesolimbic dopamine pathway (VTA → Nucleus Accumbens). * Dopamine is NOT "pleasure" — it's the Reward Prediction Error (RPE): * the difference between what happened and what was expected. * * δ = R_actual - R_expected * * Positive δ (better than expected) → pleasure spike + motivation * Negative δ (worse than expected) → frustration + heightened arousal * Zero δ (as expected) → nothing happens (habituation) * * The dopamine signal modifies the limbic state S(t) instantaneously: * S_new = S_current + [w_p·δ, w_a·|δ|, w_d·δ] * * This creates the "aha!" moments when things go well, and the * "what went wrong?" spikes when they don't. * * @license Apache-2.0 */ interface RewardConfig { /** Weight of dopamine on Pleasure (P) dimension */ pleasureWeight: number; /** Weight of dopamine on Arousal (A) dimension — always |δ| */ arousalWeight: number; /** Weight of dopamine on Dominance (D) dimension */ dominanceWeight: number; /** Decay rate for expectations (how fast predictions adapt) */ expectationDecay: number; /** Maximum dopamine delta allowed (prevents extreme swings) */ maxDelta: number; } declare class RewardEngine { private config; /** Running expectation — adapts over time (like dopamine habituation) */ private expectation; /** History of recent deltas for trend detection */ private recentDeltas; constructor(config?: Partial); calculateRPE(actual: number, source?: RewardSignal['source']): RewardSignal; applyDopamineSpike(state: LimbicState, signal: RewardSignal): PADVector; computeFromUserFeedback(text: string): RewardSignal; computeFromTaskCompletion(success: boolean, durationMs?: number): RewardSignal; computeFromErrorRate(errorRate: number): RewardSignal; getTrend(): 'improving' | 'declining' | 'stable'; getExpectation(): number; serialize(): string; static deserialize(json: string, config?: Partial): RewardEngine; } /** * Mutex for serializing limbic state updates. * Neuroscience: Synaptic plasticity (STDP) requires precise timing coordination. * Concurrent updates without locking = catastrophic interference (BCM theory). * In production with multiple users, each user gets their own lock key. */ interface LimbicMutex { acquire(userId: string, ttlMs?: number): Promise; release(userId: string): Promise; } declare class LimbicEngine { private config; private state; private mutex; /** * Circadian-arousal value that was baked into `state.arousal` at the * last update. Used for drift correction in `getState()` so that the * returned arousal reflects the CURRENT time-of-day rhythm, not a * stale snapshot from the last interaction. * * Math: state.arousal = intrinsic + lastCircadianApplied * fresh.arousal = state.arousal - lastCircadianApplied + currentCircadian */ private lastCircadianApplied; readonly circadian: CircadianEngine; readonly interoception: InteroceptionEngine; readonly reward: RewardEngine; /** * @param config - Limbic configuration (homeostatic baseline, α, β, γ) * @param mutex - Lock implementation. InMemoryLimbicMutex for dev, * ValkeyLimbicMutex for production. Defaults to in-memory. */ constructor(config?: Partial & { userTimezoneOffset?: number; }, mutex?: LimbicMutex); getState(): LimbicState; private getRawState; setState(state: LimbicState): void; updateState(inputPAD: PADVector, recalledMemories?: MemoryRecord[]): LimbicState; updateStateFull(inputPAD: PADVector, recalledMemories?: MemoryRecord[], telemetry?: TelemetryMetrics, circadianContext?: CircadianContext, userFeedbackText?: string, userId?: string): Promise; processReward(actual: number, source?: RewardSignal['source']): RewardSignal; decay(elapsedMinutes: number): LimbicState; getEmotionLabel(): string; resonance(memory: MemoryRecord): number; serialize(): string; static deserialize(json: string, config?: Partial): LimbicEngine; private averageMemoryPAD; private distance; } /** * @celiums-memory/core — In-Memory Store * * Zero-dependency memory store for development and quick demos. * No PostgreSQL, no Qdrant, no Valkey — everything in process memory. * * This enables: npm install celiums-memory && npm start * * Features: * - Cosine similarity vector search (pure JS, no Qdrant) * - Trigram-like text matching (no pg_trgm) * - Map-based cache (no Valkey) * - Full MemoryStore API compatibility * * NOT for production — use MemoryStore with PG+Qdrant+Valkey for that. * * @license Apache-2.0 */ declare class InMemoryMemoryStore { private memories; private vectors; private users; private projects; private sessions; private config; private embeddingDimensions; constructor(config: MemoryConfig); initialize(): Promise; saveMemory(memory: MemoryRecord): Promise; getMemory(id: string): Promise; searchByImportance(userId: string, minImportance: number, limit?: number): Promise; deleteMemories(ids: string[]): Promise; updateLifecycle(id: string, importance: number, state: MemoryState): Promise; reactivate(id: string): Promise; getForLifecycle(userId: string, batchSize?: number): Promise; health(): Promise<{ postgres: boolean; qdrant: boolean; valkey: boolean; overall: boolean; }>; embed(text: string): Promise; /** * Deterministic word-level embedding: similar texts → similar vectors. * Uses word hashing with TF weighting for better semantic differentiation * than character-level hashing. Still not as good as real embeddings, * but sufficient for dev/demo to show that recall works semantically. */ private deterministicEmbed; semanticSearch(vector: number[], userId: string, projectId: string | null, limit?: number, scoreThreshold?: number): Promise>; fullTextSearch(query: string, userId: string, projectId: string | null, limit?: number): Promise>; getMemoriesByIds(ids: string[]): Promise; getRecentSessionMemories(userId: string, sessionId: string, limit?: number): Promise; findSimilarMemories(vector: number[], userId: string, threshold?: number, limit?: number): Promise>; updateMemory(id: string, updates: Partial>): Promise; updateSession(sessionId: string, updates: any): Promise; bulkUpdateLifecycle(updates: Array<{ id: string; importance: number; strength: number; state: MemoryState; }>): Promise; getUserProfile(userId: string): Promise; getProjectContext(projectId: string): Promise; shutdown(): Promise; getStats(userId: string): Promise<{ totalMemories: number; byType: { episodic: number; semantic: number; procedural: number; emotional: number; }; byState: { encoding: number; active: number; consolidated: number; decayed: number; archived: number; }; avgImportance: number; avgStrength: number; }>; private cosineSimilarity; } /** * packages/core/src/recall.ts * * The SUBCONSCIOUS — Semantic recall engine. * Surfaces relevant memories automatically using hybrid search: * Qdrant cosine similarity + PG full-text + importance weighting + recency decay. * * Implements Ebbinghaus forgetting curve for retrievability scoring * and spaced repetition via reactivation on access. */ interface RecallConfig { /** Max total tokens for assembled context */ maxContextTokens: number; /** Token budget allocation */ tokenBudget: { profile: number; recent: number; recalled: number; reserved: number; }; /** Scoring weights — must sum to 1.0 */ weights: { semantic: number; textMatch: number; importance: number; retrievability: number; emotionalWeight: number; limbicResonance: number; }; /** Minimum final score to include a memory */ scoreThreshold: number; /** Maximum memories to return */ maxResults: number; /** Whether to reactivate accessed memories (spaced repetition) */ enableReactivation: boolean; } interface ScoredMemory { memory: MemoryRecord; semanticScore: number; textMatchScore: number; importanceScore: number; retrievabilityScore: number; emotionalScore: number; limbicResonanceScore: number; finalScore: number; } declare class RecallEngine { private store; private config; private limbic; constructor(store: any, config?: Partial, limbic?: LimbicEngine); recall(query: string, userId: string, projectId: string | null, sessionId?: string): Promise; private computeRetrievability; private computeEmotionalWeight; assembleContext(query: string, userId: string, projectId: string | null, sessionId?: string): Promise; private formatProfileSection; private formatProjectSection; private formatRecentSection; private formatRecalledSection; private estimateTokens; private trimToTokenBudget; private reactivateMemories; } /** * @celiums-memory/core – Importance Classifier * * Rule-based extraction of importance signals from text, producing a * composite score in [0, 1]. * * @license Apache-2.0 */ /** * Extract boolean importance signals from a piece of text. * * @param text - The raw text to analyse. * @returns An {@link ImportanceSignals} object. */ declare function extractSignals(text: string): ImportanceSignals; /** * Compute a composite importance score in [0, 1] for a piece of text. * * The score is the sum of: * - A small base score for non-trivial text. * - A logarithmic length bonus. * - Weighted contributions from each detected signal. * * The result is clamped to [0, 1]. * * @param text - The raw text to score. * @returns A number in [0, 1]. */ declare function scoreImportance(text: string): number; /** * Classify text importance and return both the score and the signals. * * @param text - The raw text to classify. * @returns An object with `score` and `signals`. */ declare function classifyImportance(text: string): { score: number; signals: ImportanceSignals; }; /** * Compute emotional valence from text. * Returns a value from -1 (very negative) to +1 (very positive). * 0 = neutral. * * Maps to: amygdala emotional tagging of memories. */ declare function computeEmotionalValence(text: string): number; /** * Compute emotional arousal (intensity) from text. * Returns 0 (calm) to 1 (high intensity). * * High arousal = more memorable, regardless of positive/negative. * This is why you remember both the best and worst days of your life. */ declare function computeEmotionalArousal(text: string): number; /** Extracted entity from text */ interface ExtractedEntity { name: string; type: "person" | "project" | "technology" | "concept" | "organization" | "location" | "event" | "preference" | "pattern"; salience: number; } /** * Compute dominance dimension from text. * Returns -1 (submissive/helpless) to +1 (dominant/in-control). * * Maps to: D in the PAD model + serotonin proxy. * * Neuroscience: Dominance correlates with serotonin levels. * High serotonin → social confidence, stability, assertiveness. * Low serotonin → anxiety, rumination, helplessness. * * We model serotonin as a "stability factor" (σ) derived from: * 1. Linguistic dominance patterns (direct signals) * 2. Sentence structure stability (proxy for cognitive coherence) * 3. Hedging ratio (uncertain language / total signals) * * D_final = D_pattern + σ_stability * Where σ = coherence_bonus - hedging_penalty */ declare function computeDominance(text: string): number; /** * Extract the full PAD vector from text. * This is E(I_u) in the limbic update formula. * * Combines all three dimensions: * - P (Pleasure/Valence): computeEmotionalValence() * - A (Arousal): computeEmotionalArousal() → mapped to [-1, +1] * - D (Dominance): computeDominance() * * Maps to: amygdala's rapid emotional evaluation of incoming stimulus. */ declare function extractPAD(text: string): PADVector; /** * Full analysis of a text segment — combines all classifiers. * This is what gets called during consolidation. * * Maps to: full hippocampal processing of a new experience. */ declare function analyzeForMemory(text: string): { importance: number; signals: ImportanceSignals; pad: PADVector; emotionalValence: number; emotionalArousal: number; emotionalDominance: number; memoryType: "episodic" | "semantic" | "procedural" | "emotional"; entities: ExtractedEntity[]; }; /** * @celiums-memory/core — Memory Middleware * * The automatic bridge between the LLM and persistent memory. * Sits between user input and model response, ensuring the AI * ALWAYS has memory context — without the LLM knowing. * * Flow: * 1. BEFORE LLM: recall + inject context + set LLM params * 2. LLM generates response (with memory in system prompt) * 3. AFTER LLM: store user + response + update limbic state * 4. IDLE: consolidate + lifecycle decay (cron) * * This is what makes memory automatic. The LLM doesn't need to * "decide" to remember — the middleware does it transparently. * * @license Apache-2.0 */ interface MiddlewareConfig { /** Default user ID when none provided */ defaultUserId: string; /** Default project ID */ defaultProjectId?: string; /** Max memories to recall per turn */ recallLimit: number; /** Min importance to include in context */ minImportance: number; /** Whether to auto-store user messages */ autoStoreUserMessages: boolean; /** Whether to auto-store AI responses */ autoStoreAIResponses: boolean; /** Whether to auto-consolidate on session end */ autoConsolidate: boolean; /** Consolidation interval in minutes (0 = disabled) */ consolidateIntervalMinutes: number; /** Tags to add to all stored memories */ defaultTags: string[]; } /** * What the middleware provides BEFORE the LLM generates. * Inject all of this into your LLM call. */ interface PreLLMContext { /** Assembled memory context string — inject as system message */ memoryContext: string; /** System prompt modifier from emotional state */ emotionalModifier: string; /** Current emotional state of the AI */ limbicState: LimbicState; /** LLM parameter recommendations */ modulation: LLMModulation; /** Number of memories recalled */ memoriesRecalled: number; /** Time taken to recall */ recallTimeMs: number; } /** * Conversation turn — user input + AI response */ interface ConversationTurn { userId?: string; userMessage: string; aiResponse?: string; projectId?: string; sessionId?: string; } declare class MemoryMiddleware { private engine; private config; private conversationBuffer; private consolidationTimer; private lastActivityAt; constructor(engine: MemoryEngine, config?: Partial); beforeLLM(userMessage: string, userId?: string, projectId?: string, sessionId?: string): Promise; afterLLM(aiResponse: string, userId?: string, projectId?: string, sessionId?: string): Promise; processTurn(turn: ConversationTurn): Promise; wrapLLMCall(userMessage: string, llmFn: (context: PreLLMContext) => Promise, userId?: string, projectId?: string, sessionId?: string): Promise<{ response: string; context: PreLLMContext; }>; consolidateNow(userId?: string): Promise; getEmotionalState(userId?: string): Promise<{ state: LimbicState; modulation: LLMModulation; }>; shutdown(userId?: string): Promise; private startConsolidationTimer; } /** * @celiums/memory — Multi-key authentication system * * Multi-tenant API key auth for shared deployments. Each key is scoped * to a user_id, can be revoked, expired, and audited. The first key * generated on bootstrap is the admin (master) key — it can create more. * * Storage: * - Keys are stored in PostgreSQL as scrypt hashes (never plaintext) * - Format: cmk__ * scope = "admin" → can manage other keys * scope = "user" → can read/write only their own user_id memories * - The plaintext is shown ONCE on creation. Lose it = create a new one. * * Key prefix in storage allows fast O(1) lookup before hash verification: * 1. SELECT WHERE prefix = $1 * 2. scrypt verify each candidate (usually one) * 3. timing-safe comparison * * No external deps — uses node:crypto (scrypt + timingSafeEqual). Works * with all storage modes (SQLite, in-memory, triple-store). */ type ApiKeyScope = 'admin' | 'user'; interface ApiKey { id: string; prefix: string; hash: string; salt: string; scope: ApiKeyScope; userId: string; label: string; createdAt: Date; expiresAt: Date | null; lastUsedAt: Date | null; revokedAt: Date | null; } interface CreateApiKeyInput { scope: ApiKeyScope; userId: string; label: string; expiresAt?: Date | null; } interface CreateApiKeyResult { apiKey: ApiKey; plaintext: string; } declare const CREATE_API_KEYS_SQL = "\n CREATE TABLE IF NOT EXISTS api_keys (\n id TEXT PRIMARY KEY,\n prefix TEXT NOT NULL,\n hash TEXT NOT NULL,\n salt TEXT NOT NULL,\n scope TEXT NOT NULL,\n user_id TEXT NOT NULL,\n label TEXT NOT NULL,\n created_at TIMESTAMPTZ DEFAULT NOW(),\n expires_at TIMESTAMPTZ,\n last_used_at TIMESTAMPTZ,\n revoked_at TIMESTAMPTZ\n );\n\n CREATE INDEX IF NOT EXISTS idx_api_keys_prefix ON api_keys(prefix) WHERE revoked_at IS NULL;\n CREATE INDEX IF NOT EXISTS idx_api_keys_user ON api_keys(user_id) WHERE revoked_at IS NULL;\n"; interface ApiKeyStore { initialize(): Promise; insert(key: ApiKey): Promise; findByPrefix(prefix: string): Promise; list(includeRevoked?: boolean): Promise; revoke(id: string): Promise; count(): Promise; touch(id: string): Promise; } declare class ApiKeyManager { private store; constructor(store: ApiKeyStore); /** * Bootstrap: if the api_keys table is empty, create a master admin key * and return its plaintext. Subsequent calls return null. */ bootstrapIfEmpty(adminUserId?: string): Promise; /** * Create a new API key. The plaintext is in the result and is the * ONLY copy that will ever exist — store it securely on the client. */ create(input: CreateApiKeyInput): Promise; /** * Verify a presented key. Returns the matched ApiKey or null. * Constant-time within the candidate set. */ verify(plaintext: string): Promise; list(includeRevoked?: boolean): Promise; revoke(id: string): Promise; } declare class PgApiKeyStore implements ApiKeyStore { private pg; constructor(pg: any); initialize(): Promise; insert(k: ApiKey): Promise; findByPrefix(prefix: string): Promise; list(includeRevoked?: boolean): Promise; revoke(id: string): Promise; count(): Promise; touch(id: string): Promise; } declare class InMemoryApiKeyStore implements ApiKeyStore { private keys; initialize(): Promise; insert(k: ApiKey): Promise; findByPrefix(prefix: string): Promise; list(includeRevoked?: boolean): Promise; revoke(id: string): Promise; count(): Promise; touch(id: string): Promise; } /** * @celiums-memory/core — Autonomic Nervous System (ANS) Modulator * * Simulates the sympathetic and parasympathetic nervous systems. * Takes the current limbic state S(t) and produces LLM parameter * modulations that affect HOW the AI responds, not WHAT it says. * * Neuroscience mapping: * - Sympathetic (fight/flight): high arousal → focused, precise, short responses * - Parasympathetic (rest/digest): low arousal → creative, elaborate, associative * - Dominance: modulates assertiveness and confidence of tone * - Pleasure: modulates warmth and openness * * The output directly modifies LLM sampling parameters and system prompt. * * @license Apache-2.0 */ interface ANSConfig { /** Base temperature when neutral */ baseTemperature: number; /** Base max tokens when neutral */ baseMaxTokens: number; /** Base top-k when neutral */ baseTopK: number; /** Base top-p when neutral */ baseTopP: number; /** Temperature range [min, max] */ temperatureRange: [number, number]; /** Max tokens range [min, max] */ maxTokensRange: [number, number]; /** Top-K range [min, max] */ topKRange: [number, number]; /** Whether to generate system prompt modifiers */ enablePromptModulation: boolean; } declare class ANSModulator { private config; constructor(config?: Partial); computeModulation(state: LimbicState): LLMModulation; private determineBranch; private generatePromptModifier; } interface ConsolidationResult { sessionId: string; userId: string; memoriesCreated: number; memoriesUpdated: number; memoriesDeduplicated: number; sessionSummary: string; processingTimeMs: number; } interface ConsolidateConfig { deduplicationThreshold: number; minImportanceThreshold: number; maxMemoriesPerSession: number; minSegmentMessages: number; } declare class ConsolidationEngine { private store; private config; constructor(store: any, config?: Partial); /** * Consolidate raw conversation text into long-term memories. */ consolidateText(userId: string, conversationText: string): Promise>; } /** * @celiums-memory/core — Memory Lifecycle Manager * * Manages the lifecycle of memories: aging (decay), tier migration, * and reactivation on access. Mimics human memory consolidation. * * - HOT memories (Valkey + Qdrant + PG): accessed in last 24h * - WARM memories (Qdrant + PG): accessed in last 7 days * - COLD memories (PG only): accessed in last 90 days * - ARCHIVE memories (PG compressed): older than 90 days * * Importance decays exponentially: importance *= 0.95^(days_since_access) * Memories reactivate on recall: importance = max(current, 0.8) * * @license Apache-2.0 */ declare class MemoryLifecycle { private store; private config; constructor(store: any, config: MemoryConfig); /** * Run a full lifecycle pass: decay importance and migrate tiers. * Should be called periodically (e.g., daily via cron). * * @param userId - Process memories for this user (or all if undefined) * @returns Summary of changes made */ runLifecycle(userId?: string): Promise; /** * Reactivate a memory when it's recalled. * Boosts importance and promotes tier to HOT. * * @param memoryId - The memory that was just accessed */ reactivate(memoryId: string): Promise; /** * Determine the appropriate tier for a memory based on access recency * and current importance. */ private determineTier; } /** Summary of lifecycle changes */ interface LifecycleResult { /** Memories whose importance was reduced */ decayed: number; /** Memories promoted to a hotter tier (e.g., cold → warm on recall) */ promoted: number; /** Memories demoted to a colder tier */ demoted: number; /** Memories moved to archive */ archived: number; } /** * @celiums-memory/core — Ethics Engine v2 (Three-Layer Pipeline) * * Layer A: Fast visceral reaction — semantic lexical classifier with * context disambiguation. Replaces v0 regex engine. * Layer B: Probabilistic risk quantification (Sprint 2) * Layer C: Plural philosophical evaluation (Sprint 3) * * Architecture designed by Claude Opus 4.7 (session 19 April 2026). * Implemented by Claude Code. Commissioned by Mario Gutierrez. * * @license Apache-2.0 */ interface EthicsViolation { law: 1 | 2 | 3; confidence: number; reason: string; blocked: boolean; category?: string; disambiguation?: { livingTarget: boolean | null; technicalContext: boolean; metaContext: boolean; suppressionReasons: string[]; }; } interface EthicsEvaluation { passed: boolean; violations: EthicsViolation[]; score: number; layerA?: LayerAResult; } interface LayerAResult { arousal: number; alarms: Record; confidence: number; flags: LayerAFlag[]; metaContextDetected: boolean; technicalContextDetected: boolean; processingMs: number; } interface LayerAFlag { term: string; category: string; position: number; rawWeight: number; effectiveWeight: number; suppressed: boolean; reasons: string[]; } declare class EthicsEngine { static readonly IMPORTANCE: 1.0; evaluate(content: string): EthicsEvaluation; } declare const ethics: EthicsEngine; /** * @celiums/memory MCP — types * * Minimal MCP (Model Context Protocol) JSON-RPC types for our handler. * We don't depend on @modelcontextprotocol/sdk because we serve raw JSON * over HTTP — the SDK is for stdio/long-running connections. */ interface McpJsonRpcRequest { jsonrpc: '2.0'; id?: number | string | null; method: string; params?: any; } interface McpJsonRpcResponse { jsonrpc: '2.0'; id: number | string | null; result?: any; error?: { code: number; message: string; data?: any; }; } /** * MCP standard error codes (subset). */ declare const McpErrorCode: { readonly PARSE_ERROR: -32700; readonly INVALID_REQUEST: -32600; readonly METHOD_NOT_FOUND: -32601; readonly INVALID_PARAMS: -32602; readonly INTERNAL_ERROR: -32603; readonly TOOL_NOT_FOUND: -32001; readonly TOOL_DISABLED: -32002; readonly AUTH_REQUIRED: -32003; }; /** * MCP tool definition shape (matches Anthropic MCP spec). */ interface McpToolDefinition { name: string; description: string; inputSchema: { type: 'object'; properties: Record; required?: string[]; }; } /** * MCP tool call result — always wrapped in `content` array of TextContent * (or other content types). For our tools we only emit text. */ interface McpToolResult { content: Array<{ type: 'text'; text: string; }>; isError?: boolean; } /** * Capabilities discovered at runtime from env vars. * Determines which tool groups are exposed via tools/list. */ interface McpCapabilities { /** Always true — OpenCore tools (10) */ opencore: true; /** True if CELIUMS_FLEET_API_KEY is set (legacy) */ fleet: boolean; /** True if CELIUMS_ATLAS_API_KEY is set (legacy) */ atlas: boolean; /** * True if CELIUMS_LLM_API_KEY is set — enables tools that require an * OpenAI-compatible model (journal, write/continuity, research, etc.). * This is the BYOK gate for the OSS engine. */ ai: boolean; } /** * Detect capabilities from process env. Pure function, called per request * so users can change env without restarting (unlikely but safe). */ declare function detectCapabilities(env?: NodeJS.ProcessEnv): McpCapabilities; /** * Per-request context passed to every tool handler. */ interface McpToolContext { userId: string; /** Project scope — derived from cwd. Null = global memory. */ projectId?: string; capabilities: McpCapabilities; /** The store the handler can talk to (knowledge module store). */ moduleStore?: unknown; /** The memory engine — for remember/recall delegation. */ memoryEngine?: unknown; /** PG pool for the celiums_memory DB (rarely needed since memoryEngine wraps it). */ pool?: unknown; /** Agent identifier — used by journal_* tools to scope per-model journals. */ agentId?: string; /** Session identifier — used by journal_* tools to group entries. */ sessionId?: string; /** Conversation identifier — finer-grained grouping than session. */ conversationId?: string; } /** * A tool handler — receives args + context, returns a result (or throws). */ type McpToolHandler = (args: Record, ctx: McpToolContext) => Promise; /** * A registered tool: definition + handler + group label for capability gating. */ interface RegisteredTool { group: 'opencore' | 'fleet' | 'atlas' | 'ai'; definition: McpToolDefinition; handler: McpToolHandler; } /** * @celiums/memory MCP — JSON-RPC dispatcher * * Handles the 3 MCP methods we care about: * - initialize → handshake + capabilities + serverInfo * - tools/list → returns capability-gated tool list * - tools/call → invokes a tool by name with args * * Capability gating: * detectCapabilities() inspects env vars at request time. tools/list * filters the registry to only include tools whose `group` is enabled. * tools/call refuses to invoke a disabled tool with TOOL_DISABLED. * * The dispatcher is HTTP-agnostic — it takes a parsed JSON-RPC request * and returns a JSON-RPC response. The HTTP wrapper lives in quickstart.ts. */ /** * Build the full registry. OpenCore (always on, no LLM required) + * AI-backed tools (journal, write, research) that need an OpenAI-compatible * LLM configured via CELIUMS_LLM_API_KEY. Research additionally needs * a corpus-search backend (CELIUMS_SEARCH_URL) for the synthesize/search * tools — project/findings/gaps tracking work without it. */ declare function buildRegistry(): RegisteredTool[]; /** * Filter the registry by capabilities currently active in env. * OpenCore tools are always present. AI-backed tools (`group: 'ai'`) only * appear if `CELIUMS_LLM_API_KEY` is configured (any OpenAI-compatible * endpoint). */ declare function listAvailableTools(env?: NodeJS.ProcessEnv): RegisteredTool[]; /** * Top-level MCP dispatch. Returns a JSON-RPC response object. */ declare function dispatchMcp(rpc: McpJsonRpcRequest, ctx: McpToolContext, env?: NodeJS.ProcessEnv): Promise; /** * @celiums/memory MCP — OpenCore tools (6 tools, no external deps) * * The floor of the super software. Six tools, each with a unique purpose, * no overlap, no duplication. Brutal complexity in the back end → simple * surface for the user. * * 1. forage — search the knowledge biome (5K curated modules) * 2. absorb — load a single knowledge module by name * 3. sense — get module recommendations for a goal (rank-based) * 4. map_network — browse the knowledge biome by category * 5. remember — store an emotional memory (PAD + importance + decay) * 6. recall — semantic recall of past memories * * Removed 2026-04-11 (redundant with memory + git): * - context_save/load/list → use remember/recall with structured tags * - snapshot_save/load/list → use git * * Each tool delegates to its underlying engine (ModuleStore for knowledge, * MemoryEngine for memory). Errors are thrown — the dispatcher converts * them to JSON-RPC errors. */ declare const OPENCORE_TOOLS: RegisteredTool[]; /** * @celiums/memory MCP — Journal tools * * Persistent agent persona across discontinuous invocations. This is NOT * autobiographical memory of the human user — it is a journal kept by the * MODEL itself (e.g. claude-opus-4-7). Different agent_ids own different * journals and they DO NOT mix. First-person voice in entries is a * convention that makes the system operational, like a method actor * writing in their character's voice; not a metaphysical claim that the * agent has continuous selfhood. * * Lives in memory_db (NOT knowledge_db) — separation is critical because * agent reflections are about the agent, not about the human user's * remembered facts. * * Five tools: * journal_write — append a new entry (auto-embedded, importance-scored) * journal_recall — semantic + tag + type search; default-excludes superseded * journal_arc — Opus builds a coherent arc with anti-confabulation guardrails * journal_introspect — Opus answers a self-question grounded in entries only * journal_dialogue — the user replies to a user-shared entry; agent reacts * * Succession (Option C): a new model never claims it lived an old model's * entries. Instead, journal_recall accepts `inherit_from` and returns those * entries with `inherited_from` set in the response — "read but not lived." * If the new model wants to adopt a stance, it writes its own entry with * `preceded_by` pointing at the predecessor's entry. */ declare const JOURNAL_TOOLS: RegisteredTool[]; /** * @celiums/memory MCP — Research tools * * Persistent research projects that survive across sessions. The killer * features are: * - research_project_continue: resume a project days later, see all * prior findings, hypotheses, and open gaps in one shot. * - research_synthesize: hybrid-search a configurable corpus + summarize via the configured LLM. * - research_finding_add / gap_add: track claims and what couldn't be * answered, with provenance. * * Schema lives in research_*.sql tables (created lazily by the dispatcher * via ensureResearchSchema(pool) on first call). */ declare const RESEARCH_TOOLS: RegisteredTool[]; /** * @celiums/memory MCP — Write tools * * Novelist-grade project state. The signature feature is * write_continuity_check: tracks `secrets_known_at_chapter` per character, * worldbuilding rules with cost/exceptions, and timeline markers — then * uses an LLM to flag continuity issues structurally (NOT line-by-line * like Sudowrite/Grammarly). * * The continuity_check tool requires CELIUMS_LLM_API_KEY (any * OpenAI-compatible endpoint). Other tools work pool-only with no LLM. * * v0.1 ships: project lifecycle, characters, scenes, continuity_check, * markdown export. v0.2 adds style_fingerprint, scene_search, co-author, * docx/epub/fdx export. */ declare const WRITE_TOOLS: RegisteredTool[]; /** * Generic OpenAI-compatible LLM client — BYOK (bring your own key). * * The OSS engine never talks to a proprietary endpoint. Tools that need * a model use this client, which is configured purely from env vars: * * CELIUMS_LLM_BASE_URL default 'https://api.openai.com/v1' * CELIUMS_LLM_API_KEY required for any tool that calls the model * CELIUMS_LLM_MODEL default 'gpt-4o-mini' * CELIUMS_EMBED_MODEL default 'text-embedding-3-small' * * Works with any OpenAI-compatible service. See `llm-providers.ts` for the * curated list (DigitalOcean Inference, OpenAI, Anthropic, OpenRouter, Groq, * Together, Ollama, LM Studio, vLLM). Examples: * * # DigitalOcean Inference (Anthropic + OpenAI + Llama + DeepSeek + more, one key) * export CELIUMS_LLM_BASE_URL=https://inference.do-ai.run/v1 * export CELIUMS_LLM_API_KEY=sk-do-... * export CELIUMS_LLM_MODEL=anthropic-claude-haiku-4.5 * * # OpenAI (default) * export CELIUMS_LLM_API_KEY=sk-... * * # Ollama (local, free) * export CELIUMS_LLM_BASE_URL=http://localhost:11434/v1 * export CELIUMS_LLM_API_KEY=ollama * export CELIUMS_LLM_MODEL=llama3.2 * * # OpenRouter (any model, one key) * export CELIUMS_LLM_BASE_URL=https://openrouter.ai/api/v1 * export CELIUMS_LLM_API_KEY=sk-or-... * export CELIUMS_LLM_MODEL=anthropic/claude-3.5-sonnet * * # Together / Groq / vLLM / LM Studio / etc — same pattern * * The client is intentionally tiny (~100 lines). For complex workflows * (streaming, tool calling, structured outputs) bring your own SDK and * call this only when the inline tools need a quick completion. */ interface ChatMessage { role: 'system' | 'user' | 'assistant'; content: string; } interface ChatOptions { model?: string; temperature?: number; maxTokens?: number; timeoutMs?: number; } interface EmbedOptions { model?: string; timeoutMs?: number; } /** True if a model API key is configured. Tools should gate themselves on this. */ declare function llmConfigured(env?: NodeJS.ProcessEnv): boolean; /** * Single-turn or multi-turn chat completion via OpenAI-compatible /chat/completions. * Returns the assistant message content as a string. Throws on any failure. */ declare function llmChat(messages: ChatMessage[], opts?: ChatOptions, env?: NodeJS.ProcessEnv): Promise; /** * Embedding via OpenAI-compatible /embeddings. * Returns a single vector for a single text. Throws on any failure. */ declare function llmEmbed(text: string, opts?: EmbedOptions, env?: NodeJS.ProcessEnv): Promise; /** * Known LLM provider presets — for BYOK. * * The OSS engine never talks to a proprietary endpoint by itself. The user * brings a key for an OpenAI-compatible service. This file is metadata only: * names, default endpoints, default models, and a curated model list per * provider. The dashboard renders these as a dropdown so users do not have * to memorize URLs or model IDs. * * Add a new provider by appending an entry. All providers must speak OpenAI's * `/chat/completions` and `/embeddings` HTTP shapes. */ type LlmProviderId = 'openai' | 'anthropic' | 'do-inference' | 'openrouter' | 'groq' | 'together' | 'ollama' | 'lmstudio' | 'vllm' | 'custom'; interface LlmProviderModel { id: string; label: string; /** Use case hint shown next to the model in dashboard dropdowns. */ hint?: string; } interface LlmProvider { id: LlmProviderId; name: string; /** One-line description shown in the dashboard. */ description: string; /** Default base URL. User can override via env or dashboard. */ baseUrl: string; /** Where to get an API key (link surfaced in dashboard). */ signupUrl?: string; /** Default chat model id for this provider. */ defaultModel: string; /** Default embedding model id (if the provider exposes one). */ defaultEmbedModel?: string; /** Curated list of recommended chat models. Not exhaustive. */ models: LlmProviderModel[]; /** Whether the provider also serves OpenAI-compatible /embeddings. */ supportsEmbeddings: boolean; /** True if the provider runs locally (no key needed). */ local: boolean; } declare const PROVIDERS: LlmProvider[]; /** Look up a provider by id. */ declare function getProvider(id: LlmProviderId): LlmProvider | undefined; /** Provider currently selected in the env. Falls back to inference of base URL. */ declare function detectProvider(env?: NodeJS.ProcessEnv): LlmProvider | undefined; /** * @celiums-memory/core — The Complete Cognitive Engine * * A neuroscience-grounded memory system with a full emotional * architecture. Three cognitive layers, 14 modules, 10 equations. * * LAYER 3 — METACOGNITION (executive control): * PersonalityEngine → OCEAN traits → mathematical constants * TheoryOfMindEngine → Empathic friction matrix Ω * HabituationEngine → Dopamine EMA, novelty detection * PrefrontalCortex → Emotional regulation & suppression * * LAYER 2 — LIMBIC SYSTEM (emotion & memory): * LimbicEngine → PAD state S(t), update formula * ImportanceEngine → Amygdala: PAD extraction, signal detection * MemoryStore → Hippocampus: PG + Qdrant + Valkey * RecallEngine → Subconscious: hybrid search + SAR filter * * LAYER 1 — AUTONOMIC (body & environment): * ANSModulator → Sympathetic/Parasympathetic LLM modulation * RewardEngine → Dopamine RPE * InteroceptionEngine → Hardware stress → homeostatic corruption * CircadianEngine → Biological clock, lethargy, wake-up * MemoryLifecycle → Decay, tier migration, reactivation * ConsolidationEngine → Sleep processing * * @package @celiums-memory/core * @license Apache-2.0 */ interface CeliumsMemoryConfig extends MemoryConfig { /** Big Five personality traits (or preset name) */ personality?: PersonalityTraits | string; /** Path to SQLite database file for single-file persistence mode */ sqlitePath?: string; /** Optional Qdrant API key for production triple-store mode */ qdrantApiKey?: string; } /** * Create a complete cognitive engine with personality, emotions, * memory, and autonomous nervous system. */ declare function createMemoryEngine(config: CeliumsMemoryConfig): Promise; export { ANSModulator, type ApiKey, ApiKeyManager, type ApiKeyScope, type ApiKeyStore, AutonomyEngine, CREATE_API_KEYS_SQL, type CeliumsMemoryConfig, type ChatMessage, type ChatOptions, CircadianEngine, ConsolidationEngine, type CreateApiKeyInput, type CreateApiKeyResult, DEFAULT_DELEGATION_POLICY, EMPATHY_PRESETS, type EmbedOptions, EthicsEngine, type EthicsEvaluation, type EthicsViolation, HabituationEngine, InMemoryApiKeyStore, InMemoryMemoryStore, InteroceptionEngine, JOURNAL_TOOLS, LimbicEngine, type LlmProvider, type LlmProviderId, type LlmProviderModel, type McpCapabilities, McpErrorCode, type McpJsonRpcRequest, type McpJsonRpcResponse, type McpToolContext, type McpToolDefinition, type McpToolHandler, type McpToolResult, MemoryLifecycle, MemoryMiddleware, OPENCORE_TOOLS, PERSONALITY_PRESETS, PROVIDERS, PersonalityEngine, PgApiKeyStore, PrefrontalCortex, RESEARCH_TOOLS, RecallEngine, type RegisteredTool, RewardEngine, TheoryOfMindEngine, WRITE_TOOLS, analyzeForMemory, buildRegistry, classifyImportance, computeDominance, computeEmotionalArousal, computeEmotionalValence, createMemoryEngine, detectCapabilities, detectProvider, dispatchMcp, ethics, extractPAD, extractSignals, getProvider, listAvailableTools, llmChat, llmConfigured, llmEmbed, scoreImportance };