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

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

import { logger } from '../../../utils/logger.js';
import {
  ServerClassifiedProviderError,
  parseRetryAfterMs,
} from './shared/error-classification.js';
import { buildServerGenerationPrompt } from './shared/prompt-builder.js';
import type {
  ServerGenerationContext,
  ServerGenerationProvider,
  ServerGenerationResult,
} from './shared/types.js';
import { readCappedErrorBody } from '../../../shared/capped-error-body.js';
import { DEFAULT_OBSERVER_THINKING_BUDGET_TOKENS, type ObserverThinkingOption } from '../../../sdk/hardened-options.js';

const ANTHROPIC_DEFAULT_BASE_URL = 'https://api.anthropic.com';
const ANTHROPIC_VERSION = '2023-06-01';
// #2554 — the previous default `claude-3-5-sonnet-latest` is stale and 404s on
// the current Anthropic Messages API. Align with the repo's canonical default
// model (CLAUDE_MEM_MODEL in src/ui/viewer/constants/settings.ts and the
// installer's model list) so a server with no explicit CLAUDE_MEM_SERVER_MODEL
// generates against a valid model id instead of failing every job with a 404.
export const DEFAULT_SERVER_CLAUDE_MODEL = 'claude-sonnet-5';
const DEFAULT_MODEL = DEFAULT_SERVER_CLAUDE_MODEL;

export interface ClaudeObservationProviderOptions {
  apiKey: string;
  model?: string;
  maxOutputTokens?: number;
  fetchImpl?: typeof fetch;
  // Anthropic-API-compatible gateway base URL (no path suffix — `/v1/messages`
  // is appended), for deployments that don't call api.anthropic.com directly.
  // Defaults to the real Anthropic API.
  baseUrl?: string;
  // The worker's CLAUDE_MEM_OBSERVER_THINKING policy (#4732), parsed by
  // resolveObserverThinkingOption; instantiateServerGenerationProvider passes
  // it, so the server defaults to `disabled` as the worker does: a model that
  // thinks by default (Claude Haiku 5.5) bills it as output and spends
  // max_tokens on it, up to a reply with no text. Unset here sends no field,
  // as before, for providers built directly by a custom module.
  thinking?: ObserverThinkingOption;
  // Extra request headers, such as a gateway's own auth header
  // (`cf-aig-authorization` on Cloudflare AI Gateway). They can't replace the
  // API key, version or content type.
  extraHeaders?: Record<string, string>;
}

interface AnthropicMessagesResponse {
  content?: Array<{ type?: string; text?: string }>;
  stop_reason?: string;
  usage?: { input_tokens?: number; output_tokens?: number };
  error?: { type?: string; message?: string };
}

/**
 * The Messages endpoint a provider built with this base URL posts to: the
 * custom base (trimmed, trailing slashes dropped) or api.anthropic.com, plus
 * /v1/messages. Exported so the runtime checks the cmem key lock against the
 * exact URL the key would be sent to.
 */
export function resolveAnthropicMessagesUrl(baseUrl?: string): string {
  return `${(baseUrl?.trim() || ANTHROPIC_DEFAULT_BASE_URL).replace(/\/+$/, '')}/v1/messages`;
}

export class ClaudeObservationProvider implements ServerGenerationProvider {
  readonly providerLabel = 'claude' as const;
  private readonly apiKey: string;
  private readonly model: string;
  private readonly maxOutputTokens: number;
  private readonly fetchImpl: typeof fetch;
  private readonly messagesUrl: string;
  private readonly thinking: ObserverThinkingOption;
  private readonly extraHeaders: Record<string, string>;

  constructor(options: ClaudeObservationProviderOptions) {
    if (!options.apiKey) {
      throw new ServerClassifiedProviderError('Anthropic API key not configured', {
        kind: 'auth_invalid',
        cause: new Error('apiKey is required'),
      });
    }
    this.apiKey = options.apiKey;
    this.model = options.model ?? DEFAULT_MODEL;
    this.maxOutputTokens = options.maxOutputTokens ?? 4096;
    this.fetchImpl = options.fetchImpl ?? fetch;
    this.messagesUrl = resolveAnthropicMessagesUrl(options.baseUrl);
    this.thinking = options.thinking ?? 'omit';
    this.extraHeaders = options.extraHeaders ?? {};
  }

