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

9.9 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0

// Legacy compatibility — new clients should use POST /v1/events directly.
//
// Legacy worker payloads to `/api/sessions/observations` are translated into
// the Server beta event/job model and delegated to IngestEventsService. The
// adapter never touches worker code, never queues observations directly, and
// never uses `src/services/worker/*` types.
//
// Translation rules:
//   - `contentSessionId` (Claude Code session UUID) becomes the
//     `external_session_id` of a Server beta `server_sessions` row, scoped to
//     the API key's team and project. The session is create-or-found.
//   - The tool-use shape (tool_name, tool_input, tool_response, tool_use_id)
//     is mapped to an `agent_event` with sourceAdapter='claude-code-compat',
//     eventType='tool_use', payload preserves the legacy fields verbatim.
//   - The API key MUST be project-scoped. Cross-project compat calls return
//     400; we never let compat traffic bypass project scope.

import type { Application, Request, Response } from 'express';
import { z } from 'zod';
import type { RouteHandler } from '../../services/server/Server.js';
import type { PostgresPool } from '../../storage/postgres/pool.js';
import { PostgresServerSessionsRepository } from '../../storage/postgres/server-sessions.js';
import { logger } from '../../utils/logger.js';
import { requirePostgresServerAuth } from '../middleware/postgres-auth.js';
import { serverUsageGuards } from '../middleware/usage-guards.js';
import { IngestEventsService } from '../services/IngestEventsService.js';
import type { CreatePostgresAgentEventInput } from '../../storage/postgres/agent-events.js';
import { DEFAULT_PLATFORM_SOURCE, normalizePlatformSource } from '../../shared/platform-source.js';

const COMPAT_SOURCE_ADAPTER = 'claude-code-compat';
const COMPAT_EVENT_TYPE = 'tool_use';

const observationsSchema = z.object({
  contentSessionId: z.string().min(1),
  tool_name: z.string().min(1),
  tool_input: z.unknown().optional(),
  tool_response: z.unknown().optional(),
  cwd: z.string().optional(),
  agentId: z.string().optional(),
  agentType: z.string().optional(),
  platformSource: z.string().optional(),
  // Provenance: which client sent this. When absent it is derived from the
  // platform, so a muse or cowork client isn't labeled claude-code-compat.
  // Client-supplied and stored on every event row, so it is bounded (abuse
  // protection) and an over-long value is rejected, never cut.
  sourceAdapter: z.string().trim().min(1).max(64).optional(),
  tool_use_id: z.string().optional(),
  toolUseId: z.string().optional(),
}).passthrough();

export interface SessionsObservationsAdapterOptions {
  pool: PostgresPool;
  ingestEvents: IngestEventsService;
  authMode?: string;
  allowLocalDevBypass?: boolean;
}

export class SessionsObservationsAdapter implements RouteHandler {
  constructor(private readonly options: SessionsObservationsAdapterOptions) {}

  setupRoutes(app: Application): void {
    const writeAuth = [requirePostgresServerAuth(this.options.pool, {
      authMode: this.options.authMode,
      allowLocalDevBypass: this.options.allowLocalDevBypass,
      requiredScopes: ['memories:write'],
    }), ...serverUsageGuards(this.options.pool, { write: true })];

    app.post('/api/sessions/observations', writeAuth, this.asyncHandler(async (req, res) => {
      const parsed = observationsSchema.safeParse(req.body);
      if (!parsed.success) {
        res.status(400).json({ error: 'ValidationError', issues: parsed.error.issues });
        return;
      }
      const teamId = req.authContext?.teamId ?? null;
      const projectId = req.authContext?.projectId ?? null;
      if (!teamId) {
        res.status(403).json({ error: 'Forbidden', message: 'API key is not bound to a team' });
        return;
      }
      if (!projectId) {
        // Compat mode requires a project-scoped key — the legacy payload does
        // not carry a Server beta projectId, so without scope we cannot place
        // the row in a tenant-scoped table.
        res.status(400).json({
          error: 'BadRequest',
          message: 'Legacy /api/sessions/observations requires a project-scoped API key',
        });
        return;
      }

      try {
        await this.ingestCompatObservation(req, res, parsed.data, teamId, projectId);
      } catch (error) {
        logger.error('SYSTEM', 'compat observations adapter failed', {
          error: error instanceof Error ? error.message : String(error),
          contentSessionId: parsed.data.contentSessionId,
        });
        res.status(500).json({ stored: false, reason: 'internal_error' });
      }
    }));
  }

