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
import { logger } from '../../../utils/logger.js';
import type { ActiveSession } from '../../worker-types.js';
import type { WorkerService } from '../../worker-service.js';
import type { SessionManager } from '../SessionManager.js';
import type { ClaudeProvider } from '../ClaudeProvider.js';
import type { GeminiProvider } from '../GeminiProvider.js';
import type { OpenRouterProvider } from '../OpenRouterProvider.js';
import type { OpenAICompatProvider } from '../OpenAICompatProvider.js';
import type { CodexProvider } from '../CodexProvider.js';
import type { SessionCompletionHandler } from './SessionCompletionHandler.js';
import {
recordCmemFallbackIfEligible,
regularProviderAfterCmemCap,
releaseCmemGatewayProbe,
routeAroundUnservableProvider,
type SelectableProvider,
} from '../provider-dispatch.js';
import { handleGeneratorExit } from './GeneratorExitHandler.js';
import { normalizeAbortReason, OBSERVER_TEXT_RATE_LIMIT_ABORT_REASON, PROVIDER_SWITCH_BOUNDARY_ABORT_REASON } from './abort-reason.js';
import {
MAX_CONSECUTIVE_STALL_RESUMES,
RESPONSE_STALL_RESUME_DELAY_MS,
planRateLimitResume,
planResponseStallResume,
planUnattendedGatewayResume,
} from './response-pacer.js';
import { telemetryBuffer } from '../../telemetry/buffer.js';
import { observerUsageLogFields } from '../observer-usage.js';
import { AMBIGUOUS_QUOTA_MESSAGE, CLAUDE_LOGIN_UNREADABLE_CODE, recordObserverFailure, type ObserverQuotaReason } from '../../../shared/observer-health.js';
import { explainQuotaAbort, globalRateLimitStore } from '../RateLimitStore.js';
import {
CODEX_CLI_SETUP_REMEDIATION,
recordClaudeSetupRequired,
recordCodexCliSetupRequired,
} from '../../../shared/dependency-health.js';
import { canCmemGatewayServe } from '../../../shared/cmem-gateway.js';
import {
releaseQuotaProbe,
recordAuthCooldown,
recordQuotaExhausted,
type ClaudeCredential,
QUOTA_EXHAUSTED_RECHECK_COOLDOWN_MS,
} from '../../../shared/quota-cooldown.js';
import {
CmemAllowanceExhaustedError,
CODEX_COOLDOWN_REFUSAL_CODE,
DEADLINE_EXCEEDED_CODE,
isClassified,
describeProviderError,
type ClassifiedProviderError,
} from '../provider-errors.js';
export interface GeneratorRunnerDependencies {
sessionManager: SessionManager;
sdkAgent: ClaudeProvider;
geminiAgent: GeminiProvider;
openRouterAgent: OpenRouterProvider;
/** Absent only in harnesses that never select Codex. */
codexAgent?: CodexProvider;
/** Absent only in harnesses that never select openai-compatible. */
openAICompatAgent?: OpenAICompatProvider;
workerService: WorkerService;
completionHandler: SessionCompletionHandler;
ensureGeneratorRunning: (sessionDbId: number, source: string) => Promise<void>;
/**
* SessionRoutes' once-per-process self-heal for a Claude CLI that is on disk
* but no longer spawnable (#3291). Returns true when a worker restart was
* triggered.
*/
maybeSelfHealStaleClaudeSpawn: (error: unknown, source: string, sessionDbId: number) => boolean;
}
/**
* Book a deadline expiry in the observer-health ledger.
*
* The provider pauses on it: it aborts the controller, so the finally books
* the turn once as aborted and the buffered work survives, and the catch
* keeps transient pauses out of the ledger. But nothing was stored. A
* backend that is always slower than CLAUDE_MEM_LLM_TIMEOUT_MS would store
* nothing and never raise the session-start warning. The error's own code
* and remedy (raise the deadline) let the warning say what to do, and age it
* into a last-known note once nothing has re-tested it
* (isDeadlineFailureStale). Every other transient pause stays out of the
* ledger: a network blip is not an outage.
*
* Only while this session is still the registered one. OpenAI-compatible
* queries do not take the session's abort signal, so a deleted session's
* request runs on to its deadline with nobody waiting for the answer.
*/
function recordDeadlineExpiry(
provider: SelectableProvider,
session: ActiveSession,
error: unknown,
sessionManager: SessionManager,
): void {
if (!isClassified(error) || error.code !== DEADLINE_EXCEEDED_CODE) return;
if (sessionManager.getSession(session.sessionDbId) !== session) return;
recordObserverFailure(provider, {
message: error.message,
kind: error.kind,
code: error.code,
action: error.action,
});
}
/** Quota prose: the observer's own reply said its allowance is spent. */
export const OBSERVER_TEXT_QUOTA_MESSAGE = 'The observer replied that its usage allowance is exhausted';
/** Rate-limit reply text (#5428): the provider throttled the observer's request. */
export const OBSERVER_TEXT_RATE_LIMIT_MESSAGE = 'The observer replied that the provider rate limited the request (429)';
/**
* The pause to book for a quota exit.
* - 'quota:observer_text': the provider's own refusal, written as the reply
* (any provider), so it is exhausted, not ambiguous.
* - Claude's guard: 'quota:<window>:<kind>'. The kind is what the guard
* decided at abort time; the snapshot only supplies the wording, and when it
* no longer explains the stop a kind-appropriate generic message is used.
* - Anything else keeps the generic record the banner reads as ambiguous.
*/
export function quotaPauseForExit(
provider: string,
reason: string | null | undefined,
profile?: string,
): { kind: 'quota_guard' | 'quota_exhausted'; message: string; reason?: ObserverQuotaReason } {
if (reason === 'quota:observer_text') {
return { kind: 'quota_exhausted', message: OBSERVER_TEXT_QUOTA_MESSAGE };
}
const kind = (reason ?? '').split(':')[2];
if (provider === 'claude' && (kind === 'quota_guard' || kind === 'quota_exhausted')) {
const explained = explainQuotaAbort(reason, globalRateLimitStore, Date.now(), profile);
if (explained?.kind === kind) return explained;
return kind === 'quota_guard'
? { kind, message: 'Memory capture paused by the Claude usage reserve guard.', reason: { kind: 'unknown' } }
: { kind, message: 'Claude rejected the request because a usage allowance is exhausted.', reason: { kind: 'used_up', window: (reason ?? '').split(':')[1] } };
}
return { kind: 'quota_exhausted', message: AMBIGUOUS_QUOTA_MESSAGE };
}
export async function startGeneratorWithProvider(
session: ActiveSession | undefined,
provider: SelectableProvider,
source: string,
/** The quota probe this run claimed, or null when it was admitted without one. */
quotaProbeClaimId: number | null,
/** The cmem-gateway re-probe this run claimed, or null when it took none. */
gatewayProbeClaimId: number | null,
deps: GeneratorRunnerDependencies,
): Promise<void> {
const { sessionManager, sdkAgent, geminiAgent, openRouterAgent, codexAgent, openAICompatAgent, workerService,
completionHandler, ensureGeneratorRunning, maybeSelfHealStaleClaudeSpawn } = deps;
if (!session) return;
// A generator is starting, so a pending resume has nothing left to do.
if (session.stallResumeTimer !== undefined) {
clearTimeout(session.stallResumeTimer);
session.stallResumeTimer = undefined;
}
if (session.scheduledResumeTimer !== undefined) {
clearTimeout(session.scheduledResumeTimer);
session.scheduledResumeTimer = undefined;
}
// A running generator is not an abandoned stall, whatever its counter says.
session.stallResumesExhaustedAt = undefined;
// The last pause no longer describes this session; if this run pauses
// too, its exit records a fresh reason. Without this, one auth pause would
// keep the session out of every automatic sweep for good.
session.pausedReason = null;
session.providerSwitchPending = false;
if (session.abortController.signal.aborted) {
logger.debug('SESSION', 'Resetting aborted AbortController before starting generator', {
sessionId: session.sessionDbId
});
session.abortController = new AbortController();
}
const agent = provider === 'codex'
? codexAgent
: provider === 'openrouter'
? openRouterAgent
: provider === 'gemini'
? geminiAgent
: provider === 'openai-compatible'
? openAICompatAgent
: sdkAgent;
const agentName = provider === 'codex'
? 'Codex'
: provider === 'openrouter'
? 'OpenRouter'
: provider === 'gemini'
? 'Gemini'
: provider === 'openai-compatible'
? 'OpenAI-compatible'
: 'Claude SDK';
if (!agent) throw new Error(`${agentName} provider is not configured`);
const actualQueueDepth = sessionManager.getMessageBuffer().getPendingCount(session.sessionDbId);
logger.info('SESSION', `Generator auto-starting (${source}) using ${agentName}`, {
sessionId: session.sessionDbId,
queueDepth: actualQueueDepth,
historyLength: session.conversationHistory.length
});
session.currentProvider = provider;
session.lastGeneratorActivity = Date.now();
// Providers refine this per-prompt ('init'|'ingest'|'summarize'); this is
// the fallback when a generator dies before dispatching its first prompt.
session.lastGeneratorSource = source;
const myController = session.abortController;
let skipGeneratorExitFinalization = false;
// Set when the catch below settled this run's failure itself. The finally
// then leaves it alone: one failure is booked once.
let failureBooked = false;
// Set when the catch decided this paused session resumes on its own: at
// once on the Anthropic plan after a cmem fallback, or after a rate limit's
// Retry-After. The finally schedules it.
let scheduledResume: { afterMs: number; source: string } | null = null;
let generatorPromise: Promise<void>;
generatorPromise = agent.startSession(session, workerService)
.catch(async error => {
const classified = isClassified(error) ? error : null;
// Since #3999 a provider PAUSES on a classified error by aborting the
// controller before rethrowing, so an aborted controller alone no longer
// means an external abort. Only an unclassified rejection after an abort
// is one (idle, shutdown, a provider switch) — nothing to book.
if (myController.signal.aborted && !classified) {
logger.debug('HTTP', 'Generator catch: ignoring error after abort', { sessionId: session.sessionDbId });
return;
}
const errorMsg = error instanceof Error ? error.message : String(error);
if (provider === 'claude' && isClassified(error) && error.kind === 'setup_required') {
skipGeneratorExitFinalization = true;
session.pausedReason = 'setup_required';
recordClaudeSetupRequired(error);
maybeSelfHealStaleClaudeSpawn(error, source, session.sessionDbId);
logger.warn('SESSION', 'Claude generator start requires setup; future Claude starts will be skipped until repaired', {
sessionId: session.sessionDbId,
provider,
error: error.message,
});
return;
}
// The same shape for Codex: a missing CLI or ChatGPT login, or a model,
// effort or isolation Codex refuses, fails every retry the same way, so
// the buffered work waits behind the codex_cli gate instead of being
// finalized. Unlike a Claude setup failure it is booked in observer-health
// too, so SessionStart says memory has stopped and how to fix it. A
// request the gate itself withheld repeats the failure that armed it:
// booking it again would restart the recheck window and count one outage
// many times.
if (provider === 'codex' && isClassified(error) && error.kind === 'setup_required') {
skipGeneratorExitFinalization = true;
session.pausedReason = 'setup_required';
if (error.code !== CODEX_COOLDOWN_REFUSAL_CODE) {
recordCodexCliSetupRequired(error.message, error.action);
recordObserverFailure(provider, {
message: error.message,
kind: error.kind,
code: error.code,
action: error.action ?? CODEX_CLI_SETUP_REMEDIATION,
});
}
logger.warn('SESSION', 'Codex generator requires setup; future Codex starts will be skipped until repaired', {
sessionId: session.sessionDbId,
provider,
error: error.message,
});
return;
}
if (errorMsg.includes('code 143') || errorMsg.includes('signal SIGTERM')) {
logger.warn('SESSION', 'Generator killed by external signal', {
sessionId: session.sessionDbId,
provider,
error: errorMsg
});
myController.abort();
return;
}
// No retry here: a quota or auth pause discards its buffered work, and
// a failed run leaves the transcript as the only record. The next observation ingest starts a fresh generator via
// ensureGeneratorRunning.
failureBooked = true;
// The cmem gateway stopped serving this account, or the post-window
// re-probe failed: memory runs on the Anthropic plan — the promised
// switch, not an outage — so it is neither booked into the health
// ledger nor given a breaker (a 30-min breaker over the marker's 15-min
// window would leave memory on neither), and the finally resumes it.
if (provider === 'openrouter' && recordCmemFallbackIfEligible(error, gatewayProbeClaimId)) {
// A real HTTP 402 allowance refusal performed no inference. Hand the
// still-live batch to the configured provider once, with its original
// age and paid-send budget. Never hand off an ambiguous prior send,
// an authentication failure, or a failed probe.
const budget = session.paidSendBudget;
const unspent = budget ? budget.spentPaidSends === 0 : !session.consecutiveUnattendedGatewayResumes;
if (classified instanceof CmemAllowanceExhaustedError && unspent
&& normalizeAbortReason(session.abortReason) === 'quota'
&& regularProviderAfterCmemCap(session.platformSource, session.observerModel) !== null
&& planUnattendedGatewayResume(session, 'cmem-cap-fallback', true).resume) {
session.abortReason = 'provider_switch:cmem_cap';
scheduledResume = { afterMs: 0, source: 'cmem-cap-fallback' };
} else if (gatewayProbeClaimId !== null && !['auth', 'quota'].includes(normalizeAbortReason(session.abortReason))
&& planUnattendedGatewayResume(session, 'cmem-fallback', true).resume) {
scheduledResume = { afterMs: 0, source: 'cmem-fallback' };
}
// The gateway's words and request id, which its copy asks users to
// quote to support.
logger.warn('SESSION', 'cmem gateway is not serving this account; local provider routing will check availability', {
sessionId: session.sessionDbId,
...(classified ? { kind: classified.kind } : {}),
...(classified?.code ? { code: classified.code } : {}),
...(classified?.requestId ? { requestId: classified.requestId } : {}),
}, classified ? describeProviderError(classified) : errorMsg);
} else if (classified?.kind === 'transient' && myController.signal.aborted) {
recordDeadlineExpiry(provider, session, classified, sessionManager);
// The provider PAUSED on a deadline or an upstream fault that outlived
// its own retries: the batch is kept for the next generator. A fault
// is not an observer failure — counting these would raise the outage
// banner over blips that clear on their own. Our own deadline is the
// exception, booked just above with its own remedy and aging. A
// transient error that did not pause the run (Claude's overloaded or
// unknown errors) ended it, and is booked below like any other failure.
const pauseContext = {
sessionId: session.sessionDbId,
provider,
...(classified.requestId ? { requestId: classified.requestId } : {}),
};
const pauseLine = 'Observer paused on a transient provider failure; buffered work kept';
// A fault that names its own remedy (#4115: a local-network host the
// worker may not be allowed to reach) is logged where the user will
// see it. A plain blip stays at debug; our own deadline is booked
// above with its remedy.
if (classified.action && classified.code !== DEADLINE_EXCEEDED_CODE) {
logger.warn('SESSION', pauseLine, pauseContext, describeProviderError(classified));
} else {
logger.debug('SESSION', pauseLine, pauseContext, describeProviderError(classified));
}
// The fault outlived the provider's own retries. When the fallback (by
// default the Anthropic plan) can take the work, hold this provider
// briefly and move the buffered work there now, rather than waiting
// for the next captured event to hit the same outage.
const fallback = routeAroundUnservableProvider(provider, classified.message, 'unavailable', session.observerProfile);
if (fallback !== null) {
logger.warn('SESSION', 'Provider unavailable after its retries; buffered work moves to the fallback', {
...pauseContext,
fallback,
}, describeProviderError(classified));
scheduledResume = { afterMs: 0, source: 'provider-fallback' };
}
} else if (classified?.code === CODEX_COOLDOWN_REFUSAL_CODE) {
// Withheld by the armed Codex breaker, never sent: the request that
// armed it was booked once. Booking this one too would re-arm the
// breaker, ending the probe whose success clears it, and count one
// outage once per withheld request.
logger.debug('SESSION', 'Observer request withheld while the Codex breaker is armed', {
sessionId: session.sessionDbId,
provider,
kind: classified.kind,
});
} else if (classified) {
// The single error-level line for a classified provider failure:
// code, message, action, link, and request id — same words the
// gateway sent. Pass the rendered string (not the Error): classified
// errors are user-state (quota/auth/rate-limit), not bugs, so the
// errorSink/captureException isn't fired for them at all.
logger.error('SESSION', 'Observer failed', {
sessionId: session.sessionDbId,
provider,
kind: classified.kind,
...(classified.code ? { code: classified.code } : {}),
...(classified.requestId ? { requestId: classified.requestId } : {}),
...observerUsageLogFields(session),
}, describeProviderError(classified));
scheduledResume = bookClassifiedFailure(session, provider, classified);
} else {
logger.error('SESSION', 'Generator failed', {
sessionId: session.sessionDbId,
provider,
error: errorMsg,
...observerUsageLogFields(session),
}, error);
recordObserverFailure(provider, errorMsg);
}
// A pause (the provider aborted) is counted by the finally under its
// abort reason; only a run that ended on the error itself is 'error'.
// The local error line (full fidelity) and this scrubbed rollup are
// one logical event.
if (!myController.signal.aborted) {
telemetryBuffer.record('session_compressed', session.sessionDbId, {
outcome: 'error',
provider,
// Providers seed lastModelId when they start; 'unknown' covers a
// generator that died before resolving its model.
model: session.lastModelId ?? 'unknown',
error_category: 'provider_error',
hook: session.lastGeneratorSource,
ide: session.platformSource,
observed_model: session.observedModel,
observed_billing: session.observedBilling,
});
}
})
.finally(async () => {
if (skipGeneratorExitFinalization) {
// Setup needs operator repair. A transport timer from an earlier
// failure must not restart Claude while that setup gate is active.
sessionManager.clearTransportResume(session.sessionDbId);
if (session.generatorPromise === generatorPromise) {
session.generatorPromise = null;
}
if (session.currentProvider === provider) {
session.currentProvider = null;
}
// This run is over even though it skips finalization, so it must not
// keep holding the probe.
releaseQuotaProbe(provider, quotaProbeClaimId);
releaseCmemGatewayProbe(gatewayProbeClaimId);
return;
}
const reason = session.abortReason ?? null;
session.abortReason = null; // consume the reason
const normalizedReason = normalizeAbortReason(reason);
// Quota surfaced as assistant prose — or Claude's proactive usage guard
// — aborts without throwing, so it never reaches the catch; book it
// here, arming the breaker too, or the prose path keeps the
// per-observation request storm the classified path no longer has.
// A thrown classified error was already booked by the catch, once: it
// is never re-booked here as a spent allowance (a rate limit is not
// one), nor given a breaker over a cmem fallback's window.
if (normalizedReason === 'quota' && !failureBooked) {
// Book what actually stopped the observer (quotaPauseForExit): the
// SessionStart banner must not call a 95% reserve pause a spent
// allowance, nor a provider's own refusal a precaution.
const pause = quotaPauseForExit(provider, reason, session.observerProfile);
const quotaReason = pause.reason ?? (pause.kind === 'quota_exhausted' && pause.message !== AMBIGUOUS_QUOTA_MESSAGE
? providerQuotaRefusalReason(provider, session)
: { kind: 'unknown' as const });
recordQuotaExhausted(provider, pause.message, reason?.split(':')[1], undefined, session.observerProfile, primaryCredentialOf(session, provider), quotaReason);
// Quota returned as assistant prose never throws, so it never reaches
// the .catch above and never armed the health ledger. Without this the
// session-start warning is structurally blind to an entire outage
// class: the allowance is spent, no observation will ever store, and
// the user is told nothing.
recordObserverFailure(provider, pause);
}
// A 429 the CLI wrote as the reply (#5428) aborts without throwing too,
// so it is booked here as the throttle it is, the way bookClassifiedFailure
// books a thrown rate_limit that named no Retry-After: move the work to
// the fallback when one can serve, otherwise hold the provider for the
// short 'rate_limit' window, never the half-hour quota cooldown.
if (reason === OBSERVER_TEXT_RATE_LIMIT_ABORT_REASON && !failureBooked) {
if (routeAroundUnservableProvider(provider, OBSERVER_TEXT_RATE_LIMIT_MESSAGE, 'rate_limit', session.observerProfile) !== null) {
scheduledResume = { afterMs: 0, source: 'provider-fallback' };
} else {
recordQuotaExhausted(provider, OBSERVER_TEXT_RATE_LIMIT_MESSAGE, 'rate_limit', undefined, session.observerProfile);
}
recordObserverFailure(provider, { message: OBSERVER_TEXT_RATE_LIMIT_MESSAGE, kind: 'rate_limit' });
}
// A signed-out Claude observer answers with the CLI's own prose ("Not
// logged in · Please run /login"). ResponseProcessor resets the batch to
// pending and aborts with 'auth:observer_text' rather than throwing, so
// it never reaches the .catch above. Without this the observer-health
// ledger stays green through a full auth outage — every observation is
// dropped, yet /api/health and the session-start warning report healthy
// (#4150). Only that Claude prose path is booked here: a classified auth
// error is booked by the .catch with the provider's own words, and the
// cmem gateway's key_invalid is the trial-expiry fallback, not an outage.
// It is booked as the refused credential it is (auth_invalid), so the
// SessionStart banner shows at once with the /login remedy rather than
// waiting out the failure threshold and then offering a restart. The same
// prose appears when the worker cannot read a credential that exists
// (#5250), so the notice names that as the next check after /login.
// When the spawn already knew it had found no usable login (#6319),
// the notice says that, with the item it read, instead: /login cannot
// help a user whose terminal is already signed in to another profile.
const unreadableLoginReason = session.unusableClaudeLoginReason ?? null;
if (reason === 'auth:observer_text' && provider === 'claude' && !failureBooked) {
recordObserverFailure(provider, unreadableLoginReason ? {
message: `claude-mem could not read your Claude Code login: ${unreadableLoginReason}`,
kind: 'auth_invalid',
code: CLAUDE_LOGIN_UNREADABLE_CODE,
action: 'If `claude auth status` says you are logged out, run /login. If it says you are logged in, your terminal uses another credential profile (CLAUDE_CONFIG_DIR / CLAUDE_SECURESTORAGE_CONFIG_DIR): run `claude setup-token` and put the token in ~/.claude-mem/.env as CLAUDE_CODE_OAUTH_TOKEN',
} : {
message: 'Claude Code could not authenticate the observer',
kind: 'auth_invalid',
action: 'Run /login in Claude Code (or `claude auth login` in a terminal) to refresh the observer credentials. If you are already signed in, check the worker log for OAUTH credential-store lookup errors',
});
}
if (reason === 'auth:observer_verification_hold' && provider === 'claude' && !failureBooked) {
recordObserverFailure(provider, {
message: 'Claude Code cannot receive replies until the account verification hold is resolved',
kind: 'auth_invalid',
action: 'Complete the account check in Anthropic’s Verification Portal, then retry the preserved work',
});
}
// A Claude fallback run, or a run on the quota-fallback credential,
// that finds Claude signed out (or refused by org policy) takes Claude
// out of the fallback rotation for a cooldown, as a
// thrown auth refusal already does (bookClassifiedFailure). Otherwise each
// captured event would start the same signed-out fallback again while
// the primary is held. A Claude primary keeps retrying on the next event.
const claudeStandInAuthBlocked = provider === 'claude' && !failureBooked
&& (session.fallbackFrom != null || session.claudeAuthOverride != null)
&& (reason === 'auth:observer_text' || reason === 'auth:observer_org_policy' || reason === 'auth:observer_verification_hold');
if (claudeStandInAuthBlocked) {
recordAuthCooldown('claude', 'Claude Code refused the fallback observer', session.observerProfile);
}
// The org-policy refusal (#4677) goes down the same preserved auth path,
// but logging in again cannot lift it, so it carries the notice's own
// remedy instead of the /login advice.
if (reason === 'auth:observer_org_policy' && provider === 'claude' && !failureBooked) {
recordObserverFailure(provider, {
message: 'Your organization has disabled Claude subscription access for Claude Code',
kind: 'auth_invalid',
action: 'Set ANTHROPIC_API_KEY in ~/.claude-mem/.env, or ask your organization admin to enable subscription access',
});
}
if (reason !== null) {
// Abort accounting lives HERE, where the reason is consumed — the
// ONLY point every abort flow (idle / shutdown / overflow / quota)
// passes through. Emit the closed enum, never the raw
// string ('quota:…' carries a window suffix).
telemetryBuffer.record('session_compressed', session.sessionDbId, {
outcome: 'aborted',
provider,
model: session.lastModelId ?? 'unknown',
abort_reason: normalizedReason,
hook: session.lastGeneratorSource,
ide: session.platformSource,
observed_model: session.observedModel,
observed_billing: session.observedBilling,
});
}
// Every generator exit releases any probe this run claimed. Success
// already deleted the breaker and a fresh refusal already re-armed it;
// this covers aborts and crashes, so a claim can never outlive its
// request and wedge the provider shut.
releaseQuotaProbe(provider, quotaProbeClaimId);
releaseCmemGatewayProbe(gatewayProbeClaimId);
await handleGeneratorExit(session, reason, {
sessionManager: sessionManager,
completionHandler: completionHandler,
resumeGenerator: resumeSource => resumeGeneratorLater(session, 0, resumeSource, ensureGeneratorRunning),
});
// Paused work that nothing else is guaranteed to pick up resumes on its
// own — without it, a session's last event (a summarize) stays in RAM:
// - a cmem fallback (or a failed gateway re-probe) moves to the
// Anthropic plan at once;
// - a rate limit that named a Retry-After resumes after it, a bounded
// number of times in a row (the catch decided which);
// - a recycle reset its batch to pending and dropped the conversation.
// Quota and auth exits have already discarded their buffered work
// (handleGeneratorExit), so nothing of theirs resumes. A zero delay still defers a tick: `session.generatorPromise`
// is assigned after this chain is built, so resuming inline could be
// overwritten by that assignment and leave a settled promise blocking
// every later start.
if (scheduledResume) {
resumeGeneratorLater(session, scheduledResume.afterMs, scheduledResume.source, ensureGeneratorRunning);
}
if (reason === 'overflow:recycle') {
resumeGeneratorLater(session, 0, 'overflow-recycle', ensureGeneratorRunning);
}
// A queued batch answered with neither XML nor the skip sentinel gets its
// one more try now, in a fresh generation; ResponseProcessor bounds it to
// one retry per batch, so this cannot loop.
if (normalizedReason === 'output_retry') {
resumeGeneratorLater(session, 0, 'output-retry', ensureGeneratorRunning);
}
// A generation that kept drifting off the observation schema was ended
// after its batches were stored; buffered work continues in a fresh one.
if (normalizedReason === 'drift') {
resumeGeneratorLater(session, 0, 'schema-drift', ensureGeneratorRunning);
}
// A generator ended at a message boundary to change providers resumes
// on the provider dispatch selects now. A parked switch starts its own.
if (reason === PROVIDER_SWITCH_BOUNDARY_ABORT_REASON) {
resumeGeneratorLater(session, 0, 'provider-switch', ensureGeneratorRunning);
}
// A response stall preserved its claimed batch but, like a recycle, has
// no later ingest guaranteed to pick it up. Resume after a delay, a
// bounded number of times in a row; an answered queued-work turn resets
// the count (#4066).
// The stalled prompt was a paid send of its batch (ClaudeProvider counts
// it): a batch whose budget is spent is parked rather than resumed, and
// only work behind it, if any, is.
const parkedOnStall = reason === 'transport:response_stall'
? sessionManager.parkBatchOnSpentPaidSendBudget?.(session) ?? []
: [];
const nothingLeftAfterParking = parkedOnStall.length > 0
&& sessionManager.getMessageBuffer().getPendingCount(session.sessionDbId) === 0;
if (reason === 'transport:response_stall' && !nothingLeftAfterParking) {
const { resume, attempts } = planResponseStallResume(session);
if (!resume) {
// The bounded resumes are spent. Holding the buffer for "the next
// captured event" stranded it until a worker restart whenever the
// content session had already ended (#5405), and a later timer or
// event replaying it would be the stale-backlog spend the observer
// lifecycle forbids. Discard it now and say how much went; the next
// captured event still starts fresh work. A newer generator that a
// captured event started while this exit was handled owns the
// buffer, so it is left alone.
const newerGeneratorRunning = session.generatorPromise != null && session.generatorPromise !== generatorPromise;
if (!newerGeneratorRunning) {
session.stallResumesExhaustedAt = Date.now();
const buffer = sessionManager.getMessageBuffer();
const pendingCount = buffer.getPendingCount(session.sessionDbId);
const parkedCount = buffer.getParkedMessages(session.sessionDbId).length;
const discarded = sessionManager.discardBufferedWork(session.sessionDbId);
logger.warn('SESSION', `Observer went unanswered ${attempts} times in a row — discarding its buffered work instead of resuming`, {
sessionId: session.sessionDbId,
consecutiveStalls: attempts,
maxResumes: MAX_CONSECUTIVE_STALL_RESUMES,
pendingCount,
parkedCount,
discarded,
});
}
} else {
// The delayed retry may hit a quota cooldown and return without
// starting a generator. Keep this pause eligible for the periodic
// sweep after the timer fires; ordinary transport pauses still
// require an explicit retry, and exhausted stalls keep their cap.
session.pausedReason = 'response_stall';
const resume = setTimeout(() => {
session.stallResumeTimer = undefined;
void ensureGeneratorRunning(session.sessionDbId, 'response-stall')
.catch(error => {
logger.error('SESSION', 'Failed to resume the observer after a response stall', {
sessionId: session.sessionDbId,
}, error instanceof Error ? error : new Error(String(error)));
});
}, RESPONSE_STALL_RESUME_DELAY_MS);
resume.unref?.();
session.stallResumeTimer = resume;
}
}
});
session.generatorPromise = generatorPromise;
}
/**
* The credential this Claude run spent (or had paused by the quota guard), so
* its breaker may hand the work to the other one (claudeQuotaStandIn). A
* quota-fallback run is never tagged: when it is refused too, both are spent.
*/
function primaryCredentialOf(session: ActiveSession, provider: SelectableProvider): ClaudeCredential | undefined {
return provider === 'claude' && !session.claudeAuthOverride ? session.observerAuth : undefined;
}
function providerQuotaRefusalReason(provider: SelectableProvider, session: ActiveSession): ObserverQuotaReason {
if (provider !== 'claude') return { kind: 'out_of_quota' };
const credential = session.claudeAuthOverride ?? session.observerAuth;
if (credential === 'api-key') return { kind: 'api_key_limit' };
return { kind: credential === 'subscription' ? 'used_up' : 'unknown' };
}
/**
* Book a classified provider failure once, with the provider's own detail
* (code, message, action, link, request id), so the session-start warning
* shows the same words as the log line. Returns when and why a paused session
* resumes on its own, or null when it waits for the next captured event (or
* the user).
*/
function bookClassifiedFailure(
session: ActiveSession,
provider: SelectableProvider,
error: ClassifiedProviderError,
): { afterMs: number; source: string } | null {
let resume: { afterMs: number; source: string } | null = null;
switch (error.kind) {
case 'quota_exhausted':
// A spent allowance: withhold requests for a cooldown, then let one
// through to re-probe, instead of one doomed request per event (#3634).
recordQuotaExhausted(provider, error.message, undefined, undefined, session.observerProfile, primaryCredentialOf(session, provider), providerQuotaRefusalReason(provider, session));
break;
case 'auth_invalid':
// A refused credential fails every request until the user acts; the
// cooldown stops one wasted request per captured event.
recordAuthCooldown(provider, error.message, session.observerProfile);
break;
case 'rate_limit': {
// Never a spent allowance: a limit that names a day or longer is
// classified quota_exhausted by the provider (Gemini's per-day quotaId,
// OpenRouter's free-models-per-day). The provider already retried in
// place, and when it said how long to wait (the gateway envelope always
// does; Gemini's body RetryInfo does), the session resumes after that —
// a bounded number of times in a row. With no Retry-After, or once the
// resumes run out, withhold requests behind the breaker instead of
// resuming into it; a 'rate_limit' window holds for the short throttle
// cooldown (resolveQuotaCooldownMs), not the quota one.
// On the cmem gateway the resume also draws on the unattended budget it
// shares with transport and fallback resumes; once that is spent, the
// breaker takes over here too.
// When the fallback (by default the Anthropic plan) can take the work,
// the limit already outlasted the provider's in-place retries: hold the
// provider for the throttle cooldown and move the work there now, rather
// than resuming into the same refusal.
if (routeAroundUnservableProvider(provider, error.message, 'rate_limit', session.observerProfile) !== null) {
resume = { afterMs: 0, source: 'provider-fallback' };
break;
}
const plan = error.retryAfterMs !== undefined ? planRateLimitResume(session) : null;
if (plan?.resume && error.retryAfterMs !== undefined
&& planUnattendedGatewayResume(session, 'rate-limit', canCmemGatewayServe(session.platformSource)).resume) {
resume = {
afterMs: Math.min(Math.max(error.retryAfterMs, 0), QUOTA_EXHAUSTED_RECHECK_COOLDOWN_MS),
source: 'rate-limit',
};
} else {
recordQuotaExhausted(provider, error.message, 'rate_limit', undefined, session.observerProfile, undefined, { kind: 'busy' });
}
break;
}
}
recordObserverFailure(provider, {
message: error.message,
kind: error.kind,
code: error.code,
action: error.action,
url: error.url,
requestId: error.requestId,
});
return resume;
}
/**
* Start the session's generator again after `delayMs`, as the next captured
* event would. The timer is kept on the session, so the periodic sweep
* leaves the session to it (a rate limit must not be retried before its
* Retry-After) and a generator that starts first cancels it.
*/
function resumeGeneratorLater(
session: ActiveSession,
delayMs: number,
source: string,
ensureGeneratorRunning: GeneratorRunnerDependencies['ensureGeneratorRunning'],
): void {
clearTimeout(session.scheduledResumeTimer);
const resume = setTimeout(() => {
session.scheduledResumeTimer = undefined;
void ensureGeneratorRunning(session.sessionDbId, source)
.catch(error => {
logger.error('SESSION', 'Failed to resume the observer', {
sessionId: session.sessionDbId,
source,
}, error instanceof Error ? error : new Error(String(error)));
});
}, delayMs);
resume.unref?.();
session.scheduledResumeTimer = resume;
}