Skip to content

Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More

18.1 KB
Raw Blame
import { EventEmitter } from 'events';
import type { PendingMessage, PendingMessageWithId } from '../worker-types.js';
import { logger } from '../../utils/logger.js';
import { LIVE_OBSERVER_MAX_AGE_MS, LIVE_OBSERVER_MAX_SESSION_MESSAGES, LIVE_OBSERVER_MAX_TOTAL_MESSAGES } from '../../shared/observer-work-policy.js';

export const IDLE_TIMEOUT_MS = 3 * 60 * 1000;

/**
 * While a drain is idle it waits in slices of at most this length, so a
 * shouldReleaseIdleSlot check (see DrainOptions) is re-evaluated at this
 * cadence instead of only after the full idle timeout (#5376).
 */
const IDLE_WAIT_SLICE_MS = 1_000;

interface BufferedMessage {
  id: number;
  message: PendingMessage;
  claimed: boolean;
  /**
   * Set aside after its batch spent its PaidSendBudget (paid-send-budget.ts):
   * never claimed or resent again, and not counted as pending, so newer work
   * behind it keeps flowing. It stays in RAM, visible to getParkedMessages,
   * until it expires, the session ends, or a new live input needs its slot
   * under the buffer's hard caps (evicted oldest first, and counted).
   */
  parked: boolean;
  /** The `x-client-request-id` of the batch's sends, so a parked message can be traced to them. */
  parkedClientAttemptId?: string;
  enqueuedAt: number;
  bufferedAt: number;
}

export interface DrainOptions {
  sessionDbId: number;
  signal: AbortSignal;
  onIdleTimeout?: () => void;
  idleTimeoutMs?: number;
  /**
   * Checked each time an idle drain finishes a wait slice: return true to
   * end the drain early through the onIdleTimeout path. The production
   * caller passes "another session is parked waiting for a concurrency
   * slot" — an idle generator otherwise holds its slot for the full
   * IDLE_TIMEOUT_MS while parked sessions starve (#5376).
   */
  shouldReleaseIdleSlot?: () => boolean;
}

/**
 * Per-session in-RAM observation buffer. This replaces the durable
 * `pending_messages` SQLite queue (and the BullMQ engine that mirrored it).
 *
 * Why in-RAM and not durable: a buffered message is one tool-use fragment fed
 * to a stateful, non-deterministic reducer (the memory agent batches N
 * tool-uses into M observations using in-memory conversation context). The old
 * durable queue persisted the fragments but threw away the reducer state, so
 * "replaying" pending rows after a crash regenerated different/duplicate
 * observations or looped forever — that was the retry storm. The Claude Code
 * transcript JSONL is the real durable source of truth, and transcript replay
 * can support a separately specified recovery workflow. This buffer holds
 * only bounded live work: no processing state to resurrect on restart and
 * no durable backlog. If the worker dies, the buffer is gone.
 *
 * confirm()/resetClaimed() exist only as in-process control flow within a
 * single live generator pass (drop a stored batch; re-yield a batch that
 * couldn't be stored yet because the memory session id wasn't captured). They
 * never cross a process boundary.
 */
export class SessionMessageBuffer {
  private readonly buffers = new Map<number, BufferedMessage[]>();
  private readonly events = new Map<number, EventEmitter>();
  private readonly seenToolUseIds = new Map<number, Set<string>>();
  private nextId = 1;
  /** Inputs discarded by expiry over this worker's lifetime (#6391). */
  private expiredInputCount = 0;
  /** Parked inputs evicted to make room for live ones over this worker's lifetime. */
  private evictedParkedInputCount = 0;

  constructor(private readonly onMutate?: () => void) {}

  /** Total live inputs discarded by expiry, for the worker's status output. */
  getExpiredInputCount(): number {
    return this.expiredInputCount;
  }

  /** Total parked inputs evicted to make room for live ones, for the worker's status output. */
  getEvictedParkedInputCount(): number {
    return this.evictedParkedInputCount;
  }

