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

20.0 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
//
// Phase 7 — Server HTTP client used by hook subcommands when the
// installer/setting selects the server runtime. This client speaks
// directly to the server runtime's `/v1/*` endpoints. It MUST NOT
// import or transitively depend on the worker runtime: the whole point
// of phase 7 is that hooks can reach the server even when no worker is
// running.
//
// On any transport-class failure (timeout, ECONNREFUSED, 5xx, missing
// API key, etc.) callers receive a typed `ServerClientError` so the
// hook handler can decide whether to fall back to the worker path.

import { fetchWithTimeout } from '../../shared/worker-utils.js';
import { HOOK_TIMEOUTS, getTimeout } from '../../shared/hook-constants.js';
import { normalizePlatformSource } from '../../shared/platform-source.js';
import { stripMemoryTags, stripMemoryTagsFromJsonStrings } from '../../utils/tag-stripping.js';
import { redactJsonStrings } from '../../utils/redaction.js';
import { retainTextHeadTail } from '../../shared/text-truncation.js';

const DEFAULT_TIMEOUT_MS = getTimeout(HOOK_TIMEOUTS.API_REQUEST);

export type ServerClientErrorKind =
  | 'missing_api_key'
  | 'transport'
  | 'timeout'
  | 'http_error'
  | 'invalid_response';

export class ServerClientError extends Error {
  readonly kind: ServerClientErrorKind;
  readonly status: number | null;
  readonly cause?: unknown;

  constructor(kind: ServerClientErrorKind, message: string, options: {
    status?: number | null;
    cause?: unknown;
  } = {}) {
    super(message);
    this.name = 'ServerClientError';
    this.kind = kind;
    this.status = options.status ?? null;
    this.cause = options.cause;
  }

  isFallbackEligible(): boolean {
    if (this.kind === 'transport' || this.kind === 'timeout' || this.kind === 'missing_api_key') {
      return true;
    }
    if (this.kind === 'http_error') {
      // 5xx and 429 are transient; fall back. 4xx other than 429 is a real
      // client bug — surface it via the worker path so it can be observed.
      if (this.status !== null && this.status >= 500) return true;
      if (this.status === 429) return true;
    }
    return false;
  }
}

export interface ServerClientConfig {
  serverBaseUrl: string;
  apiKey: string;
  timeoutMs?: number;
}

export interface ServerRequestOptions {
  timeoutMs?: number;
}

export interface ServerStartSessionRequest {
  projectId: string;
  externalSessionId?: string | null;
  contentSessionId?: string | null;
  agentId?: string | null;
  agentType?: string | null;
  platformSource?: string | null;
  metadata?: Record<string, unknown>;
}

export interface ServerStartSessionResponse {
  session: {
    id: string;
    projectId: string;
    teamId: string;
    externalSessionId: string | null;
    contentSessionId: string | null;
    [key: string]: unknown;
  };
}

export interface ServerRecordEventRequest {
  projectId: string;
  serverSessionId?: string | null;
  contentSessionId?: string | null;
  memorySessionId?: string | null;
  platformSource?: string | null;
  sourceType: 'hook' | 'worker' | 'provider' | 'server' | 'api';
  eventType: string;
  payload?: unknown;
  occurredAtEpoch: number;
  // When false, the event is recorded but no generation job is enqueued.
  // Maps to the REST endpoint's `?generate=false` query flag.
  generate?: boolean;
}

export interface ServerRecordEventResponse {
  event: {
    id: string;
    projectId: string;
    serverSessionId: string | null;
    [key: string]: unknown;
  };
  generationJob?: {
    id: string;
    status: string;
    [key: string]: unknown;
  };
}

export interface ServerEndSessionRequest {
  sessionId: string;
}

export interface ServerEndSessionResponse {
  session: {
    id: string;
    [key: string]: unknown;
  };
  generationJob?: {
    id: string;
    status: string;
    [key: string]: unknown;
  };
}

