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

67.0 KB
Raw Blame

import { getCredential } from '../../shared/EnvManager.js';
import { isOpenRouterApiUrl, resolveOpenRouterChatCompletionsUrl } from '../../shared/openrouter-base-url.js';
import { openRouterAttributionHeaders, OPENROUTER_APP_TITLE } from '../../shared/openrouter-attribution.js';
import { isMaxCompletionTokensCompatibilityError } from '../../shared/openrouter-token-compatibility.js';
import { describeNetworkFailure, isConnectionRefused, networkFailureSuffix } from '../../shared/network-failure.js';
import { parseOpenRouterExtraBody, withOpenRouterExtraBody } from '../../shared/openrouter-extra-body.js';
import { SettingsDefaultsManager } from '../../shared/SettingsDefaultsManager.js';
import { USER_SETTINGS_PATH } from '../../shared/paths.js';
import { clearProFallbackOnGatewaySuccess, isCmemGatewayUrl, isKeyAllowedForEndpoint, keysForEndpoint } from '../../shared/cmem-gateway.js';
import { clearCmemCapProbe, cmemCapProbeAllowed, noteCmemCapExhausted } from '../../shared/cmem-cap-probe.js';
import { logger } from '../../utils/logger.js';
import type { ActiveSession, ConversationMessage, PendingMessageWithId } from '../worker-types.js';
import { DatabaseManager } from './DatabaseManager.js';
import { SessionManager } from './SessionManager.js';
import { randomUUID } from 'crypto';
import { buildCmemCorrelationHeader, CMEM_CORRELATION_HEADER } from './cmem-request-correlation.js';
import { CmemAllowanceExhaustedError, ClassifiedProviderError, isClassified, rateLimitUntilNextKey, type ProviderErrorClass } from './provider-errors.js';
import type { PaidSendBudget } from './paid-send-budget.js';
import { withRetry, parseRetryAfterMs } from './retry.js';
import {
  STREAMED_REQUEST_FIELDS,
  resolveStreamIdleTimeoutMs,
  resolveStreamLiveness,
  sendChatCompletion,
  streamsChatCompletion,
  type ChatCompletionExchange,
  type StreamLiveness,
} from './streamed-chat-completion.js';
import { buildKeyPool, resolvePoolKeys, retryPolicyForPool, withKeyPool } from '../../shared/api-key-pool.js';
import {
  OpenAICompatibleProvider,
  assistantText,
  type ObserverRequestLabel,
  type OpenAIChatMessage as OpenAIMessage,
  type ProviderQueryResult,
} from './OpenAICompatibleProvider.js';
import {
  resolveContextWindowTokens,
  resolveObserverMaxOutputTokens,
  DEFAULT_OBSERVER_MAX_OUTPUT_TOKENS,
} from './context-window.js';
import { isContextOverflowObserverOutput } from '../../sdk/output-classifier.js';
import {
  claimReasoningBudgetRetry,
  combineBilledChatUsage,
  isLengthTruncatedEmptyReply,
  isReasoningDisabledRejection,
  reasoningBudgetGiveUpMessage,
  reasoningBudgetRetryMessage,
  reasoningBudgetSkippedMessage,
  OBSERVER_REASONING_BUDGET_TOKENS_BY_EFFORT,
  requestDisablesReasoning,
  startReasoningRetryDeadline,
} from './reasoning-budget.js';
import { namesPeriodRateLimit } from '../../shared/period-rate-limit.js';
import { imageTurnContent, prepareTurnImages, type ChatContentPart, type PreparedTurnMedia, type TurnImage, type TurnImageRequest } from '../media/inference.js';
import { resolveObserverImageCapability } from './media-capability.js';
import { MediaError } from '../../shared/media-contract.js';

/**
 * One chat message in the request body. Every message is string content
 * except, on an image turn, the final user message (imageTurnContent).
 */
export type OpenRouterRequestMessage =
  | OpenAIMessage
  | { role: 'user'; content: ChatContentPart[] };

/** The gateway's bad_request detail for a rejected image request (docs/media-contract-v1.md). */
const MEDIA_REQUEST_INVALID_MARKER = 'media_request_invalid:';

/**
 * The request messages for this turn: unchanged string messages, except that
 * with images the final message, when it is the user turn, becomes the
 * contract's text-first content array. Returns null when the images cannot
 * be attached (no final user message), so the turn goes text-only.
 */
/**
 * The images that fit the contract's request body bound, in request order:
 * each image is kept only if the serialized body with it stays within
 * `maxBodyBytes`. Images that do not fit stay uninspected on their events.
 * Null when none fit (or there is no final user turn): the turn goes text-only.
 */
export function fitTurnImagesToBody(
  messages: OpenAIMessage[],
  request: TurnImageRequest,
  buildBody: (messages: OpenRouterRequestMessage[]) => Record<string, unknown>,
): { messages: OpenRouterRequestMessage[]; images: TurnImage[] } | null {
  let kept: TurnImage[] = [];
  let keptMessages: OpenRouterRequestMessage[] | null = null;
  for (const image of request.images) {
    const candidate = [...kept, image];
    const candidateMessages = withTurnImages(messages, candidate);
    if (!candidateMessages) return null;
    if (Buffer.byteLength(JSON.stringify(buildBody(candidateMessages))) <= request.maxBodyBytes) {
      kept = candidate;
      keptMessages = candidateMessages;
    } else {
      logger.debug('SDK', 'Image left out of the request: the body would exceed its bound', { code: 'image_too_large' });
    }
  }
  return keptMessages && kept.length > 0 ? { messages: keptMessages, images: kept } : null;
}

export function withTurnImages(messages: OpenAIMessage[], turnImages: readonly TurnImage[] | undefined): OpenRouterRequestMessage[] | null {
  if (!turnImages?.length) return messages;
  const last = messages[messages.length - 1];
  if (!last || last.role !== 'user') return null;
  return [...messages.slice(0, -1), { role: 'user', content: imageTurnContent(last.content, turnImages) }];
}

/**
 * OpenAI-compatible client configuration.
 *
 * The endpoint is resolved from CLAUDE_MEM_OPENROUTER_BASE_URL (settings or env;
 * env var OPENROUTER_BASE_URL also honored). When unset, requests go to the
 * default OpenRouter URL — behavior unchanged. When set to an OpenAI-compatible
 * base (DeepSeek, LM Studio, a custom gateway, etc.), the provider POSTs to
 * `<base>/chat/completions`. The model is taken verbatim from
 * CLAUDE_MEM_OPENROUTER_MODEL. See src/shared/openrouter-base-url.ts for the
 * resolution rules and per-provider config examples (#2382/#2590/#2622/#2393).
 */

/**
 * Gateway error taxonomy (cmem.ai inference gateway) → worker error kind.
 * The gateway classifies once at the source and sends
 * `{ error: { code, message, action, url, request_id } }`; the worker carries
 * that envelope verbatim and only maps `code` to a retry class.
 */
const GATEWAY_CODE_TO_KIND: Record<string, ProviderErrorClass> = {
  allowance_exhausted: 'quota_exhausted',
  key_invalid: 'auth_invalid',
  subscription_inactive: 'auth_invalid',
  rate_limited: 'rate_limit',
  upstream_unavailable: 'transient',
  bad_request: 'unrecoverable',
};

interface UpstreamErrorEnvelope {
  code?: unknown;
  message?: unknown;
  action?: unknown;
  url?: unknown;
  request_id?: unknown;
  metadata?: unknown;
}

/**
 * Whether a 403 is OpenRouter refusing a moderated model's flagged input
 * rather than the key: its envelope carries the flagged reasons or input in
 * `metadata`, or its message says the input was flagged.
 */
function isModerationRefusal(envelope: UpstreamErrorEnvelope | null, lowerBody: string): boolean {
  const metadata = envelope?.metadata;
  if (
    metadata !== null && typeof metadata === 'object'
    && ('flagged_input' in metadata || Array.isArray((metadata as { reasons?: unknown }).reasons))
  ) {
    return true;
  }
  return lowerBody.includes('requires moderation') || lowerBody.includes('input was flagged');
}

/** Best-effort parse of `{ error: {...} }` from an upstream body. */
function parseUpstreamErrorEnvelope(bodyText: string): UpstreamErrorEnvelope | null {
  if (!bodyText) return null;
  try {
    const parsed: unknown = JSON.parse(bodyText);
    if (parsed && typeof parsed === 'object' && 'error' in parsed) {
      const error = (parsed as { error?: unknown }).error;
      if (error && typeof error === 'object') {
        return error as UpstreamErrorEnvelope;
      }
    }
  } catch {
    // Not JSON — legacy/plain-text body.
  }
  return null;
}

/**
 * litellm's words when it could not parse the downstream model's response.
 * The model ran and was billed; only its output was lost.
 */