  /**
   * Append a message. Returns its id, or 0 for a duplicate/full buffer.
   * Dedup matches the old partial UNIQUE(content_session_id,
   * tool_use_id) index: only observations that carry a toolUseId are deduped,
   * and only against others in the same session for this worker's lifetime.
   */
  enqueue(sessionDbId: number, message: PendingMessage, enqueuedAt = Date.now()): number {
    this.pruneExpired();
    const toolUseId = message.toolUseId;
    if (toolUseId) {
      const seen = this.getSeen(sessionDbId);
      if (seen.has(toolUseId)) {
        return 0;
      }
    }

    // Never build a catch-up obligation. Keep in-flight paid work intact;
    // reject new work when this short-lived buffer is full. Parked messages
    // are diagnostic residue that will never be sent again, so they must not
    // block live work: otherwise a spent paid-send budget silently drops
    // every later event until the parked batch expires. The hard RAM caps
    // still count every entry, parked ones included, so parked entries give
    // up their slots (oldest first) to a live input that has room.
    const sessionLiveCount = (this.buffers.get(sessionDbId) ?? [])
      .filter(message => !message.parked).length;
    if (sessionLiveCount >= LIVE_OBSERVER_MAX_SESSION_MESSAGES
      || this.liveBufferedCount() >= LIVE_OBSERVER_MAX_TOTAL_MESSAGES) {
      logger.debug('QUEUE', 'Live observer buffer full; skipping event', { sessionId: sessionDbId });
      return 0;
    }
    this.evictParkedForRoom(sessionDbId);
    if (toolUseId) this.getSeen(sessionDbId).add(toolUseId);

    const id = this.nextId++;
    this.getList(sessionDbId).push({ id, message, claimed: false, parked: false, enqueuedAt, bufferedAt: Date.now() });
    this.onMutate?.();
    this.signal(sessionDbId);
    return id;
  }

  /** Remove a stored message by id. Returns 1 if found, 0 otherwise. */
  confirm(messageId: number): number {
    for (const list of this.buffers.values()) {
      const idx = list.findIndex(m => m.id === messageId);
      if (idx !== -1) {
        list.splice(idx, 1);
        this.onMutate?.();
        return 1;
      }
    }
    return 0;
  }

  /** Un-claim all messages for a session so the iterator re-yields them. */
  resetClaimed(sessionDbId: number): number {
    const list = this.buffers.get(sessionDbId);
    if (!list) return 0;
    let reset = 0;
    for (const m of list) {
      if (m.claimed) {
        m.claimed = false;
        reset++;
      }
    }
    if (reset > 0) {
      this.pruneExpired();
      this.onMutate?.();
      this.signal(sessionDbId);
    }
    return reset;
  }

  /**
   * Park the given messages of a session: un-claim them and never yield them
   * again. Returns the ids actually parked (already-stored ids are gone).
   */
  park(sessionDbId: number, messageIds: readonly number[], clientAttemptId: string): number[] {
    const wanted = new Set(messageIds);
    const parkedIds: number[] = [];
    for (const m of this.buffers.get(sessionDbId) ?? []) {
      if (wanted.has(m.id) && !m.parked) {
        m.parked = true;
        m.parkedClientAttemptId = clientAttemptId;
        m.claimed = false;
        parkedIds.push(m.id);
      }
    }
    if (parkedIds.length > 0) this.onMutate?.();
    return parkedIds;
  }

  getParkedMessages(sessionDbId: number): Array<{ messageId: number; clientAttemptId: string | undefined }> {
    return (this.buffers.get(sessionDbId) ?? [])
      .filter(m => m.parked)
      .map(m => ({ messageId: m.id, clientAttemptId: m.parkedClientAttemptId }));
  }

  /** Drop everything buffered for a session. */
  clear(sessionDbId: number): number {
    const cleared = this.buffers.get(sessionDbId)?.length ?? 0;
    this.buffers.delete(sessionDbId);
    // Mirror dispose(): drop the dedup set too. Otherwise a clear() not followed
    // by dispose() leaves seenToolUseIds intact, so a later enqueue carrying a
    // previously-seen toolUseId is silently suppressed (returns 0) and lost.
    this.seenToolUseIds.delete(sessionDbId);
    if (cleared > 0) {
      this.onMutate?.();
    }
    return cleared;
  }

  /**
   * Drop everything buffered for a session but keep its dedup set, so neither
   * work already stored nor work just discarded can be enqueued and sent
   * again by a later hook or transcript replay (#5405).
   */
  discardKeepingDedup(sessionDbId: number): number {
    const discarded = this.buffers.get(sessionDbId)?.length ?? 0;
    this.buffers.delete(sessionDbId);
    if (discarded > 0) this.onMutate?.();
    return discarded;
  }

  /**
   * Drop messages outside the request currently in flight, preserving its
   * claimed evidence and every seen tool ID. Re-enabling capture does not
   * authorize another send of a completed, parked, or discarded event.
   */
  clearUnclaimed(sessionDbId: number): number {
    const list = this.buffers.get(sessionDbId);
    if (!list) return 0;
    const kept = list.filter(message => message.claimed);
    const removed = list.filter(message => !message.claimed);
    const cleared = removed.length;
    if (cleared === 0) return 0;

    if (kept.length === 0) {
      this.buffers.delete(sessionDbId);
    } else {
      this.buffers.set(sessionDbId, kept);
    }
    this.onMutate?.();
    return cleared;
  }

