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

5.6 KB
Raw Blame
import type { ContextConfig } from './types.js';

/**
 * Claude Code delivers a hook's stdout verbatim up to 10,000 characters. One
 * character more and the whole block is written to disk and replaced by a ~2KB
 * preview stub, so the model receives no context at all — and the hook still
 * reports success, which is why this failed silently (#3802, #1899).
 */
export const CONTEXT_OUTPUT_LIMIT = 10_000;

/**
 * Room the terminal preview leaves for the lines a hook adds above it. The
 * SessionStart hook puts the viewer link, the trial line, the trial countdown
 * and the TeamBrain discovery line over the preview in the same
 * `systemMessage`, so a preview fitted to the full limit pushed that field past
 * 10,000 and Claude Code showed the saved-to-disk stub instead (#5079).
 */
export const TERMINAL_BANNER_RESERVE_CHARS = 512;

/**
 * Item counts cannot keep the block under that limit, because items are not a
 * fixed size: an observation title runs ~150-320 characters, a session-summary
 * line ~250-600, and the last-session summary block 1-5K on its own. Any count
 * that is safe on a quiet project wastes the budget, and any count that fills
 * the budget there overflows on a busy one.
 *
 * So fit by measuring. Render, and while the result is over budget, drop the
 * most expensive thing still in it and render again. Whole items are dropped,
 * never cut in half, so the block always ends up well-formed — the header,
 * footer and at least one observation always survive.
 */
export interface ContextBudgetResult {
  text: string;
  /** The config that produced `text`, after any reductions. */
  config: ContextConfig;
  /** Observations that survived; a prefix of the input, newest first. */
  observationCount: number;
  /** How many reduction steps were taken. 0 means the first render fit. */
  reductions: number;
  /** True when everything droppable is gone and the block is still over budget. */
  overBudget: boolean;
}

/**
 * The order things are given up in, cheapest loss first.
 *
 * Full observation narratives go first: they are the largest per-item cost and
 * their titles remain in the timeline either way. The last-session summary
 * block goes next, being a single 1-5K item, then the prior session's final
 * reply ("Include last message"), a single item with no size bound at all:
 * kept to the end, a long one leaves the block over the limit after every
 * other reduction. Only then do we start losing timeline entries, sessions
 * before observations, because an observation is the smaller unit and the one
 * the timeline is mostly made of.
 */
function reduceConfig(config: ContextConfig, observationCount: number): { config: ContextConfig; observationCount: number } | null {
  if (config.fullObservationCount > 0) {
    return { config: { ...config, fullObservationCount: 0 }, observationCount };
  }
  if (config.showLastSummary) {
    return { config: { ...config, showLastSummary: false }, observationCount };
  }
  if (config.showLastMessage) {
    return { config: { ...config, showLastMessage: false }, observationCount };
  }
  if (config.sessionCount > 0) {
    return { config: { ...config, sessionCount: Math.floor(config.sessionCount / 2) }, observationCount };
  }
  if (observationCount > 1) {
    return { config, observationCount: Math.floor(observationCount / 2) };
  }
  return null;
}

/**
 * Render within `limit` characters, giving up content in `reduceConfig`'s order.
 *
 * `render` must be pure. Adding timeline entries must not shorten its output:
 * after finding a fitting count, the fitter probes that final count interval
 * to retain the largest prefix that fits, without restoring earlier losses.
 */
export function fitContextToBudget<T>(
  observations: T[],
  config: ContextConfig,
  render: (observations: T[], config: ContextConfig) => string,
  limit: number = CONTEXT_OUTPUT_LIMIT
): ContextBudgetResult {
  let currentConfig = config;
  let currentCount = observations.length;
  let text = render(observations, currentConfig);
  let reductions = 0;

  while (text.length > limit) {
    const next = reduceConfig(currentConfig, currentCount);
    if (!next) {
      return { text, config: currentConfig, observationCount: currentCount, reductions, overBudget: true };
    }
    const previousConfig = currentConfig;
    const previousCount = currentCount;
    currentConfig = next.config;
    currentCount = next.observationCount;
    text = render(observations.slice(0, currentCount), currentConfig);
    reductions++;

    // Halving finds a fitting interval quickly, but stopping there can discard
    // almost half the timeline for a one-character overflow. Refine only the
    // last count reduction, preserving the existing priority of earlier losses.
    if (text.length <= limit) {
      const sessionsReduced = currentConfig.sessionCount < previousConfig.sessionCount;
      let low = (sessionsReduced ? currentConfig.sessionCount : currentCount) + 1;
      let high = (sessionsReduced ? previousConfig.sessionCount : previousCount) - 1;
      while (low <= high) {
        const mid = low + Math.floor((high - low) / 2);
        const candidateConfig = sessionsReduced ? { ...currentConfig, sessionCount: mid } : currentConfig;
        const candidateCount = sessionsReduced ? currentCount : mid;
        const candidateText = render(observations.slice(0, candidateCount), candidateConfig);
        if (candidateText.length <= limit) {
          currentConfig = candidateConfig;
          currentCount = candidateCount;
          text = candidateText;
          low = mid + 1;
        } else {
          high = mid - 1;
        }
      }
    }
  }

  return { text, config: currentConfig, observationCount: currentCount, reductions, overBudget: false };
}