// Phase 8 — direct/manual observation insertion through `/v1/memories`.
// This calls the same Postgres repository path as the REST core, so MCP
// and REST never diverge on what counts as a valid observation insert.
export interface ServerAddObservationRequest {
  projectId: string;
  serverSessionId?: string | null;
  // Callers inside a session know the agent's own session id, not the
  // server_sessions row UUID; the server resolves it (mirrors /v1/events).
  contentSessionId?: string | null;
  platformSource?: string | null;
  kind?: string;
  content: string;
  metadata?: Record<string, unknown>;
}

export interface ServerAddObservationResponse {
  memory: {
    id: string;
    projectId: string;
    teamId: string;
    serverSessionId: string | null;
    kind: string;
    content: string;
    metadata: Record<string, unknown>;
    [key: string]: unknown;
  };
}

// Phase 8 — full-text search over generated observations.
export interface ServerSearchObservationsRequest {
  projectId: string;
  query: string;
  limit?: number;
  platformSource?: string | null;
}

export interface ServerSearchObservationsResponse {
  observations: Array<{
    id: string;
    projectId: string;
    content: string;
    [key: string]: unknown;
  }>;
}

// Phase 8 — context pack for prompt injection. Server returns both the
// matched observations AND a pre-joined `context` string.
export interface ServerContextObservationsRequest {
  projectId: string;
  // OPTIONAL, and the whole session-start read depends on it being optional.
  // With a query the route is FTS and answers by relevance; with the key ABSENT
  // it answers by recency, which is what a session-start block is. An empty
  // STRING is not the same thing -- the route's schema requires >=1 character
  // and rejects `""` -- so the key must be omitted, never blanked.
  query?: string;
  limit?: number;
  // In recency mode, reserve this portion of limit for session summaries.
  summaryLimit?: number;
  platformSource?: string | null;
  // Folder labels (observations.metadata.project) to scope the read to. Omitted
  // or empty means every folder in the server project.
  folderProjects?: string[];
  // Leave out rows generated from subagent events (CLAUDE_MEM_CONTEXT_MAIN_AGENT_ONLY).
  excludeSubagents?: boolean;
  // Active-mode filters for observations. Empty selects none; summaries keep
  // their own allowance. Omitted preserves the unfiltered API contract.
  observationTypes?: string[];
  observationConcepts?: string[];
}

export interface ServerContextObservationsResponse {
  observations: Array<{
    id: string;
    projectId: string;
    content: string;
    [key: string]: unknown;
  }>;
  context: string;
}

export interface ServerTimelineRequest {
  projectId: string;
  anchorId: string;
  depthBefore?: number;
  depthAfter?: number;
}
export interface ServerSelectedObservationsRequest {
  projectId: string;
  ids: string[];
}

// Per-prompt injection (CLAUDE_MEM_SEMANTIC_INJECT): observations near the
// prompt in meaning, rendered like the worker's /api/context/semantic.
export interface ServerSemanticContextRequest {
  projectId: string;
  query: string;
  limit?: number;
  platformSource?: string | null;
  folderProjects?: string[];
  // The Claude Code session id, as on /v1/sessions/start and /v1/events, so
  // the server can leave out the asking session's own recent observations.
  contentSessionId?: string | null;
}

export interface ServerSemanticContextResponse {
  context: string;
  count: number;
}

// Phase 8 — generation job status, scoped by api-key team/project.
export interface ServerJobStatusResponse {
  generationJob: {
    id: string;
    status: string;
    [key: string]: unknown;
  };
}

export class ServerClient {
  private readonly baseUrl: string;
  private readonly apiKey: string;
  private readonly timeoutMs: number;

  constructor(config: ServerClientConfig) {
    this.baseUrl = stripTrailingSlash(config.serverBaseUrl);
    this.apiKey = config.apiKey;
    this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
  }