  async generate(
    context: ServerGenerationContext,
    signal?: AbortSignal,
  ): Promise<ServerGenerationResult> {
    const { prompt, skippedAll, noEvents } = buildServerGenerationPrompt(context);
    // Nothing was loaded, so there is nothing to summarise and no question to
    // ask a model. Answering it anyway bought `<skip_summary />` and recorded
    // the result as an ordinary completion; the reason below names it instead.
    if (noEvents) {
      return {
        rawText: '<skip_summary reason="no_events_loaded" />',
        providerLabel: this.providerLabel,
        modelId: this.model,
      };
    }
    if (skippedAll) {
      // All events were scrubbed by privacy stripping. Don't bill the
      // provider — return a synthetic skip response that parser accepts.
      return {
        rawText: '<skip_summary reason="all_events_private" />',
        providerLabel: this.providerLabel,
        modelId: this.model,
      };
    }

    let response: Response;
    try {
      response = await this.postMessages(prompt, signal);
    } catch (networkError) {
      const err = networkError instanceof Error ? networkError : new Error(String(networkError));
      throw classifyClaudeServerError({
        cause: err,
      });
    }

    if (!response.ok) {
      const bodyText = await safeReadBody(response);
      throw classifyClaudeServerError({
        status: response.status,
        bodyText,
        headers: response.headers,
        cause: new Error(`Anthropic API error: ${response.status} - ${bodyText}`),
      });
    }

    let data: AnthropicMessagesResponse;
    try {
      data = (await response.json()) as AnthropicMessagesResponse;
    } catch (parseError) {
      const err = parseError instanceof Error ? parseError : new Error(String(parseError));
      throw new ServerClassifiedProviderError('Anthropic returned invalid JSON', {
        kind: 'parse_error',
        cause: err,
      });
    }

    if (data.error) {
      throw classifyClaudeServerError({
        status: response.status,
        bodyText: `${data.error.type ?? ''} ${data.error.message ?? ''}`,
        headers: response.headers,
        cause: new Error(`Anthropic API error: ${data.error.type} - ${data.error.message}`),
      });
    }

    const blocks = Array.isArray(data.content) ? data.content : [];
    const rawText = blocks
      .filter(block => block?.type === 'text' && typeof block.text === 'string')
      .map(block => block.text!)
      .join('\n')
      .trim();

    // A reply cut off at the output-token cap loses its tail, or all of it when
    // thinking spent the cap first; say so rather than store it silently.
    if (data.stop_reason === 'max_tokens') {
      logger.error('SDK', 'Anthropic reply was cut off at max_tokens; the unfinished tail is lost. Raise CLAUDE_MEM_SERVER_MAX_OUTPUT_TOKENS if this repeats', {
        provider: 'claude',
        model: this.model,
        maxTokens: this.requestMaxTokens(),
        hasText: rawText !== '',
      });
    } else if (!rawText) {
      logger.warn('SDK', 'Anthropic returned empty content array', {
        provider: 'claude',
        model: this.model,
      });
    }

    const usage = data.usage ?? {};
    const tokensUsed =
      typeof usage.input_tokens === 'number' || typeof usage.output_tokens === 'number'
        ? (usage.input_tokens ?? 0) + (usage.output_tokens ?? 0)
        : undefined;

    return {
      rawText,
      ...(tokensUsed !== undefined ? { tokensUsed } : {}),
      providerLabel: this.providerLabel,
      modelId: this.model,
    };
  }

  private postMessages(prompt: string, signal?: AbortSignal): Promise<Response> {
    return this.fetchImpl(this.messagesUrl, {
      method: 'POST',
      headers: this.requestHeaders(),
      // No temperature, as on the worker's Agent SDK path: Claude Haiku 5.5
      // rejects any request that sets one.
      body: JSON.stringify({
        model: this.model,
        max_tokens: this.requestMaxTokens(),
        messages: [{ role: 'user', content: prompt }],
        ...this.thinkingField(),
      }),
      signal,
    });
  }

  // Header names are case-insensitive, so the fixed headers are set last on a
  // Headers object: an extra `X-Api-Key` is replaced, not sent beside the key.
  private requestHeaders(): Headers {
    const headers = new Headers(this.extraHeaders);
    headers.set('Content-Type', 'application/json');
    headers.set('x-api-key', this.apiKey);
    headers.set('anthropic-version', ANTHROPIC_VERSION);
    return headers;
  }