const UPSTREAM_OUTPUT_FAILURE_MARKERS = ['unable to get json', 'expecting value'];

/**
 * The status to classify by. Once OpenRouter has accepted a request the HTTP
 * status is already 200, so a later failure (a rate limit, an overloaded
 * upstream) arrives as an error envelope in the body whose numeric `error.code`
 * is the real status. A litellm output failure keeps its 200 whatever its code
 * (OpenRouter reports an invalid upstream response as a 502): promoting it to
 * a 5xx would resend it and pay twice.
 */
function effectiveStatus(status: number | undefined, envelope: UpstreamErrorEnvelope | null, lowerBody: string): number | undefined {
  const code = envelope?.code;
  if (UPSTREAM_OUTPUT_FAILURE_MARKERS.some(marker => lowerBody.includes(marker))) return status;
  if (status !== undefined && status >= 200 && status < 300 && typeof code === 'number' && code >= 400 && code < 600) {
    return code;
  }
  return status;
}

/**
 * OpenRouter's answers when the configured model id itself is gone: a retired
 * model (404 "This model has been deprecated. It is recommended to migrate to
 * …", #3659), an id that is not in the catalog (400 "… is not a valid model
 * ID"), or one with no serving endpoint left (404 "No endpoints found for
 * <id>."). Retrying never helps, and the generic "check the API key, spend
 * limit and base URL" remedy points at the wrong setting, so these get their
 * own code and remedy. Phrases only count on a 400/404 or an error envelope
 * inside a 200; any other 400/404 stays a plain bad request.
 */
const MODEL_UNAVAILABLE_MARKERS = [
  'model has been deprecated',
  'not a valid model id',
  'no endpoints found for',
];

const MODEL_UNAVAILABLE_ACTION =
  'Set CLAUDE_MEM_OPENROUTER_MODEL in ~/.claude-mem/settings.json to a model your endpoint still serves (on OpenRouter, one from the model list).';

const OPENROUTER_MODEL_LIST_URL = 'https://openrouter.ai/models';

/**
 * Machine-readable context-length refusals from OpenAI-compatible servers:
 * OpenAI's error code, and llama.cpp's error type and message. The prose forms
 * ("maximum context length", "prompt is too long", "reduce the length of the
 * messages") are the ones the observer-text classifier already recognizes.
 */
const CONTEXT_OVERFLOW_MARKERS = [
  'context_length_exceeded',
  'exceed_context_size_error',
  'exceeds the available context size',
];

export function isContextOverflowBody(body: string): boolean {
  const lower = body.toLowerCase();
  return CONTEXT_OVERFLOW_MARKERS.some(marker => lower.includes(marker)) || isContextOverflowObserverOutput(body);
}


/**
 * Classify an OpenRouter fetch failure into ClassifiedProviderError. Called
 * at the boundary right after `fetch()` returns or throws.
 */
export function classifyOpenRouterError(input: {
  status?: number;
  bodyText?: string;
  headers?: Headers | { get(name: string): string | null };
  cause: unknown;
  requestId?: string;
  /** The URL a request with no response was sent to, named in the network-error message. */
  requestUrl?: string;
}): ClassifiedProviderError {
  const body = input.bodyText ?? '';
  const lower = body.toLowerCase();
  const headers = input.headers;
  const retryAfterHeader = headers?.get('retry-after') ?? null;
  const retryAfterMs = parseRetryAfterMs(retryAfterHeader);
  const envelope = parseUpstreamErrorEnvelope(body);
  const status = effectiveStatus(input.status, envelope, lower);

  // Structured taxonomy envelope from the cmem.ai gateway: carry it verbatim.
  if (envelope && typeof envelope.code === 'string' && Object.prototype.hasOwnProperty.call(GATEWAY_CODE_TO_KIND, envelope.code)) {
    const code = envelope.code;
    const kind = GATEWAY_CODE_TO_KIND[code];
    const message = typeof envelope.message === 'string' && envelope.message
      ? envelope.message
      : `OpenRouter error ${code}${status !== undefined ? ` (status ${status})` : ''}`;
    const requestId = typeof envelope.request_id === 'string' && envelope.request_id
      ? envelope.request_id
      : input.requestId;
    // Preserve the gateway default only for an absent hint. An invalid hint
    // must use ordinary retry backoff rather than reintroducing a full minute.
    const gatewayRetryAfterMs = retryAfterHeader === null ? 60_000 : retryAfterMs;
    const ErrorClass = input.status === 402 && code === 'allowance_exhausted' && isCmemGatewayUrl(input.requestUrl)
      ? CmemAllowanceExhaustedError : ClassifiedProviderError;
    return new ErrorClass(message, {
      kind,
      cause: input.cause,
      code,
      ...(typeof envelope.action === 'string' && envelope.action ? { action: envelope.action } : {}),
      ...(typeof envelope.url === 'string' && envelope.url ? { url: envelope.url } : {}),
      ...(requestId ? { requestId } : {}),
      ...(kind === 'rate_limit' && gatewayRetryAfterMs !== undefined ? { retryAfterMs: gatewayRetryAfterMs } : {}),
    });
  }

  // Legacy classification: keep the upstream body in the message (it usually
  // contains the remedy, e.g. OpenRouter's "Key limit exceeded … Manage it
  // using https://openrouter.ai/…") and carry the request id.
  const upstreamMessage = envelope && typeof envelope.message === 'string' && envelope.message
    ? envelope.message
    : body.substring(0, 300);
  const detail = { ...(input.requestId ? { requestId: input.requestId } : {}) };
  const describe = (cls: string): string =>
    `OpenRouter ${cls}${status !== undefined ? ` (status ${status})` : ''}${upstreamMessage ? `: ${upstreamMessage}` : ''}`;

  // The request did not fit the model's context window, or the server refused
  // its size outright (413). Retiring the conversation fixes both, so neither
  // may finalize the session as a bad request (#3625). Checked before the quota
  // markers: "context limit exceeded" is not a spend limit.
  if (status === 413 || (status === 400 && isContextOverflowBody(body))) {
    return new ClassifiedProviderError(
      describe('context overflow'),
      { kind: 'context_overflow', cause: input.cause, ...detail },
    );
  }

  // Quota / insufficient credits — body marker takes precedence over status.
  if (
    lower.includes('quota exceeded') ||
    lower.includes('insufficient credits') ||
    lower.includes('insufficient_quota') ||
    lower.includes('key limit exceeded') ||
    // "Rate limit exceeded" on a 429 is a rate limit, not quota — the generic
    // marker only applies off the 429 path (the key-limit marker always wins).
    (lower.includes('limit exceeded') && status !== 429) ||
    // A daily cap is a spent allowance (shared with the server runtime).
    (status === 429 && namesPeriodRateLimit(lower)) ||
    lower.includes('negative credit') ||
    status === 402
  ) {
    return new ClassifiedProviderError(
      describe('quota exhausted'),
      { kind: 'quota_exhausted', cause: input.cause, ...detail },
    );
  }

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

  // OpenRouter's moderation refusal names the INPUT, not the key: "<model>
  // requires moderation on <provider>. Your input was flagged for …", with the
  // flagged reasons in `metadata`. The next observation is a different input,
  // so this is unrecoverable for this batch only — as auth_invalid it would
  // pause all memory behind a cooldown under "credentials refused".
  if (status === 403 && isModerationRefusal(envelope, lower)) {
    return new ClassifiedProviderError(
      describe('moderation refusal'),
      { kind: 'unrecoverable', cause: input.cause, ...detail },
    );
  }

  if (status === 401 || status === 403) {
    return new ClassifiedProviderError(
      describe('auth error'),
      { kind: 'auth_invalid', cause: input.cause, ...detail },
    );
  }

  if (
    (status === 400 || status === 404 || (status === 200 && envelope !== null))
    && MODEL_UNAVAILABLE_MARKERS.some(marker => lower.includes(marker))
  ) {
    return new ClassifiedProviderError(
      describe('model unavailable'),
      {
        kind: 'unrecoverable',
        cause: input.cause,
        code: 'model_unavailable',
        action: MODEL_UNAVAILABLE_ACTION,
        url: OPENROUTER_MODEL_LIST_URL,
        ...detail,
      },
    );
  }

  if (status === 400 || status === 404) {
    return new ClassifiedProviderError(
      describe('bad request'),
      { kind: 'unrecoverable', cause: input.cause, ...detail },
    );
  }

  if (status !== undefined && status >= 500 && status < 600) {
    return new ClassifiedProviderError(
      describe('upstream error'),
      { kind: 'transient', cause: input.cause, ...detail },
    );
  }

  // Network errors (no status) — treat as transient. The runtime's error code
  // and the host say what failed where (#4092).
  if (status === undefined) {
    const network = describeNetworkFailure(input.cause, input.requestUrl);
    return new ClassifiedProviderError(
      `OpenRouter network error: ${input.cause instanceof Error ? input.cause.message : String(input.cause)}${networkFailureSuffix(network)}`,
      {
        kind: 'transient',
        cause: input.cause,
        ...detail,
        // A refused connection never sent the request, so it is pre-send and
        // must not spend the paid-send budget (#4604).
        ...(isConnectionRefused(network) ? { paidSendOutcome: 'refused_before_work' as const } : {}),
        ...(network.localNetworkHint ? { action: network.localNetworkHint } : {}),
      },
    );
  }

  // litellm (behind OpenRouter) can fail to parse the downstream model's
  // response and surface it as a body-level error inside a 200 envelope, e.g.
  // `{ error: { code: 200, message: "Unable to get json response - Expecting
  // value: line 45 column 1" } }`. The model ran and the request was billed;
  // only its output was lost. Resending pays for the same work again, so it is
  // an output failure and never retried ("never pay twice"). Kept
  // marker-scoped so it carries its own words in the log.
  if (UPSTREAM_OUTPUT_FAILURE_MARKERS.some(marker => lower.includes(marker))) {
    return new ClassifiedProviderError(
      describe('upstream output failure'),
      { kind: 'unrecoverable', paidSendOutcome: 'output_failure', cause: input.cause, ...detail },
    );
  }

  return new ClassifiedProviderError(
    describe('API error'),
    { kind: 'unrecoverable', cause: input.cause, ...detail },
  );
}