  async startSession(
    input: ServerStartSessionRequest,
    options: ServerRequestOptions = {},
  ): Promise<ServerStartSessionResponse> {
    const body = this.buildStartSessionPayload(input);
    return this.request<ServerStartSessionResponse>('POST', '/v1/sessions/start', body, options);
  }

  async recordEvent(
    input: ServerRecordEventRequest,
    options: ServerRequestOptions = {},
  ): Promise<ServerRecordEventResponse> {
    const body = this.buildEventPayload(input);
    const path = input.generate === false ? '/v1/events?generate=false' : '/v1/events';
    return this.request<ServerRecordEventResponse>('POST', path, body, options);
  }

  async endSession(input: ServerEndSessionRequest): Promise<ServerEndSessionResponse> {
    if (!input.sessionId) {
      throw new ServerClientError('invalid_response', 'sessionId is required for endSession');
    }
    return this.request<ServerEndSessionResponse>(
      'POST',
      `/v1/sessions/${encodeURIComponent(input.sessionId)}/end`,
      {},
    );
  }

  // Phase 8 — direct observation insert (MCP `observation_add`). Calls
  // `/v1/memories`, which is the canonical write path that MUST NOT enqueue
  // a generation job. Anti-pattern guard for plan line 770: never duplicate
  // generation logic in MCP tools.
  async addObservation(
    input: ServerAddObservationRequest,
  ): Promise<ServerAddObservationResponse> {
    return this.request<ServerAddObservationResponse>(
      'POST',
      '/v1/memories',
      this.buildAddObservationPayload(input),
    );
  }

  // Phase 8 — MCP `observation_search`. Routes to the FTS-backed REST
  // endpoint so search ranking and tenant scoping are owned by one place.
  async searchObservations(
    input: ServerSearchObservationsRequest,
  ): Promise<ServerSearchObservationsResponse> {
    return this.request<ServerSearchObservationsResponse>(
      'POST',
      '/v1/search',
      this.buildSearchPayload(input),
    );
  }

  async timelineObservations(input: ServerTimelineRequest): Promise<ServerSearchObservationsResponse> {
    return this.request<ServerSearchObservationsResponse>('POST', '/v1/timeline', input);
  }

  async selectedObservations(input: ServerSelectedObservationsRequest): Promise<ServerSearchObservationsResponse> {
    return this.request<ServerSearchObservationsResponse>('POST', '/v1/observations/batch', input);
  }

  // Phase 8 — MCP `observation_context` and the server-runtime session-start
  // read. With a query this is the same FTS surface as search; without one the
  // route returns the most recent rows. Either way it also returns a pre-joined
  // context string.
  async contextObservations(
    input: ServerContextObservationsRequest,
    options: ServerRequestOptions = {},
  ): Promise<ServerContextObservationsResponse> {
    // Built here rather than through buildSearchPayload(): that helper is the
    // /v1/search contract, where a query is genuinely required, and widening it
    // would let a search ship without one.
    const payload: Record<string, unknown> = { projectId: input.projectId };
    if (input.query !== undefined) payload.query = input.query;
    if (input.limit !== undefined) payload.limit = input.limit;
    if (input.summaryLimit !== undefined) payload.summaryLimit = input.summaryLimit;
    if (input.platformSource !== undefined) {
      payload.platformSource = normalizePlatformSourceField(input.platformSource);
    }
    if (input.folderProjects && input.folderProjects.length > 0) {
      payload.folderProjects = input.folderProjects;
    }
    if (input.excludeSubagents !== undefined) payload.excludeSubagents = input.excludeSubagents;
    if (input.observationTypes !== undefined) payload.observationTypes = input.observationTypes;
    if (input.observationConcepts !== undefined) payload.observationConcepts = input.observationConcepts;
    return this.request<ServerContextObservationsResponse>('POST', '/v1/context', payload, options);
  }

