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
TypeScript aiai-agentsai-memoryanthropicartificial-intelligencechromadbclaudeclaude-agent-sdkclaude-agentsclaude-codeclaude-code-pluginclaude-skillsembeddingslong-term-memorymem0memory-engineopenmemoryragsqlitesupermemory
import type { ActiveSession } from '../worker-types.js';
/**
* Applied only when a gateway reports a bare total with no prompt/completion
* breakdown. openrouter.ai and Gemini both report the split, so this is the
* custom-gateway fallback, not the normal path.
*/
const FALLBACK_INPUT_SHARE = 0.7;
const FALLBACK_OUTPUT_SHARE = 0.3;
/** The usage fields an OpenAI-compatible provider response can carry. */
export interface ObserverUsageSample {
tokensUsed?: number;
inputTokens?: number;
outputTokens?: number;
cachedInputTokens?: number;
}
/**
* Raw `usage` payload returned by OpenAI-compatible `/chat/completions`
* endpoints, including provider-specific prompt-cache counters.
*/
export interface OpenAICompatUsagePayload {
prompt_tokens?: number;
completion_tokens?: number;
total_tokens?: number;
prompt_tokens_details?: {
cached_tokens?: number;
};
prompt_cache_hit_tokens?: number;
prompt_cache_miss_tokens?: number;
cache_read_input_tokens?: number;
cache_creation_input_tokens?: number;
opencode?: {
tokens?: {
cache_read?: number;
[key: string]: unknown;
};
};
}
/** Normalized per-turn prompt-cache telemetry for an OpenAI-compatible response. */
export interface PromptCacheUsage {
cachedInputTokens?: number;
cacheWriteInputTokens?: number;
uncachedInputTokens?: number;
}
function asNonNegativeFinite(value: unknown): number | undefined {
return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;
}
function pickReportedCount(values: Array<number | undefined>): number | undefined {
const reported = values.filter((v): v is number => v !== undefined);
if (reported.length === 0) return undefined;
return reported.find(v => v > 0) ?? reported[0];
}
function sumOpencodeCacheWrites(tokens: Record<string, unknown> | undefined): number | undefined {
if (!tokens || typeof tokens !== 'object') return undefined;
let total = 0;
let found = false;
for (const [key, value] of Object.entries(tokens)) {
if (!key.startsWith('cache_write_')) continue;
const count = asNonNegativeFinite(value);
if (count !== undefined) {
total += count;
found = true;
}
}
return found ? total : undefined;
}
/**
* Normalize prompt-cache counters across OpenAI, DeepSeek, OpenCode Go, and
* Anthropic-compatible response shapes. Fields the endpoint did not report
* stay undefined rather than being coerced to 0, and redundant fields on the
* same payload (e.g. OpenAI + vendor mirror) are never summed twice.
*/
export function extractPromptCacheUsage(usage: OpenAICompatUsagePayload | undefined): PromptCacheUsage {
if (!usage) return {};
const cachedInputTokens = pickReportedCount([
asNonNegativeFinite(usage.prompt_tokens_details?.cached_tokens),
asNonNegativeFinite(usage.prompt_cache_hit_tokens),
asNonNegativeFinite(usage.opencode?.tokens?.cache_read),
asNonNegativeFinite(usage.cache_read_input_tokens),
]);
const cacheWriteInputTokens = pickReportedCount([
sumOpencodeCacheWrites(usage.opencode?.tokens),
asNonNegativeFinite(usage.cache_creation_input_tokens),
]);
const grossInputTokens = asNonNegativeFinite(usage.prompt_tokens);
const uncachedInputTokens =
cachedInputTokens !== undefined && grossInputTokens !== undefined
? Math.max(0, grossInputTokens - cachedInputTokens)
: undefined;
return {
...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}),
...(cacheWriteInputTokens !== undefined ? { cacheWriteInputTokens } : {}),
...(uncachedInputTokens !== undefined ? { uncachedInputTokens } : {}),
};
}
/** The subset of the Claude SDK's usage block that feeds the session counters. */
export interface ClaudeUsageSample {
input_tokens?: number | null;
output_tokens?: number | null;
cache_creation_input_tokens?: number | null;
cache_read_input_tokens?: number | null;
}
/**
* Fold one OpenAI-compatible response into the session's cumulative counters.
*
* Gemini (promptTokenCount/candidatesTokenCount) and OpenRouter
* (prompt_tokens/completion_tokens) both report the real split, so the
* estimate must not win when real counts exist: the observer resends its whole
* conversation on every turn, which makes its traffic overwhelmingly
* input-heavy, and a fixed 70/30 assumption understates input on exactly the
* long sessions worth noticing. Both sides or nothing, matching buildLastUsage:
* a gateway reporting only one of the two must not produce a half-real number.
*/
export function accumulateObserverUsage(session: ActiveSession, sample: ObserverUsageSample): void {
const cachedInputTokens = asNonNegativeFinite(sample.cachedInputTokens);
if (cachedInputTokens && cachedInputTokens > 0) {
session.cumulativeCacheReadTokens =
(session.cumulativeCacheReadTokens ?? 0) + cachedInputTokens;
}
if (typeof sample.inputTokens === 'number' && typeof sample.outputTokens === 'number') {
session.cumulativeInputTokens += sample.inputTokens;
session.cumulativeOutputTokens += sample.outputTokens;
return;
}
const total = sample.tokensUsed || 0;
session.cumulativeInputTokens += Math.floor(total * FALLBACK_INPUT_SHARE);
session.cumulativeOutputTokens += Math.floor(total * FALLBACK_OUTPUT_SHARE);
}
/**
* Fold one Claude SDK assistant-message usage block into the session counters.
*
* Cache reads are tracked in their own counter rather than added to
* cumulativeInputTokens: discovery_tokens is derived from the delta of
* (cumulativeInput + cumulativeOutput) across a response, so widening those two
* would silently redefine a value already persisted on every observation.
*/
export function accumulateClaudeUsage(session: ActiveSession, usage: ClaudeUsageSample): void {
session.cumulativeInputTokens += usage.input_tokens || 0;
session.cumulativeOutputTokens += usage.output_tokens || 0;
if (usage.cache_creation_input_tokens) {
session.cumulativeInputTokens += usage.cache_creation_input_tokens;
}
if (usage.cache_read_input_tokens) {
session.cumulativeCacheReadTokens =
(session.cumulativeCacheReadTokens ?? 0) + usage.cache_read_input_tokens;
}
}
/**
* Log context for the once-per-session lines that report what the observer
* spent. Cache reads are omitted when the provider never reported any, so
* HTTP-provider logs do not carry a permanent zero.
*/
export function observerUsageLogFields(session: ActiveSession): Record<string, number> {
return {
cumulativeInputTokens: session.cumulativeInputTokens,
cumulativeOutputTokens: session.cumulativeOutputTokens,
...(session.cumulativeCacheReadTokens
? { cumulativeCacheReadTokens: session.cumulativeCacheReadTokens }
: {}),
};
}