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
// SPDX-License-Identifier: Apache-2.0
import type { JsonObject, PostgresQueryable } from './utils.js';
import { assertProjectOwnership, deterministicKey, newId, queryOne, toDate, toEpoch, toJsonObject } from './utils.js';
import type { PostgresAgentEvent } from './agent-events.js';
import { normalizePlatformSourceOrNull } from '../../shared/platform-source.js';
import { stripMemoryTagsFromJsonStrings } from '../../utils/tag-stripping.js';
import { redactJsonStrings } from '../../utils/redaction.js';
export interface PostgresServerSession {
id: string;
projectId: string;
teamId: string;
externalSessionId: string | null;
idempotencyKey: string | null;
contentSessionId: string | null;
agentId: string | null;
agentType: string | null;
platformSource: string | null;
generationStatus: string;
metadata: JsonObject;
startedAtEpoch: number;
endedAtEpoch: number | null;
lastGeneratedAtEpoch: number | null;
createdAtEpoch: number;
updatedAtEpoch: number;
}
interface ServerSessionRow {
id: string;
project_id: string;
team_id: string;
external_session_id: string | null;
idempotency_key: string | null;
content_session_id: string | null;
agent_id: string | null;
agent_type: string | null;
platform_source: string | null;
generation_status: string;
metadata: unknown;
started_at: Date;
ended_at: Date | null;
last_generated_at: Date | null;
created_at: Date;
updated_at: Date;
}
export class PostgresServerSessionsRepository {
constructor(private client: PostgresQueryable) {}
async create(input: {
id?: string;
projectId: string;
teamId: string;
externalSessionId?: string | null;
contentSessionId?: string | null;
agentId?: string | null;
agentType?: string | null;
platformSource?: string | null;
generationStatus?: string;
metadata?: JsonObject;
}): Promise<PostgresServerSession> {
await assertProjectOwnership(this.client, input.projectId, input.teamId);
const id = input.id ?? newId();
const platformSource = normalizePlatformSourceOrNull(input.platformSource);
const idempotencyKey = buildServerSessionIdempotencyKey({
...input,
platformSource,
});
const row = await queryOne<ServerSessionRow>(
this.client,
`
INSERT INTO server_sessions (
id, project_id, team_id, external_session_id, idempotency_key, content_session_id,
agent_id, agent_type, platform_source, generation_status, metadata
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, COALESCE($10::text, 'idle'), $11::jsonb)
ON CONFLICT (project_id, idempotency_key) WHERE idempotency_key IS NOT NULL DO UPDATE SET
external_session_id = excluded.external_session_id,
content_session_id = excluded.content_session_id,
agent_id = excluded.agent_id,
agent_type = excluded.agent_type,
platform_source = excluded.platform_source,
-- A replay omitting the initial state must not undo a lifecycle transition.
generation_status = COALESCE($10::text, server_sessions.generation_status),
metadata = excluded.metadata,
updated_at = now()
RETURNING *
`,
[
id,
input.projectId,
input.teamId,
input.externalSessionId ?? null,
idempotencyKey,
input.contentSessionId ?? null,
input.agentId ?? null,
input.agentType ?? null,
platformSource,
input.generationStatus ?? null,
// Session metadata carries the opening prompt and follows the same
// privacy and configured redaction policy as event payloads.
JSON.stringify(redactJsonStrings(stripMemoryTagsFromJsonStrings(input.metadata ?? {})))
]
);
return mapServerSessionRow(row!);
}
async getByIdForScope(input: {
id: string;
projectId: string;
teamId: string;
}): Promise<PostgresServerSession | null> {
const row = await queryOne<ServerSessionRow>(
this.client,
'SELECT * FROM server_sessions WHERE id = $1 AND project_id = $2 AND team_id = $3',
[input.id, input.projectId, input.teamId]
);
return row ? mapServerSessionRow(row) : null;
}
async listByProject(projectId: string, teamId: string): Promise<PostgresServerSession[]> {
const result = await this.client.query<ServerSessionRow>(
`
SELECT * FROM server_sessions
WHERE project_id = $1 AND team_id = $2
ORDER BY started_at DESC
`,
[projectId, teamId]
);
return result.rows.map(mapServerSessionRow);
}
async findByExternalIdForScope(input: {
externalSessionId: string;
projectId: string;
teamId: string;
platformSource?: string | null;
}): Promise<PostgresServerSession | null> {
const hasPlatformScope = Object.prototype.hasOwnProperty.call(input, 'platformSource');
const platformSource = hasPlatformScope
? normalizePlatformSourceOrNull(input.platformSource)
: null;
const row = await queryOne<ServerSessionRow>(
this.client,
`
SELECT * FROM server_sessions
WHERE external_session_id = $1 AND project_id = $2 AND team_id = $3
AND (
$4::boolean = false
OR ($5::text IS NULL AND platform_source IS NULL)
OR platform_source = $5
)
ORDER BY started_at DESC
LIMIT 1
`,
[input.externalSessionId, input.projectId, input.teamId, hasPlatformScope, platformSource]
);
return row ? mapServerSessionRow(row) : null;
}
// Resolve only the server_session id for a content session. Used by the
// /v1/events ingest linkage path, which needs nothing but the id, so we select
// a single column to keep this hot-path query light.
async findIdByContentSessionId(input: {
contentSessionId: string;
projectId: string;
teamId: string;
platformSource?: string | null;
}): Promise<string | null> {
const hasPlatformScope = Object.prototype.hasOwnProperty.call(input, 'platformSource');
const platformSource = hasPlatformScope
? normalizePlatformSourceOrNull(input.platformSource)
: null;
const row = await queryOne<{ id: string }>(
this.client,
`
SELECT id FROM server_sessions
WHERE content_session_id = $1 AND project_id = $2 AND team_id = $3
AND (
$4::boolean = false
OR ($5::text IS NULL AND platform_source IS NULL)
OR platform_source = $5
)
ORDER BY started_at DESC
LIMIT 1
`,
[input.contentSessionId, input.projectId, input.teamId, hasPlatformScope, platformSource]
);
return row ? row.id : null;
}
/**
* End a server session by setting `ended_at = now()` if not already set.
* Idempotent: if `ended_at` is already populated, returns the row unchanged.
* Returns null if no row matches the (id, project_id, team_id) tuple.
*/
async endSession(input: {
id: string;
projectId: string;
teamId: string;
}): Promise<PostgresServerSession | null> {
const updated = await queryOne<ServerSessionRow>(
this.client,
`
UPDATE server_sessions
SET ended_at = COALESCE(ended_at, now()),
updated_at = CASE WHEN ended_at IS NULL THEN now() ELSE updated_at END
WHERE id = $1 AND project_id = $2 AND team_id = $3
RETURNING *
`,
[input.id, input.projectId, input.teamId]
);
return updated ? mapServerSessionRow(updated) : null;
}
async markGenerationStarted(input: {
id: string;
projectId: string;
teamId: string;
}): Promise<PostgresServerSession | null> {
const updated = await queryOne<ServerSessionRow>(
this.client,
`
UPDATE server_sessions
SET generation_status = 'processing', updated_at = now()
WHERE id = $1 AND project_id = $2 AND team_id = $3
RETURNING *
`,
[input.id, input.projectId, input.teamId]
);
return updated ? mapServerSessionRow(updated) : null;
}
async markGenerationCompleted(input: {
id: string;
projectId: string;
teamId: string;
}): Promise<PostgresServerSession | null> {
const updated = await queryOne<ServerSessionRow>(
this.client,
`
UPDATE server_sessions
SET generation_status = 'completed',
last_generated_at = now(),
updated_at = now()
WHERE id = $1 AND project_id = $2 AND team_id = $3
RETURNING *
`,
[input.id, input.projectId, input.teamId]
);
return updated ? mapServerSessionRow(updated) : null;
}
async markGenerationFailed(input: {
id: string;
projectId: string;
teamId: string;
error?: string | null;
}): Promise<PostgresServerSession | null> {
const updated = await queryOne<ServerSessionRow>(
this.client,
`
UPDATE server_sessions
SET generation_status = 'failed',
metadata = jsonb_set(
COALESCE(metadata, '{}'::jsonb),
'{lastGenerationError}',
COALESCE(to_jsonb($4::text), 'null'::jsonb),
true
),
updated_at = now()
WHERE id = $1 AND project_id = $2 AND team_id = $3
RETURNING *
`,
[input.id, input.projectId, input.teamId, input.error ?? null]
);
return updated ? mapServerSessionRow(updated) : null;
}
/**
* Every event of the session, in order — the input a SESSION SUMMARY needs.
* Tenant-scoped: rows are filtered by (project_id, team_id).
*
* Never only the events the per-event lane has not collapsed yet: that lane
* normally finishes first, so a summary fed those arrived at an empty list
* and the model was asked to summarise nothing (#4137).
*
* Bounded by count at BOTH ends, never only at the head: a session longer
* than 2 x `eventsPerEnd` returns its first and last `eventsPerEnd` events,
* so the summary always sees the opening (the goal) and the close (the
* outcome and what was left pending). The count bound only caps memory; the
* caller's byte budget (`capSummaryInput`) does the real sizing.
*/
async listSessionEvents(input: {
serverSessionId: string;
projectId: string;
teamId: string;
eventsPerEnd?: number;
}): Promise<PostgresAgentEvent[]> {
const eventsPerEnd = input.eventsPerEnd ?? 500;
const result = await this.client.query<SessionEventRow>(
`
SELECT e.*
FROM agent_events e
WHERE e.project_id = $2
AND e.team_id = $3
AND e.id IN (
(SELECT head.id FROM agent_events head
WHERE head.server_session_id = $1 AND head.project_id = $2 AND head.team_id = $3
ORDER BY head.occurred_at ASC, head.id ASC
LIMIT $4)
UNION
(SELECT tail.id FROM agent_events tail
WHERE tail.server_session_id = $1 AND tail.project_id = $2 AND tail.team_id = $3
ORDER BY tail.occurred_at DESC, tail.id DESC
LIMIT $4)
)
ORDER BY e.occurred_at ASC, e.id ASC
`,
[input.serverSessionId, input.projectId, input.teamId, eventsPerEnd]
);
return result.rows.map(mapSessionEventRow);
}
}
interface SessionEventRow {
id: string;
project_id: string;
team_id: string;
server_session_id: string | null;
source_adapter: string;
source_event_id: string | null;
idempotency_key: string;
event_type: string;
platform_source: string | null;
payload: unknown;
metadata: unknown;
occurred_at: Date;
received_at: Date;
created_at: Date;
}
function mapSessionEventRow(row: SessionEventRow): PostgresAgentEvent {
return {
id: row.id,
projectId: row.project_id,
teamId: row.team_id,
serverSessionId: row.server_session_id,
sourceAdapter: row.source_adapter,
sourceEventId: row.source_event_id,
idempotencyKey: row.idempotency_key,
eventType: row.event_type,
platformSource: row.platform_source,
payload: row.payload,
metadata: toJsonObject(row.metadata),
occurredAtEpoch: row.occurred_at.getTime(),
receivedAtEpoch: row.received_at.getTime(),
createdAtEpoch: row.created_at.getTime()
};
}
export function buildServerSessionIdempotencyKey(input: {
projectId: string;
teamId: string;
externalSessionId?: string | null;
contentSessionId?: string | null;
agentId?: string | null;
agentType?: string | null;
platformSource?: string | null;
}): string | null {
const platformSource = normalizePlatformSourceOrNull(input.platformSource);
if (input.externalSessionId) {
const parts = [
input.teamId,
input.projectId,
'external',
];
if (platformSource) {
parts.push(platformSource);
}
parts.push(input.externalSessionId);
return `server_session:v1:${deterministicKey(parts)}`;
}
if (input.contentSessionId) {
return `server_session:v1:${deterministicKey([
input.teamId,
input.projectId,
'content',
platformSource,
input.agentId ?? null,
input.contentSessionId
])}`;
}
if (input.agentId && platformSource) {
return `server_session:v1:${deterministicKey([
input.teamId,
input.projectId,
'agent',
platformSource,
input.agentId,
input.agentType ?? null
])}`;
}
return null;
}
function mapServerSessionRow(row: ServerSessionRow): PostgresServerSession {
return {
id: row.id,
projectId: row.project_id,
teamId: row.team_id,
externalSessionId: row.external_session_id,
idempotencyKey: row.idempotency_key,
contentSessionId: row.content_session_id,
agentId: row.agent_id,
agentType: row.agent_type,
platformSource: row.platform_source,
generationStatus: row.generation_status,
metadata: toJsonObject(row.metadata),
startedAtEpoch: toEpoch(row.started_at),
endedAtEpoch: toDate(row.ended_at)?.getTime() ?? null,
lastGeneratedAtEpoch: toDate(row.last_generated_at)?.getTime() ?? null,
createdAtEpoch: toEpoch(row.created_at),
updatedAtEpoch: toEpoch(row.updated_at)
};
}