  async semanticContext(
    input: ServerSemanticContextRequest,
    options: ServerRequestOptions = {},
  ): Promise<ServerSemanticContextResponse> {
    // The query is the user's prompt; <private> sections never leave the hook.
    const payload: Record<string, unknown> = { projectId: input.projectId, query: stripMemoryTags(input.query) };
    if (input.limit !== undefined) payload.limit = input.limit;
    if (input.platformSource !== undefined) {
      payload.platformSource = normalizePlatformSourceField(input.platformSource);
    }
    if (input.folderProjects && input.folderProjects.length > 0) {
      payload.folderProjects = input.folderProjects;
    }
    if (input.contentSessionId) payload.contentSessionId = input.contentSessionId;
    return this.request<ServerSemanticContextResponse>('POST', '/v1/context/semantic', payload, options);
  }

  // Phase 8 — MCP `observation_generation_status`. Server returns the same
  // payload as `/v1/jobs/:id` so MCP clients and REST clients see identical
  // job status (including transport state).
  async getJobStatus(jobId: string): Promise<ServerJobStatusResponse> {
    if (!jobId) {
      throw new ServerClientError('invalid_response', 'jobId is required for getJobStatus');
    }
    return this.request<ServerJobStatusResponse>(
      'GET',
      `/v1/jobs/${encodeURIComponent(jobId)}`,
    );
  }

  buildAddObservationPayload(
    input: ServerAddObservationRequest,
  ): Record<string, unknown> {
    // Write-path contract. This client is constructed ONLY on the `server`
    // runtime (runtime-selector.ts `buildServerContext`), so the only
    // /v1/memories it can ever reach is ServerV1PostgresRoutes, which validates
    // `content: z.string().min(1)` and writes an `observations` row through
    // PostgresObservationRepository.
    //
    // It previously mapped `content` onto `narrative` and added `type`, citing
    // #2684 / CreateMemoryItemSchema / `memory_items`. That is the contract of
    // the OTHER /v1/memories — ServerV1Routes, the SQLite route mounted by
    // worker-service — which this client never talks to: the `worker` runtime
    // returns before a ServerClient is built. `memory_items` does not exist in
    // the server database at all.
    //
    // Observed on a live `server` runtime: every MCP `observation_add`
    // returned 400 ValidationError "path":["content"], so the direct-write
    // surface was unusable rather than merely untested.
    const content = input.content;
    const kind = input.kind ?? 'manual';
    const metadataTitle = typeof input.metadata?.title === 'string' ? input.metadata.title : undefined;
    return {
      projectId: input.projectId,
      kind,
      content,
      ...(metadataTitle ? { title: metadataTitle } : {}),
      ...(input.serverSessionId !== undefined ? { serverSessionId: input.serverSessionId } : {}),
      // Forward the in-session identifiers so the server can resolve the
      // server_sessions row itself; without these the memory lands unlinked.
      ...(input.contentSessionId !== undefined ? { contentSessionId: input.contentSessionId } : {}),
      ...(input.platformSource !== undefined ? { platformSource: input.platformSource } : {}),
      ...(input.metadata !== undefined ? { metadata: input.metadata } : {}),
    };
  }

  buildSearchPayload(
    input: { projectId: string; query: string; limit?: number; platformSource?: string | null },
  ): Record<string, unknown> {
    return {
      projectId: input.projectId,
      query: input.query,
      ...(input.limit !== undefined ? { limit: input.limit } : {}),
      ...(input.platformSource !== undefined ? { platformSource: normalizePlatformSourceField(input.platformSource) } : {}),
    };
  }

  buildStartSessionPayload(input: ServerStartSessionRequest): Record<string, unknown> {
    return {
      projectId: input.projectId,
      ...(input.externalSessionId !== undefined ? { externalSessionId: input.externalSessionId } : {}),
      ...(input.contentSessionId !== undefined ? { contentSessionId: input.contentSessionId } : {}),
      ...(input.agentId !== undefined ? { agentId: input.agentId } : {}),
      ...(input.agentType !== undefined ? { agentType: input.agentType } : {}),
      ...(input.platformSource !== undefined ? { platformSource: normalizePlatformSourceField(input.platformSource) } : {}),
      // The prompt rides in metadata. Apply the hook's redaction settings
      // before transport as well as removing explicitly private sections.
      ...(input.metadata !== undefined ? { metadata: redactJsonStrings(stripMemoryTagsFromJsonStrings(input.metadata)) } : {}),
    };
  }