  /** Forget a session entirely (buffer, dedup set, event emitter). */
  dispose(sessionDbId: number): void {
    this.buffers.delete(sessionDbId);
    this.seenToolUseIds.delete(sessionDbId);
    this.events.get(sessionDbId)?.removeAllListeners();
    this.events.delete(sessionDbId);
  }

  /** Messages still to be sent: parked ones are excluded, nothing will send them. */
  getPendingCount(sessionDbId: number): number {
    this.pruneExpired();
    return (this.buffers.get(sessionDbId) ?? []).filter(m => !m.parked).length;
  }

  getTotalDepth(): number {
    this.pruneExpired();
    let total = 0;
    for (const list of this.buffers.values()) {
      total += list.filter(m => !m.parked).length;
    }
    return total;
  }

  getMessagesByIds(sessionDbId: number, messageIds: number[]): PendingMessageWithId[] {
    if (messageIds.length === 0) {
      return [];
    }

    const lookup = new Map<number, PendingMessageWithId>();
    for (const buffered of this.buffers.get(sessionDbId) ?? []) {
      lookup.set(buffered.id, {
        ...buffered.message,
        _persistentId: buffered.id,
        _originalTimestamp: buffered.enqueuedAt,
      });
    }

    const messages: PendingMessageWithId[] = [];
    for (const messageId of messageIds) {
      const message = lookup.get(messageId);
      if (message) {
        messages.push(message);
      }
    }
    return messages;
  }

  peekTypes(sessionDbId: number): Array<{ message_type: string; tool_name: string | null }> {
    this.pruneExpired();
    return (this.buffers.get(sessionDbId) ?? []).filter(m => !m.parked).map(m => ({
      message_type: m.message.type,
      tool_name: m.message.tool_name ?? null
    }));
  }

  /**
   * Drain buffered messages as they arrive. Yields one unclaimed message at a
   * time; when the buffer is empty it waits on the per-session event emitter
   * until a new message is enqueued, the abort signal fires, or the idle
   * timeout elapses (which triggers onIdleTimeout and ends the iterator so the
   * SDK subprocess is killed).
   */
  async *drain(options: DrainOptions): AsyncIterableIterator<PendingMessageWithId> {
    const { sessionDbId, signal, onIdleTimeout, idleTimeoutMs = IDLE_TIMEOUT_MS } = options;
    let lastActivityTime = Date.now();

    while (!signal.aborted) {
      const claimed = this.claimNext(sessionDbId);
      if (claimed) {
        yield {
          ...claimed.message,
          _persistentId: claimed.id,
          _originalTimestamp: claimed.enqueuedAt
        };
        // The idle clock starts when the consumer comes back for the next
        // message, so the time it spends answering this one does not eat
        // into the idle window.
        lastActivityTime = Date.now();
        continue;
      }

      const received = await this.waitForMessage(sessionDbId, signal, Math.min(idleTimeoutMs, IDLE_WAIT_SLICE_MS));
      if (!received && !signal.aborted) {
        const idleDuration = Date.now() - lastActivityTime;
        if (idleDuration >= idleTimeoutMs) {
          logger.info('SESSION', 'Idle timeout reached, triggering abort to kill subprocess', {
            sessionDbId,
            idleDurationMs: idleDuration,
            thresholdMs: idleTimeoutMs
          });
          onIdleTimeout?.();
          return;
        }
        if (options.shouldReleaseIdleSlot?.()) {
          logger.info('SESSION', 'Releasing idle slot early: other sessions are waiting for a slot', {
            sessionDbId,
            idleDurationMs: idleDuration,
            thresholdMs: idleTimeoutMs
          });
          onIdleTimeout?.();
          return;
        }
      } else {
        lastActivityTime = Date.now();
      }
    }
  }

  /** Claim only the immediate FIFO head, never wait or cross a rejected barrier. */
  claimNextMatching(sessionDbId: number, accepts: (message: PendingMessageWithId) => boolean): PendingMessageWithId | null {
    this.pruneExpired();
    const next = this.buffers.get(sessionDbId)?.find(message => !message.claimed && !message.parked);
    if (!next) return null;
    const message = { ...next.message, _persistentId: next.id, _originalTimestamp: next.enqueuedAt };
    if (!accepts(message)) return null;
    next.claimed = true;
    this.onMutate?.();
    return message;
  }

  private claimNext(sessionDbId: number): BufferedMessage | null {
    this.pruneExpired();
    const list = this.buffers.get(sessionDbId);
    if (!list) return null;
    const next = list.find(m => !m.claimed && !m.parked);
    if (!next) return null;
    next.claimed = true;
    this.onMutate?.();
    return next;
  }

