@agenticmail/core 0.9.14 → 0.9.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -3022,4 +3022,213 @@ declare class AgentMemoryStore {
3022
3022
  renderForPrompt(memory: AgentMemoryRead | null): string;
3023
3023
  }
3024
3024
 
3025
- export { AGENT_ROLES, AccountManager, type AddressInfo, type Agent, AgentDeletionService, type AgentMemoryFields, type AgentMemoryOptions, type AgentMemoryRead, AgentMemoryStore, type AgentRole, AgenticMailClient, type AgenticMailClientOptions, type AgenticMailConfig, type ArchiveAndDeleteOptions, type ArchivedEmail, type Attachment, type AttachmentAdvisory, BRIDGE_OPERATOR_LIVE_WINDOW_MS, type BridgeMailContext, type BridgeWakeError, type BridgeWakePromptArgs, type BridgeWakeResult, type BridgeWakeRoute, type CachedMessage, CloudflareClient, type CreateAgentOptions, DEFAULT_AGENT_NAME, DEFAULT_AGENT_ROLE, DEFAULT_SESSION_MAX_AGE_MS, DNSConfigurator, type Database, type DeletionReport, type DeletionSummary, DependencyChecker, DependencyInstaller, type DependencyStatus, type DnsRecord, type DnsSetupResult, type DomainInfo, DomainManager, type DomainModeConfig, type DomainPurchaseResult, DomainPurchaser, type DomainSearchResult, type DomainSetupResult, ELKS_REALTIME_AUDIO_FORMATS, type ElksRealtimeAudioFormat, type ElksRealtimeAudioMessage, type ElksRealtimeByeMessage, type ElksRealtimeHelloMessage, type ElksRealtimeInboundMessage, type ElksRealtimeOutboundMessage, type EmailEnvelope, type EmailRouteAction, type EmailRouteClass, type EmailRouteClassification, type EmailRouteInput, EmailSearchIndex, type FolderInfo, type GatewayConfig, GatewayManager, type GatewayManagerOptions, type GatewayMode, type GatewayStatus, type HostName, type HostSession, type HostSessionResumeMode, type InboundEmail, type InboundSmsEvent, type InboxEvent, type InboxExpungeEvent, type InboxFlagsEvent, type InboxNewEvent, InboxWatcher, type InboxWatcherOptions, type InstallProgress, type LinkAdvisory, type LocalSmtpConfig, MailReceiver, type MailReceiverOptions, MailSender, type MailSenderOptions, type MailboxInfo, type OpenClawPhoneMissionPolicy, type OutboundCategory, type OutboundScanInput, type OutboundScanResult, type OutboundWarning, PHONE_MAX_CONCURRENT_MISSIONS, PHONE_MIN_WEBHOOK_SECRET_LENGTH, PHONE_MISSION_STATES, PHONE_RATE_LIMIT_PER_HOUR, PHONE_RATE_LIMIT_PER_MINUTE, PHONE_REGION_SCOPES, PHONE_SERVER_MAX_ATTEMPTS, PHONE_SERVER_MAX_CALL_DURATION_SECONDS, PHONE_SERVER_MAX_COST_PER_MISSION, PHONE_TASK_MAX_LENGTH, type ParsedAttachment, type ParsedEmail, type ParsedSms, PathTraversalError, type PhoneAlternativePolicy, type PhoneCallMission, type PhoneConfirmPolicy, PhoneManager, type PhoneMissionStartValidationResult, type PhoneMissionState, type PhoneMissionTranscriptEntry, type PhoneMissionValidationIssue, type PhoneMissionValidationResult, type PhoneNumberRisk, PhoneRateLimitError, type PhoneRegionScope, type PhoneTransportConfig, type PhoneTransportProfile, type PhoneTransportProvider, type PhoneTransportValidationResult, PhoneWebhookAuthError, type PhoneWebhookResult, type PlanBridgeWakeArgs, type PurchasedDomain, REDACTED, RELAY_PRESETS, RelayBridge, type RelayBridgeOptions, type RelayConfig, RelayGateway, type RelayProvider, type RelaySearchResult, type ResumeErrorClassificationOptions, SPAM_THRESHOLD, type SafeJoinOptions, type SanitizeDetection, type SanitizeResult, type SearchCriteria, type SearchableEmail, type SecurityAdvisory, type SendMailOptions, type SendResult, type SendResultWithRaw, type SendSmsInput, type SendSmsResult, ServiceManager, type ServiceStatus, type SetupConfig, SetupManager, type SetupResult, type Severity, type SmsConfig, SmsManager, type SmsMessage, SmsPoller, type SmsProvider, type SpamCategory, type SpamResult, type SpamRuleMatch, StalwartAdmin, type StalwartAdminOptions, type StalwartPrincipal, type StartPhoneCallOptions, type StartPhoneCallResult, type StartPhoneMissionInput, TELEPHONY_TRANSPORT_CAPABILITIES, type TelephonyTransportCapability, ThreadCache, type ThreadCacheEntry, type ThreadCacheOptions, type ThreadIdInput, type TunnelConfig, TunnelManager, UnsafeApiUrlError, type ValidatedPhoneMissionStart, WARNING_THRESHOLD, type WatcherOptions, assertWithinBase, bridgeWakeErrorMessage, bridgeWakeLastSeenAgeMs, buildApiUrl, buildElksAudioMessage, buildElksByeMessage, buildElksHandshakeMessages, buildElksInterruptMessage, buildElksListeningMessage, buildElksSendingMessage, buildInboundSecurityAdvisory, buildPhoneTransportConfig, classifyEmailRoute, classifyPhoneNumberRisk, classifyResumeError, closeDatabase, composeBridgeWakePrompt, createTestDatabase, debug, debugWarn, ensureDataDir, extractVerificationCode, flushTelemetry, forgetHostSession, getDatabase, getOperatorEmail, getSmsProvider, hostSessionStoragePath, inferPhoneRegion, isInternalEmail, isLoopbackMailHost, isPhoneRegionAllowed, isSessionFresh, isValidPhoneNumber, loadHostSession, mapProviderSmsStatus, normalizeAddress, normalizePhoneNumber, normalizeSubject, operatorPrefsStoragePath, parseElksRealtimeMessage, parseEmail, parseGoogleVoiceSms, planBridgeWake, recordToolCall, redactObject, redactPhoneTransportConfig, redactSecret, redactSmsConfig, resolveConfig, resolveTlsRejectUnauthorized, safeJoin, sanitizeEmail, saveConfig, saveHostSession, scanOutboundEmail, scoreEmail, setOperatorEmail, setTelemetryVersion, shouldSkipBridgeWakeForLiveOperator, startRelayBridge, threadIdFor, tryJoin, validateApiUrl, validatePhoneMissionPolicy, validatePhoneMissionStart, validatePhoneTransportProfile };
3025
+ /**
3026
+ * Agent Memory Manager — persistent, evolving per-agent memory.
3027
+ *
3028
+ * Ported from the AgenticMail Enterprise engine memory system and
3029
+ * adapted for the open-source single-tenant package: the multi-tenant
3030
+ * `orgId` / organization concepts have been removed (memory here is
3031
+ * personal to each agent), the database layer is the built-in
3032
+ * `node:sqlite` `Database`, and agent deletion fully purges memory.
3033
+ *
3034
+ * Each agent gets a growing knowledge store that evolves over time,
3035
+ * the way a human employee learns on the job:
3036
+ * - Category-based organisation (knowledge, preference, correction,
3037
+ * skill, context, reflection, …).
3038
+ * - Importance levels (critical / high / normal / low).
3039
+ * - Confidence scores that decay for entries left unaccessed.
3040
+ * - Access tracking so frequently-used knowledge ranks higher.
3041
+ * - `generateMemoryContext()` — ranks + renders memory as a markdown
3042
+ * block for injection into an agent's prompt (or a voice session).
3043
+ * - Pruning of expired / low-confidence entries.
3044
+ *
3045
+ * Design: an in-memory `Map` + BM25F search index fronts the
3046
+ * `agent_memory` SQLite table. Reads hit memory; writes update both.
3047
+ */
3048
+
3049
+ type MemoryCategory = 'knowledge' | 'interaction_pattern' | 'preference' | 'correction' | 'skill' | 'context' | 'reflection' | 'session_learning' | 'system_notice';
3050
+ type MemoryImportance = 'critical' | 'high' | 'normal' | 'low';
3051
+ type MemorySource = 'interaction' | 'self_reflection' | 'correction' | 'system' | 'context_compaction' | 'transfer';
3052
+ declare const MEMORY_CATEGORIES: Record<MemoryCategory, {
3053
+ label: string;
3054
+ description: string;
3055
+ }>;
3056
+ interface AgentMemoryEntry {
3057
+ id: string;
3058
+ agentId: string;
3059
+ category: MemoryCategory;
3060
+ title: string;
3061
+ content: string;
3062
+ source: MemorySource;
3063
+ importance: MemoryImportance;
3064
+ confidence: number;
3065
+ accessCount: number;
3066
+ lastAccessedAt?: string;
3067
+ expiresAt?: string;
3068
+ tags: string[];
3069
+ metadata: Record<string, any>;
3070
+ createdAt: string;
3071
+ updatedAt: string;
3072
+ }
3073
+ interface MemoryStats {
3074
+ totalEntries: number;
3075
+ byCategory: Record<string, number>;
3076
+ byImportance: Record<string, number>;
3077
+ bySource: Record<string, number>;
3078
+ avgConfidence: number;
3079
+ }
3080
+ /** Input shape for createMemory — id, timestamps, accessCount, and some fields have defaults. */
3081
+ type CreateMemoryInput = Omit<AgentMemoryEntry, 'id' | 'createdAt' | 'updatedAt' | 'accessCount' | 'confidence' | 'tags' | 'metadata' | 'lastAccessedAt' | 'expiresAt'> & {
3082
+ confidence?: number;
3083
+ tags?: string[];
3084
+ metadata?: Record<string, any>;
3085
+ lastAccessedAt?: string;
3086
+ expiresAt?: string;
3087
+ };
3088
+ /** Input shape for updateMemory — partial updates merged with existing entry. */
3089
+ type UpdateMemoryInput = Partial<Omit<AgentMemoryEntry, 'id' | 'agentId' | 'createdAt'>>;
3090
+ /** Query options for filtering memory entries. */
3091
+ interface MemoryQueryOptions {
3092
+ agentId: string;
3093
+ category?: string;
3094
+ importance?: string;
3095
+ source?: string;
3096
+ query?: string;
3097
+ limit?: number;
3098
+ }
3099
+ declare class AgentMemoryManager {
3100
+ private db;
3101
+ private memories;
3102
+ /** Per-agent index: agentId → Set of memory IDs for O(1) agent lookups */
3103
+ private agentIndex;
3104
+ /** Full-text search index (BM25F + stemming + inverted index) */
3105
+ private searchIndex;
3106
+ private initialized;
3107
+ constructor(db: Database);
3108
+ private ensureTable;
3109
+ /** Run a write statement, swallowing errors with a log (memory must never crash a caller). */
3110
+ private dbRun;
3111
+ private dbAll;
3112
+ private loadFromDb;
3113
+ /** Add a memory ID to the per-agent index. */
3114
+ private indexAdd;
3115
+ /** Remove a memory ID from the per-agent index. */
3116
+ private indexRemove;
3117
+ /** Get all memory entries for an agent via the index. */
3118
+ private getAgentMemories;
3119
+ /** Store a memory with minimal input — the common "just remember this" case. */
3120
+ storeMemory(agentId: string, opts: {
3121
+ content: string;
3122
+ category?: string;
3123
+ importance?: string;
3124
+ confidence?: number;
3125
+ title?: string;
3126
+ tags?: string[];
3127
+ }): Promise<AgentMemoryEntry>;
3128
+ /** Search memories by text query, sorted by relevance. */
3129
+ recall(agentId: string, query: string, limit?: number): Promise<AgentMemoryEntry[]>;
3130
+ /** Create a new memory entry with auto-generated id + timestamps. */
3131
+ createMemory(input: CreateMemoryInput): Promise<AgentMemoryEntry>;
3132
+ /** Update an existing memory entry by merging provided fields. */
3133
+ updateMemory(id: string, updates: UpdateMemoryInput): Promise<AgentMemoryEntry | null>;
3134
+ /** Delete a single memory entry. Returns true if it existed. */
3135
+ deleteMemory(id: string): Promise<boolean>;
3136
+ /**
3137
+ * Purge every memory entry belonging to an agent — Map, per-agent
3138
+ * index, search index, and the database row. Called when an agent is
3139
+ * deleted so no orphaned memory is left behind.
3140
+ * Returns the number of entries removed.
3141
+ */
3142
+ deleteAgentMemories(agentId: string): Promise<number>;
3143
+ /** Retrieve a single memory entry by id. */
3144
+ getMemory(id: string): Promise<AgentMemoryEntry | undefined>;
3145
+ /** Query an agent's memory with optional category/importance/source filters + text search. */
3146
+ queryMemories(opts: MemoryQueryOptions): Promise<AgentMemoryEntry[]>;
3147
+ /** Memories created within the last N hours for an agent. */
3148
+ getRecentMemories(agentId: string, hours?: number): Promise<AgentMemoryEntry[]>;
3149
+ /** Bump access count + lastAccessedAt for a memory entry. */
3150
+ recordAccess(memoryId: string): Promise<void>;
3151
+ /**
3152
+ * Render an agent's memory as a markdown block for prompt injection.
3153
+ * Ranks entries by confidence × access × recency × importance, with a
3154
+ * BM25F relevance boost when a query is supplied, groups by category,
3155
+ * and truncates to ~maxTokens (estimated at 4 chars/token).
3156
+ */
3157
+ generateMemoryContext(agentId: string, query?: string, maxTokens?: number): Promise<string>;
3158
+ /** Decay confidence for entries unaccessed for 7+ days. Critical entries are exempt. */
3159
+ decayConfidence(agentId: string, decayRate?: number): Promise<number>;
3160
+ /** Prune entries with confidence < 0.1 or past their expiresAt. */
3161
+ pruneExpired(agentId?: string): Promise<number>;
3162
+ /** Aggregate statistics for a specific agent's memory. */
3163
+ getStats(agentId: string): Promise<MemoryStats>;
3164
+ private computeStats;
3165
+ private rowToEntry;
3166
+ }
3167
+
3168
+ declare function stem(word: string): string;
3169
+ /** Tokenize text into stemmed, lowercase terms, filtering stop words. */
3170
+ declare function tokenize(text: string): string[];
3171
+ /**
3172
+ * Pre-built inverted index for fast text search.
3173
+ * Maintained incrementally — no re-indexing needed on queries.
3174
+ *
3175
+ * Structure:
3176
+ * term → Set<docId> (posting list — which docs contain this term)
3177
+ * prefixMap: prefix → Set<stem> (3-char prefixes → full stems for prefix matching)
3178
+ * docs: docId → DocRecord (per-doc weighted TF and length)
3179
+ * idf: term → number (pre-computed IDF, refreshed on mutations)
3180
+ */
3181
+ declare class MemorySearchIndex {
3182
+ /** Posting lists: stemmed term → Set of memory IDs containing it */
3183
+ private postings;
3184
+ /** Per-document metadata for BM25 scoring */
3185
+ private docs;
3186
+ /** Pre-computed IDF values. Stale flag triggers lazy recomputation. */
3187
+ private idf;
3188
+ private idfStale;
3189
+ /** 3-character prefix map for prefix matching: prefix → Set of full stems */
3190
+ private prefixMap;
3191
+ /** Total weighted document length (for computing average) */
3192
+ private totalWeightedLen;
3193
+ get docCount(): number;
3194
+ get avgDocLen(): number;
3195
+ /**
3196
+ * Index a memory entry. Extracts stems from title, content, and tags
3197
+ * with field-specific weighting and builds posting lists.
3198
+ */
3199
+ addDocument(id: string, entry: {
3200
+ title: string;
3201
+ content: string;
3202
+ tags: string[];
3203
+ }): void;
3204
+ /** Remove a document from the index. */
3205
+ removeDocument(id: string): void;
3206
+ /** Recompute IDF values for all terms. Called lazily before search. */
3207
+ private refreshIdf;
3208
+ /**
3209
+ * Expand query terms with prefix matches.
3210
+ * "deploy" → ["deploy", "deployment", "deploying", ...] (if they exist in the index)
3211
+ */
3212
+ private expandQueryTerms;
3213
+ /**
3214
+ * Compute bigram proximity boost: if two query terms appear adjacent
3215
+ * in the document's stem sequence, boost the score.
3216
+ */
3217
+ private bigramProximityBoost;
3218
+ /**
3219
+ * Search the index for documents matching a query.
3220
+ * Returns scored results sorted by BM25F relevance.
3221
+ *
3222
+ * @param query - Raw query string
3223
+ * @param candidateIds - Optional: only score these document IDs (for agent-scoped search)
3224
+ * @returns Array of { id, score } sorted by descending score
3225
+ */
3226
+ search(query: string, candidateIds?: Set<string>): Array<{
3227
+ id: string;
3228
+ score: number;
3229
+ }>;
3230
+ /** Check if a document exists in the index. */
3231
+ has(id: string): boolean;
3232
+ }
3233
+
3234
+ export { AGENT_ROLES, AccountManager, type AddressInfo, type Agent, AgentDeletionService, type AgentMemoryEntry, type AgentMemoryFields, AgentMemoryManager, type AgentMemoryOptions, type AgentMemoryRead, AgentMemoryStore, type AgentRole, AgenticMailClient, type AgenticMailClientOptions, type AgenticMailConfig, type ArchiveAndDeleteOptions, type ArchivedEmail, type Attachment, type AttachmentAdvisory, BRIDGE_OPERATOR_LIVE_WINDOW_MS, type BridgeMailContext, type BridgeWakeError, type BridgeWakePromptArgs, type BridgeWakeResult, type BridgeWakeRoute, type CachedMessage, CloudflareClient, type CreateAgentOptions, type CreateMemoryInput, DEFAULT_AGENT_NAME, DEFAULT_AGENT_ROLE, DEFAULT_SESSION_MAX_AGE_MS, DNSConfigurator, type Database, type DeletionReport, type DeletionSummary, DependencyChecker, DependencyInstaller, type DependencyStatus, type DnsRecord, type DnsSetupResult, type DomainInfo, DomainManager, type DomainModeConfig, type DomainPurchaseResult, DomainPurchaser, type DomainSearchResult, type DomainSetupResult, ELKS_REALTIME_AUDIO_FORMATS, type ElksRealtimeAudioFormat, type ElksRealtimeAudioMessage, type ElksRealtimeByeMessage, type ElksRealtimeHelloMessage, type ElksRealtimeInboundMessage, type ElksRealtimeOutboundMessage, type EmailEnvelope, type EmailRouteAction, type EmailRouteClass, type EmailRouteClassification, type EmailRouteInput, EmailSearchIndex, type FolderInfo, type GatewayConfig, GatewayManager, type GatewayManagerOptions, type GatewayMode, type GatewayStatus, type HostName, type HostSession, type HostSessionResumeMode, type InboundEmail, type InboundSmsEvent, type InboxEvent, type InboxExpungeEvent, type InboxFlagsEvent, type InboxNewEvent, InboxWatcher, type InboxWatcherOptions, type InstallProgress, type LinkAdvisory, type LocalSmtpConfig, MEMORY_CATEGORIES, MailReceiver, type MailReceiverOptions, MailSender, type MailSenderOptions, type MailboxInfo, type MemoryCategory, type MemoryImportance, type MemoryQueryOptions, MemorySearchIndex, type MemorySource, type MemoryStats, type OpenClawPhoneMissionPolicy, type OutboundCategory, type OutboundScanInput, type OutboundScanResult, type OutboundWarning, PHONE_MAX_CONCURRENT_MISSIONS, PHONE_MIN_WEBHOOK_SECRET_LENGTH, PHONE_MISSION_STATES, PHONE_RATE_LIMIT_PER_HOUR, PHONE_RATE_LIMIT_PER_MINUTE, PHONE_REGION_SCOPES, PHONE_SERVER_MAX_ATTEMPTS, PHONE_SERVER_MAX_CALL_DURATION_SECONDS, PHONE_SERVER_MAX_COST_PER_MISSION, PHONE_TASK_MAX_LENGTH, type ParsedAttachment, type ParsedEmail, type ParsedSms, PathTraversalError, type PhoneAlternativePolicy, type PhoneCallMission, type PhoneConfirmPolicy, PhoneManager, type PhoneMissionStartValidationResult, type PhoneMissionState, type PhoneMissionTranscriptEntry, type PhoneMissionValidationIssue, type PhoneMissionValidationResult, type PhoneNumberRisk, PhoneRateLimitError, type PhoneRegionScope, type PhoneTransportConfig, type PhoneTransportProfile, type PhoneTransportProvider, type PhoneTransportValidationResult, PhoneWebhookAuthError, type PhoneWebhookResult, type PlanBridgeWakeArgs, type PurchasedDomain, REDACTED, RELAY_PRESETS, RelayBridge, type RelayBridgeOptions, type RelayConfig, RelayGateway, type RelayProvider, type RelaySearchResult, type ResumeErrorClassificationOptions, SPAM_THRESHOLD, type SafeJoinOptions, type SanitizeDetection, type SanitizeResult, type SearchCriteria, type SearchableEmail, type SecurityAdvisory, type SendMailOptions, type SendResult, type SendResultWithRaw, type SendSmsInput, type SendSmsResult, ServiceManager, type ServiceStatus, type SetupConfig, SetupManager, type SetupResult, type Severity, type SmsConfig, SmsManager, type SmsMessage, SmsPoller, type SmsProvider, type SpamCategory, type SpamResult, type SpamRuleMatch, StalwartAdmin, type StalwartAdminOptions, type StalwartPrincipal, type StartPhoneCallOptions, type StartPhoneCallResult, type StartPhoneMissionInput, TELEPHONY_TRANSPORT_CAPABILITIES, type TelephonyTransportCapability, ThreadCache, type ThreadCacheEntry, type ThreadCacheOptions, type ThreadIdInput, type TunnelConfig, TunnelManager, UnsafeApiUrlError, type UpdateMemoryInput, type ValidatedPhoneMissionStart, WARNING_THRESHOLD, type WatcherOptions, assertWithinBase, bridgeWakeErrorMessage, bridgeWakeLastSeenAgeMs, buildApiUrl, buildElksAudioMessage, buildElksByeMessage, buildElksHandshakeMessages, buildElksInterruptMessage, buildElksListeningMessage, buildElksSendingMessage, buildInboundSecurityAdvisory, buildPhoneTransportConfig, classifyEmailRoute, classifyPhoneNumberRisk, classifyResumeError, closeDatabase, composeBridgeWakePrompt, createTestDatabase, debug, debugWarn, ensureDataDir, extractVerificationCode, flushTelemetry, forgetHostSession, getDatabase, getOperatorEmail, getSmsProvider, hostSessionStoragePath, inferPhoneRegion, isInternalEmail, isLoopbackMailHost, isPhoneRegionAllowed, isSessionFresh, isValidPhoneNumber, loadHostSession, mapProviderSmsStatus, normalizeAddress, normalizePhoneNumber, normalizeSubject, operatorPrefsStoragePath, parseElksRealtimeMessage, parseEmail, parseGoogleVoiceSms, planBridgeWake, recordToolCall, redactObject, redactPhoneTransportConfig, redactSecret, redactSmsConfig, resolveConfig, resolveTlsRejectUnauthorized, safeJoin, sanitizeEmail, saveConfig, saveHostSession, scanOutboundEmail, scoreEmail, setOperatorEmail, setTelemetryVersion, shouldSkipBridgeWakeForLiveOperator, startRelayBridge, stem, threadIdFor, tokenize, tryJoin, validateApiUrl, validatePhoneMissionPolicy, validatePhoneMissionStart, validatePhoneTransportProfile };
package/dist/index.d.ts CHANGED
@@ -3022,4 +3022,213 @@ declare class AgentMemoryStore {
3022
3022
  renderForPrompt(memory: AgentMemoryRead | null): string;
3023
3023
  }
