Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ This repo is a CortexKit-maintained Anthropic auth monorepo for OpenCode and Pi.

## Unreleased

- 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.
- OpenCode 2: retries after a rate limit try other available accounts before cycling back to one that already refused the request. Accounts with confirmed exhaustion are skipped.
- OpenCode 1 and 2: every step served by Anthropic's safety fallback now writes one log line with per-attempt token counts; OpenCode 2 previously logged nothing. The safety-fallback notice no longer says follow-up requests stay on the fallback model.

Expand Down
62 changes: 55 additions & 7 deletions packages/core/scripts/check-native-quota-compatibility.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ import { pathToFileURL } from 'node:url'
import type { QuotaCodec } from '@cortexkit/common-auth/quota'
import type { OAuthQuotaSnapshot } from '../src/accounts.ts'
import {
mergeInsulaQuota,
normalizeInsulaClaudeQuota,
} from '../src/insula-quota.ts'
import {
fromNativeQuotaMap,
type NativeQuotaMap,
nativeQuotaCodec,
toNativeQuotaMap,
Expand All @@ -24,19 +29,18 @@ async function run(command: string[], cwd: string) {
return stdout
}

/** Network integration guard against making a shared pool unreadable after rollback. */
test('quota maps written by the shared store remain accepted by the published Core 2.2.7 codec', async () => {
async function checkPublishedQuotaCodec(version: string) {
const scratch = new URL('../../../target/scratch/', import.meta.url).pathname
await mkdir(scratch, { recursive: true })
const root = await mkdtemp(join(scratch, 'quota-format-227-'))
const root = await mkdtemp(join(scratch, `quota-format-${version}-`))
try {
// npm 11 prints an array of records, npm 12 an object keyed by package name.
const packed: unknown = JSON.parse(
await run(
[
'npm',
'pack',
'@cortexkit/anthropic-auth-core@2.2.7',
`@cortexkit/anthropic-auth-core@${version}`,
'--json',
'--pack-destination',
root,
Expand All @@ -47,7 +51,7 @@ test('quota maps written by the shared store remain accepted by the published Co
const [pack] = (
Array.isArray(packed) ? packed : Object.values(packed as object)
) as Array<{ filename: string; version: string; shasum: string }>
if (pack?.version !== '2.2.7')
if (pack?.version !== version)
throw new Error('Wrong compatibility release')
console.log(
'QUOTA_COMPATIBILITY_PACK',
Expand Down Expand Up @@ -110,10 +114,47 @@ test('quota maps written by the shared store remain accepted by the published Co
five_hour: { usedPercent: 12, remainingPercent: 88, checkedAt: 2000 },
seven_day: { usedPercent: 21, remainingPercent: 79, checkedAt: 2000 },
}
const weeklyOnly = { ...poll, five_hour: undefined }
const weeklyHeaders = { ...headers, five_hour: undefined }
const insula = normalizeInsulaClaudeQuota(
{
provider: 'claude',
account: identity,
fetchedAt: new Date(1500).toISOString(),
source: 'vault',
usage: { secondary: { usedPercent: 15 } },
},
{ fetchedAt: 1500 },
)
if (!insula) throw new Error('Expected a cached quota reading')
const afterHeaders = fromNativeQuotaMap(
nativeQuotaCodec.merge(
toNativeQuotaMap(weeklyOnly),
toNativeQuotaMap(weeklyHeaders),
),
)
const cases: Array<{ name: string; readings: OAuthQuotaSnapshot[] }> = [
{ name: 'full poll', readings: [poll] },
{ name: 'poll followed by headers', readings: [poll, headers] },
{ name: 'headers followed by an older poll', readings: [headers, poll] },
{
name: 'local poll clock survives newer headers on both standard windows',
readings: [{ ...poll, scoped: [] }, headers],
},
{
name: 'vault Insula reading brings the poll clock forward independently of headers',
readings: [
weeklyOnly,
weeklyHeaders,
{
...mergeInsulaQuota(insula, afterHeaders),
accountIdentity: identity,
},
],
},
{
name: 'headers followed by an older poll',
readings: [headers, poll],
},
{
name: 'newer complete poll clears optional fields',
readings: [poll, { ...headers, source: 'poll', scoped: [] }],
Expand Down Expand Up @@ -207,4 +248,11 @@ test('quota maps written by the shared store remain accepted by the published Co
} finally {
await rm(root, { recursive: true, force: true })
}
}, 60_000)
}

/** Network integration guard against making a shared pool unreadable after rollback. */
test.each(['2.2.7', '2.16.4'])(
'quota maps written by the shared store remain accepted by the published Core %s codec',
checkPublishedQuotaCodec,
60_000,
)
52 changes: 46 additions & 6 deletions packages/core/src/accounts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -663,6 +663,35 @@ export function quotaFieldSource(
)
}

/** The poll's clock, independent of newer standard windows read from headers. */
export function quotaPollCheckedAt(quota: OAuthQuotaSnapshot | undefined) {
if (!quota) return 0
const standard = ['five_hour', 'seven_day'] as const
const hasPoll =
quota.source === 'poll' ||
quotaSnapshotOmitsFiveHour(quota) ||
quota.scoped !== undefined ||
quota.extraUsage !== undefined ||
standard.some((key) => quotaFieldSource(quota, key) === 'poll')
if (!hasPoll) return 0
// Older mixed snapshots could put a header's clock here. Use only the
// surviving poll windows in that case; if none survived, the poll is due.
const topLevelIsHeader = standard.some(
(key) =>
quotaFieldSource(quota, key) === 'headers' &&
quota[key]?.checkedAt === quota.checkedAt,
)
return Math.max(
!topLevelIsHeader ? (quota.checkedAt ?? 0) : 0,
...(quota.scoped ?? []).map((window) => window.checkedAt),
...standard.map((key) =>
quotaFieldSource(quota, key) === 'poll'
? (quota[key]?.checkedAt ?? 0)
: 0,
),
)
}

function fieldSourcesForMergedQuota(
existing: OAuthQuotaSnapshot,
incoming: OAuthQuotaSnapshot,
Expand Down Expand Up @@ -712,13 +741,24 @@ export function mergeHeaderQuotaForPersistence(
) {
if (!existing || incoming.source !== 'headers') return incoming
const preservePollBinding = existing.bindingWindowSource === 'poll'
const pollCheckedAt = quotaPollCheckedAt(existing)
const preservePollFields =
pollCheckedAt > 0 && quotaPollCheckedAt(incoming) <= pollCheckedAt
const merged = {
...existing,
...incoming,
five_hour: mergeHeaderOwnedWindow(existing, incoming, 'five_hour'),
seven_day: mergeHeaderOwnedWindow(existing, incoming, 'seven_day'),
scoped: mergeHeaderScopedQuota(existing, incoming),
extraUsage: existing.extraUsage ?? incoming.extraUsage,
// A response may carry the poll fields seen at dispatch. Do not let it
// restore fields that a newer stored poll removed. Independently timed
// scoped observations still merge by window.
scoped:
preservePollFields && quotaFieldSource(incoming, 'scoped') !== 'headers'
? existing.scoped
: mergeHeaderScopedQuota(existing, incoming),
extraUsage: preservePollFields
? existing.extraUsage
: (existing.extraUsage ?? incoming.extraUsage),
fallbackAdvised:
incoming.fieldSources?.fallbackAdvised !== undefined
? incoming.fallbackAdvised
Expand All @@ -729,10 +769,10 @@ export function mergeHeaderQuotaForPersistence(
bindingWindowSource: preservePollBinding
? 'poll'
: (incoming.bindingWindowSource ?? existing.bindingWindowSource),
// Keep the successful poll's absence evidence and original clock so later
// merges can distinguish older polls from newer observations.
...(quotaSnapshotOmitsFiveHour(existing) && {
checkedAt: existing.checkedAt,
// Headers advance their own windows, not the age of the scoped limits or
// credits. The poll clock also dates evidence that the 5h limit is absent.
...(pollCheckedAt > 0 && {
checkedAt: pollCheckedAt,
}),
} satisfies OAuthQuotaSnapshot
const fieldSources = fieldSourcesForMergedQuota(existing, incoming, merged)
Expand Down
37 changes: 14 additions & 23 deletions packages/core/src/insula-quota.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ import {
type OAuthExtraUsageSnapshot,
type OAuthQuotaSnapshot,
type QuotaFieldSources,
quotaFieldSource,
quotaPollCheckedAt,
quotaSnapshotCheckedAt,
quotaSnapshotOmitsFiveHour,
} from './accounts.ts'

/** An insula reading in the shape our usage poll produces, before the account identity is attached. */
Expand Down Expand Up @@ -224,41 +225,31 @@ function newer<T extends { checkedAt: number }>(
* a window read after insula's fetch (a response header, or our own poll).
* Stored quota is replaced as one snapshot, newest wins, so publishing the
* older insula reading as is would be refused and lose its other windows.
* Keep the newer reading of each window instead.
* Keep newer standard windows, but take scoped limits and credits together
* from the newest poll, including fields it no longer reports.
*/
export function mergeInsulaQuota(
reading: InsulaClaudeQuota,
stored: OAuthQuotaSnapshot | undefined,
): OAuthQuotaSnapshot {
if (!stored || quotaSnapshotCheckedAt(stored) <= reading.checkedAt)
return reading
const five_hour = quotaSnapshotOmitsFiveHour(stored)
? undefined
: !reading.five_hour &&
(stored.five_hour?.checkedAt ?? 0) <= reading.checkedAt
if (!stored) return reading
if (quotaPollCheckedAt(stored) > reading.checkedAt) return stored
if (quotaSnapshotCheckedAt(stored) <= reading.checkedAt) return reading
const five_hour =
!reading.five_hour &&
(stored.five_hour?.checkedAt ?? 0) <= reading.checkedAt
? undefined
: newer(reading.five_hour, stored.five_hour)
const seven_day = newer(reading.seven_day, stored.seven_day)
const scoped = new Map(reading.scoped.map((window) => [window.id, window]))
for (const window of stored.scoped ?? []) {
const merged = newer(scoped.get(window.id), window)
if (merged) scoped.set(window.id, merged)
}
const fieldSources: QuotaFieldSources = { ...reading.fieldSources }
if (five_hour !== reading.five_hour && stored.fieldSources?.five_hour)
fieldSources.five_hour = stored.fieldSources.five_hour
if (seven_day !== reading.seven_day && stored.fieldSources?.seven_day)
fieldSources.seven_day = stored.fieldSources.seven_day
if (five_hour && five_hour !== reading.five_hour)
fieldSources.five_hour = quotaFieldSource(stored, 'five_hour')
if (seven_day !== reading.seven_day)
fieldSources.seven_day = quotaFieldSource(stored, 'seven_day')
return {
...reading,
five_hour,
...(seven_day && { seven_day }),
scoped: [...scoped.values()],
checkedAt: quotaSnapshotOmitsFiveHour(stored)
? stored.checkedAt
: quotaSnapshotOmitsFiveHour(reading)
? reading.checkedAt
: Math.max(reading.checkedAt, quotaSnapshotCheckedAt(stored)),
fieldSources,
}
}
6 changes: 5 additions & 1 deletion packages/core/src/native-account-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,10 @@ import {
stateLayoutOfPaths,
} from './pool-paths.ts'
import { createNativePoolStore, nativePoolStoreLocks } from './pool-store.ts'
import type { QuotaRequestDispatch } from './quota-manager.ts'
import {
QuotaRefreshDeferred,
type QuotaRequestDispatch,
} from './quota-manager.ts'
import { effectiveRelayTransport, type RelayConfig } from './relay.ts'
import {
createRelayLocationCheck,
Expand Down Expand Up @@ -2050,6 +2053,7 @@ function buildNativeAccountRuntime(
const snapshot = await runtime.read()
if (snapshot.mode === 'claustrum')
return vault.fetchQuota(routeId, fetchImpl, signal, dispatch, purpose)
if (purpose === 'background-cache') throw new QuotaRefreshDeferred()
const before = snapshot.accounts.find((row) => row.id === routeId)
const result = await fetchReading(
routeId,
Expand Down
25 changes: 21 additions & 4 deletions packages/core/src/native-quota-codec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import {
QUOTA_FIELD_NAMES,
type QuotaFieldSources,
type QuotaMoney,
quotaPollCheckedAt,
quotaSnapshotCheckedAt,
quotaSnapshotOmitsFiveHour,
} from './accounts.ts'

type ScopedMetadata = {
Expand Down Expand Up @@ -441,13 +441,12 @@ export const nativeQuotaCodec: QuotaCodec = {
)
const previousTime = quotaSnapshotCheckedAt(previous)
const incomingTime = quotaSnapshotCheckedAt(incoming)
const previousPollAt = quotaPollCheckedAt(previous)
// Poll order is the read's own clock, not a retained scoped/header clock.
if (
incoming.source === 'poll' &&
incoming.checkedAt !== undefined &&
previous.checkedAt !== undefined &&
(previous.source === 'poll' || quotaSnapshotOmitsFiveHour(previous)) &&
incoming.checkedAt < previous.checkedAt
incoming.checkedAt < previousPollAt
)
return toNativeQuotaMap(previous)
// A newer complete poll owns the absence of a session limit even if a
Expand All @@ -466,9 +465,27 @@ export const nativeQuotaCodec: QuotaCodec = {
? mergeHeaderQuotaForPersistence(incoming, {
...previous,
five_hour: undefined,
scoped: undefined,
extraUsage: undefined,
})
: incoming,
)
if (
incoming.source === 'poll' &&
incoming.checkedAt !== undefined &&
previous.source === 'headers' &&
previousPollAt > 0 &&
previousTime > incomingTime
)
// A header can arrive after the poll completed but before it was stored.
// Preserve the newer standard readings without copying old poll fields.
return toNativeQuotaMap(
mergeHeaderQuotaForPersistence(incoming, {
...previous,
scoped: undefined,
extraUsage: undefined,
}),
)
return toNativeQuotaMap(
previousTime > incomingTime ||
(previousTime === incomingTime &&
Expand Down
20 changes: 15 additions & 5 deletions packages/core/src/native-vault-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,14 +145,16 @@ export interface NativeVaultRuntimeOptions {
* minute per daemon and enrollment), look the route's account up in it,
* and skip the usage GET for a current reading, a cold cache or an upstream
* failure. Skipped misses leave the account due for the next sweep.
* - 'background-cache': apply a current reading from the already-warmed
* cache even if recent headers mean a provider poll is not due.
* - 'admission': a request needs a reading. Look the served credential's
* account up in insula's cache only, never refreshing it, then poll on a
* miss except an upstream failure, which uses a dated reading if attached
* and otherwise leaves quota unknown.
* Omitted: poll Anthropic directly (explicit user refreshes and other
* callers that must see the provider's own reading).
*/
export type NativeVaultQuotaPurpose = QuotaReadingPurpose
export type NativeVaultQuotaPurpose = QuotaReadingPurpose | 'background-cache'

export interface NativeVaultWatchOptions {
intervalMs: number
Expand Down Expand Up @@ -1249,18 +1251,23 @@ export function createNativeVaultRuntime(
},
async fetchQuota(routeId, fetchImpl = fetch, signal, dispatch, purpose) {
const row = await rowFor(await runtime.read(), routeId)
const cacheOnly = purpose === 'background-cache'
// A background sweep asks insula about the roster row's account (its
// list_scoped account_id) before any credential is fetched.
let swept: InsulaQuotaResult<InsulaClaudeQuota> | undefined
if (purpose === 'background' && row) {
await refreshInsula()
if ((purpose === 'background' || cacheOnly) && row) {
// The background sweep already warmed the cache. Leave provider polling
// to the due-gated background path when there is no current reading.
if (!cacheOnly) await refreshInsula()
check(signal)
swept = insulaLookup(row.accountIdentity)
if (swept.miss === 'cold' || swept.miss === 'upstream-failed') {
noteQuotaSource(row.routeId, 'skipped', swept.miss)
throw new QuotaRefreshDeferred()
}
}
if (cacheOnly && (swept?.miss || !swept?.reading))
throw new QuotaRefreshDeferred()
const state = await readNativeRuntime(paths.runtime, paths.storageId)
const before =
state.status === 'ready'
Expand Down Expand Up @@ -1291,7 +1298,7 @@ export function createNativeVaultRuntime(
miss: 'unreachable',
}
let accountChanged = false
if (purpose === 'background') {
if (purpose === 'background' || cacheOnly) {
// The sweep joined the roster row's account; publish it only for
// a credential served for that same account.
if (
Expand Down Expand Up @@ -1331,7 +1338,10 @@ export function createNativeVaultRuntime(
stored ? fromNativeQuotaMap(stored) : undefined,
)
}
if (purpose === 'admission' && lookup.miss === 'upstream-failed')
if (
cacheOnly ||
(purpose === 'admission' && lookup.miss === 'upstream-failed')
)
return undefined
return fetchOAuthQuotaSnapshot({
accessToken: receipt.accessToken,
Expand Down
Loading