@almadar/agent 1.1.4 → 1.2.1

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.
@@ -181,4 +181,4 @@ declare class FirestoreCheckpointer extends BaseCheckpointSaver {
181
181
  deleteThread(threadId: string): Promise<void>;
182
182
  }
183
183
 
184
- export { FirestoreCheckpointer as F, type PersistenceMode as P, type Session as S, type FirestoreCheckpointerOptions as a, type FirestoreDb as b, type FirestoreTimestamp as c, type SessionMetadata as d, type SessionRecord as e };
184
+ export { FirestoreCheckpointer as F, type PersistenceMode as P, type SessionMetadata as S, type FirestoreCheckpointerOptions as a, type FirestoreDb as b, type FirestoreTimestamp as c, type Session as d, type SessionRecord as e };
@@ -1,72 +1,177 @@
1
1
  import { LLMProvider } from '@almadar/llm';
2
2
  import { S as SubagentEventCallback, O as OrbitalCompleteCallback, D as DomainOrbitalCompleteCallback } from './orbital-subagent-cNfTLdXQ.js';
3
3
  import { BaseCheckpointSaver } from '@langchain/langgraph-checkpoint';
4
- import { P as PersistenceMode, b as FirestoreDb$1, d as SessionMetadata, e as SessionRecord } from './firestore-checkpointer-DxbQ10ve.js';
4
+ import { P as PersistenceMode, b as FirestoreDb$1, S as SessionMetadata, e as SessionRecord } from './firestore-checkpointer-CkNKXoun.js';
5
5
  import { OrbitalSchema } from '@almadar/core';
6
+ import { BaseMessage } from '@langchain/core/messages';
6
7
  import '@langchain/langgraph';
7
8
 
8
9
  /**
9
- * Session Manager
10
+ * Context Compaction for DeepAgent
10
11
  *
11
- * Unified session management API with pluggable persistence backends.
12
- * Supports in-memory (development) and Firestore (production) backends.
12
+ * Provides middleware to manage context length in long-running agent sessions.
13
+ * Uses @langchain/core's trimMessages to keep context within token limits.
14
+ *
15
+ * @packageDocumentation
13
16
  */
14
17
 
15
- interface SessionManagerOptions {
16
- /**
17
- * Persistence mode.
18
- * @default 'memory'
19
- */
20
- mode?: PersistenceMode;
21
- /**
22
- * Firestore database instance. Required when mode is 'firestore'.
23
- */
24
- firestoreDb?: FirestoreDb$1;
25
- }
26
18
  /**
27
- * Unified session management for agent sessions.
28
- *
29
- * Handles both session metadata and LangGraph checkpointers.
19
+ * Configuration for context compaction.
30
20
  */