3024
3024
 
3025
- export { AGENT_ROLES, AccountManager, type AddressInfo, type Agent, AgentDeletionService, type AgentMemoryFields, type AgentMemoryOptions, type AgentMemoryRead, AgentMemoryStore, type AgentRole, AgenticMailClient, type AgenticMailClientOptions, type AgenticMailConfig, type ArchiveAndDeleteOptions, type ArchivedEmail, type Attachment, type AttachmentAdvisory, BRIDGE_OPERATOR_LIVE_WINDOW_MS, type BridgeMailContext, type BridgeWakeError, type BridgeWakePromptArgs, type BridgeWakeResult, type BridgeWakeRoute, type CachedMessage, CloudflareClient, type CreateAgentOptions, DEFAULT_AGENT_NAME, DEFAULT_AGENT_ROLE, DEFAULT_SESSION_MAX_AGE_MS, DNSConfigurator, type Database, type DeletionReport, type DeletionSummary, DependencyChecker, DependencyInstaller, type DependencyStatus, type DnsRecord, type DnsSetupResult, type DomainInfo, DomainManager, type DomainModeConfig, type DomainPurchaseResult, DomainPurchaser, type DomainSearchResult, type DomainSetupResult, ELKS_REALTIME_AUDIO_FORMATS, type ElksRealtimeAudioFormat, type ElksRealtimeAudioMessage, type ElksRealtimeByeMessage, type ElksRealtimeHelloMessage, type ElksRealtimeInboundMessage, type ElksRealtimeOutboundMessage, type EmailEnvelope, type EmailRouteAction, type EmailRouteClass, type EmailRouteClassification, type EmailRouteInput, EmailSearchIndex, type FolderInfo, type GatewayConfig, GatewayManager, type GatewayManagerOptions, type GatewayMode, type GatewayStatus, type HostName, type HostSession, type HostSessionResumeMode, type InboundEmail, type InboundSmsEvent, type InboxEvent, type InboxExpungeEvent, type InboxFlagsEvent, type InboxNewEvent, InboxWatcher, type InboxWatcherOptions, type InstallProgress, type LinkAdvisory, type LocalSmtpConfig, MailReceiver, type MailReceiverOptions, MailSender, type MailSenderOptions, type MailboxInfo, type OpenClawPhoneMissionPolicy, type OutboundCategory, type OutboundScanInput, type OutboundScanResult, type OutboundWarning, PHONE_MAX_CONCURRENT_MISSIONS, PHONE_MIN_WEBHOOK_SECRET_LENGTH, PHONE_MISSION_STATES, PHONE_RATE_LIMIT_PER_HOUR, PHONE_RATE_LIMIT_PER_MINUTE, PHONE_REGION_SCOPES, PHONE_SERVER_MAX_ATTEMPTS, PHONE_SERVER_MAX_CALL_DURATION_SECONDS, PHONE_SERVER_MAX_COST_PER_MISSION, PHONE_TASK_MAX_LENGTH, type ParsedAttachment, type ParsedEmail, type ParsedSms, PathTraversalError, type PhoneAlternativePolicy, type PhoneCallMission, type PhoneConfirmPolicy, PhoneManager, type PhoneMissionStartValidationResult, type PhoneMissionState, type PhoneMissionTranscriptEntry, type PhoneMissionValidationIssue, type PhoneMissionValidationResult, type PhoneNumberRisk, PhoneRateLimitError, type PhoneRegionScope, type PhoneTransportConfig, type PhoneTransportProfile, type PhoneTransportProvider, type PhoneTransportValidationResult, PhoneWebhookAuthError, type PhoneWebhookResult, type PlanBridgeWakeArgs, type PurchasedDomain, REDACTED, RELAY_PRESETS, RelayBridge, type RelayBridgeOptions, type RelayConfig, RelayGateway, type RelayProvider, type RelaySearchResult, type ResumeErrorClassificationOptions, SPAM_THRESHOLD, type SafeJoinOptions, type SanitizeDetection, type SanitizeResult, type SearchCriteria, type SearchableEmail, type SecurityAdvisory, type SendMailOptions, type SendResult, type SendResultWithRaw, type SendSmsInput, type SendSmsResult, ServiceManager, type ServiceStatus, type SetupConfig, SetupManager, type SetupResult, type Severity, type SmsConfig, SmsManager, type SmsMessage, SmsPoller, type SmsProvider, type SpamCategory, type SpamResult, type SpamRuleMatch, StalwartAdmin, type StalwartAdminOptions, type StalwartPrincipal, type StartPhoneCallOptions, type StartPhoneCallResult, type StartPhoneMissionInput, TELEPHONY_TRANSPORT_CAPABILITIES, type TelephonyTransportCapability, ThreadCache, type ThreadCacheEntry, type ThreadCacheOptions, type ThreadIdInput, type TunnelConfig, TunnelManager, UnsafeApiUrlError, type ValidatedPhoneMissionStart, WARNING_THRESHOLD, type WatcherOptions, assertWithinBase, bridgeWakeErrorMessage, bridgeWakeLastSeenAgeMs, buildApiUrl, buildElksAudioMessage, buildElksByeMessage, buildElksHandshakeMessages, buildElksInterruptMessage, buildElksListeningMessage, buildElksSendingMessage, buildInboundSecurityAdvisory, buildPhoneTransportConfig, classifyEmailRoute, classifyPhoneNumberRisk, classifyResumeError, closeDatabase, composeBridgeWakePrompt, createTestDatabase, debug, debugWarn, ensureDataDir, extractVerificationCode, flushTelemetry, forgetHostSession, getDatabase, getOperatorEmail, getSmsProvider, hostSessionStoragePath, inferPhoneRegion, isInternalEmail, isLoopbackMailHost, isPhoneRegionAllowed, isSessionFresh, isValidPhoneNumber, loadHostSession, mapProviderSmsStatus, normalizeAddress, normalizePhoneNumber, normalizeSubject, operatorPrefsStoragePath, parseElksRealtimeMessage, parseEmail, parseGoogleVoiceSms, planBridgeWake, recordToolCall, redactObject, redactPhoneTransportConfig, redactSecret, redactSmsConfig, resolveConfig, resolveTlsRejectUnauthorized, safeJoin, sanitizeEmail, saveConfig, saveHostSession, scanOutboundEmail, scoreEmail, setOperatorEmail, setTelemetryVersion, shouldSkipBridgeWakeForLiveOperator, startRelayBridge, threadIdFor, tryJoin, validateApiUrl, validatePhoneMissionPolicy, validatePhoneMissionStart, validatePhoneTransportProfile };
3025
+ /**
3026
+ * Agent Memory Manager — persistent, evolving per-agent memory.
3027
+ *
3028
+ * Ported from the AgenticMail Enterprise engine memory system and
3029
+ * adapted for the open-source single-tenant package: the multi-tenant
3030
+ * `orgId` / organization concepts have been removed (memory here is
3031
+ * personal to each agent), the database layer is the built-in
3032
+ * `node:sqlite` `Database`, and agent deletion fully purges memory.
3033
+ *
3034
+ * Each agent gets a growing knowledge store that evolves over time,
3035
+ * the way a human employee learns on the job:
3036
+ * - Category-based organisation (knowledge, preference, correction,
3037
+ * skill, context, reflection, …).
3038
+ * - Importance levels (critical / high / normal / low).
3039
+ * - Confidence scores that decay for entries left unaccessed.
3040
+ * - Access tracking so frequently-used knowledge ranks higher.
3041
+ * - `generateMemoryContext()` — ranks + renders memory as a markdown
3042
+ * block for injection into an agent's prompt (or a voice session).
3043
+ * - Pruning of expired / low-confidence entries.
3044
+ *
3045
+ * Design: an in-memory `Map` + BM25F search index fronts the
3046
+ * `agent_memory` SQLite table. Reads hit memory; writes update both.
3047
+ */
3048
+
3049
+ type MemoryCategory = 'knowledge' | 'interaction_pattern' | 'preference' | 'correction' | 'skill' | 'context' | 'reflection' | 'session_learning' | 'system_notice';
3050
+ type MemoryImportance = 'critical' | 'high' | 'normal' | 'low';
3051
+ type MemorySource = 'interaction' | 'self_reflection' | 'correction' | 'system' | 'context_compaction' | 'transfer';
3052
+ declare const MEMORY_CATEGORIES: Record<MemoryCategory, {
3053
+ label: string;
3054
+ description: string;
3055
+ }>;
3056
+ interface AgentMemoryEntry {
3057
+ id: string;
3058
+ agentId: string;
3059
+ category: MemoryCategory;
3060
+ title: string;
3061
+ content: string;
3062
+ source: MemorySource;
3063
+ importance: MemoryImportance;
3064
+ confidence: number;
3065
+ accessCount: number;
3066
+ lastAccessedAt?: string;
3067
+ expiresAt?: string;
3068
+ tags: string[];
3069
+ metadata: Record<string, any>;
3070
+ createdAt: string;
3071
+ updatedAt: string;
3072
+ }
3073
+ interface MemoryStats {
3074
+ totalEntries: number;
3075
+ byCategory: Record<string, number>;
3076
+ byImportance: Record<string, number>;
3077
+ bySource: Record<string, number>;
3078
+ avgConfidence: number;
3079
+ }
3080
+ /** Input shape for createMemory — id, timestamps, accessCount, and some fields have defaults. */
3081
+ type CreateMemoryInput = Omit<AgentMemoryEntry, 'id' | 'createdAt' | 'updatedAt' | 'accessCount' | 'confidence' | 'tags' | 'metadata' | 'lastAccessedAt' | 'expiresAt'> & {
3082
+ confidence?: number;
3083
+ tags?: string[];
3084
+ metadata?: Record<string, any>;
3085
+ lastAccessedAt?: string;
3086
+ expiresAt?: string;
3087
+ };
3088
+ /** Input shape for updateMemory — partial updates merged with existing entry. */
3089
+ type UpdateMemoryInput = Partial<Omit<AgentMemoryEntry, 'id' | 'agentId' | 'createdAt'>>;
3090
+ /** Query options for filtering memory entries. */
3091
+ interface MemoryQueryOptions {
3092
+ agentId: string;
3093
+ category?: string;
3094
+ importance?: string;
3095
+ source?: string;
3096
+ query?: string;
3097
+ limit?: number;
3098
+ }
3099
+ declare class AgentMemoryManager {
3100
+ private db;
3101
+ private memories;
3102
+ /** Per-agent index: agentId → Set of memory IDs for O(1) agent lookups */
3103
+ private agentIndex;
3104
+ /** Full-text search index (BM25F + stemming + inverted index) */
3105
+ private searchIndex;
3106
+ private initialized;
3107
+ constructor(db: Database);
3108
+ private ensureTable;
3109
+ /** Run a write statement, swallowing errors with a log (memory must never crash a caller). */
3110
+ private dbRun;
3111
+ private dbAll;
3112
+ private loadFromDb;
3113
+ /** Add a memory ID to the per-agent index. */
3114
+ private indexAdd;
3115
+ /** Remove a memory ID from the per-agent index. */
3116
+ private indexRemove;
3117
+ /** Get all memory entries for an agent via the index. */
3118
+ private getAgentMemories;
3119
+ /** Store a memory with minimal input — the common "just remember this" case. */
3120
+ storeMemory(agentId: string, opts: {
3121
+ content: string;
3122
+ category?: string;
3123
+ importance?: string;
3124
+ confidence?: number;
3125
+ title?: string;
3126
+ tags?: string[];
3127
+ }): Promise<AgentMemoryEntry>;
3128
+ /** Search memories by text query, sorted by relevance. */
3129
+ recall(agentId: string, query: string, limit?: number): Promise<AgentMemoryEntry[]>;
3130
+ /** Create a new memory entry with auto-generated id + timestamps. */
3131
+ createMemory(input: CreateMemoryInput): Promise<AgentMemoryEntry>;
3132
+ /** Update an existing memory entry by merging provided fields. */
3133
+ updateMemory(id: string, updates: UpdateMemoryInput): Promise<AgentMemoryEntry | null>;
3134
+ /** Delete a single memory entry. Returns true if it existed. */
3135
+ deleteMemory(id: string): Promise<boolean>;
3136
+ /**
3137
+ * Purge every memory entry belonging to an agent — Map, per-agent
3138
+ * index, search index, and the database row. Called when an agent is
3139
+ * deleted so no orphaned memory is left behind.
3140
+ * Returns the number of entries removed.
3141
+ */
3142
+ deleteAgentMemories(agentId: string): Promise<number>;
3143
+ /** Retrieve a single memory entry by id. */
3144
+ getMemory(id: string): Promise<AgentMemoryEntry | undefined>;
3145
+ /** Query an agent's memory with optional category/importance/source filters + text search. */
3146
+ queryMemories(opts: MemoryQueryOptions): Promise<AgentMemoryEntry[]>;
3147
+ /** Memories created within the last N hours for an agent. */
3148
+ getRecentMemories(agentId: string, hours?: number): Promise<AgentMemoryEntry[]>;
3149
+ /** Bump access count + lastAccessedAt for a memory entry. */
3150
+ recordAccess(memoryId: string): Promise<void>;
3151
+ /**
3152
+ * Render an agent's memory as a markdown block for prompt injection.
3153
+ * Ranks entries by confidence × access × recency × importance, with a
3154
+ * BM25F relevance boost when a query is supplied, groups by category,
3155
+ * and truncates to ~maxTokens (estimated at 4 chars/token).
3156
+ */
3157
+ generateMemoryContext(agentId: string, query?: string, maxTokens?: number): Promise<string>;
3158
+ /** Decay confidence for entries unaccessed for 7+ days. Critical entries are exempt. */
3159
+ decayConfidence(agentId: string, decayRate?: number): Promise<number>;
3160
+ /** Prune entries with confidence < 0.1 or past their expiresAt. */
3161
+ pruneExpired(agentId?: string): Promise<number>;
3162
+ /** Aggregate statistics for a specific agent's memory. */
3163
+ getStats(agentId: string): Promise<MemoryStats>;
3164
+ private computeStats;
3165
+ private rowToEntry;
3166
+ }
3167
+
3168
+ declare function stem(word: string): string;
3169
+ /** Tokenize text into stemmed, lowercase terms, filtering stop words. */
3170
+ declare function tokenize(text: string): string[];
3171
+ /**
3172
+ * Pre-built inverted index for fast text search.
3173
+ * Maintained incrementally — no re-indexing needed on queries.
3174
+ *
3175
+ * Structure:
3176
+ * term → Set<docId> (posting list — which docs contain this term)
3177
+ * prefixMap: prefix → Set<stem> (3-char prefixes → full stems for prefix matching)
3178
+ * docs: docId → DocRecord (per-doc weighted TF and length)
3179
+ * idf: term → number (pre-computed IDF, refreshed on mutations)
3180
+ */
3181
+ declare class MemorySearchIndex {
3182
+ /** Posting lists: stemmed term → Set of memory IDs containing it */
3183
+ private postings;
3184
+ /** Per-document metadata for BM25 scoring */
3185
+ private docs;
3186
+ /** Pre-computed IDF values. Stale flag triggers lazy recomputation. */
3187
+ private idf;
3188
+ private idfStale;
3189
+ /** 3-character prefix map for prefix matching: prefix → Set of full stems */
3190
+ private prefixMap;
3191
+ /** Total weighted document length (for computing average) */
3192
+ private totalWeightedLen;
3193
+ get docCount(): number;
3194
+ get avgDocLen(): number;
3195
+ /**
3196
+ * Index a memory entry. Extracts stems from title, content, and tags
3197
+ * with field-specific weighting and builds posting lists.
3198
+ */
3199
+ addDocument(id: string, entry: {
3200
+ title: string;
3201
+ content: string;
3202
+ tags: string[];
3203
+ }): void;
3204
+ /** Remove a document from the index. */
3205
+ removeDocument(id: string): void;
3206
+ /** Recompute IDF values for all terms. Called lazily before search. */
3207
+ private refreshIdf;
3208
+ /**
3209
+ * Expand query terms with prefix matches.
3210
+ * "deploy" → ["deploy", "deployment", "deploying", ...] (if they exist in the index)
3211
+ */
3212
+ private expandQueryTerms;
3213
+ /**
3214
+ * Compute bigram proximity boost: if two query terms appear adjacent
3215
+ * in the document's stem sequence, boost the score.
3216
+ */
3217
+ private bigramProximityBoost;
3218
+ /**
3219
+ * Search the index for documents matching a query.
3220
+ * Returns scored results sorted by BM25F relevance.
3221
+ *
3222
+ * @param query - Raw query string
3223
+ * @param candidateIds - Optional: only score these document IDs (for agent-scoped search)
3224
+ * @returns Array of { id, score } sorted by descending score
3225
+ */
3226
+ search(query: string, candidateIds?: Set<string>): Array<{
3227
+ id: string;
3228
+ score: number;
3229
+ }>;
3230
+ /** Check if a document exists in the index. */
3231
+ has(id: string): boolean;
3232
+ }
3233
+
3234
+ export { AGENT_ROLES, AccountManager, type AddressInfo, type Agent, AgentDeletionService, type AgentMemoryEntry, type AgentMemoryFields, AgentMemoryManager, type AgentMemoryOptions, type AgentMemoryRead, AgentMemoryStore, type AgentRole, AgenticMailClient, type AgenticMailClientOptions, type AgenticMailConfig, type ArchiveAndDeleteOptions, type ArchivedEmail, type Attachment, type AttachmentAdvisory, BRIDGE_OPERATOR_LIVE_WINDOW_MS, type BridgeMailContext, type BridgeWakeError, type BridgeWakePromptArgs, type BridgeWakeResult, type BridgeWakeRoute, type CachedMessage, CloudflareClient, type CreateAgentOptions, type CreateMemoryInput, DEFAULT_AGENT_NAME, DEFAULT_AGENT_ROLE, DEFAULT_SESSION_MAX_AGE_MS, DNSConfigurator, type Database, type DeletionReport, type DeletionSummary, DependencyChecker, DependencyInstaller, type DependencyStatus, type DnsRecord, type DnsSetupResult, type DomainInfo, DomainManager, type DomainModeConfig, type DomainPurchaseResult, DomainPurchaser, type DomainSearchResult, type DomainSetupResult, ELKS_REALTIME_AUDIO_FORMATS, type ElksRealtimeAudioFormat, type ElksRealtimeAudioMessage, type ElksRealtimeByeMessage, type ElksRealtimeHelloMessage, type ElksRealtimeInboundMessage, type ElksRealtimeOutboundMessage, type EmailEnvelope, type EmailRouteAction, type EmailRouteClass, type EmailRouteClassification, type EmailRouteInput, EmailSearchIndex, type FolderInfo, type GatewayConfig, GatewayManager, type GatewayManagerOptions, type GatewayMode, type GatewayStatus, type HostName, type HostSession, type HostSessionResumeMode, type InboundEmail, type InboundSmsEvent, type InboxEvent, type InboxExpungeEvent, type InboxFlagsEvent, type InboxNewEvent, InboxWatcher, type InboxWatcherOptions, type InstallProgress, type LinkAdvisory, type LocalSmtpConfig, MEMORY_CATEGORIES, MailReceiver, type MailReceiverOptions, MailSender, type MailSenderOptions, type MailboxInfo, type MemoryCategory, type MemoryImportance, type MemoryQueryOptions, MemorySearchIndex, type MemorySource, type MemoryStats, type OpenClawPhoneMissionPolicy, type OutboundCategory, type OutboundScanInput, type OutboundScanResult, type OutboundWarning, PHONE_MAX_CONCURRENT_MISSIONS, PHONE_MIN_WEBHOOK_SECRET_LENGTH, PHONE_MISSION_STATES, PHONE_RATE_LIMIT_PER_HOUR, PHONE_RATE_LIMIT_PER_MINUTE, PHONE_REGION_SCOPES, PHONE_SERVER_MAX_ATTEMPTS, PHONE_SERVER_MAX_CALL_DURATION_SECONDS, PHONE_SERVER_MAX_COST_PER_MISSION, PHONE_TASK_MAX_LENGTH, type ParsedAttachment, type ParsedEmail, type ParsedSms, PathTraversalError, type PhoneAlternativePolicy, type PhoneCallMission, type PhoneConfirmPolicy, PhoneManager, type PhoneMissionStartValidationResult, type PhoneMissionState, type PhoneMissionTranscriptEntry, type PhoneMissionValidationIssue, type PhoneMissionValidationResult, type PhoneNumberRisk, PhoneRateLimitError, type PhoneRegionScope, type PhoneTransportConfig, type PhoneTransportProfile, type PhoneTransportProvider, type PhoneTransportValidationResult, PhoneWebhookAuthError, type PhoneWebhookResult, type PlanBridgeWakeArgs, type PurchasedDomain, REDACTED, RELAY_PRESETS, RelayBridge, type RelayBridgeOptions, type RelayConfig, RelayGateway, type RelayProvider, type RelaySearchResult, type ResumeErrorClassificationOptions, SPAM_THRESHOLD, type SafeJoinOptions, type SanitizeDetection, type SanitizeResult, type SearchCriteria, type SearchableEmail, type SecurityAdvisory, type SendMailOptions, type SendResult, type SendResultWithRaw, type SendSmsInput, type SendSmsResult, ServiceManager, type ServiceStatus, type SetupConfig, SetupManager, type SetupResult, type Severity, type SmsConfig, SmsManager, type SmsMessage, SmsPoller, type SmsProvider, type SpamCategory, type SpamResult, type SpamRuleMatch, StalwartAdmin, type StalwartAdminOptions, type StalwartPrincipal, type StartPhoneCallOptions, type StartPhoneCallResult, type StartPhoneMissionInput, TELEPHONY_TRANSPORT_CAPABILITIES, type TelephonyTransportCapability, ThreadCache, type ThreadCacheEntry, type ThreadCacheOptions, type ThreadIdInput, type TunnelConfig, TunnelManager, UnsafeApiUrlError, type UpdateMemoryInput, type ValidatedPhoneMissionStart, WARNING_THRESHOLD, type WatcherOptions, assertWithinBase, bridgeWakeErrorMessage, bridgeWakeLastSeenAgeMs, buildApiUrl, buildElksAudioMessage, buildElksByeMessage, buildElksHandshakeMessages, buildElksInterruptMessage, buildElksListeningMessage, buildElksSendingMessage, buildInboundSecurityAdvisory, buildPhoneTransportConfig, classifyEmailRoute, classifyPhoneNumberRisk, classifyResumeError, closeDatabase, composeBridgeWakePrompt, createTestDatabase, debug, debugWarn, ensureDataDir, extractVerificationCode, flushTelemetry, forgetHostSession, getDatabase, getOperatorEmail, getSmsProvider, hostSessionStoragePath, inferPhoneRegion, isInternalEmail, isLoopbackMailHost, isPhoneRegionAllowed, isSessionFresh, isValidPhoneNumber, loadHostSession, mapProviderSmsStatus, normalizeAddress, normalizePhoneNumber, normalizeSubject, operatorPrefsStoragePath, parseElksRealtimeMessage, parseEmail, parseGoogleVoiceSms, planBridgeWake, recordToolCall, redactObject, redactPhoneTransportConfig, redactSecret, redactSmsConfig, resolveConfig, resolveTlsRejectUnauthorized, safeJoin, sanitizeEmail, saveConfig, saveHostSession, scanOutboundEmail, scoreEmail, setOperatorEmail, setTelemetryVersion, shouldSkipBridgeWakeForLiveOperator, startRelayBridge, stem, threadIdFor, tokenize, tryJoin, validateApiUrl, validatePhoneMissionPolicy, validatePhoneMissionStart, validatePhoneTransportProfile };