const CHARS_PER_TOKEN_ESTIMATE = 4;

function openRouterRequestId(headers: Headers | undefined): string | undefined {
  return headers?.get('x-request-id') ?? headers?.get('x-openrouter-request-id') ?? undefined;
}

function openRouterReportedCost(usage: OpenRouterResponse['usage']): number | undefined {
  const orCost = typeof usage?.cost === 'number' ? usage.cost : undefined;
  const upstreamCost = typeof usage?.cost_details?.upstream_inference_cost === 'number'
    ? usage.cost_details.upstream_inference_cost
    : undefined;
  if (orCost === undefined && upstreamCost === undefined) return undefined;
  return (orCost ?? 0) + (upstreamCost ?? 0);
}

/** Last prompt for context size; both requests' completion tokens and cost were billed. */
function withCombinedOpenRouterUsage(first: OpenRouterResponse['usage'], retry: OpenRouterResponse): OpenRouterResponse {
  const combined = combineBilledChatUsage(
    {
      promptTokens: first?.prompt_tokens,
      completionTokens: first?.completion_tokens,
      totalTokens: first?.total_tokens,
      costUsd: openRouterReportedCost(first),
    },
    {
      promptTokens: retry.usage?.prompt_tokens,
      completionTokens: retry.usage?.completion_tokens,
      totalTokens: retry.usage?.total_tokens,
      costUsd: openRouterReportedCost(retry.usage),
    },
  );
  const usage: NonNullable<OpenRouterResponse['usage']> = { ...retry.usage };
  if (combined.promptTokens !== undefined) usage.prompt_tokens = combined.promptTokens;
  if (combined.completionTokens !== undefined) usage.completion_tokens = combined.completionTokens;
  if (combined.totalTokens !== undefined) usage.total_tokens = combined.totalTokens;
  if (combined.costUsd !== undefined) {
    usage.cost = combined.costUsd;
    if (usage.cost_details) usage.cost_details = { ...usage.cost_details, upstream_inference_cost: undefined };
  }
  return { ...retry, usage };
}

interface OpenRouterResponse {
  /** The model that actually served the request — not the configured string. */
  model?: string;
  choices?: Array<{
    message?: {
      role?: string;
      content?: string | Array<{ type: string; text?: string }> | null;
      reasoning_content?: string;
      reasoning?: string | null;
      tool_calls?: unknown[];
    };
    finish_reason?: string;
  }>;
  usage?: {
    prompt_tokens?: number;
    completion_tokens?: number;
    total_tokens?: number;
    /** Credits charged by openrouter.ai (~USD). With BYOK this is only the fee. */
    cost?: number;
    cost_details?: {
      /** What the upstream provider charged when using BYOK. */
      upstream_inference_cost?: number;
    };
  };
  error?: {
    message?: string;
    code?: string;
  };
}

export interface OpenRouterConfig {
  apiKey: string;
  /**
   * The rotation pool: `apiKey` followed by CLAUDE_MEM_OPENROUTER_API_KEYS.
   *
   * Always exactly `[apiKey]` when the endpoint is the cmem.ai gateway. The
   * gateway key is account-delivered, so there is no second one to rotate to,
   * and the list is by definition the user's PERSONAL keys — sending those to
   * the gateway is the exact leak `resolveOpenRouterConfig` already refuses to
   * commit when a key-only override meets a persisted cmem base URL.
   */
  apiKeys: string[];
  /** First entry of the configured list; the one named in logs and sessions. */
  model: string;
  /**
   * The rest of the configured list, in priority order, sent as OpenRouter's
   * native `models` fallback array. Empty for the ordinary single-model
   * configuration, which is every install that has not opted in.
   */
  fallbackModels: string[];
  apiUrl: string;
  siteUrl?: string;
  appName?: string;
  /** Per-call output mode for the wrap-up; never a persisted setting. */
  plainText?: boolean;
  /**
   * CLAUDE_MEM_OPENROUTER_EXTRA_BODY, parsed (src/shared/openrouter-extra-body.ts),
   * with a valid CLAUDE_MEM_OPENROUTER_TEMPERATURE merged over it.
   * Never set for the cmem gateway.
   */
  extraBody?: Record<string, unknown>;
  /** CLAUDE_MEM_OPENROUTER_REASONING_EFFORT; sent to openrouter.ai only. */
  reasoningEffort?: OpenRouterReasoningEffort;
}

/**
 * CLAUDE_MEM_OPENROUTER_REASONING_EFFORT values (OpenRouter's documented
 * effort scale, the token-saving end of it). Unset leaves the body on its
 * default, which disables reasoning wherever the request reaches OpenRouter.
 */
export const OPENROUTER_REASONING_EFFORTS = ['none', 'minimal', 'low', 'medium', 'high'] as const;
export type OpenRouterReasoningEffort = typeof OPENROUTER_REASONING_EFFORTS[number];

/** The setting as an effort, or undefined when unset or not one of the values. */
export function parseOpenRouterReasoningEffort(raw: unknown): OpenRouterReasoningEffort | undefined {
  const value = typeof raw === 'string' ? raw.trim().toLowerCase() : '';
  return (OPENROUTER_REASONING_EFFORTS as readonly string[]).includes(value)
    ? value as OpenRouterReasoningEffort
    : undefined;
}

/**
 * OpenRouter's `reasoning` field for an effort. `none` is sent as
 * `{ enabled: false }`, the shape the wrap-up already uses. Every other effort
 * is sent as its own token budget (`max_tokens`, which OpenRouter accepts
 * instead of `effort`, never with it), so reasoning has a cap of its own.
 */
function reasoningControl(effort: OpenRouterReasoningEffort): Record<string, unknown> {
  return effort === 'none' ? { enabled: false } : { max_tokens: OBSERVER_REASONING_BUDGET_TOKENS_BY_EFFORT[effort] };
}

function hasProcessEnvOverride(key: string): boolean {
  return Object.prototype.hasOwnProperty.call(process.env, key);
}

/**
 * Split CLAUDE_MEM_OPENROUTER_MODEL into a primary model and its fallbacks.
 *
 * The setting has always accepted an array, and the array has always been
 * comma-joined into a single `model` string that OpenRouter rejects outright —
 * #3829 item 3. No model id contains a comma, so the joined form is never
 * anything a user wanted; a comma- or whitespace-separated STRING is the same
 * mistake typed a different way, and is split here too.
 *
 * The first entry becomes `model`, which keeps every single-model install
 * byte-identical, and the rest become OpenRouter's native `models` fallback
 * array. Blanks and repeats are dropped: a repeat would spend a fallback slot
 * re-trying the model that just failed.
 */
export function normalizeOpenRouterModel(rawModel: unknown): { model: string; fallbackModels: string[] } {
  const parts = (Array.isArray(rawModel) ? rawModel : [rawModel])
    // Strings only: a non-string scalar resolved to the default before this
    // change, and no model id is a bare number.
    .filter((entry): entry is string => typeof entry === 'string')
    .flatMap(entry => entry.split(/[\s,]+/))
    .map(entry => entry.trim())
    .filter(entry => entry.length > 0);

  const unique = [...new Set(parts)];
  if (unique.length === 0) {
    return {
      model: SettingsDefaultsManager.getAllDefaults().CLAUDE_MEM_OPENROUTER_MODEL,
      fallbackModels: [],
    };
  }
  return { model: unique[0], fallbackModels: unique.slice(1) };
}

