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
TypeScript aiai-agentsai-memoryanthropicartificial-intelligencechromadbclaudeclaude-agent-sdkclaude-agentsclaude-codeclaude-code-pluginclaude-skillsembeddingslong-term-memorymem0memory-engineopenmemoryragsqlitesupermemory
// SPDX-License-Identifier: Apache-2.0
import { assistantText } from '../../../shared/assistant-text.js';
import { resolveOpenRouterChatCompletionsUrl } from '../../../shared/openrouter-base-url.js';
import { openRouterAttributionHeaders, OPENROUTER_APP_URL, OPENROUTER_APP_TITLE } from '../../../shared/openrouter-attribution.js';
import { fetchWithOpenRouterTokenCompatibility } from '../../../shared/openrouter-token-compatibility.js';
import { withOpenRouterExtraBody } from '../../../shared/openrouter-extra-body.js';
import { isCmemGatewayUrl } from '../../../shared/cmem-gateway.js';
import { isOpenRouterApiUrl } from '../../../shared/openrouter-base-url.js';
import {
billedTokensAcrossRetry,
isLengthTruncatedEmptyReply,
reasoningBudgetGiveUpMessage,
reasoningBudgetRetryMessage,
requestDisablesReasoning,
} from '../../../services/worker/reasoning-budget.js';
import { SettingsDefaultsManager } from '../../../shared/SettingsDefaultsManager.js';
import { logger } from '../../../utils/logger.js';
import {
ServerClassifiedProviderError,
SERVER_MAX_PAID_SENDS_PER_JOB,
classifyHttpProviderError,
} 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';
export interface OpenRouterObservationProviderOptions {
apiKey: string;
model?: string;
/**
* Optional OpenAI-compatible base URL (#2382/#2590/#2622/#2393). When set,
* requests POST to `<baseUrl>/chat/completions` (or verbatim if it already
* ends in `/chat/completions`). When unset, the default OpenRouter endpoint
* is used — behavior unchanged. Examples: https://api.deepseek.com (DeepSeek),
* http://localhost:1234/v1 (LM Studio), a custom gateway base.
*/
baseUrl?: string;
maxOutputTokens?: number;
siteUrl?: string;
appName?: string;
/**
* CLAUDE_MEM_OPENROUTER_EXTRA_BODY, parsed: provider-specific request fields
* merged into every request, under the worker's rules (protected fields
* stay, never sent to the cmem gateway).
*/
extraBody?: Record<string, unknown>;
fetchImpl?: typeof fetch;
}
interface OpenRouterResponse {
choices?: Array<{ message?: { content?: unknown }; finish_reason?: string }>;
usage?: { total_tokens?: number; prompt_tokens?: number; completion_tokens?: number };
error?: { code?: string | number; message?: string };
}
export class OpenRouterObservationProvider implements ServerGenerationProvider {
readonly providerLabel = 'openrouter' as const;
private readonly apiKey: string;
private readonly model: string;
private readonly apiUrl: string;
private readonly maxOutputTokens: number;
private readonly siteUrl: string;
private readonly appName: string;
private readonly extraBody: Record<string, unknown> | undefined;
private readonly fetchImpl: typeof fetch;
constructor(options: OpenRouterObservationProviderOptions) {
if (!options.apiKey) {
throw new ServerClassifiedProviderError('OpenRouter API key not configured', {
kind: 'auth_invalid',
cause: new Error('apiKey is required'),
});
}
this.apiKey = options.apiKey;
// Model is passed verbatim so arbitrary OpenAI-compatible ids work. #2393.
// Without one, use the worker's OpenRouter default: the old hard-coded
// 'anthropic/claude-3.5-sonnet' left OpenRouter's catalog, so every
// unconfigured server-runtime request was rejected.
this.model = options.model ?? SettingsDefaultsManager.getAllDefaults().CLAUDE_MEM_OPENROUTER_MODEL;
this.apiUrl = resolveOpenRouterChatCompletionsUrl(options.baseUrl);
this.maxOutputTokens = options.maxOutputTokens ?? 4096;
this.siteUrl = options.siteUrl ?? OPENROUTER_APP_URL;
this.appName = options.appName ?? OPENROUTER_APP_TITLE;
this.extraBody = options.extraBody;
this.fetchImpl = options.fetchImpl ?? fetch;
}
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) {
return {
rawText: '<skip_summary reason="all_events_private" />',
providerLabel: this.providerLabel,
modelId: this.model,
};
}
const firstBody = this.buildChatBody(prompt, false);
const disabledOnSend = requestDisablesReasoning(firstBody);
let data = await this.postAndRead(firstBody, signal);
let rawText = assistantText(data.choices?.[0]?.message?.content, '').trim();
let finishReason = typeof data.choices?.[0]?.finish_reason === 'string' ? data.choices[0].finish_reason : undefined;
// Same bug as the worker: an empty finish_reason=length reply spent the
// output budget on reasoning. One retry with reasoning forced off. A
// custom gateway does not get the field on the first request (strict
// schemas 400); openrouter.ai and cmem already send it, so they give up
// here instead of sending the same body again. Both calls were billed.
if (isLengthTruncatedEmptyReply(rawText, finishReason)) {
// The outbox attempt includes this request. Use the same conservative
// allowance as ProviderObservationGenerator: a correction inside the
// final allowed attempt must not buy a third potentially billed send.
if (!disabledOnSend && context.job.attempts >= SERVER_MAX_PAID_SENDS_PER_JOB) {
logger.error('SDK', 'OpenRouter reply was empty; skipping the reasoning correction because the job paid-send allowance is exhausted', {
provider: 'openrouter', model: this.model,
attempt: context.job.attempts, maxPaidSends: SERVER_MAX_PAID_SENDS_PER_JOB,
});
} else if (!disabledOnSend) {
const firstUsage = data.usage;
logger.error('SDK', reasoningBudgetRetryMessage('OpenRouter'), { provider: 'openrouter', model: this.model, finishReason });
try {
data = await this.postAndRead(this.buildChatBody(prompt, true), signal);
const billed = billedTokensAcrossRetry(firstUsage, data.usage);
if (billed !== undefined) data = { ...data, usage: { ...data.usage, total_tokens: billed } };
rawText = assistantText(data.choices?.[0]?.message?.content, '').trim();
finishReason = typeof data.choices?.[0]?.finish_reason === 'string' ? data.choices[0].finish_reason : undefined;
if (isLengthTruncatedEmptyReply(rawText, finishReason)) {
logger.error('SDK', reasoningBudgetGiveUpMessage('OpenRouter', finishReason), { provider: 'openrouter', model: this.model });
}
} catch (error) {
logger.error('SDK', reasoningBudgetGiveUpMessage('OpenRouter', finishReason), {
provider: 'openrouter',
model: this.model,
}, error instanceof Error ? error : new Error(String(error)));
}
} else {
logger.error('SDK', reasoningBudgetGiveUpMessage('OpenRouter', finishReason), { provider: 'openrouter', model: this.model });
}
}
if (!rawText) {
logger.warn('SDK', 'OpenRouter returned empty content', {
provider: 'openrouter',
model: this.model,
finishReason,
});
}
// Compatible endpoints can report only the prompt/completion split. Use
// the same accounting as the correction path even when no retry occurred.
const tokensUsed = billedTokensAcrossRetry(data.usage, undefined);
return {
rawText,
...(tokensUsed !== undefined ? { tokensUsed } : {}),
providerLabel: this.providerLabel,
modelId: this.model,
};
}
private buildChatBody(prompt: string, forceReasoningOff: boolean): Record<string, unknown> {
const reachesOpenRouter = isOpenRouterApiUrl(this.apiUrl) || isCmemGatewayUrl(this.apiUrl);
return withOpenRouterExtraBody({
model: this.model,
messages: [{ role: 'user', content: prompt }],
temperature: 0.3,
// Ask for one JSON body, as the worker does (#3668). A gateway that
// streams by default answers with text/event-stream, which
// response.json() cannot read, and `stream` is protected from the extra
// body. The cmem gateway never streams unasked; its requests stay as
// they are. Reasoning off wherever the body reaches OpenRouter, and on
// the one-shot retry for a custom gateway.
...(reachesOpenRouter || forceReasoningOff ? { reasoning: { enabled: false } } : {}),
...(isCmemGatewayUrl(this.apiUrl) ? {} : { stream: false }),
}, this.extraBody, this.apiUrl, forceReasoningOff);
}
private async postAndRead(body: Record<string, unknown>, signal?: AbortSignal): Promise<OpenRouterResponse> {
let response: Response;
try {
response = await this.postChatCompletion(body, signal);
} catch (networkError) {
const err = networkError instanceof Error ? networkError : new Error(String(networkError));
throw classifyHttpProviderError({
cause: err,
providerLabel: 'OpenRouter',
});
}
if (!response.ok) {
const bodyText = await safeReadBody(response);
throw classifyHttpProviderError({
status: response.status,
bodyText,
headers: response.headers,
cause: new Error(`OpenRouter API error: ${response.status} - ${bodyText}`),
providerLabel: 'OpenRouter',
});
}
let data: OpenRouterResponse;
try {
data = (await response.json()) as OpenRouterResponse;
} catch (parseError) {
const err = parseError instanceof Error ? parseError : new Error(String(parseError));
throw new ServerClassifiedProviderError('OpenRouter returned invalid JSON', {
kind: 'parse_error',
cause: err,
});
}
if (data.error) {
throw classifyHttpProviderError({
status: response.status,
bodyText: `${data.error.code ?? ''} ${data.error.message ?? ''}`,
headers: response.headers,
cause: new Error(`OpenRouter API error: ${data.error.code} - ${data.error.message}`),
providerLabel: 'OpenRouter',
});
}
return data;
}
private postChatCompletion(body: Record<string, unknown>, signal?: AbortSignal): Promise<Response> {
return fetchWithOpenRouterTokenCompatibility(this.fetchImpl, this.apiUrl, {
method: 'POST',
headers: {
Authorization: `Bearer ${this.apiKey}`,
...openRouterAttributionHeaders(this.siteUrl, this.appName),
'Content-Type': 'application/json',
},
signal,
}, body, this.maxOutputTokens);
}
}
async function safeReadBody(response: Response): Promise<string> {
try {
return await readCappedErrorBody(response);
} catch (readError) {
const err = readError instanceof Error ? readError : new Error(String(readError));
logger.warn('SDK', 'Failed to read OpenRouter error response body', { provider: 'openrouter' }, err);
return '';
}
}