  /**
   * Make room for one live input under the hard caps (per session and
   * worker-wide, parked entries included) by evicting parked entries, oldest
   * first. Only called once the live counts are under their caps, so enough
   * parked entries always exist. Evicted entries keep their dedup ids, so
   * they can never be enqueued and sent again; the eviction is counted and
   * logged, never silent.
   */
  private evictParkedForRoom(sessionDbId: number): void {
    const evicted = new Set<BufferedMessage>();
    const sessionList = this.buffers.get(sessionDbId) ?? [];
    const sessionParked = sessionList.filter(message => message.parked);
    for (let index = 0; sessionList.length - evicted.size >= LIVE_OBSERVER_MAX_SESSION_MESSAGES; index++) {
      evicted.add(sessionParked[index]);
    }
    let total = 0;
    for (const list of this.buffers.values()) total += list.length;
    if (total - evicted.size >= LIVE_OBSERVER_MAX_TOTAL_MESSAGES) {
      const parked: BufferedMessage[] = [];
      for (const list of this.buffers.values()) {
        for (const message of list) if (message.parked && !evicted.has(message)) parked.push(message);
      }
      parked.sort((a, b) => a.id - b.id);
      for (let index = 0; total - evicted.size >= LIVE_OBSERVER_MAX_TOTAL_MESSAGES; index++) evicted.add(parked[index]);
    }
    if (evicted.size === 0) return;
    for (const [id, list] of this.buffers) {
      const kept = list.filter(message => !evicted.has(message));
      if (kept.length !== list.length) this.buffers.set(id, kept);
    }
    this.evictedParkedInputCount += evicted.size;
    logger.warn('QUEUE', 'Evicted parked observer inputs to make room for live input; they were never resent', {
      sessionId: sessionDbId,
      evicted: evicted.size,
      total: this.evictedParkedInputCount,
    });
    this.onMutate?.();
  }

  /** Live (sendable) messages only; parked batches are never sent again. */
  private liveBufferedCount(): number {
    let total = 0;
    for (const list of this.buffers.values()) {
      for (const message of list) {
        if (!message.parked) total++;
      }
    }
    return total;
  }

  /** Expire only unsent work. A paid request already in flight may finish. */
  private pruneExpired(): void {
    const cutoff = Date.now() - LIVE_OBSERVER_MAX_AGE_MS;
    let skipped = 0;
    for (const [sessionDbId, list] of this.buffers) {
      const live = list.filter(message => message.claimed || message.bufferedAt > cutoff);
      skipped += list.length - live.length;
      if (live.length !== list.length) this.buffers.set(sessionDbId, live);
    }
    if (skipped > 0) {
      // No replay is scheduled: the input is gone, so the only thing this can
      // still do is make the loss visible (#6391).
      this.expiredInputCount += skipped;
      logger.warn('QUEUE', 'Skipped expired live observer inputs; no replay scheduled', {
        skipped,
        total: this.expiredInputCount,
      });
      this.onMutate?.();
    }
  }

  private waitForMessage(sessionDbId: number, signal: AbortSignal, timeoutMs: number): Promise<boolean> {
    return new Promise<boolean>((resolve) => {
      const events = this.getEvents(sessionDbId);
      let timeoutId: ReturnType<typeof setTimeout> | undefined;

      const cleanup = () => {
        if (timeoutId !== undefined) {
          clearTimeout(timeoutId);
        }
        events.off('message', onMessage);
        signal.removeEventListener('abort', onAbort);
      };

      const onMessage = () => {
        cleanup();
        resolve(true);
      };
      const onAbort = () => {
        cleanup();
        resolve(false);
      };
      const onTimeout = () => {
        cleanup();
        resolve(false);
      };

      events.once('message', onMessage);
      signal.addEventListener('abort', onAbort, { once: true });
      timeoutId = setTimeout(onTimeout, timeoutMs);
    });
  }

  private getList(sessionDbId: number): BufferedMessage[] {
    let list = this.buffers.get(sessionDbId);
    if (!list) {
      list = [];
      this.buffers.set(sessionDbId, list);
    }
    return list;
  }

  private getSeen(sessionDbId: number): Set<string> {
    let seen = this.seenToolUseIds.get(sessionDbId);
    if (!seen) {
      seen = new Set<string>();
      this.seenToolUseIds.set(sessionDbId, seen);
    }
    return seen;
  }

  private getEvents(sessionDbId: number): EventEmitter {
    let events = this.events.get(sessionDbId);
    if (!events) {
      events = new EventEmitter();
      this.events.set(sessionDbId, events);
    }
    return events;
  }

  private signal(sessionDbId: number): void {
    this.events.get(sessionDbId)?.emit('message');
  }
}