declare const __DEFAULT_PACKAGE_VERSION__: string;
const CLAUDE_MEM_VERSION = typeof __DEFAULT_PACKAGE_VERSION__ !== 'undefined' ? __DEFAULT_PACKAGE_VERSION__ : '0.0.0-dev';

/**
 * `session_id` and `trace` for a request that reaches OpenRouter, shaped for
 * OpenRouter Broadcast to PostHog: `session_id` → $ai_session_id,
 * `trace_id` → $ai_trace_id, `generation_name` → $ai_span_name, any other
 * trace key → metadata_<key>. The session id is also OpenRouter's
 * sticky-routing key, so a session stays on the provider that holds its prompt
 * cache. Hashed and random ids and fixed names only: never a path, a project
 * name or anything the user wrote. `user` is left to the cmem gateway, which
 * sets the account server-side.
 */
function openRouterRequestLabels(label: ObserverRequestLabel): Record<string, unknown> {
  return {
    session_id: label.sessionId,
    trace: {
      ...(label.generationId ? { trace_id: label.generationId } : {}),
      trace_name: 'claude-mem observer',
      generation_name: label.kind,
      claude_mem_version: CLAUDE_MEM_VERSION,
    },
  };
}

/**
 * The reasoning budget this request sends as `reasoning.max_tokens`, which is
 * also added to the answer's cap in the request's `max_tokens` (reasoning
 * counts against it): the typed effort's entry in
 * OBSERVER_REASONING_BUDGET_TOKENS_BY_EFFORT for an effort other than `none`
 * sent to openrouter.ai, else 0 (every other request sends reasoning off, or
 * no reasoning field at all). Shared by the body, the #4003 resend and the
 * cut-off warning so all three carry the same cap.
 */
export function openRouterReasoningBudgetTokens(input: {
  apiUrl: string;
  plainText?: boolean;
  reasoningEffort?: OpenRouterReasoningEffort;
  label?: ObserverRequestLabel;
  forceReasoningOff?: boolean;
  /** The #5265 resend leaves reasoning out, so it adds no reasoning budget. */
  omitReasoning?: boolean;
}): number {
  if (input.omitReasoning === true) return 0;
  const answerOnly = (input.plainText || input.label?.kind === 'field_compression') && input.forceReasoningOff !== true;
  const typedReasoning = isOpenRouterApiUrl(input.apiUrl) && !answerOnly && input.forceReasoningOff !== true
    && input.reasoningEffort !== undefined;
  return typedReasoning && input.reasoningEffort && input.reasoningEffort !== 'none'
    ? OBSERVER_REASONING_BUDGET_TOKENS_BY_EFFORT[input.reasoningEffort]
    : 0;
}

/**
 * Build the chat-completions request body.
 *
 * Exported so the body shape is testable without a network round trip, which
 * matters here: in OpenRouter's documented fallback shape `models` REPLACES
 * `model` rather than accompanying it, and that is not a thing to get wrong
 * silently.
 *
 * `models` is only sent to openrouter.ai. A custom gateway reached through
 * CLAUDE_MEM_OPENROUTER_BASE_URL speaks plain OpenAI, where an unknown body
 * field is a 400 — the same reason `usage` is already gated. Such a gateway
 * gets the first model, still strictly better than today's rejected
 * comma-joined string.
 */
export function buildOpenRouterRequestBody(input: {
  model: string;
  fallbackModels: string[];
  messages: OpenRouterRequestMessage[];
  apiUrl: string;
  plainText?: boolean;
  /** CLAUDE_MEM_OBSERVER_MAX_OUTPUT_TOKENS; the #4003 retry resends it as max_completion_tokens. */
  maxOutputTokens?: number;
  /** CLAUDE_MEM_OPENROUTER_EXTRA_BODY; merged last, but never to the cmem gateway. */
  extraBody?: Record<string, unknown>;
  /** CLAUDE_MEM_OPENROUTER_REASONING_EFFORT; openrouter.ai only. */
  reasoningEffort?: OpenRouterReasoningEffort;
  /** What the request is; sent as `session_id` and `trace` where the body reaches OpenRouter. */
  label?: ObserverRequestLabel;
  /**
   * One-shot retry after an empty finish_reason=length reply. Forces
   * reasoning off on every endpoint, including a custom gateway, and the
   * extra body cannot put it back.
   */
  forceReasoningOff?: boolean;
  /**
   * One-shot resend after OpenRouter rejects `reasoning: {enabled: false}`
   * because reasoning is mandatory for that endpoint (#5265). The field is
   * left out entirely, including a reasoning key in the extra body.
   */
  omitReasoning?: boolean;
}): Record<string, unknown> {
  const isOpenRouter = isOpenRouterApiUrl(input.apiUrl);
  // openrouter.ai itself, or the cmem gateway, which forwards the body there.
  const reachesOpenRouter = isOpenRouter || isCmemGatewayUrl(input.apiUrl);
  const useFallbacks = isOpenRouter && input.fallbackModels.length > 0;
  const omitReasoning = input.omitReasoning === true;
  const force = input.forceReasoningOff === true;
  // A field condensation is a short rewrite like a wrap-up: a reasoning model
  // otherwise spends the whole output cap thinking and the pass is discarded
  // as cut off (#2995). A forced retry is an observation turn, not a wrap-up.
  const answerOnly = (input.plainText || input.label?.kind === 'field_compression') && !force;
  const typedReasoning = isOpenRouter && !answerOnly && !force && !omitReasoning && input.reasoningEffort !== undefined;
  // Default for anything that reaches OpenRouter: reasoning off, so a
  // reasoning-by-default model cannot spend max_tokens thinking and return
  // empty content (#5029). A typed effort still opts back in, on openrouter.ai
  // only. A custom gateway gets no reasoning field until a length-truncated
  // empty reply retries once with it forced off — unknown fields 400 on
  // strict servers. The #5265 resend leaves the field out: an endpoint where
  // reasoning is mandatory rejects the disable with a 400, and that 400 is
  // otherwise unrecoverable.
  const defaultReasoningOff = !omitReasoning && (force || (reachesOpenRouter && !answerOnly && !typedReasoning));
  return withOpenRouterExtraBody({
    ...(useFallbacks
      ? { models: [input.model, ...input.fallbackModels] }
      : { model: input.model }),
    messages: input.messages,
    temperature: 0.3,  // Lower temperature for structured extraction
    // The answer's budget plus reasoning's own budget, which `reasoning`
    // below caps, when this request turns reasoning on: reasoning counts
    // against max_tokens, so the answer keeps its whole budget.
    max_tokens: (input.maxOutputTokens ?? DEFAULT_OBSERVER_MAX_OUTPUT_TOKENS) + openRouterReasoningBudgetTokens(input),
    // Streamed, so liveness (tokens, `:` pings) rather than a guessed deadline
    // decides when a request is dead; the reply is assembled back into one
    // chat.completion (streamed-chat-completion.ts), usage from the final
    // chunk. The cmem gateway answers with one JSON body whatever is asked,
    // and its requests stay exactly as they are.
    ...(streamsChatCompletion(input.apiUrl) ? STREAMED_REQUEST_FIELDS : {}),
    // Keep the same model, but ask for an answer instead of spending this
    // short rewrite's budget on reasoning. Only known OpenRouter endpoints
    // accept the vendor-specific reasoning control (cmem forwards it).
    ...(answerOnly && reachesOpenRouter ? {
      response_format: { type: 'text' },
      ...(omitReasoning ? {} : { reasoning: { enabled: false } }),
    } : {}),
    ...(defaultReasoningOff ? { reasoning: { enabled: false } } : {}),
    // The reasoning-effort setting, for openrouter.ai only: a custom gateway's
    // strict schema rejects the field, and the cmem gateway gets the default
    // (reasoning off) rather than the user's effort. A wrap-up keeps its own
    // control above.
    ...(typedReasoning && input.reasoningEffort
      ? { reasoning: reasoningControl(input.reasoningEffort) }
      : {}),
    // Ask openrouter.ai for usage accounting (token counts + cost).
    // Only sent to openrouter.ai — strict custom gateways may reject
    // unknown body fields.
    ...(isOpenRouter ? { usage: { include: true } } : {}),
    // Sticky routing and the Broadcast trace, wherever the body reaches
    // OpenRouter. A custom gateway gets neither: strict ones 400 on unknown
    // body fields.
    ...(input.label && reachesOpenRouter ? openRouterRequestLabels(input.label) : {}),
  }, typedReasoning || force || omitReasoning ? withoutReasoning(input.extraBody) : input.extraBody, input.apiUrl,
  // A wrap-up, a field condensation that reaches OpenRouter, and a forced
  // retry own the reasoning field. A custom gateway's extra body keeps its
  // own control until that retry.
  Boolean(input.plainText) || force || (answerOnly && reachesOpenRouter));
}

