@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.
@@ -1,6 +1,6 @@
1
- export { E as EVENT_BUDGETS, S as SessionManager, d as SessionManagerOptions, e as Skill, f as SkillAgentOptions, g as SkillAgentResult, h as SkillLoader, i as SkillMeta, j as SkillRefLoader, l as createSkillAgent, m as getBudgetWarningMessage, n as getEventBudget, o as getInterruptConfig, r as resumeSkillAgent } from '../index-wLhxy6Gb.js';
1
+ export { E as EVENT_BUDGETS, S as SessionManager, e as SessionManagerOptions, f as Skill, g as SkillAgentOptions, h as SkillAgentResult, i as SkillLoader, j as SkillMeta, k as SkillRefLoader, m as createSkillAgent, p as getBudgetWarningMessage, q as getEventBudget, r as getInterruptConfig, t as resumeSkillAgent } from '../index-D-Ahuo6F.js';
2
2
  export { Command } from '@langchain/langgraph';
3
- export { P as PersistenceMode, d as SessionMetadata, e as SessionRecord } from '../firestore-checkpointer-DxbQ10ve.js';
3
+ export { P as PersistenceMode, S as SessionMetadata, e as SessionRecord } from '../firestore-checkpointer-CkNKXoun.js';
4
4
  import '@almadar/llm';
5
5
  import '../orbital-subagent-cNfTLdXQ.js';
6
6
  import '@langchain/core/tools';
@@ -9,4 +9,5 @@ import '../api-types-BW_58thJ.js';
9
9
  import '@almadar/core/types';
10
10
  import '@langchain/langgraph-checkpoint';
11
11
  import '@almadar/core';
12
+ import '@langchain/core/messages';
12
13
  import '@langchain/core/runnables';
