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
4 changes: 2 additions & 2 deletions docs/limit-policy-conformance.md

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions packages/core/src/quota-refusal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ import type { LimitProvenanceStore } from './limit-provenance'
import { hasVaultRoutingAccessor } from './vault-routing'

export type OpenAiQuotaCause = 'killswitch' | 'quota' | 'timed-mark'

/** A configured minimum can block an account that still has quota left. */
export const OPENAI_QUOTA_MINIMUM_REFUSAL_MESSAGE =
'No OpenAI account meets the configured minimum remaining quota.'

export const OPENAI_FINAL_CAUSES = {
quota: 'Every OpenAI account has used up its quota.',
killswitch:
Expand Down
7 changes: 7 additions & 0 deletions packages/core/src/tests/quota-refusal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { LimitProvenanceStore } from '../limit-provenance'
import {
buildOpenAiQuotaRefusal,
decideOpenAiTerminal,
OPENAI_QUOTA_MINIMUM_REFUSAL_MESSAGE,
type OpenAiTerminalAccount,
openAiLimitMessages,
openAiTerminalFacts,
Expand Down Expand Up @@ -428,6 +429,12 @@ test('registered final causes survive numeric reset fuzz without generic fallbac
// Pi-ai 1.4.0 RETRYABLE_PROVIDER_ERROR_PATTERN, independent of our templates.
const pi =
/overloaded|server_busy|servers are currently busy|currently experiencing high demand|model is at capacity|rate.?limit|too many requests|(?<![a-z0-9])(?:429|500|502|503|504|520|524)(?![a-z0-9])|service.?(?:is.?)?(?:temporarily.?)?unavailable|server.?error|internal.?error|provider.?returned.?(?:an.?)?error|exceeded request buffer limit while retrying upstream|unable to forward upstream|upstream.?request.?failed|upstream_stream_read_error|stream was interrupted|http\/?2 stream failed|network.?error|connection.?error|connection.?refused|connection.?lost|other side closed|fetch failed|request to \S+ failed, reason:|getaddrinfo|ENOTFOUND|EAI_AGAIN|upstream.?connect|reset before headers|socket hang up|socket connection was closed|timed? out|timeout|terminated|websocket.?closed|websocket.?error|ended without|stream ended before message_stop|stream ended before a terminal response event|http2 request did not get a response|stream disconnected before completion|pending stream has been canceled|retry delay|you can retry your request|try your request again|please retry your request|ResourceExhausted|subscription_sharing_usage_unavailable|subscription_sharing_user_unavailable/i
const minimumText = OPENAI_QUOTA_MINIMUM_REFUSAL_MESSAGE
expect(hasUnsafeWording(minimumText)).toBe(false)
expect([...oc1, pi].some((pattern) => pattern.test(minimumText))).toBe(false)
expect(minimumText).not.toMatch(
/exhausted|unavailable|too_many_requests|try again/i,
)
const starts = {
quota: 'Every OpenAI account has used up its quota.',
killswitch:
Expand Down
5 changes: 5 additions & 0 deletions packages/pi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ Requires Pi 1.0.1 or newer. See [Install](https://github.com/cortexkit/openai-au
- [Commands](https://github.com/cortexkit/openai-auth/blob/main/docs/commands.md#pi)
- [Claustrum vault](https://github.com/cortexkit/openai-auth/blob/main/docs/vault.md#pi-in-vault-mode)

When Thalamus starts Pi, the plugin leaves the saved Pi login untouched and uses
the vault. If Pi does not expose its in-memory credential override, a saved
expired login may prevent Pi from reaching the plugin. Pi 1.5.2 was verified
with the override.

## License

MIT
15 changes: 12 additions & 3 deletions packages/pi/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import type { AccountPaths } from '@cortexkit/openai-auth-core/internal'
import {
type AccountPaths,
isVaultHosted,
} from '@cortexkit/openai-auth-core/internal'
import type { Api, Model } from '@earendil-works/pi-ai'
import { createAssistantMessageEventStream } from '@earendil-works/pi-ai'
// Imported from `/compat` rather than the deep `/api/openai-codex-responses`
Expand All @@ -25,7 +28,7 @@ import { PI_CODEX_BASE_URL } from './codex-wire.ts'
import { registerCommands } from './commands.ts'
import { PiOpenAIRuntime, type PiOpenAIRuntimeDeps } from './runtime.ts'
import { preparePiSettingsStartup } from './settings-startup.ts'
import { VAULT_PLACEHOLDER_KEY } from './vault-slot.ts'
import { installHostedVaultKey, VAULT_PLACEHOLDER_KEY } from './vault-slot.ts'

export { installRawCodexWebSocket } from './codex-websocket.ts'

Expand Down Expand Up @@ -130,7 +133,9 @@ export function registerPiProvider(
name: 'OpenAI Codex (CortexKit)',
// Pi's built-in Codex provider is OAuth-only. This enables its api_key
// resolver for the vault slot without replacing Pi's OAuth login method.
...(runtime.vaultMode() ? { apiKey: VAULT_PLACEHOLDER_KEY } : {}),
...(isVaultHosted() || runtime.vaultMode()
? { apiKey: VAULT_PLACEHOLDER_KEY }
: {}),
models: openAICodexModels(),
streamSimple: (model: Model<Api>, context, options) =>
runtime.stream(model, context, options),
Expand Down Expand Up @@ -219,6 +224,10 @@ export default async function cortexKitPiOpenAIAuth(pi: ExtensionAPI) {
: undefined
void runtime.start()
try {
if (isVaultHosted()) {
await installHostedVaultKey(ctx.modelRegistry, settingsStartup.log)
return
}
await syncSlot()
} catch {
notify(
Expand Down
6 changes: 5 additions & 1 deletion packages/pi/src/pool-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -620,7 +620,11 @@ async function routeOrdered<A extends RouteAttempt>(
const plan = planOrdered({
...routing,
placement,
mainId: ctx.mainId,
// A sticky fallback keeps vault roster order, not the vault's main preference.
mainId:
ctx.mode === 'sticky-balanced' && ctx.mainId !== undefined
? null
: ctx.mainId,
})
if (plan.kind === 'block') {
ctx.log?.debug('pool admission blocked the request', {
Expand Down
20 changes: 15 additions & 5 deletions packages/pi/src/pool-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -555,12 +555,13 @@ export class PiPoolSource {
/**
* Starts a refresh, through the store, of every candidate row whose token
* is missing, run out or inside the refresh window; rows in a refresh
* backoff are left alone. Resolves once those refreshes have ended, which
* the request path never waits for. Never rejects.
* backoff are left alone. Requests wait only for rows without a usable
* token; a still-valid token refreshes in the background. Never rejects.
*/
refreshDueTokens(
prepareTokens(
rows: readonly PoolRow[],
settings: AccountStorage | null,
{ waitForAll = false } = {},
): Promise<void> {
if (this.setAside()) return Promise.resolve()
const now = this.now()
Expand All @@ -571,13 +572,22 @@ export class PiPoolSource {
const token = oauthAccess(row)
if (!token) continue
const left = (token.expires ?? 0) - now
const due = !token.access || !token.expires || left <= windowMs
const usable = this.usableToken(row, now)
const due = !usable || left <= windowMs
if (!due || this.refreshBackedOff(row, now)) continue
runs.push(this.refresh(row.id))
const refreshed = this.refresh(row.id)
if (waitForAll || !usable) runs.push(refreshed)
}
return Promise.all(runs).then(() => {})
}

refreshDueTokens(
rows: readonly PoolRow[],
settings: AccountStorage | null,
): Promise<void> {
return this.prepareTokens(rows, settings, { waitForAll: true })
}

/** True while a failed refresh of this row's current refresh token may not be retried. */
refreshBackedOff(row: PoolRow, now = this.now()): boolean {
const token = oauthAccess(row)
Expand Down
45 changes: 34 additions & 11 deletions packages/pi/src/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,16 @@ import {
hasVaultRoutingAccessor,
isCompleteQuotaHeaderFrame,
isRecord,
isVaultHosted,
limitAccountKey,
loadAccounts,
normalizeQuotaHeaders,
normalizeWsFrame,
type OAuthQuotaSnapshot,
OPENAI_QUOTA_MINIMUM_REFUSAL_MESSAGE,
OpenAiVault,
poolLimitsNamespace,
quotaSnapshotPassesPolicy,
type RefreshAllQuotaResult,
type RoutingMode,
recordSessionCompletion,
Expand Down Expand Up @@ -234,13 +237,17 @@ export function errorEvent(
}
}

type PiBlock = PoolBlock | { reason: 'quota-minimum'; resetAtMs?: never }

/** The error message Pi shows for a request no account may serve. */
export function blockedMessage(block: PoolBlock): string {
export function blockedMessage(block: PiBlock): string {
const reset =
block.resetAtMs !== undefined
? ` It resets at ${new Date(block.resetAtMs).toISOString()}.`
: ''
switch (block.reason) {
case 'quota-minimum':
return OPENAI_QUOTA_MINIMUM_REFUSAL_MESSAGE
case 'quota-unknown':
return `No OpenAI account has a quota reading yet; one is being taken now. Try again in ${POOL_QUOTA_UNKNOWN_RETRY_SECONDS} seconds.`
case 'quota-exhausted':
Expand Down Expand Up @@ -397,7 +404,7 @@ export class PiOpenAIRuntime {
syncVaultSlot(refresh?: () => unknown, explicit = false): Promise<void> {
return this.withSlot(async () => {
await this.reconcileSlot(explicit)
if (this.slotNeedsRefresh && refresh) {
if (!isVaultHosted() && this.slotNeedsRefresh && refresh) {
await refresh()
this.slotNeedsRefresh = false
}
Expand Down Expand Up @@ -425,13 +432,17 @@ export class PiOpenAIRuntime {
}

private async reconcileSlot(explicit = false): Promise<void> {
const mode = (await this.readAuthority()) !== 'local'
const authority = await this.readAuthority()
// The hosted provider uses an in-memory key, never Pi's auth.json slot.
if (authority === 'host') return
const mode = authority !== 'local'
// Background ticks only read enrollment. An explicit sync or an unknown
// slot state must reconcile under the helper's lock even in the same mode.
if (mode === this.slotVaultMode && !explicit) return
const previousMode = this.slotVaultMode
this.slotVaultMode = undefined
const before = await this.vaultSlot().inspect()
if (isVaultHosted()) return
if (mode) await this.vaultSlot().enterVault()
else await this.vaultSlot().exitVault()
this.slotNeedsRefresh =
Expand All @@ -441,7 +452,9 @@ export class PiOpenAIRuntime {
this.slotNeedsRefresh
// Another process can change enrollment while the slot helper waits for
// its auth.json lock. Reconcile that change after the locked update finishes.
const currentMode = (await this.readAuthority()) !== 'local'
const currentAuthority = await this.readAuthority()
if (currentAuthority === 'host') return
const currentMode = currentAuthority !== 'local'
if (currentMode !== mode) {
if (currentMode) await this.vaultSlot().enterVault()
else await this.vaultSlot().exitVault()
Expand Down Expand Up @@ -698,8 +711,10 @@ export class PiOpenAIRuntime {
let wake: PiWake | undefined
for (;;) {
if (options?.signal?.aborted) return
const authority = await this.readAuthority()
if (
(await this.readAuthority()) !== 'local' &&
authority !== 'host' &&
authority !== 'local' &&
options?.apiKey !== VAULT_PLACEHOLDER_KEY
) {
outer.push(errorEvent(model, VAULT_SLOT_REFUSAL))
Expand Down Expand Up @@ -809,7 +824,7 @@ export class PiOpenAIRuntime {
execution: { canWait: boolean; wake?: PiWake; billingAttempt?: number },
): Promise<
| ({ kind: 'sent'; decision?: LimitDecision } & StreamAttempt)
| { kind: 'blocked'; block: PoolBlock; refusal?: VaultModeRefusal }
| { kind: 'blocked'; block: PiBlock; refusal?: VaultModeRefusal }
| Extract<
Awaited<ReturnType<typeof routePiRequest<StreamAttempt>>>,
{ kind: 'policy' }
Expand All @@ -830,20 +845,26 @@ export class PiOpenAIRuntime {
} else {
if (!execution.wake) this.main.observeToken(options?.apiKey)
await this.pool.current()
// Token refreshes of pool rows run in the background, so no request
// waits on the pool store's locks; a row whose token ran out sits out
// until its refresh lands.
void this.pool.refreshDueTokens(this.pool.peek().rows, settings)
await this.pool.prepareTokens(this.pool.peek().rows, settings)
}
const mode: RoutingMode = settings?.routing?.mode ?? 'main-first'
let vaultRefused = false
let candidates = 0
let quotaFiltered = false
const run = () =>
routePiRequest<StreamAttempt>({
accounts: () => {
const accounts = this.accounts(settings)
candidates = accounts.length
return accounts
const now = this.now()
const eligible = accounts.filter((account) => {
if (!account.vault) return true
const reading = windowsFromQuotaMap(account.quota)
// Leave unread routes visible so admission can request a poll.
return !reading || quotaSnapshotPassesPolicy(reading, settings, now)
})
quotaFiltered = eligible.length < candidates
return eligible
},
storage: settings,
mode,
Expand Down Expand Up @@ -919,6 +940,8 @@ export class PiOpenAIRuntime {
? 'vault-refused'
: vaultModeNoRouteCause(this.vault),
}
if (quotaFiltered && result.block.reason === 'no-credential')
return { ...result, block: { reason: 'quota-minimum' } }
if (vaultMode && result.block.reason === 'no-credential')
return { ...result, refusal: 'vault-empty' }
return result
Expand Down
Loading
Loading