supaclaw 1.0.0

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.
@@ -0,0 +1,735 @@
1
+ import { ContextBudget, ContextWindow, getContextStats } from './context-manager';
2
+ export interface OpenClawMemoryConfig {
3
+ supabaseUrl: string;
4
+ supabaseKey: string;
5
+ agentId: string;
6
+ embeddingProvider?: 'openai' | 'voyage' | 'none';
7
+ openaiApiKey?: string;
8
+ embeddingModel?: string;
9
+ }
10
+ export interface Session {
11
+ id: string;
12
+ agent_id: string;
13
+ user_id?: string;
14
+ channel?: string;
15
+ started_at: string;
16
+ ended_at?: string;
17
+ summary?: string;
18
+ metadata: Record<string, unknown>;
19
+ }
20
+ export interface Message {
21
+ id: string;
22
+ session_id: string;
23
+ role: 'user' | 'assistant' | 'system' | 'tool';
24
+ content: string;
25
+ created_at: string;
26
+ token_count?: number;
27
+ metadata: Record<string, unknown>;
28
+ }
29
+ export interface Memory {
30
+ id: string;
31
+ agent_id: string;
32
+ user_id?: string;
33
+ category?: string;
34
+ content: string;
35
+ importance: number;
36
+ source_session_id?: string;
37
+ created_at: string;
38
+ updated_at: string;
39
+ expires_at?: string;
40
+ embedding?: number[];
41
+ metadata: Record<string, unknown>;
42
+ }
43
+ export interface Entity {
44
+ id: string;
45
+ agent_id: string;
46
+ entity_type: string;
47
+ name: string;
48
+ aliases?: string[];
49
+ description?: string;
50
+ properties: Record<string, unknown>;
51
+ first_seen_at: string;
52
+ last_seen_at: string;
53
+ mention_count: number;
54
+ }
55
+ export interface Task {
56
+ id: string;
57
+ agent_id: string;
58
+ user_id?: string;
59
+ title: string;
60
+ description?: string;
61
+ status: 'pending' | 'in_progress' | 'blocked' | 'done';
62
+ priority: number;
63
+ due_at?: string;
64
+ completed_at?: string;
65
+ parent_task_id?: string;
66
+ metadata: Record<string, unknown>;
67
+ created_at: string;
68
+ updated_at: string;
69
+ }
70
+ export interface Learning {
71
+ id: string;
72
+ agent_id: string;
73
+ category: 'error' | 'correction' | 'improvement' | 'capability_gap';
74
+ trigger: string;
75
+ lesson: string;
76
+ action?: string;
77
+ severity: 'info' | 'warning' | 'critical';
78
+ source_session_id?: string;
79
+ applied_count: number;
80
+ created_at: string;
81
+ metadata: Record<string, unknown>;
82
+ }
83
+ export interface EntityRelationship {
84
+ id: string;
85
+ agent_id: string;
86
+ source_entity_id: string;
87
+ target_entity_id: string;
88
+ relationship_type: string;
89
+ properties: Record<string, unknown>;
90
+ first_seen_at: string;
91
+ last_seen_at: string;
92
+ mention_count: number;
93
+ confidence: number;
94
+ source_session_id?: string;
95
+ metadata: Record<string, unknown>;
96
+ }
97
+ export declare class OpenClawMemory {
98
+ private supabase;
99
+ private agentId;
100
+ private config;
101
+ private openai?;
102
+ constructor(config: OpenClawMemoryConfig);
103
+ /**
104
+ * Generate embedding for text using configured provider
105
+ */
106
+ private generateEmbedding;
107
+ /**
108
+ * Calculate cosine similarity between two vectors
109
+ */
110
+ private cosineSimilarity;
111
+ /**
112
+ * Initialize database tables (run once)
113
+ */
114
+ initialize(): Promise<void>;
115
+ /**
116
+ * Start a new conversation session
117
+ */
118
+ startSession(opts?: {
119
+ userId?: string;
120
+ channel?: string;
121
+ metadata?: Record<string, unknown>;
122
+ }): Promise<Session>;
123
+ /**
124
+ * End a session with optional summary
125
+ */
126
+ endSession(sessionId: string, opts?: {
127
+ summary?: string;
128
+ autoSummarize?: boolean;
129
+ }): Promise<Session>;
130
+ /**
131
+ * Generate an AI summary of a session
132
+ */
133
+ generateSessionSummary(sessionId: string): Promise<string>;
134
+ /**
135
+ * Resume a session (useful for continuing interrupted conversations)
136
+ */
137
+ resumeSession(sessionId: string): Promise<{
138
+ session: Session;
139
+ messages: Message[];
140
+ context: string;
141
+ }>;
142
+ /**
143
+ * Search sessions by date range
144
+ */
145
+ searchSessions(opts?: {
146
+ userId?: string;
147
+ startDate?: string;
148
+ endDate?: string;
149
+ channel?: string;
150
+ limit?: number;
151
+ offset?: number;
152
+ }): Promise<Session[]>;
153
+ /**
154
+ * Export a session to markdown
155
+ */
156
+ exportSessionToMarkdown(sessionId: string): Promise<string>;
157
+ /**
158
+ * Import a session from markdown
159
+ */
160
+ importSessionFromMarkdown(markdown: string, opts?: {
161
+ userId?: string;
162
+ channel?: string;
163
+ }): Promise<Session>;
164
+ /**
165
+ * Extract memories from a session
166
+ */
167
+ extractMemoriesFromSession(sessionId: string, opts?: {
168
+ minImportance?: number;
169
+ autoExtract?: boolean;
170
+ }): Promise<Memory[]>;
171
+ /**
172
+ * Count tokens in a session
173
+ */
174
+ countSessionTokens(sessionId: string): Promise<{
175
+ totalTokens: number;
176
+ messageCount: number;
177
+ averageTokensPerMessage: number;
178
+ }>;
179
+ /**
180
+ * Get a session by ID
181
+ */
182
+ getSession(sessionId: string): Promise<Session | null>;
183
+ /**
184
+ * Get recent sessions
185
+ */
186
+ getRecentSessions(opts?: {
187
+ userId?: string;
188
+ limit?: number;
189
+ }): Promise<Session[]>;
190
+ /**
191
+ * Add a message to a session
192
+ */
193
+ addMessage(sessionId: string, message: {
194
+ role: 'user' | 'assistant' | 'system' | 'tool';
195
+ content: string;
196
+ tokenCount?: number;
197
+ metadata?: Record<string, unknown>;
198
+ }): Promise<Message>;
199
+ /**
200
+ * Get messages from a session
201
+ */
202
+ getMessages(sessionId: string, opts?: {
203
+ limit?: number;
204
+ offset?: number;
205
+ }): Promise<Message[]>;
206
+ /**
207
+ * Store a long-term memory with semantic embedding
208
+ */
209
+ remember(memory: {
210
+ content: string;
211
+ category?: string;
212
+ importance?: number;
213
+ userId?: string;
214
+ sessionId?: string;
215
+ expiresAt?: string;
216
+ metadata?: Record<string, unknown>;
217
+ }): Promise<Memory>;
218
+ /**
219
+ * Search memories using vector similarity (semantic search)
220
+ */
221
+ recall(query: string, opts?: {
222
+ userId?: string;
223
+ category?: string;
224
+ limit?: number;
225
+ minImportance?: number;
226
+ minSimilarity?: number;
227
+ }): Promise<Memory[]>;
228
+ /**
229
+ * Hybrid search: combines semantic similarity and keyword matching
230
+ * Returns deduplicated results sorted by relevance score
231
+ */
232
+ hybridRecall(query: string, opts?: {
233
+ userId?: string;
234
+ category?: string;
235
+ limit?: number;
236
+ minImportance?: number;
237
+ vectorWeight?: number;
238
+ keywordWeight?: number;
239
+ }): Promise<Memory[]>;
240
+ /**
241
+ * Delete a memory
242
+ */
243
+ forget(memoryId: string): Promise<void>;
244
+ /**
245
+ * Get all memories (paginated)
246
+ */
247
+ getMemories(opts?: {
248
+ userId?: string;
249
+ category?: string;
250
+ limit?: number;
251
+ offset?: number;
252
+ }): Promise<Memory[]>;
253
+ /**
254
+ * Find memories similar to an existing memory
255
+ * Useful for context expansion and deduplication
256
+ */
257
+ findSimilarMemories(memoryId: string, opts?: {
258
+ minSimilarity?: number;
259
+ limit?: number;
260
+ }): Promise<Memory[]>;
261
+ /**
262
+ * Create a task
263
+ */
264
+ createTask(task: {
265
+ title: string;
266
+ description?: string;
267
+ priority?: number;
268
+ dueAt?: string;
269
+ userId?: string;
270
+ parentTaskId?: string;
271
+ metadata?: Record<string, unknown>;
272
+ }): Promise<Task>;
273
+ /**
274
+ * Update a task
275
+ */
276
+ updateTask(taskId: string, updates: Partial<{
277
+ title: string;
278
+ description: string;
279
+ status: 'pending' | 'in_progress' | 'blocked' | 'done';
280
+ priority: number;
281
+ dueAt: string;
282
+ metadata: Record<string, unknown>;
283
+ }>): Promise<Task>;
284
+ /**
285
+ * Get tasks
286
+ */
287
+ getTasks(opts?: {
288
+ status?: string;
289
+ userId?: string;
290
+ limit?: number;
291
+ }): Promise<Task[]>;
292
+ /**
293
+ * Delete a task
294
+ */
295
+ deleteTask(taskId: string): Promise<void>;
296
+ /**
297
+ * Get subtasks of a parent task
298
+ */
299
+ getSubtasks(parentTaskId: string): Promise<Task[]>;
300
+ /**
301
+ * Get task with all its subtasks (hierarchical)
302
+ */
303
+ getTaskWithSubtasks(taskId: string): Promise<{
304
+ task: Task;
305
+ subtasks: Task[];
306
+ }>;
307
+ /**
308
+ * Get upcoming tasks (due soon)
309
+ */
310
+ getUpcomingTasks(opts?: {
311
+ userId?: string;
312
+ hoursAhead?: number;
313
+ }): Promise<Task[]>;
314
+ /**
315
+ * Record a learning
316
+ */
317
+ learn(learning: {
318
+ category: 'error' | 'correction' | 'improvement' | 'capability_gap';
319
+ trigger: string;
320
+ lesson: string;
321
+ action?: string;
322
+ severity?: 'info' | 'warning' | 'critical';
323
+ sessionId?: string;
324
+ metadata?: Record<string, unknown>;
325
+ }): Promise<Learning>;
326
+ /**
327
+ * Get learnings
328
+ */
329
+ getLearnings(opts?: {
330
+ category?: string;
331
+ severity?: string;
332
+ limit?: number;
333
+ }): Promise<Learning[]>;
334
+ /**
335
+ * Search learnings by topic for context
336
+ */
337
+ searchLearnings(query: string, opts?: {
338
+ limit?: number;
339
+ }): Promise<Learning[]>;
340
+ /**
341
+ * Mark a learning as applied (increments applied_count)
342
+ */
343
+ applyLearning(learningId: string): Promise<Learning>;
344
+ /**
345
+ * Add a task dependency (taskId depends on dependsOnTaskId)
346
+ */
347
+ addTaskDependency(taskId: string, dependsOnTaskId: string): Promise<void>;
348
+ /**
349
+ * Remove a task dependency
350
+ */
351
+ removeTaskDependency(taskId: string, dependsOnTaskId: string): Promise<void>;
352
+ /**
353
+ * Get task dependencies
354
+ */
355
+ getTaskDependencies(taskId: string): Promise<Task[]>;
356
+ /**
357
+ * Check if a task is blocked by uncompleted dependencies
358
+ */
359
+ isTaskBlocked(taskId: string): Promise<boolean>;
360
+ /**
361
+ * Get tasks that are ready to start (no blocking dependencies)
362
+ */
363
+ getReadyTasks(opts?: {
364
+ userId?: string;
365
+ }): Promise<Task[]>;
366
+ /**
367
+ * Create a task template
368
+ */
369
+ createTaskTemplate(template: {
370
+ name: string;
371
+ description?: string;
372
+ tasks: Array<{
373
+ title: string;
374
+ description?: string;
375
+ priority?: number;
376
+ estimatedDuration?: string;
377
+ dependencies?: number[];
378
+ }>;
379
+ metadata?: Record<string, unknown>;
380
+ }): Promise<{
381
+ id: string;
382
+ }>;
383
+ /**
384
+ * Get all task templates
385
+ */
386
+ getTaskTemplates(): Promise<Array<{
387
+ id: string;
388
+ name: string;
389
+ description?: string;
390
+ tasks: Array<{
391
+ title: string;
392
+ description?: string;
393
+ priority?: number;
394
+ estimatedDuration?: string;
395
+ dependencies?: number[];
396
+ }>;
397
+ }>>;
398
+ /**
399
+ * Apply a task template (create all tasks from template)
400
+ */
401
+ applyTaskTemplate(templateId: string, opts?: {
402
+ userId?: string;
403
+ startDate?: string;
404
+ metadata?: Record<string, unknown>;
405
+ }): Promise<Task[]>;
406
+ /**
407
+ * Get tasks that need reminders (due soon but not done)
408
+ */
409
+ getTasksNeedingReminders(opts?: {
410
+ userId?: string;
411
+ hoursAhead?: number;
412
+ }): Promise<Array<Task & {
413
+ timeUntilDue: number;
414
+ }>>;
415
+ /**
416
+ * Format task reminder message
417
+ */
418
+ formatTaskReminder(task: Task, timeUntilDue: number): string;
419
+ /**
420
+ * Detect patterns in learnings (common categories, triggers, lessons)
421
+ */
422
+ detectLearningPatterns(): Promise<{
423
+ commonCategories: Array<{
424
+ category: string;
425
+ count: number;
426
+ }>;
427
+ commonTriggers: Array<{
428
+ pattern: string;
429
+ count: number;
430
+ }>;
431
+ recentTrends: Array<{
432
+ week: string;
433
+ count: number;
434
+ severity: string;
435
+ }>;
436
+ topLessons: Array<{
437
+ lesson: string;
438
+ applied: number;
439
+ id: string;
440
+ }>;
441
+ }>;
442
+ /**
443
+ * Get learning recommendations based on current context
444
+ */
445
+ getLearningRecommendations(context: string, limit?: number): Promise<Learning[]>;
446
+ /**
447
+ * Find similar learnings using embeddings
448
+ */
449
+ findSimilarLearnings(learningId: string, opts?: {
450
+ limit?: number;
451
+ threshold?: number;
452
+ }): Promise<Array<Learning & {
453
+ similarity: number;
454
+ }>>;
455
+ /**
456
+ * Export learnings to markdown report
457
+ */
458
+ exportLearningsReport(opts?: {
459
+ category?: string;
460
+ severity?: string;
461
+ since?: string;
462
+ }): Promise<string>;
463
+ /**
464
+ * Export learnings to JSON
465
+ */
466
+ exportLearningsJSON(opts?: {
467
+ category?: string;
468
+ severity?: string;
469
+ since?: string;
470
+ }): Promise<object>;
471
+ /**
472
+ * Extract entities from text using AI
473
+ */
474
+ extractEntities(text: string, opts?: {
475
+ sessionId?: string;
476
+ }): Promise<Entity[]>;
477
+ /**
478
+ * Create an entity
479
+ */
480
+ createEntity(entity: {
481
+ entityType: string;
482
+ name: string;
483
+ aliases?: string[];
484
+ description?: string;
485
+ properties?: Record<string, unknown>;
486
+ }): Promise<Entity>;
487
+ /**
488
+ * Update an entity
489
+ */
490
+ updateEntity(entityId: string, updates: Partial<{
491
+ name: string;
492
+ aliases: string[];
493
+ description: string;
494
+ properties: Record<string, unknown>;
495
+ lastSeenAt: string;
496
+ }>): Promise<Entity>;
497
+ /**
498
+ * Find an entity by name or alias
499
+ */
500
+ findEntity(nameOrAlias: string): Promise<Entity | null>;
501
+ /**
502
+ * Search entities
503
+ */
504
+ searchEntities(opts?: {
505
+ query?: string;
506
+ entityType?: string;
507
+ limit?: number;
508
+ }): Promise<Entity[]>;
509
+ /**
510
+ * Merge two entities (deduplication)
511
+ */
512
+ mergeEntities(primaryId: string, duplicateId: string): Promise<Entity>;
513
+ /**
514
+ * Create or update a relationship between entities
515
+ */
516
+ createEntityRelationship(rel: {
517
+ sourceEntityId: string;
518
+ targetEntityId: string;
519
+ relationshipType: string;
520
+ properties?: Record<string, unknown>;
521
+ confidence?: number;
522
+ sessionId?: string;
523
+ metadata?: Record<string, unknown>;
524
+ }): Promise<EntityRelationship>;
525
+ /**
526
+ * Get relationships for an entity
527
+ */
528
+ getEntityRelationships(entityId: string, opts?: {
529
+ direction?: 'outgoing' | 'incoming' | 'both';
530
+ relationshipType?: string;
531
+ minConfidence?: number;
532
+ limit?: number;
533
+ }): Promise<Array<{
534
+ relationship: EntityRelationship;
535
+ relatedEntity: Entity;
536
+ direction: 'outgoing' | 'incoming';
537
+ }>>;
538
+ /**
539
+ * Find related entities through graph traversal
540
+ */
541
+ findRelatedEntities(entityId: string, opts?: {
542
+ maxDepth?: number;
543
+ minConfidence?: number;
544
+ }): Promise<Array<{
545
+ entityId: string;
546
+ entityName: string;
547
+ entityType: string;
548
+ relationshipPath: string[];
549
+ totalConfidence: number;
550
+ depth: number;
551
+ }>>;
552
+ /**
553
+ * Get entity network statistics
554
+ */
555
+ getEntityNetworkStats(): Promise<{
556
+ totalEntities: number;
557
+ totalRelationships: number;
558
+ avgConnectionsPerEntity: number;
559
+ mostConnectedEntity?: {
560
+ id: string;
561
+ name: string;
562
+ connectionCount: number;
563
+ };
564
+ }>;
565
+ /**
566
+ * Extract entities and relationships from text using AI
567
+ */
568
+ extractEntitiesWithRelationships(text: string, opts?: {
569
+ sessionId?: string;
570
+ }): Promise<{
571
+ entities: Entity[];
572
+ relationships: EntityRelationship[];
573
+ }>;
574
+ /**
575
+ * Delete a relationship
576
+ */
577
+ deleteEntityRelationship(relationshipId: string): Promise<void>;
578
+ /**
579
+ * Search relationships
580
+ */
581
+ searchRelationships(opts?: {
582
+ relationshipType?: string;
583
+ minConfidence?: number;
584
+ limit?: number;
585
+ }): Promise<EntityRelationship[]>;
586
+ /**
587
+ * Get relevant context for a query
588
+ * Combines memories, recent messages, and entities
589
+ */
590
+ getContext(query: string, opts?: {
591
+ userId?: string;
592
+ sessionId?: string;
593
+ maxMemories?: number;
594
+ maxMessages?: number;
595
+ }): Promise<{
596
+ memories: Memory[];
597
+ recentMessages: Message[];
598
+ summary: string;
599
+ }>;
600
+ /**
601
+ * Build an optimized context window with token budgeting
602
+ * Implements smart context selection and lost-in-middle mitigation
603
+ */
604
+ buildOptimizedContext(opts: {
605
+ query: string;
606
+ sessionId?: string;
607
+ userId?: string;
608
+ modelContextSize?: number;
609
+ model?: string;
610
+ useLostInMiddleFix?: boolean;
611
+ recencyWeight?: number;
612
+ importanceWeight?: number;
613
+ customBudget?: ContextBudget;
614
+ }): Promise<{
615
+ window: ContextWindow;
616
+ formatted: string;
617
+ stats: ReturnType<typeof getContextStats>;
618
+ }>;
619
+ /**
620
+ * Get smart context with automatic budget management
621
+ * Simplified version of buildOptimizedContext for common use cases
622
+ */
623
+ getSmartContext(query: string, opts?: {
624
+ sessionId?: string;
625
+ userId?: string;
626
+ model?: string;
627
+ }): Promise<string>;
628
+ /**
629
+ * Estimate token usage for a session
630
+ */
631
+ estimateSessionTokenUsage(sessionId: string): Promise<{
632
+ messages: number;
633
+ memories: number;
634
+ total: number;
635
+ contextSize: string;
636
+ }>;
637
+ /**
638
+ * Test context window with different budgets
639
+ * Useful for optimization and debugging
640
+ */
641
+ testContextBudgets(query: string, opts?: {
642
+ sessionId?: string;
643
+ userId?: string;
644
+ models?: string[];
645
+ }): Promise<Array<{
646
+ model: string;
647
+ budget: ContextBudget;
648
+ stats: ReturnType<typeof getContextStats>;
649
+ }>>;
650
+ /**
651
+ * Apply importance decay to memories
652
+ * Reduces importance over time to prevent old memories from dominating
653
+ */
654
+ decayMemoryImportance(opts?: {
655
+ userId?: string;
656
+ decayRate?: number;
657
+ minImportance?: number;
658
+ olderThanDays?: number;
659
+ }): Promise<{
660
+ updated: number;
661
+ avgDecay: number;
662
+ }>;
663
+ /**
664
+ * Consolidate similar memories
665
+ * Merge duplicate/similar memories to reduce clutter
666
+ */
667
+ consolidateMemories(opts?: {
668
+ userId?: string;
669
+ similarityThreshold?: number;
670
+ category?: string;
671
+ limit?: number;
672
+ }): Promise<{
673
+ merged: number;
674
+ kept: number;
675
+ }>;
676
+ /**
677
+ * Version a memory (create historical snapshot)
678
+ */
679
+ versionMemory(memoryId: string): Promise<{
680
+ memory: Memory;
681
+ versionId: string;
682
+ }>;
683
+ /**
684
+ * Get memory version history
685
+ */
686
+ getMemoryVersions(memoryId: string): Promise<Array<{
687
+ version: string;
688
+ timestamp: string;
689
+ content: string;
690
+ importance: number;
691
+ }>>;
692
+ /**
693
+ * Tag memories for organization
694
+ */
695
+ tagMemory(memoryId: string, tags: string[]): Promise<Memory>;
696
+ /**
697
+ * Remove tags from memory
698
+ */
699
+ untagMemory(memoryId: string, tags: string[]): Promise<Memory>;
700
+ /**
701
+ * Search memories by tags
702
+ */
703
+ searchMemoriesByTags(tags: string[], opts?: {
704
+ userId?: string;
705
+ matchAll?: boolean;
706
+ limit?: number;
707
+ }): Promise<Memory[]>;
708
+ /**
709
+ * Auto-cleanup old sessions
710
+ * Archive or delete sessions older than a threshold
711
+ */
712
+ cleanupOldSessions(opts?: {
713
+ olderThanDays?: number;
714
+ action?: 'archive' | 'delete';
715
+ keepSummaries?: boolean;
716
+ userId?: string;
717
+ }): Promise<{
718
+ archived?: number;
719
+ deleted?: number;
720
+ }>;
721
+ /**
722
+ * Get cleanup statistics
723
+ */
724
+ getCleanupStats(): Promise<{
725
+ totalSessions: number;
726
+ archivedSessions: number;
727
+ oldSessions: number;
728
+ totalMessages: number;
729
+ orphanedMessages: number;
730
+ }>;
731
+ }
732
+ export { ContextBudget, ContextWindow, ContextItem, createContextBudget, createAdaptiveBudget, buildContextWindow, formatContextWindow, getContextStats, getBudgetForModel, estimateTokens, estimateTokensAccurate } from './context-manager';
733
+ export { ClawdbotMemoryIntegration, ClawdbotConfig, MessageContext, createClawdbotIntegration, createLoggingMiddleware } from './clawdbot-integration';
734
+ export { OpenClawError, DatabaseError, EmbeddingError, ValidationError, RateLimitError, RetryOptions, CircuitBreaker, retry, wrapDatabaseOperation, wrapEmbeddingOperation, validateInput, safeJsonParse, withTimeout, gracefulFallback, batchWithErrorHandling } from './error-handling';
735
+ export default OpenClawMemory;