/**
 * The extra body without its `reasoning` field: the typed
 * CLAUDE_MEM_OPENROUTER_REASONING_EFFORT setting decides reasoning when set.
 */
function withoutReasoning(extraBody: Record<string, unknown> | undefined): Record<string, unknown> | undefined {
  if (!extraBody || !('reasoning' in extraBody)) return extraBody;
  return Object.fromEntries(Object.entries(extraBody).filter(([key]) => key !== 'reasoning'));
}

/** The CLAUDE_MEM_OPENROUTER_EXTRA_BODY value a warning was last logged for: once per value, not per status poll. */
let lastWarnedExtraBody: string | null = null;

/** The usable extra body for a non-gateway endpoint, warning once about an unusable one. */
function resolveExtraBody(raw: unknown): Record<string, unknown> | undefined {
  const { extraBody, warning } = parseOpenRouterExtraBody(raw);
  const rawText = typeof raw === 'string' ? raw : JSON.stringify(raw ?? '');
  if (warning && lastWarnedExtraBody !== rawText) {
    lastWarnedExtraBody = rawText;
    logger.warn('SDK', warning);
  }
  return extraBody;
}

/** Endpoint a mismatched key was last withheld from, so dispatch logs it once, not per call. */
let lastWithheldCmemKeyUrl: string | null = null;

/**
 * Resolve key/base/model as a source-coherent tuple. In particular, a
 * key-only environment override must never inherit a persisted cmem.ai base
 * URL and send a personal OpenRouter credential to the cmem gateway, and a key
 * is never returned with a URL it does not belong to (a cmem memory key only
 * with the gateway, any other key only elsewhere). To
 * replace a stored cmem tuple at runtime, explicitly override the base URL too
 * (an empty CLAUDE_MEM_OPENROUTER_BASE_URL selects normal OpenRouter).
 */
export function resolveOpenRouterConfig(
  settingsPath: string = USER_SETTINGS_PATH,
): OpenRouterConfig {
  const persisted = SettingsDefaultsManager.loadFromFile(settingsPath, false);
  const settings = SettingsDefaultsManager.loadFromFile(settingsPath);
  const persistedBaseUrl = typeof persisted.CLAUDE_MEM_OPENROUTER_BASE_URL === 'string'
    ? persisted.CLAUDE_MEM_OPENROUTER_BASE_URL.trim()
    : '';
  const hasBaseOverride = hasProcessEnvOverride('CLAUDE_MEM_OPENROUTER_BASE_URL');
  const lockPersistedCmemTuple = isCmemGatewayUrl(persistedBaseUrl) && !hasBaseOverride;

  const configuredBaseUrl = typeof settings.CLAUDE_MEM_OPENROUTER_BASE_URL === 'string'
    ? settings.CLAUDE_MEM_OPENROUTER_BASE_URL.trim()
    : '';
  const baseUrl = lockPersistedCmemTuple
    ? persistedBaseUrl
    : configuredBaseUrl || process.env.OPENROUTER_BASE_URL?.trim() || '';

  const detachPersistedCmemTuple = isCmemGatewayUrl(persistedBaseUrl)
    && hasBaseOverride
    && !isCmemGatewayUrl(baseUrl);

  const persistedKey = typeof persisted.CLAUDE_MEM_OPENROUTER_API_KEY === 'string'
    ? persisted.CLAUDE_MEM_OPENROUTER_API_KEY.trim()
    : '';
  const configuredKey = typeof settings.CLAUDE_MEM_OPENROUTER_API_KEY === 'string'
    ? settings.CLAUDE_MEM_OPENROUTER_API_KEY.trim()
    : '';
  const explicitKey = hasProcessEnvOverride('CLAUDE_MEM_OPENROUTER_API_KEY')
    ? process.env.CLAUDE_MEM_OPENROUTER_API_KEY?.trim() ?? ''
    : '';
  const apiKey = lockPersistedCmemTuple
    ? persistedKey
    : detachPersistedCmemTuple
      // A base-only override must not carry the account-owned cmem key to a
      // different host. Accept only a key supplied as part of this runtime
      // tuple or the user's personal key from ~/.claude-mem/.env.
      ? explicitKey || getCredential('OPENROUTER_API_KEY') || ''
      : configuredKey || getCredential('OPENROUTER_API_KEY') || '';

  let rawModel: unknown = lockPersistedCmemTuple
    ? persisted.CLAUDE_MEM_OPENROUTER_MODEL
    : settings.CLAUDE_MEM_OPENROUTER_MODEL;
  if (
    isCmemGatewayUrl(persistedBaseUrl)
    && hasBaseOverride
    && !isCmemGatewayUrl(baseUrl)
    && !hasProcessEnvOverride('CLAUDE_MEM_OPENROUTER_MODEL')
  ) {
    // A base override that moves away from cmem must not retain the gateway's
    // cmem-observer model. Restore the ordinary OpenRouter default unless the
    // operator supplied a model override as part of the new tuple.
    rawModel = SettingsDefaultsManager.getAllDefaults().CLAUDE_MEM_OPENROUTER_MODEL;
  }
  const { model, fallbackModels } = normalizeOpenRouterModel(rawModel);

  const apiUrl = resolveOpenRouterChatCompletionsUrl(baseUrl);
  const siteUrl = settings.CLAUDE_MEM_OPENROUTER_SITE_URL || '';
  const appName = settings.CLAUDE_MEM_OPENROUTER_APP_NAME || OPENROUTER_APP_TITLE;

  // The cmem gateway and its keys go together, both ways: the account-owned
  // cm_pro_ key authenticates only against the gateway, and the gateway only
  // takes a cm_pro_ key, so a personal key must never be sent there. The tuple
  // lock above covers environment overrides, but a base URL changed in
  // settings.json itself (the settings API / viewer, a hand edit) can pair
  // either key with the wrong host. Every request resolves its key and URL
  // here, together, so the pair is checked here — and fails closed.
  if (apiKey && !isKeyAllowedForEndpoint(apiUrl, apiKey)) {
    if (lastWithheldCmemKeyUrl !== apiUrl) {
      lastWithheldCmemKeyUrl = apiUrl;
      logger.warn('SDK', 'Withholding the OpenRouter key: a cmem.ai memory key only goes to the cmem gateway, and the gateway only takes a cmem.ai memory key. Pair CLAUDE_MEM_OPENROUTER_BASE_URL with a key for that endpoint.');
    }
    return { apiKey: '', apiKeys: [], model, fallbackModels, apiUrl, siteUrl, appName };
  }

  // The gateway never pools: its key is account-delivered, so there is no
  // second one to rotate to, and the rotation list holds the user's PERSONAL
  // keys, which must never reach the gateway.
  if (isCmemGatewayUrl(apiUrl)) {
    return { apiKey, apiKeys: keysForEndpoint(apiUrl, apiKey ? [apiKey] : []), model, fallbackModels, apiUrl, siteUrl, appName };
  }

  // Off the gateway the list joins the primary, through the same lock as every
  // pool: a cm_pro_ key pasted into the list never leaves for this host.
  const apiKeys = keysForEndpoint(apiUrl, buildKeyPool(
    apiKey,
    hasProcessEnvOverride('CLAUDE_MEM_OPENROUTER_API_KEYS')
      ? process.env.CLAUDE_MEM_OPENROUTER_API_KEYS?.trim() ?? ''
      : settings.CLAUDE_MEM_OPENROUTER_API_KEYS || getCredential('OPENROUTER_API_KEYS') || '',
  ));

  // Off the gateway only: the gateway sets its own request policy on traffic
  // it pays for (the request body itself drops it there too).
  let extraBody = resolveExtraBody(settings.CLAUDE_MEM_OPENROUTER_EXTRA_BODY);
  const rawTemperature: unknown = settings.CLAUDE_MEM_OPENROUTER_TEMPERATURE;
  const temperature = typeof rawTemperature === 'number' ? rawTemperature
    : typeof rawTemperature === 'string' && rawTemperature.trim() !== '' ? Number(rawTemperature)
      : NaN;
  if (Number.isFinite(temperature) && temperature >= 0 && temperature <= 2) {
    extraBody = { ...extraBody, temperature };
  }
  const reasoningEffort = resolveReasoningEffort(settings.CLAUDE_MEM_OPENROUTER_REASONING_EFFORT);
  if (reasoningEffort && extraBody && 'reasoning' in extraBody && !warnedReasoningOverlap) {
    warnedReasoningOverlap = true;
    logger.warn('SDK', 'CLAUDE_MEM_OPENROUTER_REASONING_EFFORT is set, so the reasoning field in CLAUDE_MEM_OPENROUTER_EXTRA_BODY is ignored');
  }

  return {
    apiKey: apiKey || apiKeys[0] || '',
    apiKeys,
    model,
    fallbackModels,
    apiUrl,
    siteUrl,
    appName,
    ...(extraBody ? { extraBody } : {}),
    ...(reasoningEffort ? { reasoningEffort } : {}),
  };
}