31
- declare class SessionManager {
32
- private mode;
33
- private memoryBackend;
34
- private memoryCheckpointers;
35
- private firestoreCheckpointer;
36
- private firestoreSessionStore;
37
- constructor(options?: SessionManagerOptions);
21
+ interface ContextCompactionConfig {
38
22
  /**
39
- * Get the persistence mode.
23
+ * Maximum number of tokens before triggering compaction.
24
+ * Default: 150000 (leaves headroom for Claude's 200K context)
40
25
  */
41
- getMode(): PersistenceMode;
26
+ maxTokens?: number;
42
27
  /**
43
- * Get or create a checkpointer for a session.
28
+ * Number of recent messages to always keep.
29
+ * Default: 10
44
30
  */
45
- getCheckpointer(threadId: string): BaseCheckpointSaver<any>;
31
+ keepRecentMessages?: number;
46
32
  /**
47
- * Store session metadata.
33
+ * Whether to include the system message in trimming.
34
+ * Default: false (system message is always kept)
48
35
  */
49
- store(threadId: string, metadata: SessionMetadata): void;
36
+ includeSystem?: boolean;
50
37
  /**
51
- * Get session metadata (sync, memory only).
52
- */
53
- get(threadId: string): SessionMetadata | undefined;
54
- /**
55
- * Get session metadata (async, supports Firestore).
56
- */
57
- getAsync(threadId: string): Promise<SessionMetadata | undefined>;
58
- /**
59
- * Clear a session's checkpointer and metadata.
38
+ * Strategy for trimming: 'first' keeps first messages, 'last' keeps last messages.
39
+ * Default: 'last'
60
40
  */
61
- clear(threadId: string): boolean;
62
- /**
63
- * List all sessions (sync, memory only).
64
- */
65
- list(): SessionRecord[];
66
- /**
67
- * List all sessions (async, supports Firestore).
68
- */
69
- listAsync(): Promise<SessionRecord[]>;
41
+ strategy?: 'first' | 'last';
42
+ }
43
+ /**
44
+ * Default configuration for context compaction.
45
+ */
46
+ declare const DEFAULT_COMPACTION_CONFIG: Required<ContextCompactionConfig>;
47
+ /**
48
+ * Check if messages need compaction based on estimated token count.
49
+ */
50
+ declare function needsCompaction(messages: BaseMessage[], threshold?: number): boolean;
51
+ /**
52
+ * Create a message summarizer prompt for compacting old context.
53
+ */
54
+ declare function createSummaryPrompt(messages: BaseMessage[]): string;
55
+ /**
56
+ * Estimate token count for messages using character-based heuristic.
57
+ */
58
+ declare function estimateTokens(messages: BaseMessage[]): number;
59
+
60
+ /**
61
+ * Memory System Types
62
+ *
63
+ * Additional types for the memory system beyond the core orbital types.
64
+ */
65
+ /**
66
+ * User feedback on a generation session
67
+ */
68
+ interface UserFeedback {
69
+ /** Unique feedback ID */
70
+ feedbackId: string;
71
+ /** Session this feedback is for */
72
+ sessionId: string;
73
+ /** User who gave the feedback */
74
+ userId: string;
75
+ /** Type of feedback */
76
+ type: 'positive' | 'negative' | 'correction' | 'suggestion';
77
+ /** Optional comment */
78
+ comment?: string;
79
+ /** Suggested correction or improvement */
80
+ suggestion?: string;
81
+ /** Timestamp of feedback */
82
+ timestamp: Date;
83
+ }
84
+ /**
85
+ * Pattern affinity - tracks how well patterns work for a user
86
+ */
87
+ interface PatternAffinity {
88
+ /** User ID */
89
+ userId: string;
90
+ /** Pattern ID */
91
+ patternId: string;
92
+ /** How many times used */
93
+ usageCount: number;
94
+ /** Successful uses */
95
+ successCount: number;
96
+ /** Failed uses */
97
+ failureCount: number;
98
+ /** Contexts where this pattern was used */
99
+ contexts?: {
100
+ entityType?: string;
101
+ useCase?: string;
102
+ }[];
103
+ /** Last time this pattern was used */
104
+ lastUsedAt: Date;
105
+ /** When tracking started */
106
+ createdAt: Date;
107
+ }
108
+ /**
109
+ * Checkpoint record - tracks checkpoint history for learning
110
+ */
111
+ interface CheckpointRecord {
112
+ /** Unique checkpoint ID */
113
+ checkpointId: string;
114
+ /** Thread/session ID */
115
+ threadId: string;
116
+ /** User who owns this checkpoint */
117
+ userId: string;
118
+ /** Parent checkpoint ID (for rollback tracking) */
119
+ parentCheckpointId?: string;
120
+ /** Checkpoint metadata */
121
+ metadata: {
122
+ step?: number;
123
+ skill?: string;
124
+ status?: string;
125
+ [key: string]: unknown;
126
+ };
127
+ /** When checkpoint was created */
128
+ createdAt: Date;
129
+ /** Number of times rolled back to this checkpoint */
130
+ rollbackCount: number;
131
+ /** Whether this checkpoint was a successful outcome */
132
+ wasSuccessful: boolean;
133
+ }
134
+ /**
135
+ * Interrupt record - tracks human-in-the-loop decisions
136
+ */
137
+ interface InterruptRecord {
138
+ /** Unique interrupt ID */
139
+ interruptId: string;
140
+ /** Session this interrupt occurred in */
141
+ sessionId: string;
142
+ /** User who made the decision */
143
+ userId: string;
144
+ /** Tool that was interrupted */
145
+ toolName: string;
146
+ /** Tool arguments that were being executed */
147
+ toolArgs: Record<string, unknown>;
148
+ /** User's decision: approved, rejected, or modified */
149
+ decision: 'approved' | 'rejected' | 'modified';
150
+ /** Modified arguments if decision was 'modified' */
151
+ modifiedArgs?: Record<string, unknown>;
152
+ /** Reason for the decision */
153
+ reason?: string;
154
+ /** Timestamp of the interrupt */
155
+ timestamp: Date;
156
+ }
157
+ /**
158
+ * Tool approval preferences - learned from interrupt history
159
+ */
160
+ interface ToolApprovalPreference {
161
+ /** User ID */
162
+ userId: string;
163
+ /** Tool name */
164
+ toolName: string;
165
+ /** Auto-approve this tool in the future */
166
+ autoApprove: boolean;
167
+ /** Confidence in this preference (0-1) */
168
+ confidence: number;
169
+ /** Number of times this tool has been approved */
170
+ approvedCount: number;
171
+ /** Number of times this tool has been rejected */
172
+ rejectedCount: number;
173
+ /** Last decision timestamp */
174
+ lastDecisionAt: Date;
70
175
  }
71
176
 
72
177
  /**
@@ -124,55 +229,6 @@ type ProjectContext = {
124
229
  lastUpdatedAt: Date;
125
230
  };
126
231
 
127
- /**
128
- * Memory System Types
129
- *
130
- * Additional types for the memory system beyond the core orbital types.
131
- */
132
- /**
133
- * User feedback on a generation session
134
- */
135
- interface UserFeedback {
136
- /** Unique feedback ID */
137
- feedbackId: string;
138
- /** Session this feedback is for */
139
- sessionId: string;
140
- /** User who gave the feedback */
141
- userId: string;
142
- /** Type of feedback */
143
- type: 'positive' | 'negative' | 'correction' | 'suggestion';
144
- /** Optional comment */
145
- comment?: string;
146
- /** Suggested correction or improvement */
147
- suggestion?: string;
148
- /** Timestamp of feedback */
149
- timestamp: Date;
150
- }
151
- /**
152
- * Pattern affinity - tracks how well patterns work for a user
153
- */
154
- interface PatternAffinity {
155
- /** User ID */
156
- userId: string;
157
- /** Pattern ID */
158
- patternId: string;
159
- /** How many times used */
160
- usageCount: number;
161
- /** Successful uses */
162
- successCount: number;
163
- /** Failed uses */
164
- failureCount: number;
165
- /** Contexts where this pattern was used */
166
- contexts?: {
167
- entityType?: string;
168
- useCase?: string;
169
- }[];
170
- /** Last time this pattern was used */
171
- lastUsedAt: Date;
172
- /** When tracking started */
173
- createdAt: Date;
174
- }
175
-
176
232
  /**
177
233
  * Memory Manager - GAP-001: Orbital Memory System
178
234
  *
@@ -258,6 +314,21 @@ interface MemoryManagerOptions {
258
314
  * @default 'agent_memory_feedback'
259
315
  */
260
316
  feedbackCollection?: string;
317
+ /**
318
+ * Collection name for interrupt records
319
+ * @default 'agent_memory_interrupts'
320
+ */
321
+ interruptsCollection?: string;
322
+ /**
323
+ * Collection name for tool approval preferences
324
+ * @default 'agent_memory_tool_preferences'
325
+ */
326
+ toolPreferencesCollection?: string;
327
+ /**
328
+ * Collection name for checkpoint records
329
+ * @default 'agent_memory_checkpoints'
330
+ */
331
+ checkpointsCollection?: string;
261
332
  }