@@ -3258,9 +3258,13 @@ var SessionManager = class {
3258
3258
  constructor(options = {}) {
3259
3259
  this.firestoreCheckpointer = null;
3260
3260
  this.firestoreSessionStore = null;
3261
+ this.memoryManager = null;
3262
+ this.compactionConfig = null;
3261
3263
  this.mode = options.mode ?? "memory";
3262
3264
  this.memoryBackend = new MemorySessionBackend();
3263
3265
  this.memoryCheckpointers = /* @__PURE__ */ new Map();
3266
+ this.memoryManager = options.memoryManager ?? null;
3267
+ this.compactionConfig = options.compactionConfig ?? null;
3264
3268
  if (this.mode === "firestore" && options.firestoreDb) {
3265
3269
  this.firestoreCheckpointer = new FirestoreCheckpointer({ db: options.firestoreDb });
3266
3270
  this.firestoreSessionStore = new FirestoreSessionStore({ db: options.firestoreDb });
@@ -3360,6 +3364,260 @@ var SessionManager = class {
3360
3364
  }
3361
3365
  return this.memoryBackend.list();
3362
3366
  }
3367
+ // ============================================================================
3368
+ // Session → Memory Sync (GAP-002D)
3369
+ // ============================================================================
3370
+ /**
3371
+ * Sync a completed session to orbital memory.
3372
+ * This enables the agent to learn from past sessions.
3373
+ *
3374
+ * @param threadId - The session thread ID
3375
+ * @param userId - The user ID for memory association
3376
+ * @param sessionData - Additional session data to record
3377
+ * @returns Promise that resolves when sync is complete
3378
+ */
3379
+ async syncSessionToMemory(threadId, userId, sessionData) {
3380
+ if (!this.memoryManager) {
3381
+ console.warn("[SessionManager] No memory manager configured, skipping session sync");
3382
+ return;
3383
+ }
3384
+ const metadata = this.get(threadId);
3385
+ if (!metadata) {
3386
+ console.warn(`[SessionManager] Session ${threadId} not found, skipping sync`);
3387
+ return;
3388
+ }
3389
+ try {
3390
+ await this.memoryManager.recordGeneration(userId, {
3391
+ threadId,
3392
+ prompt: sessionData.inputDescription,
3393
+ skill: metadata.skill,
3394
+ generatedSchema: sessionData.generatedOrbital ? { name: sessionData.generatedOrbital } : void 0,
3395
+ patterns: sessionData.patternsUsed ?? [],
3396
+ entities: sessionData.entities ?? [],
3397
+ success: sessionData.success,
3398
+ completedAt: /* @__PURE__ */ new Date()
3399
+ });
3400
+ if (sessionData.patternsUsed && sessionData.patternsUsed.length > 0) {
3401
+ await this.memoryManager.updateUserPreferences(userId, {
3402
+ preferredPatterns: sessionData.patternsUsed,
3403
+ commonEntities: sessionData.entities
3404
+ });
3405
+ }
3406
+ if (sessionData.entities && sessionData.entities.length > 0) {
3407
+ await this.memoryManager.updateProjectContext(sessionData.appId, {
3408
+ userId,
3409
+ existingEntities: sessionData.entities
3410
+ });
3411
+ }
3412
+ console.log(`[SessionManager] Session ${threadId} synced to memory for user ${userId}`);
3413
+ } catch (error) {
3414
+ console.error("[SessionManager] Failed to sync session to memory:", error);
3415
+ }
3416
+ }
3417
+ // ============================================================================
3418
+ // Interrupt → Memory Sync (GAP-003: Interrupt Memory)
3419
+ // ============================================================================
3420
+ /**
3421
+ * Record an interrupt decision to memory.
3422
+ * This enables learning from HITL (Human-in-the-Loop) decisions.
3423
+ *
3424
+ * @param sessionId - The session thread ID
3425
+ * @param userId - The user who made the decision
3426
+ * @param interruptData - The interrupt decision data
3427
+ * @returns Promise that resolves when sync is complete
3428
+ */
3429
+ async recordInterruptDecision(sessionId, userId, interruptData) {
3430
+ if (!this.memoryManager) {
3431
+ console.warn("[SessionManager] No memory manager configured, skipping interrupt sync");
3432
+ return;
3433
+ }
3434
+ try {
3435
+ await this.memoryManager.recordInterruptDecision(sessionId, userId, interruptData);
3436
+ console.log(`[SessionManager] Interrupt recorded for user ${userId}: ${interruptData.toolName} ${interruptData.decision}`);
3437
+ } catch (error) {
3438
+ console.error("[SessionManager] Failed to record interrupt:", error);
3439
+ }
3440
+ }
3441
+ /**
3442
+ * Get interrupt history for a session.
3443
+ */
3444
+ async getSessionInterrupts(sessionId) {
3445
+ if (!this.memoryManager) {
3446
+ return [];
3447
+ }
3448
+ return this.memoryManager.getSessionInterrupts(sessionId);
3449
+ }
3450
+ /**
3451
+ * Check if a tool should be auto-approved for a user.
3452
+ */
3453
+ async shouldAutoApproveTool(userId, toolName) {
3454
+ if (!this.memoryManager) {
3455
+ return false;
3456
+ }
3457
+ return this.memoryManager.shouldAutoApproveTool(userId, toolName);
3458
+ }
3459
+ // ============================================================================
3460
+ // Checkpoint Management (GAP-004: Checkpoint → Memory)
3461
+ // ============================================================================
3462
+ /**
3463
+ * Record a checkpoint to memory for learning.
3464
+ *
3465
+ * @param userId - The user who owns this checkpoint
3466
+ * @param checkpointData - Checkpoint information
3467
+ * @returns Promise that resolves when checkpoint is recorded
3468
+ */
3469
+ async recordCheckpoint(userId, checkpointData) {
3470
+ if (!this.memoryManager) {
3471
+ console.warn("[SessionManager] No memory manager configured, skipping checkpoint record");
3472
+ return;
3473
+ }
3474
+ try {
3475
+ await this.memoryManager.recordCheckpoint(userId, checkpointData);
3476
+ console.log(`[SessionManager] Checkpoint ${checkpointData.checkpointId} recorded for user ${userId}`);
3477
+ } catch (error) {
3478
+ console.error("[SessionManager] Failed to record checkpoint:", error);
3479
+ }
3480
+ }
3481
+ /**
3482
+ * Record a rollback to a checkpoint.
3483
+ *
3484
+ * @param userId - The user who performed the rollback
3485
+ * @param checkpointId - The checkpoint rolled back to
3486
+ * @param reason - Optional reason for rollback
3487
+ * @returns Promise that resolves when rollback is recorded
3488
+ */
3489
+ async recordRollback(userId, checkpointId, reason) {
3490
+ if (!this.memoryManager) {
3491
+ console.warn("[SessionManager] No memory manager configured, skipping rollback record");
3492
+ return;
3493
+ }
3494
+ try {
3495
+ await this.memoryManager.recordRollback(userId, checkpointId, reason);
3496
+ console.log(`[SessionManager] Rollback to ${checkpointId} recorded for user ${userId}`);
3497
+ } catch (error) {
3498
+ console.error("[SessionManager] Failed to record rollback:", error);
3499
+ }
3500
+ }
3501
+ /**
3502
+ * Mark a checkpoint as successful (terminal state).
3503
+ *
3504
+ * @param userId - The user who owns this checkpoint
3505
+ * @param checkpointId - The checkpoint that was successful
3506
+ * @returns Promise that resolves when success is recorded
3507
+ */
3508
+ async markCheckpointSuccessful(userId, checkpointId) {
3509
+ if (!this.memoryManager) {
3510
+ console.warn("[SessionManager] No memory manager configured, skipping success mark");
3511
+ return;
3512
+ }
3513
+ try {
3514
+ await this.memoryManager.markCheckpointSuccessful(userId, checkpointId);
3515
+ console.log(`[SessionManager] Checkpoint ${checkpointId} marked as successful for user ${userId}`);
3516
+ } catch (error) {
3517
+ console.error("[SessionManager] Failed to mark checkpoint as successful:", error);
3518
+ }
3519
+ }
3520
+ /**
3521
+ * Get checkpoint history for a thread.
3522
+ *
3523
+ * @param threadId - The thread to get checkpoints for
3524
+ * @returns Array of checkpoint records
3525
+ */
3526
+ async getThreadCheckpoints(threadId) {
3527
+ if (!this.memoryManager) {
3528
+ return [];
3529
+ }
3530
+ return this.memoryManager.getThreadCheckpoints(threadId);
3531
+ }
3532
+ /**
3533
+ * Get frequently rolled-back checkpoints (problem areas).
3534
+ *
3535
+ * @param userId - The user to get problem checkpoints for
3536
+ * @param minRollbackCount - Minimum rollback count (default: 2)
3537
+ * @returns Array of checkpoint records with rollback issues
3538
+ */
3539
+ async getProblemCheckpoints(userId, minRollbackCount = 2) {
3540
+ if (!this.memoryManager) {
3541
+ return [];
3542
+ }
3543
+ return this.memoryManager.getProblemCheckpoints(userId, minRollbackCount);
3544
+ }
3545
+ // ============================================================================
3546
+ // Context Compaction (GAP-005)
3547
+ // ============================================================================
3548
+ /**
3549
+ * Get the context compaction configuration.
3550
+ * @returns The compaction configuration or null if not configured.
3551
+ */
3552
+ getCompactionConfig() {
3553
+ return this.compactionConfig;
3554
+ }
3555
+ /**
3556
+ * Check if a session's messages need compaction based on token count.
3557
+ * Uses character-based estimation for quick checks.
3558
+ *
3559
+ * @param messages - Array of messages to check
3560
+ * @returns True if compaction is recommended
3561
+ */
3562
+ shouldCompactMessages(messages) {
3563
+ if (!this.compactionConfig) {
3564
+ return false;
3565
+ }
3566
+ const totalChars = messages.reduce((sum, msg) => {
3567
+ const content = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content);
3568
+ return sum + content.length;
3569
+ }, 0);
3570
+ const estimatedTokens = totalChars / 4;
3571
+ const threshold = this.compactionConfig.maxTokens ?? 15e4;
3572
+ return estimatedTokens > threshold * 0.8;
3573
+ }
3574
+ /**
3575
+ * Record a compaction event for a session.
3576
+ * This helps track when and why compaction occurs.
3577
+ *
3578
+ * @param threadId - The session thread ID
3579
+ * @param originalMessageCount - Number of messages before compaction
3580
+ * @param compactedMessageCount - Number of messages after compaction
3581
+ * @param reason - Reason for compaction
3582
+ */
3583
+ async recordCompaction(threadId, originalMessageCount, compactedMessageCount, reason) {
3584
+ if (!this.memoryManager) {
3585
+ console.warn("[SessionManager] No memory manager configured, skipping compaction record");
3586
+ return;
3587
+ }
3588
+ try {
3589
+ const metadata = this.get(threadId);
3590
+ if (metadata) {
3591
+ const compactionInfo = {
3592
+ timestamp: Date.now(),
3593
+ originalMessageCount,
3594
+ compactedMessageCount,
3595
+ reason: reason ?? "token_limit"
3596
+ };
3597
+ const meta = metadata;
3598
+ const existingCompactions = meta.compactions ?? [];
3599
+ meta.compactions = [...existingCompactions, compactionInfo];
3600
+ this.store(threadId, metadata);
3601
+ }
3602
+ console.log(`[SessionManager] Compaction recorded for ${threadId}: ${originalMessageCount} \u2192 ${compactedMessageCount} messages`);
3603
+ } catch (error) {
3604
+ console.error("[SessionManager] Failed to record compaction:", error);
3605
+ }
3606
+ }
3607
+ /**
3608
+ * Get compaction history for a session.
3609
+ *
3610
+ * @param threadId - The session thread ID
3611
+ * @returns Array of compaction events
3612
+ */
3613
+ getCompactionHistory(threadId) {
3614
+ const metadata = this.get(threadId);
3615
+ if (!metadata) {
3616
+ return [];
3617
+ }
3618
+ const meta = metadata;
3619
+ return meta.compactions ?? [];
3620
+ }
3363
3621
  };
3364
3622
 
3365
3623
  // src/agent/interrupt-config.ts