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

11.0 KB
Raw Blame
/**
 * CLAUDE_MEM_OPENAI_COMPAT_SESSION_ENDPOINTS: a JSON object mapping a
 * session's observer provider id to the OpenAI-compatible endpoint that should
 * serve that session, e.g.
 * {"opencode-go":{"baseUrl":"https://…/v1","modelMap":{"session-model":"endpoint-model"},"keyIndexes":[1]}}.
 *
 * NO CREDENTIAL LIVES IN THIS MAP. A mapping only chooses a destination, a
 * model translation and which keys of the configured
 * CLAUDE_MEM_OPENAI_COMPAT_API_KEY / CLAUDE_MEM_OPENAI_COMPAT_API_KEYS pool that
 * destination may receive (`keyIndexes`, 0-based positions in that pool). The
 * pool stays the only credential store, so an unknown field such as `apiKey`
 * is dropped with a warning instead of being read. The setting is file/env only (never the HTTP settings API),
 * empty means off, and it is capped so one bad value cannot grow unbounded.
 *
 * One parse for every consumer, so validation warnings and dispatch agree.
 */

import { MAX_POOL_KEYS } from './api-key-pool.js';

export const MAX_SESSION_ENDPOINTS = 32;
export const MAX_SESSION_MODEL_MAP_ENTRIES = 64;
/** Same ceiling as the session-init model and provider ids these translate. */
export const MAX_MODEL_ID_LENGTH = 200;
const SESSION_ENDPOINTS_SETTING = 'CLAUDE_MEM_OPENAI_COMPAT_SESSION_ENDPOINTS';

export interface OpenAICompatSessionEndpoint {
  baseUrl: string;
  modelMap?: Readonly<Record<string, string>>;
  /**
   * 0-based positions in the configured key pool that this endpoint may
   * receive. Absent means the entry names no key, which the provider accepts
   * only while the pool holds at most one key, so one vendor's key is never
   * rotated onto another vendor's endpoint.
   */
  keyIndexes?: readonly number[];
}

export interface ParsedOpenAICompatSessionEndpoints {
  endpoints: ReadonlyMap<string, OpenAICompatSessionEndpoint>;
  /** One aggregated line naming provider ids with a dropped entry, field or model-map pair; never a value. */
  warning?: string;
}

/**
 * Provider ids and model ids name a key, not a payload: no spaces or controls,
 * and no longer than the session-init schema accepts. The rule applies to both
 * sides of a model-map pair; a value is sent verbatim, so it cannot be looser
 * than the key that selects it.
 */
const KEY_WITH_SPACE_OR_CONTROL = /[\s\x00-\x1f\x7f]/;
/** Hard cap on provider ids named in the aggregated warning; the rest are counted. */
const MAX_REPORTED_PROVIDER_IDS = 20;

function invalidValueWarning(detail: string): string {
  return `${SESSION_ENDPOINTS_SETTING} ${detail}; the value was ignored`;
}

/**
 * A provider id is echoed in the warning, so a URL used as an id must not carry
 * its userinfo into the log: `https://user:pass@host/v1` → `https://***@host/v1`
 * (and a scheme-less `user:pass@host` → `***@host`). Mask everything up to the
 * LAST `@` of the authority, so a password that itself contains `@` is not
 * half-left in the line, and stop at the first `/` so an `@` in the path stays
 * untouched. Exported for the other lines that echo a provider id, so every
 * log surface masks it the same way.
 */
export function redactUserinfo(id: string): string {
  // Two slashes may follow a scheme (`https://`) or stand alone (`//host`).
  const scheme = /^(?:[a-z][a-z0-9+.-]*:)?\/\//i.exec(id);
  const authorityStart = scheme ? scheme[0].length : 0;
  const pathStart = id.indexOf('/', authorityStart);
  const authorityEnd = pathStart === -1 ? id.length : pathStart;
  const lastAt = id.lastIndexOf('@', authorityEnd - 1);
  if (lastAt < authorityStart) return id;
  return `${id.slice(0, authorityStart)}***${id.slice(lastAt)}`;
}