262
333
  declare class MemoryManager {
263
334
  private db;
@@ -266,6 +337,9 @@ declare class MemoryManager {
266
337
  private projectsCollection;
267
338
  private patternsCollection;
268
339
  private feedbackCollection;
340
+ private interruptsCollection;
341
+ private toolPreferencesCollection;
342
+ private checkpointsCollection;
269
343
  constructor(options: MemoryManagerOptions);
270
344
  /**
271
345
  * Get user preferences with defaults
@@ -328,6 +402,266 @@ declare class MemoryManager {
328
402
  private serializeSession;
329
403
  private parseContext;
330
404
  private serializeContext;
405
+ /**
406
+ * Record an interrupt decision for learning
407
+ */
408
+ recordInterruptDecision(sessionId: string, userId: string, interruptData: {
409
+ toolName: string;
410
+ toolArgs: Record<string, unknown>;
411
+ decision: 'approved' | 'rejected' | 'modified';
412
+ modifiedArgs?: Record<string, unknown>;
413
+ reason?: string;
414
+ }): Promise<void>;
415
+ /**
416
+ * Get interrupt history for a session
417
+ */
418
+ getSessionInterrupts(sessionId: string): Promise<InterruptRecord[]>;
419
+ /**
420
+ * Get interrupt history for a user
421
+ */
422
+ getUserInterrupts(userId: string, limit?: number): Promise<InterruptRecord[]>;
423
+ /**
424
+ * Get tool approval preference for a user
425
+ */
426
+ getToolApprovalPreference(userId: string, toolName: string): Promise<ToolApprovalPreference | null>;
427
+ /**
428
+ * Update tool approval preference based on interrupt decisions
429
+ */
430
+ private updateToolApprovalPreference;
431
+ /**
432
+ * Get all tool approval preferences for a user
433
+ */
434
+ getUserToolPreferences(userId: string): Promise<ToolApprovalPreference[]>;
435
+ /**
436
+ * Check if a tool should be auto-approved for a user
437
+ */
438
+ shouldAutoApproveTool(userId: string, toolName: string): Promise<boolean>;
439
+ /**
440
+ * Record a checkpoint for learning
441
+ */
442
+ recordCheckpoint(userId: string, checkpointData: {
443
+ checkpointId: string;
444
+ threadId: string;
445
+ parentCheckpointId?: string;
446
+ metadata?: Record<string, unknown>;
447
+ }): Promise<void>;
448
+ /**
449
+ * Record a rollback to a checkpoint
450
+ */
451
+ recordRollback(userId: string, checkpointId: string, reason?: string): Promise<void>;
452
+ /**
453
+ * Mark a checkpoint as successful (terminal state)
454
+ */
455
+ markCheckpointSuccessful(userId: string, checkpointId: string): Promise<void>;
456
+ /**
457
+ * Get checkpoint history for a user
458
+ */
459
+ getUserCheckpoints(userId: string, limit?: number): Promise<CheckpointRecord[]>;
460
+ /**
461
+ * Get checkpoints for a thread
462
+ */
463
+ getThreadCheckpoints(threadId: string): Promise<CheckpointRecord[]>;
464
+ /**
465
+ * Get frequently rolled-back checkpoints (problem areas)
466
+ */
467
+ getProblemCheckpoints(userId: string, minRollbackCount?: number): Promise<CheckpointRecord[]>;
468
+ /**
469
+ * Get successful checkpoint patterns for learning
470
+ */
471
+ getSuccessfulCheckpoints(userId: string, limit?: number): Promise<CheckpointRecord[]>;
472
+ }
473
+
474
+ interface SessionManagerOptions {
475
+ /**
476
+ * Persistence mode.
477
+ * @default 'memory'
478
+ */
479
+ mode?: PersistenceMode;
480
+ /**
481
+ * Firestore database instance. Required when mode is 'firestore'.
482
+ */
483
+ firestoreDb?: FirestoreDb$1;
484
+ /**
485
+ * Memory manager for session-to-memory sync (GAP-002D).
486
+ * When provided, completed sessions are recorded to orbital memory.
487
+ */
488
+ memoryManager?: MemoryManager;
489
+ /**
490
+ * Context compaction configuration (GAP-005).
491
+ * When provided, enables automatic context length management.
492
+ */
493
+ compactionConfig?: ContextCompactionConfig;
494
+ }
495
+ /**
496
+ * Unified session management for agent sessions.
497
+ *
498
+ * Handles both session metadata and LangGraph checkpointers.
499
+ */
500
+ declare class SessionManager {
501
+ private mode;
502
+ private memoryBackend;
503
+ private memoryCheckpointers;
504
+ private firestoreCheckpointer;
505
+ private firestoreSessionStore;
506
+ private memoryManager;
507
+ private compactionConfig;
508
+ constructor(options?: SessionManagerOptions);
509
+ /**
510
+ * Get the persistence mode.
511
+ */
512
+ getMode(): PersistenceMode;
513
+ /**
514
+ * Get or create a checkpointer for a session.
515
+ */
516
+ getCheckpointer(threadId: string): BaseCheckpointSaver<any>;
517
+ /**
518
+ * Store session metadata.
519
+ */
520
+ store(threadId: string, metadata: SessionMetadata): void;
521
+ /**
522
+ * Get session metadata (sync, memory only).
523
+ */
524
+ get(threadId: string): SessionMetadata | undefined;
525
+ /**
526
+ * Get session metadata (async, supports Firestore).
527
+ */
528
+ getAsync(threadId: string): Promise<SessionMetadata | undefined>;
529
+ /**
530
+ * Clear a session's checkpointer and metadata.
531
+ */
532
+ clear(threadId: string): boolean;
533
+ /**
534
+ * List all sessions (sync, memory only).
535
+ */
536
+ list(): SessionRecord[];
537
+ /**
538
+ * List all sessions (async, supports Firestore).
539
+ */
540
+ listAsync(): Promise<SessionRecord[]>;
541
+ /**
542
+ * Sync a completed session to orbital memory.
543
+ * This enables the agent to learn from past sessions.
544
+ *
545
+ * @param threadId - The session thread ID
546
+ * @param userId - The user ID for memory association
547
+ * @param sessionData - Additional session data to record
548
+ * @returns Promise that resolves when sync is complete
549
+ */
550
+ syncSessionToMemory(threadId: string, userId: string, sessionData: {
551
+ appId: string;
552
+ inputDescription: string;
553
+ generatedOrbital?: string;
554
+ patternsUsed?: string[];
555
+ entities?: string[];
556
+ success: boolean;
557
+ errorMessage?: string;
558
+ }): Promise<void>;
559
+ /**
560
+ * Record an interrupt decision to memory.
561
+ * This enables learning from HITL (Human-in-the-Loop) decisions.
562
+ *
563
+ * @param sessionId - The session thread ID
564
+ * @param userId - The user who made the decision
565
+ * @param interruptData - The interrupt decision data
566
+ * @returns Promise that resolves when sync is complete
567
+ */
568
+ recordInterruptDecision(sessionId: string, userId: string, interruptData: {
569
+ toolName: string;
570
+ toolArgs: Record<string, unknown>;
571
+ decision: 'approved' | 'rejected' | 'modified';
572
+ modifiedArgs?: Record<string, unknown>;
573
+ reason?: string;
574
+ }): Promise<void>;
575
+ /**
576
+ * Get interrupt history for a session.
577
+ */
578
+ getSessionInterrupts(sessionId: string): Promise<InterruptRecord[]>;
579
+ /**
580
+ * Check if a tool should be auto-approved for a user.
581
+ */
582
+ shouldAutoApproveTool(userId: string, toolName: string): Promise<boolean>;
583
+ /**
584
+ * Record a checkpoint to memory for learning.
585
+ *
586
+ * @param userId - The user who owns this checkpoint
587
+ * @param checkpointData - Checkpoint information
588
+ * @returns Promise that resolves when checkpoint is recorded
589
+ */
590
+ recordCheckpoint(userId: string, checkpointData: {
591
+ checkpointId: string;
592
+ threadId: string;
593
+ parentCheckpointId?: string;
594
+ metadata?: Record<string, unknown>;
595
+ }): Promise<void>;
596
+ /**
597
+ * Record a rollback to a checkpoint.
598
+ *
599
+ * @param userId - The user who performed the rollback
600
+ * @param checkpointId - The checkpoint rolled back to
601
+ * @param reason - Optional reason for rollback
602
+ * @returns Promise that resolves when rollback is recorded
603
+ */
604
+ recordRollback(userId: string, checkpointId: string, reason?: string): Promise<void>;
605
+ /**
606
+ * Mark a checkpoint as successful (terminal state).
607
+ *
608
+ * @param userId - The user who owns this checkpoint
609
+ * @param checkpointId - The checkpoint that was successful
610
+ * @returns Promise that resolves when success is recorded
611
+ */
612
+ markCheckpointSuccessful(userId: string, checkpointId: string): Promise<void>;
613
+ /**
614
+ * Get checkpoint history for a thread.
615
+ *
616
+ * @param threadId - The thread to get checkpoints for
617
+ * @returns Array of checkpoint records
618
+ */
619
+ getThreadCheckpoints(threadId: string): Promise<CheckpointRecord[]>;
620
+ /**
621
+ * Get frequently rolled-back checkpoints (problem areas).
622
+ *
623
+ * @param userId - The user to get problem checkpoints for
624
+ * @param minRollbackCount - Minimum rollback count (default: 2)
625
+ * @returns Array of checkpoint records with rollback issues
626
+ */
627
+ getProblemCheckpoints(userId: string, minRollbackCount?: number): Promise<CheckpointRecord[]>;
628
+ /**
629
+ * Get the context compaction configuration.
630
+ * @returns The compaction configuration or null if not configured.
631
+ */
632
+ getCompactionConfig(): ContextCompactionConfig | null;
633
+ /**
634
+ * Check if a session's messages need compaction based on token count.
635
+ * Uses character-based estimation for quick checks.
636
+ *
637
+ * @param messages - Array of messages to check
638
+ * @returns True if compaction is recommended
639
+ */
640
+ shouldCompactMessages(messages: {
641
+ content: string | unknown;
642
+ }[]): boolean;
643
+ /**
644
+ * Record a compaction event for a session.
645
+ * This helps track when and why compaction occurs.
646
+ *
647
+ * @param threadId - The session thread ID
648
+ * @param originalMessageCount - Number of messages before compaction
649
+ * @param compactedMessageCount - Number of messages after compaction
650
+ * @param reason - Reason for compaction
651
+ */
652
+ recordCompaction(threadId: string, originalMessageCount: number, compactedMessageCount: number, reason?: string): Promise<void>;
653
+ /**
654
+ * Get compaction history for a session.
655
+ *
656
+ * @param threadId - The session thread ID
657
+ * @returns Array of compaction events
658
+ */
659
+ getCompactionHistory(threadId: string): Array<{
660
+ timestamp: number;
661
+ originalMessageCount: number;
662
+ compactedMessageCount: number;
663
+ reason: string;
664
+ }>;
331
665
  }
332
666
 
333
667
  /**
@@ -517,4 +851,4 @@ interface SkillMeta {
517
851
  */
518
852
  declare function getInterruptConfig(_skill: SkillMeta): Record<string, boolean>;
519
853
 
520
- export { EVENT_BUDGETS as E, type GenerationSession as G, MemoryManager as M, type PatternAffinity as P, SessionManager as S, type UserPreference as U, type MemoryManagerOptions as a, MemoryOrbitalSchema as b, type ProjectContext as c, type SessionManagerOptions as d, type Skill as e, type SkillAgentOptions as f, type SkillAgentResult as g, type SkillLoader as h, type SkillMeta as i, type SkillRefLoader as j, type UserFeedback as k, createSkillAgent as l, getBudgetWarningMessage as m, getEventBudget as n, getInterruptConfig as o, resumeSkillAgent as r };
854
+ export { type CheckpointRecord as C, DEFAULT_COMPACTION_CONFIG as D, EVENT_BUDGETS as E, type GenerationSession as G, type InterruptRecord as I, MemoryManager as M, type PatternAffinity as P, SessionManager as S, type ToolApprovalPreference as T, type UserPreference as U, type ContextCompactionConfig as a, type MemoryManagerOptions as b, MemoryOrbitalSchema as c, type ProjectContext as d, type SessionManagerOptions as e, type Skill as f, type SkillAgentOptions as g, type SkillAgentResult as h, type SkillLoader as i, type SkillMeta as j, type SkillRefLoader as k, type UserFeedback as l, createSkillAgent as m, createSummaryPrompt as n, estimateTokens as o, getBudgetWarningMessage as p, getEventBudget as q, getInterruptConfig as r, needsCompaction as s, resumeSkillAgent as t };