  // An enabled thinking budget gets its own tokens on top of the answer's
  // cap, as the worker's reasoning budget does (#5033); the API also requires
  // max_tokens above budget_tokens.
  private requestMaxTokens(): number {
    const thinking = this.thinking;
    return thinking && thinking !== 'omit' && thinking.type === 'enabled'
      ? this.maxOutputTokens + (thinking.budgetTokens ?? DEFAULT_OBSERVER_THINKING_BUDGET_TOKENS)
      : this.maxOutputTokens;
  }

  private thinkingField(): { thinking?: Record<string, unknown> } {
    if (this.thinking === 'omit' || !this.thinking) return {};
    if (this.thinking.type === 'enabled') {
      return { thinking: { type: 'enabled', budget_tokens: this.thinking.budgetTokens ?? DEFAULT_OBSERVER_THINKING_BUDGET_TOKENS } };
    }
    return { thinking: { type: this.thinking.type } };
  }
}

interface ClassifyInput {
  status?: number;
  bodyText?: string;
  headers?: Headers | { get(name: string): string | null };
  cause: unknown;
}

/**
 * Anthropic-specific HTTP error classification. Mirrors worker
 * `classifyClaudeError`, but extracted for server-beta and rebound to
 * Anthropic Messages REST semantics rather than SDK error classes.
 */
export function classifyClaudeServerError(input: ClassifyInput): ServerClassifiedProviderError {
  const status = input.status;
  const body = input.bodyText ?? '';
  const lower = body.toLowerCase();
  const retryAfterMs = input.headers ? parseRetryAfterMs(input.headers.get('retry-after')) : undefined;

  if (lower.includes('overloaded')) {
    return new ServerClassifiedProviderError(
      `Anthropic overloaded${status !== undefined ? ` (status ${status})` : ''}`,
      { kind: 'transient', cause: input.cause },
    );
  }

  if (status === 401 || status === 403 || lower.includes('invalid api key')) {
    return new ServerClassifiedProviderError(
      `Anthropic auth invalid${status !== undefined ? ` (status ${status})` : ''}`,
      { kind: 'auth_invalid', cause: input.cause },
    );
  }

  if (status === 429) {
    return new ServerClassifiedProviderError('Anthropic rate limit (429)', {
      kind: 'rate_limit',
      cause: input.cause,
      ...(retryAfterMs !== undefined ? { retryAfterMs } : {}),
    });
  }

  if (lower.includes('quota exceeded')) {
    return new ServerClassifiedProviderError('Anthropic quota exhausted', {
      kind: 'quota_exhausted',
      cause: input.cause,
    });
  }

  if (
    lower.includes('prompt is too long') ||
    lower.includes('context window') ||
    lower.includes('max_tokens')
  ) {
    return new ServerClassifiedProviderError('Anthropic context overflow', {
      kind: 'unrecoverable',
      cause: input.cause,
    });
  }

  if (status === 529) {
    return new ServerClassifiedProviderError('Anthropic overloaded (529)', {
      kind: 'transient',
      cause: input.cause,
    });
  }

  if (status !== undefined && status >= 500 && status < 600) {
    return new ServerClassifiedProviderError(`Anthropic upstream error (status ${status})`, {
      kind: 'transient',
      cause: input.cause,
    });
  }

  if (status === 400) {
    return new ServerClassifiedProviderError('Anthropic bad request (400)', {
      kind: 'unrecoverable',
      cause: input.cause,
    });
  }

  if (status === undefined) {
    const message = input.cause instanceof Error ? input.cause.message : String(input.cause);
    return new ServerClassifiedProviderError(`Anthropic network error: ${message}`, {
      kind: 'transient',
      cause: input.cause,
    });
  }

  return new ServerClassifiedProviderError(
    `Anthropic API error: ${status}${body ? ` - ${body.substring(0, 200)}` : ''}`,
    { kind: 'unrecoverable', cause: input.cause },
  );
}

async function safeReadBody(response: Response): Promise<string> {
  try {
    return await readCappedErrorBody(response);
  } catch (error) {
    const err = error instanceof Error ? error : new Error(String(error));
    logger.warn('SDK', 'Failed to read Anthropic error response body', {
      provider: 'claude',
      status: response.status,
    }, err);
    return '';
  }
}