function formatProviderIDs(ids: ReadonlySet<string>): string {
  const shown = [...ids].slice(0, MAX_REPORTED_PROVIDER_IDS);
  const remaining = ids.size - shown.length;
  return remaining > 0 ? `${shown.join(', ')}, and ${remaining} more` : shown.join(', ');
}

/**
 * One line for the whole value. It separates an entry that was dropped from a
 * kept entry whose unknown field or model-map pair was dropped, names the
 * provider ids only, and bounds the list so a huge bad value stays readable.
 */
function aggregatedWarning(
  ignoredEntries: ReadonlySet<string>,
  keptWithIgnoredFields: ReadonlySet<string>,
  overCapEntries: ReadonlySet<string>,
): string {
  const parts: string[] = [];
  if (ignoredEntries.size > 0) {
    parts.push(`ignored invalid entries for provider ids: ${formatProviderIDs(ignoredEntries)}`);
  }
  if (keptWithIgnoredFields.size > 0) {
    parts.push(`kept valid entries but ignored unknown fields or unusable model-map entries for provider ids: ${formatProviderIDs(keptWithIgnoredFields)}`);
  }
  if (overCapEntries.size > 0) {
    parts.push(`ignored entries over the cap of ${MAX_SESSION_ENDPOINTS} providers for provider ids: ${formatProviderIDs(overCapEntries)}`);
  }
  return `${SESSION_ENDPOINTS_SETTING} ${parts.join('; ')}`;
}

/**
 * Parse the setting into a provider → endpoint map. Invalid entries are
 * skipped while valid ones stay; the returned warning names only provider ids
 * (never a field name or a field value, and any URL userinfo in an id is
 * masked), so a secret pasted into the map cannot reach the log through this
 * line.
 */