  // Body of the legacy observations route — translates the legacy payload
  // into a Server beta agent_event and delegates to IngestEventsService.
  private async ingestCompatObservation(
    req: Request,
    res: Response,
    data: z.infer<typeof observationsSchema>,
    teamId: string,
    projectId: string,
  ): Promise<void> {
    const platformSource = normalizePlatformSource(
      typeof data.platformSource === 'string'
        ? data.platformSource
        : DEFAULT_PLATFORM_SOURCE,
    );
    // Provenance: the client's own adapter label wins; otherwise derive it from
    // the platform. claude keeps the legacy label so existing filters match.
    const sourceAdapter = data.sourceAdapter
      ?? (platformSource === DEFAULT_PLATFORM_SOURCE ? COMPAT_SOURCE_ADAPTER : `${platformSource}-compat`);
    const session = await resolveServerSession({
      pool: this.options.pool,
      teamId,
      projectId,
      contentSessionId: data.contentSessionId,
      platformSource,
      agentId: typeof data.agentId === 'string' ? data.agentId : null,
      agentType: typeof data.agentType === 'string' ? data.agentType : null,
    });

    const toolUseId = typeof data.tool_use_id === 'string'
      ? data.tool_use_id
      : (typeof data.toolUseId === 'string' ? data.toolUseId : null);

    const input: CreatePostgresAgentEventInput = {
      projectId,
      teamId,
      serverSessionId: session.id,
      sourceAdapter,
      sourceEventId: toolUseId,
      eventType: COMPAT_EVENT_TYPE,
      // #2560 — persist platform_source on the event row (not just inside
      // payload) so plan-09 scoping/queries can filter by platform.
      platformSource,
      payload: {
        contentSessionId: data.contentSessionId,
        tool_name: data.tool_name,
        tool_input: data.tool_input ?? null,
        tool_response: data.tool_response ?? null,
        cwd: data.cwd ?? null,
        platformSource,
        agentId: data.agentId ?? null,
        agentType: data.agentType ?? null,
        toolUseId,
      },
      metadata: { compat: 'sessions/observations' },
      occurredAt: new Date(),
    };

    const result = await this.options.ingestEvents.ingestOne(input, {
      source: 'http_post_api_sessions_observations',
      apiKeyId: req.authContext?.apiKeyId ?? null,
      actorId: null,
      sourceAdapter,
    });
    // Legacy response shape — older clients only check `status`.
    res.json({
      status: 'queued',
      observationCount: 1,
      sessionId: session.id,
      serverSessionId: session.id,
      eventId: result.event.id,
      generationJobId: result.outbox?.id ?? null,
      transport: result.enqueueState,
    });
  }

  private asyncHandler(fn: (req: Request, res: Response) => Promise<void> | void) {
    return (req: Request, res: Response, next: (err?: unknown) => void): void => {
      Promise.resolve(fn(req, res)).catch(next);
    };
  }
}

/**
 * Look up an existing server_session by platform-scoped
 * (project, team, externalSessionId) or create one if missing. Idempotent:
 * re-issuing for the same platform/content session returns the existing row.
 *
 * Concurrent compat callers can race here — both observe `existing===null`
 * and both call `repo.create`, where the second will hit one of two unique
 * constraints (`(project_id, idempotency_key)` covered by ON CONFLICT, or a
 * platform-scoped external_session_id index). Catch the unique-violation and
 * re-fetch so the caller never sees a 500.
 */
export async function resolveServerSession(input: {
  pool: PostgresPool;
  teamId: string;
  projectId: string;
  contentSessionId: string;
  platformSource: string | null;
  agentId: string | null;
  agentType: string | null;
}): Promise<{ id: string; projectId: string; teamId: string }> {
  const repo = new PostgresServerSessionsRepository(input.pool);
  const platformSource = input.platformSource
    ? normalizePlatformSource(input.platformSource)
    : null;
  const existing = await repo.findByExternalIdForScope({
    externalSessionId: input.contentSessionId,
    projectId: input.projectId,
    teamId: input.teamId,
    platformSource,
  });
  if (existing) {
    return { id: existing.id, projectId: existing.projectId, teamId: existing.teamId };
  }
  const createInput = {
    projectId: input.projectId,
    teamId: input.teamId,
    externalSessionId: input.contentSessionId,
    contentSessionId: input.contentSessionId,
    agentId: input.agentId,
    agentType: input.agentType,
    platformSource,
  };
  try {
    const created = await repo.create(createInput);
    return { id: created.id, projectId: created.projectId, teamId: created.teamId };
  } catch (error) {
    const err = error instanceof Error ? error : new Error(String(error));
    // Postgres unique_violation. A concurrent compat call inserted the row
    // for this platform-scoped external session before we could; re-fetch and
    // return that row instead of bubbling a 500 to the legacy client.
    if ((err as Error & { code?: string }).code === '23505') {
      const racedRow = await repo.findByExternalIdForScope({
        externalSessionId: input.contentSessionId,
        projectId: input.projectId,
        teamId: input.teamId,
        platformSource,
      });
      if (racedRow) {
        return { id: racedRow.id, projectId: racedRow.projectId, teamId: racedRow.teamId };
      }
    }
    throw error;
  }
}