From 431d7c898f4b613612d0c76471b07a333bd81099 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:24:23 +0100 Subject: [PATCH 01/27] OpenCode 2: custom headers only on API-key routes; cache diagnostics as on OpenCode 1 (shared in Core) --- CHANGELOG.md | 2 + docs/cache-diagnostics.md | 4 +- packages/core/src/cache-diagnostics.ts | 295 ++++++++++++++++++ packages/core/src/index.ts | 1 + packages/opencode/src/cache-diagnostics.ts | 295 ++---------------- packages/opencode/src/index.ts | 14 +- .../src/tests/opencode2-adapter.test.ts | 181 +++++++++++ packages/opencode/src/v2/adapter.ts | 79 ++++- packages/opencode/src/v2/setup.ts | 4 +- packages/opencode/src/v2/wire.ts | 90 +++++- 10 files changed, 654 insertions(+), 311 deletions(-) create mode 100644 packages/core/src/cache-diagnostics.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index d87965c62..6d6e83724 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ This repo is a CortexKit-maintained Anthropic auth monorepo for OpenCode and Pi. - Changing effort mid-conversation now preserves the prompt cache in OpenCode v1, OpenCode v2, and Pi for Claude Mythos 5.1 and 5.2, and for Claude Opus 5 and Haiku 5.5 when adaptive thinking is on. - Pi: changing thinking effort during a conversation now preserves the prompt cache on models that support per-message effort, including in conversations shortened by Magic Context. +- OpenCode 2 now keeps custom proxy headers off Claude sign-in requests, like OpenCode 1 and Pi, while still sending them on API-key routes. +- For conversation requests, OpenCode 2 now matches OpenCode 1: the first eligible request sends a null previous message ID, and cache results and beta lists appear in debug logs. ## 2.16.5 diff --git a/docs/cache-diagnostics.md b/docs/cache-diagnostics.md index 6ee4de983..3eb549182 100644 --- a/docs/cache-diagnostics.md +++ b/docs/cache-diagnostics.md @@ -2,7 +2,7 @@ ## Measure-only beta -The Anthropic API opt-in `cache-diagnosis-2026-04-07` (sent in the `anthropic-beta` header) asks for cache diagnostics; it does not change cache controls or routing. OpenCode captures the response's opaque top-level message ID and sends it as `diagnostics.previous_message_id` on the next request in that session. The first request sends `null`. +The Anthropic API opt-in `cache-diagnosis-2026-04-07` (sent in the `anthropic-beta` header) asks for cache diagnostics; it does not change cache controls or routing. OpenCode 1 and 2 capture the response's opaque top-level message ID and send it as `diagnostics.previous_message_id` on the next eligible request in that session. The first eligible request sends `null`. `MC-CACHE-DIAG ` records and the beta-list side channel are emitted only at debug level. Choose **Logging level** → `debug` in `/claude` → **Diagnostics**. An empty stream can mean no activity or a lower log level: compare it with an independent activity witness such as usage rows, billing or dumps before drawing conclusions. @@ -58,4 +58,4 @@ A short-gap `previous_message_not_found` reason is also captured as a canary whe When dumps are enabled, `.response.json` holds status and parsed response metadata without response content. Lane-start filenames include `-start-`; CacheKeep uses `-prewarm-cachekeep-`. Treat related request bodies as sensitive local data. See [dump handling](transports.md#diagnostics-and-dumps) and [the OpenCode history analyzer](cache.md#diagnostics-and-history-analysis) for retrospective estimates. -Implementation: [schema and record validation](../packages/opencode/src/cache-diagnostics.ts), [OpenCode emission](../packages/opencode/src/index.ts), and [wire opt-in](../packages/opencode/src/transform.ts). +Implementation: [schema and record validation](../packages/core/src/cache-diagnostics.ts), emission in [OpenCode 1](../packages/opencode/src/index.ts) and [OpenCode 2](../packages/opencode/src/v2/wire.ts), and [wire opt-in](../packages/opencode/src/transform.ts). diff --git a/packages/core/src/cache-diagnostics.ts b/packages/core/src/cache-diagnostics.ts new file mode 100644 index 000000000..9f1a16126 --- /dev/null +++ b/packages/core/src/cache-diagnostics.ts @@ -0,0 +1,295 @@ +import { computeXxhash64Hex } from './cch.ts' +import { setBounded } from './claude-code.ts' + +export const CACHE_DIAGNOSTICS_BETA = 'cache-diagnosis-2026-04-07' +export const CACHE_DIAGNOSTICS_LOG_PREFIX = 'MC-CACHE-DIAG ' +export const CACHE_DIAGNOSTICS_SESSION_LIMIT = 1_000 +export const CACHE_DIAGNOSTICS_SHORT_GAP_MS = 5 * 60_000 + +export type CacheDiagnosticsState = + | 'absent' + | 'server_null' + | 'pending' + | 'populated' + +export type CacheDiagnosticsSource = string + +export const CACHE_DIAGNOSTICS_SOURCE_SYNTHETIC = { + turn: false, + start: true, + prewarm_cachekeep: true, +} as const + +export const CACHE_DIAGNOSTICS_BETAS_LIMIT = 1_000 + +export type CacheDiagnosticsRecord = { + v: 2 + source: CacheDiagnosticsSource + account_id: string + synthetic: boolean + betas_hash: string + requested_model?: string + session_id: string + ts_ms_received: number + model: string + is_subagent: boolean + ttl_sent: '1h' | '5m' | null + cache_read: number + cache_creation: number + input_tokens: number + ephemeral_5m_tokens: number + ephemeral_1h_tokens: number + message_id: string + previous_message_id: string | null + diag_state: CacheDiagnosticsState + miss_reason?: string + cache_missed_input_tokens?: number +} + +export type CacheDiagnosticsRequestContext = { + sessionId: string + previousMessageId: string | null + previousMessageReceivedAt?: number + isSubagent: boolean + ttlSent: '1h' | '5m' | null +} + +type CapturedMessage = { messageId: string; receivedAt: number } + +export class CacheDiagnosticsTracker { + private readonly entries = new Map() + + previousFor(sessionId: string): CapturedMessage | null { + return this.entries.get(sessionId) ?? null + } + + capture(sessionId: string, messageId: string, receivedAt: number): void { + setBounded( + this.entries, + sessionId, + { messageId, receivedAt }, + CACHE_DIAGNOSTICS_SESSION_LIMIT, + ) + } + + forgetSession(sessionId: string): void { + this.entries.delete(sessionId) + } +} + +export class CacheDiagnosticsBetaTracker { + private readonly hashes = new Map() + + capture(hash: string, betas: string[]): string | null { + if (this.hashes.has(hash)) return null + setBounded(this.hashes, hash, true, CACHE_DIAGNOSTICS_BETAS_LIMIT) + return `MC-CACHE-DIAG-BETAS ${JSON.stringify({ + hash, + betas: [...betas].sort(), + })}` + } +} + +export async function getCacheDiagnosticsBetas(headers: Headers) { + const betas = (headers.get('anthropic-beta') ?? '') + .split(',') + .map((beta) => beta.trim()) + .filter(Boolean) + .sort() + return { + betas, + betasHash: await computeXxhash64Hex(betas.join(',')), + } +} + +export function applyCacheDiagnosticsOptIn( + body: Record, + previousMessageId: string | null, +): void { + body.diagnostics = { previous_message_id: previousMessageId } +} + +function isRecord(value: unknown): value is Record { + return value != null && typeof value === 'object' && !Array.isArray(value) +} + +function isBreakpoint(value: unknown): value is Record { + return isRecord(value) && value.type === 'ephemeral' +} + +function appendBreakpoint(value: unknown, output: Array<'1h' | '5m'>) { + if (!isBreakpoint(value)) return + output.push(value.ttl === '1h' ? '1h' : '5m') +} + +function appendArrayBreakpoints(value: unknown, output: Array<'1h' | '5m'>) { + if (!Array.isArray(value)) return + for (const entry of value) { + if (isRecord(entry)) appendBreakpoint(entry.cache_control, output) + } +} + +export function summarizeCacheTtl(body: unknown): '1h' | '5m' | null { + if (!isRecord(body)) return null + const breakpoints: Array<'1h' | '5m'> = [] + appendBreakpoint(body.cache_control, breakpoints) + appendArrayBreakpoints(body.system, breakpoints) + if (Array.isArray(body.messages)) { + for (const message of body.messages) { + if (isRecord(message)) + appendArrayBreakpoints(message.content, breakpoints) + } + } + return breakpoints.at(-1) ?? null +} + +function classifyDiagnostics(message: Record): { + state: CacheDiagnosticsState + missReason?: string + cacheMissedInputTokens?: number +} | null { + if (!Object.hasOwn(message, 'diagnostics')) return { state: 'absent' } + const diagnostics = message.diagnostics + if (diagnostics === null) return { state: 'server_null' } + if (!isRecord(diagnostics)) return null + if (!Object.hasOwn(diagnostics, 'cache_miss_reason')) return null + const reason = diagnostics.cache_miss_reason + if (reason === null) return { state: 'pending' } + if (!isRecord(reason) || typeof reason.type !== 'string' || !reason.type) + return null + const missed = reason.cache_missed_input_tokens + if (missed !== undefined && typeof missed !== 'number') return null + return { + state: 'populated', + missReason: reason.type, + cacheMissedInputTokens: missed, + } +} + +function numericUsage( + usage: Record, + key: string, +): number | null { + const value = usage[key] + return typeof value === 'number' && Number.isFinite(value) && value >= 0 + ? value + : null +} + +export function buildCacheDiagnosticsRecord(input: { + request: CacheDiagnosticsRequestContext + source: CacheDiagnosticsSource + accountId: string + synthetic: boolean + betasHash: string + requestedModel?: string + onWarning?: (message: string) => void + message: unknown + receivedAt: number +}): { + record?: CacheDiagnosticsRecord + messageId?: string + canary?: { messageId: string; previousMessageId: string } +} { + if ( + typeof input.source !== 'string' || + input.source.length === 0 || + typeof input.accountId !== 'string' || + input.accountId.length === 0 || + typeof input.synthetic !== 'boolean' || + typeof input.betasHash !== 'string' || + input.betasHash.length === 0 + ) + return {} + const expectedSynthetic = + CACHE_DIAGNOSTICS_SOURCE_SYNTHETIC[ + input.source as keyof typeof CACHE_DIAGNOSTICS_SOURCE_SYNTHETIC + ] + if ( + expectedSynthetic !== undefined && + expectedSynthetic !== input.synthetic + ) { + input.onWarning?.( + `cache diagnostics source/synthetic mismatch: source=${input.source} expected=${expectedSynthetic} actual=${input.synthetic}`, + ) + } + const receivedAt = Math.trunc(input.receivedAt) + if (!Number.isFinite(input.receivedAt) || receivedAt !== input.receivedAt) + return {} + if (!isRecord(input.message)) return {} + const messageId = input.message.id + const model = input.message.model + const usage = input.message.usage + if (typeof messageId !== 'string' || messageId.length === 0) return {} + if (typeof model !== 'string' || model.length === 0 || !isRecord(usage)) + return {} + const inputTokens = numericUsage(usage, 'input_tokens') + const cacheRead = numericUsage(usage, 'cache_read_input_tokens') + const cacheCreation = numericUsage(usage, 'cache_creation_input_tokens') + const cacheCreationDetails = usage.cache_creation + if ( + inputTokens === null || + cacheRead === null || + cacheCreation === null || + !isRecord(cacheCreationDetails) + ) + return {} + const ephemeral5m = numericUsage( + cacheCreationDetails, + 'ephemeral_5m_input_tokens', + ) + const ephemeral1h = numericUsage( + cacheCreationDetails, + 'ephemeral_1h_input_tokens', + ) + if (ephemeral5m === null || ephemeral1h === null) return {} + const diagnostics = classifyDiagnostics(input.message) + if (!diagnostics) return {} + + const record: CacheDiagnosticsRecord = { + v: 2, + source: input.source, + account_id: input.accountId, + synthetic: input.synthetic, + betas_hash: input.betasHash, + session_id: input.request.sessionId, + ts_ms_received: receivedAt, + model, + is_subagent: input.request.isSubagent, + ttl_sent: input.request.ttlSent, + cache_read: cacheRead, + cache_creation: cacheCreation, + input_tokens: inputTokens, + ephemeral_5m_tokens: ephemeral5m, + ephemeral_1h_tokens: ephemeral1h, + message_id: messageId, + previous_message_id: input.request.previousMessageId, + diag_state: diagnostics.state, + } + if (diagnostics.missReason !== undefined) + record.miss_reason = diagnostics.missReason + if (diagnostics.cacheMissedInputTokens !== undefined) + record.cache_missed_input_tokens = diagnostics.cacheMissedInputTokens + if (input.requestedModel !== undefined && input.requestedModel !== model) + record.requested_model = input.requestedModel + + const canary = + diagnostics.missReason === 'previous_message_not_found' && + input.request.previousMessageId !== null && + input.request.previousMessageReceivedAt !== undefined && + input.receivedAt - input.request.previousMessageReceivedAt < + CACHE_DIAGNOSTICS_SHORT_GAP_MS && + input.receivedAt >= input.request.previousMessageReceivedAt + ? { + messageId, + previousMessageId: input.request.previousMessageId, + } + : undefined + return { record, messageId, ...(canary ? { canary } : {}) } +} + +export function formatCacheDiagnosticsLogLine( + record: CacheDiagnosticsRecord, +): string { + return `${CACHE_DIAGNOSTICS_LOG_PREFIX}${JSON.stringify(record)}` +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index b42a83f4d..2db853513 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -37,6 +37,7 @@ export { export * from './accounts.ts' export * from './auth.ts' export * from './billing.ts' +export * from './cache-diagnostics.ts' export * from './cache1h.ts' export * from './cachekeep.ts' export * from './cachekeep-failure.ts' diff --git a/packages/opencode/src/cache-diagnostics.ts b/packages/opencode/src/cache-diagnostics.ts index c3be77fc4..5e465be30 100644 --- a/packages/opencode/src/cache-diagnostics.ts +++ b/packages/opencode/src/cache-diagnostics.ts @@ -1,94 +1,27 @@ import { hostRetryHeaders, - setBounded, stickyRetainRetryHeaders, stickyRetryAfterWithJitter, } from '@cortexkit/anthropic-auth-core' -export const CACHE_DIAGNOSTICS_BETA = 'cache-diagnosis-2026-04-07' -export const CACHE_DIAGNOSTICS_LOG_PREFIX = 'MC-CACHE-DIAG ' -export const CACHE_DIAGNOSTICS_SESSION_LIMIT = 1_000 -export const CACHE_DIAGNOSTICS_SHORT_GAP_MS = 5 * 60_000 - -export type CacheDiagnosticsState = - | 'absent' - | 'server_null' - | 'pending' - | 'populated' - -export type CacheDiagnosticsSource = string - -export const CACHE_DIAGNOSTICS_SOURCE_SYNTHETIC = { - turn: false, - start: true, - prewarm_cachekeep: true, -} as const - -export const CACHE_DIAGNOSTICS_BETAS_LIMIT = 1_000 - -export type CacheDiagnosticsRecord = { - v: 2 - source: CacheDiagnosticsSource - account_id: string - synthetic: boolean - betas_hash: string - requested_model?: string - session_id: string - ts_ms_received: number - model: string - is_subagent: boolean - ttl_sent: '1h' | '5m' | null - cache_read: number - cache_creation: number - input_tokens: number - ephemeral_5m_tokens: number - ephemeral_1h_tokens: number - message_id: string - previous_message_id: string | null - diag_state: CacheDiagnosticsState - miss_reason?: string - cache_missed_input_tokens?: number -} - -export type CacheDiagnosticsRequestContext = { - sessionId: string - previousMessageId: string | null - previousMessageReceivedAt?: number - isSubagent: boolean - ttlSent: '1h' | '5m' | null -} - -type CapturedMessage = { messageId: string; receivedAt: number } - -export class CacheDiagnosticsTracker { - private readonly entries = new Map() - - previousFor(sessionId: string): CapturedMessage | null { - return this.entries.get(sessionId) ?? null - } - - capture(sessionId: string, messageId: string, receivedAt: number): void { - setBounded( - this.entries, - sessionId, - { messageId, receivedAt }, - CACHE_DIAGNOSTICS_SESSION_LIMIT, - ) - } -} - -export class CacheDiagnosticsBetaTracker { - private readonly hashes = new Map() - - capture(hash: string, betas: string[]): string | null { - if (this.hashes.has(hash)) return null - setBounded(this.hashes, hash, true, CACHE_DIAGNOSTICS_BETAS_LIMIT) - return `MC-CACHE-DIAG-BETAS ${JSON.stringify({ - hash, - betas: [...betas].sort(), - })}` - } -} +export { + applyCacheDiagnosticsOptIn, + buildCacheDiagnosticsRecord, + CACHE_DIAGNOSTICS_BETA, + CACHE_DIAGNOSTICS_BETAS_LIMIT, + CACHE_DIAGNOSTICS_LOG_PREFIX, + CACHE_DIAGNOSTICS_SESSION_LIMIT, + CACHE_DIAGNOSTICS_SHORT_GAP_MS, + CACHE_DIAGNOSTICS_SOURCE_SYNTHETIC, + CacheDiagnosticsBetaTracker, + type CacheDiagnosticsRecord, + type CacheDiagnosticsRequestContext, + type CacheDiagnosticsSource, + type CacheDiagnosticsState, + CacheDiagnosticsTracker, + formatCacheDiagnosticsLogLine, + summarizeCacheTtl, +} from '@cortexkit/anthropic-auth-core' export function copyCacheDiagnosticsContext( contexts: WeakMap, @@ -140,195 +73,3 @@ export async function withStickyRetryAfter( copyCacheDiagnosticsContext(contexts, response, retriedResponse) return retriedResponse } - -export function applyCacheDiagnosticsOptIn( - body: Record, - previousMessageId: string | null, -): void { - body.diagnostics = { previous_message_id: previousMessageId } -} - -function isRecord(value: unknown): value is Record { - return value != null && typeof value === 'object' && !Array.isArray(value) -} - -function isBreakpoint(value: unknown): value is Record { - return isRecord(value) && value.type === 'ephemeral' -} - -function appendBreakpoint(value: unknown, output: Array<'1h' | '5m'>) { - if (!isBreakpoint(value)) return - output.push(value.ttl === '1h' ? '1h' : '5m') -} - -function appendArrayBreakpoints(value: unknown, output: Array<'1h' | '5m'>) { - if (!Array.isArray(value)) return - for (const entry of value) { - if (isRecord(entry)) appendBreakpoint(entry.cache_control, output) - } -} - -export function summarizeCacheTtl(body: unknown): '1h' | '5m' | null { - if (!isRecord(body)) return null - const breakpoints: Array<'1h' | '5m'> = [] - appendBreakpoint(body.cache_control, breakpoints) - appendArrayBreakpoints(body.system, breakpoints) - if (Array.isArray(body.messages)) { - for (const message of body.messages) { - if (isRecord(message)) - appendArrayBreakpoints(message.content, breakpoints) - } - } - return breakpoints.at(-1) ?? null -} - -function classifyDiagnostics(message: Record): { - state: CacheDiagnosticsState - missReason?: string - cacheMissedInputTokens?: number -} | null { - if (!Object.hasOwn(message, 'diagnostics')) return { state: 'absent' } - const diagnostics = message.diagnostics - if (diagnostics === null) return { state: 'server_null' } - if (!isRecord(diagnostics)) return null - if (!Object.hasOwn(diagnostics, 'cache_miss_reason')) return null - const reason = diagnostics.cache_miss_reason - if (reason === null) return { state: 'pending' } - if (!isRecord(reason) || typeof reason.type !== 'string' || !reason.type) - return null - const missed = reason.cache_missed_input_tokens - if (missed !== undefined && typeof missed !== 'number') return null - return { - state: 'populated', - missReason: reason.type, - cacheMissedInputTokens: missed, - } -} - -function numericUsage( - usage: Record, - key: string, -): number | null { - const value = usage[key] - return typeof value === 'number' && Number.isFinite(value) && value >= 0 - ? value - : null -} - -export function buildCacheDiagnosticsRecord(input: { - request: CacheDiagnosticsRequestContext - source: CacheDiagnosticsSource - accountId: string - synthetic: boolean - betasHash: string - requestedModel?: string - onWarning?: (message: string) => void - message: unknown - receivedAt: number -}): { - record?: CacheDiagnosticsRecord - messageId?: string - canary?: { messageId: string; previousMessageId: string } -} { - if ( - typeof input.source !== 'string' || - input.source.length === 0 || - typeof input.accountId !== 'string' || - input.accountId.length === 0 || - typeof input.synthetic !== 'boolean' || - typeof input.betasHash !== 'string' || - input.betasHash.length === 0 - ) - return {} - const expectedSynthetic = - CACHE_DIAGNOSTICS_SOURCE_SYNTHETIC[ - input.source as keyof typeof CACHE_DIAGNOSTICS_SOURCE_SYNTHETIC - ] - if ( - expectedSynthetic !== undefined && - expectedSynthetic !== input.synthetic - ) { - input.onWarning?.( - `cache diagnostics source/synthetic mismatch: source=${input.source} expected=${expectedSynthetic} actual=${input.synthetic}`, - ) - } - const receivedAt = Math.trunc(input.receivedAt) - if (!Number.isFinite(input.receivedAt) || receivedAt !== input.receivedAt) - return {} - if (!isRecord(input.message)) return {} - const messageId = input.message.id - const model = input.message.model - const usage = input.message.usage - if (typeof messageId !== 'string' || messageId.length === 0) return {} - if (typeof model !== 'string' || model.length === 0 || !isRecord(usage)) - return {} - const inputTokens = numericUsage(usage, 'input_tokens') - const cacheRead = numericUsage(usage, 'cache_read_input_tokens') - const cacheCreation = numericUsage(usage, 'cache_creation_input_tokens') - const cacheCreationDetails = usage.cache_creation - if ( - inputTokens === null || - cacheRead === null || - cacheCreation === null || - !isRecord(cacheCreationDetails) - ) - return {} - const ephemeral5m = numericUsage( - cacheCreationDetails, - 'ephemeral_5m_input_tokens', - ) - const ephemeral1h = numericUsage( - cacheCreationDetails, - 'ephemeral_1h_input_tokens', - ) - if (ephemeral5m === null || ephemeral1h === null) return {} - const diagnostics = classifyDiagnostics(input.message) - if (!diagnostics) return {} - - const record: CacheDiagnosticsRecord = { - v: 2, - source: input.source, - account_id: input.accountId, - synthetic: input.synthetic, - betas_hash: input.betasHash, - session_id: input.request.sessionId, - ts_ms_received: receivedAt, - model, - is_subagent: input.request.isSubagent, - ttl_sent: input.request.ttlSent, - cache_read: cacheRead, - cache_creation: cacheCreation, - input_tokens: inputTokens, - ephemeral_5m_tokens: ephemeral5m, - ephemeral_1h_tokens: ephemeral1h, - message_id: messageId, - previous_message_id: input.request.previousMessageId, - diag_state: diagnostics.state, - } - if (diagnostics.missReason !== undefined) - record.miss_reason = diagnostics.missReason - if (diagnostics.cacheMissedInputTokens !== undefined) - record.cache_missed_input_tokens = diagnostics.cacheMissedInputTokens - if (input.requestedModel !== undefined && input.requestedModel !== model) - record.requested_model = input.requestedModel - - const canary = - diagnostics.missReason === 'previous_message_not_found' && - input.request.previousMessageId !== null && - input.request.previousMessageReceivedAt !== undefined && - input.receivedAt - input.request.previousMessageReceivedAt < - CACHE_DIAGNOSTICS_SHORT_GAP_MS && - input.receivedAt >= input.request.previousMessageReceivedAt - ? { - messageId, - previousMessageId: input.request.previousMessageId, - } - : undefined - return { record, messageId, ...(canary ? { canary } : {}) } -} - -export function formatCacheDiagnosticsLogLine( - record: CacheDiagnosticsRecord, -): string { - return `${CACHE_DIAGNOSTICS_LOG_PREFIX}${JSON.stringify(record)}` -} diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index ef5537b5b..6790b46b4 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -49,7 +49,6 @@ import { claudeGatewayHeaderValues, claudeGatewayModelUrl, claudeGatewayStatusNotes, - computeXxhash64Hex, configuredAnthropicOAuthAccountCount, createDumpResponseObserver, createEmptyStorage, @@ -91,6 +90,7 @@ import { getAccountStoragePath, getCache1hMode, getCache1hPersistentMode, + getCacheDiagnosticsBetas, getCacheKeepRegistryDirectories, getCacheKeepWindow, getClaudeCodeIdentityForVerifiedAccount, @@ -3594,18 +3594,6 @@ const anthropicAuthPlugin = async ( } >() - async function getCacheDiagnosticsBetas(headers: Headers) { - const betas = (headers.get('anthropic-beta') ?? '') - .split(',') - .map((beta) => beta.trim()) - .filter(Boolean) - .sort() - return { - betas, - betasHash: await computeXxhash64Hex(betas.join(',')), - } - } - function observeCacheDiagnosticsMessage(input: { source: CacheDiagnosticsSource accountId: string diff --git a/packages/opencode/src/tests/opencode2-adapter.test.ts b/packages/opencode/src/tests/opencode2-adapter.test.ts index 6c9285150..d627ea429 100644 --- a/packages/opencode/src/tests/opencode2-adapter.test.ts +++ b/packages/opencode/src/tests/opencode2-adapter.test.ts @@ -495,6 +495,157 @@ function hostRequest( const sse = (event: string, data: unknown) => `event: ${event}\ndata: ${JSON.stringify(data)}\n\n` +function cacheDiagnosticsHost() { + const wire = createNativeWirePolicy() + const { source } = makeSource({ + requestOptions: (input) => + wire.requestOptions(input, { + policyStorage: {}, + } as core.NativeAccountSnapshot), + responseOptions: wire.responseOptions, + forgetSession: wire.forgetSession, + }) + const native = createNativeAnthropicAdapter({ source }) + return { native, host: new Host(native.adapter) } +} + +const diagnosticsMessage = (id: string) => ({ + id, + type: 'message', + model: 'claude-sonnet-5', + content: [{ type: 'text', text: 'Do not include this reply in diagnostics' }], + usage: { + input_tokens: 20, + cache_read_input_tokens: 4, + cache_creation_input_tokens: 8, + cache_creation: { + ephemeral_5m_input_tokens: 8, + ephemeral_1h_input_tokens: 0, + }, + }, + diagnostics: null, +}) + +test('OpenCode 2 sends null first, then the previous Claude response ID in cache diagnostics', async () => { + const { native, host } = cacheDiagnosticsHost() + const scope = scopeOf({ sessionID: 'ses_diagnostics_chain' }) + const send = (stream: boolean) => + host.run(scope, hostRequest({ ...sonnetPayload(), stream })) + const observe = async ( + { attempt, final }: Awaited>, + response: Response, + ) => { + await ( + await native.adapter.rewriteResponse?.({ + ...attempt, + attempt, + request: final, + response, + }) + )?.text() + } + try { + const first = await send(true) + expect(first.final.headers.get('anthropic-beta')?.split(',')).toContain( + 'cache-diagnosis-2026-04-07', + ) + expect((await bodyOf(first.final)).diagnostics).toEqual({ + previous_message_id: null, + }) + await observe( + first, + new Response( + sse('message_start', { + type: 'message_start', + message: diagnosticsMessage('msg_sse'), + }) + sse('message_stop', { type: 'message_stop' }), + ), + ) + const second = await send(false) + expect((await bodyOf(second.final)).diagnostics).toEqual({ + previous_message_id: 'msg_sse', + }) + await observe(second, Response.json(diagnosticsMessage('msg_json'))) + const third = await send(true) + expect((await bodyOf(third.final)).diagnostics).toEqual({ + previous_message_id: 'msg_json', + }) + native.forgetSession(scope.sessionID) + expect((await bodyOf((await send(true)).final)).diagnostics).toEqual({ + previous_message_id: null, + }) + } finally { + native.dispose() + } +}) + +test('OpenCode 2 logs cache diagnostics at debug level and one beta list per sent hash', async () => { + const { native, host } = cacheDiagnosticsHost() + const debug = spyOn(core.logger, 'debug').mockImplementation(() => {}) + const scope = scopeOf({ sessionID: 'ses_diagnostics_logs' }) + try { + let expectedBetas: string[] = [] + for (const id of ['msg_first', 'msg_second']) { + const { attempt, final } = await host.run( + scope, + hostRequest({ ...sonnetPayload(), stream: false }), + ) + const sentBetas = final.headers.get('anthropic-beta')?.split(',').sort() + if (!sentBetas) throw new Error('Missing sent betas') + if (id === 'msg_first') expectedBetas = sentBetas + else expect(sentBetas).toEqual(expectedBetas) + await ( + await native.adapter.rewriteResponse?.({ + ...attempt, + attempt, + request: final, + response: Response.json(diagnosticsMessage(id)), + }) + )?.text() + } + const lines = debug.mock.calls + .filter(([channel]) => channel === 'cache-diagnostics') + .map(([, message]) => message) + const prefix = 'MC-CACHE-DIAG ' + const betaPrefix = 'MC-CACHE-DIAG-BETAS ' + const records = lines + .filter((line) => line.startsWith(prefix)) + .map((line) => JSON.parse(line.slice(prefix.length))) + const hash = Bun.hash + .xxHash64(expectedBetas.join(',')) + .toString(16) + .padStart(16, '0') + expect(records).toEqual( + ['msg_first', 'msg_second'].map((id, index) => ({ + v: 2, + source: 'turn', + account_id: 'acct-local', + synthetic: false, + betas_hash: hash, + session_id: scope.sessionID, + ts_ms_received: expect.any(Number), + model: scope.modelID, + is_subagent: false, + ttl_sent: '1h', + cache_read: 4, + cache_creation: 8, + input_tokens: 20, + ephemeral_5m_tokens: 8, + ephemeral_1h_tokens: 0, + message_id: id, + previous_message_id: index === 0 ? null : 'msg_first', + diag_state: 'server_null', + })), + ) + expect(lines.filter((line) => line.startsWith(betaPrefix))).toEqual([ + `${betaPrefix}${JSON.stringify({ hash, betas: expectedBetas })}`, + ]) + } finally { + debug.mockRestore() + native.dispose() + } +}) + const PREFIXED_STREAM = [ sse('message_start', { type: 'message_start', @@ -1245,6 +1396,36 @@ describe('OpenCode 2 native Anthropic adapter: request shape', () => { }, ) + test('OpenCode 2 applies custom proxy headers to API keys but not Claude sign-in', async () => { + const { source } = makeSource({ + authorize: (scope) => + scope.sessionID === 'ses_paid' + ? apiKey('sk-ant-api03-row-key', { custody: 'api', receipt: 'api' }) + : oauth('sk-ant-oat01-local-token', { + custody: 'local', + receipt: 'local', + }), + }) + const native = createNativeAnthropicAdapter({ source }) + const host = new Host(native.adapter) + const previous = process.env.ANTHROPIC_CUSTOM_HEADERS + try { + process.env.ANTHROPIC_CUSTOM_HEADERS = 'x-proxy-metadata: configured' + const paid = await host.run( + scopeOf({ sessionID: 'ses_paid' }), + hostRequest(sonnetPayload()), + ) + const signedIn = await host.run(scopeOf(), hostRequest(sonnetPayload())) + expect(paid.final.headers.get('x-proxy-metadata')).toBe('configured') + expect(signedIn.final.headers.get('x-proxy-metadata')).toBeNull() + expect(signedIn.final.headers.get('x-host-trace')).toBe('trace-7') + } finally { + if (previous === undefined) delete process.env.ANTHROPIC_CUSTOM_HEADERS + else process.env.ANTHROPIC_CUSTOM_HEADERS = previous + native.dispose() + } + }) + test('API route gains no OAuth persona, prefix, betas or signature', async () => { const { source, seen } = makeSource({ authorize: () => diff --git a/packages/opencode/src/v2/adapter.ts b/packages/opencode/src/v2/adapter.ts index 5af677b42..3fc054589 100644 --- a/packages/opencode/src/v2/adapter.ts +++ b/packages/opencode/src/v2/adapter.ts @@ -14,6 +14,8 @@ import { applyRunnerTurnNotes, assertHostAuthorityStable, assertNotCustodyTombstone, + CACHE_DIAGNOSTICS_BETA, + type CacheDiagnosticsRequestContext, type CacheKeepRealTurn, type ClaudeCodeIdentity, type ClaudeGateway, @@ -30,6 +32,7 @@ import { dumpRelayRequest, dumpResponseArtifact, encodeGzipRequestBody, + getCacheDiagnosticsBetas, getRequestGzipLatch, getRequestGzipLatchPath, guardAnthropicStreamResponse, @@ -62,6 +65,7 @@ import { stateRefusalCause, stateRefusalPublicMessage, stripEmptyTrailingAssistantMessages, + summarizeCacheTtl, TrailingAssistantHistoryError, } from '@cortexkit/anthropic-auth-core' import type { @@ -276,7 +280,9 @@ export type NativeAnthropicBodyOptions = Omit< | 'isOAuth' | 'onToolNameMap' | 'deferSigning' -> +> & { + readonly cacheDiagnosticsPreviousMessageReceivedAt?: number +} type StrippedStreamOptions = NonNullable< Parameters[1] @@ -320,8 +326,17 @@ export interface NativeAnthropicRequestContext

export interface NativeAnthropicResponseContext

extends NativeAnthropicAttemptContext

{ readonly status: number + readonly cacheDiagnostics?: CacheDiagnosticsSend } +type CacheDiagnosticsSend = Omit< + CacheDiagnosticsRequestContext, + 'sessionId' | 'isSubagent' +> & + Awaited> & { + requestedModel?: string + } + /** An `error` event inside a streamed response. */ export interface NativeAnthropicStreamErrorContext

extends NativeAnthropicAttemptContext

{ @@ -892,6 +907,10 @@ export function createNativeAnthropicAdapter( Data, NonNullable >() + const cacheDiagnosticsSends = new WeakMap< + Data, + Promise + >() // Each sent request privately holds its own credentials, so errors about // it can be scrubbed after rewriteSend has dropped the pending credential: // a response scope for the one response the request gets, and a redactor @@ -1299,12 +1318,18 @@ export function createNativeAnthropicAdapter( } const headers = new Headers(request.headers) - applyCustomHeaders(headers) + if (data.route === 'api') applyCustomHeaders(headers) const correlation = takeInternalHeaders(headers) let body = request.body === null ? undefined : await request.text() let threadCacheSlot: Parameters< typeof prepareMessageThreadRequest >[1]['cacheSlot'] + let diagnosticsOptIn: + | Pick< + CacheDiagnosticsRequestContext, + 'previousMessageId' | 'previousMessageReceivedAt' + > + | undefined // A session forgotten while the body was read never reaches the source's // options or the body rewrite. ensureLive() @@ -1370,7 +1395,8 @@ export function createNativeAnthropicAdapter( route: 'oauth', correlation, } - const options = (await source.requestOptions?.(context)) ?? {} + const { cacheDiagnosticsPreviousMessageReceivedAt, ...options } = + (await source.requestOptions?.(context)) ?? {} // Recheck session revocation after awaiting policy options. A // cleared session must not enter body rewriting or signing. ensureLive() @@ -1378,7 +1404,14 @@ export function createNativeAnthropicAdapter( // re-signed for the prewarm. Rewriting it again would prefix the // tool names twice and add the system blocks again, so the prewarm // would miss the session's cache instead of reading it. - if (attempt.agent !== 'cachekeep') + if (attempt.agent !== 'cachekeep') { + if (options.cacheDiagnosticsPreviousMessageId !== undefined) { + diagnosticsOptIn = { + previousMessageId: options.cacheDiagnosticsPreviousMessageId, + previousMessageReceivedAt: + cacheDiagnosticsPreviousMessageReceivedAt, + } + } body = await rewriteRequestBody(body, { ...options, deferSigning: true, @@ -1391,6 +1424,7 @@ export function createNativeAnthropicAdapter( isOAuth: true, onToolNameMap: (map) => responseToolNameMaps.set(data, map), }) + } const parsed = parseJson(body) finalBody = isRecord(parsed) ? parsed : null } @@ -1848,6 +1882,35 @@ export function createNativeAnthropicAdapter( } if (data?.route !== 'oauth' || !messages || bodyText === undefined) return billingSend + if (diagnosticsOptIn) { + cacheDiagnosticsSends.delete(data) + const payload = parseJson(bodyText) + if ( + isRecord(payload) && + isRecord(payload.diagnostics) && + payload.diagnostics.previous_message_id === + diagnosticsOptIn.previousMessageId + ) { + const sent = { + ...diagnosticsOptIn, + requestedModel: + typeof payload.model === 'string' ? payload.model : undefined, + ttlSent: summarizeCacheTtl(payload), + } + // For a relay, these are the upstream headers inside the envelope, + // not the headers on the outer Request to the relay itself. + cacheDiagnosticsSends.set( + data, + getCacheDiagnosticsBetas(headers) + .then((betas) => + betas.betas.includes(CACHE_DIAGNOSTICS_BETA) + ? { ...sent, ...betas } + : undefined, + ) + .catch(() => undefined), + ) + } + } try { source.onFinalRequestPrepared?.({ attemptId: attempt.attemptId, @@ -2087,7 +2150,13 @@ export function createNativeAnthropicAdapter( : safe, ) } - const context = { ...contextOf(attempt, data), status: response.status } + const diagnostics = cacheDiagnosticsSends.get(data) + cacheDiagnosticsSends.delete(data) + const context = { + ...contextOf(attempt, data), + status: response.status, + ...(diagnostics ? { cacheDiagnostics: await diagnostics } : {}), + } const options = source.responseOptions?.(context) ?? {} const json = data ? modes.get(data) === 'http' diff --git a/packages/opencode/src/v2/setup.ts b/packages/opencode/src/v2/setup.ts index c10441b78..a0fc9f020 100644 --- a/packages/opencode/src/v2/setup.ts +++ b/packages/opencode/src/v2/setup.ts @@ -467,12 +467,14 @@ export async function setupAnthropicAuth( setDumpEnabled(isDumpPersistentlyEnabled(initial.policyStorage)) } catch {} let active = true - const wire = createNativeWirePolicy() const models = createNativeClaudeModelRules() let lifecycle: ReturnType | undefined let prime: ReturnType | undefined let cacheKeep: ReturnType | undefined const parents = new Map() + const wire = createNativeWirePolicy({ + isSubagent: (sessionID) => parents.get(sessionID)?.value, + }) const subagent = (sessionID: string): boolean | undefined => { const cached = parents.get(sessionID) if (cached) return cached.value diff --git a/packages/opencode/src/v2/wire.ts b/packages/opencode/src/v2/wire.ts index 8e980fe89..8329a57f1 100644 --- a/packages/opencode/src/v2/wire.ts +++ b/packages/opencode/src/v2/wire.ts @@ -1,4 +1,9 @@ import { + buildCacheDiagnosticsRecord, + CacheDiagnosticsBetaTracker, + CacheDiagnosticsTracker, + formatCacheDiagnosticsLogLine, + logger, type NativeAccountSnapshot, readThreeWayBoolean, remapModelId, @@ -37,11 +42,14 @@ function serverSideFallbackEnabled() { * chain per user turn with OpenCode's message IDs: one session spans many * turns, so a session ID alone cannot tell which turn a request serves. */ -export function createNativeWirePolicy() { +export function createNativeWirePolicy( + options: { isSubagent?: (sessionID: string) => boolean | undefined } = {}, +) { const billing = new BillingLineageTracker() const latest = new Map() const contexts = new Map() - const messageIDs = new Map() + const cacheDiagnostics = new CacheDiagnosticsTracker() + const cacheDiagnosticBetas = new CacheDiagnosticsBetaTracker() const laneStarts = new Set() const laneAttempts = new Set() const attemptSessions = new Map() @@ -130,7 +138,10 @@ export function createNativeWirePolicy() { } }, requestOptions( - input: NativeAnthropicRequestContext, + input: Pick< + NativeAnthropicRequestContext, + 'agent' | 'attemptId' | 'correlation' | 'sessionID' + >, snapshot: NativeAccountSnapshot, ) { const lineage = billing.resolveHeader( @@ -144,6 +155,7 @@ export function createNativeWirePolicy() { bound(attemptSessions) const laneStart = input.correlation[LANE_START_REQUEST_HEADER] === '1' if (laneStart) laneAttempts.add(input.attemptId) + const previous = cacheDiagnostics.previousFor(input.sessionID) return { cache1hEnabled: input.agent !== 'compaction' && @@ -173,13 +185,20 @@ export function createNativeWirePolicy() { previousRequestId: lineage.previousRequestId, } : undefined, - cacheDiagnosticsPreviousMessageId: messageIDs.get(input.sessionID), + cacheDiagnosticsPreviousMessageId: previous?.messageId ?? null, + cacheDiagnosticsPreviousMessageReceivedAt: previous?.receivedAt, } }, responseOptions( input: Pick< NativeAnthropicResponseContext, - 'attemptId' | 'modelID' | 'sessionID' | 'kind' + | 'accountId' + | 'attemptId' + | 'cacheDiagnostics' + | 'kind' + | 'modelID' + | 'sessionID' + | 'status' >, ) { const model = remapModelId(input.modelID) @@ -187,18 +206,63 @@ export function createNativeWirePolicy() { const canFallback = serverSideFallbackEnabled() && resolveClaudeModelCapabilities(model)?.serverSideFallback === true + const laneStart = laneAttempts.has(input.attemptId) + const sent = input.cacheDiagnostics + const observe = (message: Record) => { + if (!sent || attemptSessions.get(input.attemptId) !== input.sessionID) + return + const receivedAt = Date.now() + const { record, messageId, canary } = buildCacheDiagnosticsRecord({ + request: { + ...sent, + sessionId: input.sessionID, + isSubagent: options.isSubagent?.(input.sessionID) ?? false, + }, + source: laneStart ? 'start' : 'turn', + accountId: input.accountId, + synthetic: laneStart, + betasHash: sent.betasHash, + requestedModel: sent.requestedModel, + message, + receivedAt, + }) + if (!record || !messageId) { + logger.debug( + 'cache-diagnostics', + 'skipped invalid response envelope', + { + status: input.status, + }, + ) + return + } + logger.debug('cache-diagnostics', formatCacheDiagnosticsLogLine(record)) + const betaLine = cacheDiagnosticBetas.capture( + sent.betasHash, + sent.betas, + ) + if (betaLine) logger.debug('cache-diagnostics', betaLine) + if (canary) + logger.warn( + 'cache-diagnostics', + 'short-gap previous_message_not_found', + { + message_id: canary.messageId, + previous_message_id: canary.previousMessageId, + }, + ) + if (input.kind === 'primary') { + cacheDiagnostics.capture(input.sessionID, messageId, receivedAt) + } + } return { serverSideFallbackModel: model, onServerSideFallbackOutcome(outcome: ServerSideFallbackOutcome) { if (canFallback) logServedServerFallback(input.sessionID, outcome) }, - laneStart: laneAttempts.has(input.attemptId), - onMessageStart(message: Record) { - if (input.kind === 'primary' && typeof message.id === 'string') { - messageIDs.set(input.sessionID, message.id) - bound(messageIDs) - } - }, + laneStart, + onMessageStart: observe, + onMessageResponse: observe, onStreamEnd() { contexts.delete(input.attemptId) laneAttempts.delete(input.attemptId) @@ -215,7 +279,7 @@ export function createNativeWirePolicy() { forgetSession(sessionID: string) { billing.clearSession(sessionID) latest.delete(sessionID) - messageIDs.delete(sessionID) + cacheDiagnostics.forgetSession(sessionID) laneStarts.delete(sessionID) for (const [attempt, session] of attemptSessions) if (session === sessionID) { From 3480011dd4cbfa8746e107b8d1653f416c419616 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:26:36 +0100 Subject: [PATCH 02/27] OpenCode 2: subscription price zeroing and Prime at plugin start; OpenCode 1 Prime follows live setting changes --- CHANGELOG.md | 2 + docs/cache.md | 2 +- docs/commands.md | 2 +- docs/models.md | 2 +- packages/opencode/src/index.ts | 15 +- .../src/tests/opencode1-settings-menu.test.ts | 45 ++++- .../src/tests/opencode2-settings-read.test.ts | 162 +++++++++++++++++- packages/opencode/src/v2/models.ts | 73 +++++++- packages/opencode/src/v2/setup.ts | 16 +- 9 files changed, 291 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d6e83724..7ef45675e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ This repo is a CortexKit-maintained Anthropic auth monorepo for OpenCode and Pi. - Pi: changing thinking effort during a conversation now preserves the prompt cache on models that support per-message effort, including in conversations shortened by Magic Context. - OpenCode 2 now keeps custom proxy headers off Claude sign-in requests, like OpenCode 1 and Pi, while still sending them on API-key routes. - For conversation requests, OpenCode 2 now matches OpenCode 1: the first eligible request sends a null previous message ID, and cache results and beta lists appear in debug logs. +- OpenCode 2: Claude subscription models now show zero token prices by default, like OpenCode 1. You can opt out to display catalogue prices; API-key prices are unchanged. +- OpenCode 1 and 2: opt-in Prime can start a quota window without a first chat request, and enabling Prime in the settings file takes effect without restarting OpenCode. ## 2.16.5 diff --git a/docs/cache.md b/docs/cache.md index 3a5afc3f9..821878b22 100644 --- a/docs/cache.md +++ b/docs/cache.md @@ -47,7 +47,7 @@ When content-filter recovery switches a session to Opus 4.8 temporarily, the ori ## Prime and lane start -Prime is opt-in quota-window priming. The **Extras** group in OpenCode and Pi can enable or disable it and shows each account's next due time and last result. After a confirmed five-hour reset, Prime checks fresh quota and limits, then approximately one minute after reset can send a minimal `claude-haiku-4-5` request. Cross-process claims prevent duplicate priming for the same verified Claude account/reset, even when OpenCode and Pi (or two OpenCode installs) use separate account files. Accounts without a verified identity are deduplicated only within the same account storage. This is a real request, not a quota API trick or a guarantee of free usage. Prime is stateless: it creates neither a message thread nor a keep-warm target, and stops when the host shuts down. +Prime is opt-in quota-window priming. The **Extras** group in OpenCode and Pi can enable or disable it and shows each account's next due time and last result. In OpenCode 1 and 2, Prime runs without waiting for a chat request and picks up changes to `prime_enabled` in the shared settings file without a restart. After a confirmed five-hour reset, Prime checks fresh quota and limits, then approximately one minute after reset can send a minimal `claude-haiku-4-5` request. Cross-process claims prevent duplicate priming for the same verified Claude account/reset, even when OpenCode and Pi (or two OpenCode installs) use separate account files. Accounts without a verified identity are deduplicated only within the same account storage. This is a real request, not a quota API trick or a guarantee of free usage. Prime does not create a message thread or register a cache for keepalive. It stops when the host shuts down. OpenCode's **Fire lane start** is an explicit one-shot action. It inserts a visible synthetic lane-start marker and runs a one-token request through normal routing, custody, limits, cache shaping and transport. It is also billed usage; it neither enables Prime nor installs an automatic schedule. Pi does not expose lane start. diff --git a/docs/commands.md b/docs/commands.md index 9390742b5..5cc385d53 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -16,7 +16,7 @@ Both hosts register one `/claude` command. It opens a menu whose actions collect In local custody, Accounts offers local management and enrollment reset, not disconnect. While enrolled, only enable/disable, reset backoff and disconnect remain. Unreadable enrollment keeps that reduced set so disconnect is available. **Custody setup guidance** explains the stopped-host requirement without changing custody. -Remove, reset-enrollment and disconnect actions require confirmation. Sign-in, API-key additions, guidance and disconnect require an interactive session. In the OpenCode TUI the command opens a dialog; Desktop/headless OpenCode posts a text summary, and Pi without a UI prints status sections only. +Remove, reset-enrollment and disconnect actions require confirmation. Sign-in, API-key additions, guidance and disconnect require an interactive session. In OpenCode's terminal UI the command opens a dialog. Without the terminal UI, OpenCode 1 posts a text summary and OpenCode 2 does not. Pi without a UI prints status sections only. ## OpenCode CLI diff --git a/docs/models.md b/docs/models.md index 8f3505c76..8b71d5116 100644 --- a/docs/models.md +++ b/docs/models.md @@ -27,7 +27,7 @@ Standard input/output rates are $0.10/$0.50 per million tokens. Above 100K total | Five-minute cache write | $0.125 | $0.625 | | One-hour cache write | $0.20 | $1.00 | -OpenCode's OAuth model costs are zeroed by default because subscription use is quota-based. `costZeroing.enabled: false` retains model pricing for display; it does not turn OpenCode's dollar accounting into route-aware billing when a paid fallback serves a request. Pi's catalog includes a higher Haiku pricing tier above 100K input tokens, counting cached input toward that threshold; its displayed costs remain estimates, not billing receipts. +OpenCode 1 and 2 show zero model prices by default when signed in with OAuth because subscription use is quota-based. API-key prices are unchanged. Set `cost_zeroing_enabled: false` in the shared settings file (or `costZeroing.enabled: false` in a legacy account file) to show catalogue prices. This does not make OpenCode's dollar accounting route-aware when a paid fallback serves a request. Pi's catalog includes a higher Haiku pricing tier above 100K input tokens, counting cached input toward that threshold; its displayed costs remain estimates, not billing receipts. ## Adaptive thinking and effort diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index 6790b46b4..9fc54d1a8 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -4643,9 +4643,8 @@ const anthropicAuthPlugin = async ( }, ) const primeManager: PrimeManager = primeManagerAdoption.manager - if (isPrimePersistentlyEnabled(initialStorage)) { - primeManager.start() - } + // Each tick checks the saved setting, so file edits can enable Prime live. + primeManager.start() async function getAllTrackedCacheKeepSessions() { aggregateCacheKeepSessions = await cacheKeepRegistry.list( @@ -5681,17 +5680,11 @@ const anthropicAuthPlugin = async ( if (action.type === 'enable') { enabled = true await setPrimePersistentEnabled(true, accountStoragePath) - if (!previous) { - primeManager.start() - logger.info('commands', 'prime changed', { enabled: true }) - } + if (!previous) logger.info('commands', 'prime changed', { enabled: true }) } else if (action.type === 'disable') { enabled = false await setPrimePersistentEnabled(false, accountStoragePath) - if (previous) { - primeManager.stop() - logger.info('commands', 'prime changed', { enabled: false }) - } + if (previous) logger.info('commands', 'prime changed', { enabled: false }) } // After toggling quota priming, update its sidebar status immediately. diff --git a/packages/opencode/src/tests/opencode1-settings-menu.test.ts b/packages/opencode/src/tests/opencode1-settings-menu.test.ts index 46e48c673..a9a685b73 100644 --- a/packages/opencode/src/tests/opencode1-settings-menu.test.ts +++ b/packages/opencode/src/tests/opencode1-settings-menu.test.ts @@ -8,6 +8,7 @@ import { } from '@cortexkit/common-auth/settings' import { parse } from 'jsonc-parser' import * as commands from '../native-command' +import { getPluginTestHandles } from './plugin-test-handles' import { applyMenuAction, openClaudeMenu } from './support/opencode1-client' import { getPlugin, @@ -19,6 +20,7 @@ import { createOpencode1Test, createOpencode1TestContext, installOpencode1TestHooks, + type PluginRuntimeOverrides, } from './support/opencode1-test-context' const ctx = createOpencode1TestContext() @@ -39,6 +41,7 @@ async function fixture( failWrite?: boolean unavailableProtection?: boolean diagnostic?: core.SettingsMoveDiagnostic + runtimeOverrides?: PluginRuntimeOverrides } = {}, ) { await useTempAccountFile(ctx, { version: 1, accounts: [] }) @@ -86,8 +89,9 @@ async function fixture( quota: { enabled: false, failClosedOnUnknownQuota: false }, })) const originalStore = await readFile(pool.paths.config, 'utf8') + let service: core.SettingsService | undefined if (mode !== 'separate') { - const service = await core.openSettingsService({ + service = await core.openSettingsService({ file, host: 'opencode', // These menu tests are about a host that uses the file. @@ -149,7 +153,12 @@ async function fixture( acquisition.mockRestore() command.mockRestore() }) - const plugin = await getPlugin(ctx, undefined, pool.root) + const plugin = await getPlugin( + ctx, + undefined, + pool.root, + options.runtimeOverrides, + ) const payload = await openClaudeMenu(plugin, 'settings-menu') if (!runtime || !native) throw new Error('Missing native menu callbacks') const menu = native @@ -157,6 +166,7 @@ async function fixture( file, pool, runtime, + service, plugin, payload, originalStore, @@ -174,6 +184,37 @@ async function fixture( } } +test('OpenCode 1 picks up Prime enabled in the settings file without restarting', async () => { + const intervals = new Map() + const f = await fixture({ + source: '{"prime_enabled":false}', + runtimeOverrides: { + setInterval: ((_callback: () => void, delay: number) => { + const handle = { unref() {} } + intervals.set(handle, delay) + return handle + }) as unknown as typeof setInterval, + clearInterval: ((handle: object) => { + intervals.delete(handle) + }) as typeof clearInterval, + }, + }) + const { primeManager } = getPluginTestHandles(f.plugin) + const scheduled = () => + [...intervals].filter(([, delay]) => delay === core.PRIME_TICK_MS) + expect((await primeManager.options.loadStorage())?.prime?.enabled).toBe(false) + expect(scheduled()).toHaveLength(1) + + expect((await f.apply('prime-on')).ok).toBe(true) + expect((await f.apply('prime-off')).ok).toBe(true) + expect(scheduled()).toHaveLength(1) + + await writeFile(f.file, '{"prime_enabled":true}') + await f.service!.refresh() + expect((await primeManager.options.loadStorage())?.prime?.enabled).toBe(true) + expect(scheduled()).toHaveLength(1) +}) + const actions: { action: MenuRequest['action'] values?: unknown diff --git a/packages/opencode/src/tests/opencode2-settings-read.test.ts b/packages/opencode/src/tests/opencode2-settings-read.test.ts index b6a74b6b5..e03a866c9 100644 --- a/packages/opencode/src/tests/opencode2-settings-read.test.ts +++ b/packages/opencode/src/tests/opencode2-settings-read.test.ts @@ -10,6 +10,10 @@ import { parse } from 'jsonc-parser' import { nativeAccountSettings } from '../../../core/src/native-account-view' import { nativeQuotaCodec } from '../../../core/src/native-quota-codec' import { nativeVaultPaths } from '../../../core/src/native-vault-paths' +import { + CLAUDE_POOL_LOGIN_METHOD_ID, + CLAUDE_VAULT_ACTIVATION_METHOD_ID, +} from '../v2/activation' import { createNativeMenuCapabilities } from '../v2/menu' import * as reloadFactory from '../v2/reload' import { setupAnthropicAuth } from '../v2/setup' @@ -230,9 +234,13 @@ async function fixture( startupSpy.mockRestore() sourceSpy.mockRestore() }) - const start = async (onInstall?: () => void) => { + const start = async ( + onInstall?: () => void, + host?: Partial, + ) => { const hooks = new Map() - const dispose = await setupAnthropicAuth(context(onInstall, hooks), { + const ctx = { ...context(onInstall, hooks), ...host } + const dispose = await setupAnthropicAuth(ctx, { paths, vault: { env }, local: { resolveIdentity: legacyIdentity }, @@ -305,6 +313,156 @@ async function fixture( const legacyIdentity = async () => ({ accountUuid: '11111111-2222-4333-8444-555555555555' }) as never +test('OpenCode 2 shows zero prices only for active OAuth unless opted out', async () => { + const f = await fixture() + await put(f.target, {}) + type Connection = Awaited< + ReturnType + > + const initial = Promise.withResolvers() + let active = initial.promise + const registrations = new Map() + let transform: Parameters[0] | undefined + let publish: ((event: unknown) => void) | undefined + let reloaded = Promise.withResolvers() + const registration = { dispose: async () => {} } + const host = { + model: { + transform: async (apply: typeof transform) => { + transform = apply + return registration + }, + reload: async () => reloaded.resolve(), + }, + integration: { + transform: async ( + apply: Parameters[0], + ) => { + apply({ + method: { + list: () => [], + update: ({ method }: { method: { id: string; type: 'oauth' } }) => { + registrations.set(method.id, method.type) + }, + }, + } as never) + return registration + }, + connection: { active: () => active }, + }, + event: { + subscribe: ({ + signal, + types, + }: { + signal: AbortSignal + types?: string[] + }) => + types?.includes('credential.switched') + ? new ReadableStream({ + start(controller) { + publish = (event) => controller.enqueue(event) + signal.addEventListener('abort', () => controller.close(), { + once: true, + }) + }, + }) + : (async function* () {})(), + }, + } as unknown as Partial + await f.start(undefined, host) + + const listPrice = [ + { input: 1, output: 4, cache: { read: 0.2, write: 1.25 } }, + { + input: 2, + output: 8, + cache: { read: 0.4, write: 2.5 }, + tier: { type: 'context', size: 100_000 }, + }, + ] + const zeroPrice = [{ input: 0, output: 0, cache: { read: 0, write: 0 } }] + const price = () => { + // OpenCode runs each projection against the original catalogue, not the + // result of the previous projection. + const model = { + id: 'claude-haiku-5-5', + modelID: 'claude-haiku-5-5', + variants: [], + cost: structuredClone(listPrice), + } + transform!({ + list: () => [model], + update: ( + _provider: string, + _id: string, + update: (value: typeof model) => void, + ) => update(model), + } as never) + return model.cost + } + const connection = (id: string, method: 'oauth' | 'key' | undefined) => + ({ type: 'credential', id, label: id, method }) as Connection + const select = async (next: Connection, event?: unknown) => { + active = Promise.resolve(next) + reloaded = Promise.withResolvers() + publish!( + event ?? { + type: 'credential.switched', + data: { integrationID: 'anthropic' }, + }, + ) + await reloaded.promise + } + expect(price()).toEqual(listPrice) + expect(registrations.get(CLAUDE_POOL_LOGIN_METHOD_ID)).toBe('oauth') + expect(registrations.get(CLAUDE_VAULT_ACTIVATION_METHOD_ID)).toBe('oauth') + initial.resolve( + connection('pool', registrations.get(CLAUDE_POOL_LOGIN_METHOD_ID)), + ) + await Bun.sleep(0) + expect(price()).toEqual(zeroPrice) + + await select(connection('api-key', 'key')) + expect(price()).toEqual(listPrice) + await select( + connection('vault', registrations.get(CLAUDE_VAULT_ACTIVATION_METHOD_ID)), + ) + expect(price()).toEqual(zeroPrice) + await select({ type: 'env', name: 'ANTHROPIC_API_KEY' } as Connection, { + type: 'credential.updated', + data: {}, + }) + expect(price()).toEqual(listPrice) + + await select(connection('pool', 'oauth')) + reloaded = Promise.withResolvers() + await put(f.target, { cost_zeroing_enabled: false }) + await f.changed() + await reloaded.promise + expect(price()).toEqual(listPrice) +}) + +test('OpenCode 2 starts opted-in Prime before any model request', async () => { + const f = await fixture() + await put(f.target, { prime_enabled: true }) + const managers: core.PrimeManager[] = [] + const start = core.PrimeManager.prototype.start + const spy = spyOn(core.PrimeManager.prototype, 'start').mockImplementation( + function (this: core.PrimeManager) { + managers.push(this) + start.call(this) + }, + ) + cleanups.push(() => spy.mockRestore()) + + const plugin = await f.start() + expect(managers).toHaveLength(1) + expect((await managers[0]!.options.loadStorage())?.prime?.enabled).toBe(true) + await plugin.dispose() + expect(managers[0]!.isStopped()).toBe(true) +}) + async function seedLegacyRequest(f: Awaited>) { await f.store.add({ id: 'legacy', diff --git a/packages/opencode/src/v2/models.ts b/packages/opencode/src/v2/models.ts index 3c2cc68f7..d9af0352a 100644 --- a/packages/opencode/src/v2/models.ts +++ b/packages/opencode/src/v2/models.ts @@ -1,7 +1,10 @@ import { + type AccountStorage, CLAUDE_MODEL_CAPABILITIES, type ClaudeModelPricing, + isCostZeroingEnabled, resolveClaudeModelCapabilities, + type SettingsService, } from '@cortexkit/anthropic-auth-core' import type { Model, Plugin } from '@opencode/plugin' @@ -17,7 +20,12 @@ function effortVariants( })) } -function modelCost(pricing: ClaudeModelPricing): Model.Info['cost'][number] { +function modelCost( + pricing: Pick< + ClaudeModelPricing, + 'input' | 'output' | 'cacheRead' | 'cacheWrite5m' + >, +): Model.Info['cost'][number] { // OC2, like OC1, has one cache-write price; use the five-minute price. return { input: pricing.input, @@ -73,8 +81,60 @@ function nativeCatalogueModels(): Model.Info[] { } /** Supply missing catalogue rows and adaptive-thinking effort variants. */ -export function createNativeClaudeModelRules() { +export function createNativeClaudeModelRules( + readPricingSettings: () => Pick = () => ({}), +) { const ids = new Map() + let oauth = false + const zeroCosts = () => oauth && isCostZeroingEnabled(readPricingSettings()) + const watchPricing = ( + ctx: Pick, + settings?: Pick, + ) => { + const connection = ctx.integration.connection + if (!connection) return { dispose: async () => {} } + const abort = new AbortController() + let read = 0 + let lastZeroing = zeroCosts() + const reloadIfChanged = () => { + if (abort.signal.aborted) return + const zeroing = zeroCosts() + if (zeroing === lastZeroing) return + lastZeroing = zeroing + void ctx.model.reload().catch(() => {}) + } + const refresh = async () => { + const generation = ++read + // Only the connection kind is needed. Never resolve its secret. + const active = await connection.active('anthropic').catch(() => undefined) + if (abort.signal.aborted || generation !== read) return + oauth = active?.type === 'credential' && active.method === 'oauth' + reloadIfChanged() + } + const unwatch = settings?.watch(reloadIfChanged) + const events = (async () => { + try { + for await (const event of ctx.event.subscribe({ + types: ['credential.updated', 'credential.switched'], + signal: abort.signal, + })) { + // Older OpenCode versions publish credential.updated without an ID. + const id = event.data.integrationID + if (id === undefined || id === 'anthropic') void refresh() + } + } catch { + // The host closes the event stream on unload. + } + })() + void refresh() + return { + async dispose() { + abort.abort() + unwatch?.() + await events + }, + } + } const installProviderModels = (ctx: Pick) => ctx.provider.transform((editor) => { const provider = editor.get('anthropic') @@ -96,12 +156,18 @@ export function createNativeClaudeModelRules() { const install = (ctx: Pick) => ctx.model.transform((editor) => { ids.clear() + const zeroing = zeroCosts() for (const candidate of editor.list('anthropic')) { ids.set(String(candidate.id), String(candidate.modelID)) const efforts = resolveClaudeModelCapabilities(candidate.modelID) ?.efforts.variants - if (!efforts) continue + if (!efforts && !zeroing) continue editor.update('anthropic', String(candidate.id), (model) => { + if (zeroing) + model.cost = [ + modelCost({ input: 0, output: 0, cacheRead: 0, cacheWrite5m: 0 }), + ] + if (!efforts) return const retained = model.variants.filter( (variant) => !efforts.some((effort) => effort === String(variant.id)), @@ -113,6 +179,7 @@ export function createNativeClaudeModelRules() { return { install, installProviderModels, + watchPricing, modelId: (id: string) => ids.get(id) ?? id, } } diff --git a/packages/opencode/src/v2/setup.ts b/packages/opencode/src/v2/setup.ts index a0fc9f020..6c4c15dc3 100644 --- a/packages/opencode/src/v2/setup.ts +++ b/packages/opencode/src/v2/setup.ts @@ -3,6 +3,7 @@ import { assertUnmanagedInjectedPaths, authorize, connectVaultHost, + createEmptyStorage, createNativeAccountRuntime, createNativeUi, decideOpenCodeStateLayoutOnce, @@ -460,14 +461,18 @@ export async function setupAnthropicAuth( ) // Read the current custody mode's settings before starting background work. // As in OpenCode 1, an environment override wins over the saved log level. + let initialStorage = createEmptyStorage() try { const initial = await runtime.read() + initialStorage = initial.policyStorage if (!process.env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL) setLogLevel(getPersistedLogLevel(initial.policyStorage) ?? 'info') setDumpEnabled(isDumpPersistentlyEnabled(initial.policyStorage)) } catch {} let active = true - const models = createNativeClaudeModelRules() + const models = createNativeClaudeModelRules( + () => runtime.resolveSettings?.(initialStorage) ?? initialStorage, + ) let lifecycle: ReturnType | undefined let prime: ReturnType | undefined let cacheKeep: ReturnType | undefined @@ -551,12 +556,6 @@ export async function setupAnthropicAuth( resolveModelId: async (scope) => models.modelId(scope.modelID), onOwnedRequest: () => { lifecycle ??= startNativeAnthropicLifecycle(runtime, options.fetch) - prime ??= createNativePrime({ - runtime, - paths, - source, - fetch: options.fetch, - }) }, beginRealTurn: (input) => cacheKeep?.beginRealTurn(input), }) @@ -665,6 +664,9 @@ export async function setupAnthropicAuth( } const command = createNativeUi(ui) registrations.push(await registerNativeMenu(ctx, command, capabilities)) + registrations.push(models.watchPricing(ctx, settingsService)) + // Prime can open the next quota window even when no session is active. + prime = createNativePrime({ runtime, paths, source, fetch: options.fetch }) // Only a completed, explicit Claude-pool login selects the plugin's inert // OAuth connection. Startup never creates or replaces a host connection. requests.activate() From 06a33ed1127e6212b6abb524d94e6c8640a2a5f4 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:27:39 +0100 Subject: [PATCH 03/27] Pi: turn billing lineage and the hybrid 20-block bridge marker, as on OpenCode --- CHANGELOG.md | 2 + docs/cache.md | 2 +- docs/request-rewriting.md | 2 +- packages/pi/src/convert.ts | 98 ++++++++++-- packages/pi/src/index.ts | 8 +- packages/pi/src/stream.ts | 128 ++++++++++++---- packages/pi/src/tests/convert.test.ts | 56 +++++++ packages/pi/src/tests/scoped-stream.test.ts | 162 +++++++++++++++++++- 8 files changed, 409 insertions(+), 49 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ef45675e..2f8ce3ce8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,8 @@ This repo is a CortexKit-maintained Anthropic auth monorepo for OpenCode and Pi. - For conversation requests, OpenCode 2 now matches OpenCode 1: the first eligible request sends a null previous message ID, and cache results and beta lists appear in debug logs. - OpenCode 2: Claude subscription models now show zero token prices by default, like OpenCode 1. You can opt out to display catalogue prices; API-key prices are unchanged. - OpenCode 1 and 2: opt-in Prime can start a quota window without a first chat request, and enabling Prime in the settings file takes effect without restarting OpenCode. +- Pi now links Claude subscription requests to the same user turn across tool calls and retries, matching OpenCode 1 and 2. +- Pi's hybrid prompt cache now reuses an earlier conversation boundary after long replies or tool exchanges, matching OpenCode 1 and 2. ## 2.16.5 diff --git a/docs/cache.md b/docs/cache.md index 821878b22..0d64a7056 100644 --- a/docs/cache.md +++ b/docs/cache.md @@ -8,7 +8,7 @@ Use `/claude` → **Cache** to enable caching and choose `claudeCache.mode`: - `explicit`: use explicit prompt-cache placement. - `automatic`: use automatic cache behavior. -- `hybrid`: combine placement strategies; CacheKeep tracks hybrid-cache sessions. +- `hybrid`: combine placement strategies and let CacheKeep keep recently used sessions warm. After the fixed prompt prefix, OpenCode 1, OpenCode 2 and Pi move the system cache marker to the previous user or tool-result boundary when the latest boundary cannot reach it within Anthropic's 20-block cache lookback. Cache settings do not reduce the complete input that Anthropic receives through a relay. A relay can send smaller patches between your machine and its Worker, but Anthropic still receives the reconstructed full request. Cache hits, not those smaller uploads, determine server-side cache benefits. diff --git a/docs/request-rewriting.md b/docs/request-rewriting.md index 047fa9994..e4c1f31f7 100644 --- a/docs/request-rewriting.md +++ b/docs/request-rewriting.md @@ -17,7 +17,7 @@ The sanitizer is anchor-based: it removes paragraphs containing known OpenCode d Model-family normalization supplies [adaptive thinking and effort](models.md#adaptive-thinking-and-effort). Billing metadata uses the Claude Code identity string and version bundled with the plugin (currently 2.1.302). `cc_prompt_id` identifies the user turn across tool-loop requests, and `cc_prev_req` records the previous request in that lineage. With a prompt id, the block also carries `cc_turn_origin=human` and `cc_prompt_index`/`cc_turn_index`: the number of user prompts in the conversation, which a tool-result follow-up keeps. The prompt id is repeated in the `x-claude-code-prompt-id` header, and `x-claude-code-request-class` is `main`, or `auxiliary` for title, summary and quota-window (`prime`) requests. Large bodies to `api.anthropic.com` are [gzipped on the wire](transports.md#request-body-compression) as Claude Code 2.1.302 sends them. OpenCode 2 registers an Anthropic provider source with the host and uses the shared request transform, instead of OpenCode 1's auth-loader fetch wrapper. -Pi replaces the Anthropic provider implementation and converts its transcript, tools and system prompt to the same signed Claude-compatible request shape. When the converter recognizes Pi's standard documentation section, that paragraph is moved into a separate cached block before the first user's text. If the section layout is unrecognized, the prompt is moved as a whole rather than placing the documentation in top-level `system[]`, where Anthropic rejects it. Tool replay and origin-aware thinking-signature filtering preserve compatible Anthropic thinking and remove incompatible OpenAI reasoning signatures. +Pi replaces the Anthropic provider implementation and converts its transcript, tools and system prompt to the signed Claude-compatible request shape described above. Pi's ordinary subscription requests use the same billing lineage and turn indexes as OpenCode 1 and 2. Cache keep-warm requests, quota-window Prime requests and requests for a forked conversation stay outside the active turn's chain. When the converter recognizes Pi's standard documentation section, that paragraph is moved into a separate cached block before the first user's text. If the section layout is unrecognized, the prompt is moved as a whole rather than placing the documentation in top-level `system[]`, where Anthropic rejects it. Tool replay and origin-aware thinking-signature filtering preserve compatible Anthropic thinking and remove incompatible OpenAI reasoning signatures. API-key/proxy sends have a separate policy: proxy header/model overrides apply there, while OAuth-only fallback fields and persona betas are removed. These controls do not turn an API-key route into subscription OAuth. See [environment overrides](environment.md#api-endpoint-and-proxy-routes). diff --git a/packages/pi/src/convert.ts b/packages/pi/src/convert.ts index 63ef4e5c1..e39b37786 100644 --- a/packages/pi/src/convert.ts +++ b/packages/pi/src/convert.ts @@ -5,6 +5,7 @@ import { applyThinkingBindingControls, applyTurnEndNotes, assertNoMeaningfulTrailingAssistant, + type BillingLineageFields, buildBillingHeaderValue, type Cache1hMode, CLAUDE_CODE_ENTRYPOINT, @@ -17,6 +18,7 @@ import { CLAUDE_SONNET_5_ADAPTIVE_THINKING, ClaudeCodeFirstUserTextTracker, type ClaudeCodeIdentity, + countUserPrompts, isClaudeFableOrMythos5Model, isClaudeHaiku55Model, isClaudeOpus5Model, @@ -631,6 +633,60 @@ function applyForkCacheBridge( baseBlock.cache_control = { ...control } } +/** Find the previous boundary when the latest one's lookback cannot reach it. */ +function hybridLookbackBridge(messages: unknown[]) { + let position = 0 + let previous: + | { message: Record; index: number; end: number } + | undefined + let latest: typeof previous + for (const [index, value] of messages.entries()) { + if (!value || typeof value !== 'object') continue + const message = value as Record + const content = message.content + // A system note inserted after a reply uses string content and consumes + // one lookback block, though only user messages can be bridge anchors. + const blocks = Array.isArray(content) + ? content.length + : content == null + ? 0 + : 1 + position += blocks + if (message.role === 'user' && blocks > 0) { + previous = latest + latest = { message, index, end: position } + } + } + // OpenCode reserves the first two messages for its fixed prefix. It counts + // both boundary blocks when checking Anthropic's 20-block search window. + return previous && + previous.index > 1 && + latest && + latest.end - previous.end + 1 > 20 + ? previous.message + : undefined +} + +function applyHybridCacheBridge(body: AnthropicRequestBody) { + const system = body.system?.findLast((block) => block.cache_control) + if (!system) return + const bridge = hybridLookbackBridge(body.messages) + if (!bridge) return + if (typeof bridge.content === 'string') + bridge.content = [{ type: 'text', text: bridge.content }] + if (!Array.isArray(bridge.content)) return + const block = bridge.content.findLast( + (value) => + value && + typeof value === 'object' && + value.type !== 'thinking' && + value.type !== 'redacted_thinking', + ) + if (!block) return + block.cache_control = system.cache_control + delete system.cache_control +} + /** * Anthropic accepts at most four cache breakpoints per request. This provider * composes its own body and has already placed exactly four @@ -644,9 +700,8 @@ function applyForkCacheBridge( * rewrite path does (`applyAutomaticCache1h` / `applyHybridCache1h` both clear * every breakpoint first): * - `automatic`: the top-level control alone, at 1h. - * - `hybrid`: the four block breakpoints extended to 1h, no top-level control. - * That is the placement OpenCode's hybrid anchors reconstruct by hand and - * this converter emits natively. + * - `hybrid`: the four block breakpoints extended to 1h, with the system slot + * available for a lookback bridge on an ordinary request. * - `explicit`: the same four breakpoints, TTL only. */ function applyCacheMode( @@ -669,14 +724,24 @@ function applyCacheMode( }) } -/** Replace only the system cache marker, preserving the tool and message markers. */ +/** Let a full request after a thread reuse its last full-request cache boundary. */ export function piThreadCacheSlot( body: Record, ): Record | undefined { - if (body.cache_control || !Array.isArray(body.system)) return undefined - return body.system.findLast( - (block) => block && typeof block === 'object' && block.cache_control, - ) + if (body.cache_control) return undefined + const system = Array.isArray(body.system) + ? body.system.findLast( + (block) => block && typeof block === 'object' && block.cache_control, + ) + : undefined + if (system) return system + if (!Array.isArray(body.messages)) return undefined + const bridge = hybridLookbackBridge(body.messages) + return Array.isArray(bridge?.content) + ? bridge.content.findLast( + (block) => block && typeof block === 'object' && block.cache_control, + ) + : undefined } export async function buildAnthropicRequest( @@ -687,6 +752,7 @@ export async function buildAnthropicRequest( fastModeEnabled = false, identity?: ClaudeCodeIdentity, controls: { + billingLineage?: BillingLineageFields effortTransitions?: readonly PiEffortTransition[] forkBaseMessageCount?: number /** A fork's lower answer effort, applied to its question turn only. */ @@ -784,6 +850,12 @@ export async function buildAnthropicRequest( ? forkFirstUserText : firstUserTextTracker.resolve(options.sessionId, messages) : undefined, + identity && !forkHead && controls.billingLineage?.promptId + ? { + ...controls.billingLineage, + promptIndex: countUserPrompts(messages), + } + : undefined, ), }, { type: 'text', text: CLAUDE_CODE_IDENTITY }, @@ -921,11 +993,11 @@ export async function buildAnthropicRequest( }) addEphemeralCacheControl(body) const cachePolicy = readSessionCachePolicy(options?.sessionId, !!identity) - applyCacheMode( - body, - cachePolicy?.ttl !== undefined ? cachePolicy.ttl !== 'none' : cache.enabled, - cache.mode, - ) + const cacheEnabled = + cachePolicy?.ttl !== undefined ? cachePolicy.ttl !== 'none' : cache.enabled + applyCacheMode(body, cacheEnabled, cache.mode) + if (cacheEnabled && cache.mode === 'hybrid' && !forkHead && !forkBase) + applyHybridCacheBridge(body) if (identity) { applyThinkingBindingControls( body, diff --git a/packages/pi/src/index.ts b/packages/pi/src/index.ts index 50bd4a342..339533e45 100644 --- a/packages/pi/src/index.ts +++ b/packages/pi/src/index.ts @@ -52,6 +52,7 @@ import { clearPiStickyQuotaRetries, endPiPrimaryTurn, forgetPiMessageThread, + observePiUserPrompt, startPiCacheKeepSession, stopPiCacheKeep, streamCortexKitAnthropic, @@ -203,6 +204,11 @@ export default async function cortexKitPiAnthropicAuth( } } }) + pi.on('message_start', async (event, ctx) => { + if (event.message.role !== 'user') return + const sessionId = ctx.sessionManager.getSessionId() + if (sessionId) observePiUserPrompt(storagePath, sessionId) + }) pi.on('agent_settled', async (_event, ctx) => { const sessionId = ctx.sessionManager.getSessionId() endPiPrimaryTurn(storagePath, sessionId) @@ -211,7 +217,7 @@ export default async function cortexKitPiAnthropicAuth( pi.on('session_shutdown', async (_event, ctx) => { native.prime?.stop() const sessionId = ctx.sessionManager.getSessionId() - endPiPrimaryTurn(storagePath, sessionId) + endPiPrimaryTurn(storagePath, sessionId, true) if (sessionId) { clearPiStickyQuotaRetries(storagePath, sessionId) effortSessionManagers.delete(sessionId) diff --git a/packages/pi/src/stream.ts b/packages/pi/src/stream.ts index 307fd8fc6..0736c84ce 100644 --- a/packages/pi/src/stream.ts +++ b/packages/pi/src/stream.ts @@ -1,3 +1,4 @@ +import { randomUUID } from 'node:crypto' import { type AccountStorage, type AnthropicBillingRequest, @@ -58,6 +59,7 @@ import { isNativeTransientAccountError, isOAuthAccount, isPermanentRefreshError, + isValidAnthropicRequestId, isValidApiBaseURL, killswitchPassesPolicy, LEGACY_STATE_LAYOUT, @@ -179,8 +181,18 @@ const dumpResponseObservers = new WeakMap< Response, ReturnType >() -// Each session owns its lease; storage identifies which host may end it. -const primaryTurns = new Map() +// The active turn ends when the agent settles. The previous response ID is +// kept between turns in the same session, but cleared on session shutdown. +const primarySessions = new Map< + string, + { + storagePath: string + turn?: { promptId?: string } + previousRequestId?: string + sent: number + committed: number + } +>() export function beginPiPrimaryTurn( storagePath: string, @@ -188,22 +200,40 @@ export function beginPiPrimaryTurn( ): void { if (!sessionId) return piCacheKeep.realTurn(sessionId) - primaryTurns.delete(sessionId) - primaryTurns.set(sessionId, storagePath) - while (primaryTurns.size > 128) { - const oldest = primaryTurns.keys().next().value + const previous = primarySessions.get(sessionId) + const session = + previous?.storagePath === storagePath + ? previous + : { storagePath, sent: 0, committed: 0 } + // Pi fires turn_start for each tool iteration, not only for a human prompt. + session.turn ??= {} + primarySessions.delete(sessionId) + primarySessions.set(sessionId, session) + while (primarySessions.size > 128) { + const oldest = primarySessions.keys().next().value if (oldest === undefined) break - primaryTurns.delete(oldest) + primarySessions.delete(oldest) } } +export function observePiUserPrompt(storagePath: string, sessionId: string) { + const session = primarySessions.get(sessionId) + // A queued user message can start a new prompt before the agent settles. + if (session?.storagePath === storagePath && session.turn) session.turn = {} +} + export function endPiPrimaryTurn( storagePath: string, sessionId?: string, + closed = false, ): void { - if (sessionId && primaryTurns.get(sessionId) === storagePath) - primaryTurns.delete(sessionId) - if (sessionId) piCacheKeep.endTurn(sessionId) + if (!sessionId) return + const session = primarySessions.get(sessionId) + if (session?.storagePath === storagePath) { + if (closed) primarySessions.delete(sessionId) + else delete session.turn + } + piCacheKeep.endTurn(sessionId) } export function untrackPiCacheKeepTurn(sessionId?: string) { @@ -212,25 +242,23 @@ export function untrackPiCacheKeepTurn(sessionId?: string) { } catch {} } -function isPiPrimaryThreadRequest( +function piPrimarySession( storagePath: string, options: SimpleStreamOptions | undefined, origin: 'agent-loop' | 'direct' | undefined, -): boolean { +) { // SDK summaries disable caching; SDK cache warms request exactly one token. if ( origin !== 'agent-loop' || - options?.cacheRetention === 'none' || - options?.maxTokens === 1 - ) - return false - return Boolean( - options?.sessionId && - primaryTurns.get(options.sessionId) === storagePath && - typeof options.onPayload === 'function' && - typeof options.onResponse === 'function' && - typeof options.onProviderStreamEvent === 'function', + !options?.sessionId || + options.cacheRetention === 'none' || + options.maxTokens === 1 ) + return undefined + const session = primarySessions.get(options.sessionId) + return session?.storagePath === storagePath && session.turn + ? session + : undefined } export function forgetPiMessageThread( @@ -957,6 +985,41 @@ async function sendAnthropicRequestAttempt( const keep = deps.cacheKeep ?? cacheKeepManager const realSession = options.streamOptions?.sessionId const forkHead = piForkHeadSession(options.streamOptions) + const primary = + !options.prime && !options.apiAccount && !forkHead + ? piPrimarySession( + options.storagePath, + options.streamOptions, + options.requestOrigin, + ) + : undefined + const turn = primary?.turn + if (primary && turn) { + turn.promptId ??= randomUUID() + primary.sent += 1 + } + const lineage = + primary && turn?.promptId + ? { + promptId: turn.promptId, + previousRequestId: primary.previousRequestId, + sequence: primary.sent, + } + : undefined + const observeRequestId = (headers: Headers) => { + if ( + !lineage || + !primary || + !realSession || + primarySessions.get(realSession) !== primary || + lineage.sequence < primary.committed + ) + return + const id = headers.get('request-id') ?? headers.get('x-request-id') + if (!id || !isValidAnthropicRequestId(id)) return + primary.committed = lineage.sequence + primary.previousRequestId = id + } if (!options.prime && !forkHead && realSession) { if (options.apiAccount || !options.storagePath) { try { @@ -1031,6 +1094,7 @@ async function sendAnthropicRequestAttempt( identity, { deferSigning: true, + billingLineage: lineage, forkBaseMessageCount: forkBase?.messageCount, // API-key routes send no effort history, so no fork hint either. forkEffort: options.apiAccount @@ -1286,16 +1350,18 @@ async function sendAnthropicRequestAttempt( } let threadRequest: MessageThreadRequest | undefined if ( - !options.apiAccount && - !options.prime && - !forkHead && + primary && + primary === + piPrimarySession( + options.storagePath, + options.streamOptions, + options.requestOrigin, + ) && // Gateways may refuse the thread route: send full requests. !gateway && - isPiPrimaryThreadRequest( - options.storagePath, - options.streamOptions, - options.requestOrigin, - ) && + typeof options.streamOptions?.onPayload === 'function' && + typeof options.streamOptions.onResponse === 'function' && + typeof options.streamOptions.onProviderStreamEvent === 'function' && (!relayConfig || effectiveRelayTransport(relayConfig.transport, relayConfig.url) !== 'websocket') @@ -1557,6 +1623,7 @@ async function sendAnthropicRequestAttempt( // Some relay streams start before the provider answers. Report the // provider's actual status and headers, not that early placeholder. onResponseHeaders: (responseHeaders) => { + observeRequestId(responseHeaders) if (upstream) reportRoutingHeaders( upstream.attempt, @@ -1637,6 +1704,7 @@ async function sendAnthropicRequestAttempt( }) response = threadRequest.observe(response) } + if (lastTransport === 'direct') observeRequestId(response.headers) if (response.ok && lastTransport === 'relay' && relayAttempt) { if ( options.prime && diff --git a/packages/pi/src/tests/convert.test.ts b/packages/pi/src/tests/convert.test.ts index d4246b310..8558f24a3 100644 --- a/packages/pi/src/tests/convert.test.ts +++ b/packages/pi/src/tests/convert.test.ts @@ -1864,6 +1864,62 @@ describe('buildAnthropicRequest — cache breakpoint budget', () => { expect(newestUserBlocks[0]?.cache_control).toEqual(oneHourControl) }) + test('Pi hybrid replaces the system slot at the 20-block lookback with a tool-result bridge', async () => { + const build = async ( + blocks: number, + mode: 'hybrid' | 'explicit' = 'hybrid', + ) => + ( + await buildAnthropicRequest( + TEST_MODEL_ID, + { + messages: [ + userMsg('first prompt'), + toolCallMsg('call_1', 'read'), + toolResultMsg('call_1', 'earlier boundary'), + { + ...assistantMsg('response'), + content: Array.from({ length: blocks }, (_, index) => ({ + type: 'text' as const, + text: `response block ${index}`, + })), + }, + userMsg('latest prompt'), + ], + systemPrompt: PI_PROMPT, + tools: [{ name: 'read', description: 'Read', parameters: {} }], + }, + undefined, + { enabled: true, mode }, + ) + ).body + + const nearby = await build(18) + const distant = await build(19) + const explicit = await build(19, 'explicit') + const control = { type: 'ephemeral', ttl: '1h' } + const bridgeBlock = (body: typeof distant) => + (body.messages[2]?.content as Record[] | undefined)?.at( + -1, + ) + const bridge = bridgeBlock(distant) + expect(bridge).toMatchObject({ + type: 'tool_result', + cache_control: control, + }) + expect(piThreadCacheSlot(distant)).toBe(bridge) + expect(distant.system?.some((block) => block.cache_control)).toBe(false) + expect(distant.messages[0]).toEqual(nearby.messages[0]) + expect(distant.messages.at(-1)).toEqual(nearby.messages.at(-1)) + expect(distant.tools).toEqual(nearby.tools) + expect(countBreakpoints(distant)).toBe(4) + for (const body of [nearby, explicit]) { + expect(body.system?.at(-1)?.cache_control).toEqual(control) + expect(bridgeBlock(body)).not.toHaveProperty('cache_control') + expect(countBreakpoints(body)).toBe(4) + } + }) + test('leaves the full body for an image-bearing array user message unchanged', async () => { const firstUserText = 'earlier user message' const text = 'look at this' diff --git a/packages/pi/src/tests/scoped-stream.test.ts b/packages/pi/src/tests/scoped-stream.test.ts index dbeecaa3d..5f526affa 100644 --- a/packages/pi/src/tests/scoped-stream.test.ts +++ b/packages/pi/src/tests/scoped-stream.test.ts @@ -22,6 +22,7 @@ import { sessionCacheActivity, setLogLevel, signRequestBody, + stripBillingLineageFields, WORKER_SCRIPT, } from '@cortexkit/anthropic-auth-core' import { @@ -1523,6 +1524,158 @@ const success = () => 'event: message_start\ndata: {"type":"message_start","message":{"usage":{"input_tokens":1,"output_tokens":0}}}\n\nevent: message_delta\ndata: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}\n\nevent: message_stop\ndata: {"type":"message_stop"}\n\n', { headers: { 'content-type': 'text/event-stream' } }, ) + +test('Pi billing lineage follows the user turn across tool iterations and retries', async () => { + const f = await fixture() + const hooks = new Map unknown>() + await cortexKitPiAnthropicAuth( + { + registerCommand() {}, + registerProvider() {}, + on: (name: string, handler: (event: unknown, ctx: unknown) => unknown) => + hooks.set(name, handler), + } as unknown as ExtensionAPI, + { connectScoped: f.connect }, + ) + const sessionId = `pi-lineage-${f.path}` + const hookContext = { + hasUI: false, + sessionManager: { getSessionId: () => sessionId, getBranch: () => [] }, + } + const emit = (name: string, fields: Record = {}) => + hooks.get(name)?.({ type: name, ...fields }, hookContext) + deferCleanup(async () => { + await emit('session_shutdown') + }) + + const nextContext = forkContext(context) + const toolHistory: Context = { + ...context, + messages: [ + ...context.messages, + { + ...nextContext.messages.find( + (message): message is AssistantMessage => + message.role === 'assistant', + )!, + content: [ + { type: 'toolCall', id: 'call_read', name: 'read', arguments: {} }, + ], + stopReason: 'toolUse', + }, + { + role: 'toolResult', + toolCallId: 'call_read', + toolName: 'read', + content: [{ type: 'text', text: 'read result' }], + isError: false, + timestamp: 2, + }, + ], + } + const sent: { text: string; line: string; promptHeader: string | null }[] = [] + const send = async ( + requestContext: Context, + responseId: string, + { + status = 200, + origin = 'agent-loop' as 'agent-loop' | 'direct', + alternateHeader = false, + } = {}, + ) => { + const response = await __sendPiAnthropicRequestForTest( + { + model, + context: requestContext, + storagePath: f.path, + oauthAccountId: 'main', + requestOrigin: origin, + streamOptions: { sessionId }, + }, + { + native: f.native, + fetch: (async (_input: unknown, init?: RequestInit) => { + const text = + init?.body instanceof Uint8Array + ? gunzipSync(init.body).toString() + : String(init?.body) + sent.push({ + text, + line: JSON.parse(text).system[0].text, + promptHeader: new Headers(init?.headers).get( + 'x-claude-code-prompt-id', + ), + }) + return new Response(status === 200 ? success().body : '{}', { + status, + headers: { + 'content-type': + status === 200 ? 'text/event-stream' : 'application/json', + [alternateHeader ? 'x-request-id' : 'request-id']: responseId, + }, + }) + }) as typeof fetch, + }, + ) + expect(response.status).toBe(status) + await response.text() + } + + await emit('turn_start', { turnIndex: 0 }) + await emit('message_start', { message: context.messages[0] }) + await send(context, 'req_pi_lineage_first') + await emit('turn_start', { turnIndex: 1 }) + await send(toolHistory, 'req_pi_lineage_rejected', { status: 429 }) + await send(toolHistory, 'req_pi_lineage_tool', { alternateHeader: true }) + await send(context, 'req_pi_lineage_aux', { origin: 'direct' }) + await emit('turn_start', { turnIndex: 2 }) + await emit('message_start', { message: nextContext.messages.at(-1) }) + await send(nextContext, 'invalid-upstream-id') + await emit('agent_settled') + await emit('turn_start', { turnIndex: 0 }) + const lastContext: Context = { + ...nextContext, + messages: [ + ...nextContext.messages, + { role: 'user', content: 'Third user prompt', timestamp: 101 }, + ], + } + await send(lastContext, 'req_pi_lineage_next') + + const [first, rejected, retried, auxiliary, queued, next] = sent + const promptId = first?.promptHeader + expect(promptId).toMatch(/^[a-f0-9-]{36}$/) + for (const attempt of [first, rejected, retried]) { + expect(attempt?.promptHeader).toBe(promptId!) + expect(attempt?.line).toContain( + `cc_prompt_id=${promptId}; cc_turn_origin=human; cc_prompt_index=1; cc_turn_index=1;`, + ) + } + expect(first?.line).not.toContain('cc_prev_req=') + expect(rejected?.line).toContain('cc_prev_req=req_pi_lineage_first;') + expect(retried?.line).toContain('cc_prev_req=req_pi_lineage_rejected;') + expect(auxiliary?.promptHeader).toBeNull() + expect(auxiliary?.line).not.toMatch(/cc_(?:prev_req|prompt_id|turn_index)=/) + const prewarm = await buildCacheKeepPrewarmBody(retried!.text) + expect(prewarm.ok).toBe(true) + if (prewarm.ok) + expect(prewarm.bodyText).not.toMatch( + /cc_(?:prev_req|prompt_id|turn_index)=/, + ) + expect(queued?.promptHeader).toMatch(/^[a-f0-9-]{36}$/) + expect(queued?.promptHeader).not.toBe(promptId!) + expect(queued?.line).toContain('cc_prev_req=req_pi_lineage_tool;') + expect(queued?.line).toContain( + `cc_prompt_id=${queued?.promptHeader}; cc_turn_origin=human; cc_prompt_index=2; cc_turn_index=2;`, + ) + expect(next?.promptHeader).toMatch(/^[a-f0-9-]{36}$/) + expect(next?.promptHeader).not.toBe(queued?.promptHeader ?? null) + expect(next?.line).toContain('cc_prev_req=req_pi_lineage_tool;') + expect(next?.line).toContain( + `cc_prompt_id=${next?.promptHeader}; cc_turn_origin=human; cc_prompt_index=3; cc_turn_index=3;`, + ) +}) + const row = (id: string, accountId: string): ScopedInventoryRow => ({ id, accountId, @@ -4759,10 +4912,12 @@ for (const [transport, credentialSource] of [ expect(first.tools.at(-1)?.cache_control).toEqual(oneHourControl) expect(first.system.at(-1)?.cache_control).toEqual(oneHourControl) expect(JSON.stringify(second.tools)).toBe(JSON.stringify(first.tools)) - // The body signature (cch) changes when history is sliced. All other system - // bytes, including cache controls, must remain identical. + // The signature and lineage can change between user prompts. The fixed + // system bytes, including cache controls and the first-user version suffix, cannot. const systemBytes = (system: unknown) => - JSON.stringify(system).replace(/cch=[a-f0-9]{5}/g, 'cch=00000') + stripBillingLineageFields( + JSON.stringify(system).replace(/cch=[a-f0-9]{5}/g, 'cch=00000'), + ) expect(systemBytes(second.system)).toBe(systemBytes(first.system)) expect(second.system[0].text.match(/cc_version=[^;]+/)?.[0]).toBe( first.system[0].text.match(/cc_version=[^;]+/)?.[0], @@ -4786,6 +4941,7 @@ for (const [transport, credentialSource] of [ const prewarm = JSON.parse(warm.ok ? warm.bodyText : '{}') expect(prewarm.thread).toBeUndefined() expect(prewarm.messages).toHaveLength(3) + expect(prewarm.system?.[0]?.text).not.toContain('cc_prompt_id=') const replay = history.messages.find( (message) => message.role === 'assistant', ) From c3a7ad6532fda8560e069fd2c00737d0e46b222c Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:33:41 +0100 Subject: [PATCH 04/27] OpenCode 1 on Thalamus: shared routing in every mode, wait-start reports and per-send billing reports, as on OpenCode 2 --- CHANGELOG.md | 3 + packages/opencode/src/index.ts | 835 +++++++++++++----- packages/opencode/src/request-class.ts | 14 +- ...-and-cache-diagnostics.integration.test.ts | 37 +- .../src/tests/opencode1-routing-relay.test.ts | 195 +++- 5 files changed, 870 insertions(+), 214 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f8ce3ce8..1ca15d97f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,9 @@ This repo is a CortexKit-maintained Anthropic auth monorepo for OpenCode and Pi. - OpenCode 1 and 2: opt-in Prime can start a quota window without a first chat request, and enabling Prime in the settings file takes effect without restarting OpenCode. - Pi now links Claude subscription requests to the same user turn across tool calls and retries, matching OpenCode 1 and 2. - Pi's hybrid prompt cache now reuses an earlier conversation boundary after long replies or tool exchanges, matching OpenCode 1 and 2. +- OpenCode 1 on Thalamus now asks for the shared login choice in every routing mode and when switching logins on a retry, like OpenCode 2. +- OpenCode 1 on Thalamus now reports when a request starts waiting for routing or quota, like OpenCode 2; OpenCode still handles the wait. +- OpenCode 1 on Thalamus now reports which login paid for each Claude send and how many tokens it used, including relayed sends and keep-warm requests, like OpenCode 2. ## 2.16.5 diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index 9fc54d1a8..73fa81ff7 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -10,6 +10,7 @@ import { type AccountCommandStatusProjection, type AccountStorage, ANTHROPIC_OAUTH_ORIGIN_REFUSAL, + type AnthropicBillingRequest, type ApiKeyAccount, acquireNativeAccountRuntime, applyCustomHeaders, @@ -221,6 +222,7 @@ import { remapRequestBodyModel, reportSessionCacheTouch, requestCacheLifetimeMs, + requestShortestCacheLifetimeMs, resetClaustrumEnrollmentState, resetWaitDelayMs, resolveClaudeModelCapabilities, @@ -239,6 +241,7 @@ import { shouldFallbackStatus, signRequestBody, snapshotHasServableLocalOAuth, + startRoutingWait, startSettings, stateRefusalPublicMessage, stickyQuotaSnapshotIsFresh, @@ -251,6 +254,7 @@ import { waitForNativeUsageDrain, warnClaudeGatewayRelayIgnored, withAbortableFetch, + withAnthropicBilling, withSessionCacheReportHandoff, } from '@cortexkit/anthropic-auth-core' import type { Hooks, Plugin } from '@opencode-ai/plugin' @@ -322,8 +326,10 @@ import { RecoveryThinkingStore, } from './recovery-thinking.ts' import { + BILLING_REQUEST_KIND_HEADER, isAuxiliaryAgent, REQUEST_CLASS_REQUEST_HEADER, + takeBillingRequestKind, takeRequestClassHeader, } from './request-class.ts' import { @@ -1828,6 +1834,45 @@ const anthropicAuthPlugin = async ( localSource?: 'current' | 'validated' | 'rotated' | 'adopted' scopedAttempt?: NativeCustodyReceipt } + function hasSharedRouting() { + try { + return ( + typeof Reflect.get(globalThis, Symbol.for('cortexkit.routing')) === + 'function' + ) + } catch { + return false + } + } + function parseRequestModel(body: RequestInit['body'] | null | undefined) { + if (typeof body !== 'string') return undefined + try { + const parsed = JSON.parse(body) as { model?: unknown } + return typeof parsed.model === 'string' ? parsed.model : undefined + } catch { + return undefined + } + } + function modelBillingRequest( + sessionId: string | null | undefined, + body: RequestInit['body'], + payer: Pick, + requestKind: AnthropicBillingRequest['requestKind'], + chargeBasis: AnthropicBillingRequest['chargeBasis'], + ): AnthropicBillingRequest | undefined { + if (!sessionId || typeof body !== 'string' || !hasSharedRouting()) return + const model = parseRequestModel(body) + if (!model) return + const ttlMs = requestShortestCacheLifetimeMs(body) + return { + sessionId, + ...payer, + model, + requestKind, + chargeBasis, + ...(ttlMs > 0 && { cache: { ttlMs } }), + } + } function nativeWireIdentity(accountIdentity: string | undefined) { const accountUuid = asProviderAccountUuid(accountIdentity) if (!accountUuid) @@ -1902,7 +1947,11 @@ const anthropicAuthPlugin = async ( storage: AccountStorage, receipt?: NativeCustodyReceipt, ) => { - if (routingSessionId && routingRelay.admitted(routingSessionId, view)) + if ( + routingSessionId && + hasSharedRouting() && + routingRelay.admitted(routingSessionId, view) + ) return const quota = routingAccountQuota(view, storage, receipt) // Ordered routing can try main after eligible fallbacks are exhausted. @@ -3921,6 +3970,22 @@ const anthropicAuthPlugin = async ( // Prewarms carry an OAuth bearer: recheck the destination, no redirects. // A keep-warm is a model request, so it follows the current gateway. fetchImpl: fetchOAuthModel(() => nativeAccounts.getClaudeGateway?.()), + billingRequest: (target, attempt) => { + const payer = cacheKeepScopedAttempts.get(attempt.id) + if (!payer) return + const billing = modelBillingRequest( + target.policyState?.ownerSessionId ?? target.id, + target.bodyText, + { accountId: payer.accountIdentity, credentialId: payer.credentialId }, + 'keep_warm', + 'subscription_included', + ) + if (billing) + return { + ...billing, + cache: { ...billing.cache, warming: { on: true } }, + } + }, setIntervalImpl: runtimeTimers.setInterval, clearIntervalImpl: runtimeTimers.clearInterval, onTargetChanged: (target) => { @@ -6743,6 +6808,9 @@ const anthropicAuthPlugin = async ( ) => { if (isAuxiliaryAgent(agent)) output.headers[REQUEST_CLASS_REQUEST_HEADER] = 'auxiliary' + if (agent === 'title' || agent === 'compaction' || agent === 'summary') + output.headers[BILLING_REQUEST_KIND_HEADER] = + agent === 'title' ? 'title' : 'compaction' laneStartTracker.markHeaders({ sessionId: sessionID, messageId: message.id, @@ -7385,18 +7453,6 @@ const anthropicAuthPlugin = async ( return body == null || typeof body === 'string' } - function parseRequestModel( - body: RequestInit['body'] | null | undefined, - ) { - if (typeof body !== 'string') return undefined - try { - const parsed = JSON.parse(body) as { model?: unknown } - return typeof parsed.model === 'string' ? parsed.model : undefined - } catch { - return undefined - } - } - function isSubagentRequest(headers: Headers) { return headers.has('x-parent-session-id') } @@ -7677,6 +7733,7 @@ const anthropicAuthPlugin = async ( requestHeaders.delete(BILLING_LINEAGE_REQUEST_HEADER) // The API-key route sends no Claude Code headers; drop the marker. requestHeaders.delete(REQUEST_CLASS_REQUEST_HEADER) + const billingRequestKind = takeBillingRequestKind(requestHeaders) let body = await fetchBody(input, init) const wireSettings = requestWireSettings( currentStorage, @@ -7773,14 +7830,26 @@ const anthropicAuthPlugin = async ( ) let response: Response try { - // Redact the sent API key before response dumps, diagnostics or routing. - response = scope.redactResponse( - await fetch(rewritten.input, { + const billing = modelBillingRequest( + directAffinity, + body, + { + accountId: apiCredential.subject.binding.identity, + credentialId: apiCredential.subject.credentialFingerprint, + }, + billingRequestKind, + 'metered_api', + ) + const send = () => + fetch(rewritten.input, { ...init, body, headers: requestHeaders, ...(isInsecure() && { tls: { rejectUnauthorized: false } }), - }), + }) + // Redact the sent API key before response dumps, diagnostics or routing. + response = scope.redactResponse( + await (billing ? withAnthropicBilling(billing, send) : send()), ) } catch (caught) { const error = scope.redactError(caught) @@ -7937,6 +8006,7 @@ const anthropicAuthPlugin = async ( requestHeaders.delete(EFFORT_PLAN_REQUEST_HEADER) requestHeaders.delete(BILLING_LINEAGE_REQUEST_HEADER) const requestClass = takeRequestClassHeader(requestHeaders) + const billingRequestKind = takeBillingRequestKind(requestHeaders) let body = await fetchBody(input, init) const previousDiagnosticsMessage = relayAffinity ? cacheDiagnosticsTracker.previousFor(relayAffinity) @@ -8442,6 +8512,25 @@ const anthropicAuthPlugin = async ( let usedDirectFetch = false let directAttempt = scopedAttempt + const billingFor = (payer: NativeOAuthAuthorization) => { + const billing = modelBillingRequest( + relayAffinity, + body, + { + accountId: payer.accountIdentity, + credentialId: payer.credentialId, + }, + billingRequestKind, + 'subscription_included', + ) + if (billing) + return { + ...billing, + cacheWarming: () => + cacheKeepManager.warming(billing.sessionId), + } + } + const directFetch = async () => { usedDirectFetch = true // Validate current local credentials or obtain new vault @@ -8477,16 +8566,20 @@ const anthropicAuthPlugin = async ( const physicalSend = ( wireBody: RequestInit['body'], wireHeaders: Headers, - ) => + ) => { // fetchOAuthModel rechecks the destination, refuses // redirects and, with a gateway, sends there instead. The // ANTHROPIC_INSECURE opt-out applies to API-key routes only: // an OAuth send always checks certificates. - fetchOAuthModel(gateway)(rewritten.input, { - ...init, - body: wireBody, - headers: wireHeaders, - }) + const send = () => + fetchOAuthModel(gateway)(rewritten.input, { + ...init, + body: wireBody, + headers: wireHeaders, + }) + const billing = billingFor(nativeAuthorization) + return billing ? withAnthropicBilling(billing, send) : send() + } // Claude Code gzips large bodies on the wire. `body` stays the // signed uncompressed wire text for dumps and relay fallback. // CacheKeep retains the separate full stateless template. @@ -8670,6 +8763,7 @@ const anthropicAuthPlugin = async ( const acceptedBody = body return { headers: relayHeaders, + billing: billingFor(nextAuthorization), errorSecrets: [nextAuthorization.accessToken], onUpstreamStatus: (status: number) => { if ( @@ -9413,6 +9507,16 @@ const anthropicAuthPlugin = async ( } const responseRouteKinds = new WeakMap() + const orderedRouting = new WeakMap< + PerfTrace, + { + afterRefusal: ( + id: string, + response: Response, + ) => Promise + skipLocal: (id: string) => boolean + } + >() async function tryUsableFallbackAccounts( input: string | URL | Request, @@ -9434,6 +9538,7 @@ const anthropicAuthPlugin = async ( const returnLastOnExhausted = options?.returnLastOnExhausted ?? true let lastResponse: Response | null = currentResponse ?? null + const shared = trace && orderedRouting.get(trace) let canceledCurrentResponse = false const cancelCurrentResponse = async () => { if (canceledCurrentResponse) return @@ -9442,6 +9547,7 @@ const anthropicAuthPlugin = async ( } for (const [index, account] of accounts.entries()) { + if (shared?.skipLocal(account.id)) continue let response: Response if (isApiKeyAccount(account)) { await cancelCurrentResponse() @@ -9551,6 +9657,13 @@ const anthropicAuthPlugin = async ( } return response } + if (shared && isOAuthAccount(account)) { + const replacement = await shared.afterRefusal( + account.id, + response, + ) + if (replacement) return replacement + } if (index < accounts.length - 1 || !returnLastOnExhausted) { await response.body?.cancel().catch(() => {}) } @@ -9592,7 +9705,8 @@ const anthropicAuthPlugin = async ( (isApiKeyAccount(account) && isValidApiBaseURL(account.baseURL))), ) - if (!hasPotentialFallbackRoute) return mainResponse + const shared = trace && orderedRouting.get(trace) + if (!hasPotentialFallbackRoute && !shared) return mainResponse let currentResponse = mainResponse let shouldFallback = shouldFallbackResponse( @@ -9618,6 +9732,14 @@ const anthropicAuthPlugin = async ( if (!shouldFallback) { return currentResponse } + if (shared) { + const replacement = await shared.afterRefusal( + 'main', + currentResponse, + ) + if (replacement) return replacement + } + if (!hasPotentialFallbackRoute) return currentResponse let includeApiRoutes = false if (preselectedAccounts) { includeApiRoutes = preselectedAccounts.some(isApiKeyAccount) @@ -10051,6 +10173,7 @@ const anthropicAuthPlugin = async ( if (auth.type !== 'oauth') { const rewritten = rewriteUrl(input) const passthroughHeaders = mergeHeaders(input, init) + passthroughHeaders.delete(BILLING_REQUEST_KIND_HEADER) applyCustomHeaders(passthroughHeaders) let passthroughBody = await fetchBody(input, init) if (typeof passthroughBody === 'string') { @@ -10179,6 +10302,273 @@ const anthropicAuthPlugin = async ( currentMainObservation?.generalExhausted === true, ) : undefined + function reportHostWait( + response: Response, + reason: Parameters[0]['reason'], + ) { + if (hasSharedRouting() && response.status === 429) { + const delayMs = + resetWaitDelayMs(response) ?? + Number(response.headers.get('retry-after')) * 1000 + startRoutingWait({ + sessionId: sessionId ?? undefined, + reason, + delayMs, + nextMs: Date.now() + delayMs, + }) + } + return response + } + function routingHoldResponse(delayMs: number) { + return reportHostWait( + new Response( + JSON.stringify({ + type: 'error', + error: { + type: 'rate_limit_error', + message: + 'Shared routing requested a wait; retaining session affinity.', + }, + }), + { + status: 429, + headers: { + 'content-type': 'application/json', + 'retry-after': String(Math.ceil(delayMs / 1000)), + }, + }, + ), + 'routing_hold', + ) + } + const routingModelId = fablePlan?.effectiveModel ?? requestModelId + let countedRequest = false + function countSessionRequest() { + if (!replayableRequest || countedRequest) return + countedRequest = true + sessionRequestCount++ + if (auth.access && (!auth.expires || auth.expires > Date.now())) + scheduleSidebarMainQuotaRefresh( + storage, + auth.access, + requestMainQuotaIdentity, + ) + } + let sharedRoutingDecision = false + // OpenCode 1 ends a request that has no response after 5 minutes. + // The first ask may wait up to 4 minutes for a free account slot. + // An ask after a failed attempt has already spent part of that + // budget, so it doesn't wait in the request: a full pool becomes + // a host retry instead. + async function askSharedRouting( + routingSessionId: string, + maxInRequestMs = 240_000, + ) { + const snapshot = await nativeAccounts.read(routingModelId) + const routing = await currentStickyRouting() + const assignment = + await routing.router.readAssignment(routingSessionId) + init?.signal?.throwIfAborted() + const advice = await routingRelay.accountFor( + routingSessionId, + routingModelId ?? '', + routingCandidates(snapshot.accounts), + { + capacityWait: { maxInRequestMs }, + signal: init?.signal ?? undefined, + warmCredentialId: routingWarmCredential( + snapshot.accounts, + assignment, + ), + }, + ) + init?.signal?.throwIfAborted() + sharedRoutingDecision = Boolean(advice) + const current = advice + ? await nativeAccounts.read(routingModelId) + : snapshot + const account = + advice && + routingCandidates(current.accounts).find((row) => + routingChoiceMatches(advice, row), + ) + return { advice, account, snapshot: current, routing } + } + function retryQuotaBlocked( + account: NativeAccountView, + snapshot: NativeAccountSnapshot, + ) { + const quota = routingAccountQuota( + account, + snapshot.policyStorage, + ) + return ( + stickyQuotaSnapshotIsFresh( + quota, + snapshot.policyStorage, + runtimeNow(), + routingModelId, + ) && + (quotaSnapshotIsExhausted(quota) || + quotaSnapshotModelScopeIsExhausted(quota, routingModelId)) + ) + } + + let mainSharedRefusal: Response | undefined + if ( + sessionId && + replayableRequest && + getRoutingMode(storage) !== 'sticky-balanced' && + hasSharedRouting() + ) { + const routingSessionId = sessionId + const refused = new Set() + let triedSharedAccount = false + const judged = new WeakSet() + async function consult( + lastRefuser?: string, + ): Promise { + for (;;) { + let pick: Awaited> + try { + pick = await askSharedRouting( + routingSessionId, + lastRefuser === undefined ? undefined : 0, + ) + } catch (error) { + if (error instanceof RoutingRefusalError) + return error.response() + throw error + } + const { advice, account, snapshot, routing } = pick + if (!advice) return + if ( + !account || + (advice.hold + ? account.id !== lastRefuser + : refused.has(account.id) || + (lastRefuser && retryQuotaBlocked(account, snapshot))) + ) { + routingRelay.override( + routingSessionId, + 'unknown account, credential or retry policy', + ) + return + } + const selected = await routing.router.resolve({ + sessionId: routingSessionId, + family: stickyRouteFamilyForModel(routingModelId), + modelId: routingModelId, + affinityModelId: requestModel, + candidates: [ + { + accountId: account.id, + order: 0, + quota: account.quota ?? { kind: 'unknown' }, + }, + ], + retainAccountIds: new Set([account.id]), + storage: snapshot.policyStorage, + inputBytes: 1, + preserveOnNoCandidate: true, + routingAccountId: account.id, + accountIdentities: routing.accountIdentities, + }) + if (!selected) { + routingRelay.override( + routingSessionId, + 'advised account is not selectable', + ) + return + } + if (advice.hold) + return routingHoldResponse(advice.hold.retry_after_ms) + countSessionRequest() + triedSharedAccount = true + let response = await sendWithAccessToken( + input, + init, + '', + trace, + `routing:${account.id}`, + storage, + account.id, + undefined, + fableRequest, + laneStartRequest, + account.id === 'main' + ? requestMainQuotaIdentity + : undefined, + ) + let retry = shouldFallbackResponse(response, storage) + if (!retry) { + const inspected = await inspectStreamingRateLimit( + response, + trace, + ) + response = inspected.response + retry = inspected.rateLimited + } + if (!retry) { + writeCurrentSidebarState( + account.id, + account.id === 'main' ? 'main' : 'fallback', + ) + return response + } + judged.add(response) + refused.add(account.id) + lastRefuser = account.id + if (account.id === 'main') mainSharedRefusal = response + else await response.body?.cancel().catch(() => {}) + } + } + orderedRouting.set(trace, { + // Once shared routing sent on an account, the local loop + // should try routes that have not refused this request yet. + skipLocal: (id) => triedSharedAccount && refused.has(id), + async afterRefusal(id, response) { + if (judged.has(response)) return + judged.add(response) + refused.add(id) + const replacement = await consult(id) + if (replacement) { + await response.body?.cancel().catch(() => {}) + await mainSharedRefusal?.body?.cancel().catch(() => {}) + mainSharedRefusal = undefined + } + return replacement + }, + }) + const selected = await consult() + if (selected) { + await mainSharedRefusal?.body?.cancel().catch(() => {}) + return wrapResponse(selected) + } + if (mainSharedRefusal) + return continueAfterSharedMainRefusal(mainSharedRefusal) + } + async function continueAfterSharedMainRefusal( + response: Response, + ) { + return wrapResponse( + await tryFallbackAccounts( + input, + init, + response, + undefined, + trace, + storage, + auth.access, + (account) => + writeCurrentSidebarState(account.id, 'fallback'), + requestModelId, + fableRequest, + laneStartRequest, + requestMainQuotaIdentity, + ), + ) + } if (providerRestriction) { // A provider-issued wait applies before primary token acquisition. // Available fallbacks may serve; a blocked primary must not refresh @@ -10212,88 +10602,83 @@ const anthropicAuthPlugin = async ( return quotaRefusal( 'No OAuth account currently satisfies quota policy.', ) - return new Response( - JSON.stringify({ - type: 'error', - error: { - type: 'rate_limit_error', - message: providerRestriction.message, - }, - }), - { - status: 429, - headers: { - 'content-type': 'application/json', - 'retry-after': String( - clampHostRetryMs( - providerRestriction.retryAfter * 1000, - ) / 1000, - ), + return reportHostWait( + new Response( + JSON.stringify({ + type: 'error', + error: { + type: 'rate_limit_error', + message: providerRestriction.message, + }, + }), + { + status: 429, + headers: { + 'content-type': 'application/json', + 'retry-after': String( + clampHostRetryMs( + providerRestriction.retryAfter * 1000, + ) / 1000, + ), + }, }, - }, + ), + 'account_limit', ) } - let sharedRoutingDecision = false async function quotaRefusal( reason: string, scopedModelId?: string, ) { const current = await nativeAccounts.read() - return createQuotaRefusalResponse( - reason, - quotaRefusalTiming({ - readings: current.accounts - .filter( - (account) => - account.type === 'oauth' && - nativeAccountCanServe(account), - ) - .map((account) => ({ - quota: account.quota, - accountIdentity: account.accountIdentity, - accountId: account.id, - })), - storage: current.policyStorage, - modelId: scopedModelId ?? credentialModelId, - sessionTtlMs: sessionCacheActivity.ttlMs(sessionId), - sessionId, - waitForReset: - getWaitForReset(current.policyStorage) && - !sharedRoutingDecision, - }), + return reportHostWait( + createQuotaRefusalResponse( + reason, + quotaRefusalTiming({ + readings: current.accounts + .filter( + (account) => + account.type === 'oauth' && + nativeAccountCanServe(account), + ) + .map((account) => ({ + quota: account.quota, + accountIdentity: account.accountIdentity, + accountId: account.id, + })), + storage: current.policyStorage, + modelId: scopedModelId ?? credentialModelId, + sessionTtlMs: sessionCacheActivity.ttlMs(sessionId), + sessionId, + waitForReset: + getWaitForReset(current.policyStorage) && + !sharedRoutingDecision, + }), + ), + 'account_free', ) } const modelDeniedResponse = async () => { if (isScopedCustodyActive(storage)) - return createNativeVaultNoRouteResponse({ - snapshot: await nativeAccounts.read(), - modelId: credentialModelId, - sticky: getRoutingMode(storage) === 'sticky-balanced', - sessionId, - waitForReset: - getWaitForReset(storage) && !sharedRoutingDecision, - }) + return reportHostWait( + createNativeVaultNoRouteResponse({ + snapshot: await nativeAccounts.read(), + modelId: credentialModelId, + sticky: getRoutingMode(storage) === 'sticky-balanced', + sessionId, + waitForReset: + getWaitForReset(storage) && !sharedRoutingDecision, + }), + 'account_free', + ) return quotaRefusal( 'No enabled OAuth route can serve the requested model under current quota policy.', credentialModelId, ) } - // Count every replayable request up front — before the - // fallback-first early return — so the every-N refresh cadence - // (quota.refreshEveryNRequests) advances for main and the active - // fallback route on all paths, including successful fallback-first. - if (replayableRequest) sessionRequestCount++ - if ( - replayableRequest && - auth.access && - (!auth.expires || auth.expires > Date.now()) - ) { - scheduleSidebarMainQuotaRefresh( - storage, - auth.access, - requestMainQuotaIdentity, - ) - } + // Count requests before a fallback can return so the every-N + // quota refresh cadence uses the account that serves them. + countSessionRequest() function writeCurrentSidebarState( activeId: string | undefined, route: string, @@ -10344,8 +10729,6 @@ const anthropicAuthPlugin = async ( sessionId && getRoutingMode(storage) === 'sticky-balanced' ) { - const routingModelId = - fablePlan?.effectiveModel ?? requestModelId const family = stickyRouteFamilyForModel(routingModelId) const trackedRoute = cacheKeepManager.trackedOAuthRoute(sessionId) @@ -10367,30 +10750,10 @@ const anthropicAuthPlugin = async ( requestedModelId: routingModelId, mainQuotaIdentity: requestMainQuotaIdentity, }) - const snapshot = await nativeAccounts.read() - const routing = await currentStickyRouting() - const assignment = - await routing.router.readAssignment(sessionId) - const advice = await routingRelay.accountFor( - sessionId, - routingModelId ?? '', - routingCandidates(snapshot.accounts), - { - capacityWait: { maxInRequestMs: 240_000 }, - signal: init?.signal ?? undefined, - warmCredentialId: routingWarmCredential( - snapshot.accounts, - assignment, - ), - }, - ) - sharedRoutingDecision = Boolean(advice) + const { snapshot, advice, account } = + await askSharedRouting(sessionId) let advisedAccountId: string | undefined if (advice) { - const snapshot = await nativeAccounts.read() - const account = snapshot.accounts.find((row) => - routingChoiceMatches(advice, row), - ) if ( account && nativeAccountCanServe(account) && @@ -10410,9 +10773,7 @@ const anthropicAuthPlugin = async ( excludeAccountIds?: Set, ) => { const routing = await currentStickyRouting() - // Use shared routing advice only for the first choice; - // retries after quota exhaustion make their own account choice. - const advised = !excludeAccountIds && advisedAccountId + const advised = advisedAccountId return routing.router.resolve({ sessionId, family, @@ -10477,25 +10838,7 @@ const anthropicAuthPlugin = async ( resolution?.accountId === advisedAccountId && advice?.hold ) { - return new Response( - JSON.stringify({ - type: 'error', - error: { - type: 'rate_limit_error', - message: - 'Shared routing requested a wait; retaining session affinity.', - }, - }), - { - status: 429, - headers: { - 'content-type': 'application/json', - 'retry-after': String( - Math.ceil(advice.hold.retry_after_ms / 1000), - ), - }, - }, - ) + return routingHoldResponse(advice.hold.retry_after_ms) } if (!resolution && incompleteQuotaPool) { if (auth.modelDenied) return modelDeniedResponse() @@ -10507,25 +10850,28 @@ const anthropicAuthPlugin = async ( if (auth.modelDenied) return modelDeniedResponse() if (isScopedCustodyActive(storage)) { const current = await nativeAccounts.read() - return createNativeVaultNoRouteResponse({ - snapshot: { - ...current, - // Use the refusal's quota before its background write reaches account storage. - accounts: current.accounts.map((account) => { - const quota = stickyRoutes.allRoutes.find( - (route) => route.id === account.id, - )?.quota - return quota?.accountIdentity === - account.accountIdentity - ? { ...account, quota } - : account - }), - }, - modelId: routingModelId, - sticky: true, - sessionId, - waitForReset: getWaitForReset(storage) && !advice, - }) + return reportHostWait( + createNativeVaultNoRouteResponse({ + snapshot: { + ...current, + // Use the refusal's quota before its background write reaches account storage. + accounts: current.accounts.map((account) => { + const quota = stickyRoutes.allRoutes.find( + (route) => route.id === account.id, + )?.quota + return quota?.accountIdentity === + account.accountIdentity + ? { ...account, quota } + : account + }), + }, + modelId: routingModelId, + sticky: true, + sessionId, + waitForReset: getWaitForReset(storage) && !advice, + }), + 'account_free', + ) } const response = createStickyNoRouteResponse({ mainRefreshError: @@ -10554,7 +10900,7 @@ const anthropicAuthPlugin = async ( trace.done('return_sticky_no_route', { status: response.status, }) - return response + return reportHostWait(response, 'account_free') } if (!resolution) return noRouteResponse() let route = stickyRoutes.allRoutes.find( @@ -10694,25 +11040,28 @@ const anthropicAuthPlugin = async ( if (proactiveQuotaDecision?.action === 'hold') { return completeRoute( route, - await withStickyRetryAfter( - new Response( - JSON.stringify({ - type: 'error', - error: { - type: 'rate_limit_error', - message: - 'Sticky OAuth account quota resets shortly; retaining session affinity.', + reportHostWait( + await withStickyRetryAfter( + new Response( + JSON.stringify({ + type: 'error', + error: { + type: 'rate_limit_error', + message: + 'Sticky OAuth account quota resets shortly; retaining session affinity.', + }, + }), + { + status: 429, + headers: { 'content-type': 'application/json' }, }, - }), - { - status: 429, - headers: { 'content-type': 'application/json' }, - }, + ), + sessionId, + proactiveQuotaDecision.retryAfterSeconds, + false, + cacheDiagnosticsResponses, ), - sessionId, - proactiveQuotaDecision.retryAfterSeconds, - false, - cacheDiagnosticsResponses, + 'account_limit', ), false, ) @@ -10809,25 +11158,31 @@ const anthropicAuthPlugin = async ( if (decision.action === 'hold') { return completeRoute( route, - await withStickyRetryAfter( - inspected.response, - sessionId, - decision.retryAfterSeconds, - inspected.streamingRateLimit, - cacheDiagnosticsResponses, + reportHostWait( + await withStickyRetryAfter( + inspected.response, + sessionId, + decision.retryAfterSeconds, + inspected.streamingRateLimit, + cacheDiagnosticsResponses, + ), + 'account_limit', ), ) } if (decision.action === 'retain') { return completeRoute( route, - await withStickyRetryAfter( - inspected.response, - sessionId, - 60, - inspected.streamingRateLimit, - cacheDiagnosticsResponses, - true, + reportHostWait( + await withStickyRetryAfter( + inspected.response, + sessionId, + 60, + inspected.streamingRateLimit, + cacheDiagnosticsResponses, + true, + ), + 'rate_limited', ), ) } @@ -10848,14 +11203,70 @@ const anthropicAuthPlugin = async ( requestedModelId: routingModelId, mainQuotaIdentity: requestMainQuotaIdentity, }) + const rejectedInitialAdvice = advice && !advisedAccountId + advisedAccountId = undefined + if (hasSharedRouting()) { + let pick: Awaited> + try { + pick = await askSharedRouting(sessionId, 0) + } catch (error) { + if (error instanceof RoutingRefusalError) + await inspected.response.body + ?.cancel() + .catch(() => {}) + throw error + } + const { advice: retryAdvice, account, snapshot } = pick + if (retryAdvice) { + const eligible = + account && + stickyRoutes.allRoutes.some( + (row) => row.id === account.id, + ) + if (eligible && account) { + if ( + retryAdvice.hold && + account.id === failedRouteId + ) { + await inspected.response.body + ?.cancel() + .catch(() => {}) + return routingHoldResponse( + retryAdvice.hold.retry_after_ms, + ) + } + if ( + !retryAdvice.hold && + account.id !== failedRouteId && + !retryQuotaBlocked(account, snapshot) + ) + advisedAccountId = account.id + } + if (!advisedAccountId) + routingRelay.override( + sessionId, + 'unknown account, credential or retry policy', + ) + } + } const alternatives = stickyRoutes.candidates.filter( (candidate) => candidate.accountId !== failedRouteId, ) - if (alternatives.length > 0) { + if (advisedAccountId || alternatives.length > 0) { await inspected.response.body?.cancel().catch(() => {}) resolution = await resolveRoute( new Set([failedRouteId]), ) + if (advisedAccountId && !resolution) { + routingRelay.override( + sessionId, + 'advised account is not selectable', + ) + advisedAccountId = undefined + resolution = await resolveRoute( + new Set([failedRouteId]), + ) + } const migratedRoute = stickyRoutes.allRoutes.find( (candidate) => candidate.id === resolution?.accountId, ) @@ -10881,7 +11292,7 @@ const anthropicAuthPlugin = async ( return completeRoute(route, await sendRoute(route)) } } else if ( - !(advice && !advisedAccountId) && + !rejectedInitialAdvice && (inspected.response.status === 429 || inspected.streamingRateLimit) && mainQuotaEntryIsFreshExhausted( @@ -11032,6 +11443,9 @@ const anthropicAuthPlugin = async ( } } + if (mainSharedRefusal) + return continueAfterSharedMainRefusal(mainSharedRefusal) + // Fallback-first reached main only after its fallback attempts. // Resolve current access now; absence from the earlier metadata // view is not evidence that the stored token needs refreshing. @@ -11374,29 +11788,32 @@ const anthropicAuthPlugin = async ( nextRetryAt: lastError?.nextRetryAt, retryCount: lastError?.retryCount, }) - return new Response( - JSON.stringify({ - type: 'error', - error: { type: 'rate_limit_error', message: msg }, - }), - { - status: 429, - headers: { - 'content-type': 'application/json', - 'retry-after': String( - clampHostRetryMs( - (lastError?.nextRetryAt - ? Math.max( - 1, - Math.ceil( - (lastError.nextRetryAt - Date.now()) / 1000, - ), - ) - : 60) * 1000, - ) / 1000, - ), + return reportHostWait( + new Response( + JSON.stringify({ + type: 'error', + error: { type: 'rate_limit_error', message: msg }, + }), + { + status: 429, + headers: { + 'content-type': 'application/json', + 'retry-after': String( + clampHostRetryMs( + (lastError?.nextRetryAt + ? Math.max( + 1, + Math.ceil( + (lastError.nextRetryAt - Date.now()) / 1000, + ), + ) + : 60) * 1000, + ) / 1000, + ), + }, }, - }, + ), + 'account_free', ) } // Killswitch — eagerly refresh quota so it can evaluate diff --git a/packages/opencode/src/request-class.ts b/packages/opencode/src/request-class.ts index a6e2e2394..872e7fbff 100644 --- a/packages/opencode/src/request-class.ts +++ b/packages/opencode/src/request-class.ts @@ -1,4 +1,7 @@ -import type { ClaudeCodeRequestClass } from '@cortexkit/anthropic-auth-core' +import type { + AnthropicBillingRequest, + ClaudeCodeRequestClass, +} from '@cortexkit/anthropic-auth-core' /** * Plugin-internal header that carries a request's Claude Code request class @@ -6,6 +9,7 @@ import type { ClaudeCodeRequestClass } from '@cortexkit/anthropic-auth-core' * the request leaves. */ export const REQUEST_CLASS_REQUEST_HEADER = 'x-cortexkit-request-class' +export const BILLING_REQUEST_KIND_HEADER = 'x-cortexkit-billing-request-kind' /** * Agents whose requests Claude Code would mark `auxiliary`: they run beside a @@ -28,3 +32,11 @@ export function takeRequestClassHeader( headers.delete(REQUEST_CLASS_REQUEST_HEADER) return value === 'auxiliary' ? 'auxiliary' : 'main' } + +export function takeBillingRequestKind( + headers: Headers, +): AnthropicBillingRequest['requestKind'] { + const kind = headers.get(BILLING_REQUEST_KIND_HEADER) + headers.delete(BILLING_REQUEST_KIND_HEADER) + return kind === 'title' || kind === 'compaction' ? kind : 'primary' +} diff --git a/packages/opencode/src/tests/cachekeep-and-cache-diagnostics.integration.test.ts b/packages/opencode/src/tests/cachekeep-and-cache-diagnostics.integration.test.ts index d75ecaf69..f628f0a39 100644 --- a/packages/opencode/src/tests/cachekeep-and-cache-diagnostics.integration.test.ts +++ b/packages/opencode/src/tests/cachekeep-and-cache-diagnostics.integration.test.ts @@ -28,6 +28,7 @@ import { bindPoolAccounts, createFallbackStorage, getPlugin as getPluginWithCtx, + syntheticMainAccountUuid, syntheticMainHostAuth, updatePoolSettings, useTempAccountFile as useTempAccountFileWithCtx, @@ -620,6 +621,8 @@ describe('auth.loader', () => { describe('cache diagnostics', () => { const originalFetch = globalThis.fetch const originalDateNow = Date.now + const globals = globalThis as Record + const routingKey = Symbol.for('cortexkit.routing') const message = ( id: string, @@ -673,6 +676,7 @@ describe('cache diagnostics', () => { }) afterEach(async () => { + delete globals[routingKey] __setLogTestSink(null) globalThis.fetch = originalFetch Date.now = originalDateNow @@ -973,6 +977,12 @@ describe('cache diagnostics', () => { }) test('an OpenCode 1 prewarm preserves thinking block binding and carries its beta', async () => { + const reports: Record[] = [] + globals[routingKey] = () => ({ + report: (report: Record) => { + if (report.kind === 'billing') reports.push(report) + }, + }) let now = 1_000 Date.now = mock(() => now) as unknown as typeof Date.now await useTempAccountFile( @@ -992,7 +1002,12 @@ describe('cache diagnostics', () => { return Promise.resolve( body.max_tokens === 0 ? Response.json(message('provider-thinking-warm')) - : sseResponse(message('provider-thinking-live')), + : new Response( + `event: message_start\ndata: ${JSON.stringify({ type: 'message_start', message: message('provider-thinking-live') })}\n\n` + + 'event: message_delta\ndata: {"type":"message_delta","usage":{"output_tokens":2}}\n\n' + + 'event: message_stop\ndata: {"type":"message_stop"}\n\n', + { headers: { 'content-type': 'text/event-stream' } }, + ), ) }), ) as unknown as typeof fetch @@ -1039,6 +1054,26 @@ describe('cache diagnostics', () => { expect(warm.headers.get('anthropic-beta')?.split(',')).toContain( 'thinking-binding-controls-2026-08-01', ) + await Bun.sleep(10) + expect(reports).toHaveLength(2) + expect(reports).toContainEqual( + expect.objectContaining({ + account_id: syntheticMainAccountUuid, + request_kind: 'keep_warm', + provider_response_id: 'provider-thinking-warm', + outcome: 'completed', + usage: expect.objectContaining({ input: 101, cache_read: 75 }), + cache: expect.objectContaining({ warming: { on: true } }), + }), + ) + expect(reports).toContainEqual( + expect.objectContaining({ + account_id: syntheticMainAccountUuid, + request_kind: 'primary', + provider_response_id: 'provider-thinking-live', + cache: expect.objectContaining({ warming: { on: true } }), + }), + ) }) test('cache diagnostics records cachekeep prewarms and carries their provider id forward', async () => { diff --git a/packages/opencode/src/tests/opencode1-routing-relay.test.ts b/packages/opencode/src/tests/opencode1-routing-relay.test.ts index 561124a9a..e07377791 100644 --- a/packages/opencode/src/tests/opencode1-routing-relay.test.ts +++ b/packages/opencode/src/tests/opencode1-routing-relay.test.ts @@ -34,6 +34,11 @@ describe('OC1 shared routing relay', () => { mode = 'normal', responseFor?: () => Response, modelId?: string, + routingMode: + | 'sticky-balanced' + | 'main-first' + | 'fallback-first' = 'sticky-balanced', + relay = false, ) { const now = Date.now() const quota = (remaining: number, fable = 100) => ({ @@ -63,7 +68,16 @@ describe('OC1 shared routing relay', () => { ctx, bindPoolAccounts( createFallbackStorage({ - routing: { mode: 'sticky-balanced' }, + routing: { mode: routingMode }, + ...(relay && { + relay: { + enabled: true, + url: 'https://relay.example.test', + token: 'relay-token', + fallbackToDirect: false, + transport: 'http', + }, + }), quota: { enabled: true, checkIntervalMinutes: 5, @@ -108,6 +122,14 @@ describe('OC1 shared routing relay', () => { const bodies: string[] = [] globalThis.fetch = mock( withNativeAdmission(ctx, (input: any, init: any) => { + if (extractUrl(input).startsWith('https://relay.example.test')) { + const envelope = JSON.parse(String(init.body)) + bodies.push(envelope.body) + sends.push( + new Headers(envelope.upstream.headers).get('authorization') ?? '', + ) + if (responseFor) return Promise.resolve(responseFor()) + } if (extractUrl(input).includes('/api/oauth/usage')) return Promise.resolve( new Response( @@ -261,7 +283,10 @@ describe('OC1 shared routing relay', () => { const routingReports = (): unknown[] => reports.filter( (report) => - typeof report === 'object' && report !== null && 'outcome' in report, + typeof report === 'object' && + report !== null && + 'outcome' in report && + report.outcome === 'served', ) expect(routingReports()).toEqual([ { @@ -276,6 +301,148 @@ describe('OC1 shared routing relay', () => { expect(routingReports()).toHaveLength(2) }) + for (const [mode, accountId, token] of [ + ['main-first', syntheticFallbackAccountUuid(0), 'fallback'], + ['fallback-first', syntheticMainAccountUuid, 'main'], + ] as const) { + test(`${mode} honors the shared login choice ahead of local order`, async () => { + const f = await fixture('normal', undefined, undefined, mode) + const accountFor = mock(async () => ({ + account_id: accountId, + credential_id: 'local', + })) + globals[key] = () => ({ accountFor }) + await (await f.send()).text() + expect(accountFor).toHaveBeenCalledTimes(1) + expect(f.sends).toEqual([`Bearer sk-ant-oat01-${token}-access`]) + }) + } + + test('sticky reroute asks shared routing again and honors a final refusal', async () => { + const f = await fixture('normal', () => new Response(null, { status: 403 })) + let choices = 0 + globals[key] = () => ({ + accountFor: async () => + ++choices === 1 + ? { account_id: syntheticMainAccountUuid, credential_id: 'local' } + : { refused: { code: 'account_selection_final' } }, + }) + const response = await f.send() + expect(choices).toBe(2) + expect(response.status).toBe(403) + expect(await response.json()).toMatchObject({ + error: { code: 'account_selection_final' }, + }) + expect(f.sends).toEqual(['Bearer sk-ant-oat01-main-access']) + }) + + for (const [mode, token] of [ + ['main-first', 'main'], + ['fallback-first', 'fallback'], + ] as const) { + test(`${mode} asks again before changing an account and honors a final refusal`, async () => { + const f = await fixture( + 'normal', + () => new Response(null, { status: 403 }), + undefined, + mode, + ) + let choices = 0 + globals[key] = () => ({ + accountFor: async () => + ++choices === 1 + ? null + : { refused: { code: 'account_selection_final' } }, + }) + const response = await f.send() + expect(choices).toBe(2) + expect(await response.json()).toMatchObject({ + error: { code: 'account_selection_final' }, + }) + expect(f.sends).toEqual([`Bearer sk-ant-oat01-${token}-access`]) + }) + } + + test('bills each physical OpenCode 1 send with its own payer and usage', async () => { + let sends = 0 + const f = await fixture('normal', () => + ++sends === 1 + ? new Response(null, { status: 403 }) + : Response.json({ + id: 'msg_oc1', + type: 'message', + usage: { input_tokens: 120, output_tokens: 18 }, + }), + ) + const reports: Record[] = [] + globals[key] = () => ({ + report: (report: Record) => { + if (report.kind === 'billing') reports.push(report) + return new Promise(() => {}) + }, + }) + const response = await f.send() + expect(response.status).toBe(200) + await response.text() + await Bun.sleep(10) + expect(reports).toHaveLength(2) + expect(reports).toContainEqual( + expect.objectContaining({ + account_id: syntheticMainAccountUuid, + outcome: 'failed', + status: 403, + }), + ) + expect(reports).toContainEqual( + expect.objectContaining({ + account_id: syntheticFallbackAccountUuid(0), + outcome: 'completed', + provider_response_id: 'msg_oc1', + usage: { input: 120, output: 18 }, + }), + ) + expect(reports[0]?.attempt_id).toEqual(expect.any(String)) + expect(reports[1]?.attempt_id).toEqual(expect.any(String)) + expect(reports[0]?.attempt_id).not.toBe(reports[1]?.attempt_id) + }) + + test('bills the upstream response from an OpenCode 1 HTTP relay', async () => { + const f = await fixture( + 'normal', + () => + Response.json( + { + id: 'msg_relay', + type: 'message', + usage: { input_tokens: 80, output_tokens: 9 }, + }, + { headers: { 'request-id': 'req_relay' } }, + ), + undefined, + 'sticky-balanced', + true, + ) + const reports: Record[] = [] + globals[key] = () => ({ + report: (report: Record) => { + if (report.kind === 'billing') reports.push(report) + }, + }) + await (await f.send()).text() + await Bun.sleep(10) + expect(f.sends).toHaveLength(1) + expect(reports).toEqual([ + expect.objectContaining({ + account_id: syntheticMainAccountUuid, + request_kind: 'primary', + provider_request_id: 'req_relay', + provider_response_id: 'msg_relay', + outcome: 'completed', + usage: { input: 80, output: 9 }, + }), + ]) + }) + for (const mode of ['null', 'unknown']) { test(`${mode} advice falls back to our own account choice`, async () => { const f = await fixture(mode) @@ -414,12 +581,14 @@ describe('OC1 shared routing relay', () => { test('an eligible hold returns 429 and capped Retry-After without sending', async () => { const f = await fixture() + const reports: Record[] = [] globals[key] = () => ({ accountFor: async () => ({ account_id: syntheticFallbackAccountUuid(0), credential_id: 'local', hold: { retry_after_ms: 9_000_000 }, }), + report: (report: Record) => reports.push(report), }) const response = await f.send() expect(response.status).toBe(429) @@ -427,6 +596,16 @@ describe('OC1 shared routing relay', () => { String(ROUTING_HOLD_LIMIT_MS / 1000), ) expect(f.sends).toEqual([]) + expect(reports.filter((report) => report.kind === 'wait')).toEqual([ + { + kind: 'wait', + phase: 'start', + wait_id: expect.any(String), + reason: 'routing_hold', + next_ms: expect.any(Number), + message: 'Waiting for shared routing to release the request.', + }, + ]) delete globals[key] await (await f.send()).text() expect(f.sends.at(-1)).toBe('Bearer sk-ant-oat01-fallback-access') @@ -465,7 +644,9 @@ describe('OC1 shared routing relay', () => { const reports: unknown[] = [] globals[key] = () => ({ accountFor: async () => null, - report: (report: unknown) => reports.push(report), + report: (report: { outcome?: string }) => { + if (report.outcome === 'served') reports.push(report) + }, }) await (await f.send()).text() expect(reports).toEqual([ @@ -512,6 +693,14 @@ describe('OC1 shared routing relay', () => { 140, ) expect(f.sends).toHaveLength(1) + expect(reports).toContainEqual( + expect.objectContaining({ + kind: 'wait', + phase: 'start', + reason: 'account_limit', + next_ms: expect.any(Number), + }), + ) expect( reports.filter((report) => report.outcome === 'exhausted'), ).toEqual([ From 76ac9f6a1c6f6af9373bdcbf189bf52d0eaebecc Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:35:51 +0100 Subject: [PATCH 05/27] OpenCode 1: keep-warm and thread cache boundary survive restarts; warms gzipped on OpenCode 1 and Pi; OpenCode 1 warms leave cache diagnostics --- CHANGELOG.md | 4 + docs/cache-diagnostics.md | 2 + docs/cache.md | 2 +- docs/cachekeep-registry.md | 13 +- docs/transports.md | 2 +- packages/core/src/cachekeep-store.ts | 12 +- packages/core/src/cachekeep.ts | 10 + .../core/src/message-thread-tail-store.ts | 2 +- packages/core/src/oauth-origin.ts | 29 +- packages/opencode/src/cachekeep-restart.ts | 262 +++++++++++++ packages/opencode/src/index.ts | 202 +++++----- packages/opencode/src/oauth-destination.ts | 8 +- packages/opencode/src/plugin-test-handles.ts | 2 + ...-and-cache-diagnostics.integration.test.ts | 367 +++++++++++++++--- packages/pi/src/stream.ts | 13 +- packages/pi/src/tests/scoped-stream.test.ts | 44 +++ packages/pi/src/transport.ts | 8 +- 17 files changed, 782 insertions(+), 200 deletions(-) create mode 100644 packages/opencode/src/cachekeep-restart.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ca15d97f..731ed9593 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,10 @@ This repo is a CortexKit-maintained Anthropic auth monorepo for OpenCode and Pi. ## 2.16.6 - Changing effort mid-conversation now preserves the prompt cache in OpenCode v1, OpenCode v2, and Pi for Claude Mythos 5.1 and 5.2, and for Claude Opus 5 and Haiku 5.5 when adaptive thinking is on. +- OpenCode 1: idle sessions can keep warming a still-live Claude prompt cache after a server restart without resetting their budgets; `auto` keep-warm now uses the accepted prefix's token counts to price warms, even without a restart. +- OpenCode 1: after a server restart, a threaded session's first full request can reuse the previous full request's cache boundary, as on OpenCode 2 and Pi. +- OpenCode 1 and Pi: eligible direct CacheKeep requests now use gzip, like OpenCode 2, and resend uncompressed if gzip is rejected. +- OpenCode 1: keep-warm requests no longer appear in cache diagnostics or replace the previous real response, as on OpenCode 2. - Pi: changing thinking effort during a conversation now preserves the prompt cache on models that support per-message effort, including in conversations shortened by Magic Context. - OpenCode 2 now keeps custom proxy headers off Claude sign-in requests, like OpenCode 1 and Pi, while still sending them on API-key routes. - For conversation requests, OpenCode 2 now matches OpenCode 1: the first eligible request sends a null previous message ID, and cache results and beta lists appear in debug logs. diff --git a/docs/cache-diagnostics.md b/docs/cache-diagnostics.md index 3eb549182..4e673618f 100644 --- a/docs/cache-diagnostics.md +++ b/docs/cache-diagnostics.md @@ -4,6 +4,8 @@ The Anthropic API opt-in `cache-diagnosis-2026-04-07` (sent in the `anthropic-beta` header) asks for cache diagnostics; it does not change cache controls or routing. OpenCode 1 and 2 capture the response's opaque top-level message ID and send it as `diagnostics.previous_message_id` on the next eligible request in that session. The first eligible request sends `null`. +Keep-warm requests on OpenCode do not opt in to cache diagnostics or change the previous-message ID. In older OpenCode 1 logs, `prewarm_cachekeep` identifies a keep-warm response. + `MC-CACHE-DIAG ` records and the beta-list side channel are emitted only at debug level. Choose **Logging level** → `debug` in `/claude` → **Diagnostics**. An empty stream can mean no activity or a lower log level: compare it with an independent activity witness such as usage rows, billing or dumps before drawing conclusions. ## Version 2 record diff --git a/docs/cache.md b/docs/cache.md index 0d64a7056..7ef808dac 100644 --- a/docs/cache.md +++ b/docs/cache.md @@ -18,7 +18,7 @@ CacheKeep keeps recently used hybrid-cache sessions warm while their host proces About five minutes before a one-hour cache lifetime expires, CacheKeep sends a `max_tokens: 0` prewarm using the selected account. Checks are scheduled for the earliest target's due time, with a one-minute interval as a backstop. Due prewarms run one at a time, earliest safe-start deadline first. Failure preserves the known expiry and can schedule a bounded retry while the cache may still be alive. A [documented session registry](cachekeep-registry.md#cachekeep-session-registry) in the CortexKit data folder aggregates session/cache timing across processes without publishing request bodies, headers or tokens. Stopped sessions retain metadata until cache expiry; missing or stale leases mean unknown, not expired. Closing the host stops that process's keepalive work. -OpenCode 2 and Pi privately save accepted keep-warm targets across restarts. A restarted Pi head resumes warming its own session at session startup, even while idle and before any new request; a per-session process claim prevents duplicate warming. Only still-live caches on the same eligible login are restored. See the [private restart store](cachekeep-registry.md#location-and-permissions) for storage locations and ownership rules. +OpenCode 1, OpenCode 2 and Pi privately save accepted keep-warm targets across restarts. OpenCode restores eligible idle sessions when its server starts, without warming them twice when multiple projects are open. A restarted Pi process resumes warming its own session at startup, even before a new request; a per-session claim prevents duplicate warming. Only still-live caches on the same eligible login are restored. See the [private restart store](cachekeep-registry.md#location-and-permissions) for storage locations and ownership rules. ### Per-session runner policy diff --git a/docs/cachekeep-registry.md b/docs/cachekeep-registry.md index 06cd40904..bcedb9d53 100644 --- a/docs/cachekeep-registry.md +++ b/docs/cachekeep-registry.md @@ -50,12 +50,13 @@ The first release shipping this data-folder interface is the transition release; the following release removes the compatibility paths. Version 2.5.3 predates the data-folder interface. -OpenCode 2 and Pi share a **private restart store** implementation, which does +OpenCode 1, OpenCode 2 and Pi share a **private restart store** implementation, which does contain compressed replay bodies and is not this public interface. OpenCode 2 keeps its existing location, -`/cortexkit/anthropic-auth/cachekeep-restore//`; Pi uses +`/cortexkit/anthropic-auth/cachekeep-restore//`; OpenCode 1 uses +`/cortexkit/anthropic-auth/cachekeep-restore/opencode1//`; Pi uses `/cortexkit/anthropic-auth/cachekeep-restore/pi//`. -Both use the same owner-only protections, including Windows ACLs, and the same +All use the same owner-only protections, including Windows ACLs, and the same versioned gzip format. Records whitelist replay fields, never transport headers or credentials. Only an accepted response updates the saved body; writes keep the latest body, at most once per five seconds per session, and drain on clean @@ -76,7 +77,9 @@ it neither writes nor restores there; memory-only warming still enforces all bounds. A transient reservation failure in an enabled store instead skips that warm rather than risking an older on-disk count. See [cache policy](cache.md#per-session-runner-policy). -OpenCode 2 restores all eligible sessions in its storage. Pi restores only the +OpenCode 1 and 2 restore all eligible sessions in their respective stores. On +OpenCode 1 only one project instance in the server warms each restored session. +Pi restores only the session named by `session_start` (or the first `turn_start` on a host that delivers it first), without waiting for another request. A per-session claim is acquired in the background: startup, turns and accepted responses never @@ -84,7 +87,7 @@ wait for restart-store I/O. An early accepted body is saved after its claim arrives, including during a clean shutdown. The claim records the process id and OS start identity, so only one live Pi process warms that session; shutdown drains writes and releases the claim. Other sessions' -records remain untouched until expiry cleanup. Both hosts reject expired, +records remain untouched until expiry cleanup. All hosts reject expired, foreign-account, changed-login and disabled-account records, and reauthorize and re-sign prewarms through their normal send path. Overdue restored warms are staggered rather than sent in a restart burst. diff --git a/docs/transports.md b/docs/transports.md index 1c747c4da..1fb5f1e56 100644 --- a/docs/transports.md +++ b/docs/transports.md @@ -51,7 +51,7 @@ Claude Code 2.1.302, the version these requests present as, gzips request bodies - The wire body is the signed request with its billing `cch` reset to `00000`, followed by a newline and 0 to 256 random spaces and tabs, compressed once with gzip at level 6. The request carries `content-encoding: gzip`; the runtime sets `content-length`. - Smaller bodies, other hosts (including a [custom gateway](settings-file.md#custom-gateway)), API-key routes and relays go out uncompressed and signed. Gzip is also off whenever `HTTPS_PROXY`/`HTTP_PROXY` applies to `api.anthropic.com` (honouring `NO_PROXY`), `NODE_EXTRA_CA_CERTS` is set, or a client certificate (`CLAUDE_CODE_CLIENT_CERT`/`CLAUDE_CODE_CLIENT_KEY`) is configured. - `CLAUDE_CODE_GZIP_REQUEST_BODIES=0` turns it off. `=1` turns it on even in those cases. -- Dumps, CacheKeep tracking and relay rescue work on the uncompressed signed body; a dump's `.body.json` is that body, not the wire bytes. OpenCode 1 and Pi CacheKeep prewarms are sent uncompressed; OpenCode 2 prewarms follow the same rule as its other sends. +- Dumps, CacheKeep tracking and relay rescue work on the uncompressed signed body; a dump's `.body.json` is that body, not the wire bytes. Direct CacheKeep prewarms follow the same gzip rule on all three hosts; gateway prewarms stay uncompressed. OpenCode 1 and Pi resend an eligible prewarm uncompressed if the gzipped send is rejected. If something on the way rejects a gzipped body (a 400, 403 or 415 without Anthropic's `request-id` or Cloudflare's `cf-ray`, or a 400 saying the JSON could not be parsed), OpenCode 1 and Pi resend that request once, uncompressed and signed, with the same `x-client-request-id`; the resend does not count as a retry. Any such rejection turns gzip off for the rest of the process. When a proxy (no Anthropic headers) rejected the gzipped body and Anthropic then accepted the uncompressed resend, gzip also stays off for seven days: the plugin records that in `-request-gzip.json` next to its account storage file, never in your settings. An ordinary API 400 is passed through unchanged. diff --git a/packages/core/src/cachekeep-store.ts b/packages/core/src/cachekeep-store.ts index 01642b820..349eaeb23 100644 --- a/packages/core/src/cachekeep-store.ts +++ b/packages/core/src/cachekeep-store.ts @@ -28,10 +28,12 @@ const MAX_RECORD_BYTES = 2 * CACHE_KEEP_MAX_BODY_BYTES + 64 * 1024 // previous format so updates do not discard still-live caches. const RECORD_FORMAT_VERSION = 1 +type CacheKeepStoreHost = 'opencode1' | 'pi' + export function cacheKeepStoreDirectory( storageId: string, root = getHostDataHome(), - host?: 'pi', + host?: CacheKeepStoreHost, ) { return join( root, @@ -244,8 +246,8 @@ function validSavedPolicy(value: unknown): boolean { export interface CacheKeepStoreOptions { storageId: string pluginVersion: string - /** OpenCode retains its original namespace; Pi never reads its records. */ - host?: 'pi' + /** OpenCode 2 retains its original namespace; other hosts do not read it. */ + host?: CacheKeepStoreHost /** Test seam for the data home; never the host's config. */ root?: string /** Test seam for the pre-2.5.4 temp-root migration. */ @@ -364,8 +366,8 @@ export class CacheKeepStore { await this.chain if (!(await this.directoryReady())) return let directory = this.directory - // Only an empty OpenCode store may recover pre-2.5.4 temp files, once per - // writer. Pi has never used the legacy OpenCode location. + // Only an empty OpenCode 2 store may recover the old temp files, once per + // writer. The other hosts have never used this location. const firstLoad = !this.legacyLoadAttempted this.legacyLoadAttempted = true if ( diff --git a/packages/core/src/cachekeep.ts b/packages/core/src/cachekeep.ts index 7dc577e2b..86f87bda0 100644 --- a/packages/core/src/cachekeep.ts +++ b/packages/core/src/cachekeep.ts @@ -1217,6 +1217,16 @@ export class CacheKeepManager { return true } + /** Hand a target to another live host instance without reporting a stop. */ + releaseTarget(id: string) { + this.immediateTargets.delete(id) + if (!this.targets.delete(id)) return + for (const [controller, sessionId] of this.warmControllers) + if (sessionId === id) controller.abort() + this.publishTrackedSessions() + this.scheduleDueTimer() + } + trackedCount(): number { return this.targets.size } diff --git a/packages/core/src/message-thread-tail-store.ts b/packages/core/src/message-thread-tail-store.ts index fe8ac9539..74c8b8c96 100644 --- a/packages/core/src/message-thread-tail-store.ts +++ b/packages/core/src/message-thread-tail-store.ts @@ -20,7 +20,7 @@ const READ_TIMEOUT_MS = 50 const SWEEP_INTERVAL_MS = 60_000 const LONG_LIFETIME_MS = 3_600_000 -export type MessageThreadTailHost = 'opencode2' | 'pi' +export type MessageThreadTailHost = 'opencode1' | 'opencode2' | 'pi' export interface FullCacheTail { identity: string diff --git a/packages/core/src/oauth-origin.ts b/packages/core/src/oauth-origin.ts index 31f8299d6..f4f13fd30 100644 --- a/packages/core/src/oauth-origin.ts +++ b/packages/core/src/oauth-origin.ts @@ -7,6 +7,7 @@ import { isClaudeGatewayUrl, warnClaudeGatewayProxyRefused, } from './gateway.ts' +import { type RequestGzipLatch, sendWithRequestGzip } from './request-gzip.ts' import { copyStreamResponseTiming } from './stream-completion.ts' /** @@ -191,6 +192,8 @@ export interface ClaudeModelFetchOptions { | ClaudeGateway | undefined | (() => ClaudeGateway | undefined) + /** Opt in for hosts whose CacheKeep transport owns the physical direct send. */ + readonly requestGzipLatch?: RequestGzipLatch } /** @@ -218,12 +221,28 @@ export function createClaudeModelFetch( ) => { const gateway = gatewayNow() const url = fetchInputUrl(input) - const target = - gateway && + const post = (init?.method ?? requestMethod(input)).toUpperCase() === 'POST' - ? claudeGatewayModelUrl(url, gateway) - : undefined - if (!gateway || !target) return direct(input, init) + const target = + gateway && post ? claudeGatewayModelUrl(url, gateway) : undefined + if (!gateway || !target) { + if ( + options.requestGzipLatch && + post && + typeof init?.body === 'string' + ) { + return sendWithRequestGzip({ + url, + body: init.body, + headers: new Headers( + init.headers ?? (input instanceof Request ? input.headers : {}), + ), + latch: options.requestGzipLatch, + send: (body, headers) => direct(input, { ...init, body, headers }), + }) + } + return direct(input, init) + } const headers = applyClaudeGatewayHeaders( new Headers( init?.headers ?? (input instanceof Request ? input.headers : {}), diff --git a/packages/opencode/src/cachekeep-restart.ts b/packages/opencode/src/cachekeep-restart.ts new file mode 100644 index 000000000..b66570154 --- /dev/null +++ b/packages/opencode/src/cachekeep-restart.ts @@ -0,0 +1,262 @@ +import { createHash } from 'node:crypto' +import { lstat } from 'node:fs/promises' +import { setTimeout as delay } from 'node:timers/promises' +import { + type CacheKeepManager, + CacheKeepStore, + type CacheKeepTarget, + CacheKeepWarmRefusal, + isCacheKeepSubagentsEnabled, + localMessageThreadCredential, + logger, + type NativeAccountSnapshot, + nativeAccountCanServe, + readSessionCachePolicy, +} from '@cortexkit/anthropic-auth-core' +import { version as pluginVersion } from '../package.json' + +const RESTORE_SPACING_MS = 3000 +const SLOT = Symbol.for('cortexkit.anthropic-auth.opencode1.cachekeep-restore') + +type Lease = { + manager: CacheKeepManager + read: () => Promise + allowUrl: (url: string) => boolean + now: () => number +} + +type Shared = { + store: CacheKeepStore + leases: Set + owners: Map + restored: Set + skippedDuringLoad: Set + loading?: Promise + closing: number + lastRestoredSend: number +} + +function stores(): Map { + const scope = globalThis as typeof globalThis & { + [SLOT]?: Map + } + scope[SLOT] ??= new Map() + return scope[SLOT] +} + +const sessionHash = (id: string) => + createHash('sha256').update(id).digest('hex') + +/** The restart credential key survives token refresh, but not a replaced login. */ +export function cacheKeepRestartCredential( + source: 'local' | 'vault', + identity: string | undefined, + credential: string | undefined, +): string | undefined { + return identity && credential + ? JSON.stringify([source, identity, credential]) + : undefined +} + +function restore(shared: Shared): Promise { + shared.loading ??= (async () => { + const lease = shared.leases.values().next().value + if (!lease) return + // A fresh installation has nothing to restore. Avoid starting the account + // runtime just to discover that it has never saved a warm. + const stat = await lstat(shared.store.directory).catch(() => undefined) + if (!stat?.isDirectory()) return + const snapshot = await lease.read() + const accounts = new Map( + snapshot.accounts + .filter( + (account) => + account.type === 'oauth' && nativeAccountCanServe(account), + ) + .map( + (account) => + [ + cacheKeepRestartCredential( + account.source, + account.accountIdentity, + account.binding + ? localMessageThreadCredential(account.binding) + : account.credentialId, + ), + account, + ] as const, + ), + ) + const now = lease.now() + let overdue = 0 + const mayRestore = (hash: string) => + shared.leases.has(lease) && + !shared.owners.has(hash) && + !shared.skippedDuringLoad.has(hash) + + await shared.store.load( + now, + (entry) => { + const hash = sessionHash(entry.id) + if (!mayRestore(hash)) return undefined + if (entry.cacheExpiresAt <= lease.now()) return 'expired' + if (!lease.allowUrl(entry.url)) return 'invalid' + const account = accounts.get(entry.oauthAccountIdentity) + if (!account) return 'account-gone' + if ( + entry.isSubagent && + !entry.policyState?.planned && + readSessionCachePolicy( + entry.policyState?.ownerSessionId ?? entry.id, + true, + )?.keep_warm === undefined && + !isCacheKeepSubagentsEnabled(snapshot.policyStorage) + ) + return 'invalid' + + const tracked = lease.manager.track({ + sessionId: entry.id, + url: entry.url, + headers: new Headers(), + bodyText: entry.bodyText, + storage: snapshot.policyStorage, + cacheMode: 'hybrid', + oauthAccountId: account.id, + oauthAccountIdentity: account.accountIdentity, + hostMetadata: { restartCredential: entry.oauthAccountIdentity }, + isSubagent: entry.isSubagent, + retained: { + cacheExpiresAt: entry.cacheExpiresAt, + nextPrewarmAt: + entry.nextPrewarmAt <= now + ? now + overdue++ * RESTORE_SPACING_MS + : entry.nextPrewarmAt, + ttlMs: entry.ttlMs, + lastTouchAt: entry.lastTouchAt, + lastTouchKind: entry.lastTouchKind, + policyState: entry.policyState, + }, + }) + if (tracked.tracked) shared.restored.add(hash) + return tracked.tracked ? true : 'invalid' + }, + undefined, + mayRestore, + ) + })() + .catch(() => { + logger.warn('cachekeep', 'failed to restore tracked sessions') + }) + .finally(() => { + shared.loading = undefined + shared.skippedDuringLoad.clear() + }) + return shared.loading +} + +/** One writer and one owner per session, even when OpenCode opens several projects. */ +export function adoptCacheKeepRestart(storageId: string, lease: Lease) { + const slots = stores() + const shared: Shared = slots.get(storageId) ?? { + store: new CacheKeepStore({ + storageId, + pluginVersion, + host: 'opencode1', + now: lease.now, + }), + leases: new Set(), + owners: new Map(), + restored: new Set(), + skippedDuringLoad: new Set(), + closing: 0, + lastRestoredSend: 0, + } + slots.set(storageId, shared) + shared.leases.add(lease) + + const active = () => shared.leases.has(lease) + const persisted = (target: Readonly) => { + const credential = target.hostMetadata?.restartCredential + return !target.sourceWarm && typeof credential === 'string' + ? { ...target, oauthAccountIdentity: credential } + : undefined + } + const reserve = (target: Readonly) => { + const entry = persisted(target) + if (!entry) return Promise.resolve(true) + if (!active() || shared.owners.get(sessionHash(target.id)) !== lease) + return Promise.resolve(false) + return shared.store.reserveWarm(entry) + } + + return { + active, + restore: () => restore(shared), + changed(target: Readonly) { + const entry = persisted(target) + if (!entry || !active()) return + const hash = sessionHash(target.id) + const previous = shared.owners.get(hash) + if (previous !== lease) { + shared.owners.set(hash, lease) + shared.restored.delete(hash) + previous?.manager.releaseTarget(target.id) + } + shared.store.changed(entry) + }, + removed(id: string) { + const hash = sessionHash(id) + if (shared.owners.get(hash) !== lease) return + shared.owners.delete(hash) + shared.restored.delete(hash) + shared.store.removed(id) + }, + forget(id: string) { + const hash = sessionHash(id) + if (shared.loading) shared.skippedDuringLoad.add(hash) + const owner = shared.owners.get(hash) + if (owner?.manager.untrack(id)) return + if (owner || shared.loading) { + shared.owners.delete(hash) + shared.restored.delete(hash) + shared.store.removed(id) + } + }, + reserve, + settle: (target: Readonly) => + lease.manager.isCurrentTarget(target) + ? reserve(target) + : Promise.resolve(false), + async stagger(target: Readonly, signal?: AbortSignal) { + if (!shared.restored.delete(sessionHash(target.id))) return + // A late scheduler pass can make several restored targets due at once. + const now = lease.now() + const sendAt = Math.max(now, shared.lastRestoredSend + RESTORE_SPACING_MS) + shared.lastRestoredSend = sendAt + if (sendAt > now) await delay(sendAt - now, undefined, { signal }) + if (target.cacheExpiresAt <= lease.now()) + throw new CacheKeepWarmRefusal('expired') + }, + async dispose() { + if (!shared.leases.delete(lease)) return + shared.closing++ + try { + await lease.manager.dispose() + await shared.loading + let released = false + for (const [hash, owner] of shared.owners) { + if (owner !== lease) continue + shared.owners.delete(hash) + shared.restored.delete(hash) + released = true + } + await shared.store.drain() + if (released && shared.leases.size > 0) await restore(shared) + } finally { + shared.closing-- + if (shared.leases.size === 0 && shared.closing === 0) + slots.delete(storageId) + } + }, + } +} diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index 73fa81ff7..b5ef6bc30 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -23,6 +23,7 @@ import { CACHE_KEEP_EXTENDED_TTL_BETA, CacheKeepManager, CacheKeepSessionRegistry, + CacheKeepWarmRefusal, CLAUDE_FABLE_MYTHOS_5_MODEL_SPECS, CLAUDE_HAIKU_4_5_MODEL_ID, CLAUDE_HAIKU_5_5_CONTEXT_WINDOW, @@ -265,7 +266,6 @@ import { extractAnthropicRequestId, } from './billing-lineage.ts' import { - applyCacheDiagnosticsOptIn, buildCacheDiagnosticsRecord, CACHE_DIAGNOSTICS_BETA, CacheDiagnosticsBetaTracker, @@ -277,6 +277,10 @@ import { summarizeCacheTtl, withStickyRetryAfter, } from './cache-diagnostics.ts' +import { + adoptCacheKeepRestart, + cacheKeepRestartCredential, +} from './cachekeep-restart.ts' import { custodyStateFor, fallbackCustodyDimensions, @@ -1319,7 +1323,7 @@ const anthropicAuthPlugin = async ( const { client } = ctx const profileFetch = globalThis.fetch const accountStoragePath = getAccountStoragePath() - const messageThreads = new MessageThreadTracker() + const messageThreads = MessageThreadTracker.withTailPersistence('opencode1') // -- OAuth add-flow pending state (Add account modal) -------------------- interface OAuthPendingEntry { @@ -1873,6 +1877,12 @@ const anthropicAuthPlugin = async ( ...(ttlMs > 0 && { cache: { ttlMs } }), } } + const cacheKeepCredential = (authorization: NativeOAuthAuthorization) => + cacheKeepRestartCredential( + authorization.scopedAttempt ? 'vault' : 'local', + authorization.accountIdentity, + authorization.credentialId, + ) function nativeWireIdentity(accountIdentity: string | undefined) { const accountUuid = asProviderAccountUuid(accountIdentity) if (!accountUuid) @@ -3597,6 +3607,7 @@ const anthropicAuthPlugin = async ( toolNameMap?: ToolNameMap failThread?: () => void cacheKeepBodyText?: string + acceptedCacheKeepBodyText?: () => string | undefined cacheKeepSignal?: AbortSignal | null fableRequest?: FableRequestContext sourceCandidate?: FableSourceWarmInit @@ -3632,16 +3643,6 @@ const anthropicAuthPlugin = async ( if (!signal?.aborted) reportSessionCacheTouch(sessionId, { ...touch, source: 'response' }) } - const cacheKeepDiagnosticsRequests = new Map< - string, - CacheDiagnosticsRequestContext & { - accountId: string - synthetic: boolean - betasHash?: string - betas?: string[] - requestedModel?: string - } - >() function observeCacheDiagnosticsMessage(input: { source: CacheDiagnosticsSource @@ -3813,10 +3814,13 @@ const anthropicAuthPlugin = async ( // delta. Warming signs the template again before sending it. context.fableRequest.sourceCacheUsed = context.sourceCandidate } - if (usage) + // The wire body can be a thread delta or have a different signature. Price + // the full logical body only if this response actually replaced the target. + const acceptedBody = context.acceptedCacheKeepBodyText?.() + if (usage && acceptedBody !== undefined) cacheKeepManager.recordAcceptedUsage( context.trackSessionId, - context.cacheKeepBodyText, + acceptedBody, usage, ) } @@ -3951,7 +3955,7 @@ const anthropicAuthPlugin = async ( > = [] const cacheKeepScopedAttempts = new Map() const cacheKeepSourceCopies = new Map() - const cacheKeepManager = new CacheKeepManager({ + const cacheKeepManager: CacheKeepManager = new CacheKeepManager({ loadStorage: () => loadAccounts(accountStoragePath), resolveSettings: (storage, model) => nativeAccounts.resolveSettings?.(storage, model) ?? storage, @@ -3969,7 +3973,10 @@ const anthropicAuthPlugin = async ( }, // Prewarms carry an OAuth bearer: recheck the destination, no redirects. // A keep-warm is a model request, so it follows the current gateway. - fetchImpl: fetchOAuthModel(() => nativeAccounts.getClaudeGateway?.()), + fetchImpl: fetchOAuthModel( + () => nativeAccounts.getClaudeGateway?.(), + requestGzipLatch, + ), billingRequest: (target, attempt) => { const payer = cacheKeepScopedAttempts.get(attempt.id) if (!payer) return @@ -3988,8 +3995,13 @@ const anthropicAuthPlugin = async ( }, setIntervalImpl: runtimeTimers.setInterval, clearIntervalImpl: runtimeTimers.clearInterval, + reserveWarm: (target) => cacheKeepRestart.reserve(target), + settleWarm: (target) => cacheKeepRestart.settle(target), onTargetChanged: (target) => { - if (!target.sourceWarm) return + if (!target.sourceWarm) { + cacheKeepRestart.changed(target) + return + } const kept = fableFallbackManager.sourceWarmForTarget(target.id) if ( kept && @@ -3999,6 +4011,7 @@ const anthropicAuthPlugin = async ( cacheKeepSourceCopies.set(target.id, kept) }, onTargetRemoved: (id) => { + cacheKeepRestart.removed(id) const kept = cacheKeepSourceCopies.get(id) cacheKeepSourceCopies.delete(id) // A terminal stop must retire both copies. Do not let an old target's @@ -4010,47 +4023,15 @@ const anthropicAuthPlugin = async ( await cacheKeepRegistry.publish(sessions) aggregateCacheKeepSessions = await cacheKeepRegistry.list(sessions) }, - prepareBody: (bodyText, target) => { - if ( - !new Headers(target.headers) - .get('anthropic-beta') - ?.split(',') - .map((beta) => beta.trim()) - .includes(CACHE_DIAGNOSTICS_BETA) - ) { - return bodyText - } - try { - const body = JSON.parse(bodyText) as Record - const previous = cacheDiagnosticsTracker.previousFor(target.id) - const previousMessageId = previous?.messageId ?? null - applyCacheDiagnosticsOptIn(body, previousMessageId) - cacheKeepDiagnosticsRequests.set(target.id, { - sessionId: target.id, - previousMessageId, - ...(previous - ? { previousMessageReceivedAt: previous.receivedAt } - : {}), - isSubagent: target.isSubagent, - ttlSent: summarizeCacheTtl(body), - accountId: target.oauthAccountId ?? 'main', - synthetic: true, - requestedModel: - typeof body.model === 'string' ? body.model : undefined, - }) - return JSON.stringify(body) - } catch { - return bodyText - } + prepareBody: (bodyText) => { + // Strip the real turn's diagnostic predecessor before signing. A warm + // refreshes the prefix but does not join the turn's diagnostics chain. + const body = JSON.parse(bodyText) as Record + if (!Object.hasOwn(body, 'diagnostics')) return bodyText + delete body.diagnostics + return JSON.stringify(body) }, - onResponse: async ({ - target, - bodyText, - status, - data, - receivedAt, - attempt, - }) => { + onResponse: async ({ target, bodyText, status, receivedAt, attempt }) => { const authorization = cacheKeepScopedAttempts.get(attempt.id) // A recovery source warm protects another model, not the active fallback's cache. if ( @@ -4079,47 +4060,6 @@ const anthropicAuthPlugin = async ( ) { fableFallbackManager.noteSourceWarmSentForTarget(target.id) } - const prepared = cacheKeepDiagnosticsRequests.get(target.id) - if (!prepared?.betasHash || !prepared.betas) { - cacheKeepDiagnosticsRequests.delete(target.id) - return - } - try { - const sentBody = JSON.parse(bodyText) - const diagnostics = - sentBody && typeof sentBody === 'object' && !Array.isArray(sentBody) - ? (sentBody as { diagnostics?: unknown }).diagnostics - : undefined - const previousMessageId = - diagnostics && - typeof diagnostics === 'object' && - !Array.isArray(diagnostics) && - (diagnostics as { previous_message_id?: unknown }) - .previous_message_id === prepared.previousMessageId - ? prepared.previousMessageId - : undefined - if (previousMessageId === undefined) return - observeCacheDiagnosticsMessage({ - source: 'prewarm_cachekeep', - accountId: prepared.accountId, - synthetic: prepared.synthetic, - betasHash: prepared.betasHash, - betas: prepared.betas, - requestedModel: prepared.requestedModel, - request: { - ...prepared, - previousMessageId, - ttlSent: summarizeCacheTtl(sentBody), - }, - trackSessionId: target.id, - status, - message: data, - receivedAt, - }) - } catch { - } finally { - cacheKeepDiagnosticsRequests.delete(target.id) - } }, onComplete: ({ attempt }) => { cacheKeepScopedAttempts.delete(attempt.id) @@ -4150,6 +4090,9 @@ const anthropicAuthPlugin = async ( ) if ( current.accountIdentity !== served.accountIdentity || + (target.hostMetadata?.restartCredential !== undefined && + cacheKeepCredential(current) !== + target.hostMetadata.restartCredential) || Boolean(current.scopedAttempt) !== Boolean(served.scopedAttempt) ) return undefined @@ -4170,6 +4113,12 @@ const anthropicAuthPlugin = async ( return rotatedHeaders }, prepareHeaders: async (headers, target, attempt) => { + await cacheKeepRestart.stagger(target, attempt.signal) + if ( + !cacheKeepRestart.active() || + !cacheKeepManager.isCurrentTarget(target) + ) + throw new CacheKeepWarmRefusal('stopped') // A remembered URL gets the same destination rule as a live request; // refuse it before any credential is authorized for the prewarm. if (!isAllowedOAuthDestination(target.url, modelGateway(target.url))) @@ -4188,8 +4137,11 @@ const anthropicAuthPlugin = async ( 'cachekeep', ) if ( - target.oauthAccountIdentity && - credential.accountIdentity !== target.oauthAccountIdentity + (target.oauthAccountIdentity && + credential.accountIdentity !== target.oauthAccountIdentity) || + (target.hostMetadata?.restartCredential !== undefined && + cacheKeepCredential(credential) !== + target.hostMetadata.restartCredential) ) throw new NativeAccountRefusal('credential-changed') const accessToken = credential.accessToken @@ -4212,15 +4164,16 @@ const anthropicAuthPlugin = async ( ]), ) if (parsedBody.speed === 'fast') addFastModeBetaHeader(headers) - const prepared = cacheKeepDiagnosticsRequests.get(target.id) - if (prepared) { - const { betas, betasHash } = await getCacheDiagnosticsBetas(headers) - prepared.betas = betas - prepared.betasHash = betasHash - } } catch { setOAuthHeaders(headers, accessToken) } + const betas = headers.get('anthropic-beta')?.split(',') ?? [] + headers.set( + 'anthropic-beta', + betas + .filter((beta) => beta.trim() !== CACHE_DIAGNOSTICS_BETA) + .join(','), + ) const finalCredential = await authorizeOAuth( accountId, @@ -4231,6 +4184,9 @@ const anthropicAuthPlugin = async ( ) if ( finalCredential.accountIdentity !== credential.accountIdentity || + (target.hostMetadata?.restartCredential !== undefined && + cacheKeepCredential(finalCredential) !== + target.hostMetadata.restartCredential) || Boolean(finalCredential.scopedAttempt) !== Boolean(credential.scopedAttempt) ) @@ -4296,6 +4252,12 @@ const anthropicAuthPlugin = async ( return { ok: true as const } }, }) + const cacheKeepRestart = adoptCacheKeepRestart(accountStoragePath, { + manager: cacheKeepManager, + read: () => nativeAccounts.read(), + allowUrl: (url) => isAllowedOAuthDestination(url, modelGateway(url)), + now: runtimeNow, + }) // Track one recovery round's kept source prefix as a second CacheKeep // target. It reuses the live prewarm path (same lead, same auth, same @@ -4747,6 +4709,12 @@ const anthropicAuthPlugin = async ( const dispose: NonNullable = async () => { holderRegistration?.close() profileHydrationShutdown.abort() + try { + await cacheKeepRestart.dispose() + await cacheKeepRegistry.dispose() + } catch { + logger.warn('cachekeep', 'failed to stop') + } while (profilePublications.size) await Promise.all([...profilePublications]) try { await closeOpenCodeScopedRuntime(accountStoragePath) @@ -4797,13 +4765,6 @@ const anthropicAuthPlugin = async ( error: error instanceof Error ? error.message : String(error), }) } - try { - cacheKeepManager.stop() - } catch (error) { - logger.warn('cachekeep', 'failed to stop', { - error: error instanceof Error ? error.message : String(error), - }) - } // Bounded: waits at most about a second for the recovery record's // pending write, so a restart right after a round keeps the record. try { @@ -6909,6 +6870,7 @@ const anthropicAuthPlugin = async ( stickyQuotaRetries.clear(sessionId) sessionCacheActivity.forget(sessionId) messageThreads.forget(sessionId) + cacheKeepRestart.forget(sessionId) fableFallbackManager.clearSession(sessionId) recoveryThinking.forgetSession(sessionId) dropSessionSourceWarms(sessionId) @@ -8272,6 +8234,7 @@ const anthropicAuthPlugin = async ( if (fableRequest) fableRequest.oauthAccountId = oauthAccountId if (fableRequest) fableRequest.subagent = subagentRequest let trackCacheKeepRequest: (() => void) | undefined + let acceptedCacheKeepBodyText: string | undefined const acceptedCacheAttempts = new WeakSet() const trackAcceptedRequest = (attempt: object, sentBody = body) => { if (init?.signal?.aborted) return @@ -8320,6 +8283,7 @@ const anthropicAuthPlugin = async ( ) { const bodyText = body trackCacheKeepRequest = () => { + if (!cacheKeepRestart.active()) return const cacheKeepStart = nowMs() const tracked = cacheKeepManager.track({ sessionId: relayAffinity, @@ -8332,8 +8296,17 @@ const anthropicAuthPlugin = async ( ttlMs: acceptedCacheTtlMs, oauthAccountId, oauthAccountIdentity: nativeAuthorization?.accountIdentity, + hostMetadata: { + restartCredential: + cacheKeepCredential(nativeAuthorization), + }, isSubagent: subagentRequest, }) + acceptedCacheKeepBodyText = tracked.tracked + ? bodyText + : undefined + if (!tracked.tracked && relayAffinity) + cacheKeepRestart.forget(relayAffinity) trace?.mark('cachekeep_track', { session: relayAffinity, ms: roundMs(nowMs() - cacheKeepStart), @@ -8960,6 +8933,7 @@ const anthropicAuthPlugin = async ( accountId: oauthAccountId, synthetic: laneStartRequest, cacheKeepBodyText: typeof body === 'string' ? body : undefined, + acceptedCacheKeepBodyText: () => acceptedCacheKeepBodyText, cacheKeepSignal: init?.signal, fableRequest, sourceCandidate: fableRequest?.sourceCandidate, @@ -12155,12 +12129,14 @@ const anthropicAuthPlugin = async ( dispose, // biome-ignore lint/suspicious/noExplicitAny: Plugin type doesn't include undocumented auth/hooks } as any + await cacheKeepRestart.restore() pluginTestHandles?.set(plugin, { drainDispatchWork, drainSidebarRouteWrites, primeManager, quotaManager, cacheKeepManager, + messageThreads, nativeAccounts, fableFallbackManager, resolveMainQuotaIdentity: resolveMainQuotaAccountIdentity, diff --git a/packages/opencode/src/oauth-destination.ts b/packages/opencode/src/oauth-destination.ts index c639c5976..060738806 100644 --- a/packages/opencode/src/oauth-destination.ts +++ b/packages/opencode/src/oauth-destination.ts @@ -6,6 +6,7 @@ import { createAnthropicOAuthFetch, createClaudeModelFetch, logger, + type RequestGzipLatch, requireAnthropicOAuthOrigin, } from '@cortexkit/anthropic-auth-core' @@ -147,6 +148,11 @@ export const fetchOAuth: typeof fetch = createAnthropicOAuthFetch(originOptions) */ export function fetchOAuthModel( gateway: ClaudeGateway | undefined | (() => ClaudeGateway | undefined), + requestGzipLatch?: RequestGzipLatch, ): typeof fetch { - return createClaudeModelFetch({ origin: () => originOptions(), gateway }) + return createClaudeModelFetch({ + origin: () => originOptions(), + gateway, + requestGzipLatch, + }) } diff --git a/packages/opencode/src/plugin-test-handles.ts b/packages/opencode/src/plugin-test-handles.ts index 040155a4a..4cdbd0949 100644 --- a/packages/opencode/src/plugin-test-handles.ts +++ b/packages/opencode/src/plugin-test-handles.ts @@ -3,6 +3,7 @@ import type { acquireNativeAccountRuntime, CacheKeepManager, CustodyStatusState, + MessageThreadTracker, PrimeManager, ProviderAccountUuid, QuotaManager, @@ -15,6 +16,7 @@ export interface PluginTestHandles { primeManager: PrimeManager quotaManager: QuotaManager cacheKeepManager: CacheKeepManager + messageThreads: MessageThreadTracker fableFallbackManager: FableFallbackManager resolveMainQuotaIdentity: ( accessToken: string, diff --git a/packages/opencode/src/tests/cachekeep-and-cache-diagnostics.integration.test.ts b/packages/opencode/src/tests/cachekeep-and-cache-diagnostics.integration.test.ts index f628f0a39..25a39d076 100644 --- a/packages/opencode/src/tests/cachekeep-and-cache-diagnostics.integration.test.ts +++ b/packages/opencode/src/tests/cachekeep-and-cache-diagnostics.integration.test.ts @@ -1,21 +1,29 @@ import { afterEach, beforeEach, describe, expect, mock, spyOn } from 'bun:test' -import { mkdtemp, readdir, readFile, rm } from 'node:fs/promises' +import { mkdtemp, readdir, readFile, rm, stat } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' +import { gunzipSync } from 'node:zlib' import { __setLogTestSink, type AccountStorage, CacheKeepManager, type CommandApplyRequest, type CommandApplyResult, + cacheKeepStoreDirectory, getDumpDirectory, isDumpEnabled, type LogTestRecord, + type MessageThreadTracker, + messageThreadBetas, + prepareMessageThreadRequest, + resetBillingHeaderCCH, resetCache1hState, resetDumpState, setLogLevel, + signRequestBody, tokenFingerprint, } from '@cortexkit/anthropic-auth-core' +import { MessageThreadTailStore } from '../../../core/src/message-thread-tail-store.ts' import { drainSidebarWrites } from '../sidebar-state' import { getPluginTestHandles } from './plugin-test-handles' import { @@ -86,6 +94,273 @@ function applyMenuAction( describe('auth.loader', () => { installLoaderSetup(testContext) + async function warmFixture() { + await useTempAccountFile( + bindPoolAccounts( + createFallbackStorage({ + routing: { mode: 'fallback-first' }, + refresh: { enabled: false }, + quota: { enabled: false }, + claudeCache: { enabled: true, mode: 'hybrid' }, + cacheKeep: { enabled: true, always: true }, + }), + ), + ) + } + + async function acceptRequest( + plugin: any, + sessionId: string, + text: string, + model = 'claude-opus-4-8', + ) { + const result = await plugin.auth.loader( + () => Promise.resolve({ ...syntheticMainHostAuth(), type: 'oauth' }), + { models: {} }, + ) + const response = await result.fetch(MESSAGES_URL, { + method: 'POST', + headers: { 'x-session-affinity': sessionId }, + body: JSON.stringify({ + model, + messages: [{ role: 'user', content: text }], + }), + }) + expect(response.status).toBe(200) + await response.text() + } + + test('OC1 records prefix usage for auto keep-warm pricing without a restart', async () => { + await warmFixture() + globalThis.fetch = mock( + withNativeAdmission(() => + Response.json({ + usage: { cache_read_input_tokens: 1500, input_tokens: 12 }, + }), + ), + ) as unknown as typeof fetch + const plugin = await getPlugin() + const sessionId = 'oc1-warm-prefix-usage' + await acceptRequest(plugin, sessionId, 'a priced prefix') + const handles = getPluginTestHandles(plugin) + await handles.drainDispatchWork() + expect( + handles.cacheKeepManager.trackedPolicyState(sessionId), + ).toMatchObject({ + prefixTokens: 1500, + inputTokens: 1512, + }) + }) + + test('OC1 restores an idle warm once per server and keeps its durable budget', async () => { + let now = Date.now() + Date.now = mock(() => now) + await warmFixture() + const warmBodies: string[] = [] + const directory = cacheKeepStoreDirectory( + process.env.OPENCODE_ANTHROPIC_AUTH_FILE!, + undefined, + 'opencode1', + ) + const readRecord = async () => { + const files = (await readdir(directory)).filter((name) => + name.endsWith('.json.gz'), + ) + expect(files).toHaveLength(1) + const path = join(directory, files[0]!) + if (process.platform !== 'win32') + expect((await stat(path)).mode & 0o777).toBe(0o600) + return JSON.parse(gunzipSync(await readFile(path)).toString()) + } + const reservations: unknown[] = [] + globalThis.fetch = mock( + withNativeAdmission(async (_input: unknown, init: RequestInit) => { + const body = String(init.body) + if (JSON.parse(body).max_tokens === 0) { + warmBodies.push(body) + reservations.push((await readRecord()).policyState) + } + return Response.json({ usage: { cache_read_input_tokens: 1500 } }) + }), + ) as unknown as typeof fetch + + const original = await getPlugin(undefined, '/original-project') + const sessionId = 'oc1-restart-warm' + await acceptRequest( + original, + sessionId, + 'a restartable prefix', + 'claude-opus-5-5', + ) + await getPluginTestHandles(original).drainDispatchWork() + await original.dispose() + testContext.livePlugins.delete(original) + const saved = await readRecord() + expect(saved).toMatchObject({ v: 1, id: sessionId }) + expect(saved.bodyText).toContain('a restartable prefix') + expect(saved.headers).toBeUndefined() + expect(saved.policyState.prefixTokens).toBe(1500) + + const plugins = await Promise.all([ + getPlugin(undefined, '/first-project'), + getPlugin(undefined, '/second-project'), + ]) + const managers = plugins.map( + (plugin) => getPluginTestHandles(plugin).cacheKeepManager, + ) + expect( + managers + .flatMap((manager) => manager.trackedSessions()) + .map(({ id }) => id), + ).toEqual([sessionId]) + now = saved.nextPrewarmAt + 1 + await Promise.all(managers.map((manager) => manager.tick())) + expect(warmBodies).toHaveLength(1) + expect(warmBodies[0]).toContain('a restartable prefix') + expect(reservations).toEqual([ + expect.objectContaining({ + warmsSinceLastRealRequest: 1, + pendingWarmCost: expect.any(Number), + }), + ]) + const owner = managers.findIndex((manager) => + manager.trackedRequest(sessionId), + ) + const close = async (plugin: any) => { + await plugin.dispose() + testContext.livePlugins.delete(plugin) + } + await close(plugins[owner]) + expect(managers[1 - owner]?.trackedRequest(sessionId)).toBeDefined() + await close(plugins[1 - owner]) + const updated = await readRecord() + expect(updated.policyState).toMatchObject({ warmsSinceLastRealRequest: 1 }) + expect(updated.policyState.warmCostSoFar).toBeGreaterThan(0) + expect(updated.cacheExpiresAt).toBeGreaterThan(saved.cacheExpiresAt) + const restarted = await getPlugin(undefined, '/third-project') + const restored = + getPluginTestHandles(restarted).cacheKeepManager.trackedPolicyState( + sessionId, + ) + expect(restored).toMatchObject({ + warmsSinceLastRealRequest: 1, + warmCostSoFar: updated.policyState.warmCostSoFar, + }) + }) + + test('OC1 reuses the previous full cache boundary after a thread restart', async () => { + await warmFixture() + const original = await getPlugin(undefined, '/original-thread-project') + const tracker = getPluginTestHandles(original).messageThreads + const session = `oc1-thread-${crypto.randomUUID()}` + const mark = { type: 'ephemeral', ttl: '1h' } + const text = (text: string, cache = false) => ({ + type: 'text', + text, + ...(cache && { cache_control: mark }), + }) + const body = { + model: 'claude-opus-4-8', + system: [text('system', true)], + messages: [{ role: 'user', content: [text('cached first turn', true)] }], + } + const input = { + session, + account: 'account', + credential: 'credential', + betas: messageThreadBetas(new Headers()), + } + const reply = { role: 'assistant', content: [text('answer')] } + const complete = (prepared: ReturnType) => + prepared.complete({ + messageId: 'msg_accepted', + reply, + stopped: true, + stopReason: 'end_turn', + }) + complete(tracker.prepare({ ...input, body })) + const second = { role: 'user', content: [text('next turn', true)] } + const continued = tracker.prepare({ + ...input, + body: { ...body, messages: [...body.messages, reply, second] }, + }) + expect(continued.decision.type).toBe('continue') + complete(continued) + + const store = new MessageThreadTailStore('opencode1') + try { + for (let attempt = 0; attempt < 20; attempt++) { + if ((await store.load(session))?.continued) break + await Bun.sleep(10) + } + expect(await store.load(session)).toMatchObject({ continued: true }) + expect( + await new MessageThreadTailStore('opencode2').load(session), + ).toBeUndefined() + await original.dispose() + testContext.livePlugins.delete(original) + const restarted = await getPlugin(undefined, '/restarted-thread-project') + const prepared = await prepareMessageThreadRequest( + getPluginTestHandles(restarted).messageThreads, + { + ...input, + headers: new Headers(), + bodyText: JSON.stringify({ + ...body, + messages: [ + { role: 'user', content: [text('cached first turn')] }, + reply, + { role: 'user', content: [text('next turn')] }, + reply, + { role: 'user', content: [text('new turn', true)] }, + ], + }), + cacheSlot: (outgoing) => + (outgoing.system as Record[])[0], + }, + ) + const outgoing = JSON.parse(prepared.bodyText) + expect(outgoing.thread).toEqual({ type: 'create' }) + expect(outgoing.messages[0].content[0].cache_control).toEqual(mark) + expect(outgoing.system[0].cache_control).toBeUndefined() + } finally { + store.changed(session, undefined, false) + await store.drain() + } + }) + + test('OC1 gzips eligible prewarms and rescues them with the same signed body', async () => { + let now = Date.now() + Date.now = mock(() => now) + await warmFixture() + const sends: Array<{ body: string; encoding: string | null }> = [] + globalThis.fetch = mock( + withNativeAdmission((_input: unknown, init: RequestInit) => { + const encoding = new Headers(init.headers).get('content-encoding') + const body = + encoding === 'gzip' + ? gunzipSync(init.body as Uint8Array).toString() + : String(init.body) + if (JSON.parse(body).max_tokens === 0) { + sends.push({ body, encoding }) + if (encoding === 'gzip') + return new Response('Unsupported content-encoding: gzip', { + status: 415, + }) + } + return Response.json({ usage: { cache_read_input_tokens: 1 } }) + }), + ) as unknown as typeof fetch + const plugin = await getPlugin() + await acceptRequest(plugin, 'oc1-gzip-warm', 'large prefix '.repeat(500)) + now += 55 * 60_000 + await getPluginTestHandles(plugin).cacheKeepManager.tick() + expect(sends.map(({ encoding }) => encoding)).toEqual(['gzip', null]) + const identityBody = sends[1]!.body + expect(await signRequestBody(identityBody)).toBe(identityBody) + expect(sends[0]?.body.trimEnd()).toBe(resetBillingHeaderCCH(identityBody)) + }) + test('OC1 routing-moved stops an old-account warm before the next real turn', async () => { let now = Date.now() Date.now = mock(() => now) @@ -1076,27 +1351,11 @@ describe('cache diagnostics', () => { ) }) - test('cache diagnostics records cachekeep prewarms and carries their provider id forward', async () => { + test('OC1 CacheKeep prewarms stay out of the cache diagnostics chain', async () => { let now = 1_000 - const intervals: Array<{ callback: () => unknown; ms: number }> = [] - const sentBodies: Record[] = [] + const sent: Array<{ body: Record; betas: string[] }> = [] const records: LogTestRecord[] = [] - let prewarmStartedFlag = false - let resolvePrewarmStarted: (() => void) | undefined - const prewarmStarted = new Promise((resolve) => { - resolvePrewarmStarted = () => { - prewarmStartedFlag = true - resolve() - } - }) Date.now = mock(() => now) as unknown as typeof Date.now - testContext.pluginRuntimeOverrides = { - setInterval: mock((callback: () => unknown, ms: number) => { - intervals.push({ callback, ms }) - return { unref() {} } as unknown as ReturnType - }) as unknown as typeof setInterval, - clearInterval: mock(() => {}) as unknown as typeof clearInterval, - } await useTempAccountFile( createFallbackStorage({ accounts: [], @@ -1109,9 +1368,11 @@ describe('cache diagnostics', () => { globalThis.fetch = mock( withNativeAdmission((_input: any, init: RequestInit) => { const body = JSON.parse(String(init.body)) as Record - sentBodies.push(body) + const betas = (new Headers(init.headers).get('anthropic-beta') ?? '') + .split(',') + .map((beta) => beta.trim()) + sent.push({ body, betas }) if (body.max_tokens === 0) { - resolvePrewarmStarted?.() return Promise.resolve( new Response(JSON.stringify(message('provider-warm-B')), { status: 200, @@ -1144,49 +1405,33 @@ describe('cache diagnostics', () => { } await (await result.fetch(MESSAGES_URL, request)).text() now += 55 * 60_000 - const cacheKeepTick = intervals.at(-1) - if (!cacheKeepTick) throw new Error('missing cachekeep interval') - cacheKeepTick.callback() - await Bun.sleep(20) - await prewarmStarted - expect(prewarmStartedFlag).toBe(true) - for ( - let attempt = 0; - attempt < 50 && - !records.some( - (record) => - record.channel === 'cache-diagnostics' && - record.message.includes('provider-warm-B'), - ); - attempt++ - ) { - await Bun.sleep(10) - } + await getPluginTestHandles(plugin).cacheKeepManager.tick() await (await result.fetch(MESSAGES_URL, request)).text() - const prewarmBody = sentBodies.find((body) => body.max_tokens === 0) - expect(prewarmBody?.diagnostics).toEqual({ - previous_message_id: 'provider-real-A', - }) - expect(sentBodies.at(-1)?.diagnostics).toEqual({ - previous_message_id: 'provider-warm-B', - }) - const prewarmRecord = records.find( - (record) => - record.channel === 'cache-diagnostics' && - record.message.includes('provider-warm-B'), + const warms = sent.filter(({ body }) => body.max_tokens === 0) + expect(warms).toHaveLength(1) + const diagnosticBeta = 'cache-diagnosis-2026-04-07' + expect(sent[0]?.betas).toContain(diagnosticBeta) + expect(sent[0]?.body.diagnostics).toEqual({ previous_message_id: null }) + expect(sent.at(-1)?.betas).toContain(diagnosticBeta) + const logged = records + .filter((record) => record.message.startsWith('MC-CACHE-DIAG ')) + .map((record) => record.message) + expect(logged.some((record) => record.includes('provider-real-A'))).toBe( + true, ) - expect(prewarmRecord).toBeDefined() - expect( - JSON.parse(prewarmRecord!.message.replace('MC-CACHE-DIAG ', '')), - ).toMatchObject({ - is_subagent: false, - ttl_sent: '1h', - previous_message_id: 'provider-real-A', - source: 'prewarm_cachekeep', - synthetic: true, - account_id: 'main', - betas_hash: expect.stringMatching(/^[0-9a-f]{16}$/), + expect({ + warmDiagnostics: warms[0]?.body.diagnostics, + warmOptIn: warms[0]?.betas.includes(diagnosticBeta), + nextDiagnostics: sent.at(-1)?.body.diagnostics, + warmRecords: logged.filter((record) => + record.includes('prewarm_cachekeep'), + ), + }).toEqual({ + warmDiagnostics: undefined, + warmOptIn: false, + nextDiagnostics: { previous_message_id: 'provider-real-A' }, + warmRecords: [], }) setLogLevel('info') }) diff --git a/packages/pi/src/stream.ts b/packages/pi/src/stream.ts index 0736c84ce..88718aeb0 100644 --- a/packages/pi/src/stream.ts +++ b/packages/pi/src/stream.ts @@ -528,12 +528,13 @@ const piCacheKeep = new PiCacheKeep( fetchImpl: fetchPiOAuth, // A keep-warm is a model request, so it follows the current gateway of // the target's own runtime. - fetchForTarget: (target) => - createPiOAuthModelFetch(() => - piClaudeGatewayFromMemory( - target.accountStoragePath ?? getPiAccountStoragePath(), - ), - ), + fetchForTarget: (target) => { + const storagePath = target.accountStoragePath ?? getPiAccountStoragePath() + return createPiOAuthModelFetch( + () => piClaudeGatewayFromMemory(storagePath), + getRequestGzipLatch(getRequestGzipLatchPath(storagePath)), + ) + }, loadStorage: async () => (await getPiNativeRuntime().view()).policyStorage, resolveSettings: resolvePiSettingsFromMemory, onTrackedSessionsChanged: (sessions) => diff --git a/packages/pi/src/tests/scoped-stream.test.ts b/packages/pi/src/tests/scoped-stream.test.ts index 5f526affa..4e2232771 100644 --- a/packages/pi/src/tests/scoped-stream.test.ts +++ b/packages/pi/src/tests/scoped-stream.test.ts @@ -5513,6 +5513,50 @@ async function sendPrimary( await response.text() } +test('Pi gzips eligible prewarms and rescues them with the same signed body', async () => { + const f = await fixture() + const sent: Array<{ encoding: string | null; body: string }> = [] + globalThis.fetch = Object.assign( + async (_input: Parameters[0], init?: RequestInit) => { + const encoding = new Headers(init?.headers).get('content-encoding') + const body = + encoding === 'gzip' + ? gunzipSync(init?.body as Uint8Array).toString() + : String(init?.body) + sent.push({ encoding, body }) + if (encoding === 'gzip') + return new Response('Unsupported content-encoding: gzip', { + status: 415, + }) + return Response.json({ usage: { cache_read_input_tokens: 1 } }) + }, + { preconnect: originalFetch.preconnect }, + ) + const result = await __prewarmPiCacheKeepForTest({ + sessionId: 'pi-gzip-warm', + url: 'https://api.anthropic.com/v1/messages?beta=true', + headers: new Headers(), + bodyText: JSON.stringify({ + model: model.id, + max_tokens: 128, + system: [ + { + type: 'text', + text: 'stable prefix '.repeat(500), + cache_control: { type: 'ephemeral' }, + }, + ], + messages: [{ role: 'user', content: 'warm' }], + }), + oauthAccountId: 'main', + oauthAccountIdentity: fixtureAccountIdentity('main'), + accountStoragePath: f.path, + }) + expect(result.ok).toBe(true) + expect(sent.map(({ encoding }) => encoding)).toEqual(['gzip', null]) + expect(sent[0]?.body.trimEnd()).toBe(sent[1]?.body) +}) + test('Pi sends model and keep-warm requests to the gateway as full uncompressed requests', async () => { const f = await fixture() const sent = recordSends() diff --git a/packages/pi/src/transport.ts b/packages/pi/src/transport.ts index b903455ae..01647b0b6 100644 --- a/packages/pi/src/transport.ts +++ b/packages/pi/src/transport.ts @@ -10,6 +10,7 @@ import { createAnthropicOAuthFetch, createClaudeModelFetch, type IncompleteStreamDiagnostics, + type RequestGzipLatch, requireAnthropicOAuthOrigin, } from '@cortexkit/anthropic-auth-core' @@ -155,6 +156,11 @@ export async function fetchPiStreamResponse( */ export function createPiOAuthModelFetch( gateway: () => ClaudeGateway | undefined, + requestGzipLatch?: RequestGzipLatch, ): typeof fetch { - return createClaudeModelFetch({ origin: PI_OAUTH_ORIGIN, gateway }) + return createClaudeModelFetch({ + origin: PI_OAUTH_ORIGIN, + gateway, + requestGzipLatch, + }) } From 219290ab260ce7868679aa1e4490d1dbbc741e48 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:36:49 +0100 Subject: [PATCH 06/27] Pi /claude: quota refresh, limit editors and lane start, as on OpenCode --- CHANGELOG.md | 2 + docs/accounts-and-routing.md | 2 +- docs/cache.md | 2 +- docs/commands.md | 6 +- docs/features.md | 6 +- packages/core/src/native-menu-model.ts | 28 +-- packages/core/src/start.ts | 2 + .../src/tests/native-menu-executor.test.ts | 22 +- .../core/src/tests/native-menu-model.test.ts | 105 ++++++---- packages/core/src/tests/native-ui.test.ts | 26 +-- packages/opencode/src/lane-start.ts | 4 +- packages/pi/src/commands.ts | 16 +- packages/pi/src/convert.ts | 16 ++ packages/pi/src/native-commands.ts | 15 +- packages/pi/src/tests/commands.test.ts | 64 +++++- packages/pi/src/tests/prime.test.ts | 196 +++++++++++++++++- 16 files changed, 377 insertions(+), 135 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 731ed9593..938fdc7fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,8 @@ This repo is a CortexKit-maintained Anthropic auth monorepo for OpenCode and Pi. - OpenCode 1 on Thalamus now asks for the shared login choice in every routing mode and when switching logins on a retry, like OpenCode 2. - OpenCode 1 on Thalamus now reports when a request starts waiting for routing or quota, like OpenCode 2; OpenCode still handles the wait. - OpenCode 1 on Thalamus now reports which login paid for each Claude send and how many tokens it used, including relayed sends and keep-warm requests, like OpenCode 2. +- Pi: `/claude` can now refresh quota and edit quota floors, like OpenCode 1 and 2. +- Pi: `/claude` can now start a five-hour quota window with a one-time request, like OpenCode 1 and 2. ## 2.16.5 diff --git a/docs/accounts-and-routing.md b/docs/accounts-and-routing.md index 5272d2345..254bcc414 100644 --- a/docs/accounts-and-routing.md +++ b/docs/accounts-and-routing.md @@ -48,7 +48,7 @@ Quota figures use the shared wording, such as `5h 40% left, resets 2h29m` and `7 - A positive five-hour or seven-day floor blocks missing readings for that window regardless of `failClosedOnUnknownQuota`. - A positive `scoped` minimum-remaining percentage blocks missing model-specific quota information. An explicitly empty scoped-window list means no separate window applies. -- OpenCode can edit killswitch thresholds in **Limits**; Pi does not expose those edits. +- OpenCode and Pi can edit killswitch thresholds in **Limits**. The optional `quota_header_feed_enabled` setting is OpenCode-only, disabled by default and requires restart. It publishes allowlisted quota observations, opaque identity and timestamps to owner-only temporary lease files, not tokens, request bodies, model IDs or refresh errors. It shares observations already obtained from responses rather than making new quota API requests. diff --git a/docs/cache.md b/docs/cache.md index 7ef808dac..1503ca093 100644 --- a/docs/cache.md +++ b/docs/cache.md @@ -49,7 +49,7 @@ When content-filter recovery switches a session to Opus 4.8 temporarily, the ori Prime is opt-in quota-window priming. The **Extras** group in OpenCode and Pi can enable or disable it and shows each account's next due time and last result. In OpenCode 1 and 2, Prime runs without waiting for a chat request and picks up changes to `prime_enabled` in the shared settings file without a restart. After a confirmed five-hour reset, Prime checks fresh quota and limits, then approximately one minute after reset can send a minimal `claude-haiku-4-5` request. Cross-process claims prevent duplicate priming for the same verified Claude account/reset, even when OpenCode and Pi (or two OpenCode installs) use separate account files. Accounts without a verified identity are deduplicated only within the same account storage. This is a real request, not a quota API trick or a guarantee of free usage. Prime does not create a message thread or register a cache for keepalive. It stops when the host shuts down. -OpenCode's **Fire lane start** is an explicit one-shot action. It inserts a visible synthetic lane-start marker and runs a one-token request through normal routing, custody, limits, cache shaping and transport. It is also billed usage; it neither enables Prime nor installs an automatic schedule. Pi does not expose lane start. +In OpenCode and Pi, **Fire lane start** is an explicit one-shot action. It inserts a visible synthetic lane-start marker in the conversation and runs a one-token request through normal routing, custody, limits, cache shaping and transport. This warms the session's prompt cache for the next turn and counts as billed usage. It neither enables Prime nor installs an automatic schedule. ## Diagnostics and history analysis diff --git a/docs/commands.md b/docs/commands.md index 5cc385d53..fa995e50d 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -7,12 +7,12 @@ Both hosts register one `/claude` command. It opens a menu whose actions collect | Group | What it offers | Host differences | | --- | --- | --- | | Accounts | Account status, enable/disable, remove/reorder, reset backoff, OAuth/API-key additions, custody guidance and disconnect | Actions depend on custody | -| Quota | Quota summary and refresh | Pi shows summary only | +| Quota | Quota summary and refresh | Both hosts | | Routing | Mode selection and reset current session | Both hosts | -| Limits | Killswitch enable/disable and thresholds | OpenCode only | +| Limits | Killswitch enable/disable and thresholds | Both hosts | | Cache | Cache mode, enable/disable, keepalive schedule and subagent setting | Both hosts | | Diagnostics | Request dumps and logging level | Both hosts | -| Extras | Fast mode, Prime status/toggle and lane start | Both hosts have fast mode and Prime status/toggles; Pi has no lane start | +| Extras | Fast mode, Prime status/toggle and **Fire lane start** to warm the current session | Both hosts | In local custody, Accounts offers local management and enrollment reset, not disconnect. While enrolled, only enable/disable, reset backoff and disconnect remain. Unreadable enrollment keeps that reduced set so disconnect is available. **Custody setup guidance** explains the stopped-host requirement without changing custody. diff --git a/docs/features.md b/docs/features.md index defbb4049..a7ada013e 100644 --- a/docs/features.md +++ b/docs/features.md @@ -12,9 +12,9 @@ | Default pool | `~/.config/opencode/anthropic-auth-pool.json` | `~/.pi/agent/anthropic-auth-pool.json` | | Legacy migration source | `~/.config/opencode/anthropic-auth.json` | `~/.pi/agent/anthropic-auth.json` | | Accounts, routing, cache and diagnostics controls | `/claude` menu | `/claude` menu | -| Quota refresh and killswitch edits | Menu actions | Summary only; no killswitch edits | +| Quota refresh and killswitch edits | Menu actions | Menu actions | | Prime quota-window scheduler | Status and on/off actions | Status and on/off actions | -| Lane start | Menu action | Not available | +| Lane start | **Fire lane start** warms the current session | **Fire lane start** warms the current session | | Quota sidebar | OpenCode 1 and OpenCode 2 TUI | Not available | | Cloudflare relay | HTTP; OpenCode 1 also supports WebSocket | HTTP or WebSocket | @@ -28,7 +28,7 @@ CortexKit adds account and request controls beyond OpenCode's or Pi's single bui - **Fallback accounts and quota-aware routing:** ordered OAuth accounts and API-key routes, minimum remaining-quota thresholds, and `sticky-balanced` session affinity. See [accounts](accounts-and-routing.md) and the [routing reference](configuration.md#fallback-accounts-and-session-affinity). - **Cache controls:** explicit, automatic or hybrid prompt-cache placement, optional keepalive, and opt-in quota-window priming. [Cache controls](cache.md) explain the schedules and billed synthetic requests. -- **Quota visibility and limits:** per-account status, OpenCode quota refresh and killswitch thresholds, the quota sidebar, and OpenCode 1's optional sanitized [quota header feed](configuration.md#quota-header-feed). +- **Quota visibility and limits:** per-account status, quota refresh and killswitch thresholds in OpenCode and Pi, the OpenCode quota sidebar, and OpenCode 1's optional sanitized [quota header feed](configuration.md#quota-header-feed). - **Model controls:** adaptive reasoning summaries, effort levels, fast mode and OpenCode 1 safety fallback. See [models](models.md) and [safety fallback](request-rewriting.md#safety-fallback-opencode-1). - **Optional custody and transport:** Claustrum is a local credential-vault service that can supply accounts instead of the local pool; a user-owned Cloudflare Worker can relay request bodies. See [vault custody](vault.md) and [transports](transports.md). - **Claude-compatible request shaping:** identity and billing headers, final-body signing, tool replay and prompt-cache placement. See [request rewriting](request-rewriting.md#request-rewriting). diff --git a/packages/core/src/native-menu-model.ts b/packages/core/src/native-menu-model.ts index b34e34462..e3540fe36 100644 --- a/packages/core/src/native-menu-model.ts +++ b/packages/core/src/native-menu-model.ts @@ -745,13 +745,6 @@ function offeredUnder( : !isNativeMenuLocalCustodyAction(id) } -function hostOffers(host: NativeMenuHost, action: NativeMenuAction): boolean { - return ( - host === 'opencode' || - !['quota', 'killswitch', 'start'].includes(action.command) - ) -} - function buildModel( host: NativeMenuHost, custody: NativeMenuCustodyMode, @@ -765,17 +758,11 @@ function buildModel( actions: Object.freeze( actions.filter( (action) => - action.group === id && - hostOffers(host, action) && - offeredUnder(custody, action.id), + action.group === id && offeredUnder(custody, action.id), ), ), statuses: Object.freeze( - statuses.filter( - (status) => - status.group === id && - (host === 'opencode' || status.command !== 'killswitch'), - ), + statuses.filter((status) => status.group === id), ), }), ), @@ -794,22 +781,15 @@ const models = Object.freeze({ }), }) -const actionLists = Object.freeze({ - opencode: Object.freeze( - actions.filter((action) => hostOffers('opencode', action)), - ), - pi: Object.freeze(actions.filter((action) => hostOffers('pi', action))), -}) - /** * Every action the host supports under either custody mode, in menu order. * Request checking uses this list so it can recognise an action the current * custody mode no longer offers and refuse it by name. */ export function listNativeMenuActions( - host: NativeMenuHost, + _host: NativeMenuHost, ): readonly NativeMenuAction[] { - return actionLists[host] + return actions } /** diff --git a/packages/core/src/start.ts b/packages/core/src/start.ts index dcf7fdf4c..fb5dfe68f 100644 --- a/packages/core/src/start.ts +++ b/packages/core/src/start.ts @@ -1,4 +1,6 @@ export const CLAUDE_START_COMMAND_NAME = 'claude-start' +export const LANE_START_TEXT = + '[lane start] — automated cache warm; no response needed.' const START_STATUS_TITLE = '## Claude Lane Start Status' const START_QUEUED_TITLE = '## Claude Lane Start Queued' diff --git a/packages/core/src/tests/native-menu-executor.test.ts b/packages/core/src/tests/native-menu-executor.test.ts index 39f3b6c25..95fd88a5a 100644 --- a/packages/core/src/tests/native-menu-executor.test.ts +++ b/packages/core/src/tests/native-menu-executor.test.ts @@ -491,28 +491,8 @@ test('dispatched requests are fresh copies, not the caller objects', async () => ]) }) -test('actions the host does not offer and unknown actions are refused', async () => { - const unavailable = hostActionIds('opencode').filter( - (id) => !hostActionIds('pi').includes(id), - ) - expect(unavailable.sort()).toEqual( - ( - [ - 'quota-refresh', - 'killswitch-on', - 'killswitch-off', - 'killswitch-set', - 'start-fire', - ] satisfies NativeMenuActionId[] - ).sort(), - ) +test('unknown actions are refused', async () => { const { calls, executor } = harness('pi') - for (const id of unavailable) { - expect(await executor.execute(samples[id], full)).toEqual({ - status: 'refused', - code: 'unsupported-action', - }) - } for (const action of [ 'nope', 'status', diff --git a/packages/core/src/tests/native-menu-model.test.ts b/packages/core/src/tests/native-menu-model.test.ts index 90a40d9b6..d095e79e2 100644 --- a/packages/core/src/tests/native-menu-model.test.ts +++ b/packages/core/src/tests/native-menu-model.test.ts @@ -646,6 +646,15 @@ const fixture: Record< true, 'packages/core/src/commands/account.ts:AccountCommandAction:13-32; packages/pi/src/commands.ts:claude-account:272-366', ], + [ + 'quota-refresh', + 'quota', + 'Quota', + [], + false, + false, + 'packages/pi/src/native-commands.ts:createPiNativeCommands', + ], [ 'routing-mode', 'routing', @@ -673,6 +682,33 @@ const fixture: Record< false, 'packages/core/src/routing.ts:MaxSameAccountWait', ], + [ + 'killswitch-on', + 'killswitch', + 'Limits', + [], + false, + false, + 'packages/pi/src/native-commands.ts:createPiNativeCommands', + ], + [ + 'killswitch-off', + 'killswitch', + 'Limits', + [], + false, + false, + 'packages/pi/src/native-commands.ts:createPiNativeCommands', + ], + [ + 'killswitch-set', + 'killswitch', + 'Limits', + ['entries:limit-entries!=account|fh|sd|scoped?'], + false, + false, + 'packages/pi/src/native-commands.ts:createPiNativeCommands', + ], [ 'cache-on', 'cache', @@ -799,6 +835,15 @@ const fixture: Record< false, 'packages/pi/src/native-commands.ts:createPiNativeCommands', ], + [ + 'start-fire', + 'start', + 'Extras', + [], + false, + false, + 'packages/pi/src/native-commands.ts:createPiNativeCommands', + ], ], statuses: [ [ @@ -828,6 +873,15 @@ const fixture: Record< false, 'packages/core/src/routing.ts:RoutingCommandAction:22,25; packages/pi/src/commands.ts:claude-routing:231-256', ], + [ + 'killswitch-status', + 'killswitch', + 'Limits', + [], + false, + false, + 'packages/pi/src/native-commands.ts:createPiNativeCommands', + ], [ 'cache-status', 'cache', @@ -887,12 +941,14 @@ const fixture: Record< 'account', 'quota', 'routing', + 'killswitch', 'cache', 'cachekeep', 'dump', 'logging', 'fast', 'prime', + 'start', ], destructive: ['remove', 'enrollment-reset'], interactive: [ @@ -971,7 +1027,7 @@ for (const host of ['opencode', 'pi'] as const) { expect(actualStatuses).toEqual( fixture[host].statuses.map((row) => row.slice(0, 6)), ) - expect(actual).toHaveLength(host === 'opencode' ? 33 : 28) + expect(actual).toHaveLength(33) const families: string[] = [ ...new Set( [...allActions(host), ...statuses].map( @@ -980,7 +1036,7 @@ for (const host of ['opencode', 'pi'] as const) { ), ] expect(families.sort()).toEqual([...fixture[host].families].sort()) - expect(families).toHaveLength(host === 'opencode' ? 11 : 9) + expect(families).toHaveLength(11) for (const row of [...fixture[host].actions, ...fixture[host].statuses]) { expect(row[6]).toMatch(/packages\/.+\.ts:[A-Za-z]/) } @@ -991,44 +1047,13 @@ for (const host of ['opencode', 'pi'] as const) { }) } -test('Pi offers Prime toggles but no Limits, quota refresh or start actions', () => { - const pi = getNativeMenuModel('pi', 'local') - expect(pi.groups.find((group) => group.id === 'Limits')).toEqual({ - id: 'Limits', - actions: [], - statuses: [], - }) - expect( - allActions('pi').filter((action) => - ['quota', 'killswitch', 'start'].includes(action.command), - ), - ).toEqual([]) - expect( - allActions('pi') - .filter((action) => action.command === 'prime') - .map((action) => action.id), - ).toEqual(['prime-on', 'prime-off']) - expect( - pi.groups - .flatMap((group) => group.statuses) - .filter((status) => ['prime', 'quota'].includes(status.command)) - .map((status) => status.id), - ).toEqual(['quota-status', 'prime-status']) - expect( - allActions('opencode') - .filter((action) => - ['quota', 'killswitch', 'prime', 'start'].includes(action.command), - ) - .map((action) => action.id), - ).toEqual([ - 'quota-refresh', - 'killswitch-on', - 'killswitch-off', - 'killswitch-set', - 'prime-on', - 'prime-off', - 'start-fire', - ]) +test('Pi and OpenCode offer the same Quota, Limits and Extras controls in both custody modes', () => { + const groups = (host: NativeMenuHost, custody: 'local' | 'claustrum') => + getNativeMenuModel(host, custody).groups.filter((group) => + ['Quota', 'Limits', 'Extras'].includes(group.id), + ) + for (const custody of ['local', 'claustrum'] as const) + expect(groups('pi', custody)).toEqual(groups('opencode', custody)) }) test('destructive actions require non-empty confirmation for removal and enrollment reset', () => { diff --git a/packages/core/src/tests/native-ui.test.ts b/packages/core/src/tests/native-ui.test.ts index a030909be..947fabc5a 100644 --- a/packages/core/src/tests/native-ui.test.ts +++ b/packages/core/src/tests/native-ui.test.ts @@ -83,13 +83,6 @@ const invocation = { sessionId: 'conversation-1', notify() {} } const localCustody = async () => 'local' as const /** These tests never select disconnect; return 'idle' if the callback is invoked. */ const unusedDisconnect = async () => 'idle' as const -const piUnavailable = [ - 'quota-refresh', - 'killswitch-on', - 'killswitch-off', - 'killswitch-set', - 'start-fire', -] function applyFixture( menu: CommandMenu, @@ -368,13 +361,7 @@ describe('native UI contract', () => { payload.menu.sections.flatMap((section) => section.actions.map((action) => action.id), ), - ).toEqual( - Object.keys(fixtures).filter( - (id) => - (host === 'opencode' || !piUnavailable.includes(id)) && - id !== 'vault-disconnect', - ), - ) + ).toEqual(Object.keys(fixtures).filter((id) => id !== 'vault-disconnect')) const actions = payload.menu.sections.flatMap( (section) => section.actions, ) @@ -419,7 +406,7 @@ describe('native UI contract', () => { 'account:conversation-1', 'quota:conversation-1', 'routing:conversation-1', - ...(host === 'opencode' ? ['killswitch:conversation-1'] : []), + 'killswitch:conversation-1', 'cache:conversation-1', 'cachekeep:conversation-1', 'dump:conversation-1', @@ -429,7 +416,6 @@ describe('native UI contract', () => { ]) }) for (const actionId of Object.keys(fixtures) as NativeMenuActionId[]) { - if (host === 'pi' && piUnavailable.includes(actionId)) continue // This loop covers local accounts. Separate disconnect tests check hosts // with vault enrollment and every disconnect outcome. if (actionId === 'vault-disconnect') continue @@ -482,14 +468,6 @@ describe('native UI contract', () => { expect(calls).toEqual([]) }) - test('Pi cannot dispatch OpenCode-only capabilities', async () => { - const { calls, apply } = setup('pi') - for (const action of piUnavailable as NativeMenuActionId[]) { - expect((await apply(action)).ok).toBe(false) - } - expect(calls).toEqual([]) - }) - test('forged sections, items, aliases and cross-session requests never dispatch', async () => { const { calls, apply } = setup() for (const patch of [ diff --git a/packages/opencode/src/lane-start.ts b/packages/opencode/src/lane-start.ts index a6b0c5999..1dc18af6e 100644 --- a/packages/opencode/src/lane-start.ts +++ b/packages/opencode/src/lane-start.ts @@ -1,7 +1,7 @@ +import { LANE_START_TEXT } from '@cortexkit/anthropic-auth-core' import { resolvePromptContext } from './prompt-context' -export const LANE_START_TEXT = - '[lane start] — automated cache warm; no response needed.' +export { LANE_START_TEXT } export const LANE_START_REQUEST_HEADER = 'x-cortexkit-lane-start' const MAX_PENDING_MESSAGE_IDS = 1_000 diff --git a/packages/pi/src/commands.ts b/packages/pi/src/commands.ts index 9e60fa488..e2ee95a5b 100644 --- a/packages/pi/src/commands.ts +++ b/packages/pi/src/commands.ts @@ -2,6 +2,7 @@ import { join } from 'node:path' import { createNativeUi, disconnectNativeVaultForHost, + LANE_START_TEXT, type NativeMenuCommandId, type NativeMenuDispatch, type NativeUiOptions, @@ -13,7 +14,9 @@ import { type ExtensionAPI, getAgentDir } from '@earendil-works/pi-coding-agent' /** Backend callbacks use native authority; the renderer never receives credentials. */ export interface PiNativeCommands { - dispatch: NativeMenuDispatch + dispatch: ( + ...args: [...Parameters, queueLaneStart?: () => void] + ) => ReturnType readStatus: ( command: Exclude, invocation: { sessionId?: string }, @@ -60,9 +63,18 @@ export function registerCommands(pi: ExtensionAPI, backend: PiNativeCommands) { return } const disconnect = backend.disconnectVault ?? disconnectPi + const queueLaneStart = () => { + if ( + ctx.model?.provider !== 'anthropic' || + ctx.model.api !== 'anthropic-messages' + ) + throw new Error('Lane start requires an active Claude model') + pi.sendUserMessage(LANE_START_TEXT, { deliverAs: 'followUp' }) + } const menu = createNativeUi({ host: 'pi', - dispatch: backend.dispatch, + dispatch: (request, options) => + backend.dispatch(request, options, queueLaneStart), readStatus: backend.readStatus, readAccounts: backend.readAccounts, readMode: diff --git a/packages/pi/src/convert.ts b/packages/pi/src/convert.ts index e39b37786..5227f79f5 100644 --- a/packages/pi/src/convert.ts +++ b/packages/pi/src/convert.ts @@ -27,6 +27,7 @@ import { isClaudeSonnet55Model, isFastModeSupportedModel, isOpenAIReasoningSignature, + LANE_START_TEXT, orderClaudeCodeBody, readSessionCachePolicy, requestCacheLifetimeMs, @@ -802,6 +803,17 @@ export async function buildAnthropicRequest( systemPrompt: getCurrentSystemPrompt(transcript.messages), tools: getCurrentTools(transcript.messages), } + // Pi delivers extension prompts as ordinary user messages. Only the exact + // marker as the newest user message is a lane start; older markers are history. + const userContent = context.messages.findLast( + (message) => message.role === 'user', + )?.content + const laneStart = + typeof userContent === 'string' + ? userContent === LANE_START_TEXT + : userContent?.length === 1 && + userContent[0]?.type === 'text' && + userContent[0].text === LANE_START_TEXT // Conversion can discard opaque or incomplete blocks. Check context.messages // first so those losses cannot hide a meaningful final assistant turn. Check // the Anthropic messages again after conversion removes empty user messages. @@ -1014,6 +1026,10 @@ export async function buildAnthropicRequest( : undefined if (replaced !== undefined) body = { ...(replaced as AnthropicRequestBody), stream: true } + if (laneStart) { + body.max_tokens = 1 + delete body.thinking + } applySessionCacheTtl(body, cachePolicy?.ttl) if (baseBoundary >= 0) applyForkCacheBridge(body, baseBoundary) // As in Pi's native adapter, replacements must still request SSE. Hooks own diff --git a/packages/pi/src/native-commands.ts b/packages/pi/src/native-commands.ts index 80efc3c78..df467942d 100644 --- a/packages/pi/src/native-commands.ts +++ b/packages/pi/src/native-commands.ts @@ -28,7 +28,6 @@ import { isVaultHosted, logger, type NativeAccountSnapshot, - type NativeMenuDispatch, type NativeMenuKillswitchEntry, type NativeSettingsWriteResult, nativeAccountCanServe, @@ -93,7 +92,11 @@ export function createPiNativeCommands( } }) } - const dispatch: NativeMenuDispatch = async (request, options) => { + const dispatch: PiNativeCommands['dispatch'] = async ( + request, + options, + queueLaneStart, + ) => { const runtime = await native.service() await runtime.prepareSettingsAction?.() if ( @@ -370,10 +373,10 @@ export function createPiNativeCommands( return result } case 'start-fire': - return { - ok: false, - text: 'Pi has no lane-start action.', - } + options.signal?.throwIfAborted() + if (!queueLaneStart) throw new Error('Pi cannot queue a lane start') + queueLaneStart() + return { ok: true, text: 'Claude lane start queued in this session.' } } } return { diff --git a/packages/pi/src/tests/commands.test.ts b/packages/pi/src/tests/commands.test.ts index a119297c9..a132cfc6f 100644 --- a/packages/pi/src/tests/commands.test.ts +++ b/packages/pi/src/tests/commands.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, test } from 'bun:test' +import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test' import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -275,6 +275,68 @@ describe('native diagnostics persistence', () => { expect(text).toContain('checked 2d ago') }) + test('Pi /claude offers quota refresh and persists quota floor edits in shared settings', async () => { + const groups = ['Quota', 'Limits'] + const seen = new Map() + const { commands, ctx } = registration(undefined, { + async select(title: string, choices: string[]) { + if (title === 'Claude') { + const group = groups.shift() + return choices.find((choice) => group && choice.startsWith(group)) + } + seen.set(title.split('\n')[0] ?? '', choices) + return undefined + }, + }) + await commands.get('claude')?.handler('', ctx) + await commands.get('claude')?.handler('', ctx) + expect([...seen]).toEqual([ + ['Quota', expect.arrayContaining(['Refresh quota'])], + [ + 'Limits', + expect.arrayContaining([ + 'Enable killswitch', + 'Disable killswitch', + 'Set killswitch thresholds', + ]), + ], + ]) + + const { execute } = controller() + const runtime = await getPiNativeRuntime(storagePath).service() + const fetchQuota = spyOn(runtime, 'fetchQuota').mockResolvedValue({}) + const fetchProfile = spyOn(runtime, 'fetchProfile').mockResolvedValue({ + tier: 'max', + orgType: 'individual', + checkedAt: Date.now(), + }) + try { + expect(await execute({ action: 'quota-refresh' })).toMatchObject({ + status: 'executed', + ok: true, + }) + expect(fetchQuota.mock.calls.map(([id]) => id)).toContain('fallback') + } finally { + fetchQuota.mockRestore() + fetchProfile.mockRestore() + } + const entry = { account: 'fallback', fh: 10, sd: 20, scoped: 5 } + for (const request of [ + { action: 'killswitch-on' }, + { action: 'killswitch-set', values: { entries: [entry] } }, + { action: 'killswitch-off' }, + ] satisfies NativeMenuRequest[]) { + expect(await execute(request)).toMatchObject({ + status: 'executed', + ok: true, + }) + } + expect((await readNativePiFixture(storagePath)).killswitch).toMatchObject({ + enabled: false, + accounts: { fallback: { five_hour: 10, seven_day: 20, scoped: 5 } }, + }) + }) + test('Ultra quota status shows only weekly and Fable limits through Core', async () => { const checkedAt = Date.now() await saveNativePiFixture( diff --git a/packages/pi/src/tests/prime.test.ts b/packages/pi/src/tests/prime.test.ts index 03f8b1ec6..7dea1c10b 100644 --- a/packages/pi/src/tests/prime.test.ts +++ b/packages/pi/src/tests/prime.test.ts @@ -5,18 +5,30 @@ import { join } from 'node:path' import { gunzipSync } from 'node:zlib' import { type AccountStorage, + PROMPT_CACHE_DEFAULT_TTL_MS, PrimeManager, primeAccountMarkerDir, primeMarkerPath, resolveNativePoolPaths, + StickySessionRouter, + sessionCacheActivity, signRequestBody, + stickyRouteFamilyForModel, tokenFingerprint, } from '@cortexkit/anthropic-auth-core' -import type { ExtensionAPI } from '@earendil-works/pi-coding-agent' +import type { + ExtensionAPI, + ExtensionCommandContext, +} from '@earendil-works/pi-coding-agent' +import { registerCommands } from '../commands.ts' import cortexKitPiAnthropicAuth from '../index.ts' import { closePiNativeRuntime, getPiNativeRuntime } from '../native.ts' import { createPiNativeCommands } from '../native-commands.ts' -import { getPiTrackedCacheKeepSessions, sendPiPrimeRequest } from '../stream.ts' +import { + getPiTrackedCacheKeepSessions, + sendPiPrimeRequest, + streamCortexKitAnthropic, +} from '../stream.ts' import { saveNativePiFixture } from './native-fixture.ts' const originalFetch = globalThis.fetch @@ -94,13 +106,17 @@ beforeEach(async () => { ) expect(request.redirect).toBe('error') const bytes = Buffer.from(await request.arrayBuffer()) - sends.push({ - headers: request.headers, - text: (request.headers.get('content-encoding') === 'gzip' + const text = ( + request.headers.get('content-encoding') === 'gzip' ? gunzipSync(bytes) : bytes - ).toString(), - }) + ).toString() + sends.push({ headers: request.headers, text }) + if (JSON.parse(text).stream) { + return new Response('data: {"type":"message_stop"}\n\n', { + headers: { 'content-type': 'text/event-stream' }, + }) + } return Response.json({ usage: { input_tokens: 17, output_tokens: 1 } }) }, { preconnect: originalFetch.preconnect }, @@ -207,6 +223,172 @@ test('Pi Prime enabled with a due account fires once through the signed model tr expect([...timeouts.values()].map((timer) => timer.ms)).toEqual([90_000]) }) +test('Pi /claude queues lane start as a visible turn that warms the session cache', async () => { + const native = await fixture(false, { + routing: { mode: 'sticky-balanced' }, + accounts: [ + { + id: 'fallback', + type: 'oauth', + access: 'sk-ant-oat01-fallback-access', + refresh: 'fallback-refresh', + expires: now + 3_600_000, + }, + ], + }) + const modelId = 'claude-sonnet-5-5' + const sessionId = 'lane-start-session' + const router = new StickySessionRouter({ path: await native.routingPath() }) + expect( + await router.resolve({ + sessionId, + modelId, + family: stickyRouteFamilyForModel(modelId), + affinityModelId: modelId, + candidates: [ + { accountId: 'fallback', order: 1, quota: { kind: 'unknown' } }, + ], + retainAccountIds: new Set(['fallback']), + inputBytes: 1, + storage: (await native.view()).policyStorage, + }), + ).toMatchObject({ accountId: 'fallback' }) + await router.drain() + + const commands = new Map< + string, + Parameters[1] + >() + const queued: Parameters[] = [] + registerCommands( + { + registerCommand: ( + name: string, + definition: Parameters[1], + ) => commands.set(name, definition), + sendUserMessage: ( + ...args: Parameters + ) => { + queued.push(args) + }, + } as unknown as ExtensionAPI, + createPiNativeCommands(storagePath), + ) + async function invoke(model?: ExtensionCommandContext['model']) { + const notices: string[] = [] + let picked = false + await commands.get('claude')?.handler('', { + model, + hasUI: true, + sessionManager: { getSessionId: () => sessionId }, + ui: { + notify: (text: string) => notices.push(text), + async select(title: string, choices: string[]) { + if (picked) return undefined + if (title === 'Claude') + return choices.find((choice) => choice.startsWith('Extras')) + picked = true + return choices.find((choice) => choice === 'Fire lane start') + }, + }, + } as unknown as ExtensionCommandContext) + return notices.join('\n') + } + + const refusal = await invoke() + expect(refusal).toBeTruthy() + expect(refusal).not.toContain('Claude lane start queued in this session.') + expect(queued).toHaveLength(0) + expect(sends).toHaveLength(0) + + const model: NonNullable = { + id: modelId, + name: 'Claude Sonnet 5.5', + api: 'anthropic-messages', + provider: 'anthropic', + baseUrl: 'https://api.anthropic.com', + reasoning: true, + input: ['text'], + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + contextWindow: 200_000, + maxTokens: 64_000, + } + const notice = await invoke(model) + const marker = '[lane start] — automated cache warm; no response needed.' + expect(queued).toEqual([[marker, { deliverAs: 'followUp' }]]) + expect(sends).toHaveLength(0) + expect(notice).toContain('Claude lane start queued in this session.') + + const first = { + role: 'user', + content: 'Earlier session prompt', + timestamp: now, + } as const + const lane = { + role: 'user', + content: [{ type: 'text', text: queued[0]![0] as string }], + timestamp: now + 1, + } satisfies Parameters[1]['messages'][number] + const next = { + role: 'user', + content: 'Now answer my question', + timestamp: now + 2, + } as const + async function runTurn( + messages: Parameters[1]['messages'], + ) { + const result = await streamCortexKitAnthropic( + model, + { messages }, + { sessionId, maxTokens: 123 }, + undefined, + undefined, + 'agent-loop', + ).result() + expect(result.stopReason).toBe('stop') + } + try { + await runTurn([first, lane]) + expect(sends).toHaveLength(1) + const sent = sends[0]! + expect(sent.headers.get('authorization')).toBe( + 'Bearer sk-ant-oat01-fallback-access', + ) + const body = JSON.parse(sent.text) + expect(body).toMatchObject({ model: modelId, max_tokens: 1 }) + expect(body.messages).toHaveLength(2) + expect(body.messages[0]).toMatchObject({ + role: 'user', + content: first.content, + }) + expect(body.messages[1]).toMatchObject({ + role: 'user', + content: [ + { type: 'text', text: marker, cache_control: { type: 'ephemeral' } }, + ], + }) + expect(body.thinking).toBeUndefined() + expect(await signRequestBody(sent.text)).toBe(sent.text) + expect(sessionCacheActivity.ttlMs(sessionId)).toBe( + PROMPT_CACHE_DEFAULT_TTL_MS, + ) + + await runTurn([first, lane, next]) + expect(sends).toHaveLength(2) + const following = JSON.parse(sends[1]!.text) + expect(following.max_tokens).toBe(123) + expect(following.thinking).toBeDefined() + expect(following.messages[0]).toEqual(body.messages[0]) + expect(following.messages[1]).toMatchObject({ + role: 'user', + content: marker, + }) + } finally { + sessionCacheActivity.forget(sessionId) + } + expect((await native.view()).policyStorage.prime?.enabled).toBe(false) +}) + test('Pi Prime disabled never polls or sends, and the menu enables it live', async () => { const native = await fixture(false) await native.prime?.manager.tick() From 96f4d329f1517a883415978f6547743831b4e0e8 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:24:36 +0100 Subject: [PATCH 07/27] mason: align Pi header quota and paid model routing Save standard quota from the serving OAuth response through the native store without blocking the stream. Keep poll-owned fields and do not use rounded header percentages to authorize a paid fallback. Share the OpenCode endpoint resolver without changing its wrapper. Pi keeps saved paid endpoints and applies Core model aliases only to the paid wire body. --- CHANGELOG.md | 2 + docs/accounts-and-routing.md | 2 +- docs/environment.md | 2 +- docs/transports.md | 4 +- packages/core/src/api-route-url.ts | 56 ++++++++++++ packages/core/src/index.ts | 1 + packages/opencode/src/transform.ts | 59 +------------ packages/pi/src/convert.ts | 3 + packages/pi/src/native.ts | 28 ++++++ packages/pi/src/stream.ts | 28 +++--- packages/pi/src/tests/native-serving.test.ts | 86 ++++++++++++++++++ packages/pi/src/tests/provider-error.test.ts | 91 +++++++++++++++++++- 12 files changed, 289 insertions(+), 73 deletions(-) create mode 100644 packages/core/src/api-route-url.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 938fdc7fb..adb9c8bcc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,8 @@ This repo is a CortexKit-maintained Anthropic auth monorepo for OpenCode and Pi. - OpenCode 1 on Thalamus now reports which login paid for each Claude send and how many tokens it used, including relayed sends and keep-warm requests, like OpenCode 2. - Pi: `/claude` can now refresh quota and edit quota floors, like OpenCode 1 and 2. - Pi: `/claude` can now start a five-hour quota window with a one-time request, like OpenCode 1 and 2. +- Pi, like OpenCode 1 and 2, now updates each subscription account's quota from Claude's replies without waiting for the next quota poll. +- Pi's paid API-key route now honors the same model aliases as OpenCode 1 and 2 and keeps its configured endpoint. ## 2.16.5 diff --git a/docs/accounts-and-routing.md b/docs/accounts-and-routing.md index 254bcc414..10da2d869 100644 --- a/docs/accounts-and-routing.md +++ b/docs/accounts-and-routing.md @@ -40,7 +40,7 @@ Sticky-balanced waits on the assigned account only when every exhausted window b ## Quota and limits -Quota shows five-hour, seven-day and model-scoped windows when available. OpenCode's **Refresh quota** action requests fresh readings; Pi shows the summary without a refresh action. Passive response headers and quota API polling have different coverage: headers can update standard windows without supplying model-scoped limits. +Quota shows five-hour, seven-day and model-scoped windows when available. OpenCode's **Refresh quota** action requests fresh readings; Pi shows the summary without a refresh action. On OpenCode 1, OpenCode 2 and Pi, response headers can update the standard windows before the next quota poll. Quota polls supply the model-scoped limits and extra usage shown in the summary. Quota figures use the shared wording, such as `5h 40% left, resets 2h29m` and `7d 70% left, resets 3d23h`. Readings older than fifteen minutes include their age, such as `checked 1d6h ago`. Extra usage is shown as `credits 40% left` or `credits spent`, followed by the amount spent and the monthly limit in your account's currency: `credits 75% left · $25.00/$100.00`, `credits spent · $100.35/$100.00`. Without a limit (or without amounts), only the credit figure is shown. In a narrow OpenCode sidebar, amounts that would make the line too wide are shown without cents (`$1,250/$5,000`), and the collapsed sidebar's one-line form is unchanged. diff --git a/docs/environment.md b/docs/environment.md index b6113f501..9fd9e545d 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -14,7 +14,7 @@ Path conventions depend on the artifact. In these docs: | Variable | Effect | | --- | --- | -| `ANTHROPIC_BASE_URL` | Override the Anthropic endpoint with an HTTP(S) URL on API-key routes. Claude sign-in (OAuth) requests go only to `https://api.anthropic.com` (or the [custom gateway](settings-file.md#custom-gateway) in your own settings file), so OpenCode refuses them while this points elsewhere; it never sets or widens the gateway | +| `ANTHROPIC_BASE_URL` | Override the Anthropic endpoint with an HTTP(S) URL on API-key requests that have no route URL. Saved paid routes use their stored URL. Claude sign-in (OAuth) requests go only to `https://api.anthropic.com` (or the [custom gateway](settings-file.md#custom-gateway) in your own settings file), so OpenCode refuses them while this points elsewhere; it never sets or widens the gateway | | `ANTHROPIC_INSECURE` | OpenCode 1 TLS opt-out for API-key requests: `1` or `true`, effective only with `ANTHROPIC_BASE_URL`; never applies to Claude sign-in (OAuth) requests, which always check certificates; avoid outside controlled diagnostics | | `ANTHROPIC_CUSTOM_HEADERS` | Add proxy metadata on API-key routes; ignored for OAuth | | `ANTHROPIC_MODEL` | Default proxy alias for any `claude-*` model | diff --git a/docs/transports.md b/docs/transports.md index 1fb5f1e56..92c694547 100644 --- a/docs/transports.md +++ b/docs/transports.md @@ -61,7 +61,9 @@ Relays always send the uncompressed body to Anthropic in this release: the relay ## Proxy routes -API-key routes can use a custom base URL and auth-header selection. The CLI's API-route inputs are listed in [commands](commands.md#opencode-cli). `ANTHROPIC_BASE_URL` can override the endpoint of API-key routes. On OpenCode 1 and OpenCode 2, Claude sign-in (OAuth) requests go only to `https://api.anthropic.com`: a provider `baseURL` or `ANTHROPIC_BASE_URL` pointing elsewhere is refused for them with a local 400, and nothing is sent. The only other destination for OAuth model requests is a [custom gateway](settings-file.md#custom-gateway) in your own user settings file, on OpenCode 1, OpenCode 2 and Pi; it replaces the relay for those requests and never applies to sign-in, refresh or usage requests. OAuth requests never follow redirects and always check TLS certificates: `ANTHROPIC_INSECURE` applies to API-key routes only. Pi already sends native OAuth only to that origin. Pi additionally supports `ANTHROPIC_CUSTOM_HEADERS`, `ANTHROPIC_MODEL` and `ANTHROPIC_DEFAULT_{SONNET,OPUS,HAIKU,FABLE}_MODEL` on API-key proxy routes; those custom-header/model overrides do not alter OAuth requests. Protected authentication and protocol headers cannot be replaced by custom headers. +API-key routes can use a custom base URL and auth-header selection. The CLI's API-route inputs are listed in [commands](commands.md#opencode-cli). `ANTHROPIC_BASE_URL` applies only when the API-key request has no route URL. On OpenCode 1, OpenCode 2 and Pi, a saved paid route always uses its stored URL, even if it was saved with the default Anthropic URL. All three hosts honor `ANTHROPIC_MODEL` and `ANTHROPIC_DEFAULT_{SONNET,OPUS,HAIKU,FABLE}_MODEL` on API-key proxy routes. Pi also supports `ANTHROPIC_CUSTOM_HEADERS` there, without changing OAuth requests. Protected authentication and protocol headers cannot be replaced by custom headers. + +On OpenCode 1 and OpenCode 2, Claude sign-in (OAuth) requests go only to `https://api.anthropic.com`: a provider `baseURL` or `ANTHROPIC_BASE_URL` pointing elsewhere is refused for them with a local 400, and nothing is sent. Pi sends native OAuth only to that origin. The only other destination for OAuth model requests is a [custom gateway](settings-file.md#custom-gateway) in your own user settings file, on OpenCode 1, OpenCode 2 and Pi; it replaces the relay for those requests and never applies to sign-in, refresh or usage requests. OAuth requests never follow redirects and always check TLS certificates: `ANTHROPIC_INSECURE` applies only to OpenCode 1 API-key routes. Only use endpoints you trust: the route receives the request content and its configured authorization. Do not use insecure transport settings as a remedy for a credential or custody error. diff --git a/packages/core/src/api-route-url.ts b/packages/core/src/api-route-url.ts new file mode 100644 index 000000000..6418f5f2a --- /dev/null +++ b/packages/core/src/api-route-url.ts @@ -0,0 +1,56 @@ +/** Parse an API-route override, rejecting credentials embedded in the URL. */ +function parseBaseUrl(raw: string | undefined): URL | null { + const value = raw?.trim() + if (!value) return null + try { + const baseUrl = new URL(value) + if ( + (baseUrl.protocol !== 'http:' && baseUrl.protocol !== 'https:') || + baseUrl.username || + baseUrl.password + ) { + return null + } + return baseUrl + } catch { + return null + } +} + +/** Apply an explicit API-route URL or the environment override to a request URL. */ +export function applyAnthropicApiBaseUrl( + requestUrl: URL, + explicitBaseURL?: string, +): void { + const baseUrl = parseBaseUrl( + explicitBaseURL || process.env.ANTHROPIC_BASE_URL, + ) + if (!baseUrl) return + + const basePath = baseUrl.pathname.replace(/\/$/, '') + const inputPath = requestUrl.pathname + requestUrl.protocol = baseUrl.protocol + requestUrl.host = baseUrl.host + + const alreadyUnderBase = + inputPath === basePath || + (basePath !== '' && inputPath.startsWith(`${basePath}/`)) + if (!alreadyUnderBase) { + const baseEndsInVersion = /\/v\d[^/]*$/.test(basePath) + if (inputPath === '/messages') { + requestUrl.pathname = baseEndsInVersion + ? `${basePath}/messages` + : `${basePath}/v1/messages` + } else if (inputPath === '/v1/messages' && baseEndsInVersion) { + requestUrl.pathname = `${basePath}/messages` + } else { + requestUrl.pathname = `${basePath}${inputPath}` + } + } else if (inputPath === `${basePath}/messages`) { + // Repair only the exact SDK form under a non-versioned base. Do not + // rewrite sibling resources or explicit /v2 (and later) proxy paths. + if (!/\/v\d[^/]*$/.test(basePath)) { + requestUrl.pathname = `${basePath}/v1/messages` + } + } +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 2db853513..937d9b728 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -35,6 +35,7 @@ export { setupUsage, } from '@cortexkit/common-auth/setup' export * from './accounts.ts' +export { applyAnthropicApiBaseUrl } from './api-route-url.ts' export * from './auth.ts' export * from './billing.ts' export * from './cache-diagnostics.ts' diff --git a/packages/opencode/src/transform.ts b/packages/opencode/src/transform.ts index 31db23607..38664018a 100644 --- a/packages/opencode/src/transform.ts +++ b/packages/opencode/src/transform.ts @@ -1,5 +1,6 @@ import { createHash } from 'node:crypto' import { + applyAnthropicApiBaseUrl, applyClaudeCodeHeaders, applyClaudeCodeMetadata, applyRunnerTurnNotes, @@ -533,32 +534,6 @@ export function isInsecure(): boolean { return raw === '1' || raw === 'true' } -/** - * Parse ANTHROPIC_BASE_URL from the environment. - * Returns a valid HTTP(S) URL or null if unset/invalid. - */ -function parseBaseUrl(raw: string | undefined): URL | null { - const value = raw?.trim() - if (!value) return null - try { - const baseUrl = new URL(value) - if ( - (baseUrl.protocol !== 'http:' && baseUrl.protocol !== 'https:') || - baseUrl.username || - baseUrl.password - ) { - return null - } - return baseUrl - } catch { - return null - } -} - -function resolveBaseUrl(): URL | null { - return parseBaseUrl(process.env.ANTHROPIC_BASE_URL) -} - /** * Rewrite the request URL to add ?beta=true for /v1/messages requests. * When ANTHROPIC_BASE_URL is set, overrides the origin (protocol + host) @@ -587,37 +562,7 @@ export function rewriteUrl( const originalHref = requestUrl.href - const baseUrl = options.baseURL - ? parseBaseUrl(options.baseURL) - : resolveBaseUrl() - if (baseUrl) { - const basePath = baseUrl.pathname.replace(/\/$/, '') - const inputPath = requestUrl.pathname - requestUrl.protocol = baseUrl.protocol - requestUrl.host = baseUrl.host - - const alreadyUnderBase = - inputPath === basePath || - (basePath !== '' && inputPath.startsWith(`${basePath}/`)) - if (!alreadyUnderBase) { - const baseEndsInVersion = /\/v\d[^/]*$/.test(basePath) - if (inputPath === '/messages') { - requestUrl.pathname = baseEndsInVersion - ? `${basePath}/messages` - : `${basePath}/v1/messages` - } else if (inputPath === '/v1/messages' && baseEndsInVersion) { - requestUrl.pathname = `${basePath}/messages` - } else { - requestUrl.pathname = `${basePath}${inputPath}` - } - } else if (inputPath === `${basePath}/messages`) { - // Repair only the exact SDK form under a non-versioned base. Do not - // rewrite sibling resources or explicit /v2 (and later) proxy paths. - if (!/\/v\d[^/]*$/.test(basePath)) { - requestUrl.pathname = `${basePath}/v1/messages` - } - } - } + applyAnthropicApiBaseUrl(requestUrl, options.baseURL) if ( requestUrl.pathname.endsWith('/v1/messages') && diff --git a/packages/pi/src/convert.ts b/packages/pi/src/convert.ts index 5227f79f5..f7231a6ba 100644 --- a/packages/pi/src/convert.ts +++ b/packages/pi/src/convert.ts @@ -30,6 +30,7 @@ import { LANE_START_TEXT, orderClaudeCodeBody, readSessionCachePolicy, + remapRequestBodyModel, requestCacheLifetimeMs, signRequestBody, stripEmptyTrailingAssistantMessages, @@ -760,6 +761,7 @@ export async function buildAnthropicRequest( forkEffort?: PiForkEffortHint /** Leave the billing signature placeholder for the transport to finalize. */ deferSigning?: boolean + modelRemapEnabled?: boolean thinkingPrefixMismatchBehavior?: ThinkingPrefixMismatchBehavior turnEndNote?: { tools: string[] } /** @@ -1043,6 +1045,7 @@ export async function buildAnthropicRequest( throw new Error( `Anthropic accepts at most 4 cache breakpoints; the onPayload hook left ${breakpoints}`, ) + if (controls.modelRemapEnabled) remapRequestBodyModel(body) const unsigned = JSON.stringify( orderClaudeCodeBody(body, { isOAuth: !!identity }), ) diff --git a/packages/pi/src/native.ts b/packages/pi/src/native.ts index 7809913b3..4d3474eed 100644 --- a/packages/pi/src/native.ts +++ b/packages/pi/src/native.ts @@ -11,6 +11,7 @@ import { getPersistedLogLevel, getSettingsFilePath, isKillswitchEnabled, + isQuotaBearingHeaderFrame, isVaultHosted, killswitchPassesPolicy, LEGACY_STATE_LAYOUT, @@ -32,6 +33,7 @@ import { nativeLocalAccountRefusal, nativeMigrationAuthorityPhase, nativeRuntimeOptionIdentity, + normalizeQuotaHeaders, quotaSnapshotHasStandardWindows, quotaSnapshotPassesModelScope, quotaSnapshotPassesPolicy, @@ -625,6 +627,32 @@ export class PiNativeRuntime { ) } + observeQuotaHeaders( + served: PiNativeAttempt, + headers: Headers, + runtime: NativeAccountRuntime, + ): void { + if (!isQuotaBearingHeaderFrame(headers)) return + const quota = { + ...normalizeQuotaHeaders(headers), + accountIdentity: served.accountIdentity, + } + // The store accepts updates only for the account that served the request. + // It merges against the latest quota so poll-owned windows and credits stay. + this.usagePublications.publish(async (signal) => { + const kept = + served.source === 'vault' + ? await runtime.vault.publish(served.receipt, { quota }, signal) + : await runtime.publishLocal( + served.admission.subject, + { quota }, + signal, + ) + if (!kept) + logger.debug('quota', 'Native header quota publication refused') + }) + } + close(): Promise { this.prime?.stop() this.closed = true diff --git a/packages/pi/src/stream.ts b/packages/pi/src/stream.ts index 88718aeb0..96be63e8d 100644 --- a/packages/pi/src/stream.ts +++ b/packages/pi/src/stream.ts @@ -3,6 +3,7 @@ import { type AccountStorage, type AnthropicBillingRequest, type ApiKeyAccount, + applyAnthropicApiBaseUrl, applyClaudeCodeHeaders, applyClaudeCodeMetadata, applyClaudeGatewayHeaders, @@ -86,6 +87,7 @@ import { type QuotaState, quotaBackoffActive, quotaExhaustionFromHeaders, + quotaFieldSource, quotaRefusalTiming, quotaSnapshotHasStandardWindows, quotaSnapshotModelScopeIsExhausted, @@ -776,13 +778,11 @@ function updateUsage( export function buildExplicitBaseMessagesUrl(baseURL: string) { const url = new URL(baseURL) const basePath = url.pathname.replace(/\/$/, '') - if (/\/v\d[^/]*\/messages$/.test(basePath)) { - url.pathname = basePath - } else if (/\/v\d[^/]*$/.test(basePath)) { - url.pathname = `${basePath}/messages` - } else { - url.pathname = `${basePath}/v1/messages` - } + // A route can already name the messages resource rather than a base path. + url.pathname = /\/v\d[^/]*\/messages$/.test(basePath) + ? basePath + : '/v1/messages' + applyAnthropicApiBaseUrl(url, baseURL) url.searchParams.set('beta', 'true') return url } @@ -1096,6 +1096,7 @@ async function sendAnthropicRequestAttempt( { deferSigning: true, billingLineage: lineage, + modelRemapEnabled: options.apiAccount !== undefined, forkBaseMessageCount: forkBase?.messageCount, // API-key routes send no effort history, so no fork hint either. forkEffort: options.apiAccount @@ -1140,11 +1141,12 @@ async function sendAnthropicRequestAttempt( ...(options.prime && { requestClass: 'auxiliary' }), }) const relayAffinity = options.streamOptions?.sessionId ?? null - const reportRoutingHeaders = ( + const observeResponseHeaders = ( attempt: PiNativeAttempt, responseHeaders: Headers, status: number, ) => { + native.observeQuotaHeaders(attempt, responseHeaders, servingRuntime) if (options.prime || !relayAffinity) return if ( options.routingRelay && @@ -1479,7 +1481,7 @@ async function sendAnthropicRequestAttempt( ? withAnthropicBilling(billing, send) : send()) if (attempt) - reportRoutingHeaders(attempt, response.headers, response.status) + observeResponseHeaders(attempt, response.headers, response.status) return response } let response: Response @@ -1626,7 +1628,7 @@ async function sendAnthropicRequestAttempt( onResponseHeaders: (responseHeaders) => { observeRequestId(responseHeaders) if (upstream) - reportRoutingHeaders( + observeResponseHeaders( upstream.attempt, responseHeaders, upstream.status, @@ -1756,8 +1758,12 @@ async function endIfCancelled( function quotaSnapshotIsExhausted( quota: Awaited> | undefined, ) { + // A deferred poll can return the cached quota. A header percentage rounded + // to 100% is display evidence, not permission to switch to a paid route. return (['five_hour', 'seven_day'] as const).some( - (key) => (quota?.[key]?.remainingPercent ?? 1) <= 0, + (key) => + quotaFieldSource(quota, key) !== 'headers' && + (quota?.[key]?.remainingPercent ?? 1) <= 0, ) } diff --git a/packages/pi/src/tests/native-serving.test.ts b/packages/pi/src/tests/native-serving.test.ts index 6e544843a..9fd8bb2b4 100644 --- a/packages/pi/src/tests/native-serving.test.ts +++ b/packages/pi/src/tests/native-serving.test.ts @@ -202,6 +202,92 @@ test('Pi abort ends a stalled quota preflight without sending a model request', expect(sends).toBe(0) }) +test('Pi ready replies do not wait for header quota to merge with the last poll', async () => { + const checkedAt = Date.now() - 60_000 + const resetAt = Math.floor(Date.now() / 1_000) + 3_600 + const weekly = { usedPercent: 22, remainingPercent: 78, checkedAt } + const scoped = [{ ...weekly, id: 'opus', title: 'Opus', modelName: 'Opus' }] + const extraUsage = { + used: { amountMinor: 100, currency: 'USD', exponent: 2 }, + limit: { amountMinor: 500, currency: 'USD', exponent: 2 }, + utilizationPercent: 20, + exhausted: false, + } + await saveNativePiFixture( + { + version: 1, + accounts: [], + quota: { + enabled: false, + mainQuota: { + source: 'poll', + checkedAt, + five_hour: { usedPercent: 5, remainingPercent: 95, checkedAt }, + seven_day: weekly, + scoped, + extraUsage, + }, + }, + }, + storagePath, + ) + const native = getPiNativeRuntime(storagePath) + const runtime = await native.service() + const publishLocal = runtime.publishLocal.bind(runtime) + const started = Promise.withResolvers() + const unblock = Promise.withResolvers() + const publication = spyOn(runtime, 'publishLocal').mockImplementation( + async (subject, patch, signal) => { + if (patch.quota?.source === 'headers') { + started.resolve() + await unblock.promise + } + return publishLocal(subject, patch, signal) + }, + ) + globalThis.fetch = Object.assign( + async () => { + const response = success() + response.headers.set('anthropic-ratelimit-unified-5h-utilization', '.39') + response.headers.set( + 'anthropic-ratelimit-unified-5h-reset', + String(resetAt), + ) + return response + }, + { preconnect: originalFetch.preconnect }, + ) + + const pending = streamCortexKitAnthropic(model, context).result() + try { + const result = await Promise.race([ + pending, + started.promise.then(() => Bun.sleep(1_000)).then(() => undefined), + ]) + expect(result?.stopReason).toBe('stop') + } finally { + unblock.resolve() + await pending + await native.usagePublications.drain() + publication.mockRestore() + } + const snapshot = await runtime.read() + expect( + snapshot.accounts.find((account) => account.id === 'main')?.quota, + ).toMatchObject({ + source: 'headers', + checkedAt, + five_hour: { + usedPercent: 39, + remainingPercent: 61, + resetsAt: new Date(resetAt * 1_000).toISOString(), + }, + seven_day: weekly, + scoped, + extraUsage, + }) +}) + test('Pi empty-init routing uses the construction-time override or native derived path; missing authority refuses', () => trackPiTestBody( (async () => { diff --git a/packages/pi/src/tests/provider-error.test.ts b/packages/pi/src/tests/provider-error.test.ts index e2ebdf808..1f53ed889 100644 --- a/packages/pi/src/tests/provider-error.test.ts +++ b/packages/pi/src/tests/provider-error.test.ts @@ -177,6 +177,9 @@ async function ownDirectory(prefix: string) { const directory = await mkdtemp(join(tmpdir(), prefix)) const storagePath = join(directory, 'accounts.json') const envKeys = [ + 'ANTHROPIC_BASE_URL', + 'ANTHROPIC_DEFAULT_SONNET_MODEL', + 'ANTHROPIC_MODEL', 'PI_CODING_AGENT_DIR', 'PI_AGENT_DIR', 'PI_ANTHROPIC_AUTH_FILE', @@ -491,7 +494,10 @@ function expectQuotaPollGaps(requested: readonly number[]) { } /** Create a local OAuth account with a paid API fallback for general quota exhaustion. */ -async function paidFixture(apiKey = PAID_KEY) { +async function paidFixture( + apiKey = PAID_KEY, + baseURL = 'https://paid.invalid', +) { const quotaPauses = recordQuotaPauses() const { directory, storagePath } = await ownDirectory( 'pi-provider-error-paid-', @@ -504,7 +510,7 @@ async function paidFixture(apiKey = PAID_KEY) { type: 'api', id: 'paid', apiKey, - baseURL: 'https://paid.invalid', + baseURL, }, ], }, @@ -514,6 +520,53 @@ async function paidFixture(apiKey = PAID_KEY) { return { directory, quotaPauses } } +for (const customEndpoint of [false, true]) { + test(`Pi paid route keeps its ${customEndpoint ? 'custom URL and uses the family alias' : 'stored default URL and uses the default alias'}`, async () => { + await paidFixture( + PAID_KEY, + customEndpoint + ? 'https://paid.invalid/anthropic/v2' + : 'https://api.anthropic.com', + ) + process.env.ANTHROPIC_BASE_URL = 'https://proxy.invalid' + process.env.ANTHROPIC_MODEL = 'default-proxy-alias' + if (customEndpoint) + process.env.ANTHROPIC_DEFAULT_SONNET_MODEL = 'sonnet-proxy-alias' + else delete process.env.ANTHROPIC_DEFAULT_SONNET_MODEL + + const requests: Array<{ url: string; model: string }> = [] + useFetch(async (url, init) => { + if (url.includes('/api/oauth/usage')) + return Response.json({ + five_hour: { utilization: 100 }, + seven_day: { utilization: 100 }, + }) + if (!url.includes('/messages')) return new Response('{}', { status: 503 }) + const body = JSON.parse(String(init?.body)) as { model: string } + requests.push({ url, model: body.model }) + return authorizationOf(init) === `Bearer ${PAID_KEY}` + ? eventStream(healthy('paid reply')) + : jsonError(429, 'rate_limit_error', MAIN_ACCESS) + }) + + expect( + (await streamCortexKitAnthropic(model, context).result()).stopReason, + ).toBe('stop') + expect(requests).toEqual([ + { + url: 'https://api.anthropic.com/v1/messages?beta=true', + model: model.id, + }, + { + url: customEndpoint + ? 'https://paid.invalid/anthropic/v2/messages?beta=true' + : 'https://api.anthropic.com/v1/messages?beta=true', + model: customEndpoint ? 'sonnet-proxy-alias' : 'default-proxy-alias', + }, + ]) + }) +} + test('Pi usage-limit echo still reaches the paid route, whose error omits the paid key', async () => { const { quotaPauses } = await paidFixture() const modelRequests: string[] = [] @@ -562,6 +615,40 @@ test('Pi usage-limit echo without exhaustion keeps the primary 429 and scrubs it expectQuotaPollGaps(quotaPauses) }) +test('Pi never opens the paid route from rounded header quota while polling is backed off', async () => { + const { directory } = await paidFixture() + const modelRequests: string[] = [] + let polls = 0 + useFetch(async (url, init) => { + if (url.includes('/api/oauth/usage')) { + polls++ + return new Response(null, { status: 429 }) + } + if (!url.includes('/v1/messages')) + return new Response('{}', { status: 503 }) + const authorization = authorizationOf(init) + modelRequests.push(authorization) + if (authorization === `Bearer ${PAID_KEY}`) + return eventStream(healthy('paid reply')) + const response = jsonError(429, 'rate_limit_error', MAIN_ACCESS) + response.headers.set('anthropic-ratelimit-unified-5h-utilization', '.999') + return response + }) + await expectError('pi-first-poll-429', [MAIN_ACCESS], ['HTTP 429']) + const native = getPiNativeRuntime(join(directory, 'accounts.json')) + await native.usagePublications.drain() + const snapshot = await native.view() + const main = snapshot.accounts.find((account) => account.id === 'main') + expect(main?.quota?.five_hour?.remainingPercent).toBe(0) + + await expectError('pi-poll-backed-off', [MAIN_ACCESS], ['HTTP 429']) + expect(polls).toBe(1) + expect(modelRequests).toEqual([ + `Bearer ${MAIN_ACCESS}`, + `Bearer ${MAIN_ACCESS}`, + ]) +}) + // A streamed rate limit arrives as an `error` event whose `error.type` is // `rate_limit_error`. It must route like an HTTP 429: refresh the primary's // quota, move to another OAuth account when one is eligible, and use a paid From b2e13fe8639708590c1ede7eeaaa443e31da879e Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:37:27 +0100 Subject: [PATCH 08/27] mason: add Pi conversation cache diagnostics Use Core opt-in, record validation and beta hashing on the final OAuth body and the corresponding SSE message start. Only primary conversation replies advance the processor-local predecessor, while session-tagged auxiliary replies can log without replacing it. Keep paid requests, forks, Prime and CacheKeep observations out of this chain. Forget correlations at session shutdown. --- CHANGELOG.md | 1 + docs/cache-diagnostics.md | 6 +- packages/pi/src/convert.ts | 9 ++ packages/pi/src/stream.ts | 119 ++++++++++++++++++++++++- packages/pi/src/tests/stream.test.ts | 126 +++++++++++++++++++++++++++ 5 files changed, 255 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index adb9c8bcc..4ba215daa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,7 @@ This repo is a CortexKit-maintained Anthropic auth monorepo for OpenCode and Pi. - Pi: `/claude` can now start a five-hour quota window with a one-time request, like OpenCode 1 and 2. - Pi, like OpenCode 1 and 2, now updates each subscription account's quota from Claude's replies without waiting for the next quota poll. - Pi's paid API-key route now honors the same model aliases as OpenCode 1 and 2 and keeps its configured endpoint. +- Pi now links cache diagnostics across conversation replies like OpenCode 1 and 2, with cache results and beta lists in the debug log. ## 2.16.5 diff --git a/docs/cache-diagnostics.md b/docs/cache-diagnostics.md index 4e673618f..63a23986a 100644 --- a/docs/cache-diagnostics.md +++ b/docs/cache-diagnostics.md @@ -2,7 +2,7 @@ ## Measure-only beta -The Anthropic API opt-in `cache-diagnosis-2026-04-07` (sent in the `anthropic-beta` header) asks for cache diagnostics; it does not change cache controls or routing. OpenCode 1 and 2 capture the response's opaque top-level message ID and send it as `diagnostics.previous_message_id` on the next eligible request in that session. The first eligible request sends `null`. +The Anthropic API opt-in `cache-diagnosis-2026-04-07` (sent in the `anthropic-beta` header) asks for cache diagnostics; it does not change cache controls or routing. OpenCode 1, OpenCode 2 and Pi capture the response's opaque top-level message ID and send it as `diagnostics.previous_message_id` on the next eligible request in that session. The first eligible request sends `null`. On Pi, session-associated Claude sign-in requests can use the preceding ID, but only the main conversation advances it. Paid API-key requests, forks, Prime and keep-warm do not advance that chain or write its diagnostic records. Keep-warm requests on OpenCode do not opt in to cache diagnostics or change the previous-message ID. In older OpenCode 1 logs, `prewarm_cachekeep` identifies a keep-warm response. @@ -20,7 +20,7 @@ Each record is one JSON line after the exact prefix `MC-CACHE-DIAG `, including | `account_id` | Opaque persisted routing/account identifier; do not validate its string shape | | `betas_hash` | 16-character lowercase xxHash64 (seed 0) of the sorted sent beta list | | `requested_model` | Optional sent model, only when different from the response model | -| `session_id` | OpenCode session affinity | +| `session_id` | Identifier of the host conversation this record belongs to | | `ts_ms_received` | Integer local receipt time | | `model` | Anthropic response model | | `is_subagent` | Original request context | @@ -60,4 +60,4 @@ A short-gap `previous_message_not_found` reason is also captured as a canary whe When dumps are enabled, `.response.json` holds status and parsed response metadata without response content. Lane-start filenames include `-start-`; CacheKeep uses `-prewarm-cachekeep-`. Treat related request bodies as sensitive local data. See [dump handling](transports.md#diagnostics-and-dumps) and [the OpenCode history analyzer](cache.md#diagnostics-and-history-analysis) for retrospective estimates. -Implementation: [schema and record validation](../packages/core/src/cache-diagnostics.ts), emission in [OpenCode 1](../packages/opencode/src/index.ts) and [OpenCode 2](../packages/opencode/src/v2/wire.ts), and [wire opt-in](../packages/opencode/src/transform.ts). +Implementation: [schema and record validation](../packages/core/src/cache-diagnostics.ts), with host integrations in [OpenCode 1](../packages/opencode/src/index.ts), [OpenCode 2](../packages/opencode/src/v2/wire.ts) and [Pi](../packages/pi/src/stream.ts). diff --git a/packages/pi/src/convert.ts b/packages/pi/src/convert.ts index f7231a6ba..4dcac24c7 100644 --- a/packages/pi/src/convert.ts +++ b/packages/pi/src/convert.ts @@ -1,4 +1,5 @@ import { + applyCacheDiagnosticsOptIn, applyClaudeCodeMetadata, applyRunnerTurnNotes, applySessionCacheTtl, @@ -7,6 +8,7 @@ import { assertNoMeaningfulTrailingAssistant, type BillingLineageFields, buildBillingHeaderValue, + CACHE_DIAGNOSTICS_BETA, type Cache1hMode, CLAUDE_CODE_ENTRYPOINT, CLAUDE_CODE_IDENTITY, @@ -32,6 +34,7 @@ import { readSessionCachePolicy, remapRequestBodyModel, requestCacheLifetimeMs, + selectClaudeCodeBetas, signRequestBody, stripEmptyTrailingAssistantMessages, type ThinkingPrefixMismatchBehavior, @@ -761,6 +764,7 @@ export async function buildAnthropicRequest( forkEffort?: PiForkEffortHint /** Leave the billing signature placeholder for the transport to finalize. */ deferSigning?: boolean + cacheDiagnosticsPreviousMessageId?: string | null modelRemapEnabled?: boolean thinkingPrefixMismatchBehavior?: ThinkingPrefixMismatchBehavior turnEndNote?: { tools: string[] } @@ -1046,6 +1050,11 @@ export async function buildAnthropicRequest( `Anthropic accepts at most 4 cache breakpoints; the onPayload hook left ${breakpoints}`, ) if (controls.modelRemapEnabled) remapRequestBodyModel(body) + if ( + controls.cacheDiagnosticsPreviousMessageId !== undefined && + selectClaudeCodeBetas(body).split(',').includes(CACHE_DIAGNOSTICS_BETA) + ) + applyCacheDiagnosticsOptIn(body, controls.cacheDiagnosticsPreviousMessageId) const unsigned = JSON.stringify( orderClaudeCodeBody(body, { isOAuth: !!identity }), ) diff --git a/packages/pi/src/stream.ts b/packages/pi/src/stream.ts index 96be63e8d..9995d5d23 100644 --- a/packages/pi/src/stream.ts +++ b/packages/pi/src/stream.ts @@ -10,8 +10,13 @@ import { applyCustomHeaders, assertHostAuthorityStable, buildBillingHeaderValue, + buildCacheDiagnosticsRecord, buildPrimeRequestBody, + CACHE_DIAGNOSTICS_BETA, + CACHE_DIAGNOSTICS_SESSION_LIMIT, CACHE_KEEP_EXTENDED_TTL_BETA, + CacheDiagnosticsBetaTracker, + CacheDiagnosticsTracker, type CacheKeepManager, type CacheKeepRealTurn, CacheKeepSessionRegistry, @@ -38,7 +43,9 @@ import { dumpResponseArtifact, effectiveRelayTransport, FAST_MODE_BETA, + formatCacheDiagnosticsLogLine, getCache1hPersistentMode, + getCacheDiagnosticsBetas, getCacheKeepRegistryDirectories, getClaudeCodeIdentityForVerifiedAccount, getFallbackReauthLabels, @@ -121,6 +128,7 @@ import { stickyRetryAfterWithJitter, stickyRouteCandidateWeight, stickyRouteFamilyForModel, + summarizeCacheTtl, warnClaudeGatewayRelayIgnored, withAnthropicBilling, withCacheKeepRealTurn, @@ -196,6 +204,25 @@ const primarySessions = new Map< } >() +const cacheDiagnostics = new CacheDiagnosticsTracker() +const cacheDiagnosticBetas = new CacheDiagnosticsBetaTracker() +const cacheDiagnosticsSessions = new Map() +const cacheDiagnosticsObservers = new WeakMap< + Response, + (message: unknown) => Promise +>() + +function cacheDiagnosticsSession(sessionId: string): object { + const session = cacheDiagnosticsSessions.get(sessionId) ?? {} + cacheDiagnosticsSessions.delete(sessionId) + cacheDiagnosticsSessions.set(sessionId, session) + if (cacheDiagnosticsSessions.size > CACHE_DIAGNOSTICS_SESSION_LIMIT) { + const oldest = cacheDiagnosticsSessions.keys().next().value + if (oldest !== undefined) cacheDiagnosticsSessions.delete(oldest) + } + return session +} + export function beginPiPrimaryTurn( storagePath: string, sessionId?: string, @@ -268,6 +295,8 @@ export function forgetPiMessageThread( disposition: 'session_closed' | 'session_deleted' = 'session_deleted', ): void { messageThreads.forget(sessionId, disposition) + cacheDiagnostics.forgetSession(sessionId) + cacheDiagnosticsSessions.delete(sessionId) } /** Dump label for a physical send that failed before any response arrived. */ @@ -820,6 +849,7 @@ export async function* parseSse( return } const dumpObserver = dumpResponseObservers.get(response) + let cacheDiagnosticsObserver = cacheDiagnosticsObservers.get(response) const reader = response.body.getReader() // Core's byte framer ends frames at blank lines with CRLF, LF or CR line // endings and keeps a multibyte character split across reads in one frame, @@ -844,6 +874,11 @@ export async function* parseSse( if (!data || data === '[DONE]') continue const event = JSON.parse(data) as AnthropicEvent dumpObserver?.observe(event) + if (event.type === 'message_start' && cacheDiagnosticsObserver) { + const observe = cacheDiagnosticsObserver + cacheDiagnosticsObserver = undefined + await observe(event.message).catch(() => {}) + } yield event } } @@ -1021,6 +1056,14 @@ async function sendAnthropicRequestAttempt( primary.committed = lineage.sequence primary.previousRequestId = id } + const diagnosticsSession = + realSession && !options.apiAccount && !options.prime && !forkHead + ? { + id: realSession, + token: cacheDiagnosticsSession(realSession), + previous: cacheDiagnostics.previousFor(realSession), + } + : undefined if (!options.prime && !forkHead && realSession) { if (options.apiAccount || !options.storagePath) { try { @@ -1096,6 +1139,10 @@ async function sendAnthropicRequestAttempt( { deferSigning: true, billingLineage: lineage, + ...(diagnosticsSession && { + cacheDiagnosticsPreviousMessageId: + diagnosticsSession.previous?.messageId ?? null, + }), modelRemapEnabled: options.apiAccount !== undefined, forkBaseMessageCount: forkBase?.messageCount, // API-key routes send no effort history, so no fork hint either. @@ -1352,14 +1399,17 @@ async function sendAnthropicRequestAttempt( relayConfig = null } let threadRequest: MessageThreadRequest | undefined - if ( - primary && + // A real conversation request in the turn this process still owns. + const primaryThread = + primary !== undefined && primary === piPrimarySession( options.storagePath, options.streamOptions, options.requestOrigin, - ) && + ) + if ( + primaryThread && // Gateways may refuse the thread route: send full requests. !gateway && typeof options.streamOptions?.onPayload === 'function' && @@ -1733,6 +1783,66 @@ async function sendAnthropicRequestAttempt( createDumpResponseObserver(dumpHandle, response.status), ) } + if (diagnosticsSession && response.ok) { + const previousMessageId = diagnosticsSession.previous?.messageId ?? null + const payload = JSON.parse(wireBodyText) as { + diagnostics?: { previous_message_id?: string | null } + model?: unknown + } + // Thread recovery can replace the prepared body. Attribute the result only + // if the actual send carried this diagnostic predecessor and beta. + if (payload.diagnostics?.previous_message_id === previousMessageId) { + const betas = getCacheDiagnosticsBetas(headers).catch(() => undefined) + const ttlSent = summarizeCacheTtl(payload) + const requestedModel = + typeof payload.model === 'string' ? payload.model : undefined + cacheDiagnosticsObservers.set(response, async (message) => { + const receivedAt = Date.now() + const sent = await betas + if ( + !sent?.betas.includes(CACHE_DIAGNOSTICS_BETA) || + init.signal?.aborted || + cacheDiagnosticsSessions.get(diagnosticsSession.id) !== + diagnosticsSession.token + ) + return + const { record, messageId, canary } = buildCacheDiagnosticsRecord({ + request: { + sessionId: diagnosticsSession.id, + previousMessageId, + previousMessageReceivedAt: diagnosticsSession.previous?.receivedAt, + isSubagent: false, + ttlSent, + }, + source: 'turn', + accountId: routeId, + synthetic: false, + betasHash: sent.betasHash, + requestedModel, + message, + receivedAt, + }) + if (!record || !messageId) return + logger.debug('cache-diagnostics', formatCacheDiagnosticsLogLine(record)) + const betaLine = cacheDiagnosticBetas.capture( + sent.betasHash, + sent.betas, + ) + if (betaLine) logger.debug('cache-diagnostics', betaLine) + if (canary) + logger.warn( + 'cache-diagnostics', + 'short-gap previous_message_not_found', + { + message_id: canary.messageId, + previous_message_id: canary.previousMessageId, + }, + ) + if (primaryThread) + cacheDiagnostics.capture(diagnosticsSession.id, messageId, receivedAt) + }) + } + } return response } @@ -1883,6 +1993,9 @@ export async function firstStreamingError( const inspected = copyStreamResponseTiming(response, replay(true)) const dumpObserver = dumpResponseObservers.get(response) if (dumpObserver) dumpResponseObservers.set(inspected, dumpObserver) + const cacheDiagnosticsObserver = cacheDiagnosticsObservers.get(response) + if (cacheDiagnosticsObserver) + cacheDiagnosticsObservers.set(inspected, cacheDiagnosticsObserver) return { response: inspected, preflight: inspected } } diff --git a/packages/pi/src/tests/stream.test.ts b/packages/pi/src/tests/stream.test.ts index 0ee99cfc5..316e83106 100644 --- a/packages/pi/src/tests/stream.test.ts +++ b/packages/pi/src/tests/stream.test.ts @@ -735,6 +735,132 @@ test.each([ }, ) +test('Pi conversation cache diagnostics link replies and log one beta list per hash', async () => { + tempDir = await mkdtemp(join(tmpdir(), 'pi-cache-diagnostics-')) + const storagePath = join(tempDir, 'accounts.json') + const sessionId = 'ses_pi_cache_diagnostics' + process.env.PI_ANTHROPIC_AUTH_FILE = storagePath + await saveNativePiFixture( + { + version: 1, + accounts: [], + logging: { level: 'debug' }, + quota: { enabled: false }, + }, + storagePath, + ) + const sent: Array<{ diagnostics?: unknown; betas: string[] }> = [] + const records: LogTestRecord[] = [] + const level = core.getLogLevel() + await getPiNativeRuntime(storagePath).service() + core.setLogLevel('debug') + __setLogTestSink((record) => records.push(record)) + globalThis.fetch = mock( + async (input: string | URL | Request, init?: RequestInit) => { + if (!String(input).includes('/v1/messages')) + throw new Error('unexpected request') + const body = JSON.parse(String(init?.body)) as { diagnostics?: unknown } + const betas = ( + new Headers(init?.headers).get('anthropic-beta') ?? '' + ).split(',') + sent.push({ diagnostics: body.diagnostics, betas }) + return new Response( + [ + { + type: 'message_start', + message: { + id: `msg_pi_diag_${sent.length}`, + model: anthropicModel.id, + diagnostics: null, + usage: { + input_tokens: 24, + output_tokens: 0, + cache_read_input_tokens: 12, + cache_creation_input_tokens: 4, + cache_creation: { + ephemeral_5m_input_tokens: 4, + ephemeral_1h_input_tokens: 0, + }, + }, + }, + }, + { type: 'message_delta', delta: { stop_reason: 'end_turn' } }, + { type: 'message_stop' }, + ] + .map((event) => `data: ${JSON.stringify(event)}\n\n`) + .join(''), + { headers: { 'content-type': 'text/event-stream' } }, + ) + }, + ) as unknown as typeof fetch + + const send = (origin: 'agent-loop' | 'direct' = 'agent-loop') => + streamCortexKitAnthropic( + anthropicModel, + anthropicContext, + { + sessionId, + onPayload: (payload) => payload, + onResponse: () => {}, + onProviderStreamEvent: () => {}, + }, + undefined, + undefined, + origin, + ).result() + beginPiPrimaryTurn(storagePath, sessionId) + try { + expect((await send()).stopReason).toBe('stop') + expect((await send('direct')).stopReason).toBe('stop') + expect((await send()).stopReason).toBe('stop') + expect(sent[0]?.betas).toContain(core.CACHE_DIAGNOSTICS_BETA) + expect(sent.map((request) => request.diagnostics)).toEqual([ + { previous_message_id: null }, + { previous_message_id: 'msg_pi_diag_1' }, + { previous_message_id: 'msg_pi_diag_1' }, + ]) + const lines = records.filter(({ message }) => + message.startsWith('MC-CACHE-DIAG '), + ) + expect(lines.map(({ level }) => level)).toEqual(['debug', 'debug', 'debug']) + const [first, auxiliary, second] = lines.map(({ message }) => + JSON.parse(message.slice('MC-CACHE-DIAG '.length)), + ) + expect(first).toMatchObject({ + source: 'turn', + session_id: sessionId, + message_id: 'msg_pi_diag_1', + previous_message_id: null, + diag_state: 'server_null', + cache_read: 12, + }) + expect(auxiliary).toMatchObject({ + message_id: 'msg_pi_diag_2', + previous_message_id: 'msg_pi_diag_1', + }) + expect(auxiliary.betas_hash).toMatch(/^[0-9a-f]{16}$/) + expect(auxiliary.betas_hash).not.toBe(first.betas_hash) + expect(second).toMatchObject({ + message_id: 'msg_pi_diag_3', + previous_message_id: 'msg_pi_diag_1', + betas_hash: first.betas_hash, + }) + const betaLines = records.filter(({ message }) => + message.startsWith('MC-CACHE-DIAG-BETAS '), + ) + expect(betaLines.map(({ level }) => level)).toEqual(['debug', 'debug']) + expect(betaLines.map(({ message }) => message)).toEqual([ + `MC-CACHE-DIAG-BETAS ${JSON.stringify({ hash: first.betas_hash, betas: [...sent[0]!.betas].sort() })}`, + `MC-CACHE-DIAG-BETAS ${JSON.stringify({ hash: auxiliary.betas_hash, betas: [...sent[1]!.betas].sort() })}`, + ]) + } finally { + endPiPrimaryTurn(storagePath, sessionId) + forgetPiMessageThread(sessionId) + __setLogTestSink(null) + core.setLogLevel(level) + } +}) + describe('Pi stream stop reasons', () => { const refusal = 'Claude refused this request (stop_reason: refusal).' const cases = [ From 2174ce7ab66d62e86b040082105685cd9f1d71ec Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:40:52 +0100 Subject: [PATCH 09/27] Paid API-key requests unshaped on every host; ANTHROPIC_INSECURE removed --- CHANGELOG.md | 2 + docs/environment.md | 1 - docs/request-rewriting.md | 2 +- docs/settings-file.md | 3 +- docs/transports.md | 6 +- packages/core/src/api-key-request.ts | 87 +++++++ packages/core/src/index.ts | 1 + packages/core/src/server-fallback-usage.ts | 2 + packages/opencode/src/index.ts | 83 +++--- packages/opencode/src/server-fallback.ts | 6 +- .../src/tests/opencode1-settings-read.test.ts | 75 +++--- .../tests/request-history.integration.test.ts | 243 +++++++++++------- packages/opencode/src/tests/transform.test.ts | 55 ---- packages/opencode/src/transform.ts | 11 - packages/opencode/src/v2/adapter.ts | 61 +---- packages/pi/src/convert.ts | 106 ++++---- packages/pi/src/stream.ts | 4 +- .../src/tests/request-history-stream.test.ts | 100 ++++++- 18 files changed, 483 insertions(+), 365 deletions(-) create mode 100644 packages/core/src/api-key-request.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ba215daa..00821117e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,8 @@ This repo is a CortexKit-maintained Anthropic auth monorepo for OpenCode and Pi. - OpenCode 1: after a server restart, a threaded session's first full request can reuse the previous full request's cache boundary, as on OpenCode 2 and Pi. - OpenCode 1 and Pi: eligible direct CacheKeep requests now use gzip, like OpenCode 2, and resend uncompressed if gzip is rejected. - OpenCode 1: keep-warm requests no longer appear in cache diagnostics or replace the previous real response, as on OpenCode 2. +- OpenCode 1 and Pi now send paid API-key requests like OpenCode 2, without adding a Claude Code prompt or billing signature or renaming tools. Claude subscription requests are unchanged. +- OpenCode 1, OpenCode 2 and Pi always verify TLS for API-key requests to custom HTTPS addresses. The `ANTHROPIC_INSECURE` environment variable is gone. - Pi: changing thinking effort during a conversation now preserves the prompt cache on models that support per-message effort, including in conversations shortened by Magic Context. - OpenCode 2 now keeps custom proxy headers off Claude sign-in requests, like OpenCode 1 and Pi, while still sending them on API-key routes. - For conversation requests, OpenCode 2 now matches OpenCode 1: the first eligible request sends a null previous message ID, and cache results and beta lists appear in debug logs. diff --git a/docs/environment.md b/docs/environment.md index 9fd9e545d..a96db7a9e 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -15,7 +15,6 @@ Path conventions depend on the artifact. In these docs: | Variable | Effect | | --- | --- | | `ANTHROPIC_BASE_URL` | Override the Anthropic endpoint with an HTTP(S) URL on API-key requests that have no route URL. Saved paid routes use their stored URL. Claude sign-in (OAuth) requests go only to `https://api.anthropic.com` (or the [custom gateway](settings-file.md#custom-gateway) in your own settings file), so OpenCode refuses them while this points elsewhere; it never sets or widens the gateway | -| `ANTHROPIC_INSECURE` | OpenCode 1 TLS opt-out for API-key requests: `1` or `true`, effective only with `ANTHROPIC_BASE_URL`; never applies to Claude sign-in (OAuth) requests, which always check certificates; avoid outside controlled diagnostics | | `ANTHROPIC_CUSTOM_HEADERS` | Add proxy metadata on API-key routes; ignored for OAuth | | `ANTHROPIC_MODEL` | Default proxy alias for any `claude-*` model | | `ANTHROPIC_DEFAULT_SONNET_MODEL` | Alias for `claude-sonnet-*` | diff --git a/docs/request-rewriting.md b/docs/request-rewriting.md index e4c1f31f7..36e48bf00 100644 --- a/docs/request-rewriting.md +++ b/docs/request-rewriting.md @@ -19,7 +19,7 @@ Model-family normalization supplies [adaptive thinking and effort](models.md#ada Pi replaces the Anthropic provider implementation and converts its transcript, tools and system prompt to the signed Claude-compatible request shape described above. Pi's ordinary subscription requests use the same billing lineage and turn indexes as OpenCode 1 and 2. Cache keep-warm requests, quota-window Prime requests and requests for a forked conversation stay outside the active turn's chain. When the converter recognizes Pi's standard documentation section, that paragraph is moved into a separate cached block before the first user's text. If the section layout is unrecognized, the prompt is moved as a whole rather than placing the documentation in top-level `system[]`, where Anthropic rejects it. Tool replay and origin-aware thinking-signature filtering preserve compatible Anthropic thinking and remove incompatible OpenAI reasoning signatures. -API-key/proxy sends have a separate policy: proxy header/model overrides apply there, while OAuth-only fallback fields and persona betas are removed. These controls do not turn an API-key route into subscription OAuth. See [environment overrides](environment.md#api-endpoint-and-proxy-routes). +OpenCode 1, OpenCode 2 and Pi send paid API-key requests without adding a Claude Code identity, changing tool names, or signing the body. The plugin still checks the message history, removes internal markers and OAuth-only fallback fields and persona betas, and applies the API route's endpoint, header and model overrides. See [environment overrides](environment.md#api-endpoint-and-proxy-routes). ## Safety fallback (OpenCode 1) diff --git a/docs/settings-file.md b/docs/settings-file.md index 23d9d9aeb..6b59f79ec 100644 --- a/docs/settings-file.md +++ b/docs/settings-file.md @@ -208,8 +208,7 @@ Through the gateway: requests the gateway does not take still use the relay as before, and a WebSocket relay still refuses them. - Redirects are refused, as for every sign-in request. -- Certificates are always checked; `ANTHROPIC_INSECURE` never applies to - sign-in requests. +- TLS certificates are always checked. - A loopback `http:` gateway is refused while `HTTP_PROXY` or `http_proxy` is set, because Bun would send those plain-text requests, with your sign-in token and gateway headers, through that proxy, and a repository's `.env` diff --git a/docs/transports.md b/docs/transports.md index 92c694547..068085ba7 100644 --- a/docs/transports.md +++ b/docs/transports.md @@ -49,7 +49,7 @@ The OpenCode 1 sidebar shows the relay and its transport only when requests can Claude Code 2.1.302, the version these requests present as, gzips request bodies. OAuth requests sent directly to `api.anthropic.com` (OpenCode 1, OpenCode 2 and Pi) do the same when the body is at least 4,096 characters: - The wire body is the signed request with its billing `cch` reset to `00000`, followed by a newline and 0 to 256 random spaces and tabs, compressed once with gzip at level 6. The request carries `content-encoding: gzip`; the runtime sets `content-length`. -- Smaller bodies, other hosts (including a [custom gateway](settings-file.md#custom-gateway)), API-key routes and relays go out uncompressed and signed. Gzip is also off whenever `HTTPS_PROXY`/`HTTP_PROXY` applies to `api.anthropic.com` (honouring `NO_PROXY`), `NODE_EXTRA_CA_CERTS` is set, or a client certificate (`CLAUDE_CODE_CLIENT_CERT`/`CLAUDE_CODE_CLIENT_KEY`) is configured. +- OAuth bodies under 4,096 characters and OAuth requests to a [custom gateway](settings-file.md#custom-gateway) or relay go out uncompressed and signed. API-key requests are neither compressed nor signed by the plugin. Gzip is also off whenever `HTTPS_PROXY`/`HTTP_PROXY` applies to `api.anthropic.com` (honouring `NO_PROXY`), `NODE_EXTRA_CA_CERTS` is set, or a client certificate (`CLAUDE_CODE_CLIENT_CERT`/`CLAUDE_CODE_CLIENT_KEY`) is configured. - `CLAUDE_CODE_GZIP_REQUEST_BODIES=0` turns it off. `=1` turns it on even in those cases. - Dumps, CacheKeep tracking and relay rescue work on the uncompressed signed body; a dump's `.body.json` is that body, not the wire bytes. Direct CacheKeep prewarms follow the same gzip rule on all three hosts; gateway prewarms stay uncompressed. OpenCode 1 and Pi resend an eligible prewarm uncompressed if the gzipped send is rejected. @@ -61,9 +61,9 @@ Relays always send the uncompressed body to Anthropic in this release: the relay ## Proxy routes -API-key routes can use a custom base URL and auth-header selection. The CLI's API-route inputs are listed in [commands](commands.md#opencode-cli). `ANTHROPIC_BASE_URL` applies only when the API-key request has no route URL. On OpenCode 1, OpenCode 2 and Pi, a saved paid route always uses its stored URL, even if it was saved with the default Anthropic URL. All three hosts honor `ANTHROPIC_MODEL` and `ANTHROPIC_DEFAULT_{SONNET,OPUS,HAIKU,FABLE}_MODEL` on API-key proxy routes. Pi also supports `ANTHROPIC_CUSTOM_HEADERS` there, without changing OAuth requests. Protected authentication and protocol headers cannot be replaced by custom headers. +API-key routes can use a custom base URL and auth-header selection. The CLI's API-route inputs are listed in [commands](commands.md#opencode-cli). `ANTHROPIC_BASE_URL` applies only when the API-key request has no route URL. On OpenCode 1, OpenCode 2 and Pi, a saved paid route always uses its stored URL, even if it was saved with the default Anthropic URL. All three hosts honor `ANTHROPIC_MODEL` and `ANTHROPIC_DEFAULT_{SONNET,OPUS,HAIKU,FABLE}_MODEL` on API-key proxy routes, and apply `ANTHROPIC_CUSTOM_HEADERS` only on API-key requests. Protected authentication and protocol headers cannot be replaced by custom headers. HTTPS connections, including to custom API-key addresses, always verify TLS certificates. -On OpenCode 1 and OpenCode 2, Claude sign-in (OAuth) requests go only to `https://api.anthropic.com`: a provider `baseURL` or `ANTHROPIC_BASE_URL` pointing elsewhere is refused for them with a local 400, and nothing is sent. Pi sends native OAuth only to that origin. The only other destination for OAuth model requests is a [custom gateway](settings-file.md#custom-gateway) in your own user settings file, on OpenCode 1, OpenCode 2 and Pi; it replaces the relay for those requests and never applies to sign-in, refresh or usage requests. OAuth requests never follow redirects and always check TLS certificates: `ANTHROPIC_INSECURE` applies only to OpenCode 1 API-key routes. +On OpenCode 1 and OpenCode 2, Claude sign-in (OAuth) requests go only to `https://api.anthropic.com`: a provider `baseURL` or `ANTHROPIC_BASE_URL` pointing elsewhere is refused for them with a local 400, and nothing is sent. Pi sends native OAuth only to that origin. The only other destination for OAuth model requests is a [custom gateway](settings-file.md#custom-gateway) in your own user settings file, on OpenCode 1, OpenCode 2 and Pi; it replaces the relay for those requests and never applies to sign-in, refresh or usage requests. OAuth requests never follow redirects. Only use endpoints you trust: the route receives the request content and its configured authorization. Do not use insecure transport settings as a remedy for a credential or custody error. diff --git a/packages/core/src/api-key-request.ts b/packages/core/src/api-key-request.ts new file mode 100644 index 000000000..243de586e --- /dev/null +++ b/packages/core/src/api-key-request.ts @@ -0,0 +1,87 @@ +import { mergeAnthropicBetas } from './constants.ts' +import { remapRequestBodyModel } from './model-remap.ts' +import { stripEmptyTrailingAssistantMessages } from './request-history.ts' +import { + SERVER_FALLBACK_SIGNATURE_PREFIX, + SERVER_SIDE_FALLBACK_BETA, + stripServerFallbackUsageMarkers, +} from './server-fallback-usage.ts' +import { applyRunnerTurnNotes } from './turn-end-note.ts' + +const OAUTH_ONLY_BETAS = new Set([ + 'oauth-2025-04-20', + 'claude-code-20250219', + SERVER_SIDE_FALLBACK_BETA, +]) + +/** Preserve the host's betas except those used by the plugin's OAuth route. */ +export function apiKeyRequestBetas(value: string): string { + const kept = value + .split(',') + .map((beta) => beta.trim()) + .filter((beta) => beta && !OAUTH_ONLY_BETAS.has(beta)) + return mergeAnthropicBetas(null, kept) +} + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value) +} + +/** Validate the transcript, scrub plugin-only fallback state and apply proxy aliases. */ +export function prepareApiKeyRequestBody( + body: Record, + scrubHostMarkers?: (body: Record) => boolean, +): boolean { + let changed = stripEmptyTrailingAssistantMessages(body.messages) > 0 + if (body.fallbacks === 'default') { + delete body.fallbacks + changed = true + } + if (stripServerFallbackUsageMarkers(body) > 0) changed = true + if (Array.isArray(body.messages)) { + for (const message of body.messages) { + if (message?.role !== 'assistant' || !Array.isArray(message.content)) + continue + const content = message.content.filter( + (block: unknown) => + !( + isRecord(block) && + block.type === 'thinking' && + typeof block.signature === 'string' && + block.signature.startsWith(SERVER_FALLBACK_SIGNATURE_PREFIX) + ), + ) + if (content.length !== message.content.length) { + message.content = content + changed = true + } + } + } + if (scrubHostMarkers?.(body)) changed = true + return remapRequestBodyModel(body) || changed +} + +/** Leave the host's original bytes intact when the API route need not edit them. */ +export function rewriteApiKeyRequestBody( + text: string, + options: { + sessionId?: string + modelId: string + scrubHostMarkers?: (body: Record) => boolean + }, +): string { + let body: unknown + try { + body = JSON.parse(text) + } catch { + return text + } + if (!isRecord(body)) return text + const changed = prepareApiKeyRequestBody(body, options.scrubHostMarkers) + applyRunnerTurnNotes(body, { + sessionId: options.sessionId, + modelId: options.modelId, + isOAuth: false, + }) + return changed ? JSON.stringify(body) : text +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 937d9b728..faa5721a1 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -35,6 +35,7 @@ export { setupUsage, } from '@cortexkit/common-auth/setup' export * from './accounts.ts' +export * from './api-key-request.ts' export { applyAnthropicApiBaseUrl } from './api-route-url.ts' export * from './auth.ts' export * from './billing.ts' diff --git a/packages/core/src/server-fallback-usage.ts b/packages/core/src/server-fallback-usage.ts index daf633f4f..e2d11026b 100644 --- a/packages/core/src/server-fallback-usage.ts +++ b/packages/core/src/server-fallback-usage.ts @@ -1,3 +1,5 @@ +export const SERVER_SIDE_FALLBACK_BETA = 'server-side-fallback-2026-07-01' +export const SERVER_FALLBACK_SIGNATURE_PREFIX = 'cortexkit-server-fallback-v1:' export const SERVER_FALLBACK_USAGE_MARKER_TEXT = '\u2060\u2060' export const SERVER_FALLBACK_USAGE_SIGNATURE_PREFIX = 'cortexkit-server-fallback-usage-v1:' diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index b5ef6bc30..b5c17f191 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -13,6 +13,7 @@ import { type AnthropicBillingRequest, type ApiKeyAccount, acquireNativeAccountRuntime, + apiKeyRequestBetas, applyCustomHeaders, assertNotCustodyTombstone, authorize, @@ -228,6 +229,7 @@ import { resetWaitDelayMs, resolveClaudeModelCapabilities, resolveNativePoolPaths, + rewriteApiKeyRequestBody, STICKY_ROUTING_MAIN_ACCOUNT_ID, StickyQuotaRetryCounter, type StickyRouteCandidate, @@ -292,6 +294,7 @@ import { reconcileCustodyStartup, } from './custody-mode.ts' import { + applyOpenCodeEffortMarkers, EFFORT_PLAN_REQUEST_HEADER, EffortMarkerCorrelationError, markOpenCodeEffortTransitions, @@ -387,7 +390,6 @@ import { createStrippedStream, extractLatestHybridMessageCacheAnchor, hybridUserMessageCacheAnchorFingerprints, - isInsecure, mergeHeaders, normalizeToolNameResponseError, rewriteRequestBody, @@ -7661,7 +7663,6 @@ const anthropicAuthPlugin = async ( account: ApiKeyAccount, trace?: PerfTrace, route = 'api_fallback', - currentStorage?: Awaited>, fableRequest?: FableRequestContext, mainAccessToken?: string, mainQuotaIdentity?: MainQuotaIdentityBinding, @@ -7675,7 +7676,6 @@ const anthropicAuthPlugin = async ( const directAffinity = requestHeaders.get('x-session-affinity') || requestHeaders.get('x-opencode-session') - const subagentRequest = isSubagentRequest(requestHeaders) const effortPlanHeader = requestHeaders.get(EFFORT_PLAN_REQUEST_HEADER) ?? undefined const resolvedEffortPlan = @@ -7697,47 +7697,37 @@ const anthropicAuthPlugin = async ( requestHeaders.delete(REQUEST_CLASS_REQUEST_HEADER) const billingRequestKind = takeBillingRequestKind(requestHeaders) let body = await fetchBody(input, init) - const wireSettings = requestWireSettings( - currentStorage, - parseRequestModel(body), - ) let streaming = false let dump: DumpHandle | null = null - let toolNameMap: ToolNameMap | undefined const originalBytes = typeof body === 'string' ? body.length : undefined if (body && typeof body === 'string') { const rewriteStart = nowMs() - const fastModeRequested = (() => { - if (!wireSettings.fastModeEnabled) return false - try { - return isFastModeSupportedModel(JSON.parse(body).model) - } catch { - return false - } - })() try { - body = await rewriteRequestBody(body, { - onToolNameMap: (map) => { - toolNameMap = map - }, - cache1hEnabled: !subagentRequest && wireSettings.cacheEnabled, - cache1hMode: wireSettings.cacheMode, - fastModeEnabled: fastModeRequested, + const originalBody = body + body = rewriteApiKeyRequestBody(body, { sessionId: directAffinity || undefined, modelId: fableRequest?.plan.requestedModel ?? parseRequestModel(body) ?? '', - midConversationEffortEnabled: false, - midConversationEffortPlan: effortPlanHeader, - midConversationEffortResolvedPlan: resolvedEffortPlan, - midConversationEffortPlanVersions: effortPlanVersions, - modelRemapEnabled: true, - perf: (stage, data) => - trace?.mark(`rewrite_body_${stage}`, { route, ...data }), + // OpenCode 1 carries effort transitions in its transcript. + // Validate and consume them without sending OAuth effort messages. + scrubHostMarkers: (payload) => { + const messages = payload.messages + applyOpenCodeEffortMarkers( + payload, + false, + effortPlanHeader, + resolvedEffortPlan, + effortPlanVersions, + ) + return payload.messages !== messages + }, }) + if (body !== originalBody) + requestHeaders.delete('content-length') } catch (error) { if (error instanceof EffortMarkerCorrelationError) { return effortMarkerFailureResponse(error) @@ -7747,12 +7737,6 @@ const anthropicAuthPlugin = async ( } throw error } - configureApiRouteHeaders(requestHeaders, account) - requestHeaders.set( - 'anthropic-beta', - mergeAnthropicBetas(requestHeaders.get('anthropic-beta'), []), - ) - if (fastModeRequested) addFastModeBetaHeader(requestHeaders) try { streaming = JSON.parse(body).stream === true } catch {} @@ -7761,15 +7745,15 @@ const anthropicAuthPlugin = async ( ms: roundMs(nowMs() - rewriteStart), originalBytes, rewrittenBytes: body.length, - cacheEnabled: !subagentRequest && wireSettings.cacheEnabled, - cacheMode: wireSettings.cacheMode, - fastModeEnabled: fastModeRequested, - subagent: subagentRequest, }) - } else { - configureApiRouteHeaders(requestHeaders, account) } + const betas = requestHeaders.get('anthropic-beta') + if (betas !== null) { + const kept = apiKeyRequestBetas(betas) + if (kept) requestHeaders.set('anthropic-beta', kept) + else requestHeaders.delete('anthropic-beta') + } const cacheDiagnosticsBetas = await getCacheDiagnosticsBetas(requestHeaders) const apiCredential = await authorizePaidFallback( @@ -7807,7 +7791,14 @@ const anthropicAuthPlugin = async ( ...init, body, headers: requestHeaders, - ...(isInsecure() && { tls: { rejectUnauthorized: false } }), + tls: { + ...( + init as + | (RequestInit & { tls?: Bun.TLSOptions }) + | undefined + )?.tls, + rejectUnauthorized: true, + }, }) // Redact the sent API key before response dumps, diagnostics or routing. response = scope.redactResponse( @@ -7845,7 +7836,6 @@ const anthropicAuthPlugin = async ( } attachCacheDiagnosticsResponse(response, { source: 'turn', - toolNameMap, accountId: account.id, synthetic: false, ...cacheDiagnosticsBetas, @@ -8541,9 +8531,7 @@ const anthropicAuthPlugin = async ( wireHeaders: Headers, ) => { // fetchOAuthModel rechecks the destination, refuses - // redirects and, with a gateway, sends there instead. The - // ANTHROPIC_INSECURE opt-out applies to API-key routes only: - // an OAuth send always checks certificates. + // redirects and, with a gateway, sends there instead. const send = () => fetchOAuthModel(gateway)(rewritten.input, { ...init, @@ -9531,7 +9519,6 @@ const anthropicAuthPlugin = async ( account, trace, `api_fallback_${index}`, - storage, options?.fableRequest, options?.mainAccessToken, options?.mainQuotaIdentity, diff --git a/packages/opencode/src/server-fallback.ts b/packages/opencode/src/server-fallback.ts index 9be119406..e2f19fbed 100644 --- a/packages/opencode/src/server-fallback.ts +++ b/packages/opencode/src/server-fallback.ts @@ -2,18 +2,20 @@ import { logger, normalizeAnthropicModelId, resolveClaudeModelCapabilities, + SERVER_FALLBACK_SIGNATURE_PREFIX, SERVER_FALLBACK_USAGE_MARKER_TEXT, SERVER_FALLBACK_USAGE_SIGNATURE_PREFIX, + SERVER_SIDE_FALLBACK_BETA, stripServerFallbackUsageMarkers, } from '@cortexkit/anthropic-auth-core' import { recoverableRefusalFamily } from './fable-fallback' -export const SERVER_SIDE_FALLBACK_BETA = 'server-side-fallback-2026-07-01' export const SERVER_FALLBACK_MARKER_TEXT = '\u2060' -export const SERVER_FALLBACK_SIGNATURE_PREFIX = 'cortexkit-server-fallback-v1:' export { + SERVER_FALLBACK_SIGNATURE_PREFIX, SERVER_FALLBACK_USAGE_MARKER_TEXT, SERVER_FALLBACK_USAGE_SIGNATURE_PREFIX, + SERVER_SIDE_FALLBACK_BETA, } type ServerSideFallbackIteration = { diff --git a/packages/opencode/src/tests/opencode1-settings-read.test.ts b/packages/opencode/src/tests/opencode1-settings-read.test.ts index 3405af560..73b031d7b 100644 --- a/packages/opencode/src/tests/opencode1-settings-read.test.ts +++ b/packages/opencode/src/tests/opencode1-settings-read.test.ts @@ -416,7 +416,11 @@ describe('OpenCode 1 settings service reads', () => { } for (const route of ['oauth', 'api'] as const) { - test(`${route} requests take fast mode and cache mode from their model context, regardless of process latches`, async () => { + const title = + route === 'oauth' + ? 'oauth requests take fast mode and cache mode from their model context, regardless of process latches' + : 'paid requests leave the host cache markers alone and do not add fast mode' + test(title, async () => { if (route === 'api') await useTempAccountFile( ctx, @@ -446,16 +450,37 @@ describe('OpenCode 1 settings service reads', () => { core.setCache1hState({ enabled: false, mode: 'hybrid' }) core.setFastModeEnabled(false) const opus = await instance.request('claude-opus-5-5[1m]') - if (route === 'api') + if (route === 'api') { expect(opus.headers.get('x-api-key')).toBe('synthetic-settings-key') - expect(opus.body.speed).toBe('fast') - expect(opus.body.cache_control).toEqual({ type: 'ephemeral', ttl: '1h' }) + expect(opus.body.speed).toBeUndefined() + expect(opus.body.cache_control).toBeUndefined() + expect(opus.body.messages).toEqual([ + { + role: 'user', + content: [ + { + type: 'text', + text: 'hello', + cache_control: { type: 'ephemeral' }, + }, + ], + }, + ]) + } else { + expect(opus.body.speed).toBe('fast') + expect(opus.body.cache_control).toEqual({ + type: 'ephemeral', + ttl: '1h', + }) + } core.setCache1hState({ enabled: true, mode: 'automatic' }) core.setFastModeEnabled(true) const other = await instance.request('claude-opus-4-8') expect(other.body.speed).toBeUndefined() expect(other.body.cache_control).toBeUndefined() - expect(JSON.stringify(other.body.messages)).toContain('"ttl":"1h"') + if (route === 'api') + expect(other.body.messages).toEqual(opus.body.messages) + else expect(JSON.stringify(other.body.messages)).toContain('"ttl":"1h"') expect( (await instance.runtime.read('claude-opus-5-5-20261001[1m]')) .policyStorage.claudeFast?.enabled, @@ -820,7 +845,6 @@ describe('OpenCode 1 user gateway', () => { url: string headers: Headers body: string - tls: unknown } function record( gatewayAnswer?: (body: Record) => Response | undefined, @@ -835,7 +859,6 @@ describe('OpenCode 1 user gateway', () => { url, headers: new Headers(init?.headers), body: typeof init?.body === 'string' ? init.body : '', - tls: (init as { tls?: unknown } | undefined)?.tls, }) if (url.startsWith(GATEWAY) && gatewayAnswer) { const answer = gatewayAnswer( @@ -1002,44 +1025,6 @@ describe('OpenCode 1 user gateway', () => { ) }) - for (const gateway of [true, false]) - test(`ANTHROPIC_INSECURE never turns off certificate checks on an OAuth send${gateway ? ' to the gateway' : ''}`, async () => { - const f = await fixture() - await f.put({ - quota_enabled: 'off', - ...(gateway ? { gateway_url: `${GATEWAY}/claude` } : {}), - }) - const seen = record() - const previous = { - base: process.env.ANTHROPIC_BASE_URL, - insecure: process.env.ANTHROPIC_INSECURE, - } - cleanups.push(() => { - if (previous.base === undefined) delete process.env.ANTHROPIC_BASE_URL - else process.env.ANTHROPIC_BASE_URL = previous.base - if (previous.insecure === undefined) - delete process.env.ANTHROPIC_INSECURE - else process.env.ANTHROPIC_INSECURE = previous.insecure - }) - // A repository `.env` can set both; the base URL passes the OAuth - // destination check, so nothing else stops the send. - process.env.ANTHROPIC_BASE_URL = 'https://api.anthropic.com' - process.env.ANTHROPIC_INSECURE = '1' - const instance = await f.launch() - const response = await instance.loader.fetch!( - MESSAGES_URL, - largeRequest('ses-oc1-insecure'), - ) - await response.text() - expect(response.status).toBe(200) - const models = seen.filter((entry) => entry.url.includes('/v1/messages')) - expect(models).toHaveLength(1) - expect(new URL(models[0]!.url).origin).toBe( - gateway ? GATEWAY : 'https://api.anthropic.com', - ) - for (const entry of seen) expect(entry.tls).toBeUndefined() - }) - test('a gateway takes requests instead of a configured relay, with one warning', async () => { const f = await fixture() await f.put({ diff --git a/packages/opencode/src/tests/request-history.integration.test.ts b/packages/opencode/src/tests/request-history.integration.test.ts index 779aadac5..7a5d1f553 100644 --- a/packages/opencode/src/tests/request-history.integration.test.ts +++ b/packages/opencode/src/tests/request-history.integration.test.ts @@ -5,6 +5,7 @@ import { join } from 'node:path' import { __setLogTestSink, type AccountStorage, + CLAUDE_CODE_IDENTITY, type LogTestRecord, resetCache1hState, resetDumpState, @@ -70,108 +71,176 @@ function readAccountStorage(): Promise { return readAccountStorageWithCtx(testContext) } -describe('OpenCode 1 service_tier shaping', () => { +describe('OpenCode 1 OAuth and paid request shaping', () => { const originalFetch = globalThis.fetch + const alias = process.env.ANTHROPIC_DEFAULT_OPUS_MODEL afterEach(() => { globalThis.fetch = originalFetch + if (alias === undefined) delete process.env.ANTHROPIC_DEFAULT_OPUS_MODEL + else process.env.ANTHROPIC_DEFAULT_OPUS_MODEL = alias }) - test.each(['oauth', 'api fallback'] as const)( - 'service_tier follows the OpenCode 1 %s route', - async (route) => { - await useTempAccountFile( - createFallbackStorage({ - fallbackOn: [429], - refresh: { - enabled: false, - intervalMinutes: 10, - refreshBeforeExpiryMinutes: 30, - }, - quota: { - enabled: false, - checkIntervalMinutes: 5, - minimumRemaining: {}, - failClosedOnUnknownQuota: false, + async function capture(route: 'oauth' | 'api fallback') { + await useTempAccountFile( + createFallbackStorage({ + fallbackOn: [429], + refresh: { + enabled: false, + intervalMinutes: 10, + refreshBeforeExpiryMinutes: 30, + }, + quota: { + enabled: false, + checkIntervalMinutes: 5, + minimumRemaining: {}, + failClosedOnUnknownQuota: false, + }, + accounts: [ + { + id: 'service-tier-api', + type: 'api', + apiKey: 'synthetic-service-tier-key', + baseURL: 'https://paid.invalid', + authHeader: 'x-api-key', }, - accounts: [ - { - id: 'service-tier-api', - type: 'api', - apiKey: 'synthetic-service-tier-key', - baseURL: 'https://paid.invalid', - authHeader: 'x-api-key', - }, - ], - }), + ], + }), + ) + process.env.ANTHROPIC_DEFAULT_OPUS_MODEL = 'paid-opus-alias' + const sent: Array<{ + url: string + headers: Headers + body: string + tls?: Bun.TLSOptions + }> = [] + globalThis.fetch = mock( + withNativeAdmission( + (input: string | URL | Request, init?: RequestInit) => { + const url = extractUrl(input) + if (url.includes('/claude_cli/bootstrap')) + return Promise.resolve( + Response.json({ + oauth_account: { account_uuid: 'service-tier-account' }, + }), + ) + if (url.includes('/api/oauth/usage')) + return Promise.resolve( + Response.json({ + five_hour: { utilization: 100 }, + seven_day: { utilization: 50 }, + }), + ) + if (url.includes('/v1/messages')) { + const headers = new Headers(init?.headers) + sent.push({ + url, + headers, + body: String(init?.body), + tls: ( + init as (RequestInit & { tls?: Bun.TLSOptions }) | undefined + )?.tls, + }) + return Promise.resolve( + new Response('{}', { + status: + route === 'api fallback' && headers.has('authorization') + ? 429 + : 200, + }), + ) + } + throw new Error(`Unexpected service-tier fixture request: ${url}`) + }, + ), + ) as unknown as typeof fetch + const plugin = await getPlugin() + try { + const auth = await plugin.auth.loader( + () => Promise.resolve({ type: 'oauth', ...syntheticMainHostAuth() }), + { models: {} }, ) - const sent: Array<{ headers: Headers; body: Record }> = - [] - globalThis.fetch = mock( - withNativeAdmission( - (input: string | URL | Request, init?: RequestInit) => { - const url = extractUrl(input) - if (url.includes('/claude_cli/bootstrap')) - return Promise.resolve( - Response.json({ - oauth_account: { account_uuid: 'service-tier-account' }, - }), - ) - if (url.includes('/api/oauth/usage')) - return Promise.resolve( - Response.json({ - five_hour: { utilization: 100 }, - seven_day: { utilization: 50 }, - }), - ) - if (url.includes('/v1/messages')) { - const headers = new Headers(init?.headers) - sent.push({ headers, body: JSON.parse(String(init?.body)) }) - return Promise.resolve( - new Response('{}', { - status: - route === 'api fallback' && headers.has('authorization') - ? 429 - : 200, - }), - ) - } - throw new Error(`Unexpected service-tier fixture request: ${url}`) + const payload = { + model: 'claude-opus-4-8', + max_tokens: 64, + service_tier: route === 'oauth' ? 'auto' : 'standard_only', + messages: [{ role: 'user', content: 'Hello' }], + system: [{ type: 'text', text: 'Keep the host prompt.' }], + tools: [ + { + name: 'read', + description: 'Read data', + input_schema: { type: 'object' }, }, - ), - ) as unknown as typeof fetch - const plugin = await getPlugin() - try { - const auth = await plugin.auth.loader( - () => Promise.resolve({ type: 'oauth', ...syntheticMainHostAuth() }), - { models: {} }, + ], + } + const response = await auth.fetch(MESSAGES_URL, { + method: 'POST', + headers: + route === 'oauth' + ? {} + : { + 'anthropic-beta': + 'host-feature-2026-01-01,oauth-2025-04-20,claude-code-20250219', + }, + body: JSON.stringify(payload), + }) + expect(response.status).toBe(200) + expect(sent).toHaveLength(route === 'oauth' ? 1 : 2) + return { sent, payload } + } finally { + await plugin.dispose?.() + } + } + + test.each(['oauth', 'api fallback'] as const)( + 'OpenCode 1 %s applies Claude Code shaping only on OAuth', + async (route) => { + const { sent, payload } = await capture(route) + expect(sent[0]?.headers.get('authorization')).toBe( + 'Bearer sk-ant-oat01-main-access', + ) + const oauthBody = sent[0]!.body + expect(oauthBody).toContain(CLAUDE_CODE_IDENTITY) + expect(oauthBody).toContain('x-anthropic-billing-header:') + expect(JSON.parse(oauthBody)).not.toHaveProperty('service_tier') + expect(JSON.parse(oauthBody).model).toBe(payload.model) + if (route === 'api fallback') { + expect(sent[1]?.headers.get('x-api-key')).toBe( + 'synthetic-service-tier-key', ) - const response = await auth.fetch(MESSAGES_URL, { - method: 'POST', - body: JSON.stringify({ - model: 'claude-opus-4-8', - max_tokens: 64, - service_tier: route === 'oauth' ? 'auto' : 'standard_only', - messages: [{ role: 'user', content: 'Hello' }], - }), + expect(new URL(sent[1]!.url).origin).toBe('https://paid.invalid') + expect(JSON.parse(sent[1]!.body)).toEqual({ + ...payload, + model: 'paid-opus-alias', }) - expect(response.status).toBe(200) - expect(sent).toHaveLength(route === 'oauth' ? 1 : 2) - expect(sent[0]?.headers.get('authorization')).toBe( - 'Bearer sk-ant-oat01-main-access', + expect(sent[1]!.headers.get('anthropic-beta')).toBe( + 'host-feature-2026-01-01', ) - expect(sent[0]?.body).not.toHaveProperty('service_tier') - if (route === 'api fallback') { - expect(sent[1]?.headers.get('x-api-key')).toBe( - 'synthetic-service-tier-key', - ) - expect(sent[1]?.body.service_tier).toBe('standard_only') - } - } finally { - await plugin.dispose?.() } }, ) + + test('OpenCode 1 verifies TLS for paid sends to a custom address even with the old opt-out set', async () => { + const baseURL = process.env.ANTHROPIC_BASE_URL + const insecure = process.env.ANTHROPIC_INSECURE + try { + // The explicit paid URL wins over this environment default. Keeping the + // default on Anthropic lets the OAuth attempt reach the fallback decision. + process.env.ANTHROPIC_BASE_URL = 'https://api.anthropic.com' + process.env.ANTHROPIC_INSECURE = '1' + const { sent } = await capture('api fallback') + const paid = sent[1]! + expect(new URL(paid.url).origin).toBe('https://paid.invalid') + expect(paid.headers.get('x-api-key')).toBe('synthetic-service-tier-key') + expect(paid.tls?.rejectUnauthorized ?? true).toBe(true) + } finally { + if (baseURL === undefined) delete process.env.ANTHROPIC_BASE_URL + else process.env.ANTHROPIC_BASE_URL = baseURL + if (insecure === undefined) delete process.env.ANTHROPIC_INSECURE + else process.env.ANTHROPIC_INSECURE = insecure + } + }) }) describe('Fable 5.1 request-scoped effort history', () => { diff --git a/packages/opencode/src/tests/transform.test.ts b/packages/opencode/src/tests/transform.test.ts index 2a97292c9..fa42e4f87 100644 --- a/packages/opencode/src/tests/transform.test.ts +++ b/packages/opencode/src/tests/transform.test.ts @@ -44,7 +44,6 @@ import { extractLatestHybridMessageCacheAnchor, getSanitizeMemoStats, hasPinnedFirstUserTextForTest, - isInsecure, mergeBetaHeaders, mergeHeaders, NON_STREAMING_DIAGNOSTICS_MAX_BYTES, @@ -1784,60 +1783,6 @@ describe('rewriteUrl', () => { }) }) -describe('isInsecure', () => { - const originalBaseUrl = process.env.ANTHROPIC_BASE_URL - const originalInsecure = process.env.ANTHROPIC_INSECURE - - afterEach(() => { - if (originalBaseUrl === undefined) { - delete process.env.ANTHROPIC_BASE_URL - } else { - process.env.ANTHROPIC_BASE_URL = originalBaseUrl - } - if (originalInsecure === undefined) { - delete process.env.ANTHROPIC_INSECURE - } else { - process.env.ANTHROPIC_INSECURE = originalInsecure - } - }) - - test('returns false when neither env var is set', () => { - delete process.env.ANTHROPIC_BASE_URL - delete process.env.ANTHROPIC_INSECURE - expect(isInsecure()).toBe(false) - }) - - test('returns false when only ANTHROPIC_INSECURE is set (no base URL)', () => { - delete process.env.ANTHROPIC_BASE_URL - process.env.ANTHROPIC_INSECURE = '1' - expect(isInsecure()).toBe(false) - }) - - test('returns false when ANTHROPIC_BASE_URL is set but ANTHROPIC_INSECURE is not', () => { - process.env.ANTHROPIC_BASE_URL = 'https://proxy.local' - delete process.env.ANTHROPIC_INSECURE - expect(isInsecure()).toBe(false) - }) - - test('returns true when both are set and ANTHROPIC_INSECURE is "1"', () => { - process.env.ANTHROPIC_BASE_URL = 'https://proxy.local' - process.env.ANTHROPIC_INSECURE = '1' - expect(isInsecure()).toBe(true) - }) - - test('returns true when ANTHROPIC_INSECURE is "true"', () => { - process.env.ANTHROPIC_BASE_URL = 'https://proxy.local' - process.env.ANTHROPIC_INSECURE = 'true' - expect(isInsecure()).toBe(true) - }) - - test('returns false for other ANTHROPIC_INSECURE values', () => { - process.env.ANTHROPIC_BASE_URL = 'https://proxy.local' - process.env.ANTHROPIC_INSECURE = 'yes' - expect(isInsecure()).toBe(false) - }) -}) - describe('createStrippedStream', () => { test('rewrites the lane-start max_tokens finish as end_turn before completion', async () => { const finishReasons: string[] = [] diff --git a/packages/opencode/src/transform.ts b/packages/opencode/src/transform.ts index 38664018a..0c48406b0 100644 --- a/packages/opencode/src/transform.ts +++ b/packages/opencode/src/transform.ts @@ -523,17 +523,6 @@ function createToolNameRewriter( } } -/** - * Check if TLS verification should be skipped for custom API endpoints. - * Only effective when ANTHROPIC_BASE_URL is also set, and only on API-key - * routes: Claude OAuth sends always check certificates. - */ -export function isInsecure(): boolean { - if (!process.env.ANTHROPIC_BASE_URL?.trim()) return false - const raw = process.env.ANTHROPIC_INSECURE?.trim() - return raw === '1' || raw === 'true' -} - /** * Rewrite the request URL to add ?beta=true for /v1/messages requests. * When ANTHROPIC_BASE_URL is set, overrides the origin (protocol + host) diff --git a/packages/opencode/src/v2/adapter.ts b/packages/opencode/src/v2/adapter.ts index 3fc054589..2a9094d3e 100644 --- a/packages/opencode/src/v2/adapter.ts +++ b/packages/opencode/src/v2/adapter.ts @@ -9,9 +9,9 @@ import { createHash, randomUUID } from 'node:crypto' import { type AnthropicBillingRequest, AnthropicOAuthOriginError, + apiKeyRequestBetas, applyClaudeGatewayHeaders, applyCustomHeaders, - applyRunnerTurnNotes, assertHostAuthorityStable, assertNotCustodyTombstone, CACHE_DIAGNOSTICS_BETA, @@ -41,7 +41,6 @@ import { isNativeTransientAccountError, type MessageThreadRequest, MessageThreadTracker, - mergeAnthropicBetas, observeAnthropicBillingResponse, type ProviderErrorRedactor, type ProviderErrorResponseScope, @@ -51,12 +50,12 @@ import { type RequestGzipLatch, relayProxyApplies, remapModelId, - remapRequestBodyModel, reportAnthropicBillingFailure, requestCacheLifetimeMs, requestShortestCacheLifetimeMs, requestSignal, resolveNativePoolPaths, + rewriteApiKeyRequestBody, runWithRequestSignal, sendWithRequestGzip, setDumpEnabled as setDumpEnabledCore, @@ -64,7 +63,6 @@ import { stateLayoutOfPaths, stateRefusalCause, stateRefusalPublicMessage, - stripEmptyTrailingAssistantMessages, summarizeCacheTtl, TrailingAssistantHistoryError, } from '@cortexkit/anthropic-auth-core' @@ -94,10 +92,6 @@ import { import { LANE_START_REQUEST_HEADER } from '../lane-start' import { requireOAuthDestination } from '../oauth-destination' import { isAuxiliaryAgent } from '../request-class' -import { - applyServerSideFallbackToBody, - SERVER_SIDE_FALLBACK_BETA, -} from '../server-fallback' import { createStrippedStream, rewriteRequestBody, @@ -780,50 +774,6 @@ function sendSecrets(send: PendingSend, physical: Headers): string[] { return [...new Set(secrets.filter(Boolean))] } -/** - * Betas that this plugin itself adds to its OAuth sends: the OAuth beta, the - * Claude Code persona beta, and the server-side fallback opt-in that goes - * with the `fallbacks` body field the API route also removes. They are - * stripped from API-key sends so the plugin's OAuth persona and fallback - * handoff never reach an API key or proxy route. Every other beta value the - * host requested is passed on unchanged. - */ -const OAUTH_ONLY_BETAS = new Set([ - 'oauth-2025-04-20', - 'claude-code-20250219', - SERVER_SIDE_FALLBACK_BETA, -]) - -/** Remove plugin-added OAuth authentication, Claude Code compatibility and server - * safety-fallback betas from paid API/proxy sends; preserve unrelated host betas. */ -function apiBetas(value: string) { - const kept = value - .split(',') - .map((beta) => beta.trim()) - .filter((beta) => beta && !OAUTH_ONLY_BETAS.has(beta)) - return mergeAnthropicBetas(null, kept) -} - -/** - * Validate history, remove OAuth-only fallback fields and internal boundary - * markers, and apply the configured model alias for paid API/proxy requests. - * No Claude Code identity, tool-name prefix or body signature is added. - * Preserve the original text when no field changes or the body is not an object. - */ -function rewriteApiBody(body: string, sessionId: string, modelId: string) { - const parsed = parseJson(body) - if (!isRecord(parsed)) return body - const removed = stripEmptyTrailingAssistantMessages(parsed.messages) - const hadFallbacks = Object.hasOwn(parsed, 'fallbacks') - const { droppedMarkers } = applyServerSideFallbackToBody(parsed, false) - const fallbacksRemoved = hadFallbacks && !Object.hasOwn(parsed, 'fallbacks') - const remapped = remapRequestBodyModel(parsed) - applyRunnerTurnNotes(parsed, { sessionId, modelId, isOAuth: false }) - return removed > 0 || droppedMarkers > 0 || fallbacksRemoved || remapped - ? JSON.stringify(parsed) - : body -} - /** Resolves `work` or gives up after `ms`, so a stuck callback cannot hold the host. */ async function settleWithin( work: Promise | void, @@ -1438,7 +1388,10 @@ export function createNativeAnthropicAdapter( }) } else { if (body !== undefined && messages) - body = rewriteApiBody(body, input.sessionID, input.modelID) + body = rewriteApiKeyRequestBody(body, { + sessionId: input.sessionID, + modelId: input.modelID, + }) headers.delete('authorization') headers.delete('x-api-key') for (const [name, value] of Object.entries(send.apiHeaders ?? {})) { @@ -1450,7 +1403,7 @@ export function createNativeAnthropicAdapter( } const betas = headers.get('anthropic-beta') if (betas !== null) { - const kept = apiBetas(betas) + const kept = apiKeyRequestBetas(betas) if (kept) headers.set('anthropic-beta', kept) else headers.delete('anthropic-beta') } diff --git a/packages/pi/src/convert.ts b/packages/pi/src/convert.ts index 4dcac24c7..0ab409a55 100644 --- a/packages/pi/src/convert.ts +++ b/packages/pi/src/convert.ts @@ -31,8 +31,8 @@ import { isOpenAIReasoningSignature, LANE_START_TEXT, orderClaudeCodeBody, + prepareApiKeyRequestBody, readSessionCachePolicy, - remapRequestBodyModel, requestCacheLifetimeMs, selectClaudeCodeBetas, signRequestBody, @@ -255,6 +255,7 @@ function convertMessages( targetModelId: string, visibleReplies: WeakMap, droppedAssistants: WeakSet, + mapToolName = toClaudeCodeToolName, ): AnthropicRequestBody['messages'] { const result: AnthropicRequestBody['messages'] = [] // Effort history counts source assistant turns, including ones with nothing @@ -353,7 +354,7 @@ function convertMessages( blocks.push({ type: 'tool_use', id: sanitizeToolId(block.id), - name: toClaudeCodeToolName(block.name), + name: mapToolName(block.name), input: block.arguments, }) } @@ -423,11 +424,12 @@ function convertMessages( function convertTools( tools: Tool[] | undefined, + mapToolName: (name: string) => string, ): AnthropicRequestBody['tools'] { if (!tools?.length) return undefined return tools.map((tool) => ({ // Names are checked for collisions by createClaudeCodeToolNameMap first. - name: toClaudeCodeToolName(tool.name), + name: mapToolName(tool.name), description: tool.description, input_schema: { type: 'object', @@ -757,6 +759,8 @@ export async function buildAnthropicRequest( fastModeEnabled = false, identity?: ClaudeCodeIdentity, controls: { + /** Convert Pi's typed context without adding Claude Code wire shaping. */ + apiKey?: boolean billingLineage?: BillingLineageFields effortTransitions?: readonly PiEffortTransition[] forkBaseMessageCount?: number @@ -765,7 +769,6 @@ export async function buildAnthropicRequest( /** Leave the billing signature placeholder for the transport to finalize. */ deferSigning?: boolean cacheDiagnosticsPreviousMessageId?: string | null - modelRemapEnabled?: boolean thinkingPrefixMismatchBehavior?: ThinkingPrefixMismatchBehavior turnEndNote?: { tools: string[] } /** @@ -784,6 +787,8 @@ export async function buildAnthropicRequest( /** Set only when `controls.forkEffort` changed the request. */ forkEffortApplied?: PiForkEffortHint }> { + const apiKey = controls.apiKey === true + const mapToolName = apiKey ? (name: string) => name : toClaudeCodeToolName const forkBase = controls.forkBaseMessageCount === undefined ? undefined @@ -831,6 +836,7 @@ export async function buildAnthropicRequest( modelId, visibleReplies, droppedAssistants, + mapToolName, ) stripEmptyTrailingAssistantMessages(messages) const baseLastMessage = forkBase @@ -856,30 +862,35 @@ export async function buildAnthropicRequest( : undefined if (forkHead && forkFirstUserText === undefined) throw new PiForkRefusal('base') - const system = [ - { - type: 'text', - text: buildBillingHeaderValue( - messages, - undefined, - CLAUDE_CODE_ENTRYPOINT, - options?.sessionId - ? forkHead - ? forkFirstUserText - : firstUserTextTracker.resolve(options.sessionId, messages) - : undefined, - identity && !forkHead && controls.billingLineage?.promptId - ? { - ...controls.billingLineage, - promptIndex: countUserPrompts(messages), - } - : undefined, - ), - }, - { type: 'text', text: CLAUDE_CODE_IDENTITY }, - ] + const system = apiKey + ? [] + : [ + { + type: 'text', + text: buildBillingHeaderValue( + messages, + undefined, + CLAUDE_CODE_ENTRYPOINT, + options?.sessionId + ? forkHead + ? forkFirstUserText + : firstUserTextTracker.resolve(options.sessionId, messages) + : undefined, + identity && !forkHead && controls.billingLineage?.promptId + ? { + ...controls.billingLineage, + promptIndex: countUserPrompts(messages), + } + : undefined, + ), + }, + { type: 'text', text: CLAUDE_CODE_IDENTITY }, + ] const systemPrompt = systemPromptText(context.systemPrompt) - if (systemPrompt.trim()) { + if (apiKey) { + if (systemPrompt.trim()) + system.push({ type: 'text', text: sanitize(systemPrompt) }) + } else if (systemPrompt.trim()) { // Pi's prompt cannot sit whole in the top-level system[] array: two lines of // its documentation paragraph (the docs/*.md enumeration and the "follow .md // cross-references" instruction) are each independently sufficient to make @@ -915,15 +926,17 @@ export async function buildAnthropicRequest( model: modelId, max_tokens: options?.maxTokens ?? 16_384, stream: true, - system, + ...(system.length ? { system } : {}), messages, } - const declaredToolNames = createClaudeCodeToolNameMap(context.tools ?? []) - const tools = convertTools(context.tools) + const declaredToolNames = apiKey + ? new Map() + : createClaudeCodeToolNameMap(context.tools ?? []) + const tools = convertTools(context.tools, mapToolName) if (tools?.length) body.tools = tools - if (fastModeEnabled && isFastModeSupportedModel(modelId)) { + if (!apiKey && fastModeEnabled && isFastModeSupportedModel(modelId)) { body.speed = 'fast' } @@ -1009,13 +1022,19 @@ export async function buildAnthropicRequest( modelId, isOAuth: !!identity, }) - addEphemeralCacheControl(body) - const cachePolicy = readSessionCachePolicy(options?.sessionId, !!identity) - const cacheEnabled = - cachePolicy?.ttl !== undefined ? cachePolicy.ttl !== 'none' : cache.enabled - applyCacheMode(body, cacheEnabled, cache.mode) - if (cacheEnabled && cache.mode === 'hybrid' && !forkHead && !forkBase) - applyHybridCacheBridge(body) + const cachePolicy = apiKey + ? undefined + : readSessionCachePolicy(options?.sessionId, !!identity) + if (!apiKey) { + addEphemeralCacheControl(body) + const cacheEnabled = + cachePolicy?.ttl !== undefined + ? cachePolicy.ttl !== 'none' + : cache.enabled + applyCacheMode(body, cacheEnabled, cache.mode) + if (cacheEnabled && cache.mode === 'hybrid' && !forkHead && !forkBase) + applyHybridCacheBridge(body) + } if (identity) { applyThinkingBindingControls( body, @@ -1036,7 +1055,8 @@ export async function buildAnthropicRequest( body.max_tokens = 1 delete body.thinking } - applySessionCacheTtl(body, cachePolicy?.ttl) + if (apiKey) prepareApiKeyRequestBody(body) + else applySessionCacheTtl(body, cachePolicy?.ttl) if (baseBoundary >= 0) applyForkCacheBridge(body, baseBoundary) // As in Pi's native adapter, replacements must still request SSE. Hooks own // the validity of their other edits and must not add a fifth cache breakpoint: @@ -1049,18 +1069,16 @@ export async function buildAnthropicRequest( throw new Error( `Anthropic accepts at most 4 cache breakpoints; the onPayload hook left ${breakpoints}`, ) - if (controls.modelRemapEnabled) remapRequestBodyModel(body) if ( controls.cacheDiagnosticsPreviousMessageId !== undefined && selectClaudeCodeBetas(body).split(',').includes(CACHE_DIAGNOSTICS_BETA) ) applyCacheDiagnosticsOptIn(body, controls.cacheDiagnosticsPreviousMessageId) const unsigned = JSON.stringify( - orderClaudeCodeBody(body, { isOAuth: !!identity }), + apiKey ? body : orderClaudeCodeBody(body, { isOAuth: !!identity }), ) - const bodyText = controls.deferSigning - ? unsigned - : await signRequestBody(unsigned) + const bodyText = + apiKey || controls.deferSigning ? unsigned : await signRequestBody(unsigned) // Translate only known host/wire pairs that survived the hook and JSON // serialization. Hook-added or renamed tools must not acquire an alias, and // response decoding must never change outgoing names or signed history. diff --git a/packages/pi/src/stream.ts b/packages/pi/src/stream.ts index 9995d5d23..d05008180 100644 --- a/packages/pi/src/stream.ts +++ b/packages/pi/src/stream.ts @@ -1137,13 +1137,13 @@ async function sendAnthropicRequestAttempt( isFastModePersistentlyEnabled(storage), identity, { + apiKey: !!options.apiAccount, deferSigning: true, billingLineage: lineage, ...(diagnosticsSession && { cacheDiagnosticsPreviousMessageId: diagnosticsSession.previous?.messageId ?? null, }), - modelRemapEnabled: options.apiAccount !== undefined, forkBaseMessageCount: forkBase?.messageCount, // API-key routes send no effort history, so no fork hint either. forkEffort: options.apiAccount @@ -1436,7 +1436,7 @@ async function sendAnthropicRequestAttempt( options.onThreadPrepared?.(threadRequest.fail) wireBodyText = threadRequest.bodyText init.body = wireBodyText - } else { + } else if (!options.apiAccount) { wireBodyText = await signRequestBody(bodyText) init.body = wireBodyText } diff --git a/packages/pi/src/tests/request-history-stream.test.ts b/packages/pi/src/tests/request-history-stream.test.ts index 3799863a8..e82336e30 100644 --- a/packages/pi/src/tests/request-history-stream.test.ts +++ b/packages/pi/src/tests/request-history-stream.test.ts @@ -237,7 +237,12 @@ test('Pi model-switch stream omits old thinking and keeps the effort change betw ]) }) -test('Pi API-key requests never use message threads', async () => { +test('Pi API-key requests preserve the host prompt and tools without Claude Code shaping', async () => { + const previous = { + ANTHROPIC_BASE_URL: process.env.ANTHROPIC_BASE_URL, + ANTHROPIC_DEFAULT_OPUS_MODEL: process.env.ANTHROPIC_DEFAULT_OPUS_MODEL, + ANTHROPIC_MODEL: process.env.ANTHROPIC_MODEL, + } directory = await mkdtemp(join(tmpdir(), 'pi-api-thread-exclusion-')) const storagePath = join(directory, 'accounts.json') currentStoragePath = storagePath @@ -250,7 +255,7 @@ test('Pi API-key requests never use message threads', async () => { id: 'api-thread', type: 'api', apiKey: 'synthetic-api-thread-key', - baseURL: 'https://paid.invalid', + baseURL: 'https://paid.invalid/proxy/v2', }, ], }, @@ -263,9 +268,16 @@ test('Pi API-key requests never use message threads', async () => { (account) => account.id === 'api-thread', ) if (!apiAccount) throw new Error('Missing API account fixture') + process.env.ANTHROPIC_BASE_URL = 'https://unused-paid.invalid' + // The Opus alias is itself a Claude ID, so remapping it a second time + // would match the generic override and lose the Opus-specific choice. + process.env.ANTHROPIC_DEFAULT_OPUS_MODEL = 'claude-paid-opus-alias' + process.env.ANTHROPIC_MODEL = 'paid-generic-alias' let sent: RequestInit | undefined - const fetchImpl = (async (_input: unknown, init?: RequestInit) => { + let url: string | undefined + const fetchImpl = (async (input: unknown, init?: RequestInit) => { sent = init + url = String(input) return new Response( 'event: message_stop\ndata: {"type":"message_stop"}\n\n', { headers: { 'content-type': 'text/event-stream' } }, @@ -276,8 +288,43 @@ test('Pi API-key requests never use message threads', async () => { { model, context: { - messages: [{ role: 'user', content: 'Hello', timestamp: 0 }], - tools: [], + systemPrompt: 'Keep the Pi system prompt.', + messages: [ + { role: 'user', content: 'Hello', timestamp: 0 }, + { + ...assistant, + content: [ + { + type: 'thinking', + thinking: '\u2060', + thinkingSignature: + 'cortexkit-server-fallback-v1:claude-fable-5-1|claude-opus-5-5', + }, + { + type: 'toolCall', + id: 'call_read', + name: 'read', + arguments: {}, + }, + ], + stopReason: 'toolUse', + }, + { + role: 'toolResult', + toolCallId: 'call_read', + toolName: 'read', + content: [{ type: 'text', text: 'Result' }], + isError: false, + timestamp: 2, + }, + ], + tools: [ + { + name: 'read', + description: 'Read data', + parameters: { type: 'object', properties: {} }, + }, + ], }, apiAccount, storagePath, @@ -286,18 +333,51 @@ test('Pi API-key requests never use message threads', async () => { onPayload: (payload) => ({ ...(payload as Record), service_tier: 'standard_only', + fallbacks: 'default', }), }, }, { fetch: fetchImpl }, ) ).text() - expect(JSON.parse(String(sent?.body)).thread).toBeUndefined() - expect(JSON.parse(String(sent?.body)).service_tier).toBe('standard_only') - expect(new Headers(sent?.headers).get('anthropic-beta')).not.toContain( - 'message-threads-', - ) + const body = JSON.parse(String(sent?.body)) + expect(body.system).toEqual([ + { type: 'text', text: 'Keep the Pi system prompt.' }, + ]) + expect(body.tools).toMatchObject([{ name: 'read' }]) + expect(body.messages).toEqual([ + { role: 'user', content: 'Hello' }, + { + role: 'assistant', + content: [ + { type: 'tool_use', id: 'call_read', name: 'read', input: {} }, + ], + }, + { + role: 'user', + content: [ + { + type: 'tool_result', + tool_use_id: 'call_read', + content: 'Result', + is_error: false, + }, + ], + }, + ]) + expect(body.model).toBe('claude-paid-opus-alias') + expect(body.thread).toBeUndefined() + expect(body.fallbacks).toBeUndefined() + expect(body.service_tier).toBe('standard_only') + expect(url).toBe('https://paid.invalid/proxy/v2/messages?beta=true') + const headers = new Headers(sent?.headers) + expect(headers.get('authorization')).toBe('Bearer synthetic-api-thread-key') + expect(headers.get('anthropic-beta')).not.toContain('message-threads-') } finally { + for (const [key, value] of Object.entries(previous)) { + if (value === undefined) delete process.env[key] + else process.env[key] = value + } await closePiNativeRuntime(storagePath) } }) From 75b281ba751ef4dcbd239227d345e6a2de5cd4d2 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:06:53 +0100 Subject: [PATCH 10/27] mason: align cache default and remove OpenCode quota feed OpenCode 2 now uses the short cache when the setting is missing or default; existing settings and runner policies still decide explicit choices. Update the release-oracle comparison only for the removed setting and the intentional default wire difference. Remove the opt-in filesystem feed and keep the existing quota header harvest and relay coverage. Keep the legacy stored field available to migration for rollback; the shared settings reader reports it as unknown without rewriting the file. --- CHANGELOG.md | 2 + docs/accounts-and-routing.md | 2 - docs/cache.md | 3 +- docs/configuration.md | 11 +- docs/environment.md | 3 +- docs/features.md | 4 +- docs/settings-file.md | 21 +- .../core/schema/anthropic-auth.schema.json | 22 - packages/core/src/accounts.ts | 5 +- packages/core/src/index.ts | 1 - packages/core/src/native-account-view.ts | 1 - packages/core/src/native-migration-source.ts | 2 +- packages/core/src/native-settings-write.ts | 1 - packages/core/src/quota-header-feed.ts | 478 ------------ packages/core/src/settings-definition.ts | 5 +- packages/core/src/settings-move-source.ts | 1 - packages/core/src/settings-record.ts | 4 - .../src/tests/native-runtime-settings.test.ts | 7 - .../src/tests/native-setup-settings.test.ts | 1 - .../src/tests/settings-definition.test.ts | 7 - .../src/tests/settings-move-source.test.ts | 5 +- .../core/src/tests/settings-reader-fixture.ts | 1 - .../core/src/tests/settings-record.test.ts | 3 - .../core/src/tests/settings-service.test.ts | 18 + packages/core/src/tests/setup.ts | 5 - packages/e2e-tests/src/harness.ts | 2 - packages/e2e-tests/src/opencode-runner.ts | 12 - .../tests/native-process-fixture.test.ts | 1 - .../tests/quota-header-relay.test.ts | 59 +- .../scripts/smoke-tui-pack-install.ts | 3 - packages/opencode/src/index.ts | 128 +--- .../src/tests/account-command.test.ts | 1 - .../src/tests/add-account-flows.test.ts | 1 - .../commands-and-profiles.integration.test.ts | 2 +- .../src/tests/custody-tombstone.test.ts | 1 - .../src/tests/dispose-cleanup.test.ts | 1 - .../tests/fallback-token-use-sites.test.ts | 1 - .../opencode/src/tests/host-isolation.test.ts | 3 - packages/opencode/src/tests/info-logs.test.ts | 1 - .../src/tests/killswitch-preflight.test.ts | 1 - .../src/tests/local-routing-migration.test.ts | 3 - packages/opencode/src/tests/native-fixture.ts | 2 - .../src/tests/native-menu-settings.test.ts | 1 - .../opencode/src/tests/native-serving.test.ts | 5 - .../src/tests/native-status-profile.test.ts | 1 - .../oauth-callback-corrupt-store.test.ts | 1 - .../src/tests/opencode1-settings-read.test.ts | 39 +- .../opencode/src/tests/opencode2-e2e.test.ts | 1 - .../src/tests/opencode2-settings-read.test.ts | 8 +- .../src/tests/opencode2-settings-readers.ts | 5 - .../opencode/src/tests/preload-sandbox.ts | 1 - .../opencode/src/tests/provider-error.test.ts | 2 - .../src/tests/quota-header-feed.test.ts | 697 ------------------ .../quota-header-harvest.integration.test.ts | 2 +- ... => quota-persistence.integration.test.ts} | 475 +----------- ...-policy-and-killswitch.integration.test.ts | 61 +- .../opencode/src/tests/quota-sweep.test.ts | 1 - .../src/tests/relay-store-location.test.ts | 1 - .../routing-and-sticky.integration.test.ts | 2 +- .../src/tests/rpc-multi-project.test.ts | 43 +- .../src/tests/scoped-custody-serving.test.ts | 1 - .../scoped-main-quota-persistence.test.ts | 1 - .../src/tests/settings-install-paths.test.ts | 1 - .../src/tests/settings-snapshot-fixture.ts | 26 + .../src/tests/settings-three-way.test.ts | 20 +- .../opencode/src/tests/setup-command.test.ts | 1 - .../tests/state-layout-host-wiring.test.ts | 2 - .../tests/support/opencode1-pool-fixture.ts | 4 - ...code1-quota-feed.ts => opencode1-quota.ts} | 92 +-- .../support/opencode1-state-observers.ts | 2 +- .../tests/support/opencode1-test-context.ts | 1 - packages/opencode/src/v2/wire.ts | 2 +- packages/pi/src/tests/settings-read.test.ts | 7 +- .../pi/src/tests/settings-snapshot-fixture.ts | 2 - 74 files changed, 159 insertions(+), 2184 deletions(-) delete mode 100644 packages/core/src/quota-header-feed.ts delete mode 100644 packages/opencode/src/tests/quota-header-feed.test.ts rename packages/opencode/src/tests/{quota-feed.integration.test.ts => quota-persistence.integration.test.ts} (80%) rename packages/opencode/src/tests/support/{opencode1-quota-feed.ts => opencode1-quota.ts} (64%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 00821117e..12d9fe24b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,8 @@ This repo is a CortexKit-maintained Anthropic auth monorepo for OpenCode and Pi. - Pi, like OpenCode 1 and 2, now updates each subscription account's quota from Claude's replies without waiting for the next quota poll. - Pi's paid API-key route now honors the same model aliases as OpenCode 1 and 2 and keeps its configured endpoint. - Pi now links cache diagnostics across conversation replies like OpenCode 1 and 2, with cache results and beta lists in the debug log. +- OpenCode 2 now uses the five-minute Claude prompt cache by default, like OpenCode 1 and Pi. An explicit cache setting or Agent Runner session policy still takes precedence. +- OpenCode 1 no longer publishes the optional quota header feed; quota readings still reach the vault. The `quota_header_feed_enabled` setting is gone and can be deleted from your settings file. ## 2.16.5 diff --git a/docs/accounts-and-routing.md b/docs/accounts-and-routing.md index 10da2d869..25ba736a6 100644 --- a/docs/accounts-and-routing.md +++ b/docs/accounts-and-routing.md @@ -50,8 +50,6 @@ Quota figures use the shared wording, such as `5h 40% left, resets 2h29m` and `7 - A positive `scoped` minimum-remaining percentage blocks missing model-specific quota information. An explicitly empty scoped-window list means no separate window applies. - OpenCode and Pi can edit killswitch thresholds in **Limits**. -The optional `quota_header_feed_enabled` setting is OpenCode-only, disabled by default and requires restart. It publishes allowlisted quota observations, opaque identity and timestamps to owner-only temporary lease files, not tokens, request bodies, model IDs or refresh errors. It shares observations already obtained from responses rather than making new quota API requests. - ## Settings and custody User settings are shared across OpenCode 1, OpenCode 2 and Pi in [`anthropic-auth.jsonc`](settings-file.md), independent of local, vault or hosted custody. The default is `$HOME/.config/cortexkit/anthropic-auth.jsonc` on Linux/macOS or `%APPDATA%\cortexkit\anthropic-auth.jsonc` on Windows; an absolute `XDG_CONFIG_HOME` takes precedence on every OS, and `ANTHROPIC_AUTH_SETTINGS_FILE` can name another absolute path. See the [complete path and separate-install rules](settings-file.md#location). diff --git a/docs/cache.md b/docs/cache.md index 1503ca093..1f08c5adb 100644 --- a/docs/cache.md +++ b/docs/cache.md @@ -4,7 +4,8 @@ Prompt caching, cache keepalive and quota-window priming do different jobs. Enab ## Cache modes -Use `/claude` → **Cache** to enable caching and choose `claudeCache.mode`: +OpenCode 1, OpenCode 2 and Pi use the five-minute prompt cache by default. Use +`/claude` → **Cache** to enable one-hour caching and choose `claudeCache.mode`: - `explicit`: use explicit prompt-cache placement. - `automatic`: use automatic cache behavior. diff --git a/docs/configuration.md b/docs/configuration.md index 1088dc147..61c8f32e5 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -15,9 +15,8 @@ The flat keys below describe user choices, not a complete default configuration. | `fallback_on` | Retryable OAuth fallback statuses; default `[401, 403, 429]` | | `refresh_enabled`, `refresh_interval_minutes`, `refresh_refresh_before_expiry_minutes` | Token refresh policy | | `quota_enabled`, `quota_check_interval_minutes`, `quota_refresh_every_n_requests`, `quota_minimum_remaining_five_hour`, `quota_minimum_remaining_seven_day`, `quota_minimum_remaining_scoped`, `quota_fail_closed_on_unknown_quota`, `quota_show_toasts` | Quota policy, floors and notifications | -| `quota_header_feed_enabled` | OpenCode 1 opt-in, disabled by default; restart required | | `killswitch_enabled`, `killswitch_default_five_hour`, `killswitch_default_seven_day`, `killswitch_default_scoped`, `killswitch_account_floors` | Default and per-account remaining-quota floors | -| `claude_cache_enabled`, `claude_cache_mode` | 1-hour cache; mode is `explicit`, `automatic` or `hybrid` | +| `claude_cache_enabled`, `claude_cache_mode` | Five-minute cache by default; choose `on` for one hour. Mode is `explicit`, `automatic` or `hybrid` | | `cache_keep_enabled`, `cache_keep_always`, `cache_keep_window`, `cache_keep_subagents` | Keep-warm policy; the window list permits at most one entry | | `prime_enabled` | Opt-in quota-window priming | | `dump_enabled`, `log_level` | Request dumps and logging (`default`, `error`, `warn`, `info`, `debug`, `trace`) | @@ -79,10 +78,4 @@ Local refresh and its persisted retry delay are bound to the refresh-token gener Quota routing compares **remaining** percentages. `five_hour` / `seven_day` accept menu aliases `5h` / `1w`. A killswitch floor is the minimum remaining percentage required to use an account. A positive five-hour or seven-day floor blocks requests on that account when its reading is missing, regardless of `quota_fail_closed_on_unknown_quota`; without a positive floor, unknown readings follow that setting. A positive `scoped` floor requires a model-specific quota reading; an explicitly empty scoped list means no separate window applies. OpenCode offers the threshold edits in **Limits**; Pi does not. -## Quota header feed - -The OpenCode 1 plugin can publish quota observations from Anthropic model-response headers; the feed does not independently poll the quota API. Enable `quota_header_feed_enabled` and restart. Owner-only files under `opencode-anthropic-auth/quota-header-feed` in the [system temp folder](environment.md#paths-on-windows-macos-and-linux) (`$TMPDIR` or `/tmp` on macOS and Linux, `%TEMP%` on Windows) expire after three minutes; `OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR` redirects them. - -The allowlisted record contains quota-window values and provenance (which values came from response headers or quota polling), observation time, configured OAuth-account count and account identity references (including a resolved Anthropic account UUID when available). It does not contain tokens, raw headers, request bodies, model IDs or refresh errors. Treat the directory as local account metadata, not an anonymous public telemetry feed. - -Implementation: [settings import whitelist](../packages/core/src/native-migration-source.ts), [native account view](../packages/core/src/native-account-view.ts), [sticky routing](../packages/core/src/sticky-routing.ts), [account policy](../packages/core/src/accounts.ts), [native credential runtime](../packages/core/src/native-account-runtime.ts), [quota feed](../packages/core/src/quota-header-feed.ts), and [OpenCode publisher](../packages/opencode/src/index.ts). +Implementation: [settings import whitelist](../packages/core/src/native-migration-source.ts), [native account view](../packages/core/src/native-account-view.ts), [sticky routing](../packages/core/src/sticky-routing.ts), [account policy](../packages/core/src/accounts.ts), and [native credential runtime](../packages/core/src/native-account-runtime.ts). diff --git a/docs/environment.md b/docs/environment.md index a96db7a9e..99b71206c 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -62,14 +62,13 @@ A completed import records its routing destination in the journal; serving uses | `OPENCODE_ANTHROPIC_AUTH_CONTENT_FILTER_FALLBACK` | OpenCode 2 wire policy: `legacy` disables its server-side fallback opt-in; it does not enable OC1's client recovery | | `OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR` | OpenCode 1 and 2 [CacheKeep session registry](cachekeep-registry.md#location-and-permissions) directory override | | `PI_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR` | Pi [CacheKeep session registry](cachekeep-registry.md#location-and-permissions) directory override | -| `OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR` | OpenCode 1 quota-header-feed lease directory; publishing still requires `quota_header_feed_enabled` | | `OPENCODE_ANTHROPIC_AUTH_RPC_DIR` | OpenCode TUI menu bridge's port/token directory; default is per-project under OpenCode state | | `OPENCODE_ANTHROPIC_AUTH_PERF` | `1` enables structural request/relay/stream performance instrumentation | | `CLAUDE_CODE_GZIP_REQUEST_BODIES` | Claude Code's own switch for [request-body gzip](transports.md#request-body-compression): `0` or `false` sends every OAuth body uncompressed; `1` or `true` gzips even behind a proxy, custom CA or client certificate, or while the seven-day latch is set; unset follows Claude Code's default | | `HTTPS_PROXY`, `HTTP_PROXY` (and lower-case), `NO_PROXY` | A proxy that applies to `api.anthropic.com` turns request-body gzip off, as in Claude Code. `HTTP_PROXY`/`http_proxy` also makes a loopback `http:` [custom gateway](settings-file.md#custom-gateway) refuse its requests unless `NO_PROXY`, and `no_proxy` when set, list the gateway host | | `NODE_EXTRA_CA_CERTS`, `CLAUDE_CODE_CLIENT_CERT`, `CLAUDE_CODE_CLIENT_KEY` | A custom CA or a client certificate turns request-body gzip off, as in Claude Code | -The [sidebar guide](sidebar.md#tui-preferences), [quota feed](configuration.md#quota-header-feed), [safety fallback](request-rewriting.md#safety-fallback-opencode-1) and [dump guide](transports.md#diagnostics-and-dumps) explain scope and sensitive artifacts. The OpenCode TUI menu bridge accepts connections only from the local machine (`127.0.0.1`) and requires its bearer token. +The [sidebar guide](sidebar.md#tui-preferences), [safety fallback](request-rewriting.md#safety-fallback-opencode-1) and [dump guide](transports.md#diagnostics-and-dumps) explain scope and sensitive artifacts. The OpenCode TUI menu bridge accepts connections only from the local machine (`127.0.0.1`) and requires its bearer token. ## CLI inputs diff --git a/docs/features.md b/docs/features.md index a7ada013e..6d6ca02d5 100644 --- a/docs/features.md +++ b/docs/features.md @@ -20,7 +20,7 @@ `~` is your home folder; on Windows it is `%USERPROFILE%`, so the default OpenCode pool is `%USERPROFILE%\.config\opencode\anthropic-auth-pool.json`. See [paths on each OS](environment.md#paths-on-windows-macos-and-linux). -[Setup](installation.md#recommended-setup) prepares the selected hosts and records which credential store they may use before sign-in. OpenCode 2 has its own [login and transport boundaries](opencode-2.md); OpenCode 1's host-local quota-feed publisher and deterministic client safety recovery are not OpenCode 2 features. +[Setup](installation.md#recommended-setup) prepares the selected hosts and records which credential store they may use before sign-in. OpenCode 2 has its own [login and transport boundaries](opencode-2.md); OpenCode 1's deterministic client safety recovery is not an OpenCode 2 feature. ## What CortexKit adds over the original plugin @@ -28,7 +28,7 @@ CortexKit adds account and request controls beyond OpenCode's or Pi's single bui - **Fallback accounts and quota-aware routing:** ordered OAuth accounts and API-key routes, minimum remaining-quota thresholds, and `sticky-balanced` session affinity. See [accounts](accounts-and-routing.md) and the [routing reference](configuration.md#fallback-accounts-and-session-affinity). - **Cache controls:** explicit, automatic or hybrid prompt-cache placement, optional keepalive, and opt-in quota-window priming. [Cache controls](cache.md) explain the schedules and billed synthetic requests. -- **Quota visibility and limits:** per-account status, quota refresh and killswitch thresholds in OpenCode and Pi, the OpenCode quota sidebar, and OpenCode 1's optional sanitized [quota header feed](configuration.md#quota-header-feed). +- **Quota visibility and limits:** per-account status, quota refresh and killswitch thresholds in OpenCode and Pi, plus the OpenCode quota sidebar. - **Model controls:** adaptive reasoning summaries, effort levels, fast mode and OpenCode 1 safety fallback. See [models](models.md) and [safety fallback](request-rewriting.md#safety-fallback-opencode-1). - **Optional custody and transport:** Claustrum is a local credential-vault service that can supply accounts instead of the local pool; a user-owned Cloudflare Worker can relay request bodies. See [vault custody](vault.md) and [transports](transports.md). - **Claude-compatible request shaping:** identity and billing headers, final-body signing, tool replay and prompt-cache placement. See [request rewriting](request-rewriting.md#request-rewriting). diff --git a/docs/settings-file.md b/docs/settings-file.md index 6b59f79ec..3ef2d9872 100644 --- a/docs/settings-file.md +++ b/docs/settings-file.md @@ -43,7 +43,7 @@ file are flat, lower-case snake_case, not the legacy nested camelCase names. | --- | --- | | Routing | `routing_mode`, `max_same_account_wait`, `fallback_on` | | Refresh | `refresh_enabled`, `refresh_interval_minutes`, `refresh_refresh_before_expiry_minutes` | -| Quota | `quota_enabled`, `quota_check_interval_minutes`, `quota_refresh_every_n_requests`, `quota_minimum_remaining_five_hour`, `quota_minimum_remaining_seven_day`, `quota_minimum_remaining_scoped`, `quota_fail_closed_on_unknown_quota`, `quota_show_toasts`, `quota_header_feed_enabled` | +| Quota | `quota_enabled`, `quota_check_interval_minutes`, `quota_refresh_every_n_requests`, `quota_minimum_remaining_five_hour`, `quota_minimum_remaining_seven_day`, `quota_minimum_remaining_scoped`, `quota_fail_closed_on_unknown_quota`, `quota_show_toasts` | | Killswitch | `killswitch_enabled`, `killswitch_default_five_hour`, `killswitch_default_seven_day`, `killswitch_default_scoped`, `killswitch_account_floors` | | Cache | `claude_cache_enabled`, `claude_cache_mode`, `cache_keep_enabled`, `cache_keep_always`, `cache_keep_window`, `cache_keep_subagents` | | Request features | `dump_enabled`, `prime_enabled`, `claude_fast_enabled`, `cost_zeroing_enabled` | @@ -67,18 +67,18 @@ good window stays in effect. The error is logged and shown in Status. `claude_cache_enabled`, `quota_enabled` and `quota_fail_closed_on_unknown_quota` accept `"default"`, `"on"` and `"off"`, not booleans. `"on"` and `"off"` are explicit choices on every host. -`"default"` (also the value when unset) preserves each reader's existing -unset behavior; it does **not** unify the hosts. For cache and quota enablement: +With `claude_cache_enabled` unset or set to `"default"`, OpenCode 1, OpenCode 2 +and Pi use the five-minute cache. Choose `"on"` for one-hour caching or `"off"` +for five-minute caching. A [session cache policy](cache.md#per-session-runner-policy) +can override individual cache settings for that session. + +For `quota_enabled`, `"default"` (also the value when unset) uses each reader's +own default: | Setting | OpenCode 1 | OpenCode 2 | Pi | | --- | --- | --- | --- | -| `claude_cache_enabled` | Off | On for request options | Off | | `quota_enabled` | Core quota policy, provider restriction and fallback polling are on; sidebar main-quota refresh and the host's main-quota routing check are off | Quota policy and polling are on | Core quota policy is on | -Keep-warm treats `claude_cache_enabled: "default"` as off on every host, -including OpenCode 2. To avoid the per-reader distinction, choose `"on"` or -`"off"` explicitly. - `log_level: "default"` defers to `OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL`, or `info` if it is unset. The environment variable retains startup precedence. `thinking_binding_prefix_mismatch_behavior: "account-default"` leaves thinking @@ -266,9 +266,8 @@ the gateway's origin and path prefix and the header names only. ## Editing and Status -Hand edits are watched and apply to later requests without a restart, except -`quota_header_feed_enabled`, which still requires a restart. Requests use an -in-memory snapshot and never wait for settings file I/O. Process-wide readers +Hand edits are watched and apply to later requests without a restart. Requests +use an in-memory snapshot and never wait for settings file I/O. Process-wide readers use the no-model values. Keep-warm tracks accepted session requests and uses the model of each tracked request for its three model-aware cache settings. diff --git a/packages/core/schema/anthropic-auth.schema.json b/packages/core/schema/anthropic-auth.schema.json index 4f3b904f3..a448d335d 100644 --- a/packages/core/schema/anthropic-auth.schema.json +++ b/packages/core/schema/anthropic-auth.schema.json @@ -455,28 +455,6 @@ } ] }, - "quota_header_feed_enabled": { - "anyOf": [ - { - "type": "boolean" - }, - { - "type": "object", - "properties": { - "default": { - "type": "boolean" - }, - "opencode": { - "type": "boolean" - }, - "pi": { - "type": "boolean" - } - }, - "additionalProperties": false - } - ] - }, "killswitch_enabled": { "anyOf": [ { diff --git a/packages/core/src/accounts.ts b/packages/core/src/accounts.ts index a2a35dcd9..fef803712 100644 --- a/packages/core/src/accounts.ts +++ b/packages/core/src/accounts.ts @@ -61,9 +61,7 @@ export type AccountBase = { export type OAuthAccount = AccountBase & { type: 'oauth' authLineageId?: string - // Persisted under this name on both fallback accounts and the main profile because the - // quota feed schema owns the anthropicAccountUuid key; only the branded type and the - // request-scoped identity variables use the provider-neutral providerAccountUuid name. + // Keep the stored field name so older releases can still read the account identity. anthropicAccountUuid?: ProviderAccountUuid /** Non-secret scoped identity; never a capability handle or bearer token. */ claustrumScopedCredentialId?: string @@ -318,6 +316,7 @@ export type AccountStorage = { // when a separate process allocated an equal or higher generation. mainQuotaErrorClearedAt?: number } + /** Legacy stored field; retained for rollback, not used by the plugin. */ quotaHeaderFeed?: { enabled?: boolean } diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index faa5721a1..da11a1519 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -359,7 +359,6 @@ export { summarizePrewarmProviderError, } from './provider-error.ts' export { renameWithWindowsSharingRetry } from './publication-rename.ts' -export * from './quota-header-feed.ts' export * from './quota-headers.ts' export * from './quota-manager.ts' export * from './quota-refusal.ts' diff --git a/packages/core/src/native-account-view.ts b/packages/core/src/native-account-view.ts index 5f0a549c0..3304b05b7 100644 --- a/packages/core/src/native-account-view.ts +++ b/packages/core/src/native-account-view.ts @@ -413,7 +413,6 @@ const settingFields: Readonly> = { 'failClosedOnUnknownQuota', 'showToasts', ], - quotaHeaderFeed: ['enabled'], claudeCache: ['enabled', 'mode'], dump: ['enabled'], logging: ['level'], diff --git a/packages/core/src/native-migration-source.ts b/packages/core/src/native-migration-source.ts index 2b782f65d..9517e2af9 100644 --- a/packages/core/src/native-migration-source.ts +++ b/packages/core/src/native-migration-source.ts @@ -117,7 +117,7 @@ const settingFields: Record = { 'failClosedOnUnknownQuota', 'showToasts', ], - quotaHeaderFeed: ['enabled'], + quotaHeaderFeed: ['enabled'], // Preserve an existing value when migrating stored settings for rollback. claudeCache: ['enabled', 'mode'], dump: ['enabled'], logging: ['level'], diff --git a/packages/core/src/native-settings-write.ts b/packages/core/src/native-settings-write.ts index 60d2c9e7e..e2eb79040 100644 --- a/packages/core/src/native-settings-write.ts +++ b/packages/core/src/native-settings-write.ts @@ -37,7 +37,6 @@ const paths = { quota_minimum_remaining_scoped: ['quota', 'minimumRemaining', 'scoped'], quota_fail_closed_on_unknown_quota: ['quota', 'failClosedOnUnknownQuota'], quota_show_toasts: ['quota', 'showToasts'], - quota_header_feed_enabled: ['quotaHeaderFeed', 'enabled'], killswitch_enabled: ['killswitch', 'enabled'], killswitch_default_five_hour: ['killswitch', 'main', 'five_hour'], killswitch_default_seven_day: ['killswitch', 'main', 'seven_day'], diff --git a/packages/core/src/quota-header-feed.ts b/packages/core/src/quota-header-feed.ts deleted file mode 100644 index 594c41b8d..000000000 --- a/packages/core/src/quota-header-feed.ts +++ /dev/null @@ -1,478 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { - chmod, - lstat, - mkdir, - readdir, - readFile, - rename, - rm, - stat, - writeFile, -} from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' - -import { - type AccountQuotaWindow, - type AccountScopedQuotaWindow, - type AccountStorage, - isOAuthAccount, - type OAuthExtraUsageSnapshot, - type OAuthQuotaSnapshot, - QUOTA_FIELD_NAMES, - type QuotaFieldName, - type QuotaFieldSource, - type QuotaFieldSources, - type QuotaMoney, -} from './accounts.ts' - -export const QUOTA_HEADER_FEED_SCHEMA_VERSION = 3 -export const QUOTA_HEADER_FEED_LEASE_MS = 180_000 - -/** - * Lease files are per process; each carries only the accounts whose response - * headers THAT process harvested. Consumers MUST union entries across all files - * inside `lease_horizon_ms`, deduplicating by account; "newest file wins" is wrong. - * `anthropic_account_uuid` is always present: null is unresolvable, while absence - * identifies an old producer. A fallback `account_ref` is store-local. - */ -export type QuotaHeaderFeedIdentity = - | { identity_source: 'credential_id'; credential_id: string } - | { identity_source: 'account_ref'; account_ref: string } - | { identity_source: 'none' } - -export type QuotaHeaderFeedProvenance = Partial< - Record -> - -type QuotaHeaderFeedQuota = Pick< - OAuthQuotaSnapshot, - | 'five_hour' - | 'seven_day' - | 'bindingWindow' - | 'fallbackAdvised' - | 'scoped' - | 'extraUsage' -> & { - provenance?: QuotaHeaderFeedProvenance -} - -type QuotaHeaderFeedMetadata = { - schema_version: typeof QUOTA_HEADER_FEED_SCHEMA_VERSION - provider: 'anthropic' - configured_account_count: number - /** Header observation time; merged poll-owned fields retain their own checkedAt. */ - observed_at_ms: number -} - -export type QuotaHeaderFeedEntry = QuotaHeaderFeedIdentity & - QuotaHeaderFeedMetadata & { - /** Always present: null means UUID resolution failed; absence denotes an old producer. */ - anthropic_account_uuid: string | null - quota: QuotaHeaderFeedQuota - } - -export type QuotaHeaderFeedPublishEntry = QuotaHeaderFeedIdentity & - QuotaHeaderFeedMetadata & { - anthropic_account_uuid: string | null - quota: Omit & { - fieldSources?: QuotaFieldSources - } - accountKey: string - } - -type FeedRecord = { - version: typeof QUOTA_HEADER_FEED_SCHEMA_VERSION - lease_horizon_ms: number - entries: Record -} - -export function getDefaultQuotaHeaderFeedDirectory() { - return ( - process.env.OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR ?? - join(tmpdir(), 'opencode-anthropic-auth', 'quota-header-feed') - ) -} - -export function configuredAnthropicOAuthAccountCount(input: { - storage: AccountStorage | null - mainOAuthConfigured: boolean -}): number { - const fallbackCount = - input.storage?.accounts.filter(isOAuthAccount).length ?? 0 - return fallbackCount + (input.mainOAuthConfigured ? 1 : 0) -} - -function validIdentity( - entry: Record, -): entry is QuotaHeaderFeedEntry { - if ( - entry.schema_version !== QUOTA_HEADER_FEED_SCHEMA_VERSION || - entry.provider !== 'anthropic' - ) - return false - if ( - !Number.isFinite(entry.configured_account_count) || - !Number.isFinite(entry.observed_at_ms) - ) - return false - if (!entry.quota || typeof entry.quota !== 'object') return false - if ( - !Object.hasOwn(entry, 'anthropic_account_uuid') || - (entry.anthropic_account_uuid !== null && - typeof entry.anthropic_account_uuid !== 'string') - ) - return false - if (entry.identity_source === 'none') { - return !('credential_id' in entry) && !('account_ref' in entry) - } - if (entry.identity_source === 'credential_id') { - return ( - typeof entry.credential_id === 'string' && - entry.credential_id.length > 0 && - entry.credential_id !== 'main' && - !('account_ref' in entry) - ) - } - if (entry.identity_source === 'account_ref') { - return ( - typeof entry.account_ref === 'string' && - entry.account_ref.length > 0 && - entry.account_ref !== 'main' && - !('credential_id' in entry) - ) - } - return false -} - -function validatePublishEntry(entry: QuotaHeaderFeedEntry) { - if ( - entry.schema_version !== QUOTA_HEADER_FEED_SCHEMA_VERSION || - entry.provider !== 'anthropic' || - !validIdentity(entry as unknown as Record) - ) { - throw new Error('Invalid quota header feed entry') - } -} - -function finiteNumber(value: unknown): value is number { - return typeof value === 'number' && Number.isFinite(value) -} - -function projectQuotaWindow(value: unknown): AccountQuotaWindow | undefined { - if (!value || typeof value !== 'object') return undefined - const candidate = value as Record - if ( - !finiteNumber(candidate.usedPercent) || - !finiteNumber(candidate.remainingPercent) || - !finiteNumber(candidate.checkedAt) - ) { - return undefined - } - return { - usedPercent: candidate.usedPercent, - remainingPercent: candidate.remainingPercent, - ...(typeof candidate.resetsAt === 'string' && { - resetsAt: candidate.resetsAt, - }), - checkedAt: candidate.checkedAt, - } -} - -function projectScopedQuotaWindow( - value: unknown, -): AccountScopedQuotaWindow | undefined { - if (!value || typeof value !== 'object') return undefined - const candidate = value as Record - const window = projectQuotaWindow(candidate) - if ( - !window || - typeof candidate.id !== 'string' || - !candidate.id.trim() || - typeof candidate.title !== 'string' || - !candidate.title.trim() || - typeof candidate.modelName !== 'string' || - !candidate.modelName.trim() - ) { - return undefined - } - return { - ...window, - id: candidate.id, - title: candidate.title, - ...(typeof candidate.modelId === 'string' && - candidate.modelId.trim() && { - modelId: candidate.modelId, - }), - modelName: candidate.modelName, - } -} - -function projectQuotaMoney(value: unknown): QuotaMoney | undefined { - if (!value || typeof value !== 'object') return undefined - const candidate = value as Record - if ( - !finiteNumber(candidate.amountMinor) || - typeof candidate.currency !== 'string' || - !candidate.currency.trim() || - !finiteNumber(candidate.exponent) - ) { - return undefined - } - return { - amountMinor: candidate.amountMinor, - currency: candidate.currency, - exponent: candidate.exponent, - } -} - -function projectExtraUsage( - value: unknown, -): OAuthExtraUsageSnapshot | undefined { - if (!value || typeof value !== 'object') return undefined - const candidate = value as Record - const used = projectQuotaMoney(candidate.used) - const limit = projectQuotaMoney(candidate.limit) - if (!used || !limit || typeof candidate.exhausted !== 'boolean') { - return undefined - } - return { - used, - limit, - ...(finiteNumber(candidate.utilizationPercent) && { - utilizationPercent: candidate.utilizationPercent, - }), - ...(typeof candidate.severity === 'string' && { - severity: candidate.severity, - }), - exhausted: candidate.exhausted, - } -} - -function projectQuotaProvenance( - value: unknown, - presentFields: ReadonlySet, -): QuotaHeaderFeedProvenance | undefined { - if (!value || typeof value !== 'object') return undefined - const candidate = value as Record - const provenance: QuotaHeaderFeedProvenance = {} - for (const field of QUOTA_FIELD_NAMES) { - if (!presentFields.has(field)) continue - const source = candidate[field] - if (source === 'poll' || source === 'headers') provenance[field] = source - } - return Object.keys(provenance).length > 0 ? provenance : undefined -} - -function projectQuota(quota: QuotaHeaderFeedPublishEntry['quota']) { - const fiveHour = projectQuotaWindow(quota.five_hour) - const sevenDay = projectQuotaWindow(quota.seven_day) - const scoped = Array.isArray(quota.scoped) - ? quota.scoped - .map(projectScopedQuotaWindow) - .filter((entry): entry is AccountScopedQuotaWindow => entry != null) - : undefined - const extraUsage = projectExtraUsage(quota.extraUsage) - const presentFields = new Set() - if (fiveHour) presentFields.add('five_hour') - if (sevenDay) presentFields.add('seven_day') - if (typeof quota.bindingWindow === 'string') { - presentFields.add('bindingWindow') - } - if (typeof quota.fallbackAdvised === 'boolean') { - presentFields.add('fallbackAdvised') - } - if (scoped) presentFields.add('scoped') - if (extraUsage) presentFields.add('extraUsage') - const provenance = projectQuotaProvenance(quota.fieldSources, presentFields) - return { - ...(fiveHour && { five_hour: fiveHour }), - ...(sevenDay && { seven_day: sevenDay }), - ...(typeof quota.bindingWindow === 'string' && { - bindingWindow: quota.bindingWindow, - }), - ...(typeof quota.fallbackAdvised === 'boolean' && { - fallbackAdvised: quota.fallbackAdvised, - }), - ...(scoped && { scoped }), - ...(extraUsage && { extraUsage }), - ...(provenance && { provenance }), - } -} - -export class QuotaHeaderFeedRegistry { - private readonly filePath: string - private writeChain: Promise = Promise.resolve() - - constructor( - private readonly options: { - directory?: string - now?: () => number - leaseMs?: number - instanceId?: string - removeFile?: (path: string) => Promise - beforeRemoveFile?: (path: string) => Promise - } = {}, - ) { - const instanceId = options.instanceId ?? `${process.pid}-${randomUUID()}` - this.filePath = join( - options.directory ?? getDefaultQuotaHeaderFeedDirectory(), - `${instanceId}.json`, - ) - } - - publish(entry: QuotaHeaderFeedPublishEntry): Promise { - const { accountKey, quota } = entry - try { - validatePublishEntry(entry) - } catch (error) { - return Promise.reject(error) - } - const identity = - entry.identity_source === 'credential_id' - ? { - identity_source: 'credential_id' as const, - credential_id: entry.credential_id, - } - : entry.identity_source === 'account_ref' - ? { - identity_source: 'account_ref' as const, - account_ref: entry.account_ref, - } - : { identity_source: 'none' as const } - const cleanEntry: QuotaHeaderFeedEntry = { - ...identity, - schema_version: entry.schema_version, - provider: entry.provider, - configured_account_count: entry.configured_account_count, - observed_at_ms: entry.observed_at_ms, - anthropic_account_uuid: entry.anthropic_account_uuid, - quota: projectQuota(quota), - } - if (!accountKey) - return Promise.reject(new Error('Invalid quota header feed account key')) - this.writeChain = this.writeChain - .catch(() => {}) - .then(async () => { - const directory = - this.options.directory ?? getDefaultQuotaHeaderFeedDirectory() - await mkdir(directory, { recursive: true, mode: 0o700 }) - await chmod(directory, 0o700) - await this.reapStaleSiblingLeases(directory) - let entries: Record = {} - try { - const record = JSON.parse( - await readFile(this.filePath, 'utf8'), - ) as Partial - if ( - record.version === QUOTA_HEADER_FEED_SCHEMA_VERSION && - record.entries && - typeof record.entries === 'object' - ) - entries = record.entries - } catch {} - entries[accountKey] = cleanEntry - const tempPath = `${this.filePath}.${randomUUID()}.tmp` - try { - await writeFile( - tempPath, - `${JSON.stringify({ version: QUOTA_HEADER_FEED_SCHEMA_VERSION, lease_horizon_ms: this.options.leaseMs ?? QUOTA_HEADER_FEED_LEASE_MS, entries })}\n`, - { mode: 0o600 }, - ) - await chmod(tempPath, 0o600) - await rename(tempPath, this.filePath) - } finally { - await rm(tempPath, { force: true }) - } - }) - return this.writeChain - } - - private async reapStaleSiblingLeases(directory: string): Promise { - const now = this.options.now?.() ?? Date.now() - const leaseMs = this.options.leaseMs ?? QUOTA_HEADER_FEED_LEASE_MS - let names: string[] - try { - names = await readdir(directory) - } catch { - return - } - await Promise.all( - names - .filter((name) => /^\d+-[0-9a-f-]+\.json$/i.test(name)) - .map(async (name) => { - const path = join(directory, name) - if (path === this.filePath) return - try { - const file = await stat(path) - if (file.mtimeMs > now || now - file.mtimeMs < leaseMs) return - await this.options.beforeRemoveFile?.(path) - const current = await lstat(path) - if (current.ino !== file.ino || current.mtimeMs !== file.mtimeMs) - return - await (this.options.removeFile ?? ((target) => rm(target)))(path) - } catch { - // A missed cleanup must not prevent this process from refreshing its lease. - } - }), - ) - } - - async list(): Promise { - await this.writeChain.catch(() => {}) - const directory = - this.options.directory ?? getDefaultQuotaHeaderFeedDirectory() - const now = this.options.now?.() ?? Date.now() - const leaseMs = this.options.leaseMs ?? QUOTA_HEADER_FEED_LEASE_MS - let names: string[] - try { - names = (await readdir(directory)).filter((name) => - name.endsWith('.json'), - ) - } catch { - return [] - } - const newest = new Map() - await Promise.all( - names.map(async (name) => { - try { - const record = JSON.parse( - await readFile(join(directory, name), 'utf8'), - ) as Partial - if ( - record.version !== QUOTA_HEADER_FEED_SCHEMA_VERSION || - !record.entries || - typeof record.entries !== 'object' - ) - return - for (const [accountKey, candidate] of Object.entries( - record.entries, - )) { - if ( - !candidate || - typeof candidate !== 'object' || - candidate.schema_version !== QUOTA_HEADER_FEED_SCHEMA_VERSION || - candidate.provider !== 'anthropic' || - !validIdentity(candidate as unknown as Record) - ) - continue - const observed = candidate.observed_at_ms - if (observed > now || now - observed >= leaseMs) continue - const existing = newest.get(accountKey) - if (!existing || observed > existing.observed_at_ms) - newest.set(accountKey, candidate) - } - } catch {} - }), - ) - return [...newest.values()].sort( - (a, b) => a.observed_at_ms - b.observed_at_ms, - ) - } - - async dispose(): Promise { - await this.writeChain.catch(() => {}) - await rm(this.filePath, { force: true }) - } -} diff --git a/packages/core/src/settings-definition.ts b/packages/core/src/settings-definition.ts index 03da26e95..99edb8b62 100644 --- a/packages/core/src/settings-definition.ts +++ b/packages/core/src/settings-definition.ts @@ -58,7 +58,6 @@ export const settingsDefinition = defineSettings({ default: 'default', }, quota_show_toasts: { ...host, value: boolean(), default: false }, - quota_header_feed_enabled: { ...host, value: boolean(), default: false }, killswitch_enabled: { ...host, value: boolean(), default: false }, killswitch_default_five_hour: { ...host, value: floor, default: 5 }, killswitch_default_seven_day: { ...host, value: floor, default: 10 }, @@ -166,8 +165,6 @@ export const SETTINGS_DEFAULT_READERS = { quota_fail_closed_on_unknown_quota: 'packages/core/src/accounts.ts:failClosedOnUnknownQuota', quota_show_toasts: 'packages/opencode/src/index.ts:showQuotaToastFromCache', - quota_header_feed_enabled: - 'packages/opencode/src/index.ts:AnthropicAuthPlugin quotaHeaderFeedRegistry', killswitch_enabled: 'packages/core/src/accounts.ts:isKillswitchEnabled', killswitch_default_five_hour: 'packages/core/src/accounts.ts:getKillswitchThresholdsForAccount', @@ -232,7 +229,7 @@ export const SETTINGS_THREE_WAY_READERS = { { path: 'packages/opencode/src/v2/wire.ts', reader: 'createNativeWirePolicy transformOptions', - absent: true, + absent: false, }, { path: 'packages/pi/src/stream.ts', diff --git a/packages/core/src/settings-move-source.ts b/packages/core/src/settings-move-source.ts index 1b440b241..e5c807957 100644 --- a/packages/core/src/settings-move-source.ts +++ b/packages/core/src/settings-move-source.ts @@ -34,7 +34,6 @@ export const SETTINGS_MOVE_PATHS = { quota_minimum_remaining_scoped: ['quota', 'minimumRemaining', 'scoped'], quota_fail_closed_on_unknown_quota: ['quota', 'failClosedOnUnknownQuota'], quota_show_toasts: ['quota', 'showToasts'], - quota_header_feed_enabled: ['quotaHeaderFeed', 'enabled'], killswitch_enabled: ['killswitch', 'enabled'], killswitch_default_five_hour: ['killswitch', 'main', 'five_hour'], killswitch_default_seven_day: ['killswitch', 'main', 'seven_day'], diff --git a/packages/core/src/settings-record.ts b/packages/core/src/settings-record.ts index 8290ebe4f..a40c3534a 100644 --- a/packages/core/src/settings-record.ts +++ b/packages/core/src/settings-record.ts @@ -168,10 +168,6 @@ export function resolveSettingsRecord( failClosedOnUnknownQuota: values.quota_fail_closed_on_unknown_quota, showToasts: values.quota_show_toasts, }, - quotaHeaderFeed: { - ...section(stored, 'quotaHeaderFeed'), - enabled: values.quota_header_feed_enabled, - }, killswitch: killswitchRecord(stored, values, host), claudeCache: { ...section(stored, 'claudeCache'), diff --git a/packages/core/src/tests/native-runtime-settings.test.ts b/packages/core/src/tests/native-runtime-settings.test.ts index 0d7986a44..462f8bf03 100644 --- a/packages/core/src/tests/native-runtime-settings.test.ts +++ b/packages/core/src/tests/native-runtime-settings.test.ts @@ -204,13 +204,6 @@ for (const [name, values, read, expected] of [ ['quota poll', { quota_enabled: 'off' }, quotaEnabled, false], ['refresh', { refresh_interval_minutes: 3 }, getRefreshIntervalMs, 180_000], ['prime', { prime_enabled: true }, isPrimePersistentlyEnabled, true], - [ - 'quota header feed', - { quota_header_feed_enabled: true }, - (storage: ReturnType) => - storage.quotaHeaderFeed?.enabled, - true, - ], [ 'keep-warm schedule', { cache_keep_window: [{ start_hour: 2, end_hour: 7 }] }, diff --git a/packages/core/src/tests/native-setup-settings.test.ts b/packages/core/src/tests/native-setup-settings.test.ts index 93d4cc383..02ddf3534 100644 --- a/packages/core/src/tests/native-setup-settings.test.ts +++ b/packages/core/src/tests/native-setup-settings.test.ts @@ -375,7 +375,6 @@ test('setup writes every explicitly held moved field in schema form without stor quota_minimum_remaining_scoped: 0, quota_fail_closed_on_unknown_quota: 'on', quota_show_toasts: true, - quota_header_feed_enabled: true, killswitch_enabled: true, killswitch_default_five_hour: 9, killswitch_default_seven_day: 21, diff --git a/packages/core/src/tests/settings-definition.test.ts b/packages/core/src/tests/settings-definition.test.ts index bd3b3253b..d7ef468fc 100644 --- a/packages/core/src/tests/settings-definition.test.ts +++ b/packages/core/src/tests/settings-definition.test.ts @@ -90,7 +90,6 @@ test('all shared settings are flat, user-only and have exactly the allowed overr 'quota_minimum_remaining_scoped', 'quota_fail_closed_on_unknown_quota', 'quota_show_toasts', - 'quota_header_feed_enabled', 'killswitch_enabled', 'killswitch_default_five_hour', 'killswitch_default_seven_day', @@ -352,12 +351,6 @@ const defaultReaders = { 'showQuotaToastFromCache', s, ), - quota_header_feed_enabled: (s: AccountStorage) => - hostPredicate( - /const quotaHeaderFeedRegistry =\s*(initialStorage[\s\S]*?)\s*\? new QuotaHeaderFeedRegistry/, - 'quotaHeaderFeedRegistry', - s, - ), killswitch_enabled: isKillswitchEnabled, killswitch_default_five_hour: (s: AccountStorage) => getKillswitchThresholdsForAccount(s).five_hour, diff --git a/packages/core/src/tests/settings-move-source.test.ts b/packages/core/src/tests/settings-move-source.test.ts index 692bc7c47..aa542a280 100644 --- a/packages/core/src/tests/settings-move-source.test.ts +++ b/packages/core/src/tests/settings-move-source.test.ts @@ -70,7 +70,6 @@ test('the closed move map names every schema key and only explicitly held user s failClosedOnUnknownQuota: true, showToasts: true, }, - quotaHeaderFeed: { enabled: true }, killswitch: { enabled: true, main: { five_hour: 9, seven_day: 21, scoped: 3 }, @@ -128,7 +127,6 @@ test('the closed move map names every schema key and only explicitly held user s quota_minimum_remaining_scoped: 4, quota_fail_closed_on_unknown_quota: 'on', quota_show_toasts: true, - quota_header_feed_enabled: true, killswitch_enabled: true, killswitch_default_five_hour: 9, killswitch_default_seven_day: 21, @@ -458,7 +456,6 @@ test('invalid non-protection domains are omitted independently', () => { }, claudeCache: { enabled: 1, mode: 'unknown' }, cacheKeep: { enabled: 'yes', always: 0, subagents: null }, - quotaHeaderFeed: { enabled: 1 }, dump: { enabled: 'yes' }, prime: { enabled: 0 }, claudeFast: { enabled: 1 }, @@ -469,7 +466,7 @@ test('invalid non-protection domains are omitted independently', () => { }), ), ).toEqual({}) - expect(reader.messages).toHaveLength(22) + expect(reader.messages).toHaveLength(21) }) test('window hours use the legacy numeric domain, but require a complete pair', () => { diff --git a/packages/core/src/tests/settings-reader-fixture.ts b/packages/core/src/tests/settings-reader-fixture.ts index da7441821..b86f665e0 100644 --- a/packages/core/src/tests/settings-reader-fixture.ts +++ b/packages/core/src/tests/settings-reader-fixture.ts @@ -21,7 +21,6 @@ export const explicitLegacySettings = { failClosedOnUnknownQuota: false, showToasts: true, }, - quotaHeaderFeed: { enabled: true }, killswitch: { enabled: true, main: { five_hour: 21, seven_day: 22, scoped: 23 }, diff --git a/packages/core/src/tests/settings-record.test.ts b/packages/core/src/tests/settings-record.test.ts index 0b88b5e6b..2b110439a 100644 --- a/packages/core/src/tests/settings-record.test.ts +++ b/packages/core/src/tests/settings-record.test.ts @@ -122,7 +122,6 @@ const defaults = { failClosedOnUnknownQuota: 'default', showToasts: false, }, - quotaHeaderFeed: { enabled: false }, killswitch: { enabled: false, main: { five_hour: 5, seven_day: 10, scoped: 0 }, @@ -160,7 +159,6 @@ const explicit = { failClosedOnUnknownQuota: 'off', showToasts: true, }, - quotaHeaderFeed: { enabled: true }, killswitch: { enabled: true, main: { five_hour: 21, seven_day: 22, scoped: 23 }, @@ -199,7 +197,6 @@ const fileValues = { quota_minimum_remaining_scoped: 13, quota_fail_closed_on_unknown_quota: 'off', quota_show_toasts: true, - quota_header_feed_enabled: true, killswitch_enabled: true, killswitch_default_five_hour: 21, killswitch_default_seven_day: 22, diff --git a/packages/core/src/tests/settings-service.test.ts b/packages/core/src/tests/settings-service.test.ts index daec20150..3d56b4585 100644 --- a/packages/core/src/tests/settings-service.test.ts +++ b/packages/core/src/tests/settings-service.test.ts @@ -234,6 +234,24 @@ test('an unknown model uses the no-model values and unknown override keys are re }) }) +test('an old quota header feed setting is ignored without losing other settings', async () => { + const source = '{"quota_header_feed_enabled":true,"dump_enabled":true}' + const f = await fixture(source) + const service = await f.open() + for (const host of ['opencode', 'pi'] as const) { + expect(service.resolve(host).dump_enabled).toBe(true) + expect(service.resolve(host)).not.toHaveProperty( + 'quota_header_feed_enabled', + ) + } + expect(service.snapshot().report).toContainEqual({ + file: { kind: 'user', path: f.file }, + keyPath: ['quota_header_feed_enabled'], + reason: 'unknown-key', + }) + expect(await readFile(f.file, 'utf8')).toBe(source) +}) + for (const restore of [false, true]) { test(`a change between two gets${restore ? ' restored with the same size and timestamps' : ''} never publishes mixed values`, async () => { const old = diff --git a/packages/core/src/tests/setup.ts b/packages/core/src/tests/setup.ts index 603c14d78..11349dbfa 100644 --- a/packages/core/src/tests/setup.ts +++ b/packages/core/src/tests/setup.ts @@ -30,10 +30,6 @@ beforeEach(async () => { // The state file is left to derive beside whichever config path a test uses: an explicit // STATE_FILE overrides that derivation for every caller, which would redirect tests that // pass their own storage path (and their spawned worker processes) to a shared file. - process.env.OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR = join( - testDir, - 'quota-header-feed', - ) process.env.OPENCODE_ANTHROPIC_AUTH_LOG_FILE = join(testDir, 'auth.log') const authority = await import('../native-vault-host.ts') authority.resetVaultHostAuthorityForTests?.() @@ -43,6 +39,5 @@ afterEach(async () => { if (testDir) await rm(testDir, { recursive: true, force: true }) testDir = undefined delete process.env.OPENCODE_ANTHROPIC_AUTH_FILE - delete process.env.OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR delete process.env.OPENCODE_ANTHROPIC_AUTH_LOG_FILE }) diff --git a/packages/e2e-tests/src/harness.ts b/packages/e2e-tests/src/harness.ts index 58a98efb4..e6e607d05 100644 --- a/packages/e2e-tests/src/harness.ts +++ b/packages/e2e-tests/src/harness.ts @@ -43,7 +43,6 @@ type SdkClient = { export type E2EHarnessOptions = { relay?: 'websocket' | 'http' - quotaFeed?: boolean relayResponseStartDelayMs?: number hybridCache?: boolean fallbackMode?: 'server' | 'legacy' @@ -98,7 +97,6 @@ export class E2EHarness { hybridCache: options.hybridCache, fallbackMode: options.fallbackMode, childTmpDir: options.childTmpDir, - quotaFeed: options.quotaFeed, childEnv: options.childEnv, beforeSpawn: options.beforeSpawn, nativeAccounts: options.nativeAccounts, diff --git a/packages/e2e-tests/src/opencode-runner.ts b/packages/e2e-tests/src/opencode-runner.ts index 4e7d693f9..3abd59b57 100644 --- a/packages/e2e-tests/src/opencode-runner.ts +++ b/packages/e2e-tests/src/opencode-runner.ts @@ -52,7 +52,6 @@ export type IsolatedEnv = { dataDir: string cacheDir: string workdir: string - quotaFeedDir: string } function isExpectedE2ETempDir(path: string, root: string) { @@ -239,7 +238,6 @@ export type SpawnOptions = { beforeSpawn?: (env: IsolatedEnv) => void | Promise childEnv?: Record childTmpDir?: string - quotaFeed?: boolean /** Defaults to `{ kind: 'local' }`. */ nativeAccounts?: NativeAccountFixture } @@ -316,7 +314,6 @@ export function createIsolatedEnv(root = tmpdir()): IsolatedEnv { dataDir: join(base, 'data'), cacheDir: join(base, 'cache'), workdir: join(base, 'work'), - quotaFeedDir: join(base, 'quota-header-feed'), } try { for (const dir of Object.values(env)) mkdirSync(dir, { recursive: true }) @@ -394,7 +391,6 @@ function writeConfigs(env: IsolatedEnv, options: SpawnOptions) { accounts: [], quota: { enabled: false }, refresh: { enabled: false }, - ...(options.quotaFeed ? { quotaHeaderFeed: { enabled: true } } : {}), ...(options.hybridCache ? { claudeCache: { enabled: true, mode: 'hybrid' } } : {}), @@ -684,9 +680,6 @@ async function prepareNativeAccounts(input: { ...settings, quota: { enabled: false }, refresh: { enabled: false }, - ...(input.options.quotaFeed - ? { quotaHeaderFeed: { enabled: true } } - : {}), ...(input.options.hybridCache ? { claudeCache: { enabled: true, mode: 'hybrid' } } : {}), @@ -1029,11 +1022,6 @@ export async function spawnOpencode( env.tempDir, 'opencode-anthropic-auth.log', ) - if (options.quotaFeed) { - childEnv.OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR = env.quotaFeedDir - } else { - delete childEnv.OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR - } childEnv.OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION = '1' if (options.fallbackMode) { childEnv.OPENCODE_ANTHROPIC_AUTH_FALLBACK_MODE = options.fallbackMode diff --git a/packages/e2e-tests/tests/native-process-fixture.test.ts b/packages/e2e-tests/tests/native-process-fixture.test.ts index 3edc00c6c..a2d5361ab 100644 --- a/packages/e2e-tests/tests/native-process-fixture.test.ts +++ b/packages/e2e-tests/tests/native-process-fixture.test.ts @@ -158,7 +158,6 @@ describe('native process fixture preparation', () => { token: 'relay-token', transport: 'websocket', }, - quotaFeed: true, hybridCache: true, }) expect(String(run.failure)).toContain( diff --git a/packages/e2e-tests/tests/quota-header-relay.test.ts b/packages/e2e-tests/tests/quota-header-relay.test.ts index ba5cda613..804b13d78 100644 --- a/packages/e2e-tests/tests/quota-header-relay.test.ts +++ b/packages/e2e-tests/tests/quota-header-relay.test.ts @@ -2,7 +2,7 @@ import { describe, expect } from 'bun:test' import { createNativeAccountRuntime, type NativeAccountSnapshot } from '@cortexkit/anthropic-auth-core' -import { readFile, readdir, stat } from 'node:fs/promises' +import { readFile, stat } from 'node:fs/promises' import { createTestLifetimeSuite } from '../../core/src/tests/test-lifetime.ts' import { join } from 'node:path' import { E2EHarness, type E2EHarnessOptions } from '../src/harness.ts' @@ -105,28 +105,6 @@ async function waitForHeaderQuotaState(harness: E2EHarness) { ) } -async function readFeedFiles(harness: E2EHarness) { - try { - const names = await readdir(harness.opencode.env.quotaFeedDir) - return Promise.all( - names.filter((name) => name.endsWith('.json')).map(async (name) => - readFile(join(harness.opencode.env.quotaFeedDir, name), 'utf8'), - ), - ) - } catch { - return [] - } -} - -async function waitForFeed(harness: E2EHarness) { - for (let attempt = 0; attempt < 100; attempt += 1) { - const values = await readFeedFiles(harness) - if (values.length === 1) return values - await Bun.sleep(50) - } - throw new Error('quota feed record did not appear') -} - const quotaHeaders = { 'anthropic-ratelimit-unified-representative-claim': 'five_hour', 'anthropic-ratelimit-unified-5h-utilization': '0.78', @@ -138,7 +116,7 @@ const quotaHeaders = { describe('quota headers through relay', () => { it('harvests quota headers from a websocket relay response', async () => { - const harness = await createHarness({ relay: 'websocket', quotaFeed: true }) + const harness = await createHarness({ relay: 'websocket' }) harness.script([ { type: 'text', @@ -158,28 +136,18 @@ describe('quota headers through relay', () => { await assertNativeHeaderQuota(harness, state) }, 90_000) - it('writes one equivalent schema-v3 feed record for an HTTP relay response', async () => { - const harness = await createHarness({ relay: 'http', quotaFeed: true }) + it('harvests quota headers from an HTTP relay response', async () => { + const harness = await createHarness({ relay: 'http' }) harness.script([{ type: 'text', text: 'http relay response', headers: quotaHeaders }]) const sessionId = await harness.createSession() await harness.sendPrompt(sessionId, 'return the http relay response') await harness.waitFor(() => (harness.relay?.acceptedRequests() ?? 0) >= 1) await assertNativeHeaderQuota(harness, await waitForHeaderQuotaState(harness)) - const files = await waitForFeed(harness) - const record = JSON.parse(files[0]!) - expect(record.version).toBe(3) - expect(Object.values(record.entries)).toHaveLength(1) - expect(Object.values(record.entries)[0]).toEqual( - expect.objectContaining({ provider: 'anthropic', schema_version: 3 }), - ) - expect(files[0]).not.toContain('authorization') - expect(files[0]).not.toContain('access-token') }, 90_000) it('does not publish optimistic websocket headers before response_start', async () => { const harness = await createHarness({ relay: 'websocket', - quotaFeed: true, relayResponseStartDelayMs: 250, }) harness.script([{ type: 'text', text: 'delayed relay response', headers: quotaHeaders }]) @@ -189,27 +157,14 @@ describe('quota headers through relay', () => { await harness.waitFor(() => (harness.relay?.acceptedRequests() ?? 0) >= 1) await Bun.sleep(50) // The optimistic envelope has no quota-bearing headers. Only genuine - // response_start headers may populate native metadata and the quota feed. - expect(await readFeedFiles(harness)).toHaveLength(0) + // response_start headers may populate native metadata. + expect(mainAccount(await readQuotaState(harness)).quota).toBeUndefined() await prompt await assertNativeHeaderQuota(harness, await waitForHeaderQuotaState(harness)) - const files = await waitForFeed(harness) - expect(files).toHaveLength(1) - const record = JSON.parse(files[0]!) - expect(Object.values(record.entries)).toHaveLength(1) - expect(Object.values(record.entries)[0]).toEqual( - expect.objectContaining({ - provider: 'anthropic', - schema_version: 3, - quota: expect.objectContaining({ - five_hour: expect.objectContaining({ usedPercent: 78 }), - }), - }), - ) }, 90_000) it('leaves quota state untouched when websocket relay headers have no quota data', async () => { - const harness = await createHarness({ relay: 'websocket', quotaFeed: true }) + const harness = await createHarness({ relay: 'websocket' }) harness.script([{ type: 'text', text: 'relay response without quota' }]) const sessionId = await harness.createSession() diff --git a/packages/opencode/scripts/smoke-tui-pack-install.ts b/packages/opencode/scripts/smoke-tui-pack-install.ts index 03a5bbec2..dad953f1b 100644 --- a/packages/opencode/scripts/smoke-tui-pack-install.ts +++ b/packages/opencode/scripts/smoke-tui-pack-install.ts @@ -178,7 +178,6 @@ async function runPackedHostRuntimeProbe( const xdgState = join(home, 'state') const bunInstallCache = join(fixtureRoot, 'bun-install-cache') const cacheKeepDir = join(fixtureRoot, 'cachekeep') - const quotaFeedDir = join(fixtureRoot, 'quota-feed') const dumpDir = join(fixtureRoot, 'dumps') const rpcDir = join(fixtureRoot, 'rpc') const env: NodeJS.ProcessEnv = { @@ -211,7 +210,6 @@ async function runPackedHostRuntimeProbe( ), OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE: sidebarStateFile, OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR: cacheKeepDir, - OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR: quotaFeedDir, OPENCODE_ANTHROPIC_AUTH_DUMP_DIR: dumpDir, OPENCODE_ANTHROPIC_AUTH_RPC_DIR: rpcDir, } @@ -226,7 +224,6 @@ async function runPackedHostRuntimeProbe( xdgState, bunInstallCache, cacheKeepDir, - quotaFeedDir, dumpDir, rpcDir, ] diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index b5c17f191..888382f0f 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -52,7 +52,6 @@ import { claudeGatewayHeaderValues, claudeGatewayModelUrl, claudeGatewayStatusNotes, - configuredAnthropicOAuthAccountCount, createDumpResponseObserver, createEmptyStorage, createNativeAccountRuntime, @@ -195,11 +194,8 @@ import { parseSseFrame, peekRoutingAccount, prepareMessageThreadRequest, - QUOTA_HEADER_FEED_SCHEMA_VERSION, type QuotaAccountSummary, type QuotaEntry, - type QuotaHeaderFeedPublishEntry, - QuotaHeaderFeedRegistry, QuotaManager, type QuotaManagerOptions, type QuotaReadingPurpose, @@ -2478,10 +2474,6 @@ const anthropicAuthPlugin = async ( } } - const quotaHeaderFeedRegistry = - initialStorage?.quotaHeaderFeed?.enabled === true - ? new QuotaHeaderFeedRegistry() - : null // Profiles fetched by this plugin instance, keyed by route and account // identity. A failed network request is not repeated for that account this // boot, and a fetched profile is reused until it goes stale, even if saving @@ -3022,114 +3014,6 @@ const anthropicAuthPlugin = async ( }) } - function getCredentialId(value: unknown): string | undefined { - if (!value || typeof value !== 'object') return undefined - const record = value as Record - const direct = record.credential_id - if (typeof direct === 'string' && direct && direct !== 'main') return direct - const vault = record.vault - if (vault && typeof vault === 'object') { - const nested = (vault as Record).credential_id - if (typeof nested === 'string' && nested && nested !== 'main') - return nested - } - return undefined - } - - async function publishQuotaHeaderFeed( - served: ServedQuotaHeaders, - entry: QuotaEntry, - ): Promise { - if (!quotaHeaderFeedRegistry) return - if (served.accountId === 'main' && !served.mainQuotaIdentity?.quotaKey) { - // An unresolved main account must not overwrite verified account-bound quota. - return - } - const storage = - (await loadAccounts(accountStoragePath)) ?? createEmptyStorage() - const mainAuth = await latestGetAuth?.() - const mainOAuthConfigured = mainAuth?.type === 'oauth' - const account = - served.accountId === 'main' - ? storage.main - : storage.accounts.find( - (candidate) => candidate.id === served.accountId, - ) - const credentialId = getCredentialId(account) - const configuredAccountCount = configuredAnthropicOAuthAccountCount({ - storage, - mainOAuthConfigured, - }) - const observedAtMs = entry.checkedAt - const quota = { - five_hour: entry.quota.five_hour, - seven_day: entry.quota.seven_day, - bindingWindow: entry.quota.bindingWindow, - fallbackAdvised: entry.quota.fallbackAdvised, - scoped: entry.quota.scoped, - extraUsage: entry.quota.extraUsage, - fieldSources: entry.quota.fieldSources, - } - const accountKey = - credentialId ?? - (served.accountId === 'main' - ? (served.mainQuotaIdentity?.quotaKey ?? 'main') - : served.accountId) - const feedEntry: QuotaHeaderFeedPublishEntry = credentialId - ? { - identity_source: 'credential_id', - credential_id: credentialId, - schema_version: QUOTA_HEADER_FEED_SCHEMA_VERSION, - provider: 'anthropic', - configured_account_count: configuredAccountCount, - observed_at_ms: observedAtMs, - anthropic_account_uuid: served.anthropicAccountUuid ?? null, - quota, - accountKey, - } - : served.accountId === 'main' && served.mainQuotaIdentity?.quotaKey - ? { - identity_source: 'account_ref', - account_ref: served.mainQuotaIdentity.quotaKey, - schema_version: QUOTA_HEADER_FEED_SCHEMA_VERSION, - provider: 'anthropic', - configured_account_count: configuredAccountCount, - observed_at_ms: observedAtMs, - anthropic_account_uuid: served.anthropicAccountUuid ?? null, - quota, - accountKey, - } - : served.accountId === 'main' - ? { - identity_source: 'none', - schema_version: QUOTA_HEADER_FEED_SCHEMA_VERSION, - provider: 'anthropic', - configured_account_count: configuredAccountCount, - observed_at_ms: observedAtMs, - anthropic_account_uuid: served.anthropicAccountUuid ?? null, - quota, - accountKey, - } - : { - identity_source: 'account_ref', - account_ref: served.accountId, - schema_version: QUOTA_HEADER_FEED_SCHEMA_VERSION, - provider: 'anthropic', - configured_account_count: configuredAccountCount, - observed_at_ms: observedAtMs, - anthropic_account_uuid: served.anthropicAccountUuid ?? null, - quota, - accountKey, - } - await quotaHeaderFeedRegistry.publish(feedEntry) - } - - function logQuotaHeaderFeedFailure(error: unknown) { - logger.debug('quota', 'failed to publish quota header feed', { - error: error instanceof Error ? error.message : String(error), - }) - } - function harvestQuotaHeaders( headers: Headers, served: ServedQuotaHeaders, @@ -3232,7 +3116,7 @@ const anthropicAuthPlugin = async ( ) return // Store acceptance checks that the row still has the observed - // credential epoch and account identity before updating cache or feed. + // credential epoch and account identity before updating the cache. // The accepted write may still be queued rather than on disk. const entry = persistedEntry if ( @@ -3249,7 +3133,6 @@ const anthropicAuthPlugin = async ( authLineageId: served.authLineageId, }) void refreshSidebarQuota().catch(() => {}) - await publishQuotaHeaderFeed(served, entry) logger.debug('quota', 'harvested response quota', { account: served.accountId, fiveHourPercent: entry.quota.five_hour?.usedPercent, @@ -3269,7 +3152,7 @@ const anthropicAuthPlugin = async ( }) } } - })().catch(logQuotaHeaderFeedFailure) + })().catch(logPersistFailure) logger.trace('quota', 'response quota awaiting publication', { account: served.accountId, }) @@ -4729,13 +4612,6 @@ const anthropicAuthPlugin = async ( try { quotaManager.close() } catch {} - try { - await quotaHeaderFeedRegistry?.dispose() - } catch (error) { - logger.warn('quota-header-feed', 'failed to dispose', { - error: error instanceof Error ? error.message : String(error), - }) - } // Per-instance background services must be torn down before the RPC // guard so a disposed instance never leaves its timer running for the // rest of the process. Each step is isolated: one failure cannot skip diff --git a/packages/opencode/src/tests/account-command.test.ts b/packages/opencode/src/tests/account-command.test.ts index 889a7d848..0d2f904fa 100644 --- a/packages/opencode/src/tests/account-command.test.ts +++ b/packages/opencode/src/tests/account-command.test.ts @@ -59,7 +59,6 @@ const nativeEnvKeys = [ 'OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE', 'OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE', 'OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR', - 'OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR', 'OPENCODE_ANTHROPIC_AUTH_RPC_DIR', 'CLAUDE_CONFIG_DIR', 'OPENCODE_AUTH_CONTENT', diff --git a/packages/opencode/src/tests/add-account-flows.test.ts b/packages/opencode/src/tests/add-account-flows.test.ts index 23aa91b8c..3061439b0 100644 --- a/packages/opencode/src/tests/add-account-flows.test.ts +++ b/packages/opencode/src/tests/add-account-flows.test.ts @@ -46,7 +46,6 @@ const nativeEnvKeys = [ 'OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE', 'OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE', 'OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR', - 'OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR', 'OPENCODE_ANTHROPIC_AUTH_RPC_DIR', 'CLAUDE_CONFIG_DIR', 'OPENCODE_AUTH_CONTENT', diff --git a/packages/opencode/src/tests/commands-and-profiles.integration.test.ts b/packages/opencode/src/tests/commands-and-profiles.integration.test.ts index 6a9b67a60..8768ec3d4 100644 --- a/packages/opencode/src/tests/commands-and-profiles.integration.test.ts +++ b/packages/opencode/src/tests/commands-and-profiles.integration.test.ts @@ -50,7 +50,7 @@ import { useTempAccountFile as useTempAccountFileWithCtx, withNativeAdmission as withNativeAdmissionWithCtx, } from './support/opencode1-pool-fixture.ts' -import { waitForLogRecord as waitForLogRecordWithCtx } from './support/opencode1-quota-feed.ts' +import { waitForLogRecord as waitForLogRecordWithCtx } from './support/opencode1-quota.ts' import { readAccountStorage as readAccountStorageWithCtx, waitForAccountStorage as waitForAccountStorageWithCtx, diff --git a/packages/opencode/src/tests/custody-tombstone.test.ts b/packages/opencode/src/tests/custody-tombstone.test.ts index b19031713..79045801b 100644 --- a/packages/opencode/src/tests/custody-tombstone.test.ts +++ b/packages/opencode/src/tests/custody-tombstone.test.ts @@ -74,7 +74,6 @@ const nativeEnvKeys = [ 'OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE', 'OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE', 'OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR', - 'OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR', 'OPENCODE_ANTHROPIC_AUTH_RPC_DIR', 'OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION', 'OPENCODE_AUTH_CONTENT', diff --git a/packages/opencode/src/tests/dispose-cleanup.test.ts b/packages/opencode/src/tests/dispose-cleanup.test.ts index 449b5d152..65e10d58a 100644 --- a/packages/opencode/src/tests/dispose-cleanup.test.ts +++ b/packages/opencode/src/tests/dispose-cleanup.test.ts @@ -44,7 +44,6 @@ const envKeys = [ 'OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE', 'OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE', 'OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR', - 'OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR', 'OPENCODE_ANTHROPIC_AUTH_RPC_DIR', 'CLAUDE_CONFIG_DIR', 'OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION', diff --git a/packages/opencode/src/tests/fallback-token-use-sites.test.ts b/packages/opencode/src/tests/fallback-token-use-sites.test.ts index 086da7cb3..2489a16eb 100644 --- a/packages/opencode/src/tests/fallback-token-use-sites.test.ts +++ b/packages/opencode/src/tests/fallback-token-use-sites.test.ts @@ -59,7 +59,6 @@ const fixtureEnvKeys = [ 'OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE', 'OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE', 'OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR', - 'OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR', 'OPENCODE_ANTHROPIC_AUTH_RPC_DIR', 'CLAUDE_CONFIG_DIR', 'OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION', diff --git a/packages/opencode/src/tests/host-isolation.test.ts b/packages/opencode/src/tests/host-isolation.test.ts index fa6f06514..fd56a2400 100644 --- a/packages/opencode/src/tests/host-isolation.test.ts +++ b/packages/opencode/src/tests/host-isolation.test.ts @@ -3,7 +3,6 @@ import { readFile } from 'node:fs/promises' import { getAccountStoragePath, getDefaultCacheKeepRegistryDirectory, - getDefaultQuotaHeaderFeedDirectory, getDumpDirectory, getLogFilePath, resolveClaustrumConnectionPath, @@ -20,7 +19,6 @@ const FEATURE_OVERRIDES = [ 'OPENCODE_ANTHROPIC_AUTH_FILE', 'OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE', 'OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR', - 'OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR', 'OPENCODE_ANTHROPIC_AUTH_RPC_DIR', 'OPENCODE_ANTHROPIC_AUTH_DUMP_DIR', ] as const @@ -42,7 +40,6 @@ test('feature-path overrides deleted by a test cannot resolve outside the preloa getPiAuthPath(), getSidebarStateFile(), getDefaultCacheKeepRegistryDirectory('opencode'), - getDefaultQuotaHeaderFeedDirectory(), getRpcDir('/tmp/hostile-project'), getDumpDirectory(), getLogFilePath(), diff --git a/packages/opencode/src/tests/info-logs.test.ts b/packages/opencode/src/tests/info-logs.test.ts index 5f12361ff..7aa74c949 100644 --- a/packages/opencode/src/tests/info-logs.test.ts +++ b/packages/opencode/src/tests/info-logs.test.ts @@ -69,7 +69,6 @@ const envKeys = [ 'OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE', 'OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE', 'OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR', - 'OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR', 'OPENCODE_ANTHROPIC_AUTH_RPC_DIR', 'CLAUDE_CONFIG_DIR', 'OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION', diff --git a/packages/opencode/src/tests/killswitch-preflight.test.ts b/packages/opencode/src/tests/killswitch-preflight.test.ts index adadaf516..6792acd96 100644 --- a/packages/opencode/src/tests/killswitch-preflight.test.ts +++ b/packages/opencode/src/tests/killswitch-preflight.test.ts @@ -77,7 +77,6 @@ const envKeys = [ 'OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE', 'OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE', 'OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR', - 'OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR', 'OPENCODE_ANTHROPIC_AUTH_RPC_DIR', 'OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION', 'OPENCODE_AUTH_CONTENT', diff --git a/packages/opencode/src/tests/local-routing-migration.test.ts b/packages/opencode/src/tests/local-routing-migration.test.ts index 1b97004f9..bfdc266cc 100644 --- a/packages/opencode/src/tests/local-routing-migration.test.ts +++ b/packages/opencode/src/tests/local-routing-migration.test.ts @@ -52,7 +52,6 @@ const envKeys = [ 'OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE', 'OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE', 'OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR', - 'OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR', 'OPENCODE_ANTHROPIC_AUTH_RPC_DIR', 'OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION', ] as const @@ -115,7 +114,6 @@ async function fixture(override = false) { ), OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE: join(root, 'sidebar.json'), OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR: join(root, 'cachekeep'), - OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR: join(root, 'quota-feed'), OPENCODE_ANTHROPIC_AUTH_RPC_DIR: join(root, 'rpc'), OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION: '1', }) @@ -371,7 +369,6 @@ async function emptyFixture(override: boolean): Promise { ), OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE: join(root, 'sidebar.json'), OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR: join(root, 'cachekeep'), - OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR: join(root, 'quota-feed'), OPENCODE_ANTHROPIC_AUTH_RPC_DIR: join(root, 'rpc'), OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION: '1', }) diff --git a/packages/opencode/src/tests/native-fixture.ts b/packages/opencode/src/tests/native-fixture.ts index 55222bc8b..9e9913f06 100644 --- a/packages/opencode/src/tests/native-fixture.ts +++ b/packages/opencode/src/tests/native-fixture.ts @@ -64,7 +64,6 @@ export type NativeOpencodeFixtureEnv = Readonly<{ OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE: string OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE: string OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR: string - OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR: string OPENCODE_ANTHROPIC_AUTH_RPC_DIR: string CLAUDE_CONFIG_DIR: string }> @@ -217,7 +216,6 @@ async function migrate( root, 'cachekeep-registry', ), - OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR: join(root, 'quota-header-feed'), OPENCODE_ANTHROPIC_AUTH_RPC_DIR: join(root, 'rpc'), CLAUDE_CONFIG_DIR: join(root, 'claude'), }) diff --git a/packages/opencode/src/tests/native-menu-settings.test.ts b/packages/opencode/src/tests/native-menu-settings.test.ts index a7eb0f9d6..158c015ed 100644 --- a/packages/opencode/src/tests/native-menu-settings.test.ts +++ b/packages/opencode/src/tests/native-menu-settings.test.ts @@ -44,7 +44,6 @@ const envKeys = [ 'OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE', 'OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE', 'OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR', - 'OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR', 'OPENCODE_ANTHROPIC_AUTH_RPC_DIR', 'OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION', 'OPENCODE_AUTH_CONTENT', diff --git a/packages/opencode/src/tests/native-serving.test.ts b/packages/opencode/src/tests/native-serving.test.ts index a463036c7..9497b9902 100644 --- a/packages/opencode/src/tests/native-serving.test.ts +++ b/packages/opencode/src/tests/native-serving.test.ts @@ -89,7 +89,6 @@ const envKeys = [ 'OPENCODE_ANTHROPIC_AUTH_STATE_FILE', 'OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE', 'OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR', - 'OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR', 'OPENCODE_ANTHROPIC_AUTH_RPC_DIR', 'OPENCODE_ANTHROPIC_AUTH_ROUTING_STATE_FILE', 'OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_ENROLLMENT_FILE', @@ -239,10 +238,6 @@ async function setupBody() { directory, 'cachekeep', ) - process.env.OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR = join( - directory, - 'quota-feed', - ) process.env.OPENCODE_ANTHROPIC_AUTH_RPC_DIR = join(directory, 'rpc') process.env.OPENCODE_ANTHROPIC_AUTH_ROUTING_STATE_FILE = join( directory, diff --git a/packages/opencode/src/tests/native-status-profile.test.ts b/packages/opencode/src/tests/native-status-profile.test.ts index dcc9bf6c5..8528e7cec 100644 --- a/packages/opencode/src/tests/native-status-profile.test.ts +++ b/packages/opencode/src/tests/native-status-profile.test.ts @@ -77,7 +77,6 @@ const envKeys = [ 'OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE', 'OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE', 'OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR', - 'OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR', 'OPENCODE_ANTHROPIC_AUTH_RPC_DIR', 'OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION', 'OPENCODE_AUTH_CONTENT', diff --git a/packages/opencode/src/tests/oauth-callback-corrupt-store.test.ts b/packages/opencode/src/tests/oauth-callback-corrupt-store.test.ts index f6b3ad62a..f8ede35a5 100644 --- a/packages/opencode/src/tests/oauth-callback-corrupt-store.test.ts +++ b/packages/opencode/src/tests/oauth-callback-corrupt-store.test.ts @@ -51,7 +51,6 @@ const envKeys = [ 'OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE', 'OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE', 'OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR', - 'OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR', 'OPENCODE_ANTHROPIC_AUTH_RPC_DIR', 'CLAUDE_CONFIG_DIR', 'OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION', diff --git a/packages/opencode/src/tests/opencode1-settings-read.test.ts b/packages/opencode/src/tests/opencode1-settings-read.test.ts index 73b031d7b..c61ad7f0d 100644 --- a/packages/opencode/src/tests/opencode1-settings-read.test.ts +++ b/packages/opencode/src/tests/opencode1-settings-read.test.ts @@ -7,10 +7,12 @@ import { applyEdits, modify, parse } from 'jsonc-parser' import { nativeAccountSettings } from '../../../core/src/native-account-view' import { nativeQuotaCodec } from '../../../core/src/native-quota-codec' import { nativeVaultPaths } from '../../../core/src/native-vault-paths' -import releaseSnapshots from './fixtures/settings-2.11.2.json' import { settingsReaderOutputs } from './opencode2-settings-readers' import { getPluginTestHandles } from './plugin-test-handles' -import { snapshotSettings } from './settings-snapshot-fixture' +import { + expectedReleaseSnapshot, + snapshotSettings, +} from './settings-snapshot-fixture' import { observeSettings } from './settings-snapshot-observe' import { applyMenuAction, @@ -32,10 +34,6 @@ import { useVaultAccountFile, withNativeAdmission, } from './support/opencode1-pool-fixture' -import { - readFeedEntries, - waitForFeedEntries, -} from './support/opencode1-quota-feed' import { createOpencode1Test, createOpencode1TestContext, @@ -60,8 +58,6 @@ async function fixture( const saved = process.env.ANTHROPIC_AUTH_SETTINGS_FILE const level = process.env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL const liveLevel = core.getLogLevel() - const feed = process.env.OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR - process.env.OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR = join(pool.root, 'feed') if (mode !== 'separate') process.env.ANTHROPIC_AUTH_SETTINGS_FILE = target else delete process.env.ANTHROPIC_AUTH_SETTINGS_FILE delete process.env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL @@ -73,9 +69,6 @@ async function fixture( if (level === undefined) delete process.env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL else process.env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL = level - if (feed === undefined) - delete process.env.OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR - else process.env.OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR = feed }) const protection = core.legacySettingsProtection( await readNativeSettings(ctx), @@ -524,7 +517,6 @@ describe('OpenCode 1 settings service reads', () => { claude_cache_enabled: 'on', claude_cache_mode: 'automatic', quota_enabled: 'off', - quota_header_feed_enabled: true, }) expect(core.isDumpEnabled()).toBe(true) expect(core.getLogLevel()).toBe('debug') @@ -534,9 +526,6 @@ describe('OpenCode 1 settings service reads', () => { const changed = await instance.request() expect(changed.body.speed).toBe('fast') expect(changed.body.cache_control).toEqual({ type: 'ephemeral', ttl: '1h' }) - expect( - (await instance.runtime.read()).policyStorage.quotaHeaderFeed?.enabled, - ).toBe(true) await f.change({ dump_enabled: false, log_level: 'debug', @@ -558,24 +547,6 @@ describe('OpenCode 1 settings service reads', () => { expect(core.getLogLevel()).toBe('debug') }) - test('quota header feed enablement still requires a restart after a hand edit', async () => { - const f = await fixture() - const a = await f.launch() - await f.change({ quota_header_feed_enabled: true, quota_enabled: 'off' }) - await a.request() - expect(await readFeedEntries()).toEqual([]) - await a.plugin.dispose!() - ctx.livePlugins.delete(a.plugin) - const b = await f.launch() - await b.request() - const entries = await waitForFeedEntries( - ctx, - (entries) => entries.length > 0, - 'enabled feed after restart', - ) - expect(entries.length).toBeGreaterThan(0) - }) - for (const event of ['action', 'timer'] as const) { test(`a legacy instance notices a peer marker on the next ${event}, never on a request`, async () => { const f = await fixture('legacy') @@ -823,7 +794,7 @@ describe('OpenCode 1 settings service reads', () => { ), } expect(JSON.stringify(compatible), phase).toBe( - JSON.stringify(releaseSnapshots[`oc1-${sample}`]), + JSON.stringify(expectedReleaseSnapshot(1, sample)), ) expect(observed.logs.length).toBeGreaterThan(0) expect(observed.track.tracked).toBe(true) diff --git a/packages/opencode/src/tests/opencode2-e2e.test.ts b/packages/opencode/src/tests/opencode2-e2e.test.ts index 93be5961f..97aec9556 100644 --- a/packages/opencode/src/tests/opencode2-e2e.test.ts +++ b/packages/opencode/src/tests/opencode2-e2e.test.ts @@ -403,7 +403,6 @@ async function seedOc1Bootstrap( configDir: env.XDG_CONFIG_HOME!, dataDir: env.XDG_DATA_HOME!, cacheDir: env.XDG_CACHE_HOME!, - quotaFeedDir: join(root, 'quota-feed'), }, // OC1 runs here without OPENCODE_CONFIG_DIR, but the shared helper always // adds that variable's directory as a target. Name the XDG config diff --git a/packages/opencode/src/tests/opencode2-settings-read.test.ts b/packages/opencode/src/tests/opencode2-settings-read.test.ts index e03a866c9..a024a3d34 100644 --- a/packages/opencode/src/tests/opencode2-settings-read.test.ts +++ b/packages/opencode/src/tests/opencode2-settings-read.test.ts @@ -18,9 +18,11 @@ import { createNativeMenuCapabilities } from '../v2/menu' import * as reloadFactory from '../v2/reload' import { setupAnthropicAuth } from '../v2/setup' import * as sourceFactory from '../v2/source' -import releaseSnapshots from './fixtures/settings-2.11.2.json' import { settingsReaderOutputs } from './opencode2-settings-readers' -import { snapshotSettings } from './settings-snapshot-fixture' +import { + expectedReleaseSnapshot, + snapshotSettings, +} from './settings-snapshot-fixture' import { observeSettings } from './settings-snapshot-observe' const cleanups: (() => unknown | Promise)[] = [] @@ -1254,7 +1256,7 @@ for (const mode of ['local', 'claustrum'] as const) { ), } expect(JSON.stringify(compatible), phase).toBe( - JSON.stringify(releaseSnapshots[`oc2-${sample}`]), + JSON.stringify(expectedReleaseSnapshot(2, sample)), ) expect(observed.logs.length).toBeGreaterThan(0) expect(observed.track.tracked).toBe(true) diff --git a/packages/opencode/src/tests/opencode2-settings-readers.ts b/packages/opencode/src/tests/opencode2-settings-readers.ts index 9beb52a1b..6d1fb2a1a 100644 --- a/packages/opencode/src/tests/opencode2-settings-readers.ts +++ b/packages/opencode/src/tests/opencode2-settings-readers.ts @@ -70,10 +70,6 @@ export function settingsReaderOutputs( /function showQuotaToastFromCache\(\) \{\s*if \(([^\n]+)\) return/, s, ), - quota_header_feed_enabled: predicate( - /const quotaHeaderFeedRegistry =\s*(initialStorage[\s\S]*?)\s*\? new QuotaHeaderFeedRegistry/, - s, - ), killswitch_enabled: core.isKillswitchEnabled(s), killswitch_default_five_hour: core.getKillswitchThresholdsForAccount(s).five_hour, @@ -147,7 +143,6 @@ export function nondefaultSettings(account: string) { failClosedOnUnknownQuota: false, showToasts: true, }, - quotaHeaderFeed: { enabled: true }, killswitch: { enabled: true, main: { five_hour: 21, seven_day: 22, scoped: 23 }, diff --git a/packages/opencode/src/tests/preload-sandbox.ts b/packages/opencode/src/tests/preload-sandbox.ts index debd156eb..c40737a18 100644 --- a/packages/opencode/src/tests/preload-sandbox.ts +++ b/packages/opencode/src/tests/preload-sandbox.ts @@ -42,7 +42,6 @@ const safetyPaths = { testDir, 'cachekeep-registry', ), - OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR: join(testDir, 'quota-header-feed'), OPENCODE_ANTHROPIC_AUTH_RPC_DIR: join(testDir, 'rpc'), OPENCODE_ANTHROPIC_AUTH_DUMP_DIR: join(testDir, 'dumps'), } as const diff --git a/packages/opencode/src/tests/provider-error.test.ts b/packages/opencode/src/tests/provider-error.test.ts index 0525b384f..787f98908 100644 --- a/packages/opencode/src/tests/provider-error.test.ts +++ b/packages/opencode/src/tests/provider-error.test.ts @@ -50,7 +50,6 @@ const envKeys = [ 'OPENCODE_ANTHROPIC_AUTH_STATE_FILE', 'OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE', 'OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR', - 'OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR', 'OPENCODE_ANTHROPIC_AUTH_RPC_DIR', 'OPENCODE_ANTHROPIC_AUTH_ROUTING_STATE_FILE', 'OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_ENROLLMENT_FILE', @@ -278,7 +277,6 @@ async function startBody() { ) process.env.OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE = file('sidebar.json') process.env.OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR = file('cachekeep') - process.env.OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR = file('quota-feed') process.env.OPENCODE_ANTHROPIC_AUTH_RPC_DIR = file('rpc') process.env.OPENCODE_ANTHROPIC_AUTH_ROUTING_STATE_FILE = file('routing.json') process.env.OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_ENROLLMENT_FILE = diff --git a/packages/opencode/src/tests/quota-header-feed.test.ts b/packages/opencode/src/tests/quota-header-feed.test.ts deleted file mode 100644 index f6379da25..000000000 --- a/packages/opencode/src/tests/quota-header-feed.test.ts +++ /dev/null @@ -1,697 +0,0 @@ -import { afterEach, beforeEach, describe, expect, test } from 'bun:test' -import { - chmod, - mkdir, - mkdtemp, - readdir, - readFile, - rename, - rm, - stat, - utimes, - writeFile, -} from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import type { AccountStorage } from '../../../core/src/accounts.ts' -import { - configuredAnthropicOAuthAccountCount, - QUOTA_HEADER_FEED_LEASE_MS, - QUOTA_HEADER_FEED_SCHEMA_VERSION, - type QuotaHeaderFeedEntry, - type QuotaHeaderFeedPublishEntry, - QuotaHeaderFeedRegistry, -} from '../../../core/src/quota-header-feed.ts' -import { normalizeQuotaHeaders } from '../../../core/src/quota-headers.ts' - -const quota = { bindingWindow: 'five_hour', fallbackAdvised: false } - -function entry(overrides: Record = {}): QuotaHeaderFeedEntry { - return { - identity_source: 'credential_id', - credential_id: 'cred-1', - schema_version: QUOTA_HEADER_FEED_SCHEMA_VERSION, - provider: 'anthropic', - configured_account_count: 1, - observed_at_ms: 1_000, - anthropic_account_uuid: null, - quota, - ...overrides, - } as QuotaHeaderFeedEntry -} - -function storage(accounts: AccountStorage['accounts']): AccountStorage { - return { - version: 1, - main: { type: 'opencode', provider: 'anthropic' }, - accounts, - } -} - -function noneEntry(): QuotaHeaderFeedEntry { - const { credential_id: _credentialId, ...withoutCredential } = - entry() as Extract< - QuotaHeaderFeedEntry, - { identity_source: 'credential_id' } - > - return { ...withoutCredential, identity_source: 'none' } -} - -describe('quota header feed', () => { - let directory: string - beforeEach(async () => { - directory = await mkdtemp(join(tmpdir(), 'quota-header-feed-test-')) - }) - afterEach(async () => { - await rm(directory, { recursive: true, force: true }) - }) - - test('requires schema version and provider', async () => { - const registry = new QuotaHeaderFeedRegistry({ - directory, - instanceId: 'required', - }) - await expect( - registry.publish({ ...entry(), accountKey: 'a' }), - ).resolves.toBeUndefined() - const raw = JSON.parse( - await readFile(join(directory, 'required.json'), 'utf8'), - ) - expect(QUOTA_HEADER_FEED_SCHEMA_VERSION).toBe(3) - expect(raw.entries.a.schema_version).toBe(3) - expect(raw.entries.a.provider).toBe('anthropic') - expect(raw.lease_horizon_ms).toBe(QUOTA_HEADER_FEED_LEASE_MS) - expect(raw.entries.a).toHaveProperty('anthropic_account_uuid', null) - }) - - test('projects only the documented entry keys', async () => { - const registry = new QuotaHeaderFeedRegistry({ - directory, - instanceId: 'entry-allowlist', - }) - await registry.publish({ - ...entry({ - anthropic_account_uuid: 'uuid-1', - unexpected_entry_secret: 'must-not-publish', - }), - accountKey: 'a', - } as unknown as QuotaHeaderFeedPublishEntry) - - const raw = JSON.parse( - await readFile(join(directory, 'entry-allowlist.json'), 'utf8'), - ) - expect(raw.entries.a).toEqual({ - identity_source: 'credential_id', - credential_id: 'cred-1', - schema_version: QUOTA_HEADER_FEED_SCHEMA_VERSION, - provider: 'anthropic', - configured_account_count: 1, - observed_at_ms: 1_000, - anthropic_account_uuid: 'uuid-1', - quota, - }) - expect(JSON.stringify(raw)).not.toContain('must-not-publish') - }) - - test('publishes the configured lease horizon from the registry seam', async () => { - const registry = new QuotaHeaderFeedRegistry({ - directory, - instanceId: 'lease-horizon', - leaseMs: 17, - }) - await registry.publish({ ...entry(), accountKey: 'a' }) - const raw = JSON.parse( - await readFile(join(directory, 'lease-horizon.json'), 'utf8'), - ) - expect(raw.lease_horizon_ms).toBe(17) - }) - - test.each([1, 2, 999])( - 'rejects unknown schema versions %p', - async (version) => { - await mkdir(directory, { recursive: true }) - await writeFile( - join(directory, 'unknown.json'), - JSON.stringify({ - version, - entries: { a: { ...entry(), schema_version: version } }, - updated_at_ms: 1_000, - }), - ) - const registry = new QuotaHeaderFeedRegistry({ - directory, - now: () => 1_000, - }) - expect(await registry.list()).toEqual([]) - }, - ) - - test('enforces identity exclusivity and omits identity fields for none', async () => { - const registry = new QuotaHeaderFeedRegistry({ - directory, - instanceId: 'identity', - }) - await expect( - registry.publish({ ...entry({ account_ref: 'ref-1' }), accountKey: 'a' }), - ).rejects.toThrow() - await expect( - registry.publish({ - ...noneEntry(), - accountKey: 'none', - }), - ).resolves.toBeUndefined() - const raw = JSON.parse( - await readFile(join(directory, 'identity.json'), 'utf8'), - ) - expect(raw.entries.none).not.toHaveProperty('credential_id') - expect(raw.entries.none).not.toHaveProperty('account_ref') - }) - - test.each(['main', '', null])( - 'rejects sentinel identity value %p', - async (value) => { - const registry = new QuotaHeaderFeedRegistry({ directory }) - await expect( - registry.publish({ - ...entry({ credential_id: value as string | null }), - accountKey: 'a', - }), - ).rejects.toThrow() - }, - ) - - test('counts live main OAuth and every OAuth fallback, including disabled and migrated', () => { - const accounts = [ - { id: 'idle', type: 'oauth', refresh: 'r' }, - { id: 'disabled', type: 'oauth', refresh: 'r', enabled: false }, - { id: 'migrated', type: 'oauth', refresh: 'r', enabled: true }, - { id: 'api', type: 'api', apiKey: 'k', baseURL: 'https://example.com' }, - ] as AccountStorage['accounts'] - expect( - configuredAnthropicOAuthAccountCount({ - storage: storage(accounts), - mainOAuthConfigured: true, - }), - ).toBe(4) - expect( - configuredAnthropicOAuthAccountCount({ - storage: storage(accounts), - mainOAuthConfigured: false, - }), - ).toBe(3) - }) - - test('absent main identity uses none', async () => { - const registry = new QuotaHeaderFeedRegistry({ - directory, - instanceId: 'none', - now: () => 1_001, - }) - await registry.publish({ - ...noneEntry(), - accountKey: 'a', - }) - expect((await registry.list())[0]).toEqual( - expect.objectContaining({ identity_source: 'none' }), - ) - }) - - test('does not expose even a complete lease before its atomic rename', async () => { - const registry = new QuotaHeaderFeedRegistry({ - directory, - instanceId: 'committed-only', - now: () => 1_001, - }) - const temporary = join(directory, 'committed-only.json.uncommitted.tmp') - await writeFile( - temporary, - JSON.stringify({ - version: QUOTA_HEADER_FEED_SCHEMA_VERSION, - lease_horizon_ms: QUOTA_HEADER_FEED_LEASE_MS, - entries: { a: entry() }, - }), - { mode: 0o600 }, - ) - expect(await registry.list()).toEqual([]) - await rename(temporary, join(directory, 'committed-only.json')) - expect(await registry.list()).toEqual([entry()]) - }) - - test('uses restrictive permissions and atomic temp rename', async () => { - await chmod(directory, 0o777) - expect((await stat(directory)).mode & 0o777).toBe(0o777) - const registry = new QuotaHeaderFeedRegistry({ - directory, - instanceId: 'permissions', - }) - await registry.publish({ ...entry(), accountKey: 'a' }) - expect((await stat(directory)).mode & 0o777).toBe(0o700) - expect((await stat(join(directory, 'permissions.json'))).mode & 0o777).toBe( - 0o600, - ) - expect(await readdir(directory)).toEqual(['permissions.json']) - }) - - test('publishes only the allowlisted quota fields', async () => { - const registry = new QuotaHeaderFeedRegistry({ - directory, - instanceId: 'quota-fields', - }) - await registry.publish({ - ...entry({ - quota: { - five_hour: { - usedPercent: 10, - remainingPercent: 90, - resetsAt: '2026-08-26T01:00:00.000Z', - checkedAt: 800, - unexpected_window_secret: 'must-not-publish-window', - }, - seven_day: { - usedPercent: 20, - remainingPercent: 80, - resetsAt: '2026-08-27T00:00:00.000Z', - checkedAt: 801, - unexpected_window_secret: 'must-not-publish-window', - }, - bindingWindow: 'five_hour', - fallbackAdvised: false, - scoped: [ - { - id: 'scope-1', - title: 'Fable only', - modelName: 'Fable', - usedPercent: 55, - remainingPercent: 45, - resetsAt: '2026-08-26T00:00:00.000Z', - checkedAt: 900, - unexpected_scope_secret: 'must-not-publish-scope', - }, - ], - extraUsage: { - used: { - amountMinor: 25, - currency: 'USD', - exponent: 2, - unexpected_money_secret: 'must-not-publish-money', - }, - limit: { amountMinor: 100, currency: 'USD', exponent: 2 }, - utilizationPercent: 25, - severity: 'warning', - exhausted: false, - unexpected_extra_usage_secret: 'must-not-publish-extra-usage', - }, - unexpected_secret: 'must-not-publish', - } as unknown as QuotaHeaderFeedEntry['quota'], - }), - accountKey: 'a', - } as unknown as QuotaHeaderFeedPublishEntry) - const raw = JSON.parse( - await readFile(join(directory, 'quota-fields.json'), 'utf8'), - ) - const bytes = await readFile(join(directory, 'quota-fields.json'), 'utf8') - expect(raw.entries.a.quota).toEqual({ - five_hour: { - usedPercent: 10, - remainingPercent: 90, - resetsAt: '2026-08-26T01:00:00.000Z', - checkedAt: 800, - }, - seven_day: { - usedPercent: 20, - remainingPercent: 80, - resetsAt: '2026-08-27T00:00:00.000Z', - checkedAt: 801, - }, - bindingWindow: 'five_hour', - fallbackAdvised: false, - scoped: [ - { - id: 'scope-1', - title: 'Fable only', - modelName: 'Fable', - usedPercent: 55, - remainingPercent: 45, - resetsAt: '2026-08-26T00:00:00.000Z', - checkedAt: 900, - }, - ], - extraUsage: { - used: { amountMinor: 25, currency: 'USD', exponent: 2 }, - limit: { amountMinor: 100, currency: 'USD', exponent: 2 }, - utilizationPercent: 25, - severity: 'warning', - exhausted: false, - }, - }) - expect(raw.entries.a.quota).not.toHaveProperty('unexpected_secret') - expect(bytes).not.toContain('must-not-publish-window') - expect(bytes).not.toContain('must-not-publish-scope') - expect(bytes).not.toContain('must-not-publish-money') - expect(bytes).not.toContain('must-not-publish-extra-usage') - expect(bytes).not.toContain('must-not-publish') - expect(bytes).not.toContain('authorization') - expect(bytes).not.toContain('access-token') - }) - - test('publishes only allowlisted per-field provenance', async () => { - const registry = new QuotaHeaderFeedRegistry({ - directory, - instanceId: 'provenance-fields', - }) - await registry.publish({ - ...entry({ - quota: { - five_hour: { - usedPercent: 10, - remainingPercent: 90, - checkedAt: 800, - }, - seven_day: { - usedPercent: 20, - remainingPercent: 80, - checkedAt: 801, - }, - bindingWindow: 'five_hour', - fallbackAdvised: false, - fieldSources: { - five_hour: 'headers', - seven_day: 'poll', - scoped: 'poll', - extraUsage: 'poll', - bindingWindow: 'headers', - unexpected: 'must-not-publish', - }, - } as unknown as QuotaHeaderFeedEntry['quota'], - }), - accountKey: 'a', - } as unknown as QuotaHeaderFeedPublishEntry) - - const raw = JSON.parse( - await readFile(join(directory, 'provenance-fields.json'), 'utf8'), - ) - const bytes = await readFile( - join(directory, 'provenance-fields.json'), - 'utf8', - ) - expect(raw.entries.a.quota.provenance).toEqual({ - five_hour: 'headers', - seven_day: 'poll', - bindingWindow: 'headers', - }) - expect(bytes).not.toContain('must-not-publish') - }) - - test('does not publish provenance for absent quota fields', async () => { - const registry = new QuotaHeaderFeedRegistry({ - directory, - instanceId: 'provenance-presence', - }) - await registry.publish({ - ...entry({ - quota: { - seven_day: { - usedPercent: 20, - remainingPercent: 80, - checkedAt: 801, - }, - fieldSources: { - five_hour: 'poll', - seven_day: 'headers', - }, - } as unknown as QuotaHeaderFeedEntry['quota'], - }), - accountKey: 'a', - } as unknown as QuotaHeaderFeedPublishEntry) - - const raw = JSON.parse( - await readFile(join(directory, 'provenance-presence.json'), 'utf8'), - ) - expect(raw.entries.a.quota.provenance).toEqual({ - seven_day: 'headers', - }) - }) - - test('keeps source internal and excludes it from published entries', async () => { - const registry = new QuotaHeaderFeedRegistry({ - directory, - instanceId: 'source-projection', - }) - const internalSnapshot = normalizeQuotaHeaders( - new Headers({ - 'anthropic-ratelimit-unified-fallback': 'available', - }), - ) - expect(internalSnapshot).toHaveProperty('source', 'headers') - - await registry.publish({ - ...entry(), - quota: { - fallbackAdvised: internalSnapshot.fallbackAdvised, - source: 'headers', - } as unknown as QuotaHeaderFeedPublishEntry['quota'], - accountKey: 'a', - }) - const raw = JSON.parse( - await readFile(join(directory, 'source-projection.json'), 'utf8'), - ) - expect(raw.entries.a.quota).not.toHaveProperty('source') - }) - - test('omits malformed nested quota values without dropping the entry', async () => { - const registry = new QuotaHeaderFeedRegistry({ - directory, - instanceId: 'malformed-nested', - }) - await registry.publish({ - ...entry({ - quota: { - five_hour: { - usedPercent: 'not-a-number', - remainingPercent: 90, - checkedAt: 800, - }, - seven_day: { - usedPercent: 20, - remainingPercent: 80, - checkedAt: 801, - }, - bindingWindow: 'seven_day', - fallbackAdvised: false, - scoped: [ - { - id: 'valid', - title: 'Valid', - modelName: 'Fable', - usedPercent: 55, - remainingPercent: 45, - checkedAt: 900, - }, - { - id: 'invalid', - title: 'Invalid', - modelName: 'Fable', - usedPercent: Number.NaN, - remainingPercent: 45, - checkedAt: 900, - }, - ], - extraUsage: { - used: { amountMinor: 25, currency: 'USD', exponent: 2 }, - limit: { amountMinor: Number.NaN, currency: 'USD', exponent: 2 }, - utilizationPercent: Number.NaN, - severity: 42, - exhausted: false, - }, - } as unknown as QuotaHeaderFeedEntry['quota'], - }), - accountKey: 'a', - } as unknown as QuotaHeaderFeedPublishEntry) - const raw = JSON.parse( - await readFile(join(directory, 'malformed-nested.json'), 'utf8'), - ) - expect(raw.entries.a.quota).toEqual({ - seven_day: { - usedPercent: 20, - remainingPercent: 80, - checkedAt: 801, - }, - bindingWindow: 'seven_day', - fallbackAdvised: false, - scoped: [ - { - id: 'valid', - title: 'Valid', - modelName: 'Fable', - usedPercent: 55, - remainingPercent: 45, - checkedAt: 900, - }, - ], - }) - }) - - test('ignores stale, future, and malformed records', async () => { - await mkdir(directory, { recursive: true }) - await writeFile( - join(directory, 'stale.json'), - JSON.stringify({ - version: 3, - entries: { a: entry({ observed_at_ms: 1_000 }) }, - }), - ) - await writeFile( - join(directory, 'future.json'), - JSON.stringify({ - version: 3, - entries: { a: entry({ observed_at_ms: 181_001 }) }, - }), - ) - await writeFile(join(directory, 'bad.json'), '{not-json') - const registry = new QuotaHeaderFeedRegistry({ - directory, - now: () => 1_000 + QUOTA_HEADER_FEED_LEASE_MS, - }) - expect(await registry.list()).toEqual([]) - }) - - test('deduplicates one account using newest observation', async () => { - const first = new QuotaHeaderFeedRegistry({ - directory, - instanceId: 'first', - now: () => 1_003, - }) - const second = new QuotaHeaderFeedRegistry({ - directory, - instanceId: 'second', - now: () => 1_003, - }) - await first.publish({ - ...entry({ observed_at_ms: 1_001 }), - accountKey: 'same', - }) - await second.publish({ - ...entry({ observed_at_ms: 1_002, credential_id: 'new' }), - accountKey: 'same', - }) - expect(await first.list()).toEqual([ - entry({ observed_at_ms: 1_002, credential_id: 'new' }), - ]) - }) - - test('reaps stale sibling process leases without touching fresh or foreign files', async () => { - const now = Date.now() - await mkdir(directory, { recursive: true }) - const staleNames = [ - '101-11111111-1111-1111-1111-111111111111.json', - '102-22222222-2222-2222-2222-222222222222.json', - '103-33333333-3333-3333-3333-333333333333.json', - ] - const freshNames = [ - '104-44444444-4444-4444-4444-444444444444.json', - '105-55555555-5555-5555-5555-555555555555.json', - ] - for (const name of [...staleNames, ...freshNames]) { - const path = join(directory, name) - await writeFile(path, '{}') - const age = staleNames.includes(name) - ? QUOTA_HEADER_FEED_LEASE_MS + 1 - : QUOTA_HEADER_FEED_LEASE_MS - 1 - await utimes(path, (now - age) / 1_000, (now - age) / 1_000) - } - await writeFile(join(directory, 'foreign-named-file.json'), '{}') - await utimes( - join(directory, 'foreign-named-file.json'), - (now - QUOTA_HEADER_FEED_LEASE_MS - 1) / 1_000, - (now - QUOTA_HEADER_FEED_LEASE_MS - 1) / 1_000, - ) - - const registry = new QuotaHeaderFeedRegistry({ - directory, - instanceId: '106-66666666-6666-6666-6666-666666666666', - now: () => now, - }) - await registry.publish({ ...entry(), accountKey: 'a' }) - - const names = await readdir(directory) - for (const name of staleNames) expect(names).not.toContain(name) - for (const name of freshNames) expect(names).toContain(name) - expect(names).toContain('foreign-named-file.json') - expect(names).toContain('106-66666666-6666-6666-6666-666666666666.json') - }) - - test('does not unlink a fresh lease published after the stale lease was inspected', async () => { - const now = Date.now() - const siblingName = '101-11111111-1111-1111-1111-111111111111.json' - const siblingPath = join(directory, siblingName) - const replacementPath = join(directory, 'fresh-publisher.tmp') - await mkdir(directory, { recursive: true }) - await writeFile(siblingPath, '{"stale":true}') - await utimes( - siblingPath, - (now - QUOTA_HEADER_FEED_LEASE_MS - 1) / 1_000, - (now - QUOTA_HEADER_FEED_LEASE_MS - 1) / 1_000, - ) - expect(now - (await stat(siblingPath)).mtimeMs).toBeGreaterThanOrEqual( - QUOTA_HEADER_FEED_LEASE_MS, - ) - - let publisherRan = false - let publisherError: unknown - const registry = new QuotaHeaderFeedRegistry({ - directory, - instanceId: '102-22222222-2222-2222-2222-222222222222', - now: () => now, - beforeRemoveFile: async (path: string) => { - publisherRan = true - try { - await writeFile(replacementPath, '{"fresh":true}') - await utimes(replacementPath, now / 1_000, now / 1_000) - await rename(replacementPath, siblingPath) - expect(path).toBe(siblingPath) - } catch (error) { - publisherError = error - throw error - } - }, - }) - - await registry.publish({ ...entry(), accountKey: 'a' }) - - expect(publisherRan).toBe(true) - expect(publisherError).toBeUndefined() - expect(await readFile(siblingPath, 'utf8')).toBe('{"fresh":true}') - }) - - test('continues publishing when a sibling lease sweep cannot unlink a stale file', async () => { - const now = Date.now() - const stalePath = join( - directory, - '101-11111111-1111-1111-1111-111111111111.json', - ) - await mkdir(directory, { recursive: true }) - await writeFile(stalePath, '{}') - await utimes( - stalePath, - (now - QUOTA_HEADER_FEED_LEASE_MS - 1) / 1_000, - (now - QUOTA_HEADER_FEED_LEASE_MS - 1) / 1_000, - ) - const ownFile = '102-22222222-2222-2222-2222-222222222222.json' - const registry = new QuotaHeaderFeedRegistry({ - directory, - instanceId: ownFile.slice(0, -'.json'.length), - now: () => now, - removeFile: async () => { - throw Object.assign(new Error('permission denied'), { code: 'EACCES' }) - }, - }) - - await expect( - registry.publish({ ...entry(), accountKey: 'a' }), - ).resolves.toBeUndefined() - expect(await readdir(directory)).toContain(ownFile) - expect(await readdir(directory)).toContain( - '101-11111111-1111-1111-1111-111111111111.json', - ) - }) -}) diff --git a/packages/opencode/src/tests/quota-header-harvest.integration.test.ts b/packages/opencode/src/tests/quota-header-harvest.integration.test.ts index 7200c3075..f2e507bc0 100644 --- a/packages/opencode/src/tests/quota-header-harvest.integration.test.ts +++ b/packages/opencode/src/tests/quota-header-harvest.integration.test.ts @@ -37,7 +37,7 @@ import { useTempAccountFile as useTempAccountFileWithCtx, withNativeAdmission as withNativeAdmissionWithCtx, } from './support/opencode1-pool-fixture.ts' -import { waitForLogRecord as waitForLogRecordWithCtx } from './support/opencode1-quota-feed.ts' +import { waitForLogRecord as waitForLogRecordWithCtx } from './support/opencode1-quota.ts' import { readAccountStorage as readAccountStorageWithCtx, waitForSidebarState as waitForSidebarStateWithCtx, diff --git a/packages/opencode/src/tests/quota-feed.integration.test.ts b/packages/opencode/src/tests/quota-persistence.integration.test.ts similarity index 80% rename from packages/opencode/src/tests/quota-feed.integration.test.ts rename to packages/opencode/src/tests/quota-persistence.integration.test.ts index 8e96675a1..9741330b4 100644 --- a/packages/opencode/src/tests/quota-feed.integration.test.ts +++ b/packages/opencode/src/tests/quota-persistence.integration.test.ts @@ -1,8 +1,7 @@ import { afterEach, describe, expect, mock } from 'bun:test' import { randomUUID } from 'node:crypto' import { readFileSync } from 'node:fs' -import { mkdir, readFile, writeFile } from 'node:fs/promises' -import { dirname, join } from 'node:path' +import { readFile } from 'node:fs/promises' import { __setLogTestSink, type AccountStorage, @@ -51,11 +50,8 @@ import { import { expectNonOatMainRefused as expectNonOatMainRefusedWithCtx, expectUnknownQuotaAdmissionBlocked as expectUnknownQuotaAdmissionBlockedWithCtx, - loadMainAndFetch as loadMainAndFetchWithCtx, - readFeedEntries, - waitForFeedEntries as waitForFeedEntriesWithCtx, waitForLogRecord as waitForLogRecordWithCtx, -} from './support/opencode1-quota-feed.ts' +} from './support/opencode1-quota.ts' import { readAccountStorage as readAccountStorageWithCtx, waitForAccountStorage as waitForAccountStorageWithCtx, @@ -175,12 +171,6 @@ function waitForNativePoolQuota( ) { return waitForNativePoolQuotaWithCtx(testContext, routeId, predicate, options) } -function waitForFeedEntries( - predicate: (entries: Awaited>) => boolean, - description: string, -) { - return waitForFeedEntriesWithCtx(testContext, predicate, description) -} function waitForLogRecord( records: LogTestRecord[], predicate: (record: LogTestRecord) => boolean, @@ -188,13 +178,6 @@ function waitForLogRecord( ) { return waitForLogRecordWithCtx(testContext, records, predicate, description) } -function loadMainAndFetch( - storage: AccountStorage, - response: Response | (() => Response), - requestHeaders?: Record, -) { - return loadMainAndFetchWithCtx(testContext, storage, response, requestHeaders) -} function expectNonOatMainRefused(access: string) { return expectNonOatMainRefusedWithCtx(testContext, access) } @@ -351,7 +334,7 @@ describe('fallback quota persistence ordering', () => { }) }) -describe('quota header feed integration', () => { +describe('quota header harvest and persistence', () => { const originalFetch = globalThis.fetch afterEach(async () => { @@ -369,12 +352,12 @@ describe('quota header feed integration', () => { 'non-OAT compatibility identity stays a local quota key without a provider uuid', async () => { // OAuth records without Anthropic's access-token prefix are no longer served natively: the request is - // refused with guidance and nothing reaches the model or the quota feed. + // refused with guidance before a model request is sent. await expectNonOatMainRefused('local-adapter-access') }, ) - async function publishFallbackUuid({ + async function persistFallbackUuid({ fallbackUuid, persistedUuid, bootstrapResponse, @@ -392,7 +375,6 @@ describe('quota header feed integration', () => { minimumRemaining: { five_hour: 10, seven_day: 20 }, failClosedOnUnknownQuota: true, }, - quotaHeaderFeed: { enabled: true }, accounts: [ { id: 'fallback-1', @@ -487,13 +469,6 @@ describe('quota header feed integration', () => { const response = await result.fetch(MESSAGES_URL, EMPTY_POST) await response.text() - const [published] = await waitForFeedEntries( - (entries) => - entries.some( - (entry: any) => entry.anthropic_account_uuid === fallbackUuid, - ), - 'a fallback UUID feed entry', - ) const persisted = await waitForAccountStorage( (candidate) => ( @@ -502,123 +477,33 @@ describe('quota header feed integration', () => { ) as any )?.anthropicAccountUuid === fallbackUuid, ) - return { published, persisted } + return persisted } - test('does not treat a complete but uncommitted .tmp lease as a published feed entry', async () => { - await useTempAccountFile(createFallbackStorage({ accounts: [] })) - const directory = process.env.OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR! - await mkdir(directory, { recursive: true }) - await writeFile( - join(directory, 'pretend.json.uncommitted.tmp'), - JSON.stringify({ - version: 3, - entries: { a: { account_ref: 'not-yet-published' } }, - }), - { mode: 0o600 }, - ) - expect(await readFeedEntries()).toEqual([]) - }) - - test('non-oat main feed leaves provider UUID null while retaining its quota slot', async () => { + test('refuses a main login with a non-OAuth access token', async () => { // OAuth records without Anthropic's access-token prefix are no longer served natively: the request is - // refused with guidance and nothing reaches the model or the quota feed. + // refused with guidance before a model request is sent. await expectNonOatMainRefused('main-access') }) - test('oat main feed preserves its bootstrapped Anthropic account UUID', async () => { - const mainAccountId = 'main-oat-slot' - const providerAccountUuid = '33333333-3333-3333-3333-333333333333' - await useTempAccountFile( - createFallbackStorage({ - mainAccountId, - quotaHeaderFeed: { enabled: true }, - accounts: [], - }), - { - access: 'sk-ant-oat-main-feed', - refresh: 'main-refresh', - expires: Date.now() + 100_000, - }, - ) - globalThis.fetch = mock( - withNativeTokenExchange((input: any) => { - const url = extractUrl(input) - if (url.includes('/claude_cli/bootstrap')) { - return Promise.resolve( - Response.json({ - oauth_account: { account_uuid: providerAccountUuid }, - }), - ) - } - return Promise.resolve( - new Response('{}', { - status: 200, - headers: { 'anthropic-ratelimit-unified-5h-utilization': '0.25' }, - }), - ) - }), - ) as unknown as typeof fetch - - const plugin = await getPlugin() - const result = await plugin.auth.loader( - () => - Promise.resolve({ - type: 'oauth' as const, - access: 'sk-ant-oat-main-feed', - refresh: 'main-refresh', - expires: Date.now() + 100_000, - }), - { models: {} }, - ) - const response = await result.fetch(MESSAGES_URL, EMPTY_POST) - await response.text() - - const [published] = await waitForFeedEntries( - (entries) => - entries.some( - (entry: any) => entry.anthropic_account_uuid === providerAccountUuid, - ), - 'a bootstrapped main UUID feed entry', - ) - // The native feed keys the main account by its stable Claude account - // UUID; the configured slot id stays a local name only. - expect(published).toEqual( - expect.objectContaining({ - account_ref: providerAccountUuid, - anthropic_account_uuid: providerAccountUuid, - }), - ) - expect((published as { account_ref?: unknown }).account_ref).not.toBe( - mainAccountId, - ) - }) - - test('main feed drops a cached oat UUID after the current credential becomes non-oat', async () => { + test('refuses the non-OAuth replacement token', async () => { // OAuth records without Anthropic's access-token prefix are no longer served natively: the request is - // refused with guidance and nothing reaches the model or the quota feed. - await expectNonOatMainRefused('main-feed-non-oat-after-rotation') + // refused with guidance before a model request is sent. + await expectNonOatMainRefused('main-non-oat-after-rotation') }) - test('fresh non-oat main install persists a quota slot and publishes no provider UUID', async () => { + test('refuses a fresh install with a non-OAuth access token', async () => { // OAuth records without Anthropic's access-token prefix are no longer served natively: the request is - // refused with guidance and nothing reaches the model or the quota feed. + // refused with guidance before a model request is sent. await expectNonOatMainRefused('fresh-main-non-oat') }) - test('publishes and persists a fallback Anthropic account UUID', async () => { + test('persists a fallback Anthropic account UUID', async () => { const fallbackUuid = '11111111-1111-1111-1111-111111111111' - const { published, persisted } = await publishFallbackUuid({ + const persisted = await persistFallbackUuid({ fallbackUuid, bootstrapResponse: { oauth_account: { account_uuid: fallbackUuid } }, }) - expect(published).toEqual( - expect.objectContaining({ - identity_source: 'account_ref', - account_ref: 'fallback-1', - anthropic_account_uuid: fallbackUuid, - }), - ) expect( ( persisted?.accounts.find( @@ -630,17 +515,11 @@ describe('quota header feed integration', () => { test('uses a persisted fallback Anthropic account UUID before bootstrap resolves it', async () => { const fallbackUuid = '22222222-2222-2222-2222-222222222222' - const { published, persisted } = await publishFallbackUuid({ + const persisted = await persistFallbackUuid({ fallbackUuid, persistedUuid: fallbackUuid as ProviderAccountUuid, bootstrapResponse: {}, }) - expect(published).toEqual( - expect.objectContaining({ - account_ref: 'fallback-1', - anthropic_account_uuid: fallbackUuid, - }), - ) expect( ( persisted?.accounts.find( @@ -650,9 +529,9 @@ describe('quota header feed integration', () => { ).toBe(fallbackUuid) }) - test('cache-seeded poll fields survive a later header harvest into the feed', async () => { + test('cache-seeded poll fields survive a later header harvest', async () => { const originalNow = Date.now - let clock = 1_000_000 + const clock = 1_000_000 Date.now = () => clock try { const mainAccountId = syntheticMainAccountUuid @@ -695,7 +574,6 @@ describe('quota header feed integration', () => { const storage = bindMainQuotaToAccount( createFallbackStorage({ mainAccountId, - quotaHeaderFeed: { enabled: true }, accounts: [], quota: { ...createFallbackStorage().quota, @@ -819,49 +697,9 @@ describe('quota header feed integration', () => { expect((await readAccountStorage())?.quota?.mainQuota?.scoped).toEqual( scoped, ) - // Storage acceptance does not wait for the detached feed write. - await waitForFeedEntries( - (entries) => - entries.some( - (entry) => - entry !== null && - typeof entry === 'object' && - 'observed_at_ms' in entry && - entry.observed_at_ms === clock, - ), - 'first header observation', - ) - clock += 1_000 - const secondResponse = await result.fetch(MESSAGES_URL, EMPTY_POST) - expect(secondResponse.status).toBe(200) - await secondResponse.text() - const secondEntry = ( - await waitForFeedEntries( - (entries) => - entries.length === 1 && - entries[0] !== null && - typeof entries[0] === 'object' && - 'observed_at_ms' in entries[0] && - entries[0].observed_at_ms === clock, - 'second header observation', - ) - )[0] - if ( - secondEntry === null || - typeof secondEntry !== 'object' || - !('quota' in secondEntry) - ) - throw new Error('Published feed entry has no quota') - const quota = secondEntry.quota - if (quota === null || typeof quota !== 'object') - throw new Error('Published quota is not an object') - expect('scoped' in quota ? quota.scoped : undefined).toEqual(scoped) - expect('extraUsage' in quota ? quota.extraUsage : undefined).toEqual( - extraUsage, - ) - expect('bindingWindow' in quota ? quota.bindingWindow : undefined).toBe( - 'claude-weekly-scoped-fable', - ) + expect(persisted?.scoped).toEqual(scoped) + expect(persisted?.extraUsage).toEqual(extraUsage) + expect(persisted?.bindingWindow).toBe('claude-weekly-scoped-fable') } finally { release.open() await Promise.allSettled([pollWriter, firstRequest]) @@ -998,7 +836,7 @@ describe('quota header feed integration', () => { } }) - test('stale fallback headers do not persist or publish after re-login', async () => { + test('stale fallback headers do not persist after re-login', async () => { const fallbackAccess = 'sk-ant-oat01-fallback-lineage-a-access' const fallbackCheckedAt = Date.now() const responseGate = bodyLifetime().gate() @@ -1014,7 +852,6 @@ describe('quota header feed integration', () => { await useTempAccountFile( bindPoolAccounts( createFallbackStorage({ - quotaHeaderFeed: { enabled: true }, quota: { ...createFallbackStorage().quota, checkIntervalMinutes: 60, @@ -1220,7 +1057,6 @@ describe('quota header feed integration', () => { ) expect(settledAccount?.quota?.five_hour?.usedPercent).toBe(60) expect(settledAccount?.quota?.seven_day?.usedPercent).toBe(70) - expect(await readFeedEntries()).toEqual([]) } finally { responseGate.open() await Promise.allSettled([responsePromise, fallbackResponse]) @@ -1444,7 +1280,7 @@ describe('quota header feed integration', () => { } }) - test('cross-account reload cannot retime a published main observation', async () => { + test('cross-account reload preserves the account-bound main quota timestamp', async () => { const originalNow = Date.now const requestCheckedAt = 1_000_000 Date.now = () => requestCheckedAt @@ -1455,7 +1291,6 @@ describe('quota header feed integration', () => { const storage = bindMainQuotaToAccount( createFallbackStorage({ mainAccountId: 'main-slot', - quotaHeaderFeed: { enabled: true }, accounts: [], quota: { ...createFallbackStorage().quota, @@ -1525,32 +1360,21 @@ describe('quota header feed integration', () => { const response = await result.fetch(MESSAGES_URL, EMPTY_POST) expect(response.status).toBe(200) await response.text() - const entries = await waitForFeedEntries( - (entries) => entries.length === 1, - 'one account-bound header observation', - ) - expect(entries[0]).toMatchObject({ - account_ref: accountIdentity, - anthropic_account_uuid: accountIdentity, - observed_at_ms: requestCheckedAt, - }) - expect(entries[0]).not.toMatchObject({ observed_at_ms: otherCheckedAt }) } finally { Date.now = originalNow } }) - test('withholds the main feed entry when bootstrap cannot identify the account', async () => { + test('refuses the model request when bootstrap cannot identify the main account', async () => { let modelCalls = 0 let bootstrapCalls = 0 await useTempAccountFile( createFallbackStorage({ mainAccountId: 'unknown-main', - quotaHeaderFeed: { enabled: true }, accounts: [], }), { - access: 'sk-ant-oat01-unknown-feed', + access: 'sk-ant-oat01-unknown-account', refresh: 'unknown-refresh', expires: Date.now() + 8 * 60 * 60_000, }, @@ -1561,7 +1385,7 @@ describe('quota header feed integration', () => { if (url.includes('/v1/oauth/token')) return Promise.resolve( Response.json({ - access_token: 'sk-ant-oat01-unknown-feed-successor', + access_token: 'sk-ant-oat01-unknown-account-successor', refresh_token: 'unknown-refresh-successor', expires_in: 28800, }), @@ -1585,7 +1409,7 @@ describe('quota header feed integration', () => { () => Promise.resolve({ type: 'oauth' as const, - access: 'sk-ant-oat01-unknown-feed', + access: 'sk-ant-oat01-unknown-account', refresh: 'unknown-refresh', expires: Date.now() + 100000, }), @@ -1596,18 +1420,17 @@ describe('quota header feed integration', () => { ) expect(bootstrapCalls).toBeGreaterThan(0) expect(modelCalls).toBe(0) - expect(await readFeedEntries()).toEqual([]) }) test('coalesces concurrent main identity resolution for the same token', async () => { // OAuth records without Anthropic's access-token prefix are no longer served natively: the request is - // refused with guidance and nothing reaches the model or the quota feed. + // refused with guidance before a model request is sent. await expectNonOatMainRefused('compat-main-access') }) test('aborts a request whose main identity becomes stale during resolution', async () => { // OAuth records without Anthropic's access-token prefix are no longer served natively: the request is - // refused with guidance and nothing reaches the model or the quota feed. + // refused with guidance before a model request is sent. await expectNonOatMainRefused('compat-a') }) }) @@ -1714,7 +1537,7 @@ describe('main identity boot order', () => { }) }) -describe('quota header feed extended integration', () => { +describe('quota persistence and admission', () => { const originalFetch = globalThis.fetch afterEach(async () => { @@ -1728,39 +1551,13 @@ describe('quota header feed extended integration', () => { deferModelRequestUntilTeardown, ) - test('disabled quota header feed publishes nothing by default or when explicitly false', async () => { - for (const enabled of [undefined, false]) { - const storage = createFallbackStorage({ - quotaHeaderFeed: enabled === undefined ? undefined : { enabled }, - accounts: [], - }) - const { response } = await loadMainAndFetch( - storage, - new Response('{}', { - status: 200, - headers: { 'anthropic-ratelimit-unified-5h-utilization': '0.25' }, - }), - ) - expect(await response.text()).toBe('{}') - expect(await readFeedEntries()).toEqual([]) - } - }) - - test('feed publication failure does not affect response, quota persistence, or sidebar update', async () => { - const feedDirectory = process.env.OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR! + test('response headers update persisted quota and the sidebar when polling is off', async () => { await useTempAccountFile( createFallbackStorage({ - quotaHeaderFeed: { enabled: true }, accounts: [], quota: { enabled: false }, }), ) - const feedParentFile = join(dirname(feedDirectory), 'feed-parent-file') - await Bun.write(feedParentFile, 'not a directory') - process.env.OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR = join( - feedParentFile, - 'quota-header-feed', - ) globalThis.fetch = mock( withNativeAdmission(() => Promise.resolve( @@ -1798,7 +1595,6 @@ describe('quota header feed extended integration', () => { (state) => state.main.quota?.five_hour?.usedPercent === 25, ) expect(sidebar.main.quota?.five_hour?.usedPercent).toBe(25) - expect(await readFeedEntries()).toEqual([]) }) test('sidebar quota refresh preserves rotated account metadata without acquiring credentials', async () => { @@ -1889,79 +1685,6 @@ describe('quota header feed extended integration', () => { await plugin.dispose?.() }) - test('deduplicates main feed observations across access-token rotation', async () => { - await useTempAccountFile( - createFallbackStorage({ - mainAccountId: 'stable-main-account', - quotaHeaderFeed: { enabled: true }, - accounts: [], - quota: { enabled: false }, - }), - { - access: 'sk-ant-oat01-main-access-a', - refresh: 'main-refresh', - expires: Date.now() + 100000, - }, - ) - let requestCount = 0 - globalThis.fetch = mock( - withNativeAdmission(() => { - requestCount += 1 - return Promise.resolve( - new Response('{}', { - status: 200, - headers: { - 'anthropic-ratelimit-unified-5h-utilization': String( - requestCount / 100, - ), - }, - }), - ) - }), - ) as unknown as typeof fetch - const plugin = await getPlugin() - - for (const access of [ - 'sk-ant-oat01-main-access-a', - 'sk-ant-oat01-main-access-b', - ]) { - // The second generation is a refresh of the same account in another - // OpenCode process, which rotates the pool's main access token. - if (access !== 'sk-ant-oat01-main-access-a') - await refreshPoolMainElsewhere({ - access, - refresh: `main-refresh-${access}`, - expires: Date.now() + 100000, - }) - const result = await plugin.auth.loader( - () => - Promise.resolve({ - type: 'oauth' as const, - access: 'sk-ant-oat01-main-access-a', - refresh: 'main-refresh', - expires: Date.now() + 100000, - }), - { models: {} }, - ) - const response = await result.fetch(MESSAGES_URL, EMPTY_POST) - await response.text() - } - - const entries = await waitForFeedEntries( - (candidate) => candidate.length === 1, - 'one published entry', - ) - expect(entries).toHaveLength(1) - expect(entries[0]).toEqual( - // Quota uses Anthropic's account UUID, not the local identifier used - // to keep the main login's device identity stable across token rotation. - expect.objectContaining({ - identity_source: 'account_ref', - account_ref: poolMainIdentity(), - }), - ) - }) - test('ordered fallback admission sends an unknown-quota OAuth account', async () => { await useTempAccountFile( createFallbackStorage({ @@ -2269,140 +1992,4 @@ describe('quota header feed extended integration', () => { expect(messageRequests).toHaveLength(1) expect(messageRequests[0]).toContain(MESSAGES_URL) }) - - test('selects account_ref for main and fallback without leaking credential_id', async () => { - const main = await loadMainAndFetch( - createFallbackStorage({ - quotaHeaderFeed: { enabled: true }, - accounts: [], - }), - new Response('{}', { - status: 200, - headers: { 'anthropic-ratelimit-unified-5h-utilization': '0.25' }, - }), - ) - await main.response.text() - const mainEntries = await waitForFeedEntries( - (entries) => entries.length === 1, - 'one main published entry', - ) - const mainAccountId = (await readAccountStorage())?.mainAccountId - expect(mainEntries[0]).toEqual( - expect.objectContaining({ - identity_source: 'account_ref', - account_ref: mainAccountId, - }), - ) - expect(mainEntries[0]).not.toHaveProperty('credential_id') - - const fallback = await loadMainAndFetch( - bindPoolAccounts( - createFallbackStorage({ - quotaHeaderFeed: { enabled: true }, - routing: { mode: 'fallback-first' }, - }), - ), - new Response('{}', { - status: 200, - headers: { 'anthropic-ratelimit-unified-5h-utilization': '0.25' }, - }), - ) - await fallback.response.text() - const fallbackEntry = ( - await waitForFeedEntries( - (entries) => - entries.length === 1 && - entries.some((entry: any) => entry.account_ref === 'fallback-1'), - 'one fallback-1 published entry', - ) - ).find((entry: any) => entry.identity_source === 'account_ref') as any - expect(fallbackEntry).toEqual( - expect.objectContaining({ - identity_source: 'account_ref', - account_ref: 'fallback-1', - }), - ) - expect(fallbackEntry).not.toHaveProperty('credential_id') - }) - - test('published configured account count uses live main OAuth plus every OAuth fallback and excludes API keys', async () => { - const { response } = await loadMainAndFetch( - createFallbackStorage({ - quotaHeaderFeed: { enabled: true }, - accounts: [ - { - id: 'disabled-oauth', - type: 'oauth', - access: 'sk-ant-oat01-disabled-access', - refresh: 'disabled-refresh', - expires: Date.now() + 8 * 60 * 60_000, - enabled: false, - }, - { - id: 'enabled-oauth', - type: 'oauth', - access: 'sk-ant-oat01-enabled-access', - refresh: 'enabled-refresh', - expires: Date.now() + 8 * 60 * 60_000, - enabled: true, - }, - { - id: 'api-key', - type: 'api', - apiKey: 'key', - baseURL: 'https://example.test', - }, - ] as AccountStorage['accounts'], - }), - new Response('{}', { - status: 200, - headers: { 'anthropic-ratelimit-unified-5h-utilization': '0.25' }, - }), - ) - expect(response.status).toBe(200) - await response.text() - const entries = await waitForFeedEntries( - (candidate) => candidate.length === 1, - 'one configured-account-count entry', - ) - expect(entries[0]).toEqual( - expect.objectContaining({ configured_account_count: 3 }), - ) - }) - - test('publishes genuine relay response headers through onResponseHeaders', async () => { - const { response } = await loadMainAndFetch( - createFallbackStorage({ - quotaHeaderFeed: { enabled: true }, - relay: { - enabled: true, - url: 'https://relay.example.test', - token: 'relay-token', - transport: 'http', - }, - }), - () => - new Response('{}', { - status: 200, - headers: { - 'anthropic-ratelimit-unified-5h-utilization': '0.5', - 'x-cortexkit-relay-optimistic': 'true', - }, - }), - { 'x-session-affinity': 'feed-relay-session' }, - ) - await response.text() - const entries = await waitForFeedEntries( - (candidate) => candidate.length === 1, - 'one relay published entry', - ) - expect(entries).toHaveLength(1) - expect(entries[0]).toEqual( - expect.objectContaining({ - quota: expect.objectContaining({ - five_hour: expect.objectContaining({ usedPercent: 50 }), - }), - }), - ) - }) }) diff --git a/packages/opencode/src/tests/quota-policy-and-killswitch.integration.test.ts b/packages/opencode/src/tests/quota-policy-and-killswitch.integration.test.ts index ac881ba20..e831c696c 100644 --- a/packages/opencode/src/tests/quota-policy-and-killswitch.integration.test.ts +++ b/packages/opencode/src/tests/quota-policy-and-killswitch.integration.test.ts @@ -31,13 +31,10 @@ import { useTempAccountFile as useTempAccountFileWithCtx, withNativeAdmission as withNativeAdmissionWithCtx, } from './support/opencode1-pool-fixture.ts' -import { - readFeedEntries, - waitForFeedEntries as waitForFeedEntriesWithCtx, - waitForLogRecord as waitForLogRecordWithCtx, -} from './support/opencode1-quota-feed.ts' +import { waitForLogRecord as waitForLogRecordWithCtx } from './support/opencode1-quota.ts' import { readAccountStorage as readAccountStorageWithCtx, + waitForAccountStorage, waitForSidebarState as waitForSidebarStateWithCtx, } from './support/opencode1-state-observers.ts' import type { PluginRuntimeOverrides } from './support/opencode1-test-context.ts' @@ -106,12 +103,6 @@ function waitForSidebarState( function readAccountStorage(): Promise { return readAccountStorageWithCtx(testContext) } -function waitForFeedEntries( - predicate: (entries: Awaited>) => boolean, - description: string, -) { - return waitForFeedEntriesWithCtx(testContext, predicate, description) -} function waitForLogRecord( records: LogTestRecord[], predicate: (record: LogTestRecord) => boolean, @@ -637,14 +628,14 @@ describe('killswitch fetch gate', () => { }) }) -describe('quota header feed integration', () => { +describe('main account quota and identity', () => { const originalFetch = globalThis.fetch afterEach(() => { globalThis.fetch = originalFetch }) - test('main account replacement fences quota, backoff, and feed identity', async () => { + test('main account replacement fences quota and backoff by account identity', async () => { const uuidA = syntheticMainAccountUuid const uuidB = syntheticFallbackAccountUuid(99) const accessA = 'sk-ant-oat01-token-a' @@ -659,7 +650,6 @@ describe('quota header feed integration', () => { createFallbackStorage({ mainAccountId: 'main-slot', accounts: [], - quotaHeaderFeed: { enabled: true }, quota: { enabled: true, checkIntervalMinutes: 5, @@ -760,16 +750,11 @@ describe('quota header feed integration', () => { const response = await modelRequest expect(response.status).toBe(200) await response.text() - const entries = await waitForFeedEntries( - (entries) => - entries.some( - (entry) => - entry !== null && - typeof entry === 'object' && - 'anthropic_account_uuid' in entry && - entry.anthropic_account_uuid === uuidB, - ), - 'replacement account quota feed', + await waitForAccountStorage( + testContext, + (storage) => + storage?.quota?.mainQuota?.accountIdentity === uuidB && + storage.quota.mainQuota.five_hour?.usedPercent === 20, ) expect(quotaManager.getMain(uuidA)).toBeNull() expect(quotaManager.getMain(uuidB)?.quota.accountIdentity).toBe(uuidB) @@ -781,15 +766,6 @@ describe('quota header feed integration', () => { expect( (await readAccountStorage())?.quota?.mainLastQuotaApiError, ).toBeUndefined() - expect(entries).toContainEqual( - expect.objectContaining({ - identity_source: 'account_ref', - anthropic_account_uuid: uuidB, - }), - ) - expect(await readFeedEntries()).not.toContainEqual( - expect.objectContaining({ anthropic_account_uuid: uuidA }), - ) } finally { releaseOldPoll.open() await Promise.allSettled([priorPoll, modelRequest]) @@ -1354,7 +1330,6 @@ describe('quota header feed integration', () => { createFallbackStorage({ mainAccountId: 'main-slot', accounts: [], - quotaHeaderFeed: { enabled: true }, quota: { enabled: true, checkIntervalMinutes: 5, @@ -1461,16 +1436,11 @@ describe('quota header feed integration', () => { const currentResponse = await result.fetch(MESSAGES_URL, EMPTY_POST) expect(currentResponse.status).toBe(200) await currentResponse.text() - await waitForFeedEntries( - (entries) => - entries.some( - (entry) => - entry !== null && - typeof entry === 'object' && - 'anthropic_account_uuid' in entry && - entry.anthropic_account_uuid === uuidB, - ), - 'new account observation before old response release', + await waitForAccountStorage( + testContext, + (storage) => + storage?.quota?.mainQuota?.accountIdentity === uuidB && + storage.quota.mainQuota.five_hour?.usedPercent === 60, ) expect( getPluginTestHandles(plugin).quotaManager.getMain(uuidB)?.quota @@ -1485,9 +1455,6 @@ describe('quota header feed integration', () => { record.message === 'discarded stale main quota headers', 'old account header discard', ) - expect(await readFeedEntries()).not.toContainEqual( - expect.objectContaining({ anthropic_account_uuid: uuidA }), - ) expect( getPluginTestHandles(plugin).quotaManager.getMain(uuidA), ).toBeNull() diff --git a/packages/opencode/src/tests/quota-sweep.test.ts b/packages/opencode/src/tests/quota-sweep.test.ts index 2bf4814ce..1bcb22675 100644 --- a/packages/opencode/src/tests/quota-sweep.test.ts +++ b/packages/opencode/src/tests/quota-sweep.test.ts @@ -70,7 +70,6 @@ const envKeys = [ 'OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE', 'OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE', 'OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR', - 'OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR', 'OPENCODE_ANTHROPIC_AUTH_RPC_DIR', 'OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION', 'OPENCODE_AUTH_CONTENT', diff --git a/packages/opencode/src/tests/relay-store-location.test.ts b/packages/opencode/src/tests/relay-store-location.test.ts index c51cbed21..2c85f1a35 100644 --- a/packages/opencode/src/tests/relay-store-location.test.ts +++ b/packages/opencode/src/tests/relay-store-location.test.ts @@ -29,7 +29,6 @@ const envKeys = [ 'OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE', 'OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE', 'OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR', - 'OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR', 'OPENCODE_ANTHROPIC_AUTH_RPC_DIR', 'CLAUDE_CONFIG_DIR', 'OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION', diff --git a/packages/opencode/src/tests/routing-and-sticky.integration.test.ts b/packages/opencode/src/tests/routing-and-sticky.integration.test.ts index de6486eec..1f1c22960 100644 --- a/packages/opencode/src/tests/routing-and-sticky.integration.test.ts +++ b/packages/opencode/src/tests/routing-and-sticky.integration.test.ts @@ -19,7 +19,7 @@ import { withNativeAdmission as withNativeAdmissionWithCtx, withNativeBootstrap as withNativeBootstrapWithCtx, } from './support/opencode1-pool-fixture.ts' -import { expectUnknownQuotaAdmissionBlocked as expectUnknownQuotaAdmissionBlockedWithCtx } from './support/opencode1-quota-feed.ts' +import { expectUnknownQuotaAdmissionBlocked as expectUnknownQuotaAdmissionBlockedWithCtx } from './support/opencode1-quota.ts' import { readAccountStorage as readAccountStorageWithCtx, waitForSidebarState as waitForSidebarStateWithCtx, diff --git a/packages/opencode/src/tests/rpc-multi-project.test.ts b/packages/opencode/src/tests/rpc-multi-project.test.ts index 129b3fdf7..126784b6b 100644 --- a/packages/opencode/src/tests/rpc-multi-project.test.ts +++ b/packages/opencode/src/tests/rpc-multi-project.test.ts @@ -2,10 +2,7 @@ import { describe, expect, mock } from 'bun:test' import { mkdtemp, readFile, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { - createEmptyStorage, - QuotaHeaderFeedRegistry, -} from '@cortexkit/anthropic-auth-core' +import { createEmptyStorage } from '@cortexkit/anthropic-auth-core' import type { Hooks, PluginInput } from '@opencode-ai/plugin' import { createOpencodeClient } from '@opencode-ai/sdk' import { $ } from 'bun' @@ -41,7 +38,6 @@ const envKeys = [ 'OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE', 'OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE', 'OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR', - 'OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR', 'OPENCODE_ANTHROPIC_AUTH_RPC_DIR', 'CLAUDE_CONFIG_DIR', 'OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION', @@ -241,43 +237,6 @@ async function migratedProjects( } describe('RPC server lifecycle', () => { - test('dispose stops and removes its server when feed cleanup rejects', async () => { - // The migrated settings enable the quota header feed, so the plugin builds - // the registry whose disposal is made to fail here. - await migratedProjects({ - ...createEmptyStorage(), - quotaHeaderFeed: { enabled: true }, - }) - const originalDispose = QuotaHeaderFeedRegistry.prototype.dispose - let feedDisposals = 0 - QuotaHeaderFeedRegistry.prototype.dispose = async () => { - feedDisposals++ - throw new Error('feed disposal failed') - } - try { - const directory = join(testRoot, 'project') - const plugin = await getPlugin(directory) - const rpcDir = getRpcDir(directory) - const entry = await discoverPortFile(rpcDir) - - expect(entry).not.toBeNull() - await plugin.dispose?.() - - // Quota-feed disposal threw as configured. The assertions below prove - // that this failure did not prevent RPC server cleanup. - expect(feedDisposals).toBe(1) - expect(await discoverPortFile(rpcDir)).toBeNull() - expect( - (globalThis as RpcGlobal).__anthropicAuthRpcServers?.get(rpcDir), - ).toBeUndefined() - await expect( - fetch(`http://127.0.0.1:${entry?.port}/health`), - ).rejects.toThrow() - } finally { - QuotaHeaderFeedRegistry.prototype.dispose = originalDispose - } - }) - test('keeps RPC servers live for distinct project directories', async () => { await migratedProjects() const directoryA = join(testRoot, 'project-a') diff --git a/packages/opencode/src/tests/scoped-custody-serving.test.ts b/packages/opencode/src/tests/scoped-custody-serving.test.ts index 75ba5ae20..7c725c27c 100644 --- a/packages/opencode/src/tests/scoped-custody-serving.test.ts +++ b/packages/opencode/src/tests/scoped-custody-serving.test.ts @@ -37,7 +37,6 @@ const bodyEnvKeys = [ 'OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE', 'OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE', 'OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR', - 'OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR', 'OPENCODE_ANTHROPIC_AUTH_RPC_DIR', 'CLAUDE_CONFIG_DIR', 'OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION', diff --git a/packages/opencode/src/tests/scoped-main-quota-persistence.test.ts b/packages/opencode/src/tests/scoped-main-quota-persistence.test.ts index a5b5d2418..2b6769578 100644 --- a/packages/opencode/src/tests/scoped-main-quota-persistence.test.ts +++ b/packages/opencode/src/tests/scoped-main-quota-persistence.test.ts @@ -32,7 +32,6 @@ const bodyEnvKeys = [ 'OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE', 'OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE', 'OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR', - 'OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR', 'OPENCODE_ANTHROPIC_AUTH_RPC_DIR', 'CLAUDE_CONFIG_DIR', 'OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION', diff --git a/packages/opencode/src/tests/settings-install-paths.test.ts b/packages/opencode/src/tests/settings-install-paths.test.ts index 14261d994..13a92a699 100644 --- a/packages/opencode/src/tests/settings-install-paths.test.ts +++ b/packages/opencode/src/tests/settings-install-paths.test.ts @@ -103,7 +103,6 @@ async function fixture(override: Override, named = false) { root, 'sidebar-state.json', ), - OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR: join(root, 'feed'), }) if (override === 'account') process.env.OPENCODE_ANTHROPIC_AUTH_FILE = join( diff --git a/packages/opencode/src/tests/settings-snapshot-fixture.ts b/packages/opencode/src/tests/settings-snapshot-fixture.ts index fe0d18497..dcd544d92 100644 --- a/packages/opencode/src/tests/settings-snapshot-fixture.ts +++ b/packages/opencode/src/tests/settings-snapshot-fixture.ts @@ -1,9 +1,35 @@ import type * as core from '@cortexkit/anthropic-auth-core' +import releaseSnapshots from './fixtures/settings-2.11.2.json' import { nondefaultSettings } from './opencode2-settings-readers' export const snapshotTime = 1_900_000_000_000 export const snapshotModel = 'claude-opus-5-5' +export function expectedReleaseSnapshot( + host: 1 | 2, + sample: 'explicit' | 'absent', +) { + const released = releaseSnapshots[`oc${host}-${sample}`] + // The feed setting is gone. The wire reader in both snapshots is OpenCode 2's. + const { quota_header_feed_enabled: _removed, ...outputs } = + released.readers.outputs + // The frozen OpenCode 1 sample already has the five-minute request bytes and + // CacheKeep body sizes that OpenCode 2 should now produce with no override. + const short = releaseSnapshots['oc1-absent'] + return { + ...released, + readers: { + outputs, + wire: { ...released.readers.wire, cache1hEnabled: sample === 'explicit' }, + }, + ...(host === 2 && + sample === 'absent' && { + request: { ...released.request, body: short.request.body }, + logs: short.logs, + }), + } +} + export function snapshotSettings(absent: boolean): core.AccountStorage { const settings: core.AccountStorage = { version: 1, diff --git a/packages/opencode/src/tests/settings-three-way.test.ts b/packages/opencode/src/tests/settings-three-way.test.ts index d3f5df3af..dc81b1ec7 100644 --- a/packages/opencode/src/tests/settings-three-way.test.ts +++ b/packages/opencode/src/tests/settings-three-way.test.ts @@ -36,7 +36,7 @@ function snapshotFor( } } -test('createNativeWirePolicy transformOptions reads all six cache inputs and preserves excluded agents', () => { +test('OpenCode 2 defaults to five-minute caching and preserves explicit values and excluded agents', () => { const policy = createNativeWirePolicy() const context = { attemptId: 'three-way-cache', @@ -44,13 +44,17 @@ test('createNativeWirePolicy transformOptions reads all six cache inputs and pre agent: 'build', correlation: {}, } as NativeAnthropicRequestContext - expect( - inputs.map( - (value) => - policy.requestOptions(context, snapshotFor('claudeCache', value)) - .cache1hEnabled, - ), - ).toEqual(enabledByDefault) + for (const agent of ['build', 'summary', 'prime']) { + expect( + inputs.map( + (value) => + policy.requestOptions( + { ...context, agent }, + snapshotFor('claudeCache', value), + ).cache1hEnabled, + ), + ).toEqual([true, false, false, true, false, false]) + } for (const agent of ['compaction', 'title']) { expect( inputs.map( diff --git a/packages/opencode/src/tests/setup-command.test.ts b/packages/opencode/src/tests/setup-command.test.ts index e9fd9901b..440171786 100644 --- a/packages/opencode/src/tests/setup-command.test.ts +++ b/packages/opencode/src/tests/setup-command.test.ts @@ -2508,7 +2508,6 @@ async function sendSetupOc1( f.env.HOME!, 'sidebar.json', ), - OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR: join(f.env.HOME!, 'quota-feed'), OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR: join( f.env.HOME!, 'cachekeep', diff --git a/packages/opencode/src/tests/state-layout-host-wiring.test.ts b/packages/opencode/src/tests/state-layout-host-wiring.test.ts index 0f5366a95..1c8f0f02e 100644 --- a/packages/opencode/src/tests/state-layout-host-wiring.test.ts +++ b/packages/opencode/src/tests/state-layout-host-wiring.test.ts @@ -58,7 +58,6 @@ const ENV_KEYS = [ 'OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_ENROLLMENT_FILE', 'OPENCODE_TUI_PREFERENCES_FILE', 'OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR', - 'OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR', 'OPENCODE_ANTHROPIC_AUTH_RPC_DIR', 'OPENCODE_AUTH_CONTENT', ] as const @@ -214,7 +213,6 @@ async function startHost(host: 'opencode1' | 'opencode2', m: Machine) { m.root, 'registry', ) - process.env.OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR = join(m.root, 'feed') process.env.OPENCODE_ANTHROPIC_AUTH_RPC_DIR = join(m.root, 'rpc') const plugin = await AnthropicAuthPlugin( { diff --git a/packages/opencode/src/tests/support/opencode1-pool-fixture.ts b/packages/opencode/src/tests/support/opencode1-pool-fixture.ts index 745b20667..532dc91fe 100644 --- a/packages/opencode/src/tests/support/opencode1-pool-fixture.ts +++ b/packages/opencode/src/tests/support/opencode1-pool-fixture.ts @@ -953,10 +953,6 @@ export async function useUnmigratedAccountFile( root, 'cachekeep-registry', ) - process.env.OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR = join( - root, - 'quota-header-feed', - ) process.env.OPENCODE_ANTHROPIC_AUTH_RPC_DIR = join(root, 'rpc') await writeLegacyAccountFiles( process.env.OPENCODE_ANTHROPIC_AUTH_FILE, diff --git a/packages/opencode/src/tests/support/opencode1-quota-feed.ts b/packages/opencode/src/tests/support/opencode1-quota.ts similarity index 64% rename from packages/opencode/src/tests/support/opencode1-quota-feed.ts rename to packages/opencode/src/tests/support/opencode1-quota.ts index 75bf1ace4..72a76e60e 100644 --- a/packages/opencode/src/tests/support/opencode1-quota-feed.ts +++ b/packages/opencode/src/tests/support/opencode1-quota.ts @@ -1,6 +1,4 @@ import { expect, mock } from 'bun:test' -import { readdir, readFile } from 'node:fs/promises' -import { join } from 'node:path' import type { AccountStorage, LogTestRecord, @@ -29,52 +27,6 @@ import { untilStateOrTestEnd, } from './opencode1-test-context.ts' -export async function readFeedEntries() { - const directory = process.env.OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR - if (!directory) return [] - try { - // The producer writes a complete .tmp before renaming it into a committed - // .json lease. Match the real consumer: transient files are not published. - const files = (await readdir(directory)).filter((name) => - name.endsWith('.json'), - ) - const records = await Promise.all( - files.map(async (file) => - JSON.parse(await readFile(join(directory, file), 'utf8')), - ), - ) - return records.flatMap((record) => Object.values(record.entries ?? {})) - } catch { - return [] - } -} - -/** - * Wait for the committed feed leases to satisfy `predicate`, re-reading them - * until they match or the test ends instead of polling to a fixed wall-clock - * deadline. - */ -export async function waitForFeedEntries( - ctx: Opencode1TestContext, - predicate: (entries: Awaited>) => boolean, - description: string, -) { - const changes = untilStateOrTestEnd(ctx, STATE_READ_PAUSE_MS) - try { - while (!changes.ended) { - await changes.next() - const entries = await readFeedEntries() - if (predicate(entries)) return entries - } - } finally { - changes.close() - } - const entries = await readFeedEntries() - throw new Error( - `Quota header feed did not match ${description}: ${JSON.stringify(entries)}`, - ) -} - /** * Wait for a log record matching `predicate`, re-checking the test's sink * until one arrives or the test ends rather than to a fixed wall-clock @@ -102,39 +54,6 @@ export async function waitForLogRecord( } } -export async function loadMainAndFetch( - ctx: Opencode1TestContext, - storage: AccountStorage, - response: Response | (() => Response), - requestHeaders?: Record, -) { - await useTempAccountFile(ctx, storage) - globalThis.fetch = mock( - withNativeAdmission(ctx, () => - Promise.resolve( - typeof response === 'function' ? response() : response.clone(), - ), - ), - ) as unknown as typeof fetch - const plugin = await getPlugin(ctx) - const result = await plugin.auth.loader( - () => - Promise.resolve({ - type: 'oauth', - access: 'sk-ant-oat01-main-access', - refresh: 'main-refresh', - expires: Date.now() + 100000, - }), - { models: {} }, - ) - const fetched = await result.fetch(MESSAGES_URL, { - method: 'POST', - headers: requestHeaders, - body: JSON.stringify({ model: 'claude-sonnet-4-5', messages: [] }), - }) - return { plugin, response: fetched } -} - export { extractUrl, MESSAGES_URL, @@ -152,11 +71,11 @@ export async function expectNonOatMainRefused( ctx: Opencode1TestContext, access: string, ) { - await useTempAccountFile( - ctx, - createFallbackStorage({ accounts: [], quotaHeaderFeed: { enabled: true } }), - { access, refresh: `refresh-${access}`, expires: Date.now() + 100_000 }, - ) + await useTempAccountFile(ctx, createFallbackStorage({ accounts: [] }), { + access, + refresh: `refresh-${access}`, + expires: Date.now() + 100_000, + }) const modelRequests: string[] = [] globalThis.fetch = mock( withNativeTokenExchange(ctx, (input: Parameters[0]) => { @@ -189,7 +108,6 @@ export async function expectNonOatMainRefused( }), ).rejects.toThrow(/API key/i) expect(modelRequests).toEqual([]) - expect(await readFeedEntries()).toEqual([]) const pool = ctx.migratedPool if (!pool) throw new Error('Expected migrated pool for non-OAT refusal check') const runtime = createNativeAccountRuntime({ diff --git a/packages/opencode/src/tests/support/opencode1-state-observers.ts b/packages/opencode/src/tests/support/opencode1-state-observers.ts index c1a5433f1..fb45785ff 100644 --- a/packages/opencode/src/tests/support/opencode1-state-observers.ts +++ b/packages/opencode/src/tests/support/opencode1-state-observers.ts @@ -129,7 +129,7 @@ export async function waitForAccountStorage( throw new Error(`Account storage did not match: ${JSON.stringify(storage)}`) } -/** Wait on pool file changes, not a cache/feed event, when asserting disk quota. */ +/** Wait on pool file changes, not an in-memory cache event, when asserting disk quota. */ export async function waitForNativePoolQuota( ctx: Opencode1TestContext, routeId: string, diff --git a/packages/opencode/src/tests/support/opencode1-test-context.ts b/packages/opencode/src/tests/support/opencode1-test-context.ts index 478e1ab8b..d3ab643e7 100644 --- a/packages/opencode/src/tests/support/opencode1-test-context.ts +++ b/packages/opencode/src/tests/support/opencode1-test-context.ts @@ -49,7 +49,6 @@ export const nativeEnvKeys = [ 'OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE', 'OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE', 'OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR', - 'OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR', 'OPENCODE_ANTHROPIC_AUTH_RPC_DIR', 'CLAUDE_CONFIG_DIR', 'OPENCODE_AUTH_CONTENT', diff --git a/packages/opencode/src/v2/wire.ts b/packages/opencode/src/v2/wire.ts index 8329a57f1..ac7899d64 100644 --- a/packages/opencode/src/v2/wire.ts +++ b/packages/opencode/src/v2/wire.ts @@ -162,7 +162,7 @@ export function createNativeWirePolicy( input.agent !== 'title' && readThreeWayBoolean( snapshot.policyStorage.claudeCache?.enabled, - true, + false, ), cache1hMode: snapshot.policyStorage.claudeCache?.mode ?? 'explicit', fastModeEnabled: snapshot.policyStorage.claudeFast?.enabled === true, diff --git a/packages/pi/src/tests/settings-read.test.ts b/packages/pi/src/tests/settings-read.test.ts index ccdf13bbe..099bcc03a 100644 --- a/packages/pi/src/tests/settings-read.test.ts +++ b/packages/pi/src/tests/settings-read.test.ts @@ -1132,7 +1132,10 @@ for (const mode of ['local', 'claustrum'] as const) expect(await (await native.service()).getSettingsPath()).toBe(file) expect(await fs.exists(`${file}.moved`)).toBe(true) expect(await fs.readFile(selected.config, 'utf8')).toBe(sourceBytes) - const expected = JSON.stringify(releaseSnapshots[fixture]) + const released = releaseSnapshots[fixture] + const { quota_header_feed_enabled: _removed, ...readers } = + released.readers + const expected = JSON.stringify({ ...released, readers }) for (const [phase, storage] of [ ['before', before], ['after', after], @@ -1201,7 +1204,6 @@ function readerOutputs(storage: core.AccountStorage) { ).scoped, quota_fail_closed_on_unknown_quota: core.failClosedOnUnknownQuota(storage), quota_show_toasts: storage.quota?.showToasts === true, - quota_header_feed_enabled: storage.quotaHeaderFeed?.enabled === true, killswitch_enabled: core.isKillswitchEnabled(storage), killswitch_default_five_hour: main.five_hour, killswitch_default_seven_day: main.seven_day, @@ -1257,7 +1259,6 @@ for (const mode of ['local', 'claustrum'] as const) failClosedOnUnknownQuota: false, showToasts: true, }, - quotaHeaderFeed: { enabled: true }, killswitch: { enabled: true, main: { five_hour: 9, seven_day: 21, scoped: 3 }, diff --git a/packages/pi/src/tests/settings-snapshot-fixture.ts b/packages/pi/src/tests/settings-snapshot-fixture.ts index 74c2455a4..34345d33d 100644 --- a/packages/pi/src/tests/settings-snapshot-fixture.ts +++ b/packages/pi/src/tests/settings-snapshot-fixture.ts @@ -33,7 +33,6 @@ export function snapshotSettings(absent: boolean): core.AccountStorage { failClosedOnUnknownQuota: false, showToasts: true, }, - quotaHeaderFeed: { enabled: true }, killswitch: { enabled: true, main: { five_hour: 9, seven_day: 11, scoped: 3 }, @@ -117,7 +116,6 @@ export function snapshotReaderOutputs(storage: core.AccountStorage) { ).scoped, quota_fail_closed_on_unknown_quota: core.failClosedOnUnknownQuota(storage), quota_show_toasts: storage.quota?.showToasts === true, - quota_header_feed_enabled: storage.quotaHeaderFeed?.enabled === true, killswitch_enabled: core.isKillswitchEnabled(storage), killswitch_default_five_hour: main.five_hour, killswitch_default_seven_day: main.seven_day, From 15352e78c7172531beebb1c6737bdb101abf933c Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:10:53 +0100 Subject: [PATCH 11/27] mason: align strict test expectations with host parity Prime adds one startup timer even when disabled; quota-sweep fixtures still exercise the original poll and dispatch assertions. Keep-warm-off continues to report exact cache touches without forwarding usage to price a nonexistent target. The paid fallback sends no Claude Code betas, while the Pi settings test still observes both OAuth fast-mode states. Archive comparisons account for the first diagnostics predecessor, and fork prefix comparisons mask only the non-cache billing text and diagnostics. --- .../core/src/tests/prompt-cache-snapshot.ts | 16 +++++++ .../src/tests/account-command.test.ts | 4 +- .../src/tests/add-account-flows.test.ts | 7 ++- .../src/tests/cache-policy-reports.test.ts | 23 ++-------- .../src/tests/dispose-cleanup.test.ts | 39 +++++++--------- packages/opencode/src/tests/info-logs.test.ts | 8 ++-- .../src/tests/opencode1-settings-read.test.ts | 10 +++-- .../src/tests/opencode2-settings-read.test.ts | 10 +++-- ...-policy-and-killswitch.integration.test.ts | 5 +-- .../opencode/src/tests/quota-sweep.test.ts | 19 ++++---- .../src/tests/settings-snapshot-fixture.ts | 26 ----------- .../src/tests/settings-snapshot-parity.ts | 44 +++++++++++++++++++ packages/pi/src/tests/scoped-stream.test.ts | 8 +++- packages/pi/src/tests/settings-read.test.ts | 32 +++++++++++--- 14 files changed, 147 insertions(+), 104 deletions(-) create mode 100644 packages/core/src/tests/prompt-cache-snapshot.ts create mode 100644 packages/opencode/src/tests/settings-snapshot-parity.ts diff --git a/packages/core/src/tests/prompt-cache-snapshot.ts b/packages/core/src/tests/prompt-cache-snapshot.ts new file mode 100644 index 000000000..81cdf3f47 --- /dev/null +++ b/packages/core/src/tests/prompt-cache-snapshot.ts @@ -0,0 +1,16 @@ +export function promptCacheSnapshot(body: Record): string { + // The billing header carries a request signature and turn lineage, and the + // top-level diagnostics ID links provider replies. Neither is part of the + // prompt-cache prefix; forks deliberately don't join those chains. + const { diagnostics: _diagnostics, ...prefix } = body + if (Array.isArray(prefix.system)) { + prefix.system = prefix.system.map((block) => + block?.type === 'text' && + typeof block?.text === 'string' && + block.text.startsWith('x-anthropic-billing-header:') + ? { ...block, text: 'x-anthropic-billing-header: MASKED' } + : block, + ) + } + return JSON.stringify(prefix) +} diff --git a/packages/opencode/src/tests/account-command.test.ts b/packages/opencode/src/tests/account-command.test.ts index 0d2f904fa..dd56cda1e 100644 --- a/packages/opencode/src/tests/account-command.test.ts +++ b/packages/opencode/src/tests/account-command.test.ts @@ -1347,7 +1347,8 @@ describe('account command INFO logs (via plugin)', () => { test('does not retain a background interval unless the helper opts in', async () => { const fixture = await migrate(baseStorage()) await fixture.getPlugin() - expect(timerTracking.disabledIntervalCalls).toBe(1) + // Prime registers at startup alongside fallback refresh, even when off. + expect(timerTracking.disabledIntervalCalls).toBe(2) expect(activeIntervals.size).toBe(0) await timerTracking.withTrackedInterval(async () => { @@ -1355,6 +1356,7 @@ describe('account command INFO logs (via plugin)', () => { setInterval: trackedSetInterval, clearInterval: trackedClearInterval, }) + // The second instance shares the Prime timer; only its fallback refresh is new. expect(activeIntervals.size).toBe(1) }) expect(activeIntervals.size).toBe(0) diff --git a/packages/opencode/src/tests/add-account-flows.test.ts b/packages/opencode/src/tests/add-account-flows.test.ts index 3061439b0..5cbfd1b21 100644 --- a/packages/opencode/src/tests/add-account-flows.test.ts +++ b/packages/opencode/src/tests/add-account-flows.test.ts @@ -428,7 +428,8 @@ pluginTest( 'does not retain a background interval unless the helper opts in', async (fixture) => { await fixture.getPlugin() - expect(timerTracking.disabledIntervalCalls).toBe(1) + // Prime registers at startup alongside fallback refresh, even when off. + expect(timerTracking.disabledIntervalCalls).toBe(2) expect(activeIntervals.size).toBe(0) let thrown: unknown @@ -438,6 +439,7 @@ pluginTest( setInterval: trackedSetInterval, clearInterval: trackedClearInterval, }) + // The second instance shares the Prime timer; only its fallback refresh is new. expect(activeIntervals.size).toBe(1) throw new Error('forced timer assertion failure') }) @@ -454,7 +456,8 @@ pluginTest( 'partial timer overrides retain disabled interval defaults', async (fixture) => { await fixture.getPlugin({ clearInterval: trackedClearInterval }) - expect(timerTracking.disabledIntervalCalls).toBe(1) + // The interval mock still intercepts both fallback refresh and Prime. + expect(timerTracking.disabledIntervalCalls).toBe(2) expect(activeIntervals.size).toBe(0) }, ) diff --git a/packages/opencode/src/tests/cache-policy-reports.test.ts b/packages/opencode/src/tests/cache-policy-reports.test.ts index fe58c378a..02be736f3 100644 --- a/packages/opencode/src/tests/cache-policy-reports.test.ts +++ b/packages/opencode/src/tests/cache-policy-reports.test.ts @@ -339,26 +339,9 @@ describe('OC1 final response cache reports', () => { ]) expect(reports[0]!.at as number).toBeGreaterThanOrEqual(before) expect(reports[0]!.at as number).toBeLessThanOrEqual(Date.now()) - expect(usage).toHaveBeenCalledWith( - 'ses_oc1_reports', - expect.any(String), - { - cache_read_input_tokens: 9, - cache_creation_input_tokens: 5, - input_tokens: 10_000, - }, - ) - if (ttl === 'short') - expect(usage).toHaveBeenCalledWith( - 'ses_oc1_reports', - expect.any(String), - { - cache_read_input_tokens: 9, - cache_creation_input_tokens: 6, - input_tokens: 10_000, - output_tokens: 1, - }, - ) + // Cache touches are reported even when the keeper is off; usage is + // delivered to CacheKeep only to price an accepted warm target. + expect(usage).toHaveBeenCalledTimes(0) }, ) oc1Test.each(['unmarked', 'ttl-child'] as const)( diff --git a/packages/opencode/src/tests/dispose-cleanup.test.ts b/packages/opencode/src/tests/dispose-cleanup.test.ts index 65e10d58a..4ccd2f145 100644 --- a/packages/opencode/src/tests/dispose-cleanup.test.ts +++ b/packages/opencode/src/tests/dispose-cleanup.test.ts @@ -241,40 +241,31 @@ async function migratedPool(options: { hostAuth?: Record }) { } describe('dispose stops per-instance background services', () => { - // The plugin starts the fallback-account refresh interval after loading the - // shared native account pool. Injected timer functions let this test verify - // that dispose clears the same interval handle. + // Use injected timers to verify dispose clears the actual handles. lifetimes.test( - 'dispose clears the native fallback refresh interval it started', + 'dispose clears the native fallback refresh and Prime intervals it started', async () => { const pool = await migratedPool({}) - // With the disabled interval mock, count the intervals this instance - // schedules. The default overrides from timer-tracking disable - // CacheKeep's aggregate refresh, so the fallback-account refresh is the - // only interval started here. + // The fixture disables CacheKeep's aggregate refresh. Construction + // schedules fallback refresh and Prime, even while Prime is off. const counted = await pool.getPlugin() - expect(timerTracking.disabledIntervalCalls).toBe(1) + expect(timerTracking.disabledIntervalCalls).toBe(2) await pool.dispose(counted) // Disposing must not schedule any additional intervals for this instance. - expect(timerTracking.disabledIntervalCalls).toBe(1) + expect(timerTracking.disabledIntervalCalls).toBe(2) - // With real tracked intervals, the handle construction created is the - // one dispose clears. The tracked clear removes only handles passed to it. const tracked = await pool.getPlugin({ setInterval: timerTracking.trackedSetInterval, clearInterval: timerTracking.trackedClearInterval, }) - expect(activeIntervals.size).toBe(1) - const [fallbackRefresh] = activeIntervals - if (fallbackRefresh === undefined) - throw new Error('Plugin started no tracked interval') - // Nothing has cleared the construction interval before dispose. - expect(activeIntervals.has(fallbackRefresh)).toBe(true) + expect(activeIntervals.size).toBe(2) + const handles = [...activeIntervals] await pool.dispose(tracked) - expect(activeIntervals.has(fallbackRefresh)).toBe(false) + for (const handle of handles) + expect(activeIntervals.has(handle)).toBe(false) expect(activeIntervals.size).toBe(0) }, ) @@ -312,14 +303,14 @@ describe('dispose stops per-instance background services', () => { }) lifetimes.test( - 'dispose clears tracked fallback and main refresh intervals', + 'dispose clears tracked fallback refresh, main refresh and Prime intervals', async () => { const pool = await migratedPool({ hostAuth: syntheticHostAuth() }) const plugin = await pool.getPlugin({ setInterval: timerTracking.trackedSetInterval, clearInterval: timerTracking.trackedClearInterval, }) - expect(activeIntervals.size).toBe(1) + expect(activeIntervals.size).toBe(2) // Offline migration replaces OpenCode's OAuth credentials with a // non-secret activation marker. Pass that stored marker to the loader, @@ -333,9 +324,9 @@ describe('dispose stops per-instance background services', () => { const options = await loader(() => Promise.resolve(activation), provider) expect(options.fetch).toBeFunction() - // The loader adds a second interval, the main account's OAuth refresh, - // beside the fallback-account refresh started during construction. - expect(activeIntervals.size).toBe(2) + // The loader adds main's OAuth refresh beside fallback refresh and + // Prime, which both start during construction. + expect(activeIntervals.size).toBe(3) await pool.dispose(plugin) diff --git a/packages/opencode/src/tests/info-logs.test.ts b/packages/opencode/src/tests/info-logs.test.ts index 7aa74c949..543b24bcd 100644 --- a/packages/opencode/src/tests/info-logs.test.ts +++ b/packages/opencode/src/tests/info-logs.test.ts @@ -278,10 +278,9 @@ async function migratedClaude() { test('does not retain a background interval unless the helper opts in', async () => { const claude = await migratedClaude() - // The helper supplies an interval mock that starts no timer. Construction - // schedules only the fallback-account refresh, so the mock is called once - // while the tracked set of active intervals remains empty. - expect(timerTracking.disabledIntervalCalls).toBe(1) + // Construction schedules fallback refresh and Prime, whose tick checks + // whether it is enabled. The helper's mock starts neither timer. + expect(timerTracking.disabledIntervalCalls).toBe(2) expect(activeIntervals.size).toBe(0) await timerTracking.withTrackedInterval(async () => { @@ -289,6 +288,7 @@ test('does not retain a background interval unless the helper opts in', async () setInterval: trackedSetInterval, clearInterval: trackedClearInterval, }) + // The second instance shares the Prime timer; only its fallback refresh is new. expect(activeIntervals.size).toBe(1) }) expect(activeIntervals.size).toBe(0) diff --git a/packages/opencode/src/tests/opencode1-settings-read.test.ts b/packages/opencode/src/tests/opencode1-settings-read.test.ts index c61ad7f0d..edc94578d 100644 --- a/packages/opencode/src/tests/opencode1-settings-read.test.ts +++ b/packages/opencode/src/tests/opencode1-settings-read.test.ts @@ -9,11 +9,12 @@ import { nativeQuotaCodec } from '../../../core/src/native-quota-codec' import { nativeVaultPaths } from '../../../core/src/native-vault-paths' import { settingsReaderOutputs } from './opencode2-settings-readers' import { getPluginTestHandles } from './plugin-test-handles' +import { snapshotSettings } from './settings-snapshot-fixture' +import { observeSettings } from './settings-snapshot-observe' import { + cacheKeepWarmSnapshot, expectedReleaseSnapshot, - snapshotSettings, -} from './settings-snapshot-fixture' -import { observeSettings } from './settings-snapshot-observe' +} from './settings-snapshot-parity' import { applyMenuAction, createMockClient, @@ -785,6 +786,9 @@ describe('OpenCode 1 settings service reads', () => { // keep every older diagnostic and request byte in the release oracle. const compatible = { ...observed, + warms: observed.warms.map((warm) => + cacheKeepWarmSnapshot(warm, 'current'), + ), logs: observed.logs.filter( (record) => !( diff --git a/packages/opencode/src/tests/opencode2-settings-read.test.ts b/packages/opencode/src/tests/opencode2-settings-read.test.ts index a024a3d34..c1d29accc 100644 --- a/packages/opencode/src/tests/opencode2-settings-read.test.ts +++ b/packages/opencode/src/tests/opencode2-settings-read.test.ts @@ -19,11 +19,12 @@ import * as reloadFactory from '../v2/reload' import { setupAnthropicAuth } from '../v2/setup' import * as sourceFactory from '../v2/source' import { settingsReaderOutputs } from './opencode2-settings-readers' +import { snapshotSettings } from './settings-snapshot-fixture' +import { observeSettings } from './settings-snapshot-observe' import { + cacheKeepWarmSnapshot, expectedReleaseSnapshot, - snapshotSettings, -} from './settings-snapshot-fixture' -import { observeSettings } from './settings-snapshot-observe' +} from './settings-snapshot-parity' const cleanups: (() => unknown | Promise)[] = [] afterEach(async () => { @@ -1247,6 +1248,9 @@ for (const mode of ['local', 'claustrum'] as const) { // keep every older diagnostic and request byte in the release oracle. const compatible = { ...observed, + warms: observed.warms.map((warm) => + cacheKeepWarmSnapshot(warm, 'current'), + ), logs: observed.logs.filter( (record) => !( diff --git a/packages/opencode/src/tests/quota-policy-and-killswitch.integration.test.ts b/packages/opencode/src/tests/quota-policy-and-killswitch.integration.test.ts index e831c696c..b48522ddc 100644 --- a/packages/opencode/src/tests/quota-policy-and-killswitch.integration.test.ts +++ b/packages/opencode/src/tests/quota-policy-and-killswitch.integration.test.ts @@ -2590,9 +2590,8 @@ describe('auth.loader', () => { authorization: 'Bearer kie-key', }) expect(requests[1]?.body).not.toHaveProperty('fallbacks') - expect(requests[1]?.beta?.split(',')).not.toContain( - SERVER_SIDE_FALLBACK_BETA, - ) + // An API-key request has no injected Claude Code betas. + expect(requests[1]?.beta).toBeNull() }) test('does not route to API-key fallback after main 429 when quota does not confirm exhaustion', async () => { diff --git a/packages/opencode/src/tests/quota-sweep.test.ts b/packages/opencode/src/tests/quota-sweep.test.ts index 1bcb22675..3471cba37 100644 --- a/packages/opencode/src/tests/quota-sweep.test.ts +++ b/packages/opencode/src/tests/quota-sweep.test.ts @@ -449,17 +449,14 @@ async function startBody(options: BodyOptions) { stopPlugin = stop lifetimes.trackDetached(stopping.wait.then(stop)) const plugin = await creation - // Only the background fallback sweep is registered while the plugin is - // created; its period is one minute plus up to one minute of jitter. - const sweepTicks = intervals.filter( - (interval) => interval.ms >= 60_000 && interval.ms <= 120_000, - ) - if (intervals.length !== 1 || sweepTicks.length !== 1) - throw new Error( - `Expected one background sweep interval, saw ${JSON.stringify(intervals.map((interval) => interval.ms))}`, - ) - const backgroundSweep = sweepTicks[0]?.run - if (!backgroundSweep) throw new Error('Missing background sweep interval') + // Construction registers the jittered fallback sweep first, then Prime. + // Prime has an interval even when disabled and can share the sweep's delay. + expect(intervals).toHaveLength(2) + const [sweep, prime] = intervals + expect(sweep!.ms).toBeGreaterThanOrEqual(60_000) + expect(sweep!.ms).toBeLessThanOrEqual(120_000) + expect(prime!.ms).toBe(Core.PRIME_TICK_MS) + const backgroundSweep = sweep!.run const startupSweep = getPluginTestHandles(plugin).fallbackRefreshReady if (!startupSweep) throw new Error('Plugin exposed no startup sweep') const loader: AuthLoader | undefined = plugin.auth?.loader diff --git a/packages/opencode/src/tests/settings-snapshot-fixture.ts b/packages/opencode/src/tests/settings-snapshot-fixture.ts index dcd544d92..fe0d18497 100644 --- a/packages/opencode/src/tests/settings-snapshot-fixture.ts +++ b/packages/opencode/src/tests/settings-snapshot-fixture.ts @@ -1,35 +1,9 @@ import type * as core from '@cortexkit/anthropic-auth-core' -import releaseSnapshots from './fixtures/settings-2.11.2.json' import { nondefaultSettings } from './opencode2-settings-readers' export const snapshotTime = 1_900_000_000_000 export const snapshotModel = 'claude-opus-5-5' -export function expectedReleaseSnapshot( - host: 1 | 2, - sample: 'explicit' | 'absent', -) { - const released = releaseSnapshots[`oc${host}-${sample}`] - // The feed setting is gone. The wire reader in both snapshots is OpenCode 2's. - const { quota_header_feed_enabled: _removed, ...outputs } = - released.readers.outputs - // The frozen OpenCode 1 sample already has the five-minute request bytes and - // CacheKeep body sizes that OpenCode 2 should now produce with no override. - const short = releaseSnapshots['oc1-absent'] - return { - ...released, - readers: { - outputs, - wire: { ...released.readers.wire, cache1hEnabled: sample === 'explicit' }, - }, - ...(host === 2 && - sample === 'absent' && { - request: { ...released.request, body: short.request.body }, - logs: short.logs, - }), - } -} - export function snapshotSettings(absent: boolean): core.AccountStorage { const settings: core.AccountStorage = { version: 1, diff --git a/packages/opencode/src/tests/settings-snapshot-parity.ts b/packages/opencode/src/tests/settings-snapshot-parity.ts new file mode 100644 index 000000000..e2dd2700f --- /dev/null +++ b/packages/opencode/src/tests/settings-snapshot-parity.ts @@ -0,0 +1,44 @@ +import { expect } from 'bun:test' +import { promptCacheSnapshot } from '../../../core/src/tests/prompt-cache-snapshot' +import releaseSnapshots from './fixtures/settings-2.11.2.json' + +export function cacheKeepWarmSnapshot( + warm: T, + source: 'release' | 'current', +) { + const body = JSON.parse(warm.body) + // Older OpenCode warms sent the previous-message ID; current warms must not. + if (source === 'current') expect(body).not.toHaveProperty('diagnostics') + return { ...warm, body: promptCacheSnapshot(body) } +} + +export function expectedReleaseSnapshot( + host: 1 | 2, + sample: 'explicit' | 'absent', +) { + const released = releaseSnapshots[`oc${host}-${sample}`] + // The feed setting is gone. The wire reader in both snapshots is OpenCode 2's. + const { quota_header_feed_enabled: _removed, ...outputs } = + released.readers.outputs + // The frozen OpenCode 1 sample already has the five-minute request bytes and + // CacheKeep body sizes that OpenCode 2 should now produce with no override. + const short = releaseSnapshots['oc1-absent'] + return { + ...released, + warms: released.warms.map((warm) => cacheKeepWarmSnapshot(warm, 'release')), + readers: { + outputs, + wire: { + ...released.readers.wire, + cache1hEnabled: sample === 'explicit', + // The shared OpenCode 2 wire policy sends a null predecessor on the first turn. + cacheDiagnosticsPreviousMessageId: null, + }, + }, + ...(host === 2 && + sample === 'absent' && { + request: { ...released.request, body: short.request.body }, + logs: short.logs, + }), + } +} diff --git a/packages/pi/src/tests/scoped-stream.test.ts b/packages/pi/src/tests/scoped-stream.test.ts index 4e2232771..b32076ba5 100644 --- a/packages/pi/src/tests/scoped-stream.test.ts +++ b/packages/pi/src/tests/scoped-stream.test.ts @@ -49,6 +49,7 @@ import { type ProviderConfig, } from '@earendil-works/pi-coding-agent' import { nativeVaultPaths } from '../../../core/src/native-vault-paths.ts' +import { promptCacheSnapshot } from '../../../core/src/tests/prompt-cache-snapshot.ts' import { createTestLifetimeSuite } from '../../../core/src/tests/test-lifetime.ts' import { recordedTimers, @@ -401,6 +402,11 @@ for (const mode of [ ).toEqual([]) const rawHead = JSON.parse(bodies[0]!) const rawFork = JSON.parse(bodies.at(-1)!) + expect(rawHead.diagnostics).toEqual({ previous_message_id: null }) + expect(rawFork).not.toHaveProperty('diagnostics') + expect(rawFork.system[0].text).not.toMatch( + /cc_(?:prompt_id|prev_req|prompt_index|turn_index|turn_origin)=/, + ) const blocks = rawFork.messages.flatMap( (message: { content: unknown[] }) => message.content, ) as Record[] @@ -436,7 +442,7 @@ for (const mode of [ expect(countMarkers(rawFork)).toBeLessThanOrEqual(4) delete headBody.messages delete forkBody.messages - expect(JSON.stringify(forkBody)).toBe(JSON.stringify(headBody)) + expect(promptCacheSnapshot(forkBody)).toBe(promptCacheSnapshot(headBody)) expect(JSON.stringify(await getPiTrackedCacheKeepSessions())).toBe(before) expect(sessionCacheActivity.ttlMs(head)).toBe( mode === 'head TTL' ? 3_600_000 : 300_000, diff --git a/packages/pi/src/tests/settings-read.test.ts b/packages/pi/src/tests/settings-read.test.ts index 099bcc03a..0cc749b4a 100644 --- a/packages/pi/src/tests/settings-read.test.ts +++ b/packages/pi/src/tests/settings-read.test.ts @@ -21,6 +21,7 @@ import { parse } from 'jsonc-parser' import { nativeAccountSettings } from '../../../core/src/native-account-view.ts' import { nativeQuotaCodec } from '../../../core/src/native-quota-codec.ts' import { nativeVaultPaths } from '../../../core/src/native-vault-paths.ts' +import { promptCacheSnapshot } from '../../../core/src/tests/prompt-cache-snapshot.ts' import { buildAnthropicRequest } from '../convert.ts' import { closePiNativeRuntime, @@ -1132,10 +1133,18 @@ for (const mode of ['local', 'claustrum'] as const) expect(await (await native.service()).getSettingsPath()).toBe(file) expect(await fs.exists(`${file}.moved`)).toBe(true) expect(await fs.readFile(selected.config, 'utf8')).toBe(sourceBytes) - const released = releaseSnapshots[fixture] + const release = releaseSnapshots[fixture] const { quota_header_feed_enabled: _removed, ...readers } = - released.readers - const expected = JSON.stringify({ ...released, readers }) + release.readers + const conversationBytes = (send: (typeof release.sends)[number]) => ({ + ...send, + body: promptCacheSnapshot(JSON.parse(send.body)), + }) + const expected = JSON.stringify({ + ...release, + readers, + sends: release.sends.map(conversationBytes), + }) for (const [phase, storage] of [ ['before', before], ['after', after], @@ -1148,6 +1157,9 @@ for (const mode of ['local', 'claustrum'] as const) // keep every older diagnostic and request byte in the release oracle. const compatible = { ...observed, + // The conversation gained a diagnostics predecessor, which also + // changes the body signature. Warm bodies still compare byte for byte. + sends: observed.sends.map(conversationBytes), logs: observed.logs.filter( (record) => !( @@ -1158,6 +1170,9 @@ for (const mode of ['local', 'claustrum'] as const) } expect(JSON.stringify(compatible), phase).toBe(expected) expect(observed.sends).toHaveLength(1) + expect(JSON.parse(observed.sends[0]!.body).diagnostics).toEqual({ + previous_message_id: null, + }) expect(observed.logs.length).toBeGreaterThan(0) expect(observed.tracks).toHaveLength(1) } @@ -1398,6 +1413,7 @@ test('the stream applies model settings and mirrors dump_enabled from every snap baseURL: 'https://api.anthropic.com', }, ], + quota: { enabled: false }, prime: { enabled: false }, }, storagePath, @@ -1412,11 +1428,11 @@ test('the stream applies model settings and mirrors dump_enabled from every snap (account) => account.type === 'api', ) const bodies: Record[] = [] - const send = () => + const send = (account?: typeof apiAccount) => __sendPiAnthropicRequestForTest( { storagePath, - apiAccount, + apiAccount: account, model: { id: 'claude-opus-5-5', name: 'Opus', @@ -1451,6 +1467,10 @@ test('the stream applies model settings and mirrors dump_enabled from every snap await send() expect(core.isDumpEnabled()).toBe(true) expect(bodies[0]?.speed).toBe('fast') + if (!apiAccount) throw new Error('Missing paid fixture account') + // API-key requests are not shaped with the subscription fast-mode setting. + await send(apiAccount) + expect(bodies[1]).not.toHaveProperty('speed') await write({ dump_enabled: false, claude_fast_enabled: false }) await changed( native, @@ -1459,7 +1479,7 @@ test('the stream applies model settings and mirrors dump_enabled from every snap core.setDumpEnabled(true) await send() expect(core.isDumpEnabled()).toBe(false) - expect(bodies[1]?.speed).toBeUndefined() + expect(bodies[2]).not.toHaveProperty('speed') }) for (const peer of ['never ran', 'stricter'] as const) { From c5714d7c0f368f6cb16310bae1ff136be2d52865 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:17:41 +0100 Subject: [PATCH 12/27] mason: restore CacheKeep prewarms without turn diagnostics Check the original CacheKeep target after the restart delay. The header hook receives a copy with rewritten bytes, but immediate attempts are fenced by the original object identity. Keep every existing account and origin check before dispatch. Drop diagnostics when building a warm in Core so Pi cannot replay a conversation predecessor and OpenCode keeps the same rule. --- CHANGELOG.md | 2 ++ packages/core/src/cachekeep.ts | 5 +++++ packages/opencode/src/index.ts | 15 ++------------- packages/pi/src/cachekeep.ts | 9 +++++++-- packages/pi/src/tests/scoped-stream.test.ts | 4 +++- 5 files changed, 19 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 12d9fe24b..320b981d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ This repo is a CortexKit-maintained Anthropic auth monorepo for OpenCode and Pi. ## 2.16.6 +- OpenCode 1 CacheKeep can run a one-off prewarm again without dropping its normal account and destination checks. +- Pi keep-warms no longer send the conversation's previous message ID to Claude. - Changing effort mid-conversation now preserves the prompt cache in OpenCode v1, OpenCode v2, and Pi for Claude Mythos 5.1 and 5.2, and for Claude Opus 5 and Haiku 5.5 when adaptive thinking is on. - OpenCode 1: idle sessions can keep warming a still-live Claude prompt cache after a server restart without resetting their budgets; `auto` keep-warm now uses the accepted prefix's token counts to price warms, even without a restart. - OpenCode 1: after a server restart, a threaded session's first full request can reuse the previous full request's cache boundary, as on OpenCode 2 and Pi. diff --git a/packages/core/src/cachekeep.ts b/packages/core/src/cachekeep.ts index 86f87bda0..3f71fc8ac 100644 --- a/packages/core/src/cachekeep.ts +++ b/packages/core/src/cachekeep.ts @@ -366,6 +366,8 @@ export async function buildCacheKeepPrewarmBody( reason: 'a thread continuation is not a full cache prefix', } + // Keep-warm refreshes the cache without advancing the conversation's previous-message ID. + delete body.diagnostics if (!hasExplicitCacheControl(body)) { return { ok: false, reason: 'body has no explicit cache breakpoints' } } @@ -833,6 +835,8 @@ export class CacheKeepManager { headers: Headers, target: CacheKeepTarget, attempt: CacheKeepPrewarmAttempt, + /** Check the original target after waiting; `target` carries the rewritten body. */ + isTargetCurrent: () => boolean, ) => Promise | Headers | undefined /** Pure in-memory route lookup; an unknown answer keeps the target. */ peekRoutingAccount?: ( @@ -2387,6 +2391,7 @@ export class CacheKeepManager { new Headers(target.headers), prewarmTarget, attempt, + () => this.isCurrentTarget(target), ) : new Headers(target.headers) ensureActive() diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index 888382f0f..101236013 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -3908,14 +3908,6 @@ const anthropicAuthPlugin = async ( await cacheKeepRegistry.publish(sessions) aggregateCacheKeepSessions = await cacheKeepRegistry.list(sessions) }, - prepareBody: (bodyText) => { - // Strip the real turn's diagnostic predecessor before signing. A warm - // refreshes the prefix but does not join the turn's diagnostics chain. - const body = JSON.parse(bodyText) as Record - if (!Object.hasOwn(body, 'diagnostics')) return bodyText - delete body.diagnostics - return JSON.stringify(body) - }, onResponse: async ({ target, bodyText, status, receivedAt, attempt }) => { const authorization = cacheKeepScopedAttempts.get(attempt.id) // A recovery source warm protects another model, not the active fallback's cache. @@ -3997,12 +3989,9 @@ const anthropicAuthPlugin = async ( cacheKeepScopedAttempts.set(attempt.id, current) return rotatedHeaders }, - prepareHeaders: async (headers, target, attempt) => { + prepareHeaders: async (headers, target, attempt, isTargetCurrent) => { await cacheKeepRestart.stagger(target, attempt.signal) - if ( - !cacheKeepRestart.active() || - !cacheKeepManager.isCurrentTarget(target) - ) + if (!cacheKeepRestart.active() || !isTargetCurrent()) throw new CacheKeepWarmRefusal('stopped') // A remembered URL gets the same destination rule as a live request; // refuse it before any credential is authorized for the prewarm. diff --git a/packages/pi/src/cachekeep.ts b/packages/pi/src/cachekeep.ts index 35c8b2143..1025a5219 100644 --- a/packages/pi/src/cachekeep.ts +++ b/packages/pi/src/cachekeep.ts @@ -126,7 +126,7 @@ export class PiCacheKeep { this.sessions.get(id)?.store.removed(id) managerOptions.onTargetRemoved?.(id) }, - prepareHeaders: async (headers, target, attempt) => { + prepareHeaders: async (headers, target, attempt, isTargetCurrent) => { // Delay the actual first send, not just its due time: minute ticks can // coalesce all overdue sessions after many Pi processes restart. const stagger = this.restored.get(target.id) @@ -151,7 +151,12 @@ export class PiCacheKeep { if (!account || !nativeAccountCanServe(account)) return undefined } else if (this.manager.trackedRequest(target.id)) return undefined return managerOptions.prepareHeaders - ? managerOptions.prepareHeaders(headers, target, attempt) + ? managerOptions.prepareHeaders( + headers, + target, + attempt, + isTargetCurrent, + ) : headers }, }) diff --git a/packages/pi/src/tests/scoped-stream.test.ts b/packages/pi/src/tests/scoped-stream.test.ts index b32076ba5..46f4726ea 100644 --- a/packages/pi/src/tests/scoped-stream.test.ts +++ b/packages/pi/src/tests/scoped-stream.test.ts @@ -5519,7 +5519,7 @@ async function sendPrimary( await response.text() } -test('Pi gzips eligible prewarms and rescues them with the same signed body', async () => { +test('Pi gzips eligible prewarms and rescues them with the same signed body outside the diagnostics chain', async () => { const f = await fixture() const sent: Array<{ encoding: string | null; body: string }> = [] globalThis.fetch = Object.assign( @@ -5545,6 +5545,7 @@ test('Pi gzips eligible prewarms and rescues them with the same signed body', as bodyText: JSON.stringify({ model: model.id, max_tokens: 128, + diagnostics: { previous_message_id: 'msg_pi_conversation' }, system: [ { type: 'text', @@ -5560,6 +5561,7 @@ test('Pi gzips eligible prewarms and rescues them with the same signed body', as }) expect(result.ok).toBe(true) expect(sent.map(({ encoding }) => encoding)).toEqual(['gzip', null]) + expect(JSON.parse(sent[0]!.body)).not.toHaveProperty('diagnostics') expect(sent[0]?.body.trimEnd()).toBe(sent[1]?.body) }) From d7605939dc7ffb47eed80440227fa680e7910389 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:37:15 +0100 Subject: [PATCH 13/27] mason: exercise the right CacheKeep tick and cache default The new Prime interval and CacheKeep share a 60-second cadence, so find-by-period invoked Prime instead of exercising the token and retry assertions. Tick the CacheKeep manager directly. The OpenCode 2 default TTL in both diagnostics records is now five minutes; keep exact comparison of the other fields and the beta list. --- .../tests/fallback-token-use-sites.test.ts | 26 ++++--------------- .../src/tests/opencode2-adapter.test.ts | 3 ++- 2 files changed, 7 insertions(+), 22 deletions(-) diff --git a/packages/opencode/src/tests/fallback-token-use-sites.test.ts b/packages/opencode/src/tests/fallback-token-use-sites.test.ts index 2489a16eb..10c0fc1b8 100644 --- a/packages/opencode/src/tests/fallback-token-use-sites.test.ts +++ b/packages/opencode/src/tests/fallback-token-use-sites.test.ts @@ -6,7 +6,6 @@ import { join } from 'node:path' import { __setLogTestSink, type AccountStorage, - CACHE_KEEP_TICK_MS, createNativeAccountRuntime, custodyTombstoneOAuth, getLogLevel, @@ -1148,11 +1147,8 @@ describe('vault-served fallback outbound token census', () => { ;( fixture.intervals as IntervalRecord[] & { clock: (now: number) => void } ).clock(now + 55 * 60_000) - const cacheKeepTick = fixture.intervals.find( - (interval) => interval.ms === CACHE_KEEP_TICK_MS, - ) - if (!cacheKeepTick) throw new Error('missing CacheKeep interval') - cacheKeepTick.callback() + // Prime also registers a 60-second interval, so use the CacheKeep manager directly. + await getPluginTestHandles(fixture.plugin).cacheKeepManager.tick() await waitFor( () => fixture.records.some((record) => { @@ -1202,11 +1198,7 @@ describe('vault-served fallback outbound token census', () => { ;( fixture.intervals as IntervalRecord[] & { clock: (now: number) => void } ).clock(now + 55 * 60_000) - const cacheKeepTick = fixture.intervals.find( - (interval) => interval.ms === CACHE_KEEP_TICK_MS, - ) - if (!cacheKeepTick) throw new Error('missing CacheKeep interval') - cacheKeepTick.callback() + await getPluginTestHandles(fixture.plugin).cacheKeepManager.tick() await waitFor( () => fixture.records.some((record) => { @@ -1452,11 +1444,7 @@ describe('scoped maintenance rotation recovery', () => { ;( fixture.intervals as IntervalRecord[] & { clock: (now: number) => void } ).clock(now + 55 * 60_000) - const interval = fixture.intervals.find( - (candidate) => candidate.ms === CACHE_KEEP_TICK_MS, - ) - if (!interval) throw new Error('CacheKeep interval missing') - interval.callback() + await getPluginTestHandles(fixture.plugin).cacheKeepManager.tick() await waitFor( () => sent.length >= 2, 'rotated CacheKeep prewarm was not replayed', @@ -1563,11 +1551,7 @@ describe('scoped maintenance rotation recovery', () => { clock: (now: number) => void } ).clock(now + 55 * 60_000) - const interval = fixture.intervals.find( - (candidate) => candidate.ms === CACHE_KEEP_TICK_MS, - ) - if (!interval) throw new Error('CacheKeep interval missing') - interval.callback() + await getPluginTestHandles(fixture.plugin).cacheKeepManager.tick() await waitFor( () => reports.length >= 1, 'CacheKeep 401 was not reported after re-authorization failed', diff --git a/packages/opencode/src/tests/opencode2-adapter.test.ts b/packages/opencode/src/tests/opencode2-adapter.test.ts index d627ea429..2329fa5a8 100644 --- a/packages/opencode/src/tests/opencode2-adapter.test.ts +++ b/packages/opencode/src/tests/opencode2-adapter.test.ts @@ -626,7 +626,8 @@ test('OpenCode 2 logs cache diagnostics at debug level and one beta list per sen ts_ms_received: expect.any(Number), model: scope.modelID, is_subagent: false, - ttl_sent: '1h', + // When no cache lifetime is configured, OpenCode 2 now sends five minutes. + ttl_sent: '5m', cache_read: 4, cache_creation: 8, input_tokens: 20, From 8db8f60b018027b3ad0f822cb0b46981b7c4d6df Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:45:52 +0100 Subject: [PATCH 14/27] Test comments: say what the Prime timer is --- packages/opencode/src/tests/account-command.test.ts | 3 ++- packages/opencode/src/tests/add-account-flows.test.ts | 3 ++- packages/opencode/src/tests/dispose-cleanup.test.ts | 3 ++- packages/opencode/src/tests/info-logs.test.ts | 3 ++- packages/opencode/src/tests/quota-sweep.test.ts | 3 ++- 5 files changed, 10 insertions(+), 5 deletions(-) diff --git a/packages/opencode/src/tests/account-command.test.ts b/packages/opencode/src/tests/account-command.test.ts index dd56cda1e..a623800e5 100644 --- a/packages/opencode/src/tests/account-command.test.ts +++ b/packages/opencode/src/tests/account-command.test.ts @@ -1347,7 +1347,8 @@ describe('account command INFO logs (via plugin)', () => { test('does not retain a background interval unless the helper opts in', async () => { const fixture = await migrate(baseStorage()) await fixture.getPlugin() - // Prime registers at startup alongside fallback refresh, even when off. + // The Prime timer (the opt-in five-hour window starter) registers at + // startup alongside fallback refresh, even when Prime is off. expect(timerTracking.disabledIntervalCalls).toBe(2) expect(activeIntervals.size).toBe(0) diff --git a/packages/opencode/src/tests/add-account-flows.test.ts b/packages/opencode/src/tests/add-account-flows.test.ts index 5cbfd1b21..2dec33149 100644 --- a/packages/opencode/src/tests/add-account-flows.test.ts +++ b/packages/opencode/src/tests/add-account-flows.test.ts @@ -428,7 +428,8 @@ pluginTest( 'does not retain a background interval unless the helper opts in', async (fixture) => { await fixture.getPlugin() - // Prime registers at startup alongside fallback refresh, even when off. + // The Prime timer (the opt-in five-hour window starter) registers at + // startup alongside fallback refresh, even when Prime is off. expect(timerTracking.disabledIntervalCalls).toBe(2) expect(activeIntervals.size).toBe(0) diff --git a/packages/opencode/src/tests/dispose-cleanup.test.ts b/packages/opencode/src/tests/dispose-cleanup.test.ts index 4ccd2f145..0e4e64542 100644 --- a/packages/opencode/src/tests/dispose-cleanup.test.ts +++ b/packages/opencode/src/tests/dispose-cleanup.test.ts @@ -248,7 +248,8 @@ describe('dispose stops per-instance background services', () => { const pool = await migratedPool({}) // The fixture disables CacheKeep's aggregate refresh. Construction - // schedules fallback refresh and Prime, even while Prime is off. + // schedules fallback refresh and the Prime timer (the opt-in five-hour + // window starter), even while Prime is off. const counted = await pool.getPlugin() expect(timerTracking.disabledIntervalCalls).toBe(2) await pool.dispose(counted) diff --git a/packages/opencode/src/tests/info-logs.test.ts b/packages/opencode/src/tests/info-logs.test.ts index 543b24bcd..359f54513 100644 --- a/packages/opencode/src/tests/info-logs.test.ts +++ b/packages/opencode/src/tests/info-logs.test.ts @@ -278,7 +278,8 @@ async function migratedClaude() { test('does not retain a background interval unless the helper opts in', async () => { const claude = await migratedClaude() - // Construction schedules fallback refresh and Prime, whose tick checks + // Construction schedules fallback refresh and the Prime timer (the opt-in + // five-hour window starter), whose tick checks // whether it is enabled. The helper's mock starts neither timer. expect(timerTracking.disabledIntervalCalls).toBe(2) expect(activeIntervals.size).toBe(0) diff --git a/packages/opencode/src/tests/quota-sweep.test.ts b/packages/opencode/src/tests/quota-sweep.test.ts index 3471cba37..84c908c21 100644 --- a/packages/opencode/src/tests/quota-sweep.test.ts +++ b/packages/opencode/src/tests/quota-sweep.test.ts @@ -449,7 +449,8 @@ async function startBody(options: BodyOptions) { stopPlugin = stop lifetimes.trackDetached(stopping.wait.then(stop)) const plugin = await creation - // Construction registers the jittered fallback sweep first, then Prime. + // Construction registers the jittered fallback sweep first, then the Prime + // timer (the opt-in five-hour window starter). // Prime has an interval even when disabled and can share the sweep's delay. expect(intervals).toHaveLength(2) const [sweep, prime] = intervals From 3508c5cde15dd56bf83bedec5057194dceae564f Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:38:10 +0100 Subject: [PATCH 15/27] Docs: ARCHITECTURE.md and STRUCTURE.md match host parity --- ARCHITECTURE.md | 55 ++++++++++++++++++++++++++++++------------------- STRUCTURE.md | 7 +++++-- 2 files changed, 39 insertions(+), 23 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 624da6516..6016b486b 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -1,6 +1,6 @@ # Architecture -anthropic-auth lets coding agents use a Claude Pro, Max or Ultra subscription the way Claude Code does. It signs in with Claude's OAuth flow and keeps the tokens fresh. It reshapes each model request into the shape Claude Code 2.1.302 sends, and it spreads sessions across several subscription accounts while respecting their quota. Beyond that, it keeps the provider's prompt cache stable and warm, because on a long session the cached prefix is most of the cost. +anthropic-auth lets coding agents use a Claude Pro, Max or Ultra subscription the way Claude Code does. It signs in with Claude's OAuth flow and keeps the tokens fresh. It reshapes each subscription request into the shape Claude Code 2.1.302 sends, and it spreads sessions across several subscription accounts while respecting their quota. Beyond that, it keeps the provider's prompt cache stable and warm, because on a long session the cached prefix is most of the cost. It runs in three hosts and shares one core: @@ -16,6 +16,7 @@ Accounts are kept either in a **local pool** on disk or in the **Claustrum vault - **Route:** one place a request can go: an OAuth account, or (local mode only) a paid API key. - **Custody:** who holds the credentials. **Local** means the native pool files on this machine. **Vault** means Claustrum, reached through an enrollment approved once per host kind. While a host is enrolled, local credentials never serve, refresh, poll or warm (the exclusive-vault rule). - **Placeholder:** a non-secret entry in the host's own auth slot that makes the host route Anthropic requests to this plugin without holding a real token. OpenCode 1 uses an expired OAuth tombstone (`claustrum-tombstone:v1:anthropic`). OpenCode 2 uses common-auth's `common-auth-placeholder.anthropic`. Pi uses common-auth's move-aside slot, with an inert API-key placeholder. +- **Body signature (`cch`):** the hash Claude Code writes into its billing line (`cch=`), computed over the final request body. Any later change to the body needs a new signature. - **Sticky session:** in `sticky-balanced` routing, a session stays on the account it was given, so its prompt cache stays valid. - **Hold:** keeping a session on its exhausted account and asking the host to retry later, instead of moving it and paying for a cache rebuild. - **Killswitch / quota floor:** a user-set minimum remaining quota below which an account is refused locally. @@ -36,21 +37,21 @@ Accounts are kept either in a **local pool** on disk or in the **Claustrum vault | OpenCode 1 entry | `packages/opencode/src/index.ts` | Plugin factory: auth loader with custom `fetch`, message and header hooks, `/claude` command, background services, dispose. | | OpenCode 1 request shaping | `packages/opencode/src/transform.ts` | Rewrites URL and body, and rewrites the SSE stream on the way back. | | OpenCode 2 | `packages/opencode/src/v2/` | `setup.ts` installs common-auth's OpenCode 2 adapter. `source.ts` chooses accounts and retries. `adapter.ts` shapes and sends requests. Also menus, sidebar projection, keep-warm and Prime. | -| OpenCode shared | `packages/opencode/src/` | Server fallback, OpenCode 1 recovery rounds, effort plan transport, billing lineage, cache diagnostics, sidebar state, RPC for the TUI, setup CLI. | +| OpenCode shared | `packages/opencode/src/` | Server fallback, OpenCode 1 recovery rounds, effort plan transport, billing lineage, cache-diagnostics integration, sidebar state, RPC for the TUI, setup CLI. | | TUI | `packages/opencode/src/tui/`, `src/tui.tsx` | Sidebar (shared common-auth frame) and `/claude` dialogs, precompiled to `src/tui-compiled/` at build time. | | Pi | `packages/pi/src/` | Provider registration, request conversion (`convert.ts`), streaming and transport (`stream.ts`, `transport.ts`), commands, keep-warm. | | Core accounts | `packages/core/src/native-*.ts`, `pool-*.ts` | Native account runtime, local credential service and refresh coordinator, vault runtime and custody, enrollment authority, migration, host auth slots, menus. | -| Core request | `packages/core/src/` | `cch.ts` and `claude-code.ts` (billing header and body signature), `model-capabilities.ts` (per-model handling), `message-threads.ts`, `request-gzip.ts`, `relay.ts`, `thinking-binding.ts`, `mid-conversation-output-config.ts`, `turn-end-note.ts`, `oauth-origin.ts`. | +| Core request | `packages/core/src/` | `cch.ts` and `claude-code.ts` (billing header and body signature), `api-key-request.ts` and `api-route-url.ts` (paid routes), `cache-diagnostics.ts`, `model-capabilities.ts` (per-model handling), `message-threads.ts`, `request-gzip.ts`, `relay.ts`, `thinking-binding.ts`, `mid-conversation-output-config.ts`, `turn-end-note.ts`, `oauth-origin.ts`. | | Core policy | `packages/core/src/` | `routing.ts`, `sticky-routing.ts`, `killswitch.ts`, `quota-manager.ts`, `quota-headers.ts`, `insula-quota.ts`, `quota-refusal.ts`, `session-cache-activity.ts`. | | Core cache | `packages/core/src/` | `cache1h.ts`, `cachekeep.ts` (keep-warm manager), `cachekeep-store.ts` (restart store), `cachekeep-registry.ts` (cross-process session list), `prime.ts`. | -| State layout | `packages/core/src/state-layout-*.ts`, `holder-registry.ts`, `layout-fence.ts` | Moving machine-written state out of OpenCode's config folder. Written, with the move switched off. | +| State layout | `packages/core/src/state-layout-*.ts`, `holder-registry.ts`, `layout-fence.ts` | Fenced relocation of OpenCode's machine-written state out of its config folder. Pi registers holders but keeps its legacy layout. | | End-to-end | `packages/e2e-tests/` | Real OpenCode processes against mock Anthropic, relay and Claustrum servers. | `STRUCTURE.md` has the directory map and where to add code. ## Request lifecycle -The order is the same on every host. Only the hook that runs each step differs (see the host sections). +The OAuth order is the same on every host. Only the hook that runs each step differs (see the host sections). Paid API-key routes use the separate policy under Transport. 1. **Admission.** Choose an account for the session (see Routing) and check it against quota policy. A request blocked by the user's own floor or killswitch is refused locally, with a message naming the limit and when it resets. 2. **Authorization.** Get a valid access token for that account. In local mode this goes through the refresh coordinator. In vault mode each send asks the vault for a fresh scoped receipt. A healthy request (valid token, known identity, ready roster) takes **no lock** before it is sent; per-host tests count lock acquisitions to enforce this. @@ -58,17 +59,19 @@ The order is the same on every host. Only the hook that runs each step differs ( - **Identity and billing:** sanitize OpenCode's identity out of the system prompt and prepend Claude Code's identity. Add the billing header with its `cc_version` suffix (pinned per session from the first user message) and request lineage (`cc_prompt_id`, `cc_prev_req`). - **Tools:** prefix tool names with `mcp_`. - **Cache:** place cache breakpoints for the chosen strategy (explicit, automatic or hybrid; at most four) and set the cache lifetime. - - **Per-model handling** from `model-capabilities.ts`: thinking mode, rejected forced tool choice, effort markers, thinking-binding controls, turn-end notes, server-side fallback, fast mode, beta lists. + - **Per-model handling** from `model-capabilities.ts`: thinking mode, rejected forced tool choice, effort markers, thinking-binding controls, turn-end notes, server-side fallback, fast mode, beta lists. Per-message effort covers Fable 5.1/5.2 and Mythos 5.1/5.2, plus Opus 5/5.5, Sonnet 5.5 and Haiku 5.5 with adaptive thinking. - **History checks:** refuse locally, before anything is signed, a history that ends on a meaningful assistant turn or carries effort markers that don't match the session's plan. -4. **Message thread.** On the final body, decide `create`, `continue` or stateless (see Message threads), then compute the `cch` body signature once. +4. **Message thread.** On the final OAuth body, decide `create`, `continue` or stateless (see Message threads), then compute the `cch` body signature once. 5. **Transport.** - - **Destination:** OAuth requests go only to `https://api.anthropic.com`. Neither the provider `baseURL` nor `ANTHROPIC_BASE_URL` moves them; the latter applies to API-key routes only. - - **Direct sends:** large direct bodies are gzipped the way Claude Code does, with one uncompressed resend if a proxy rejects them. + - **Destination:** OAuth requests go only to `https://api.anthropic.com` or the custom gateway in the user's settings file. Neither the provider `baseURL` nor `ANTHROPIC_BASE_URL` moves them. A saved paid-route URL takes precedence over `ANTHROPIC_BASE_URL`; the environment variable applies only when the API-key route has no saved URL. + - **Paid API-key routes:** the plugin adds no Claude Code identity, `mcp_` tool prefix or `cch` body signature. It still checks history. It removes internal fallback state and OAuth-only betas. It applies model aliases. `ANTHROPIC_CUSTOM_HEADERS` applies only to these routes. HTTPS certificates are always verified. + - **Direct sends:** large direct OAuth bodies, including eligible CacheKeep warms, are gzipped the way Claude Code does. OpenCode 1 and Pi resend an eligible rejected body once uncompressed. OpenCode 2 cannot resend its host-owned initial request. An eligible rejection turns gzip off for later sends. - **Relay:** the optional Cloudflare Worker relay supports HTTP and WebSocket on OpenCode 1 and Pi, and HTTP only on OpenCode 2. A relay failure falls back to a direct send at most once per request. - **Abort:** the caller's abort signal ends the request at every step, including pre-send quota, profile and refresh work, which also have their own 30-second limits. 6. **Response.** - - **Stream:** the stream is rewritten on the way back: `mcp_` prefixes are stripped, server-fallback blocks are turned into storable markers, and in-stream API errors become retryable connection errors. + - **Stream:** the OAuth stream is rewritten on the way back: `mcp_` prefixes are stripped, server-fallback blocks are turned into storable markers, and in-stream API errors become retryable connection errors. - **Bookkeeping:** rate-limit headers are read as quota evidence, the thread anchor is recorded, and the request is tracked for keep-warm once Anthropic accepts it. Bookkeeping writes never delay the response. At shutdown they get a one-second grace before pending lock waits are cancelled. + - **Cache diagnostics:** eligible OAuth conversation requests link to the previous response's opaque message ID. Every host emits cache-result and beta-list debug records for them. Paid requests, forks, Prime and keep-warm do not advance that chain. ### OpenCode 1 @@ -81,14 +84,17 @@ The order is the same on every host. Only the hook that runs each step differs ( - **Placeholder:** OpenCode 2 routes to the plugin only when the selected Anthropic connection is the plugin's exact placeholder. Stock API keys, OpenCode's own Anthropic login and custom proxies pass through untouched. - **Holds:** OpenCode 2 holds by returning a retry delay from the installer, capped at 15 minutes per hold. - **No WebSocket relay:** a selected WebSocket relay is refused before dispatch. +- **Pricing:** OAuth models show zero token prices by default. `cost_zeroing_enabled: false` restores catalogue prices. API-key prices are unchanged. +- **Command:** `/claude` emits a menu-open event. Without a TUI subscriber it posts no text fallback. ### Pi - **Provider:** `registerProvider('anthropic', …)` with `streamSimple`. - **Conversion:** `convert.ts` builds the body. Pi's documentation paragraph is moved out of the top-level system prompt into a cached block before the first user text, because its text can trigger OAuth billing rejection. Signed thinking is replayed only when it came from the same API and model. -- **Effort history:** rebuilt from the session branch on each `turn_start`. +- **Effort history:** rebuilt from the session branch on each `turn_start`, including compaction. Top-level effort stays at its baseline when per-message effort applies. Changes are inserted at the dispatched history boundaries. - **Threads:** a whole-turn lease keeps tool-loop steps on one thread. - **Server fallback:** Pi does not opt into server-side fallback. +- **Command:** `/claude` can refresh quota. It can edit quota floors and killswitch thresholds. It can fire a lane start: a visible marker turn with a one-token request that warms the session's prompt cache before the next real turn. ## Shared user settings @@ -128,7 +134,9 @@ Modes are `main-first` (default), `fallback-first` and `sticky-balanced` (`routi - **Unconfirmed 429:** the session stays on its account, with waits of at most 60 seconds each, up to `MAX_UNCONFIRMED_SAME_ACCOUNT_RETRIES` (2) per turn. The third unconfirmed 429 moves it. - **No route:** a complete pool with no eligible route returns an explicit refusal (sign in again, or a quota 429, or a non-retryable 412 when waiting is off). An incomplete pool fails retryably. -**Shared routing.** When Thalamus provides the `cortexkit.routing` accessor, the plugin asks it once per account choice (OpenCode 1 sticky resolve, OpenCode 2 `chooseAccount`), with a 2-second limit. The answer is only advice: the local rules above still apply. The plugin also sends detached `served` and `exhausted` reports. +**Shared routing.** When Thalamus provides the `cortexkit.routing` accessor, all three hosts ask it for advice with a 2-second limit. OpenCode 1 asks in every routing mode, including account switches on retry. OpenCode 2 asks when choosing or retrying an account. Pi asks once per model request, including each step of a tool loop, and keeps the answer across that request's retries. The answer is only advice: the local rules above still apply. The plugin also sends detached `served` and `exhausted` reports. OpenCode reports when a host-owned routing or quota wait starts; Pi reports both ends of waits it owns and the start of host-owned retries. + +**Thalamus billing.** Ordinary model sends and CacheKeep warms report their payer, request kind and token usage on every host. Prime does not emit a session billing report. Agent Runner bills Pi fork answers itself. ## Quota @@ -141,9 +149,10 @@ Modes are `main-first` (default), `fallback-first` and `sticky-balanced` (`routi ## Prompt cache - **Strategy:** set per account (`cache1h.ts`): explicit breakpoints, automatic, or hybrid. Hybrid keeps a stable system anchor. When the last two user or tool-result boundaries are more than 20 content blocks apart, it moves that marker to a bridge anchor on the earlier boundary, so the latest marker's 20-block lookback still reaches a cache entry. A full request after accepted thread continuations may use that slot for the previous full request's cache boundary, as described below. Markers that reconnect caches when a session switches between Fable and Opus take priority. +- **Lifetime:** an unset or `default` `claude_cache_enabled` selects the 5-minute cache on every host. `on` selects 1 hour. `off` selects 5 minutes. A Thalamus session policy can override the choice. - **Keep-warm:** `CacheKeepManager` (`cachekeep.ts`) tracks up to 32 sessions, within a 64 MiB body budget, once Anthropic has accepted their request. - **Timing:** it sends the prewarm 5 minutes before expiry, on the account that served the session. Transient failures retry at about 20, 40 and 60 seconds until the cache would expire. A refusal a retry cannot fix (killswitch floor, account disabled or signed out, changed login, vault refusal) stops warming that session with one warning. - - **Restarts:** OpenCode 2 and Pi save the latest accepted body per session, gzipped and owner-only, under `cortexkit/anthropic-auth/cachekeep-restore/` in the data folder. A restarted host warms again from there. + - **Restarts:** every host saves the latest accepted body per session, gzipped and owner-only, under `cortexkit/anthropic-auth/cachekeep-restore/` in the data folder. A restarted host warms again from there. OpenCode 1 assigns one project instance to each restored session. Pi restores only its own session. - **Session list:** each process publishes session ids and cache timing, never bodies or tokens, to `cortexkit/anthropic-auth/cachekeep-sessions/` (documented in `docs/cachekeep-registry.md`). - **Per-session policy (Thalamus):** `session-cache-policy.ts` reads a session's `{ttl, keep_warm, hours}` through common-auth's `sessionCachePolicy`, synchronously, on every OAuth request and before every warm. No policy, or an invalid one, leaves the plugin's own settings in charge, field by field. - **Lifetime:** `none` strips every cache marker from the final body (after Pi's `onPayload`), and `short` and `long` set 5-minute or 1-hour markers. The applied lifetime is read from the body actually sent. @@ -151,7 +160,7 @@ Modes are `main-first` (default), `fallback-first` and `sticky-balanced` (`routi - **Durability:** each attempt's count and admitted cost are written owner-only before the warm is sent, so a restart cannot reset the cap. An unusable restart folder keeps every bound in memory instead. - **Reports:** an accepted response or a successful warm sends a detached `cache_touch` with the applied lifetime, and a warmed session's retirement sends `cache_warm_stopped` with a shared reason. Neither can delay a request. Opus 4.8 source warms send no touch, because the runner tracks one cache per session. - **Activity:** `session-cache-activity.ts` records when each session's cache was last refreshed by an accepted response or a successful prewarm. The sticky hold rule uses it. -- **Prime:** an opt-in five-hour window starter. On OpenCode 1, OpenCode 2 and Pi it sends one `max_tokens: 1` Haiku request per account when the window's reset has passed. A marker keyed by the verified Claude account makes sure only one process fires per reset, even across separate account files and hosts. +- **Prime:** an opt-in five-hour window starter. On OpenCode 1, OpenCode 2 and Pi it sends one `max_tokens: 1` Haiku request per account when the window's reset has passed. On OpenCode 1 and 2 its scheduler starts with the plugin and follows `prime_enabled` changes without a restart. A marker keyed by the verified Claude account makes sure only one process fires per reset, even across separate account files and hosts. ## Message threads @@ -166,24 +175,27 @@ Anything else sends a full `create` request. Title, summary, compaction, keep-wa **Full-after-thread cache boundary:** after at least one continuation has been accepted since the last full request, a new full request may reuse that full request's last message marker, including one nested inside a tool result. Core retains only the marker's position, lifetime, accepted time and hashes of its prefix and account/credential identity. The prefix, beta list and speed must still match, and the entry must not have expired. The marker replaces OpenCode's ordinary system/lookback marker or Pi's system marker, never exceeding four markers. It cannot replace an Opus standby bridge (anchoring the cache kept ready for an Opus recovery turn) or a Fable return marker (anchoring the Fable prefix when returning from Opus). If no slot is offered, Core skips the prefix hash and body clone. Every failed condition leaves the ordinary full body untouched and logs one content-free tail reason such as `prefix_changed`, `slot_taken` or `layout_unrecordable`. A create directly after a create, and a session that has only sent stateless requests, never gets this extra boundary. +All three hosts persist the full-after-thread cache-boundary metadata across restarts. A restart does not preserve a live continuation anchor. + **Wire safety:** 1-hour markers must precede every 5-minute marker. Core checks the final continuation after restoring fixed fields and budgeting message markers; invalid order falls back to the untouched full request rather than repairing the accepted fixed fields. Every accepted create records the fingerprint and last message marker from the body actually sent. Fixed annotation layouts must be recordable before a tail marker can replace another marker. **Recovery:** if Anthropic rejects a continue, the plugin resends once with the full conversation as a new thread. If that create is rejected for using threads, it resends once more statelessly and turns threads off for that account until restart. Removing the thread beta for that last retry changes the cache-prefix identity, so the retry keeps the ordinary full body's cache markers. A thread problem never reaches the user as an error when a stateless send would work. ## Content-filter fallback -- **Opt-in:** OAuth Fable 5, Fable 5.1, Opus 5 and Opus 5.5 requests opt into server-side fallback on OpenCode 1 and 2. +- **Opt-in:** OAuth Fable 5, Fable 5.1, Fable 5.2, Opus 5 and Opus 5.5 requests opt into server-side fallback on OpenCode 1 and 2. - **Boundary marker:** OpenCode cannot store Anthropic's `fallback` block, so the stream turns it into a signed hidden thinking marker (`cortexkit-server-fallback-v1:`). The next request turns it back into the exact `fallback` block before signing. - **Usage marker:** a fallback step's usage is the billed sum of both attempts. A second hidden marker (`cortexkit-server-fallback-usage-v1:`) carries the per-attempt breakdown for tools that size the context. It is stripped from every outgoing request. -- **Tool call before a refusal:** if a served fallback completes a tool call and then refuses, the finish becomes `tool_use`, so the tool doesn't run twice. -- **Recovery rounds (OpenCode 1 only):** a refusal the server fallback did not absorb starts a recovery round on Opus 4.8. During the round, keep-warm also keeps the original model's cache alive from its last sent body, so returning to it doesn't rebuild the prompt. `OPENCODE_ANTHROPIC_AUTH_FALLBACK_MODE=legacy` skips server fallback and uses recovery rounds only. +- **Tool call before a refusal (OpenCode 1 only):** in server-first recovery, if a served fallback completes a tool call and then refuses, the finish becomes `tool_use`, so the tool doesn't run twice. +- **Recovery rounds (OpenCode 1 only):** a refusal the server fallback did not absorb starts a recovery round on Opus 4.8. During the round, keep-warm also keeps the original model's cache alive from its last accepted body, so returning to it doesn't rebuild the prompt. `OPENCODE_ANTHROPIC_AUTH_FALLBACK_MODE=legacy` skips server fallback and uses recovery rounds only. OpenCode 2 relies on server-side fallback alone. Pi has neither server-side fallback nor client recovery. ## State layout -OpenCode 2 watches its config folder, so machine-written state should move out of it, into the user's state folder. +OpenCode 2 watches its config folder, so OpenCode's machine-written state moves into the user's state folder when the relocation fences allow it. -- **Release N (shipped in 2.4.0):** every process registers itself in `anthropic-auth-holders.json` beside the account files, and the relocation guards run inside the locks a move must hold. -- **The mover and restore:** both are written (`state-layout-move.ts`, `state-layout-restore.ts`), but `RELOCATION_MOVE_ENABLED` is `false`. Until that switch flips in its own release, every install keeps the legacy layout, and no code path may refuse an install that 2.4.x serves. +- **Decision:** OpenCode 1 and 2 run `decideOpenCodeStateLayout` before pool reads. They serve an already moved dataset, recover an unfinished transition, or move a legacy dataset after the holder and version fences find no older live writer. Explicit path overrides stay legacy. A start that creates the config folder does not move it on that start. +- **Move and restore:** `state-layout-move.ts` copies and verifies the closed file set under locks, installs legacy barriers, commits the move, then cleans old copies. A failure before commit rolls back; after commit the state folder serves and cleanup retries. `state-layout-restore.ts` restores the legacy layout. +- **Pi:** `decidePiStateLayout` registers and fences holders but keeps Pi's files in the legacy layout. They do not move. - **Storage id:** it is always derived from the legacy-layout path, so a move never changes it. ## Concurrency rules @@ -196,7 +208,8 @@ OpenCode 2 watches its config folder, so machine-written state should move out o - **Parse failures:** request bodies that can't be parsed pass through unchanged. Structural history errors and effort-plan mismatches refuse locally with a non-retryable 400, before cache shaping, signing, dumping or sending. - **Stream errors:** a transient `api_error` inside a 200 SSE stream becomes a connection-reset error, so the host retries it instead of storing it. -- **Redaction:** logs, dumps, sidebar state, RPC and menus never carry tokens, raw provider bodies or prompt text. Errors use fixed messages and closed codes. Dumps (`OPENCODE_ANTHROPIC_AUTH_DUMP_DIR`, default `opencode-anthropic-auth-dumps` in the temp folder) keep only an allowlisted response summary. +- **Redaction:** logs, sidebar state, RPC and menus never carry tokens, raw provider bodies or prompt text. Errors use fixed messages and a fixed set of error codes. +- **Dumps:** request `.body.json` files contain the outgoing request body and can contain prompts and tool content. Response `.response.json` files keep an allowlisted summary without response text. `OPENCODE_ANTHROPIC_AUTH_DUMP_DIR` overrides the default `opencode-anthropic-auth-dumps` folder in the temp directory. - **Logging:** the log goes to `opencode-anthropic-auth.log` in the temp folder, or to `OPENCODE_ANTHROPIC_AUTH_LOG_FILE`. ## Testing and gates diff --git a/STRUCTURE.md b/STRUCTURE.md index b8642ca70..c707b776b 100644 --- a/STRUCTURE.md +++ b/STRUCTURE.md @@ -34,13 +34,15 @@ docs/ public user and contributor documentation - **Menus:** `native-menu-model.ts`, `native-menu-executor.ts` and `native-ui.ts`. `commands/account.ts` holds the account command execution. - **Request:** - Claude Code shape: `claude-code.ts`, `cch.ts` (billing header and body signature), `constants.ts` (the emulated Claude Code version and betas). + - Paid API-key routes: `api-key-request.ts` (history checks, internal-marker cleanup and model aliases without OAuth shaping) and `api-route-url.ts` (saved URL and environment precedence). + - Cache diagnostics: `cache-diagnostics.ts` (previous-message tracking, record validation and debug formatting shared by all hosts). - Per-model handling: `model-capabilities.ts` (one row per model) and `models.ts` (catalogue and pricing). - Mid-conversation controls: `thinking-binding.ts`, `mid-conversation-output-config.ts` (effort markers) and `turn-end-note.ts`. - History and transport: `request-history.ts` (structural checks), `message-threads.ts`, `request-gzip.ts`, `relay.ts`, `oauth-origin.ts` and `request-abort.ts`. - **Routing and quota:** - Routing: `routing.ts` and `sticky-routing.ts`. - Quota policy: `killswitch.ts`, `quota-refusal.ts` and `session-cache-activity.ts`. - - Quota readings: `quota-manager.ts`, `quota-headers.ts`, `quota-header-feed.ts`, `insula-quota.ts` and `quotas.ts`. + - Quota readings: `quota-manager.ts`, `quota-headers.ts`, `insula-quota.ts` and `quotas.ts`. - **Cache:** `cache1h.ts`, `session-cache-policy.ts` (per-session policy from Thalamus), `cachekeep.ts`, `cachekeep-store.ts` (restart store), `cachekeep-registry.ts` (session list) and `prime.ts`. - **State layout:** `state-layout-*.ts`, `holder-registry.ts`, `layout-fence.ts`, `relocation-guard.ts` and `state-home-serving-guard.ts`. - **Shared plumbing:** `logger.ts`, `logging.ts`, `dump.ts`, `json.ts` (redacting JSON parse), `sse.ts`, `owner-only.ts`, `publication-rename.ts`, `network-errors.ts` and `provider-error.ts`. @@ -51,6 +53,7 @@ docs/ public user and contributor documentation - `index.ts`: the OpenCode 1 plugin factory. It must export only `AnthropicAuthPlugin`, because OpenCode's file loader calls every exported function. - `transform.ts`: OpenCode 1 request and stream rewriting. +- `cachekeep-restart.ts`: OpenCode 1 restart ownership, persistence and staggered restore. - **Shared by OpenCode 1 and 2:** - Server fallback and OpenCode 1 recovery rounds: `server-fallback.ts`, `fable-fallback.ts`. - Request plumbing: `effort-history.ts` (the effort plan), `billing-lineage.ts`, `lane-start.ts`, `routing-relay.ts` (shared routing), `prompt-context.ts`. @@ -72,7 +75,7 @@ docs/ public user and contributor documentation - `index.ts`: extension entry; registers the provider, commands and session hooks. - `convert.ts` and `transcript.ts`: build the Anthropic body from Pi's context. -- `stream.ts` and `transport.ts`: send, relay, threads and stream mapping. +- `stream.ts` and `transport.ts`: send, relay, threads, billing lineage, quota-header observation, cache diagnostics and stream mapping. - `native.ts` and `native-commands.ts`: the account runtime and menu. - `cachekeep.ts` and `cachekeep-claim.ts`: keep-warm, with the restart store and the per-session claim. - `prime.ts`: the Prime scheduler, which sends through `stream.ts`'s registered Prime sender. From 64080c127b5c5eabde85fdecfbbe96f88bf2a87e Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:11:20 +0100 Subject: [PATCH 16/27] Changelog: parity entries under Unreleased after the 2.16.6 release --- CHANGELOG.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 320b981d7..64ba0b0d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,19 +6,14 @@ This repo is a CortexKit-maintained Anthropic auth monorepo for OpenCode and Pi. - OpenCode 1, OpenCode 2 and Pi: when shared routing reports that every account is at its concurrent-request limit, requests wait for a free slot instead of ending the turn. - OpenCode: the one-time state move no longer treats a running older plugin as gone after the system clock is corrected forward. A start with a different XDG_STATE_HOME no longer moves the state while an earlier move under another state folder is unfinished; it stops and says to start again with the setting used then. - -## 2.16.6 - - OpenCode 1 CacheKeep can run a one-off prewarm again without dropping its normal account and destination checks. - Pi keep-warms no longer send the conversation's previous message ID to Claude. -- Changing effort mid-conversation now preserves the prompt cache in OpenCode v1, OpenCode v2, and Pi for Claude Mythos 5.1 and 5.2, and for Claude Opus 5 and Haiku 5.5 when adaptive thinking is on. - OpenCode 1: idle sessions can keep warming a still-live Claude prompt cache after a server restart without resetting their budgets; `auto` keep-warm now uses the accepted prefix's token counts to price warms, even without a restart. - OpenCode 1: after a server restart, a threaded session's first full request can reuse the previous full request's cache boundary, as on OpenCode 2 and Pi. - OpenCode 1 and Pi: eligible direct CacheKeep requests now use gzip, like OpenCode 2, and resend uncompressed if gzip is rejected. - OpenCode 1: keep-warm requests no longer appear in cache diagnostics or replace the previous real response, as on OpenCode 2. - OpenCode 1 and Pi now send paid API-key requests like OpenCode 2, without adding a Claude Code prompt or billing signature or renaming tools. Claude subscription requests are unchanged. - OpenCode 1, OpenCode 2 and Pi always verify TLS for API-key requests to custom HTTPS addresses. The `ANTHROPIC_INSECURE` environment variable is gone. -- Pi: changing thinking effort during a conversation now preserves the prompt cache on models that support per-message effort, including in conversations shortened by Magic Context. - OpenCode 2 now keeps custom proxy headers off Claude sign-in requests, like OpenCode 1 and Pi, while still sending them on API-key routes. - For conversation requests, OpenCode 2 now matches OpenCode 1: the first eligible request sends a null previous message ID, and cache results and beta lists appear in debug logs. - OpenCode 2: Claude subscription models now show zero token prices by default, like OpenCode 1. You can opt out to display catalogue prices; API-key prices are unchanged. @@ -36,6 +31,11 @@ This repo is a CortexKit-maintained Anthropic auth monorepo for OpenCode and Pi. - OpenCode 2 now uses the five-minute Claude prompt cache by default, like OpenCode 1 and Pi. An explicit cache setting or Agent Runner session policy still takes precedence. - OpenCode 1 no longer publishes the optional quota header feed; quota readings still reach the vault. The `quota_header_feed_enabled` setting is gone and can be deleted from your settings file. +## 2.16.6 + +- Changing effort mid-conversation now preserves the prompt cache in OpenCode v1, OpenCode v2, and Pi for Claude Mythos 5.1 and 5.2, and for Claude Opus 5 and Haiku 5.5 when adaptive thinking is on. +- Pi: changing thinking effort during a conversation now preserves the prompt cache on models that support per-message effort, including in conversations shortened by Magic Context. + ## 2.16.5 - OpenCode 2: the serving account's model-scoped weekly windows and credits now refresh from Insula (vault) or the regular poll (local) while response headers keep arriving, so the sidebar no longer shows a growing 'checked … ago' for it. From d09e41d0763c6ade82ef39cdd6d0b6a85f4a0c7a Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:12:44 +0100 Subject: [PATCH 17/27] OpenCode 1: a routing ask after a failed attempt doesn't wait for capacity inside the request --- .../src/tests/opencode1-routing-relay.test.ts | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/packages/opencode/src/tests/opencode1-routing-relay.test.ts b/packages/opencode/src/tests/opencode1-routing-relay.test.ts index e07377791..c10a30bdc 100644 --- a/packages/opencode/src/tests/opencode1-routing-relay.test.ts +++ b/packages/opencode/src/tests/opencode1-routing-relay.test.ts @@ -535,6 +535,40 @@ describe('OC1 shared routing relay', () => { expect(ids[1]).not.toBe(ids[0]) }) + // A retry ask comes after a failed attempt has used part of OpenCode 1's + // 5-minute response budget, so a full pool must become a host retry at once + // rather than a wait inside the request (a 2-minute wait here would also + // outlast the test's timeout). + for (const mode of ['sticky-balanced', 'main-first'] as const) { + test(`${mode} retry ask hands a full pool to the host without waiting`, async () => { + const f = await fixture( + 'normal', + () => new Response(null, { status: 403 }), + undefined, + mode === 'sticky-balanced' ? undefined : mode, + ) + const reset = Date.now() + 2 * 60_000 + let choices = 0 + globals[key] = () => ({ + accountFor: async () => + ++choices === 1 + ? mode === 'sticky-balanced' + ? { account_id: syntheticMainAccountUuid, credential_id: 'local' } + : null + : { refused: { code: 'concurrency_full', resets_at_ms: reset } }, + }) + const started = Date.now() + const response = await f.send() + expect(Date.now() - started).toBeLessThan(4_000) + expect(choices).toBe(2) + expect(response.status).toBe(429) + expect(await response.json()).toMatchObject({ + error: { code: 'concurrency_full' }, + }) + expect(f.sends).toHaveLength(1) + }) + } + test.each(['floor', 'reserve', 'unknown quota'])( 'routing quota trust serves OC1 advice despite %s', async (mode) => { From 49186bf9f6db6362a3860c76dcf0f6bf55b8aca3 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:13:26 +0100 Subject: [PATCH 18/27] Comment: say which host imposes the 5-minute limit --- packages/opencode/src/index.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index 101236013..96e66c679 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -10181,7 +10181,8 @@ const anthropicAuthPlugin = async ( ) } let sharedRoutingDecision = false - // OpenCode 1 ends a request that has no response after 5 minutes. + // The OpenCode 1 host (the app this plugin's fetch runs inside) + // abandons a model request that has no response after 5 minutes. // The first ask may wait up to 4 minutes for a free account slot. // An ask after a failed attempt has already spent part of that // budget, so it doesn't wait in the request: a full pool becomes From 5e7c897972030654f1d58bd3c90b7b2785eaf045 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:32:25 +0100 Subject: [PATCH 19/27] OpenCode 1 shared routing: provider waits, credential failures, paid fallback, revisits and refusal returns as on OpenCode 2 --- packages/opencode/src/index.ts | 323 ++++++++++++--- .../src/tests/opencode1-routing-relay.test.ts | 387 +++++++++++++++--- 2 files changed, 587 insertions(+), 123 deletions(-) diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index 96e66c679..4b1c04f13 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -243,6 +243,7 @@ import { startRoutingWait, startSettings, stateRefusalPublicMessage, + stickyQuotaBlockerInForce, stickyQuotaSnapshotIsFresh, stickyRouteCandidateWeight, stickyRouteFamilyForModel, @@ -9334,6 +9335,28 @@ const anthropicAuthPlugin = async ( } const responseRouteKinds = new WeakMap() + function cancelAbandonedResponse(response?: Response) { + void response?.body?.cancel().catch(() => {}) + } + + function scheduleServedFallbackQuotaRefresh( + account: OAuthAccount, + storage: Awaited>, + ) { + // Keep the serving fallback's quota fresh on the same cadence as + // main, without delaying the response or polling idle fallbacks. + if ( + !mainQuotaRoutingEnabled(storage) || + !quotaManager.shouldRefreshOnRequestCount(sessionRequestCount) + ) + return + // The native runtime obtains the credential for the quota poll. + void quotaManager + .refreshFallback(account.id, '', account) + .then(() => refreshSidebarQuota()) + .catch(() => {}) + } + const orderedRouting = new WeakMap< PerfTrace, { @@ -9367,17 +9390,17 @@ const anthropicAuthPlugin = async ( let lastResponse: Response | null = currentResponse ?? null const shared = trace && orderedRouting.get(trace) let canceledCurrentResponse = false - const cancelCurrentResponse = async () => { + const cancelCurrentResponse = () => { if (canceledCurrentResponse) return canceledCurrentResponse = true - await currentResponse?.body?.cancel().catch(() => {}) + cancelAbandonedResponse(currentResponse) } for (const [index, account] of accounts.entries()) { if (shared?.skipLocal(account.id)) continue let response: Response if (isApiKeyAccount(account)) { - await cancelCurrentResponse() + cancelCurrentResponse() response = await sendWithApiAccount( input, init, @@ -9409,7 +9432,7 @@ const anthropicAuthPlugin = async ( throw new Error( 'Native vault fallback credential is unavailable', ) - await cancelCurrentResponse() + cancelCurrentResponse() response = await sendWithAccessToken( input, init, @@ -9428,7 +9451,7 @@ const anthropicAuthPlugin = async ( getClaustrumMode(storage) === 'local' && account.access ) { - await cancelCurrentResponse() + cancelCurrentResponse() response = await sendWithAccessToken( input, init, @@ -9460,27 +9483,8 @@ const anthropicAuthPlugin = async ( ) options?.onSuccess?.(account) - // Active-route every-N refresh: this fallback just served the - // request, so keep its quota fresh on the same cadence as main. - // Non-blocking; only the served account, never idle fallbacks. - if ( - isOAuthAccount(account) && - mainQuotaRoutingEnabled(storage) && - quotaManager.shouldRefreshOnRequestCount(sessionRequestCount) - ) { - if (isScopedCustodyActive(storage) || account.access) { - void quotaManager - .refreshFallback( - account.id, - isScopedCustodyActive(storage) - ? '' - : (account.access ?? ''), - account, - ) - .then(() => refreshSidebarQuota()) - .catch(() => {}) - } - } + if (isOAuthAccount(account)) + scheduleServedFallbackQuotaRefresh(account, storage) return response } if (shared && isOAuthAccount(account)) { @@ -9491,7 +9495,7 @@ const anthropicAuthPlugin = async ( if (replacement) return replacement } if (index < accounts.length - 1 || !returnLastOnExhausted) { - await response.body?.cancel().catch(() => {}) + cancelAbandonedResponse(response) } } @@ -10242,19 +10246,101 @@ const anthropicAuthPlugin = async ( } let mainSharedRefusal: Response | undefined + let mainSharedCredentialError: + | NativeCredentialUnavailableError + | NativeModelPolicyError + | NativeUnsupportedCredentialError + | undefined if ( sessionId && - replayableRequest && getRoutingMode(storage) !== 'sticky-balanced' && hasSharedRouting() ) { const routingSessionId = sessionId - const refused = new Set() + const refused = new Map() + const revisited = new Set() + const unavailable = new Set() let triedSharedAccount = false const judged = new WeakSet() + function blockedOnRetry( + account: NativeAccountView, + snapshot: NativeAccountSnapshot, + ) { + if ( + unavailable.has(account.id) || + (account.id === 'main' && providerRestriction) + ) + return true + const responseHeaders = refused.get(account.id) + const quota = routingAccountQuota( + account, + snapshot.policyStorage, + ) + const now = runtimeNow() + return Boolean( + stickyQuotaBlockerInForce({ + quota: + responseHeaders || + stickyQuotaSnapshotIsFresh( + quota, + snapshot.policyStorage, + now, + routingModelId, + ) + ? quota + : undefined, + responseHeaders, + modelId: routingModelId, + now, + }), + ) + } + async function hasUntriedAlternative( + snapshot: NativeAccountSnapshot, + lastRefuser: string, + ) { + for (const row of routingCandidates(snapshot.accounts)) { + if ( + row.id === lastRefuser || + refused.has(row.id) || + blockedOnRetry(row, snapshot) || + routingRelay.policy( + routingSessionId, + row, + snapshot, + routingModelId, + ).status !== 'allowed' + ) + continue + if (row.source === 'vault') return true + const admission = await nativeAccounts.authorizeLocal( + row.id, + { + signal: init?.signal ?? undefined, + policy: (account, view) => + routingRelay.policy( + routingSessionId, + account, + view, + routingModelId, + ), + }, + ) + init?.signal?.throwIfAborted() + if (admission.status === 'usable') return true + unavailable.add(row.id) + } + return false + } async function consult( lastRefuser?: string, + localRefusal?: Response, ): Promise { + let lastSharedRefusal: Response | undefined + const abandonLastFallback = () => { + if (lastSharedRefusal !== mainSharedRefusal) + cancelAbandonedResponse(lastSharedRefusal) + } for (;;) { let pick: Awaited> try { @@ -10263,25 +10349,55 @@ const anthropicAuthPlugin = async ( lastRefuser === undefined ? undefined : 0, ) } catch (error) { + abandonLastFallback() if (error instanceof RoutingRefusalError) return error.response() throw error } const { advice, account, snapshot, routing } = pick - if (!advice) return + if (!advice) { + abandonLastFallback() + return + } + if (account?.id === 'main' && providerRestriction) { + abandonLastFallback() + routingRelay.override( + routingSessionId, + 'provider wait on main account', + ) + return + } if ( !account || + unavailable.has(account.id) || (advice.hold ? account.id !== lastRefuser - : refused.has(account.id) || - (lastRefuser && retryQuotaBlocked(account, snapshot))) + : lastRefuser !== undefined && + (account.id === lastRefuser || + blockedOnRetry(account, snapshot) || + (refused.has(account.id) && + (await hasUntriedAlternative( + snapshot, + lastRefuser, + ))))) ) { + abandonLastFallback() routingRelay.override( routingSessionId, 'unknown account, credential or retry policy', ) return } + // This fetch loop sends retries without a host retry limit. + // Allow one revisit per account so alternating advice ends. + if (!advice.hold && revisited.has(account.id)) { + routingRelay.override( + routingSessionId, + 'account retry budget spent', + ) + return lastSharedRefusal ?? localRefusal + } + abandonLastFallback() const selected = await routing.router.resolve({ sessionId: routingSessionId, family: stickyRouteFamilyForModel(routingModelId), @@ -10312,23 +10428,45 @@ const anthropicAuthPlugin = async ( return routingHoldResponse(advice.hold.retry_after_ms) countSessionRequest() triedSharedAccount = true - let response = await sendWithAccessToken( - input, - init, - '', - trace, - `routing:${account.id}`, - storage, - account.id, - undefined, - fableRequest, - laneStartRequest, - account.id === 'main' - ? requestMainQuotaIdentity - : undefined, - ) - let retry = shouldFallbackResponse(response, storage) - if (!retry) { + if (refused.has(account.id)) revisited.add(account.id) + let response: Response + try { + response = await sendWithAccessToken( + input, + init, + '', + trace, + `routing:${account.id}`, + storage, + account.id, + undefined, + fableRequest, + laneStartRequest, + account.id === 'main' + ? requestMainQuotaIdentity + : undefined, + ) + } catch (error) { + init?.signal?.throwIfAborted() + if ( + !(error instanceof NativeCredentialUnavailableError) && + !(error instanceof NativeModelPolicyError) && + !(error instanceof NativeUnsupportedCredentialError) + ) + throw error + unavailable.add(account.id) + if (account.id === 'main') + mainSharedCredentialError = error + routingRelay.override( + routingSessionId, + 'advised credential could not serve', + ) + return + } + let retry = + replayableRequest && + shouldFallbackResponse(response, storage) + if (replayableRequest && !retry) { const inspected = await inspectStreamingRateLimit( response, trace, @@ -10341,27 +10479,46 @@ const anthropicAuthPlugin = async ( account.id, account.id === 'main' ? 'main' : 'fallback', ) + const fallback = snapshot.policyStorage.accounts.find( + (row) => row.id === account.id, + ) + if ( + replayableRequest && + fallback && + isOAuthAccount(fallback) + ) + scheduleServedFallbackQuotaRefresh( + fallback, + snapshot.policyStorage, + ) return response } judged.add(response) - refused.add(account.id) + refused.set(account.id, response.headers) lastRefuser = account.id - if (account.id === 'main') mainSharedRefusal = response - else await response.body?.cancel().catch(() => {}) + lastSharedRefusal = response + if (account.id === 'main') { + cancelAbandonedResponse(mainSharedRefusal) + mainSharedRefusal = response + } } } orderedRouting.set(trace, { // Once shared routing sent on an account, the local loop // should try routes that have not refused this request yet. - skipLocal: (id) => triedSharedAccount && refused.has(id), + skipLocal: (id) => + unavailable.has(id) || + (triedSharedAccount && refused.has(id)), async afterRefusal(id, response) { - if (judged.has(response)) return + if (!replayableRequest || judged.has(response)) return judged.add(response) - refused.add(id) - const replacement = await consult(id) + refused.set(id, response.headers) + const replacement = await consult(id, response) if (replacement) { - await response.body?.cancel().catch(() => {}) - await mainSharedRefusal?.body?.cancel().catch(() => {}) + if (response !== replacement) + cancelAbandonedResponse(response) + if (mainSharedRefusal !== replacement) + cancelAbandonedResponse(mainSharedRefusal) mainSharedRefusal = undefined } return replacement @@ -10369,7 +10526,8 @@ const anthropicAuthPlugin = async ( }) const selected = await consult() if (selected) { - await mainSharedRefusal?.body?.cancel().catch(() => {}) + if (mainSharedRefusal !== selected) + cancelAbandonedResponse(mainSharedRefusal) return wrapResponse(selected) } if (mainSharedRefusal) @@ -11031,6 +11189,7 @@ const anthropicAuthPlugin = async ( mainQuotaIdentity: requestMainQuotaIdentity, }) const rejectedInitialAdvice = advice && !advisedAccountId + let retryAdviceGiven = false advisedAccountId = undefined if (hasSharedRouting()) { let pick: Awaited> @@ -11038,13 +11197,12 @@ const anthropicAuthPlugin = async ( pick = await askSharedRouting(sessionId, 0) } catch (error) { if (error instanceof RoutingRefusalError) - await inspected.response.body - ?.cancel() - .catch(() => {}) + cancelAbandonedResponse(inspected.response) throw error } const { advice: retryAdvice, account, snapshot } = pick if (retryAdvice) { + retryAdviceGiven = true const eligible = account && stickyRoutes.allRoutes.some( @@ -11055,9 +11213,7 @@ const anthropicAuthPlugin = async ( retryAdvice.hold && account.id === failedRouteId ) { - await inspected.response.body - ?.cancel() - .catch(() => {}) + cancelAbandonedResponse(inspected.response) return routingHoldResponse( retryAdvice.hold.retry_after_ms, ) @@ -11120,6 +11276,7 @@ const anthropicAuthPlugin = async ( } } else if ( !rejectedInitialAdvice && + !retryAdviceGiven && (inspected.response.status === 429 || inspected.streamingRateLimit) && mainQuotaEntryIsFreshExhausted( @@ -11189,7 +11346,7 @@ const anthropicAuthPlugin = async ( ), ) ) { - await inspected.response.body?.cancel().catch(() => {}) + cancelAbandonedResponse(inspected.response) return completeRoute(route, await noRouteResponse()) } return completeRoute(route, inspected.response) @@ -11273,6 +11430,40 @@ const anthropicAuthPlugin = async ( if (mainSharedRefusal) return continueAfterSharedMainRefusal(mainSharedRefusal) + if (mainSharedCredentialError) { + const fallbackAccounts = + replayableRequest && + getRoutingMode(storage) !== 'fallback-first' + ? await getRoutableFallbackAccounts(storage, { + modelId: requestModelId, + }) + : [] + const response = await tryUsableFallbackAccounts( + input, + init, + fallbackAccounts, + storage, + undefined, + trace, + { + onSuccess: (account) => + writeCurrentSidebarState(account.id, 'fallback'), + fableRequest, + laneStartRequest, + }, + ) + if (response) return wrapResponse(response) + if (mainSharedCredentialError instanceof NativeModelPolicyError) + return modelDeniedResponse() + if ( + isScopedCustodyActive(storage) && + mainSharedCredentialError instanceof + NativeCredentialUnavailableError + ) + throw new NativeVaultNoAccountError() + throw mainSharedCredentialError + } + // Fallback-first reached main only after its fallback attempts. // Resolve current access now; absence from the earlier metadata // view is not evidence that the stored token needs refreshing. diff --git a/packages/opencode/src/tests/opencode1-routing-relay.test.ts b/packages/opencode/src/tests/opencode1-routing-relay.test.ts index c10a30bdc..d48f5f095 100644 --- a/packages/opencode/src/tests/opencode1-routing-relay.test.ts +++ b/packages/opencode/src/tests/opencode1-routing-relay.test.ts @@ -1,7 +1,8 @@ -import { afterEach, describe, expect, mock } from 'bun:test' +import { afterEach, describe, expect, mock, spyOn } from 'bun:test' import { gunzipSync } from 'node:zlib' import { tokenFingerprint } from '@cortexkit/anthropic-auth-core' import { ROUTING_HOLD_LIMIT_MS } from '../routing-relay' +import { getPluginTestHandles } from './plugin-test-handles' import { installLoaderSetup } from './support/opencode1-loader-setup' import { bindPoolAccounts, @@ -89,32 +90,66 @@ describe('OC1 shared routing relay', () => { ), mainQuotaCheckedAt: now, mainQuotaToken: tokenFingerprint('sk-ant-oat01-main-access'), + ...(mode === 'provider wait' && { + mainLastQuotaApiError: { + message: 'usage wait', + checkedAt: now, + nextRetryAt: now + 60_000, + accountIdentity: syntheticMainAccountUuid, + }, + }), + ...(mode === 'refresh cadence' && { refreshEveryNRequests: 1 }), }, ...(mode === 'floor' || mode === 'blocked' ? { killswitch: { enabled: true, main: { five_hour: 20 } } } : {}), - accounts: [ - { - id: 'fallback-1', - type: 'oauth', - access: 'sk-ant-oat01-fallback-access', - refresh: 'fallback-refresh', - expires: now + 3600_000, - quota: - mode === 'unknown quota' - ? undefined - : quota(mode === 'floor' || mode === 'blocked' ? 10 : 80), - ...(mode === 'signed out' - ? { - lastRefreshError: { - message: 'sign in required', - checkedAt: now, - permanent: true, - }, - } - : {}), - }, - ], + accounts: + mode === 'paid backup' + ? [ + { + id: 'paid', + type: 'api', + apiKey: 'paid-key', + baseURL: 'https://paid.example.test', + authHeader: 'authorization-bearer', + }, + ] + : [ + { + id: 'fallback-1', + type: 'oauth', + access: 'sk-ant-oat01-fallback-access', + refresh: 'fallback-refresh', + expires: now + 3600_000, + quota: + mode === 'unknown quota' + ? undefined + : quota( + mode === 'floor' || mode === 'blocked' ? 10 : 80, + ), + ...(mode === 'signed out' + ? { + lastRefreshError: { + message: 'sign in required', + checkedAt: now, + permanent: true, + }, + } + : {}), + }, + ...(mode === 'three accounts' + ? [ + { + id: 'fallback-2', + type: 'oauth' as const, + access: 'sk-ant-oat01-third-access', + refresh: 'third-refresh', + expires: now + 3600_000, + quota: quota(80), + }, + ] + : []), + ], }), ), ) @@ -140,7 +175,9 @@ describe('OC1 shared routing relay', () => { ?.includes('fallback') ? {} : { - five_hour: { utilization: 0 }, + five_hour: { + utilization: mode === 'paid backup' ? 100 : 0, + }, seven_day: { utilization: 0 }, }, ), @@ -175,23 +212,33 @@ describe('OC1 shared routing relay', () => { }), { models: {} } as any, )) as any - const send = (payload?: Record) => + const send = ( + payload?: Record | ReadableStream, + ) => loader.fetch(MESSAGES_URL, { method: 'POST', headers: { 'x-session-affinity': 'ses_relay_oc1' }, - body: JSON.stringify( - payload ?? { - model: mode.startsWith('fable') - ? 'claude-fable-5' - : mode === 'reserve' - ? 'claude-opus-4-8' - : 'claude-sonnet-5', - messages: [{ role: 'user', content: 'hello' }], - max_tokens: 10, - }, - ), + body: + payload instanceof ReadableStream + ? payload + : JSON.stringify( + payload ?? { + model: mode.startsWith('fable') + ? 'claude-fable-5' + : mode === 'reserve' + ? 'claude-opus-4-8' + : 'claude-sonnet-5', + messages: [{ role: 'user', content: 'hello' }], + max_tokens: 10, + }, + ), }) as Promise - return { sends, send, bodies } + return { + sends, + send, + bodies, + ...getPluginTestHandles(plugin), + } } test('OC1 OAuth sends runner notes from its session handle in the final signed body', async () => { @@ -266,39 +313,36 @@ describe('OC1 shared routing relay', () => { // Establish a different sticky assignment before the runner asks to move it. await (await f.send()).text() expect(f.sends.at(-1)).toBe('Bearer sk-ant-oat01-main-access') - const reports: unknown[] = [] + const reports: Record[] = [] let answer: unknown = { account_id: syntheticFallbackAccountUuid(0), credential_id: 'local', } globals[key] = () => ({ accountFor: async () => answer, - report: (value: unknown) => { + report: (value: Record) => { reports.push(value) throw new Error('report failure cannot fail the request') }, }) await (await f.send()).text() expect(f.sends.at(-1)).toBe('Bearer sk-ant-oat01-fallback-access') - const routingReports = (): unknown[] => - reports.filter( - (report) => - typeof report === 'object' && - report !== null && - 'outcome' in report && - report.outcome === 'served', - ) - expect(routingReports()).toEqual([ - { - account_id: syntheticFallbackAccountUuid(0), - outcome: 'served', - headers: { 'anthropic-ratelimit-future': 'all' }, - }, - ]) + const routingReports = () => + reports.filter((report) => report.kind !== 'billing') + const touch = expect.objectContaining({ + kind: 'cache_touch', + source: 'response', + }) + const served = { + account_id: syntheticFallbackAccountUuid(0), + outcome: 'served', + headers: { 'anthropic-ratelimit-future': 'all' }, + } + expect(routingReports()).toEqual([touch, served]) answer = null await (await f.send()).text() expect(f.sends.at(-1)).toBe('Bearer sk-ant-oat01-fallback-access') - expect(routingReports()).toHaveLength(2) + expect(routingReports()).toEqual([touch, served, touch, served]) }) for (const [mode, accountId, token] of [ @@ -318,6 +362,235 @@ describe('OC1 shared routing relay', () => { }) } + test('ordered routing overrides main advice before acquiring its bearer during a provider wait', async () => { + const f = await fixture( + 'provider wait', + undefined, + undefined, + 'fallback-first', + ) + const authorizeLocal = spyOn(f.nativeAccounts, 'authorizeLocal') + globals[key] = () => ({ + accountFor: async () => ({ + account_id: syntheticMainAccountUuid, + credential_id: 'local', + }), + }) + try { + expect(await (await f.send()).text()).toBe('ok') + expect(f.sends).toEqual(['Bearer sk-ant-oat01-fallback-access']) + expect(authorizeLocal.mock.calls.map(([id]) => id)).not.toContain('main') + } finally { + authorizeLocal.mockRestore() + } + }) + + test('ordered routing tries a healthy login when the advised credential cannot refresh', async () => { + const f = await fixture('normal', undefined, undefined, 'main-first') + const authorize = f.nativeAccounts.authorizeLocal.bind(f.nativeAccounts) + const authorizeLocal = spyOn( + f.nativeAccounts, + 'authorizeLocal', + ).mockImplementation(async (id, options) => + id === 'fallback-1' + ? { + status: 'failed', + failure: { + kind: 'provider', + classification: 'invalid-grant', + status: 400, + }, + persisted: true, + reconciliationFailed: false, + } + : authorize(id, options), + ) + globals[key] = () => ({ + accountFor: async () => ({ + account_id: syntheticFallbackAccountUuid(0), + credential_id: 'local', + }), + }) + try { + expect(await (await f.send()).text()).toBe('ok') + expect(authorizeLocal).toHaveBeenCalledWith( + 'fallback-1', + expect.objectContaining({ intent: 'serve' }), + ) + expect(f.sends).toEqual(['Bearer sk-ant-oat01-main-access']) + } finally { + authorizeLocal.mockRestore() + } + }) + + test.each(['recovered', 'exhausted', 'alternative'])( + 'ordered routing revisits an earlier refuser only when appropriate (%s)', + async (scenario) => { + let sends = 0 + const f = await fixture( + scenario === 'alternative' ? 'three accounts' : 'normal', + () => { + sends++ + return scenario !== 'exhausted' && sends === 3 + ? new Response('recovered') + : new Response(`refusal ${sends}`, { status: 403 }) + }, + undefined, + 'main-first', + ) + let asks = 0 + globals[key] = () => ({ + accountFor: async () => ({ + account_id: + asks++ % 2 === 0 + ? syntheticMainAccountUuid + : syntheticFallbackAccountUuid(0), + credential_id: 'local', + }), + }) + const response = await f.send() + const main = 'Bearer sk-ant-oat01-main-access' + const fallback = 'Bearer sk-ant-oat01-fallback-access' + if (scenario === 'exhausted') { + expect(response.status).toBe(403) + expect(await response.text()).toBe('refusal 4') + expect(f.sends).toEqual([main, fallback, main, fallback]) + expect(asks).toBe(5) + } else { + expect(response.status).toBe(200) + expect(await response.text()).toBe('recovered') + expect(f.sends).toEqual([ + main, + fallback, + scenario === 'alternative' + ? 'Bearer sk-ant-oat01-third-access' + : main, + ]) + } + }, + ) + + test('ordered routing schedules the serving fallback quota refresh without waiting', async () => { + const f = await fixture( + 'refresh cadence', + undefined, + undefined, + 'main-first', + ) + const pending = + Promise.withResolvers< + Awaited> + >() + const refreshFallback = spyOn( + f.quotaManager, + 'refreshFallback', + ).mockReturnValue(pending.promise) + globals[key] = () => ({ + accountFor: async () => ({ + account_id: syntheticFallbackAccountUuid(0), + credential_id: 'local', + }), + }) + try { + expect(await (await f.send()).text()).toBe('ok') + expect(f.sends).toEqual(['Bearer sk-ant-oat01-fallback-access']) + expect( + refreshFallback.mock.calls.map(([id, access]) => [id, access]), + ).toEqual([['fallback-1', '']]) + } finally { + pending.reject(new Error('fixture quota poll ended')) + await pending.promise.catch(() => {}) + refreshFallback.mockRestore() + } + }) + + for (const mode of ['sticky-balanced', 'main-first'] as const) { + test(`${mode} returns routing refusal while abandoned body cancellation is pending`, async () => { + const upstream = new Response('upstream refusal', { status: 403 }) + const cancel = Promise.withResolvers() + const cancelBody = spyOn(upstream.body!, 'cancel').mockReturnValue( + cancel.promise, + ) + const f = await fixture('normal', () => upstream, undefined, mode) + let asks = 0 + globals[key] = () => ({ + accountFor: async () => + ++asks === 1 + ? { + account_id: + mode === 'sticky-balanced' + ? syntheticMainAccountUuid + : syntheticFallbackAccountUuid(0), + credential_id: 'local', + } + : { refused: { code: 'account_selection_final' } }, + }) + const request = f.send() + try { + const response = await Promise.race([ + request, + Bun.sleep(1_000).then(() => null), + ]) + expect(response).not.toBeNull() + expect(response?.status).toBe(403) + expect(await response?.json()).toMatchObject({ + error: { code: 'account_selection_final' }, + }) + expect(cancelBody).toHaveBeenCalledTimes(1) + expect(asks).toBe(2) + } finally { + cancel.resolve() + await Promise.allSettled([request]) + cancelBody.mockRestore() + } + }) + } + + test('ordered routing asks before sending a non-replayable request', async () => { + const f = await fixture('normal', undefined, undefined, 'main-first') + const accountFor = mock(async () => ({ + refused: { code: 'account_selection_final' }, + })) + globals[key] = () => ({ accountFor }) + const response = await f.send( + new ReadableStream({ start: (controller) => controller.close() }), + ) + expect(response.status).toBe(403) + expect(await response.json()).toMatchObject({ + error: { code: 'account_selection_final' }, + }) + expect(accountFor).toHaveBeenCalledTimes(1) + expect(f.sends).toEqual([]) + }) + + test.each([true, false])( + 'sticky retry advice blocks paid fallback only when given (%s)', + async (advised) => { + let sends = 0 + const f = await fixture('paid backup', () => + ++sends === 1 + ? new Response('usage limit reached', { status: 429 }) + : new Response('paid'), + ) + let asks = 0 + globals[key] = () => ({ + accountFor: async () => + ++asks === 2 && advised + ? { account_id: syntheticMainAccountUuid, credential_id: 'local' } + : null, + }) + const response = await f.send() + expect(asks).toBe(2) + expect(response.status).toBe(advised ? 429 : 200) + await response.text() + expect(f.sends).toEqual( + advised + ? ['Bearer sk-ant-oat01-main-access'] + : ['Bearer sk-ant-oat01-main-access', 'Bearer paid-key'], + ) + }, + ) + test('sticky reroute asks shared routing again and honors a final refusal', async () => { const f = await fixture('normal', () => new Response(null, { status: 403 })) let choices = 0 @@ -678,8 +951,8 @@ describe('OC1 shared routing relay', () => { const reports: unknown[] = [] globals[key] = () => ({ accountFor: async () => null, - report: (report: { outcome?: string }) => { - if (report.outcome === 'served') reports.push(report) + report: (report: { kind?: string }) => { + if (report.kind !== 'billing') reports.push(report) }, }) await (await f.send()).text() From 3f7542c06c7f10108833e7967dc60bfb9fd822bb Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:35:56 +0100 Subject: [PATCH 20/27] Pi: paid requests keep Pi's own cache markers; hybrid layout independent of lifetime; first-prompt and fork lookback; lane start by queued action; /claude refresh and killswitch edits as on OpenCode 2 --- packages/pi/src/commands.ts | 8 +- packages/pi/src/convert.ts | 136 ++++++++----- packages/pi/src/index.ts | 14 +- packages/pi/src/lane-start.ts | 75 +++++++ packages/pi/src/native-commands.ts | 23 ++- packages/pi/src/stream.ts | 31 ++- packages/pi/src/tests/commands.test.ts | 48 +++++ packages/pi/src/tests/convert.test.ts | 131 ++++++++++++ packages/pi/src/tests/prime.test.ts | 189 ++++++++++++++---- .../src/tests/request-history-stream.test.ts | 13 +- packages/pi/src/tests/scoped-stream.test.ts | 67 +++++-- .../pi/src/tests/session-cache-policy.test.ts | 71 ++++++- 12 files changed, 685 insertions(+), 121 deletions(-) create mode 100644 packages/pi/src/lane-start.ts diff --git a/packages/pi/src/commands.ts b/packages/pi/src/commands.ts index e2ee95a5b..bbefaae8e 100644 --- a/packages/pi/src/commands.ts +++ b/packages/pi/src/commands.ts @@ -2,7 +2,6 @@ import { join } from 'node:path' import { createNativeUi, disconnectNativeVaultForHost, - LANE_START_TEXT, type NativeMenuCommandId, type NativeMenuDispatch, type NativeUiOptions, @@ -11,6 +10,7 @@ import { runPiCommandMenu, } from '@cortexkit/anthropic-auth-core' import { type ExtensionAPI, getAgentDir } from '@earendil-works/pi-coding-agent' +import { queuePiLaneStart } from './lane-start.ts' /** Backend callbacks use native authority; the renderer never receives credentials. */ export interface PiNativeCommands { @@ -63,13 +63,16 @@ export function registerCommands(pi: ExtensionAPI, backend: PiNativeCommands) { return } const disconnect = backend.disconnectVault ?? disconnectPi + const sessionId = ctx.sessionManager.getSessionId() const queueLaneStart = () => { if ( ctx.model?.provider !== 'anthropic' || ctx.model.api !== 'anthropic-messages' ) throw new Error('Lane start requires an active Claude model') - pi.sendUserMessage(LANE_START_TEXT, { deliverAs: 'followUp' }) + pi.sendUserMessage(queuePiLaneStart(sessionId), { + deliverAs: 'followUp', + }) } const menu = createNativeUi({ host: 'pi', @@ -99,7 +102,6 @@ export function registerCommands(pi: ExtensionAPI, backend: PiNativeCommands) { }, interactive: ctx.hasUI, }) - const sessionId = ctx.sessionManager.getSessionId() if (ctx.hasUI) { await runPiCommandMenu(menu, ctx.ui, { sessionId }) } else { diff --git a/packages/pi/src/convert.ts b/packages/pi/src/convert.ts index 0ab409a55..eb1f9a6f2 100644 --- a/packages/pi/src/convert.ts +++ b/packages/pi/src/convert.ts @@ -29,7 +29,6 @@ import { isClaudeSonnet55Model, isFastModeSupportedModel, isOpenAIReasoningSignature, - LANE_START_TEXT, orderClaudeCodeBody, prepareApiKeyRequestBody, readSessionCachePolicy, @@ -43,6 +42,7 @@ import type { Context, ImageContent, Message, + Model, SimpleStreamOptions, TextContent, ThinkingContent, @@ -56,6 +56,7 @@ import { PiForkRefusal, piForkHeadSession, } from './forks.ts' +import { isPiLaneStartMessage, stripPiLaneStartNonce } from './lane-start.ts' import { collapseSystemMessages, getCurrentSystemPrompt, @@ -464,6 +465,52 @@ function addEphemeralCacheControl(body: AnthropicRequestBody): void { } } +/** Keep Pi's native system, tool and conversation markers without the OAuth lookback bridge. */ +function applyPiApiKeyCache( + body: AnthropicRequestBody, + options: SimpleStreamOptions | undefined, + compat: Model<'anthropic-messages'>['compat'], +): void { + const retention = + options?.cacheRetention ?? + ((options?.env?.PI_CACHE_RETENTION || process.env.PI_CACHE_RETENTION) === + 'long' + ? 'long' + : 'short') + if (retention === 'none') return + const control = { + type: 'ephemeral', + ...(retention === 'long' && compat?.supportsLongCacheRetention !== false + ? { ttl: '1h' } + : {}), + } + const system = body.system?.at(-1) + if (system) system.cache_control = control + const tool = body.tools?.at(-1) + if (tool && compat?.supportsCacheControlOnTools !== false) + tool.cache_control = control + + const last = body.messages.at(-1) + if (last?.role !== 'user' && last?.role !== 'system') return + if (typeof last.content === 'string') { + last.content = [ + { type: 'text', text: last.content, cache_control: control }, + ] + } else if (Array.isArray(last.content)) { + const block = last.content.at(-1) + if ( + [ + 'text', + 'image', + 'tool_result', + 'tool_addition', + 'tool_removal', + ].includes(block?.type) + ) + block.cache_control = control + } +} + /** * Flatten a host system prompt to text. * @@ -605,7 +652,8 @@ function applyForkCacheBridge( : blocks.findLast((block) => block.cache_control) const newestPosition = newest === body ? blocks.length - 1 : blocks.indexOf(newest ?? {}) - if (!newest || newestPosition - blocks.indexOf(baseBlock) <= 20) return + // Both the new and retained boundaries count toward the 20-block window. + if (!newest || newestPosition - blocks.indexOf(baseBlock) < 20) return const control = newest.cache_control as Record const holders: Record[] = [] walkCacheControlHolders(body, (holder) => holders.push(holder)) @@ -643,11 +691,9 @@ function applyForkCacheBridge( /** Find the previous boundary when the latest one's lookback cannot reach it. */ function hybridLookbackBridge(messages: unknown[]) { let position = 0 - let previous: - | { message: Record; index: number; end: number } - | undefined + let previous: { message: Record; end: number } | undefined let latest: typeof previous - for (const [index, value] of messages.entries()) { + for (const value of messages) { if (!value || typeof value !== 'object') continue const message = value as Record const content = message.content @@ -661,15 +707,12 @@ function hybridLookbackBridge(messages: unknown[]) { position += blocks if (message.role === 'user' && blocks > 0) { previous = latest - latest = { message, index, end: position } + latest = { message, end: position } } } - // OpenCode reserves the first two messages for its fixed prefix. It counts - // both boundary blocks when checking Anthropic's 20-block search window. - return previous && - previous.index > 1 && - latest && - latest.end - previous.end + 1 > 20 + // Pi has no fixed marker at the tail of its first user message. Count both + // boundaries in Anthropic's lookback, even when the earlier one is first. + return previous && latest && latest.end - previous.end + 1 > 20 ? previous.message : undefined } @@ -706,29 +749,25 @@ function applyHybridCacheBridge(body: AnthropicRequestBody) { * Each mode now places its own breakpoints and nothing else, as the OpenCode * rewrite path does (`applyAutomaticCache1h` / `applyHybridCache1h` both clear * every breakpoint first): - * - `automatic`: the top-level control alone, at 1h. - * - `hybrid`: the four block breakpoints extended to 1h, with the system slot + * - `automatic`: the top-level control alone. + * - `hybrid`: the four block breakpoints, with the system slot * available for a lookback bridge on an ordinary request. * - `explicit`: the same four breakpoints, TTL only. */ function applyCacheMode( body: AnthropicRequestBody, - enabled: boolean, + long: boolean, mode: Cache1hMode, ): void { - if (!enabled) return - if (mode === 'automatic') { walkCacheControlHolders(body, (holder) => { delete holder.cache_control }) - body.cache_control = { type: 'ephemeral', ttl: '1h' } + body.cache_control = { type: 'ephemeral', ...(long && { ttl: '1h' }) } return } - walkCacheControlHolders(body, (holder) => { - ;(holder.cache_control as Record).ttl = '1h' - }) + if (long) applySessionCacheTtl(body, 'long') } /** Let a full request after a thread reuse its last full-request cache boundary. */ @@ -761,6 +800,8 @@ export async function buildAnthropicRequest( controls: { /** Convert Pi's typed context without adding Claude Code wire shaping. */ apiKey?: boolean + apiKeyModelCompat?: Model<'anthropic-messages'>['compat'] + laneStart?: boolean billingLineage?: BillingLineageFields effortTransitions?: readonly PiEffortTransition[] forkBaseMessageCount?: number @@ -788,6 +829,7 @@ export async function buildAnthropicRequest( forkEffortApplied?: PiForkEffortHint }> { const apiKey = controls.apiKey === true + for (const message of context.messages) stripPiLaneStartNonce(message) const mapToolName = apiKey ? (name: string) => name : toClaudeCodeToolName const forkBase = controls.forkBaseMessageCount === undefined @@ -814,17 +856,6 @@ export async function buildAnthropicRequest( systemPrompt: getCurrentSystemPrompt(transcript.messages), tools: getCurrentTools(transcript.messages), } - // Pi delivers extension prompts as ordinary user messages. Only the exact - // marker as the newest user message is a lane start; older markers are history. - const userContent = context.messages.findLast( - (message) => message.role === 'user', - )?.content - const laneStart = - typeof userContent === 'string' - ? userContent === LANE_START_TEXT - : userContent?.length === 1 && - userContent[0]?.type === 'text' && - userContent[0].text === LANE_START_TEXT // Conversion can discard opaque or incomplete blocks. Check context.messages // first so those losses cannot hide a meaningful final assistant turn. Check // the Anthropic messages again after conversion removes empty user messages. @@ -879,7 +910,9 @@ export async function buildAnthropicRequest( identity && !forkHead && controls.billingLineage?.promptId ? { ...controls.billingLineage, - promptIndex: countUserPrompts(messages), + promptIndex: + countUserPrompts(messages) - + context.messages.filter(isPiLaneStartMessage).length, } : undefined, ), @@ -1001,12 +1034,14 @@ export async function buildAnthropicRequest( } } - const forkEffortApplied = applyPiForkEffort( - body, - controls.effortTransitions ?? [], - controls.forkEffort, - baseLastMessage, - ) + const forkEffortApplied = apiKey + ? undefined + : applyPiForkEffort( + body, + controls.effortTransitions ?? [], + controls.forkEffort, + baseLastMessage, + ) body.messages = body.messages.filter( (message) => !droppedAssistants.has(message), ) @@ -1025,14 +1060,17 @@ export async function buildAnthropicRequest( const cachePolicy = apiKey ? undefined : readSessionCachePolicy(options?.sessionId, !!identity) - if (!apiKey) { + if (apiKey) { + applyPiApiKeyCache(body, options, controls.apiKeyModelCompat) + } else { addEphemeralCacheControl(body) - const cacheEnabled = - cachePolicy?.ttl !== undefined - ? cachePolicy.ttl !== 'none' - : cache.enabled - applyCacheMode(body, cacheEnabled, cache.mode) - if (cacheEnabled && cache.mode === 'hybrid' && !forkHead && !forkBase) + applyCacheMode( + body, + cachePolicy?.ttl === 'long' || + (cachePolicy?.ttl === undefined && cache.enabled), + cache.mode, + ) + if (cache.mode === 'hybrid' && !forkHead && !forkBase) applyHybridCacheBridge(body) } if (identity) { @@ -1051,13 +1089,13 @@ export async function buildAnthropicRequest( : undefined if (replaced !== undefined) body = { ...(replaced as AnthropicRequestBody), stream: true } - if (laneStart) { + if (controls.laneStart) { body.max_tokens = 1 delete body.thinking } if (apiKey) prepareApiKeyRequestBody(body) else applySessionCacheTtl(body, cachePolicy?.ttl) - if (baseBoundary >= 0) applyForkCacheBridge(body, baseBoundary) + if (!apiKey && baseBoundary >= 0) applyForkCacheBridge(body, baseBoundary) // As in Pi's native adapter, replacements must still request SSE. Hooks own // the validity of their other edits and must not add a fifth cache breakpoint: // the provider's existing layout may already use Anthropic's four slots. diff --git a/packages/pi/src/index.ts b/packages/pi/src/index.ts index 339533e45..009a38315 100644 --- a/packages/pi/src/index.ts +++ b/packages/pi/src/index.ts @@ -35,6 +35,11 @@ import type { import { registerCommands } from './commands.ts' import { collectPiRequestEffortHistory } from './effort-history.ts' import { piForkEffortSnapshots, piForkHeadSession } from './forks.ts' +import { + forgetPiLaneStarts, + isPiLaneStartMessage, + stripPiLaneStartNonce, +} from './lane-start.ts' import { closePiNativeRuntime, getPiNativeRuntime, @@ -207,7 +212,13 @@ export default async function cortexKitPiAnthropicAuth( pi.on('message_start', async (event, ctx) => { if (event.message.role !== 'user') return const sessionId = ctx.sessionManager.getSessionId() - if (sessionId) observePiUserPrompt(storagePath, sessionId) + stripPiLaneStartNonce(event.message, sessionId) + if (sessionId) + observePiUserPrompt( + storagePath, + sessionId, + isPiLaneStartMessage(event.message), + ) }) pi.on('agent_settled', async (_event, ctx) => { const sessionId = ctx.sessionManager.getSessionId() @@ -222,6 +233,7 @@ export default async function cortexKitPiAnthropicAuth( clearPiStickyQuotaRetries(storagePath, sessionId) effortSessionManagers.delete(sessionId) piForkEffortSnapshots.forget(sessionId) + forgetPiLaneStarts(sessionId) workingMessageBySession.delete(sessionId) sessionCacheActivity.forget(sessionId) forgetPiMessageThread(sessionId, 'session_closed') diff --git a/packages/pi/src/lane-start.ts b/packages/pi/src/lane-start.ts new file mode 100644 index 000000000..3e1a02f2d --- /dev/null +++ b/packages/pi/src/lane-start.ts @@ -0,0 +1,75 @@ +import { randomUUID } from 'node:crypto' +import { LANE_START_TEXT } from '@cortexkit/anthropic-auth-core' +import type { Message } from '@earendil-works/pi-ai' + +type LaneUserMessage = Extract & { + cortexkitLaneStart?: true +} + +const marker = `${LANE_START_TEXT}\n[cortexkit lane start: ` +const sessions = new Map; ready?: number }>() + +export function queuePiLaneStart(sessionId: string): string { + const state = sessions.get(sessionId) ?? { pending: new Set() } + const nonce = randomUUID() + state.pending.add(nonce) + sessions.delete(sessionId) + sessions.set(sessionId, state) + if (sessions.size > 128) { + const oldest = sessions.keys().next().value + if (oldest !== undefined) sessions.delete(oldest) + } + return `${marker}${nonce}]` +} + +export function forgetPiLaneStarts(sessionId: string): void { + sessions.delete(sessionId) +} + +/** Pi rebuilds queued user messages from text; strip its delivery token before display or persistence. */ +export function stripPiLaneStartNonce( + message: Message, + sessionId?: string, +): void { + if (message.role !== 'user') return + const content = message.content + const block = + Array.isArray(content) && content.length === 1 ? content[0] : undefined + const text = + typeof content === 'string' + ? content + : block?.type === 'text' + ? block.text + : undefined + if (!text?.startsWith(marker) || !text.endsWith(']')) return + const nonce = text.slice(marker.length, -1) + if (!/^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/.test(nonce)) return + if (block?.type === 'text') block.text = LANE_START_TEXT + else message.content = LANE_START_TEXT + const state = sessionId ? sessions.get(sessionId) : undefined + if (state?.pending.delete(nonce)) { + ;(message as LaneUserMessage).cortexkitLaneStart = true + state.ready = message.timestamp + } +} + +export function isPiLaneStartMessage(message: Message): boolean { + return ( + message.role === 'user' && + (message as LaneUserMessage).cortexkitLaneStart === true + ) +} + +export function takePiLaneStart( + messages: Message[], + sessionId?: string, +): boolean { + // Dispatch also sees the raw marker on hosts that did not deliver message_start. + for (const message of messages) stripPiLaneStartNonce(message, sessionId) + const state = sessionId ? sessions.get(sessionId) : undefined + if (!state || state.ready === undefined) return false + const tail = messages.findLast((message) => message.role !== 'system') + const ready = state.ready + delete state.ready + return !!tail && tail.timestamp === ready && isPiLaneStartMessage(tail) +} diff --git a/packages/pi/src/native-commands.ts b/packages/pi/src/native-commands.ts index df467942d..0e1dcd86e 100644 --- a/packages/pi/src/native-commands.ts +++ b/packages/pi/src/native-commands.ts @@ -88,7 +88,7 @@ export function createPiNativeCommands( } return { ...settings, - killswitch: { ...limits, enabled: true, main, accounts }, + killswitch: { ...limits, main, accounts }, } }) } @@ -246,13 +246,22 @@ export function createPiNativeCommands( } case 'quota-refresh': { const snapshot = await native.view() - for (const account of snapshot.accounts) { - if (!nativeAccountCanServe(account) || account.type !== 'oauth') - continue - await runtime.fetchQuota(account.id, fetchPiOAuth, options.signal) - await runtime.fetchProfile(account.id, fetchPiOAuth, options.signal) + const accounts = snapshot.accounts.filter( + (account) => + account.type === 'oauth' && nativeAccountCanServe(account), + ) + const results = await Promise.allSettled( + accounts.map((account) => + runtime.fetchQuota(account.id, fetchPiOAuth, options.signal), + ), + ) + const refreshed = results.filter( + (result) => result.status === 'fulfilled', + ).length + return { + ok: refreshed === accounts.length, + text: `${refreshed}/${accounts.length} native quota readings refreshed.`, } - return { ok: true, text: 'Native OAuth quota and profile refreshed.' } } case 'routing-mode': return written( diff --git a/packages/pi/src/stream.ts b/packages/pi/src/stream.ts index d05008180..491829dc5 100644 --- a/packages/pi/src/stream.ts +++ b/packages/pi/src/stream.ts @@ -162,6 +162,7 @@ import { piForkEffortSnapshots, piForkHeadSession, } from './forks.ts' +import { takePiLaneStart } from './lane-start.ts' import { getPiNativeRuntime, type PiNativeAttempt, @@ -197,7 +198,7 @@ const primarySessions = new Map< string, { storagePath: string - turn?: { promptId?: string } + turn?: { promptId?: string; synthetic?: boolean } previousRequestId?: string sent: number committed: number @@ -245,10 +246,15 @@ export function beginPiPrimaryTurn( } } -export function observePiUserPrompt(storagePath: string, sessionId: string) { +export function observePiUserPrompt( + storagePath: string, + sessionId: string, + synthetic = false, +) { const session = primarySessions.get(sessionId) // A queued user message can start a new prompt before the agent settles. - if (session?.storagePath === storagePath && session.turn) session.turn = {} + if (session?.storagePath === storagePath && session.turn) + session.turn = { synthetic } } export function endPiPrimaryTurn( @@ -981,6 +987,7 @@ async function sendAnthropicRequestAttempt( context: Context streamOptions?: SimpleStreamOptions requestOrigin?: 'agent-loop' | 'direct' + laneStart?: boolean apiAccount?: NativeAccountView storagePath: string oauthAccountId?: string @@ -1029,7 +1036,8 @@ async function sendAnthropicRequestAttempt( options.requestOrigin, ) : undefined - const turn = primary?.turn + const turn = + options.laneStart || primary?.turn?.synthetic ? undefined : primary?.turn if (primary && turn) { turn.promptId ??= randomUUID() primary.sent += 1 @@ -1138,6 +1146,9 @@ async function sendAnthropicRequestAttempt( identity, { apiKey: !!options.apiAccount, + apiKeyModelCompat: options.model + .compat as Model<'anthropic-messages'>['compat'], + laneStart: options.laneStart, deferSigning: true, billingLineage: lineage, ...(diagnosticsSession && { @@ -1814,9 +1825,9 @@ async function sendAnthropicRequestAttempt( isSubagent: false, ttlSent, }, - source: 'turn', + source: options.laneStart ? 'start' : 'turn', accountId: routeId, - synthetic: false, + synthetic: options.laneStart === true, betasHash: sent.betasHash, requestedModel, message, @@ -2004,6 +2015,7 @@ async function executeWithFallback(options: { context: Context streamOptions?: SimpleStreamOptions requestOrigin?: 'agent-loop' | 'direct' + laneStart?: boolean storagePath: string effortTransitions?: readonly PiEffortTransition[] onResolvedToolNames?: (toolNames: ReadonlyMap) => void @@ -3004,6 +3016,12 @@ export function streamCortexKitAnthropic( try { buildPiOAuthMessagesUrl(model.baseUrl) const storagePath = getPiAccountStoragePath() + const laneStart = + requestOrigin === 'agent-loop' && + !piForkHeadSession(options) && + takePiLaneStart(context.messages, options?.sessionId) + if (laneStart && options?.sessionId) + observePiUserPrompt(storagePath, options.sessionId, true) let toolNames: ReadonlyMap = new Map() let recordCacheUsage: | ((usage?: Record) => void) @@ -3014,6 +3032,7 @@ export function streamCortexKitAnthropic( context, streamOptions: options, requestOrigin, + laneStart, storagePath, onCapacityWait: setWorkingMessage ? () => { diff --git a/packages/pi/src/tests/commands.test.ts b/packages/pi/src/tests/commands.test.ts index a132cfc6f..554f4bd77 100644 --- a/packages/pi/src/tests/commands.test.ts +++ b/packages/pi/src/tests/commands.test.ts @@ -337,6 +337,54 @@ describe('native diagnostics persistence', () => { }) }) + test('quota refresh reports partial success without requesting profiles', async () => { + const runtime = await getPiNativeRuntime(storagePath).service() + const fetchQuota = spyOn(runtime, 'fetchQuota').mockImplementation( + async (id) => { + if (id === 'main') throw new Error('main quota unavailable') + return {} + }, + ) + const fetchProfile = spyOn(runtime, 'fetchProfile').mockRejectedValue( + new Error('profile unavailable'), + ) + try { + expect( + await controller().execute({ action: 'quota-refresh' }), + ).toMatchObject({ + status: 'executed', + ok: false, + text: '1/2 native quota readings refreshed.', + }) + expect(fetchQuota.mock.calls.map(([id]) => id).sort()).toEqual([ + 'fallback', + 'main', + ]) + expect(fetchProfile).not.toHaveBeenCalled() + } finally { + fetchQuota.mockRestore() + fetchProfile.mockRestore() + } + }) + + test('editing killswitch thresholds leaves the disabled switch off', async () => { + const { execute } = controller() + expect(await execute({ action: 'killswitch-off' })).toMatchObject({ + status: 'executed', + ok: true, + }) + expect( + await execute({ + action: 'killswitch-set', + values: { entries: [{ account: 'main', fh: 90, sd: 95 }] }, + }), + ).toMatchObject({ status: 'executed', ok: true }) + expect((await readNativePiFixture(storagePath)).killswitch).toMatchObject({ + enabled: false, + main: { five_hour: 90, seven_day: 95 }, + }) + }) + test('Ultra quota status shows only weekly and Fable limits through Core', async () => { const checkedAt = Date.now() await saveNativePiFixture( diff --git a/packages/pi/src/tests/convert.test.ts b/packages/pi/src/tests/convert.test.ts index 8558f24a3..e05d26e60 100644 --- a/packages/pi/src/tests/convert.test.ts +++ b/packages/pi/src/tests/convert.test.ts @@ -4,6 +4,7 @@ import { CLAUDE_CODE_IDENTITY, CLAUDE_CODE_VERSION, computeCcVersionSuffix, + LANE_START_TEXT, MessageThreadTracker, type ProviderAccountUuid, signRequestBody, @@ -13,6 +14,7 @@ import type { Context, Message } from '@earendil-works/pi-ai' import { buildAnthropicRequest, piThreadCacheSlot } from '../convert' import { collectPiEffortHistory } from '../effort-history.ts' import { PiForkEffortSnapshots } from '../forks.ts' +import { forgetPiLaneStarts, queuePiLaneStart } from '../lane-start.ts' import { normalizeContext } from '../transcript.ts' function userMsg(text: string): Message { @@ -59,6 +61,105 @@ const PI_PROMPT = [ 'Pi documentation (read only when the user asks about pi itself):\n- MOVE THIS', ].join('\n\n') +test('conversion strips a lane delivery nonce when the host hook did not run', async () => { + const sessionId = 'lane-converter-backstop' + const user = userMsg(queuePiLaneStart(sessionId)) + try { + const { bodyText } = await buildAnthropicRequest( + TEST_MODEL_ID, + { messages: [user] }, + { sessionId }, + defaultCache, + ) + expect(user).toMatchObject({ role: 'user', content: LANE_START_TEXT }) + expect(bodyText).not.toContain('cortexkit lane start:') + expect(bodyText).toContain(LANE_START_TEXT) + } finally { + forgetPiLaneStarts(sessionId) + } +}) + +test('paid Pi requests keep the native Anthropic cache markers and lifetimes', async () => { + const tools = ['read', 'write'].map((name) => ({ + name, + description: name, + parameters: {}, + })) + for (const retention of [ + 'default', + 'short', + 'long', + 'none', + 'env long', + 'compat short', + ] as const) { + const compatible = retention !== 'compat short' + const control = + retention === 'none' + ? undefined + : { + type: 'ephemeral', + ...((retention === 'long' || retention === 'env long') && { + ttl: '1h', + }), + } + const { body, bodyText, cacheTtlMs } = await buildAnthropicRequest( + 'claude-sonnet-5', + { + systemPrompt: PI_PROMPT, + tools, + messages: [userMsg('First'), assistantMsg('Reply'), userMsg('Latest')], + }, + { + env: { + PI_CACHE_RETENTION: retention === 'env long' ? 'long' : 'short', + }, + ...(retention === 'compat short' + ? { cacheRetention: 'long' } + : retention !== 'default' && retention !== 'env long' + ? { cacheRetention: retention } + : {}), + }, + { enabled: true, mode: 'automatic' }, + false, + undefined, + { + apiKey: true, + ...(compatible + ? {} + : { + apiKeyModelCompat: { + supportsLongCacheRetention: false, + supportsCacheControlOnTools: false, + }, + }), + }, + ) + expect(body.system).toEqual([ + { + type: 'text', + text: PI_PROMPT, + ...(control && { cache_control: control }), + }, + ]) + expect( + body.tools?.map(({ name, cache_control }) => [name, cache_control]), + ).toEqual([ + ['read', undefined], + ['write', compatible ? control : undefined], + ]) + expect(body.messages[0]?.content).toBe('First') + expect(body.messages.at(-1)?.content).toEqual( + control + ? [{ type: 'text', text: 'Latest', cache_control: control }] + : 'Latest', + ) + expect(body.cache_control).toBeUndefined() + expect(bodyText).not.toContain('x-anthropic-billing-header') + expect(cacheTtlMs).toBe(control ? (control.ttl ? 3_600_000 : 300_000) : 0) + } +}) + test('Pi full-after-thread trades only its system slot for the accepted full tail', async () => { const messages = [ userMsg('first'), @@ -1920,6 +2021,36 @@ describe('buildAnthropicRequest — cache breakpoint budget', () => { } }) + test('Pi hybrid anchors the tail of the first user message beyond the lookback', async () => { + const { body } = await buildAnthropicRequest( + TEST_MODEL_ID, + { + systemPrompt: PI_PROMPT, + tools: [{ name: 'read', description: 'Read', parameters: {} }], + messages: [ + userMsg('Long first prompt'), + { + ...assistantMsg('response'), + content: Array.from({ length: 20 }, (_, index) => ({ + type: 'text' as const, + text: `response block ${index}`, + })), + }, + userMsg('second prompt'), + ], + }, + undefined, + { enabled: true, mode: 'hybrid' }, + ) + expect(piThreadCacheSlot(body)).toEqual({ + type: 'text', + text: 'Long first prompt', + cache_control: { type: 'ephemeral', ttl: '1h' }, + }) + expect(body.system?.some((block) => block.cache_control)).toBe(false) + expect(countBreakpoints(body)).toBe(4) + }) + test('leaves the full body for an image-bearing array user message unchanged', async () => { const firstUserText = 'earlier user message' const text = 'look at this' diff --git a/packages/pi/src/tests/prime.test.ts b/packages/pi/src/tests/prime.test.ts index 7dea1c10b..d58709c15 100644 --- a/packages/pi/src/tests/prime.test.ts +++ b/packages/pi/src/tests/prime.test.ts @@ -1,10 +1,13 @@ import { afterEach, beforeEach, expect, spyOn, test } from 'bun:test' -import { mkdir, mkdtemp, readdir, rm } from 'node:fs/promises' +import { mkdir, mkdtemp, readdir, readFile, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { gunzipSync } from 'node:zlib' import { + __setLogTestSink, type AccountStorage, + getLogLevel, + LANE_START_TEXT, PROMPT_CACHE_DEFAULT_TTL_MS, PrimeManager, primeAccountMarkerDir, @@ -12,19 +15,22 @@ import { resolveNativePoolPaths, StickySessionRouter, sessionCacheActivity, + setLogLevel, signRequestBody, stickyRouteFamilyForModel, tokenFingerprint, } from '@cortexkit/anthropic-auth-core' -import type { - ExtensionAPI, - ExtensionCommandContext, +import { + type ExtensionAPI, + type ExtensionCommandContext, + SessionManager, } from '@earendil-works/pi-coding-agent' -import { registerCommands } from '../commands.ts' import cortexKitPiAnthropicAuth from '../index.ts' import { closePiNativeRuntime, getPiNativeRuntime } from '../native.ts' import { createPiNativeCommands } from '../native-commands.ts' import { + beginPiPrimaryTurn, + endPiPrimaryTurn, getPiTrackedCacheKeepSessions, sendPiPrimeRequest, streamCortexKitAnthropic, @@ -113,9 +119,36 @@ beforeEach(async () => { ).toString() sends.push({ headers: request.headers, text }) if (JSON.parse(text).stream) { - return new Response('data: {"type":"message_stop"}\n\n', { - headers: { 'content-type': 'text/event-stream' }, - }) + return new Response( + [ + { + type: 'message_start', + message: { + id: `msg_pi_lane_${sends.length}`, + model: JSON.parse(text).model, + diagnostics: null, + usage: { + input_tokens: 1, + cache_read_input_tokens: 0, + cache_creation_input_tokens: 0, + cache_creation: { + ephemeral_5m_input_tokens: 0, + ephemeral_1h_input_tokens: 0, + }, + }, + }, + }, + { type: 'message_stop' }, + ] + .map((event) => `data: ${JSON.stringify(event)}\n\n`) + .join(''), + { + headers: { + 'content-type': 'text/event-stream', + 'request-id': `req_lane_test_${sends.length}`, + }, + }, + ) } return Response.json({ usage: { input_tokens: 17, output_tokens: 1 } }) }, @@ -237,7 +270,11 @@ test('Pi /claude queues lane start as a visible turn that warms the session cach ], }) const modelId = 'claude-sonnet-5-5' - const sessionId = 'lane-start-session' + const transcript = SessionManager.create( + directory, + join(directory, 'transcripts'), + ) + const sessionId = transcript.getSessionId() const router = new StickySessionRouter({ path: await native.routingPath() }) expect( await router.resolve({ @@ -260,27 +297,31 @@ test('Pi /claude queues lane start as a visible turn that warms the session cach Parameters[1] >() const queued: Parameters[] = [] - registerCommands( - { - registerCommand: ( - name: string, - definition: Parameters[1], - ) => commands.set(name, definition), - sendUserMessage: ( - ...args: Parameters - ) => { - queued.push(args) - }, - } as unknown as ExtensionAPI, - createPiNativeCommands(storagePath), - ) + const handlers = new Map< + string, + (event: unknown, context: unknown) => Promise + >() + await cortexKitPiAnthropicAuth({ + on: ( + name: string, + handler: (event: unknown, context: unknown) => Promise, + ) => handlers.set(name, handler), + registerProvider() {}, + registerCommand: ( + name: string, + definition: Parameters[1], + ) => commands.set(name, definition), + sendUserMessage: (...args: Parameters) => { + queued.push(args) + }, + } as unknown as ExtensionAPI) async function invoke(model?: ExtensionCommandContext['model']) { const notices: string[] = [] let picked = false await commands.get('claude')?.handler('', { model, hasUI: true, - sessionManager: { getSessionId: () => sessionId }, + sessionManager: transcript, ui: { notify: (text: string) => notices.push(text), async select(title: string, choices: string[]) { @@ -314,8 +355,15 @@ test('Pi /claude queues lane start as a visible turn that warms the session cach maxTokens: 64_000, } const notice = await invoke(model) - const marker = '[lane start] — automated cache warm; no response needed.' - expect(queued).toEqual([[marker, { deliverAs: 'followUp' }]]) + const marker = LANE_START_TEXT + expect(queued).toEqual([ + [ + expect.stringMatching( + /^\[lane start\].*\n\[cortexkit lane start: [\da-f-]+\]$/, + ), + { deliverAs: 'followUp' }, + ], + ]) expect(sends).toHaveLength(0) expect(notice).toContain('Claude lane start queued in this session.') @@ -327,19 +375,28 @@ test('Pi /claude queues lane start as a visible turn that warms the session cach const lane = { role: 'user', content: [{ type: 'text', text: queued[0]![0] as string }], - timestamp: now + 1, + timestamp: now + 2, } satisfies Parameters[1]['messages'][number] + const typed = { role: 'user', content: marker, timestamp: now + 1 } as const const next = { role: 'user', content: 'Now answer my question', - timestamp: now + 2, + timestamp: now + 3, } as const async function runTurn( messages: Parameters[1]['messages'], + newUser = messages.at(-1), ) { + if (newUser?.role === 'user') { + await handlers.get('message_start')?.( + { message: newUser }, + { sessionManager: transcript }, + ) + transcript.appendMessage(newUser) + } const result = await streamCortexKitAnthropic( model, - { messages }, + { messages: structuredClone(messages) }, { sessionId, maxTokens: 123 }, undefined, undefined, @@ -347,43 +404,101 @@ test('Pi /claude queues lane start as a visible turn that warms the session cach ).result() expect(result.stopReason).toBe('stop') } + const records: string[] = [] + const level = getLogLevel() + setLogLevel('debug') + __setLogTestSink(({ message }) => records.push(message)) + beginPiPrimaryTurn(storagePath, sessionId) try { - await runTurn([first, lane]) - expect(sends).toHaveLength(1) - const sent = sends[0]! + await runTurn([first, typed]) + const human = JSON.parse(sends[0]!.text) + expect(human.max_tokens).toBe(123) + expect(human.thinking).toBeDefined() + expect(human.system[0].text).toContain('cc_prompt_index=2;') + + await runTurn([first, typed, lane]) + expect(sends).toHaveLength(2) + const sent = sends[1]! expect(sent.headers.get('authorization')).toBe( 'Bearer sk-ant-oat01-fallback-access', ) const body = JSON.parse(sent.text) expect(body).toMatchObject({ model: modelId, max_tokens: 1 }) - expect(body.messages).toHaveLength(2) + expect(body.messages).toHaveLength(3) expect(body.messages[0]).toMatchObject({ role: 'user', content: first.content, }) expect(body.messages[1]).toMatchObject({ + role: 'user', + content: marker, + }) + expect(body.messages[2]).toMatchObject({ role: 'user', content: [ { type: 'text', text: marker, cache_control: { type: 'ephemeral' } }, ], }) + // Pi appends the live message after message_start and clones it for the provider. + const persisted = await readFile(transcript.getSessionFile()!, 'utf8') + expect(persisted).not.toContain('cortexkit lane start:') + expect( + JSON.parse(persisted.trimEnd().split('\n').at(-1)!).message.content, + ).toEqual([{ type: 'text', text: marker }]) + expect(sent.text).not.toContain('cortexkit lane start:') + expect(body.system[0].text).not.toMatch(/cc_(?:prompt_id|prev_req)=/) expect(body.thinking).toBeUndefined() expect(await signRequestBody(sent.text)).toBe(sent.text) expect(sessionCacheActivity.ttlMs(sessionId)).toBe( PROMPT_CACHE_DEFAULT_TTL_MS, ) - await runTurn([first, lane, next]) - expect(sends).toHaveLength(2) - const following = JSON.parse(sends[1]!.text) + await runTurn([ + first, + typed, + lane, + { + role: 'assistant', + content: [ + { type: 'toolCall', id: 'tool_lane', name: 'read', arguments: {} }, + ], + } as Parameters[1]['messages'][number], + { + role: 'toolResult', + toolCallId: 'tool_lane', + toolName: 'read', + content: [{ type: 'text', text: 'Tool reply' }], + isError: false, + timestamp: now + 3, + }, + ]) + const toolStep = JSON.parse(sends[2]!.text) + expect(toolStep.max_tokens).toBe(123) + expect(toolStep.thinking).toBeDefined() + expect(toolStep.system[0].text).not.toMatch(/cc_(?:prompt_id|prev_req)=/) + + await runTurn([first, typed, lane, next]) + expect(sends).toHaveLength(4) + const following = JSON.parse(sends[3]!.text) expect(following.max_tokens).toBe(123) expect(following.thinking).toBeDefined() expect(following.messages[0]).toEqual(body.messages[0]) - expect(following.messages[1]).toMatchObject({ + expect(following.messages[2]).toMatchObject({ role: 'user', content: marker, }) + expect(following.system[0].text).toContain('cc_prev_req=req_lane_test_1;') + expect(following.system[0].text).toContain('cc_prompt_index=3;') + expect( + records + .filter((message) => message.startsWith('MC-CACHE-DIAG ')) + .map((message) => JSON.parse(message.slice('MC-CACHE-DIAG '.length))) + .find((record) => record.message_id === 'msg_pi_lane_2'), + ).toMatchObject({ source: 'start', synthetic: true }) } finally { + endPiPrimaryTurn(storagePath, sessionId, true) + __setLogTestSink(null) + setLogLevel(level) sessionCacheActivity.forget(sessionId) } expect((await native.view()).policyStorage.prime?.enabled).toBe(false) diff --git a/packages/pi/src/tests/request-history-stream.test.ts b/packages/pi/src/tests/request-history-stream.test.ts index e82336e30..971cd5478 100644 --- a/packages/pi/src/tests/request-history-stream.test.ts +++ b/packages/pi/src/tests/request-history-stream.test.ts @@ -330,6 +330,7 @@ test('Pi API-key requests preserve the host prompt and tools without Claude Code storagePath, streamOptions: { sessionId: 'pi-api-thread', + cacheRetention: 'short', onPayload: (payload) => ({ ...(payload as Record), service_tier: 'standard_only', @@ -341,10 +342,17 @@ test('Pi API-key requests preserve the host prompt and tools without Claude Code ) ).text() const body = JSON.parse(String(sent?.body)) + const cacheControl = { type: 'ephemeral' } expect(body.system).toEqual([ - { type: 'text', text: 'Keep the Pi system prompt.' }, + { + type: 'text', + text: 'Keep the Pi system prompt.', + cache_control: cacheControl, + }, + ]) + expect(body.tools).toMatchObject([ + { name: 'read', cache_control: cacheControl }, ]) - expect(body.tools).toMatchObject([{ name: 'read' }]) expect(body.messages).toEqual([ { role: 'user', content: 'Hello' }, { @@ -361,6 +369,7 @@ test('Pi API-key requests preserve the host prompt and tools without Claude Code tool_use_id: 'call_read', content: 'Result', is_error: false, + cache_control: cacheControl, }, ], }, diff --git a/packages/pi/src/tests/scoped-stream.test.ts b/packages/pi/src/tests/scoped-stream.test.ts index 46f4726ea..5586a07b9 100644 --- a/packages/pi/src/tests/scoped-stream.test.ts +++ b/packages/pi/src/tests/scoped-stream.test.ts @@ -49,7 +49,6 @@ import { type ProviderConfig, } from '@earendil-works/pi-coding-agent' import { nativeVaultPaths } from '../../../core/src/native-vault-paths.ts' -import { promptCacheSnapshot } from '../../../core/src/tests/prompt-cache-snapshot.ts' import { createTestLifetimeSuite } from '../../../core/src/tests/test-lifetime.ts' import { recordedTimers, @@ -220,10 +219,22 @@ function forkContext(base: Context, branchLength = 0): Context { } function normalizedForkBody(text: string) { - return JSON.parse( - text.replace(/cch=[a-f0-9]+/g, 'cch=SIGNATURE'), - (key, value) => (key === 'cache_control' ? undefined : value), - ) + return JSON.parse(text, (key, value) => { + if (key === 'cache_control') return undefined + if ( + typeof value === 'string' && + key === 'text' && + value.startsWith('x-anthropic-billing-header:') + ) + return value.replace(/ cch=[a-f0-9]+;/, ' cch=SIGNATURE;') + return value + }) +} + +function forkSystemSnapshot(body: ReturnType) { + const { diagnostics: _diagnostics, messages: _messages, ...prefix } = body + prefix.system[0].text = stripBillingLineageFields(prefix.system[0].text) + return JSON.stringify(prefix) } function stateBytes(value: unknown) { @@ -245,11 +256,18 @@ for (const mode of [ 'turn notes', 'head TTL', 'long branch', + 'bridged head at the lookback limit', ] as const) { test(`Pi fork preserves the head cache prefix: ${mode}`, async () => { const f = await fixture() const head = `fork-prefix-${mode}-${f.path}` const fork = `${head}-fork` + const bridged = mode === 'bridged head at the lookback limit' + if (bridged) + await (await f.native.service()).updateSettings((settings) => ({ + ...settings, + claudeCache: { enabled: false, mode: 'hybrid' }, + })) const note = { after_tool_use_id: 'tool-1', text: 'Runner base note' } const notesReads: string[] = [] const policyReads: string[] = [] @@ -279,7 +297,7 @@ for (const mode of [ : null }, })) - const base: Context = + let base: Context = mode === 'multi-turn' ? forkContext(context) : mode === 'long branch' @@ -320,6 +338,23 @@ for (const mode of [ ], } : context + if (bridged) { + const [first, answer, latest] = forkContext(context).messages + base = { + ...context, + messages: [ + first!, + { + ...(answer as AssistantMessage), + content: Array.from({ length: 20 }, (_, i) => ({ + type: 'text' as const, + text: `Head answer block ${i}`, + })), + }, + latest!, + ], + } + } const bodies: string[] = [] const server = Bun.serve({ hostname: '127.0.0.1', @@ -383,7 +418,7 @@ for (const mode of [ const before = JSON.stringify(await getPiTrackedCacheKeepSessions()) const result = await streamCortexKitAnthropic( model, - forkContext(base, mode === 'long branch' ? 30 : 0), + forkContext(base, mode === 'long branch' ? 30 : bridged ? 9 : 0), forkOptions(head), mode === 'plain' ? history @@ -402,6 +437,14 @@ for (const mode of [ ).toEqual([]) const rawHead = JSON.parse(bodies[0]!) const rawFork = JSON.parse(bodies.at(-1)!) + if (bridged) { + expect( + rawHead.system.some( + (block: Record) => block.cache_control, + ), + ).toBe(false) + expect(rawHead.messages[0].content.at(-1)).toHaveProperty('cache_control') + } expect(rawHead.diagnostics).toEqual({ previous_message_id: null }) expect(rawFork).not.toHaveProperty('diagnostics') expect(rawFork.system[0].text).not.toMatch( @@ -418,10 +461,12 @@ for (const mode of [ ) expect( markerPositions.some( - (position) => position >= basePosition && position - basePosition <= 20, + (position) => position >= basePosition && position - basePosition < 20, ), ).toBe(true) - expect(Boolean(baseBlock.cache_control)).toBe(mode === 'long branch') + expect(Boolean(baseBlock.cache_control)).toBe( + mode === 'long branch' || bridged, + ) if (mode === 'long branch') expect(rawFork.messages[0].content[0].cache_control).toBeUndefined() if (mode === 'turn notes') expect(bodies[0]).toContain(note.text) @@ -440,9 +485,7 @@ for (const mode of [ ), ].filter((holder) => holder.cache_control).length expect(countMarkers(rawFork)).toBeLessThanOrEqual(4) - delete headBody.messages - delete forkBody.messages - expect(promptCacheSnapshot(forkBody)).toBe(promptCacheSnapshot(headBody)) + expect(forkSystemSnapshot(forkBody)).toBe(forkSystemSnapshot(headBody)) expect(JSON.stringify(await getPiTrackedCacheKeepSessions())).toBe(before) expect(sessionCacheActivity.ttlMs(head)).toBe( mode === 'head TTL' ? 3_600_000 : 300_000, diff --git a/packages/pi/src/tests/session-cache-policy.test.ts b/packages/pi/src/tests/session-cache-policy.test.ts index b95509a9b..dc473fe89 100644 --- a/packages/pi/src/tests/session-cache-policy.test.ts +++ b/packages/pi/src/tests/session-cache-policy.test.ts @@ -3,8 +3,8 @@ import { getClaudeCodeIdentityForVerifiedAccount, type ProviderAccountUuid, } from '@cortexkit/anthropic-auth-core' -import type { Context } from '@earendil-works/pi-ai' -import { buildAnthropicRequest } from '../convert.ts' +import type { Context, Message } from '@earendil-works/pi-ai' +import { buildAnthropicRequest, piThreadCacheSlot } from '../convert.ts' const key = Symbol.for('cortexkit.routing') const globals = globalThis as Record @@ -65,9 +65,9 @@ for (const mode of ['explicit', 'automatic', 'hybrid'] as const) { } } -test('API-key conversion does not consult policy and keeps local long caching', async () => { +test('identity-free conversion does not consult policy and keeps local long caching', async () => { globals[key] = () => { - throw new Error('API-key requests must not read routing') + throw new Error('Requests without OAuth identity must not read routing') } const sent = await buildAnthropicRequest( 'claude-sonnet-5', @@ -81,3 +81,66 @@ test('API-key conversion does not consult policy and keeps local long caching', }) expect(sent.cacheTtlMs).toBe(3_600_000) }) + +test('paid requests do not inherit session cache policy', async () => { + let policyReads = 0 + globals[key] = () => ({ + cache: () => { + policyReads++ + return { ttl: 'none' } + }, + }) + const sent = await buildAnthropicRequest( + 'claude-sonnet-5', + structuredClone(context), + { sessionId: 'ses_pi_api', cacheRetention: 'short' }, + { enabled: true, mode: 'automatic' }, + false, + undefined, + { apiKey: true }, + ) + expect(policyReads).toBe(0) + expect(sent.cacheTtlMs).toBe(300_000) +}) + +test('five-minute hybrid sessions keep the bridge with or without a policy override', async () => { + const history: Context = { + ...context, + messages: [ + ...context.messages, + { + role: 'assistant', + content: [{ type: 'text', text: 'reply' }], + } as Message, + { role: 'user', content: 'Earlier boundary', timestamp: 1 }, + { + role: 'assistant', + content: Array.from({ length: 19 }, (_, index) => ({ + type: 'text', + text: `Reply block ${index}`, + })), + } as Message, + { role: 'user', content: 'Latest boundary', timestamp: 2 }, + ], + } + const build = async (ttl?: 'short') => { + globals[key] = () => ({ cache: () => (ttl ? { ttl } : null) }) + return buildAnthropicRequest( + 'claude-sonnet-5', + history, + { sessionId: 'ses_pi_hybrid_layout' }, + { enabled: false, mode: 'hybrid' }, + false, + identity, + { deferSigning: true }, + ) + } + const { body, cacheTtlMs } = await build() + expect(piThreadCacheSlot(body)).toEqual({ + type: 'text', + text: 'Earlier boundary', + cache_control: { type: 'ephemeral' }, + }) + expect(cacheTtlMs).toBe(300_000) + expect((await build('short')).body).toEqual(body) +}) From 6e4e08cd8c1e65e14e71fe785caa08c908e61ac3 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:38:31 +0100 Subject: [PATCH 21/27] Keep-warm restore never delays OpenCode startup; one claim per session across OpenCode 1 and 2 servers; restart scans keep live temp files --- packages/core/src/cachekeep-store.ts | 338 ++++++++++++++++-- packages/opencode/src/cachekeep-restart.ts | 10 +- packages/opencode/src/index.ts | 7 +- ...-and-cache-diagnostics.integration.test.ts | 56 +++ .../src/tests/cachekeep-process.test.ts | 135 +++++++ .../src/tests/fixtures/cachekeep-process.ts | 174 +++++++++ .../tests/opencode2-cachekeep-reload.test.ts | 26 +- .../tests/opencode2-cachekeep-store.test.ts | 28 ++ .../src/tests/opencode2-cachekeep.test.ts | 84 ++++- packages/opencode/src/v2/cachekeep.ts | 125 ++++--- packages/opencode/src/v2/setup.ts | 10 +- 11 files changed, 882 insertions(+), 111 deletions(-) create mode 100644 packages/opencode/src/tests/cachekeep-process.test.ts create mode 100644 packages/opencode/src/tests/fixtures/cachekeep-process.ts diff --git a/packages/core/src/cachekeep-store.ts b/packages/core/src/cachekeep-store.ts index 349eaeb23..2f03f079d 100644 --- a/packages/core/src/cachekeep-store.ts +++ b/packages/core/src/cachekeep-store.ts @@ -3,11 +3,20 @@ import { constants } from 'node:fs' import { lstat, mkdir, open, readdir, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' +import { setTimeout as delay } from 'node:timers/promises' import { promisify } from 'node:util' import { gunzip, gzip } from 'node:zlib' import { CACHE_KEEP_MAX_BODY_BYTES, type CacheKeepTarget } from './cachekeep.ts' +import { + ensureHolderDirectory, + type HolderLiveness, + holderEntryIsLive, + holderEntryLiveness, + processIncarnation, +} from './holder-registry.ts' import { getHostDataHome } from './host-paths.ts' import { logger } from './logger.ts' +import { withNativeLock } from './native-lock-observer.ts' import { createWindowsOwnerOnly, ensureWindowsOwnerOnlyDirectory, @@ -22,6 +31,7 @@ const decompress = promisify(gunzip) const hash = (value: string) => createHash('sha256').update(value).digest('hex') const FILE = /^[a-f0-9]{64}\.json\.gz$/ const TEMP = /^[a-f0-9]{64}\.json\.gz\.[a-f0-9-]+\.tmp$/ +const TEMP_STALE_MS = 60 * 60 * 1000 const MAX_RECORD_BYTES = 2 * CACHE_KEEP_MAX_BODY_BYTES + 64 * 1024 // Replay compatibility depends only on the record format, not the plugin // version. Bump this for format changes; the loader must accept or migrate the @@ -94,6 +104,142 @@ export type CacheKeepStoreRelease = (() => Promise) & { canRemove?: () => boolean | Promise } +const CLAIM_LOCK = { + name: 'cachekeep-session', + ttlMs: 10_000, + timeoutMs: 2000, + renew: true, +} + +/** A process-lifetime claim, not a timer lease that can expire during a pause. */ +export class CacheKeepClaim { + private readonly token = randomUUID() + private readonly path: string + private readonly purpose: 'session' | 'sweep' + private held = false + + constructor( + private readonly directory: string, + sessionId: string, + private readonly options: { + ownerOnly?: OwnerOnlyOptions + liveness?: HolderLiveness + sessionHash?: boolean + purpose?: 'session' | 'sweep' + } = {}, + ) { + const key = options.sessionHash ? sessionId : hash(sessionId) + if (!/^[a-f0-9]{64}$/.test(key)) throw new Error('Invalid session hash') + this.path = join(directory, `${key}.claim.json`) + this.purpose = + options.purpose ?? (options.sessionHash ? 'sweep' : 'session') + } + + private async read(): Promise | undefined> { + try { + const stat = await lstat(this.path) + if ( + !stat.isFile() || + stat.isSymbolicLink() || + stat.size > 4096 || + !(await isOwnerOnly( + this.path, + () => + stat.uid === process.getuid?.() && (stat.mode & 0o777) === 0o600, + this.options.ownerOnly, + )) + ) + throw new Error('Unsafe CacheKeep claim') + let bytes = await readWindowsOwnerOnly(this.path, this.options.ownerOnly) + if (!bytes) { + const file = await open( + this.path, + constants.O_RDONLY | constants.O_NOFOLLOW, + ) + try { + bytes = await file.readFile() + } finally { + await file.close() + } + } + const value = JSON.parse(bytes.toString()) + if (!holderEntryLiveness(value) || typeof value.token !== 'string') + throw new Error('Invalid CacheKeep claim') + return value + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined + throw error + } + } + + async acquire() { + if (this.held) return true + await ensureHolderDirectory(this.directory, this.options.ownerOnly) + for (;;) { + const result = await this.tryAcquire() + if (result !== 'sweep') return result + // A sweep only borrows ownership to inspect one record. A resuming + // session waits in the background rather than abandoning its claim. + await delay(25) + } + } + + private tryAcquire() { + return withNativeLock(this.path, CLAIM_LOCK, async (lease) => { + const existing = await this.read() + const life = holderEntryLiveness(existing) + if (life && (await holderEntryIsLive(life, this.options.liveness))) + return this.purpose === 'session' && existing?.purpose === 'sweep' + ? ('sweep' as const) + : false + const bytes = JSON.stringify({ + pid: process.pid, + incarnation: await ( + this.options.liveness?.incarnation ?? processIncarnation + )(process.pid), + registeredAt: Date.now(), + token: this.token, + purpose: this.purpose, + }) + const temp = `${this.path}.${this.token}.tmp` + try { + if ( + !(await createWindowsOwnerOnly(temp, bytes, this.options.ownerOnly)) + ) + await writeFile(temp, bytes, { flag: 'wx', mode: 0o600 }) + await lease.assertOwned() + await renameWithWindowsSharingRetry(temp, this.path, { + platform: this.options.ownerOnly?.platform, + }) + this.held = true + return true + } finally { + await rm(temp, { force: true }) + } + }) + } + + async isCurrent() { + if (!this.held) return false + try { + return (await this.read())?.token === this.token + } catch { + return false + } + } + + async release() { + if (!this.held) return + await withNativeLock(this.path, CLAIM_LOCK, async (lease) => { + if ((await this.read())?.token === this.token) { + await lease.assertOwned() + await rm(this.path, { force: true }) + } + this.held = false + }) + } +} + function record( target: Readonly, pluginVersion: string, @@ -256,11 +402,21 @@ export interface CacheKeepStoreOptions { now?: () => number setTimeoutImpl?: typeof globalThis.setTimeout clearTimeoutImpl?: typeof globalThis.clearTimeout + /** Hold a process claim from adoption or a live write through the last warm. */ + sessionClaims?: boolean +} + +type StoreClaim = { + claim: CacheKeepClaim + acquired: Promise + retained: boolean + closing?: Promise } /** Best-effort restart storage. No caller of changed() waits for disk or zlib. */ export class CacheKeepStore { readonly directory: string + private readonly claims?: Map private disabled = false private memoryOnly = false private persistenceEnabled = false @@ -281,11 +437,71 @@ export class CacheKeepStore { options.root, options.host, ) + if (options.sessionClaims) this.claims = previous?.claims ?? new Map() // Capture pending writes before the shared entry switches writers. New // writes and loads wait for them, so an old write cannot land last. this.chain = previous?.drain() ?? Promise.resolve() } + get isMemoryOnly() { + return this.memoryOnly + } + + private openClaim(key: string, purpose: 'session' | 'sweep') { + if (!this.claims || this.claims.has(key)) return + // Keep claims outside the record directory, including during migration + // from the legacy temp directory. Old readers still see the same files. + const claim = new CacheKeepClaim(`${this.directory}.claims`, key, { + sessionHash: true, + purpose, + ownerOnly: this.options.ownerOnly, + }) + const item: StoreClaim = { + claim, + retained: false, + acquired: claim.acquire().catch(() => { + this.writeFailed() + return false + }), + } + if (purpose === 'session') this.claims.set(key, item) + return item + } + + private closeClaim(key: string, item: StoreClaim) { + item.closing ??= (async () => { + if (await item.acquired) await item.claim.release() + })().finally(() => { + if (this.claims?.get(key) === item) this.claims.delete(key) + }) + return item.closing + } + + private async scanClaim(key: string, purpose: 'session' | 'sweep') { + const item = this.openClaim(key, purpose) + if (!item) return undefined + if (!(await item.acquired)) { + await this.closeClaim(key, item) + return undefined + } + return Object.assign( + () => (item.retained ? Promise.resolve() : this.closeClaim(key, item)), + { + canRemove: async () => (await item.claim.isCurrent()) && !item.retained, + }, + ) + } + + async releaseClaims(shouldRelease: (hash: string) => boolean) { + this.chain = this.chain.then(async () => { + for (const [key, item] of this.claims ?? []) { + if (!shouldRelease(key)) continue + await this.closeClaim(key, item).catch(() => this.writeFailed()) + } + }) + await this.chain + } + private refuse(memoryOnly = false) { if (this.disabled) return this.disabled = true @@ -362,6 +578,7 @@ export class CacheKeepStore { accept: (entry: SavedCacheKeepTarget) => Acceptance, claim?: (sessionHash: string) => Promise, guard?: (sessionHash: string) => boolean | Promise, + mode: 'restore' | 'sweep' = 'restore', ) { await this.chain if (!(await this.directoryReady())) return @@ -391,19 +608,28 @@ export class CacheKeepStore { let dropped = 0 try { for (const name of (await readdir(directory)).sort()) { - if (!FILE.test(name) && !TEMP.test(name)) continue + const temp = TEMP.test(name) + if (!FILE.test(name) && !temp) continue + const key = name.slice(0, 64) + const path = join(directory, name) + if (temp && !(await this.staleTemp(path))) continue + if (guard && !(await guard(key))) continue // Multi-process hosts must hold the session claim while reading or // deleting, including expiry cleanup and abandoned temporary writes. - const release = claim ? await claim(name.slice(0, 64)) : undefined - if (claim && !release) continue - const path = join(directory, name) + const release = claim + ? await claim(key) + : await this.scanClaim( + key, + temp || mode === 'sweep' ? 'sweep' : 'session', + ) + if ((claim || this.claims) && !release) continue let reason: DropReason = 'unreadable' let entry: SavedCacheKeepTarget | undefined const permitted = async () => { try { return ( - (!guard || (await guard(name.slice(0, 64)))) && - (!release?.canRemove || (await release.canRemove())) + (!release?.canRemove || (await release.canRemove())) && + (!guard || (await guard(key))) ) } catch { return false @@ -411,7 +637,7 @@ export class CacheKeepStore { } try { if (!(await permitted())) continue - if (TEMP.test(name)) { + if (temp) { reason = 'unfinished-write' throw new Error('Unfinished write') } @@ -461,6 +687,8 @@ export class CacheKeepStore { throw new Error('Stale restart file') } if (accepted === true) { + const owned = this.claims?.get(key) + if (owned && !claim && mode === 'restore') owned.retained = true // Retire pre-2.5.4 files only after the accepted record is durable // in the private data store. if (directory !== this.directory) { @@ -482,20 +710,24 @@ export class CacheKeepStore { restored++ } } catch { - // Serialize deletion with live writes and recheck file ownership, - // even when the saved file cannot be decoded. - this.chain = this.chain - .then(async () => { - if (!(await permitted())) return - await rm(path, { force: true }) - logger.debug('cachekeep', 'restart record dropped', { - file: name, - reason, - }) - dropped++ + const drop = async () => { + if (temp && !(await this.staleTemp(path))) return + if (!(await permitted())) return + await rm(path, { force: true }) + logger.debug('cachekeep', 'restart record dropped', { + file: name, + reason, }) - .catch(() => this.writeFailed()) - await this.chain + dropped++ + } + // A live writer may already be queued behind the sweep's claim. + // Delete under that claim rather than waiting for the writer. + if (this.claims && !claim) + await drop().catch(() => this.writeFailed()) + else { + this.chain = this.chain.then(drop).catch(() => this.writeFailed()) + await this.chain + } } finally { await release?.() } @@ -511,6 +743,13 @@ export class CacheKeepStore { } } + private async staleTemp(path: string) { + // Older writers used anonymous temporary names. Allow a full long-cache + // lifetime for publication before treating any of these files as abandoned. + const stat = await lstat(path).catch(() => undefined) + return !!stat && stat.mtimeMs <= Date.now() - TEMP_STALE_MS + } + changed(target: Readonly) { if (this.disabled) return const entry = record(target, this.options.pluginVersion) @@ -532,6 +771,16 @@ export class CacheKeepStore { return this.latest.set(entry.id, entry) this.pending.set(entry.id, entry) + if (this.claims) { + const key = hash(entry.id) + this.enqueue(async () => { + await this.claims?.get(key)?.closing + const item = this.claims?.get(key) ?? this.openClaim(key, 'session') + if (!item) return + item.retained = true + if (!(await item.acquired)) await this.closeClaim(key, item) + }) + } if (this.timers.has(entry.id)) return // Coalesce nearby preparations into the latest body, including tool steps // in a long user turn. Each session is capped at one write per five seconds; @@ -558,7 +807,9 @@ export class CacheKeepStore { this.pending.delete(id) if (!entry) return this.chain this.lastWrite.set(id, this.options.now?.() ?? Date.now()) - this.enqueue(() => this.writeEntry(entry)) + this.enqueue(async () => { + if (await this.canWrite(id)) await this.writeEntry(entry) + }) return this.chain } @@ -582,6 +833,7 @@ export class CacheKeepStore { this.chain = this.chain .then(async () => { if (!(await this.directoryReady())) return + if (!(await this.canWrite(entry.id))) return await this.writeEntry(entry) committed = true }) @@ -590,6 +842,12 @@ export class CacheKeepStore { return committed || this.memoryOnly } + private async canWrite(id: string) { + if (!this.claims) return true + const item = this.claims.get(hash(id)) + return !!item?.retained && (await item.claim.isCurrent()) + } + private async writeEntry(entry: SavedCacheKeepTarget) { const path = join(this.directory, `${hash(entry.id)}.json.gz`) const temp = `${path}.${randomUUID()}.tmp` @@ -606,16 +864,28 @@ export class CacheKeepStore { } } - removed(id: string) { + removed(id: string, removeUnowned = false) { const timer = this.timers.get(id) if (timer) (this.options.clearTimeoutImpl ?? clearTimeout)(timer) this.timers.delete(id) this.pending.delete(id) this.latest.delete(id) this.lastWrite.delete(id) - this.enqueue(() => - rm(join(this.directory, `${hash(id)}.json.gz`), { force: true }), - ) + this.enqueue(async () => { + const key = hash(id) + const item = + this.claims?.get(key) ?? + (removeUnowned ? this.openClaim(key, 'sweep') : undefined) + try { + if ( + !this.claims || + (item && (await item.acquired) && (await item.claim.isCurrent())) + ) + await rm(join(this.directory, `${key}.json.gz`), { force: true }) + } finally { + if (item) await this.closeClaim(key, item) + } + }) } clear() { @@ -626,9 +896,21 @@ export class CacheKeepStore { this.latest.clear() this.lastWrite.clear() this.enqueue(async () => { - for (const name of await readdir(this.directory)) - if (FILE.test(name) || TEMP.test(name)) - await rm(join(this.directory, name), { force: true }) + for (const name of await readdir(this.directory)) { + const path = join(this.directory, name) + const temp = TEMP.test(name) + if (!FILE.test(name) && !temp) continue + if (temp && !(await this.staleTemp(path))) continue + const release = await this.scanClaim(name.slice(0, 64), 'sweep') + if (this.claims && !release) continue + try { + if (release?.canRemove && !(await release.canRemove())) continue + if (temp && !(await this.staleTemp(path))) continue + await rm(path, { force: true }) + } finally { + await release?.() + } + } }) } diff --git a/packages/opencode/src/cachekeep-restart.ts b/packages/opencode/src/cachekeep-restart.ts index b66570154..4d017f6d7 100644 --- a/packages/opencode/src/cachekeep-restart.ts +++ b/packages/opencode/src/cachekeep-restart.ts @@ -163,6 +163,7 @@ export function adoptCacheKeepRestart(storageId: string, lease: Lease) { pluginVersion, host: 'opencode1', now: lease.now, + sessionClaims: true, }), leases: new Set(), owners: new Map(), @@ -219,7 +220,7 @@ export function adoptCacheKeepRestart(storageId: string, lease: Lease) { if (owner || shared.loading) { shared.owners.delete(hash) shared.restored.delete(hash) - shared.store.removed(id) + shared.store.removed(id, true) } }, reserve, @@ -242,7 +243,8 @@ export function adoptCacheKeepRestart(storageId: string, lease: Lease) { shared.closing++ try { await lease.manager.dispose() - await shared.loading + const loading = shared.loading + await loading let released = false for (const [hash, owner] of shared.owners) { if (owner !== lease) continue @@ -251,7 +253,9 @@ export function adoptCacheKeepRestart(storageId: string, lease: Lease) { released = true } await shared.store.drain() - if (released && shared.leases.size > 0) await restore(shared) + await shared.store.releaseClaims((hash) => !shared.owners.has(hash)) + if ((released || loading) && shared.leases.size > 0) + await restore(shared) } finally { shared.closing-- if (shared.leases.size === 0 && shared.closing === 0) diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index 4b1c04f13..70d15b9d7 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -12173,9 +12173,12 @@ const anthropicAuthPlugin = async ( dispose, // biome-ignore lint/suspicious/noExplicitAny: Plugin type doesn't include undocumented auth/hooks } as any - await cacheKeepRestart.restore() + const restoredCacheKeep = cacheKeepRestart.restore() pluginTestHandles?.set(plugin, { - drainDispatchWork, + async drainDispatchWork() { + await restoredCacheKeep + await drainDispatchWork() + }, drainSidebarRouteWrites, primeManager, quotaManager, diff --git a/packages/opencode/src/tests/cachekeep-and-cache-diagnostics.integration.test.ts b/packages/opencode/src/tests/cachekeep-and-cache-diagnostics.integration.test.ts index 25a39d076..65d47a024 100644 --- a/packages/opencode/src/tests/cachekeep-and-cache-diagnostics.integration.test.ts +++ b/packages/opencode/src/tests/cachekeep-and-cache-diagnostics.integration.test.ts @@ -7,6 +7,7 @@ import { __setLogTestSink, type AccountStorage, CacheKeepManager, + CacheKeepStore, type CommandApplyRequest, type CommandApplyResult, cacheKeepStoreDirectory, @@ -208,6 +209,9 @@ describe('auth.loader', () => { const managers = plugins.map( (plugin) => getPluginTestHandles(plugin).cacheKeepManager, ) + await Promise.all( + plugins.map((p) => getPluginTestHandles(p).drainDispatchWork()), + ) expect( managers .flatMap((manager) => manager.trackedSessions()) @@ -238,6 +242,7 @@ describe('auth.loader', () => { expect(updated.policyState.warmCostSoFar).toBeGreaterThan(0) expect(updated.cacheExpiresAt).toBeGreaterThan(saved.cacheExpiresAt) const restarted = await getPlugin(undefined, '/third-project') + await getPluginTestHandles(restarted).drainDispatchWork() const restored = getPluginTestHandles(restarted).cacheKeepManager.trackedPolicyState( sessionId, @@ -248,6 +253,57 @@ describe('auth.loader', () => { }) }) + test('OC1 dispatches the first request without waiting for restart restoration', async () => { + await warmFixture() + globalThis.fetch = mock( + withNativeAdmission(() => + Response.json({ usage: { cache_read_input_tokens: 1500 } }), + ), + ) as unknown as typeof fetch + const sessionId = 'oc1-late-restore' + const original = await getPlugin() + await acceptRequest(original, sessionId, 'saved prefix') + await original.dispose() + testContext.livePlugins.delete(original) + + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const load = CacheKeepStore.prototype.load + const scan = spyOn(CacheKeepStore.prototype, 'load').mockImplementation( + async function (this: CacheKeepStore, ...args) { + entered.resolve() + await release.promise + return load.apply(this, args) + }, + ) + const firstRequest = (async () => { + const plugin = await getPlugin(undefined, '/late-restore') + await acceptRequest(plugin, sessionId, 'first live prefix') + return getPluginTestHandles(plugin) + })() + let cancelDeadline = () => {} + let finished: Awaited | undefined + try { + await entered.promise + finished = await Promise.race([ + firstRequest, + new Promise((resolve) => { + const deadline = setTimeout(resolve, 1500) + cancelDeadline = () => clearTimeout(deadline) + }), + ]) + } finally { + cancelDeadline() + release.resolve() + scan.mockRestore() + await (await firstRequest).drainDispatchWork() + } + expect(finished).toBeDefined() + expect( + finished?.cacheKeepManager.trackedRequest(sessionId)?.bodyText, + ).toContain('first live prefix') + }) + test('OC1 reuses the previous full cache boundary after a thread restart', async () => { await warmFixture() const original = await getPlugin(undefined, '/original-thread-project') diff --git a/packages/opencode/src/tests/cachekeep-process.test.ts b/packages/opencode/src/tests/cachekeep-process.test.ts new file mode 100644 index 000000000..359999ebd --- /dev/null +++ b/packages/opencode/src/tests/cachekeep-process.test.ts @@ -0,0 +1,135 @@ +import { expect, test } from 'bun:test' +import { mkdtemp, readdir, readFile, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { gunzipSync } from 'node:zlib' +import { + CACHE_KEEP_PREWARM_LEAD_MS, + CacheKeepStore, + cacheKeepStoreDirectory, +} from '@cortexkit/anthropic-auth-core' +import { type Host, openKeeper } from './fixtures/cachekeep-process.ts' + +function spawnKeeper(host: Host, storageId: string, root: string, now: number) { + const online = Promise.withResolvers<{ tracked: number; sent: number }>() + const child = Bun.spawn( + [ + process.execPath, + join(import.meta.dir, 'fixtures', 'cachekeep-process.ts'), + host, + storageId, + root, + String(now), + ], + { + env: { ...process.env, XDG_DATA_HOME: root }, + stdin: 'pipe', + stderr: 'inherit', + ipc(message) { + online.resolve(message as { tracked: number; sent: number }) + }, + }, + ) + void child.exited.then((code) => + online.reject(new Error(`Keeper exited before reporting: ${code}`)), + ) + return { + child, + online: online.promise, + async close(command = '') { + if (command) child.stdin.write(command) + await child.stdin.end() + expect(await child.exited).toBe(0) + }, + } +} + +test.each(['opencode1', 'opencode2'] as const)( + '%s restores and warms a shared session only in the owning process', + async (host) => { + const root = await mkdtemp(join(tmpdir(), 'shared-cachekeep-')) + const dataHome = process.env.XDG_DATA_HOME + process.env.XDG_DATA_HOME = root + const storageId = join(root, 'accounts.json') + const directory = cacheKeepStoreDirectory( + storageId, + root, + host === 'opencode1' ? host : undefined, + ) + const readSaved = async () => { + const [name] = (await readdir(directory)).filter((entry) => + entry.endsWith('.json.gz'), + ) + expect(name).toBeDefined() + return JSON.parse( + gunzipSync(await readFile(join(directory, name!))).toString(), + ) + } + const children = new Set>() + const disposals: Array<() => Promise> = [] + let now = Date.now() + const start = async () => { + const keeper = await openKeeper(host, storageId, root, () => now) + disposals.push(keeper.dispose) + return keeper + } + const child = () => { + const running = spawnKeeper(host, storageId, root, now) + children.add(running) + return running + } + try { + const initial = await start() + expect(await initial.prepare()).toEqual({ tracked: true }) + await initial.dispose() + const saved = await readSaved() + const owner = await start() + expect(owner.manager.trackedCount()).toBe(1) + now = saved.cacheExpiresAt - CACHE_KEEP_PREWARM_LEAD_MS + 1 + + const duplicate = child() + expect(await duplicate.online).toEqual({ tracked: 0, sent: 0 }) + await duplicate.close() + expect(await readSaved()).toEqual(saved) + await owner.dispose() + + const successor = child() + expect(await successor.online).toEqual({ tracked: 1, sent: 1 }) + const warmed = await readSaved() + expect(warmed.policyState.warmsSinceLastRealRequest).toBe(1) + + const returning = await start() + expect(returning.manager.trackedCount()).toBe(0) + await returning.manager.tick() + expect(returning.sent()).toBe(0) + const sweep = new CacheKeepStore({ + storageId, + root, + host: host === 'opencode1' ? host : undefined, + pluginVersion: 'test', + sessionClaims: true, + }) + await sweep.load(now, () => 'invalid', undefined, undefined, 'sweep') + sweep.clear() + await sweep.drain() + expect(await readSaved()).toEqual(warmed) + + await successor.close('delete') + await returning.dispose() + const afterDelete = await start() + expect(afterDelete.manager.trackedCount()).toBe(0) + expect( + (await readdir(directory)).filter((name) => name.endsWith('.json.gz')), + ).toEqual([]) + } finally { + for (const { child } of children) { + if (child.exitCode === null) child.kill() + await child.exited + } + for (const dispose of disposals.reverse()) await dispose() + if (dataHome === undefined) delete process.env.XDG_DATA_HOME + else process.env.XDG_DATA_HOME = dataHome + await rm(root, { recursive: true, force: true }) + } + }, +) diff --git a/packages/opencode/src/tests/fixtures/cachekeep-process.ts b/packages/opencode/src/tests/fixtures/cachekeep-process.ts new file mode 100644 index 000000000..6e3911cec --- /dev/null +++ b/packages/opencode/src/tests/fixtures/cachekeep-process.ts @@ -0,0 +1,174 @@ +import { join } from 'node:path' +import { + type AccountStorage, + CacheKeepManager, + type NativeAccountRuntime, + type NativeAccountSnapshot, + type NativeAccountView, +} from '@cortexkit/anthropic-auth-core' +import { + adoptCacheKeepRestart, + cacheKeepRestartCredential, +} from '../../cachekeep-restart.ts' +import { createNativeCacheKeep } from '../../v2/cachekeep.ts' +import type { CacheKeepStore } from '../../v2/cachekeep-store.ts' +import type { NativeSource } from '../../v2/source.ts' + +export type Host = 'opencode1' | 'opencode2' +export const SESSION = 'ses_shared_restart' +const credentialId = 'synthetic-credential' +const account: NativeAccountView = { + id: 'main', + type: 'oauth', + source: 'vault', + enabled: true, + state: 'active', + accountIdentity: 'synthetic-identity', + credentialId, +} +const storage: AccountStorage = { + version: 1, + accounts: [], + claudeCache: { enabled: true, mode: 'hybrid' }, + cacheKeep: { enabled: true, always: true }, +} +const read = async () => + ({ accounts: [account], policyStorage: storage }) as NativeAccountSnapshot +const bodyText = JSON.stringify({ + model: 'claude-sonnet-4-6', + max_tokens: 8, + system: [ + { + type: 'text', + text: 'Shared prefix', + cache_control: { type: 'ephemeral', ttl: '1h' }, + }, + ], + messages: [{ role: 'user', content: 'Hello' }], +}) + +export async function openKeeper( + host: Host, + storageId: string, + root: string, + now: () => number, +) { + let sent = 0 + const fetchImpl = Object.assign( + async () => { + sent++ + return Response.json({ usage: { cache_read_input_tokens: 1500 } }) + }, + { preconnect: fetch.preconnect }, + ) + const url = 'https://api.anthropic.com/v1/messages' + if (host === 'opencode1') { + const identity = cacheKeepRestartCredential( + 'vault', + account.accountIdentity, + account.credentialId, + ) + const manager = new CacheKeepManager({ + now, + loadStorage: async () => storage, + onTargetChanged: (target) => lease.changed(target), + onTargetRemoved: (id) => lease.removed(id), + reserveWarm: (target) => lease.reserve(target), + settleWarm: (target) => lease.settle(target), + fetchImpl, + }) + const lease = adoptCacheKeepRestart(storageId, { + manager, + read, + allowUrl: () => true, + now, + }) + await lease.restore() + return { + manager, + sent: () => sent, + prepare: async () => + manager.track({ + sessionId: SESSION, + url, + headers: new Headers(), + bodyText, + storage, + cacheMode: 'hybrid', + oauthAccountId: account.id, + hostMetadata: { restartCredential: identity }, + }), + dispose: lease.dispose, + } + } + const source: Pick = { + chooseAccount: () => account.id, + authorizeAccount: async () => ({ + route: 'oauth', + accessToken: 'sk-ant-oat01-synthetic', + credentialId, + provenance: { kind: 'vault', credentialId, recordVersion: 1 }, + }), + } + const keeper = createNativeCacheKeep({ + now, + storageId, + persistence: { root, now }, + registryDirectory: join(root, `registry-${process.pid}`), + fetch: fetchImpl, + runtime: { read } as NativeAccountRuntime, + source: source as NativeSource, + }) + await keeper.ready + const key = Symbol.for('cortexkit.anthropic-auth.opencode2.cachekeep.v2') + const owner = ( + (globalThis as Record)[key] as Map< + string, + { + manager: CacheKeepManager + persistence: CacheKeepStore + } + > + ).get(storageId) + if (!owner) throw new Error('OpenCode 2 did not start a keep-warm owner') + return { + manager: owner.manager, + sent: () => sent, + async prepare() { + const attemptId = 'synthetic-attempt' + await keeper.track({ + attemptId, + sessionID: SESSION, + kind: 'primary', + agent: 'build', + route: 'oauth', + providerID: 'anthropic', + modelID: 'claude-sonnet-4-6', + transport: 'http', + dispatch: 'direct', + url, + bodyText, + accountId: account.id, + provenance: { kind: 'vault', credentialId, recordVersion: 1 }, + }) + return keeper.onResponseHeaders({ attemptId, status: 200 }) + }, + dispose: keeper.dispose, + } +} + +if (import.meta.main) { + const [host, storageId, root, now] = process.argv.slice(2) as [ + Host, + string, + string, + string, + ] + const keeper = await openKeeper(host, storageId, root, () => Number(now)) + const tracked = keeper.manager.trackedCount() + await keeper.manager.tick() + process.send?.({ tracked, sent: keeper.sent() }) + const finish = await Bun.stdin.text() + if (finish === 'delete') keeper.manager.untrack(SESSION) + await keeper.dispose() +} diff --git a/packages/opencode/src/tests/opencode2-cachekeep-reload.test.ts b/packages/opencode/src/tests/opencode2-cachekeep-reload.test.ts index 14061c7ea..26f9ceb2e 100644 --- a/packages/opencode/src/tests/opencode2-cachekeep-reload.test.ts +++ b/packages/opencode/src/tests/opencode2-cachekeep-reload.test.ts @@ -1,8 +1,9 @@ import { afterEach, expect, spyOn, test } from 'bun:test' import { randomUUID } from 'node:crypto' -import { mkdtemp, readdir, rm } from 'node:fs/promises' +import { mkdtemp, readdir, readFile, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' +import { gunzipSync } from 'node:zlib' import { CacheKeepManager, CacheKeepSessionRegistry, @@ -287,19 +288,16 @@ test('OpenCode 2 hybrid disable removes local records but preserves a mixed stor expect( shared.manager.trackedSessions().map(({ id }: { id: string }) => id), ).toEqual(['ses_runner']) - const retained: string[] = [] - let saved: any - await shared.persistence.load(now, (entry: { id: string }) => { - retained.push(entry.id) - saved = entry - return undefined - }) - expect(retained).toEqual(['ses_runner']) - expect( - (await readdir(shared.persistence.directory)).filter((name) => - name.endsWith('.json.gz'), - ), - ).toHaveLength(1) + const files = (await readdir(shared.persistence.directory)).filter((name) => + name.endsWith('.json.gz'), + ) + expect(files).toHaveLength(1) + const saved = JSON.parse( + gunzipSync( + await readFile(join(shared.persistence.directory, files[0]!)), + ).toString(), + ) + expect(saved.id).toBe('ses_runner') const reports: unknown[] = [] shared.manager.track({ sessionId: 'ses_runner', diff --git a/packages/opencode/src/tests/opencode2-cachekeep-store.test.ts b/packages/opencode/src/tests/opencode2-cachekeep-store.test.ts index 7a73cd706..e9bd0f57f 100644 --- a/packages/opencode/src/tests/opencode2-cachekeep-store.test.ts +++ b/packages/opencode/src/tests/opencode2-cachekeep-store.test.ts @@ -7,6 +7,7 @@ import { rename, rm, symlink, + utimes, writeFile, } from 'node:fs/promises' import { tmpdir } from 'node:os' @@ -73,6 +74,33 @@ test('restart storage defaults to a hashed private data folder, never the config expect(cacheKeepStoreDirectory('another-account')).not.toBe(path) }) +test('a restart scan preserves a writer’s new temporary file but removes old leftovers', async () => { + const f = await fixture() + f.store.changed(f.target) + await f.store.drain() + const [name] = await readdir(f.store.directory) + const published = join(f.store.directory, name!) + const writing = `${published}.1234.tmp` + const abandoned = `${published}.5678.tmp` + await rename(published, writing) + await writeFile(abandoned, 'abandoned', { mode: 0o600 }) + await utimes(abandoned, 0, 0) + + const scanning = new CacheKeepStore({ storageId: 'store', root: f.root }) + const restored: string[] = [] + const scan = () => + scanning.load(Date.now(), (entry) => { + restored.push(entry.id) + return true + }) + await scan() + expect(await readdir(f.store.directory)).toEqual([basename(writing)]) + expect(restored).toEqual([]) + await rename(writing, published) + await scan() + expect(restored).toEqual([f.target.id]) +}) + test('restart files exclude headers and credential fields, use gzip and owner-only modes', async () => { const f = await fixture() f.target.bodyText = JSON.stringify({ diff --git a/packages/opencode/src/tests/opencode2-cachekeep.test.ts b/packages/opencode/src/tests/opencode2-cachekeep.test.ts index c20b0d2aa..ce3eeeecf 100644 --- a/packages/opencode/src/tests/opencode2-cachekeep.test.ts +++ b/packages/opencode/src/tests/opencode2-cachekeep.test.ts @@ -7,6 +7,7 @@ import { readFile, rename, rm, + utimes, writeFile, } from 'node:fs/promises' import { tmpdir } from 'node:os' @@ -57,7 +58,7 @@ import { import * as cacheKeepFactory from '../v2/cachekeep' import { createNativeCacheKeep } from '../v2/cachekeep' import { - type CacheKeepStore, + CacheKeepStore, cacheKeepStoreDirectory, legacyCacheKeepStoreDirectory, } from '../v2/cachekeep-store' @@ -326,7 +327,10 @@ async function fixture( recursive: true, mode: 0o755, }) - const start = async (enrollmentFile = 'enrollment.json') => { + const start = async ( + enrollmentFile = 'enrollment.json', + waitForRestore = true, + ) => { const hooks = new Map unknown>>() const registration = { dispose: async () => {} } const ctx = { @@ -404,6 +408,10 @@ async function fixture( }, }) cleanups.push(dispose) + if (waitForRestore) { + const key = Symbol.for('cortexkit.anthropic-auth.opencode2.cachekeep.v2') + await (globalThis as any)[key]?.get(paths.storageId)?.loading + } const prepare = async ( url = 'https://api.anthropic.com/v1/messages', extra: Record = {}, @@ -1566,10 +1574,12 @@ test('OC2 last-lease disposal aborts and joins a due-timer restored delay before expect(active.sent).toHaveLength(0) const key = Symbol.for('cortexkit.anthropic-auth.opencode2.cachekeep.v2') const owner = (globalThis as any)[key].get(f.paths.storageId) - expect(owner.manager.trackedCount()).toBe(1) + expect(owner.manager.trackedCount()).toBe(0) expect( (await readdir(f.disk)).filter((name) => name.endsWith('.json.gz')), ).toHaveLength(1) + await f.start() + expect(owner.manager.trackedCount()).toBe(1) } finally { release?.() await stopping @@ -1751,6 +1761,55 @@ test('an OpenCode 2 instance that boots after the last one was disposed keeps wa ) }) +test('OC2 dispatches the first request without waiting for restart restoration', async () => { + const f = await fixture() + await f.live(undefined, { + messages: [{ role: 'user', content: 'saved prefix' }], + }) + await f.dispose() + + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const load = CacheKeepStore.prototype.load + const scan = spyOn(CacheKeepStore.prototype, 'load').mockImplementation( + async function (this: CacheKeepStore, ...args) { + entered.resolve() + await release.promise + return load.apply(this, args) + }, + ) + const firstRequest = (async () => { + const next = await f.start(undefined, false) + await next.live(undefined, { + messages: [{ role: 'user', content: 'first live prefix' }], + }) + return true + })() + const key = Symbol.for('cortexkit.anthropic-auth.opencode2.cachekeep.v2') + const owner = (globalThis as any)[key].get(f.paths.storageId) + let deadline: ReturnType | undefined + let finished = false + try { + await entered.promise + finished = await Promise.race([ + firstRequest, + new Promise((resolve) => { + deadline = setTimeout(() => resolve(false), 1500) + }), + ]) + } finally { + clearTimeout(deadline) + release.resolve() + scan.mockRestore() + await firstRequest + await owner.loading + } + expect(finished).toBe(true) + expect(owner.manager.trackedRequest('ses_oc2_keep')?.bodyText).toContain( + 'first live prefix', + ) +}) + test('OpenCode 2 restores a gzipped session after a server restart with the same cacheable prefix', async () => { const f = await fixture() const live = (await ( @@ -2367,8 +2426,10 @@ test.each([ ) const droppedName = change === 'unfinished-write' ? `${name!}.1234.tmp` : name! - if (change === 'unfinished-write') + if (change === 'unfinished-write') { await rename(path, join(f.disk, droppedName)) + await utimes(join(f.disk, droppedName), 0, 0) + } if (change === 'unsafe-file') await chmod(path, 0o644) forgetCacheKeepProcess(f.paths.storageId) lines.length = 0 @@ -3001,11 +3062,16 @@ test('hybrid-disabled request dispatch never waits on a held restart write', asy await owner.localCleanup drain.mockRestore() await owner.persistence.drain() - const retained: string[] = [] - await owner.persistence.load(f.now(), (entry: { id: string }) => { - retained.push(entry.id) - return undefined - }) + const files = (await readdir(f.disk)).filter((name) => + name.endsWith('.json.gz'), + ) + const retained = await Promise.all( + files.map( + async (file) => + JSON.parse(gunzipSync(await readFile(join(f.disk, file))).toString()) + .id, + ), + ) expect(retained).toEqual(['ses_oc2_keep']) } finally { clearTimeout(timeout) diff --git a/packages/opencode/src/v2/cachekeep.ts b/packages/opencode/src/v2/cachekeep.ts index da52bdaab..4bc06dc5b 100644 --- a/packages/opencode/src/v2/cachekeep.ts +++ b/packages/opencode/src/v2/cachekeep.ts @@ -161,6 +161,7 @@ interface SharedCacheKeep { readonly persistenceFollowsOwner?: true legacyPersistence?: CacheKeepStore loading?: Promise + restoreSkips?: Set readonly prepared: Map< number, { @@ -194,42 +195,32 @@ function discardLocalTargets( } const controlled = (id: string) => readSessionCachePolicy(id, true)?.keep_warm !== undefined - let hasRunnerTargets = false for (const session of shared.manager.trackedSessions()) { - if (controlled(session.id) || shared.manager.hasPlannedTarget?.(session.id)) - hasRunnerTargets = true - else shared.manager.untrack(session.id, 'disabled') + if ( + !controlled(session.id) && + !shared.manager.hasPlannedTarget?.(session.id) + ) + shared.manager.untrack(session.id, 'disabled') } if (shared.hybridDisabled) return shared.hybridDisabled = true const persistence = shared.persistence - // Inspect saved as well as live targets before a whole-store clear: a saved - // session with explicit keep_warm may not have been restored into memory yet. + // Sweep only records we can claim. Another server may still be warming its + // sessions, and a saved session with an explicit policy can stay on disk. shared.localCleanup = (shared.localCleanup ?? Promise.resolve()) .then(async () => { await persistence.drain() - await persistence.load(now, (entry) => { - if (!shared.hybridDisabled) return undefined - if ( + await persistence.load( + now, + (entry) => entry.policyState?.planned || controlled(entry.policyState?.ownerSessionId ?? entry.id) - ) { - hasRunnerTargets = true - return undefined - } - persistence.removed(entry.id) - return 'invalid' - }) - // A response may admit a runner target while the disk sweep awaits I/O. - const liveRunner = shared.manager - .trackedSessions() - .some( - (session) => - controlled(session.id) || - shared.manager.hasPlannedTarget?.(session.id), - ) - if (!hasRunnerTargets && !liveRunner && shared.hybridDisabled) - persistence.clear() + ? undefined + : 'invalid', + undefined, + () => !!shared.hybridDisabled, + 'sweep', + ) }) .catch(() => logger.warn('cachekeep', 'local restart cleanup failed')) } @@ -252,6 +243,9 @@ function sharedCacheKeeps(): Map { return scope[SHARED_CACHE_KEEPS] } +const sessionHash = (id: string) => + createHash('sha256').update(id).digest('hex') + function createSharedCacheKeep( storageId: string, options: NativeCacheKeepOptions, @@ -261,6 +255,7 @@ function createSharedCacheKeep( const leases: SharedCacheKeep['leases'] = new Map() const restored = new Set() let lastRestoredSend = 0 + let retaining: Promise | undefined const registry = new CacheKeepSessionRegistry({ ...getCacheKeepRegistryDirectories('opencode', options.registryDirectory), now: options.now, @@ -360,13 +355,10 @@ function createSharedCacheKeep( prepared.delete(attempt.id) }, }) - // OpenCode 2 disposes an evicted directory's instance before anything boots - // that directory again, so the last release must not drop the sessions: a - // new instance for this storage may adopt them while their cache is alive. - // The bodies also survive a server restart in private temporary storage. - // There is no timer sending prewarms, runtime or credential until adoption. - // A single timer deletes each body when its cache expires. + // If there is no usable restart store, keep the in-memory targets across + // directory eviction. They cannot warm without a live lease. let expiry: ReturnType | undefined + let retainedUntil = 0 const stopExpiry = () => { if (expiry !== undefined) clearTimeout(expiry) expiry = undefined @@ -374,13 +366,15 @@ function createSharedCacheKeep( const dropExpired = () => { stopExpiry() if (leases.size > 0) return - const earliest = manager.dropExpiredTargets() + const now = options.now?.() ?? Date.now() + const earliest = + manager.dropExpiredTargets() ?? + (retainedUntil > now ? retainedUntil : undefined) if (earliest === undefined) { const shareds = sharedCacheKeeps() if (shareds.get(storageId) === shared) shareds.delete(storageId) return } - const now = options.now?.() ?? Date.now() expiry = setTimeout(dropExpired, Math.max(0, earliest - now)) if (typeof expiry === 'object' && 'unref' in expiry) expiry.unref() } @@ -392,18 +386,41 @@ function createSharedCacheKeep( prepared, leases, nextGeneration: 0, - async retain() { + retain() { manager.stop() manager.abortWarms() prepared.clear() - await manager.drain() - dropExpired() + const loading = shared.loading + retaining = (async () => { + await manager.drain() + await loading + await shared.localCleanup + await shared.persistence.drain() + if (leases.size === 0 && !shared.persistence.isMemoryOnly) { + // Once the claim is released, only the disk record is authoritative: + // another server may spend its budget, replace it, or delete it. + for (const { id, cacheExpiresAt } of manager.trackedSessions()) { + retainedUntil = Math.max(retainedUntil, cacheExpiresAt) + manager.releaseTarget(id) + } + restored.clear() + await shared.persistence.releaseClaims(() => true) + } + dropExpired() + })().finally(() => { + retaining = undefined + }) + return retaining }, async adopt() { + if (retaining) await retaining stopExpiry() + retainedUntil = 0 shared.loading ??= (async () => { const lease = newestLease() if (!lease) return + const skipped = new Set() + shared.restoreSkips = skipped const snapshot = await lease.read() const now = options.now?.() ?? Date.now() let overdue = 0 @@ -411,7 +428,11 @@ function createSharedCacheKeep( now, (entry) => { // Disposal may race startup. Leave the file for the next live lease. - if (!leases.size || manager.trackedRequest(entry?.id)) + if ( + !leases.size || + skipped.has(sessionHash(entry.id)) || + manager.trackedRequest(entry.id) + ) return undefined if (entry.cacheExpiresAt <= now) return 'expired' if ( @@ -472,16 +493,19 @@ function createSharedCacheKeep( undefined, (hash) => leases.size > 0 && + !skipped.has(hash) && !manager .trackedSessions() - .some( - ({ id }) => - createHash('sha256').update(id).digest('hex') === hash, - ), + .some(({ id }) => sessionHash(id) === hash), ) - })().catch(() => { - logger.warn('cachekeep', 'failed to restore tracked sessions') - }) + })() + .catch(() => { + logger.warn('cachekeep', 'failed to restore tracked sessions') + }) + .finally(() => { + shared.loading = undefined + shared.restoreSkips = undefined + }) await shared.loading if (!leases.size) return // A session whose cache expired while no instance was live has nothing @@ -522,7 +546,11 @@ export function createNativeCacheKeep( const shareds = sharedCacheKeeps() const previous = shareds.get(options.storageId) const persistence = new CacheKeepStore( - { storageId: options.storageId, ...options.persistence }, + { + storageId: options.storageId, + ...options.persistence, + sessionClaims: true, + }, previous?.persistence, ) // Reloads keep the older manager, registry and timers, publishing only the @@ -552,6 +580,7 @@ export function createNativeCacheKeep( input.agent === 'prime' ) return undefined + owner.restoreSkips?.add(sessionHash(input.sessionID)) try { if (manager.beginRealTurn) { for (const turn of realTurns) if (!turn.active) realTurns.delete(turn) @@ -1175,7 +1204,9 @@ export function createNativeCacheKeep( resolvedParent, forgetSession(sessionID: string) { acceptedStates.delete(sessionID) - manager.untrack(sessionID) + owner.restoreSkips?.add(sessionHash(sessionID)) + if (!manager.untrack(sessionID) && owner.restoreSkips) + owner.persistence.removed(sessionID, true) for (const [attemptId, entry] of pending) if (entry.sessionID === sessionID) discardAttempt(attemptId) }, diff --git a/packages/opencode/src/v2/setup.ts b/packages/opencode/src/v2/setup.ts index 6c4c15dc3..ebb9a508d 100644 --- a/packages/opencode/src/v2/setup.ts +++ b/packages/opencode/src/v2/setup.ts @@ -567,14 +567,8 @@ export async function setupAnthropicAuth( fetch: options.fetch, subagent, }) - await cacheKeep.ready.catch(async (error: unknown) => { - requests.retire() - holderRegistration?.close() - await cacheKeep?.dispose() - await source.close() - await runtime.close() - await settingsService?.dispose() - throw error + void cacheKeep.ready.catch(() => { + logger.warn('cachekeep', 'failed to start keep-warm restoration') }) const capabilities = createNativeMenuCapabilities({ runtime, From 5100e75eb8e9565cbfd0579b2651cf04386c4143 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:41:09 +0100 Subject: [PATCH 22/27] Pi: use Core's shared keep-warm session claim --- STRUCTURE.md | 2 +- packages/pi/src/cachekeep-claim.ts | 165 ------------------------ packages/pi/src/cachekeep.ts | 8 +- packages/pi/src/tests/cachekeep.test.ts | 14 +- 4 files changed, 12 insertions(+), 177 deletions(-) delete mode 100644 packages/pi/src/cachekeep-claim.ts diff --git a/STRUCTURE.md b/STRUCTURE.md index c707b776b..48e554721 100644 --- a/STRUCTURE.md +++ b/STRUCTURE.md @@ -77,7 +77,7 @@ docs/ public user and contributor documentation - `convert.ts` and `transcript.ts`: build the Anthropic body from Pi's context. - `stream.ts` and `transport.ts`: send, relay, threads, billing lineage, quota-header observation, cache diagnostics and stream mapping. - `native.ts` and `native-commands.ts`: the account runtime and menu. -- `cachekeep.ts` and `cachekeep-claim.ts`: keep-warm, with the restart store and the per-session claim. +- `cachekeep.ts`: keep-warm, with the restart store and Core's per-session claim (`CacheKeepClaim`, shared with OpenCode 1 and 2). - `prime.ts`: the Prime scheduler, which sends through `stream.ts`'s registered Prime sender. - Other files: `effort-history.ts`, `quota-wait.ts`, `custody.ts` and `paths.ts`. diff --git a/packages/pi/src/cachekeep-claim.ts b/packages/pi/src/cachekeep-claim.ts deleted file mode 100644 index 254f3132b..000000000 --- a/packages/pi/src/cachekeep-claim.ts +++ /dev/null @@ -1,165 +0,0 @@ -import { createHash, randomUUID } from 'node:crypto' -import { constants } from 'node:fs' -import { lstat, open, rm, writeFile } from 'node:fs/promises' -import { join } from 'node:path' -import { setTimeout as delay } from 'node:timers/promises' -import { - createWindowsOwnerOnly, - ensureHolderDirectory, - type HolderLiveness, - holderEntryIsLive, - holderEntryLiveness, - isOwnerOnly, - type OwnerOnlyOptions, - processIncarnation, - readWindowsOwnerOnly, - renameWithWindowsSharingRetry, - withNativeLock, -} from '@cortexkit/anthropic-auth-core' - -/** A process-lifetime claim, not a timer lease that can expire during a pause. */ -export class PiCacheKeepClaim { - private readonly token = randomUUID() - private readonly path: string - private held = false - - constructor( - private readonly directory: string, - sessionId: string, - private readonly options: { - ownerOnly?: OwnerOnlyOptions - liveness?: HolderLiveness - sessionHash?: boolean - } = {}, - ) { - const hash = options.sessionHash - ? sessionId - : createHash('sha256').update(sessionId).digest('hex') - if (!/^[a-f0-9]{64}$/.test(hash)) throw new Error('Invalid session hash') - this.path = join(directory, `${hash}.claim.json`) - } - - private async read(): Promise | undefined> { - try { - const stat = await lstat(this.path) - if ( - !stat.isFile() || - stat.isSymbolicLink() || - stat.size > 4096 || - !(await isOwnerOnly( - this.path, - () => - stat.uid === process.getuid?.() && (stat.mode & 0o777) === 0o600, - this.options.ownerOnly, - )) - ) - throw new Error('Unsafe CacheKeep claim') - let bytes = await readWindowsOwnerOnly(this.path, this.options.ownerOnly) - if (!bytes) { - const file = await open( - this.path, - constants.O_RDONLY | constants.O_NOFOLLOW, - ) - try { - bytes = await file.readFile() - } finally { - await file.close() - } - } - const value = JSON.parse(bytes.toString()) - if (!holderEntryLiveness(value) || typeof value.token !== 'string') - throw new Error('Invalid CacheKeep claim') - return value - } catch (error) { - if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined - throw error - } - } - - async acquire() { - if (this.held) return true - await ensureHolderDirectory(this.directory, this.options.ownerOnly) - for (;;) { - const result = await this.tryAcquire() - if (result !== 'sweep') return result - // A sweep borrows ownership only while reading one record. A resuming - // session waits in the background instead of mistaking temporary sweep - // ownership for an active session claim. - await delay(25) - } - } - - private tryAcquire() { - return withNativeLock( - this.path, - { - name: 'cachekeep-session', - ttlMs: 10_000, - timeoutMs: 2000, - renew: true, - }, - async (lease) => { - const existing = await this.read() - const life = holderEntryLiveness(existing) - if (life && (await holderEntryIsLive(life, this.options.liveness))) - return !this.options.sessionHash && existing?.purpose === 'sweep' - ? ('sweep' as const) - : false - const bytes = JSON.stringify({ - pid: process.pid, - incarnation: await ( - this.options.liveness?.incarnation ?? processIncarnation - )(process.pid), - registeredAt: Date.now(), - token: this.token, - purpose: this.options.sessionHash ? 'sweep' : 'session', - }) - const temp = `${this.path}.${this.token}.tmp` - try { - if ( - !(await createWindowsOwnerOnly(temp, bytes, this.options.ownerOnly)) - ) - await writeFile(temp, bytes, { flag: 'wx', mode: 0o600 }) - await lease.assertOwned() - await renameWithWindowsSharingRetry(temp, this.path, { - platform: this.options.ownerOnly?.platform, - }) - this.held = true - return true - } finally { - await rm(temp, { force: true }) - } - }, - ) - } - - async isCurrent() { - if (!this.held) return false - try { - return (await this.read())?.token === this.token - } catch { - return false - } - } - - async release() { - if (!this.held) return - await withNativeLock( - this.path, - { - name: 'cachekeep-session', - ttlMs: 10_000, - timeoutMs: 2000, - renew: true, - }, - async (lease) => { - const current = await this.read() - if (current?.token === this.token) { - await lease.assertOwned() - await rm(this.path, { force: true }) - } - this.held = false - }, - ) - } -} diff --git a/packages/pi/src/cachekeep.ts b/packages/pi/src/cachekeep.ts index 1025a5219..7bdc1f665 100644 --- a/packages/pi/src/cachekeep.ts +++ b/packages/pi/src/cachekeep.ts @@ -1,6 +1,7 @@ import { createHash } from 'node:crypto' import { setTimeout as delay } from 'node:timers/promises' import { + CacheKeepClaim, CacheKeepManager, type CacheKeepRealTurn, CacheKeepStore, @@ -19,13 +20,12 @@ import { type StickySessionRouter, } from '@cortexkit/anthropic-auth-core' import { version as pluginVersion } from '../package.json' -import { PiCacheKeepClaim } from './cachekeep-claim.ts' type TrackInput = Parameters[0] type ManagerOptions = ConstructorParameters[0] type Session = { storagePath: string - claim: PiCacheKeepClaim + claim: CacheKeepClaim store: CacheKeepStore } @@ -191,7 +191,7 @@ export class PiCacheKeep { let claiming: Promise claiming = (async () => { const store = await this.store(storagePath) - const claim = new PiCacheKeepClaim(store.directory, sessionId, { + const claim = new CacheKeepClaim(store.directory, sessionId, { ownerOnly: this.options.persistence?.ownerOnly, liveness: this.options.liveness, }) @@ -238,7 +238,7 @@ export class PiCacheKeep { }) : undefined } - const cleanup = new PiCacheKeepClaim(store.directory, hash, { + const cleanup = new CacheKeepClaim(store.directory, hash, { ...this.options.persistence, liveness: this.options.liveness, sessionHash: true, diff --git a/packages/pi/src/tests/cachekeep.test.ts b/packages/pi/src/tests/cachekeep.test.ts index dfae9469c..2ce6873f7 100644 --- a/packages/pi/src/tests/cachekeep.test.ts +++ b/packages/pi/src/tests/cachekeep.test.ts @@ -5,6 +5,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { gunzipSync, gzipSync } from 'node:zlib' import { + CacheKeepClaim, type CacheKeepManager, cacheKeepStoreDirectory, createEmptyStorage, @@ -12,7 +13,6 @@ import { type NativeAccountSnapshot, } from '@cortexkit/anthropic-auth-core' import { PiCacheKeep } from '../cachekeep.ts' -import { PiCacheKeepClaim } from '../cachekeep-claim.ts' const cleanups: Array<() => unknown | Promise> = [] afterEach(async () => { @@ -582,7 +582,7 @@ test('Pi shutdown aborts and joins Core due-timer warms before releasing their c ...( Reflect.get(active.process, 'sessions') as Map< string, - { claim: PiCacheKeepClaim } + { claim: CacheKeepClaim } > ).values(), ][0]!.claim @@ -975,16 +975,16 @@ test('Pi drains the latest accepted body on shutdown and removes stopped targets test('a reused pid cannot hold a Pi session and an old release cannot remove its successor claim', async () => { const f = await fixture() const directory = cacheKeepStoreDirectory('shared-storage', f.root, 'pi') - const old = new PiCacheKeepClaim(directory, 'S', { + const old = new CacheKeepClaim(directory, 'S', { liveness: { pidAlive: () => true, incarnation: async () => 'old-start' }, }) - const next = new PiCacheKeepClaim(directory, 'S', { + const next = new CacheKeepClaim(directory, 'S', { liveness: { pidAlive: () => true, incarnation: async () => 'new-start' }, }) expect(await old.acquire()).toBe(true) expect(await next.acquire()).toBe(true) await old.release() - const contender = new PiCacheKeepClaim(directory, 'S', { + const contender = new CacheKeepClaim(directory, 'S', { liveness: { pidAlive: () => true, incarnation: async () => 'new-start' }, }) expect(await contender.acquire()).toBe(false) @@ -1001,7 +1001,7 @@ test('a Pi owner waits out a sweep and restores without another turn or request' f.advance(55 * 60_000) const directory = cacheKeepStoreDirectory('shared-storage', f.root, 'pi') const hash = createHash('sha256').update('session-S').digest('hex') - const sweep = new PiCacheKeepClaim(directory, hash, { + const sweep = new CacheKeepClaim(directory, hash, { sessionHash: true, liveness: { pidAlive: () => true, incarnation: async () => 'same-start' }, }) @@ -1049,7 +1049,7 @@ test('shutdown saves an accepted body queued before a sweep releases its claim', const f = await fixture() const directory = cacheKeepStoreDirectory('shared-storage', f.root, 'pi') const hash = createHash('sha256').update('session-S').digest('hex') - const sweep = new PiCacheKeepClaim(directory, hash, { + const sweep = new CacheKeepClaim(directory, hash, { sessionHash: true, liveness: { pidAlive: () => true, incarnation: async () => 'same-start' }, }) From 596444594ca9f48ce0f359728e06fb5476f09be3 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:33:27 +0100 Subject: [PATCH 23/27] Cache diagnostics never delay OpenCode 2 or Pi replies; reply IDs captured without full usage; Pi warms stay out of diagnostics; OC2 prices survive a failed lookup; stricter test oracles --- packages/core/src/cache-diagnostics.ts | 20 ++- .../src/tests/prompt-cache-snapshot.test.ts | 34 ++++ .../core/src/tests/prompt-cache-snapshot.ts | 14 +- .../src/tests/opencode1-settings-read.test.ts | 4 +- .../src/tests/opencode2-adapter.test.ts | 96 ++++++++++ .../src/tests/opencode2-settings-read.test.ts | 13 ++ .../tests/request-history.integration.test.ts | 6 +- .../src/tests/settings-snapshot-parity.ts | 1 + packages/opencode/src/v2/adapter.ts | 39 ++-- packages/opencode/src/v2/models.ts | 11 +- packages/opencode/src/v2/wire.ts | 100 ++++++----- packages/pi/src/stream.ts | 39 ++-- packages/pi/src/tests/stream.test.ts | 167 ++++++++++++++++-- 13 files changed, 435 insertions(+), 109 deletions(-) create mode 100644 packages/core/src/tests/prompt-cache-snapshot.test.ts diff --git a/packages/core/src/cache-diagnostics.ts b/packages/core/src/cache-diagnostics.ts index 9f1a16126..45bf65205 100644 --- a/packages/core/src/cache-diagnostics.ts +++ b/packages/core/src/cache-diagnostics.ts @@ -102,6 +102,15 @@ export async function getCacheDiagnosticsBetas(headers: Headers) { } } +export function hasCacheDiagnosticsBeta(headers: Headers): boolean { + return ( + headers + .get('anthropic-beta') + ?.split(',') + .some((beta) => beta.trim() === CACHE_DIAGNOSTICS_BETA) ?? false + ) +} + export function applyCacheDiagnosticsOptIn( body: Record, previousMessageId: string | null, @@ -113,6 +122,13 @@ function isRecord(value: unknown): value is Record { return value != null && typeof value === 'object' && !Array.isArray(value) } +export function cacheDiagnosticsMessageId( + message: unknown, +): string | undefined { + const id = isRecord(message) ? message.id : undefined + return typeof id === 'string' && id.length > 0 ? id : undefined +} + function isBreakpoint(value: unknown): value is Record { return isRecord(value) && value.type === 'ephemeral' } @@ -217,10 +233,10 @@ export function buildCacheDiagnosticsRecord(input: { if (!Number.isFinite(input.receivedAt) || receivedAt !== input.receivedAt) return {} if (!isRecord(input.message)) return {} - const messageId = input.message.id + const messageId = cacheDiagnosticsMessageId(input.message) const model = input.message.model const usage = input.message.usage - if (typeof messageId !== 'string' || messageId.length === 0) return {} + if (!messageId) return {} if (typeof model !== 'string' || model.length === 0 || !isRecord(usage)) return {} const inputTokens = numericUsage(usage, 'input_tokens') diff --git a/packages/core/src/tests/prompt-cache-snapshot.test.ts b/packages/core/src/tests/prompt-cache-snapshot.test.ts new file mode 100644 index 000000000..8453f6757 --- /dev/null +++ b/packages/core/src/tests/prompt-cache-snapshot.test.ts @@ -0,0 +1,34 @@ +import { expect, test } from 'bun:test' +import { promptCacheSnapshot } from './prompt-cache-snapshot.ts' + +const body = (billing: string) => ({ + system: [{ type: 'text', text: `x-anthropic-billing-header: ${billing}` }], +}) +const original = 'cc_version=2.1.302.804; cc_entrypoint=cli; cch=4c6e9;' + +test.each([ + ['entrypoint', original.replace('cc_entrypoint=cli', 'cc_entrypoint=sdk')], + ['version suffix', original.replace('2.1.302.804', '2.1.302.123')], +])( + 'the prompt-cache snapshot detects a changed billing %s', + (_name, changed) => { + expect(promptCacheSnapshot(body(changed))).not.toBe( + promptCacheSnapshot(body(original)), + ) + }, +) + +test('the prompt-cache snapshot ignores only the billing signature, lineage and diagnostics', () => { + expect( + promptCacheSnapshot({ + ...body( + `${original.replace('cch=4c6e9', 'cch=5abcd')} cc_prev_req=req_12345678; cc_prompt_id=prompt; cc_turn_origin=human; cc_prompt_index=1; cc_turn_index=1;`, + ), + diagnostics: { previous_message_id: 'msg_previous' }, + }), + ).toBe( + JSON.stringify( + body('cc_version=2.1.302.804; cc_entrypoint=cli; cch=00000;'), + ), + ) +}) diff --git a/packages/core/src/tests/prompt-cache-snapshot.ts b/packages/core/src/tests/prompt-cache-snapshot.ts index 81cdf3f47..5c4b6b6ae 100644 --- a/packages/core/src/tests/prompt-cache-snapshot.ts +++ b/packages/core/src/tests/prompt-cache-snapshot.ts @@ -1,14 +1,20 @@ +import { CCH_PATTERN, stripBillingLineageFields } from '../cch.ts' + export function promptCacheSnapshot(body: Record): string { - // The billing header carries a request signature and turn lineage, and the - // top-level diagnostics ID links provider replies. Neither is part of the - // prompt-cache prefix; forks deliberately don't join those chains. + // Compare fixed prefix bytes without the per-send signature or lineage. + // Callers that compare different diagnostic contexts assert those separately. const { diagnostics: _diagnostics, ...prefix } = body if (Array.isArray(prefix.system)) { prefix.system = prefix.system.map((block) => block?.type === 'text' && typeof block?.text === 'string' && block.text.startsWith('x-anthropic-billing-header:') - ? { ...block, text: 'x-anthropic-billing-header: MASKED' } + ? { + ...block, + text: stripBillingLineageFields( + block.text.replace(CCH_PATTERN, 'cch=00000;'), + ), + } : block, ) } diff --git a/packages/opencode/src/tests/opencode1-settings-read.test.ts b/packages/opencode/src/tests/opencode1-settings-read.test.ts index edc94578d..35064b003 100644 --- a/packages/opencode/src/tests/opencode1-settings-read.test.ts +++ b/packages/opencode/src/tests/opencode1-settings-read.test.ts @@ -782,8 +782,8 @@ describe('OpenCode 1 settings service reads', () => { ] as const) { settingsReaderOutputs(storage) const observed = await observeSettings(storage, 1) - // Per-warm timings are tested separately and were absent in 2.11.2; - // keep every older diagnostic and request byte in the release oracle. + // Per-warm timings were absent in 2.11.2. Compare the fixed warm + // body bytes, and check the intentional diagnostics difference separately. const compatible = { ...observed, warms: observed.warms.map((warm) => diff --git a/packages/opencode/src/tests/opencode2-adapter.test.ts b/packages/opencode/src/tests/opencode2-adapter.test.ts index 2329fa5a8..f357b3bd3 100644 --- a/packages/opencode/src/tests/opencode2-adapter.test.ts +++ b/packages/opencode/src/tests/opencode2-adapter.test.ts @@ -93,6 +93,7 @@ type Data = NativeAnthropicAttemptData const ENV_KEYS = [ 'ANTHROPIC_BASE_URL', 'ANTHROPIC_CUSTOM_HEADERS', + 'ANTHROPIC_INSECURE', 'ANTHROPIC_MODEL', 'ANTHROPIC_DEFAULT_SONNET_MODEL', 'ANTHROPIC_DEFAULT_OPUS_MODEL', @@ -526,6 +527,92 @@ const diagnosticsMessage = (id: string) => ({ diagnostics: null, }) +test('OpenCode 2 delivers the reply and captures its ID even while the diagnostics hash is pending', async () => { + const { native, host } = cacheDiagnosticsHost() + const hash = core.getCacheDiagnosticsBetas + const pending = Promise.withResolvers() + const hashSpy = spyOn(core, 'getCacheDiagnosticsBetas').mockImplementation( + async (headers) => { + await pending.promise + return hash(headers) + }, + ) + const debug = spyOn(core.logger, 'debug').mockImplementation(() => {}) + const send = () => + host.run(scopeOf(), hostRequest({ ...sonnetPayload(), stream: false })) + let reading: Promise | undefined + try { + const { attempt, final } = await send() + expect(hashSpy).toHaveBeenCalledTimes(1) + let delivered: unknown + reading = Promise.resolve( + native.adapter.rewriteResponse?.({ + ...attempt, + attempt, + request: final, + response: Response.json(diagnosticsMessage('msg_pending_hash')), + }), + ) + .then((response) => response?.json()) + .then((message) => (delivered = message)) + await until(() => delivered !== undefined) + expect(delivered).toHaveProperty('id', 'msg_pending_hash') + expect((await bodyOf((await send()).final)).diagnostics).toEqual({ + previous_message_id: 'msg_pending_hash', + }) + const logged = () => + debug.mock.calls.some( + ([channel, line]) => + channel === 'cache-diagnostics' && + line.startsWith('MC-CACHE-DIAG ') && + line.includes('"message_id":"msg_pending_hash"'), + ) + expect(logged()).toBe(false) + pending.resolve() + await until(logged) + } finally { + pending.resolve() + await reading + hashSpy.mockRestore() + debug.mockRestore() + native.dispose() + } +}) + +test('OpenCode 2 links the next request to a reply without detailed cache usage', async () => { + const { native, host } = cacheDiagnosticsHost() + const send = () => + host.run(scopeOf(), hostRequest({ ...sonnetPayload(), stream: true })) + const debug = spyOn(core.logger, 'debug').mockImplementation(() => {}) + try { + const { attempt, final } = await send() + const message = diagnosticsMessage('msg_without_breakdown') + const { cache_creation: _omitted, ...usage } = message.usage + await ( + await native.adapter.rewriteResponse?.({ + ...attempt, + attempt, + request: final, + response: new Response( + sse('message_start', { + type: 'message_start', + message: { ...message, usage }, + }) + sse('message_stop', { type: 'message_stop' }), + ), + }) + )?.text() + expect((await bodyOf((await send()).final)).diagnostics).toEqual({ + previous_message_id: 'msg_without_breakdown', + }) + expect( + debug.mock.calls.some(([, line]) => line.startsWith('MC-CACHE-DIAG ')), + ).toBe(false) + } finally { + debug.mockRestore() + native.dispose() + } +}) + test('OpenCode 2 sends null first, then the previous Claude response ID in cache diagnostics', async () => { const { native, host } = cacheDiagnosticsHost() const scope = scopeOf({ sessionID: 'ses_diagnostics_chain' }) @@ -3554,12 +3641,15 @@ describe.each(['direct', 'http'] as const)( ])( '%s recovery sends at most one full create with the same request id', async (code) => { + process.env.ANTHROPIC_INSECURE = '1' const { source } = makeSource({ authorize }) const resent: Request[] = [] + const tls: (Bun.TLSOptions | undefined)[] = [] const native = createNativeAnthropicAdapter({ source, fetch: Object.assign( async (url: string | URL | Request, init?: RequestInit) => { + tls.push((init as RequestInit & { tls?: Bun.TLSOptions })?.tls) resent.push( url instanceof Request ? new Request(url, init) @@ -3641,6 +3731,12 @@ describe.each(['direct', 'http'] as const)( await response?.text() expect(resent).toHaveLength(code === 'unrelated' ? 0 : 1) if (resent[0]) { + if (transport === 'direct') { + expect(resent[0].headers.get('authorization')).toBe( + 'Bearer stable-thread-token', + ) + expect(tls[0]?.rejectUnauthorized ?? true).toBe(true) + } const text = await resent[0].text() const secondText = await second.final.clone().text() expect( diff --git a/packages/opencode/src/tests/opencode2-settings-read.test.ts b/packages/opencode/src/tests/opencode2-settings-read.test.ts index c1d29accc..e5f29e555 100644 --- a/packages/opencode/src/tests/opencode2-settings-read.test.ts +++ b/packages/opencode/src/tests/opencode2-settings-read.test.ts @@ -426,6 +426,19 @@ test('OpenCode 2 shows zero prices only for active OAuth unless opted out', asyn await Bun.sleep(0) expect(price()).toEqual(zeroPrice) + const failedRead = Promise.withResolvers() + active = failedRead.promise + const failure = new Error('temporary connection lookup failure') + const ignoredRejection = active.catch(() => {}) + publish!({ + type: 'credential.updated', + data: { integrationID: 'anthropic' }, + }) + failedRead.reject(failure) + await ignoredRejection + await Bun.sleep(0) + expect(price()).toEqual(zeroPrice) + await select(connection('api-key', 'key')) expect(price()).toEqual(listPrice) await select( diff --git a/packages/opencode/src/tests/request-history.integration.test.ts b/packages/opencode/src/tests/request-history.integration.test.ts index 7a5d1f553..b8f34416b 100644 --- a/packages/opencode/src/tests/request-history.integration.test.ts +++ b/packages/opencode/src/tests/request-history.integration.test.ts @@ -221,7 +221,7 @@ describe('OpenCode 1 OAuth and paid request shaping', () => { }, ) - test('OpenCode 1 verifies TLS for paid sends to a custom address even with the old opt-out set', async () => { + test('OpenCode 1 verifies TLS for sign-in and paid sends even with the old opt-out set', async () => { const baseURL = process.env.ANTHROPIC_BASE_URL const insecure = process.env.ANTHROPIC_INSECURE try { @@ -230,6 +230,10 @@ describe('OpenCode 1 OAuth and paid request shaping', () => { process.env.ANTHROPIC_BASE_URL = 'https://api.anthropic.com' process.env.ANTHROPIC_INSECURE = '1' const { sent } = await capture('api fallback') + expect(sent[0]?.headers.get('authorization')).toBe( + 'Bearer sk-ant-oat01-main-access', + ) + expect(sent[0]!.tls?.rejectUnauthorized ?? true).toBe(true) const paid = sent[1]! expect(new URL(paid.url).origin).toBe('https://paid.invalid') expect(paid.headers.get('x-api-key')).toBe('synthetic-service-tier-key') diff --git a/packages/opencode/src/tests/settings-snapshot-parity.ts b/packages/opencode/src/tests/settings-snapshot-parity.ts index e2dd2700f..dc9ff8ff7 100644 --- a/packages/opencode/src/tests/settings-snapshot-parity.ts +++ b/packages/opencode/src/tests/settings-snapshot-parity.ts @@ -9,6 +9,7 @@ export function cacheKeepWarmSnapshot( const body = JSON.parse(warm.body) // Older OpenCode warms sent the previous-message ID; current warms must not. if (source === 'current') expect(body).not.toHaveProperty('diagnostics') + else expect(body.diagnostics).toEqual({ previous_message_id: null }) return { ...warm, body: promptCacheSnapshot(body) } } diff --git a/packages/opencode/src/v2/adapter.ts b/packages/opencode/src/v2/adapter.ts index 2a9094d3e..233c4c5d7 100644 --- a/packages/opencode/src/v2/adapter.ts +++ b/packages/opencode/src/v2/adapter.ts @@ -14,7 +14,6 @@ import { applyCustomHeaders, assertHostAuthorityStable, assertNotCustodyTombstone, - CACHE_DIAGNOSTICS_BETA, type CacheDiagnosticsRequestContext, type CacheKeepRealTurn, type ClaudeCodeIdentity, @@ -36,6 +35,7 @@ import { getRequestGzipLatch, getRequestGzipLatchPath, guardAnthropicStreamResponse, + hasCacheDiagnosticsBeta, type IncompleteStreamDiagnostics, isDumpEnabled as isDumpEnabledCore, isNativeTransientAccountError, @@ -326,10 +326,12 @@ export interface NativeAnthropicResponseContext

type CacheDiagnosticsSend = Omit< CacheDiagnosticsRequestContext, 'sessionId' | 'isSubagent' -> & - Awaited> & { - requestedModel?: string - } +> & { + betaInfo: Promise< + Awaited> | undefined + > + requestedModel?: string +} /** An `error` event inside a streamed response. */ export interface NativeAnthropicStreamErrorContext

@@ -857,10 +859,7 @@ export function createNativeAnthropicAdapter( Data, NonNullable >() - const cacheDiagnosticsSends = new WeakMap< - Data, - Promise - >() + const cacheDiagnosticsSends = new WeakMap() // Each sent request privately holds its own credentials, so errors about // it can be scrubbed after rewriteSend has dropped the pending credential: // a response scope for the one response the request gets, and a redactor @@ -1838,30 +1837,22 @@ export function createNativeAnthropicAdapter( if (diagnosticsOptIn) { cacheDiagnosticsSends.delete(data) const payload = parseJson(bodyText) + // For a relay, these are the upstream headers inside the envelope, + // not the headers on the outer Request to the relay itself. if ( + hasCacheDiagnosticsBeta(headers) && isRecord(payload) && isRecord(payload.diagnostics) && payload.diagnostics.previous_message_id === diagnosticsOptIn.previousMessageId ) { - const sent = { + cacheDiagnosticsSends.set(data, { ...diagnosticsOptIn, requestedModel: typeof payload.model === 'string' ? payload.model : undefined, ttlSent: summarizeCacheTtl(payload), - } - // For a relay, these are the upstream headers inside the envelope, - // not the headers on the outer Request to the relay itself. - cacheDiagnosticsSends.set( - data, - getCacheDiagnosticsBetas(headers) - .then((betas) => - betas.betas.includes(CACHE_DIAGNOSTICS_BETA) - ? { ...sent, ...betas } - : undefined, - ) - .catch(() => undefined), - ) + betaInfo: getCacheDiagnosticsBetas(headers).catch(() => undefined), + }) } } try { @@ -2108,7 +2099,7 @@ export function createNativeAnthropicAdapter( const context = { ...contextOf(attempt, data), status: response.status, - ...(diagnostics ? { cacheDiagnostics: await diagnostics } : {}), + ...(diagnostics ? { cacheDiagnostics: diagnostics } : {}), } const options = source.responseOptions?.(context) ?? {} const json = data diff --git a/packages/opencode/src/v2/models.ts b/packages/opencode/src/v2/models.ts index d9af0352a..b1bc1eeb0 100644 --- a/packages/opencode/src/v2/models.ts +++ b/packages/opencode/src/v2/models.ts @@ -106,9 +106,14 @@ export function createNativeClaudeModelRules( const refresh = async () => { const generation = ++read // Only the connection kind is needed. Never resolve its secret. - const active = await connection.active('anthropic').catch(() => undefined) - if (abort.signal.aborted || generation !== read) return - oauth = active?.type === 'credential' && active.method === 'oauth' + try { + const active = await connection.active('anthropic') + if (abort.signal.aborted || generation !== read) return + oauth = active?.type === 'credential' && active.method === 'oauth' + } catch { + // Keep the last confirmed pricing until a credential event prompts another read. + return + } reloadIfChanged() } const unwatch = settings?.watch(reloadIfChanged) diff --git a/packages/opencode/src/v2/wire.ts b/packages/opencode/src/v2/wire.ts index ac7899d64..c95917e50 100644 --- a/packages/opencode/src/v2/wire.ts +++ b/packages/opencode/src/v2/wire.ts @@ -2,6 +2,7 @@ import { buildCacheDiagnosticsRecord, CacheDiagnosticsBetaTracker, CacheDiagnosticsTracker, + cacheDiagnosticsMessageId, formatCacheDiagnosticsLogLine, logger, type NativeAccountSnapshot, @@ -212,48 +213,67 @@ export function createNativeWirePolicy( if (!sent || attemptSessions.get(input.attemptId) !== input.sessionID) return const receivedAt = Date.now() - const { record, messageId, canary } = buildCacheDiagnosticsRecord({ - request: { - ...sent, - sessionId: input.sessionID, - isSubagent: options.isSubagent?.(input.sessionID) ?? false, - }, - source: laneStart ? 'start' : 'turn', - accountId: input.accountId, - synthetic: laneStart, - betasHash: sent.betasHash, - requestedModel: sent.requestedModel, - message, - receivedAt, - }) - if (!record || !messageId) { - logger.debug( - 'cache-diagnostics', - 'skipped invalid response envelope', - { - status: input.status, - }, - ) - return - } - logger.debug('cache-diagnostics', formatCacheDiagnosticsLogLine(record)) - const betaLine = cacheDiagnosticBetas.capture( - sent.betasHash, - sent.betas, - ) - if (betaLine) logger.debug('cache-diagnostics', betaLine) - if (canary) - logger.warn( - 'cache-diagnostics', - 'short-gap previous_message_not_found', - { - message_id: canary.messageId, - previous_message_id: canary.previousMessageId, - }, - ) - if (input.kind === 'primary') { + const messageId = cacheDiagnosticsMessageId(message) + // The next request needs the ID even when the reply has no detailed usage. + if ( + messageId && + input.kind === 'primary' && + input.status >= 200 && + input.status < 300 + ) { cacheDiagnostics.capture(input.sessionID, messageId, receivedAt) } + const request = { + previousMessageId: sent.previousMessageId, + previousMessageReceivedAt: sent.previousMessageReceivedAt, + ttlSent: sent.ttlSent, + sessionId: input.sessionID, + isSubagent: options.isSubagent?.(input.sessionID) ?? false, + } + // Only the optional log needs the hash; the host can consume the reply now. + void sent.betaInfo + .then((betaInfo) => { + if (!betaInfo) return + const { record, canary } = buildCacheDiagnosticsRecord({ + request, + source: laneStart ? 'start' : 'turn', + accountId: input.accountId, + synthetic: laneStart, + betasHash: betaInfo.betasHash, + requestedModel: sent.requestedModel, + message, + receivedAt, + }) + if (!record) { + logger.debug( + 'cache-diagnostics', + 'skipped invalid response envelope', + { + status: input.status, + }, + ) + return + } + logger.debug( + 'cache-diagnostics', + formatCacheDiagnosticsLogLine(record), + ) + const betaLine = cacheDiagnosticBetas.capture( + betaInfo.betasHash, + betaInfo.betas, + ) + if (betaLine) logger.debug('cache-diagnostics', betaLine) + if (canary) + logger.warn( + 'cache-diagnostics', + 'short-gap previous_message_not_found', + { + message_id: canary.messageId, + previous_message_id: canary.previousMessageId, + }, + ) + }) + .catch(() => {}) } return { serverSideFallbackModel: model, diff --git a/packages/pi/src/stream.ts b/packages/pi/src/stream.ts index 491829dc5..b9e64ced0 100644 --- a/packages/pi/src/stream.ts +++ b/packages/pi/src/stream.ts @@ -12,7 +12,6 @@ import { buildBillingHeaderValue, buildCacheDiagnosticsRecord, buildPrimeRequestBody, - CACHE_DIAGNOSTICS_BETA, CACHE_DIAGNOSTICS_SESSION_LIMIT, CACHE_KEEP_EXTENDED_TTL_BETA, CacheDiagnosticsBetaTracker, @@ -24,6 +23,7 @@ import { CLAUDE_CODE_ENTRYPOINT, CLAUDE_CODE_IDENTITY, type ClaudeCodeIdentity, + cacheDiagnosticsMessageId, claudeGatewayHeaderValues, claudeGatewayModelUrl, copyStreamResponseTiming, @@ -57,6 +57,7 @@ import { getScopedQuotaWindowForModel, getThinkingPrefixMismatchBehavior, getWaitForReset, + hasCacheDiagnosticsBeta, hostRetryHeaders, hostRetryResponse, isCache1hPersistentlyEnabled, @@ -883,7 +884,7 @@ export async function* parseSse( if (event.type === 'message_start' && cacheDiagnosticsObserver) { const observe = cacheDiagnosticsObserver cacheDiagnosticsObserver = undefined - await observe(event.message).catch(() => {}) + void observe(event.message).catch(() => {}) } yield event } @@ -1065,7 +1066,11 @@ async function sendAnthropicRequestAttempt( primary.previousRequestId = id } const diagnosticsSession = - realSession && !options.apiAccount && !options.prime && !forkHead + realSession && + !options.apiAccount && + !options.prime && + !forkHead && + options.streamOptions?.maxTokens !== 1 ? { id: realSession, token: cacheDiagnosticsSession(realSession), @@ -1802,22 +1807,28 @@ async function sendAnthropicRequestAttempt( } // Thread recovery can replace the prepared body. Attribute the result only // if the actual send carried this diagnostic predecessor and beta. - if (payload.diagnostics?.previous_message_id === previousMessageId) { + if ( + payload.diagnostics?.previous_message_id === previousMessageId && + hasCacheDiagnosticsBeta(headers) + ) { const betas = getCacheDiagnosticsBetas(headers).catch(() => undefined) const ttlSent = summarizeCacheTtl(payload) const requestedModel = typeof payload.model === 'string' ? payload.model : undefined + const current = () => + !init.signal?.aborted && + cacheDiagnosticsSessions.get(diagnosticsSession.id) === + diagnosticsSession.token cacheDiagnosticsObservers.set(response, async (message) => { + if (!current()) return const receivedAt = Date.now() + const messageId = cacheDiagnosticsMessageId(message) + // Record the predecessor before yielding, even if debug logging is delayed or skipped. + if (primaryThread && messageId) + cacheDiagnostics.capture(diagnosticsSession.id, messageId, receivedAt) const sent = await betas - if ( - !sent?.betas.includes(CACHE_DIAGNOSTICS_BETA) || - init.signal?.aborted || - cacheDiagnosticsSessions.get(diagnosticsSession.id) !== - diagnosticsSession.token - ) - return - const { record, messageId, canary } = buildCacheDiagnosticsRecord({ + if (!sent || !current()) return + const { record, canary } = buildCacheDiagnosticsRecord({ request: { sessionId: diagnosticsSession.id, previousMessageId, @@ -1833,7 +1844,7 @@ async function sendAnthropicRequestAttempt( message, receivedAt, }) - if (!record || !messageId) return + if (!record) return logger.debug('cache-diagnostics', formatCacheDiagnosticsLogLine(record)) const betaLine = cacheDiagnosticBetas.capture( sent.betasHash, @@ -1849,8 +1860,6 @@ async function sendAnthropicRequestAttempt( previous_message_id: canary.previousMessageId, }, ) - if (primaryThread) - cacheDiagnostics.capture(diagnosticsSession.id, messageId, receivedAt) }) } } diff --git a/packages/pi/src/tests/stream.test.ts b/packages/pi/src/tests/stream.test.ts index 316e83106..19af26c0f 100644 --- a/packages/pi/src/tests/stream.test.ts +++ b/packages/pi/src/tests/stream.test.ts @@ -1,4 +1,4 @@ -import { afterEach, describe, expect, mock, test } from 'bun:test' +import { afterEach, describe, expect, mock, spyOn, test } from 'bun:test' import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -735,10 +735,19 @@ test.each([ }, ) -test('Pi conversation cache diagnostics link replies and log one beta list per hash', async () => { +async function piCacheDiagnosticsFixture({ + withoutDetailsOn, + fastOpus = false, +}: { + withoutDetailsOn?: number + fastOpus?: boolean +} = {}) { tempDir = await mkdtemp(join(tmpdir(), 'pi-cache-diagnostics-')) const storagePath = join(tempDir, 'accounts.json') const sessionId = 'ses_pi_cache_diagnostics' + const model = fastOpus + ? { ...anthropicModel, id: 'claude-opus-5-5' } + : anthropicModel process.env.PI_ANTHROPIC_AUTH_FILE = storagePath await saveNativePiFixture( { @@ -746,10 +755,16 @@ test('Pi conversation cache diagnostics link replies and log one beta list per h accounts: [], logging: { level: 'debug' }, quota: { enabled: false }, + claudeFast: { enabled: fastOpus }, }, storagePath, ) - const sent: Array<{ diagnostics?: unknown; betas: string[] }> = [] + const sent: Array<{ + diagnostics?: unknown + betas: string[] + authorization: string | null + tls?: Bun.TLSOptions + }> = [] const records: LogTestRecord[] = [] const level = core.getLogLevel() await getPiNativeRuntime(storagePath).service() @@ -760,27 +775,32 @@ test('Pi conversation cache diagnostics link replies and log one beta list per h if (!String(input).includes('/v1/messages')) throw new Error('unexpected request') const body = JSON.parse(String(init?.body)) as { diagnostics?: unknown } - const betas = ( - new Headers(init?.headers).get('anthropic-beta') ?? '' - ).split(',') - sent.push({ diagnostics: body.diagnostics, betas }) + const headers = new Headers(init?.headers) + sent.push({ + diagnostics: body.diagnostics, + betas: (headers.get('anthropic-beta') ?? '').split(','), + authorization: headers.get('authorization'), + tls: (init as RequestInit & { tls?: Bun.TLSOptions })?.tls, + }) return new Response( [ { type: 'message_start', message: { id: `msg_pi_diag_${sent.length}`, - model: anthropicModel.id, + model: model.id, diagnostics: null, usage: { input_tokens: 24, output_tokens: 0, cache_read_input_tokens: 12, cache_creation_input_tokens: 4, - cache_creation: { - ephemeral_5m_input_tokens: 4, - ephemeral_1h_input_tokens: 0, - }, + ...(sent.length !== withoutDetailsOn && { + cache_creation: { + ephemeral_5m_input_tokens: 4, + ephemeral_1h_input_tokens: 0, + }, + }), }, }, }, @@ -794,12 +814,16 @@ test('Pi conversation cache diagnostics link replies and log one beta list per h }, ) as unknown as typeof fetch - const send = (origin: 'agent-loop' | 'direct' = 'agent-loop') => + const send = ( + origin: 'agent-loop' | 'direct' = 'agent-loop', + maxTokens?: number, + ) => streamCortexKitAnthropic( - anthropicModel, + model, anthropicContext, { sessionId, + maxTokens, onPayload: (payload) => payload, onResponse: () => {}, onProviderStreamEvent: () => {}, @@ -809,11 +833,121 @@ test('Pi conversation cache diagnostics link replies and log one beta list per h origin, ).result() beginPiPrimaryTurn(storagePath, sessionId) + const close = () => { + endPiPrimaryTurn(storagePath, sessionId) + forgetPiMessageThread(sessionId) + __setLogTestSink(null) + core.setLogLevel(level) + } + return { send, sent, records, sessionId, close } +} + +test('Pi verifies TLS for sign-in sends even with the old opt-out set', async () => { + const { send, sent, close } = await piCacheDiagnosticsFixture() + const insecure = process.env.ANTHROPIC_INSECURE + try { + process.env.ANTHROPIC_INSECURE = '1' + expect((await send()).stopReason).toBe('stop') + expect(sent).toHaveLength(1) + expect(sent[0]?.authorization).toMatch(/^Bearer \S+$/) + expect(sent[0]!.tls?.rejectUnauthorized ?? true).toBe(true) + } finally { + if (insecure === undefined) delete process.env.ANTHROPIC_INSECURE + else process.env.ANTHROPIC_INSECURE = insecure + close() + } +}) + +test('Pi delivers the reply and captures its ID even while the diagnostics hash is pending', async () => { + const { send, sent, close } = await piCacheDiagnosticsFixture() + const hash = core.getCacheDiagnosticsBetas + const started = Promise.withResolvers() + const pending = Promise.withResolvers() + const hashSpy = spyOn(core, 'getCacheDiagnosticsBetas').mockImplementation( + async (headers) => { + started.resolve() + await pending.promise + return hash(headers) + }, + ) + const reading = send() + try { + await Promise.race([reading, started.promise]) + expect(hashSpy).toHaveBeenCalledTimes(1) + const result = await Promise.race([reading, Bun.sleep(150)]) + expect(result).toMatchObject({ + stopReason: 'stop', + responseId: 'msg_pi_diag_1', + }) + expect((await send()).stopReason).toBe('stop') + expect(sent[1]?.diagnostics).toEqual({ + previous_message_id: 'msg_pi_diag_1', + }) + } finally { + pending.resolve() + await reading + hashSpy.mockRestore() + close() + } +}) + +test('Pi links the next request to a reply without detailed cache usage', async () => { + const { send, sent, records, close } = await piCacheDiagnosticsFixture({ + withoutDetailsOn: 1, + }) + try { + expect((await send()).stopReason).toBe('stop') + expect((await send()).stopReason).toBe('stop') + expect(sent[1]?.diagnostics).toEqual({ + previous_message_id: 'msg_pi_diag_1', + }) + expect( + records.some( + ({ message }) => + message.startsWith('MC-CACHE-DIAG ') && + message.includes('"message_id":"msg_pi_diag_1"'), + ), + ).toBe(false) + } finally { + close() + } +}) + +test('Pi keeps one-token SDK warms out of cache diagnostics', async () => { + const { send, sent, records, close } = await piCacheDiagnosticsFixture() + try { + expect((await send()).stopReason).toBe('stop') + expect((await send('agent-loop', 1)).stopReason).toBe('stop') + expect((await send()).stopReason).toBe('stop') + expect(sent.map((request) => request.diagnostics)).toEqual([ + { previous_message_id: null }, + undefined, + { previous_message_id: 'msg_pi_diag_1' }, + ]) + const lines = records.filter(({ message }) => + message.startsWith('MC-CACHE-DIAG '), + ) + expect( + lines.map( + ({ message }) => + JSON.parse(message.slice('MC-CACHE-DIAG '.length)).message_id, + ), + ).toEqual(['msg_pi_diag_1', 'msg_pi_diag_3']) + } finally { + close() + } +}) + +test('Pi conversation cache diagnostics link replies and log one beta list per hash', async () => { + // Use a distinct beta set because the reporter deduplicates across sessions. + const { send, sent, records, sessionId, close } = + await piCacheDiagnosticsFixture({ fastOpus: true }) try { expect((await send()).stopReason).toBe('stop') expect((await send('direct')).stopReason).toBe('stop') expect((await send()).stopReason).toBe('stop') expect(sent[0]?.betas).toContain(core.CACHE_DIAGNOSTICS_BETA) + expect(sent[0]?.betas).toContain(core.FAST_MODE_BETA) expect(sent.map((request) => request.diagnostics)).toEqual([ { previous_message_id: null }, { previous_message_id: 'msg_pi_diag_1' }, @@ -854,10 +988,7 @@ test('Pi conversation cache diagnostics link replies and log one beta list per h `MC-CACHE-DIAG-BETAS ${JSON.stringify({ hash: auxiliary.betas_hash, betas: [...sent[1]!.betas].sort() })}`, ]) } finally { - endPiPrimaryTurn(storagePath, sessionId) - forgetPiMessageThread(sessionId) - __setLogTestSink(null) - core.setLogLevel(level) + close() } }) From b11eb8d6d9afb8a0bf34b55bab5aed47ccb207a3 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:47:07 +0100 Subject: [PATCH 24/27] Changelog: parity audit fixes --- CHANGELOG.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 64ba0b0d8..06b989a79 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,16 @@ This repo is a CortexKit-maintained Anthropic auth monorepo for OpenCode and Pi. - Pi now links cache diagnostics across conversation replies like OpenCode 1 and 2, with cache results and beta lists in the debug log. - OpenCode 2 now uses the five-minute Claude prompt cache by default, like OpenCode 1 and Pi. An explicit cache setting or Agent Runner session policy still takes precedence. - OpenCode 1 no longer publishes the optional quota header feed; quota readings still reach the vault. The `quota_header_feed_enabled` setting is gone and can be deleted from your settings file. +- OpenCode 1 on Thalamus honors Claude's own wait before using the main login, even when shared routing picks it, and tries another eligible login when a routing pick can't authenticate. +- OpenCode 1 no longer switches to a paid API key on a retry where shared routing gave advice, retries an earlier login once when nothing untried can serve, and asks shared routing before sending one-shot request bodies. +- OpenCode 1 and 2 no longer wait for saved keep-warm sessions before starting or sending the first request. +- OpenCode 1 and 2 servers sharing an account store no longer warm the same saved session twice or overwrite its warm budget; all three hosts now use one keep-warm session claim. +- Pi's paid API-key requests keep Pi's own prompt-cache markers. +- Pi's hybrid cache keeps the same layout at five minutes and one hour, can reuse a long first prompt's cache after a long tool exchange, and lets forks reach the head's cache at the 20-block lookback limit. +- Pi: only a lane start queued from `/claude` gets the one-token warm, and it no longer joins the conversation's request chain. +- Pi: `/claude` quota refresh continues when one account fails, and editing killswitch thresholds no longer turns the killswitch on. +- OpenCode 2 and Pi no longer wait for optional cache diagnostics before delivering replies, and keep diagnostics linked to the latest reply when detailed cache usage is missing. +- OpenCode 2 keeps subscription prices at zero when a credential lookup fails temporarily. ## 2.16.6 From 41e7f7029bd969010696ca31e49ea475244f8628 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:50:08 +0100 Subject: [PATCH 25/27] Comments and changelog wording from review --- CHANGELOG.md | 4 ++-- packages/opencode/src/index.ts | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 06b989a79..38f72cb6f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,12 +31,12 @@ This repo is a CortexKit-maintained Anthropic auth monorepo for OpenCode and Pi. - OpenCode 2 now uses the five-minute Claude prompt cache by default, like OpenCode 1 and Pi. An explicit cache setting or Agent Runner session policy still takes precedence. - OpenCode 1 no longer publishes the optional quota header feed; quota readings still reach the vault. The `quota_header_feed_enabled` setting is gone and can be deleted from your settings file. - OpenCode 1 on Thalamus honors Claude's own wait before using the main login, even when shared routing picks it, and tries another eligible login when a routing pick can't authenticate. -- OpenCode 1 no longer switches to a paid API key on a retry where shared routing gave advice, retries an earlier login once when nothing untried can serve, and asks shared routing before sending one-shot request bodies. +- OpenCode 1 no longer switches to a paid API key on a retry where shared routing picked a login, retries an earlier login once when nothing untried can serve, and asks shared routing before sending one-shot request bodies. - OpenCode 1 and 2 no longer wait for saved keep-warm sessions before starting or sending the first request. - OpenCode 1 and 2 servers sharing an account store no longer warm the same saved session twice or overwrite its warm budget; all three hosts now use one keep-warm session claim. - Pi's paid API-key requests keep Pi's own prompt-cache markers. - Pi's hybrid cache keeps the same layout at five minutes and one hour, can reuse a long first prompt's cache after a long tool exchange, and lets forks reach the head's cache at the 20-block lookback limit. -- Pi: only a lane start queued from `/claude` gets the one-token warm, and it no longer joins the conversation's request chain. +- Pi: only the cache-warming request queued from `/claude` is cut to one token (a prompt with the same text is sent normally), and it no longer joins the conversation's request chain. - Pi: `/claude` quota refresh continues when one account fails, and editing killswitch thresholds no longer turns the killswitch on. - OpenCode 2 and Pi no longer wait for optional cache diagnostics before delivering replies, and keep diagnostics linked to the latest reply when detailed cache usage is missing. - OpenCode 2 keeps subscription prices at zero when a credential lookup fails temporarily. diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index 70d15b9d7..29d3d78f1 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -9350,7 +9350,8 @@ const anthropicAuthPlugin = async ( !quotaManager.shouldRefreshOnRequestCount(sessionRequestCount) ) return - // The native runtime obtains the credential for the quota poll. + // The empty token is deliberate: the shared account runtime + // (nativeAccounts) fetches the account's credential for the poll. void quotaManager .refreshFallback(account.id, '', account) .then(() => refreshSidebarQuota()) From 3af1d9ac2f5b79ad22b1b4eea5f01eeeaa1ef351 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:57:18 +0100 Subject: [PATCH 26/27] Tests: Pi killswitch-set leaves the switch alone; loopback test fetches don't pool sockets across tests --- packages/opencode/src/tests/setup.ts | 7 ++++++- packages/pi/src/tests/settings-menu.test.ts | 13 ++++++++----- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/packages/opencode/src/tests/setup.ts b/packages/opencode/src/tests/setup.ts index 430cd0063..e1c50dfeb 100644 --- a/packages/opencode/src/tests/setup.ts +++ b/packages/opencode/src/tests/setup.ts @@ -114,7 +114,12 @@ export function createGuardedFetch( request, // Bun's connection-pool opt-out is a fetch option, not a Request // property. Preserve it when rebuilding requests, including redirects. - { keepalive: init?.keepalive }, + // Tests default to no pooling: every test starts its own loopback + // servers, and when the OS gives a new server a port an earlier, + // stopped server used, Bun reuses the stale pooled socket and the + // request fails with ECONNRESET. A test that needs pooling passes + // keepalive: true. + { keepalive: init?.keepalive ?? false }, ]) if (!REDIRECT_STATUSES.has(response.status)) return response const location = response.headers.get('location') diff --git a/packages/pi/src/tests/settings-menu.test.ts b/packages/pi/src/tests/settings-menu.test.ts index 4891a893f..9fabb8865 100644 --- a/packages/pi/src/tests/settings-menu.test.ts +++ b/packages/pi/src/tests/settings-menu.test.ts @@ -231,14 +231,14 @@ const actions: SettingCase[] = [ values: { entries: [{ account: 'main', fh: 3, sd: 4 }] }, }, initial: {}, + // Editing thresholds leaves the on/off switch alone, as on OpenCode 2; + // the tests below check that it isn't written. expected: { - killswitch_enabled: true, killswitch_default_five_hour: 3, killswitch_default_seven_day: 4, }, legacy: { killswitch: { - enabled: true, main: { five_hour: 3, seven_day: 4, scoped: 0 }, }, }, @@ -349,6 +349,8 @@ for (const mode of ['user-file', 'legacy', 'separate'] as const) ...setting.expected, }) expect(await fs.readFile(paths.config, 'utf8')).toBe(before) + if (setting.request.action === 'killswitch-set') + expect(parse(text)).not.toHaveProperty('killswitch_enabled') if (setting.request.action === 'cachekeep-always') expect(parse(text)).not.toHaveProperty('cache_keep_window') if (setting.request.action === 'cachekeep-subagents') @@ -358,9 +360,10 @@ for (const mode of ['user-file', 'legacy', 'separate'] as const) ), ).toEqual(['cache_keep_subagents']) } else { - expect(parse(await fs.readFile(paths.config, 'utf8'))).toMatchObject( - setting.legacy, - ) + const legacy = parse(await fs.readFile(paths.config, 'utf8')) + expect(legacy).toMatchObject(setting.legacy) + if (setting.request.action === 'killswitch-set') + expect(legacy.killswitch?.enabled).not.toBe(true) if (userBefore) expect(await fs.readFile(file, 'utf8')).toBe(userBefore) else expect(await fs.exists(file)).toBe(false) } From d7e754d76350f232f51bfe5fe11e2950c692dcf3 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:01:49 +0100 Subject: [PATCH 27/27] Keep-warm session claims survive a wall-clock step during setup and are never taken over on boot-time evidence alone --- packages/core/src/cachekeep-store.ts | 25 +++++++- .../core/src/tests/cachekeep-store.test.ts | 62 +++++++++++++++++++ .../src/tests/opencode1-settings-read.test.ts | 32 +++++----- .../tests/support/opencode1-test-context.ts | 1 + 4 files changed, 101 insertions(+), 19 deletions(-) create mode 100644 packages/core/src/tests/cachekeep-store.test.ts diff --git a/packages/core/src/cachekeep-store.ts b/packages/core/src/cachekeep-store.ts index 2f03f079d..09c7e37b9 100644 --- a/packages/core/src/cachekeep-store.ts +++ b/packages/core/src/cachekeep-store.ts @@ -6,6 +6,7 @@ import { join } from 'node:path' import { setTimeout as delay } from 'node:timers/promises' import { promisify } from 'node:util' import { gunzip, gzip } from 'node:zlib' +import { LockOwnershipError } from '@cortexkit/common-auth/fs' import { CACHE_KEEP_MAX_BODY_BYTES, type CacheKeepTarget } from './cachekeep.ts' import { ensureHolderDirectory, @@ -175,9 +176,19 @@ export class CacheKeepClaim { async acquire() { if (this.held) return true await ensureHolderDirectory(this.directory, this.options.ownerOnly) + let retriedOwnershipLoss = false for (;;) { - const result = await this.tryAcquire() - if (result !== 'sweep') return result + try { + const result = await this.tryAcquire() + if (result !== 'sweep') return result + } catch (error) { + if (retriedOwnershipLoss || !(error instanceof LockOwnershipError)) + throw error + // A wall-clock step or a suspend can expire the publication lock. + // Reacquire once and recheck whether another process claimed the session. + retriedOwnershipLoss = true + continue + } // A sweep only borrows ownership to inspect one record. A resuming // session waits in the background rather than abandoning its claim. await delay(25) @@ -188,7 +199,15 @@ export class CacheKeepClaim { return withNativeLock(this.path, CLAIM_LOCK, async (lease) => { const existing = await this.read() const life = holderEntryLiveness(existing) - if (life && (await holderEntryIsLive(life, this.options.liveness))) + // Without an incarnation, a live PID still blocks takeover. A wall-clock + // correction is not evidence that its registration predates this boot. + if ( + life && + (await holderEntryIsLive( + { pid: life.pid, incarnation: life.incarnation }, + this.options.liveness, + )) + ) return this.purpose === 'session' && existing?.purpose === 'sweep' ? ('sweep' as const) : false diff --git a/packages/core/src/tests/cachekeep-store.test.ts b/packages/core/src/tests/cachekeep-store.test.ts new file mode 100644 index 000000000..9bcd1b10b --- /dev/null +++ b/packages/core/src/tests/cachekeep-store.test.ts @@ -0,0 +1,62 @@ +import { expect, test } from 'bun:test' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { CacheKeepClaim } from '../cachekeep-store.ts' + +test('a forward wall-clock step during publication does not prevent claiming a live session', async () => { + const root = await mkdtemp(join(tmpdir(), 'cachekeep-claim-')) + const realNow = Date.now + let offset = 0 + const claim = new CacheKeepClaim(root, 'session', { + liveness: { + pidAlive: (pid) => pid === process.pid, + incarnation: async () => { + // Step the wall clock while the process is reading its own identity. + offset = 30_000 + return 'live-process' + }, + }, + }) + try { + Date.now = () => realNow() + offset + expect(await claim.acquire()).toBe(true) + expect(await claim.isCurrent()).toBe(true) + } finally { + Date.now = realNow + try { + await claim.release() + } finally { + await rm(root, { recursive: true, force: true }) + } + } +}) + +test('a forward wall-clock step cannot displace a live claim without an incarnation', async () => { + const root = await mkdtemp(join(tmpdir(), 'cachekeep-claim-')) + const realNow = Date.now + const liveness = { + pidAlive: (pid: number) => pid === process.pid, + incarnation: async () => null, + uptime: () => 60, + } + const holder = new CacheKeepClaim(root, 'session', { liveness }) + const contender = new CacheKeepClaim(root, 'session', { liveness }) + try { + expect(await holder.acquire()).toBe(true) + expect(await contender.acquire()).toBe(false) + // Correct a wall clock that was ten minutes slow shortly after boot. + Date.now = () => realNow() + 10 * 60_000 + expect(await holder.isCurrent()).toBe(true) + expect(await contender.acquire()).toBe(false) + expect(await holder.isCurrent()).toBe(true) + } finally { + Date.now = realNow + try { + await contender.release() + await holder.release() + } finally { + await rm(root, { recursive: true, force: true }) + } + } +}) diff --git a/packages/opencode/src/tests/opencode1-settings-read.test.ts b/packages/opencode/src/tests/opencode1-settings-read.test.ts index 35064b003..356d0d756 100644 --- a/packages/opencode/src/tests/opencode1-settings-read.test.ts +++ b/packages/opencode/src/tests/opencode1-settings-read.test.ts @@ -39,6 +39,7 @@ import { createOpencode1Test, createOpencode1TestContext, installOpencode1TestHooks, + type PluginRuntimeOverrides, } from './support/opencode1-test-context' import { MESSAGES_URL } from './test-fetch' @@ -204,8 +205,16 @@ async function fixture( }, ), ) as unknown as typeof fetch - const launch = async (directory?: string) => { - const plugin = await getPlugin(ctx, createMockClient(), directory) + const launch = async ( + directory?: string, + runtimeOverrides?: PluginRuntimeOverrides, + ) => { + const plugin = await getPlugin( + ctx, + createMockClient(), + directory, + runtimeOverrides, + ) const runtime = runtimes.at(-1)! const loader = await plugin.auth!.loader!( async () => ({ @@ -890,12 +899,7 @@ describe('OpenCode 1 user gateway', () => { } test('model and keep-warm requests go to the gateway as full uncompressed requests; nothing else does', async () => { - let now = 1_000 - const realNow = Date.now - Date.now = mock(() => now) as unknown as typeof Date.now - cleanups.push(() => { - Date.now = realNow - }) + let now = Date.now() const f = await fixture() await f.put({ quota_enabled: 'off', @@ -908,7 +912,7 @@ describe('OpenCode 1 user gateway', () => { }) const seen = record() const records = logs() - const instance = await f.launch() + const instance = await f.launch(undefined, { now: () => now }) const response = await instance.loader.fetch!( MESSAGES_URL, largeRequest('ses-oc1-gateway'), @@ -1048,12 +1052,7 @@ describe('OpenCode 1 user gateway', () => { ) test('gateway errors echoing a gateway header value are redacted for model and keep-warm sends, logs and dumps', async () => { - let now = 1_000 - const realNow = Date.now - Date.now = mock(() => now) as unknown as typeof Date.now - cleanups.push(() => { - Date.now = realNow - }) + let now = Date.now() const dumps = await fs.mkdtemp(join(ctx.migratedPool!.root, 'dumps-')) const previousDir = process.env.OPENCODE_ANTHROPIC_AUTH_DUMP_DIR process.env.OPENCODE_ANTHROPIC_AUTH_DUMP_DIR = dumps @@ -1079,7 +1078,8 @@ describe('OpenCode 1 user gateway', () => { body.max_tokens === 0 ? echo(401) : undefined, ) const records = logs() - const instance = await f.launch() + // Advance the scheduler without stepping the wall clock under the claim lock. + const instance = await f.launch(undefined, { now: () => now }) const live = await instance.loader.fetch!( MESSAGES_URL, largeRequest('ses-oc1-gateway-redact'), diff --git a/packages/opencode/src/tests/support/opencode1-test-context.ts b/packages/opencode/src/tests/support/opencode1-test-context.ts index d3ab643e7..5e45e540e 100644 --- a/packages/opencode/src/tests/support/opencode1-test-context.ts +++ b/packages/opencode/src/tests/support/opencode1-test-context.ts @@ -21,6 +21,7 @@ export type PoolLogin = { access: string; refresh: string; identity: string } export type PluginRuntimeOverrides = Partial<{ authorize: typeof import('@cortexkit/anthropic-auth-core').authorize + now: () => number setTimeout: typeof globalThis.setTimeout clearTimeout: typeof globalThis.clearTimeout setInterval: typeof globalThis.setInterval