/** The reasoning-effort value a warning was last logged for: once per value, not per status poll. */
let lastWarnedReasoningEffort: string | null = null;

/** Whether the effort-overrides-extra-body warning was logged (once per process). */
let warnedReasoningOverlap = false;

/** The configured effort, warning once about a value that is not one. Never throws. */
function resolveReasoningEffort(raw: unknown): OpenRouterReasoningEffort | undefined {
  const effort = parseOpenRouterReasoningEffort(raw);
  const text = typeof raw === 'string' ? raw.trim() : '';
  if (!effort && text && lastWarnedReasoningEffort !== text) {
    lastWarnedReasoningEffort = text;
    logger.warn('SDK', `Ignoring CLAUDE_MEM_OPENROUTER_REASONING_EFFORT "${text}": use one of ${OPENROUTER_REASONING_EFFORTS.join(', ')}, or leave it empty`);
  }
  return effort;
}

export class OpenRouterProvider extends OpenAICompatibleProvider<OpenRouterConfig> {
  protected readonly providerName = 'OpenRouter';
  protected readonly syntheticIdPrefix = 'openrouter';
  protected readonly forwardEmptyMessageResponse = true;

  constructor(dbManager: DatabaseManager, sessionManager: SessionManager) {
    super(dbManager, sessionManager);
  }

  protected getConfig(): OpenRouterConfig {
    return resolveOpenRouterConfig();
  }

  protected missingApiKeyError(): Error {
    return new Error('OpenRouter API key not configured. Set CLAUDE_MEM_OPENROUTER_API_KEY in settings or OPENROUTER_API_KEY environment variable.');
  }

  protected prepareSessionExtras(session: ActiveSession, config: OpenRouterConfig): void {
    // openrouter.ai responses carry real usage/cost; custom OpenAI-compatible
    // gateways often fabricate or omit usage — let telemetry segment the two.
    session.endpointClass = isOpenRouterApiUrl(config.apiUrl) ? 'openrouter' : 'custom';
  }

  /**
   * Image side refs for the current observation turn, when image inference
   * is enabled and this endpoint qualifies (media-capability.ts). The
   * derivatives come from the Phase 2 MediaStore; nothing else is read.
   */
  protected async prepareObservationMedia(
    _session: ActiveSession,
    messages: PendingMessageWithId[],
    config: OpenRouterConfig,
  ): Promise<PreparedTurnMedia | null> {
    const capability = await resolveObserverImageCapability(config);
    if (!capability.supported) {
      logger.debug('SDK', 'Observation images deferred; the turn is sent text-only', { reason: capability.reason });
      return null;
    }
    const store = this.dbManager.getMediaStore();
    return prepareTurnImages(messages, async attachmentId => {
      const metadata = store.getMetadata(attachmentId).llm;
      if (!metadata) throw new MediaError('media_not_ready');
      // readVariant verifies the bytes against this immutable stored variant.
      return { bytes: await store.readVariant(attachmentId, 'llm'), width: metadata.width, height: metadata.height };
    }, capability.bounds);
  }

  protected resolveContextWindow(config: OpenRouterConfig): Promise<number> {
    return resolveContextWindowTokens('openrouter', config.model, config.apiUrl);
  }

  protected estimateTokens(text: string): number {
    return Math.ceil(text.length / CHARS_PER_TOKEN_ESTIMATE);
  }

  /**
   * Real usage only, both sides or nothing: a gateway that reports just one of
   * prompt/completion tokens must not produce a half-real event (a lone
   * completion count used to surface as tokens_input=0 → compression_ratio 0.0).
   */
  protected buildLastUsage(result: ProviderQueryResult): ActiveSession['lastUsage'] {
    if (typeof result.inputTokens !== 'number' || typeof result.outputTokens !== 'number') {
      return null;
    }
    return {
      input: result.inputTokens,
      output: result.outputTokens,
      ...(typeof result.costUsd === 'number' ? { costUsd: result.costUsd } : {}),
    };
  }

  protected async query(
    history: ConversationMessage[],
    config: OpenRouterConfig,
    signal?: AbortSignal,
    perAttemptTimeoutMs?: number,
    paidSendBudget?: PaidSendBudget,
    label?: ObserverRequestLabel,
    turnImages?: TurnImageRequest,
  ): Promise<ProviderQueryResult> {
    // Rotation wraps withRetry rather than living inside it: the inner retry
    // still owns transient failures against one key, and this outer sweep moves
    // on only for the kinds that mean the key itself is spent. A pool of one —
    // every install that has not opted in, and every cmem-gateway install — is
    // a pass-through.
    return withKeyPool(
      { poolId: 'openrouter', keys: resolvePoolKeys(config), label: 'OpenRouter', rateLimitUntilNextKey },
      ({ key, poolSize }) => this.queryOpenRouterMultiTurn(
        history, key, poolSize, config.model, config.fallbackModels, config.apiUrl, config.siteUrl, config.appName,
        signal, config.plainText, perAttemptTimeoutMs, config.extraBody, config.reasoningEffort, paidSendBudget, label,
        turnImages,
      ),
    );
  }

  /**
   * Overrides the streamed request's idle window when set — a test hook, the
   * only reason this is a field. Unset, every request resolves
   * CLAUDE_MEM_LLM_STREAM_IDLE_TIMEOUT_MS (#4737), so a settings change takes
   * effect without a restart.
   */
  protected streamIdleTimeoutMs: number | undefined;

  /** POST the chat-completions request and read its (streamed) reply. */
  private async requestChatCompletion(
    apiUrl: string,
    apiKey: string,
    model: string,
    fallbackModels: string[],
    messages: OpenRouterRequestMessage[],
    siteUrl: string | undefined,
    appName: string | undefined,
    clientAttemptId: string,
    attemptSignal: AbortSignal,
    maxOutputTokens: number,
    liveness: StreamLiveness | null,
    plainText?: boolean,
    extraBody?: Record<string, unknown>,
    reasoningEffort?: OpenRouterReasoningEffort,
    label?: ObserverRequestLabel,
    forceReasoningOff: boolean = false,
    carriesImages: boolean = false,
    cmemCorrelationHeaderValue?: string,
  ): Promise<ChatCompletionExchange> {
    const send = (omitReasoning: boolean) => {
      const request = {
        model, fallbackModels, messages, apiUrl, plainText, maxOutputTokens, extraBody, reasoningEffort, label, forceReasoningOff,
        ...(omitReasoning ? { omitReasoning: true } : {}),
      };
      return sendChatCompletion({
        url: apiUrl,
        headers: {
          'Authorization': `Bearer ${apiKey}`,
          ...openRouterAttributionHeaders(siteUrl, appName),
          'Content-Type': 'application/json',
          // Tracing only: names every send of one batch in our logs and the
          // provider's. Never treated as server-side idempotency.
          'x-client-request-id': clientAttemptId,
          // ID-only correlation, cmem gateway only (cmem-request-correlation.ts).
          ...(cmemCorrelationHeaderValue ? { [CMEM_CORRELATION_HEADER]: cmemCorrelationHeaderValue } : {}),
        },
        body: buildOpenRouterRequestBody(request),
        // The #4003 resend carries the body's whole cap: answer plus reasoning.
        maxOutputTokens: maxOutputTokens + openRouterReasoningBudgetTokens(request),
        signal: attemptSignal,
        liveness,
        label: 'OpenRouter',
        // max_completion_tokens is never sent with images: an endpoint that
        // requires it rejects the image request, which goes out again text-only.
        allowMaxCompletionTokensRetry: !carriesImages,
        classify: (input) => {
          if (carriesImages && input.status !== undefined && input.bodyText !== undefined) {
            if (input.status === 400 && input.bodyText.includes(MEDIA_REQUEST_INVALID_MARKER)) {
              return new MediaRequestRejectedError(input.bodyText);
            }
            if (isMaxCompletionTokensCompatibilityError(input.status, input.bodyText)) {
              return new MediaRequestRejectedError('media_request_invalid:max_completion_tokens_required');
            }
          }
          const requestId = openRouterRequestId(input.headers);
          return classifyOpenRouterError({ ...input, requestUrl: apiUrl, ...(requestId ? { requestId } : {}) });
        },
      });
    };

    // The length-truncated retry is already the send that forces reasoning
    // off. A mandatory-reasoning 400 there is the caller's give-up, not a
    // second copy of the request that just burned the budget.
    if (forceReasoningOff) return send(false);

    try {
      return await send(false);
    } catch (error) {
      // #5029 disables reasoning by default so a reasoning model cannot spend
      // the answer budget thinking. An endpoint where reasoning is mandatory
      // rejects that body with a 400, which is unrecoverable and drops the
      // batch (#5265). Resend once without the field. Not remembered against
      // the URL: a router serves a different model on the next request, and
      // the ones that accept the disable should keep getting it. A refusal that
      // arrives after the reply started is an output failure: that send was
      // billed, so it is never resent.
      const text = error instanceof Error ? error.message : String(error);
      if (!isClassified(error) || error.kind !== 'unrecoverable' || error.paidSendOutcome === 'output_failure' || !isReasoningDisabledRejection(text)) {
        throw error;
      }
      const sent = buildOpenRouterRequestBody({
        model, fallbackModels, messages, apiUrl, plainText, maxOutputTokens, extraBody, reasoningEffort, label, forceReasoningOff,
      });
      if (!requestDisablesReasoning(sent)) throw error;
      logger.warn('SDK', 'OpenRouter refused to disable reasoning; resending once without the reasoning field', { url: apiUrl });
      return send(true);
    }
  }