  buildEventPayload(input: ServerRecordEventRequest): Record<string, unknown> {
    return {
      projectId: input.projectId,
      sourceType: input.sourceType,
      eventType: input.eventType,
      occurredAtEpoch: input.occurredAtEpoch,
      ...(input.serverSessionId !== undefined ? { serverSessionId: input.serverSessionId } : {}),
      ...(input.contentSessionId !== undefined ? { contentSessionId: input.contentSessionId } : {}),
      ...(input.memorySessionId !== undefined ? { memorySessionId: input.memorySessionId } : {}),
      ...(input.platformSource !== undefined ? { platformSource: normalizePlatformSourceField(input.platformSource) } : {}),
      // Every server-bound event (tool use, file edit, assistant message, MCP
      // record_event) passes here: <private> sections never leave the hook,
      // the same rule worker ingest applies before storing tool data.
      ...(input.payload !== undefined ? { payload: redactJsonStrings(stripMemoryTagsFromJsonStrings(input.payload)) } : {}),
    };
  }

  private async request<T>(
    method: 'GET' | 'POST',
    path: string,
    body?: unknown,
    options: ServerRequestOptions = {},
  ): Promise<T> {
    if (!this.apiKey || !this.apiKey.trim()) {
      throw new ServerClientError(
        'missing_api_key',
        'Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).',
      );
    }

    const url = `${this.baseUrl}${path}`;
    const init: RequestInit = {
      method,
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${this.apiKey}`,
      },
    };
    if (body !== undefined) {
      init.body = JSON.stringify(body);
    }

    const transportFailure = (error: unknown): ServerClientError => {
      const message = error instanceof Error ? error.message : String(error);
      const isTimeout = /timed out|timeout/i.test(message)
        || (error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError'));
      return new ServerClientError(
        isTimeout ? 'timeout' : 'transport',
        `Server ${method} ${path} failed: ${message}`,
        { cause: error },
      );
    };
    let response: Response;
    const timeoutMs = options.timeoutMs ?? this.timeoutMs;
    try {
      response = await fetchWithTimeout(url, init, timeoutMs);
    } catch (error: unknown) {
      throw transportFailure(error);
    }

    if (!response.ok) {
      const text = await response.text().catch(() => '');
      throw new ServerClientError(
        'http_error',
        `Server ${method} ${path} returned ${response.status}: ${truncate(text, 200)}`,
        { status: response.status },
      );
    }

    let text: string;
    try {
      text = await response.text();
    } catch (error: unknown) {
      throw transportFailure(error);
    }
    if (!text || text.length === 0) {
      // Endpoints we call always return JSON; a body-less success is unusual
      // but not fatal — return undefined-shaped object.
      return {} as T;
    }
    try {
      return JSON.parse(text) as T;
    } catch (error: unknown) {
      const err = error instanceof Error ? error : new Error(String(error));
      throw new ServerClientError(
        'invalid_response',
        `Server ${method} ${path} returned non-JSON response`,
        { cause: err },
      );
    }
  }
}

export function isServerClientError(error: unknown): error is ServerClientError {
  return error instanceof ServerClientError;
}

function stripTrailingSlash(url: string): string {
  return url.replace(/\/+$/, '');
}

function normalizePlatformSourceField(value: string | null): string | null {
  return typeof value === 'string' ? normalizePlatformSource(value) : null;
}

function truncate(text: string, max: number): string {
  if (text.length <= max) return text;
  return `${retainTextHeadTail(text, max, 0).head}…`;
}