export function parseOpenAICompatSessionEndpoints(raw: unknown): ParsedOpenAICompatSessionEndpoints {
  const endpoints = new Map<string, OpenAICompatSessionEndpoint>();
  if (raw === undefined || raw === null) return { endpoints };
  if (typeof raw !== 'string') {
    // An object written directly in settings.json is the common mistake; the
    // setting is the JSON TEXT, so name the string, not another object.
    return { endpoints, warning: invalidValueWarning('must be a JSON string containing an object mapping a provider id to { baseUrl, modelMap?, keyIndexes? }') };
  }
  const text = raw.trim();
  if (text === '') return { endpoints };

  let parsed: unknown;
  try {
    parsed = JSON.parse(text);
  } catch {
    return { endpoints, warning: invalidValueWarning('is not valid JSON') };
  }
  if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
    return { endpoints, warning: invalidValueWarning('must be a JSON object mapping a provider id to { baseUrl, modelMap?, keyIndexes? }') };
  }

  const ignoredEntries = new Set<string>();
  const keptWithIgnoredFields = new Set<string>();
  const overCapEntries = new Set<string>();
  const report = (providerID: string, kind: 'ignored' | 'fields' | 'over-cap'): void => {
    const id = redactUserinfo(providerID);
    if (kind === 'ignored') {
      // An ignored entry subsumes any field warning for the same provider.
      keptWithIgnoredFields.delete(id);
      ignoredEntries.add(id);
    } else if (kind === 'fields') {
      if (!ignoredEntries.has(id)) keptWithIgnoredFields.add(id);
    } else {
      overCapEntries.add(id);
    }
  };

  for (const [key, value] of Object.entries(parsed)) {
    const providerID = key.trim();
    if (providerID === '' || KEY_WITH_SPACE_OR_CONTROL.test(providerID)) {
      // JSON.stringify keeps a control character escaped on the log line; a
      // blank id still reports the fault without inventing a name.
      ignoredEntries.add(providerID === '' ? '(blank provider id)' : JSON.stringify(redactUserinfo(providerID)));
      continue;
    }
    if (endpoints.size >= MAX_SESSION_ENDPOINTS) {
      report(providerID, 'over-cap');
      continue;
    }
    if (endpoints.has(providerID)) {
      // Two spellings that trim to the same id must not silently overwrite one
      // another; the first entry wins and the duplicate is reported.
      report(providerID, 'ignored');
      continue;
    }
    if (typeof value !== 'object' || value === null || Array.isArray(value)) {
      report(providerID, 'ignored');
      continue;
    }

    const entry = value as Record<string, unknown>;
    const rawBaseUrl = Object.hasOwn(entry, 'baseUrl') ? entry.baseUrl : undefined;
    if (typeof rawBaseUrl !== 'string') {
      report(providerID, 'ignored');
      continue;
    }
    const baseUrl = rawBaseUrl.trim();
    let url: URL;
    try {
      url = new URL(baseUrl);
    } catch {
      report(providerID, 'ignored');
      continue;
    }
    if ((url.protocol !== 'http:' && url.protocol !== 'https:') || url.username !== '' || url.password !== '') {
      report(providerID, 'ignored');
      continue;
    }

    if (Object.keys(entry).some((field) => field !== 'baseUrl' && field !== 'modelMap' && field !== 'keyIndexes')) {
      // A field this map does not define, typically an `apiKey`: ignored, and
      // the provider id is named without recopying the field name or its value.
      report(providerID, 'fields');
    }

    const endpoint: { baseUrl: string; modelMap?: Record<string, string>; keyIndexes?: number[] } = { baseUrl };
    if (Object.hasOwn(entry, 'keyIndexes')) {
      // The list decides which secrets leave for this host, so a malformed one
      // drops the whole entry rather than falling back to "every key".
      const rawIndexes = entry.keyIndexes;
      if (!Array.isArray(rawIndexes) || rawIndexes.length === 0 || rawIndexes.length > MAX_POOL_KEYS
        || !rawIndexes.every((index) => Number.isInteger(index) && index >= 0 && index < MAX_POOL_KEYS)) {
        report(providerID, 'ignored');
        continue;
      }
      endpoint.keyIndexes = [...new Set(rawIndexes as number[])];
    }
    if (Object.hasOwn(entry, 'modelMap')) {
      const rawMap = entry.modelMap;
      if (typeof rawMap !== 'object' || rawMap === null || Array.isArray(rawMap)) {
        report(providerID, 'ignored');
        continue;
      }
      const modelMapPairs: Array<[string, string]> = [];
      const seenModelIDs = new Set<string>();
      for (const [rawModelID, rawEndpointModelID] of Object.entries(rawMap)) {
        if (modelMapPairs.length >= MAX_SESSION_MODEL_MAP_ENTRIES) {
          report(providerID, 'fields');
          break;
        }
        const modelID = rawModelID.trim();
        const endpointModelID = typeof rawEndpointModelID === 'string' ? rawEndpointModelID.trim() : '';
        if (modelID === '' || KEY_WITH_SPACE_OR_CONTROL.test(modelID) || modelID.length > MAX_MODEL_ID_LENGTH
          || endpointModelID === '' || KEY_WITH_SPACE_OR_CONTROL.test(endpointModelID)
          || endpointModelID.length > MAX_MODEL_ID_LENGTH) {
          report(providerID, 'fields');
          continue;
        }
        if (seenModelIDs.has(modelID)) {
          // First spelling wins, like duplicate provider ids; a later one must
          // not silently replace the translation.
          report(providerID, 'fields');
          continue;
        }
        seenModelIDs.add(modelID);
        modelMapPairs.push([modelID, endpointModelID]);
      }
      // Object.fromEntries defines own properties, so an id like `__proto__`
      // stays data instead of reaching the prototype setter.
      if (modelMapPairs.length > 0) endpoint.modelMap = Object.fromEntries(modelMapPairs);
    }

    endpoints.set(providerID, endpoint);
  }

  if (ignoredEntries.size === 0 && keptWithIgnoredFields.size === 0 && overCapEntries.size === 0) {
    return { endpoints };
  }
  return { endpoints, warning: aggregatedWarning(ignoredEntries, keptWithIgnoredFields, overCapEntries) };
}