  private async queryOpenRouterMultiTurn(
    history: ConversationMessage[],
    apiKey: string,
    /** Size of the rotation pool this attempt belongs to; 1 means no rotation. */
    poolSize: number,
    model: string,
    fallbackModels: string[],
    apiUrl: string,
    siteUrl?: string,
    appName?: string,
    signal?: AbortSignal,
    plainText?: boolean,
    perAttemptTimeoutMs?: number,
    extraBody?: Record<string, unknown>,
    reasoningEffort?: OpenRouterReasoningEffort,
    paidSendBudget?: PaidSendBudget,
    label?: ObserverRequestLabel,
    turnImages?: TurnImageRequest,
  ): Promise<ProviderQueryResult> {
    const messages = this.conversationToOpenAIMessages(history);
    if (turnImages?.images.length) {
      const maxOutputTokens = resolveObserverMaxOutputTokens();
      const fitted = fitTurnImagesToBody(messages, turnImages, body => buildOpenRouterRequestBody({
        model, fallbackModels, messages: body, apiUrl, plainText, maxOutputTokens, extraBody, reasoningEffort, label,
      }));
      if (fitted) {
        try {
          const result = await this.queryOpenRouterRequest(
            history, messages, fitted.messages, apiKey, poolSize, model, fallbackModels, apiUrl, siteUrl, appName,
            signal, plainText, perAttemptTimeoutMs, extraBody, reasoningEffort, paidSendBudget, label, fitted.images.length,
            fitted.images.map(image => image.eventKey),
          );
          return { ...result, deliveredImageLabels: fitted.images.map(image => image.requestLabel) };
        } catch (error) {
          if (!(error instanceof MediaRequestRejectedError)) throw error;
          // Rejected before any upstream inference (gateway validator), or the
          // endpoint needs max_completion_tokens, which is never sent with
          // images. Resend this turn once, text-only; its images stay
          // uninspected and the resend is not a vision call.
          logger.warn('SDK', 'Image request rejected; resending the turn text-only', { code: error.reason });
        }
      }
    }
    const result = await this.queryOpenRouterRequest(
      history, messages, messages, apiKey, poolSize, model, fallbackModels, apiUrl, siteUrl, appName,
      signal, plainText, perAttemptTimeoutMs, extraBody, reasoningEffort, paidSendBudget, label, 0,
      turnImages?.images.map(image => image.eventKey) ?? [],
    );
    return turnImages?.images.length ? { ...result, deliveredImageLabels: [] } : result;
  }

  /** One observer request: `requestMessages` is `messages` with this turn's images, if any. */
  private async queryOpenRouterRequest(
    history: ConversationMessage[],
    messages: OpenAIMessage[],
    requestMessages: OpenRouterRequestMessage[],
    apiKey: string,
    poolSize: number,
    model: string,
    fallbackModels: string[],
    apiUrl: string,
    siteUrl?: string,
    appName?: string,
    signal?: AbortSignal,
    plainText?: boolean,
    perAttemptTimeoutMs?: number,
    extraBody?: Record<string, unknown>,
    reasoningEffort?: OpenRouterReasoningEffort,
    paidSendBudget?: PaidSendBudget,
    label?: ObserverRequestLabel,
    imageCount = 0,
    /** Media source events this request carries (or, text-only, came from); IDs only. */
    correlationEventKeys: readonly string[] = [],
  ): Promise<ProviderQueryResult> {
    // The gateway emits pro_inference_cap_exhausted on every spent request.
    // After the first refusal, further sends wait until the next day.
    if (isCmemGatewayUrl(apiUrl) && !cmemCapProbeAllowed()) {
      throw new CmemAllowanceExhaustedError('cmem.ai inference allowance is still spent; the next probe is tomorrow', {
        kind: 'quota_exhausted', code: 'allowance_exhausted', cause: new Error('cap probe withheld'),
      });
    }
    const carriesImages = imageCount > 0;
    // One logical request: every send (retries, the reasoning retry) shares
    // request_id and counts attempts.
    const correlationRequestId = randomUUID();
    let correlationAttempt = 0;
    const nextCorrelationHeaderValue = (): string | undefined => {
      if (!isCmemGatewayUrl(apiUrl)) return undefined;
      correlationAttempt += 1;
      return buildCmemCorrelationHeader({ requestId: correlationRequestId, attempt: correlationAttempt, eventKeys: correlationEventKeys });
    };
    const totalChars = history.reduce((sum, m) => sum + m.content.length, 0);
    // Text only: image token cost is provider-specific, so it is reported as a count.
    const estimatedTokens = this.estimateTokens(messages.map(m => m.content).join(''));
    const maxOutputTokens = resolveObserverMaxOutputTokens();

    logger.debug('SDK', `Querying OpenRouter multi-turn (${model})`, {
      turns: history.length,
      totalChars,
      estimatedTokens,
      maxOutputTokens,
      ...(carriesImages ? { images: imageCount } : {}),
    });

    const clientAttemptId = paidSendBudget?.clientAttemptId ?? randomUUID();
    // The id of the response actually returned, for the cut-off warning.
    let finalRequestId: string | undefined;
    // Taken from the body we are about to send, before any retry. A later
    // forced retry must not flip this: an already-disabled request that comes
    // back empty is a give-up, not a second identical send.
    const disabledOnSend = requestDisablesReasoning(buildOpenRouterRequestBody({
      model, fallbackModels, messages: requestMessages, apiUrl, plainText, maxOutputTokens, extraBody, reasoningEffort, label,
    }));

    // Decided once, so every attempt is bounded the way withRetry was told.
    const streamed = streamsChatCompletion(apiUrl);
    const liveness = streamed
      ? resolveStreamLiveness(perAttemptTimeoutMs, this.streamIdleTimeoutMs ?? resolveStreamIdleTimeoutMs())
      : null;
    let data: OpenRouterResponse;
    try {
      data = await withRetry<OpenRouterResponse>(async (attemptSignal) => {
      const exchange = await this.requestChatCompletion(
        apiUrl, apiKey, model, fallbackModels, requestMessages, siteUrl, appName, clientAttemptId, attemptSignal,
        maxOutputTokens, liveness, plainText, extraBody, reasoningEffort, label, false, carriesImages,
        nextCorrelationHeaderValue(),
      );
      const requestId = openRouterRequestId(exchange.headers);
      finalRequestId = requestId;
      const responseData = exchange.body as OpenRouterResponse;

      if (carriesImages && responseData.error && isMaxCompletionTokensCompatibilityError(exchange.status, JSON.stringify(responseData))) {
        throw new MediaRequestRejectedError('media_request_invalid:max_completion_tokens_required');
      }
      if (responseData.error) {
        // Per OpenRouter spec, errors can come in 200 responses too.
        throw classifyOpenRouterError({
          status: exchange.status,
          requestUrl: apiUrl,
          bodyText: JSON.stringify(responseData),
          headers: exchange.headers,
          cause: new Error(`OpenRouter API error: ${responseData.error.code} - ${responseData.error.message}`),
          ...(requestId ? { requestId } : {}),
        });
      }

      return responseData;
    }, {
      label: `OpenRouter ${model}`, abortSignal: signal, perAttemptTimeoutMs, paidSendBudget, clientAttemptId,
      // A streamed request is bounded by its idle timeout and absolute cap, and
      // may be resent once if it fails before any output.
      ...(streamed ? { attemptDeadlineOwnedByCaller: true, retryBeforeOutput: true } : {}),
      ...(signal ? { maxRetries: 0 } : {}), ...retryPolicyForPool(poolSize),
    });
    } catch (error) {
      if (error instanceof CmemAllowanceExhaustedError) noteCmemCapExhausted();
      throw error;
    }

    // A successful cmem-gateway response proves the delivered key is funded
    // again (resubscribed) — clear the trial-expiry fallback marker so
    // dispatch returns to the gateway. No-op for every other endpoint.
    clearProFallbackOnGatewaySuccess(apiUrl);
    if (isCmemGatewayUrl(apiUrl)) clearCmemCapProbe();

    const choice = data.choices?.[0];
    let message = choice?.message;
    // OpenAI-compatible gateways may represent assistant text as content
    // blocks. Never substitute reasoning or tool arguments for the answer.
    let content = assistantText(message?.content);
    // `length`: generation stopped at the output-token limit. A block cut off
    // mid-tag never closes, so the parser drops it: silently when earlier blocks
    // parsed, taking the whole batch when none did. Logged before the plain-text
    // and empty-reply exits so a reply cut off before any text is named too.
    let finishReason = typeof choice?.finish_reason === 'string' ? choice.finish_reason : undefined;
    // The cap a request actually sent: the answer's, plus reasoning's own
    // budget when that request turned reasoning on (the forced retry never does).
    const reasoningMaxTokensSent = (forceReasoningOff: boolean) => openRouterReasoningBudgetTokens({
      apiUrl, plainText, reasoningEffort, label, forceReasoningOff,
    });
    const warnIfCutOff = (reason: string | undefined, response: OpenRouterResponse, chars: number, forceReasoningOff = false) => {
      if (reason !== 'length') return;
      const reasoningMaxTokens = reasoningMaxTokensSent(forceReasoningOff);
      logger.warn('SDK', 'OpenRouter reply was cut off at the output-token limit', {
        model: response.model ?? model,
        requestId: finalRequestId,
        clientAttemptId,
        maxTokens: maxOutputTokens + reasoningMaxTokens,
        answerMaxTokens: maxOutputTokens,
        reasoningMaxTokens,
        outputTokens: response.usage?.completion_tokens,
        contentChars: chars,
        messagesInContext: history.length,
      });
    };
    warnIfCutOff(finishReason, data, content.length);

    // Empty + length is the reasoning budget burning the answer (#2995). One
    // retry, outside withRetry's loop, but counted on the same paid-send
    // allowance. A non-streamed retry gets the same per-attempt deadline
    // withRetry would have armed; a streamed one is already capped by liveness.
    // Already-disabled requests (openrouter.ai, cmem, effort "none") give up
    // loudly instead of sending the same body again.
    if (isLengthTruncatedEmptyReply(content, finishReason) && !disabledOnSend) {
      if (!claimReasoningBudgetRetry(paidSendBudget)) {
        logger.error('SDK', reasoningBudgetSkippedMessage('OpenRouter', paidSendBudget?.spentPaidSends ?? 0), {
          model: data.model ?? model,
          requestId: finalRequestId,
          finishReason,
          maxTokens: maxOutputTokens + reasoningMaxTokensSent(false),
        });
      } else {
        const firstUsage = data.usage;
        logger.error('SDK', reasoningBudgetRetryMessage('OpenRouter'), {
          model: data.model ?? model,
          requestId: finalRequestId,
          finishReason,
          maxTokens: maxOutputTokens + reasoningMaxTokensSent(false),
        });
        const deadline = liveness ? undefined : startReasoningRetryDeadline(signal, perAttemptTimeoutMs);
        try {
          const retrySignal = deadline?.signal ?? signal ?? new AbortController().signal;
          const exchange = await this.requestChatCompletion(
            apiUrl, apiKey, model, fallbackModels, requestMessages, siteUrl, appName, clientAttemptId, retrySignal,
            maxOutputTokens, liveness, plainText, extraBody, reasoningEffort, label, true, carriesImages,
            nextCorrelationHeaderValue(),
          );
          const requestId = openRouterRequestId(exchange.headers);
          finalRequestId = requestId;
          const retryData = exchange.body as OpenRouterResponse;
          if (retryData.error) {
            throw classifyOpenRouterError({
              status: exchange.status,
              bodyText: JSON.stringify(retryData),
              headers: exchange.headers,
              cause: new Error(`OpenRouter API error: ${retryData.error.code} - ${retryData.error.message}`),
              ...(requestId ? { requestId } : {}),
            });
          }
          data = withCombinedOpenRouterUsage(firstUsage, retryData);
          const retryChoice = data.choices?.[0];
          message = retryChoice?.message;
          content = assistantText(message?.content);
          finishReason = typeof retryChoice?.finish_reason === 'string' ? retryChoice.finish_reason : undefined;
          warnIfCutOff(finishReason, data, content.length, true);
          if (isLengthTruncatedEmptyReply(content, finishReason)) {
            logger.error('SDK', reasoningBudgetGiveUpMessage('OpenRouter', finishReason), {
              model: data.model ?? model,
              requestId: finalRequestId,
            });
          }
        } catch (error) {
          signal?.throwIfAborted();
          logger.error('SDK', reasoningBudgetGiveUpMessage('OpenRouter', finishReason), {
            model,
            requestId: finalRequestId,
          }, error instanceof Error ? error : new Error(String(error)));
        } finally {
          deadline?.finish();
        }
      }
    } else if (isLengthTruncatedEmptyReply(content, finishReason)) {
      logger.error('SDK', reasoningBudgetGiveUpMessage('OpenRouter', finishReason), {
        model: data.model ?? model,
        requestId: finalRequestId,
        maxTokens: maxOutputTokens + reasoningMaxTokensSent(false),
      });
    }

    if (plainText && !content.trim()) {
      const error = new Error('OpenRouter returned no assistant text for the Telegram wrap-up');
      logger.error('TELEGRAM', error.message, {
        model: data.model ?? model,
        requestId: finalRequestId,
        clientAttemptId,
        finishReason,
        contentType: Array.isArray(message?.content) ? 'array' : typeof message?.content,
        hasReasoningContent: Boolean(message?.reasoning_content || message?.reasoning),
        toolCalls: message?.tool_calls?.length ?? 0,
        completionTokens: data.usage?.completion_tokens,
      }, error);
      throw error;
    }
    if (!message || (typeof message.content !== 'string' && !content)) {
      logger.error('SDK', 'Empty response from OpenRouter');
      return { content: '', ...(finishReason ? { finishReason } : {}) };
    }

    if (content.length === 0) {
      logger.debug('SDK', 'OpenRouter returned an empty message', {
        finishReason,
        hasReasoningContent: Boolean(message.reasoning_content),
      });
    }
    const tokensUsed = data.usage?.total_tokens;
    const realInputTokens = data.usage?.prompt_tokens;
    const realOutputTokens = data.usage?.completion_tokens;
    // usage.cost is what openrouter.ai charged in credits (~USD); with BYOK the
    // model spend is reported separately as upstream_inference_cost. Custom
    // gateways usually omit both — costUsd stays undefined (never estimated).
    const orCost = typeof data.usage?.cost === 'number' ? data.usage.cost : undefined;
    const upstreamCost = typeof data.usage?.cost_details?.upstream_inference_cost === 'number'
      ? data.usage.cost_details.upstream_inference_cost
      : undefined;
    const costUsd = orCost !== undefined || upstreamCost !== undefined
      ? (orCost ?? 0) + (upstreamCost ?? 0)
      : undefined;
    const servedModel = typeof data.model === 'string' && data.model ? data.model : undefined;

    if (tokensUsed) {
      logger.info('SDK', 'OpenRouter API usage', {
        model: servedModel ?? model,
        inputTokens: realInputTokens || 0,
        outputTokens: realOutputTokens || 0,
        totalTokens: tokensUsed,
        ...(costUsd !== undefined ? { costUSD: costUsd.toFixed(6) } : {}),
        messagesInContext: history.length,
        requestId: finalRequestId,
        clientAttemptId,
      });
    }

    return {
      content, tokensUsed, inputTokens: realInputTokens, outputTokens: realOutputTokens, costUsd, servedModel,
      ...(finishReason ? { finishReason } : {}),
    };
  }

}

/**
 * The cmem gateway refused an image request (`bad_request`,
 * `media_request_invalid:<reason>`). Unrecoverable for this request shape, so
 * never retried as is; the caller resends the turn once text-only.
 */
class MediaRequestRejectedError extends ClassifiedProviderError {
  readonly reason: string;
  constructor(bodyText: string) {
    const match = /media_request_invalid:([a-z_]{1,40})/.exec(bodyText);
    super('Gateway rejected the image request', { kind: 'unrecoverable', cause: null, code: 'media_request_invalid' });
    this.name = 'MediaRequestRejectedError';
    this.reason = match ? match[1] : 'unknown';
  }
}

export function isOpenRouterAvailable(settingsPath: string = USER_SETTINGS_PATH): boolean {
  return Boolean(resolveOpenRouterConfig(settingsPath).apiKey);
}

export function isOpenRouterSelected(): boolean {
  const settingsPath = USER_SETTINGS_PATH;
  const settings = SettingsDefaultsManager.loadFromFile(settingsPath);
  return settings.CLAUDE_MEM_PROVIDER === 'openrouter';
}